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_codec.h>
36 #include <vlc_interface.h>
40 #ifdef HAVE_FFMPEG_AVCODEC_H
41 # include <ffmpeg/avcodec.h>
48 #define HURRY_UP_GUARD1 (450000)
49 #define HURRY_UP_GUARD2 (300000)
50 #define HURRY_UP_GUARD3 (100000)
52 #define MAX_FRAME_DELAY (FF_MAX_B_FRAMES + 2)
54 /*****************************************************************************
56 *****************************************************************************/
57 int E_(OpenEncoder) ( vlc_object_t * );
58 void E_(CloseEncoder)( vlc_object_t * );
60 static block_t *EncodeVideo( encoder_t *, picture_t * );
61 static block_t *EncodeAudio( encoder_t *, aout_buffer_t * );
63 struct thread_context_t;
64 static int FfmpegThread( struct thread_context_t *p_context );
65 static int FfmpegExecute( AVCodecContext *s,
66 int (*pf_func)(AVCodecContext *c2, void *arg2),
67 void **arg, int *ret, int count );
69 /*****************************************************************************
70 * thread_context_t : for multithreaded encoding
71 *****************************************************************************/
72 struct thread_context_t
76 AVCodecContext *p_context;
77 int (* pf_func)(AVCodecContext *c, void *arg);
83 vlc_bool_t b_work, b_done;
86 /*****************************************************************************
87 * encoder_sys_t : ffmpeg encoder descriptor
88 *****************************************************************************/
95 AVCodecContext *p_context;
106 mtime_t i_last_ref_pts;
107 mtime_t i_buggy_pts_detect;
118 /* Encoding settings */
125 vlc_bool_t b_strict_rc;
126 int i_rc_buffer_size;
127 float f_rc_buffer_aggressivity;
129 vlc_bool_t b_hurry_up;
130 vlc_bool_t b_interlace, b_interlace_me;
131 float f_i_quant_factor;
132 int i_noise_reduction;
133 vlc_bool_t b_mpeg4_matrix;
134 vlc_bool_t b_trellis;
135 int i_quality; /* for VBR */
136 float f_lumi_masking, f_dark_masking, f_p_masking, f_border_masking;
137 int i_luma_elim, i_chroma_elim;
139 /* Used to work around stupid timestamping behaviour in libavcodec */
141 mtime_t pi_delay_pts[MAX_FRAME_DELAY];
144 static const char *ppsz_enc_options[] = {
145 "keyint", "bframes", "vt", "qmin", "qmax", "hq", "strict-rc",
146 "rc-buffer-size", "rc-buffer-aggressivity", "pre-me", "hurry-up",
147 "interlace", "i-quant-factor", "noise-reduction", "mpeg4-matrix",
148 "trellis", "qscale", "strict", "lumi-masking", "dark-masking",
149 "p-masking", "border-masking", "luma-elim-threshold",
150 "chroma-elim-threshold", NULL
153 static const uint16_t mpa_bitrate_tab[2][15] =
155 {0, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384},
156 {0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160}
159 static const uint16_t mpa_freq_tab[6] =
160 { 44100, 48000, 32000, 22050, 24000, 16000 };
162 static const int16_t mpeg4_default_intra_matrix[64] = {
163 8, 17, 18, 19, 21, 23, 25, 27,
164 17, 18, 19, 21, 23, 25, 27, 28,
165 20, 21, 22, 23, 24, 26, 28, 30,
166 21, 22, 23, 24, 26, 28, 30, 32,
167 22, 23, 24, 26, 28, 30, 32, 35,
168 23, 24, 26, 28, 30, 32, 35, 38,
169 25, 26, 28, 30, 32, 35, 38, 41,
170 27, 28, 30, 32, 35, 38, 41, 45,
173 static const int16_t mpeg4_default_non_intra_matrix[64] = {
174 16, 17, 18, 19, 20, 21, 22, 23,
175 17, 18, 19, 20, 21, 22, 23, 24,
176 18, 19, 20, 21, 22, 23, 24, 25,
177 19, 20, 21, 22, 23, 24, 26, 27,
178 20, 21, 22, 23, 25, 26, 27, 28,
179 21, 22, 23, 24, 26, 27, 28, 30,
180 22, 23, 24, 26, 27, 28, 30, 31,
181 23, 24, 25, 27, 28, 30, 31, 33,
185 /*****************************************************************************
186 * OpenEncoder: probe the encoder
187 *****************************************************************************/
189 int E_(OpenEncoder)( vlc_object_t *p_this )
191 encoder_t *p_enc = (encoder_t *)p_this;
192 encoder_sys_t *p_sys = p_enc->p_sys;
193 AVCodecContext *p_context;
195 int i_codec_id, i_cat;
196 const char *psz_namecodec;
200 var_Get( p_enc->p_libvlc_global, "avcodec", &lockval );
202 if( !E_(GetFfmpegCodec)( p_enc->fmt_out.i_codec, &i_cat, &i_codec_id,
205 if( E_(GetFfmpegChroma)( p_enc->fmt_out.i_codec ) < 0 )
207 /* handed chroma output */
211 i_codec_id = CODEC_ID_RAWVIDEO;
212 psz_namecodec = "Raw video";
215 if( p_enc->fmt_out.i_cat == VIDEO_ES && i_cat != VIDEO_ES )
217 msg_Err( p_enc, "\"%s\" is not a video encoder", psz_namecodec );
218 intf_UserFatal( p_enc, VLC_FALSE, _("Streaming / Transcoding failed"),
219 _("\"%s\" is no video encoder."), psz_namecodec );
223 if( p_enc->fmt_out.i_cat == AUDIO_ES && i_cat != AUDIO_ES )
225 msg_Err( p_enc, "\"%s\" is not an audio encoder", psz_namecodec );
226 intf_UserFatal( p_enc, VLC_FALSE, _("Streaming / Transcoding failed"),
227 _("\"%s\" is no audio encoder."), psz_namecodec );
231 /* Initialization must be done before avcodec_find_encoder() */
232 E_(InitLibavcodec)(p_this);
234 p_codec = avcodec_find_encoder( i_codec_id );
237 msg_Err( p_enc, "cannot find encoder %s", psz_namecodec );
238 intf_UserFatal( p_enc, VLC_FALSE, _("Streaming / Transcoding failed"),
239 _("VLC could not find encoder \"%s\"."), psz_namecodec );
243 /* Allocate the memory needed to store the encoder's structure */
244 if( ( p_sys = (encoder_sys_t *)malloc(sizeof(encoder_sys_t)) ) == NULL )
246 msg_Err( p_enc, "out of memory" );
249 memset( p_sys, 0, sizeof(encoder_sys_t) );
250 p_enc->p_sys = p_sys;
251 p_sys->p_codec = p_codec;
253 p_enc->pf_encode_video = EncodeVideo;
254 p_enc->pf_encode_audio = EncodeAudio;
256 p_sys->p_buffer_out = NULL;
257 p_sys->p_buffer = NULL;
259 p_sys->p_context = p_context = avcodec_alloc_context();
260 p_context->debug = config_GetInt( p_enc, "ffmpeg-debug" );
261 p_context->opaque = (void *)p_this;
263 /* Set CPU capabilities */
264 unsigned i_cpu = vlc_CPU();
265 p_context->dsp_mask = 0;
266 if( !(i_cpu & CPU_CAPABILITY_MMX) )
268 p_context->dsp_mask |= FF_MM_MMX;
270 if( !(i_cpu & CPU_CAPABILITY_MMXEXT) )
272 p_context->dsp_mask |= FF_MM_MMXEXT;
274 if( !(i_cpu & CPU_CAPABILITY_3DNOW) )
276 p_context->dsp_mask |= FF_MM_3DNOW;
278 if( !(i_cpu & CPU_CAPABILITY_SSE) )
280 p_context->dsp_mask |= FF_MM_SSE;
281 p_context->dsp_mask |= FF_MM_SSE2;
284 config_ChainParse( p_enc, ENC_CFG_PREFIX, ppsz_enc_options, p_enc->p_cfg );
286 var_Get( p_enc, ENC_CFG_PREFIX "keyint", &val );
287 p_sys->i_key_int = val.i_int;
289 var_Get( p_enc, ENC_CFG_PREFIX "bframes", &val );
290 p_sys->i_b_frames = val.i_int;
292 var_Get( p_enc, ENC_CFG_PREFIX "vt", &val );
293 p_sys->i_vtolerance = val.i_int;
295 var_Get( p_enc, ENC_CFG_PREFIX "interlace", &val );
296 p_sys->b_interlace = val.b_bool;
298 var_Get( p_enc, ENC_CFG_PREFIX "interlace-me", &val );
299 p_sys->b_interlace_me = val.b_bool;
301 var_Get( p_enc, ENC_CFG_PREFIX "pre-me", &val );
302 p_sys->b_pre_me = val.b_bool;
304 var_Get( p_enc, ENC_CFG_PREFIX "hurry-up", &val );
305 p_sys->b_hurry_up = val.b_bool;
306 if( p_sys->b_hurry_up )
308 /* hurry up mode needs noise reduction, even small */
309 p_sys->i_noise_reduction = 1;
312 var_Get( p_enc, ENC_CFG_PREFIX "strict-rc", &val );
313 p_sys->b_strict_rc = val.b_bool;
314 var_Get( p_enc, ENC_CFG_PREFIX "rc-buffer-size", &val );
315 p_sys->i_rc_buffer_size = val.i_int;
316 var_Get( p_enc, ENC_CFG_PREFIX "rc-buffer-aggressivity", &val );
317 p_sys->f_rc_buffer_aggressivity = val.f_float;
319 var_Get( p_enc, ENC_CFG_PREFIX "i-quant-factor", &val );
320 p_sys->f_i_quant_factor = val.f_float;
322 var_Get( p_enc, ENC_CFG_PREFIX "noise-reduction", &val );
323 p_sys->i_noise_reduction = val.i_int;
325 var_Get( p_enc, ENC_CFG_PREFIX "mpeg4-matrix", &val );
326 p_sys->b_mpeg4_matrix = val.b_bool;
328 var_Get( p_enc, ENC_CFG_PREFIX "qscale", &val );
329 if( val.f_float < 0.01 || val.f_float > 255.0 ) val.f_float = 0;
330 p_sys->i_quality = (int)(FF_QP2LAMBDA * val.f_float + 0.5);
332 var_Get( p_enc, ENC_CFG_PREFIX "hq", &val );
333 if( val.psz_string && *val.psz_string )
335 if( !strcmp( val.psz_string, "rd" ) )
336 p_sys->i_hq = FF_MB_DECISION_RD;
337 else if( !strcmp( val.psz_string, "bits" ) )
338 p_sys->i_hq = FF_MB_DECISION_BITS;
339 else if( !strcmp( val.psz_string, "simple" ) )
340 p_sys->i_hq = FF_MB_DECISION_SIMPLE;
342 p_sys->i_hq = FF_MB_DECISION_RD;
344 if( val.psz_string ) free( val.psz_string );
346 var_Get( p_enc, ENC_CFG_PREFIX "qmin", &val );
347 p_sys->i_qmin = val.i_int;
348 var_Get( p_enc, ENC_CFG_PREFIX "qmax", &val );
349 p_sys->i_qmax = val.i_int;
350 var_Get( p_enc, ENC_CFG_PREFIX "trellis", &val );
351 p_sys->b_trellis = val.b_bool;
353 var_Get( p_enc, ENC_CFG_PREFIX "strict", &val );
354 if( val.i_int < - 1 || val.i_int > 1 ) val.i_int = 0;
355 p_context->strict_std_compliance = val.i_int;
357 var_Get( p_enc, ENC_CFG_PREFIX "lumi-masking", &val );
358 p_sys->f_lumi_masking = val.f_float;
359 var_Get( p_enc, ENC_CFG_PREFIX "dark-masking", &val );
360 p_sys->f_dark_masking = val.f_float;
361 var_Get( p_enc, ENC_CFG_PREFIX "p-masking", &val );
362 p_sys->f_p_masking = val.f_float;
363 var_Get( p_enc, ENC_CFG_PREFIX "border-masking", &val );
364 p_sys->f_border_masking = val.f_float;
365 var_Get( p_enc, ENC_CFG_PREFIX "luma-elim-threshold", &val );
366 p_sys->i_luma_elim = val.i_int;
367 var_Get( p_enc, ENC_CFG_PREFIX "chroma-elim-threshold", &val );
368 p_sys->i_chroma_elim = val.i_int;
370 if( p_enc->fmt_in.i_cat == VIDEO_ES )
372 int i_aspect_num, i_aspect_den;
374 if( !p_enc->fmt_in.video.i_width || !p_enc->fmt_in.video.i_height )
376 msg_Warn( p_enc, "invalid size %ix%i", p_enc->fmt_in.video.i_width,
377 p_enc->fmt_in.video.i_height );
382 p_context->width = p_enc->fmt_in.video.i_width;
383 p_context->height = p_enc->fmt_in.video.i_height;
384 if( p_enc->fmt_out.i_codec == VLC_FOURCC('m', 'p', '2', 'v')
385 && (p_context->width > 720 || p_context->height > 576) )
386 p_context->level = 4; /* High level */
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 /* Defaults from ffmpeg.c */
392 p_context->qblur = 0.5;
393 p_context->qcompress = 0.5;
394 p_context->b_quant_offset = 1.25;
395 p_context->b_quant_factor = 1.25;
396 p_context->i_quant_offset = 0.0;
397 p_context->i_quant_factor = -0.8;
399 p_context->lumi_masking = p_sys->f_lumi_masking;
400 p_context->dark_masking = p_sys->f_dark_masking;
401 p_context->p_masking = p_sys->f_p_masking;
402 p_context->border_masking = p_sys->f_border_masking;
403 p_context->luma_elim_threshold = p_sys->i_luma_elim;
404 p_context->chroma_elim_threshold = p_sys->i_chroma_elim;
406 if( p_sys->i_key_int > 0 )
407 p_context->gop_size = p_sys->i_key_int;
408 p_context->max_b_frames =
409 __MAX( __MIN( p_sys->i_b_frames, FF_MAX_B_FRAMES ), 0 );
410 p_context->b_frame_strategy = 0;
411 if( !p_context->max_b_frames &&
412 ( p_enc->fmt_out.i_codec == VLC_FOURCC('m', 'p', '2', 'v') ||
413 p_enc->fmt_out.i_codec == VLC_FOURCC('m', 'p', '1', 'v') ) )
414 p_context->flags |= CODEC_FLAG_LOW_DELAY;
416 av_reduce( &i_aspect_num, &i_aspect_den,
417 p_enc->fmt_in.video.i_aspect,
418 VOUT_ASPECT_FACTOR, 1 << 30 /* something big */ );
419 av_reduce( &p_context->sample_aspect_ratio.num,
420 &p_context->sample_aspect_ratio.den,
421 i_aspect_num * (int64_t)p_context->height,
422 i_aspect_den * (int64_t)p_context->width, 1 << 30 );
424 p_sys->p_buffer_out = malloc( p_context->height * p_context->width * 3 );
426 p_enc->fmt_in.i_codec = VLC_FOURCC('I','4','2','0');
427 p_context->pix_fmt = E_(GetFfmpegChroma)( p_enc->fmt_in.i_codec );
428 if( p_codec->pix_fmts )
430 const enum PixelFormat *p = p_codec->pix_fmts;
431 for( ; *p != -1; p++ )
433 if( *p == p_context->pix_fmt ) break;
435 if( *p == -1 ) p_context->pix_fmt = p_codec->pix_fmts[0];
436 p_enc->fmt_in.i_codec = E_(GetVlcChroma)( p_context->pix_fmt );
439 if ( p_sys->b_strict_rc )
441 p_context->rc_max_rate = p_enc->fmt_out.i_bitrate;
442 p_context->rc_buffer_size = p_sys->i_rc_buffer_size;
443 /* This is from ffmpeg's ffmpeg.c : */
444 p_context->rc_initial_buffer_occupancy
445 = p_sys->i_rc_buffer_size * 3/4;
446 p_context->rc_buffer_aggressivity = p_sys->f_rc_buffer_aggressivity;
449 if ( p_sys->f_i_quant_factor != 0.0 )
450 p_context->i_quant_factor = p_sys->f_i_quant_factor;
452 p_context->noise_reduction = p_sys->i_noise_reduction;
454 if ( p_sys->b_mpeg4_matrix )
456 p_context->intra_matrix = mpeg4_default_intra_matrix;
457 p_context->inter_matrix = mpeg4_default_non_intra_matrix;
460 if ( p_sys->b_pre_me )
462 p_context->pre_me = 1;
463 p_context->me_pre_cmp = FF_CMP_CHROMA;
466 if ( p_sys->b_interlace )
468 if ( p_context->height <= 280 )
470 if ( p_context->height != 16 || p_context->width != 16 )
472 "disabling interlaced video because height=%d <= 280",
477 p_context->flags |= CODEC_FLAG_INTERLACED_DCT;
478 if ( p_sys->b_interlace_me )
479 p_context->flags |= CODEC_FLAG_INTERLACED_ME;
483 if ( p_sys->b_trellis )
484 p_context->flags |= CODEC_FLAG_TRELLIS_QUANT;
486 if ( p_sys->i_qmin > 0 && p_sys->i_qmin == p_sys->i_qmax )
487 p_context->flags |= CODEC_FLAG_QSCALE;
489 if ( p_enc->i_threads >= 1 )
490 p_context->thread_count = p_enc->i_threads;
492 if( p_sys->i_vtolerance > 0 )
493 p_context->bit_rate_tolerance = p_sys->i_vtolerance;
495 if( p_sys->i_qmin > 0 )
496 p_context->mb_qmin = p_context->qmin = p_sys->i_qmin;
497 if( p_sys->i_qmax > 0 )
498 p_context->mb_qmax = p_context->qmax = p_sys->i_qmax;
499 p_context->max_qdiff = 3;
501 p_context->mb_decision = p_sys->i_hq;
503 if( p_sys->i_quality )
505 p_context->flags |= CODEC_FLAG_QSCALE;
506 p_context->global_quality = p_sys->i_quality;
509 else if( p_enc->fmt_in.i_cat == AUDIO_ES )
511 /* work around bug in libmp3lame encoding */
512 if( i_codec_id == CODEC_ID_MP3 && p_enc->fmt_in.audio.i_channels > 2 )
513 p_enc->fmt_in.audio.i_channels = 2;
515 p_enc->fmt_in.i_codec = AOUT_FMT_S16_NE;
516 p_context->sample_rate = p_enc->fmt_in.audio.i_rate;
517 p_context->channels = p_enc->fmt_in.audio.i_channels;
520 /* Misc parameters */
521 p_context->bit_rate = p_enc->fmt_out.i_bitrate;
523 if( i_codec_id == CODEC_ID_RAWVIDEO )
525 /* XXX: hack: Force same codec (will be handled by transcode) */
526 p_enc->fmt_in.i_codec = p_enc->fmt_out.i_codec;
527 p_context->pix_fmt = E_(GetFfmpegChroma)( p_enc->fmt_in.i_codec );
530 /* Make sure we get extradata filled by the encoder */
531 p_context->extradata_size = 0;
532 p_context->extradata = NULL;
533 p_context->flags |= CODEC_FLAG_GLOBAL_HEADER;
535 vlc_mutex_lock( lockval.p_address );
536 if( avcodec_open( p_context, p_codec ) )
538 vlc_mutex_unlock( lockval.p_address );
539 if( p_enc->fmt_in.i_cat == AUDIO_ES &&
540 (p_context->channels > 2 || i_codec_id == CODEC_ID_MP2
541 || i_codec_id == CODEC_ID_MP3) )
543 if( p_context->channels > 2 )
545 p_context->channels = 2;
546 p_enc->fmt_in.audio.i_channels = 2; // FIXME
547 msg_Warn( p_enc, "stereo mode selected (codec limitation)" );
550 if( i_codec_id == CODEC_ID_MP2 || i_codec_id == CODEC_ID_MP3 )
554 for ( i_frequency = 0; i_frequency < 6; i_frequency++ )
556 if ( p_enc->fmt_out.audio.i_rate
557 == mpa_freq_tab[i_frequency] )
560 if ( i_frequency == 6 )
562 msg_Err( p_enc, "MPEG audio doesn't support frequency=%d",
563 p_enc->fmt_out.audio.i_rate );
568 for ( i = 1; i < 14; i++ )
570 if ( p_enc->fmt_out.i_bitrate / 1000
571 <= mpa_bitrate_tab[i_frequency / 3][i] )
574 if ( p_enc->fmt_out.i_bitrate / 1000
575 != mpa_bitrate_tab[i_frequency / 3][i] )
578 "MPEG audio doesn't support bitrate=%d, using %d",
579 p_enc->fmt_out.i_bitrate,
580 mpa_bitrate_tab[i_frequency / 3][i] * 1000 );
581 p_enc->fmt_out.i_bitrate =
582 mpa_bitrate_tab[i_frequency / 3][i] * 1000;
583 p_context->bit_rate = p_enc->fmt_out.i_bitrate;
587 p_context->codec = NULL;
588 vlc_mutex_lock( lockval.p_address );
589 if( avcodec_open( p_context, p_codec ) )
591 vlc_mutex_unlock( lockval.p_address );
592 msg_Err( p_enc, "cannot open encoder" );
593 intf_UserFatal( p_enc, VLC_FALSE, _("Streaming / Transcoding failed"),
594 _("VLC could not open the encoder.") );
601 msg_Err( p_enc, "cannot open encoder" );
602 intf_UserFatal( p_enc, VLC_FALSE, _("Streaming / Transcoding failed"),
603 _("VLC could not open the encoder.") );
608 vlc_mutex_unlock( lockval.p_address );
610 p_enc->fmt_out.i_extra = p_context->extradata_size;
611 if( p_enc->fmt_out.i_extra )
613 p_enc->fmt_out.p_extra = malloc( p_enc->fmt_out.i_extra );
614 memcpy( p_enc->fmt_out.p_extra, p_context->extradata,
615 p_enc->fmt_out.i_extra );
617 p_context->flags &= ~CODEC_FLAG_GLOBAL_HEADER;
619 if( p_enc->fmt_in.i_cat == AUDIO_ES )
621 p_sys->p_buffer_out = malloc( 2 * AVCODEC_MAX_AUDIO_FRAME_SIZE );
622 p_sys->i_frame_size = p_context->frame_size * 2 * p_context->channels;
623 p_sys->p_buffer = malloc( p_sys->i_frame_size );
626 msg_Dbg( p_enc, "found encoder %s", psz_namecodec );
631 /****************************************************************************
632 * Ffmpeg threading system
633 ****************************************************************************/
634 static int FfmpegThread( struct thread_context_t *p_context )
636 while ( !p_context->b_die && !p_context->b_error )
638 vlc_mutex_lock( &p_context->lock );
639 while ( !p_context->b_work && !p_context->b_die && !p_context->b_error )
641 vlc_cond_wait( &p_context->cond, &p_context->lock );
643 p_context->b_work = 0;
644 vlc_mutex_unlock( &p_context->lock );
645 if ( p_context->b_die || p_context->b_error )
648 if ( p_context->pf_func )
650 p_context->i_ret = p_context->pf_func( p_context->p_context,
654 vlc_mutex_lock( &p_context->lock );
655 p_context->b_done = 1;
656 vlc_cond_signal( &p_context->cond );
657 vlc_mutex_unlock( &p_context->lock );
663 static int FfmpegExecute( AVCodecContext *s,
664 int (*pf_func)(AVCodecContext *c2, void *arg2),
665 void **arg, int *ret, int count )
667 struct thread_context_t ** pp_contexts =
668 (struct thread_context_t **)s->thread_opaque;
671 /* Note, we can be certain that this is not called with the same
672 * AVCodecContext by different threads at the same time */
673 for ( i = 0; i < count; i++ )
675 vlc_mutex_lock( &pp_contexts[i]->lock );
676 pp_contexts[i]->arg = arg[i];
677 pp_contexts[i]->pf_func = pf_func;
678 pp_contexts[i]->i_ret = 12345;
679 pp_contexts[i]->b_work = 1;
680 vlc_cond_signal( &pp_contexts[i]->cond );
681 vlc_mutex_unlock( &pp_contexts[i]->lock );
683 for ( i = 0; i < count; i++ )
685 vlc_mutex_lock( &pp_contexts[i]->lock );
686 while ( !pp_contexts[i]->b_done )
688 vlc_cond_wait( &pp_contexts[i]->cond, &pp_contexts[i]->lock );
690 pp_contexts[i]->b_done = 0;
691 pp_contexts[i]->pf_func = NULL;
692 vlc_mutex_unlock( &pp_contexts[i]->lock );
696 ret[i] = pp_contexts[i]->i_ret;
703 /****************************************************************************
704 * EncodeVideo: the whole thing
705 ****************************************************************************/
706 static block_t *EncodeVideo( encoder_t *p_enc, picture_t *p_pict )
708 encoder_sys_t *p_sys = p_enc->p_sys;
712 if ( !p_sys->b_inited && p_enc->i_threads >= 1 )
714 struct thread_context_t ** pp_contexts;
718 pp_contexts = malloc( sizeof(struct thread_context_t *)
719 * p_enc->i_threads );
720 p_sys->p_context->thread_opaque = (void *)pp_contexts;
722 for ( i = 0; i < p_enc->i_threads; i++ )
724 pp_contexts[i] = vlc_object_create( p_enc,
725 sizeof(struct thread_context_t) );
726 pp_contexts[i]->p_context = p_sys->p_context;
727 vlc_mutex_init( p_enc, &pp_contexts[i]->lock );
728 vlc_cond_init( p_enc, &pp_contexts[i]->cond );
729 pp_contexts[i]->b_work = 0;
730 pp_contexts[i]->b_done = 0;
731 if ( vlc_thread_create( pp_contexts[i], "encoder", FfmpegThread,
732 VLC_THREAD_PRIORITY_VIDEO, VLC_FALSE ) )
734 msg_Err( p_enc, "cannot spawn encoder thread, expect to die soon" );
739 p_sys->p_context->execute = FfmpegExecute;
742 memset( &frame, 0, sizeof( AVFrame ) );
743 for( i_plane = 0; i_plane < p_pict->i_planes; i_plane++ )
745 frame.data[i_plane] = p_pict->p[i_plane].p_pixels;
746 frame.linesize[i_plane] = p_pict->p[i_plane].i_pitch;
749 /* Let ffmpeg select the frame type */
752 frame.repeat_pict = p_pict->i_nb_fields - 2;
753 frame.interlaced_frame = !p_pict->b_progressive;
754 frame.top_field_first = !!p_pict->b_top_field_first;
756 /* Set the pts of the frame being encoded (segfaults with mpeg4!)*/
757 if( p_enc->fmt_out.i_codec == VLC_FOURCC( 'm', 'p', 'g', 'v' ) ||
758 p_enc->fmt_out.i_codec == VLC_FOURCC( 'm', 'p', '1', 'v' ) ||
759 p_enc->fmt_out.i_codec == VLC_FOURCC( 'm', 'p', '2', 'v' ) )
761 frame.pts = p_pict->date ? p_pict->date : (int64_t)AV_NOPTS_VALUE;
763 if ( p_sys->b_hurry_up && frame.pts != (int64_t)AV_NOPTS_VALUE )
765 mtime_t current_date = mdate();
767 if ( current_date + HURRY_UP_GUARD3 > frame.pts )
769 p_sys->p_context->mb_decision = FF_MB_DECISION_SIMPLE;
770 p_sys->p_context->flags &= ~CODEC_FLAG_TRELLIS_QUANT;
771 msg_Dbg( p_enc, "hurry up mode 3" );
775 p_sys->p_context->mb_decision = p_sys->i_hq;
777 if ( current_date + HURRY_UP_GUARD2 > frame.pts )
779 p_sys->p_context->flags &= ~CODEC_FLAG_TRELLIS_QUANT;
780 p_sys->p_context->noise_reduction = p_sys->i_noise_reduction
781 + (HURRY_UP_GUARD2 + current_date - frame.pts) / 500;
782 msg_Dbg( p_enc, "hurry up mode 2" );
786 if ( p_sys->b_trellis )
787 p_sys->p_context->flags |= CODEC_FLAG_TRELLIS_QUANT;
789 p_sys->p_context->noise_reduction =
790 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 = (int64_t)AV_NOPTS_VALUE;
806 if ( frame.pts != (int64_t)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 */
831 p_sys->pi_delay_pts[p_sys->i_framenum % MAX_FRAME_DELAY] = frame.pts;
832 frame.pts = p_sys->i_framenum * AV_TIME_BASE *
833 p_enc->fmt_in.video.i_frame_rate_base;
834 frame.pts += p_enc->fmt_in.video.i_frame_rate - 1;
835 frame.pts /= p_enc->fmt_in.video.i_frame_rate;
836 /* End work-around */
838 i_out = avcodec_encode_video( p_sys->p_context, (uint8_t*)p_sys->p_buffer_out,
839 p_sys->p_context->height * p_sys->p_context->width * 3, &frame );
843 block_t *p_block = block_New( p_enc, i_out );
844 memcpy( p_block->p_buffer, p_sys->p_buffer_out, i_out );
846 /* FIXME, 3-2 pulldown is not handled correctly */
847 p_block->i_length = I64C(1000000) *
848 p_enc->fmt_in.video.i_frame_rate_base /
849 p_enc->fmt_in.video.i_frame_rate;
851 if( !p_sys->p_context->max_b_frames || !p_sys->p_context->delay )
853 /* No delay -> output pts == input pts */
854 p_block->i_pts = p_block->i_dts = p_pict->date;
856 else if( p_sys->p_context->coded_frame->pts != (int64_t)AV_NOPTS_VALUE &&
857 p_sys->p_context->coded_frame->pts != 0 &&
858 p_sys->i_buggy_pts_detect != p_sys->p_context->coded_frame->pts )
860 p_sys->i_buggy_pts_detect = p_sys->p_context->coded_frame->pts;
861 p_block->i_pts = p_sys->p_context->coded_frame->pts;
863 /* Ugly work-around for stupid libavcodec behaviour */
865 int64_t i_framenum = p_block->i_pts *
866 p_enc->fmt_in.video.i_frame_rate /
867 p_enc->fmt_in.video.i_frame_rate_base / AV_TIME_BASE;
869 p_block->i_pts = p_sys->pi_delay_pts[i_framenum % MAX_FRAME_DELAY];
871 /* End work-around */
873 if( p_sys->p_context->coded_frame->pict_type != FF_I_TYPE &&
874 p_sys->p_context->coded_frame->pict_type != FF_P_TYPE )
876 p_block->i_dts = p_block->i_pts;
880 if( p_sys->i_last_ref_pts )
882 p_block->i_dts = p_sys->i_last_ref_pts;
886 /* Let's put something sensible */
887 p_block->i_dts = p_block->i_pts;
890 p_sys->i_last_ref_pts = p_block->i_pts;
895 /* Buggy libavcodec which doesn't update coded_frame->pts
897 p_block->i_dts = p_block->i_pts = p_pict->date;
900 switch ( p_sys->p_context->coded_frame->pict_type )
903 p_block->i_flags |= BLOCK_FLAG_TYPE_I;
906 p_block->i_flags |= BLOCK_FLAG_TYPE_P;
909 p_block->i_flags |= BLOCK_FLAG_TYPE_B;
919 /****************************************************************************
920 * EncodeAudio: the whole thing
921 ****************************************************************************/
922 static block_t *EncodeAudio( encoder_t *p_enc, aout_buffer_t *p_aout_buf )
924 encoder_sys_t *p_sys = p_enc->p_sys;
925 block_t *p_block, *p_chain = NULL;
927 uint8_t *p_buffer = p_aout_buf->p_buffer;
928 int i_samples = p_aout_buf->i_nb_samples;
929 int i_samples_delay = p_sys->i_samples_delay;
931 p_sys->i_pts = p_aout_buf->start_date -
932 (mtime_t)1000000 * (mtime_t)p_sys->i_samples_delay /
933 (mtime_t)p_enc->fmt_in.audio.i_rate;
935 p_sys->i_samples_delay += i_samples;
937 while( p_sys->i_samples_delay >= p_sys->p_context->frame_size )
942 if( i_samples_delay )
944 /* Take care of the left-over from last time */
945 int i_delay_size = i_samples_delay * 2 *
946 p_sys->p_context->channels;
947 int i_size = p_sys->i_frame_size - i_delay_size;
949 p_samples = (int16_t *)p_sys->p_buffer;
950 memcpy( p_sys->p_buffer + i_delay_size, p_buffer, i_size );
951 p_buffer -= i_delay_size;
952 i_samples += i_samples_delay;
957 p_samples = (int16_t *)p_buffer;
960 i_out = avcodec_encode_audio( p_sys->p_context, (uint8_t *)p_sys->p_buffer_out,
961 2 * AVCODEC_MAX_AUDIO_FRAME_SIZE,
965 msg_Warn( p_enc, "avcodec_encode_audio: %d", i_out );
967 if( i_out < 0 ) break;
969 p_buffer += p_sys->i_frame_size;
970 p_sys->i_samples_delay -= p_sys->p_context->frame_size;
971 i_samples -= p_sys->p_context->frame_size;
973 if( i_out == 0 ) continue;
975 p_block = block_New( p_enc, i_out );
976 memcpy( p_block->p_buffer, p_sys->p_buffer_out, i_out );
978 p_block->i_length = (mtime_t)1000000 *
979 (mtime_t)p_sys->p_context->frame_size /
980 (mtime_t)p_sys->p_context->sample_rate;
982 p_block->i_dts = p_block->i_pts = p_sys->i_pts;
985 p_sys->i_pts += p_block->i_length;
986 block_ChainAppend( &p_chain, p_block );
989 /* Backup the remaining raw samples */
992 memcpy( p_sys->p_buffer + i_samples_delay * 2 *
993 p_sys->p_context->channels, p_buffer,
994 i_samples * 2 * p_sys->p_context->channels );
1000 /*****************************************************************************
1001 * CloseEncoder: ffmpeg encoder destruction
1002 *****************************************************************************/
1003 void E_(CloseEncoder)( vlc_object_t *p_this )
1005 encoder_t *p_enc = (encoder_t *)p_this;
1006 encoder_sys_t *p_sys = p_enc->p_sys;
1007 vlc_value_t lockval;
1009 var_Get( p_enc->p_libvlc_global, "avcodec", &lockval );
1011 if ( p_sys->b_inited && p_enc->i_threads >= 1 )
1014 struct thread_context_t ** pp_contexts =
1015 (struct thread_context_t **)p_sys->p_context->thread_opaque;
1016 for ( i = 0; i < p_enc->i_threads; i++ )
1018 vlc_object_kill( pp_contexts[i] );
1019 vlc_cond_signal( &pp_contexts[i]->cond );
1020 vlc_thread_join( pp_contexts[i] );
1021 vlc_mutex_destroy( &pp_contexts[i]->lock );
1022 vlc_cond_destroy( &pp_contexts[i]->cond );
1023 vlc_object_destroy( pp_contexts[i] );
1026 free( pp_contexts );
1029 vlc_mutex_lock( lockval.p_address );
1030 avcodec_close( p_sys->p_context );
1031 vlc_mutex_unlock( lockval.p_address );
1032 av_free( p_sys->p_context );
1034 if( p_sys->p_buffer ) free( p_sys->p_buffer );
1035 if( p_sys->p_buffer_out ) free( p_sys->p_buffer_out );