]> git.sesse.net Git - vlc/blob - modules/codec/flac.c
vout_macosx: protect vout_display_SendEvent calls to prevent potential crashes
[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_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 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         {-1},
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
158         { 0, 1, 6, 4, 5, 2, 3 },    /* 7.0 Unspecified by flac, but following SMPTE */
159         { 0, 1, 6, 7, 4, 5, 2, 3 }, /* 7.1 Unspecified by flac, but following SMPTE */
160     };
161
162     VLC_UNUSED(decoder);
163     decoder_t *p_dec = (decoder_t *)client_data;
164     decoder_sys_t *p_sys = p_dec->p_sys;
165
166     if( p_dec->fmt_out.audio.i_channels <= 0 ||
167         p_dec->fmt_out.audio.i_channels > 8 )
168         return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
169     if( date_Get( &p_sys->end_date ) <= VLC_TS_INVALID )
170         return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
171
172     const unsigned char *pi_reorder = ppi_reorder[p_dec->fmt_out.audio.i_channels];
173
174     p_sys->p_aout_buffer =
175         decoder_NewAudioBuffer( p_dec, frame->header.blocksize );
176
177     if( p_sys->p_aout_buffer == NULL )
178         return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
179
180     Interleave( (int32_t *)p_sys->p_aout_buffer->p_buffer, buffer, pi_reorder,
181                  frame->header.channels, frame->header.blocksize,
182                  frame->header.bits_per_sample );
183
184     /* Date management (already done by packetizer) */
185     p_sys->p_aout_buffer->i_pts = date_Get( &p_sys->end_date );
186     p_sys->p_aout_buffer->i_length =
187         date_Increment( &p_sys->end_date, frame->header.blocksize ) -
188         p_sys->p_aout_buffer->i_pts;
189
190     return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
191 }
192
193 /*****************************************************************************
194  * DecoderReadCallback: called by libflac when it needs more data
195  *****************************************************************************/
196 static FLAC__StreamDecoderReadStatus
197 DecoderReadCallback( const FLAC__StreamDecoder *decoder, FLAC__byte buffer[],
198                      size_t *bytes, void *client_data )
199 {
200     VLC_UNUSED(decoder);
201     decoder_t *p_dec = (decoder_t *)client_data;
202     decoder_sys_t *p_sys = p_dec->p_sys;
203
204     if( p_sys->p_block && p_sys->p_block->i_buffer )
205     {
206         *bytes = __MIN(*bytes, p_sys->p_block->i_buffer);
207         memcpy( buffer, p_sys->p_block->p_buffer, *bytes );
208         p_sys->p_block->i_buffer -= *bytes;
209         p_sys->p_block->p_buffer += *bytes;
210     }
211     else
212     {
213         *bytes = 0;
214         return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
215     }
216
217     return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
218 }
219
220 /*****************************************************************************
221  * DecoderMetadataCallback: called by libflac to when it encounters metadata
222  *****************************************************************************/
223 static void DecoderMetadataCallback( const FLAC__StreamDecoder *decoder,
224                                      const FLAC__StreamMetadata *metadata,
225                                      void *client_data )
226 {
227     VLC_UNUSED(decoder);
228     decoder_t *p_dec = (decoder_t *)client_data;
229     decoder_sys_t *p_sys = p_dec->p_sys;
230
231     /* Setup the format */
232     p_dec->fmt_out.audio.i_rate     = metadata->data.stream_info.sample_rate;
233     p_dec->fmt_out.audio.i_channels = metadata->data.stream_info.channels;
234     p_dec->fmt_out.audio.i_physical_channels =
235         p_dec->fmt_out.audio.i_original_channels =
236             pi_channels_maps[metadata->data.stream_info.channels];
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     default:
275         msg_Err( p_dec, "got decoder error: %d", status );
276     }
277
278     FLAC__stream_decoder_flush( p_dec->p_sys->p_flac );
279     return;
280 }
281 /*****************************************************************************
282  * OpenDecoder: probe the decoder and return score
283  *****************************************************************************/
284 static int OpenDecoder( vlc_object_t *p_this )
285 {
286     decoder_t *p_dec = (decoder_t*)p_this;
287     decoder_sys_t *p_sys;
288
289     if( p_dec->fmt_in.i_codec != VLC_CODEC_FLAC )
290     {
291         return VLC_EGENERIC;
292     }
293
294     /* Allocate the memory needed to store the decoder's structure */
295     if( ( p_dec->p_sys = p_sys = malloc(sizeof(*p_sys)) ) == NULL )
296         return VLC_ENOMEM;
297
298     /* Misc init */
299     p_sys->b_stream_info = false;
300     p_sys->p_block = NULL;
301
302     /* Take care of flac init */
303     if( !(p_sys->p_flac = FLAC__stream_decoder_new()) )
304     {
305         msg_Err( p_dec, "FLAC__stream_decoder_new() failed" );
306         free( p_sys );
307         return VLC_EGENERIC;
308     }
309
310 #ifdef USE_NEW_FLAC_API
311     if( FLAC__stream_decoder_init_stream( p_sys->p_flac,
312                                           DecoderReadCallback,
313                                           NULL,
314                                           NULL,
315                                           NULL,
316                                           NULL,
317                                           DecoderWriteCallback,
318                                           DecoderMetadataCallback,
319                                           DecoderErrorCallback,
320                                           p_dec )
321         != FLAC__STREAM_DECODER_INIT_STATUS_OK )
322     {
323         msg_Err( p_dec, "FLAC__stream_decoder_init_stream() failed" );
324         FLAC__stream_decoder_delete( p_sys->p_flac );
325         free( p_sys );
326         return VLC_EGENERIC;
327     }
328 #else
329     FLAC__stream_decoder_set_read_callback( p_sys->p_flac,
330                                             DecoderReadCallback );
331     FLAC__stream_decoder_set_write_callback( p_sys->p_flac,
332                                              DecoderWriteCallback );
333     FLAC__stream_decoder_set_metadata_callback( p_sys->p_flac,
334                                                 DecoderMetadataCallback );
335     FLAC__stream_decoder_set_error_callback( p_sys->p_flac,
336                                              DecoderErrorCallback );
337     FLAC__stream_decoder_set_client_data( p_sys->p_flac, p_dec );
338
339     FLAC__stream_decoder_init( p_sys->p_flac );
340 #endif
341
342     /* Set output properties */
343     p_dec->fmt_out.i_cat = AUDIO_ES;
344     p_dec->fmt_out.i_codec = VLC_CODEC_S32N;
345
346     /* Set callbacks */
347     p_dec->pf_decode_audio = DecodeBlock;
348
349     /* */
350     p_dec->b_need_packetized = true;
351
352     return VLC_SUCCESS;
353 }
354
355 /*****************************************************************************
356  * CloseDecoder: flac decoder destruction
357  *****************************************************************************/
358 static void CloseDecoder( vlc_object_t *p_this )
359 {
360     decoder_t *p_dec = (decoder_t *)p_this;
361     decoder_sys_t *p_sys = p_dec->p_sys;
362
363     FLAC__stream_decoder_finish( p_sys->p_flac );
364     FLAC__stream_decoder_delete( p_sys->p_flac );
365
366     if( p_sys->p_block )
367         block_Release( p_sys->p_block );
368     free( p_sys );
369 }
370
371 /*****************************************************************************
372  * ProcessHeader: process Flac header.
373  *****************************************************************************/
374 static void ProcessHeader( decoder_t *p_dec )
375 {
376     decoder_sys_t *p_sys = p_dec->p_sys;
377
378     if( !p_dec->fmt_in.i_extra )
379         return;
380
381     /* Decode STREAMINFO */
382     msg_Dbg( p_dec, "decode STREAMINFO" );
383     p_sys->p_block = block_Alloc( p_dec->fmt_in.i_extra );
384     memcpy( p_sys->p_block->p_buffer, p_dec->fmt_in.p_extra,
385             p_dec->fmt_in.i_extra );
386     FLAC__stream_decoder_process_until_end_of_metadata( p_sys->p_flac );
387     msg_Dbg( p_dec, "STREAMINFO decoded" );
388 }
389
390 /*****************************************************************************
391  * decoder_state_error: print meaningful error messages
392  *****************************************************************************/
393 static void decoder_state_error( decoder_t *p_dec,
394                                  FLAC__StreamDecoderState state )
395 {
396     switch ( state )
397     {
398     case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
399         msg_Dbg( p_dec, "the decoder is ready to search for metadata." );
400         break;
401     case FLAC__STREAM_DECODER_READ_METADATA:
402         msg_Dbg( p_dec, "the decoder is ready to or is in the process of "
403                  "reading metadata." );
404         break;
405     case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
406         msg_Dbg( p_dec, "the decoder is ready to or is in the process of "
407                  "searching for the frame sync code." );
408         break;
409     case FLAC__STREAM_DECODER_READ_FRAME:
410         msg_Dbg( p_dec, "the decoder is ready to or is in the process of "
411                  "reading a frame." );
412         break;
413     case FLAC__STREAM_DECODER_END_OF_STREAM:
414         msg_Dbg( p_dec, "the decoder has reached the end of the stream." );
415         break;
416 #ifdef USE_NEW_FLAC_API
417     case FLAC__STREAM_DECODER_OGG_ERROR:
418         msg_Err( p_dec, "error occurred in the Ogg layer." );
419         break;
420     case FLAC__STREAM_DECODER_SEEK_ERROR:
421         msg_Err( p_dec, "error occurred while seeking." );
422         break;
423 #endif
424     case FLAC__STREAM_DECODER_ABORTED:
425         msg_Warn( p_dec, "the decoder was aborted by the read callback." );
426         break;
427 #ifndef USE_NEW_FLAC_API
428     case FLAC__STREAM_DECODER_UNPARSEABLE_STREAM:
429         msg_Warn( p_dec, "the decoder encountered reserved fields in use "
430                  "in the stream." );
431         break;
432 #endif
433     case FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR:
434         msg_Err( p_dec, "error when allocating memory." );
435         break;
436 #ifndef USE_NEW_FLAC_API
437     case FLAC__STREAM_DECODER_ALREADY_INITIALIZED:
438         msg_Err( p_dec, "FLAC__stream_decoder_init() was called when the "
439                  "decoder was already initialized, usually because "
440                  "FLAC__stream_decoder_finish() was not called." );
441         break;
442     case FLAC__STREAM_DECODER_INVALID_CALLBACK:
443         msg_Err( p_dec, "FLAC__stream_decoder_init() was called without "
444                  "all callbacks being set." );
445         break;
446 #endif
447     case FLAC__STREAM_DECODER_UNINITIALIZED:
448         msg_Err( p_dec, "decoder in uninitialized state." );
449         break;
450     default:
451         msg_Warn(p_dec, "unknown error" );
452     }
453 }
454
455 /****************************************************************************
456  * DecodeBlock: the whole thing
457  ****************************************************************************/
458 static block_t *DecodeBlock( decoder_t *p_dec, block_t **pp_block )
459 {
460     decoder_sys_t *p_sys = p_dec->p_sys;
461
462     if( !pp_block || !*pp_block )
463         return NULL;
464     if( (*pp_block)->i_flags&(BLOCK_FLAG_DISCONTINUITY|BLOCK_FLAG_CORRUPTED) )
465     {
466         block_Release( *pp_block );
467         return NULL;
468     }
469
470     if( !p_sys->b_stream_info )
471         ProcessHeader( p_dec );
472
473     p_sys->p_block = *pp_block;
474     *pp_block = NULL;
475
476     if( p_sys->p_block->i_pts > VLC_TS_INVALID &&
477         p_sys->p_block->i_pts != date_Get( &p_sys->end_date ) )
478         date_Set( &p_sys->end_date, p_sys->p_block->i_pts );
479
480     p_sys->p_aout_buffer = 0;
481
482     if( !FLAC__stream_decoder_process_single( p_sys->p_flac ) )
483     {
484         decoder_state_error( p_dec,
485                              FLAC__stream_decoder_get_state( p_sys->p_flac ) );
486         FLAC__stream_decoder_flush( p_dec->p_sys->p_flac );
487     }
488
489     /* If the decoder is in the "aborted" state,
490      * FLAC__stream_decoder_process_single() won't return an error. */
491     if( FLAC__stream_decoder_get_state(p_dec->p_sys->p_flac)
492         == FLAC__STREAM_DECODER_ABORTED )
493     {
494         FLAC__stream_decoder_flush( p_dec->p_sys->p_flac );
495     }
496
497     block_Release( p_sys->p_block );
498     p_sys->p_block = NULL;
499
500     return p_sys->p_aout_buffer;
501 }
502
503 #ifdef ENABLE_SOUT
504
505 /*****************************************************************************
506  * encoder_sys_t : flac encoder descriptor
507  *****************************************************************************/
508 struct encoder_sys_t
509 {
510     /*
511      * Input properties
512      */
513     int i_headers;
514
515     int i_samples_delay;
516
517     FLAC__int32 *p_buffer;
518     unsigned int i_buffer;
519
520     block_t *p_chain;
521
522     /*
523      * FLAC properties
524      */
525     FLAC__StreamEncoder *p_flac;
526     FLAC__StreamMetadata_StreamInfo stream_info;
527
528     /*
529      * Common properties
530      */
531     mtime_t i_pts;
532 };
533
534 #define STREAMINFO_SIZE 38
535
536 static block_t *Encode( encoder_t *, block_t * );
537
538 /*****************************************************************************
539  * EncoderWriteCallback: called by libflac to output encoded samples
540  *****************************************************************************/
541 static FLAC__StreamEncoderWriteStatus
542 EncoderWriteCallback( const FLAC__StreamEncoder *encoder,
543                       const FLAC__byte buffer[],
544                       size_t bytes, unsigned samples,
545                       unsigned current_frame, void *client_data )
546 {
547     VLC_UNUSED(encoder); VLC_UNUSED(current_frame);
548     encoder_t *p_enc = (encoder_t *)client_data;
549     encoder_sys_t *p_sys = p_enc->p_sys;
550     block_t *p_block;
551
552     if( samples == 0 )
553     {
554         if( p_sys->i_headers == 1 )
555         {
556             msg_Dbg( p_enc, "Writing STREAMINFO: %zu", bytes );
557
558             /* Backup the STREAMINFO metadata block */
559             p_enc->fmt_out.i_extra = STREAMINFO_SIZE + 4;
560             p_enc->fmt_out.p_extra = xmalloc( STREAMINFO_SIZE + 4 );
561             memcpy( p_enc->fmt_out.p_extra, "fLaC", 4 );
562             memcpy( ((uint8_t *)p_enc->fmt_out.p_extra) + 4, buffer,
563                     STREAMINFO_SIZE );
564
565             /* Fake this as the last metadata block */
566             ((uint8_t*)p_enc->fmt_out.p_extra)[4] |= 0x80;
567         }
568         p_sys->i_headers++;
569         return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
570     }
571
572     p_block = block_Alloc( bytes );
573     memcpy( p_block->p_buffer, buffer, bytes );
574
575     p_block->i_dts = p_block->i_pts = p_sys->i_pts;
576
577     p_sys->i_samples_delay -= samples;
578
579     p_block->i_length = (mtime_t)1000000 *
580         (mtime_t)samples / (mtime_t)p_enc->fmt_in.audio.i_rate;
581
582     /* Update pts */
583     p_sys->i_pts += p_block->i_length;
584
585     block_ChainAppend( &p_sys->p_chain, p_block );
586
587     return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
588 }
589 /*****************************************************************************
590  * EncoderMetadataCallback: called by libflac to output metadata
591  *****************************************************************************/
592 static void EncoderMetadataCallback( const FLAC__StreamEncoder *encoder,
593                                      const FLAC__StreamMetadata *metadata,
594                                      void *client_data )
595 {
596     VLC_UNUSED(encoder);
597     encoder_t *p_enc = (encoder_t *)client_data;
598
599     msg_Err( p_enc, "MetadataCallback: %i", metadata->type );
600     return;
601 }
602
603 /*****************************************************************************
604  * OpenEncoder: probe the encoder and return score
605  *****************************************************************************/
606 static int OpenEncoder( vlc_object_t *p_this )
607 {
608     encoder_t *p_enc = (encoder_t *)p_this;
609     encoder_sys_t *p_sys;
610
611     if( p_enc->fmt_out.i_codec != VLC_CODEC_FLAC &&
612         !p_enc->b_force )
613     {
614         return VLC_EGENERIC;
615     }
616
617     /* Allocate the memory needed to store the decoder's structure */
618     if( ( p_sys = (encoder_sys_t *)malloc(sizeof(encoder_sys_t)) ) == NULL )
619         return VLC_ENOMEM;
620     p_enc->p_sys = p_sys;
621     p_enc->pf_encode_audio = Encode;
622     p_enc->fmt_out.i_codec = VLC_CODEC_FLAC;
623
624     p_sys->i_headers = 0;
625     p_sys->p_buffer = 0;
626     p_sys->i_buffer = 0;
627     p_sys->i_samples_delay = 0;
628
629     /* Create flac encoder */
630     if( !(p_sys->p_flac = FLAC__stream_encoder_new()) )
631     {
632         msg_Err( p_enc, "FLAC__stream_encoder_new() failed" );
633         free( p_sys );
634         return VLC_EGENERIC;
635     }
636
637     FLAC__stream_encoder_set_streamable_subset( p_sys->p_flac, 1 );
638     FLAC__stream_encoder_set_channels( p_sys->p_flac,
639                                        p_enc->fmt_in.audio.i_channels );
640     FLAC__stream_encoder_set_sample_rate( p_sys->p_flac,
641                                           p_enc->fmt_in.audio.i_rate );
642     FLAC__stream_encoder_set_bits_per_sample( p_sys->p_flac, 16 );
643     p_enc->fmt_in.i_codec = VLC_CODEC_S16N;
644
645     /* Get and store the STREAMINFO metadata block as a p_extra */
646     p_sys->p_chain = 0;
647
648 #ifdef USE_NEW_FLAC_API
649     if( FLAC__stream_encoder_init_stream( p_sys->p_flac,
650                                           EncoderWriteCallback,
651                                           NULL,
652                                           NULL,
653                                           EncoderMetadataCallback,
654                                           p_enc )
655         != FLAC__STREAM_ENCODER_INIT_STATUS_OK )
656     {
657         msg_Err( p_enc, "FLAC__stream_encoder_init_stream() failed" );
658         FLAC__stream_encoder_delete( p_sys->p_flac );
659         free( p_sys );
660         return VLC_EGENERIC;
661     }
662 #else
663     FLAC__stream_encoder_set_write_callback( p_sys->p_flac,
664         EncoderWriteCallback );
665     FLAC__stream_encoder_set_metadata_callback( p_sys->p_flac,
666         EncoderMetadataCallback );
667     FLAC__stream_encoder_set_client_data( p_sys->p_flac, p_enc );
668
669     FLAC__stream_encoder_init( p_sys->p_flac );
670 #endif
671
672     return VLC_SUCCESS;
673 }
674
675 /****************************************************************************
676  * Encode: the whole thing
677  ****************************************************************************
678  * This function spits out ogg packets.
679  ****************************************************************************/
680 static block_t *Encode( encoder_t *p_enc, block_t *p_aout_buf )
681 {
682     encoder_sys_t *p_sys = p_enc->p_sys;
683     block_t *p_chain;
684     unsigned int i;
685
686     /* FIXME: p_aout_buf is NULL when it's time to flush*/
687     if( unlikely( !p_aout_buf ) ) return NULL;
688
689     p_sys->i_pts = p_aout_buf->i_pts -
690                 (mtime_t)1000000 * (mtime_t)p_sys->i_samples_delay /
691                 (mtime_t)p_enc->fmt_in.audio.i_rate;
692
693     p_sys->i_samples_delay += p_aout_buf->i_nb_samples;
694
695     /* Convert samples to FLAC__int32 */
696     if( p_sys->i_buffer < p_aout_buf->i_buffer * 2 )
697     {
698         p_sys->p_buffer =
699             xrealloc( p_sys->p_buffer, p_aout_buf->i_buffer * 2 );
700         p_sys->i_buffer = p_aout_buf->i_buffer * 2;
701     }
702
703     for( i = 0 ; i < p_aout_buf->i_buffer / 2 ; i++ )
704     {
705         p_sys->p_buffer[i]= ((int16_t *)p_aout_buf->p_buffer)[i];
706     }
707
708     FLAC__stream_encoder_process_interleaved( p_sys->p_flac, p_sys->p_buffer,
709                                               p_aout_buf->i_nb_samples );
710
711     p_chain = p_sys->p_chain;
712     p_sys->p_chain = 0;
713
714     return p_chain;
715 }
716
717 /*****************************************************************************
718  * CloseEncoder: encoder destruction
719  *****************************************************************************/
720 static void CloseEncoder( vlc_object_t *p_this )
721 {
722     encoder_t *p_enc = (encoder_t *)p_this;
723     encoder_sys_t *p_sys = p_enc->p_sys;
724
725     FLAC__stream_encoder_delete( p_sys->p_flac );
726
727     free( p_sys->p_buffer );
728     free( p_sys );
729 }
730 #endif