]> git.sesse.net Git - vlc/blob - modules/codec/vorbis.c
* modules/codec/vorbis.c: vorbis encoder takes float32 as input.
[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 int  ProcessHeaders( decoder_t * );
105 static void *ProcessPacket ( decoder_t *, ogg_packet *, block_t ** );
106
107 static aout_buffer_t *DecodePacket  ( decoder_t *, ogg_packet * );
108 static block_t *SendPacket( decoder_t *, ogg_packet *, block_t * );
109
110 static void ParseVorbisComments( decoder_t * );
111
112 #ifdef MODULE_NAME_IS_tremor
113 static void Interleave   ( int32_t *, const int32_t **, int, int );
114 #else
115 static void Interleave   ( float *, const float **, int, int );
116 #endif
117
118 #ifndef MODULE_NAME_IS_tremor
119 static int OpenEncoder   ( vlc_object_t * );
120 static void CloseEncoder ( vlc_object_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     /* Check for headers */
273     if( p_sys->i_headers == 0 && p_dec->fmt_in.i_extra )
274     {
275         /* Headers already available as extra data */
276         p_sys->i_headers = 3;
277     }
278     else if( oggpacket.bytes && p_sys->i_headers < 3 )
279     {
280         /* Backup headers as extra data */
281         uint8_t *p_extra;
282
283         p_dec->fmt_in.p_extra =
284             realloc( p_dec->fmt_in.p_extra, p_dec->fmt_in.i_extra +
285                      oggpacket.bytes + 2 );
286         p_extra = p_dec->fmt_in.p_extra + p_dec->fmt_in.i_extra;
287         *(p_extra++) = oggpacket.bytes >> 8;
288         *(p_extra++) = oggpacket.bytes & 0xFF;
289
290         memcpy( p_extra, oggpacket.packet, oggpacket.bytes );
291         p_dec->fmt_in.i_extra += oggpacket.bytes + 2;
292
293         block_Release( *pp_block );
294         p_sys->i_headers++;
295         return NULL;
296     }
297
298     if( p_sys->i_headers == 3 )
299     {
300         if( ProcessHeaders( p_dec ) != VLC_SUCCESS )
301         {
302             p_sys->i_headers = 0;
303             p_dec->fmt_in.i_extra = 0;
304             block_Release( *pp_block );
305             return NULL;
306         }
307         else p_sys->i_headers++;
308     }
309
310     return ProcessPacket( p_dec, &oggpacket, pp_block );
311 }
312
313 /*****************************************************************************
314  * ProcessHeaders: process Vorbis headers.
315  *****************************************************************************/
316 static int ProcessHeaders( decoder_t *p_dec )
317 {
318     decoder_sys_t *p_sys = p_dec->p_sys;
319     ogg_packet oggpacket;
320     uint8_t *p_extra;
321     int i_extra;
322
323     if( !p_dec->fmt_in.i_extra ) return VLC_EGENERIC;
324
325     oggpacket.granulepos = -1;
326     oggpacket.b_o_s = 1; /* yes this actually is a b_o_s packet :) */
327     oggpacket.e_o_s = 0;
328     oggpacket.packetno = 0;
329     p_extra = p_dec->fmt_in.p_extra;
330     i_extra = p_dec->fmt_in.i_extra;
331
332     /* Take care of the initial Vorbis header */
333     oggpacket.bytes = *(p_extra++) << 8;
334     oggpacket.bytes |= (*(p_extra++) & 0xFF);
335     oggpacket.packet = p_extra;
336     p_extra += oggpacket.bytes;
337     i_extra -= (oggpacket.bytes + 2);
338     if( i_extra < 0 )
339     {
340         msg_Err( p_dec, "header data corrupted");
341         return VLC_EGENERIC;
342     }
343
344     if( vorbis_synthesis_headerin( &p_sys->vi, &p_sys->vc, &oggpacket ) < 0 )
345     {
346         msg_Err( p_dec, "this bitstream does not contain Vorbis audio data");
347         return VLC_EGENERIC;
348     }
349
350     /* Setup the format */
351     p_dec->fmt_out.audio.i_rate     = p_sys->vi.rate;
352     p_dec->fmt_out.audio.i_channels = p_sys->vi.channels;
353     p_dec->fmt_out.audio.i_physical_channels =
354         p_dec->fmt_out.audio.i_original_channels =
355             pi_channels_maps[p_sys->vi.channels];
356     p_dec->fmt_out.i_bitrate = p_sys->vi.bitrate_nominal;
357
358     aout_DateInit( &p_sys->end_date, p_sys->vi.rate );
359     aout_DateSet( &p_sys->end_date, 0 );
360
361     msg_Dbg( p_dec, "channels:%d samplerate:%ld bitrate:%ld",
362              p_sys->vi.channels, p_sys->vi.rate, p_sys->vi.bitrate_nominal );
363
364     /* The next packet in order is the comments header */
365     oggpacket.b_o_s = 0;
366     oggpacket.bytes = *(p_extra++) << 8;
367     oggpacket.bytes |= (*(p_extra++) & 0xFF);
368     oggpacket.packet = p_extra;
369     p_extra += oggpacket.bytes;
370     i_extra -= (oggpacket.bytes + 2);
371     if( i_extra < 0 )
372     {
373         msg_Err( p_dec, "header data corrupted");
374         return VLC_EGENERIC;
375     }
376
377     if( vorbis_synthesis_headerin( &p_sys->vi, &p_sys->vc, &oggpacket ) < 0 )
378     {
379         msg_Err( p_dec, "2nd Vorbis header is corrupted" );
380         return VLC_EGENERIC;
381     }
382     ParseVorbisComments( p_dec );
383
384     /* The next packet in order is the codebooks header
385      * We need to watch out that this packet is not missing as a
386      * missing or corrupted header is fatal. */
387     oggpacket.bytes = *(p_extra++) << 8;
388     oggpacket.bytes |= (*(p_extra++) & 0xFF);
389     oggpacket.packet = p_extra;
390     i_extra -= (oggpacket.bytes + 2);
391     if( i_extra < 0 )
392     {
393         msg_Err( p_dec, "header data corrupted");
394         return VLC_EGENERIC;
395     }
396
397     if( vorbis_synthesis_headerin( &p_sys->vi, &p_sys->vc, &oggpacket ) < 0 )
398     {
399         msg_Err( p_dec, "3rd Vorbis header is corrupted" );
400         return VLC_EGENERIC;
401     }
402
403     if( !p_sys->b_packetizer )
404     {
405         /* Initialize the Vorbis packet->PCM decoder */
406         vorbis_synthesis_init( &p_sys->vd, &p_sys->vi );
407         vorbis_block_init( &p_sys->vd, &p_sys->vb );
408     }
409     else
410     {
411         p_dec->fmt_out.i_extra = p_dec->fmt_in.i_extra;
412         p_dec->fmt_out.p_extra =
413             realloc( p_dec->fmt_out.p_extra, p_dec->fmt_out.i_extra );
414         memcpy( p_dec->fmt_out.p_extra,
415                 p_dec->fmt_in.p_extra, p_dec->fmt_out.i_extra );
416     }
417
418     return VLC_SUCCESS;
419 }
420
421 /*****************************************************************************
422  * ProcessPacket: processes a Vorbis packet.
423  *****************************************************************************/
424 static void *ProcessPacket( decoder_t *p_dec, ogg_packet *p_oggpacket,
425                             block_t **pp_block )
426 {
427     decoder_sys_t *p_sys = p_dec->p_sys;
428     block_t *p_block = *pp_block;
429
430     /* Date management */
431     if( p_block && p_block->i_pts > 0 &&
432         p_block->i_pts != aout_DateGet( &p_sys->end_date ) )
433     {
434         aout_DateSet( &p_sys->end_date, p_block->i_pts );
435     }
436
437     if( !aout_DateGet( &p_sys->end_date ) )
438     {
439         /* We've just started the stream, wait for the first PTS. */
440         if( p_block ) block_Release( p_block );
441         return NULL;
442     }
443
444     *pp_block = NULL; /* To avoid being fed the same packet again */
445
446     if( p_sys->b_packetizer )
447     {
448         return SendPacket( p_dec, p_oggpacket, p_block );
449     }
450     else
451     {
452         aout_buffer_t *p_aout_buffer;
453
454         if( p_sys->i_headers >= 3 )
455             p_aout_buffer = DecodePacket( p_dec, p_oggpacket );
456         else
457             p_aout_buffer = NULL;
458
459         if( p_block ) block_Release( p_block );
460         return p_aout_buffer;
461     }
462 }
463
464 /*****************************************************************************
465  * DecodePacket: decodes a Vorbis packet.
466  *****************************************************************************/
467 static aout_buffer_t *DecodePacket( decoder_t *p_dec, ogg_packet *p_oggpacket )
468 {
469     decoder_sys_t *p_sys = p_dec->p_sys;
470     int           i_samples;
471
472 #ifdef MODULE_NAME_IS_tremor
473     int32_t       **pp_pcm;
474 #else
475     float         **pp_pcm;
476 #endif
477
478     if( p_oggpacket->bytes &&
479         vorbis_synthesis( &p_sys->vb, p_oggpacket ) == 0 )
480         vorbis_synthesis_blockin( &p_sys->vd, &p_sys->vb );
481
482     /* **pp_pcm is a multichannel float vector. In stereo, for
483      * example, pp_pcm[0] is left, and pp_pcm[1] is right. i_samples is
484      * the size of each channel. Convert the float values
485      * (-1.<=range<=1.) to whatever PCM format and write it out */
486
487     if( ( i_samples = vorbis_synthesis_pcmout( &p_sys->vd, &pp_pcm ) ) > 0 )
488     {
489
490         aout_buffer_t *p_aout_buffer;
491
492         p_aout_buffer =
493             p_dec->pf_aout_buffer_new( p_dec, i_samples );
494
495         if( p_aout_buffer == NULL ) return NULL;
496
497         /* Interleave the samples */
498 #ifdef MODULE_NAME_IS_tremor
499         Interleave( (int32_t *)p_aout_buffer->p_buffer,
500                     (const int32_t **)pp_pcm, p_sys->vi.channels, i_samples );
501 #else
502         Interleave( (float *)p_aout_buffer->p_buffer,
503                     (const float **)pp_pcm, p_sys->vi.channels, i_samples );
504 #endif
505
506         /* Tell libvorbis how many samples we actually consumed */
507         vorbis_synthesis_read( &p_sys->vd, i_samples );
508
509         /* Date management */
510         p_aout_buffer->start_date = aout_DateGet( &p_sys->end_date );
511         p_aout_buffer->end_date = aout_DateIncrement( &p_sys->end_date,
512                                                       i_samples );
513         return p_aout_buffer;
514     }
515     else
516     {
517         return NULL;
518     }
519 }
520
521 /*****************************************************************************
522  * SendPacket: send an ogg dated packet to the stream output.
523  *****************************************************************************/
524 static block_t *SendPacket( decoder_t *p_dec, ogg_packet *p_oggpacket,
525                             block_t *p_block )
526 {
527     decoder_sys_t *p_sys = p_dec->p_sys;
528     int i_block_size, i_samples;
529
530     i_block_size = vorbis_packet_blocksize( &p_sys->vi, p_oggpacket );
531     if( i_block_size < 0 ) i_block_size = 0; /* non audio packet */
532     i_samples = ( p_sys->i_last_block_size + i_block_size ) >> 2;
533     p_sys->i_last_block_size = i_block_size;
534
535     /* Date management */
536     p_block->i_dts = p_block->i_pts = aout_DateGet( &p_sys->end_date );
537
538     if( p_sys->i_headers >= 3 )
539         p_block->i_length = aout_DateIncrement( &p_sys->end_date, i_samples ) -
540             p_block->i_pts;
541     else
542         p_block->i_length = 0;
543
544     return p_block;
545 }
546
547 /*****************************************************************************
548  * ParseVorbisComments: FIXME should be done in demuxer
549  *****************************************************************************/
550 static void ParseVorbisComments( decoder_t *p_dec )
551 {
552     input_thread_t *p_input = (input_thread_t *)p_dec->p_parent;
553     char *psz_name, *psz_value, *psz_comment;
554     int i = 0;
555
556     if( p_input->i_object_type != VLC_OBJECT_INPUT ) return;
557
558     while( i < p_dec->p_sys->vc.comments )
559     {
560         psz_comment = strdup( p_dec->p_sys->vc.user_comments[i] );
561         if( !psz_comment )
562         {
563             msg_Warn( p_dec, "out of memory" );
564             break;
565         }
566         psz_name = psz_comment;
567         psz_value = strchr( psz_comment, '=' );
568         if( psz_value )
569         {
570             *psz_value = '\0';
571             psz_value++;
572             input_Control( p_input, INPUT_ADD_INFO, _("Vorbis comment"),
573                            psz_name, psz_value );
574         }
575         free( psz_comment );
576         i++;
577     }
578 }
579
580 /*****************************************************************************
581  * Interleave: helper function to interleave channels
582  *****************************************************************************/
583 static void Interleave(
584 #ifdef MODULE_NAME_IS_tremor
585                         int32_t *p_out, const int32_t **pp_in,
586 #else
587                         float *p_out, const float **pp_in,
588 #endif
589                         int i_nb_channels, int i_samples )
590 {
591     int i, j;
592
593     for ( j = 0; j < i_samples; j++ )
594     {
595         for ( i = 0; i < i_nb_channels; i++ )
596         {
597             p_out[j * i_nb_channels + i] = pp_in[i][j];
598         }
599     }
600 }
601
602 /*****************************************************************************
603  * CloseDecoder: vorbis decoder destruction
604  *****************************************************************************/
605 static void CloseDecoder( vlc_object_t *p_this )
606 {
607     decoder_t *p_dec = (decoder_t *)p_this;
608     decoder_sys_t *p_sys = p_dec->p_sys;
609
610     if( !p_sys->b_packetizer && p_sys->i_headers >= 3 )
611     {
612         vorbis_block_clear( &p_sys->vb );
613         vorbis_dsp_clear( &p_sys->vd );
614     }
615
616     vorbis_comment_clear( &p_sys->vc );
617     vorbis_info_clear( &p_sys->vi );  /* must be called last */
618
619     free( p_sys );
620 }
621
622 #if defined(HAVE_VORBIS_VORBISENC_H) && !defined(MODULE_NAME_IS_tremor)
623
624 /*****************************************************************************
625  * encoder_sys_t : vorbis encoder descriptor
626  *****************************************************************************/
627 struct encoder_sys_t
628 {
629     /*
630      * Vorbis properties
631      */
632     vorbis_info      vi; /* struct that stores all the static vorbis bitstream
633                             settings */
634     vorbis_comment   vc; /* struct that stores all the bitstream user
635                           * comments */
636     vorbis_dsp_state vd; /* central working state for the packet->PCM
637                           * decoder */
638     vorbis_block     vb; /* local working space for packet->PCM decode */
639
640     int i_last_block_size;
641     int i_samples_delay;
642     int i_channels;
643
644     /*
645      * Common properties
646      */
647     mtime_t i_pts;
648 };
649
650 /*****************************************************************************
651  * OpenEncoder: probe the encoder and return score
652  *****************************************************************************/
653 static int OpenEncoder( vlc_object_t *p_this )
654 {
655     encoder_t *p_enc = (encoder_t *)p_this;
656     encoder_sys_t *p_sys;
657     int i_quality, i_min_bitrate, i_max_bitrate, i;
658     ogg_packet header[3];
659     vlc_value_t val;
660     uint8_t *p_extra;
661
662     if( p_enc->fmt_out.i_codec != VLC_FOURCC('v','o','r','b') &&
663         !p_enc->b_force )
664     {
665         return VLC_EGENERIC;
666     }
667
668     /* Allocate the memory needed to store the decoder's structure */
669     if( ( p_sys = (encoder_sys_t *)malloc(sizeof(encoder_sys_t)) ) == NULL )
670     {
671         msg_Err( p_enc, "out of memory" );
672         return VLC_EGENERIC;
673     }
674     p_enc->p_sys = p_sys;
675
676     p_enc->pf_encode_audio = Encode;
677     p_enc->fmt_in.i_codec = VLC_FOURCC('f','l','3','2');
678     p_enc->fmt_out.i_codec = VLC_FOURCC('v','o','r','b');
679
680     sout_CfgParse( p_enc, ENC_CFG_PREFIX, ppsz_enc_options, p_enc->p_cfg );
681
682     var_Get( p_enc, ENC_CFG_PREFIX "quality", &val );
683     i_quality = val.i_int;
684     if( i_quality > 10 ) i_quality = 10;
685     if( i_quality < 0 ) i_quality = 0;
686     var_Get( p_enc, ENC_CFG_PREFIX "max-bitrate", &val );
687     i_max_bitrate = val.i_int;
688     var_Get( p_enc, ENC_CFG_PREFIX "min-bitrate", &val );
689     i_min_bitrate = val.i_int;
690
691     /* Initialize vorbis encoder */
692     vorbis_info_init( &p_sys->vi );
693
694     if( i_quality > 0 )
695     {
696         /* VBR mode */
697         if( vorbis_encode_setup_vbr( &p_sys->vi,
698               p_enc->fmt_in.audio.i_channels, p_enc->fmt_in.audio.i_rate,
699               i_quality * 0.1 ) )
700         {
701             vorbis_info_clear( &p_sys->vi );
702             free( p_enc->p_sys );
703             msg_Err( p_enc, "VBR mode initialisation failed" );
704             return VLC_EGENERIC;
705         }
706
707         /* Do we have optional hard quality restrictions? */
708         if( i_max_bitrate > 0 || i_min_bitrate > 0 )
709         {
710             struct ovectl_ratemanage_arg ai;
711             vorbis_encode_ctl( &p_sys->vi, OV_ECTL_RATEMANAGE_GET, &ai );
712
713             ai.bitrate_hard_min = i_min_bitrate;
714             ai.bitrate_hard_max = i_max_bitrate;
715             ai.management_active = 1;
716
717             vorbis_encode_ctl( &p_sys->vi, OV_ECTL_RATEMANAGE_SET, &ai );
718
719         }
720         else
721         {
722             /* Turn off management entirely */
723             vorbis_encode_ctl( &p_sys->vi, OV_ECTL_RATEMANAGE_SET, NULL );
724         }
725     }
726     else
727     {
728         if( vorbis_encode_setup_managed( &p_sys->vi,
729               p_enc->fmt_in.audio.i_channels, p_enc->fmt_in.audio.i_rate,
730               i_min_bitrate > 0 ? i_min_bitrate * 1000: -1,
731               p_enc->fmt_out.i_bitrate,
732               i_max_bitrate > 0 ? i_max_bitrate * 1000: -1 ) )
733           {
734               vorbis_info_clear( &p_sys->vi );
735               msg_Err( p_enc, "CBR mode initialisation failed" );
736               free( p_enc->p_sys );
737               return VLC_EGENERIC;
738           }
739     }
740
741     vorbis_encode_setup_init( &p_sys->vi );
742
743     /* Add a comment */
744     vorbis_comment_init( &p_sys->vc);
745     vorbis_comment_add_tag( &p_sys->vc, "ENCODER", "VLC media player");
746
747     /* Set up the analysis state and auxiliary encoding storage */
748     vorbis_analysis_init( &p_sys->vd, &p_sys->vi );
749     vorbis_block_init( &p_sys->vd, &p_sys->vb );
750
751     /* Create and store headers */
752     vorbis_analysis_headerout( &p_sys->vd, &p_sys->vc,
753                                &header[0], &header[1], &header[2]);
754     p_enc->fmt_out.i_extra = 3 * 2 + header[0].bytes +
755        header[1].bytes + header[2].bytes;
756     p_extra = p_enc->fmt_out.p_extra = malloc( p_enc->fmt_out.i_extra );
757     for( i = 0; i < 3; i++ )
758     {
759         *(p_extra++) = header[i].bytes >> 8;
760         *(p_extra++) = header[i].bytes & 0xFF;
761         memcpy( p_extra, header[i].packet, header[i].bytes );
762         p_extra += header[i].bytes;
763     }
764
765     p_sys->i_channels = p_enc->fmt_in.audio.i_channels;
766     p_sys->i_last_block_size = 0;
767     p_sys->i_samples_delay = 0;
768     p_sys->i_pts = 0;
769
770     return VLC_SUCCESS;
771 }
772
773 /****************************************************************************
774  * Encode: the whole thing
775  ****************************************************************************
776  * This function spits out ogg packets.
777  ****************************************************************************/
778 static block_t *Encode( encoder_t *p_enc, aout_buffer_t *p_aout_buf )
779 {
780     encoder_sys_t *p_sys = p_enc->p_sys;
781     ogg_packet oggpacket;
782     block_t *p_block, *p_chain = NULL;
783     float **buffer;
784     int i;
785     unsigned int j;
786
787     p_sys->i_pts = p_aout_buf->start_date -
788                 (mtime_t)1000000 * (mtime_t)p_sys->i_samples_delay /
789                 (mtime_t)p_enc->fmt_in.audio.i_rate;
790
791     p_sys->i_samples_delay += p_aout_buf->i_nb_samples;
792
793     buffer = vorbis_analysis_buffer( &p_sys->vd, p_aout_buf->i_nb_samples );
794
795     /* convert samples to float and uninterleave */
796     for( i = 0; i < p_sys->i_channels; i++ )
797     {
798         for( j = 0 ; j < p_aout_buf->i_nb_samples ; j++ )
799         {
800             buffer[i][j]= ((float *)p_aout_buf->p_buffer)
801                                     [j * p_sys->i_channels + i ];
802         }
803     }
804
805     vorbis_analysis_wrote( &p_sys->vd, p_aout_buf->i_nb_samples );
806
807     while( vorbis_analysis_blockout( &p_sys->vd, &p_sys->vb ) == 1 )
808     {
809         int i_samples;
810
811         vorbis_analysis( &p_sys->vb, NULL );
812         vorbis_bitrate_addblock( &p_sys->vb );
813
814         while( vorbis_bitrate_flushpacket( &p_sys->vd, &oggpacket ) )
815         {
816             int i_block_size;
817             p_block = block_New( p_enc, oggpacket.bytes );
818             memcpy( p_block->p_buffer, oggpacket.packet, oggpacket.bytes );
819
820             i_block_size = vorbis_packet_blocksize( &p_sys->vi, &oggpacket );
821
822             if( i_block_size < 0 ) i_block_size = 0;
823             i_samples = ( p_sys->i_last_block_size + i_block_size ) >> 2;
824             p_sys->i_last_block_size = i_block_size;
825
826             p_block->i_length = (mtime_t)1000000 *
827                 (mtime_t)i_samples / (mtime_t)p_enc->fmt_in.audio.i_rate;
828
829             p_block->i_dts = p_block->i_pts = p_sys->i_pts;
830
831             p_sys->i_samples_delay -= i_samples;
832
833             /* Update pts */
834             p_sys->i_pts += p_block->i_length;
835             block_ChainAppend( &p_chain, p_block );
836         }
837     }
838
839     return p_chain;
840 }
841
842 /*****************************************************************************
843  * CloseEncoder: vorbis encoder destruction
844  *****************************************************************************/
845 static void CloseEncoder( vlc_object_t *p_this )
846 {
847     encoder_t *p_enc = (encoder_t *)p_this;
848     encoder_sys_t *p_sys = p_enc->p_sys;
849
850     vorbis_block_clear( &p_sys->vb );
851     vorbis_dsp_clear( &p_sys->vd );
852     vorbis_comment_clear( &p_sys->vc );
853     vorbis_info_clear( &p_sys->vi );  /* must be called last */
854
855     free( p_sys );
856 }
857
858 #endif /* HAVE_VORBIS_VORBISENC_H && !MODULE_NAME_IS_tremor */