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