2 * Copyright (c) 2010 The WebM project authors. All Rights Reserved.
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.
12 #include "./vpx_config.h"
23 #include "third_party/libyuv/include/libyuv/scale.h"
26 #include "vpx/vpx_encoder.h"
28 #include "vpx/vpx_decoder.h"
33 #include "./tools_common.h"
35 #if CONFIG_VP8_ENCODER || CONFIG_VP9_ENCODER
36 #include "vpx/vp8cx.h"
38 #if CONFIG_VP8_DECODER || CONFIG_VP9_DECODER
39 #include "vpx/vp8dx.h"
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"
49 #include "./webmenc.h"
51 #include "./y4minput.h"
53 static size_t wrap_fwrite(const void *ptr, size_t size, size_t nmemb,
55 return fwrite(ptr, size, nmemb, stream);
57 #define fwrite wrap_fwrite
59 static const char *exec_name;
61 static void warn_or_exit_on_errorv(vpx_codec_ctx_t *ctx, int fatal,
62 const char *s, va_list ap) {
64 const char *detail = vpx_codec_error_detail(ctx);
66 vfprintf(stderr, s, ap);
67 fprintf(stderr, ": %s\n", vpx_codec_error(ctx));
69 if (detail) fprintf(stderr, " %s\n", detail);
71 if (fatal) exit(EXIT_FAILURE);
75 static void ctx_exit_on_error(vpx_codec_ctx_t *ctx, const char *s, ...) {
79 warn_or_exit_on_errorv(ctx, 1, s, ap);
83 static void warn_or_exit_on_error(vpx_codec_ctx_t *ctx, int fatal,
88 warn_or_exit_on_errorv(ctx, fatal, s, ap);
92 static const arg_def_t help =
93 ARG_DEF(NULL, "help", 0, "Show usage options and exit");
94 static const arg_def_t debugmode =
95 ARG_DEF("D", "debug", 0, "Debug mode (makes output deterministic)");
96 static const arg_def_t outputfile =
97 ARG_DEF("o", "output", 1, "Output filename");
98 static const arg_def_t use_yv12 =
99 ARG_DEF(NULL, "yv12", 0, "Input file is YV12 ");
100 static const arg_def_t use_i420 =
101 ARG_DEF(NULL, "i420", 0, "Input file is I420 (default)");
102 static const arg_def_t use_i422 =
103 ARG_DEF(NULL, "i422", 0, "Input file is I422");
104 static const arg_def_t use_i444 =
105 ARG_DEF(NULL, "i444", 0, "Input file is I444");
106 static const arg_def_t use_i440 =
107 ARG_DEF(NULL, "i440", 0, "Input file is I440");
108 static const arg_def_t codecarg = ARG_DEF(NULL, "codec", 1, "Codec to use");
109 static const arg_def_t passes =
110 ARG_DEF("p", "passes", 1, "Number of passes (1/2)");
111 static const arg_def_t pass_arg =
112 ARG_DEF(NULL, "pass", 1, "Pass to execute (1/2)");
113 static const arg_def_t fpf_name =
114 ARG_DEF(NULL, "fpf", 1, "First pass statistics file name");
115 #if CONFIG_FP_MB_STATS
116 static const arg_def_t fpmbf_name =
117 ARG_DEF(NULL, "fpmbf", 1, "First pass block statistics file name");
119 static const arg_def_t limit =
120 ARG_DEF(NULL, "limit", 1, "Stop encoding after n input frames");
121 static const arg_def_t skip =
122 ARG_DEF(NULL, "skip", 1, "Skip the first n input frames");
123 static const arg_def_t deadline =
124 ARG_DEF("d", "deadline", 1, "Deadline per frame (usec)");
125 static const arg_def_t best_dl =
126 ARG_DEF(NULL, "best", 0, "Use Best Quality Deadline");
127 static const arg_def_t good_dl =
128 ARG_DEF(NULL, "good", 0, "Use Good Quality Deadline");
129 static const arg_def_t rt_dl =
130 ARG_DEF(NULL, "rt", 0, "Use Realtime Quality Deadline");
131 static const arg_def_t quietarg =
132 ARG_DEF("q", "quiet", 0, "Do not print encode progress");
133 static const arg_def_t verbosearg =
134 ARG_DEF("v", "verbose", 0, "Show encoder parameters");
135 static const arg_def_t psnrarg =
136 ARG_DEF(NULL, "psnr", 0, "Show PSNR in status line");
138 static const struct arg_enum_list test_decode_enum[] = {
139 { "off", TEST_DECODE_OFF },
140 { "fatal", TEST_DECODE_FATAL },
141 { "warn", TEST_DECODE_WARN },
144 static const arg_def_t recontest = ARG_DEF_ENUM(
145 NULL, "test-decode", 1, "Test encode/decode mismatch", test_decode_enum);
146 static const arg_def_t framerate =
147 ARG_DEF(NULL, "fps", 1, "Stream frame rate (rate/scale)");
148 static const arg_def_t use_webm =
149 ARG_DEF(NULL, "webm", 0, "Output WebM (default when WebM IO is enabled)");
150 static const arg_def_t use_ivf = ARG_DEF(NULL, "ivf", 0, "Output IVF");
151 static const arg_def_t out_part =
152 ARG_DEF("P", "output-partitions", 0,
153 "Makes encoder output partitions. Requires IVF output!");
154 static const arg_def_t q_hist_n =
155 ARG_DEF(NULL, "q-hist", 1, "Show quantizer histogram (n-buckets)");
156 static const arg_def_t rate_hist_n =
157 ARG_DEF(NULL, "rate-hist", 1, "Show rate histogram (n-buckets)");
158 static const arg_def_t disable_warnings =
159 ARG_DEF(NULL, "disable-warnings", 0,
160 "Disable warnings about potentially incorrect encode settings.");
161 static const arg_def_t disable_warning_prompt =
162 ARG_DEF("y", "disable-warning-prompt", 0,
163 "Display warnings, but do not prompt user to continue.");
165 #if CONFIG_VP9_HIGHBITDEPTH
166 static const arg_def_t test16bitinternalarg = ARG_DEF(
167 NULL, "test-16bit-internal", 0, "Force use of 16 bit internal buffer");
170 static const arg_def_t *main_args[] = { &help,
192 &disable_warning_prompt,
196 static const arg_def_t usage =
197 ARG_DEF("u", "usage", 1, "Usage profile number to use");
198 static const arg_def_t threads =
199 ARG_DEF("t", "threads", 1, "Max number of threads to use");
200 static const arg_def_t profile =
201 ARG_DEF(NULL, "profile", 1, "Bitstream profile number to use");
202 static const arg_def_t width = ARG_DEF("w", "width", 1, "Frame width");
203 static const arg_def_t height = ARG_DEF("h", "height", 1, "Frame height");
205 static const struct arg_enum_list stereo_mode_enum[] = {
206 { "mono", STEREO_FORMAT_MONO },
207 { "left-right", STEREO_FORMAT_LEFT_RIGHT },
208 { "bottom-top", STEREO_FORMAT_BOTTOM_TOP },
209 { "top-bottom", STEREO_FORMAT_TOP_BOTTOM },
210 { "right-left", STEREO_FORMAT_RIGHT_LEFT },
213 static const arg_def_t stereo_mode = ARG_DEF_ENUM(
214 NULL, "stereo-mode", 1, "Stereo 3D video format", stereo_mode_enum);
216 static const arg_def_t timebase = ARG_DEF(
217 NULL, "timebase", 1, "Output timestamp precision (fractional seconds)");
218 static const arg_def_t error_resilient =
219 ARG_DEF(NULL, "error-resilient", 1, "Enable error resiliency features");
220 static const arg_def_t lag_in_frames =
221 ARG_DEF(NULL, "lag-in-frames", 1, "Max number of frames to lag");
223 static const arg_def_t *global_args[] = { &use_yv12,
239 #if CONFIG_VP9_HIGHBITDEPTH
240 &test16bitinternalarg,
245 static const arg_def_t dropframe_thresh =
246 ARG_DEF(NULL, "drop-frame", 1, "Temporal resampling threshold (buf %)");
247 static const arg_def_t resize_allowed =
248 ARG_DEF(NULL, "resize-allowed", 1, "Spatial resampling enabled (bool)");
249 static const arg_def_t resize_width =
250 ARG_DEF(NULL, "resize-width", 1, "Width of encoded frame");
251 static const arg_def_t resize_height =
252 ARG_DEF(NULL, "resize-height", 1, "Height of encoded frame");
253 static const arg_def_t resize_up_thresh =
254 ARG_DEF(NULL, "resize-up", 1, "Upscale threshold (buf %)");
255 static const arg_def_t resize_down_thresh =
256 ARG_DEF(NULL, "resize-down", 1, "Downscale threshold (buf %)");
257 static const struct arg_enum_list end_usage_enum[] = { { "vbr", VPX_VBR },
262 static const arg_def_t end_usage =
263 ARG_DEF_ENUM(NULL, "end-usage", 1, "Rate control mode", end_usage_enum);
264 static const arg_def_t target_bitrate =
265 ARG_DEF(NULL, "target-bitrate", 1, "Bitrate (kbps)");
266 static const arg_def_t min_quantizer =
267 ARG_DEF(NULL, "min-q", 1, "Minimum (best) quantizer");
268 static const arg_def_t max_quantizer =
269 ARG_DEF(NULL, "max-q", 1, "Maximum (worst) quantizer");
270 static const arg_def_t undershoot_pct =
271 ARG_DEF(NULL, "undershoot-pct", 1, "Datarate undershoot (min) target (%)");
272 static const arg_def_t overshoot_pct =
273 ARG_DEF(NULL, "overshoot-pct", 1, "Datarate overshoot (max) target (%)");
274 static const arg_def_t buf_sz =
275 ARG_DEF(NULL, "buf-sz", 1, "Client buffer size (ms)");
276 static const arg_def_t buf_initial_sz =
277 ARG_DEF(NULL, "buf-initial-sz", 1, "Client initial buffer size (ms)");
278 static const arg_def_t buf_optimal_sz =
279 ARG_DEF(NULL, "buf-optimal-sz", 1, "Client optimal buffer size (ms)");
280 static const arg_def_t *rc_args[] = {
281 &dropframe_thresh, &resize_allowed, &resize_width, &resize_height,
282 &resize_up_thresh, &resize_down_thresh, &end_usage, &target_bitrate,
283 &min_quantizer, &max_quantizer, &undershoot_pct, &overshoot_pct,
284 &buf_sz, &buf_initial_sz, &buf_optimal_sz, NULL
287 static const arg_def_t bias_pct =
288 ARG_DEF(NULL, "bias-pct", 1, "CBR/VBR bias (0=CBR, 100=VBR)");
289 static const arg_def_t minsection_pct =
290 ARG_DEF(NULL, "minsection-pct", 1, "GOP min bitrate (% of target)");
291 static const arg_def_t maxsection_pct =
292 ARG_DEF(NULL, "maxsection-pct", 1, "GOP max bitrate (% of target)");
293 static const arg_def_t corpus_complexity =
294 ARG_DEF(NULL, "corpus-complexity", 1, "corpus vbr complexity midpoint");
295 static const arg_def_t *rc_twopass_args[] = {
296 &bias_pct, &minsection_pct, &maxsection_pct, &corpus_complexity, NULL
299 static const arg_def_t kf_min_dist =
300 ARG_DEF(NULL, "kf-min-dist", 1, "Minimum keyframe interval (frames)");
301 static const arg_def_t kf_max_dist =
302 ARG_DEF(NULL, "kf-max-dist", 1, "Maximum keyframe interval (frames)");
303 static const arg_def_t kf_disabled =
304 ARG_DEF(NULL, "disable-kf", 0, "Disable keyframe placement");
305 static const arg_def_t *kf_args[] = { &kf_min_dist, &kf_max_dist, &kf_disabled,
308 static const arg_def_t noise_sens =
309 ARG_DEF(NULL, "noise-sensitivity", 1, "Noise sensitivity (frames to blur)");
310 static const arg_def_t sharpness =
311 ARG_DEF(NULL, "sharpness", 1,
312 "Increase sharpness at the expense of lower PSNR. (0..7)");
313 static const arg_def_t static_thresh =
314 ARG_DEF(NULL, "static-thresh", 1, "Motion detection threshold");
315 static const arg_def_t auto_altref =
316 ARG_DEF(NULL, "auto-alt-ref", 1, "Enable automatic alt reference frames");
317 static const arg_def_t arnr_maxframes =
318 ARG_DEF(NULL, "arnr-maxframes", 1, "AltRef max frames (0..15)");
319 static const arg_def_t arnr_strength =
320 ARG_DEF(NULL, "arnr-strength", 1, "AltRef filter strength (0..6)");
321 static const arg_def_t arnr_type =
322 ARG_DEF(NULL, "arnr-type", 1, "AltRef filter type (1..3)");
323 static const struct arg_enum_list tuning_enum[] = {
324 { "psnr", VP8_TUNE_PSNR }, { "ssim", VP8_TUNE_SSIM }, { NULL, 0 }
326 static const arg_def_t tune_ssim =
327 ARG_DEF_ENUM(NULL, "tune", 1, "Material to favor", tuning_enum);
328 static const arg_def_t cq_level =
329 ARG_DEF(NULL, "cq-level", 1, "Constant/Constrained Quality level");
330 static const arg_def_t max_intra_rate_pct =
331 ARG_DEF(NULL, "max-intra-rate", 1, "Max I-frame bitrate (pct)");
332 static const arg_def_t gf_cbr_boost_pct = ARG_DEF(
333 NULL, "gf-cbr-boost", 1, "Boost for Golden Frame in CBR mode (pct)");
335 #if CONFIG_VP8_ENCODER
336 static const arg_def_t cpu_used_vp8 =
337 ARG_DEF(NULL, "cpu-used", 1, "CPU Used (-16..16)");
338 static const arg_def_t token_parts =
339 ARG_DEF(NULL, "token-parts", 1, "Number of token partitions to use, log2");
340 static const arg_def_t screen_content_mode =
341 ARG_DEF(NULL, "screen-content-mode", 1, "Screen content mode");
342 static const arg_def_t *vp8_args[] = { &cpu_used_vp8,
355 &screen_content_mode,
357 static const int vp8_arg_ctrl_map[] = { VP8E_SET_CPUUSED,
358 VP8E_SET_ENABLEAUTOALTREF,
359 VP8E_SET_NOISE_SENSITIVITY,
361 VP8E_SET_STATIC_THRESHOLD,
362 VP8E_SET_TOKEN_PARTITIONS,
363 VP8E_SET_ARNR_MAXFRAMES,
364 VP8E_SET_ARNR_STRENGTH,
368 VP8E_SET_MAX_INTRA_BITRATE_PCT,
369 VP8E_SET_GF_CBR_BOOST_PCT,
370 VP8E_SET_SCREEN_CONTENT_MODE,
374 #if CONFIG_VP9_ENCODER
375 static const arg_def_t cpu_used_vp9 =
376 ARG_DEF(NULL, "cpu-used", 1, "CPU Used (-8..8)");
377 static const arg_def_t tile_cols =
378 ARG_DEF(NULL, "tile-columns", 1, "Number of tile columns to use, log2");
379 static const arg_def_t tile_rows =
380 ARG_DEF(NULL, "tile-rows", 1,
381 "Number of tile rows to use, log2 (set to 0 while threads > 1)");
383 static const arg_def_t enable_tpl_model =
384 ARG_DEF(NULL, "enable-tpl", 1, "Enable temporal dependency model");
386 static const arg_def_t lossless =
387 ARG_DEF(NULL, "lossless", 1, "Lossless mode (0: false (default), 1: true)");
388 static const arg_def_t frame_parallel_decoding = ARG_DEF(
389 NULL, "frame-parallel", 1, "Enable frame parallel decodability features");
390 static const arg_def_t aq_mode = ARG_DEF(
392 "Adaptive quantization mode (0: off (default), 1: variance 2: complexity, "
393 "3: cyclic refresh, 4: equator360)");
394 static const arg_def_t alt_ref_aq = ARG_DEF(NULL, "alt-ref-aq", 1,
395 "Special adaptive quantization for "
396 "the alternate reference frames.");
397 static const arg_def_t frame_periodic_boost =
398 ARG_DEF(NULL, "frame-boost", 1,
399 "Enable frame periodic boost (0: off (default), 1: on)");
400 static const arg_def_t max_inter_rate_pct =
401 ARG_DEF(NULL, "max-inter-rate", 1, "Max P-frame bitrate (pct)");
402 static const arg_def_t min_gf_interval = ARG_DEF(
403 NULL, "min-gf-interval", 1,
404 "min gf/arf frame interval (default 0, indicating in-built behavior)");
405 static const arg_def_t max_gf_interval = ARG_DEF(
406 NULL, "max-gf-interval", 1,
407 "max gf/arf frame interval (default 0, indicating in-built behavior)");
409 static const struct arg_enum_list color_space_enum[] = {
410 { "unknown", VPX_CS_UNKNOWN },
411 { "bt601", VPX_CS_BT_601 },
412 { "bt709", VPX_CS_BT_709 },
413 { "smpte170", VPX_CS_SMPTE_170 },
414 { "smpte240", VPX_CS_SMPTE_240 },
415 { "bt2020", VPX_CS_BT_2020 },
416 { "reserved", VPX_CS_RESERVED },
417 { "sRGB", VPX_CS_SRGB },
421 static const arg_def_t input_color_space =
422 ARG_DEF_ENUM(NULL, "color-space", 1,
423 "The color space of input content:", color_space_enum);
425 #if CONFIG_VP9_HIGHBITDEPTH
426 static const struct arg_enum_list bitdepth_enum[] = {
427 { "8", VPX_BITS_8 }, { "10", VPX_BITS_10 }, { "12", VPX_BITS_12 }, { NULL, 0 }
430 static const arg_def_t bitdeptharg = ARG_DEF_ENUM(
432 "Bit depth for codec (8 for version <=1, 10 or 12 for version 2)",
434 static const arg_def_t inbitdeptharg =
435 ARG_DEF(NULL, "input-bit-depth", 1, "Bit depth of input");
438 static const struct arg_enum_list tune_content_enum[] = {
439 { "default", VP9E_CONTENT_DEFAULT },
440 { "screen", VP9E_CONTENT_SCREEN },
441 { "film", VP9E_CONTENT_FILM },
445 static const arg_def_t tune_content = ARG_DEF_ENUM(
446 NULL, "tune-content", 1, "Tune content type", tune_content_enum);
448 static const arg_def_t target_level = ARG_DEF(
449 NULL, "target-level", 1,
451 " 255: off (default)\n"
452 " 0: only keep level stats\n"
453 " 1: adaptively set alt-ref "
454 "distance and column tile limit based on picture size, and keep"
456 " 10: level 1.0 11: level 1.1 "
457 "... 62: level 6.2");
459 static const arg_def_t row_mt =
460 ARG_DEF(NULL, "row-mt", 1,
461 "Enable row based non-deterministic multi-threading in VP9");
464 #if CONFIG_VP9_ENCODER
465 static const arg_def_t *vp9_args[] = { &cpu_used_vp9,
481 &frame_parallel_decoding,
484 &frame_periodic_boost,
492 #if CONFIG_VP9_HIGHBITDEPTH
495 #endif // CONFIG_VP9_HIGHBITDEPTH
497 static const int vp9_arg_ctrl_map[] = { VP8E_SET_CPUUSED,
498 VP8E_SET_ENABLEAUTOALTREF,
500 VP8E_SET_STATIC_THRESHOLD,
501 VP9E_SET_TILE_COLUMNS,
504 VP8E_SET_ARNR_MAXFRAMES,
505 VP8E_SET_ARNR_STRENGTH,
509 VP8E_SET_MAX_INTRA_BITRATE_PCT,
510 VP9E_SET_MAX_INTER_BITRATE_PCT,
511 VP9E_SET_GF_CBR_BOOST_PCT,
513 VP9E_SET_FRAME_PARALLEL_DECODING,
516 VP9E_SET_FRAME_PERIODIC_BOOST,
517 VP9E_SET_NOISE_SENSITIVITY,
518 VP9E_SET_TUNE_CONTENT,
519 VP9E_SET_COLOR_SPACE,
520 VP9E_SET_MIN_GF_INTERVAL,
521 VP9E_SET_MAX_GF_INTERVAL,
522 VP9E_SET_TARGET_LEVEL,
527 static const arg_def_t *no_args[] = { NULL };
529 static void show_help(FILE *fout, int shorthelp) {
531 const int num_encoder = get_vpx_encoder_count();
533 fprintf(fout, "Usage: %s <options> -o dst_filename src_filename \n",
537 fprintf(fout, "Use --help to see the full list of options.\n");
541 fprintf(fout, "\nOptions:\n");
542 arg_show_usage(fout, main_args);
543 fprintf(fout, "\nEncoder Global Options:\n");
544 arg_show_usage(fout, global_args);
545 fprintf(fout, "\nRate Control Options:\n");
546 arg_show_usage(fout, rc_args);
547 fprintf(fout, "\nTwopass Rate Control Options:\n");
548 arg_show_usage(fout, rc_twopass_args);
549 fprintf(fout, "\nKeyframe Placement Options:\n");
550 arg_show_usage(fout, kf_args);
551 #if CONFIG_VP8_ENCODER
552 fprintf(fout, "\nVP8 Specific Options:\n");
553 arg_show_usage(fout, vp8_args);
555 #if CONFIG_VP9_ENCODER
556 fprintf(fout, "\nVP9 Specific Options:\n");
557 arg_show_usage(fout, vp9_args);
560 "\nStream timebase (--timebase):\n"
561 " The desired precision of timestamps in the output, expressed\n"
562 " in fractional seconds. Default is 1/1000.\n");
563 fprintf(fout, "\nIncluded encoders:\n\n");
565 for (i = 0; i < num_encoder; ++i) {
566 const VpxInterface *const encoder = get_vpx_encoder_by_index(i);
567 const char *defstr = (i == (num_encoder - 1)) ? "(default)" : "";
568 fprintf(fout, " %-6s - %s %s\n", encoder->name,
569 vpx_codec_iface_name(encoder->codec_interface()), defstr);
571 fprintf(fout, "\n ");
572 fprintf(fout, "Use --codec to switch to a non-default encoder.\n\n");
575 void usage_exit(void) {
576 show_help(stderr, 1);
580 #define mmin(a, b) ((a) < (b) ? (a) : (b))
582 #if CONFIG_VP9_HIGHBITDEPTH
583 static void find_mismatch_high(const vpx_image_t *const img1,
584 const vpx_image_t *const img2, int yloc[4],
585 int uloc[4], int vloc[4]) {
586 uint16_t *plane1, *plane2;
587 uint32_t stride1, stride2;
588 const uint32_t bsize = 64;
589 const uint32_t bsizey = bsize >> img1->y_chroma_shift;
590 const uint32_t bsizex = bsize >> img1->x_chroma_shift;
592 (img1->d_w + img1->x_chroma_shift) >> img1->x_chroma_shift;
594 (img1->d_h + img1->y_chroma_shift) >> img1->y_chroma_shift;
597 yloc[0] = yloc[1] = yloc[2] = yloc[3] = -1;
598 plane1 = (uint16_t *)img1->planes[VPX_PLANE_Y];
599 plane2 = (uint16_t *)img2->planes[VPX_PLANE_Y];
600 stride1 = img1->stride[VPX_PLANE_Y] / 2;
601 stride2 = img2->stride[VPX_PLANE_Y] / 2;
602 for (i = 0, match = 1; match && i < img1->d_h; i += bsize) {
603 for (j = 0; match && j < img1->d_w; j += bsize) {
605 const int si = mmin(i + bsize, img1->d_h) - i;
606 const int sj = mmin(j + bsize, img1->d_w) - j;
607 for (k = 0; match && k < si; ++k) {
608 for (l = 0; match && l < sj; ++l) {
609 if (*(plane1 + (i + k) * stride1 + j + l) !=
610 *(plane2 + (i + k) * stride2 + j + l)) {
613 yloc[2] = *(plane1 + (i + k) * stride1 + j + l);
614 yloc[3] = *(plane2 + (i + k) * stride2 + j + l);
623 uloc[0] = uloc[1] = uloc[2] = uloc[3] = -1;
624 plane1 = (uint16_t *)img1->planes[VPX_PLANE_U];
625 plane2 = (uint16_t *)img2->planes[VPX_PLANE_U];
626 stride1 = img1->stride[VPX_PLANE_U] / 2;
627 stride2 = img2->stride[VPX_PLANE_U] / 2;
628 for (i = 0, match = 1; match && i < c_h; i += bsizey) {
629 for (j = 0; match && j < c_w; j += bsizex) {
631 const int si = mmin(i + bsizey, c_h - i);
632 const int sj = mmin(j + bsizex, c_w - j);
633 for (k = 0; match && k < si; ++k) {
634 for (l = 0; match && l < sj; ++l) {
635 if (*(plane1 + (i + k) * stride1 + j + l) !=
636 *(plane2 + (i + k) * stride2 + j + l)) {
639 uloc[2] = *(plane1 + (i + k) * stride1 + j + l);
640 uloc[3] = *(plane2 + (i + k) * stride2 + j + l);
649 vloc[0] = vloc[1] = vloc[2] = vloc[3] = -1;
650 plane1 = (uint16_t *)img1->planes[VPX_PLANE_V];
651 plane2 = (uint16_t *)img2->planes[VPX_PLANE_V];
652 stride1 = img1->stride[VPX_PLANE_V] / 2;
653 stride2 = img2->stride[VPX_PLANE_V] / 2;
654 for (i = 0, match = 1; match && i < c_h; i += bsizey) {
655 for (j = 0; match && j < c_w; j += bsizex) {
657 const int si = mmin(i + bsizey, c_h - i);
658 const int sj = mmin(j + bsizex, c_w - j);
659 for (k = 0; match && k < si; ++k) {
660 for (l = 0; match && l < sj; ++l) {
661 if (*(plane1 + (i + k) * stride1 + j + l) !=
662 *(plane2 + (i + k) * stride2 + j + l)) {
665 vloc[2] = *(plane1 + (i + k) * stride1 + j + l);
666 vloc[3] = *(plane2 + (i + k) * stride2 + j + l);
677 static void find_mismatch(const vpx_image_t *const img1,
678 const vpx_image_t *const img2, int yloc[4],
679 int uloc[4], int vloc[4]) {
680 const uint32_t bsize = 64;
681 const uint32_t bsizey = bsize >> img1->y_chroma_shift;
682 const uint32_t bsizex = bsize >> img1->x_chroma_shift;
684 (img1->d_w + img1->x_chroma_shift) >> img1->x_chroma_shift;
686 (img1->d_h + img1->y_chroma_shift) >> img1->y_chroma_shift;
689 yloc[0] = yloc[1] = yloc[2] = yloc[3] = -1;
690 for (i = 0, match = 1; match && i < img1->d_h; i += bsize) {
691 for (j = 0; match && j < img1->d_w; j += bsize) {
693 const int si = mmin(i + bsize, img1->d_h) - i;
694 const int sj = mmin(j + bsize, img1->d_w) - j;
695 for (k = 0; match && k < si; ++k) {
696 for (l = 0; match && l < sj; ++l) {
697 if (*(img1->planes[VPX_PLANE_Y] +
698 (i + k) * img1->stride[VPX_PLANE_Y] + j + l) !=
699 *(img2->planes[VPX_PLANE_Y] +
700 (i + k) * img2->stride[VPX_PLANE_Y] + j + l)) {
703 yloc[2] = *(img1->planes[VPX_PLANE_Y] +
704 (i + k) * img1->stride[VPX_PLANE_Y] + j + l);
705 yloc[3] = *(img2->planes[VPX_PLANE_Y] +
706 (i + k) * img2->stride[VPX_PLANE_Y] + j + l);
715 uloc[0] = uloc[1] = uloc[2] = uloc[3] = -1;
716 for (i = 0, match = 1; match && i < c_h; i += bsizey) {
717 for (j = 0; match && j < c_w; j += bsizex) {
719 const int si = mmin(i + bsizey, c_h - i);
720 const int sj = mmin(j + bsizex, c_w - j);
721 for (k = 0; match && k < si; ++k) {
722 for (l = 0; match && l < sj; ++l) {
723 if (*(img1->planes[VPX_PLANE_U] +
724 (i + k) * img1->stride[VPX_PLANE_U] + j + l) !=
725 *(img2->planes[VPX_PLANE_U] +
726 (i + k) * img2->stride[VPX_PLANE_U] + j + l)) {
729 uloc[2] = *(img1->planes[VPX_PLANE_U] +
730 (i + k) * img1->stride[VPX_PLANE_U] + j + l);
731 uloc[3] = *(img2->planes[VPX_PLANE_U] +
732 (i + k) * img2->stride[VPX_PLANE_U] + j + l);
740 vloc[0] = vloc[1] = vloc[2] = vloc[3] = -1;
741 for (i = 0, match = 1; match && i < c_h; i += bsizey) {
742 for (j = 0; match && j < c_w; j += bsizex) {
744 const int si = mmin(i + bsizey, c_h - i);
745 const int sj = mmin(j + bsizex, c_w - j);
746 for (k = 0; match && k < si; ++k) {
747 for (l = 0; match && l < sj; ++l) {
748 if (*(img1->planes[VPX_PLANE_V] +
749 (i + k) * img1->stride[VPX_PLANE_V] + j + l) !=
750 *(img2->planes[VPX_PLANE_V] +
751 (i + k) * img2->stride[VPX_PLANE_V] + j + l)) {
754 vloc[2] = *(img1->planes[VPX_PLANE_V] +
755 (i + k) * img1->stride[VPX_PLANE_V] + j + l);
756 vloc[3] = *(img2->planes[VPX_PLANE_V] +
757 (i + k) * img2->stride[VPX_PLANE_V] + j + l);
767 static int compare_img(const vpx_image_t *const img1,
768 const vpx_image_t *const img2) {
769 uint32_t l_w = img1->d_w;
770 uint32_t c_w = (img1->d_w + img1->x_chroma_shift) >> img1->x_chroma_shift;
772 (img1->d_h + img1->y_chroma_shift) >> img1->y_chroma_shift;
776 match &= (img1->fmt == img2->fmt);
777 match &= (img1->d_w == img2->d_w);
778 match &= (img1->d_h == img2->d_h);
779 #if CONFIG_VP9_HIGHBITDEPTH
780 if (img1->fmt & VPX_IMG_FMT_HIGHBITDEPTH) {
786 for (i = 0; i < img1->d_h; ++i)
787 match &= (memcmp(img1->planes[VPX_PLANE_Y] + i * img1->stride[VPX_PLANE_Y],
788 img2->planes[VPX_PLANE_Y] + i * img2->stride[VPX_PLANE_Y],
791 for (i = 0; i < c_h; ++i)
792 match &= (memcmp(img1->planes[VPX_PLANE_U] + i * img1->stride[VPX_PLANE_U],
793 img2->planes[VPX_PLANE_U] + i * img2->stride[VPX_PLANE_U],
796 for (i = 0; i < c_h; ++i)
797 match &= (memcmp(img1->planes[VPX_PLANE_V] + i * img1->stride[VPX_PLANE_V],
798 img2->planes[VPX_PLANE_V] + i * img2->stride[VPX_PLANE_V],
804 #define NELEMENTS(x) (sizeof(x) / sizeof(x[0]))
805 #if CONFIG_VP9_ENCODER
806 #define ARG_CTRL_CNT_MAX NELEMENTS(vp9_arg_ctrl_map)
808 #define ARG_CTRL_CNT_MAX NELEMENTS(vp8_arg_ctrl_map)
812 typedef int stereo_format_t;
813 struct WebmOutputContext {
818 /* Per-stream configuration */
819 struct stream_config {
820 struct vpx_codec_enc_cfg cfg;
822 const char *stats_fn;
823 #if CONFIG_FP_MB_STATS
824 const char *fpmb_stats_fn;
826 stereo_format_t stereo_fmt;
827 int arg_ctrls[ARG_CTRL_CNT_MAX][2];
830 #if CONFIG_VP9_HIGHBITDEPTH
831 // whether to use 16bit internal buffers
832 int use_16bit_internal;
836 struct stream_state {
838 struct stream_state *next;
839 struct stream_config config;
841 struct rate_hist *rate_hist;
842 struct WebmOutputContext webm_ctx;
843 uint64_t psnr_sse_total;
844 uint64_t psnr_samples_total;
845 double psnr_totals[4];
848 vpx_codec_ctx_t encoder;
849 unsigned int frames_out;
853 #if CONFIG_FP_MB_STATS
854 stats_io_t fpmb_stats;
856 struct vpx_image *img;
857 vpx_codec_ctx_t decoder;
861 static void validate_positive_rational(const char *msg,
862 struct vpx_rational *rat) {
868 if (rat->num < 0) die("Error: %s must be positive\n", msg);
870 if (!rat->den) die("Error: %s has zero denominator\n", msg);
873 static void parse_global_config(struct VpxEncoderConfig *global, char **argv) {
876 const int num_encoder = get_vpx_encoder_count();
878 if (num_encoder < 1) die("Error: no valid encoder available\n");
880 /* Initialize default parameters */
881 memset(global, 0, sizeof(*global));
882 global->codec = get_vpx_encoder_by_index(num_encoder - 1);
884 global->color_type = I420;
885 /* Assign default deadline to good quality */
886 global->deadline = VPX_DL_GOOD_QUALITY;
888 for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step) {
891 if (arg_match(&arg, &help, argi)) {
892 show_help(stdout, 0);
894 } else if (arg_match(&arg, &codecarg, argi)) {
895 global->codec = get_vpx_encoder_by_name(arg.val);
897 die("Error: Unrecognized argument (%s) to --codec\n", arg.val);
898 } else if (arg_match(&arg, &passes, argi)) {
899 global->passes = arg_parse_uint(&arg);
901 if (global->passes < 1 || global->passes > 2)
902 die("Error: Invalid number of passes (%d)\n", global->passes);
903 } else if (arg_match(&arg, &pass_arg, argi)) {
904 global->pass = arg_parse_uint(&arg);
906 if (global->pass < 1 || global->pass > 2)
907 die("Error: Invalid pass selected (%d)\n", global->pass);
908 } else if (arg_match(&arg, &usage, argi))
909 global->usage = arg_parse_uint(&arg);
910 else if (arg_match(&arg, &deadline, argi))
911 global->deadline = arg_parse_uint(&arg);
912 else if (arg_match(&arg, &best_dl, argi))
913 global->deadline = VPX_DL_BEST_QUALITY;
914 else if (arg_match(&arg, &good_dl, argi))
915 global->deadline = VPX_DL_GOOD_QUALITY;
916 else if (arg_match(&arg, &rt_dl, argi))
917 global->deadline = VPX_DL_REALTIME;
918 else if (arg_match(&arg, &use_yv12, argi))
919 global->color_type = YV12;
920 else if (arg_match(&arg, &use_i420, argi))
921 global->color_type = I420;
922 else if (arg_match(&arg, &use_i422, argi))
923 global->color_type = I422;
924 else if (arg_match(&arg, &use_i444, argi))
925 global->color_type = I444;
926 else if (arg_match(&arg, &use_i440, argi))
927 global->color_type = I440;
928 else if (arg_match(&arg, &quietarg, argi))
930 else if (arg_match(&arg, &verbosearg, argi))
932 else if (arg_match(&arg, &limit, argi))
933 global->limit = arg_parse_uint(&arg);
934 else if (arg_match(&arg, &skip, argi))
935 global->skip_frames = arg_parse_uint(&arg);
936 else if (arg_match(&arg, &psnrarg, argi))
937 global->show_psnr = 1;
938 else if (arg_match(&arg, &recontest, argi))
939 global->test_decode = arg_parse_enum_or_int(&arg);
940 else if (arg_match(&arg, &framerate, argi)) {
941 global->framerate = arg_parse_rational(&arg);
942 validate_positive_rational(arg.name, &global->framerate);
943 global->have_framerate = 1;
944 } else if (arg_match(&arg, &out_part, argi))
945 global->out_part = 1;
946 else if (arg_match(&arg, &debugmode, argi))
948 else if (arg_match(&arg, &q_hist_n, argi))
949 global->show_q_hist_buckets = arg_parse_uint(&arg);
950 else if (arg_match(&arg, &rate_hist_n, argi))
951 global->show_rate_hist_buckets = arg_parse_uint(&arg);
952 else if (arg_match(&arg, &disable_warnings, argi))
953 global->disable_warnings = 1;
954 else if (arg_match(&arg, &disable_warning_prompt, argi))
955 global->disable_warning_prompt = 1;
961 /* DWIM: Assume the user meant passes=2 if pass=2 is specified */
962 if (global->pass > global->passes) {
963 warn("Assuming --pass=%d implies --passes=%d\n", global->pass,
965 global->passes = global->pass;
968 /* Validate global config */
969 if (global->passes == 0) {
970 #if CONFIG_VP9_ENCODER
971 // Make default VP9 passes = 2 until there is a better quality 1-pass
973 if (global->codec != NULL && global->codec->name != NULL)
974 global->passes = (strcmp(global->codec->name, "vp9") == 0 &&
975 global->deadline != VPX_DL_REALTIME)
983 if (global->deadline == VPX_DL_REALTIME && global->passes > 1) {
984 warn("Enforcing one-pass encoding in realtime mode\n");
989 static struct stream_state *new_stream(struct VpxEncoderConfig *global,
990 struct stream_state *prev) {
991 struct stream_state *stream;
993 stream = calloc(1, sizeof(*stream));
994 if (stream == NULL) {
995 fatal("Failed to allocate new stream.");
999 memcpy(stream, prev, sizeof(*stream));
1001 prev->next = stream;
1003 vpx_codec_err_t res;
1005 /* Populate encoder configuration */
1006 res = vpx_codec_enc_config_default(global->codec->codec_interface(),
1007 &stream->config.cfg, global->usage);
1008 if (res) fatal("Failed to get config: %s\n", vpx_codec_err_to_string(res));
1010 /* Change the default timebase to a high enough value so that the
1011 * encoder will always create strictly increasing timestamps.
1013 stream->config.cfg.g_timebase.den = 1000;
1015 /* Never use the library's default resolution, require it be parsed
1016 * from the file or set on the command line.
1018 stream->config.cfg.g_w = 0;
1019 stream->config.cfg.g_h = 0;
1021 /* Initialize remaining stream parameters */
1022 stream->config.write_webm = 1;
1024 stream->config.stereo_fmt = STEREO_FORMAT_MONO;
1025 stream->webm_ctx.last_pts_ns = -1;
1026 stream->webm_ctx.writer = NULL;
1027 stream->webm_ctx.segment = NULL;
1030 /* Allows removal of the application version from the EBML tags */
1031 stream->webm_ctx.debug = global->debug;
1033 /* Default lag_in_frames is 0 in realtime mode CBR mode*/
1034 if (global->deadline == VPX_DL_REALTIME &&
1035 stream->config.cfg.rc_end_usage == 1)
1036 stream->config.cfg.g_lag_in_frames = 0;
1039 /* Output files must be specified for each stream */
1040 stream->config.out_fn = NULL;
1042 stream->next = NULL;
1046 static int parse_stream_params(struct VpxEncoderConfig *global,
1047 struct stream_state *stream, char **argv) {
1048 char **argi, **argj;
1050 static const arg_def_t **ctrl_args = no_args;
1051 static const int *ctrl_args_map = NULL;
1052 struct stream_config *config = &stream->config;
1053 int eos_mark_found = 0;
1054 #if CONFIG_VP9_HIGHBITDEPTH
1055 int test_16bit_internal = 0;
1058 // Handle codec specific options
1060 #if CONFIG_VP8_ENCODER
1061 } else if (strcmp(global->codec->name, "vp8") == 0) {
1062 ctrl_args = vp8_args;
1063 ctrl_args_map = vp8_arg_ctrl_map;
1065 #if CONFIG_VP9_ENCODER
1066 } else if (strcmp(global->codec->name, "vp9") == 0) {
1067 ctrl_args = vp9_args;
1068 ctrl_args_map = vp9_arg_ctrl_map;
1072 for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step) {
1075 /* Once we've found an end-of-stream marker (--) we want to continue
1076 * shifting arguments but not consuming them.
1078 if (eos_mark_found) {
1081 } else if (!strcmp(*argj, "--")) {
1086 if (arg_match(&arg, &outputfile, argi)) {
1087 config->out_fn = arg.val;
1088 } else if (arg_match(&arg, &fpf_name, argi)) {
1089 config->stats_fn = arg.val;
1090 #if CONFIG_FP_MB_STATS
1091 } else if (arg_match(&arg, &fpmbf_name, argi)) {
1092 config->fpmb_stats_fn = arg.val;
1094 } else if (arg_match(&arg, &use_webm, argi)) {
1096 config->write_webm = 1;
1098 die("Error: --webm specified but webm is disabled.");
1100 } else if (arg_match(&arg, &use_ivf, argi)) {
1101 config->write_webm = 0;
1102 } else if (arg_match(&arg, &threads, argi)) {
1103 config->cfg.g_threads = arg_parse_uint(&arg);
1104 } else if (arg_match(&arg, &profile, argi)) {
1105 config->cfg.g_profile = arg_parse_uint(&arg);
1106 } else if (arg_match(&arg, &width, argi)) {
1107 config->cfg.g_w = arg_parse_uint(&arg);
1108 } else if (arg_match(&arg, &height, argi)) {
1109 config->cfg.g_h = arg_parse_uint(&arg);
1110 #if CONFIG_VP9_HIGHBITDEPTH
1111 } else if (arg_match(&arg, &bitdeptharg, argi)) {
1112 config->cfg.g_bit_depth = arg_parse_enum_or_int(&arg);
1113 } else if (arg_match(&arg, &inbitdeptharg, argi)) {
1114 config->cfg.g_input_bit_depth = arg_parse_uint(&arg);
1117 } else if (arg_match(&arg, &stereo_mode, argi)) {
1118 config->stereo_fmt = arg_parse_enum_or_int(&arg);
1120 } else if (arg_match(&arg, &timebase, argi)) {
1121 config->cfg.g_timebase = arg_parse_rational(&arg);
1122 validate_positive_rational(arg.name, &config->cfg.g_timebase);
1123 } else if (arg_match(&arg, &error_resilient, argi)) {
1124 config->cfg.g_error_resilient = arg_parse_uint(&arg);
1125 } else if (arg_match(&arg, &end_usage, argi)) {
1126 config->cfg.rc_end_usage = arg_parse_enum_or_int(&arg);
1127 } else if (arg_match(&arg, &lag_in_frames, argi)) {
1128 config->cfg.g_lag_in_frames = arg_parse_uint(&arg);
1129 if (global->deadline == VPX_DL_REALTIME &&
1130 config->cfg.rc_end_usage == VPX_CBR &&
1131 config->cfg.g_lag_in_frames != 0) {
1132 warn("non-zero %s option ignored in realtime CBR mode.\n", arg.name);
1133 config->cfg.g_lag_in_frames = 0;
1135 } else if (arg_match(&arg, &dropframe_thresh, argi)) {
1136 config->cfg.rc_dropframe_thresh = arg_parse_uint(&arg);
1137 } else if (arg_match(&arg, &resize_allowed, argi)) {
1138 config->cfg.rc_resize_allowed = arg_parse_uint(&arg);
1139 } else if (arg_match(&arg, &resize_width, argi)) {
1140 config->cfg.rc_scaled_width = arg_parse_uint(&arg);
1141 } else if (arg_match(&arg, &resize_height, argi)) {
1142 config->cfg.rc_scaled_height = arg_parse_uint(&arg);
1143 } else if (arg_match(&arg, &resize_up_thresh, argi)) {
1144 config->cfg.rc_resize_up_thresh = arg_parse_uint(&arg);
1145 } else if (arg_match(&arg, &resize_down_thresh, argi)) {
1146 config->cfg.rc_resize_down_thresh = arg_parse_uint(&arg);
1147 } else if (arg_match(&arg, &end_usage, argi)) {
1148 config->cfg.rc_end_usage = arg_parse_enum_or_int(&arg);
1149 } else if (arg_match(&arg, &target_bitrate, argi)) {
1150 config->cfg.rc_target_bitrate = arg_parse_uint(&arg);
1151 } else if (arg_match(&arg, &min_quantizer, argi)) {
1152 config->cfg.rc_min_quantizer = arg_parse_uint(&arg);
1153 } else if (arg_match(&arg, &max_quantizer, argi)) {
1154 config->cfg.rc_max_quantizer = arg_parse_uint(&arg);
1155 } else if (arg_match(&arg, &undershoot_pct, argi)) {
1156 config->cfg.rc_undershoot_pct = arg_parse_uint(&arg);
1157 } else if (arg_match(&arg, &overshoot_pct, argi)) {
1158 config->cfg.rc_overshoot_pct = arg_parse_uint(&arg);
1159 } else if (arg_match(&arg, &buf_sz, argi)) {
1160 config->cfg.rc_buf_sz = arg_parse_uint(&arg);
1161 } else if (arg_match(&arg, &buf_initial_sz, argi)) {
1162 config->cfg.rc_buf_initial_sz = arg_parse_uint(&arg);
1163 } else if (arg_match(&arg, &buf_optimal_sz, argi)) {
1164 config->cfg.rc_buf_optimal_sz = arg_parse_uint(&arg);
1165 } else if (arg_match(&arg, &bias_pct, argi)) {
1166 config->cfg.rc_2pass_vbr_bias_pct = arg_parse_uint(&arg);
1167 if (global->passes < 2)
1168 warn("option %s ignored in one-pass mode.\n", arg.name);
1169 } else if (arg_match(&arg, &minsection_pct, argi)) {
1170 config->cfg.rc_2pass_vbr_minsection_pct = arg_parse_uint(&arg);
1172 if (global->passes < 2)
1173 warn("option %s ignored in one-pass mode.\n", arg.name);
1174 } else if (arg_match(&arg, &maxsection_pct, argi)) {
1175 config->cfg.rc_2pass_vbr_maxsection_pct = arg_parse_uint(&arg);
1177 if (global->passes < 2)
1178 warn("option %s ignored in one-pass mode.\n", arg.name);
1179 } else if (arg_match(&arg, &corpus_complexity, argi)) {
1180 config->cfg.rc_2pass_vbr_corpus_complexity = arg_parse_uint(&arg);
1182 if (global->passes < 2)
1183 warn("option %s ignored in one-pass mode.\n", arg.name);
1184 } else if (arg_match(&arg, &kf_min_dist, argi)) {
1185 config->cfg.kf_min_dist = arg_parse_uint(&arg);
1186 } else if (arg_match(&arg, &kf_max_dist, argi)) {
1187 config->cfg.kf_max_dist = arg_parse_uint(&arg);
1188 } else if (arg_match(&arg, &kf_disabled, argi)) {
1189 config->cfg.kf_mode = VPX_KF_DISABLED;
1190 #if CONFIG_VP9_HIGHBITDEPTH
1191 } else if (arg_match(&arg, &test16bitinternalarg, argi)) {
1192 if (strcmp(global->codec->name, "vp9") == 0) {
1193 test_16bit_internal = 1;
1198 for (i = 0; ctrl_args[i]; i++) {
1199 if (arg_match(&arg, ctrl_args[i], argi)) {
1203 /* Point either to the next free element or the first
1204 * instance of this control.
1206 for (j = 0; j < config->arg_ctrl_cnt; j++)
1207 if (ctrl_args_map != NULL &&
1208 config->arg_ctrls[j][0] == ctrl_args_map[i])
1212 assert(j < (int)ARG_CTRL_CNT_MAX);
1213 if (ctrl_args_map != NULL && j < (int)ARG_CTRL_CNT_MAX) {
1214 config->arg_ctrls[j][0] = ctrl_args_map[i];
1215 config->arg_ctrls[j][1] = arg_parse_enum_or_int(&arg);
1216 if (j == config->arg_ctrl_cnt) config->arg_ctrl_cnt++;
1223 #if CONFIG_VP9_HIGHBITDEPTH
1224 if (strcmp(global->codec->name, "vp9") == 0) {
1225 config->use_16bit_internal =
1226 test_16bit_internal | (config->cfg.g_profile > 1);
1229 return eos_mark_found;
1232 #define FOREACH_STREAM(func) \
1234 struct stream_state *stream; \
1235 for (stream = streams; stream; stream = stream->next) { \
1240 static void validate_stream_config(const struct stream_state *stream,
1241 const struct VpxEncoderConfig *global) {
1242 const struct stream_state *streami;
1245 if (!stream->config.cfg.g_w || !stream->config.cfg.g_h)
1247 "Stream %d: Specify stream dimensions with --width (-w) "
1248 " and --height (-h)",
1251 // Check that the codec bit depth is greater than the input bit depth.
1252 if (stream->config.cfg.g_input_bit_depth >
1253 (unsigned int)stream->config.cfg.g_bit_depth) {
1254 fatal("Stream %d: codec bit depth (%d) less than input bit depth (%d)",
1255 stream->index, (int)stream->config.cfg.g_bit_depth,
1256 stream->config.cfg.g_input_bit_depth);
1259 for (streami = stream; streami; streami = streami->next) {
1260 /* All streams require output files */
1261 if (!streami->config.out_fn)
1262 fatal("Stream %d: Output file is required (specify with -o)",
1265 /* Check for two streams outputting to the same file */
1266 if (streami != stream) {
1267 const char *a = stream->config.out_fn;
1268 const char *b = streami->config.out_fn;
1269 if (!strcmp(a, b) && strcmp(a, "/dev/null") && strcmp(a, ":nul"))
1270 fatal("Stream %d: duplicate output file (from stream %d)",
1271 streami->index, stream->index);
1274 /* Check for two streams sharing a stats file. */
1275 if (streami != stream) {
1276 const char *a = stream->config.stats_fn;
1277 const char *b = streami->config.stats_fn;
1278 if (a && b && !strcmp(a, b))
1279 fatal("Stream %d: duplicate stats file (from stream %d)",
1280 streami->index, stream->index);
1283 #if CONFIG_FP_MB_STATS
1284 /* Check for two streams sharing a mb stats file. */
1285 if (streami != stream) {
1286 const char *a = stream->config.fpmb_stats_fn;
1287 const char *b = streami->config.fpmb_stats_fn;
1288 if (a && b && !strcmp(a, b))
1289 fatal("Stream %d: duplicate mb stats file (from stream %d)",
1290 streami->index, stream->index);
1296 static void set_stream_dimensions(struct stream_state *stream, unsigned int w,
1298 if (!stream->config.cfg.g_w) {
1299 if (!stream->config.cfg.g_h)
1300 stream->config.cfg.g_w = w;
1302 stream->config.cfg.g_w = w * stream->config.cfg.g_h / h;
1304 if (!stream->config.cfg.g_h) {
1305 stream->config.cfg.g_h = h * stream->config.cfg.g_w / w;
1309 static const char *file_type_to_string(enum VideoFileType t) {
1311 case FILE_TYPE_RAW: return "RAW";
1312 case FILE_TYPE_Y4M: return "Y4M";
1313 default: return "Other";
1317 static const char *image_format_to_string(vpx_img_fmt_t f) {
1319 case VPX_IMG_FMT_I420: return "I420";
1320 case VPX_IMG_FMT_I422: return "I422";
1321 case VPX_IMG_FMT_I444: return "I444";
1322 case VPX_IMG_FMT_I440: return "I440";
1323 case VPX_IMG_FMT_YV12: return "YV12";
1324 case VPX_IMG_FMT_I42016: return "I42016";
1325 case VPX_IMG_FMT_I42216: return "I42216";
1326 case VPX_IMG_FMT_I44416: return "I44416";
1327 case VPX_IMG_FMT_I44016: return "I44016";
1328 default: return "Other";
1332 static void show_stream_config(struct stream_state *stream,
1333 struct VpxEncoderConfig *global,
1334 struct VpxInputContext *input) {
1335 #define SHOW(field) \
1336 fprintf(stderr, " %-28s = %d\n", #field, stream->config.cfg.field)
1338 if (stream->index == 0) {
1339 fprintf(stderr, "Codec: %s\n",
1340 vpx_codec_iface_name(global->codec->codec_interface()));
1341 fprintf(stderr, "Source file: %s File Type: %s Format: %s\n",
1342 input->filename, file_type_to_string(input->file_type),
1343 image_format_to_string(input->fmt));
1345 if (stream->next || stream->index)
1346 fprintf(stderr, "\nStream Index: %d\n", stream->index);
1347 fprintf(stderr, "Destination file: %s\n", stream->config.out_fn);
1348 fprintf(stderr, "Encoder parameters:\n");
1356 SHOW(g_input_bit_depth);
1357 SHOW(g_timebase.num);
1358 SHOW(g_timebase.den);
1359 SHOW(g_error_resilient);
1361 SHOW(g_lag_in_frames);
1362 SHOW(rc_dropframe_thresh);
1363 SHOW(rc_resize_allowed);
1364 SHOW(rc_scaled_width);
1365 SHOW(rc_scaled_height);
1366 SHOW(rc_resize_up_thresh);
1367 SHOW(rc_resize_down_thresh);
1369 SHOW(rc_target_bitrate);
1370 SHOW(rc_min_quantizer);
1371 SHOW(rc_max_quantizer);
1372 SHOW(rc_undershoot_pct);
1373 SHOW(rc_overshoot_pct);
1375 SHOW(rc_buf_initial_sz);
1376 SHOW(rc_buf_optimal_sz);
1377 SHOW(rc_2pass_vbr_bias_pct);
1378 SHOW(rc_2pass_vbr_minsection_pct);
1379 SHOW(rc_2pass_vbr_maxsection_pct);
1380 SHOW(rc_2pass_vbr_corpus_complexity);
1386 static void open_output_file(struct stream_state *stream,
1387 struct VpxEncoderConfig *global,
1388 const struct VpxRational *pixel_aspect_ratio) {
1389 const char *fn = stream->config.out_fn;
1390 const struct vpx_codec_enc_cfg *const cfg = &stream->config.cfg;
1392 if (cfg->g_pass == VPX_RC_FIRST_PASS) return;
1394 stream->file = strcmp(fn, "-") ? fopen(fn, "wb") : set_binary_mode(stdout);
1396 if (!stream->file) fatal("Failed to open output file");
1398 if (stream->config.write_webm && fseek(stream->file, 0, SEEK_CUR))
1399 fatal("WebM output to pipes not supported.");
1402 if (stream->config.write_webm) {
1403 stream->webm_ctx.stream = stream->file;
1404 write_webm_file_header(&stream->webm_ctx, cfg, stream->config.stereo_fmt,
1405 global->codec->fourcc, pixel_aspect_ratio);
1408 (void)pixel_aspect_ratio;
1411 if (!stream->config.write_webm) {
1412 ivf_write_file_header(stream->file, cfg, global->codec->fourcc, 0);
1416 static void close_output_file(struct stream_state *stream,
1417 unsigned int fourcc) {
1418 const struct vpx_codec_enc_cfg *const cfg = &stream->config.cfg;
1420 if (cfg->g_pass == VPX_RC_FIRST_PASS) return;
1423 if (stream->config.write_webm) {
1424 write_webm_file_footer(&stream->webm_ctx);
1428 if (!stream->config.write_webm) {
1429 if (!fseek(stream->file, 0, SEEK_SET))
1430 ivf_write_file_header(stream->file, &stream->config.cfg, fourcc,
1431 stream->frames_out);
1434 fclose(stream->file);
1437 static void setup_pass(struct stream_state *stream,
1438 struct VpxEncoderConfig *global, int pass) {
1439 if (stream->config.stats_fn) {
1440 if (!stats_open_file(&stream->stats, stream->config.stats_fn, pass))
1441 fatal("Failed to open statistics store");
1443 if (!stats_open_mem(&stream->stats, pass))
1444 fatal("Failed to open statistics store");
1447 #if CONFIG_FP_MB_STATS
1448 if (stream->config.fpmb_stats_fn) {
1449 if (!stats_open_file(&stream->fpmb_stats, stream->config.fpmb_stats_fn,
1451 fatal("Failed to open mb statistics store");
1453 if (!stats_open_mem(&stream->fpmb_stats, pass))
1454 fatal("Failed to open mb statistics store");
1458 stream->config.cfg.g_pass = global->passes == 2
1459 ? pass ? VPX_RC_LAST_PASS : VPX_RC_FIRST_PASS
1462 stream->config.cfg.rc_twopass_stats_in = stats_get(&stream->stats);
1463 #if CONFIG_FP_MB_STATS
1464 stream->config.cfg.rc_firstpass_mb_stats_in =
1465 stats_get(&stream->fpmb_stats);
1469 stream->cx_time = 0;
1471 stream->frames_out = 0;
1474 static void initialize_encoder(struct stream_state *stream,
1475 struct VpxEncoderConfig *global) {
1479 flags |= global->show_psnr ? VPX_CODEC_USE_PSNR : 0;
1480 flags |= global->out_part ? VPX_CODEC_USE_OUTPUT_PARTITION : 0;
1481 #if CONFIG_VP9_HIGHBITDEPTH
1482 flags |= stream->config.use_16bit_internal ? VPX_CODEC_USE_HIGHBITDEPTH : 0;
1485 /* Construct Encoder Context */
1486 vpx_codec_enc_init(&stream->encoder, global->codec->codec_interface(),
1487 &stream->config.cfg, flags);
1488 ctx_exit_on_error(&stream->encoder, "Failed to initialize encoder");
1490 /* Note that we bypass the vpx_codec_control wrapper macro because
1491 * we're being clever to store the control IDs in an array. Real
1492 * applications will want to make use of the enumerations directly
1494 for (i = 0; i < stream->config.arg_ctrl_cnt; i++) {
1495 int ctrl = stream->config.arg_ctrls[i][0];
1496 int value = stream->config.arg_ctrls[i][1];
1497 if (vpx_codec_control_(&stream->encoder, ctrl, value))
1498 fprintf(stderr, "Error: Tried to set control %d = %d\n", ctrl, value);
1500 ctx_exit_on_error(&stream->encoder, "Failed to control codec");
1504 if (global->test_decode != TEST_DECODE_OFF) {
1505 const VpxInterface *decoder = get_vpx_decoder_by_name(global->codec->name);
1506 vpx_codec_dec_init(&stream->decoder, decoder->codec_interface(), NULL, 0);
1511 static void encode_frame(struct stream_state *stream,
1512 struct VpxEncoderConfig *global, struct vpx_image *img,
1513 unsigned int frames_in) {
1514 vpx_codec_pts_t frame_start, next_frame_start;
1515 struct vpx_codec_enc_cfg *cfg = &stream->config.cfg;
1516 struct vpx_usec_timer timer;
1519 (cfg->g_timebase.den * (int64_t)(frames_in - 1) * global->framerate.den) /
1520 cfg->g_timebase.num / global->framerate.num;
1522 (cfg->g_timebase.den * (int64_t)(frames_in)*global->framerate.den) /
1523 cfg->g_timebase.num / global->framerate.num;
1525 /* Scale if necessary */
1526 #if CONFIG_VP9_HIGHBITDEPTH
1528 if ((img->fmt & VPX_IMG_FMT_HIGHBITDEPTH) &&
1529 (img->d_w != cfg->g_w || img->d_h != cfg->g_h)) {
1530 if (img->fmt != VPX_IMG_FMT_I42016) {
1531 fprintf(stderr, "%s can only scale 4:2:0 inputs\n", exec_name);
1537 vpx_img_alloc(NULL, VPX_IMG_FMT_I42016, cfg->g_w, cfg->g_h, 16);
1540 (uint16_t *)img->planes[VPX_PLANE_Y], img->stride[VPX_PLANE_Y] / 2,
1541 (uint16_t *)img->planes[VPX_PLANE_U], img->stride[VPX_PLANE_U] / 2,
1542 (uint16_t *)img->planes[VPX_PLANE_V], img->stride[VPX_PLANE_V] / 2,
1543 img->d_w, img->d_h, (uint16_t *)stream->img->planes[VPX_PLANE_Y],
1544 stream->img->stride[VPX_PLANE_Y] / 2,
1545 (uint16_t *)stream->img->planes[VPX_PLANE_U],
1546 stream->img->stride[VPX_PLANE_U] / 2,
1547 (uint16_t *)stream->img->planes[VPX_PLANE_V],
1548 stream->img->stride[VPX_PLANE_V] / 2, stream->img->d_w,
1549 stream->img->d_h, kFilterBox);
1552 stream->encoder.err = 1;
1553 ctx_exit_on_error(&stream->encoder,
1554 "Stream %d: Failed to encode frame.\n"
1555 "Scaling disabled in this configuration. \n"
1556 "To enable, configure with --enable-libyuv\n",
1562 if (img && (img->d_w != cfg->g_w || img->d_h != cfg->g_h)) {
1563 if (img->fmt != VPX_IMG_FMT_I420 && img->fmt != VPX_IMG_FMT_YV12) {
1564 fprintf(stderr, "%s can only scale 4:2:0 8bpp inputs\n", exec_name);
1570 vpx_img_alloc(NULL, VPX_IMG_FMT_I420, cfg->g_w, cfg->g_h, 16);
1572 img->planes[VPX_PLANE_Y], img->stride[VPX_PLANE_Y],
1573 img->planes[VPX_PLANE_U], img->stride[VPX_PLANE_U],
1574 img->planes[VPX_PLANE_V], img->stride[VPX_PLANE_V], img->d_w, img->d_h,
1575 stream->img->planes[VPX_PLANE_Y], stream->img->stride[VPX_PLANE_Y],
1576 stream->img->planes[VPX_PLANE_U], stream->img->stride[VPX_PLANE_U],
1577 stream->img->planes[VPX_PLANE_V], stream->img->stride[VPX_PLANE_V],
1578 stream->img->d_w, stream->img->d_h, kFilterBox);
1581 stream->encoder.err = 1;
1582 ctx_exit_on_error(&stream->encoder,
1583 "Stream %d: Failed to encode frame.\n"
1584 "Scaling disabled in this configuration. \n"
1585 "To enable, configure with --enable-libyuv\n",
1590 vpx_usec_timer_start(&timer);
1591 vpx_codec_encode(&stream->encoder, img, frame_start,
1592 (unsigned long)(next_frame_start - frame_start), 0,
1594 vpx_usec_timer_mark(&timer);
1595 stream->cx_time += vpx_usec_timer_elapsed(&timer);
1596 ctx_exit_on_error(&stream->encoder, "Stream %d: Failed to encode frame",
1600 static void update_quantizer_histogram(struct stream_state *stream) {
1601 if (stream->config.cfg.g_pass != VPX_RC_FIRST_PASS) {
1604 vpx_codec_control(&stream->encoder, VP8E_GET_LAST_QUANTIZER_64, &q);
1605 ctx_exit_on_error(&stream->encoder, "Failed to read quantizer");
1606 stream->counts[q]++;
1610 static void get_cx_data(struct stream_state *stream,
1611 struct VpxEncoderConfig *global, int *got_data) {
1612 const vpx_codec_cx_pkt_t *pkt;
1613 const struct vpx_codec_enc_cfg *cfg = &stream->config.cfg;
1614 vpx_codec_iter_t iter = NULL;
1617 while ((pkt = vpx_codec_get_cx_data(&stream->encoder, &iter))) {
1618 static size_t fsize = 0;
1619 static FileOffset ivf_header_pos = 0;
1621 switch (pkt->kind) {
1622 case VPX_CODEC_CX_FRAME_PKT:
1623 if (!(pkt->data.frame.flags & VPX_FRAME_IS_FRAGMENT)) {
1624 stream->frames_out++;
1627 fprintf(stderr, " %6luF", (unsigned long)pkt->data.frame.sz);
1629 update_rate_histogram(stream->rate_hist, cfg, pkt);
1631 if (stream->config.write_webm) {
1632 write_webm_block(&stream->webm_ctx, cfg, pkt);
1635 if (!stream->config.write_webm) {
1636 if (pkt->data.frame.partition_id <= 0) {
1637 ivf_header_pos = ftello(stream->file);
1638 fsize = pkt->data.frame.sz;
1640 ivf_write_frame_header(stream->file, pkt->data.frame.pts, fsize);
1642 fsize += pkt->data.frame.sz;
1644 if (!(pkt->data.frame.flags & VPX_FRAME_IS_FRAGMENT)) {
1645 const FileOffset currpos = ftello(stream->file);
1646 fseeko(stream->file, ivf_header_pos, SEEK_SET);
1647 ivf_write_frame_size(stream->file, fsize);
1648 fseeko(stream->file, currpos, SEEK_SET);
1652 (void)fwrite(pkt->data.frame.buf, 1, pkt->data.frame.sz,
1655 stream->nbytes += pkt->data.raw.sz;
1659 if (global->test_decode != TEST_DECODE_OFF && !stream->mismatch_seen) {
1660 vpx_codec_decode(&stream->decoder, pkt->data.frame.buf,
1661 (unsigned int)pkt->data.frame.sz, NULL, 0);
1662 if (stream->decoder.err) {
1663 warn_or_exit_on_error(&stream->decoder,
1664 global->test_decode == TEST_DECODE_FATAL,
1665 "Failed to decode frame %d in stream %d",
1666 stream->frames_out + 1, stream->index);
1667 stream->mismatch_seen = stream->frames_out + 1;
1672 case VPX_CODEC_STATS_PKT:
1673 stream->frames_out++;
1674 stats_write(&stream->stats, pkt->data.twopass_stats.buf,
1675 pkt->data.twopass_stats.sz);
1676 stream->nbytes += pkt->data.raw.sz;
1678 #if CONFIG_FP_MB_STATS
1679 case VPX_CODEC_FPMB_STATS_PKT:
1680 stats_write(&stream->fpmb_stats, pkt->data.firstpass_mb_stats.buf,
1681 pkt->data.firstpass_mb_stats.sz);
1682 stream->nbytes += pkt->data.raw.sz;
1685 case VPX_CODEC_PSNR_PKT:
1687 if (global->show_psnr) {
1690 stream->psnr_sse_total += pkt->data.psnr.sse[0];
1691 stream->psnr_samples_total += pkt->data.psnr.samples[0];
1692 for (i = 0; i < 4; i++) {
1694 fprintf(stderr, "%.3f ", pkt->data.psnr.psnr[i]);
1695 stream->psnr_totals[i] += pkt->data.psnr.psnr[i];
1697 stream->psnr_count++;
1706 static void show_psnr(struct stream_state *stream, double peak) {
1710 if (!stream->psnr_count) return;
1712 fprintf(stderr, "Stream %d PSNR (Overall/Avg/Y/U/V)", stream->index);
1713 ovpsnr = sse_to_psnr((double)stream->psnr_samples_total, peak,
1714 (double)stream->psnr_sse_total);
1715 fprintf(stderr, " %.3f", ovpsnr);
1717 for (i = 0; i < 4; i++) {
1718 fprintf(stderr, " %.3f", stream->psnr_totals[i] / stream->psnr_count);
1720 fprintf(stderr, "\n");
1723 static float usec_to_fps(uint64_t usec, unsigned int frames) {
1724 return (float)(usec > 0 ? frames * 1000000.0 / (float)usec : 0);
1727 static void test_decode(struct stream_state *stream,
1728 enum TestDecodeFatality fatal,
1729 const VpxInterface *codec) {
1730 vpx_image_t enc_img, dec_img;
1732 if (stream->mismatch_seen) return;
1734 /* Get the internal reference frame */
1735 if (strcmp(codec->name, "vp8") == 0) {
1736 struct vpx_ref_frame ref_enc, ref_dec;
1739 width = (stream->config.cfg.g_w + 15) & ~15;
1740 height = (stream->config.cfg.g_h + 15) & ~15;
1741 vpx_img_alloc(&ref_enc.img, VPX_IMG_FMT_I420, width, height, 1);
1742 enc_img = ref_enc.img;
1743 vpx_img_alloc(&ref_dec.img, VPX_IMG_FMT_I420, width, height, 1);
1744 dec_img = ref_dec.img;
1746 ref_enc.frame_type = VP8_LAST_FRAME;
1747 ref_dec.frame_type = VP8_LAST_FRAME;
1748 vpx_codec_control(&stream->encoder, VP8_COPY_REFERENCE, &ref_enc);
1749 vpx_codec_control(&stream->decoder, VP8_COPY_REFERENCE, &ref_dec);
1751 struct vp9_ref_frame ref_enc, ref_dec;
1755 vpx_codec_control(&stream->encoder, VP9_GET_REFERENCE, &ref_enc);
1756 enc_img = ref_enc.img;
1757 vpx_codec_control(&stream->decoder, VP9_GET_REFERENCE, &ref_dec);
1758 dec_img = ref_dec.img;
1759 #if CONFIG_VP9_HIGHBITDEPTH
1760 if ((enc_img.fmt & VPX_IMG_FMT_HIGHBITDEPTH) !=
1761 (dec_img.fmt & VPX_IMG_FMT_HIGHBITDEPTH)) {
1762 if (enc_img.fmt & VPX_IMG_FMT_HIGHBITDEPTH) {
1763 vpx_img_alloc(&enc_img, enc_img.fmt - VPX_IMG_FMT_HIGHBITDEPTH,
1764 enc_img.d_w, enc_img.d_h, 16);
1765 vpx_img_truncate_16_to_8(&enc_img, &ref_enc.img);
1767 if (dec_img.fmt & VPX_IMG_FMT_HIGHBITDEPTH) {
1768 vpx_img_alloc(&dec_img, dec_img.fmt - VPX_IMG_FMT_HIGHBITDEPTH,
1769 dec_img.d_w, dec_img.d_h, 16);
1770 vpx_img_truncate_16_to_8(&dec_img, &ref_dec.img);
1775 ctx_exit_on_error(&stream->encoder, "Failed to get encoder reference frame");
1776 ctx_exit_on_error(&stream->decoder, "Failed to get decoder reference frame");
1778 if (!compare_img(&enc_img, &dec_img)) {
1779 int y[4], u[4], v[4];
1780 #if CONFIG_VP9_HIGHBITDEPTH
1781 if (enc_img.fmt & VPX_IMG_FMT_HIGHBITDEPTH) {
1782 find_mismatch_high(&enc_img, &dec_img, y, u, v);
1784 find_mismatch(&enc_img, &dec_img, y, u, v);
1787 find_mismatch(&enc_img, &dec_img, y, u, v);
1789 stream->decoder.err = 1;
1790 warn_or_exit_on_error(&stream->decoder, fatal == TEST_DECODE_FATAL,
1791 "Stream %d: Encode/decode mismatch on frame %d at"
1792 " Y[%d, %d] {%d/%d},"
1793 " U[%d, %d] {%d/%d},"
1794 " V[%d, %d] {%d/%d}",
1795 stream->index, stream->frames_out, y[0], y[1], y[2],
1796 y[3], u[0], u[1], u[2], u[3], v[0], v[1], v[2], v[3]);
1797 stream->mismatch_seen = stream->frames_out;
1800 vpx_img_free(&enc_img);
1801 vpx_img_free(&dec_img);
1804 static void print_time(const char *label, int64_t etl) {
1811 etl -= hours * 3600;
1816 fprintf(stderr, "[%3s %2" PRId64 ":%02" PRId64 ":%02" PRId64 "] ", label,
1819 fprintf(stderr, "[%3s unknown] ", label);
1823 int main(int argc, const char **argv_) {
1826 #if CONFIG_VP9_HIGHBITDEPTH
1827 vpx_image_t raw_shift;
1828 int allocated_raw_shift = 0;
1829 int use_16bit_internal = 0;
1830 int input_shift = 0;
1832 int frame_avail, got_data;
1834 struct VpxInputContext input;
1835 struct VpxEncoderConfig global;
1836 struct stream_state *streams = NULL;
1837 char **argv, **argi;
1838 uint64_t cx_time = 0;
1842 memset(&input, 0, sizeof(input));
1843 exec_name = argv_[0];
1845 /* Setup default input stream settings */
1846 input.framerate.numerator = 30;
1847 input.framerate.denominator = 1;
1848 input.only_i420 = 1;
1849 input.bit_depth = 0;
1851 /* First parse the global configuration values, because we want to apply
1852 * other parameters on top of the default configuration provided by the
1855 argv = argv_dup(argc - 1, argv_ + 1);
1856 parse_global_config(&global, argv);
1858 if (argc < 3) usage_exit();
1860 switch (global.color_type) {
1861 case I420: input.fmt = VPX_IMG_FMT_I420; break;
1862 case I422: input.fmt = VPX_IMG_FMT_I422; break;
1863 case I444: input.fmt = VPX_IMG_FMT_I444; break;
1864 case I440: input.fmt = VPX_IMG_FMT_I440; break;
1865 case YV12: input.fmt = VPX_IMG_FMT_YV12; break;
1869 /* Now parse each stream's parameters. Using a local scope here
1870 * due to the use of 'stream' as loop variable in FOREACH_STREAM
1873 struct stream_state *stream = NULL;
1876 stream = new_stream(&global, stream);
1878 if (!streams) streams = stream;
1879 } while (parse_stream_params(&global, stream, argv));
1882 /* Check for unrecognized options */
1883 for (argi = argv; *argi; argi++)
1884 if (argi[0][0] == '-' && argi[0][1])
1885 die("Error: Unrecognized option %s\n", *argi);
1887 FOREACH_STREAM(check_encoder_config(global.disable_warning_prompt, &global,
1888 &stream->config.cfg););
1890 /* Handle non-option arguments */
1891 input.filename = argv[0];
1893 if (!input.filename) {
1894 fprintf(stderr, "No input file specified!\n");
1898 /* Decide if other chroma subsamplings than 4:2:0 are supported */
1899 if (global.codec->fourcc == VP9_FOURCC) input.only_i420 = 0;
1901 for (pass = global.pass ? global.pass - 1 : 0; pass < global.passes; pass++) {
1902 int frames_in = 0, seen_frames = 0;
1903 int64_t estimated_time_left = -1;
1904 int64_t average_rate = -1;
1905 int64_t lagged_count = 0;
1907 open_input_file(&input);
1909 /* If the input file doesn't specify its w/h (raw files), try to get
1910 * the data from the first stream's configuration.
1912 if (!input.width || !input.height) {
1914 if (stream->config.cfg.g_w && stream->config.cfg.g_h) {
1915 input.width = stream->config.cfg.g_w;
1916 input.height = stream->config.cfg.g_h;
1922 /* Update stream configurations from the input file's parameters */
1923 if (!input.width || !input.height)
1925 "Specify stream dimensions with --width (-w) "
1926 " and --height (-h)");
1928 /* If input file does not specify bit-depth but input-bit-depth parameter
1929 * exists, assume that to be the input bit-depth. However, if the
1930 * input-bit-depth paramter does not exist, assume the input bit-depth
1931 * to be the same as the codec bit-depth.
1933 if (!input.bit_depth) {
1935 if (stream->config.cfg.g_input_bit_depth)
1936 input.bit_depth = stream->config.cfg.g_input_bit_depth;
1938 input.bit_depth = stream->config.cfg.g_input_bit_depth =
1939 (int)stream->config.cfg.g_bit_depth;
1941 if (input.bit_depth > 8) input.fmt |= VPX_IMG_FMT_HIGHBITDEPTH;
1944 { stream->config.cfg.g_input_bit_depth = input.bit_depth; });
1947 FOREACH_STREAM(set_stream_dimensions(stream, input.width, input.height));
1948 FOREACH_STREAM(validate_stream_config(stream, &global));
1950 /* Ensure that --passes and --pass are consistent. If --pass is set and
1951 * --passes=2, ensure --fpf was set.
1953 if (global.pass && global.passes == 2)
1955 if (!stream->config.stats_fn)
1956 die("Stream %d: Must specify --fpf when --pass=%d"
1957 " and --passes=2\n",
1958 stream->index, global.pass);
1963 if (stream->config.write_webm) {
1964 stream->config.write_webm = 0;
1966 "vpxenc was compiled without WebM container support."
1967 "Producing IVF output");
1972 /* Use the frame rate from the file only if none was specified
1973 * on the command-line.
1975 if (!global.have_framerate) {
1976 global.framerate.num = input.framerate.numerator;
1977 global.framerate.den = input.framerate.denominator;
1978 FOREACH_STREAM(stream->config.cfg.g_timebase.den = global.framerate.num;
1979 stream->config.cfg.g_timebase.num = global.framerate.den);
1982 /* Show configuration */
1983 if (global.verbose && pass == 0)
1984 FOREACH_STREAM(show_stream_config(stream, &global, &input));
1986 if (pass == (global.pass ? global.pass - 1 : 0)) {
1987 if (input.file_type == FILE_TYPE_Y4M)
1988 /*The Y4M reader does its own allocation.
1989 Just initialize this here to avoid problems if we never read any
1991 memset(&raw, 0, sizeof(raw));
1993 vpx_img_alloc(&raw, input.fmt, input.width, input.height, 32);
1995 FOREACH_STREAM(stream->rate_hist = init_rate_histogram(
1996 &stream->config.cfg, &global.framerate));
1999 FOREACH_STREAM(setup_pass(stream, &global, pass));
2001 open_output_file(stream, &global, &input.pixel_aspect_ratio));
2002 FOREACH_STREAM(initialize_encoder(stream, &global));
2004 #if CONFIG_VP9_HIGHBITDEPTH
2005 if (strcmp(global.codec->name, "vp9") == 0) {
2006 // Check to see if at least one stream uses 16 bit internal.
2007 // Currently assume that the bit_depths for all streams using
2008 // highbitdepth are the same.
2010 if (stream->config.use_16bit_internal) {
2011 use_16bit_internal = 1;
2013 if (stream->config.cfg.g_profile == 0) {
2016 input_shift = (int)stream->config.cfg.g_bit_depth -
2017 stream->config.cfg.g_input_bit_depth;
2026 while (frame_avail || got_data) {
2027 struct vpx_usec_timer timer;
2029 if (!global.limit || frames_in < global.limit) {
2030 frame_avail = read_frame(&input, &raw);
2032 if (frame_avail) frames_in++;
2034 frames_in > global.skip_frames ? frames_in - global.skip_frames : 0;
2036 if (!global.quiet) {
2037 float fps = usec_to_fps(cx_time, seen_frames);
2038 fprintf(stderr, "\rPass %d/%d ", pass + 1, global.passes);
2040 if (stream_cnt == 1)
2041 fprintf(stderr, "frame %4d/%-4d %7" PRId64 "B ", frames_in,
2042 streams->frames_out, (int64_t)streams->nbytes);
2044 fprintf(stderr, "frame %4d ", frames_in);
2046 fprintf(stderr, "%7" PRId64 " %s %.2f %s ",
2047 cx_time > 9999999 ? cx_time / 1000 : cx_time,
2048 cx_time > 9999999 ? "ms" : "us", fps >= 1.0 ? fps : fps * 60,
2049 fps >= 1.0 ? "fps" : "fpm");
2050 print_time("ETA", estimated_time_left);
2056 if (frames_in > global.skip_frames) {
2057 #if CONFIG_VP9_HIGHBITDEPTH
2058 vpx_image_t *frame_to_encode;
2059 if (input_shift || (use_16bit_internal && input.bit_depth == 8)) {
2060 assert(use_16bit_internal);
2061 // Input bit depth and stream bit depth do not match, so up
2062 // shift frame to stream bit depth
2063 if (!allocated_raw_shift) {
2064 vpx_img_alloc(&raw_shift, raw.fmt | VPX_IMG_FMT_HIGHBITDEPTH,
2065 input.width, input.height, 32);
2066 allocated_raw_shift = 1;
2068 vpx_img_upshift(&raw_shift, &raw, input_shift);
2069 frame_to_encode = &raw_shift;
2071 frame_to_encode = &raw;
2073 vpx_usec_timer_start(&timer);
2074 if (use_16bit_internal) {
2075 assert(frame_to_encode->fmt & VPX_IMG_FMT_HIGHBITDEPTH);
2077 if (stream->config.use_16bit_internal)
2078 encode_frame(stream, &global,
2079 frame_avail ? frame_to_encode : NULL, frames_in);
2084 assert((frame_to_encode->fmt & VPX_IMG_FMT_HIGHBITDEPTH) == 0);
2085 FOREACH_STREAM(encode_frame(stream, &global,
2086 frame_avail ? frame_to_encode : NULL,
2090 vpx_usec_timer_start(&timer);
2091 FOREACH_STREAM(encode_frame(stream, &global, frame_avail ? &raw : NULL,
2094 vpx_usec_timer_mark(&timer);
2095 cx_time += vpx_usec_timer_elapsed(&timer);
2097 FOREACH_STREAM(update_quantizer_histogram(stream));
2100 FOREACH_STREAM(get_cx_data(stream, &global, &got_data));
2102 if (!got_data && input.length && streams != NULL &&
2103 !streams->frames_out) {
2104 lagged_count = global.limit ? seen_frames : ftello(input.file);
2105 } else if (input.length) {
2110 const int64_t frame_in_lagged = (seen_frames - lagged_count) * 1000;
2112 rate = cx_time ? frame_in_lagged * (int64_t)1000000 / cx_time : 0;
2113 remaining = 1000 * (global.limit - global.skip_frames -
2114 seen_frames + lagged_count);
2116 const int64_t input_pos = ftello(input.file);
2117 const int64_t input_pos_lagged = input_pos - lagged_count;
2118 const int64_t limit = input.length;
2120 rate = cx_time ? input_pos_lagged * (int64_t)1000000 / cx_time : 0;
2121 remaining = limit - input_pos + lagged_count;
2125 (average_rate <= 0) ? rate : (average_rate * 7 + rate) / 8;
2126 estimated_time_left = average_rate ? remaining / average_rate : -1;
2129 if (got_data && global.test_decode != TEST_DECODE_OFF)
2130 FOREACH_STREAM(test_decode(stream, global.test_decode, global.codec));
2134 if (!global.quiet) fprintf(stderr, "\033[K");
2137 if (stream_cnt > 1) fprintf(stderr, "\n");
2139 if (!global.quiet) {
2140 FOREACH_STREAM(fprintf(
2142 "\rPass %d/%d frame %4d/%-4d %7" PRId64 "B %7" PRId64 "b/f %7" PRId64
2143 "b/s %7" PRId64 " %s (%.2f fps)\033[K\n",
2144 pass + 1, global.passes, frames_in, stream->frames_out,
2145 (int64_t)stream->nbytes,
2146 seen_frames ? (int64_t)(stream->nbytes * 8 / seen_frames) : 0,
2148 ? (int64_t)stream->nbytes * 8 * (int64_t)global.framerate.num /
2149 global.framerate.den / seen_frames
2151 stream->cx_time > 9999999 ? stream->cx_time / 1000 : stream->cx_time,
2152 stream->cx_time > 9999999 ? "ms" : "us",
2153 usec_to_fps(stream->cx_time, seen_frames)));
2156 if (global.show_psnr) {
2157 if (global.codec->fourcc == VP9_FOURCC) {
2159 show_psnr(stream, (1 << stream->config.cfg.g_input_bit_depth) - 1));
2161 FOREACH_STREAM(show_psnr(stream, 255.0));
2165 FOREACH_STREAM(vpx_codec_destroy(&stream->encoder));
2167 if (global.test_decode != TEST_DECODE_OFF) {
2168 FOREACH_STREAM(vpx_codec_destroy(&stream->decoder));
2171 close_input_file(&input);
2173 if (global.test_decode == TEST_DECODE_FATAL) {
2174 FOREACH_STREAM(res |= stream->mismatch_seen);
2176 FOREACH_STREAM(close_output_file(stream, global.codec->fourcc));
2178 FOREACH_STREAM(stats_close(&stream->stats, global.passes - 1));
2180 #if CONFIG_FP_MB_STATS
2181 FOREACH_STREAM(stats_close(&stream->fpmb_stats, global.passes - 1));
2184 if (global.pass) break;
2187 if (global.show_q_hist_buckets)
2189 show_q_histogram(stream->counts, global.show_q_hist_buckets));
2191 if (global.show_rate_hist_buckets)
2192 FOREACH_STREAM(show_rate_histogram(stream->rate_hist, &stream->config.cfg,
2193 global.show_rate_hist_buckets));
2194 FOREACH_STREAM(destroy_rate_histogram(stream->rate_hist));
2196 #if CONFIG_INTERNAL_STATS
2197 /* TODO(jkoleszar): This doesn't belong in this executable. Do it for now,
2198 * to match some existing utilities.
2200 if (!(global.pass == 1 && global.passes == 2))
2202 FILE *f = fopen("opsnr.stt", "a");
2203 if (stream->mismatch_seen) {
2204 fprintf(f, "First mismatch occurred in frame %d\n",
2205 stream->mismatch_seen);
2207 fprintf(f, "No mismatch detected in recon buffers\n");
2213 #if CONFIG_VP9_HIGHBITDEPTH
2214 if (allocated_raw_shift) vpx_img_free(&raw_shift);
2219 return res ? EXIT_FAILURE : EXIT_SUCCESS;