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