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