]> git.sesse.net Git - vlc/blob - modules/demux/real.c
fa3219867c8905bb55893ef2ae3b201f0bbba2fc
[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", 0 )
72     set_category( CAT_INPUT )
73     set_subcategory( SUBCAT_INPUT_DEMUX )
74     set_callbacks( Open, Close )
75     add_shortcut( "real", "rm" )
76 vlc_module_end ()
77
78 /*****************************************************************************
79  * Local prototypes
80  *****************************************************************************/
81
82 typedef struct
83 {
84     int         i_id;
85     es_format_t fmt;
86
87     es_out_id_t *p_es;
88
89     unsigned    i_frame_size;
90
91     int         i_frame_num;
92     unsigned    i_frame_pos;
93     int         i_frame_slice;
94     int         i_frame_slice_count;
95     block_t     *p_frame;
96
97     int         i_subpacket_h;
98     int         i_subpacket_size;
99     int         i_coded_frame_size;
100
101     int         i_subpacket;
102     int         i_subpackets;
103     block_t     **p_subpackets;
104     mtime_t     *p_subpackets_timecode;
105     int         i_out_subpacket;
106
107     block_t     *p_sipr_packet;
108     int         i_sipr_subpacket_count;
109     mtime_t     i_last_dts;
110 } real_track_t;
111
112 typedef struct
113 {
114     uint32_t i_file_offset;
115     uint32_t i_time_offset;
116     uint32_t i_frame_index;
117 } real_index_t;
118
119 struct demux_sys_t
120 {
121     int64_t  i_data_offset;
122     int64_t  i_data_size;
123     uint32_t i_data_packets_count;
124     uint32_t i_data_packets;
125     int64_t  i_data_offset_next;
126
127     bool     b_real_audio;
128
129     int64_t i_our_duration;
130
131     char* psz_title;
132     char* psz_artist;
133     char* psz_copyright;
134     char* psz_description;
135
136     int          i_track;
137     real_track_t **track;
138
139     size_t     i_buffer;
140     uint8_t buffer[65536];
141
142     int64_t     i_pcr;
143
144     int64_t     i_index_offset;
145     bool        b_seek;
146     real_index_t *p_index;
147 };
148
149 static const unsigned char i_subpacket_size_sipr[4] = { 29, 19, 37, 20 };
150
151 static int Demux( demux_t * );
152 static int Control( demux_t *, int i_query, va_list args );
153
154
155 static void DemuxVideo( demux_t *, real_track_t *tk, mtime_t i_dts, unsigned i_flags );
156 static void DemuxAudio( demux_t *, real_track_t *tk, mtime_t i_pts, unsigned i_flags );
157
158 static int ControlSeekByte( demux_t *, int64_t i_bytes );
159 static int ControlSeekTime( demux_t *, mtime_t i_time );
160
161 static int HeaderRead( demux_t *p_demux );
162 static int CodecParse( demux_t *p_demux, int i_len, int i_num );
163
164 static void     RVoid( const uint8_t **pp_data, int *pi_data, int i_size );
165 static int      RLength( const uint8_t **pp_data, int *pi_data );
166 static uint8_t  R8( const uint8_t **pp_data, int *pi_data );
167 static uint16_t R16( const uint8_t **pp_data, int *pi_data );
168 static uint32_t R32( const uint8_t **pp_data, int *pi_data );
169 static void     SiprPacketReorder(uint8_t *buf, int sub_packet_h, int framesize);
170
171 /*****************************************************************************
172  * Open
173  *****************************************************************************/
174 static int Open( vlc_object_t *p_this )
175 {
176     demux_t     *p_demux = (demux_t*)p_this;
177     demux_sys_t *p_sys;
178
179     const uint8_t *p_peek;
180     bool           b_real_audio = false;
181
182     if( stream_Peek( p_demux->s, &p_peek, 10 ) < 10 )
183         return VLC_EGENERIC;
184
185     /* Real Audio */
186     if( !memcmp( p_peek, ".ra", 3 ) )
187     {
188         msg_Err( p_demux, ".ra files unsuported" );
189         b_real_audio = true;
190     }
191     /* Real Media Format */
192     else if( memcmp( p_peek, ".RMF", 4 ) )
193     {
194         return VLC_EGENERIC;
195     }
196
197     /* Fill p_demux field */
198     p_demux->pf_demux = Demux;
199     p_demux->pf_control = Control;
200
201     p_demux->p_sys = p_sys = calloc( 1, sizeof( *p_sys ) );
202     if( !p_sys )
203         return VLC_ENOMEM;
204
205     p_sys->i_data_offset = 0;
206     p_sys->i_track = 0;
207     p_sys->track   = NULL;
208     p_sys->i_pcr   = VLC_TS_INVALID;
209
210     p_sys->b_seek  = false;
211     p_sys->b_real_audio = b_real_audio;
212
213     /* Parse the headers */
214     /* Real Audio files */
215     if( b_real_audio )
216     {
217         CodecParse( p_demux, 32, 0 ); /* At least 32 */
218         return VLC_EGENERIC;                     /* We don't know how to read
219                                                     correctly the data yet */
220     }
221     /* RMF files */
222     else if( HeaderRead( p_demux ) )
223     {
224         msg_Err( p_demux, "invalid header" );
225         Close( p_this );
226         return VLC_EGENERIC;
227     }
228
229     return VLC_SUCCESS;
230 }
231
232 /*****************************************************************************
233  * Close
234  *****************************************************************************/
235 static void Close( vlc_object_t *p_this )
236 {
237     demux_t *p_demux = (demux_t*)p_this;
238     demux_sys_t *p_sys = p_demux->p_sys;
239
240     for( int i = 0; i < p_sys->i_track; i++ )
241     {
242         real_track_t *tk = p_sys->track[i];
243
244         es_format_Clean( &tk->fmt );
245
246         if( tk->p_frame )
247             block_Release( tk->p_frame );
248
249         for( int j = 0; j < tk->i_subpackets; j++ )
250         {
251             if( tk->p_subpackets[ j ] )
252                 block_Release( tk->p_subpackets[ j ] );
253         }
254         free( tk->p_subpackets );
255         free( tk->p_subpackets_timecode );
256         if( tk->p_sipr_packet )
257             block_Release( tk->p_sipr_packet );
258         free( tk );
259     }
260     if( p_sys->i_track > 0 )
261         free( p_sys->track );
262
263     free( p_sys->psz_title );
264     free( p_sys->psz_artist );
265     free( p_sys->psz_copyright );
266     free( p_sys->psz_description );
267     free( p_sys->p_index );
268
269     free( p_sys );
270 }
271
272
273 /*****************************************************************************
274  * Demux:
275  *****************************************************************************/
276 static int Demux( demux_t *p_demux )
277 {
278     demux_sys_t *p_sys = p_demux->p_sys;
279     uint8_t     header[18];
280
281     if( p_sys->i_data_packets >= p_sys->i_data_packets_count &&
282         p_sys->i_data_packets_count )
283     {
284         if( stream_Read( p_demux->s, header, 18 ) < 18 )
285             return 0;
286
287         if( memcmp( header, "DATA", 4 ) )
288             return 0;
289
290         p_sys->i_data_offset = stream_Tell( p_demux->s ) - 18;
291         p_sys->i_data_size   = GetDWBE( &header[4] );
292         p_sys->i_data_packets_count = GetDWBE( &header[10] );
293         p_sys->i_data_packets = 0;
294         p_sys->i_data_offset_next = GetDWBE( &header[14] );
295
296         msg_Dbg( p_demux, "entering new DATA packets=%d next=%u",
297                  p_sys->i_data_packets_count,
298                  (unsigned int)p_sys->i_data_offset_next );
299     }
300
301     /* Read Packet Header */
302     if( stream_Read( p_demux->s, header, 12 ) < 12 )
303         return 0;
304     //const int i_version = GetWBE( &header[0] );
305     const size_t  i_size = GetWBE( &header[2] ) - 12;
306     const int     i_id   = GetWBE( &header[4] );
307     const int64_t i_pts  = VLC_TS_0 + 1000 * GetDWBE( &header[6] );
308     const int     i_flags= header[11]; /* flags 0x02 -> keyframe */
309
310     p_sys->i_data_packets++;
311     if( i_size > sizeof(p_sys->buffer) )
312     {
313         msg_Err( p_demux, "Got a NUKK size to read. (Invalid format?)" );
314         return 1;
315     }
316
317     p_sys->i_buffer = stream_Read( p_demux->s, p_sys->buffer, i_size );
318     if( p_sys->i_buffer < i_size )
319         return 0;
320
321     real_track_t *tk = NULL;
322     for( int i = 0; i < p_sys->i_track; i++ )
323     {
324         if( p_sys->track[i]->i_id == i_id )
325             tk = p_sys->track[i];
326     }
327
328     if( !tk )
329     {
330         msg_Warn( p_demux, "unknown track id(0x%x)", i_id );
331         return 1;
332     }
333
334     if( tk->fmt.i_cat == VIDEO_ES )
335     {
336         DemuxVideo( p_demux, tk, i_pts, i_flags );
337     }
338     else
339     {
340         assert( tk->fmt.i_cat == AUDIO_ES );
341         DemuxAudio( p_demux, tk, i_pts, i_flags );
342     }
343
344     /* Update PCR */
345     mtime_t i_pcr = VLC_TS_INVALID;
346     for( int i = 0; i < p_sys->i_track; i++ )
347     {
348         real_track_t *tk = p_sys->track[i];
349
350         if( i_pcr <= VLC_TS_INVALID || ( tk->i_last_dts > VLC_TS_INVALID && tk->i_last_dts < i_pcr ) )
351             i_pcr = tk->i_last_dts;
352     }
353     if( i_pcr > VLC_TS_INVALID && i_pcr != p_sys->i_pcr )
354     {
355         p_sys->i_pcr = i_pcr;
356         es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_sys->i_pcr );
357     }
358     return 1;
359 }
360
361 /*****************************************************************************
362  * Control:
363  *****************************************************************************/
364 static int Control( demux_t *p_demux, int i_query, va_list args )
365 {
366     demux_sys_t *p_sys = p_demux->p_sys;
367     double f, *pf;
368     int64_t i64;
369     int64_t *pi64;
370
371     switch( i_query )
372     {
373         case DEMUX_GET_POSITION:
374             pf = (double*) va_arg( args, double* );
375
376             /* read stream size maybe failed in rtsp streaming, 
377                so use duration to determin the position at first  */
378             if( p_sys->i_our_duration > 0 )
379             {
380                 if( p_sys->i_pcr > VLC_TS_INVALID )
381                     *pf = (double)p_sys->i_pcr / 1000.0 / p_sys->i_our_duration;
382                 else
383                     *pf = 0.0;
384                 return VLC_SUCCESS;
385             }
386
387             i64 = stream_Size( p_demux->s );
388             if( i64 > 0 )
389                 *pf = (double)1.0*stream_Tell( p_demux->s ) / (double)i64;
390             else
391                 *pf = 0.0;
392             return VLC_SUCCESS;
393
394         case DEMUX_GET_TIME:
395             pi64 = (int64_t*)va_arg( args, int64_t * );
396
397             if( p_sys->i_our_duration > 0 )
398             {
399                 *pi64 = p_sys->i_pcr > VLC_TS_INVALID ? p_sys->i_pcr : 0;
400                 return VLC_SUCCESS;
401             }
402
403             /* same as GET_POSTION */
404             i64 = stream_Size( p_demux->s );
405             if( p_sys->i_our_duration > 0 && i64 > 0 )
406             {
407                 *pi64 = (int64_t)( 1000.0 * p_sys->i_our_duration * stream_Tell( p_demux->s ) / i64 );
408                 return VLC_SUCCESS;
409             }
410
411             *pi64 = 0;
412             return VLC_EGENERIC;
413
414         case DEMUX_SET_POSITION:
415             f = (double) va_arg( args, double );
416             i64 = (int64_t) ( stream_Size( p_demux->s ) * f );
417
418             if( !p_sys->p_index && i64 != 0 )
419             {
420                 /* TODO seek */
421                 msg_Err( p_demux,"Seek No Index Real File failed!" );
422                 return VLC_EGENERIC; // no index!
423             }
424             else if( i64 == 0 )
425             {
426                 /* it is a rtsp stream , it is specials in access/rtsp/... */
427                 msg_Dbg(p_demux, "Seek in real rtsp stream!");
428                 p_sys->i_pcr = VLC_TS_0 + INT64_C(1000) * ( p_sys->i_our_duration * f  );
429                 p_sys->b_seek = true;
430                 return stream_Seek( p_demux->s, p_sys->i_pcr - VLC_TS_0 );
431             }
432             return ControlSeekByte( p_demux, i64 );
433
434         case DEMUX_SET_TIME:
435             if( !p_sys->p_index )
436                 return VLC_EGENERIC;
437
438             i64 = (int64_t) va_arg( args, int64_t );
439             return ControlSeekTime( p_demux, i64 );
440
441         case DEMUX_GET_LENGTH:
442             pi64 = (int64_t*)va_arg( args, int64_t * );
443  
444             if( p_sys->i_our_duration <= 0 )
445             {
446                 *pi64 = 0;
447                 return VLC_EGENERIC;
448             }
449
450             /* our stored duration is in ms, so... */
451             *pi64 = INT64_C(1000) * p_sys->i_our_duration;
452             return VLC_SUCCESS;
453
454         case DEMUX_GET_META:
455         {
456             vlc_meta_t *p_meta = (vlc_meta_t*)va_arg( args, vlc_meta_t* );
457
458             /* the core will crash if we provide NULL strings, so check
459              * every string first */
460             if( p_sys->psz_title )
461                 vlc_meta_SetTitle( p_meta, p_sys->psz_title );
462             if( p_sys->psz_artist )
463                 vlc_meta_SetArtist( p_meta, p_sys->psz_artist );
464             if( p_sys->psz_copyright )
465                 vlc_meta_SetCopyright( p_meta, p_sys->psz_copyright );
466             if( p_sys->psz_description )
467                 vlc_meta_SetDescription( p_meta, p_sys->psz_description );
468             return VLC_SUCCESS;
469         }
470
471         case DEMUX_GET_FPS:
472         default:
473             return VLC_EGENERIC;
474     }
475     return VLC_EGENERIC;
476 }
477
478 /*****************************************************************************
479  * Helpers: demux
480  *****************************************************************************/
481 static void CheckPcr( demux_t *p_demux, real_track_t *tk, mtime_t i_dts )
482 {
483     demux_sys_t *p_sys = p_demux->p_sys;
484
485     if( i_dts > VLC_TS_INVALID )
486         tk->i_last_dts = i_dts;
487
488     if( p_sys->i_pcr > VLC_TS_INVALID || i_dts <= VLC_TS_INVALID )
489         return;
490
491     p_sys->i_pcr = i_dts;
492     es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_sys->i_pcr );
493 }
494
495 static void DemuxVideo( demux_t *p_demux, real_track_t *tk, mtime_t i_dts, unsigned i_flags )
496 {
497     demux_sys_t *p_sys = p_demux->p_sys;
498
499     const uint8_t *p_data = p_sys->buffer;
500     int     i_data = p_sys->i_buffer;
501
502     while( i_data > 1 )
503     {
504         uint8_t i_hdr = R8( &p_data, &i_data );
505         uint8_t i_type = i_hdr >> 6;
506
507         uint8_t i_seq;
508         int i_len;
509         int i_pos;
510         int i_frame_num;
511
512         if( i_type == 1 )
513         {
514             R8( &p_data, &i_data );
515             i_len = i_data;
516             i_pos = 0;
517             i_frame_num = -1;
518             i_seq = 1;
519             i_hdr &= ~0x3f;
520         }
521         else if( i_type == 3 )
522         {
523             i_len = RLength( &p_data, &i_data );
524             i_pos = RLength( &p_data, &i_data );
525             i_frame_num = R8( &p_data, &i_data );
526             i_seq = 1;
527             i_hdr &= ~0x3f;
528         }
529         else
530         {
531             assert( i_type == 0 || i_type == 2 );
532             i_seq = R8( &p_data, &i_data );
533             i_len = RLength( &p_data, &i_data );
534
535             i_pos = RLength( &p_data, &i_data );
536             i_frame_num = R8( &p_data, &i_data );
537         }
538
539         if( (i_seq & 0x7f) == 1 || tk->i_frame_num != i_frame_num )
540         {
541             tk->i_frame_slice = 0;
542             tk->i_frame_slice_count = 2 * (i_hdr & 0x3f) + 1;
543             tk->i_frame_pos = 2*4 * tk->i_frame_slice_count + 1;
544             tk->i_frame_size = i_len + 2*4 * tk->i_frame_slice_count + 1;
545             tk->i_frame_num = i_frame_num;
546
547             if( tk->p_frame )
548                 block_Release( tk->p_frame );
549
550             tk->p_frame = block_Alloc( tk->i_frame_size );
551             if( !tk->p_frame )
552             {
553                 tk->i_frame_size = 0;
554                 return;
555             }
556
557             tk->p_frame->i_dts = i_dts;
558             tk->p_frame->i_pts = VLC_TS_INVALID;
559             if( i_flags & 0x02 )
560                 tk->p_frame->i_flags |= BLOCK_FLAG_TYPE_I;
561
562             i_dts = VLC_TS_INVALID;
563         }
564
565         int i_frame_data;
566         if( i_type == 3 )
567         {
568             i_frame_data = i_len;
569         }
570         else
571         {
572             i_frame_data = i_data;
573             if( i_type == 2 && i_frame_data > i_pos )
574                 i_frame_data = i_pos;
575         }
576         if( i_frame_data > i_data )
577             break;
578
579         /* */
580         tk->i_frame_slice++;
581         if( tk->i_frame_slice > tk->i_frame_slice_count || !tk->p_frame )
582             break;
583
584         /* */
585         SetDWLE( &tk->p_frame->p_buffer[2*4*(tk->i_frame_slice-1) + 1 + 0], 1 );
586         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) );
587
588         if( tk->i_frame_pos + i_frame_data > tk->i_frame_size )
589             break;
590
591         memcpy( &tk->p_frame->p_buffer[tk->i_frame_pos], p_data, i_frame_data );
592         RVoid( &p_data, &i_data, i_frame_data );
593         tk->i_frame_pos += i_frame_data;
594
595         if( i_type != 0 || tk->i_frame_pos >= tk->i_frame_size )
596         {
597             /* Fix the buffer once the real number of slice is known */
598             tk->p_frame->p_buffer[0] = tk->i_frame_slice - 1;
599             tk->p_frame->i_buffer = tk->i_frame_pos - 2*4*( tk->i_frame_slice_count - tk->i_frame_slice );
600
601             memmove( &tk->p_frame->p_buffer[1+2*4*tk->i_frame_slice      ],
602                      &tk->p_frame->p_buffer[1+2*4*tk->i_frame_slice_count],
603                      tk->i_frame_pos - (2*4*tk->i_frame_slice_count + 1) );
604
605             /* Send it */
606             CheckPcr( p_demux, tk, tk->p_frame->i_dts );
607             es_out_Send( p_demux->out, tk->p_es, tk->p_frame );
608
609             tk->i_frame_size = 0;
610             tk->p_frame = NULL;
611         }
612     }
613 }
614
615 static void DemuxAudioMethod1( demux_t *p_demux, real_track_t *tk, mtime_t i_pts, unsigned int i_flags )
616 {
617     demux_sys_t *p_sys = p_demux->p_sys;
618     uint8_t *p_buf = p_sys->buffer;
619
620     /* Sanity check */
621     if( (i_flags & 2) || p_sys->b_seek )
622     {
623         tk->i_subpacket = 0;
624         tk->i_out_subpacket = 0;
625         p_sys->b_seek = false;
626     }
627
628     if( tk->fmt.i_codec == VLC_CODEC_COOK ||
629         tk->fmt.i_codec == VLC_CODEC_ATRAC3 )
630     {
631         const int i_num = tk->i_frame_size / tk->i_subpacket_size;
632         const int y = tk->i_subpacket / ( tk->i_frame_size / tk->i_subpacket_size );
633
634         for( int i = 0; i < i_num; i++ )
635         {
636             int i_index = tk->i_subpacket_h * i +
637                           ((tk->i_subpacket_h + 1) / 2) * (y&1) + (y>>1);
638             if( i_index >= tk->i_subpackets )
639                 return;
640
641             block_t *p_block = block_Alloc( tk->i_subpacket_size );
642             if( !p_block )
643                 return;
644             if( &p_buf[tk->i_subpacket_size] > &p_sys->buffer[p_sys->i_buffer] )
645                 return;
646
647             memcpy( p_block->p_buffer, p_buf, tk->i_subpacket_size );
648             p_block->i_dts =
649             p_block->i_pts = VLC_TS_INVALID;
650
651             p_buf += tk->i_subpacket_size;
652
653             if( tk->p_subpackets[i_index] != NULL )
654             {
655                 msg_Dbg(p_demux, "p_subpackets[ %d ] not null!",  i_index );
656                 block_Release( tk->p_subpackets[i_index] );
657             }
658
659             tk->p_subpackets[i_index] = p_block;
660             if( tk->i_subpacket == 0 )
661                 tk->p_subpackets_timecode[0] = i_pts;
662             tk->i_subpacket++;
663         }
664     }
665     else
666     {
667         const int y = tk->i_subpacket / (tk->i_subpacket_h / 2);
668         assert( tk->fmt.i_codec == VLC_CODEC_RA_288 );
669
670         for( int i = 0; i < tk->i_subpacket_h / 2; i++ )
671         {
672             int i_index = (i * 2 * tk->i_frame_size / tk->i_coded_frame_size) + y;
673             if( i_index >= tk->i_subpackets )
674                 return;
675
676             block_t *p_block = block_Alloc( tk->i_coded_frame_size);
677             if( !p_block )
678                 return;
679             if( &p_buf[tk->i_coded_frame_size] > &p_sys->buffer[p_sys->i_buffer] )
680                 return;
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_Alloc( 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_Alloc( 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      || tk->i_sipr_subpacket_count >= tk->i_subpacket_h )
845         return;
846
847     if( !p_block )
848     {
849         p_block = block_Alloc( tk->i_frame_size * tk->i_subpacket_h );
850         if( !p_block )
851             return;
852         tk->p_sipr_packet = p_block;
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 = xcalloc( 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 = i_data - 26;
1381     fmt.p_extra = malloc( fmt.i_extra );
1382     if( !fmt.p_extra )
1383         return VLC_ENOMEM;
1384
1385     memcpy( fmt.p_extra, &p_data[26], fmt.i_extra );
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] = {0,0,0,0};
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         {
1486             es_format_Clean( &fmt );
1487             return VLC_EGENERIC;
1488         }
1489
1490         RVoid( &p_data, &i_data, 2 + (i_version == 5 ? 6 : 0 ) );
1491
1492         fmt.audio.i_rate = R16( &p_data, &i_data );
1493         RVoid( &p_data, &i_data, 2 );
1494         fmt.audio.i_bitspersample = R16( &p_data, &i_data );
1495         fmt.audio.i_channels = R16( &p_data, &i_data );
1496         fmt.audio.i_blockalign = i_frame_size;
1497
1498         if( i_version == 5 )
1499         {
1500             if( i_data >= 8 )
1501             {
1502                 memcpy( p_genr,       &p_data[0], 4 );
1503                 memcpy( &fmt.i_codec, &p_data[4], 4 );
1504             }
1505             RVoid( &p_data, &i_data, 8 );
1506         }
1507         else /* version 4 */
1508         {
1509             if( i_data > 0 )
1510                 RVoid( &p_data, &i_data, 1 + *p_data );
1511             if( i_data >= 1 + 4 )
1512                 memcpy( &fmt.i_codec, &p_data[1], 4 );
1513             if( i_data > 0 )
1514                 RVoid( &p_data, &i_data, 1 + *p_data );
1515         }
1516
1517         msg_Dbg( p_demux, "    - audio codec=%4.4s channels=%d rate=%dHz",
1518              (char*)&fmt.i_codec, fmt.audio.i_channels, fmt.audio.i_rate );
1519
1520         RVoid( &p_data, &i_data, 3 );
1521
1522         if( p_sys->b_real_audio )
1523         {
1524             CodecMetaRead( p_demux, &p_data, &i_data );
1525         }
1526         else
1527         {
1528             if( i_version == 5 )
1529                 RVoid( &p_data, &i_data, 1 );
1530             i_extra_codec = R32( &p_data, &i_data );
1531         }
1532     }
1533
1534     switch( fmt.i_codec )
1535     {
1536     case VLC_FOURCC('l','p','c','J'):
1537     case VLC_FOURCC('1','4','_','4'):
1538         fmt.i_codec = VLC_CODEC_RA_144;
1539         fmt.audio.i_blockalign = 0x14 ;
1540         break;
1541
1542     case VLC_FOURCC('2','8','_','8'):
1543         if( i_coded_frame_size <= 0 )
1544         {
1545             es_format_Clean( &fmt );
1546             return VLC_EGENERIC;
1547         }
1548         fmt.i_codec = VLC_CODEC_RA_288;
1549         fmt.audio.i_blockalign = i_coded_frame_size;
1550         break;
1551
1552     case VLC_FOURCC( 'a','5','2',' ' ):
1553     case VLC_FOURCC( 'd','n','e','t' ):
1554         fmt.i_codec = VLC_CODEC_A52;
1555         break;
1556
1557     case VLC_FOURCC( 'r','a','a','c' ):
1558     case VLC_FOURCC( 'r','a','c','p' ):
1559         fmt.i_codec = VLC_CODEC_MP4A;
1560
1561         if( i_extra_codec > 0 )
1562         {
1563             i_extra_codec--;
1564             RVoid( &p_data, &i_data, 1 );
1565         }
1566         if( i_extra_codec > 0 )
1567         {
1568             fmt.p_extra = malloc( i_extra_codec );
1569             if( !fmt.p_extra || i_extra_codec > i_data )
1570             {
1571                 free( fmt.p_extra );
1572                 return VLC_ENOMEM;
1573             }
1574
1575             fmt.i_extra = i_extra_codec;
1576             memcpy( fmt.p_extra, p_data, fmt.i_extra );
1577         }
1578         break;
1579
1580     case VLC_CODEC_SIPR:
1581         fmt.i_codec = VLC_CODEC_SIPR;
1582         if( i_flavor > 3 )
1583         {
1584             msg_Dbg( p_demux, "    - unsupported sipr flavorc=%i", i_flavor );
1585             es_format_Clean( &fmt );
1586             return VLC_EGENERIC;
1587         }
1588
1589         i_subpacket_size = i_subpacket_size_sipr[i_flavor];
1590         // The libavcodec sipr decoder requires stream bitrate
1591         // to be set during initialization so that the correct mode
1592         // can be selected.
1593         fmt.i_bitrate = fmt.audio.i_rate;
1594         msg_Dbg( p_demux, "    - sipr flavor=%i", i_flavor );
1595
1596     case VLC_CODEC_COOK:
1597     case VLC_CODEC_ATRAC3:
1598         if( i_subpacket_size <= 0 || i_frame_size / i_subpacket_size <= 0 )
1599         {
1600             es_format_Clean( &fmt );
1601             return VLC_EGENERIC;
1602         }
1603         if( !memcmp( p_genr, "genr", 4 ) )
1604             fmt.audio.i_blockalign = i_subpacket_size;
1605         else
1606             fmt.audio.i_blockalign = i_coded_frame_size;
1607
1608         if( i_extra_codec > 0 )
1609         {
1610             fmt.p_extra = malloc( i_extra_codec );
1611             if( !fmt.p_extra || i_extra_codec > i_data )
1612             {
1613                 free( fmt.p_extra );
1614                 return VLC_ENOMEM;
1615             }
1616
1617             fmt.i_extra = i_extra_codec;
1618             memcpy( fmt.p_extra, p_data, fmt.i_extra );
1619         }
1620
1621         break;
1622
1623     case VLC_FOURCC('r','a','l','f'):
1624     default:
1625         msg_Dbg( p_demux, "    - unknown audio codec=%4.4s",
1626                 (char*)&fmt.i_codec );
1627         es_format_Clean( &fmt );
1628         return VLC_EGENERIC;
1629         break;
1630     }
1631     msg_Dbg( p_demux, "    - extra data=%d", fmt.i_extra );
1632
1633     /* */
1634     real_track_t *tk = malloc( sizeof( *tk ) );
1635     if( !tk )
1636     {
1637         es_format_Clean( &fmt );
1638         return VLC_ENOMEM;
1639     }
1640     tk->i_id = i_tk_id;
1641     tk->fmt = fmt;
1642     tk->i_frame_size = 0;
1643     tk->p_frame = NULL;
1644
1645     tk->i_subpacket_h = i_subpacket_h;
1646     tk->i_subpacket_size = i_subpacket_size;
1647     tk->i_coded_frame_size = i_coded_frame_size;
1648     tk->i_frame_size = i_frame_size;
1649
1650     tk->i_out_subpacket = 0;
1651     tk->i_subpacket = 0;
1652     tk->i_subpackets = 0;
1653     tk->p_subpackets = NULL;
1654     tk->p_subpackets_timecode = NULL;
1655
1656     tk->p_sipr_packet          = NULL;
1657     tk->i_sipr_subpacket_count = 0;
1658
1659     if( fmt.i_codec == VLC_CODEC_COOK ||
1660         fmt.i_codec == VLC_CODEC_ATRAC3 )
1661     {
1662         tk->i_subpackets =
1663             i_subpacket_h * i_frame_size / tk->i_subpacket_size;
1664         tk->p_subpackets =
1665             xcalloc( tk->i_subpackets, sizeof(block_t *) );
1666         tk->p_subpackets_timecode =
1667             xcalloc( tk->i_subpackets , sizeof( int64_t ) );
1668     }
1669     else if( fmt.i_codec == VLC_CODEC_RA_288 )
1670     {
1671         tk->i_subpackets =
1672             i_subpacket_h * i_frame_size / tk->i_coded_frame_size;
1673         tk->p_subpackets =
1674             xcalloc( tk->i_subpackets, sizeof(block_t *) );
1675         tk->p_subpackets_timecode =
1676             xcalloc( tk->i_subpackets , sizeof( int64_t ) );
1677     }
1678
1679     /* Check if the calloc went correctly */
1680     if( tk->i_subpacket > 0 && ( !tk->p_subpackets || !tk->p_subpackets_timecode ) )
1681     {
1682         free( tk->p_subpackets_timecode );
1683         free( tk->p_subpackets );
1684         free( tk );
1685         msg_Err( p_demux, "Can't alloc subpacket" );
1686         return VLC_EGENERIC;
1687     }
1688
1689     tk->i_last_dts = 0;
1690     tk->p_es = es_out_Add( p_demux->out, &fmt );
1691
1692     TAB_APPEND( p_sys->i_track, p_sys->track, tk );
1693
1694     return VLC_SUCCESS;
1695 }
1696
1697
1698 static int CodecParse( demux_t *p_demux, int i_len, int i_num )
1699 {
1700     const uint8_t *p_peek;
1701
1702     msg_Dbg( p_demux, "    - specific data len=%d", i_len );
1703     if( stream_Peek( p_demux->s, &p_peek, i_len ) < i_len )
1704         return VLC_EGENERIC;
1705
1706     if( i_len >= 8 && !memcmp( &p_peek[4], "VIDO", 4 ) )
1707     {
1708         return CodecVideoParse( p_demux, i_num, p_peek, i_len );
1709     }
1710     else if( i_len >= 4 && !memcmp( &p_peek[0], ".ra\xfd", 4 ) )
1711     {
1712         return CodecAudioParse( p_demux, i_num, p_peek, i_len );
1713     }
1714     return VLC_SUCCESS;
1715 }
1716
1717 /*****************************************************************************
1718  * Helpers: memory buffer fct.
1719  *****************************************************************************/
1720 static void RVoid( const uint8_t **pp_data, int *pi_data, int i_size )
1721 {
1722     if( i_size > *pi_data )
1723         i_size = *pi_data;
1724
1725     *pp_data += i_size;
1726     *pi_data -= i_size;
1727 }
1728 #define RX(name, type, size, code ) \
1729 static type name( const uint8_t **pp_data, int *pi_data ) { \
1730     if( *pi_data < (size) )          \
1731         return 0;                    \
1732     type v = code;                   \
1733     RVoid( pp_data, pi_data, size ); \
1734     return v;                        \
1735 }
1736 RX(R8,  uint8_t, 1, **pp_data )
1737 RX(R16, uint16_t, 2, GetWBE( *pp_data ) )
1738 RX(R32, uint32_t, 4, GetDWBE( *pp_data ) )
1739 static int RLength( const uint8_t **pp_data, int *pi_data )
1740 {
1741     const int v0 = R16( pp_data, pi_data ) & 0x7FFF;
1742     if( v0 >= 0x4000 )
1743         return v0 - 0x4000;
1744     return (v0 << 16) | R16( pp_data, pi_data );
1745 }
1746
1747