]> git.sesse.net Git - vlc/blob - modules/codec/speex.c
Support for decoding Speex from RTP - refs #1291
[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     unsigned int rtp_rate;
62
63     /*
64      * Common properties
65      */
66     audio_date_t end_date;
67
68 };
69
70 static int pi_channels_maps[6] =
71 {
72     0,
73     AOUT_CHAN_CENTER,   AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT,
74     AOUT_CHAN_CENTER | AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT,
75     AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_REARLEFT
76      | AOUT_CHAN_REARRIGHT,
77     AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_CENTER
78      | AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT
79 };
80
81 /****************************************************************************
82  * Local prototypes
83  ****************************************************************************/
84 static int  OpenDecoder   ( vlc_object_t * );
85 static int  OpenPacketizer( vlc_object_t * );
86 static void CloseDecoder  ( vlc_object_t * );
87
88 static void *DecodeBlock  ( decoder_t *, block_t ** );
89 static aout_buffer_t *DecodeRtpSpeexPacket( decoder_t *, block_t **);
90 static int  ProcessHeaders( decoder_t * );
91 static int  ProcessInitialHeader ( decoder_t *, ogg_packet * );
92 static void *ProcessPacket( decoder_t *, ogg_packet *, block_t ** );
93
94 static aout_buffer_t *DecodePacket( decoder_t *, ogg_packet * );
95 static block_t *SendPacket( decoder_t *, ogg_packet *, block_t * );
96
97 static void ParseSpeexComments( decoder_t *, ogg_packet * );
98
99 static int OpenEncoder   ( vlc_object_t * );
100 static void CloseEncoder ( vlc_object_t * );
101 static block_t *Encode   ( encoder_t *, aout_buffer_t * );
102
103 /*****************************************************************************
104  * Module descriptor
105  *****************************************************************************/
106 vlc_module_begin();
107     set_category( CAT_INPUT );
108     set_subcategory( SUBCAT_INPUT_ACODEC );
109
110     set_description( _("Speex audio decoder") );
111     set_capability( "decoder", 100 );
112     set_callbacks( OpenDecoder, CloseDecoder );
113
114     add_submodule();
115     set_description( _("Speex audio packetizer") );
116     set_capability( "packetizer", 100 );
117     set_callbacks( OpenPacketizer, CloseDecoder );
118
119     add_submodule();
120     set_description( _("Speex audio encoder") );
121     set_capability( "encoder", 100 );
122     set_callbacks( OpenEncoder, CloseEncoder );
123 vlc_module_end();
124
125 /*****************************************************************************
126  * OpenDecoder: probe the decoder and return score
127  *****************************************************************************/
128 static int OpenDecoder( vlc_object_t *p_this )
129 {
130     decoder_t *p_dec = (decoder_t*)p_this;
131     decoder_sys_t *p_sys = p_dec->p_sys;
132
133     if( p_dec->fmt_in.i_codec != VLC_FOURCC('s','p','x',' ') 
134         && p_dec->fmt_in.i_codec != VLC_FOURCC('s', 'p', 'x', 'r') )
135     {
136         return VLC_EGENERIC;
137     }
138
139     /* Allocate the memory needed to store the decoder's structure */
140     if( ( p_dec->p_sys = p_sys =
141           (decoder_sys_t *)malloc(sizeof(decoder_sys_t)) ) == NULL )
142     {
143         msg_Err( p_dec, "out of memory" );
144         return VLC_EGENERIC;
145     }
146     p_dec->p_sys->bits.buf_size = 0;
147     p_dec->p_sys->b_packetizer = VLC_FALSE;
148     p_dec->p_sys->rtp_rate = p_dec->fmt_in.audio.i_rate;
149
150     aout_DateSet( &p_sys->end_date, 0 );
151
152     /* Set output properties */
153     p_dec->fmt_out.i_cat = AUDIO_ES;
154     p_dec->fmt_out.i_codec = AOUT_FMT_S16_NE;
155
156     /*
157       Set callbacks
158       If the codec is spxr then this decoder is 
159       being invoked on a Speex stream arriving via RTP. 
160       A special decoder callback is used.
161     */
162     if (p_dec->fmt_in.i_codec == VLC_FOURCC('s', 'p', 'x', 'r'))
163     {
164         msg_Dbg( p_dec, "Using RTP version of Speex decoder @ rate %d.", 
165             p_dec->fmt_in.audio.i_rate );
166         p_dec->pf_decode_audio = (aout_buffer_t *(*)(decoder_t *, block_t **))
167             DecodeRtpSpeexPacket;
168     }
169     else
170     {
171         p_dec->pf_decode_audio = (aout_buffer_t *(*)(decoder_t *, block_t **))
172             DecodeBlock;
173     }
174     p_dec->pf_packetize    = (block_t *(*)(decoder_t *, block_t **))
175         DecodeBlock;
176
177     p_sys->i_headers = 0;
178     p_sys->p_state = NULL;
179     p_sys->p_header = NULL;
180     p_sys->i_frame_in_packet = 0;
181
182     return VLC_SUCCESS;
183 }
184
185 static int OpenPacketizer( vlc_object_t *p_this )
186 {
187     decoder_t *p_dec = (decoder_t*)p_this;
188
189     int i_ret = OpenDecoder( p_this );
190
191     if( i_ret == VLC_SUCCESS )
192     {
193         p_dec->p_sys->b_packetizer = VLC_TRUE;
194         p_dec->fmt_out.i_codec = VLC_FOURCC('s','p','x',' ');
195     }
196
197     return i_ret;
198 }
199
200 /****************************************************************************
201  * DecodeBlock: the whole thing
202  ****************************************************************************
203  * This function must be fed with ogg packets.
204  ****************************************************************************/
205 static void *DecodeBlock( decoder_t *p_dec, block_t **pp_block )
206 {
207     decoder_sys_t *p_sys = p_dec->p_sys;
208     ogg_packet oggpacket;
209
210     if( !pp_block ) return NULL;
211
212     if( *pp_block )
213     {
214         /* Block to Ogg packet */
215         oggpacket.packet = (*pp_block)->p_buffer;
216         oggpacket.bytes = (*pp_block)->i_buffer;
217     }
218     else
219     {
220         if( p_sys->b_packetizer ) return NULL;
221
222         /* Block to Ogg packet */
223         oggpacket.packet = NULL;
224         oggpacket.bytes = 0;
225     }
226
227     oggpacket.granulepos = -1;
228     oggpacket.b_o_s = 0;
229     oggpacket.e_o_s = 0;
230     oggpacket.packetno = 0;
231
232     /* Check for headers */
233     if( p_sys->i_headers == 0 && p_dec->fmt_in.i_extra )
234     {
235         p_sys->i_headers = 2;
236     }
237     else if( oggpacket.bytes && p_sys->i_headers < 2 )
238     {
239         uint8_t *p_extra;
240
241         p_dec->fmt_in.p_extra =
242             realloc( p_dec->fmt_in.p_extra, p_dec->fmt_in.i_extra +
243                      oggpacket.bytes + 2 );
244         p_extra = ((uint8_t *)p_dec->fmt_in.p_extra) + p_dec->fmt_in.i_extra;
245         *(p_extra++) = oggpacket.bytes >> 8;
246         *(p_extra++) = oggpacket.bytes & 0xFF;
247
248         memcpy( p_extra, oggpacket.packet, oggpacket.bytes );
249         p_dec->fmt_in.i_extra += oggpacket.bytes + 2;
250
251         block_Release( *pp_block );
252         p_sys->i_headers++;
253         return NULL;
254     }
255
256     if( p_sys->i_headers == 2 )
257     {
258         if( ProcessHeaders( p_dec ) != VLC_SUCCESS )
259         {
260             p_sys->i_headers = 0;
261             p_dec->fmt_in.i_extra = 0;
262             block_Release( *pp_block );
263             return NULL;
264         }
265         else p_sys->i_headers++;
266     }
267
268     return ProcessPacket( p_dec, &oggpacket, pp_block );
269 }
270
271 /*****************************************************************************
272  * ProcessHeaders: process Speex headers.
273  *****************************************************************************/
274 static int ProcessHeaders( decoder_t *p_dec )
275 {
276     decoder_sys_t *p_sys = p_dec->p_sys;
277     ogg_packet oggpacket;
278     uint8_t *p_extra;
279     int i_extra;
280
281     if( !p_dec->fmt_in.i_extra ) return VLC_EGENERIC;
282
283     oggpacket.granulepos = -1;
284     oggpacket.b_o_s = 1; /* yes this actually is a b_o_s packet :) */
285     oggpacket.e_o_s = 0;
286     oggpacket.packetno = 0;
287     p_extra = p_dec->fmt_in.p_extra;
288     i_extra = p_dec->fmt_in.i_extra;
289
290     /* Take care of the initial Vorbis header */
291     oggpacket.bytes = *(p_extra++) << 8;
292     oggpacket.bytes |= (*(p_extra++) & 0xFF);
293     oggpacket.packet = p_extra;
294     p_extra += oggpacket.bytes;
295     i_extra -= (oggpacket.bytes + 2);
296     if( i_extra < 0 )
297     {
298         msg_Err( p_dec, "header data corrupted");
299         return VLC_EGENERIC;
300     }
301
302     /* Take care of the initial Speex header */
303     if( ProcessInitialHeader( p_dec, &oggpacket ) != VLC_SUCCESS )
304     {
305         msg_Err( p_dec, "initial Speex header is corrupted" );
306         return VLC_EGENERIC;
307     }
308
309     /* The next packet in order is the comments header */
310     oggpacket.b_o_s = 0;
311     oggpacket.bytes = *(p_extra++) << 8;
312     oggpacket.bytes |= (*(p_extra++) & 0xFF);
313     oggpacket.packet = p_extra;
314     p_extra += oggpacket.bytes;
315     i_extra -= (oggpacket.bytes + 2);
316     if( i_extra < 0 )
317     {
318         msg_Err( p_dec, "header data corrupted");
319         return VLC_EGENERIC;
320     }
321
322     ParseSpeexComments( p_dec, &oggpacket );
323
324     if( p_sys->b_packetizer )
325     {
326         p_dec->fmt_out.i_extra = p_dec->fmt_in.i_extra;
327         p_dec->fmt_out.p_extra =
328             realloc( p_dec->fmt_out.p_extra, p_dec->fmt_out.i_extra );
329         memcpy( p_dec->fmt_out.p_extra,
330                 p_dec->fmt_in.p_extra, p_dec->fmt_out.i_extra );
331     }
332
333     return VLC_SUCCESS;
334 }
335
336 /*****************************************************************************
337  * ProcessInitialHeader: processes the inital Speex header packet.
338  *****************************************************************************/
339 static int ProcessInitialHeader( decoder_t *p_dec, ogg_packet *p_oggpacket )
340 {
341     decoder_sys_t *p_sys = p_dec->p_sys;
342
343     void *p_state;
344     SpeexHeader *p_header;
345     const SpeexMode *p_mode;
346     SpeexCallback callback;
347
348     p_sys->p_header = p_header =
349         speex_packet_to_header( (char *)p_oggpacket->packet,
350                                 p_oggpacket->bytes );
351     if( !p_header )
352     {
353         msg_Err( p_dec, "cannot read Speex header" );
354         return VLC_EGENERIC;
355     }
356     if( p_header->mode >= SPEEX_NB_MODES )
357     {
358         msg_Err( p_dec, "mode number %d does not (yet/any longer) exist in "
359                  "this version of libspeex.", p_header->mode );
360         return VLC_EGENERIC;
361     }
362
363     p_mode = speex_mode_list[p_header->mode];
364     if( p_mode == NULL )
365         return VLC_EGENERIC;
366
367     if( p_header->speex_version_id > 1 )
368     {
369         msg_Err( p_dec, "this file was encoded with Speex bit-stream "
370                  "version %d which is not supported by this decoder.",
371                  p_header->speex_version_id );
372         return VLC_EGENERIC;
373     }
374
375     if( p_mode->bitstream_version < p_header->mode_bitstream_version )
376     {
377         msg_Err( p_dec, "file encoded with a newer version of Speex." );
378         return VLC_EGENERIC;
379     }
380     if( p_mode->bitstream_version > p_header->mode_bitstream_version )
381     {
382         msg_Err( p_dec, "file encoded with an older version of Speex." );
383         return VLC_EGENERIC;
384     }
385
386     msg_Dbg( p_dec, "Speex %d Hz audio using %s mode %s%s",
387              p_header->rate, p_mode->modeName,
388              ( p_header->nb_channels == 1 ) ? " (mono" : " (stereo",
389              p_header->vbr ? ", VBR)" : ")" );
390
391     /* Take care of speex decoder init */
392     speex_bits_init( &p_sys->bits );
393     p_sys->p_state = p_state = speex_decoder_init( p_mode );
394     if( !p_state )
395     {
396         msg_Err( p_dec, "decoder initialization failed" );
397         return VLC_EGENERIC;
398     }
399
400     if( p_header->nb_channels == 2 )
401     {
402         SpeexStereoState stereo = SPEEX_STEREO_STATE_INIT;
403         p_sys->stereo = stereo;
404         callback.callback_id = SPEEX_INBAND_STEREO;
405         callback.func = speex_std_stereo_request_handler;
406         callback.data = &p_sys->stereo;
407         speex_decoder_ctl( p_state, SPEEX_SET_HANDLER, &callback );
408     }
409     if( p_header->nb_channels <= 0 ||
410         p_header->nb_channels > 5 )
411     {
412         msg_Err( p_dec, "invalid number of channels (not between 1 and 5): %i",
413                  p_header->nb_channels );
414         return VLC_EGENERIC;
415     }
416
417     /* Setup the format */
418     p_dec->fmt_out.audio.i_physical_channels =
419         p_dec->fmt_out.audio.i_original_channels =
420             pi_channels_maps[p_header->nb_channels];
421     p_dec->fmt_out.audio.i_channels = p_header->nb_channels;
422     p_dec->fmt_out.audio.i_rate = p_header->rate;
423
424     aout_DateInit( &p_sys->end_date, p_header->rate );
425
426     return VLC_SUCCESS;
427 }
428
429 /*****************************************************************************
430  * ProcessPacket: processes a Speex packet.
431  *****************************************************************************/
432 static void *ProcessPacket( decoder_t *p_dec, ogg_packet *p_oggpacket,
433                             block_t **pp_block )
434 {
435     decoder_sys_t *p_sys = p_dec->p_sys;
436     block_t *p_block = *pp_block;
437
438     /* Date management */
439     if( p_block && p_block->i_pts > 0 && 
440         p_block->i_pts != aout_DateGet( &p_sys->end_date ) )
441     {
442         aout_DateSet( &p_sys->end_date, p_block->i_pts );
443     }
444
445     if( !aout_DateGet( &p_sys->end_date ) )
446     {
447         /* We've just started the stream, wait for the first PTS. */
448         if( p_block ) block_Release( p_block );
449         return NULL;
450     }
451
452     *pp_block = NULL; /* To avoid being fed the same packet again */
453
454     if( p_sys->b_packetizer )
455     {
456         if ( p_sys->p_header->frames_per_packet > 1 )
457         {
458             short *p_frame_holder = NULL;
459             int i_bits_before = 0, i_bits_after = 0, i_bytes_in_speex_frame = 0,
460                 i_pcm_output_size = 0, i_bits_in_speex_frame = 0;
461             block_t *p_new_block = NULL;
462
463             i_pcm_output_size = p_sys->p_header->frame_size;
464             p_frame_holder = (short*)malloc( sizeof(short)*i_pcm_output_size );
465
466             speex_bits_read_from( &p_sys->bits, (char*)p_oggpacket->packet,
467                 p_oggpacket->bytes);
468             i_bits_before = speex_bits_remaining( &p_sys->bits );
469             speex_decode_int(p_sys->p_state, &p_sys->bits, p_frame_holder);
470             i_bits_after = speex_bits_remaining( &p_sys->bits );
471
472             i_bits_in_speex_frame = i_bits_before - i_bits_after;
473             i_bytes_in_speex_frame = ( i_bits_in_speex_frame + 
474                 (8 - (i_bits_in_speex_frame % 8)) )
475                 / 8;
476
477             p_new_block = block_New( p_dec, i_bytes_in_speex_frame );
478             memset( p_new_block->p_buffer, 0xff, i_bytes_in_speex_frame );
479
480             /*
481              * Copy the first frame in this packet to a new packet.
482              */
483             speex_bits_rewind( &p_sys->bits );
484             speex_bits_write( &p_sys->bits, 
485                 p_new_block->p_buffer, 
486                 i_bytes_in_speex_frame );
487
488             /*
489              * Move the remaining part of the original packet (subsequent
490              * frames, if there are any) into the beginning 
491              * of the original packet so
492              * they are preserved following the realloc. 
493              * Note: Any bits that
494              * remain in the initial packet
495              * are "filler" if they do not constitute
496              * an entire byte. 
497              */
498             if ( i_bits_after > 7 )
499             {
500                 /* round-down since we rounded-up earlier (to include
501                  * the speex terminator code. 
502                  */
503                 i_bytes_in_speex_frame--;
504                 speex_bits_write( &p_sys->bits, 
505                     p_block->p_buffer, 
506                     p_block->i_buffer - i_bytes_in_speex_frame );
507                 p_block = block_Realloc( p_block, 
508                     0, 
509                     p_block->i_buffer-i_bytes_in_speex_frame );
510                 *pp_block = p_block;
511             }
512             else
513             {
514                 speex_bits_reset( &p_sys->bits );
515             }
516
517             free( p_frame_holder );
518             return SendPacket( p_dec, p_oggpacket /*Not used*/, p_new_block);
519         }
520         else
521         {
522             return SendPacket( p_dec, p_oggpacket, p_block );
523         }
524     }
525     else
526     {
527         aout_buffer_t *p_aout_buffer;
528
529         if( p_sys->i_headers >= p_sys->p_header->extra_headers + 2 )
530             p_aout_buffer = DecodePacket( p_dec, p_oggpacket );
531         else
532             p_aout_buffer = NULL; /* Skip headers */
533
534         if( p_block ) block_Release( p_block );
535         return p_aout_buffer;
536     }
537 }
538
539 static aout_buffer_t *DecodeRtpSpeexPacket( decoder_t *p_dec, block_t **pp_block )
540 {
541     block_t *p_speex_bit_block = *pp_block;
542     decoder_sys_t *p_sys = p_dec->p_sys;
543     aout_buffer_t *p_aout_buffer;
544     int i_decode_ret;
545     unsigned int i_speex_frame_size;
546
547     if ( !p_speex_bit_block || p_speex_bit_block->i_pts == 0 ) return NULL;
548
549     /* 
550       If the SpeexBits buffer size is 0 (a default value),
551       we know that a proper initialization has not yet been done.
552     */
553     if ( p_sys->bits.buf_size==0 )
554     {
555         p_sys->p_header = (SpeexHeader *)malloc(sizeof(SpeexHeader));
556         if ( !p_sys->p_header )
557         {
558             msg_Err( p_dec, "Could not allocate a Speex header.");
559             return NULL;
560         }
561         speex_init_header( p_sys->p_header,p_sys->rtp_rate,1,&speex_nb_mode );
562         speex_bits_init( &p_sys->bits );
563         p_sys->p_state = speex_decoder_init( &speex_nb_mode );
564         if ( !p_sys->p_state )
565         {
566             msg_Err( p_dec, "Could not allocate a Speex decoder." );
567             free( p_sys->p_header );
568             return NULL;
569         }
570
571         /*
572           Assume that variable bit rate is enabled. Also assume
573           that there is only one frame per packet. 
574         */
575         p_sys->p_header->vbr = 1;
576         p_sys->p_header->frames_per_packet = 1;
577
578         p_dec->fmt_out.audio.i_channels = p_sys->p_header->nb_channels;
579         p_dec->fmt_out.audio.i_physical_channels = 
580         p_dec->fmt_out.audio.i_original_channels = 
581             pi_channels_maps[p_sys->p_header->nb_channels];
582         p_dec->fmt_out.audio.i_rate = p_sys->p_header->rate;
583
584         if ( speex_mode_query( &speex_nb_mode, 
585             SPEEX_MODE_FRAME_SIZE, 
586             &i_speex_frame_size ) )
587         {
588             msg_Err( p_dec, "Could not determine the frame size." );
589             speex_decoder_destroy( p_sys->p_state );
590             free( p_sys->p_header );
591             return NULL;
592         }
593         p_dec->fmt_out.audio.i_bytes_per_frame = i_speex_frame_size;
594
595         aout_DateInit(&p_sys->end_date, p_sys->p_header->rate);
596     }
597
598     /* 
599       If the SpeexBits are initialized but there is 
600       still no header, an error must be thrown.
601     */
602     if ( !p_sys->p_header )
603     {
604         msg_Err( p_dec, "There is no valid Speex header found." );
605         return NULL;
606     }
607     *pp_block = NULL;
608
609     if ( !aout_DateGet( &p_sys->end_date ) )
610         aout_DateSet( &p_sys->end_date, p_speex_bit_block->i_dts );
611
612     /*
613       Ask for a new audio output buffer and make sure
614       we get one. 
615     */
616     p_aout_buffer = p_dec->pf_aout_buffer_new( p_dec, 
617         p_sys->p_header->frame_size );
618     if ( !p_aout_buffer || p_aout_buffer->i_nb_bytes == 0 )
619     {
620         msg_Err(p_dec, "Oops: No new buffer was returned!");
621         return NULL;
622     }
623
624     /*
625       Read the Speex payload into the SpeexBits buffer.
626     */
627     speex_bits_read_from( &p_sys->bits, 
628         (char*)p_speex_bit_block->p_buffer, 
629         p_speex_bit_block->i_buffer );
630     
631     /* 
632       Decode the input and ensure that no errors 
633       were encountered.
634     */
635     i_decode_ret = 
636         speex_decode_int( p_sys->p_state,&p_sys->bits,p_aout_buffer->p_buffer );
637     if ( i_decode_ret < 0 )
638     {
639         msg_Err( p_dec, "Decoding failed. Perhaps we have a bad stream?" );
640         return NULL;
641     }
642
643     /* 
644       Handle date management on the audio output buffer. 
645     */
646     p_aout_buffer->start_date = aout_DateGet( &p_sys->end_date );
647     p_aout_buffer->end_date = aout_DateIncrement( &p_sys->end_date, 
648         p_sys->p_header->frame_size );
649     
650     
651     p_sys->i_frame_in_packet++;
652     block_Release( p_speex_bit_block );
653
654     return p_aout_buffer;
655 }
656
657 /*****************************************************************************
658  * DecodePacket: decodes a Speex packet.
659  *****************************************************************************/
660 static aout_buffer_t *DecodePacket( decoder_t *p_dec, ogg_packet *p_oggpacket )
661 {
662     decoder_sys_t *p_sys = p_dec->p_sys;
663
664     if( p_oggpacket->bytes )
665     {
666         /* Copy Ogg packet to Speex bitstream */
667         speex_bits_read_from( &p_sys->bits, (char *)p_oggpacket->packet,
668                               p_oggpacket->bytes );
669         p_sys->i_frame_in_packet = 0;
670     }
671
672     /* Decode one frame at a time */
673     if( p_sys->i_frame_in_packet < p_sys->p_header->frames_per_packet )
674     {
675         aout_buffer_t *p_aout_buffer;
676         if( p_sys->p_header->frame_size == 0 )
677             return NULL;
678
679         p_aout_buffer =
680             p_dec->pf_aout_buffer_new( p_dec, p_sys->p_header->frame_size );
681         if( !p_aout_buffer )
682         {
683             return NULL;
684         }
685
686         switch( speex_decode_int( p_sys->p_state, &p_sys->bits,
687                                   (int16_t *)p_aout_buffer->p_buffer ) )
688         {
689             case -2:
690                 msg_Err( p_dec, "decoding error: corrupted stream?" );
691             case -1: /* End of stream */
692                 return NULL;
693         }
694
695         if( speex_bits_remaining( &p_sys->bits ) < 0 )
696         {
697             msg_Err( p_dec, "decoding overflow: corrupted stream?" );
698         }
699
700         if( p_sys->p_header->nb_channels == 2 )
701             speex_decode_stereo_int( (int16_t *)p_aout_buffer->p_buffer,
702                                      p_sys->p_header->frame_size,
703                                      &p_sys->stereo );
704
705         /* Date management */
706         p_aout_buffer->start_date = aout_DateGet( &p_sys->end_date );
707         p_aout_buffer->end_date =
708             aout_DateIncrement( &p_sys->end_date, p_sys->p_header->frame_size );
709
710         p_sys->i_frame_in_packet++;
711
712         return p_aout_buffer;
713     }
714     else
715     {
716         return NULL;
717     }
718 }
719
720 /*****************************************************************************
721  * SendPacket: send an ogg packet to the stream output.
722  *****************************************************************************/
723 static block_t *SendPacket( decoder_t *p_dec, ogg_packet *p_oggpacket,
724                             block_t *p_block )
725 {
726     decoder_sys_t *p_sys = p_dec->p_sys;
727
728     /* Date management */
729     p_block->i_dts = p_block->i_pts = aout_DateGet( &p_sys->end_date );
730
731     if( p_sys->i_headers >= p_sys->p_header->extra_headers + 2 )
732     {
733         p_block->i_length =
734             aout_DateIncrement( &p_sys->end_date,
735                                 p_sys->p_header->frame_size ) -
736             p_block->i_pts;
737     }
738     else
739         p_block->i_length = 0;
740
741     return p_block;
742 }
743
744 /*****************************************************************************
745  * ParseSpeexComments: FIXME should be done in demuxer
746  *****************************************************************************/
747 #define readint(buf, base) (((buf[base+3]<<24)&0xff000000)| \
748                            ((buf[base+2]<<16)&0xff0000)| \
749                            ((buf[base+1]<<8)&0xff00)| \
750                             (buf[base]&0xff))
751
752 static void ParseSpeexComments( decoder_t *p_dec, ogg_packet *p_oggpacket )
753 {
754     input_thread_t *p_input = (input_thread_t *)p_dec->p_parent;
755     decoder_sys_t *p_sys = p_dec->p_sys;
756
757     char *p_buf = (char *)p_oggpacket->packet;
758     const SpeexMode *p_mode;
759     int i_len;
760
761     if( p_input->i_object_type != VLC_OBJECT_INPUT ) return;
762
763     assert( p_sys->p_header->mode < SPEEX_NB_MODES );
764
765     p_mode = speex_mode_list[p_sys->p_header->mode];
766     assert( p_mode != NULL );
767
768     input_Control( p_input, INPUT_ADD_INFO, _("Speex comment"), _("Mode"),
769                    "%s%s", p_mode->modeName,
770                    p_sys->p_header->vbr ? " VBR" : "" );
771
772     if( p_oggpacket->bytes < 8 )
773     {
774         msg_Err( p_dec, "invalid/corrupted comments" );
775         return;
776     }
777
778     i_len = readint( p_buf, 0 ); p_buf += 4;
779     if( i_len > p_oggpacket->bytes - 4 )
780     {
781         msg_Err( p_dec, "invalid/corrupted comments" );
782         return;
783     }
784
785     input_Control( p_input, INPUT_ADD_INFO, _("Speex comment"), p_buf, "" );
786
787     /* TODO: finish comments parsing */
788 }
789
790 /*****************************************************************************
791  * CloseDecoder: speex decoder destruction
792  *****************************************************************************/
793 static void CloseDecoder( vlc_object_t *p_this )
794 {
795     decoder_t * p_dec = (decoder_t *)p_this;
796     decoder_sys_t *p_sys = p_dec->p_sys;
797
798     if( p_sys->p_state )
799     {
800         speex_decoder_destroy( p_sys->p_state );
801         speex_bits_destroy( &p_sys->bits );
802     }
803
804     if( p_sys->p_header ) free( p_sys->p_header );
805     free( p_sys );
806 }
807
808 /*****************************************************************************
809  * encoder_sys_t: encoder descriptor
810  *****************************************************************************/
811 #define MAX_FRAME_SIZE  2000
812 #define MAX_FRAME_BYTES 2000
813
814 struct encoder_sys_t
815 {
816     /*
817      * Input properties
818      */
819     char *p_buffer;
820     char p_buffer_out[MAX_FRAME_BYTES];
821
822     /*
823      * Speex properties
824      */
825     SpeexBits bits;
826     SpeexHeader header;
827     SpeexStereoState stereo;
828     void *p_state;
829
830     int i_frames_per_packet;
831     int i_frames_in_packet;
832
833     int i_frame_length;
834     int i_samples_delay;
835     int i_frame_size;
836
837     /*
838      * Common properties
839      */
840     mtime_t i_pts;
841 };
842
843 /*****************************************************************************
844  * OpenEncoder: probe the encoder and return score
845  *****************************************************************************/
846 static int OpenEncoder( vlc_object_t *p_this )
847 {
848     encoder_t *p_enc = (encoder_t *)p_this;
849     encoder_sys_t *p_sys;
850     const SpeexMode *p_speex_mode = &speex_nb_mode;
851     int i_quality, i;
852     const char *pp_header[2];
853     int pi_header[2];
854     uint8_t *p_extra;
855
856     if( p_enc->fmt_out.i_codec != VLC_FOURCC('s','p','x',' ') &&
857         !p_enc->b_force )
858     {
859         return VLC_EGENERIC;
860     }
861
862     /* Allocate the memory needed to store the decoder's structure */
863     if( ( p_sys = (encoder_sys_t *)malloc(sizeof(encoder_sys_t)) ) == NULL )
864     {
865         msg_Err( p_enc, "out of memory" );
866         return VLC_EGENERIC;
867     }
868     p_enc->p_sys = p_sys;
869     p_enc->pf_encode_audio = Encode;
870     p_enc->fmt_in.i_codec = AOUT_FMT_S16_NE;
871     p_enc->fmt_out.i_codec = VLC_FOURCC('s','p','x',' ');
872
873     speex_init_header( &p_sys->header, p_enc->fmt_in.audio.i_rate,
874                        1, p_speex_mode );
875
876     p_sys->header.frames_per_packet = 1;
877     p_sys->header.vbr = 1;
878     p_sys->header.nb_channels = p_enc->fmt_in.audio.i_channels;
879
880     /* Create a new encoder state in narrowband mode */
881     p_sys->p_state = speex_encoder_init( p_speex_mode );
882
883     /* Set the quality to 8 (15 kbps) */
884     i_quality = 8;
885     speex_encoder_ctl( p_sys->p_state, SPEEX_SET_QUALITY, &i_quality );
886
887     /*Initialization of the structure that holds the bits*/
888     speex_bits_init( &p_sys->bits );
889
890     p_sys->i_frames_in_packet = 0;
891     p_sys->i_samples_delay = 0;
892     p_sys->i_pts = 0;
893
894     speex_encoder_ctl( p_sys->p_state, SPEEX_GET_FRAME_SIZE,
895                        &p_sys->i_frame_length );
896
897     p_sys->i_frame_size = p_sys->i_frame_length *
898         sizeof(int16_t) * p_enc->fmt_in.audio.i_channels;
899     p_sys->p_buffer = malloc( p_sys->i_frame_size );
900
901     /* Create and store headers */
902     pp_header[0] = speex_header_to_packet( &p_sys->header, &pi_header[0] );
903     pp_header[1] = "ENCODER=VLC media player";
904     pi_header[1] = sizeof("ENCODER=VLC media player");
905
906     p_enc->fmt_out.i_extra = 3 * 2 + pi_header[0] + pi_header[1];
907     p_extra = p_enc->fmt_out.p_extra = malloc( p_enc->fmt_out.i_extra );
908     for( i = 0; i < 2; i++ )
909     {
910         *(p_extra++) = pi_header[i] >> 8;
911         *(p_extra++) = pi_header[i] & 0xFF;
912         memcpy( p_extra, pp_header[i], pi_header[i] );
913         p_extra += pi_header[i];
914     }
915
916     msg_Dbg( p_enc, "encoding: frame size:%d, channels:%d, samplerate:%d",
917              p_sys->i_frame_size, p_enc->fmt_in.audio.i_channels,
918              p_enc->fmt_in.audio.i_rate );
919
920     return VLC_SUCCESS;
921 }
922
923 /****************************************************************************
924  * Encode: the whole thing
925  ****************************************************************************
926  * This function spits out ogg packets.
927  ****************************************************************************/
928 static block_t *Encode( encoder_t *p_enc, aout_buffer_t *p_aout_buf )
929 {
930     encoder_sys_t *p_sys = p_enc->p_sys;
931     block_t *p_block, *p_chain = NULL;
932
933     unsigned char *p_buffer = p_aout_buf->p_buffer;
934     int i_samples = p_aout_buf->i_nb_samples;
935     int i_samples_delay = p_sys->i_samples_delay;
936
937     p_sys->i_pts = p_aout_buf->start_date -
938                 (mtime_t)1000000 * (mtime_t)p_sys->i_samples_delay /
939                 (mtime_t)p_enc->fmt_in.audio.i_rate;
940
941     p_sys->i_samples_delay += i_samples;
942
943     while( p_sys->i_samples_delay >= p_sys->i_frame_length )
944     {
945         int16_t *p_samples;
946         int i_out;
947
948         if( i_samples_delay )
949         {
950             /* Take care of the left-over from last time */
951             int i_delay_size = i_samples_delay * 2 *
952                                  p_enc->fmt_in.audio.i_channels;
953             int i_size = p_sys->i_frame_size - i_delay_size;
954
955             p_samples = (int16_t *)p_sys->p_buffer;
956             memcpy( p_sys->p_buffer + i_delay_size, p_buffer, i_size );
957             p_buffer -= i_delay_size;
958             i_samples += i_samples_delay;
959             i_samples_delay = 0;
960         }
961         else
962         {
963             p_samples = (int16_t *)p_buffer;
964         }
965
966         /* Encode current frame */
967         if( p_enc->fmt_in.audio.i_channels == 2 )
968             speex_encode_stereo_int( p_samples, p_sys->i_frame_length,
969                                      &p_sys->bits );
970
971 #if 0
972         if( p_sys->preprocess )
973             speex_preprocess( p_sys->preprocess, p_samples, NULL );
974 #endif
975
976         speex_encode_int( p_sys->p_state, p_samples, &p_sys->bits );
977
978         p_buffer += p_sys->i_frame_size;
979         p_sys->i_samples_delay -= p_sys->i_frame_length;
980         i_samples -= p_sys->i_frame_length;
981
982         p_sys->i_frames_in_packet++;
983
984         if( p_sys->i_frames_in_packet < p_sys->header.frames_per_packet )
985             continue;
986
987         p_sys->i_frames_in_packet = 0;
988
989         speex_bits_insert_terminator( &p_sys->bits );
990         i_out = speex_bits_write( &p_sys->bits, p_sys->p_buffer_out,
991                                   MAX_FRAME_BYTES );
992         speex_bits_reset( &p_sys->bits );
993
994         p_block = block_New( p_enc, i_out );
995         memcpy( p_block->p_buffer, p_sys->p_buffer_out, i_out );
996
997         p_block->i_length = (mtime_t)1000000 *
998             (mtime_t)p_sys->i_frame_length * p_sys->header.frames_per_packet /
999             (mtime_t)p_enc->fmt_in.audio.i_rate;
1000
1001         p_block->i_dts = p_block->i_pts = p_sys->i_pts;
1002
1003         /* Update pts */
1004         p_sys->i_pts += p_block->i_length;
1005         block_ChainAppend( &p_chain, p_block );
1006
1007     }
1008
1009     /* Backup the remaining raw samples */
1010     if( i_samples )
1011     {
1012         memcpy( p_sys->p_buffer + i_samples_delay * 2 *
1013                 p_enc->fmt_in.audio.i_channels, p_buffer,
1014                 i_samples * 2 * p_enc->fmt_in.audio.i_channels );
1015     }
1016
1017     return p_chain;
1018 }
1019
1020 /*****************************************************************************
1021  * CloseEncoder: encoder destruction
1022  *****************************************************************************/
1023 static void CloseEncoder( vlc_object_t *p_this )
1024 {
1025     encoder_t *p_enc = (encoder_t *)p_this;
1026     encoder_sys_t *p_sys = p_enc->p_sys;
1027
1028     speex_encoder_destroy( p_sys->p_state );
1029     speex_bits_destroy( &p_sys->bits );
1030
1031     if( p_sys->p_buffer ) free( p_sys->p_buffer );
1032     free( p_sys );
1033 }