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