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