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