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