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