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