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