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