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