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