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