]> git.sesse.net Git - vlc/blob - modules/codec/flac.c
Marginally better
[vlc] / modules / codec / flac.c
1 /*****************************************************************************
2  * flac.c: flac decoder/packetizer/encoder module making use of libflac
3  *****************************************************************************
4  * Copyright (C) 1999-2001 VideoLAN
5  * $Id: flac.c,v 1.6 2003/12/04 22:37:02 gbazin Exp $
6  *
7  * Authors: Gildas Bazin <gbazin@netcourrier.com>
8  *          Sigmund Augdal <sigmunau@idi.ntnu.no>
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
23  *****************************************************************************/
24
25 /*****************************************************************************
26  * Preamble
27  *****************************************************************************/
28
29 #include <vlc/vlc.h>
30 #include <vlc/decoder.h>
31
32 #include <FLAC/stream_decoder.h>
33 #include <FLAC/stream_encoder.h>
34
35 #include "vlc_block_helper.h"
36
37 #define MAX_FLAC_HEADER_SIZE 16
38
39 /*****************************************************************************
40  * decoder_sys_t : FLAC decoder descriptor
41  *****************************************************************************/
42 struct decoder_sys_t
43 {
44     /*
45      * Input properties
46      */
47     int i_state;
48
49     block_bytestream_t bytestream;
50
51     /*
52      * Input/Output properties
53      */
54     block_t *p_block;
55     aout_buffer_t *p_aout_buffer;
56
57     /*
58      * FLAC properties
59      */
60     FLAC__StreamDecoder *p_flac;
61
62     vlc_bool_t b_stream_info;
63     FLAC__StreamMetadata_StreamInfo stream_info;
64
65     /*
66      * Common properties
67      */
68     audio_date_t end_date;
69     mtime_t i_pts;
70
71     int i_frame_size, i_frame_length, i_bits_per_sample;
72     unsigned int i_rate, i_channels, i_channels_conf;
73 };
74
75 enum {
76
77     STATE_NOSYNC,
78     STATE_SYNC,
79     STATE_HEADER,
80     STATE_NEXT_SYNC,
81     STATE_GET_DATA,
82     STATE_SEND_DATA
83 };
84
85 static int pi_channels_maps[6] =
86 {
87     0,
88     AOUT_CHAN_CENTER,
89     AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT,
90     AOUT_CHAN_CENTER | AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT,
91     AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_REARLEFT
92      | AOUT_CHAN_REARRIGHT,
93     AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_CENTER
94      | AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT
95 };
96
97 /*****************************************************************************
98  * Local prototypes
99  *****************************************************************************/
100 static int  OpenDecoder   ( vlc_object_t * );
101 static int  OpenPacketizer( vlc_object_t * );
102 static void CloseDecoder  ( vlc_object_t * );
103
104 static int OpenEncoder   ( vlc_object_t * );
105 static void CloseEncoder ( vlc_object_t * );
106
107 static aout_buffer_t *DecodeBlock( decoder_t *, block_t ** );
108 static block_t *PacketizeBlock( decoder_t *, block_t ** );
109
110 static int SyncInfo( decoder_t *, uint8_t *, int *, int *, int *,int * );
111
112
113 static FLAC__StreamDecoderReadStatus
114 DecoderReadCallback( const FLAC__StreamDecoder *decoder,
115                      FLAC__byte buffer[], unsigned *bytes, void *client_data );
116
117 static FLAC__StreamDecoderWriteStatus
118 DecoderWriteCallback( const FLAC__StreamDecoder *decoder,
119                       const FLAC__Frame *frame,
120                       const FLAC__int32 *const buffer[], void *client_data );
121
122 static void DecoderMetadataCallback( const FLAC__StreamDecoder *decoder,
123                                      const FLAC__StreamMetadata *metadata,
124                                      void *client_data );
125 static void DecoderErrorCallback( const FLAC__StreamDecoder *decoder,
126                                   FLAC__StreamDecoderErrorStatus status,
127                                   void *client_data);
128
129 static void Interleave32( int32_t *p_out, const int32_t * const *pp_in,
130                           int i_nb_channels, int i_samples );
131 static void Interleave16( int16_t *p_out, const int32_t * const *pp_in,
132                           int i_nb_channels, int i_samples );
133
134 static void decoder_state_error( decoder_t *p_dec,
135                                  FLAC__StreamDecoderState state );
136
137 static uint64_t read_utf8( const uint8_t *p_buf, int *pi_read );
138 static uint8_t flac_crc8( const uint8_t *data, unsigned len );
139
140 /*****************************************************************************
141  * Module descriptor
142  *****************************************************************************/
143 vlc_module_begin();
144
145     set_description( _("Flac audio decoder") );
146     set_capability( "decoder", 100 );
147     set_callbacks( OpenDecoder, CloseDecoder );
148
149     add_submodule();
150     set_description( _("Flac audio packetizer") );
151     set_capability( "packetizer", 100 );
152     set_callbacks( OpenPacketizer, CloseDecoder );
153
154     add_submodule();
155     set_description( _("Flac audio encoder") );
156     set_capability( "encoder", 100 );
157     set_callbacks( OpenEncoder, CloseEncoder );
158
159 vlc_module_end();
160
161 /*****************************************************************************
162  * OpenDecoder: probe the decoder and return score
163  *****************************************************************************/
164 static int OpenDecoder( vlc_object_t *p_this )
165 {
166     decoder_t *p_dec = (decoder_t*)p_this;
167     decoder_sys_t *p_sys;
168
169     if( p_dec->fmt_in.i_codec != VLC_FOURCC('f','l','a','c') )
170     {
171         return VLC_EGENERIC;
172     }
173
174     /* Allocate the memory needed to store the decoder's structure */
175     if( ( p_dec->p_sys = p_sys =
176           (decoder_sys_t *)malloc(sizeof(decoder_sys_t)) ) == NULL )
177     {
178         msg_Err( p_dec, "out of memory" );
179         return VLC_EGENERIC;
180     }
181
182     /* Misc init */
183     aout_DateSet( &p_sys->end_date, 0 );
184     p_sys->i_state = STATE_NOSYNC;
185     p_sys->b_stream_info = VLC_FALSE;
186
187     p_sys->bytestream = block_BytestreamInit( p_dec );
188
189     /* Take care of flac init */
190     if( !(p_sys->p_flac = FLAC__stream_decoder_new()) )
191     {
192         msg_Err( p_dec, "FLAC__stream_decoder_new() failed" );
193         free( p_sys );
194         return VLC_EGENERIC;
195     }
196
197     FLAC__stream_decoder_set_read_callback( p_sys->p_flac,
198                                             DecoderReadCallback );
199     FLAC__stream_decoder_set_write_callback( p_sys->p_flac,
200                                              DecoderWriteCallback );
201     FLAC__stream_decoder_set_metadata_callback( p_sys->p_flac,
202                                                 DecoderMetadataCallback );
203     FLAC__stream_decoder_set_error_callback( p_sys->p_flac,
204                                              DecoderErrorCallback );
205     FLAC__stream_decoder_set_client_data( p_sys->p_flac, p_dec );
206
207     FLAC__stream_decoder_init( p_sys->p_flac );
208
209     /* Set output properties */
210     p_dec->fmt_out.i_cat = AUDIO_ES;
211     p_dec->fmt_out.i_codec = VLC_FOURCC('f','l','3','2');
212
213     /* Set callbacks */
214     p_dec->pf_decode_audio = DecodeBlock;
215     p_dec->pf_packetize    = PacketizeBlock;
216
217     /* Decode STREAMINFO */
218     msg_Dbg( p_dec, "decode STREAMINFO" );
219     p_sys->p_block = block_New( p_dec, p_dec->fmt_in.i_extra );
220     memcpy( p_sys->p_block->p_buffer, p_dec->fmt_in.p_extra,
221             p_dec->fmt_in.i_extra );
222     FLAC__stream_decoder_process_until_end_of_metadata( p_sys->p_flac );
223     msg_Dbg( p_dec, "STREAMINFO decoded" );
224
225     return VLC_SUCCESS;
226 }
227
228 static int OpenPacketizer( vlc_object_t *p_this )
229 {
230     decoder_t *p_dec = (decoder_t*)p_this;
231
232     int i_ret = OpenDecoder( p_this );
233
234     if( i_ret != VLC_SUCCESS ) return i_ret;
235
236     es_format_Copy( &p_dec->fmt_out, &p_dec->fmt_in );
237
238     return i_ret;
239 }
240
241 /****************************************************************************
242  * PacketizeBlock: the whole thing
243  ****************************************************************************
244  * This function is called just after the thread is launched.
245  ****************************************************************************/
246 static block_t *PacketizeBlock( decoder_t *p_dec, block_t **pp_block )
247 {
248     decoder_sys_t *p_sys = p_dec->p_sys;
249     uint8_t p_header[MAX_FLAC_HEADER_SIZE];
250     block_t *p_sout_block;
251
252     if( !pp_block || !*pp_block ) return NULL;
253
254     if( !aout_DateGet( &p_sys->end_date ) && !(*pp_block)->i_pts )
255     {
256         /* We've just started the stream, wait for the first PTS. */
257         block_Release( *pp_block );
258         return NULL;
259     }
260
261     if( (*pp_block)->b_discontinuity )
262     {
263         p_sys->i_state = STATE_NOSYNC;
264     }
265
266     block_BytestreamPush( &p_sys->bytestream, *pp_block );
267
268     while( 1 )
269     {
270         switch( p_sys->i_state )
271         {
272         case STATE_NOSYNC:
273             while( block_PeekBytes( &p_sys->bytestream, p_header, 2 )
274                    == VLC_SUCCESS )
275             {
276                 if( p_header[0] == 0xFF && p_header[1] == 0xF8 )
277                 {
278                     p_sys->i_state = STATE_SYNC;
279                     break;
280                 }
281                 block_SkipByte( &p_sys->bytestream );
282             }
283             if( p_sys->i_state != STATE_SYNC )
284             {
285                 block_BytestreamFlush( &p_sys->bytestream );
286
287                 /* Need more data */
288                 return NULL;
289             }
290
291         case STATE_SYNC:
292             /* New frame, set the Presentation Time Stamp */
293             p_sys->i_pts = p_sys->bytestream.p_block->i_pts;
294             if( p_sys->i_pts != 0 &&
295                 p_sys->i_pts != aout_DateGet( &p_sys->end_date ) )
296             {
297                 aout_DateSet( &p_sys->end_date, p_sys->i_pts );
298             }
299             p_sys->i_state = STATE_HEADER;
300
301         case STATE_HEADER:
302             /* Get FLAC frame header (MAX_FLAC_HEADER_SIZE bytes) */
303             if( block_PeekBytes( &p_sys->bytestream, p_header,
304                                  MAX_FLAC_HEADER_SIZE ) != VLC_SUCCESS )
305             {
306                 /* Need more data */
307                 return NULL;
308             }
309
310             /* Check if frame is valid and get frame info */
311             p_sys->i_frame_length = SyncInfo( p_dec, p_header,
312                                               &p_sys->i_channels,
313                                               &p_sys->i_channels_conf,
314                                               &p_sys->i_rate,
315                                               &p_sys->i_bits_per_sample );
316             if( !p_sys->i_frame_length )
317             {
318                 msg_Dbg( p_dec, "emulated sync word" );
319                 block_SkipByte( &p_sys->bytestream );
320                 p_sys->i_state = STATE_NOSYNC;
321                 break;
322             }
323             if( p_sys->i_rate != p_dec->fmt_out.audio.i_rate )
324             {
325                 p_dec->fmt_out.audio.i_rate = p_sys->i_rate;
326                 aout_DateInit( &p_sys->end_date, p_sys->i_rate );
327                 p_dec->fmt_out.audio.i_rate = p_sys->i_rate;
328             }
329             p_sys->i_state = STATE_NEXT_SYNC;
330             p_sys->i_frame_size = 1;
331
332         case STATE_NEXT_SYNC:
333             /* TODO: If pp_block == NULL, flush the buffer without checking the
334              * next sync word */
335
336             /* Check if next expected frame contains the sync word */
337             while( block_PeekOffsetBytes( &p_sys->bytestream,
338                                           p_sys->i_frame_size, p_header,
339                                           MAX_FLAC_HEADER_SIZE )
340                    == VLC_SUCCESS )
341             {
342                 if( p_header[0] == 0xFF && p_header[1] == 0xF8 )
343                 {
344                     /* Check if frame is valid and get frame info */
345                     int i_frame_length =
346                         SyncInfo( p_dec, p_header,
347                                   &p_sys->i_channels,
348                                   &p_sys->i_channels_conf,
349                                   &p_sys->i_rate,
350                                   &p_sys->i_bits_per_sample );
351
352                     if( i_frame_length )
353                     {
354                         p_sys->i_state = STATE_SEND_DATA;
355                         break;
356                     }
357                 }
358                 p_sys->i_frame_size++;
359             }
360
361             if( p_sys->i_state != STATE_SEND_DATA )
362             {
363                 /* Need more data */
364                 return NULL;
365             }
366             break;
367
368         case STATE_SEND_DATA:
369             p_sout_block = block_New( p_dec, p_sys->i_frame_size );
370
371             /* Copy the whole frame into the buffer. When we reach this point
372              * we already know we have enough data available. */
373             block_GetBytes( &p_sys->bytestream, p_sout_block->p_buffer,
374                             p_sys->i_frame_size );
375
376             /* Make sure we don't reuse the same pts twice */
377             if( p_sys->i_pts == p_sys->bytestream.p_block->i_pts )
378                 p_sys->i_pts = p_sys->bytestream.p_block->i_pts = 0;
379
380             /* So p_block doesn't get re-added several times */
381             *pp_block = block_BytestreamPop( &p_sys->bytestream );
382
383             p_sys->i_state = STATE_NOSYNC;
384
385             /* Date management */
386             p_sout_block->i_pts =
387                 p_sout_block->i_dts = aout_DateGet( &p_sys->end_date );
388             aout_DateIncrement( &p_sys->end_date, p_sys->i_frame_length );
389             p_sout_block->i_length =
390                 aout_DateGet( &p_sys->end_date ) - p_sout_block->i_pts;
391
392             return p_sout_block;
393         }
394     }
395
396     return NULL;
397 }
398
399 /****************************************************************************
400  * DecodeBlock: the whole thing
401  ****************************************************************************/
402 static aout_buffer_t *DecodeBlock( decoder_t *p_dec, block_t **pp_block )
403 {
404     decoder_sys_t *p_sys = p_dec->p_sys;
405
406     if( !pp_block || !*pp_block ) return NULL;
407
408     p_sys->p_aout_buffer = 0;
409     if( ( p_sys->p_block = PacketizeBlock( p_dec, pp_block ) ) )
410     {
411         if( !FLAC__stream_decoder_process_single( p_sys->p_flac ) )
412         {
413             decoder_state_error( p_dec,
414                 FLAC__stream_decoder_get_state( p_sys->p_flac ) );
415             FLAC__stream_decoder_flush( p_dec->p_sys->p_flac );
416         }
417
418         /* If the decoder is in the "aborted" state,
419          * FLAC__stream_decoder_process_single() won't return an error. */
420         if( FLAC__stream_decoder_get_state(p_dec->p_sys->p_flac)
421             == FLAC__STREAM_DECODER_ABORTED )
422         {
423             FLAC__stream_decoder_flush( p_dec->p_sys->p_flac );
424         }
425
426         block_Release( p_sys->p_block );
427     }
428
429     return p_sys->p_aout_buffer;
430 }
431
432 /*****************************************************************************
433  * CloseDecoder: flac decoder destruction
434  *****************************************************************************/
435 static void CloseDecoder( vlc_object_t *p_this )
436 {
437     decoder_t *p_dec = (decoder_t *)p_this;
438     decoder_sys_t *p_sys = p_dec->p_sys;
439
440     FLAC__stream_decoder_finish( p_sys->p_flac );
441     FLAC__stream_decoder_delete( p_sys->p_flac );
442     free( p_sys );
443 }
444     
445 /*****************************************************************************
446  * DecoderReadCallback: called by libflac when it needs more data
447  *****************************************************************************/
448 static FLAC__StreamDecoderReadStatus
449 DecoderReadCallback( const FLAC__StreamDecoder *decoder, FLAC__byte buffer[],
450                      unsigned *bytes, void *client_data )
451 {
452     decoder_t *p_dec = (decoder_t *)client_data;
453     decoder_sys_t *p_sys = p_dec->p_sys;
454
455     if( p_sys->p_block && p_sys->p_block->i_buffer )
456     {
457         *bytes = __MIN(*bytes, (unsigned)p_sys->p_block->i_buffer);
458         memcpy( buffer, p_sys->p_block->p_buffer, *bytes );
459         p_sys->p_block->i_buffer -= *bytes;
460         p_sys->p_block->p_buffer += *bytes;
461     }
462     else
463     {
464         *bytes = 0;
465         return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
466     }
467
468     return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
469 }
470
471 /*****************************************************************************
472  * DecoderWriteCallback: called by libflac to output decoded samples
473  *****************************************************************************/
474 static FLAC__StreamDecoderWriteStatus
475 DecoderWriteCallback( const FLAC__StreamDecoder *decoder,
476                       const FLAC__Frame *frame,
477                       const FLAC__int32 *const buffer[], void *client_data )
478 {
479     decoder_t *p_dec = (decoder_t *)client_data;
480     decoder_sys_t *p_sys = p_dec->p_sys;
481
482     p_sys->p_aout_buffer =
483         p_dec->pf_aout_buffer_new( p_dec, frame->header.blocksize );
484
485     if( p_sys->p_aout_buffer == NULL )
486         return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
487
488     switch( frame->header.bits_per_sample )
489     {
490     case 16:
491         Interleave16( (int16_t *)p_sys->p_aout_buffer->p_buffer, buffer,
492                       frame->header.channels, frame->header.blocksize );
493         break;
494     default:
495         Interleave32( (int32_t *)p_sys->p_aout_buffer->p_buffer, buffer,
496                       frame->header.channels, frame->header.blocksize );
497     }
498
499     /* Date management (already done by packetizer) */
500     p_sys->p_aout_buffer->start_date = p_sys->p_block->i_pts;
501     p_sys->p_aout_buffer->end_date =
502         p_sys->p_block->i_pts + p_sys->p_block->i_length;
503
504     return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
505 }
506
507 /*****************************************************************************
508  * DecoderMetadataCallback: called by libflac to when it encounters metadata
509  *****************************************************************************/
510 static void DecoderMetadataCallback( const FLAC__StreamDecoder *decoder,
511                                      const FLAC__StreamMetadata *metadata,
512                                      void *client_data )
513 {
514     decoder_t *p_dec = (decoder_t *)client_data;
515     decoder_sys_t *p_sys = p_dec->p_sys;
516
517     switch( metadata->data.stream_info.bits_per_sample )
518     {
519     case 8:
520         p_dec->fmt_out.i_codec = VLC_FOURCC('s','8',' ',' ');
521         break;
522     case 16:
523         p_dec->fmt_out.i_codec = AOUT_FMT_S16_NE;
524         break;
525     default:
526         msg_Dbg( p_dec, "strange bps %d",
527                  metadata->data.stream_info.bits_per_sample );
528         p_dec->fmt_out.i_codec = VLC_FOURCC('f','i','3','2');
529         break;
530     }
531
532     /* Setup the format */
533     p_dec->fmt_out.audio.i_rate     = metadata->data.stream_info.sample_rate;
534     p_dec->fmt_out.audio.i_channels = metadata->data.stream_info.channels;
535     p_dec->fmt_out.audio.i_physical_channels =
536         p_dec->fmt_out.audio.i_original_channels =
537             pi_channels_maps[metadata->data.stream_info.channels];
538     p_dec->fmt_out.audio.i_bitspersample =
539         metadata->data.stream_info.bits_per_sample;
540
541     aout_DateInit( &p_sys->end_date, p_dec->fmt_out.audio.i_rate );
542
543     msg_Dbg( p_dec, "channels:%d samplerate:%d bitspersamples:%d",
544              p_dec->fmt_out.audio.i_channels, p_dec->fmt_out.audio.i_rate,
545              p_dec->fmt_out.audio.i_bitspersample );
546
547     p_sys->b_stream_info = VLC_TRUE;
548     p_sys->stream_info = metadata->data.stream_info;
549
550     return;
551 }
552
553 /*****************************************************************************
554  * DecoderErrorCallback: called when the libflac decoder encounters an error
555  *****************************************************************************/
556 static void DecoderErrorCallback( const FLAC__StreamDecoder *decoder,
557                                   FLAC__StreamDecoderErrorStatus status,
558                                   void *client_data )
559 {
560     decoder_t *p_dec = (decoder_t *)client_data;
561
562     switch( status )
563     {
564     case FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC:
565         msg_Err( p_dec, "An error in the stream caused the decoder to "
566                  "loose synchronization." );
567         break;
568     case FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER:
569         msg_Err( p_dec, "The decoder encountered a corrupted frame header." );
570         break;
571     case FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH:
572         msg_Err( p_dec, "The frame's data did not match the CRC in the "
573                  "footer." );
574         break;
575     default:
576         msg_Err( p_dec, "got decoder error: %d", status );
577     }
578
579     FLAC__stream_decoder_flush( p_dec->p_sys->p_flac );
580     return;
581 }
582
583 /*****************************************************************************
584  * Interleave: helper function to interleave channels
585  *****************************************************************************/
586 static void Interleave32( int32_t *p_out, const int32_t * const *pp_in,
587                           int i_nb_channels, int i_samples )
588 {
589     int i, j;
590     for ( j = 0; j < i_samples; j++ )
591     {
592         for ( i = 0; i < i_nb_channels; i++ )
593         {
594             p_out[j * i_nb_channels + i] = pp_in[i][j];
595         }
596     }
597 }
598 static void Interleave16( int16_t *p_out, const int32_t * const *pp_in,
599                           int i_nb_channels, int i_samples )
600 {
601     int i, j;
602     for ( j = 0; j < i_samples; j++ )
603     {
604         for ( i = 0; i < i_nb_channels; i++ )
605         {
606             p_out[j * i_nb_channels + i] = (int32_t)(pp_in[i][j]);
607         }
608     }
609 }
610
611 /*****************************************************************************
612  * decoder_state_error: print meaningful error messages
613  *****************************************************************************/
614 static void decoder_state_error( decoder_t *p_dec,
615                                  FLAC__StreamDecoderState state )
616 {
617     switch ( state )
618     {
619     case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
620         msg_Err( p_dec, "The decoder is ready to search for metadata." );
621         break;
622     case FLAC__STREAM_DECODER_READ_METADATA:
623         msg_Err( p_dec, "The decoder is ready to or is in the process of "
624                  "reading metadata." );
625         break;
626     case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
627         msg_Err( p_dec, "The decoder is ready to or is in the process of "
628                  "searching for the frame sync code." );
629         break;
630     case FLAC__STREAM_DECODER_READ_FRAME:
631         msg_Err( p_dec, "The decoder is ready to or is in the process of "
632                  "reading a frame." );
633         break;
634     case FLAC__STREAM_DECODER_END_OF_STREAM:
635         msg_Err( p_dec, "The decoder has reached the end of the stream." );
636         break;
637     case FLAC__STREAM_DECODER_ABORTED:
638         msg_Err( p_dec, "The decoder was aborted by the read callback." );
639         break;
640     case FLAC__STREAM_DECODER_UNPARSEABLE_STREAM:
641         msg_Err( p_dec, "The decoder encountered reserved fields in use "
642                  "in the stream." );
643         break;
644     case FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR:
645         msg_Err( p_dec, "An error occurred allocating memory." );
646         break;
647     case FLAC__STREAM_DECODER_ALREADY_INITIALIZED:
648         msg_Err( p_dec, "FLAC__stream_decoder_init() was called when the "
649                  "decoder was already initialized, usually because "
650                  "FLAC__stream_decoder_finish() was not called." );
651         break;
652     case FLAC__STREAM_DECODER_INVALID_CALLBACK:
653         msg_Err( p_dec, "FLAC__stream_decoder_init() was called without "
654                  "all callbacks being set." );
655         break;
656     case FLAC__STREAM_DECODER_UNINITIALIZED:
657         msg_Err( p_dec, "The decoder is in the uninitialized state." );
658         break;
659     default:
660         msg_Err(p_dec, "unknown error" );
661     }
662 }
663
664 /*****************************************************************************
665  * SyncInfo: parse FLAC sync info
666  *****************************************************************************/
667 static int SyncInfo( decoder_t *p_dec, uint8_t *p_buf,
668                      int * pi_channels, int * pi_channels_conf,
669                      int * pi_sample_rate, int * pi_bits_per_sample )
670 {
671     decoder_sys_t *p_sys = p_dec->p_sys;
672     int i_header, i_temp, i_read;
673     int i_blocksize = 0, i_blocksize_hint = 0, i_sample_rate_hint = 0;
674     uint64_t i_sample_number = 0;
675
676     vlc_bool_t b_variable_blocksize = ( p_sys->b_stream_info &&
677         p_sys->stream_info.min_blocksize != p_sys->stream_info.max_blocksize );
678     vlc_bool_t b_fixed_blocksize = ( p_sys->b_stream_info &&
679         p_sys->stream_info.min_blocksize == p_sys->stream_info.max_blocksize );
680
681     /* Check syncword */
682     if( p_buf[0] != 0xFF || p_buf[1] != 0xF8 ) return 0;
683
684     /* Check there is no emulated sync code in the rest of the header */
685     if( p_buf[2] == 0xff || p_buf[3] == 0xFF ) return 0;
686
687     /* Find blocksize (framelength) */
688     switch( i_temp = p_buf[2] >> 4 )
689     {
690     case 0:
691         if( b_fixed_blocksize )
692             i_blocksize = p_sys->stream_info.min_blocksize;
693         else return 0; /* We can't do anything with this */
694         break;
695
696     case 1:
697         i_blocksize = 192;
698         break;
699
700     case 2:
701     case 3:
702     case 4:
703     case 5:
704         i_blocksize = 576 << (i_temp - 2);
705         break;
706
707     case 6:
708     case 7:
709         i_blocksize_hint = i_temp;
710         break;
711
712     case 8:
713     case 9:
714     case 10:
715     case 11:
716     case 12:
717     case 13:
718     case 14:
719     case 15:
720         i_blocksize = 256 << (i_temp - 8);
721         break;
722     }
723
724     /* Find samplerate */
725     switch( i_temp = p_buf[2] & 0x0f )
726     {
727     case 0:
728         if( p_sys->b_stream_info )
729             *pi_sample_rate = p_sys->stream_info.sample_rate;
730         else return 0; /* We can't do anything with this */
731         break;
732
733     case 1:
734     case 2:
735     case 3:
736         return 0;
737         break;
738
739     case 4:
740         *pi_sample_rate = 8000;
741         break;
742
743     case 5:
744         *pi_sample_rate = 16000;
745         break;
746
747     case 6:
748         *pi_sample_rate = 22050;
749         break;
750
751     case 7:
752         *pi_sample_rate = 24000;
753         break;
754
755     case 8:
756         *pi_sample_rate = 32000;
757         break;
758
759     case 9:
760         *pi_sample_rate = 44100;
761         break;
762
763     case 10:
764         *pi_sample_rate = 48000;
765         break;
766
767     case 11:
768         *pi_sample_rate = 96000;
769         break;
770
771     case 12:
772     case 13:
773     case 14:
774         i_sample_rate_hint = i_temp;
775         break;
776
777     case 15:
778         return 0;
779     }
780
781     /* Find channels */
782     i_temp = (unsigned)(p_buf[3] >> 4);
783     if( i_temp & 8 )
784     {
785         int i_channel_assignment; /* ??? */
786
787         *pi_channels = 2;
788         switch( i_temp & 7 )
789         {
790         case 0:
791             i_channel_assignment = FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE;
792             break;
793         case 1:
794             i_channel_assignment = FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE;
795             break;
796         case 2:
797             i_channel_assignment = FLAC__CHANNEL_ASSIGNMENT_MID_SIDE;
798             break;
799         default:
800             return 0;
801             break;
802         }
803     }
804     else
805     {
806         *pi_channels = i_temp + 1;
807         *pi_channels_conf = pi_channels_maps[ *pi_channels ];
808     }
809
810     /* Find bits per sample */
811     switch( i_temp = (unsigned)(p_buf[3] & 0x0e) >> 1 )
812     {
813     case 0:
814         if( p_sys->b_stream_info )
815             *pi_bits_per_sample = p_sys->stream_info.bits_per_sample;
816         else
817             return 0;
818         break;
819
820     case 1:
821         *pi_bits_per_sample = 8;
822         break;
823
824     case 2:
825         *pi_bits_per_sample = 12;
826         break;
827
828     case 4:
829         *pi_bits_per_sample = 16;
830         break;
831
832     case 5:
833         *pi_bits_per_sample = 20;
834         break;
835
836     case 6:
837         *pi_bits_per_sample = 24;
838         break;
839
840     case 3:
841     case 7:
842         return 0;
843         break;
844     }
845
846     /* Zero padding bit */
847     if( p_buf[3] & 0x01 ) return 0;
848
849     /* End of fixed size header */
850     i_header = 4;
851
852     /* Find Sample/Frame number */
853     if( i_blocksize_hint && b_variable_blocksize )
854     {
855         i_sample_number = read_utf8( &p_buf[i_header++], &i_read );
856         if( i_sample_number == I64C(0xffffffffffffffff) ) return 0;
857     }
858     else
859     {
860         i_sample_number = read_utf8( &p_buf[i_header++], &i_read );
861         if( i_sample_number == I64C(0xffffffffffffffff) ) return 0;
862
863         if( p_sys->b_stream_info )
864             i_sample_number *= p_sys->stream_info.min_blocksize;
865     }
866
867     i_header += i_read;
868
869     /* Read blocksize */
870     if( i_blocksize_hint )
871     {
872         int i_val1 = p_buf[i_header++];
873         if( i_blocksize_hint == 7 )
874         {
875             int i_val2 = p_buf[i_header++];
876             i_val1 = (i_val1 << 8) | i_val2;
877         }
878         i_blocksize = i_val1 + 1;
879     }
880
881     /* Read sample rate */
882     if( i_sample_rate_hint )
883     {
884         int i_val1 = p_buf[i_header++];
885         if( i_sample_rate_hint != 12 )
886         {
887             int i_val2 = p_buf[i_header++];
888             i_val1 = (i_val1 << 8) | i_val2;
889         }
890         if( i_sample_rate_hint == 12 ) *pi_sample_rate = i_val1 * 1000;
891         else if( i_sample_rate_hint == 13 ) *pi_sample_rate = i_val1;
892         else *pi_sample_rate = i_val1 * 10;
893     }
894
895     /* Check the CRC-8 byte */
896     if( flac_crc8( p_buf, i_header ) != p_buf[i_header] )
897     {
898         return 0;
899     }
900
901     return i_blocksize;
902 }
903
904 /* Will return 0xffffffffffffffff for an invalid utf-8 sequence */
905 static uint64_t read_utf8( const uint8_t *p_buf, int *pi_read )
906 {
907     uint64_t i_result = 0;
908     unsigned i, j;
909
910     if( !(p_buf[0] & 0x80) ) /* 0xxxxxxx */
911     {
912         i_result = p_buf[0];
913         i = 0;
914     }
915     else if( p_buf[0] & 0xC0 && !(p_buf[0] & 0x20) ) /* 110xxxxx */
916     {
917         i_result = p_buf[0] & 0x1F;
918         i = 1;
919     }
920     else if( p_buf[0] & 0xE0 && !(p_buf[0] & 0x10) ) /* 1110xxxx */
921     {
922         i_result = p_buf[0] & 0x0F;
923         i = 2;
924     }
925     else if( p_buf[0] & 0xF0 && !(p_buf[0] & 0x08) ) /* 11110xxx */
926     {
927         i_result = p_buf[0] & 0x07;
928         i = 3;
929     }
930     else if( p_buf[0] & 0xF8 && !(p_buf[0] & 0x04) ) /* 111110xx */
931     {
932         i_result = p_buf[0] & 0x03;
933         i = 4;
934     }
935     else if( p_buf[0] & 0xFC && !(p_buf[0] & 0x02) ) /* 1111110x */
936     {
937         i_result = p_buf[0] & 0x01;
938         i = 5;
939     }
940     else if( p_buf[0] & 0xFE && !(p_buf[0] & 0x01) ) /* 11111110 */
941     {
942         i_result = 0;
943         i = 6;
944     }
945     else {
946         return I64C(0xffffffffffffffff);
947     }
948
949     for( j = 1; j <= i; j++ )
950     {
951         if( !(p_buf[j] & 0x80) || (p_buf[j] & 0x40) ) /* 10xxxxxx */
952         {
953             return I64C(0xffffffffffffffff);
954         }
955         i_result <<= 6;
956         i_result |= (p_buf[j] & 0x3F);
957     }
958
959     *pi_read = i;
960     return i_result;
961 }
962
963 /* CRC-8, poly = x^8 + x^2 + x^1 + x^0, init = 0 */
964 static uint8_t const flac_crc8_table[256] = {
965         0x00, 0x07, 0x0E, 0x09, 0x1C, 0x1B, 0x12, 0x15,
966         0x38, 0x3F, 0x36, 0x31, 0x24, 0x23, 0x2A, 0x2D,
967         0x70, 0x77, 0x7E, 0x79, 0x6C, 0x6B, 0x62, 0x65,
968         0x48, 0x4F, 0x46, 0x41, 0x54, 0x53, 0x5A, 0x5D,
969         0xE0, 0xE7, 0xEE, 0xE9, 0xFC, 0xFB, 0xF2, 0xF5,
970         0xD8, 0xDF, 0xD6, 0xD1, 0xC4, 0xC3, 0xCA, 0xCD,
971         0x90, 0x97, 0x9E, 0x99, 0x8C, 0x8B, 0x82, 0x85,
972         0xA8, 0xAF, 0xA6, 0xA1, 0xB4, 0xB3, 0xBA, 0xBD,
973         0xC7, 0xC0, 0xC9, 0xCE, 0xDB, 0xDC, 0xD5, 0xD2,
974         0xFF, 0xF8, 0xF1, 0xF6, 0xE3, 0xE4, 0xED, 0xEA,
975         0xB7, 0xB0, 0xB9, 0xBE, 0xAB, 0xAC, 0xA5, 0xA2,
976         0x8F, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9D, 0x9A,
977         0x27, 0x20, 0x29, 0x2E, 0x3B, 0x3C, 0x35, 0x32,
978         0x1F, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0D, 0x0A,
979         0x57, 0x50, 0x59, 0x5E, 0x4B, 0x4C, 0x45, 0x42,
980         0x6F, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7D, 0x7A,
981         0x89, 0x8E, 0x87, 0x80, 0x95, 0x92, 0x9B, 0x9C,
982         0xB1, 0xB6, 0xBF, 0xB8, 0xAD, 0xAA, 0xA3, 0xA4,
983         0xF9, 0xFE, 0xF7, 0xF0, 0xE5, 0xE2, 0xEB, 0xEC,
984         0xC1, 0xC6, 0xCF, 0xC8, 0xDD, 0xDA, 0xD3, 0xD4,
985         0x69, 0x6E, 0x67, 0x60, 0x75, 0x72, 0x7B, 0x7C,
986         0x51, 0x56, 0x5F, 0x58, 0x4D, 0x4A, 0x43, 0x44,
987         0x19, 0x1E, 0x17, 0x10, 0x05, 0x02, 0x0B, 0x0C,
988         0x21, 0x26, 0x2F, 0x28, 0x3D, 0x3A, 0x33, 0x34,
989         0x4E, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5C, 0x5B,
990         0x76, 0x71, 0x78, 0x7F, 0x6A, 0x6D, 0x64, 0x63,
991         0x3E, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2C, 0x2B,
992         0x06, 0x01, 0x08, 0x0F, 0x1A, 0x1D, 0x14, 0x13,
993         0xAE, 0xA9, 0xA0, 0xA7, 0xB2, 0xB5, 0xBC, 0xBB,
994         0x96, 0x91, 0x98, 0x9F, 0x8A, 0x8D, 0x84, 0x83,
995         0xDE, 0xD9, 0xD0, 0xD7, 0xC2, 0xC5, 0xCC, 0xCB,
996         0xE6, 0xE1, 0xE8, 0xEF, 0xFA, 0xFD, 0xF4, 0xF3
997 };
998
999 static uint8_t flac_crc8( const uint8_t *data, unsigned len )
1000 {
1001     uint8_t crc = 0;
1002
1003     while(len--)
1004         crc = flac_crc8_table[crc ^ *data++];
1005
1006     return crc;
1007 }
1008
1009 /*****************************************************************************
1010  * encoder_sys_t : flac encoder descriptor
1011  *****************************************************************************/
1012 struct encoder_sys_t
1013 {
1014     /*
1015      * Input properties
1016      */
1017     int i_headers;
1018
1019     int i_samples_delay;
1020     int i_channels;
1021
1022     FLAC__int32 *p_buffer;
1023     int         i_buffer;
1024
1025     block_t *p_chain;
1026
1027     /*
1028      * FLAC properties
1029      */
1030     FLAC__StreamEncoder *p_flac;
1031     FLAC__StreamMetadata_StreamInfo stream_info;
1032
1033     /*
1034      * Common properties
1035      */
1036     mtime_t i_pts;
1037 };
1038
1039 #define STREAMINFO_SIZE 38
1040
1041 static block_t *Encode( encoder_t *, aout_buffer_t * );
1042
1043 static FLAC__StreamEncoderWriteStatus
1044 EncoderWriteCallback( const FLAC__StreamEncoder *encoder,
1045                       const FLAC__byte buffer[],
1046                       unsigned bytes, unsigned samples,
1047                       unsigned current_frame, void *client_data );
1048
1049 static void EncoderMetadataCallback( const FLAC__StreamEncoder *encoder,
1050                                      const FLAC__StreamMetadata *metadata,
1051                                      void *client_data );
1052
1053 /*****************************************************************************
1054  * OpenEncoder: probe the encoder and return score
1055  *****************************************************************************/
1056 static int OpenEncoder( vlc_object_t *p_this )
1057 {
1058     encoder_t *p_enc = (encoder_t *)p_this;
1059     encoder_sys_t *p_sys;
1060
1061     if( p_enc->fmt_out.i_codec != VLC_FOURCC('f','l','a','c') )
1062     {
1063         return VLC_EGENERIC;
1064     }
1065
1066     /* Allocate the memory needed to store the decoder's structure */
1067     if( ( p_sys = (encoder_sys_t *)malloc(sizeof(encoder_sys_t)) ) == NULL )
1068     {
1069         msg_Err( p_enc, "out of memory" );
1070         return VLC_EGENERIC;
1071     }
1072     p_enc->p_sys = p_sys;
1073     p_enc->pf_encode_audio = Encode;
1074     p_sys->i_headers = 0;
1075     p_sys->p_buffer = 0;
1076     p_sys->i_buffer = 0;
1077     p_sys->i_samples_delay = 0;
1078
1079     /* Create flac encoder */
1080     p_sys->p_flac = FLAC__stream_encoder_new();
1081
1082     FLAC__stream_encoder_set_streamable_subset( p_sys->p_flac, 1 );
1083     FLAC__stream_encoder_set_channels( p_sys->p_flac,
1084                                        p_enc->fmt_in.audio.i_channels );
1085     FLAC__stream_encoder_set_sample_rate( p_sys->p_flac,
1086                                           p_enc->fmt_in.audio.i_rate );
1087     FLAC__stream_encoder_set_bits_per_sample( p_sys->p_flac, 16 );
1088     p_enc->fmt_in.i_codec = AOUT_FMT_S16_NE;
1089
1090     FLAC__stream_encoder_set_write_callback( p_sys->p_flac,
1091         EncoderWriteCallback );
1092     FLAC__stream_encoder_set_metadata_callback( p_sys->p_flac,
1093         EncoderMetadataCallback );
1094     FLAC__stream_encoder_set_client_data( p_sys->p_flac, p_enc );
1095
1096     /* Get and store the STREAMINFO metadata block as a p_extra */
1097     p_sys->p_chain = 0;
1098     FLAC__stream_encoder_init( p_sys->p_flac );
1099
1100     return VLC_SUCCESS;
1101 }
1102
1103 /****************************************************************************
1104  * Encode: the whole thing
1105  ****************************************************************************
1106  * This function spits out ogg packets.
1107  ****************************************************************************/
1108 static block_t *Encode( encoder_t *p_enc, aout_buffer_t *p_aout_buf )
1109 {
1110     encoder_sys_t *p_sys = p_enc->p_sys;
1111     block_t *p_chain;
1112     int i;
1113
1114     p_sys->i_pts = p_aout_buf->start_date -
1115                 (mtime_t)1000000 * (mtime_t)p_sys->i_samples_delay /
1116                 (mtime_t)p_enc->fmt_in.audio.i_rate;
1117
1118     p_sys->i_samples_delay += p_aout_buf->i_nb_samples;
1119
1120     /* Convert samples to FLAC__int32 */
1121     if( p_sys->i_buffer < p_aout_buf->i_nb_bytes * 2 )
1122     {
1123         p_sys->p_buffer =
1124             realloc( p_sys->p_buffer, p_aout_buf->i_nb_bytes * 2 );
1125         p_sys->i_buffer = p_aout_buf->i_nb_bytes * 2;
1126     }
1127
1128     for( i = 0 ; i < p_aout_buf->i_nb_bytes / 2 ; i++ )
1129     {
1130         p_sys->p_buffer[i]= ((int16_t *)p_aout_buf->p_buffer)[i];
1131     }
1132
1133     FLAC__stream_encoder_process_interleaved( p_sys->p_flac, p_sys->p_buffer,
1134                                               p_aout_buf->i_nb_samples );
1135
1136     p_chain = p_sys->p_chain;
1137     p_sys->p_chain = 0;
1138
1139     return p_chain;
1140 }
1141
1142 /*****************************************************************************
1143  * CloseEncoder: encoder destruction
1144  *****************************************************************************/
1145 static void CloseEncoder( vlc_object_t *p_this )
1146 {
1147     encoder_t *p_enc = (encoder_t *)p_this;
1148     encoder_sys_t *p_sys = p_enc->p_sys;
1149
1150     FLAC__stream_encoder_delete( p_sys->p_flac );
1151
1152     if( p_sys->p_buffer ) free( p_sys->p_buffer );
1153     free( p_sys );
1154 }
1155
1156 /*****************************************************************************
1157  * EncoderMetadataCallback: called by libflac to output metadata
1158  *****************************************************************************/
1159 static void EncoderMetadataCallback( const FLAC__StreamEncoder *encoder,
1160                                      const FLAC__StreamMetadata *metadata,
1161                                      void *client_data )
1162 {
1163     encoder_t *p_enc = (encoder_t *)client_data;
1164
1165     msg_Err( p_enc, "MetadataCallback: %i", metadata->type );
1166     return;
1167 }
1168
1169 /*****************************************************************************
1170  * EncoderWriteCallback: called by libflac to output encoded samples
1171  *****************************************************************************/
1172 static FLAC__StreamEncoderWriteStatus
1173 EncoderWriteCallback( const FLAC__StreamEncoder *encoder,
1174                       const FLAC__byte buffer[],
1175                       unsigned bytes, unsigned samples,
1176                       unsigned current_frame, void *client_data )
1177 {
1178     encoder_t *p_enc = (encoder_t *)client_data;
1179     encoder_sys_t *p_sys = p_enc->p_sys;
1180     block_t *p_block;
1181
1182     if( samples == 0 )
1183     {
1184         if( p_sys->i_headers == 1 )
1185         {
1186             msg_Dbg( p_enc, "Writing STREAMINFO: %i", bytes );
1187
1188             /* Backup the STREAMINFO metadata block */
1189             p_enc->fmt_out.i_extra = STREAMINFO_SIZE + 4;
1190             p_enc->fmt_out.p_extra = malloc( STREAMINFO_SIZE + 4 );
1191             memcpy( p_enc->fmt_out.p_extra, "fLaC", 4 );
1192             memcpy( ((uint8_t *)p_enc->fmt_out.p_extra) + 4, buffer,
1193                     STREAMINFO_SIZE );
1194
1195             /* Fake this as the last metadata block */
1196             ((uint8_t*)p_enc->fmt_out.p_extra)[4] |= 0x80;
1197         }
1198         p_sys->i_headers++;
1199         return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
1200     }
1201
1202     p_block = block_New( p_enc, bytes );
1203     memcpy( p_block->p_buffer, buffer, bytes );
1204
1205     p_block->i_dts = p_block->i_pts = p_sys->i_pts;
1206
1207     p_sys->i_samples_delay -= samples;
1208
1209     p_block->i_length = (mtime_t)1000000 *
1210         (mtime_t)samples / (mtime_t)p_enc->fmt_in.audio.i_rate;
1211
1212     /* Update pts */
1213     p_sys->i_pts += p_block->i_length;
1214
1215     block_ChainAppend( &p_sys->p_chain, p_block );
1216
1217     return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
1218 }