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