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