]> git.sesse.net Git - vlc/blob - modules/codec/vorbis.c
aout_buffer_t: store length instead of end timestamp
[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 =
322             realloc( p_dec->fmt_in.p_extra, p_dec->fmt_in.i_extra +
323                      oggpacket.bytes + 2 );
324         p_extra = (uint8_t *)p_dec->fmt_in.p_extra + p_dec->fmt_in.i_extra;
325         *(p_extra++) = oggpacket.bytes >> 8;
326         *(p_extra++) = oggpacket.bytes & 0xFF;
327
328         memcpy( p_extra, oggpacket.packet, oggpacket.bytes );
329         p_dec->fmt_in.i_extra += oggpacket.bytes + 2;
330
331         block_Release( *pp_block );
332         p_sys->i_headers++;
333         return NULL;
334     }
335
336     if( p_sys->i_headers == 3 )
337     {
338         if( ProcessHeaders( p_dec ) != VLC_SUCCESS )
339         {
340             p_sys->i_headers = 0;
341             p_dec->fmt_in.i_extra = 0;
342             block_Release( *pp_block );
343             return NULL;
344         }
345         else p_sys->i_headers++;
346     }
347
348     return ProcessPacket( p_dec, &oggpacket, pp_block );
349 }
350
351 /*****************************************************************************
352  * ProcessHeaders: process Vorbis headers.
353  *****************************************************************************/
354 static int ProcessHeaders( decoder_t *p_dec )
355 {
356     decoder_sys_t *p_sys = p_dec->p_sys;
357     ogg_packet oggpacket;
358     uint8_t *p_extra;
359     int i_extra;
360
361     if( !p_dec->fmt_in.i_extra ) return VLC_EGENERIC;
362
363     oggpacket.granulepos = -1;
364     oggpacket.b_o_s = 1; /* yes this actually is a b_o_s packet :) */
365     oggpacket.e_o_s = 0;
366     oggpacket.packetno = 0;
367     p_extra = p_dec->fmt_in.p_extra;
368     i_extra = p_dec->fmt_in.i_extra;
369
370     /* Take care of the initial Vorbis header */
371     oggpacket.bytes = *(p_extra++) << 8;
372     oggpacket.bytes |= (*(p_extra++) & 0xFF);
373     oggpacket.packet = p_extra;
374     p_extra += oggpacket.bytes;
375     i_extra -= (oggpacket.bytes + 2);
376     if( i_extra < 0 )
377     {
378         msg_Err( p_dec, "header data corrupted");
379         return VLC_EGENERIC;
380     }
381
382     if( vorbis_synthesis_headerin( &p_sys->vi, &p_sys->vc, &oggpacket ) < 0 )
383     {
384         msg_Err( p_dec, "this bitstream does not contain Vorbis audio data");
385         return VLC_EGENERIC;
386     }
387
388     /* Setup the format */
389     p_dec->fmt_out.audio.i_rate     = p_sys->vi.rate;
390     p_dec->fmt_out.audio.i_channels = p_sys->vi.channels;
391
392     if( p_dec->fmt_out.audio.i_channels > 9 )
393     {
394         msg_Err( p_dec, "invalid number of channels (not between 1 and 9): %i",
395                  p_dec->fmt_out.audio.i_channels );
396         return VLC_EGENERIC;
397     }
398
399     p_dec->fmt_out.audio.i_physical_channels =
400         p_dec->fmt_out.audio.i_original_channels =
401             pi_channels_maps[p_sys->vi.channels];
402     p_dec->fmt_out.i_bitrate = p_sys->vi.bitrate_nominal;
403
404     date_Init( &p_sys->end_date, p_sys->vi.rate, 1 );
405
406     msg_Dbg( p_dec, "channels:%d samplerate:%ld bitrate:%ld",
407              p_sys->vi.channels, p_sys->vi.rate, p_sys->vi.bitrate_nominal );
408
409     /* The next packet in order is the comments header */
410     oggpacket.b_o_s = 0;
411     oggpacket.bytes = *(p_extra++) << 8;
412     oggpacket.bytes |= (*(p_extra++) & 0xFF);
413     oggpacket.packet = p_extra;
414     p_extra += oggpacket.bytes;
415     i_extra -= (oggpacket.bytes + 2);
416     if( i_extra < 0 )
417     {
418         msg_Err( p_dec, "header data corrupted");
419         return VLC_EGENERIC;
420     }
421
422     if( vorbis_synthesis_headerin( &p_sys->vi, &p_sys->vc, &oggpacket ) < 0 )
423     {
424         msg_Err( p_dec, "2nd Vorbis header is corrupted" );
425         return VLC_EGENERIC;
426     }
427     ParseVorbisComments( p_dec );
428
429     /* The next packet in order is the codebooks header
430      * We need to watch out that this packet is not missing as a
431      * missing or corrupted header is fatal. */
432     oggpacket.bytes = *(p_extra++) << 8;
433     oggpacket.bytes |= (*(p_extra++) & 0xFF);
434     oggpacket.packet = p_extra;
435     i_extra -= (oggpacket.bytes + 2);
436     if( i_extra < 0 )
437     {
438         msg_Err( p_dec, "header data corrupted");
439         return VLC_EGENERIC;
440     }
441
442     if( vorbis_synthesis_headerin( &p_sys->vi, &p_sys->vc, &oggpacket ) < 0 )
443     {
444         msg_Err( p_dec, "3rd Vorbis header is corrupted" );
445         return VLC_EGENERIC;
446     }
447
448     if( !p_sys->b_packetizer )
449     {
450         /* Initialize the Vorbis packet->PCM decoder */
451         vorbis_synthesis_init( &p_sys->vd, &p_sys->vi );
452         vorbis_block_init( &p_sys->vd, &p_sys->vb );
453     }
454     else
455     {
456         p_dec->fmt_out.i_extra = p_dec->fmt_in.i_extra;
457         p_dec->fmt_out.p_extra =
458             realloc( p_dec->fmt_out.p_extra, p_dec->fmt_out.i_extra );
459         memcpy( p_dec->fmt_out.p_extra,
460                 p_dec->fmt_in.p_extra, p_dec->fmt_out.i_extra );
461     }
462
463     ConfigureChannelOrder(p_sys->pi_chan_table, p_sys->vi.channels,
464             p_dec->fmt_out.audio.i_physical_channels, true);
465
466     return VLC_SUCCESS;
467 }
468
469 /*****************************************************************************
470  * ProcessPacket: processes a Vorbis packet.
471  *****************************************************************************/
472 static void *ProcessPacket( decoder_t *p_dec, ogg_packet *p_oggpacket,
473                             block_t **pp_block )
474 {
475     decoder_sys_t *p_sys = p_dec->p_sys;
476     block_t *p_block = *pp_block;
477
478     /* Date management */
479     if( p_block && p_block->i_pts > 0 &&
480         p_block->i_pts != date_Get( &p_sys->end_date ) )
481     {
482         date_Set( &p_sys->end_date, p_block->i_pts );
483     }
484
485     if( !date_Get( &p_sys->end_date ) )
486     {
487         /* We've just started the stream, wait for the first PTS. */
488         if( p_block ) block_Release( p_block );
489         return NULL;
490     }
491
492     *pp_block = NULL; /* To avoid being fed the same packet again */
493
494     if( p_sys->b_packetizer )
495     {
496         return SendPacket( p_dec, p_oggpacket, p_block );
497     }
498     else
499     {
500         aout_buffer_t *p_aout_buffer;
501
502         if( p_sys->i_headers >= 3 )
503             p_aout_buffer = DecodePacket( p_dec, p_oggpacket );
504         else
505             p_aout_buffer = NULL;
506
507         if( p_block ) block_Release( p_block );
508         return p_aout_buffer;
509     }
510 }
511
512 /*****************************************************************************
513  * DecodePacket: decodes a Vorbis packet.
514  *****************************************************************************/
515 static aout_buffer_t *DecodePacket( decoder_t *p_dec, ogg_packet *p_oggpacket )
516 {
517     decoder_sys_t *p_sys = p_dec->p_sys;
518     int           i_samples;
519
520 #ifdef MODULE_NAME_IS_tremor
521     int32_t       **pp_pcm;
522 #else
523     float         **pp_pcm;
524 #endif
525
526     if( p_oggpacket->bytes &&
527 #ifdef MODULE_NAME_IS_tremor
528         vorbis_synthesis( &p_sys->vb, p_oggpacket, 1 ) == 0 )
529 #else
530         vorbis_synthesis( &p_sys->vb, p_oggpacket ) == 0 )
531 #endif
532         vorbis_synthesis_blockin( &p_sys->vd, &p_sys->vb );
533
534     /* **pp_pcm is a multichannel float vector. In stereo, for
535      * example, pp_pcm[0] is left, and pp_pcm[1] is right. i_samples is
536      * the size of each channel. Convert the float values
537      * (-1.<=range<=1.) to whatever PCM format and write it out */
538
539     if( ( i_samples = vorbis_synthesis_pcmout( &p_sys->vd, &pp_pcm ) ) > 0 )
540     {
541
542         aout_buffer_t *p_aout_buffer;
543
544         p_aout_buffer =
545             decoder_NewAudioBuffer( p_dec, i_samples );
546
547         if( p_aout_buffer == NULL ) return NULL;
548
549         /* Interleave the samples */
550 #ifdef MODULE_NAME_IS_tremor
551         Interleave( (int32_t *)p_aout_buffer->p_buffer,
552                     (const int32_t **)pp_pcm, p_sys->vi.channels, i_samples, p_sys->pi_chan_table);
553 #else
554         Interleave( (float *)p_aout_buffer->p_buffer,
555                     (const float **)pp_pcm, p_sys->vi.channels, i_samples, p_sys->pi_chan_table);
556 #endif
557
558         /* Tell libvorbis how many samples we actually consumed */
559         vorbis_synthesis_read( &p_sys->vd, i_samples );
560
561         /* Date management */
562         p_aout_buffer->i_pts = date_Get( &p_sys->end_date );
563         p_aout_buffer->i_length = date_Increment( &p_sys->end_date,
564                                            i_samples ) - p_aout_buffer->i_pts;
565         return p_aout_buffer;
566     }
567     else
568     {
569         return NULL;
570     }
571 }
572
573 /*****************************************************************************
574  * SendPacket: send an ogg dated packet to the stream output.
575  *****************************************************************************/
576 static block_t *SendPacket( decoder_t *p_dec, ogg_packet *p_oggpacket,
577                             block_t *p_block )
578 {
579     decoder_sys_t *p_sys = p_dec->p_sys;
580     int i_block_size, i_samples;
581
582     i_block_size = vorbis_packet_blocksize( &p_sys->vi, p_oggpacket );
583     if( i_block_size < 0 ) i_block_size = 0; /* non audio packet */
584     i_samples = ( p_sys->i_last_block_size + i_block_size ) >> 2;
585     p_sys->i_last_block_size = i_block_size;
586
587     /* Date management */
588     p_block->i_dts = p_block->i_pts = date_Get( &p_sys->end_date );
589
590     if( p_sys->i_headers >= 3 )
591         p_block->i_length = date_Increment( &p_sys->end_date, i_samples ) - p_block->i_pts;
592     else
593         p_block->i_length = 0;
594
595     return p_block;
596 }
597
598 /*****************************************************************************
599  * ParseVorbisComments
600  *****************************************************************************/
601 static void ParseVorbisComments( decoder_t *p_dec )
602 {
603     char *psz_name, *psz_value, *psz_comment;
604     int i = 0;
605
606     while( i < p_dec->p_sys->vc.comments )
607     {
608         psz_comment = strdup( p_dec->p_sys->vc.user_comments[i] );
609         if( !psz_comment )
610             break;
611         psz_name = psz_comment;
612         psz_value = strchr( psz_comment, '=' );
613         if( psz_value )
614         {
615             *psz_value = '\0';
616             psz_value++;
617
618             if( !p_dec->p_description )
619                 p_dec->p_description = vlc_meta_New();
620             if( p_dec->p_description )
621                 vlc_meta_AddExtra( p_dec->p_description, psz_name, psz_value );
622
623             if( !strcasecmp( psz_name, "REPLAYGAIN_TRACK_GAIN" ) ||
624                      !strcasecmp( psz_name, "RG_RADIO" ) )
625             {
626                 audio_replay_gain_t *r = &p_dec->fmt_out.audio_replay_gain;
627
628                 r->pb_gain[AUDIO_REPLAY_GAIN_TRACK] = true;
629                 r->pf_gain[AUDIO_REPLAY_GAIN_TRACK] = atof( psz_value );
630             }
631             else if( !strcasecmp( psz_name, "REPLAYGAIN_TRACK_PEAK" ) ||
632                      !strcasecmp( psz_name, "RG_PEAK" ) )
633             {
634                 audio_replay_gain_t *r = &p_dec->fmt_out.audio_replay_gain;
635
636                 r->pb_peak[AUDIO_REPLAY_GAIN_TRACK] = true;
637                 r->pf_peak[AUDIO_REPLAY_GAIN_TRACK] = atof( psz_value );
638             }
639             else if( !strcasecmp( psz_name, "REPLAYGAIN_ALBUM_GAIN" ) ||
640                      !strcasecmp( psz_name, "RG_AUDIOPHILE" ) )
641             {
642                 audio_replay_gain_t *r = &p_dec->fmt_out.audio_replay_gain;
643
644                 r->pb_gain[AUDIO_REPLAY_GAIN_ALBUM] = true;
645                 r->pf_gain[AUDIO_REPLAY_GAIN_ALBUM] = atof( psz_value );
646             }
647             else if( !strcasecmp( psz_name, "REPLAYGAIN_ALBUM_PEAK" ) )
648             {
649                 audio_replay_gain_t *r = &p_dec->fmt_out.audio_replay_gain;
650
651                 r->pb_peak[AUDIO_REPLAY_GAIN_ALBUM] = true;
652                 r->pf_peak[AUDIO_REPLAY_GAIN_ALBUM] = atof( psz_value );
653             }
654         }
655         free( psz_comment );
656         i++;
657     }
658 }
659
660 /*****************************************************************************
661  * Interleave: helper function to interleave channels
662  *****************************************************************************/
663 static void ConfigureChannelOrder(int *pi_chan_table, int i_channels, uint32_t i_channel_mask, bool b_decode)
664 {
665     const uint32_t *pi_channels_in;
666     switch( i_channels )
667     {
668         case 6:
669         case 5:
670             pi_channels_in = pi_6channels_in;
671             break;
672         case 4:
673             pi_channels_in = pi_4channels_in;
674             break;
675         case 3:
676             pi_channels_in = pi_3channels_in;
677             break;
678         default:
679             {
680                 int i;
681                 for( i = 0; i< i_channels; ++i )
682                 {
683                     pi_chan_table[i] = i;
684                 }
685                 return;
686             }
687     }
688
689     if( b_decode )
690         aout_CheckChannelReorder( pi_channels_in, NULL,
691                                   i_channel_mask & AOUT_CHAN_PHYSMASK,
692                                   i_channels,
693                                   pi_chan_table );
694     else
695         aout_CheckChannelReorder( NULL, pi_channels_in,
696                                   i_channel_mask & AOUT_CHAN_PHYSMASK,
697                                   i_channels,
698                                   pi_chan_table );
699 }
700
701 /*****************************************************************************
702  * Interleave: helper function to interleave channels
703  *****************************************************************************/
704 #ifdef MODULE_NAME_IS_tremor
705 static void Interleave( int32_t *p_out, const int32_t **pp_in,
706                         int i_nb_channels, int i_samples, int *pi_chan_table)
707 {
708     int i, j;
709
710     for ( j = 0; j < i_samples; j++ )
711         for ( i = 0; i < i_nb_channels; i++ )
712             p_out[j * i_nb_channels + pi_chan_table[i]] = pp_in[i][j] * (FIXED32_ONE >> 24);
713 }
714 #else
715 static void Interleave( float *p_out, const float **pp_in,
716                         int i_nb_channels, int i_samples, int *pi_chan_table )
717 {
718     int i, j;
719
720     for ( j = 0; j < i_samples; j++ )
721         for ( i = 0; i < i_nb_channels; i++ )
722             p_out[j * i_nb_channels + pi_chan_table[i]] = pp_in[i][j];
723 }
724 #endif
725
726 /*****************************************************************************
727  * CloseDecoder: vorbis decoder destruction
728  *****************************************************************************/
729 static void CloseDecoder( vlc_object_t *p_this )
730 {
731     decoder_t *p_dec = (decoder_t *)p_this;
732     decoder_sys_t *p_sys = p_dec->p_sys;
733
734     if( !p_sys->b_packetizer && p_sys->i_headers > 3 )
735     {
736         vorbis_block_clear( &p_sys->vb );
737         vorbis_dsp_clear( &p_sys->vd );
738     }
739
740     vorbis_comment_clear( &p_sys->vc );
741     vorbis_info_clear( &p_sys->vi );  /* must be called last */
742
743     free( p_sys );
744 }
745
746 #ifndef MODULE_NAME_IS_tremor
747
748 /*****************************************************************************
749  * encoder_sys_t : vorbis encoder descriptor
750  *****************************************************************************/
751 struct encoder_sys_t
752 {
753     /*
754      * Vorbis properties
755      */
756     vorbis_info      vi; /* struct that stores all the static vorbis bitstream
757                             settings */
758     vorbis_comment   vc; /* struct that stores all the bitstream user
759                           * comments */
760     vorbis_dsp_state vd; /* central working state for the packet->PCM
761                           * decoder */
762     vorbis_block     vb; /* local working space for packet->PCM decode */
763
764     int i_last_block_size;
765     int i_samples_delay;
766     int i_channels;
767
768     /*
769      * Common properties
770      */
771     mtime_t i_pts;
772
773     /*
774     ** Channel reordering
775     */
776     int pi_chan_table[AOUT_CHAN_MAX];
777
778 };
779
780 /*****************************************************************************
781  * OpenEncoder: probe the encoder and return score
782  *****************************************************************************/
783 static int OpenEncoder( vlc_object_t *p_this )
784 {
785     encoder_t *p_enc = (encoder_t *)p_this;
786     encoder_sys_t *p_sys;
787     int i_quality, i_min_bitrate, i_max_bitrate, i;
788     ogg_packet header[3];
789     vlc_value_t val;
790     uint8_t *p_extra;
791
792     if( p_enc->fmt_out.i_codec != VLC_CODEC_VORBIS &&
793         !p_enc->b_force )
794     {
795         return VLC_EGENERIC;
796     }
797
798     /* Allocate the memory needed to store the decoder's structure */
799     if( ( p_sys = (encoder_sys_t *)malloc(sizeof(encoder_sys_t)) ) == NULL )
800         return VLC_ENOMEM;
801     p_enc->p_sys = p_sys;
802
803     p_enc->pf_encode_audio = Encode;
804     p_enc->fmt_in.i_codec = VLC_CODEC_FL32;
805     p_enc->fmt_out.i_codec = VLC_CODEC_VORBIS;
806
807     config_ChainParse( p_enc, ENC_CFG_PREFIX, ppsz_enc_options, p_enc->p_cfg );
808
809     var_Get( p_enc, ENC_CFG_PREFIX "quality", &val );
810     i_quality = val.i_int;
811     if( i_quality > 10 ) i_quality = 10;
812     if( i_quality < 0 ) i_quality = 0;
813     var_Get( p_enc, ENC_CFG_PREFIX "cbr", &val );
814     if( val.b_bool ) i_quality = 0;
815     var_Get( p_enc, ENC_CFG_PREFIX "max-bitrate", &val );
816     i_max_bitrate = val.i_int;
817     var_Get( p_enc, ENC_CFG_PREFIX "min-bitrate", &val );
818     i_min_bitrate = val.i_int;
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     for( i = 0; i < 3; i++ )
887     {
888         *(p_extra++) = header[i].bytes >> 8;
889         *(p_extra++) = header[i].bytes & 0xFF;
890         memcpy( p_extra, header[i].packet, header[i].bytes );
891         p_extra += header[i].bytes;
892     }
893
894     p_sys->i_channels = p_enc->fmt_in.audio.i_channels;
895     p_sys->i_last_block_size = 0;
896     p_sys->i_samples_delay = 0;
897     p_sys->i_pts = 0;
898
899     ConfigureChannelOrder(p_sys->pi_chan_table, p_sys->vi.channels,
900             p_enc->fmt_in.audio.i_physical_channels, true);
901
902     return VLC_SUCCESS;
903 }
904
905 /****************************************************************************
906  * Encode: the whole thing
907  ****************************************************************************
908  * This function spits out ogg packets.
909  ****************************************************************************/
910 static block_t *Encode( encoder_t *p_enc, aout_buffer_t *p_aout_buf )
911 {
912     encoder_sys_t *p_sys = p_enc->p_sys;
913     ogg_packet oggpacket;
914     block_t *p_block, *p_chain = NULL;
915     float **buffer;
916     int i;
917     unsigned int j;
918
919     p_sys->i_pts = p_aout_buf->i_pts -
920                 (mtime_t)1000000 * (mtime_t)p_sys->i_samples_delay /
921                 (mtime_t)p_enc->fmt_in.audio.i_rate;
922
923     p_sys->i_samples_delay += p_aout_buf->i_nb_samples;
924
925     buffer = vorbis_analysis_buffer( &p_sys->vd, p_aout_buf->i_nb_samples );
926
927     /* convert samples to float and uninterleave */
928     for( i = 0; i < p_sys->i_channels; i++ )
929     {
930         for( j = 0 ; j < p_aout_buf->i_nb_samples ; j++ )
931         {
932             buffer[i][j]= ((float *)p_aout_buf->p_buffer)
933                                     [j * p_sys->i_channels + p_sys->pi_chan_table[i]];
934         }
935     }
936
937     vorbis_analysis_wrote( &p_sys->vd, p_aout_buf->i_nb_samples );
938
939     while( vorbis_analysis_blockout( &p_sys->vd, &p_sys->vb ) == 1 )
940     {
941         int i_samples;
942
943         vorbis_analysis( &p_sys->vb, NULL );
944         vorbis_bitrate_addblock( &p_sys->vb );
945
946         while( vorbis_bitrate_flushpacket( &p_sys->vd, &oggpacket ) )
947         {
948             int i_block_size;
949             p_block = block_New( p_enc, oggpacket.bytes );
950             memcpy( p_block->p_buffer, oggpacket.packet, oggpacket.bytes );
951
952             i_block_size = vorbis_packet_blocksize( &p_sys->vi, &oggpacket );
953
954             if( i_block_size < 0 ) i_block_size = 0;
955             i_samples = ( p_sys->i_last_block_size + i_block_size ) >> 2;
956             p_sys->i_last_block_size = i_block_size;
957
958             p_block->i_length = (mtime_t)1000000 *
959                 (mtime_t)i_samples / (mtime_t)p_enc->fmt_in.audio.i_rate;
960
961             p_block->i_dts = p_block->i_pts = p_sys->i_pts;
962
963             p_sys->i_samples_delay -= i_samples;
964
965             /* Update pts */
966             p_sys->i_pts += p_block->i_length;
967             block_ChainAppend( &p_chain, p_block );
968         }
969     }
970
971     return p_chain;
972 }
973
974 /*****************************************************************************
975  * CloseEncoder: vorbis encoder destruction
976  *****************************************************************************/
977 static void CloseEncoder( vlc_object_t *p_this )
978 {
979     encoder_t *p_enc = (encoder_t *)p_this;
980     encoder_sys_t *p_sys = p_enc->p_sys;
981
982     vorbis_block_clear( &p_sys->vb );
983     vorbis_dsp_clear( &p_sys->vd );
984     vorbis_comment_clear( &p_sys->vc );
985     vorbis_info_clear( &p_sys->vi );  /* must be called last */
986
987     free( p_sys );
988 }
989
990 #endif /* HAVE_VORBIS_VORBISENC_H && !MODULE_NAME_IS_tremor */