]> git.sesse.net Git - vlc/blob - modules/codec/speex.c
Fix NULL dereference due to Speex header corruption
[vlc] / modules / codec / speex.c
1 /*****************************************************************************
2  * speex.c: speex decoder/packetizer/encoder module making use of libspeex.
3  *****************************************************************************
4  * Copyright (C) 2003 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 #include <vlc/vlc.h>
28 #include <vlc_input.h>
29 #include <vlc_codec.h>
30 #include <vlc_aout.h>
31
32 #include <ogg/ogg.h>
33 #include <speex/speex.h>
34 #include <speex/speex_header.h>
35 #include <speex/speex_stereo.h>
36 #include <speex/speex_callbacks.h>
37
38 #include <assert.h>
39
40 /*****************************************************************************
41  * decoder_sys_t : speex decoder descriptor
42  *****************************************************************************/
43 struct decoder_sys_t
44 {
45     /* Module mode */
46     vlc_bool_t b_packetizer;
47
48     /*
49      * Input properties
50      */
51     int i_headers;
52     int i_frame_in_packet;
53
54     /*
55      * Speex properties
56      */
57     SpeexBits bits;
58     SpeexHeader *p_header;
59     SpeexStereoState stereo;
60     void *p_state;
61
62     /*
63      * Common properties
64      */
65     audio_date_t end_date;
66
67 };
68
69 static int pi_channels_maps[6] =
70 {
71     0,
72     AOUT_CHAN_CENTER,   AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT,
73     AOUT_CHAN_CENTER | AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT,
74     AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_REARLEFT
75      | AOUT_CHAN_REARRIGHT,
76     AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_CENTER
77      | AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT
78 };
79
80 /****************************************************************************
81  * Local prototypes
82  ****************************************************************************/
83 static int  OpenDecoder   ( vlc_object_t * );
84 static int  OpenPacketizer( vlc_object_t * );
85 static void CloseDecoder  ( vlc_object_t * );
86
87 static void *DecodeBlock  ( decoder_t *, block_t ** );
88 static int  ProcessHeaders( decoder_t * );
89 static int  ProcessInitialHeader ( decoder_t *, ogg_packet * );
90 static void *ProcessPacket( decoder_t *, ogg_packet *, block_t ** );
91
92 static aout_buffer_t *DecodePacket( decoder_t *, ogg_packet * );
93 static block_t *SendPacket( decoder_t *, ogg_packet *, block_t * );
94
95 static void ParseSpeexComments( decoder_t *, ogg_packet * );
96
97 static int OpenEncoder   ( vlc_object_t * );
98 static void CloseEncoder ( vlc_object_t * );
99 static block_t *Encode   ( encoder_t *, aout_buffer_t * );
100
101 /*****************************************************************************
102  * Module descriptor
103  *****************************************************************************/
104 vlc_module_begin();
105     set_category( CAT_INPUT );
106     set_subcategory( SUBCAT_INPUT_ACODEC );
107
108     set_description( _("Speex audio decoder") );
109     set_capability( "decoder", 100 );
110     set_callbacks( OpenDecoder, CloseDecoder );
111
112     add_submodule();
113     set_description( _("Speex audio packetizer") );
114     set_capability( "packetizer", 100 );
115     set_callbacks( OpenPacketizer, CloseDecoder );
116
117     add_submodule();
118     set_description( _("Speex audio encoder") );
119     set_capability( "encoder", 100 );
120     set_callbacks( OpenEncoder, CloseEncoder );
121 vlc_module_end();
122
123 /*****************************************************************************
124  * OpenDecoder: probe the decoder and return score
125  *****************************************************************************/
126 static int OpenDecoder( vlc_object_t *p_this )
127 {
128     decoder_t *p_dec = (decoder_t*)p_this;
129     decoder_sys_t *p_sys = p_dec->p_sys;
130
131     if( p_dec->fmt_in.i_codec != VLC_FOURCC('s','p','x',' ') )
132     {
133         return VLC_EGENERIC;
134     }
135
136     /* Allocate the memory needed to store the decoder's structure */
137     if( ( p_dec->p_sys = p_sys =
138           (decoder_sys_t *)malloc(sizeof(decoder_sys_t)) ) == NULL )
139     {
140         msg_Err( p_dec, "out of memory" );
141         return VLC_EGENERIC;
142     }
143     p_dec->p_sys->b_packetizer = VLC_FALSE;
144
145     aout_DateSet( &p_sys->end_date, 0 );
146
147     /* Set output properties */
148     p_dec->fmt_out.i_cat = AUDIO_ES;
149     p_dec->fmt_out.i_codec = AOUT_FMT_S16_NE;
150
151     /* Set callbacks */
152     p_dec->pf_decode_audio = (aout_buffer_t *(*)(decoder_t *, block_t **))
153         DecodeBlock;
154     p_dec->pf_packetize    = (block_t *(*)(decoder_t *, block_t **))
155         DecodeBlock;
156
157     p_sys->i_headers = 0;
158     p_sys->p_state = NULL;
159     p_sys->p_header = NULL;
160     p_sys->i_frame_in_packet = 0;
161
162     return VLC_SUCCESS;
163 }
164
165 static int OpenPacketizer( vlc_object_t *p_this )
166 {
167     decoder_t *p_dec = (decoder_t*)p_this;
168
169     int i_ret = OpenDecoder( p_this );
170
171     if( i_ret == VLC_SUCCESS )
172     {
173         p_dec->p_sys->b_packetizer = VLC_TRUE;
174         p_dec->fmt_out.i_codec = VLC_FOURCC('s','p','x',' ');
175     }
176
177     return i_ret;
178 }
179
180 /****************************************************************************
181  * DecodeBlock: the whole thing
182  ****************************************************************************
183  * This function must be fed with ogg packets.
184  ****************************************************************************/
185 static void *DecodeBlock( decoder_t *p_dec, block_t **pp_block )
186 {
187     decoder_sys_t *p_sys = p_dec->p_sys;
188     ogg_packet oggpacket;
189
190     if( !pp_block ) return NULL;
191
192     if( *pp_block )
193     {
194         /* Block to Ogg packet */
195         oggpacket.packet = (*pp_block)->p_buffer;
196         oggpacket.bytes = (*pp_block)->i_buffer;
197     }
198     else
199     {
200         if( p_sys->b_packetizer ) return NULL;
201
202         /* Block to Ogg packet */
203         oggpacket.packet = NULL;
204         oggpacket.bytes = 0;
205     }
206
207     oggpacket.granulepos = -1;
208     oggpacket.b_o_s = 0;
209     oggpacket.e_o_s = 0;
210     oggpacket.packetno = 0;
211
212     /* Check for headers */
213     if( p_sys->i_headers == 0 && p_dec->fmt_in.i_extra )
214     {
215         /* Headers already available as extra data */
216         p_sys->i_headers = 2;
217     }
218     else if( oggpacket.bytes && p_sys->i_headers < 2 )
219     {
220         /* Backup headers as extra data */
221         uint8_t *p_extra;
222
223         p_dec->fmt_in.p_extra =
224             realloc( p_dec->fmt_in.p_extra, p_dec->fmt_in.i_extra +
225                      oggpacket.bytes + 2 );
226         p_extra = ((uint8_t *)p_dec->fmt_in.p_extra) + p_dec->fmt_in.i_extra;
227         *(p_extra++) = oggpacket.bytes >> 8;
228         *(p_extra++) = oggpacket.bytes & 0xFF;
229
230         memcpy( p_extra, oggpacket.packet, oggpacket.bytes );
231         p_dec->fmt_in.i_extra += oggpacket.bytes + 2;
232
233         block_Release( *pp_block );
234         p_sys->i_headers++;
235         return NULL;
236     }
237
238     if( p_sys->i_headers == 2 )
239     {
240         if( ProcessHeaders( p_dec ) != VLC_SUCCESS )
241         {
242             p_sys->i_headers = 0;
243             p_dec->fmt_in.i_extra = 0;
244             block_Release( *pp_block );
245             return NULL;
246         }
247         else p_sys->i_headers++;
248     }
249
250     return ProcessPacket( p_dec, &oggpacket, pp_block );
251 }
252
253 /*****************************************************************************
254  * ProcessHeaders: process Speex headers.
255  *****************************************************************************/
256 static int ProcessHeaders( decoder_t *p_dec )
257 {
258     decoder_sys_t *p_sys = p_dec->p_sys;
259     ogg_packet oggpacket;
260     uint8_t *p_extra;
261     int i_extra;
262
263     if( !p_dec->fmt_in.i_extra ) return VLC_EGENERIC;
264
265     oggpacket.granulepos = -1;
266     oggpacket.b_o_s = 1; /* yes this actually is a b_o_s packet :) */
267     oggpacket.e_o_s = 0;
268     oggpacket.packetno = 0;
269     p_extra = p_dec->fmt_in.p_extra;
270     i_extra = p_dec->fmt_in.i_extra;
271
272     /* Take care of the initial Vorbis header */
273     oggpacket.bytes = *(p_extra++) << 8;
274     oggpacket.bytes |= (*(p_extra++) & 0xFF);
275     oggpacket.packet = p_extra;
276     p_extra += oggpacket.bytes;
277     i_extra -= (oggpacket.bytes + 2);
278     if( i_extra < 0 )
279     {
280         msg_Err( p_dec, "header data corrupted");
281         return VLC_EGENERIC;
282     }
283
284     /* Take care of the initial Speex header */
285     if( ProcessInitialHeader( p_dec, &oggpacket ) != VLC_SUCCESS )
286     {
287         msg_Err( p_dec, "initial Speex header is corrupted" );
288         return VLC_EGENERIC;
289     }
290
291     /* The next packet in order is the comments header */
292     oggpacket.b_o_s = 0;
293     oggpacket.bytes = *(p_extra++) << 8;
294     oggpacket.bytes |= (*(p_extra++) & 0xFF);
295     oggpacket.packet = p_extra;
296     p_extra += oggpacket.bytes;
297     i_extra -= (oggpacket.bytes + 2);
298     if( i_extra < 0 )
299     {
300         msg_Err( p_dec, "header data corrupted");
301         return VLC_EGENERIC;
302     }
303
304     ParseSpeexComments( p_dec, &oggpacket );
305
306     if( p_sys->b_packetizer )
307     {
308         p_dec->fmt_out.i_extra = p_dec->fmt_in.i_extra;
309         p_dec->fmt_out.p_extra =
310             realloc( p_dec->fmt_out.p_extra, p_dec->fmt_out.i_extra );
311         memcpy( p_dec->fmt_out.p_extra,
312                 p_dec->fmt_in.p_extra, p_dec->fmt_out.i_extra );
313     }
314
315     return VLC_SUCCESS;
316 }
317
318 /*****************************************************************************
319  * ProcessInitialHeader: processes the inital Speex header packet.
320  *****************************************************************************/
321 static int ProcessInitialHeader( decoder_t *p_dec, ogg_packet *p_oggpacket )
322 {
323     decoder_sys_t *p_sys = p_dec->p_sys;
324
325     void *p_state;
326     SpeexHeader *p_header;
327     const SpeexMode *p_mode;
328     SpeexCallback callback;
329
330     p_sys->p_header = p_header =
331         speex_packet_to_header( (char *)p_oggpacket->packet,
332                                 p_oggpacket->bytes );
333     if( !p_header )
334     {
335         msg_Err( p_dec, "cannot read Speex header" );
336         return VLC_EGENERIC;
337     }
338     if( p_header->mode >= SPEEX_NB_MODES )
339     {
340         msg_Err( p_dec, "mode number %d does not (yet/any longer) exist in "
341                  "this version of libspeex.", p_header->mode );
342         return VLC_EGENERIC;
343     }
344
345     p_mode = speex_mode_list[p_header->mode];
346     if( p_mode == NULL )
347         return VLC_EGENERIC;
348
349     if( p_header->speex_version_id > 1 )
350     {
351         msg_Err( p_dec, "this file was encoded with Speex bit-stream "
352                  "version %d which is not supported by this decoder.",
353                  p_header->speex_version_id );
354         return VLC_EGENERIC;
355     }
356
357     if( p_mode->bitstream_version < p_header->mode_bitstream_version )
358     {
359         msg_Err( p_dec, "file encoded with a newer version of Speex." );
360         return VLC_EGENERIC;
361     }
362     if( p_mode->bitstream_version > p_header->mode_bitstream_version )
363     {
364         msg_Err( p_dec, "file encoded with an older version of Speex." );
365         return VLC_EGENERIC;
366     }
367
368     msg_Dbg( p_dec, "Speex %d Hz audio using %s mode %s%s",
369              p_header->rate, p_mode->modeName,
370              ( p_header->nb_channels == 1 ) ? " (mono" : " (stereo",
371              p_header->vbr ? ", VBR)" : ")" );
372
373     /* Take care of speex decoder init */
374     speex_bits_init( &p_sys->bits );
375     p_sys->p_state = p_state = speex_decoder_init( p_mode );
376     if( !p_state )
377     {
378         msg_Err( p_dec, "decoder initialization failed" );
379         return VLC_EGENERIC;
380     }
381
382     if( p_header->nb_channels == 2 )
383     {
384         SpeexStereoState stereo = SPEEX_STEREO_STATE_INIT;
385         p_sys->stereo = stereo;
386         callback.callback_id = SPEEX_INBAND_STEREO;
387         callback.func = speex_std_stereo_request_handler;
388         callback.data = &p_sys->stereo;
389         speex_decoder_ctl( p_state, SPEEX_SET_HANDLER, &callback );
390     }
391     if( p_header->nb_channels <= 0 ||
392         p_header->nb_channels > 5 )
393     {
394         msg_Err( p_dec, "invalid number of channels (not between 1 and 5): %i",
395                  p_header->nb_channels );
396         return VLC_EGENERIC;
397     }
398
399     /* Setup the format */
400     p_dec->fmt_out.audio.i_physical_channels =
401         p_dec->fmt_out.audio.i_original_channels =
402             pi_channels_maps[p_header->nb_channels];
403     p_dec->fmt_out.audio.i_channels = p_header->nb_channels;
404     p_dec->fmt_out.audio.i_rate = p_header->rate;
405
406     aout_DateInit( &p_sys->end_date, p_header->rate );
407
408     return VLC_SUCCESS;
409 }
410
411 /*****************************************************************************
412  * ProcessPacket: processes a Speex packet.
413  *****************************************************************************/
414 static void *ProcessPacket( decoder_t *p_dec, ogg_packet *p_oggpacket,
415                             block_t **pp_block )
416 {
417     decoder_sys_t *p_sys = p_dec->p_sys;
418     block_t *p_block = *pp_block;
419
420     /* Date management */
421     if( p_block && p_block->i_pts > 0 &&
422         p_block->i_pts != aout_DateGet( &p_sys->end_date ) )
423     {
424         aout_DateSet( &p_sys->end_date, p_block->i_pts );
425     }
426
427     if( !aout_DateGet( &p_sys->end_date ) )
428     {
429         /* We've just started the stream, wait for the first PTS. */
430         if( p_block ) block_Release( p_block );
431         return NULL;
432     }
433
434     *pp_block = NULL; /* To avoid being fed the same packet again */
435
436     if( p_sys->b_packetizer )
437     {
438          return SendPacket( p_dec, p_oggpacket, p_block );
439     }
440     else
441     {
442         aout_buffer_t *p_aout_buffer;
443
444         if( p_sys->i_headers >= p_sys->p_header->extra_headers + 2 )
445             p_aout_buffer = DecodePacket( p_dec, p_oggpacket );
446         else
447             p_aout_buffer = NULL; /* Skip headers */
448
449         if( p_block ) block_Release( p_block );
450         return p_aout_buffer;
451     }
452 }
453
454 /*****************************************************************************
455  * DecodePacket: decodes a Speex packet.
456  *****************************************************************************/
457 static aout_buffer_t *DecodePacket( decoder_t *p_dec, ogg_packet *p_oggpacket )
458 {
459     decoder_sys_t *p_sys = p_dec->p_sys;
460
461     if( p_oggpacket->bytes )
462     {
463         /* Copy Ogg packet to Speex bitstream */
464         speex_bits_read_from( &p_sys->bits, (char *)p_oggpacket->packet,
465                               p_oggpacket->bytes );
466         p_sys->i_frame_in_packet = 0;
467     }
468
469     /* Decode one frame at a time */
470     if( p_sys->i_frame_in_packet < p_sys->p_header->frames_per_packet )
471     {
472         aout_buffer_t *p_aout_buffer;
473         int i_ret;
474
475         p_aout_buffer =
476             p_dec->pf_aout_buffer_new( p_dec, p_sys->p_header->frame_size );
477         if( !p_aout_buffer )
478         {
479             return NULL;
480         }
481
482         i_ret = speex_decode_int( p_sys->p_state, &p_sys->bits,
483                                   (int16_t *)p_aout_buffer->p_buffer );
484         if( i_ret == -1 )
485         {
486             /* End of stream */
487             return NULL;
488         }
489
490         if( i_ret== -2 )
491         {
492             msg_Warn( p_dec, "decoding error: corrupted stream?" );
493             return NULL;
494         }
495
496         if( speex_bits_remaining( &p_sys->bits ) < 0 )
497         {
498             msg_Warn( p_dec, "decoding overflow: corrupted stream?" );
499         }
500
501         if( p_sys->p_header->nb_channels == 2 )
502             speex_decode_stereo_int( (int16_t *)p_aout_buffer->p_buffer,
503                                      p_sys->p_header->frame_size,
504                                      &p_sys->stereo );
505
506         /* Date management */
507         p_aout_buffer->start_date = aout_DateGet( &p_sys->end_date );
508         p_aout_buffer->end_date =
509             aout_DateIncrement( &p_sys->end_date, p_sys->p_header->frame_size);
510
511         p_sys->i_frame_in_packet++;
512
513         return p_aout_buffer;
514     }
515     else
516     {
517         return NULL;
518     }
519 }
520
521 /*****************************************************************************
522  * SendPacket: send an ogg packet to the stream output.
523  *****************************************************************************/
524 static block_t *SendPacket( decoder_t *p_dec, ogg_packet *p_oggpacket,
525                             block_t *p_block )
526 {
527     decoder_sys_t *p_sys = p_dec->p_sys;
528
529     /* Date management */
530     p_block->i_dts = p_block->i_pts = aout_DateGet( &p_sys->end_date );
531
532     if( p_sys->i_headers >= p_sys->p_header->extra_headers + 2 )
533         p_block->i_length =
534             aout_DateIncrement( &p_sys->end_date,
535                                 p_sys->p_header->frame_size ) -
536             p_block->i_pts;
537     else
538         p_block->i_length = 0;
539
540     return p_block;
541 }
542
543 /*****************************************************************************
544  * ParseSpeexComments: FIXME should be done in demuxer
545  *****************************************************************************/
546 #define readint(buf, base) (((buf[base+3]<<24)&0xff000000)| \
547                            ((buf[base+2]<<16)&0xff0000)| \
548                            ((buf[base+1]<<8)&0xff00)| \
549                             (buf[base]&0xff))
550
551 static void ParseSpeexComments( decoder_t *p_dec, ogg_packet *p_oggpacket )
552 {
553     input_thread_t *p_input = (input_thread_t *)p_dec->p_parent;
554     decoder_sys_t *p_sys = p_dec->p_sys;
555
556     char *p_buf = (char *)p_oggpacket->packet;
557     const SpeexMode *p_mode;
558     int i_len;
559
560     if( p_input->i_object_type != VLC_OBJECT_INPUT ) return;
561
562     assert( p_sys->p_header->mode < SPEEX_NB_MODES );
563
564     p_mode = speex_mode_list[p_sys->p_header->mode];
565     assert( p_mode != NULL );
566
567     input_Control( p_input, INPUT_ADD_INFO, _("Speex comment"), _("Mode"),
568                    "%s%s", p_mode->modeName,
569                    p_sys->p_header->vbr ? " VBR" : "" );
570
571     if( p_oggpacket->bytes < 8 )
572     {
573         msg_Warn( p_dec, "invalid/corrupted comments" );
574         return;
575     }
576
577     i_len = readint( p_buf, 0 ); p_buf += 4;
578     if( i_len > p_oggpacket->bytes - 4 )
579     {
580         msg_Warn( p_dec, "invalid/corrupted comments" );
581         return;
582     }
583
584     input_Control( p_input, INPUT_ADD_INFO, _("Speex comment"), p_buf, "" );
585
586     /* TODO: finish comments parsing */
587 }
588
589 /*****************************************************************************
590  * CloseDecoder: speex decoder destruction
591  *****************************************************************************/
592 static void CloseDecoder( vlc_object_t *p_this )
593 {
594     decoder_t * p_dec = (decoder_t *)p_this;
595     decoder_sys_t *p_sys = p_dec->p_sys;
596
597     if( p_sys->p_state )
598     {
599         speex_decoder_destroy( p_sys->p_state );
600         speex_bits_destroy( &p_sys->bits );
601     }
602
603     if( p_sys->p_header ) free( p_sys->p_header );
604     free( p_sys );
605 }
606
607 /*****************************************************************************
608  * encoder_sys_t: encoder descriptor
609  *****************************************************************************/
610 #define MAX_FRAME_SIZE  2000
611 #define MAX_FRAME_BYTES 2000
612
613 struct encoder_sys_t
614 {
615     /*
616      * Input properties
617      */
618     char *p_buffer;
619     char p_buffer_out[MAX_FRAME_BYTES];
620
621     /*
622      * Speex properties
623      */
624     SpeexBits bits;
625     SpeexHeader header;
626     SpeexStereoState stereo;
627     void *p_state;
628
629     int i_frames_per_packet;
630     int i_frames_in_packet;
631
632     int i_frame_length;
633     int i_samples_delay;
634     int i_frame_size;
635
636     /*
637      * Common properties
638      */
639     mtime_t i_pts;
640 };
641
642 /*****************************************************************************
643  * OpenEncoder: probe the encoder and return score
644  *****************************************************************************/
645 static int OpenEncoder( vlc_object_t *p_this )
646 {
647     encoder_t *p_enc = (encoder_t *)p_this;
648     encoder_sys_t *p_sys;
649     const SpeexMode *p_speex_mode = &speex_nb_mode;
650     int i_quality, i;
651     const char *pp_header[2];
652     int pi_header[2];
653     uint8_t *p_extra;
654
655     if( p_enc->fmt_out.i_codec != VLC_FOURCC('s','p','x',' ') &&
656         !p_enc->b_force )
657     {
658         return VLC_EGENERIC;
659     }
660
661     /* Allocate the memory needed to store the decoder's structure */
662     if( ( p_sys = (encoder_sys_t *)malloc(sizeof(encoder_sys_t)) ) == NULL )
663     {
664         msg_Err( p_enc, "out of memory" );
665         return VLC_EGENERIC;
666     }
667     p_enc->p_sys = p_sys;
668     p_enc->pf_encode_audio = Encode;
669     p_enc->fmt_in.i_codec = AOUT_FMT_S16_NE;
670     p_enc->fmt_out.i_codec = VLC_FOURCC('s','p','x',' ');
671
672     speex_init_header( &p_sys->header, p_enc->fmt_in.audio.i_rate,
673                        1, p_speex_mode );
674
675     p_sys->header.frames_per_packet = 1;
676     p_sys->header.vbr = 1;
677     p_sys->header.nb_channels = p_enc->fmt_in.audio.i_channels;
678
679     /* Create a new encoder state in narrowband mode */
680     p_sys->p_state = speex_encoder_init( p_speex_mode );
681
682     /* Set the quality to 8 (15 kbps) */
683     i_quality = 8;
684     speex_encoder_ctl( p_sys->p_state, SPEEX_SET_QUALITY, &i_quality );
685
686     /*Initialization of the structure that holds the bits*/
687     speex_bits_init( &p_sys->bits );
688
689     p_sys->i_frames_in_packet = 0;
690     p_sys->i_samples_delay = 0;
691     p_sys->i_pts = 0;
692
693     speex_encoder_ctl( p_sys->p_state, SPEEX_GET_FRAME_SIZE,
694                        &p_sys->i_frame_length );
695
696     p_sys->i_frame_size = p_sys->i_frame_length *
697         sizeof(int16_t) * p_enc->fmt_in.audio.i_channels;
698     p_sys->p_buffer = malloc( p_sys->i_frame_size );
699
700     /* Create and store headers */
701     pp_header[0] = speex_header_to_packet( &p_sys->header, &pi_header[0] );
702     pp_header[1] = "ENCODER=VLC media player";
703     pi_header[1] = sizeof("ENCODER=VLC media player");
704
705     p_enc->fmt_out.i_extra = 3 * 2 + pi_header[0] + pi_header[1];
706     p_extra = p_enc->fmt_out.p_extra = malloc( p_enc->fmt_out.i_extra );
707     for( i = 0; i < 2; i++ )
708     {
709         *(p_extra++) = pi_header[i] >> 8;
710         *(p_extra++) = pi_header[i] & 0xFF;
711         memcpy( p_extra, pp_header[i], pi_header[i] );
712         p_extra += pi_header[i];
713     }
714
715     msg_Dbg( p_enc, "encoding: frame size:%d, channels:%d, samplerate:%d",
716              p_sys->i_frame_size, p_enc->fmt_in.audio.i_channels,
717              p_enc->fmt_in.audio.i_rate );
718
719     return VLC_SUCCESS;
720 }
721
722 /****************************************************************************
723  * Encode: the whole thing
724  ****************************************************************************
725  * This function spits out ogg packets.
726  ****************************************************************************/
727 static block_t *Encode( encoder_t *p_enc, aout_buffer_t *p_aout_buf )
728 {
729     encoder_sys_t *p_sys = p_enc->p_sys;
730     block_t *p_block, *p_chain = NULL;
731
732     unsigned char *p_buffer = p_aout_buf->p_buffer;
733     int i_samples = p_aout_buf->i_nb_samples;
734     int i_samples_delay = p_sys->i_samples_delay;
735
736     p_sys->i_pts = p_aout_buf->start_date -
737                 (mtime_t)1000000 * (mtime_t)p_sys->i_samples_delay /
738                 (mtime_t)p_enc->fmt_in.audio.i_rate;
739
740     p_sys->i_samples_delay += i_samples;
741
742     while( p_sys->i_samples_delay >= p_sys->i_frame_length )
743     {
744         int16_t *p_samples;
745         int i_out;
746
747         if( i_samples_delay )
748         {
749             /* Take care of the left-over from last time */
750             int i_delay_size = i_samples_delay * 2 *
751                                  p_enc->fmt_in.audio.i_channels;
752             int i_size = p_sys->i_frame_size - i_delay_size;
753
754             p_samples = (int16_t *)p_sys->p_buffer;
755             memcpy( p_sys->p_buffer + i_delay_size, p_buffer, i_size );
756             p_buffer -= i_delay_size;
757             i_samples += i_samples_delay;
758             i_samples_delay = 0;
759         }
760         else
761         {
762             p_samples = (int16_t *)p_buffer;
763         }
764
765         /* Encode current frame */
766         if( p_enc->fmt_in.audio.i_channels == 2 )
767             speex_encode_stereo_int( p_samples, p_sys->i_frame_length,
768                                      &p_sys->bits );
769
770 #if 0
771         if( p_sys->preprocess )
772             speex_preprocess( p_sys->preprocess, p_samples, NULL );
773 #endif
774
775         speex_encode_int( p_sys->p_state, p_samples, &p_sys->bits );
776
777         p_buffer += p_sys->i_frame_size;
778         p_sys->i_samples_delay -= p_sys->i_frame_length;
779         i_samples -= p_sys->i_frame_length;
780
781         p_sys->i_frames_in_packet++;
782
783         if( p_sys->i_frames_in_packet < p_sys->header.frames_per_packet )
784             continue;
785
786         p_sys->i_frames_in_packet = 0;
787
788         speex_bits_insert_terminator( &p_sys->bits );
789         i_out = speex_bits_write( &p_sys->bits, p_sys->p_buffer_out,
790                                   MAX_FRAME_BYTES );
791         speex_bits_reset( &p_sys->bits );
792
793         p_block = block_New( p_enc, i_out );
794         memcpy( p_block->p_buffer, p_sys->p_buffer_out, i_out );
795
796         p_block->i_length = (mtime_t)1000000 *
797             (mtime_t)p_sys->i_frame_length * p_sys->header.frames_per_packet /
798             (mtime_t)p_enc->fmt_in.audio.i_rate;
799
800         p_block->i_dts = p_block->i_pts = p_sys->i_pts;
801
802         /* Update pts */
803         p_sys->i_pts += p_block->i_length;
804         block_ChainAppend( &p_chain, p_block );
805
806     }
807
808     /* Backup the remaining raw samples */
809     if( i_samples )
810     {
811         memcpy( p_sys->p_buffer + i_samples_delay * 2 *
812                 p_enc->fmt_in.audio.i_channels, p_buffer,
813                 i_samples * 2 * p_enc->fmt_in.audio.i_channels );
814     }
815
816     return p_chain;
817 }
818
819 /*****************************************************************************
820  * CloseEncoder: encoder destruction
821  *****************************************************************************/
822 static void CloseEncoder( vlc_object_t *p_this )
823 {
824     encoder_t *p_enc = (encoder_t *)p_this;
825     encoder_sys_t *p_sys = p_enc->p_sys;
826
827     speex_encoder_destroy( p_sys->p_state );
828     speex_bits_destroy( &p_sys->bits );
829
830     if( p_sys->p_buffer ) free( p_sys->p_buffer );
831     free( p_sys );
832 }