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