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