* faad: can read stream with multiple frames per pes_packet_t (for mkv).
[vlc.git] / modules / codec / faad / decoder.c
1 /*****************************************************************************
2  * decoder.c: AAC decoder using libfaad2
3  *****************************************************************************
4  * Copyright (C) 2001, 2002 VideoLAN
5  * $Id: decoder.c,v 1.25 2003/06/22 08:49:11 fenrir Exp $
6  *
7  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
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 <vlc/vlc.h>
28 #include <vlc/aout.h>
29 #include <vlc/decoder.h>
30 #include <vlc/input.h>
31
32 #include <stdlib.h>                                      /* malloc(), free() */
33 #include <string.h>                                              /* strdup() */
34
35 #include <faad.h>
36 #include "codecs.h"
37 #include "decoder.h"
38
39
40 /*****************************************************************************
41  * Local prototypes
42  *****************************************************************************/
43 static int  OpenDecoder    ( vlc_object_t * );
44
45 static int  RunDecoder     ( decoder_fifo_t * );
46 static int  InitThread     ( adec_thread_t * );
47 static void DecodeThread   ( adec_thread_t * );
48 static void EndThread      ( adec_thread_t * );
49
50 /*****************************************************************************
51  * Module descriptor
52  *****************************************************************************/
53
54 vlc_module_begin();
55     set_description( _("AAC audio decoder (using libfaad2)") );
56     set_capability( "decoder", 60 );
57     set_callbacks( OpenDecoder, NULL );
58 vlc_module_end();
59
60 /*****************************************************************************
61  * OpenDecoder: probe the decoder and return score
62  *****************************************************************************
63  * Tries to launch a decoder and return score so that the interface is able
64  * to choose.
65  *****************************************************************************/
66 static int OpenDecoder( vlc_object_t *p_this )
67 {
68     decoder_fifo_t *p_fifo = (decoder_fifo_t*) p_this;
69
70     if( p_fifo->i_fourcc != VLC_FOURCC('m','p','4','a') )
71     {
72         return VLC_EGENERIC;
73     }
74
75     p_fifo->pf_run = RunDecoder;
76     return VLC_SUCCESS;
77 }
78
79 /*****************************************************************************
80  * RunDecoder: this function is called just after the thread is created
81  *****************************************************************************/
82 static int RunDecoder( decoder_fifo_t *p_fifo )
83 {
84     adec_thread_t *p_adec;
85     int b_error;
86
87     if( !( p_adec = malloc( sizeof( adec_thread_t ) ) ) )
88     {
89         msg_Err( p_fifo, "out of memory" );
90         DecoderError( p_fifo );
91         return( -1 );
92     }
93     memset( p_adec, 0, sizeof( adec_thread_t ) );
94
95     p_adec->p_fifo = p_fifo;
96
97     if( InitThread( p_adec ) != 0 )
98     {
99         DecoderError( p_fifo );
100         return( -1 );
101     }
102
103     while( ( !p_adec->p_fifo->b_die )&&( !p_adec->p_fifo->b_error ) )
104     {
105         DecodeThread( p_adec );
106     }
107
108
109     if( ( b_error = p_adec->p_fifo->b_error ) )
110     {
111         DecoderError( p_adec->p_fifo );
112     }
113
114     EndThread( p_adec );
115     if( b_error )
116     {
117         return( -1 );
118     }
119
120     return( 0 );
121 }
122
123 static unsigned int pi_channels_maps[7] =
124 {
125     0,
126     AOUT_CHAN_CENTER,
127     AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT,
128     AOUT_CHAN_CENTER | AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT,
129     AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT,
130     AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_CENTER | AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT,
131      /* FIXME */
132     AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_CENTER | AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT | AOUT_CHAN_REARCENTER,
133
134 };
135
136 #define FREE( p ) if( p != NULL ) free( p ); p = NULL
137 #define GetWLE( p ) \
138     ( *(uint8_t*)(p) + ( *((uint8_t*)(p)+1) << 8 ) )
139
140 #define GetDWLE( p ) \
141     (  *(uint8_t*)(p) + ( *((uint8_t*)(p)+1) << 8 ) + \
142         ( *((uint8_t*)(p)+2) << 16 ) + ( *((uint8_t*)(p)+3) << 24 ) )
143
144
145 static void GetPESData( uint8_t *p_buf, int i_max, pes_packet_t *p_pes )
146 {
147     int i_copy;
148     int i_count;
149
150     data_packet_t   *p_data;
151
152     i_count = 0;
153     p_data = p_pes->p_first;
154     while( p_data != NULL && i_count < i_max )
155     {
156
157         i_copy = __MIN( p_data->p_payload_end - p_data->p_payload_start,
158                         i_max - i_count );
159
160         if( i_copy > 0 )
161         {
162             memcpy( p_buf,
163                     p_data->p_payload_start,
164                     i_copy );
165         }
166
167         p_data = p_data->p_next;
168         i_count += i_copy;
169         p_buf   += i_copy;
170     }
171
172     if( i_count < i_max )
173     {
174         memset( p_buf, 0, i_max - i_count );
175     }
176 }
177
178 /*****************************************************************************
179  * InitThread: initialize data before entering main loop
180  *****************************************************************************/
181 static int InitThread( adec_thread_t * p_adec )
182 {
183     WAVEFORMATEX    wf, *p_wf;
184     int i_status;
185     unsigned long   i_rate;
186     unsigned char   i_nb_channels;
187
188     faacDecConfiguration *p_faad_config;
189
190     if( ( p_wf = (WAVEFORMATEX*)p_adec->p_fifo->p_waveformatex ) == NULL )
191     {
192         msg_Warn( p_adec->p_fifo,
193                   "cannot load stream informations" );
194         p_wf = &wf;
195         memset( p_wf, 0, sizeof( WAVEFORMATEX ) );
196     }
197
198     p_adec->p_buffer = NULL;
199     p_adec->i_buffer = 0;
200
201
202     if( !( p_adec->p_handle = faacDecOpen() ) )
203     {
204         msg_Err( p_adec->p_fifo,
205                  "cannot initialize faad" );
206         return( -1 );
207     }
208
209     if( p_wf->cbSize <= 0 )
210     {
211         int i_frame_size;
212         pes_packet_t *p_pes;
213
214         faacDecConfigurationPtr cfg;
215
216         cfg = faacDecGetCurrentConfiguration( p_adec->p_handle );
217         if( p_wf->nSamplesPerSec > 0 )
218         {
219             cfg->defSampleRate = p_wf->nSamplesPerSec;
220         }
221         faacDecSetConfiguration( p_adec->p_handle, cfg );
222         msg_Warn( p_adec->p_fifo,
223                  "DecoderSpecificInfo missing, trying with first frame" );
224         // gather first frame
225         do
226         {
227             input_ExtractPES( p_adec->p_fifo, &p_pes );
228             if( !p_pes )
229             {
230                 return( -1 );
231             }
232             i_frame_size = p_pes->i_pes_size;
233
234             if( i_frame_size > 0 )
235             {
236                 if( p_adec->i_buffer < i_frame_size + 16 )
237                 {
238                     FREE( p_adec->p_buffer );
239                     p_adec->p_buffer = malloc( i_frame_size + 16 );
240                     p_adec->i_buffer = i_frame_size + 16;
241                 }
242
243                 GetPESData( p_adec->p_buffer, p_adec->i_buffer, p_pes );
244             }
245             else
246             {
247                 input_DeletePES( p_adec->p_fifo->p_packets_mgt, p_pes );
248             }
249         } while( i_frame_size <= 0 );
250
251 #ifdef HAVE_OLD_FAAD2
252         i_status = faacDecInit( p_adec->p_handle,
253                                 p_adec->p_buffer,
254                                 &i_rate,
255                                 &i_nb_channels );
256 #else
257         i_status = faacDecInit( p_adec->p_handle,
258                                 p_adec->p_buffer,
259                                 i_frame_size,
260                                 &i_rate,
261                                 &i_nb_channels );
262 #endif
263
264     }
265     else
266     {
267         i_status = faacDecInit2( p_adec->p_handle,
268                                  (uint8_t*)&p_wf[1],
269                                  p_wf->cbSize,
270                                  &i_rate,
271                                  &i_nb_channels );
272     }
273
274     if( i_status < 0 )
275     {
276         msg_Err( p_adec->p_fifo,
277                  "failed to initialize faad" );
278         //faacDecClose( p_adec->p_handle );
279         return( -1 );
280     }
281     msg_Dbg( p_adec->p_fifo,
282              "faad intitialized, samplerate: %ldHz channels: %d",
283              i_rate, 
284              i_nb_channels );
285
286
287     /* set default configuration */
288     p_faad_config = faacDecGetCurrentConfiguration( p_adec->p_handle );
289     p_faad_config->outputFormat = FAAD_FMT_FLOAT;
290     faacDecSetConfiguration( p_adec->p_handle, p_faad_config );
291
292
293     /* Initialize the thread properties */
294     p_adec->output_format.i_format = VLC_FOURCC('f','l','3','2');
295     p_adec->output_format.i_rate = i_rate;
296     p_adec->output_format.i_physical_channels =
297         p_adec->output_format.i_original_channels =
298             pi_channels_maps[i_nb_channels];
299     p_adec->p_aout = NULL;
300     p_adec->p_aout_input = NULL;
301
302     p_adec->pts = 0;
303
304     return( 0 );
305 }
306
307 /*****************************************************************************
308  * DecodeThread: decodes a frame
309  *****************************************************************************
310  * XXX it will work only for frame based streams like from mp4 file
311  *     but it's the only way to use libfaad2 without having segfault
312  *     after 1 or 2 frames
313  *****************************************************************************/
314 static void DecodeThread( adec_thread_t *p_adec )
315 {
316     aout_buffer_t    *p_aout_buffer;
317
318     void             *p_faad_buffer;
319     faacDecFrameInfo faad_frame;
320     int  i_frame_size;
321     pes_packet_t *p_pes;
322     int  i_used;
323
324     /* **** Get a new frames from streams **** */
325     do
326     {
327         input_ExtractPES( p_adec->p_fifo, &p_pes );
328         if( !p_pes )
329         {
330             p_adec->p_fifo->b_error = 1;
331             return;
332         }
333         if( p_pes->i_pts != 0 )
334         {
335             p_adec->pts = p_pes->i_pts;
336         }
337         i_frame_size = p_pes->i_pes_size;
338
339         if( i_frame_size > 0 )
340         {
341             if( p_adec->i_buffer < i_frame_size + 16 )
342             {
343                 FREE( p_adec->p_buffer );
344                 p_adec->p_buffer = malloc( i_frame_size + 16 );
345                 p_adec->i_buffer = i_frame_size + 16;
346             }
347
348             GetPESData( p_adec->p_buffer, p_adec->i_buffer, p_pes );
349         }
350         input_DeletePES( p_adec->p_fifo->p_packets_mgt, p_pes );
351     } while( i_frame_size <= 0 );
352
353
354     i_used = 0;
355     while( i_used < i_frame_size )
356     {
357         /* **** decode this frame **** */
358 #ifdef HAVE_OLD_FAAD2
359         p_faad_buffer = faacDecDecode( p_adec->p_handle,
360                                        &faad_frame,
361                                        &p_adec->p_buffer[i_used] );
362 #else
363         p_faad_buffer = faacDecDecode( p_adec->p_handle,
364                                        &faad_frame,
365                                        &p_adec->p_buffer[i_used],
366                                        i_frame_size - i_used );
367 #endif
368
369         /* **** some sanity checks to see if we have samples to out **** */
370         if( faad_frame.error > 0 )
371         {
372             msg_Warn( p_adec->p_fifo, "%s",
373                       faacDecGetErrorMessage(faad_frame.error) );
374             return;
375         }
376         if( ( faad_frame.channels <= 0 )||
377             ( faad_frame.channels > AAC_MAXCHANNELS) ||
378             ( faad_frame.channels > 6 ) )
379         {
380             msg_Warn( p_adec->p_fifo,
381                       "invalid channels count(%d)", faad_frame.channels );
382             return;
383         }
384         if( faad_frame.samples <= 0 )
385         {
386             msg_Warn( p_adec->p_fifo, "decoded zero sample !" );
387             return;
388         }
389
390 #if 0
391         msg_Dbg( p_adec->p_fifo,
392                  "decoded frame samples:%d, channels:%d, consumed:%d",
393                  faad_frame.samples,
394                  faad_frame.channels,
395                  faad_frame.bytesconsumed );
396 #endif
397         i_used += faad_frame.bytesconsumed;
398
399         /* **** Now we can output these samples **** */
400
401         /* **** First check if we have a valid output **** */
402         if( ( !p_adec->p_aout_input )||
403             ( p_adec->output_format.i_original_channels !=
404                  pi_channels_maps[faad_frame.channels] ) )
405         {
406             if( p_adec->p_aout_input )
407             {
408                 /* **** Delete the old **** */
409                 aout_DecDelete( p_adec->p_aout, p_adec->p_aout_input );
410             }
411
412             /* **** Create a new audio output **** */
413             p_adec->output_format.i_physical_channels =
414                 p_adec->output_format.i_original_channels =
415                     pi_channels_maps[faad_frame.channels];
416
417             aout_DateInit( &p_adec->date, p_adec->output_format.i_rate );
418             p_adec->p_aout_input = aout_DecNew( p_adec->p_fifo,
419                                                 &p_adec->p_aout,
420                                                 &p_adec->output_format );
421         }
422
423         if( !p_adec->p_aout_input )
424         {
425             msg_Err( p_adec->p_fifo, "cannot create aout" );
426             return;
427         }
428
429         if( p_adec->pts != 0 && p_adec->pts != aout_DateGet( &p_adec->date ) )
430         {
431             aout_DateSet( &p_adec->date, p_adec->pts );
432         }
433         else if( !aout_DateGet( &p_adec->date ) )
434         {
435             return;
436         }
437
438         p_aout_buffer = aout_DecNewBuffer( p_adec->p_aout,
439                                            p_adec->p_aout_input,
440                                            faad_frame.samples / faad_frame.channels );
441         if( !p_aout_buffer )
442         {
443             msg_Err( p_adec->p_fifo, "cannot get aout buffer" );
444             p_adec->p_fifo->b_error = 1;
445             return;
446         }
447         p_aout_buffer->start_date = aout_DateGet( &p_adec->date );
448         p_aout_buffer->end_date = aout_DateIncrement( &p_adec->date,
449                                                       faad_frame.samples /
450                                                           faad_frame.channels );
451         memcpy( p_aout_buffer->p_buffer,
452                 p_faad_buffer,
453                 p_aout_buffer->i_nb_bytes );
454
455         aout_DecPlay( p_adec->p_aout, p_adec->p_aout_input, p_aout_buffer );
456     }
457 }
458
459
460 /*****************************************************************************
461  * EndThread : faad decoder thread destruction
462  *****************************************************************************/
463 static void EndThread (adec_thread_t *p_adec)
464 {
465     if( p_adec->p_aout_input )
466     {
467         aout_DecDelete( p_adec->p_aout, p_adec->p_aout_input );
468     }
469
470     if( p_adec->p_handle )
471     {
472         faacDecClose( p_adec->p_handle );
473     }
474
475     FREE( p_adec->p_buffer );
476
477     msg_Dbg( p_adec->p_fifo, "faad decoder closed" );
478
479     free( p_adec );
480 }
481