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