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