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