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