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