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