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