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