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