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