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