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