]> git.sesse.net Git - ffmpeg/blob - libavformat/asfdec.c
lavf: replace avio_seek(SEEK_CUR) with avio_skip where it makes sense
[ffmpeg] / libavformat / asfdec.c
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 = avio_tell(s->pb);
164
165     if ((unsigned)len >= (UINT_MAX - 1)/2)
166         return;
167
168     value = av_malloc(2*len+1);
169     if (!value)
170         goto finish;
171
172     if (type == 0) {         // UTF16-LE
173         avio_get_str16le(s->pb, len, value, 2*len + 1);
174     } else if (type > 1 && type <= 5) {  // boolean or DWORD or QWORD or WORD
175         uint64_t num = get_value(s->pb, type);
176         snprintf(value, len, "%"PRIu64, num);
177     } else {
178         av_log(s, AV_LOG_DEBUG, "Unsupported value type %d in tag %s.\n", type, key);
179         goto finish;
180     }
181     if (*value)
182         av_metadata_set2(&s->metadata, key, value, 0);
183 finish:
184     av_freep(&value);
185     avio_seek(s->pb, off + len, SEEK_SET);
186 }
187
188 static int asf_read_file_properties(AVFormatContext *s, int64_t size)
189 {
190     ASFContext *asf = s->priv_data;
191     AVIOContext *pb = s->pb;
192
193     ff_get_guid(pb, &asf->hdr.guid);
194     asf->hdr.file_size          = avio_rl64(pb);
195     asf->hdr.create_time        = avio_rl64(pb);
196     avio_rl64(pb);                               /* number of packets */
197     asf->hdr.play_time          = avio_rl64(pb);
198     asf->hdr.send_time          = avio_rl64(pb);
199     asf->hdr.preroll            = avio_rl32(pb);
200     asf->hdr.ignore             = avio_rl32(pb);
201     asf->hdr.flags              = avio_rl32(pb);
202     asf->hdr.min_pktsize        = avio_rl32(pb);
203     asf->hdr.max_pktsize        = avio_rl32(pb);
204     asf->hdr.max_bitrate        = avio_rl32(pb);
205     s->packet_size = asf->hdr.max_pktsize;
206
207     return 0;
208 }
209
210 static int asf_read_stream_properties(AVFormatContext *s, int64_t size)
211 {
212     ASFContext *asf = s->priv_data;
213     AVIOContext *pb = s->pb;
214     AVStream *st;
215     ASFStream *asf_st;
216     ff_asf_guid g;
217     enum AVMediaType type;
218     int type_specific_size, sizeX;
219     uint64_t total_size;
220     unsigned int tag1;
221     int64_t pos1, pos2, start_time;
222     int test_for_ext_stream_audio, is_dvr_ms_audio=0;
223
224     if (s->nb_streams == ASF_MAX_STREAMS) {
225         av_log(s, AV_LOG_ERROR, "too many streams\n");
226         return AVERROR(EINVAL);
227     }
228
229     pos1 = avio_tell(pb);
230
231     st = av_new_stream(s, 0);
232     if (!st)
233         return AVERROR(ENOMEM);
234     av_set_pts_info(st, 32, 1, 1000); /* 32 bit pts in ms */
235     asf_st = av_mallocz(sizeof(ASFStream));
236     if (!asf_st)
237         return AVERROR(ENOMEM);
238     st->priv_data = asf_st;
239     start_time = asf->hdr.preroll;
240
241     asf_st->stream_language_index = 128; // invalid stream index means no language info
242
243     if(!(asf->hdr.flags & 0x01)) { // if we aren't streaming...
244         st->duration = asf->hdr.play_time /
245             (10000000 / 1000) - start_time;
246     }
247     ff_get_guid(pb, &g);
248
249     test_for_ext_stream_audio = 0;
250     if (!ff_guidcmp(&g, &ff_asf_audio_stream)) {
251         type = AVMEDIA_TYPE_AUDIO;
252     } else if (!ff_guidcmp(&g, &ff_asf_video_stream)) {
253         type = AVMEDIA_TYPE_VIDEO;
254     } else if (!ff_guidcmp(&g, &ff_asf_jfif_media)) {
255         type = AVMEDIA_TYPE_VIDEO;
256         st->codec->codec_id = CODEC_ID_MJPEG;
257     } else if (!ff_guidcmp(&g, &ff_asf_command_stream)) {
258         type = AVMEDIA_TYPE_DATA;
259     } else if (!ff_guidcmp(&g, &ff_asf_ext_stream_embed_stream_header)) {
260         test_for_ext_stream_audio = 1;
261         type = AVMEDIA_TYPE_UNKNOWN;
262     } else {
263         return -1;
264     }
265     ff_get_guid(pb, &g);
266     total_size = avio_rl64(pb);
267     type_specific_size = avio_rl32(pb);
268     avio_rl32(pb);
269     st->id = avio_rl16(pb) & 0x7f; /* stream id */
270     // mapping of asf ID to AV stream ID;
271     asf->asfid2avid[st->id] = s->nb_streams - 1;
272
273     avio_rl32(pb);
274
275     if (test_for_ext_stream_audio) {
276         ff_get_guid(pb, &g);
277         if (!ff_guidcmp(&g, &ff_asf_ext_stream_audio_stream)) {
278             type = AVMEDIA_TYPE_AUDIO;
279             is_dvr_ms_audio=1;
280             ff_get_guid(pb, &g);
281             avio_rl32(pb);
282             avio_rl32(pb);
283             avio_rl32(pb);
284             ff_get_guid(pb, &g);
285             avio_rl32(pb);
286         }
287     }
288
289     st->codec->codec_type = type;
290     if (type == AVMEDIA_TYPE_AUDIO) {
291         ff_get_wav_header(pb, st->codec, type_specific_size);
292         if (is_dvr_ms_audio) {
293             // codec_id and codec_tag are unreliable in dvr_ms
294             // files. Set them later by probing stream.
295             st->codec->codec_id = CODEC_ID_PROBE;
296             st->codec->codec_tag = 0;
297         }
298         if (st->codec->codec_id == CODEC_ID_AAC) {
299             st->need_parsing = AVSTREAM_PARSE_NONE;
300         } else {
301             st->need_parsing = AVSTREAM_PARSE_FULL;
302         }
303         /* We have to init the frame size at some point .... */
304         pos2 = avio_tell(pb);
305         if (size >= (pos2 + 8 - pos1 + 24)) {
306             asf_st->ds_span = avio_r8(pb);
307             asf_st->ds_packet_size = avio_rl16(pb);
308             asf_st->ds_chunk_size = avio_rl16(pb);
309             avio_rl16(pb); //ds_data_size
310             avio_r8(pb);   //ds_silence_data
311         }
312         //printf("Descrambling: ps:%d cs:%d ds:%d s:%d  sd:%d\n",
313         //       asf_st->ds_packet_size, asf_st->ds_chunk_size,
314         //       asf_st->ds_data_size, asf_st->ds_span, asf_st->ds_silence_data);
315         if (asf_st->ds_span > 1) {
316             if (!asf_st->ds_chunk_size
317                     || (asf_st->ds_packet_size/asf_st->ds_chunk_size <= 1)
318                     || asf_st->ds_packet_size % asf_st->ds_chunk_size)
319                 asf_st->ds_span = 0; // disable descrambling
320         }
321         switch (st->codec->codec_id) {
322             case CODEC_ID_MP3:
323                 st->codec->frame_size = MPA_FRAME_SIZE;
324                 break;
325             case CODEC_ID_PCM_S16LE:
326             case CODEC_ID_PCM_S16BE:
327             case CODEC_ID_PCM_U16LE:
328             case CODEC_ID_PCM_U16BE:
329             case CODEC_ID_PCM_S8:
330             case CODEC_ID_PCM_U8:
331             case CODEC_ID_PCM_ALAW:
332             case CODEC_ID_PCM_MULAW:
333                 st->codec->frame_size = 1;
334                 break;
335             default:
336                 /* This is probably wrong, but it prevents a crash later */
337                 st->codec->frame_size = 1;
338                 break;
339         }
340     } else if (type == AVMEDIA_TYPE_VIDEO &&
341             size - (avio_tell(pb) - pos1 + 24) >= 51) {
342         avio_rl32(pb);
343         avio_rl32(pb);
344         avio_r8(pb);
345         avio_rl16(pb);        /* size */
346         sizeX= avio_rl32(pb); /* size */
347         st->codec->width = avio_rl32(pb);
348         st->codec->height = avio_rl32(pb);
349         /* not available for asf */
350         avio_rl16(pb); /* panes */
351         st->codec->bits_per_coded_sample = avio_rl16(pb); /* depth */
352         tag1 = avio_rl32(pb);
353         avio_skip(pb, 20);
354         //                av_log(s, AV_LOG_DEBUG, "size:%d tsize:%d sizeX:%d\n", size, total_size, sizeX);
355         if (sizeX > 40) {
356             st->codec->extradata_size = sizeX - 40;
357             st->codec->extradata = av_mallocz(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
358             avio_read(pb, st->codec->extradata, st->codec->extradata_size);
359         }
360
361         /* Extract palette from extradata if bpp <= 8 */
362         /* This code assumes that extradata contains only palette */
363         /* This is true for all paletted codecs implemented in ffmpeg */
364         if (st->codec->extradata_size && (st->codec->bits_per_coded_sample <= 8)) {
365             int av_unused i;
366             st->codec->palctrl = av_mallocz(sizeof(AVPaletteControl));
367 #if HAVE_BIGENDIAN
368             for (i = 0; i < FFMIN(st->codec->extradata_size, AVPALETTE_SIZE)/4; i++)
369                 st->codec->palctrl->palette[i] = av_bswap32(((uint32_t*)st->codec->extradata)[i]);
370 #else
371             memcpy(st->codec->palctrl->palette, st->codec->extradata,
372                     FFMIN(st->codec->extradata_size, AVPALETTE_SIZE));
373 #endif
374             st->codec->palctrl->palette_changed = 1;
375         }
376
377         st->codec->codec_tag = tag1;
378         st->codec->codec_id = ff_codec_get_id(ff_codec_bmp_tags, tag1);
379         if(tag1 == MKTAG('D', 'V', 'R', ' ')){
380             st->need_parsing = AVSTREAM_PARSE_FULL;
381             // 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
382             st->codec->width  =
383                 st->codec->height = 0;
384             av_freep(&st->codec->extradata);
385             st->codec->extradata_size=0;
386         }
387         if(st->codec->codec_id == CODEC_ID_H264)
388             st->need_parsing = AVSTREAM_PARSE_FULL_ONCE;
389     }
390     pos2 = avio_tell(pb);
391     avio_skip(pb, size - (pos2 - pos1 + 24));
392
393     return 0;
394 }
395
396 static int asf_read_ext_stream_properties(AVFormatContext *s, int64_t size)
397 {
398     ASFContext *asf = s->priv_data;
399     AVIOContext *pb = s->pb;
400     ff_asf_guid g;
401     int ext_len, payload_ext_ct, stream_ct, i;
402     uint32_t ext_d, leak_rate, stream_num;
403     unsigned int stream_languageid_index;
404
405     avio_rl64(pb); // starttime
406     avio_rl64(pb); // endtime
407     leak_rate = avio_rl32(pb); // leak-datarate
408     avio_rl32(pb); // bucket-datasize
409     avio_rl32(pb); // init-bucket-fullness
410     avio_rl32(pb); // alt-leak-datarate
411     avio_rl32(pb); // alt-bucket-datasize
412     avio_rl32(pb); // alt-init-bucket-fullness
413     avio_rl32(pb); // max-object-size
414     avio_rl32(pb); // flags (reliable,seekable,no_cleanpoints?,resend-live-cleanpoints, rest of bits reserved)
415     stream_num = avio_rl16(pb); // stream-num
416
417     stream_languageid_index = avio_rl16(pb); // stream-language-id-index
418     if (stream_num < 128)
419         asf->streams[stream_num].stream_language_index = stream_languageid_index;
420
421     avio_rl64(pb); // avg frametime in 100ns units
422     stream_ct = avio_rl16(pb); //stream-name-count
423     payload_ext_ct = avio_rl16(pb); //payload-extension-system-count
424
425     if (stream_num < 128)
426         asf->stream_bitrates[stream_num] = leak_rate;
427
428     for (i=0; i<stream_ct; i++){
429         avio_rl16(pb);
430         ext_len = avio_rl16(pb);
431         avio_skip(pb, ext_len);
432     }
433
434     for (i=0; i<payload_ext_ct; i++){
435         ff_get_guid(pb, &g);
436         ext_d=avio_rl16(pb);
437         ext_len=avio_rl32(pb);
438         avio_skip(pb, ext_len);
439     }
440
441     return 0;
442 }
443
444 static int asf_read_content_desc(AVFormatContext *s, int64_t size)
445 {
446     AVIOContext *pb = s->pb;
447     int len1, len2, len3, len4, len5;
448
449     len1 = avio_rl16(pb);
450     len2 = avio_rl16(pb);
451     len3 = avio_rl16(pb);
452     len4 = avio_rl16(pb);
453     len5 = avio_rl16(pb);
454     get_tag(s, "title"    , 0, len1);
455     get_tag(s, "author"   , 0, len2);
456     get_tag(s, "copyright", 0, len3);
457     get_tag(s, "comment"  , 0, len4);
458     avio_skip(pb, len5);
459
460     return 0;
461 }
462
463 static int asf_read_ext_content_desc(AVFormatContext *s, int64_t size)
464 {
465     AVIOContext *pb = s->pb;
466     ASFContext *asf = s->priv_data;
467     int desc_count, i, ret;
468
469     desc_count = avio_rl16(pb);
470     for(i=0;i<desc_count;i++) {
471         int name_len,value_type,value_len;
472         char name[1024];
473
474         name_len = avio_rl16(pb);
475         if (name_len%2)     // must be even, broken lavf versions wrote len-1
476             name_len += 1;
477         if ((ret = avio_get_str16le(pb, name_len, name, sizeof(name))) < name_len)
478             avio_skip(pb, name_len - ret);
479         value_type = avio_rl16(pb);
480         value_len  = avio_rl16(pb);
481         if (!value_type && value_len%2)
482             value_len += 1;
483         /**
484          * My sample has that stream set to 0 maybe that mean the container.
485          * Asf stream count start at 1. I am using 0 to the container value since it's unused
486          */
487         if (!strcmp(name, "AspectRatioX")){
488             asf->dar[0].num= get_value(s->pb, value_type);
489         } else if(!strcmp(name, "AspectRatioY")){
490             asf->dar[0].den= get_value(s->pb, value_type);
491         } else
492             get_tag(s, name, value_type, value_len);
493     }
494
495     return 0;
496 }
497
498 static int asf_read_language_list(AVFormatContext *s, int64_t size)
499 {
500     AVIOContext *pb = s->pb;
501     ASFContext *asf = s->priv_data;
502     int j, ret;
503     int stream_count = avio_rl16(pb);
504     for(j = 0; j < stream_count; j++) {
505         char lang[6];
506         unsigned int lang_len = avio_r8(pb);
507         if ((ret = avio_get_str16le(pb, lang_len, lang, sizeof(lang))) < lang_len)
508             avio_skip(pb, lang_len - ret);
509         if (j < 128)
510             av_strlcpy(asf->stream_languages[j], lang, sizeof(*asf->stream_languages));
511     }
512
513     return 0;
514 }
515
516 static int asf_read_metadata(AVFormatContext *s, int64_t size)
517 {
518     AVIOContext *pb = s->pb;
519     ASFContext *asf = s->priv_data;
520     int n, stream_num, name_len, value_len, value_type, value_num;
521     int ret, i;
522     n = avio_rl16(pb);
523
524     for(i=0;i<n;i++) {
525         char name[1024];
526
527         avio_rl16(pb); //lang_list_index
528         stream_num= avio_rl16(pb);
529         name_len=   avio_rl16(pb);
530         value_type= avio_rl16(pb);
531         value_len=  avio_rl32(pb);
532
533         if ((ret = avio_get_str16le(pb, name_len, name, sizeof(name))) < name_len)
534             avio_skip(pb, name_len - ret);
535         //av_log(s, AV_LOG_ERROR, "%d %d %d %d %d <%s>\n", i, stream_num, name_len, value_type, value_len, name);
536         value_num= avio_rl16(pb);//we should use get_value() here but it does not work 2 is le16 here but le32 elsewhere
537         avio_skip(pb, value_len - 2);
538
539         if(stream_num<128){
540             if     (!strcmp(name, "AspectRatioX")) asf->dar[stream_num].num= value_num;
541             else if(!strcmp(name, "AspectRatioY")) asf->dar[stream_num].den= value_num;
542         }
543     }
544
545     return 0;
546 }
547
548 static int asf_read_marker(AVFormatContext *s, int64_t size)
549 {
550     AVIOContext *pb = s->pb;
551     int i, count, name_len, ret;
552     char name[1024];
553
554     avio_rl64(pb);            // reserved 16 bytes
555     avio_rl64(pb);            // ...
556     count = avio_rl32(pb);    // markers count
557     avio_rl16(pb);            // reserved 2 bytes
558     name_len = avio_rl16(pb); // name length
559     for(i=0;i<name_len;i++){
560         avio_r8(pb); // skip the name
561     }
562
563     for(i=0;i<count;i++){
564         int64_t pres_time;
565         int name_len;
566
567         avio_rl64(pb);             // offset, 8 bytes
568         pres_time = avio_rl64(pb); // presentation time
569         avio_rl16(pb);             // entry length
570         avio_rl32(pb);             // send time
571         avio_rl32(pb);             // flags
572         name_len = avio_rl32(pb);  // name length
573         if ((ret = avio_get_str16le(pb, name_len * 2, name, sizeof(name))) < name_len)
574             avio_skip(pb, name_len - ret);
575         ff_new_chapter(s, i, (AVRational){1, 10000000}, pres_time, AV_NOPTS_VALUE, name );
576     }
577
578     return 0;
579 }
580
581 static int asf_read_header(AVFormatContext *s, AVFormatParameters *ap)
582 {
583     ASFContext *asf = s->priv_data;
584     ff_asf_guid g;
585     AVIOContext *pb = s->pb;
586     int i;
587     int64_t gsize;
588
589     ff_get_guid(pb, &g);
590     if (ff_guidcmp(&g, &ff_asf_header))
591         return -1;
592     avio_rl64(pb);
593     avio_rl32(pb);
594     avio_r8(pb);
595     avio_r8(pb);
596     memset(&asf->asfid2avid, -1, sizeof(asf->asfid2avid));
597     for(;;) {
598         uint64_t gpos= avio_tell(pb);
599         ff_get_guid(pb, &g);
600         gsize = avio_rl64(pb);
601         av_dlog(s, "%08"PRIx64": ", gpos);
602         print_guid(&g);
603         av_dlog(s, "  size=0x%"PRIx64"\n", gsize);
604         if (!ff_guidcmp(&g, &ff_asf_data_header)) {
605             asf->data_object_offset = avio_tell(pb);
606             // if not streaming, gsize is not unlimited (how?), and there is enough space in the file..
607             if (!(asf->hdr.flags & 0x01) && gsize >= 100) {
608                 asf->data_object_size = gsize - 24;
609             } else {
610                 asf->data_object_size = (uint64_t)-1;
611             }
612             break;
613         }
614         if (gsize < 24)
615             return -1;
616         if (!ff_guidcmp(&g, &ff_asf_file_header)) {
617             asf_read_file_properties(s, gsize);
618         } else if (!ff_guidcmp(&g, &ff_asf_stream_header)) {
619             asf_read_stream_properties(s, gsize);
620         } else if (!ff_guidcmp(&g, &ff_asf_comment_header)) {
621             asf_read_content_desc(s, gsize);
622         } else if (!ff_guidcmp(&g, &ff_asf_language_guid)) {
623             asf_read_language_list(s, gsize);
624         } else if (!ff_guidcmp(&g, &ff_asf_extended_content_header)) {
625             asf_read_ext_content_desc(s, gsize);
626         } else if (!ff_guidcmp(&g, &ff_asf_metadata_header)) {
627             asf_read_metadata(s, gsize);
628         } else if (!ff_guidcmp(&g, &ff_asf_ext_stream_header)) {
629             asf_read_ext_stream_properties(s, gsize);
630
631             // there could be a optional stream properties object to follow
632             // if so the next iteration will pick it up
633             continue;
634         } else if (!ff_guidcmp(&g, &ff_asf_head1_guid)) {
635             int v1, v2;
636             ff_get_guid(pb, &g);
637             v1 = avio_rl32(pb);
638             v2 = avio_rl16(pb);
639             continue;
640         } else if (!ff_guidcmp(&g, &ff_asf_marker_header)) {
641             asf_read_marker(s, gsize);
642         } else if (pb->eof_reached) {
643             return -1;
644         } else {
645             if (!s->keylen) {
646                 if (!ff_guidcmp(&g, &ff_asf_content_encryption)) {
647                     av_log(s, AV_LOG_WARNING, "DRM protected stream detected, decoding will likely fail!\n");
648                 } else if (!ff_guidcmp(&g, &ff_asf_ext_content_encryption)) {
649                     av_log(s, AV_LOG_WARNING, "Ext DRM protected stream detected, decoding will likely fail!\n");
650                 } else if (!ff_guidcmp(&g, &ff_asf_digital_signature)) {
651                     av_log(s, AV_LOG_WARNING, "Digital signature detected, decoding will likely fail!\n");
652                 }
653             }
654         }
655         if(avio_tell(pb) != gpos + gsize)
656             av_log(s, AV_LOG_DEBUG, "gpos mismatch our pos=%"PRIu64", end=%"PRIu64"\n", avio_tell(pb)-gpos, gsize);
657         avio_seek(pb, gpos + gsize, SEEK_SET);
658     }
659     ff_get_guid(pb, &g);
660     avio_rl64(pb);
661     avio_r8(pb);
662     avio_r8(pb);
663     if (pb->eof_reached)
664         return -1;
665     asf->data_offset = avio_tell(pb);
666     asf->packet_size_left = 0;
667
668
669     for(i=0; i<128; i++){
670         int stream_num= asf->asfid2avid[i];
671         if(stream_num>=0){
672             AVStream *st = s->streams[stream_num];
673             if (!st->codec->bit_rate)
674                 st->codec->bit_rate = asf->stream_bitrates[i];
675             if (asf->dar[i].num > 0 && asf->dar[i].den > 0){
676                 av_reduce(&st->sample_aspect_ratio.num,
677                           &st->sample_aspect_ratio.den,
678                           asf->dar[i].num, asf->dar[i].den, INT_MAX);
679             } 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.
680                 av_reduce(&st->sample_aspect_ratio.num,
681                           &st->sample_aspect_ratio.den,
682                           asf->dar[0].num, asf->dar[0].den, INT_MAX);
683
684 //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);
685
686             // copy and convert language codes to the frontend
687             if (asf->streams[i].stream_language_index < 128) {
688                 const char *rfc1766 = asf->stream_languages[asf->streams[i].stream_language_index];
689                 if (rfc1766 && strlen(rfc1766) > 1) {
690                     const char primary_tag[3] = { rfc1766[0], rfc1766[1], '\0' }; // ignore country code if any
691                     const char *iso6392 = av_convert_lang_to(primary_tag, AV_LANG_ISO639_2_BIBL);
692                     if (iso6392)
693                         av_metadata_set2(&st->metadata, "language", iso6392, 0);
694                 }
695             }
696         }
697     }
698
699     ff_metadata_conv(&s->metadata, NULL, ff_asf_metadata_conv);
700
701     return 0;
702 }
703
704 #define DO_2BITS(bits, var, defval) \
705     switch (bits & 3) \
706     { \
707     case 3: var = avio_rl32(pb); rsize += 4; break; \
708     case 2: var = avio_rl16(pb); rsize += 2; break; \
709     case 1: var = avio_r8(pb);   rsize++; break; \
710     default: var = defval; break; \
711     }
712
713 /**
714  * Load a single ASF packet into the demuxer.
715  * @param s demux context
716  * @param pb context to read data from
717  * @return 0 on success, <0 on error
718  */
719 static int ff_asf_get_packet(AVFormatContext *s, AVIOContext *pb)
720 {
721     ASFContext *asf = s->priv_data;
722     uint32_t packet_length, padsize;
723     int rsize = 8;
724     int c, d, e, off;
725
726     // if we do not know packet size, allow skipping up to 32 kB
727     off= 32768;
728     if (s->packet_size > 0)
729         off= (avio_tell(pb) - s->data_offset) % s->packet_size + 3;
730
731     c=d=e=-1;
732     while(off-- > 0){
733         c=d; d=e;
734         e= avio_r8(pb);
735         if(c == 0x82 && !d && !e)
736             break;
737     }
738
739     if (c != 0x82) {
740         /**
741          * This code allows handling of -EAGAIN at packet boundaries (i.e.
742          * if the packet sync code above triggers -EAGAIN). This does not
743          * imply complete -EAGAIN handling support at random positions in
744          * the stream.
745          */
746         if (pb->error == AVERROR(EAGAIN))
747             return AVERROR(EAGAIN);
748         if (!pb->eof_reached)
749             av_log(s, AV_LOG_ERROR, "ff asf bad header %x  at:%"PRId64"\n", c, avio_tell(pb));
750     }
751     if ((c & 0x8f) == 0x82) {
752         if (d || e) {
753             if (!pb->eof_reached)
754                 av_log(s, AV_LOG_ERROR, "ff asf bad non zero\n");
755             return -1;
756         }
757         c= avio_r8(pb);
758         d= avio_r8(pb);
759         rsize+=3;
760     }else{
761         avio_seek(pb, -1, SEEK_CUR); //FIXME
762     }
763
764     asf->packet_flags    = c;
765     asf->packet_property = d;
766
767     DO_2BITS(asf->packet_flags >> 5, packet_length, s->packet_size);
768     DO_2BITS(asf->packet_flags >> 1, padsize, 0); // sequence ignored
769     DO_2BITS(asf->packet_flags >> 3, padsize, 0); // padding length
770
771     //the following checks prevent overflows and infinite loops
772     if(!packet_length || packet_length >= (1U<<29)){
773         av_log(s, AV_LOG_ERROR, "invalid packet_length %d at:%"PRId64"\n", packet_length, avio_tell(pb));
774         return -1;
775     }
776     if(padsize >= packet_length){
777         av_log(s, AV_LOG_ERROR, "invalid padsize %d at:%"PRId64"\n", padsize, avio_tell(pb));
778         return -1;
779     }
780
781     asf->packet_timestamp = avio_rl32(pb);
782     avio_rl16(pb); /* duration */
783     // rsize has at least 11 bytes which have to be present
784
785     if (asf->packet_flags & 0x01) {
786         asf->packet_segsizetype = avio_r8(pb); rsize++;
787         asf->packet_segments = asf->packet_segsizetype & 0x3f;
788     } else {
789         asf->packet_segments = 1;
790         asf->packet_segsizetype = 0x80;
791     }
792     asf->packet_size_left = packet_length - padsize - rsize;
793     if (packet_length < asf->hdr.min_pktsize)
794         padsize += asf->hdr.min_pktsize - packet_length;
795     asf->packet_padsize = padsize;
796     av_dlog(s, "packet: size=%d padsize=%d  left=%d\n", s->packet_size, asf->packet_padsize, asf->packet_size_left);
797     return 0;
798 }
799
800 /**
801  *
802  * @return <0 if error
803  */
804 static int asf_read_frame_header(AVFormatContext *s, AVIOContext *pb){
805     ASFContext *asf = s->priv_data;
806     int rsize = 1;
807     int num = avio_r8(pb);
808     int64_t ts0, ts1;
809
810     asf->packet_segments--;
811     asf->packet_key_frame = num >> 7;
812     asf->stream_index = asf->asfid2avid[num & 0x7f];
813     // sequence should be ignored!
814     DO_2BITS(asf->packet_property >> 4, asf->packet_seq, 0);
815     DO_2BITS(asf->packet_property >> 2, asf->packet_frag_offset, 0);
816     DO_2BITS(asf->packet_property, asf->packet_replic_size, 0);
817 //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);
818     if (asf->packet_replic_size >= 8) {
819         asf->packet_obj_size = avio_rl32(pb);
820         if(asf->packet_obj_size >= (1<<24) || asf->packet_obj_size <= 0){
821             av_log(s, AV_LOG_ERROR, "packet_obj_size invalid\n");
822             return -1;
823         }
824         asf->packet_frag_timestamp = avio_rl32(pb); // timestamp
825         if(asf->packet_replic_size >= 8+38+4){
826 //            for(i=0; i<asf->packet_replic_size-8; i++)
827 //                av_log(s, AV_LOG_DEBUG, "%02X ",avio_r8(pb));
828 //            av_log(s, AV_LOG_DEBUG, "\n");
829             avio_skip(pb, 10);
830             ts0= avio_rl64(pb);
831             ts1= avio_rl64(pb);
832             avio_skip(pb, 12);
833             avio_rl32(pb);
834             avio_skip(pb, asf->packet_replic_size - 8 - 38 - 4);
835             if(ts0!= -1) asf->packet_frag_timestamp= ts0/10000;
836             else         asf->packet_frag_timestamp= AV_NOPTS_VALUE;
837         }else
838             avio_skip(pb, asf->packet_replic_size - 8);
839         rsize += asf->packet_replic_size; // FIXME - check validity
840     } else if (asf->packet_replic_size==1){
841         // multipacket - frag_offset is beginning timestamp
842         asf->packet_time_start = asf->packet_frag_offset;
843         asf->packet_frag_offset = 0;
844         asf->packet_frag_timestamp = asf->packet_timestamp;
845
846         asf->packet_time_delta = avio_r8(pb);
847         rsize++;
848     }else if(asf->packet_replic_size!=0){
849         av_log(s, AV_LOG_ERROR, "unexpected packet_replic_size of %d\n", asf->packet_replic_size);
850         return -1;
851     }
852     if (asf->packet_flags & 0x01) {
853         DO_2BITS(asf->packet_segsizetype >> 6, asf->packet_frag_size, 0); // 0 is illegal
854         if(asf->packet_frag_size > asf->packet_size_left - rsize){
855             av_log(s, AV_LOG_ERROR, "packet_frag_size is invalid\n");
856             return -1;
857         }
858         //printf("Fragsize %d\n", asf->packet_frag_size);
859     } else {
860         asf->packet_frag_size = asf->packet_size_left - rsize;
861         //printf("Using rest  %d %d %d\n", asf->packet_frag_size, asf->packet_size_left, rsize);
862     }
863     if (asf->packet_replic_size == 1) {
864         asf->packet_multi_size = asf->packet_frag_size;
865         if (asf->packet_multi_size > asf->packet_size_left)
866             return -1;
867     }
868     asf->packet_size_left -= rsize;
869     //printf("___objsize____  %d   %d    rs:%d\n", asf->packet_obj_size, asf->packet_frag_offset, rsize);
870
871     return 0;
872 }
873
874 /**
875  * Parse data from individual ASF packets (which were previously loaded
876  * with asf_get_packet()).
877  * @param s demux context
878  * @param pb context to read data from
879  * @param pkt pointer to store packet data into
880  * @return 0 if data was stored in pkt, <0 on error or 1 if more ASF
881  *          packets need to be loaded (through asf_get_packet())
882  */
883 static int ff_asf_parse_packet(AVFormatContext *s, AVIOContext *pb, AVPacket *pkt)
884 {
885     ASFContext *asf = s->priv_data;
886     ASFStream *asf_st = 0;
887     for (;;) {
888         int ret;
889         if(pb->eof_reached)
890             return AVERROR_EOF;
891         if (asf->packet_size_left < FRAME_HEADER_SIZE
892             || asf->packet_segments < 1) {
893             //asf->packet_size_left <= asf->packet_padsize) {
894             int ret = asf->packet_size_left + asf->packet_padsize;
895             //printf("PacketLeftSize:%d  Pad:%d Pos:%"PRId64"\n", asf->packet_size_left, asf->packet_padsize, avio_tell(pb));
896             assert(ret>=0);
897             /* fail safe */
898             avio_skip(pb, ret);
899
900             asf->packet_pos= avio_tell(pb);
901             if (asf->data_object_size != (uint64_t)-1 &&
902                 (asf->packet_pos - asf->data_object_offset >= asf->data_object_size))
903                 return AVERROR_EOF; /* Do not exceed the size of the data object */
904             return 1;
905         }
906         if (asf->packet_time_start == 0) {
907             if(asf_read_frame_header(s, pb) < 0){
908                 asf->packet_segments= 0;
909                 continue;
910             }
911             if (asf->stream_index < 0
912                 || s->streams[asf->stream_index]->discard >= AVDISCARD_ALL
913                 || (!asf->packet_key_frame && s->streams[asf->stream_index]->discard >= AVDISCARD_NONKEY)
914                 ) {
915                 asf->packet_time_start = 0;
916                 /* unhandled packet (should not happen) */
917                 avio_skip(pb, asf->packet_frag_size);
918                 asf->packet_size_left -= asf->packet_frag_size;
919                 if(asf->stream_index < 0)
920                     av_log(s, AV_LOG_ERROR, "ff asf skip %d (unknown stream)\n", asf->packet_frag_size);
921                 continue;
922             }
923             asf->asf_st = s->streams[asf->stream_index]->priv_data;
924         }
925         asf_st = asf->asf_st;
926
927         if (asf->packet_replic_size == 1) {
928             // frag_offset is here used as the beginning timestamp
929             asf->packet_frag_timestamp = asf->packet_time_start;
930             asf->packet_time_start += asf->packet_time_delta;
931             asf->packet_obj_size = asf->packet_frag_size = avio_r8(pb);
932             asf->packet_size_left--;
933             asf->packet_multi_size--;
934             if (asf->packet_multi_size < asf->packet_obj_size)
935             {
936                 asf->packet_time_start = 0;
937                 avio_skip(pb, asf->packet_multi_size);
938                 asf->packet_size_left -= asf->packet_multi_size;
939                 continue;
940             }
941             asf->packet_multi_size -= asf->packet_obj_size;
942             //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);
943         }
944         if(   /*asf->packet_frag_size == asf->packet_obj_size*/
945               asf_st->frag_offset + asf->packet_frag_size <= asf_st->pkt.size
946            && asf_st->frag_offset + asf->packet_frag_size > asf->packet_obj_size){
947             av_log(s, AV_LOG_INFO, "ignoring invalid packet_obj_size (%d %d %d %d)\n",
948                 asf_st->frag_offset, asf->packet_frag_size,
949                 asf->packet_obj_size, asf_st->pkt.size);
950             asf->packet_obj_size= asf_st->pkt.size;
951         }
952
953         if (   asf_st->pkt.size != asf->packet_obj_size
954             || asf_st->frag_offset + asf->packet_frag_size > asf_st->pkt.size) { //FIXME is this condition sufficient?
955             if(asf_st->pkt.data){
956                 av_log(s, AV_LOG_INFO, "freeing incomplete packet size %d, new %d\n", asf_st->pkt.size, asf->packet_obj_size);
957                 asf_st->frag_offset = 0;
958                 av_free_packet(&asf_st->pkt);
959             }
960             /* new packet */
961             av_new_packet(&asf_st->pkt, asf->packet_obj_size);
962             asf_st->seq = asf->packet_seq;
963             asf_st->pkt.dts = asf->packet_frag_timestamp;
964             asf_st->pkt.stream_index = asf->stream_index;
965             asf_st->pkt.pos =
966             asf_st->packet_pos= asf->packet_pos;
967 //printf("new packet: stream:%d key:%d packet_key:%d audio:%d size:%d\n",
968 //asf->stream_index, asf->packet_key_frame, asf_st->pkt.flags & AV_PKT_FLAG_KEY,
969 //s->streams[asf->stream_index]->codec->codec_type == AVMEDIA_TYPE_AUDIO, asf->packet_obj_size);
970             if (s->streams[asf->stream_index]->codec->codec_type == AVMEDIA_TYPE_AUDIO)
971                 asf->packet_key_frame = 1;
972             if (asf->packet_key_frame)
973                 asf_st->pkt.flags |= AV_PKT_FLAG_KEY;
974         }
975
976         /* read data */
977         //printf("READ PACKET s:%d  os:%d  o:%d,%d  l:%d   DATA:%p\n",
978         //       s->packet_size, asf_st->pkt.size, asf->packet_frag_offset,
979         //       asf_st->frag_offset, asf->packet_frag_size, asf_st->pkt.data);
980         asf->packet_size_left -= asf->packet_frag_size;
981         if (asf->packet_size_left < 0)
982             continue;
983
984         if(   asf->packet_frag_offset >= asf_st->pkt.size
985            || asf->packet_frag_size > asf_st->pkt.size - asf->packet_frag_offset){
986             av_log(s, AV_LOG_ERROR, "packet fragment position invalid %u,%u not in %u\n",
987                 asf->packet_frag_offset, asf->packet_frag_size, asf_st->pkt.size);
988             continue;
989         }
990
991         ret = avio_read(pb, asf_st->pkt.data + asf->packet_frag_offset,
992                          asf->packet_frag_size);
993         if (ret != asf->packet_frag_size) {
994             if (ret < 0 || asf->packet_frag_offset + ret == 0)
995                 return ret < 0 ? ret : AVERROR_EOF;
996             if (asf_st->ds_span > 1) {
997                 // scrambling, we can either drop it completely or fill the remainder
998                 // TODO: should we fill the whole packet instead of just the current
999                 // fragment?
1000                 memset(asf_st->pkt.data + asf->packet_frag_offset + ret, 0,
1001                        asf->packet_frag_size - ret);
1002                 ret = asf->packet_frag_size;
1003             } else
1004                 // no scrambling, so we can return partial packets
1005                 av_shrink_packet(&asf_st->pkt, asf->packet_frag_offset + ret);
1006         }
1007         if (s->key && s->keylen == 20)
1008             ff_asfcrypt_dec(s->key, asf_st->pkt.data + asf->packet_frag_offset,
1009                             ret);
1010         asf_st->frag_offset += ret;
1011         /* test if whole packet is read */
1012         if (asf_st->frag_offset == asf_st->pkt.size) {
1013             //workaround for macroshit radio DVR-MS files
1014             if(   s->streams[asf->stream_index]->codec->codec_id == CODEC_ID_MPEG2VIDEO
1015                && asf_st->pkt.size > 100){
1016                 int i;
1017                 for(i=0; i<asf_st->pkt.size && !asf_st->pkt.data[i]; i++);
1018                 if(i == asf_st->pkt.size){
1019                     av_log(s, AV_LOG_DEBUG, "discarding ms fart\n");
1020                     asf_st->frag_offset = 0;
1021                     av_free_packet(&asf_st->pkt);
1022                     continue;
1023                 }
1024             }
1025
1026             /* return packet */
1027             if (asf_st->ds_span > 1) {
1028               if(asf_st->pkt.size != asf_st->ds_packet_size * asf_st->ds_span){
1029                     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);
1030               }else{
1031                 /* packet descrambling */
1032                 uint8_t *newdata = av_malloc(asf_st->pkt.size + FF_INPUT_BUFFER_PADDING_SIZE);
1033                 if (newdata) {
1034                     int offset = 0;
1035                     memset(newdata + asf_st->pkt.size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
1036                     while (offset < asf_st->pkt.size) {
1037                         int off = offset / asf_st->ds_chunk_size;
1038                         int row = off / asf_st->ds_span;
1039                         int col = off % asf_st->ds_span;
1040                         int idx = row + col * asf_st->ds_packet_size / asf_st->ds_chunk_size;
1041                         //printf("off:%d  row:%d  col:%d  idx:%d\n", off, row, col, idx);
1042
1043                         assert(offset + asf_st->ds_chunk_size <= asf_st->pkt.size);
1044                         assert(idx+1 <= asf_st->pkt.size / asf_st->ds_chunk_size);
1045                         memcpy(newdata + offset,
1046                                asf_st->pkt.data + idx * asf_st->ds_chunk_size,
1047                                asf_st->ds_chunk_size);
1048                         offset += asf_st->ds_chunk_size;
1049                     }
1050                     av_free(asf_st->pkt.data);
1051                     asf_st->pkt.data = newdata;
1052                 }
1053               }
1054             }
1055             asf_st->frag_offset = 0;
1056             *pkt= asf_st->pkt;
1057             //printf("packet %d %d\n", asf_st->pkt.size, asf->packet_frag_size);
1058             asf_st->pkt.size = 0;
1059             asf_st->pkt.data = 0;
1060             break; // packet completed
1061         }
1062     }
1063     return 0;
1064 }
1065
1066 static int asf_read_packet(AVFormatContext *s, AVPacket *pkt)
1067 {
1068     ASFContext *asf = s->priv_data;
1069
1070     for (;;) {
1071         int ret;
1072
1073         /* parse cached packets, if any */
1074         if ((ret = ff_asf_parse_packet(s, s->pb, pkt)) <= 0)
1075             return ret;
1076         if ((ret = ff_asf_get_packet(s, s->pb)) < 0)
1077             assert(asf->packet_size_left < FRAME_HEADER_SIZE || asf->packet_segments < 1);
1078         asf->packet_time_start = 0;
1079     }
1080
1081     return 0;
1082 }
1083
1084 // Added to support seeking after packets have been read
1085 // If information is not reset, read_packet fails due to
1086 // leftover information from previous reads
1087 static void asf_reset_header(AVFormatContext *s)
1088 {
1089     ASFContext *asf = s->priv_data;
1090     ASFStream *asf_st;
1091     int i;
1092
1093     asf->packet_size_left = 0;
1094     asf->packet_segments = 0;
1095     asf->packet_flags = 0;
1096     asf->packet_property = 0;
1097     asf->packet_timestamp = 0;
1098     asf->packet_segsizetype = 0;
1099     asf->packet_segments = 0;
1100     asf->packet_seq = 0;
1101     asf->packet_replic_size = 0;
1102     asf->packet_key_frame = 0;
1103     asf->packet_padsize = 0;
1104     asf->packet_frag_offset = 0;
1105     asf->packet_frag_size = 0;
1106     asf->packet_frag_timestamp = 0;
1107     asf->packet_multi_size = 0;
1108     asf->packet_obj_size = 0;
1109     asf->packet_time_delta = 0;
1110     asf->packet_time_start = 0;
1111
1112     for(i=0; i<s->nb_streams; i++){
1113         asf_st= s->streams[i]->priv_data;
1114         av_free_packet(&asf_st->pkt);
1115         asf_st->frag_offset=0;
1116         asf_st->seq=0;
1117     }
1118     asf->asf_st= NULL;
1119 }
1120
1121 static int asf_read_close(AVFormatContext *s)
1122 {
1123     int i;
1124
1125     asf_reset_header(s);
1126     for(i=0;i<s->nb_streams;i++) {
1127         AVStream *st = s->streams[i];
1128         av_free(st->codec->palctrl);
1129     }
1130     return 0;
1131 }
1132
1133 static int64_t asf_read_pts(AVFormatContext *s, int stream_index, int64_t *ppos, int64_t pos_limit)
1134 {
1135     AVPacket pkt1, *pkt = &pkt1;
1136     ASFStream *asf_st;
1137     int64_t pts;
1138     int64_t pos= *ppos;
1139     int i;
1140     int64_t start_pos[ASF_MAX_STREAMS];
1141
1142     for(i=0; i<s->nb_streams; i++){
1143         start_pos[i]= pos;
1144     }
1145
1146     if (s->packet_size > 0)
1147         pos= (pos+s->packet_size-1-s->data_offset)/s->packet_size*s->packet_size+ s->data_offset;
1148     *ppos= pos;
1149     avio_seek(s->pb, pos, SEEK_SET);
1150
1151 //printf("asf_read_pts\n");
1152     asf_reset_header(s);
1153     for(;;){
1154         if (av_read_frame(s, pkt) < 0){
1155             av_log(s, AV_LOG_INFO, "asf_read_pts failed\n");
1156             return AV_NOPTS_VALUE;
1157         }
1158
1159         pts= pkt->pts;
1160
1161         av_free_packet(pkt);
1162         if(pkt->flags&AV_PKT_FLAG_KEY){
1163             i= pkt->stream_index;
1164
1165             asf_st= s->streams[i]->priv_data;
1166
1167 //            assert((asf_st->packet_pos - s->data_offset) % s->packet_size == 0);
1168             pos= asf_st->packet_pos;
1169
1170             av_add_index_entry(s->streams[i], pos, pts, pkt->size, pos - start_pos[i] + 1, AVINDEX_KEYFRAME);
1171             start_pos[i]= asf_st->packet_pos + 1;
1172
1173             if(pkt->stream_index == stream_index)
1174                break;
1175         }
1176     }
1177
1178     *ppos= pos;
1179 //printf("found keyframe at %"PRId64" stream %d stamp:%"PRId64"\n", *ppos, stream_index, pts);
1180
1181     return pts;
1182 }
1183
1184 static void asf_build_simple_index(AVFormatContext *s, int stream_index)
1185 {
1186     ff_asf_guid g;
1187     ASFContext *asf = s->priv_data;
1188     int64_t current_pos= avio_tell(s->pb);
1189     int i;
1190
1191     avio_seek(s->pb, asf->data_object_offset + asf->data_object_size, SEEK_SET);
1192     ff_get_guid(s->pb, &g);
1193
1194     /* the data object can be followed by other top-level objects,
1195        skip them until the simple index object is reached */
1196     while (ff_guidcmp(&g, &index_guid)) {
1197         int64_t gsize= avio_rl64(s->pb);
1198         if (gsize < 24 || s->pb->eof_reached) {
1199             avio_seek(s->pb, current_pos, SEEK_SET);
1200             return;
1201         }
1202         avio_skip(s->pb, gsize-24);
1203         ff_get_guid(s->pb, &g);
1204     }
1205
1206     {
1207         int64_t itime, last_pos=-1;
1208         int pct, ict;
1209         int64_t av_unused gsize= avio_rl64(s->pb);
1210         ff_get_guid(s->pb, &g);
1211         itime=avio_rl64(s->pb);
1212         pct=avio_rl32(s->pb);
1213         ict=avio_rl32(s->pb);
1214         av_log(s, AV_LOG_DEBUG, "itime:0x%"PRIx64", pct:%d, ict:%d\n",itime,pct,ict);
1215
1216         for (i=0;i<ict;i++){
1217             int pktnum=avio_rl32(s->pb);
1218             int pktct =avio_rl16(s->pb);
1219             int64_t pos      = s->data_offset + s->packet_size*(int64_t)pktnum;
1220             int64_t index_pts= av_rescale(itime, i, 10000);
1221
1222             if(pos != last_pos){
1223             av_log(s, AV_LOG_DEBUG, "pktnum:%d, pktct:%d\n", pktnum, pktct);
1224             av_add_index_entry(s->streams[stream_index], pos, index_pts, s->packet_size, 0, AVINDEX_KEYFRAME);
1225             last_pos=pos;
1226             }
1227         }
1228         asf->index_read= 1;
1229     }
1230     avio_seek(s->pb, current_pos, SEEK_SET);
1231 }
1232
1233 static int asf_read_seek(AVFormatContext *s, int stream_index, int64_t pts, int flags)
1234 {
1235     ASFContext *asf = s->priv_data;
1236     AVStream *st = s->streams[stream_index];
1237     int64_t pos;
1238     int index;
1239
1240     if (s->packet_size <= 0)
1241         return -1;
1242
1243     /* Try using the protocol's read_seek if available */
1244     if(s->pb) {
1245         int ret = av_url_read_fseek(s->pb, stream_index, pts, flags);
1246         if(ret >= 0)
1247             asf_reset_header(s);
1248         if (ret != AVERROR(ENOSYS))
1249             return ret;
1250     }
1251
1252     if (!asf->index_read)
1253         asf_build_simple_index(s, stream_index);
1254
1255     if(!(asf->index_read && st->index_entries)){
1256         if(av_seek_frame_binary(s, stream_index, pts, flags)<0)
1257             return -1;
1258     }else{
1259         index= av_index_search_timestamp(st, pts, flags);
1260         if(index<0)
1261             return -1;
1262
1263         /* find the position */
1264         pos = st->index_entries[index].pos;
1265
1266     // various attempts to find key frame have failed so far
1267     //    asf_reset_header(s);
1268     //    avio_seek(s->pb, pos, SEEK_SET);
1269     //    key_pos = pos;
1270     //     for(i=0;i<16;i++){
1271     //         pos = avio_tell(s->pb);
1272     //         if (av_read_frame(s, &pkt) < 0){
1273     //             av_log(s, AV_LOG_INFO, "seek failed\n");
1274     //             return -1;
1275     //         }
1276     //         asf_st = s->streams[stream_index]->priv_data;
1277     //         pos += st->parser->frame_offset;
1278     //
1279     //         if (pkt.size > b) {
1280     //             b = pkt.size;
1281     //             key_pos = pos;
1282     //         }
1283     //
1284     //         av_free_packet(&pkt);
1285     //     }
1286
1287         /* do the seek */
1288         av_log(s, AV_LOG_DEBUG, "SEEKTO: %"PRId64"\n", pos);
1289         avio_seek(s->pb, pos, SEEK_SET);
1290     }
1291     asf_reset_header(s);
1292     return 0;
1293 }
1294
1295 AVInputFormat ff_asf_demuxer = {
1296     "asf",
1297     NULL_IF_CONFIG_SMALL("ASF format"),
1298     sizeof(ASFContext),
1299     asf_probe,
1300     asf_read_header,
1301     asf_read_packet,
1302     asf_read_close,
1303     asf_read_seek,
1304     asf_read_pts,
1305 };