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