encoder.c 38.7 KB
Newer Older
gbazin's avatar
   
gbazin committed
1
2
3
/*****************************************************************************
 * encoder.c: video and audio encoder using the ffmpeg library
 *****************************************************************************
4
 * Copyright (C) 1999-2004 the VideoLAN team
gbazin's avatar
gbazin committed
5
 * $Id$
gbazin's avatar
   
gbazin committed
6
7
 *
 * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8
 *          Gildas Bazin <gbazin@videolan.org>
9
 *          Christophe Massiot <massiot@via.ecp.fr>
10
11
 * Part of the file Copyright (C) FFMPEG Project Developers
 * (mpeg4_default matrixes)
gbazin's avatar
   
gbazin committed
12
13
14
15
16
17
18
19
20
21
22
23
24
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
dionoea's avatar
dionoea committed
25
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
gbazin's avatar
   
gbazin committed
26
27
28
29
30
 *****************************************************************************/

/*****************************************************************************
 * Preamble
 *****************************************************************************/
31
32
33
34
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

35
#include <vlc_common.h>
zorglub's avatar
zorglub committed
36
37
38
39
40
#include <vlc_vout.h>
#include <vlc_aout.h>
#include <vlc_sout.h>
#include <vlc_codec.h>
#include <vlc_interface.h>
gbazin's avatar
   
gbazin committed
41
42

/* ffmpeg header */
43
#define HAVE_MMX 1
44
45
46
#ifdef HAVE_LIBAVCODEC_AVCODEC_H
#   include <libavcodec/avcodec.h>
#elif defined(HAVE_FFMPEG_AVCODEC_H)
47
#   include <ffmpeg/avcodec.h>
gbazin's avatar
   
gbazin committed
48
49
50
51
#else
#   include <avcodec.h>
#endif

52
#include "avcodec.h"
gbazin's avatar
   
gbazin committed
53

54
55
56
#define HURRY_UP_GUARD1 (450000)
#define HURRY_UP_GUARD2 (300000)
#define HURRY_UP_GUARD3 (100000)
gbazin's avatar
   
gbazin committed
57

58
59
#define MAX_FRAME_DELAY (FF_MAX_B_FRAMES + 2)

gbazin's avatar
   
gbazin committed
60
61
62
/*****************************************************************************
 * Local prototypes
 *****************************************************************************/
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
63
64
int  OpenEncoder ( vlc_object_t * );
void CloseEncoder( vlc_object_t * );
gbazin's avatar
   
gbazin committed
65
66
67
68

static block_t *EncodeVideo( encoder_t *, picture_t * );
static block_t *EncodeAudio( encoder_t *, aout_buffer_t * );

69
struct thread_context_t;
70
static void* FfmpegThread( vlc_object_t *p_this );
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
static int FfmpegExecute( AVCodecContext *s,
                          int (*pf_func)(AVCodecContext *c2, void *arg2),
                          void **arg, int *ret, int count );

/*****************************************************************************
 * thread_context_t : for multithreaded encoding
 *****************************************************************************/
struct thread_context_t
{
    VLC_COMMON_MEMBERS

    AVCodecContext  *p_context;
    int             (* pf_func)(AVCodecContext *c, void *arg);
    void            *arg;
    int             i_ret;

    vlc_mutex_t     lock;
    vlc_cond_t      cond;
dionoea's avatar
dionoea committed
89
    bool            b_work, b_done;
90
91
};

gbazin's avatar
   
gbazin committed
92
93
94
95
96
97
98
99
100
101
102
103
104
105
/*****************************************************************************
 * encoder_sys_t : ffmpeg encoder descriptor
 *****************************************************************************/
struct encoder_sys_t
{
    /*
     * Ffmpeg properties
     */
    AVCodec         *p_codec;
    AVCodecContext  *p_context;

    /*
     * Common properties
     */
gbazin's avatar
   
gbazin committed
106
    char *p_buffer;
107
108
    uint8_t *p_buffer_out;
    size_t i_buffer_out;
gbazin's avatar
   
gbazin committed
109

gbazin's avatar
   
gbazin committed
110
    /*
111
     * Video properties
gbazin's avatar
   
gbazin committed
112
     */
gbazin's avatar
   
gbazin committed
113
114
    mtime_t i_last_ref_pts;
    mtime_t i_buggy_pts_detect;
115
    mtime_t i_last_pts;
dionoea's avatar
dionoea committed
116
    bool    b_inited;
gbazin's avatar
   
gbazin committed
117

gbazin's avatar
   
gbazin committed
118
119
120
    /*
     * Audio properties
     */
gbazin's avatar
   
gbazin committed
121
    int i_frame_size;
gbazin's avatar
   
gbazin committed
122
123
    int i_samples_delay;
    mtime_t i_pts;
124
125
126
127
128
129
130
131
132
133

    /* Encoding settings */
    int        i_key_int;
    int        i_b_frames;
    int        i_vtolerance;
    int        i_qmin;
    int        i_qmax;
    int        i_hq;
    int        i_rc_buffer_size;
    float      f_rc_buffer_aggressivity;
dionoea's avatar
dionoea committed
134
135
136
    bool       b_pre_me;
    bool       b_hurry_up;
    bool       b_interlace, b_interlace_me;
137
138
    float      f_i_quant_factor;
    int        i_noise_reduction;
dionoea's avatar
dionoea committed
139
140
    bool       b_mpeg4_matrix;
    bool       b_trellis;
gbazin's avatar
gbazin committed
141
    int        i_quality; /* for VBR */
142
143
    float      f_lumi_masking, f_dark_masking, f_p_masking, f_border_masking;
    int        i_luma_elim, i_chroma_elim;
144
#if LIBAVCODEC_VERSION_INT >= ((51<<16)+(40<<8)+4)
145
    int        i_aac_profile; /* AAC profile to use.*/
146
#endif
147
148
149
    /* Used to work around stupid timestamping behaviour in libavcodec */
    uint64_t i_framenum;
    mtime_t  pi_delay_pts[MAX_FRAME_DELAY];
150
151
};

152
static const char *const ppsz_enc_options[] = {
dionoea's avatar
dionoea committed
153
    "keyint", "bframes", "vt", "qmin", "qmax", "hq",
154
155
    "rc-buffer-size", "rc-buffer-aggressivity", "pre-me", "hurry-up",
    "interlace", "i-quant-factor", "noise-reduction", "mpeg4-matrix",
156
157
    "trellis", "qscale", "strict", "lumi-masking", "dark-masking",
    "p-masking", "border-masking", "luma-elim-threshold",
dionoea's avatar
dionoea committed
158
    "chroma-elim-threshold",
159
#if LIBAVCODEC_VERSION_INT >= ((51<<16)+(40<<8)+4)
dionoea's avatar
dionoea committed
160
     "aac-profile",
161
162
#endif
     NULL
gbazin's avatar
   
gbazin committed
163
164
};

165
166
167
168
169
170
171
172
173
static const uint16_t mpa_bitrate_tab[2][15] =
{
    {0, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384},
    {0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160}
};

static const uint16_t mpa_freq_tab[6] =
{ 44100, 48000, 32000, 22050, 24000, 16000 };

174
static const uint16_t mpeg4_default_intra_matrix[64] = {
175
176
177
178
179
180
181
182
183
184
  8, 17, 18, 19, 21, 23, 25, 27,
 17, 18, 19, 21, 23, 25, 27, 28,
 20, 21, 22, 23, 24, 26, 28, 30,
 21, 22, 23, 24, 26, 28, 30, 32,
 22, 23, 24, 26, 28, 30, 32, 35,
 23, 24, 26, 28, 30, 32, 35, 38,
 25, 26, 28, 30, 32, 35, 38, 41,
 27, 28, 30, 32, 35, 38, 41, 45,
};

185
static const uint16_t mpeg4_default_non_intra_matrix[64] = {
186
187
188
189
190
191
192
193
194
195
 16, 17, 18, 19, 20, 21, 22, 23,
 17, 18, 19, 20, 21, 22, 23, 24,
 18, 19, 20, 21, 22, 23, 24, 25,
 19, 20, 21, 22, 23, 24, 26, 27,
 20, 21, 22, 23, 25, 26, 27, 28,
 21, 22, 23, 24, 26, 27, 28, 30,
 22, 23, 24, 26, 27, 28, 30, 31,
 23, 24, 25, 27, 28, 30, 31, 33,
};

gbazin's avatar
   
gbazin committed
196
/*****************************************************************************
gbazin's avatar
   
gbazin committed
197
 * OpenEncoder: probe the encoder
gbazin's avatar
   
gbazin committed
198
 *****************************************************************************/
199

Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
200
int OpenEncoder( vlc_object_t *p_this )
gbazin's avatar
   
gbazin committed
201
202
203
{
    encoder_t *p_enc = (encoder_t *)p_this;
    encoder_sys_t *p_sys = p_enc->p_sys;
gbazin's avatar
   
gbazin committed
204
    AVCodecContext *p_context;
gbazin's avatar
   
gbazin committed
205
    AVCodec *p_codec;
gbazin's avatar
   
gbazin committed
206
    int i_codec_id, i_cat;
207
    const char *psz_namecodec;
208
    vlc_value_t val;
gbazin's avatar
   
gbazin committed
209

Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
210
    if( !GetFfmpegCodec( p_enc->fmt_out.i_codec, &i_cat, &i_codec_id,
gbazin's avatar
   
gbazin committed
211
                             &psz_namecodec ) )
gbazin's avatar
   
gbazin committed
212
    {
213
        if( TestFfmpegChroma( -1, p_enc->fmt_out.i_codec ) != VLC_SUCCESS )
214
215
216
217
218
219
220
        {
            /* handed chroma output */
            return VLC_EGENERIC;
        }
        i_cat      = VIDEO_ES;
        i_codec_id = CODEC_ID_RAWVIDEO;
        psz_namecodec = "Raw video";
gbazin's avatar
   
gbazin committed
221
222
    }

gbazin's avatar
   
gbazin committed
223
    if( p_enc->fmt_out.i_cat == VIDEO_ES && i_cat != VIDEO_ES )
gbazin's avatar
   
gbazin committed
224
    {
gbazin's avatar
   
gbazin committed
225
        msg_Err( p_enc, "\"%s\" is not a video encoder", psz_namecodec );
226
        intf_UserFatal( p_enc, false, _("Streaming / Transcoding failed"),
227
                        _("\"%s\" is no video encoder."), psz_namecodec );
gbazin's avatar
   
gbazin committed
228
229
230
        return VLC_EGENERIC;
    }

gbazin's avatar
   
gbazin committed
231
232
233
    if( p_enc->fmt_out.i_cat == AUDIO_ES && i_cat != AUDIO_ES )
    {
        msg_Err( p_enc, "\"%s\" is not an audio encoder", psz_namecodec );
234
        intf_UserFatal( p_enc, false, _("Streaming / Transcoding failed"),
235
                        _("\"%s\" is no audio encoder."), psz_namecodec );
gbazin's avatar
   
gbazin committed
236
237
238
        return VLC_EGENERIC;
    }

Jean-Paul Saman's avatar
Jean-Paul Saman committed
239
    /* Initialization must be done before avcodec_find_encoder() */
dionoea's avatar
dionoea committed
240
    InitLibavcodec( p_this );
gbazin's avatar
   
gbazin committed
241

gbazin's avatar
   
gbazin committed
242
243
244
    p_codec = avcodec_find_encoder( i_codec_id );
    if( !p_codec )
    {
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
        msg_Err( p_enc, "cannot find encoder %s\n"
"*** Your FFMPEG installation is crippled.   ***\n"
"*** Please check with your FFMPEG packager. ***\n"
"*** This is NOT a VLC media player issue.   ***\n", psz_namecodec );

        intf_UserFatal( p_enc, false, _("Streaming / Transcoding failed"), _(
/* I have had enough of all these MPEG-3 transcoding bug reports.
 * Downstream packager, you had better not patch this out, or I will be really
 * annoyed. Think about it - you don't want to fork the VLC translation files,
 * do you? -- Courmisch, 2008-10-22 */
"It seems your FFMPEG (libavcodec) installation lacks the following encoder:\n"
"%s.\n"
"If you don't know how to fix this, ask for support from your distribution.\n"
"\n"
"This is not an error inside VLC media player.\n"
"Do not contact the VideoLAN project about this issue.\n"),
            psz_namecodec );
gbazin's avatar
   
gbazin committed
262
263
264
        return VLC_EGENERIC;
    }

Jean-Paul Saman's avatar
Jean-Paul Saman committed
265
    /* Allocate the memory needed to store the encoder's structure */
gbazin's avatar
   
gbazin committed
266
    if( ( p_sys = (encoder_sys_t *)malloc(sizeof(encoder_sys_t)) ) == NULL )
ivoire's avatar
ivoire committed
267
        return VLC_ENOMEM;
268
    memset( p_sys, 0, sizeof(encoder_sys_t) );
gbazin's avatar
   
gbazin committed
269
270
271
272
    p_enc->p_sys = p_sys;
    p_sys->p_codec = p_codec;

    p_enc->pf_encode_video = EncodeVideo;
gbazin's avatar
   
gbazin committed
273
    p_enc->pf_encode_audio = EncodeAudio;
gbazin's avatar
   
gbazin committed
274

gbazin's avatar
   
gbazin committed
275
    p_sys->p_buffer = NULL;
276
277
    p_sys->p_buffer_out = NULL;
    p_sys->i_buffer_out = 0;
gbazin's avatar
   
gbazin committed
278
279

    p_sys->p_context = p_context = avcodec_alloc_context();
280
281
    p_context->debug = config_GetInt( p_enc, "ffmpeg-debug" );
    p_context->opaque = (void *)p_this;
gbazin's avatar
   
gbazin committed
282
283

    /* Set CPU capabilities */
284
    unsigned i_cpu = vlc_CPU();
gbazin's avatar
   
gbazin committed
285
    p_context->dsp_mask = 0;
286
    if( !(i_cpu & CPU_CAPABILITY_MMX) )
gbazin's avatar
   
gbazin committed
287
    {
gbazin's avatar
   
gbazin committed
288
        p_context->dsp_mask |= FF_MM_MMX;
gbazin's avatar
   
gbazin committed
289
    }
290
    if( !(i_cpu & CPU_CAPABILITY_MMXEXT) )
gbazin's avatar
   
gbazin committed
291
    {
gbazin's avatar
   
gbazin committed
292
        p_context->dsp_mask |= FF_MM_MMXEXT;
gbazin's avatar
   
gbazin committed
293
    }
294
    if( !(i_cpu & CPU_CAPABILITY_3DNOW) )
gbazin's avatar
   
gbazin committed
295
    {
gbazin's avatar
   
gbazin committed
296
        p_context->dsp_mask |= FF_MM_3DNOW;
gbazin's avatar
   
gbazin committed
297
    }
298
    if( !(i_cpu & CPU_CAPABILITY_SSE) )
gbazin's avatar
   
gbazin committed
299
    {
gbazin's avatar
   
gbazin committed
300
301
        p_context->dsp_mask |= FF_MM_SSE;
        p_context->dsp_mask |= FF_MM_SSE2;
gbazin's avatar
   
gbazin committed
302
303
    }

304
    config_ChainParse( p_enc, ENC_CFG_PREFIX, ppsz_enc_options, p_enc->p_cfg );
305
306
307
308
309
310
311
312

    var_Get( p_enc, ENC_CFG_PREFIX "keyint", &val );
    p_sys->i_key_int = val.i_int;

    var_Get( p_enc, ENC_CFG_PREFIX "bframes", &val );
    p_sys->i_b_frames = val.i_int;

    var_Get( p_enc, ENC_CFG_PREFIX "vt", &val );
313
    p_sys->i_vtolerance = val.i_int * 1000;
314
315
316
317

    var_Get( p_enc, ENC_CFG_PREFIX "interlace", &val );
    p_sys->b_interlace = val.b_bool;

318
319
320
    var_Get( p_enc, ENC_CFG_PREFIX "interlace-me", &val );
    p_sys->b_interlace_me = val.b_bool;

321
    var_Get( p_enc, ENC_CFG_PREFIX "pre-me", &val );
322
323
    p_sys->b_pre_me = val.b_bool;

324
    var_Get( p_enc, ENC_CFG_PREFIX "hurry-up", &val );
325
326
327
328
329
330
331
    p_sys->b_hurry_up = val.b_bool;
    if( p_sys->b_hurry_up )
    {
        /* hurry up mode needs noise reduction, even small */
        p_sys->i_noise_reduction = 1;
    }

332
    var_Get( p_enc, ENC_CFG_PREFIX "rc-buffer-size", &val );
333
    p_sys->i_rc_buffer_size = val.i_int;
334
    var_Get( p_enc, ENC_CFG_PREFIX "rc-buffer-aggressivity", &val );
335
336
    p_sys->f_rc_buffer_aggressivity = val.f_float;

337
    var_Get( p_enc, ENC_CFG_PREFIX "i-quant-factor", &val );
338
339
    p_sys->f_i_quant_factor = val.f_float;

340
    var_Get( p_enc, ENC_CFG_PREFIX "noise-reduction", &val );
341
342
    p_sys->i_noise_reduction = val.i_int;

343
    var_Get( p_enc, ENC_CFG_PREFIX "mpeg4-matrix", &val );
344
345
    p_sys->b_mpeg4_matrix = val.b_bool;

gbazin's avatar
gbazin committed
346
347
348
349
    var_Get( p_enc, ENC_CFG_PREFIX "qscale", &val );
    if( val.f_float < 0.01 || val.f_float > 255.0 ) val.f_float = 0;
    p_sys->i_quality = (int)(FF_QP2LAMBDA * val.f_float + 0.5);

350
    var_Get( p_enc, ENC_CFG_PREFIX "hq", &val );
351
    p_sys->i_hq = FF_MB_DECISION_RD;
352
353
354
355
356
357
358
359
360
361
362
    if( val.psz_string && *val.psz_string )
    {
        if( !strcmp( val.psz_string, "rd" ) )
            p_sys->i_hq = FF_MB_DECISION_RD;
        else if( !strcmp( val.psz_string, "bits" ) )
            p_sys->i_hq = FF_MB_DECISION_BITS;
        else if( !strcmp( val.psz_string, "simple" ) )
            p_sys->i_hq = FF_MB_DECISION_SIMPLE;
        else
            p_sys->i_hq = FF_MB_DECISION_RD;
    }
363
364
365
    else
        p_sys->i_hq = FF_MB_DECISION_RD;
    free( val.psz_string );
366
367
368
369
370
371
372
373

    var_Get( p_enc, ENC_CFG_PREFIX "qmin", &val );
    p_sys->i_qmin = val.i_int;
    var_Get( p_enc, ENC_CFG_PREFIX "qmax", &val );
    p_sys->i_qmax = val.i_int;
    var_Get( p_enc, ENC_CFG_PREFIX "trellis", &val );
    p_sys->b_trellis = val.b_bool;

gbazin's avatar
gbazin committed
374
375
376
377
    var_Get( p_enc, ENC_CFG_PREFIX "strict", &val );
    if( val.i_int < - 1 || val.i_int > 1 ) val.i_int = 0;
    p_context->strict_std_compliance = val.i_int;

378
379
380
381
382
383
384
385
386
387
388
389
390
    var_Get( p_enc, ENC_CFG_PREFIX "lumi-masking", &val );
    p_sys->f_lumi_masking = val.f_float;
    var_Get( p_enc, ENC_CFG_PREFIX "dark-masking", &val );
    p_sys->f_dark_masking = val.f_float;
    var_Get( p_enc, ENC_CFG_PREFIX "p-masking", &val );
    p_sys->f_p_masking = val.f_float;
    var_Get( p_enc, ENC_CFG_PREFIX "border-masking", &val );
    p_sys->f_border_masking = val.f_float;
    var_Get( p_enc, ENC_CFG_PREFIX "luma-elim-threshold", &val );
    p_sys->i_luma_elim = val.i_int;
    var_Get( p_enc, ENC_CFG_PREFIX "chroma-elim-threshold", &val );
    p_sys->i_chroma_elim = val.i_int;

391
#if LIBAVCODEC_VERSION_INT >= ((51<<16)+(40<<8)+4)
392
    var_Get( p_enc, ENC_CFG_PREFIX "aac-profile", &val );
393
    p_sys->i_aac_profile = FF_PROFILE_AAC_LOW;
394
395
396
397
398
399
400
401
402
403
404
405
406
    if( val.psz_string && *val.psz_string )
    {
        if( !strncmp( val.psz_string, "main", 4 ) )
            p_sys->i_aac_profile = FF_PROFILE_AAC_MAIN;
        else if( !strncmp( val.psz_string, "low", 3 ) )
            p_sys->i_aac_profile = FF_PROFILE_AAC_LOW;
#if 0    /* Not supported by FAAC encoder */
        else if( !strncmp( val.psz_string, "ssr", 3 ) )
            p_sys->i_aac_profile = FF_PROFILE_AAC_SSR;
#endif
        else  if( !strncmp( val.psz_string, "ltp", 3 ) )
            p_sys->i_aac_profile = FF_PROFILE_AAC_LTP;
        else
407
        {
408
409
            msg_Warn( p_enc, "unknown AAC profile requested, setting it to low" );
            p_sys->i_aac_profile = FF_PROFILE_AAC_LOW;
410
        }
411
    }
412
    free( val.psz_string );
413
#endif
414

gbazin's avatar
   
gbazin committed
415
416
    if( p_enc->fmt_in.i_cat == VIDEO_ES )
    {
417
418
        int i_aspect_num, i_aspect_den;

419
420
421
422
423
424
425
426
        if( !p_enc->fmt_in.video.i_width || !p_enc->fmt_in.video.i_height )
        {
            msg_Warn( p_enc, "invalid size %ix%i", p_enc->fmt_in.video.i_width,
                      p_enc->fmt_in.video.i_height );
            free( p_sys );
            return VLC_EGENERIC;
        }

gbazin's avatar
   
gbazin committed
427
428
        p_context->width = p_enc->fmt_in.video.i_width;
        p_context->height = p_enc->fmt_in.video.i_height;
429
430
431
        if( p_enc->fmt_out.i_codec == VLC_FOURCC('m', 'p', '2', 'v')
             && (p_context->width > 720 || p_context->height > 576) )
            p_context->level = 4; /* High level */
gbazin's avatar
   
gbazin committed
432

433
434
        p_context->time_base.num = p_enc->fmt_in.video.i_frame_rate_base;
        p_context->time_base.den = p_enc->fmt_in.video.i_frame_rate;
gbazin's avatar
   
gbazin committed
435

436
437
438
439
440
441
442
443
        /* Defaults from ffmpeg.c */
        p_context->qblur = 0.5;
        p_context->qcompress = 0.5;
        p_context->b_quant_offset = 1.25;
        p_context->b_quant_factor = 1.25;
        p_context->i_quant_offset = 0.0;
        p_context->i_quant_factor = -0.8;

444
445
446
447
448
449
450
        p_context->lumi_masking = p_sys->f_lumi_masking;
        p_context->dark_masking = p_sys->f_dark_masking;
        p_context->p_masking = p_sys->f_p_masking;
        p_context->border_masking = p_sys->f_border_masking;
        p_context->luma_elim_threshold = p_sys->i_luma_elim;
        p_context->chroma_elim_threshold = p_sys->i_chroma_elim;

451
452
        if( p_sys->i_key_int > 0 )
            p_context->gop_size = p_sys->i_key_int;
453
        p_context->max_b_frames =
454
            __MAX( __MIN( p_sys->i_b_frames, FF_MAX_B_FRAMES ), 0 );
455
        p_context->b_frame_strategy = 0;
456
        if( !p_context->max_b_frames  &&
457
458
            (  p_enc->fmt_out.i_codec == VLC_FOURCC('m', 'p', '2', 'v') ||
               p_enc->fmt_out.i_codec == VLC_FOURCC('m', 'p', '1', 'v') ) )
459
            p_context->flags |= CODEC_FLAG_LOW_DELAY;
460

461
        av_reduce( &i_aspect_num, &i_aspect_den,
462
463
                   p_enc->fmt_in.video.i_aspect,
                   VOUT_ASPECT_FACTOR, 1 << 30 /* something big */ );
464
465
466
467
        av_reduce( &p_context->sample_aspect_ratio.num,
                   &p_context->sample_aspect_ratio.den,
                   i_aspect_num * (int64_t)p_context->height,
                   i_aspect_den * (int64_t)p_context->width, 1 << 30 );
gbazin's avatar
   
gbazin committed
468

469
470
471
472
        p_sys->i_buffer_out = p_context->height * p_context->width * 3;
        if( p_sys->i_buffer_out < FF_MIN_BUFFER_SIZE )
            p_sys->i_buffer_out = FF_MIN_BUFFER_SIZE;
        p_sys->p_buffer_out = malloc( p_sys->i_buffer_out );
gbazin's avatar
   
gbazin committed
473

474
        p_enc->fmt_in.i_codec = VLC_FOURCC('I','4','2','0');
475
476
477
        p_enc->fmt_in.video.i_chroma = p_enc->fmt_in.i_codec;
        GetFfmpegChroma( &p_context->pix_fmt, p_enc->fmt_in.video );

478
479
480
481
482
483
484
485
        if( p_codec->pix_fmts )
        {
            const enum PixelFormat *p = p_codec->pix_fmts;
            for( ; *p != -1; p++ )
            {
                if( *p == p_context->pix_fmt ) break;
            }
            if( *p == -1 ) p_context->pix_fmt = p_codec->pix_fmts[0];
486
487
            GetVlcChroma( &p_enc->fmt_in.video, p_context->pix_fmt );
            p_enc->fmt_in.i_codec = p_enc->fmt_in.video.i_chroma;
488
        }
Christophe Massiot's avatar
Christophe Massiot committed
489

490

491
492
        if ( p_sys->f_i_quant_factor != 0.0 )
            p_context->i_quant_factor = p_sys->f_i_quant_factor;
493

494
        p_context->noise_reduction = p_sys->i_noise_reduction;
495

496
        if ( p_sys->b_mpeg4_matrix )
497
        {
498
499
            p_context->intra_matrix = mpeg4_default_intra_matrix;
            p_context->inter_matrix = mpeg4_default_non_intra_matrix;
Christophe Massiot's avatar
Christophe Massiot committed
500
501
        }

502
        if ( p_sys->b_pre_me )
Christophe Massiot's avatar
Christophe Massiot committed
503
504
505
506
        {
            p_context->pre_me = 1;
            p_context->me_pre_cmp = FF_CMP_CHROMA;
        }
507

508
        if ( p_sys->b_interlace )
509
        {
510
511
            if ( p_context->height <= 280 )
            {
512
513
514
515
                if ( p_context->height != 16 || p_context->width != 16 )
                    msg_Warn( p_enc,
                        "disabling interlaced video because height=%d <= 280",
                        p_context->height );
516
517
518
519
520
521
522
            }
            else
            {
                p_context->flags |= CODEC_FLAG_INTERLACED_DCT;
                if ( p_sys->b_interlace_me )
                    p_context->flags |= CODEC_FLAG_INTERLACED_ME;
            }
523
524
        }

aballier's avatar
aballier committed
525
#if LIBAVCODEC_VERSION_INT < ((52<<16)+(0<<8)+0)
526
        if ( p_sys->b_trellis )
527
            p_context->flags |= CODEC_FLAG_TRELLIS_QUANT;
aballier's avatar
aballier committed
528
529
530
#else
        p_context->trellis = p_sys->b_trellis;
#endif
531

532
        if ( p_sys->i_qmin > 0 && p_sys->i_qmin == p_sys->i_qmax )
533
534
            p_context->flags |= CODEC_FLAG_QSCALE;

535
536
537
        if ( p_enc->i_threads >= 1 )
            p_context->thread_count = p_enc->i_threads;

538
539
        if( p_sys->i_vtolerance > 0 )
            p_context->bit_rate_tolerance = p_sys->i_vtolerance;
540

dionoea's avatar
dionoea committed
541
542
        /* usually if someone sets bitrate, he likes more to get that bitrate
         * over quality should help 'normal' user to get asked bitrate
543
544
545
546
         */
        if( p_enc->fmt_out.i_bitrate > 0 && p_sys->i_qmax == 0 && p_sys->i_qmin == 0 )
        {
            p_sys->i_qmax = 51;
547
            p_sys->i_qmin = 3;
548
549
        }

550
        if( p_sys->i_qmin > 0 )
551
        {
552
            p_context->mb_qmin = p_context->qmin = p_sys->i_qmin;
553
            p_context->mb_lmin = p_context->lmin = p_sys->i_qmin * FF_QP2LAMBDA;
554
        }
555
        if( p_sys->i_qmax > 0 )
556
        {
557
            p_context->mb_qmax = p_context->qmax = p_sys->i_qmax;
558
            p_context->mb_lmax = p_context->lmax = p_sys->i_qmax * FF_QP2LAMBDA;
559
        }
560
561
        p_context->max_qdiff = 3;

562
        p_context->mb_decision = p_sys->i_hq;
gbazin's avatar
gbazin committed
563
564
565
566
567

        if( p_sys->i_quality )
        {
            p_context->flags |= CODEC_FLAG_QSCALE;
            p_context->global_quality = p_sys->i_quality;
dionoea's avatar
dionoea committed
568
569
        }
        else
570
571
572
573
574
575
576
577
578
        {
            p_context->rc_qsquish = 1.0;
            p_context->rc_max_rate = p_enc->fmt_out.i_bitrate;
            p_context->rc_min_rate = p_enc->fmt_out.i_bitrate;
            p_context->rc_buffer_size = p_sys->i_rc_buffer_size;
            /* This is from ffmpeg's ffmpeg.c : */
            p_context->rc_initial_buffer_occupancy
                = p_sys->i_rc_buffer_size * 3/4;
            p_context->rc_buffer_aggressivity = p_sys->f_rc_buffer_aggressivity;
gbazin's avatar
gbazin committed
579
        }
gbazin's avatar
   
gbazin committed
580
581
582
    }
    else if( p_enc->fmt_in.i_cat == AUDIO_ES )
    {
583
584
585
586
        /* work around bug in libmp3lame encoding */
        if( i_codec_id == CODEC_ID_MP3 && p_enc->fmt_in.audio.i_channels > 2 )
            p_enc->fmt_in.audio.i_channels = 2;

gbazin's avatar
   
gbazin committed
587
        p_enc->fmt_in.i_codec  = AOUT_FMT_S16_NE;
588
589
        p_context->sample_rate = p_enc->fmt_out.audio.i_rate;
        p_context->channels    = p_enc->fmt_out.audio.i_channels;
590

591
592
593
        if ( p_enc->fmt_out.i_codec == VLC_FOURCC('m','p','4','a') )
        {
            /* XXX: FAAC does resample only when setting the INPUT samplerate
dionoea's avatar
dionoea committed
594
             * to the desired value (-R option of the faac frontend)
595
            p_enc->fmt_in.audio.i_rate = p_context->sample_rate;*/
596
#if LIBAVCODEC_VERSION_INT >= ((51<<16)+(40<<8)+4)
597
        /* Ignore FF_PROFILE_UNKNOWN */
598
        if( p_sys->i_aac_profile >= FF_PROFILE_AAC_MAIN )
599
            p_context->profile = p_sys->i_aac_profile;
600
#endif
601
        }
gbazin's avatar
   
gbazin committed
602
603
604
    }

    /* Misc parameters */
gbazin's avatar
   
gbazin committed
605
    p_context->bit_rate = p_enc->fmt_out.i_bitrate;
gbazin's avatar
   
gbazin committed
606

gbazin's avatar
   
gbazin committed
607
    if( i_codec_id == CODEC_ID_RAWVIDEO )
gbazin's avatar
   
gbazin committed
608
    {
609
        /* XXX: hack: Force same codec (will be handled by transcode) */
610
611
        p_enc->fmt_in.video.i_chroma = p_enc->fmt_in.i_codec = p_enc->fmt_out.i_codec;
        GetFfmpegChroma( &p_context->pix_fmt, p_enc->fmt_in.video );
gbazin's avatar
   
gbazin committed
612
613
614
615
616
617
618
    }

    /* Make sure we get extradata filled by the encoder */
    p_context->extradata_size = 0;
    p_context->extradata = NULL;
    p_context->flags |= CODEC_FLAG_GLOBAL_HEADER;

Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
619
    vlc_mutex_lock( &avcodec_lock );
620

gbazin's avatar
   
gbazin committed
621
    if( avcodec_open( p_context, p_codec ) )
gbazin's avatar
   
gbazin committed
622
    {
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
623
        vlc_mutex_unlock( &avcodec_lock );
624
625
626
        if( p_enc->fmt_in.i_cat == AUDIO_ES &&
             (p_context->channels > 2 || i_codec_id == CODEC_ID_MP2
               || i_codec_id == CODEC_ID_MP3) )
gbazin's avatar
   
gbazin committed
627
        {
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
            if( p_context->channels > 2 )
            {
                p_context->channels = 2;
                p_enc->fmt_in.audio.i_channels = 2; // FIXME
                msg_Warn( p_enc, "stereo mode selected (codec limitation)" );
            }

            if( i_codec_id == CODEC_ID_MP2 || i_codec_id == CODEC_ID_MP3 )
            {
                int i_frequency, i;

                for ( i_frequency = 0; i_frequency < 6; i_frequency++ )
                {
                    if ( p_enc->fmt_out.audio.i_rate
                            == mpa_freq_tab[i_frequency] )
                        break;
                }
                if ( i_frequency == 6 )
                {
                    msg_Err( p_enc, "MPEG audio doesn't support frequency=%d",
                             p_enc->fmt_out.audio.i_rate );
                    free( p_sys );
                    return VLC_EGENERIC;
                }

                for ( i = 1; i < 14; i++ )
                {
                    if ( p_enc->fmt_out.i_bitrate / 1000
                          <= mpa_bitrate_tab[i_frequency / 3][i] )
                        break;
                }
                if ( p_enc->fmt_out.i_bitrate / 1000
                      != mpa_bitrate_tab[i_frequency / 3][i] )
                {
                    msg_Warn( p_enc,
                              "MPEG audio doesn't support bitrate=%d, using %d",
                              p_enc->fmt_out.i_bitrate,
                              mpa_bitrate_tab[i_frequency / 3][i] * 1000 );
                    p_enc->fmt_out.i_bitrate =
                        mpa_bitrate_tab[i_frequency / 3][i] * 1000;
                    p_context->bit_rate = p_enc->fmt_out.i_bitrate;
                }
            }

            p_context->codec = NULL;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
673
            vlc_mutex_lock( &avcodec_lock );
gbazin's avatar
   
gbazin committed
674
675
            if( avcodec_open( p_context, p_codec ) )
            {
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
676
                vlc_mutex_unlock( &avcodec_lock );
gbazin's avatar
   
gbazin committed
677
                msg_Err( p_enc, "cannot open encoder" );
dionoea's avatar
dionoea committed
678
679
                intf_UserFatal( p_enc, false,
                                _("Streaming / Transcoding failed"),
680
                                _("VLC could not open the encoder.") );
681
                free( p_sys );
gbazin's avatar
   
gbazin committed
682
683
684
685
686
687
                return VLC_EGENERIC;
            }
        }
        else
        {
            msg_Err( p_enc, "cannot open encoder" );
688
            intf_UserFatal( p_enc, false, _("Streaming / Transcoding failed"),
689
                            _("VLC could not open the encoder.") );
690
            free( p_sys );
gbazin's avatar
   
gbazin committed
691
692
            return VLC_EGENERIC;
        }
gbazin's avatar
   
gbazin committed
693
    }
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
694
    vlc_mutex_unlock( &avcodec_lock );
gbazin's avatar
   
gbazin committed
695

gbazin's avatar
   
gbazin committed
696
    p_enc->fmt_out.i_extra = p_context->extradata_size;
697
698
699
700
701
702
    if( p_enc->fmt_out.i_extra )
    {
        p_enc->fmt_out.p_extra = malloc( p_enc->fmt_out.i_extra );
        memcpy( p_enc->fmt_out.p_extra, p_context->extradata,
                p_enc->fmt_out.i_extra );
    }
gbazin's avatar
   
gbazin committed
703
704
    p_context->flags &= ~CODEC_FLAG_GLOBAL_HEADER;

gbazin's avatar
   
gbazin committed
705
706
    if( p_enc->fmt_in.i_cat == AUDIO_ES )
    {
707
708
        p_sys->i_buffer_out = 2 * AVCODEC_MAX_AUDIO_FRAME_SIZE;
        p_sys->p_buffer_out = malloc( p_sys->i_buffer_out );
gbazin's avatar
   
gbazin committed
709
710
        p_sys->i_frame_size = p_context->frame_size * 2 * p_context->channels;
        p_sys->p_buffer = malloc( p_sys->i_frame_size );
711
        p_enc->fmt_out.audio.i_blockalign = p_context->block_align;
gbazin's avatar
   
gbazin committed
712
713
    }

gbazin's avatar
   
gbazin committed
714
715
    msg_Dbg( p_enc, "found encoder %s", psz_namecodec );

gbazin's avatar
   
gbazin committed
716
717
718
    return VLC_SUCCESS;
}

719
720
721
/****************************************************************************
 * Ffmpeg threading system
 ****************************************************************************/
722
static void* FfmpegThread( vlc_object_t *p_this )
723
{
724
    struct thread_context_t *p_context = (struct thread_context_t *)p_this;
725
    int canc = vlc_savecancel ();
726
    while ( vlc_object_alive (p_context) && !p_context->b_error )
727
728
    {
        vlc_mutex_lock( &p_context->lock );
729
        while ( !p_context->b_work && vlc_object_alive (p_context) && !p_context->b_error )
730
731
732
733
734
        {
            vlc_cond_wait( &p_context->cond, &p_context->lock );
        }
        p_context->b_work = 0;
        vlc_mutex_unlock( &p_context->lock );
735
        if ( !vlc_object_alive (p_context) || p_context->b_error )
736
737
738
739
740
741
742
743
744
745
746
747
748
749
            break;

        if ( p_context->pf_func )
        {
            p_context->i_ret = p_context->pf_func( p_context->p_context,
                                                   p_context->arg );
        }

        vlc_mutex_lock( &p_context->lock );
        p_context->b_done = 1;
        vlc_cond_signal( &p_context->cond );
        vlc_mutex_unlock( &p_context->lock );
    }

750
    vlc_restorecancel (canc);
751
    return NULL;
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
}

static int FfmpegExecute( AVCodecContext *s,
                          int (*pf_func)(AVCodecContext *c2, void *arg2),
                          void **arg, int *ret, int count )
{
    struct thread_context_t ** pp_contexts =
                         (struct thread_context_t **)s->thread_opaque;
    int i;

    /* Note, we can be certain that this is not called with the same
     * AVCodecContext by different threads at the same time */
    for ( i = 0; i < count; i++ )
    {
        vlc_mutex_lock( &pp_contexts[i]->lock );
        pp_contexts[i]->arg = arg[i];
        pp_contexts[i]->pf_func = pf_func;
        pp_contexts[i]->i_ret = 12345;
        pp_contexts[i]->b_work = 1;
        vlc_cond_signal( &pp_contexts[i]->cond );
        vlc_mutex_unlock( &pp_contexts[i]->lock );
    }
    for ( i = 0; i < count; i++ )
    {
        vlc_mutex_lock( &pp_contexts[i]->lock );
        while ( !pp_contexts[i]->b_done )
        {
            vlc_cond_wait( &pp_contexts[i]->cond, &pp_contexts[i]->lock );
        }
        pp_contexts[i]->b_done = 0;
        pp_contexts[i]->pf_func = NULL;
        vlc_mutex_unlock( &pp_contexts[i]->lock );

        if ( ret )
        {
            ret[i] = pp_contexts[i]->i_ret;
        }
    }

    return 0;
}

gbazin's avatar
   
gbazin committed
794
795
796
797
798
799
800
801
/****************************************************************************
 * EncodeVideo: the whole thing
 ****************************************************************************/
static block_t *EncodeVideo( encoder_t *p_enc, picture_t *p_pict )
{
    encoder_sys_t *p_sys = p_enc->p_sys;
    AVFrame frame;
    int i_out, i_plane;
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817

    if ( !p_sys->b_inited && p_enc->i_threads >= 1 )
    {
        struct thread_context_t ** pp_contexts;
        int i;

        p_sys->b_inited = 1;
        pp_contexts = malloc( sizeof(struct thread_context_t *)
                                 * p_enc->i_threads );
        p_sys->p_context->thread_opaque = (void *)pp_contexts;

        for ( i = 0; i < p_enc->i_threads; i++ )
        {
            pp_contexts[i] = vlc_object_create( p_enc,
                                     sizeof(struct thread_context_t) );
            pp_contexts[i]->p_context = p_sys->p_context;
818
            vlc_mutex_init( &pp_contexts[i]->lock );
819
            vlc_cond_init( &pp_contexts[i]->cond );
820
821
822
            pp_contexts[i]->b_work = 0;
            pp_contexts[i]->b_done = 0;
            if ( vlc_thread_create( pp_contexts[i], "encoder", FfmpegThread,
823
                                    VLC_THREAD_PRIORITY_VIDEO, false ) )
824
825
826
827
828
829
830
831
            {
                msg_Err( p_enc, "cannot spawn encoder thread, expect to die soon" );
                return NULL;
            }
        }

        p_sys->p_context->execute = FfmpegExecute;
    }
gbazin's avatar
   
gbazin committed
832

Laurent Aimar's avatar
Laurent Aimar committed
833
    memset( &frame, 0, sizeof( AVFrame ) );
gbazin's avatar
   
gbazin committed
834
835
836
837
838
839
    for( i_plane = 0; i_plane < p_pict->i_planes; i_plane++ )
    {
        frame.data[i_plane] = p_pict->p[i_plane].p_pixels;
        frame.linesize[i_plane] = p_pict->p[i_plane].i_pitch;
    }

840
841
842
    /* Let ffmpeg select the frame type */
    frame.pict_type = 0;

843
    frame.repeat_pict = p_pict->i_nb_fields - 2;
844
    frame.interlaced_frame = !p_pict->b_progressive;
845
    frame.top_field_first = !!p_pict->b_top_field_first;
846

gbazin's avatar
   
gbazin committed
847
    /* Set the pts of the frame being encoded (segfaults with mpeg4!)*/
848
    if( p_enc->fmt_out.i_codec != VLC_FOURCC( 'm', 'p', '4', 'v' ) )
Christophe Massiot's avatar
Christophe Massiot committed
849
    {
850
        frame.pts = p_pict->date ? p_pict->date : (int64_t)AV_NOPTS_VALUE;
851

852
        if ( p_sys->b_hurry_up && frame.pts != (int64_t)AV_NOPTS_VALUE )
Christophe Massiot's avatar
Christophe Massiot committed
853
        {
854
855
            mtime_t current_date = mdate();

856
            if ( current_date + HURRY_UP_GUARD3 > frame.pts )
857
858
            {
                p_sys->p_context->mb_decision = FF_MB_DECISION_SIMPLE;
aballier's avatar
aballier committed
859
#if LIBAVCODEC_VERSION_INT < ((52<<16)+(0<<8)+0)
860
                p_sys->p_context->flags &= ~CODEC_FLAG_TRELLIS_QUANT;
aballier's avatar
aballier committed
861
862
863
#else
                p_sys->p_context->trellis = 0;
#endif
864
865
866
867
                msg_Dbg( p_enc, "hurry up mode 3" );
            }
            else
            {
868
                p_sys->p_context->mb_decision = p_sys->i_hq;
869

870
                if ( current_date + HURRY_UP_GUARD2 > frame.pts )
871
                {
aballier's avatar
aballier committed
872
#if LIBAVCODEC_VERSION_INT < ((52<<16)+(0<<8)+0)
873
                    p_sys->p_context->flags &= ~CODEC_FLAG_TRELLIS_QUANT;
aballier's avatar
aballier committed
874
875
876
#else
                    p_sys->p_context->trellis = 0;
#endif
877
                    p_sys->p_context->noise_reduction = p_sys->i_noise_reduction
878
                         + (HURRY_UP_GUARD2 + current_date - frame.pts) / 500;
879
880
881
882
                    msg_Dbg( p_enc, "hurry up mode 2" );
                }
                else
                {
aballier's avatar
aballier committed
883
#if LIBAVCODEC_VERSION_INT < ((52<<16)+(0<<8)+0)
884
                    if ( p_sys->b_trellis )
885
                        p_sys->p_context->flags |= CODEC_FLAG_TRELLIS_QUANT;
aballier's avatar
aballier committed
886
887
888
#else
                    p_sys->p_context->trellis = p_sys->b_trellis;
#endif
889

890
                    p_sys->p_context->noise_reduction =
891
                        p_sys->i_noise_reduction;
892
893
894
                }
            }

895
            if ( current_date + HURRY_UP_GUARD1 > frame.pts )
896
            {
897
898
                frame.pict_type = FF_P_TYPE;
                /* msg_Dbg( p_enc, "hurry up mode 1 %lld", current_date + HURRY_UP_GUARD1 - frame.pts ); */
899
            }
Christophe Massiot's avatar
Christophe Massiot committed
900
901
        }
    }
gbazin's avatar
   
gbazin committed
902
    else
Christophe Massiot's avatar
Christophe Massiot committed
903
    {
904
        frame.pts = (int64_t)AV_NOPTS_VALUE;
Christophe Massiot's avatar
Christophe Massiot committed
905
    }
gbazin's avatar
   
gbazin committed
906

907
    if ( frame.pts != (int64_t)AV_NOPTS_VALUE && frame.pts != 0 )
908
909
910
    {
        if ( p_sys->i_last_pts == frame.pts )
        {
gbazin's avatar
gbazin committed
911
            msg_Warn( p_enc, "almost fed libavcodec with two frames with the "
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
912
                      "same PTS (%"PRId64 ")", frame.pts );
913
914
            return NULL;
        }
915
916
917
        else if ( p_sys->i_last_pts > frame.pts )
        {
            msg_Warn( p_enc, "almost fed libavcodec with a frame in the "
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
918
                      "past (current: %"PRId64 ", last: %"PRId64")",
919
920
921
                      frame.pts, p_sys->i_last_pts );
            return NULL;
        }
922
923
924
925
926
        else
        {
            p_sys->i_last_pts = frame.pts;
        }
    }
gbazin's avatar
   
gbazin committed
927

gbazin's avatar
gbazin committed
928
929
    frame.quality = p_sys->i_quality;

930
931
932
933
934
935
936
937
938
    /* Ugly work-around for stupid libavcodec behaviour */
    p_sys->i_framenum++;
    p_sys->pi_delay_pts[p_sys->i_framenum % MAX_FRAME_DELAY] = frame.pts;
    frame.pts = p_sys->i_framenum * AV_TIME_BASE *
        p_enc->fmt_in.video.i_frame_rate_base;
    frame.pts += p_enc->fmt_in.video.i_frame_rate - 1;
    frame.pts /= p_enc->fmt_in.video.i_frame_rate;
    /* End work-around */

939
940
    i_out = avcodec_encode_video( p_sys->p_context, p_sys->p_buffer_out,
                                  p_sys->i_buffer_out, &frame );
Christophe Massiot's avatar
Christophe Massiot committed
941

gbazin's avatar
   
gbazin committed
942
943
944
945
946
    if( i_out > 0 )
    {
        block_t *p_block = block_New( p_enc, i_out );
        memcpy( p_block->p_buffer, p_sys->p_buffer_out, i_out );

947
        /* FIXME, 3-2 pulldown is not handled correctly */
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
948
        p_block->i_length = INT64_C(1000000) *
949
950
951
952
953
954
955
956
            p_enc->fmt_in.video.i_frame_rate_base /
                p_enc->fmt_in.video.i_frame_rate;

        if( !p_sys->p_context->max_b_frames || !p_sys->p_context->delay )
        {
            /* No delay -> output pts == input pts */
            p_block->i_pts = p_block->i_dts = p_pict->date;
        }
957
        else if( p_sys->p_context->coded_frame->pts != (int64_t)AV_NOPTS_VALUE &&
gbazin's avatar
gbazin committed
958
            p_sys->p_context->coded_frame->pts != 0 &&
gbazin's avatar
   
gbazin committed
959
960
961
            p_sys->i_buggy_pts_detect != p_sys->p_context->coded_frame->pts )
        {
            p_sys->i_buggy_pts_detect = p_sys->p_context->coded_frame->pts;
962
            p_block->i_pts = p_sys->p_context->coded_frame->pts;
gbazin's avatar
   
gbazin committed
963

964
965
            /* Ugly work-around for stupid libavcodec behaviour */
            {
966
967
968
                int64_t i_framenum = p_block->i_pts *
                    p_enc->fmt_in.video.i_frame_rate /
                    p_enc->fmt_in.video.i_frame_rate_base / AV_TIME_BASE;
gbazin's avatar
   
gbazin committed
969

970
                p_block->i_pts = p_sys->pi_delay_pts[i_framenum % MAX_FRAME_DELAY];
971
972
973
974
975
            }
            /* End work-around */

            if( p_sys->p_context->coded_frame->pict_type != FF_I_TYPE &&
                p_sys->p_context->coded_frame->pict_type != FF_P_TYPE )
gbazin's avatar
   
gbazin committed
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
            {
                p_block->i_dts = p_block->i_pts;
            }
            else
            {
                if( p_sys->i_last_ref_pts )
                {
                    p_block->i_dts = p_sys->i_last_ref_pts;
                }
                else
                {
                    /* Let's put something sensible */
                    p_block->i_dts = p_block->i_pts;
                }

                p_sys->i_last_ref_pts = p_block->i_pts;
            }
        }
        else
        {
            /* Buggy libavcodec which doesn't update coded_frame->pts
             * correctly */
            p_block->i_dts = p_block->i_pts = p_pict->date;
        }

1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
        switch ( p_sys->p_context->coded_frame->pict_type )
        {
        case FF_I_TYPE:
            p_block->i_flags |= BLOCK_FLAG_TYPE_I;
            break;
        case FF_P_TYPE:
            p_block->i_flags |= BLOCK_FLAG_TYPE_P;
            break;
        case FF_B_TYPE:
            p_block->i_flags |= BLOCK_FLAG_TYPE_B;
            break;
        }

gbazin's avatar
   
gbazin committed
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
        return p_block;
    }

    return NULL;
}

/****************************************************************************
 * EncodeAudio: the whole thing
 ****************************************************************************/
static block_t *EncodeAudio( encoder_t *p_enc, aout_buffer_t *p_aout_buf )
{
    encoder_sys_t *p_sys = p_enc->p_sys;
    block_t *p_block, *p_chain = NULL;
gbazin's avatar
   
gbazin committed
1027

1028
    uint8_t *p_buffer = p_aout_buf->p_buffer;
gbazin's avatar
   
gbazin committed
1029
1030
1031
1032
1033
    int i_samples = p_aout_buf->i_nb_samples;
    int i_samples_delay = p_sys->i_samples_delay;

    p_sys->i_pts = p_aout_buf->start_date -
                (mtime_t)1000000 * (mtime_t)p_sys->i_samples_delay /
gbazin's avatar
   
gbazin committed
1034
                (mtime_t)p_enc->fmt_in.audio.i_rate;
gbazin's avatar
   
gbazin committed
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045

    p_sys->i_samples_delay += i_samples;

    while( p_sys->i_samples_delay >= p_sys->p_context->frame_size )
    {
        int16_t *p_samples;
        int i_out;

        if( i_samples_delay )
        {
            /* Take care of the left-over from last time */
gbazin's avatar
   
gbazin committed
1046
            int i_delay_size = i_samples_delay * 2 *
gbazin's avatar
   
gbazin committed
1047
1048
1049
1050
1051
1052
                                 p_sys->p_context->channels;
            int i_size = p_sys->i_frame_size - i_delay_size;

            p_samples = (int16_t *)p_sys->p_buffer;
            memcpy( p_sys->p_buffer + i_delay_size, p_buffer, i_size );
            p_buffer -= i_delay_size;
gbazin's avatar
   
gbazin committed
1053
            i_samples += i_samples_delay;
gbazin's avatar
   
gbazin committed
1054
1055
1056
1057
1058
1059
1060
            i_samples_delay = 0;
        }
        else
        {
            p_samples = (int16_t *)p_buffer;
        }

1061
1062
        i_out = avcodec_encode_audio( p_sys->p_context, p_sys->p_buffer_out,
                                      p_sys->i_buffer_out, p_samples );
gbazin's avatar
   
gbazin committed
1063
1064
1065
1066
1067

#if 0
        msg_Warn( p_enc, "avcodec_encode_audio: %d", i_out );
#endif