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