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