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