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