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