Statistics
| Branch: | Revision:

ffmpeg / libavformat / asfdec.c @ 2912e87a

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 Libav.
6
 *
7
 * Libav 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
 * Libav 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 Libav; 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(AVIOContext *s, ff_asf_guid *g)
136
{
137
    assert(sizeof(*g) == 16);
138
    avio_read(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(AVIOContext *pb, int type){
151
    switch(type){
152
        case 2: return avio_rl32(pb);
153
        case 3: return avio_rl32(pb);
154
        case 4: return avio_rl64(pb);
155
        case 5: return avio_rl16(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 = avio_tell(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
    if (*value)
182
        av_metadata_set2(&s->metadata, key, value, 0);
183
finish:
184
    av_freep(&value);
185
    avio_seek(s->pb, off + len, SEEK_SET);
186
}
187

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

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

    
207
    return 0;
208
}
209

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

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

    
229
    pos1 = avio_tell(pb);
230

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

    
242
    asf_st->stream_language_index = 128; // invalid stream index means no language info
243

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

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

    
274
    avio_rl32(pb);
275

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

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

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

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

    
394
    return 0;
395
}
396

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

    
406
    avio_rl64(pb); // starttime
407
    avio_rl64(pb); // endtime
408
    leak_rate = avio_rl32(pb); // leak-datarate
409
    avio_rl32(pb); // bucket-datasize
410
    avio_rl32(pb); // init-bucket-fullness
411
    avio_rl32(pb); // alt-leak-datarate
412
    avio_rl32(pb); // alt-bucket-datasize
413
    avio_rl32(pb); // alt-init-bucket-fullness
414
    avio_rl32(pb); // max-object-size
415
    avio_rl32(pb); // flags (reliable,seekable,no_cleanpoints?,resend-live-cleanpoints, rest of bits reserved)
416
    stream_num = avio_rl16(pb); // stream-num
417

    
418
    stream_languageid_index = avio_rl16(pb); // stream-language-id-index
419
    if (stream_num < 128)
420
        asf->streams[stream_num].stream_language_index = stream_languageid_index;
421

    
422
    avio_rl64(pb); // avg frametime in 100ns units
423
    stream_ct = avio_rl16(pb); //stream-name-count
424
    payload_ext_ct = avio_rl16(pb); //payload-extension-system-count
425

    
426
    if (stream_num < 128)
427
        asf->stream_bitrates[stream_num] = leak_rate;
428

    
429
    for (i=0; i<stream_ct; i++){
430
        avio_rl16(pb);
431
        ext_len = avio_rl16(pb);
432
        avio_skip(pb, ext_len);
433
    }
434

    
435
    for (i=0; i<payload_ext_ct; i++){
436
        ff_get_guid(pb, &g);
437
        ext_d=avio_rl16(pb);
438
        ext_len=avio_rl32(pb);
439
        avio_skip(pb, ext_len);
440
    }
441

    
442
    return 0;
443
}
444

    
445
static int asf_read_content_desc(AVFormatContext *s, int64_t size)
446
{
447
    AVIOContext *pb = s->pb;
448
    int len1, len2, len3, len4, len5;
449

    
450
    len1 = avio_rl16(pb);
451
    len2 = avio_rl16(pb);
452
    len3 = avio_rl16(pb);
453
    len4 = avio_rl16(pb);
454
    len5 = avio_rl16(pb);
455
    get_tag(s, "title"    , 0, len1);
456
    get_tag(s, "author"   , 0, len2);
457
    get_tag(s, "copyright", 0, len3);
458
    get_tag(s, "comment"  , 0, len4);
459
    avio_skip(pb, len5);
460

    
461
    return 0;
462
}
463

    
464
static int asf_read_ext_content_desc(AVFormatContext *s, int64_t size)
465
{
466
    AVIOContext *pb = s->pb;
467
    ASFContext *asf = s->priv_data;
468
    int desc_count, i, ret;
469

    
470
    desc_count = avio_rl16(pb);
471
    for(i=0;i<desc_count;i++) {
472
        int name_len,value_type,value_len;
473
        char name[1024];
474

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

    
496
    return 0;
497
}
498

    
499
static int asf_read_language_list(AVFormatContext *s, int64_t size)
500
{
501
    AVIOContext *pb = s->pb;
502
    ASFContext *asf = s->priv_data;
503
    int j, ret;
504
    int stream_count = avio_rl16(pb);
505
    for(j = 0; j < stream_count; j++) {
506
        char lang[6];
507
        unsigned int lang_len = avio_r8(pb);
508
        if ((ret = avio_get_str16le(pb, lang_len, lang, sizeof(lang))) < lang_len)
509
            avio_skip(pb, lang_len - ret);
510
        if (j < 128)
511
            av_strlcpy(asf->stream_languages[j], lang, sizeof(*asf->stream_languages));
512
    }
513

    
514
    return 0;
515
}
516

    
517
static int asf_read_metadata(AVFormatContext *s, int64_t size)
518
{
519
    AVIOContext *pb = s->pb;
520
    ASFContext *asf = s->priv_data;
521
    int n, stream_num, name_len, value_len, value_type, value_num;
522
    int ret, i;
523
    n = avio_rl16(pb);
524

    
525
    for(i=0;i<n;i++) {
526
        char name[1024];
527

    
528
        avio_rl16(pb); //lang_list_index
529
        stream_num= avio_rl16(pb);
530
        name_len=   avio_rl16(pb);
531
        value_type= avio_rl16(pb);
532
        value_len=  avio_rl32(pb);
533

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

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

    
546
    return 0;
547
}
548

    
549
static int asf_read_marker(AVFormatContext *s, int64_t size)
550
{
551
    AVIOContext *pb = s->pb;
552
    int i, count, name_len, ret;
553
    char name[1024];
554

    
555
    avio_rl64(pb);            // reserved 16 bytes
556
    avio_rl64(pb);            // ...
557
    count = avio_rl32(pb);    // markers count
558
    avio_rl16(pb);            // reserved 2 bytes
559
    name_len = avio_rl16(pb); // name length
560
    for(i=0;i<name_len;i++){
561
        avio_r8(pb); // skip the name
562
    }
563

    
564
    for(i=0;i<count;i++){
565
        int64_t pres_time;
566
        int name_len;
567

    
568
        avio_rl64(pb);             // offset, 8 bytes
569
        pres_time = avio_rl64(pb); // presentation time
570
        avio_rl16(pb);             // entry length
571
        avio_rl32(pb);             // send time
572
        avio_rl32(pb);             // flags
573
        name_len = avio_rl32(pb);  // name length
574
        if ((ret = avio_get_str16le(pb, name_len * 2, name, sizeof(name))) < name_len)
575
            avio_skip(pb, name_len - ret);
576
        ff_new_chapter(s, i, (AVRational){1, 10000000}, pres_time, AV_NOPTS_VALUE, name );
577
    }
578

    
579
    return 0;
580
}
581

    
582
static int asf_read_header(AVFormatContext *s, AVFormatParameters *ap)
583
{
584
    ASFContext *asf = s->priv_data;
585
    ff_asf_guid g;
586
    AVIOContext *pb = s->pb;
587
    int i;
588
    int64_t gsize;
589

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

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

    
669

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

    
685
//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);
686

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

    
700
    ff_metadata_conv(&s->metadata, NULL, ff_asf_metadata_conv);
701

    
702
    return 0;
703
}
704

    
705
#define DO_2BITS(bits, var, defval) \
706
    switch (bits & 3) \
707
    { \
708
    case 3: var = avio_rl32(pb); rsize += 4; break; \
709
    case 2: var = avio_rl16(pb); rsize += 2; break; \
710
    case 1: var = avio_r8(pb);   rsize++; break; \
711
    default: var = defval; break; \
712
    }
713

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

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

    
732
    c=d=e=-1;
733
    while(off-- > 0){
734
        c=d; d=e;
735
        e= avio_r8(pb);
736
        if(c == 0x82 && !d && !e)
737
            break;
738
    }
739

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

    
765
    asf->packet_flags    = c;
766
    asf->packet_property = d;
767

    
768
    DO_2BITS(asf->packet_flags >> 5, packet_length, s->packet_size);
769
    DO_2BITS(asf->packet_flags >> 1, padsize, 0); // sequence ignored
770
    DO_2BITS(asf->packet_flags >> 3, padsize, 0); // padding length
771

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

    
782
    asf->packet_timestamp = avio_rl32(pb);
783
    avio_rl16(pb); /* duration */
784
    // rsize has at least 11 bytes which have to be present
785

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

    
801
/**
802
 *
803
 * @return <0 if error
804
 */
805
static int asf_read_frame_header(AVFormatContext *s, AVIOContext *pb){
806
    ASFContext *asf = s->priv_data;
807
    int rsize = 1;
808
    int num = avio_r8(pb);
809
    int64_t ts0, ts1;
810

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

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

    
872
    return 0;
873
}
874

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

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

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

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

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

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

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

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

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

    
1067
static int asf_read_packet(AVFormatContext *s, AVPacket *pkt)
1068
{
1069
    ASFContext *asf = s->priv_data;
1070

    
1071
    for (;;) {
1072
        int ret;
1073

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

    
1082
    return 0;
1083
}
1084

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

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

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

    
1122
static int asf_read_close(AVFormatContext *s)
1123
{
1124
    int i;
1125

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

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

    
1143
    for(i=0; i<s->nb_streams; i++){
1144
        start_pos[i]= pos;
1145
    }
1146

    
1147
    if (s->packet_size > 0)
1148
        pos= (pos+s->packet_size-1-s->data_offset)/s->packet_size*s->packet_size+ s->data_offset;
1149
    *ppos= pos;
1150
    avio_seek(s->pb, pos, SEEK_SET);
1151

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

    
1160
        pts= pkt->pts;
1161

    
1162
        av_free_packet(pkt);
1163
        if(pkt->flags&AV_PKT_FLAG_KEY){
1164
            i= pkt->stream_index;
1165

    
1166
            asf_st= s->streams[i]->priv_data;
1167

    
1168
//            assert((asf_st->packet_pos - s->data_offset) % s->packet_size == 0);
1169
            pos= asf_st->packet_pos;
1170

    
1171
            av_add_index_entry(s->streams[i], pos, pts, pkt->size, pos - start_pos[i] + 1, AVINDEX_KEYFRAME);
1172
            start_pos[i]= asf_st->packet_pos + 1;
1173

    
1174
            if(pkt->stream_index == stream_index)
1175
               break;
1176
        }
1177
    }
1178

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

    
1182
    return pts;
1183
}
1184

    
1185
static void asf_build_simple_index(AVFormatContext *s, int stream_index)
1186
{
1187
    ff_asf_guid g;
1188
    ASFContext *asf = s->priv_data;
1189
    int64_t current_pos= avio_tell(s->pb);
1190
    int i;
1191

    
1192
    avio_seek(s->pb, asf->data_object_offset + asf->data_object_size, SEEK_SET);
1193
    ff_get_guid(s->pb, &g);
1194

    
1195
    /* the data object can be followed by other top-level objects,
1196
       skip them until the simple index object is reached */
1197
    while (ff_guidcmp(&g, &index_guid)) {
1198
        int64_t gsize= avio_rl64(s->pb);
1199
        if (gsize < 24 || s->pb->eof_reached) {
1200
            avio_seek(s->pb, current_pos, SEEK_SET);
1201
            return;
1202
        }
1203
        avio_skip(s->pb, gsize-24);
1204
        ff_get_guid(s->pb, &g);
1205
    }
1206

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

    
1217
        for (i=0;i<ict;i++){
1218
            int pktnum=avio_rl32(s->pb);
1219
            int pktct =avio_rl16(s->pb);
1220
            int64_t pos      = s->data_offset + s->packet_size*(int64_t)pktnum;
1221
            int64_t index_pts= av_rescale(itime, i, 10000);
1222

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

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

    
1241
    if (s->packet_size <= 0)
1242
        return -1;
1243

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

    
1253
    if (!asf->index_read)
1254
        asf_build_simple_index(s, stream_index);
1255

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

    
1264
        /* find the position */
1265
        pos = st->index_entries[index].pos;
1266

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

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

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