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