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