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