]> git.sesse.net Git - ffmpeg/blob - libavformat/rm.c
add 'wide' reversed tag in probe, detect broken xdcam files xdcam_hd_1080i60.mov
[ffmpeg] / libavformat / rm.c
1 /*
2  * "Real" compatible muxer and 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 #include "avformat.h"
22
23 /* in ms */
24 #define BUFFER_DURATION 0
25
26 typedef struct {
27     int nb_packets;
28     int packet_total_size;
29     int packet_max_size;
30     /* codec related output */
31     int bit_rate;
32     float frame_rate;
33     int nb_frames;    /* current frame number */
34     int total_frames; /* total number of frames */
35     int num;
36     AVCodecContext *enc;
37 } StreamInfo;
38
39 typedef struct {
40     StreamInfo streams[2];
41     StreamInfo *audio_stream, *video_stream;
42     int data_pos; /* position of the data after the header */
43     int nb_packets;
44     int old_format;
45     int current_stream;
46     int remaining_len;
47     /// Audio descrambling matrix parameters
48     uint8_t *audiobuf; ///< place to store reordered audio data
49     int64_t audiotimestamp; ///< Audio packet timestamp
50     int sub_packet_cnt; // Subpacket counter, used while reading
51     int sub_packet_size, sub_packet_h, coded_framesize; ///< Descrambling parameters from container
52     int audio_stream_num; ///< Stream number for audio packets
53     int audio_pkt_cnt; ///< Output packet counter
54     int audio_framesize; /// Audio frame size from container
55     int sub_packet_lengths[16]; /// Length of each aac subpacket
56 } RMContext;
57
58 #ifdef CONFIG_MUXERS
59 static void put_str(ByteIOContext *s, const char *tag)
60 {
61     put_be16(s,strlen(tag));
62     while (*tag) {
63         put_byte(s, *tag++);
64     }
65 }
66
67 static void put_str8(ByteIOContext *s, const char *tag)
68 {
69     put_byte(s, strlen(tag));
70     while (*tag) {
71         put_byte(s, *tag++);
72     }
73 }
74
75 static void rv10_write_header(AVFormatContext *ctx,
76                               int data_size, int index_pos)
77 {
78     RMContext *rm = ctx->priv_data;
79     ByteIOContext *s = &ctx->pb;
80     StreamInfo *stream;
81     unsigned char *data_offset_ptr, *start_ptr;
82     const char *desc, *mimetype;
83     int nb_packets, packet_total_size, packet_max_size, size, packet_avg_size, i;
84     int bit_rate, v, duration, flags, data_pos;
85
86     start_ptr = s->buf_ptr;
87
88     put_tag(s, ".RMF");
89     put_be32(s,18); /* header size */
90     put_be16(s,0);
91     put_be32(s,0);
92     put_be32(s,4 + ctx->nb_streams); /* num headers */
93
94     put_tag(s,"PROP");
95     put_be32(s, 50);
96     put_be16(s, 0);
97     packet_max_size = 0;
98     packet_total_size = 0;
99     nb_packets = 0;
100     bit_rate = 0;
101     duration = 0;
102     for(i=0;i<ctx->nb_streams;i++) {
103         StreamInfo *stream = &rm->streams[i];
104         bit_rate += stream->bit_rate;
105         if (stream->packet_max_size > packet_max_size)
106             packet_max_size = stream->packet_max_size;
107         nb_packets += stream->nb_packets;
108         packet_total_size += stream->packet_total_size;
109         /* select maximum duration */
110         v = (int) (1000.0 * (float)stream->total_frames / stream->frame_rate);
111         if (v > duration)
112             duration = v;
113     }
114     put_be32(s, bit_rate); /* max bit rate */
115     put_be32(s, bit_rate); /* avg bit rate */
116     put_be32(s, packet_max_size);        /* max packet size */
117     if (nb_packets > 0)
118         packet_avg_size = packet_total_size / nb_packets;
119     else
120         packet_avg_size = 0;
121     put_be32(s, packet_avg_size);        /* avg packet size */
122     put_be32(s, nb_packets);  /* num packets */
123     put_be32(s, duration); /* duration */
124     put_be32(s, BUFFER_DURATION);           /* preroll */
125     put_be32(s, index_pos);           /* index offset */
126     /* computation of data the data offset */
127     data_offset_ptr = s->buf_ptr;
128     put_be32(s, 0);           /* data offset : will be patched after */
129     put_be16(s, ctx->nb_streams);    /* num streams */
130     flags = 1 | 2; /* save allowed & perfect play */
131     if (url_is_streamed(s))
132         flags |= 4; /* live broadcast */
133     put_be16(s, flags);
134
135     /* comments */
136
137     put_tag(s,"CONT");
138     size = strlen(ctx->title) + strlen(ctx->author) + strlen(ctx->copyright) +
139         strlen(ctx->comment) + 4 * 2 + 10;
140     put_be32(s,size);
141     put_be16(s,0);
142     put_str(s, ctx->title);
143     put_str(s, ctx->author);
144     put_str(s, ctx->copyright);
145     put_str(s, ctx->comment);
146
147     for(i=0;i<ctx->nb_streams;i++) {
148         int codec_data_size;
149
150         stream = &rm->streams[i];
151
152         if (stream->enc->codec_type == CODEC_TYPE_AUDIO) {
153             desc = "The Audio Stream";
154             mimetype = "audio/x-pn-realaudio";
155             codec_data_size = 73;
156         } else {
157             desc = "The Video Stream";
158             mimetype = "video/x-pn-realvideo";
159             codec_data_size = 34;
160         }
161
162         put_tag(s,"MDPR");
163         size = 10 + 9 * 4 + strlen(desc) + strlen(mimetype) + codec_data_size;
164         put_be32(s, size);
165         put_be16(s, 0);
166
167         put_be16(s, i); /* stream number */
168         put_be32(s, stream->bit_rate); /* max bit rate */
169         put_be32(s, stream->bit_rate); /* avg bit rate */
170         put_be32(s, stream->packet_max_size);        /* max packet size */
171         if (stream->nb_packets > 0)
172             packet_avg_size = stream->packet_total_size /
173                 stream->nb_packets;
174         else
175             packet_avg_size = 0;
176         put_be32(s, packet_avg_size);        /* avg packet size */
177         put_be32(s, 0);           /* start time */
178         put_be32(s, BUFFER_DURATION);           /* preroll */
179         /* duration */
180         if (url_is_streamed(s) || !stream->total_frames)
181             put_be32(s, (int)(3600 * 1000));
182         else
183             put_be32(s, (int)(stream->total_frames * 1000 / stream->frame_rate));
184         put_str8(s, desc);
185         put_str8(s, mimetype);
186         put_be32(s, codec_data_size);
187
188         if (stream->enc->codec_type == CODEC_TYPE_AUDIO) {
189             int coded_frame_size, fscode, sample_rate;
190             sample_rate = stream->enc->sample_rate;
191             coded_frame_size = (stream->enc->bit_rate *
192                                 stream->enc->frame_size) / (8 * sample_rate);
193             /* audio codec info */
194             put_tag(s, ".ra");
195             put_byte(s, 0xfd);
196             put_be32(s, 0x00040000); /* version */
197             put_tag(s, ".ra4");
198             put_be32(s, 0x01b53530); /* stream length */
199             put_be16(s, 4); /* unknown */
200             put_be32(s, 0x39); /* header size */
201
202             switch(sample_rate) {
203             case 48000:
204             case 24000:
205             case 12000:
206                 fscode = 1;
207                 break;
208             default:
209             case 44100:
210             case 22050:
211             case 11025:
212                 fscode = 2;
213                 break;
214             case 32000:
215             case 16000:
216             case 8000:
217                 fscode = 3;
218             }
219             put_be16(s, fscode); /* codec additional info, for AC3, seems
220                                      to be a frequency code */
221             /* special hack to compensate rounding errors... */
222             if (coded_frame_size == 557)
223                 coded_frame_size--;
224             put_be32(s, coded_frame_size); /* frame length */
225             put_be32(s, 0x51540); /* unknown */
226             put_be32(s, 0x249f0); /* unknown */
227             put_be32(s, 0x249f0); /* unknown */
228             put_be16(s, 0x01);
229             /* frame length : seems to be very important */
230             put_be16(s, coded_frame_size);
231             put_be32(s, 0); /* unknown */
232             put_be16(s, stream->enc->sample_rate); /* sample rate */
233             put_be32(s, 0x10); /* unknown */
234             put_be16(s, stream->enc->channels);
235             put_str8(s, "Int0"); /* codec name */
236             put_str8(s, "dnet"); /* codec name */
237             put_be16(s, 0); /* title length */
238             put_be16(s, 0); /* author length */
239             put_be16(s, 0); /* copyright length */
240             put_byte(s, 0); /* end of header */
241         } else {
242             /* video codec info */
243             put_be32(s,34); /* size */
244             if(stream->enc->codec_id == CODEC_ID_RV10)
245                 put_tag(s,"VIDORV10");
246             else
247                 put_tag(s,"VIDORV20");
248             put_be16(s, stream->enc->width);
249             put_be16(s, stream->enc->height);
250             put_be16(s, (int) stream->frame_rate); /* frames per seconds ? */
251             put_be32(s,0);     /* unknown meaning */
252             put_be16(s, (int) stream->frame_rate);  /* unknown meaning */
253             put_be32(s,0);     /* unknown meaning */
254             put_be16(s, 8);    /* unknown meaning */
255             /* Seems to be the codec version: only use basic H263. The next
256                versions seems to add a diffential DC coding as in
257                MPEG... nothing new under the sun */
258             if(stream->enc->codec_id == CODEC_ID_RV10)
259                 put_be32(s,0x10000000);
260             else
261                 put_be32(s,0x20103001);
262             //put_be32(s,0x10003000);
263         }
264     }
265
266     /* patch data offset field */
267     data_pos = s->buf_ptr - start_ptr;
268     rm->data_pos = data_pos;
269     data_offset_ptr[0] = data_pos >> 24;
270     data_offset_ptr[1] = data_pos >> 16;
271     data_offset_ptr[2] = data_pos >> 8;
272     data_offset_ptr[3] = data_pos;
273
274     /* data stream */
275     put_tag(s,"DATA");
276     put_be32(s,data_size + 10 + 8);
277     put_be16(s,0);
278
279     put_be32(s, nb_packets); /* number of packets */
280     put_be32(s,0); /* next data header */
281 }
282
283 static void write_packet_header(AVFormatContext *ctx, StreamInfo *stream,
284                                 int length, int key_frame)
285 {
286     int timestamp;
287     ByteIOContext *s = &ctx->pb;
288
289     stream->nb_packets++;
290     stream->packet_total_size += length;
291     if (length > stream->packet_max_size)
292         stream->packet_max_size =  length;
293
294     put_be16(s,0); /* version */
295     put_be16(s,length + 12);
296     put_be16(s, stream->num); /* stream number */
297     timestamp = (1000 * (float)stream->nb_frames) / stream->frame_rate;
298     put_be32(s, timestamp); /* timestamp */
299     put_byte(s, 0); /* reserved */
300     put_byte(s, key_frame ? 2 : 0); /* flags */
301 }
302
303 static int rm_write_header(AVFormatContext *s)
304 {
305     RMContext *rm = s->priv_data;
306     StreamInfo *stream;
307     int n;
308     AVCodecContext *codec;
309
310     for(n=0;n<s->nb_streams;n++) {
311         s->streams[n]->id = n;
312         codec = s->streams[n]->codec;
313         stream = &rm->streams[n];
314         memset(stream, 0, sizeof(StreamInfo));
315         stream->num = n;
316         stream->bit_rate = codec->bit_rate;
317         stream->enc = codec;
318
319         switch(codec->codec_type) {
320         case CODEC_TYPE_AUDIO:
321             rm->audio_stream = stream;
322             stream->frame_rate = (float)codec->sample_rate / (float)codec->frame_size;
323             /* XXX: dummy values */
324             stream->packet_max_size = 1024;
325             stream->nb_packets = 0;
326             stream->total_frames = stream->nb_packets;
327             break;
328         case CODEC_TYPE_VIDEO:
329             rm->video_stream = stream;
330             stream->frame_rate = (float)codec->time_base.den / (float)codec->time_base.num;
331             /* XXX: dummy values */
332             stream->packet_max_size = 4096;
333             stream->nb_packets = 0;
334             stream->total_frames = stream->nb_packets;
335             break;
336         default:
337             return -1;
338         }
339     }
340
341     rv10_write_header(s, 0, 0);
342     put_flush_packet(&s->pb);
343     return 0;
344 }
345
346 static int rm_write_audio(AVFormatContext *s, const uint8_t *buf, int size, int flags)
347 {
348     uint8_t *buf1;
349     RMContext *rm = s->priv_data;
350     ByteIOContext *pb = &s->pb;
351     StreamInfo *stream = rm->audio_stream;
352     int i;
353
354     /* XXX: suppress this malloc */
355     buf1= (uint8_t*) av_malloc( size * sizeof(uint8_t) );
356
357     write_packet_header(s, stream, size, !!(flags & PKT_FLAG_KEY));
358
359     /* for AC3, the words seems to be reversed */
360     for(i=0;i<size;i+=2) {
361         buf1[i] = buf[i+1];
362         buf1[i+1] = buf[i];
363     }
364     put_buffer(pb, buf1, size);
365     put_flush_packet(pb);
366     stream->nb_frames++;
367     av_free(buf1);
368     return 0;
369 }
370
371 static int rm_write_video(AVFormatContext *s, const uint8_t *buf, int size, int flags)
372 {
373     RMContext *rm = s->priv_data;
374     ByteIOContext *pb = &s->pb;
375     StreamInfo *stream = rm->video_stream;
376     int key_frame = !!(flags & PKT_FLAG_KEY);
377
378     /* XXX: this is incorrect: should be a parameter */
379
380     /* Well, I spent some time finding the meaning of these bits. I am
381        not sure I understood everything, but it works !! */
382 #if 1
383     write_packet_header(s, stream, size + 7, key_frame);
384     /* bit 7: '1' if final packet of a frame converted in several packets */
385     put_byte(pb, 0x81);
386     /* bit 7: '1' if I frame. bits 6..0 : sequence number in current
387        frame starting from 1 */
388     if (key_frame) {
389         put_byte(pb, 0x81);
390     } else {
391         put_byte(pb, 0x01);
392     }
393     put_be16(pb, 0x4000 + (size)); /* total frame size */
394     put_be16(pb, 0x4000 + (size));              /* offset from the start or the end */
395 #else
396     /* full frame */
397     write_packet_header(s, size + 6);
398     put_byte(pb, 0xc0);
399     put_be16(pb, 0x4000 + size); /* total frame size */
400     put_be16(pb, 0x4000 + packet_number * 126); /* position in stream */
401 #endif
402     put_byte(pb, stream->nb_frames & 0xff);
403
404     put_buffer(pb, buf, size);
405     put_flush_packet(pb);
406
407     stream->nb_frames++;
408     return 0;
409 }
410
411 static int rm_write_packet(AVFormatContext *s, AVPacket *pkt)
412 {
413     if (s->streams[pkt->stream_index]->codec->codec_type ==
414         CODEC_TYPE_AUDIO)
415         return rm_write_audio(s, pkt->data, pkt->size, pkt->flags);
416     else
417         return rm_write_video(s, pkt->data, pkt->size, pkt->flags);
418 }
419
420 static int rm_write_trailer(AVFormatContext *s)
421 {
422     RMContext *rm = s->priv_data;
423     int data_size, index_pos, i;
424     ByteIOContext *pb = &s->pb;
425
426     if (!url_is_streamed(&s->pb)) {
427         /* end of file: finish to write header */
428         index_pos = url_fseek(pb, 0, SEEK_CUR);
429         data_size = index_pos - rm->data_pos;
430
431         /* index */
432         put_tag(pb, "INDX");
433         put_be32(pb, 10 + 10 * s->nb_streams);
434         put_be16(pb, 0);
435
436         for(i=0;i<s->nb_streams;i++) {
437             put_be32(pb, 0); /* zero indices */
438             put_be16(pb, i); /* stream number */
439             put_be32(pb, 0); /* next index */
440         }
441         /* undocumented end header */
442         put_be32(pb, 0);
443         put_be32(pb, 0);
444
445         url_fseek(pb, 0, SEEK_SET);
446         for(i=0;i<s->nb_streams;i++)
447             rm->streams[i].total_frames = rm->streams[i].nb_frames;
448         rv10_write_header(s, data_size, index_pos);
449     } else {
450         /* undocumented end header */
451         put_be32(pb, 0);
452         put_be32(pb, 0);
453     }
454     put_flush_packet(pb);
455     return 0;
456 }
457 #endif //CONFIG_MUXERS
458
459 /***************************************************/
460
461 static void get_str(ByteIOContext *pb, char *buf, int buf_size)
462 {
463     int len, i;
464     char *q;
465
466     len = get_be16(pb);
467     q = buf;
468     for(i=0;i<len;i++) {
469         if (i < buf_size - 1)
470             *q++ = get_byte(pb);
471     }
472     *q = '\0';
473 }
474
475 static void get_str8(ByteIOContext *pb, char *buf, int buf_size)
476 {
477     int len, i;
478     char *q;
479
480     len = get_byte(pb);
481     q = buf;
482     for(i=0;i<len;i++) {
483         if (i < buf_size - 1)
484             *q++ = get_byte(pb);
485     }
486     *q = '\0';
487 }
488
489 static int rm_read_audio_stream_info(AVFormatContext *s, AVStream *st,
490                                       int read_all)
491 {
492     RMContext *rm = s->priv_data;
493     ByteIOContext *pb = &s->pb;
494     char buf[256];
495     uint32_t version;
496     int i;
497
498     /* ra type header */
499     version = get_be32(pb); /* version */
500     if (((version >> 16) & 0xff) == 3) {
501         int64_t startpos = url_ftell(pb);
502         /* very old version */
503         for(i = 0; i < 14; i++)
504             get_byte(pb);
505         get_str8(pb, s->title, sizeof(s->title));
506         get_str8(pb, s->author, sizeof(s->author));
507         get_str8(pb, s->copyright, sizeof(s->copyright));
508         get_str8(pb, s->comment, sizeof(s->comment));
509         if ((startpos + (version & 0xffff)) >= url_ftell(pb) + 2) {
510         // fourcc (should always be "lpcJ")
511         get_byte(pb);
512         get_str8(pb, buf, sizeof(buf));
513         }
514         // Skip extra header crap (this should never happen)
515         if ((startpos + (version & 0xffff)) > url_ftell(pb))
516             url_fskip(pb, (version & 0xffff) + startpos - url_ftell(pb));
517         st->codec->sample_rate = 8000;
518         st->codec->channels = 1;
519         st->codec->codec_type = CODEC_TYPE_AUDIO;
520         st->codec->codec_id = CODEC_ID_RA_144;
521     } else {
522         int flavor, sub_packet_h, coded_framesize, sub_packet_size;
523         /* old version (4) */
524         get_be32(pb); /* .ra4 */
525         get_be32(pb); /* data size */
526         get_be16(pb); /* version2 */
527         get_be32(pb); /* header size */
528         flavor= get_be16(pb); /* add codec info / flavor */
529         rm->coded_framesize = coded_framesize = get_be32(pb); /* coded frame size */
530         get_be32(pb); /* ??? */
531         get_be32(pb); /* ??? */
532         get_be32(pb); /* ??? */
533         rm->sub_packet_h = sub_packet_h = get_be16(pb); /* 1 */
534         st->codec->block_align= get_be16(pb); /* frame size */
535         rm->sub_packet_size = sub_packet_size = get_be16(pb); /* sub packet size */
536         get_be16(pb); /* ??? */
537         if (((version >> 16) & 0xff) == 5) {
538             get_be16(pb); get_be16(pb); get_be16(pb); }
539         st->codec->sample_rate = get_be16(pb);
540         get_be32(pb);
541         st->codec->channels = get_be16(pb);
542         if (((version >> 16) & 0xff) == 5) {
543             get_be32(pb);
544             buf[0] = get_byte(pb);
545             buf[1] = get_byte(pb);
546             buf[2] = get_byte(pb);
547             buf[3] = get_byte(pb);
548             buf[4] = 0;
549         } else {
550             get_str8(pb, buf, sizeof(buf)); /* desc */
551             get_str8(pb, buf, sizeof(buf)); /* desc */
552         }
553         st->codec->codec_type = CODEC_TYPE_AUDIO;
554         if (!strcmp(buf, "dnet")) {
555             st->codec->codec_id = CODEC_ID_AC3;
556         } else if (!strcmp(buf, "28_8")) {
557             st->codec->codec_id = CODEC_ID_RA_288;
558             st->codec->extradata_size= 0;
559             rm->audio_framesize = st->codec->block_align;
560             st->codec->block_align = coded_framesize;
561
562             if(rm->audio_framesize >= UINT_MAX / sub_packet_h){
563                 av_log(s, AV_LOG_ERROR, "rm->audio_framesize * sub_packet_h too large\n");
564                 return -1;
565             }
566
567             rm->audiobuf = av_malloc(rm->audio_framesize * sub_packet_h);
568         } else if ((!strcmp(buf, "cook")) || (!strcmp(buf, "atrc"))) {
569             int codecdata_length, i;
570             get_be16(pb); get_byte(pb);
571             if (((version >> 16) & 0xff) == 5)
572                 get_byte(pb);
573             codecdata_length = get_be32(pb);
574             if(codecdata_length + FF_INPUT_BUFFER_PADDING_SIZE <= (unsigned)codecdata_length){
575                 av_log(s, AV_LOG_ERROR, "codecdata_length too large\n");
576                 return -1;
577             }
578
579             if (!strcmp(buf, "cook")) st->codec->codec_id = CODEC_ID_COOK;
580             else st->codec->codec_id = CODEC_ID_ATRAC3;
581             st->codec->extradata_size= codecdata_length;
582             st->codec->extradata= av_mallocz(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
583             for(i = 0; i < codecdata_length; i++)
584                 ((uint8_t*)st->codec->extradata)[i] = get_byte(pb);
585             rm->audio_framesize = st->codec->block_align;
586             st->codec->block_align = rm->sub_packet_size;
587
588             if(rm->audio_framesize >= UINT_MAX / sub_packet_h){
589                 av_log(s, AV_LOG_ERROR, "rm->audio_framesize * sub_packet_h too large\n");
590                 return -1;
591             }
592
593             rm->audiobuf = av_malloc(rm->audio_framesize * sub_packet_h);
594         } else if (!strcmp(buf, "raac") || !strcmp(buf, "racp")) {
595             int codecdata_length, i;
596             get_be16(pb); get_byte(pb);
597             if (((version >> 16) & 0xff) == 5)
598                 get_byte(pb);
599             st->codec->codec_id = CODEC_ID_AAC;
600             codecdata_length = get_be32(pb);
601             if(codecdata_length + FF_INPUT_BUFFER_PADDING_SIZE <= (unsigned)codecdata_length){
602                 av_log(s, AV_LOG_ERROR, "codecdata_length too large\n");
603                 return -1;
604             }
605             if (codecdata_length >= 1) {
606                 st->codec->extradata_size = codecdata_length - 1;
607                 st->codec->extradata = av_mallocz(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
608                 get_byte(pb);
609                 for(i = 0; i < st->codec->extradata_size; i++)
610                     ((uint8_t*)st->codec->extradata)[i] = get_byte(pb);
611             }
612         } else {
613             st->codec->codec_id = CODEC_ID_NONE;
614             pstrcpy(st->codec->codec_name, sizeof(st->codec->codec_name),
615                     buf);
616         }
617         if (read_all) {
618             get_byte(pb);
619             get_byte(pb);
620             get_byte(pb);
621
622             get_str8(pb, s->title, sizeof(s->title));
623             get_str8(pb, s->author, sizeof(s->author));
624             get_str8(pb, s->copyright, sizeof(s->copyright));
625             get_str8(pb, s->comment, sizeof(s->comment));
626         }
627     }
628     return 0;
629 }
630
631 static int rm_read_header_old(AVFormatContext *s, AVFormatParameters *ap)
632 {
633     RMContext *rm = s->priv_data;
634     AVStream *st;
635
636     rm->old_format = 1;
637     st = av_new_stream(s, 0);
638     if (!st)
639         return -1;
640     return rm_read_audio_stream_info(s, st, 1);
641 }
642
643 static int rm_read_header(AVFormatContext *s, AVFormatParameters *ap)
644 {
645     RMContext *rm = s->priv_data;
646     AVStream *st;
647     ByteIOContext *pb = &s->pb;
648     unsigned int tag, v;
649     int tag_size, size, codec_data_size, i;
650     int64_t codec_pos;
651     unsigned int start_time, duration;
652     char buf[128];
653     int flags = 0;
654
655     tag = get_le32(pb);
656     if (tag == MKTAG('.', 'r', 'a', 0xfd)) {
657         /* very old .ra format */
658         return rm_read_header_old(s, ap);
659     } else if (tag != MKTAG('.', 'R', 'M', 'F')) {
660         return AVERROR_IO;
661     }
662
663     get_be32(pb); /* header size */
664     get_be16(pb);
665     get_be32(pb);
666     get_be32(pb); /* number of headers */
667
668     for(;;) {
669         if (url_feof(pb))
670             goto fail;
671         tag = get_le32(pb);
672         tag_size = get_be32(pb);
673         get_be16(pb);
674 #if 0
675         printf("tag=%c%c%c%c (%08x) size=%d\n",
676                (tag) & 0xff,
677                (tag >> 8) & 0xff,
678                (tag >> 16) & 0xff,
679                (tag >> 24) & 0xff,
680                tag,
681                tag_size);
682 #endif
683         if (tag_size < 10 && tag != MKTAG('D', 'A', 'T', 'A'))
684             goto fail;
685         switch(tag) {
686         case MKTAG('P', 'R', 'O', 'P'):
687             /* file header */
688             get_be32(pb); /* max bit rate */
689             get_be32(pb); /* avg bit rate */
690             get_be32(pb); /* max packet size */
691             get_be32(pb); /* avg packet size */
692             get_be32(pb); /* nb packets */
693             get_be32(pb); /* duration */
694             get_be32(pb); /* preroll */
695             get_be32(pb); /* index offset */
696             get_be32(pb); /* data offset */
697             get_be16(pb); /* nb streams */
698             flags = get_be16(pb); /* flags */
699             break;
700         case MKTAG('C', 'O', 'N', 'T'):
701             get_str(pb, s->title, sizeof(s->title));
702             get_str(pb, s->author, sizeof(s->author));
703             get_str(pb, s->copyright, sizeof(s->copyright));
704             get_str(pb, s->comment, sizeof(s->comment));
705             break;
706         case MKTAG('M', 'D', 'P', 'R'):
707             st = av_new_stream(s, 0);
708             if (!st)
709                 goto fail;
710             st->id = get_be16(pb);
711             get_be32(pb); /* max bit rate */
712             st->codec->bit_rate = get_be32(pb); /* bit rate */
713             get_be32(pb); /* max packet size */
714             get_be32(pb); /* avg packet size */
715             start_time = get_be32(pb); /* start time */
716             get_be32(pb); /* preroll */
717             duration = get_be32(pb); /* duration */
718             st->start_time = start_time;
719             st->duration = duration;
720             get_str8(pb, buf, sizeof(buf)); /* desc */
721             get_str8(pb, buf, sizeof(buf)); /* mimetype */
722             codec_data_size = get_be32(pb);
723             codec_pos = url_ftell(pb);
724             st->codec->codec_type = CODEC_TYPE_DATA;
725             av_set_pts_info(st, 64, 1, 1000);
726
727             v = get_be32(pb);
728             if (v == MKTAG(0xfd, 'a', 'r', '.')) {
729                 /* ra type header */
730                 if (rm_read_audio_stream_info(s, st, 0))
731                     return -1;
732             } else {
733                 int fps, fps2;
734                 if (get_le32(pb) != MKTAG('V', 'I', 'D', 'O')) {
735                 fail1:
736                     av_log(st->codec, AV_LOG_ERROR, "Unsupported video codec\n");
737                     goto skip;
738                 }
739                 st->codec->codec_tag = get_le32(pb);
740 //                av_log(NULL, AV_LOG_DEBUG, "%X %X\n", st->codec->codec_tag, MKTAG('R', 'V', '2', '0'));
741                 if (   st->codec->codec_tag != MKTAG('R', 'V', '1', '0')
742                     && st->codec->codec_tag != MKTAG('R', 'V', '2', '0')
743                     && st->codec->codec_tag != MKTAG('R', 'V', '3', '0')
744                     && st->codec->codec_tag != MKTAG('R', 'V', '4', '0'))
745                     goto fail1;
746                 st->codec->width = get_be16(pb);
747                 st->codec->height = get_be16(pb);
748                 st->codec->time_base.num= 1;
749                 fps= get_be16(pb);
750                 st->codec->codec_type = CODEC_TYPE_VIDEO;
751                 get_be32(pb);
752                 fps2= get_be16(pb);
753                 get_be16(pb);
754
755                 st->codec->extradata_size= codec_data_size - (url_ftell(pb) - codec_pos);
756
757                 if(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE <= (unsigned)st->codec->extradata_size){
758                     //check is redundant as get_buffer() will catch this
759                     av_log(s, AV_LOG_ERROR, "st->codec->extradata_size too large\n");
760                     return -1;
761                 }
762                 st->codec->extradata= av_mallocz(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
763                 get_buffer(pb, st->codec->extradata, st->codec->extradata_size);
764
765 //                av_log(NULL, AV_LOG_DEBUG, "fps= %d fps2= %d\n", fps, fps2);
766                 st->codec->time_base.den = fps * st->codec->time_base.num;
767                 switch(((uint8_t*)st->codec->extradata)[4]>>4){
768                 case 1: st->codec->codec_id = CODEC_ID_RV10; break;
769                 case 2: st->codec->codec_id = CODEC_ID_RV20; break;
770                 case 3: st->codec->codec_id = CODEC_ID_RV30; break;
771                 case 4: st->codec->codec_id = CODEC_ID_RV40; break;
772                 default: goto fail1;
773                 }
774             }
775 skip:
776             /* skip codec info */
777             size = url_ftell(pb) - codec_pos;
778             url_fskip(pb, codec_data_size - size);
779             break;
780         case MKTAG('D', 'A', 'T', 'A'):
781             goto header_end;
782         default:
783             /* unknown tag: skip it */
784             url_fskip(pb, tag_size - 10);
785             break;
786         }
787     }
788  header_end:
789     rm->nb_packets = get_be32(pb); /* number of packets */
790     if (!rm->nb_packets && (flags & 4))
791         rm->nb_packets = 3600 * 25;
792     get_be32(pb); /* next data header */
793     return 0;
794
795  fail:
796     for(i=0;i<s->nb_streams;i++) {
797         av_free(s->streams[i]);
798     }
799     return AVERROR_IO;
800 }
801
802 static int get_num(ByteIOContext *pb, int *len)
803 {
804     int n, n1;
805
806     n = get_be16(pb);
807     (*len)-=2;
808     if (n >= 0x4000) {
809         return n - 0x4000;
810     } else {
811         n1 = get_be16(pb);
812         (*len)-=2;
813         return (n << 16) | n1;
814     }
815 }
816
817 /* multiple of 20 bytes for ra144 (ugly) */
818 #define RAW_PACKET_SIZE 1000
819
820 static int sync(AVFormatContext *s, int64_t *timestamp, int *flags, int *stream_index, int64_t *pos){
821     RMContext *rm = s->priv_data;
822     ByteIOContext *pb = &s->pb;
823     int len, num, res, i;
824     AVStream *st;
825     uint32_t state=0xFFFFFFFF;
826
827     while(!url_feof(pb)){
828         *pos= url_ftell(pb);
829         if(rm->remaining_len > 0){
830             num= rm->current_stream;
831             len= rm->remaining_len;
832             *timestamp = AV_NOPTS_VALUE;
833             *flags= 0;
834         }else{
835             state= (state<<8) + get_byte(pb);
836
837             if(state == MKBETAG('I', 'N', 'D', 'X')){
838                 len = get_be16(pb) - 6;
839                 if(len<0)
840                     continue;
841                 goto skip;
842             }
843
844             if(state > (unsigned)0xFFFF || state < 12)
845                 continue;
846             len=state;
847             state= 0xFFFFFFFF;
848
849             num = get_be16(pb);
850             *timestamp = get_be32(pb);
851             res= get_byte(pb); /* reserved */
852             *flags = get_byte(pb); /* flags */
853
854
855             len -= 12;
856         }
857         for(i=0;i<s->nb_streams;i++) {
858             st = s->streams[i];
859             if (num == st->id)
860                 break;
861         }
862         if (i == s->nb_streams) {
863 skip:
864             /* skip packet if unknown number */
865             url_fskip(pb, len);
866             rm->remaining_len -= len;
867             continue;
868         }
869         *stream_index= i;
870
871         return len;
872     }
873     return -1;
874 }
875
876 static int rm_read_packet(AVFormatContext *s, AVPacket *pkt)
877 {
878     RMContext *rm = s->priv_data;
879     ByteIOContext *pb = &s->pb;
880     AVStream *st;
881     int i, len, tmp, j;
882     int64_t timestamp, pos;
883     uint8_t *ptr;
884     int flags;
885
886     if (rm->audio_pkt_cnt) {
887         // If there are queued audio packet return them first
888         st = s->streams[rm->audio_stream_num];
889         if (st->codec->codec_id == CODEC_ID_AAC)
890             av_get_packet(pb, pkt, rm->sub_packet_lengths[rm->sub_packet_cnt - rm->audio_pkt_cnt]);
891         else {
892         av_new_packet(pkt, st->codec->block_align);
893         memcpy(pkt->data, rm->audiobuf + st->codec->block_align *
894                (rm->sub_packet_h * rm->audio_framesize / st->codec->block_align - rm->audio_pkt_cnt),
895                st->codec->block_align);
896         }
897         rm->audio_pkt_cnt--;
898         pkt->flags = 0;
899         pkt->stream_index = rm->audio_stream_num;
900     } else if (rm->old_format) {
901         st = s->streams[0];
902         if (st->codec->codec_id == CODEC_ID_RA_288) {
903             int x, y;
904
905             for (y = 0; y < rm->sub_packet_h; y++)
906                 for (x = 0; x < rm->sub_packet_h/2; x++)
907                     if (get_buffer(pb, rm->audiobuf+x*2*rm->audio_framesize+y*rm->coded_framesize, rm->coded_framesize) <= 0)
908                         return AVERROR_IO;
909             rm->audio_stream_num = 0;
910             rm->audio_pkt_cnt = rm->sub_packet_h * rm->audio_framesize / st->codec->block_align - 1;
911             // Release first audio packet
912             av_new_packet(pkt, st->codec->block_align);
913             memcpy(pkt->data, rm->audiobuf, st->codec->block_align);
914             pkt->flags |= PKT_FLAG_KEY; // Mark first packet as keyframe
915             pkt->stream_index = 0;
916         } else {
917             /* just read raw bytes */
918             len = RAW_PACKET_SIZE;
919             len= av_get_packet(pb, pkt, len);
920             pkt->stream_index = 0;
921             if (len <= 0) {
922                 return AVERROR_IO;
923             }
924             pkt->size = len;
925         }
926     } else {
927         int seq=1;
928 resync:
929         len=sync(s, &timestamp, &flags, &i, &pos);
930         if(len<0)
931             return AVERROR_IO;
932         st = s->streams[i];
933
934         if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
935             int h, pic_num, len2, pos;
936
937             h= get_byte(pb); len--;
938             if(!(h & 0x40)){
939                 seq = get_byte(pb); len--;
940             }
941
942             if((h & 0xc0) == 0x40){
943                 len2= pos= 0;
944             }else{
945                 len2 = get_num(pb, &len);
946                 pos = get_num(pb, &len);
947             }
948             /* picture number */
949             pic_num= get_byte(pb); len--;
950             rm->remaining_len= len;
951             rm->current_stream= st->id;
952
953 //            av_log(NULL, AV_LOG_DEBUG, "%X len:%d pos:%d len2:%d pic_num:%d\n",h, len, pos, len2, pic_num);
954             if(len2 && len2<len)
955                 len=len2;
956             rm->remaining_len-= len;
957             av_get_packet(pb, pkt, len);
958
959         } else if (st->codec->codec_type == CODEC_TYPE_AUDIO) {
960             if ((st->codec->codec_id == CODEC_ID_RA_288) ||
961                 (st->codec->codec_id == CODEC_ID_COOK) ||
962                 (st->codec->codec_id == CODEC_ID_ATRAC3)) {
963                 int x;
964                 int sps = rm->sub_packet_size;
965                 int cfs = rm->coded_framesize;
966                 int h = rm->sub_packet_h;
967                 int y = rm->sub_packet_cnt;
968                 int w = rm->audio_framesize;
969
970                 if (flags & 2)
971                     y = rm->sub_packet_cnt = 0;
972                 if (!y)
973                     rm->audiotimestamp = timestamp;
974
975                 switch(st->codec->codec_id) {
976                     case CODEC_ID_RA_288:
977                         for (x = 0; x < h/2; x++)
978                             get_buffer(pb, rm->audiobuf+x*2*w+y*cfs, cfs);
979                         break;
980                     case CODEC_ID_ATRAC3:
981                     case CODEC_ID_COOK:
982                         for (x = 0; x < w/sps; x++)
983                             get_buffer(pb, rm->audiobuf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), sps);
984                         break;
985                 }
986
987                 if (++(rm->sub_packet_cnt) < h)
988                     goto resync;
989                 else {
990                     rm->sub_packet_cnt = 0;
991                     rm->audio_stream_num = i;
992                     rm->audio_pkt_cnt = h * w / st->codec->block_align - 1;
993                     // Release first audio packet
994                     av_new_packet(pkt, st->codec->block_align);
995                     memcpy(pkt->data, rm->audiobuf, st->codec->block_align);
996                     timestamp = rm->audiotimestamp;
997                     flags = 2; // Mark first packet as keyframe
998                 }
999             } else if (st->codec->codec_id == CODEC_ID_AAC) {
1000                 int x;
1001                 rm->audio_stream_num = i;
1002                 rm->sub_packet_cnt = (get_be16(pb) & 0xf0) >> 4;
1003                 if (rm->sub_packet_cnt) {
1004                     for (x = 0; x < rm->sub_packet_cnt; x++)
1005                         rm->sub_packet_lengths[x] = get_be16(pb);
1006                     // Release first audio packet
1007                     rm->audio_pkt_cnt = rm->sub_packet_cnt - 1;
1008                     av_get_packet(pb, pkt, rm->sub_packet_lengths[0]);
1009                     flags = 2; // Mark first packet as keyframe
1010                 }
1011             } else
1012                 av_get_packet(pb, pkt, len);
1013
1014         } else
1015             av_get_packet(pb, pkt, len);
1016
1017         if(  (st->discard >= AVDISCARD_NONKEY && !(flags&2))
1018            || st->discard >= AVDISCARD_ALL){
1019             av_free_packet(pkt);
1020             goto resync;
1021         }
1022
1023         pkt->stream_index = i;
1024
1025 #if 0
1026         if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
1027             if(st->codec->codec_id == CODEC_ID_RV20){
1028                 int seq= 128*(pkt->data[2]&0x7F) + (pkt->data[3]>>1);
1029                 av_log(NULL, AV_LOG_DEBUG, "%d %"PRId64" %d\n", timestamp, timestamp*512LL/25, seq);
1030
1031                 seq |= (timestamp&~0x3FFF);
1032                 if(seq - timestamp >  0x2000) seq -= 0x4000;
1033                 if(seq - timestamp < -0x2000) seq += 0x4000;
1034             }
1035         }
1036 #endif
1037         pkt->pts= timestamp;
1038         if(flags&2){
1039             pkt->flags |= PKT_FLAG_KEY;
1040             if((seq&0x7F) == 1)
1041                 av_add_index_entry(st, pos, timestamp, 0, 0, AVINDEX_KEYFRAME);
1042         }
1043     }
1044
1045     /* for AC3, needs to swap bytes */
1046     if (st->codec->codec_id == CODEC_ID_AC3) {
1047         ptr = pkt->data;
1048         for(j=0;j<len;j+=2) {
1049             tmp = ptr[0];
1050             ptr[0] = ptr[1];
1051             ptr[1] = tmp;
1052                 ptr += 2;
1053         }
1054     }
1055     return 0;
1056 }
1057
1058 static int rm_read_close(AVFormatContext *s)
1059 {
1060     RMContext *rm = s->priv_data;
1061
1062     av_free(rm->audiobuf);
1063     return 0;
1064 }
1065
1066 static int rm_probe(AVProbeData *p)
1067 {
1068     /* check file header */
1069     if ((p->buf[0] == '.' && p->buf[1] == 'R' &&
1070          p->buf[2] == 'M' && p->buf[3] == 'F' &&
1071          p->buf[4] == 0 && p->buf[5] == 0) ||
1072         (p->buf[0] == '.' && p->buf[1] == 'r' &&
1073          p->buf[2] == 'a' && p->buf[3] == 0xfd))
1074         return AVPROBE_SCORE_MAX;
1075     else
1076         return 0;
1077 }
1078
1079 static int64_t rm_read_dts(AVFormatContext *s, int stream_index,
1080                                int64_t *ppos, int64_t pos_limit)
1081 {
1082     RMContext *rm = s->priv_data;
1083     int64_t pos, dts;
1084     int stream_index2, flags, len, h;
1085
1086     pos = *ppos;
1087
1088     if(rm->old_format)
1089         return AV_NOPTS_VALUE;
1090
1091     url_fseek(&s->pb, pos, SEEK_SET);
1092     rm->remaining_len=0;
1093     for(;;){
1094         int seq=1;
1095         AVStream *st;
1096
1097         len=sync(s, &dts, &flags, &stream_index2, &pos);
1098         if(len<0)
1099             return AV_NOPTS_VALUE;
1100
1101         st = s->streams[stream_index2];
1102         if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
1103             h= get_byte(&s->pb); len--;
1104             if(!(h & 0x40)){
1105                 seq = get_byte(&s->pb); len--;
1106             }
1107         }
1108
1109         if((flags&2) && (seq&0x7F) == 1){
1110 //            av_log(s, AV_LOG_DEBUG, "%d %d-%d %"PRId64" %d\n", flags, stream_index2, stream_index, dts, seq);
1111             av_add_index_entry(st, pos, dts, 0, 0, AVINDEX_KEYFRAME);
1112             if(stream_index2 == stream_index)
1113                 break;
1114         }
1115
1116         url_fskip(&s->pb, len);
1117     }
1118     *ppos = pos;
1119     return dts;
1120 }
1121
1122 #ifdef CONFIG_RM_DEMUXER
1123 AVInputFormat rm_demuxer = {
1124     "rm",
1125     "rm format",
1126     sizeof(RMContext),
1127     rm_probe,
1128     rm_read_header,
1129     rm_read_packet,
1130     rm_read_close,
1131     NULL,
1132     rm_read_dts,
1133 };
1134 #endif
1135 #ifdef CONFIG_RM_MUXER
1136 AVOutputFormat rm_muxer = {
1137     "rm",
1138     "rm format",
1139     "application/vnd.rn-realmedia",
1140     "rm,ra",
1141     sizeof(RMContext),
1142     CODEC_ID_AC3,
1143     CODEC_ID_RV10,
1144     rm_write_header,
1145     rm_write_packet,
1146     rm_write_trailer,
1147 };
1148 #endif