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