Statistics
| Branch: | Revision:

ffmpeg / libavformat / asfdec.c @ 83120e3b

History | View | Annotate | Download (47.6 KB)

1
/*
2
 * ASF compatible demuxer
3
 * Copyright (c) 2000, 2001 Fabrice Bellard
4
 *
5
 * This file is part of FFmpeg.
6
 *
7
 * FFmpeg is free software; you can redistribute it and/or
8
 * modify it under the terms of the GNU Lesser General Public
9
 * License as published by the Free Software Foundation; either
10
 * version 2.1 of the License, or (at your option) any later version.
11
 *
12
 * FFmpeg is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15
 * Lesser General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU Lesser General Public
18
 * License along with FFmpeg; if not, write to the Free Software
19
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
 */
21

    
22
//#define DEBUG
23

    
24
#include "libavutil/common.h"
25
#include "libavutil/avstring.h"
26
#include "libavcodec/mpegaudio.h"
27
#include "avformat.h"
28
#include "riff.h"
29
#include "asf.h"
30
#include "asfcrypt.h"
31
#include "avlanguage.h"
32

    
33
void ff_mms_set_stream_selection(URLContext *h, AVFormatContext *format);
34

    
35
typedef struct {
36
    int asfid2avid[128];                 ///< conversion table from asf ID 2 AVStream ID
37
    ASFStream streams[128];              ///< it's max number and it's not that big
38
    uint32_t stream_bitrates[128];       ///< max number of streams, bitrate for each (for streaming)
39
    char stream_languages[128][6];       ///< max number of streams, language for each (RFC1766, e.g. en-US)
40
    /* non streamed additonnal info */
41
    uint64_t nb_packets;                 ///< how many packets are there in the file, invalid if broadcasting
42
    /* packet filling */
43
    int packet_size_left;
44
    int packet_nb_frames;
45
    /* only for reading */
46
    uint64_t data_offset;                ///< beginning of the first data packet
47
    uint64_t data_object_offset;         ///< data object offset (excl. GUID & size)
48
    uint64_t data_object_size;           ///< size of the data object
49
    int index_read;
50

    
51
    ASFMainHeader hdr;
52

    
53
    int packet_flags;
54
    int packet_property;
55
    int packet_timestamp;
56
    int packet_segsizetype;
57
    int packet_segments;
58
    int packet_seq;
59
    int packet_replic_size;
60
    int packet_key_frame;
61
    int packet_padsize;
62
    unsigned int packet_frag_offset;
63
    unsigned int packet_frag_size;
64
    int64_t packet_frag_timestamp;
65
    int packet_multi_size;
66
    int packet_obj_size;
67
    int packet_time_delta;
68
    int packet_time_start;
69
    int64_t packet_pos;
70

    
71
    int stream_index;
72

    
73
    ASFStream* asf_st;                   ///< currently decoded stream
74
} ASFContext;
75

    
76
#undef NDEBUG
77
#include <assert.h>
78

    
79
#define ASF_MAX_STREAMS 127
80
#define FRAME_HEADER_SIZE 17
81
// Fix Me! FRAME_HEADER_SIZE may be different.
82

    
83
static const ff_asf_guid index_guid = {
84
    0x90, 0x08, 0x00, 0x33, 0xb1, 0xe5, 0xcf, 0x11, 0x89, 0xf4, 0x00, 0xa0, 0xc9, 0x03, 0x49, 0xcb
85
};
86

    
87
static const ff_asf_guid stream_bitrate_guid = { /* (http://get.to/sdp) */
88
    0xce, 0x75, 0xf8, 0x7b, 0x8d, 0x46, 0xd1, 0x11, 0x8d, 0x82, 0x00, 0x60, 0x97, 0xc9, 0xa2, 0xb2
89
};
90
/**********************************/
91
/* decoding */
92

    
93
#ifdef DEBUG
94
#define PRINT_IF_GUID(g,cmp) \
95
if (!ff_guidcmp(g, &cmp)) \
96
    av_dlog(NULL, "(GUID: %s) ", #cmp)
97

    
98
static void print_guid(const ff_asf_guid *g)
99
{
100
    int i;
101
    PRINT_IF_GUID(g, ff_asf_header);
102
    else PRINT_IF_GUID(g, ff_asf_file_header);
103
    else PRINT_IF_GUID(g, ff_asf_stream_header);
104
    else PRINT_IF_GUID(g, ff_asf_audio_stream);
105
    else PRINT_IF_GUID(g, ff_asf_audio_conceal_none);
106
    else PRINT_IF_GUID(g, ff_asf_video_stream);
107
    else PRINT_IF_GUID(g, ff_asf_video_conceal_none);
108
    else PRINT_IF_GUID(g, ff_asf_command_stream);
109
    else PRINT_IF_GUID(g, ff_asf_comment_header);
110
    else PRINT_IF_GUID(g, ff_asf_codec_comment_header);
111
    else PRINT_IF_GUID(g, ff_asf_codec_comment1_header);
112
    else PRINT_IF_GUID(g, ff_asf_data_header);
113
    else PRINT_IF_GUID(g, index_guid);
114
    else PRINT_IF_GUID(g, ff_asf_head1_guid);
115
    else PRINT_IF_GUID(g, ff_asf_head2_guid);
116
    else PRINT_IF_GUID(g, ff_asf_my_guid);
117
    else PRINT_IF_GUID(g, ff_asf_ext_stream_header);
118
    else PRINT_IF_GUID(g, ff_asf_extended_content_header);
119
    else PRINT_IF_GUID(g, ff_asf_ext_stream_embed_stream_header);
120
    else PRINT_IF_GUID(g, ff_asf_ext_stream_audio_stream);
121
    else PRINT_IF_GUID(g, ff_asf_metadata_header);
122
    else PRINT_IF_GUID(g, ff_asf_marker_header);
123
    else PRINT_IF_GUID(g, stream_bitrate_guid);
124
    else PRINT_IF_GUID(g, ff_asf_language_guid);
125
    else
126
        av_dlog(NULL, "(GUID: unknown) ");
127
    for(i=0;i<16;i++)
128
        av_dlog(NULL, " 0x%02x,", (*g)[i]);
129
    av_dlog(NULL, "}\n");
130
}
131
#undef PRINT_IF_GUID
132
#else
133
#define print_guid(g)
134
#endif
135

    
136
void ff_get_guid(ByteIOContext *s, ff_asf_guid *g)
137
{
138
    assert(sizeof(*g) == 16);
139
    get_buffer(s, *g, sizeof(*g));
140
}
141

    
142
static int asf_probe(AVProbeData *pd)
143
{
144
    /* check file header */
145
    if (!ff_guidcmp(pd->buf, &ff_asf_header))
146
        return AVPROBE_SCORE_MAX;
147
    else
148
        return 0;
149
}
150

    
151
static int get_value(ByteIOContext *pb, int type){
152
    switch(type){
153
        case 2: return get_le32(pb);
154
        case 3: return get_le32(pb);
155
        case 4: return get_le64(pb);
156
        case 5: return get_le16(pb);
157
        default:return INT_MIN;
158
    }
159
}
160

    
161
static void get_tag(AVFormatContext *s, const char *key, int type, int len)
162
{
163
    char *value;
164
    int64_t off = url_ftell(s->pb);
165

    
166
    if ((unsigned)len >= (UINT_MAX - 1)/2)
167
        return;
168

    
169
    value = av_malloc(2*len+1);
170
    if (!value)
171
        goto finish;
172

    
173
    if (type == 0) {         // UTF16-LE
174
        avio_get_str16le(s->pb, len, value, 2*len + 1);
175
    } else if (type > 1 && type <= 5) {  // boolean or DWORD or QWORD or WORD
176
        uint64_t num = get_value(s->pb, type);
177
        snprintf(value, len, "%"PRIu64, num);
178
    } else {
179
        av_log(s, AV_LOG_DEBUG, "Unsupported value type %d in tag %s.\n", type, key);
180
        goto finish;
181
    }
182
    av_metadata_set2(&s->metadata, key, value, 0);
183
finish:
184
    av_freep(&value);
185
    url_fseek(s->pb, off + len, SEEK_SET);
186
}
187

    
188
static int asf_read_header(AVFormatContext *s, AVFormatParameters *ap)
189
{
190
    ASFContext *asf = s->priv_data;
191
    ff_asf_guid g;
192
    ByteIOContext *pb = s->pb;
193
    AVStream *st;
194
    ASFStream *asf_st;
195
    int size, i;
196
    int64_t gsize;
197
    AVRational dar[128];
198
    uint32_t bitrate[128];
199

    
200
    memset(dar, 0, sizeof(dar));
201
    memset(bitrate, 0, sizeof(bitrate));
202

    
203
    ff_get_guid(pb, &g);
204
    if (ff_guidcmp(&g, &ff_asf_header))
205
        return -1;
206
    get_le64(pb);
207
    get_le32(pb);
208
    get_byte(pb);
209
    get_byte(pb);
210
    memset(&asf->asfid2avid, -1, sizeof(asf->asfid2avid));
211
    for(;;) {
212
        uint64_t gpos= url_ftell(pb);
213
        int ret;
214
        ff_get_guid(pb, &g);
215
        gsize = get_le64(pb);
216
        av_dlog(s, "%08"PRIx64": ", gpos);
217
        print_guid(&g);
218
        av_dlog(s, "  size=0x%"PRIx64"\n", gsize);
219
        if (!ff_guidcmp(&g, &ff_asf_data_header)) {
220
            asf->data_object_offset = url_ftell(pb);
221
            // if not streaming, gsize is not unlimited (how?), and there is enough space in the file..
222
            if (!(asf->hdr.flags & 0x01) && gsize >= 100) {
223
                asf->data_object_size = gsize - 24;
224
            } else {
225
                asf->data_object_size = (uint64_t)-1;
226
            }
227
            break;
228
        }
229
        if (gsize < 24)
230
            return -1;
231
        if (!ff_guidcmp(&g, &ff_asf_file_header)) {
232
            ff_get_guid(pb, &asf->hdr.guid);
233
            asf->hdr.file_size          = get_le64(pb);
234
            asf->hdr.create_time        = get_le64(pb);
235
            asf->nb_packets             = get_le64(pb);
236
            asf->hdr.play_time          = get_le64(pb);
237
            asf->hdr.send_time          = get_le64(pb);
238
            asf->hdr.preroll            = get_le32(pb);
239
            asf->hdr.ignore             = get_le32(pb);
240
            asf->hdr.flags              = get_le32(pb);
241
            asf->hdr.min_pktsize        = get_le32(pb);
242
            asf->hdr.max_pktsize        = get_le32(pb);
243
            asf->hdr.max_bitrate        = get_le32(pb);
244
            s->packet_size = asf->hdr.max_pktsize;
245
        } else if (!ff_guidcmp(&g, &ff_asf_stream_header)) {
246
            enum AVMediaType type;
247
            int type_specific_size, sizeX;
248
            uint64_t total_size;
249
            unsigned int tag1;
250
            int64_t pos1, pos2, start_time;
251
            int test_for_ext_stream_audio, is_dvr_ms_audio=0;
252

    
253
            if (s->nb_streams == ASF_MAX_STREAMS) {
254
                av_log(s, AV_LOG_ERROR, "too many streams\n");
255
                return AVERROR(EINVAL);
256
            }
257

    
258
            pos1 = url_ftell(pb);
259

    
260
            st = av_new_stream(s, 0);
261
            if (!st)
262
                return AVERROR(ENOMEM);
263
            av_set_pts_info(st, 32, 1, 1000); /* 32 bit pts in ms */
264
            asf_st = av_mallocz(sizeof(ASFStream));
265
            if (!asf_st)
266
                return AVERROR(ENOMEM);
267
            st->priv_data = asf_st;
268
            start_time = asf->hdr.preroll;
269

    
270
            asf_st->stream_language_index = 128; // invalid stream index means no language info
271

    
272
            if(!(asf->hdr.flags & 0x01)) { // if we aren't streaming...
273
                st->duration = asf->hdr.play_time /
274
                    (10000000 / 1000) - start_time;
275
            }
276
            ff_get_guid(pb, &g);
277

    
278
            test_for_ext_stream_audio = 0;
279
            if (!ff_guidcmp(&g, &ff_asf_audio_stream)) {
280
                type = AVMEDIA_TYPE_AUDIO;
281
            } else if (!ff_guidcmp(&g, &ff_asf_video_stream)) {
282
                type = AVMEDIA_TYPE_VIDEO;
283
            } else if (!ff_guidcmp(&g, &ff_asf_jfif_media)) {
284
                type = AVMEDIA_TYPE_VIDEO;
285
                st->codec->codec_id = CODEC_ID_MJPEG;
286
            } else if (!ff_guidcmp(&g, &ff_asf_command_stream)) {
287
                type = AVMEDIA_TYPE_DATA;
288
            } else if (!ff_guidcmp(&g, &ff_asf_ext_stream_embed_stream_header)) {
289
                test_for_ext_stream_audio = 1;
290
                type = AVMEDIA_TYPE_UNKNOWN;
291
            } else {
292
                return -1;
293
            }
294
            ff_get_guid(pb, &g);
295
            total_size = get_le64(pb);
296
            type_specific_size = get_le32(pb);
297
            get_le32(pb);
298
            st->id = get_le16(pb) & 0x7f; /* stream id */
299
            // mapping of asf ID to AV stream ID;
300
            asf->asfid2avid[st->id] = s->nb_streams - 1;
301

    
302
            get_le32(pb);
303

    
304
            if (test_for_ext_stream_audio) {
305
                ff_get_guid(pb, &g);
306
                if (!ff_guidcmp(&g, &ff_asf_ext_stream_audio_stream)) {
307
                    type = AVMEDIA_TYPE_AUDIO;
308
                    is_dvr_ms_audio=1;
309
                    ff_get_guid(pb, &g);
310
                    get_le32(pb);
311
                    get_le32(pb);
312
                    get_le32(pb);
313
                    ff_get_guid(pb, &g);
314
                    get_le32(pb);
315
                }
316
            }
317

    
318
            st->codec->codec_type = type;
319
            if (type == AVMEDIA_TYPE_AUDIO) {
320
                ff_get_wav_header(pb, st->codec, type_specific_size);
321
                if (is_dvr_ms_audio) {
322
                    // codec_id and codec_tag are unreliable in dvr_ms
323
                    // files. Set them later by probing stream.
324
                    st->codec->codec_id = CODEC_ID_PROBE;
325
                    st->codec->codec_tag = 0;
326
                }
327
                if (st->codec->codec_id == CODEC_ID_AAC) {
328
                    st->need_parsing = AVSTREAM_PARSE_NONE;
329
                } else {
330
                    st->need_parsing = AVSTREAM_PARSE_FULL;
331
                }
332
                /* We have to init the frame size at some point .... */
333
                pos2 = url_ftell(pb);
334
                if (gsize >= (pos2 + 8 - pos1 + 24)) {
335
                    asf_st->ds_span = get_byte(pb);
336
                    asf_st->ds_packet_size = get_le16(pb);
337
                    asf_st->ds_chunk_size = get_le16(pb);
338
                    get_le16(pb); //ds_data_size
339
                    get_byte(pb); //ds_silence_data
340
                }
341
                //printf("Descrambling: ps:%d cs:%d ds:%d s:%d  sd:%d\n",
342
                //       asf_st->ds_packet_size, asf_st->ds_chunk_size,
343
                //       asf_st->ds_data_size, asf_st->ds_span, asf_st->ds_silence_data);
344
                if (asf_st->ds_span > 1) {
345
                    if (!asf_st->ds_chunk_size
346
                        || (asf_st->ds_packet_size/asf_st->ds_chunk_size <= 1)
347
                        || asf_st->ds_packet_size % asf_st->ds_chunk_size)
348
                        asf_st->ds_span = 0; // disable descrambling
349
                }
350
                switch (st->codec->codec_id) {
351
                case CODEC_ID_MP3:
352
                    st->codec->frame_size = MPA_FRAME_SIZE;
353
                    break;
354
                case CODEC_ID_PCM_S16LE:
355
                case CODEC_ID_PCM_S16BE:
356
                case CODEC_ID_PCM_U16LE:
357
                case CODEC_ID_PCM_U16BE:
358
                case CODEC_ID_PCM_S8:
359
                case CODEC_ID_PCM_U8:
360
                case CODEC_ID_PCM_ALAW:
361
                case CODEC_ID_PCM_MULAW:
362
                    st->codec->frame_size = 1;
363
                    break;
364
                default:
365
                    /* This is probably wrong, but it prevents a crash later */
366
                    st->codec->frame_size = 1;
367
                    break;
368
                }
369
            } else if (type == AVMEDIA_TYPE_VIDEO &&
370
                       gsize - (url_ftell(pb) - pos1 + 24) >= 51) {
371
                get_le32(pb);
372
                get_le32(pb);
373
                get_byte(pb);
374
                size = get_le16(pb); /* size */
375
                sizeX= get_le32(pb); /* size */
376
                st->codec->width = get_le32(pb);
377
                st->codec->height = get_le32(pb);
378
                /* not available for asf */
379
                get_le16(pb); /* panes */
380
                st->codec->bits_per_coded_sample = get_le16(pb); /* depth */
381
                tag1 = get_le32(pb);
382
                url_fskip(pb, 20);
383
//                av_log(s, AV_LOG_DEBUG, "size:%d tsize:%d sizeX:%d\n", size, total_size, sizeX);
384
                size= sizeX;
385
                if (size > 40) {
386
                    st->codec->extradata_size = size - 40;
387
                    st->codec->extradata = av_mallocz(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
388
                    get_buffer(pb, st->codec->extradata, st->codec->extradata_size);
389
                }
390

    
391
                /* Extract palette from extradata if bpp <= 8 */
392
                /* This code assumes that extradata contains only palette */
393
                /* This is true for all paletted codecs implemented in ffmpeg */
394
                if (st->codec->extradata_size && (st->codec->bits_per_coded_sample <= 8)) {
395
                    st->codec->palctrl = av_mallocz(sizeof(AVPaletteControl));
396
#if HAVE_BIGENDIAN
397
                    for (i = 0; i < FFMIN(st->codec->extradata_size, AVPALETTE_SIZE)/4; i++)
398
                        st->codec->palctrl->palette[i] = av_bswap32(((uint32_t*)st->codec->extradata)[i]);
399
#else
400
                    memcpy(st->codec->palctrl->palette, st->codec->extradata,
401
                           FFMIN(st->codec->extradata_size, AVPALETTE_SIZE));
402
#endif
403
                    st->codec->palctrl->palette_changed = 1;
404
                }
405

    
406
                st->codec->codec_tag = tag1;
407
                st->codec->codec_id = ff_codec_get_id(ff_codec_bmp_tags, tag1);
408
                if(tag1 == MKTAG('D', 'V', 'R', ' ')){
409
                    st->need_parsing = AVSTREAM_PARSE_FULL;
410
                    // issue658 containse wrong w/h and MS even puts a fake seq header with wrong w/h in extradata while a correct one is in te stream. maximum lameness
411
                    st->codec->width  =
412
                    st->codec->height = 0;
413
                    av_freep(&st->codec->extradata);
414
                    st->codec->extradata_size=0;
415
                }
416
                if(st->codec->codec_id == CODEC_ID_H264)
417
                    st->need_parsing = AVSTREAM_PARSE_FULL_ONCE;
418
            }
419
            pos2 = url_ftell(pb);
420
            url_fskip(pb, gsize - (pos2 - pos1 + 24));
421
        } else if (!ff_guidcmp(&g, &ff_asf_comment_header)) {
422
            int len1, len2, len3, len4, len5;
423

    
424
            len1 = get_le16(pb);
425
            len2 = get_le16(pb);
426
            len3 = get_le16(pb);
427
            len4 = get_le16(pb);
428
            len5 = get_le16(pb);
429
            get_tag(s, "title"    , 0, len1);
430
            get_tag(s, "author"   , 0, len2);
431
            get_tag(s, "copyright", 0, len3);
432
            get_tag(s, "comment"  , 0, len4);
433
            url_fskip(pb, len5);
434
        } else if (!ff_guidcmp(&g, &stream_bitrate_guid)) {
435
            int stream_count = get_le16(pb);
436
            int j;
437

    
438
//            av_log(s, AV_LOG_ERROR, "stream bitrate properties\n");
439
//            av_log(s, AV_LOG_ERROR, "streams %d\n", streams);
440
            for(j = 0; j < stream_count; j++) {
441
                int flags, bitrate, stream_id;
442

    
443
                flags= get_le16(pb);
444
                bitrate= get_le32(pb);
445
                stream_id= (flags & 0x7f);
446
//                av_log(s, AV_LOG_ERROR, "flags: 0x%x stream id %d, bitrate %d\n", flags, stream_id, bitrate);
447
                asf->stream_bitrates[stream_id]= bitrate;
448
            }
449
        } else if (!ff_guidcmp(&g, &ff_asf_language_guid)) {
450
            int j;
451
            int stream_count = get_le16(pb);
452
            for(j = 0; j < stream_count; j++) {
453
                char lang[6];
454
                unsigned int lang_len = get_byte(pb);
455
                if ((ret = avio_get_str16le(pb, lang_len, lang, sizeof(lang))) < lang_len)
456
                    url_fskip(pb, lang_len - ret);
457
                if (j < 128)
458
                    av_strlcpy(asf->stream_languages[j], lang, sizeof(*asf->stream_languages));
459
            }
460
        } else if (!ff_guidcmp(&g, &ff_asf_extended_content_header)) {
461
            int desc_count, i;
462

    
463
            desc_count = get_le16(pb);
464
            for(i=0;i<desc_count;i++) {
465
                    int name_len,value_type,value_len;
466
                    char name[1024];
467

    
468
                    name_len = get_le16(pb);
469
                    if (name_len%2)     // must be even, broken lavf versions wrote len-1
470
                        name_len += 1;
471
                    if ((ret = avio_get_str16le(pb, name_len, name, sizeof(name))) < name_len)
472
                        url_fskip(pb, name_len - ret);
473
                    value_type = get_le16(pb);
474
                    value_len  = get_le16(pb);
475
                    if (!value_type && value_len%2)
476
                        value_len += 1;
477
                    /**
478
                     * My sample has that stream set to 0 maybe that mean the container.
479
                     * Asf stream count start at 1. I am using 0 to the container value since it's unused
480
                     */
481
                    if (!strcmp(name, "AspectRatioX")){
482
                        dar[0].num= get_value(s->pb, value_type);
483
                    } else if(!strcmp(name, "AspectRatioY")){
484
                        dar[0].den= get_value(s->pb, value_type);
485
                    } else
486
                        get_tag(s, name, value_type, value_len);
487
            }
488
        } else if (!ff_guidcmp(&g, &ff_asf_metadata_header)) {
489
            int n, stream_num, name_len, value_len, value_type, value_num;
490
            n = get_le16(pb);
491

    
492
            for(i=0;i<n;i++) {
493
                char name[1024];
494

    
495
                get_le16(pb); //lang_list_index
496
                stream_num= get_le16(pb);
497
                name_len=   get_le16(pb);
498
                value_type= get_le16(pb);
499
                value_len=  get_le32(pb);
500

    
501
                if ((ret = avio_get_str16le(pb, name_len, name, sizeof(name))) < name_len)
502
                    url_fskip(pb, name_len - ret);
503
//av_log(s, AV_LOG_ERROR, "%d %d %d %d %d <%s>\n", i, stream_num, name_len, value_type, value_len, name);
504
                value_num= get_le16(pb);//we should use get_value() here but it does not work 2 is le16 here but le32 elsewhere
505
                url_fskip(pb, value_len - 2);
506

    
507
                if(stream_num<128){
508
                    if     (!strcmp(name, "AspectRatioX")) dar[stream_num].num= value_num;
509
                    else if(!strcmp(name, "AspectRatioY")) dar[stream_num].den= value_num;
510
                }
511
            }
512
        } else if (!ff_guidcmp(&g, &ff_asf_ext_stream_header)) {
513
            int ext_len, payload_ext_ct, stream_ct;
514
            uint32_t ext_d, leak_rate, stream_num;
515
            unsigned int stream_languageid_index;
516

    
517
            get_le64(pb); // starttime
518
            get_le64(pb); // endtime
519
            leak_rate = get_le32(pb); // leak-datarate
520
            get_le32(pb); // bucket-datasize
521
            get_le32(pb); // init-bucket-fullness
522
            get_le32(pb); // alt-leak-datarate
523
            get_le32(pb); // alt-bucket-datasize
524
            get_le32(pb); // alt-init-bucket-fullness
525
            get_le32(pb); // max-object-size
526
            get_le32(pb); // flags (reliable,seekable,no_cleanpoints?,resend-live-cleanpoints, rest of bits reserved)
527
            stream_num = get_le16(pb); // stream-num
528

    
529
            stream_languageid_index = get_le16(pb); // stream-language-id-index
530
            if (stream_num < 128)
531
                asf->streams[stream_num].stream_language_index = stream_languageid_index;
532

    
533
            get_le64(pb); // avg frametime in 100ns units
534
            stream_ct = get_le16(pb); //stream-name-count
535
            payload_ext_ct = get_le16(pb); //payload-extension-system-count
536

    
537
            if (stream_num < 128)
538
                bitrate[stream_num] = leak_rate;
539

    
540
            for (i=0; i<stream_ct; i++){
541
                get_le16(pb);
542
                ext_len = get_le16(pb);
543
                url_fseek(pb, ext_len, SEEK_CUR);
544
            }
545

    
546
            for (i=0; i<payload_ext_ct; i++){
547
                ff_get_guid(pb, &g);
548
                ext_d=get_le16(pb);
549
                ext_len=get_le32(pb);
550
                url_fseek(pb, ext_len, SEEK_CUR);
551
            }
552

    
553
            // there could be a optional stream properties object to follow
554
            // if so the next iteration will pick it up
555
            continue;
556
        } else if (!ff_guidcmp(&g, &ff_asf_head1_guid)) {
557
            int v1, v2;
558
            ff_get_guid(pb, &g);
559
            v1 = get_le32(pb);
560
            v2 = get_le16(pb);
561
            continue;
562
        } else if (!ff_guidcmp(&g, &ff_asf_marker_header)) {
563
            int i, count, name_len;
564
            char name[1024];
565

    
566
            get_le64(pb);            // reserved 16 bytes
567
            get_le64(pb);            // ...
568
            count = get_le32(pb);    // markers count
569
            get_le16(pb);            // reserved 2 bytes
570
            name_len = get_le16(pb); // name length
571
            for(i=0;i<name_len;i++){
572
                get_byte(pb); // skip the name
573
            }
574

    
575
            for(i=0;i<count;i++){
576
                int64_t pres_time;
577
                int name_len;
578

    
579
                get_le64(pb);             // offset, 8 bytes
580
                pres_time = get_le64(pb); // presentation time
581
                get_le16(pb);             // entry length
582
                get_le32(pb);             // send time
583
                get_le32(pb);             // flags
584
                name_len = get_le32(pb);  // name length
585
                if ((ret = avio_get_str16le(pb, name_len * 2, name, sizeof(name))) < name_len)
586
                    url_fskip(pb, name_len - ret);
587
                ff_new_chapter(s, i, (AVRational){1, 10000000}, pres_time, AV_NOPTS_VALUE, name );
588
            }
589
        } else if (url_feof(pb)) {
590
            return -1;
591
        } else {
592
            if (!s->keylen) {
593
                if (!ff_guidcmp(&g, &ff_asf_content_encryption)) {
594
                    av_log(s, AV_LOG_WARNING, "DRM protected stream detected, decoding will likely fail!\n");
595
                } else if (!ff_guidcmp(&g, &ff_asf_ext_content_encryption)) {
596
                    av_log(s, AV_LOG_WARNING, "Ext DRM protected stream detected, decoding will likely fail!\n");
597
                } else if (!ff_guidcmp(&g, &ff_asf_digital_signature)) {
598
                    av_log(s, AV_LOG_WARNING, "Digital signature detected, decoding will likely fail!\n");
599
                }
600
            }
601
        }
602
        if(url_ftell(pb) != gpos + gsize)
603
            av_log(s, AV_LOG_DEBUG, "gpos mismatch our pos=%"PRIu64", end=%"PRIu64"\n", url_ftell(pb)-gpos, gsize);
604
        url_fseek(pb, gpos + gsize, SEEK_SET);
605
    }
606
    ff_get_guid(pb, &g);
607
    get_le64(pb);
608
    get_byte(pb);
609
    get_byte(pb);
610
    if (url_feof(pb))
611
        return -1;
612
    asf->data_offset = url_ftell(pb);
613
    asf->packet_size_left = 0;
614

    
615

    
616
    for(i=0; i<128; i++){
617
        int stream_num= asf->asfid2avid[i];
618
        if(stream_num>=0){
619
            AVStream *st = s->streams[stream_num];
620
            if (!st->codec->bit_rate)
621
                st->codec->bit_rate = bitrate[i];
622
            if (dar[i].num > 0 && dar[i].den > 0){
623
                av_reduce(&st->sample_aspect_ratio.num,
624
                          &st->sample_aspect_ratio.den,
625
                          dar[i].num, dar[i].den, INT_MAX);
626
            } else if ((dar[0].num > 0) && (dar[0].den > 0) && (st->codec->codec_type==AVMEDIA_TYPE_VIDEO)) // Use ASF container value if the stream doesn't AR set.
627
                av_reduce(&st->sample_aspect_ratio.num,
628
                          &st->sample_aspect_ratio.den,
629
                          dar[0].num, dar[0].den, INT_MAX);
630

    
631
//av_log(s, AV_LOG_INFO, "i=%d, st->codec->codec_type:%d, dar %d:%d sar=%d:%d\n", i, st->codec->codec_type, dar[i].num, dar[i].den, st->sample_aspect_ratio.num, st->sample_aspect_ratio.den);
632

    
633
            // copy and convert language codes to the frontend
634
            if (asf->streams[i].stream_language_index < 128) {
635
                const char *rfc1766 = asf->stream_languages[asf->streams[i].stream_language_index];
636
                if (rfc1766 && strlen(rfc1766) > 1) {
637
                    const char primary_tag[3] = { rfc1766[0], rfc1766[1], '\0' }; // ignore country code if any
638
                    const char *iso6392 = av_convert_lang_to(primary_tag, AV_LANG_ISO639_2_BIBL);
639
                    if (iso6392)
640
                        av_metadata_set2(&st->metadata, "language", iso6392, 0);
641
                }
642
            }
643
        }
644
    }
645

    
646
    ff_metadata_conv(&s->metadata, NULL, ff_asf_metadata_conv);
647

    
648
    return 0;
649
}
650

    
651
#define DO_2BITS(bits, var, defval) \
652
    switch (bits & 3) \
653
    { \
654
    case 3: var = get_le32(pb); rsize += 4; break; \
655
    case 2: var = get_le16(pb); rsize += 2; break; \
656
    case 1: var = get_byte(pb); rsize++; break; \
657
    default: var = defval; break; \
658
    }
659

    
660
/**
661
 * Load a single ASF packet into the demuxer.
662
 * @param s demux context
663
 * @param pb context to read data from
664
 * @return 0 on success, <0 on error
665
 */
666
static int ff_asf_get_packet(AVFormatContext *s, ByteIOContext *pb)
667
{
668
    ASFContext *asf = s->priv_data;
669
    uint32_t packet_length, padsize;
670
    int rsize = 8;
671
    int c, d, e, off;
672

    
673
    // if we do not know packet size, allow skipping up to 32 kB
674
    off= 32768;
675
    if (s->packet_size > 0)
676
        off= (url_ftell(pb) - s->data_offset) % s->packet_size + 3;
677

    
678
    c=d=e=-1;
679
    while(off-- > 0){
680
        c=d; d=e;
681
        e= get_byte(pb);
682
        if(c == 0x82 && !d && !e)
683
            break;
684
    }
685

    
686
    if (c != 0x82) {
687
        /**
688
         * This code allows handling of -EAGAIN at packet boundaries (i.e.
689
         * if the packet sync code above triggers -EAGAIN). This does not
690
         * imply complete -EAGAIN handling support at random positions in
691
         * the stream.
692
         */
693
        if (url_ferror(pb) == AVERROR(EAGAIN))
694
            return AVERROR(EAGAIN);
695
        if (!url_feof(pb))
696
            av_log(s, AV_LOG_ERROR, "ff asf bad header %x  at:%"PRId64"\n", c, url_ftell(pb));
697
    }
698
    if ((c & 0x8f) == 0x82) {
699
        if (d || e) {
700
            if (!url_feof(pb))
701
                av_log(s, AV_LOG_ERROR, "ff asf bad non zero\n");
702
            return -1;
703
        }
704
        c= get_byte(pb);
705
        d= get_byte(pb);
706
        rsize+=3;
707
    }else{
708
        url_fseek(pb, -1, SEEK_CUR); //FIXME
709
    }
710

    
711
    asf->packet_flags    = c;
712
    asf->packet_property = d;
713

    
714
    DO_2BITS(asf->packet_flags >> 5, packet_length, s->packet_size);
715
    DO_2BITS(asf->packet_flags >> 1, padsize, 0); // sequence ignored
716
    DO_2BITS(asf->packet_flags >> 3, padsize, 0); // padding length
717

    
718
    //the following checks prevent overflows and infinite loops
719
    if(!packet_length || packet_length >= (1U<<29)){
720
        av_log(s, AV_LOG_ERROR, "invalid packet_length %d at:%"PRId64"\n", packet_length, url_ftell(pb));
721
        return -1;
722
    }
723
    if(padsize >= packet_length){
724
        av_log(s, AV_LOG_ERROR, "invalid padsize %d at:%"PRId64"\n", padsize, url_ftell(pb));
725
        return -1;
726
    }
727

    
728
    asf->packet_timestamp = get_le32(pb);
729
    get_le16(pb); /* duration */
730
    // rsize has at least 11 bytes which have to be present
731

    
732
    if (asf->packet_flags & 0x01) {
733
        asf->packet_segsizetype = get_byte(pb); rsize++;
734
        asf->packet_segments = asf->packet_segsizetype & 0x3f;
735
    } else {
736
        asf->packet_segments = 1;
737
        asf->packet_segsizetype = 0x80;
738
    }
739
    asf->packet_size_left = packet_length - padsize - rsize;
740
    if (packet_length < asf->hdr.min_pktsize)
741
        padsize += asf->hdr.min_pktsize - packet_length;
742
    asf->packet_padsize = padsize;
743
    av_dlog(s, "packet: size=%d padsize=%d  left=%d\n", s->packet_size, asf->packet_padsize, asf->packet_size_left);
744
    return 0;
745
}
746

    
747
/**
748
 *
749
 * @return <0 if error
750
 */
751
static int asf_read_frame_header(AVFormatContext *s, ByteIOContext *pb){
752
    ASFContext *asf = s->priv_data;
753
    int rsize = 1;
754
    int num = get_byte(pb);
755
    int64_t ts0, ts1;
756

    
757
    asf->packet_segments--;
758
    asf->packet_key_frame = num >> 7;
759
    asf->stream_index = asf->asfid2avid[num & 0x7f];
760
    // sequence should be ignored!
761
    DO_2BITS(asf->packet_property >> 4, asf->packet_seq, 0);
762
    DO_2BITS(asf->packet_property >> 2, asf->packet_frag_offset, 0);
763
    DO_2BITS(asf->packet_property, asf->packet_replic_size, 0);
764
//printf("key:%d stream:%d seq:%d offset:%d replic_size:%d\n", asf->packet_key_frame, asf->stream_index, asf->packet_seq, //asf->packet_frag_offset, asf->packet_replic_size);
765
    if (asf->packet_replic_size >= 8) {
766
        asf->packet_obj_size = get_le32(pb);
767
        if(asf->packet_obj_size >= (1<<24) || asf->packet_obj_size <= 0){
768
            av_log(s, AV_LOG_ERROR, "packet_obj_size invalid\n");
769
            return -1;
770
        }
771
        asf->packet_frag_timestamp = get_le32(pb); // timestamp
772
        if(asf->packet_replic_size >= 8+38+4){
773
//            for(i=0; i<asf->packet_replic_size-8; i++)
774
//                av_log(s, AV_LOG_DEBUG, "%02X ",get_byte(pb));
775
//            av_log(s, AV_LOG_DEBUG, "\n");
776
            url_fskip(pb, 10);
777
            ts0= get_le64(pb);
778
            ts1= get_le64(pb);
779
            url_fskip(pb, 12);
780
            get_le32(pb);
781
            url_fskip(pb, asf->packet_replic_size - 8 - 38 - 4);
782
            if(ts0!= -1) asf->packet_frag_timestamp= ts0/10000;
783
            else         asf->packet_frag_timestamp= AV_NOPTS_VALUE;
784
        }else
785
            url_fskip(pb, asf->packet_replic_size - 8);
786
        rsize += asf->packet_replic_size; // FIXME - check validity
787
    } else if (asf->packet_replic_size==1){
788
        // multipacket - frag_offset is beginning timestamp
789
        asf->packet_time_start = asf->packet_frag_offset;
790
        asf->packet_frag_offset = 0;
791
        asf->packet_frag_timestamp = asf->packet_timestamp;
792

    
793
        asf->packet_time_delta = get_byte(pb);
794
        rsize++;
795
    }else if(asf->packet_replic_size!=0){
796
        av_log(s, AV_LOG_ERROR, "unexpected packet_replic_size of %d\n", asf->packet_replic_size);
797
        return -1;
798
    }
799
    if (asf->packet_flags & 0x01) {
800
        DO_2BITS(asf->packet_segsizetype >> 6, asf->packet_frag_size, 0); // 0 is illegal
801
        if(asf->packet_frag_size > asf->packet_size_left - rsize){
802
            av_log(s, AV_LOG_ERROR, "packet_frag_size is invalid\n");
803
            return -1;
804
        }
805
        //printf("Fragsize %d\n", asf->packet_frag_size);
806
    } else {
807
        asf->packet_frag_size = asf->packet_size_left - rsize;
808
        //printf("Using rest  %d %d %d\n", asf->packet_frag_size, asf->packet_size_left, rsize);
809
    }
810
    if (asf->packet_replic_size == 1) {
811
        asf->packet_multi_size = asf->packet_frag_size;
812
        if (asf->packet_multi_size > asf->packet_size_left)
813
            return -1;
814
    }
815
    asf->packet_size_left -= rsize;
816
    //printf("___objsize____  %d   %d    rs:%d\n", asf->packet_obj_size, asf->packet_frag_offset, rsize);
817

    
818
    return 0;
819
}
820

    
821
/**
822
 * Parse data from individual ASF packets (which were previously loaded
823
 * with asf_get_packet()).
824
 * @param s demux context
825
 * @param pb context to read data from
826
 * @param pkt pointer to store packet data into
827
 * @return 0 if data was stored in pkt, <0 on error or 1 if more ASF
828
 *          packets need to be loaded (through asf_get_packet())
829
 */
830
static int ff_asf_parse_packet(AVFormatContext *s, ByteIOContext *pb, AVPacket *pkt)
831
{
832
    ASFContext *asf = s->priv_data;
833
    ASFStream *asf_st = 0;
834
    for (;;) {
835
        int ret;
836
        if(url_feof(pb))
837
            return AVERROR_EOF;
838
        if (asf->packet_size_left < FRAME_HEADER_SIZE
839
            || asf->packet_segments < 1) {
840
            //asf->packet_size_left <= asf->packet_padsize) {
841
            int ret = asf->packet_size_left + asf->packet_padsize;
842
            //printf("PacketLeftSize:%d  Pad:%d Pos:%"PRId64"\n", asf->packet_size_left, asf->packet_padsize, url_ftell(pb));
843
            assert(ret>=0);
844
            /* fail safe */
845
            url_fskip(pb, ret);
846

    
847
            asf->packet_pos= url_ftell(pb);
848
            if (asf->data_object_size != (uint64_t)-1 &&
849
                (asf->packet_pos - asf->data_object_offset >= asf->data_object_size))
850
                return AVERROR_EOF; /* Do not exceed the size of the data object */
851
            return 1;
852
        }
853
        if (asf->packet_time_start == 0) {
854
            if(asf_read_frame_header(s, pb) < 0){
855
                asf->packet_segments= 0;
856
                continue;
857
            }
858
            if (asf->stream_index < 0
859
                || s->streams[asf->stream_index]->discard >= AVDISCARD_ALL
860
                || (!asf->packet_key_frame && s->streams[asf->stream_index]->discard >= AVDISCARD_NONKEY)
861
                ) {
862
                asf->packet_time_start = 0;
863
                /* unhandled packet (should not happen) */
864
                url_fskip(pb, asf->packet_frag_size);
865
                asf->packet_size_left -= asf->packet_frag_size;
866
                if(asf->stream_index < 0)
867
                    av_log(s, AV_LOG_ERROR, "ff asf skip %d (unknown stream)\n", asf->packet_frag_size);
868
                continue;
869
            }
870
            asf->asf_st = s->streams[asf->stream_index]->priv_data;
871
        }
872
        asf_st = asf->asf_st;
873

    
874
        if (asf->packet_replic_size == 1) {
875
            // frag_offset is here used as the beginning timestamp
876
            asf->packet_frag_timestamp = asf->packet_time_start;
877
            asf->packet_time_start += asf->packet_time_delta;
878
            asf->packet_obj_size = asf->packet_frag_size = get_byte(pb);
879
            asf->packet_size_left--;
880
            asf->packet_multi_size--;
881
            if (asf->packet_multi_size < asf->packet_obj_size)
882
            {
883
                asf->packet_time_start = 0;
884
                url_fskip(pb, asf->packet_multi_size);
885
                asf->packet_size_left -= asf->packet_multi_size;
886
                continue;
887
            }
888
            asf->packet_multi_size -= asf->packet_obj_size;
889
            //printf("COMPRESS size  %d  %d  %d   ms:%d\n", asf->packet_obj_size, asf->packet_frag_timestamp, asf->packet_size_left, asf->packet_multi_size);
890
        }
891
        if(   /*asf->packet_frag_size == asf->packet_obj_size*/
892
              asf_st->frag_offset + asf->packet_frag_size <= asf_st->pkt.size
893
           && asf_st->frag_offset + asf->packet_frag_size > asf->packet_obj_size){
894
            av_log(s, AV_LOG_INFO, "ignoring invalid packet_obj_size (%d %d %d %d)\n",
895
                asf_st->frag_offset, asf->packet_frag_size,
896
                asf->packet_obj_size, asf_st->pkt.size);
897
            asf->packet_obj_size= asf_st->pkt.size;
898
        }
899

    
900
        if (   asf_st->pkt.size != asf->packet_obj_size
901
            || asf_st->frag_offset + asf->packet_frag_size > asf_st->pkt.size) { //FIXME is this condition sufficient?
902
            if(asf_st->pkt.data){
903
                av_log(s, AV_LOG_INFO, "freeing incomplete packet size %d, new %d\n", asf_st->pkt.size, asf->packet_obj_size);
904
                asf_st->frag_offset = 0;
905
                av_free_packet(&asf_st->pkt);
906
            }
907
            /* new packet */
908
            av_new_packet(&asf_st->pkt, asf->packet_obj_size);
909
            asf_st->seq = asf->packet_seq;
910
            asf_st->pkt.dts = asf->packet_frag_timestamp;
911
            asf_st->pkt.stream_index = asf->stream_index;
912
            asf_st->pkt.pos =
913
            asf_st->packet_pos= asf->packet_pos;
914
//printf("new packet: stream:%d key:%d packet_key:%d audio:%d size:%d\n",
915
//asf->stream_index, asf->packet_key_frame, asf_st->pkt.flags & AV_PKT_FLAG_KEY,
916
//s->streams[asf->stream_index]->codec->codec_type == AVMEDIA_TYPE_AUDIO, asf->packet_obj_size);
917
            if (s->streams[asf->stream_index]->codec->codec_type == AVMEDIA_TYPE_AUDIO)
918
                asf->packet_key_frame = 1;
919
            if (asf->packet_key_frame)
920
                asf_st->pkt.flags |= AV_PKT_FLAG_KEY;
921
        }
922

    
923
        /* read data */
924
        //printf("READ PACKET s:%d  os:%d  o:%d,%d  l:%d   DATA:%p\n",
925
        //       s->packet_size, asf_st->pkt.size, asf->packet_frag_offset,
926
        //       asf_st->frag_offset, asf->packet_frag_size, asf_st->pkt.data);
927
        asf->packet_size_left -= asf->packet_frag_size;
928
        if (asf->packet_size_left < 0)
929
            continue;
930

    
931
        if(   asf->packet_frag_offset >= asf_st->pkt.size
932
           || asf->packet_frag_size > asf_st->pkt.size - asf->packet_frag_offset){
933
            av_log(s, AV_LOG_ERROR, "packet fragment position invalid %u,%u not in %u\n",
934
                asf->packet_frag_offset, asf->packet_frag_size, asf_st->pkt.size);
935
            continue;
936
        }
937

    
938
        ret = get_buffer(pb, asf_st->pkt.data + asf->packet_frag_offset,
939
                         asf->packet_frag_size);
940
        if (ret != asf->packet_frag_size) {
941
            if (ret < 0 || asf->packet_frag_offset + ret == 0)
942
                return ret < 0 ? ret : AVERROR_EOF;
943
            if (asf_st->ds_span > 1) {
944
                // scrambling, we can either drop it completely or fill the remainder
945
                // TODO: should we fill the whole packet instead of just the current
946
                // fragment?
947
                memset(asf_st->pkt.data + asf->packet_frag_offset + ret, 0,
948
                       asf->packet_frag_size - ret);
949
                ret = asf->packet_frag_size;
950
            } else
951
                // no scrambling, so we can return partial packets
952
                av_shrink_packet(&asf_st->pkt, asf->packet_frag_offset + ret);
953
        }
954
        if (s->key && s->keylen == 20)
955
            ff_asfcrypt_dec(s->key, asf_st->pkt.data + asf->packet_frag_offset,
956
                            ret);
957
        asf_st->frag_offset += ret;
958
        /* test if whole packet is read */
959
        if (asf_st->frag_offset == asf_st->pkt.size) {
960
            //workaround for macroshit radio DVR-MS files
961
            if(   s->streams[asf->stream_index]->codec->codec_id == CODEC_ID_MPEG2VIDEO
962
               && asf_st->pkt.size > 100){
963
                int i;
964
                for(i=0; i<asf_st->pkt.size && !asf_st->pkt.data[i]; i++);
965
                if(i == asf_st->pkt.size){
966
                    av_log(s, AV_LOG_DEBUG, "discarding ms fart\n");
967
                    asf_st->frag_offset = 0;
968
                    av_free_packet(&asf_st->pkt);
969
                    continue;
970
                }
971
            }
972

    
973
            /* return packet */
974
            if (asf_st->ds_span > 1) {
975
              if(asf_st->pkt.size != asf_st->ds_packet_size * asf_st->ds_span){
976
                    av_log(s, AV_LOG_ERROR, "pkt.size != ds_packet_size * ds_span (%d %d %d)\n", asf_st->pkt.size, asf_st->ds_packet_size, asf_st->ds_span);
977
              }else{
978
                /* packet descrambling */
979
                uint8_t *newdata = av_malloc(asf_st->pkt.size + FF_INPUT_BUFFER_PADDING_SIZE);
980
                if (newdata) {
981
                    int offset = 0;
982
                    memset(newdata + asf_st->pkt.size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
983
                    while (offset < asf_st->pkt.size) {
984
                        int off = offset / asf_st->ds_chunk_size;
985
                        int row = off / asf_st->ds_span;
986
                        int col = off % asf_st->ds_span;
987
                        int idx = row + col * asf_st->ds_packet_size / asf_st->ds_chunk_size;
988
                        //printf("off:%d  row:%d  col:%d  idx:%d\n", off, row, col, idx);
989

    
990
                        assert(offset + asf_st->ds_chunk_size <= asf_st->pkt.size);
991
                        assert(idx+1 <= asf_st->pkt.size / asf_st->ds_chunk_size);
992
                        memcpy(newdata + offset,
993
                               asf_st->pkt.data + idx * asf_st->ds_chunk_size,
994
                               asf_st->ds_chunk_size);
995
                        offset += asf_st->ds_chunk_size;
996
                    }
997
                    av_free(asf_st->pkt.data);
998
                    asf_st->pkt.data = newdata;
999
                }
1000
              }
1001
            }
1002
            asf_st->frag_offset = 0;
1003
            *pkt= asf_st->pkt;
1004
            //printf("packet %d %d\n", asf_st->pkt.size, asf->packet_frag_size);
1005
            asf_st->pkt.size = 0;
1006
            asf_st->pkt.data = 0;
1007
            break; // packet completed
1008
        }
1009
    }
1010
    return 0;
1011
}
1012

    
1013
static int asf_read_packet(AVFormatContext *s, AVPacket *pkt)
1014
{
1015
    ASFContext *asf = s->priv_data;
1016

    
1017
    for (;;) {
1018
        int ret;
1019

    
1020
        /* parse cached packets, if any */
1021
        if ((ret = ff_asf_parse_packet(s, s->pb, pkt)) <= 0)
1022
            return ret;
1023
        if ((ret = ff_asf_get_packet(s, s->pb)) < 0)
1024
            assert(asf->packet_size_left < FRAME_HEADER_SIZE || asf->packet_segments < 1);
1025
        asf->packet_time_start = 0;
1026
    }
1027

    
1028
    return 0;
1029
}
1030

    
1031
// Added to support seeking after packets have been read
1032
// If information is not reset, read_packet fails due to
1033
// leftover information from previous reads
1034
static void asf_reset_header(AVFormatContext *s)
1035
{
1036
    ASFContext *asf = s->priv_data;
1037
    ASFStream *asf_st;
1038
    int i;
1039

    
1040
    asf->packet_nb_frames = 0;
1041
    asf->packet_size_left = 0;
1042
    asf->packet_segments = 0;
1043
    asf->packet_flags = 0;
1044
    asf->packet_property = 0;
1045
    asf->packet_timestamp = 0;
1046
    asf->packet_segsizetype = 0;
1047
    asf->packet_segments = 0;
1048
    asf->packet_seq = 0;
1049
    asf->packet_replic_size = 0;
1050
    asf->packet_key_frame = 0;
1051
    asf->packet_padsize = 0;
1052
    asf->packet_frag_offset = 0;
1053
    asf->packet_frag_size = 0;
1054
    asf->packet_frag_timestamp = 0;
1055
    asf->packet_multi_size = 0;
1056
    asf->packet_obj_size = 0;
1057
    asf->packet_time_delta = 0;
1058
    asf->packet_time_start = 0;
1059

    
1060
    for(i=0; i<s->nb_streams; i++){
1061
        asf_st= s->streams[i]->priv_data;
1062
        av_free_packet(&asf_st->pkt);
1063
        asf_st->frag_offset=0;
1064
        asf_st->seq=0;
1065
    }
1066
    asf->asf_st= NULL;
1067
}
1068

    
1069
static int asf_read_close(AVFormatContext *s)
1070
{
1071
    int i;
1072

    
1073
    asf_reset_header(s);
1074
    for(i=0;i<s->nb_streams;i++) {
1075
        AVStream *st = s->streams[i];
1076
        av_free(st->codec->palctrl);
1077
    }
1078
    return 0;
1079
}
1080

    
1081
static int64_t asf_read_pts(AVFormatContext *s, int stream_index, int64_t *ppos, int64_t pos_limit)
1082
{
1083
    AVPacket pkt1, *pkt = &pkt1;
1084
    ASFStream *asf_st;
1085
    int64_t pts;
1086
    int64_t pos= *ppos;
1087
    int i;
1088
    int64_t start_pos[ASF_MAX_STREAMS];
1089

    
1090
    for(i=0; i<s->nb_streams; i++){
1091
        start_pos[i]= pos;
1092
    }
1093

    
1094
    if (s->packet_size > 0)
1095
        pos= (pos+s->packet_size-1-s->data_offset)/s->packet_size*s->packet_size+ s->data_offset;
1096
    *ppos= pos;
1097
    url_fseek(s->pb, pos, SEEK_SET);
1098

    
1099
//printf("asf_read_pts\n");
1100
    asf_reset_header(s);
1101
    for(;;){
1102
        if (av_read_frame(s, pkt) < 0){
1103
            av_log(s, AV_LOG_INFO, "asf_read_pts failed\n");
1104
            return AV_NOPTS_VALUE;
1105
        }
1106

    
1107
        pts= pkt->pts;
1108

    
1109
        av_free_packet(pkt);
1110
        if(pkt->flags&AV_PKT_FLAG_KEY){
1111
            i= pkt->stream_index;
1112

    
1113
            asf_st= s->streams[i]->priv_data;
1114

    
1115
//            assert((asf_st->packet_pos - s->data_offset) % s->packet_size == 0);
1116
            pos= asf_st->packet_pos;
1117

    
1118
            av_add_index_entry(s->streams[i], pos, pts, pkt->size, pos - start_pos[i] + 1, AVINDEX_KEYFRAME);
1119
            start_pos[i]= asf_st->packet_pos + 1;
1120

    
1121
            if(pkt->stream_index == stream_index)
1122
               break;
1123
        }
1124
    }
1125

    
1126
    *ppos= pos;
1127
//printf("found keyframe at %"PRId64" stream %d stamp:%"PRId64"\n", *ppos, stream_index, pts);
1128

    
1129
    return pts;
1130
}
1131

    
1132
static void asf_build_simple_index(AVFormatContext *s, int stream_index)
1133
{
1134
    ff_asf_guid g;
1135
    ASFContext *asf = s->priv_data;
1136
    int64_t current_pos= url_ftell(s->pb);
1137
    int i;
1138

    
1139
    url_fseek(s->pb, asf->data_object_offset + asf->data_object_size, SEEK_SET);
1140
    ff_get_guid(s->pb, &g);
1141

    
1142
    /* the data object can be followed by other top-level objects,
1143
       skip them until the simple index object is reached */
1144
    while (ff_guidcmp(&g, &index_guid)) {
1145
        int64_t gsize= get_le64(s->pb);
1146
        if (gsize < 24 || url_feof(s->pb)) {
1147
            url_fseek(s->pb, current_pos, SEEK_SET);
1148
            return;
1149
        }
1150
        url_fseek(s->pb, gsize-24, SEEK_CUR);
1151
        ff_get_guid(s->pb, &g);
1152
    }
1153

    
1154
    {
1155
        int64_t itime, last_pos=-1;
1156
        int pct, ict;
1157
        int64_t av_unused gsize= get_le64(s->pb);
1158
        ff_get_guid(s->pb, &g);
1159
        itime=get_le64(s->pb);
1160
        pct=get_le32(s->pb);
1161
        ict=get_le32(s->pb);
1162
        av_log(s, AV_LOG_DEBUG, "itime:0x%"PRIx64", pct:%d, ict:%d\n",itime,pct,ict);
1163

    
1164
        for (i=0;i<ict;i++){
1165
            int pktnum=get_le32(s->pb);
1166
            int pktct =get_le16(s->pb);
1167
            int64_t pos      = s->data_offset + s->packet_size*(int64_t)pktnum;
1168
            int64_t index_pts= av_rescale(itime, i, 10000);
1169

    
1170
            if(pos != last_pos){
1171
            av_log(s, AV_LOG_DEBUG, "pktnum:%d, pktct:%d\n", pktnum, pktct);
1172
            av_add_index_entry(s->streams[stream_index], pos, index_pts, s->packet_size, 0, AVINDEX_KEYFRAME);
1173
            last_pos=pos;
1174
            }
1175
        }
1176
        asf->index_read= 1;
1177
    }
1178
    url_fseek(s->pb, current_pos, SEEK_SET);
1179
}
1180

    
1181
static int asf_read_seek(AVFormatContext *s, int stream_index, int64_t pts, int flags)
1182
{
1183
    ASFContext *asf = s->priv_data;
1184
    AVStream *st = s->streams[stream_index];
1185
    int64_t pos;
1186
    int index;
1187

    
1188
    if (s->packet_size <= 0)
1189
        return -1;
1190

    
1191
    /* Try using the protocol's read_seek if available */
1192
    if(s->pb) {
1193
        int ret = av_url_read_fseek(s->pb, stream_index, pts, flags);
1194
        if(ret >= 0)
1195
            asf_reset_header(s);
1196
        if (ret != AVERROR(ENOSYS))
1197
            return ret;
1198
    }
1199

    
1200
    if (!asf->index_read)
1201
        asf_build_simple_index(s, stream_index);
1202

    
1203
    if(!(asf->index_read && st->index_entries)){
1204
        if(av_seek_frame_binary(s, stream_index, pts, flags)<0)
1205
            return -1;
1206
    }else{
1207
        index= av_index_search_timestamp(st, pts, flags);
1208
        if(index<0)
1209
            return -1;
1210

    
1211
        /* find the position */
1212
        pos = st->index_entries[index].pos;
1213

    
1214
    // various attempts to find key frame have failed so far
1215
    //    asf_reset_header(s);
1216
    //    url_fseek(s->pb, pos, SEEK_SET);
1217
    //    key_pos = pos;
1218
    //     for(i=0;i<16;i++){
1219
    //         pos = url_ftell(s->pb);
1220
    //         if (av_read_frame(s, &pkt) < 0){
1221
    //             av_log(s, AV_LOG_INFO, "seek failed\n");
1222
    //             return -1;
1223
    //         }
1224
    //         asf_st = s->streams[stream_index]->priv_data;
1225
    //         pos += st->parser->frame_offset;
1226
    //
1227
    //         if (pkt.size > b) {
1228
    //             b = pkt.size;
1229
    //             key_pos = pos;
1230
    //         }
1231
    //
1232
    //         av_free_packet(&pkt);
1233
    //     }
1234

    
1235
        /* do the seek */
1236
        av_log(s, AV_LOG_DEBUG, "SEEKTO: %"PRId64"\n", pos);
1237
        url_fseek(s->pb, pos, SEEK_SET);
1238
    }
1239
    asf_reset_header(s);
1240
    return 0;
1241
}
1242

    
1243
AVInputFormat ff_asf_demuxer = {
1244
    "asf",
1245
    NULL_IF_CONFIG_SMALL("ASF format"),
1246
    sizeof(ASFContext),
1247
    asf_probe,
1248
    asf_read_header,
1249
    asf_read_packet,
1250
    asf_read_close,
1251
    asf_read_seek,
1252
    asf_read_pts,
1253
};