Statistics
| Branch: | Revision:

ffmpeg / libavformat / asfdec.c @ c1309b27

History | View | Annotate | Download (46 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 "avio_internal.h"
29
#include "riff.h"
30
#include "asf.h"
31
#include "asfcrypt.h"
32
#include "avlanguage.h"
33

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

    
36
typedef struct {
37
    int asfid2avid[128];                 ///< conversion table from asf ID 2 AVStream ID
38
    ASFStream streams[128];              ///< it's max number and it's not that big
39
    uint32_t stream_bitrates[128];       ///< max number of streams, bitrate for each (for streaming)
40
    AVRational dar[128];
41
    char stream_languages[128][6];       ///< max number of streams, language for each (RFC1766, e.g. en-US)
42
    /* non streamed additonnal info */
43
    /* packet filling */
44
    int packet_size_left;
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
static int asf_probe(AVProbeData *pd)
137
{
138
    /* check file header */
139
    if (!ff_guidcmp(pd->buf, &ff_asf_header))
140
        return AVPROBE_SCORE_MAX;
141
    else
142
        return 0;
143
}
144

    
145
static int get_value(AVIOContext *pb, int type){
146
    switch(type){
147
        case 2: return avio_rl32(pb);
148
        case 3: return avio_rl32(pb);
149
        case 4: return avio_rl64(pb);
150
        case 5: return avio_rl16(pb);
151
        default:return INT_MIN;
152
    }
153
}
154

    
155
static void get_tag(AVFormatContext *s, const char *key, int type, int len)
156
{
157
    char *value;
158
    int64_t off = avio_tell(s->pb);
159

    
160
    if ((unsigned)len >= (UINT_MAX - 1)/2)
161
        return;
162

    
163
    value = av_malloc(2*len+1);
164
    if (!value)
165
        goto finish;
166

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

    
182
static int asf_read_file_properties(AVFormatContext *s, int64_t size)
183
{
184
    ASFContext *asf = s->priv_data;
185
    AVIOContext *pb = s->pb;
186

    
187
    ff_get_guid(pb, &asf->hdr.guid);
188
    asf->hdr.file_size          = avio_rl64(pb);
189
    asf->hdr.create_time        = avio_rl64(pb);
190
    avio_rl64(pb);                               /* number of packets */
191
    asf->hdr.play_time          = avio_rl64(pb);
192
    asf->hdr.send_time          = avio_rl64(pb);
193
    asf->hdr.preroll            = avio_rl32(pb);
194
    asf->hdr.ignore             = avio_rl32(pb);
195
    asf->hdr.flags              = avio_rl32(pb);
196
    asf->hdr.min_pktsize        = avio_rl32(pb);
197
    asf->hdr.max_pktsize        = avio_rl32(pb);
198
    asf->hdr.max_bitrate        = avio_rl32(pb);
199
    s->packet_size = asf->hdr.max_pktsize;
200

    
201
    return 0;
202
}
203

    
204
static int asf_read_stream_properties(AVFormatContext *s, int64_t size)
205
{
206
    ASFContext *asf = s->priv_data;
207
    AVIOContext *pb = s->pb;
208
    AVStream *st;
209
    ASFStream *asf_st;
210
    ff_asf_guid g;
211
    enum AVMediaType type;
212
    int type_specific_size, sizeX;
213
    uint64_t total_size;
214
    unsigned int tag1;
215
    int64_t pos1, pos2, start_time;
216
    int test_for_ext_stream_audio, is_dvr_ms_audio=0;
217

    
218
    if (s->nb_streams == ASF_MAX_STREAMS) {
219
        av_log(s, AV_LOG_ERROR, "too many streams\n");
220
        return AVERROR(EINVAL);
221
    }
222

    
223
    pos1 = avio_tell(pb);
224

    
225
    st = av_new_stream(s, 0);
226
    if (!st)
227
        return AVERROR(ENOMEM);
228
    av_set_pts_info(st, 32, 1, 1000); /* 32 bit pts in ms */
229
    asf_st = av_mallocz(sizeof(ASFStream));
230
    if (!asf_st)
231
        return AVERROR(ENOMEM);
232
    st->priv_data = asf_st;
233
    start_time = asf->hdr.preroll;
234

    
235
    asf_st->stream_language_index = 128; // invalid stream index means no language info
236

    
237
    if(!(asf->hdr.flags & 0x01)) { // if we aren't streaming...
238
        st->duration = asf->hdr.play_time /
239
            (10000000 / 1000) - start_time;
240
    }
241
    ff_get_guid(pb, &g);
242

    
243
    test_for_ext_stream_audio = 0;
244
    if (!ff_guidcmp(&g, &ff_asf_audio_stream)) {
245
        type = AVMEDIA_TYPE_AUDIO;
246
    } else if (!ff_guidcmp(&g, &ff_asf_video_stream)) {
247
        type = AVMEDIA_TYPE_VIDEO;
248
    } else if (!ff_guidcmp(&g, &ff_asf_jfif_media)) {
249
        type = AVMEDIA_TYPE_VIDEO;
250
        st->codec->codec_id = CODEC_ID_MJPEG;
251
    } else if (!ff_guidcmp(&g, &ff_asf_command_stream)) {
252
        type = AVMEDIA_TYPE_DATA;
253
    } else if (!ff_guidcmp(&g, &ff_asf_ext_stream_embed_stream_header)) {
254
        test_for_ext_stream_audio = 1;
255
        type = AVMEDIA_TYPE_UNKNOWN;
256
    } else {
257
        return -1;
258
    }
259
    ff_get_guid(pb, &g);
260
    total_size = avio_rl64(pb);
261
    type_specific_size = avio_rl32(pb);
262
    avio_rl32(pb);
263
    st->id = avio_rl16(pb) & 0x7f; /* stream id */
264
    // mapping of asf ID to AV stream ID;
265
    asf->asfid2avid[st->id] = s->nb_streams - 1;
266

    
267
    avio_rl32(pb);
268

    
269
    if (test_for_ext_stream_audio) {
270
        ff_get_guid(pb, &g);
271
        if (!ff_guidcmp(&g, &ff_asf_ext_stream_audio_stream)) {
272
            type = AVMEDIA_TYPE_AUDIO;
273
            is_dvr_ms_audio=1;
274
            ff_get_guid(pb, &g);
275
            avio_rl32(pb);
276
            avio_rl32(pb);
277
            avio_rl32(pb);
278
            ff_get_guid(pb, &g);
279
            avio_rl32(pb);
280
        }
281
    }
282

    
283
    st->codec->codec_type = type;
284
    if (type == AVMEDIA_TYPE_AUDIO) {
285
        ff_get_wav_header(pb, st->codec, type_specific_size);
286
        if (is_dvr_ms_audio) {
287
            // codec_id and codec_tag are unreliable in dvr_ms
288
            // files. Set them later by probing stream.
289
            st->request_probe= 1;
290
            st->codec->codec_tag = 0;
291
        }
292
        if (st->codec->codec_id == CODEC_ID_AAC) {
293
            st->need_parsing = AVSTREAM_PARSE_NONE;
294
        } else {
295
            st->need_parsing = AVSTREAM_PARSE_FULL;
296
        }
297
        /* We have to init the frame size at some point .... */
298
        pos2 = avio_tell(pb);
299
        if (size >= (pos2 + 8 - pos1 + 24)) {
300
            asf_st->ds_span = avio_r8(pb);
301
            asf_st->ds_packet_size = avio_rl16(pb);
302
            asf_st->ds_chunk_size = avio_rl16(pb);
303
            avio_rl16(pb); //ds_data_size
304
            avio_r8(pb);   //ds_silence_data
305
        }
306
        //printf("Descrambling: ps:%d cs:%d ds:%d s:%d  sd:%d\n",
307
        //       asf_st->ds_packet_size, asf_st->ds_chunk_size,
308
        //       asf_st->ds_data_size, asf_st->ds_span, asf_st->ds_silence_data);
309
        if (asf_st->ds_span > 1) {
310
            if (!asf_st->ds_chunk_size
311
                    || (asf_st->ds_packet_size/asf_st->ds_chunk_size <= 1)
312
                    || asf_st->ds_packet_size % asf_st->ds_chunk_size)
313
                asf_st->ds_span = 0; // disable descrambling
314
        }
315
        switch (st->codec->codec_id) {
316
            case CODEC_ID_MP3:
317
                st->codec->frame_size = MPA_FRAME_SIZE;
318
                break;
319
            case CODEC_ID_PCM_S16LE:
320
            case CODEC_ID_PCM_S16BE:
321
            case CODEC_ID_PCM_U16LE:
322
            case CODEC_ID_PCM_U16BE:
323
            case CODEC_ID_PCM_S8:
324
            case CODEC_ID_PCM_U8:
325
            case CODEC_ID_PCM_ALAW:
326
            case CODEC_ID_PCM_MULAW:
327
                st->codec->frame_size = 1;
328
                break;
329
            default:
330
                /* This is probably wrong, but it prevents a crash later */
331
                st->codec->frame_size = 1;
332
                break;
333
        }
334
    } else if (type == AVMEDIA_TYPE_VIDEO &&
335
            size - (avio_tell(pb) - pos1 + 24) >= 51) {
336
        avio_rl32(pb);
337
        avio_rl32(pb);
338
        avio_r8(pb);
339
        avio_rl16(pb);        /* size */
340
        sizeX= avio_rl32(pb); /* size */
341
        st->codec->width = avio_rl32(pb);
342
        st->codec->height = avio_rl32(pb);
343
        /* not available for asf */
344
        avio_rl16(pb); /* panes */
345
        st->codec->bits_per_coded_sample = avio_rl16(pb); /* depth */
346
        tag1 = avio_rl32(pb);
347
        avio_skip(pb, 20);
348
        //                av_log(s, AV_LOG_DEBUG, "size:%d tsize:%d sizeX:%d\n", size, total_size, sizeX);
349
        if (sizeX > 40) {
350
            st->codec->extradata_size = sizeX - 40;
351
            st->codec->extradata = av_mallocz(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
352
            avio_read(pb, st->codec->extradata, st->codec->extradata_size);
353
        }
354

    
355
        /* Extract palette from extradata if bpp <= 8 */
356
        /* This code assumes that extradata contains only palette */
357
        /* This is true for all paletted codecs implemented in ffmpeg */
358
        if (st->codec->extradata_size && (st->codec->bits_per_coded_sample <= 8)) {
359
            int av_unused i;
360
            st->codec->palctrl = av_mallocz(sizeof(AVPaletteControl));
361
#if HAVE_BIGENDIAN
362
            for (i = 0; i < FFMIN(st->codec->extradata_size, AVPALETTE_SIZE)/4; i++)
363
                st->codec->palctrl->palette[i] = av_bswap32(((uint32_t*)st->codec->extradata)[i]);
364
#else
365
            memcpy(st->codec->palctrl->palette, st->codec->extradata,
366
                    FFMIN(st->codec->extradata_size, AVPALETTE_SIZE));
367
#endif
368
            st->codec->palctrl->palette_changed = 1;
369
        }
370

    
371
        st->codec->codec_tag = tag1;
372
        st->codec->codec_id = ff_codec_get_id(ff_codec_bmp_tags, tag1);
373
        if(tag1 == MKTAG('D', 'V', 'R', ' ')){
374
            st->need_parsing = AVSTREAM_PARSE_FULL;
375
            // 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
376
            st->codec->width  =
377
                st->codec->height = 0;
378
            av_freep(&st->codec->extradata);
379
            st->codec->extradata_size=0;
380
        }
381
        if(st->codec->codec_id == CODEC_ID_H264)
382
            st->need_parsing = AVSTREAM_PARSE_FULL_ONCE;
383
    }
384
    pos2 = avio_tell(pb);
385
    avio_skip(pb, size - (pos2 - pos1 + 24));
386

    
387
    return 0;
388
}
389

    
390
static int asf_read_ext_stream_properties(AVFormatContext *s, int64_t size)
391
{
392
    ASFContext *asf = s->priv_data;
393
    AVIOContext *pb = s->pb;
394
    ff_asf_guid g;
395
    int ext_len, payload_ext_ct, stream_ct, i;
396
    uint32_t ext_d, leak_rate, stream_num;
397
    unsigned int stream_languageid_index;
398

    
399
    avio_rl64(pb); // starttime
400
    avio_rl64(pb); // endtime
401
    leak_rate = avio_rl32(pb); // leak-datarate
402
    avio_rl32(pb); // bucket-datasize
403
    avio_rl32(pb); // init-bucket-fullness
404
    avio_rl32(pb); // alt-leak-datarate
405
    avio_rl32(pb); // alt-bucket-datasize
406
    avio_rl32(pb); // alt-init-bucket-fullness
407
    avio_rl32(pb); // max-object-size
408
    avio_rl32(pb); // flags (reliable,seekable,no_cleanpoints?,resend-live-cleanpoints, rest of bits reserved)
409
    stream_num = avio_rl16(pb); // stream-num
410

    
411
    stream_languageid_index = avio_rl16(pb); // stream-language-id-index
412
    if (stream_num < 128)
413
        asf->streams[stream_num].stream_language_index = stream_languageid_index;
414

    
415
    avio_rl64(pb); // avg frametime in 100ns units
416
    stream_ct = avio_rl16(pb); //stream-name-count
417
    payload_ext_ct = avio_rl16(pb); //payload-extension-system-count
418

    
419
    if (stream_num < 128)
420
        asf->stream_bitrates[stream_num] = leak_rate;
421

    
422
    for (i=0; i<stream_ct; i++){
423
        avio_rl16(pb);
424
        ext_len = avio_rl16(pb);
425
        avio_skip(pb, ext_len);
426
    }
427

    
428
    for (i=0; i<payload_ext_ct; i++){
429
        ff_get_guid(pb, &g);
430
        ext_d=avio_rl16(pb);
431
        ext_len=avio_rl32(pb);
432
        avio_skip(pb, ext_len);
433
    }
434

    
435
    return 0;
436
}
437

    
438
static int asf_read_content_desc(AVFormatContext *s, int64_t size)
439
{
440
    AVIOContext *pb = s->pb;
441
    int len1, len2, len3, len4, len5;
442

    
443
    len1 = avio_rl16(pb);
444
    len2 = avio_rl16(pb);
445
    len3 = avio_rl16(pb);
446
    len4 = avio_rl16(pb);
447
    len5 = avio_rl16(pb);
448
    get_tag(s, "title"    , 0, len1);
449
    get_tag(s, "author"   , 0, len2);
450
    get_tag(s, "copyright", 0, len3);
451
    get_tag(s, "comment"  , 0, len4);
452
    avio_skip(pb, len5);
453

    
454
    return 0;
455
}
456

    
457
static int asf_read_ext_content_desc(AVFormatContext *s, int64_t size)
458
{
459
    AVIOContext *pb = s->pb;
460
    ASFContext *asf = s->priv_data;
461
    int desc_count, i, ret;
462

    
463
    desc_count = avio_rl16(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 = avio_rl16(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
            avio_skip(pb, name_len - ret);
473
        value_type = avio_rl16(pb);
474
        value_len  = avio_rl16(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
            asf->dar[0].num= get_value(s->pb, value_type);
483
        } else if(!strcmp(name, "AspectRatioY")){
484
            asf->dar[0].den= get_value(s->pb, value_type);
485
        } else
486
            get_tag(s, name, value_type, value_len);
487
    }
488

    
489
    return 0;
490
}
491

    
492
static int asf_read_language_list(AVFormatContext *s, int64_t size)
493
{
494
    AVIOContext *pb = s->pb;
495
    ASFContext *asf = s->priv_data;
496
    int j, ret;
497
    int stream_count = avio_rl16(pb);
498
    for(j = 0; j < stream_count; j++) {
499
        char lang[6];
500
        unsigned int lang_len = avio_r8(pb);
501
        if ((ret = avio_get_str16le(pb, lang_len, lang, sizeof(lang))) < lang_len)
502
            avio_skip(pb, lang_len - ret);
503
        if (j < 128)
504
            av_strlcpy(asf->stream_languages[j], lang, sizeof(*asf->stream_languages));
505
    }
506

    
507
    return 0;
508
}
509

    
510
static int asf_read_metadata(AVFormatContext *s, int64_t size)
511
{
512
    AVIOContext *pb = s->pb;
513
    ASFContext *asf = s->priv_data;
514
    int n, stream_num, name_len, value_len, value_type, value_num;
515
    int ret, i;
516
    n = avio_rl16(pb);
517

    
518
    for(i=0;i<n;i++) {
519
        char name[1024];
520

    
521
        avio_rl16(pb); //lang_list_index
522
        stream_num= avio_rl16(pb);
523
        name_len=   avio_rl16(pb);
524
        value_type= avio_rl16(pb);
525
        value_len=  avio_rl32(pb);
526

    
527
        if ((ret = avio_get_str16le(pb, name_len, name, sizeof(name))) < name_len)
528
            avio_skip(pb, name_len - ret);
529
        //av_log(s, AV_LOG_ERROR, "%d %d %d %d %d <%s>\n", i, stream_num, name_len, value_type, value_len, name);
530
        value_num= avio_rl16(pb);//we should use get_value() here but it does not work 2 is le16 here but le32 elsewhere
531
        avio_skip(pb, value_len - 2);
532

    
533
        if(stream_num<128){
534
            if     (!strcmp(name, "AspectRatioX")) asf->dar[stream_num].num= value_num;
535
            else if(!strcmp(name, "AspectRatioY")) asf->dar[stream_num].den= value_num;
536
        }
537
    }
538

    
539
    return 0;
540
}
541

    
542
static int asf_read_marker(AVFormatContext *s, int64_t size)
543
{
544
    AVIOContext *pb = s->pb;
545
    int i, count, name_len, ret;
546
    char name[1024];
547

    
548
    avio_rl64(pb);            // reserved 16 bytes
549
    avio_rl64(pb);            // ...
550
    count = avio_rl32(pb);    // markers count
551
    avio_rl16(pb);            // reserved 2 bytes
552
    name_len = avio_rl16(pb); // name length
553
    for(i=0;i<name_len;i++){
554
        avio_r8(pb); // skip the name
555
    }
556

    
557
    for(i=0;i<count;i++){
558
        int64_t pres_time;
559
        int name_len;
560

    
561
        avio_rl64(pb);             // offset, 8 bytes
562
        pres_time = avio_rl64(pb); // presentation time
563
        avio_rl16(pb);             // entry length
564
        avio_rl32(pb);             // send time
565
        avio_rl32(pb);             // flags
566
        name_len = avio_rl32(pb);  // name length
567
        if ((ret = avio_get_str16le(pb, name_len * 2, name, sizeof(name))) < name_len)
568
            avio_skip(pb, name_len - ret);
569
        ff_new_chapter(s, i, (AVRational){1, 10000000}, pres_time, AV_NOPTS_VALUE, name );
570
    }
571

    
572
    return 0;
573
}
574

    
575
static int asf_read_header(AVFormatContext *s, AVFormatParameters *ap)
576
{
577
    ASFContext *asf = s->priv_data;
578
    ff_asf_guid g;
579
    AVIOContext *pb = s->pb;
580
    int i;
581
    int64_t gsize;
582

    
583
    ff_get_guid(pb, &g);
584
    if (ff_guidcmp(&g, &ff_asf_header))
585
        return -1;
586
    avio_rl64(pb);
587
    avio_rl32(pb);
588
    avio_r8(pb);
589
    avio_r8(pb);
590
    memset(&asf->asfid2avid, -1, sizeof(asf->asfid2avid));
591
    for(;;) {
592
        uint64_t gpos= avio_tell(pb);
593
        ff_get_guid(pb, &g);
594
        gsize = avio_rl64(pb);
595
        av_dlog(s, "%08"PRIx64": ", gpos);
596
        print_guid(&g);
597
        av_dlog(s, "  size=0x%"PRIx64"\n", gsize);
598
        if (!ff_guidcmp(&g, &ff_asf_data_header)) {
599
            asf->data_object_offset = avio_tell(pb);
600
            // if not streaming, gsize is not unlimited (how?), and there is enough space in the file..
601
            if (!(asf->hdr.flags & 0x01) && gsize >= 100) {
602
                asf->data_object_size = gsize - 24;
603
            } else {
604
                asf->data_object_size = (uint64_t)-1;
605
            }
606
            break;
607
        }
608
        if (gsize < 24)
609
            return -1;
610
        if (!ff_guidcmp(&g, &ff_asf_file_header)) {
611
            asf_read_file_properties(s, gsize);
612
        } else if (!ff_guidcmp(&g, &ff_asf_stream_header)) {
613
            asf_read_stream_properties(s, gsize);
614
        } else if (!ff_guidcmp(&g, &ff_asf_comment_header)) {
615
            asf_read_content_desc(s, gsize);
616
        } else if (!ff_guidcmp(&g, &ff_asf_language_guid)) {
617
            asf_read_language_list(s, gsize);
618
        } else if (!ff_guidcmp(&g, &ff_asf_extended_content_header)) {
619
            asf_read_ext_content_desc(s, gsize);
620
        } else if (!ff_guidcmp(&g, &ff_asf_metadata_header)) {
621
            asf_read_metadata(s, gsize);
622
        } else if (!ff_guidcmp(&g, &ff_asf_ext_stream_header)) {
623
            asf_read_ext_stream_properties(s, gsize);
624

    
625
            // there could be a optional stream properties object to follow
626
            // if so the next iteration will pick it up
627
            continue;
628
        } else if (!ff_guidcmp(&g, &ff_asf_head1_guid)) {
629
            int v1, v2;
630
            ff_get_guid(pb, &g);
631
            v1 = avio_rl32(pb);
632
            v2 = avio_rl16(pb);
633
            continue;
634
        } else if (!ff_guidcmp(&g, &ff_asf_marker_header)) {
635
            asf_read_marker(s, gsize);
636
        } else if (url_feof(pb)) {
637
            return -1;
638
        } else {
639
            if (!s->keylen) {
640
                if (!ff_guidcmp(&g, &ff_asf_content_encryption)) {
641
                    av_log(s, AV_LOG_WARNING, "DRM protected stream detected, decoding will likely fail!\n");
642
                } else if (!ff_guidcmp(&g, &ff_asf_ext_content_encryption)) {
643
                    av_log(s, AV_LOG_WARNING, "Ext DRM protected stream detected, decoding will likely fail!\n");
644
                } else if (!ff_guidcmp(&g, &ff_asf_digital_signature)) {
645
                    av_log(s, AV_LOG_WARNING, "Digital signature detected, decoding will likely fail!\n");
646
                }
647
            }
648
        }
649
        if(avio_tell(pb) != gpos + gsize)
650
            av_log(s, AV_LOG_DEBUG, "gpos mismatch our pos=%"PRIu64", end=%"PRIu64"\n", avio_tell(pb)-gpos, gsize);
651
        avio_seek(pb, gpos + gsize, SEEK_SET);
652
    }
653
    ff_get_guid(pb, &g);
654
    avio_rl64(pb);
655
    avio_r8(pb);
656
    avio_r8(pb);
657
    if (url_feof(pb))
658
        return -1;
659
    asf->data_offset = avio_tell(pb);
660
    asf->packet_size_left = 0;
661

    
662

    
663
    for(i=0; i<128; i++){
664
        int stream_num= asf->asfid2avid[i];
665
        if(stream_num>=0){
666
            AVStream *st = s->streams[stream_num];
667
            if (!st->codec->bit_rate)
668
                st->codec->bit_rate = asf->stream_bitrates[i];
669
            if (asf->dar[i].num > 0 && asf->dar[i].den > 0){
670
                av_reduce(&st->sample_aspect_ratio.num,
671
                          &st->sample_aspect_ratio.den,
672
                          asf->dar[i].num, asf->dar[i].den, INT_MAX);
673
            } else if ((asf->dar[0].num > 0) && (asf->dar[0].den > 0) && (st->codec->codec_type==AVMEDIA_TYPE_VIDEO)) // Use ASF container value if the stream doesn't AR set.
674
                av_reduce(&st->sample_aspect_ratio.num,
675
                          &st->sample_aspect_ratio.den,
676
                          asf->dar[0].num, asf->dar[0].den, INT_MAX);
677

    
678
//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);
679

    
680
            // copy and convert language codes to the frontend
681
            if (asf->streams[i].stream_language_index < 128) {
682
                const char *rfc1766 = asf->stream_languages[asf->streams[i].stream_language_index];
683
                if (rfc1766 && strlen(rfc1766) > 1) {
684
                    const char primary_tag[3] = { rfc1766[0], rfc1766[1], '\0' }; // ignore country code if any
685
                    const char *iso6392 = av_convert_lang_to(primary_tag, AV_LANG_ISO639_2_BIBL);
686
                    if (iso6392)
687
                        av_metadata_set2(&st->metadata, "language", iso6392, 0);
688
                }
689
            }
690
        }
691
    }
692

    
693
    ff_metadata_conv(&s->metadata, NULL, ff_asf_metadata_conv);
694

    
695
    return 0;
696
}
697

    
698
#define DO_2BITS(bits, var, defval) \
699
    switch (bits & 3) \
700
    { \
701
    case 3: var = avio_rl32(pb); rsize += 4; break; \
702
    case 2: var = avio_rl16(pb); rsize += 2; break; \
703
    case 1: var = avio_r8(pb);   rsize++; break; \
704
    default: var = defval; break; \
705
    }
706

    
707
/**
708
 * Load a single ASF packet into the demuxer.
709
 * @param s demux context
710
 * @param pb context to read data from
711
 * @return 0 on success, <0 on error
712
 */
713
static int ff_asf_get_packet(AVFormatContext *s, AVIOContext *pb)
714
{
715
    ASFContext *asf = s->priv_data;
716
    uint32_t packet_length, padsize;
717
    int rsize = 8;
718
    int c, d, e, off;
719

    
720
    // if we do not know packet size, allow skipping up to 32 kB
721
    off= 32768;
722
    if (s->packet_size > 0)
723
        off= (avio_tell(pb) - s->data_offset) % s->packet_size + 3;
724

    
725
    c=d=e=-1;
726
    while(off-- > 0){
727
        c=d; d=e;
728
        e= avio_r8(pb);
729
        if(c == 0x82 && !d && !e)
730
            break;
731
    }
732

    
733
    if (c != 0x82) {
734
        /**
735
         * This code allows handling of -EAGAIN at packet boundaries (i.e.
736
         * if the packet sync code above triggers -EAGAIN). This does not
737
         * imply complete -EAGAIN handling support at random positions in
738
         * the stream.
739
         */
740
        if (pb->error == AVERROR(EAGAIN))
741
            return AVERROR(EAGAIN);
742
        if (!url_feof(pb))
743
            av_log(s, AV_LOG_ERROR, "ff asf bad header %x  at:%"PRId64"\n", c, avio_tell(pb));
744
    }
745
    if ((c & 0x8f) == 0x82) {
746
        if (d || e) {
747
            if (!url_feof(pb))
748
                av_log(s, AV_LOG_ERROR, "ff asf bad non zero\n");
749
            return -1;
750
        }
751
        c= avio_r8(pb);
752
        d= avio_r8(pb);
753
        rsize+=3;
754
    }else{
755
        avio_seek(pb, -1, SEEK_CUR); //FIXME
756
    }
757

    
758
    asf->packet_flags    = c;
759
    asf->packet_property = d;
760

    
761
    DO_2BITS(asf->packet_flags >> 5, packet_length, s->packet_size);
762
    DO_2BITS(asf->packet_flags >> 1, padsize, 0); // sequence ignored
763
    DO_2BITS(asf->packet_flags >> 3, padsize, 0); // padding length
764

    
765
    //the following checks prevent overflows and infinite loops
766
    if(!packet_length || packet_length >= (1U<<29)){
767
        av_log(s, AV_LOG_ERROR, "invalid packet_length %d at:%"PRId64"\n", packet_length, avio_tell(pb));
768
        return -1;
769
    }
770
    if(padsize >= packet_length){
771
        av_log(s, AV_LOG_ERROR, "invalid padsize %d at:%"PRId64"\n", padsize, avio_tell(pb));
772
        return -1;
773
    }
774

    
775
    asf->packet_timestamp = avio_rl32(pb);
776
    avio_rl16(pb); /* duration */
777
    // rsize has at least 11 bytes which have to be present
778

    
779
    if (asf->packet_flags & 0x01) {
780
        asf->packet_segsizetype = avio_r8(pb); rsize++;
781
        asf->packet_segments = asf->packet_segsizetype & 0x3f;
782
    } else {
783
        asf->packet_segments = 1;
784
        asf->packet_segsizetype = 0x80;
785
    }
786
    asf->packet_size_left = packet_length - padsize - rsize;
787
    if (packet_length < asf->hdr.min_pktsize)
788
        padsize += asf->hdr.min_pktsize - packet_length;
789
    asf->packet_padsize = padsize;
790
    av_dlog(s, "packet: size=%d padsize=%d  left=%d\n", s->packet_size, asf->packet_padsize, asf->packet_size_left);
791
    return 0;
792
}
793

    
794
/**
795
 *
796
 * @return <0 if error
797
 */
798
static int asf_read_frame_header(AVFormatContext *s, AVIOContext *pb){
799
    ASFContext *asf = s->priv_data;
800
    int rsize = 1;
801
    int num = avio_r8(pb);
802
    int64_t ts0, ts1;
803

    
804
    asf->packet_segments--;
805
    asf->packet_key_frame = num >> 7;
806
    asf->stream_index = asf->asfid2avid[num & 0x7f];
807
    // sequence should be ignored!
808
    DO_2BITS(asf->packet_property >> 4, asf->packet_seq, 0);
809
    DO_2BITS(asf->packet_property >> 2, asf->packet_frag_offset, 0);
810
    DO_2BITS(asf->packet_property, asf->packet_replic_size, 0);
811
//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);
812
    if (asf->packet_replic_size >= 8) {
813
        asf->packet_obj_size = avio_rl32(pb);
814
        if(asf->packet_obj_size >= (1<<24) || asf->packet_obj_size <= 0){
815
            av_log(s, AV_LOG_ERROR, "packet_obj_size invalid\n");
816
            return -1;
817
        }
818
        asf->packet_frag_timestamp = avio_rl32(pb); // timestamp
819
        if(asf->packet_replic_size >= 8+38+4){
820
//            for(i=0; i<asf->packet_replic_size-8; i++)
821
//                av_log(s, AV_LOG_DEBUG, "%02X ",avio_r8(pb));
822
//            av_log(s, AV_LOG_DEBUG, "\n");
823
            avio_skip(pb, 10);
824
            ts0= avio_rl64(pb);
825
            ts1= avio_rl64(pb);
826
            avio_skip(pb, 12);
827
            avio_rl32(pb);
828
            avio_skip(pb, asf->packet_replic_size - 8 - 38 - 4);
829
            if(ts0!= -1) asf->packet_frag_timestamp= ts0/10000;
830
            else         asf->packet_frag_timestamp= AV_NOPTS_VALUE;
831
        }else
832
            avio_skip(pb, asf->packet_replic_size - 8);
833
        rsize += asf->packet_replic_size; // FIXME - check validity
834
    } else if (asf->packet_replic_size==1){
835
        // multipacket - frag_offset is beginning timestamp
836
        asf->packet_time_start = asf->packet_frag_offset;
837
        asf->packet_frag_offset = 0;
838
        asf->packet_frag_timestamp = asf->packet_timestamp;
839

    
840
        asf->packet_time_delta = avio_r8(pb);
841
        rsize++;
842
    }else if(asf->packet_replic_size!=0){
843
        av_log(s, AV_LOG_ERROR, "unexpected packet_replic_size of %d\n", asf->packet_replic_size);
844
        return -1;
845
    }
846
    if (asf->packet_flags & 0x01) {
847
        DO_2BITS(asf->packet_segsizetype >> 6, asf->packet_frag_size, 0); // 0 is illegal
848
        if(asf->packet_frag_size > asf->packet_size_left - rsize){
849
            av_log(s, AV_LOG_ERROR, "packet_frag_size is invalid\n");
850
            return -1;
851
        }
852
        //printf("Fragsize %d\n", asf->packet_frag_size);
853
    } else {
854
        asf->packet_frag_size = asf->packet_size_left - rsize;
855
        //printf("Using rest  %d %d %d\n", asf->packet_frag_size, asf->packet_size_left, rsize);
856
    }
857
    if (asf->packet_replic_size == 1) {
858
        asf->packet_multi_size = asf->packet_frag_size;
859
        if (asf->packet_multi_size > asf->packet_size_left)
860
            return -1;
861
    }
862
    asf->packet_size_left -= rsize;
863
    //printf("___objsize____  %d   %d    rs:%d\n", asf->packet_obj_size, asf->packet_frag_offset, rsize);
864

    
865
    return 0;
866
}
867

    
868
/**
869
 * Parse data from individual ASF packets (which were previously loaded
870
 * with asf_get_packet()).
871
 * @param s demux context
872
 * @param pb context to read data from
873
 * @param pkt pointer to store packet data into
874
 * @return 0 if data was stored in pkt, <0 on error or 1 if more ASF
875
 *          packets need to be loaded (through asf_get_packet())
876
 */
877
static int ff_asf_parse_packet(AVFormatContext *s, AVIOContext *pb, AVPacket *pkt)
878
{
879
    ASFContext *asf = s->priv_data;
880
    ASFStream *asf_st = 0;
881
    for (;;) {
882
        int ret;
883
        if(url_feof(pb))
884
            return AVERROR_EOF;
885
        if (asf->packet_size_left < FRAME_HEADER_SIZE
886
            || asf->packet_segments < 1) {
887
            //asf->packet_size_left <= asf->packet_padsize) {
888
            int ret = asf->packet_size_left + asf->packet_padsize;
889
            //printf("PacketLeftSize:%d  Pad:%d Pos:%"PRId64"\n", asf->packet_size_left, asf->packet_padsize, avio_tell(pb));
890
            assert(ret>=0);
891
            /* fail safe */
892
            avio_skip(pb, ret);
893

    
894
            asf->packet_pos= avio_tell(pb);
895
            if (asf->data_object_size != (uint64_t)-1 &&
896
                (asf->packet_pos - asf->data_object_offset >= asf->data_object_size))
897
                return AVERROR_EOF; /* Do not exceed the size of the data object */
898
            return 1;
899
        }
900
        if (asf->packet_time_start == 0) {
901
            if(asf_read_frame_header(s, pb) < 0){
902
                asf->packet_segments= 0;
903
                continue;
904
            }
905
            if (asf->stream_index < 0
906
                || s->streams[asf->stream_index]->discard >= AVDISCARD_ALL
907
                || (!asf->packet_key_frame && s->streams[asf->stream_index]->discard >= AVDISCARD_NONKEY)
908
                ) {
909
                asf->packet_time_start = 0;
910
                /* unhandled packet (should not happen) */
911
                avio_skip(pb, asf->packet_frag_size);
912
                asf->packet_size_left -= asf->packet_frag_size;
913
                if(asf->stream_index < 0)
914
                    av_log(s, AV_LOG_ERROR, "ff asf skip %d (unknown stream)\n", asf->packet_frag_size);
915
                continue;
916
            }
917
            asf->asf_st = s->streams[asf->stream_index]->priv_data;
918
        }
919
        asf_st = asf->asf_st;
920

    
921
        if (asf->packet_replic_size == 1) {
922
            // frag_offset is here used as the beginning timestamp
923
            asf->packet_frag_timestamp = asf->packet_time_start;
924
            asf->packet_time_start += asf->packet_time_delta;
925
            asf->packet_obj_size = asf->packet_frag_size = avio_r8(pb);
926
            asf->packet_size_left--;
927
            asf->packet_multi_size--;
928
            if (asf->packet_multi_size < asf->packet_obj_size)
929
            {
930
                asf->packet_time_start = 0;
931
                avio_skip(pb, asf->packet_multi_size);
932
                asf->packet_size_left -= asf->packet_multi_size;
933
                continue;
934
            }
935
            asf->packet_multi_size -= asf->packet_obj_size;
936
            //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);
937
        }
938
        if(   /*asf->packet_frag_size == asf->packet_obj_size*/
939
              asf_st->frag_offset + asf->packet_frag_size <= asf_st->pkt.size
940
           && asf_st->frag_offset + asf->packet_frag_size > asf->packet_obj_size){
941
            av_log(s, AV_LOG_INFO, "ignoring invalid packet_obj_size (%d %d %d %d)\n",
942
                asf_st->frag_offset, asf->packet_frag_size,
943
                asf->packet_obj_size, asf_st->pkt.size);
944
            asf->packet_obj_size= asf_st->pkt.size;
945
        }
946

    
947
        if (   asf_st->pkt.size != asf->packet_obj_size
948
            || asf_st->frag_offset + asf->packet_frag_size > asf_st->pkt.size) { //FIXME is this condition sufficient?
949
            if(asf_st->pkt.data){
950
                av_log(s, AV_LOG_INFO, "freeing incomplete packet size %d, new %d\n", asf_st->pkt.size, asf->packet_obj_size);
951
                asf_st->frag_offset = 0;
952
                av_free_packet(&asf_st->pkt);
953
            }
954
            /* new packet */
955
            av_new_packet(&asf_st->pkt, asf->packet_obj_size);
956
            asf_st->seq = asf->packet_seq;
957
            asf_st->pkt.dts = asf->packet_frag_timestamp - asf->hdr.preroll;
958
            asf_st->pkt.stream_index = asf->stream_index;
959
            asf_st->pkt.pos =
960
            asf_st->packet_pos= asf->packet_pos;
961
//printf("new packet: stream:%d key:%d packet_key:%d audio:%d size:%d\n",
962
//asf->stream_index, asf->packet_key_frame, asf_st->pkt.flags & AV_PKT_FLAG_KEY,
963
//s->streams[asf->stream_index]->codec->codec_type == AVMEDIA_TYPE_AUDIO, asf->packet_obj_size);
964
            if (s->streams[asf->stream_index]->codec->codec_type == AVMEDIA_TYPE_AUDIO)
965
                asf->packet_key_frame = 1;
966
            if (asf->packet_key_frame)
967
                asf_st->pkt.flags |= AV_PKT_FLAG_KEY;
968
        }
969

    
970
        /* read data */
971
        //printf("READ PACKET s:%d  os:%d  o:%d,%d  l:%d   DATA:%p\n",
972
        //       s->packet_size, asf_st->pkt.size, asf->packet_frag_offset,
973
        //       asf_st->frag_offset, asf->packet_frag_size, asf_st->pkt.data);
974
        asf->packet_size_left -= asf->packet_frag_size;
975
        if (asf->packet_size_left < 0)
976
            continue;
977

    
978
        if(   asf->packet_frag_offset >= asf_st->pkt.size
979
           || asf->packet_frag_size > asf_st->pkt.size - asf->packet_frag_offset){
980
            av_log(s, AV_LOG_ERROR, "packet fragment position invalid %u,%u not in %u\n",
981
                asf->packet_frag_offset, asf->packet_frag_size, asf_st->pkt.size);
982
            continue;
983
        }
984

    
985
        ret = avio_read(pb, asf_st->pkt.data + asf->packet_frag_offset,
986
                         asf->packet_frag_size);
987
        if (ret != asf->packet_frag_size) {
988
            if (ret < 0 || asf->packet_frag_offset + ret == 0)
989
                return ret < 0 ? ret : AVERROR_EOF;
990
            if (asf_st->ds_span > 1) {
991
                // scrambling, we can either drop it completely or fill the remainder
992
                // TODO: should we fill the whole packet instead of just the current
993
                // fragment?
994
                memset(asf_st->pkt.data + asf->packet_frag_offset + ret, 0,
995
                       asf->packet_frag_size - ret);
996
                ret = asf->packet_frag_size;
997
            } else
998
                // no scrambling, so we can return partial packets
999
                av_shrink_packet(&asf_st->pkt, asf->packet_frag_offset + ret);
1000
        }
1001
        if (s->key && s->keylen == 20)
1002
            ff_asfcrypt_dec(s->key, asf_st->pkt.data + asf->packet_frag_offset,
1003
                            ret);
1004
        asf_st->frag_offset += ret;
1005
        /* test if whole packet is read */
1006
        if (asf_st->frag_offset == asf_st->pkt.size) {
1007
            //workaround for macroshit radio DVR-MS files
1008
            if(   s->streams[asf->stream_index]->codec->codec_id == CODEC_ID_MPEG2VIDEO
1009
               && asf_st->pkt.size > 100){
1010
                int i;
1011
                for(i=0; i<asf_st->pkt.size && !asf_st->pkt.data[i]; i++);
1012
                if(i == asf_st->pkt.size){
1013
                    av_log(s, AV_LOG_DEBUG, "discarding ms fart\n");
1014
                    asf_st->frag_offset = 0;
1015
                    av_free_packet(&asf_st->pkt);
1016
                    continue;
1017
                }
1018
            }
1019

    
1020
            /* return packet */
1021
            if (asf_st->ds_span > 1) {
1022
              if(asf_st->pkt.size != asf_st->ds_packet_size * asf_st->ds_span){
1023
                    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);
1024
              }else{
1025
                /* packet descrambling */
1026
                uint8_t *newdata = av_malloc(asf_st->pkt.size + FF_INPUT_BUFFER_PADDING_SIZE);
1027
                if (newdata) {
1028
                    int offset = 0;
1029
                    memset(newdata + asf_st->pkt.size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
1030
                    while (offset < asf_st->pkt.size) {
1031
                        int off = offset / asf_st->ds_chunk_size;
1032
                        int row = off / asf_st->ds_span;
1033
                        int col = off % asf_st->ds_span;
1034
                        int idx = row + col * asf_st->ds_packet_size / asf_st->ds_chunk_size;
1035
                        //printf("off:%d  row:%d  col:%d  idx:%d\n", off, row, col, idx);
1036

    
1037
                        assert(offset + asf_st->ds_chunk_size <= asf_st->pkt.size);
1038
                        assert(idx+1 <= asf_st->pkt.size / asf_st->ds_chunk_size);
1039
                        memcpy(newdata + offset,
1040
                               asf_st->pkt.data + idx * asf_st->ds_chunk_size,
1041
                               asf_st->ds_chunk_size);
1042
                        offset += asf_st->ds_chunk_size;
1043
                    }
1044
                    av_free(asf_st->pkt.data);
1045
                    asf_st->pkt.data = newdata;
1046
                }
1047
              }
1048
            }
1049
            asf_st->frag_offset = 0;
1050
            *pkt= asf_st->pkt;
1051
            //printf("packet %d %d\n", asf_st->pkt.size, asf->packet_frag_size);
1052
            asf_st->pkt.size = 0;
1053
            asf_st->pkt.data = 0;
1054
            break; // packet completed
1055
        }
1056
    }
1057
    return 0;
1058
}
1059

    
1060
static int asf_read_packet(AVFormatContext *s, AVPacket *pkt)
1061
{
1062
    ASFContext *asf = s->priv_data;
1063

    
1064
    for (;;) {
1065
        int ret;
1066

    
1067
        /* parse cached packets, if any */
1068
        if ((ret = ff_asf_parse_packet(s, s->pb, pkt)) <= 0)
1069
            return ret;
1070
        if ((ret = ff_asf_get_packet(s, s->pb)) < 0)
1071
            assert(asf->packet_size_left < FRAME_HEADER_SIZE || asf->packet_segments < 1);
1072
        asf->packet_time_start = 0;
1073
    }
1074

    
1075
    return 0;
1076
}
1077

    
1078
// Added to support seeking after packets have been read
1079
// If information is not reset, read_packet fails due to
1080
// leftover information from previous reads
1081
static void asf_reset_header(AVFormatContext *s)
1082
{
1083
    ASFContext *asf = s->priv_data;
1084
    ASFStream *asf_st;
1085
    int i;
1086

    
1087
    asf->packet_size_left = 0;
1088
    asf->packet_segments = 0;
1089
    asf->packet_flags = 0;
1090
    asf->packet_property = 0;
1091
    asf->packet_timestamp = 0;
1092
    asf->packet_segsizetype = 0;
1093
    asf->packet_segments = 0;
1094
    asf->packet_seq = 0;
1095
    asf->packet_replic_size = 0;
1096
    asf->packet_key_frame = 0;
1097
    asf->packet_padsize = 0;
1098
    asf->packet_frag_offset = 0;
1099
    asf->packet_frag_size = 0;
1100
    asf->packet_frag_timestamp = 0;
1101
    asf->packet_multi_size = 0;
1102
    asf->packet_obj_size = 0;
1103
    asf->packet_time_delta = 0;
1104
    asf->packet_time_start = 0;
1105

    
1106
    for(i=0; i<s->nb_streams; i++){
1107
        asf_st= s->streams[i]->priv_data;
1108
        av_free_packet(&asf_st->pkt);
1109
        asf_st->frag_offset=0;
1110
        asf_st->seq=0;
1111
    }
1112
    asf->asf_st= NULL;
1113
}
1114

    
1115
static int asf_read_close(AVFormatContext *s)
1116
{
1117
    int i;
1118

    
1119
    asf_reset_header(s);
1120
    for(i=0;i<s->nb_streams;i++) {
1121
        AVStream *st = s->streams[i];
1122
        av_free(st->codec->palctrl);
1123
    }
1124
    return 0;
1125
}
1126

    
1127
static int64_t asf_read_pts(AVFormatContext *s, int stream_index, int64_t *ppos, int64_t pos_limit)
1128
{
1129
    AVPacket pkt1, *pkt = &pkt1;
1130
    ASFStream *asf_st;
1131
    int64_t pts;
1132
    int64_t pos= *ppos;
1133
    int i;
1134
    int64_t start_pos[ASF_MAX_STREAMS];
1135

    
1136
    for(i=0; i<s->nb_streams; i++){
1137
        start_pos[i]= pos;
1138
    }
1139

    
1140
    if (s->packet_size > 0)
1141
        pos= (pos+s->packet_size-1-s->data_offset)/s->packet_size*s->packet_size+ s->data_offset;
1142
    *ppos= pos;
1143
    avio_seek(s->pb, pos, SEEK_SET);
1144

    
1145
//printf("asf_read_pts\n");
1146
    asf_reset_header(s);
1147
    for(;;){
1148
        if (av_read_frame(s, pkt) < 0){
1149
            av_log(s, AV_LOG_INFO, "asf_read_pts failed\n");
1150
            return AV_NOPTS_VALUE;
1151
        }
1152

    
1153
        pts= pkt->pts;
1154

    
1155
        av_free_packet(pkt);
1156
        if(pkt->flags&AV_PKT_FLAG_KEY){
1157
            i= pkt->stream_index;
1158

    
1159
            asf_st= s->streams[i]->priv_data;
1160

    
1161
//            assert((asf_st->packet_pos - s->data_offset) % s->packet_size == 0);
1162
            pos= asf_st->packet_pos;
1163

    
1164
            av_add_index_entry(s->streams[i], pos, pts, pkt->size, pos - start_pos[i] + 1, AVINDEX_KEYFRAME);
1165
            start_pos[i]= asf_st->packet_pos + 1;
1166

    
1167
            if(pkt->stream_index == stream_index)
1168
               break;
1169
        }
1170
    }
1171

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

    
1175
    return pts;
1176
}
1177

    
1178
static void asf_build_simple_index(AVFormatContext *s, int stream_index)
1179
{
1180
    ff_asf_guid g;
1181
    ASFContext *asf = s->priv_data;
1182
    int64_t current_pos= avio_tell(s->pb);
1183
    int i;
1184

    
1185
    avio_seek(s->pb, asf->data_object_offset + asf->data_object_size, SEEK_SET);
1186
    ff_get_guid(s->pb, &g);
1187

    
1188
    /* the data object can be followed by other top-level objects,
1189
       skip them until the simple index object is reached */
1190
    while (ff_guidcmp(&g, &index_guid)) {
1191
        int64_t gsize= avio_rl64(s->pb);
1192
        if (gsize < 24 || url_feof(s->pb)) {
1193
            avio_seek(s->pb, current_pos, SEEK_SET);
1194
            return;
1195
        }
1196
        avio_skip(s->pb, gsize-24);
1197
        ff_get_guid(s->pb, &g);
1198
    }
1199

    
1200
    {
1201
        int64_t itime, last_pos=-1;
1202
        int pct, ict;
1203
        int64_t av_unused gsize= avio_rl64(s->pb);
1204
        ff_get_guid(s->pb, &g);
1205
        itime=avio_rl64(s->pb);
1206
        pct=avio_rl32(s->pb);
1207
        ict=avio_rl32(s->pb);
1208
        av_log(s, AV_LOG_DEBUG, "itime:0x%"PRIx64", pct:%d, ict:%d\n",itime,pct,ict);
1209

    
1210
        for (i=0;i<ict;i++){
1211
            int pktnum=avio_rl32(s->pb);
1212
            int pktct =avio_rl16(s->pb);
1213
            int64_t pos      = s->data_offset + s->packet_size*(int64_t)pktnum;
1214
            int64_t index_pts= FFMAX(av_rescale(itime, i, 10000) - asf->hdr.preroll, 0);
1215

    
1216
            if(pos != last_pos){
1217
            av_log(s, AV_LOG_DEBUG, "pktnum:%d, pktct:%d  pts: %"PRId64"\n", pktnum, pktct, index_pts);
1218
            av_add_index_entry(s->streams[stream_index], pos, index_pts, s->packet_size, 0, AVINDEX_KEYFRAME);
1219
            last_pos=pos;
1220
            }
1221
        }
1222
        asf->index_read= 1;
1223
    }
1224
    avio_seek(s->pb, current_pos, SEEK_SET);
1225
}
1226

    
1227
static int asf_read_seek(AVFormatContext *s, int stream_index, int64_t pts, int flags)
1228
{
1229
    ASFContext *asf = s->priv_data;
1230
    AVStream *st = s->streams[stream_index];
1231
    int64_t pos;
1232
    int index;
1233

    
1234
    if (s->packet_size <= 0)
1235
        return -1;
1236

    
1237
    /* Try using the protocol's read_seek if available */
1238
    if(s->pb) {
1239
        int ret = ffio_read_seek(s->pb, stream_index, pts, flags);
1240
        if(ret >= 0)
1241
            asf_reset_header(s);
1242
        if (ret != AVERROR(ENOSYS))
1243
            return ret;
1244
    }
1245

    
1246
    if (!asf->index_read)
1247
        asf_build_simple_index(s, stream_index);
1248

    
1249
    if(!(asf->index_read && st->index_entries)){
1250
        if(av_seek_frame_binary(s, stream_index, pts, flags)<0)
1251
            return -1;
1252
    }else{
1253
        index= av_index_search_timestamp(st, pts, flags);
1254
        if(index<0)
1255
            return -1;
1256

    
1257
        /* find the position */
1258
        pos = st->index_entries[index].pos;
1259

    
1260
    // various attempts to find key frame have failed so far
1261
    //    asf_reset_header(s);
1262
    //    avio_seek(s->pb, pos, SEEK_SET);
1263
    //    key_pos = pos;
1264
    //     for(i=0;i<16;i++){
1265
    //         pos = avio_tell(s->pb);
1266
    //         if (av_read_frame(s, &pkt) < 0){
1267
    //             av_log(s, AV_LOG_INFO, "seek failed\n");
1268
    //             return -1;
1269
    //         }
1270
    //         asf_st = s->streams[stream_index]->priv_data;
1271
    //         pos += st->parser->frame_offset;
1272
    //
1273
    //         if (pkt.size > b) {
1274
    //             b = pkt.size;
1275
    //             key_pos = pos;
1276
    //         }
1277
    //
1278
    //         av_free_packet(&pkt);
1279
    //     }
1280

    
1281
        /* do the seek */
1282
        av_log(s, AV_LOG_DEBUG, "SEEKTO: %"PRId64"\n", pos);
1283
        avio_seek(s->pb, pos, SEEK_SET);
1284
    }
1285
    asf_reset_header(s);
1286
    return 0;
1287
}
1288

    
1289
AVInputFormat ff_asf_demuxer = {
1290
    "asf",
1291
    NULL_IF_CONFIG_SMALL("ASF format"),
1292
    sizeof(ASFContext),
1293
    asf_probe,
1294
    asf_read_header,
1295
    asf_read_packet,
1296
    asf_read_close,
1297
    asf_read_seek,
1298
    asf_read_pts,
1299
};