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