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