]> git.sesse.net Git - vlc/blob - modules/codec/x264.c
Convenience target to run also the broken tests
[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 #ifdef HAVE_CONFIG_H
28 # include "config.h"
29 #endif
30
31 #include <vlc_common.h>
32 #include <vlc_plugin.h>
33 #include <vlc_vout.h>
34 #include <vlc_sout.h>
35 #include <vlc_codec.h>
36
37 #ifdef PTW32_STATIC_LIB
38 #include <pthread.h>
39 #endif
40 #include <x264.h>
41
42 #define SOUT_CFG_PREFIX "sout-x264-"
43
44 /*****************************************************************************
45  * Module descriptor
46  *****************************************************************************/
47 static int  Open ( vlc_object_t * );
48 static void Close( vlc_object_t * );
49
50 /* Frame-type options */
51
52 #define KEYINT_TEXT N_("Maximum GOP size")
53 #define KEYINT_LONGTEXT N_( "Sets maximum interval between IDR-frames." \
54     "Larger values save bits, thus improving quality for a given bitrate at " \
55     "the cost of seeking precision." )
56
57 #define MIN_KEYINT_TEXT N_("Minimum GOP size")
58 #define MIN_KEYINT_LONGTEXT N_( "Sets minimum interval between IDR-frames. " \
59     "In H.264, I-frames do not necessarily bound a closed GOP because it is " \
60     "allowable for a P-frame to be predicted from more frames than just the " \
61     "one frame before it (also see reference frame option). Therefore, " \
62     "I-frames are not necessarily seekable. IDR-frames restrict subsequent " \
63     "P-frames from referring to any frame prior to the IDR-frame. \n" \
64     "If scenecuts appear within this interval, they are still encoded as " \
65     "I-frames, but do not start a new GOP." )
66
67 #define SCENE_TEXT N_("Extra I-frames aggressivity" )
68 #define SCENE_LONGTEXT N_( "Scene-cut detection. Controls how " \
69     "aggressively to insert extra I-frames. With small values of " \
70     "scenecut, the codec often has " \
71     "to force an I-frame when it would exceed keyint. " \
72     "Good values of scenecut may find a better location for the " \
73     "I-frame. Large values use more I-frames " \
74     "than necessary, thus wasting bits. -1 disables scene-cut detection, so " \
75     "I-frames are inserted only every other keyint frames, which probably " \
76     "leads to ugly encoding artifacts. Range 1 to 100." )
77
78 #if X264_BUILD >= 55 /* r607 */
79 #define PRESCENE_TEXT N_("Faster, less precise scenecut detection" )
80 #define PRESCENE_LONGTEXT N_( "Faster, less precise scenecut detection. " \
81     "Required and implied by multi-threading." )
82 #endif
83
84 #define BFRAMES_TEXT N_("B-frames between I and P")
85 #define BFRAMES_LONGTEXT N_( "Number of consecutive B-frames between I and " \
86     "P-frames. Range 1 to 16." )
87
88 #define B_ADAPT_TEXT N_("Adaptive B-frame decision")
89 #if X264_BUILD >= 63
90 #define B_ADAPT_LONGTEXT N_( "Force the specified number of " \
91     "consecutive B-frames to be used, except possibly before an I-frame." \
92     "Range 0 to 2." )
93 #else
94 #define B_ADAPT_LONGTEXT N_( "Force the specified number of " \
95     "consecutive B-frames to be used, except possibly before an I-frame." )
96 #endif
97
98 #define B_BIAS_TEXT N_("Influence (bias) B-frames usage")
99 #define B_BIAS_LONGTEXT N_( "Bias the choice to use B-frames. Positive values " \
100     "cause more B-frames, negative values cause less B-frames." )
101
102 #define BPYRAMID_TEXT N_("Keep some B-frames as references")
103 #define BPYRAMID_LONGTEXT N_( "Allows B-frames to be used as references for " \
104     "predicting other frames. Keeps the middle of 2+ consecutive B-frames " \
105     "as a reference, and reorders frame appropriately." )
106
107 #define CABAC_TEXT N_("CABAC")
108 #define CABAC_LONGTEXT N_( "CABAC (Context-Adaptive Binary Arithmetic "\
109     "Coding). Slightly slows down encoding and decoding, but should save " \
110     "10 to 15% bitrate." )
111
112 #define REF_TEXT N_("Number of reference frames")
113 #define REF_LONGTEXT N_( "Number of previous frames used as predictors. " \
114     "This is effective in Anime, but seems to make little difference in " \
115     "live-action source material. Some decoders are unable to deal with " \
116     "large frameref values. Range 1 to 16." )
117
118 #define NF_TEXT N_("Skip loop filter")
119 #define NF_LONGTEXT N_( "Deactivate the deblocking loop filter (decreases quality).")
120
121 #define FILTER_TEXT N_("Loop filter AlphaC0 and Beta parameters alpha:beta")
122 #define FILTER_LONGTEXT N_( "Loop filter AlphaC0 and Beta parameters. " \
123     "Range -6 to 6 for both alpha and beta parameters. -6 means light " \
124     "filter, 6 means strong.")
125  
126 #define LEVEL_TEXT N_("H.264 level")
127 #define LEVEL_LONGTEXT N_( "Specify H.264 level (as defined by Annex A " \
128     "of the standard). Levels are not enforced; it's up to the user to select " \
129     "a level compatible with the rest of the encoding options. Range 1 to 5.1 " \
130     "(10 to 51 is also allowed).")
131
132 /* In order to play an interlaced output stream encoded by x264, a decoder needs
133    mbaff support. r570 is using the 'mb' part and not 'aff' yet; so it's really
134    'pure-interlaced' mode */
135 #if X264_BUILD >= 51 /* r570 */
136 #define INTERLACED_TEXT N_("Interlaced mode")
137 #define INTERLACED_LONGTEXT N_( "Pure-interlaced mode.")
138 #endif
139
140 /* Ratecontrol */
141
142 #define QP_TEXT N_("Set QP")
143 #define QP_LONGTEXT N_( "This selects the quantizer to use. " \
144     "Lower values result in better fidelity, but higher bitrates. 26 is a " \
145     "good default value. Range 0 (lossless) to 51." )
146
147 #define CRF_TEXT N_("Quality-based VBR")
148 #define CRF_LONGTEXT N_( "1-pass Quality-based VBR. Range 0 to 51." )
149
150 #define QPMIN_TEXT N_("Min QP")
151 #define QPMIN_LONGTEXT N_( "Minimum quantizer parameter. 15 to 35 seems to " \
152     "be a useful range." )
153
154 #define QPMAX_TEXT N_("Max QP")
155 #define QPMAX_LONGTEXT N_( "Maximum quantizer parameter." )
156
157 #define QPSTEP_TEXT N_("Max QP step")
158 #define QPSTEP_LONGTEXT N_( "Max QP step between frames.")
159
160 #define RATETOL_TEXT N_("Average bitrate tolerance")
161 #define RATETOL_LONGTEXT N_( "Allowed variance in average " \
162     "bitrate (in kbits/s).")
163
164 #define VBV_MAXRATE_TEXT N_("Max local bitrate")
165 #define VBV_MAXRATE_LONGTEXT N_( "Sets a maximum local bitrate (in kbits/s).")
166
167 #define VBV_BUFSIZE_TEXT N_("VBV buffer")
168 #define VBV_BUFSIZE_LONGTEXT N_( "Averaging period for the maximum " \
169     "local bitrate (in kbits).")
170
171 #define VBV_INIT_TEXT N_("Initial VBV buffer occupancy")
172 #define VBV_INIT_LONGTEXT N_( "Sets the initial buffer occupancy as a " \
173     "fraction of the buffer size. Range 0.0 to 1.0.")
174
175 #if X264_BUILD >= 59
176 #define AQ_MODE_TEXT N_("How AQ distributes bits")
177 #define AQ_MODE_LONGTEXT N_("Defines bitdistribution mode for AQ, default 2\n" \
178         " - 0: Disabled\n"\
179         " - 1: Avoid moving bits between frames\n"\
180         " - 2: Move bits between frames")
181
182 #define AQ_STRENGTH_TEXT N_("Strength of AQ")
183 #define AQ_STRENGTH_LONGTEXT N_("Strength to reduce blocking and blurring in flat\n"\
184         "and textured areas, default 1.0 recommented to be between 0..2\n"\
185         " - 0.5: weak AQ\n"\
186         " - 1.5: strong AQ")
187 #endif
188
189 /* IP Ratio < 1 is technically valid but should never improve quality */
190 #define IPRATIO_TEXT N_("QP factor between I and P")
191 #define IPRATIO_LONGTEXT N_( "QP factor between I and P. Range 1.0 to 2.0.")
192
193 /* PB ratio < 1 is not valid and breaks ratecontrol */
194 #define PBRATIO_TEXT N_("QP factor between P and B")
195 #define PBRATIO_LONGTEXT N_( "QP factor between P and B. Range 1.0 to 2.0.")
196
197 #define CHROMA_QP_OFFSET_TEXT N_("QP difference between chroma and luma")
198 #define CHROMA_QP_OFFSET_LONGTEXT N_( "QP difference between chroma and luma.")
199
200 #define PASS_TEXT N_("Multipass ratecontrol")
201 #define PASS_LONGTEXT N_( "Multipass ratecontrol:\n" \
202     " - 1: First pass, creates stats file\n" \
203     " - 2: Last pass, does not overwrite stats file\n" \
204     " - 3: Nth pass, overwrites stats file\n" )
205
206 #define QCOMP_TEXT N_("QP curve compression")
207 #define QCOMP_LONGTEXT N_( "QP curve compression. Range 0.0 (CBR) to 1.0 (QCP).")
208
209 #define CPLXBLUR_TEXT N_("Reduce fluctuations in QP")
210 #define CPLXBLUR_LONGTEXT N_( "This reduces the fluctuations in QP " \
211     "before curve compression. Temporally blurs complexity.")
212
213 #define QBLUR_TEXT N_("Reduce fluctuations in QP")
214 #define QBLUR_LONGTEXT N_( "This reduces the fluctations in QP " \
215     "after curve compression. Temporally blurs quants.")
216
217 /* Analysis */
218
219 #define ANALYSE_TEXT N_("Partitions to consider")
220 #define ANALYSE_LONGTEXT N_( "Partitions to consider in analyse mode: \n" \
221     " - none  : \n" \
222     " - fast  : i4x4\n" \
223     " - normal: i4x4,p8x8,(i8x8)\n" \
224     " - slow  : i4x4,p8x8,(i8x8),b8x8\n" \
225     " - all   : i4x4,p8x8,(i8x8),b8x8,p4x4\n" \
226     "(p4x4 requires p8x8. i8x8 requires 8x8dct).")
227
228 #define DIRECT_PRED_TEXT N_("Direct MV prediction mode")
229 #define DIRECT_PRED_LONGTEXT N_( "Direct MV prediction mode.")
230
231 #if X264_BUILD >= 52 /* r573 */
232 #define DIRECT_PRED_SIZE_TEXT N_("Direct prediction size")
233 #define DIRECT_PRED_SIZE_LONGTEXT N_( "Direct prediction size: "\
234     " -  0: 4x4\n" \
235     " -  1: 8x8\n" \
236     " - -1: smallest possible according to level\n" )
237 #endif
238
239 #define WEIGHTB_TEXT N_("Weighted prediction for B-frames")
240 #define WEIGHTB_LONGTEXT N_( "Weighted prediction for B-frames.")
241
242 #define ME_TEXT N_("Integer pixel motion estimation method")
243 #if X264_BUILD >= 58 /* r728 */
244 #define ME_LONGTEXT N_( "Selects the motion estimation algorithm: "\
245     " - dia: diamond search, radius 1 (fast)\n" \
246     " - hex: hexagonal search, radius 2\n" \
247     " - umh: uneven multi-hexagon search (better but slower)\n" \
248     " - esa: exhaustive search (extremely slow, primarily for testing)\n" \
249     " - tesa: hadamard exhaustive search (extremely slow, primarily for testing)\n" )
250 #else
251 #define ME_LONGTEXT N_( "Selects the motion estimation algorithm: "\
252     " - dia: diamond search, radius 1 (fast)\n" \
253     " - hex: hexagonal search, radius 2\n" \
254     " - umh: uneven multi-hexagon search (better but slower)\n" \
255     " - esa: exhaustive search (extremely slow, primarily for testing)\n" )
256 #endif
257
258 #if X264_BUILD >= 24
259 #define MERANGE_TEXT N_("Maximum motion vector search range")
260 #define MERANGE_LONGTEXT N_( "Maximum distance to search for " \
261     "motion estimation, measured from predicted position(s). " \
262     "Default of 16 is good for most footage, high motion sequences may " \
263     "benefit from settings between 24 and 32. Range 0 to 64." )
264
265 #define MVRANGE_TEXT N_("Maximum motion vector length")
266 #define MVRANGE_LONGTEXT N_( "Maximum motion vector length in pixels. " \
267     "-1 is automatic, based on level." )
268 #endif
269
270 #if X264_BUILD >= 55 /* r607 */
271 #define MVRANGE_THREAD_TEXT N_("Minimum buffer space between threads")
272 #define MVRANGE_THREAD_LONGTEXT N_( "Minimum buffer space between threads. " \
273     "-1 is automatic, based on number of threads." )
274 #endif
275
276 #define SUBME_TEXT N_("Subpixel motion estimation and partition decision " \
277     "quality")
278 #if X264_BUILD >= 65 
279 #define SUBME_MAX 9
280 #define SUBME_LONGTEXT N_( "This parameter controls quality versus speed " \
281     "tradeoffs involved in the motion estimation decision process " \
282     "(lower = quicker and higher = better quality). Range 1 to 9." )
283 #elif X264_BUILD >= 46 /* r477 */
284 #define SUBME_MAX 7
285 #define SUBME_LONGTEXT N_( "This parameter controls quality versus speed " \
286     "tradeoffs involved in the motion estimation decision process " \
287     "(lower = quicker and higher = better quality). Range 1 to 7." )
288 #elif X264_BUILD >= 30 /* r262 */
289 #define SUBME_MAX 6
290 #define SUBME_LONGTEXT N_( "This parameter controls quality versus speed " \
291     "tradeoffs involved in the motion estimation decision process " \
292     "(lower = quicker and higher = better quality). Range 1 to 6." )
293 #else
294 #define SUBME_MAX 5
295 #define SUBME_LONGTEXT N_( "This parameter controls quality versus speed " \
296     "tradeoffs involved in the motion estimation decision process " \
297     "(lower = quicker and higher = better quality). Range 1 to 5." )
298 #endif
299
300 #define B_RDO_TEXT N_("RD based mode decision for B-frames")
301 #define B_RDO_LONGTEXT N_( "RD based mode decision for B-frames. This " \
302     "requires subme 6 (or higher).")
303
304 #define MIXED_REFS_TEXT N_("Decide references on a per partition basis")
305 #define MIXED_REFS_LONGTEXT N_( "Allows each 8x8 or 16x8 partition to " \
306     "independently select a reference frame, as opposed to only one ref " \
307     "per macroblock." )
308
309 #define CHROMA_ME_TEXT N_("Chroma in motion estimation")
310 #define CHROMA_ME_LONGTEXT N_( "Chroma ME for subpel and mode decision in " \
311     "P-frames.")
312
313 #define BIME_TEXT N_("Jointly optimize both MVs in B-frames")
314 #define BIME_LONGTEXT N_( "Joint bidirectional motion refinement.")
315
316 #define TRANSFORM_8X8DCT_TEXT N_("Adaptive spatial transform size")
317 #define TRANSFORM_8X8DCT_LONGTEXT N_( \
318     "SATD-based decision for 8x8 transform in inter-MBs.")
319
320 #define TRELLIS_TEXT N_("Trellis RD quantization" )
321 #define TRELLIS_LONGTEXT N_( "Trellis RD quantization: \n" \
322     " - 0: disabled\n" \
323     " - 1: enabled only on the final encode of a MB\n" \
324     " - 2: enabled on all mode decisions\n" \
325     "This requires CABAC." )
326
327 #define FAST_PSKIP_TEXT N_("Early SKIP detection on P-frames")
328 #define FAST_PSKIP_LONGTEXT N_( "Early SKIP detection on P-frames.")
329
330 #define DCT_DECIMATE_TEXT N_("Coefficient thresholding on P-frames")
331 #define DCT_DECIMATE_LONGTEXT N_( "Coefficient thresholding on P-frames." \
332     "Eliminate dct blocks containing only a small single coefficient.")
333
334 /* Noise reduction 1 is too weak to measure, suggest at least 10 */
335 #define NR_TEXT N_("Noise reduction")
336 #define NR_LONGTEXT N_( "Dct-domain noise reduction. Adaptive pseudo-deadzone. " \
337     "10 to 1000 seems to be a useful range." )
338
339 #if X264_BUILD >= 52 /* r573 */
340 #define DEADZONE_INTER_TEXT N_("Inter luma quantization deadzone")
341 #define DEADZONE_INTER_LONGTEXT N_( "Set the size of the inter luma quantization deadzone. " \
342     "Range 0 to 32." )
343
344 #define DEADZONE_INTRA_TEXT N_("Intra luma quantization deadzone")
345 #define DEADZONE_INTRA_LONGTEXT N_( "Set the size of the intra luma quantization deadzone. " \
346     "Range 0 to 32." )
347 #endif
348
349 /* Input/Output */
350
351 #if X264_BUILD >= 55 /* r607 */
352 #define NON_DETERMINISTIC_TEXT N_("Non-deterministic optimizations when threaded")
353 #define NON_DETERMINISTIC_LONGTEXT N_( "Slightly improve quality of SMP, " \
354     "at the cost of repeatability.")
355 #endif
356
357 #define ASM_TEXT N_("CPU optimizations")
358 #define ASM_LONGTEXT N_( "Use assembler CPU optimizations.")
359
360 #define STATS_TEXT N_("Filename for 2 pass stats file")
361 #define STATS_LONGTEXT N_( "Filename for 2 pass stats file for multi-pass encoding.")
362
363 #define PSNR_TEXT N_("PSNR computation")
364 #define PSNR_LONGTEXT N_( "Compute and print PSNR stats. This has no effect on " \
365     "the actual encoding quality." )
366
367 #define SSIM_TEXT N_("SSIM computation")
368 #define SSIM_LONGTEXT N_( "Compute and print SSIM stats. This has no effect on " \
369     "the actual encoding quality." )
370
371 #define QUIET_TEXT N_("Quiet mode")
372 #define QUIET_LONGTEXT N_( "Quiet mode.")
373
374 #define VERBOSE_TEXT N_("Statistics")
375 #define VERBOSE_LONGTEXT N_( "Print stats for each frame.")
376
377 #if X264_BUILD >= 47 /* r518 */
378 #define SPS_ID_TEXT N_("SPS and PPS id numbers")
379 #define SPS_ID_LONGTEXT N_( "Set SPS and PPS id numbers to allow concatenating " \
380     "streams with different settings.")
381 #endif
382
383 #define AUD_TEXT N_("Access unit delimiters")
384 #define AUD_LONGTEXT N_( "Generate access unit delimiter NAL units.")
385
386 #if X264_BUILD >= 24 && X264_BUILD < 58
387 static const char *const enc_me_list[] =
388   { "dia", "hex", "umh", "esa" };
389 static const char *const enc_me_list_text[] =
390   { N_("dia"), N_("hex"), N_("umh"), N_("esa") };
391 #endif
392
393 #if X264_BUILD >= 58 /* r728 */
394 static const char *const enc_me_list[] =
395   { "dia", "hex", "umh", "esa", "tesa" };
396 static const char *const enc_me_list_text[] =
397   { N_("dia"), N_("hex"), N_("umh"), N_("esa"), N_("tesa") };
398 #endif
399
400 static const char *const enc_analyse_list[] =
401   { "none", "fast", "normal", "slow", "all" };
402 static const char *const enc_analyse_list_text[] =
403   { N_("none"), N_("fast"), N_("normal"), N_("slow"), N_("all") };
404
405 #if X264_BUILD >= 45 /* r457 */
406 static const char *const direct_pred_list[] =
407   { "none", "spatial", "temporal", "auto" };
408 static const char *const direct_pred_list_text[] =
409   { N_("none"), N_("spatial"), N_("temporal"), N_("auto") };
410 #else
411 static const char *const direct_pred_list[] =
412   { "none", "spatial", "temporal" };
413 static const char *const direct_pred_list_text[] =
414   { N_("none"), N_("spatial"), N_("temporal") };
415 #endif
416
417 vlc_module_begin ()
418     set_description( N_("H.264/MPEG4 AVC encoder (x264)"))
419     set_capability( "encoder", 200 )
420     set_callbacks( Open, Close )
421     set_category( CAT_INPUT )
422     set_subcategory( SUBCAT_INPUT_VCODEC )
423
424 /* Frame-type options */
425
426     add_integer( SOUT_CFG_PREFIX "keyint", 250, NULL, KEYINT_TEXT,
427                  KEYINT_LONGTEXT, false )
428
429     add_integer( SOUT_CFG_PREFIX "min-keyint", 25, NULL, MIN_KEYINT_TEXT,
430                  MIN_KEYINT_LONGTEXT, false )
431         add_deprecated_alias( SOUT_CFG_PREFIX "keyint-min" ) /* Deprecated since 0.8.5 */
432
433     add_integer( SOUT_CFG_PREFIX "scenecut", 40, NULL, SCENE_TEXT,
434                  SCENE_LONGTEXT, false )
435         change_integer_range( -1, 100 )
436
437 #if X264_BUILD >= 55 /* r607 */
438     add_bool( SOUT_CFG_PREFIX "pre-scenecut", 0, NULL, PRESCENE_TEXT,
439               PRESCENE_LONGTEXT, false )
440 #endif
441
442     add_integer( SOUT_CFG_PREFIX "bframes", 0, NULL, BFRAMES_TEXT,
443                  BFRAMES_LONGTEXT, false )
444         change_integer_range( 0, 16 )
445
446 #if X264_BUILD >= 63
447     add_integer( SOUT_CFG_PREFIX "b-adapt", 1, NULL, B_ADAPT_TEXT,
448                  B_ADAPT_LONGTEXT, false )
449         change_integer_range( 0, 2 )
450 #elif  X264_BUILD >= 0x0013 /* r137 */
451     add_bool( SOUT_CFG_PREFIX "b-adapt", 1, NULL, B_ADAPT_TEXT,
452               B_ADAPT_LONGTEXT, false )
453 #endif
454
455 #if  X264_BUILD >= 0x0013 /* r137 */
456     add_integer( SOUT_CFG_PREFIX "b-bias", 0, NULL, B_BIAS_TEXT,
457                  B_BIAS_LONGTEXT, false )
458         change_integer_range( -100, 100 )
459 #endif
460
461     add_bool( SOUT_CFG_PREFIX "bpyramid", 0, NULL, BPYRAMID_TEXT,
462               BPYRAMID_LONGTEXT, false )
463
464     add_bool( SOUT_CFG_PREFIX "cabac", 1, NULL, CABAC_TEXT, CABAC_LONGTEXT,
465               false )
466
467     add_integer( SOUT_CFG_PREFIX "ref", 1, NULL, REF_TEXT,
468                  REF_LONGTEXT, false )
469         change_integer_range( 1, 16 )
470         add_deprecated_alias( SOUT_CFG_PREFIX "frameref" ) /* Deprecated since 0.8.5 */
471
472     add_bool( SOUT_CFG_PREFIX "nf", 0, NULL, NF_TEXT,
473               NF_LONGTEXT, false )
474         add_deprecated_alias( SOUT_CFG_PREFIX "loopfilter" ) /* Deprecated since 0.8.5 */
475
476     add_string( SOUT_CFG_PREFIX "deblock", "0:0", NULL, FILTER_TEXT,
477                  FILTER_LONGTEXT, false )
478         add_deprecated_alias( SOUT_CFG_PREFIX "filter" ) /* Deprecated since 0.8.6 */
479
480     add_string( SOUT_CFG_PREFIX "level", "5.1", NULL, LEVEL_TEXT,
481                LEVEL_LONGTEXT, false )
482
483 #if X264_BUILD >= 51 /* r570 */
484     add_bool( SOUT_CFG_PREFIX "interlaced", 0, NULL, INTERLACED_TEXT, INTERLACED_LONGTEXT,
485               false )
486 #endif
487
488 /* Ratecontrol */
489
490     add_integer( SOUT_CFG_PREFIX "qp", 26, NULL, QP_TEXT, QP_LONGTEXT,
491                  false )
492         change_integer_range( 0, 51 ) /* QP 0 -> lossless encoding */
493
494 #if X264_BUILD >= 37 /* r334 */
495     add_integer( SOUT_CFG_PREFIX "crf", 0, NULL, CRF_TEXT,
496                  CRF_LONGTEXT, false )
497         change_integer_range( 0, 51 )
498 #endif
499
500     add_integer( SOUT_CFG_PREFIX "qpmin", 10, NULL, QPMIN_TEXT,
501                  QPMIN_LONGTEXT, false )
502         change_integer_range( 0, 51 )
503         add_deprecated_alias( SOUT_CFG_PREFIX "qp-min" ) /* Deprecated since 0.8.5 */
504
505     add_integer( SOUT_CFG_PREFIX "qpmax", 51, NULL, QPMAX_TEXT,
506                  QPMAX_LONGTEXT, false )
507         change_integer_range( 0, 51 )
508         add_deprecated_alias( SOUT_CFG_PREFIX "qp-max" ) /* Deprecated since 0.8.5 */
509
510     add_integer( SOUT_CFG_PREFIX "qpstep", 4, NULL, QPSTEP_TEXT,
511                  QPSTEP_LONGTEXT, false )
512         change_integer_range( 0, 51 )
513
514     add_float( SOUT_CFG_PREFIX "ratetol", 1.0, NULL, RATETOL_TEXT,
515                RATETOL_LONGTEXT, false )
516         change_float_range( 0, 100 )
517         add_deprecated_alias( SOUT_CFG_PREFIX "tolerance" ) /* Deprecated since 0.8.5 */
518
519     add_integer( SOUT_CFG_PREFIX "vbv-maxrate", 0, NULL, VBV_MAXRATE_TEXT,
520                  VBV_MAXRATE_LONGTEXT, false )
521
522     add_integer( SOUT_CFG_PREFIX "vbv-bufsize", 0, NULL, VBV_BUFSIZE_TEXT,
523                  VBV_BUFSIZE_LONGTEXT, false )
524
525     add_float( SOUT_CFG_PREFIX "vbv-init", 0.9, NULL, VBV_INIT_TEXT,
526                VBV_INIT_LONGTEXT, false )
527         change_float_range( 0, 1 )
528
529     add_float( SOUT_CFG_PREFIX "ipratio", 1.40, NULL, IPRATIO_TEXT,
530                IPRATIO_LONGTEXT, false )
531         change_float_range( 1, 2 )
532
533     add_float( SOUT_CFG_PREFIX "pbratio", 1.30, NULL, PBRATIO_TEXT,
534                PBRATIO_LONGTEXT, false )
535         change_float_range( 1, 2 )
536
537 #if X264_BUILD >= 23 /* r190 */
538     add_integer( SOUT_CFG_PREFIX "chroma-qp-offset", 0, NULL, CHROMA_QP_OFFSET_TEXT,
539                  CHROMA_QP_OFFSET_LONGTEXT, false )
540 #endif
541
542     add_integer( SOUT_CFG_PREFIX "pass", 0, NULL, PASS_TEXT,
543                  PASS_LONGTEXT, false )
544         change_integer_range( 0, 3 )
545
546     add_float( SOUT_CFG_PREFIX "qcomp", 0.60, NULL, QCOMP_TEXT,
547                QCOMP_LONGTEXT, false )
548         change_float_range( 0, 1 )
549
550     add_float( SOUT_CFG_PREFIX "cplxblur", 20.0, NULL, CPLXBLUR_TEXT,
551                CPLXBLUR_LONGTEXT, false )
552
553     add_float( SOUT_CFG_PREFIX "qblur", 0.5, NULL, QBLUR_TEXT,
554                QBLUR_LONGTEXT, false )
555 #if X264_BUILD >= 59
556     add_integer( SOUT_CFG_PREFIX "aq-mode", 2, NULL, AQ_MODE_TEXT,
557                  AQ_MODE_LONGTEXT, false )
558          change_integer_range( 0, 2 )
559     add_float( SOUT_CFG_PREFIX "aq-strength", 1.0, NULL, AQ_STRENGTH_TEXT,
560                AQ_STRENGTH_LONGTEXT, false )
561 #endif
562
563 /* Analysis */
564
565     /* x264 partitions = none (default). set at least "normal" mode. */
566     add_string( SOUT_CFG_PREFIX "partitions", "normal", NULL, ANALYSE_TEXT,
567                 ANALYSE_LONGTEXT, false )
568         change_string_list( enc_analyse_list, enc_analyse_list_text, 0 );
569         add_deprecated_alias( SOUT_CFG_PREFIX "analyse" ) /* Deprecated since 0.8.6 */
570
571     add_string( SOUT_CFG_PREFIX "direct", "spatial", NULL, DIRECT_PRED_TEXT,
572                 DIRECT_PRED_LONGTEXT, false )
573         change_string_list( direct_pred_list, direct_pred_list_text, 0 );
574
575 #if X264_BUILD >= 52 /* r573 */
576     add_integer( SOUT_CFG_PREFIX "direct-8x8", -1, NULL, DIRECT_PRED_SIZE_TEXT,
577                  DIRECT_PRED_SIZE_LONGTEXT, false )
578         change_integer_range( -1, 1 )
579 #endif
580
581 #if X264_BUILD >= 0x0012 /* r134 */
582     add_bool( SOUT_CFG_PREFIX "weightb", 0, NULL, WEIGHTB_TEXT,
583               WEIGHTB_LONGTEXT, false )
584 #endif
585
586 #if X264_BUILD >= 24 /* r221 */
587     add_string( SOUT_CFG_PREFIX "me", "hex", NULL, ME_TEXT,
588                 ME_LONGTEXT, false )
589         change_string_list( enc_me_list, enc_me_list_text, 0 );
590
591     add_integer( SOUT_CFG_PREFIX "merange", 16, NULL, MERANGE_TEXT,
592                  MERANGE_LONGTEXT, false )
593         change_integer_range( 1, 64 )
594 #endif
595
596     add_integer( SOUT_CFG_PREFIX "mvrange", -1, NULL, MVRANGE_TEXT,
597                  MVRANGE_LONGTEXT, false )
598
599 #if X264_BUILD >= 55 /* r607 */
600     add_integer( SOUT_CFG_PREFIX "mvrange-thread", -1, NULL, MVRANGE_THREAD_TEXT,
601                  MVRANGE_THREAD_LONGTEXT, false )
602 #endif
603
604     add_integer( SOUT_CFG_PREFIX "subme", 5, NULL, SUBME_TEXT,
605                  SUBME_LONGTEXT, false )
606         change_integer_range( 1, SUBME_MAX )
607         add_deprecated_alias( SOUT_CFG_PREFIX "subpel" ) /* Deprecated since 0.8.5 */
608
609 #if X264_BUILD >= 41 && X264_BUILD < 65 /* r368 */
610     add_bool( SOUT_CFG_PREFIX "b-rdo", 0, NULL, B_RDO_TEXT,
611               B_RDO_LONGTEXT, false )
612 #endif
613
614 #if X264_BUILD >= 36 /* r318 */
615     add_bool( SOUT_CFG_PREFIX "mixed-refs", 0, NULL, MIXED_REFS_TEXT,
616               MIXED_REFS_LONGTEXT, false )
617 #endif
618
619 #if X264_BUILD >= 23 /* r171 */
620     add_bool( SOUT_CFG_PREFIX "chroma-me", 1, NULL, CHROMA_ME_TEXT,
621               CHROMA_ME_LONGTEXT, false )
622 #endif
623
624 #if X264_BUILD >= 43 && X264_BUILD < 65 /* r390 */
625     add_bool( SOUT_CFG_PREFIX "bime", 0, NULL, BIME_TEXT,
626               BIME_LONGTEXT, false )
627 #endif
628
629 #if X264_BUILD >= 30 /* r251 */
630     add_bool( SOUT_CFG_PREFIX "8x8dct", 0, NULL, TRANSFORM_8X8DCT_TEXT,
631               TRANSFORM_8X8DCT_LONGTEXT, false )
632 #endif
633
634 #if X264_BUILD >= 39 /* r360 */
635     add_integer( SOUT_CFG_PREFIX "trellis", 0, NULL, TRELLIS_TEXT,
636                  TRELLIS_LONGTEXT, false )
637         change_integer_range( 0, 2 )
638 #endif
639
640 #if X264_BUILD >= 42 /* r384 */
641     add_bool( SOUT_CFG_PREFIX "fast-pskip", 1, NULL, FAST_PSKIP_TEXT,
642               FAST_PSKIP_LONGTEXT, false )
643 #endif
644
645 #if X264_BUILD >= 46 /* r503 */
646     add_bool( SOUT_CFG_PREFIX "dct-decimate", 1, NULL, DCT_DECIMATE_TEXT,
647               DCT_DECIMATE_LONGTEXT, false )
648 #endif
649
650 #if X264_BUILD >= 44 /* r398 */
651     add_integer( SOUT_CFG_PREFIX "nr", 0, NULL, NR_TEXT,
652                  NR_LONGTEXT, false )
653         change_integer_range( 0, 1000 )
654 #endif
655
656 #if X264_BUILD >= 52 /* r573 */
657     add_integer( SOUT_CFG_PREFIX "deadzone-inter", 21, NULL, DEADZONE_INTER_TEXT,
658                  DEADZONE_INTRA_LONGTEXT, false )
659         change_integer_range( 0, 32 )
660
661     add_integer( SOUT_CFG_PREFIX "deadzone-intra", 11, NULL, DEADZONE_INTRA_TEXT,
662                  DEADZONE_INTRA_LONGTEXT, false )
663         change_integer_range( 0, 32 )
664 #endif
665
666 /* Input/Output */
667
668 #if X264_BUILD >= 55 /* r607 */
669     add_bool( SOUT_CFG_PREFIX "non-deterministic", 0, NULL, NON_DETERMINISTIC_TEXT,
670               NON_DETERMINISTIC_LONGTEXT, false )
671 #endif
672
673     add_bool( SOUT_CFG_PREFIX "asm", 1, NULL, ASM_TEXT,
674               ASM_LONGTEXT, false )
675
676     /* x264 psnr = 1 (default). disable PSNR computation for speed. */
677     add_bool( SOUT_CFG_PREFIX "psnr", 0, NULL, PSNR_TEXT,
678               PSNR_LONGTEXT, false )
679
680 #if X264_BUILD >= 50 /* r554 */
681     /* x264 ssim = 1 (default). disable SSIM computation for speed. */
682     add_bool( SOUT_CFG_PREFIX "ssim", 0, NULL, SSIM_TEXT,
683               SSIM_LONGTEXT, false )
684 #endif
685
686     add_bool( SOUT_CFG_PREFIX "quiet", 0, NULL, QUIET_TEXT,
687               QUIET_LONGTEXT, false )
688
689 #if X264_BUILD >= 47 /* r518 */
690     add_integer( SOUT_CFG_PREFIX "sps-id", 0, NULL, SPS_ID_TEXT,
691                  SPS_ID_LONGTEXT, false )
692 #endif
693
694     add_bool( SOUT_CFG_PREFIX "aud", 0, NULL, AUD_TEXT,
695               AUD_LONGTEXT, false )
696
697 #if X264_BUILD >= 0x000e /* r81 */
698     add_bool( SOUT_CFG_PREFIX "verbose", 0, NULL, VERBOSE_TEXT,
699               VERBOSE_LONGTEXT, false )
700 #endif
701
702     add_string( SOUT_CFG_PREFIX "stats", "x264_2pass.log", NULL, STATS_TEXT,
703                 STATS_LONGTEXT, false )
704
705 vlc_module_end ()
706
707 /*****************************************************************************
708  * Local prototypes
709  *****************************************************************************/
710 static const char *const ppsz_sout_options[] = {
711     "8x8dct", "analyse", "asm", "aud", "bframes", "bime", "bpyramid",
712     "b-adapt", "b-bias", "b-rdo", "cabac", "chroma-me", "chroma-qp-offset",
713     "cplxblur", "crf", "dct-decimate", "deadzone-inter", "deadzone-intra",
714     "deblock", "direct", "direct-8x8", "filter", "fast-pskip", "frameref",
715     "interlaced", "ipratio", "keyint", "keyint-min", "level", "loopfilter",
716     "me", "merange", "min-keyint", "mixed-refs", "mvrange", "mvrange-thread",
717     "nf", "non-deterministic", "nr", "partitions", "pass", "pbratio",
718     "pre-scenecut", "psnr", "qblur", "qp", "qcomp", "qpstep", "qpmax",
719     "qpmin", "qp-max", "qp-min", "quiet", "ratetol", "ref", "scenecut",
720     "sps-id", "ssim", "stats", "subme", "subpel", "tolerance", "trellis",
721     "verbose", "vbv-bufsize", "vbv-init", "vbv-maxrate", "weightb", "aq-mode",
722     "aq-strength",NULL
723 };
724
725 static block_t *Encode( encoder_t *, picture_t * );
726
727 struct encoder_sys_t
728 {
729     x264_t          *h;
730     x264_param_t    param;
731
732     int             i_buffer;
733     uint8_t         *p_buffer;
734
735     mtime_t         i_interpolated_dts;
736
737     char *psz_stat_name;
738 };
739
740 /*****************************************************************************
741  * Open: probe the encoder
742  *****************************************************************************/
743 static int  Open ( vlc_object_t *p_this )
744 {
745     encoder_t     *p_enc = (encoder_t *)p_this;
746     encoder_sys_t *p_sys;
747     vlc_value_t    val;
748     int i_qmin = 0, i_qmax = 0;
749     x264_nal_t    *nal;
750     int i, i_nal;
751
752     if( p_enc->fmt_out.i_codec != VLC_FOURCC( 'h', '2', '6', '4' ) &&
753         !p_enc->b_force )
754     {
755         return VLC_EGENERIC;
756     }
757
758     /* X264_POINTVER or X264_VERSION are not available */
759     msg_Dbg ( p_enc, "version x264 0.%d.X", X264_BUILD );
760
761 #if X264_BUILD < 37
762     if( p_enc->fmt_in.video.i_width % 16 != 0 ||
763         p_enc->fmt_in.video.i_height % 16 != 0 )
764     {
765         msg_Warn( p_enc, "size is not a multiple of 16 (%ix%i)",
766                   p_enc->fmt_in.video.i_width, p_enc->fmt_in.video.i_height );
767
768         if( p_enc->fmt_in.video.i_width < 16 ||
769             p_enc->fmt_in.video.i_height < 16 )
770         {
771             msg_Err( p_enc, "video is too small to be cropped" );
772             return VLC_EGENERIC;
773         }
774
775         msg_Warn( p_enc, "cropping video to %ix%i",
776                   p_enc->fmt_in.video.i_width >> 4 << 4,
777                   p_enc->fmt_in.video.i_height >> 4 << 4 );
778     }
779 #endif
780
781     config_ChainParse( p_enc, SOUT_CFG_PREFIX, ppsz_sout_options, p_enc->p_cfg );
782
783     p_enc->fmt_out.i_cat = VIDEO_ES;
784     p_enc->fmt_out.i_codec = VLC_FOURCC( 'h', '2', '6', '4' );
785     p_enc->fmt_in.i_codec = VLC_FOURCC('I','4','2','0');
786
787     p_enc->pf_encode_video = Encode;
788     p_enc->pf_encode_audio = NULL;
789     p_enc->p_sys = p_sys = malloc( sizeof( encoder_sys_t ) );
790     if( !p_sys )
791         return VLC_ENOMEM;
792     p_sys->i_interpolated_dts = 0;
793     p_sys->psz_stat_name = NULL;
794
795     x264_param_default( &p_sys->param );
796     p_sys->param.i_width  = p_enc->fmt_in.video.i_width;
797     p_sys->param.i_height = p_enc->fmt_in.video.i_height;
798 #if X264_BUILD < 37
799     p_sys->param.i_width  = p_sys->param.i_width >> 4 << 4;
800     p_sys->param.i_height = p_sys->param.i_height >> 4 << 4;
801 #endif
802
803     /* average bitrate specified by transcode vb */
804     p_sys->param.rc.i_bitrate = p_enc->fmt_out.i_bitrate / 1000;
805
806     var_Get( p_enc, SOUT_CFG_PREFIX "qpstep", &val );
807     if( val.i_int >= 0 && val.i_int <= 51 ) p_sys->param.rc.i_qp_step = val.i_int;
808     var_Get( p_enc, SOUT_CFG_PREFIX "qpmin", &val );
809     if( val.i_int >= 0 && val.i_int <= 51 )
810     {
811         i_qmin = val.i_int;
812         p_sys->param.rc.i_qp_min = i_qmin;
813     }
814     var_Get( p_enc, SOUT_CFG_PREFIX "qpmax", &val );
815     if( val.i_int >= 0 && val.i_int <= 51 )
816     {
817         i_qmax = val.i_int;
818         p_sys->param.rc.i_qp_max = i_qmax;
819     }
820
821     var_Get( p_enc, SOUT_CFG_PREFIX "qp", &val );
822     if( val.i_int >= 0 && val.i_int <= 51 )
823     {
824         if( i_qmin > val.i_int ) i_qmin = val.i_int;
825         if( i_qmax < val.i_int ) i_qmax = val.i_int;
826
827         p_sys->param.rc.i_rc_method = X264_RC_CQP;
828 #if X264_BUILD >= 0x000a
829         p_sys->param.rc.i_qp_constant = val.i_int;
830         p_sys->param.rc.i_qp_min = i_qmin;
831         p_sys->param.rc.i_qp_max = i_qmax;
832 #else
833         p_sys->param.i_qp_constant = val.i_int;
834 #endif
835     }
836
837 #if X264_BUILD < 48
838     /* cbr = 1 overrides qp or crf and sets an average bitrate
839        but maxrate = average bitrate is needed for "real" CBR */
840     if( p_sys->param.rc.i_bitrate > 0 ) p_sys->param.rc.b_cbr = 1;
841 #else
842     if( p_sys->param.rc.i_bitrate > 0 ) p_sys->param.rc.i_rc_method = X264_RC_ABR;
843 #endif
844
845 #if X264_BUILD >= 24
846     var_Get( p_enc, SOUT_CFG_PREFIX "ratetol", &val );
847     p_sys->param.rc.f_rate_tolerance = val.f_float;
848
849     var_Get( p_enc, SOUT_CFG_PREFIX "vbv-init", &val );
850     p_sys->param.rc.f_vbv_buffer_init = val.f_float;
851
852     var_Get( p_enc, SOUT_CFG_PREFIX "vbv-bufsize", &val );
853     p_sys->param.rc.i_vbv_buffer_size = val.i_int;
854
855     /* x264 vbv-bufsize = 0 (default). if not provided set period
856        in seconds for local maximum bitrate (cache/bufsize) based
857        on average bitrate. */
858     if( !val.i_int )
859         p_sys->param.rc.i_vbv_buffer_size = p_sys->param.rc.i_bitrate * 2;
860
861     /* max bitrate = average bitrate -> CBR */
862     var_Get( p_enc, SOUT_CFG_PREFIX "vbv-maxrate", &val );
863     p_sys->param.rc.i_vbv_max_bitrate = val.i_int;
864
865 #else
866     p_sys->param.rc.i_rc_buffer_size = p_sys->param.rc.i_bitrate;
867     p_sys->param.rc.i_rc_init_buffer = p_sys->param.rc.i_bitrate / 4;
868 #endif
869
870     var_Get( p_enc, SOUT_CFG_PREFIX "cabac", &val );
871     p_sys->param.b_cabac = val.b_bool;
872
873     /* disable deblocking when nf (no loop filter) is enabled */
874     var_Get( p_enc, SOUT_CFG_PREFIX "nf", &val );
875     p_sys->param.b_deblocking_filter = !val.b_bool;
876
877     var_Get( p_enc, SOUT_CFG_PREFIX "deblock", &val );
878     if( val.psz_string )
879     {
880         char *p = strchr( val.psz_string, ':' );
881         p_sys->param.i_deblocking_filter_alphac0 = atoi( val.psz_string );
882         p_sys->param.i_deblocking_filter_beta = p ? atoi( p+1 ) : p_sys->param.i_deblocking_filter_alphac0;
883         free( val.psz_string );
884     }
885
886     var_Get( p_enc, SOUT_CFG_PREFIX "level", &val );
887     if( val.psz_string )
888     {
889         if( atof (val.psz_string) < 6 )
890             p_sys->param.i_level_idc = (int) ( 10 * atof (val.psz_string) + .5);
891         else
892             p_sys->param.i_level_idc = atoi (val.psz_string);
893         free( val.psz_string );
894     }
895
896 #if X264_BUILD >= 51 /* r570 */
897     var_Get( p_enc, SOUT_CFG_PREFIX "interlaced", &val );
898     p_sys->param.b_interlaced = val.b_bool;
899 #endif
900
901     var_Get( p_enc, SOUT_CFG_PREFIX "ipratio", &val );
902     p_sys->param.rc.f_ip_factor = val.f_float;
903
904     var_Get( p_enc, SOUT_CFG_PREFIX "pbratio", &val );
905     p_sys->param.rc.f_pb_factor = val.f_float;
906
907     var_Get( p_enc, SOUT_CFG_PREFIX "qcomp", &val );
908     p_sys->param.rc.f_qcompress = val.f_float;
909
910     var_Get( p_enc, SOUT_CFG_PREFIX "cplxblur", &val );
911     p_sys->param.rc.f_complexity_blur = val.f_float;
912
913     var_Get( p_enc, SOUT_CFG_PREFIX "qblur", &val );
914     p_sys->param.rc.f_qblur = val.f_float;
915
916 #if X264_BUILD >= 59
917     var_Get( p_enc, SOUT_CFG_PREFIX "aq-mode", &val );
918     p_sys->param.rc.i_aq_mode = val.i_int;
919
920     var_Get( p_enc, SOUT_CFG_PREFIX "aq-strength", &val );
921     p_sys->param.rc.f_aq_strength = val.f_float;
922 #endif
923
924 #if X264_BUILD >= 0x000e
925     var_Get( p_enc, SOUT_CFG_PREFIX "verbose", &val );
926     if( val.b_bool ) p_sys->param.i_log_level = X264_LOG_DEBUG;
927 #endif
928
929     var_Get( p_enc, SOUT_CFG_PREFIX "quiet", &val );
930     if( val.b_bool ) p_sys->param.i_log_level = X264_LOG_NONE;
931
932 #if X264_BUILD >= 47 /* r518 */
933     var_Get( p_enc, SOUT_CFG_PREFIX "sps-id", &val );
934     if( val.i_int >= 0 ) p_sys->param.i_sps_id = val.i_int;
935 #endif
936
937     var_Get( p_enc, SOUT_CFG_PREFIX "aud", &val );
938     if( val.b_bool ) p_sys->param.b_aud = val.b_bool;
939
940     var_Get( p_enc, SOUT_CFG_PREFIX "keyint", &val );
941 #if X264_BUILD >= 0x000e
942     if( val.i_int > 0 ) p_sys->param.i_keyint_max = val.i_int;
943 #else
944     if( val.i_int > 0 ) p_sys->param.i_iframe = val.i_int;
945 #endif
946
947     var_Get( p_enc, SOUT_CFG_PREFIX "min-keyint", &val );
948 #if X264_BUILD >= 0x000e
949     if( val.i_int > 0 ) p_sys->param.i_keyint_min = val.i_int;
950 #else
951     if( val.i_int > 0 ) p_sys->param.i_idrframe = val.i_int;
952 #endif
953
954     var_Get( p_enc, SOUT_CFG_PREFIX "bframes", &val );
955     if( val.i_int >= 0 && val.i_int <= 16 )
956         p_sys->param.i_bframe = val.i_int;
957
958 #if X264_BUILD >= 22
959     var_Get( p_enc, SOUT_CFG_PREFIX "bpyramid", &val );
960     p_sys->param.b_bframe_pyramid = val.b_bool;
961 #endif
962
963     var_Get( p_enc, SOUT_CFG_PREFIX "ref", &val );
964     if( val.i_int > 0 && val.i_int <= 15 )
965         p_sys->param.i_frame_reference = val.i_int;
966
967     var_Get( p_enc, SOUT_CFG_PREFIX "scenecut", &val );
968 #if X264_BUILD >= 0x000b
969     if( val.i_int >= -1 && val.i_int <= 100 )
970         p_sys->param.i_scenecut_threshold = val.i_int;
971 #endif
972
973 #if X264_BUILD >= 55 /* r607 */
974     var_Get( p_enc, SOUT_CFG_PREFIX "pre-scenecut", &val );
975     p_sys->param.b_pre_scenecut = val.b_bool;
976     var_Get( p_enc, SOUT_CFG_PREFIX "non-deterministic", &val );
977     p_sys->param.b_deterministic = val.b_bool;
978 #endif
979
980     var_Get( p_enc, SOUT_CFG_PREFIX "subme", &val );
981     if( val.i_int >= 1 && val.i_int <= SUBME_MAX )
982         p_sys->param.analyse.i_subpel_refine = val.i_int;
983
984 #if X264_BUILD >= 24
985     var_Get( p_enc, SOUT_CFG_PREFIX "me", &val );
986     if( !strcmp( val.psz_string, "dia" ) )
987     {
988         p_sys->param.analyse.i_me_method = X264_ME_DIA;
989     }
990     else if( !strcmp( val.psz_string, "hex" ) )
991     {
992         p_sys->param.analyse.i_me_method = X264_ME_HEX;
993     }
994     else if( !strcmp( val.psz_string, "umh" ) )
995     {
996         p_sys->param.analyse.i_me_method = X264_ME_UMH;
997     }
998     else if( !strcmp( val.psz_string, "esa" ) )
999     {
1000         p_sys->param.analyse.i_me_method = X264_ME_ESA;
1001     }
1002 #   if X264_BUILD >= 58 /* r728 */
1003     else if( !strcmp( val.psz_string, "tesa" ) )
1004     {
1005         p_sys->param.analyse.i_me_method = X264_ME_TESA;
1006     }
1007 #   endif
1008     free( val.psz_string );
1009
1010     var_Get( p_enc, SOUT_CFG_PREFIX "merange", &val );
1011     if( val.i_int >= 0 && val.i_int <= 64 )
1012         p_sys->param.analyse.i_me_range = val.i_int;
1013
1014     var_Get( p_enc, SOUT_CFG_PREFIX "mvrange", &val );
1015         p_sys->param.analyse.i_mv_range = val.i_int;
1016 #endif
1017
1018 #if X264_BUILD >= 55 /* r607 */
1019     var_Get( p_enc, SOUT_CFG_PREFIX "mvrange-thread", &val );
1020         p_sys->param.analyse.i_mv_range_thread = val.i_int;
1021 #endif
1022
1023     var_Get( p_enc, SOUT_CFG_PREFIX "direct", &val );
1024     if( !strcmp( val.psz_string, "none" ) )
1025     {
1026         p_sys->param.analyse.i_direct_mv_pred = X264_DIRECT_PRED_NONE;
1027     }
1028     else if( !strcmp( val.psz_string, "spatial" ) )
1029     {
1030         p_sys->param.analyse.i_direct_mv_pred = X264_DIRECT_PRED_SPATIAL;
1031     }
1032     else if( !strcmp( val.psz_string, "temporal" ) )
1033     {
1034         p_sys->param.analyse.i_direct_mv_pred = X264_DIRECT_PRED_TEMPORAL;
1035     }
1036 #if X264_BUILD >= 45 /* r457 */
1037     else if( !strcmp( val.psz_string, "auto" ) )
1038     {
1039         p_sys->param.analyse.i_direct_mv_pred = X264_DIRECT_PRED_AUTO;
1040     }
1041 #endif
1042     free( val.psz_string );
1043
1044     var_Get( p_enc, SOUT_CFG_PREFIX "psnr", &val );
1045     p_sys->param.analyse.b_psnr = val.b_bool;
1046
1047 #if X264_BUILD >= 50 /* r554 */
1048     var_Get( p_enc, SOUT_CFG_PREFIX "ssim", &val );
1049     p_sys->param.analyse.b_ssim = val.b_bool;
1050 #endif
1051
1052 #if X264_BUILD >= 0x0012
1053     var_Get( p_enc, SOUT_CFG_PREFIX "weightb", &val );
1054     p_sys->param.analyse.b_weighted_bipred = val.b_bool;
1055 #endif
1056
1057 #if X264_BUILD >= 0x0013
1058     var_Get( p_enc, SOUT_CFG_PREFIX "b-adapt", &val );
1059 #if X264_BUILD >= 63
1060     p_sys->param.i_bframe_adaptive = val.i_int;
1061 #else
1062     p_sys->param.b_bframe_adaptive = val.b_bool;
1063 #endif
1064
1065     var_Get( p_enc, SOUT_CFG_PREFIX "b-bias", &val );
1066     if( val.i_int >= -100 && val.i_int <= 100 )
1067         p_sys->param.i_bframe_bias = val.i_int;
1068 #endif
1069
1070 #if X264_BUILD >= 23
1071     var_Get( p_enc, SOUT_CFG_PREFIX "chroma-me", &val );
1072     p_sys->param.analyse.b_chroma_me = val.b_bool;
1073     var_Get( p_enc, SOUT_CFG_PREFIX "chroma-qp-offset", &val );
1074     p_sys->param.analyse.i_chroma_qp_offset = val.i_int;
1075 #endif
1076
1077 #if X264_BUILD >= 36
1078     var_Get( p_enc, SOUT_CFG_PREFIX "mixed-refs", &val );
1079     p_sys->param.analyse.b_mixed_references = val.b_bool;
1080 #endif
1081
1082 #if X264_BUILD >= 37
1083     var_Get( p_enc, SOUT_CFG_PREFIX "crf", &val );
1084     if( val.i_int > 0 && val.i_int <= 51 )
1085     {
1086 #   if X264_BUILD >= 54
1087         p_sys->param.rc.f_rf_constant = val.i_int;
1088 #   else
1089         p_sys->param.rc.i_rf_constant = val.i_int;
1090 #   endif
1091 #   if X264_BUILD >= 48
1092         p_sys->param.rc.i_rc_method = X264_RC_CRF;
1093 #   endif
1094     }
1095 #endif
1096
1097 #if X264_BUILD >= 39
1098     var_Get( p_enc, SOUT_CFG_PREFIX "trellis", &val );
1099     if( val.i_int >= 0 && val.i_int <= 2 )
1100         p_sys->param.analyse.i_trellis = val.i_int;
1101 #endif
1102
1103 #if X264_BUILD >= 41 && X264_BUILD < 65
1104     var_Get( p_enc, SOUT_CFG_PREFIX "b-rdo", &val );
1105     p_sys->param.analyse.b_bframe_rdo = val.b_bool;
1106 #endif
1107
1108 #if X264_BUILD >= 42
1109     var_Get( p_enc, SOUT_CFG_PREFIX "fast-pskip", &val );
1110     p_sys->param.analyse.b_fast_pskip = val.b_bool;
1111 #endif
1112
1113 #if X264_BUILD >= 43 && X264_BUILD < 65
1114     var_Get( p_enc, SOUT_CFG_PREFIX "bime", &val );
1115     p_sys->param.analyse.b_bidir_me = val.b_bool;
1116 #endif
1117
1118 #if X264_BUILD >= 44
1119     var_Get( p_enc, SOUT_CFG_PREFIX "nr", &val );
1120     if( val.i_int >= 0 && val.i_int <= 1000 )
1121         p_sys->param.analyse.i_noise_reduction = val.i_int;
1122 #endif
1123
1124 #if X264_BUILD >= 46
1125     var_Get( p_enc, SOUT_CFG_PREFIX "dct-decimate", &val );
1126     p_sys->param.analyse.b_dct_decimate = val.b_bool;
1127 #endif
1128
1129 #if X264_BUILD >= 52
1130     var_Get( p_enc, SOUT_CFG_PREFIX "deadzone-inter", &val );
1131     if( val.i_int >= 0 && val.i_int <= 32 )
1132         p_sys->param.analyse.i_luma_deadzone[0] = val.i_int;
1133
1134     var_Get( p_enc, SOUT_CFG_PREFIX "deadzone-intra", &val );
1135     if( val.i_int >= 0 && val.i_int <= 32 )
1136         p_sys->param.analyse.i_luma_deadzone[1] = val.i_int;
1137
1138 #if X264_BUILD <= 65
1139     var_Get( p_enc, SOUT_CFG_PREFIX "direct-8x8", &val );
1140     if( val.i_int >= -1 && val.i_int <= 1 )
1141         p_sys->param.analyse.i_direct_8x8_inference = val.i_int;
1142 #endif
1143 #endif
1144
1145     var_Get( p_enc, SOUT_CFG_PREFIX "asm", &val );
1146     if( !val.b_bool ) p_sys->param.cpu = 0;
1147
1148 #ifndef X264_ANALYSE_BSUB16x16
1149 #   define X264_ANALYSE_BSUB16x16 0
1150 #endif
1151     var_Get( p_enc, SOUT_CFG_PREFIX "partitions", &val );
1152     if( !strcmp( val.psz_string, "none" ) )
1153     {
1154         p_sys->param.analyse.inter = 0;
1155     }
1156     else if( !strcmp( val.psz_string, "fast" ) )
1157     {
1158         p_sys->param.analyse.inter = X264_ANALYSE_I4x4;
1159     }
1160     else if( !strcmp( val.psz_string, "normal" ) )
1161     {
1162         p_sys->param.analyse.inter =
1163             X264_ANALYSE_I4x4 |
1164             X264_ANALYSE_PSUB16x16;
1165 #ifdef X264_ANALYSE_I8x8
1166         p_sys->param.analyse.inter |= X264_ANALYSE_I8x8;
1167 #endif
1168     }
1169     else if( !strcmp( val.psz_string, "slow" ) )
1170     {
1171         p_sys->param.analyse.inter =
1172             X264_ANALYSE_I4x4 |
1173             X264_ANALYSE_PSUB16x16 |
1174             X264_ANALYSE_BSUB16x16;
1175 #ifdef X264_ANALYSE_I8x8
1176         p_sys->param.analyse.inter |= X264_ANALYSE_I8x8;
1177 #endif
1178     }
1179     else if( !strcmp( val.psz_string, "all" ) )
1180     {
1181         p_sys->param.analyse.inter =
1182             X264_ANALYSE_I4x4 |
1183             X264_ANALYSE_PSUB16x16 |
1184             X264_ANALYSE_BSUB16x16 |
1185             X264_ANALYSE_PSUB8x8;
1186 #ifdef X264_ANALYSE_I8x8
1187         p_sys->param.analyse.inter |= X264_ANALYSE_I8x8;
1188 #endif
1189     }
1190     free( val.psz_string );
1191
1192 #if X264_BUILD >= 30
1193     var_Get( p_enc, SOUT_CFG_PREFIX "8x8dct", &val );
1194     p_sys->param.analyse.b_transform_8x8 = val.b_bool;
1195 #endif
1196
1197     if( p_enc->fmt_in.video.i_aspect > 0 )
1198     {
1199         int64_t i_num, i_den;
1200         unsigned int i_dst_num, i_dst_den;
1201
1202         i_num = p_enc->fmt_in.video.i_aspect *
1203             (int64_t)p_enc->fmt_in.video.i_height;
1204         i_den = VOUT_ASPECT_FACTOR * p_enc->fmt_in.video.i_width;
1205         vlc_ureduce( &i_dst_num, &i_dst_den, i_num, i_den, 0 );
1206
1207         p_sys->param.vui.i_sar_width = i_dst_num;
1208         p_sys->param.vui.i_sar_height = i_dst_den;
1209     }
1210
1211     if( p_enc->fmt_in.video.i_frame_rate_base > 0 )
1212     {
1213         p_sys->param.i_fps_num = p_enc->fmt_in.video.i_frame_rate;
1214         p_sys->param.i_fps_den = p_enc->fmt_in.video.i_frame_rate_base;
1215     }
1216
1217     unsigned i_cpu = vlc_CPU();
1218     if( !(i_cpu & CPU_CAPABILITY_MMX) )
1219     {
1220         p_sys->param.cpu &= ~X264_CPU_MMX;
1221     }
1222     if( !(i_cpu & CPU_CAPABILITY_MMXEXT) )
1223     {
1224         p_sys->param.cpu &= ~X264_CPU_MMXEXT;
1225     }
1226     if( !(i_cpu & CPU_CAPABILITY_SSE) )
1227     {
1228         p_sys->param.cpu &= ~X264_CPU_SSE;
1229     }
1230     if( !(i_cpu & CPU_CAPABILITY_SSE2) )
1231     {
1232         p_sys->param.cpu &= ~X264_CPU_SSE2;
1233     }
1234
1235     /* BUILD 29 adds support for multi-threaded encoding while BUILD 49 (r543)
1236        also adds support for threads = 0 for automatically selecting an optimal
1237        value (cores * 1.5) based on detected CPUs. Default behavior for x264 is
1238        threads = 1, however VLC usage differs and uses threads = 0 (auto) by
1239        default unless ofcourse transcode threads is explicitly specified.. */
1240 #if X264_BUILD >= 29
1241     p_sys->param.i_threads = p_enc->i_threads;
1242 #endif
1243
1244     var_Get( p_enc, SOUT_CFG_PREFIX "stats", &val );
1245     if( val.psz_string )
1246     {
1247         p_sys->param.rc.psz_stat_in  =
1248         p_sys->param.rc.psz_stat_out =
1249         p_sys->psz_stat_name         = val.psz_string;
1250     }
1251
1252     var_Get( p_enc, SOUT_CFG_PREFIX "pass", &val );
1253     if( val.i_int > 0 && val.i_int <= 3 )
1254     {
1255         p_sys->param.rc.b_stat_write = val.i_int & 1;
1256         p_sys->param.rc.b_stat_read = val.i_int & 2;
1257     }
1258
1259     /* We need to initialize pthreadw32 before we open the encoder,
1260        but only oncce for the whole application. Since pthreadw32
1261        doesn't keep a refcount, do it ourselves. */
1262 #ifdef PTW32_STATIC_LIB
1263     vlc_value_t lock, count;
1264
1265     var_Create( p_enc->p_libvlc, "pthread_win32_mutex", VLC_VAR_MUTEX );
1266     var_Get( p_enc->p_libvlc, "pthread_win32_mutex", &lock );
1267     vlc_mutex_lock( lock.p_address );
1268
1269     var_Create( p_enc->p_libvlc, "pthread_win32_count", VLC_VAR_INTEGER );
1270     var_Get( p_enc->p_libvlc, "pthread_win32_count", &count );
1271
1272     if( count.i_int == 0 )
1273     {
1274         msg_Dbg( p_enc, "initializing pthread-win32" );
1275         if( !pthread_win32_process_attach_np() || !pthread_win32_thread_attach_np() )   
1276         {
1277             msg_Warn( p_enc, "pthread Win32 Initialization failed" );
1278             vlc_mutex_unlock( lock.p_address );
1279             return VLC_EGENERIC;
1280         }
1281     }
1282
1283     count.i_int++;
1284     var_Set( p_enc->p_libvlc, "pthread_win32_count", count );
1285     vlc_mutex_unlock( lock.p_address );
1286
1287 #endif
1288
1289     /* Open the encoder */
1290     p_sys->h = x264_encoder_open( &p_sys->param );
1291
1292     /* alloc mem */
1293     p_sys->i_buffer = 4 * p_enc->fmt_in.video.i_width *
1294         p_enc->fmt_in.video.i_height + 1000;
1295     p_sys->p_buffer = malloc( p_sys->i_buffer );
1296     if( !p_sys->p_buffer )
1297     {
1298         Close( VLC_OBJECT(p_enc) );
1299         return VLC_ENOMEM;
1300     }
1301
1302     /* get the globals headers */
1303     p_enc->fmt_out.i_extra = 0;
1304     p_enc->fmt_out.p_extra = NULL;
1305
1306     x264_encoder_headers( p_sys->h, &nal, &i_nal );
1307     for( i = 0; i < i_nal; i++ )
1308     {
1309         void *p_tmp;
1310         int i_size = p_sys->i_buffer;
1311
1312         x264_nal_encode( p_sys->p_buffer, &i_size, 1, &nal[i] );
1313
1314         p_tmp = realloc( p_enc->fmt_out.p_extra, p_enc->fmt_out.i_extra + i_size );
1315         if( !p_tmp )
1316         {
1317             Close( VLC_OBJECT(p_enc) );
1318             return VLC_ENOMEM;
1319         }
1320         p_enc->fmt_out.p_extra = p_tmp;
1321
1322         memcpy( (uint8_t*)p_enc->fmt_out.p_extra + p_enc->fmt_out.i_extra,
1323                 p_sys->p_buffer, i_size );
1324
1325         p_enc->fmt_out.i_extra += i_size;
1326     }
1327
1328     return VLC_SUCCESS;
1329 }
1330
1331 /****************************************************************************
1332  * Encode:
1333  ****************************************************************************/
1334 static block_t *Encode( encoder_t *p_enc, picture_t *p_pict )
1335 {
1336     encoder_sys_t *p_sys = p_enc->p_sys;
1337     x264_picture_t pic;
1338     x264_nal_t *nal;
1339     block_t *p_block;
1340     int i_nal, i_out, i;
1341
1342     /* init pic */
1343     memset( &pic, 0, sizeof( x264_picture_t ) );
1344     pic.i_pts = p_pict->date;
1345     pic.img.i_csp = X264_CSP_I420;
1346     pic.img.i_plane = p_pict->i_planes;
1347     for( i = 0; i < p_pict->i_planes; i++ )
1348     {
1349         pic.img.plane[i] = p_pict->p[i].p_pixels;
1350         pic.img.i_stride[i] = p_pict->p[i].i_pitch;
1351     }
1352
1353 #if X264_BUILD >= 0x0013
1354     x264_encoder_encode( p_sys->h, &nal, &i_nal, &pic, &pic );
1355 #else
1356     x264_encoder_encode( p_sys->h, &nal, &i_nal, &pic );
1357 #endif
1358
1359     if( !i_nal ) return NULL;
1360
1361     for( i = 0, i_out = 0; i < i_nal; i++ )
1362     {
1363         int i_size = p_sys->i_buffer - i_out;
1364         x264_nal_encode( p_sys->p_buffer + i_out, &i_size, 1, &nal[i] );
1365
1366         i_out += i_size;
1367     }
1368
1369     p_block = block_New( p_enc, i_out );
1370     if( !p_block ) return NULL;
1371     memcpy( p_block->p_buffer, p_sys->p_buffer, i_out );
1372
1373     if( pic.i_type == X264_TYPE_IDR || pic.i_type == X264_TYPE_I )
1374         p_block->i_flags |= BLOCK_FLAG_TYPE_I;
1375     else if( pic.i_type == X264_TYPE_P )
1376         p_block->i_flags |= BLOCK_FLAG_TYPE_P;
1377     else if( pic.i_type == X264_TYPE_B )
1378         p_block->i_flags |= BLOCK_FLAG_TYPE_B;
1379
1380     /* This isn't really valid for streams with B-frames */
1381     p_block->i_length = INT64_C(1000000) *
1382         p_enc->fmt_in.video.i_frame_rate_base /
1383             p_enc->fmt_in.video.i_frame_rate;
1384
1385     p_block->i_pts = pic.i_pts;
1386
1387     if( p_sys->param.i_bframe > 0 )
1388     {
1389         if( p_block->i_flags & BLOCK_FLAG_TYPE_B )
1390         {
1391             /* FIXME : this is wrong if bpyramid is set */
1392             p_block->i_dts = p_block->i_pts;
1393             p_sys->i_interpolated_dts = p_block->i_dts;
1394         }
1395         else
1396         {
1397             if( p_sys->i_interpolated_dts )
1398             {
1399                 p_block->i_dts = p_sys->i_interpolated_dts;
1400             }
1401             else
1402             {
1403                 /* Let's put something sensible */
1404                 p_block->i_dts = p_block->i_pts;
1405             }
1406
1407             p_sys->i_interpolated_dts += p_block->i_length;
1408         }
1409     }
1410     else
1411     {
1412         p_block->i_dts = p_block->i_pts;
1413     }
1414
1415     return p_block;
1416 }
1417
1418 /*****************************************************************************
1419  * CloseEncoder: x264 encoder destruction
1420  *****************************************************************************/
1421 static void Close( vlc_object_t *p_this )
1422 {
1423     encoder_t     *p_enc = (encoder_t *)p_this;
1424     encoder_sys_t *p_sys = p_enc->p_sys;
1425
1426     free( p_sys->psz_stat_name );
1427
1428     x264_encoder_close( p_sys->h );
1429
1430 #ifdef PTW32_STATIC_LIB
1431     vlc_value_t lock, count;
1432
1433     var_Create( p_enc->p_libvlc, "pthread_win32_mutex", VLC_VAR_MUTEX );
1434     var_Get( p_enc->p_libvlc, "pthread_win32_mutex", &lock );
1435     vlc_mutex_lock( lock.p_address );
1436
1437     var_Create( p_enc->p_libvlc, "pthread_win32_count", VLC_VAR_INTEGER );
1438     var_Get( p_enc->p_libvlc, "pthread_win32_count", &count );
1439     count.i_int--;
1440     var_Set( p_enc->p_libvlc, "pthread_win32_count", count );
1441
1442     if( count.i_int == 0 )
1443     {
1444         pthread_win32_thread_detach_np();
1445         pthread_win32_process_detach_np();
1446         msg_Dbg( p_enc, "pthread-win32 deinitialized" );
1447     }
1448     vlc_mutex_unlock( lock.p_address );
1449 #endif
1450
1451     free( p_sys->p_buffer );
1452     free( p_sys );
1453 }