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>
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
21 * You should have received a copy of the GNU General Public License
22 * along with this program; if not, write to the Free Software
23 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111, USA.
24 *****************************************************************************/
26 /*****************************************************************************
28 *****************************************************************************/
33 #include <vlc/decoder.h>
37 #ifdef HAVE_FFMPEG_AVCODEC_H
38 # include <ffmpeg/avcodec.h>
43 #if LIBAVCODEC_BUILD < 4704
44 # define AV_NOPTS_VALUE 0
46 #if LIBAVCODEC_BUILD < 4684
47 # define FF_QP2LAMBDA 118
52 #define AVCODEC_MAX_VIDEO_FRAME_SIZE (3*1024*1024)
53 #define HURRY_UP_GUARD1 (450000)
54 #define HURRY_UP_GUARD2 (300000)
55 #define HURRY_UP_GUARD3 (100000)
57 #define MAX_FRAME_DELAY (FF_MAX_B_FRAMES + 2)
59 /*****************************************************************************
61 *****************************************************************************/
62 int E_(OpenEncoder) ( vlc_object_t * );
63 void E_(CloseEncoder)( vlc_object_t * );
65 static block_t *EncodeVideo( encoder_t *, picture_t * );
66 static block_t *EncodeAudio( encoder_t *, aout_buffer_t * );
68 struct thread_context_t;
69 static int FfmpegThread( struct thread_context_t *p_context );
70 static int FfmpegExecute( AVCodecContext *s,
71 int (*pf_func)(AVCodecContext *c2, void *arg2),
72 void **arg, int *ret, int count );
74 /*****************************************************************************
75 * thread_context_t : for multithreaded encoding
76 *****************************************************************************/
77 #if LIBAVCODEC_BUILD >= 4702
78 struct thread_context_t
82 AVCodecContext *p_context;
83 int (* pf_func)(AVCodecContext *c, void *arg);
89 vlc_bool_t b_work, b_done;
93 /*****************************************************************************
94 * encoder_sys_t : ffmpeg encoder descriptor
95 *****************************************************************************/
102 AVCodecContext *p_context;
113 mtime_t i_last_ref_pts;
114 mtime_t i_buggy_pts_detect;
125 /* Encoding settings */
132 vlc_bool_t b_strict_rc;
133 int i_rc_buffer_size;
134 float f_rc_buffer_aggressivity;
136 vlc_bool_t b_hurry_up;
137 vlc_bool_t b_interlace, b_interlace_me;
138 float f_i_quant_factor;
139 int i_noise_reduction;
140 vlc_bool_t b_mpeg4_matrix;
141 vlc_bool_t b_trellis;
142 int i_quality; /* for VBR */
143 float f_lumi_masking, f_dark_masking, f_p_masking, f_border_masking;
144 int i_luma_elim, i_chroma_elim;
146 /* Used to work around stupid timestamping behaviour in libavcodec */
148 mtime_t pi_delay_pts[MAX_FRAME_DELAY];
151 static const char *ppsz_enc_options[] = {
152 "keyint", "bframes", "vt", "qmin", "qmax", "hq", "strict-rc",
153 "rc-buffer-size", "rc-buffer-aggressivity", "pre-me", "hurry-up",
154 "interlace", "i-quant-factor", "noise-reduction", "mpeg4-matrix",
155 "trellis", "qscale", "strict", "lumi-masking", "dark-masking",
156 "p-masking", "border-masking", "luma-elim-threshold",
157 "chroma-elim-threshold", NULL
160 static const uint16_t mpa_bitrate_tab[2][15] =
162 {0, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384},
163 {0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160}
166 static const uint16_t mpa_freq_tab[6] =
167 { 44100, 48000, 32000, 22050, 24000, 16000 };
169 /*****************************************************************************
170 * OpenEncoder: probe the encoder
171 *****************************************************************************/
172 extern int16_t IMPORT_SYMBOL ff_mpeg4_default_intra_matrix[];
173 extern int16_t IMPORT_SYMBOL ff_mpeg4_default_non_intra_matrix[];
175 int E_(OpenEncoder)( vlc_object_t *p_this )
177 encoder_t *p_enc = (encoder_t *)p_this;
178 encoder_sys_t *p_sys = p_enc->p_sys;
179 AVCodecContext *p_context;
181 int i_codec_id, i_cat;
186 var_Get( p_enc->p_libvlc, "avcodec", &lockval );
188 if( !E_(GetFfmpegCodec)( p_enc->fmt_out.i_codec, &i_cat, &i_codec_id,
191 if( E_(GetFfmpegChroma)( p_enc->fmt_out.i_codec ) < 0 )
193 /* handed chroma output */
197 i_codec_id = CODEC_ID_RAWVIDEO;
198 psz_namecodec = "Raw video";
202 if( p_enc->fmt_out.i_cat == VIDEO_ES && i_cat != VIDEO_ES )
204 msg_Err( p_enc, "\"%s\" is not a video encoder", psz_namecodec );
208 if( p_enc->fmt_out.i_cat == AUDIO_ES && i_cat != AUDIO_ES )
210 msg_Err( p_enc, "\"%s\" is not an audio encoder", psz_namecodec );
214 /* Initialization must be done before avcodec_find_decoder() */
215 E_(InitLibavcodec)(p_this);
217 p_codec = avcodec_find_encoder( i_codec_id );
220 msg_Err( p_enc, "cannot find encoder %s", psz_namecodec );
224 /* Allocate the memory needed to store the decoder's structure */
225 if( ( p_sys = (encoder_sys_t *)malloc(sizeof(encoder_sys_t)) ) == NULL )
227 msg_Err( p_enc, "out of memory" );
230 memset( p_sys, 0, sizeof(encoder_sys_t) );
231 p_enc->p_sys = p_sys;
232 p_sys->p_codec = p_codec;
234 p_enc->pf_encode_video = EncodeVideo;
235 p_enc->pf_encode_audio = EncodeAudio;
237 p_sys->p_buffer_out = NULL;
238 p_sys->p_buffer = NULL;
240 p_sys->p_context = p_context = avcodec_alloc_context();
242 /* Set CPU capabilities */
243 p_context->dsp_mask = 0;
244 if( !(p_enc->p_libvlc->i_cpu & CPU_CAPABILITY_MMX) )
246 p_context->dsp_mask |= FF_MM_MMX;
248 if( !(p_enc->p_libvlc->i_cpu & CPU_CAPABILITY_MMXEXT) )
250 p_context->dsp_mask |= FF_MM_MMXEXT;
252 if( !(p_enc->p_libvlc->i_cpu & CPU_CAPABILITY_3DNOW) )
254 p_context->dsp_mask |= FF_MM_3DNOW;
256 if( !(p_enc->p_libvlc->i_cpu & CPU_CAPABILITY_SSE) )
258 p_context->dsp_mask |= FF_MM_SSE;
259 p_context->dsp_mask |= FF_MM_SSE2;
262 sout_CfgParse( p_enc, ENC_CFG_PREFIX, ppsz_enc_options, p_enc->p_cfg );
264 var_Get( p_enc, ENC_CFG_PREFIX "keyint", &val );
265 p_sys->i_key_int = val.i_int;
267 var_Get( p_enc, ENC_CFG_PREFIX "bframes", &val );
268 p_sys->i_b_frames = val.i_int;
270 var_Get( p_enc, ENC_CFG_PREFIX "vt", &val );
271 p_sys->i_vtolerance = val.i_int;
273 var_Get( p_enc, ENC_CFG_PREFIX "interlace", &val );
274 p_sys->b_interlace = val.b_bool;
276 var_Get( p_enc, ENC_CFG_PREFIX "interlace-me", &val );
277 p_sys->b_interlace_me = val.b_bool;
279 var_Get( p_enc, ENC_CFG_PREFIX "pre-me", &val );
280 p_sys->b_pre_me = val.b_bool;
282 var_Get( p_enc, ENC_CFG_PREFIX "hurry-up", &val );
283 p_sys->b_hurry_up = val.b_bool;
284 if( p_sys->b_hurry_up )
286 /* hurry up mode needs noise reduction, even small */
287 p_sys->i_noise_reduction = 1;
290 var_Get( p_enc, ENC_CFG_PREFIX "strict-rc", &val );
291 p_sys->b_strict_rc = val.b_bool;
292 var_Get( p_enc, ENC_CFG_PREFIX "rc-buffer-size", &val );
293 p_sys->i_rc_buffer_size = val.i_int;
294 var_Get( p_enc, ENC_CFG_PREFIX "rc-buffer-aggressivity", &val );
295 p_sys->f_rc_buffer_aggressivity = val.f_float;
297 var_Get( p_enc, ENC_CFG_PREFIX "i-quant-factor", &val );
298 p_sys->f_i_quant_factor = val.f_float;
300 var_Get( p_enc, ENC_CFG_PREFIX "noise-reduction", &val );
301 p_sys->i_noise_reduction = val.i_int;
303 var_Get( p_enc, ENC_CFG_PREFIX "mpeg4-matrix", &val );
304 p_sys->b_mpeg4_matrix = val.b_bool;
306 var_Get( p_enc, ENC_CFG_PREFIX "qscale", &val );
307 if( val.f_float < 0.01 || val.f_float > 255.0 ) val.f_float = 0;
308 p_sys->i_quality = (int)(FF_QP2LAMBDA * val.f_float + 0.5);
310 var_Get( p_enc, ENC_CFG_PREFIX "hq", &val );
311 if( val.psz_string && *val.psz_string )
313 if( !strcmp( val.psz_string, "rd" ) )
314 p_sys->i_hq = FF_MB_DECISION_RD;
315 else if( !strcmp( val.psz_string, "bits" ) )
316 p_sys->i_hq = FF_MB_DECISION_BITS;
317 else if( !strcmp( val.psz_string, "simple" ) )
318 p_sys->i_hq = FF_MB_DECISION_SIMPLE;
320 p_sys->i_hq = FF_MB_DECISION_RD;
322 if( val.psz_string ) free( val.psz_string );
324 var_Get( p_enc, ENC_CFG_PREFIX "qmin", &val );
325 p_sys->i_qmin = val.i_int;
326 var_Get( p_enc, ENC_CFG_PREFIX "qmax", &val );
327 p_sys->i_qmax = val.i_int;
328 var_Get( p_enc, ENC_CFG_PREFIX "trellis", &val );
329 p_sys->b_trellis = val.b_bool;
331 var_Get( p_enc, ENC_CFG_PREFIX "strict", &val );
332 if( val.i_int < - 1 || val.i_int > 1 ) val.i_int = 0;
333 p_context->strict_std_compliance = val.i_int;
335 var_Get( p_enc, ENC_CFG_PREFIX "lumi-masking", &val );
336 p_sys->f_lumi_masking = val.f_float;
337 var_Get( p_enc, ENC_CFG_PREFIX "dark-masking", &val );
338 p_sys->f_dark_masking = val.f_float;
339 var_Get( p_enc, ENC_CFG_PREFIX "p-masking", &val );
340 p_sys->f_p_masking = val.f_float;
341 var_Get( p_enc, ENC_CFG_PREFIX "border-masking", &val );
342 p_sys->f_border_masking = val.f_float;
343 var_Get( p_enc, ENC_CFG_PREFIX "luma-elim-threshold", &val );
344 p_sys->i_luma_elim = val.i_int;
345 var_Get( p_enc, ENC_CFG_PREFIX "chroma-elim-threshold", &val );
346 p_sys->i_chroma_elim = val.i_int;
348 if( p_enc->fmt_in.i_cat == VIDEO_ES )
350 int i_aspect_num, i_aspect_den;
352 if( !p_enc->fmt_in.video.i_width || !p_enc->fmt_in.video.i_height )
354 msg_Warn( p_enc, "invalid size %ix%i", p_enc->fmt_in.video.i_width,
355 p_enc->fmt_in.video.i_height );
360 p_context->width = p_enc->fmt_in.video.i_width;
361 p_context->height = p_enc->fmt_in.video.i_height;
363 #if LIBAVCODEC_BUILD >= 4754
364 p_context->time_base.num = p_enc->fmt_in.video.i_frame_rate_base;
365 p_context->time_base.den = p_enc->fmt_in.video.i_frame_rate;
367 p_context->frame_rate = p_enc->fmt_in.video.i_frame_rate;
368 p_context->frame_rate_base= p_enc->fmt_in.video.i_frame_rate_base;
371 /* Defaults from ffmpeg.c */
372 p_context->qblur = 0.5;
373 p_context->qcompress = 0.5;
374 p_context->b_quant_offset = 1.25;
375 p_context->b_quant_factor = 1.25;
376 p_context->i_quant_offset = 0.0;
377 p_context->i_quant_factor = -0.8;
379 p_context->lumi_masking = p_sys->f_lumi_masking;
380 p_context->dark_masking = p_sys->f_dark_masking;
381 p_context->p_masking = p_sys->f_p_masking;
382 #if LIBAVCODEC_BUILD >= 4741
383 p_context->border_masking = p_sys->f_border_masking;
385 p_context->luma_elim_threshold = p_sys->i_luma_elim;
386 p_context->chroma_elim_threshold = p_sys->i_chroma_elim;
388 if( p_sys->i_key_int > 0 )
389 p_context->gop_size = p_sys->i_key_int;
390 p_context->max_b_frames =
391 __MAX( __MIN( p_sys->i_b_frames, FF_MAX_B_FRAMES ), 0 );
392 p_context->b_frame_strategy = 0;
394 #if LIBAVCODEC_BUILD >= 4687
395 av_reduce( &i_aspect_num, &i_aspect_den,
396 p_enc->fmt_in.video.i_aspect,
397 VOUT_ASPECT_FACTOR, 1 << 30 /* something big */ );
398 av_reduce( &p_context->sample_aspect_ratio.num,
399 &p_context->sample_aspect_ratio.den,
400 i_aspect_num * (int64_t)p_context->height,
401 i_aspect_den * (int64_t)p_context->width, 1 << 30 );
403 p_context->aspect_ratio = ((float)p_enc->fmt_in.video.i_aspect) /
407 p_sys->p_buffer_out = malloc( AVCODEC_MAX_VIDEO_FRAME_SIZE );
409 p_enc->fmt_in.i_codec = VLC_FOURCC('I','4','2','0');
410 p_context->pix_fmt = E_(GetFfmpegChroma)( p_enc->fmt_in.i_codec );
411 #if LIBAVCODEC_BUILD >= 4714
412 if( p_codec->pix_fmts )
414 const enum PixelFormat *p = p_codec->pix_fmts;
415 for( ; *p != -1; p++ )
417 if( *p == p_context->pix_fmt ) break;
419 if( *p == -1 ) p_context->pix_fmt = p_codec->pix_fmts[0];
420 p_enc->fmt_in.i_codec = E_(GetVlcChroma)( p_context->pix_fmt );
423 p_enc->fmt_in.i_codec = E_(GetVlcChroma)( p_context->pix_fmt );
426 if ( p_sys->b_strict_rc )
428 p_context->rc_max_rate = p_enc->fmt_out.i_bitrate;
429 p_context->rc_buffer_size = p_sys->i_rc_buffer_size;
430 /* This is from ffmpeg's ffmpeg.c : */
431 p_context->rc_initial_buffer_occupancy
432 = p_sys->i_rc_buffer_size * 3/4;
433 p_context->rc_buffer_aggressivity = p_sys->f_rc_buffer_aggressivity;
436 if ( p_sys->f_i_quant_factor != 0.0 )
437 p_context->i_quant_factor = p_sys->f_i_quant_factor;
439 #if LIBAVCODEC_BUILD >= 4690
440 p_context->noise_reduction = p_sys->i_noise_reduction;
443 if ( p_sys->b_mpeg4_matrix )
445 p_context->intra_matrix = ff_mpeg4_default_intra_matrix;
446 p_context->inter_matrix = ff_mpeg4_default_non_intra_matrix;
449 if ( p_sys->b_pre_me )
451 p_context->pre_me = 1;
452 p_context->me_pre_cmp = FF_CMP_CHROMA;
455 if ( p_sys->b_interlace )
457 if ( p_context->height <= 280 )
459 if ( p_context->height != 16 || p_context->width != 16 )
461 "disabling interlaced video because height=%d <= 280",
466 p_context->flags |= CODEC_FLAG_INTERLACED_DCT;
467 #if LIBAVCODEC_BUILD >= 4698
468 if ( p_sys->b_interlace_me )
469 p_context->flags |= CODEC_FLAG_INTERLACED_ME;
474 if ( p_sys->b_trellis )
475 p_context->flags |= CODEC_FLAG_TRELLIS_QUANT;
477 if ( p_sys->i_qmin > 0 && p_sys->i_qmin == p_sys->i_qmax )
478 p_context->flags |= CODEC_FLAG_QSCALE;
480 #if LIBAVCODEC_BUILD >= 4702
481 if ( p_enc->i_threads >= 1 )
482 p_context->thread_count = p_enc->i_threads;
485 if( p_sys->i_vtolerance > 0 )
486 p_context->bit_rate_tolerance = p_sys->i_vtolerance;
488 if( p_sys->i_qmin > 0 )
489 p_context->mb_qmin = p_context->qmin = p_sys->i_qmin;
490 if( p_sys->i_qmax > 0 )
491 p_context->mb_qmax = p_context->qmax = p_sys->i_qmax;
492 p_context->max_qdiff = 3;
494 p_context->mb_decision = p_sys->i_hq;
496 if( p_sys->i_quality )
498 p_context->flags |= CODEC_FLAG_QSCALE;
499 #if LIBAVCODEC_BUILD >= 4668
500 p_context->global_quality = p_sys->i_quality;
504 else if( p_enc->fmt_in.i_cat == AUDIO_ES )
506 /* work around bug in libmp3lame encoding */
507 if( i_codec_id == CODEC_ID_MP3 && p_enc->fmt_in.audio.i_channels > 2 )
508 p_enc->fmt_in.audio.i_channels = 2;
510 p_enc->fmt_in.i_codec = AOUT_FMT_S16_NE;
511 p_context->sample_rate = p_enc->fmt_in.audio.i_rate;
512 p_context->channels = p_enc->fmt_in.audio.i_channels;
515 /* Misc parameters */
516 p_context->bit_rate = p_enc->fmt_out.i_bitrate;
518 if( i_codec_id == CODEC_ID_RAWVIDEO )
520 /* XXX: hack: Force same codec (will be handled by transcode) */
521 p_enc->fmt_in.i_codec = p_enc->fmt_out.i_codec;
522 p_context->pix_fmt = E_(GetFfmpegChroma)( p_enc->fmt_in.i_codec );
525 /* Make sure we get extradata filled by the encoder */
526 p_context->extradata_size = 0;
527 p_context->extradata = NULL;
528 p_context->flags |= CODEC_FLAG_GLOBAL_HEADER;
530 vlc_mutex_lock( lockval.p_address );
531 if( avcodec_open( p_context, p_codec ) )
533 vlc_mutex_unlock( lockval.p_address );
534 if( p_enc->fmt_in.i_cat == AUDIO_ES &&
535 (p_context->channels > 2 || i_codec_id == CODEC_ID_MP2
536 || i_codec_id == CODEC_ID_MP3) )
538 if( p_context->channels > 2 )
540 p_context->channels = 2;
541 p_enc->fmt_in.audio.i_channels = 2; // FIXME
542 msg_Warn( p_enc, "stereo mode selected (codec limitation)" );
545 if( i_codec_id == CODEC_ID_MP2 || i_codec_id == CODEC_ID_MP3 )
549 for ( i_frequency = 0; i_frequency < 6; i_frequency++ )
551 if ( p_enc->fmt_out.audio.i_rate
552 == mpa_freq_tab[i_frequency] )
555 if ( i_frequency == 6 )
557 msg_Err( p_enc, "MPEG audio doesn't support frequency=%d",
558 p_enc->fmt_out.audio.i_rate );
563 for ( i = 1; i < 14; i++ )
565 if ( p_enc->fmt_out.i_bitrate / 1000
566 <= mpa_bitrate_tab[i_frequency / 3][i] )
569 if ( p_enc->fmt_out.i_bitrate / 1000
570 != mpa_bitrate_tab[i_frequency / 3][i] )
573 "MPEG audio doesn't support bitrate=%d, using %d",
574 p_enc->fmt_out.i_bitrate,
575 mpa_bitrate_tab[i_frequency / 3][i] * 1000 );
576 p_enc->fmt_out.i_bitrate =
577 mpa_bitrate_tab[i_frequency / 3][i] * 1000;
578 p_context->bit_rate = p_enc->fmt_out.i_bitrate;
582 p_context->codec = NULL;
583 vlc_mutex_lock( lockval.p_address );
584 if( avcodec_open( p_context, p_codec ) )
586 vlc_mutex_unlock( lockval.p_address );
587 msg_Err( p_enc, "cannot open encoder" );
594 msg_Err( p_enc, "cannot open encoder" );
599 vlc_mutex_unlock( lockval.p_address );
601 p_enc->fmt_out.i_extra = p_context->extradata_size;
602 p_enc->fmt_out.p_extra = p_context->extradata;
603 p_context->flags &= ~CODEC_FLAG_GLOBAL_HEADER;
605 if( p_enc->fmt_in.i_cat == AUDIO_ES )
607 p_sys->p_buffer_out = malloc( 2 * AVCODEC_MAX_AUDIO_FRAME_SIZE );
608 p_sys->i_frame_size = p_context->frame_size * 2 * p_context->channels;
609 p_sys->p_buffer = malloc( p_sys->i_frame_size );
612 msg_Dbg( p_enc, "found encoder %s", psz_namecodec );
617 /****************************************************************************
618 * Ffmpeg threading system
619 ****************************************************************************/
620 #if LIBAVCODEC_BUILD >= 4702
621 static int FfmpegThread( struct thread_context_t *p_context )
623 while ( !p_context->b_die && !p_context->b_error )
625 vlc_mutex_lock( &p_context->lock );
626 while ( !p_context->b_work && !p_context->b_die && !p_context->b_error )
628 vlc_cond_wait( &p_context->cond, &p_context->lock );
630 p_context->b_work = 0;
631 vlc_mutex_unlock( &p_context->lock );
632 if ( p_context->b_die || p_context->b_error )
635 if ( p_context->pf_func )
637 p_context->i_ret = p_context->pf_func( p_context->p_context,
641 vlc_mutex_lock( &p_context->lock );
642 p_context->b_done = 1;
643 vlc_cond_signal( &p_context->cond );
644 vlc_mutex_unlock( &p_context->lock );
650 static int FfmpegExecute( AVCodecContext *s,
651 int (*pf_func)(AVCodecContext *c2, void *arg2),
652 void **arg, int *ret, int count )
654 struct thread_context_t ** pp_contexts =
655 (struct thread_context_t **)s->thread_opaque;
658 /* Note, we can be certain that this is not called with the same
659 * AVCodecContext by different threads at the same time */
660 for ( i = 0; i < count; i++ )
662 vlc_mutex_lock( &pp_contexts[i]->lock );
663 pp_contexts[i]->arg = arg[i];
664 pp_contexts[i]->pf_func = pf_func;
665 pp_contexts[i]->i_ret = 12345;
666 pp_contexts[i]->b_work = 1;
667 vlc_cond_signal( &pp_contexts[i]->cond );
668 vlc_mutex_unlock( &pp_contexts[i]->lock );
670 for ( i = 0; i < count; i++ )
672 vlc_mutex_lock( &pp_contexts[i]->lock );
673 while ( !pp_contexts[i]->b_done )
675 vlc_cond_wait( &pp_contexts[i]->cond, &pp_contexts[i]->lock );
677 pp_contexts[i]->b_done = 0;
678 pp_contexts[i]->pf_func = NULL;
679 vlc_mutex_unlock( &pp_contexts[i]->lock );
683 ret[i] = pp_contexts[i]->i_ret;
691 /****************************************************************************
692 * EncodeVideo: the whole thing
693 ****************************************************************************/
694 static block_t *EncodeVideo( encoder_t *p_enc, picture_t *p_pict )
696 encoder_sys_t *p_sys = p_enc->p_sys;
700 #if LIBAVCODEC_BUILD >= 4702
701 if ( !p_sys->b_inited && p_enc->i_threads >= 1 )
703 struct thread_context_t ** pp_contexts;
707 pp_contexts = malloc( sizeof(struct thread_context_t *)
708 * p_enc->i_threads );
709 p_sys->p_context->thread_opaque = (void *)pp_contexts;
711 for ( i = 0; i < p_enc->i_threads; i++ )
713 pp_contexts[i] = vlc_object_create( p_enc,
714 sizeof(struct thread_context_t) );
715 pp_contexts[i]->p_context = p_sys->p_context;
716 vlc_mutex_init( p_enc, &pp_contexts[i]->lock );
717 vlc_cond_init( p_enc, &pp_contexts[i]->cond );
718 pp_contexts[i]->b_work = 0;
719 pp_contexts[i]->b_done = 0;
720 if ( vlc_thread_create( pp_contexts[i], "encoder", FfmpegThread,
721 VLC_THREAD_PRIORITY_VIDEO, VLC_FALSE ) )
723 msg_Err( p_enc, "cannot spawn encoder thread, expect to die soon" );
728 p_sys->p_context->execute = FfmpegExecute;
732 memset( &frame, 0, sizeof( AVFrame ) );
733 for( i_plane = 0; i_plane < p_pict->i_planes; i_plane++ )
735 frame.data[i_plane] = p_pict->p[i_plane].p_pixels;
736 frame.linesize[i_plane] = p_pict->p[i_plane].i_pitch;
739 /* Let ffmpeg select the frame type */
742 frame.repeat_pict = p_pict->i_nb_fields - 2;
744 #if LIBAVCODEC_BUILD >= 4685
745 frame.interlaced_frame = !p_pict->b_progressive;
746 frame.top_field_first = !!p_pict->b_top_field_first;
749 #if LIBAVCODEC_BUILD < 4702
750 /* Set the pts of the frame being encoded (segfaults with mpeg4!)*/
751 if( p_enc->fmt_out.i_codec == VLC_FOURCC( 'm', 'p', 'g', 'v' ) ||
752 p_enc->fmt_out.i_codec == VLC_FOURCC( 'm', 'p', '1', 'v' ) ||
753 p_enc->fmt_out.i_codec == VLC_FOURCC( 'm', 'p', '2', 'v' ) )
758 frame.pts = p_pict->date ? p_pict->date : AV_NOPTS_VALUE;
760 if ( p_sys->b_hurry_up && frame.pts != AV_NOPTS_VALUE )
762 mtime_t current_date = mdate();
764 if ( current_date + HURRY_UP_GUARD3 > frame.pts )
766 p_sys->p_context->mb_decision = FF_MB_DECISION_SIMPLE;
767 p_sys->p_context->flags &= ~CODEC_FLAG_TRELLIS_QUANT;
768 msg_Dbg( p_enc, "hurry up mode 3" );
772 p_sys->p_context->mb_decision = p_sys->i_hq;
774 if ( current_date + HURRY_UP_GUARD2 > frame.pts )
776 p_sys->p_context->flags &= ~CODEC_FLAG_TRELLIS_QUANT;
777 #if LIBAVCODEC_BUILD >= 4690
778 p_sys->p_context->noise_reduction = p_sys->i_noise_reduction
779 + (HURRY_UP_GUARD2 + current_date - frame.pts) / 500;
781 msg_Dbg( p_enc, "hurry up mode 2" );
785 if ( p_sys->b_trellis )
786 p_sys->p_context->flags |= CODEC_FLAG_TRELLIS_QUANT;
787 #if LIBAVCODEC_BUILD >= 4690
788 p_sys->p_context->noise_reduction =
789 p_sys->i_noise_reduction;
794 if ( current_date + HURRY_UP_GUARD1 > frame.pts )
796 frame.pict_type = FF_P_TYPE;
797 /* msg_Dbg( p_enc, "hurry up mode 1 %lld", current_date + HURRY_UP_GUARD1 - frame.pts ); */
803 frame.pts = AV_NOPTS_VALUE;
806 if ( frame.pts != AV_NOPTS_VALUE && frame.pts != 0 )
808 if ( p_sys->i_last_pts == frame.pts )
810 msg_Warn( p_enc, "almost fed libavcodec with two frames with the "
811 "same PTS (" I64Fd ")", frame.pts );
814 else if ( p_sys->i_last_pts > frame.pts )
816 msg_Warn( p_enc, "almost fed libavcodec with a frame in the "
817 "past (current: " I64Fd ", last: "I64Fd")",
818 frame.pts, p_sys->i_last_pts );
823 p_sys->i_last_pts = frame.pts;
827 frame.quality = p_sys->i_quality;
829 /* Ugly work-around for stupid libavcodec behaviour */
830 #if LIBAVCODEC_BUILD >= 4722
832 p_sys->pi_delay_pts[p_sys->i_framenum % MAX_FRAME_DELAY] = frame.pts;
833 frame.pts = p_sys->i_framenum * AV_TIME_BASE *
834 p_enc->fmt_in.video.i_frame_rate_base;
835 frame.pts += p_enc->fmt_in.video.i_frame_rate - 1;
836 frame.pts /= p_enc->fmt_in.video.i_frame_rate;
838 /* End work-around */
840 i_out = avcodec_encode_video( p_sys->p_context, p_sys->p_buffer_out,
841 AVCODEC_MAX_VIDEO_FRAME_SIZE, &frame );
845 block_t *p_block = block_New( p_enc, i_out );
846 memcpy( p_block->p_buffer, p_sys->p_buffer_out, i_out );
848 /* FIXME, 3-2 pulldown is not handled correctly */
849 p_block->i_length = I64C(1000000) *
850 p_enc->fmt_in.video.i_frame_rate_base /
851 p_enc->fmt_in.video.i_frame_rate;
853 if( !p_sys->p_context->max_b_frames || !p_sys->p_context->delay )
855 /* No delay -> output pts == input pts */
856 p_block->i_pts = p_block->i_dts = p_pict->date;
858 else if( p_sys->p_context->coded_frame->pts != AV_NOPTS_VALUE &&
859 p_sys->p_context->coded_frame->pts != 0 &&
860 p_sys->i_buggy_pts_detect != p_sys->p_context->coded_frame->pts )
862 p_sys->i_buggy_pts_detect = p_sys->p_context->coded_frame->pts;
863 p_block->i_pts = p_sys->p_context->coded_frame->pts;
865 /* Ugly work-around for stupid libavcodec behaviour */
866 #if LIBAVCODEC_BUILD >= 4722
868 int64_t i_framenum = p_block->i_pts *
869 p_enc->fmt_in.video.i_frame_rate /
870 p_enc->fmt_in.video.i_frame_rate_base / AV_TIME_BASE;
872 p_block->i_pts = p_sys->pi_delay_pts[i_framenum % MAX_FRAME_DELAY];
875 /* End work-around */
877 if( p_sys->p_context->coded_frame->pict_type != FF_I_TYPE &&
878 p_sys->p_context->coded_frame->pict_type != FF_P_TYPE )
880 p_block->i_dts = p_block->i_pts;
884 if( p_sys->i_last_ref_pts )
886 p_block->i_dts = p_sys->i_last_ref_pts;
890 /* Let's put something sensible */
891 p_block->i_dts = p_block->i_pts;
894 p_sys->i_last_ref_pts = p_block->i_pts;
899 /* Buggy libavcodec which doesn't update coded_frame->pts
901 p_block->i_dts = p_block->i_pts = p_pict->date;
904 switch ( p_sys->p_context->coded_frame->pict_type )
907 p_block->i_flags |= BLOCK_FLAG_TYPE_I;
910 p_block->i_flags |= BLOCK_FLAG_TYPE_P;
913 p_block->i_flags |= BLOCK_FLAG_TYPE_B;
923 /****************************************************************************
924 * EncodeAudio: the whole thing
925 ****************************************************************************/
926 static block_t *EncodeAudio( encoder_t *p_enc, aout_buffer_t *p_aout_buf )
928 encoder_sys_t *p_sys = p_enc->p_sys;
929 block_t *p_block, *p_chain = NULL;
931 char *p_buffer = p_aout_buf->p_buffer;
932 int i_samples = p_aout_buf->i_nb_samples;
933 int i_samples_delay = p_sys->i_samples_delay;
935 p_sys->i_pts = p_aout_buf->start_date -
936 (mtime_t)1000000 * (mtime_t)p_sys->i_samples_delay /
937 (mtime_t)p_enc->fmt_in.audio.i_rate;
939 p_sys->i_samples_delay += i_samples;
941 while( p_sys->i_samples_delay >= p_sys->p_context->frame_size )
946 if( i_samples_delay )
948 /* Take care of the left-over from last time */
949 int i_delay_size = i_samples_delay * 2 *
950 p_sys->p_context->channels;
951 int i_size = p_sys->i_frame_size - i_delay_size;
953 p_samples = (int16_t *)p_sys->p_buffer;
954 memcpy( p_sys->p_buffer + i_delay_size, p_buffer, i_size );
955 p_buffer -= i_delay_size;
956 i_samples += i_samples_delay;
961 p_samples = (int16_t *)p_buffer;
964 i_out = avcodec_encode_audio( p_sys->p_context, p_sys->p_buffer_out,
965 2 * AVCODEC_MAX_AUDIO_FRAME_SIZE,
969 msg_Warn( p_enc, "avcodec_encode_audio: %d", i_out );
971 if( i_out < 0 ) break;
973 p_buffer += p_sys->i_frame_size;
974 p_sys->i_samples_delay -= p_sys->p_context->frame_size;
975 i_samples -= p_sys->p_context->frame_size;
977 if( i_out == 0 ) continue;
979 p_block = block_New( p_enc, i_out );
980 memcpy( p_block->p_buffer, p_sys->p_buffer_out, i_out );
982 p_block->i_length = (mtime_t)1000000 *
983 (mtime_t)p_sys->p_context->frame_size /
984 (mtime_t)p_sys->p_context->sample_rate;
986 p_block->i_dts = p_block->i_pts = p_sys->i_pts;
989 p_sys->i_pts += p_block->i_length;
990 block_ChainAppend( &p_chain, p_block );
993 /* Backup the remaining raw samples */
996 memcpy( p_sys->p_buffer + i_samples_delay * 2 *
997 p_sys->p_context->channels, p_buffer,
998 i_samples * 2 * p_sys->p_context->channels );
1004 /*****************************************************************************
1005 * CloseEncoder: ffmpeg encoder destruction
1006 *****************************************************************************/
1007 void E_(CloseEncoder)( vlc_object_t *p_this )
1009 encoder_t *p_enc = (encoder_t *)p_this;
1010 encoder_sys_t *p_sys = p_enc->p_sys;
1011 vlc_value_t lockval;
1013 var_Get( p_enc->p_libvlc, "avcodec", &lockval );
1015 #if LIBAVCODEC_BUILD >= 4702
1016 if ( p_sys->b_inited && p_enc->i_threads >= 1 )
1019 struct thread_context_t ** pp_contexts =
1020 (struct thread_context_t **)p_sys->p_context->thread_opaque;
1021 for ( i = 0; i < p_enc->i_threads; i++ )
1023 pp_contexts[i]->b_die = 1;
1024 vlc_cond_signal( &pp_contexts[i]->cond );
1025 vlc_thread_join( pp_contexts[i] );
1026 vlc_mutex_destroy( &pp_contexts[i]->lock );
1027 vlc_cond_destroy( &pp_contexts[i]->cond );
1028 vlc_object_destroy( pp_contexts[i] );
1031 free( pp_contexts );
1035 vlc_mutex_lock( lockval.p_address );
1036 avcodec_close( p_sys->p_context );
1037 vlc_mutex_unlock( lockval.p_address );
1038 av_free( p_sys->p_context );
1040 if( p_sys->p_buffer ) free( p_sys->p_buffer );
1041 if( p_sys->p_buffer_out ) free( p_sys->p_buffer_out );