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_description( _("Speex audio decoder") );
103 set_capability( "decoder", 100 );
104 set_callbacks( OpenDecoder, CloseDecoder );
107 set_description( _("Speex audio packetizer") );
108 set_capability( "packetizer", 100 );
109 set_callbacks( OpenPacketizer, CloseDecoder );
112 set_description( _("Speex audio encoder") );
113 set_capability( "encoder", 100 );
114 set_callbacks( OpenEncoder, CloseEncoder );
117 /*****************************************************************************
118 * OpenDecoder: probe the decoder and return score
119 *****************************************************************************/
120 static int OpenDecoder( vlc_object_t *p_this )
122 decoder_t *p_dec = (decoder_t*)p_this;
123 decoder_sys_t *p_sys = p_dec->p_sys;
125 if( p_dec->fmt_in.i_codec != VLC_FOURCC('s','p','x',' ') )
130 /* Allocate the memory needed to store the decoder's structure */
131 if( ( p_dec->p_sys = p_sys =
132 (decoder_sys_t *)malloc(sizeof(decoder_sys_t)) ) == NULL )
134 msg_Err( p_dec, "out of memory" );
137 p_dec->p_sys->b_packetizer = VLC_FALSE;
139 aout_DateSet( &p_sys->end_date, 0 );
141 /* Set output properties */
142 p_dec->fmt_out.i_cat = AUDIO_ES;
143 p_dec->fmt_out.i_codec = AOUT_FMT_S16_NE;
146 p_dec->pf_decode_audio = (aout_buffer_t *(*)(decoder_t *, block_t **))
148 p_dec->pf_packetize = (block_t *(*)(decoder_t *, block_t **))
151 p_sys->i_headers = 0;
152 p_sys->p_state = NULL;
153 p_sys->p_header = NULL;
154 p_sys->i_frame_in_packet = 0;
159 static int OpenPacketizer( vlc_object_t *p_this )
161 decoder_t *p_dec = (decoder_t*)p_this;
163 int i_ret = OpenDecoder( p_this );
165 if( i_ret == VLC_SUCCESS )
167 p_dec->p_sys->b_packetizer = VLC_TRUE;
168 p_dec->fmt_out.i_codec = VLC_FOURCC('s','p','x',' ');
174 /****************************************************************************
175 * DecodeBlock: the whole thing
176 ****************************************************************************
177 * This function must be fed with ogg packets.
178 ****************************************************************************/
179 static void *DecodeBlock( decoder_t *p_dec, block_t **pp_block )
181 decoder_sys_t *p_sys = p_dec->p_sys;
182 ogg_packet oggpacket;
184 if( !pp_block ) return NULL;
188 /* Block to Ogg packet */
189 oggpacket.packet = (*pp_block)->p_buffer;
190 oggpacket.bytes = (*pp_block)->i_buffer;
194 if( p_sys->b_packetizer ) return NULL;
196 /* Block to Ogg packet */
197 oggpacket.packet = NULL;
201 oggpacket.granulepos = -1;
204 oggpacket.packetno = 0;
206 /* Check for headers */
207 if( p_sys->i_headers == 0 && p_dec->fmt_in.i_extra )
209 /* Headers already available as extra data */
210 p_sys->i_headers = 2;
212 else if( oggpacket.bytes && p_sys->i_headers < 2 )
214 /* Backup headers as extra data */
217 p_dec->fmt_in.p_extra =
218 realloc( p_dec->fmt_in.p_extra, p_dec->fmt_in.i_extra +
219 oggpacket.bytes + 2 );
220 p_extra = p_dec->fmt_in.p_extra + p_dec->fmt_in.i_extra;
221 *(p_extra++) = oggpacket.bytes >> 8;
222 *(p_extra++) = oggpacket.bytes & 0xFF;
224 memcpy( p_extra, oggpacket.packet, oggpacket.bytes );
225 p_dec->fmt_in.i_extra += oggpacket.bytes + 2;
227 block_Release( *pp_block );
232 if( p_sys->i_headers == 2 )
234 if( ProcessHeaders( p_dec ) != VLC_SUCCESS )
236 p_sys->i_headers = 0;
237 p_dec->fmt_in.i_extra = 0;
238 block_Release( *pp_block );
241 else p_sys->i_headers++;
244 return ProcessPacket( p_dec, &oggpacket, pp_block );
247 /*****************************************************************************
248 * ProcessHeaders: process Speex headers.
249 *****************************************************************************/
250 static int ProcessHeaders( decoder_t *p_dec )
252 decoder_sys_t *p_sys = p_dec->p_sys;
253 ogg_packet oggpacket;
257 if( !p_dec->fmt_in.i_extra ) return VLC_EGENERIC;
259 oggpacket.granulepos = -1;
260 oggpacket.b_o_s = 1; /* yes this actually is a b_o_s packet :) */
262 oggpacket.packetno = 0;
263 p_extra = p_dec->fmt_in.p_extra;
264 i_extra = p_dec->fmt_in.i_extra;
266 /* Take care of the initial Vorbis header */
267 oggpacket.bytes = *(p_extra++) << 8;
268 oggpacket.bytes |= (*(p_extra++) & 0xFF);
269 oggpacket.packet = p_extra;
270 p_extra += oggpacket.bytes;
271 i_extra -= (oggpacket.bytes + 2);
274 msg_Err( p_dec, "header data corrupted");
278 /* Take care of the initial Speex header */
279 if( ProcessInitialHeader( p_dec, &oggpacket ) != VLC_SUCCESS )
281 msg_Err( p_dec, "initial Speex header is corrupted" );
285 /* The next packet in order is the comments header */
287 oggpacket.bytes = *(p_extra++) << 8;
288 oggpacket.bytes |= (*(p_extra++) & 0xFF);
289 oggpacket.packet = p_extra;
290 p_extra += oggpacket.bytes;
291 i_extra -= (oggpacket.bytes + 2);
294 msg_Err( p_dec, "header data corrupted");
298 ParseSpeexComments( p_dec, &oggpacket );
300 if( p_sys->b_packetizer )
302 p_dec->fmt_out.i_extra = p_dec->fmt_in.i_extra;
303 p_dec->fmt_out.p_extra =
304 realloc( p_dec->fmt_out.p_extra, p_dec->fmt_out.i_extra );
305 memcpy( p_dec->fmt_out.p_extra,
306 p_dec->fmt_in.p_extra, p_dec->fmt_out.i_extra );
312 /*****************************************************************************
313 * ProcessInitialHeader: processes the inital Speex header packet.
314 *****************************************************************************/
315 static int ProcessInitialHeader( decoder_t *p_dec, ogg_packet *p_oggpacket )
317 decoder_sys_t *p_sys = p_dec->p_sys;
320 SpeexHeader *p_header;
321 const SpeexMode *p_mode;
322 SpeexCallback callback;
324 p_sys->p_header = p_header =
325 speex_packet_to_header( p_oggpacket->packet, p_oggpacket->bytes );
328 msg_Err( p_dec, "cannot read Speex header" );
331 if( p_header->mode >= SPEEX_NB_MODES )
333 msg_Err( p_dec, "mode number %d does not (yet/any longer) exist in "
334 "this version of libspeex.", p_header->mode );
338 p_mode = speex_mode_list[p_header->mode];
340 if( p_header->speex_version_id > 1 )
342 msg_Err( p_dec, "this file was encoded with Speex bit-stream "
343 "version %d, which I don't know how to decode.",
344 p_header->speex_version_id );
348 if( p_mode->bitstream_version < p_header->mode_bitstream_version )
350 msg_Err( p_dec, "file encoded with a newer version of Speex." );
353 if( p_mode->bitstream_version > p_header->mode_bitstream_version )
355 msg_Err( p_dec, "file encoded with an older version of Speex." );
359 msg_Dbg( p_dec, "Speex %d Hz audio using %s mode %s%s",
360 p_header->rate, p_mode->modeName,
361 ( p_header->nb_channels == 1 ) ? " (mono" : " (stereo",
362 p_header->vbr ? ", VBR)" : ")" );
364 /* Take care of speex decoder init */
365 speex_bits_init( &p_sys->bits );
366 p_sys->p_state = p_state = speex_decoder_init( p_mode );
369 msg_Err( p_dec, "decoder initialization failed" );
373 if( p_header->nb_channels == 2 )
375 SpeexStereoState stereo = SPEEX_STEREO_STATE_INIT;
376 p_sys->stereo = stereo;
377 callback.callback_id = SPEEX_INBAND_STEREO;
378 callback.func = speex_std_stereo_request_handler;
379 callback.data = &p_sys->stereo;
380 speex_decoder_ctl( p_state, SPEEX_SET_HANDLER, &callback );
383 /* Setup the format */
384 p_dec->fmt_out.audio.i_physical_channels =
385 p_dec->fmt_out.audio.i_original_channels =
386 pi_channels_maps[p_header->nb_channels];
387 p_dec->fmt_out.audio.i_channels = p_header->nb_channels;
388 p_dec->fmt_out.audio.i_rate = p_header->rate;
390 aout_DateInit( &p_sys->end_date, p_header->rate );
395 /*****************************************************************************
396 * ProcessPacket: processes a Speex packet.
397 *****************************************************************************/
398 static void *ProcessPacket( decoder_t *p_dec, ogg_packet *p_oggpacket,
401 decoder_sys_t *p_sys = p_dec->p_sys;
402 block_t *p_block = *pp_block;
404 /* Date management */
405 if( p_block && p_block->i_pts > 0 &&
406 p_block->i_pts != aout_DateGet( &p_sys->end_date ) )
408 aout_DateSet( &p_sys->end_date, p_block->i_pts );
411 if( !aout_DateGet( &p_sys->end_date ) )
413 /* We've just started the stream, wait for the first PTS. */
414 if( p_block ) block_Release( p_block );
418 *pp_block = NULL; /* To avoid being fed the same packet again */
420 if( p_sys->b_packetizer )
422 return SendPacket( p_dec, p_oggpacket, p_block );
426 aout_buffer_t *p_aout_buffer;
428 if( p_sys->i_headers >= p_sys->p_header->extra_headers + 2 )
429 p_aout_buffer = DecodePacket( p_dec, p_oggpacket );
431 p_aout_buffer = NULL; /* Skip headers */
433 if( p_block ) block_Release( p_block );
434 return p_aout_buffer;
438 /*****************************************************************************
439 * DecodePacket: decodes a Speex packet.
440 *****************************************************************************/
441 static aout_buffer_t *DecodePacket( decoder_t *p_dec, ogg_packet *p_oggpacket )
443 decoder_sys_t *p_sys = p_dec->p_sys;
445 if( p_oggpacket->bytes )
447 /* Copy Ogg packet to Speex bitstream */
448 speex_bits_read_from( &p_sys->bits, p_oggpacket->packet,
449 p_oggpacket->bytes );
450 p_sys->i_frame_in_packet = 0;
453 /* Decode one frame at a time */
454 if( p_sys->i_frame_in_packet < p_sys->p_header->frames_per_packet )
456 aout_buffer_t *p_aout_buffer;
460 p_dec->pf_aout_buffer_new( p_dec, p_sys->p_header->frame_size );
466 i_ret = speex_decode_int( p_sys->p_state, &p_sys->bits,
467 (int16_t *)p_aout_buffer->p_buffer );
476 msg_Warn( p_dec, "decoding error: corrupted stream?" );
480 if( speex_bits_remaining( &p_sys->bits ) < 0 )
482 msg_Warn( p_dec, "decoding overflow: corrupted stream?" );
485 if( p_sys->p_header->nb_channels == 2 )
486 speex_decode_stereo_int( (int16_t *)p_aout_buffer->p_buffer,
487 p_sys->p_header->frame_size,
490 /* Date management */
491 p_aout_buffer->start_date = aout_DateGet( &p_sys->end_date );
492 p_aout_buffer->end_date =
493 aout_DateIncrement( &p_sys->end_date, p_sys->p_header->frame_size);
495 p_sys->i_frame_in_packet++;
497 return p_aout_buffer;
505 /*****************************************************************************
506 * SendPacket: send an ogg packet to the stream output.
507 *****************************************************************************/
508 static block_t *SendPacket( decoder_t *p_dec, ogg_packet *p_oggpacket,
511 decoder_sys_t *p_sys = p_dec->p_sys;
513 /* Date management */
514 p_block->i_dts = p_block->i_pts = aout_DateGet( &p_sys->end_date );
516 if( p_sys->i_headers >= p_sys->p_header->extra_headers + 2 )
518 aout_DateIncrement( &p_sys->end_date,
519 p_sys->p_header->frame_size ) -
522 p_block->i_length = 0;
527 /*****************************************************************************
528 * ParseSpeexComments: FIXME should be done in demuxer
529 *****************************************************************************/
530 #define readint(buf, base) (((buf[base+3]<<24)&0xff000000)| \
531 ((buf[base+2]<<16)&0xff0000)| \
532 ((buf[base+1]<<8)&0xff00)| \
535 static void ParseSpeexComments( decoder_t *p_dec, ogg_packet *p_oggpacket )
537 input_thread_t *p_input = (input_thread_t *)p_dec->p_parent;
538 decoder_sys_t *p_sys = p_dec->p_sys;
540 char *p_buf = (char *)p_oggpacket->packet;
541 const SpeexMode *p_mode;
544 if( p_input->i_object_type != VLC_OBJECT_INPUT ) return;
546 p_mode = speex_mode_list[p_sys->p_header->mode];
548 input_Control( p_input, INPUT_ADD_INFO, _("Speex comment"), _("Mode"),
549 "%s%s", p_mode->modeName,
550 p_sys->p_header->vbr ? " VBR" : "" );
552 if( p_oggpacket->bytes < 8 )
554 msg_Warn( p_dec, "invalid/corrupted comments" );
558 i_len = readint( p_buf, 0 ); p_buf += 4;
559 if( i_len > p_oggpacket->bytes - 4 )
561 msg_Warn( p_dec, "invalid/corrupted comments" );
565 input_Control( p_input, INPUT_ADD_INFO, _("Speex comment"), p_buf, "" );
567 /* TODO: finish comments parsing */
570 /*****************************************************************************
571 * CloseDecoder: speex decoder destruction
572 *****************************************************************************/
573 static void CloseDecoder( vlc_object_t *p_this )
575 decoder_t * p_dec = (decoder_t *)p_this;
576 decoder_sys_t *p_sys = p_dec->p_sys;
580 speex_decoder_destroy( p_sys->p_state );
581 speex_bits_destroy( &p_sys->bits );
584 if( p_sys->p_header ) free( p_sys->p_header );
588 /*****************************************************************************
589 * encoder_sys_t: encoder descriptor
590 *****************************************************************************/
591 #define MAX_FRAME_SIZE 2000
592 #define MAX_FRAME_BYTES 2000
600 char p_buffer_out[MAX_FRAME_BYTES];
607 SpeexStereoState stereo;
610 int i_frames_per_packet;
611 int i_frames_in_packet;
623 /*****************************************************************************
624 * OpenEncoder: probe the encoder and return score
625 *****************************************************************************/
626 static int OpenEncoder( vlc_object_t *p_this )
628 encoder_t *p_enc = (encoder_t *)p_this;
629 encoder_sys_t *p_sys;
630 const SpeexMode *p_speex_mode = &speex_nb_mode;
636 if( p_enc->fmt_out.i_codec != VLC_FOURCC('s','p','x',' ') &&
642 /* Allocate the memory needed to store the decoder's structure */
643 if( ( p_sys = (encoder_sys_t *)malloc(sizeof(encoder_sys_t)) ) == NULL )
645 msg_Err( p_enc, "out of memory" );
648 p_enc->p_sys = p_sys;
649 p_enc->pf_encode_audio = Encode;
650 p_enc->fmt_in.i_codec = AOUT_FMT_S16_NE;
651 p_enc->fmt_out.i_codec = VLC_FOURCC('s','p','x',' ');
653 speex_init_header( &p_sys->header, p_enc->fmt_in.audio.i_rate,
656 p_sys->header.frames_per_packet = 1;
657 p_sys->header.vbr = 1;
658 p_sys->header.nb_channels = p_enc->fmt_in.audio.i_channels;
660 /* Create a new encoder state in narrowband mode */
661 p_sys->p_state = speex_encoder_init( p_speex_mode );
663 /* Set the quality to 8 (15 kbps) */
665 speex_encoder_ctl( p_sys->p_state, SPEEX_SET_QUALITY, &i_quality );
667 /*Initialization of the structure that holds the bits*/
668 speex_bits_init( &p_sys->bits );
670 p_sys->i_frames_in_packet = 0;
671 p_sys->i_samples_delay = 0;
674 speex_encoder_ctl( p_sys->p_state, SPEEX_GET_FRAME_SIZE,
675 &p_sys->i_frame_length );
677 p_sys->i_frame_size = p_sys->i_frame_length *
678 sizeof(int16_t) * p_enc->fmt_in.audio.i_channels;
679 p_sys->p_buffer = malloc( p_sys->i_frame_size );
681 /* Create and store headers */
682 pp_header[0] = speex_header_to_packet( &p_sys->header, &pi_header[0] );
683 pp_header[1] = "ENCODER=VLC media player";
684 pi_header[1] = sizeof("ENCODER=VLC media player");
686 p_enc->fmt_out.i_extra = 3 * 2 + pi_header[0] + pi_header[1];
687 p_extra = p_enc->fmt_out.p_extra = malloc( p_enc->fmt_out.i_extra );
688 for( i = 0; i < 2; i++ )
690 *(p_extra++) = pi_header[i] >> 8;
691 *(p_extra++) = pi_header[i] & 0xFF;
692 memcpy( p_extra, pp_header[i], pi_header[i] );
693 p_extra += pi_header[i];
696 msg_Dbg( p_enc, "encoding: frame size:%d, channels:%d, samplerate:%d",
697 p_sys->i_frame_size, p_enc->fmt_in.audio.i_channels,
698 p_enc->fmt_in.audio.i_rate );
703 /****************************************************************************
704 * Encode: the whole thing
705 ****************************************************************************
706 * This function spits out ogg packets.
707 ****************************************************************************/
708 static block_t *Encode( encoder_t *p_enc, aout_buffer_t *p_aout_buf )
710 encoder_sys_t *p_sys = p_enc->p_sys;
711 block_t *p_block, *p_chain = NULL;
713 char *p_buffer = p_aout_buf->p_buffer;
714 int i_samples = p_aout_buf->i_nb_samples;
715 int i_samples_delay = p_sys->i_samples_delay;
717 p_sys->i_pts = p_aout_buf->start_date -
718 (mtime_t)1000000 * (mtime_t)p_sys->i_samples_delay /
719 (mtime_t)p_enc->fmt_in.audio.i_rate;
721 p_sys->i_samples_delay += i_samples;
723 while( p_sys->i_samples_delay >= p_sys->i_frame_length )
728 if( i_samples_delay )
730 /* Take care of the left-over from last time */
731 int i_delay_size = i_samples_delay * 2 *
732 p_enc->fmt_in.audio.i_channels;
733 int i_size = p_sys->i_frame_size - i_delay_size;
735 p_samples = (int16_t *)p_sys->p_buffer;
736 memcpy( p_sys->p_buffer + i_delay_size, p_buffer, i_size );
737 p_buffer -= i_delay_size;
738 i_samples += i_samples_delay;
743 p_samples = (int16_t *)p_buffer;
746 /* Encode current frame */
747 if( p_enc->fmt_in.audio.i_channels == 2 )
748 speex_encode_stereo_int( p_samples, p_sys->i_frame_length,
752 if( p_sys->preprocess )
753 speex_preprocess( p_sys->preprocess, p_samples, NULL );
756 speex_encode_int( p_sys->p_state, p_samples, &p_sys->bits );
758 p_buffer += p_sys->i_frame_size;
759 p_sys->i_samples_delay -= p_sys->i_frame_length;
760 i_samples -= p_sys->i_frame_length;
762 p_sys->i_frames_in_packet++;
764 if( p_sys->i_frames_in_packet < p_sys->header.frames_per_packet )
767 p_sys->i_frames_in_packet = 0;
769 speex_bits_insert_terminator( &p_sys->bits );
770 i_out = speex_bits_write( &p_sys->bits, p_sys->p_buffer_out,
772 speex_bits_reset( &p_sys->bits );
774 p_block = block_New( p_enc, i_out );
775 memcpy( p_block->p_buffer, p_sys->p_buffer_out, i_out );
777 p_block->i_length = (mtime_t)1000000 *
778 (mtime_t)p_sys->i_frame_length * p_sys->header.frames_per_packet /
779 (mtime_t)p_enc->fmt_in.audio.i_rate;
781 p_block->i_dts = p_block->i_pts = p_sys->i_pts;
784 p_sys->i_pts += p_block->i_length;
785 block_ChainAppend( &p_chain, p_block );
789 /* Backup the remaining raw samples */
792 memcpy( p_sys->p_buffer + i_samples_delay * 2 *
793 p_enc->fmt_in.audio.i_channels, p_buffer,
794 i_samples * 2 * p_enc->fmt_in.audio.i_channels );
800 /*****************************************************************************
801 * CloseEncoder: encoder destruction
802 *****************************************************************************/
803 static void CloseEncoder( vlc_object_t *p_this )
805 encoder_t *p_enc = (encoder_t *)p_this;
806 encoder_sys_t *p_sys = p_enc->p_sys;
808 speex_encoder_destroy( p_sys->p_state );
809 speex_bits_destroy( &p_sys->bits );
811 if( p_sys->p_buffer ) free( p_sys->p_buffer );