Statistics
| Branch: | Revision:

ffmpeg / libavformat / asfdec.c @ f9d6b13a

History | View | Annotate | Download (47.2 KB)

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

    
22
//#define DEBUG
23

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

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

    
35
#undef NDEBUG
36
#include <assert.h>
37

    
38
#define ASF_MAX_STREAMS 127
39
#define FRAME_HEADER_SIZE 17
40
// Fix Me! FRAME_HEADER_SIZE may be different.
41

    
42
static const ff_asf_guid index_guid = {
43
    0x90, 0x08, 0x00, 0x33, 0xb1, 0xe5, 0xcf, 0x11, 0x89, 0xf4, 0x00, 0xa0, 0xc9, 0x03, 0x49, 0xcb
44
};
45

    
46
static const ff_asf_guid stream_bitrate_guid = { /* (http://get.to/sdp) */
47
    0xce, 0x75, 0xf8, 0x7b, 0x8d, 0x46, 0xd1, 0x11, 0x8d, 0x82, 0x00, 0x60, 0x97, 0xc9, 0xa2, 0xb2
48
};
49
/**********************************/
50
/* decoding */
51

    
52
int ff_guidcmp(const void *g1, const void *g2)
53
{
54
    return memcmp(g1, g2, sizeof(ff_asf_guid));
55
}
56

    
57
#ifdef DEBUG
58
#define PRINT_IF_GUID(g,cmp) \
59
if (!ff_guidcmp(g, &cmp)) \
60
    dprintf(NULL, "(GUID: %s) ", #cmp)
61

    
62
static void print_guid(const ff_asf_guid *g)
63
{
64
    int i;
65
    PRINT_IF_GUID(g, ff_asf_header);
66
    else PRINT_IF_GUID(g, ff_asf_file_header);
67
    else PRINT_IF_GUID(g, ff_asf_stream_header);
68
    else PRINT_IF_GUID(g, ff_asf_audio_stream);
69
    else PRINT_IF_GUID(g, ff_asf_audio_conceal_none);
70
    else PRINT_IF_GUID(g, ff_asf_video_stream);
71
    else PRINT_IF_GUID(g, ff_asf_video_conceal_none);
72
    else PRINT_IF_GUID(g, ff_asf_command_stream);
73
    else PRINT_IF_GUID(g, ff_asf_comment_header);
74
    else PRINT_IF_GUID(g, ff_asf_codec_comment_header);
75
    else PRINT_IF_GUID(g, ff_asf_codec_comment1_header);
76
    else PRINT_IF_GUID(g, ff_asf_data_header);
77
    else PRINT_IF_GUID(g, index_guid);
78
    else PRINT_IF_GUID(g, ff_asf_head1_guid);
79
    else PRINT_IF_GUID(g, ff_asf_head2_guid);
80
    else PRINT_IF_GUID(g, ff_asf_my_guid);
81
    else PRINT_IF_GUID(g, ff_asf_ext_stream_header);
82
    else PRINT_IF_GUID(g, ff_asf_extended_content_header);
83
    else PRINT_IF_GUID(g, ff_asf_ext_stream_embed_stream_header);
84
    else PRINT_IF_GUID(g, ff_asf_ext_stream_audio_stream);
85
    else PRINT_IF_GUID(g, ff_asf_metadata_header);
86
    else PRINT_IF_GUID(g, ff_asf_marker_header);
87
    else PRINT_IF_GUID(g, stream_bitrate_guid);
88
    else PRINT_IF_GUID(g, ff_asf_language_guid);
89
    else
90
        dprintf(NULL, "(GUID: unknown) ");
91
    for(i=0;i<16;i++)
92
        dprintf(NULL, " 0x%02x,", (*g)[i]);
93
    dprintf(NULL, "}\n");
94
}
95
#undef PRINT_IF_GUID
96
#else
97
#define print_guid(g)
98
#endif
99

    
100
void ff_get_guid(ByteIOContext *s, ff_asf_guid *g)
101
{
102
    assert(sizeof(*g) == 16);
103
    get_buffer(s, *g, sizeof(*g));
104
}
105

    
106
#if 0
107
static void get_str16(ByteIOContext *pb, char *buf, int buf_size)
108
{
109
    int len, c;
110
    char *q;
111

112
    len = get_le16(pb);
113
    q = buf;
114
    while (len > 0) {
115
        c = get_le16(pb);
116
        if ((q - buf) < buf_size - 1)
117
            *q++ = c;
118
        len--;
119
    }
120
    *q = '\0';
121
}
122
#endif
123

    
124
static int asf_probe(AVProbeData *pd)
125
{
126
    /* check file header */
127
    if (!ff_guidcmp(pd->buf, &ff_asf_header))
128
        return AVPROBE_SCORE_MAX;
129
    else
130
        return 0;
131
}
132

    
133
static int get_value(ByteIOContext *pb, int type){
134
    switch(type){
135
        case 2: return get_le32(pb);
136
        case 3: return get_le32(pb);
137
        case 4: return get_le64(pb);
138
        case 5: return get_le16(pb);
139
        default:return INT_MIN;
140
    }
141
}
142

    
143
static void get_tag(AVFormatContext *s, const char *key, int type, int len)
144
{
145
    char *value;
146

    
147
    if ((unsigned)len >= (UINT_MAX - 1)/2)
148
        return;
149

    
150
    value = av_malloc(2*len+1);
151
    if (!value)
152
        return;
153

    
154
    if (type == 0) {         // UTF16-LE
155
        avio_get_str16le(s->pb, len, value, 2*len + 1);
156
    } else if (type > 1 && type <= 5) {  // boolean or DWORD or QWORD or WORD
157
        uint64_t num = get_value(s->pb, type);
158
        snprintf(value, len, "%"PRIu64, num);
159
    } else {
160
        url_fskip(s->pb, len);
161
        av_freep(&value);
162
        av_log(s, AV_LOG_DEBUG, "Unsupported value type %d in tag %s.\n", type, key);
163
        return;
164
    }
165
    av_metadata_set2(&s->metadata, key, value, 0);
166
    av_freep(&value);
167
}
168

    
169
static int asf_read_header(AVFormatContext *s, AVFormatParameters *ap)
170
{
171
    ASFContext *asf = s->priv_data;
172
    ff_asf_guid g;
173
    ByteIOContext *pb = s->pb;
174
    AVStream *st;
175
    ASFStream *asf_st;
176
    int size, i;
177
    int64_t gsize;
178
    AVRational dar[128];
179
    uint32_t bitrate[128];
180

    
181
    memset(dar, 0, sizeof(dar));
182
    memset(bitrate, 0, sizeof(bitrate));
183

    
184
    ff_get_guid(pb, &g);
185
    if (ff_guidcmp(&g, &ff_asf_header))
186
        return -1;
187
    get_le64(pb);
188
    get_le32(pb);
189
    get_byte(pb);
190
    get_byte(pb);
191
    memset(&asf->asfid2avid, -1, sizeof(asf->asfid2avid));
192
    for(;;) {
193
        uint64_t gpos= url_ftell(pb);
194
        int ret;
195
        ff_get_guid(pb, &g);
196
        gsize = get_le64(pb);
197
        dprintf(s, "%08"PRIx64": ", gpos);
198
        print_guid(&g);
199
        dprintf(s, "  size=0x%"PRIx64"\n", gsize);
200
        if (!ff_guidcmp(&g, &ff_asf_data_header)) {
201
            asf->data_object_offset = url_ftell(pb);
202
            // if not streaming, gsize is not unlimited (how?), and there is enough space in the file..
203
            if (!(asf->hdr.flags & 0x01) && gsize >= 100) {
204
                asf->data_object_size = gsize - 24;
205
            } else {
206
                asf->data_object_size = (uint64_t)-1;
207
            }
208
            break;
209
        }
210
        if (gsize < 24)
211
            return -1;
212
        if (!ff_guidcmp(&g, &ff_asf_file_header)) {
213
            ff_get_guid(pb, &asf->hdr.guid);
214
            asf->hdr.file_size          = get_le64(pb);
215
            asf->hdr.create_time        = get_le64(pb);
216
            asf->nb_packets             = get_le64(pb);
217
            asf->hdr.play_time          = get_le64(pb);
218
            asf->hdr.send_time          = get_le64(pb);
219
            asf->hdr.preroll            = get_le32(pb);
220
            asf->hdr.ignore             = get_le32(pb);
221
            asf->hdr.flags              = get_le32(pb);
222
            asf->hdr.min_pktsize        = get_le32(pb);
223
            asf->hdr.max_pktsize        = get_le32(pb);
224
            asf->hdr.max_bitrate        = get_le32(pb);
225
            s->packet_size = asf->hdr.max_pktsize;
226
        } else if (!ff_guidcmp(&g, &ff_asf_stream_header)) {
227
            enum AVMediaType type;
228
            int type_specific_size, sizeX;
229
            uint64_t total_size;
230
            unsigned int tag1;
231
            int64_t pos1, pos2, start_time;
232
            int test_for_ext_stream_audio, is_dvr_ms_audio=0;
233

    
234
            if (s->nb_streams == ASF_MAX_STREAMS) {
235
                av_log(s, AV_LOG_ERROR, "too many streams\n");
236
                return AVERROR(EINVAL);
237
            }
238

    
239
            pos1 = url_ftell(pb);
240

    
241
            st = av_new_stream(s, 0);
242
            if (!st)
243
                return AVERROR(ENOMEM);
244
            av_set_pts_info(st, 32, 1, 1000); /* 32 bit pts in ms */
245
            asf_st = av_mallocz(sizeof(ASFStream));
246
            if (!asf_st)
247
                return AVERROR(ENOMEM);
248
            st->priv_data = asf_st;
249
            start_time = asf->hdr.preroll;
250

    
251
            asf_st->stream_language_index = 128; // invalid stream index means no language info
252

    
253
            if(!(asf->hdr.flags & 0x01)) { // if we aren't streaming...
254
                st->duration = asf->hdr.play_time /
255
                    (10000000 / 1000) - start_time;
256
            }
257
            ff_get_guid(pb, &g);
258

    
259
            test_for_ext_stream_audio = 0;
260
            if (!ff_guidcmp(&g, &ff_asf_audio_stream)) {
261
                type = AVMEDIA_TYPE_AUDIO;
262
            } else if (!ff_guidcmp(&g, &ff_asf_video_stream)) {
263
                type = AVMEDIA_TYPE_VIDEO;
264
            } else if (!ff_guidcmp(&g, &ff_asf_jfif_media)) {
265
                type = AVMEDIA_TYPE_VIDEO;
266
                st->codec->codec_id = CODEC_ID_MJPEG;
267
            } else if (!ff_guidcmp(&g, &ff_asf_command_stream)) {
268
                type = AVMEDIA_TYPE_DATA;
269
            } else if (!ff_guidcmp(&g, &ff_asf_ext_stream_embed_stream_header)) {
270
                test_for_ext_stream_audio = 1;
271
                type = AVMEDIA_TYPE_UNKNOWN;
272
            } else {
273
                return -1;
274
            }
275
            ff_get_guid(pb, &g);
276
            total_size = get_le64(pb);
277
            type_specific_size = get_le32(pb);
278
            get_le32(pb);
279
            st->id = get_le16(pb) & 0x7f; /* stream id */
280
            // mapping of asf ID to AV stream ID;
281
            asf->asfid2avid[st->id] = s->nb_streams - 1;
282

    
283
            get_le32(pb);
284

    
285
            if (test_for_ext_stream_audio) {
286
                ff_get_guid(pb, &g);
287
                if (!ff_guidcmp(&g, &ff_asf_ext_stream_audio_stream)) {
288
                    type = AVMEDIA_TYPE_AUDIO;
289
                    is_dvr_ms_audio=1;
290
                    ff_get_guid(pb, &g);
291
                    get_le32(pb);
292
                    get_le32(pb);
293
                    get_le32(pb);
294
                    ff_get_guid(pb, &g);
295
                    get_le32(pb);
296
                }
297
            }
298

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

    
372
                /* Extract palette from extradata if bpp <= 8 */
373
                /* This code assumes that extradata contains only palette */
374
                /* This is true for all paletted codecs implemented in ffmpeg */
375
                if (st->codec->extradata_size && (st->codec->bits_per_coded_sample <= 8)) {
376
                    st->codec->palctrl = av_mallocz(sizeof(AVPaletteControl));
377
#if HAVE_BIGENDIAN
378
                    for (i = 0; i < FFMIN(st->codec->extradata_size, AVPALETTE_SIZE)/4; i++)
379
                        st->codec->palctrl->palette[i] = av_bswap32(((uint32_t*)st->codec->extradata)[i]);
380
#else
381
                    memcpy(st->codec->palctrl->palette, st->codec->extradata,
382
                           FFMIN(st->codec->extradata_size, AVPALETTE_SIZE));
383
#endif
384
                    st->codec->palctrl->palette_changed = 1;
385
                }
386

    
387
                st->codec->codec_tag = tag1;
388
                st->codec->codec_id = ff_codec_get_id(ff_codec_bmp_tags, tag1);
389
                if(tag1 == MKTAG('D', 'V', 'R', ' ')){
390
                    st->need_parsing = AVSTREAM_PARSE_FULL;
391
                    // 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
392
                    st->codec->width  =
393
                    st->codec->height = 0;
394
                    av_freep(&st->codec->extradata);
395
                    st->codec->extradata_size=0;
396
                }
397
                if(st->codec->codec_id == CODEC_ID_H264)
398
                    st->need_parsing = AVSTREAM_PARSE_FULL_ONCE;
399
            }
400
            pos2 = url_ftell(pb);
401
            url_fskip(pb, gsize - (pos2 - pos1 + 24));
402
        } else if (!ff_guidcmp(&g, &ff_asf_comment_header)) {
403
            int len1, len2, len3, len4, len5;
404

    
405
            len1 = get_le16(pb);
406
            len2 = get_le16(pb);
407
            len3 = get_le16(pb);
408
            len4 = get_le16(pb);
409
            len5 = get_le16(pb);
410
            get_tag(s, "title"    , 0, len1);
411
            get_tag(s, "author"   , 0, len2);
412
            get_tag(s, "copyright", 0, len3);
413
            get_tag(s, "comment"  , 0, len4);
414
            url_fskip(pb, len5);
415
        } else if (!ff_guidcmp(&g, &stream_bitrate_guid)) {
416
            int stream_count = get_le16(pb);
417
            int j;
418

    
419
//            av_log(s, AV_LOG_ERROR, "stream bitrate properties\n");
420
//            av_log(s, AV_LOG_ERROR, "streams %d\n", streams);
421
            for(j = 0; j < stream_count; j++) {
422
                int flags, bitrate, stream_id;
423

    
424
                flags= get_le16(pb);
425
                bitrate= get_le32(pb);
426
                stream_id= (flags & 0x7f);
427
//                av_log(s, AV_LOG_ERROR, "flags: 0x%x stream id %d, bitrate %d\n", flags, stream_id, bitrate);
428
                asf->stream_bitrates[stream_id]= bitrate;
429
            }
430
        } else if (!ff_guidcmp(&g, &ff_asf_language_guid)) {
431
            int j;
432
            int stream_count = get_le16(pb);
433
            for(j = 0; j < stream_count; j++) {
434
                char lang[6];
435
                unsigned int lang_len = get_byte(pb);
436
                if ((ret = avio_get_str16le(pb, lang_len, lang, sizeof(lang))) < lang_len)
437
                    url_fskip(pb, lang_len - ret);
438
                if (j < 128)
439
                    av_strlcpy(asf->stream_languages[j], lang, sizeof(*asf->stream_languages));
440
            }
441
        } else if (!ff_guidcmp(&g, &ff_asf_extended_content_header)) {
442
            int desc_count, i;
443

    
444
            desc_count = get_le16(pb);
445
            for(i=0;i<desc_count;i++) {
446
                    int name_len,value_type,value_len;
447
                    char name[1024];
448

    
449
                    name_len = get_le16(pb);
450
                    if (name_len%2)     // must be even, broken lavf versions wrote len-1
451
                        name_len += 1;
452
                    if ((ret = avio_get_str16le(pb, name_len, name, sizeof(name))) < name_len)
453
                        url_fskip(pb, name_len - ret);
454
                    value_type = get_le16(pb);
455
                    value_len  = get_le16(pb);
456
                    if (!value_type && value_len%2)
457
                        value_len += 1;
458
                    /**
459
                     * My sample has that stream set to 0 maybe that mean the container.
460
                     * Asf stream count start at 1. I am using 0 to the container value since it's unused
461
                     */
462
                    if (!strcmp(name, "AspectRatioX")){
463
                        dar[0].num= get_value(s->pb, value_type);
464
                    } else if(!strcmp(name, "AspectRatioY")){
465
                        dar[0].den= get_value(s->pb, value_type);
466
                    } else
467
                        get_tag(s, name, value_type, value_len);
468
            }
469
        } else if (!ff_guidcmp(&g, &ff_asf_metadata_header)) {
470
            int n, stream_num, name_len, value_len, value_type, value_num;
471
            n = get_le16(pb);
472

    
473
            for(i=0;i<n;i++) {
474
                char name[1024];
475

    
476
                get_le16(pb); //lang_list_index
477
                stream_num= get_le16(pb);
478
                name_len=   get_le16(pb);
479
                value_type= get_le16(pb);
480
                value_len=  get_le32(pb);
481

    
482
                if ((ret = avio_get_str16le(pb, name_len, name, sizeof(name))) < name_len)
483
                    url_fskip(pb, name_len - ret);
484
//av_log(s, AV_LOG_ERROR, "%d %d %d %d %d <%s>\n", i, stream_num, name_len, value_type, value_len, name);
485
                value_num= get_le16(pb);//we should use get_value() here but it does not work 2 is le16 here but le32 elsewhere
486
                url_fskip(pb, value_len - 2);
487

    
488
                if(stream_num<128){
489
                    if     (!strcmp(name, "AspectRatioX")) dar[stream_num].num= value_num;
490
                    else if(!strcmp(name, "AspectRatioY")) dar[stream_num].den= value_num;
491
                }
492
            }
493
        } else if (!ff_guidcmp(&g, &ff_asf_ext_stream_header)) {
494
            int ext_len, payload_ext_ct, stream_ct;
495
            uint32_t ext_d, leak_rate, stream_num;
496
            unsigned int stream_languageid_index;
497

    
498
            get_le64(pb); // starttime
499
            get_le64(pb); // endtime
500
            leak_rate = get_le32(pb); // leak-datarate
501
            get_le32(pb); // bucket-datasize
502
            get_le32(pb); // init-bucket-fullness
503
            get_le32(pb); // alt-leak-datarate
504
            get_le32(pb); // alt-bucket-datasize
505
            get_le32(pb); // alt-init-bucket-fullness
506
            get_le32(pb); // max-object-size
507
            get_le32(pb); // flags (reliable,seekable,no_cleanpoints?,resend-live-cleanpoints, rest of bits reserved)
508
            stream_num = get_le16(pb); // stream-num
509

    
510
            stream_languageid_index = get_le16(pb); // stream-language-id-index
511
            if (stream_num < 128)
512
                asf->streams[stream_num].stream_language_index = stream_languageid_index;
513

    
514
            get_le64(pb); // avg frametime in 100ns units
515
            stream_ct = get_le16(pb); //stream-name-count
516
            payload_ext_ct = get_le16(pb); //payload-extension-system-count
517

    
518
            if (stream_num < 128)
519
                bitrate[stream_num] = leak_rate;
520

    
521
            for (i=0; i<stream_ct; i++){
522
                get_le16(pb);
523
                ext_len = get_le16(pb);
524
                url_fseek(pb, ext_len, SEEK_CUR);
525
            }
526

    
527
            for (i=0; i<payload_ext_ct; i++){
528
                ff_get_guid(pb, &g);
529
                ext_d=get_le16(pb);
530
                ext_len=get_le32(pb);
531
                url_fseek(pb, ext_len, SEEK_CUR);
532
            }
533

    
534
            // there could be a optional stream properties object to follow
535
            // if so the next iteration will pick it up
536
            continue;
537
        } else if (!ff_guidcmp(&g, &ff_asf_head1_guid)) {
538
            int v1, v2;
539
            ff_get_guid(pb, &g);
540
            v1 = get_le32(pb);
541
            v2 = get_le16(pb);
542
            continue;
543
        } else if (!ff_guidcmp(&g, &ff_asf_marker_header)) {
544
            int i, count, name_len;
545
            char name[1024];
546

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

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

    
560
                get_le64(pb);             // offset, 8 bytes
561
                pres_time = get_le64(pb); // presentation time
562
                get_le16(pb);             // entry length
563
                get_le32(pb);             // send time
564
                get_le32(pb);             // flags
565
                name_len = get_le32(pb);  // name length
566
                if ((ret = avio_get_str16le(pb, name_len * 2, name, sizeof(name))) < name_len)
567
                    url_fskip(pb, name_len - ret);
568
                ff_new_chapter(s, i, (AVRational){1, 10000000}, pres_time, AV_NOPTS_VALUE, name );
569
            }
570
#if 0
571
        } else if (!ff_guidcmp(&g, &ff_asf_codec_comment_header)) {
572
            int len, v1, n, num;
573
            char str[256], *q;
574
            char tag[16];
575

576
            ff_get_guid(pb, &g);
577
            print_guid(&g);
578

579
            n = get_le32(pb);
580
            for(i=0;i<n;i++) {
581
                num = get_le16(pb); /* stream number */
582
                get_str16(pb, str, sizeof(str));
583
                get_str16(pb, str, sizeof(str));
584
                len = get_le16(pb);
585
                q = tag;
586
                while (len > 0) {
587
                    v1 = get_byte(pb);
588
                    if ((q - tag) < sizeof(tag) - 1)
589
                        *q++ = v1;
590
                    len--;
591
                }
592
                *q = '\0';
593
            }
594
#endif
595
        } else if (url_feof(pb)) {
596
            return -1;
597
        } else {
598
            if (!s->keylen) {
599
                if (!ff_guidcmp(&g, &ff_asf_content_encryption)) {
600
                    av_log(s, AV_LOG_WARNING, "DRM protected stream detected, decoding will likely fail!\n");
601
                } else if (!ff_guidcmp(&g, &ff_asf_ext_content_encryption)) {
602
                    av_log(s, AV_LOG_WARNING, "Ext DRM protected stream detected, decoding will likely fail!\n");
603
                } else if (!ff_guidcmp(&g, &ff_asf_digital_signature)) {
604
                    av_log(s, AV_LOG_WARNING, "Digital signature detected, decoding will likely fail!\n");
605
                }
606
            }
607
        }
608
        if(url_ftell(pb) != gpos + gsize)
609
            av_log(s, AV_LOG_DEBUG, "gpos mismatch our pos=%"PRIu64", end=%"PRIu64"\n", url_ftell(pb)-gpos, gsize);
610
        url_fseek(pb, gpos + gsize, SEEK_SET);
611
    }
612
    ff_get_guid(pb, &g);
613
    get_le64(pb);
614
    get_byte(pb);
615
    get_byte(pb);
616
    if (url_feof(pb))
617
        return -1;
618
    asf->data_offset = url_ftell(pb);
619
    asf->packet_size_left = 0;
620

    
621

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

    
637
//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);
638

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

    
652
    ff_metadata_conv(&s->metadata, NULL, ff_asf_metadata_conv);
653

    
654
    return 0;
655
}
656

    
657
#define DO_2BITS(bits, var, defval) \
658
    switch (bits & 3) \
659
    { \
660
    case 3: var = get_le32(pb); rsize += 4; break; \
661
    case 2: var = get_le16(pb); rsize += 2; break; \
662
    case 1: var = get_byte(pb); rsize++; break; \
663
    default: var = defval; break; \
664
    }
665

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

    
679
    // if we do not know packet size, allow skipping up to 32 kB
680
    off= 32768;
681
    if (s->packet_size > 0)
682
        off= (url_ftell(pb) - s->data_offset) % s->packet_size + 3;
683

    
684
    c=d=e=-1;
685
    while(off-- > 0){
686
        c=d; d=e;
687
        e= get_byte(pb);
688
        if(c == 0x82 && !d && !e)
689
            break;
690
    }
691

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

    
717
    asf->packet_flags    = c;
718
    asf->packet_property = d;
719

    
720
    DO_2BITS(asf->packet_flags >> 5, packet_length, s->packet_size);
721
    DO_2BITS(asf->packet_flags >> 1, padsize, 0); // sequence ignored
722
    DO_2BITS(asf->packet_flags >> 3, padsize, 0); // padding length
723

    
724
    //the following checks prevent overflows and infinite loops
725
    if(!packet_length || packet_length >= (1U<<29)){
726
        av_log(s, AV_LOG_ERROR, "invalid packet_length %d at:%"PRId64"\n", packet_length, url_ftell(pb));
727
        return -1;
728
    }
729
    if(padsize >= packet_length){
730
        av_log(s, AV_LOG_ERROR, "invalid padsize %d at:%"PRId64"\n", padsize, url_ftell(pb));
731
        return -1;
732
    }
733

    
734
    asf->packet_timestamp = get_le32(pb);
735
    get_le16(pb); /* duration */
736
    // rsize has at least 11 bytes which have to be present
737

    
738
    if (asf->packet_flags & 0x01) {
739
        asf->packet_segsizetype = get_byte(pb); rsize++;
740
        asf->packet_segments = asf->packet_segsizetype & 0x3f;
741
    } else {
742
        asf->packet_segments = 1;
743
        asf->packet_segsizetype = 0x80;
744
    }
745
    asf->packet_size_left = packet_length - padsize - rsize;
746
    if (packet_length < asf->hdr.min_pktsize)
747
        padsize += asf->hdr.min_pktsize - packet_length;
748
    asf->packet_padsize = padsize;
749
    dprintf(s, "packet: size=%d padsize=%d  left=%d\n", s->packet_size, asf->packet_padsize, asf->packet_size_left);
750
    return 0;
751
}
752

    
753
/**
754
 *
755
 * @return <0 if error
756
 */
757
static int asf_read_frame_header(AVFormatContext *s, ByteIOContext *pb){
758
    ASFContext *asf = s->priv_data;
759
    int rsize = 1;
760
    int num = get_byte(pb);
761
    int64_t ts0, ts1;
762

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

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

    
824
    return 0;
825
}
826

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

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

    
880
        if (asf->packet_replic_size == 1) {
881
            // frag_offset is here used as the beginning timestamp
882
            asf->packet_frag_timestamp = asf->packet_time_start;
883
            asf->packet_time_start += asf->packet_time_delta;
884
            asf->packet_obj_size = asf->packet_frag_size = get_byte(pb);
885
            asf->packet_size_left--;
886
            asf->packet_multi_size--;
887
            if (asf->packet_multi_size < asf->packet_obj_size)
888
            {
889
                asf->packet_time_start = 0;
890
                url_fskip(pb, asf->packet_multi_size);
891
                asf->packet_size_left -= asf->packet_multi_size;
892
                continue;
893
            }
894
            asf->packet_multi_size -= asf->packet_obj_size;
895
            //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);
896
        }
897
        if(   /*asf->packet_frag_size == asf->packet_obj_size*/
898
              asf_st->frag_offset + asf->packet_frag_size <= asf_st->pkt.size
899
           && asf_st->frag_offset + asf->packet_frag_size > asf->packet_obj_size){
900
            av_log(s, AV_LOG_INFO, "ignoring invalid packet_obj_size (%d %d %d %d)\n",
901
                asf_st->frag_offset, asf->packet_frag_size,
902
                asf->packet_obj_size, asf_st->pkt.size);
903
            asf->packet_obj_size= asf_st->pkt.size;
904
        }
905

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

    
929
        /* read data */
930
        //printf("READ PACKET s:%d  os:%d  o:%d,%d  l:%d   DATA:%p\n",
931
        //       s->packet_size, asf_st->pkt.size, asf->packet_frag_offset,
932
        //       asf_st->frag_offset, asf->packet_frag_size, asf_st->pkt.data);
933
        asf->packet_size_left -= asf->packet_frag_size;
934
        if (asf->packet_size_left < 0)
935
            continue;
936

    
937
        if(   asf->packet_frag_offset >= asf_st->pkt.size
938
           || asf->packet_frag_size > asf_st->pkt.size - asf->packet_frag_offset){
939
            av_log(s, AV_LOG_ERROR, "packet fragment position invalid %u,%u not in %u\n",
940
                asf->packet_frag_offset, asf->packet_frag_size, asf_st->pkt.size);
941
            continue;
942
        }
943

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

    
979
            /* return packet */
980
            if (asf_st->ds_span > 1) {
981
              if(asf_st->pkt.size != asf_st->ds_packet_size * asf_st->ds_span){
982
                    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);
983
              }else{
984
                /* packet descrambling */
985
                uint8_t *newdata = av_malloc(asf_st->pkt.size + FF_INPUT_BUFFER_PADDING_SIZE);
986
                if (newdata) {
987
                    int offset = 0;
988
                    memset(newdata + asf_st->pkt.size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
989
                    while (offset < asf_st->pkt.size) {
990
                        int off = offset / asf_st->ds_chunk_size;
991
                        int row = off / asf_st->ds_span;
992
                        int col = off % asf_st->ds_span;
993
                        int idx = row + col * asf_st->ds_packet_size / asf_st->ds_chunk_size;
994
                        //printf("off:%d  row:%d  col:%d  idx:%d\n", off, row, col, idx);
995

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

    
1019
static int asf_read_packet(AVFormatContext *s, AVPacket *pkt)
1020
{
1021
    ASFContext *asf = s->priv_data;
1022

    
1023
    for (;;) {
1024
        int ret;
1025

    
1026
        /* parse cached packets, if any */
1027
        if ((ret = ff_asf_parse_packet(s, s->pb, pkt)) <= 0)
1028
            return ret;
1029
        if ((ret = ff_asf_get_packet(s, s->pb)) < 0)
1030
            assert(asf->packet_size_left < FRAME_HEADER_SIZE || asf->packet_segments < 1);
1031
        asf->packet_time_start = 0;
1032
    }
1033

    
1034
    return 0;
1035
}
1036

    
1037
// Added to support seeking after packets have been read
1038
// If information is not reset, read_packet fails due to
1039
// leftover information from previous reads
1040
static void asf_reset_header(AVFormatContext *s)
1041
{
1042
    ASFContext *asf = s->priv_data;
1043
    ASFStream *asf_st;
1044
    int i;
1045

    
1046
    asf->packet_nb_frames = 0;
1047
    asf->packet_size_left = 0;
1048
    asf->packet_segments = 0;
1049
    asf->packet_flags = 0;
1050
    asf->packet_property = 0;
1051
    asf->packet_timestamp = 0;
1052
    asf->packet_segsizetype = 0;
1053
    asf->packet_segments = 0;
1054
    asf->packet_seq = 0;
1055
    asf->packet_replic_size = 0;
1056
    asf->packet_key_frame = 0;
1057
    asf->packet_padsize = 0;
1058
    asf->packet_frag_offset = 0;
1059
    asf->packet_frag_size = 0;
1060
    asf->packet_frag_timestamp = 0;
1061
    asf->packet_multi_size = 0;
1062
    asf->packet_obj_size = 0;
1063
    asf->packet_time_delta = 0;
1064
    asf->packet_time_start = 0;
1065

    
1066
    for(i=0; i<s->nb_streams; i++){
1067
        asf_st= s->streams[i]->priv_data;
1068
        av_free_packet(&asf_st->pkt);
1069
        asf_st->frag_offset=0;
1070
        asf_st->seq=0;
1071
    }
1072
    asf->asf_st= NULL;
1073
}
1074

    
1075
static int asf_read_close(AVFormatContext *s)
1076
{
1077
    int i;
1078

    
1079
    asf_reset_header(s);
1080
    for(i=0;i<s->nb_streams;i++) {
1081
        AVStream *st = s->streams[i];
1082
        av_free(st->codec->palctrl);
1083
    }
1084
    return 0;
1085
}
1086

    
1087
static int64_t asf_read_pts(AVFormatContext *s, int stream_index, int64_t *ppos, int64_t pos_limit)
1088
{
1089
    AVPacket pkt1, *pkt = &pkt1;
1090
    ASFStream *asf_st;
1091
    int64_t pts;
1092
    int64_t pos= *ppos;
1093
    int i;
1094
    int64_t start_pos[ASF_MAX_STREAMS];
1095

    
1096
    for(i=0; i<s->nb_streams; i++){
1097
        start_pos[i]= pos;
1098
    }
1099

    
1100
    if (s->packet_size > 0)
1101
        pos= (pos+s->packet_size-1-s->data_offset)/s->packet_size*s->packet_size+ s->data_offset;
1102
    *ppos= pos;
1103
    url_fseek(s->pb, pos, SEEK_SET);
1104

    
1105
//printf("asf_read_pts\n");
1106
    asf_reset_header(s);
1107
    for(;;){
1108
        if (av_read_frame(s, pkt) < 0){
1109
            av_log(s, AV_LOG_INFO, "asf_read_pts failed\n");
1110
            return AV_NOPTS_VALUE;
1111
        }
1112

    
1113
        pts= pkt->pts;
1114

    
1115
        av_free_packet(pkt);
1116
        if(pkt->flags&AV_PKT_FLAG_KEY){
1117
            i= pkt->stream_index;
1118

    
1119
            asf_st= s->streams[i]->priv_data;
1120

    
1121
//            assert((asf_st->packet_pos - s->data_offset) % s->packet_size == 0);
1122
            pos= asf_st->packet_pos;
1123

    
1124
            av_add_index_entry(s->streams[i], pos, pts, pkt->size, pos - start_pos[i] + 1, AVINDEX_KEYFRAME);
1125
            start_pos[i]= asf_st->packet_pos + 1;
1126

    
1127
            if(pkt->stream_index == stream_index)
1128
               break;
1129
        }
1130
    }
1131

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

    
1135
    return pts;
1136
}
1137

    
1138
static void asf_build_simple_index(AVFormatContext *s, int stream_index)
1139
{
1140
    ff_asf_guid g;
1141
    ASFContext *asf = s->priv_data;
1142
    int64_t current_pos= url_ftell(s->pb);
1143
    int i;
1144

    
1145
    url_fseek(s->pb, asf->data_object_offset + asf->data_object_size, SEEK_SET);
1146
    ff_get_guid(s->pb, &g);
1147

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

    
1160
    {
1161
        int64_t itime, last_pos=-1;
1162
        int pct, ict;
1163
        int64_t av_unused gsize= get_le64(s->pb);
1164
        ff_get_guid(s->pb, &g);
1165
        itime=get_le64(s->pb);
1166
        pct=get_le32(s->pb);
1167
        ict=get_le32(s->pb);
1168
        av_log(s, AV_LOG_DEBUG, "itime:0x%"PRIx64", pct:%d, ict:%d\n",itime,pct,ict);
1169

    
1170
        for (i=0;i<ict;i++){
1171
            int pktnum=get_le32(s->pb);
1172
            int pktct =get_le16(s->pb);
1173
            int64_t pos      = s->data_offset + s->packet_size*(int64_t)pktnum;
1174
            int64_t index_pts= av_rescale(itime, i, 10000);
1175

    
1176
            if(pos != last_pos){
1177
            av_log(s, AV_LOG_DEBUG, "pktnum:%d, pktct:%d\n", pktnum, pktct);
1178
            av_add_index_entry(s->streams[stream_index], pos, index_pts, s->packet_size, 0, AVINDEX_KEYFRAME);
1179
            last_pos=pos;
1180
            }
1181
        }
1182
        asf->index_read= 1;
1183
    }
1184
    url_fseek(s->pb, current_pos, SEEK_SET);
1185
}
1186

    
1187
static int asf_read_seek(AVFormatContext *s, int stream_index, int64_t pts, int flags)
1188
{
1189
    ASFContext *asf = s->priv_data;
1190
    AVStream *st = s->streams[stream_index];
1191
    int64_t pos;
1192
    int index;
1193

    
1194
    if (s->packet_size <= 0)
1195
        return -1;
1196

    
1197
    /* Try using the protocol's read_seek if available */
1198
    if(s->pb) {
1199
        int ret = av_url_read_fseek(s->pb, stream_index, pts, flags);
1200
        if(ret >= 0)
1201
            asf_reset_header(s);
1202
        if (ret != AVERROR(ENOSYS))
1203
            return ret;
1204
    }
1205

    
1206
    if (!asf->index_read)
1207
        asf_build_simple_index(s, stream_index);
1208

    
1209
    if(!(asf->index_read && st->index_entries)){
1210
        if(av_seek_frame_binary(s, stream_index, pts, flags)<0)
1211
            return -1;
1212
    }else{
1213
        index= av_index_search_timestamp(st, pts, flags);
1214
        if(index<0)
1215
            return -1;
1216

    
1217
        /* find the position */
1218
        pos = st->index_entries[index].pos;
1219

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

    
1241
        /* do the seek */
1242
        av_log(s, AV_LOG_DEBUG, "SEEKTO: %"PRId64"\n", pos);
1243
        url_fseek(s->pb, pos, SEEK_SET);
1244
    }
1245
    asf_reset_header(s);
1246
    return 0;
1247
}
1248

    
1249
AVInputFormat asf_demuxer = {
1250
    "asf",
1251
    NULL_IF_CONFIG_SMALL("ASF format"),
1252
    sizeof(ASFContext),
1253
    asf_probe,
1254
    asf_read_header,
1255
    asf_read_packet,
1256
    asf_read_close,
1257
    asf_read_seek,
1258
    asf_read_pts,
1259
};