]> git.sesse.net Git - vlc/blob - modules/codec/ffmpeg/encoder.c
* modules/codec/ffmpeg: New options to fine-tune advanced encoder options.
[vlc] / modules / codec / ffmpeg / encoder.c
1 /*****************************************************************************
2  * encoder.c: video and audio encoder using the ffmpeg library
3  *****************************************************************************
4  * Copyright (C) 1999-2004 VideoLAN
5  * $Id$
6  *
7  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8  *          Gildas Bazin <gbazin@videolan.org>
9  *          Christophe Massiot <massiot@via.ecp.fr>
10  *
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.
15  *
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.
20  *
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  *****************************************************************************/
25
26 /*****************************************************************************
27  * Preamble
28  *****************************************************************************/
29 #include <vlc/vlc.h>
30 #include <vlc/vout.h>
31 #include <vlc/aout.h>
32 #include <vlc/sout.h>
33 #include <vlc/decoder.h>
34
35 /* ffmpeg header */
36 #define HAVE_MMX
37 #ifdef HAVE_FFMPEG_AVCODEC_H
38 #   include <ffmpeg/avcodec.h>
39 #else
40 #   include <avcodec.h>
41 #endif
42
43 #if LIBAVCODEC_BUILD < 4704
44 #   define AV_NOPTS_VALUE 0
45 #endif
46 #if LIBAVCODEC_BUILD < 4684
47 #    define FF_QP2LAMBDA 118
48 #endif
49
50 #include "ffmpeg.h"
51
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)
56
57 #define MAX_FRAME_DELAY (FF_MAX_B_FRAMES + 2)
58
59 /*****************************************************************************
60  * Local prototypes
61  *****************************************************************************/
62 int  E_(OpenEncoder) ( vlc_object_t * );
63 void E_(CloseEncoder)( vlc_object_t * );
64
65 static block_t *EncodeVideo( encoder_t *, picture_t * );
66 static block_t *EncodeAudio( encoder_t *, aout_buffer_t * );
67
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 );
73
74 /*****************************************************************************
75  * thread_context_t : for multithreaded encoding
76  *****************************************************************************/
77 #if LIBAVCODEC_BUILD >= 4702
78 struct thread_context_t
79 {
80     VLC_COMMON_MEMBERS
81
82     AVCodecContext  *p_context;
83     int             (* pf_func)(AVCodecContext *c, void *arg);
84     void            *arg;
85     int             i_ret;
86
87     vlc_mutex_t     lock;
88     vlc_cond_t      cond;
89     vlc_bool_t      b_work, b_done;
90 };
91 #endif
92
93 /*****************************************************************************
94  * encoder_sys_t : ffmpeg encoder descriptor
95  *****************************************************************************/
96 struct encoder_sys_t
97 {
98     /*
99      * Ffmpeg properties
100      */
101     AVCodec         *p_codec;
102     AVCodecContext  *p_context;
103
104     /*
105      * Common properties
106      */
107     char *p_buffer;
108     char *p_buffer_out;
109
110     /*
111      * Video properties
112      */
113     mtime_t i_last_ref_pts;
114     mtime_t i_buggy_pts_detect;
115     mtime_t i_last_pts;
116     vlc_bool_t b_inited;
117
118     /*
119      * Audio properties
120      */
121     int i_frame_size;
122     int i_samples_delay;
123     mtime_t i_pts;
124
125     /* Encoding settings */
126     int        i_key_int;
127     int        i_b_frames;
128     int        i_vtolerance;
129     int        i_qmin;
130     int        i_qmax;
131     int        i_hq;
132     vlc_bool_t b_strict_rc;
133     int        i_rc_buffer_size;
134     float      f_rc_buffer_aggressivity;
135     vlc_bool_t b_pre_me;
136     vlc_bool_t b_hurry_up;
137     vlc_bool_t b_interlace;
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;
145
146     /* Used to work around stupid timestamping behaviour in libavcodec */
147     uint64_t i_framenum;
148     mtime_t  pi_delay_pts[MAX_FRAME_DELAY];
149 };
150
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
158 };
159
160 /*****************************************************************************
161  * OpenEncoder: probe the encoder
162  *****************************************************************************/
163 extern int16_t IMPORT_SYMBOL ff_mpeg4_default_intra_matrix[];
164 extern int16_t IMPORT_SYMBOL ff_mpeg4_default_non_intra_matrix[];
165
166 int E_(OpenEncoder)( vlc_object_t *p_this )
167 {
168     encoder_t *p_enc = (encoder_t *)p_this;
169     encoder_sys_t *p_sys = p_enc->p_sys;
170     AVCodecContext *p_context;
171     AVCodec *p_codec;
172     int i_codec_id, i_cat;
173     char *psz_namecodec;
174     vlc_value_t val;
175
176     if( !E_(GetFfmpegCodec)( p_enc->fmt_out.i_codec, &i_cat, &i_codec_id,
177                              &psz_namecodec ) )
178     {
179         if( E_(GetFfmpegChroma)( p_enc->fmt_out.i_codec ) < 0 )
180         {
181             /* handed chroma output */
182             return VLC_EGENERIC;
183         }
184         i_cat      = VIDEO_ES;
185         i_codec_id = CODEC_ID_RAWVIDEO;
186         psz_namecodec = "Raw video";
187     }
188
189
190     if( p_enc->fmt_out.i_cat == VIDEO_ES && i_cat != VIDEO_ES )
191     {
192         msg_Err( p_enc, "\"%s\" is not a video encoder", psz_namecodec );
193         return VLC_EGENERIC;
194     }
195
196     if( p_enc->fmt_out.i_cat == AUDIO_ES && i_cat != AUDIO_ES )
197     {
198         msg_Err( p_enc, "\"%s\" is not an audio encoder", psz_namecodec );
199         return VLC_EGENERIC;
200     }
201
202     /* Initialization must be done before avcodec_find_decoder() */
203     E_(InitLibavcodec)(p_this);
204
205     p_codec = avcodec_find_encoder( i_codec_id );
206     if( !p_codec )
207     {
208         msg_Err( p_enc, "cannot find encoder %s", psz_namecodec );
209         return VLC_EGENERIC;
210     }
211
212     /* Allocate the memory needed to store the decoder's structure */
213     if( ( p_sys = (encoder_sys_t *)malloc(sizeof(encoder_sys_t)) ) == NULL )
214     {
215         msg_Err( p_enc, "out of memory" );
216         return VLC_EGENERIC;
217     }
218     memset( p_sys, 0, sizeof(encoder_sys_t) );
219     p_enc->p_sys = p_sys;
220     p_sys->p_codec = p_codec;
221
222     p_enc->pf_encode_video = EncodeVideo;
223     p_enc->pf_encode_audio = EncodeAudio;
224
225     p_sys->p_buffer_out = NULL;
226     p_sys->p_buffer = NULL;
227
228     p_sys->p_context = p_context = avcodec_alloc_context();
229
230     /* Set CPU capabilities */
231     p_context->dsp_mask = 0;
232     if( !(p_enc->p_libvlc->i_cpu & CPU_CAPABILITY_MMX) )
233     {
234         p_context->dsp_mask |= FF_MM_MMX;
235     }
236     if( !(p_enc->p_libvlc->i_cpu & CPU_CAPABILITY_MMXEXT) )
237     {
238         p_context->dsp_mask |= FF_MM_MMXEXT;
239     }
240     if( !(p_enc->p_libvlc->i_cpu & CPU_CAPABILITY_3DNOW) )
241     {
242         p_context->dsp_mask |= FF_MM_3DNOW;
243     }
244     if( !(p_enc->p_libvlc->i_cpu & CPU_CAPABILITY_SSE) )
245     {
246         p_context->dsp_mask |= FF_MM_SSE;
247         p_context->dsp_mask |= FF_MM_SSE2;
248     }
249
250     sout_CfgParse( p_enc, ENC_CFG_PREFIX, ppsz_enc_options, p_enc->p_cfg );
251
252     var_Get( p_enc, ENC_CFG_PREFIX "keyint", &val );
253     p_sys->i_key_int = val.i_int;
254
255     var_Get( p_enc, ENC_CFG_PREFIX "bframes", &val );
256     p_sys->i_b_frames = val.i_int;
257
258     var_Get( p_enc, ENC_CFG_PREFIX "vt", &val );
259     p_sys->i_vtolerance = val.i_int;
260
261     var_Get( p_enc, ENC_CFG_PREFIX "interlace", &val );
262     p_sys->b_interlace = val.b_bool;
263
264     var_Get( p_enc, ENC_CFG_PREFIX "pre-me", &val );
265     p_sys->b_pre_me = val.b_bool;
266
267     var_Get( p_enc, ENC_CFG_PREFIX "hurry-up", &val );
268     p_sys->b_hurry_up = val.b_bool;
269     if( p_sys->b_hurry_up )
270     {
271         /* hurry up mode needs noise reduction, even small */
272         p_sys->i_noise_reduction = 1;
273     }
274
275     var_Get( p_enc, ENC_CFG_PREFIX "strict-rc", &val );
276     p_sys->b_strict_rc = val.b_bool;
277     var_Get( p_enc, ENC_CFG_PREFIX "rc-buffer-size", &val );
278     p_sys->i_rc_buffer_size = val.i_int;
279     var_Get( p_enc, ENC_CFG_PREFIX "rc-buffer-aggressivity", &val );
280     p_sys->f_rc_buffer_aggressivity = val.f_float;
281
282     var_Get( p_enc, ENC_CFG_PREFIX "i-quant-factor", &val );
283     p_sys->f_i_quant_factor = val.f_float;
284
285     var_Get( p_enc, ENC_CFG_PREFIX "noise-reduction", &val );
286     p_sys->i_noise_reduction = val.i_int;
287
288     var_Get( p_enc, ENC_CFG_PREFIX "mpeg4-matrix", &val );
289     p_sys->b_mpeg4_matrix = val.b_bool;
290
291     var_Get( p_enc, ENC_CFG_PREFIX "qscale", &val );
292     if( val.f_float < 0.01 || val.f_float > 255.0 ) val.f_float = 0;
293     p_sys->i_quality = (int)(FF_QP2LAMBDA * val.f_float + 0.5);
294
295     var_Get( p_enc, ENC_CFG_PREFIX "hq", &val );
296     if( val.psz_string && *val.psz_string )
297     {
298         if( !strcmp( val.psz_string, "rd" ) )
299             p_sys->i_hq = FF_MB_DECISION_RD;
300         else if( !strcmp( val.psz_string, "bits" ) )
301             p_sys->i_hq = FF_MB_DECISION_BITS;
302         else if( !strcmp( val.psz_string, "simple" ) )
303             p_sys->i_hq = FF_MB_DECISION_SIMPLE;
304         else
305             p_sys->i_hq = FF_MB_DECISION_RD;
306     }
307     if( val.psz_string ) free( val.psz_string );
308
309     var_Get( p_enc, ENC_CFG_PREFIX "qmin", &val );
310     p_sys->i_qmin = val.i_int;
311     var_Get( p_enc, ENC_CFG_PREFIX "qmax", &val );
312     p_sys->i_qmax = val.i_int;
313     var_Get( p_enc, ENC_CFG_PREFIX "trellis", &val );
314     p_sys->b_trellis = val.b_bool;
315
316     var_Get( p_enc, ENC_CFG_PREFIX "strict", &val );
317     if( val.i_int < - 1 || val.i_int > 1 ) val.i_int = 0;
318     p_context->strict_std_compliance = val.i_int;
319
320     var_Get( p_enc, ENC_CFG_PREFIX "lumi-masking", &val );
321     p_sys->f_lumi_masking = val.f_float;
322     var_Get( p_enc, ENC_CFG_PREFIX "dark-masking", &val );
323     p_sys->f_dark_masking = val.f_float;
324     var_Get( p_enc, ENC_CFG_PREFIX "p-masking", &val );
325     p_sys->f_p_masking = val.f_float;
326     var_Get( p_enc, ENC_CFG_PREFIX "border-masking", &val );
327     p_sys->f_border_masking = val.f_float;
328     var_Get( p_enc, ENC_CFG_PREFIX "luma-elim-threshold", &val );
329     p_sys->i_luma_elim = val.i_int;
330     var_Get( p_enc, ENC_CFG_PREFIX "chroma-elim-threshold", &val );
331     p_sys->i_chroma_elim = val.i_int;
332
333     if( p_enc->fmt_in.i_cat == VIDEO_ES )
334     {
335         int i_aspect_num, i_aspect_den;
336
337         if( !p_enc->fmt_in.video.i_width || !p_enc->fmt_in.video.i_height )
338         {
339             msg_Warn( p_enc, "invalid size %ix%i", p_enc->fmt_in.video.i_width,
340                       p_enc->fmt_in.video.i_height );
341             free( p_sys );
342             return VLC_EGENERIC;
343         }
344
345         p_context->width = p_enc->fmt_in.video.i_width;
346         p_context->height = p_enc->fmt_in.video.i_height;
347
348 #if LIBAVCODEC_BUILD >= 4754
349         p_context->time_base.num = p_enc->fmt_in.video.i_frame_rate_base;
350         p_context->time_base.den = p_enc->fmt_in.video.i_frame_rate;
351 #else
352         p_context->frame_rate = p_enc->fmt_in.video.i_frame_rate;
353         p_context->frame_rate_base= p_enc->fmt_in.video.i_frame_rate_base;
354 #endif
355
356         /* Defaults from ffmpeg.c */
357         p_context->qblur = 0.5;
358         p_context->qcompress = 0.5;
359         p_context->b_quant_offset = 1.25;
360         p_context->b_quant_factor = 1.25;
361         p_context->i_quant_offset = 0.0;
362         p_context->i_quant_factor = -0.8;
363
364         p_context->lumi_masking = p_sys->f_lumi_masking;
365         p_context->dark_masking = p_sys->f_dark_masking;
366         p_context->p_masking = p_sys->f_p_masking;
367         p_context->border_masking = p_sys->f_border_masking;
368         p_context->luma_elim_threshold = p_sys->i_luma_elim;
369         p_context->chroma_elim_threshold = p_sys->i_chroma_elim;
370
371         if( p_sys->i_key_int > 0 )
372             p_context->gop_size = p_sys->i_key_int;
373         p_context->max_b_frames =
374             __MAX( __MIN( p_sys->i_b_frames, FF_MAX_B_FRAMES ), 0 );
375         p_context->b_frame_strategy = 0;
376
377 #if LIBAVCODEC_BUILD >= 4687
378         av_reduce( &i_aspect_num, &i_aspect_den,
379                    p_enc->fmt_in.video.i_aspect,
380                    VOUT_ASPECT_FACTOR, 1 << 30 /* something big */ );
381         av_reduce( &p_context->sample_aspect_ratio.num,
382                    &p_context->sample_aspect_ratio.den,
383                    i_aspect_num * (int64_t)p_context->height,
384                    i_aspect_den * (int64_t)p_context->width, 1 << 30 );
385 #else
386         p_context->aspect_ratio = ((float)p_enc->fmt_in.video.i_aspect) /
387             VOUT_ASPECT_FACTOR;
388 #endif
389
390         p_sys->p_buffer_out = malloc( AVCODEC_MAX_VIDEO_FRAME_SIZE );
391
392         p_enc->fmt_in.i_codec = VLC_FOURCC('I','4','2','0');
393         p_context->pix_fmt = E_(GetFfmpegChroma)( p_enc->fmt_in.i_codec );
394 #if LIBAVCODEC_BUILD >= 4714
395         if( p_codec->pix_fmts )
396         {
397             const enum PixelFormat *p = p_codec->pix_fmts;
398             for( ; *p != -1; p++ )
399             {
400                 if( *p == p_context->pix_fmt ) break;
401             }
402             if( *p == -1 ) p_context->pix_fmt = p_codec->pix_fmts[0];
403             p_enc->fmt_in.i_codec = E_(GetVlcChroma)( p_context->pix_fmt );
404         }
405 #else
406         p_enc->fmt_in.i_codec = E_(GetVlcChroma)( p_context->pix_fmt );
407 #endif
408
409         if ( p_sys->b_strict_rc )
410         {
411             p_context->rc_max_rate = p_enc->fmt_out.i_bitrate;
412             p_context->rc_buffer_size = p_sys->i_rc_buffer_size;
413             /* This is from ffmpeg's ffmpeg.c : */
414             p_context->rc_initial_buffer_occupancy
415                 = p_sys->i_rc_buffer_size * 3/4;
416             p_context->rc_buffer_aggressivity = p_sys->f_rc_buffer_aggressivity;
417         }
418
419         if ( p_sys->f_i_quant_factor != 0.0 )
420             p_context->i_quant_factor = p_sys->f_i_quant_factor;
421
422 #if LIBAVCODEC_BUILD >= 4690
423         p_context->noise_reduction = p_sys->i_noise_reduction;
424 #endif
425
426         if ( p_sys->b_mpeg4_matrix )
427         {
428             p_context->intra_matrix = ff_mpeg4_default_intra_matrix;
429             p_context->inter_matrix = ff_mpeg4_default_non_intra_matrix;
430         }
431
432         if ( p_sys->b_pre_me )
433         {
434             p_context->pre_me = 1;
435             p_context->me_pre_cmp = FF_CMP_CHROMA;
436         }
437
438         if ( p_sys->b_interlace )
439         {
440             p_context->flags |= CODEC_FLAG_INTERLACED_DCT;
441 #if LIBAVCODEC_BUILD >= 4698
442             p_context->flags |= CODEC_FLAG_INTERLACED_ME;
443 #endif
444         }
445
446         if ( p_sys->b_trellis )
447             p_context->flags |= CODEC_FLAG_TRELLIS_QUANT;
448
449         if ( p_sys->i_qmin > 0 && p_sys->i_qmin == p_sys->i_qmax )
450             p_context->flags |= CODEC_FLAG_QSCALE;
451
452 #if LIBAVCODEC_BUILD >= 4702
453         if ( p_enc->i_threads >= 1 )
454             p_context->thread_count = p_enc->i_threads;
455 #endif
456
457         if( p_sys->i_vtolerance > 0 )
458             p_context->bit_rate_tolerance = p_sys->i_vtolerance;
459
460         if( p_sys->i_qmin > 0 )
461             p_context->mb_qmin = p_context->qmin = p_sys->i_qmin;
462         if( p_sys->i_qmax > 0 )
463             p_context->mb_qmax = p_context->qmax = p_sys->i_qmax;
464         p_context->max_qdiff = 3;
465
466         p_context->mb_decision = p_sys->i_hq;
467
468         if( p_sys->i_quality )
469         {
470             p_context->flags |= CODEC_FLAG_QSCALE;
471 #if LIBAVCODEC_BUILD >= 4668
472             p_context->global_quality = p_sys->i_quality;
473 #endif
474         }
475     }
476     else if( p_enc->fmt_in.i_cat == AUDIO_ES )
477     {
478         /* work around bug in libmp3lame encoding */
479         if( i_codec_id == CODEC_ID_MP3 && p_enc->fmt_in.audio.i_channels > 2 )
480             p_enc->fmt_in.audio.i_channels = 2;
481
482         p_enc->fmt_in.i_codec  = AOUT_FMT_S16_NE;
483         p_context->sample_rate = p_enc->fmt_in.audio.i_rate;
484         p_context->channels    = p_enc->fmt_in.audio.i_channels;
485     }
486
487     /* Misc parameters */
488     p_context->bit_rate = p_enc->fmt_out.i_bitrate;
489
490     if( i_codec_id == CODEC_ID_RAWVIDEO )
491     {
492         /* XXX: hack: Force same codec (will be handled by transcode) */
493         p_enc->fmt_in.i_codec = p_enc->fmt_out.i_codec;
494         p_context->pix_fmt = E_(GetFfmpegChroma)( p_enc->fmt_in.i_codec );
495     }
496
497     /* Make sure we get extradata filled by the encoder */
498     p_context->extradata_size = 0;
499     p_context->extradata = NULL;
500     p_context->flags |= CODEC_FLAG_GLOBAL_HEADER;
501
502     if( avcodec_open( p_context, p_codec ) )
503     {
504         if( p_enc->fmt_in.i_cat == AUDIO_ES && p_context->channels > 2 )
505         {
506             p_context->channels = 2;
507             p_enc->fmt_in.audio.i_channels = 2; // FIXME
508             if( avcodec_open( p_context, p_codec ) )
509             {
510                 msg_Err( p_enc, "cannot open encoder" );
511                 free( p_sys );
512                 return VLC_EGENERIC;
513             }
514             msg_Warn( p_enc, "stereo mode selected (codec limitation)" );
515         }
516         else
517         {
518             msg_Err( p_enc, "cannot open encoder" );
519             free( p_sys );
520             return VLC_EGENERIC;
521         }
522     }
523
524     p_enc->fmt_out.i_extra = p_context->extradata_size;
525     p_enc->fmt_out.p_extra = p_context->extradata;
526     p_context->flags &= ~CODEC_FLAG_GLOBAL_HEADER;
527
528     if( p_enc->fmt_in.i_cat == AUDIO_ES )
529     {
530         p_sys->p_buffer_out = malloc( 2 * AVCODEC_MAX_AUDIO_FRAME_SIZE );
531         p_sys->i_frame_size = p_context->frame_size * 2 * p_context->channels;
532         p_sys->p_buffer = malloc( p_sys->i_frame_size );
533     }
534
535     msg_Dbg( p_enc, "found encoder %s", psz_namecodec );
536
537     return VLC_SUCCESS;
538 }
539
540 /****************************************************************************
541  * Ffmpeg threading system
542  ****************************************************************************/
543 #if LIBAVCODEC_BUILD >= 4702
544 static int FfmpegThread( struct thread_context_t *p_context )
545 {
546     while ( !p_context->b_die && !p_context->b_error )
547     {
548         vlc_mutex_lock( &p_context->lock );
549         while ( !p_context->b_work && !p_context->b_die && !p_context->b_error )
550         {
551             vlc_cond_wait( &p_context->cond, &p_context->lock );
552         }
553         p_context->b_work = 0;
554         vlc_mutex_unlock( &p_context->lock );
555         if ( p_context->b_die || p_context->b_error )
556             break;
557
558         if ( p_context->pf_func )
559         {
560             p_context->i_ret = p_context->pf_func( p_context->p_context,
561                                                    p_context->arg );
562         }
563
564         vlc_mutex_lock( &p_context->lock );
565         p_context->b_done = 1;
566         vlc_cond_signal( &p_context->cond );
567         vlc_mutex_unlock( &p_context->lock );
568     }
569
570     return 0;
571 }
572
573 static int FfmpegExecute( AVCodecContext *s,
574                           int (*pf_func)(AVCodecContext *c2, void *arg2),
575                           void **arg, int *ret, int count )
576 {
577     struct thread_context_t ** pp_contexts =
578                          (struct thread_context_t **)s->thread_opaque;
579     int i;
580
581     /* Note, we can be certain that this is not called with the same
582      * AVCodecContext by different threads at the same time */
583     for ( i = 0; i < count; i++ )
584     {
585         vlc_mutex_lock( &pp_contexts[i]->lock );
586         pp_contexts[i]->arg = arg[i];
587         pp_contexts[i]->pf_func = pf_func;
588         pp_contexts[i]->i_ret = 12345;
589         pp_contexts[i]->b_work = 1;
590         vlc_cond_signal( &pp_contexts[i]->cond );
591         vlc_mutex_unlock( &pp_contexts[i]->lock );
592     }
593     for ( i = 0; i < count; i++ )
594     {
595         vlc_mutex_lock( &pp_contexts[i]->lock );
596         while ( !pp_contexts[i]->b_done )
597         {
598             vlc_cond_wait( &pp_contexts[i]->cond, &pp_contexts[i]->lock );
599         }
600         pp_contexts[i]->b_done = 0;
601         pp_contexts[i]->pf_func = NULL;
602         vlc_mutex_unlock( &pp_contexts[i]->lock );
603
604         if ( ret )
605         {
606             ret[i] = pp_contexts[i]->i_ret;
607         }
608     }
609
610     return 0;
611 }
612 #endif
613
614 /****************************************************************************
615  * EncodeVideo: the whole thing
616  ****************************************************************************/
617 static block_t *EncodeVideo( encoder_t *p_enc, picture_t *p_pict )
618 {
619     encoder_sys_t *p_sys = p_enc->p_sys;
620     AVFrame frame;
621     int i_out, i_plane;
622
623 #if LIBAVCODEC_BUILD >= 4702
624     if ( !p_sys->b_inited && p_enc->i_threads >= 1 )
625     {
626         struct thread_context_t ** pp_contexts;
627         int i;
628
629         p_sys->b_inited = 1;
630         pp_contexts = malloc( sizeof(struct thread_context_t *)
631                                  * p_enc->i_threads );
632         p_sys->p_context->thread_opaque = (void *)pp_contexts;
633
634         for ( i = 0; i < p_enc->i_threads; i++ )
635         {
636             pp_contexts[i] = vlc_object_create( p_enc,
637                                      sizeof(struct thread_context_t) );
638             pp_contexts[i]->p_context = p_sys->p_context;
639             vlc_mutex_init( p_enc, &pp_contexts[i]->lock );
640             vlc_cond_init( p_enc, &pp_contexts[i]->cond );
641             pp_contexts[i]->b_work = 0;
642             pp_contexts[i]->b_done = 0;
643             if ( vlc_thread_create( pp_contexts[i], "encoder", FfmpegThread,
644                                     VLC_THREAD_PRIORITY_VIDEO, VLC_FALSE ) )
645             {
646                 msg_Err( p_enc, "cannot spawn encoder thread, expect to die soon" );
647                 return NULL;
648             }
649         }
650
651         p_sys->p_context->execute = FfmpegExecute;
652     }
653 #endif
654
655     memset( &frame, 0, sizeof( AVFrame ) );
656     for( i_plane = 0; i_plane < p_pict->i_planes; i_plane++ )
657     {
658         frame.data[i_plane] = p_pict->p[i_plane].p_pixels;
659         frame.linesize[i_plane] = p_pict->p[i_plane].i_pitch;
660     }
661
662     /* Let ffmpeg select the frame type */
663     frame.pict_type = 0;
664
665     frame.repeat_pict = 2 - p_pict->i_nb_fields;
666
667 #if LIBAVCODEC_BUILD >= 4685
668     frame.interlaced_frame = !p_pict->b_progressive;
669     frame.top_field_first = !!p_pict->b_top_field_first;
670 #endif
671
672 #if LIBAVCODEC_BUILD < 4702
673     /* Set the pts of the frame being encoded (segfaults with mpeg4!)*/
674     if( p_enc->fmt_out.i_codec == VLC_FOURCC( 'm', 'p', 'g', 'v' ) ||
675         p_enc->fmt_out.i_codec == VLC_FOURCC( 'm', 'p', '1', 'v' ) ||
676         p_enc->fmt_out.i_codec == VLC_FOURCC( 'm', 'p', '2', 'v' ) )
677 #else
678     if( 1 )
679 #endif
680     {
681         frame.pts = p_pict->date ? p_pict->date : AV_NOPTS_VALUE;
682
683         if ( p_sys->b_hurry_up && frame.pts != AV_NOPTS_VALUE )
684         {
685             mtime_t current_date = mdate();
686
687             if ( current_date + HURRY_UP_GUARD3 > frame.pts )
688             {
689                 p_sys->p_context->mb_decision = FF_MB_DECISION_SIMPLE;
690                 p_sys->p_context->flags &= ~CODEC_FLAG_TRELLIS_QUANT;
691                 msg_Dbg( p_enc, "hurry up mode 3" );
692             }
693             else
694             {
695                 p_sys->p_context->mb_decision = p_sys->i_hq;
696
697                 if ( current_date + HURRY_UP_GUARD2 > frame.pts )
698                 {
699                     p_sys->p_context->flags &= ~CODEC_FLAG_TRELLIS_QUANT;
700 #if LIBAVCODEC_BUILD >= 4690
701                     p_sys->p_context->noise_reduction = p_sys->i_noise_reduction
702                          + (HURRY_UP_GUARD2 + current_date - frame.pts) / 500;
703 #endif
704                     msg_Dbg( p_enc, "hurry up mode 2" );
705                 }
706                 else
707                 {
708                     if ( p_sys->b_trellis )
709                         p_sys->p_context->flags |= CODEC_FLAG_TRELLIS_QUANT;
710 #if LIBAVCODEC_BUILD >= 4690
711                     p_sys->p_context->noise_reduction =
712                         p_sys->i_noise_reduction;
713 #endif
714                 }
715             }
716
717             if ( current_date + HURRY_UP_GUARD1 > frame.pts )
718             {
719                 frame.pict_type = FF_P_TYPE;
720                 /* msg_Dbg( p_enc, "hurry up mode 1 %lld", current_date + HURRY_UP_GUARD1 - frame.pts ); */
721             }
722         }
723     }
724     else
725     {
726         frame.pts = AV_NOPTS_VALUE;
727     }
728
729     if ( frame.pts != AV_NOPTS_VALUE && frame.pts != 0 )
730     {
731         if ( p_sys->i_last_pts == frame.pts )
732         {
733             msg_Warn( p_enc, "almost fed libavcodec with two frames with the "
734                       "same PTS (" I64Fd ")", frame.pts );
735             return NULL;
736         }
737         else if ( p_sys->i_last_pts > frame.pts )
738         {
739             msg_Warn( p_enc, "almost fed libavcodec with a frame in the "
740                       "past (current: " I64Fd ", last: "I64Fd")",
741                       frame.pts, p_sys->i_last_pts );
742             return NULL;
743         }
744         else
745         {
746             p_sys->i_last_pts = frame.pts;
747         }
748     }
749
750     frame.quality = p_sys->i_quality;
751
752     /* Ugly work-around for stupid libavcodec behaviour */
753 #if LIBAVCODEC_BUILD >= 4722
754     p_sys->i_framenum++;
755     p_sys->pi_delay_pts[p_sys->i_framenum % MAX_FRAME_DELAY] = frame.pts;
756     frame.pts = p_sys->i_framenum * AV_TIME_BASE *
757         p_enc->fmt_in.video.i_frame_rate_base;
758     frame.pts += p_enc->fmt_in.video.i_frame_rate - 1;
759     frame.pts /= p_enc->fmt_in.video.i_frame_rate;
760 #endif
761     /* End work-around */
762
763     i_out = avcodec_encode_video( p_sys->p_context, p_sys->p_buffer_out,
764                                   AVCODEC_MAX_VIDEO_FRAME_SIZE, &frame );
765
766     if( i_out > 0 )
767     {
768         block_t *p_block = block_New( p_enc, i_out );
769         memcpy( p_block->p_buffer, p_sys->p_buffer_out, i_out );
770
771         /* FIXME, 3-2 pulldown is not handled correctly */
772         p_block->i_length = I64C(1000000) *
773             p_enc->fmt_in.video.i_frame_rate_base /
774                 p_enc->fmt_in.video.i_frame_rate;
775
776         if( !p_sys->p_context->max_b_frames || !p_sys->p_context->delay )
777         {
778             /* No delay -> output pts == input pts */
779             p_block->i_pts = p_block->i_dts = p_pict->date;
780         }
781         else if( p_sys->p_context->coded_frame->pts != AV_NOPTS_VALUE &&
782             p_sys->p_context->coded_frame->pts != 0 &&
783             p_sys->i_buggy_pts_detect != p_sys->p_context->coded_frame->pts )
784         {
785             p_sys->i_buggy_pts_detect = p_sys->p_context->coded_frame->pts;
786             p_block->i_pts = p_sys->p_context->coded_frame->pts;
787
788             /* Ugly work-around for stupid libavcodec behaviour */
789 #if LIBAVCODEC_BUILD >= 4722
790             {
791             int64_t i_framenum = p_block->i_pts *
792                 p_enc->fmt_in.video.i_frame_rate /
793                 p_enc->fmt_in.video.i_frame_rate_base / AV_TIME_BASE;
794
795             p_block->i_pts = p_sys->pi_delay_pts[i_framenum % MAX_FRAME_DELAY];
796             }
797 #endif
798             /* End work-around */
799
800             if( p_sys->p_context->coded_frame->pict_type != FF_I_TYPE &&
801                 p_sys->p_context->coded_frame->pict_type != FF_P_TYPE )
802             {
803                 p_block->i_dts = p_block->i_pts;
804             }
805             else
806             {
807                 if( p_sys->i_last_ref_pts )
808                 {
809                     p_block->i_dts = p_sys->i_last_ref_pts;
810                 }
811                 else
812                 {
813                     /* Let's put something sensible */
814                     p_block->i_dts = p_block->i_pts;
815                 }
816
817                 p_sys->i_last_ref_pts = p_block->i_pts;
818             }
819         }
820         else
821         {
822             /* Buggy libavcodec which doesn't update coded_frame->pts
823              * correctly */
824             p_block->i_dts = p_block->i_pts = p_pict->date;
825         }
826
827         switch ( p_sys->p_context->coded_frame->pict_type )
828         {
829         case FF_I_TYPE:
830             p_block->i_flags |= BLOCK_FLAG_TYPE_I;
831             break;
832         case FF_P_TYPE:
833             p_block->i_flags |= BLOCK_FLAG_TYPE_P;
834             break;
835         case FF_B_TYPE:
836             p_block->i_flags |= BLOCK_FLAG_TYPE_B;
837             break;
838         }
839
840         return p_block;
841     }
842
843     return NULL;
844 }
845
846 /****************************************************************************
847  * EncodeAudio: the whole thing
848  ****************************************************************************/
849 static block_t *EncodeAudio( encoder_t *p_enc, aout_buffer_t *p_aout_buf )
850 {
851     encoder_sys_t *p_sys = p_enc->p_sys;
852     block_t *p_block, *p_chain = NULL;
853
854     char *p_buffer = p_aout_buf->p_buffer;
855     int i_samples = p_aout_buf->i_nb_samples;
856     int i_samples_delay = p_sys->i_samples_delay;
857
858     p_sys->i_pts = p_aout_buf->start_date -
859                 (mtime_t)1000000 * (mtime_t)p_sys->i_samples_delay /
860                 (mtime_t)p_enc->fmt_in.audio.i_rate;
861
862     p_sys->i_samples_delay += i_samples;
863
864     while( p_sys->i_samples_delay >= p_sys->p_context->frame_size )
865     {
866         int16_t *p_samples;
867         int i_out;
868
869         if( i_samples_delay )
870         {
871             /* Take care of the left-over from last time */
872             int i_delay_size = i_samples_delay * 2 *
873                                  p_sys->p_context->channels;
874             int i_size = p_sys->i_frame_size - i_delay_size;
875
876             p_samples = (int16_t *)p_sys->p_buffer;
877             memcpy( p_sys->p_buffer + i_delay_size, p_buffer, i_size );
878             p_buffer -= i_delay_size;
879             i_samples += i_samples_delay;
880             i_samples_delay = 0;
881         }
882         else
883         {
884             p_samples = (int16_t *)p_buffer;
885         }
886
887         i_out = avcodec_encode_audio( p_sys->p_context, p_sys->p_buffer_out,
888                                       2 * AVCODEC_MAX_AUDIO_FRAME_SIZE,
889                                       p_samples );
890
891 #if 0
892         msg_Warn( p_enc, "avcodec_encode_audio: %d", i_out );
893 #endif
894         if( i_out < 0 ) break;
895
896         p_buffer += p_sys->i_frame_size;
897         p_sys->i_samples_delay -= p_sys->p_context->frame_size;
898         i_samples -= p_sys->p_context->frame_size;
899
900         if( i_out == 0 ) continue;
901
902         p_block = block_New( p_enc, i_out );
903         memcpy( p_block->p_buffer, p_sys->p_buffer_out, i_out );
904
905         p_block->i_length = (mtime_t)1000000 *
906             (mtime_t)p_sys->p_context->frame_size /
907             (mtime_t)p_sys->p_context->sample_rate;
908
909         p_block->i_dts = p_block->i_pts = p_sys->i_pts;
910
911         /* Update pts */
912         p_sys->i_pts += p_block->i_length;
913         block_ChainAppend( &p_chain, p_block );
914     }
915
916     /* Backup the remaining raw samples */
917     if( i_samples )
918     {
919         memcpy( p_sys->p_buffer + i_samples_delay * 2 *
920                 p_sys->p_context->channels, p_buffer,
921                 i_samples * 2 * p_sys->p_context->channels );
922     }
923
924     return p_chain;
925 }
926
927 /*****************************************************************************
928  * CloseEncoder: ffmpeg encoder destruction
929  *****************************************************************************/
930 void E_(CloseEncoder)( vlc_object_t *p_this )
931 {
932     encoder_t *p_enc = (encoder_t *)p_this;
933     encoder_sys_t *p_sys = p_enc->p_sys;
934
935 #if LIBAVCODEC_BUILD >= 4702
936     if ( p_sys->b_inited && p_enc->i_threads >= 1 )
937     {
938         int i;
939         struct thread_context_t ** pp_contexts =
940                 (struct thread_context_t **)p_sys->p_context->thread_opaque;
941         for ( i = 0; i < p_enc->i_threads; i++ )
942         {
943             pp_contexts[i]->b_die = 1;
944             vlc_cond_signal( &pp_contexts[i]->cond );
945             vlc_thread_join( pp_contexts[i] );
946             vlc_mutex_destroy( &pp_contexts[i]->lock );
947             vlc_cond_destroy( &pp_contexts[i]->cond );
948             vlc_object_destroy( pp_contexts[i] );
949         }
950
951         free( pp_contexts );
952     }
953 #endif
954
955     avcodec_close( p_sys->p_context );
956     av_free( p_sys->p_context );
957
958     if( p_sys->p_buffer ) free( p_sys->p_buffer );
959     if( p_sys->p_buffer_out ) free( p_sys->p_buffer_out );
960
961     free( p_sys );
962 }