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