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