]> git.sesse.net Git - vlc/blob - modules/codec/opus.c
omxil: Change the default for the omxil-dr flag to true
[vlc] / modules / codec / opus.c
1 /*****************************************************************************
2  * opus.c: opus decoder/encoder module making use of libopus.
3  *****************************************************************************
4  * Copyright (C) 2003-2009, 2012 VLC authors and VideoLAN
5  *
6  * Authors: Gregory Maxwell <greg@xiph.org>
7  * Based on speex.c by: Gildas Bazin <gbazin@videolan.org>
8  *
9  * This program is free software; you can redistribute it and/or modify it
10  * under the terms of the GNU Lesser General Public License as published by
11  * the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public License
20  * along with this program; if not, write to the Free Software Foundation,
21  * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22  *****************************************************************************/
23
24 /*
25  * TODO: preskip, trimming, file duration
26  */
27
28 /*****************************************************************************
29  * Preamble
30  *****************************************************************************/
31 #ifdef HAVE_CONFIG_H
32 # include "config.h"
33 #endif
34
35 #include <vlc_common.h>
36 #include <vlc_plugin.h>
37 #include <vlc_input.h>
38 #include <vlc_codec.h>
39 #include <vlc_aout.h>
40 #include "../demux/xiph.h"
41
42 #include <ogg/ogg.h>
43 #include <opus.h>
44 #include <opus_multistream.h>
45
46 #include "opus_header.h"
47
48 #ifndef OPUS_SET_GAIN
49 #include <math.h>
50 #endif
51
52 /*****************************************************************************
53  * Module descriptor
54  *****************************************************************************/
55 static int  OpenDecoder   ( vlc_object_t * );
56 static void CloseDecoder  ( vlc_object_t * );
57 #ifdef ENABLE_SOUT
58 static int  OpenEncoder   ( vlc_object_t * );
59 static void CloseEncoder  ( vlc_object_t * );
60 #endif
61
62 vlc_module_begin ()
63     set_category( CAT_INPUT )
64     set_subcategory( SUBCAT_INPUT_ACODEC )
65
66     set_description( N_("Opus audio decoder") )
67     set_capability( "decoder", 100 )
68     set_shortname( N_("Opus") )
69     set_callbacks( OpenDecoder, CloseDecoder )
70
71 #ifdef ENABLE_SOUT
72     add_submodule ()
73     set_description( N_("Opus audio encoder") )
74     set_capability( "encoder", 150 )
75     set_shortname( N_("Opus") )
76     set_callbacks( OpenEncoder, CloseEncoder )
77 #endif
78
79 vlc_module_end ()
80
81 /*****************************************************************************
82  * decoder_sys_t : opus decoder descriptor
83  *****************************************************************************/
84 struct decoder_sys_t
85 {
86     /*
87      * Input properties
88      */
89     bool b_has_headers;
90
91     /*
92      * Opus properties
93      */
94     OpusHeader header;
95     OpusMSDecoder *p_st;
96
97     /*
98      * Common properties
99      */
100     date_t end_date;
101 };
102
103 static const int pi_channels_maps[9] =
104 {
105     0,
106     AOUT_CHAN_CENTER,
107     AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT,
108     AOUT_CHAN_CENTER | AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT,
109     AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_REARLEFT
110      | AOUT_CHAN_REARRIGHT,
111     AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_CENTER
112      | AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT,
113     AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_CENTER
114      | AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT | AOUT_CHAN_LFE,
115     AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_CENTER
116      | AOUT_CHAN_REARCENTER | AOUT_CHAN_MIDDLELEFT
117      | AOUT_CHAN_MIDDLERIGHT | AOUT_CHAN_LFE,
118     AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_CENTER | AOUT_CHAN_REARLEFT
119      | AOUT_CHAN_REARRIGHT | AOUT_CHAN_MIDDLELEFT | AOUT_CHAN_MIDDLERIGHT
120      | AOUT_CHAN_LFE,
121 };
122
123 /*
124 **  channel order as defined in http://www.xiph.org/vorbis/doc/Vorbis_I_spec.html#x1-800004.3.9
125 */
126
127 /* recommended vorbis channel order for 8 channels */
128 static const uint32_t pi_8channels_in[] =
129 { AOUT_CHAN_LEFT, AOUT_CHAN_CENTER, AOUT_CHAN_RIGHT,
130   AOUT_CHAN_MIDDLELEFT, AOUT_CHAN_MIDDLERIGHT,
131   AOUT_CHAN_REARLEFT, AOUT_CHAN_REARRIGHT,AOUT_CHAN_LFE, 0 };
132
133 /* recommended vorbis channel order for 7 channels */
134 static const uint32_t pi_7channels_in[] =
135 { AOUT_CHAN_LEFT, AOUT_CHAN_CENTER, AOUT_CHAN_RIGHT,
136   AOUT_CHAN_MIDDLELEFT, AOUT_CHAN_MIDDLERIGHT,
137   AOUT_CHAN_REARCENTER, AOUT_CHAN_LFE, 0 };
138
139 /* recommended vorbis channel order for 6 channels */
140 static const uint32_t pi_6channels_in[] =
141 { AOUT_CHAN_LEFT, AOUT_CHAN_CENTER, AOUT_CHAN_RIGHT,
142   AOUT_CHAN_REARLEFT, AOUT_CHAN_REARRIGHT, AOUT_CHAN_LFE, 0 };
143
144 /* recommended vorbis channel order for 5 channels */
145 static const uint32_t pi_5channels_in[] =
146 { AOUT_CHAN_LEFT, AOUT_CHAN_CENTER, AOUT_CHAN_RIGHT,
147   AOUT_CHAN_REARLEFT, AOUT_CHAN_REARRIGHT, 0 };
148
149 /* recommended vorbis channel order for 4 channels */
150 static const uint32_t pi_4channels_in[] =
151 { AOUT_CHAN_LEFT, AOUT_CHAN_RIGHT, AOUT_CHAN_REARLEFT, AOUT_CHAN_REARRIGHT, 0 };
152
153 /* recommended vorbis channel order for 3 channels */
154 static const uint32_t pi_3channels_in[] =
155 { AOUT_CHAN_LEFT, AOUT_CHAN_CENTER, AOUT_CHAN_RIGHT, 0 };
156
157 /****************************************************************************
158  * Local prototypes
159  ****************************************************************************/
160
161 static block_t *DecodeBlock  ( decoder_t *, block_t ** );
162 static int  ProcessHeaders( decoder_t * );
163 static int  ProcessInitialHeader ( decoder_t *, ogg_packet * );
164 static void *ProcessPacket( decoder_t *, ogg_packet *, block_t ** );
165
166 static block_t *DecodePacket( decoder_t *, ogg_packet *, int, int );
167
168 /*****************************************************************************
169  * OpenDecoder: probe the decoder and return score
170  *****************************************************************************/
171 static int OpenDecoder( vlc_object_t *p_this )
172 {
173     decoder_t *p_dec = (decoder_t*)p_this;
174     decoder_sys_t *p_sys;
175
176     if( p_dec->fmt_in.i_codec != VLC_CODEC_OPUS )
177         return VLC_EGENERIC;
178
179     /* Allocate the memory needed to store the decoder's structure */
180     if( ( p_dec->p_sys = p_sys = malloc(sizeof(decoder_sys_t)) ) == NULL )
181         return VLC_ENOMEM;
182     p_dec->p_sys->b_has_headers = false;
183
184     date_Set( &p_sys->end_date, 0 );
185
186     /* Set output properties */
187     p_dec->fmt_out.i_cat = AUDIO_ES;
188     p_dec->fmt_out.i_codec = VLC_CODEC_FL32;
189
190     p_dec->pf_decode_audio = DecodeBlock;
191     p_dec->pf_packetize    = DecodeBlock;
192
193     p_sys->p_st = NULL;
194
195     return VLC_SUCCESS;
196 }
197
198 /****************************************************************************
199  * DecodeBlock: the whole thing
200  ****************************************************************************
201  * This function must be fed with ogg packets.
202  ****************************************************************************/
203 static block_t *DecodeBlock( decoder_t *p_dec, block_t **pp_block )
204 {
205     decoder_sys_t *p_sys = p_dec->p_sys;
206     ogg_packet oggpacket;
207
208     if( !pp_block || !*pp_block)
209         return NULL;
210
211     /* Block to Ogg packet */
212     oggpacket.packet = (*pp_block)->p_buffer;
213     oggpacket.bytes = (*pp_block)->i_buffer;
214
215     oggpacket.granulepos = -1;
216     oggpacket.b_o_s = 0;
217     oggpacket.e_o_s = 0;
218     oggpacket.packetno = 0;
219
220     /* Check for headers */
221     if( !p_sys->b_has_headers )
222     {
223         if( ProcessHeaders( p_dec ) )
224         {
225             block_Release( *pp_block );
226             return NULL;
227         }
228         p_sys->b_has_headers = true;
229     }
230
231     return ProcessPacket( p_dec, &oggpacket, pp_block );
232 }
233
234 /*****************************************************************************
235  * ProcessHeaders: process Opus headers.
236  *****************************************************************************/
237 static int ProcessHeaders( decoder_t *p_dec )
238 {
239     ogg_packet oggpacket;
240
241     unsigned pi_size[XIPH_MAX_HEADER_COUNT];
242     void     *pp_data[XIPH_MAX_HEADER_COUNT];
243     unsigned i_count;
244
245     if( xiph_SplitHeaders( pi_size, pp_data, &i_count,
246                            p_dec->fmt_in.i_extra, p_dec->fmt_in.p_extra) )
247         return VLC_EGENERIC;
248     if( i_count < 2 )
249         return VLC_EGENERIC;;
250
251     oggpacket.granulepos = -1;
252     oggpacket.e_o_s = 0;
253     oggpacket.packetno = 0;
254
255     /* Take care of the initial Opus header */
256     oggpacket.b_o_s = 1; /* yes this actually is a b_o_s packet :) */
257     oggpacket.bytes  = pi_size[0];
258     oggpacket.packet = pp_data[0];
259     int ret = ProcessInitialHeader( p_dec, &oggpacket );
260
261     if (ret != VLC_SUCCESS)
262         msg_Err( p_dec, "initial Opus header is corrupted" );
263
264     return ret;
265 }
266
267 /*****************************************************************************
268  * ProcessInitialHeader: processes the inital Opus header packet.
269  *****************************************************************************/
270 static int ProcessInitialHeader( decoder_t *p_dec, ogg_packet *p_oggpacket )
271 {
272     int err;
273     unsigned char new_stream_map[8];
274     decoder_sys_t *p_sys = p_dec->p_sys;
275
276     OpusHeader *p_header = &p_sys->header;
277
278     if( !opus_header_parse((unsigned char *)p_oggpacket->packet,p_oggpacket->bytes,p_header) )
279     {
280         msg_Err( p_dec, "cannot read Opus header" );
281         return VLC_EGENERIC;
282     }
283     msg_Dbg( p_dec, "Opus audio with %d channels", p_header->channels);
284
285     if((p_header->channels>2 && p_header->channel_mapping==0) ||
286         p_header->channels>8 ||
287         p_header->channel_mapping>1)
288     {
289         msg_Err( p_dec, "Unsupported channel mapping" );
290         return VLC_EGENERIC;
291     }
292
293     /* Setup the format */
294     p_dec->fmt_out.audio.i_physical_channels =
295         p_dec->fmt_out.audio.i_original_channels =
296             pi_channels_maps[p_header->channels];
297     p_dec->fmt_out.audio.i_channels = p_header->channels;
298     p_dec->fmt_out.audio.i_rate = 48000;
299
300     if( p_header->channels>2 )
301     {
302         static const uint32_t *pi_ch[6] = { pi_3channels_in, pi_4channels_in,
303                                             pi_5channels_in, pi_6channels_in,
304                                             pi_7channels_in, pi_8channels_in };
305         uint8_t pi_chan_table[AOUT_CHAN_MAX];
306
307         aout_CheckChannelReorder( pi_ch[p_header->channels-3], NULL,
308                                   p_dec->fmt_out.audio.i_physical_channels,
309                                   pi_chan_table );
310         for(int i=0;i<p_header->channels;i++)
311             new_stream_map[pi_chan_table[i]]=p_header->stream_map[i];
312     }
313     /* Opus decoder init */
314     p_sys->p_st = opus_multistream_decoder_create( 48000, p_header->channels,
315                     p_header->nb_streams, p_header->nb_coupled,
316                     p_header->channels>2?new_stream_map:p_header->stream_map,
317                     &err );
318     if( !p_sys->p_st || err!=OPUS_OK )
319     {
320         msg_Err( p_dec, "decoder initialization failed" );
321         return VLC_EGENERIC;
322     }
323
324 #ifdef OPUS_SET_GAIN
325     if( opus_multistream_decoder_ctl( p_sys->p_st,OPUS_SET_GAIN(p_header->gain) ) != OPUS_OK )
326     {
327         msg_Err( p_dec, "OPUS_SET_GAIN failed" );
328         opus_multistream_decoder_destroy( p_sys->p_st );
329         return VLC_EGENERIC;
330     }
331 #endif
332
333     date_Init( &p_sys->end_date, 48000, 1 );
334
335     return VLC_SUCCESS;
336 }
337
338 /*****************************************************************************
339  * ProcessPacket: processes a Opus packet.
340  *****************************************************************************/
341 static void *ProcessPacket( decoder_t *p_dec, ogg_packet *p_oggpacket,
342                             block_t **pp_block )
343 {
344     decoder_sys_t *p_sys = p_dec->p_sys;
345     block_t *p_block = *pp_block;
346
347     /* Date management */
348     if( p_block && p_block->i_pts > VLC_TS_INVALID &&
349         p_block->i_pts != date_Get( &p_sys->end_date ) )
350     {
351         date_Set( &p_sys->end_date, p_block->i_pts );
352     }
353
354     if( !date_Get( &p_sys->end_date ) )
355     {
356         /* We've just started the stream, wait for the first PTS. */
357         if( p_block ) block_Release( p_block );
358         return NULL;
359     }
360
361     *pp_block = NULL; /* To avoid being fed the same packet again */
362
363     if( !p_block )
364         return NULL;
365
366     block_t *p_aout_buffer = DecodePacket( p_dec, p_oggpacket,
367                                            p_block->i_nb_samples,
368                                            (int)p_block->i_length );
369
370     block_Release( p_block );
371     return p_aout_buffer;
372 }
373
374 /*****************************************************************************
375  * DecodePacket: decodes a Opus packet.
376  *****************************************************************************/
377 static block_t *DecodePacket( decoder_t *p_dec, ogg_packet *p_oggpacket,
378                               int i_nb_samples, int i_end_trim )
379 {
380     decoder_sys_t *p_sys = p_dec->p_sys;
381
382     if( !p_oggpacket->bytes )
383         return NULL;
384
385     int spp;
386     spp=opus_packet_get_nb_frames(p_oggpacket->packet,p_oggpacket->bytes);
387     if(spp>0)spp*=opus_packet_get_samples_per_frame(p_oggpacket->packet,48000);
388     if(spp<120||spp>120*48)return NULL;
389
390     /* Since the information isn't always available at the demux level
391      * use the packet's sample number */
392     if(!i_nb_samples)
393         i_nb_samples = spp;
394
395     block_t *p_aout_buffer=decoder_NewAudioBuffer( p_dec, spp );
396     if ( !p_aout_buffer )
397     {
398         msg_Err(p_dec, "Oops: No new buffer was returned!");
399         return NULL;
400     }
401
402     spp=opus_multistream_decode_float(p_sys->p_st, p_oggpacket->packet,
403          p_oggpacket->bytes, (float *)p_aout_buffer->p_buffer, spp, 0);
404     if( spp < 0 || i_nb_samples <= 0 || i_end_trim >= i_nb_samples)
405     {
406         block_Release(p_aout_buffer);
407         if( spp < 0 )
408             msg_Err( p_dec, "Error: corrupted stream?" );
409         return NULL;
410     }
411
412     p_aout_buffer->i_buffer = (i_nb_samples - i_end_trim) *
413                               p_sys->header.channels * sizeof(float);
414
415     if( spp > i_nb_samples )
416     {
417         memmove(p_aout_buffer->p_buffer,
418             p_aout_buffer->p_buffer
419             + (spp - i_nb_samples)*p_sys->header.channels*sizeof(float),
420             p_aout_buffer->i_buffer);
421     }
422     i_nb_samples -= i_end_trim;
423
424 #ifndef OPUS_SET_GAIN
425     if(p_sys->header.gain!=0)
426     {
427         float gain = pow(10., p_sys->header.gain/5120.);
428         float *buf =(float *)p_aout_buffer->p_buffer;
429         int i;
430         for( i = 0; i < i_nb_samples*p_sys->header.channels; i++)
431             buf[i] *= gain;
432     }
433 #endif
434     p_aout_buffer->i_nb_samples = i_nb_samples;
435     p_aout_buffer->i_pts = date_Get( &p_sys->end_date );
436     p_aout_buffer->i_length = date_Increment( &p_sys->end_date, i_nb_samples )
437         - p_aout_buffer->i_pts;
438     return p_aout_buffer;
439 }
440
441 /*****************************************************************************
442  * CloseDecoder: Opus decoder destruction
443  *****************************************************************************/
444 static void CloseDecoder( vlc_object_t *p_this )
445 {
446     decoder_t * p_dec = (decoder_t *)p_this;
447     decoder_sys_t *p_sys = p_dec->p_sys;
448
449     if( p_sys->p_st ) opus_multistream_decoder_destroy(p_sys->p_st);
450
451     free( p_sys );
452 }
453
454 #ifdef ENABLE_SOUT
455
456 /* only ever encode 20 ms at a time, going longer doesn't yield much compression
457    gain, shorter does have a compression loss, and doesn't matter so much in
458    Ogg, unless you really need low latency, which would also require muxing one
459    packet per page. */
460 static const unsigned OPUS_FRAME_SIZE = 960; /* 48000 * 20 / 1000 */
461
462 struct encoder_sys_t
463 {
464     OpusMSEncoder *enc;
465     float *buffer;
466     unsigned i_nb_samples;
467     int i_samples_delay;
468     block_t *padding;
469     int nb_streams;
470 };
471
472 static unsigned fill_buffer(encoder_t *enc, unsigned src_start, block_t *src,
473                             unsigned samples)
474 {
475     encoder_sys_t *p_sys = enc->p_sys;
476     const unsigned channels = enc->fmt_out.audio.i_channels;
477     const float *src_buf = ((const float *) src->p_buffer) + src_start;
478     float *dest_buf = p_sys->buffer + (p_sys->i_nb_samples * channels);
479     const unsigned len = samples * channels;
480
481     memcpy(dest_buf, src_buf, len * sizeof(float));
482
483     p_sys->i_nb_samples += samples;
484     src_start += len;
485
486     src->i_nb_samples -= samples;
487     return src_start;
488 }
489
490 static block_t *Encode(encoder_t *enc, block_t *buf)
491 {
492     encoder_sys_t *sys = enc->p_sys;
493
494     if (!buf)
495         return NULL;
496
497     mtime_t i_pts = buf->i_pts -
498                 (mtime_t) CLOCK_FREQ * (mtime_t) sys->i_samples_delay /
499                 (mtime_t) enc->fmt_in.audio.i_rate;
500
501     sys->i_samples_delay += buf->i_nb_samples;
502
503     block_t *result = NULL;
504     unsigned src_start = 0;
505     unsigned padding_start = 0;
506     /* The maximum Opus frame size is 1275 bytes + TOC sequence length. */
507     const unsigned OPUS_MAX_ENCODED_BYTES = ((1275 + 3) * sys->nb_streams) - 2;
508
509     while (sys->i_nb_samples + buf->i_nb_samples >= OPUS_FRAME_SIZE)
510     {
511         block_t *out_block = block_Alloc(OPUS_MAX_ENCODED_BYTES);
512
513         /* add padding to beginning */
514         if (sys->padding)
515         {
516             const size_t leftover_space = OPUS_FRAME_SIZE - sys->i_nb_samples;
517             padding_start = fill_buffer(enc, padding_start, sys->padding,
518                     __MIN(sys->padding->i_nb_samples, leftover_space));
519             if (sys->padding->i_nb_samples <= 0)
520             {
521                 block_Release(sys->padding);
522                 sys->padding = NULL;
523             }
524         }
525
526         /* padding may have been freed either before or inside previous
527          * if-statement */
528         if (!sys->padding)
529         {
530             const size_t leftover_space = OPUS_FRAME_SIZE - sys->i_nb_samples;
531             src_start = fill_buffer(enc, src_start, buf,
532                     __MIN(buf->i_nb_samples, leftover_space));
533         }
534
535         opus_int32 bytes_encoded = opus_multistream_encode_float(sys->enc, sys->buffer,
536                 OPUS_FRAME_SIZE, out_block->p_buffer, out_block->i_buffer);
537
538         if (bytes_encoded < 0)
539         {
540             block_Release(out_block);
541         }
542         else
543         {
544             out_block->i_length = (mtime_t) CLOCK_FREQ *
545                 (mtime_t) OPUS_FRAME_SIZE / (mtime_t) enc->fmt_in.audio.i_rate;
546
547             out_block->i_dts = out_block->i_pts = i_pts;
548
549             sys->i_samples_delay -= OPUS_FRAME_SIZE;
550
551             i_pts += out_block->i_length;
552
553             sys->i_nb_samples = 0;
554
555             out_block->i_buffer = bytes_encoded;
556             block_ChainAppend(&result, out_block);
557         }
558     }
559
560     /* put leftover samples at beginning of buffer */
561     if (buf->i_nb_samples > 0)
562         fill_buffer(enc, src_start, buf, buf->i_nb_samples);
563
564     return result;
565 }
566
567 static int OpenEncoder(vlc_object_t *p_this)
568 {
569     encoder_t *enc = (encoder_t *)p_this;
570
571     if (enc->fmt_out.i_codec != VLC_CODEC_OPUS)
572         return VLC_EGENERIC;
573
574     encoder_sys_t *sys = malloc(sizeof(*sys));
575     if (!sys)
576         return VLC_ENOMEM;
577
578     int status = VLC_SUCCESS;
579     sys->buffer = NULL;
580     sys->enc = NULL;
581
582     enc->pf_encode_audio = Encode;
583     enc->fmt_in.i_codec = VLC_CODEC_FL32;
584     enc->fmt_in.audio.i_rate = /* Only 48kHz */
585     enc->fmt_out.audio.i_rate = 48000;
586     enc->fmt_out.audio.i_channels = enc->fmt_in.audio.i_channels;
587
588     OpusHeader header;
589
590     if (opus_prepare_header(enc->fmt_out.audio.i_channels,
591             enc->fmt_out.audio.i_rate,
592             &header))
593     {
594         msg_Err(enc, "Failed to prepare header.");
595         status = VLC_ENOMEM;
596         goto error;
597     }
598
599     /* needed for max encoded size calculation */
600     sys->nb_streams = header.nb_streams;
601
602     int err;
603     sys->enc =
604         opus_multistream_surround_encoder_create(enc->fmt_in.audio.i_rate,
605                 enc->fmt_in.audio.i_channels, header.channel_mapping,
606                 &header.nb_streams, &header.nb_coupled, header.stream_map,
607                 OPUS_APPLICATION_AUDIO, &err);
608
609     if (err != OPUS_OK)
610     {
611         msg_Err(enc, "Could not create encoder: error %d", err);
612         sys->enc = NULL;
613         status = VLC_EGENERIC;
614         goto error;
615     }
616
617     /* TODO: vbr, fec */
618
619     if( enc->fmt_out.i_bitrate )
620         opus_multistream_encoder_ctl(sys->enc, OPUS_SET_BITRATE( enc->fmt_out.i_bitrate ));
621
622     /* Buffer for incoming audio, since opus only accepts frame sizes that are
623        multiples of 2.5ms */
624     enc->p_sys = sys;
625     sys->buffer = malloc(OPUS_FRAME_SIZE * header.channels * sizeof(float));
626     if (!sys->buffer) {
627         status = VLC_ENOMEM;
628         goto error;
629     }
630
631     sys->i_nb_samples = 0;
632
633     sys->i_samples_delay = 0;
634     int ret = opus_multistream_encoder_ctl(enc->p_sys->enc,
635             OPUS_GET_LOOKAHEAD(&sys->i_samples_delay));
636     if (ret != OPUS_OK)
637         msg_Err(enc, "Unable to get number of lookahead samples: %s\n",
638                 opus_strerror(ret));
639
640     header.preskip = sys->i_samples_delay;
641
642     /* Now that we have preskip, we can write the header to extradata */
643     if (opus_write_header((uint8_t **) &enc->fmt_out.p_extra,
644                           &enc->fmt_out.i_extra, &header, opus_get_version_string()))
645     {
646         msg_Err(enc, "Failed to write header.");
647         status = VLC_ENOMEM;
648         goto error;
649     }
650
651     if (sys->i_samples_delay > 0)
652     {
653         const unsigned padding_samples = sys->i_samples_delay *
654             enc->fmt_out.audio.i_channels;
655         sys->padding = block_Alloc(padding_samples * sizeof(float));
656         if (!sys->padding) {
657             status = VLC_ENOMEM;
658             goto error;
659         }
660         sys->padding->i_nb_samples = sys->i_samples_delay;
661         float *pad_ptr = (float *) sys->padding->p_buffer;
662         memset(pad_ptr, 0, padding_samples * sizeof(float));
663     }
664     else
665     {
666         sys->padding = NULL;
667     }
668
669     return status;
670
671 error:
672     if (sys->enc)
673         opus_multistream_encoder_destroy(sys->enc);
674     free(sys->buffer);
675     free(sys);
676     return status;
677 }
678
679 static void CloseEncoder(vlc_object_t *p_this)
680 {
681     encoder_t *enc = (encoder_t *)p_this;
682     encoder_sys_t *sys = enc->p_sys;
683
684     opus_multistream_encoder_destroy(sys->enc);
685     if (sys->padding)
686         block_Release(sys->padding);
687     free(sys->buffer);
688     free(sys);
689 }
690 #endif /* ENABLE_SOUT */