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