]> git.sesse.net Git - vlc/blob - modules/codec/avcodec/encoder.c
ec8e02a131e03c2b9c7931fb56eb084824a6c1bf
[vlc] / modules / codec / avcodec / encoder.c
1 /*****************************************************************************
2  * encoder.c: video and audio encoder using the libavcodec library
3  *****************************************************************************
4  * Copyright (C) 1999-2004 VLC authors and VideoLAN
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 it
14  * under the terms of the GNU Lesser General Public License as published by
15  * the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
22  *
23  * You should have received a copy of the GNU Lesser General Public License
24  * along with this program; if not, write to the Free Software Foundation,
25  * 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 #include <libavcodec/avcodec.h>
44 #include <libavutil/audioconvert.h>
45
46 #include "avcodec.h"
47 #include "avcommon.h"
48
49 #if LIBAVUTIL_VERSION_CHECK( 52,2,6,0,0 )
50 # include <libavutil/channel_layout.h>
51 #endif
52
53 #define HURRY_UP_GUARD1 (450000)
54 #define HURRY_UP_GUARD2 (300000)
55 #define HURRY_UP_GUARD3 (100000)
56
57 #define MAX_FRAME_DELAY (FF_MAX_B_FRAMES + 2)
58
59 #define RAW_AUDIO_FRAME_SIZE (2048)
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 *, block_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 : libavcodec encoder descriptor
91  *****************************************************************************/
92 struct encoder_sys_t
93 {
94     /*
95      * libavcodec properties
96      */
97     AVCodec         *p_codec;
98     AVCodecContext  *p_context;
99
100     /*
101      * Common buffer mainly for audio as frame size in there needs usually be constant
102      */
103     uint8_t *p_buffer;
104     size_t i_buffer_out;
105     uint8_t *p_interleave_buf;
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     size_t i_sample_bytes;
119     size_t i_frame_size;
120     size_t i_samples_delay; //How much samples in delay buffer
121     bool b_planar;
122     bool b_variable;    //Encoder can be fed with any size frames not just frame_size
123     mtime_t i_pts;
124     date_t  buffer_date;
125
126     /* Multichannel (>2) channel reordering */
127     uint8_t    i_channels_to_reorder;
128     uint8_t    pi_reorder_layout[AOUT_CHAN_MAX];
129
130     /* Encoding settings */
131     int        i_key_int;
132     int        i_b_frames;
133     int        i_vtolerance;
134     int        i_qmin;
135     int        i_qmax;
136     int        i_hq;
137     int        i_rc_buffer_size;
138     float      f_rc_buffer_aggressivity;
139     bool       b_pre_me;
140     bool       b_hurry_up;
141     bool       b_interlace, b_interlace_me;
142     float      f_i_quant_factor;
143     int        i_noise_reduction;
144     bool       b_mpeg4_matrix;
145     bool       b_trellis;
146     int        i_quality; /* for VBR */
147     float      f_lumi_masking, f_dark_masking, f_p_masking, f_border_masking;
148 #if (LIBAVCODEC_VERSION_MAJOR < 55)
149     int        i_luma_elim, i_chroma_elim;
150 #endif
151     int        i_aac_profile; /* AAC profile to use.*/
152
153     AVFrame    *frame;
154 };
155
156
157 /* Taken from audio.c*/
158 static const uint64_t pi_channels_map[][2] =
159 {
160     { AV_CH_FRONT_LEFT,        AOUT_CHAN_LEFT },
161     { AV_CH_FRONT_RIGHT,       AOUT_CHAN_RIGHT },
162     { AV_CH_FRONT_CENTER,      AOUT_CHAN_CENTER },
163     { AV_CH_LOW_FREQUENCY,     AOUT_CHAN_LFE },
164     { AV_CH_BACK_LEFT,         AOUT_CHAN_REARLEFT },
165     { AV_CH_BACK_RIGHT,        AOUT_CHAN_REARRIGHT },
166     { AV_CH_FRONT_LEFT_OF_CENTER, 0 },
167     { AV_CH_FRONT_RIGHT_OF_CENTER, 0 },
168     { AV_CH_BACK_CENTER,       AOUT_CHAN_REARCENTER },
169     { AV_CH_SIDE_LEFT,         AOUT_CHAN_MIDDLELEFT },
170     { AV_CH_SIDE_RIGHT,        AOUT_CHAN_MIDDLERIGHT },
171     { AV_CH_TOP_CENTER,        0 },
172     { AV_CH_TOP_FRONT_LEFT,    0 },
173     { AV_CH_TOP_FRONT_CENTER,  0 },
174     { AV_CH_TOP_FRONT_RIGHT,   0 },
175     { AV_CH_TOP_BACK_LEFT,     0 },
176     { AV_CH_TOP_BACK_CENTER,   0 },
177     { AV_CH_TOP_BACK_RIGHT,    0 },
178     { AV_CH_STEREO_LEFT,       0 },
179     { AV_CH_STEREO_RIGHT,      0 },
180 };
181
182 static const uint32_t channel_mask[][2] = {
183     {0,0},
184     {AOUT_CHAN_CENTER, AV_CH_LAYOUT_MONO},
185     {AOUT_CHANS_STEREO, AV_CH_LAYOUT_STEREO},
186     {AOUT_CHANS_2_1, AV_CH_LAYOUT_2POINT1},
187     {AOUT_CHANS_4_0, AV_CH_LAYOUT_4POINT0},
188     {AOUT_CHANS_4_1, AV_CH_LAYOUT_4POINT1},
189     {AOUT_CHANS_5_1, AV_CH_LAYOUT_5POINT1_BACK},
190     {AOUT_CHANS_7_0, AV_CH_LAYOUT_7POINT0},
191     {AOUT_CHANS_7_1, AV_CH_LAYOUT_7POINT1},
192     {AOUT_CHANS_8_1, AV_CH_LAYOUT_OCTAGONAL},
193 };
194
195 static const char *const ppsz_enc_options[] = {
196     "keyint", "bframes", "vt", "qmin", "qmax", "codec", "hq",
197     "rc-buffer-size", "rc-buffer-aggressivity", "pre-me", "hurry-up",
198     "interlace", "interlace-me", "i-quant-factor", "noise-reduction", "mpeg4-matrix",
199     "trellis", "qscale", "strict", "lumi-masking", "dark-masking",
200     "p-masking", "border-masking",
201 #if (LIBAVCODEC_VERSION_MAJOR < 55)
202     "luma-elim-threshold", "chroma-elim-threshold",
203 #endif
204     "aac-profile", "options",
205     NULL
206 };
207
208 static const uint16_t mpa_bitrate_tab[2][15] =
209 {
210     {0, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384},
211     {0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160}
212 };
213
214 static const uint16_t mpa_freq_tab[6] =
215 { 44100, 48000, 32000, 22050, 24000, 16000 };
216
217 static const uint16_t mpeg4_default_intra_matrix[64] = {
218   8, 17, 18, 19, 21, 23, 25, 27,
219  17, 18, 19, 21, 23, 25, 27, 28,
220  20, 21, 22, 23, 24, 26, 28, 30,
221  21, 22, 23, 24, 26, 28, 30, 32,
222  22, 23, 24, 26, 28, 30, 32, 35,
223  23, 24, 26, 28, 30, 32, 35, 38,
224  25, 26, 28, 30, 32, 35, 38, 41,
225  27, 28, 30, 32, 35, 38, 41, 45,
226 };
227
228 static const uint16_t mpeg4_default_non_intra_matrix[64] = {
229  16, 17, 18, 19, 20, 21, 22, 23,
230  17, 18, 19, 20, 21, 22, 23, 24,
231  18, 19, 20, 21, 22, 23, 24, 25,
232  19, 20, 21, 22, 23, 24, 26, 27,
233  20, 21, 22, 23, 25, 26, 27, 28,
234  21, 22, 23, 24, 26, 27, 28, 30,
235  22, 23, 24, 26, 27, 28, 30, 31,
236  23, 24, 25, 27, 28, 30, 31, 33,
237 };
238
239 #if LIBAVUTIL_VERSION_CHECK( 51, 27, 2, 46, 100 )
240 static const int DEFAULT_ALIGN = 0;
241 #else
242 static const int DEFAULT_ALIGN = 1;
243 #endif
244
245
246 /*****************************************************************************
247  * OpenEncoder: probe the encoder
248  *****************************************************************************/
249
250 int OpenEncoder( vlc_object_t *p_this )
251 {
252     encoder_t *p_enc = (encoder_t *)p_this;
253     encoder_sys_t *p_sys;
254     AVCodecContext *p_context;
255     AVCodec *p_codec = NULL;
256     unsigned i_codec_id;
257     int i_cat;
258     const char *psz_namecodec;
259     float f_val;
260     char *psz_val;
261
262     /* Initialization must be done before avcodec_find_encoder() */
263     vlc_init_avcodec(p_this);
264
265     config_ChainParse( p_enc, ENC_CFG_PREFIX, ppsz_enc_options, p_enc->p_cfg );
266
267     if( p_enc->fmt_out.i_codec == VLC_CODEC_MP1V )
268     {
269         i_cat = VIDEO_ES;
270         i_codec_id = AV_CODEC_ID_MPEG1VIDEO;
271         psz_namecodec = "MPEG-1 video";
272     }
273     else if( !GetFfmpegCodec( p_enc->fmt_out.i_codec, &i_cat, &i_codec_id,
274                              &psz_namecodec ) )
275     {
276         if( FindFfmpegChroma( p_enc->fmt_out.i_codec ) == PIX_FMT_NONE )
277             return VLC_EGENERIC; /* handed chroma output */
278
279         i_cat      = VIDEO_ES;
280         i_codec_id = AV_CODEC_ID_RAWVIDEO;
281         psz_namecodec = "Raw video";
282     }
283
284     if( p_enc->fmt_out.i_cat == VIDEO_ES && i_cat != VIDEO_ES )
285     {
286         msg_Err( p_enc, "\"%s\" is not a video encoder", psz_namecodec );
287         dialog_Fatal( p_enc, _("Streaming / Transcoding failed"),
288                         _("\"%s\" is no video encoder."), psz_namecodec );
289         return VLC_EGENERIC;
290     }
291
292     if( p_enc->fmt_out.i_cat == AUDIO_ES && i_cat != AUDIO_ES )
293     {
294         msg_Err( p_enc, "\"%s\" is not an audio encoder", psz_namecodec );
295         dialog_Fatal( p_enc, _("Streaming / Transcoding failed"),
296                         _("\"%s\" is no audio encoder."), psz_namecodec );
297         return VLC_EGENERIC;
298     }
299
300     if( p_enc->fmt_out.i_cat == SPU_ES )
301     {
302         /* We don't support subtitle encoding */
303         return VLC_EGENERIC;
304     }
305
306     char *psz_encoder = var_GetString( p_this, ENC_CFG_PREFIX "codec" );
307     if( psz_encoder && *psz_encoder )
308     {
309         p_codec = avcodec_find_encoder_by_name( psz_encoder );
310         if( !p_codec )
311             msg_Err( p_this, "Encoder `%s' not found", psz_encoder );
312         else if( p_codec->id != i_codec_id )
313         {
314             msg_Err( p_this, "Encoder `%s' can't handle %4.4s",
315                     psz_encoder, (char*)&p_enc->fmt_out.i_codec );
316             p_codec = NULL;
317         }
318     }
319     free( psz_encoder );
320     if( !p_codec )
321         p_codec = avcodec_find_encoder( i_codec_id );
322     if( !p_codec )
323     {
324         msg_Err( p_enc, "cannot find encoder %s\n"
325 "*** Your Libav/FFmpeg installation is crippled.   ***\n"
326 "*** Please check with your Libav/FFmpeg packager. ***\n"
327 "*** This is NOT a VLC media player issue.   ***", psz_namecodec );
328
329         dialog_Fatal( p_enc, _("Streaming / Transcoding failed"), _(
330 /* I have had enough of all these MPEG-3 transcoding bug reports.
331  * Downstream packager, you had better not patch this out, or I will be really
332  * annoyed. Think about it - you don't want to fork the VLC translation files,
333  * do you? -- Courmisch, 2008-10-22 */
334 "It seems your Libav/FFmpeg (libavcodec) installation lacks the following encoder:\n"
335 "%s.\n"
336 "If you don't know how to fix this, ask for support from your distribution.\n"
337 "\n"
338 "This is not an error inside VLC media player.\n"
339 "Do not contact the VideoLAN project about this issue.\n"),
340             psz_namecodec );
341         return VLC_EGENERIC;
342     }
343
344     /* Allocate the memory needed to store the encoder's structure */
345     if( ( p_sys = calloc( 1, sizeof(encoder_sys_t) ) ) == NULL )
346         return VLC_ENOMEM;
347     p_enc->p_sys = p_sys;
348     p_sys->i_samples_delay = 0;
349     p_sys->p_codec = p_codec;
350     p_sys->b_planar = false;
351
352     p_sys->p_buffer = NULL;
353     p_sys->p_interleave_buf = NULL;
354     p_sys->i_buffer_out = 0;
355
356     p_context = avcodec_alloc_context3(p_codec);
357     p_sys->p_context = p_context;
358     p_sys->p_context->codec_id = p_sys->p_codec->id;
359     p_context->thread_type = 0;
360     p_context->debug = var_InheritInteger( p_enc, "avcodec-debug" );
361     p_context->opaque = (void *)p_this;
362
363     p_sys->i_key_int = var_GetInteger( p_enc, ENC_CFG_PREFIX "keyint" );
364     p_sys->i_b_frames = var_GetInteger( p_enc, ENC_CFG_PREFIX "bframes" );
365     p_sys->i_vtolerance = var_GetInteger( p_enc, ENC_CFG_PREFIX "vt" ) * 1000;
366     p_sys->b_interlace = var_GetBool( p_enc, ENC_CFG_PREFIX "interlace" );
367     p_sys->b_interlace_me = var_GetBool( p_enc, ENC_CFG_PREFIX "interlace-me" );
368     p_sys->b_pre_me = var_GetBool( p_enc, ENC_CFG_PREFIX "pre-me" );
369     p_sys->b_hurry_up = var_GetBool( p_enc, ENC_CFG_PREFIX "hurry-up" );
370
371     if( p_sys->b_hurry_up )
372     {
373         /* hurry up mode needs noise reduction, even small */
374         p_sys->i_noise_reduction = 1;
375     }
376
377     p_sys->i_rc_buffer_size = var_GetInteger( p_enc, ENC_CFG_PREFIX "rc-buffer-size" );
378     p_sys->f_rc_buffer_aggressivity = var_GetFloat( p_enc, ENC_CFG_PREFIX "rc-buffer-aggressivity" );
379     p_sys->f_i_quant_factor = var_GetFloat( p_enc, ENC_CFG_PREFIX "i-quant-factor" );
380     p_sys->i_noise_reduction = var_GetInteger( p_enc, ENC_CFG_PREFIX "noise-reduction" );
381     p_sys->b_mpeg4_matrix = var_GetBool( p_enc, ENC_CFG_PREFIX "mpeg4-matrix" );
382
383     f_val = var_GetFloat( p_enc, ENC_CFG_PREFIX "qscale" );
384
385     p_sys->i_quality = 0;
386     if( f_val < 0.01 || f_val > 255.0 )
387         f_val = 0;
388     else
389         p_sys->i_quality = (int)(FF_QP2LAMBDA * f_val + 0.5);
390
391     psz_val = var_GetString( p_enc, ENC_CFG_PREFIX "hq" );
392     p_sys->i_hq = FF_MB_DECISION_RD;
393     if( psz_val && *psz_val )
394     {
395         if( !strcmp( psz_val, "rd" ) )
396             p_sys->i_hq = FF_MB_DECISION_RD;
397         else if( !strcmp( psz_val, "bits" ) )
398             p_sys->i_hq = FF_MB_DECISION_BITS;
399         else if( !strcmp( psz_val, "simple" ) )
400             p_sys->i_hq = FF_MB_DECISION_SIMPLE;
401         else
402             p_sys->i_hq = FF_MB_DECISION_RD;
403     }
404     else
405         p_sys->i_hq = FF_MB_DECISION_RD;
406     free( psz_val );
407
408     p_sys->i_qmin = var_GetInteger( p_enc, ENC_CFG_PREFIX "qmin" );
409     p_sys->i_qmax = var_GetInteger( p_enc, ENC_CFG_PREFIX "qmax" );
410     p_sys->b_trellis = var_GetBool( p_enc, ENC_CFG_PREFIX "trellis" );
411
412     p_context->strict_std_compliance = var_GetInteger( p_enc, ENC_CFG_PREFIX "strict" );
413
414     p_sys->f_lumi_masking = var_GetFloat( p_enc, ENC_CFG_PREFIX "lumi-masking" );
415     p_sys->f_dark_masking = var_GetFloat( p_enc, ENC_CFG_PREFIX "dark-masking" );
416     p_sys->f_p_masking = var_GetFloat( p_enc, ENC_CFG_PREFIX "p-masking" );
417     p_sys->f_border_masking = var_GetFloat( p_enc, ENC_CFG_PREFIX "border-masking" );
418 #if (LIBAVCODEC_VERSION_MAJOR < 55)
419     p_sys->i_luma_elim = var_GetInteger( p_enc, ENC_CFG_PREFIX "luma-elim-threshold" );
420     p_sys->i_chroma_elim = var_GetInteger( p_enc, ENC_CFG_PREFIX "chroma-elim-threshold" );
421 #endif
422
423     psz_val = var_GetString( p_enc, ENC_CFG_PREFIX "aac-profile" );
424     /* libavcodec uses faac encoder atm, and it has issues with
425      * other than low-complexity profile, so default to that */
426     p_sys->i_aac_profile = FF_PROFILE_AAC_LOW;
427     if( psz_val && *psz_val )
428     {
429         if( !strncmp( psz_val, "main", 4 ) )
430             p_sys->i_aac_profile = FF_PROFILE_AAC_MAIN;
431         else if( !strncmp( psz_val, "low", 3 ) )
432             p_sys->i_aac_profile = FF_PROFILE_AAC_LOW;
433         else if( !strncmp( psz_val, "ssr", 3 ) )
434             p_sys->i_aac_profile = FF_PROFILE_AAC_SSR;
435         else if( !strncmp( psz_val, "ltp", 3 ) )
436             p_sys->i_aac_profile = FF_PROFILE_AAC_LTP;
437 #if LIBAVCODEC_VERSION_CHECK( 54, 19, 0, 35, 100 )
438 /* These require libavcodec with libfdk-aac */
439         else if( !strncmp( psz_val, "hev2", 4 ) )
440             p_sys->i_aac_profile = FF_PROFILE_AAC_HE_V2;
441         else if( !strncmp( psz_val, "hev1", 4 ) )
442             p_sys->i_aac_profile = FF_PROFILE_AAC_HE;
443         else if( !strncmp( psz_val, "ld", 2 ) )
444             p_sys->i_aac_profile = FF_PROFILE_AAC_LD;
445         else if( !strncmp( psz_val, "eld", 3 ) )
446             p_sys->i_aac_profile = FF_PROFILE_AAC_ELD;
447 #endif
448         else
449         {
450             msg_Warn( p_enc, "unknown AAC profile requested, setting it to low" );
451             p_sys->i_aac_profile = FF_PROFILE_AAC_LOW;
452         }
453     }
454     free( psz_val );
455
456     if( p_enc->fmt_in.i_cat == VIDEO_ES )
457     {
458         if( !p_enc->fmt_in.video.i_visible_width || !p_enc->fmt_in.video.i_visible_height )
459         {
460             msg_Warn( p_enc, "invalid size %ix%i", p_enc->fmt_in.video.i_visible_width,
461                       p_enc->fmt_in.video.i_visible_height );
462             free( p_sys );
463             return VLC_EGENERIC;
464         }
465
466         p_context->codec_type = AVMEDIA_TYPE_VIDEO;
467
468         p_context->width = p_enc->fmt_in.video.i_visible_width;
469         p_context->height = p_enc->fmt_in.video.i_visible_height;
470
471         /* if we don't have i_frame_rate_base, we are probing and just checking if we can find codec
472          * so set fps to 25 as some codecs (DIV3 atleast) needs time_base data */
473         p_context->time_base.num = p_enc->fmt_in.video.i_frame_rate_base ? p_enc->fmt_in.video.i_frame_rate_base : 1;
474         p_context->time_base.den = p_enc->fmt_in.video.i_frame_rate_base ? p_enc->fmt_in.video.i_frame_rate : 25 ;
475         if( p_codec->supported_framerates )
476         {
477             AVRational target = {
478                 .num = p_enc->fmt_in.video.i_frame_rate,
479                 .den = p_enc->fmt_in.video.i_frame_rate_base,
480             };
481             int idx = av_find_nearest_q_idx(target, p_codec->supported_framerates);
482
483             p_context->time_base.num = p_codec->supported_framerates[idx].den;
484             p_context->time_base.den = p_codec->supported_framerates[idx].num;
485         }
486         msg_Dbg( p_enc, "Time base set to %d/%d", p_context->time_base.num, p_context->time_base.den );
487
488         /* Defaults from ffmpeg.c */
489         p_context->qblur = 0.5;
490         p_context->qcompress = 0.5;
491         p_context->b_quant_offset = 1.25;
492         p_context->b_quant_factor = 1.25;
493         p_context->i_quant_offset = 0.0;
494         p_context->i_quant_factor = -0.8;
495
496         p_context->lumi_masking = p_sys->f_lumi_masking;
497         p_context->dark_masking = p_sys->f_dark_masking;
498         p_context->p_masking = p_sys->f_p_masking;
499         p_context->border_masking = p_sys->f_border_masking;
500 #if (LIBAVCODEC_VERSION_MAJOR < 55)
501         p_context->luma_elim_threshold = p_sys->i_luma_elim;
502         p_context->chroma_elim_threshold = p_sys->i_chroma_elim;
503 #endif
504
505         if( p_sys->i_key_int > 0 )
506             p_context->gop_size = p_sys->i_key_int;
507         p_context->max_b_frames =
508             VLC_CLIP( p_sys->i_b_frames, 0, FF_MAX_B_FRAMES );
509         p_context->b_frame_strategy = 0;
510         if( !p_context->max_b_frames  &&
511             (  p_enc->fmt_out.i_codec == VLC_CODEC_MPGV ||
512                p_enc->fmt_out.i_codec == VLC_CODEC_MP2V ) )
513             p_context->flags |= CODEC_FLAG_LOW_DELAY;
514
515         av_reduce( &p_context->sample_aspect_ratio.num,
516                    &p_context->sample_aspect_ratio.den,
517                    p_enc->fmt_in.video.i_sar_num,
518                    p_enc->fmt_in.video.i_sar_den, 1 << 30 );
519
520
521         p_enc->fmt_in.i_codec = VLC_CODEC_I420;
522         p_enc->fmt_in.video.i_chroma = p_enc->fmt_in.i_codec;
523         GetFfmpegChroma( &p_context->pix_fmt, &p_enc->fmt_in.video );
524
525         if( p_codec->pix_fmts )
526         {
527             const enum PixelFormat *p = p_codec->pix_fmts;
528             for( ; *p != -1; p++ )
529             {
530                 if( *p == p_context->pix_fmt ) break;
531             }
532             if( *p == -1 ) p_context->pix_fmt = p_codec->pix_fmts[0];
533             GetVlcChroma( &p_enc->fmt_in.video, p_context->pix_fmt );
534             p_enc->fmt_in.i_codec = p_enc->fmt_in.video.i_chroma;
535         }
536
537
538         if ( p_sys->f_i_quant_factor != 0.0 )
539             p_context->i_quant_factor = p_sys->f_i_quant_factor;
540
541         p_context->noise_reduction = p_sys->i_noise_reduction;
542
543         if ( p_sys->b_mpeg4_matrix )
544         {
545             p_context->intra_matrix = mpeg4_default_intra_matrix;
546             p_context->inter_matrix = mpeg4_default_non_intra_matrix;
547         }
548
549         if ( p_sys->b_pre_me )
550         {
551             p_context->pre_me = 1;
552             p_context->me_pre_cmp = FF_CMP_CHROMA;
553         }
554
555         if ( p_sys->b_interlace )
556         {
557             if ( p_context->height <= 280 )
558             {
559                 if ( p_context->height != 16 || p_context->width != 16 )
560                     msg_Warn( p_enc,
561                         "disabling interlaced video because height=%d <= 280",
562                         p_context->height );
563             }
564             else
565             {
566                 p_context->flags |= CODEC_FLAG_INTERLACED_DCT;
567                 if ( p_sys->b_interlace_me )
568                     p_context->flags |= CODEC_FLAG_INTERLACED_ME;
569             }
570         }
571
572         p_context->trellis = p_sys->b_trellis;
573
574         if ( p_sys->i_qmin > 0 && p_sys->i_qmin == p_sys->i_qmax )
575             p_context->flags |= CODEC_FLAG_QSCALE;
576         /* These codecs cause libavcodec to exit if thread_count is > 1.
577            See libavcodec/mpegvideo_enc.c:MPV_encode_init and
578            libavcodec/svq3.c , WMV2 calls MPV_encode_init also.
579          */
580         if ( i_codec_id == AV_CODEC_ID_FLV1 ||
581              i_codec_id == AV_CODEC_ID_H261 ||
582              i_codec_id == AV_CODEC_ID_LJPEG ||
583              i_codec_id == AV_CODEC_ID_MJPEG ||
584              i_codec_id == AV_CODEC_ID_H263 ||
585              i_codec_id == AV_CODEC_ID_H263P ||
586              i_codec_id == AV_CODEC_ID_MSMPEG4V1 ||
587              i_codec_id == AV_CODEC_ID_MSMPEG4V2 ||
588              i_codec_id == AV_CODEC_ID_MSMPEG4V3 ||
589              i_codec_id == AV_CODEC_ID_WMV1 ||
590              i_codec_id == AV_CODEC_ID_WMV2 ||
591              i_codec_id == AV_CODEC_ID_RV10 ||
592              i_codec_id == AV_CODEC_ID_RV20 ||
593              i_codec_id == AV_CODEC_ID_SVQ3 )
594             p_enc->i_threads = 1;
595
596         if( p_sys->i_vtolerance > 0 )
597             p_context->bit_rate_tolerance = p_sys->i_vtolerance;
598
599         /* usually if someone sets bitrate, he likes more to get that bitrate
600          * over quality should help 'normal' user to get asked bitrate
601          */
602         if( p_enc->fmt_out.i_bitrate > 0 && p_sys->i_qmax == 0 && p_sys->i_qmin == 0 )
603         {
604             p_sys->i_qmax = 51;
605             p_sys->i_qmin = 3;
606         }
607
608         if( p_sys->i_qmin > 0 )
609         {
610             p_context->qmin = p_sys->i_qmin;
611             p_context->mb_lmin = p_context->lmin = p_sys->i_qmin * FF_QP2LAMBDA;
612         }
613         if( p_sys->i_qmax > 0 )
614         {
615             p_context->qmax = p_sys->i_qmax;
616             p_context->mb_lmax = p_context->lmax = p_sys->i_qmax * FF_QP2LAMBDA;
617         }
618         p_context->max_qdiff = 3;
619
620         p_context->mb_decision = p_sys->i_hq;
621
622         if( p_sys->i_quality )
623         {
624             p_context->flags |= CODEC_FLAG_QSCALE;
625             p_context->global_quality = p_sys->i_quality;
626         }
627         else
628         {
629             p_context->rc_qsquish = 1.0;
630             /* Default to 1/2 second buffer for given bitrate unless defined otherwise*/
631             if( !p_sys->i_rc_buffer_size )
632             {
633                 p_sys->i_rc_buffer_size = p_enc->fmt_out.i_bitrate * 8 / 2;
634             }
635             msg_Dbg( p_enc, "rc buffer size %d bits", p_sys->i_rc_buffer_size );
636             /* Set maxrate/minrate to bitrate to try to get CBR */
637             p_context->rc_max_rate = p_enc->fmt_out.i_bitrate;
638             p_context->rc_min_rate = p_enc->fmt_out.i_bitrate;
639             p_context->rc_buffer_size = p_sys->i_rc_buffer_size;
640             /* This is from ffmpeg's ffmpeg.c : */
641             p_context->rc_initial_buffer_occupancy
642                 = p_sys->i_rc_buffer_size * 3/4;
643             p_context->rc_buffer_aggressivity = p_sys->f_rc_buffer_aggressivity;
644         }
645     }
646     else if( p_enc->fmt_in.i_cat == AUDIO_ES )
647     {
648         /* work around bug in libmp3lame encoding */
649         if( i_codec_id == AV_CODEC_ID_MP3 && p_enc->fmt_out.audio.i_channels  > 2 )
650             p_enc->fmt_out.audio.i_channels = 2;
651         p_context->codec_type  = AVMEDIA_TYPE_AUDIO;
652         p_context->sample_fmt  = p_codec->sample_fmts ?
653                                     p_codec->sample_fmts[0] :
654                                     AV_SAMPLE_FMT_S16;
655
656         /* Try to match avcodec input format to vlc format so we could avoid one
657            format conversion */
658         if( GetVlcAudioFormat( p_context->sample_fmt ) != p_enc->fmt_in.i_codec )
659         {
660             msg_Dbg( p_enc, "Trying to find more suitable sample format instead of %s", av_get_sample_fmt_name( p_context->sample_fmt ) );
661             for( unsigned int i=0; p_codec->sample_fmts[i] != -1; i++ )
662             {
663                 if( GetVlcAudioFormat( p_codec->sample_fmts[i] ) == p_enc->fmt_in.i_codec )
664                 {
665                     p_context->sample_fmt = p_codec->sample_fmts[i];
666                     msg_Dbg( p_enc, "Using %s as new sample format", av_get_sample_fmt_name( p_context->sample_fmt ) );
667                     break;
668                 }
669             }
670         }
671         p_sys->b_planar = av_sample_fmt_is_planar( p_context->sample_fmt );
672         // Try if we can use interleaved format for codec input as VLC doesn't really do planar audio yet
673         // FIXME: Remove when planar/interleaved audio in vlc is equally supported
674         if( p_sys->b_planar )
675         {
676             msg_Dbg( p_enc, "Trying to find packet sample format instead of planar %s", av_get_sample_fmt_name( p_context->sample_fmt ) );
677             for( unsigned int i=0; p_codec->sample_fmts[i] != -1; i++ )
678             {
679                 if( !av_sample_fmt_is_planar( p_codec->sample_fmts[i] ) )
680                 {
681                     p_context->sample_fmt = p_codec->sample_fmts[i];
682                     msg_Dbg( p_enc, "Changing to packet format %s as new sample format", av_get_sample_fmt_name( p_context->sample_fmt ) );
683                     break;
684                 }
685             }
686         }
687         msg_Dbg( p_enc, "Ended up using %s as sample format", av_get_sample_fmt_name( p_context->sample_fmt ) );
688         p_enc->fmt_in.i_codec  = GetVlcAudioFormat( p_context->sample_fmt );
689         p_sys->b_planar = av_sample_fmt_is_planar( p_context->sample_fmt );
690
691         p_context->sample_rate = p_enc->fmt_out.audio.i_rate;
692         date_Init( &p_sys->buffer_date, p_enc->fmt_out.audio.i_rate, 1 );
693         date_Set( &p_sys->buffer_date, AV_NOPTS_VALUE );
694         p_context->time_base.num = 1;
695         p_context->time_base.den = p_context->sample_rate;
696         p_context->channels      = p_enc->fmt_out.audio.i_channels;
697 #if LIBAVUTIL_VERSION_CHECK( 52, 2, 6, 0, 0)
698         p_context->channel_layout = channel_mask[p_context->channels][1];
699
700         /* Setup Channel ordering for multichannel audio
701          * as VLC channel order isn't same as libavcodec expects
702          */
703
704         p_sys->i_channels_to_reorder = 0;
705
706         /* Specified order
707          * Copied from audio.c
708          */
709         const unsigned i_order_max = 8 * sizeof(p_context->channel_layout);
710         uint32_t pi_order_dst[AOUT_CHAN_MAX];
711         int i_channels_src = 0;
712
713         if( p_context->channel_layout )
714         {
715             msg_Dbg( p_enc, "Creating channel order for reordering");
716             for( unsigned i = 0; i < sizeof(pi_channels_map)/sizeof(*pi_channels_map); i++ )
717             {
718                 if( p_context->channel_layout & pi_channels_map[i][0] )
719                 {
720                     msg_Dbg( p_enc, "%d %x mapped to %x", i_channels_src, pi_channels_map[i][0], pi_channels_map[i][1]);
721                     pi_order_dst[i_channels_src++] = pi_channels_map[i][1];
722                 }
723             }
724         }
725         else
726         {
727             msg_Dbg( p_enc, "Creating default channel order for reordering");
728             /* Create default order  */
729             for( unsigned int i = 0; i < __MIN( i_order_max, (unsigned)p_sys->p_context->channels ); i++ )
730             {
731                 if( i < sizeof(pi_channels_map)/sizeof(*pi_channels_map) )
732                 {
733                     msg_Dbg( p_enc, "%d channel is %x", i_channels_src, pi_channels_map[i][1]);
734                     pi_order_dst[i_channels_src++] = pi_channels_map[i][1];
735                 }
736             }
737         }
738         if( i_channels_src != p_context->channels )
739             msg_Err( p_enc, "Channel layout not understood" );
740
741         p_sys->i_channels_to_reorder = aout_CheckChannelReorder( NULL, pi_order_dst,
742             channel_mask[p_context->channels][0], p_sys->pi_reorder_layout );
743 #endif
744
745         if ( p_enc->fmt_out.i_codec == VLC_CODEC_MP4A )
746         {
747             /* XXX: FAAC does resample only when setting the INPUT samplerate
748              * to the desired value (-R option of the faac frontend)
749             p_enc->fmt_in.audio.i_rate = p_context->sample_rate;*/
750             /* vlc should default to low-complexity profile, faac encoder
751              * has bug and aac audio has issues otherwise atm */
752             p_context->profile = p_sys->i_aac_profile;
753         }
754     }
755
756     /* Misc parameters */
757     p_context->bit_rate = p_enc->fmt_out.i_bitrate;
758
759     /* Set reasonable defaults to VP8, based on
760        libvpx-720p preset from libvpx ffmpeg-patch */
761     if( i_codec_id == AV_CODEC_ID_VP8 )
762     {
763         /* Lets give bitrate tolerance */
764         p_context->bit_rate_tolerance = __MAX(2 * (int)p_enc->fmt_out.i_bitrate, p_sys->i_vtolerance );
765         /* default to 120 frames between keyframe */
766         if( !var_GetInteger( p_enc, ENC_CFG_PREFIX "keyint" ) )
767             p_context->gop_size = 120;
768         /* Don't set rc-values atm, they were from time before
769            libvpx was officially in FFmpeg */
770         //p_context->rc_max_rate = 24 * 1000 * 1000; //24M
771         //p_context->rc_min_rate = 40 * 1000; // 40k
772         /* seems that FFmpeg presets have 720p as divider for buffers */
773         if( p_enc->fmt_out.video.i_visible_height >= 720 )
774         {
775             /* Check that we don't overrun users qmin/qmax values */
776             if( !var_GetInteger( p_enc, ENC_CFG_PREFIX "qmin" ) )
777             {
778                 p_context->qmin = 10;
779                 p_context->mb_lmin = p_context->lmin = 10 * FF_QP2LAMBDA;
780             }
781
782             if( !var_GetInteger( p_enc, ENC_CFG_PREFIX "qmax" ) )
783             {
784                 p_context->qmax = 42;
785                 p_context->mb_lmax = p_context->lmax = 42 * FF_QP2LAMBDA;
786             }
787
788             } else {
789             if( !var_GetInteger( p_enc, ENC_CFG_PREFIX "qmin" ) )
790             {
791                 p_context->qmin = 1;
792                 p_context->mb_lmin = p_context->lmin = FF_QP2LAMBDA;
793             }
794         }
795
796
797 #if 0 /* enable when/if vp8 encoder is accepted in libavcodec */
798         p_context->lag = 16;
799         p_context->level = 216;
800         p_context->profile = 0;
801         p_context->rc_buffer_aggressivity = 0.95;
802         p_context->token_partitions = 4;
803         p_context->mb_static_threshold = 0;
804 #endif
805     }
806
807     if( i_codec_id == AV_CODEC_ID_RAWVIDEO )
808     {
809         /* XXX: hack: Force same codec (will be handled by transcode) */
810         p_enc->fmt_in.video.i_chroma = p_enc->fmt_in.i_codec = p_enc->fmt_out.i_codec;
811         GetFfmpegChroma( &p_context->pix_fmt, &p_enc->fmt_in.video );
812     }
813
814     /* Make sure we get extradata filled by the encoder */
815     p_context->extradata_size = 0;
816     p_context->extradata = NULL;
817     p_context->flags |= CODEC_FLAG_GLOBAL_HEADER;
818
819     if( p_enc->i_threads >= 1)
820         p_context->thread_count = p_enc->i_threads;
821     else
822         p_context->thread_count = vlc_GetCPUCount();
823
824     int ret;
825     char *psz_opts = var_InheritString(p_enc, ENC_CFG_PREFIX "options");
826     AVDictionary *options = NULL;
827     if (psz_opts && *psz_opts)
828         options = vlc_av_get_options(psz_opts);
829     free(psz_opts);
830
831     vlc_avcodec_lock();
832     ret = avcodec_open2( p_context, p_codec, options ? &options : NULL );
833     vlc_avcodec_unlock();
834
835     AVDictionaryEntry *t = NULL;
836     while ((t = av_dict_get(options, "", t, AV_DICT_IGNORE_SUFFIX))) {
837         msg_Err(p_enc, "Unknown option \"%s\"", t->key);
838     }
839
840     if( ret )
841     {
842         if( p_enc->fmt_in.i_cat != AUDIO_ES ||
843                 (p_context->channels <= 2 && i_codec_id != AV_CODEC_ID_MP2
844                  && i_codec_id != AV_CODEC_ID_MP3) )
845 errmsg:
846         {
847             static const char types[][12] = {
848                 [UNKNOWN_ES] = N_("unknown"), [VIDEO_ES] = N_("video"),
849                 [AUDIO_ES] = N_("audio"), [SPU_ES] = N_("subpicture"),
850             };
851             const char *type = types[0];
852             union
853             {
854                 vlc_fourcc_t value;
855                 char txt[4];
856             } fcc = { .value = p_enc->fmt_out.i_codec };
857
858             if (likely((unsigned)p_enc->fmt_in.i_cat < sizeof (types) / sizeof (types[0])))
859                 type = types[p_enc->fmt_in.i_cat];
860             msg_Err( p_enc, "cannot open %4.4s %s encoder", fcc.txt, type );
861             dialog_Fatal( p_enc, _("Streaming / Transcoding failed"),
862                           _("VLC could not open the %4.4s %s encoder."),
863                           fcc.txt, vlc_gettext(type) );
864             av_dict_free(&options);
865             goto error;
866         }
867
868         if( p_context->channels > 2 )
869         {
870             p_context->channels = 2;
871             p_enc->fmt_in.audio.i_channels = 2; // FIXME
872             msg_Warn( p_enc, "stereo mode selected (codec limitation)" );
873         }
874
875         if( i_codec_id == AV_CODEC_ID_MP2 || i_codec_id == AV_CODEC_ID_MP3 )
876         {
877             int i_frequency, i;
878             es_format_t *fmt = &p_enc->fmt_out;
879
880             for ( i_frequency = 0; i_frequency < 6; i_frequency++ )
881                 if ( fmt->audio.i_rate == mpa_freq_tab[i_frequency] )
882                     break;
883
884             if ( i_frequency == 6 )
885             {
886                 msg_Err( p_enc, "MPEG audio doesn't support frequency=%d",
887                         fmt->audio.i_rate );
888                 av_dict_free(&options);
889                 goto error;
890             }
891
892             for ( i = 1; i < 14; i++ )
893                 if (fmt->i_bitrate/1000 <= mpa_bitrate_tab[i_frequency / 3][i])
894                     break;
895
896             if (fmt->i_bitrate / 1000 != mpa_bitrate_tab[i_frequency / 3][i])
897             {
898                 msg_Warn( p_enc,
899                         "MPEG audio doesn't support bitrate=%d, using %d",
900                         fmt->i_bitrate,
901                         mpa_bitrate_tab[i_frequency / 3][i] * 1000 );
902                 fmt->i_bitrate = mpa_bitrate_tab[i_frequency / 3][i] * 1000;
903                 p_context->bit_rate = fmt->i_bitrate;
904             }
905         }
906
907         p_context->codec = NULL;
908         vlc_avcodec_lock();
909         ret = avcodec_open2( p_context, p_codec, options ? &options : NULL );
910         vlc_avcodec_unlock();
911         if( ret )
912             goto errmsg;
913     }
914
915     av_dict_free(&options);
916
917     if( i_codec_id == AV_CODEC_ID_FLAC )
918     {
919         p_enc->fmt_out.i_extra = 4 + 1 + 3 + p_context->extradata_size;
920         p_enc->fmt_out.p_extra = malloc( p_enc->fmt_out.i_extra );
921         if( p_enc->fmt_out.p_extra )
922         {
923             uint8_t *p = p_enc->fmt_out.p_extra;
924             p[0] = 0x66;    /* f */
925             p[1] = 0x4C;    /* L */
926             p[2] = 0x61;    /* a */
927             p[3] = 0x43;    /* C */
928             p[4] = 0x80;    /* streaminfo block, last block before audio */
929             p[5] = ( p_context->extradata_size >> 16 ) & 0xff;
930             p[6] = ( p_context->extradata_size >>  8 ) & 0xff;
931             p[7] = ( p_context->extradata_size       ) & 0xff;
932             memcpy( &p[8], p_context->extradata, p_context->extradata_size );
933         }
934         else
935         {
936             p_enc->fmt_out.i_extra = 0;
937         }
938     }
939     else
940     {
941         p_enc->fmt_out.i_extra = p_context->extradata_size;
942         if( p_enc->fmt_out.i_extra )
943         {
944             p_enc->fmt_out.p_extra = malloc( p_enc->fmt_out.i_extra );
945             if ( p_enc->fmt_out.p_extra == NULL )
946             {
947                 goto error;
948             }
949             memcpy( p_enc->fmt_out.p_extra, p_context->extradata,
950                     p_enc->fmt_out.i_extra );
951         }
952     }
953
954     p_context->flags &= ~CODEC_FLAG_GLOBAL_HEADER;
955
956     if( p_enc->fmt_in.i_cat == AUDIO_ES )
957     {
958         p_enc->fmt_in.i_codec = GetVlcAudioFormat( p_sys->p_context->sample_fmt );
959         p_enc->fmt_in.audio.i_bitspersample = aout_BitsPerSample( p_enc->fmt_in.i_codec );
960
961         p_sys->i_sample_bytes = (p_enc->fmt_in.audio.i_bitspersample / 8);
962         p_sys->i_frame_size = p_context->frame_size > 1 ?
963                                     p_context->frame_size :
964                                     FF_MIN_BUFFER_SIZE;
965         p_sys->i_buffer_out = av_samples_get_buffer_size(NULL,
966                 p_sys->p_context->channels, p_sys->i_frame_size,
967                 p_sys->p_context->sample_fmt, DEFAULT_ALIGN);
968         p_sys->p_buffer = malloc( p_sys->i_buffer_out );
969         if ( unlikely( p_sys->p_buffer == NULL ) )
970         {
971             goto error;
972         }
973         p_enc->fmt_out.audio.i_frame_length = p_context->frame_size;
974         p_enc->fmt_out.audio.i_blockalign = p_context->block_align;
975         p_enc->fmt_out.audio.i_bitspersample = aout_BitsPerSample( p_enc->fmt_out.i_codec );
976         //b_variable tells if we can feed any size frames to encoder
977         p_sys->b_variable = p_context->frame_size ? false : true;
978
979
980         if( p_sys->b_planar )
981         {
982             p_sys->p_interleave_buf = malloc( p_sys->i_buffer_out );
983             if( unlikely( p_sys->p_interleave_buf == NULL ) )
984                 goto error;
985         }
986     }
987
988     p_sys->frame = avcodec_alloc_frame();
989     if( !p_sys->frame )
990     {
991         goto error;
992     }
993     msg_Dbg( p_enc, "found encoder %s", psz_namecodec );
994     
995     p_enc->pf_encode_video = EncodeVideo;
996     p_enc->pf_encode_audio = EncodeAudio;
997
998
999     return VLC_SUCCESS;
1000 error:
1001     free( p_enc->fmt_out.p_extra );
1002     free( p_sys->p_buffer );
1003     free( p_sys->p_interleave_buf );
1004     free( p_sys );
1005     return VLC_ENOMEM;
1006 }
1007
1008 /****************************************************************************
1009  * EncodeVideo: the whole thing
1010  ****************************************************************************/
1011 static block_t *EncodeVideo( encoder_t *p_enc, picture_t *p_pict )
1012 {
1013     encoder_sys_t *p_sys = p_enc->p_sys;
1014     int i_plane;
1015     /* Initialize the video output buffer the first time.
1016      * This is done here instead of OpenEncoder() because we need the actual
1017      * bits_per_pixel value, without having to assume anything.
1018      */
1019     const int bytesPerPixel = p_enc->fmt_out.video.i_bits_per_pixel ?
1020                          p_enc->fmt_out.video.i_bits_per_pixel / 8 : 3;
1021     const int blocksize = __MAX( FF_MIN_BUFFER_SIZE,bytesPerPixel * p_sys->p_context->height * p_sys->p_context->width + 200 );
1022     block_t *p_block = block_Alloc( blocksize );
1023     if( unlikely(p_block == NULL) )
1024         return NULL;
1025
1026     AVFrame *frame = NULL;
1027     if( likely(p_pict) ) {
1028         frame = p_sys->frame;
1029         avcodec_get_frame_defaults( frame );
1030         for( i_plane = 0; i_plane < p_pict->i_planes; i_plane++ )
1031         {
1032             p_sys->frame->data[i_plane] = p_pict->p[i_plane].p_pixels;
1033             p_sys->frame->linesize[i_plane] = p_pict->p[i_plane].i_pitch;
1034         }
1035
1036         /* Let libavcodec select the frame type */
1037         frame->pict_type = 0;
1038
1039         frame->repeat_pict = p_pict->i_nb_fields - 2;
1040         frame->interlaced_frame = !p_pict->b_progressive;
1041         frame->top_field_first = !!p_pict->b_top_field_first;
1042
1043         /* Set the pts of the frame being encoded */
1044         frame->pts = p_pict->date ? p_pict->date : AV_NOPTS_VALUE;
1045
1046         if ( p_sys->b_hurry_up && frame->pts != AV_NOPTS_VALUE )
1047         {
1048             mtime_t current_date = mdate();
1049
1050             if ( current_date + HURRY_UP_GUARD3 > frame->pts )
1051             {
1052                 p_sys->p_context->mb_decision = FF_MB_DECISION_SIMPLE;
1053                 p_sys->p_context->trellis = 0;
1054                 msg_Dbg( p_enc, "hurry up mode 3" );
1055             }
1056             else
1057             {
1058                 p_sys->p_context->mb_decision = p_sys->i_hq;
1059
1060                 if ( current_date + HURRY_UP_GUARD2 > frame->pts )
1061                 {
1062                     p_sys->p_context->trellis = 0;
1063                     p_sys->p_context->noise_reduction = p_sys->i_noise_reduction
1064                         + (HURRY_UP_GUARD2 + current_date - frame->pts) / 500;
1065                     msg_Dbg( p_enc, "hurry up mode 2" );
1066                 }
1067                 else
1068                 {
1069                     p_sys->p_context->trellis = p_sys->b_trellis;
1070
1071                     p_sys->p_context->noise_reduction =
1072                        p_sys->i_noise_reduction;
1073                 }
1074             }
1075
1076             if ( current_date + HURRY_UP_GUARD1 > frame->pts )
1077             {
1078                 frame->pict_type = AV_PICTURE_TYPE_P;
1079                 /* msg_Dbg( p_enc, "hurry up mode 1 %lld", current_date + HURRY_UP_GUARD1 - frame.pts ); */
1080             }
1081         }
1082
1083         if ( frame->pts != AV_NOPTS_VALUE && frame->pts != 0 )
1084         {
1085             if ( p_sys->i_last_pts == frame->pts )
1086             {
1087                 msg_Warn( p_enc, "almost fed libavcodec with two frames with "
1088                           "the same PTS (%"PRId64 ")", frame->pts );
1089                 return NULL;
1090             }
1091             else if ( p_sys->i_last_pts > frame->pts )
1092             {
1093                 msg_Warn( p_enc, "almost fed libavcodec with a frame in the "
1094                          "past (current: %"PRId64 ", last: %"PRId64")",
1095                          frame->pts, p_sys->i_last_pts );
1096                 return NULL;
1097             }
1098             else
1099                 p_sys->i_last_pts = frame->pts;
1100         }
1101
1102         frame->quality = p_sys->i_quality;
1103     }
1104
1105 #if (LIBAVCODEC_VERSION_MAJOR >= 54)
1106     AVPacket av_pkt;
1107     int is_data;
1108
1109     av_init_packet( &av_pkt );
1110     av_pkt.data = p_block->p_buffer;
1111     av_pkt.size = p_block->i_buffer;
1112
1113     if( avcodec_encode_video2( p_sys->p_context, &av_pkt, frame, &is_data ) < 0
1114      || is_data == 0 )
1115     {
1116         block_Release( p_block );
1117         return NULL;
1118     }
1119
1120     p_block->i_buffer = av_pkt.size;
1121     p_block->i_length = av_pkt.duration / p_sys->p_context->time_base.den;
1122     p_block->i_pts = av_pkt.pts;
1123     p_block->i_dts = av_pkt.dts;
1124     if( unlikely( av_pkt.flags & AV_PKT_FLAG_CORRUPT ) )
1125         p_block->i_flags |= BLOCK_FLAG_CORRUPTED;
1126
1127 #else
1128     int i_out = avcodec_encode_video( p_sys->p_context, p_block->p_buffer,
1129                                       p_block->i_buffer, frame );
1130     if( i_out <= 0 )
1131     {
1132         block_Release( p_block );
1133         return NULL;
1134     }
1135
1136     p_block->i_buffer = i_out;
1137
1138     /* FIXME, 3-2 pulldown is not handled correctly */
1139     p_block->i_length = INT64_C(1000000) *
1140         p_enc->fmt_in.video.i_frame_rate_base /
1141             p_enc->fmt_in.video.i_frame_rate;
1142
1143     if( !p_sys->p_context->max_b_frames || !p_sys->p_context->delay )
1144     {
1145         /* No delay -> output pts == input pts */
1146         if( p_pict )
1147             p_block->i_dts = p_pict->date;
1148         p_block->i_pts = p_block->i_dts;
1149     }
1150     else if( p_sys->p_context->coded_frame->pts != AV_NOPTS_VALUE &&
1151         p_sys->p_context->coded_frame->pts != 0 &&
1152         p_sys->i_buggy_pts_detect != p_sys->p_context->coded_frame->pts )
1153     {
1154         p_sys->i_buggy_pts_detect = p_sys->p_context->coded_frame->pts;
1155         p_block->i_pts = p_sys->p_context->coded_frame->pts;
1156
1157         if( p_sys->p_context->coded_frame->pict_type != AV_PICTURE_TYPE_I &&
1158             p_sys->p_context->coded_frame->pict_type != AV_PICTURE_TYPE_P )
1159         {
1160             p_block->i_dts = p_block->i_pts;
1161         }
1162         else
1163         {
1164             if( p_sys->i_last_ref_pts )
1165             {
1166                 p_block->i_dts = p_sys->i_last_ref_pts;
1167             }
1168             else
1169             {
1170                 /* Let's put something sensible */
1171                 p_block->i_dts = p_block->i_pts;
1172             }
1173
1174             p_sys->i_last_ref_pts = p_block->i_pts;
1175         }
1176     }
1177     else if( p_pict )
1178     {
1179         /* Buggy libavcodec which doesn't update coded_frame->pts
1180          * correctly */
1181         p_block->i_dts = p_block->i_pts = p_pict->date;
1182     }
1183 #endif
1184
1185     switch ( p_sys->p_context->coded_frame->pict_type )
1186     {
1187     case AV_PICTURE_TYPE_I:
1188     case AV_PICTURE_TYPE_SI:
1189         p_block->i_flags |= BLOCK_FLAG_TYPE_I;
1190         break;
1191     case AV_PICTURE_TYPE_P:
1192     case AV_PICTURE_TYPE_SP:
1193         p_block->i_flags |= BLOCK_FLAG_TYPE_P;
1194         break;
1195     case AV_PICTURE_TYPE_B:
1196     case AV_PICTURE_TYPE_BI:
1197         p_block->i_flags |= BLOCK_FLAG_TYPE_B;
1198         break;
1199     default:
1200         p_block->i_flags |= BLOCK_FLAG_TYPE_PB;
1201     }
1202
1203     return p_block;
1204 }
1205
1206 static block_t *encode_audio_buffer( encoder_t *p_enc, encoder_sys_t *p_sys,  AVFrame *frame )
1207 {
1208     int got_packet, i_out;
1209     got_packet=i_out=0;
1210     AVPacket packet = {0};
1211     block_t *p_block = block_Alloc( p_sys->i_buffer_out );
1212     av_init_packet( &packet );
1213     packet.data = p_block->p_buffer;
1214     packet.size = p_block->i_buffer;
1215
1216     i_out = avcodec_encode_audio2( p_sys->p_context, &packet, frame, &got_packet );
1217     if( unlikely( !got_packet || ( i_out < 0 ) ) )
1218     {
1219         if( i_out < 0 )
1220         {
1221             msg_Err( p_enc,"Encoding problem..");
1222         }
1223         block_Release( p_block );
1224         return NULL;
1225     }
1226     p_block->i_buffer = packet.size;
1227
1228     p_block->i_length = (mtime_t)1000000 *
1229      (mtime_t)p_sys->i_frame_size /
1230      (mtime_t)p_sys->p_context->sample_rate;
1231
1232     if( likely( packet.pts != AV_NOPTS_VALUE ) )
1233         p_block->i_dts = p_block->i_pts = packet.pts;
1234     else
1235         p_block->i_dts = p_block->i_pts = VLC_TS_INVALID;
1236     return p_block;
1237 }
1238
1239 static block_t *handle_delay_buffer( encoder_t *p_enc, encoder_sys_t *p_sys, int buffer_delay, block_t *p_aout_buf, int leftover_samples )
1240 {
1241     block_t *p_block = NULL;
1242     //How much we need to copy from new packet
1243     const int leftover = leftover_samples * p_sys->p_context->channels * p_sys->i_sample_bytes;
1244
1245     avcodec_get_frame_defaults( p_sys->frame );
1246     p_sys->frame->format     = p_sys->p_context->sample_fmt;
1247     p_sys->frame->nb_samples = leftover_samples + p_sys->i_samples_delay;
1248
1249
1250     p_sys->frame->pts        = date_Get( &p_sys->buffer_date );
1251
1252     if( likely( p_sys->frame->pts != AV_NOPTS_VALUE) )
1253         date_Increment( &p_sys->buffer_date, p_sys->frame->nb_samples );
1254
1255     if( likely( p_aout_buf ) )
1256     {
1257
1258         p_aout_buf->i_nb_samples -= leftover_samples;
1259         memcpy( p_sys->p_buffer+buffer_delay, p_aout_buf->p_buffer, leftover );
1260
1261         // We need to deinterleave from p_aout_buf to p_buffer the leftover bytes
1262         if( p_sys->b_planar )
1263             aout_Deinterleave( p_sys->p_interleave_buf, p_sys->p_buffer,
1264                 p_sys->i_frame_size, p_sys->p_context->channels, p_enc->fmt_in.i_codec );
1265         else
1266             memcpy( p_sys->p_buffer + buffer_delay, p_aout_buf->p_buffer, leftover);
1267
1268         p_aout_buf->p_buffer     += leftover;
1269         p_aout_buf->i_buffer     -= leftover;
1270         if( likely( p_sys->frame->pts != AV_NOPTS_VALUE) )
1271             p_aout_buf->i_pts         = date_Get( &p_sys->buffer_date );
1272     }
1273
1274     if(unlikely( ( (leftover + buffer_delay) < p_sys->i_buffer_out ) &&
1275                  !(p_sys->p_codec->capabilities & CODEC_CAP_SMALL_LAST_FRAME )))
1276     {
1277         msg_Dbg( p_enc, "No small last frame support, padding");
1278         size_t padding_size = p_sys->i_buffer_out - (leftover+buffer_delay);
1279         memset( p_sys->p_buffer + (leftover+buffer_delay), 0, padding_size );
1280         buffer_delay += padding_size;
1281     }
1282     if( avcodec_fill_audio_frame( p_sys->frame, p_sys->p_context->channels,
1283             p_sys->p_context->sample_fmt, p_sys->b_planar ? p_sys->p_interleave_buf : p_sys->p_buffer,
1284             p_sys->i_buffer_out,
1285             DEFAULT_ALIGN) < 0 )
1286     {
1287         msg_Err( p_enc, "filling error on fillup" );
1288         p_sys->frame->nb_samples = 0;
1289     }
1290
1291
1292     p_sys->i_samples_delay = 0;
1293
1294     p_block = encode_audio_buffer( p_enc, p_sys, p_sys->frame );
1295
1296     return p_block;
1297 }
1298
1299 /****************************************************************************
1300  * EncodeAudio: the whole thing
1301  ****************************************************************************/
1302 static block_t *EncodeAudio( encoder_t *p_enc, block_t *p_aout_buf )
1303 {
1304     encoder_sys_t *p_sys = p_enc->p_sys;
1305
1306     block_t *p_block, *p_chain = NULL;
1307     size_t buffer_delay = 0, i_samples_left = 0;
1308
1309
1310     //i_bytes_left is amount of bytes we get
1311     i_samples_left = p_aout_buf ? p_aout_buf->i_nb_samples : 0;
1312     buffer_delay = p_sys->i_samples_delay * p_sys->i_sample_bytes * p_sys->p_context->channels;
1313
1314     //p_sys->i_buffer_out = p_sys->i_frame_size * chan * p_sys->i_sample_bytes
1315     //Calculate how many bytes we would need from current buffer to fill frame
1316     size_t leftover_samples = __MAX(0,__MIN((ssize_t)i_samples_left, (ssize_t)(p_sys->i_frame_size - p_sys->i_samples_delay)));
1317
1318     if( p_aout_buf && ( p_aout_buf->i_pts > VLC_TS_INVALID ) )
1319     {
1320         date_Set( &p_sys->buffer_date, p_aout_buf->i_pts );
1321         /* take back amount we have leftover from previous buffer*/
1322         if( p_sys->i_samples_delay > 0 )
1323             date_Decrement( &p_sys->buffer_date, p_sys->i_samples_delay );
1324     }
1325     /* Handle reordering here so we have p_sys->p_buffer always in correct
1326      * order already */
1327     if( p_aout_buf && p_sys->i_channels_to_reorder > 0 )
1328     {
1329         aout_ChannelReorder( p_aout_buf->p_buffer, p_aout_buf->i_buffer,
1330              p_sys->i_channels_to_reorder, p_sys->pi_reorder_layout,
1331              p_enc->fmt_in.i_codec );
1332     }
1333
1334     // Check if we have enough samples in delay_buffer and current p_aout_buf to fill frame
1335     // Or if we are cleaning up
1336     if( ( buffer_delay > 0 ) &&
1337             ( ( p_aout_buf && ( leftover_samples <= p_aout_buf->i_nb_samples ) &&
1338                ( (leftover_samples + p_sys->i_samples_delay ) >= p_sys->i_frame_size )
1339               ) ||
1340              ( !p_aout_buf )
1341             )
1342          )
1343     {
1344         p_chain = handle_delay_buffer( p_enc, p_sys, buffer_delay, p_aout_buf, leftover_samples );
1345         buffer_delay = 0;
1346         if( unlikely( !p_chain ) )
1347             return NULL;
1348     }
1349
1350     if( unlikely( !p_aout_buf ) )
1351     {
1352         msg_Dbg(p_enc,"Flushing..");
1353         do {
1354             p_block = encode_audio_buffer( p_enc, p_sys, NULL );
1355             if( likely( p_block ) )
1356             {
1357                 block_ChainAppend( &p_chain, p_block );
1358             }
1359         } while( p_block );
1360         return p_chain;
1361     }
1362
1363
1364     while( ( p_aout_buf->i_nb_samples >= p_sys->i_frame_size ) ||
1365            ( p_sys->b_variable && p_aout_buf->i_nb_samples ) )
1366     {
1367         avcodec_get_frame_defaults( p_sys->frame );
1368         if( p_sys->b_variable )
1369             p_sys->frame->nb_samples = p_aout_buf->i_nb_samples;
1370         else
1371             p_sys->frame->nb_samples = p_sys->i_frame_size;
1372         p_sys->frame->format     = p_sys->p_context->sample_fmt;
1373         p_sys->frame->pts        = date_Get( &p_sys->buffer_date );
1374
1375         const int in_bytes = p_sys->frame->nb_samples *
1376             p_sys->p_context->channels * p_sys->i_sample_bytes;
1377
1378         if( p_sys->b_planar )
1379         {
1380             aout_Deinterleave( p_sys->p_buffer, p_aout_buf->p_buffer,
1381                                p_sys->frame->nb_samples, p_sys->p_context->channels, p_enc->fmt_in.i_codec );
1382
1383         }
1384         else
1385         {
1386             memcpy(p_sys->p_buffer, p_aout_buf->p_buffer, in_bytes);
1387         }
1388
1389         if( avcodec_fill_audio_frame( p_sys->frame, p_sys->p_context->channels,
1390                                     p_sys->p_context->sample_fmt,
1391                                     p_sys->p_buffer,
1392                                     p_sys->i_buffer_out,
1393                                     DEFAULT_ALIGN) < 0 )
1394         {
1395                  msg_Err( p_enc, "filling error on encode" );
1396                  p_sys->frame->nb_samples = 0;
1397         }
1398
1399         p_aout_buf->p_buffer     += in_bytes;
1400         p_aout_buf->i_buffer     -= in_bytes;
1401         p_aout_buf->i_nb_samples -= p_sys->frame->nb_samples;
1402         if( likely( p_sys->frame->pts != AV_NOPTS_VALUE) )
1403             date_Increment( &p_sys->buffer_date, p_sys->frame->nb_samples );
1404
1405         p_block = encode_audio_buffer( p_enc, p_sys, p_sys->frame );
1406         if( likely( p_block ) )
1407             block_ChainAppend( &p_chain, p_block );
1408     }
1409
1410     // We have leftover samples that don't fill frame_size, and libavcodec doesn't seem to like
1411     // that frame has more data than p_sys->i_frame_size most of the cases currently.
1412     if( p_aout_buf->i_nb_samples > 0 )
1413     {
1414        memcpy( p_sys->p_buffer + buffer_delay, p_aout_buf->p_buffer,
1415                p_aout_buf->i_nb_samples * p_sys->i_sample_bytes * p_sys->p_context->channels);
1416        p_sys->i_samples_delay += p_aout_buf->i_nb_samples;
1417     }
1418
1419     return p_chain;
1420 }
1421
1422 /*****************************************************************************
1423  * CloseEncoder: libavcodec encoder destruction
1424  *****************************************************************************/
1425 void CloseEncoder( vlc_object_t *p_this )
1426 {
1427     encoder_t *p_enc = (encoder_t *)p_this;
1428     encoder_sys_t *p_sys = p_enc->p_sys;
1429
1430     /*FIXME: we should use avcodec_free_frame, but we don't require so new avcodec that has it*/
1431     av_freep( &p_sys->frame );
1432
1433     vlc_avcodec_lock();
1434     avcodec_close( p_sys->p_context );
1435     vlc_avcodec_unlock();
1436     av_free( p_sys->p_context );
1437
1438
1439     free( p_sys->p_interleave_buf );
1440     free( p_sys->p_buffer );
1441
1442     free( p_sys );
1443 }