]> git.sesse.net Git - vlc/blob - modules/codec/vorbis.c
all: sout_ParseCfg -> sout_CfgParse.
[vlc] / modules / codec / vorbis.c
1 /*****************************************************************************
2  * vorbis.c: vorbis decoder/encoder/packetizer module making use of libvorbis.
3  *****************************************************************************
4  * Copyright (C) 2001-2003 VideoLAN
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., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
22  *****************************************************************************/
23
24 /*****************************************************************************
25  * Preamble
26  *****************************************************************************/
27 #include <vlc/vlc.h>
28 #include <vlc/decoder.h>
29 #include <vlc/input.h>
30 #include <vlc/sout.h>
31
32 #include <ogg/ogg.h>
33
34 #ifdef MODULE_NAME_IS_tremor
35 #include <tremor/ivorbiscodec.h>
36
37 #else
38 #include <vorbis/codec.h>
39
40 /* vorbis header */
41 #ifdef HAVE_VORBIS_VORBISENC_H
42 #   include <vorbis/vorbisenc.h>
43 #   ifndef OV_ECTL_RATEMANAGE_AVG
44 #       define OV_ECTL_RATEMANAGE_AVG 0x0
45 #   endif
46 #endif
47
48 #endif
49
50 /*****************************************************************************
51  * decoder_sys_t : vorbis decoder descriptor
52  *****************************************************************************/
53 struct decoder_sys_t
54 {
55     /* Module mode */
56     vlc_bool_t b_packetizer;
57
58     /*
59      * Input properties
60      */
61     int i_headers;
62
63     /*
64      * Vorbis properties
65      */
66     vorbis_info      vi; /* struct that stores all the static vorbis bitstream
67                             settings */
68     vorbis_comment   vc; /* struct that stores all the bitstream user
69                           * comments */
70     vorbis_dsp_state vd; /* central working state for the packet->PCM
71                           * decoder */
72     vorbis_block     vb; /* local working space for packet->PCM decode */
73
74     /*
75      * Common properties
76      */
77     audio_date_t end_date;
78     int          i_last_block_size;
79
80 };
81
82 static int pi_channels_maps[7] =
83 {
84     0,
85     AOUT_CHAN_CENTER,
86     AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT,
87     AOUT_CHAN_CENTER | AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT,
88     AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_REARLEFT
89      | AOUT_CHAN_REARRIGHT,
90     AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_CENTER
91      | AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT,
92     AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_CENTER
93      | AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT | AOUT_CHAN_LFE
94 };
95
96 /****************************************************************************
97  * Local prototypes
98  ****************************************************************************/
99 static int  OpenDecoder   ( vlc_object_t * );
100 static int  OpenPacketizer( vlc_object_t * );
101 static void CloseDecoder  ( vlc_object_t * );
102 static void *DecodeBlock  ( decoder_t *, block_t ** );
103
104 static void *ProcessPacket ( decoder_t *, ogg_packet *, block_t ** );
105
106 static aout_buffer_t *DecodePacket  ( decoder_t *, ogg_packet * );
107 static block_t *SendPacket( decoder_t *, ogg_packet *, block_t * );
108
109 static void ParseVorbisComments( decoder_t * );
110
111 #ifdef MODULE_NAME_IS_tremor
112 static void Interleave   ( int32_t *, const int32_t **, int, int );
113 #else
114 static void Interleave   ( float *, const float **, int, int );
115 #endif
116
117 #ifndef MODULE_NAME_IS_tremor
118 static int OpenEncoder   ( vlc_object_t * );
119 static void CloseEncoder ( vlc_object_t * );
120 static block_t *Headers  ( encoder_t * );
121 static block_t *Encode   ( encoder_t *, aout_buffer_t * );
122 #endif
123
124 /*****************************************************************************
125  * Module descriptor
126  *****************************************************************************/
127 #define ENC_QUALITY_TEXT N_("Encoding quality")
128 #define ENC_QUALITY_LONGTEXT N_( \
129   "Allows you to specify a quality between 1 (low) and 10 (high), instead " \
130   "of specifying a particular bitrate. This will produce a VBR stream." )
131 #define ENC_MAXBR_TEXT N_("Maximum encoding bitrate")
132 #define ENC_MAXBR_LONGTEXT N_( \
133   "Allows you to specify a maximum bitrate in kbps. " \
134   "Useful for streaming applications." )
135 #define ENC_MINBR_TEXT N_("Minimum encoding bitrate")
136 #define ENC_MINBR_LONGTEXT N_( \
137   "Allows you to specify a minimum bitrate in kbps. " \
138   "Useful for encoding for a fixed-size channel." )
139
140 vlc_module_begin();
141
142     set_description( _("Vorbis audio decoder") );
143 #ifdef MODULE_NAME_IS_tremor
144     set_capability( "decoder", 90 );
145 #else
146     set_capability( "decoder", 100 );
147 #endif
148     set_callbacks( OpenDecoder, CloseDecoder );
149
150     add_submodule();
151     set_description( _("Vorbis audio packetizer") );
152     set_capability( "packetizer", 100 );
153     set_callbacks( OpenPacketizer, CloseDecoder );
154
155 #ifndef MODULE_NAME_IS_tremor
156 #   define ENC_CFG_PREFIX "sout-vorbis-"
157     add_submodule();
158     set_description( _("Vorbis audio encoder") );
159     set_capability( "encoder", 100 );
160     set_callbacks( OpenEncoder, CloseEncoder );
161
162     add_integer( ENC_CFG_PREFIX "quality", 0, NULL, ENC_QUALITY_TEXT,
163                  ENC_QUALITY_LONGTEXT, VLC_FALSE );
164     add_integer( ENC_CFG_PREFIX "max-bitrate", 0, NULL, ENC_MAXBR_TEXT,
165                  ENC_MAXBR_LONGTEXT, VLC_FALSE );
166     add_integer( ENC_CFG_PREFIX "min-bitrate", 0, NULL, ENC_MINBR_TEXT,
167                  ENC_MINBR_LONGTEXT, VLC_FALSE );
168 #endif
169
170 vlc_module_end();
171
172 #ifndef MODULE_NAME_IS_tremor
173 static const char *ppsz_enc_options[] = {
174     "quality", "max-bitrate", "min-bitrate", NULL
175 };
176 #endif
177
178 /*****************************************************************************
179  * OpenDecoder: probe the decoder and return score
180  *****************************************************************************/
181 static int OpenDecoder( vlc_object_t *p_this )
182 {
183     decoder_t *p_dec = (decoder_t*)p_this;
184     decoder_sys_t *p_sys;
185
186     if( p_dec->fmt_in.i_codec != VLC_FOURCC('v','o','r','b') )
187     {
188         return VLC_EGENERIC;
189     }
190
191     /* Allocate the memory needed to store the decoder's structure */
192     if( ( p_dec->p_sys = p_sys =
193           (decoder_sys_t *)malloc(sizeof(decoder_sys_t)) ) == NULL )
194     {
195         msg_Err( p_dec, "out of memory" );
196         return VLC_EGENERIC;
197     }
198
199     /* Misc init */
200     aout_DateSet( &p_sys->end_date, 0 );
201     p_sys->b_packetizer = VLC_FALSE;
202     p_sys->i_headers = 0;
203
204     /* Take care of vorbis init */
205     vorbis_info_init( &p_sys->vi );
206     vorbis_comment_init( &p_sys->vc );
207
208     /* Set output properties */
209     p_dec->fmt_out.i_cat = AUDIO_ES;
210 #ifdef MODULE_NAME_IS_tremor
211     p_dec->fmt_out.i_codec = VLC_FOURCC('f','i','3','2');
212 #else
213     p_dec->fmt_out.i_codec = VLC_FOURCC('f','l','3','2');
214 #endif
215
216     /* Set callbacks */
217     p_dec->pf_decode_audio = (aout_buffer_t *(*)(decoder_t *, block_t **))
218         DecodeBlock;
219     p_dec->pf_packetize    = (block_t *(*)(decoder_t *, block_t **))
220         DecodeBlock;
221
222     return VLC_SUCCESS;
223 }
224
225 static int OpenPacketizer( vlc_object_t *p_this )
226 {
227     decoder_t *p_dec = (decoder_t*)p_this;
228
229     int i_ret = OpenDecoder( p_this );
230
231     if( i_ret == VLC_SUCCESS )
232     {
233         p_dec->p_sys->b_packetizer = VLC_TRUE;
234         p_dec->fmt_out.i_codec = VLC_FOURCC('v','o','r','b');
235     }
236
237     return i_ret;
238 }
239
240 /****************************************************************************
241  * DecodeBlock: the whole thing
242  ****************************************************************************
243  * This function must be fed with ogg packets.
244  ****************************************************************************/
245 static void *DecodeBlock( decoder_t *p_dec, block_t **pp_block )
246 {
247     decoder_sys_t *p_sys = p_dec->p_sys;
248     ogg_packet oggpacket;
249
250     if( !pp_block ) return NULL;
251
252     if( *pp_block )
253     {
254         /* Block to Ogg packet */
255         oggpacket.packet = (*pp_block)->p_buffer;
256         oggpacket.bytes = (*pp_block)->i_buffer;
257     }
258     else
259     {
260         if( p_sys->b_packetizer ) return NULL;
261
262         /* Block to Ogg packet */
263         oggpacket.packet = NULL;
264         oggpacket.bytes = 0;
265     }
266
267     oggpacket.granulepos = -1;
268     oggpacket.b_o_s = 0;
269     oggpacket.e_o_s = 0;
270     oggpacket.packetno = 0;
271
272     if( p_sys->i_headers == 0 )
273     {
274         /* Take care of the initial Vorbis header */
275
276         oggpacket.b_o_s = 1; /* yes this actually is a b_o_s packet :) */
277         if( vorbis_synthesis_headerin( &p_sys->vi, &p_sys->vc,
278                                        &oggpacket ) < 0 )
279         {
280             msg_Err( p_dec, "this bitstream does not contain Vorbis "
281                      "audio data.");
282             block_Release( *pp_block );
283             return NULL;
284         }
285         p_sys->i_headers++;
286
287         /* Setup the format */
288         p_dec->fmt_out.audio.i_rate     = p_sys->vi.rate;
289         p_dec->fmt_out.audio.i_channels = p_sys->vi.channels;
290         p_dec->fmt_out.audio.i_physical_channels =
291             p_dec->fmt_out.audio.i_original_channels =
292                 pi_channels_maps[p_sys->vi.channels];
293         p_dec->fmt_out.i_bitrate = p_sys->vi.bitrate_nominal;
294
295         aout_DateInit( &p_sys->end_date, p_sys->vi.rate );
296
297         msg_Dbg( p_dec, "channels:%d samplerate:%ld bitrate:%ld",
298                  p_sys->vi.channels, p_sys->vi.rate,
299                  p_sys->vi.bitrate_nominal );
300
301         return ProcessPacket( p_dec, &oggpacket, pp_block );
302     }
303
304     if( p_sys->i_headers == 1 )
305     {
306         /* The next packet in order is the comments header */
307         if( vorbis_synthesis_headerin( &p_sys->vi, &p_sys->vc, &oggpacket )
308             < 0 )
309         {
310             msg_Err( p_dec, "2nd Vorbis header is corrupted" );
311             block_Release( *pp_block );
312             return NULL;
313         }
314         p_sys->i_headers++;
315
316         ParseVorbisComments( p_dec );
317
318         return ProcessPacket( p_dec, &oggpacket, pp_block );
319     }
320
321     if( p_sys->i_headers == 2 )
322     {
323         /* The next packet in order is the codebooks header
324            We need to watch out that this packet is not missing as a
325            missing or corrupted header is fatal. */
326         if( vorbis_synthesis_headerin( &p_sys->vi, &p_sys->vc, &oggpacket )
327             < 0 )
328         {
329             msg_Err( p_dec, "3rd Vorbis header is corrupted" );
330             block_Release( *pp_block );
331             return NULL;
332         }
333         p_sys->i_headers++;
334
335         if( !p_sys->b_packetizer )
336         {
337             /* Initialize the Vorbis packet->PCM decoder */
338             vorbis_synthesis_init( &p_sys->vd, &p_sys->vi );
339             vorbis_block_init( &p_sys->vd, &p_sys->vb );
340         }
341
342         return ProcessPacket( p_dec, &oggpacket, pp_block );
343     }
344
345     return ProcessPacket( p_dec, &oggpacket, pp_block );
346 }
347
348 /*****************************************************************************
349  * ProcessPacket: processes a Vorbis packet.
350  *****************************************************************************/
351 static void *ProcessPacket( decoder_t *p_dec, ogg_packet *p_oggpacket,
352                             block_t **pp_block )
353 {
354     decoder_sys_t *p_sys = p_dec->p_sys;
355     block_t *p_block = *pp_block;
356
357     /* Date management */
358     if( p_block && p_block->i_pts > 0 &&
359         p_block->i_pts != aout_DateGet( &p_sys->end_date ) )
360     {
361         aout_DateSet( &p_sys->end_date, p_block->i_pts );
362     }
363
364     if( !aout_DateGet( &p_sys->end_date ) )
365     {
366         /* We've just started the stream, wait for the first PTS. */
367         if( p_block ) block_Release( p_block );
368         return NULL;
369     }
370
371     *pp_block = NULL; /* To avoid being fed the same packet again */
372
373     if( p_sys->b_packetizer )
374     {
375         return SendPacket( p_dec, p_oggpacket, p_block );
376     }
377     else
378     {
379         aout_buffer_t *p_aout_buffer;
380
381         if( p_sys->i_headers >= 3 )
382             p_aout_buffer = DecodePacket( p_dec, p_oggpacket );
383         else
384             p_aout_buffer = NULL;
385
386         if( p_block )
387         {
388             block_Release( p_block );
389         }
390         return p_aout_buffer;
391     }
392 }
393
394 /*****************************************************************************
395  * DecodePacket: decodes a Vorbis packet.
396  *****************************************************************************/
397 static aout_buffer_t *DecodePacket( decoder_t *p_dec, ogg_packet *p_oggpacket )
398 {
399     decoder_sys_t *p_sys = p_dec->p_sys;
400     int           i_samples;
401
402 #ifdef MODULE_NAME_IS_tremor
403     int32_t       **pp_pcm;
404 #else
405     float         **pp_pcm;
406 #endif
407
408     if( p_oggpacket->bytes &&
409         vorbis_synthesis( &p_sys->vb, p_oggpacket ) == 0 )
410         vorbis_synthesis_blockin( &p_sys->vd, &p_sys->vb );
411
412     /* **pp_pcm is a multichannel float vector. In stereo, for
413      * example, pp_pcm[0] is left, and pp_pcm[1] is right. i_samples is
414      * the size of each channel. Convert the float values
415      * (-1.<=range<=1.) to whatever PCM format and write it out */
416
417     if( ( i_samples = vorbis_synthesis_pcmout( &p_sys->vd, &pp_pcm ) ) > 0 )
418     {
419
420         aout_buffer_t *p_aout_buffer;
421
422         p_aout_buffer =
423             p_dec->pf_aout_buffer_new( p_dec, i_samples );
424
425         if( p_aout_buffer == NULL ) return NULL;
426
427         /* Interleave the samples */
428 #ifdef MODULE_NAME_IS_tremor
429         Interleave( (int32_t *)p_aout_buffer->p_buffer,
430                     (const int32_t **)pp_pcm, p_sys->vi.channels, i_samples );
431 #else
432         Interleave( (float *)p_aout_buffer->p_buffer,
433                     (const float **)pp_pcm, p_sys->vi.channels, i_samples );
434 #endif
435
436         /* Tell libvorbis how many samples we actually consumed */
437         vorbis_synthesis_read( &p_sys->vd, i_samples );
438
439         /* Date management */
440         p_aout_buffer->start_date = aout_DateGet( &p_sys->end_date );
441         p_aout_buffer->end_date = aout_DateIncrement( &p_sys->end_date,
442                                                       i_samples );
443         return p_aout_buffer;
444     }
445     else
446     {
447         return NULL;
448     }
449 }
450
451 /*****************************************************************************
452  * SendPacket: send an ogg dated packet to the stream output.
453  *****************************************************************************/
454 static block_t *SendPacket( decoder_t *p_dec, ogg_packet *p_oggpacket,
455                             block_t *p_block )
456 {
457     decoder_sys_t *p_sys = p_dec->p_sys;
458     int i_block_size, i_samples;
459
460     i_block_size = vorbis_packet_blocksize( &p_sys->vi, p_oggpacket );
461     if( i_block_size < 0 ) i_block_size = 0; /* non audio packet */
462     i_samples = ( p_sys->i_last_block_size + i_block_size ) >> 2;
463     p_sys->i_last_block_size = i_block_size;
464
465     /* Date management */
466     p_block->i_dts = p_block->i_pts = aout_DateGet( &p_sys->end_date );
467
468     if( p_sys->i_headers >= 3 )
469         p_block->i_length = aout_DateIncrement( &p_sys->end_date, i_samples ) -
470             p_block->i_pts;
471     else
472         p_block->i_length = 0;
473
474     return p_block;
475 }
476
477 /*****************************************************************************
478  * ParseVorbisComments: FIXME should be done in demuxer
479  *****************************************************************************/
480 static void ParseVorbisComments( decoder_t *p_dec )
481 {
482     input_thread_t *p_input = (input_thread_t *)p_dec->p_parent;
483     int i = 0;
484     char *psz_name, *psz_value, *psz_comment;
485     while ( i < p_dec->p_sys->vc.comments )
486     {
487         psz_comment = strdup( p_dec->p_sys->vc.user_comments[i] );
488         if( !psz_comment )
489         {
490             msg_Warn( p_dec, "out of memory" );
491             break;
492         }
493         psz_name = psz_comment;
494         psz_value = strchr( psz_comment, '=' );
495         if( psz_value )
496         {
497             *psz_value = '\0';
498             psz_value++;
499             input_Control( p_input, INPUT_ADD_INFO, _("Vorbis comment"),
500                            psz_name, psz_value );
501         }
502         free( psz_comment );
503         i++;
504     }
505 }
506
507 /*****************************************************************************
508  * Interleave: helper function to interleave channels
509  *****************************************************************************/
510 static void Interleave(
511 #ifdef MODULE_NAME_IS_tremor
512                         int32_t *p_out, const int32_t **pp_in,
513 #else
514                         float *p_out, const float **pp_in,
515 #endif
516                         int i_nb_channels, int i_samples )
517 {
518     int i, j;
519
520     for ( j = 0; j < i_samples; j++ )
521     {
522         for ( i = 0; i < i_nb_channels; i++ )
523         {
524             p_out[j * i_nb_channels + i] = pp_in[i][j];
525         }
526     }
527 }
528
529 /*****************************************************************************
530  * CloseDecoder: vorbis decoder destruction
531  *****************************************************************************/
532 static void CloseDecoder( vlc_object_t *p_this )
533 {
534     decoder_t *p_dec = (decoder_t *)p_this;
535     decoder_sys_t *p_sys = p_dec->p_sys;
536
537     if( !p_sys->b_packetizer && p_sys->i_headers >= 3 )
538     {
539         vorbis_block_clear( &p_sys->vb );
540         vorbis_dsp_clear( &p_sys->vd );
541     }
542
543     vorbis_comment_clear( &p_sys->vc );
544     vorbis_info_clear( &p_sys->vi );  /* must be called last */
545
546     free( p_sys );
547 }
548
549 #if defined(HAVE_VORBIS_VORBISENC_H) && !defined(MODULE_NAME_IS_tremor)
550
551 /*****************************************************************************
552  * encoder_sys_t : theora encoder descriptor
553  *****************************************************************************/
554 struct encoder_sys_t
555 {
556     /*
557      * Input properties
558      */
559     int i_headers;
560
561     /*
562      * Vorbis properties
563      */
564     vorbis_info      vi; /* struct that stores all the static vorbis bitstream
565                             settings */
566     vorbis_comment   vc; /* struct that stores all the bitstream user
567                           * comments */
568     vorbis_dsp_state vd; /* central working state for the packet->PCM
569                           * decoder */
570     vorbis_block     vb; /* local working space for packet->PCM decode */
571
572     int i_last_block_size;
573     int i_samples_delay;
574     int i_channels;
575
576     /*
577      * Common properties
578      */
579     mtime_t i_pts;
580 };
581
582 /*****************************************************************************
583  * OpenEncoder: probe the encoder and return score
584  *****************************************************************************/
585 static int OpenEncoder( vlc_object_t *p_this )
586 {
587     encoder_t *p_enc = (encoder_t *)p_this;
588     encoder_sys_t *p_sys;
589     int i_quality, i_min_bitrate, i_max_bitrate;
590     vlc_value_t val;
591
592     if( p_enc->fmt_out.i_codec != VLC_FOURCC('v','o','r','b') &&
593         !p_enc->b_force )
594     {
595         return VLC_EGENERIC;
596     }
597
598     /* Allocate the memory needed to store the decoder's structure */
599     if( ( p_sys = (encoder_sys_t *)malloc(sizeof(encoder_sys_t)) ) == NULL )
600     {
601         msg_Err( p_enc, "out of memory" );
602         return VLC_EGENERIC;
603     }
604     p_enc->p_sys = p_sys;
605
606     p_enc->pf_header = Headers;
607     p_enc->pf_encode_audio = Encode;
608     p_enc->fmt_in.i_codec = VLC_FOURCC('f','l','3','2');
609     p_enc->fmt_out.i_codec = VLC_FOURCC('v','o','r','b');
610
611     sout_CfgParse( p_enc, ENC_CFG_PREFIX, ppsz_enc_options, p_enc->p_cfg );
612
613     var_Get( p_enc, ENC_CFG_PREFIX "quality", &val );
614     i_quality = val.i_int;
615     if( i_quality > 10 ) i_quality = 10;
616     if( i_quality < 0 ) i_quality = 0;
617     var_Get( p_enc, ENC_CFG_PREFIX "max-bitrate", &val );
618     i_max_bitrate = val.i_int;
619     var_Get( p_enc, ENC_CFG_PREFIX "min-bitrate", &val );
620     i_min_bitrate = val.i_int;
621
622     /* Initialize vorbis encoder */
623     vorbis_info_init( &p_sys->vi );
624
625     if( i_quality > 0 )
626     {
627         /* VBR mode */
628         if( vorbis_encode_setup_vbr( &p_sys->vi,
629               p_enc->fmt_in.audio.i_channels, p_enc->fmt_in.audio.i_rate,
630               i_quality * 0.1 ) )
631         {
632             vorbis_info_clear( &p_sys->vi );
633             free( p_enc->p_sys );
634             msg_Err( p_enc, "VBR mode initialisation failed" );
635             return VLC_EGENERIC;
636         }
637
638         /* Do we have optional hard quality restrictions? */
639         if( i_max_bitrate > 0 || i_min_bitrate > 0 )
640         {
641             struct ovectl_ratemanage_arg ai;
642             vorbis_encode_ctl( &p_sys->vi, OV_ECTL_RATEMANAGE_GET, &ai );
643
644             ai.bitrate_hard_min = i_min_bitrate;
645             ai.bitrate_hard_max = i_max_bitrate;
646             ai.management_active = 1;
647
648             vorbis_encode_ctl( &p_sys->vi, OV_ECTL_RATEMANAGE_SET, &ai );
649
650         }
651         else
652         {
653             /* Turn off management entirely */
654             vorbis_encode_ctl( &p_sys->vi, OV_ECTL_RATEMANAGE_SET, NULL );
655         }
656     }
657     else
658     {
659         if( vorbis_encode_setup_managed( &p_sys->vi,
660               p_enc->fmt_in.audio.i_channels, p_enc->fmt_in.audio.i_rate,
661               i_min_bitrate > 0 ? i_min_bitrate * 1000: -1,
662               p_enc->fmt_out.i_bitrate,
663               i_max_bitrate > 0 ? i_max_bitrate * 1000: -1 ) )
664           {
665               vorbis_info_clear( &p_sys->vi );
666               msg_Err( p_enc, "CBR mode initialisation failed" );
667               free( p_enc->p_sys );
668               return VLC_EGENERIC;
669           }
670     }
671
672     vorbis_encode_setup_init( &p_sys->vi );
673
674     /* add a comment */
675     vorbis_comment_init( &p_sys->vc);
676     vorbis_comment_add_tag( &p_sys->vc, "ENCODER", "VLC media player");
677
678     /* set up the analysis state and auxiliary encoding storage */
679     vorbis_analysis_init( &p_sys->vd, &p_sys->vi );
680     vorbis_block_init( &p_sys->vd, &p_sys->vb );
681
682     p_sys->i_channels = p_enc->fmt_in.audio.i_channels;
683     p_sys->i_last_block_size = 0;
684     p_sys->i_samples_delay = 0;
685     p_sys->i_headers = 0;
686     p_sys->i_pts = 0;
687
688     return VLC_SUCCESS;
689 }
690
691 /****************************************************************************
692  * Encode: the whole thing
693  ****************************************************************************
694  * This function spits out ogg packets.
695  ****************************************************************************/
696 static block_t *Headers( encoder_t *p_enc )
697 {
698     encoder_sys_t *p_sys = p_enc->p_sys;
699     block_t *p_block, *p_chain = NULL;
700
701     /* Create theora headers */
702     if( !p_sys->i_headers )
703     {
704         ogg_packet header[3];
705         int i;
706
707         vorbis_analysis_headerout( &p_sys->vd, &p_sys->vc,
708                                    &header[0], &header[1], &header[2]);
709         for( i = 0; i < 3; i++ )
710         {
711             p_block = block_New( p_enc, header[i].bytes );
712             memcpy( p_block->p_buffer, header[i].packet, header[i].bytes );
713
714             p_block->i_dts = p_block->i_pts = p_block->i_length = 0;
715
716             block_ChainAppend( &p_chain, p_block );
717         }
718         p_sys->i_headers = 3;
719     }
720
721     return p_chain;
722 }
723
724 /****************************************************************************
725  * Encode: the whole thing
726  ****************************************************************************
727  * This function spits out ogg packets.
728  ****************************************************************************/
729 static block_t *Encode( encoder_t *p_enc, aout_buffer_t *p_aout_buf )
730 {
731     encoder_sys_t *p_sys = p_enc->p_sys;
732     ogg_packet oggpacket;
733     block_t *p_block, *p_chain = NULL;
734     float **buffer;
735     int i;
736     unsigned int j;
737
738     p_sys->i_pts = p_aout_buf->start_date -
739                 (mtime_t)1000000 * (mtime_t)p_sys->i_samples_delay /
740                 (mtime_t)p_enc->fmt_in.audio.i_rate;
741
742     p_sys->i_samples_delay += p_aout_buf->i_nb_samples;
743
744     buffer = vorbis_analysis_buffer( &p_sys->vd, p_aout_buf->i_nb_samples );
745
746     /* convert samples to float and uninterleave */
747     for( i = 0; i < p_sys->i_channels; i++ )
748     {
749         for( j = 0 ; j < p_aout_buf->i_nb_samples ; j++ )
750         {
751             buffer[i][j]= ((float)( ((int16_t *)p_aout_buf->p_buffer )
752                                     [j * p_sys->i_channels + i ] )) / 32768.f;
753         }
754     }
755
756     vorbis_analysis_wrote( &p_sys->vd, p_aout_buf->i_nb_samples );
757
758     while( vorbis_analysis_blockout( &p_sys->vd, &p_sys->vb ) == 1 )
759     {
760         int i_samples;
761
762         vorbis_analysis( &p_sys->vb, NULL );
763         vorbis_bitrate_addblock( &p_sys->vb );
764
765         while( vorbis_bitrate_flushpacket( &p_sys->vd, &oggpacket ) )
766         {
767             int i_block_size;
768             p_block = block_New( p_enc, oggpacket.bytes );
769             memcpy( p_block->p_buffer, oggpacket.packet, oggpacket.bytes );
770
771             i_block_size = vorbis_packet_blocksize( &p_sys->vi, &oggpacket );
772
773             if( i_block_size < 0 ) i_block_size = 0;
774             i_samples = ( p_sys->i_last_block_size + i_block_size ) >> 2;
775             p_sys->i_last_block_size = i_block_size;
776
777             p_block->i_length = (mtime_t)1000000 *
778                 (mtime_t)i_samples / (mtime_t)p_enc->fmt_in.audio.i_rate;
779
780             p_block->i_dts = p_block->i_pts = p_sys->i_pts;
781
782             p_sys->i_samples_delay -= i_samples;
783
784             /* Update pts */
785             p_sys->i_pts += p_block->i_length;
786             block_ChainAppend( &p_chain, p_block );
787         }
788     }
789
790     return p_chain;
791 }
792
793 /*****************************************************************************
794  * CloseEncoder: theora encoder destruction
795  *****************************************************************************/
796 static void CloseEncoder( vlc_object_t *p_this )
797 {
798     encoder_t *p_enc = (encoder_t *)p_this;
799     encoder_sys_t *p_sys = p_enc->p_sys;
800
801     vorbis_block_clear( &p_sys->vb );
802     vorbis_dsp_clear( &p_sys->vd );
803     vorbis_comment_clear( &p_sys->vc );
804     vorbis_info_clear( &p_sys->vi );  /* must be called last */
805
806     free( p_sys );
807 }
808
809 #endif /* HAVE_VORBIS_VORBISENC_H && !MODULE_NAME_IS_tremor */