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