]> git.sesse.net Git - vlc/blob - modules/demux/avformat/mux.c
avformat mux: transmit Opus extradata in the expected format
[vlc] / modules / demux / avformat / mux.c
1 /*****************************************************************************
2  * mux.c: muxer using libavformat
3  *****************************************************************************
4  * Copyright (C) 2006 VLC authors and 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 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
28 #ifdef HAVE_CONFIG_H
29 # include "config.h"
30 #endif
31
32 #include <vlc_common.h>
33 #include <vlc_block.h>
34 #include <vlc_sout.h>
35
36 #include <libavformat/avformat.h>
37
38 #include "avformat.h"
39 #include "../../codec/avcodec/avcodec.h"
40 #include "../../codec/avcodec/avcommon.h"
41 #include "../xiph.h"
42
43
44 //#define AVFORMAT_DEBUG 1
45
46 static const char *const ppsz_mux_options[] = {
47     "mux", "options", NULL
48 };
49
50 /*****************************************************************************
51  * mux_sys_t: mux descriptor
52  *****************************************************************************/
53 struct sout_mux_sys_t
54 {
55     AVIOContext     *io;
56     int             io_buffer_size;
57     uint8_t        *io_buffer;
58
59     AVFormatContext *oc;
60
61     bool     b_write_header;
62     bool     b_write_keyframe;
63     bool     b_error;
64 };
65
66 /*****************************************************************************
67  * Local prototypes
68  *****************************************************************************/
69 static int Control  ( sout_mux_t *, int, va_list );
70 static int AddStream( sout_mux_t *, sout_input_t * );
71 static int DelStream( sout_mux_t *, sout_input_t * );
72 static int Mux      ( sout_mux_t * );
73
74 static int IOWrite( void *opaque, uint8_t *buf, int buf_size );
75 static int64_t IOSeek( void *opaque, int64_t offset, int whence );
76
77 /*****************************************************************************
78  * Open
79  *****************************************************************************/
80 int OpenMux( vlc_object_t *p_this )
81 {
82     AVOutputFormat *file_oformat;
83     sout_mux_t *p_mux = (sout_mux_t*)p_this;
84     sout_mux_sys_t *p_sys;
85     char *psz_mux;
86
87     vlc_init_avformat(p_this);
88
89     config_ChainParse( p_mux, "sout-avformat-", ppsz_mux_options, p_mux->p_cfg );
90
91     /* Find the requested muxer */
92     psz_mux = var_GetNonEmptyString( p_mux, "sout-avformat-mux" );
93     if( psz_mux )
94     {
95         file_oformat = av_guess_format( psz_mux, NULL, NULL );
96         free( psz_mux );
97     }
98     else
99     {
100         file_oformat =
101             av_guess_format( NULL, p_mux->p_access->psz_path, NULL);
102     }
103     if (!file_oformat)
104     {
105       msg_Err( p_mux, "unable for find a suitable output format" );
106       return VLC_EGENERIC;
107     }
108
109     p_mux->p_sys = p_sys = malloc( sizeof( sout_mux_sys_t ) );
110     if( !p_sys )
111         return VLC_ENOMEM;
112
113     p_sys->oc = avformat_alloc_context();
114     p_sys->oc->oformat = file_oformat;
115     /* If we use dummy access, let avformat write output */
116     if( !strcmp( p_mux->p_access->psz_access, "dummy") )
117         strcpy( p_sys->oc->filename, p_mux->p_access->psz_path );
118
119     /* Create I/O wrapper */
120     p_sys->io_buffer_size = 10 * 1024 * 1024;  /* FIXME */
121     p_sys->io_buffer = malloc( p_sys->io_buffer_size );
122
123     bool b_can_seek;
124     if( sout_AccessOutControl( p_mux->p_access, ACCESS_OUT_CAN_SEEK, &b_can_seek ) )
125         b_can_seek = false;
126     p_sys->io = avio_alloc_context(
127         p_sys->io_buffer, p_sys->io_buffer_size,
128         1, p_mux, NULL, IOWrite, b_can_seek ? IOSeek : NULL );
129
130     p_sys->oc->pb = p_sys->io;
131     p_sys->oc->nb_streams = 0;
132
133     p_sys->b_write_header = true;
134     p_sys->b_write_keyframe = false;
135     p_sys->b_error = false;
136
137     /* Fill p_mux fields */
138     p_mux->pf_control   = Control;
139     p_mux->pf_addstream = AddStream;
140     p_mux->pf_delstream = DelStream;
141     p_mux->pf_mux       = Mux;
142
143     return VLC_SUCCESS;
144 }
145
146 /*****************************************************************************
147  * Close
148  *****************************************************************************/
149 void CloseMux( vlc_object_t *p_this )
150 {
151     sout_mux_t *p_mux = (sout_mux_t*)p_this;
152     sout_mux_sys_t *p_sys = p_mux->p_sys;
153
154     if( !p_sys->b_write_header && !p_sys->b_error && av_write_trailer( p_sys->oc ) < 0 )
155     {
156         msg_Err( p_mux, "could not write trailer" );
157     }
158
159     avformat_free_context(p_sys->oc);
160
161     free( p_sys->io_buffer );
162     free( p_sys );
163 }
164
165 /*****************************************************************************
166  * AddStream
167  *****************************************************************************/
168 static int AddStream( sout_mux_t *p_mux, sout_input_t *p_input )
169 {
170     sout_mux_sys_t *p_sys = p_mux->p_sys;
171     es_format_t *fmt = p_input->p_fmt;
172     AVCodecContext *codec;
173     AVStream *stream;
174     unsigned i_codec_id;
175
176     msg_Dbg( p_mux, "adding input" );
177
178     if( !GetFfmpegCodec( fmt->i_codec, 0, &i_codec_id, 0 ) )
179     {
180         msg_Dbg( p_mux, "couldn't find codec for fourcc '%4.4s'",
181                  (char *)&fmt->i_codec );
182         return VLC_EGENERIC;
183     }
184
185     unsigned opus_size[XIPH_MAX_HEADER_COUNT];
186     void     *opus_packet[XIPH_MAX_HEADER_COUNT];
187     if( fmt->i_codec == VLC_CODEC_OPUS )
188     {
189         unsigned count;
190         /* Only transmits the first packet (OpusHead) */
191         if( xiph_SplitHeaders(opus_size, opus_packet, &count, fmt->i_extra, fmt->p_extra ) ) {
192             count = 0;
193         }
194         if (count != 2 || opus_size[0] < 19) {
195             msg_Err(p_mux, "Invalid Opus header");
196             return VLC_EGENERIC;
197         }
198     }
199
200     p_input->p_sys = malloc( sizeof( int ) );
201     *((int *)p_input->p_sys) = p_sys->oc->nb_streams;
202
203     if( fmt->i_cat != VIDEO_ES && fmt->i_cat != AUDIO_ES)
204     {
205         msg_Warn( p_mux, "Unhandled ES category" );
206         return VLC_EGENERIC;
207     }
208
209     stream = avformat_new_stream( p_sys->oc, NULL);
210     if( !stream )
211     {
212         free( p_input->p_sys );
213         return VLC_EGENERIC;
214     }
215     codec = stream->codec;
216
217     codec->opaque = p_mux;
218
219     switch( fmt->i_cat )
220     {
221     case AUDIO_ES:
222         codec->codec_type = AVMEDIA_TYPE_AUDIO;
223         codec->channels = fmt->audio.i_channels;
224         codec->sample_rate = fmt->audio.i_rate;
225         codec->time_base = (AVRational){1, codec->sample_rate};
226         codec->frame_size = fmt->audio.i_frame_length;
227         break;
228
229     case VIDEO_ES:
230         if( !fmt->video.i_frame_rate ||
231             !fmt->video.i_frame_rate_base )
232         {
233             msg_Warn( p_mux, "Missing frame rate, assuming 25fps" );
234             fmt->video.i_frame_rate = 25;
235             fmt->video.i_frame_rate_base = 1;
236         }
237         codec->codec_type = AVMEDIA_TYPE_VIDEO;
238         codec->width = fmt->video.i_width;
239         codec->height = fmt->video.i_height;
240         av_reduce( &codec->sample_aspect_ratio.num,
241                    &codec->sample_aspect_ratio.den,
242                    fmt->video.i_sar_num,
243                    fmt->video.i_sar_den, 1 << 30 /* something big */ );
244         stream->sample_aspect_ratio.den = codec->sample_aspect_ratio.den;
245         stream->sample_aspect_ratio.num = codec->sample_aspect_ratio.num;
246         codec->time_base.den = fmt->video.i_frame_rate;
247         codec->time_base.num = fmt->video.i_frame_rate_base;
248         break;
249
250     }
251
252     codec->bit_rate = fmt->i_bitrate;
253     codec->codec_tag = av_codec_get_tag( p_sys->oc->oformat->codec_tag, i_codec_id );
254     if( !codec->codec_tag && i_codec_id == AV_CODEC_ID_MP2 )
255     {
256         i_codec_id = AV_CODEC_ID_MP3;
257         codec->codec_tag = av_codec_get_tag( p_sys->oc->oformat->codec_tag, i_codec_id );
258     }
259     codec->codec_id = i_codec_id;
260
261     if( fmt->i_extra )
262     {
263         if( fmt->i_codec == VLC_CODEC_OPUS )
264         {
265             codec->extradata_size = opus_size[0];
266             codec->extradata = av_malloc( opus_size[0] );
267             memcpy( codec->extradata, opus_packet[0], opus_size[0] );
268         }
269         else
270         {
271             codec->extradata_size = fmt->i_extra;
272             codec->extradata = av_malloc( fmt->i_extra );
273             memcpy( codec->extradata, fmt->p_extra, fmt->i_extra );
274         }
275     }
276
277     return VLC_SUCCESS;
278 }
279
280 /*****************************************************************************
281  * DelStream
282  *****************************************************************************/
283 static int DelStream( sout_mux_t *p_mux, sout_input_t *p_input )
284 {
285     msg_Dbg( p_mux, "removing input" );
286     free( p_input->p_sys );
287     return VLC_SUCCESS;
288 }
289
290 static int MuxBlock( sout_mux_t *p_mux, sout_input_t *p_input )
291 {
292     sout_mux_sys_t *p_sys = p_mux->p_sys;
293     block_t *p_data = block_FifoGet( p_input->p_fifo );
294     int i_stream = *((int *)p_input->p_sys);
295     AVStream *p_stream = p_sys->oc->streams[i_stream];
296     AVPacket pkt;
297
298     memset( &pkt, 0, sizeof(AVPacket) );
299
300     av_init_packet(&pkt);
301     pkt.data = p_data->p_buffer;
302     pkt.size = p_data->i_buffer;
303     pkt.stream_index = i_stream;
304
305     if( p_data->i_flags & BLOCK_FLAG_TYPE_I )
306     {
307 #ifdef AVFMT_ALLOW_FLUSH
308         /* Make sure we don't inadvertedly mark buffered data as keyframes. */
309         if( p_sys->oc->oformat->flags & AVFMT_ALLOW_FLUSH )
310             av_write_frame( p_sys->oc, NULL );
311 #endif
312
313         p_sys->b_write_keyframe = true;
314         pkt.flags |= AV_PKT_FLAG_KEY;
315     }
316
317     if( p_data->i_pts > 0 )
318         pkt.pts = p_data->i_pts * p_stream->time_base.den /
319             CLOCK_FREQ / p_stream->time_base.num;
320     if( p_data->i_dts > 0 )
321         pkt.dts = p_data->i_dts * p_stream->time_base.den /
322             CLOCK_FREQ / p_stream->time_base.num;
323
324     /* this is another hack to prevent libavformat from triggering the "non monotone timestamps" check in avformat/utils.c */
325     p_stream->cur_dts = ( p_data->i_dts * p_stream->time_base.den /
326             CLOCK_FREQ / p_stream->time_base.num ) - 1;
327
328     if( av_write_frame( p_sys->oc, &pkt ) < 0 )
329     {
330         msg_Err( p_mux, "could not write frame (pts: %"PRId64", dts: %"PRId64") "
331                  "(pkt pts: %"PRId64", dts: %"PRId64")",
332                  p_data->i_pts, p_data->i_dts, pkt.pts, pkt.dts );
333         block_Release( p_data );
334         return VLC_EGENERIC;
335     }
336
337     block_Release( p_data );
338     return VLC_SUCCESS;
339 }
340
341 /*****************************************************************************
342  * Mux: multiplex available data in input fifos
343  *****************************************************************************/
344 static int Mux( sout_mux_t *p_mux )
345 {
346     sout_mux_sys_t *p_sys = p_mux->p_sys;
347
348     if( p_sys->b_error ) return VLC_EGENERIC;
349
350     if( p_sys->b_write_header )
351     {
352         int error;
353         msg_Dbg( p_mux, "writing header" );
354
355         char *psz_opts = var_GetNonEmptyString( p_mux, "sout-avformat-options" );
356         AVDictionary *options = NULL;
357         if (psz_opts && *psz_opts)
358             options = vlc_av_get_options(psz_opts);
359         free(psz_opts);
360         error = avformat_write_header( p_sys->oc, options ? &options : NULL);
361         AVDictionaryEntry *t = NULL;
362         while ((t = av_dict_get(options, "", t, AV_DICT_IGNORE_SUFFIX))) {
363             msg_Err( p_mux, "Unknown option \"%s\"", t->key );
364         }
365         av_dict_free(&options);
366         if( error < 0 )
367         {
368             msg_Err( p_mux, "could not write header: %s",
369                      vlc_strerror_c(AVUNERROR(error)) );
370             p_sys->b_write_header = false;
371             p_sys->b_error = true;
372             return VLC_EGENERIC;
373         }
374
375         avio_flush( p_sys->oc->pb );
376         p_sys->b_write_header = false;
377     }
378
379     for( ;; )
380     {
381         mtime_t i_dts;
382
383         int i_stream = sout_MuxGetStream( p_mux, 1, &i_dts );
384         if( i_stream < 0 )
385             return VLC_SUCCESS;
386
387         MuxBlock( p_mux, p_mux->pp_inputs[i_stream] );
388     }
389
390     return VLC_SUCCESS;
391 }
392
393 /*****************************************************************************
394  * Control:
395  *****************************************************************************/
396 static int Control( sout_mux_t *p_mux, int i_query, va_list args )
397 {
398     bool *pb_bool;
399
400     switch( i_query )
401     {
402     case MUX_CAN_ADD_STREAM_WHILE_MUXING:
403         pb_bool = (bool*)va_arg( args, bool * );
404         *pb_bool = false;
405         return VLC_SUCCESS;
406
407     case MUX_GET_ADD_STREAM_WAIT:
408         pb_bool = (bool*)va_arg( args, bool * );
409         *pb_bool = true;
410         return VLC_SUCCESS;
411
412     case MUX_GET_MIME:
413     {
414         char **ppsz = (char**)va_arg( args, char ** );
415         *ppsz = strdup( p_mux->p_sys->oc->oformat->mime_type );
416         return VLC_SUCCESS;
417     }
418
419     default:
420         return VLC_EGENERIC;
421     }
422 }
423
424 /*****************************************************************************
425  * I/O wrappers for libavformat
426  *****************************************************************************/
427 static int IOWrite( void *opaque, uint8_t *buf, int buf_size )
428 {
429     sout_mux_t *p_mux = opaque;
430     int i_ret;
431
432 #ifdef AVFORMAT_DEBUG
433     msg_Dbg( p_mux, "IOWrite %i bytes", buf_size );
434 #endif
435
436     block_t *p_buf = block_Alloc( buf_size );
437     if( buf_size > 0 ) memcpy( p_buf->p_buffer, buf, buf_size );
438
439     if( p_mux->p_sys->b_write_header )
440         p_buf->i_flags |= BLOCK_FLAG_HEADER;
441
442     if( p_mux->p_sys->b_write_keyframe )
443     {
444         p_buf->i_flags |= BLOCK_FLAG_TYPE_I;
445         p_mux->p_sys->b_write_keyframe = false;
446     }
447
448     i_ret = sout_AccessOutWrite( p_mux->p_access, p_buf );
449     return i_ret ? i_ret : -1;
450 }
451
452 static int64_t IOSeek( void *opaque, int64_t offset, int whence )
453 {
454     sout_mux_t *p_mux = opaque;
455
456 #ifdef AVFORMAT_DEBUG
457     msg_Dbg( p_mux, "IOSeek offset: %"PRId64", whence: %i", offset, whence );
458 #endif
459
460     switch( whence )
461     {
462     case SEEK_SET:
463         return sout_AccessOutSeek( p_mux->p_access, offset );
464     case SEEK_CUR:
465     case SEEK_END:
466     default:
467         return -1;
468     }
469 }