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