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