]> git.sesse.net Git - vlc/blob - modules/codec/avcodec/encoder.c
Increase avcodec encoding output buffer size
[vlc] / modules / codec / avcodec / encoder.c
1 /*****************************************************************************
2  * encoder.c: video and audio encoder using the ffmpeg 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 /* ffmpeg header */
44 #define HAVE_MMX 1
45 #ifdef HAVE_LIBAVCODEC_AVCODEC_H
46 #   include <libavcodec/avcodec.h>
47 #elif defined(HAVE_FFMPEG_AVCODEC_H)
48 #   include <ffmpeg/avcodec.h>
49 #else
50 #   include <avcodec.h>
51 #endif
52
53 #include "avcodec.h"
54
55 #define HURRY_UP_GUARD1 (450000)
56 #define HURRY_UP_GUARD2 (300000)
57 #define HURRY_UP_GUARD3 (100000)
58
59 #define MAX_FRAME_DELAY (FF_MAX_B_FRAMES + 2)
60
61 /*****************************************************************************
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 *, aout_buffer_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 : ffmpeg encoder descriptor
91  *****************************************************************************/
92 struct encoder_sys_t
93 {
94     /*
95      * Ffmpeg properties
96      */
97     AVCodec         *p_codec;
98     AVCodecContext  *p_context;
99
100     /*
101      * Common properties
102      */
103     char *p_buffer;
104     uint8_t *p_buffer_out;
105     size_t i_buffer_out;
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     int i_frame_size;
119     int i_samples_delay;
120     mtime_t i_pts;
121
122     /* Encoding settings */
123     int        i_key_int;
124     int        i_b_frames;
125     int        i_vtolerance;
126     int        i_qmin;
127     int        i_qmax;
128     int        i_hq;
129     int        i_rc_buffer_size;
130     float      f_rc_buffer_aggressivity;
131     bool       b_pre_me;
132     bool       b_hurry_up;
133     bool       b_interlace, b_interlace_me;
134     float      f_i_quant_factor;
135     int        i_noise_reduction;
136     bool       b_mpeg4_matrix;
137     bool       b_trellis;
138     int        i_quality; /* for VBR */
139     float      f_lumi_masking, f_dark_masking, f_p_masking, f_border_masking;
140     int        i_luma_elim, i_chroma_elim;
141     int        i_aac_profile; /* AAC profile to use.*/
142     /* Used to work around stupid timestamping behaviour in libavcodec */
143     uint64_t i_framenum;
144     mtime_t  pi_delay_pts[MAX_FRAME_DELAY];
145 };
146
147 static const char *const ppsz_enc_options[] = {
148     "keyint", "bframes", "vt", "qmin", "qmax", "hq",
149     "rc-buffer-size", "rc-buffer-aggressivity", "pre-me", "hurry-up",
150     "interlace", "interlace-me", "i-quant-factor", "noise-reduction", "mpeg4-matrix",
151     "trellis", "qscale", "strict", "lumi-masking", "dark-masking",
152     "p-masking", "border-masking", "luma-elim-threshold",
153     "chroma-elim-threshold",
154      "aac-profile",
155      NULL
156 };
157
158 static const uint16_t mpa_bitrate_tab[2][15] =
159 {
160     {0, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384},
161     {0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160}
162 };
163
164 static const uint16_t mpa_freq_tab[6] =
165 { 44100, 48000, 32000, 22050, 24000, 16000 };
166
167 static const uint16_t mpeg4_default_intra_matrix[64] = {
168   8, 17, 18, 19, 21, 23, 25, 27,
169  17, 18, 19, 21, 23, 25, 27, 28,
170  20, 21, 22, 23, 24, 26, 28, 30,
171  21, 22, 23, 24, 26, 28, 30, 32,
172  22, 23, 24, 26, 28, 30, 32, 35,
173  23, 24, 26, 28, 30, 32, 35, 38,
174  25, 26, 28, 30, 32, 35, 38, 41,
175  27, 28, 30, 32, 35, 38, 41, 45,
176 };
177
178 static const uint16_t mpeg4_default_non_intra_matrix[64] = {
179  16, 17, 18, 19, 20, 21, 22, 23,
180  17, 18, 19, 20, 21, 22, 23, 24,
181  18, 19, 20, 21, 22, 23, 24, 25,
182  19, 20, 21, 22, 23, 24, 26, 27,
183  20, 21, 22, 23, 25, 26, 27, 28,
184  21, 22, 23, 24, 26, 27, 28, 30,
185  22, 23, 24, 26, 27, 28, 30, 31,
186  23, 24, 25, 27, 28, 30, 31, 33,
187 };
188
189 /*****************************************************************************
190  * OpenEncoder: probe the encoder
191  *****************************************************************************/
192
193 int OpenEncoder( vlc_object_t *p_this )
194 {
195     encoder_t *p_enc = (encoder_t *)p_this;
196     encoder_sys_t *p_sys;
197     AVCodecContext *p_context;
198     AVCodec *p_codec;
199     int i_codec_id, i_cat;
200     const char *psz_namecodec;
201     float f_val;
202     char *psz_val;
203     int i_val;
204
205     if( !GetFfmpegCodec( p_enc->fmt_out.i_codec, &i_cat, &i_codec_id,
206                              &psz_namecodec ) )
207     {
208         if( TestFfmpegChroma( -1, p_enc->fmt_out.i_codec ) != VLC_SUCCESS )
209         {
210             /* handed chroma output */
211             return VLC_EGENERIC;
212         }
213         i_cat      = VIDEO_ES;
214         i_codec_id = CODEC_ID_RAWVIDEO;
215         psz_namecodec = "Raw video";
216     }
217
218     if( p_enc->fmt_out.i_cat == VIDEO_ES && i_cat != VIDEO_ES )
219     {
220         msg_Err( p_enc, "\"%s\" is not a video encoder", psz_namecodec );
221         dialog_Fatal( p_enc, _("Streaming / Transcoding failed"),
222                         _("\"%s\" is no video encoder."), psz_namecodec );
223         return VLC_EGENERIC;
224     }
225
226     if( p_enc->fmt_out.i_cat == AUDIO_ES && i_cat != AUDIO_ES )
227     {
228         msg_Err( p_enc, "\"%s\" is not an audio encoder", psz_namecodec );
229         dialog_Fatal( p_enc, _("Streaming / Transcoding failed"),
230                         _("\"%s\" is no audio encoder."), psz_namecodec );
231         return VLC_EGENERIC;
232     }
233
234     if( p_enc->fmt_out.i_cat == SPU_ES )
235     {
236         /* We don't support subtitle encoding */
237         return VLC_EGENERIC;
238     }
239
240     /* Initialization must be done before avcodec_find_encoder() */
241     InitLibavcodec( p_this );
242
243     p_codec = avcodec_find_encoder( i_codec_id );
244     if( !p_codec )
245     {
246         msg_Err( p_enc, "cannot find encoder %s\n"
247 "*** Your FFMPEG installation is crippled.   ***\n"
248 "*** Please check with your FFMPEG packager. ***\n"
249 "*** This is NOT a VLC media player issue.   ***", psz_namecodec );
250
251         dialog_Fatal( p_enc, _("Streaming / Transcoding failed"), _(
252 /* I have had enough of all these MPEG-3 transcoding bug reports.
253  * Downstream packager, you had better not patch this out, or I will be really
254  * annoyed. Think about it - you don't want to fork the VLC translation files,
255  * do you? -- Courmisch, 2008-10-22 */
256 "It seems your FFMPEG (libavcodec) installation lacks the following encoder:\n"
257 "%s.\n"
258 "If you don't know how to fix this, ask for support from your distribution.\n"
259 "\n"
260 "This is not an error inside VLC media player.\n"
261 "Do not contact the VideoLAN project about this issue.\n"),
262             psz_namecodec );
263         return VLC_EGENERIC;
264     }
265
266     /* Allocate the memory needed to store the encoder's structure */
267     if( ( p_sys = calloc( 1, sizeof(encoder_sys_t) ) ) == NULL )
268         return VLC_ENOMEM;
269     p_enc->p_sys = p_sys;
270     p_sys->p_codec = p_codec;
271
272     p_enc->pf_encode_video = EncodeVideo;
273     p_enc->pf_encode_audio = EncodeAudio;
274
275     p_sys->p_buffer = NULL;
276     p_sys->p_buffer_out = NULL;
277     p_sys->i_buffer_out = 0;
278
279     p_sys->p_context = p_context = avcodec_alloc_context();
280     p_sys->p_context->codec_id = p_sys->p_codec->id;
281     p_context->debug = config_GetInt( p_enc, "ffmpeg-debug" );
282     p_context->opaque = (void *)p_this;
283
284     /* Set CPU capabilities */
285     unsigned i_cpu = vlc_CPU();
286     p_context->dsp_mask = 0;
287     if( !(i_cpu & CPU_CAPABILITY_MMX) )
288     {
289         p_context->dsp_mask |= FF_MM_MMX;
290     }
291     if( !(i_cpu & CPU_CAPABILITY_MMXEXT) )
292     {
293         p_context->dsp_mask |= FF_MM_MMXEXT;
294     }
295     if( !(i_cpu & CPU_CAPABILITY_3DNOW) )
296     {
297         p_context->dsp_mask |= FF_MM_3DNOW;
298     }
299     if( !(i_cpu & CPU_CAPABILITY_SSE) )
300     {
301         p_context->dsp_mask |= FF_MM_SSE;
302         p_context->dsp_mask |= FF_MM_SSE2;
303     }
304
305     config_ChainParse( p_enc, ENC_CFG_PREFIX, ppsz_enc_options, p_enc->p_cfg );
306
307     p_sys->i_key_int = var_GetInteger( p_enc, ENC_CFG_PREFIX "keyint" );
308     p_sys->i_b_frames = var_GetInteger( p_enc, ENC_CFG_PREFIX "bframes" );
309     p_sys->i_vtolerance = var_GetInteger( p_enc, ENC_CFG_PREFIX "vt" ) * 1000;
310     p_sys->b_interlace = var_GetBool( p_enc, ENC_CFG_PREFIX "interlace" );
311     p_sys->b_interlace_me = var_GetBool( p_enc, ENC_CFG_PREFIX "interlace-me" );
312     p_sys->b_pre_me = var_GetBool( p_enc, ENC_CFG_PREFIX "pre-me" );
313     p_sys->b_hurry_up = var_GetBool( p_enc, ENC_CFG_PREFIX "hurry-up" );
314
315     if( p_sys->b_hurry_up )
316     {
317         /* hurry up mode needs noise reduction, even small */
318         p_sys->i_noise_reduction = 1;
319     }
320
321     p_sys->i_rc_buffer_size = var_GetInteger( p_enc, ENC_CFG_PREFIX "rc-buffer-size" );
322     p_sys->f_rc_buffer_aggressivity = var_GetFloat( p_enc, ENC_CFG_PREFIX "rc-buffer-aggressivity" );
323     p_sys->f_i_quant_factor = var_GetFloat( p_enc, ENC_CFG_PREFIX "i-quant-factor" );
324     p_sys->i_noise_reduction = var_GetInteger( p_enc, ENC_CFG_PREFIX "noise-reduction" );
325     p_sys->b_mpeg4_matrix = var_GetBool( p_enc, ENC_CFG_PREFIX "mpeg4-matrix" );
326
327     f_val = var_GetFloat( p_enc, ENC_CFG_PREFIX "qscale" );
328     if( f_val < 0.01 || f_val > 255.0 ) f_val = 0;
329     p_sys->i_quality = (int)(FF_QP2LAMBDA * f_val + 0.5);
330
331     psz_val = var_GetString( p_enc, ENC_CFG_PREFIX "hq" );
332     p_sys->i_hq = FF_MB_DECISION_RD;
333     if( psz_val && *psz_val )
334     {
335         if( !strcmp( psz_val, "rd" ) )
336             p_sys->i_hq = FF_MB_DECISION_RD;
337         else if( !strcmp( psz_val, "bits" ) )
338             p_sys->i_hq = FF_MB_DECISION_BITS;
339         else if( !strcmp( psz_val, "simple" ) )
340             p_sys->i_hq = FF_MB_DECISION_SIMPLE;
341         else
342             p_sys->i_hq = FF_MB_DECISION_RD;
343     }
344     else
345         p_sys->i_hq = FF_MB_DECISION_RD;
346     free( psz_val );
347
348     p_sys->i_qmin = var_GetInteger( p_enc, ENC_CFG_PREFIX "qmin" );
349     p_sys->i_qmax = var_GetInteger( p_enc, ENC_CFG_PREFIX "qmax" );
350     p_sys->b_trellis = var_GetBool( p_enc, ENC_CFG_PREFIX "trellis" );
351
352     i_val = var_GetInteger( p_enc, ENC_CFG_PREFIX "strict" );
353     if( i_val < - 1 || i_val > 1 ) i_val = 0;
354     p_context->strict_std_compliance = i_val;
355
356     p_sys->f_lumi_masking = var_GetFloat( p_enc, ENC_CFG_PREFIX "lumi-masking" );
357     p_sys->f_dark_masking = var_GetFloat( p_enc, ENC_CFG_PREFIX "dark-masking" );
358     p_sys->f_p_masking = var_GetFloat( p_enc, ENC_CFG_PREFIX "p-masking" );
359     p_sys->f_border_masking = var_GetFloat( p_enc, ENC_CFG_PREFIX "border-masking" );
360     p_sys->i_luma_elim = var_GetInteger( p_enc, ENC_CFG_PREFIX "luma-elim-threshold" );
361     p_sys->i_chroma_elim = var_GetInteger( p_enc, ENC_CFG_PREFIX "chroma-elim-threshold" );
362
363     psz_val = var_GetString( p_enc, ENC_CFG_PREFIX "aac-profile" );
364     /* ffmpeg uses faac encoder atm, and it has issues with
365      * other than low-complexity profile, so default to that */
366     p_sys->i_aac_profile = FF_PROFILE_AAC_LOW;
367     if( psz_val && *psz_val )
368     {
369         if( !strncmp( psz_val, "main", 4 ) )
370             p_sys->i_aac_profile = FF_PROFILE_AAC_MAIN;
371         else if( !strncmp( psz_val, "low", 3 ) )
372             p_sys->i_aac_profile = FF_PROFILE_AAC_LOW;
373 #if 0    /* Not supported by FAAC encoder */
374         else if( !strncmp( psz_val, "ssr", 3 ) )
375             p_sys->i_aac_profile = FF_PROFILE_AAC_SSR;
376 #endif
377         else  if( !strncmp( psz_val, "ltp", 3 ) )
378             p_sys->i_aac_profile = FF_PROFILE_AAC_LTP;
379         else
380         {
381             msg_Warn( p_enc, "unknown AAC profile requested, setting it to low" );
382             p_sys->i_aac_profile = FF_PROFILE_AAC_LOW;
383         }
384     }
385     free( psz_val );
386
387     if( p_enc->fmt_in.i_cat == VIDEO_ES )
388     {
389         if( !p_enc->fmt_in.video.i_width || !p_enc->fmt_in.video.i_height )
390         {
391             msg_Warn( p_enc, "invalid size %ix%i", p_enc->fmt_in.video.i_width,
392                       p_enc->fmt_in.video.i_height );
393             free( p_sys );
394             return VLC_EGENERIC;
395         }
396
397         p_context->codec_type = CODEC_TYPE_VIDEO;
398
399         p_context->width = p_enc->fmt_in.video.i_width;
400         p_context->height = p_enc->fmt_in.video.i_height;
401
402         p_context->time_base.num = p_enc->fmt_in.video.i_frame_rate_base;
403         p_context->time_base.den = p_enc->fmt_in.video.i_frame_rate;
404
405         /* Defaults from ffmpeg.c */
406         p_context->qblur = 0.5;
407         p_context->qcompress = 0.5;
408         p_context->b_quant_offset = 1.25;
409         p_context->b_quant_factor = 1.25;
410         p_context->i_quant_offset = 0.0;
411         p_context->i_quant_factor = -0.8;
412
413         p_context->lumi_masking = p_sys->f_lumi_masking;
414         p_context->dark_masking = p_sys->f_dark_masking;
415         p_context->p_masking = p_sys->f_p_masking;
416         p_context->border_masking = p_sys->f_border_masking;
417         p_context->luma_elim_threshold = p_sys->i_luma_elim;
418         p_context->chroma_elim_threshold = p_sys->i_chroma_elim;
419
420         if( p_sys->i_key_int > 0 )
421             p_context->gop_size = p_sys->i_key_int;
422         p_context->max_b_frames =
423             __MAX( __MIN( p_sys->i_b_frames, FF_MAX_B_FRAMES ), 0 );
424         p_context->b_frame_strategy = 0;
425         if( !p_context->max_b_frames  &&
426             (  p_enc->fmt_out.i_codec == VLC_CODEC_MPGV ||
427                p_enc->fmt_out.i_codec == VLC_CODEC_MP2V ||
428                p_enc->fmt_out.i_codec == VLC_CODEC_MP1V ) )
429             p_context->flags |= CODEC_FLAG_LOW_DELAY;
430
431         av_reduce( &p_context->sample_aspect_ratio.num,
432                    &p_context->sample_aspect_ratio.den,
433                    p_enc->fmt_in.video.i_sar_num,
434                    p_enc->fmt_in.video.i_sar_den, 1 << 30 );
435
436         p_sys->i_buffer_out = p_context->height * p_context->width
437             * 3     /* Assume 24bpp maximum */
438             + 200;  /* some room for potential headers (such as BMP) */
439
440         if( p_sys->i_buffer_out < FF_MIN_BUFFER_SIZE )
441             p_sys->i_buffer_out = FF_MIN_BUFFER_SIZE;
442         p_sys->p_buffer_out = malloc( p_sys->i_buffer_out );
443
444         p_enc->fmt_in.i_codec = VLC_CODEC_I420;
445         p_enc->fmt_in.video.i_chroma = p_enc->fmt_in.i_codec;
446         GetFfmpegChroma( &p_context->pix_fmt, p_enc->fmt_in.video );
447
448         if( p_codec->pix_fmts )
449         {
450             const enum PixelFormat *p = p_codec->pix_fmts;
451             for( ; *p != -1; p++ )
452             {
453                 if( *p == p_context->pix_fmt ) break;
454             }
455             if( *p == -1 ) p_context->pix_fmt = p_codec->pix_fmts[0];
456             GetVlcChroma( &p_enc->fmt_in.video, p_context->pix_fmt );
457             p_enc->fmt_in.i_codec = p_enc->fmt_in.video.i_chroma;
458         }
459
460
461         if ( p_sys->f_i_quant_factor != 0.0 )
462             p_context->i_quant_factor = p_sys->f_i_quant_factor;
463
464         p_context->noise_reduction = p_sys->i_noise_reduction;
465
466         if ( p_sys->b_mpeg4_matrix )
467         {
468             p_context->intra_matrix = mpeg4_default_intra_matrix;
469             p_context->inter_matrix = mpeg4_default_non_intra_matrix;
470         }
471
472         if ( p_sys->b_pre_me )
473         {
474             p_context->pre_me = 1;
475             p_context->me_pre_cmp = FF_CMP_CHROMA;
476         }
477
478         if ( p_sys->b_interlace )
479         {
480             if ( p_context->height <= 280 )
481             {
482                 if ( p_context->height != 16 || p_context->width != 16 )
483                     msg_Warn( p_enc,
484                         "disabling interlaced video because height=%d <= 280",
485                         p_context->height );
486             }
487             else
488             {
489                 p_context->flags |= CODEC_FLAG_INTERLACED_DCT;
490                 if ( p_sys->b_interlace_me )
491                     p_context->flags |= CODEC_FLAG_INTERLACED_ME;
492             }
493         }
494
495 #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT( 52, 0, 0 )
496         if ( p_sys->b_trellis )
497             p_context->flags |= CODEC_FLAG_TRELLIS_QUANT;
498 #else
499         p_context->trellis = p_sys->b_trellis;
500 #endif
501
502         if ( p_sys->i_qmin > 0 && p_sys->i_qmin == p_sys->i_qmax )
503             p_context->flags |= CODEC_FLAG_QSCALE;
504
505         if ( p_enc->i_threads >= 1 )
506             avcodec_thread_init( p_context, p_enc->i_threads );
507
508         if( p_sys->i_vtolerance > 0 )
509             p_context->bit_rate_tolerance = p_sys->i_vtolerance;
510
511         /* usually if someone sets bitrate, he likes more to get that bitrate
512          * over quality should help 'normal' user to get asked bitrate
513          */
514         if( p_enc->fmt_out.i_bitrate > 0 && p_sys->i_qmax == 0 && p_sys->i_qmin == 0 )
515         {
516             p_sys->i_qmax = 51;
517             p_sys->i_qmin = 3;
518         }
519
520         if( p_sys->i_qmin > 0 )
521         {
522             p_context->mb_qmin = p_context->qmin = p_sys->i_qmin;
523             p_context->mb_lmin = p_context->lmin = p_sys->i_qmin * FF_QP2LAMBDA;
524         }
525         if( p_sys->i_qmax > 0 )
526         {
527             p_context->mb_qmax = p_context->qmax = p_sys->i_qmax;
528             p_context->mb_lmax = p_context->lmax = p_sys->i_qmax * FF_QP2LAMBDA;
529         }
530         p_context->max_qdiff = 3;
531
532         p_context->mb_decision = p_sys->i_hq;
533
534         if( p_sys->i_quality )
535         {
536             p_context->flags |= CODEC_FLAG_QSCALE;
537             p_context->global_quality = p_sys->i_quality;
538         }
539         else
540         {
541             p_context->rc_qsquish = 1.0;
542             p_context->rc_max_rate = p_enc->fmt_out.i_bitrate;
543             p_context->rc_min_rate = p_enc->fmt_out.i_bitrate;
544             p_context->rc_buffer_size = p_sys->i_rc_buffer_size;
545             /* This is from ffmpeg's ffmpeg.c : */
546             p_context->rc_initial_buffer_occupancy
547                 = p_sys->i_rc_buffer_size * 3/4;
548             p_context->rc_buffer_aggressivity = p_sys->f_rc_buffer_aggressivity;
549         }
550     }
551     else if( p_enc->fmt_in.i_cat == AUDIO_ES )
552     {
553         /* work around bug in libmp3lame encoding */
554         if( i_codec_id == CODEC_ID_MP3 && p_enc->fmt_in.audio.i_channels > 2 )
555             p_enc->fmt_in.audio.i_channels = 2;
556
557         p_context->codec_type = CODEC_TYPE_AUDIO;
558         p_enc->fmt_in.i_codec  = VLC_CODEC_S16N;
559         p_context->sample_rate = p_enc->fmt_out.audio.i_rate;
560         p_context->channels    = p_enc->fmt_out.audio.i_channels;
561
562         if ( p_enc->fmt_out.i_codec == VLC_CODEC_MP4A )
563         {
564             /* XXX: FAAC does resample only when setting the INPUT samplerate
565              * to the desired value (-R option of the faac frontend)
566             p_enc->fmt_in.audio.i_rate = p_context->sample_rate;*/
567             /* vlc should default to low-complexity profile, faac encoder
568              * has bug and aac audio has issues otherwise atm */
569             p_context->profile = p_sys->i_aac_profile;
570         }
571     }
572
573     /* Misc parameters */
574     p_context->bit_rate = p_enc->fmt_out.i_bitrate;
575
576     if( i_codec_id == CODEC_ID_RAWVIDEO )
577     {
578         /* XXX: hack: Force same codec (will be handled by transcode) */
579         p_enc->fmt_in.video.i_chroma = p_enc->fmt_in.i_codec = p_enc->fmt_out.i_codec;
580         GetFfmpegChroma( &p_context->pix_fmt, p_enc->fmt_in.video );
581     }
582
583     /* Make sure we get extradata filled by the encoder */
584     p_context->extradata_size = 0;
585     p_context->extradata = NULL;
586     p_context->flags |= CODEC_FLAG_GLOBAL_HEADER;
587
588     int ret;
589     vlc_avcodec_lock();
590     ret = avcodec_open( p_context, p_codec );
591     vlc_avcodec_unlock();
592     if( ret )
593     {
594         if( p_enc->fmt_in.i_cat == AUDIO_ES &&
595              (p_context->channels > 2 || i_codec_id == CODEC_ID_MP2
596                || i_codec_id == CODEC_ID_MP3) )
597         {
598             if( p_context->channels > 2 )
599             {
600                 p_context->channels = 2;
601                 p_enc->fmt_in.audio.i_channels = 2; // FIXME
602                 msg_Warn( p_enc, "stereo mode selected (codec limitation)" );
603             }
604
605             if( i_codec_id == CODEC_ID_MP2 || i_codec_id == CODEC_ID_MP3 )
606             {
607                 int i_frequency, i;
608
609                 for ( i_frequency = 0; i_frequency < 6; i_frequency++ )
610                 {
611                     if ( p_enc->fmt_out.audio.i_rate
612                             == mpa_freq_tab[i_frequency] )
613                         break;
614                 }
615                 if ( i_frequency == 6 )
616                 {
617                     msg_Err( p_enc, "MPEG audio doesn't support frequency=%d",
618                              p_enc->fmt_out.audio.i_rate );
619                     free( p_sys );
620                     return VLC_EGENERIC;
621                 }
622
623                 for ( i = 1; i < 14; i++ )
624                 {
625                     if ( p_enc->fmt_out.i_bitrate / 1000
626                           <= mpa_bitrate_tab[i_frequency / 3][i] )
627                         break;
628                 }
629                 if ( p_enc->fmt_out.i_bitrate / 1000
630                       != mpa_bitrate_tab[i_frequency / 3][i] )
631                 {
632                     msg_Warn( p_enc,
633                               "MPEG audio doesn't support bitrate=%d, using %d",
634                               p_enc->fmt_out.i_bitrate,
635                               mpa_bitrate_tab[i_frequency / 3][i] * 1000 );
636                     p_enc->fmt_out.i_bitrate =
637                         mpa_bitrate_tab[i_frequency / 3][i] * 1000;
638                     p_context->bit_rate = p_enc->fmt_out.i_bitrate;
639                 }
640             }
641
642             p_context->codec = NULL;
643             vlc_avcodec_lock();
644             ret = avcodec_open( p_context, p_codec );
645             vlc_avcodec_unlock();
646             if( ret )
647             {
648                 msg_Err( p_enc, "cannot open encoder" );
649                 dialog_Fatal( p_enc,
650                                 _("Streaming / Transcoding failed"),
651                                 "%s", _("VLC could not open the encoder.") );
652                 free( p_sys );
653                 return VLC_EGENERIC;
654             }
655         }
656         else
657         {
658             msg_Err( p_enc, "cannot open encoder" );
659             dialog_Fatal( p_enc, _("Streaming / Transcoding failed"),
660                             "%s", _("VLC could not open the encoder.") );
661             free( p_sys );
662             return VLC_EGENERIC;
663         }
664     }
665
666     if( i_codec_id == CODEC_ID_FLAC )
667     {
668         p_enc->fmt_out.i_extra = 4 + 1 + 3 + p_context->extradata_size;
669         p_enc->fmt_out.p_extra = malloc( p_enc->fmt_out.i_extra );
670         if( p_enc->fmt_out.p_extra )
671         {
672             uint8_t *p = p_enc->fmt_out.p_extra;
673             p[0] = 0x66;    /* f */
674             p[1] = 0x4C;    /* L */
675             p[2] = 0x61;    /* a */
676             p[3] = 0x43;    /* C */
677             p[4] = 0x80;    /* streaminfo block, last block before audio */
678             p[5] = ( p_context->extradata_size >> 16 ) & 0xff;
679             p[6] = ( p_context->extradata_size >>  8 ) & 0xff;
680             p[7] = ( p_context->extradata_size       ) & 0xff;
681             memcpy( &p[8], p_context->extradata, p_context->extradata_size );
682         }
683         else
684         {
685             p_enc->fmt_out.i_extra = 0;
686         }
687     }
688     else
689     {
690         p_enc->fmt_out.i_extra = p_context->extradata_size;
691         if( p_enc->fmt_out.i_extra )
692         {
693             p_enc->fmt_out.p_extra = malloc( p_enc->fmt_out.i_extra );
694             memcpy( p_enc->fmt_out.p_extra, p_context->extradata,
695                     p_enc->fmt_out.i_extra );
696         }
697     }
698
699     p_context->flags &= ~CODEC_FLAG_GLOBAL_HEADER;
700
701     if( p_enc->fmt_in.i_cat == AUDIO_ES )
702     {
703         p_sys->i_buffer_out = 2 * AVCODEC_MAX_AUDIO_FRAME_SIZE;
704         p_sys->p_buffer_out = malloc( p_sys->i_buffer_out );
705         p_sys->i_frame_size = p_context->frame_size * 2 * p_context->channels;
706         p_sys->p_buffer = malloc( p_sys->i_frame_size );
707         p_enc->fmt_out.audio.i_blockalign = p_context->block_align;
708     }
709
710     msg_Dbg( p_enc, "found encoder %s", psz_namecodec );
711
712     return VLC_SUCCESS;
713 }
714
715 /****************************************************************************
716  * EncodeVideo: the whole thing
717  ****************************************************************************/
718 static block_t *EncodeVideo( encoder_t *p_enc, picture_t *p_pict )
719 {
720     encoder_sys_t *p_sys = p_enc->p_sys;
721     AVFrame frame;
722     int i_out, i_plane;
723
724
725     memset( &frame, 0, sizeof( AVFrame ) );
726     for( i_plane = 0; i_plane < p_pict->i_planes; i_plane++ )
727     {
728         frame.data[i_plane] = p_pict->p[i_plane].p_pixels;
729         frame.linesize[i_plane] = p_pict->p[i_plane].i_pitch;
730     }
731
732     /* Let ffmpeg select the frame type */
733     frame.pict_type = 0;
734
735     frame.repeat_pict = p_pict->i_nb_fields - 2;
736     frame.interlaced_frame = !p_pict->b_progressive;
737     frame.top_field_first = !!p_pict->b_top_field_first;
738
739     /* Set the pts of the frame being encoded (segfaults with mpeg4!)*/
740     if( p_enc->fmt_out.i_codec != VLC_CODEC_MP4V )
741     {
742         frame.pts = p_pict->date ? p_pict->date : (int64_t)AV_NOPTS_VALUE;
743
744         if ( p_sys->b_hurry_up && frame.pts != (int64_t)AV_NOPTS_VALUE )
745         {
746             mtime_t current_date = mdate();
747
748             if ( current_date + HURRY_UP_GUARD3 > frame.pts )
749             {
750                 p_sys->p_context->mb_decision = FF_MB_DECISION_SIMPLE;
751 #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT( 52, 0, 0 )
752                 p_sys->p_context->flags &= ~CODEC_FLAG_TRELLIS_QUANT;
753 #else
754                 p_sys->p_context->trellis = 0;
755 #endif
756                 msg_Dbg( p_enc, "hurry up mode 3" );
757             }
758             else
759             {
760                 p_sys->p_context->mb_decision = p_sys->i_hq;
761
762                 if ( current_date + HURRY_UP_GUARD2 > frame.pts )
763                 {
764 #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT( 52, 0, 0 )
765                     p_sys->p_context->flags &= ~CODEC_FLAG_TRELLIS_QUANT;
766 #else
767                     p_sys->p_context->trellis = 0;
768 #endif
769                     p_sys->p_context->noise_reduction = p_sys->i_noise_reduction
770                          + (HURRY_UP_GUARD2 + current_date - frame.pts) / 500;
771                     msg_Dbg( p_enc, "hurry up mode 2" );
772                 }
773                 else
774                 {
775 #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT( 52, 0, 0 )
776                     if ( p_sys->b_trellis )
777                         p_sys->p_context->flags |= CODEC_FLAG_TRELLIS_QUANT;
778 #else
779                     p_sys->p_context->trellis = p_sys->b_trellis;
780 #endif
781
782                     p_sys->p_context->noise_reduction =
783                         p_sys->i_noise_reduction;
784                 }
785             }
786
787             if ( current_date + HURRY_UP_GUARD1 > frame.pts )
788             {
789                 frame.pict_type = FF_P_TYPE;
790                 /* msg_Dbg( p_enc, "hurry up mode 1 %lld", current_date + HURRY_UP_GUARD1 - frame.pts ); */
791             }
792         }
793     }
794     else
795     {
796         frame.pts = (int64_t)AV_NOPTS_VALUE;
797     }
798
799     if ( frame.pts != (int64_t)AV_NOPTS_VALUE && frame.pts != 0 )
800     {
801         if ( p_sys->i_last_pts == frame.pts )
802         {
803             msg_Warn( p_enc, "almost fed libavcodec with two frames with the "
804                       "same PTS (%"PRId64 ")", frame.pts );
805             return NULL;
806         }
807         else if ( p_sys->i_last_pts > frame.pts )
808         {
809             msg_Warn( p_enc, "almost fed libavcodec with a frame in the "
810                       "past (current: %"PRId64 ", last: %"PRId64")",
811                       frame.pts, p_sys->i_last_pts );
812             return NULL;
813         }
814         else
815         {
816             p_sys->i_last_pts = frame.pts;
817         }
818     }
819
820     frame.quality = p_sys->i_quality;
821
822     /* Ugly work-around for stupid libavcodec behaviour */
823     p_sys->i_framenum++;
824     p_sys->pi_delay_pts[p_sys->i_framenum % MAX_FRAME_DELAY] = frame.pts;
825     frame.pts = p_sys->i_framenum * AV_TIME_BASE *
826         p_enc->fmt_in.video.i_frame_rate_base;
827     frame.pts += p_enc->fmt_in.video.i_frame_rate - 1;
828     frame.pts /= p_enc->fmt_in.video.i_frame_rate;
829     /* End work-around */
830
831     i_out = avcodec_encode_video( p_sys->p_context, p_sys->p_buffer_out,
832                                   p_sys->i_buffer_out, &frame );
833
834     if( i_out > 0 )
835     {
836         block_t *p_block = block_New( p_enc, i_out );
837         memcpy( p_block->p_buffer, p_sys->p_buffer_out, i_out );
838
839         /* FIXME, 3-2 pulldown is not handled correctly */
840         p_block->i_length = INT64_C(1000000) *
841             p_enc->fmt_in.video.i_frame_rate_base /
842                 p_enc->fmt_in.video.i_frame_rate;
843
844         if( !p_sys->p_context->max_b_frames || !p_sys->p_context->delay )
845         {
846             /* No delay -> output pts == input pts */
847             p_block->i_pts = p_block->i_dts = p_pict->date;
848         }
849         else if( p_sys->p_context->coded_frame->pts != (int64_t)AV_NOPTS_VALUE &&
850             p_sys->p_context->coded_frame->pts != 0 &&
851             p_sys->i_buggy_pts_detect != p_sys->p_context->coded_frame->pts )
852         {
853             p_sys->i_buggy_pts_detect = p_sys->p_context->coded_frame->pts;
854             p_block->i_pts = p_sys->p_context->coded_frame->pts;
855
856             /* Ugly work-around for stupid libavcodec behaviour */
857             {
858                 int64_t i_framenum = p_block->i_pts *
859                     p_enc->fmt_in.video.i_frame_rate /
860                     p_enc->fmt_in.video.i_frame_rate_base / AV_TIME_BASE;
861
862                 p_block->i_pts = p_sys->pi_delay_pts[i_framenum % MAX_FRAME_DELAY];
863             }
864             /* End work-around */
865
866             if( p_sys->p_context->coded_frame->pict_type != FF_I_TYPE &&
867                 p_sys->p_context->coded_frame->pict_type != FF_P_TYPE )
868             {
869                 p_block->i_dts = p_block->i_pts;
870             }
871             else
872             {
873                 if( p_sys->i_last_ref_pts )
874                 {
875                     p_block->i_dts = p_sys->i_last_ref_pts;
876                 }
877                 else
878                 {
879                     /* Let's put something sensible */
880                     p_block->i_dts = p_block->i_pts;
881                 }
882
883                 p_sys->i_last_ref_pts = p_block->i_pts;
884             }
885         }
886         else
887         {
888             /* Buggy libavcodec which doesn't update coded_frame->pts
889              * correctly */
890             p_block->i_dts = p_block->i_pts = p_pict->date;
891         }
892
893         switch ( p_sys->p_context->coded_frame->pict_type )
894         {
895         case FF_I_TYPE:
896             p_block->i_flags |= BLOCK_FLAG_TYPE_I;
897             break;
898         case FF_P_TYPE:
899             p_block->i_flags |= BLOCK_FLAG_TYPE_P;
900             break;
901         case FF_B_TYPE:
902             p_block->i_flags |= BLOCK_FLAG_TYPE_B;
903             break;
904         }
905
906         return p_block;
907     }
908
909     return NULL;
910 }
911
912 /****************************************************************************
913  * EncodeAudio: the whole thing
914  ****************************************************************************/
915 static block_t *EncodeAudio( encoder_t *p_enc, aout_buffer_t *p_aout_buf )
916 {
917     encoder_sys_t *p_sys = p_enc->p_sys;
918     block_t *p_block, *p_chain = NULL;
919
920     uint8_t *p_buffer = p_aout_buf->p_buffer;
921     int i_samples = p_aout_buf->i_nb_samples;
922     int i_samples_delay = p_sys->i_samples_delay;
923
924     p_sys->i_pts = p_aout_buf->i_pts -
925                 (mtime_t)1000000 * (mtime_t)p_sys->i_samples_delay /
926                 (mtime_t)p_enc->fmt_in.audio.i_rate;
927
928     p_sys->i_samples_delay += i_samples;
929
930     while( p_sys->i_samples_delay >= p_sys->p_context->frame_size )
931     {
932         int16_t *p_samples;
933         int i_out;
934
935         if( i_samples_delay )
936         {
937             /* Take care of the left-over from last time */
938             int i_delay_size = i_samples_delay * 2 *
939                                  p_sys->p_context->channels;
940             int i_size = p_sys->i_frame_size - i_delay_size;
941
942             p_samples = (int16_t *)p_sys->p_buffer;
943             memcpy( p_sys->p_buffer + i_delay_size, p_buffer, i_size );
944             p_buffer -= i_delay_size;
945             i_samples += i_samples_delay;
946             i_samples_delay = 0;
947         }
948         else
949         {
950             p_samples = (int16_t *)p_buffer;
951         }
952
953         i_out = avcodec_encode_audio( p_sys->p_context, p_sys->p_buffer_out,
954                                       p_sys->i_buffer_out, p_samples );
955
956 #if 0
957         msg_Warn( p_enc, "avcodec_encode_audio: %d", i_out );
958 #endif
959         if( i_out < 0 ) break;
960
961         p_buffer += p_sys->i_frame_size;
962         p_sys->i_samples_delay -= p_sys->p_context->frame_size;
963         i_samples -= p_sys->p_context->frame_size;
964
965         if( i_out == 0 ) continue;
966
967         p_block = block_New( p_enc, i_out );
968         memcpy( p_block->p_buffer, p_sys->p_buffer_out, i_out );
969
970         p_block->i_length = (mtime_t)1000000 *
971             (mtime_t)p_sys->p_context->frame_size /
972             (mtime_t)p_sys->p_context->sample_rate;
973
974         p_block->i_dts = p_block->i_pts = p_sys->i_pts;
975
976         /* Update pts */
977         p_sys->i_pts += p_block->i_length;
978         block_ChainAppend( &p_chain, p_block );
979     }
980
981     /* Backup the remaining raw samples */
982     if( i_samples )
983     {
984         memcpy( p_sys->p_buffer + i_samples_delay * 2 *
985                 p_sys->p_context->channels, p_buffer,
986                 i_samples * 2 * p_sys->p_context->channels );
987     }
988
989     return p_chain;
990 }
991
992 /*****************************************************************************
993  * CloseEncoder: ffmpeg encoder destruction
994  *****************************************************************************/
995 void CloseEncoder( vlc_object_t *p_this )
996 {
997     encoder_t *p_enc = (encoder_t *)p_this;
998     encoder_sys_t *p_sys = p_enc->p_sys;
999
1000     vlc_avcodec_lock();
1001     avcodec_close( p_sys->p_context );
1002     vlc_avcodec_unlock();
1003     av_free( p_sys->p_context );
1004
1005     free( p_sys->p_buffer );
1006     free( p_sys->p_buffer_out );
1007
1008     free( p_sys );
1009 }