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