]> git.sesse.net Git - vlc/blob - modules/codec/x264.c
codec 2nd round exept fo x264 (refs #438)
[vlc] / modules / codec / x264.c
1 /*****************************************************************************
2  * x264.c: h264 video encoder
3  *****************************************************************************
4  * Copyright (C) 2004-2006 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22  *****************************************************************************/
23
24 /*****************************************************************************
25  * Preamble
26  *****************************************************************************/
27 #include <vlc/vlc.h>
28 #include <vlc/vout.h>
29 #include <vlc/sout.h>
30 #include <vlc/decoder.h>
31
32 #include <x264.h>
33
34 #define SOUT_CFG_PREFIX "sout-x264-"
35
36 /*****************************************************************************
37  * Module descriptor
38  *****************************************************************************/
39 static int  Open ( vlc_object_t * );
40 static void Close( vlc_object_t * );
41
42 /* Frame-type options */
43
44 #define KEYINT_TEXT N_("Maximum GOP size")
45 #define KEYINT_LONGTEXT N_( "Sets maximum interval between IDR-frames." \
46     "Larger values save bits, thus improve quality for a given bitrate at " \
47     "the cost of seeking precision." )
48
49 #define MIN_KEYINT_TEXT N_("Minimum GOP size")
50 #define MIN_KEYINT_LONGTEXT N_( "Sets minimum interval between IDR-frames. " \
51     "In H.264, I-frames do not necessarily bound a closed GOP because it is " \
52     "allowable for a P-frame to be predicted from more frames than just the " \
53     "one frame before it (also see frameref). Therefore, I-frames are not " \
54     "necessarily seekable. IDR-Frames restrict subsequent P-frames from " \
55     "referring to any frame prior to the IDR-Frame. \n" \
56     "If scenecuts appear within this interval, they are still encoded as " \
57     "I-frames, but do not start a new GOP." )
58
59 #define SCENE_TEXT N_("Extra I-Frames aggressivity" )
60 #define SCENE_LONGTEXT N_( "Scene-cut detection. Controls how aggressively to " \
61     "insert extra I-frames. With small values of scenecut, the codec often has " \
62     "to force an I-frame when it would exceed keyint. Good values of scenecut " \
63     "may find a better location for the I-frame. Large values use more I-frames " \
64     "than necessary, thus wasting bits. -1 disables scene-cut detection, so " \
65     "I-frames are be inserted only every other keyint frames, which probably " \
66     "leads to ugly encoding artifacts. (1-100)." )
67
68 #define BFRAMES_TEXT N_("Number of B-frames between I and P (1 to 16)")
69 #define BFRAMES_LONGTEXT N_( "Number of consecutive B-frames between I and " \
70     "P-frames." )
71
72 #define B_ADAPT_TEXT N_("Adaptive B-frame decision")
73 #define B_ADAPT_LONGTEXT N_( "Force the specified number of " \
74     "consecutive B-frames to be used, except possibly before an I-frame. " )
75
76 #define B_BIAS_TEXT N_("Influences how often B-frames are used")
77 #define B_BIAS_LONGTEXT N_( "Bias the choice to use B-frames. Positive values " \
78     "cause more B-frames, negative values cause less B-frames. " )
79
80 #define BPYRAMID_TEXT N_("Keep some B-frames as references")
81 #define BPYRAMID_LONGTEXT N_( "Allows B-frames to be used as references for " \
82     "predicting other frames. Keeps the middle of 2+ consecutive B-frames " \
83     "as a reference, and reorders frame appropriately." )
84
85 #define CABAC_TEXT N_("CABAC")
86 #define CABAC_LONGTEXT N_( "CABAC (Context-Adaptive Binary Arithmetic "\
87     "Coding). Slightly slows down encoding and decoding, but should save " \
88     "10-15% bitrate." )
89
90 #define REF_TEXT N_("Number of reference frames (1 to 16)")
91 #define REF_LONGTEXT N_( "Number of previous frames used as predictors. " \
92     "This is effective in Anime, but seems to make little difference in " \
93     "live-action source material. Some decoders are unable to deal with " \
94     "large frameref values." )
95
96 #define NF_TEXT N_("Loop filter")
97 #define NF_LONGTEXT N_( "Deblocking loop filter (increases quality).")
98
99 /* Ratecontrol */
100
101 #define QP_TEXT N_("Set QP (0=lossless) (0 to 51)")
102 #define QP_LONGTEXT N_( "This selects the quantizer to use. " \
103     "Lower values result in better fidelity, but higher bitrates. 26 is a " \
104     "good default value." )
105
106 #define CRF_TEXT N_("Quality-based VBR (nominal QP) (0 to 51)")
107 #define CRF_LONGTEXT N_( "1-pass Quality-based VBR." )
108
109 #define QPMIN_TEXT N_("Set min QP")
110 #define QPMIN_LONGTEXT N_( "Minimum quantizer, 15/35 seems to be a useful " \
111     "range." )
112
113 #define QPMAX_TEXT N_("Set max QP")
114 #define QPMAX_LONGTEXT N_( "Maximum quantizer parameter." )
115
116 #define QPSTEP_TEXT N_("Set max QP step")
117 #define QPSTEP_LONGTEXT N_( "Max QP step between frames.")
118
119 #define RATETOL_TEXT N_("Average bitrate tolerance")
120 #define RATETOL_LONGTEXT N_( "Allowed variance in average. " \
121     "bitrate (in kbits/s).")
122
123 #define VBV_MAXRATE_TEXT N_("Max local bitrate")
124 #define VBV_MAXRATE_LONGTEXT N_( "Sets a maximum local bitrate in kbits/s.")
125
126 #define VBV_BUFSIZE_TEXT N_("VBV buffer")
127 #define VBV_BUFSIZE_LONGTEXT N_( "Averaging period for the maximum " \
128     "local bitrate in kbits.")
129
130 #define VBV_INIT_TEXT N_("Initial VBV buffer occupancy")
131 #define VBV_INIT_LONGTEXT N_( "Sets the initial buffer occupancy as a " \
132     "fraction of the buffer size.")
133
134 #define IPRATIO_TEXT N_("QP factor between I and P")
135 #define IPRATIO_LONGTEXT N_( "QP factor between I and P.")
136
137 #define PBRATIO_TEXT N_("QP factor between P and B")
138 #define PBRATIO_LONGTEXT N_( "QP factor between P and B.")
139
140 #define CHROMA_QP_OFFSET_TEXT N_("QP difference between chroma and luma")
141 #define CHROMA_QP_OFFSET_LONGTEXT N_( "QP difference between chroma and luma.")
142
143 #define QCOMP_TEXT N_("QP curve compression")
144 #define QCOMP_LONGTEXT N_( "QP curve compression. (0.0=CBR to 1.0=QCP)")
145
146 #define CPLXBLUR_TEXT N_("Reduce fluctuations in QP (before curve compression)")
147 #define CPLXBLUR_LONGTEXT N_( "Temporally blur complexity.")
148
149 #define QBLUR_TEXT N_("Reduce fluctuations in QP (after curve compression)")
150 #define QBLUR_LONGTEXT N_( "Temporally blur quants.")
151
152 /* Analysis */
153
154 #define ANALYSE_TEXT N_("Partitions to consider")
155 #define ANALYSE_LONGTEXT N_( "Partitions to consider in analyse mode: \n" \
156     " - none  : \n" \
157     " - fast  : i4x4\n" \
158     " - normal: i4x4,p8x8,(i8x8)\n" \
159     " - slow  : i4x4,p8x8,(i8x8),b8x8\n" \
160     " - all   : i4x4,p8x8,(i8x8),b8x8,p4x4\n" \
161     "(p4x4 requires p8x8. i8x8 requires 8x8dct).")
162
163 #define DIRECT_PRED_TEXT N_("Direct MV prediction mode")
164 #define DIRECT_PRED_LONGTEXT N_( "Direct MV prediction mode. ")
165      
166 #define WEIGHTB_TEXT N_("Weighted prediction for B-frames")
167 #define WEIGHTB_LONGTEXT N_( "Weighted prediction for B-frames.")
168
169 #define ME_TEXT N_("Integer pixel motion estimation method")
170 #define ME_LONGTEXT N_( "Selects the motion estimation algorithm: "\
171     " - dia: diamond search, radius 1 (fast)\n" \
172     " - hex: hexagonal search, radius 2\n" \
173     " - umh: uneven multi-hexagon search (better but slower)\n" \
174     " - esa: exhaustive search (extremely slow, primarily for testing)\n" )
175
176 #define MERANGE_TEXT N_("Maximum motion vector search range (0 to 64)")
177 #define MERANGE_LONGTEXT N_( "Maximum distance to search for motion estimation, "\
178     "measured from predicted position(s). Default of 16 is good for most footage, "\
179     "high motion sequences may benefit from settings between 24-32." )
180
181 #define SUBME_TEXT N_("Subpixel motion estimation and partition decision " \
182     "quality (1 to 6)")
183 #define SUBME_LONGTEXT N_( "This parameter controls quality versus speed " \
184     "tradeoffs involved in the motion estimation decision process " \
185     "(lower = quicker and higher = better quality)." )
186
187 #define B_RDO_TEXT N_("RD based mode decision for B-frames. Requires subme 6")
188 #define B_RDO_LONGTEXT N_( "RD based mode decision for B-frames. " )
189
190 #define MIXED_REFS_TEXT N_("Decide references on a per partition basis")
191 #define MIXED_REFS_LONGTEXT N_( "Allows each 8x8 or 16x8 partition to independently " \
192      "select a reference frame, as opposed to only one ref per macroblock." )
193
194 #define CHROMA_ME_TEXT N_("Ignore chroma in motion estimation")
195 #define CHROMA_ME_LONGTEXT N_( "Chroma ME for subpel and mode decision in P-frames.")
196
197 #define BIME_TEXT N_("Jointly optimize both MVs in B-frames")
198 #define BIME_LONGTEXT N_( "Joint bidirectional motion refinement.")
199
200 #define TRANSFORM_8X8DCT_TEXT N_("Adaptive spatial transform size")
201 #define TRANSFORM_8X8DCT_LONGTEXT N_( "SATD-based decision for 8x8 transform in inter-MBs.")
202
203 #define TRELLIS_TEXT N_("Trellis RD quantization (0,1,2). Requires CABAC")
204 #define TRELLIS_LONGTEXT N_( "Trellis RD quantization: \n" \
205      " - 0: disabled\n" \
206      " - 1: enabled only on the final encode of a MB\n" \
207      " - 2: enabled on all mode decisions\n" )
208
209 #define FAST_PSKIP_TEXT N_("Early SKIP detection on P-frames")
210 #define FAST_PSKIP_LONGTEXT N_( "Early SKIP detection on P-frames.")
211
212 #define NR_TEXT N_("Noise reduction")
213 #define NR_LONGTEXT N_( "Dct-domain noise reduction. Adaptive pseudo-deadzone.")
214
215 /* Input/Output */
216
217 #define ASM_TEXT N_("CPU optimizations")
218 #define ASM_LONGTEXT N_( "Use assembler CPU optimizations.")
219
220 #define PSNR_TEXT N_("PSNR calculation")
221 #define PSNR_LONGTEXT N_( "This has no effect on actual encoding quality, "\
222     "it just prevents the stats from being calculated (for speed)." )
223
224 #define VERBOSE_TEXT N_("Print stats for each frame")
225 #define VERBOSE_LONGTEXT N_( "Print stats for each frame.")
226
227 #if X264_BUILD >= 24
228 static char *enc_me_list[] =
229   { "", "dia", "hex", "umh", "esa" };
230 static char *enc_me_list_text[] =
231   { N_("default"), N_("dia"), N_("hex"), N_("umh"), N_("esa") };
232 #endif
233
234 static char *enc_analyse_list[] =
235   { "", "none", "fast", "normal", "slow", "all" };
236 static char *enc_analyse_list_text[] =
237   { N_("default"), N_("none"), N_("fast"), N_("normal"),
238     N_("slow"), N_("all") };
239
240 static char *direct_pred_list[] =
241   { "", "none", "spatial", "temporal" };
242 static char *direct_pred_list_text[] =
243   { N_("default"), N_("none"), N_("spatial"), N_("temporal") };
244
245 vlc_module_begin();
246     set_description( _("H.264/MPEG4 AVC encoder (using x264 library)"));
247     set_capability( "encoder", 200 );
248     set_callbacks( Open, Close );
249     set_category( CAT_INPUT );
250     set_subcategory( SUBCAT_INPUT_VCODEC );
251     
252 /* Frame-type options */
253
254     add_integer( SOUT_CFG_PREFIX "keyint", 250, NULL, KEYINT_TEXT,
255                  KEYINT_LONGTEXT, VLC_FALSE );
256
257     add_integer( SOUT_CFG_PREFIX "min-keyint", 25, NULL, MIN_KEYINT_TEXT,
258                  MIN_KEYINT_LONGTEXT, VLC_FALSE );
259         add_deprecated( SOUT_CFG_PREFIX "keyint-min", VLC_FALSE ); /* Deprecated since 0.8.5 */
260
261     add_integer( SOUT_CFG_PREFIX "scenecut", 40, NULL, SCENE_TEXT,
262                  SCENE_LONGTEXT, VLC_FALSE );
263         change_integer_range( -1, 100 );
264
265     add_integer( SOUT_CFG_PREFIX "bframes", 0, NULL, BFRAMES_TEXT,
266                  BFRAMES_LONGTEXT, VLC_FALSE );
267         change_integer_range( 0, 16 );
268
269 #if X264_BUILD >= 0x0013 /* r137 */
270     add_bool( SOUT_CFG_PREFIX "b-adapt", 1, NULL, B_ADAPT_TEXT,
271               B_ADAPT_LONGTEXT, VLC_FALSE );
272
273     add_integer( SOUT_CFG_PREFIX "b-bias", 0, NULL, B_BIAS_TEXT,
274                  B_BIAS_LONGTEXT, VLC_FALSE );
275         change_integer_range( -100, 100 );
276 #endif
277
278     add_bool( SOUT_CFG_PREFIX "bpyramid", 0, NULL, BPYRAMID_TEXT,
279               BPYRAMID_LONGTEXT, VLC_FALSE );
280
281     add_bool( SOUT_CFG_PREFIX "cabac", 1, NULL, CABAC_TEXT, CABAC_LONGTEXT,
282               VLC_FALSE );
283
284     add_integer( SOUT_CFG_PREFIX "ref", 1, NULL, REF_TEXT,
285                  REF_LONGTEXT, VLC_FALSE );
286         add_deprecated( SOUT_CFG_PREFIX "frameref", VLC_FALSE ); /* Deprecated since 0.8.5 */
287         change_integer_range( 1, 16 );
288
289     add_bool( SOUT_CFG_PREFIX "nf", 0, NULL, NF_TEXT,
290               NF_LONGTEXT, VLC_FALSE );
291         add_deprecated( SOUT_CFG_PREFIX "loopfilter", VLC_FALSE ); /* Deprecated since 0.8.5 */
292
293 /* Ratecontrol */
294
295     add_integer( SOUT_CFG_PREFIX "qp", 26, NULL, QP_TEXT, QP_LONGTEXT,
296                  VLC_FALSE );
297         change_integer_range( 0, 51 ); /* QP 0 -> lossless encoding */
298
299 #if X264_BUILD >= 37 /* r334 */
300     add_integer( SOUT_CFG_PREFIX "crf", 0, NULL, CRF_TEXT,
301                  CRF_LONGTEXT, VLC_FALSE );
302         change_integer_range( 0, 51 );
303 #endif
304
305     add_integer( SOUT_CFG_PREFIX "qpmin", 10, NULL, QPMIN_TEXT,
306                  QPMIN_LONGTEXT, VLC_FALSE );
307         add_deprecated( SOUT_CFG_PREFIX "qp-min", VLC_FALSE ); /* Deprecated since 0.8.5 */
308         change_integer_range( 0, 51 );
309
310     add_integer( SOUT_CFG_PREFIX "qpmax", 51, NULL, QPMAX_TEXT,
311                  QPMAX_LONGTEXT, VLC_FALSE );
312         add_deprecated( SOUT_CFG_PREFIX "qp-max", VLC_FALSE ); /* Deprecated since 0.8.5 */
313         change_integer_range( 0, 51 );
314
315     add_integer( SOUT_CFG_PREFIX "qpstep", 4, NULL, QPSTEP_TEXT,
316                  QPSTEP_LONGTEXT, VLC_FALSE );
317         change_integer_range( 0, 51 );
318
319     add_float( SOUT_CFG_PREFIX "ratetol", 1.0, NULL, RATETOL_TEXT,
320                RATETOL_LONGTEXT, VLC_FALSE );
321         add_deprecated( SOUT_CFG_PREFIX "tolerance", VLC_FALSE ); /* Deprecated since 0.8.5 */
322         change_float_range( 0, 100 );
323
324     add_integer( SOUT_CFG_PREFIX "vbv-maxrate", 0, NULL, VBV_MAXRATE_TEXT,
325                  VBV_MAXRATE_LONGTEXT, VLC_FALSE );
326
327     add_integer( SOUT_CFG_PREFIX "vbv-bufsize", 0, NULL, VBV_BUFSIZE_TEXT,
328                  VBV_BUFSIZE_LONGTEXT, VLC_FALSE );
329
330     add_float( SOUT_CFG_PREFIX "vbv-init", 0.9, NULL, VBV_INIT_TEXT,
331                VBV_INIT_LONGTEXT, VLC_FALSE );
332         change_float_range( 0, 1 );
333
334     add_float( SOUT_CFG_PREFIX "ipratio", 1.40, NULL, IPRATIO_TEXT,
335                IPRATIO_LONGTEXT, VLC_FALSE );
336         change_float_range( 0, 100 );
337
338     add_float( SOUT_CFG_PREFIX "pbratio", 1.30, NULL, PBRATIO_TEXT,
339                PBRATIO_LONGTEXT, VLC_FALSE );
340         change_float_range( 0, 100 );
341
342 #if X264_BUILD >= 23 /* r190 */
343     add_integer( SOUT_CFG_PREFIX "chroma-qp-offset", 0, NULL, CHROMA_QP_OFFSET_TEXT,
344                  CHROMA_QP_OFFSET_LONGTEXT, VLC_FALSE );
345 #endif
346
347     add_float( SOUT_CFG_PREFIX "qcomp", 0.60, NULL, QCOMP_TEXT,
348                QCOMP_LONGTEXT, VLC_FALSE );
349         change_float_range( 0, 1 );
350
351     add_float( SOUT_CFG_PREFIX "cplxblur", 20.0, NULL, CPLXBLUR_TEXT,
352                CPLXBLUR_LONGTEXT, VLC_FALSE );
353
354     add_float( SOUT_CFG_PREFIX "qblur", 0.5, NULL, QBLUR_TEXT,
355                QBLUR_LONGTEXT, VLC_FALSE );
356
357 /* Analysis */
358
359     add_string( SOUT_CFG_PREFIX "analyse", "all", NULL, ANALYSE_TEXT,
360                 ANALYSE_LONGTEXT, VLC_FALSE );
361         change_string_list( enc_analyse_list, enc_analyse_list_text, 0 );
362
363     add_string( SOUT_CFG_PREFIX "direct", "temporal", NULL, DIRECT_PRED_TEXT,
364                 DIRECT_PRED_LONGTEXT, VLC_FALSE );
365         change_string_list( direct_pred_list, direct_pred_list_text, 0 );
366
367 #if X264_BUILD >= 0x0012 /* r134 */
368     add_bool( SOUT_CFG_PREFIX "weightb", 0, NULL, WEIGHTB_TEXT,
369               WEIGHTB_LONGTEXT, VLC_FALSE );
370 #endif
371
372 #if X264_BUILD >= 24 /* r221 */
373     add_string( SOUT_CFG_PREFIX "me", "hex", NULL, ME_TEXT,
374                 ME_LONGTEXT, VLC_FALSE );
375         change_string_list( enc_me_list, enc_me_list_text, 0 );
376
377     add_integer( SOUT_CFG_PREFIX "merange", 16, NULL, MERANGE_TEXT,
378                  MERANGE_LONGTEXT, VLC_FALSE );
379         change_integer_range( 1, 64 );
380 #endif
381
382     add_integer( SOUT_CFG_PREFIX "subme", 5, NULL, SUBME_TEXT,
383                  SUBME_LONGTEXT, VLC_FALSE );
384         add_deprecated( SOUT_CFG_PREFIX "subpel", VLC_FALSE ); /* Deprecated since 0.8.5 */
385 #if X264_BUILD >= 30 /* r262 */
386         change_integer_range( 1, 6 );
387 #else
388         change_integer_range( 1, 5 );
389 #endif
390
391 #if X264_BUILD >= 41 /* r368 */
392     add_bool( SOUT_CFG_PREFIX "b-rdo", 0, NULL, B_RDO_TEXT,
393               B_RDO_LONGTEXT, VLC_FALSE );
394 #endif
395
396 #if X264_BUILD >= 36 /* r318 */
397     add_bool( SOUT_CFG_PREFIX "mixed-refs", 0, NULL, MIXED_REFS_TEXT,
398               MIXED_REFS_LONGTEXT, VLC_FALSE );
399 #endif
400
401 #if X264_BUILD >= 23 /* r171 */
402     add_bool( SOUT_CFG_PREFIX "chroma-me", 1, NULL, CHROMA_ME_TEXT,
403               CHROMA_ME_LONGTEXT, VLC_FALSE );
404 #endif
405
406 #if X264_BUILD >= 43 /* r390 */
407     add_bool( SOUT_CFG_PREFIX "bime", 0, NULL, BIME_TEXT,
408               BIME_LONGTEXT, VLC_FALSE );
409 #endif
410
411 #if X264_BUILD >= 30 /* r251 */
412     add_bool( SOUT_CFG_PREFIX "8x8dct", 0, NULL, TRANSFORM_8X8DCT_TEXT,
413               TRANSFORM_8X8DCT_LONGTEXT, VLC_FALSE );
414 #endif
415
416 #if X264_BUILD >= 39 /* r360 */
417     add_integer( SOUT_CFG_PREFIX "trellis", 0, NULL, TRELLIS_TEXT,
418                  TRELLIS_LONGTEXT, VLC_FALSE );
419         change_integer_range( 0, 2 );
420 #endif
421
422 #if X264_BUILD >= 42 /* r384 */
423     add_bool( SOUT_CFG_PREFIX "fast-pskip", 1, NULL, FAST_PSKIP_TEXT,
424               FAST_PSKIP_LONGTEXT, VLC_FALSE );
425 #endif
426
427 #if X264_BUILD >= 44 /* r398 */
428     add_integer( SOUT_CFG_PREFIX "nr", 0, NULL, NR_TEXT,
429                  NR_LONGTEXT, VLC_FALSE );
430 #endif
431
432 /* Input/Output */
433
434     add_bool( SOUT_CFG_PREFIX "asm", 1, NULL, ASM_TEXT,
435               ASM_LONGTEXT, VLC_FALSE );
436
437     /* x264 psnr = 1 (default). disable PSNR calculation for speed. */
438     add_bool( SOUT_CFG_PREFIX "psnr", 0, NULL, PSNR_TEXT,
439               PSNR_LONGTEXT, VLC_FALSE );
440
441 #if X264_BUILD >= 0x000e /* r81 */
442     add_bool( SOUT_CFG_PREFIX "verbose", 0, NULL, VERBOSE_TEXT,
443               VERBOSE_LONGTEXT, VLC_FALSE );
444 #endif
445
446 vlc_module_end();
447
448 /*****************************************************************************
449  * Local prototypes
450  *****************************************************************************/
451 static const char *ppsz_sout_options[] = {
452     "8x8dct", "analyse", "asm", "bframes", "bime", "bpyramid", "b-adapt",
453     "b-bias", "b-rdo", "cabac", "chroma-me", "chroma-qp-offset", "cplxblur",
454     "crf", "direct", "fast-pskip", "frameref", "ipratio", "keyint",
455     "keyint-min", "loopfilter", "me", "merange", "min-keyint", "mixed-refs",
456     "nf", "nr", "pbratio", "psnr", "qblur", "qp", "qcomp", "qpstep",
457     "qpmax", "qpmin", "qp-max", "qp-min", "ratetol", "ref", "scenecut",
458     "subme", "subpel", "tolerance", "trellis", "verbose", "vbv-bufsize",
459     "vbv-init", "vbv-maxrate", "weightb" , NULL
460 };
461
462 static block_t *Encode( encoder_t *, picture_t * );
463
464 struct encoder_sys_t
465 {
466     x264_t          *h;
467     x264_param_t    param;
468
469     int             i_buffer;
470     uint8_t         *p_buffer;
471
472     mtime_t         i_last_ref_pts;
473 };
474
475 /*****************************************************************************
476  * Open: probe the encoder
477  *****************************************************************************/
478 static int  Open ( vlc_object_t *p_this )
479 {
480     encoder_t     *p_enc = (encoder_t *)p_this;
481     encoder_sys_t *p_sys;
482     vlc_value_t    val;
483     int i_qmin = 0, i_qmax = 0;
484
485     if( p_enc->fmt_out.i_codec != VLC_FOURCC( 'h', '2', '6', '4' ) &&
486         !p_enc->b_force )
487     {
488         return VLC_EGENERIC;
489     }
490
491 #if X264_BUILD < 37
492     if( p_enc->fmt_in.video.i_width % 16 != 0 ||
493         p_enc->fmt_in.video.i_height % 16!= 0 )
494     {
495         msg_Warn( p_enc, "size is not a multiple of 16 (%ix%i)",
496                   p_enc->fmt_in.video.i_width, p_enc->fmt_in.video.i_height );
497
498         if( p_enc->fmt_in.video.i_width < 16 ||
499             p_enc->fmt_in.video.i_height < 16 )
500         {
501             msg_Err( p_enc, "video is too small to be cropped" );
502             return VLC_EGENERIC;
503         }
504
505         msg_Warn( p_enc, "cropping video to %ix%i",
506                   p_enc->fmt_in.video.i_width >> 4 << 4,
507                   p_enc->fmt_in.video.i_height >> 4 << 4 );
508     }
509 #endif
510
511     sout_CfgParse( p_enc, SOUT_CFG_PREFIX, ppsz_sout_options, p_enc->p_cfg );
512
513     p_enc->fmt_out.i_codec = VLC_FOURCC( 'h', '2', '6', '4' );
514     p_enc->fmt_in.i_codec = VLC_FOURCC('I','4','2','0');
515
516     p_enc->pf_encode_video = Encode;
517     p_enc->pf_encode_audio = NULL;
518     p_enc->p_sys = p_sys = malloc( sizeof( encoder_sys_t ) );
519     p_sys->i_last_ref_pts = 0;
520
521     x264_param_default( &p_sys->param );
522     p_sys->param.i_width  = p_enc->fmt_in.video.i_width;
523     p_sys->param.i_height = p_enc->fmt_in.video.i_height;
524 #if X264_BUILD < 37
525     p_sys->param.i_width  = p_sys->param.i_width >> 4 << 4;
526     p_sys->param.i_height = p_sys->param.i_height >> 4 << 4;
527 #endif
528
529     /* average bitrate specified by transcode vb */
530     p_sys->param.rc.i_bitrate = p_enc->fmt_out.i_bitrate / 1000;
531
532     /* cbr = 1 overrides qp or crf and sets an average bitrate
533        but maxrate = average bitrate is needed for "real" CBR */
534     if( p_sys->param.rc.i_bitrate > 0 ) p_sys->param.rc.b_cbr = 1;
535
536     var_Get( p_enc, SOUT_CFG_PREFIX "qpstep", &val );
537     if( val.i_int >= 0 && val.i_int <= 51 ) p_sys->param.rc.i_qp_step = val.i_int;
538     var_Get( p_enc, SOUT_CFG_PREFIX "qpmin", &val );
539     if( val.i_int >= 0 && val.i_int <= 51 ) i_qmin = val.i_int;
540     var_Get( p_enc, SOUT_CFG_PREFIX "qpmax", &val );
541     if( val.i_int >= 0 && val.i_int <= 51 ) i_qmax = val.i_int;
542
543     var_Get( p_enc, SOUT_CFG_PREFIX "qp", &val );
544     if( val.i_int >= 0 && val.i_int <= 51 )
545     {
546         if( i_qmin > val.i_int ) i_qmin = val.i_int;
547         if( i_qmax < val.i_int ) i_qmax = val.i_int;
548
549 #if X264_BUILD >= 0x000a
550         p_sys->param.rc.i_qp_constant = val.i_int;
551         p_sys->param.rc.i_qp_min = i_qmin;
552         p_sys->param.rc.i_qp_max = i_qmax;
553 #else
554         p_sys->param.i_qp_constant = val.i_int;
555 #endif
556     }
557
558 #if X264_BUILD >= 24
559     var_Get( p_enc, SOUT_CFG_PREFIX "ratetol", &val );
560     p_sys->param.rc.f_rate_tolerance = val.f_float;
561
562     var_Get( p_enc, SOUT_CFG_PREFIX "vbv-init", &val );
563     p_sys->param.rc.f_vbv_buffer_init = val.f_float;
564
565     var_Get( p_enc, SOUT_CFG_PREFIX "vbv-bufsize", &val );
566     p_sys->param.rc.i_vbv_buffer_size = val.i_int;
567
568     /* x264 vbv-bufsize = 0 (default). if not provided set period
569        in seconds for local maximum bitrate (cache/bufsize) based
570        on average bitrate. */
571     if( !val.i_int )
572         p_sys->param.rc.i_vbv_buffer_size = p_sys->param.rc.i_bitrate * 2;
573
574     /* max bitrate = average bitrate -> CBR */
575     var_Get( p_enc, SOUT_CFG_PREFIX "vbv-maxrate", &val );
576     p_sys->param.rc.i_vbv_max_bitrate = val.i_int;
577
578 #else
579     p_sys->param.rc.i_rc_buffer_size = p_sys->param.rc.i_bitrate;
580     p_sys->param.rc.i_rc_init_buffer = p_sys->param.rc.i_bitrate / 4;
581 #endif
582
583     var_Get( p_enc, SOUT_CFG_PREFIX "cabac", &val );
584     p_sys->param.b_cabac = val.b_bool;
585
586     /* disable deblocking when nf (no loop filter) is enabled */
587     var_Get( p_enc, SOUT_CFG_PREFIX "nf", &val );
588     p_sys->param.b_deblocking_filter = !val.b_bool;
589
590     var_Get( p_enc, SOUT_CFG_PREFIX "ipratio", &val );
591     p_sys->param.rc.f_ip_factor = val.f_float;
592
593     var_Get( p_enc, SOUT_CFG_PREFIX "pbratio", &val );
594     p_sys->param.rc.f_pb_factor = val.f_float;
595
596     var_Get( p_enc, SOUT_CFG_PREFIX "qcomp", &val );
597     p_sys->param.rc.f_qcompress = val.f_float;
598
599     var_Get( p_enc, SOUT_CFG_PREFIX "cplxblur", &val );
600     p_sys->param.rc.f_complexity_blur = val.f_float;
601
602     var_Get( p_enc, SOUT_CFG_PREFIX "qblur", &val );
603     p_sys->param.rc.f_qblur = val.f_float;
604
605 #if X264_BUILD >= 0x000e
606     var_Get( p_enc, SOUT_CFG_PREFIX "verbose", &val );
607     if( val.b_bool ) p_sys->param.i_log_level = X264_LOG_DEBUG;
608 #endif
609
610     var_Get( p_enc, SOUT_CFG_PREFIX "keyint", &val );
611 #if X264_BUILD >= 0x000e
612     if( val.i_int > 0 ) p_sys->param.i_keyint_max = val.i_int;
613 #else
614     if( val.i_int > 0 ) p_sys->param.i_iframe = val.i_int;
615 #endif
616
617     var_Get( p_enc, SOUT_CFG_PREFIX "min-keyint", &val );
618 #if X264_BUILD >= 0x000e
619     if( val.i_int > 0 ) p_sys->param.i_keyint_min = val.i_int;
620 #else
621     if( val.i_int > 0 ) p_sys->param.i_idrframe = val.i_int;
622 #endif
623
624     var_Get( p_enc, SOUT_CFG_PREFIX "bframes", &val );
625     if( val.i_int >= 0 && val.i_int <= 16 )
626         p_sys->param.i_bframe = val.i_int;
627
628 #if X264_BUILD >= 22
629     var_Get( p_enc, SOUT_CFG_PREFIX "bpyramid", &val );
630     p_sys->param.b_bframe_pyramid = val.b_bool;
631 #endif
632
633     var_Get( p_enc, SOUT_CFG_PREFIX "ref", &val );
634     if( val.i_int > 0 && val.i_int <= 15 )
635         p_sys->param.i_frame_reference = val.i_int;
636
637     var_Get( p_enc, SOUT_CFG_PREFIX "scenecut", &val );
638 #if X264_BUILD >= 0x000b
639     if( val.i_int >= -1 && val.i_int <= 100 )
640         p_sys->param.i_scenecut_threshold = val.i_int;
641 #endif
642
643 #if X264_BUILD >= 30
644     var_Get( p_enc, SOUT_CFG_PREFIX "subme", &val );
645     if( val.i_int >= 1 && val.i_int <= 6 )
646         p_sys->param.analyse.i_subpel_refine = val.i_int;
647 #else
648     if( val.i_int >= 1 && val.i_int <= 5 )
649         p_sys->param.analyse.i_subpel_refine = val.i_int;
650 #endif
651
652 #if X264_BUILD >= 24
653     var_Get( p_enc, SOUT_CFG_PREFIX "me", &val );
654     if( !strcmp( val.psz_string, "dia" ) )
655     {
656         p_sys->param.analyse.i_me_method = X264_ME_DIA;
657     }
658     else if( !strcmp( val.psz_string, "hex" ) )
659     {
660         p_sys->param.analyse.i_me_method = X264_ME_HEX;
661     }
662     else if( !strcmp( val.psz_string, "umh" ) )
663     {
664         p_sys->param.analyse.i_me_method = X264_ME_UMH;
665     }
666     else if( !strcmp( val.psz_string, "esa" ) )
667     {
668         p_sys->param.analyse.i_me_method = X264_ME_ESA;
669     }
670     if( val.psz_string ) free( val.psz_string );
671
672     var_Get( p_enc, SOUT_CFG_PREFIX "merange", &val );
673     if( val.i_int >= 1 && val.i_int <= 64 )
674         p_sys->param.analyse.i_me_range = val.i_int;
675 #endif
676
677     var_Get( p_enc, SOUT_CFG_PREFIX "direct", &val );
678     if( !strcmp( val.psz_string, "none" ) )
679     {
680         p_sys->param.analyse.i_direct_mv_pred = X264_DIRECT_PRED_NONE;
681     }
682     else if( !strcmp( val.psz_string, "spatial" ) )
683     {
684         p_sys->param.analyse.i_direct_mv_pred = X264_DIRECT_PRED_SPATIAL;
685     }
686     else if( !strcmp( val.psz_string, "temporal" ) )
687     {
688         p_sys->param.analyse.i_direct_mv_pred = X264_DIRECT_PRED_TEMPORAL;
689     }
690     if( val.psz_string ) free( val.psz_string );
691
692     var_Get( p_enc, SOUT_CFG_PREFIX "psnr", &val );
693     p_sys->param.analyse.b_psnr = val.b_bool;
694
695 #if X264_BUILD >= 0x0012
696     var_Get( p_enc, SOUT_CFG_PREFIX "weightb", &val );
697     p_sys->param.analyse.b_weighted_bipred = val.b_bool;
698 #endif
699
700 #if X264_BUILD >= 0x0013
701     var_Get( p_enc, SOUT_CFG_PREFIX "b-adapt", &val );
702     p_sys->param.b_bframe_adaptive = val.b_bool;
703
704     var_Get( p_enc, SOUT_CFG_PREFIX "b-bias", &val );
705     if( val.i_int >= -100 && val.i_int <= 100 )
706         p_sys->param.i_bframe_bias = val.i_int;
707 #endif
708
709 #if X264_BUILD >= 23
710     var_Get( p_enc, SOUT_CFG_PREFIX "chroma-me", &val );
711     p_sys->param.analyse.b_chroma_me = val.b_bool;
712     var_Get( p_enc, SOUT_CFG_PREFIX "chroma-qp-offset", &val );
713     p_sys->param.analyse.i_chroma_qp_offset = val.i_int;
714 #endif
715
716 #if X264_BUILD >= 36
717     var_Get( p_enc, SOUT_CFG_PREFIX "mixed-refs", &val );
718     p_sys->param.analyse.b_mixed_references = val.b_bool;
719 #endif
720
721 #if X264_BUILD >= 37
722     var_Get( p_enc, SOUT_CFG_PREFIX "crf", &val ); 
723     if( val.i_int >= 0 && val.i_int <= 51 ) /* crf != 0 overrides qp */
724         p_sys->param.rc.i_rf_constant = val.i_int;
725 #endif
726
727 #if X264_BUILD >= 39
728     var_Get( p_enc, SOUT_CFG_PREFIX "trellis", &val );
729     if( val.i_int >= 0 && val.i_int <= 2 )
730         p_sys->param.analyse.i_trellis = val.i_int;
731 #endif
732
733 #if X264_BUILD >= 41
734     var_Get( p_enc, SOUT_CFG_PREFIX "b-rdo", &val );
735     p_sys->param.analyse.b_bframe_rdo = val.b_bool;
736 #endif
737
738 #if X264_BUILD >= 42
739     var_Get( p_enc, SOUT_CFG_PREFIX "fast-pskip", &val );
740     p_sys->param.analyse.b_fast_pskip = val.b_bool;
741 #endif
742
743 #if X264_BUILD >= 43
744     var_Get( p_enc, SOUT_CFG_PREFIX "bime", &val );
745     p_sys->param.analyse.b_bidir_me = val.b_bool;
746 #endif
747
748 #if X264_BUILD >= 44
749     var_Get( p_enc, SOUT_CFG_PREFIX "nr", &val );
750     p_sys->param.analyse.i_noise_reduction = val.i_int;
751 #endif
752
753     var_Get( p_enc, SOUT_CFG_PREFIX "asm", &val );
754     if( !val.b_bool ) p_sys->param.cpu = 0;
755
756 #ifndef X264_ANALYSE_BSUB16x16
757 #   define X264_ANALYSE_BSUB16x16 0
758 #endif
759     var_Get( p_enc, SOUT_CFG_PREFIX "analyse", &val );
760     if( !strcmp( val.psz_string, "none" ) )
761     {
762         p_sys->param.analyse.inter = 0;
763     }
764     else if( !strcmp( val.psz_string, "fast" ) )
765     {
766         p_sys->param.analyse.inter = X264_ANALYSE_I4x4;
767     }
768     else if( !strcmp( val.psz_string, "normal" ) )
769     {
770         p_sys->param.analyse.inter =
771             X264_ANALYSE_I4x4 |
772             X264_ANALYSE_PSUB16x16;
773 #ifdef X264_ANALYSE_I8x8
774         p_sys->param.analyse.inter |= X264_ANALYSE_I8x8;
775 #endif
776     }
777     else if( !strcmp( val.psz_string, "slow" ) )
778     {
779         p_sys->param.analyse.inter =
780             X264_ANALYSE_I4x4 |
781             X264_ANALYSE_PSUB16x16 |
782             X264_ANALYSE_BSUB16x16;
783 #ifdef X264_ANALYSE_I8x8
784         p_sys->param.analyse.inter |= X264_ANALYSE_I8x8;
785 #endif
786     }
787     else if( !strcmp( val.psz_string, "all" ) )
788     {
789         p_sys->param.analyse.inter =
790             X264_ANALYSE_I4x4 |
791             X264_ANALYSE_PSUB16x16 |
792             X264_ANALYSE_BSUB16x16 |
793             X264_ANALYSE_PSUB8x8;
794 #ifdef X264_ANALYSE_I8x8
795         p_sys->param.analyse.inter |= X264_ANALYSE_I8x8;
796 #endif
797     }
798     if( val.psz_string ) free( val.psz_string );
799
800 #if X264_BUILD >= 30
801     var_Get( p_enc, SOUT_CFG_PREFIX "8x8dct", &val );
802     p_sys->param.analyse.b_transform_8x8 = val.b_bool;
803 #endif
804
805     if( p_enc->fmt_in.video.i_aspect > 0 )
806     {
807         int64_t i_num, i_den;
808         int i_dst_num, i_dst_den;
809
810         i_num = p_enc->fmt_in.video.i_aspect *
811             (int64_t)p_enc->fmt_in.video.i_height;
812         i_den = VOUT_ASPECT_FACTOR * p_enc->fmt_in.video.i_width;
813         vlc_ureduce( &i_dst_num, &i_dst_den, i_num, i_den, 0 );
814
815         p_sys->param.vui.i_sar_width = i_dst_num;
816         p_sys->param.vui.i_sar_height = i_dst_den;
817     }
818     if( p_enc->fmt_in.video.i_frame_rate_base > 0 )
819     {
820         p_sys->param.i_fps_num = p_enc->fmt_in.video.i_frame_rate;
821         p_sys->param.i_fps_den = p_enc->fmt_in.video.i_frame_rate_base;
822     }
823     if( !(p_enc->p_libvlc->i_cpu & CPU_CAPABILITY_MMX) )
824     {
825         p_sys->param.cpu &= ~X264_CPU_MMX;
826     }
827     if( !(p_enc->p_libvlc->i_cpu & CPU_CAPABILITY_MMXEXT) )
828     {
829         p_sys->param.cpu &= ~X264_CPU_MMXEXT;
830     }
831     if( !(p_enc->p_libvlc->i_cpu & CPU_CAPABILITY_SSE) )
832     {
833         p_sys->param.cpu &= ~X264_CPU_SSE;
834     }
835     if( !(p_enc->p_libvlc->i_cpu & CPU_CAPABILITY_SSE2) )
836     {
837         p_sys->param.cpu &= ~X264_CPU_SSE2;
838     }
839
840 #if X264_BUILD >= 29
841     if( p_enc->i_threads >= 1 )
842         p_sys->param.i_threads = p_enc->i_threads;
843 #endif
844
845     /* Open the encoder */
846     p_sys->h = x264_encoder_open( &p_sys->param );
847
848     /* alloc mem */
849     p_sys->i_buffer = 4 * p_enc->fmt_in.video.i_width *
850         p_enc->fmt_in.video.i_height + 1000;
851     p_sys->p_buffer = malloc( p_sys->i_buffer );
852
853     /* get the globals headers */
854     p_enc->fmt_out.i_extra = 0;
855     p_enc->fmt_out.p_extra = NULL;
856
857 #if 0
858     x264_encoder_headers( p_sys->h, &nal, &i_nal );
859     for( i = 0; i < i_nal; i++ )
860     {
861         int i_size = p_sys->i_buffer;
862
863         x264_nal_encode( p_sys->p_buffer, &i_size, 1, &nal[i] );
864
865         p_enc->fmt_out.p_extra = realloc( p_enc->fmt_out.p_extra, p_enc->fmt_out.i_extra + i_size );
866
867         memcpy( p_enc->fmt_out.p_extra + p_enc->fmt_out.i_extra,
868                 p_sys->p_buffer, i_size );
869
870         p_enc->fmt_out.i_extra += i_size;
871     }
872 #endif
873
874     return VLC_SUCCESS;
875 }
876
877 /****************************************************************************
878  * Encode:
879  ****************************************************************************/
880 static block_t *Encode( encoder_t *p_enc, picture_t *p_pict )
881 {
882     encoder_sys_t *p_sys = p_enc->p_sys;
883     x264_picture_t pic;
884     x264_nal_t *nal;
885     block_t *p_block;
886     int i_nal, i_out, i;
887
888     /* init pic */
889     memset( &pic, 0, sizeof( x264_picture_t ) );
890     pic.i_pts = p_pict->date;
891     pic.img.i_csp = X264_CSP_I420;
892     pic.img.i_plane = p_pict->i_planes;
893     for( i = 0; i < p_pict->i_planes; i++ )
894     {
895         pic.img.plane[i] = p_pict->p[i].p_pixels;
896         pic.img.i_stride[i] = p_pict->p[i].i_pitch;
897     }
898
899 #if X264_BUILD >= 0x0013
900     x264_encoder_encode( p_sys->h, &nal, &i_nal, &pic, &pic );
901 #else
902     x264_encoder_encode( p_sys->h, &nal, &i_nal, &pic );
903 #endif
904
905     if( !i_nal ) return NULL;
906
907     for( i = 0, i_out = 0; i < i_nal; i++ )
908     {
909         int i_size = p_sys->i_buffer - i_out;
910         x264_nal_encode( p_sys->p_buffer + i_out, &i_size, 1, &nal[i] );
911
912         i_out += i_size;
913     }
914
915     p_block = block_New( p_enc, i_out );
916     memcpy( p_block->p_buffer, p_sys->p_buffer, i_out );
917
918     if( pic.i_type == X264_TYPE_IDR || pic.i_type == X264_TYPE_I )
919         p_block->i_flags |= BLOCK_FLAG_TYPE_I;
920     else if( pic.i_type == X264_TYPE_P )
921         p_block->i_flags |= BLOCK_FLAG_TYPE_P;
922     else if( pic.i_type == X264_TYPE_B )
923         p_block->i_flags |= BLOCK_FLAG_TYPE_B;
924
925     /* This isn't really valid for streams with B-frames */
926     p_block->i_length = I64C(1000000) *
927         p_enc->fmt_in.video.i_frame_rate_base /
928             p_enc->fmt_in.video.i_frame_rate;
929
930     p_block->i_dts = p_block->i_pts = pic.i_pts;
931
932     if( p_sys->param.i_bframe > 0 )
933     {
934         if( p_block->i_flags & BLOCK_FLAG_TYPE_B )
935         {
936             p_block->i_dts = p_block->i_pts;
937         }
938         else
939         {
940             if( p_sys->i_last_ref_pts )
941             {
942                 p_block->i_dts = p_sys->i_last_ref_pts;
943             }
944             else
945             {
946                 /* Let's put something sensible */
947                 p_block->i_dts = p_block->i_pts;
948             }
949
950             p_sys->i_last_ref_pts = p_block->i_pts;
951         }
952     }
953
954     return p_block;
955 }
956
957 /*****************************************************************************
958  * CloseEncoder: x264 encoder destruction
959  *****************************************************************************/
960 static void Close( vlc_object_t *p_this )
961 {
962     encoder_t     *p_enc = (encoder_t *)p_this;
963     encoder_sys_t *p_sys = p_enc->p_sys;
964
965     x264_encoder_close( p_sys->h );
966     free( p_sys->p_buffer );
967     free( p_sys );
968 }