libavformat/asfdec_f.c
de6d9b64
 /*
7fbde343
  * ASF compatible demuxer
406792e7
  * Copyright (c) 2000, 2001 Fabrice Bellard
de6d9b64
  *
b78e7197
  * This file is part of FFmpeg.
  *
  * FFmpeg is free software; you can redistribute it and/or
19720f15
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
b78e7197
  * version 2.1 of the License, or (at your option) any later version.
de6d9b64
  *
b78e7197
  * FFmpeg is distributed in the hope that it will be useful,
de6d9b64
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19720f15
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
de6d9b64
  *
19720f15
  * You should have received a copy of the GNU Lesser General Public
b78e7197
  * License along with FFmpeg; if not, write to the Free Software
5509bffa
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
de6d9b64
  */
245976da
 
d92024f1
 #include <inttypes.h>
 
72eaba5e
 #include "libavutil/attributes.h"
1ef0e8a6
 #include "libavutil/avassert.h"
48a4ffa7
 #include "libavutil/avstring.h"
b122c651
 #include "libavutil/bswap.h"
245976da
 #include "libavutil/common.h"
d2d67e42
 #include "libavutil/dict.h"
7950e519
 #include "libavutil/internal.h"
0ebcdf5c
 #include "libavutil/mathematics.h"
75b7feae
 #include "libavutil/opt.h"
de6d9b64
 #include "avformat.h"
933e90a6
 #include "avio_internal.h"
48a4ffa7
 #include "avlanguage.h"
5e745cef
 #include "id3v2.h"
48a4ffa7
 #include "internal.h"
9d9f4119
 #include "riff.h"
542993b0
 #include "asf.h"
72be7db4
 #include "asfcrypt.h"
de6d9b64
 
30b8f3e7
 typedef struct ASFPayload {
     uint8_t type;
     uint16_t size;
 } ASFPayload;
b08569a2
 
 typedef struct ASFStream {
30b8f3e7
     int num;
     unsigned char seq;
     /* use for reading */
     AVPacket pkt;
     int frag_offset;
     int packet_obj_size;
     int timestamp;
     int64_t duration;
     int skip_to_key;
     int pkt_clean;
b08569a2
 
30b8f3e7
     int ds_span;                /* descrambling  */
     int ds_packet_size;
     int ds_chunk_size;
b08569a2
 
30b8f3e7
     int64_t packet_pos;
4bc328a2
 
30b8f3e7
     uint16_t stream_language_index;
75b7feae
 
30b8f3e7
     int      palette_changed;
     uint32_t palette[256];
75b7feae
 
30b8f3e7
     int payload_ext_ct;
     ASFPayload payload[8];
 } ASFStream;
615b92fd
 
daf8cf35
 typedef struct ASFContext {
75b7feae
     const AVClass *class;
83120e3b
     int asfid2avid[128];                 ///< conversion table from asf ID 2 AVStream ID
     ASFStream streams[128];              ///< it's max number and it's not that big
     uint32_t stream_bitrates[128];       ///< max number of streams, bitrate for each (for streaming)
26783e85
     AVRational dar[128];
83120e3b
     char stream_languages[128][6];       ///< max number of streams, language for each (RFC1766, e.g. en-US)
     /* non streamed additonnal info */
     /* packet filling */
     int packet_size_left;
     /* only for reading */
     uint64_t data_offset;                ///< beginning of the first data packet
     uint64_t data_object_offset;         ///< data object offset (excl. GUID & size)
     uint64_t data_object_size;           ///< size of the data object
     int index_read;
 
     ASFMainHeader hdr;
 
     int packet_flags;
     int packet_property;
     int packet_timestamp;
     int packet_segsizetype;
     int packet_segments;
     int packet_seq;
     int packet_replic_size;
     int packet_key_frame;
     int packet_padsize;
     unsigned int packet_frag_offset;
     unsigned int packet_frag_size;
     int64_t packet_frag_timestamp;
4eb13cdf
     int ts_is_pts;
83120e3b
     int packet_multi_size;
     int packet_time_delta;
     int packet_time_start;
     int64_t packet_pos;
 
     int stream_index;
 
48a4ffa7
     ASFStream *asf_st;                   ///< currently decoded stream
75b7feae
 
     int no_resync_search;
0af3b658
     int export_xmp;
5d79a073
 
     int uses_std_ecc;
83120e3b
 } ASFContext;
 
75b7feae
 static const AVOption options[] = {
48a4ffa7
     { "no_resync_search", "Don't try to resynchronize by looking for a certain optional start code", offsetof(ASFContext, no_resync_search), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
0af3b658
     { "export_xmp", "Export full XMP metadata", offsetof(ASFContext, export_xmp), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
75b7feae
     { NULL },
 };
 
 static const AVClass asf_class = {
     .class_name = "asf demuxer",
     .item_name  = av_default_item_name,
     .option     = options,
     .version    = LIBAVUTIL_VERSION_INT,
 };
 
580fb5e7
 #undef NDEBUG
 #include <assert.h>
 
30cdfb49
 #define ASF_MAX_STREAMS 127
5a458420
 #define FRAME_HEADER_SIZE 6
 // Fix Me! FRAME_HEADER_SIZE may be different.
 // (7 is known to be too large for GipsyGuitar.wmv)
615b92fd
 
91c9aa09
 #ifdef DEBUG
b8b00d94
 static const ff_asf_guid stream_bitrate_guid = { /* (http://get.to/sdp) */
0e3b6a6f
     0xce, 0x75, 0xf8, 0x7b, 0x8d, 0x46, 0xd1, 0x11, 0x8d, 0x82, 0x00, 0x60, 0x97, 0xc9, 0xa2, 0xb2
 };
de6d9b64
 
48a4ffa7
 #define PRINT_IF_GUID(g, cmp) \
     if (!ff_guidcmp(g, &cmp)) \
1a3eb042
         av_log(NULL, AV_LOG_TRACE, "(GUID: %s) ", # cmp)
5082f759
 
36fab50e
 static void print_guid(ff_asf_guid *g)
de6d9b64
 {
     int i;
17af0525
     PRINT_IF_GUID(g, ff_asf_header);
     else PRINT_IF_GUID(g, ff_asf_file_header);
     else PRINT_IF_GUID(g, ff_asf_stream_header);
     else PRINT_IF_GUID(g, ff_asf_audio_stream);
     else PRINT_IF_GUID(g, ff_asf_audio_conceal_none);
     else PRINT_IF_GUID(g, ff_asf_video_stream);
     else PRINT_IF_GUID(g, ff_asf_video_conceal_none);
     else PRINT_IF_GUID(g, ff_asf_command_stream);
     else PRINT_IF_GUID(g, ff_asf_comment_header);
     else PRINT_IF_GUID(g, ff_asf_codec_comment_header);
     else PRINT_IF_GUID(g, ff_asf_codec_comment1_header);
     else PRINT_IF_GUID(g, ff_asf_data_header);
b61e596a
     else PRINT_IF_GUID(g, ff_asf_simple_index_header);
17af0525
     else PRINT_IF_GUID(g, ff_asf_head1_guid);
     else PRINT_IF_GUID(g, ff_asf_head2_guid);
     else PRINT_IF_GUID(g, ff_asf_my_guid);
     else PRINT_IF_GUID(g, ff_asf_ext_stream_header);
     else PRINT_IF_GUID(g, ff_asf_extended_content_header);
     else PRINT_IF_GUID(g, ff_asf_ext_stream_embed_stream_header);
     else PRINT_IF_GUID(g, ff_asf_ext_stream_audio_stream);
     else PRINT_IF_GUID(g, ff_asf_metadata_header);
84b721db
     else PRINT_IF_GUID(g, ff_asf_metadata_library_header);
88b51ea9
     else PRINT_IF_GUID(g, ff_asf_marker_header);
0e3b6a6f
     else PRINT_IF_GUID(g, stream_bitrate_guid);
5f1ac36d
     else PRINT_IF_GUID(g, ff_asf_language_guid);
5082f759
     else
1a3eb042
         av_log(NULL, AV_LOG_TRACE, "(GUID: unknown) ");
48a4ffa7
     for (i = 0; i < 16; i++)
1a3eb042
         av_log(NULL, AV_LOG_TRACE, " 0x%02x,", (*g)[i]);
     av_log(NULL, AV_LOG_TRACE, "}\n");
de6d9b64
 }
6df84c3a
 #undef PRINT_IF_GUID
f94981ea
 #else
374cf935
 #define print_guid(g) while(0)
de6d9b64
 #endif
 
c9a65ca8
 static int asf_probe(AVProbeData *pd)
 {
     /* check file header */
a750050f
     if (!ff_guidcmp(pd->buf, &ff_asf_header))
c9a65ca8
         return AVPROBE_SCORE_MAX;
     else
         return 0;
 }
 
61f9ad2d
 /* size of type 2 (BOOL) is 32bit for "Extended Content Description Object"
  * but 16 bit for "Metadata Object" and "Metadata Library Object" */
 static int get_value(AVIOContext *pb, int type, int type2_size)
48a4ffa7
 {
     switch (type) {
     case 2:
61f9ad2d
         return (type2_size == 32) ? avio_rl32(pb) : avio_rl16(pb);
48a4ffa7
     case 3:
         return avio_rl32(pb);
     case 4:
         return avio_rl64(pb);
     case 5:
         return avio_rl16(pb);
     default:
         return INT_MIN;
30e88789
     }
 }
 
5e745cef
 /* MSDN claims that this should be "compatible with the ID3 frame, APIC",
  * but in reality this is only loosely similar */
 static int asf_read_picture(AVFormatContext *s, int len)
 {
48a4ffa7
     AVPacket pkt          = { 0 };
5e745cef
     const CodecMime *mime = ff_id3v2_mime_tags;
48a4ffa7
     enum  AVCodecID id    = AV_CODEC_ID_NONE;
5e745cef
     char mimetype[64];
     uint8_t  *desc = NULL;
     AVStream   *st = NULL;
     int ret, type, picsize, desc_len;
 
     /* type + picsize + mime + desc */
     if (len < 1 + 4 + 2 + 2) {
         av_log(s, AV_LOG_ERROR, "Invalid attached picture size: %d.\n", len);
         return AVERROR_INVALIDDATA;
     }
 
     /* picture type */
     type = avio_r8(s->pb);
     len--;
     if (type >= FF_ARRAY_ELEMS(ff_id3v2_picture_types) || type < 0) {
         av_log(s, AV_LOG_WARNING, "Unknown attached picture type: %d.\n", type);
         type = 0;
     }
 
     /* picture data size */
     picsize = avio_rl32(s->pb);
48a4ffa7
     len    -= 4;
5e745cef
 
     /* picture MIME type */
     len -= avio_get_str16le(s->pb, len, mimetype, sizeof(mimetype));
36ef5369
     while (mime->id != AV_CODEC_ID_NONE) {
5e745cef
         if (!strncmp(mime->str, mimetype, sizeof(mimetype))) {
             id = mime->id;
             break;
         }
         mime++;
     }
36ef5369
     if (id == AV_CODEC_ID_NONE) {
5e745cef
         av_log(s, AV_LOG_ERROR, "Unknown attached picture mimetype: %s.\n",
                mimetype);
         return 0;
     }
 
     if (picsize >= len) {
         av_log(s, AV_LOG_ERROR, "Invalid attached picture data size: %d >= %d.\n",
                picsize, len);
         return AVERROR_INVALIDDATA;
     }
 
     /* picture description */
     desc_len = (len - picsize) * 2 + 1;
     desc     = av_malloc(desc_len);
     if (!desc)
         return AVERROR(ENOMEM);
     len -= avio_get_str16le(s->pb, len - picsize, desc, desc_len);
 
     ret = av_get_packet(s->pb, &pkt, picsize);
     if (ret < 0)
         goto fail;
 
48a4ffa7
     st  = avformat_new_stream(s, NULL);
1ef0e8a6
     if (!st) {
5e745cef
         ret = AVERROR(ENOMEM);
         goto fail;
     }
48a4ffa7
     st->disposition              |= AV_DISPOSITION_ATTACHED_PIC;
     st->codec->codec_type         = AVMEDIA_TYPE_VIDEO;
     st->codec->codec_id           = id;
     st->attached_pic              = pkt;
5e745cef
     st->attached_pic.stream_index = st->index;
48a4ffa7
     st->attached_pic.flags       |= AV_PKT_FLAG_KEY;
5e745cef
 
     if (*desc)
         av_dict_set(&st->metadata, "title", desc, AV_DICT_DONT_STRDUP_VAL);
     else
         av_freep(&desc);
 
     av_dict_set(&st->metadata, "comment", ff_id3v2_picture_types[type], 0);
 
     return 0;
 
 fail:
     av_freep(&desc);
     av_free_packet(&pkt);
     return ret;
 }
 
f5fac6f7
 static void get_id3_tag(AVFormatContext *s, int len)
 {
     ID3v2ExtraMeta *id3v2_extra_meta = NULL;
 
5331773c
     ff_id3v2_read(s, ID3v2_DEFAULT_MAGIC, &id3v2_extra_meta, len);
f5fac6f7
     if (id3v2_extra_meta)
         ff_id3v2_parse_apic(s, &id3v2_extra_meta);
     ff_id3v2_free_extra_meta(&id3v2_extra_meta);
 }
 
61f9ad2d
 static void get_tag(AVFormatContext *s, const char *key, int type, int len, int type2_size)
20e2a7ae
 {
0af3b658
     ASFContext *asf = s->priv_data;
     char *value = NULL;
384c9c2f
     int64_t off = avio_tell(s->pb);
d9293648
 #define LEN 22
12ad6671
 
d9293648
     if ((unsigned)len >= (UINT_MAX - LEN) / 2)
12ad6671
         return;
 
0af3b658
     if (!asf->export_xmp && !strncmp(key, "xmp", 3))
         goto finish;
 
d9293648
     value = av_malloc(2 * len + LEN);
12ad6671
     if (!value)
82704826
         goto finish;
12ad6671
 
72cad800
     switch (type) {
     case ASF_UNICODE:
48a4ffa7
         avio_get_str16le(s->pb, len, value, 2 * len + 1);
72cad800
         break;
     case -1: // ASCI
53d70a33
         avio_read(s->pb, value, len);
2eaa5537
         value[len]=0;
72cad800
         break;
     case ASF_BYTE_ARRAY:
f5fac6f7
         if (!strcmp(key, "WM/Picture")) { // handle cover art
             asf_read_picture(s, len);
         } else if (!strcmp(key, "ID3")) { // handle ID3 tag
             get_id3_tag(s, len);
         } else {
             av_log(s, AV_LOG_VERBOSE, "Unsupported byte array in tag %s.\n", key);
         }
         goto finish;
72cad800
     case ASF_BOOL:
     case ASF_DWORD:
     case ASF_QWORD:
     case ASF_WORD: {
61f9ad2d
         uint64_t num = get_value(s->pb, type, type2_size);
d9293648
         snprintf(value, LEN, "%"PRIu64, num);
72cad800
         break;
     }
     case ASF_GUID:
84b721db
         av_log(s, AV_LOG_DEBUG, "Unsupported GUID value in tag %s.\n", key);
         goto finish;
72cad800
     default:
48a4ffa7
         av_log(s, AV_LOG_DEBUG,
                "Unsupported value type %d in tag %s.\n", type, key);
82704826
         goto finish;
20e2a7ae
     }
5cbd3b5d
     if (*value)
d2d67e42
         av_dict_set(&s->metadata, key, value, 0);
48a4ffa7
 
82704826
 finish:
fce44489
     av_freep(&value);
f59d8ff8
     avio_seek(s->pb, off + len, SEEK_SET);
20e2a7ae
 }
 
e5d4a953
 static int asf_read_file_properties(AVFormatContext *s, int64_t size)
 {
     ASFContext *asf = s->priv_data;
471fe57e
     AVIOContext *pb = s->pb;
e5d4a953
 
     ff_get_guid(pb, &asf->hdr.guid);
48a4ffa7
     asf->hdr.file_size   = avio_rl64(pb);
     asf->hdr.create_time = avio_rl64(pb);
e63a3628
     avio_rl64(pb);                               /* number of packets */
48a4ffa7
     asf->hdr.play_time   = avio_rl64(pb);
     asf->hdr.send_time   = avio_rl64(pb);
     asf->hdr.preroll     = avio_rl32(pb);
     asf->hdr.ignore      = avio_rl32(pb);
     asf->hdr.flags       = avio_rl32(pb);
     asf->hdr.min_pktsize = avio_rl32(pb);
     asf->hdr.max_pktsize = avio_rl32(pb);
     if (asf->hdr.min_pktsize >= (1U << 29))
6e57a02b
         return AVERROR_INVALIDDATA;
48a4ffa7
     asf->hdr.max_bitrate = avio_rl32(pb);
     s->packet_size       = asf->hdr.max_pktsize;
e5d4a953
 
     return 0;
 }
 
607f5fe5
 static int asf_read_stream_properties(AVFormatContext *s, int64_t size)
 {
     ASFContext *asf = s->priv_data;
471fe57e
     AVIOContext *pb = s->pb;
607f5fe5
     AVStream *st;
     ASFStream *asf_st;
     ff_asf_guid g;
     enum AVMediaType type;
     int type_specific_size, sizeX;
     unsigned int tag1;
     int64_t pos1, pos2, start_time;
48a4ffa7
     int test_for_ext_stream_audio, is_dvr_ms_audio = 0;
607f5fe5
 
     if (s->nb_streams == ASF_MAX_STREAMS) {
         av_log(s, AV_LOG_ERROR, "too many streams\n");
         return AVERROR(EINVAL);
     }
 
384c9c2f
     pos1 = avio_tell(pb);
607f5fe5
 
3b3bbdd3
     st = avformat_new_stream(s, NULL);
607f5fe5
     if (!st)
         return AVERROR(ENOMEM);
c3f9ebf7
     avpriv_set_pts_info(st, 32, 1, 1000); /* 32 bit pts in ms */
48a4ffa7
     start_time     = asf->hdr.preroll;
607f5fe5
 
48a4ffa7
     if (!(asf->hdr.flags & 0x01)) { // if we aren't streaming...
d8f27ece
         int64_t fsize = avio_size(pb);
e3fd263f
         if (fsize <= 0 || (int64_t)asf->hdr.file_size <= 0 ||
f902b0b2
             20*FFABS(fsize - (int64_t)asf->hdr.file_size) < FFMIN(fsize, asf->hdr.file_size))
d8f27ece
             st->duration = asf->hdr.play_time /
48a4ffa7
                        (10000000 / 1000) - start_time;
607f5fe5
     }
     ff_get_guid(pb, &g);
 
     test_for_ext_stream_audio = 0;
     if (!ff_guidcmp(&g, &ff_asf_audio_stream)) {
         type = AVMEDIA_TYPE_AUDIO;
     } else if (!ff_guidcmp(&g, &ff_asf_video_stream)) {
         type = AVMEDIA_TYPE_VIDEO;
     } else if (!ff_guidcmp(&g, &ff_asf_jfif_media)) {
48a4ffa7
         type                = AVMEDIA_TYPE_VIDEO;
36ef5369
         st->codec->codec_id = AV_CODEC_ID_MJPEG;
607f5fe5
     } else if (!ff_guidcmp(&g, &ff_asf_command_stream)) {
         type = AVMEDIA_TYPE_DATA;
     } else if (!ff_guidcmp(&g, &ff_asf_ext_stream_embed_stream_header)) {
         test_for_ext_stream_audio = 1;
48a4ffa7
         type                      = AVMEDIA_TYPE_UNKNOWN;
607f5fe5
     } else {
         return -1;
     }
     ff_get_guid(pb, &g);
e65ab9d9
     avio_skip(pb, 8); /* total_size */
e63a3628
     type_specific_size = avio_rl32(pb);
     avio_rl32(pb);
     st->id = avio_rl16(pb) & 0x7f; /* stream id */
607f5fe5
     // mapping of asf ID to AV stream ID;
     asf->asfid2avid[st->id] = s->nb_streams - 1;
cb6d02df
     asf_st = &asf->streams[st->id];
607f5fe5
 
e63a3628
     avio_rl32(pb);
607f5fe5
 
     if (test_for_ext_stream_audio) {
         ff_get_guid(pb, &g);
         if (!ff_guidcmp(&g, &ff_asf_ext_stream_audio_stream)) {
48a4ffa7
             type            = AVMEDIA_TYPE_AUDIO;
             is_dvr_ms_audio = 1;
607f5fe5
             ff_get_guid(pb, &g);
e63a3628
             avio_rl32(pb);
             avio_rl32(pb);
             avio_rl32(pb);
607f5fe5
             ff_get_guid(pb, &g);
e63a3628
             avio_rl32(pb);
607f5fe5
         }
     }
 
     st->codec->codec_type = type;
     if (type == AVMEDIA_TYPE_AUDIO) {
ba77fb61
         int ret = ff_get_wav_header(s, pb, st->codec, type_specific_size, 0);
ca402f32
         if (ret < 0)
             return ret;
607f5fe5
         if (is_dvr_ms_audio) {
             // codec_id and codec_tag are unreliable in dvr_ms
             // files. Set them later by probing stream.
fadf8459
             st->request_probe    = 1;
607f5fe5
             st->codec->codec_tag = 0;
         }
48a4ffa7
         if (st->codec->codec_id == AV_CODEC_ID_AAC)
607f5fe5
             st->need_parsing = AVSTREAM_PARSE_NONE;
48a4ffa7
         else
607f5fe5
             st->need_parsing = AVSTREAM_PARSE_FULL;
         /* We have to init the frame size at some point .... */
384c9c2f
         pos2 = avio_tell(pb);
607f5fe5
         if (size >= (pos2 + 8 - pos1 + 24)) {
48a4ffa7
             asf_st->ds_span        = avio_r8(pb);
e63a3628
             asf_st->ds_packet_size = avio_rl16(pb);
48a4ffa7
             asf_st->ds_chunk_size  = avio_rl16(pb);
             avio_rl16(pb);  // ds_data_size
             avio_r8(pb);    // ds_silence_data
607f5fe5
         }
         if (asf_st->ds_span > 1) {
48a4ffa7
             if (!asf_st->ds_chunk_size                                ||
                 (asf_st->ds_packet_size / asf_st->ds_chunk_size <= 1) ||
                 asf_st->ds_packet_size % asf_st->ds_chunk_size)
                 asf_st->ds_span = 0;  // disable descrambling
607f5fe5
         }
     } else if (type == AVMEDIA_TYPE_VIDEO &&
48a4ffa7
                size - (avio_tell(pb) - pos1 + 24) >= 51) {
e63a3628
         avio_rl32(pb);
         avio_rl32(pb);
         avio_r8(pb);
         avio_rl16(pb);        /* size */
48a4ffa7
         sizeX             = avio_rl32(pb); /* size */
         st->codec->width  = avio_rl32(pb);
e63a3628
         st->codec->height = avio_rl32(pb);
607f5fe5
         /* not available for asf */
e63a3628
         avio_rl16(pb); /* panes */
         st->codec->bits_per_coded_sample = avio_rl16(pb); /* depth */
48a4ffa7
         tag1                             = avio_rl32(pb);
45a8a02a
         avio_skip(pb, 20);
607f5fe5
         if (sizeX > 40) {
80aa89bd
             st->codec->extradata_size = ffio_limit(pb, sizeX - 40);
48a4ffa7
             st->codec->extradata      = av_mallocz(st->codec->extradata_size +
29d147c9
                                                    AV_INPUT_BUFFER_PADDING_SIZE);
81f231b5
             if (!st->codec->extradata)
                 return AVERROR(ENOMEM);
e63a3628
             avio_read(pb, st->codec->extradata, st->codec->extradata_size);
607f5fe5
         }
 
         /* Extract palette from extradata if bpp <= 8 */
         /* This code assumes that extradata contains only palette */
2f5df0b1
         /* This is true for all paletted codecs implemented in libavcodec */
607f5fe5
         if (st->codec->extradata_size && (st->codec->bits_per_coded_sample <= 8)) {
 #if HAVE_BIGENDIAN
6df5c528
             int i;
48a4ffa7
             for (i = 0; i < FFMIN(st->codec->extradata_size, AVPALETTE_SIZE) / 4; i++)
                 asf_st->palette[i] = av_bswap32(((uint32_t *)st->codec->extradata)[i]);
607f5fe5
 #else
2d8591c2
             memcpy(asf_st->palette, st->codec->extradata,
                    FFMIN(st->codec->extradata_size, AVPALETTE_SIZE));
607f5fe5
 #endif
2d8591c2
             asf_st->palette_changed = 1;
607f5fe5
         }
 
         st->codec->codec_tag = tag1;
48a4ffa7
         st->codec->codec_id  = ff_codec_get_id(ff_codec_bmp_tags, tag1);
         if (tag1 == MKTAG('D', 'V', 'R', ' ')) {
607f5fe5
             st->need_parsing = AVSTREAM_PARSE_FULL;
48a4ffa7
             /* issue658 contains wrong w/h and MS even puts a fake seq header
              * with wrong w/h in extradata while a correct one is in the stream.
              * maximum lameness */
             st->codec->width      =
607f5fe5
                 st->codec->height = 0;
             av_freep(&st->codec->extradata);
48a4ffa7
             st->codec->extradata_size = 0;
607f5fe5
         }
48a4ffa7
         if (st->codec->codec_id == AV_CODEC_ID_H264)
607f5fe5
             st->need_parsing = AVSTREAM_PARSE_FULL_ONCE;
72e4ceeb
         if (st->codec->codec_id == AV_CODEC_ID_MPEG4)
             st->need_parsing = AVSTREAM_PARSE_FULL_ONCE;
607f5fe5
     }
384c9c2f
     pos2 = avio_tell(pb);
45a8a02a
     avio_skip(pb, size - (pos2 - pos1 + 24));
607f5fe5
 
     return 0;
 }
 
e5d4a953
 static int asf_read_ext_stream_properties(AVFormatContext *s, int64_t size)
 {
     ASFContext *asf = s->priv_data;
471fe57e
     AVIOContext *pb = s->pb;
e5d4a953
     ff_asf_guid g;
     int ext_len, payload_ext_ct, stream_ct, i;
e65ab9d9
     uint32_t leak_rate, stream_num;
e5d4a953
     unsigned int stream_languageid_index;
 
e63a3628
     avio_rl64(pb); // starttime
     avio_rl64(pb); // endtime
     leak_rate = avio_rl32(pb); // leak-datarate
     avio_rl32(pb); // bucket-datasize
     avio_rl32(pb); // init-bucket-fullness
     avio_rl32(pb); // alt-leak-datarate
     avio_rl32(pb); // alt-bucket-datasize
     avio_rl32(pb); // alt-init-bucket-fullness
     avio_rl32(pb); // max-object-size
     avio_rl32(pb); // flags (reliable,seekable,no_cleanpoints?,resend-live-cleanpoints, rest of bits reserved)
     stream_num = avio_rl16(pb); // stream-num
 
     stream_languageid_index = avio_rl16(pb); // stream-language-id-index
e5d4a953
     if (stream_num < 128)
         asf->streams[stream_num].stream_language_index = stream_languageid_index;
 
e63a3628
     avio_rl64(pb); // avg frametime in 100ns units
48a4ffa7
     stream_ct      = avio_rl16(pb); // stream-name-count
     payload_ext_ct = avio_rl16(pb); // payload-extension-system-count
e5d4a953
 
2d8c76eb
     if (stream_num < 128) {
e5d4a953
         asf->stream_bitrates[stream_num] = leak_rate;
2d8c76eb
         asf->streams[stream_num].payload_ext_ct = 0;
     }
e5d4a953
 
48a4ffa7
     for (i = 0; i < stream_ct; i++) {
e63a3628
         avio_rl16(pb);
         ext_len = avio_rl16(pb);
45a8a02a
         avio_skip(pb, ext_len);
e5d4a953
     }
 
48a4ffa7
     for (i = 0; i < payload_ext_ct; i++) {
2d8c76eb
         int size;
e5d4a953
         ff_get_guid(pb, &g);
2d8c76eb
         size = avio_rl16(pb);
48a4ffa7
         ext_len = avio_rl32(pb);
45a8a02a
         avio_skip(pb, ext_len);
2d8c76eb
         if (stream_num < 128 && i < FF_ARRAY_ELEMS(asf->streams[stream_num].payload)) {
             ASFPayload *p = &asf->streams[stream_num].payload[i];
             p->type = g[0];
             p->size = size;
             av_log(s, AV_LOG_DEBUG, "Payload extension %x %d\n", g[0], p->size );
             asf->streams[stream_num].payload_ext_ct ++;
         }
e5d4a953
     }
 
     return 0;
 }
 
 static int asf_read_content_desc(AVFormatContext *s, int64_t size)
 {
471fe57e
     AVIOContext *pb = s->pb;
e5d4a953
     int len1, len2, len3, len4, len5;
 
e63a3628
     len1 = avio_rl16(pb);
     len2 = avio_rl16(pb);
     len3 = avio_rl16(pb);
     len4 = avio_rl16(pb);
     len5 = avio_rl16(pb);
61f9ad2d
     get_tag(s, "title", 0, len1, 32);
     get_tag(s, "author", 0, len2, 32);
     get_tag(s, "copyright", 0, len3, 32);
     get_tag(s, "comment", 0, len4, 32);
45a8a02a
     avio_skip(pb, len5);
e5d4a953
 
     return 0;
 }
 
 static int asf_read_ext_content_desc(AVFormatContext *s, int64_t size)
 {
471fe57e
     AVIOContext *pb = s->pb;
e5d4a953
     ASFContext *asf = s->priv_data;
     int desc_count, i, ret;
 
e63a3628
     desc_count = avio_rl16(pb);
48a4ffa7
     for (i = 0; i < desc_count; i++) {
         int name_len, value_type, value_len;
e5d4a953
         char name[1024];
 
e63a3628
         name_len = avio_rl16(pb);
48a4ffa7
         if (name_len % 2)   // must be even, broken lavf versions wrote len-1
e5d4a953
             name_len += 1;
         if ((ret = avio_get_str16le(pb, name_len, name, sizeof(name))) < name_len)
45a8a02a
             avio_skip(pb, name_len - ret);
e63a3628
         value_type = avio_rl16(pb);
         value_len  = avio_rl16(pb);
48a4ffa7
         if (!value_type && value_len % 2)
e5d4a953
             value_len += 1;
48a4ffa7
         /* My sample has that stream set to 0 maybe that mean the container.
          * ASF stream count starts at 1. I am using 0 to the container value
          * since it's unused. */
         if (!strcmp(name, "AspectRatioX"))
61f9ad2d
             asf->dar[0].num = get_value(s->pb, value_type, 32);
48a4ffa7
         else if (!strcmp(name, "AspectRatioY"))
61f9ad2d
             asf->dar[0].den = get_value(s->pb, value_type, 32);
48a4ffa7
         else
61f9ad2d
             get_tag(s, name, value_type, value_len, 32);
e5d4a953
     }
 
     return 0;
 }
 
 static int asf_read_language_list(AVFormatContext *s, int64_t size)
 {
471fe57e
     AVIOContext *pb = s->pb;
e5d4a953
     ASFContext *asf = s->priv_data;
     int j, ret;
e63a3628
     int stream_count = avio_rl16(pb);
48a4ffa7
     for (j = 0; j < stream_count; j++) {
e5d4a953
         char lang[6];
e63a3628
         unsigned int lang_len = avio_r8(pb);
48a4ffa7
         if ((ret = avio_get_str16le(pb, lang_len, lang,
                                     sizeof(lang))) < lang_len)
45a8a02a
             avio_skip(pb, lang_len - ret);
e5d4a953
         if (j < 128)
48a4ffa7
             av_strlcpy(asf->stream_languages[j], lang,
                        sizeof(*asf->stream_languages));
e5d4a953
     }
 
     return 0;
 }
 
 static int asf_read_metadata(AVFormatContext *s, int64_t size)
 {
471fe57e
     AVIOContext *pb = s->pb;
e5d4a953
     ASFContext *asf = s->priv_data;
59fffefd
     int n, stream_num, name_len_utf16, name_len_utf8, value_len;
e5d4a953
     int ret, i;
e63a3628
     n = avio_rl16(pb);
e5d4a953
 
48a4ffa7
     for (i = 0; i < n; i++) {
59fffefd
         uint8_t *name;
61f9ad2d
         int value_type;
e5d4a953
 
48a4ffa7
         avio_rl16(pb);  // lang_list_index
         stream_num = avio_rl16(pb);
59fffefd
         name_len_utf16 = avio_rl16(pb);
72eaba5e
         value_type = avio_rl16(pb); /* value_type */
48a4ffa7
         value_len  = avio_rl32(pb);
e5d4a953
 
59fffefd
         name_len_utf8 = 2*name_len_utf16 + 1;
         name          = av_malloc(name_len_utf8);
         if (!name)
             return AVERROR(ENOMEM);
 
         if ((ret = avio_get_str16le(pb, name_len_utf16, name, name_len_utf8)) < name_len_utf16)
             avio_skip(pb, name_len_utf16 - ret);
1a3eb042
         av_log(s, AV_LOG_TRACE, "%d stream %d name_len %2d type %d len %4d <%s>\n",
59fffefd
                 i, stream_num, name_len_utf16, value_type, value_len, name);
61f9ad2d
 
         if (!strcmp(name, "AspectRatioX")){
             int aspect_x = get_value(s->pb, value_type, 16);
             if(stream_num < 128)
                 asf->dar[stream_num].num = aspect_x;
         } else if(!strcmp(name, "AspectRatioY")){
             int aspect_y = get_value(s->pb, value_type, 16);
             if(stream_num < 128)
                 asf->dar[stream_num].den = aspect_y;
         } else {
             get_tag(s, name, value_type, value_len, 16);
e5d4a953
         }
1f69b7ba
         av_freep(&name);
e5d4a953
     }
 
     return 0;
 }
 
 static int asf_read_marker(AVFormatContext *s, int64_t size)
 {
471fe57e
     AVIOContext *pb = s->pb;
5f408333
     ASFContext *asf = s->priv_data;
e5d4a953
     int i, count, name_len, ret;
     char name[1024];
 
e63a3628
     avio_rl64(pb);            // reserved 16 bytes
     avio_rl64(pb);            // ...
     count = avio_rl32(pb);    // markers count
     avio_rl16(pb);            // reserved 2 bytes
     name_len = avio_rl16(pb); // name length
48a4ffa7
     for (i = 0; i < name_len; i++)
e63a3628
         avio_r8(pb); // skip the name
e5d4a953
 
48a4ffa7
     for (i = 0; i < count; i++) {
e5d4a953
         int64_t pres_time;
         int name_len;
 
e63a3628
         avio_rl64(pb);             // offset, 8 bytes
         pres_time = avio_rl64(pb); // presentation time
5f408333
         pres_time -= asf->hdr.preroll * 10000;
e63a3628
         avio_rl16(pb);             // entry length
         avio_rl32(pb);             // send time
         avio_rl32(pb);             // flags
         name_len = avio_rl32(pb);  // name length
48a4ffa7
         if ((ret = avio_get_str16le(pb, name_len * 2, name,
                                     sizeof(name))) < name_len)
45a8a02a
             avio_skip(pb, name_len - ret);
48a4ffa7
         avpriv_new_chapter(s, i, (AVRational) { 1, 10000000 }, pres_time,
                            AV_NOPTS_VALUE, name);
e5d4a953
     }
 
     return 0;
 }
 
6e9651d1
 static int asf_read_header(AVFormatContext *s)
de6d9b64
 {
c9a65ca8
     ASFContext *asf = s->priv_data;
b8b00d94
     ff_asf_guid g;
471fe57e
     AVIOContext *pb = s->pb;
4ca29c65
     int i;
0c1a9eda
     int64_t gsize;
de6d9b64
 
a750050f
     ff_get_guid(pb, &g);
     if (ff_guidcmp(&g, &ff_asf_header))
a5c1a0c0
         return AVERROR_INVALIDDATA;
e63a3628
     avio_rl64(pb);
     avio_rl32(pb);
     avio_r8(pb);
     avio_r8(pb);
2141dc37
     memset(&asf->asfid2avid, -1, sizeof(asf->asfid2avid));
cb6d02df
 
     for (i = 0; i<128; i++)
         asf->streams[i].stream_language_index = 128; // invalid stream index means no language info
 
48a4ffa7
     for (;;) {
         uint64_t gpos = avio_tell(pb);
c8eca438
         int ret = 0;
a750050f
         ff_get_guid(pb, &g);
e63a3628
         gsize = avio_rl64(pb);
de6d9b64
         print_guid(&g);
a750050f
         if (!ff_guidcmp(&g, &ff_asf_data_header)) {
384c9c2f
             asf->data_object_offset = avio_tell(pb);
48a4ffa7
             /* If not streaming, gsize is not unlimited (how?),
              * and there is enough space in the file.. */
             if (!(asf->hdr.flags & 0x01) && gsize >= 100)
09d9672a
                 asf->data_object_size = gsize - 24;
48a4ffa7
             else
09d9672a
                 asf->data_object_size = (uint64_t)-1;
             break;
         }
de6d9b64
         if (gsize < 24)
a5c1a0c0
             return AVERROR_INVALIDDATA;
a750050f
         if (!ff_guidcmp(&g, &ff_asf_file_header)) {
c8eca438
             ret = asf_read_file_properties(s, gsize);
a750050f
         } else if (!ff_guidcmp(&g, &ff_asf_stream_header)) {
c8eca438
             ret = asf_read_stream_properties(s, gsize);
a750050f
         } else if (!ff_guidcmp(&g, &ff_asf_comment_header)) {
e5d4a953
             asf_read_content_desc(s, gsize);
a750050f
         } else if (!ff_guidcmp(&g, &ff_asf_language_guid)) {
e5d4a953
             asf_read_language_list(s, gsize);
a750050f
         } else if (!ff_guidcmp(&g, &ff_asf_extended_content_header)) {
e5d4a953
             asf_read_ext_content_desc(s, gsize);
a750050f
         } else if (!ff_guidcmp(&g, &ff_asf_metadata_header)) {
e5d4a953
             asf_read_metadata(s, gsize);
84b721db
         } else if (!ff_guidcmp(&g, &ff_asf_metadata_library_header)) {
             asf_read_metadata(s, gsize);
a750050f
         } else if (!ff_guidcmp(&g, &ff_asf_ext_stream_header)) {
e5d4a953
             asf_read_ext_stream_properties(s, gsize);
88141c91
 
             // there could be a optional stream properties object to follow
             // if so the next iteration will pick it up
1d4c1c3b
             continue;
a750050f
         } else if (!ff_guidcmp(&g, &ff_asf_head1_guid)) {
             ff_get_guid(pb, &g);
e65ab9d9
             avio_skip(pb, 6);
1d4c1c3b
             continue;
a750050f
         } else if (!ff_guidcmp(&g, &ff_asf_marker_header)) {
e5d4a953
             asf_read_marker(s, gsize);
d34ec64a
         } else if (avio_feof(pb)) {
a5c1a0c0
             return AVERROR_EOF;
de6d9b64
         } else {
febd1c90
             if (!s->keylen) {
a750050f
                 if (!ff_guidcmp(&g, &ff_asf_content_encryption)) {
2eaa5537
                     unsigned int len;
                     AVPacket pkt;
48a4ffa7
                     av_log(s, AV_LOG_WARNING,
                            "DRM protected stream detected, decoding will likely fail!\n");
2eaa5537
                     len= avio_rl32(pb);
                     av_log(s, AV_LOG_DEBUG, "Secret data:\n");
ab161bfa
 
                     if ((ret = av_get_packet(pb, &pkt, len)) < 0)
                         return ret;
                     av_hex_dump_log(s, AV_LOG_DEBUG, pkt.data, pkt.size);
                     av_free_packet(&pkt);
2eaa5537
                     len= avio_rl32(pb);
3600049d
                     get_tag(s, "ASF_Protection_Type", -1, len, 32);
2eaa5537
                     len= avio_rl32(pb);
3600049d
                     get_tag(s, "ASF_Key_ID", -1, len, 32);
2eaa5537
                     len= avio_rl32(pb);
3600049d
                     get_tag(s, "ASF_License_URL", -1, len, 32);
a750050f
                 } else if (!ff_guidcmp(&g, &ff_asf_ext_content_encryption)) {
48a4ffa7
                     av_log(s, AV_LOG_WARNING,
                            "Ext DRM protected stream detected, decoding will likely fail!\n");
410c06d2
                     av_dict_set(&s->metadata, "encryption", "ASF Extended Content Encryption", 0);
a750050f
                 } else if (!ff_guidcmp(&g, &ff_asf_digital_signature)) {
6322a31d
                     av_log(s, AV_LOG_INFO, "Digital signature detected!\n");
febd1c90
                 }
             }
de6d9b64
         }
c8eca438
         if (ret < 0)
             return ret;
 
48a4ffa7
         if (avio_tell(pb) != gpos + gsize)
             av_log(s, AV_LOG_DEBUG,
                    "gpos mismatch our pos=%"PRIu64", end=%"PRId64"\n",
                    avio_tell(pb) - gpos, gsize);
f59d8ff8
         avio_seek(pb, gpos + gsize, SEEK_SET);
de6d9b64
     }
a750050f
     ff_get_guid(pb, &g);
e63a3628
     avio_rl64(pb);
     avio_r8(pb);
     avio_r8(pb);
d34ec64a
     if (avio_feof(pb))
a5c1a0c0
         return AVERROR_EOF;
48a4ffa7
     asf->data_offset      = avio_tell(pb);
de6d9b64
     asf->packet_size_left = 0;
 
48a4ffa7
     for (i = 0; i < 128; i++) {
         int stream_num = asf->asfid2avid[i];
         if (stream_num >= 0) {
59729451
             AVStream *st = s->streams[stream_num];
             if (!st->codec->bit_rate)
56a67a8d
                 st->codec->bit_rate = asf->stream_bitrates[i];
48a4ffa7
             if (asf->dar[i].num > 0 && asf->dar[i].den > 0) {
e5927910
                 av_reduce(&st->sample_aspect_ratio.num,
                           &st->sample_aspect_ratio.den,
26783e85
                           asf->dar[i].num, asf->dar[i].den, INT_MAX);
48a4ffa7
             } else if ((asf->dar[0].num > 0) && (asf->dar[0].den > 0) &&
                        // Use ASF container value if the stream doesn't set AR.
                        (st->codec->codec_type == AVMEDIA_TYPE_VIDEO))
e5927910
                 av_reduce(&st->sample_aspect_ratio.num,
                           &st->sample_aspect_ratio.den,
26783e85
                           asf->dar[0].num, asf->dar[0].den, INT_MAX);
6ac6e3d1
 
1a3eb042
             av_log(s, AV_LOG_TRACE, "i=%d, st->codec->codec_type:%d, asf->dar %d:%d sar=%d:%d\n",
72eaba5e
                     i, st->codec->codec_type, asf->dar[i].num, asf->dar[i].den,
                     st->sample_aspect_ratio.num, st->sample_aspect_ratio.den);
5f1ac36d
 
             // copy and convert language codes to the frontend
             if (asf->streams[i].stream_language_index < 128) {
                 const char *rfc1766 = asf->stream_languages[asf->streams[i].stream_language_index];
                 if (rfc1766 && strlen(rfc1766) > 1) {
                     const char primary_tag[3] = { rfc1766[0], rfc1766[1], '\0' }; // ignore country code if any
48a4ffa7
                     const char *iso6392       = av_convert_lang_to(primary_tag,
                                                                    AV_LANG_ISO639_2_BIBL);
5f1ac36d
                     if (iso6392)
d2d67e42
                         av_dict_set(&st->metadata, "language", iso6392, 0);
5f1ac36d
                 }
             }
30e88789
         }
     }
 
ad7768f4
     ff_metadata_conv(&s->metadata, NULL, ff_asf_metadata_conv);
03700d39
 
de6d9b64
     return 0;
 }
 
48a4ffa7
 #define DO_2BITS(bits, var, defval)             \
     switch (bits & 3) {                         \
     case 3:                                     \
         var = avio_rl32(pb);                    \
         rsize += 4;                             \
         break;                                  \
     case 2:                                     \
         var = avio_rl16(pb);                    \
         rsize += 2;                             \
         break;                                  \
     case 1:                                     \
         var = avio_r8(pb);                      \
         rsize++;                                \
         break;                                  \
     default:                                    \
         var = defval;                           \
         break;                                  \
2a10020b
     }
 
277a28e8
 /**
  * Load a single ASF packet into the demuxer.
  * @param s demux context
  * @param pb context to read data from
32e543f8
  * @return 0 on success, <0 on error
277a28e8
  */
e926b5ce
 static int asf_get_packet(AVFormatContext *s, AVIOContext *pb)
de6d9b64
 {
     ASFContext *asf = s->priv_data;
2a10020b
     uint32_t packet_length, padsize;
0c0d17f3
     int rsize = 8;
0fd9e6f3
     int c, d, e, off;
 
9837d3b0
     if (asf->uses_std_ecc > 0) {
5d79a073
         // if we do not know packet size, allow skipping up to 32 kB
         off = 32768;
         if (asf->no_resync_search)
             off = 3;
9837d3b0
 //         else if (s->packet_size > 0 && !asf->uses_std_ecc)
 //             off = (avio_tell(pb) - s->internal->data_offset) % s->packet_size + 3;
5d79a073
 
         c = d = e = -1;
         while (off-- > 0) {
             c = d;
             d = e;
             e = avio_r8(pb);
             if (c == 0x82 && !d && !e)
                 break;
         }
115329f1
 
5d79a073
         if (c != 0x82) {
             /* This code allows handling of -EAGAIN at packet boundaries (i.e.
             * if the packet sync code above triggers -EAGAIN). This does not
             * imply complete -EAGAIN handling support at random positions in
             * the stream. */
             if (pb->error == AVERROR(EAGAIN))
                 return AVERROR(EAGAIN);
d34ec64a
             if (!avio_feof(pb))
5d79a073
                 av_log(s, AV_LOG_ERROR,
                     "ff asf bad header %x  at:%"PRId64"\n", c, avio_tell(pb));
bb270c08
         }
5d79a073
         if ((c & 0x8f) == 0x82) {
             if (d || e) {
                 if (!avio_feof(pb))
                     av_log(s, AV_LOG_ERROR, "ff asf bad non zero\n");
                 return AVERROR_INVALIDDATA;
             }
             c      = avio_r8(pb);
             d      = avio_r8(pb);
             rsize += 3;
         } else if(!avio_feof(pb)) {
             avio_seek(pb, -1, SEEK_CUR); // FIXME
         }
     } else {
         c = avio_r8(pb);
9837d3b0
         if (c & 0x80) {
             rsize ++;
             if (!(c & 0x60)) {
                 d = avio_r8(pb);
                 e = avio_r8(pb);
                 avio_seek(pb, (c & 0xF) - 2, SEEK_CUR);
                 rsize += c & 0xF;
             }
 
             if (c != 0x82)
                 avpriv_request_sample(s, "Invalid ECC byte\n");
 
             if (!asf->uses_std_ecc)
                 asf->uses_std_ecc =  (c == 0x82 && !d && !e) ? 1 : -1;
 
             c = avio_r8(pb);
         } else
             asf->uses_std_ecc =  -1;
5d79a073
         d = avio_r8(pb);
de6d9b64
     }
2a10020b
 
0c0d17f3
     asf->packet_flags    = c;
     asf->packet_property = d;
2a10020b
 
91d19d47
     DO_2BITS(asf->packet_flags >> 5, packet_length, s->packet_size);
2a10020b
     DO_2BITS(asf->packet_flags >> 1, padsize, 0); // sequence ignored
     DO_2BITS(asf->packet_flags >> 3, padsize, 0); // padding length
 
48a4ffa7
     // the following checks prevent overflows and infinite loops
     if (!packet_length || packet_length >= (1U << 29)) {
         av_log(s, AV_LOG_ERROR,
d92024f1
                "invalid packet_length %"PRIu32" at:%"PRId64"\n",
48a4ffa7
                packet_length, avio_tell(pb));
a5c1a0c0
         return AVERROR_INVALIDDATA;
5b11e081
     }
48a4ffa7
     if (padsize >= packet_length) {
         av_log(s, AV_LOG_ERROR,
d92024f1
                "invalid padsize %"PRIu32" at:%"PRId64"\n", padsize, avio_tell(pb));
a5c1a0c0
         return AVERROR_INVALIDDATA;
5b11e081
     }
 
e63a3628
     asf->packet_timestamp = avio_rl32(pb);
     avio_rl16(pb); /* duration */
2141dc37
     // rsize has at least 11 bytes which have to be present
2a10020b
 
     if (asf->packet_flags & 0x01) {
48a4ffa7
         asf->packet_segsizetype = avio_r8(pb);
         rsize++;
2a10020b
         asf->packet_segments = asf->packet_segsizetype & 0x3f;
     } else {
48a4ffa7
         asf->packet_segments    = 1;
2a10020b
         asf->packet_segsizetype = 0x80;
     }
41afac7f
     if (rsize > packet_length - padsize) {
         asf->packet_size_left = 0;
         av_log(s, AV_LOG_ERROR,
d92024f1
                "invalid packet header length %d for pktlen %"PRIu32"-%"PRIu32" at %"PRId64"\n",
41afac7f
                rsize, packet_length, padsize, avio_tell(pb));
a5c1a0c0
         return AVERROR_INVALIDDATA;
41afac7f
     }
2a10020b
     asf->packet_size_left = packet_length - padsize - rsize;
acbe6cfa
     if (packet_length < asf->hdr.min_pktsize)
         padsize += asf->hdr.min_pktsize - packet_length;
2a10020b
     asf->packet_padsize = padsize;
1a3eb042
     av_log(s, AV_LOG_TRACE, "packet: size=%d padsize=%d  left=%d\n",
48a4ffa7
             s->packet_size, asf->packet_padsize, asf->packet_size_left);
de6d9b64
     return 0;
 }
 
ae60a857
 /**
  *
  * @return <0 if error
  */
48a4ffa7
 static int asf_read_frame_header(AVFormatContext *s, AVIOContext *pb)
 {
ae60a857
     ASFContext *asf = s->priv_data;
8c93269e
     ASFStream *asfst;
48a4ffa7
     int rsize       = 1;
     int num         = avio_r8(pb);
8c93269e
     int i;
53cb0de2
     int64_t ts0, ts1 av_unused;
ae60a857
 
     asf->packet_segments--;
     asf->packet_key_frame = num >> 7;
48a4ffa7
     asf->stream_index     = asf->asfid2avid[num & 0x7f];
fadf8459
     asfst                 = &asf->streams[num & 0x7f];
ae60a857
     // sequence should be ignored!
     DO_2BITS(asf->packet_property >> 4, asf->packet_seq, 0);
     DO_2BITS(asf->packet_property >> 2, asf->packet_frag_offset, 0);
     DO_2BITS(asf->packet_property, asf->packet_replic_size, 0);
385eb066
     av_log(asf, AV_LOG_TRACE, "key:%d stream:%d seq:%d offset:%d replic_size:%d num:%X packet_property %X\n",
72eaba5e
             asf->packet_key_frame, asf->stream_index, asf->packet_seq,
385eb066
             asf->packet_frag_offset, asf->packet_replic_size, num, asf->packet_property);
fe6767f8
     if (rsize+(int64_t)asf->packet_replic_size > asf->packet_size_left) {
60fcc19b
         av_log(s, AV_LOG_ERROR, "packet_replic_size %d is invalid\n", asf->packet_replic_size);
a5c1a0c0
         return AVERROR_INVALIDDATA;
60fcc19b
     }
ae60a857
     if (asf->packet_replic_size >= 8) {
8c93269e
         int64_t end = avio_tell(pb) + asf->packet_replic_size;
343c73e2
         AVRational aspect;
465aa53f
         asfst->packet_obj_size = avio_rl32(pb);
4ccd2b31
         if (asfst->packet_obj_size >= (1 << 24) || asfst->packet_obj_size < 0) {
be4e1f28
             av_log(s, AV_LOG_ERROR, "packet_obj_size %d invalid\n", asfst->packet_obj_size);
465aa53f
             asfst->packet_obj_size = 0;
a5c1a0c0
             return AVERROR_INVALIDDATA;
ae60a857
         }
e63a3628
         asf->packet_frag_timestamp = avio_rl32(pb); // timestamp
8c93269e
 
fadf8459
         for (i = 0; i < asfst->payload_ext_ct; i++) {
8c93269e
             ASFPayload *p = &asfst->payload[i];
             int size = p->size;
             int64_t payend;
fadf8459
             if (size == 0xFFFF)
8c93269e
                 size = avio_rl16(pb);
             payend = avio_tell(pb) + size;
             if (payend > end) {
                 av_log(s, AV_LOG_ERROR, "too long payload\n");
                 break;
             }
fadf8459
             switch (p->type) {
8c93269e
             case 0x50:
 //              duration = avio_rl16(pb);
                 break;
343c73e2
             case 0x54:
                 aspect.num = avio_r8(pb);
                 aspect.den = avio_r8(pb);
b7280cff
                 if (aspect.num > 0 && aspect.den > 0 && asf->stream_index >= 0) {
343c73e2
                     s->streams[asf->stream_index]->sample_aspect_ratio = aspect;
                 }
                 break;
8c93269e
             case 0x2A:
                 avio_skip(pb, 8);
fadf8459
                 ts0 = avio_rl64(pb);
                 ts1 = avio_rl64(pb);
                 if (ts0!= -1) asf->packet_frag_timestamp = ts0/10000;
                 else          asf->packet_frag_timestamp = AV_NOPTS_VALUE;
4eb13cdf
                 asf->ts_is_pts = 1;
8c93269e
                 break;
             case 0x5B:
             case 0xB7:
             case 0xCC:
             case 0xC0:
             case 0xA0:
                 //unknown
                 break;
             }
             avio_seek(pb, payend, SEEK_SET);
         }
 
         avio_seek(pb, end, SEEK_SET);
ae60a857
         rsize += asf->packet_replic_size; // FIXME - check validity
48a4ffa7
     } else if (asf->packet_replic_size == 1) {
efc90ebf
         // multipacket - frag_offset is beginning timestamp
48a4ffa7
         asf->packet_time_start     = asf->packet_frag_offset;
         asf->packet_frag_offset    = 0;
ae60a857
         asf->packet_frag_timestamp = asf->packet_timestamp;
 
e63a3628
         asf->packet_time_delta = avio_r8(pb);
ae60a857
         rsize++;
48a4ffa7
     } else if (asf->packet_replic_size != 0) {
         av_log(s, AV_LOG_ERROR, "unexpected packet_replic_size of %d\n",
                asf->packet_replic_size);
a5c1a0c0
         return AVERROR_INVALIDDATA;
ae60a857
     }
     if (asf->packet_flags & 0x01) {
         DO_2BITS(asf->packet_segsizetype >> 6, asf->packet_frag_size, 0); // 0 is illegal
29fa570d
         if (rsize > asf->packet_size_left) {
             av_log(s, AV_LOG_ERROR, "packet_replic_size is invalid\n");
a5c1a0c0
             return AVERROR_INVALIDDATA;
48a4ffa7
         } else if (asf->packet_frag_size > asf->packet_size_left - rsize) {
f8b12459
             if (asf->packet_frag_size > asf->packet_size_left - rsize + asf->packet_padsize) {
385eb066
                 av_log(s, AV_LOG_ERROR, "packet_frag_size is invalid (%d>%d-%d+%d)\n",
                        asf->packet_frag_size, asf->packet_size_left, rsize, asf->packet_padsize);
a5c1a0c0
                 return AVERROR_INVALIDDATA;
f8b12459
             } else {
                 int diff = asf->packet_frag_size - (asf->packet_size_left - rsize);
                 asf->packet_size_left += diff;
                 asf->packet_padsize   -= diff;
             }
13f7e4b9
         }
ae60a857
     } else {
         asf->packet_frag_size = asf->packet_size_left - rsize;
     }
     if (asf->packet_replic_size == 1) {
         asf->packet_multi_size = asf->packet_frag_size;
         if (asf->packet_multi_size > asf->packet_size_left)
a5c1a0c0
             return AVERROR_INVALIDDATA;
ae60a857
     }
     asf->packet_size_left -= rsize;
 
     return 0;
 }
 
277a28e8
 /**
  * Parse data from individual ASF packets (which were previously loaded
  * with asf_get_packet()).
  * @param s demux context
  * @param pb context to read data from
  * @param pkt pointer to store packet data into
32e543f8
  * @return 0 if data was stored in pkt, <0 on error or 1 if more ASF
277a28e8
  *          packets need to be loaded (through asf_get_packet())
  */
e926b5ce
 static int asf_parse_packet(AVFormatContext *s, AVIOContext *pb, AVPacket *pkt)
de6d9b64
 {
48a4ffa7
     ASFContext *asf   = s->priv_data;
2a10020b
     ASFStream *asf_st = 0;
     for (;;) {
4172951b
         int ret;
d34ec64a
         if (avio_feof(pb))
799a0722
             return AVERROR_EOF;
2db1bcf1
         if (asf->packet_size_left < FRAME_HEADER_SIZE ||
             asf->packet_segments < 1 && asf->packet_time_start == 0) {
bb270c08
             int ret = asf->packet_size_left + asf->packet_padsize;
292a08cb
 
a5f617e9
             if (asf->packet_size_left && asf->packet_size_left < FRAME_HEADER_SIZE)
                 av_log(s, AV_LOG_WARNING, "Skip due to FRAME_HEADER_SIZE\n");
 
292a08cb
             assert(ret >= 0);
bb270c08
             /* fail safe */
45a8a02a
             avio_skip(pb, ret);
b04d5d31
 
48a4ffa7
             asf->packet_pos = avio_tell(pb);
b6eaae39
             if (asf->data_object_size != (uint64_t)-1 &&
                 (asf->packet_pos - asf->data_object_offset >= asf->data_object_size))
48a4ffa7
                 return AVERROR_EOF;  /* Do not exceed the size of the data object */
f27544fd
             return 1;
bb270c08
         }
         if (asf->packet_time_start == 0) {
292a08cb
             if (asf_read_frame_header(s, pb) < 0) {
edf7d15e
                 asf->packet_time_start = asf->packet_segments = 0;
236116cb
                 continue;
1305a9d5
             }
292a08cb
             if (asf->stream_index < 0 ||
                 s->streams[asf->stream_index]->discard >= AVDISCARD_ALL ||
                 (!asf->packet_key_frame &&
d6686149
                  (s->streams[asf->stream_index]->discard >= AVDISCARD_NONKEY || asf->streams[s->streams[asf->stream_index]->id].skip_to_key))) {
1359c2d4
                 asf->packet_time_start = 0;
bb270c08
                 /* unhandled packet (should not happen) */
45a8a02a
                 avio_skip(pb, asf->packet_frag_size);
bb270c08
                 asf->packet_size_left -= asf->packet_frag_size;
292a08cb
                 if (asf->stream_index < 0)
48a4ffa7
                     av_log(s, AV_LOG_ERROR, "ff asf skip %d (unknown stream)\n",
                            asf->packet_frag_size);
1359c2d4
                 continue;
bb270c08
             }
cb6d02df
             asf->asf_st = &asf->streams[s->streams[asf->stream_index]->id];
28206b75
             if (!asf->packet_frag_offset)
                 asf->asf_st->skip_to_key = 0;
bb270c08
         }
         asf_st = asf->asf_st;
1ef0e8a6
         av_assert0(asf_st);
bb270c08
 
f5d92d9c
         if (!asf_st->frag_offset && asf->packet_frag_offset) {
1a3eb042
             av_log(s, AV_LOG_TRACE, "skipping asf data pkt with fragment offset for "
f5d92d9c
                     "stream:%d, expected:%d but got %d from pkt)\n",
                     asf->stream_index, asf_st->frag_offset,
                     asf->packet_frag_offset);
             avio_skip(pb, asf->packet_frag_size);
             asf->packet_size_left -= asf->packet_frag_size;
             continue;
         }
 
bb270c08
         if (asf->packet_replic_size == 1) {
efc90ebf
             // frag_offset is here used as the beginning timestamp
bb270c08
             asf->packet_frag_timestamp = asf->packet_time_start;
292a08cb
             asf->packet_time_start    += asf->packet_time_delta;
465aa53f
             asf_st->packet_obj_size    = asf->packet_frag_size = avio_r8(pb);
bb270c08
             asf->packet_size_left--;
2141dc37
             asf->packet_multi_size--;
465aa53f
             if (asf->packet_multi_size < asf_st->packet_obj_size) {
bb270c08
                 asf->packet_time_start = 0;
45a8a02a
                 avio_skip(pb, asf->packet_multi_size);
bb270c08
                 asf->packet_size_left -= asf->packet_multi_size;
2141dc37
                 continue;
bb270c08
             }
465aa53f
             asf->packet_multi_size -= asf_st->packet_obj_size;
bb270c08
         }
60ff1c44
 
465aa53f
         if (asf_st->pkt.size != asf_st->packet_obj_size ||
48a4ffa7
             // FIXME is this condition sufficient?
292a08cb
             asf_st->frag_offset + asf->packet_frag_size > asf_st->pkt.size) {
20760955
             int ret;
 
292a08cb
             if (asf_st->pkt.data) {
48a4ffa7
                 av_log(s, AV_LOG_INFO,
                        "freeing incomplete packet size %d, new %d\n",
465aa53f
                        asf_st->pkt.size, asf_st->packet_obj_size);
200026aa
                 asf_st->frag_offset = 0;
                 av_free_packet(&asf_st->pkt);
             }
bb270c08
             /* new packet */
20760955
             if ((ret = av_new_packet(&asf_st->pkt, asf_st->packet_obj_size)) < 0)
                 return ret;
292a08cb
             asf_st->seq              = asf->packet_seq;
4eb13cdf
             if (asf->ts_is_pts) {
                 asf_st->pkt.pts          = asf->packet_frag_timestamp - asf->hdr.preroll;
             } else
                 asf_st->pkt.dts          = asf->packet_frag_timestamp - asf->hdr.preroll;
bb270c08
             asf_st->pkt.stream_index = asf->stream_index;
292a08cb
             asf_st->pkt.pos          = asf_st->packet_pos = asf->packet_pos;
f5cf0ea9
             asf_st->pkt_clean        = 0;
292a08cb
 
2d8591c2
             if (asf_st->pkt.data && asf_st->palette_changed) {
                 uint8_t *pal;
e9dc9201
                 pal = av_packet_new_side_data(&asf_st->pkt, AV_PKT_DATA_PALETTE,
2d8591c2
                                               AVPALETTE_SIZE);
                 if (!pal) {
                     av_log(s, AV_LOG_ERROR, "Cannot append palette to packet\n");
                 } else {
                     memcpy(pal, asf_st->palette, AVPALETTE_SIZE);
                     asf_st->palette_changed = 0;
                 }
             }
1a3eb042
             av_log(asf, AV_LOG_TRACE, "new packet: stream:%d key:%d packet_key:%d audio:%d size:%d\n",
72eaba5e
                     asf->stream_index, asf->packet_key_frame,
                     asf_st->pkt.flags & AV_PKT_FLAG_KEY,
                     s->streams[asf->stream_index]->codec->codec_type == AVMEDIA_TYPE_AUDIO,
465aa53f
                     asf_st->packet_obj_size);
72415b2a
             if (s->streams[asf->stream_index]->codec->codec_type == AVMEDIA_TYPE_AUDIO)
bb270c08
                 asf->packet_key_frame = 1;
             if (asf->packet_key_frame)
cc947f04
                 asf_st->pkt.flags |= AV_PKT_FLAG_KEY;
bb270c08
         }
 
         /* read data */
1a3eb042
         av_log(asf, AV_LOG_TRACE, "READ PACKET s:%d  os:%d  o:%d,%d  l:%d   DATA:%p\n",
72eaba5e
                 s->packet_size, asf_st->pkt.size, asf->packet_frag_offset,
                 asf_st->frag_offset, asf->packet_frag_size, asf_st->pkt.data);
bb270c08
         asf->packet_size_left -= asf->packet_frag_size;
         if (asf->packet_size_left < 0)
2141dc37
             continue;
4c71d727
 
292a08cb
         if (asf->packet_frag_offset >= asf_st->pkt.size ||
             asf->packet_frag_size > asf_st->pkt.size - asf->packet_frag_offset) {
48a4ffa7
             av_log(s, AV_LOG_ERROR,
                    "packet fragment position invalid %u,%u not in %u\n",
                    asf->packet_frag_offset, asf->packet_frag_size,
                    asf_st->pkt.size);
4c71d727
             continue;
         }
 
f5cf0ea9
         if (asf->packet_frag_offset != asf_st->frag_offset && !asf_st->pkt_clean) {
             memset(asf_st->pkt.data + asf_st->frag_offset, 0, asf_st->pkt.size - asf_st->frag_offset);
             asf_st->pkt_clean = 1;
         }
 
e63a3628
         ret = avio_read(pb, asf_st->pkt.data + asf->packet_frag_offset,
292a08cb
                         asf->packet_frag_size);
bf09a019
         if (ret != asf->packet_frag_size) {
             if (ret < 0 || asf->packet_frag_offset + ret == 0)
                 return ret < 0 ? ret : AVERROR_EOF;
292a08cb
 
bf09a019
             if (asf_st->ds_span > 1) {
                 // scrambling, we can either drop it completely or fill the remainder
                 // TODO: should we fill the whole packet instead of just the current
                 // fragment?
                 memset(asf_st->pkt.data + asf->packet_frag_offset + ret, 0,
                        asf->packet_frag_size - ret);
                 ret = asf->packet_frag_size;
292a08cb
             } else {
bf09a019
                 // no scrambling, so we can return partial packets
                 av_shrink_packet(&asf_st->pkt, asf->packet_frag_offset + ret);
292a08cb
             }
bf09a019
         }
72be7db4
         if (s->key && s->keylen == 20)
             ff_asfcrypt_dec(s->key, asf_st->pkt.data + asf->packet_frag_offset,
bf09a019
                             ret);
         asf_st->frag_offset += ret;
bb270c08
         /* test if whole packet is read */
         if (asf_st->frag_offset == asf_st->pkt.size) {
48a4ffa7
             // workaround for macroshit radio DVR-MS files
292a08cb
             if (s->streams[asf->stream_index]->codec->codec_id == AV_CODEC_ID_MPEG2VIDEO &&
                 asf_st->pkt.size > 100) {
da0b94f5
                 int i;
48a4ffa7
                 for (i = 0; i < asf_st->pkt.size && !asf_st->pkt.data[i]; i++)
                     ;
292a08cb
                 if (i == asf_st->pkt.size) {
da0b94f5
                     av_log(s, AV_LOG_DEBUG, "discarding ms fart\n");
                     asf_st->frag_offset = 0;
                     av_free_packet(&asf_st->pkt);
                     continue;
                 }
             }
 
bb270c08
             /* return packet */
             if (asf_st->ds_span > 1) {
48a4ffa7
                 if (asf_st->pkt.size != asf_st->ds_packet_size * asf_st->ds_span) {
                     av_log(s, AV_LOG_ERROR,
                            "pkt.size != ds_packet_size * ds_span (%d %d %d)\n",
                            asf_st->pkt.size, asf_st->ds_packet_size,
                            asf_st->ds_span);
292a08cb
                 } else {
                     /* packet descrambling */
1afddbe5
                     AVBufferRef *buf = av_buffer_alloc(asf_st->pkt.size +
29d147c9
                                                        AV_INPUT_BUFFER_PADDING_SIZE);
1afddbe5
                     if (buf) {
                         uint8_t *newdata = buf->data;
292a08cb
                         int offset = 0;
48a4ffa7
                         memset(newdata + asf_st->pkt.size, 0,
29d147c9
                                AV_INPUT_BUFFER_PADDING_SIZE);
292a08cb
                         while (offset < asf_st->pkt.size) {
                             int off = offset / asf_st->ds_chunk_size;
                             int row = off / asf_st->ds_span;
                             int col = off % asf_st->ds_span;
                             int idx = row + col * asf_st->ds_packet_size / asf_st->ds_chunk_size;
                             assert(offset + asf_st->ds_chunk_size <= asf_st->pkt.size);
48a4ffa7
                             assert(idx + 1 <= asf_st->pkt.size / asf_st->ds_chunk_size);
292a08cb
                             memcpy(newdata + offset,
                                    asf_st->pkt.data + idx * asf_st->ds_chunk_size,
                                    asf_st->ds_chunk_size);
                             offset += asf_st->ds_chunk_size;
                         }
1afddbe5
                         av_buffer_unref(&asf_st->pkt.buf);
                         asf_st->pkt.buf  = buf;
                         asf_st->pkt.data = buf->data;
bb270c08
                     }
                 }
             }
292a08cb
             asf_st->frag_offset         = 0;
             *pkt                        = asf_st->pkt;
1afddbe5
 #if FF_API_DESTRUCT_PACKET
7950e519
 FF_DISABLE_DEPRECATION_WARNINGS
1afddbe5
             asf_st->pkt.destruct        = NULL;
7950e519
 FF_ENABLE_DEPRECATION_WARNINGS
1afddbe5
 #endif
             asf_st->pkt.buf             = 0;
292a08cb
             asf_st->pkt.size            = 0;
             asf_st->pkt.data            = 0;
e73c6aaa
             asf_st->pkt.side_data_elems = 0;
292a08cb
             asf_st->pkt.side_data       = NULL;
bb270c08
             break; // packet completed
         }
de6d9b64
     }
     return 0;
 }
 
f27544fd
 static int asf_read_packet(AVFormatContext *s, AVPacket *pkt)
 {
     ASFContext *asf = s->priv_data;
 
     for (;;) {
         int ret;
 
         /* parse cached packets, if any */
e926b5ce
         if ((ret = asf_parse_packet(s, s->pb, pkt)) <= 0)
f27544fd
             return ret;
e926b5ce
         if ((ret = asf_get_packet(s, s->pb)) < 0)
48a4ffa7
             assert(asf->packet_size_left < FRAME_HEADER_SIZE ||
                    asf->packet_segments < 1);
f27544fd
         asf->packet_time_start = 0;
     }
 }
 
38376f00
 // Added to support seeking after packets have been read
 // If information is not reset, read_packet fails due to
 // leftover information from previous reads
 static void asf_reset_header(AVFormatContext *s)
 {
     ASFContext *asf = s->priv_data;
82b9e4a2
     ASFStream *asf_st;
     int i;
38376f00
 
48a4ffa7
     asf->packet_size_left      = 0;
     asf->packet_flags          = 0;
     asf->packet_property       = 0;
     asf->packet_timestamp      = 0;
     asf->packet_segsizetype    = 0;
     asf->packet_segments       = 0;
     asf->packet_seq            = 0;
     asf->packet_replic_size    = 0;
     asf->packet_key_frame      = 0;
     asf->packet_padsize        = 0;
     asf->packet_frag_offset    = 0;
     asf->packet_frag_size      = 0;
38376f00
     asf->packet_frag_timestamp = 0;
48a4ffa7
     asf->packet_multi_size     = 0;
     asf->packet_time_delta     = 0;
     asf->packet_time_start     = 0;
115329f1
 
cb6d02df
     for (i = 0; i < 128; i++) {
         asf_st = &asf->streams[i];
82b9e4a2
         av_free_packet(&asf_st->pkt);
465aa53f
         asf_st->packet_obj_size = 0;
48a4ffa7
         asf_st->frag_offset = 0;
         asf_st->seq         = 0;
82b9e4a2
     }
48a4ffa7
     asf->asf_st = NULL;
38376f00
 }
 
d6686149
 static void skip_to_key(AVFormatContext *s)
 {
     ASFContext *asf = s->priv_data;
     int i;
 
     for (i = 0; i < 128; i++) {
         int j = asf->asfid2avid[i];
         ASFStream *asf_st = &asf->streams[i];
         if (j < 0 || s->streams[j]->codec->codec_type != AVMEDIA_TYPE_VIDEO)
             continue;
 
         asf_st->skip_to_key = 1;
     }
 }
 
5d25d2a9
 static int asf_read_close(AVFormatContext *s)
 {
     asf_reset_header(s);
0b5ae1fd
 
5d25d2a9
     return 0;
 }
 
48a4ffa7
 static int64_t asf_read_pts(AVFormatContext *s, int stream_index,
                             int64_t *ppos, int64_t pos_limit)
38376f00
 {
cb6d02df
     ASFContext *asf     = s->priv_data;
38376f00
     AVPacket pkt1, *pkt = &pkt1;
82b9e4a2
     ASFStream *asf_st;
580fb5e7
     int64_t pts;
48a4ffa7
     int64_t pos = *ppos;
3e9245a9
     int i;
30cdfb49
     int64_t start_pos[ASF_MAX_STREAMS];
115329f1
 
48a4ffa7
     for (i = 0; i < s->nb_streams; i++)
         start_pos[i] = pos;
115329f1
 
68a10b40
     if (s->packet_size > 0)
9deaec78
         pos = (pos + s->packet_size - 1 - s->internal->data_offset) /
48a4ffa7
               s->packet_size * s->packet_size +
9deaec78
               s->internal->data_offset;
48a4ffa7
     *ppos = pos;
ac1d4893
     if (avio_seek(s->pb, pos, SEEK_SET) < 0)
         return AV_NOPTS_VALUE;
115329f1
 
4b101ab0
     ff_read_frame_flush(s);
82b9e4a2
     asf_reset_header(s);
48a4ffa7
     for (;;) {
fadf8459
         if (av_read_frame(s, pkt) < 0) {
0b93103a
             av_log(s, AV_LOG_INFO, "asf_read_pts failed\n");
bb270c08
             return AV_NOPTS_VALUE;
82b9e4a2
         }
115329f1
 
b88eb876
         pts = pkt->dts;
580fb5e7
 
         av_free_packet(pkt);
48a4ffa7
         if (pkt->flags & AV_PKT_FLAG_KEY) {
             i = pkt->stream_index;
3e9245a9
 
cb6d02df
             asf_st = &asf->streams[s->streams[i]->id];
3e9245a9
 
91d19d47
 //            assert((asf_st->packet_pos - s->data_offset) % s->packet_size == 0);
48a4ffa7
             pos = asf_st->packet_pos;
811008b8
             av_assert1(pkt->pos == asf_st->packet_pos);
09646bab
 
48a4ffa7
             av_add_index_entry(s->streams[i], pos, pts, pkt->size,
                                pos - start_pos[i] + 1, AVINDEX_KEYFRAME);
             start_pos[i] = asf_st->packet_pos + 1;
115329f1
 
48a4ffa7
             if (pkt->stream_index == stream_index)
                 break;
3e9245a9
         }
     }
 
48a4ffa7
     *ppos = pos;
580fb5e7
     return pts;
38376f00
 }
 
0ebb523f
 static int asf_build_simple_index(AVFormatContext *s, int stream_index)
56c96a22
 {
b8b00d94
     ff_asf_guid g;
48a4ffa7
     ASFContext *asf     = s->priv_data;
     int64_t current_pos = avio_tell(s->pb);
d4936d28
     int64_t ret;
56c96a22
 
c3204856
     if((ret = avio_seek(s->pb, asf->data_object_offset + asf->data_object_size, SEEK_SET)) < 0) {
         return ret;
6c9a2463
     }
ac1d4893
 
0ebb523f
     if ((ret = ff_get_guid(s->pb, &g)) < 0)
         goto end;
77b7c334
 
     /* the data object can be followed by other top-level objects,
48a4ffa7
      * skip them until the simple index object is reached */
b61e596a
     while (ff_guidcmp(&g, &ff_asf_simple_index_header)) {
48a4ffa7
         int64_t gsize = avio_rl64(s->pb);
d34ec64a
         if (gsize < 24 || avio_feof(s->pb)) {
0ebb523f
             goto end;
77b7c334
         }
48a4ffa7
         avio_skip(s->pb, gsize - 24);
0ebb523f
         if ((ret = ff_get_guid(s->pb, &g)) < 0)
             goto end;
77b7c334
     }
 
     {
48a4ffa7
         int64_t itime, last_pos = -1;
d728e3cd
         int pct, ict;
6003ec88
         int i;
48a4ffa7
         int64_t av_unused gsize = avio_rl64(s->pb);
0ebb523f
         if ((ret = ff_get_guid(s->pb, &g)) < 0)
             goto end;
48a4ffa7
         itime = avio_rl64(s->pb);
         pct   = avio_rl32(s->pb);
         ict   = avio_rl32(s->pb);
         av_log(s, AV_LOG_DEBUG,
                "itime:0x%"PRIx64", pct:%d, ict:%d\n", itime, pct, ict);
 
         for (i = 0; i < ict; i++) {
             int pktnum        = avio_rl32(s->pb);
             int pktct         = avio_rl16(s->pb);
9deaec78
             int64_t pos       = s->internal->data_offset + s->packet_size * (int64_t)pktnum;
48a4ffa7
             int64_t index_pts = FFMAX(av_rescale(itime, i, 10000) - asf->hdr.preroll, 0);
 
             if (pos != last_pos) {
                 av_log(s, AV_LOG_DEBUG, "pktnum:%d, pktct:%d  pts: %"PRId64"\n",
                        pktnum, pktct, index_pts);
                 av_add_index_entry(s->streams[stream_index], pos, index_pts,
                                    s->packet_size, 0, AVINDEX_KEYFRAME);
                 last_pos = pos;
134271c2
             }
56c96a22
         }
fadf8459
         asf->index_read = ict > 1;
56c96a22
     }
0ebb523f
 end:
d34ec64a
 //     if (avio_feof(s->pb)) {
5634c951
 //         ret = 0;
 //     }
f59d8ff8
     avio_seek(s->pb, current_pos, SEEK_SET);
0ebb523f
     return ret;
56c96a22
 }
 
48a4ffa7
 static int asf_read_seek(AVFormatContext *s, int stream_index,
                          int64_t pts, int flags)
2a10020b
 {
afda223c
     ASFContext *asf = s->priv_data;
48a4ffa7
     AVStream *st    = s->streams[stream_index];
5634c951
     int ret = 0;
115329f1
 
91d19d47
     if (s->packet_size <= 0)
38376f00
         return -1;
 
fa13095a
     /* Try using the protocol's read_seek if available */
48a4ffa7
     if (s->pb) {
d4936d28
         int64_t ret = avio_seek_time(s->pb, stream_index, pts, flags);
48a4ffa7
         if (ret >= 0)
fa13095a
             asf_reset_header(s);
fd2982a0
         if (ret != AVERROR(ENOSYS))
cd31f8dc
             return ret;
fa13095a
     }
 
0c082565
     /* explicitly handle the case of seeking to 0 */
     if (!pts) {
         asf_reset_header(s);
9deaec78
         avio_seek(s->pb, s->internal->data_offset, SEEK_SET);
0c082565
         return 0;
     }
 
5634c951
     if (!asf->index_read) {
0ebb523f
         ret = asf_build_simple_index(s, stream_index);
5634c951
         if (ret < 0)
             asf->index_read = -1;
     }
56c96a22
 
5634c951
     if (asf->index_read > 0 && st->index_entries) {
fadf8459
         int index = av_index_search_timestamp(st, pts, flags);
48a4ffa7
         if (index >= 0) {
b58bc17c
             /* find the position */
6003ec88
             uint64_t pos = st->index_entries[index].pos;
56c96a22
 
b58bc17c
             /* do the seek */
             av_log(s, AV_LOG_DEBUG, "SEEKTO: %"PRId64"\n", pos);
ac1d4893
             if(avio_seek(s->pb, pos, SEEK_SET) < 0)
                 return -1;
b58bc17c
             asf_reset_header(s);
d6686149
             skip_to_key(s);
b58bc17c
             return 0;
c7bd5eda
         }
56c96a22
     }
c7bd5eda
     /* no index or seeking by index failed */
a2faa951
     if (ff_seek_frame_binary(s, stream_index, pts, flags) < 0)
c7bd5eda
         return -1;
38376f00
     asf_reset_header(s);
d6686149
     skip_to_key(s);
38376f00
     return 0;
2a10020b
 }
 
66355be3
 AVInputFormat ff_asf_demuxer = {
dfc2c4d9
     .name           = "asf",
0177b7d2
     .long_name      = NULL_IF_CONFIG_SMALL("ASF (Advanced / Active Streaming Format)"),
dfc2c4d9
     .priv_data_size = sizeof(ASFContext),
     .read_probe     = asf_probe,
     .read_header    = asf_read_header,
     .read_packet    = asf_read_packet,
     .read_close     = asf_read_close,
     .read_seek      = asf_read_seek,
     .read_timestamp = asf_read_pts,
20234a4b
     .flags          = AVFMT_NOBINSEARCH | AVFMT_NOGENSEARCH,
75b7feae
     .priv_class     = &asf_class,
c9a65ca8
 };