]> git.sesse.net Git - vlc/blob - modules/codec/flacdec.c
* ALL: final improvements to the decoders/packetizers api.
[vlc] / modules / codec / flacdec.c
1 /*****************************************************************************
2  * flac.c: flac decoder module making use of libflac
3  *****************************************************************************
4  * Copyright (C) 1999-2001 VideoLAN
5  * $Id: flacdec.c,v 1.5 2003/11/16 21:07:30 gbazin Exp $
6  *
7  * Authors: Sigmund Augdal <sigmunau@idi.ntnu.no>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  * 
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
22  *****************************************************************************/
23
24 /*****************************************************************************
25  * Preamble
26  *****************************************************************************/
27 #include <stdlib.h>                                      /* malloc(), free() */
28 #include <string.h>                                    /* memcpy(), memset() */
29 #include <errno.h>
30
31 #include <vlc/vlc.h>
32 #include <vlc/aout.h>
33 #include <vlc/decoder.h>
34 #include <input_ext-dec.h>
35
36 #include <vlc/input.h>
37
38 #include <FLAC/stream_decoder.h>
39
40 /*****************************************************************************
41  * dec_thread_t : flac decoder thread descriptor
42  *****************************************************************************/
43 typedef struct dec_thread_t
44 {
45     /*
46      * Thread properties
47      */
48     vlc_thread_t        thread_id;                /* id for thread functions */
49
50     /*
51      * Input properties
52      */
53     decoder_fifo_t         *p_fifo;            /* stores the PES stream data */
54     pes_packet_t           *p_pes;            /* current PES we are decoding */
55     int                     i_last_pes_pos;             /* possition into pes*/
56
57     int i_tot;
58     /*
59      * libflac decoder struct
60      */
61     FLAC__StreamDecoder *p_decoder;
62     
63     /*
64      * Output properties
65      */
66     aout_instance_t        *p_aout;
67     aout_input_t           *p_aout_input;
68     audio_sample_format_t   output_format;
69     audio_date_t            end_date;
70     mtime_t                 pts;
71
72 } dec_thread_t;
73
74 static int pi_channels_maps[6] =
75 {
76     0,
77     AOUT_CHAN_CENTER,   AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT,
78     AOUT_CHAN_CENTER | AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT,
79     AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_REARLEFT
80      | AOUT_CHAN_REARRIGHT,
81     AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_CENTER
82      | AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT
83 };
84
85 /*****************************************************************************
86  * Local prototypes
87  *****************************************************************************/
88 static int  OpenDecoder  ( vlc_object_t * );
89 static int  RunDecoder   ( decoder_fifo_t * );
90 static void CloseDecoder ( dec_thread_t * );
91
92 static FLAC__StreamDecoderReadStatus DecoderReadCallback (const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], unsigned *bytes, void *client_data);
93
94 static FLAC__StreamDecoderWriteStatus DecoderWriteCallback (const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 *const buffer[], void *client_data);
95
96 static void DecoderMetadataCallback (const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
97 static void DecoderErrorCallback (const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
98 static void Interleave32( int32_t *p_out, const int32_t * const *pp_in,
99                         int i_nb_channels, int i_samples );
100 static void Interleave16( int16_t *p_out, const int32_t * const *pp_in,
101                         int i_nb_channels, int i_samples );
102 static void decoder_state_error( dec_thread_t *p_dec, FLAC__StreamDecoderState state );
103 /*****************************************************************************
104  * Module descriptor
105  *****************************************************************************/
106 vlc_module_begin();
107     set_description( _("flac audio decoder") );
108     set_capability( "decoder", 100 );
109     set_callbacks( OpenDecoder, NULL );
110 vlc_module_end();
111
112 /*****************************************************************************
113  * OpenDecoder: probe the decoder and return score
114  *****************************************************************************/
115 static int OpenDecoder( vlc_object_t *p_this )
116 {
117     decoder_t *p_dec = (decoder_t*)p_this;
118
119     if( p_dec->fmt_in.i_codec != VLC_FOURCC('f','l','a','c') )
120     {
121         return VLC_EGENERIC;
122     }
123
124     p_dec->pf_run = RunDecoder;
125     return VLC_SUCCESS;
126 }
127
128 /*****************************************************************************
129  * RunDecoder: the vorbis decoder
130  *****************************************************************************/
131 static int RunDecoder( decoder_fifo_t * p_fifo )
132 {
133     dec_thread_t *p_dec;
134     FLAC__StreamDecoderState state;
135     /* Allocate the memory needed to store the thread's structure */
136     if( (p_dec = (dec_thread_t *)malloc (sizeof(dec_thread_t)) )
137             == NULL)
138     {
139         msg_Err( p_fifo, "out of memory" );
140         goto error;
141     }
142
143     /* Initialize the thread properties */
144     memset( p_dec, 0, sizeof(dec_thread_t) );
145     p_dec->p_fifo = p_fifo;
146     p_dec->p_pes  = NULL;
147     p_dec->p_decoder = FLAC__stream_decoder_new();
148     if( p_dec->p_decoder == NULL )
149     {
150         msg_Err( p_fifo, "FLAC__stream_decoder_new() failed" );
151         goto error;
152     }
153     FLAC__stream_decoder_set_read_callback( p_dec->p_decoder,
154                                                DecoderReadCallback );
155     FLAC__stream_decoder_set_write_callback( p_dec->p_decoder,
156                                                DecoderWriteCallback );
157     FLAC__stream_decoder_set_metadata_callback( p_dec->p_decoder,
158                                                DecoderMetadataCallback );
159     FLAC__stream_decoder_set_error_callback( p_dec->p_decoder,
160                                                DecoderErrorCallback );
161     FLAC__stream_decoder_set_client_data( p_dec->p_decoder,
162                                              p_dec );
163
164
165     FLAC__stream_decoder_init( p_dec->p_decoder );
166     if ( !FLAC__stream_decoder_process_until_end_of_metadata( p_dec->p_decoder ) )
167     {
168         state = FLAC__stream_decoder_get_state( p_dec->p_decoder );
169         decoder_state_error( p_dec, state );                
170         goto error;
171     }
172
173     aout_DateInit( &p_dec->end_date, p_dec->output_format.i_rate );
174     p_dec->p_aout = NULL;
175     p_dec->p_aout_input = aout_DecNew( p_dec->p_fifo,
176                                        &p_dec->p_aout,
177                                        &p_dec->output_format );
178
179     if( p_dec->p_aout_input == NULL )
180     {
181         msg_Err( p_dec->p_fifo, "failed to create aout fifo" );
182         goto error;
183     }
184     
185     /* flac decoder thread's main loop */
186     while( (!p_dec->p_fifo->b_die) && (!p_dec->p_fifo->b_error) )
187     { 
188         if ( !FLAC__stream_decoder_process_single( p_dec->p_decoder ) )
189         {
190             state = FLAC__stream_decoder_get_state( p_dec->p_decoder );
191             decoder_state_error( p_dec, state );
192         }
193     }
194
195     /* If b_error is set, the vorbis decoder thread enters the error loop */
196     if( p_dec->p_fifo->b_error )
197     {
198         DecoderError( p_dec->p_fifo );
199     }
200
201     /* End of the vorbis decoder thread */
202     CloseDecoder( p_dec );
203
204     return 0;
205
206  error:
207     DecoderError( p_fifo );
208     if( p_dec )
209     {
210         if( p_dec->p_fifo )
211             p_dec->p_fifo->b_error = 1;
212
213         /* End of the vorbis decoder thread */
214         CloseDecoder( p_dec );
215     }
216
217     return -1;
218 }
219
220 /*****************************************************************************
221  * CloseDecoder: closes the decoder
222  *****************************************************************************/
223 static void CloseDecoder ( dec_thread_t *p_dec )
224 {
225     if( p_dec->p_aout_input != NULL )
226     {
227         aout_DecDelete( p_dec->p_aout, p_dec->p_aout_input );
228     }
229
230     if( p_dec )
231     {
232         if( p_dec->p_pes )
233             input_DeletePES( p_dec->p_fifo->p_packets_mgt, p_dec->p_pes );
234         FLAC__stream_decoder_finish( p_dec->p_decoder );
235         FLAC__stream_decoder_delete( p_dec->p_decoder );
236         free( p_dec );
237     }
238
239 }
240
241
242     
243 /*****************************************************************************
244  * DecoderReadCallback: called by libflac when it needs more data
245  *****************************************************************************/
246 static FLAC__StreamDecoderReadStatus DecoderReadCallback (const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], unsigned *bytes, void *client_data)
247 {
248     dec_thread_t *p_dec = (dec_thread_t *)client_data;
249     if( !p_dec->i_last_pes_pos )
250     {
251         input_DeletePES( p_dec->p_fifo->p_packets_mgt,
252                          p_dec->p_pes );
253         input_ExtractPES( p_dec->p_fifo, &p_dec->p_pes );
254         if( !p_dec->p_pes )
255         {
256             return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
257         }
258     }
259     p_dec->pts = p_dec->p_pes->i_pts;
260     if( ( p_dec->p_pes->i_pes_size - p_dec->i_last_pes_pos ) > *bytes )
261     {
262         p_dec->p_fifo->p_vlc->pf_memcpy( buffer,
263                                          p_dec->p_pes->p_first->p_payload_start
264                                          + p_dec->i_last_pes_pos,
265                                          *bytes );
266         p_dec->i_last_pes_pos += *bytes;
267     }
268     else
269     {
270         p_dec->p_fifo->p_vlc->pf_memcpy( buffer,
271                                          p_dec->p_pes->p_first->p_payload_start
272                                          + p_dec->i_last_pes_pos,
273                                          p_dec->p_pes->i_pes_size
274                                          - p_dec->i_last_pes_pos );
275         *bytes = p_dec->p_pes->i_pes_size - p_dec->i_last_pes_pos ;
276         p_dec->i_last_pes_pos = 0;
277     }
278     p_dec->i_tot += *bytes;
279
280     return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
281 }
282
283 /*****************************************************************************
284  * DecoderWriteCallback: called by libflac to output decoded samples
285  *****************************************************************************/
286 static FLAC__StreamDecoderWriteStatus DecoderWriteCallback (
287     const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame,
288     const FLAC__int32 *const buffer[], void *client_data )
289 {
290     dec_thread_t *p_dec = (dec_thread_t *)client_data;
291     int i_samples = frame->header.blocksize;
292     aout_buffer_t *p_aout_buffer;
293     p_aout_buffer = aout_DecNewBuffer( p_dec->p_aout, p_dec->p_aout_input,
294                                        i_samples );
295     if( !p_aout_buffer )
296     {
297         msg_Err( p_dec->p_fifo, "cannot get aout buffer" );
298         p_dec->p_fifo->b_error = 1;
299         return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
300     }
301     switch ( frame->header.bits_per_sample )
302     {
303     case 16:
304         Interleave16( (int16_t *)p_aout_buffer->p_buffer, buffer,
305                 frame->header.channels, i_samples );
306         break;
307     default:
308         Interleave32( (int32_t *)p_aout_buffer->p_buffer, buffer,
309                 frame->header.channels, i_samples );
310     }
311         
312     if( p_dec->pts != 0 && p_dec->pts != aout_DateGet( &p_dec->end_date ) )
313     {
314         aout_DateSet( &p_dec->end_date, p_dec->pts );
315         p_dec->pts = 0;
316     }
317     else if( !aout_DateGet( &p_dec->end_date ) )
318     {
319         return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
320     }
321
322     /* Date management */
323     p_aout_buffer->start_date = aout_DateGet( &p_dec->end_date );
324     p_aout_buffer->end_date = aout_DateIncrement( &p_dec->end_date,
325                                                   i_samples );
326     aout_DecPlay( p_dec->p_aout, p_dec->p_aout_input, p_aout_buffer );
327     return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
328 }
329
330 /*****************************************************************************
331 ' * DecoderMetadataCallback: called by libflac to when it encounters metadata
332  *****************************************************************************/
333 static void DecoderMetadataCallback (const FLAC__StreamDecoder *decoder,
334                                      const FLAC__StreamMetadata *metadata,
335                                      void *client_data)
336 {
337     dec_thread_t *p_dec = (dec_thread_t *)client_data;
338     switch ( metadata->data.stream_info.bits_per_sample )
339     {
340     case 8:
341         p_dec->output_format.i_format = VLC_FOURCC('s','8',' ',' ');
342         break;
343     case 16:
344         p_dec->output_format.i_format = AOUT_FMT_S16_NE;
345         break;
346     default:
347         msg_Dbg( p_dec->p_fifo, "strange bps %d",
348                  metadata->data.stream_info.bits_per_sample );
349         p_dec->output_format.i_format = VLC_FOURCC('f','i','3','2');
350         break;
351     }
352     p_dec->output_format.i_physical_channels =
353         p_dec->output_format.i_original_channels =
354             pi_channels_maps[metadata->data.stream_info.channels];
355     p_dec->output_format.i_rate = metadata->data.stream_info.sample_rate;
356
357     return;
358 }
359
360 /*****************************************************************************
361  * DecoderErrorCallback: called when the libflac decoder encounters an error
362  *****************************************************************************/
363 static void DecoderErrorCallback (const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
364 {
365     dec_thread_t *p_dec = (dec_thread_t *)client_data;
366     switch ( status )
367     {
368     case FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC :
369         msg_Err( p_dec->p_fifo, "An error in the stream caused the decoder to lose synchronization.");
370         break;
371
372     case FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER :
373         msg_Err( p_dec->p_fifo, "The decoder encountered a corrupted frame header.");
374         break;
375
376     case FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH :
377         msg_Err( p_dec->p_fifo, "The frame's data did not match the CRC in the footer.");
378         break;
379     default:
380         msg_Err( p_dec->p_fifo, "got decoder error: %d", status );
381     }
382     return;
383 }
384
385 /*****************************************************************************
386  * Interleave: helper function to interleave channels
387  *****************************************************************************/
388 static void Interleave32( int32_t *p_out, const int32_t * const *pp_in,
389                         int i_nb_channels, int i_samples )
390 {
391     int i, j;
392
393     for ( j = 0; j < i_samples; j++ )
394     {
395         for ( i = 0; i < i_nb_channels; i++ )
396         {
397             p_out[j * i_nb_channels + i] = pp_in[i][j];
398         }
399     }
400 }
401 static void Interleave16( int16_t *p_out, const int32_t * const *pp_in,
402                         int i_nb_channels, int i_samples )
403 {
404     int i, j;
405
406     for ( j = 0; j < i_samples; j++ )
407     {
408         for ( i = 0; i < i_nb_channels; i++ )
409         {
410             p_out[j * i_nb_channels + i] = (int32_t)(pp_in[i][j]);
411         }
412     }
413 }
414
415
416 static void decoder_state_error( dec_thread_t *p_dec, FLAC__StreamDecoderState state )
417 {
418     switch ( state )
419     {
420     case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA  : 
421         msg_Err( p_dec->p_fifo, "The decoder is ready to search for metadata.");
422         break;
423     case FLAC__STREAM_DECODER_READ_METADATA  : 
424         msg_Err( p_dec->p_fifo, "The decoder is ready to or is in the process of reading metadata.");
425         break;
426     case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC  : 
427         msg_Err( p_dec->p_fifo, "The decoder is ready to or is in the process of searching for the frame sync code.");
428         break;
429     case FLAC__STREAM_DECODER_READ_FRAME  : 
430         msg_Err( p_dec->p_fifo, "The decoder is ready to or is in the process of reading a frame.");
431         break;
432     case FLAC__STREAM_DECODER_END_OF_STREAM  : 
433         msg_Err( p_dec->p_fifo, "The decoder has reached the end of the stream.");
434         break;
435     case FLAC__STREAM_DECODER_ABORTED  : 
436         msg_Err( p_dec->p_fifo, "The decoder was aborted by the read callback.");
437         break;
438     case FLAC__STREAM_DECODER_UNPARSEABLE_STREAM  : 
439         msg_Err( p_dec->p_fifo, "The decoder encountered reserved fields in use in the stream.");
440         FLAC__stream_decoder_flush( p_dec->p_decoder );
441         break;
442     case FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR  : 
443         msg_Err( p_dec->p_fifo, "An error occurred allocating memory.");
444         break;
445     case FLAC__STREAM_DECODER_ALREADY_INITIALIZED  : 
446         msg_Err( p_dec->p_fifo, "FLAC__stream_decoder_init() was called when the decoder was already initialized, usually because FLAC__stream_decoder_finish() was not called.");
447         break;
448     case FLAC__STREAM_DECODER_INVALID_CALLBACK  : 
449         msg_Err( p_dec->p_fifo, "FLAC__stream_decoder_init() was called without all callbacks being set.");
450         break;
451     case FLAC__STREAM_DECODER_UNINITIALIZED  : 
452         msg_Err( p_dec->p_fifo, "The decoder is in the uninitialized state.");
453         break;
454     default:
455         msg_Err(p_dec->p_fifo, "unknown error" );
456     }
457 }