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