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