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