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