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