Statistics
| Branch: | Revision:

ffmpeg / libavformat / asfdec.c @ f59d8ff8

History | View | Annotate | Download (46.1 KB)

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

    
22
//#define DEBUG
23

    
24
#include "libavutil/common.h"
25
#include "libavutil/avstring.h"
26
#include "libavcodec/mpegaudio.h"
27
#include "avformat.h"
28
#include "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 = url_ftell(s->pb);
164

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

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

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

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

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

    
206
    return 0;
207
}
208

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

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

    
228
    pos1 = url_ftell(pb);
229

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

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

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

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

    
272
    avio_rl32(pb);
273

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

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

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

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

    
392
    return 0;
393
}
394

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

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

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

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

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

    
427
    for (i=0; i<stream_ct; i++){
428
        avio_rl16(pb);
429
        ext_len = avio_rl16(pb);
430
        avio_seek(pb, ext_len, SEEK_CUR);
431
    }
432

    
433
    for (i=0; i<payload_ext_ct; i++){
434
        ff_get_guid(pb, &g);
435
        ext_d=avio_rl16(pb);
436
        ext_len=avio_rl32(pb);
437
        avio_seek(pb, ext_len, SEEK_CUR);
438
    }
439

    
440
    return 0;
441
}
442

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

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

    
459
    return 0;
460
}
461

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

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

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

    
494
    return 0;
495
}
496

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

    
512
    return 0;
513
}
514

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

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

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

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

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

    
544
    return 0;
545
}
546

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

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

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

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

    
577
    return 0;
578
}
579

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

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

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

    
667

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

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

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

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

    
700
    return 0;
701
}
702

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

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

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

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

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

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

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

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

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

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

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

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

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

    
870
    return 0;
871
}
872

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

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

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

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

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

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

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

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

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

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

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

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

    
1080
    return 0;
1081
}
1082

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

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

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

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

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

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

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

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

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

    
1158
        pts= pkt->pts;
1159

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

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

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

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

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

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

    
1180
    return pts;
1181
}
1182

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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