ea9732544e26b10d689b6a116cb0876ad93e0bfc
[libav.git] / libavformat / rmdec.c
1 /*
2 * "Real" compatible demuxer.
3 * Copyright (c) 2000, 2001 Fabrice Bellard
4 *
5 * This file is part of FFmpeg.
6 *
7 * FFmpeg is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
11 *
12 * FFmpeg is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 */
21
22 #include "libavutil/avstring.h"
23 #include "libavutil/intreadwrite.h"
24 #include "avformat.h"
25 #include "riff.h"
26 #include "rm.h"
27
28 struct RMStream {
29 AVPacket pkt; ///< place to store merged video frame / reordered audio data
30 int videobufsize; ///< current assembled frame size
31 int videobufpos; ///< position for the next slice in the video buffer
32 int curpic_num; ///< picture number of current frame
33 int cur_slice, slices;
34 int64_t pktpos; ///< first slice position in file
35 /// Audio descrambling matrix parameters
36 int64_t audiotimestamp; ///< Audio packet timestamp
37 int sub_packet_cnt; // Subpacket counter, used while reading
38 int sub_packet_size, sub_packet_h, coded_framesize; ///< Descrambling parameters from container
39 int audio_framesize; /// Audio frame size from container
40 int sub_packet_lengths[16]; /// Length of each subpacket
41 };
42
43 typedef struct {
44 int nb_packets;
45 int old_format;
46 int current_stream;
47 int remaining_len;
48 int audio_stream_num; ///< Stream number for audio packets
49 int audio_pkt_cnt; ///< Output packet counter
50 } RMDemuxContext;
51
52 static const AVCodecTag rm_codec_tags[] = {
53 { CODEC_ID_RV10, MKTAG('R','V','1','0') },
54 { CODEC_ID_RV20, MKTAG('R','V','2','0') },
55 { CODEC_ID_RV20, MKTAG('R','V','T','R') },
56 { CODEC_ID_RV30, MKTAG('R','V','3','0') },
57 { CODEC_ID_RV40, MKTAG('R','V','4','0') },
58 { CODEC_ID_AC3, MKTAG('d','n','e','t') },
59 { CODEC_ID_RA_144, MKTAG('l','p','c','J') },
60 { CODEC_ID_RA_288, MKTAG('2','8','_','8') },
61 { CODEC_ID_COOK, MKTAG('c','o','o','k') },
62 { CODEC_ID_ATRAC3, MKTAG('a','t','r','c') },
63 { CODEC_ID_SIPR, MKTAG('s','i','p','r') },
64 { CODEC_ID_AAC, MKTAG('r','a','a','c') },
65 { CODEC_ID_AAC, MKTAG('r','a','c','p') },
66 { CODEC_ID_NONE },
67 };
68
69 static const unsigned char sipr_swaps[38][2] = {
70 { 0, 63 }, { 1, 22 }, { 2, 44 }, { 3, 90 },
71 { 5, 81 }, { 7, 31 }, { 8, 86 }, { 9, 58 },
72 { 10, 36 }, { 12, 68 }, { 13, 39 }, { 14, 73 },
73 { 15, 53 }, { 16, 69 }, { 17, 57 }, { 19, 88 },
74 { 20, 34 }, { 21, 71 }, { 24, 46 }, { 25, 94 },
75 { 26, 54 }, { 28, 75 }, { 29, 50 }, { 32, 70 },
76 { 33, 92 }, { 35, 74 }, { 38, 85 }, { 40, 56 },
77 { 42, 87 }, { 43, 65 }, { 45, 59 }, { 48, 79 },
78 { 49, 93 }, { 51, 89 }, { 55, 95 }, { 61, 76 },
79 { 67, 83 }, { 77, 80 }
80 };
81
82 const unsigned char ff_sipr_subpk_size[4] = { 29, 19, 37, 20 };
83
84 static inline void get_strl(ByteIOContext *pb, char *buf, int buf_size, int len)
85 {
86 int i;
87 char *q, r;
88
89 q = buf;
90 for(i=0;i<len;i++) {
91 r = get_byte(pb);
92 if (i < buf_size - 1)
93 *q++ = r;
94 }
95 if (buf_size > 0) *q = '\0';
96 }
97
98 static void get_str8(ByteIOContext *pb, char *buf, int buf_size)
99 {
100 get_strl(pb, buf, buf_size, get_byte(pb));
101 }
102
103 static int rm_read_extradata(ByteIOContext *pb, AVCodecContext *avctx, unsigned size)
104 {
105 if (size >= 1<<24)
106 return -1;
107 avctx->extradata = av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);
108 if (!avctx->extradata)
109 return AVERROR_NOMEM;
110 avctx->extradata_size = get_buffer(pb, avctx->extradata, size);
111 memset(avctx->extradata + avctx->extradata_size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
112 if (avctx->extradata_size != size)
113 return AVERROR(EIO);
114 return 0;
115 }
116
117 static void rm_read_metadata(AVFormatContext *s, int wide)
118 {
119 char buf[1024];
120 int i;
121 for (i=0; i<FF_ARRAY_ELEMS(ff_rm_metadata); i++) {
122 int len = wide ? get_be16(s->pb) : get_byte(s->pb);
123 get_strl(s->pb, buf, sizeof(buf), len);
124 av_metadata_set(&s->metadata, ff_rm_metadata[i], buf);
125 }
126 }
127
128 RMStream *ff_rm_alloc_rmstream (void)
129 {
130 RMStream *rms = av_mallocz(sizeof(RMStream));
131 rms->curpic_num = -1;
132 return rms;
133 }
134
135 void ff_rm_free_rmstream (RMStream *rms)
136 {
137 av_free_packet(&rms->pkt);
138 }
139
140 static int rm_read_audio_stream_info(AVFormatContext *s, ByteIOContext *pb,
141 AVStream *st, RMStream *ast, int read_all)
142 {
143 char buf[256];
144 uint32_t version;
145 int ret;
146
147 /* ra type header */
148 version = get_be16(pb); /* version */
149 if (version == 3) {
150 int header_size = get_be16(pb);
151 int64_t startpos = url_ftell(pb);
152 url_fskip(pb, 14);
153 rm_read_metadata(s, 0);
154 if ((startpos + header_size) >= url_ftell(pb) + 2) {
155 // fourcc (should always be "lpcJ")
156 get_byte(pb);
157 get_str8(pb, buf, sizeof(buf));
158 }
159 // Skip extra header crap (this should never happen)
160 if ((startpos + header_size) > url_ftell(pb))
161 url_fskip(pb, header_size + startpos - url_ftell(pb));
162 st->codec->sample_rate = 8000;
163 st->codec->channels = 1;
164 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
165 st->codec->codec_id = CODEC_ID_RA_144;
166 } else {
167 int flavor, sub_packet_h, coded_framesize, sub_packet_size;
168 int codecdata_length;
169 /* old version (4) */
170 url_fskip(pb, 2); /* unused */
171 get_be32(pb); /* .ra4 */
172 get_be32(pb); /* data size */
173 get_be16(pb); /* version2 */
174 get_be32(pb); /* header size */
175 flavor= get_be16(pb); /* add codec info / flavor */
176 ast->coded_framesize = coded_framesize = get_be32(pb); /* coded frame size */
177 get_be32(pb); /* ??? */
178 get_be32(pb); /* ??? */
179 get_be32(pb); /* ??? */
180 ast->sub_packet_h = sub_packet_h = get_be16(pb); /* 1 */
181 st->codec->block_align= get_be16(pb); /* frame size */
182 ast->sub_packet_size = sub_packet_size = get_be16(pb); /* sub packet size */
183 get_be16(pb); /* ??? */
184 if (version == 5) {
185 get_be16(pb); get_be16(pb); get_be16(pb);
186 }
187 st->codec->sample_rate = get_be16(pb);
188 get_be32(pb);
189 st->codec->channels = get_be16(pb);
190 if (version == 5) {
191 get_be32(pb);
192 get_buffer(pb, buf, 4);
193 buf[4] = 0;
194 } else {
195 get_str8(pb, buf, sizeof(buf)); /* desc */
196 get_str8(pb, buf, sizeof(buf)); /* desc */
197 }
198 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
199 st->codec->codec_tag = AV_RL32(buf);
200 st->codec->codec_id = ff_codec_get_id(rm_codec_tags, st->codec->codec_tag);
201 switch (st->codec->codec_id) {
202 case CODEC_ID_AC3:
203 st->need_parsing = AVSTREAM_PARSE_FULL;
204 break;
205 case CODEC_ID_RA_288:
206 st->codec->extradata_size= 0;
207 ast->audio_framesize = st->codec->block_align;
208 st->codec->block_align = coded_framesize;
209
210 if(ast->audio_framesize >= UINT_MAX / sub_packet_h){
211 av_log(s, AV_LOG_ERROR, "ast->audio_framesize * sub_packet_h too large\n");
212 return -1;
213 }
214
215 av_new_packet(&ast->pkt, ast->audio_framesize * sub_packet_h);
216 break;
217 case CODEC_ID_COOK:
218 case CODEC_ID_ATRAC3:
219 case CODEC_ID_SIPR:
220 get_be16(pb); get_byte(pb);
221 if (version == 5)
222 get_byte(pb);
223 codecdata_length = get_be32(pb);
224 if(codecdata_length + FF_INPUT_BUFFER_PADDING_SIZE <= (unsigned)codecdata_length){
225 av_log(s, AV_LOG_ERROR, "codecdata_length too large\n");
226 return -1;
227 }
228
229 if (!strcmp(buf, "cook")) st->codec->codec_id = CODEC_ID_COOK;
230 else if (!strcmp(buf, "sipr")) st->codec->codec_id = CODEC_ID_SIPR;
231 else st->codec->codec_id = CODEC_ID_ATRAC3;
232
233 ast->audio_framesize = st->codec->block_align;
234 if (st->codec->codec_id == CODEC_ID_SIPR) {
235 if (flavor > 3) {
236 av_log(s, AV_LOG_ERROR, "bad SIPR file flavor %d\n",
237 flavor);
238 return -1;
239 }
240 st->codec->block_align = ff_sipr_subpk_size[flavor];
241 } else {
242 if(sub_packet_size <= 0){
243 av_log(s, AV_LOG_ERROR, "sub_packet_size is invalid\n");
244 return -1;
245 }
246 st->codec->block_align = ast->sub_packet_size;
247 }
248 if ((ret = rm_read_extradata(pb, st->codec, codecdata_length)) < 0)
249 return ret;
250
251 if(ast->audio_framesize >= UINT_MAX / sub_packet_h){
252 av_log(s, AV_LOG_ERROR, "rm->audio_framesize * sub_packet_h too large\n");
253 return -1;
254 }
255
256 av_new_packet(&ast->pkt, ast->audio_framesize * sub_packet_h);
257 break;
258 case CODEC_ID_AAC:
259 get_be16(pb); get_byte(pb);
260 if (version == 5)
261 get_byte(pb);
262 st->codec->codec_id = CODEC_ID_AAC;
263 codecdata_length = get_be32(pb);
264 if(codecdata_length + FF_INPUT_BUFFER_PADDING_SIZE <= (unsigned)codecdata_length){
265 av_log(s, AV_LOG_ERROR, "codecdata_length too large\n");
266 return -1;
267 }
268 if (codecdata_length >= 1) {
269 get_byte(pb);
270 if ((ret = rm_read_extradata(pb, st->codec, codecdata_length - 1)) < 0)
271 return ret;
272 }
273 break;
274 default:
275 av_strlcpy(st->codec->codec_name, buf, sizeof(st->codec->codec_name));
276 }
277 if (read_all) {
278 get_byte(pb);
279 get_byte(pb);
280 get_byte(pb);
281 rm_read_metadata(s, 0);
282 }
283 }
284 return 0;
285 }
286
287 int
288 ff_rm_read_mdpr_codecdata (AVFormatContext *s, ByteIOContext *pb,
289 AVStream *st, RMStream *rst, int codec_data_size)
290 {
291 unsigned int v;
292 int size;
293 int64_t codec_pos;
294 int ret;
295
296 av_set_pts_info(st, 64, 1, 1000);
297 codec_pos = url_ftell(pb);
298 v = get_be32(pb);
299 if (v == MKTAG(0xfd, 'a', 'r', '.')) {
300 /* ra type header */
301 if (rm_read_audio_stream_info(s, pb, st, rst, 0))
302 return -1;
303 } else {
304 int fps, fps2;
305 if (get_le32(pb) != MKTAG('V', 'I', 'D', 'O')) {
306 fail1:
307 av_log(st->codec, AV_LOG_ERROR, "Unsupported video codec\n");
308 goto skip;
309 }
310 st->codec->codec_tag = get_le32(pb);
311 st->codec->codec_id = ff_codec_get_id(rm_codec_tags, st->codec->codec_tag);
312 // av_log(s, AV_LOG_DEBUG, "%X %X\n", st->codec->codec_tag, MKTAG('R', 'V', '2', '0'));
313 if (st->codec->codec_id == CODEC_ID_NONE)
314 goto fail1;
315 st->codec->width = get_be16(pb);
316 st->codec->height = get_be16(pb);
317 st->codec->time_base.num= 1;
318 fps= get_be16(pb);
319 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
320 get_be32(pb);
321 fps2= get_be16(pb);
322 get_be16(pb);
323
324 if ((ret = rm_read_extradata(pb, st->codec, codec_data_size - (url_ftell(pb) - codec_pos))) < 0)
325 return ret;
326
327 // av_log(s, AV_LOG_DEBUG, "fps= %d fps2= %d\n", fps, fps2);
328 st->codec->time_base.den = fps * st->codec->time_base.num;
329 //XXX: do we really need that?
330 switch(st->codec->extradata[4]>>4){
331 case 1: st->codec->codec_id = CODEC_ID_RV10; break;
332 case 2: st->codec->codec_id = CODEC_ID_RV20; break;
333 case 3: st->codec->codec_id = CODEC_ID_RV30; break;
334 case 4: st->codec->codec_id = CODEC_ID_RV40; break;
335 default:
336 av_log(st->codec, AV_LOG_ERROR, "extra:%02X %02X %02X %02X %02X\n", st->codec->extradata[0], st->codec->extradata[1], st->codec->extradata[2], st->codec->extradata[3], st->codec->extradata[4]);
337 goto fail1;
338 }
339 }
340
341 skip:
342 /* skip codec info */
343 size = url_ftell(pb) - codec_pos;
344 url_fskip(pb, codec_data_size - size);
345
346 return 0;
347 }
348
349 /** this function assumes that the demuxer has already seeked to the start
350 * of the INDX chunk, and will bail out if not. */
351 static int rm_read_index(AVFormatContext *s)
352 {
353 ByteIOContext *pb = s->pb;
354 unsigned int size, n_pkts, str_id, next_off, n, pos, pts;
355 AVStream *st;
356
357 do {
358 if (get_le32(pb) != MKTAG('I','N','D','X'))
359 return -1;
360 size = get_be32(pb);
361 if (size < 20)
362 return -1;
363 url_fskip(pb, 2);
364 n_pkts = get_be32(pb);
365 str_id = get_be16(pb);
366 next_off = get_be32(pb);
367 for (n = 0; n < s->nb_streams; n++)
368 if (s->streams[n]->id == str_id) {
369 st = s->streams[n];
370 break;
371 }
372 if (n == s->nb_streams)
373 goto skip;
374
375 for (n = 0; n < n_pkts; n++) {
376 url_fskip(pb, 2);
377 pts = get_be32(pb);
378 pos = get_be32(pb);
379 url_fskip(pb, 4); /* packet no. */
380
381 av_add_index_entry(st, pos, pts, 0, 0, AVINDEX_KEYFRAME);
382 }
383
384 skip:
385 if (next_off && url_ftell(pb) != next_off &&
386 url_fseek(pb, next_off, SEEK_SET) < 0)
387 return -1;
388 } while (next_off);
389
390 return 0;
391 }
392
393 static int rm_read_header_old(AVFormatContext *s, AVFormatParameters *ap)
394 {
395 RMDemuxContext *rm = s->priv_data;
396 AVStream *st;
397
398 rm->old_format = 1;
399 st = av_new_stream(s, 0);
400 if (!st)
401 return -1;
402 st->priv_data = ff_rm_alloc_rmstream();
403 return rm_read_audio_stream_info(s, s->pb, st, st->priv_data, 1);
404 }
405
406 static int rm_read_header(AVFormatContext *s, AVFormatParameters *ap)
407 {
408 RMDemuxContext *rm = s->priv_data;
409 AVStream *st;
410 ByteIOContext *pb = s->pb;
411 unsigned int tag;
412 int tag_size;
413 unsigned int start_time, duration;
414 unsigned int data_off = 0, indx_off = 0;
415 char buf[128];
416 int flags = 0;
417
418 tag = get_le32(pb);
419 if (tag == MKTAG('.', 'r', 'a', 0xfd)) {
420 /* very old .ra format */
421 return rm_read_header_old(s, ap);
422 } else if (tag != MKTAG('.', 'R', 'M', 'F')) {
423 return AVERROR(EIO);
424 }
425
426 get_be32(pb); /* header size */
427 get_be16(pb);
428 get_be32(pb);
429 get_be32(pb); /* number of headers */
430
431 for(;;) {
432 if (url_feof(pb))
433 return -1;
434 tag = get_le32(pb);
435 tag_size = get_be32(pb);
436 get_be16(pb);
437 #if 0
438 printf("tag=%c%c%c%c (%08x) size=%d\n",
439 (tag) & 0xff,
440 (tag >> 8) & 0xff,
441 (tag >> 16) & 0xff,
442 (tag >> 24) & 0xff,
443 tag,
444 tag_size);
445 #endif
446 if (tag_size < 10 && tag != MKTAG('D', 'A', 'T', 'A'))
447 return -1;
448 switch(tag) {
449 case MKTAG('P', 'R', 'O', 'P'):
450 /* file header */
451 get_be32(pb); /* max bit rate */
452 get_be32(pb); /* avg bit rate */
453 get_be32(pb); /* max packet size */
454 get_be32(pb); /* avg packet size */
455 get_be32(pb); /* nb packets */
456 get_be32(pb); /* duration */
457 get_be32(pb); /* preroll */
458 indx_off = get_be32(pb); /* index offset */
459 data_off = get_be32(pb); /* data offset */
460 get_be16(pb); /* nb streams */
461 flags = get_be16(pb); /* flags */
462 break;
463 case MKTAG('C', 'O', 'N', 'T'):
464 rm_read_metadata(s, 1);
465 break;
466 case MKTAG('M', 'D', 'P', 'R'):
467 st = av_new_stream(s, 0);
468 if (!st)
469 return AVERROR(ENOMEM);
470 st->id = get_be16(pb);
471 get_be32(pb); /* max bit rate */
472 st->codec->bit_rate = get_be32(pb); /* bit rate */
473 get_be32(pb); /* max packet size */
474 get_be32(pb); /* avg packet size */
475 start_time = get_be32(pb); /* start time */
476 get_be32(pb); /* preroll */
477 duration = get_be32(pb); /* duration */
478 st->start_time = start_time;
479 st->duration = duration;
480 get_str8(pb, buf, sizeof(buf)); /* desc */
481 get_str8(pb, buf, sizeof(buf)); /* mimetype */
482 st->codec->codec_type = AVMEDIA_TYPE_DATA;
483 st->priv_data = ff_rm_alloc_rmstream();
484 if (ff_rm_read_mdpr_codecdata(s, s->pb, st, st->priv_data,
485 get_be32(pb)) < 0)
486 return -1;
487 break;
488 case MKTAG('D', 'A', 'T', 'A'):
489 goto header_end;
490 default:
491 /* unknown tag: skip it */
492 url_fskip(pb, tag_size - 10);
493 break;
494 }
495 }
496 header_end:
497 rm->nb_packets = get_be32(pb); /* number of packets */
498 if (!rm->nb_packets && (flags & 4))
499 rm->nb_packets = 3600 * 25;
500 get_be32(pb); /* next data header */
501
502 if (!data_off)
503 data_off = url_ftell(pb) - 18;
504 if (indx_off && url_fseek(pb, indx_off, SEEK_SET) >= 0) {
505 rm_read_index(s);
506 url_fseek(pb, data_off + 18, SEEK_SET);
507 }
508
509 return 0;
510 }
511
512 static int get_num(ByteIOContext *pb, int *len)
513 {
514 int n, n1;
515
516 n = get_be16(pb);
517 (*len)-=2;
518 n &= 0x7FFF;
519 if (n >= 0x4000) {
520 return n - 0x4000;
521 } else {
522 n1 = get_be16(pb);
523 (*len)-=2;
524 return (n << 16) | n1;
525 }
526 }
527
528 /* multiple of 20 bytes for ra144 (ugly) */
529 #define RAW_PACKET_SIZE 1000
530
531 static int sync(AVFormatContext *s, int64_t *timestamp, int *flags, int *stream_index, int64_t *pos){
532 RMDemuxContext *rm = s->priv_data;
533 ByteIOContext *pb = s->pb;
534 AVStream *st;
535 uint32_t state=0xFFFFFFFF;
536
537 while(!url_feof(pb)){
538 int len, num, i;
539 *pos= url_ftell(pb) - 3;
540 if(rm->remaining_len > 0){
541 num= rm->current_stream;
542 len= rm->remaining_len;
543 *timestamp = AV_NOPTS_VALUE;
544 *flags= 0;
545 }else{
546 state= (state<<8) + get_byte(pb);
547
548 if(state == MKBETAG('I', 'N', 'D', 'X')){
549 int n_pkts, expected_len;
550 len = get_be32(pb);
551 url_fskip(pb, 2);
552 n_pkts = get_be32(pb);
553 expected_len = 20 + n_pkts * 14;
554 if (len == 20)
555 /* some files don't add index entries to chunk size... */
556 len = expected_len;
557 else if (len != expected_len)
558 av_log(s, AV_LOG_WARNING,
559 "Index size %d (%d pkts) is wrong, should be %d.\n",
560 len, n_pkts, expected_len);
561 len -= 14; // we already read part of the index header
562 if(len<0)
563 continue;
564 goto skip;
565 } else if (state == MKBETAG('D','A','T','A')) {
566 av_log(s, AV_LOG_WARNING,
567 "DATA tag in middle of chunk, file may be broken.\n");
568 }
569
570 if(state > (unsigned)0xFFFF || state <= 12)
571 continue;
572 len=state - 12;
573 state= 0xFFFFFFFF;
574
575 num = get_be16(pb);
576 *timestamp = get_be32(pb);
577 get_byte(pb); /* reserved */
578 *flags = get_byte(pb); /* flags */
579 }
580 for(i=0;i<s->nb_streams;i++) {
581 st = s->streams[i];
582 if (num == st->id)
583 break;
584 }
585 if (i == s->nb_streams) {
586 skip:
587 /* skip packet if unknown number */
588 url_fskip(pb, len);
589 rm->remaining_len = 0;
590 continue;
591 }
592 *stream_index= i;
593
594 return len;
595 }
596 return -1;
597 }
598
599 static int rm_assemble_video_frame(AVFormatContext *s, ByteIOContext *pb,
600 RMDemuxContext *rm, RMStream *vst,
601 AVPacket *pkt, int len, int *pseq)
602 {
603 int hdr, seq, pic_num, len2, pos;
604 int type;
605
606 hdr = get_byte(pb); len--;
607 type = hdr >> 6;
608
609 if(type != 3){ // not frame as a part of packet
610 seq = get_byte(pb); len--;
611 }
612 if(type != 1){ // not whole frame
613 len2 = get_num(pb, &len);
614 pos = get_num(pb, &len);
615 pic_num = get_byte(pb); len--;
616 }
617 if(len<0)
618 return -1;
619 rm->remaining_len = len;
620 if(type&1){ // frame, not slice
621 if(type == 3) // frame as a part of packet
622 len= len2;
623 if(rm->remaining_len < len)
624 return -1;
625 rm->remaining_len -= len;
626 if(av_new_packet(pkt, len + 9) < 0)
627 return AVERROR(EIO);
628 pkt->data[0] = 0;
629 AV_WL32(pkt->data + 1, 1);
630 AV_WL32(pkt->data + 5, 0);
631 get_buffer(pb, pkt->data + 9, len);
632 return 0;
633 }
634 //now we have to deal with single slice
635
636 *pseq = seq;
637 if((seq & 0x7F) == 1 || vst->curpic_num != pic_num){
638 vst->slices = ((hdr & 0x3F) << 1) + 1;
639 vst->videobufsize = len2 + 8*vst->slices + 1;
640 av_free_packet(&vst->pkt); //FIXME this should be output.
641 if(av_new_packet(&vst->pkt, vst->videobufsize) < 0)
642 return AVERROR(ENOMEM);
643 vst->videobufpos = 8*vst->slices + 1;
644 vst->cur_slice = 0;
645 vst->curpic_num = pic_num;
646 vst->pktpos = url_ftell(pb);
647 }
648 if(type == 2)
649 len = FFMIN(len, pos);
650
651 if(++vst->cur_slice > vst->slices)
652 return 1;
653 AV_WL32(vst->pkt.data - 7 + 8*vst->cur_slice, 1);
654 AV_WL32(vst->pkt.data - 3 + 8*vst->cur_slice, vst->videobufpos - 8*vst->slices - 1);
655 if(vst->videobufpos + len > vst->videobufsize)
656 return 1;
657 if (get_buffer(pb, vst->pkt.data + vst->videobufpos, len) != len)
658 return AVERROR(EIO);
659 vst->videobufpos += len;
660 rm->remaining_len-= len;
661
662 if(type == 2 || (vst->videobufpos) == vst->videobufsize){
663 vst->pkt.data[0] = vst->cur_slice-1;
664 *pkt= vst->pkt;
665 vst->pkt.data= NULL;
666 vst->pkt.size= 0;
667 if(vst->slices != vst->cur_slice) //FIXME find out how to set slices correct from the begin
668 memmove(pkt->data + 1 + 8*vst->cur_slice, pkt->data + 1 + 8*vst->slices,
669 vst->videobufpos - 1 - 8*vst->slices);
670 pkt->size = vst->videobufpos + 8*(vst->cur_slice - vst->slices);
671 pkt->pts = AV_NOPTS_VALUE;
672 pkt->pos = vst->pktpos;
673 vst->slices = 0;
674 return 0;
675 }
676
677 return 1;
678 }
679
680 static inline void
681 rm_ac3_swap_bytes (AVStream *st, AVPacket *pkt)
682 {
683 uint8_t *ptr;
684 int j;
685
686 if (st->codec->codec_id == CODEC_ID_AC3) {
687 ptr = pkt->data;
688 for (j=0;j<pkt->size;j+=2) {
689 FFSWAP(int, ptr[0], ptr[1]);
690 ptr += 2;
691 }
692 }
693 }
694
695 /**
696 * Perform 4-bit block reordering for SIPR data.
697 * @todo This can be optimized, e.g. use memcpy() if data blocks are aligned
698 */
699 void ff_rm_reorder_sipr_data(uint8_t *buf, int sub_packet_h, int framesize)
700 {
701 int n, bs = sub_packet_h * framesize * 2 / 96; // nibbles per subpacket
702
703 for (n = 0; n < 38; n++) {
704 int j;
705 int i = bs * sipr_swaps[n][0];
706 int o = bs * sipr_swaps[n][1];
707
708 /* swap 4bit-nibbles of block 'i' with 'o' */
709 for (j = 0; j < bs; j++, i++, o++) {
710 int x = (buf[i >> 1] >> (4 * (i & 1))) & 0xF,
711 y = (buf[o >> 1] >> (4 * (o & 1))) & 0xF;
712
713 buf[o >> 1] = (x << (4 * (o & 1))) |
714 (buf[o >> 1] & (0xF << (4 * !(o & 1))));
715 buf[i >> 1] = (y << (4 * (i & 1))) |
716 (buf[i >> 1] & (0xF << (4 * !(i & 1))));
717 }
718 }
719 }
720
721 int
722 ff_rm_parse_packet (AVFormatContext *s, ByteIOContext *pb,
723 AVStream *st, RMStream *ast, int len, AVPacket *pkt,
724 int *seq, int flags, int64_t timestamp)
725 {
726 RMDemuxContext *rm = s->priv_data;
727
728 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
729 rm->current_stream= st->id;
730 if(rm_assemble_video_frame(s, pb, rm, ast, pkt, len, seq))
731 return -1; //got partial frame
732 } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
733 if ((st->codec->codec_id == CODEC_ID_RA_288) ||
734 (st->codec->codec_id == CODEC_ID_COOK) ||
735 (st->codec->codec_id == CODEC_ID_ATRAC3) ||
736 (st->codec->codec_id == CODEC_ID_SIPR)) {
737 int x;
738 int sps = ast->sub_packet_size;
739 int cfs = ast->coded_framesize;
740 int h = ast->sub_packet_h;
741 int y = ast->sub_packet_cnt;
742 int w = ast->audio_framesize;
743
744 if (flags & 2)
745 y = ast->sub_packet_cnt = 0;
746 if (!y)
747 ast->audiotimestamp = timestamp;
748
749 switch(st->codec->codec_id) {
750 case CODEC_ID_RA_288:
751 for (x = 0; x < h/2; x++)
752 get_buffer(pb, ast->pkt.data+x*2*w+y*cfs, cfs);
753 break;
754 case CODEC_ID_ATRAC3:
755 case CODEC_ID_COOK:
756 for (x = 0; x < w/sps; x++)
757 get_buffer(pb, ast->pkt.data+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), sps);
758 break;
759 case CODEC_ID_SIPR:
760 get_buffer(pb, ast->pkt.data + y * w, w);
761 break;
762 }
763
764 if (++(ast->sub_packet_cnt) < h)
765 return -1;
766 if (st->codec->codec_id == CODEC_ID_SIPR)
767 ff_rm_reorder_sipr_data(ast->pkt.data, h, w);
768
769 ast->sub_packet_cnt = 0;
770 rm->audio_stream_num = st->index;
771 rm->audio_pkt_cnt = h * w / st->codec->block_align;
772 } else if (st->codec->codec_id == CODEC_ID_AAC) {
773 int x;
774 rm->audio_stream_num = st->index;
775 ast->sub_packet_cnt = (get_be16(pb) & 0xf0) >> 4;
776 if (ast->sub_packet_cnt) {
777 for (x = 0; x < ast->sub_packet_cnt; x++)
778 ast->sub_packet_lengths[x] = get_be16(pb);
779 rm->audio_pkt_cnt = ast->sub_packet_cnt;
780 ast->audiotimestamp = timestamp;
781 } else
782 return -1;
783 } else {
784 av_get_packet(pb, pkt, len);
785 rm_ac3_swap_bytes(st, pkt);
786 }
787 } else
788 av_get_packet(pb, pkt, len);
789
790 pkt->stream_index = st->index;
791
792 #if 0
793 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
794 if(st->codec->codec_id == CODEC_ID_RV20){
795 int seq= 128*(pkt->data[2]&0x7F) + (pkt->data[3]>>1);
796 av_log(s, AV_LOG_DEBUG, "%d %"PRId64" %d\n", *timestamp, *timestamp*512LL/25, seq);
797
798 seq |= (timestamp&~0x3FFF);
799 if(seq - timestamp > 0x2000) seq -= 0x4000;
800 if(seq - timestamp < -0x2000) seq += 0x4000;
801 }
802 }
803 #endif
804
805 pkt->pts= timestamp;
806 if (flags & 2)
807 pkt->flags |= AV_PKT_FLAG_KEY;
808
809 return st->codec->codec_type == AVMEDIA_TYPE_AUDIO ? rm->audio_pkt_cnt : 0;
810 }
811
812 int
813 ff_rm_retrieve_cache (AVFormatContext *s, ByteIOContext *pb,
814 AVStream *st, RMStream *ast, AVPacket *pkt)
815 {
816 RMDemuxContext *rm = s->priv_data;
817
818 assert (rm->audio_pkt_cnt > 0);
819
820 if (st->codec->codec_id == CODEC_ID_AAC)
821 av_get_packet(pb, pkt, ast->sub_packet_lengths[ast->sub_packet_cnt - rm->audio_pkt_cnt]);
822 else {
823 av_new_packet(pkt, st->codec->block_align);
824 memcpy(pkt->data, ast->pkt.data + st->codec->block_align * //FIXME avoid this
825 (ast->sub_packet_h * ast->audio_framesize / st->codec->block_align - rm->audio_pkt_cnt),
826 st->codec->block_align);
827 }
828 rm->audio_pkt_cnt--;
829 if ((pkt->pts = ast->audiotimestamp) != AV_NOPTS_VALUE) {
830 ast->audiotimestamp = AV_NOPTS_VALUE;
831 pkt->flags = AV_PKT_FLAG_KEY;
832 } else
833 pkt->flags = 0;
834 pkt->stream_index = st->index;
835
836 return rm->audio_pkt_cnt;
837 }
838
839 static int rm_read_packet(AVFormatContext *s, AVPacket *pkt)
840 {
841 RMDemuxContext *rm = s->priv_data;
842 AVStream *st;
843 int i, len, res, seq = 1;
844 int64_t timestamp, pos;
845 int flags;
846
847 for (;;) {
848 if (rm->audio_pkt_cnt) {
849 // If there are queued audio packet return them first
850 st = s->streams[rm->audio_stream_num];
851 ff_rm_retrieve_cache(s, s->pb, st, st->priv_data, pkt);
852 flags = 0;
853 } else {
854 if (rm->old_format) {
855 RMStream *ast;
856
857 st = s->streams[0];
858 ast = st->priv_data;
859 timestamp = AV_NOPTS_VALUE;
860 len = !ast->audio_framesize ? RAW_PACKET_SIZE :
861 ast->coded_framesize * ast->sub_packet_h / 2;
862 flags = (seq++ == 1) ? 2 : 0;
863 } else {
864 len=sync(s, &timestamp, &flags, &i, &pos);
865 if (len > 0)
866 st = s->streams[i];
867 }
868
869 if(len<0 || url_feof(s->pb))
870 return AVERROR(EIO);
871
872 res = ff_rm_parse_packet (s, s->pb, st, st->priv_data, len, pkt,
873 &seq, flags, timestamp);
874 if((flags&2) && (seq&0x7F) == 1)
875 av_add_index_entry(st, pos, timestamp, 0, 0, AVINDEX_KEYFRAME);
876 if (res)
877 continue;
878 }
879
880 if( (st->discard >= AVDISCARD_NONKEY && !(flags&2))
881 || st->discard >= AVDISCARD_ALL){
882 av_free_packet(pkt);
883 } else
884 break;
885 }
886
887 return 0;
888 }
889
890 static int rm_read_close(AVFormatContext *s)
891 {
892 int i;
893
894 for (i=0;i<s->nb_streams;i++)
895 ff_rm_free_rmstream(s->streams[i]->priv_data);
896
897 return 0;
898 }
899
900 static int rm_probe(AVProbeData *p)
901 {
902 /* check file header */
903 if ((p->buf[0] == '.' && p->buf[1] == 'R' &&
904 p->buf[2] == 'M' && p->buf[3] == 'F' &&
905 p->buf[4] == 0 && p->buf[5] == 0) ||
906 (p->buf[0] == '.' && p->buf[1] == 'r' &&
907 p->buf[2] == 'a' && p->buf[3] == 0xfd))
908 return AVPROBE_SCORE_MAX;
909 else
910 return 0;
911 }
912
913 static int64_t rm_read_dts(AVFormatContext *s, int stream_index,
914 int64_t *ppos, int64_t pos_limit)
915 {
916 RMDemuxContext *rm = s->priv_data;
917 int64_t pos, dts;
918 int stream_index2, flags, len, h;
919
920 pos = *ppos;
921
922 if(rm->old_format)
923 return AV_NOPTS_VALUE;
924
925 url_fseek(s->pb, pos, SEEK_SET);
926 rm->remaining_len=0;
927 for(;;){
928 int seq=1;
929 AVStream *st;
930
931 len=sync(s, &dts, &flags, &stream_index2, &pos);
932 if(len<0)
933 return AV_NOPTS_VALUE;
934
935 st = s->streams[stream_index2];
936 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
937 h= get_byte(s->pb); len--;
938 if(!(h & 0x40)){
939 seq = get_byte(s->pb); len--;
940 }
941 }
942
943 if((flags&2) && (seq&0x7F) == 1){
944 // av_log(s, AV_LOG_DEBUG, "%d %d-%d %"PRId64" %d\n", flags, stream_index2, stream_index, dts, seq);
945 av_add_index_entry(st, pos, dts, 0, 0, AVINDEX_KEYFRAME);
946 if(stream_index2 == stream_index)
947 break;
948 }
949
950 url_fskip(s->pb, len);
951 }
952 *ppos = pos;
953 return dts;
954 }
955
956 AVInputFormat rm_demuxer = {
957 "rm",
958 NULL_IF_CONFIG_SMALL("RealMedia format"),
959 sizeof(RMDemuxContext),
960 rm_probe,
961 rm_read_header,
962 rm_read_packet,
963 rm_read_close,
964 NULL,
965 rm_read_dts,
966 };
967
968 AVInputFormat rdt_demuxer = {
969 "rdt",
970 NULL_IF_CONFIG_SMALL("RDT demuxer"),
971 sizeof(RMDemuxContext),
972 NULL,
973 NULL,
974 NULL,
975 rm_read_close,
976 };