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