]> git.sesse.net Git - vlc/blob - modules/codec/a52.c
f6521d558d50d2027991299e571a7e572da30a12
[vlc] / modules / codec / a52.c
1 /*****************************************************************************
2  * a52.c: parse A/52 audio sync info and packetize the stream
3  *****************************************************************************
4  * Copyright (C) 2001-2002 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Stéphane Borel <stef@via.ecp.fr>
8  *          Christophe Massiot <massiot@via.ecp.fr>
9  *          Gildas Bazin <gbazin@videolan.org>
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 2 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program; if not, write to the Free Software
23  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
24  *****************************************************************************/
25
26 /*****************************************************************************
27  * Preamble
28  *****************************************************************************/
29 #ifdef HAVE_CONFIG_H
30 # include "config.h"
31 #endif
32
33 #include <vlc_common.h>
34 #include <vlc_plugin.h>
35 #include <vlc_codec.h>
36 #include <vlc_aout.h>
37 #include <vlc_block_helper.h>
38 #include <vlc_bits.h>
39
40 /*****************************************************************************
41  * Module descriptor
42  *****************************************************************************/
43 static int  OpenDecoder   ( vlc_object_t * );
44 static int  OpenPacketizer( vlc_object_t * );
45 static void CloseCommon   ( vlc_object_t * );
46
47 vlc_module_begin();
48     set_description( N_("A/52 parser") );
49     set_capability( "decoder", 100 );
50     set_callbacks( OpenDecoder, CloseCommon );
51     set_category( CAT_INPUT );
52     set_subcategory( SUBCAT_INPUT_ACODEC );
53
54     add_submodule();
55     set_description( N_("A/52 audio packetizer") );
56     set_capability( "packetizer", 10 );
57     set_callbacks( OpenPacketizer, CloseCommon );
58 vlc_module_end();
59
60 /*****************************************************************************
61  * decoder_sys_t : decoder descriptor
62  *****************************************************************************/
63
64 #define A52_HEADER_SIZE 7
65
66 struct decoder_sys_t
67 {
68     /* Module mode */
69     bool b_packetizer;
70
71     /*
72      * Input properties
73      */
74     int i_state;
75
76     block_bytestream_t bytestream;
77
78     /*
79      * Common properties
80      */
81     audio_date_t   end_date;
82
83     mtime_t i_pts;
84     int i_frame_size, i_bit_rate;
85     unsigned int i_rate, i_channels, i_channels_conf;
86 };
87
88 enum {
89
90     STATE_NOSYNC,
91     STATE_SYNC,
92     STATE_HEADER,
93     STATE_NEXT_SYNC,
94     STATE_GET_DATA,
95     STATE_SEND_DATA
96 };
97
98 /****************************************************************************
99  * Local prototypes
100  ****************************************************************************/
101 static void *DecodeBlock  ( decoder_t *, block_t ** );
102
103 static int  SyncInfo      ( const uint8_t *, unsigned int *, unsigned int *,
104                             unsigned int *, int * );
105
106 static uint8_t       *GetOutBuffer ( decoder_t *, void ** );
107 static aout_buffer_t *GetAoutBuffer( decoder_t * );
108 static block_t       *GetSoutBuffer( decoder_t * );
109
110 /*****************************************************************************
111  * OpenCommon: probe the decoder/packetizer and return score
112  *****************************************************************************/
113 static int OpenCommon( vlc_object_t *p_this, bool b_packetizer )
114 {
115     decoder_t *p_dec = (decoder_t*)p_this;
116     decoder_sys_t *p_sys;
117     vlc_fourcc_t i_codec;
118
119     switch( p_dec->fmt_in.i_codec )
120     {
121     case VLC_FOURCC('a','5','2',' '):
122     case VLC_FOURCC('a','5','2','b'):
123         i_codec = VLC_FOURCC('a','5','2',' ');
124         break;
125     case VLC_FOURCC('e','a','c','3'):
126         /* XXX ugly hack, a52 does not support eac3 so no eac3 pass-through
127          * support */
128         if( !b_packetizer )
129             return VLC_EGENERIC;
130         i_codec = VLC_FOURCC('e','a','c','3');
131         break;
132     default:
133         return VLC_EGENERIC;
134     }
135
136     /* Allocate the memory needed to store the decoder's structure */
137     if( ( p_dec->p_sys = p_sys =
138           (decoder_sys_t *)malloc(sizeof(decoder_sys_t)) ) == NULL )
139         return VLC_ENOMEM;
140
141     /* Misc init */
142     p_sys->b_packetizer = b_packetizer;
143     p_sys->i_state = STATE_NOSYNC;
144     aout_DateSet( &p_sys->end_date, 0 );
145
146     p_sys->bytestream = block_BytestreamInit();
147
148     /* Set output properties */
149     p_dec->fmt_out.i_cat = AUDIO_ES;
150     p_dec->fmt_out.i_codec = i_codec;
151     p_dec->fmt_out.audio.i_rate = 0; /* So end_date gets initialized */
152
153     /* Set callback */
154     if( b_packetizer )
155         p_dec->pf_packetize    = (block_t *(*)(decoder_t *, block_t **))
156             DecodeBlock;
157     else
158         p_dec->pf_decode_audio = (aout_buffer_t *(*)(decoder_t *, block_t **))
159             DecodeBlock;
160     return VLC_SUCCESS;
161 }
162
163 static int OpenDecoder( vlc_object_t *p_this )
164 {
165     return OpenCommon( p_this, false );
166 }
167
168 static int OpenPacketizer( vlc_object_t *p_this )
169 {
170     return OpenCommon( p_this, true );
171 }
172
173 /****************************************************************************
174  * DecodeBlock: the whole thing
175  ****************************************************************************
176  * This function is called just after the thread is launched.
177  ****************************************************************************/
178 static void *DecodeBlock( decoder_t *p_dec, block_t **pp_block )
179 {
180     decoder_sys_t *p_sys = p_dec->p_sys;
181     uint8_t p_header[A52_HEADER_SIZE];
182     uint8_t *p_buf;
183     void *p_out_buffer;
184
185     if( !pp_block || !*pp_block ) return NULL;
186
187     if( (*pp_block)->i_flags&(BLOCK_FLAG_DISCONTINUITY|BLOCK_FLAG_CORRUPTED) )
188     {
189         if( (*pp_block)->i_flags&BLOCK_FLAG_CORRUPTED )
190         {
191             p_sys->i_state = STATE_NOSYNC;
192             block_BytestreamFlush( &p_sys->bytestream );
193         }
194 //        aout_DateSet( &p_sys->end_date, 0 );
195         block_Release( *pp_block );
196         return NULL;
197     }
198
199     if( !aout_DateGet( &p_sys->end_date ) && !(*pp_block)->i_pts )
200     {
201         /* We've just started the stream, wait for the first PTS. */
202         block_Release( *pp_block );
203         return NULL;
204     }
205
206     block_BytestreamPush( &p_sys->bytestream, *pp_block );
207
208     while( 1 )
209     {
210         switch( p_sys->i_state )
211         {
212         case STATE_NOSYNC:
213             while( block_PeekBytes( &p_sys->bytestream, p_header, 2 )
214                    == VLC_SUCCESS )
215             {
216                 if( p_header[0] == 0x0b && p_header[1] == 0x77 )
217                 {
218                     p_sys->i_state = STATE_SYNC;
219                     break;
220                 }
221                 block_SkipByte( &p_sys->bytestream );
222             }
223             if( p_sys->i_state != STATE_SYNC )
224             {
225                 block_BytestreamFlush( &p_sys->bytestream );
226
227                 /* Need more data */
228                 return NULL;
229             }
230
231         case STATE_SYNC:
232             /* New frame, set the Presentation Time Stamp */
233             p_sys->i_pts = p_sys->bytestream.p_block->i_pts;
234             if( p_sys->i_pts != 0 &&
235                 p_sys->i_pts != aout_DateGet( &p_sys->end_date ) )
236             {
237                 aout_DateSet( &p_sys->end_date, p_sys->i_pts );
238             }
239             p_sys->i_state = STATE_HEADER;
240
241         case STATE_HEADER:
242             /* Get A/52 frame header (A52_HEADER_SIZE bytes) */
243             if( block_PeekBytes( &p_sys->bytestream, p_header,
244                                  A52_HEADER_SIZE ) != VLC_SUCCESS )
245             {
246                 /* Need more data */
247                 return NULL;
248             }
249
250             /* Check if frame is valid and get frame info */
251             p_sys->i_frame_size = SyncInfo( p_header,
252                                             &p_sys->i_channels,
253                                             &p_sys->i_channels_conf,
254                                             &p_sys->i_rate,
255                                             &p_sys->i_bit_rate );
256             if( !p_sys->i_frame_size )
257             {
258                 msg_Dbg( p_dec, "emulated sync word" );
259                 block_SkipByte( &p_sys->bytestream );
260                 p_sys->i_state = STATE_NOSYNC;
261                 break;
262             }
263             p_sys->i_state = STATE_NEXT_SYNC;
264
265         case STATE_NEXT_SYNC:
266             /* TODO: If pp_block == NULL, flush the buffer without checking the
267              * next sync word */
268
269             /* Check if next expected frame contains the sync word */
270             if( block_PeekOffsetBytes( &p_sys->bytestream,
271                                        p_sys->i_frame_size, p_header, 2 )
272                 != VLC_SUCCESS )
273             {
274                 /* Need more data */
275                 return NULL;
276             }
277
278             if( p_sys->b_packetizer &&
279                 p_header[0] == 0 && p_header[1] == 0 )
280             {
281                 /* A52 wav files and audio CD's use stuffing */
282                 p_sys->i_state = STATE_GET_DATA;
283                 break;
284             }
285
286             if( p_header[0] != 0x0b || p_header[1] != 0x77 )
287             {
288                 msg_Dbg( p_dec, "emulated sync word "
289                          "(no sync on following frame)" );
290                 p_sys->i_state = STATE_NOSYNC;
291                 block_SkipByte( &p_sys->bytestream );
292                 break;
293             }
294             p_sys->i_state = STATE_SEND_DATA;
295             break;
296
297         case STATE_GET_DATA:
298             /* Make sure we have enough data.
299              * (Not useful if we went through NEXT_SYNC) */
300             if( block_WaitBytes( &p_sys->bytestream,
301                                  p_sys->i_frame_size ) != VLC_SUCCESS )
302             {
303                 /* Need more data */
304                 return NULL;
305             }
306             p_sys->i_state = STATE_SEND_DATA;
307
308         case STATE_SEND_DATA:
309             if( !(p_buf = GetOutBuffer( p_dec, &p_out_buffer )) )
310             {
311                 //p_dec->b_error = true;
312                 return NULL;
313             }
314
315             /* Copy the whole frame into the buffer. When we reach this point
316              * we already know we have enough data available. */
317             block_GetBytes( &p_sys->bytestream, p_buf, p_sys->i_frame_size );
318
319             /* Make sure we don't reuse the same pts twice */
320             if( p_sys->i_pts == p_sys->bytestream.p_block->i_pts )
321                 p_sys->i_pts = p_sys->bytestream.p_block->i_pts = 0;
322
323             /* So p_block doesn't get re-added several times */
324             *pp_block = block_BytestreamPop( &p_sys->bytestream );
325
326             p_sys->i_state = STATE_NOSYNC;
327
328             return p_out_buffer;
329         }
330     }
331
332     return NULL;
333 }
334
335 /*****************************************************************************
336  * CloseCommon: clean up the decoder
337  *****************************************************************************/
338 static void CloseCommon( vlc_object_t *p_this )
339 {
340     decoder_t *p_dec = (decoder_t*)p_this;
341     decoder_sys_t *p_sys = p_dec->p_sys;
342
343     block_BytestreamRelease( &p_sys->bytestream );
344
345     free( p_sys );
346 }
347
348 /*****************************************************************************
349  * GetOutBuffer:
350  *****************************************************************************/
351 static uint8_t *GetOutBuffer( decoder_t *p_dec, void **pp_out_buffer )
352 {
353     decoder_sys_t *p_sys = p_dec->p_sys;
354     uint8_t *p_buf;
355
356     if( p_dec->fmt_out.audio.i_rate != p_sys->i_rate )
357     {
358         msg_Info( p_dec, "A/52 channels:%d samplerate:%d bitrate:%d",
359                   p_sys->i_channels, p_sys->i_rate, p_sys->i_bit_rate );
360
361         aout_DateInit( &p_sys->end_date, p_sys->i_rate );
362         aout_DateSet( &p_sys->end_date, p_sys->i_pts );
363     }
364
365     p_dec->fmt_out.audio.i_rate     = p_sys->i_rate;
366     p_dec->fmt_out.audio.i_channels = p_sys->i_channels;
367     p_dec->fmt_out.audio.i_bytes_per_frame = p_sys->i_frame_size;
368     p_dec->fmt_out.audio.i_frame_length = A52_FRAME_NB;
369
370     p_dec->fmt_out.audio.i_original_channels = p_sys->i_channels_conf;
371     p_dec->fmt_out.audio.i_physical_channels =
372         p_sys->i_channels_conf & AOUT_CHAN_PHYSMASK;
373
374     p_dec->fmt_out.i_bitrate = p_sys->i_bit_rate;
375
376     if( p_sys->b_packetizer )
377     {
378         block_t *p_sout_buffer = GetSoutBuffer( p_dec );
379         p_buf = p_sout_buffer ? p_sout_buffer->p_buffer : NULL;
380         *pp_out_buffer = p_sout_buffer;
381     }
382     else
383     {
384         aout_buffer_t *p_aout_buffer = GetAoutBuffer( p_dec );
385         p_buf = p_aout_buffer ? p_aout_buffer->p_buffer : NULL;
386         *pp_out_buffer = p_aout_buffer;
387     }
388
389     return p_buf;
390 }
391
392 /*****************************************************************************
393  * GetAoutBuffer:
394  *****************************************************************************/
395 static aout_buffer_t *GetAoutBuffer( decoder_t *p_dec )
396 {
397     decoder_sys_t *p_sys = p_dec->p_sys;
398     aout_buffer_t *p_buf;
399
400     p_buf = p_dec->pf_aout_buffer_new( p_dec, A52_FRAME_NB  );
401     if( p_buf == NULL ) return NULL;
402
403     p_buf->start_date = aout_DateGet( &p_sys->end_date );
404     p_buf->end_date = aout_DateIncrement( &p_sys->end_date, A52_FRAME_NB );
405
406     return p_buf;
407 }
408
409 /*****************************************************************************
410  * GetSoutBuffer:
411  *****************************************************************************/
412 static block_t *GetSoutBuffer( decoder_t *p_dec )
413 {
414     decoder_sys_t *p_sys = p_dec->p_sys;
415     block_t *p_block;
416
417     p_block = block_New( p_dec, p_sys->i_frame_size );
418     if( p_block == NULL ) return NULL;
419
420     p_block->i_pts = p_block->i_dts = aout_DateGet( &p_sys->end_date );
421
422     p_block->i_length =
423         aout_DateIncrement( &p_sys->end_date, A52_FRAME_NB ) - p_block->i_pts;
424
425     return p_block;
426 }
427
428 /* Tables */
429 static const struct
430 {
431     unsigned int i_count;
432     unsigned int i_configuration;
433 } p_acmod[8] = {
434     { 2, AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_DUALMONO },   /* Dual-channel 1+1 */
435     { 1, AOUT_CHAN_CENTER },                                        /* Mono 1/0 */
436     { 2, AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT },                        /* Stereo 2/0 */
437     { 3, AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_CENTER },     /* 3F 3/0 */
438     { 3, AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_REARCENTER }, /* 2F1R 2/1 */
439     { 4, AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_CENTER |
440          AOUT_CHAN_REARCENTER },                                    /* 3F1R 3/1 */
441     { 5, AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT |
442          AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT },                /* 2F2R 2/2 */
443     { 6, AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_CENTER |
444          AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT },                /* 3F2R 3/2 */
445 };
446
447 /**
448  * It parse AC3 sync info.
449  *
450  * This code is borrowed from liba52 by Aaron Holtzman & Michel Lespinasse,
451  * since we don't want to oblige S/PDIF people to use liba52 just to get
452  * their SyncInfo...
453  */
454 static int SyncInfoAC3( const uint8_t *p_buf,
455                         unsigned int *pi_channels,
456                         unsigned int *pi_channels_conf,
457                         unsigned int *pi_sample_rate, int *pi_bit_rate )
458 {
459     static const uint8_t halfrate[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3 };
460     static const int rate[] = { 32,  40,  48,  56,  64,  80,  96, 112,
461                                 128, 160, 192, 224, 256, 320, 384, 448,
462                                 512, 576, 640 };
463     static const uint8_t lfeon[8] = { 0x10, 0x10, 0x04, 0x04,
464                                       0x04, 0x01, 0x04, 0x01 };
465     int frmsizecod;
466     int bitrate;
467     int half;
468     int acmod;
469
470     /* */
471     half = halfrate[p_buf[5] >> 3];
472
473     /* acmod, dsurmod and lfeon */
474     acmod = p_buf[6] >> 5;
475     if ( (p_buf[6] & 0xf8) == 0x50 )
476     {
477         /* Dolby surround = stereo + Dolby */
478         *pi_channels = 2;
479         *pi_channels_conf = AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT
480                             | AOUT_CHAN_DOLBYSTEREO;
481     }
482     else
483     {
484         *pi_channels      = p_acmod[acmod].i_count;
485         *pi_channels_conf = p_acmod[acmod].i_configuration;
486     }
487
488     if ( p_buf[6] & lfeon[acmod] )
489     {
490         (*pi_channels)++;
491         *pi_channels_conf |= AOUT_CHAN_LFE;
492     }
493
494     frmsizecod = p_buf[4] & 63;
495     if (frmsizecod >= 38)
496         return 0;
497     bitrate = rate [frmsizecod >> 1];
498     *pi_bit_rate = (bitrate * 1000) >> half;
499
500     switch (p_buf[4] & 0xc0) {
501     case 0:
502         *pi_sample_rate = 48000 >> half;
503         return 4 * bitrate;
504     case 0x40:
505         *pi_sample_rate = 44100 >> half;
506         return 2 * (320 * bitrate / 147 + (frmsizecod & 1));
507     case 0x80:
508         *pi_sample_rate = 32000 >> half;
509         return 6 * bitrate;
510     default:
511         return 0;
512     }
513 }
514
515 /**
516  * It parse E-AC3 sync info
517  */
518 static int SyncInfoEAC3( const uint8_t *p_buf,
519                          unsigned int *pi_channels,
520                          unsigned int *pi_channels_conf,
521                          unsigned int *pi_sample_rate, int *pi_bit_rate )
522 {
523     static const int pi_samplerate[3] = { 48000, 44100, 32000 };
524     bs_t s;
525     int i_frame_size;
526     int i_fscod, i_fscod2;
527     int i_numblkscod;
528     int i_acmod, i_lfeon;
529     int i_bytes;
530
531
532     bs_init( &s, (void*)p_buf, A52_HEADER_SIZE );
533     bs_skip( &s, 16 +   /* start code */
534                  2 +    /* stream type */
535                  3 );   /* substream id */
536     i_frame_size = bs_read( &s, 11 );
537     if( i_frame_size < 2 )
538         return 0;
539     i_bytes = 2 * ( i_frame_size + 1 );
540
541     i_fscod = bs_read( &s, 2 );
542     if( i_fscod == 0x03 )
543     {
544         i_fscod2 = bs_read( &s, 2 );
545         if( i_fscod2 == 0X03 )
546             return 0;
547         *pi_sample_rate = pi_samplerate[i_fscod2] / 2;
548         i_numblkscod = 6;
549     }
550     else
551     {
552         static const int pi_blocks[4] = { 1, 2, 3, 6 };
553
554         *pi_sample_rate = pi_samplerate[i_fscod];
555         i_numblkscod = pi_blocks[bs_read( &s, 2 )];
556     }
557
558     i_acmod = bs_read( &s, 3 );
559     i_lfeon = bs_read1( &s );
560
561     *pi_channels      = p_acmod[i_acmod].i_count + i_lfeon;
562     *pi_channels_conf = p_acmod[i_acmod].i_configuration | ( i_lfeon ? AOUT_CHAN_LFE : 0);
563     *pi_bit_rate = 8 * i_bytes * (*pi_sample_rate) / (i_numblkscod * 256);
564
565     return i_bytes;
566 }
567
568 static int SyncInfo( const uint8_t *p_buf,
569                      unsigned int *pi_channels,
570                      unsigned int *pi_channels_conf,
571                      unsigned int *pi_sample_rate, int *pi_bit_rate )
572 {
573     int bsid;
574
575     /* Check synword */
576     if( p_buf[0] != 0x0b || p_buf[1] != 0x77 )
577         return 0;
578
579     /* Check bsid */
580     bsid = p_buf[5] >> 3;
581     if( bsid > 16 )
582         return 0;
583
584     if( bsid <= 10 )
585         return SyncInfoAC3( p_buf, pi_channels, pi_channels_conf,
586                             pi_sample_rate, pi_bit_rate );
587     else
588         return SyncInfoEAC3( p_buf, pi_channels, pi_channels_conf,
589                              pi_sample_rate, pi_bit_rate );
590 }
591