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