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