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 *****************************************************************************/
39 #include <vlc_codec.h>
40 #include <vlc_interface.h>
44 #ifdef HAVE_LIBAVCODEC_AVCODEC_H
45 # include <libavcodec/avcodec.h>
46 #elif defined(HAVE_FFMPEG_AVCODEC_H)
47 # include <ffmpeg/avcodec.h>
54 #define HURRY_UP_GUARD1 (450000)
55 #define HURRY_UP_GUARD2 (300000)
56 #define HURRY_UP_GUARD3 (100000)
58 #define MAX_FRAME_DELAY (FF_MAX_B_FRAMES + 2)
60 /*****************************************************************************
62 *****************************************************************************/
63 int E_(OpenEncoder) ( vlc_object_t * );
64 void E_(CloseEncoder)( vlc_object_t * );
66 static block_t *EncodeVideo( encoder_t *, picture_t * );
67 static block_t *EncodeAudio( encoder_t *, aout_buffer_t * );
69 struct thread_context_t;
70 static int FfmpegThread( struct thread_context_t *p_context );
71 static int FfmpegExecute( AVCodecContext *s,
72 int (*pf_func)(AVCodecContext *c2, void *arg2),
73 void **arg, int *ret, int count );
75 /*****************************************************************************
76 * thread_context_t : for multithreaded encoding
77 *****************************************************************************/
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;
92 /*****************************************************************************
93 * encoder_sys_t : ffmpeg encoder descriptor
94 *****************************************************************************/
101 AVCodecContext *p_context;
112 mtime_t i_last_ref_pts;
113 mtime_t i_buggy_pts_detect;
124 /* Encoding settings */
131 vlc_bool_t b_strict_rc;
132 int i_rc_buffer_size;
133 float f_rc_buffer_aggressivity;
135 vlc_bool_t b_hurry_up;
136 vlc_bool_t b_interlace, b_interlace_me;
137 float f_i_quant_factor;
138 int i_noise_reduction;
139 vlc_bool_t b_mpeg4_matrix;
140 vlc_bool_t b_trellis;
141 int i_quality; /* for VBR */
142 float f_lumi_masking, f_dark_masking, f_p_masking, f_border_masking;
143 int i_luma_elim, i_chroma_elim;
144 int i_aac_profile; /* AAC profile to use.*/
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", "aac-profile", 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 static const uint16_t mpeg4_default_intra_matrix[64] = {
170 8, 17, 18, 19, 21, 23, 25, 27,
171 17, 18, 19, 21, 23, 25, 27, 28,
172 20, 21, 22, 23, 24, 26, 28, 30,
173 21, 22, 23, 24, 26, 28, 30, 32,
174 22, 23, 24, 26, 28, 30, 32, 35,
175 23, 24, 26, 28, 30, 32, 35, 38,
176 25, 26, 28, 30, 32, 35, 38, 41,
177 27, 28, 30, 32, 35, 38, 41, 45,
180 static const uint16_t mpeg4_default_non_intra_matrix[64] = {
181 16, 17, 18, 19, 20, 21, 22, 23,
182 17, 18, 19, 20, 21, 22, 23, 24,
183 18, 19, 20, 21, 22, 23, 24, 25,
184 19, 20, 21, 22, 23, 24, 26, 27,
185 20, 21, 22, 23, 25, 26, 27, 28,
186 21, 22, 23, 24, 26, 27, 28, 30,
187 22, 23, 24, 26, 27, 28, 30, 31,
188 23, 24, 25, 27, 28, 30, 31, 33,
191 /*****************************************************************************
192 * OpenEncoder: probe the encoder
193 *****************************************************************************/
195 int E_(OpenEncoder)( vlc_object_t *p_this )
197 encoder_t *p_enc = (encoder_t *)p_this;
198 encoder_sys_t *p_sys = p_enc->p_sys;
199 AVCodecContext *p_context;
201 int i_codec_id, i_cat;
202 const char *psz_namecodec;
205 if( !E_(GetFfmpegCodec)( p_enc->fmt_out.i_codec, &i_cat, &i_codec_id,
208 if( E_(GetFfmpegChroma)( p_enc->fmt_out.i_codec ) < 0 )
210 /* handed chroma output */
214 i_codec_id = CODEC_ID_RAWVIDEO;
215 psz_namecodec = "Raw video";
218 if( p_enc->fmt_out.i_cat == VIDEO_ES && i_cat != VIDEO_ES )
220 msg_Err( p_enc, "\"%s\" is not a video encoder", psz_namecodec );
221 intf_UserFatal( p_enc, VLC_FALSE, _("Streaming / Transcoding failed"),
222 _("\"%s\" is no video encoder."), psz_namecodec );
226 if( p_enc->fmt_out.i_cat == AUDIO_ES && i_cat != AUDIO_ES )
228 msg_Err( p_enc, "\"%s\" is not an audio encoder", psz_namecodec );
229 intf_UserFatal( p_enc, VLC_FALSE, _("Streaming / Transcoding failed"),
230 _("\"%s\" is no audio encoder."), psz_namecodec );
234 /* Initialization must be done before avcodec_find_encoder() */
235 E_(InitLibavcodec)(p_this);
237 p_codec = avcodec_find_encoder( i_codec_id );
240 msg_Err( p_enc, "cannot find encoder %s", psz_namecodec );
241 intf_UserFatal( p_enc, VLC_FALSE, _("Streaming / Transcoding failed"),
242 _("VLC could not 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 unsigned i_cpu = vlc_CPU();
268 p_context->dsp_mask = 0;
269 if( !(i_cpu & CPU_CAPABILITY_MMX) )
271 p_context->dsp_mask |= FF_MM_MMX;
273 if( !(i_cpu & CPU_CAPABILITY_MMXEXT) )
275 p_context->dsp_mask |= FF_MM_MMXEXT;
277 if( !(i_cpu & CPU_CAPABILITY_3DNOW) )
279 p_context->dsp_mask |= FF_MM_3DNOW;
281 if( !(i_cpu & CPU_CAPABILITY_SSE) )
283 p_context->dsp_mask |= FF_MM_SSE;
284 p_context->dsp_mask |= FF_MM_SSE2;
287 config_ChainParse( p_enc, ENC_CFG_PREFIX, ppsz_enc_options, p_enc->p_cfg );
289 var_Get( p_enc, ENC_CFG_PREFIX "keyint", &val );
290 p_sys->i_key_int = val.i_int;
292 var_Get( p_enc, ENC_CFG_PREFIX "bframes", &val );
293 p_sys->i_b_frames = val.i_int;
295 var_Get( p_enc, ENC_CFG_PREFIX "vt", &val );
296 p_sys->i_vtolerance = val.i_int;
298 var_Get( p_enc, ENC_CFG_PREFIX "interlace", &val );
299 p_sys->b_interlace = val.b_bool;
301 var_Get( p_enc, ENC_CFG_PREFIX "interlace-me", &val );
302 p_sys->b_interlace_me = val.b_bool;
304 var_Get( p_enc, ENC_CFG_PREFIX "pre-me", &val );
305 p_sys->b_pre_me = val.b_bool;
307 var_Get( p_enc, ENC_CFG_PREFIX "hurry-up", &val );
308 p_sys->b_hurry_up = val.b_bool;
309 if( p_sys->b_hurry_up )
311 /* hurry up mode needs noise reduction, even small */
312 p_sys->i_noise_reduction = 1;
315 var_Get( p_enc, ENC_CFG_PREFIX "strict-rc", &val );
316 p_sys->b_strict_rc = val.b_bool;
317 var_Get( p_enc, ENC_CFG_PREFIX "rc-buffer-size", &val );
318 p_sys->i_rc_buffer_size = val.i_int;
319 var_Get( p_enc, ENC_CFG_PREFIX "rc-buffer-aggressivity", &val );
320 p_sys->f_rc_buffer_aggressivity = val.f_float;
322 var_Get( p_enc, ENC_CFG_PREFIX "i-quant-factor", &val );
323 p_sys->f_i_quant_factor = val.f_float;
325 var_Get( p_enc, ENC_CFG_PREFIX "noise-reduction", &val );
326 p_sys->i_noise_reduction = val.i_int;
328 var_Get( p_enc, ENC_CFG_PREFIX "mpeg4-matrix", &val );
329 p_sys->b_mpeg4_matrix = val.b_bool;
331 var_Get( p_enc, ENC_CFG_PREFIX "qscale", &val );
332 if( val.f_float < 0.01 || val.f_float > 255.0 ) val.f_float = 0;
333 p_sys->i_quality = (int)(FF_QP2LAMBDA * val.f_float + 0.5);
335 var_Get( p_enc, ENC_CFG_PREFIX "hq", &val );
336 p_sys->i_hq = FF_MB_DECISION_RD;
337 if( val.psz_string && *val.psz_string )
339 if( !strcmp( val.psz_string, "rd" ) )
340 p_sys->i_hq = FF_MB_DECISION_RD;
341 else if( !strcmp( val.psz_string, "bits" ) )
342 p_sys->i_hq = FF_MB_DECISION_BITS;
343 else if( !strcmp( val.psz_string, "simple" ) )
344 p_sys->i_hq = FF_MB_DECISION_SIMPLE;
346 p_sys->i_hq = FF_MB_DECISION_RD;
348 if( val.psz_string ) free( val.psz_string );
350 var_Get( p_enc, ENC_CFG_PREFIX "qmin", &val );
351 p_sys->i_qmin = val.i_int;
352 var_Get( p_enc, ENC_CFG_PREFIX "qmax", &val );
353 p_sys->i_qmax = val.i_int;
354 var_Get( p_enc, ENC_CFG_PREFIX "trellis", &val );
355 p_sys->b_trellis = val.b_bool;
357 var_Get( p_enc, ENC_CFG_PREFIX "strict", &val );
358 if( val.i_int < - 1 || val.i_int > 1 ) val.i_int = 0;
359 p_context->strict_std_compliance = val.i_int;
361 var_Get( p_enc, ENC_CFG_PREFIX "lumi-masking", &val );
362 p_sys->f_lumi_masking = val.f_float;
363 var_Get( p_enc, ENC_CFG_PREFIX "dark-masking", &val );
364 p_sys->f_dark_masking = val.f_float;
365 var_Get( p_enc, ENC_CFG_PREFIX "p-masking", &val );
366 p_sys->f_p_masking = val.f_float;
367 var_Get( p_enc, ENC_CFG_PREFIX "border-masking", &val );
368 p_sys->f_border_masking = val.f_float;
369 var_Get( p_enc, ENC_CFG_PREFIX "luma-elim-threshold", &val );
370 p_sys->i_luma_elim = val.i_int;
371 var_Get( p_enc, ENC_CFG_PREFIX "chroma-elim-threshold", &val );
372 p_sys->i_chroma_elim = val.i_int;
374 var_Get( p_enc, ENC_CFG_PREFIX "aac-profile", &val );
375 p_sys->i_aac_profile = FF_PROFILE_UNKNOWN;
376 if( val.psz_string && *val.psz_string )
378 if( !strncmp( val.psz_string, "main", 4 ) )
379 p_sys->i_aac_profile = FF_PROFILE_AAC_MAIN;
380 else if( !strncmp( val.psz_string, "low", 3 ) )
381 p_sys->i_aac_profile = FF_PROFILE_AAC_LOW;
382 #if 0 /* Not supported by FAAC encoder */
383 else if( !strncmp( val.psz_string, "ssr", 3 ) )
384 p_sys->i_aac_profile = FF_PROFILE_AAC_SSR;
386 else if( !strncmp( val.psz_string, "ltp", 3 ) )
387 p_sys->i_aac_profile = FF_PROFILE_AAC_LTP;
390 msg_Warn( p_enc, "unknown AAC profile requested" );
391 p_sys->i_aac_profile = FF_PROFILE_UNKNOWN;
394 if( val.psz_string ) free( val.psz_string );
396 if( p_enc->fmt_in.i_cat == VIDEO_ES )
398 int i_aspect_num, i_aspect_den;
400 if( !p_enc->fmt_in.video.i_width || !p_enc->fmt_in.video.i_height )
402 msg_Warn( p_enc, "invalid size %ix%i", p_enc->fmt_in.video.i_width,
403 p_enc->fmt_in.video.i_height );
408 p_context->width = p_enc->fmt_in.video.i_width;
409 p_context->height = p_enc->fmt_in.video.i_height;
410 if( p_enc->fmt_out.i_codec == VLC_FOURCC('m', 'p', '2', 'v')
411 && (p_context->width > 720 || p_context->height > 576) )
412 p_context->level = 4; /* High level */
414 p_context->time_base.num = p_enc->fmt_in.video.i_frame_rate_base;
415 p_context->time_base.den = p_enc->fmt_in.video.i_frame_rate;
417 /* Defaults from ffmpeg.c */
418 p_context->qblur = 0.5;
419 p_context->qcompress = 0.5;
420 p_context->b_quant_offset = 1.25;
421 p_context->b_quant_factor = 1.25;
422 p_context->i_quant_offset = 0.0;
423 p_context->i_quant_factor = -0.8;
425 p_context->lumi_masking = p_sys->f_lumi_masking;
426 p_context->dark_masking = p_sys->f_dark_masking;
427 p_context->p_masking = p_sys->f_p_masking;
428 p_context->border_masking = p_sys->f_border_masking;
429 p_context->luma_elim_threshold = p_sys->i_luma_elim;
430 p_context->chroma_elim_threshold = p_sys->i_chroma_elim;
432 if( p_sys->i_key_int > 0 )
433 p_context->gop_size = p_sys->i_key_int;
434 p_context->max_b_frames =
435 __MAX( __MIN( p_sys->i_b_frames, FF_MAX_B_FRAMES ), 0 );
436 p_context->b_frame_strategy = 0;
437 if( !p_context->max_b_frames &&
438 ( p_enc->fmt_out.i_codec == VLC_FOURCC('m', 'p', '2', 'v') ||
439 p_enc->fmt_out.i_codec == VLC_FOURCC('m', 'p', '1', 'v') ) )
440 p_context->flags |= CODEC_FLAG_LOW_DELAY;
442 av_reduce( &i_aspect_num, &i_aspect_den,
443 p_enc->fmt_in.video.i_aspect,
444 VOUT_ASPECT_FACTOR, 1 << 30 /* something big */ );
445 av_reduce( &p_context->sample_aspect_ratio.num,
446 &p_context->sample_aspect_ratio.den,
447 i_aspect_num * (int64_t)p_context->height,
448 i_aspect_den * (int64_t)p_context->width, 1 << 30 );
450 p_sys->p_buffer_out = malloc( p_context->height * p_context->width * 3 );
452 p_enc->fmt_in.i_codec = VLC_FOURCC('I','4','2','0');
453 p_context->pix_fmt = E_(GetFfmpegChroma)( p_enc->fmt_in.i_codec );
454 if( p_codec->pix_fmts )
456 const enum PixelFormat *p = p_codec->pix_fmts;
457 for( ; *p != -1; p++ )
459 if( *p == p_context->pix_fmt ) break;
461 if( *p == -1 ) p_context->pix_fmt = p_codec->pix_fmts[0];
462 p_enc->fmt_in.i_codec = E_(GetVlcChroma)( p_context->pix_fmt );
465 if ( p_sys->b_strict_rc )
467 p_context->rc_max_rate = p_enc->fmt_out.i_bitrate;
468 p_context->rc_min_rate = p_enc->fmt_out.i_bitrate;
469 p_context->rc_buffer_size = p_sys->i_rc_buffer_size;
470 /* This is from ffmpeg's ffmpeg.c : */
471 p_context->rc_initial_buffer_occupancy
472 = p_sys->i_rc_buffer_size * 3/4;
473 p_context->rc_buffer_aggressivity = p_sys->f_rc_buffer_aggressivity;
476 if ( p_sys->f_i_quant_factor != 0.0 )
477 p_context->i_quant_factor = p_sys->f_i_quant_factor;
479 p_context->noise_reduction = p_sys->i_noise_reduction;
481 if ( p_sys->b_mpeg4_matrix )
483 p_context->intra_matrix = mpeg4_default_intra_matrix;
484 p_context->inter_matrix = mpeg4_default_non_intra_matrix;
487 if ( p_sys->b_pre_me )
489 p_context->pre_me = 1;
490 p_context->me_pre_cmp = FF_CMP_CHROMA;
493 if ( p_sys->b_interlace )
495 if ( p_context->height <= 280 )
497 if ( p_context->height != 16 || p_context->width != 16 )
499 "disabling interlaced video because height=%d <= 280",
504 p_context->flags |= CODEC_FLAG_INTERLACED_DCT;
505 if ( p_sys->b_interlace_me )
506 p_context->flags |= CODEC_FLAG_INTERLACED_ME;
510 if ( p_sys->b_trellis )
511 p_context->flags |= CODEC_FLAG_TRELLIS_QUANT;
513 if ( p_sys->i_qmin > 0 && p_sys->i_qmin == p_sys->i_qmax )
514 p_context->flags |= CODEC_FLAG_QSCALE;
516 if ( p_enc->i_threads >= 1 )
517 p_context->thread_count = p_enc->i_threads;
519 if( p_sys->i_vtolerance > 0 )
520 p_context->bit_rate_tolerance = p_sys->i_vtolerance;
522 /* usually if someone sets bitrate, he likes more to get that bitrate over quality
523 * should help 'normal' user to get asked bitrate
525 if( p_enc->fmt_out.i_bitrate > 0 && p_sys->i_qmax == 0 && p_sys->i_qmin == 0 )
531 if( p_sys->i_qmin > 0 )
533 p_context->mb_qmin = p_context->qmin = p_sys->i_qmin;
534 p_context->mb_lmin = p_context->lmin = p_sys->i_qmin * FF_QP2LAMBDA;
536 if( p_sys->i_qmax > 0 )
538 p_context->mb_qmax = p_context->qmax = p_sys->i_qmax;
539 p_context->mb_lmax = p_context->lmax = p_sys->i_qmax * FF_QP2LAMBDA;
541 p_context->max_qdiff = 3;
543 p_context->mb_decision = p_sys->i_hq;
545 if( p_sys->i_quality )
547 p_context->flags |= CODEC_FLAG_QSCALE;
548 p_context->global_quality = p_sys->i_quality;
551 else if( p_enc->fmt_in.i_cat == AUDIO_ES )
553 /* work around bug in libmp3lame encoding */
554 if( i_codec_id == CODEC_ID_MP3 && p_enc->fmt_in.audio.i_channels > 2 )
555 p_enc->fmt_in.audio.i_channels = 2;
557 p_enc->fmt_in.i_codec = AOUT_FMT_S16_NE;
558 p_context->sample_rate = p_enc->fmt_in.audio.i_rate;
559 p_context->channels = p_enc->fmt_in.audio.i_channels;
561 /* Ignore FF_PROFILE_UNKNOWN */
562 if( ( p_sys->i_aac_profile >= FF_PROFILE_AAC_MAIN ) &&
563 ( p_enc->fmt_out.i_codec == VLC_FOURCC('m','p','4','a') ) )
564 p_context->profile = p_sys->i_aac_profile;
567 /* Misc parameters */
568 p_context->bit_rate = p_enc->fmt_out.i_bitrate;
570 if( i_codec_id == CODEC_ID_RAWVIDEO )
572 /* XXX: hack: Force same codec (will be handled by transcode) */
573 p_enc->fmt_in.i_codec = p_enc->fmt_out.i_codec;
574 p_context->pix_fmt = E_(GetFfmpegChroma)( p_enc->fmt_in.i_codec );
577 /* Make sure we get extradata filled by the encoder */
578 p_context->extradata_size = 0;
579 p_context->extradata = NULL;
580 p_context->flags |= CODEC_FLAG_GLOBAL_HEADER;
582 vlc_mutex_t *lock = var_AcquireMutex( "avcodec" );
584 if( avcodec_open( p_context, p_codec ) )
586 vlc_mutex_unlock( lock );
587 if( p_enc->fmt_in.i_cat == AUDIO_ES &&
588 (p_context->channels > 2 || i_codec_id == CODEC_ID_MP2
589 || i_codec_id == CODEC_ID_MP3) )
591 if( p_context->channels > 2 )
593 p_context->channels = 2;
594 p_enc->fmt_in.audio.i_channels = 2; // FIXME
595 msg_Warn( p_enc, "stereo mode selected (codec limitation)" );
598 if( i_codec_id == CODEC_ID_MP2 || i_codec_id == CODEC_ID_MP3 )
602 for ( i_frequency = 0; i_frequency < 6; i_frequency++ )
604 if ( p_enc->fmt_out.audio.i_rate
605 == mpa_freq_tab[i_frequency] )
608 if ( i_frequency == 6 )
610 msg_Err( p_enc, "MPEG audio doesn't support frequency=%d",
611 p_enc->fmt_out.audio.i_rate );
616 for ( i = 1; i < 14; i++ )
618 if ( p_enc->fmt_out.i_bitrate / 1000
619 <= mpa_bitrate_tab[i_frequency / 3][i] )
622 if ( p_enc->fmt_out.i_bitrate / 1000
623 != mpa_bitrate_tab[i_frequency / 3][i] )
626 "MPEG audio doesn't support bitrate=%d, using %d",
627 p_enc->fmt_out.i_bitrate,
628 mpa_bitrate_tab[i_frequency / 3][i] * 1000 );
629 p_enc->fmt_out.i_bitrate =
630 mpa_bitrate_tab[i_frequency / 3][i] * 1000;
631 p_context->bit_rate = p_enc->fmt_out.i_bitrate;
635 p_context->codec = NULL;
636 vlc_mutex_lock( lock );
637 if( avcodec_open( p_context, p_codec ) )
639 vlc_mutex_unlock( lock );
640 msg_Err( p_enc, "cannot open encoder" );
641 intf_UserFatal( p_enc, VLC_FALSE, _("Streaming / Transcoding failed"),
642 _("VLC could not open the encoder.") );
649 msg_Err( p_enc, "cannot open encoder" );
650 intf_UserFatal( p_enc, VLC_FALSE, _("Streaming / Transcoding failed"),
651 _("VLC could not open the encoder.") );
656 vlc_mutex_unlock( lock);
658 p_enc->fmt_out.i_extra = p_context->extradata_size;
659 if( p_enc->fmt_out.i_extra )
661 p_enc->fmt_out.p_extra = malloc( p_enc->fmt_out.i_extra );
662 memcpy( p_enc->fmt_out.p_extra, p_context->extradata,
663 p_enc->fmt_out.i_extra );
665 p_context->flags &= ~CODEC_FLAG_GLOBAL_HEADER;
667 if( p_enc->fmt_in.i_cat == AUDIO_ES )
669 p_sys->p_buffer_out = malloc( 2 * AVCODEC_MAX_AUDIO_FRAME_SIZE );
670 p_sys->i_frame_size = p_context->frame_size * 2 * p_context->channels;
671 p_sys->p_buffer = malloc( p_sys->i_frame_size );
672 p_enc->fmt_out.audio.i_blockalign = p_context->block_align;
675 msg_Dbg( p_enc, "found encoder %s", psz_namecodec );
680 /****************************************************************************
681 * Ffmpeg threading system
682 ****************************************************************************/
683 static int FfmpegThread( struct thread_context_t *p_context )
685 while ( !p_context->b_die && !p_context->b_error )
687 vlc_mutex_lock( &p_context->lock );
688 while ( !p_context->b_work && !p_context->b_die && !p_context->b_error )
690 vlc_cond_wait( &p_context->cond, &p_context->lock );
692 p_context->b_work = 0;
693 vlc_mutex_unlock( &p_context->lock );
694 if ( p_context->b_die || p_context->b_error )
697 if ( p_context->pf_func )
699 p_context->i_ret = p_context->pf_func( p_context->p_context,
703 vlc_mutex_lock( &p_context->lock );
704 p_context->b_done = 1;
705 vlc_cond_signal( &p_context->cond );
706 vlc_mutex_unlock( &p_context->lock );
712 static int FfmpegExecute( AVCodecContext *s,
713 int (*pf_func)(AVCodecContext *c2, void *arg2),
714 void **arg, int *ret, int count )
716 struct thread_context_t ** pp_contexts =
717 (struct thread_context_t **)s->thread_opaque;
720 /* Note, we can be certain that this is not called with the same
721 * AVCodecContext by different threads at the same time */
722 for ( i = 0; i < count; i++ )
724 vlc_mutex_lock( &pp_contexts[i]->lock );
725 pp_contexts[i]->arg = arg[i];
726 pp_contexts[i]->pf_func = pf_func;
727 pp_contexts[i]->i_ret = 12345;
728 pp_contexts[i]->b_work = 1;
729 vlc_cond_signal( &pp_contexts[i]->cond );
730 vlc_mutex_unlock( &pp_contexts[i]->lock );
732 for ( i = 0; i < count; i++ )
734 vlc_mutex_lock( &pp_contexts[i]->lock );
735 while ( !pp_contexts[i]->b_done )
737 vlc_cond_wait( &pp_contexts[i]->cond, &pp_contexts[i]->lock );
739 pp_contexts[i]->b_done = 0;
740 pp_contexts[i]->pf_func = NULL;
741 vlc_mutex_unlock( &pp_contexts[i]->lock );
745 ret[i] = pp_contexts[i]->i_ret;
752 /****************************************************************************
753 * EncodeVideo: the whole thing
754 ****************************************************************************/
755 static block_t *EncodeVideo( encoder_t *p_enc, picture_t *p_pict )
757 encoder_sys_t *p_sys = p_enc->p_sys;
761 if ( !p_sys->b_inited && p_enc->i_threads >= 1 )
763 struct thread_context_t ** pp_contexts;
767 pp_contexts = malloc( sizeof(struct thread_context_t *)
768 * p_enc->i_threads );
769 p_sys->p_context->thread_opaque = (void *)pp_contexts;
771 for ( i = 0; i < p_enc->i_threads; i++ )
773 pp_contexts[i] = vlc_object_create( p_enc,
774 sizeof(struct thread_context_t) );
775 pp_contexts[i]->p_context = p_sys->p_context;
776 vlc_mutex_init( p_enc, &pp_contexts[i]->lock );
777 vlc_cond_init( p_enc, &pp_contexts[i]->cond );
778 pp_contexts[i]->b_work = 0;
779 pp_contexts[i]->b_done = 0;
780 if ( vlc_thread_create( pp_contexts[i], "encoder", FfmpegThread,
781 VLC_THREAD_PRIORITY_VIDEO, VLC_FALSE ) )
783 msg_Err( p_enc, "cannot spawn encoder thread, expect to die soon" );
788 p_sys->p_context->execute = FfmpegExecute;
791 memset( &frame, 0, sizeof( AVFrame ) );
792 for( i_plane = 0; i_plane < p_pict->i_planes; i_plane++ )
794 frame.data[i_plane] = p_pict->p[i_plane].p_pixels;
795 frame.linesize[i_plane] = p_pict->p[i_plane].i_pitch;
798 /* Let ffmpeg select the frame type */
801 frame.repeat_pict = p_pict->i_nb_fields - 2;
802 frame.interlaced_frame = !p_pict->b_progressive;
803 frame.top_field_first = !!p_pict->b_top_field_first;
805 /* Set the pts of the frame being encoded (segfaults with mpeg4!)*/
806 if( p_enc->fmt_out.i_codec != VLC_FOURCC( 'm', 'p', '4', 'v' ) )
808 frame.pts = p_pict->date ? p_pict->date : (int64_t)AV_NOPTS_VALUE;
810 if ( p_sys->b_hurry_up && frame.pts != (int64_t)AV_NOPTS_VALUE )
812 mtime_t current_date = mdate();
814 if ( current_date + HURRY_UP_GUARD3 > frame.pts )
816 p_sys->p_context->mb_decision = FF_MB_DECISION_SIMPLE;
817 p_sys->p_context->flags &= ~CODEC_FLAG_TRELLIS_QUANT;
818 msg_Dbg( p_enc, "hurry up mode 3" );
822 p_sys->p_context->mb_decision = p_sys->i_hq;
824 if ( current_date + HURRY_UP_GUARD2 > frame.pts )
826 p_sys->p_context->flags &= ~CODEC_FLAG_TRELLIS_QUANT;
827 p_sys->p_context->noise_reduction = p_sys->i_noise_reduction
828 + (HURRY_UP_GUARD2 + current_date - frame.pts) / 500;
829 msg_Dbg( p_enc, "hurry up mode 2" );
833 if ( p_sys->b_trellis )
834 p_sys->p_context->flags |= CODEC_FLAG_TRELLIS_QUANT;
836 p_sys->p_context->noise_reduction =
837 p_sys->i_noise_reduction;
841 if ( current_date + HURRY_UP_GUARD1 > frame.pts )
843 frame.pict_type = FF_P_TYPE;
844 /* msg_Dbg( p_enc, "hurry up mode 1 %lld", current_date + HURRY_UP_GUARD1 - frame.pts ); */
850 frame.pts = (int64_t)AV_NOPTS_VALUE;
853 if ( frame.pts != (int64_t)AV_NOPTS_VALUE && frame.pts != 0 )
855 if ( p_sys->i_last_pts == frame.pts )
857 msg_Warn( p_enc, "almost fed libavcodec with two frames with the "
858 "same PTS (" I64Fd ")", frame.pts );
861 else if ( p_sys->i_last_pts > frame.pts )
863 msg_Warn( p_enc, "almost fed libavcodec with a frame in the "
864 "past (current: " I64Fd ", last: "I64Fd")",
865 frame.pts, p_sys->i_last_pts );
870 p_sys->i_last_pts = frame.pts;
874 frame.quality = p_sys->i_quality;
876 /* Ugly work-around for stupid libavcodec behaviour */
878 p_sys->pi_delay_pts[p_sys->i_framenum % MAX_FRAME_DELAY] = frame.pts;
879 frame.pts = p_sys->i_framenum * AV_TIME_BASE *
880 p_enc->fmt_in.video.i_frame_rate_base;
881 frame.pts += p_enc->fmt_in.video.i_frame_rate - 1;
882 frame.pts /= p_enc->fmt_in.video.i_frame_rate;
883 /* End work-around */
885 i_out = avcodec_encode_video( p_sys->p_context, (uint8_t*)p_sys->p_buffer_out,
886 p_sys->p_context->height * p_sys->p_context->width * 3, &frame );
890 block_t *p_block = block_New( p_enc, i_out );
891 memcpy( p_block->p_buffer, p_sys->p_buffer_out, i_out );
893 /* FIXME, 3-2 pulldown is not handled correctly */
894 p_block->i_length = I64C(1000000) *
895 p_enc->fmt_in.video.i_frame_rate_base /
896 p_enc->fmt_in.video.i_frame_rate;
898 if( !p_sys->p_context->max_b_frames || !p_sys->p_context->delay )
900 /* No delay -> output pts == input pts */
901 p_block->i_pts = p_block->i_dts = p_pict->date;
903 else if( p_sys->p_context->coded_frame->pts != (int64_t)AV_NOPTS_VALUE &&
904 p_sys->p_context->coded_frame->pts != 0 &&
905 p_sys->i_buggy_pts_detect != p_sys->p_context->coded_frame->pts )
907 p_sys->i_buggy_pts_detect = p_sys->p_context->coded_frame->pts;
908 p_block->i_pts = p_sys->p_context->coded_frame->pts;
910 /* Ugly work-around for stupid libavcodec behaviour */
912 int64_t i_framenum = p_block->i_pts *
913 p_enc->fmt_in.video.i_frame_rate /
914 p_enc->fmt_in.video.i_frame_rate_base / AV_TIME_BASE;
916 p_block->i_pts = p_sys->pi_delay_pts[i_framenum % MAX_FRAME_DELAY];
918 /* End work-around */
920 if( p_sys->p_context->coded_frame->pict_type != FF_I_TYPE &&
921 p_sys->p_context->coded_frame->pict_type != FF_P_TYPE )
923 p_block->i_dts = p_block->i_pts;
927 if( p_sys->i_last_ref_pts )
929 p_block->i_dts = p_sys->i_last_ref_pts;
933 /* Let's put something sensible */
934 p_block->i_dts = p_block->i_pts;
937 p_sys->i_last_ref_pts = p_block->i_pts;
942 /* Buggy libavcodec which doesn't update coded_frame->pts
944 p_block->i_dts = p_block->i_pts = p_pict->date;
947 switch ( p_sys->p_context->coded_frame->pict_type )
950 p_block->i_flags |= BLOCK_FLAG_TYPE_I;
953 p_block->i_flags |= BLOCK_FLAG_TYPE_P;
956 p_block->i_flags |= BLOCK_FLAG_TYPE_B;
966 /****************************************************************************
967 * EncodeAudio: the whole thing
968 ****************************************************************************/
969 static block_t *EncodeAudio( encoder_t *p_enc, aout_buffer_t *p_aout_buf )
971 encoder_sys_t *p_sys = p_enc->p_sys;
972 block_t *p_block, *p_chain = NULL;
974 uint8_t *p_buffer = p_aout_buf->p_buffer;
975 int i_samples = p_aout_buf->i_nb_samples;
976 int i_samples_delay = p_sys->i_samples_delay;
978 p_sys->i_pts = p_aout_buf->start_date -
979 (mtime_t)1000000 * (mtime_t)p_sys->i_samples_delay /
980 (mtime_t)p_enc->fmt_in.audio.i_rate;
982 p_sys->i_samples_delay += i_samples;
984 while( p_sys->i_samples_delay >= p_sys->p_context->frame_size )
989 if( i_samples_delay )
991 /* Take care of the left-over from last time */
992 int i_delay_size = i_samples_delay * 2 *
993 p_sys->p_context->channels;
994 int i_size = p_sys->i_frame_size - i_delay_size;
996 p_samples = (int16_t *)p_sys->p_buffer;
997 memcpy( p_sys->p_buffer + i_delay_size, p_buffer, i_size );
998 p_buffer -= i_delay_size;
999 i_samples += i_samples_delay;
1000 i_samples_delay = 0;
1004 p_samples = (int16_t *)p_buffer;
1007 i_out = avcodec_encode_audio( p_sys->p_context, (uint8_t *)p_sys->p_buffer_out,
1008 2 * AVCODEC_MAX_AUDIO_FRAME_SIZE,
1012 msg_Warn( p_enc, "avcodec_encode_audio: %d", i_out );
1014 if( i_out < 0 ) break;
1016 p_buffer += p_sys->i_frame_size;
1017 p_sys->i_samples_delay -= p_sys->p_context->frame_size;
1018 i_samples -= p_sys->p_context->frame_size;
1020 if( i_out == 0 ) continue;
1022 p_block = block_New( p_enc, i_out );
1023 memcpy( p_block->p_buffer, p_sys->p_buffer_out, i_out );
1025 p_block->i_length = (mtime_t)1000000 *
1026 (mtime_t)p_sys->p_context->frame_size /
1027 (mtime_t)p_sys->p_context->sample_rate;
1029 p_block->i_dts = p_block->i_pts = p_sys->i_pts;
1032 p_sys->i_pts += p_block->i_length;
1033 block_ChainAppend( &p_chain, p_block );
1036 /* Backup the remaining raw samples */
1039 memcpy( p_sys->p_buffer + i_samples_delay * 2 *
1040 p_sys->p_context->channels, p_buffer,
1041 i_samples * 2 * p_sys->p_context->channels );
1047 /*****************************************************************************
1048 * CloseEncoder: ffmpeg encoder destruction
1049 *****************************************************************************/
1050 void E_(CloseEncoder)( vlc_object_t *p_this )
1052 encoder_t *p_enc = (encoder_t *)p_this;
1053 encoder_sys_t *p_sys = p_enc->p_sys;
1055 if ( p_sys->b_inited && p_enc->i_threads >= 1 )
1058 struct thread_context_t ** pp_contexts =
1059 (struct thread_context_t **)p_sys->p_context->thread_opaque;
1060 for ( i = 0; i < p_enc->i_threads; i++ )
1062 vlc_object_kill( pp_contexts[i] );
1063 vlc_cond_signal( &pp_contexts[i]->cond );
1064 vlc_thread_join( pp_contexts[i] );
1065 vlc_mutex_destroy( &pp_contexts[i]->lock );
1066 vlc_cond_destroy( &pp_contexts[i]->cond );
1067 vlc_object_release( pp_contexts[i] );
1070 free( pp_contexts );
1073 vlc_mutex_t *lock = var_AcquireMutex( "avcodec" );
1074 avcodec_close( p_sys->p_context );
1075 vlc_mutex_unlock( lock );
1076 av_free( p_sys->p_context );
1078 if( p_sys->p_buffer ) free( p_sys->p_buffer );
1079 if( p_sys->p_buffer_out ) free( p_sys->p_buffer_out );