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