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