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