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