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