]> git.sesse.net Git - vlc/blob - modules/codec/opus.c
codec: opus: fix oob read (cid #1062575)
[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 && p_header->channel_mapping==1) ||
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 && p_header->channels<9 )
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     {
364         block_t *p_aout_buffer = DecodePacket( p_dec, p_oggpacket,
365                                                p_block->i_nb_samples,
366                                                (int)p_block->i_length );
367
368         block_Release( p_block );
369         return p_aout_buffer;
370     }
371 }
372
373 /*****************************************************************************
374  * DecodePacket: decodes a Opus packet.
375  *****************************************************************************/
376 static block_t *DecodePacket( decoder_t *p_dec, ogg_packet *p_oggpacket,
377                               int i_nb_samples, int i_end_trim )
378 {
379     decoder_sys_t *p_sys = p_dec->p_sys;
380
381     if( !p_oggpacket->bytes )
382         return NULL;
383
384     int spp;
385     spp=opus_packet_get_nb_frames(p_oggpacket->packet,p_oggpacket->bytes);
386     if(spp>0)spp*=opus_packet_get_samples_per_frame(p_oggpacket->packet,48000);
387     if(spp<120||spp>120*48)return NULL;
388
389     /* Since the information isn't always available at the demux level
390      * use the packet's sample number */
391     if(!i_nb_samples)
392         i_nb_samples = spp;
393
394     block_t *p_aout_buffer=decoder_NewAudioBuffer( p_dec, spp );
395     if ( !p_aout_buffer )
396     {
397         msg_Err(p_dec, "Oops: No new buffer was returned!");
398         return NULL;
399     }
400
401     spp=opus_multistream_decode_float(p_sys->p_st, p_oggpacket->packet,
402          p_oggpacket->bytes, (float *)p_aout_buffer->p_buffer, spp, 0);
403     if( spp < 0 || i_nb_samples <= 0 || i_end_trim >= i_nb_samples)
404     {
405         block_Release(p_aout_buffer);
406         if( spp < 0 )
407             msg_Err( p_dec, "Error: corrupted stream?" );
408         return NULL;
409     }
410     if( spp > i_nb_samples )
411     {
412         p_aout_buffer->i_buffer = (i_nb_samples - i_end_trim) *
413                                   p_sys->header.channels * sizeof(float);
414         memmove(p_aout_buffer->p_buffer,
415             p_aout_buffer->p_buffer
416             + (spp - i_nb_samples)*p_sys->header.channels*sizeof(float),
417             p_aout_buffer->i_buffer);
418     }
419     i_nb_samples -= i_end_trim;
420
421 #ifndef OPUS_SET_GAIN
422     if(p_sys->header.gain!=0)
423     {
424         float gain = pow(10., p_sys->header.gain/5120.);
425         float *buf =(float *)p_aout_buffer->p_buffer;
426         int i;
427         for( i = 0; i < i_nb_samples*p_sys->header.channels; i++)
428             buf[i] *= gain;
429     }
430 #endif
431     p_aout_buffer->i_nb_samples = i_nb_samples;
432     p_aout_buffer->i_pts = date_Get( &p_sys->end_date );
433     p_aout_buffer->i_length = date_Increment( &p_sys->end_date, i_nb_samples )
434         - p_aout_buffer->i_pts;
435     return p_aout_buffer;
436 }
437
438 /*****************************************************************************
439  * CloseDecoder: Opus decoder destruction
440  *****************************************************************************/
441 static void CloseDecoder( vlc_object_t *p_this )
442 {
443     decoder_t * p_dec = (decoder_t *)p_this;
444     decoder_sys_t *p_sys = p_dec->p_sys;
445
446     if( p_sys->p_st ) opus_multistream_decoder_destroy(p_sys->p_st);
447
448     free( p_sys );
449 }
450
451 #ifdef ENABLE_SOUT
452
453 /* only ever encode 20 ms at a time, going longer doesn't yield much compression
454    gain, shorter does have a compression loss, and doesn't matter so much in
455    Ogg, unless you really need low latency, which would also require muxing one
456    packet per page. */
457 static const unsigned OPUS_FRAME_SIZE = 960; /* 48000 * 20 / 1000 */
458
459 struct encoder_sys_t
460 {
461     OpusMSEncoder *enc;
462     float *buffer;
463     unsigned i_nb_samples;
464     int i_samples_delay;
465     block_t *padding;
466     int nb_streams;
467 };
468
469 static unsigned fill_buffer(encoder_t *enc, unsigned src_start, block_t *src,
470                             unsigned samples)
471 {
472     encoder_sys_t *p_sys = enc->p_sys;
473     const unsigned channels = enc->fmt_out.audio.i_channels;
474     const float *src_buf = ((const float *) src->p_buffer) + src_start;
475     float *dest_buf = p_sys->buffer + (p_sys->i_nb_samples * channels);
476     const unsigned len = samples * channels;
477
478     memcpy(dest_buf, src_buf, len * sizeof(float));
479
480     p_sys->i_nb_samples += samples;
481     src_start += len;
482
483     src->i_nb_samples -= samples;
484     return src_start;
485 }
486
487 static block_t *Encode(encoder_t *enc, block_t *buf)
488 {
489     encoder_sys_t *sys = enc->p_sys;
490
491     if (!buf)
492         return NULL;
493
494     mtime_t i_pts = buf->i_pts -
495                 (mtime_t) CLOCK_FREQ * (mtime_t) sys->i_samples_delay /
496                 (mtime_t) enc->fmt_in.audio.i_rate;
497
498     sys->i_samples_delay += buf->i_nb_samples;
499
500     block_t *result = NULL;
501     unsigned src_start = 0;
502     unsigned padding_start = 0;
503     /* The maximum Opus frame size is 1275 bytes + TOC sequence length. */
504     const unsigned OPUS_MAX_ENCODED_BYTES = ((1275 + 3) * sys->nb_streams) - 2;
505
506     while (sys->i_nb_samples + buf->i_nb_samples >= OPUS_FRAME_SIZE)
507     {
508         block_t *out_block = block_Alloc(OPUS_MAX_ENCODED_BYTES);
509
510         /* add padding to beginning */
511         if (sys->padding)
512         {
513             const size_t leftover_space = OPUS_FRAME_SIZE - sys->i_nb_samples;
514             padding_start = fill_buffer(enc, padding_start, sys->padding,
515                     __MIN(sys->padding->i_nb_samples, leftover_space));
516             if (sys->padding->i_nb_samples <= 0)
517             {
518                 block_Release(sys->padding);
519                 sys->padding = NULL;
520             }
521         }
522
523         /* padding may have been freed either before or inside previous
524          * if-statement */
525         if (!sys->padding)
526         {
527             const size_t leftover_space = OPUS_FRAME_SIZE - sys->i_nb_samples;
528             src_start = fill_buffer(enc, src_start, buf,
529                     __MIN(buf->i_nb_samples, leftover_space));
530         }
531
532         opus_int32 bytes_encoded = opus_multistream_encode_float(sys->enc, sys->buffer,
533                 OPUS_FRAME_SIZE, out_block->p_buffer, out_block->i_buffer);
534
535         if (bytes_encoded < 0)
536         {
537             block_Release(out_block);
538         }
539         else
540         {
541             out_block->i_length = (mtime_t) CLOCK_FREQ *
542                 (mtime_t) OPUS_FRAME_SIZE / (mtime_t) enc->fmt_in.audio.i_rate;
543
544             out_block->i_dts = out_block->i_pts = i_pts;
545
546             sys->i_samples_delay -= OPUS_FRAME_SIZE;
547
548             i_pts += out_block->i_length;
549
550             sys->i_nb_samples = 0;
551
552             out_block->i_buffer = bytes_encoded;
553             block_ChainAppend(&result, out_block);
554         }
555     }
556
557     /* put leftover samples at beginning of buffer */
558     if (buf->i_nb_samples > 0)
559         fill_buffer(enc, src_start, buf, buf->i_nb_samples);
560
561     return result;
562 }
563
564 static int OpenEncoder(vlc_object_t *p_this)
565 {
566     encoder_t *enc = (encoder_t *)p_this;
567
568     if (enc->fmt_out.i_codec != VLC_CODEC_OPUS)
569         return VLC_EGENERIC;
570
571     encoder_sys_t *sys = malloc(sizeof(*sys));
572     if (!sys)
573         return VLC_ENOMEM;
574
575     int status = VLC_SUCCESS;
576     sys->buffer = NULL;
577     sys->enc = NULL;
578
579     enc->pf_encode_audio = Encode;
580     enc->fmt_in.i_codec = VLC_CODEC_FL32;
581     enc->fmt_in.audio.i_rate = /* Only 48kHz */
582     enc->fmt_out.audio.i_rate = 48000;
583     enc->fmt_out.audio.i_channels = enc->fmt_in.audio.i_channels;
584
585     OpusHeader header;
586
587     if (opus_prepare_header(enc->fmt_out.audio.i_channels,
588             enc->fmt_out.audio.i_rate,
589             &header))
590     {
591         msg_Err(enc, "Failed to prepare header.");
592         status = VLC_ENOMEM;
593         goto error;
594     }
595
596     /* needed for max encoded size calculation */
597     sys->nb_streams = header.nb_streams;
598
599     int err;
600     sys->enc =
601         opus_multistream_surround_encoder_create(enc->fmt_in.audio.i_rate,
602                 enc->fmt_in.audio.i_channels, header.channel_mapping,
603                 &header.nb_streams, &header.nb_coupled, header.stream_map,
604                 OPUS_APPLICATION_AUDIO, &err);
605
606     if (err != OPUS_OK)
607     {
608         msg_Err(enc, "Could not create encoder: error %d", err);
609         sys->enc = NULL;
610         status = VLC_EGENERIC;
611         goto error;
612     }
613
614     /* TODO: vbr, bitrate, fec */
615
616     /* Buffer for incoming audio, since opus only accepts frame sizes that are
617        multiples of 2.5ms */
618     enc->p_sys = sys;
619     sys->buffer = malloc(OPUS_FRAME_SIZE * header.channels * sizeof(float));
620     if (!sys->buffer) {
621         status = VLC_ENOMEM;
622         goto error;
623     }
624
625     sys->i_nb_samples = 0;
626
627     sys->i_samples_delay = 0;
628     int ret = opus_multistream_encoder_ctl(enc->p_sys->enc,
629             OPUS_GET_LOOKAHEAD(&sys->i_samples_delay));
630     if (ret != OPUS_OK)
631         msg_Err(enc, "Unable to get number of lookahead samples: %s\n",
632                 opus_strerror(ret));
633
634     header.preskip = sys->i_samples_delay;
635
636     /* Now that we have preskip, we can write the header to extradata */
637     if (opus_write_header((uint8_t **) &enc->fmt_out.p_extra,
638                           &enc->fmt_out.i_extra, &header))
639     {
640         msg_Err(enc, "Failed to write header.");
641         status = VLC_ENOMEM;
642         goto error;
643     }
644
645     if (sys->i_samples_delay > 0)
646     {
647         const unsigned padding_samples = sys->i_samples_delay *
648             enc->fmt_out.audio.i_channels;
649         sys->padding = block_Alloc(padding_samples * sizeof(float));
650         if (!sys->padding) {
651             status = VLC_ENOMEM;
652             goto error;
653         }
654         sys->padding->i_nb_samples = sys->i_samples_delay;
655         float *pad_ptr = (float *) sys->padding->p_buffer;
656         memset(pad_ptr, 0, padding_samples * sizeof(float));
657     }
658     else
659     {
660         sys->padding = NULL;
661     }
662
663     return status;
664
665 error:
666     if (sys->enc)
667         opus_multistream_encoder_destroy(sys->enc);
668     free(sys->buffer);
669     free(sys);
670     return status;
671 }
672
673 static void CloseEncoder(vlc_object_t *p_this)
674 {
675     encoder_t *enc = (encoder_t *)p_this;
676     encoder_sys_t *sys = enc->p_sys;
677
678     opus_multistream_encoder_destroy(sys->enc);
679     if (sys->padding)
680         block_Release(sys->padding);
681     free(sys->buffer);
682     free(sys);
683 }
684 #endif /* ENABLE_SOUT */