Statistics
| Branch: | Revision:

ffmpeg / libavformat / asfdec.c @ 607f5fe5

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 "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
    AVRational dar[128];
40
    char stream_languages[128][6];       ///< max number of streams, language for each (RFC1766, e.g. en-US)
41
    /* non streamed additonnal info */
42
    /* packet filling */
43
    int packet_size_left;
44
    /* only for reading */
45
    uint64_t data_offset;                ///< beginning of the first data packet
46
    uint64_t data_object_offset;         ///< data object offset (excl. GUID & size)
47
    uint64_t data_object_size;           ///< size of the data object
48
    int index_read;
49

    
50
    ASFMainHeader hdr;
51

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

    
70
    int stream_index;
71

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
187
static int asf_read_file_properties(AVFormatContext *s, int64_t size)
188
{
189
    ASFContext *asf = s->priv_data;
190
    ByteIOContext *pb = s->pb;
191

    
192
    ff_get_guid(pb, &asf->hdr.guid);
193
    asf->hdr.file_size          = get_le64(pb);
194
    asf->hdr.create_time        = get_le64(pb);
195
    get_le64(pb);                               /* number of packets */
196
    asf->hdr.play_time          = get_le64(pb);
197
    asf->hdr.send_time          = get_le64(pb);
198
    asf->hdr.preroll            = get_le32(pb);
199
    asf->hdr.ignore             = get_le32(pb);
200
    asf->hdr.flags              = get_le32(pb);
201
    asf->hdr.min_pktsize        = get_le32(pb);
202
    asf->hdr.max_pktsize        = get_le32(pb);
203
    asf->hdr.max_bitrate        = get_le32(pb);
204
    s->packet_size = asf->hdr.max_pktsize;
205

    
206
    return 0;
207
}
208

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

    
223
    if (s->nb_streams == ASF_MAX_STREAMS) {
224
        av_log(s, AV_LOG_ERROR, "too many streams\n");
225
        return AVERROR(EINVAL);
226
    }
227

    
228
    pos1 = url_ftell(pb);
229

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

    
240
    asf_st->stream_language_index = 128; // invalid stream index means no language info
241

    
242
    if(!(asf->hdr.flags & 0x01)) { // if we aren't streaming...
243
        st->duration = asf->hdr.play_time /
244
            (10000000 / 1000) - start_time;
245
    }
246
    ff_get_guid(pb, &g);
247

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

    
272
    get_le32(pb);
273

    
274
    if (test_for_ext_stream_audio) {
275
        ff_get_guid(pb, &g);
276
        if (!ff_guidcmp(&g, &ff_asf_ext_stream_audio_stream)) {
277
            type = AVMEDIA_TYPE_AUDIO;
278
            is_dvr_ms_audio=1;
279
            ff_get_guid(pb, &g);
280
            get_le32(pb);
281
            get_le32(pb);
282
            get_le32(pb);
283
            ff_get_guid(pb, &g);
284
            get_le32(pb);
285
        }
286
    }
287

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

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

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

    
391
    return 0;
392
}
393

    
394
static int asf_read_ext_stream_properties(AVFormatContext *s, int64_t size)
395
{
396
    ASFContext *asf = s->priv_data;
397
    ByteIOContext *pb = s->pb;
398
    ff_asf_guid g;
399
    int ext_len, payload_ext_ct, stream_ct, i;
400
    uint32_t ext_d, leak_rate, stream_num;
401
    unsigned int stream_languageid_index;
402

    
403
    get_le64(pb); // starttime
404
    get_le64(pb); // endtime
405
    leak_rate = get_le32(pb); // leak-datarate
406
    get_le32(pb); // bucket-datasize
407
    get_le32(pb); // init-bucket-fullness
408
    get_le32(pb); // alt-leak-datarate
409
    get_le32(pb); // alt-bucket-datasize
410
    get_le32(pb); // alt-init-bucket-fullness
411
    get_le32(pb); // max-object-size
412
    get_le32(pb); // flags (reliable,seekable,no_cleanpoints?,resend-live-cleanpoints, rest of bits reserved)
413
    stream_num = get_le16(pb); // stream-num
414

    
415
    stream_languageid_index = get_le16(pb); // stream-language-id-index
416
    if (stream_num < 128)
417
        asf->streams[stream_num].stream_language_index = stream_languageid_index;
418

    
419
    get_le64(pb); // avg frametime in 100ns units
420
    stream_ct = get_le16(pb); //stream-name-count
421
    payload_ext_ct = get_le16(pb); //payload-extension-system-count
422

    
423
    if (stream_num < 128)
424
        asf->stream_bitrates[stream_num] = leak_rate;
425

    
426
    for (i=0; i<stream_ct; i++){
427
        get_le16(pb);
428
        ext_len = get_le16(pb);
429
        url_fseek(pb, ext_len, SEEK_CUR);
430
    }
431

    
432
    for (i=0; i<payload_ext_ct; i++){
433
        ff_get_guid(pb, &g);
434
        ext_d=get_le16(pb);
435
        ext_len=get_le32(pb);
436
        url_fseek(pb, ext_len, SEEK_CUR);
437
    }
438

    
439
    return 0;
440
}
441

    
442
static int asf_read_content_desc(AVFormatContext *s, int64_t size)
443
{
444
    ByteIOContext *pb = s->pb;
445
    int len1, len2, len3, len4, len5;
446

    
447
    len1 = get_le16(pb);
448
    len2 = get_le16(pb);
449
    len3 = get_le16(pb);
450
    len4 = get_le16(pb);
451
    len5 = get_le16(pb);
452
    get_tag(s, "title"    , 0, len1);
453
    get_tag(s, "author"   , 0, len2);
454
    get_tag(s, "copyright", 0, len3);
455
    get_tag(s, "comment"  , 0, len4);
456
    url_fskip(pb, len5);
457

    
458
    return 0;
459
}
460

    
461
static int asf_read_ext_content_desc(AVFormatContext *s, int64_t size)
462
{
463
    ByteIOContext *pb = s->pb;
464
    ASFContext *asf = s->priv_data;
465
    int desc_count, i, ret;
466

    
467
    desc_count = get_le16(pb);
468
    for(i=0;i<desc_count;i++) {
469
        int name_len,value_type,value_len;
470
        char name[1024];
471

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

    
493
    return 0;
494
}
495

    
496
static int asf_read_language_list(AVFormatContext *s, int64_t size)
497
{
498
    ByteIOContext *pb = s->pb;
499
    ASFContext *asf = s->priv_data;
500
    int j, ret;
501
    int stream_count = get_le16(pb);
502
    for(j = 0; j < stream_count; j++) {
503
        char lang[6];
504
        unsigned int lang_len = get_byte(pb);
505
        if ((ret = avio_get_str16le(pb, lang_len, lang, sizeof(lang))) < lang_len)
506
            url_fskip(pb, lang_len - ret);
507
        if (j < 128)
508
            av_strlcpy(asf->stream_languages[j], lang, sizeof(*asf->stream_languages));
509
    }
510

    
511
    return 0;
512
}
513

    
514
static int asf_read_metadata(AVFormatContext *s, int64_t size)
515
{
516
    ByteIOContext *pb = s->pb;
517
    ASFContext *asf = s->priv_data;
518
    int n, stream_num, name_len, value_len, value_type, value_num;
519
    int ret, i;
520
    n = get_le16(pb);
521

    
522
    for(i=0;i<n;i++) {
523
        char name[1024];
524

    
525
        get_le16(pb); //lang_list_index
526
        stream_num= get_le16(pb);
527
        name_len=   get_le16(pb);
528
        value_type= get_le16(pb);
529
        value_len=  get_le32(pb);
530

    
531
        if ((ret = avio_get_str16le(pb, name_len, name, sizeof(name))) < name_len)
532
            url_fskip(pb, name_len - ret);
533
        //av_log(s, AV_LOG_ERROR, "%d %d %d %d %d <%s>\n", i, stream_num, name_len, value_type, value_len, name);
534
        value_num= get_le16(pb);//we should use get_value() here but it does not work 2 is le16 here but le32 elsewhere
535
        url_fskip(pb, value_len - 2);
536

    
537
        if(stream_num<128){
538
            if     (!strcmp(name, "AspectRatioX")) asf->dar[stream_num].num= value_num;
539
            else if(!strcmp(name, "AspectRatioY")) asf->dar[stream_num].den= value_num;
540
        }
541
    }
542

    
543
    return 0;
544
}
545

    
546
static int asf_read_marker(AVFormatContext *s, int64_t size)
547
{
548
    ByteIOContext *pb = s->pb;
549
    int i, count, name_len, ret;
550
    char name[1024];
551

    
552
    get_le64(pb);            // reserved 16 bytes
553
    get_le64(pb);            // ...
554
    count = get_le32(pb);    // markers count
555
    get_le16(pb);            // reserved 2 bytes
556
    name_len = get_le16(pb); // name length
557
    for(i=0;i<name_len;i++){
558
        get_byte(pb); // skip the name
559
    }
560

    
561
    for(i=0;i<count;i++){
562
        int64_t pres_time;
563
        int name_len;
564

    
565
        get_le64(pb);             // offset, 8 bytes
566
        pres_time = get_le64(pb); // presentation time
567
        get_le16(pb);             // entry length
568
        get_le32(pb);             // send time
569
        get_le32(pb);             // flags
570
        name_len = get_le32(pb);  // name length
571
        if ((ret = avio_get_str16le(pb, name_len * 2, name, sizeof(name))) < name_len)
572
            url_fskip(pb, name_len - ret);
573
        ff_new_chapter(s, i, (AVRational){1, 10000000}, pres_time, AV_NOPTS_VALUE, name );
574
    }
575

    
576
    return 0;
577
}
578

    
579
static int asf_read_header(AVFormatContext *s, AVFormatParameters *ap)
580
{
581
    ASFContext *asf = s->priv_data;
582
    ff_asf_guid g;
583
    ByteIOContext *pb = s->pb;
584
    int i;
585
    int64_t gsize;
586

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

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

    
666

    
667
    for(i=0; i<128; i++){
668
        int stream_num= asf->asfid2avid[i];
669
        if(stream_num>=0){
670
            AVStream *st = s->streams[stream_num];
671
            if (!st->codec->bit_rate)
672
                st->codec->bit_rate = asf->stream_bitrates[i];
673
            if (asf->dar[i].num > 0 && asf->dar[i].den > 0){
674
                av_reduce(&st->sample_aspect_ratio.num,
675
                          &st->sample_aspect_ratio.den,
676
                          asf->dar[i].num, asf->dar[i].den, INT_MAX);
677
            } 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.
678
                av_reduce(&st->sample_aspect_ratio.num,
679
                          &st->sample_aspect_ratio.den,
680
                          asf->dar[0].num, asf->dar[0].den, INT_MAX);
681

    
682
//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);
683

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

    
697
    ff_metadata_conv(&s->metadata, NULL, ff_asf_metadata_conv);
698

    
699
    return 0;
700
}
701

    
702
#define DO_2BITS(bits, var, defval) \
703
    switch (bits & 3) \
704
    { \
705
    case 3: var = get_le32(pb); rsize += 4; break; \
706
    case 2: var = get_le16(pb); rsize += 2; break; \
707
    case 1: var = get_byte(pb); rsize++; break; \
708
    default: var = defval; break; \
709
    }
710

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

    
724
    // if we do not know packet size, allow skipping up to 32 kB
725
    off= 32768;
726
    if (s->packet_size > 0)
727
        off= (url_ftell(pb) - s->data_offset) % s->packet_size + 3;
728

    
729
    c=d=e=-1;
730
    while(off-- > 0){
731
        c=d; d=e;
732
        e= get_byte(pb);
733
        if(c == 0x82 && !d && !e)
734
            break;
735
    }
736

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

    
762
    asf->packet_flags    = c;
763
    asf->packet_property = d;
764

    
765
    DO_2BITS(asf->packet_flags >> 5, packet_length, s->packet_size);
766
    DO_2BITS(asf->packet_flags >> 1, padsize, 0); // sequence ignored
767
    DO_2BITS(asf->packet_flags >> 3, padsize, 0); // padding length
768

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

    
779
    asf->packet_timestamp = get_le32(pb);
780
    get_le16(pb); /* duration */
781
    // rsize has at least 11 bytes which have to be present
782

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

    
798
/**
799
 *
800
 * @return <0 if error
801
 */
802
static int asf_read_frame_header(AVFormatContext *s, ByteIOContext *pb){
803
    ASFContext *asf = s->priv_data;
804
    int rsize = 1;
805
    int num = get_byte(pb);
806
    int64_t ts0, ts1;
807

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

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

    
869
    return 0;
870
}
871

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

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

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

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

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

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

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

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

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

    
1064
static int asf_read_packet(AVFormatContext *s, AVPacket *pkt)
1065
{
1066
    ASFContext *asf = s->priv_data;
1067

    
1068
    for (;;) {
1069
        int ret;
1070

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

    
1079
    return 0;
1080
}
1081

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

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

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

    
1119
static int asf_read_close(AVFormatContext *s)
1120
{
1121
    int i;
1122

    
1123
    asf_reset_header(s);
1124
    for(i=0;i<s->nb_streams;i++) {
1125
        AVStream *st = s->streams[i];
1126
        av_free(st->codec->palctrl);
1127
    }
1128
    return 0;
1129
}
1130

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

    
1140
    for(i=0; i<s->nb_streams; i++){
1141
        start_pos[i]= pos;
1142
    }
1143

    
1144
    if (s->packet_size > 0)
1145
        pos= (pos+s->packet_size-1-s->data_offset)/s->packet_size*s->packet_size+ s->data_offset;
1146
    *ppos= pos;
1147
    url_fseek(s->pb, pos, SEEK_SET);
1148

    
1149
//printf("asf_read_pts\n");
1150
    asf_reset_header(s);
1151
    for(;;){
1152
        if (av_read_frame(s, pkt) < 0){
1153
            av_log(s, AV_LOG_INFO, "asf_read_pts failed\n");
1154
            return AV_NOPTS_VALUE;
1155
        }
1156

    
1157
        pts= pkt->pts;
1158

    
1159
        av_free_packet(pkt);
1160
        if(pkt->flags&AV_PKT_FLAG_KEY){
1161
            i= pkt->stream_index;
1162

    
1163
            asf_st= s->streams[i]->priv_data;
1164

    
1165
//            assert((asf_st->packet_pos - s->data_offset) % s->packet_size == 0);
1166
            pos= asf_st->packet_pos;
1167

    
1168
            av_add_index_entry(s->streams[i], pos, pts, pkt->size, pos - start_pos[i] + 1, AVINDEX_KEYFRAME);
1169
            start_pos[i]= asf_st->packet_pos + 1;
1170

    
1171
            if(pkt->stream_index == stream_index)
1172
               break;
1173
        }
1174
    }
1175

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

    
1179
    return pts;
1180
}
1181

    
1182
static void asf_build_simple_index(AVFormatContext *s, int stream_index)
1183
{
1184
    ff_asf_guid g;
1185
    ASFContext *asf = s->priv_data;
1186
    int64_t current_pos= url_ftell(s->pb);
1187
    int i;
1188

    
1189
    url_fseek(s->pb, asf->data_object_offset + asf->data_object_size, SEEK_SET);
1190
    ff_get_guid(s->pb, &g);
1191

    
1192
    /* the data object can be followed by other top-level objects,
1193
       skip them until the simple index object is reached */
1194
    while (ff_guidcmp(&g, &index_guid)) {
1195
        int64_t gsize= get_le64(s->pb);
1196
        if (gsize < 24 || url_feof(s->pb)) {
1197
            url_fseek(s->pb, current_pos, SEEK_SET);
1198
            return;
1199
        }
1200
        url_fseek(s->pb, gsize-24, SEEK_CUR);
1201
        ff_get_guid(s->pb, &g);
1202
    }
1203

    
1204
    {
1205
        int64_t itime, last_pos=-1;
1206
        int pct, ict;
1207
        int64_t av_unused gsize= get_le64(s->pb);
1208
        ff_get_guid(s->pb, &g);
1209
        itime=get_le64(s->pb);
1210
        pct=get_le32(s->pb);
1211
        ict=get_le32(s->pb);
1212
        av_log(s, AV_LOG_DEBUG, "itime:0x%"PRIx64", pct:%d, ict:%d\n",itime,pct,ict);
1213

    
1214
        for (i=0;i<ict;i++){
1215
            int pktnum=get_le32(s->pb);
1216
            int pktct =get_le16(s->pb);
1217
            int64_t pos      = s->data_offset + s->packet_size*(int64_t)pktnum;
1218
            int64_t index_pts= av_rescale(itime, i, 10000);
1219

    
1220
            if(pos != last_pos){
1221
            av_log(s, AV_LOG_DEBUG, "pktnum:%d, pktct:%d\n", pktnum, pktct);
1222
            av_add_index_entry(s->streams[stream_index], pos, index_pts, s->packet_size, 0, AVINDEX_KEYFRAME);
1223
            last_pos=pos;
1224
            }
1225
        }
1226
        asf->index_read= 1;
1227
    }
1228
    url_fseek(s->pb, current_pos, SEEK_SET);
1229
}
1230

    
1231
static int asf_read_seek(AVFormatContext *s, int stream_index, int64_t pts, int flags)
1232
{
1233
    ASFContext *asf = s->priv_data;
1234
    AVStream *st = s->streams[stream_index];
1235
    int64_t pos;
1236
    int index;
1237

    
1238
    if (s->packet_size <= 0)
1239
        return -1;
1240

    
1241
    /* Try using the protocol's read_seek if available */
1242
    if(s->pb) {
1243
        int ret = av_url_read_fseek(s->pb, stream_index, pts, flags);
1244
        if(ret >= 0)
1245
            asf_reset_header(s);
1246
        if (ret != AVERROR(ENOSYS))
1247
            return ret;
1248
    }
1249

    
1250
    if (!asf->index_read)
1251
        asf_build_simple_index(s, stream_index);
1252

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

    
1261
        /* find the position */
1262
        pos = st->index_entries[index].pos;
1263

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

    
1285
        /* do the seek */
1286
        av_log(s, AV_LOG_DEBUG, "SEEKTO: %"PRId64"\n", pos);
1287
        url_fseek(s->pb, pos, SEEK_SET);
1288
    }
1289
    asf_reset_header(s);
1290
    return 0;
1291
}
1292

    
1293
AVInputFormat ff_asf_demuxer = {
1294
    "asf",
1295
    NULL_IF_CONFIG_SMALL("ASF format"),
1296
    sizeof(ASFContext),
1297
    asf_probe,
1298
    asf_read_header,
1299
    asf_read_packet,
1300
    asf_read_close,
1301
    asf_read_seek,
1302
    asf_read_pts,
1303
};