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