WebM Codec SDK

vpxenc
1 /*
2 * Copyright (c) 2010 The WebM project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11 #include "./vpxenc.h"
12 #include "./vpx_config.h"
13
14 #include <assert.h>
15 #include <limits.h>
16 #include <math.h>
17 #include <stdarg.h>
18 #include <stdio.h>
19 #include <stdlib.h>
20 #include <string.h>
21
22 #if CONFIG_LIBYUV
23 #include "third_party/libyuv/include/libyuv/scale.h"
24 #endif
25
26 #include "vpx/vpx_encoder.h"
27 #if CONFIG_DECODERS
28 #include "vpx/vpx_decoder.h"
29 #endif
30
31 #include "./args.h"
32 #include "./ivfenc.h"
33 #include "./tools_common.h"
34
35 #if CONFIG_VP8_ENCODER || CONFIG_VP9_ENCODER
36 #include "vpx/vp8cx.h"
37 #endif
38 #if CONFIG_VP8_DECODER || CONFIG_VP9_DECODER
39 #include "vpx/vp8dx.h"
40 #endif
41
42 #include "vpx/vpx_integer.h"
43 #include "vpx_ports/mem_ops.h"
44 #include "vpx_ports/vpx_timer.h"
45 #include "./rate_hist.h"
46 #include "./vpxstats.h"
47 #include "./warnings.h"
48 #if CONFIG_WEBM_IO
49 #include "./webmenc.h"
50 #endif
51 #include "./y4minput.h"
52
53 /* Swallow warnings about unused results of fread/fwrite */
54 static size_t wrap_fread(void *ptr, size_t size, size_t nmemb, FILE *stream) {
55 return fread(ptr, size, nmemb, stream);
56 }
57 #define fread wrap_fread
58
59 static size_t wrap_fwrite(const void *ptr, size_t size, size_t nmemb,
60 FILE *stream) {
61 return fwrite(ptr, size, nmemb, stream);
62 }
63 #define fwrite wrap_fwrite
64
65 static const char *exec_name;
66
67 static void warn_or_exit_on_errorv(vpx_codec_ctx_t *ctx, int fatal,
68 const char *s, va_list ap) {
69 if (ctx->err) {
70 const char *detail = vpx_codec_error_detail(ctx);
71
72 vfprintf(stderr, s, ap);
73 fprintf(stderr, ": %s\n", vpx_codec_error(ctx));
74
75 if (detail) fprintf(stderr, " %s\n", detail);
76
77 if (fatal) exit(EXIT_FAILURE);
78 }
79 }
80
81 static void ctx_exit_on_error(vpx_codec_ctx_t *ctx, const char *s, ...) {
82 va_list ap;
83
84 va_start(ap, s);
85 warn_or_exit_on_errorv(ctx, 1, s, ap);
86 va_end(ap);
87 }
88
89 static void warn_or_exit_on_error(vpx_codec_ctx_t *ctx, int fatal,
90 const char *s, ...) {
91 va_list ap;
92
93 va_start(ap, s);
94 warn_or_exit_on_errorv(ctx, fatal, s, ap);
95 va_end(ap);
96 }
97
98 static int read_frame(struct VpxInputContext *input_ctx, vpx_image_t *img) {
99 FILE *f = input_ctx->file;
100 y4m_input *y4m = &input_ctx->y4m;
101 int shortread = 0;
102
103 if (input_ctx->file_type == FILE_TYPE_Y4M) {
104 if (y4m_input_fetch_frame(y4m, f, img) < 1) return 0;
105 } else {
106 shortread = read_yuv_frame(input_ctx, img);
107 }
108
109 return !shortread;
110 }
111
112 static int file_is_y4m(const char detect[4]) {
113 if (memcmp(detect, "YUV4", 4) == 0) {
114 return 1;
115 }
116 return 0;
117 }
118
119 static int fourcc_is_ivf(const char detect[4]) {
120 if (memcmp(detect, "DKIF", 4) == 0) {
121 return 1;
122 }
123 return 0;
124 }
125
126 static const arg_def_t help =
127 ARG_DEF(NULL, "help", 0, "Show usage options and exit");
128 static const arg_def_t debugmode =
129 ARG_DEF("D", "debug", 0, "Debug mode (makes output deterministic)");
130 static const arg_def_t outputfile =
131 ARG_DEF("o", "output", 1, "Output filename");
132 static const arg_def_t use_yv12 =
133 ARG_DEF(NULL, "yv12", 0, "Input file is YV12 ");
134 static const arg_def_t use_i420 =
135 ARG_DEF(NULL, "i420", 0, "Input file is I420 (default)");
136 static const arg_def_t use_i422 =
137 ARG_DEF(NULL, "i422", 0, "Input file is I422");
138 static const arg_def_t use_i444 =
139 ARG_DEF(NULL, "i444", 0, "Input file is I444");
140 static const arg_def_t use_i440 =
141 ARG_DEF(NULL, "i440", 0, "Input file is I440");
142 static const arg_def_t codecarg = ARG_DEF(NULL, "codec", 1, "Codec to use");
143 static const arg_def_t passes =
144 ARG_DEF("p", "passes", 1, "Number of passes (1/2)");
145 static const arg_def_t pass_arg =
146 ARG_DEF(NULL, "pass", 1, "Pass to execute (1/2)");
147 static const arg_def_t fpf_name =
148 ARG_DEF(NULL, "fpf", 1, "First pass statistics file name");
149 #if CONFIG_FP_MB_STATS
150 static const arg_def_t fpmbf_name =
151 ARG_DEF(NULL, "fpmbf", 1, "First pass block statistics file name");
152 #endif
153 static const arg_def_t limit =
154 ARG_DEF(NULL, "limit", 1, "Stop encoding after n input frames");
155 static const arg_def_t skip =
156 ARG_DEF(NULL, "skip", 1, "Skip the first n input frames");
157 static const arg_def_t deadline =
158 ARG_DEF("d", "deadline", 1, "Deadline per frame (usec)");
159 static const arg_def_t best_dl =
160 ARG_DEF(NULL, "best", 0, "Use Best Quality Deadline");
161 static const arg_def_t good_dl =
162 ARG_DEF(NULL, "good", 0, "Use Good Quality Deadline");
163 static const arg_def_t rt_dl =
164 ARG_DEF(NULL, "rt", 0, "Use Realtime Quality Deadline");
165 static const arg_def_t quietarg =
166 ARG_DEF("q", "quiet", 0, "Do not print encode progress");
167 static const arg_def_t verbosearg =
168 ARG_DEF("v", "verbose", 0, "Show encoder parameters");
169 static const arg_def_t psnrarg =
170 ARG_DEF(NULL, "psnr", 0, "Show PSNR in status line");
171
172 static const struct arg_enum_list test_decode_enum[] = {
173 { "off", TEST_DECODE_OFF },
174 { "fatal", TEST_DECODE_FATAL },
175 { "warn", TEST_DECODE_WARN },
176 { NULL, 0 }
177 };
178 static const arg_def_t recontest = ARG_DEF_ENUM(
179 NULL, "test-decode", 1, "Test encode/decode mismatch", test_decode_enum);
180 static const arg_def_t framerate =
181 ARG_DEF(NULL, "fps", 1, "Stream frame rate (rate/scale)");
182 static const arg_def_t use_webm =
183 ARG_DEF(NULL, "webm", 0, "Output WebM (default when WebM IO is enabled)");
184 static const arg_def_t use_ivf = ARG_DEF(NULL, "ivf", 0, "Output IVF");
185 static const arg_def_t out_part =
186 ARG_DEF("P", "output-partitions", 0,
187 "Makes encoder output partitions. Requires IVF output!");
188 static const arg_def_t q_hist_n =
189 ARG_DEF(NULL, "q-hist", 1, "Show quantizer histogram (n-buckets)");
190 static const arg_def_t rate_hist_n =
191 ARG_DEF(NULL, "rate-hist", 1, "Show rate histogram (n-buckets)");
192 static const arg_def_t disable_warnings =
193 ARG_DEF(NULL, "disable-warnings", 0,
194 "Disable warnings about potentially incorrect encode settings.");
195 static const arg_def_t disable_warning_prompt =
196 ARG_DEF("y", "disable-warning-prompt", 0,
197 "Display warnings, but do not prompt user to continue.");
198
199 #if CONFIG_VP9_HIGHBITDEPTH
200 static const arg_def_t test16bitinternalarg = ARG_DEF(
201 NULL, "test-16bit-internal", 0, "Force use of 16 bit internal buffer");
202 #endif
203
204 static const arg_def_t *main_args[] = { &help,
205 &debugmode,
206 &outputfile,
207 &codecarg,
208 &passes,
209 &pass_arg,
210 &fpf_name,
211 &limit,
212 &skip,
213 &deadline,
214 &best_dl,
215 &good_dl,
216 &rt_dl,
217 &quietarg,
218 &verbosearg,
219 &psnrarg,
220 &use_webm,
221 &use_ivf,
222 &out_part,
223 &q_hist_n,
224 &rate_hist_n,
225 &disable_warnings,
226 &disable_warning_prompt,
227 &recontest,
228 NULL };
229
230 static const arg_def_t usage =
231 ARG_DEF("u", "usage", 1, "Usage profile number to use");
232 static const arg_def_t threads =
233 ARG_DEF("t", "threads", 1, "Max number of threads to use");
234 static const arg_def_t profile =
235 ARG_DEF(NULL, "profile", 1, "Bitstream profile number to use");
236 static const arg_def_t width = ARG_DEF("w", "width", 1, "Frame width");
237 static const arg_def_t height = ARG_DEF("h", "height", 1, "Frame height");
238 #if CONFIG_WEBM_IO
239 static const struct arg_enum_list stereo_mode_enum[] = {
240 { "mono", STEREO_FORMAT_MONO },
241 { "left-right", STEREO_FORMAT_LEFT_RIGHT },
242 { "bottom-top", STEREO_FORMAT_BOTTOM_TOP },
243 { "top-bottom", STEREO_FORMAT_TOP_BOTTOM },
244 { "right-left", STEREO_FORMAT_RIGHT_LEFT },
245 { NULL, 0 }
246 };
247 static const arg_def_t stereo_mode = ARG_DEF_ENUM(
248 NULL, "stereo-mode", 1, "Stereo 3D video format", stereo_mode_enum);
249 #endif
250 static const arg_def_t timebase = ARG_DEF(
251 NULL, "timebase", 1, "Output timestamp precision (fractional seconds)");
252 static const arg_def_t error_resilient =
253 ARG_DEF(NULL, "error-resilient", 1, "Enable error resiliency features");
254 static const arg_def_t lag_in_frames =
255 ARG_DEF(NULL, "lag-in-frames", 1, "Max number of frames to lag");
256
257 static const arg_def_t *global_args[] = { &use_yv12,
258 &use_i420,
259 &use_i422,
260 &use_i444,
261 &use_i440,
262 &usage,
263 &threads,
264 &profile,
265 &width,
266 &height,
267 #if CONFIG_WEBM_IO
268 &stereo_mode,
269 #endif
270 &timebase,
271 &framerate,
272 &error_resilient,
273 #if CONFIG_VP9_HIGHBITDEPTH
274 &test16bitinternalarg,
275 #endif
276 &lag_in_frames,
277 NULL };
278
279 static const arg_def_t dropframe_thresh =
280 ARG_DEF(NULL, "drop-frame", 1, "Temporal resampling threshold (buf %)");
281 static const arg_def_t resize_allowed =
282 ARG_DEF(NULL, "resize-allowed", 1, "Spatial resampling enabled (bool)");
283 static const arg_def_t resize_width =
284 ARG_DEF(NULL, "resize-width", 1, "Width of encoded frame");
285 static const arg_def_t resize_height =
286 ARG_DEF(NULL, "resize-height", 1, "Height of encoded frame");
287 static const arg_def_t resize_up_thresh =
288 ARG_DEF(NULL, "resize-up", 1, "Upscale threshold (buf %)");
289 static const arg_def_t resize_down_thresh =
290 ARG_DEF(NULL, "resize-down", 1, "Downscale threshold (buf %)");
291 static const struct arg_enum_list end_usage_enum[] = { { "vbr", VPX_VBR },
292 { "cbr", VPX_CBR },
293 { "cq", VPX_CQ },
294 { "q", VPX_Q },
295 { NULL, 0 } };
296 static const arg_def_t end_usage =
297 ARG_DEF_ENUM(NULL, "end-usage", 1, "Rate control mode", end_usage_enum);
298 static const arg_def_t target_bitrate =
299 ARG_DEF(NULL, "target-bitrate", 1, "Bitrate (kbps)");
300 static const arg_def_t min_quantizer =
301 ARG_DEF(NULL, "min-q", 1, "Minimum (best) quantizer");
302 static const arg_def_t max_quantizer =
303 ARG_DEF(NULL, "max-q", 1, "Maximum (worst) quantizer");
304 static const arg_def_t undershoot_pct =
305 ARG_DEF(NULL, "undershoot-pct", 1, "Datarate undershoot (min) target (%)");
306 static const arg_def_t overshoot_pct =
307 ARG_DEF(NULL, "overshoot-pct", 1, "Datarate overshoot (max) target (%)");
308 static const arg_def_t buf_sz =
309 ARG_DEF(NULL, "buf-sz", 1, "Client buffer size (ms)");
310 static const arg_def_t buf_initial_sz =
311 ARG_DEF(NULL, "buf-initial-sz", 1, "Client initial buffer size (ms)");
312 static const arg_def_t buf_optimal_sz =
313 ARG_DEF(NULL, "buf-optimal-sz", 1, "Client optimal buffer size (ms)");
314 static const arg_def_t *rc_args[] = {
315 &dropframe_thresh, &resize_allowed, &resize_width, &resize_height,
316 &resize_up_thresh, &resize_down_thresh, &end_usage, &target_bitrate,
317 &min_quantizer, &max_quantizer, &undershoot_pct, &overshoot_pct,
318 &buf_sz, &buf_initial_sz, &buf_optimal_sz, NULL
319 };
320
321 static const arg_def_t bias_pct =
322 ARG_DEF(NULL, "bias-pct", 1, "CBR/VBR bias (0=CBR, 100=VBR)");
323 static const arg_def_t minsection_pct =
324 ARG_DEF(NULL, "minsection-pct", 1, "GOP min bitrate (% of target)");
325 static const arg_def_t maxsection_pct =
326 ARG_DEF(NULL, "maxsection-pct", 1, "GOP max bitrate (% of target)");
327 static const arg_def_t corpus_complexity =
328 ARG_DEF(NULL, "corpus-complexity", 1, "corpus vbr complexity midpoint");
329 static const arg_def_t *rc_twopass_args[] = {
330 &bias_pct, &minsection_pct, &maxsection_pct, &corpus_complexity, NULL
331 };
332
333 static const arg_def_t kf_min_dist =
334 ARG_DEF(NULL, "kf-min-dist", 1, "Minimum keyframe interval (frames)");
335 static const arg_def_t kf_max_dist =
336 ARG_DEF(NULL, "kf-max-dist", 1, "Maximum keyframe interval (frames)");
337 static const arg_def_t kf_disabled =
338 ARG_DEF(NULL, "disable-kf", 0, "Disable keyframe placement");
339 static const arg_def_t *kf_args[] = { &kf_min_dist, &kf_max_dist, &kf_disabled,
340 NULL };
341
342 static const arg_def_t noise_sens =
343 ARG_DEF(NULL, "noise-sensitivity", 1, "Noise sensitivity (frames to blur)");
344 static const arg_def_t sharpness =
345 ARG_DEF(NULL, "sharpness", 1,
346 "Increase sharpness at the expense of lower PSNR. (0..7)");
347 static const arg_def_t static_thresh =
348 ARG_DEF(NULL, "static-thresh", 1, "Motion detection threshold");
349 static const arg_def_t auto_altref =
350 ARG_DEF(NULL, "auto-alt-ref", 1, "Enable automatic alt reference frames");
351 static const arg_def_t arnr_maxframes =
352 ARG_DEF(NULL, "arnr-maxframes", 1, "AltRef max frames (0..15)");
353 static const arg_def_t arnr_strength =
354 ARG_DEF(NULL, "arnr-strength", 1, "AltRef filter strength (0..6)");
355 static const arg_def_t arnr_type =
356 ARG_DEF(NULL, "arnr-type", 1, "AltRef filter type (1..3)");
357 static const struct arg_enum_list tuning_enum[] = {
358 { "psnr", VP8_TUNE_PSNR }, { "ssim", VP8_TUNE_SSIM }, { NULL, 0 }
359 };
360 static const arg_def_t tune_ssim =
361 ARG_DEF_ENUM(NULL, "tune", 1, "Material to favor", tuning_enum);
362 static const arg_def_t cq_level =
363 ARG_DEF(NULL, "cq-level", 1, "Constant/Constrained Quality level");
364 static const arg_def_t max_intra_rate_pct =
365 ARG_DEF(NULL, "max-intra-rate", 1, "Max I-frame bitrate (pct)");
366 static const arg_def_t gf_cbr_boost_pct = ARG_DEF(
367 NULL, "gf-cbr-boost", 1, "Boost for Golden Frame in CBR mode (pct)");
368
369 #if CONFIG_VP8_ENCODER
370 static const arg_def_t cpu_used_vp8 =
371 ARG_DEF(NULL, "cpu-used", 1, "CPU Used (-16..16)");
372 static const arg_def_t token_parts =
373 ARG_DEF(NULL, "token-parts", 1, "Number of token partitions to use, log2");
374 static const arg_def_t screen_content_mode =
375 ARG_DEF(NULL, "screen-content-mode", 1, "Screen content mode");
376 static const arg_def_t *vp8_args[] = { &cpu_used_vp8,
377 &auto_altref,
378 &noise_sens,
379 &sharpness,
380 &static_thresh,
381 &token_parts,
382 &arnr_maxframes,
383 &arnr_strength,
384 &arnr_type,
385 &tune_ssim,
386 &cq_level,
387 &max_intra_rate_pct,
388 &gf_cbr_boost_pct,
389 &screen_content_mode,
390 NULL };
391 static const int vp8_arg_ctrl_map[] = { VP8E_SET_CPUUSED,
392 VP8E_SET_ENABLEAUTOALTREF,
393 VP8E_SET_NOISE_SENSITIVITY,
394 VP8E_SET_SHARPNESS,
395 VP8E_SET_STATIC_THRESHOLD,
396 VP8E_SET_TOKEN_PARTITIONS,
397 VP8E_SET_ARNR_MAXFRAMES,
398 VP8E_SET_ARNR_STRENGTH,
399 VP8E_SET_ARNR_TYPE,
400 VP8E_SET_TUNING,
401 VP8E_SET_CQ_LEVEL,
402 VP8E_SET_MAX_INTRA_BITRATE_PCT,
403 VP8E_SET_GF_CBR_BOOST_PCT,
404 VP8E_SET_SCREEN_CONTENT_MODE,
405 0 };
406 #endif
407
408 #if CONFIG_VP9_ENCODER
409 static const arg_def_t cpu_used_vp9 =
410 ARG_DEF(NULL, "cpu-used", 1, "CPU Used (-8..8)");
411 static const arg_def_t tile_cols =
412 ARG_DEF(NULL, "tile-columns", 1, "Number of tile columns to use, log2");
413 static const arg_def_t tile_rows =
414 ARG_DEF(NULL, "tile-rows", 1,
415 "Number of tile rows to use, log2 (set to 0 while threads > 1)");
416
417 static const arg_def_t enable_tpl_model =
418 ARG_DEF(NULL, "enable-tpl", 1, "Enable temporal dependency model");
419
420 static const arg_def_t lossless =
421 ARG_DEF(NULL, "lossless", 1, "Lossless mode (0: false (default), 1: true)");
422 static const arg_def_t frame_parallel_decoding = ARG_DEF(
423 NULL, "frame-parallel", 1, "Enable frame parallel decodability features");
424 static const arg_def_t aq_mode = ARG_DEF(
425 NULL, "aq-mode", 1,
426 "Adaptive quantization mode (0: off (default), 1: variance 2: complexity, "
427 "3: cyclic refresh, 4: equator360)");
428 static const arg_def_t alt_ref_aq = ARG_DEF(NULL, "alt-ref-aq", 1,
429 "Special adaptive quantization for "
430 "the alternate reference frames.");
431 static const arg_def_t frame_periodic_boost =
432 ARG_DEF(NULL, "frame-boost", 1,
433 "Enable frame periodic boost (0: off (default), 1: on)");
434 static const arg_def_t max_inter_rate_pct =
435 ARG_DEF(NULL, "max-inter-rate", 1, "Max P-frame bitrate (pct)");
436 static const arg_def_t min_gf_interval = ARG_DEF(
437 NULL, "min-gf-interval", 1,
438 "min gf/arf frame interval (default 0, indicating in-built behavior)");
439 static const arg_def_t max_gf_interval = ARG_DEF(
440 NULL, "max-gf-interval", 1,
441 "max gf/arf frame interval (default 0, indicating in-built behavior)");
442
443 static const struct arg_enum_list color_space_enum[] = {
444 { "unknown", VPX_CS_UNKNOWN },
445 { "bt601", VPX_CS_BT_601 },
446 { "bt709", VPX_CS_BT_709 },
447 { "smpte170", VPX_CS_SMPTE_170 },
448 { "smpte240", VPX_CS_SMPTE_240 },
449 { "bt2020", VPX_CS_BT_2020 },
450 { "reserved", VPX_CS_RESERVED },
451 { "sRGB", VPX_CS_SRGB },
452 { NULL, 0 }
453 };
454
455 static const arg_def_t input_color_space =
456 ARG_DEF_ENUM(NULL, "color-space", 1,
457 "The color space of input content:", color_space_enum);
458
459 #if CONFIG_VP9_HIGHBITDEPTH
460 static const struct arg_enum_list bitdepth_enum[] = {
461 { "8", VPX_BITS_8 }, { "10", VPX_BITS_10 }, { "12", VPX_BITS_12 }, { NULL, 0 }
462 };
463
464 static const arg_def_t bitdeptharg = ARG_DEF_ENUM(
465 "b", "bit-depth", 1,
466 "Bit depth for codec (8 for version <=1, 10 or 12 for version 2)",
467 bitdepth_enum);
468 static const arg_def_t inbitdeptharg =
469 ARG_DEF(NULL, "input-bit-depth", 1, "Bit depth of input");
470 #endif
471
472 static const struct arg_enum_list tune_content_enum[] = {
473 { "default", VP9E_CONTENT_DEFAULT },
474 { "screen", VP9E_CONTENT_SCREEN },
475 { "film", VP9E_CONTENT_FILM },
476 { NULL, 0 }
477 };
478
479 static const arg_def_t tune_content = ARG_DEF_ENUM(
480 NULL, "tune-content", 1, "Tune content type", tune_content_enum);
481
482 static const arg_def_t target_level = ARG_DEF(
483 NULL, "target-level", 1,
484 "Target level\n"
485 " 255: off (default)\n"
486 " 0: only keep level stats\n"
487 " 1: adaptively set alt-ref "
488 "distance and column tile limit based on picture size, and keep"
489 " level stats\n"
490 " 10: level 1.0 11: level 1.1 "
491 "... 62: level 6.2");
492
493 static const arg_def_t row_mt =
494 ARG_DEF(NULL, "row-mt", 1,
495 "Enable row based non-deterministic multi-threading in VP9");
496 #endif
497
498 #if CONFIG_VP9_ENCODER
499 static const arg_def_t *vp9_args[] = { &cpu_used_vp9,
500 &auto_altref,
501 &sharpness,
502 &static_thresh,
503 &tile_cols,
504 &tile_rows,
505 &enable_tpl_model,
506 &arnr_maxframes,
507 &arnr_strength,
508 &arnr_type,
509 &tune_ssim,
510 &cq_level,
511 &max_intra_rate_pct,
512 &max_inter_rate_pct,
513 &gf_cbr_boost_pct,
514 &lossless,
515 &frame_parallel_decoding,
516 &aq_mode,
517 &alt_ref_aq,
518 &frame_periodic_boost,
519 &noise_sens,
520 &tune_content,
521 &input_color_space,
522 &min_gf_interval,
523 &max_gf_interval,
524 &target_level,
525 &row_mt,
526 #if CONFIG_VP9_HIGHBITDEPTH
527 &bitdeptharg,
528 &inbitdeptharg,
529 #endif // CONFIG_VP9_HIGHBITDEPTH
530 NULL };
531 static const int vp9_arg_ctrl_map[] = { VP8E_SET_CPUUSED,
532 VP8E_SET_ENABLEAUTOALTREF,
533 VP8E_SET_SHARPNESS,
534 VP8E_SET_STATIC_THRESHOLD,
535 VP9E_SET_TILE_COLUMNS,
536 VP9E_SET_TILE_ROWS,
537 VP9E_SET_TPL,
538 VP8E_SET_ARNR_MAXFRAMES,
539 VP8E_SET_ARNR_STRENGTH,
540 VP8E_SET_ARNR_TYPE,
541 VP8E_SET_TUNING,
542 VP8E_SET_CQ_LEVEL,
543 VP8E_SET_MAX_INTRA_BITRATE_PCT,
544 VP9E_SET_MAX_INTER_BITRATE_PCT,
545 VP9E_SET_GF_CBR_BOOST_PCT,
546 VP9E_SET_LOSSLESS,
547 VP9E_SET_FRAME_PARALLEL_DECODING,
548 VP9E_SET_AQ_MODE,
549 VP9E_SET_ALT_REF_AQ,
550 VP9E_SET_FRAME_PERIODIC_BOOST,
551 VP9E_SET_NOISE_SENSITIVITY,
552 VP9E_SET_TUNE_CONTENT,
553 VP9E_SET_COLOR_SPACE,
554 VP9E_SET_MIN_GF_INTERVAL,
555 VP9E_SET_MAX_GF_INTERVAL,
556 VP9E_SET_TARGET_LEVEL,
557 VP9E_SET_ROW_MT,
558 0 };
559 #endif
560
561 static const arg_def_t *no_args[] = { NULL };
562
563 static void show_help(FILE *fout, int shorthelp) {
564 int i;
565 const int num_encoder = get_vpx_encoder_count();
566
567 fprintf(fout, "Usage: %s <options> -o dst_filename src_filename \n",
568 exec_name);
569
570 if (shorthelp) {
571 fprintf(fout, "Use --help to see the full list of options.\n");
572 return;
573 }
574
575 fprintf(fout, "\nOptions:\n");
576 arg_show_usage(fout, main_args);
577 fprintf(fout, "\nEncoder Global Options:\n");
578 arg_show_usage(fout, global_args);
579 fprintf(fout, "\nRate Control Options:\n");
580 arg_show_usage(fout, rc_args);
581 fprintf(fout, "\nTwopass Rate Control Options:\n");
582 arg_show_usage(fout, rc_twopass_args);
583 fprintf(fout, "\nKeyframe Placement Options:\n");
584 arg_show_usage(fout, kf_args);
585 #if CONFIG_VP8_ENCODER
586 fprintf(fout, "\nVP8 Specific Options:\n");
587 arg_show_usage(fout, vp8_args);
588 #endif
589 #if CONFIG_VP9_ENCODER
590 fprintf(fout, "\nVP9 Specific Options:\n");
591 arg_show_usage(fout, vp9_args);
592 #endif
593 fprintf(fout,
594 "\nStream timebase (--timebase):\n"
595 " The desired precision of timestamps in the output, expressed\n"
596 " in fractional seconds. Default is 1/1000.\n");
597 fprintf(fout, "\nIncluded encoders:\n\n");
598
599 for (i = 0; i < num_encoder; ++i) {
600 const VpxInterface *const encoder = get_vpx_encoder_by_index(i);
601 const char *defstr = (i == (num_encoder - 1)) ? "(default)" : "";
602 fprintf(fout, " %-6s - %s %s\n", encoder->name,
603 vpx_codec_iface_name(encoder->codec_interface()), defstr);
604 }
605 fprintf(fout, "\n ");
606 fprintf(fout, "Use --codec to switch to a non-default encoder.\n\n");
607 }
608
609 void usage_exit(void) {
610 show_help(stderr, 1);
611 exit(EXIT_FAILURE);
612 }
613
614 #define mmin(a, b) ((a) < (b) ? (a) : (b))
615
616 #if CONFIG_VP9_HIGHBITDEPTH
617 static void find_mismatch_high(const vpx_image_t *const img1,
618 const vpx_image_t *const img2, int yloc[4],
619 int uloc[4], int vloc[4]) {
620 uint16_t *plane1, *plane2;
621 uint32_t stride1, stride2;
622 const uint32_t bsize = 64;
623 const uint32_t bsizey = bsize >> img1->y_chroma_shift;
624 const uint32_t bsizex = bsize >> img1->x_chroma_shift;
625 const uint32_t c_w =
626 (img1->d_w + img1->x_chroma_shift) >> img1->x_chroma_shift;
627 const uint32_t c_h =
628 (img1->d_h + img1->y_chroma_shift) >> img1->y_chroma_shift;
629 int match = 1;
630 uint32_t i, j;
631 yloc[0] = yloc[1] = yloc[2] = yloc[3] = -1;
632 plane1 = (uint16_t *)img1->planes[VPX_PLANE_Y];
633 plane2 = (uint16_t *)img2->planes[VPX_PLANE_Y];
634 stride1 = img1->stride[VPX_PLANE_Y] / 2;
635 stride2 = img2->stride[VPX_PLANE_Y] / 2;
636 for (i = 0, match = 1; match && i < img1->d_h; i += bsize) {
637 for (j = 0; match && j < img1->d_w; j += bsize) {
638 int k, l;
639 const int si = mmin(i + bsize, img1->d_h) - i;
640 const int sj = mmin(j + bsize, img1->d_w) - j;
641 for (k = 0; match && k < si; ++k) {
642 for (l = 0; match && l < sj; ++l) {
643 if (*(plane1 + (i + k) * stride1 + j + l) !=
644 *(plane2 + (i + k) * stride2 + j + l)) {
645 yloc[0] = i + k;
646 yloc[1] = j + l;
647 yloc[2] = *(plane1 + (i + k) * stride1 + j + l);
648 yloc[3] = *(plane2 + (i + k) * stride2 + j + l);
649 match = 0;
650 break;
651 }
652 }
653 }
654 }
655 }
656
657 uloc[0] = uloc[1] = uloc[2] = uloc[3] = -1;
658 plane1 = (uint16_t *)img1->planes[VPX_PLANE_U];
659 plane2 = (uint16_t *)img2->planes[VPX_PLANE_U];
660 stride1 = img1->stride[VPX_PLANE_U] / 2;
661 stride2 = img2->stride[VPX_PLANE_U] / 2;
662 for (i = 0, match = 1; match && i < c_h; i += bsizey) {
663 for (j = 0; match && j < c_w; j += bsizex) {
664 int k, l;
665 const int si = mmin(i + bsizey, c_h - i);
666 const int sj = mmin(j + bsizex, c_w - j);
667 for (k = 0; match && k < si; ++k) {
668 for (l = 0; match && l < sj; ++l) {
669 if (*(plane1 + (i + k) * stride1 + j + l) !=
670 *(plane2 + (i + k) * stride2 + j + l)) {
671 uloc[0] = i + k;
672 uloc[1] = j + l;
673 uloc[2] = *(plane1 + (i + k) * stride1 + j + l);
674 uloc[3] = *(plane2 + (i + k) * stride2 + j + l);
675 match = 0;
676 break;
677 }
678 }
679 }
680 }
681 }
682
683 vloc[0] = vloc[1] = vloc[2] = vloc[3] = -1;
684 plane1 = (uint16_t *)img1->planes[VPX_PLANE_V];
685 plane2 = (uint16_t *)img2->planes[VPX_PLANE_V];
686 stride1 = img1->stride[VPX_PLANE_V] / 2;
687 stride2 = img2->stride[VPX_PLANE_V] / 2;
688 for (i = 0, match = 1; match && i < c_h; i += bsizey) {
689 for (j = 0; match && j < c_w; j += bsizex) {
690 int k, l;
691 const int si = mmin(i + bsizey, c_h - i);
692 const int sj = mmin(j + bsizex, c_w - j);
693 for (k = 0; match && k < si; ++k) {
694 for (l = 0; match && l < sj; ++l) {
695 if (*(plane1 + (i + k) * stride1 + j + l) !=
696 *(plane2 + (i + k) * stride2 + j + l)) {
697 vloc[0] = i + k;
698 vloc[1] = j + l;
699 vloc[2] = *(plane1 + (i + k) * stride1 + j + l);
700 vloc[3] = *(plane2 + (i + k) * stride2 + j + l);
701 match = 0;
702 break;
703 }
704 }
705 }
706 }
707 }
708 }
709 #endif
710
711 static void find_mismatch(const vpx_image_t *const img1,
712 const vpx_image_t *const img2, int yloc[4],
713 int uloc[4], int vloc[4]) {
714 const uint32_t bsize = 64;
715 const uint32_t bsizey = bsize >> img1->y_chroma_shift;
716 const uint32_t bsizex = bsize >> img1->x_chroma_shift;
717 const uint32_t c_w =
718 (img1->d_w + img1->x_chroma_shift) >> img1->x_chroma_shift;
719 const uint32_t c_h =
720 (img1->d_h + img1->y_chroma_shift) >> img1->y_chroma_shift;
721 int match = 1;
722 uint32_t i, j;
723 yloc[0] = yloc[1] = yloc[2] = yloc[3] = -1;
724 for (i = 0, match = 1; match && i < img1->d_h; i += bsize) {
725 for (j = 0; match && j < img1->d_w; j += bsize) {
726 int k, l;
727 const int si = mmin(i + bsize, img1->d_h) - i;
728 const int sj = mmin(j + bsize, img1->d_w) - j;
729 for (k = 0; match && k < si; ++k) {
730 for (l = 0; match && l < sj; ++l) {
731 if (*(img1->planes[VPX_PLANE_Y] +
732 (i + k) * img1->stride[VPX_PLANE_Y] + j + l) !=
733 *(img2->planes[VPX_PLANE_Y] +
734 (i + k) * img2->stride[VPX_PLANE_Y] + j + l)) {
735 yloc[0] = i + k;
736 yloc[1] = j + l;
737 yloc[2] = *(img1->planes[VPX_PLANE_Y] +
738 (i + k) * img1->stride[VPX_PLANE_Y] + j + l);
739 yloc[3] = *(img2->planes[VPX_PLANE_Y] +
740 (i + k) * img2->stride[VPX_PLANE_Y] + j + l);
741 match = 0;
742 break;
743 }
744 }
745 }
746 }
747 }
748
749 uloc[0] = uloc[1] = uloc[2] = uloc[3] = -1;
750 for (i = 0, match = 1; match && i < c_h; i += bsizey) {
751 for (j = 0; match && j < c_w; j += bsizex) {
752 int k, l;
753 const int si = mmin(i + bsizey, c_h - i);
754 const int sj = mmin(j + bsizex, c_w - j);
755 for (k = 0; match && k < si; ++k) {
756 for (l = 0; match && l < sj; ++l) {
757 if (*(img1->planes[VPX_PLANE_U] +
758 (i + k) * img1->stride[VPX_PLANE_U] + j + l) !=
759 *(img2->planes[VPX_PLANE_U] +
760 (i + k) * img2->stride[VPX_PLANE_U] + j + l)) {
761 uloc[0] = i + k;
762 uloc[1] = j + l;
763 uloc[2] = *(img1->planes[VPX_PLANE_U] +
764 (i + k) * img1->stride[VPX_PLANE_U] + j + l);
765 uloc[3] = *(img2->planes[VPX_PLANE_U] +
766 (i + k) * img2->stride[VPX_PLANE_U] + j + l);
767 match = 0;
768 break;
769 }
770 }
771 }
772 }
773 }
774 vloc[0] = vloc[1] = vloc[2] = vloc[3] = -1;
775 for (i = 0, match = 1; match && i < c_h; i += bsizey) {
776 for (j = 0; match && j < c_w; j += bsizex) {
777 int k, l;
778 const int si = mmin(i + bsizey, c_h - i);
779 const int sj = mmin(j + bsizex, c_w - j);
780 for (k = 0; match && k < si; ++k) {
781 for (l = 0; match && l < sj; ++l) {
782 if (*(img1->planes[VPX_PLANE_V] +
783 (i + k) * img1->stride[VPX_PLANE_V] + j + l) !=
784 *(img2->planes[VPX_PLANE_V] +
785 (i + k) * img2->stride[VPX_PLANE_V] + j + l)) {
786 vloc[0] = i + k;
787 vloc[1] = j + l;
788 vloc[2] = *(img1->planes[VPX_PLANE_V] +
789 (i + k) * img1->stride[VPX_PLANE_V] + j + l);
790 vloc[3] = *(img2->planes[VPX_PLANE_V] +
791 (i + k) * img2->stride[VPX_PLANE_V] + j + l);
792 match = 0;
793 break;
794 }
795 }
796 }
797 }
798 }
799 }
800
801 static int compare_img(const vpx_image_t *const img1,
802 const vpx_image_t *const img2) {
803 uint32_t l_w = img1->d_w;
804 uint32_t c_w = (img1->d_w + img1->x_chroma_shift) >> img1->x_chroma_shift;
805 const uint32_t c_h =
806 (img1->d_h + img1->y_chroma_shift) >> img1->y_chroma_shift;
807 uint32_t i;
808 int match = 1;
809
810 match &= (img1->fmt == img2->fmt);
811 match &= (img1->d_w == img2->d_w);
812 match &= (img1->d_h == img2->d_h);
813 #if CONFIG_VP9_HIGHBITDEPTH
814 if (img1->fmt & VPX_IMG_FMT_HIGHBITDEPTH) {
815 l_w *= 2;
816 c_w *= 2;
817 }
818 #endif
819
820 for (i = 0; i < img1->d_h; ++i)
821 match &= (memcmp(img1->planes[VPX_PLANE_Y] + i * img1->stride[VPX_PLANE_Y],
822 img2->planes[VPX_PLANE_Y] + i * img2->stride[VPX_PLANE_Y],
823 l_w) == 0);
824
825 for (i = 0; i < c_h; ++i)
826 match &= (memcmp(img1->planes[VPX_PLANE_U] + i * img1->stride[VPX_PLANE_U],
827 img2->planes[VPX_PLANE_U] + i * img2->stride[VPX_PLANE_U],
828 c_w) == 0);
829
830 for (i = 0; i < c_h; ++i)
831 match &= (memcmp(img1->planes[VPX_PLANE_V] + i * img1->stride[VPX_PLANE_V],
832 img2->planes[VPX_PLANE_V] + i * img2->stride[VPX_PLANE_V],
833 c_w) == 0);
834
835 return match;
836 }
837
838 #define NELEMENTS(x) (sizeof(x) / sizeof(x[0]))
839 #if CONFIG_VP9_ENCODER
840 #define ARG_CTRL_CNT_MAX NELEMENTS(vp9_arg_ctrl_map)
841 #else
842 #define ARG_CTRL_CNT_MAX NELEMENTS(vp8_arg_ctrl_map)
843 #endif
844
845 #if !CONFIG_WEBM_IO
846 typedef int stereo_format_t;
847 struct WebmOutputContext {
848 int debug;
849 };
850 #endif
851
852 /* Per-stream configuration */
853 struct stream_config {
854 struct vpx_codec_enc_cfg cfg;
855 const char *out_fn;
856 const char *stats_fn;
857 #if CONFIG_FP_MB_STATS
858 const char *fpmb_stats_fn;
859 #endif
860 stereo_format_t stereo_fmt;
861 int arg_ctrls[ARG_CTRL_CNT_MAX][2];
862 int arg_ctrl_cnt;
863 int write_webm;
864 #if CONFIG_VP9_HIGHBITDEPTH
865 // whether to use 16bit internal buffers
866 int use_16bit_internal;
867 #endif
868 };
869
870 struct stream_state {
871 int index;
872 struct stream_state *next;
873 struct stream_config config;
874 FILE *file;
875 struct rate_hist *rate_hist;
876 struct WebmOutputContext webm_ctx;
877 uint64_t psnr_sse_total;
878 uint64_t psnr_samples_total;
879 double psnr_totals[4];
880 int psnr_count;
881 int counts[64];
882 vpx_codec_ctx_t encoder;
883 unsigned int frames_out;
884 uint64_t cx_time;
885 size_t nbytes;
886 stats_io_t stats;
887 #if CONFIG_FP_MB_STATS
888 stats_io_t fpmb_stats;
889 #endif
890 struct vpx_image *img;
891 vpx_codec_ctx_t decoder;
892 int mismatch_seen;
893 };
894
895 static void validate_positive_rational(const char *msg,
896 struct vpx_rational *rat) {
897 if (rat->den < 0) {
898 rat->num *= -1;
899 rat->den *= -1;
900 }
901
902 if (rat->num < 0) die("Error: %s must be positive\n", msg);
903
904 if (!rat->den) die("Error: %s has zero denominator\n", msg);
905 }
906
907 static void parse_global_config(struct VpxEncoderConfig *global, char **argv) {
908 char **argi, **argj;
909 struct arg arg;
910 const int num_encoder = get_vpx_encoder_count();
911
912 if (num_encoder < 1) die("Error: no valid encoder available\n");
913
914 /* Initialize default parameters */
915 memset(global, 0, sizeof(*global));
916 global->codec = get_vpx_encoder_by_index(num_encoder - 1);
917 global->passes = 0;
918 global->color_type = I420;
919 /* Assign default deadline to good quality */
920 global->deadline = VPX_DL_GOOD_QUALITY;
921
922 for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step) {
923 arg.argv_step = 1;
924
925 if (arg_match(&arg, &help, argi)) {
926 show_help(stdout, 0);
927 exit(EXIT_SUCCESS);
928 } else if (arg_match(&arg, &codecarg, argi)) {
929 global->codec = get_vpx_encoder_by_name(arg.val);
930 if (!global->codec)
931 die("Error: Unrecognized argument (%s) to --codec\n", arg.val);
932 } else if (arg_match(&arg, &passes, argi)) {
933 global->passes = arg_parse_uint(&arg);
934
935 if (global->passes < 1 || global->passes > 2)
936 die("Error: Invalid number of passes (%d)\n", global->passes);
937 } else if (arg_match(&arg, &pass_arg, argi)) {
938 global->pass = arg_parse_uint(&arg);
939
940 if (global->pass < 1 || global->pass > 2)
941 die("Error: Invalid pass selected (%d)\n", global->pass);
942 } else if (arg_match(&arg, &usage, argi))
943 global->usage = arg_parse_uint(&arg);
944 else if (arg_match(&arg, &deadline, argi))
945 global->deadline = arg_parse_uint(&arg);
946 else if (arg_match(&arg, &best_dl, argi))
947 global->deadline = VPX_DL_BEST_QUALITY;
948 else if (arg_match(&arg, &good_dl, argi))
949 global->deadline = VPX_DL_GOOD_QUALITY;
950 else if (arg_match(&arg, &rt_dl, argi))
951 global->deadline = VPX_DL_REALTIME;
952 else if (arg_match(&arg, &use_yv12, argi))
953 global->color_type = YV12;
954 else if (arg_match(&arg, &use_i420, argi))
955 global->color_type = I420;
956 else if (arg_match(&arg, &use_i422, argi))
957 global->color_type = I422;
958 else if (arg_match(&arg, &use_i444, argi))
959 global->color_type = I444;
960 else if (arg_match(&arg, &use_i440, argi))
961 global->color_type = I440;
962 else if (arg_match(&arg, &quietarg, argi))
963 global->quiet = 1;
964 else if (arg_match(&arg, &verbosearg, argi))
965 global->verbose = 1;
966 else if (arg_match(&arg, &limit, argi))
967 global->limit = arg_parse_uint(&arg);
968 else if (arg_match(&arg, &skip, argi))
969 global->skip_frames = arg_parse_uint(&arg);
970 else if (arg_match(&arg, &psnrarg, argi))
971 global->show_psnr = 1;
972 else if (arg_match(&arg, &recontest, argi))
973 global->test_decode = arg_parse_enum_or_int(&arg);
974 else if (arg_match(&arg, &framerate, argi)) {
975 global->framerate = arg_parse_rational(&arg);
976 validate_positive_rational(arg.name, &global->framerate);
977 global->have_framerate = 1;
978 } else if (arg_match(&arg, &out_part, argi))
979 global->out_part = 1;
980 else if (arg_match(&arg, &debugmode, argi))
981 global->debug = 1;
982 else if (arg_match(&arg, &q_hist_n, argi))
983 global->show_q_hist_buckets = arg_parse_uint(&arg);
984 else if (arg_match(&arg, &rate_hist_n, argi))
985 global->show_rate_hist_buckets = arg_parse_uint(&arg);
986 else if (arg_match(&arg, &disable_warnings, argi))
987 global->disable_warnings = 1;
988 else if (arg_match(&arg, &disable_warning_prompt, argi))
989 global->disable_warning_prompt = 1;
990 else
991 argj++;
992 }
993
994 if (global->pass) {
995 /* DWIM: Assume the user meant passes=2 if pass=2 is specified */
996 if (global->pass > global->passes) {
997 warn("Assuming --pass=%d implies --passes=%d\n", global->pass,
998 global->pass);
999 global->passes = global->pass;
1000 }
1001 }
1002 /* Validate global config */
1003 if (global->passes == 0) {
1004 #if CONFIG_VP9_ENCODER
1005 // Make default VP9 passes = 2 until there is a better quality 1-pass
1006 // encoder
1007 if (global->codec != NULL && global->codec->name != NULL)
1008 global->passes = (strcmp(global->codec->name, "vp9") == 0 &&
1009 global->deadline != VPX_DL_REALTIME)
1010 ? 2
1011 : 1;
1012 #else
1013 global->passes = 1;
1014 #endif
1015 }
1016
1017 if (global->deadline == VPX_DL_REALTIME && global->passes > 1) {
1018 warn("Enforcing one-pass encoding in realtime mode\n");
1019 global->passes = 1;
1020 }
1021 }
1022
1023 static void open_input_file(struct VpxInputContext *input) {
1024 /* Parse certain options from the input file, if possible */
1025 input->file = strcmp(input->filename, "-") ? fopen(input->filename, "rb")
1026 : set_binary_mode(stdin);
1027
1028 if (!input->file) fatal("Failed to open input file");
1029
1030 if (!fseeko(input->file, 0, SEEK_END)) {
1031 /* Input file is seekable. Figure out how long it is, so we can get
1032 * progress info.
1033 */
1034 input->length = ftello(input->file);
1035 rewind(input->file);
1036 }
1037
1038 /* Default to 1:1 pixel aspect ratio. */
1039 input->pixel_aspect_ratio.numerator = 1;
1040 input->pixel_aspect_ratio.denominator = 1;
1041
1042 /* For RAW input sources, these bytes will applied on the first frame
1043 * in read_frame().
1044 */
1045 input->detect.buf_read = fread(input->detect.buf, 1, 4, input->file);
1046 input->detect.position = 0;
1047
1048 if (input->detect.buf_read == 4 && file_is_y4m(input->detect.buf)) {
1049 if (y4m_input_open(&input->y4m, input->file, input->detect.buf, 4,
1050 input->only_i420) >= 0) {
1051 input->file_type = FILE_TYPE_Y4M;
1052 input->width = input->y4m.pic_w;
1053 input->height = input->y4m.pic_h;
1054 input->pixel_aspect_ratio.numerator = input->y4m.par_n;
1055 input->pixel_aspect_ratio.denominator = input->y4m.par_d;
1056 input->framerate.numerator = input->y4m.fps_n;
1057 input->framerate.denominator = input->y4m.fps_d;
1058 input->fmt = input->y4m.vpx_fmt;
1059 input->bit_depth = input->y4m.bit_depth;
1060 } else
1061 fatal("Unsupported Y4M stream.");
1062 } else if (input->detect.buf_read == 4 && fourcc_is_ivf(input->detect.buf)) {
1063 fatal("IVF is not supported as input.");
1064 } else {
1065 input->file_type = FILE_TYPE_RAW;
1066 }
1067 }
1068
1069 static void close_input_file(struct VpxInputContext *input) {
1070 fclose(input->file);
1071 if (input->file_type == FILE_TYPE_Y4M) y4m_input_close(&input->y4m);
1072 }
1073
1074 static struct stream_state *new_stream(struct VpxEncoderConfig *global,
1075 struct stream_state *prev) {
1076 struct stream_state *stream;
1077
1078 stream = calloc(1, sizeof(*stream));
1079 if (stream == NULL) {
1080 fatal("Failed to allocate new stream.");
1081 }
1082
1083 if (prev) {
1084 memcpy(stream, prev, sizeof(*stream));
1085 stream->index++;
1086 prev->next = stream;
1087 } else {
1088 vpx_codec_err_t res;
1089
1090 /* Populate encoder configuration */
1091 res = vpx_codec_enc_config_default(global->codec->codec_interface(),
1092 &stream->config.cfg, global->usage);
1093 if (res) fatal("Failed to get config: %s\n", vpx_codec_err_to_string(res));
1094
1095 /* Change the default timebase to a high enough value so that the
1096 * encoder will always create strictly increasing timestamps.
1097 */
1098 stream->config.cfg.g_timebase.den = 1000;
1099
1100 /* Never use the library's default resolution, require it be parsed
1101 * from the file or set on the command line.
1102 */
1103 stream->config.cfg.g_w = 0;
1104 stream->config.cfg.g_h = 0;
1105
1106 /* Initialize remaining stream parameters */
1107 stream->config.write_webm = 1;
1108 #if CONFIG_WEBM_IO
1109 stream->config.stereo_fmt = STEREO_FORMAT_MONO;
1110 stream->webm_ctx.last_pts_ns = -1;
1111 stream->webm_ctx.writer = NULL;
1112 stream->webm_ctx.segment = NULL;
1113 #endif
1114
1115 /* Allows removal of the application version from the EBML tags */
1116 stream->webm_ctx.debug = global->debug;
1117
1118 /* Default lag_in_frames is 0 in realtime mode CBR mode*/
1119 if (global->deadline == VPX_DL_REALTIME &&
1120 stream->config.cfg.rc_end_usage == 1)
1121 stream->config.cfg.g_lag_in_frames = 0;
1122 }
1123
1124 /* Output files must be specified for each stream */
1125 stream->config.out_fn = NULL;
1126
1127 stream->next = NULL;
1128 return stream;
1129 }
1130
1131 static int parse_stream_params(struct VpxEncoderConfig *global,
1132 struct stream_state *stream, char **argv) {
1133 char **argi, **argj;
1134 struct arg arg;
1135 static const arg_def_t **ctrl_args = no_args;
1136 static const int *ctrl_args_map = NULL;
1137 struct stream_config *config = &stream->config;
1138 int eos_mark_found = 0;
1139 #if CONFIG_VP9_HIGHBITDEPTH
1140 int test_16bit_internal = 0;
1141 #endif
1142
1143 // Handle codec specific options
1144 if (0) {
1145 #if CONFIG_VP8_ENCODER
1146 } else if (strcmp(global->codec->name, "vp8") == 0) {
1147 ctrl_args = vp8_args;
1148 ctrl_args_map = vp8_arg_ctrl_map;
1149 #endif
1150 #if CONFIG_VP9_ENCODER
1151 } else if (strcmp(global->codec->name, "vp9") == 0) {
1152 ctrl_args = vp9_args;
1153 ctrl_args_map = vp9_arg_ctrl_map;
1154 #endif
1155 }
1156
1157 for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step) {
1158 arg.argv_step = 1;
1159
1160 /* Once we've found an end-of-stream marker (--) we want to continue
1161 * shifting arguments but not consuming them.
1162 */
1163 if (eos_mark_found) {
1164 argj++;
1165 continue;
1166 } else if (!strcmp(*argj, "--")) {
1167 eos_mark_found = 1;
1168 continue;
1169 }
1170
1171 if (arg_match(&arg, &outputfile, argi)) {
1172 config->out_fn = arg.val;
1173 } else if (arg_match(&arg, &fpf_name, argi)) {
1174 config->stats_fn = arg.val;
1175 #if CONFIG_FP_MB_STATS
1176 } else if (arg_match(&arg, &fpmbf_name, argi)) {
1177 config->fpmb_stats_fn = arg.val;
1178 #endif
1179 } else if (arg_match(&arg, &use_webm, argi)) {
1180 #if CONFIG_WEBM_IO
1181 config->write_webm = 1;
1182 #else
1183 die("Error: --webm specified but webm is disabled.");
1184 #endif
1185 } else if (arg_match(&arg, &use_ivf, argi)) {
1186 config->write_webm = 0;
1187 } else if (arg_match(&arg, &threads, argi)) {
1188 config->cfg.g_threads = arg_parse_uint(&arg);
1189 } else if (arg_match(&arg, &profile, argi)) {
1190 config->cfg.g_profile = arg_parse_uint(&arg);
1191 } else if (arg_match(&arg, &width, argi)) {
1192 config->cfg.g_w = arg_parse_uint(&arg);
1193 } else if (arg_match(&arg, &height, argi)) {
1194 config->cfg.g_h = arg_parse_uint(&arg);
1195 #if CONFIG_VP9_HIGHBITDEPTH
1196 } else if (arg_match(&arg, &bitdeptharg, argi)) {
1197 config->cfg.g_bit_depth = arg_parse_enum_or_int(&arg);
1198 } else if (arg_match(&arg, &inbitdeptharg, argi)) {
1199 config->cfg.g_input_bit_depth = arg_parse_uint(&arg);
1200 #endif
1201 #if CONFIG_WEBM_IO
1202 } else if (arg_match(&arg, &stereo_mode, argi)) {
1203 config->stereo_fmt = arg_parse_enum_or_int(&arg);
1204 #endif
1205 } else if (arg_match(&arg, &timebase, argi)) {
1206 config->cfg.g_timebase = arg_parse_rational(&arg);
1207 validate_positive_rational(arg.name, &config->cfg.g_timebase);
1208 } else if (arg_match(&arg, &error_resilient, argi)) {
1209 config->cfg.g_error_resilient = arg_parse_uint(&arg);
1210 } else if (arg_match(&arg, &end_usage, argi)) {
1211 config->cfg.rc_end_usage = arg_parse_enum_or_int(&arg);
1212 } else if (arg_match(&arg, &lag_in_frames, argi)) {
1213 config->cfg.g_lag_in_frames = arg_parse_uint(&arg);
1214 if (global->deadline == VPX_DL_REALTIME &&
1215 config->cfg.rc_end_usage == VPX_CBR &&
1216 config->cfg.g_lag_in_frames != 0) {
1217 warn("non-zero %s option ignored in realtime CBR mode.\n", arg.name);
1218 config->cfg.g_lag_in_frames = 0;
1219 }
1220 } else if (arg_match(&arg, &dropframe_thresh, argi)) {
1221 config->cfg.rc_dropframe_thresh = arg_parse_uint(&arg);
1222 } else if (arg_match(&arg, &resize_allowed, argi)) {
1223 config->cfg.rc_resize_allowed = arg_parse_uint(&arg);
1224 } else if (arg_match(&arg, &resize_width, argi)) {
1225 config->cfg.rc_scaled_width = arg_parse_uint(&arg);
1226 } else if (arg_match(&arg, &resize_height, argi)) {
1227 config->cfg.rc_scaled_height = arg_parse_uint(&arg);
1228 } else if (arg_match(&arg, &resize_up_thresh, argi)) {
1229 config->cfg.rc_resize_up_thresh = arg_parse_uint(&arg);
1230 } else if (arg_match(&arg, &resize_down_thresh, argi)) {
1231 config->cfg.rc_resize_down_thresh = arg_parse_uint(&arg);
1232 } else if (arg_match(&arg, &end_usage, argi)) {
1233 config->cfg.rc_end_usage = arg_parse_enum_or_int(&arg);
1234 } else if (arg_match(&arg, &target_bitrate, argi)) {
1235 config->cfg.rc_target_bitrate = arg_parse_uint(&arg);
1236 } else if (arg_match(&arg, &min_quantizer, argi)) {
1237 config->cfg.rc_min_quantizer = arg_parse_uint(&arg);
1238 } else if (arg_match(&arg, &max_quantizer, argi)) {
1239 config->cfg.rc_max_quantizer = arg_parse_uint(&arg);
1240 } else if (arg_match(&arg, &undershoot_pct, argi)) {
1241 config->cfg.rc_undershoot_pct = arg_parse_uint(&arg);
1242 } else if (arg_match(&arg, &overshoot_pct, argi)) {
1243 config->cfg.rc_overshoot_pct = arg_parse_uint(&arg);
1244 } else if (arg_match(&arg, &buf_sz, argi)) {
1245 config->cfg.rc_buf_sz = arg_parse_uint(&arg);
1246 } else if (arg_match(&arg, &buf_initial_sz, argi)) {
1247 config->cfg.rc_buf_initial_sz = arg_parse_uint(&arg);
1248 } else if (arg_match(&arg, &buf_optimal_sz, argi)) {
1249 config->cfg.rc_buf_optimal_sz = arg_parse_uint(&arg);
1250 } else if (arg_match(&arg, &bias_pct, argi)) {
1251 config->cfg.rc_2pass_vbr_bias_pct = arg_parse_uint(&arg);
1252 if (global->passes < 2)
1253 warn("option %s ignored in one-pass mode.\n", arg.name);
1254 } else if (arg_match(&arg, &minsection_pct, argi)) {
1255 config->cfg.rc_2pass_vbr_minsection_pct = arg_parse_uint(&arg);
1256
1257 if (global->passes < 2)
1258 warn("option %s ignored in one-pass mode.\n", arg.name);
1259 } else if (arg_match(&arg, &maxsection_pct, argi)) {
1260 config->cfg.rc_2pass_vbr_maxsection_pct = arg_parse_uint(&arg);
1261
1262 if (global->passes < 2)
1263 warn("option %s ignored in one-pass mode.\n", arg.name);
1264 } else if (arg_match(&arg, &corpus_complexity, argi)) {
1265 config->cfg.rc_2pass_vbr_corpus_complexity = arg_parse_uint(&arg);
1266
1267 if (global->passes < 2)
1268 warn("option %s ignored in one-pass mode.\n", arg.name);
1269 } else if (arg_match(&arg, &kf_min_dist, argi)) {
1270 config->cfg.kf_min_dist = arg_parse_uint(&arg);
1271 } else if (arg_match(&arg, &kf_max_dist, argi)) {
1272 config->cfg.kf_max_dist = arg_parse_uint(&arg);
1273 } else if (arg_match(&arg, &kf_disabled, argi)) {
1274 config->cfg.kf_mode = VPX_KF_DISABLED;
1275 #if CONFIG_VP9_HIGHBITDEPTH
1276 } else if (arg_match(&arg, &test16bitinternalarg, argi)) {
1277 if (strcmp(global->codec->name, "vp9") == 0) {
1278 test_16bit_internal = 1;
1279 }
1280 #endif
1281 } else {
1282 int i, match = 0;
1283 for (i = 0; ctrl_args[i]; i++) {
1284 if (arg_match(&arg, ctrl_args[i], argi)) {
1285 int j;
1286 match = 1;
1287
1288 /* Point either to the next free element or the first
1289 * instance of this control.
1290 */
1291 for (j = 0; j < config->arg_ctrl_cnt; j++)
1292 if (ctrl_args_map != NULL &&
1293 config->arg_ctrls[j][0] == ctrl_args_map[i])
1294 break;
1295
1296 /* Update/insert */
1297 assert(j < (int)ARG_CTRL_CNT_MAX);
1298 if (ctrl_args_map != NULL && j < (int)ARG_CTRL_CNT_MAX) {
1299 config->arg_ctrls[j][0] = ctrl_args_map[i];
1300 config->arg_ctrls[j][1] = arg_parse_enum_or_int(&arg);
1301 if (j == config->arg_ctrl_cnt) config->arg_ctrl_cnt++;
1302 }
1303 }
1304 }
1305 if (!match) argj++;
1306 }
1307 }
1308 #if CONFIG_VP9_HIGHBITDEPTH
1309 if (strcmp(global->codec->name, "vp9") == 0) {
1310 config->use_16bit_internal =
1311 test_16bit_internal | (config->cfg.g_profile > 1);
1312 }
1313 #endif
1314 return eos_mark_found;
1315 }
1316
1317 #define FOREACH_STREAM(func) \
1318 do { \
1319 struct stream_state *stream; \
1320 for (stream = streams; stream; stream = stream->next) { \
1321 func; \
1322 } \
1323 } while (0)
1324
1325 static void validate_stream_config(const struct stream_state *stream,
1326 const struct VpxEncoderConfig *global) {
1327 const struct stream_state *streami;
1328 (void)global;
1329
1330 if (!stream->config.cfg.g_w || !stream->config.cfg.g_h)
1331 fatal(
1332 "Stream %d: Specify stream dimensions with --width (-w) "
1333 " and --height (-h)",
1334 stream->index);
1335
1336 // Check that the codec bit depth is greater than the input bit depth.
1337 if (stream->config.cfg.g_input_bit_depth >
1338 (unsigned int)stream->config.cfg.g_bit_depth) {
1339 fatal("Stream %d: codec bit depth (%d) less than input bit depth (%d)",
1340 stream->index, (int)stream->config.cfg.g_bit_depth,
1341 stream->config.cfg.g_input_bit_depth);
1342 }
1343
1344 for (streami = stream; streami; streami = streami->next) {
1345 /* All streams require output files */
1346 if (!streami->config.out_fn)
1347 fatal("Stream %d: Output file is required (specify with -o)",
1348 streami->index);
1349
1350 /* Check for two streams outputting to the same file */
1351 if (streami != stream) {
1352 const char *a = stream->config.out_fn;
1353 const char *b = streami->config.out_fn;
1354 if (!strcmp(a, b) && strcmp(a, "/dev/null") && strcmp(a, ":nul"))
1355 fatal("Stream %d: duplicate output file (from stream %d)",
1356 streami->index, stream->index);
1357 }
1358
1359 /* Check for two streams sharing a stats file. */
1360 if (streami != stream) {
1361 const char *a = stream->config.stats_fn;
1362 const char *b = streami->config.stats_fn;
1363 if (a && b && !strcmp(a, b))
1364 fatal("Stream %d: duplicate stats file (from stream %d)",
1365 streami->index, stream->index);
1366 }
1367
1368 #if CONFIG_FP_MB_STATS
1369 /* Check for two streams sharing a mb stats file. */
1370 if (streami != stream) {
1371 const char *a = stream->config.fpmb_stats_fn;
1372 const char *b = streami->config.fpmb_stats_fn;
1373 if (a && b && !strcmp(a, b))
1374 fatal("Stream %d: duplicate mb stats file (from stream %d)",
1375 streami->index, stream->index);
1376 }
1377 #endif
1378 }
1379 }
1380
1381 static void set_stream_dimensions(struct stream_state *stream, unsigned int w,
1382 unsigned int h) {
1383 if (!stream->config.cfg.g_w) {
1384 if (!stream->config.cfg.g_h)
1385 stream->config.cfg.g_w = w;
1386 else
1387 stream->config.cfg.g_w = w * stream->config.cfg.g_h / h;
1388 }
1389 if (!stream->config.cfg.g_h) {
1390 stream->config.cfg.g_h = h * stream->config.cfg.g_w / w;
1391 }
1392 }
1393
1394 static const char *file_type_to_string(enum VideoFileType t) {
1395 switch (t) {
1396 case FILE_TYPE_RAW: return "RAW";
1397 case FILE_TYPE_Y4M: return "Y4M";
1398 default: return "Other";
1399 }
1400 }
1401
1402 static const char *image_format_to_string(vpx_img_fmt_t f) {
1403 switch (f) {
1404 case VPX_IMG_FMT_I420: return "I420";
1405 case VPX_IMG_FMT_I422: return "I422";
1406 case VPX_IMG_FMT_I444: return "I444";
1407 case VPX_IMG_FMT_I440: return "I440";
1408 case VPX_IMG_FMT_YV12: return "YV12";
1409 case VPX_IMG_FMT_I42016: return "I42016";
1410 case VPX_IMG_FMT_I42216: return "I42216";
1411 case VPX_IMG_FMT_I44416: return "I44416";
1412 case VPX_IMG_FMT_I44016: return "I44016";
1413 default: return "Other";
1414 }
1415 }
1416
1417 static void show_stream_config(struct stream_state *stream,
1418 struct VpxEncoderConfig *global,
1419 struct VpxInputContext *input) {
1420 #define SHOW(field) \
1421 fprintf(stderr, " %-28s = %d\n", #field, stream->config.cfg.field)
1422
1423 if (stream->index == 0) {
1424 fprintf(stderr, "Codec: %s\n",
1425 vpx_codec_iface_name(global->codec->codec_interface()));
1426 fprintf(stderr, "Source file: %s File Type: %s Format: %s\n",
1427 input->filename, file_type_to_string(input->file_type),
1428 image_format_to_string(input->fmt));
1429 }
1430 if (stream->next || stream->index)
1431 fprintf(stderr, "\nStream Index: %d\n", stream->index);
1432 fprintf(stderr, "Destination file: %s\n", stream->config.out_fn);
1433 fprintf(stderr, "Encoder parameters:\n");
1434
1435 SHOW(g_usage);
1436 SHOW(g_threads);
1437 SHOW(g_profile);
1438 SHOW(g_w);
1439 SHOW(g_h);
1440 SHOW(g_bit_depth);
1441 SHOW(g_input_bit_depth);
1442 SHOW(g_timebase.num);
1443 SHOW(g_timebase.den);
1444 SHOW(g_error_resilient);
1445 SHOW(g_pass);
1446 SHOW(g_lag_in_frames);
1447 SHOW(rc_dropframe_thresh);
1448 SHOW(rc_resize_allowed);
1449 SHOW(rc_scaled_width);
1450 SHOW(rc_scaled_height);
1451 SHOW(rc_resize_up_thresh);
1452 SHOW(rc_resize_down_thresh);
1453 SHOW(rc_end_usage);
1454 SHOW(rc_target_bitrate);
1455 SHOW(rc_min_quantizer);
1456 SHOW(rc_max_quantizer);
1457 SHOW(rc_undershoot_pct);
1458 SHOW(rc_overshoot_pct);
1459 SHOW(rc_buf_sz);
1460 SHOW(rc_buf_initial_sz);
1461 SHOW(rc_buf_optimal_sz);
1462 SHOW(rc_2pass_vbr_bias_pct);
1463 SHOW(rc_2pass_vbr_minsection_pct);
1464 SHOW(rc_2pass_vbr_maxsection_pct);
1465 SHOW(rc_2pass_vbr_corpus_complexity);
1466 SHOW(kf_mode);
1467 SHOW(kf_min_dist);
1468 SHOW(kf_max_dist);
1469 }
1470
1471 static void open_output_file(struct stream_state *stream,
1472 struct VpxEncoderConfig *global,
1473 const struct VpxRational *pixel_aspect_ratio) {
1474 const char *fn = stream->config.out_fn;
1475 const struct vpx_codec_enc_cfg *const cfg = &stream->config.cfg;
1476
1477 if (cfg->g_pass == VPX_RC_FIRST_PASS) return;
1478
1479 stream->file = strcmp(fn, "-") ? fopen(fn, "wb") : set_binary_mode(stdout);
1480
1481 if (!stream->file) fatal("Failed to open output file");
1482
1483 if (stream->config.write_webm && fseek(stream->file, 0, SEEK_CUR))
1484 fatal("WebM output to pipes not supported.");
1485
1486 #if CONFIG_WEBM_IO
1487 if (stream->config.write_webm) {
1488 stream->webm_ctx.stream = stream->file;
1489 write_webm_file_header(&stream->webm_ctx, cfg, stream->config.stereo_fmt,
1490 global->codec->fourcc, pixel_aspect_ratio);
1491 }
1492 #else
1493 (void)pixel_aspect_ratio;
1494 #endif
1495
1496 if (!stream->config.write_webm) {
1497 ivf_write_file_header(stream->file, cfg, global->codec->fourcc, 0);
1498 }
1499 }
1500
1501 static void close_output_file(struct stream_state *stream,
1502 unsigned int fourcc) {
1503 const struct vpx_codec_enc_cfg *const cfg = &stream->config.cfg;
1504
1505 if (cfg->g_pass == VPX_RC_FIRST_PASS) return;
1506
1507 #if CONFIG_WEBM_IO
1508 if (stream->config.write_webm) {
1509 write_webm_file_footer(&stream->webm_ctx);
1510 }
1511 #endif
1512
1513 if (!stream->config.write_webm) {
1514 if (!fseek(stream->file, 0, SEEK_SET))
1515 ivf_write_file_header(stream->file, &stream->config.cfg, fourcc,
1516 stream->frames_out);
1517 }
1518
1519 fclose(stream->file);
1520 }
1521
1522 static void setup_pass(struct stream_state *stream,
1523 struct VpxEncoderConfig *global, int pass) {
1524 if (stream->config.stats_fn) {
1525 if (!stats_open_file(&stream->stats, stream->config.stats_fn, pass))
1526 fatal("Failed to open statistics store");
1527 } else {
1528 if (!stats_open_mem(&stream->stats, pass))
1529 fatal("Failed to open statistics store");
1530 }
1531
1532 #if CONFIG_FP_MB_STATS
1533 if (stream->config.fpmb_stats_fn) {
1534 if (!stats_open_file(&stream->fpmb_stats, stream->config.fpmb_stats_fn,
1535 pass))
1536 fatal("Failed to open mb statistics store");
1537 } else {
1538 if (!stats_open_mem(&stream->fpmb_stats, pass))
1539 fatal("Failed to open mb statistics store");
1540 }
1541 #endif
1542
1543 stream->config.cfg.g_pass = global->passes == 2
1544 ? pass ? VPX_RC_LAST_PASS : VPX_RC_FIRST_PASS
1545 : VPX_RC_ONE_PASS;
1546 if (pass) {
1547 stream->config.cfg.rc_twopass_stats_in = stats_get(&stream->stats);
1548 #if CONFIG_FP_MB_STATS
1549 stream->config.cfg.rc_firstpass_mb_stats_in =
1550 stats_get(&stream->fpmb_stats);
1551 #endif
1552 }
1553
1554 stream->cx_time = 0;
1555 stream->nbytes = 0;
1556 stream->frames_out = 0;
1557 }
1558
1559 static void initialize_encoder(struct stream_state *stream,
1560 struct VpxEncoderConfig *global) {
1561 int i;
1562 int flags = 0;
1563
1564 flags |= global->show_psnr ? VPX_CODEC_USE_PSNR : 0;
1565 flags |= global->out_part ? VPX_CODEC_USE_OUTPUT_PARTITION : 0;
1566 #if CONFIG_VP9_HIGHBITDEPTH
1567 flags |= stream->config.use_16bit_internal ? VPX_CODEC_USE_HIGHBITDEPTH : 0;
1568 #endif
1569
1570 /* Construct Encoder Context */
1571 vpx_codec_enc_init(&stream->encoder, global->codec->codec_interface(),
1572 &stream->config.cfg, flags);
1573 ctx_exit_on_error(&stream->encoder, "Failed to initialize encoder");
1574
1575 /* Note that we bypass the vpx_codec_control wrapper macro because
1576 * we're being clever to store the control IDs in an array. Real
1577 * applications will want to make use of the enumerations directly
1578 */
1579 for (i = 0; i < stream->config.arg_ctrl_cnt; i++) {
1580 int ctrl = stream->config.arg_ctrls[i][0];
1581 int value = stream->config.arg_ctrls[i][1];
1582 if (vpx_codec_control_(&stream->encoder, ctrl, value))
1583 fprintf(stderr, "Error: Tried to set control %d = %d\n", ctrl, value);
1584
1585 ctx_exit_on_error(&stream->encoder, "Failed to control codec");
1586 }
1587
1588 #if CONFIG_DECODERS
1589 if (global->test_decode != TEST_DECODE_OFF) {
1590 const VpxInterface *decoder = get_vpx_decoder_by_name(global->codec->name);
1591 vpx_codec_dec_init(&stream->decoder, decoder->codec_interface(), NULL, 0);
1592 }
1593 #endif
1594 }
1595
1596 static void encode_frame(struct stream_state *stream,
1597 struct VpxEncoderConfig *global, struct vpx_image *img,
1598 unsigned int frames_in) {
1599 vpx_codec_pts_t frame_start, next_frame_start;
1600 struct vpx_codec_enc_cfg *cfg = &stream->config.cfg;
1601 struct vpx_usec_timer timer;
1602
1603 frame_start =
1604 (cfg->g_timebase.den * (int64_t)(frames_in - 1) * global->framerate.den) /
1605 cfg->g_timebase.num / global->framerate.num;
1606 next_frame_start =
1607 (cfg->g_timebase.den * (int64_t)(frames_in)*global->framerate.den) /
1608 cfg->g_timebase.num / global->framerate.num;
1609
1610 /* Scale if necessary */
1611 #if CONFIG_VP9_HIGHBITDEPTH
1612 if (img) {
1613 if ((img->fmt & VPX_IMG_FMT_HIGHBITDEPTH) &&
1614 (img->d_w != cfg->g_w || img->d_h != cfg->g_h)) {
1615 if (img->fmt != VPX_IMG_FMT_I42016) {
1616 fprintf(stderr, "%s can only scale 4:2:0 inputs\n", exec_name);
1617 exit(EXIT_FAILURE);
1618 }
1619 #if CONFIG_LIBYUV
1620 if (!stream->img) {
1621 stream->img =
1622 vpx_img_alloc(NULL, VPX_IMG_FMT_I42016, cfg->g_w, cfg->g_h, 16);
1623 }
1624 I420Scale_16(
1625 (uint16_t *)img->planes[VPX_PLANE_Y], img->stride[VPX_PLANE_Y] / 2,
1626 (uint16_t *)img->planes[VPX_PLANE_U], img->stride[VPX_PLANE_U] / 2,
1627 (uint16_t *)img->planes[VPX_PLANE_V], img->stride[VPX_PLANE_V] / 2,
1628 img->d_w, img->d_h, (uint16_t *)stream->img->planes[VPX_PLANE_Y],
1629 stream->img->stride[VPX_PLANE_Y] / 2,
1630 (uint16_t *)stream->img->planes[VPX_PLANE_U],
1631 stream->img->stride[VPX_PLANE_U] / 2,
1632 (uint16_t *)stream->img->planes[VPX_PLANE_V],
1633 stream->img->stride[VPX_PLANE_V] / 2, stream->img->d_w,
1634 stream->img->d_h, kFilterBox);
1635 img = stream->img;
1636 #else
1637 stream->encoder.err = 1;
1638 ctx_exit_on_error(&stream->encoder,
1639 "Stream %d: Failed to encode frame.\n"
1640 "Scaling disabled in this configuration. \n"
1641 "To enable, configure with --enable-libyuv\n",
1642 stream->index);
1643 #endif
1644 }
1645 }
1646 #endif
1647 if (img && (img->d_w != cfg->g_w || img->d_h != cfg->g_h)) {
1648 if (img->fmt != VPX_IMG_FMT_I420 && img->fmt != VPX_IMG_FMT_YV12) {
1649 fprintf(stderr, "%s can only scale 4:2:0 8bpp inputs\n", exec_name);
1650 exit(EXIT_FAILURE);
1651 }
1652 #if CONFIG_LIBYUV
1653 if (!stream->img)
1654 stream->img =
1655 vpx_img_alloc(NULL, VPX_IMG_FMT_I420, cfg->g_w, cfg->g_h, 16);
1656 I420Scale(
1657 img->planes[VPX_PLANE_Y], img->stride[VPX_PLANE_Y],
1658 img->planes[VPX_PLANE_U], img->stride[VPX_PLANE_U],
1659 img->planes[VPX_PLANE_V], img->stride[VPX_PLANE_V], img->d_w, img->d_h,
1660 stream->img->planes[VPX_PLANE_Y], stream->img->stride[VPX_PLANE_Y],
1661 stream->img->planes[VPX_PLANE_U], stream->img->stride[VPX_PLANE_U],
1662 stream->img->planes[VPX_PLANE_V], stream->img->stride[VPX_PLANE_V],
1663 stream->img->d_w, stream->img->d_h, kFilterBox);
1664 img = stream->img;
1665 #else
1666 stream->encoder.err = 1;
1667 ctx_exit_on_error(&stream->encoder,
1668 "Stream %d: Failed to encode frame.\n"
1669 "Scaling disabled in this configuration. \n"
1670 "To enable, configure with --enable-libyuv\n",
1671 stream->index);
1672 #endif
1673 }
1674
1675 vpx_usec_timer_start(&timer);
1676 vpx_codec_encode(&stream->encoder, img, frame_start,
1677 (unsigned long)(next_frame_start - frame_start), 0,
1678 global->deadline);
1679 vpx_usec_timer_mark(&timer);
1680 stream->cx_time += vpx_usec_timer_elapsed(&timer);
1681 ctx_exit_on_error(&stream->encoder, "Stream %d: Failed to encode frame",
1682 stream->index);
1683 }
1684
1685 static void update_quantizer_histogram(struct stream_state *stream) {
1686 if (stream->config.cfg.g_pass != VPX_RC_FIRST_PASS) {
1687 int q;
1688
1689 vpx_codec_control(&stream->encoder, VP8E_GET_LAST_QUANTIZER_64, &q);
1690 ctx_exit_on_error(&stream->encoder, "Failed to read quantizer");
1691 stream->counts[q]++;
1692 }
1693 }
1694
1695 static void get_cx_data(struct stream_state *stream,
1696 struct VpxEncoderConfig *global, int *got_data) {
1697 const vpx_codec_cx_pkt_t *pkt;
1698 const struct vpx_codec_enc_cfg *cfg = &stream->config.cfg;
1699 vpx_codec_iter_t iter = NULL;
1700
1701 *got_data = 0;
1702 while ((pkt = vpx_codec_get_cx_data(&stream->encoder, &iter))) {
1703 static size_t fsize = 0;
1704 static FileOffset ivf_header_pos = 0;
1705
1706 switch (pkt->kind) {
1707 case VPX_CODEC_CX_FRAME_PKT:
1708 if (!(pkt->data.frame.flags & VPX_FRAME_IS_FRAGMENT)) {
1709 stream->frames_out++;
1710 }
1711 if (!global->quiet)
1712 fprintf(stderr, " %6luF", (unsigned long)pkt->data.frame.sz);
1713
1714 update_rate_histogram(stream->rate_hist, cfg, pkt);
1715 #if CONFIG_WEBM_IO
1716 if (stream->config.write_webm) {
1717 write_webm_block(&stream->webm_ctx, cfg, pkt);
1718 }
1719 #endif
1720 if (!stream->config.write_webm) {
1721 if (pkt->data.frame.partition_id <= 0) {
1722 ivf_header_pos = ftello(stream->file);
1723 fsize = pkt->data.frame.sz;
1724
1725 ivf_write_frame_header(stream->file, pkt->data.frame.pts, fsize);
1726 } else {
1727 fsize += pkt->data.frame.sz;
1728
1729 if (!(pkt->data.frame.flags & VPX_FRAME_IS_FRAGMENT)) {
1730 const FileOffset currpos = ftello(stream->file);
1731 fseeko(stream->file, ivf_header_pos, SEEK_SET);
1732 ivf_write_frame_size(stream->file, fsize);
1733 fseeko(stream->file, currpos, SEEK_SET);
1734 }
1735 }
1736
1737 (void)fwrite(pkt->data.frame.buf, 1, pkt->data.frame.sz,
1738 stream->file);
1739 }
1740 stream->nbytes += pkt->data.raw.sz;
1741
1742 *got_data = 1;
1743 #if CONFIG_DECODERS
1744 if (global->test_decode != TEST_DECODE_OFF && !stream->mismatch_seen) {
1745 vpx_codec_decode(&stream->decoder, pkt->data.frame.buf,
1746 (unsigned int)pkt->data.frame.sz, NULL, 0);
1747 if (stream->decoder.err) {
1748 warn_or_exit_on_error(&stream->decoder,
1749 global->test_decode == TEST_DECODE_FATAL,
1750 "Failed to decode frame %d in stream %d",
1751 stream->frames_out + 1, stream->index);
1752 stream->mismatch_seen = stream->frames_out + 1;
1753 }
1754 }
1755 #endif
1756 break;
1757 case VPX_CODEC_STATS_PKT:
1758 stream->frames_out++;
1759 stats_write(&stream->stats, pkt->data.twopass_stats.buf,
1760 pkt->data.twopass_stats.sz);
1761 stream->nbytes += pkt->data.raw.sz;
1762 break;
1763 #if CONFIG_FP_MB_STATS
1764 case VPX_CODEC_FPMB_STATS_PKT:
1765 stats_write(&stream->fpmb_stats, pkt->data.firstpass_mb_stats.buf,
1766 pkt->data.firstpass_mb_stats.sz);
1767 stream->nbytes += pkt->data.raw.sz;
1768 break;
1769 #endif
1770 case VPX_CODEC_PSNR_PKT:
1771
1772 if (global->show_psnr) {
1773 int i;
1774
1775 stream->psnr_sse_total += pkt->data.psnr.sse[0];
1776 stream->psnr_samples_total += pkt->data.psnr.samples[0];
1777 for (i = 0; i < 4; i++) {
1778 if (!global->quiet)
1779 fprintf(stderr, "%.3f ", pkt->data.psnr.psnr[i]);
1780 stream->psnr_totals[i] += pkt->data.psnr.psnr[i];
1781 }
1782 stream->psnr_count++;
1783 }
1784
1785 break;
1786 default: break;
1787 }
1788 }
1789 }
1790
1791 static void show_psnr(struct stream_state *stream, double peak) {
1792 int i;
1793 double ovpsnr;
1794
1795 if (!stream->psnr_count) return;
1796
1797 fprintf(stderr, "Stream %d PSNR (Overall/Avg/Y/U/V)", stream->index);
1798 ovpsnr = sse_to_psnr((double)stream->psnr_samples_total, peak,
1799 (double)stream->psnr_sse_total);
1800 fprintf(stderr, " %.3f", ovpsnr);
1801
1802 for (i = 0; i < 4; i++) {
1803 fprintf(stderr, " %.3f", stream->psnr_totals[i] / stream->psnr_count);
1804 }
1805 fprintf(stderr, "\n");
1806 }
1807
1808 static float usec_to_fps(uint64_t usec, unsigned int frames) {
1809 return (float)(usec > 0 ? frames * 1000000.0 / (float)usec : 0);
1810 }
1811
1812 static void test_decode(struct stream_state *stream,
1813 enum TestDecodeFatality fatal,
1814 const VpxInterface *codec) {
1815 vpx_image_t enc_img, dec_img;
1816
1817 if (stream->mismatch_seen) return;
1818
1819 /* Get the internal reference frame */
1820 if (strcmp(codec->name, "vp8") == 0) {
1821 struct vpx_ref_frame ref_enc, ref_dec;
1822 int width, height;
1823
1824 width = (stream->config.cfg.g_w + 15) & ~15;
1825 height = (stream->config.cfg.g_h + 15) & ~15;
1826 vpx_img_alloc(&ref_enc.img, VPX_IMG_FMT_I420, width, height, 1);
1827 enc_img = ref_enc.img;
1828 vpx_img_alloc(&ref_dec.img, VPX_IMG_FMT_I420, width, height, 1);
1829 dec_img = ref_dec.img;
1830
1831 ref_enc.frame_type = VP8_LAST_FRAME;
1832 ref_dec.frame_type = VP8_LAST_FRAME;
1833 vpx_codec_control(&stream->encoder, VP8_COPY_REFERENCE, &ref_enc);
1834 vpx_codec_control(&stream->decoder, VP8_COPY_REFERENCE, &ref_dec);
1835 } else {
1836 struct vp9_ref_frame ref_enc, ref_dec;
1837
1838 ref_enc.idx = 0;
1839 ref_dec.idx = 0;
1840 vpx_codec_control(&stream->encoder, VP9_GET_REFERENCE, &ref_enc);
1841 enc_img = ref_enc.img;
1842 vpx_codec_control(&stream->decoder, VP9_GET_REFERENCE, &ref_dec);
1843 dec_img = ref_dec.img;
1844 #if CONFIG_VP9_HIGHBITDEPTH
1845 if ((enc_img.fmt & VPX_IMG_FMT_HIGHBITDEPTH) !=
1846 (dec_img.fmt & VPX_IMG_FMT_HIGHBITDEPTH)) {
1847 if (enc_img.fmt & VPX_IMG_FMT_HIGHBITDEPTH) {
1848 vpx_img_alloc(&enc_img, enc_img.fmt - VPX_IMG_FMT_HIGHBITDEPTH,
1849 enc_img.d_w, enc_img.d_h, 16);
1850 vpx_img_truncate_16_to_8(&enc_img, &ref_enc.img);
1851 }
1852 if (dec_img.fmt & VPX_IMG_FMT_HIGHBITDEPTH) {
1853 vpx_img_alloc(&dec_img, dec_img.fmt - VPX_IMG_FMT_HIGHBITDEPTH,
1854 dec_img.d_w, dec_img.d_h, 16);
1855 vpx_img_truncate_16_to_8(&dec_img, &ref_dec.img);
1856 }
1857 }
1858 #endif
1859 }
1860 ctx_exit_on_error(&stream->encoder, "Failed to get encoder reference frame");
1861 ctx_exit_on_error(&stream->decoder, "Failed to get decoder reference frame");
1862
1863 if (!compare_img(&enc_img, &dec_img)) {
1864 int y[4], u[4], v[4];
1865 #if CONFIG_VP9_HIGHBITDEPTH
1866 if (enc_img.fmt & VPX_IMG_FMT_HIGHBITDEPTH) {
1867 find_mismatch_high(&enc_img, &dec_img, y, u, v);
1868 } else {
1869 find_mismatch(&enc_img, &dec_img, y, u, v);
1870 }
1871 #else
1872 find_mismatch(&enc_img, &dec_img, y, u, v);
1873 #endif
1874 stream->decoder.err = 1;
1875 warn_or_exit_on_error(&stream->decoder, fatal == TEST_DECODE_FATAL,
1876 "Stream %d: Encode/decode mismatch on frame %d at"
1877 " Y[%d, %d] {%d/%d},"
1878 " U[%d, %d] {%d/%d},"
1879 " V[%d, %d] {%d/%d}",
1880 stream->index, stream->frames_out, y[0], y[1], y[2],
1881 y[3], u[0], u[1], u[2], u[3], v[0], v[1], v[2], v[3]);
1882 stream->mismatch_seen = stream->frames_out;
1883 }
1884
1885 vpx_img_free(&enc_img);
1886 vpx_img_free(&dec_img);
1887 }
1888
1889 static void print_time(const char *label, int64_t etl) {
1890 int64_t hours;
1891 int64_t mins;
1892 int64_t secs;
1893
1894 if (etl >= 0) {
1895 hours = etl / 3600;
1896 etl -= hours * 3600;
1897 mins = etl / 60;
1898 etl -= mins * 60;
1899 secs = etl;
1900
1901 fprintf(stderr, "[%3s %2" PRId64 ":%02" PRId64 ":%02" PRId64 "] ", label,
1902 hours, mins, secs);
1903 } else {
1904 fprintf(stderr, "[%3s unknown] ", label);
1905 }
1906 }
1907
1908 int main(int argc, const char **argv_) {
1909 int pass;
1910 vpx_image_t raw;
1911 #if CONFIG_VP9_HIGHBITDEPTH
1912 vpx_image_t raw_shift;
1913 int allocated_raw_shift = 0;
1914 int use_16bit_internal = 0;
1915 int input_shift = 0;
1916 #endif
1917 int frame_avail, got_data;
1918
1919 struct VpxInputContext input;
1920 struct VpxEncoderConfig global;
1921 struct stream_state *streams = NULL;
1922 char **argv, **argi;
1923 uint64_t cx_time = 0;
1924 int stream_cnt = 0;
1925 int res = 0;
1926
1927 memset(&input, 0, sizeof(input));
1928 exec_name = argv_[0];
1929
1930 /* Setup default input stream settings */
1931 input.framerate.numerator = 30;
1932 input.framerate.denominator = 1;
1933 input.only_i420 = 1;
1934 input.bit_depth = 0;
1935
1936 /* First parse the global configuration values, because we want to apply
1937 * other parameters on top of the default configuration provided by the
1938 * codec.
1939 */
1940 argv = argv_dup(argc - 1, argv_ + 1);
1941 parse_global_config(&global, argv);
1942
1943 if (argc < 3) usage_exit();
1944
1945 switch (global.color_type) {
1946 case I420: input.fmt = VPX_IMG_FMT_I420; break;
1947 case I422: input.fmt = VPX_IMG_FMT_I422; break;
1948 case I444: input.fmt = VPX_IMG_FMT_I444; break;
1949 case I440: input.fmt = VPX_IMG_FMT_I440; break;
1950 case YV12: input.fmt = VPX_IMG_FMT_YV12; break;
1951 }
1952
1953 {
1954 /* Now parse each stream's parameters. Using a local scope here
1955 * due to the use of 'stream' as loop variable in FOREACH_STREAM
1956 * loops
1957 */
1958 struct stream_state *stream = NULL;
1959
1960 do {
1961 stream = new_stream(&global, stream);
1962 stream_cnt++;
1963 if (!streams) streams = stream;
1964 } while (parse_stream_params(&global, stream, argv));
1965 }
1966
1967 /* Check for unrecognized options */
1968 for (argi = argv; *argi; argi++)
1969 if (argi[0][0] == '-' && argi[0][1])
1970 die("Error: Unrecognized option %s\n", *argi);
1971
1972 FOREACH_STREAM(check_encoder_config(global.disable_warning_prompt, &global,
1973 &stream->config.cfg););
1974
1975 /* Handle non-option arguments */
1976 input.filename = argv[0];
1977
1978 if (!input.filename) {
1979 fprintf(stderr, "No input file specified!\n");
1980 usage_exit();
1981 }
1982
1983 /* Decide if other chroma subsamplings than 4:2:0 are supported */
1984 if (global.codec->fourcc == VP9_FOURCC) input.only_i420 = 0;
1985
1986 for (pass = global.pass ? global.pass - 1 : 0; pass < global.passes; pass++) {
1987 int frames_in = 0, seen_frames = 0;
1988 int64_t estimated_time_left = -1;
1989 int64_t average_rate = -1;
1990 int64_t lagged_count = 0;
1991
1992 open_input_file(&input);
1993
1994 /* If the input file doesn't specify its w/h (raw files), try to get
1995 * the data from the first stream's configuration.
1996 */
1997 if (!input.width || !input.height) {
1998 FOREACH_STREAM({
1999 if (stream->config.cfg.g_w && stream->config.cfg.g_h) {
2000 input.width = stream->config.cfg.g_w;
2001 input.height = stream->config.cfg.g_h;
2002 break;
2003 }
2004 });
2005 }
2006
2007 /* Update stream configurations from the input file's parameters */
2008 if (!input.width || !input.height)
2009 fatal(
2010 "Specify stream dimensions with --width (-w) "
2011 " and --height (-h)");
2012
2013 /* If input file does not specify bit-depth but input-bit-depth parameter
2014 * exists, assume that to be the input bit-depth. However, if the
2015 * input-bit-depth paramter does not exist, assume the input bit-depth
2016 * to be the same as the codec bit-depth.
2017 */
2018 if (!input.bit_depth) {
2019 FOREACH_STREAM({
2020 if (stream->config.cfg.g_input_bit_depth)
2021 input.bit_depth = stream->config.cfg.g_input_bit_depth;
2022 else
2023 input.bit_depth = stream->config.cfg.g_input_bit_depth =
2024 (int)stream->config.cfg.g_bit_depth;
2025 });
2026 if (input.bit_depth > 8) input.fmt |= VPX_IMG_FMT_HIGHBITDEPTH;
2027 } else {
2028 FOREACH_STREAM(
2029 { stream->config.cfg.g_input_bit_depth = input.bit_depth; });
2030 }
2031
2032 FOREACH_STREAM(set_stream_dimensions(stream, input.width, input.height));
2033 FOREACH_STREAM(validate_stream_config(stream, &global));
2034
2035 /* Ensure that --passes and --pass are consistent. If --pass is set and
2036 * --passes=2, ensure --fpf was set.
2037 */
2038 if (global.pass && global.passes == 2)
2039 FOREACH_STREAM({
2040 if (!stream->config.stats_fn)
2041 die("Stream %d: Must specify --fpf when --pass=%d"
2042 " and --passes=2\n",
2043 stream->index, global.pass);
2044 });
2045
2046 #if !CONFIG_WEBM_IO
2047 FOREACH_STREAM({
2048 if (stream->config.write_webm) {
2049 stream->config.write_webm = 0;
2050 warn(
2051 "vpxenc was compiled without WebM container support."
2052 "Producing IVF output");
2053 }
2054 });
2055 #endif
2056
2057 /* Use the frame rate from the file only if none was specified
2058 * on the command-line.
2059 */
2060 if (!global.have_framerate) {
2061 global.framerate.num = input.framerate.numerator;
2062 global.framerate.den = input.framerate.denominator;
2063 FOREACH_STREAM(stream->config.cfg.g_timebase.den = global.framerate.num;
2064 stream->config.cfg.g_timebase.num = global.framerate.den);
2065 }
2066
2067 /* Show configuration */
2068 if (global.verbose && pass == 0)
2069 FOREACH_STREAM(show_stream_config(stream, &global, &input));
2070
2071 if (pass == (global.pass ? global.pass - 1 : 0)) {
2072 if (input.file_type == FILE_TYPE_Y4M)
2073 /*The Y4M reader does its own allocation.
2074 Just initialize this here to avoid problems if we never read any
2075 frames.*/
2076 memset(&raw, 0, sizeof(raw));
2077 else
2078 vpx_img_alloc(&raw, input.fmt, input.width, input.height, 32);
2079
2080 FOREACH_STREAM(stream->rate_hist = init_rate_histogram(
2081 &stream->config.cfg, &global.framerate));
2082 }
2083
2084 FOREACH_STREAM(setup_pass(stream, &global, pass));
2085 FOREACH_STREAM(
2086 open_output_file(stream, &global, &input.pixel_aspect_ratio));
2087 FOREACH_STREAM(initialize_encoder(stream, &global));
2088
2089 #if CONFIG_VP9_HIGHBITDEPTH
2090 if (strcmp(global.codec->name, "vp9") == 0) {
2091 // Check to see if at least one stream uses 16 bit internal.
2092 // Currently assume that the bit_depths for all streams using
2093 // highbitdepth are the same.
2094 FOREACH_STREAM({
2095 if (stream->config.use_16bit_internal) {
2096 use_16bit_internal = 1;
2097 }
2098 if (stream->config.cfg.g_profile == 0) {
2099 input_shift = 0;
2100 } else {
2101 input_shift = (int)stream->config.cfg.g_bit_depth -
2102 stream->config.cfg.g_input_bit_depth;
2103 }
2104 });
2105 }
2106 #endif
2107
2108 frame_avail = 1;
2109 got_data = 0;
2110
2111 while (frame_avail || got_data) {
2112 struct vpx_usec_timer timer;
2113
2114 if (!global.limit || frames_in < global.limit) {
2115 frame_avail = read_frame(&input, &raw);
2116
2117 if (frame_avail) frames_in++;
2118 seen_frames =
2119 frames_in > global.skip_frames ? frames_in - global.skip_frames : 0;
2120
2121 if (!global.quiet) {
2122 float fps = usec_to_fps(cx_time, seen_frames);
2123 fprintf(stderr, "\rPass %d/%d ", pass + 1, global.passes);
2124
2125 if (stream_cnt == 1)
2126 fprintf(stderr, "frame %4d/%-4d %7" PRId64 "B ", frames_in,
2127 streams->frames_out, (int64_t)streams->nbytes);
2128 else
2129 fprintf(stderr, "frame %4d ", frames_in);
2130
2131 fprintf(stderr, "%7" PRId64 " %s %.2f %s ",
2132 cx_time > 9999999 ? cx_time / 1000 : cx_time,
2133 cx_time > 9999999 ? "ms" : "us", fps >= 1.0 ? fps : fps * 60,
2134 fps >= 1.0 ? "fps" : "fpm");
2135 print_time("ETA", estimated_time_left);
2136 }
2137
2138 } else
2139 frame_avail = 0;
2140
2141 if (frames_in > global.skip_frames) {
2142 #if CONFIG_VP9_HIGHBITDEPTH
2143 vpx_image_t *frame_to_encode;
2144 if (input_shift || (use_16bit_internal && input.bit_depth == 8)) {
2145 assert(use_16bit_internal);
2146 // Input bit depth and stream bit depth do not match, so up
2147 // shift frame to stream bit depth
2148 if (!allocated_raw_shift) {
2149 vpx_img_alloc(&raw_shift, raw.fmt | VPX_IMG_FMT_HIGHBITDEPTH,
2150 input.width, input.height, 32);
2151 allocated_raw_shift = 1;
2152 }
2153 vpx_img_upshift(&raw_shift, &raw, input_shift);
2154 frame_to_encode = &raw_shift;
2155 } else {
2156 frame_to_encode = &raw;
2157 }
2158 vpx_usec_timer_start(&timer);
2159 if (use_16bit_internal) {
2160 assert(frame_to_encode->fmt & VPX_IMG_FMT_HIGHBITDEPTH);
2161 FOREACH_STREAM({
2162 if (stream->config.use_16bit_internal)
2163 encode_frame(stream, &global,
2164 frame_avail ? frame_to_encode : NULL, frames_in);
2165 else
2166 assert(0);
2167 });
2168 } else {
2169 assert((frame_to_encode->fmt & VPX_IMG_FMT_HIGHBITDEPTH) == 0);
2170 FOREACH_STREAM(encode_frame(stream, &global,
2171 frame_avail ? frame_to_encode : NULL,
2172 frames_in));
2173 }
2174 #else
2175 vpx_usec_timer_start(&timer);
2176 FOREACH_STREAM(encode_frame(stream, &global, frame_avail ? &raw : NULL,
2177 frames_in));
2178 #endif
2179 vpx_usec_timer_mark(&timer);
2180 cx_time += vpx_usec_timer_elapsed(&timer);
2181
2182 FOREACH_STREAM(update_quantizer_histogram(stream));
2183
2184 got_data = 0;
2185 FOREACH_STREAM(get_cx_data(stream, &global, &got_data));
2186
2187 if (!got_data && input.length && streams != NULL &&
2188 !streams->frames_out) {
2189 lagged_count = global.limit ? seen_frames : ftello(input.file);
2190 } else if (input.length) {
2191 int64_t remaining;
2192 int64_t rate;
2193
2194 if (global.limit) {
2195 const int64_t frame_in_lagged = (seen_frames - lagged_count) * 1000;
2196
2197 rate = cx_time ? frame_in_lagged * (int64_t)1000000 / cx_time : 0;
2198 remaining = 1000 * (global.limit - global.skip_frames -
2199 seen_frames + lagged_count);
2200 } else {
2201 const int64_t input_pos = ftello(input.file);
2202 const int64_t input_pos_lagged = input_pos - lagged_count;
2203 const int64_t limit = input.length;
2204
2205 rate = cx_time ? input_pos_lagged * (int64_t)1000000 / cx_time : 0;
2206 remaining = limit - input_pos + lagged_count;
2207 }
2208
2209 average_rate =
2210 (average_rate <= 0) ? rate : (average_rate * 7 + rate) / 8;
2211 estimated_time_left = average_rate ? remaining / average_rate : -1;
2212 }
2213
2214 if (got_data && global.test_decode != TEST_DECODE_OFF)
2215 FOREACH_STREAM(test_decode(stream, global.test_decode, global.codec));
2216 }
2217
2218 fflush(stdout);
2219 if (!global.quiet) fprintf(stderr, "\033[K");
2220 }
2221
2222 if (stream_cnt > 1) fprintf(stderr, "\n");
2223
2224 if (!global.quiet) {
2225 FOREACH_STREAM(fprintf(
2226 stderr,
2227 "\rPass %d/%d frame %4d/%-4d %7" PRId64 "B %7" PRId64 "b/f %7" PRId64
2228 "b/s %7" PRId64 " %s (%.2f fps)\033[K\n",
2229 pass + 1, global.passes, frames_in, stream->frames_out,
2230 (int64_t)stream->nbytes,
2231 seen_frames ? (int64_t)(stream->nbytes * 8 / seen_frames) : 0,
2232 seen_frames
2233 ? (int64_t)stream->nbytes * 8 * (int64_t)global.framerate.num /
2234 global.framerate.den / seen_frames
2235 : 0,
2236 stream->cx_time > 9999999 ? stream->cx_time / 1000 : stream->cx_time,
2237 stream->cx_time > 9999999 ? "ms" : "us",
2238 usec_to_fps(stream->cx_time, seen_frames)));
2239 }
2240
2241 if (global.show_psnr) {
2242 if (global.codec->fourcc == VP9_FOURCC) {
2243 FOREACH_STREAM(
2244 show_psnr(stream, (1 << stream->config.cfg.g_input_bit_depth) - 1));
2245 } else {
2246 FOREACH_STREAM(show_psnr(stream, 255.0));
2247 }
2248 }
2249
2250 FOREACH_STREAM(vpx_codec_destroy(&stream->encoder));
2251
2252 if (global.test_decode != TEST_DECODE_OFF) {
2253 FOREACH_STREAM(vpx_codec_destroy(&stream->decoder));
2254 }
2255
2256 close_input_file(&input);
2257
2258 if (global.test_decode == TEST_DECODE_FATAL) {
2259 FOREACH_STREAM(res |= stream->mismatch_seen);
2260 }
2261 FOREACH_STREAM(close_output_file(stream, global.codec->fourcc));
2262
2263 FOREACH_STREAM(stats_close(&stream->stats, global.passes - 1));
2264
2265 #if CONFIG_FP_MB_STATS
2266 FOREACH_STREAM(stats_close(&stream->fpmb_stats, global.passes - 1));
2267 #endif
2268
2269 if (global.pass) break;
2270 }
2271
2272 if (global.show_q_hist_buckets)
2273 FOREACH_STREAM(
2274 show_q_histogram(stream->counts, global.show_q_hist_buckets));
2275
2276 if (global.show_rate_hist_buckets)
2277 FOREACH_STREAM(show_rate_histogram(stream->rate_hist, &stream->config.cfg,
2278 global.show_rate_hist_buckets));
2279 FOREACH_STREAM(destroy_rate_histogram(stream->rate_hist));
2280
2281 #if CONFIG_INTERNAL_STATS
2282 /* TODO(jkoleszar): This doesn't belong in this executable. Do it for now,
2283 * to match some existing utilities.
2284 */
2285 if (!(global.pass == 1 && global.passes == 2))
2286 FOREACH_STREAM({
2287 FILE *f = fopen("opsnr.stt", "a");
2288 if (stream->mismatch_seen) {
2289 fprintf(f, "First mismatch occurred in frame %d\n",
2290 stream->mismatch_seen);
2291 } else {
2292 fprintf(f, "No mismatch detected in recon buffers\n");
2293 }
2294 fclose(f);
2295 });
2296 #endif
2297
2298 #if CONFIG_VP9_HIGHBITDEPTH
2299 if (allocated_raw_shift) vpx_img_free(&raw_shift);
2300 #endif
2301 vpx_img_free(&raw);
2302 free(argv);
2303 free(streams);
2304 return res ? EXIT_FAILURE : EXIT_SUCCESS;
2305 }
vpx_rational
Rational Number.
Definition: vpx_encoder.h:218
VPX_IMG_FMT_I44016
Definition: vpx_image.h:49
vpx_codec_cx_pkt::twopass_stats
vpx_fixed_buf_t twopass_stats
Definition: vpx_encoder.h:182
VP8E_SET_CPUUSED
Codec control function to set encoder internal speed settings.
Definition: vp8cx.h:155
VPX_Q
Definition: vpx_encoder.h:235
vpx_image
Image Descriptor.
Definition: vpx_image.h:71
vpx_decoder.h
Describes the decoder algorithm interface to applications.
vpx_encoder.h
Describes the encoder algorithm interface to applications.
vpx_codec_iface_name
const char * vpx_codec_iface_name(vpx_codec_iface_t *iface)
Return the name for a given interface.
VPX_CS_BT_709
Definition: vpx_image.h:56
VP9E_SET_TPL
Codec control function to enable temporal dependency model.
Definition: vp8cx.h:665
VPX_IMG_FMT_YV12
Definition: vpx_image.h:40
vpx_codec_err_to_string
const char * vpx_codec_err_to_string(vpx_codec_err_t err)
Convert error number to printable string.
VP9E_SET_TUNE_CONTENT
Codec control function to set content type.
Definition: vp8cx.h:460
vpx_codec_enc_cfg::g_timebase
struct vpx_rational g_timebase
Stream timebase units.
Definition: vpx_encoder.h:343
VPX_CBR
Definition: vpx_encoder.h:233
VP9E_SET_NOISE_SENSITIVITY
Codec control function to set noise sensitivity.
Definition: vp8cx.h:418
VPX_CS_RESERVED
Definition: vpx_image.h:60
VPX_CS_SRGB
Definition: vpx_image.h:61
VPX_CS_SMPTE_240
Definition: vpx_image.h:58
vpx_rational::den
int den
Definition: vpx_encoder.h:220
vpx_codec_encode
vpx_codec_err_t vpx_codec_encode(vpx_codec_ctx_t *ctx, const vpx_image_t *img, vpx_codec_pts_t pts, unsigned long duration, vpx_enc_frame_flags_t flags, unsigned long deadline)
Encode a frame.
VPX_CODEC_STATS_PKT
Definition: vpx_encoder.h:148
vp8dx.h
Provides definitions for using VP8 or VP9 within the vpx Decoder interface.
vpx_codec_enc_cfg
Encoder configuration structure.
Definition: vpx_encoder.h:268
VP8E_SET_TUNING
Codec control function to set visual tuning.
Definition: vp8cx.h:229
VP8E_SET_CQ_LEVEL
Codec control function to set constrained quality level.
Definition: vp8cx.h:239
VP8E_SET_ARNR_TYPE
Definition: vp8cx.h:223
VPX_CODEC_PSNR_PKT
Definition: vpx_encoder.h:150
VP9E_SET_ROW_MT
Codec control function to set row level multi-threading.
Definition: vp8cx.h:567
VPX_PLANE_Y
#define VPX_PLANE_Y
Definition: vpx_image.h:95
VP8E_SET_MAX_INTRA_BITRATE_PCT
Codec control function to set Max data rate for Intra frames.
Definition: vp8cx.h:254
VPX_CODEC_USE_HIGHBITDEPTH
#define VPX_CODEC_USE_HIGHBITDEPTH
Definition: vpx_encoder.h:90
vpx_codec_cx_pkt
Encoder output packet.
Definition: vpx_encoder.h:159
vpx_fixed_buf::buf
void * buf
Definition: vpx_encoder.h:97
VPX_PLANE_V
#define VPX_PLANE_V
Definition: vpx_image.h:97
VPX_RC_FIRST_PASS
Definition: vpx_encoder.h:226
VPX_RC_LAST_PASS
Definition: vpx_encoder.h:227
vpx_image::x_chroma_shift
unsigned int x_chroma_shift
Definition: vpx_image.h:90
vpx_image::y_chroma_shift
unsigned int y_chroma_shift
Definition: vpx_image.h:91
VP9E_SET_TILE_COLUMNS
Codec control function to set number of tile columns.
Definition: vp8cx.h:348
VPX_IMG_FMT_HIGHBITDEPTH
#define VPX_IMG_FMT_HIGHBITDEPTH
Definition: vpx_image.h:35
vpx_codec_cx_pkt::frame
struct vpx_codec_cx_pkt::@1::@2 frame
VP8_COPY_REFERENCE
Definition: vp8.h:48
VPX_IMG_FMT_I44416
Definition: vpx_image.h:48
vpx_img_alloc
vpx_image_t * vpx_img_alloc(vpx_image_t *img, vpx_img_fmt_t fmt, unsigned int d_w, unsigned int d_h, unsigned int align)
Open a descriptor, allocating storage for the underlying image.
VPX_IMG_FMT_I420
Definition: vpx_image.h:42
vpx_image::d_w
unsigned int d_w
Definition: vpx_image.h:82
vpx_codec_dec_init
#define vpx_codec_dec_init(ctx, iface, cfg, flags)
Convenience macro for vpx_codec_dec_init_ver()
Definition: vpx_decoder.h:144
VP9E_SET_TARGET_LEVEL
Codec control function to set target level.
Definition: vp8cx.h:559
vpx_codec_enc_cfg::g_w
unsigned int g_w
Width of the frame.
Definition: vpx_encoder.h:304
VPX_IMG_FMT_I42216
Definition: vpx_image.h:47
VP9E_SET_AQ_MODE
Codec control function to set adaptive quantization mode.
Definition: vp8cx.h:395
VP9E_SET_COLOR_SPACE
Codec control function to set color space info.
Definition: vp8cx.h:491
vpx_codec_decode
vpx_codec_err_t vpx_codec_decode(vpx_codec_ctx_t *ctx, const uint8_t *data, unsigned int data_sz, void *user_priv, long deadline)
Decode data.
vpx_codec_enc_cfg::g_h
unsigned int g_h
Height of the frame.
Definition: vpx_encoder.h:313
vpx_img_fmt_t
enum vpx_img_fmt vpx_img_fmt_t
List of supported image formats.
vpx_image::stride
int stride[4]
Definition: vpx_image.h:100
vpx_codec_cx_pkt::kind
enum vpx_codec_cx_pkt_kind kind
Definition: vpx_encoder.h:160
VP9E_SET_LOSSLESS
Codec control function to set lossless encoding mode.
Definition: vp8cx.h:324
vpx_codec_cx_pkt::raw
vpx_fixed_buf_t raw
Definition: vpx_encoder.h:189
VP8E_GET_LAST_QUANTIZER_64
Codec control function to get last quantizer chosen by the encoder.
Definition: vp8cx.h:208
VPX_CS_SMPTE_170
Definition: vpx_image.h:57
VP8E_SET_GF_CBR_BOOST_PCT
Boost percentage for Golden Frame in CBR mode.
Definition: vp8cx.h:598
vpx_img_free
void vpx_img_free(vpx_image_t *img)
Close an image descriptor.
VPX_CODEC_USE_OUTPUT_PARTITION
#define VPX_CODEC_USE_OUTPUT_PARTITION
Make the encoder output one partition at a time.
Definition: vpx_encoder.h:89
vpx_image::fmt
vpx_img_fmt_t fmt
Definition: vpx_image.h:72
VPX_IMG_FMT_I422
Definition: vpx_image.h:43
vpx_image::planes
unsigned char * planes[4]
Definition: vpx_image.h:99
VPX_CS_BT_601
Definition: vpx_image.h:55
VP8E_SET_TOKEN_PARTITIONS
Codec control function to set the number of token partitions.
Definition: vp8cx.h:191
VPX_DL_REALTIME
#define VPX_DL_REALTIME
deadline parameter analogous to VPx REALTIME mode.
Definition: vpx_encoder.h:830
vpx_rational::num
int num
Definition: vpx_encoder.h:219
VP8E_SET_NOISE_SENSITIVITY
control function to set noise sensitivity
Definition: vp8cx.h:170
VPX_BITS_12
Definition: vpx_codec.h:220
VP9E_SET_GF_CBR_BOOST_PCT
Boost percentage for Golden Frame in CBR mode.
Definition: vp8cx.h:290
VPX_DL_BEST_QUALITY
#define VPX_DL_BEST_QUALITY
deadline parameter analogous to VPx BEST QUALITY mode.
Definition: vpx_encoder.h:834
vpx_codec_enc_config_default
vpx_codec_err_t vpx_codec_enc_config_default(vpx_codec_iface_t *iface, vpx_codec_enc_cfg_t *cfg, unsigned int usage)
Get a default configuration.
VPX_VBR
Definition: vpx_encoder.h:232
vpx_codec_enc_cfg::g_pass
enum vpx_enc_pass g_pass
Multi-pass Encoding Mode.
Definition: vpx_encoder.h:358
vpx_codec_cx_pkt::psnr
double psnr[4]
Definition: vpx_encoder.h:187
VPX_CODEC_USE_PSNR
#define VPX_CODEC_USE_PSNR
Initialization-time Feature Enabling.
Definition: vpx_encoder.h:87
VPX_DL_GOOD_QUALITY
#define VPX_DL_GOOD_QUALITY
deadline parameter analogous to VPx GOOD QUALITY mode.
Definition: vpx_encoder.h:832
vpx_codec_cx_pkt::firstpass_mb_stats
vpx_fixed_buf_t firstpass_mb_stats
Definition: vpx_encoder.h:183
vpx_codec_error_detail
const char * vpx_codec_error_detail(vpx_codec_ctx_t *ctx)
Retrieve detailed error information for codec context.
vp8cx.h
Provides definitions for using VP8 or VP9 encoder algorithm within the vpx Codec Interface.
VPX_PLANE_U
#define VPX_PLANE_U
Definition: vpx_image.h:96
vpx_codec_enc_init
#define vpx_codec_enc_init(ctx, iface, cfg, flags)
Convenience macro for vpx_codec_enc_init_ver()
Definition: vpx_encoder.h:741
VP8E_SET_SCREEN_CONTENT_MODE
Codec control function to set encoder screen content mode.
Definition: vp8cx.h:309
vpx_codec_err_t
vpx_codec_err_t
Algorithm return codes.
Definition: vpx_codec.h:90
vpx_codec_get_cx_data
const vpx_codec_cx_pkt_t * vpx_codec_get_cx_data(vpx_codec_ctx_t *ctx, vpx_codec_iter_t *iter)
Encoded data iterator.
vpx_codec_cx_pkt::data
union vpx_codec_cx_pkt::@1 data
VP8E_SET_ARNR_MAXFRAMES
Codec control function to set the max no of frames to create arf.
Definition: vp8cx.h:214
vp9_ref_frame
VP9 specific reference frame data struct.
Definition: vp8.h:110
VPX_KF_DISABLED
Definition: vpx_encoder.h:249
VPX_IMG_FMT_I42016
Definition: vpx_image.h:46
VP8E_SET_ARNR_STRENGTH
Codec control function to set the filter strength for the arf.
Definition: vp8cx.h:220
VP9E_SET_FRAME_PERIODIC_BOOST
Codec control function to enable/disable periodic Q boost.
Definition: vp8cx.h:410
VPX_CODEC_FPMB_STATS_PKT
Definition: vpx_encoder.h:149
vpx_codec_pts_t
int64_t vpx_codec_pts_t
Time Stamp Type.
Definition: vpx_encoder.h:106
VPX_IMG_FMT_I444
Definition: vpx_image.h:44
VP8E_SET_ENABLEAUTOALTREF
Codec control function to enable automatic use of arf frames.
Definition: vp8cx.h:161
vpx_codec_control_
vpx_codec_err_t vpx_codec_control_(vpx_codec_ctx_t *ctx, int ctrl_id,...)
Control algorithm.
VP9E_SET_MIN_GF_INTERVAL
Codec control function to set minimum interval between GF/ARF frames.
Definition: vp8cx.h:511
vpx_ref_frame
reference frame data struct
Definition: vp8.h:101
VP9E_SET_MAX_GF_INTERVAL
Codec control function to set minimum interval between GF/ARF frames.
Definition: vp8cx.h:519
VPX_CQ
Definition: vpx_encoder.h:234
vp9_ref_frame::idx
int idx
Definition: vp8.h:111
vpx_codec_control
#define vpx_codec_control(ctx, id, data)
vpx_codec_control wrapper macro
Definition: vpx_codec.h:404
vpx_codec_destroy
vpx_codec_err_t vpx_codec_destroy(vpx_codec_ctx_t *ctx)
Destroy a codec instance.
VP9E_SET_FRAME_PARALLEL_DECODING
Codec control function to enable frame parallel decoding feature.
Definition: vp8cx.h:382
vpx_image::d_h
unsigned int d_h
Definition: vpx_image.h:83
VPX_CS_UNKNOWN
Definition: vpx_image.h:54
vpx_fixed_buf::sz
size_t sz
Definition: vpx_encoder.h:98
VP9E_SET_MAX_INTER_BITRATE_PCT
Codec control function to set max data rate for Inter frames.
Definition: vp8cx.h:275
VPX_BITS_8
Definition: vpx_codec.h:218
vpx_codec_ctx::err
vpx_codec_err_t err
Definition: vpx_codec.h:200
VP9_GET_REFERENCE
Definition: vp8.h:55
VP8E_SET_STATIC_THRESHOLD
Codec control function to set the threshold for MBs treated static.
Definition: vp8cx.h:185
vpx_codec_error
const char * vpx_codec_error(vpx_codec_ctx_t *ctx)
Retrieve error synopsis for codec context.
VPX_CS_BT_2020
Definition: vpx_image.h:59
VPX_IMG_FMT_I440
Definition: vpx_image.h:45
VPX_BITS_10
Definition: vpx_codec.h:219
VP9E_SET_TILE_ROWS
Codec control function to set number of tile rows.
Definition: vp8cx.h:368
vpx_codec_iter_t
const void * vpx_codec_iter_t
Iterator.
Definition: vpx_codec.h:187
VP8E_SET_SHARPNESS
Codec control function to set higher sharpness at the expense of a lower PSNR.
Definition: vp8cx.h:179
VPX_CODEC_CX_FRAME_PKT
Definition: vpx_encoder.h:147
VP9E_SET_ALT_REF_AQ
Codec control function to enable/disable special mode for altref adaptive quantization. You can use it with –aq-mode concurrently.
Definition: vp8cx.h:583
VPX_FRAME_IS_FRAGMENT
#define VPX_FRAME_IS_FRAGMENT
this is a fragment of the encoded frame
Definition: vpx_encoder.h:123
VPX_RC_ONE_PASS
Definition: vpx_encoder.h:225
vpx_codec_ctx
Codec context structure.
Definition: vpx_codec.h:197