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