]> git.sesse.net Git - vlc/blob - modules/codec/flac.c
Use var_Inherit* instead of var_CreateGet*.
[vlc] / modules / codec / flac.c
1 /*****************************************************************************
2  * flac.c: flac decoder/encoder module making use of libflac
3  *****************************************************************************
4  * Copyright (C) 1999-2001 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Gildas Bazin <gbazin@videolan.org>
8  *          Sigmund Augdal Helberg <dnumgis@videolan.org>
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., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
23  *****************************************************************************/
24
25 /*****************************************************************************
26  * Preamble
27  *****************************************************************************/
28
29 /* workaround libflac overriding assert.h system header */
30 #define assert(x) do {} while(0)
31
32 #ifdef HAVE_CONFIG_H
33 # include "config.h"
34 #endif
35
36 #include <vlc_common.h>
37 #include <vlc_plugin.h>
38 #include <vlc_codec.h>
39 #include <vlc_aout.h>
40
41 #include <stream_decoder.h>
42 #include <stream_encoder.h>
43
44 #include <vlc_block_helper.h>
45 #include <vlc_bits.h>
46
47 #if defined(FLAC_API_VERSION_CURRENT) && FLAC_API_VERSION_CURRENT >= 8
48 #   define USE_NEW_FLAC_API
49 #endif
50
51 /*****************************************************************************
52  * decoder_sys_t : FLAC decoder descriptor
53  *****************************************************************************/
54 struct decoder_sys_t
55 {
56     /*
57      * Input/Output properties
58      */
59     block_t *p_block;
60     aout_buffer_t *p_aout_buffer;
61     date_t        end_date;
62
63     /*
64      * FLAC properties
65      */
66     FLAC__StreamDecoder *p_flac;
67     FLAC__StreamMetadata_StreamInfo stream_info;
68     bool b_stream_info;
69 };
70
71 static const int pi_channels_maps[9] =
72 {
73     0,
74     AOUT_CHAN_CENTER,
75     AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT,
76     AOUT_CHAN_CENTER | AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT,
77     AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_REARLEFT
78      | AOUT_CHAN_REARRIGHT,
79     AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_CENTER
80      | AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT,
81     AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_CENTER
82      | AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT | AOUT_CHAN_LFE,
83     AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_CENTER
84      | AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT | AOUT_CHAN_MIDDLELEFT
85      | AOUT_CHAN_MIDDLERIGHT,
86     AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_CENTER | AOUT_CHAN_REARLEFT
87      | AOUT_CHAN_REARRIGHT | AOUT_CHAN_MIDDLELEFT | AOUT_CHAN_MIDDLERIGHT
88      | AOUT_CHAN_LFE
89 };
90
91 /*****************************************************************************
92  * Local prototypes
93  *****************************************************************************/
94 static int  OpenDecoder   ( vlc_object_t * );
95 static void CloseDecoder  ( vlc_object_t * );
96
97 static int OpenEncoder   ( vlc_object_t * );
98 static void CloseEncoder ( vlc_object_t * );
99
100 static aout_buffer_t *DecodeBlock( decoder_t *, block_t ** );
101
102 static FLAC__StreamDecoderReadStatus
103 DecoderReadCallback( const FLAC__StreamDecoder *decoder,
104                      FLAC__byte buffer[], unsigned *bytes, void *client_data );
105
106 static FLAC__StreamDecoderWriteStatus
107 DecoderWriteCallback( const FLAC__StreamDecoder *decoder,
108                       const FLAC__Frame *frame,
109                       const FLAC__int32 *const buffer[], void *client_data );
110
111 static void DecoderMetadataCallback( const FLAC__StreamDecoder *decoder,
112                                      const FLAC__StreamMetadata *metadata,
113                                      void *client_data );
114 static void DecoderErrorCallback( const FLAC__StreamDecoder *decoder,
115                                   FLAC__StreamDecoderErrorStatus status,
116                                   void *client_data);
117
118 static void Interleave32( int32_t *p_out, const int32_t * const *pp_in,
119                           const int *pi_order, int i_nb_channels, int i_samples );
120 static void Interleave24( int8_t *p_out, const int32_t * const *pp_in,
121                           const int *pi_order, int i_nb_channels, int i_samples );
122 static void Interleave16( int16_t *p_out, const int32_t * const *pp_in,
123                           const int *pi_order, int i_nb_channels, int i_samples );
124
125 static void decoder_state_error( decoder_t *p_dec,
126                                  FLAC__StreamDecoderState state );
127
128 /*****************************************************************************
129  * Module descriptor
130  *****************************************************************************/
131 vlc_module_begin ()
132
133     set_category( CAT_INPUT )
134     set_subcategory( SUBCAT_INPUT_ACODEC )
135     add_shortcut( "flac" )
136
137     set_description( N_("Flac audio decoder") )
138     set_capability( "decoder", 100 )
139     set_callbacks( OpenDecoder, CloseDecoder )
140
141     add_submodule ()
142     add_shortcut( "flac" )
143     set_description( N_("Flac audio encoder") )
144     set_capability( "encoder", 100 )
145     set_callbacks( OpenEncoder, CloseEncoder )
146
147 vlc_module_end ()
148
149 /*****************************************************************************
150  * OpenDecoder: probe the decoder and return score
151  *****************************************************************************/
152 static int OpenDecoder( vlc_object_t *p_this )
153 {
154     decoder_t *p_dec = (decoder_t*)p_this;
155     decoder_sys_t *p_sys;
156
157     if( p_dec->fmt_in.i_codec != VLC_CODEC_FLAC )
158     {
159         return VLC_EGENERIC;
160     }
161
162     /* Allocate the memory needed to store the decoder's structure */
163     if( ( p_dec->p_sys = p_sys = malloc(sizeof(*p_sys)) ) == NULL )
164         return VLC_ENOMEM;
165
166     /* Misc init */
167     p_sys->b_stream_info = false;
168     p_sys->p_block = NULL;
169
170     /* Take care of flac init */
171     if( !(p_sys->p_flac = FLAC__stream_decoder_new()) )
172     {
173         msg_Err( p_dec, "FLAC__stream_decoder_new() failed" );
174         free( p_sys );
175         return VLC_EGENERIC;
176     }
177
178 #ifdef USE_NEW_FLAC_API
179     if( FLAC__stream_decoder_init_stream( p_sys->p_flac,
180                                           DecoderReadCallback,
181                                           NULL,
182                                           NULL,
183                                           NULL,
184                                           NULL,
185                                           DecoderWriteCallback,
186                                           DecoderMetadataCallback,
187                                           DecoderErrorCallback,
188                                           p_dec )
189         != FLAC__STREAM_DECODER_INIT_STATUS_OK )
190     {
191         msg_Err( p_dec, "FLAC__stream_decoder_init_stream() failed" );
192         FLAC__stream_decoder_delete( p_sys->p_flac );
193         free( p_sys );
194         return VLC_EGENERIC;
195     }
196 #else
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 #endif
209
210     /* Set output properties */
211     p_dec->fmt_out.i_cat = AUDIO_ES;
212     p_dec->fmt_out.i_codec = VLC_CODEC_FL32;
213
214     /* Set callbacks */
215     p_dec->pf_decode_audio = DecodeBlock;
216
217     /* */
218     p_dec->b_need_packetized = true;
219
220     return VLC_SUCCESS;
221 }
222
223 /*****************************************************************************
224  * CloseDecoder: flac decoder destruction
225  *****************************************************************************/
226 static void CloseDecoder( vlc_object_t *p_this )
227 {
228     decoder_t *p_dec = (decoder_t *)p_this;
229     decoder_sys_t *p_sys = p_dec->p_sys;
230
231     FLAC__stream_decoder_finish( p_sys->p_flac );
232     FLAC__stream_decoder_delete( p_sys->p_flac );
233
234     if( p_sys->p_block )
235         block_Release( p_sys->p_block );
236     free( p_sys );
237 }
238
239 /*****************************************************************************
240  * ProcessHeader: process Flac header.
241  *****************************************************************************/
242 static void ProcessHeader( decoder_t *p_dec )
243 {
244     decoder_sys_t *p_sys = p_dec->p_sys;
245
246     if( !p_dec->fmt_in.i_extra )
247         return;
248
249     /* Decode STREAMINFO */
250     msg_Dbg( p_dec, "decode STREAMINFO" );
251     p_sys->p_block = block_New( p_dec, p_dec->fmt_in.i_extra );
252     memcpy( p_sys->p_block->p_buffer, p_dec->fmt_in.p_extra,
253             p_dec->fmt_in.i_extra );
254     FLAC__stream_decoder_process_until_end_of_metadata( p_sys->p_flac );
255     msg_Dbg( p_dec, "STREAMINFO decoded" );
256 }
257
258 /****************************************************************************
259  * DecodeBlock: the whole thing
260  ****************************************************************************/
261 static aout_buffer_t *DecodeBlock( decoder_t *p_dec, block_t **pp_block )
262 {
263     decoder_sys_t *p_sys = p_dec->p_sys;
264
265     if( !pp_block || !*pp_block )
266         return NULL;
267     if( (*pp_block)->i_flags&(BLOCK_FLAG_DISCONTINUITY|BLOCK_FLAG_CORRUPTED) )
268     {
269         block_Release( *pp_block );
270         return NULL;
271     }
272
273     if( !p_sys->b_stream_info )
274         ProcessHeader( p_dec );
275
276     p_sys->p_block = *pp_block;
277     *pp_block = NULL;
278
279     if( p_sys->p_block->i_pts > VLC_TS_INVALID &&
280         p_sys->p_block->i_pts != date_Get( &p_sys->end_date ) )
281         date_Set( &p_sys->end_date, p_sys->p_block->i_pts );
282
283     p_sys->p_aout_buffer = 0;
284
285     if( !FLAC__stream_decoder_process_single( p_sys->p_flac ) )
286     {
287         decoder_state_error( p_dec,
288                              FLAC__stream_decoder_get_state( p_sys->p_flac ) );
289         FLAC__stream_decoder_flush( p_dec->p_sys->p_flac );
290     }
291
292     /* If the decoder is in the "aborted" state,
293      * FLAC__stream_decoder_process_single() won't return an error. */
294     if( FLAC__stream_decoder_get_state(p_dec->p_sys->p_flac)
295         == FLAC__STREAM_DECODER_ABORTED )
296     {
297         FLAC__stream_decoder_flush( p_dec->p_sys->p_flac );
298     }
299
300     block_Release( p_sys->p_block );
301     p_sys->p_block = NULL;
302
303     return p_sys->p_aout_buffer;
304 }
305
306 /*****************************************************************************
307  * DecoderReadCallback: called by libflac when it needs more data
308  *****************************************************************************/
309 static FLAC__StreamDecoderReadStatus
310 DecoderReadCallback( const FLAC__StreamDecoder *decoder, FLAC__byte buffer[],
311                      unsigned *bytes, void *client_data )
312 {
313     VLC_UNUSED(decoder);
314     decoder_t *p_dec = (decoder_t *)client_data;
315     decoder_sys_t *p_sys = p_dec->p_sys;
316
317     if( p_sys->p_block && p_sys->p_block->i_buffer )
318     {
319         *bytes = __MIN(*bytes, (unsigned)p_sys->p_block->i_buffer);
320         memcpy( buffer, p_sys->p_block->p_buffer, *bytes );
321         p_sys->p_block->i_buffer -= *bytes;
322         p_sys->p_block->p_buffer += *bytes;
323     }
324     else
325     {
326         *bytes = 0;
327         return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
328     }
329
330     return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
331 }
332
333 /*****************************************************************************
334  * DecoderWriteCallback: called by libflac to output decoded samples
335  *****************************************************************************/
336 static FLAC__StreamDecoderWriteStatus
337 DecoderWriteCallback( const FLAC__StreamDecoder *decoder,
338                       const FLAC__Frame *frame,
339                       const FLAC__int32 *const buffer[], void *client_data )
340 {
341     /* XXX it supposes our internal format is WG4 */
342     static const int ppi_reorder[1+8][8] = {
343         {-1},
344         { 0, },
345         { 0, 1 },
346         { 0, 1, 2 },
347         { 0, 1, 2, 3 },
348         { 0, 1, 3, 4, 2 },
349         { 0, 1, 4, 5, 2, 3 },
350
351         { 0, 1, 6, 4, 5, 2, 3 },    /* 7.0 Unspecified by flac, but following SMPTE */
352         { 0, 1, 6, 7, 4, 5, 2, 3 }, /* 7.1 Unspecified by flac, but following SMPTE */
353     };
354
355     VLC_UNUSED(decoder);
356     decoder_t *p_dec = (decoder_t *)client_data;
357     decoder_sys_t *p_sys = p_dec->p_sys;
358
359     if( p_dec->fmt_out.audio.i_channels <= 0 ||
360         p_dec->fmt_out.audio.i_channels > 8 )
361         return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
362     if( date_Get( &p_sys->end_date ) <= VLC_TS_INVALID )
363         return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
364
365     const int * const pi_reorder = ppi_reorder[p_dec->fmt_out.audio.i_channels];
366
367     p_sys->p_aout_buffer =
368         decoder_NewAudioBuffer( p_dec, frame->header.blocksize );
369
370     if( p_sys->p_aout_buffer == NULL )
371         return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
372
373     switch( frame->header.bits_per_sample )
374     {
375     case 16:
376         Interleave16( (int16_t *)p_sys->p_aout_buffer->p_buffer, buffer, pi_reorder,
377                       frame->header.channels, frame->header.blocksize );
378         break;
379     case 24:
380         Interleave24( (int8_t *)p_sys->p_aout_buffer->p_buffer, buffer, pi_reorder,
381                       frame->header.channels, frame->header.blocksize );
382         break;
383     default:
384         Interleave32( (int32_t *)p_sys->p_aout_buffer->p_buffer, buffer, pi_reorder,
385                       frame->header.channels, frame->header.blocksize );
386     }
387
388     /* Date management (already done by packetizer) */
389     p_sys->p_aout_buffer->i_pts = date_Get( &p_sys->end_date );
390     p_sys->p_aout_buffer->i_length =
391         date_Increment( &p_sys->end_date, frame->header.blocksize ) -
392         p_sys->p_aout_buffer->i_pts;
393
394     return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
395 }
396
397 /*****************************************************************************
398  * DecoderMetadataCallback: called by libflac to when it encounters metadata
399  *****************************************************************************/
400 static void DecoderMetadataCallback( const FLAC__StreamDecoder *decoder,
401                                      const FLAC__StreamMetadata *metadata,
402                                      void *client_data )
403 {
404     VLC_UNUSED(decoder);
405     decoder_t *p_dec = (decoder_t *)client_data;
406     decoder_sys_t *p_sys = p_dec->p_sys;
407
408     if( p_dec->pf_decode_audio )
409     {
410         switch( metadata->data.stream_info.bits_per_sample )
411         {
412         case 8:
413             p_dec->fmt_out.i_codec = VLC_CODEC_S8;
414             break;
415         case 16:
416             p_dec->fmt_out.i_codec = VLC_CODEC_S16N;
417             break;
418         case 24:
419             p_dec->fmt_out.i_codec = VLC_CODEC_S24N;
420             break;
421         default:
422             msg_Dbg( p_dec, "strange bit/sample value: %d",
423                      metadata->data.stream_info.bits_per_sample );
424             p_dec->fmt_out.i_codec = VLC_CODEC_FI32;
425             break;
426         }
427     }
428
429     /* Setup the format */
430     p_dec->fmt_out.audio.i_rate     = metadata->data.stream_info.sample_rate;
431     p_dec->fmt_out.audio.i_channels = metadata->data.stream_info.channels;
432     p_dec->fmt_out.audio.i_physical_channels =
433         p_dec->fmt_out.audio.i_original_channels =
434             pi_channels_maps[metadata->data.stream_info.channels];
435     p_dec->fmt_out.audio.i_bitspersample =
436         metadata->data.stream_info.bits_per_sample;
437
438     msg_Dbg( p_dec, "channels:%d samplerate:%d bitspersamples:%d",
439              p_dec->fmt_out.audio.i_channels, p_dec->fmt_out.audio.i_rate,
440              p_dec->fmt_out.audio.i_bitspersample );
441
442     p_sys->b_stream_info = true;
443     p_sys->stream_info = metadata->data.stream_info;
444
445     date_Init( &p_sys->end_date, p_dec->fmt_out.audio.i_rate, 1 );
446     date_Set( &p_sys->end_date, VLC_TS_INVALID );
447 }
448
449 /*****************************************************************************
450  * DecoderErrorCallback: called when the libflac decoder encounters an error
451  *****************************************************************************/
452 static void DecoderErrorCallback( const FLAC__StreamDecoder *decoder,
453                                   FLAC__StreamDecoderErrorStatus status,
454                                   void *client_data )
455 {
456     VLC_UNUSED(decoder);
457     decoder_t *p_dec = (decoder_t *)client_data;
458
459     switch( status )
460     {
461     case FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC:
462         msg_Warn( p_dec, "an error in the stream caused the decoder to "
463                  "lose synchronization." );
464         break;
465     case FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER:
466         msg_Err( p_dec, "the decoder encountered a corrupted frame header." );
467         break;
468     case FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH:
469         msg_Err( p_dec, "frame's data did not match the CRC in the "
470                  "footer." );
471         break;
472     default:
473         msg_Err( p_dec, "got decoder error: %d", status );
474     }
475
476     FLAC__stream_decoder_flush( p_dec->p_sys->p_flac );
477     return;
478 }
479
480 /*****************************************************************************
481  * Interleave: helper function to interleave channels
482  *****************************************************************************/
483 static void Interleave32( int32_t *p_out, const int32_t * const *pp_in,
484                           const int pi_index[],
485                           int i_nb_channels, int i_samples )
486 {
487     int i, j;
488     for ( j = 0; j < i_samples; j++ )
489     {
490         for ( i = 0; i < i_nb_channels; i++ )
491         {
492             p_out[j * i_nb_channels + i] = pp_in[pi_index[i]][j];
493         }
494     }
495 }
496
497 static void Interleave24( int8_t *p_out, const int32_t * const *pp_in,
498                           const int pi_index[],
499                           int i_nb_channels, int i_samples )
500 {
501     int i, j;
502     for ( j = 0; j < i_samples; j++ )
503     {
504         for ( i = 0; i < i_nb_channels; i++ )
505         {
506             const int i_index = pi_index[i];
507 #ifdef WORDS_BIGENDIAN
508             p_out[3*(j * i_nb_channels + i)+0] = (pp_in[i_index][j] >> 16) & 0xff;
509             p_out[3*(j * i_nb_channels + i)+1] = (pp_in[i_index][j] >> 8 ) & 0xff;
510             p_out[3*(j * i_nb_channels + i)+2] = (pp_in[i_index][j] >> 0 ) & 0xff;
511 #else
512             p_out[3*(j * i_nb_channels + i)+2] = (pp_in[i_index][j] >> 16) & 0xff;
513             p_out[3*(j * i_nb_channels + i)+1] = (pp_in[i_index][j] >> 8 ) & 0xff;
514             p_out[3*(j * i_nb_channels + i)+0] = (pp_in[i_index][j] >> 0 ) & 0xff;
515 #endif
516         }
517     }
518 }
519
520 static void Interleave16( int16_t *p_out, const int32_t * const *pp_in,
521                           const int pi_index[],
522                           int i_nb_channels, int i_samples )
523 {
524     int i, j;
525     for ( j = 0; j < i_samples; j++ )
526     {
527         for ( i = 0; i < i_nb_channels; i++ )
528         {
529             p_out[j * i_nb_channels + i] = (int32_t)(pp_in[pi_index[i]][j]);
530         }
531     }
532 }
533
534 /*****************************************************************************
535  * decoder_state_error: print meaningful error messages
536  *****************************************************************************/
537 static void decoder_state_error( decoder_t *p_dec,
538                                  FLAC__StreamDecoderState state )
539 {
540     switch ( state )
541     {
542     case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
543         msg_Dbg( p_dec, "the decoder is ready to search for metadata." );
544         break;
545     case FLAC__STREAM_DECODER_READ_METADATA:
546         msg_Dbg( p_dec, "the decoder is ready to or is in the process of "
547                  "reading metadata." );
548         break;
549     case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
550         msg_Dbg( p_dec, "the decoder is ready to or is in the process of "
551                  "searching for the frame sync code." );
552         break;
553     case FLAC__STREAM_DECODER_READ_FRAME:
554         msg_Dbg( p_dec, "the decoder is ready to or is in the process of "
555                  "reading a frame." );
556         break;
557     case FLAC__STREAM_DECODER_END_OF_STREAM:
558         msg_Dbg( p_dec, "the decoder has reached the end of the stream." );
559         break;
560 #ifdef USE_NEW_FLAC_API
561     case FLAC__STREAM_DECODER_OGG_ERROR:
562         msg_Err( p_dec, "error occurred in the Ogg layer." );
563         break;
564     case FLAC__STREAM_DECODER_SEEK_ERROR:
565         msg_Err( p_dec, "error occurred while seeking." );
566         break;
567 #endif
568     case FLAC__STREAM_DECODER_ABORTED:
569         msg_Warn( p_dec, "the decoder was aborted by the read callback." );
570         break;
571 #ifndef USE_NEW_FLAC_API
572     case FLAC__STREAM_DECODER_UNPARSEABLE_STREAM:
573         msg_Warn( p_dec, "the decoder encountered reserved fields in use "
574                  "in the stream." );
575         break;
576 #endif
577     case FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR:
578         msg_Err( p_dec, "error when allocating memory." );
579         break;
580 #ifndef USE_NEW_FLAC_API
581     case FLAC__STREAM_DECODER_ALREADY_INITIALIZED:
582         msg_Err( p_dec, "FLAC__stream_decoder_init() was called when the "
583                  "decoder was already initialized, usually because "
584                  "FLAC__stream_decoder_finish() was not called." );
585         break;
586     case FLAC__STREAM_DECODER_INVALID_CALLBACK:
587         msg_Err( p_dec, "FLAC__stream_decoder_init() was called without "
588                  "all callbacks being set." );
589         break;
590 #endif
591     case FLAC__STREAM_DECODER_UNINITIALIZED:
592         msg_Err( p_dec, "decoder in uninitialized state." );
593         break;
594     default:
595         msg_Warn(p_dec, "unknown error" );
596     }
597 }
598
599 /*****************************************************************************
600  * encoder_sys_t : flac encoder descriptor
601  *****************************************************************************/
602 struct encoder_sys_t
603 {
604     /*
605      * Input properties
606      */
607     int i_headers;
608
609     int i_samples_delay;
610     int i_channels;
611
612     FLAC__int32 *p_buffer;
613     unsigned int i_buffer;
614
615     block_t *p_chain;
616
617     /*
618      * FLAC properties
619      */
620     FLAC__StreamEncoder *p_flac;
621     FLAC__StreamMetadata_StreamInfo stream_info;
622
623     /*
624      * Common properties
625      */
626     mtime_t i_pts;
627 };
628
629 #define STREAMINFO_SIZE 38
630
631 static block_t *Encode( encoder_t *, aout_buffer_t * );
632
633 static FLAC__StreamEncoderWriteStatus
634 EncoderWriteCallback( const FLAC__StreamEncoder *encoder,
635                       const FLAC__byte buffer[],
636                       unsigned bytes, unsigned samples,
637                       unsigned current_frame, void *client_data );
638
639 static void EncoderMetadataCallback( const FLAC__StreamEncoder *encoder,
640                                      const FLAC__StreamMetadata *metadata,
641                                      void *client_data );
642
643 /*****************************************************************************
644  * OpenEncoder: probe the encoder and return score
645  *****************************************************************************/
646 static int OpenEncoder( vlc_object_t *p_this )
647 {
648     encoder_t *p_enc = (encoder_t *)p_this;
649     encoder_sys_t *p_sys;
650
651     if( p_enc->fmt_out.i_codec != VLC_CODEC_FLAC &&
652         !p_enc->b_force )
653     {
654         return VLC_EGENERIC;
655     }
656
657     /* Allocate the memory needed to store the decoder's structure */
658     if( ( p_sys = (encoder_sys_t *)malloc(sizeof(encoder_sys_t)) ) == NULL )
659         return VLC_ENOMEM;
660     p_enc->p_sys = p_sys;
661     p_enc->pf_encode_audio = Encode;
662     p_enc->fmt_out.i_codec = VLC_CODEC_FLAC;
663
664     p_sys->i_headers = 0;
665     p_sys->p_buffer = 0;
666     p_sys->i_buffer = 0;
667     p_sys->i_samples_delay = 0;
668
669     /* Create flac encoder */
670     if( !(p_sys->p_flac = FLAC__stream_encoder_new()) )
671     {
672         msg_Err( p_enc, "FLAC__stream_encoder_new() failed" );
673         free( p_sys );
674         return VLC_EGENERIC;
675     }
676
677     FLAC__stream_encoder_set_streamable_subset( p_sys->p_flac, 1 );
678     FLAC__stream_encoder_set_channels( p_sys->p_flac,
679                                        p_enc->fmt_in.audio.i_channels );
680     FLAC__stream_encoder_set_sample_rate( p_sys->p_flac,
681                                           p_enc->fmt_in.audio.i_rate );
682     FLAC__stream_encoder_set_bits_per_sample( p_sys->p_flac, 16 );
683     p_enc->fmt_in.i_codec = VLC_CODEC_S16N;
684
685     /* Get and store the STREAMINFO metadata block as a p_extra */
686     p_sys->p_chain = 0;
687
688 #ifdef USE_NEW_FLAC_API
689     if( FLAC__stream_encoder_init_stream( p_sys->p_flac,
690                                           EncoderWriteCallback,
691                                           NULL,
692                                           NULL,
693                                           EncoderMetadataCallback,
694                                           p_enc )
695         != FLAC__STREAM_ENCODER_INIT_STATUS_OK )
696     {
697         msg_Err( p_enc, "FLAC__stream_encoder_init_stream() failed" );
698         FLAC__stream_encoder_delete( p_sys->p_flac );
699         free( p_sys );
700         return VLC_EGENERIC;
701     }
702 #else
703     FLAC__stream_encoder_set_write_callback( p_sys->p_flac,
704         EncoderWriteCallback );
705     FLAC__stream_encoder_set_metadata_callback( p_sys->p_flac,
706         EncoderMetadataCallback );
707     FLAC__stream_encoder_set_client_data( p_sys->p_flac, p_enc );
708
709     FLAC__stream_encoder_init( p_sys->p_flac );
710 #endif
711
712     return VLC_SUCCESS;
713 }
714
715 /****************************************************************************
716  * Encode: the whole thing
717  ****************************************************************************
718  * This function spits out ogg packets.
719  ****************************************************************************/
720 static block_t *Encode( encoder_t *p_enc, aout_buffer_t *p_aout_buf )
721 {
722     encoder_sys_t *p_sys = p_enc->p_sys;
723     block_t *p_chain;
724     unsigned int i;
725
726     p_sys->i_pts = p_aout_buf->i_pts -
727                 (mtime_t)1000000 * (mtime_t)p_sys->i_samples_delay /
728                 (mtime_t)p_enc->fmt_in.audio.i_rate;
729
730     p_sys->i_samples_delay += p_aout_buf->i_nb_samples;
731
732     /* Convert samples to FLAC__int32 */
733     if( p_sys->i_buffer < p_aout_buf->i_buffer * 2 )
734     {
735         p_sys->p_buffer =
736             xrealloc( p_sys->p_buffer, p_aout_buf->i_buffer * 2 );
737         p_sys->i_buffer = p_aout_buf->i_buffer * 2;
738     }
739
740     for( i = 0 ; i < p_aout_buf->i_buffer / 2 ; i++ )
741     {
742         p_sys->p_buffer[i]= ((int16_t *)p_aout_buf->p_buffer)[i];
743     }
744
745     FLAC__stream_encoder_process_interleaved( p_sys->p_flac, p_sys->p_buffer,
746                                               p_aout_buf->i_nb_samples );
747
748     p_chain = p_sys->p_chain;
749     p_sys->p_chain = 0;
750
751     return p_chain;
752 }
753
754 /*****************************************************************************
755  * CloseEncoder: encoder destruction
756  *****************************************************************************/
757 static void CloseEncoder( vlc_object_t *p_this )
758 {
759     encoder_t *p_enc = (encoder_t *)p_this;
760     encoder_sys_t *p_sys = p_enc->p_sys;
761
762     FLAC__stream_encoder_delete( p_sys->p_flac );
763
764     free( p_sys->p_buffer );
765     free( p_sys );
766 }
767
768 /*****************************************************************************
769  * EncoderMetadataCallback: called by libflac to output metadata
770  *****************************************************************************/
771 static void EncoderMetadataCallback( const FLAC__StreamEncoder *encoder,
772                                      const FLAC__StreamMetadata *metadata,
773                                      void *client_data )
774 {
775     VLC_UNUSED(encoder);
776     encoder_t *p_enc = (encoder_t *)client_data;
777
778     msg_Err( p_enc, "MetadataCallback: %i", metadata->type );
779     return;
780 }
781
782 /*****************************************************************************
783  * EncoderWriteCallback: called by libflac to output encoded samples
784  *****************************************************************************/
785 static FLAC__StreamEncoderWriteStatus
786 EncoderWriteCallback( const FLAC__StreamEncoder *encoder,
787                       const FLAC__byte buffer[],
788                       unsigned bytes, unsigned samples,
789                       unsigned current_frame, void *client_data )
790 {
791     VLC_UNUSED(encoder); VLC_UNUSED(current_frame);
792     encoder_t *p_enc = (encoder_t *)client_data;
793     encoder_sys_t *p_sys = p_enc->p_sys;
794     block_t *p_block;
795
796     if( samples == 0 )
797     {
798         if( p_sys->i_headers == 1 )
799         {
800             msg_Dbg( p_enc, "Writing STREAMINFO: %i", bytes );
801
802             /* Backup the STREAMINFO metadata block */
803             p_enc->fmt_out.i_extra = STREAMINFO_SIZE + 4;
804             p_enc->fmt_out.p_extra = xmalloc( STREAMINFO_SIZE + 4 );
805             memcpy( p_enc->fmt_out.p_extra, "fLaC", 4 );
806             memcpy( ((uint8_t *)p_enc->fmt_out.p_extra) + 4, buffer,
807                     STREAMINFO_SIZE );
808
809             /* Fake this as the last metadata block */
810             ((uint8_t*)p_enc->fmt_out.p_extra)[4] |= 0x80;
811         }
812         p_sys->i_headers++;
813         return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
814     }
815
816     p_block = block_New( p_enc, bytes );
817     memcpy( p_block->p_buffer, buffer, bytes );
818
819     p_block->i_dts = p_block->i_pts = p_sys->i_pts;
820
821     p_sys->i_samples_delay -= samples;
822
823     p_block->i_length = (mtime_t)1000000 *
824         (mtime_t)samples / (mtime_t)p_enc->fmt_in.audio.i_rate;
825
826     /* Update pts */
827     p_sys->i_pts += p_block->i_length;
828
829     block_ChainAppend( &p_sys->p_chain, p_block );
830
831     return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
832 }
833