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