]> git.sesse.net Git - vlc/blob - modules/codec/speex.c
Do not assert memory allocations
[vlc] / modules / codec / speex.c
1 /*****************************************************************************
2  * speex.c: speex decoder/packetizer/encoder module making use of libspeex.
3  *****************************************************************************
4  * Copyright (C) 2003-2009 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Gildas Bazin <gbazin@videolan.org>
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., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22  *****************************************************************************/
23
24 /*****************************************************************************
25  * Preamble
26  *****************************************************************************/
27 #ifdef HAVE_CONFIG_H
28 # include "config.h"
29 #endif
30
31 #include <vlc_common.h>
32 #include <vlc_plugin.h>
33 #include <vlc_input.h>
34 #include <vlc_codec.h>
35 #include <vlc_aout.h>
36
37 #include <ogg/ogg.h>
38 #include <speex/speex.h>
39 #include <speex/speex_header.h>
40 #include <speex/speex_stereo.h>
41 #include <speex/speex_callbacks.h>
42
43 #include <assert.h>
44
45 /*****************************************************************************
46  * Module descriptor
47  *****************************************************************************/
48 static int  OpenDecoder   ( vlc_object_t * );
49 static int  OpenPacketizer( vlc_object_t * );
50 static void CloseDecoder  ( vlc_object_t * );
51 static int OpenEncoder   ( vlc_object_t * );
52 static void CloseEncoder ( vlc_object_t * );
53
54 #define ENC_CFG_PREFIX "sout-speex-"
55
56 #define ENC_MODE_TEXT N_("Mode" )
57 #define ENC_MODE_LONGTEXT N_( \
58     "Enforce the mode of the encoder." )
59
60 #define ENC_QUALITY_TEXT N_("Encoding quality")
61 #define ENC_QUALITY_LONGTEXT N_( \
62     "Enforce a quality between 0 (low) and 10 (high)." )
63
64 #define ENC_COMPLEXITY_TEXT N_("Encoding complexity" )
65 #define ENC_COMPLEXITY_LONGTEXT N_( \
66     "Enforce the complexity of the encoder." )
67
68 #define ENC_MAXBITRATE_TEXT N_( "Maximal bitrate" )
69 #define ENC_MAXBITRATE_LONGTEXT N_( \
70     "Enforce the maximal VBR bitrate" )
71
72 #define ENC_CBR_TEXT N_( "CBR encoding" )
73 #define ENC_CBR_LONGTEXT N_( \
74     "Enforce a constant bitrate encoding (CBR) instead of default " \
75     "variable bitrate encoding (VBR)." )
76
77 #define ENC_VAD_TEXT N_( "Voice activity detection" )
78 #define ENC_VAD_LONGTEXT N_( \
79     "Enable voice activity detection (VAD). It is automatically " \
80     "activated in VBR mode." )
81
82 #define ENC_DTX_TEXT N_( "Discontinuous Transmission" )
83 #define ENC_DTX_LONGTEXT N_( \
84     "Enable discontinuous transmission (DTX)." )
85
86 static const int pi_enc_mode_values[] = { 0, 1, 2 };
87 static const char * const ppsz_enc_mode_descriptions[] = {
88     N_("Narrow-band (8kHz)"), N_("Wide-band (16kHz)"), N_("Ultra-wideband (32kHz)"), NULL
89 };
90
91 vlc_module_begin ()
92     set_category( CAT_INPUT )
93     set_subcategory( SUBCAT_INPUT_ACODEC )
94
95     set_description( N_("Speex audio decoder") )
96     set_capability( "decoder", 100 )
97     set_shortname( N_("Speex") )
98     set_callbacks( OpenDecoder, CloseDecoder )
99
100     add_submodule ()
101     set_description( N_("Speex audio packetizer") )
102     set_capability( "packetizer", 100 )
103     set_callbacks( OpenPacketizer, CloseDecoder )
104
105     add_submodule ()
106     set_description( N_("Speex audio encoder") )
107     set_capability( "encoder", 100 )
108     set_callbacks( OpenEncoder, CloseEncoder )
109
110     add_integer( ENC_CFG_PREFIX "mode", 0, NULL, ENC_MODE_TEXT,
111                  ENC_MODE_LONGTEXT, false )
112         change_integer_list( pi_enc_mode_values, ppsz_enc_mode_descriptions, NULL )
113
114     add_integer( ENC_CFG_PREFIX "complexity", 3, NULL, ENC_COMPLEXITY_TEXT,
115                  ENC_COMPLEXITY_LONGTEXT, false )
116         change_integer_range( 1, 10 )
117
118     add_bool( ENC_CFG_PREFIX "cbr", false, NULL, ENC_CBR_TEXT,
119                  ENC_CBR_LONGTEXT, false )
120
121     add_float( ENC_CFG_PREFIX "quality", 8.0, NULL, ENC_QUALITY_TEXT,
122                ENC_QUALITY_LONGTEXT, false )
123         change_float_range( 0.0, 10.0 )
124
125     add_integer( ENC_CFG_PREFIX "max-bitrate", 0, NULL, ENC_MAXBITRATE_TEXT,
126                  ENC_MAXBITRATE_LONGTEXT, false )
127
128     add_bool( ENC_CFG_PREFIX "vad", true, NULL, ENC_VAD_TEXT,
129                  ENC_VAD_LONGTEXT, false )
130
131     add_bool( ENC_CFG_PREFIX "dtx", false, NULL, ENC_DTX_TEXT,
132                  ENC_DTX_LONGTEXT, false )
133
134     /* TODO agc, noise suppression, */
135
136 vlc_module_end ()
137
138 static const char *const ppsz_enc_options[] = {
139     "mode", "complexity", "cbr", "quality", "max-bitrate", "vad", "dtx", NULL
140 };
141
142 /*****************************************************************************
143  * decoder_sys_t : speex decoder descriptor
144  *****************************************************************************/
145 struct decoder_sys_t
146 {
147     /* Module mode */
148     bool b_packetizer;
149
150     /*
151      * Input properties
152      */
153     int i_headers;
154     int i_frame_in_packet;
155
156     /*
157      * Speex properties
158      */
159     SpeexBits bits;
160     SpeexHeader *p_header;
161     SpeexStereoState stereo;
162     void *p_state;
163     unsigned int rtp_rate;
164
165     /*
166      * Common properties
167      */
168     date_t end_date;
169
170 };
171
172 static const int pi_channels_maps[6] =
173 {
174     0,
175     AOUT_CHAN_CENTER,   AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT,
176     AOUT_CHAN_CENTER | AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT,
177     AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_REARLEFT
178      | AOUT_CHAN_REARRIGHT,
179     AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_CENTER
180      | AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT
181 };
182
183 /****************************************************************************
184  * Local prototypes
185  ****************************************************************************/
186
187 static void *DecodeBlock  ( decoder_t *, block_t ** );
188 static aout_buffer_t *DecodeRtpSpeexPacket( decoder_t *, block_t **);
189 static int  ProcessHeaders( decoder_t * );
190 static int  ProcessInitialHeader ( decoder_t *, ogg_packet * );
191 static void *ProcessPacket( decoder_t *, ogg_packet *, block_t ** );
192
193 static aout_buffer_t *DecodePacket( decoder_t *, ogg_packet * );
194 static block_t *SendPacket( decoder_t *, block_t * );
195
196 static void ParseSpeexComments( decoder_t *, ogg_packet * );
197
198 static block_t *Encode   ( encoder_t *, aout_buffer_t * );
199
200 /*****************************************************************************
201  * OpenDecoder: probe the decoder and return score
202  *****************************************************************************/
203 static int OpenDecoder( vlc_object_t *p_this )
204 {
205     decoder_t *p_dec = (decoder_t*)p_this;
206     decoder_sys_t *p_sys;
207
208     if( p_dec->fmt_in.i_codec != VLC_CODEC_SPEEX )
209         return VLC_EGENERIC;
210
211     /* Allocate the memory needed to store the decoder's structure */
212     if( ( p_dec->p_sys = p_sys = malloc(sizeof(decoder_sys_t)) ) == NULL )
213         return VLC_ENOMEM;
214     p_dec->p_sys->bits.buf_size = 0;
215     p_dec->p_sys->b_packetizer = false;
216     p_dec->p_sys->rtp_rate = p_dec->fmt_in.audio.i_rate;
217
218     date_Set( &p_sys->end_date, 0 );
219
220     /* Set output properties */
221     p_dec->fmt_out.i_cat = AUDIO_ES;
222     p_dec->fmt_out.i_codec = VLC_CODEC_S16N;
223
224     /*
225       Set callbacks
226       If the codec is spxr then this decoder is 
227       being invoked on a Speex stream arriving via RTP. 
228       A special decoder callback is used.
229     */
230     if (p_dec->fmt_in.i_original_fourcc == VLC_FOURCC('s', 'p', 'x', 'r'))
231     {
232         msg_Dbg( p_dec, "Using RTP version of Speex decoder @ rate %d.", 
233             p_dec->fmt_in.audio.i_rate );
234         p_dec->pf_decode_audio = (aout_buffer_t *(*)(decoder_t *, block_t **))
235             DecodeRtpSpeexPacket;
236     }
237     else
238     {
239         p_dec->pf_decode_audio = (aout_buffer_t *(*)(decoder_t *, block_t **))
240             DecodeBlock;
241     }
242     p_dec->pf_packetize    = (block_t *(*)(decoder_t *, block_t **))
243         DecodeBlock;
244
245     p_sys->i_headers = 0;
246     p_sys->p_state = NULL;
247     p_sys->p_header = NULL;
248     p_sys->i_frame_in_packet = 0;
249
250     return VLC_SUCCESS;
251 }
252
253 static int OpenPacketizer( vlc_object_t *p_this )
254 {
255     decoder_t *p_dec = (decoder_t*)p_this;
256
257     int i_ret = OpenDecoder( p_this );
258
259     if( i_ret == VLC_SUCCESS )
260     {
261         p_dec->p_sys->b_packetizer = true;
262         p_dec->fmt_out.i_codec = VLC_CODEC_SPEEX;
263     }
264
265     return i_ret;
266 }
267
268 /****************************************************************************
269  * DecodeBlock: the whole thing
270  ****************************************************************************
271  * This function must be fed with ogg packets.
272  ****************************************************************************/
273 static void *DecodeBlock( decoder_t *p_dec, block_t **pp_block )
274 {
275     decoder_sys_t *p_sys = p_dec->p_sys;
276     ogg_packet oggpacket;
277
278     if( !pp_block ) return NULL;
279
280     if( *pp_block )
281     {
282         /* Block to Ogg packet */
283         oggpacket.packet = (*pp_block)->p_buffer;
284         oggpacket.bytes = (*pp_block)->i_buffer;
285     }
286     else
287     {
288         if( p_sys->b_packetizer ) return NULL;
289
290         /* Block to Ogg packet */
291         oggpacket.packet = NULL;
292         oggpacket.bytes = 0;
293     }
294
295     oggpacket.granulepos = -1;
296     oggpacket.b_o_s = 0;
297     oggpacket.e_o_s = 0;
298     oggpacket.packetno = 0;
299
300     /* Check for headers */
301     if( p_sys->i_headers == 0 && p_dec->fmt_in.i_extra )
302     {
303         p_sys->i_headers = 2;
304     }
305     else if( oggpacket.bytes && p_sys->i_headers < 2 )
306     {
307         uint8_t *p_extra;
308
309         p_dec->fmt_in.p_extra = xrealloc( p_dec->fmt_in.p_extra,
310                                 p_dec->fmt_in.i_extra + oggpacket.bytes + 2 );
311         p_extra = ((uint8_t *)p_dec->fmt_in.p_extra) + p_dec->fmt_in.i_extra;
312         *(p_extra++) = oggpacket.bytes >> 8;
313         *(p_extra++) = oggpacket.bytes & 0xFF;
314
315         memcpy( p_extra, oggpacket.packet, oggpacket.bytes );
316         p_dec->fmt_in.i_extra += oggpacket.bytes + 2;
317
318         block_Release( *pp_block );
319         p_sys->i_headers++;
320         return NULL;
321     }
322
323     if( p_sys->i_headers == 2 )
324     {
325         if( ProcessHeaders( p_dec ) != VLC_SUCCESS )
326         {
327             p_sys->i_headers = 0;
328             p_dec->fmt_in.i_extra = 0;
329             block_Release( *pp_block );
330             return NULL;
331         }
332         else p_sys->i_headers++;
333     }
334
335     return ProcessPacket( p_dec, &oggpacket, pp_block );
336 }
337
338 /*****************************************************************************
339  * ProcessHeaders: process Speex headers.
340  *****************************************************************************/
341 static int ProcessHeaders( decoder_t *p_dec )
342 {
343     decoder_sys_t *p_sys = p_dec->p_sys;
344     ogg_packet oggpacket;
345     uint8_t *p_extra;
346     int i_extra;
347
348     if( !p_dec->fmt_in.i_extra ) return VLC_EGENERIC;
349
350     oggpacket.granulepos = -1;
351     oggpacket.b_o_s = 1; /* yes this actually is a b_o_s packet :) */
352     oggpacket.e_o_s = 0;
353     oggpacket.packetno = 0;
354     p_extra = p_dec->fmt_in.p_extra;
355     i_extra = p_dec->fmt_in.i_extra;
356
357     /* Take care of the initial Vorbis header */
358     oggpacket.bytes = *(p_extra++) << 8;
359     oggpacket.bytes |= (*(p_extra++) & 0xFF);
360     oggpacket.packet = p_extra;
361     p_extra += oggpacket.bytes;
362     i_extra -= (oggpacket.bytes + 2);
363     if( i_extra < 0 )
364     {
365         msg_Err( p_dec, "header data corrupted");
366         return VLC_EGENERIC;
367     }
368
369     /* Take care of the initial Speex header */
370     if( ProcessInitialHeader( p_dec, &oggpacket ) != VLC_SUCCESS )
371     {
372         msg_Err( p_dec, "initial Speex header is corrupted" );
373         return VLC_EGENERIC;
374     }
375
376     /* The next packet in order is the comments header */
377     oggpacket.b_o_s = 0;
378     oggpacket.bytes = *(p_extra++) << 8;
379     oggpacket.bytes |= (*(p_extra++) & 0xFF);
380     oggpacket.packet = p_extra;
381     p_extra += oggpacket.bytes;
382     i_extra -= (oggpacket.bytes + 2);
383     if( i_extra < 0 )
384     {
385         msg_Err( p_dec, "header data corrupted");
386         return VLC_EGENERIC;
387     }
388
389     ParseSpeexComments( p_dec, &oggpacket );
390
391     if( p_sys->b_packetizer )
392     {
393         p_dec->fmt_out.i_extra = p_dec->fmt_in.i_extra;
394         p_dec->fmt_out.p_extra = xrealloc( p_dec->fmt_out.p_extra,
395                                                   p_dec->fmt_out.i_extra );
396         memcpy( p_dec->fmt_out.p_extra,
397                 p_dec->fmt_in.p_extra, p_dec->fmt_out.i_extra );
398     }
399
400     return VLC_SUCCESS;
401 }
402
403 /*****************************************************************************
404  * ProcessInitialHeader: processes the inital Speex header packet.
405  *****************************************************************************/
406 static int ProcessInitialHeader( decoder_t *p_dec, ogg_packet *p_oggpacket )
407 {
408     decoder_sys_t *p_sys = p_dec->p_sys;
409
410     void *p_state;
411     SpeexHeader *p_header;
412     const SpeexMode *p_mode;
413     SpeexCallback callback;
414
415     p_sys->p_header = p_header =
416         speex_packet_to_header( (char *)p_oggpacket->packet,
417                                 p_oggpacket->bytes );
418     if( !p_header )
419     {
420         msg_Err( p_dec, "cannot read Speex header" );
421         return VLC_EGENERIC;
422     }
423     if( p_header->mode >= SPEEX_NB_MODES || p_header->mode < 0 )
424     {
425         msg_Err( p_dec, "mode number %d does not (yet/any longer) exist in "
426                  "this version of libspeex.", p_header->mode );
427         return VLC_EGENERIC;
428     }
429
430     p_mode = speex_mode_list[p_header->mode];
431     if( p_mode == NULL )
432         return VLC_EGENERIC;
433
434     if( p_header->speex_version_id > 1 )
435     {
436         msg_Err( p_dec, "this file was encoded with Speex bit-stream "
437                  "version %d which is not supported by this decoder.",
438                  p_header->speex_version_id );
439         return VLC_EGENERIC;
440     }
441
442     if( p_mode->bitstream_version < p_header->mode_bitstream_version )
443     {
444         msg_Err( p_dec, "file encoded with a newer version of Speex." );
445         return VLC_EGENERIC;
446     }
447     if( p_mode->bitstream_version > p_header->mode_bitstream_version )
448     {
449         msg_Err( p_dec, "file encoded with an older version of Speex." );
450         return VLC_EGENERIC;
451     }
452
453     msg_Dbg( p_dec, "Speex %d Hz audio using %s mode %s%s",
454              p_header->rate, p_mode->modeName,
455              ( p_header->nb_channels == 1 ) ? " (mono" : " (stereo",
456              p_header->vbr ? ", VBR)" : ")" );
457
458     /* Take care of speex decoder init */
459     speex_bits_init( &p_sys->bits );
460     p_sys->p_state = p_state = speex_decoder_init( p_mode );
461     if( !p_state )
462     {
463         msg_Err( p_dec, "decoder initialization failed" );
464         return VLC_EGENERIC;
465     }
466
467     if( p_header->nb_channels == 2 )
468     {
469         SpeexStereoState stereo = SPEEX_STEREO_STATE_INIT;
470         p_sys->stereo = stereo;
471         callback.callback_id = SPEEX_INBAND_STEREO;
472         callback.func = speex_std_stereo_request_handler;
473         callback.data = &p_sys->stereo;
474         speex_decoder_ctl( p_state, SPEEX_SET_HANDLER, &callback );
475     }
476     if( p_header->nb_channels <= 0 ||
477         p_header->nb_channels > 5 )
478     {
479         msg_Err( p_dec, "invalid number of channels (not between 1 and 5): %i",
480                  p_header->nb_channels );
481         return VLC_EGENERIC;
482     }
483
484     /* Setup the format */
485     p_dec->fmt_out.audio.i_physical_channels =
486         p_dec->fmt_out.audio.i_original_channels =
487             pi_channels_maps[p_header->nb_channels];
488     p_dec->fmt_out.audio.i_channels = p_header->nb_channels;
489     p_dec->fmt_out.audio.i_rate = p_header->rate;
490
491     date_Init( &p_sys->end_date, p_header->rate, 1 );
492
493     return VLC_SUCCESS;
494 }
495
496 /*****************************************************************************
497  * ProcessPacket: processes a Speex packet.
498  *****************************************************************************/
499 static void *ProcessPacket( decoder_t *p_dec, ogg_packet *p_oggpacket,
500                             block_t **pp_block )
501 {
502     decoder_sys_t *p_sys = p_dec->p_sys;
503     block_t *p_block = *pp_block;
504
505     /* Date management */
506     if( p_block && p_block->i_pts > 0 && 
507         p_block->i_pts != date_Get( &p_sys->end_date ) )
508     {
509         date_Set( &p_sys->end_date, p_block->i_pts );
510     }
511
512     if( !date_Get( &p_sys->end_date ) )
513     {
514         /* We've just started the stream, wait for the first PTS. */
515         if( p_block ) block_Release( p_block );
516         return NULL;
517     }
518
519     *pp_block = NULL; /* To avoid being fed the same packet again */
520
521     if( p_sys->b_packetizer )
522     {
523         if ( p_sys->p_header->frames_per_packet > 1 )
524         {
525             short *p_frame_holder = NULL;
526             int i_bits_before = 0, i_bits_after = 0, i_bytes_in_speex_frame = 0,
527                 i_pcm_output_size = 0, i_bits_in_speex_frame = 0;
528             block_t *p_new_block = NULL;
529
530             i_pcm_output_size = p_sys->p_header->frame_size;
531             p_frame_holder = (short*)xmalloc( sizeof(short)*i_pcm_output_size );
532
533             speex_bits_read_from( &p_sys->bits, (char*)p_oggpacket->packet,
534                 p_oggpacket->bytes);
535             i_bits_before = speex_bits_remaining( &p_sys->bits );
536             speex_decode_int(p_sys->p_state, &p_sys->bits, p_frame_holder);
537             i_bits_after = speex_bits_remaining( &p_sys->bits );
538
539             i_bits_in_speex_frame = i_bits_before - i_bits_after;
540             i_bytes_in_speex_frame = ( i_bits_in_speex_frame + 
541                 (8 - (i_bits_in_speex_frame % 8)) )
542                 / 8;
543
544             p_new_block = block_New( p_dec, i_bytes_in_speex_frame );
545             memset( p_new_block->p_buffer, 0xff, i_bytes_in_speex_frame );
546
547             /*
548              * Copy the first frame in this packet to a new packet.
549              */
550             speex_bits_rewind( &p_sys->bits );
551             speex_bits_write( &p_sys->bits, 
552                 (char*)p_new_block->p_buffer, 
553                     (int)i_bytes_in_speex_frame );
554
555             /*
556              * Move the remaining part of the original packet (subsequent
557              * frames, if there are any) into the beginning 
558              * of the original packet so
559              * they are preserved following the realloc. 
560              * Note: Any bits that
561              * remain in the initial packet
562              * are "filler" if they do not constitute
563              * an entire byte. 
564              */
565             if ( i_bits_after > 7 )
566             {
567                 /* round-down since we rounded-up earlier (to include
568                  * the speex terminator code. 
569                  */
570                 i_bytes_in_speex_frame--;
571                 speex_bits_write( &p_sys->bits, 
572                         (char*)p_block->p_buffer, 
573                         p_block->i_buffer - i_bytes_in_speex_frame );
574             p_block = block_Realloc( p_block, 
575                     0, 
576                         p_block->i_buffer-i_bytes_in_speex_frame );
577                 *pp_block = p_block;
578             }
579             else
580             {
581                 speex_bits_reset( &p_sys->bits );
582             }
583
584             free( p_frame_holder );
585             return SendPacket( p_dec, p_new_block);
586         }
587         else
588         {
589             return SendPacket( p_dec, p_block );
590         }
591     }
592     else
593     {
594         aout_buffer_t *p_aout_buffer;
595
596         if( p_sys->i_headers >= p_sys->p_header->extra_headers + 2 )
597             p_aout_buffer = DecodePacket( p_dec, p_oggpacket );
598         else
599             p_aout_buffer = NULL; /* Skip headers */
600
601         if( p_block ) block_Release( p_block );
602         return p_aout_buffer;
603     }
604 }
605
606 static aout_buffer_t *DecodeRtpSpeexPacket( decoder_t *p_dec, block_t **pp_block )
607 {
608     block_t *p_speex_bit_block = *pp_block;
609     decoder_sys_t *p_sys = p_dec->p_sys;
610     aout_buffer_t *p_aout_buffer;
611     int i_decode_ret;
612     unsigned int i_speex_frame_size;
613
614     if ( !p_speex_bit_block || p_speex_bit_block->i_pts == 0 ) return NULL;
615
616     /* 
617       If the SpeexBits buffer size is 0 (a default value),
618       we know that a proper initialization has not yet been done.
619     */
620     if ( p_sys->bits.buf_size==0 )
621     {
622         p_sys->p_header = (SpeexHeader *)malloc(sizeof(SpeexHeader));
623         if ( !p_sys->p_header )
624         {
625             msg_Err( p_dec, "Could not allocate a Speex header.");
626             return NULL;
627         }
628         speex_init_header( p_sys->p_header,p_sys->rtp_rate,1,&speex_nb_mode );
629         speex_bits_init( &p_sys->bits );
630         p_sys->p_state = speex_decoder_init( &speex_nb_mode );
631         if ( !p_sys->p_state )
632         {
633             msg_Err( p_dec, "Could not allocate a Speex decoder." );
634             free( p_sys->p_header );
635             return NULL;
636         }
637
638         /*
639           Assume that variable bit rate is enabled. Also assume
640           that there is only one frame per packet. 
641         */
642         p_sys->p_header->vbr = 1;
643         p_sys->p_header->frames_per_packet = 1;
644
645         p_dec->fmt_out.audio.i_channels = p_sys->p_header->nb_channels;
646         p_dec->fmt_out.audio.i_physical_channels = 
647         p_dec->fmt_out.audio.i_original_channels = 
648             pi_channels_maps[p_sys->p_header->nb_channels];
649         p_dec->fmt_out.audio.i_rate = p_sys->p_header->rate;
650
651         if ( speex_mode_query( &speex_nb_mode, 
652             SPEEX_MODE_FRAME_SIZE, 
653             &i_speex_frame_size ) )
654         {
655             msg_Err( p_dec, "Could not determine the frame size." );
656             speex_decoder_destroy( p_sys->p_state );
657             free( p_sys->p_header );
658             return NULL;
659         }
660         p_dec->fmt_out.audio.i_bytes_per_frame = i_speex_frame_size;
661
662         date_Init(&p_sys->end_date, p_sys->p_header->rate, 1);
663     }
664
665     /* 
666       If the SpeexBits are initialized but there is 
667       still no header, an error must be thrown.
668     */
669     if ( !p_sys->p_header )
670     {
671         msg_Err( p_dec, "There is no valid Speex header found." );
672         return NULL;
673     }
674     *pp_block = NULL;
675
676     if ( !date_Get( &p_sys->end_date ) )
677         date_Set( &p_sys->end_date, p_speex_bit_block->i_dts );
678
679     /*
680       Ask for a new audio output buffer and make sure
681       we get one. 
682     */
683     p_aout_buffer = decoder_NewAudioBuffer( p_dec, 
684         p_sys->p_header->frame_size );
685     if ( !p_aout_buffer || p_aout_buffer->i_buffer == 0 )
686     {
687         msg_Err(p_dec, "Oops: No new buffer was returned!");
688         return NULL;
689     }
690
691     /*
692       Read the Speex payload into the SpeexBits buffer.
693     */
694     speex_bits_read_from( &p_sys->bits, 
695         (char*)p_speex_bit_block->p_buffer, 
696         p_speex_bit_block->i_buffer );
697     
698     /* 
699       Decode the input and ensure that no errors 
700       were encountered.
701     */
702     i_decode_ret = speex_decode_int( p_sys->p_state, &p_sys->bits, 
703             (int16_t*)p_aout_buffer->p_buffer );
704     if ( i_decode_ret < 0 )
705     {
706         msg_Err( p_dec, "Decoding failed. Perhaps we have a bad stream?" );
707         return NULL;
708     }
709
710     /* 
711       Handle date management on the audio output buffer. 
712     */
713     p_aout_buffer->i_pts = date_Get( &p_sys->end_date );
714     p_aout_buffer->i_length = date_Increment( &p_sys->end_date,
715         p_sys->p_header->frame_size ) - p_aout_buffer->i_pts;
716     
717     
718     p_sys->i_frame_in_packet++;
719     block_Release( p_speex_bit_block );
720
721     return p_aout_buffer;
722 }
723
724 /*****************************************************************************
725  * DecodePacket: decodes a Speex packet.
726  *****************************************************************************/
727 static aout_buffer_t *DecodePacket( decoder_t *p_dec, ogg_packet *p_oggpacket )
728 {
729     decoder_sys_t *p_sys = p_dec->p_sys;
730
731     if( p_oggpacket->bytes )
732     {
733         /* Copy Ogg packet to Speex bitstream */
734         speex_bits_read_from( &p_sys->bits, (char *)p_oggpacket->packet,
735                               p_oggpacket->bytes );
736         p_sys->i_frame_in_packet = 0;
737     }
738
739     /* Decode one frame at a time */
740     if( p_sys->i_frame_in_packet < p_sys->p_header->frames_per_packet )
741     {
742         aout_buffer_t *p_aout_buffer;
743         if( p_sys->p_header->frame_size == 0 )
744             return NULL;
745
746         p_aout_buffer =
747             decoder_NewAudioBuffer( p_dec, p_sys->p_header->frame_size );
748         if( !p_aout_buffer )
749         {
750             return NULL;
751         }
752
753         switch( speex_decode_int( p_sys->p_state, &p_sys->bits,
754                                   (int16_t *)p_aout_buffer->p_buffer ) )
755         {
756             case -2:
757                 msg_Err( p_dec, "decoding error: corrupted stream?" );
758             case -1: /* End of stream */
759                 return NULL;
760         }
761
762         if( speex_bits_remaining( &p_sys->bits ) < 0 )
763         {
764             msg_Err( p_dec, "decoding overflow: corrupted stream?" );
765         }
766
767         if( p_sys->p_header->nb_channels == 2 )
768             speex_decode_stereo_int( (int16_t *)p_aout_buffer->p_buffer,
769                                      p_sys->p_header->frame_size,
770                                      &p_sys->stereo );
771
772         /* Date management */
773         p_aout_buffer->i_pts = date_Get( &p_sys->end_date );
774         p_aout_buffer->i_length =
775             date_Increment( &p_sys->end_date, p_sys->p_header->frame_size )
776             - p_aout_buffer->i_pts;
777
778         p_sys->i_frame_in_packet++;
779
780         return p_aout_buffer;
781     }
782     else
783     {
784         return NULL;
785     }
786 }
787
788 /*****************************************************************************
789  * SendPacket: send an ogg packet to the stream output.
790  *****************************************************************************/
791 static block_t *SendPacket( decoder_t *p_dec, block_t *p_block )
792 {
793     decoder_sys_t *p_sys = p_dec->p_sys;
794
795     /* Date management */
796     p_block->i_dts = p_block->i_pts = date_Get( &p_sys->end_date );
797
798     if( p_sys->i_headers >= p_sys->p_header->extra_headers + 2 )
799     {
800         p_block->i_length =
801             date_Increment( &p_sys->end_date,
802                                 p_sys->p_header->frame_size ) -
803             p_block->i_pts;
804     }
805     else
806         p_block->i_length = 0;
807
808     return p_block;
809 }
810
811 /*****************************************************************************
812  * ParseSpeexComments:
813  *****************************************************************************/
814 #define readint(buf, base) (((buf[base+3]<<24)&0xff000000)| \
815                            ((buf[base+2]<<16)&0xff0000)| \
816                            ((buf[base+1]<<8)&0xff00)| \
817                             (buf[base]&0xff))
818
819 static void ParseSpeexComments( decoder_t *p_dec, ogg_packet *p_oggpacket )
820 {
821     decoder_sys_t *p_sys = p_dec->p_sys;
822     const SpeexMode *p_mode;
823
824     assert( p_sys->p_header->mode < SPEEX_NB_MODES );
825
826     p_mode = speex_mode_list[p_sys->p_header->mode];
827     assert( p_mode != NULL );
828
829     if( !p_dec->p_description )
830     {
831         p_dec->p_description = vlc_meta_New();
832         if( !p_dec->p_description )
833             return;
834     }
835
836     /* */
837     char *psz_mode;
838     if( asprintf( &psz_mode, "%s%s", p_mode->modeName, p_sys->p_header->vbr ? " VBR" : "" ) >= 0 )
839     {
840         vlc_meta_AddExtra( p_dec->p_description, _("Mode"), psz_mode );
841         free( psz_mode );
842     }
843
844     /* TODO: finish comments parsing */
845     VLC_UNUSED( p_oggpacket );
846 }
847
848 /*****************************************************************************
849  * CloseDecoder: speex decoder destruction
850  *****************************************************************************/
851 static void CloseDecoder( vlc_object_t *p_this )
852 {
853     decoder_t * p_dec = (decoder_t *)p_this;
854     decoder_sys_t *p_sys = p_dec->p_sys;
855
856     if( p_sys->p_state )
857     {
858         speex_decoder_destroy( p_sys->p_state );
859         speex_bits_destroy( &p_sys->bits );
860     }
861
862     free( p_sys->p_header );
863     free( p_sys );
864 }
865
866 /*****************************************************************************
867  * encoder_sys_t: encoder descriptor
868  *****************************************************************************/
869 #define MAX_FRAME_SIZE  2000
870 #define MAX_FRAME_BYTES 2000
871
872 struct encoder_sys_t
873 {
874     /*
875      * Input properties
876      */
877     char *p_buffer;
878     char p_buffer_out[MAX_FRAME_BYTES];
879
880     /*
881      * Speex properties
882      */
883     SpeexBits bits;
884     SpeexHeader header;
885     SpeexStereoState stereo;
886     void *p_state;
887
888     int i_frames_per_packet;
889     int i_frames_in_packet;
890
891     int i_frame_length;
892     int i_samples_delay;
893     int i_frame_size;
894
895     /*
896      * Common properties
897      */
898     mtime_t i_pts;
899 };
900
901 /*****************************************************************************
902  * OpenEncoder: probe the encoder and return score
903  *****************************************************************************/
904 static int OpenEncoder( vlc_object_t *p_this )
905 {
906     encoder_t *p_enc = (encoder_t *)p_this;
907     encoder_sys_t *p_sys;
908     const SpeexMode *p_speex_mode = &speex_nb_mode;
909     int i_tmp, i;
910     const char *pp_header[2];
911     int pi_header[2];
912     uint8_t *p_extra;
913
914     if( p_enc->fmt_out.i_codec != VLC_CODEC_SPEEX &&
915         !p_enc->b_force )
916     {
917         return VLC_EGENERIC;
918     }
919
920     config_ChainParse( p_enc, ENC_CFG_PREFIX, ppsz_enc_options, p_enc->p_cfg );
921     switch( var_GetInteger( p_enc, ENC_CFG_PREFIX "mode" ) )
922     {
923     case 1:
924         msg_Dbg( p_enc, "Using wideband" );
925         p_speex_mode = &speex_wb_mode;
926         break;
927     case 2:
928         msg_Dbg( p_enc, "Using ultra-wideband" );
929         p_speex_mode = &speex_uwb_mode;
930         break;
931     default:
932         msg_Dbg( p_enc, "Using narrowband" );
933         p_speex_mode = &speex_nb_mode;
934         break;
935     }
936
937     /* Allocate the memory needed to store the decoder's structure */
938     if( ( p_sys = (encoder_sys_t *)malloc(sizeof(encoder_sys_t)) ) == NULL )
939         return VLC_ENOMEM;
940     p_enc->p_sys = p_sys;
941     p_enc->pf_encode_audio = Encode;
942     p_enc->fmt_in.i_codec = VLC_CODEC_S16N;
943     p_enc->fmt_out.i_codec = VLC_CODEC_SPEEX;
944
945     speex_init_header( &p_sys->header, p_enc->fmt_in.audio.i_rate,
946                        1, p_speex_mode );
947
948     p_sys->header.frames_per_packet = 1;
949     p_sys->header.vbr = var_GetBool( p_enc, ENC_CFG_PREFIX "cbr" ) ? 0 : 1;
950     p_sys->header.nb_channels = p_enc->fmt_in.audio.i_channels;
951
952     /* Create a new encoder state in narrowband mode */
953     p_sys->p_state = speex_encoder_init( p_speex_mode );
954
955     /* Parameters */
956     i_tmp = var_GetInteger( p_enc, ENC_CFG_PREFIX "complexity" );
957     speex_encoder_ctl( p_sys->p_state, SPEEX_SET_COMPLEXITY, &i_tmp );
958
959     i_tmp = var_GetBool( p_enc, ENC_CFG_PREFIX "cbr" ) ? 0 : 1;
960     speex_encoder_ctl( p_sys->p_state, SPEEX_SET_VBR, &i_tmp );
961
962     if( i_tmp == 0 ) /* CBR */
963     {
964         i_tmp = var_GetFloat( p_enc, ENC_CFG_PREFIX "quality" );
965         speex_encoder_ctl( p_sys->p_state, SPEEX_SET_QUALITY, &i_tmp );
966
967         i_tmp = var_GetBool( p_enc, ENC_CFG_PREFIX "vad" ) ? 1 : 0;
968         speex_encoder_ctl( p_sys->p_state, SPEEX_SET_VAD, &i_tmp );
969     }
970     else
971     {
972         float f_tmp;
973
974         f_tmp = var_GetFloat( p_enc, ENC_CFG_PREFIX "quality" );
975         speex_encoder_ctl( p_sys->p_state, SPEEX_SET_VBR_QUALITY, &f_tmp );
976
977         i_tmp = var_GetInteger( p_enc, ENC_CFG_PREFIX "max-bitrate" );
978         if( i_tmp > 0 )
979 #ifdef SPEEX_SET_VBR_MAX_BITRATE
980             speex_encoder_ctl( p_sys->p_state, SPEEX_SET_VBR_MAX_BITRATE, &i_tmp );
981 #else
982             msg_Dbg( p_enc, "max-bitrate cannot be set in this version of libspeex");
983 #endif
984     }
985
986     i_tmp = var_GetBool( p_enc, ENC_CFG_PREFIX "dtx" ) ? 1 : 0;
987     speex_encoder_ctl( p_sys->p_state, SPEEX_SET_DTX, &i_tmp );
988
989
990     /*Initialization of the structure that holds the bits*/
991     speex_bits_init( &p_sys->bits );
992
993     p_sys->i_frames_in_packet = 0;
994     p_sys->i_samples_delay = 0;
995     p_sys->i_pts = 0;
996
997     speex_encoder_ctl( p_sys->p_state, SPEEX_GET_FRAME_SIZE,
998                        &p_sys->i_frame_length );
999
1000     p_sys->i_frame_size = p_sys->i_frame_length *
1001         sizeof(int16_t) * p_enc->fmt_in.audio.i_channels;
1002     p_sys->p_buffer = xmalloc( p_sys->i_frame_size );
1003
1004     /* Create and store headers */
1005     pp_header[0] = speex_header_to_packet( &p_sys->header, &pi_header[0] );
1006     pp_header[1] = "ENCODER=VLC media player";
1007     pi_header[1] = sizeof("ENCODER=VLC media player");
1008
1009     p_enc->fmt_out.i_extra = 3 * 2 + pi_header[0] + pi_header[1];
1010     p_extra = p_enc->fmt_out.p_extra = xmalloc( p_enc->fmt_out.i_extra );
1011     for( i = 0; i < 2; i++ )
1012     {
1013         *(p_extra++) = pi_header[i] >> 8;
1014         *(p_extra++) = pi_header[i] & 0xFF;
1015         memcpy( p_extra, pp_header[i], pi_header[i] );
1016         p_extra += pi_header[i];
1017     }
1018
1019     msg_Dbg( p_enc, "encoding: frame size:%d, channels:%d, samplerate:%d",
1020              p_sys->i_frame_size, p_enc->fmt_in.audio.i_channels,
1021              p_enc->fmt_in.audio.i_rate );
1022
1023     return VLC_SUCCESS;
1024 }
1025
1026 /****************************************************************************
1027  * Encode: the whole thing
1028  ****************************************************************************
1029  * This function spits out ogg packets.
1030  ****************************************************************************/
1031 static block_t *Encode( encoder_t *p_enc, aout_buffer_t *p_aout_buf )
1032 {
1033     encoder_sys_t *p_sys = p_enc->p_sys;
1034     block_t *p_block, *p_chain = NULL;
1035
1036     unsigned char *p_buffer = p_aout_buf->p_buffer;
1037     int i_samples = p_aout_buf->i_nb_samples;
1038     int i_samples_delay = p_sys->i_samples_delay;
1039
1040     p_sys->i_pts = p_aout_buf->i_pts -
1041                 (mtime_t)1000000 * (mtime_t)p_sys->i_samples_delay /
1042                 (mtime_t)p_enc->fmt_in.audio.i_rate;
1043
1044     p_sys->i_samples_delay += i_samples;
1045
1046     while( p_sys->i_samples_delay >= p_sys->i_frame_length )
1047     {
1048         int16_t *p_samples;
1049         int i_out;
1050
1051         if( i_samples_delay )
1052         {
1053             /* Take care of the left-over from last time */
1054             int i_delay_size = i_samples_delay * 2 *
1055                                  p_enc->fmt_in.audio.i_channels;
1056             int i_size = p_sys->i_frame_size - i_delay_size;
1057
1058             p_samples = (int16_t *)p_sys->p_buffer;
1059             memcpy( p_sys->p_buffer + i_delay_size, p_buffer, i_size );
1060             p_buffer -= i_delay_size;
1061             i_samples += i_samples_delay;
1062             i_samples_delay = 0;
1063         }
1064         else
1065         {
1066             p_samples = (int16_t *)p_buffer;
1067         }
1068
1069         /* Encode current frame */
1070         if( p_enc->fmt_in.audio.i_channels == 2 )
1071             speex_encode_stereo_int( p_samples, p_sys->i_frame_length,
1072                                      &p_sys->bits );
1073
1074 #if 0
1075         if( p_sys->preprocess )
1076             speex_preprocess( p_sys->preprocess, p_samples, NULL );
1077 #endif
1078
1079         speex_encode_int( p_sys->p_state, p_samples, &p_sys->bits );
1080
1081         p_buffer += p_sys->i_frame_size;
1082         p_sys->i_samples_delay -= p_sys->i_frame_length;
1083         i_samples -= p_sys->i_frame_length;
1084
1085         p_sys->i_frames_in_packet++;
1086
1087         if( p_sys->i_frames_in_packet < p_sys->header.frames_per_packet )
1088             continue;
1089
1090         p_sys->i_frames_in_packet = 0;
1091
1092         speex_bits_insert_terminator( &p_sys->bits );
1093         i_out = speex_bits_write( &p_sys->bits, p_sys->p_buffer_out,
1094                                   MAX_FRAME_BYTES );
1095         speex_bits_reset( &p_sys->bits );
1096
1097         p_block = block_New( p_enc, i_out );
1098         memcpy( p_block->p_buffer, p_sys->p_buffer_out, i_out );
1099
1100         p_block->i_length = (mtime_t)1000000 *
1101             (mtime_t)p_sys->i_frame_length * p_sys->header.frames_per_packet /
1102             (mtime_t)p_enc->fmt_in.audio.i_rate;
1103
1104         p_block->i_dts = p_block->i_pts = p_sys->i_pts;
1105
1106         /* Update pts */
1107         p_sys->i_pts += p_block->i_length;
1108         block_ChainAppend( &p_chain, p_block );
1109
1110     }
1111
1112     /* Backup the remaining raw samples */
1113     if( i_samples )
1114     {
1115         memcpy( p_sys->p_buffer + i_samples_delay * 2 *
1116                 p_enc->fmt_in.audio.i_channels, p_buffer,
1117                 i_samples * 2 * p_enc->fmt_in.audio.i_channels );
1118     }
1119
1120     return p_chain;
1121 }
1122
1123 /*****************************************************************************
1124  * CloseEncoder: encoder destruction
1125  *****************************************************************************/
1126 static void CloseEncoder( vlc_object_t *p_this )
1127 {
1128     encoder_t *p_enc = (encoder_t *)p_this;
1129     encoder_sys_t *p_sys = p_enc->p_sys;
1130
1131     speex_encoder_destroy( p_sys->p_state );
1132     speex_bits_destroy( &p_sys->bits );
1133
1134     free( p_sys->p_buffer );
1135     free( p_sys );
1136 }