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