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