1 /*****************************************************************************
2 * encoder.c: video and audio encoder using the ffmpeg library
3 *****************************************************************************
4 * Copyright (C) 1999-2004 the VideoLAN team
7 * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8 * Gildas Bazin <gbazin@videolan.org>
9 * Christophe Massiot <massiot@via.ecp.fr>
10 * Part of the file Copyright (C) FFMPEG Project Developers
11 * (mpeg4_default matrixes)
13 * This program is free software; you can redistribute it and/or modify
14 * it under the terms of the GNU General Public License as published by
15 * the Free Software Foundation; either version 2 of the License, or
16 * (at your option) any later version.
18 * This program is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU General Public License for more details.
23 * You should have received a copy of the GNU General Public License
24 * along with this program; if not, write to the Free Software
25 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
26 *****************************************************************************/
28 /*****************************************************************************
30 *****************************************************************************/
35 #include <vlc/decoder.h>
39 #ifdef HAVE_FFMPEG_AVCODEC_H
40 # include <ffmpeg/avcodec.h>
45 #if LIBAVCODEC_BUILD < 4704
46 # define AV_NOPTS_VALUE 0
48 #if LIBAVCODEC_BUILD < 4684
49 # define FF_QP2LAMBDA 118
54 #define AVCODEC_MAX_VIDEO_FRAME_SIZE (3*1024*1024)
55 #define HURRY_UP_GUARD1 (450000)
56 #define HURRY_UP_GUARD2 (300000)
57 #define HURRY_UP_GUARD3 (100000)
59 #define MAX_FRAME_DELAY (FF_MAX_B_FRAMES + 2)
61 /*****************************************************************************
63 *****************************************************************************/
64 int E_(OpenEncoder) ( vlc_object_t * );
65 void E_(CloseEncoder)( vlc_object_t * );
67 static block_t *EncodeVideo( encoder_t *, picture_t * );
68 static block_t *EncodeAudio( encoder_t *, aout_buffer_t * );
70 struct thread_context_t;
71 static int FfmpegThread( struct thread_context_t *p_context );
72 static int FfmpegExecute( AVCodecContext *s,
73 int (*pf_func)(AVCodecContext *c2, void *arg2),
74 void **arg, int *ret, int count );
76 /*****************************************************************************
77 * thread_context_t : for multithreaded encoding
78 *****************************************************************************/
79 #if LIBAVCODEC_BUILD >= 4702
80 struct thread_context_t
84 AVCodecContext *p_context;
85 int (* pf_func)(AVCodecContext *c, void *arg);
91 vlc_bool_t b_work, b_done;
95 /*****************************************************************************
96 * encoder_sys_t : ffmpeg encoder descriptor
97 *****************************************************************************/
104 AVCodecContext *p_context;
115 mtime_t i_last_ref_pts;
116 mtime_t i_buggy_pts_detect;
127 /* Encoding settings */
134 vlc_bool_t b_strict_rc;
135 int i_rc_buffer_size;
136 float f_rc_buffer_aggressivity;
138 vlc_bool_t b_hurry_up;
139 vlc_bool_t b_interlace, b_interlace_me;
140 float f_i_quant_factor;
141 int i_noise_reduction;
142 vlc_bool_t b_mpeg4_matrix;
143 vlc_bool_t b_trellis;
144 int i_quality; /* for VBR */
145 float f_lumi_masking, f_dark_masking, f_p_masking, f_border_masking;
146 int i_luma_elim, i_chroma_elim;
148 /* Used to work around stupid timestamping behaviour in libavcodec */
150 mtime_t pi_delay_pts[MAX_FRAME_DELAY];
153 static const char *ppsz_enc_options[] = {
154 "keyint", "bframes", "vt", "qmin", "qmax", "hq", "strict-rc",
155 "rc-buffer-size", "rc-buffer-aggressivity", "pre-me", "hurry-up",
156 "interlace", "i-quant-factor", "noise-reduction", "mpeg4-matrix",
157 "trellis", "qscale", "strict", "lumi-masking", "dark-masking",
158 "p-masking", "border-masking", "luma-elim-threshold",
159 "chroma-elim-threshold", NULL
162 static const uint16_t mpa_bitrate_tab[2][15] =
164 {0, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384},
165 {0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160}
168 static const uint16_t mpa_freq_tab[6] =
169 { 44100, 48000, 32000, 22050, 24000, 16000 };
171 static const int16_t mpeg4_default_intra_matrix[64] = {
172 8, 17, 18, 19, 21, 23, 25, 27,
173 17, 18, 19, 21, 23, 25, 27, 28,
174 20, 21, 22, 23, 24, 26, 28, 30,
175 21, 22, 23, 24, 26, 28, 30, 32,
176 22, 23, 24, 26, 28, 30, 32, 35,
177 23, 24, 26, 28, 30, 32, 35, 38,
178 25, 26, 28, 30, 32, 35, 38, 41,
179 27, 28, 30, 32, 35, 38, 41, 45,
182 static const int16_t mpeg4_default_non_intra_matrix[64] = {
183 16, 17, 18, 19, 20, 21, 22, 23,
184 17, 18, 19, 20, 21, 22, 23, 24,
185 18, 19, 20, 21, 22, 23, 24, 25,
186 19, 20, 21, 22, 23, 24, 26, 27,
187 20, 21, 22, 23, 25, 26, 27, 28,
188 21, 22, 23, 24, 26, 27, 28, 30,
189 22, 23, 24, 26, 27, 28, 30, 31,
190 23, 24, 25, 27, 28, 30, 31, 33,
194 /*****************************************************************************
195 * OpenEncoder: probe the encoder
196 *****************************************************************************/
198 int E_(OpenEncoder)( vlc_object_t *p_this )
200 encoder_t *p_enc = (encoder_t *)p_this;
201 encoder_sys_t *p_sys = p_enc->p_sys;
202 AVCodecContext *p_context;
204 int i_codec_id, i_cat;
209 var_Get( p_enc->p_libvlc, "avcodec", &lockval );
211 if( !E_(GetFfmpegCodec)( p_enc->fmt_out.i_codec, &i_cat, &i_codec_id,
214 if( E_(GetFfmpegChroma)( p_enc->fmt_out.i_codec ) < 0 )
216 /* handed chroma output */
220 i_codec_id = CODEC_ID_RAWVIDEO;
221 psz_namecodec = "Raw video";
224 if( p_enc->fmt_out.i_cat == VIDEO_ES && i_cat != VIDEO_ES )
226 msg_Err( p_enc, "\"%s\" is not a video encoder", psz_namecodec );
230 if( p_enc->fmt_out.i_cat == AUDIO_ES && i_cat != AUDIO_ES )
232 msg_Err( p_enc, "\"%s\" is not an audio encoder", psz_namecodec );
236 /* Initialization must be done before avcodec_find_encoder() */
237 E_(InitLibavcodec)(p_this);
239 p_codec = avcodec_find_encoder( i_codec_id );
242 msg_Err( p_enc, "cannot find encoder %s", psz_namecodec );
246 /* Allocate the memory needed to store the encoder's structure */
247 if( ( p_sys = (encoder_sys_t *)malloc(sizeof(encoder_sys_t)) ) == NULL )
249 msg_Err( p_enc, "out of memory" );
252 memset( p_sys, 0, sizeof(encoder_sys_t) );
253 p_enc->p_sys = p_sys;
254 p_sys->p_codec = p_codec;
256 p_enc->pf_encode_video = EncodeVideo;
257 p_enc->pf_encode_audio = EncodeAudio;
259 p_sys->p_buffer_out = NULL;
260 p_sys->p_buffer = NULL;
262 p_sys->p_context = p_context = avcodec_alloc_context();
263 p_context->debug = config_GetInt( p_enc, "ffmpeg-debug" );
264 p_context->opaque = (void *)p_this;
266 /* Set CPU capabilities */
267 p_context->dsp_mask = 0;
268 if( !(p_enc->p_libvlc->i_cpu & CPU_CAPABILITY_MMX) )
270 p_context->dsp_mask |= FF_MM_MMX;
272 if( !(p_enc->p_libvlc->i_cpu & CPU_CAPABILITY_MMXEXT) )
274 p_context->dsp_mask |= FF_MM_MMXEXT;
276 if( !(p_enc->p_libvlc->i_cpu & CPU_CAPABILITY_3DNOW) )
278 p_context->dsp_mask |= FF_MM_3DNOW;
280 if( !(p_enc->p_libvlc->i_cpu & CPU_CAPABILITY_SSE) )
282 p_context->dsp_mask |= FF_MM_SSE;
283 p_context->dsp_mask |= FF_MM_SSE2;
286 sout_CfgParse( p_enc, ENC_CFG_PREFIX, ppsz_enc_options, p_enc->p_cfg );
288 var_Get( p_enc, ENC_CFG_PREFIX "keyint", &val );
289 p_sys->i_key_int = val.i_int;
291 var_Get( p_enc, ENC_CFG_PREFIX "bframes", &val );
292 p_sys->i_b_frames = val.i_int;
294 var_Get( p_enc, ENC_CFG_PREFIX "vt", &val );
295 p_sys->i_vtolerance = val.i_int;
297 var_Get( p_enc, ENC_CFG_PREFIX "interlace", &val );
298 p_sys->b_interlace = val.b_bool;
300 var_Get( p_enc, ENC_CFG_PREFIX "interlace-me", &val );
301 p_sys->b_interlace_me = val.b_bool;
303 var_Get( p_enc, ENC_CFG_PREFIX "pre-me", &val );
304 p_sys->b_pre_me = val.b_bool;
306 var_Get( p_enc, ENC_CFG_PREFIX "hurry-up", &val );
307 p_sys->b_hurry_up = val.b_bool;
308 if( p_sys->b_hurry_up )
310 /* hurry up mode needs noise reduction, even small */
311 p_sys->i_noise_reduction = 1;
314 var_Get( p_enc, ENC_CFG_PREFIX "strict-rc", &val );
315 p_sys->b_strict_rc = val.b_bool;
316 var_Get( p_enc, ENC_CFG_PREFIX "rc-buffer-size", &val );
317 p_sys->i_rc_buffer_size = val.i_int;
318 var_Get( p_enc, ENC_CFG_PREFIX "rc-buffer-aggressivity", &val );
319 p_sys->f_rc_buffer_aggressivity = val.f_float;
321 var_Get( p_enc, ENC_CFG_PREFIX "i-quant-factor", &val );
322 p_sys->f_i_quant_factor = val.f_float;
324 var_Get( p_enc, ENC_CFG_PREFIX "noise-reduction", &val );
325 p_sys->i_noise_reduction = val.i_int;
327 var_Get( p_enc, ENC_CFG_PREFIX "mpeg4-matrix", &val );
328 p_sys->b_mpeg4_matrix = val.b_bool;
330 var_Get( p_enc, ENC_CFG_PREFIX "qscale", &val );
331 if( val.f_float < 0.01 || val.f_float > 255.0 ) val.f_float = 0;
332 p_sys->i_quality = (int)(FF_QP2LAMBDA * val.f_float + 0.5);
334 var_Get( p_enc, ENC_CFG_PREFIX "hq", &val );
335 if( val.psz_string && *val.psz_string )
337 if( !strcmp( val.psz_string, "rd" ) )
338 p_sys->i_hq = FF_MB_DECISION_RD;
339 else if( !strcmp( val.psz_string, "bits" ) )
340 p_sys->i_hq = FF_MB_DECISION_BITS;
341 else if( !strcmp( val.psz_string, "simple" ) )
342 p_sys->i_hq = FF_MB_DECISION_SIMPLE;
344 p_sys->i_hq = FF_MB_DECISION_RD;
346 if( val.psz_string ) free( val.psz_string );
348 var_Get( p_enc, ENC_CFG_PREFIX "qmin", &val );
349 p_sys->i_qmin = val.i_int;
350 var_Get( p_enc, ENC_CFG_PREFIX "qmax", &val );
351 p_sys->i_qmax = val.i_int;
352 var_Get( p_enc, ENC_CFG_PREFIX "trellis", &val );
353 p_sys->b_trellis = val.b_bool;
355 var_Get( p_enc, ENC_CFG_PREFIX "strict", &val );
356 if( val.i_int < - 1 || val.i_int > 1 ) val.i_int = 0;
357 p_context->strict_std_compliance = val.i_int;
359 var_Get( p_enc, ENC_CFG_PREFIX "lumi-masking", &val );
360 p_sys->f_lumi_masking = val.f_float;
361 var_Get( p_enc, ENC_CFG_PREFIX "dark-masking", &val );
362 p_sys->f_dark_masking = val.f_float;
363 var_Get( p_enc, ENC_CFG_PREFIX "p-masking", &val );
364 p_sys->f_p_masking = val.f_float;
365 var_Get( p_enc, ENC_CFG_PREFIX "border-masking", &val );
366 p_sys->f_border_masking = val.f_float;
367 var_Get( p_enc, ENC_CFG_PREFIX "luma-elim-threshold", &val );
368 p_sys->i_luma_elim = val.i_int;
369 var_Get( p_enc, ENC_CFG_PREFIX "chroma-elim-threshold", &val );
370 p_sys->i_chroma_elim = val.i_int;
372 if( p_enc->fmt_in.i_cat == VIDEO_ES )
374 int i_aspect_num, i_aspect_den;
376 if( !p_enc->fmt_in.video.i_width || !p_enc->fmt_in.video.i_height )
378 msg_Warn( p_enc, "invalid size %ix%i", p_enc->fmt_in.video.i_width,
379 p_enc->fmt_in.video.i_height );
384 p_context->width = p_enc->fmt_in.video.i_width;
385 p_context->height = p_enc->fmt_in.video.i_height;
387 #if LIBAVCODEC_BUILD >= 4754
388 p_context->time_base.num = p_enc->fmt_in.video.i_frame_rate_base;
389 p_context->time_base.den = p_enc->fmt_in.video.i_frame_rate;
391 p_context->frame_rate = p_enc->fmt_in.video.i_frame_rate;
392 p_context->frame_rate_base= p_enc->fmt_in.video.i_frame_rate_base;
395 /* Defaults from ffmpeg.c */
396 p_context->qblur = 0.5;
397 p_context->qcompress = 0.5;
398 p_context->b_quant_offset = 1.25;
399 p_context->b_quant_factor = 1.25;
400 p_context->i_quant_offset = 0.0;
401 p_context->i_quant_factor = -0.8;
403 p_context->lumi_masking = p_sys->f_lumi_masking;
404 p_context->dark_masking = p_sys->f_dark_masking;
405 p_context->p_masking = p_sys->f_p_masking;
406 #if LIBAVCODEC_BUILD >= 4741
407 p_context->border_masking = p_sys->f_border_masking;
409 p_context->luma_elim_threshold = p_sys->i_luma_elim;
410 p_context->chroma_elim_threshold = p_sys->i_chroma_elim;
412 if( p_sys->i_key_int > 0 )
413 p_context->gop_size = p_sys->i_key_int;
414 p_context->max_b_frames =
415 __MAX( __MIN( p_sys->i_b_frames, FF_MAX_B_FRAMES ), 0 );
416 p_context->b_frame_strategy = 0;
418 #if LIBAVCODEC_BUILD >= 4687
419 av_reduce( &i_aspect_num, &i_aspect_den,
420 p_enc->fmt_in.video.i_aspect,
421 VOUT_ASPECT_FACTOR, 1 << 30 /* something big */ );
422 av_reduce( &p_context->sample_aspect_ratio.num,
423 &p_context->sample_aspect_ratio.den,
424 i_aspect_num * (int64_t)p_context->height,
425 i_aspect_den * (int64_t)p_context->width, 1 << 30 );
427 p_context->aspect_ratio = ((float)p_enc->fmt_in.video.i_aspect) /
431 p_sys->p_buffer_out = malloc( AVCODEC_MAX_VIDEO_FRAME_SIZE );
433 p_enc->fmt_in.i_codec = VLC_FOURCC('I','4','2','0');
434 p_context->pix_fmt = E_(GetFfmpegChroma)( p_enc->fmt_in.i_codec );
435 #if LIBAVCODEC_BUILD >= 4714
436 if( p_codec->pix_fmts )
438 const enum PixelFormat *p = p_codec->pix_fmts;
439 for( ; *p != -1; p++ )
441 if( *p == p_context->pix_fmt ) break;
443 if( *p == -1 ) p_context->pix_fmt = p_codec->pix_fmts[0];
444 p_enc->fmt_in.i_codec = E_(GetVlcChroma)( p_context->pix_fmt );
447 p_enc->fmt_in.i_codec = E_(GetVlcChroma)( p_context->pix_fmt );
450 if ( p_sys->b_strict_rc )
452 p_context->rc_max_rate = p_enc->fmt_out.i_bitrate;
453 p_context->rc_buffer_size = p_sys->i_rc_buffer_size;
454 /* This is from ffmpeg's ffmpeg.c : */
455 p_context->rc_initial_buffer_occupancy
456 = p_sys->i_rc_buffer_size * 3/4;
457 p_context->rc_buffer_aggressivity = p_sys->f_rc_buffer_aggressivity;
460 if ( p_sys->f_i_quant_factor != 0.0 )
461 p_context->i_quant_factor = p_sys->f_i_quant_factor;
463 #if LIBAVCODEC_BUILD >= 4690
464 p_context->noise_reduction = p_sys->i_noise_reduction;
467 if ( p_sys->b_mpeg4_matrix )
469 p_context->intra_matrix = mpeg4_default_intra_matrix;
470 p_context->inter_matrix = mpeg4_default_non_intra_matrix;
473 if ( p_sys->b_pre_me )
475 p_context->pre_me = 1;
476 p_context->me_pre_cmp = FF_CMP_CHROMA;
479 if ( p_sys->b_interlace )
481 if ( p_context->height <= 280 )
483 if ( p_context->height != 16 || p_context->width != 16 )
485 "disabling interlaced video because height=%d <= 280",
490 p_context->flags |= CODEC_FLAG_INTERLACED_DCT;
491 #if LIBAVCODEC_BUILD >= 4698
492 if ( p_sys->b_interlace_me )
493 p_context->flags |= CODEC_FLAG_INTERLACED_ME;
498 if ( p_sys->b_trellis )
499 p_context->flags |= CODEC_FLAG_TRELLIS_QUANT;
501 if ( p_sys->i_qmin > 0 && p_sys->i_qmin == p_sys->i_qmax )
502 p_context->flags |= CODEC_FLAG_QSCALE;
504 #if LIBAVCODEC_BUILD >= 4702
505 if ( p_enc->i_threads >= 1 )
506 p_context->thread_count = p_enc->i_threads;
509 if( p_sys->i_vtolerance > 0 )
510 p_context->bit_rate_tolerance = p_sys->i_vtolerance;
512 if( p_sys->i_qmin > 0 )
513 p_context->mb_qmin = p_context->qmin = p_sys->i_qmin;
514 if( p_sys->i_qmax > 0 )
515 p_context->mb_qmax = p_context->qmax = p_sys->i_qmax;
516 p_context->max_qdiff = 3;
518 p_context->mb_decision = p_sys->i_hq;
520 if( p_sys->i_quality )
522 p_context->flags |= CODEC_FLAG_QSCALE;
523 #if LIBAVCODEC_BUILD >= 4668
524 p_context->global_quality = p_sys->i_quality;
528 else if( p_enc->fmt_in.i_cat == AUDIO_ES )
530 /* work around bug in libmp3lame encoding */
531 if( i_codec_id == CODEC_ID_MP3 && p_enc->fmt_in.audio.i_channels > 2 )
532 p_enc->fmt_in.audio.i_channels = 2;
534 p_enc->fmt_in.i_codec = AOUT_FMT_S16_NE;
535 p_context->sample_rate = p_enc->fmt_in.audio.i_rate;
536 p_context->channels = p_enc->fmt_in.audio.i_channels;
539 /* Misc parameters */
540 p_context->bit_rate = p_enc->fmt_out.i_bitrate;
542 if( i_codec_id == CODEC_ID_RAWVIDEO )
544 /* XXX: hack: Force same codec (will be handled by transcode) */
545 p_enc->fmt_in.i_codec = p_enc->fmt_out.i_codec;
546 p_context->pix_fmt = E_(GetFfmpegChroma)( p_enc->fmt_in.i_codec );
549 /* Make sure we get extradata filled by the encoder */
550 p_context->extradata_size = 0;
551 p_context->extradata = NULL;
552 p_context->flags |= CODEC_FLAG_GLOBAL_HEADER;
554 vlc_mutex_lock( lockval.p_address );
555 if( avcodec_open( p_context, p_codec ) )
557 vlc_mutex_unlock( lockval.p_address );
558 if( p_enc->fmt_in.i_cat == AUDIO_ES &&
559 (p_context->channels > 2 || i_codec_id == CODEC_ID_MP2
560 || i_codec_id == CODEC_ID_MP3) )
562 if( p_context->channels > 2 )
564 p_context->channels = 2;
565 p_enc->fmt_in.audio.i_channels = 2; // FIXME
566 msg_Warn( p_enc, "stereo mode selected (codec limitation)" );
569 if( i_codec_id == CODEC_ID_MP2 || i_codec_id == CODEC_ID_MP3 )
573 for ( i_frequency = 0; i_frequency < 6; i_frequency++ )
575 if ( p_enc->fmt_out.audio.i_rate
576 == mpa_freq_tab[i_frequency] )
579 if ( i_frequency == 6 )
581 msg_Err( p_enc, "MPEG audio doesn't support frequency=%d",
582 p_enc->fmt_out.audio.i_rate );
587 for ( i = 1; i < 14; i++ )
589 if ( p_enc->fmt_out.i_bitrate / 1000
590 <= mpa_bitrate_tab[i_frequency / 3][i] )
593 if ( p_enc->fmt_out.i_bitrate / 1000
594 != mpa_bitrate_tab[i_frequency / 3][i] )
597 "MPEG audio doesn't support bitrate=%d, using %d",
598 p_enc->fmt_out.i_bitrate,
599 mpa_bitrate_tab[i_frequency / 3][i] * 1000 );
600 p_enc->fmt_out.i_bitrate =
601 mpa_bitrate_tab[i_frequency / 3][i] * 1000;
602 p_context->bit_rate = p_enc->fmt_out.i_bitrate;
606 p_context->codec = NULL;
607 vlc_mutex_lock( lockval.p_address );
608 if( avcodec_open( p_context, p_codec ) )
610 vlc_mutex_unlock( lockval.p_address );
611 msg_Err( p_enc, "cannot open encoder" );
618 msg_Err( p_enc, "cannot open encoder" );
623 vlc_mutex_unlock( lockval.p_address );
625 p_enc->fmt_out.i_extra = p_context->extradata_size;
626 if( p_enc->fmt_out.i_extra )
628 p_enc->fmt_out.p_extra = malloc( p_enc->fmt_out.i_extra );
629 memcpy( p_enc->fmt_out.p_extra, p_context->extradata,
630 p_enc->fmt_out.i_extra );
632 p_context->flags &= ~CODEC_FLAG_GLOBAL_HEADER;
634 if( p_enc->fmt_in.i_cat == AUDIO_ES )
636 p_sys->p_buffer_out = malloc( 2 * AVCODEC_MAX_AUDIO_FRAME_SIZE );
637 p_sys->i_frame_size = p_context->frame_size * 2 * p_context->channels;
638 p_sys->p_buffer = malloc( p_sys->i_frame_size );
641 msg_Dbg( p_enc, "found encoder %s", psz_namecodec );
646 /****************************************************************************
647 * Ffmpeg threading system
648 ****************************************************************************/
649 #if LIBAVCODEC_BUILD >= 4702
650 static int FfmpegThread( struct thread_context_t *p_context )
652 while ( !p_context->b_die && !p_context->b_error )
654 vlc_mutex_lock( &p_context->lock );
655 while ( !p_context->b_work && !p_context->b_die && !p_context->b_error )
657 vlc_cond_wait( &p_context->cond, &p_context->lock );
659 p_context->b_work = 0;
660 vlc_mutex_unlock( &p_context->lock );
661 if ( p_context->b_die || p_context->b_error )
664 if ( p_context->pf_func )
666 p_context->i_ret = p_context->pf_func( p_context->p_context,
670 vlc_mutex_lock( &p_context->lock );
671 p_context->b_done = 1;
672 vlc_cond_signal( &p_context->cond );
673 vlc_mutex_unlock( &p_context->lock );
679 static int FfmpegExecute( AVCodecContext *s,
680 int (*pf_func)(AVCodecContext *c2, void *arg2),
681 void **arg, int *ret, int count )
683 struct thread_context_t ** pp_contexts =
684 (struct thread_context_t **)s->thread_opaque;
687 /* Note, we can be certain that this is not called with the same
688 * AVCodecContext by different threads at the same time */
689 for ( i = 0; i < count; i++ )
691 vlc_mutex_lock( &pp_contexts[i]->lock );
692 pp_contexts[i]->arg = arg[i];
693 pp_contexts[i]->pf_func = pf_func;
694 pp_contexts[i]->i_ret = 12345;
695 pp_contexts[i]->b_work = 1;
696 vlc_cond_signal( &pp_contexts[i]->cond );
697 vlc_mutex_unlock( &pp_contexts[i]->lock );
699 for ( i = 0; i < count; i++ )
701 vlc_mutex_lock( &pp_contexts[i]->lock );
702 while ( !pp_contexts[i]->b_done )
704 vlc_cond_wait( &pp_contexts[i]->cond, &pp_contexts[i]->lock );
706 pp_contexts[i]->b_done = 0;
707 pp_contexts[i]->pf_func = NULL;
708 vlc_mutex_unlock( &pp_contexts[i]->lock );
712 ret[i] = pp_contexts[i]->i_ret;
720 /****************************************************************************
721 * EncodeVideo: the whole thing
722 ****************************************************************************/
723 static block_t *EncodeVideo( encoder_t *p_enc, picture_t *p_pict )
725 encoder_sys_t *p_sys = p_enc->p_sys;
729 #if LIBAVCODEC_BUILD >= 4702
730 if ( !p_sys->b_inited && p_enc->i_threads >= 1 )
732 struct thread_context_t ** pp_contexts;
736 pp_contexts = malloc( sizeof(struct thread_context_t *)
737 * p_enc->i_threads );
738 p_sys->p_context->thread_opaque = (void *)pp_contexts;
740 for ( i = 0; i < p_enc->i_threads; i++ )
742 pp_contexts[i] = vlc_object_create( p_enc,
743 sizeof(struct thread_context_t) );
744 pp_contexts[i]->p_context = p_sys->p_context;
745 vlc_mutex_init( p_enc, &pp_contexts[i]->lock );
746 vlc_cond_init( p_enc, &pp_contexts[i]->cond );
747 pp_contexts[i]->b_work = 0;
748 pp_contexts[i]->b_done = 0;
749 if ( vlc_thread_create( pp_contexts[i], "encoder", FfmpegThread,
750 VLC_THREAD_PRIORITY_VIDEO, VLC_FALSE ) )
752 msg_Err( p_enc, "cannot spawn encoder thread, expect to die soon" );
757 p_sys->p_context->execute = FfmpegExecute;
761 memset( &frame, 0, sizeof( AVFrame ) );
762 for( i_plane = 0; i_plane < p_pict->i_planes; i_plane++ )
764 frame.data[i_plane] = p_pict->p[i_plane].p_pixels;
765 frame.linesize[i_plane] = p_pict->p[i_plane].i_pitch;
768 /* Let ffmpeg select the frame type */
771 frame.repeat_pict = p_pict->i_nb_fields - 2;
773 #if LIBAVCODEC_BUILD >= 4685
774 frame.interlaced_frame = !p_pict->b_progressive;
775 frame.top_field_first = !!p_pict->b_top_field_first;
778 #if LIBAVCODEC_BUILD < 4702
779 /* Set the pts of the frame being encoded (segfaults with mpeg4!)*/
780 if( p_enc->fmt_out.i_codec == VLC_FOURCC( 'm', 'p', 'g', 'v' ) ||
781 p_enc->fmt_out.i_codec == VLC_FOURCC( 'm', 'p', '1', 'v' ) ||
782 p_enc->fmt_out.i_codec == VLC_FOURCC( 'm', 'p', '2', 'v' ) )
787 frame.pts = p_pict->date ? p_pict->date : (signed int) AV_NOPTS_VALUE;
789 if ( p_sys->b_hurry_up && frame.pts != (signed int) AV_NOPTS_VALUE )
791 mtime_t current_date = mdate();
793 if ( current_date + HURRY_UP_GUARD3 > frame.pts )
795 p_sys->p_context->mb_decision = FF_MB_DECISION_SIMPLE;
796 p_sys->p_context->flags &= ~CODEC_FLAG_TRELLIS_QUANT;
797 msg_Dbg( p_enc, "hurry up mode 3" );
801 p_sys->p_context->mb_decision = p_sys->i_hq;
803 if ( current_date + HURRY_UP_GUARD2 > frame.pts )
805 p_sys->p_context->flags &= ~CODEC_FLAG_TRELLIS_QUANT;
806 #if LIBAVCODEC_BUILD >= 4690
807 p_sys->p_context->noise_reduction = p_sys->i_noise_reduction
808 + (HURRY_UP_GUARD2 + current_date - frame.pts) / 500;
810 msg_Dbg( p_enc, "hurry up mode 2" );
814 if ( p_sys->b_trellis )
815 p_sys->p_context->flags |= CODEC_FLAG_TRELLIS_QUANT;
816 #if LIBAVCODEC_BUILD >= 4690
817 p_sys->p_context->noise_reduction =
818 p_sys->i_noise_reduction;
823 if ( current_date + HURRY_UP_GUARD1 > frame.pts )
825 frame.pict_type = FF_P_TYPE;
826 /* msg_Dbg( p_enc, "hurry up mode 1 %lld", current_date + HURRY_UP_GUARD1 - frame.pts ); */
832 frame.pts = AV_NOPTS_VALUE;
835 if ( frame.pts != (signed int) AV_NOPTS_VALUE && frame.pts != 0 )
837 if ( p_sys->i_last_pts == frame.pts )
839 msg_Warn( p_enc, "almost fed libavcodec with two frames with the "
840 "same PTS (" I64Fd ")", frame.pts );
843 else if ( p_sys->i_last_pts > frame.pts )
845 msg_Warn( p_enc, "almost fed libavcodec with a frame in the "
846 "past (current: " I64Fd ", last: "I64Fd")",
847 frame.pts, p_sys->i_last_pts );
852 p_sys->i_last_pts = frame.pts;
856 frame.quality = p_sys->i_quality;
858 /* Ugly work-around for stupid libavcodec behaviour */
859 #if LIBAVCODEC_BUILD >= 4722
861 p_sys->pi_delay_pts[p_sys->i_framenum % MAX_FRAME_DELAY] = frame.pts;
862 frame.pts = p_sys->i_framenum * AV_TIME_BASE *
863 p_enc->fmt_in.video.i_frame_rate_base;
864 frame.pts += p_enc->fmt_in.video.i_frame_rate - 1;
865 frame.pts /= p_enc->fmt_in.video.i_frame_rate;
867 /* End work-around */
869 i_out = avcodec_encode_video( p_sys->p_context, p_sys->p_buffer_out,
870 AVCODEC_MAX_VIDEO_FRAME_SIZE, &frame );
874 block_t *p_block = block_New( p_enc, i_out );
875 memcpy( p_block->p_buffer, p_sys->p_buffer_out, i_out );
877 /* FIXME, 3-2 pulldown is not handled correctly */
878 p_block->i_length = I64C(1000000) *
879 p_enc->fmt_in.video.i_frame_rate_base /
880 p_enc->fmt_in.video.i_frame_rate;
882 if( !p_sys->p_context->max_b_frames || !p_sys->p_context->delay )
884 /* No delay -> output pts == input pts */
885 p_block->i_pts = p_block->i_dts = p_pict->date;
887 else if( p_sys->p_context->coded_frame->pts != (signed int) AV_NOPTS_VALUE &&
888 p_sys->p_context->coded_frame->pts != 0 &&
889 p_sys->i_buggy_pts_detect != p_sys->p_context->coded_frame->pts )
891 p_sys->i_buggy_pts_detect = p_sys->p_context->coded_frame->pts;
892 p_block->i_pts = p_sys->p_context->coded_frame->pts;
894 /* Ugly work-around for stupid libavcodec behaviour */
895 #if LIBAVCODEC_BUILD >= 4722
897 int64_t i_framenum = p_block->i_pts *
898 p_enc->fmt_in.video.i_frame_rate /
899 p_enc->fmt_in.video.i_frame_rate_base / AV_TIME_BASE;
901 p_block->i_pts = p_sys->pi_delay_pts[i_framenum % MAX_FRAME_DELAY];
904 /* End work-around */
906 if( p_sys->p_context->coded_frame->pict_type != FF_I_TYPE &&
907 p_sys->p_context->coded_frame->pict_type != FF_P_TYPE )
909 p_block->i_dts = p_block->i_pts;
913 if( p_sys->i_last_ref_pts )
915 p_block->i_dts = p_sys->i_last_ref_pts;
919 /* Let's put something sensible */
920 p_block->i_dts = p_block->i_pts;
923 p_sys->i_last_ref_pts = p_block->i_pts;
928 /* Buggy libavcodec which doesn't update coded_frame->pts
930 p_block->i_dts = p_block->i_pts = p_pict->date;
933 switch ( p_sys->p_context->coded_frame->pict_type )
936 p_block->i_flags |= BLOCK_FLAG_TYPE_I;
939 p_block->i_flags |= BLOCK_FLAG_TYPE_P;
942 p_block->i_flags |= BLOCK_FLAG_TYPE_B;
952 /****************************************************************************
953 * EncodeAudio: the whole thing
954 ****************************************************************************/
955 static block_t *EncodeAudio( encoder_t *p_enc, aout_buffer_t *p_aout_buf )
957 encoder_sys_t *p_sys = p_enc->p_sys;
958 block_t *p_block, *p_chain = NULL;
960 char *p_buffer = p_aout_buf->p_buffer;
961 int i_samples = p_aout_buf->i_nb_samples;
962 int i_samples_delay = p_sys->i_samples_delay;
964 p_sys->i_pts = p_aout_buf->start_date -
965 (mtime_t)1000000 * (mtime_t)p_sys->i_samples_delay /
966 (mtime_t)p_enc->fmt_in.audio.i_rate;
968 p_sys->i_samples_delay += i_samples;
970 while( p_sys->i_samples_delay >= p_sys->p_context->frame_size )
975 if( i_samples_delay )
977 /* Take care of the left-over from last time */
978 int i_delay_size = i_samples_delay * 2 *
979 p_sys->p_context->channels;
980 int i_size = p_sys->i_frame_size - i_delay_size;
982 p_samples = (int16_t *)p_sys->p_buffer;
983 memcpy( p_sys->p_buffer + i_delay_size, p_buffer, i_size );
984 p_buffer -= i_delay_size;
985 i_samples += i_samples_delay;
990 p_samples = (int16_t *)p_buffer;
993 i_out = avcodec_encode_audio( p_sys->p_context, p_sys->p_buffer_out,
994 2 * AVCODEC_MAX_AUDIO_FRAME_SIZE,
998 msg_Warn( p_enc, "avcodec_encode_audio: %d", i_out );
1000 if( i_out < 0 ) break;
1002 p_buffer += p_sys->i_frame_size;
1003 p_sys->i_samples_delay -= p_sys->p_context->frame_size;
1004 i_samples -= p_sys->p_context->frame_size;
1006 if( i_out == 0 ) continue;
1008 p_block = block_New( p_enc, i_out );
1009 memcpy( p_block->p_buffer, p_sys->p_buffer_out, i_out );
1011 p_block->i_length = (mtime_t)1000000 *
1012 (mtime_t)p_sys->p_context->frame_size /
1013 (mtime_t)p_sys->p_context->sample_rate;
1015 p_block->i_dts = p_block->i_pts = p_sys->i_pts;
1018 p_sys->i_pts += p_block->i_length;
1019 block_ChainAppend( &p_chain, p_block );
1022 /* Backup the remaining raw samples */
1025 memcpy( p_sys->p_buffer + i_samples_delay * 2 *
1026 p_sys->p_context->channels, p_buffer,
1027 i_samples * 2 * p_sys->p_context->channels );
1033 /*****************************************************************************
1034 * CloseEncoder: ffmpeg encoder destruction
1035 *****************************************************************************/
1036 void E_(CloseEncoder)( vlc_object_t *p_this )
1038 encoder_t *p_enc = (encoder_t *)p_this;
1039 encoder_sys_t *p_sys = p_enc->p_sys;
1040 vlc_value_t lockval;
1042 var_Get( p_enc->p_libvlc, "avcodec", &lockval );
1044 #if LIBAVCODEC_BUILD >= 4702
1045 if ( p_sys->b_inited && p_enc->i_threads >= 1 )
1048 struct thread_context_t ** pp_contexts =
1049 (struct thread_context_t **)p_sys->p_context->thread_opaque;
1050 for ( i = 0; i < p_enc->i_threads; i++ )
1052 pp_contexts[i]->b_die = 1;
1053 vlc_cond_signal( &pp_contexts[i]->cond );
1054 vlc_thread_join( pp_contexts[i] );
1055 vlc_mutex_destroy( &pp_contexts[i]->lock );
1056 vlc_cond_destroy( &pp_contexts[i]->cond );
1057 vlc_object_destroy( pp_contexts[i] );
1060 free( pp_contexts );
1064 vlc_mutex_lock( lockval.p_address );
1065 avcodec_close( p_sys->p_context );
1066 vlc_mutex_unlock( lockval.p_address );
1067 av_free( p_sys->p_context );
1069 if( p_sys->p_buffer ) free( p_sys->p_buffer );
1070 if( p_sys->p_buffer_out ) free( p_sys->p_buffer_out );