]> git.sesse.net Git - vlc/blob - modules/demux/real.c
Cosmetics : Fix real.c comment header since sipr support was merged in trunk.
[vlc] / modules / demux / real.c
1 /*****************************************************************************
2  * real.c: Real demuxer.
3  *****************************************************************************
4  * Copyright (C) 2004, 2006-2007 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22  *****************************************************************************/
23
24 /**
25  * Status of this demuxer:
26  * Real Media format
27  * -----------------
28  *
29  * version v3 w/ 14_4/lpcJ is ok.
30  * version v4/5: - atrac3 is ok.
31  *               - cook is ok.
32  *               - raac, racp are ok.
33  *               - dnet is twisted "The byte order of the data is reversed
34  *                                  from standard AC3" but ok
35  *               - 28_8 is ok.
36  *               - sipr is ok.
37  *               - ralf is unsupported, but hardly any sample exist.
38  *               - mp3 is unsupported, one sample exists...
39  *
40  * Real Audio Only
41  * ---------------
42  * v3 and v4/5 headers are parsed.
43  * Doesn't work yet...
44  */
45
46 /*****************************************************************************
47  * Preamble
48  *****************************************************************************/
49
50 #ifdef HAVE_CONFIG_H
51 # include "config.h"
52 #endif
53
54 #include <vlc_common.h>
55 #include <vlc_plugin.h>
56
57 #include <vlc_demux.h>
58 #include <vlc_charset.h>
59 #include <vlc_meta.h>
60
61 #include <assert.h>
62
63 /*****************************************************************************
64  * Module descriptor
65  *****************************************************************************/
66 static int  Open    ( vlc_object_t * );
67 static void Close  ( vlc_object_t * );
68
69 vlc_module_begin ()
70     set_description( N_("Real demuxer" ) )
71     set_capability( "demux", 50 )
72     set_category( CAT_INPUT )
73     set_subcategory( SUBCAT_INPUT_DEMUX )
74     set_callbacks( Open, Close )
75     add_shortcut( "real" )
76     add_shortcut( "rm" )
77 vlc_module_end ()
78
79 /*****************************************************************************
80  * Local prototypes
81  *****************************************************************************/
82
83 typedef struct
84 {
85     int         i_id;
86     es_format_t fmt;
87
88     es_out_id_t *p_es;
89
90     int         i_frame_size;
91
92     int         i_frame_num;
93     int         i_frame_pos;
94     int         i_frame_slice;
95     int         i_frame_slice_count;
96     block_t     *p_frame;
97
98     int         i_subpacket_h;
99     int         i_subpacket_size;
100     int         i_coded_frame_size;
101
102     int         i_subpacket;
103     int         i_subpackets;
104     block_t     **p_subpackets;
105     mtime_t     *p_subpackets_timecode;
106     int         i_out_subpacket;
107
108     block_t     *p_sipr_packet;
109     int         i_sipr_subpacket_count;
110     mtime_t     i_last_dts;
111 } real_track_t;
112
113 typedef struct
114 {
115     uint32_t i_file_offset;
116     uint32_t i_time_offset;
117     uint32_t i_frame_index;
118 } real_index_t;
119
120 struct demux_sys_t
121 {
122     int64_t  i_data_offset;
123     int64_t  i_data_size;
124     uint32_t i_data_packets_count;
125     uint32_t i_data_packets;
126     int64_t  i_data_offset_next;
127
128     bool     b_real_audio;
129
130     int64_t i_our_duration;
131
132     char* psz_title;
133     char* psz_artist;
134     char* psz_copyright;
135     char* psz_description;
136
137     int          i_track;
138     real_track_t **track;
139
140     size_t     i_buffer;
141     uint8_t buffer[65536];
142
143     int64_t     i_pcr;
144
145     int64_t     i_index_offset;
146     bool        b_seek;
147     real_index_t *p_index;
148 };
149
150 static const unsigned char i_subpacket_size_sipr[4] = { 29, 19, 37, 20 };
151
152 static int Demux( demux_t * );
153 static int Control( demux_t *, int i_query, va_list args );
154
155
156 static void DemuxVideo( demux_t *, real_track_t *tk, mtime_t i_dts, unsigned i_flags );
157 static void DemuxAudio( demux_t *, real_track_t *tk, mtime_t i_pts, unsigned i_flags );
158
159 static int ControlSeekByte( demux_t *, int64_t i_bytes );
160 static int ControlSeekTime( demux_t *, mtime_t i_time );
161
162 static int HeaderRead( demux_t *p_demux );
163 static int CodecParse( demux_t *p_demux, int i_len, int i_num );
164
165 static void     RVoid( const uint8_t **pp_data, int *pi_data, int i_size );
166 static int      RLength( const uint8_t **pp_data, int *pi_data );
167 static uint8_t  R8( const uint8_t **pp_data, int *pi_data );
168 static uint16_t R16( const uint8_t **pp_data, int *pi_data );
169 static uint32_t R32( const uint8_t **pp_data, int *pi_data );
170 static void     SiprPacketReorder(uint8_t *buf, int sub_packet_h, int framesize);
171
172 /*****************************************************************************
173  * Open
174  *****************************************************************************/
175 static int Open( vlc_object_t *p_this )
176 {
177     demux_t     *p_demux = (demux_t*)p_this;
178     demux_sys_t *p_sys;
179
180     const uint8_t *p_peek;
181     bool           b_real_audio = false;
182
183     if( stream_Peek( p_demux->s, &p_peek, 10 ) < 10 )
184         return VLC_EGENERIC;
185
186     /* Real Audio */
187     if( !memcmp( p_peek, ".ra", 3 ) )
188     {
189         msg_Err( p_demux, ".ra files unsuported" );
190         b_real_audio = true;
191     }
192     /* Real Media Format */
193     else if( memcmp( p_peek, ".RMF", 4 ) )
194     {
195         return VLC_EGENERIC;
196     }
197
198     /* Fill p_demux field */
199     p_demux->pf_demux = Demux;
200     p_demux->pf_control = Control;
201
202     p_demux->p_sys = p_sys = calloc( 1, sizeof( *p_sys ) );
203     if( !p_sys )
204         return VLC_ENOMEM;
205
206     p_sys->i_data_offset = 0;
207     p_sys->i_track = 0;
208     p_sys->track   = NULL;
209     p_sys->i_pcr   = VLC_TS_INVALID;
210
211     p_sys->b_seek  = false;
212     p_sys->b_real_audio = b_real_audio;
213
214     /* Parse the headers */
215     /* Real Audio files */
216     if( b_real_audio )
217     {
218         CodecParse( p_demux, 32, 0 ); /* At least 32 */
219         return VLC_EGENERIC;                     /* We don't know how to read
220                                                     correctly the data yet */
221     }
222     /* RMF files */
223     else if( HeaderRead( p_demux ) )
224     {
225         msg_Err( p_demux, "invalid header" );
226         Close( p_this );
227         return VLC_EGENERIC;
228     }
229
230     return VLC_SUCCESS;
231 }
232
233 /*****************************************************************************
234  * Close
235  *****************************************************************************/
236 static void Close( vlc_object_t *p_this )
237 {
238     demux_t *p_demux = (demux_t*)p_this;
239     demux_sys_t *p_sys = p_demux->p_sys;
240
241     for( int i = 0; i < p_sys->i_track; i++ )
242     {
243         real_track_t *tk = p_sys->track[i];
244
245         es_format_Clean( &tk->fmt );
246
247         if( tk->p_frame )
248             block_Release( tk->p_frame );
249
250         for( int j = 0; j < tk->i_subpackets; j++ )
251         {
252             if( tk->p_subpackets[ j ] )
253                 block_Release( tk->p_subpackets[ j ] );
254         }
255         if( tk->i_subpackets )
256         {
257             free( tk->p_subpackets );
258             free( tk->p_subpackets_timecode );
259         }
260         if( tk->p_sipr_packet )
261             block_Release( tk->p_sipr_packet );
262         free( tk );
263     }
264     if( p_sys->i_track > 0 )
265         free( p_sys->track );
266
267     free( p_sys->psz_title );
268     free( p_sys->psz_artist );
269     free( p_sys->psz_copyright );
270     free( p_sys->psz_description );
271     free( p_sys->p_index );
272
273     free( p_sys );
274 }
275
276
277 /*****************************************************************************
278  * Demux:
279  *****************************************************************************/
280 static int Demux( demux_t *p_demux )
281 {
282     demux_sys_t *p_sys = p_demux->p_sys;
283     uint8_t     header[18];
284
285     if( p_sys->i_data_packets >= p_sys->i_data_packets_count &&
286         p_sys->i_data_packets_count )
287     {
288         if( stream_Read( p_demux->s, header, 18 ) < 18 )
289             return 0;
290
291         if( memcmp( header, "DATA", 4 ) )
292             return 0;
293
294         p_sys->i_data_offset = stream_Tell( p_demux->s ) - 18;
295         p_sys->i_data_size   = GetDWBE( &header[4] );
296         p_sys->i_data_packets_count = GetDWBE( &header[10] );
297         p_sys->i_data_packets = 0;
298         p_sys->i_data_offset_next = GetDWBE( &header[14] );
299
300         msg_Dbg( p_demux, "entering new DATA packets=%d next=%u",
301                  p_sys->i_data_packets_count,
302                  (unsigned int)p_sys->i_data_offset_next );
303     }
304
305     /* Read Packet Header */
306     if( stream_Read( p_demux->s, header, 12 ) < 12 )
307         return 0;
308     //const int i_version = GetWBE( &header[0] );
309     const size_t  i_size = GetWBE( &header[2] ) - 12;
310     const int     i_id   = GetWBE( &header[4] );
311     const int64_t i_pts  = VLC_TS_0 + 1000 * GetDWBE( &header[6] );
312     const int     i_flags= header[11]; /* flags 0x02 -> keyframe */
313
314     p_sys->i_data_packets++;
315     if( i_size > sizeof(p_sys->buffer) )
316     {
317         msg_Err( p_demux, "Got a NUKK size to read. (Invalid format?)" );
318         return 1;
319     }
320
321     p_sys->i_buffer = stream_Read( p_demux->s, p_sys->buffer, i_size );
322     if( p_sys->i_buffer < i_size )
323         return 0;
324
325     real_track_t *tk = NULL;
326     for( int i = 0; i < p_sys->i_track; i++ )
327     {
328         if( p_sys->track[i]->i_id == i_id )
329             tk = p_sys->track[i];
330     }
331
332     if( !tk )
333     {
334         msg_Warn( p_demux, "unknown track id(0x%x)", i_id );
335         return 1;
336     }
337
338     if( tk->fmt.i_cat == VIDEO_ES )
339     {
340         DemuxVideo( p_demux, tk, i_pts, i_flags );
341     }
342     else
343     {
344         assert( tk->fmt.i_cat == AUDIO_ES );
345         DemuxAudio( p_demux, tk, i_pts, i_flags );
346     }
347
348     /* Update PCR */
349     mtime_t i_pcr = VLC_TS_INVALID;
350     for( int i = 0; i < p_sys->i_track; i++ )
351     {
352         real_track_t *tk = p_sys->track[i];
353
354         if( i_pcr <= VLC_TS_INVALID || ( tk->i_last_dts > VLC_TS_INVALID && tk->i_last_dts < i_pcr ) )
355             i_pcr = tk->i_last_dts;
356     }
357     if( i_pcr > VLC_TS_INVALID && i_pcr != p_sys->i_pcr )
358     {
359         p_sys->i_pcr = i_pcr;
360         es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_sys->i_pcr );
361     }
362     return 1;
363 }
364
365 /*****************************************************************************
366  * Control:
367  *****************************************************************************/
368 static int Control( demux_t *p_demux, int i_query, va_list args )
369 {
370     demux_sys_t *p_sys = p_demux->p_sys;
371     double f, *pf;
372     int64_t i64;
373     int64_t *pi64;
374
375     switch( i_query )
376     {
377         case DEMUX_GET_POSITION:
378             pf = (double*) va_arg( args, double* );
379
380             /* read stream size maybe failed in rtsp streaming, 
381                so use duration to determin the position at first  */
382             if( p_sys->i_our_duration > 0 )
383             {
384                 if( p_sys->i_pcr > VLC_TS_INVALID )
385                     *pf = (double)p_sys->i_pcr / 1000.0 / p_sys->i_our_duration;
386                 else
387                     *pf = 0.0;
388                 return VLC_SUCCESS;
389             }
390
391             i64 = stream_Size( p_demux->s );
392             if( i64 > 0 )
393                 *pf = (double)1.0*stream_Tell( p_demux->s ) / (double)i64;
394             else
395                 *pf = 0.0;
396             return VLC_SUCCESS;
397
398         case DEMUX_GET_TIME:
399             pi64 = (int64_t*)va_arg( args, int64_t * );
400
401             if( p_sys->i_our_duration > 0 )
402             {
403                 *pi64 = p_sys->i_pcr > VLC_TS_INVALID ? p_sys->i_pcr : 0;
404                 return VLC_SUCCESS;
405             }
406
407             /* same as GET_POSTION */
408             i64 = stream_Size( p_demux->s );
409             if( p_sys->i_our_duration > 0 && i64 > 0 )
410             {
411                 *pi64 = (int64_t)( 1000.0 * p_sys->i_our_duration * stream_Tell( p_demux->s ) / i64 );
412                 return VLC_SUCCESS;
413             }
414
415             *pi64 = 0;
416             return VLC_EGENERIC;
417
418         case DEMUX_SET_POSITION:
419             f = (double) va_arg( args, double );
420             i64 = (int64_t) ( stream_Size( p_demux->s ) * f );
421
422             if( !p_sys->p_index && i64 != 0 )
423             {
424                 /* TODO seek */
425                 msg_Err( p_demux,"Seek No Index Real File failed!" );
426                 return VLC_EGENERIC; // no index!
427             }
428             else if( i64 == 0 )
429             {
430                 /* it is a rtsp stream , it is specials in access/rtsp/... */
431                 msg_Dbg(p_demux, "Seek in real rtsp stream!");
432                 p_sys->i_pcr = VLC_TS_0 + INT64_C(1000) * ( p_sys->i_our_duration * f  );
433                 p_sys->b_seek = true;
434                 return stream_Seek( p_demux->s, p_sys->i_pcr - VLC_TS_0 );
435             }
436             return ControlSeekByte( p_demux, i64 );
437
438         case DEMUX_SET_TIME:
439             if( !p_sys->p_index )
440                 return VLC_EGENERIC;
441
442             i64 = (int64_t) va_arg( args, int64_t );
443             return ControlSeekTime( p_demux, i64 );
444
445         case DEMUX_GET_LENGTH:
446             pi64 = (int64_t*)va_arg( args, int64_t * );
447  
448             if( p_sys->i_our_duration <= 0 )
449             {
450                 *pi64 = 0;
451                 return VLC_EGENERIC;
452             }
453
454             /* our stored duration is in ms, so... */
455             *pi64 = INT64_C(1000) * p_sys->i_our_duration;
456             return VLC_SUCCESS;
457
458         case DEMUX_GET_META:
459         {
460             vlc_meta_t *p_meta = (vlc_meta_t*)va_arg( args, vlc_meta_t* );
461
462             /* the core will crash if we provide NULL strings, so check
463              * every string first */
464             if( p_sys->psz_title )
465                 vlc_meta_SetTitle( p_meta, p_sys->psz_title );
466             if( p_sys->psz_artist )
467                 vlc_meta_SetArtist( p_meta, p_sys->psz_artist );
468             if( p_sys->psz_copyright )
469                 vlc_meta_SetCopyright( p_meta, p_sys->psz_copyright );
470             if( p_sys->psz_description )
471                 vlc_meta_SetDescription( p_meta, p_sys->psz_description );
472             return VLC_SUCCESS;
473         }
474
475         case DEMUX_GET_FPS:
476         default:
477             return VLC_EGENERIC;
478     }
479     return VLC_EGENERIC;
480 }
481
482 /*****************************************************************************
483  * Helpers: demux
484  *****************************************************************************/
485 static void CheckPcr( demux_t *p_demux, real_track_t *tk, mtime_t i_dts )
486 {
487     demux_sys_t *p_sys = p_demux->p_sys;
488
489     if( i_dts > VLC_TS_INVALID )
490         tk->i_last_dts = i_dts;
491
492     if( p_sys->i_pcr > VLC_TS_INVALID || i_dts <= VLC_TS_INVALID )
493         return;
494
495     p_sys->i_pcr = i_dts;
496     es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_sys->i_pcr );
497 }
498
499 static void DemuxVideo( demux_t *p_demux, real_track_t *tk, mtime_t i_dts, unsigned i_flags )
500 {
501     demux_sys_t *p_sys = p_demux->p_sys;
502
503     const uint8_t *p_data = p_sys->buffer;
504     int     i_data = p_sys->i_buffer;
505
506     while( i_data > 1 )
507     {
508         uint8_t i_hdr = R8( &p_data, &i_data );
509         uint8_t i_type = i_hdr >> 6;
510
511         uint8_t i_seq;
512         int i_len;
513         int i_pos;
514         int i_frame_num;
515
516         if( i_type == 1 )
517         {
518             R8( &p_data, &i_data );
519             i_len = i_data;
520             i_pos = 0;
521             i_frame_num = -1;
522             i_seq = 1;
523             i_hdr &= ~0x3f;
524         }
525         else if( i_type == 3 )
526         {
527             i_len = RLength( &p_data, &i_data );
528             i_pos = RLength( &p_data, &i_data );
529             i_frame_num = R8( &p_data, &i_data );
530             i_seq = 1;
531             i_hdr &= ~0x3f;
532         }
533         else
534         {
535             assert( i_type == 0 || i_type == 2 );
536             i_seq = R8( &p_data, &i_data );
537             i_len = RLength( &p_data, &i_data );
538
539             i_pos = RLength( &p_data, &i_data );
540             i_frame_num = R8( &p_data, &i_data );
541         }
542
543         if( (i_seq & 0x7f) == 1 || tk->i_frame_num != i_frame_num )
544         {
545             tk->i_frame_slice = 0;
546             tk->i_frame_slice_count = 2 * (i_hdr & 0x3f) + 1;
547             tk->i_frame_pos = 2*4 * tk->i_frame_slice_count + 1;
548             tk->i_frame_size = i_len + 2*4 * tk->i_frame_slice_count + 1;
549             tk->i_frame_num = i_frame_num;
550
551             if( tk->p_frame )
552                 block_Release( tk->p_frame );
553
554             tk->p_frame = block_New( p_demux, tk->i_frame_size );
555             if( !tk->p_frame )
556             {
557                 tk->i_frame_size = 0;
558                 return;
559             }
560
561             tk->p_frame->i_dts = i_dts;
562             tk->p_frame->i_pts = VLC_TS_INVALID;
563             if( i_flags & 0x02 )
564                 tk->p_frame->i_flags |= BLOCK_FLAG_TYPE_I;
565
566             i_dts = VLC_TS_INVALID;
567         }
568
569         int i_frame_data;
570         if( i_type == 3 )
571         {
572             i_frame_data = i_len;
573         }
574         else
575         {
576             i_frame_data = i_data;
577             if( i_type == 2 && i_frame_data > i_pos )
578                 i_frame_data = i_pos;
579         }
580         if( i_frame_data > i_data )
581             break;
582
583         /* */
584         tk->i_frame_slice++;
585         if( tk->i_frame_slice > tk->i_frame_slice_count || !tk->p_frame )
586             break;
587
588         /* */
589         SetDWLE( &tk->p_frame->p_buffer[2*4*(tk->i_frame_slice-1) + 1 + 0], 1 );
590         SetDWLE( &tk->p_frame->p_buffer[2*4*(tk->i_frame_slice-1) + 1 + 4], tk->i_frame_pos - (2*4 * tk->i_frame_slice_count + 1) );
591
592         if( tk->i_frame_pos + i_frame_data > tk->i_frame_size )
593             break;
594
595         memcpy( &tk->p_frame->p_buffer[tk->i_frame_pos], p_data, i_frame_data );
596         RVoid( &p_data, &i_data, i_frame_data );
597         tk->i_frame_pos += i_frame_data;
598
599         if( i_type != 0 || tk->i_frame_pos >= tk->i_frame_size )
600         {
601             /* Fix the buffer once the real number of slice is known */
602             tk->p_frame->p_buffer[0] = tk->i_frame_slice - 1;
603             tk->p_frame->i_buffer = tk->i_frame_pos - 2*4*( tk->i_frame_slice_count - tk->i_frame_slice );
604
605             memmove( &tk->p_frame->p_buffer[1+2*4*tk->i_frame_slice      ],
606                      &tk->p_frame->p_buffer[1+2*4*tk->i_frame_slice_count],
607                      tk->i_frame_pos - (2*4*tk->i_frame_slice_count + 1) );
608
609             /* Send it */
610             CheckPcr( p_demux, tk, tk->p_frame->i_dts );
611             es_out_Send( p_demux->out, tk->p_es, tk->p_frame );
612
613             tk->i_frame_size = 0;
614             tk->p_frame = NULL;
615         }
616     }
617 }
618
619 static void DemuxAudioMethod1( demux_t *p_demux, real_track_t *tk, mtime_t i_pts, unsigned int i_flags )
620 {
621     demux_sys_t *p_sys = p_demux->p_sys;
622     uint8_t *p_buf = p_sys->buffer;
623
624     /* Sanity check */
625     if( (i_flags & 2) || p_sys->b_seek )
626     {
627         tk->i_subpacket = 0;
628         tk->i_out_subpacket = 0;
629         p_sys->b_seek = false;
630     }
631
632     if( tk->fmt.i_codec == VLC_CODEC_COOK ||
633         tk->fmt.i_codec == VLC_CODEC_ATRAC3 )
634     {
635         const int i_num = tk->i_frame_size / tk->i_subpacket_size;
636         const int y = tk->i_subpacket / ( tk->i_frame_size / tk->i_subpacket_size );
637
638         for( int i = 0; i < i_num; i++ )
639         {
640             block_t *p_block = block_New( p_demux, tk->i_subpacket_size );
641             if( !p_block )
642                 return;
643             if( &p_buf[tk->i_subpacket_size] > &p_sys->buffer[p_sys->i_buffer] )
644                 return;
645
646             memcpy( p_block->p_buffer, p_buf, tk->i_subpacket_size );
647             p_block->i_dts =
648             p_block->i_pts = VLC_TS_INVALID;
649
650             p_buf += tk->i_subpacket_size;
651
652             int i_index = tk->i_subpacket_h * i +
653                           ((tk->i_subpacket_h + 1) / 2) * (y&1) + (y>>1);
654
655             if( tk->p_subpackets[i_index] != NULL )
656             {
657                 msg_Dbg(p_demux, "p_subpackets[ %d ] not null!",  i_index );
658                 block_Release( tk->p_subpackets[i_index] );
659             }
660
661             tk->p_subpackets[i_index] = p_block;
662             if( tk->i_subpacket == 0 )
663                 tk->p_subpackets_timecode[0] = i_pts;
664             tk->i_subpacket++;
665         }
666     }
667     else
668     {
669         const int y = tk->i_subpacket / (tk->i_subpacket_h / 2);
670         assert( tk->fmt.i_codec == VLC_CODEC_RA_288 );
671
672         for( int i = 0; i < tk->i_subpacket_h / 2; i++ )
673         {
674             block_t *p_block = block_New( p_demux, tk->i_coded_frame_size);
675             if( !p_block )
676                 return;
677             if( &p_buf[tk->i_coded_frame_size] > &p_sys->buffer[p_sys->i_buffer] )
678                 return;
679
680             int i_index = (i * 2 * tk->i_frame_size / tk->i_coded_frame_size) + y;
681
682             memcpy( p_block->p_buffer, p_buf, tk->i_coded_frame_size );
683             p_block->i_dts =
684             p_block->i_pts = i_index == 0 ? i_pts : VLC_TS_INVALID;
685
686             p_buf += tk->i_coded_frame_size;
687
688             if( tk->p_subpackets[i_index] != NULL )
689             {
690                 msg_Dbg(p_demux, "p_subpackets[ %d ] not null!",  i_index );
691                 block_Release( tk->p_subpackets[i_index] );
692             }
693
694             tk->p_subpackets[i_index] = p_block;
695             tk->i_subpacket++;
696         }
697     }
698
699     while( tk->i_out_subpacket != tk->i_subpackets &&
700            tk->p_subpackets[tk->i_out_subpacket] )
701     {
702         block_t *p_block = tk->p_subpackets[tk->i_out_subpacket];
703         tk->p_subpackets[tk->i_out_subpacket] = NULL;
704
705         if( tk->p_subpackets_timecode[tk->i_out_subpacket] )
706         {
707             p_block->i_dts =
708             p_block->i_pts = tk->p_subpackets_timecode[tk->i_out_subpacket];
709
710             tk->p_subpackets_timecode[tk->i_out_subpacket] = 0;
711         }
712         tk->i_out_subpacket++;
713
714         CheckPcr( p_demux, tk, p_block->i_pts );
715         es_out_Send( p_demux->out, tk->p_es, p_block );
716     }
717
718     if( tk->i_subpacket == tk->i_subpackets &&
719         tk->i_out_subpacket != tk->i_subpackets )
720     {
721         msg_Warn( p_demux, "i_subpacket != i_out_subpacket, "
722                   "this shouldn't happen" );
723     }
724
725     if( tk->i_subpacket == tk->i_subpackets )
726     {
727         tk->i_subpacket = 0;
728         tk->i_out_subpacket = 0;
729     }
730 }
731
732 static void DemuxAudioMethod2( demux_t *p_demux, real_track_t *tk, mtime_t i_pts )
733 {
734     demux_sys_t *p_sys = p_demux->p_sys;
735
736     if( p_sys->i_buffer < 2 )
737         return;
738
739     unsigned i_sub = (p_sys->buffer[1] >> 4)&0x0f;
740     if( p_sys->i_buffer < 2+2*i_sub )
741         return;
742
743     uint8_t *p_sub = &p_sys->buffer[2+2*i_sub];
744
745     for( unsigned i = 0; i < i_sub; i++ )
746     {
747         const int i_sub_size = GetWBE( &p_sys->buffer[2+i*2] );
748         block_t *p_block = block_New( p_demux, i_sub_size );
749         if( !p_block )
750             break;
751
752         if( &p_sub[i_sub_size] > &p_sys->buffer[p_sys->i_buffer] )
753             break;
754
755         memcpy( p_block->p_buffer, p_sub, i_sub_size );
756         p_sub += i_sub_size;
757
758         p_block->i_dts =
759         p_block->i_pts = i == 0 ? i_pts : VLC_TS_INVALID;
760
761         CheckPcr( p_demux, tk, p_block->i_pts );
762         es_out_Send( p_demux->out, tk->p_es, p_block );
763     }
764 }
765 static void DemuxAudioMethod3( demux_t *p_demux, real_track_t *tk, mtime_t i_pts )
766 {
767     demux_sys_t *p_sys = p_demux->p_sys;
768
769     if( p_sys->i_buffer <= 0 )
770         return;
771
772     block_t *p_block = block_New( p_demux, p_sys->i_buffer );
773     if( !p_block )
774         return;
775
776     if( tk->fmt.i_codec == VLC_CODEC_A52 )
777     {
778         uint8_t *p_src = p_sys->buffer;
779         uint8_t *p_dst = p_block->p_buffer;
780
781         /* byte swap data */
782         while( p_dst < &p_block->p_buffer[p_sys->i_buffer - 1])
783         {
784             *p_dst++ = p_src[1];
785             *p_dst++ = p_src[0];
786
787             p_src += 2;
788         }
789     }
790     else
791     {
792         memcpy( p_block->p_buffer, p_sys->buffer, p_sys->i_buffer );
793     }
794     p_block->i_dts =
795     p_block->i_pts = i_pts;
796
797     CheckPcr( p_demux, tk, p_block->i_pts );
798     es_out_Send( p_demux->out, tk->p_es, p_block );
799 }
800
801 // Sipr packet re-ordering code and index table borrowed from
802 // the MPlayer Realmedia demuxer.
803 static const uint8_t sipr_swap_index_table[38][2] = {
804     {  0, 63 }, {  1, 22 }, {  2, 44 }, {  3, 90 },
805     {  5, 81 }, {  7, 31 }, {  8, 86 }, {  9, 58 },
806     { 10, 36 }, { 12, 68 }, { 13, 39 }, { 14, 73 },
807     { 15, 53 }, { 16, 69 }, { 17, 57 }, { 19, 88 },
808     { 20, 34 }, { 21, 71 }, { 24, 46 }, { 25, 94 },
809     { 26, 54 }, { 28, 75 }, { 29, 50 }, { 32, 70 },
810     { 33, 92 }, { 35, 74 }, { 38, 85 }, { 40, 56 },
811     { 42, 87 }, { 43, 65 }, { 45, 59 }, { 48, 79 },
812     { 49, 93 }, { 51, 89 }, { 55, 95 }, { 61, 76 },
813     { 67, 83 }, { 77, 80 }
814 };
815
816 static void SiprPacketReorder(uint8_t *buf, int sub_packet_h, int framesize)
817 {
818     int n, bs = sub_packet_h * framesize * 2 / 96; // nibbles per subpacket
819
820     for (n = 0; n < 38; n++) {
821         int j;
822         int i = bs * sipr_swap_index_table[n][0];
823         int o = bs * sipr_swap_index_table[n][1];
824
825         /* swap 4 bit-nibbles of block 'i' with 'o' */
826         for (j = 0; j < bs; j++, i++, o++) {
827            int x = (buf[i >> 1] >> (4 * (i & 1))) & 0xF,
828                 y = (buf[o >> 1] >> (4 * (o & 1))) & 0xF;
829
830             buf[o >> 1] = (x << (4 * (o & 1))) |
831                 (buf[o >> 1] & (0xF << (4 * !(o & 1))));
832             buf[i >> 1] = (y << (4 * (i & 1))) |
833                 (buf[i >> 1] & (0xF << (4 * !(i & 1))));
834         }
835     }
836 }
837
838 static void DemuxAudioSipr( demux_t *p_demux, real_track_t *tk, mtime_t i_pts )
839 {
840     demux_sys_t *p_sys = p_demux->p_sys;
841     block_t *p_block = tk->p_sipr_packet;
842
843     if( p_sys->i_buffer < tk->i_frame_size )
844         return;
845
846     if( !p_block )
847     {
848         p_block = block_New( p_demux, tk->i_frame_size * tk->i_subpacket_h );
849         if( !p_block )
850             return;
851         tk->p_sipr_packet = p_block;
852     }
853
854     memcpy( p_block->p_buffer + tk->i_sipr_subpacket_count * tk->i_frame_size,
855             p_sys->buffer, tk->i_frame_size );
856     if (!tk->i_sipr_subpacket_count)
857     {
858         p_block->i_dts =
859         p_block->i_pts = i_pts;
860     }
861
862     if( ++tk->i_sipr_subpacket_count < tk->i_subpacket_h )
863         return;
864
865     SiprPacketReorder(p_block->p_buffer, tk->i_subpacket_h, tk->i_frame_size);
866     CheckPcr( p_demux, tk, p_block->i_pts );
867     es_out_Send( p_demux->out, tk->p_es, p_block );
868     tk->i_sipr_subpacket_count = 0;
869     tk->p_sipr_packet = NULL;
870 }
871
872 static void DemuxAudio( demux_t *p_demux, real_track_t *tk, mtime_t i_pts, unsigned i_flags )
873 {
874     switch( tk->fmt.i_codec )
875     {
876     case VLC_CODEC_COOK:
877     case VLC_CODEC_ATRAC3:
878     case VLC_CODEC_RA_288:
879         DemuxAudioMethod1( p_demux, tk, i_pts, i_flags );
880         break;
881     case VLC_CODEC_MP4A:
882         DemuxAudioMethod2( p_demux, tk, i_pts );
883         break;
884     case VLC_CODEC_SIPR:
885         DemuxAudioSipr( p_demux, tk, i_pts );
886         break;
887     default:
888         DemuxAudioMethod3( p_demux, tk, i_pts );
889         break;
890     }
891 }
892
893 /*****************************************************************************
894  * Helpers: seek/control
895  *****************************************************************************/
896 static int ControlGoToIndex( demux_t *p_demux, real_index_t *p_index )
897 {
898     demux_sys_t *p_sys = p_demux->p_sys;
899
900     p_sys->b_seek = true;
901     p_sys->i_pcr = INT64_C(1000) * p_index->i_time_offset;
902     for( int i = 0; i < p_sys->i_track; i++ )
903         p_sys->track[i]->i_last_dts = 0;
904     return stream_Seek( p_demux->s, p_index->i_file_offset );
905 }
906 static int ControlSeekTime( demux_t *p_demux, mtime_t i_time )
907 {
908     demux_sys_t *p_sys = p_demux->p_sys;
909     real_index_t *p_index = p_sys->p_index;
910
911     while( p_index->i_file_offset != 0 )
912     {
913         if( p_index->i_time_offset * INT64_C(1000) > i_time )
914         {
915             if( p_index != p_sys->p_index )
916                 p_index--;
917             break;
918         }
919         p_index++;
920     }
921     if( p_index->i_file_offset == 0 )
922         return VLC_EGENERIC;
923     return ControlGoToIndex( p_demux, p_index );
924 }
925 static int ControlSeekByte( demux_t *p_demux, int64_t i_bytes )
926 {
927     demux_sys_t *p_sys = p_demux->p_sys;
928     real_index_t *p_index = p_sys->p_index;
929
930     while( p_index->i_file_offset != 0 )
931     {
932         if( p_index->i_file_offset > i_bytes )
933         {
934             if( p_index != p_sys->p_index )
935                 p_index--;
936             break;
937         }
938         p_index++;
939     }
940     if( p_index->i_file_offset == 0 )
941         return VLC_EGENERIC;
942     return ControlGoToIndex( p_demux, p_index );
943 }
944
945 /*****************************************************************************
946  * Helpers: header reading
947  *****************************************************************************/
948
949 /**
950  * This function will read a pascal string with size stored in 2 bytes from
951  * a stream_t.
952  *
953  * FIXME what is the right charset ?
954  */
955 static char *StreamReadString2( stream_t *s )
956 {
957     uint8_t p_tmp[2];
958
959     if( stream_Read( s, p_tmp, 2 ) < 2 )
960         return NULL;
961
962     const int i_length = GetWBE( p_tmp );
963     if( i_length <= 0 )
964         return NULL;
965
966     char *psz_string = calloc( 1, i_length + 1 );
967
968     stream_Read( s, psz_string, i_length ); /* Valid even if !psz_string */
969
970     if( psz_string )
971         EnsureUTF8( psz_string );
972     return psz_string;
973 }
974
975 /**
976  * This function will read a pascal string with size stored in 1 byte from a
977  * memory buffer.
978  *
979  * FIXME what is the right charset ?
980  */
981 static char *MemoryReadString1( const uint8_t **pp_data, int *pi_data )
982 {
983     const uint8_t *p_data = *pp_data;
984     int           i_data = *pi_data;
985
986     char *psz_string = NULL;
987
988     if( i_data < 1 )
989         goto exit;
990
991     int i_length = *p_data++; i_data--;
992     if( i_length > i_data )
993         i_length = i_data;
994
995     if( i_length > 0 )
996     {
997         psz_string = strndup( (const char*)p_data, i_length );
998         if( psz_string )
999             EnsureUTF8( psz_string );
1000
1001         p_data += i_length;
1002         i_data -= i_length;
1003     }
1004
1005 exit:
1006     *pp_data = p_data;
1007     *pi_data = i_data;
1008     return psz_string;
1009 }
1010
1011 /**
1012  * This function parses(skip) the .RMF identification chunk.
1013  */
1014 static int HeaderRMF( demux_t *p_demux )
1015 {
1016     uint8_t p_buffer[8];
1017
1018     if( stream_Read( p_demux->s, p_buffer, 8 ) < 8 )
1019         return VLC_EGENERIC;
1020
1021     msg_Dbg( p_demux, "    - file version=0x%x num headers=%d",
1022              GetDWBE( &p_buffer[0] ), GetDWBE( &p_buffer[4] ) );
1023     return VLC_SUCCESS;
1024 }
1025 /**
1026  * This function parses the PROP properties chunk.
1027  */
1028 static int HeaderPROP( demux_t *p_demux )
1029 {
1030     demux_sys_t *p_sys = p_demux->p_sys;
1031
1032     uint8_t p_buffer[40];
1033     int i_flags;
1034
1035     if( stream_Read( p_demux->s, p_buffer, 40 ) < 40 )
1036         return VLC_EGENERIC;
1037
1038     msg_Dbg( p_demux, "    - max bitrate=%d avg bitrate=%d",
1039              GetDWBE(&p_buffer[0]), GetDWBE(&p_buffer[4]) );
1040     msg_Dbg( p_demux, "    - max packet size=%d avg bitrate=%d",
1041              GetDWBE(&p_buffer[8]), GetDWBE(&p_buffer[12]) );
1042     msg_Dbg( p_demux, "    - packets count=%d", GetDWBE(&p_buffer[16]) );
1043     msg_Dbg( p_demux, "    - duration=%d ms", GetDWBE(&p_buffer[20]) );
1044     msg_Dbg( p_demux, "    - preroll=%d ms", GetDWBE(&p_buffer[24]) );
1045     msg_Dbg( p_demux, "    - index offset=%d", GetDWBE(&p_buffer[28]) );
1046     msg_Dbg( p_demux, "    - data offset=%d", GetDWBE(&p_buffer[32]) );
1047     msg_Dbg( p_demux, "    - num streams=%d", GetWBE(&p_buffer[36]) );
1048
1049     /* set the duration for export in control */
1050     p_sys->i_our_duration = GetDWBE(&p_buffer[20]);
1051
1052     p_sys->i_index_offset = GetDWBE(&p_buffer[28]);
1053
1054     i_flags = GetWBE(&p_buffer[38]);
1055     msg_Dbg( p_demux, "    - flags=0x%x %s%s%s",
1056              i_flags,
1057              i_flags&0x0001 ? "PN_SAVE_ENABLED " : "",
1058              i_flags&0x0002 ? "PN_PERFECT_PLAY_ENABLED " : "",
1059              i_flags&0x0004 ? "PN_LIVE_BROADCAST" : "" );
1060
1061     return VLC_SUCCESS;
1062 }
1063 /**
1064  * This functions parses the CONT commentairs chunk.
1065  */
1066 static int HeaderCONT( demux_t *p_demux )
1067 {
1068     demux_sys_t *p_sys = p_demux->p_sys;
1069
1070     /* */
1071     p_sys->psz_title = StreamReadString2( p_demux->s );
1072     if( p_sys->psz_title )
1073         msg_Dbg( p_demux, "    - title=`%s'", p_sys->psz_title );
1074
1075     /* */
1076     p_sys->psz_artist = StreamReadString2( p_demux->s );
1077     if( p_sys->psz_artist )
1078         msg_Dbg( p_demux, "    - artist=`%s'", p_sys->psz_artist );
1079
1080     /* */
1081     p_sys->psz_copyright = StreamReadString2( p_demux->s );
1082     if( p_sys->psz_copyright )
1083         msg_Dbg( p_demux, "    - copyright=`%s'", p_sys->psz_copyright );
1084
1085     /* */
1086     p_sys->psz_description = StreamReadString2( p_demux->s );
1087     if( p_sys->psz_description )
1088         msg_Dbg( p_demux, "    - comment=`%s'", p_sys->psz_description );
1089
1090     return VLC_SUCCESS;
1091 }
1092 /**
1093  * This function parses the MDPR (Media properties) chunk.
1094  */
1095 static int HeaderMDPR( demux_t *p_demux )
1096 {
1097     uint8_t p_buffer[30];
1098
1099     if( stream_Read( p_demux->s, p_buffer, 30 ) < 30 )
1100         return VLC_EGENERIC;
1101
1102     const int i_num = GetWBE( &p_buffer[0] );
1103     msg_Dbg( p_demux, "    - id=0x%x", i_num );
1104     msg_Dbg( p_demux, "    - max bitrate=%d avg bitrate=%d",
1105              GetDWBE(&p_buffer[2]), GetDWBE(&p_buffer[6]) );
1106     msg_Dbg( p_demux, "    - max packet size=%d avg packet size=%d",
1107              GetDWBE(&p_buffer[10]), GetDWBE(&p_buffer[14]) );
1108     msg_Dbg( p_demux, "    - start time=%d", GetDWBE(&p_buffer[18]) );
1109     msg_Dbg( p_demux, "    - preroll=%d", GetDWBE(&p_buffer[22]) );
1110     msg_Dbg( p_demux, "    - duration=%d", GetDWBE(&p_buffer[26]) );
1111
1112     /* */
1113     const uint8_t *p_peek;
1114     int i_peek_org = stream_Peek( p_demux->s, &p_peek, 2 * 256 );
1115     int i_peek = i_peek_org;
1116     if( i_peek <= 0 )
1117         return VLC_EGENERIC;
1118
1119     char *psz_name = MemoryReadString1( &p_peek, &i_peek );
1120     if( psz_name )
1121     {
1122         msg_Dbg( p_demux, "    - name=`%s'", psz_name );
1123         free( psz_name );
1124     }
1125     char *psz_mime = MemoryReadString1( &p_peek, &i_peek );
1126     if( psz_mime )
1127     {
1128         msg_Dbg( p_demux, "    - mime=`%s'", psz_mime );
1129         free( psz_mime );
1130     }
1131     const int i_skip = i_peek_org - i_peek;
1132     if( i_skip > 0 && stream_Read( p_demux->s, NULL, i_skip ) < i_skip )
1133         return VLC_EGENERIC;
1134
1135     /* */
1136     if( stream_Read( p_demux->s, p_buffer, 4 ) < 4 )
1137         return VLC_EGENERIC;
1138
1139     const uint32_t i_size = GetDWBE( p_buffer );
1140     if( i_size > 0 )
1141     {
1142         CodecParse( p_demux, i_size, i_num );
1143         unsigned size = stream_Read( p_demux->s, NULL, i_size );
1144         if( size < i_size )
1145             return VLC_EGENERIC;
1146     }
1147     return VLC_SUCCESS;
1148 }
1149 /**
1150  * This function parses DATA chunk (it contains the actual movie data).
1151  */
1152 static int HeaderDATA( demux_t *p_demux, uint32_t i_size )
1153 {
1154     demux_sys_t *p_sys = p_demux->p_sys;
1155     uint8_t p_buffer[8];
1156
1157     if( stream_Read( p_demux->s, p_buffer, 8 ) < 8 )
1158         return VLC_EGENERIC;
1159
1160     p_sys->i_data_offset    = stream_Tell( p_demux->s ) - 10;
1161     p_sys->i_data_size      = i_size;
1162     p_sys->i_data_packets_count = GetDWBE( p_buffer );
1163     p_sys->i_data_packets   = 0;
1164     p_sys->i_data_offset_next = GetDWBE( &p_buffer[4] );
1165
1166     msg_Dbg( p_demux, "    - packets count=%d next=%u",
1167              p_sys->i_data_packets_count,
1168              (unsigned int)p_sys->i_data_offset_next );
1169     return VLC_SUCCESS;
1170 }
1171 /**
1172  * This function parses the INDX (movie index chunk).
1173  * It is optional but seeking without it is ... hard.
1174  */
1175 static void HeaderINDX( demux_t *p_demux )
1176 {
1177     demux_sys_t *p_sys = p_demux->p_sys;
1178     uint8_t       buffer[20];
1179
1180     uint32_t      i_index_count;
1181
1182     if( p_sys->i_index_offset == 0 )
1183         return;
1184
1185     stream_Seek( p_demux->s, p_sys->i_index_offset );
1186
1187     if( stream_Read( p_demux->s, buffer, 20 ) < 20 )
1188         return ;
1189
1190     const uint32_t i_id = VLC_FOURCC( buffer[0], buffer[1], buffer[2], buffer[3] );
1191     const uint32_t i_size      = GetDWBE( &buffer[4] );
1192     int i_version   = GetWBE( &buffer[8] );
1193
1194     msg_Dbg( p_demux, "Real index %4.4s size=%d version=%d",
1195                  (char*)&i_id, i_size, i_version );
1196
1197     if( (i_size < 20) && (i_id != VLC_FOURCC('I','N','D','X')) )
1198         return;
1199
1200     i_index_count = GetDWBE( &buffer[10] );
1201
1202     msg_Dbg( p_demux, "Real Index : num : %d ", i_index_count );
1203
1204     if( i_index_count >= ( 0xffffffff / sizeof(*p_sys->p_index) ) )
1205         return;
1206
1207     if( GetDWBE( &buffer[16] ) > 0 )
1208         msg_Dbg( p_demux, "Real Index: Does next index exist? %d ",
1209                         GetDWBE( &buffer[16] )  );
1210
1211     /* One extra entry is allocated (that MUST be set to 0) to identify the
1212      * end of the index.
1213      * TODO add a clean entry count (easier to build index on the fly) */
1214     p_sys->p_index = calloc( i_index_count + 1, sizeof(*p_sys->p_index) );
1215     if( !p_sys->p_index )
1216         return;
1217
1218     for( unsigned int i = 0; i < i_index_count; i++ )
1219     {
1220         uint8_t p_entry[14];
1221
1222         if( stream_Read( p_demux->s, p_entry, 14 ) < 14 )
1223             return ;
1224
1225         if( GetWBE( &p_entry[0] ) != 0 )
1226         {
1227             msg_Dbg( p_demux, "Real Index: invaild version of index entry %d ",
1228                               GetWBE( &p_entry[0] ) );
1229             return;
1230         }
1231
1232         real_index_t *p_idx = &p_sys->p_index[i];
1233         
1234         p_idx->i_time_offset = GetDWBE( &p_entry[2] );
1235         p_idx->i_file_offset = GetDWBE( &p_entry[6] );
1236         p_idx->i_frame_index = GetDWBE( &p_entry[10] );
1237
1238 #if 0
1239         msg_Dbg( p_demux,
1240                  "Real Index: time %"PRIu32" file %"PRIu32" frame %"PRIu32,
1241                  p_idx->i_time_offset,
1242                  p_idx->i_file_offset,
1243                  p_idx->i_frame_index );
1244 #endif
1245     }
1246 }
1247
1248
1249 /**
1250  * This function parses the complete RM headers and move the
1251  * stream pointer to the data to be read.
1252  */
1253 static int HeaderRead( demux_t *p_demux )
1254 {
1255     demux_sys_t *p_sys = p_demux->p_sys;
1256
1257     for( ;; )
1258     {
1259         const int64_t i_stream_position = stream_Tell( p_demux->s );
1260         uint8_t header[100];    /* FIXME */
1261
1262         /* Read the header */
1263         if( stream_Read( p_demux->s, header, 10 ) < 10 )
1264             return VLC_EGENERIC;
1265
1266         const uint32_t i_id = VLC_FOURCC( header[0], header[1],
1267                                           header[2], header[3] );
1268         const uint32_t i_size = GetDWBE( &header[4] );
1269         const int i_version = GetWBE( &header[8] );
1270
1271         msg_Dbg( p_demux, "object %4.4s size=%d version=%d",
1272                  (char*)&i_id, i_size, i_version );
1273
1274         /* */
1275         if( i_size < 10 && i_id != VLC_FOURCC('D','A','T','A') )
1276         {
1277             msg_Dbg( p_demux, "invalid size for object %4.4s", (char*)&i_id );
1278             return VLC_EGENERIC;
1279         }
1280
1281         int i_ret;
1282         switch( i_id )
1283         {
1284         case VLC_FOURCC('.','R','M','F'):
1285             i_ret = HeaderRMF( p_demux );
1286             break;
1287         case VLC_FOURCC('P','R','O','P'):
1288             i_ret = HeaderPROP( p_demux );
1289             break;
1290         case VLC_FOURCC('C','O','N','T'):
1291             i_ret = HeaderCONT( p_demux );
1292             break;
1293         case VLC_FOURCC('M','D','P','R'):
1294             i_ret = HeaderMDPR( p_demux );
1295             break;
1296         case VLC_FOURCC('D','A','T','A'):
1297             i_ret = HeaderDATA( p_demux, i_size );
1298             break;
1299         default:
1300             /* unknow header */
1301             msg_Dbg( p_demux, "unknown chunk" );
1302             i_ret = VLC_SUCCESS;
1303             break;
1304         }
1305         if( i_ret )
1306             return i_ret;
1307
1308         if( i_id == VLC_FOURCC('D','A','T','A') ) /* In this case, parsing is finished */
1309             break;
1310
1311         /* Skip unread data */
1312         const int64_t i_stream_current = stream_Tell( p_demux->s );
1313         const int64_t i_stream_skip = (i_stream_position + i_size) - i_stream_current;
1314
1315         if( i_stream_skip > 0 )
1316         {
1317             if( stream_Read( p_demux->s, NULL, i_stream_skip ) != i_stream_skip )
1318                 return VLC_EGENERIC;
1319         }
1320         else if( i_stream_skip < 0 )
1321         {
1322             return VLC_EGENERIC;
1323         }
1324     }
1325
1326     /* read index if possible */
1327     if( p_sys->i_index_offset > 0 )
1328     {
1329         const int64_t i_position = stream_Tell( p_demux->s );
1330
1331         HeaderINDX( p_demux );
1332
1333         if( stream_Seek( p_demux->s, i_position ) )
1334             return VLC_EGENERIC;
1335     }
1336     return VLC_SUCCESS;
1337 }
1338
1339 static void CodecMetaRead( demux_t *p_demux, const uint8_t **pp_data, int *pi_data )
1340 {
1341     demux_sys_t *p_sys = p_demux->p_sys;
1342
1343     /* Title */
1344     p_sys->psz_title = MemoryReadString1( pp_data, pi_data );
1345     if( p_sys->psz_title )
1346         msg_Dbg( p_demux, "    - title=`%s'", p_sys->psz_title );
1347
1348     /* Authors */
1349     p_sys->psz_artist = MemoryReadString1( pp_data, pi_data );
1350     if( p_sys->psz_artist )
1351         msg_Dbg( p_demux, "    - artist=`%s'", p_sys->psz_artist );
1352
1353     /* Copyright */
1354     p_sys->psz_copyright = MemoryReadString1( pp_data, pi_data );
1355     if( p_sys->psz_copyright )
1356         msg_Dbg( p_demux, "    - copyright=`%s'", p_sys->psz_copyright );
1357
1358     /* Comment */
1359     p_sys->psz_description = MemoryReadString1( pp_data, pi_data );
1360     if( p_sys->psz_description )
1361         msg_Dbg( p_demux, "    - Comment=`%s'", p_sys->psz_description );
1362 }
1363
1364 static int CodecVideoParse( demux_t *p_demux, int i_tk_id, const uint8_t *p_data, int i_data )
1365 {
1366     demux_sys_t *p_sys = p_demux->p_sys;
1367
1368     if( i_data < 34 )
1369         return VLC_EGENERIC;
1370
1371     /* */
1372     es_format_t fmt;
1373     es_format_Init( &fmt, VIDEO_ES,
1374                     VLC_FOURCC( p_data[8], p_data[9], p_data[10], p_data[11] ) );
1375     fmt.video.i_width = GetWBE( &p_data[12] );
1376     fmt.video.i_height= GetWBE( &p_data[14] );
1377     fmt.video.i_frame_rate = (GetWBE( &p_data[22] ) << 16) | GetWBE( &p_data[24] );
1378     fmt.video.i_frame_rate_base = 1 << 16;
1379
1380     fmt.i_extra = 8;
1381     fmt.p_extra = malloc( 8 );
1382     if( !fmt.p_extra )
1383         return VLC_ENOMEM;
1384
1385     memcpy( fmt.p_extra, &p_data[26], 8 );
1386
1387     //msg_Dbg( p_demux, "    - video 0x%08x 0x%08x", dw0, dw1 );
1388
1389     /* */
1390     switch( GetDWBE( &p_data[30] ) )
1391     {
1392     case 0x10003000:
1393     case 0x10003001:
1394         fmt.i_codec = VLC_CODEC_RV13;
1395         break;
1396     case 0x20001000:
1397     case 0x20100001:
1398     case 0x20200002:
1399     case 0x20201002:
1400         fmt.i_codec = VLC_CODEC_RV20;
1401         break;
1402     case 0x30202002:
1403         fmt.i_codec = VLC_CODEC_RV30;
1404         break;
1405     case 0x40000000:
1406         fmt.i_codec = VLC_CODEC_RV40;
1407         break;
1408     }
1409     msg_Dbg( p_demux, "    - video %4.4s %dx%d - %8.8x",
1410              (char*)&fmt.i_codec, fmt.video.i_width, fmt.video.i_height, GetDWBE( &p_data[30] ) );
1411
1412     real_track_t *tk = malloc( sizeof( *tk ) );
1413     if( !tk )
1414     {
1415         es_format_Clean( &fmt );
1416         return VLC_ENOMEM;
1417     }
1418     tk->i_out_subpacket = 0;
1419     tk->i_subpacket = 0;
1420     tk->i_subpackets = 0;
1421     tk->p_subpackets = NULL;
1422     tk->p_subpackets_timecode = NULL;
1423     tk->i_id = i_tk_id;
1424     tk->fmt = fmt;
1425     tk->i_frame_num = -1;
1426     tk->i_frame_size = 0;
1427     tk->p_frame = NULL;
1428     tk->i_last_dts = 0;
1429     tk->p_sipr_packet = NULL;
1430     tk->p_es = es_out_Add( p_demux->out, &fmt );
1431
1432     TAB_APPEND( p_sys->i_track, p_sys->track, tk );
1433     return VLC_SUCCESS;
1434 }
1435 static int CodecAudioParse( demux_t *p_demux, int i_tk_id, const uint8_t *p_data, int i_data )
1436 {
1437     demux_sys_t *p_sys = p_demux->p_sys;
1438     es_format_t fmt;
1439
1440     if( i_data < 6 )
1441         return VLC_EGENERIC;
1442
1443     int i_flavor = 0;
1444     int i_coded_frame_size = 0;
1445     int i_subpacket_h = 0;
1446     int i_frame_size = 0;
1447     int i_subpacket_size = 0;
1448     char p_genr[4];
1449     int i_version = GetWBE( &p_data[4] );
1450     int i_extra_codec = 0;
1451
1452     msg_Dbg( p_demux, "    - audio version=%d", i_version );
1453
1454     es_format_Init( &fmt, AUDIO_ES, 0 );
1455
1456     RVoid( &p_data, &i_data, 6 );                         /* 4 + version */
1457     if( i_version == 3 ) /* RMF version 3 or .ra version 3 */
1458     {
1459         RVoid( &p_data, &i_data, 2 + 10 + 4 );
1460
1461         /* Meta Datas */
1462         CodecMetaRead( p_demux, &p_data, &i_data );
1463
1464         RVoid( &p_data, &i_data, 1 + 1 );
1465         if( i_data >= 4 )
1466             memcpy( &fmt.i_codec, p_data, 4 );
1467         RVoid( &p_data, &i_data, 4 );
1468
1469         fmt.audio.i_channels = 1;      /* This is always the case in rm3 */
1470         fmt.audio.i_rate = 8000;
1471
1472         msg_Dbg( p_demux, "    - audio codec=%4.4s channels=%d rate=%dHz",
1473              (char*)&fmt.i_codec, fmt.audio.i_channels, fmt.audio.i_rate );
1474     }
1475     else  /* RMF version 4/5 or .ra version 4 */
1476     {
1477         RVoid( &p_data, &i_data, 2 + 4 + 4 + 2 + 4 );
1478         i_flavor = R16( &p_data, &i_data );
1479         i_coded_frame_size = R32( &p_data, &i_data );
1480         RVoid( &p_data, &i_data, 4 + 4 + 4 );
1481         i_subpacket_h = R16( &p_data, &i_data );
1482         i_frame_size = R16( &p_data, &i_data );
1483         i_subpacket_size = R16( &p_data, &i_data );
1484         if( !i_frame_size || !i_coded_frame_size )
1485             return VLC_EGENERIC;
1486
1487         RVoid( &p_data, &i_data, 2 + (i_version == 5 ? 6 : 0 ) );
1488
1489         fmt.audio.i_rate = R16( &p_data, &i_data );
1490         RVoid( &p_data, &i_data, 2 );
1491         fmt.audio.i_bitspersample = R16( &p_data, &i_data );
1492         fmt.audio.i_channels = R16( &p_data, &i_data );
1493         fmt.audio.i_blockalign = i_frame_size;
1494
1495         if( i_version == 5 )
1496         {
1497             if( i_data >= 8 )
1498             {
1499                 memcpy( p_genr,       &p_data[0], 4 );
1500                 memcpy( &fmt.i_codec, &p_data[4], 4 );
1501             }
1502             RVoid( &p_data, &i_data, 8 );
1503         }
1504         else /* version 4 */
1505         {
1506             if( i_data > 0 )
1507                 RVoid( &p_data, &i_data, 1 + *p_data );
1508             if( i_data >= 1 + 4 )
1509                 memcpy( &fmt.i_codec, &p_data[1], 4 );
1510             if( i_data > 0 )
1511                 RVoid( &p_data, &i_data, 1 + *p_data );
1512         }
1513
1514         msg_Dbg( p_demux, "    - audio codec=%4.4s channels=%d rate=%dHz",
1515              (char*)&fmt.i_codec, fmt.audio.i_channels, fmt.audio.i_rate );
1516
1517         RVoid( &p_data, &i_data, 3 );
1518
1519         if( p_sys->b_real_audio )
1520         {
1521             CodecMetaRead( p_demux, &p_data, &i_data );
1522         }
1523         else
1524         {
1525             if( i_version == 5 )
1526                 RVoid( &p_data, &i_data, 1 );
1527             i_extra_codec = R32( &p_data, &i_data );
1528         }
1529     }
1530
1531     switch( fmt.i_codec )
1532     {
1533     case VLC_FOURCC('l','p','c','J'):
1534     case VLC_FOURCC('1','4','_','4'):
1535         fmt.i_codec = VLC_CODEC_RA_144;
1536         fmt.audio.i_blockalign = 0x14 ;
1537         break;
1538
1539     case VLC_FOURCC('2','8','_','8'):
1540         fmt.i_codec = VLC_CODEC_RA_288;
1541         fmt.audio.i_blockalign = i_coded_frame_size;
1542         break;
1543
1544     case VLC_FOURCC( 'a','5','2',' ' ):
1545     case VLC_FOURCC( 'd','n','e','t' ):
1546         fmt.i_codec = VLC_CODEC_A52;
1547         break;
1548
1549     case VLC_FOURCC( 'r','a','a','c' ):
1550     case VLC_FOURCC( 'r','a','c','p' ):
1551         fmt.i_codec = VLC_CODEC_MP4A;
1552
1553         if( i_extra_codec > 0 )
1554         {
1555             i_extra_codec--;
1556             RVoid( &p_data, &i_data, 1 );
1557         }
1558         if( i_extra_codec > 0 )
1559         {
1560             fmt.p_extra = malloc( i_extra_codec );
1561             if( !fmt.p_extra || i_extra_codec > i_data )
1562                 return VLC_ENOMEM;
1563
1564             fmt.i_extra = i_extra_codec;
1565             memcpy( fmt.p_extra, p_data, fmt.i_extra );
1566         }
1567         break;
1568
1569     case VLC_FOURCC( 's','i','p','r' ):
1570         fmt.i_codec = VLC_CODEC_SIPR;
1571         if( i_flavor > 3 )
1572             return VLC_EGENERIC;
1573
1574         i_subpacket_size = i_subpacket_size_sipr[i_flavor];
1575         // The libavcodec sipr decoder requires stream bitrate
1576         // to be set during initialization so that the correct mode
1577         // can be selected.
1578         fmt.i_bitrate = fmt.audio.i_rate;
1579         msg_Dbg( p_demux, "    - sipr flavor=%i", i_flavor );
1580
1581     case VLC_FOURCC( 'c','o','o','k' ):
1582     case VLC_FOURCC( 'a','t','r','c' ):
1583         if( i_subpacket_size <= 0 || i_frame_size / i_subpacket_size <= 0 )
1584         {
1585             es_format_Clean( &fmt );
1586             return VLC_EGENERIC;
1587         }
1588         if( !memcmp( p_genr, "genr", 4 ) )
1589             fmt.audio.i_blockalign = i_subpacket_size;
1590         else
1591             fmt.audio.i_blockalign = i_coded_frame_size;
1592
1593         if( fmt.i_codec == VLC_FOURCC( 'c','o','o','k' ) )
1594             fmt.i_codec = VLC_CODEC_COOK;
1595         else if( fmt.i_codec == VLC_FOURCC( 'a','t','r','c' ) )
1596             fmt.i_codec = VLC_CODEC_ATRAC3;
1597
1598         if( i_extra_codec > 0 )
1599         {
1600             fmt.p_extra = malloc( i_extra_codec );
1601             if( !fmt.p_extra || i_extra_codec > i_data )
1602                 return VLC_ENOMEM;
1603
1604             fmt.i_extra = i_extra_codec;
1605             memcpy( fmt.p_extra, p_data, fmt.i_extra );
1606         }
1607
1608         break;
1609
1610     case VLC_FOURCC('r','a','l','f'):
1611         msg_Dbg( p_demux, "    - audio codec not supported=%4.4s",
1612                  (char*)&fmt.i_codec );
1613         break;
1614
1615     default:
1616         msg_Dbg( p_demux, "    - unknown audio codec=%4.4s",
1617                  (char*)&fmt.i_codec );
1618         break;
1619     }
1620     msg_Dbg( p_demux, "    - extra data=%d", fmt.i_extra );
1621
1622     /* */
1623     real_track_t *tk = malloc( sizeof( *tk ) );
1624     if( !tk )
1625     {
1626         es_format_Clean( &fmt );
1627         return VLC_ENOMEM;
1628     }
1629     tk->i_id = i_tk_id;
1630     tk->fmt = fmt;
1631     tk->i_frame_size = 0;
1632     tk->p_frame = NULL;
1633
1634     tk->i_subpacket_h = i_subpacket_h;
1635     tk->i_subpacket_size = i_subpacket_size;
1636     tk->i_coded_frame_size = i_coded_frame_size;
1637     tk->i_frame_size = i_frame_size;
1638
1639     tk->i_out_subpacket = 0;
1640     tk->i_subpacket = 0;
1641     tk->i_subpackets = 0;
1642     tk->p_subpackets = NULL;
1643     tk->p_subpackets_timecode = NULL;
1644
1645     tk->p_sipr_packet          = NULL;
1646     tk->i_sipr_subpacket_count = 0;
1647
1648     if( fmt.i_codec == VLC_CODEC_COOK ||
1649         fmt.i_codec == VLC_CODEC_ATRAC3 )
1650     {
1651         tk->i_subpackets =
1652             i_subpacket_h * i_frame_size / tk->i_subpacket_size;
1653         tk->p_subpackets =
1654             calloc( tk->i_subpackets, sizeof(block_t *) );
1655         tk->p_subpackets_timecode =
1656             calloc( tk->i_subpackets , sizeof( int64_t ) );
1657     }
1658     else if( fmt.i_codec == VLC_CODEC_RA_288 )
1659     {
1660         tk->i_subpackets =
1661             i_subpacket_h * i_frame_size / tk->i_coded_frame_size;
1662         tk->p_subpackets =
1663             calloc( tk->i_subpackets, sizeof(block_t *) );
1664         tk->p_subpackets_timecode =
1665             calloc( tk->i_subpackets , sizeof( int64_t ) );
1666     }
1667
1668     /* Check if the calloc went correctly */
1669     if( tk->i_subpacket > 0 && ( !tk->p_subpackets || !tk->p_subpackets_timecode ) )
1670     {
1671         free( tk->p_subpackets_timecode );
1672         free( tk->p_subpackets );
1673         free( tk );
1674         msg_Err( p_demux, "Can't alloc subpacket" );
1675         return VLC_EGENERIC;
1676     }
1677
1678     tk->i_last_dts = 0;
1679     tk->p_es = es_out_Add( p_demux->out, &fmt );
1680
1681     TAB_APPEND( p_sys->i_track, p_sys->track, tk );
1682
1683     return VLC_SUCCESS;
1684 }
1685
1686
1687 static int CodecParse( demux_t *p_demux, int i_len, int i_num )
1688 {
1689     const uint8_t *p_peek;
1690
1691     msg_Dbg( p_demux, "    - specific data len=%d", i_len );
1692     if( stream_Peek( p_demux->s, &p_peek, i_len ) < i_len )
1693         return VLC_EGENERIC;
1694
1695     if( i_len >= 8 && !memcmp( &p_peek[4], "VIDO", 4 ) )
1696     {
1697         return CodecVideoParse( p_demux, i_num, p_peek, i_len );
1698     }
1699     else if( i_len >= 4 && !memcmp( &p_peek[0], ".ra\xfd", 4 ) )
1700     {
1701         return CodecAudioParse( p_demux, i_num, p_peek, i_len );
1702     }
1703     return VLC_SUCCESS;
1704 }
1705
1706 /*****************************************************************************
1707  * Helpers: memory buffer fct.
1708  *****************************************************************************/
1709 static void RVoid( const uint8_t **pp_data, int *pi_data, int i_size )
1710 {
1711     if( i_size > *pi_data )
1712         i_size = *pi_data;
1713
1714     *pp_data += i_size;
1715     *pi_data -= i_size;
1716 }
1717 #define RX(name, type, size, code ) \
1718 static type name( const uint8_t **pp_data, int *pi_data ) { \
1719     if( *pi_data < (size) )          \
1720         return 0;                    \
1721     type v = code;                   \
1722     RVoid( pp_data, pi_data, size ); \
1723     return v;                        \
1724 }
1725 RX(R8,  uint8_t, 1, **pp_data )
1726 RX(R16, uint16_t, 2, GetWBE( *pp_data ) )
1727 RX(R32, uint32_t, 4, GetDWBE( *pp_data ) )
1728 static int RLength( const uint8_t **pp_data, int *pi_data )
1729 {
1730     const int v0 = R16( pp_data, pi_data ) & 0x7FFF;
1731     if( v0 >= 0x4000 )
1732         return v0 - 0x4000;
1733     return (v0 << 16) | R16( pp_data, pi_data );
1734 }
1735
1736