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