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