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