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