]> git.sesse.net Git - vlc/blob - modules/codec/vorbis.c
Modified the way xiph codecs headers are transported in VLC.
[vlc] / modules / codec / vorbis.c
1 /*****************************************************************************
2  * vorbis.c: vorbis decoder/encoder/packetizer module using of libvorbis.
3  *****************************************************************************
4  * Copyright (C) 2001-2003 the VideoLAN team
5  * Copyright (C) 2007 Société des arts technologiques
6  * Copyright (C) 2007 Savoir-faire Linux
7  *
8  * $Id$
9  *
10  * Authors: Gildas Bazin <gbazin@videolan.org>
11  *
12  * This program is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License as published by
14  * the Free Software Foundation; either version 2 of the License, or
15  * (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program; if not, write to the Free Software
24  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
25  *****************************************************************************/
26
27 /*****************************************************************************
28  * Preamble
29  *****************************************************************************/
30 #ifdef HAVE_CONFIG_H
31 # include "config.h"
32 #endif
33
34 #include <vlc_common.h>
35 #include <vlc_plugin.h>
36 #include <vlc_codec.h>
37 #include <vlc_aout.h>
38 #include <vlc_input.h>
39 #include <vlc_sout.h>
40 #include "../demux/xiph.h"
41
42 #include <ogg/ogg.h>
43
44 #ifdef MODULE_NAME_IS_tremor
45 #include <tremor/ivorbiscodec.h>
46
47 #else
48 #include <vorbis/vorbisenc.h>
49
50 # ifndef OV_ECTL_RATEMANAGE_AVG
51 #   define OV_ECTL_RATEMANAGE_AVG 0x0
52 # endif
53
54 #endif
55
56 /*****************************************************************************
57  * decoder_sys_t : vorbis decoder descriptor
58  *****************************************************************************/
59 struct decoder_sys_t
60 {
61     /* Module mode */
62     bool b_packetizer;
63
64     bool            b_has_headers;
65
66     /*
67      * Vorbis properties
68      */
69     vorbis_info      vi; /* struct that stores all the static vorbis bitstream
70                             settings */
71     vorbis_comment   vc; /* struct that stores all the bitstream user
72                           * comments */
73     vorbis_dsp_state vd; /* central working state for the packet->PCM
74                           * decoder */
75     vorbis_block     vb; /* local working space for packet->PCM decode */
76
77     /*
78      * Common properties
79      */
80     date_t       end_date;
81     int          i_last_block_size;
82
83     /*
84     ** Channel reordering
85     */
86     int pi_chan_table[AOUT_CHAN_MAX];
87 };
88
89 static const int pi_channels_maps[9] =
90 {
91     0,
92     AOUT_CHAN_CENTER,
93     AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT,
94     AOUT_CHAN_CENTER | AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT,
95     AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_REARLEFT
96      | AOUT_CHAN_REARRIGHT,
97     AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_CENTER
98      | AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT,
99     AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_CENTER
100      | AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT | AOUT_CHAN_LFE,
101     AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_CENTER
102      | AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT | AOUT_CHAN_MIDDLELEFT
103      | AOUT_CHAN_MIDDLERIGHT,
104     AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_CENTER | AOUT_CHAN_REARLEFT
105      | AOUT_CHAN_REARRIGHT | AOUT_CHAN_MIDDLELEFT | AOUT_CHAN_MIDDLERIGHT
106      | AOUT_CHAN_LFE
107 };
108
109 /*
110 **  channel order as defined in http://www.ogghelp.com/ogg/glossary.cfm#Audio_Channels
111 */
112
113 /* recommended vorbis channel order for 6 channels */
114 static const uint32_t pi_6channels_in[] =
115 { AOUT_CHAN_LEFT, AOUT_CHAN_CENTER, AOUT_CHAN_RIGHT,
116   AOUT_CHAN_REARLEFT, AOUT_CHAN_REARRIGHT,AOUT_CHAN_LFE,0 };
117
118 /* recommended vorbis channel order for 4 channels */
119 static const uint32_t pi_4channels_in[] =
120 { AOUT_CHAN_LEFT, AOUT_CHAN_RIGHT, AOUT_CHAN_CENTER, AOUT_CHAN_LFE, 0 };
121
122 /* recommended vorbis channel order for 3 channels */
123 static const uint32_t pi_3channels_in[] =
124 { AOUT_CHAN_LEFT, AOUT_CHAN_CENTER, AOUT_CHAN_RIGHT, 0 };
125
126 /****************************************************************************
127  * Local prototypes
128  ****************************************************************************/
129 static int  OpenDecoder   ( vlc_object_t * );
130 static int  OpenPacketizer( vlc_object_t * );
131 static void CloseDecoder  ( vlc_object_t * );
132 static void *DecodeBlock  ( decoder_t *, block_t ** );
133
134 static int  ProcessHeaders( decoder_t * );
135 static void *ProcessPacket ( decoder_t *, ogg_packet *, block_t ** );
136
137 static aout_buffer_t *DecodePacket  ( decoder_t *, ogg_packet * );
138 static block_t *SendPacket( decoder_t *, ogg_packet *, block_t * );
139
140 static void ParseVorbisComments( decoder_t * );
141
142 static void ConfigureChannelOrder(int *, int, uint32_t, bool );
143
144 #ifdef MODULE_NAME_IS_tremor
145 static void Interleave   ( int32_t *, const int32_t **, int, int, int * );
146 #else
147 static void Interleave   ( float *, const float **, int, int, int * );
148 #endif
149
150 #ifndef MODULE_NAME_IS_tremor
151 static int OpenEncoder   ( vlc_object_t * );
152 static void CloseEncoder ( vlc_object_t * );
153 static block_t *Encode   ( encoder_t *, aout_buffer_t * );
154 #endif
155
156 /*****************************************************************************
157  * Module descriptor
158  *****************************************************************************/
159 #define ENC_QUALITY_TEXT N_("Encoding quality")
160 #define ENC_QUALITY_LONGTEXT N_( \
161   "Enforce a quality between 1 (low) and 10 (high), instead " \
162   "of specifying a particular bitrate. This will produce a VBR stream." )
163 #define ENC_MAXBR_TEXT N_("Maximum encoding bitrate")
164 #define ENC_MAXBR_LONGTEXT N_( \
165   "Maximum bitrate in kbps. This is useful for streaming applications." )
166 #define ENC_MINBR_TEXT N_("Minimum encoding bitrate")
167 #define ENC_MINBR_LONGTEXT N_( \
168   "Minimum bitrate in kbps. This is useful for encoding for a fixed-size channel." )
169 #define ENC_CBR_TEXT N_("CBR encoding")
170 #define ENC_CBR_LONGTEXT N_( \
171   "Force a constant bitrate encoding (CBR)." )
172
173 vlc_module_begin ()
174     set_shortname( "Vorbis" )
175     set_description( N_("Vorbis audio decoder") )
176 #ifdef MODULE_NAME_IS_tremor
177     set_capability( "decoder", 90 )
178 #else
179     set_capability( "decoder", 100 )
180 #endif
181     set_category( CAT_INPUT )
182     set_subcategory( SUBCAT_INPUT_ACODEC )
183     set_callbacks( OpenDecoder, CloseDecoder )
184
185     add_submodule ()
186     set_description( N_("Vorbis audio packetizer") )
187     set_capability( "packetizer", 100 )
188     set_callbacks( OpenPacketizer, CloseDecoder )
189
190 #ifndef MODULE_NAME_IS_tremor
191 #   define ENC_CFG_PREFIX "sout-vorbis-"
192     add_submodule ()
193     set_description( N_("Vorbis audio encoder") )
194     set_capability( "encoder", 100 )
195     set_callbacks( OpenEncoder, CloseEncoder )
196
197     add_integer( ENC_CFG_PREFIX "quality", 0, NULL, ENC_QUALITY_TEXT,
198                  ENC_QUALITY_LONGTEXT, false )
199         change_integer_range( 0, 10 )
200     add_integer( ENC_CFG_PREFIX "max-bitrate", 0, NULL, ENC_MAXBR_TEXT,
201                  ENC_MAXBR_LONGTEXT, false )
202     add_integer( ENC_CFG_PREFIX "min-bitrate", 0, NULL, ENC_MINBR_TEXT,
203                  ENC_MINBR_LONGTEXT, false )
204     add_bool( ENC_CFG_PREFIX "cbr", false, NULL, ENC_CBR_TEXT,
205                  ENC_CBR_LONGTEXT, false )
206 #endif
207
208 vlc_module_end ()
209
210 #ifndef MODULE_NAME_IS_tremor
211 static const char *const ppsz_enc_options[] = {
212     "quality", "max-bitrate", "min-bitrate", "cbr", NULL
213 };
214 #endif
215
216 /*****************************************************************************
217  * OpenDecoder: probe the decoder and return score
218  *****************************************************************************/
219 static int OpenDecoder( vlc_object_t *p_this )
220 {
221     decoder_t *p_dec = (decoder_t*)p_this;
222     decoder_sys_t *p_sys;
223
224     if( p_dec->fmt_in.i_codec != VLC_CODEC_VORBIS )
225     {
226         return VLC_EGENERIC;
227     }
228
229     /* Allocate the memory needed to store the decoder's structure */
230     if( ( p_dec->p_sys = p_sys = malloc( sizeof(*p_sys) ) ) == NULL )
231         return VLC_ENOMEM;
232
233     /* Misc init */
234     date_Set( &p_sys->end_date, 0 );
235     p_sys->i_last_block_size = 0;
236     p_sys->b_packetizer = false;
237     p_sys->b_has_headers = false;
238
239     /* Take care of vorbis init */
240     vorbis_info_init( &p_sys->vi );
241     vorbis_comment_init( &p_sys->vc );
242
243     /* Set output properties */
244     p_dec->fmt_out.i_cat = AUDIO_ES;
245 #ifdef MODULE_NAME_IS_tremor
246     p_dec->fmt_out.i_codec = VLC_CODEC_FI32;
247 #else
248     p_dec->fmt_out.i_codec = VLC_CODEC_FL32;
249 #endif
250
251     /* Set callbacks */
252     p_dec->pf_decode_audio = (aout_buffer_t *(*)(decoder_t *, block_t **))
253         DecodeBlock;
254     p_dec->pf_packetize    = (block_t *(*)(decoder_t *, block_t **))
255         DecodeBlock;
256
257     return VLC_SUCCESS;
258 }
259
260 static int OpenPacketizer( vlc_object_t *p_this )
261 {
262     decoder_t *p_dec = (decoder_t*)p_this;
263
264     int i_ret = OpenDecoder( p_this );
265
266     if( i_ret == VLC_SUCCESS )
267     {
268         p_dec->p_sys->b_packetizer = true;
269         p_dec->fmt_out.i_codec = VLC_CODEC_VORBIS;
270     }
271
272     return i_ret;
273 }
274
275 /****************************************************************************
276  * DecodeBlock: the whole thing
277  ****************************************************************************
278  * This function must be fed with ogg packets.
279  ****************************************************************************/
280 static void *DecodeBlock( decoder_t *p_dec, block_t **pp_block )
281 {
282     decoder_sys_t *p_sys = p_dec->p_sys;
283     ogg_packet oggpacket;
284
285     if( !pp_block ) return NULL;
286
287     if( *pp_block )
288     {
289         /* Block to Ogg packet */
290         oggpacket.packet = (*pp_block)->p_buffer;
291         oggpacket.bytes = (*pp_block)->i_buffer;
292     }
293     else
294     {
295         if( p_sys->b_packetizer ) return NULL;
296
297         /* Block to Ogg packet */
298         oggpacket.packet = NULL;
299         oggpacket.bytes = 0;
300     }
301
302     oggpacket.granulepos = -1;
303     oggpacket.b_o_s = 0;
304     oggpacket.e_o_s = 0;
305     oggpacket.packetno = 0;
306
307     /* Check for headers */
308     if( !p_sys->b_has_headers )
309     {
310         if( ProcessHeaders( p_dec ) )
311         {
312             block_Release( *pp_block );
313             return NULL;
314         }
315         p_sys->b_has_headers = true;
316     }
317
318     return ProcessPacket( p_dec, &oggpacket, pp_block );
319 }
320
321 /*****************************************************************************
322  * ProcessHeaders: process Vorbis headers.
323  *****************************************************************************/
324 static int ProcessHeaders( decoder_t *p_dec )
325 {
326     decoder_sys_t *p_sys = p_dec->p_sys;
327     ogg_packet oggpacket;
328
329     unsigned pi_size[XIPH_MAX_HEADER_COUNT];
330     void     *pp_data[XIPH_MAX_HEADER_COUNT];
331     unsigned i_count;
332     if( xiph_SplitHeaders( pi_size, pp_data, &i_count,
333                            p_dec->fmt_in.i_extra, p_dec->fmt_in.p_extra) )
334         return VLC_EGENERIC;
335     if( i_count < 3 )
336         goto error;
337
338     oggpacket.granulepos = -1;
339     oggpacket.e_o_s = 0;
340     oggpacket.packetno = 0;
341
342     /* Take care of the initial Vorbis header */
343     oggpacket.b_o_s  = 1; /* yes this actually is a b_o_s packet :) */
344     oggpacket.bytes  = pi_size[0];
345     oggpacket.packet = pp_data[0];
346     if( vorbis_synthesis_headerin( &p_sys->vi, &p_sys->vc, &oggpacket ) < 0 )
347     {
348         msg_Err( p_dec, "this bitstream does not contain Vorbis audio data");
349         goto error;
350     }
351
352     /* Setup the format */
353     p_dec->fmt_out.audio.i_rate     = p_sys->vi.rate;
354     p_dec->fmt_out.audio.i_channels = p_sys->vi.channels;
355
356     if( p_dec->fmt_out.audio.i_channels > 9 )
357     {
358         msg_Err( p_dec, "invalid number of channels (not between 1 and 9): %i",
359                  p_dec->fmt_out.audio.i_channels );
360         goto error;
361     }
362
363     p_dec->fmt_out.audio.i_physical_channels =
364         p_dec->fmt_out.audio.i_original_channels =
365             pi_channels_maps[p_sys->vi.channels];
366     p_dec->fmt_out.i_bitrate = p_sys->vi.bitrate_nominal;
367
368     date_Init( &p_sys->end_date, p_sys->vi.rate, 1 );
369
370     msg_Dbg( p_dec, "channels:%d samplerate:%ld bitrate:%ld",
371              p_sys->vi.channels, p_sys->vi.rate, p_sys->vi.bitrate_nominal );
372
373     /* The next packet in order is the comments header */
374     oggpacket.b_o_s  = 0;
375     oggpacket.bytes  = pi_size[1];
376     oggpacket.packet = pp_data[1];
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         goto error;
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.b_o_s  = 0;
388     oggpacket.bytes  = pi_size[2];
389     oggpacket.packet = pp_data[2];
390     if( vorbis_synthesis_headerin( &p_sys->vi, &p_sys->vc, &oggpacket ) < 0 )
391     {
392         msg_Err( p_dec, "3rd Vorbis header is corrupted" );
393         return VLC_EGENERIC;
394     }
395
396     if( !p_sys->b_packetizer )
397     {
398         /* Initialize the Vorbis packet->PCM decoder */
399         vorbis_synthesis_init( &p_sys->vd, &p_sys->vi );
400         vorbis_block_init( &p_sys->vd, &p_sys->vb );
401     }
402     else
403     {
404         p_dec->fmt_out.i_extra = p_dec->fmt_in.i_extra;
405         p_dec->fmt_out.p_extra = xrealloc( p_dec->fmt_out.p_extra,
406                                            p_dec->fmt_out.i_extra );
407         memcpy( p_dec->fmt_out.p_extra,
408                 p_dec->fmt_in.p_extra, p_dec->fmt_out.i_extra );
409     }
410
411     ConfigureChannelOrder(p_sys->pi_chan_table, p_sys->vi.channels,
412             p_dec->fmt_out.audio.i_physical_channels, true);
413
414     for( unsigned i = 0; i < i_count; i++ )
415         free( pp_data[i] );
416     return VLC_SUCCESS;
417
418 error:
419     for( unsigned i = 0; i < i_count; i++ )
420         free( pp_data[i] );
421     return VLC_EGENERIC;
422 }
423
424 /*****************************************************************************
425  * ProcessPacket: processes a Vorbis packet.
426  *****************************************************************************/
427 static void *ProcessPacket( decoder_t *p_dec, ogg_packet *p_oggpacket,
428                             block_t **pp_block )
429 {
430     decoder_sys_t *p_sys = p_dec->p_sys;
431     block_t *p_block = *pp_block;
432
433     /* Date management */
434     if( p_block && p_block->i_pts > VLC_TS_INVALID &&
435         p_block->i_pts != date_Get( &p_sys->end_date ) )
436     {
437         date_Set( &p_sys->end_date, p_block->i_pts );
438     }
439
440     if( !date_Get( &p_sys->end_date ) )
441     {
442         /* We've just started the stream, wait for the first PTS. */
443         if( p_block ) block_Release( p_block );
444         return NULL;
445     }
446
447     *pp_block = NULL; /* To avoid being fed the same packet again */
448
449     if( p_sys->b_packetizer )
450     {
451         return SendPacket( p_dec, p_oggpacket, p_block );
452     }
453     else
454     {
455         aout_buffer_t *p_aout_buffer = DecodePacket( p_dec, p_oggpacket );
456         if( p_block )
457             block_Release( p_block );
458         return p_aout_buffer;
459     }
460 }
461
462 /*****************************************************************************
463  * DecodePacket: decodes a Vorbis packet.
464  *****************************************************************************/
465 static aout_buffer_t *DecodePacket( decoder_t *p_dec, ogg_packet *p_oggpacket )
466 {
467     decoder_sys_t *p_sys = p_dec->p_sys;
468     int           i_samples;
469
470 #ifdef MODULE_NAME_IS_tremor
471     int32_t       **pp_pcm;
472 #else
473     float         **pp_pcm;
474 #endif
475
476     if( p_oggpacket->bytes &&
477 #ifdef MODULE_NAME_IS_tremor
478         vorbis_synthesis( &p_sys->vb, p_oggpacket, 1 ) == 0 )
479 #else
480         vorbis_synthesis( &p_sys->vb, p_oggpacket ) == 0 )
481 #endif
482         vorbis_synthesis_blockin( &p_sys->vd, &p_sys->vb );
483
484     /* **pp_pcm is a multichannel float vector. In stereo, for
485      * example, pp_pcm[0] is left, and pp_pcm[1] is right. i_samples is
486      * the size of each channel. Convert the float values
487      * (-1.<=range<=1.) to whatever PCM format and write it out */
488
489     if( ( i_samples = vorbis_synthesis_pcmout( &p_sys->vd, &pp_pcm ) ) > 0 )
490     {
491
492         aout_buffer_t *p_aout_buffer;
493
494         p_aout_buffer =
495             decoder_NewAudioBuffer( p_dec, i_samples );
496
497         if( p_aout_buffer == NULL ) return NULL;
498
499         /* Interleave the samples */
500 #ifdef MODULE_NAME_IS_tremor
501         Interleave( (int32_t *)p_aout_buffer->p_buffer,
502                     (const int32_t **)pp_pcm, p_sys->vi.channels, i_samples, p_sys->pi_chan_table);
503 #else
504         Interleave( (float *)p_aout_buffer->p_buffer,
505                     (const float **)pp_pcm, p_sys->vi.channels, i_samples, p_sys->pi_chan_table);
506 #endif
507
508         /* Tell libvorbis how many samples we actually consumed */
509         vorbis_synthesis_read( &p_sys->vd, i_samples );
510
511         /* Date management */
512         p_aout_buffer->i_pts = date_Get( &p_sys->end_date );
513         p_aout_buffer->i_length = date_Increment( &p_sys->end_date,
514                                            i_samples ) - p_aout_buffer->i_pts;
515         return p_aout_buffer;
516     }
517     else
518     {
519         return NULL;
520     }
521 }
522
523 /*****************************************************************************
524  * SendPacket: send an ogg dated packet to the stream output.
525  *****************************************************************************/
526 static block_t *SendPacket( decoder_t *p_dec, ogg_packet *p_oggpacket,
527                             block_t *p_block )
528 {
529     decoder_sys_t *p_sys = p_dec->p_sys;
530     int i_block_size, i_samples;
531
532     i_block_size = vorbis_packet_blocksize( &p_sys->vi, p_oggpacket );
533     if( i_block_size < 0 ) i_block_size = 0; /* non audio packet */
534     i_samples = ( p_sys->i_last_block_size + i_block_size ) >> 2;
535     p_sys->i_last_block_size = i_block_size;
536
537     /* Date management */
538     p_block->i_dts = p_block->i_pts = date_Get( &p_sys->end_date );
539
540     p_block->i_length = date_Increment( &p_sys->end_date, i_samples ) - p_block->i_pts;
541
542     return p_block;
543 }
544
545 /*****************************************************************************
546  * ParseVorbisComments
547  *****************************************************************************/
548 static void ParseVorbisComments( decoder_t *p_dec )
549 {
550     char *psz_name, *psz_value, *psz_comment;
551     int i = 0;
552
553     while( i < p_dec->p_sys->vc.comments )
554     {
555         psz_comment = strdup( p_dec->p_sys->vc.user_comments[i] );
556         if( !psz_comment )
557             break;
558         psz_name = psz_comment;
559         psz_value = strchr( psz_comment, '=' );
560         if( psz_value )
561         {
562             *psz_value = '\0';
563             psz_value++;
564
565             if( !p_dec->p_description )
566                 p_dec->p_description = vlc_meta_New();
567             if( p_dec->p_description )
568                 vlc_meta_AddExtra( p_dec->p_description, psz_name, psz_value );
569
570             if( !strcasecmp( psz_name, "REPLAYGAIN_TRACK_GAIN" ) ||
571                      !strcasecmp( psz_name, "RG_RADIO" ) )
572             {
573                 audio_replay_gain_t *r = &p_dec->fmt_out.audio_replay_gain;
574
575                 r->pb_gain[AUDIO_REPLAY_GAIN_TRACK] = true;
576                 r->pf_gain[AUDIO_REPLAY_GAIN_TRACK] = atof( psz_value );
577             }
578             else if( !strcasecmp( psz_name, "REPLAYGAIN_TRACK_PEAK" ) ||
579                      !strcasecmp( psz_name, "RG_PEAK" ) )
580             {
581                 audio_replay_gain_t *r = &p_dec->fmt_out.audio_replay_gain;
582
583                 r->pb_peak[AUDIO_REPLAY_GAIN_TRACK] = true;
584                 r->pf_peak[AUDIO_REPLAY_GAIN_TRACK] = atof( psz_value );
585             }
586             else if( !strcasecmp( psz_name, "REPLAYGAIN_ALBUM_GAIN" ) ||
587                      !strcasecmp( psz_name, "RG_AUDIOPHILE" ) )
588             {
589                 audio_replay_gain_t *r = &p_dec->fmt_out.audio_replay_gain;
590
591                 r->pb_gain[AUDIO_REPLAY_GAIN_ALBUM] = true;
592                 r->pf_gain[AUDIO_REPLAY_GAIN_ALBUM] = atof( psz_value );
593             }
594             else if( !strcasecmp( psz_name, "REPLAYGAIN_ALBUM_PEAK" ) )
595             {
596                 audio_replay_gain_t *r = &p_dec->fmt_out.audio_replay_gain;
597
598                 r->pb_peak[AUDIO_REPLAY_GAIN_ALBUM] = true;
599                 r->pf_peak[AUDIO_REPLAY_GAIN_ALBUM] = atof( psz_value );
600             }
601         }
602         free( psz_comment );
603         i++;
604     }
605 }
606
607 /*****************************************************************************
608  * Interleave: helper function to interleave channels
609  *****************************************************************************/
610 static void ConfigureChannelOrder(int *pi_chan_table, int i_channels, uint32_t i_channel_mask, bool b_decode)
611 {
612     const uint32_t *pi_channels_in;
613     switch( i_channels )
614     {
615         case 6:
616         case 5:
617             pi_channels_in = pi_6channels_in;
618             break;
619         case 4:
620             pi_channels_in = pi_4channels_in;
621             break;
622         case 3:
623             pi_channels_in = pi_3channels_in;
624             break;
625         default:
626             {
627                 int i;
628                 for( i = 0; i< i_channels; ++i )
629                 {
630                     pi_chan_table[i] = i;
631                 }
632                 return;
633             }
634     }
635
636     if( b_decode )
637         aout_CheckChannelReorder( pi_channels_in, NULL,
638                                   i_channel_mask & AOUT_CHAN_PHYSMASK,
639                                   i_channels,
640                                   pi_chan_table );
641     else
642         aout_CheckChannelReorder( NULL, pi_channels_in,
643                                   i_channel_mask & AOUT_CHAN_PHYSMASK,
644                                   i_channels,
645                                   pi_chan_table );
646 }
647
648 /*****************************************************************************
649  * Interleave: helper function to interleave channels
650  *****************************************************************************/
651 #ifdef MODULE_NAME_IS_tremor
652 static void Interleave( int32_t *p_out, const int32_t **pp_in,
653                         int i_nb_channels, int i_samples, int *pi_chan_table)
654 {
655     int i, j;
656
657     for ( j = 0; j < i_samples; j++ )
658         for ( i = 0; i < i_nb_channels; i++ )
659             p_out[j * i_nb_channels + pi_chan_table[i]] = pp_in[i][j] * (FIXED32_ONE >> 24);
660 }
661 #else
662 static void Interleave( float *p_out, const float **pp_in,
663                         int i_nb_channels, int i_samples, int *pi_chan_table )
664 {
665     int i, j;
666
667     for ( j = 0; j < i_samples; j++ )
668         for ( i = 0; i < i_nb_channels; i++ )
669             p_out[j * i_nb_channels + pi_chan_table[i]] = pp_in[i][j];
670 }
671 #endif
672
673 /*****************************************************************************
674  * CloseDecoder: vorbis decoder destruction
675  *****************************************************************************/
676 static void CloseDecoder( vlc_object_t *p_this )
677 {
678     decoder_t *p_dec = (decoder_t *)p_this;
679     decoder_sys_t *p_sys = p_dec->p_sys;
680
681     if( !p_sys->b_packetizer && p_sys->b_has_headers )
682     {
683         vorbis_block_clear( &p_sys->vb );
684         vorbis_dsp_clear( &p_sys->vd );
685     }
686
687     vorbis_comment_clear( &p_sys->vc );
688     vorbis_info_clear( &p_sys->vi );  /* must be called last */
689
690     free( p_sys );
691 }
692
693 #ifndef MODULE_NAME_IS_tremor
694
695 /*****************************************************************************
696  * encoder_sys_t : vorbis encoder descriptor
697  *****************************************************************************/
698 struct encoder_sys_t
699 {
700     /*
701      * Vorbis properties
702      */
703     vorbis_info      vi; /* struct that stores all the static vorbis bitstream
704                             settings */
705     vorbis_comment   vc; /* struct that stores all the bitstream user
706                           * comments */
707     vorbis_dsp_state vd; /* central working state for the packet->PCM
708                           * decoder */
709     vorbis_block     vb; /* local working space for packet->PCM decode */
710
711     int i_last_block_size;
712     int i_samples_delay;
713     int i_channels;
714
715     /*
716     ** Channel reordering
717     */
718     int pi_chan_table[AOUT_CHAN_MAX];
719
720 };
721
722 /*****************************************************************************
723  * OpenEncoder: probe the encoder and return score
724  *****************************************************************************/
725 static int OpenEncoder( vlc_object_t *p_this )
726 {
727     encoder_t *p_enc = (encoder_t *)p_this;
728     encoder_sys_t *p_sys;
729     int i_quality, i_min_bitrate, i_max_bitrate, i;
730     ogg_packet header[3];
731     uint8_t *p_extra;
732
733     if( p_enc->fmt_out.i_codec != VLC_CODEC_VORBIS &&
734         !p_enc->b_force )
735     {
736         return VLC_EGENERIC;
737     }
738
739     /* Allocate the memory needed to store the decoder's structure */
740     if( ( p_sys = (encoder_sys_t *)malloc(sizeof(encoder_sys_t)) ) == NULL )
741         return VLC_ENOMEM;
742     p_enc->p_sys = p_sys;
743
744     p_enc->pf_encode_audio = Encode;
745     p_enc->fmt_in.i_codec = VLC_CODEC_FL32;
746     p_enc->fmt_out.i_codec = VLC_CODEC_VORBIS;
747
748     config_ChainParse( p_enc, ENC_CFG_PREFIX, ppsz_enc_options, p_enc->p_cfg );
749
750     i_quality = var_GetInteger( p_enc, ENC_CFG_PREFIX "quality" );
751     if( i_quality > 10 ) i_quality = 10;
752     if( i_quality < 0 ) i_quality = 0;
753
754     if( var_GetBool( p_enc, ENC_CFG_PREFIX "cbr" ) ) i_quality = 0;
755     i_max_bitrate = var_GetInteger( p_enc, ENC_CFG_PREFIX "max-bitrate" );
756     i_min_bitrate = var_GetInteger( p_enc, ENC_CFG_PREFIX "min-bitrate" );
757
758     /* Initialize vorbis encoder */
759     vorbis_info_init( &p_sys->vi );
760
761     if( i_quality > 0 )
762     {
763         /* VBR mode */
764         if( vorbis_encode_setup_vbr( &p_sys->vi,
765               p_enc->fmt_in.audio.i_channels, p_enc->fmt_in.audio.i_rate,
766               i_quality * 0.1 ) )
767         {
768             vorbis_info_clear( &p_sys->vi );
769             free( p_enc->p_sys );
770             msg_Err( p_enc, "VBR mode initialisation failed" );
771             return VLC_EGENERIC;
772         }
773
774         /* Do we have optional hard quality restrictions? */
775         if( i_max_bitrate > 0 || i_min_bitrate > 0 )
776         {
777             struct ovectl_ratemanage_arg ai;
778             vorbis_encode_ctl( &p_sys->vi, OV_ECTL_RATEMANAGE_GET, &ai );
779
780             ai.bitrate_hard_min = i_min_bitrate;
781             ai.bitrate_hard_max = i_max_bitrate;
782             ai.management_active = 1;
783
784             vorbis_encode_ctl( &p_sys->vi, OV_ECTL_RATEMANAGE_SET, &ai );
785
786         }
787         else
788         {
789             /* Turn off management entirely */
790             vorbis_encode_ctl( &p_sys->vi, OV_ECTL_RATEMANAGE_SET, NULL );
791         }
792     }
793     else
794     {
795         if( vorbis_encode_setup_managed( &p_sys->vi,
796               p_enc->fmt_in.audio.i_channels, p_enc->fmt_in.audio.i_rate,
797               i_min_bitrate > 0 ? i_min_bitrate * 1000: -1,
798               p_enc->fmt_out.i_bitrate,
799               i_max_bitrate > 0 ? i_max_bitrate * 1000: -1 ) )
800           {
801               vorbis_info_clear( &p_sys->vi );
802               msg_Err( p_enc, "CBR mode initialisation failed" );
803               free( p_enc->p_sys );
804               return VLC_EGENERIC;
805           }
806     }
807
808     vorbis_encode_setup_init( &p_sys->vi );
809
810     /* Add a comment */
811     vorbis_comment_init( &p_sys->vc);
812     vorbis_comment_add_tag( &p_sys->vc, "ENCODER", "VLC media player");
813
814     /* Set up the analysis state and auxiliary encoding storage */
815     vorbis_analysis_init( &p_sys->vd, &p_sys->vi );
816     vorbis_block_init( &p_sys->vd, &p_sys->vb );
817
818     /* Create and store headers */
819     vorbis_analysis_headerout( &p_sys->vd, &p_sys->vc,
820                                &header[0], &header[1], &header[2]);
821     p_enc->fmt_out.i_extra = 3 * 2 + header[0].bytes +
822        header[1].bytes + header[2].bytes;
823     p_extra = p_enc->fmt_out.p_extra = xmalloc( p_enc->fmt_out.i_extra );
824     for( i = 0; i < 3; i++ )
825     {
826         *(p_extra++) = header[i].bytes >> 8;
827         *(p_extra++) = header[i].bytes & 0xFF;
828         memcpy( p_extra, header[i].packet, header[i].bytes );
829         p_extra += header[i].bytes;
830     }
831
832     p_sys->i_channels = p_enc->fmt_in.audio.i_channels;
833     p_sys->i_last_block_size = 0;
834     p_sys->i_samples_delay = 0;
835
836     ConfigureChannelOrder(p_sys->pi_chan_table, p_sys->vi.channels,
837             p_enc->fmt_in.audio.i_physical_channels, true);
838
839     return VLC_SUCCESS;
840 }
841
842 /****************************************************************************
843  * Encode: the whole thing
844  ****************************************************************************
845  * This function spits out ogg packets.
846  ****************************************************************************/
847 static block_t *Encode( encoder_t *p_enc, aout_buffer_t *p_aout_buf )
848 {
849     encoder_sys_t *p_sys = p_enc->p_sys;
850     ogg_packet oggpacket;
851     block_t *p_block, *p_chain = NULL;
852     float **buffer;
853     int i;
854     unsigned int j;
855
856     mtime_t i_pts = p_aout_buf->i_pts -
857                 (mtime_t)1000000 * (mtime_t)p_sys->i_samples_delay /
858                 (mtime_t)p_enc->fmt_in.audio.i_rate;
859
860     p_sys->i_samples_delay += p_aout_buf->i_nb_samples;
861
862     buffer = vorbis_analysis_buffer( &p_sys->vd, p_aout_buf->i_nb_samples );
863
864     /* convert samples to float and uninterleave */
865     for( i = 0; i < p_sys->i_channels; i++ )
866     {
867         for( j = 0 ; j < p_aout_buf->i_nb_samples ; j++ )
868         {
869             buffer[i][j]= ((float *)p_aout_buf->p_buffer)
870                                     [j * p_sys->i_channels + p_sys->pi_chan_table[i]];
871         }
872     }
873
874     vorbis_analysis_wrote( &p_sys->vd, p_aout_buf->i_nb_samples );
875
876     while( vorbis_analysis_blockout( &p_sys->vd, &p_sys->vb ) == 1 )
877     {
878         int i_samples;
879
880         vorbis_analysis( &p_sys->vb, NULL );
881         vorbis_bitrate_addblock( &p_sys->vb );
882
883         while( vorbis_bitrate_flushpacket( &p_sys->vd, &oggpacket ) )
884         {
885             int i_block_size;
886             p_block = block_New( p_enc, oggpacket.bytes );
887             memcpy( p_block->p_buffer, oggpacket.packet, oggpacket.bytes );
888
889             i_block_size = vorbis_packet_blocksize( &p_sys->vi, &oggpacket );
890
891             if( i_block_size < 0 ) i_block_size = 0;
892             i_samples = ( p_sys->i_last_block_size + i_block_size ) >> 2;
893             p_sys->i_last_block_size = i_block_size;
894
895             p_block->i_length = (mtime_t)1000000 *
896                 (mtime_t)i_samples / (mtime_t)p_enc->fmt_in.audio.i_rate;
897
898             p_block->i_dts = p_block->i_pts = i_pts;
899
900             p_sys->i_samples_delay -= i_samples;
901
902             /* Update pts */
903             i_pts += p_block->i_length;
904             block_ChainAppend( &p_chain, p_block );
905         }
906     }
907
908     return p_chain;
909 }
910
911 /*****************************************************************************
912  * CloseEncoder: vorbis encoder destruction
913  *****************************************************************************/
914 static void CloseEncoder( vlc_object_t *p_this )
915 {
916     encoder_t *p_enc = (encoder_t *)p_this;
917     encoder_sys_t *p_sys = p_enc->p_sys;
918
919     vorbis_block_clear( &p_sys->vb );
920     vorbis_dsp_clear( &p_sys->vd );
921     vorbis_comment_clear( &p_sys->vc );
922     vorbis_info_clear( &p_sys->vi );  /* must be called last */
923
924     free( p_sys );
925 }
926
927 #endif /* HAVE_VORBIS_VORBISENC_H && !MODULE_NAME_IS_tremor */