2 * "Real" compatible demuxer.
3 * Copyright (c) 2000, 2001 Fabrice Bellard
5 * This file is part of FFmpeg.
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.
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.
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
24 #include "libavutil/avassert.h"
25 #include "libavutil/avstring.h"
26 #include "libavutil/channel_layout.h"
27 #include "libavutil/internal.h"
28 #include "libavutil/intreadwrite.h"
29 #include "libavutil/dict.h"
31 #include "avio_internal.h"
36 #define DEINT_ID_GENR MKTAG('g', 'e', 'n', 'r') ///< interleaving for Cooker/ATRAC
37 #define DEINT_ID_INT0 MKTAG('I', 'n', 't', '0') ///< no interleaving needed
38 #define DEINT_ID_INT4 MKTAG('I', 'n', 't', '4') ///< interleaving for 28.8
39 #define DEINT_ID_SIPR MKTAG('s', 'i', 'p', 'r') ///< interleaving for Sipro
40 #define DEINT_ID_VBRF MKTAG('v', 'b', 'r', 'f') ///< VBR case for AAC
41 #define DEINT_ID_VBRS MKTAG('v', 'b', 'r', 's') ///< VBR case for AAC
44 AVPacket pkt; ///< place to store merged video frame / reordered audio data
45 int videobufsize; ///< current assembled frame size
46 int videobufpos; ///< position for the next slice in the video buffer
47 int curpic_num; ///< picture number of current frame
48 int cur_slice, slices;
49 int64_t pktpos; ///< first slice position in file
50 /// Audio descrambling matrix parameters
51 int64_t audiotimestamp; ///< Audio packet timestamp
52 int sub_packet_cnt; // Subpacket counter, used while reading
53 int sub_packet_size, sub_packet_h, coded_framesize; ///< Descrambling parameters from container
54 int audio_framesize; /// Audio frame size from container
55 int sub_packet_lengths[16]; /// Length of each subpacket
56 int32_t deint_id; ///< deinterleaver used in audio stream
59 typedef struct RMDemuxContext {
64 int audio_stream_num; ///< Stream number for audio packets
65 int audio_pkt_cnt; ///< Output packet counter
69 static int rm_read_close(AVFormatContext *s);
71 static inline void get_strl(AVIOContext *pb, char *buf, int buf_size, int len)
73 int read = avio_get_str(pb, len, buf, buf_size);
76 avio_skip(pb, len - read);
79 static void get_str8(AVIOContext *pb, char *buf, int buf_size)
81 get_strl(pb, buf, buf_size, avio_r8(pb));
84 static int rm_read_extradata(AVFormatContext *s, AVIOContext *pb, AVCodecParameters *par, unsigned size)
87 av_log(s, AV_LOG_ERROR, "extradata size %u too large\n", size);
90 return ff_get_extradata(s, par, pb, size);
93 static void rm_read_metadata(AVFormatContext *s, AVIOContext *pb, int wide)
98 for (i=0; i<FF_ARRAY_ELEMS(ff_rm_metadata); i++) {
99 int len = wide ? avio_rb16(pb) : avio_r8(pb);
101 get_strl(pb, buf, sizeof(buf), len);
102 av_dict_set(&s->metadata, ff_rm_metadata[i], buf, 0);
107 RMStream *ff_rm_alloc_rmstream (void)
109 RMStream *rms = av_mallocz(sizeof(RMStream));
112 rms->curpic_num = -1;
116 void ff_rm_free_rmstream (RMStream *rms)
121 av_packet_unref(&rms->pkt);
124 static int rm_read_audio_stream_info(AVFormatContext *s, AVIOContext *pb,
125 AVStream *st, RMStream *ast, int read_all)
132 version = avio_rb16(pb); /* version */
134 unsigned bytes_per_minute;
135 int header_size = avio_rb16(pb);
136 int64_t startpos = avio_tell(pb);
138 bytes_per_minute = avio_rb16(pb);
140 rm_read_metadata(s, pb, 0);
141 if ((startpos + header_size) >= avio_tell(pb) + 2) {
142 // fourcc (should always be "lpcJ")
144 get_str8(pb, buf, sizeof(buf));
146 // Skip extra header crap (this should never happen)
147 if ((startpos + header_size) > avio_tell(pb))
148 avio_skip(pb, header_size + startpos - avio_tell(pb));
149 if (bytes_per_minute)
150 st->codecpar->bit_rate = 8LL * bytes_per_minute / 60;
151 st->codecpar->sample_rate = 8000;
152 st->codecpar->channels = 1;
153 st->codecpar->channel_layout = AV_CH_LAYOUT_MONO;
154 st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
155 st->codecpar->codec_id = AV_CODEC_ID_RA_144;
156 ast->deint_id = DEINT_ID_INT0;
158 int flavor, sub_packet_h, coded_framesize, sub_packet_size;
159 int codecdata_length;
160 unsigned bytes_per_minute;
161 /* old version (4) */
162 avio_skip(pb, 2); /* unused */
163 avio_rb32(pb); /* .ra4 */
164 avio_rb32(pb); /* data size */
165 avio_rb16(pb); /* version2 */
166 avio_rb32(pb); /* header size */
167 flavor= avio_rb16(pb); /* add codec info / flavor */
168 coded_framesize = avio_rb32(pb); /* coded frame size */
169 if (coded_framesize < 0)
170 return AVERROR_INVALIDDATA;
171 ast->coded_framesize = coded_framesize;
173 avio_rb32(pb); /* ??? */
174 bytes_per_minute = avio_rb32(pb);
176 if (bytes_per_minute)
177 st->codecpar->bit_rate = 8LL * bytes_per_minute / 60;
179 avio_rb32(pb); /* ??? */
180 ast->sub_packet_h = sub_packet_h = avio_rb16(pb); /* 1 */
181 st->codecpar->block_align= avio_rb16(pb); /* frame size */
182 ast->sub_packet_size = sub_packet_size = avio_rb16(pb); /* sub packet size */
183 avio_rb16(pb); /* ??? */
185 avio_rb16(pb); avio_rb16(pb); avio_rb16(pb);
187 st->codecpar->sample_rate = avio_rb16(pb);
189 st->codecpar->channels = avio_rb16(pb);
191 ast->deint_id = avio_rl32(pb);
192 avio_read(pb, buf, 4);
196 get_str8(pb, buf, sizeof(buf)); /* desc */
197 ast->deint_id = AV_RL32(buf);
198 get_str8(pb, buf, sizeof(buf)); /* desc */
200 st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
201 st->codecpar->codec_tag = AV_RL32(buf);
202 st->codecpar->codec_id = ff_codec_get_id(ff_rm_codec_tags,
203 st->codecpar->codec_tag);
205 switch (st->codecpar->codec_id) {
206 case AV_CODEC_ID_AC3:
207 st->need_parsing = AVSTREAM_PARSE_FULL;
209 case AV_CODEC_ID_RA_288:
210 st->codecpar->extradata_size= 0;
211 av_freep(&st->codecpar->extradata);
212 ast->audio_framesize = st->codecpar->block_align;
213 st->codecpar->block_align = coded_framesize;
215 case AV_CODEC_ID_COOK:
216 st->need_parsing = AVSTREAM_PARSE_HEADERS;
217 case AV_CODEC_ID_ATRAC3:
218 case AV_CODEC_ID_SIPR:
220 codecdata_length = 0;
222 avio_rb16(pb); avio_r8(pb);
225 codecdata_length = avio_rb32(pb);
226 if((unsigned)codecdata_length > INT_MAX - AV_INPUT_BUFFER_PADDING_SIZE){
227 av_log(s, AV_LOG_ERROR, "codecdata_length too large\n");
232 ast->audio_framesize = st->codecpar->block_align;
233 if (st->codecpar->codec_id == AV_CODEC_ID_SIPR) {
235 av_log(s, AV_LOG_ERROR, "bad SIPR file flavor %d\n",
239 st->codecpar->block_align = ff_sipr_subpk_size[flavor];
240 st->need_parsing = AVSTREAM_PARSE_FULL_RAW;
242 if(sub_packet_size <= 0){
243 av_log(s, AV_LOG_ERROR, "sub_packet_size is invalid\n");
246 st->codecpar->block_align = ast->sub_packet_size;
248 if ((ret = rm_read_extradata(s, pb, st->codecpar, codecdata_length)) < 0)
252 case AV_CODEC_ID_AAC:
253 avio_rb16(pb); avio_r8(pb);
256 codecdata_length = avio_rb32(pb);
257 if((unsigned)codecdata_length > INT_MAX - AV_INPUT_BUFFER_PADDING_SIZE){
258 av_log(s, AV_LOG_ERROR, "codecdata_length too large\n");
261 if (codecdata_length >= 1) {
263 if ((ret = rm_read_extradata(s, pb, st->codecpar, codecdata_length - 1)) < 0)
268 switch (ast->deint_id) {
270 if (ast->coded_framesize > ast->audio_framesize ||
272 ast->coded_framesize * sub_packet_h > (2 + (sub_packet_h & 1)) * ast->audio_framesize)
273 return AVERROR_INVALIDDATA;
274 if (ast->coded_framesize * sub_packet_h != 2*ast->audio_framesize) {
275 avpriv_request_sample(s, "mismatching interleaver parameters");
276 return AVERROR_INVALIDDATA;
280 if (ast->sub_packet_size <= 0 ||
281 ast->sub_packet_size > ast->audio_framesize)
282 return AVERROR_INVALIDDATA;
283 if (ast->audio_framesize % ast->sub_packet_size)
284 return AVERROR_INVALIDDATA;
292 av_log(s, AV_LOG_ERROR ,"Unknown interleaver %"PRIX32"\n", ast->deint_id);
293 return AVERROR_INVALIDDATA;
295 if (ast->deint_id == DEINT_ID_INT4 ||
296 ast->deint_id == DEINT_ID_GENR ||
297 ast->deint_id == DEINT_ID_SIPR) {
298 if (st->codecpar->block_align <= 0 ||
299 ast->audio_framesize * sub_packet_h > (unsigned)INT_MAX ||
300 ast->audio_framesize * sub_packet_h < st->codecpar->block_align)
301 return AVERROR_INVALIDDATA;
302 if (av_new_packet(&ast->pkt, ast->audio_framesize * sub_packet_h) < 0)
303 return AVERROR(ENOMEM);
310 rm_read_metadata(s, pb, 0);
316 int ff_rm_read_mdpr_codecdata(AVFormatContext *s, AVIOContext *pb,
317 AVStream *st, RMStream *rst,
318 unsigned int codec_data_size, const uint8_t *mime)
325 if (codec_data_size > INT_MAX)
326 return AVERROR_INVALIDDATA;
327 if (codec_data_size == 0)
330 avpriv_set_pts_info(st, 64, 1, 1000);
331 codec_pos = avio_tell(pb);
334 if (v == MKTAG(0xfd, 'a', 'r', '.')) {
336 if (rm_read_audio_stream_info(s, pb, st, rst, 0))
338 } else if (v == MKBETAG('L', 'S', 'D', ':')) {
339 avio_seek(pb, -4, SEEK_CUR);
340 if ((ret = rm_read_extradata(s, pb, st->codecpar, codec_data_size)) < 0)
343 st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
344 st->codecpar->codec_tag = AV_RL32(st->codecpar->extradata);
345 st->codecpar->codec_id = ff_codec_get_id(ff_rm_codec_tags,
346 st->codecpar->codec_tag);
347 } else if(mime && !strcmp(mime, "logical-fileinfo")){
348 int stream_count, rule_count, property_count, i;
349 ff_free_stream(s, st);
350 if (avio_rb16(pb) != 0) {
351 av_log(s, AV_LOG_WARNING, "Unsupported version\n");
354 stream_count = avio_rb16(pb);
355 avio_skip(pb, 6*stream_count);
356 rule_count = avio_rb16(pb);
357 avio_skip(pb, 2*rule_count);
358 property_count = avio_rb16(pb);
359 for(i=0; i<property_count; i++){
360 uint8_t name[128], val[128];
362 if (avio_rb16(pb) != 0) {
363 av_log(s, AV_LOG_WARNING, "Unsupported Name value property version\n");
364 goto skip; //FIXME skip just this one
366 get_str8(pb, name, sizeof(name));
367 switch(avio_rb32(pb)) {
368 case 2: get_strl(pb, val, sizeof(val), avio_rb16(pb));
369 av_dict_set(&s->metadata, name, val, 0);
371 default: avio_skip(pb, avio_rb16(pb));
376 if (avio_rl32(pb) != MKTAG('V', 'I', 'D', 'O')) {
378 av_log(s, AV_LOG_WARNING, "Unsupported stream type %08x\n", v);
381 st->codecpar->codec_tag = avio_rl32(pb);
382 st->codecpar->codec_id = ff_codec_get_id(ff_rm_codec_tags,
383 st->codecpar->codec_tag);
384 av_log(s, AV_LOG_TRACE, "%"PRIX32" %X\n",
385 st->codecpar->codec_tag, MKTAG('R', 'V', '2', '0'));
386 if (st->codecpar->codec_id == AV_CODEC_ID_NONE)
388 st->codecpar->width = avio_rb16(pb);
389 st->codecpar->height = avio_rb16(pb);
390 avio_skip(pb, 2); // looks like bits per sample
391 avio_skip(pb, 4); // always zero?
392 st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
393 st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS;
396 if ((ret = rm_read_extradata(s, pb, st->codecpar, codec_data_size - (avio_tell(pb) - codec_pos))) < 0)
400 av_reduce(&st->avg_frame_rate.den, &st->avg_frame_rate.num,
401 0x10000, fps, (1 << 30) - 1);
402 #if FF_API_R_FRAME_RATE
403 st->r_frame_rate = st->avg_frame_rate;
405 } else if (s->error_recognition & AV_EF_EXPLODE) {
406 av_log(s, AV_LOG_ERROR, "Invalid framerate\n");
407 return AVERROR_INVALIDDATA;
412 /* skip codec info */
413 size = avio_tell(pb) - codec_pos;
414 if (codec_data_size >= size) {
415 avio_skip(pb, codec_data_size - size);
417 av_log(s, AV_LOG_WARNING, "codec_data_size %u < size %d\n", codec_data_size, size);
423 /** this function assumes that the demuxer has already seeked to the start
424 * of the INDX chunk, and will bail out if not. */
425 static int rm_read_index(AVFormatContext *s)
427 AVIOContext *pb = s->pb;
428 unsigned int size, n_pkts, str_id, next_off, n, pos, pts;
432 if (avio_rl32(pb) != MKTAG('I','N','D','X'))
434 size = avio_rb32(pb);
438 n_pkts = avio_rb32(pb);
439 str_id = avio_rb16(pb);
440 next_off = avio_rb32(pb);
441 for (n = 0; n < s->nb_streams; n++)
442 if (s->streams[n]->id == str_id) {
446 if (n == s->nb_streams) {
447 av_log(s, AV_LOG_ERROR,
448 "Invalid stream index %d for index at pos %"PRId64"\n",
449 str_id, avio_tell(pb));
451 } else if ((avio_size(pb) - avio_tell(pb)) / 14 < n_pkts) {
452 av_log(s, AV_LOG_ERROR,
453 "Nr. of packets in packet index for stream index %d "
454 "exceeds filesize (%"PRId64" at %"PRId64" = %"PRId64")\n",
455 str_id, avio_size(pb), avio_tell(pb),
456 (avio_size(pb) - avio_tell(pb)) / 14);
460 for (n = 0; n < n_pkts; n++) {
462 return AVERROR_INVALIDDATA;
466 avio_skip(pb, 4); /* packet no. */
468 av_add_index_entry(st, pos, pts, 0, 0, AVINDEX_KEYFRAME);
472 if (next_off && avio_tell(pb) < next_off &&
473 avio_seek(pb, next_off, SEEK_SET) < 0) {
474 av_log(s, AV_LOG_ERROR,
475 "Non-linear index detected, not supported\n");
483 static int rm_read_header_old(AVFormatContext *s)
485 RMDemuxContext *rm = s->priv_data;
489 st = avformat_new_stream(s, NULL);
492 st->priv_data = ff_rm_alloc_rmstream();
494 return AVERROR(ENOMEM);
495 return rm_read_audio_stream_info(s, s->pb, st, st->priv_data, 1);
498 static int rm_read_multi(AVFormatContext *s, AVIOContext *pb,
499 AVStream *st, char *mime)
501 int number_of_streams = avio_rb16(pb);
505 for (i = 0; i<number_of_streams; i++)
507 number_of_mdpr = avio_rb16(pb);
508 if (number_of_mdpr != 1) {
509 avpriv_request_sample(s, "MLTI with multiple (%d) MDPR", number_of_mdpr);
511 for (i = 0; i < number_of_mdpr; i++) {
514 st2 = avformat_new_stream(s, NULL);
516 ret = AVERROR(ENOMEM);
519 st2->id = st->id + (i<<16);
520 st2->codecpar->bit_rate = st->codecpar->bit_rate;
521 st2->start_time = st->start_time;
522 st2->duration = st->duration;
523 st2->codecpar->codec_type = AVMEDIA_TYPE_DATA;
524 st2->priv_data = ff_rm_alloc_rmstream();
526 return AVERROR(ENOMEM);
530 size2 = avio_rb32(pb);
531 ret = ff_rm_read_mdpr_codecdata(s, s->pb, st2, st2->priv_data,
539 static int rm_read_header(AVFormatContext *s)
541 RMDemuxContext *rm = s->priv_data;
543 AVIOContext *pb = s->pb;
546 unsigned int start_time, duration;
547 unsigned int data_off = 0, indx_off = 0;
548 char buf[128], mime[128];
555 if (tag == MKTAG('.', 'r', 'a', 0xfd)) {
556 /* very old .ra format */
557 return rm_read_header_old(s);
558 } else if (tag != MKTAG('.', 'R', 'M', 'F')) {
562 tag_size = avio_rb32(pb);
563 avio_skip(pb, tag_size - 8);
566 ret = AVERROR_INVALIDDATA;
570 tag_size = avio_rb32(pb);
572 av_log(s, AV_LOG_TRACE, "tag=%s size=%d\n",
573 av_fourcc2str(tag), tag_size);
574 if (tag_size < 10 && tag != MKTAG('D', 'A', 'T', 'A'))
577 case MKTAG('P', 'R', 'O', 'P'):
579 avio_rb32(pb); /* max bit rate */
580 avio_rb32(pb); /* avg bit rate */
581 avio_rb32(pb); /* max packet size */
582 avio_rb32(pb); /* avg packet size */
583 avio_rb32(pb); /* nb packets */
584 duration = avio_rb32(pb); /* duration */
585 s->duration = av_rescale(duration, AV_TIME_BASE, 1000);
586 avio_rb32(pb); /* preroll */
587 indx_off = avio_rb32(pb); /* index offset */
588 data_off = avio_rb32(pb); /* data offset */
589 avio_rb16(pb); /* nb streams */
590 flags = avio_rb16(pb); /* flags */
592 case MKTAG('C', 'O', 'N', 'T'):
593 rm_read_metadata(s, pb, 1);
595 case MKTAG('M', 'D', 'P', 'R'):
596 st = avformat_new_stream(s, NULL);
598 ret = AVERROR(ENOMEM);
601 st->id = avio_rb16(pb);
602 avio_rb32(pb); /* max bit rate */
603 st->codecpar->bit_rate = avio_rb32(pb); /* bit rate */
604 avio_rb32(pb); /* max packet size */
605 avio_rb32(pb); /* avg packet size */
606 start_time = avio_rb32(pb); /* start time */
607 avio_rb32(pb); /* preroll */
608 duration = avio_rb32(pb); /* duration */
609 st->start_time = start_time;
610 st->duration = duration;
612 s->duration = AV_NOPTS_VALUE;
613 get_str8(pb, buf, sizeof(buf)); /* desc */
614 get_str8(pb, mime, sizeof(mime)); /* mimetype */
615 st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
616 st->priv_data = ff_rm_alloc_rmstream();
618 return AVERROR(ENOMEM);
620 size = avio_rb32(pb);
621 codec_pos = avio_tell(pb);
623 ffio_ensure_seekback(pb, 4);
625 if (v == MKBETAG('M', 'L', 'T', 'I')) {
626 ret = rm_read_multi(s, s->pb, st, mime);
629 avio_seek(pb, codec_pos + size, SEEK_SET);
632 ret = ff_rm_read_mdpr_codecdata(s, s->pb, st, st->priv_data,
639 case MKTAG('D', 'A', 'T', 'A'):
642 /* unknown tag: skip it */
643 avio_skip(pb, tag_size - 10);
648 rm->nb_packets = avio_rb32(pb); /* number of packets */
649 if (!rm->nb_packets && (flags & 4))
650 rm->nb_packets = 3600 * 25;
651 avio_rb32(pb); /* next data header */
654 data_off = avio_tell(pb) - 18;
655 if (indx_off && (pb->seekable & AVIO_SEEKABLE_NORMAL) &&
656 !(s->flags & AVFMT_FLAG_IGNIDX) &&
657 avio_seek(pb, indx_off, SEEK_SET) >= 0) {
659 avio_seek(pb, data_off + 18, SEEK_SET);
669 static int get_num(AVIOContext *pb, int *len)
681 return (n << 16) | n1;
685 /* multiple of 20 bytes for ra144 (ugly) */
686 #define RAW_PACKET_SIZE 1000
688 static int rm_sync(AVFormatContext *s, int64_t *timestamp, int *flags, int *stream_index, int64_t *pos){
689 RMDemuxContext *rm = s->priv_data;
690 AVIOContext *pb = s->pb;
692 uint32_t state=0xFFFFFFFF;
694 while(!avio_feof(pb)){
697 *pos= avio_tell(pb) - 3;
698 if(rm->remaining_len > 0){
699 num= rm->current_stream;
701 len= rm->remaining_len;
702 *timestamp = AV_NOPTS_VALUE;
705 state= (state<<8) + avio_r8(pb);
707 if(state == MKBETAG('I', 'N', 'D', 'X')){
709 int64_t expected_len;
712 n_pkts = avio_rb32(pb);
713 expected_len = 20 + n_pkts * 14LL;
715 if (len == 20 && expected_len <= INT_MAX)
716 /* some files don't add index entries to chunk size... */
718 else if (len != expected_len)
719 av_log(s, AV_LOG_WARNING,
720 "Index size %d (%d pkts) is wrong, should be %"PRId64".\n",
721 len, n_pkts, expected_len);
724 len -= 14; // we already read part of the index header
726 } else if (state == MKBETAG('D','A','T','A')) {
727 av_log(s, AV_LOG_WARNING,
728 "DATA tag in middle of chunk, file may be broken.\n");
731 if(state > (unsigned)0xFFFF || state <= 12)
737 *timestamp = avio_rb32(pb);
738 mlti_id = (avio_r8(pb) >> 1) - 1;
739 mlti_id = FFMAX(mlti_id, 0) << 16;
740 *flags = avio_r8(pb); /* flags */
742 for(i=0;i<s->nb_streams;i++) {
744 if (mlti_id + num == st->id)
747 if (i == s->nb_streams) {
749 /* skip packet if unknown number */
751 rm->remaining_len = 0;
761 static int rm_assemble_video_frame(AVFormatContext *s, AVIOContext *pb,
762 RMDemuxContext *rm, RMStream *vst,
763 AVPacket *pkt, int len, int *pseq,
767 int seq = 0, pic_num = 0, len2 = 0, pos = 0; //init to silence compiler warning
771 hdr = avio_r8(pb); len--;
774 if(type != 3){ // not frame as a part of packet
775 seq = avio_r8(pb); len--;
777 if(type != 1){ // not whole frame
778 len2 = get_num(pb, &len);
779 pos = get_num(pb, &len);
780 pic_num = avio_r8(pb); len--;
783 av_log(s, AV_LOG_ERROR, "Insufficient data\n");
786 rm->remaining_len = len;
787 if(type&1){ // frame, not slice
788 if(type == 3){ // frame as a part of packet
792 if(rm->remaining_len < len) {
793 av_log(s, AV_LOG_ERROR, "Insufficient remaining len\n");
796 rm->remaining_len -= len;
797 if ((ret = av_new_packet(pkt, len + 9)) < 0)
800 AV_WL32(pkt->data + 1, 1);
801 AV_WL32(pkt->data + 5, 0);
802 if ((ret = avio_read(pb, pkt->data + 9, len)) != len) {
803 av_packet_unref(pkt);
804 av_log(s, AV_LOG_ERROR, "Failed to read %d bytes\n", len);
805 return ret < 0 ? ret : AVERROR(EIO);
809 //now we have to deal with single slice
812 if((seq & 0x7F) == 1 || vst->curpic_num != pic_num){
813 if (len2 > ffio_limit(pb, len2)) {
814 av_log(s, AV_LOG_ERROR, "Impossibly sized packet\n");
815 return AVERROR_INVALIDDATA;
817 vst->slices = ((hdr & 0x3F) << 1) + 1;
818 vst->videobufsize = len2 + 8*vst->slices + 1;
819 av_packet_unref(&vst->pkt); //FIXME this should be output.
820 if ((ret = av_new_packet(&vst->pkt, vst->videobufsize)) < 0)
822 vst->videobufpos = 8*vst->slices + 1;
824 vst->curpic_num = pic_num;
825 vst->pktpos = avio_tell(pb);
828 len = FFMIN(len, pos);
830 if(++vst->cur_slice > vst->slices) {
831 av_log(s, AV_LOG_ERROR, "cur slice %d, too large\n", vst->cur_slice);
835 return AVERROR(ENOMEM);
836 AV_WL32(vst->pkt.data - 7 + 8*vst->cur_slice, 1);
837 AV_WL32(vst->pkt.data - 3 + 8*vst->cur_slice, vst->videobufpos - 8*vst->slices - 1);
838 if(vst->videobufpos + len > vst->videobufsize) {
839 av_log(s, AV_LOG_ERROR, "outside videobufsize\n");
842 if (avio_read(pb, vst->pkt.data + vst->videobufpos, len) != len)
844 vst->videobufpos += len;
845 rm->remaining_len-= len;
847 if (type == 2 || vst->videobufpos == vst->videobufsize) {
848 vst->pkt.data[0] = vst->cur_slice-1;
849 av_packet_move_ref(pkt, &vst->pkt);
850 if(vst->slices != vst->cur_slice) //FIXME find out how to set slices correct from the begin
851 memmove(pkt->data + 1 + 8*vst->cur_slice, pkt->data + 1 + 8*vst->slices,
852 vst->videobufpos - 1 - 8*vst->slices);
853 av_shrink_packet(pkt, vst->videobufpos + 8*(vst->cur_slice - vst->slices));
854 pkt->pts = AV_NOPTS_VALUE;
855 pkt->pos = vst->pktpos;
864 rm_ac3_swap_bytes (AVStream *st, AVPacket *pkt)
869 if (st->codecpar->codec_id == AV_CODEC_ID_AC3) {
871 for (j=0;j<pkt->size;j+=2) {
872 FFSWAP(int, ptr[0], ptr[1]);
878 static int readfull(AVFormatContext *s, AVIOContext *pb, uint8_t *dst, int n) {
879 int ret = avio_read(pb, dst, n);
881 if (ret >= 0) memset(dst + ret, 0, n - ret);
882 else memset(dst , 0, n);
883 av_log(s, AV_LOG_ERROR, "Failed to fully read block\n");
889 ff_rm_parse_packet (AVFormatContext *s, AVIOContext *pb,
890 AVStream *st, RMStream *ast, int len, AVPacket *pkt,
891 int *seq, int flags, int64_t timestamp)
893 RMDemuxContext *rm = s->priv_data;
896 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
897 rm->current_stream= st->id;
898 ret = rm_assemble_video_frame(s, pb, rm, ast, pkt, len, seq, ×tamp);
900 return ret < 0 ? ret : -1; //got partial frame or error
901 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
902 if ((ast->deint_id == DEINT_ID_GENR) ||
903 (ast->deint_id == DEINT_ID_INT4) ||
904 (ast->deint_id == DEINT_ID_SIPR)) {
906 int sps = ast->sub_packet_size;
907 int cfs = ast->coded_framesize;
908 int h = ast->sub_packet_h;
909 int y = ast->sub_packet_cnt;
910 int w = ast->audio_framesize;
913 y = ast->sub_packet_cnt = 0;
915 ast->audiotimestamp = timestamp;
917 switch (ast->deint_id) {
919 for (x = 0; x < h/2; x++)
920 readfull(s, pb, ast->pkt.data+x*2*w+y*cfs, cfs);
923 for (x = 0; x < w/sps; x++)
924 readfull(s, pb, ast->pkt.data+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), sps);
927 readfull(s, pb, ast->pkt.data + y * w, w);
931 if (++(ast->sub_packet_cnt) < h)
933 if (ast->deint_id == DEINT_ID_SIPR)
934 ff_rm_reorder_sipr_data(ast->pkt.data, h, w);
936 ast->sub_packet_cnt = 0;
937 rm->audio_stream_num = st->index;
938 if (st->codecpar->block_align <= 0) {
939 av_log(s, AV_LOG_ERROR, "Invalid block alignment %d\n", st->codecpar->block_align);
940 return AVERROR_INVALIDDATA;
942 rm->audio_pkt_cnt = h * w / st->codecpar->block_align;
943 } else if ((ast->deint_id == DEINT_ID_VBRF) ||
944 (ast->deint_id == DEINT_ID_VBRS)) {
946 rm->audio_stream_num = st->index;
947 ast->sub_packet_cnt = (avio_rb16(pb) & 0xf0) >> 4;
948 if (ast->sub_packet_cnt) {
949 for (x = 0; x < ast->sub_packet_cnt; x++)
950 ast->sub_packet_lengths[x] = avio_rb16(pb);
951 rm->audio_pkt_cnt = ast->sub_packet_cnt;
952 ast->audiotimestamp = timestamp;
956 ret = av_get_packet(pb, pkt, len);
959 rm_ac3_swap_bytes(st, pkt);
962 ret = av_get_packet(pb, pkt, len);
967 pkt->stream_index = st->index;
969 pkt->pts = timestamp;
971 pkt->flags |= AV_PKT_FLAG_KEY;
973 return st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO ? rm->audio_pkt_cnt : 0;
977 ff_rm_retrieve_cache (AVFormatContext *s, AVIOContext *pb,
978 AVStream *st, RMStream *ast, AVPacket *pkt)
980 RMDemuxContext *rm = s->priv_data;
983 av_assert0 (rm->audio_pkt_cnt > 0);
985 if (ast->deint_id == DEINT_ID_VBRF ||
986 ast->deint_id == DEINT_ID_VBRS) {
987 ret = av_get_packet(pb, pkt, ast->sub_packet_lengths[ast->sub_packet_cnt - rm->audio_pkt_cnt]);
991 ret = av_new_packet(pkt, st->codecpar->block_align);
994 memcpy(pkt->data, ast->pkt.data + st->codecpar->block_align * //FIXME avoid this
995 (ast->sub_packet_h * ast->audio_framesize / st->codecpar->block_align - rm->audio_pkt_cnt),
996 st->codecpar->block_align);
999 if ((pkt->pts = ast->audiotimestamp) != AV_NOPTS_VALUE) {
1000 ast->audiotimestamp = AV_NOPTS_VALUE;
1001 pkt->flags = AV_PKT_FLAG_KEY;
1004 pkt->stream_index = st->index;
1006 return rm->audio_pkt_cnt;
1009 static int rm_read_packet(AVFormatContext *s, AVPacket *pkt)
1011 RMDemuxContext *rm = s->priv_data;
1012 AVStream *st = NULL; // init to silence compiler warning
1013 int i, len, res, seq = 1;
1014 int64_t timestamp, pos;
1018 if (rm->audio_pkt_cnt) {
1019 // If there are queued audio packet return them first
1020 st = s->streams[rm->audio_stream_num];
1021 res = ff_rm_retrieve_cache(s, s->pb, st, st->priv_data, pkt);
1026 if (rm->old_format) {
1030 ast = st->priv_data;
1031 timestamp = AV_NOPTS_VALUE;
1032 len = !ast->audio_framesize ? RAW_PACKET_SIZE :
1033 ast->coded_framesize * ast->sub_packet_h / 2;
1034 flags = (seq++ == 1) ? 2 : 0;
1035 pos = avio_tell(s->pb);
1037 len = rm_sync(s, ×tamp, &flags, &i, &pos);
1042 if (avio_feof(s->pb))
1045 return AVERROR(EIO);
1047 res = ff_rm_parse_packet (s, s->pb, st, st->priv_data, len, pkt,
1048 &seq, flags, timestamp);
1051 if((flags&2) && (seq&0x7F) == 1)
1052 av_add_index_entry(st, pos, timestamp, 0, 0, AVINDEX_KEYFRAME);
1057 if( (st->discard >= AVDISCARD_NONKEY && !(flags&2))
1058 || st->discard >= AVDISCARD_ALL){
1059 av_packet_unref(pkt);
1067 static int rm_read_close(AVFormatContext *s)
1071 for (i=0;i<s->nb_streams;i++)
1072 ff_rm_free_rmstream(s->streams[i]->priv_data);
1077 static int rm_probe(const AVProbeData *p)
1079 /* check file header */
1080 if ((p->buf[0] == '.' && p->buf[1] == 'R' &&
1081 p->buf[2] == 'M' && p->buf[3] == 'F' &&
1082 p->buf[4] == 0 && p->buf[5] == 0) ||
1083 (p->buf[0] == '.' && p->buf[1] == 'r' &&
1084 p->buf[2] == 'a' && p->buf[3] == 0xfd))
1085 return AVPROBE_SCORE_MAX;
1090 static int64_t rm_read_dts(AVFormatContext *s, int stream_index,
1091 int64_t *ppos, int64_t pos_limit)
1093 RMDemuxContext *rm = s->priv_data;
1095 int stream_index2, flags, len, h;
1100 return AV_NOPTS_VALUE;
1102 if (avio_seek(s->pb, pos, SEEK_SET) < 0)
1103 return AV_NOPTS_VALUE;
1105 rm->remaining_len=0;
1110 len = rm_sync(s, &dts, &flags, &stream_index2, &pos);
1112 return AV_NOPTS_VALUE;
1114 st = s->streams[stream_index2];
1115 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
1116 h= avio_r8(s->pb); len--;
1118 seq = avio_r8(s->pb); len--;
1122 if((flags&2) && (seq&0x7F) == 1){
1123 av_log(s, AV_LOG_TRACE, "%d %d-%d %"PRId64" %d\n",
1124 flags, stream_index2, stream_index, dts, seq);
1125 av_add_index_entry(st, pos, dts, 0, 0, AVINDEX_KEYFRAME);
1126 if(stream_index2 == stream_index)
1130 avio_skip(s->pb, len);
1136 static int rm_read_seek(AVFormatContext *s, int stream_index,
1137 int64_t pts, int flags)
1139 RMDemuxContext *rm = s->priv_data;
1141 if (ff_seek_frame_binary(s, stream_index, pts, flags) < 0)
1143 rm->audio_pkt_cnt = 0;
1148 AVInputFormat ff_rm_demuxer = {
1150 .long_name = NULL_IF_CONFIG_SMALL("RealMedia"),
1151 .priv_data_size = sizeof(RMDemuxContext),
1152 .read_probe = rm_probe,
1153 .read_header = rm_read_header,
1154 .read_packet = rm_read_packet,
1155 .read_close = rm_read_close,
1156 .read_timestamp = rm_read_dts,
1157 .read_seek = rm_read_seek,
1160 AVInputFormat ff_rdt_demuxer = {
1162 .long_name = NULL_IF_CONFIG_SMALL("RDT demuxer"),
1163 .priv_data_size = sizeof(RMDemuxContext),
1164 .read_close = rm_read_close,
1165 .flags = AVFMT_NOFILE,
1168 static int ivr_probe(const AVProbeData *p)
1170 if (memcmp(p->buf, ".R1M\x0\x1\x1", 7) &&
1171 memcmp(p->buf, ".REC", 4))
1174 return AVPROBE_SCORE_MAX;
1177 static int ivr_read_header(AVFormatContext *s)
1179 unsigned tag, type, len, tlen, value;
1180 int i, j, n, count, nb_streams = 0, ret;
1181 uint8_t key[256], val[256];
1182 AVIOContext *pb = s->pb;
1184 int64_t pos, offset=0, temp;
1186 pos = avio_tell(pb);
1187 tag = avio_rl32(pb);
1188 if (tag == MKTAG('.','R','1','M')) {
1189 if (avio_rb16(pb) != 1)
1190 return AVERROR_INVALIDDATA;
1191 if (avio_r8(pb) != 1)
1192 return AVERROR_INVALIDDATA;
1193 len = avio_rb32(pb);
1196 temp = avio_rb64(pb);
1197 while (!avio_feof(pb) && temp) {
1199 temp = avio_rb64(pb);
1202 return AVERROR_INVALIDDATA;
1203 avio_skip(pb, offset - avio_tell(pb));
1204 if (avio_r8(pb) != 1)
1205 return AVERROR_INVALIDDATA;
1206 len = avio_rb32(pb);
1208 if (avio_r8(pb) != 2)
1209 return AVERROR_INVALIDDATA;
1211 pos = avio_tell(pb);
1212 tag = avio_rl32(pb);
1215 if (tag != MKTAG('.','R','E','C'))
1216 return AVERROR_INVALIDDATA;
1218 if (avio_r8(pb) != 0)
1219 return AVERROR_INVALIDDATA;
1220 count = avio_rb32(pb);
1221 for (i = 0; i < count; i++) {
1223 return AVERROR_INVALIDDATA;
1226 tlen = avio_rb32(pb);
1227 avio_get_str(pb, tlen, key, sizeof(key));
1228 len = avio_rb32(pb);
1230 avio_get_str(pb, len, val, sizeof(val));
1231 av_log(s, AV_LOG_DEBUG, "%s = '%s'\n", key, val);
1232 } else if (type == 4) {
1233 av_log(s, AV_LOG_DEBUG, "%s = '0x", key);
1234 for (j = 0; j < len; j++) {
1236 return AVERROR_INVALIDDATA;
1237 av_log(s, AV_LOG_DEBUG, "%X", avio_r8(pb));
1239 av_log(s, AV_LOG_DEBUG, "'\n");
1240 } else if (len == 4 && type == 3 && !strncmp(key, "StreamCount", tlen)) {
1241 nb_streams = value = avio_rb32(pb);
1242 } else if (len == 4 && type == 3) {
1243 value = avio_rb32(pb);
1244 av_log(s, AV_LOG_DEBUG, "%s = %d\n", key, value);
1246 av_log(s, AV_LOG_DEBUG, "Skipping unsupported key: %s\n", key);
1251 for (n = 0; n < nb_streams; n++) {
1252 st = avformat_new_stream(s, NULL);
1254 return AVERROR(ENOMEM);
1255 st->priv_data = ff_rm_alloc_rmstream();
1257 return AVERROR(ENOMEM);
1259 if (avio_r8(pb) != 1)
1260 return AVERROR_INVALIDDATA;
1262 count = avio_rb32(pb);
1263 for (i = 0; i < count; i++) {
1265 return AVERROR_INVALIDDATA;
1268 tlen = avio_rb32(pb);
1269 avio_get_str(pb, tlen, key, sizeof(key));
1270 len = avio_rb32(pb);
1272 avio_get_str(pb, len, val, sizeof(val));
1273 av_log(s, AV_LOG_DEBUG, "%s = '%s'\n", key, val);
1274 } else if (type == 4 && !strncmp(key, "OpaqueData", tlen)) {
1275 ret = ffio_ensure_seekback(pb, 4);
1278 if (avio_rb32(pb) == MKBETAG('M', 'L', 'T', 'I')) {
1279 ret = rm_read_multi(s, pb, st, NULL);
1282 return AVERROR_INVALIDDATA;
1283 avio_seek(pb, -4, SEEK_CUR);
1284 ret = ff_rm_read_mdpr_codecdata(s, pb, st, st->priv_data, len, NULL);
1289 } else if (type == 4) {
1292 av_log(s, AV_LOG_DEBUG, "%s = '0x", key);
1293 for (j = 0; j < len; j++) {
1295 return AVERROR_INVALIDDATA;
1296 av_log(s, AV_LOG_DEBUG, "%X", avio_r8(pb));
1298 av_log(s, AV_LOG_DEBUG, "'\n");
1299 } else if (len == 4 && type == 3 && !strncmp(key, "Duration", tlen)) {
1300 st->duration = avio_rb32(pb);
1301 } else if (len == 4 && type == 3) {
1302 value = avio_rb32(pb);
1303 av_log(s, AV_LOG_DEBUG, "%s = %d\n", key, value);
1305 av_log(s, AV_LOG_DEBUG, "Skipping unsupported key: %s\n", key);
1311 if (avio_r8(pb) != 6)
1312 return AVERROR_INVALIDDATA;
1314 avio_skip(pb, avio_rb64(pb) + pos - avio_tell(s->pb));
1315 if (avio_r8(pb) != 8)
1316 return AVERROR_INVALIDDATA;
1322 static int ivr_read_packet(AVFormatContext *s, AVPacket *pkt)
1324 RMDemuxContext *rm = s->priv_data;
1325 int ret = AVERROR_EOF, opcode;
1326 AVIOContext *pb = s->pb;
1327 unsigned size, index;
1330 if (avio_feof(pb) || rm->data_end)
1333 pos = avio_tell(pb);
1336 if (rm->audio_pkt_cnt) {
1337 // If there are queued audio packet return them first
1340 st = s->streams[rm->audio_stream_num];
1341 ret = ff_rm_retrieve_cache(s, pb, st, st->priv_data, pkt);
1346 if (rm->remaining_len) {
1347 avio_skip(pb, rm->remaining_len);
1348 rm->remaining_len = 0;
1354 opcode = avio_r8(pb);
1359 pts = avio_rb32(pb);
1360 index = avio_rb16(pb);
1361 if (index >= s->nb_streams)
1362 return AVERROR_INVALIDDATA;
1365 size = avio_rb32(pb);
1368 if (size < 1 || size > INT_MAX/4) {
1369 av_log(s, AV_LOG_ERROR, "size %u is invalid\n", size);
1370 return AVERROR_INVALIDDATA;
1373 st = s->streams[index];
1374 ret = ff_rm_parse_packet(s, pb, st, st->priv_data, size, pkt,
1384 pkt->stream_index = index;
1385 } else if (opcode == 7) {
1386 pos = avio_rb64(pb);
1392 av_log(s, AV_LOG_ERROR, "Unsupported opcode=%d at %"PRIX64"\n", opcode, avio_tell(pb) - 1);
1393 return AVERROR(EIO);
1403 AVInputFormat ff_ivr_demuxer = {
1405 .long_name = NULL_IF_CONFIG_SMALL("IVR (Internet Video Recording)"),
1406 .priv_data_size = sizeof(RMDemuxContext),
1407 .read_probe = ivr_probe,
1408 .read_header = ivr_read_header,
1409 .read_packet = ivr_read_packet,
1410 .read_close = rm_read_close,
1411 .extensions = "ivr",