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