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