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