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