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