]> git.sesse.net Git - vlc/blob - modules/codec/ffmpeg/encoder.c
Forgot that yesterday...
[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.11 2003/11/28 10:36:58 massiot 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 #ifdef HAVE_FFMPEG_AVCODEC_H
35 #   include <ffmpeg/avcodec.h>
36 #else
37 #   include <avcodec.h>
38 #endif
39
40 #include "ffmpeg.h"
41
42 #define AVCODEC_MAX_VIDEO_FRAME_SIZE (3*1024*1024)
43 #define HURRY_UP_GUARD (200000)
44
45 /*****************************************************************************
46  * Local prototypes
47  *****************************************************************************/
48 int  E_(OpenEncoder) ( vlc_object_t * );
49 void E_(CloseEncoder)( vlc_object_t * );
50
51 static block_t *EncodeVideo( encoder_t *, picture_t * );
52 static block_t *EncodeAudio( encoder_t *, aout_buffer_t * );
53
54 /*****************************************************************************
55  * encoder_sys_t : ffmpeg encoder descriptor
56  *****************************************************************************/
57 struct encoder_sys_t
58 {
59     /*
60      * Ffmpeg properties
61      */
62     AVCodec         *p_codec;
63     AVCodecContext  *p_context;
64
65     /*
66      * Common properties
67      */
68     char *p_buffer;
69     char *p_buffer_out;
70
71     /*
72      * Videoo properties
73      */
74     mtime_t i_last_ref_pts;
75     mtime_t i_buggy_pts_detect;
76
77     /*
78      * Audio properties
79      */
80     int i_frame_size;
81     int i_samples_delay;
82     mtime_t i_pts;
83 };
84
85 /*****************************************************************************
86  * OpenEncoder: probe the encoder
87  *****************************************************************************/
88 int E_(OpenEncoder)( vlc_object_t *p_this )
89 {
90     encoder_t *p_enc = (encoder_t *)p_this;
91     encoder_sys_t *p_sys = p_enc->p_sys;
92     AVCodecContext *p_context;
93     AVCodec *p_codec;
94     int i_codec_id, i_cat;
95     char *psz_namecodec;
96
97     if( !E_(GetFfmpegCodec)( p_enc->fmt_out.i_codec, &i_cat, &i_codec_id,
98                              &psz_namecodec ) )
99     {
100         return VLC_EGENERIC;
101     }
102
103     if( p_enc->fmt_out.i_cat == VIDEO_ES && i_cat != VIDEO_ES )
104     {
105         msg_Err( p_enc, "\"%s\" is not a video encoder", psz_namecodec );
106         return VLC_EGENERIC;
107     }
108
109     if( p_enc->fmt_out.i_cat == AUDIO_ES && i_cat != AUDIO_ES )
110     {
111         msg_Err( p_enc, "\"%s\" is not an audio encoder", psz_namecodec );
112         return VLC_EGENERIC;
113     }
114
115     /* Initialization must be done before avcodec_find_decoder() */
116     E_(InitLibavcodec)(p_this);
117
118     p_codec = avcodec_find_encoder( i_codec_id );
119     if( !p_codec )
120     {
121         msg_Err( p_enc, "cannot find encoder %s", psz_namecodec );
122         return VLC_EGENERIC;
123     }
124
125     /* Allocate the memory needed to store the decoder's structure */
126     if( ( p_sys = (encoder_sys_t *)malloc(sizeof(encoder_sys_t)) ) == NULL )
127     {
128         msg_Err( p_enc, "out of memory" );
129         return VLC_EGENERIC;
130     }
131     p_enc->p_sys = p_sys;
132     p_sys->p_codec = p_codec;
133
134     p_enc->pf_encode_video = EncodeVideo;
135     p_enc->pf_encode_audio = EncodeAudio;
136
137     p_sys->p_buffer_out = NULL;
138     p_sys->p_buffer = NULL;
139
140     p_sys->p_context = p_context = avcodec_alloc_context();
141
142     /* Set CPU capabilities */
143 #ifdef HAVE_MMX
144     p_context->dsp_mask = 0;
145     if( p_enc->p_libvlc->i_cpu & CPU_CAPABILITY_MMX )
146     {
147         p_context->dsp_mask &= FF_MM_MMX;
148     }
149     if( p_enc->p_libvlc->i_cpu & CPU_CAPABILITY_MMXEXT )
150     {
151         p_context->dsp_mask &= FF_MM_MMXEXT;
152     }
153     if( p_enc->p_libvlc->i_cpu & CPU_CAPABILITY_3DNOW )
154     {
155         p_context->dsp_mask &= FF_MM_3DNOW;
156     }
157     if( p_enc->p_libvlc->i_cpu & CPU_CAPABILITY_SSE )
158     {
159         p_context->dsp_mask &= FF_MM_SSE;
160         p_context->dsp_mask &= FF_MM_SSE2; /* FIXME */
161     }
162     /* Hack to make sure everything can be disabled **/
163     p_context->dsp_mask &= (FF_MM_FORCE >> 1);
164 #endif
165
166     /* Make sure we get extradata filled by the encoder */
167     p_context->extradata_size = 0;
168     p_context->extradata = NULL;
169     p_context->flags |= CODEC_FLAG_GLOBAL_HEADER;
170
171     if( p_enc->fmt_in.i_cat == VIDEO_ES )
172     {
173         p_context->width = p_enc->fmt_in.video.i_width;
174         p_context->height = p_enc->fmt_in.video.i_height;
175
176         p_context->frame_rate = p_enc->fmt_in.video.i_frame_rate;
177 #if LIBAVCODEC_BUILD >= 4662
178         p_context->frame_rate_base= p_enc->fmt_in.video.i_frame_rate_base;
179 #endif
180
181 #if LIBAVCODEC_BUILD >= 4687
182         p_context->sample_aspect_ratio =
183             av_d2q( p_enc->fmt_in.video.i_aspect * p_context->height /
184                     p_context->width / VOUT_ASPECT_FACTOR, 255 );
185 #else
186         p_context->aspect_ratio = ((float)p_enc->fmt_in.video.i_aspect) /
187             VOUT_ASPECT_FACTOR;
188 #endif
189
190         p_sys->p_buffer_out = malloc( AVCODEC_MAX_VIDEO_FRAME_SIZE );
191
192         /* Ffmpeg does handle the conversion itself */
193         //p_enc->fmt_in.i_codec = VLC_FOURCC('I','4','2','0');
194
195         if ( p_enc->b_strict_rc )
196         {
197             p_context->rc_max_rate = p_enc->fmt_out.i_bitrate;
198             p_context->rc_buffer_size = p_context->bit_rate / 2;
199             p_context->rc_buffer_aggressivity = 1000.0; /* FIXME */
200         }
201
202         if ( p_enc->b_pre_me )
203         {
204             p_context->pre_me = 1;
205             p_context->me_pre_cmp = FF_CMP_CHROMA;
206         }
207     }
208     else if( p_enc->fmt_in.i_cat == AUDIO_ES )
209     {
210         p_enc->fmt_in.i_codec  = AOUT_FMT_S16_NE;
211         p_context->sample_rate = p_enc->fmt_in.audio.i_rate;
212         p_context->channels    = p_enc->fmt_in.audio.i_channels;
213         p_sys->i_frame_size = p_context->frame_size * 2 * p_context->channels;
214         p_sys->p_buffer = malloc( p_sys->i_frame_size );
215         p_sys->p_buffer_out = malloc( 2 * AVCODEC_MAX_AUDIO_FRAME_SIZE );
216     }
217
218     /* Misc parameters */
219     p_context->bit_rate = p_enc->fmt_out.i_bitrate;
220     p_context->gop_size = p_enc->i_key_int > 0 ? p_enc->i_key_int : 50;
221     p_context->max_b_frames =
222         __MIN( p_enc->i_b_frames, FF_MAX_B_FRAMES );
223     p_context->b_frame_strategy = 0;
224     p_context->b_quant_factor = 2.0;
225
226     if( p_enc->i_vtolerance > 0 )
227     {
228         p_context->bit_rate_tolerance = p_enc->i_vtolerance;
229     }
230     p_context->qmin = p_enc->i_qmin;
231     p_context->qmax = p_enc->i_qmax;
232
233 #if LIBAVCODEC_BUILD >= 4673
234     p_context->mb_decision = p_enc->i_hq;
235 #else
236     if( p_enc->i_hq )
237     {
238         p_context->flags |= CODEC_FLAG_HQ;
239     }
240 #endif
241
242     if( i_codec_id == CODEC_ID_RAWVIDEO )
243     {
244         p_context->pix_fmt = E_(GetFfmpegChroma)( p_enc->fmt_in.i_codec );
245     }
246
247     /* Make sure we get extradata filled by the encoder */
248     p_context->extradata_size = 0;
249     p_context->extradata = NULL;
250     p_context->flags |= CODEC_FLAG_GLOBAL_HEADER;
251
252     if( avcodec_open( p_context, p_codec ) )
253     {
254         if( p_enc->fmt_in.i_cat == AUDIO_ES && p_context->channels > 2 )
255         {
256             p_context->channels = 2;
257             p_enc->fmt_in.audio.i_channels = 2; // FIXME
258             if( avcodec_open( p_context, p_codec ) )
259             {
260                 msg_Err( p_enc, "cannot open encoder" );
261                 return VLC_EGENERIC;
262             }
263             msg_Warn( p_enc, "stereo mode selected (codec limitation)" );
264         }
265         else
266         {
267             msg_Err( p_enc, "cannot open encoder" );
268             return VLC_EGENERIC;
269         }
270     }
271
272     p_enc->fmt_out.i_extra = p_context->extradata_size;
273     p_enc->fmt_out.p_extra = p_context->extradata;
274     p_context->flags &= ~CODEC_FLAG_GLOBAL_HEADER;
275
276     if( p_enc->fmt_in.i_cat == AUDIO_ES )
277     {
278         p_sys->i_frame_size = p_context->frame_size * 2 * p_context->channels;
279         p_sys->p_buffer = malloc( p_sys->i_frame_size );
280     }
281
282     p_sys->i_last_ref_pts = 0;
283     p_sys->i_buggy_pts_detect = 0;
284     p_sys->i_samples_delay = 0;
285     p_sys->i_pts = 0;
286
287     msg_Dbg( p_enc, "found encoder %s", psz_namecodec );
288
289     return VLC_SUCCESS;
290 }
291
292 /****************************************************************************
293  * EncodeVideo: the whole thing
294  ****************************************************************************/
295 static block_t *EncodeVideo( encoder_t *p_enc, picture_t *p_pict )
296 {
297     encoder_sys_t *p_sys = p_enc->p_sys;
298     AVFrame frame;
299     int i_out, i_plane;
300     vlc_bool_t b_hurry_up;
301
302     for( i_plane = 0; i_plane < p_pict->i_planes; i_plane++ )
303     {
304         frame.data[i_plane] = p_pict->p[i_plane].p_pixels;
305         frame.linesize[i_plane] = p_pict->p[i_plane].i_pitch;
306     }
307
308     /* Set the pts of the frame being encoded (segfaults with mpeg4!)*/
309     if( p_enc->fmt_out.i_codec == VLC_FOURCC( 'm', 'p', 'g', 'v' ) ||
310         p_enc->fmt_out.i_codec == VLC_FOURCC( 'm', 'p', '1', 'v' ) ||
311         p_enc->fmt_out.i_codec == VLC_FOURCC( 'm', 'p', '2', 'v' ) )
312     {
313         frame.pts = p_pict->date;
314 #if LIBAVCODEC_BUILD >= 4673
315         if ( frame.pts && mdate() + HURRY_UP_GUARD > frame.pts
316               && p_enc->b_hurry_up )
317         {
318             msg_Dbg( p_enc, "hurry up mode" );
319             p_sys->p_context->mb_decision = FF_MB_DECISION_SIMPLE;
320             b_hurry_up = 1;
321         }
322 #endif
323     }
324     else
325     {
326         frame.pts = 0;
327     }
328
329     /* Let ffmpeg select the frame type */
330     frame.pict_type = 0;
331     frame.interlaced_frame = !p_pict->b_progressive;
332     frame.repeat_pict = p_pict->i_nb_fields;
333     frame.top_field_first = p_pict->b_top_field_first;
334
335     i_out = avcodec_encode_video( p_sys->p_context, p_sys->p_buffer_out,
336                                   AVCODEC_MAX_VIDEO_FRAME_SIZE, &frame );
337
338 #if LIBAVCODEC_BUILD >= 4673
339     if ( b_hurry_up )
340     {
341         p_sys->p_context->mb_decision = p_enc->i_hq;
342     }
343 #endif
344
345     if( i_out > 0 )
346     {
347         block_t *p_block = block_New( p_enc, i_out );
348         memcpy( p_block->p_buffer, p_sys->p_buffer_out, i_out );
349
350         if( p_sys->p_context->coded_frame->pts != 0 &&
351             p_sys->i_buggy_pts_detect != p_sys->p_context->coded_frame->pts )
352         {
353             p_sys->i_buggy_pts_detect = p_sys->p_context->coded_frame->pts;
354
355             /* FIXME, 3-2 pulldown is not handled correctly */
356             p_block->i_length = I64C(1000000) *
357                 p_enc->fmt_in.video.i_frame_rate_base /
358                 p_enc->fmt_in.video.i_frame_rate;
359             p_block->i_pts    = p_sys->p_context->coded_frame->pts;
360
361             if( !p_sys->p_context->delay ||
362                 ( p_sys->p_context->coded_frame->pict_type != FF_I_TYPE &&
363                   p_sys->p_context->coded_frame->pict_type != FF_P_TYPE ) )
364             {
365                 p_block->i_dts = p_block->i_pts;
366             }
367             else
368             {
369                 if( p_sys->i_last_ref_pts )
370                 {
371                     p_block->i_dts = p_sys->i_last_ref_pts;
372                 }
373                 else
374                 {
375                     /* Let's put something sensible */
376                     p_block->i_dts = p_block->i_pts;
377                 }
378
379                 p_sys->i_last_ref_pts = p_block->i_pts;
380             }
381         }
382         else
383         {
384             /* Buggy libavcodec which doesn't update coded_frame->pts
385              * correctly */
386             p_block->i_length = I64C(1000000) *
387                 p_enc->fmt_in.video.i_frame_rate_base /
388                 p_enc->fmt_in.video.i_frame_rate;
389             p_block->i_dts = p_block->i_pts = p_pict->date;
390         }
391
392         return p_block;
393     }
394
395     return NULL;
396 }
397
398 /****************************************************************************
399  * EncodeAudio: the whole thing
400  ****************************************************************************/
401 static block_t *EncodeAudio( encoder_t *p_enc, aout_buffer_t *p_aout_buf )
402 {
403     encoder_sys_t *p_sys = p_enc->p_sys;
404     block_t *p_block, *p_chain = NULL;
405
406     char *p_buffer = p_aout_buf->p_buffer;
407     int i_samples = p_aout_buf->i_nb_samples;
408     int i_samples_delay = p_sys->i_samples_delay;
409
410     p_sys->i_pts = p_aout_buf->start_date -
411                 (mtime_t)1000000 * (mtime_t)p_sys->i_samples_delay /
412                 (mtime_t)p_enc->fmt_in.audio.i_rate;
413
414     p_sys->i_samples_delay += i_samples;
415
416     while( p_sys->i_samples_delay >= p_sys->p_context->frame_size )
417     {
418         int16_t *p_samples;
419         int i_out;
420
421         if( i_samples_delay )
422         {
423             /* Take care of the left-over from last time */
424             int i_delay_size = i_samples_delay * 2 *
425                                  p_sys->p_context->channels;
426             int i_size = p_sys->i_frame_size - i_delay_size;
427
428             p_samples = (int16_t *)p_sys->p_buffer;
429             memcpy( p_sys->p_buffer + i_delay_size, p_buffer, i_size );
430             p_buffer -= i_delay_size;
431             i_samples += i_samples_delay;
432             i_samples_delay = 0;
433         }
434         else
435         {
436             p_samples = (int16_t *)p_buffer;
437         }
438
439         i_out = avcodec_encode_audio( p_sys->p_context, p_sys->p_buffer_out,
440                                       2 * AVCODEC_MAX_AUDIO_FRAME_SIZE,
441                                       p_samples );
442
443 #if 0
444         msg_Warn( p_enc, "avcodec_encode_audio: %d", i_out );
445 #endif
446         if( i_out < 0 ) break;
447
448         p_buffer += p_sys->i_frame_size;
449         p_sys->i_samples_delay -= p_sys->p_context->frame_size;
450         i_samples -= p_sys->p_context->frame_size;
451
452         if( i_out == 0 ) continue;
453
454         p_block = block_New( p_enc, i_out );
455         memcpy( p_block->p_buffer, p_sys->p_buffer_out, i_out );
456
457         p_block->i_length = (mtime_t)1000000 *
458             (mtime_t)p_sys->p_context->frame_size /
459             (mtime_t)p_sys->p_context->sample_rate;
460
461         p_block->i_dts = p_block->i_pts = p_sys->i_pts;
462
463         /* Update pts */
464         p_sys->i_pts += p_block->i_length;
465         block_ChainAppend( &p_chain, p_block );
466     }
467
468     /* Backup the remaining raw samples */
469     if( i_samples )
470     {
471         memcpy( p_sys->p_buffer, p_buffer + i_samples_delay * 2 *
472                 p_sys->p_context->channels,
473                 i_samples * 2 * p_sys->p_context->channels );
474     }
475
476     return p_chain;
477 }
478
479 /*****************************************************************************
480  * CloseEncoder: ffmpeg encoder destruction
481  *****************************************************************************/
482 void E_(CloseEncoder)( vlc_object_t *p_this )
483 {
484     encoder_t *p_enc = (encoder_t *)p_this;
485     encoder_sys_t *p_sys = p_enc->p_sys;
486
487     avcodec_close( p_sys->p_context );
488     free( p_sys->p_context );
489
490     if( p_sys->p_buffer ) free( p_sys->p_buffer );
491     if( p_sys->p_buffer_out ) free( p_sys->p_buffer_out );
492
493     free( p_sys );
494 }