demux: mp4: avoid audio cuts on seek
[vlc.git] / modules / codec / flac.c
blobb6fcac1481a29d04c5b24c9f0b4d27a973887409
1 /*****************************************************************************
2 * flac.c: flac decoder/encoder module making use of libflac
3 *****************************************************************************
4 * Copyright (C) 1999-2001 VLC authors and VideoLAN
5 * $Id$
7 * Authors: Gildas Bazin <gbazin@videolan.org>
8 * Sigmund Augdal Helberg <dnumgis@videolan.org>
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.
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.
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 *****************************************************************************/
25 /*****************************************************************************
26 * Preamble
27 *****************************************************************************/
29 /* workaround libflac overriding assert.h system header */
30 #define assert(x) do {} while(0)
32 #ifdef HAVE_CONFIG_H
33 # include "config.h"
34 #endif
36 #include <vlc_common.h>
37 #include <vlc_plugin.h>
38 #include <vlc_codec.h>
39 #include <vlc_codecs.h>
40 #include <vlc_aout.h>
42 #ifdef _WIN32
43 # define FLAC__NO_DLL
44 #endif
46 #include <FLAC/stream_decoder.h>
47 #include <FLAC/stream_encoder.h>
49 #include <vlc_block_helper.h>
50 #include <vlc_bits.h>
52 #if defined(FLAC_API_VERSION_CURRENT) && FLAC_API_VERSION_CURRENT >= 8
53 # define USE_NEW_FLAC_API
54 #endif
56 /*****************************************************************************
57 * decoder_sys_t : FLAC decoder descriptor
58 *****************************************************************************/
59 struct decoder_sys_t
62 * Input/Output properties
64 block_t *p_block;
65 block_t *p_aout_buffer;
66 date_t end_date;
69 * FLAC properties
71 FLAC__StreamDecoder *p_flac;
72 FLAC__StreamMetadata_StreamInfo stream_info;
74 uint8_t rgi_channels_reorder[AOUT_CHAN_MAX];
75 bool b_stream_info;
78 static const int pi_channels_maps[FLAC__MAX_CHANNELS + 1] =
81 AOUT_CHAN_CENTER,
82 AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT,
83 AOUT_CHAN_CENTER | AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT,
84 AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_REARLEFT
85 | AOUT_CHAN_REARRIGHT,
86 AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_CENTER
87 | AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT,
88 AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_CENTER
89 | AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT | AOUT_CHAN_LFE,
90 AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_CENTER
91 | AOUT_CHAN_REARCENTER | AOUT_CHAN_MIDDLELEFT| AOUT_CHAN_MIDDLERIGHT
92 | AOUT_CHAN_LFE,
93 AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_CENTER | AOUT_CHAN_REARLEFT
94 | AOUT_CHAN_REARRIGHT | AOUT_CHAN_MIDDLELEFT | AOUT_CHAN_MIDDLERIGHT
95 | AOUT_CHAN_LFE
98 /* XXX it supposes our internal format is WG4 */
99 static const uint8_t ppi_reorder[1+FLAC__MAX_CHANNELS][FLAC__MAX_CHANNELS] =
101 { },
102 { 0, },
103 { 0, 1 },
104 { 0, 1, 2 },
105 { 0, 1, 2, 3 },
106 { 0, 1, 3, 4, 2 },
107 { 0, 1, 4, 5, 2, 3 },
108 { 0, 1, 5, 6, 4, 2, 3 },
109 { 0, 1, 6, 7, 4, 5, 2, 3 },
112 /* Flac uses same order as waveformatex */
113 #define MAPPED_WFX_CHANNELS 9
114 static const uint32_t wfx_remapping[MAPPED_WFX_CHANNELS][2] =
116 { WAVE_SPEAKER_FRONT_LEFT, AOUT_CHAN_LEFT },
117 { WAVE_SPEAKER_FRONT_RIGHT, AOUT_CHAN_RIGHT },
118 { WAVE_SPEAKER_FRONT_CENTER, AOUT_CHAN_CENTER },
119 { WAVE_SPEAKER_LOW_FREQUENCY, AOUT_CHAN_LFE },
120 { WAVE_SPEAKER_BACK_LEFT, AOUT_CHAN_REARLEFT },
121 { WAVE_SPEAKER_BACK_RIGHT, AOUT_CHAN_REARRIGHT },
122 { WAVE_SPEAKER_BACK_CENTER, AOUT_CHAN_REARCENTER },
123 { WAVE_SPEAKER_SIDE_LEFT, AOUT_CHAN_MIDDLELEFT },
124 { WAVE_SPEAKER_SIDE_RIGHT, AOUT_CHAN_MIDDLERIGHT },
127 static const uint32_t wfx_chans_order[MAPPED_WFX_CHANNELS + 1] =
129 AOUT_CHAN_LEFT,
130 AOUT_CHAN_RIGHT,
131 AOUT_CHAN_CENTER,
132 AOUT_CHAN_LFE,
133 AOUT_CHAN_REARLEFT,
134 AOUT_CHAN_REARRIGHT,
135 AOUT_CHAN_REARCENTER,
136 AOUT_CHAN_MIDDLELEFT,
137 AOUT_CHAN_MIDDLERIGHT,
141 /*****************************************************************************
142 * Local prototypes
143 *****************************************************************************/
144 static int OpenDecoder ( vlc_object_t * );
145 static void CloseDecoder ( vlc_object_t * );
147 #ifdef ENABLE_SOUT
148 static int OpenEncoder ( vlc_object_t * );
149 static void CloseEncoder ( vlc_object_t * );
150 #endif
152 static int DecodeBlock( decoder_t *, block_t * );
153 static void Flush( decoder_t * );
155 /*****************************************************************************
156 * Module descriptor
157 *****************************************************************************/
158 vlc_module_begin ()
160 set_category( CAT_INPUT )
161 set_subcategory( SUBCAT_INPUT_ACODEC )
162 add_shortcut( "flac" )
164 set_description( N_("Flac audio decoder") )
165 set_capability( "audio decoder", 100 )
166 set_callbacks( OpenDecoder, CloseDecoder )
168 #ifdef ENABLE_SOUT
169 add_submodule ()
170 add_shortcut( "flac" )
171 set_description( N_("Flac audio encoder") )
172 set_capability( "encoder", 100 )
173 set_callbacks( OpenEncoder, CloseEncoder )
174 #endif
176 vlc_module_end ()
178 /*****************************************************************************
179 * Interleave: helper function to interleave channels
180 *****************************************************************************/
181 static void Interleave( int32_t *p_out, const int32_t * const *pp_in,
182 const uint8_t *restrict pi_index, unsigned i_nb_channels,
183 unsigned i_samples, unsigned bits )
185 unsigned shift = 32 - bits;
187 for( unsigned j = 0; j < i_samples; j++ )
188 for( unsigned i = 0; i < i_nb_channels; i++ )
190 union { int32_t i; uint32_t u; } spl;
192 spl.u = ((uint32_t)pp_in[pi_index[i]][j]) << shift;
193 p_out[j * i_nb_channels + i] = spl.i;
197 /*****************************************************************************
198 * DecoderSetOutputFormat: helper function to convert and check frame format
199 *****************************************************************************/
200 static int DecoderSetOutputFormat( unsigned i_channels, unsigned i_rate,
201 unsigned i_streaminfo_rate,
202 unsigned i_bitspersample,
203 audio_format_t *fmt,
204 uint8_t *pi_channels_reorder )
206 if( i_channels == 0 || i_channels > FLAC__MAX_CHANNELS ||
207 i_bitspersample == 0 || (i_rate == 0 && i_streaminfo_rate == 0) )
208 return VLC_EGENERIC;
210 fmt->i_channels = i_channels;
211 fmt->i_rate = (i_rate > 0 ) ? i_rate : i_streaminfo_rate;
212 fmt->i_physical_channels = pi_channels_maps[i_channels];
213 memcpy( pi_channels_reorder, ppi_reorder[i_channels], i_channels );
214 fmt->i_bitspersample = i_bitspersample;
216 return VLC_SUCCESS;
219 /*****************************************************************************
220 * DecoderWriteCallback: called by libflac to output decoded samples
221 *****************************************************************************/
222 static FLAC__StreamDecoderWriteStatus
223 DecoderWriteCallback( const FLAC__StreamDecoder *decoder,
224 const FLAC__Frame *frame,
225 const FLAC__int32 *const buffer[], void *client_data )
227 VLC_UNUSED(decoder);
228 decoder_t *p_dec = (decoder_t *)client_data;
229 decoder_sys_t *p_sys = p_dec->p_sys;
231 if( DecoderSetOutputFormat( frame->header.channels,
232 frame->header.sample_rate,
233 p_sys->b_stream_info ? p_sys->stream_info.sample_rate : 0,
234 frame->header.bits_per_sample,
235 &p_dec->fmt_out.audio,
236 p_sys->rgi_channels_reorder ) )
237 return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
239 if( p_sys->end_date.i_divider_num != p_dec->fmt_out.audio.i_rate )
241 if( p_sys->end_date.i_divider_num > 0 )
242 date_Change( &p_sys->end_date, p_dec->fmt_out.audio.i_rate, 1 );
243 else
244 date_Init( &p_sys->end_date, p_dec->fmt_out.audio.i_rate, 1 );
247 if( decoder_UpdateAudioFormat( p_dec ) )
248 return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
250 if( date_Get( &p_sys->end_date ) <= VLC_TS_INVALID )
251 return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
253 p_sys->p_aout_buffer =
254 decoder_NewAudioBuffer( p_dec, frame->header.blocksize );
256 if( p_sys->p_aout_buffer == NULL )
257 return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
259 Interleave( (int32_t *)p_sys->p_aout_buffer->p_buffer, buffer,
260 p_sys->rgi_channels_reorder,
261 frame->header.channels, frame->header.blocksize,
262 frame->header.bits_per_sample );
264 /* Date management (already done by packetizer) */
265 p_sys->p_aout_buffer->i_pts = date_Get( &p_sys->end_date );
266 p_sys->p_aout_buffer->i_length =
267 date_Increment( &p_sys->end_date, frame->header.blocksize ) -
268 p_sys->p_aout_buffer->i_pts;
270 return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
273 /*****************************************************************************
274 * DecoderReadCallback: called by libflac when it needs more data
275 *****************************************************************************/
276 static FLAC__StreamDecoderReadStatus
277 DecoderReadCallback( const FLAC__StreamDecoder *decoder, FLAC__byte buffer[],
278 size_t *bytes, void *client_data )
280 VLC_UNUSED(decoder);
281 decoder_t *p_dec = (decoder_t *)client_data;
282 decoder_sys_t *p_sys = p_dec->p_sys;
284 if( p_sys->p_block && p_sys->p_block->i_buffer )
286 *bytes = __MIN(*bytes, p_sys->p_block->i_buffer);
287 memcpy( buffer, p_sys->p_block->p_buffer, *bytes );
288 p_sys->p_block->i_buffer -= *bytes;
289 p_sys->p_block->p_buffer += *bytes;
291 else
293 *bytes = 0;
294 return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
297 return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
300 /*****************************************************************************
301 * DecoderMetadataCallback: called by libflac to when it encounters metadata
302 *****************************************************************************/
303 static void DecoderMetadataCallback( const FLAC__StreamDecoder *decoder,
304 const FLAC__StreamMetadata *metadata,
305 void *client_data )
307 VLC_UNUSED(decoder);
308 decoder_t *p_dec = (decoder_t *)client_data;
309 decoder_sys_t *p_sys = p_dec->p_sys;
311 switch(metadata->type)
313 case FLAC__METADATA_TYPE_STREAMINFO:
314 /* Setup the format */
315 DecoderSetOutputFormat( metadata->data.stream_info.channels,
316 metadata->data.stream_info.sample_rate,
317 metadata->data.stream_info.sample_rate,
318 metadata->data.stream_info.bits_per_sample,
319 &p_dec->fmt_out.audio, p_sys->rgi_channels_reorder );
321 msg_Dbg( p_dec, "channels:%d samplerate:%d bitspersamples:%d",
322 p_dec->fmt_out.audio.i_channels, p_dec->fmt_out.audio.i_rate,
323 p_dec->fmt_out.audio.i_bitspersample );
325 p_sys->b_stream_info = true;
326 p_sys->stream_info = metadata->data.stream_info;
328 date_Init( &p_sys->end_date, p_dec->fmt_out.audio.i_rate, 1 );
329 date_Set( &p_sys->end_date, VLC_TS_INVALID );
330 break;
332 case FLAC__METADATA_TYPE_VORBIS_COMMENT:
333 for( FLAC__uint32 i=0; i<metadata->data.vorbis_comment.num_comments; i++ )
335 const FLAC__StreamMetadata_VorbisComment_Entry *comment =
336 &metadata->data.vorbis_comment.comments[i];
337 /* Check for custom WAVEFORMATEX channel ordering */
338 if( comment->length > 34 &&
339 !strncmp( "WAVEFORMATEXTENSIBLE_CHANNEL_MASK=", (char *) comment->entry, 34 ) )
341 char *endptr = (char *) &comment->entry[34] + comment->length;
342 const uint32_t i_wfxmask = strtoul( (char *) &comment->entry[34], &endptr, 16 );
343 const unsigned i_wfxchannels = popcount( i_wfxmask );
344 if( i_wfxchannels > 0 && i_wfxchannels <= AOUT_CHAN_MAX )
346 /* Create the vlc bitmap from wfx channels */
347 uint32_t i_vlcmask = 0;
348 for( uint32_t i_chan = 1; i_chan && i_chan <= i_wfxmask; i_chan <<= 1 )
350 if( (i_chan & i_wfxmask) == 0 )
351 continue;
352 for( size_t i=0; i<MAPPED_WFX_CHANNELS; i++ )
354 if( wfx_remapping[i][0] == i_chan )
355 i_vlcmask |= wfx_remapping[i][1];
358 /* Check if we have the 1 to 1 mapping */
359 if( popcount(i_vlcmask) != i_wfxchannels )
361 msg_Warn( p_dec, "Unsupported channel mask %x", i_wfxmask );
362 return;
365 /* Compute the remapping */
366 uint8_t neworder[AOUT_CHAN_MAX] = {0};
367 aout_CheckChannelReorder( wfx_chans_order, NULL,
368 i_vlcmask, neworder );
370 /* /!\ Invert our source/dest reordering,
371 * as Interleave() here works source indexes */
372 for( unsigned i=0; i<i_wfxchannels; i++ )
373 p_sys->rgi_channels_reorder[neworder[i]] = i;
375 p_dec->fmt_out.audio.i_physical_channels = i_vlcmask;
376 p_dec->fmt_out.audio.i_channels = i_wfxchannels;
379 break;
383 default:
384 break;
388 /*****************************************************************************
389 * DecoderErrorCallback: called when the libflac decoder encounters an error
390 *****************************************************************************/
391 static void DecoderErrorCallback( const FLAC__StreamDecoder *decoder,
392 FLAC__StreamDecoderErrorStatus status,
393 void *client_data )
395 VLC_UNUSED(decoder);
396 decoder_t *p_dec = (decoder_t *)client_data;
398 switch( status )
400 case FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC:
401 msg_Warn( p_dec, "an error in the stream caused the decoder to "
402 "lose synchronization." );
403 break;
404 case FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER:
405 msg_Err( p_dec, "the decoder encountered a corrupted frame header." );
406 break;
407 case FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH:
408 msg_Err( p_dec, "frame's data did not match the CRC in the "
409 "footer." );
410 break;
411 case FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM:
412 msg_Err( p_dec, "The decoder encountered reserved fields in use in "
413 "the stream." );
414 break;
415 default:
416 msg_Err( p_dec, "got decoder error: %d", status );
419 FLAC__stream_decoder_flush( p_dec->p_sys->p_flac );
420 return;
422 /*****************************************************************************
423 * OpenDecoder: probe the decoder and return score
424 *****************************************************************************/
425 static int OpenDecoder( vlc_object_t *p_this )
427 decoder_t *p_dec = (decoder_t*)p_this;
428 decoder_sys_t *p_sys;
430 if( p_dec->fmt_in.i_codec != VLC_CODEC_FLAC )
432 return VLC_EGENERIC;
435 /* Allocate the memory needed to store the decoder's structure */
436 if( ( p_dec->p_sys = p_sys = malloc(sizeof(*p_sys)) ) == NULL )
437 return VLC_ENOMEM;
439 /* Misc init */
440 p_sys->b_stream_info = false;
441 memset(p_sys->rgi_channels_reorder, 0, AOUT_CHAN_MAX);
442 p_sys->p_block = NULL;
444 /* Take care of flac init */
445 if( !(p_sys->p_flac = FLAC__stream_decoder_new()) )
447 msg_Err( p_dec, "FLAC__stream_decoder_new() failed" );
448 free( p_sys );
449 return VLC_EGENERIC;
452 /* Enable STREAMINFO + COMMENTS */
453 FLAC__stream_decoder_set_metadata_respond( p_sys->p_flac,
454 FLAC__METADATA_TYPE_VORBIS_COMMENT );
456 #ifdef USE_NEW_FLAC_API
457 if( FLAC__stream_decoder_init_stream( p_sys->p_flac,
458 DecoderReadCallback,
459 NULL,
460 NULL,
461 NULL,
462 NULL,
463 DecoderWriteCallback,
464 DecoderMetadataCallback,
465 DecoderErrorCallback,
466 p_dec )
467 != FLAC__STREAM_DECODER_INIT_STATUS_OK )
469 msg_Err( p_dec, "FLAC__stream_decoder_init_stream() failed" );
470 FLAC__stream_decoder_delete( p_sys->p_flac );
471 free( p_sys );
472 return VLC_EGENERIC;
474 #else
475 FLAC__stream_decoder_set_read_callback( p_sys->p_flac,
476 DecoderReadCallback );
477 FLAC__stream_decoder_set_write_callback( p_sys->p_flac,
478 DecoderWriteCallback );
479 FLAC__stream_decoder_set_metadata_callback( p_sys->p_flac,
480 DecoderMetadataCallback );
481 FLAC__stream_decoder_set_error_callback( p_sys->p_flac,
482 DecoderErrorCallback );
483 FLAC__stream_decoder_set_client_data( p_sys->p_flac, p_dec );
485 FLAC__stream_decoder_init( p_sys->p_flac );
486 #endif
488 /* Set output properties */
489 p_dec->fmt_out.i_codec = VLC_CODEC_S32N;
491 /* Set callbacks */
492 p_dec->pf_decode = DecodeBlock;
493 p_dec->pf_flush = Flush;
495 return VLC_SUCCESS;
498 /*****************************************************************************
499 * CloseDecoder: flac decoder destruction
500 *****************************************************************************/
501 static void CloseDecoder( vlc_object_t *p_this )
503 decoder_t *p_dec = (decoder_t *)p_this;
504 decoder_sys_t *p_sys = p_dec->p_sys;
506 FLAC__stream_decoder_finish( p_sys->p_flac );
507 FLAC__stream_decoder_delete( p_sys->p_flac );
509 if( p_sys->p_block )
510 block_Release( p_sys->p_block );
511 free( p_sys );
514 /*****************************************************************************
515 * ProcessHeader: process Flac header.
516 *****************************************************************************/
517 static void ProcessHeader( decoder_t *p_dec )
519 decoder_sys_t *p_sys = p_dec->p_sys;
521 if( !p_dec->fmt_in.i_extra )
522 return;
524 /* Decode STREAMINFO */
525 msg_Dbg( p_dec, "decode STREAMINFO" );
526 int i_extra = p_dec->fmt_in.i_extra;
528 static const char header[4] = { 'f', 'L', 'a', 'C' };
530 if( memcmp( p_dec->fmt_in.p_extra, header, 4 ) )
531 i_extra += 8;
533 p_sys->p_block = block_Alloc( i_extra );
534 if( p_sys->p_block == NULL )
535 return;
537 uint8_t *p_data = p_sys->p_block->p_buffer;
538 if( i_extra != p_dec->fmt_in.i_extra )
540 memcpy( p_data, header, 4);
541 p_data[4] = 0x80 | 0; /* STREAMINFO faked as last block */
542 p_data[5] = 0;
543 p_data[6] = 0;
544 p_data[7] = 34; /* block size */
545 p_data += 8;
547 memcpy( p_data, p_dec->fmt_in.p_extra, p_dec->fmt_in.i_extra );
549 FLAC__stream_decoder_process_until_end_of_metadata( p_sys->p_flac );
550 msg_Dbg( p_dec, "STREAMINFO decoded" );
552 block_Release( p_sys->p_block );
553 p_sys->p_block = NULL;
556 /*****************************************************************************
557 * decoder_state_error: print meaningful error messages
558 *****************************************************************************/
559 static void decoder_state_error( decoder_t *p_dec,
560 FLAC__StreamDecoderState state )
562 switch ( state )
564 case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
565 msg_Dbg( p_dec, "the decoder is ready to search for metadata." );
566 break;
567 case FLAC__STREAM_DECODER_READ_METADATA:
568 msg_Dbg( p_dec, "the decoder is ready to or is in the process of "
569 "reading metadata." );
570 break;
571 case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
572 msg_Dbg( p_dec, "the decoder is ready to or is in the process of "
573 "searching for the frame sync code." );
574 break;
575 case FLAC__STREAM_DECODER_READ_FRAME:
576 msg_Dbg( p_dec, "the decoder is ready to or is in the process of "
577 "reading a frame." );
578 break;
579 case FLAC__STREAM_DECODER_END_OF_STREAM:
580 msg_Dbg( p_dec, "the decoder has reached the end of the stream." );
581 break;
582 #ifdef USE_NEW_FLAC_API
583 case FLAC__STREAM_DECODER_OGG_ERROR:
584 msg_Err( p_dec, "error occurred in the Ogg layer." );
585 break;
586 case FLAC__STREAM_DECODER_SEEK_ERROR:
587 msg_Err( p_dec, "error occurred while seeking." );
588 break;
589 #endif
590 case FLAC__STREAM_DECODER_ABORTED:
591 msg_Warn( p_dec, "the decoder was aborted by the read callback." );
592 break;
593 #ifndef USE_NEW_FLAC_API
594 case FLAC__STREAM_DECODER_UNPARSEABLE_STREAM:
595 msg_Warn( p_dec, "the decoder encountered reserved fields in use "
596 "in the stream." );
597 break;
598 #endif
599 case FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR:
600 msg_Err( p_dec, "error when allocating memory." );
601 break;
602 #ifndef USE_NEW_FLAC_API
603 case FLAC__STREAM_DECODER_ALREADY_INITIALIZED:
604 msg_Err( p_dec, "FLAC__stream_decoder_init() was called when the "
605 "decoder was already initialized, usually because "
606 "FLAC__stream_decoder_finish() was not called." );
607 break;
608 case FLAC__STREAM_DECODER_INVALID_CALLBACK:
609 msg_Err( p_dec, "FLAC__stream_decoder_init() was called without "
610 "all callbacks being set." );
611 break;
612 #endif
613 case FLAC__STREAM_DECODER_UNINITIALIZED:
614 msg_Err( p_dec, "decoder in uninitialized state." );
615 break;
616 default:
617 msg_Warn(p_dec, "unknown error" );
621 /*****************************************************************************
622 * Flush:
623 *****************************************************************************/
624 static void Flush( decoder_t *p_dec )
626 decoder_sys_t *p_sys = p_dec->p_sys;
628 if( p_sys->b_stream_info )
629 FLAC__stream_decoder_flush( p_dec->p_sys->p_flac );
630 date_Set( &p_sys->end_date, 0 );
633 /****************************************************************************
634 * DecodeBlock: the whole thing
635 ****************************************************************************/
636 static int DecodeBlock( decoder_t *p_dec, block_t *p_block )
638 decoder_sys_t *p_sys = p_dec->p_sys;
640 if( p_block == NULL ) /* No Drain */
641 return VLCDEC_SUCCESS;
642 if( p_block->i_flags & (BLOCK_FLAG_DISCONTINUITY | BLOCK_FLAG_CORRUPTED) )
644 Flush( p_dec );
645 if( p_block->i_flags & BLOCK_FLAG_CORRUPTED )
647 block_Release( p_block );
648 return VLCDEC_SUCCESS;
652 if( !p_sys->b_stream_info )
654 ProcessHeader( p_dec );
655 if( !p_sys->b_stream_info )
657 block_Release( p_block );
658 return VLCDEC_ECRITICAL;
662 p_sys->p_block = p_block;
664 if( p_sys->p_block->i_pts > VLC_TS_INVALID &&
665 p_sys->p_block->i_pts != date_Get( &p_sys->end_date ) )
666 date_Set( &p_sys->end_date, p_sys->p_block->i_pts );
668 p_sys->p_aout_buffer = 0;
670 if( !FLAC__stream_decoder_process_single( p_sys->p_flac ) )
672 decoder_state_error( p_dec,
673 FLAC__stream_decoder_get_state( p_sys->p_flac ) );
674 FLAC__stream_decoder_flush( p_dec->p_sys->p_flac );
677 /* If the decoder is in the "aborted" state,
678 * FLAC__stream_decoder_process_single() won't return an error. */
679 switch ( FLAC__stream_decoder_get_state(p_dec->p_sys->p_flac) )
681 case FLAC__STREAM_DECODER_ABORTED:
682 FLAC__stream_decoder_flush( p_dec->p_sys->p_flac );
683 break;
684 case FLAC__STREAM_DECODER_END_OF_STREAM:
685 FLAC__stream_decoder_reset( p_dec->p_sys->p_flac );
686 break;
687 default:
688 break;
691 block_Release( p_sys->p_block );
692 p_sys->p_block = NULL;
694 if( p_sys->p_aout_buffer != NULL )
695 decoder_QueueAudio( p_dec, p_sys->p_aout_buffer );
696 return VLCDEC_SUCCESS;
699 #ifdef ENABLE_SOUT
701 /*****************************************************************************
702 * encoder_sys_t : flac encoder descriptor
703 *****************************************************************************/
704 struct encoder_sys_t
707 * Input properties
709 int i_headers;
711 int i_samples_delay;
713 FLAC__int32 *p_buffer;
714 unsigned int i_buffer;
716 block_t *p_chain;
719 * FLAC properties
721 FLAC__StreamEncoder *p_flac;
722 FLAC__StreamMetadata_StreamInfo stream_info;
725 * Common properties
727 mtime_t i_pts;
730 #define STREAMINFO_SIZE 34
732 static block_t *Encode( encoder_t *, block_t * );
734 /*****************************************************************************
735 * EncoderWriteCallback: called by libflac to output encoded samples
736 *****************************************************************************/
737 static FLAC__StreamEncoderWriteStatus
738 EncoderWriteCallback( const FLAC__StreamEncoder *encoder,
739 const FLAC__byte buffer[],
740 size_t bytes, unsigned samples,
741 unsigned current_frame, void *client_data )
743 VLC_UNUSED(encoder); VLC_UNUSED(current_frame);
744 encoder_t *p_enc = (encoder_t *)client_data;
745 encoder_sys_t *p_sys = p_enc->p_sys;
746 block_t *p_block;
748 if( samples == 0 )
750 if( p_sys->i_headers == 1 )
752 msg_Dbg( p_enc, "Writing STREAMINFO: %zu", bytes );
754 /* Backup the STREAMINFO metadata block */
755 p_enc->fmt_out.i_extra = STREAMINFO_SIZE + 8;
756 p_enc->fmt_out.p_extra = xmalloc( STREAMINFO_SIZE + 8);
757 memcpy(p_enc->fmt_out.p_extra, "fLaC", 4);
758 memcpy((uint8_t*)p_enc->fmt_out.p_extra + 4, buffer, STREAMINFO_SIZE );
759 /* Fake this as the last metadata block */
760 ((uint8_t*)p_enc->fmt_out.p_extra)[4] |= 0x80;
762 p_sys->i_headers++;
763 return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
766 p_block = block_Alloc( bytes );
767 memcpy( p_block->p_buffer, buffer, bytes );
769 p_block->i_dts = p_block->i_pts = p_sys->i_pts;
771 p_sys->i_samples_delay -= samples;
773 p_block->i_length = (mtime_t)1000000 *
774 (mtime_t)samples / (mtime_t)p_enc->fmt_in.audio.i_rate;
776 /* Update pts */
777 p_sys->i_pts += p_block->i_length;
779 block_ChainAppend( &p_sys->p_chain, p_block );
781 return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
783 /*****************************************************************************
784 * EncoderMetadataCallback: called by libflac to output metadata
785 *****************************************************************************/
786 static void EncoderMetadataCallback( const FLAC__StreamEncoder *encoder,
787 const FLAC__StreamMetadata *metadata,
788 void *client_data )
790 VLC_UNUSED(encoder);
791 encoder_t *p_enc = (encoder_t *)client_data;
793 msg_Err( p_enc, "MetadataCallback: %i", metadata->type );
794 return;
797 /*****************************************************************************
798 * OpenEncoder: probe the encoder and return score
799 *****************************************************************************/
800 static int OpenEncoder( vlc_object_t *p_this )
802 encoder_t *p_enc = (encoder_t *)p_this;
803 encoder_sys_t *p_sys;
805 if( p_enc->fmt_out.i_codec != VLC_CODEC_FLAC &&
806 !p_enc->obj.force )
808 return VLC_EGENERIC;
811 /* Allocate the memory needed to store the decoder's structure */
812 if( ( p_sys = (encoder_sys_t *)malloc(sizeof(encoder_sys_t)) ) == NULL )
813 return VLC_ENOMEM;
814 p_enc->p_sys = p_sys;
815 p_enc->pf_encode_audio = Encode;
816 p_enc->fmt_out.i_codec = VLC_CODEC_FLAC;
818 p_sys->i_headers = 0;
819 p_sys->p_buffer = 0;
820 p_sys->i_buffer = 0;
821 p_sys->i_samples_delay = 0;
823 /* Create flac encoder */
824 if( !(p_sys->p_flac = FLAC__stream_encoder_new()) )
826 msg_Err( p_enc, "FLAC__stream_encoder_new() failed" );
827 free( p_sys );
828 return VLC_EGENERIC;
831 FLAC__stream_encoder_set_streamable_subset( p_sys->p_flac, 1 );
832 FLAC__stream_encoder_set_channels( p_sys->p_flac,
833 p_enc->fmt_in.audio.i_channels );
834 FLAC__stream_encoder_set_sample_rate( p_sys->p_flac,
835 p_enc->fmt_in.audio.i_rate );
836 FLAC__stream_encoder_set_bits_per_sample( p_sys->p_flac, 16 );
837 p_enc->fmt_in.i_codec = VLC_CODEC_S16N;
839 /* Get and store the STREAMINFO metadata block as a p_extra */
840 p_sys->p_chain = 0;
842 #ifdef USE_NEW_FLAC_API
843 if( FLAC__stream_encoder_init_stream( p_sys->p_flac,
844 EncoderWriteCallback,
845 NULL,
846 NULL,
847 EncoderMetadataCallback,
848 p_enc )
849 != FLAC__STREAM_ENCODER_INIT_STATUS_OK )
851 msg_Err( p_enc, "FLAC__stream_encoder_init_stream() failed" );
852 FLAC__stream_encoder_delete( p_sys->p_flac );
853 free( p_sys );
854 return VLC_EGENERIC;
856 #else
857 FLAC__stream_encoder_set_write_callback( p_sys->p_flac,
858 EncoderWriteCallback );
859 FLAC__stream_encoder_set_metadata_callback( p_sys->p_flac,
860 EncoderMetadataCallback );
861 FLAC__stream_encoder_set_client_data( p_sys->p_flac, p_enc );
863 FLAC__stream_encoder_init( p_sys->p_flac );
864 #endif
866 return VLC_SUCCESS;
869 /****************************************************************************
870 * Encode: the whole thing
871 ****************************************************************************
872 * This function spits out ogg packets.
873 ****************************************************************************/
874 static block_t *Encode( encoder_t *p_enc, block_t *p_aout_buf )
876 encoder_sys_t *p_sys = p_enc->p_sys;
877 block_t *p_chain;
879 /* FIXME: p_aout_buf is NULL when it's time to flush*/
880 if( unlikely( !p_aout_buf ) ) return NULL;
882 p_sys->i_pts = p_aout_buf->i_pts -
883 (mtime_t)1000000 * (mtime_t)p_sys->i_samples_delay /
884 (mtime_t)p_enc->fmt_in.audio.i_rate;
886 p_sys->i_samples_delay += p_aout_buf->i_nb_samples;
888 /* Convert samples to FLAC__int32 */
889 if( p_sys->i_buffer < p_aout_buf->i_buffer * sizeof(FLAC__int32) )
891 p_sys->p_buffer =
892 xrealloc( p_sys->p_buffer, p_aout_buf->i_buffer * sizeof(FLAC__int32) );
893 p_sys->i_buffer = p_aout_buf->i_buffer * 2;
896 for( unsigned i = 0 ; i < p_aout_buf->i_buffer / 2 ; i++ )
898 p_sys->p_buffer[i]= ((int16_t *)p_aout_buf->p_buffer)[i];
901 FLAC__stream_encoder_process_interleaved( p_sys->p_flac, p_sys->p_buffer,
902 p_aout_buf->i_nb_samples );
904 p_chain = p_sys->p_chain;
905 p_sys->p_chain = 0;
907 return p_chain;
910 /*****************************************************************************
911 * CloseEncoder: encoder destruction
912 *****************************************************************************/
913 static void CloseEncoder( vlc_object_t *p_this )
915 encoder_t *p_enc = (encoder_t *)p_this;
916 encoder_sys_t *p_sys = p_enc->p_sys;
918 FLAC__stream_encoder_delete( p_sys->p_flac );
920 free( p_sys->p_buffer );
921 free( p_sys );
923 #endif