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