]> git.sesse.net Git - vlc/blob - modules/codec/speex.c
Trailing ;
[vlc] / modules / codec / speex.c
1 /*****************************************************************************
2  * speex.c: speex decoder/packetizer/encoder module making use of libspeex.
3  *****************************************************************************
4  * Copyright (C) 2003-2008 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     audio_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 = p_dec->p_sys;
207
208     if( p_dec->fmt_in.i_codec != VLC_FOURCC('s','p','x',' ') 
209         && p_dec->fmt_in.i_codec != VLC_FOURCC('s', 'p', 'x', 'r') )
210     {
211         return VLC_EGENERIC;
212     }
213
214     /* Allocate the memory needed to store the decoder's structure */
215     if( ( p_dec->p_sys = p_sys =
216           (decoder_sys_t *)malloc(sizeof(decoder_sys_t)) ) == NULL )
217         return VLC_ENOMEM;
218     p_dec->p_sys->bits.buf_size = 0;
219     p_dec->p_sys->b_packetizer = false;
220     p_dec->p_sys->rtp_rate = p_dec->fmt_in.audio.i_rate;
221
222     aout_DateSet( &p_sys->end_date, 0 );
223
224     /* Set output properties */
225     p_dec->fmt_out.i_cat = AUDIO_ES;
226     p_dec->fmt_out.i_codec = AOUT_FMT_S16_NE;
227
228     /*
229       Set callbacks
230       If the codec is spxr then this decoder is 
231       being invoked on a Speex stream arriving via RTP. 
232       A special decoder callback is used.
233     */
234     if (p_dec->fmt_in.i_codec == VLC_FOURCC('s', 'p', 'x', 'r'))
235     {
236         msg_Dbg( p_dec, "Using RTP version of Speex decoder @ rate %d.", 
237             p_dec->fmt_in.audio.i_rate );
238         p_dec->pf_decode_audio = (aout_buffer_t *(*)(decoder_t *, block_t **))
239             DecodeRtpSpeexPacket;
240     }
241     else
242     {
243         p_dec->pf_decode_audio = (aout_buffer_t *(*)(decoder_t *, block_t **))
244             DecodeBlock;
245     }
246     p_dec->pf_packetize    = (block_t *(*)(decoder_t *, block_t **))
247         DecodeBlock;
248
249     p_sys->i_headers = 0;
250     p_sys->p_state = NULL;
251     p_sys->p_header = NULL;
252     p_sys->i_frame_in_packet = 0;
253
254     return VLC_SUCCESS;
255 }
256
257 static int OpenPacketizer( vlc_object_t *p_this )
258 {
259     decoder_t *p_dec = (decoder_t*)p_this;
260
261     int i_ret = OpenDecoder( p_this );
262
263     if( i_ret == VLC_SUCCESS )
264     {
265         p_dec->p_sys->b_packetizer = true;
266         p_dec->fmt_out.i_codec = VLC_FOURCC('s','p','x',' ');
267     }
268
269     return i_ret;
270 }
271
272 /****************************************************************************
273  * DecodeBlock: the whole thing
274  ****************************************************************************
275  * This function must be fed with ogg packets.
276  ****************************************************************************/
277 static void *DecodeBlock( decoder_t *p_dec, block_t **pp_block )
278 {
279     decoder_sys_t *p_sys = p_dec->p_sys;
280     ogg_packet oggpacket;
281
282     if( !pp_block ) return NULL;
283
284     if( *pp_block )
285     {
286         /* Block to Ogg packet */
287         oggpacket.packet = (*pp_block)->p_buffer;
288         oggpacket.bytes = (*pp_block)->i_buffer;
289     }
290     else
291     {
292         if( p_sys->b_packetizer ) return NULL;
293
294         /* Block to Ogg packet */
295         oggpacket.packet = NULL;
296         oggpacket.bytes = 0;
297     }
298
299     oggpacket.granulepos = -1;
300     oggpacket.b_o_s = 0;
301     oggpacket.e_o_s = 0;
302     oggpacket.packetno = 0;
303
304     /* Check for headers */
305     if( p_sys->i_headers == 0 && p_dec->fmt_in.i_extra )
306     {
307         p_sys->i_headers = 2;
308     }
309     else if( oggpacket.bytes && p_sys->i_headers < 2 )
310     {
311         uint8_t *p_extra;
312
313         p_dec->fmt_in.p_extra =
314             realloc( p_dec->fmt_in.p_extra, p_dec->fmt_in.i_extra +
315                      oggpacket.bytes + 2 );
316         p_extra = ((uint8_t *)p_dec->fmt_in.p_extra) + p_dec->fmt_in.i_extra;
317         *(p_extra++) = oggpacket.bytes >> 8;
318         *(p_extra++) = oggpacket.bytes & 0xFF;
319
320         memcpy( p_extra, oggpacket.packet, oggpacket.bytes );
321         p_dec->fmt_in.i_extra += oggpacket.bytes + 2;
322
323         block_Release( *pp_block );
324         p_sys->i_headers++;
325         return NULL;
326     }
327
328     if( p_sys->i_headers == 2 )
329     {
330         if( ProcessHeaders( p_dec ) != VLC_SUCCESS )
331         {
332             p_sys->i_headers = 0;
333             p_dec->fmt_in.i_extra = 0;
334             block_Release( *pp_block );
335             return NULL;
336         }
337         else p_sys->i_headers++;
338     }
339
340     return ProcessPacket( p_dec, &oggpacket, pp_block );
341 }
342
343 /*****************************************************************************
344  * ProcessHeaders: process Speex headers.
345  *****************************************************************************/
346 static int ProcessHeaders( decoder_t *p_dec )
347 {
348     decoder_sys_t *p_sys = p_dec->p_sys;
349     ogg_packet oggpacket;
350     uint8_t *p_extra;
351     int i_extra;
352
353     if( !p_dec->fmt_in.i_extra ) return VLC_EGENERIC;
354
355     oggpacket.granulepos = -1;
356     oggpacket.b_o_s = 1; /* yes this actually is a b_o_s packet :) */
357     oggpacket.e_o_s = 0;
358     oggpacket.packetno = 0;
359     p_extra = p_dec->fmt_in.p_extra;
360     i_extra = p_dec->fmt_in.i_extra;
361
362     /* Take care of the initial Vorbis header */
363     oggpacket.bytes = *(p_extra++) << 8;
364     oggpacket.bytes |= (*(p_extra++) & 0xFF);
365     oggpacket.packet = p_extra;
366     p_extra += oggpacket.bytes;
367     i_extra -= (oggpacket.bytes + 2);
368     if( i_extra < 0 )
369     {
370         msg_Err( p_dec, "header data corrupted");
371         return VLC_EGENERIC;
372     }
373
374     /* Take care of the initial Speex header */
375     if( ProcessInitialHeader( p_dec, &oggpacket ) != VLC_SUCCESS )
376     {
377         msg_Err( p_dec, "initial Speex header is corrupted" );
378         return VLC_EGENERIC;
379     }
380
381     /* The next packet in order is the comments header */
382     oggpacket.b_o_s = 0;
383     oggpacket.bytes = *(p_extra++) << 8;
384     oggpacket.bytes |= (*(p_extra++) & 0xFF);
385     oggpacket.packet = p_extra;
386     p_extra += oggpacket.bytes;
387     i_extra -= (oggpacket.bytes + 2);
388     if( i_extra < 0 )
389     {
390         msg_Err( p_dec, "header data corrupted");
391         return VLC_EGENERIC;
392     }
393
394     ParseSpeexComments( p_dec, &oggpacket );
395
396     if( p_sys->b_packetizer )
397     {
398         p_dec->fmt_out.i_extra = p_dec->fmt_in.i_extra;
399         p_dec->fmt_out.p_extra =
400             realloc( p_dec->fmt_out.p_extra, p_dec->fmt_out.i_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     aout_DateInit( &p_sys->end_date, p_header->rate );
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 != aout_DateGet( &p_sys->end_date ) )
513     {
514         aout_DateSet( &p_sys->end_date, p_block->i_pts );
515     }
516
517     if( !aout_DateGet( &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
538             speex_bits_read_from( &p_sys->bits, (char*)p_oggpacket->packet,
539                 p_oggpacket->bytes);
540             i_bits_before = speex_bits_remaining( &p_sys->bits );
541             speex_decode_int(p_sys->p_state, &p_sys->bits, p_frame_holder);
542             i_bits_after = speex_bits_remaining( &p_sys->bits );
543
544             i_bits_in_speex_frame = i_bits_before - i_bits_after;
545             i_bytes_in_speex_frame = ( i_bits_in_speex_frame + 
546                 (8 - (i_bits_in_speex_frame % 8)) )
547                 / 8;
548
549             p_new_block = block_New( p_dec, i_bytes_in_speex_frame );
550             memset( p_new_block->p_buffer, 0xff, i_bytes_in_speex_frame );
551
552             /*
553              * Copy the first frame in this packet to a new packet.
554              */
555             speex_bits_rewind( &p_sys->bits );
556             speex_bits_write( &p_sys->bits, 
557                 (char*)p_new_block->p_buffer, 
558                     (int)i_bytes_in_speex_frame );
559
560             /*
561              * Move the remaining part of the original packet (subsequent
562              * frames, if there are any) into the beginning 
563              * of the original packet so
564              * they are preserved following the realloc. 
565              * Note: Any bits that
566              * remain in the initial packet
567              * are "filler" if they do not constitute
568              * an entire byte. 
569              */
570             if ( i_bits_after > 7 )
571             {
572                 /* round-down since we rounded-up earlier (to include
573                  * the speex terminator code. 
574                  */
575                 i_bytes_in_speex_frame--;
576                 speex_bits_write( &p_sys->bits, 
577                         (char*)p_block->p_buffer, 
578                         p_block->i_buffer - i_bytes_in_speex_frame );
579             p_block = block_Realloc( p_block, 
580                     0, 
581                         p_block->i_buffer-i_bytes_in_speex_frame );
582                 *pp_block = p_block;
583             }
584             else
585             {
586                 speex_bits_reset( &p_sys->bits );
587             }
588
589             free( p_frame_holder );
590             return SendPacket( p_dec, p_new_block);
591         }
592         else
593         {
594             return SendPacket( p_dec, p_block );
595         }
596     }
597     else
598     {
599         aout_buffer_t *p_aout_buffer;
600
601         if( p_sys->i_headers >= p_sys->p_header->extra_headers + 2 )
602             p_aout_buffer = DecodePacket( p_dec, p_oggpacket );
603         else
604             p_aout_buffer = NULL; /* Skip headers */
605
606         if( p_block ) block_Release( p_block );
607         return p_aout_buffer;
608     }
609 }
610
611 static aout_buffer_t *DecodeRtpSpeexPacket( decoder_t *p_dec, block_t **pp_block )
612 {
613     block_t *p_speex_bit_block = *pp_block;
614     decoder_sys_t *p_sys = p_dec->p_sys;
615     aout_buffer_t *p_aout_buffer;
616     int i_decode_ret;
617     unsigned int i_speex_frame_size;
618
619     if ( !p_speex_bit_block || p_speex_bit_block->i_pts == 0 ) return NULL;
620
621     /* 
622       If the SpeexBits buffer size is 0 (a default value),
623       we know that a proper initialization has not yet been done.
624     */
625     if ( p_sys->bits.buf_size==0 )
626     {
627         p_sys->p_header = (SpeexHeader *)malloc(sizeof(SpeexHeader));
628         if ( !p_sys->p_header )
629         {
630             msg_Err( p_dec, "Could not allocate a Speex header.");
631             return NULL;
632         }
633         speex_init_header( p_sys->p_header,p_sys->rtp_rate,1,&speex_nb_mode );
634         speex_bits_init( &p_sys->bits );
635         p_sys->p_state = speex_decoder_init( &speex_nb_mode );
636         if ( !p_sys->p_state )
637         {
638             msg_Err( p_dec, "Could not allocate a Speex decoder." );
639             free( p_sys->p_header );
640             return NULL;
641         }
642
643         /*
644           Assume that variable bit rate is enabled. Also assume
645           that there is only one frame per packet. 
646         */
647         p_sys->p_header->vbr = 1;
648         p_sys->p_header->frames_per_packet = 1;
649
650         p_dec->fmt_out.audio.i_channels = p_sys->p_header->nb_channels;
651         p_dec->fmt_out.audio.i_physical_channels = 
652         p_dec->fmt_out.audio.i_original_channels = 
653             pi_channels_maps[p_sys->p_header->nb_channels];
654         p_dec->fmt_out.audio.i_rate = p_sys->p_header->rate;
655
656         if ( speex_mode_query( &speex_nb_mode, 
657             SPEEX_MODE_FRAME_SIZE, 
658             &i_speex_frame_size ) )
659         {
660             msg_Err( p_dec, "Could not determine the frame size." );
661             speex_decoder_destroy( p_sys->p_state );
662             free( p_sys->p_header );
663             return NULL;
664         }
665         p_dec->fmt_out.audio.i_bytes_per_frame = i_speex_frame_size;
666
667         aout_DateInit(&p_sys->end_date, p_sys->p_header->rate);
668     }
669
670     /* 
671       If the SpeexBits are initialized but there is 
672       still no header, an error must be thrown.
673     */
674     if ( !p_sys->p_header )
675     {
676         msg_Err( p_dec, "There is no valid Speex header found." );
677         return NULL;
678     }
679     *pp_block = NULL;
680
681     if ( !aout_DateGet( &p_sys->end_date ) )
682         aout_DateSet( &p_sys->end_date, p_speex_bit_block->i_dts );
683
684     /*
685       Ask for a new audio output buffer and make sure
686       we get one. 
687     */
688     p_aout_buffer = decoder_NewAudioBuffer( p_dec, 
689         p_sys->p_header->frame_size );
690     if ( !p_aout_buffer || p_aout_buffer->i_nb_bytes == 0 )
691     {
692         msg_Err(p_dec, "Oops: No new buffer was returned!");
693         return NULL;
694     }
695
696     /*
697       Read the Speex payload into the SpeexBits buffer.
698     */
699     speex_bits_read_from( &p_sys->bits, 
700         (char*)p_speex_bit_block->p_buffer, 
701         p_speex_bit_block->i_buffer );
702     
703     /* 
704       Decode the input and ensure that no errors 
705       were encountered.
706     */
707     i_decode_ret = speex_decode_int( p_sys->p_state, &p_sys->bits, 
708             (int16_t*)p_aout_buffer->p_buffer );
709     if ( i_decode_ret < 0 )
710     {
711         msg_Err( p_dec, "Decoding failed. Perhaps we have a bad stream?" );
712         return NULL;
713     }
714
715     /* 
716       Handle date management on the audio output buffer. 
717     */
718     p_aout_buffer->start_date = aout_DateGet( &p_sys->end_date );
719     p_aout_buffer->end_date = aout_DateIncrement( &p_sys->end_date, 
720         p_sys->p_header->frame_size );
721     
722     
723     p_sys->i_frame_in_packet++;
724     block_Release( p_speex_bit_block );
725
726     return p_aout_buffer;
727 }
728
729 /*****************************************************************************
730  * DecodePacket: decodes a Speex packet.
731  *****************************************************************************/
732 static aout_buffer_t *DecodePacket( decoder_t *p_dec, ogg_packet *p_oggpacket )
733 {
734     decoder_sys_t *p_sys = p_dec->p_sys;
735
736     if( p_oggpacket->bytes )
737     {
738         /* Copy Ogg packet to Speex bitstream */
739         speex_bits_read_from( &p_sys->bits, (char *)p_oggpacket->packet,
740                               p_oggpacket->bytes );
741         p_sys->i_frame_in_packet = 0;
742     }
743
744     /* Decode one frame at a time */
745     if( p_sys->i_frame_in_packet < p_sys->p_header->frames_per_packet )
746     {
747         aout_buffer_t *p_aout_buffer;
748         if( p_sys->p_header->frame_size == 0 )
749             return NULL;
750
751         p_aout_buffer =
752             decoder_NewAudioBuffer( p_dec, p_sys->p_header->frame_size );
753         if( !p_aout_buffer )
754         {
755             return NULL;
756         }
757
758         switch( speex_decode_int( p_sys->p_state, &p_sys->bits,
759                                   (int16_t *)p_aout_buffer->p_buffer ) )
760         {
761             case -2:
762                 msg_Err( p_dec, "decoding error: corrupted stream?" );
763             case -1: /* End of stream */
764                 return NULL;
765         }
766
767         if( speex_bits_remaining( &p_sys->bits ) < 0 )
768         {
769             msg_Err( p_dec, "decoding overflow: corrupted stream?" );
770         }
771
772         if( p_sys->p_header->nb_channels == 2 )
773             speex_decode_stereo_int( (int16_t *)p_aout_buffer->p_buffer,
774                                      p_sys->p_header->frame_size,
775                                      &p_sys->stereo );
776
777         /* Date management */
778         p_aout_buffer->start_date = aout_DateGet( &p_sys->end_date );
779         p_aout_buffer->end_date =
780             aout_DateIncrement( &p_sys->end_date, p_sys->p_header->frame_size );
781
782         p_sys->i_frame_in_packet++;
783
784         return p_aout_buffer;
785     }
786     else
787     {
788         return NULL;
789     }
790 }
791
792 /*****************************************************************************
793  * SendPacket: send an ogg packet to the stream output.
794  *****************************************************************************/
795 static block_t *SendPacket( decoder_t *p_dec, block_t *p_block )
796 {
797     decoder_sys_t *p_sys = p_dec->p_sys;
798
799     /* Date management */
800     p_block->i_dts = p_block->i_pts = aout_DateGet( &p_sys->end_date );
801
802     if( p_sys->i_headers >= p_sys->p_header->extra_headers + 2 )
803     {
804         p_block->i_length =
805             aout_DateIncrement( &p_sys->end_date,
806                                 p_sys->p_header->frame_size ) -
807             p_block->i_pts;
808     }
809     else
810         p_block->i_length = 0;
811
812     return p_block;
813 }
814
815 /*****************************************************************************
816  * ParseSpeexComments:
817  *****************************************************************************/
818 #define readint(buf, base) (((buf[base+3]<<24)&0xff000000)| \
819                            ((buf[base+2]<<16)&0xff0000)| \
820                            ((buf[base+1]<<8)&0xff00)| \
821                             (buf[base]&0xff))
822
823 static void ParseSpeexComments( decoder_t *p_dec, ogg_packet *p_oggpacket )
824 {
825     decoder_sys_t *p_sys = p_dec->p_sys;
826     const SpeexMode *p_mode;
827
828     assert( p_sys->p_header->mode < SPEEX_NB_MODES );
829
830     p_mode = speex_mode_list[p_sys->p_header->mode];
831     assert( p_mode != NULL );
832
833     if( !p_dec->p_description )
834     {
835         p_dec->p_description = vlc_meta_New();
836         if( !p_dec->p_description )
837             return;
838     }
839
840     /* */
841     char *psz_mode;
842     if( asprintf( &psz_mode, "%s%s", p_mode->modeName, p_sys->p_header->vbr ? " VBR" : "" ) >= 0 )
843     {
844         vlc_meta_AddExtra( p_dec->p_description, _("Mode"), psz_mode );
845         free( psz_mode );
846     }
847
848     /* TODO: finish comments parsing */
849     VLC_UNUSED( p_oggpacket );
850 }
851
852 /*****************************************************************************
853  * CloseDecoder: speex decoder destruction
854  *****************************************************************************/
855 static void CloseDecoder( vlc_object_t *p_this )
856 {
857     decoder_t * p_dec = (decoder_t *)p_this;
858     decoder_sys_t *p_sys = p_dec->p_sys;
859
860     if( p_sys->p_state )
861     {
862         speex_decoder_destroy( p_sys->p_state );
863         speex_bits_destroy( &p_sys->bits );
864     }
865
866     free( p_sys->p_header );
867     free( p_sys );
868 }
869
870 /*****************************************************************************
871  * encoder_sys_t: encoder descriptor
872  *****************************************************************************/
873 #define MAX_FRAME_SIZE  2000
874 #define MAX_FRAME_BYTES 2000
875
876 struct encoder_sys_t
877 {
878     /*
879      * Input properties
880      */
881     char *p_buffer;
882     char p_buffer_out[MAX_FRAME_BYTES];
883
884     /*
885      * Speex properties
886      */
887     SpeexBits bits;
888     SpeexHeader header;
889     SpeexStereoState stereo;
890     void *p_state;
891
892     int i_frames_per_packet;
893     int i_frames_in_packet;
894
895     int i_frame_length;
896     int i_samples_delay;
897     int i_frame_size;
898
899     /*
900      * Common properties
901      */
902     mtime_t i_pts;
903 };
904
905 /*****************************************************************************
906  * OpenEncoder: probe the encoder and return score
907  *****************************************************************************/
908 static int OpenEncoder( vlc_object_t *p_this )
909 {
910     encoder_t *p_enc = (encoder_t *)p_this;
911     encoder_sys_t *p_sys;
912     const SpeexMode *p_speex_mode = &speex_nb_mode;
913     int i_tmp, i;
914     const char *pp_header[2];
915     int pi_header[2];
916     uint8_t *p_extra;
917
918     if( p_enc->fmt_out.i_codec != VLC_FOURCC('s','p','x',' ') &&
919         !p_enc->b_force )
920     {
921         return VLC_EGENERIC;
922     }
923
924     config_ChainParse( p_enc, ENC_CFG_PREFIX, ppsz_enc_options, p_enc->p_cfg );
925     switch( var_GetInteger( p_enc, ENC_CFG_PREFIX "mode" ) )
926     {
927     case 1:
928         msg_Dbg( p_enc, "Using wideband" );
929         p_speex_mode = &speex_wb_mode;
930         break;
931     case 2:
932         msg_Dbg( p_enc, "Using ultra-wideband" );
933         p_speex_mode = &speex_uwb_mode;
934         break;
935     default:
936         msg_Dbg( p_enc, "Using narrowband" );
937         p_speex_mode = &speex_nb_mode;
938         break;
939     }
940
941     /* Allocate the memory needed to store the decoder's structure */
942     if( ( p_sys = (encoder_sys_t *)malloc(sizeof(encoder_sys_t)) ) == NULL )
943         return VLC_ENOMEM;
944     p_enc->p_sys = p_sys;
945     p_enc->pf_encode_audio = Encode;
946     p_enc->fmt_in.i_codec = AOUT_FMT_S16_NE;
947     p_enc->fmt_out.i_codec = VLC_FOURCC('s','p','x',' ');
948
949     speex_init_header( &p_sys->header, p_enc->fmt_in.audio.i_rate,
950                        1, p_speex_mode );
951
952     p_sys->header.frames_per_packet = 1;
953     p_sys->header.vbr = var_GetBool( p_enc, ENC_CFG_PREFIX "cbr" ) ? 0 : 1;
954     p_sys->header.nb_channels = p_enc->fmt_in.audio.i_channels;
955
956     /* Create a new encoder state in narrowband mode */
957     p_sys->p_state = speex_encoder_init( p_speex_mode );
958
959     /* Parameters */
960     i_tmp = var_GetInteger( p_enc, ENC_CFG_PREFIX "complexity" );
961     speex_encoder_ctl( p_sys->p_state, SPEEX_SET_COMPLEXITY, &i_tmp );
962
963     i_tmp = var_GetBool( p_enc, ENC_CFG_PREFIX "cbr" ) ? 0 : 1;
964     speex_encoder_ctl( p_sys->p_state, SPEEX_SET_VBR, &i_tmp );
965
966     if( i_tmp == 0 ) /* CBR */
967     {
968         i_tmp = var_GetFloat( p_enc, ENC_CFG_PREFIX "quality" );
969         speex_encoder_ctl( p_sys->p_state, SPEEX_SET_QUALITY, &i_tmp );
970
971         i_tmp = var_GetBool( p_enc, ENC_CFG_PREFIX "vad" ) ? 1 : 0;
972         speex_encoder_ctl( p_sys->p_state, SPEEX_SET_VAD, &i_tmp );
973     }
974     else
975     {
976         float f_tmp;
977
978         f_tmp = var_GetFloat( p_enc, ENC_CFG_PREFIX "quality" );
979         speex_encoder_ctl( p_sys->p_state, SPEEX_SET_VBR_QUALITY, &f_tmp );
980
981         i_tmp = var_GetInteger( p_enc, ENC_CFG_PREFIX "max-bitrate" );
982         if( i_tmp > 0 )
983 #ifdef SPEEX_SET_VBR_MAX_BITRATE
984             speex_encoder_ctl( p_sys->p_state, SPEEX_SET_VBR_MAX_BITRATE, &i_tmp );
985 #else
986             msg_Dbg( p_enc, "max-bitrate cannot be set in this version of libspeex");
987 #endif
988     }
989
990     i_tmp = var_GetBool( p_enc, ENC_CFG_PREFIX "dtx" ) ? 1 : 0;
991     speex_encoder_ctl( p_sys->p_state, SPEEX_SET_DTX, &i_tmp );
992
993
994     /*Initialization of the structure that holds the bits*/
995     speex_bits_init( &p_sys->bits );
996
997     p_sys->i_frames_in_packet = 0;
998     p_sys->i_samples_delay = 0;
999     p_sys->i_pts = 0;
1000
1001     speex_encoder_ctl( p_sys->p_state, SPEEX_GET_FRAME_SIZE,
1002                        &p_sys->i_frame_length );
1003
1004     p_sys->i_frame_size = p_sys->i_frame_length *
1005         sizeof(int16_t) * p_enc->fmt_in.audio.i_channels;
1006     p_sys->p_buffer = malloc( p_sys->i_frame_size );
1007
1008     /* Create and store headers */
1009     pp_header[0] = speex_header_to_packet( &p_sys->header, &pi_header[0] );
1010     pp_header[1] = "ENCODER=VLC media player";
1011     pi_header[1] = sizeof("ENCODER=VLC media player");
1012
1013     p_enc->fmt_out.i_extra = 3 * 2 + pi_header[0] + pi_header[1];
1014     p_extra = p_enc->fmt_out.p_extra = malloc( p_enc->fmt_out.i_extra );
1015     for( i = 0; i < 2; i++ )
1016     {
1017         *(p_extra++) = pi_header[i] >> 8;
1018         *(p_extra++) = pi_header[i] & 0xFF;
1019         memcpy( p_extra, pp_header[i], pi_header[i] );
1020         p_extra += pi_header[i];
1021     }
1022
1023     msg_Dbg( p_enc, "encoding: frame size:%d, channels:%d, samplerate:%d",
1024              p_sys->i_frame_size, p_enc->fmt_in.audio.i_channels,
1025              p_enc->fmt_in.audio.i_rate );
1026
1027     return VLC_SUCCESS;
1028 }
1029
1030 /****************************************************************************
1031  * Encode: the whole thing
1032  ****************************************************************************
1033  * This function spits out ogg packets.
1034  ****************************************************************************/
1035 static block_t *Encode( encoder_t *p_enc, aout_buffer_t *p_aout_buf )
1036 {
1037     encoder_sys_t *p_sys = p_enc->p_sys;
1038     block_t *p_block, *p_chain = NULL;
1039
1040     unsigned char *p_buffer = p_aout_buf->p_buffer;
1041     int i_samples = p_aout_buf->i_nb_samples;
1042     int i_samples_delay = p_sys->i_samples_delay;
1043
1044     p_sys->i_pts = p_aout_buf->start_date -
1045                 (mtime_t)1000000 * (mtime_t)p_sys->i_samples_delay /
1046                 (mtime_t)p_enc->fmt_in.audio.i_rate;
1047
1048     p_sys->i_samples_delay += i_samples;
1049
1050     while( p_sys->i_samples_delay >= p_sys->i_frame_length )
1051     {
1052         int16_t *p_samples;
1053         int i_out;
1054
1055         if( i_samples_delay )
1056         {
1057             /* Take care of the left-over from last time */
1058             int i_delay_size = i_samples_delay * 2 *
1059                                  p_enc->fmt_in.audio.i_channels;
1060             int i_size = p_sys->i_frame_size - i_delay_size;
1061
1062             p_samples = (int16_t *)p_sys->p_buffer;
1063             memcpy( p_sys->p_buffer + i_delay_size, p_buffer, i_size );
1064             p_buffer -= i_delay_size;
1065             i_samples += i_samples_delay;
1066             i_samples_delay = 0;
1067         }
1068         else
1069         {
1070             p_samples = (int16_t *)p_buffer;
1071         }
1072
1073         /* Encode current frame */
1074         if( p_enc->fmt_in.audio.i_channels == 2 )
1075             speex_encode_stereo_int( p_samples, p_sys->i_frame_length,
1076                                      &p_sys->bits );
1077
1078 #if 0
1079         if( p_sys->preprocess )
1080             speex_preprocess( p_sys->preprocess, p_samples, NULL );
1081 #endif
1082
1083         speex_encode_int( p_sys->p_state, p_samples, &p_sys->bits );
1084
1085         p_buffer += p_sys->i_frame_size;
1086         p_sys->i_samples_delay -= p_sys->i_frame_length;
1087         i_samples -= p_sys->i_frame_length;
1088
1089         p_sys->i_frames_in_packet++;
1090
1091         if( p_sys->i_frames_in_packet < p_sys->header.frames_per_packet )
1092             continue;
1093
1094         p_sys->i_frames_in_packet = 0;
1095
1096         speex_bits_insert_terminator( &p_sys->bits );
1097         i_out = speex_bits_write( &p_sys->bits, p_sys->p_buffer_out,
1098                                   MAX_FRAME_BYTES );
1099         speex_bits_reset( &p_sys->bits );
1100
1101         p_block = block_New( p_enc, i_out );
1102         memcpy( p_block->p_buffer, p_sys->p_buffer_out, i_out );
1103
1104         p_block->i_length = (mtime_t)1000000 *
1105             (mtime_t)p_sys->i_frame_length * p_sys->header.frames_per_packet /
1106             (mtime_t)p_enc->fmt_in.audio.i_rate;
1107
1108         p_block->i_dts = p_block->i_pts = p_sys->i_pts;
1109
1110         /* Update pts */
1111         p_sys->i_pts += p_block->i_length;
1112         block_ChainAppend( &p_chain, p_block );
1113
1114     }
1115
1116     /* Backup the remaining raw samples */
1117     if( i_samples )
1118     {
1119         memcpy( p_sys->p_buffer + i_samples_delay * 2 *
1120                 p_enc->fmt_in.audio.i_channels, p_buffer,
1121                 i_samples * 2 * p_enc->fmt_in.audio.i_channels );
1122     }
1123
1124     return p_chain;
1125 }
1126
1127 /*****************************************************************************
1128  * CloseEncoder: encoder destruction
1129  *****************************************************************************/
1130 static void CloseEncoder( vlc_object_t *p_this )
1131 {
1132     encoder_t *p_enc = (encoder_t *)p_this;
1133     encoder_sys_t *p_sys = p_enc->p_sys;
1134
1135     speex_encoder_destroy( p_sys->p_state );
1136     speex_bits_destroy( &p_sys->bits );
1137
1138     free( p_sys->p_buffer );
1139     free( p_sys );
1140 }