Statistics
| Branch: | Revision:

ffmpeg / libavformat / asfdec.c @ bcedf2e5

History | View | Annotate | Download (46.1 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
typedef struct {
35
    int asfid2avid[128];                 ///< conversion table from asf ID 2 AVStream ID
36
    ASFStream streams[128];              ///< it's max number and it's not that big
37
    uint32_t stream_bitrates[128];       ///< max number of streams, bitrate for each (for streaming)
38
    AVRational dar[128];
39
    char stream_languages[128][6];       ///< max number of streams, language for each (RFC1766, e.g. en-US)
40
    /* non streamed additonnal info */
41
    /* packet filling */
42
    int packet_size_left;
43
    /* only for reading */
44
    uint64_t data_offset;                ///< beginning of the first data packet
45
    uint64_t data_object_offset;         ///< data object offset (excl. GUID & size)
46
    uint64_t data_object_size;           ///< size of the data object
47
    int index_read;
48

    
49
    ASFMainHeader hdr;
50

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

    
69
    int stream_index;
70

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

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

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

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

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

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

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

    
134
static int asf_probe(AVProbeData *pd)
135
{
136
    /* check file header */
137
    if (!ff_guidcmp(pd->buf, &ff_asf_header))
138
        return AVPROBE_SCORE_MAX;
139
    else
140
        return 0;
141
}
142

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

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

    
158
    if ((unsigned)len >= (UINT_MAX - 1)/2)
159
        return;
160

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

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

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

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

    
199
    return 0;
200
}
201

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

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

    
221
    pos1 = avio_tell(pb);
222

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

    
233
    asf_st->stream_language_index = 128; // invalid stream index means no language info
234

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

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

    
265
    avio_rl32(pb);
266

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

    
281
    st->codec->codec_type = type;
282
    if (type == AVMEDIA_TYPE_AUDIO) {
283
        int ret = ff_get_wav_header(pb, st->codec, type_specific_size);
284
        if (ret < 0)
285
            return ret;
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
#if HAVE_BIGENDIAN
361
            for (i = 0; i < FFMIN(st->codec->extradata_size, AVPALETTE_SIZE)/4; i++)
362
                asf_st->palette[i] = av_bswap32(((uint32_t*)st->codec->extradata)[i]);
363
#else
364
            memcpy(asf_st->palette, st->codec->extradata,
365
                   FFMIN(st->codec->extradata_size, AVPALETTE_SIZE));
366
#endif
367
            asf_st->palette_changed = 1;
368
        }
369

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

    
386
    return 0;
387
}
388

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

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

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

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

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

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

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

    
434
    return 0;
435
}
436

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

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

    
453
    return 0;
454
}
455

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

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

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

    
488
    return 0;
489
}
490

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

    
506
    return 0;
507
}
508

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

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

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

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

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

    
538
    return 0;
539
}
540

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

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

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

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

    
571
    return 0;
572
}
573

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

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

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

    
661

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

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

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

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

    
694
    return 0;
695
}
696

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

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

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

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

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

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

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

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

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

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

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

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

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

    
874
    return 0;
875
}
876

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

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

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

    
956
        if (   asf_st->pkt.size != asf->packet_obj_size
957
            || asf_st->frag_offset + asf->packet_frag_size > asf_st->pkt.size) { //FIXME is this condition sufficient?
958
            if(asf_st->pkt.data){
959
                av_log(s, AV_LOG_INFO, "freeing incomplete packet size %d, new %d\n", asf_st->pkt.size, asf->packet_obj_size);
960
                asf_st->frag_offset = 0;
961
                av_free_packet(&asf_st->pkt);
962
            }
963
            /* new packet */
964
            av_new_packet(&asf_st->pkt, asf->packet_obj_size);
965
            asf_st->seq = asf->packet_seq;
966
            asf_st->pkt.dts = asf->packet_frag_timestamp - asf->hdr.preroll;
967
            asf_st->pkt.stream_index = asf->stream_index;
968
            asf_st->pkt.pos =
969
            asf_st->packet_pos= asf->packet_pos;
970
            if (asf_st->pkt.data && asf_st->palette_changed) {
971
                uint8_t *pal;
972
                pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE,
973
                                              AVPALETTE_SIZE);
974
                if (!pal) {
975
                    av_log(s, AV_LOG_ERROR, "Cannot append palette to packet\n");
976
                } else {
977
                    memcpy(pal, asf_st->palette, AVPALETTE_SIZE);
978
                    asf_st->palette_changed = 0;
979
                }
980
            }
981
//printf("new packet: stream:%d key:%d packet_key:%d audio:%d size:%d\n",
982
//asf->stream_index, asf->packet_key_frame, asf_st->pkt.flags & AV_PKT_FLAG_KEY,
983
//s->streams[asf->stream_index]->codec->codec_type == AVMEDIA_TYPE_AUDIO, asf->packet_obj_size);
984
            if (s->streams[asf->stream_index]->codec->codec_type == AVMEDIA_TYPE_AUDIO)
985
                asf->packet_key_frame = 1;
986
            if (asf->packet_key_frame)
987
                asf_st->pkt.flags |= AV_PKT_FLAG_KEY;
988
        }
989

    
990
        /* read data */
991
        //printf("READ PACKET s:%d  os:%d  o:%d,%d  l:%d   DATA:%p\n",
992
        //       s->packet_size, asf_st->pkt.size, asf->packet_frag_offset,
993
        //       asf_st->frag_offset, asf->packet_frag_size, asf_st->pkt.data);
994
        asf->packet_size_left -= asf->packet_frag_size;
995
        if (asf->packet_size_left < 0)
996
            continue;
997

    
998
        if(   asf->packet_frag_offset >= asf_st->pkt.size
999
           || asf->packet_frag_size > asf_st->pkt.size - asf->packet_frag_offset){
1000
            av_log(s, AV_LOG_ERROR, "packet fragment position invalid %u,%u not in %u\n",
1001
                asf->packet_frag_offset, asf->packet_frag_size, asf_st->pkt.size);
1002
            continue;
1003
        }
1004

    
1005
        ret = avio_read(pb, asf_st->pkt.data + asf->packet_frag_offset,
1006
                         asf->packet_frag_size);
1007
        if (ret != asf->packet_frag_size) {
1008
            if (ret < 0 || asf->packet_frag_offset + ret == 0)
1009
                return ret < 0 ? ret : AVERROR_EOF;
1010
            if (asf_st->ds_span > 1) {
1011
                // scrambling, we can either drop it completely or fill the remainder
1012
                // TODO: should we fill the whole packet instead of just the current
1013
                // fragment?
1014
                memset(asf_st->pkt.data + asf->packet_frag_offset + ret, 0,
1015
                       asf->packet_frag_size - ret);
1016
                ret = asf->packet_frag_size;
1017
            } else
1018
                // no scrambling, so we can return partial packets
1019
                av_shrink_packet(&asf_st->pkt, asf->packet_frag_offset + ret);
1020
        }
1021
        if (s->key && s->keylen == 20)
1022
            ff_asfcrypt_dec(s->key, asf_st->pkt.data + asf->packet_frag_offset,
1023
                            ret);
1024
        asf_st->frag_offset += ret;
1025
        /* test if whole packet is read */
1026
        if (asf_st->frag_offset == asf_st->pkt.size) {
1027
            //workaround for macroshit radio DVR-MS files
1028
            if(   s->streams[asf->stream_index]->codec->codec_id == CODEC_ID_MPEG2VIDEO
1029
               && asf_st->pkt.size > 100){
1030
                int i;
1031
                for(i=0; i<asf_st->pkt.size && !asf_st->pkt.data[i]; i++);
1032
                if(i == asf_st->pkt.size){
1033
                    av_log(s, AV_LOG_DEBUG, "discarding ms fart\n");
1034
                    asf_st->frag_offset = 0;
1035
                    av_free_packet(&asf_st->pkt);
1036
                    continue;
1037
                }
1038
            }
1039

    
1040
            /* return packet */
1041
            if (asf_st->ds_span > 1) {
1042
              if(asf_st->pkt.size != asf_st->ds_packet_size * asf_st->ds_span){
1043
                    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);
1044
              }else{
1045
                /* packet descrambling */
1046
                uint8_t *newdata = av_malloc(asf_st->pkt.size + FF_INPUT_BUFFER_PADDING_SIZE);
1047
                if (newdata) {
1048
                    int offset = 0;
1049
                    memset(newdata + asf_st->pkt.size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
1050
                    while (offset < asf_st->pkt.size) {
1051
                        int off = offset / asf_st->ds_chunk_size;
1052
                        int row = off / asf_st->ds_span;
1053
                        int col = off % asf_st->ds_span;
1054
                        int idx = row + col * asf_st->ds_packet_size / asf_st->ds_chunk_size;
1055
                        //printf("off:%d  row:%d  col:%d  idx:%d\n", off, row, col, idx);
1056

    
1057
                        assert(offset + asf_st->ds_chunk_size <= asf_st->pkt.size);
1058
                        assert(idx+1 <= asf_st->pkt.size / asf_st->ds_chunk_size);
1059
                        memcpy(newdata + offset,
1060
                               asf_st->pkt.data + idx * asf_st->ds_chunk_size,
1061
                               asf_st->ds_chunk_size);
1062
                        offset += asf_st->ds_chunk_size;
1063
                    }
1064
                    av_free(asf_st->pkt.data);
1065
                    asf_st->pkt.data = newdata;
1066
                }
1067
              }
1068
            }
1069
            asf_st->frag_offset = 0;
1070
            *pkt= asf_st->pkt;
1071
            //printf("packet %d %d\n", asf_st->pkt.size, asf->packet_frag_size);
1072
            asf_st->pkt.size = 0;
1073
            asf_st->pkt.data = 0;
1074
            break; // packet completed
1075
        }
1076
    }
1077
    return 0;
1078
}
1079

    
1080
static int asf_read_packet(AVFormatContext *s, AVPacket *pkt)
1081
{
1082
    ASFContext *asf = s->priv_data;
1083

    
1084
    for (;;) {
1085
        int ret;
1086

    
1087
        /* parse cached packets, if any */
1088
        if ((ret = ff_asf_parse_packet(s, s->pb, pkt)) <= 0)
1089
            return ret;
1090
        if ((ret = ff_asf_get_packet(s, s->pb)) < 0)
1091
            assert(asf->packet_size_left < FRAME_HEADER_SIZE || asf->packet_segments < 1);
1092
        asf->packet_time_start = 0;
1093
    }
1094

    
1095
    return 0;
1096
}
1097

    
1098
// Added to support seeking after packets have been read
1099
// If information is not reset, read_packet fails due to
1100
// leftover information from previous reads
1101
static void asf_reset_header(AVFormatContext *s)
1102
{
1103
    ASFContext *asf = s->priv_data;
1104
    ASFStream *asf_st;
1105
    int i;
1106

    
1107
    asf->packet_size_left = 0;
1108
    asf->packet_segments = 0;
1109
    asf->packet_flags = 0;
1110
    asf->packet_property = 0;
1111
    asf->packet_timestamp = 0;
1112
    asf->packet_segsizetype = 0;
1113
    asf->packet_segments = 0;
1114
    asf->packet_seq = 0;
1115
    asf->packet_replic_size = 0;
1116
    asf->packet_key_frame = 0;
1117
    asf->packet_padsize = 0;
1118
    asf->packet_frag_offset = 0;
1119
    asf->packet_frag_size = 0;
1120
    asf->packet_frag_timestamp = 0;
1121
    asf->packet_multi_size = 0;
1122
    asf->packet_obj_size = 0;
1123
    asf->packet_time_delta = 0;
1124
    asf->packet_time_start = 0;
1125

    
1126
    for(i=0; i<s->nb_streams; i++){
1127
        asf_st= s->streams[i]->priv_data;
1128
        av_free_packet(&asf_st->pkt);
1129
        asf_st->frag_offset=0;
1130
        asf_st->seq=0;
1131
    }
1132
    asf->asf_st= NULL;
1133
}
1134

    
1135
static int asf_read_close(AVFormatContext *s)
1136
{
1137
    asf_reset_header(s);
1138

    
1139
    return 0;
1140
}
1141

    
1142
static int64_t asf_read_pts(AVFormatContext *s, int stream_index, int64_t *ppos, int64_t pos_limit)
1143
{
1144
    AVPacket pkt1, *pkt = &pkt1;
1145
    ASFStream *asf_st;
1146
    int64_t pts;
1147
    int64_t pos= *ppos;
1148
    int i;
1149
    int64_t start_pos[ASF_MAX_STREAMS];
1150

    
1151
    for(i=0; i<s->nb_streams; i++){
1152
        start_pos[i]= pos;
1153
    }
1154

    
1155
    if (s->packet_size > 0)
1156
        pos= (pos+s->packet_size-1-s->data_offset)/s->packet_size*s->packet_size+ s->data_offset;
1157
    *ppos= pos;
1158
    avio_seek(s->pb, pos, SEEK_SET);
1159

    
1160
//printf("asf_read_pts\n");
1161
    asf_reset_header(s);
1162
    for(;;){
1163
        if (av_read_frame(s, pkt) < 0){
1164
            av_log(s, AV_LOG_INFO, "asf_read_pts failed\n");
1165
            return AV_NOPTS_VALUE;
1166
        }
1167

    
1168
        pts= pkt->pts;
1169

    
1170
        av_free_packet(pkt);
1171
        if(pkt->flags&AV_PKT_FLAG_KEY){
1172
            i= pkt->stream_index;
1173

    
1174
            asf_st= s->streams[i]->priv_data;
1175

    
1176
//            assert((asf_st->packet_pos - s->data_offset) % s->packet_size == 0);
1177
            pos= asf_st->packet_pos;
1178

    
1179
            av_add_index_entry(s->streams[i], pos, pts, pkt->size, pos - start_pos[i] + 1, AVINDEX_KEYFRAME);
1180
            start_pos[i]= asf_st->packet_pos + 1;
1181

    
1182
            if(pkt->stream_index == stream_index)
1183
               break;
1184
        }
1185
    }
1186

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

    
1190
    return pts;
1191
}
1192

    
1193
static void asf_build_simple_index(AVFormatContext *s, int stream_index)
1194
{
1195
    ff_asf_guid g;
1196
    ASFContext *asf = s->priv_data;
1197
    int64_t current_pos= avio_tell(s->pb);
1198
    int i;
1199

    
1200
    avio_seek(s->pb, asf->data_object_offset + asf->data_object_size, SEEK_SET);
1201
    ff_get_guid(s->pb, &g);
1202

    
1203
    /* the data object can be followed by other top-level objects,
1204
       skip them until the simple index object is reached */
1205
    while (ff_guidcmp(&g, &index_guid)) {
1206
        int64_t gsize= avio_rl64(s->pb);
1207
        if (gsize < 24 || url_feof(s->pb)) {
1208
            avio_seek(s->pb, current_pos, SEEK_SET);
1209
            return;
1210
        }
1211
        avio_skip(s->pb, gsize-24);
1212
        ff_get_guid(s->pb, &g);
1213
    }
1214

    
1215
    {
1216
        int64_t itime, last_pos=-1;
1217
        int pct, ict;
1218
        int64_t av_unused gsize= avio_rl64(s->pb);
1219
        ff_get_guid(s->pb, &g);
1220
        itime=avio_rl64(s->pb);
1221
        pct=avio_rl32(s->pb);
1222
        ict=avio_rl32(s->pb);
1223
        av_log(s, AV_LOG_DEBUG, "itime:0x%"PRIx64", pct:%d, ict:%d\n",itime,pct,ict);
1224

    
1225
        for (i=0;i<ict;i++){
1226
            int pktnum=avio_rl32(s->pb);
1227
            int pktct =avio_rl16(s->pb);
1228
            int64_t pos      = s->data_offset + s->packet_size*(int64_t)pktnum;
1229
            int64_t index_pts= FFMAX(av_rescale(itime, i, 10000) - asf->hdr.preroll, 0);
1230

    
1231
            if(pos != last_pos){
1232
            av_log(s, AV_LOG_DEBUG, "pktnum:%d, pktct:%d  pts: %"PRId64"\n", pktnum, pktct, index_pts);
1233
            av_add_index_entry(s->streams[stream_index], pos, index_pts, s->packet_size, 0, AVINDEX_KEYFRAME);
1234
            last_pos=pos;
1235
            }
1236
        }
1237
        asf->index_read= 1;
1238
    }
1239
    avio_seek(s->pb, current_pos, SEEK_SET);
1240
}
1241

    
1242
static int asf_read_seek(AVFormatContext *s, int stream_index, int64_t pts, int flags)
1243
{
1244
    ASFContext *asf = s->priv_data;
1245
    AVStream *st = s->streams[stream_index];
1246
    int64_t pos;
1247
    int index;
1248

    
1249
    if (s->packet_size <= 0)
1250
        return -1;
1251

    
1252
    /* Try using the protocol's read_seek if available */
1253
    if(s->pb) {
1254
        int ret = avio_seek_time(s->pb, stream_index, pts, flags);
1255
        if(ret >= 0)
1256
            asf_reset_header(s);
1257
        if (ret != AVERROR(ENOSYS))
1258
            return ret;
1259
    }
1260

    
1261
    if (!asf->index_read)
1262
        asf_build_simple_index(s, stream_index);
1263

    
1264
    if(!(asf->index_read && st->index_entries)){
1265
        if(av_seek_frame_binary(s, stream_index, pts, flags)<0)
1266
            return -1;
1267
    }else{
1268
        index= av_index_search_timestamp(st, pts, flags);
1269
        if(index<0)
1270
            return -1;
1271

    
1272
        /* find the position */
1273
        pos = st->index_entries[index].pos;
1274

    
1275
        /* do the seek */
1276
        av_log(s, AV_LOG_DEBUG, "SEEKTO: %"PRId64"\n", pos);
1277
        avio_seek(s->pb, pos, SEEK_SET);
1278
    }
1279
    asf_reset_header(s);
1280
    return 0;
1281
}
1282

    
1283
AVInputFormat ff_asf_demuxer = {
1284
    "asf",
1285
    NULL_IF_CONFIG_SMALL("ASF format"),
1286
    sizeof(ASFContext),
1287
    asf_probe,
1288
    asf_read_header,
1289
    asf_read_packet,
1290
    asf_read_close,
1291
    asf_read_seek,
1292
    asf_read_pts,
1293
};