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