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