1 /*****************************************************************************
2 * speex.c: speex decoder/packetizer/encoder module making use of libspeex.
3 *****************************************************************************
4 * Copyright (C) 2003 VideoLAN
7 * Authors: Gildas Bazin <gbazin@videolan.org>
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.
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.
19 * You should have received a copy of the GNU General Public License
20 * along with this program; if not, write to the Free Software
21 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111, USA.
22 *****************************************************************************/
24 /*****************************************************************************
26 *****************************************************************************/
28 #include <vlc/decoder.h>
29 #include <vlc/input.h>
32 #include <speex/speex.h>
33 #include <speex/speex_header.h>
34 #include <speex/speex_stereo.h>
35 #include <speex/speex_callbacks.h>
37 /*****************************************************************************
38 * decoder_sys_t : speex decoder descriptor
39 *****************************************************************************/
43 vlc_bool_t b_packetizer;
49 int i_frame_in_packet;
55 SpeexHeader *p_header;
56 SpeexStereoState stereo;
62 audio_date_t end_date;
66 static int pi_channels_maps[6] =
69 AOUT_CHAN_CENTER, AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT,
70 AOUT_CHAN_CENTER | AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT,
71 AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_REARLEFT
72 | AOUT_CHAN_REARRIGHT,
73 AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_CENTER
74 | AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT
77 /****************************************************************************
79 ****************************************************************************/
80 static int OpenDecoder ( vlc_object_t * );
81 static int OpenPacketizer( vlc_object_t * );
82 static void CloseDecoder ( vlc_object_t * );
84 static void *DecodeBlock ( decoder_t *, block_t ** );
85 static int ProcessHeaders( decoder_t * );
86 static int ProcessInitialHeader ( decoder_t *, ogg_packet * );
87 static void *ProcessPacket( decoder_t *, ogg_packet *, block_t ** );
89 static aout_buffer_t *DecodePacket( decoder_t *, ogg_packet * );
90 static block_t *SendPacket( decoder_t *, ogg_packet *, block_t * );
92 static void ParseSpeexComments( decoder_t *, ogg_packet * );
94 static int OpenEncoder ( vlc_object_t * );
95 static void CloseEncoder ( vlc_object_t * );
96 static block_t *Encode ( encoder_t *, aout_buffer_t * );
98 /*****************************************************************************
100 *****************************************************************************/
102 set_category( CAT_INPUT );
103 set_subcategory( SUBCAT_INPUT_ACODEC );
105 set_description( _("Speex audio decoder") );
106 set_capability( "decoder", 100 );
107 set_callbacks( OpenDecoder, CloseDecoder );
110 set_description( _("Speex audio packetizer") );
111 set_capability( "packetizer", 100 );
112 set_callbacks( OpenPacketizer, CloseDecoder );
115 set_description( _("Speex audio encoder") );
116 set_capability( "encoder", 100 );
117 set_callbacks( OpenEncoder, CloseEncoder );
120 /*****************************************************************************
121 * OpenDecoder: probe the decoder and return score
122 *****************************************************************************/
123 static int OpenDecoder( vlc_object_t *p_this )
125 decoder_t *p_dec = (decoder_t*)p_this;
126 decoder_sys_t *p_sys = p_dec->p_sys;
128 if( p_dec->fmt_in.i_codec != VLC_FOURCC('s','p','x',' ') )
133 /* Allocate the memory needed to store the decoder's structure */
134 if( ( p_dec->p_sys = p_sys =
135 (decoder_sys_t *)malloc(sizeof(decoder_sys_t)) ) == NULL )
137 msg_Err( p_dec, "out of memory" );
140 p_dec->p_sys->b_packetizer = VLC_FALSE;
142 aout_DateSet( &p_sys->end_date, 0 );
144 /* Set output properties */
145 p_dec->fmt_out.i_cat = AUDIO_ES;
146 p_dec->fmt_out.i_codec = AOUT_FMT_S16_NE;
149 p_dec->pf_decode_audio = (aout_buffer_t *(*)(decoder_t *, block_t **))
151 p_dec->pf_packetize = (block_t *(*)(decoder_t *, block_t **))
154 p_sys->i_headers = 0;
155 p_sys->p_state = NULL;
156 p_sys->p_header = NULL;
157 p_sys->i_frame_in_packet = 0;
162 static int OpenPacketizer( vlc_object_t *p_this )
164 decoder_t *p_dec = (decoder_t*)p_this;
166 int i_ret = OpenDecoder( p_this );
168 if( i_ret == VLC_SUCCESS )
170 p_dec->p_sys->b_packetizer = VLC_TRUE;
171 p_dec->fmt_out.i_codec = VLC_FOURCC('s','p','x',' ');
177 /****************************************************************************
178 * DecodeBlock: the whole thing
179 ****************************************************************************
180 * This function must be fed with ogg packets.
181 ****************************************************************************/
182 static void *DecodeBlock( decoder_t *p_dec, block_t **pp_block )
184 decoder_sys_t *p_sys = p_dec->p_sys;
185 ogg_packet oggpacket;
187 if( !pp_block ) return NULL;
191 /* Block to Ogg packet */
192 oggpacket.packet = (*pp_block)->p_buffer;
193 oggpacket.bytes = (*pp_block)->i_buffer;
197 if( p_sys->b_packetizer ) return NULL;
199 /* Block to Ogg packet */
200 oggpacket.packet = NULL;
204 oggpacket.granulepos = -1;
207 oggpacket.packetno = 0;
209 /* Check for headers */
210 if( p_sys->i_headers == 0 && p_dec->fmt_in.i_extra )
212 /* Headers already available as extra data */
213 p_sys->i_headers = 2;
215 else if( oggpacket.bytes && p_sys->i_headers < 2 )
217 /* Backup headers as extra data */
220 p_dec->fmt_in.p_extra =
221 realloc( p_dec->fmt_in.p_extra, p_dec->fmt_in.i_extra +
222 oggpacket.bytes + 2 );
223 p_extra = p_dec->fmt_in.p_extra + p_dec->fmt_in.i_extra;
224 *(p_extra++) = oggpacket.bytes >> 8;
225 *(p_extra++) = oggpacket.bytes & 0xFF;
227 memcpy( p_extra, oggpacket.packet, oggpacket.bytes );
228 p_dec->fmt_in.i_extra += oggpacket.bytes + 2;
230 block_Release( *pp_block );
235 if( p_sys->i_headers == 2 )
237 if( ProcessHeaders( p_dec ) != VLC_SUCCESS )
239 p_sys->i_headers = 0;
240 p_dec->fmt_in.i_extra = 0;
241 block_Release( *pp_block );
244 else p_sys->i_headers++;
247 return ProcessPacket( p_dec, &oggpacket, pp_block );
250 /*****************************************************************************
251 * ProcessHeaders: process Speex headers.
252 *****************************************************************************/
253 static int ProcessHeaders( decoder_t *p_dec )
255 decoder_sys_t *p_sys = p_dec->p_sys;
256 ogg_packet oggpacket;
260 if( !p_dec->fmt_in.i_extra ) return VLC_EGENERIC;
262 oggpacket.granulepos = -1;
263 oggpacket.b_o_s = 1; /* yes this actually is a b_o_s packet :) */
265 oggpacket.packetno = 0;
266 p_extra = p_dec->fmt_in.p_extra;
267 i_extra = p_dec->fmt_in.i_extra;
269 /* Take care of the initial Vorbis header */
270 oggpacket.bytes = *(p_extra++) << 8;
271 oggpacket.bytes |= (*(p_extra++) & 0xFF);
272 oggpacket.packet = p_extra;
273 p_extra += oggpacket.bytes;
274 i_extra -= (oggpacket.bytes + 2);
277 msg_Err( p_dec, "header data corrupted");
281 /* Take care of the initial Speex header */
282 if( ProcessInitialHeader( p_dec, &oggpacket ) != VLC_SUCCESS )
284 msg_Err( p_dec, "initial Speex header is corrupted" );
288 /* The next packet in order is the comments header */
290 oggpacket.bytes = *(p_extra++) << 8;
291 oggpacket.bytes |= (*(p_extra++) & 0xFF);
292 oggpacket.packet = p_extra;
293 p_extra += oggpacket.bytes;
294 i_extra -= (oggpacket.bytes + 2);
297 msg_Err( p_dec, "header data corrupted");
301 ParseSpeexComments( p_dec, &oggpacket );
303 if( p_sys->b_packetizer )
305 p_dec->fmt_out.i_extra = p_dec->fmt_in.i_extra;
306 p_dec->fmt_out.p_extra =
307 realloc( p_dec->fmt_out.p_extra, p_dec->fmt_out.i_extra );
308 memcpy( p_dec->fmt_out.p_extra,
309 p_dec->fmt_in.p_extra, p_dec->fmt_out.i_extra );
315 /*****************************************************************************
316 * ProcessInitialHeader: processes the inital Speex header packet.
317 *****************************************************************************/
318 static int ProcessInitialHeader( decoder_t *p_dec, ogg_packet *p_oggpacket )
320 decoder_sys_t *p_sys = p_dec->p_sys;
323 SpeexHeader *p_header;
324 const SpeexMode *p_mode;
325 SpeexCallback callback;
327 p_sys->p_header = p_header =
328 speex_packet_to_header( p_oggpacket->packet, p_oggpacket->bytes );
331 msg_Err( p_dec, "cannot read Speex header" );
334 if( p_header->mode >= SPEEX_NB_MODES )
336 msg_Err( p_dec, "mode number %d does not (yet/any longer) exist in "
337 "this version of libspeex.", p_header->mode );
341 p_mode = speex_mode_list[p_header->mode];
343 if( p_header->speex_version_id > 1 )
345 msg_Err( p_dec, "this file was encoded with Speex bit-stream "
346 "version %d, which I don't know how to decode.",
347 p_header->speex_version_id );
351 if( p_mode->bitstream_version < p_header->mode_bitstream_version )
353 msg_Err( p_dec, "file encoded with a newer version of Speex." );
356 if( p_mode->bitstream_version > p_header->mode_bitstream_version )
358 msg_Err( p_dec, "file encoded with an older version of Speex." );
362 msg_Dbg( p_dec, "Speex %d Hz audio using %s mode %s%s",
363 p_header->rate, p_mode->modeName,
364 ( p_header->nb_channels == 1 ) ? " (mono" : " (stereo",
365 p_header->vbr ? ", VBR)" : ")" );
367 /* Take care of speex decoder init */
368 speex_bits_init( &p_sys->bits );
369 p_sys->p_state = p_state = speex_decoder_init( p_mode );
372 msg_Err( p_dec, "decoder initialization failed" );
376 if( p_header->nb_channels == 2 )
378 SpeexStereoState stereo = SPEEX_STEREO_STATE_INIT;
379 p_sys->stereo = stereo;
380 callback.callback_id = SPEEX_INBAND_STEREO;
381 callback.func = speex_std_stereo_request_handler;
382 callback.data = &p_sys->stereo;
383 speex_decoder_ctl( p_state, SPEEX_SET_HANDLER, &callback );
386 /* Setup the format */
387 p_dec->fmt_out.audio.i_physical_channels =
388 p_dec->fmt_out.audio.i_original_channels =
389 pi_channels_maps[p_header->nb_channels];
390 p_dec->fmt_out.audio.i_channels = p_header->nb_channels;
391 p_dec->fmt_out.audio.i_rate = p_header->rate;
393 aout_DateInit( &p_sys->end_date, p_header->rate );
398 /*****************************************************************************
399 * ProcessPacket: processes a Speex packet.
400 *****************************************************************************/
401 static void *ProcessPacket( decoder_t *p_dec, ogg_packet *p_oggpacket,
404 decoder_sys_t *p_sys = p_dec->p_sys;
405 block_t *p_block = *pp_block;
407 /* Date management */
408 if( p_block && p_block->i_pts > 0 &&
409 p_block->i_pts != aout_DateGet( &p_sys->end_date ) )
411 aout_DateSet( &p_sys->end_date, p_block->i_pts );
414 if( !aout_DateGet( &p_sys->end_date ) )
416 /* We've just started the stream, wait for the first PTS. */
417 if( p_block ) block_Release( p_block );
421 *pp_block = NULL; /* To avoid being fed the same packet again */
423 if( p_sys->b_packetizer )
425 return SendPacket( p_dec, p_oggpacket, p_block );
429 aout_buffer_t *p_aout_buffer;
431 if( p_sys->i_headers >= p_sys->p_header->extra_headers + 2 )
432 p_aout_buffer = DecodePacket( p_dec, p_oggpacket );
434 p_aout_buffer = NULL; /* Skip headers */
436 if( p_block ) block_Release( p_block );
437 return p_aout_buffer;
441 /*****************************************************************************
442 * DecodePacket: decodes a Speex packet.
443 *****************************************************************************/
444 static aout_buffer_t *DecodePacket( decoder_t *p_dec, ogg_packet *p_oggpacket )
446 decoder_sys_t *p_sys = p_dec->p_sys;
448 if( p_oggpacket->bytes )
450 /* Copy Ogg packet to Speex bitstream */
451 speex_bits_read_from( &p_sys->bits, p_oggpacket->packet,
452 p_oggpacket->bytes );
453 p_sys->i_frame_in_packet = 0;
456 /* Decode one frame at a time */
457 if( p_sys->i_frame_in_packet < p_sys->p_header->frames_per_packet )
459 aout_buffer_t *p_aout_buffer;
463 p_dec->pf_aout_buffer_new( p_dec, p_sys->p_header->frame_size );
469 i_ret = speex_decode_int( p_sys->p_state, &p_sys->bits,
470 (int16_t *)p_aout_buffer->p_buffer );
479 msg_Warn( p_dec, "decoding error: corrupted stream?" );
483 if( speex_bits_remaining( &p_sys->bits ) < 0 )
485 msg_Warn( p_dec, "decoding overflow: corrupted stream?" );
488 if( p_sys->p_header->nb_channels == 2 )
489 speex_decode_stereo_int( (int16_t *)p_aout_buffer->p_buffer,
490 p_sys->p_header->frame_size,
493 /* Date management */
494 p_aout_buffer->start_date = aout_DateGet( &p_sys->end_date );
495 p_aout_buffer->end_date =
496 aout_DateIncrement( &p_sys->end_date, p_sys->p_header->frame_size);
498 p_sys->i_frame_in_packet++;
500 return p_aout_buffer;
508 /*****************************************************************************
509 * SendPacket: send an ogg packet to the stream output.
510 *****************************************************************************/
511 static block_t *SendPacket( decoder_t *p_dec, ogg_packet *p_oggpacket,
514 decoder_sys_t *p_sys = p_dec->p_sys;
516 /* Date management */
517 p_block->i_dts = p_block->i_pts = aout_DateGet( &p_sys->end_date );
519 if( p_sys->i_headers >= p_sys->p_header->extra_headers + 2 )
521 aout_DateIncrement( &p_sys->end_date,
522 p_sys->p_header->frame_size ) -
525 p_block->i_length = 0;
530 /*****************************************************************************
531 * ParseSpeexComments: FIXME should be done in demuxer
532 *****************************************************************************/
533 #define readint(buf, base) (((buf[base+3]<<24)&0xff000000)| \
534 ((buf[base+2]<<16)&0xff0000)| \
535 ((buf[base+1]<<8)&0xff00)| \
538 static void ParseSpeexComments( decoder_t *p_dec, ogg_packet *p_oggpacket )
540 input_thread_t *p_input = (input_thread_t *)p_dec->p_parent;
541 decoder_sys_t *p_sys = p_dec->p_sys;
543 char *p_buf = (char *)p_oggpacket->packet;
544 const SpeexMode *p_mode;
547 if( p_input->i_object_type != VLC_OBJECT_INPUT ) return;
549 p_mode = speex_mode_list[p_sys->p_header->mode];
551 input_Control( p_input, INPUT_ADD_INFO, _("Speex comment"), _("Mode"),
552 "%s%s", p_mode->modeName,
553 p_sys->p_header->vbr ? " VBR" : "" );
555 if( p_oggpacket->bytes < 8 )
557 msg_Warn( p_dec, "invalid/corrupted comments" );
561 i_len = readint( p_buf, 0 ); p_buf += 4;
562 if( i_len > p_oggpacket->bytes - 4 )
564 msg_Warn( p_dec, "invalid/corrupted comments" );
568 input_Control( p_input, INPUT_ADD_INFO, _("Speex comment"), p_buf, "" );
570 /* TODO: finish comments parsing */
573 /*****************************************************************************
574 * CloseDecoder: speex decoder destruction
575 *****************************************************************************/
576 static void CloseDecoder( vlc_object_t *p_this )
578 decoder_t * p_dec = (decoder_t *)p_this;
579 decoder_sys_t *p_sys = p_dec->p_sys;
583 speex_decoder_destroy( p_sys->p_state );
584 speex_bits_destroy( &p_sys->bits );
587 if( p_sys->p_header ) free( p_sys->p_header );
591 /*****************************************************************************
592 * encoder_sys_t: encoder descriptor
593 *****************************************************************************/
594 #define MAX_FRAME_SIZE 2000
595 #define MAX_FRAME_BYTES 2000
603 char p_buffer_out[MAX_FRAME_BYTES];
610 SpeexStereoState stereo;
613 int i_frames_per_packet;
614 int i_frames_in_packet;
626 /*****************************************************************************
627 * OpenEncoder: probe the encoder and return score
628 *****************************************************************************/
629 static int OpenEncoder( vlc_object_t *p_this )
631 encoder_t *p_enc = (encoder_t *)p_this;
632 encoder_sys_t *p_sys;
633 const SpeexMode *p_speex_mode = &speex_nb_mode;
639 if( p_enc->fmt_out.i_codec != VLC_FOURCC('s','p','x',' ') &&
645 /* Allocate the memory needed to store the decoder's structure */
646 if( ( p_sys = (encoder_sys_t *)malloc(sizeof(encoder_sys_t)) ) == NULL )
648 msg_Err( p_enc, "out of memory" );
651 p_enc->p_sys = p_sys;
652 p_enc->pf_encode_audio = Encode;
653 p_enc->fmt_in.i_codec = AOUT_FMT_S16_NE;
654 p_enc->fmt_out.i_codec = VLC_FOURCC('s','p','x',' ');
656 speex_init_header( &p_sys->header, p_enc->fmt_in.audio.i_rate,
659 p_sys->header.frames_per_packet = 1;
660 p_sys->header.vbr = 1;
661 p_sys->header.nb_channels = p_enc->fmt_in.audio.i_channels;
663 /* Create a new encoder state in narrowband mode */
664 p_sys->p_state = speex_encoder_init( p_speex_mode );
666 /* Set the quality to 8 (15 kbps) */
668 speex_encoder_ctl( p_sys->p_state, SPEEX_SET_QUALITY, &i_quality );
670 /*Initialization of the structure that holds the bits*/
671 speex_bits_init( &p_sys->bits );
673 p_sys->i_frames_in_packet = 0;
674 p_sys->i_samples_delay = 0;
677 speex_encoder_ctl( p_sys->p_state, SPEEX_GET_FRAME_SIZE,
678 &p_sys->i_frame_length );
680 p_sys->i_frame_size = p_sys->i_frame_length *
681 sizeof(int16_t) * p_enc->fmt_in.audio.i_channels;
682 p_sys->p_buffer = malloc( p_sys->i_frame_size );
684 /* Create and store headers */
685 pp_header[0] = speex_header_to_packet( &p_sys->header, &pi_header[0] );
686 pp_header[1] = "ENCODER=VLC media player";
687 pi_header[1] = sizeof("ENCODER=VLC media player");
689 p_enc->fmt_out.i_extra = 3 * 2 + pi_header[0] + pi_header[1];
690 p_extra = p_enc->fmt_out.p_extra = malloc( p_enc->fmt_out.i_extra );
691 for( i = 0; i < 2; i++ )
693 *(p_extra++) = pi_header[i] >> 8;
694 *(p_extra++) = pi_header[i] & 0xFF;
695 memcpy( p_extra, pp_header[i], pi_header[i] );
696 p_extra += pi_header[i];
699 msg_Dbg( p_enc, "encoding: frame size:%d, channels:%d, samplerate:%d",
700 p_sys->i_frame_size, p_enc->fmt_in.audio.i_channels,
701 p_enc->fmt_in.audio.i_rate );
706 /****************************************************************************
707 * Encode: the whole thing
708 ****************************************************************************
709 * This function spits out ogg packets.
710 ****************************************************************************/
711 static block_t *Encode( encoder_t *p_enc, aout_buffer_t *p_aout_buf )
713 encoder_sys_t *p_sys = p_enc->p_sys;
714 block_t *p_block, *p_chain = NULL;
716 char *p_buffer = p_aout_buf->p_buffer;
717 int i_samples = p_aout_buf->i_nb_samples;
718 int i_samples_delay = p_sys->i_samples_delay;
720 p_sys->i_pts = p_aout_buf->start_date -
721 (mtime_t)1000000 * (mtime_t)p_sys->i_samples_delay /
722 (mtime_t)p_enc->fmt_in.audio.i_rate;
724 p_sys->i_samples_delay += i_samples;
726 while( p_sys->i_samples_delay >= p_sys->i_frame_length )
731 if( i_samples_delay )
733 /* Take care of the left-over from last time */
734 int i_delay_size = i_samples_delay * 2 *
735 p_enc->fmt_in.audio.i_channels;
736 int i_size = p_sys->i_frame_size - i_delay_size;
738 p_samples = (int16_t *)p_sys->p_buffer;
739 memcpy( p_sys->p_buffer + i_delay_size, p_buffer, i_size );
740 p_buffer -= i_delay_size;
741 i_samples += i_samples_delay;
746 p_samples = (int16_t *)p_buffer;
749 /* Encode current frame */
750 if( p_enc->fmt_in.audio.i_channels == 2 )
751 speex_encode_stereo_int( p_samples, p_sys->i_frame_length,
755 if( p_sys->preprocess )
756 speex_preprocess( p_sys->preprocess, p_samples, NULL );
759 speex_encode_int( p_sys->p_state, p_samples, &p_sys->bits );
761 p_buffer += p_sys->i_frame_size;
762 p_sys->i_samples_delay -= p_sys->i_frame_length;
763 i_samples -= p_sys->i_frame_length;
765 p_sys->i_frames_in_packet++;
767 if( p_sys->i_frames_in_packet < p_sys->header.frames_per_packet )
770 p_sys->i_frames_in_packet = 0;
772 speex_bits_insert_terminator( &p_sys->bits );
773 i_out = speex_bits_write( &p_sys->bits, p_sys->p_buffer_out,
775 speex_bits_reset( &p_sys->bits );
777 p_block = block_New( p_enc, i_out );
778 memcpy( p_block->p_buffer, p_sys->p_buffer_out, i_out );
780 p_block->i_length = (mtime_t)1000000 *
781 (mtime_t)p_sys->i_frame_length * p_sys->header.frames_per_packet /
782 (mtime_t)p_enc->fmt_in.audio.i_rate;
784 p_block->i_dts = p_block->i_pts = p_sys->i_pts;
787 p_sys->i_pts += p_block->i_length;
788 block_ChainAppend( &p_chain, p_block );
792 /* Backup the remaining raw samples */
795 memcpy( p_sys->p_buffer + i_samples_delay * 2 *
796 p_enc->fmt_in.audio.i_channels, p_buffer,
797 i_samples * 2 * p_enc->fmt_in.audio.i_channels );
803 /*****************************************************************************
804 * CloseEncoder: encoder destruction
805 *****************************************************************************/
806 static void CloseEncoder( vlc_object_t *p_this )
808 encoder_t *p_enc = (encoder_t *)p_this;
809 encoder_sys_t *p_sys = p_enc->p_sys;
811 speex_encoder_destroy( p_sys->p_state );
812 speex_bits_destroy( &p_sys->bits );
814 if( p_sys->p_buffer ) free( p_sys->p_buffer );