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