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