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