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