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