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 /* 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);
57 #define fread wrap_fread
59 static size_t wrap_fwrite(const void *ptr, size_t size, size_t nmemb,
61 return fwrite(ptr, size, nmemb, stream);
63 #define fwrite wrap_fwrite
65 static const char *exec_name;
67 static void warn_or_exit_on_errorv(vpx_codec_ctx_t *ctx, int fatal,
68 const char *s, va_list ap) {
70 const char *detail = vpx_codec_error_detail(ctx);
72 vfprintf(stderr, s, ap);
73 fprintf(stderr, ": %s\n", vpx_codec_error(ctx));
75 if (detail) fprintf(stderr, " %s\n", detail);
77 if (fatal) exit(EXIT_FAILURE);
81 static void ctx_exit_on_error(vpx_codec_ctx_t *ctx, const char *s, ...) {
85 warn_or_exit_on_errorv(ctx, 1, s, ap);
89 static void warn_or_exit_on_error(vpx_codec_ctx_t *ctx, int fatal,
94 warn_or_exit_on_errorv(ctx, fatal, s, ap);
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;
103 if (input_ctx->file_type == FILE_TYPE_Y4M) {
104 if (y4m_input_fetch_frame(y4m, f, img) < 1) return 0;
106 shortread = read_yuv_frame(input_ctx, img);
112 static int file_is_y4m(const char detect[4]) {
113 if (memcmp(detect, "YUV4", 4) == 0) {
119 static int fourcc_is_ivf(const char detect[4]) {
120 if (memcmp(detect, "DKIF", 4) == 0) {
126 static const arg_def_t debugmode =
127 ARG_DEF("D", "debug", 0, "Debug mode (makes output deterministic)");
128 static const arg_def_t outputfile =
129 ARG_DEF("o", "output", 1, "Output filename");
130 static const arg_def_t use_yv12 =
131 ARG_DEF(NULL, "yv12", 0, "Input file is YV12 ");
132 static const arg_def_t use_i420 =
133 ARG_DEF(NULL, "i420", 0, "Input file is I420 (default)");
134 static const arg_def_t use_i422 =
135 ARG_DEF(NULL, "i422", 0, "Input file is I422");
136 static const arg_def_t use_i444 =
137 ARG_DEF(NULL, "i444", 0, "Input file is I444");
138 static const arg_def_t use_i440 =
139 ARG_DEF(NULL, "i440", 0, "Input file is I440");
140 static const arg_def_t codecarg = ARG_DEF(NULL, "codec", 1, "Codec to use");
141 static const arg_def_t passes =
142 ARG_DEF("p", "passes", 1, "Number of passes (1/2)");
143 static const arg_def_t pass_arg =
144 ARG_DEF(NULL, "pass", 1, "Pass to execute (1/2)");
145 static const arg_def_t fpf_name =
146 ARG_DEF(NULL, "fpf", 1, "First pass statistics file name");
147 #if CONFIG_FP_MB_STATS
148 static const arg_def_t fpmbf_name =
149 ARG_DEF(NULL, "fpmbf", 1, "First pass block statistics file name");
151 static const arg_def_t limit =
152 ARG_DEF(NULL, "limit", 1, "Stop encoding after n input frames");
153 static const arg_def_t skip =
154 ARG_DEF(NULL, "skip", 1, "Skip the first n input frames");
155 static const arg_def_t deadline =
156 ARG_DEF("d", "deadline", 1, "Deadline per frame (usec)");
157 static const arg_def_t best_dl =
158 ARG_DEF(NULL, "best", 0, "Use Best Quality Deadline");
159 static const arg_def_t good_dl =
160 ARG_DEF(NULL, "good", 0, "Use Good Quality Deadline");
161 static const arg_def_t rt_dl =
162 ARG_DEF(NULL, "rt", 0, "Use Realtime Quality Deadline");
163 static const arg_def_t quietarg =
164 ARG_DEF("q", "quiet", 0, "Do not print encode progress");
165 static const arg_def_t verbosearg =
166 ARG_DEF("v", "verbose", 0, "Show encoder parameters");
167 static const arg_def_t psnrarg =
168 ARG_DEF(NULL, "psnr", 0, "Show PSNR in status line");
170 static const struct arg_enum_list test_decode_enum[] = {
171 { "off", TEST_DECODE_OFF },
172 { "fatal", TEST_DECODE_FATAL },
173 { "warn", TEST_DECODE_WARN },
176 static const arg_def_t recontest = ARG_DEF_ENUM(
177 NULL, "test-decode", 1, "Test encode/decode mismatch", test_decode_enum);
178 static const arg_def_t framerate =
179 ARG_DEF(NULL, "fps", 1, "Stream frame rate (rate/scale)");
180 static const arg_def_t use_webm =
181 ARG_DEF(NULL, "webm", 0, "Output WebM (default when WebM IO is enabled)");
182 static const arg_def_t use_ivf = ARG_DEF(NULL, "ivf", 0, "Output IVF");
183 static const arg_def_t out_part =
184 ARG_DEF("P", "output-partitions", 0,
185 "Makes encoder output partitions. Requires IVF output!");
186 static const arg_def_t q_hist_n =
187 ARG_DEF(NULL, "q-hist", 1, "Show quantizer histogram (n-buckets)");
188 static const arg_def_t rate_hist_n =
189 ARG_DEF(NULL, "rate-hist", 1, "Show rate histogram (n-buckets)");
190 static const arg_def_t disable_warnings =
191 ARG_DEF(NULL, "disable-warnings", 0,
192 "Disable warnings about potentially incorrect encode settings.");
193 static const arg_def_t disable_warning_prompt =
194 ARG_DEF("y", "disable-warning-prompt", 0,
195 "Display warnings, but do not prompt user to continue.");
197 #if CONFIG_VP9_HIGHBITDEPTH
198 static const arg_def_t test16bitinternalarg = ARG_DEF(
199 NULL, "test-16bit-internal", 0, "Force use of 16 bit internal buffer");
202 static const arg_def_t *main_args[] = { &debugmode,
223 &disable_warning_prompt,
227 static const arg_def_t usage =
228 ARG_DEF("u", "usage", 1, "Usage profile number to use");
229 static const arg_def_t threads =
230 ARG_DEF("t", "threads", 1, "Max number of threads to use");
231 static const arg_def_t profile =
232 ARG_DEF(NULL, "profile", 1, "Bitstream profile number to use");
233 static const arg_def_t width = ARG_DEF("w", "width", 1, "Frame width");
234 static const arg_def_t height = ARG_DEF("h", "height", 1, "Frame height");
236 static const struct arg_enum_list stereo_mode_enum[] = {
237 { "mono", STEREO_FORMAT_MONO },
238 { "left-right", STEREO_FORMAT_LEFT_RIGHT },
239 { "bottom-top", STEREO_FORMAT_BOTTOM_TOP },
240 { "top-bottom", STEREO_FORMAT_TOP_BOTTOM },
241 { "right-left", STEREO_FORMAT_RIGHT_LEFT },
244 static const arg_def_t stereo_mode = ARG_DEF_ENUM(
245 NULL, "stereo-mode", 1, "Stereo 3D video format", stereo_mode_enum);
247 static const arg_def_t timebase = ARG_DEF(
248 NULL, "timebase", 1, "Output timestamp precision (fractional seconds)");
249 static const arg_def_t error_resilient =
250 ARG_DEF(NULL, "error-resilient", 1, "Enable error resiliency features");
251 static const arg_def_t lag_in_frames =
252 ARG_DEF(NULL, "lag-in-frames", 1, "Max number of frames to lag");
254 static const arg_def_t *global_args[] = { &use_yv12,
270 #if CONFIG_VP9_HIGHBITDEPTH
271 &test16bitinternalarg,
276 static const arg_def_t dropframe_thresh =
277 ARG_DEF(NULL, "drop-frame", 1, "Temporal resampling threshold (buf %)");
278 static const arg_def_t resize_allowed =
279 ARG_DEF(NULL, "resize-allowed", 1, "Spatial resampling enabled (bool)");
280 static const arg_def_t resize_width =
281 ARG_DEF(NULL, "resize-width", 1, "Width of encoded frame");
282 static const arg_def_t resize_height =
283 ARG_DEF(NULL, "resize-height", 1, "Height of encoded frame");
284 static const arg_def_t resize_up_thresh =
285 ARG_DEF(NULL, "resize-up", 1, "Upscale threshold (buf %)");
286 static const arg_def_t resize_down_thresh =
287 ARG_DEF(NULL, "resize-down", 1, "Downscale threshold (buf %)");
288 static const struct arg_enum_list end_usage_enum[] = { { "vbr", VPX_VBR },
293 static const arg_def_t end_usage =
294 ARG_DEF_ENUM(NULL, "end-usage", 1, "Rate control mode", end_usage_enum);
295 static const arg_def_t target_bitrate =
296 ARG_DEF(NULL, "target-bitrate", 1, "Bitrate (kbps)");
297 static const arg_def_t min_quantizer =
298 ARG_DEF(NULL, "min-q", 1, "Minimum (best) quantizer");
299 static const arg_def_t max_quantizer =
300 ARG_DEF(NULL, "max-q", 1, "Maximum (worst) quantizer");
301 static const arg_def_t undershoot_pct =
302 ARG_DEF(NULL, "undershoot-pct", 1, "Datarate undershoot (min) target (%)");
303 static const arg_def_t overshoot_pct =
304 ARG_DEF(NULL, "overshoot-pct", 1, "Datarate overshoot (max) target (%)");
305 static const arg_def_t buf_sz =
306 ARG_DEF(NULL, "buf-sz", 1, "Client buffer size (ms)");
307 static const arg_def_t buf_initial_sz =
308 ARG_DEF(NULL, "buf-initial-sz", 1, "Client initial buffer size (ms)");
309 static const arg_def_t buf_optimal_sz =
310 ARG_DEF(NULL, "buf-optimal-sz", 1, "Client optimal buffer size (ms)");
311 static const arg_def_t *rc_args[] = {
312 &dropframe_thresh, &resize_allowed, &resize_width, &resize_height,
313 &resize_up_thresh, &resize_down_thresh, &end_usage, &target_bitrate,
314 &min_quantizer, &max_quantizer, &undershoot_pct, &overshoot_pct,
315 &buf_sz, &buf_initial_sz, &buf_optimal_sz, NULL
318 static const arg_def_t bias_pct =
319 ARG_DEF(NULL, "bias-pct", 1, "CBR/VBR bias (0=CBR, 100=VBR)");
320 static const arg_def_t minsection_pct =
321 ARG_DEF(NULL, "minsection-pct", 1, "GOP min bitrate (% of target)");
322 static const arg_def_t maxsection_pct =
323 ARG_DEF(NULL, "maxsection-pct", 1, "GOP max bitrate (% of target)");
324 static const arg_def_t *rc_twopass_args[] = { &bias_pct, &minsection_pct,
325 &maxsection_pct, NULL };
327 static const arg_def_t kf_min_dist =
328 ARG_DEF(NULL, "kf-min-dist", 1, "Minimum keyframe interval (frames)");
329 static const arg_def_t kf_max_dist =
330 ARG_DEF(NULL, "kf-max-dist", 1, "Maximum keyframe interval (frames)");
331 static const arg_def_t kf_disabled =
332 ARG_DEF(NULL, "disable-kf", 0, "Disable keyframe placement");
333 static const arg_def_t *kf_args[] = { &kf_min_dist, &kf_max_dist, &kf_disabled,
336 static const arg_def_t noise_sens =
337 ARG_DEF(NULL, "noise-sensitivity", 1, "Noise sensitivity (frames to blur)");
338 static const arg_def_t sharpness =
339 ARG_DEF(NULL, "sharpness", 1, "Loop filter sharpness (0..7)");
340 static const arg_def_t static_thresh =
341 ARG_DEF(NULL, "static-thresh", 1, "Motion detection threshold");
342 static const arg_def_t auto_altref =
343 ARG_DEF(NULL, "auto-alt-ref", 1, "Enable automatic alt reference frames");
344 static const arg_def_t arnr_maxframes =
345 ARG_DEF(NULL, "arnr-maxframes", 1, "AltRef max frames (0..15)");
346 static const arg_def_t arnr_strength =
347 ARG_DEF(NULL, "arnr-strength", 1, "AltRef filter strength (0..6)");
348 static const arg_def_t arnr_type = ARG_DEF(NULL, "arnr-type", 1, "AltRef type");
349 static const struct arg_enum_list tuning_enum[] = {
350 { "psnr", VP8_TUNE_PSNR }, { "ssim", VP8_TUNE_SSIM }, { NULL, 0 }
352 static const arg_def_t tune_ssim =
353 ARG_DEF_ENUM(NULL, "tune", 1, "Material to favor", tuning_enum);
354 static const arg_def_t cq_level =
355 ARG_DEF(NULL, "cq-level", 1, "Constant/Constrained Quality level");
356 static const arg_def_t max_intra_rate_pct =
357 ARG_DEF(NULL, "max-intra-rate", 1, "Max I-frame bitrate (pct)");
359 #if CONFIG_VP8_ENCODER
360 static const arg_def_t cpu_used_vp8 =
361 ARG_DEF(NULL, "cpu-used", 1, "CPU Used (-16..16)");
362 static const arg_def_t token_parts =
363 ARG_DEF(NULL, "token-parts", 1, "Number of token partitions to use, log2");
364 static const arg_def_t screen_content_mode =
365 ARG_DEF(NULL, "screen-content-mode", 1, "Screen content mode");
366 static const arg_def_t *vp8_args[] = {
367 &cpu_used_vp8, &auto_altref, &noise_sens, &sharpness,
368 &static_thresh, &token_parts, &arnr_maxframes, &arnr_strength,
369 &arnr_type, &tune_ssim, &cq_level, &max_intra_rate_pct,
370 &screen_content_mode, NULL
372 static const int vp8_arg_ctrl_map[] = { VP8E_SET_CPUUSED,
373 VP8E_SET_ENABLEAUTOALTREF,
374 VP8E_SET_NOISE_SENSITIVITY,
376 VP8E_SET_STATIC_THRESHOLD,
377 VP8E_SET_TOKEN_PARTITIONS,
378 VP8E_SET_ARNR_MAXFRAMES,
379 VP8E_SET_ARNR_STRENGTH,
383 VP8E_SET_MAX_INTRA_BITRATE_PCT,
384 VP8E_SET_SCREEN_CONTENT_MODE,
388 #if CONFIG_VP9_ENCODER
389 static const arg_def_t cpu_used_vp9 =
390 ARG_DEF(NULL, "cpu-used", 1, "CPU Used (-8..8)");
391 static const arg_def_t tile_cols =
392 ARG_DEF(NULL, "tile-columns", 1, "Number of tile columns to use, log2");
393 static const arg_def_t tile_rows =
394 ARG_DEF(NULL, "tile-rows", 1,
395 "Number of tile rows to use, log2 (set to 0 while threads > 1)");
396 static const arg_def_t lossless =
397 ARG_DEF(NULL, "lossless", 1, "Lossless mode (0: false (default), 1: true)");
398 static const arg_def_t frame_parallel_decoding = ARG_DEF(
399 NULL, "frame-parallel", 1, "Enable frame parallel decodability features");
400 static const arg_def_t aq_mode = ARG_DEF(
402 "Adaptive quantization mode (0: off (default), 1: variance 2: complexity, "
403 "3: cyclic refresh, 4: equator360)");
404 static const arg_def_t frame_periodic_boost =
405 ARG_DEF(NULL, "frame-boost", 1,
406 "Enable frame periodic boost (0: off (default), 1: on)");
407 static const arg_def_t gf_cbr_boost_pct = ARG_DEF(
408 NULL, "gf-cbr-boost", 1, "Boost for Golden Frame in CBR mode (pct)");
409 static const arg_def_t max_inter_rate_pct =
410 ARG_DEF(NULL, "max-inter-rate", 1, "Max P-frame bitrate (pct)");
411 static const arg_def_t min_gf_interval = ARG_DEF(
412 NULL, "min-gf-interval", 1,
413 "min gf/arf frame interval (default 0, indicating in-built behavior)");
414 static const arg_def_t max_gf_interval = ARG_DEF(
415 NULL, "max-gf-interval", 1,
416 "max gf/arf frame interval (default 0, indicating in-built behavior)");
418 static const struct arg_enum_list color_space_enum[] = {
419 { "unknown", VPX_CS_UNKNOWN },
420 { "bt601", VPX_CS_BT_601 },
421 { "bt709", VPX_CS_BT_709 },
422 { "smpte170", VPX_CS_SMPTE_170 },
423 { "smpte240", VPX_CS_SMPTE_240 },
424 { "bt2020", VPX_CS_BT_2020 },
425 { "reserved", VPX_CS_RESERVED },
426 { "sRGB", VPX_CS_SRGB },
430 static const arg_def_t input_color_space =
431 ARG_DEF_ENUM(NULL, "color-space", 1, "The color space of input content:",
434 #if CONFIG_VP9_HIGHBITDEPTH
435 static const struct arg_enum_list bitdepth_enum[] = {
436 { "8", VPX_BITS_8 }, { "10", VPX_BITS_10 }, { "12", VPX_BITS_12 }, { NULL, 0 }
439 static const arg_def_t bitdeptharg = ARG_DEF_ENUM(
441 "Bit depth for codec (8 for version <=1, 10 or 12 for version 2)",
443 static const arg_def_t inbitdeptharg =
444 ARG_DEF(NULL, "input-bit-depth", 1, "Bit depth of input");
447 static const struct arg_enum_list tune_content_enum[] = {
448 { "default", VP9E_CONTENT_DEFAULT },
449 { "screen", VP9E_CONTENT_SCREEN },
453 static const arg_def_t tune_content = ARG_DEF_ENUM(
454 NULL, "tune-content", 1, "Tune content type", tune_content_enum);
456 static const arg_def_t target_level = ARG_DEF(
457 NULL, "target-level", 1,
458 "Target level (255: off (default); 0: only keep level stats; 10: level 1.0;"
459 " 11: level 1.1; ... 62: level 6.2)");
462 #if CONFIG_VP9_ENCODER
463 static const arg_def_t *vp9_args[] = { &cpu_used_vp9,
478 &frame_parallel_decoding,
480 &frame_periodic_boost,
487 #if CONFIG_VP9_HIGHBITDEPTH
490 #endif // CONFIG_VP9_HIGHBITDEPTH
492 static const int vp9_arg_ctrl_map[] = { VP8E_SET_CPUUSED,
493 VP8E_SET_ENABLEAUTOALTREF,
495 VP8E_SET_STATIC_THRESHOLD,
496 VP9E_SET_TILE_COLUMNS,
498 VP8E_SET_ARNR_MAXFRAMES,
499 VP8E_SET_ARNR_STRENGTH,
503 VP8E_SET_MAX_INTRA_BITRATE_PCT,
504 VP9E_SET_MAX_INTER_BITRATE_PCT,
505 VP9E_SET_GF_CBR_BOOST_PCT,
507 VP9E_SET_FRAME_PARALLEL_DECODING,
509 VP9E_SET_FRAME_PERIODIC_BOOST,
510 VP9E_SET_NOISE_SENSITIVITY,
511 VP9E_SET_TUNE_CONTENT,
512 VP9E_SET_COLOR_SPACE,
513 VP9E_SET_MIN_GF_INTERVAL,
514 VP9E_SET_MAX_GF_INTERVAL,
515 VP9E_SET_TARGET_LEVEL,
519 static const arg_def_t *no_args[] = { NULL };
521 void usage_exit(void) {
523 const int num_encoder = get_vpx_encoder_count();
525 fprintf(stderr, "Usage: %s <options> -o dst_filename src_filename \n",
528 fprintf(stderr, "\nOptions:\n");
529 arg_show_usage(stderr, main_args);
530 fprintf(stderr, "\nEncoder Global Options:\n");
531 arg_show_usage(stderr, global_args);
532 fprintf(stderr, "\nRate Control Options:\n");
533 arg_show_usage(stderr, rc_args);
534 fprintf(stderr, "\nTwopass Rate Control Options:\n");
535 arg_show_usage(stderr, rc_twopass_args);
536 fprintf(stderr, "\nKeyframe Placement Options:\n");
537 arg_show_usage(stderr, kf_args);
538 #if CONFIG_VP8_ENCODER
539 fprintf(stderr, "\nVP8 Specific Options:\n");
540 arg_show_usage(stderr, vp8_args);
542 #if CONFIG_VP9_ENCODER
543 fprintf(stderr, "\nVP9 Specific Options:\n");
544 arg_show_usage(stderr, vp9_args);
547 "\nStream timebase (--timebase):\n"
548 " The desired precision of timestamps in the output, expressed\n"
549 " in fractional seconds. Default is 1/1000.\n");
550 fprintf(stderr, "\nIncluded encoders:\n\n");
552 for (i = 0; i < num_encoder; ++i) {
553 const VpxInterface *const encoder = get_vpx_encoder_by_index(i);
554 const char *defstr = (i == (num_encoder - 1)) ? "(default)" : "";
555 fprintf(stderr, " %-6s - %s %s\n", encoder->name,
556 vpx_codec_iface_name(encoder->codec_interface()), defstr);
558 fprintf(stderr, "\n ");
559 fprintf(stderr, "Use --codec to switch to a non-default encoder.\n\n");
564 #define mmin(a, b) ((a) < (b) ? (a) : (b))
566 #if CONFIG_VP9_HIGHBITDEPTH
567 static void find_mismatch_high(const vpx_image_t *const img1,
568 const vpx_image_t *const img2, int yloc[4],
569 int uloc[4], int vloc[4]) {
570 uint16_t *plane1, *plane2;
571 uint32_t stride1, stride2;
572 const uint32_t bsize = 64;
573 const uint32_t bsizey = bsize >> img1->y_chroma_shift;
574 const uint32_t bsizex = bsize >> img1->x_chroma_shift;
576 (img1->d_w + img1->x_chroma_shift) >> img1->x_chroma_shift;
578 (img1->d_h + img1->y_chroma_shift) >> img1->y_chroma_shift;
581 yloc[0] = yloc[1] = yloc[2] = yloc[3] = -1;
582 plane1 = (uint16_t *)img1->planes[VPX_PLANE_Y];
583 plane2 = (uint16_t *)img2->planes[VPX_PLANE_Y];
584 stride1 = img1->stride[VPX_PLANE_Y] / 2;
585 stride2 = img2->stride[VPX_PLANE_Y] / 2;
586 for (i = 0, match = 1; match && i < img1->d_h; i += bsize) {
587 for (j = 0; match && j < img1->d_w; j += bsize) {
589 const int si = mmin(i + bsize, img1->d_h) - i;
590 const int sj = mmin(j + bsize, img1->d_w) - j;
591 for (k = 0; match && k < si; ++k) {
592 for (l = 0; match && l < sj; ++l) {
593 if (*(plane1 + (i + k) * stride1 + j + l) !=
594 *(plane2 + (i + k) * stride2 + j + l)) {
597 yloc[2] = *(plane1 + (i + k) * stride1 + j + l);
598 yloc[3] = *(plane2 + (i + k) * stride2 + j + l);
607 uloc[0] = uloc[1] = uloc[2] = uloc[3] = -1;
608 plane1 = (uint16_t *)img1->planes[VPX_PLANE_U];
609 plane2 = (uint16_t *)img2->planes[VPX_PLANE_U];
610 stride1 = img1->stride[VPX_PLANE_U] / 2;
611 stride2 = img2->stride[VPX_PLANE_U] / 2;
612 for (i = 0, match = 1; match && i < c_h; i += bsizey) {
613 for (j = 0; match && j < c_w; j += bsizex) {
615 const int si = mmin(i + bsizey, c_h - i);
616 const int sj = mmin(j + bsizex, c_w - j);
617 for (k = 0; match && k < si; ++k) {
618 for (l = 0; match && l < sj; ++l) {
619 if (*(plane1 + (i + k) * stride1 + j + l) !=
620 *(plane2 + (i + k) * stride2 + j + l)) {
623 uloc[2] = *(plane1 + (i + k) * stride1 + j + l);
624 uloc[3] = *(plane2 + (i + k) * stride2 + j + l);
633 vloc[0] = vloc[1] = vloc[2] = vloc[3] = -1;
634 plane1 = (uint16_t *)img1->planes[VPX_PLANE_V];
635 plane2 = (uint16_t *)img2->planes[VPX_PLANE_V];
636 stride1 = img1->stride[VPX_PLANE_V] / 2;
637 stride2 = img2->stride[VPX_PLANE_V] / 2;
638 for (i = 0, match = 1; match && i < c_h; i += bsizey) {
639 for (j = 0; match && j < c_w; j += bsizex) {
641 const int si = mmin(i + bsizey, c_h - i);
642 const int sj = mmin(j + bsizex, c_w - j);
643 for (k = 0; match && k < si; ++k) {
644 for (l = 0; match && l < sj; ++l) {
645 if (*(plane1 + (i + k) * stride1 + j + l) !=
646 *(plane2 + (i + k) * stride2 + j + l)) {
649 vloc[2] = *(plane1 + (i + k) * stride1 + j + l);
650 vloc[3] = *(plane2 + (i + k) * stride2 + j + l);
661 static void find_mismatch(const vpx_image_t *const img1,
662 const vpx_image_t *const img2, int yloc[4],
663 int uloc[4], int vloc[4]) {
664 const uint32_t bsize = 64;
665 const uint32_t bsizey = bsize >> img1->y_chroma_shift;
666 const uint32_t bsizex = bsize >> img1->x_chroma_shift;
668 (img1->d_w + img1->x_chroma_shift) >> img1->x_chroma_shift;
670 (img1->d_h + img1->y_chroma_shift) >> img1->y_chroma_shift;
673 yloc[0] = yloc[1] = yloc[2] = yloc[3] = -1;
674 for (i = 0, match = 1; match && i < img1->d_h; i += bsize) {
675 for (j = 0; match && j < img1->d_w; j += bsize) {
677 const int si = mmin(i + bsize, img1->d_h) - i;
678 const int sj = mmin(j + bsize, img1->d_w) - j;
679 for (k = 0; match && k < si; ++k) {
680 for (l = 0; match && l < sj; ++l) {
681 if (*(img1->planes[VPX_PLANE_Y] +
682 (i + k) * img1->stride[VPX_PLANE_Y] + j + l) !=
683 *(img2->planes[VPX_PLANE_Y] +
684 (i + k) * img2->stride[VPX_PLANE_Y] + j + l)) {
687 yloc[2] = *(img1->planes[VPX_PLANE_Y] +
688 (i + k) * img1->stride[VPX_PLANE_Y] + j + l);
689 yloc[3] = *(img2->planes[VPX_PLANE_Y] +
690 (i + k) * img2->stride[VPX_PLANE_Y] + j + l);
699 uloc[0] = uloc[1] = uloc[2] = uloc[3] = -1;
700 for (i = 0, match = 1; match && i < c_h; i += bsizey) {
701 for (j = 0; match && j < c_w; j += bsizex) {
703 const int si = mmin(i + bsizey, c_h - i);
704 const int sj = mmin(j + bsizex, c_w - j);
705 for (k = 0; match && k < si; ++k) {
706 for (l = 0; match && l < sj; ++l) {
707 if (*(img1->planes[VPX_PLANE_U] +
708 (i + k) * img1->stride[VPX_PLANE_U] + j + l) !=
709 *(img2->planes[VPX_PLANE_U] +
710 (i + k) * img2->stride[VPX_PLANE_U] + j + l)) {
713 uloc[2] = *(img1->planes[VPX_PLANE_U] +
714 (i + k) * img1->stride[VPX_PLANE_U] + j + l);
715 uloc[3] = *(img2->planes[VPX_PLANE_U] +
716 (i + k) * img2->stride[VPX_PLANE_U] + j + l);
724 vloc[0] = vloc[1] = vloc[2] = vloc[3] = -1;
725 for (i = 0, match = 1; match && i < c_h; i += bsizey) {
726 for (j = 0; match && j < c_w; j += bsizex) {
728 const int si = mmin(i + bsizey, c_h - i);
729 const int sj = mmin(j + bsizex, c_w - j);
730 for (k = 0; match && k < si; ++k) {
731 for (l = 0; match && l < sj; ++l) {
732 if (*(img1->planes[VPX_PLANE_V] +
733 (i + k) * img1->stride[VPX_PLANE_V] + j + l) !=
734 *(img2->planes[VPX_PLANE_V] +
735 (i + k) * img2->stride[VPX_PLANE_V] + j + l)) {
738 vloc[2] = *(img1->planes[VPX_PLANE_V] +
739 (i + k) * img1->stride[VPX_PLANE_V] + j + l);
740 vloc[3] = *(img2->planes[VPX_PLANE_V] +
741 (i + k) * img2->stride[VPX_PLANE_V] + j + l);
751 static int compare_img(const vpx_image_t *const img1,
752 const vpx_image_t *const img2) {
753 uint32_t l_w = img1->d_w;
754 uint32_t c_w = (img1->d_w + img1->x_chroma_shift) >> img1->x_chroma_shift;
756 (img1->d_h + img1->y_chroma_shift) >> img1->y_chroma_shift;
760 match &= (img1->fmt == img2->fmt);
761 match &= (img1->d_w == img2->d_w);
762 match &= (img1->d_h == img2->d_h);
763 #if CONFIG_VP9_HIGHBITDEPTH
764 if (img1->fmt & VPX_IMG_FMT_HIGHBITDEPTH) {
770 for (i = 0; i < img1->d_h; ++i)
771 match &= (memcmp(img1->planes[VPX_PLANE_Y] + i * img1->stride[VPX_PLANE_Y],
772 img2->planes[VPX_PLANE_Y] + i * img2->stride[VPX_PLANE_Y],
775 for (i = 0; i < c_h; ++i)
776 match &= (memcmp(img1->planes[VPX_PLANE_U] + i * img1->stride[VPX_PLANE_U],
777 img2->planes[VPX_PLANE_U] + i * img2->stride[VPX_PLANE_U],
780 for (i = 0; i < c_h; ++i)
781 match &= (memcmp(img1->planes[VPX_PLANE_V] + i * img1->stride[VPX_PLANE_V],
782 img2->planes[VPX_PLANE_V] + i * img2->stride[VPX_PLANE_V],
788 #define NELEMENTS(x) (sizeof(x) / sizeof(x[0]))
789 #if CONFIG_VP9_ENCODER
790 #define ARG_CTRL_CNT_MAX NELEMENTS(vp9_arg_ctrl_map)
792 #define ARG_CTRL_CNT_MAX NELEMENTS(vp8_arg_ctrl_map)
796 typedef int stereo_format_t;
797 struct WebmOutputContext {
802 /* Per-stream configuration */
803 struct stream_config {
804 struct vpx_codec_enc_cfg cfg;
806 const char *stats_fn;
807 #if CONFIG_FP_MB_STATS
808 const char *fpmb_stats_fn;
810 stereo_format_t stereo_fmt;
811 int arg_ctrls[ARG_CTRL_CNT_MAX][2];
814 #if CONFIG_VP9_HIGHBITDEPTH
815 // whether to use 16bit internal buffers
816 int use_16bit_internal;
820 struct stream_state {
822 struct stream_state *next;
823 struct stream_config config;
825 struct rate_hist *rate_hist;
826 struct WebmOutputContext webm_ctx;
827 uint64_t psnr_sse_total;
828 uint64_t psnr_samples_total;
829 double psnr_totals[4];
832 vpx_codec_ctx_t encoder;
833 unsigned int frames_out;
837 #if CONFIG_FP_MB_STATS
838 stats_io_t fpmb_stats;
840 struct vpx_image *img;
841 vpx_codec_ctx_t decoder;
845 static void validate_positive_rational(const char *msg,
846 struct vpx_rational *rat) {
852 if (rat->num < 0) die("Error: %s must be positive\n", msg);
854 if (!rat->den) die("Error: %s has zero denominator\n", msg);
857 static void parse_global_config(struct VpxEncoderConfig *global, char **argv) {
860 const int num_encoder = get_vpx_encoder_count();
862 if (num_encoder < 1) die("Error: no valid encoder available\n");
864 /* Initialize default parameters */
865 memset(global, 0, sizeof(*global));
866 global->codec = get_vpx_encoder_by_index(num_encoder - 1);
868 global->color_type = I420;
869 /* Assign default deadline to good quality */
870 global->deadline = VPX_DL_GOOD_QUALITY;
872 for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step) {
875 if (arg_match(&arg, &codecarg, argi)) {
876 global->codec = get_vpx_encoder_by_name(arg.val);
878 die("Error: Unrecognized argument (%s) to --codec\n", arg.val);
879 } else if (arg_match(&arg, &passes, argi)) {
880 global->passes = arg_parse_uint(&arg);
882 if (global->passes < 1 || global->passes > 2)
883 die("Error: Invalid number of passes (%d)\n", global->passes);
884 } else if (arg_match(&arg, &pass_arg, argi)) {
885 global->pass = arg_parse_uint(&arg);
887 if (global->pass < 1 || global->pass > 2)
888 die("Error: Invalid pass selected (%d)\n", global->pass);
889 } else if (arg_match(&arg, &usage, argi))
890 global->usage = arg_parse_uint(&arg);
891 else if (arg_match(&arg, &deadline, argi))
892 global->deadline = arg_parse_uint(&arg);
893 else if (arg_match(&arg, &best_dl, argi))
894 global->deadline = VPX_DL_BEST_QUALITY;
895 else if (arg_match(&arg, &good_dl, argi))
896 global->deadline = VPX_DL_GOOD_QUALITY;
897 else if (arg_match(&arg, &rt_dl, argi))
898 global->deadline = VPX_DL_REALTIME;
899 else if (arg_match(&arg, &use_yv12, argi))
900 global->color_type = YV12;
901 else if (arg_match(&arg, &use_i420, argi))
902 global->color_type = I420;
903 else if (arg_match(&arg, &use_i422, argi))
904 global->color_type = I422;
905 else if (arg_match(&arg, &use_i444, argi))
906 global->color_type = I444;
907 else if (arg_match(&arg, &use_i440, argi))
908 global->color_type = I440;
909 else if (arg_match(&arg, &quietarg, argi))
911 else if (arg_match(&arg, &verbosearg, argi))
913 else if (arg_match(&arg, &limit, argi))
914 global->limit = arg_parse_uint(&arg);
915 else if (arg_match(&arg, &skip, argi))
916 global->skip_frames = arg_parse_uint(&arg);
917 else if (arg_match(&arg, &psnrarg, argi))
918 global->show_psnr = 1;
919 else if (arg_match(&arg, &recontest, argi))
920 global->test_decode = arg_parse_enum_or_int(&arg);
921 else if (arg_match(&arg, &framerate, argi)) {
922 global->framerate = arg_parse_rational(&arg);
923 validate_positive_rational(arg.name, &global->framerate);
924 global->have_framerate = 1;
925 } else if (arg_match(&arg, &out_part, argi))
926 global->out_part = 1;
927 else if (arg_match(&arg, &debugmode, argi))
929 else if (arg_match(&arg, &q_hist_n, argi))
930 global->show_q_hist_buckets = arg_parse_uint(&arg);
931 else if (arg_match(&arg, &rate_hist_n, argi))
932 global->show_rate_hist_buckets = arg_parse_uint(&arg);
933 else if (arg_match(&arg, &disable_warnings, argi))
934 global->disable_warnings = 1;
935 else if (arg_match(&arg, &disable_warning_prompt, argi))
936 global->disable_warning_prompt = 1;
942 /* DWIM: Assume the user meant passes=2 if pass=2 is specified */
943 if (global->pass > global->passes) {
944 warn("Assuming --pass=%d implies --passes=%d\n", global->pass,
946 global->passes = global->pass;
949 /* Validate global config */
950 if (global->passes == 0) {
951 #if CONFIG_VP9_ENCODER
952 // Make default VP9 passes = 2 until there is a better quality 1-pass
954 if (global->codec != NULL && global->codec->name != NULL)
955 global->passes = (strcmp(global->codec->name, "vp9") == 0 &&
956 global->deadline != VPX_DL_REALTIME)
964 if (global->deadline == VPX_DL_REALTIME && global->passes > 1) {
965 warn("Enforcing one-pass encoding in realtime mode\n");
970 static void open_input_file(struct VpxInputContext *input) {
971 /* Parse certain options from the input file, if possible */
972 input->file = strcmp(input->filename, "-") ? fopen(input->filename, "rb")
973 : set_binary_mode(stdin);
975 if (!input->file) fatal("Failed to open input file");
977 if (!fseeko(input->file, 0, SEEK_END)) {
978 /* Input file is seekable. Figure out how long it is, so we can get
981 input->length = ftello(input->file);
985 /* Default to 1:1 pixel aspect ratio. */
986 input->pixel_aspect_ratio.numerator = 1;
987 input->pixel_aspect_ratio.denominator = 1;
989 /* For RAW input sources, these bytes will applied on the first frame
992 input->detect.buf_read = fread(input->detect.buf, 1, 4, input->file);
993 input->detect.position = 0;
995 if (input->detect.buf_read == 4 && file_is_y4m(input->detect.buf)) {
996 if (y4m_input_open(&input->y4m, input->file, input->detect.buf, 4,
997 input->only_i420) >= 0) {
998 input->file_type = FILE_TYPE_Y4M;
999 input->width = input->y4m.pic_w;
1000 input->height = input->y4m.pic_h;
1001 input->pixel_aspect_ratio.numerator = input->y4m.par_n;
1002 input->pixel_aspect_ratio.denominator = input->y4m.par_d;
1003 input->framerate.numerator = input->y4m.fps_n;
1004 input->framerate.denominator = input->y4m.fps_d;
1005 input->fmt = input->y4m.vpx_fmt;
1006 input->bit_depth = input->y4m.bit_depth;
1008 fatal("Unsupported Y4M stream.");
1009 } else if (input->detect.buf_read == 4 && fourcc_is_ivf(input->detect.buf)) {
1010 fatal("IVF is not supported as input.");
1012 input->file_type = FILE_TYPE_RAW;
1016 static void close_input_file(struct VpxInputContext *input) {
1017 fclose(input->file);
1018 if (input->file_type == FILE_TYPE_Y4M) y4m_input_close(&input->y4m);
1021 static struct stream_state *new_stream(struct VpxEncoderConfig *global,
1022 struct stream_state *prev) {
1023 struct stream_state *stream;
1025 stream = calloc(1, sizeof(*stream));
1026 if (stream == NULL) {
1027 fatal("Failed to allocate new stream.");
1031 memcpy(stream, prev, sizeof(*stream));
1033 prev->next = stream;
1035 vpx_codec_err_t res;
1037 /* Populate encoder configuration */
1038 res = vpx_codec_enc_config_default(global->codec->codec_interface(),
1039 &stream->config.cfg, global->usage);
1040 if (res) fatal("Failed to get config: %s\n", vpx_codec_err_to_string(res));
1042 /* Change the default timebase to a high enough value so that the
1043 * encoder will always create strictly increasing timestamps.
1045 stream->config.cfg.g_timebase.den = 1000;
1047 /* Never use the library's default resolution, require it be parsed
1048 * from the file or set on the command line.
1050 stream->config.cfg.g_w = 0;
1051 stream->config.cfg.g_h = 0;
1053 /* Initialize remaining stream parameters */
1054 stream->config.write_webm = 1;
1056 stream->config.stereo_fmt = STEREO_FORMAT_MONO;
1057 stream->webm_ctx.last_pts_ns = -1;
1058 stream->webm_ctx.writer = NULL;
1059 stream->webm_ctx.segment = NULL;
1062 /* Allows removal of the application version from the EBML tags */
1063 stream->webm_ctx.debug = global->debug;
1065 /* Default lag_in_frames is 0 in realtime mode CBR mode*/
1066 if (global->deadline == VPX_DL_REALTIME &&
1067 stream->config.cfg.rc_end_usage == 1)
1068 stream->config.cfg.g_lag_in_frames = 0;
1071 /* Output files must be specified for each stream */
1072 stream->config.out_fn = NULL;
1074 stream->next = NULL;
1078 static int parse_stream_params(struct VpxEncoderConfig *global,
1079 struct stream_state *stream, char **argv) {
1080 char **argi, **argj;
1082 static const arg_def_t **ctrl_args = no_args;
1083 static const int *ctrl_args_map = NULL;
1084 struct stream_config *config = &stream->config;
1085 int eos_mark_found = 0;
1086 #if CONFIG_VP9_HIGHBITDEPTH
1087 int test_16bit_internal = 0;
1090 // Handle codec specific options
1092 #if CONFIG_VP8_ENCODER
1093 } else if (strcmp(global->codec->name, "vp8") == 0) {
1094 ctrl_args = vp8_args;
1095 ctrl_args_map = vp8_arg_ctrl_map;
1097 #if CONFIG_VP9_ENCODER
1098 } else if (strcmp(global->codec->name, "vp9") == 0) {
1099 ctrl_args = vp9_args;
1100 ctrl_args_map = vp9_arg_ctrl_map;
1104 for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step) {
1107 /* Once we've found an end-of-stream marker (--) we want to continue
1108 * shifting arguments but not consuming them.
1110 if (eos_mark_found) {
1113 } else if (!strcmp(*argj, "--")) {
1118 if (arg_match(&arg, &outputfile, argi)) {
1119 config->out_fn = arg.val;
1120 } else if (arg_match(&arg, &fpf_name, argi)) {
1121 config->stats_fn = arg.val;
1122 #if CONFIG_FP_MB_STATS
1123 } else if (arg_match(&arg, &fpmbf_name, argi)) {
1124 config->fpmb_stats_fn = arg.val;
1126 } else if (arg_match(&arg, &use_webm, argi)) {
1128 config->write_webm = 1;
1130 die("Error: --webm specified but webm is disabled.");
1132 } else if (arg_match(&arg, &use_ivf, argi)) {
1133 config->write_webm = 0;
1134 } else if (arg_match(&arg, &threads, argi)) {
1135 config->cfg.g_threads = arg_parse_uint(&arg);
1136 } else if (arg_match(&arg, &profile, argi)) {
1137 config->cfg.g_profile = arg_parse_uint(&arg);
1138 } else if (arg_match(&arg, &width, argi)) {
1139 config->cfg.g_w = arg_parse_uint(&arg);
1140 } else if (arg_match(&arg, &height, argi)) {
1141 config->cfg.g_h = arg_parse_uint(&arg);
1142 #if CONFIG_VP9_HIGHBITDEPTH
1143 } else if (arg_match(&arg, &bitdeptharg, argi)) {
1144 config->cfg.g_bit_depth = arg_parse_enum_or_int(&arg);
1145 } else if (arg_match(&arg, &inbitdeptharg, argi)) {
1146 config->cfg.g_input_bit_depth = arg_parse_uint(&arg);
1149 } else if (arg_match(&arg, &stereo_mode, argi)) {
1150 config->stereo_fmt = arg_parse_enum_or_int(&arg);
1152 } else if (arg_match(&arg, &timebase, argi)) {
1153 config->cfg.g_timebase = arg_parse_rational(&arg);
1154 validate_positive_rational(arg.name, &config->cfg.g_timebase);
1155 } else if (arg_match(&arg, &error_resilient, argi)) {
1156 config->cfg.g_error_resilient = arg_parse_uint(&arg);
1157 } else if (arg_match(&arg, &end_usage, argi)) {
1158 config->cfg.rc_end_usage = arg_parse_enum_or_int(&arg);
1159 } else if (arg_match(&arg, &lag_in_frames, argi)) {
1160 config->cfg.g_lag_in_frames = arg_parse_uint(&arg);
1161 if (global->deadline == VPX_DL_REALTIME &&
1162 config->cfg.rc_end_usage == VPX_CBR &&
1163 config->cfg.g_lag_in_frames != 0) {
1164 warn("non-zero %s option ignored in realtime CBR mode.\n", arg.name);
1165 config->cfg.g_lag_in_frames = 0;
1167 } else if (arg_match(&arg, &dropframe_thresh, argi)) {
1168 config->cfg.rc_dropframe_thresh = arg_parse_uint(&arg);
1169 } else if (arg_match(&arg, &resize_allowed, argi)) {
1170 config->cfg.rc_resize_allowed = arg_parse_uint(&arg);
1171 } else if (arg_match(&arg, &resize_width, argi)) {
1172 config->cfg.rc_scaled_width = arg_parse_uint(&arg);
1173 } else if (arg_match(&arg, &resize_height, argi)) {
1174 config->cfg.rc_scaled_height = arg_parse_uint(&arg);
1175 } else if (arg_match(&arg, &resize_up_thresh, argi)) {
1176 config->cfg.rc_resize_up_thresh = arg_parse_uint(&arg);
1177 } else if (arg_match(&arg, &resize_down_thresh, argi)) {
1178 config->cfg.rc_resize_down_thresh = arg_parse_uint(&arg);
1179 } else if (arg_match(&arg, &end_usage, argi)) {
1180 config->cfg.rc_end_usage = arg_parse_enum_or_int(&arg);
1181 } else if (arg_match(&arg, &target_bitrate, argi)) {
1182 config->cfg.rc_target_bitrate = arg_parse_uint(&arg);
1183 } else if (arg_match(&arg, &min_quantizer, argi)) {
1184 config->cfg.rc_min_quantizer = arg_parse_uint(&arg);
1185 } else if (arg_match(&arg, &max_quantizer, argi)) {
1186 config->cfg.rc_max_quantizer = arg_parse_uint(&arg);
1187 } else if (arg_match(&arg, &undershoot_pct, argi)) {
1188 config->cfg.rc_undershoot_pct = arg_parse_uint(&arg);
1189 } else if (arg_match(&arg, &overshoot_pct, argi)) {
1190 config->cfg.rc_overshoot_pct = arg_parse_uint(&arg);
1191 } else if (arg_match(&arg, &buf_sz, argi)) {
1192 config->cfg.rc_buf_sz = arg_parse_uint(&arg);
1193 } else if (arg_match(&arg, &buf_initial_sz, argi)) {
1194 config->cfg.rc_buf_initial_sz = arg_parse_uint(&arg);
1195 } else if (arg_match(&arg, &buf_optimal_sz, argi)) {
1196 config->cfg.rc_buf_optimal_sz = arg_parse_uint(&arg);
1197 } else if (arg_match(&arg, &bias_pct, argi)) {
1198 config->cfg.rc_2pass_vbr_bias_pct = arg_parse_uint(&arg);
1199 if (global->passes < 2)
1200 warn("option %s ignored in one-pass mode.\n", arg.name);
1201 } else if (arg_match(&arg, &minsection_pct, argi)) {
1202 config->cfg.rc_2pass_vbr_minsection_pct = arg_parse_uint(&arg);
1204 if (global->passes < 2)
1205 warn("option %s ignored in one-pass mode.\n", arg.name);
1206 } else if (arg_match(&arg, &maxsection_pct, argi)) {
1207 config->cfg.rc_2pass_vbr_maxsection_pct = arg_parse_uint(&arg);
1209 if (global->passes < 2)
1210 warn("option %s ignored in one-pass mode.\n", arg.name);
1211 } else if (arg_match(&arg, &kf_min_dist, argi)) {
1212 config->cfg.kf_min_dist = arg_parse_uint(&arg);
1213 } else if (arg_match(&arg, &kf_max_dist, argi)) {
1214 config->cfg.kf_max_dist = arg_parse_uint(&arg);
1215 } else if (arg_match(&arg, &kf_disabled, argi)) {
1216 config->cfg.kf_mode = VPX_KF_DISABLED;
1217 #if CONFIG_VP9_HIGHBITDEPTH
1218 } else if (arg_match(&arg, &test16bitinternalarg, argi)) {
1219 if (strcmp(global->codec->name, "vp9") == 0) {
1220 test_16bit_internal = 1;
1225 for (i = 0; ctrl_args[i]; i++) {
1226 if (arg_match(&arg, ctrl_args[i], argi)) {
1230 /* Point either to the next free element or the first
1231 * instance of this control.
1233 for (j = 0; j < config->arg_ctrl_cnt; j++)
1234 if (ctrl_args_map != NULL &&
1235 config->arg_ctrls[j][0] == ctrl_args_map[i])
1239 assert(j < (int)ARG_CTRL_CNT_MAX);
1240 if (ctrl_args_map != NULL && j < (int)ARG_CTRL_CNT_MAX) {
1241 config->arg_ctrls[j][0] = ctrl_args_map[i];
1242 config->arg_ctrls[j][1] = arg_parse_enum_or_int(&arg);
1243 if (j == config->arg_ctrl_cnt) config->arg_ctrl_cnt++;
1250 #if CONFIG_VP9_HIGHBITDEPTH
1251 if (strcmp(global->codec->name, "vp9") == 0) {
1252 config->use_16bit_internal =
1253 test_16bit_internal | (config->cfg.g_profile > 1);
1256 return eos_mark_found;
1259 #define FOREACH_STREAM(func) \
1261 struct stream_state *stream; \
1262 for (stream = streams; stream; stream = stream->next) { \
1267 static void validate_stream_config(const struct stream_state *stream,
1268 const struct VpxEncoderConfig *global) {
1269 const struct stream_state *streami;
1272 if (!stream->config.cfg.g_w || !stream->config.cfg.g_h)
1274 "Stream %d: Specify stream dimensions with --width (-w) "
1275 " and --height (-h)",
1278 // Check that the codec bit depth is greater than the input bit depth.
1279 if (stream->config.cfg.g_input_bit_depth >
1280 (unsigned int)stream->config.cfg.g_bit_depth) {
1281 fatal("Stream %d: codec bit depth (%d) less than input bit depth (%d)",
1282 stream->index, (int)stream->config.cfg.g_bit_depth,
1283 stream->config.cfg.g_input_bit_depth);
1286 for (streami = stream; streami; streami = streami->next) {
1287 /* All streams require output files */
1288 if (!streami->config.out_fn)
1289 fatal("Stream %d: Output file is required (specify with -o)",
1292 /* Check for two streams outputting to the same file */
1293 if (streami != stream) {
1294 const char *a = stream->config.out_fn;
1295 const char *b = streami->config.out_fn;
1296 if (!strcmp(a, b) && strcmp(a, "/dev/null") && strcmp(a, ":nul"))
1297 fatal("Stream %d: duplicate output file (from stream %d)",
1298 streami->index, stream->index);
1301 /* Check for two streams sharing a stats file. */
1302 if (streami != stream) {
1303 const char *a = stream->config.stats_fn;
1304 const char *b = streami->config.stats_fn;
1305 if (a && b && !strcmp(a, b))
1306 fatal("Stream %d: duplicate stats file (from stream %d)",
1307 streami->index, stream->index);
1310 #if CONFIG_FP_MB_STATS
1311 /* Check for two streams sharing a mb stats file. */
1312 if (streami != stream) {
1313 const char *a = stream->config.fpmb_stats_fn;
1314 const char *b = streami->config.fpmb_stats_fn;
1315 if (a && b && !strcmp(a, b))
1316 fatal("Stream %d: duplicate mb stats file (from stream %d)",
1317 streami->index, stream->index);
1323 static void set_stream_dimensions(struct stream_state *stream, unsigned int w,
1325 if (!stream->config.cfg.g_w) {
1326 if (!stream->config.cfg.g_h)
1327 stream->config.cfg.g_w = w;
1329 stream->config.cfg.g_w = w * stream->config.cfg.g_h / h;
1331 if (!stream->config.cfg.g_h) {
1332 stream->config.cfg.g_h = h * stream->config.cfg.g_w / w;
1336 static const char *file_type_to_string(enum VideoFileType t) {
1338 case FILE_TYPE_RAW: return "RAW";
1339 case FILE_TYPE_Y4M: return "Y4M";
1340 default: return "Other";
1344 static const char *image_format_to_string(vpx_img_fmt_t f) {
1346 case VPX_IMG_FMT_I420: return "I420";
1347 case VPX_IMG_FMT_I422: return "I422";
1348 case VPX_IMG_FMT_I444: return "I444";
1349 case VPX_IMG_FMT_I440: return "I440";
1350 case VPX_IMG_FMT_YV12: return "YV12";
1351 case VPX_IMG_FMT_I42016: return "I42016";
1352 case VPX_IMG_FMT_I42216: return "I42216";
1353 case VPX_IMG_FMT_I44416: return "I44416";
1354 case VPX_IMG_FMT_I44016: return "I44016";
1355 default: return "Other";
1359 static void show_stream_config(struct stream_state *stream,
1360 struct VpxEncoderConfig *global,
1361 struct VpxInputContext *input) {
1362 #define SHOW(field) \
1363 fprintf(stderr, " %-28s = %d\n", #field, stream->config.cfg.field)
1365 if (stream->index == 0) {
1366 fprintf(stderr, "Codec: %s\n",
1367 vpx_codec_iface_name(global->codec->codec_interface()));
1368 fprintf(stderr, "Source file: %s File Type: %s Format: %s\n",
1369 input->filename, file_type_to_string(input->file_type),
1370 image_format_to_string(input->fmt));
1372 if (stream->next || stream->index)
1373 fprintf(stderr, "\nStream Index: %d\n", stream->index);
1374 fprintf(stderr, "Destination file: %s\n", stream->config.out_fn);
1375 fprintf(stderr, "Encoder parameters:\n");
1383 SHOW(g_input_bit_depth);
1384 SHOW(g_timebase.num);
1385 SHOW(g_timebase.den);
1386 SHOW(g_error_resilient);
1388 SHOW(g_lag_in_frames);
1389 SHOW(rc_dropframe_thresh);
1390 SHOW(rc_resize_allowed);
1391 SHOW(rc_scaled_width);
1392 SHOW(rc_scaled_height);
1393 SHOW(rc_resize_up_thresh);
1394 SHOW(rc_resize_down_thresh);
1396 SHOW(rc_target_bitrate);
1397 SHOW(rc_min_quantizer);
1398 SHOW(rc_max_quantizer);
1399 SHOW(rc_undershoot_pct);
1400 SHOW(rc_overshoot_pct);
1402 SHOW(rc_buf_initial_sz);
1403 SHOW(rc_buf_optimal_sz);
1404 SHOW(rc_2pass_vbr_bias_pct);
1405 SHOW(rc_2pass_vbr_minsection_pct);
1406 SHOW(rc_2pass_vbr_maxsection_pct);
1412 static void open_output_file(struct stream_state *stream,
1413 struct VpxEncoderConfig *global,
1414 const struct VpxRational *pixel_aspect_ratio) {
1415 const char *fn = stream->config.out_fn;
1416 const struct vpx_codec_enc_cfg *const cfg = &stream->config.cfg;
1418 if (cfg->g_pass == VPX_RC_FIRST_PASS) return;
1420 stream->file = strcmp(fn, "-") ? fopen(fn, "wb") : set_binary_mode(stdout);
1422 if (!stream->file) fatal("Failed to open output file");
1424 if (stream->config.write_webm && fseek(stream->file, 0, SEEK_CUR))
1425 fatal("WebM output to pipes not supported.");
1428 if (stream->config.write_webm) {
1429 stream->webm_ctx.stream = stream->file;
1430 write_webm_file_header(&stream->webm_ctx, cfg, &global->framerate,
1431 stream->config.stereo_fmt, global->codec->fourcc,
1432 pixel_aspect_ratio);
1435 (void)pixel_aspect_ratio;
1438 if (!stream->config.write_webm) {
1439 ivf_write_file_header(stream->file, cfg, global->codec->fourcc, 0);
1443 static void close_output_file(struct stream_state *stream,
1444 unsigned int fourcc) {
1445 const struct vpx_codec_enc_cfg *const cfg = &stream->config.cfg;
1447 if (cfg->g_pass == VPX_RC_FIRST_PASS) return;
1450 if (stream->config.write_webm) {
1451 write_webm_file_footer(&stream->webm_ctx);
1455 if (!stream->config.write_webm) {
1456 if (!fseek(stream->file, 0, SEEK_SET))
1457 ivf_write_file_header(stream->file, &stream->config.cfg, fourcc,
1458 stream->frames_out);
1461 fclose(stream->file);
1464 static void setup_pass(struct stream_state *stream,
1465 struct VpxEncoderConfig *global, int pass) {
1466 if (stream->config.stats_fn) {
1467 if (!stats_open_file(&stream->stats, stream->config.stats_fn, pass))
1468 fatal("Failed to open statistics store");
1470 if (!stats_open_mem(&stream->stats, pass))
1471 fatal("Failed to open statistics store");
1474 #if CONFIG_FP_MB_STATS
1475 if (stream->config.fpmb_stats_fn) {
1476 if (!stats_open_file(&stream->fpmb_stats, stream->config.fpmb_stats_fn,
1478 fatal("Failed to open mb statistics store");
1480 if (!stats_open_mem(&stream->fpmb_stats, pass))
1481 fatal("Failed to open mb statistics store");
1485 stream->config.cfg.g_pass = global->passes == 2
1486 ? pass ? VPX_RC_LAST_PASS : VPX_RC_FIRST_PASS
1489 stream->config.cfg.rc_twopass_stats_in = stats_get(&stream->stats);
1490 #if CONFIG_FP_MB_STATS
1491 stream->config.cfg.rc_firstpass_mb_stats_in =
1492 stats_get(&stream->fpmb_stats);
1496 stream->cx_time = 0;
1498 stream->frames_out = 0;
1501 static void initialize_encoder(struct stream_state *stream,
1502 struct VpxEncoderConfig *global) {
1506 flags |= global->show_psnr ? VPX_CODEC_USE_PSNR : 0;
1507 flags |= global->out_part ? VPX_CODEC_USE_OUTPUT_PARTITION : 0;
1508 #if CONFIG_VP9_HIGHBITDEPTH
1509 flags |= stream->config.use_16bit_internal ? VPX_CODEC_USE_HIGHBITDEPTH : 0;
1512 /* Construct Encoder Context */
1513 vpx_codec_enc_init(&stream->encoder, global->codec->codec_interface(),
1514 &stream->config.cfg, flags);
1515 ctx_exit_on_error(&stream->encoder, "Failed to initialize encoder");
1517 /* Note that we bypass the vpx_codec_control wrapper macro because
1518 * we're being clever to store the control IDs in an array. Real
1519 * applications will want to make use of the enumerations directly
1521 for (i = 0; i < stream->config.arg_ctrl_cnt; i++) {
1522 int ctrl = stream->config.arg_ctrls[i][0];
1523 int value = stream->config.arg_ctrls[i][1];
1524 if (vpx_codec_control_(&stream->encoder, ctrl, value))
1525 fprintf(stderr, "Error: Tried to set control %d = %d\n", ctrl, value);
1527 ctx_exit_on_error(&stream->encoder, "Failed to control codec");
1531 if (global->test_decode != TEST_DECODE_OFF) {
1532 const VpxInterface *decoder = get_vpx_decoder_by_name(global->codec->name);
1533 vpx_codec_dec_init(&stream->decoder, decoder->codec_interface(), NULL, 0);
1538 static void encode_frame(struct stream_state *stream,
1539 struct VpxEncoderConfig *global, struct vpx_image *img,
1540 unsigned int frames_in) {
1541 vpx_codec_pts_t frame_start, next_frame_start;
1542 struct vpx_codec_enc_cfg *cfg = &stream->config.cfg;
1543 struct vpx_usec_timer timer;
1546 (cfg->g_timebase.den * (int64_t)(frames_in - 1) * global->framerate.den) /
1547 cfg->g_timebase.num / global->framerate.num;
1549 (cfg->g_timebase.den * (int64_t)(frames_in)*global->framerate.den) /
1550 cfg->g_timebase.num / global->framerate.num;
1552 /* Scale if necessary */
1553 #if CONFIG_VP9_HIGHBITDEPTH
1555 if ((img->fmt & VPX_IMG_FMT_HIGHBITDEPTH) &&
1556 (img->d_w != cfg->g_w || img->d_h != cfg->g_h)) {
1557 if (img->fmt != VPX_IMG_FMT_I42016) {
1558 fprintf(stderr, "%s can only scale 4:2:0 inputs\n", exec_name);
1564 vpx_img_alloc(NULL, VPX_IMG_FMT_I42016, cfg->g_w, cfg->g_h, 16);
1567 (uint16 *)img->planes[VPX_PLANE_Y], img->stride[VPX_PLANE_Y] / 2,
1568 (uint16 *)img->planes[VPX_PLANE_U], img->stride[VPX_PLANE_U] / 2,
1569 (uint16 *)img->planes[VPX_PLANE_V], img->stride[VPX_PLANE_V] / 2,
1570 img->d_w, img->d_h, (uint16 *)stream->img->planes[VPX_PLANE_Y],
1571 stream->img->stride[VPX_PLANE_Y] / 2,
1572 (uint16 *)stream->img->planes[VPX_PLANE_U],
1573 stream->img->stride[VPX_PLANE_U] / 2,
1574 (uint16 *)stream->img->planes[VPX_PLANE_V],
1575 stream->img->stride[VPX_PLANE_V] / 2, stream->img->d_w,
1576 stream->img->d_h, kFilterBox);
1579 stream->encoder.err = 1;
1580 ctx_exit_on_error(&stream->encoder,
1581 "Stream %d: Failed to encode frame.\n"
1582 "Scaling disabled in this configuration. \n"
1583 "To enable, configure with --enable-libyuv\n",
1589 if (img && (img->d_w != cfg->g_w || img->d_h != cfg->g_h)) {
1590 if (img->fmt != VPX_IMG_FMT_I420 && img->fmt != VPX_IMG_FMT_YV12) {
1591 fprintf(stderr, "%s can only scale 4:2:0 8bpp inputs\n", exec_name);
1597 vpx_img_alloc(NULL, VPX_IMG_FMT_I420, cfg->g_w, cfg->g_h, 16);
1599 img->planes[VPX_PLANE_Y], img->stride[VPX_PLANE_Y],
1600 img->planes[VPX_PLANE_U], img->stride[VPX_PLANE_U],
1601 img->planes[VPX_PLANE_V], img->stride[VPX_PLANE_V], img->d_w, img->d_h,
1602 stream->img->planes[VPX_PLANE_Y], stream->img->stride[VPX_PLANE_Y],
1603 stream->img->planes[VPX_PLANE_U], stream->img->stride[VPX_PLANE_U],
1604 stream->img->planes[VPX_PLANE_V], stream->img->stride[VPX_PLANE_V],
1605 stream->img->d_w, stream->img->d_h, kFilterBox);
1608 stream->encoder.err = 1;
1609 ctx_exit_on_error(&stream->encoder,
1610 "Stream %d: Failed to encode frame.\n"
1611 "Scaling disabled in this configuration. \n"
1612 "To enable, configure with --enable-libyuv\n",
1617 vpx_usec_timer_start(&timer);
1618 vpx_codec_encode(&stream->encoder, img, frame_start,
1619 (unsigned long)(next_frame_start - frame_start), 0,
1621 vpx_usec_timer_mark(&timer);
1622 stream->cx_time += vpx_usec_timer_elapsed(&timer);
1623 ctx_exit_on_error(&stream->encoder, "Stream %d: Failed to encode frame",
1627 static void update_quantizer_histogram(struct stream_state *stream) {
1628 if (stream->config.cfg.g_pass != VPX_RC_FIRST_PASS) {
1631 vpx_codec_control(&stream->encoder, VP8E_GET_LAST_QUANTIZER_64, &q);
1632 ctx_exit_on_error(&stream->encoder, "Failed to read quantizer");
1633 stream->counts[q]++;
1637 static void get_cx_data(struct stream_state *stream,
1638 struct VpxEncoderConfig *global, int *got_data) {
1639 const vpx_codec_cx_pkt_t *pkt;
1640 const struct vpx_codec_enc_cfg *cfg = &stream->config.cfg;
1641 vpx_codec_iter_t iter = NULL;
1644 while ((pkt = vpx_codec_get_cx_data(&stream->encoder, &iter))) {
1645 static size_t fsize = 0;
1646 static int64_t ivf_header_pos = 0;
1648 switch (pkt->kind) {
1649 case VPX_CODEC_CX_FRAME_PKT:
1650 if (!(pkt->data.frame.flags & VPX_FRAME_IS_FRAGMENT)) {
1651 stream->frames_out++;
1654 fprintf(stderr, " %6luF", (unsigned long)pkt->data.frame.sz);
1656 update_rate_histogram(stream->rate_hist, cfg, pkt);
1658 if (stream->config.write_webm) {
1659 write_webm_block(&stream->webm_ctx, cfg, pkt);
1662 if (!stream->config.write_webm) {
1663 if (pkt->data.frame.partition_id <= 0) {
1664 ivf_header_pos = ftello(stream->file);
1665 fsize = pkt->data.frame.sz;
1667 ivf_write_frame_header(stream->file, pkt->data.frame.pts, fsize);
1669 fsize += pkt->data.frame.sz;
1671 if (!(pkt->data.frame.flags & VPX_FRAME_IS_FRAGMENT)) {
1672 const int64_t currpos = ftello(stream->file);
1673 fseeko(stream->file, ivf_header_pos, SEEK_SET);
1674 ivf_write_frame_size(stream->file, fsize);
1675 fseeko(stream->file, currpos, SEEK_SET);
1679 (void)fwrite(pkt->data.frame.buf, 1, pkt->data.frame.sz,
1682 stream->nbytes += pkt->data.raw.sz;
1686 if (global->test_decode != TEST_DECODE_OFF && !stream->mismatch_seen) {
1687 vpx_codec_decode(&stream->decoder, pkt->data.frame.buf,
1688 (unsigned int)pkt->data.frame.sz, NULL, 0);
1689 if (stream->decoder.err) {
1690 warn_or_exit_on_error(&stream->decoder,
1691 global->test_decode == TEST_DECODE_FATAL,
1692 "Failed to decode frame %d in stream %d",
1693 stream->frames_out + 1, stream->index);
1694 stream->mismatch_seen = stream->frames_out + 1;
1699 case VPX_CODEC_STATS_PKT:
1700 stream->frames_out++;
1701 stats_write(&stream->stats, pkt->data.twopass_stats.buf,
1702 pkt->data.twopass_stats.sz);
1703 stream->nbytes += pkt->data.raw.sz;
1705 #if CONFIG_FP_MB_STATS
1706 case VPX_CODEC_FPMB_STATS_PKT:
1707 stats_write(&stream->fpmb_stats, pkt->data.firstpass_mb_stats.buf,
1708 pkt->data.firstpass_mb_stats.sz);
1709 stream->nbytes += pkt->data.raw.sz;
1712 case VPX_CODEC_PSNR_PKT:
1714 if (global->show_psnr) {
1717 stream->psnr_sse_total += pkt->data.psnr.sse[0];
1718 stream->psnr_samples_total += pkt->data.psnr.samples[0];
1719 for (i = 0; i < 4; i++) {
1721 fprintf(stderr, "%.3f ", pkt->data.psnr.psnr[i]);
1722 stream->psnr_totals[i] += pkt->data.psnr.psnr[i];
1724 stream->psnr_count++;
1733 static void show_psnr(struct stream_state *stream, double peak) {
1737 if (!stream->psnr_count) return;
1739 fprintf(stderr, "Stream %d PSNR (Overall/Avg/Y/U/V)", stream->index);
1740 ovpsnr = sse_to_psnr((double)stream->psnr_samples_total, peak,
1741 (double)stream->psnr_sse_total);
1742 fprintf(stderr, " %.3f", ovpsnr);
1744 for (i = 0; i < 4; i++) {
1745 fprintf(stderr, " %.3f", stream->psnr_totals[i] / stream->psnr_count);
1747 fprintf(stderr, "\n");
1750 static float usec_to_fps(uint64_t usec, unsigned int frames) {
1751 return (float)(usec > 0 ? frames * 1000000.0 / (float)usec : 0);
1754 static void test_decode(struct stream_state *stream,
1755 enum TestDecodeFatality fatal,
1756 const VpxInterface *codec) {
1757 vpx_image_t enc_img, dec_img;
1759 if (stream->mismatch_seen) return;
1761 /* Get the internal reference frame */
1762 if (strcmp(codec->name, "vp8") == 0) {
1763 struct vpx_ref_frame ref_enc, ref_dec;
1766 width = (stream->config.cfg.g_w + 15) & ~15;
1767 height = (stream->config.cfg.g_h + 15) & ~15;
1768 vpx_img_alloc(&ref_enc.img, VPX_IMG_FMT_I420, width, height, 1);
1769 enc_img = ref_enc.img;
1770 vpx_img_alloc(&ref_dec.img, VPX_IMG_FMT_I420, width, height, 1);
1771 dec_img = ref_dec.img;
1773 ref_enc.frame_type = VP8_LAST_FRAME;
1774 ref_dec.frame_type = VP8_LAST_FRAME;
1775 vpx_codec_control(&stream->encoder, VP8_COPY_REFERENCE, &ref_enc);
1776 vpx_codec_control(&stream->decoder, VP8_COPY_REFERENCE, &ref_dec);
1778 struct vp9_ref_frame ref_enc, ref_dec;
1782 vpx_codec_control(&stream->encoder, VP9_GET_REFERENCE, &ref_enc);
1783 enc_img = ref_enc.img;
1784 vpx_codec_control(&stream->decoder, VP9_GET_REFERENCE, &ref_dec);
1785 dec_img = ref_dec.img;
1786 #if CONFIG_VP9_HIGHBITDEPTH
1787 if ((enc_img.fmt & VPX_IMG_FMT_HIGHBITDEPTH) !=
1788 (dec_img.fmt & VPX_IMG_FMT_HIGHBITDEPTH)) {
1789 if (enc_img.fmt & VPX_IMG_FMT_HIGHBITDEPTH) {
1790 vpx_img_alloc(&enc_img, enc_img.fmt - VPX_IMG_FMT_HIGHBITDEPTH,
1791 enc_img.d_w, enc_img.d_h, 16);
1792 vpx_img_truncate_16_to_8(&enc_img, &ref_enc.img);
1794 if (dec_img.fmt & VPX_IMG_FMT_HIGHBITDEPTH) {
1795 vpx_img_alloc(&dec_img, dec_img.fmt - VPX_IMG_FMT_HIGHBITDEPTH,
1796 dec_img.d_w, dec_img.d_h, 16);
1797 vpx_img_truncate_16_to_8(&dec_img, &ref_dec.img);
1802 ctx_exit_on_error(&stream->encoder, "Failed to get encoder reference frame");
1803 ctx_exit_on_error(&stream->decoder, "Failed to get decoder reference frame");
1805 if (!compare_img(&enc_img, &dec_img)) {
1806 int y[4], u[4], v[4];
1807 #if CONFIG_VP9_HIGHBITDEPTH
1808 if (enc_img.fmt & VPX_IMG_FMT_HIGHBITDEPTH) {
1809 find_mismatch_high(&enc_img, &dec_img, y, u, v);
1811 find_mismatch(&enc_img, &dec_img, y, u, v);
1814 find_mismatch(&enc_img, &dec_img, y, u, v);
1816 stream->decoder.err = 1;
1817 warn_or_exit_on_error(&stream->decoder, fatal == TEST_DECODE_FATAL,
1818 "Stream %d: Encode/decode mismatch on frame %d at"
1819 " Y[%d, %d] {%d/%d},"
1820 " U[%d, %d] {%d/%d},"
1821 " V[%d, %d] {%d/%d}",
1822 stream->index, stream->frames_out, y[0], y[1], y[2],
1823 y[3], u[0], u[1], u[2], u[3], v[0], v[1], v[2], v[3]);
1824 stream->mismatch_seen = stream->frames_out;
1827 vpx_img_free(&enc_img);
1828 vpx_img_free(&dec_img);
1831 static void print_time(const char *label, int64_t etl) {
1838 etl -= hours * 3600;
1843 fprintf(stderr, "[%3s %2" PRId64 ":%02" PRId64 ":%02" PRId64 "] ", label,
1846 fprintf(stderr, "[%3s unknown] ", label);
1850 int main(int argc, const char **argv_) {
1853 #if CONFIG_VP9_HIGHBITDEPTH
1854 vpx_image_t raw_shift;
1855 int allocated_raw_shift = 0;
1856 int use_16bit_internal = 0;
1857 int input_shift = 0;
1859 int frame_avail, got_data;
1861 struct VpxInputContext input;
1862 struct VpxEncoderConfig global;
1863 struct stream_state *streams = NULL;
1864 char **argv, **argi;
1865 uint64_t cx_time = 0;
1869 memset(&input, 0, sizeof(input));
1870 exec_name = argv_[0];
1872 if (argc < 3) usage_exit();
1874 /* Setup default input stream settings */
1875 input.framerate.numerator = 30;
1876 input.framerate.denominator = 1;
1877 input.only_i420 = 1;
1878 input.bit_depth = 0;
1880 /* First parse the global configuration values, because we want to apply
1881 * other parameters on top of the default configuration provided by the
1884 argv = argv_dup(argc - 1, argv_ + 1);
1885 parse_global_config(&global, argv);
1887 switch (global.color_type) {
1888 case I420: input.fmt = VPX_IMG_FMT_I420; break;
1889 case I422: input.fmt = VPX_IMG_FMT_I422; break;
1890 case I444: input.fmt = VPX_IMG_FMT_I444; break;
1891 case I440: input.fmt = VPX_IMG_FMT_I440; break;
1892 case YV12: input.fmt = VPX_IMG_FMT_YV12; break;
1896 /* Now parse each stream's parameters. Using a local scope here
1897 * due to the use of 'stream' as loop variable in FOREACH_STREAM
1900 struct stream_state *stream = NULL;
1903 stream = new_stream(&global, stream);
1905 if (!streams) streams = stream;
1906 } while (parse_stream_params(&global, stream, argv));
1909 /* Check for unrecognized options */
1910 for (argi = argv; *argi; argi++)
1911 if (argi[0][0] == '-' && argi[0][1])
1912 die("Error: Unrecognized option %s\n", *argi);
1914 FOREACH_STREAM(check_encoder_config(global.disable_warning_prompt, &global,
1915 &stream->config.cfg););
1917 /* Handle non-option arguments */
1918 input.filename = argv[0];
1920 if (!input.filename) usage_exit();
1922 /* Decide if other chroma subsamplings than 4:2:0 are supported */
1923 if (global.codec->fourcc == VP9_FOURCC) input.only_i420 = 0;
1925 for (pass = global.pass ? global.pass - 1 : 0; pass < global.passes; pass++) {
1926 int frames_in = 0, seen_frames = 0;
1927 int64_t estimated_time_left = -1;
1928 int64_t average_rate = -1;
1929 int64_t lagged_count = 0;
1931 open_input_file(&input);
1933 /* If the input file doesn't specify its w/h (raw files), try to get
1934 * the data from the first stream's configuration.
1936 if (!input.width || !input.height) {
1938 if (stream->config.cfg.g_w && stream->config.cfg.g_h) {
1939 input.width = stream->config.cfg.g_w;
1940 input.height = stream->config.cfg.g_h;
1946 /* Update stream configurations from the input file's parameters */
1947 if (!input.width || !input.height)
1949 "Specify stream dimensions with --width (-w) "
1950 " and --height (-h)");
1952 /* If input file does not specify bit-depth but input-bit-depth parameter
1953 * exists, assume that to be the input bit-depth. However, if the
1954 * input-bit-depth paramter does not exist, assume the input bit-depth
1955 * to be the same as the codec bit-depth.
1957 if (!input.bit_depth) {
1959 if (stream->config.cfg.g_input_bit_depth)
1960 input.bit_depth = stream->config.cfg.g_input_bit_depth;
1962 input.bit_depth = stream->config.cfg.g_input_bit_depth =
1963 (int)stream->config.cfg.g_bit_depth;
1965 if (input.bit_depth > 8) input.fmt |= VPX_IMG_FMT_HIGHBITDEPTH;
1968 { stream->config.cfg.g_input_bit_depth = input.bit_depth; });
1971 FOREACH_STREAM(set_stream_dimensions(stream, input.width, input.height));
1972 FOREACH_STREAM(validate_stream_config(stream, &global));
1974 /* Ensure that --passes and --pass are consistent. If --pass is set and
1975 * --passes=2, ensure --fpf was set.
1977 if (global.pass && global.passes == 2)
1979 if (!stream->config.stats_fn)
1981 "Stream %d: Must specify --fpf when --pass=%d"
1982 " and --passes=2\n",
1983 stream->index, global.pass);
1988 if (stream->config.write_webm) {
1989 stream->config.write_webm = 0;
1991 "vpxenc was compiled without WebM container support."
1992 "Producing IVF output");
1997 /* Use the frame rate from the file only if none was specified
1998 * on the command-line.
2000 if (!global.have_framerate) {
2001 global.framerate.num = input.framerate.numerator;
2002 global.framerate.den = input.framerate.denominator;
2003 FOREACH_STREAM(stream->config.cfg.g_timebase.den = global.framerate.num;
2004 stream->config.cfg.g_timebase.num = global.framerate.den);
2007 /* Show configuration */
2008 if (global.verbose && pass == 0)
2009 FOREACH_STREAM(show_stream_config(stream, &global, &input));
2011 if (pass == (global.pass ? global.pass - 1 : 0)) {
2012 if (input.file_type == FILE_TYPE_Y4M)
2013 /*The Y4M reader does its own allocation.
2014 Just initialize this here to avoid problems if we never read any
2016 memset(&raw, 0, sizeof(raw));
2018 vpx_img_alloc(&raw, input.fmt, input.width, input.height, 32);
2020 FOREACH_STREAM(stream->rate_hist = init_rate_histogram(
2021 &stream->config.cfg, &global.framerate));
2024 FOREACH_STREAM(setup_pass(stream, &global, pass));
2026 open_output_file(stream, &global, &input.pixel_aspect_ratio));
2027 FOREACH_STREAM(initialize_encoder(stream, &global));
2029 #if CONFIG_VP9_HIGHBITDEPTH
2030 if (strcmp(global.codec->name, "vp9") == 0) {
2031 // Check to see if at least one stream uses 16 bit internal.
2032 // Currently assume that the bit_depths for all streams using
2033 // highbitdepth are the same.
2035 if (stream->config.use_16bit_internal) {
2036 use_16bit_internal = 1;
2038 if (stream->config.cfg.g_profile == 0) {
2041 input_shift = (int)stream->config.cfg.g_bit_depth -
2042 stream->config.cfg.g_input_bit_depth;
2051 while (frame_avail || got_data) {
2052 struct vpx_usec_timer timer;
2054 if (!global.limit || frames_in < global.limit) {
2055 frame_avail = read_frame(&input, &raw);
2057 if (frame_avail) frames_in++;
2059 frames_in > global.skip_frames ? frames_in - global.skip_frames : 0;
2061 if (!global.quiet) {
2062 float fps = usec_to_fps(cx_time, seen_frames);
2063 fprintf(stderr, "\rPass %d/%d ", pass + 1, global.passes);
2065 if (stream_cnt == 1)
2066 fprintf(stderr, "frame %4d/%-4d %7" PRId64 "B ", frames_in,
2067 streams->frames_out, (int64_t)streams->nbytes);
2069 fprintf(stderr, "frame %4d ", frames_in);
2071 fprintf(stderr, "%7" PRId64 " %s %.2f %s ",
2072 cx_time > 9999999 ? cx_time / 1000 : cx_time,
2073 cx_time > 9999999 ? "ms" : "us", fps >= 1.0 ? fps : fps * 60,
2074 fps >= 1.0 ? "fps" : "fpm");
2075 print_time("ETA", estimated_time_left);
2081 if (frames_in > global.skip_frames) {
2082 #if CONFIG_VP9_HIGHBITDEPTH
2083 vpx_image_t *frame_to_encode;
2084 if (input_shift || (use_16bit_internal && input.bit_depth == 8)) {
2085 assert(use_16bit_internal);
2086 // Input bit depth and stream bit depth do not match, so up
2087 // shift frame to stream bit depth
2088 if (!allocated_raw_shift) {
2089 vpx_img_alloc(&raw_shift, raw.fmt | VPX_IMG_FMT_HIGHBITDEPTH,
2090 input.width, input.height, 32);
2091 allocated_raw_shift = 1;
2093 vpx_img_upshift(&raw_shift, &raw, input_shift);
2094 frame_to_encode = &raw_shift;
2096 frame_to_encode = &raw;
2098 vpx_usec_timer_start(&timer);
2099 if (use_16bit_internal) {
2100 assert(frame_to_encode->fmt & VPX_IMG_FMT_HIGHBITDEPTH);
2102 if (stream->config.use_16bit_internal)
2103 encode_frame(stream, &global,
2104 frame_avail ? frame_to_encode : NULL, frames_in);
2109 assert((frame_to_encode->fmt & VPX_IMG_FMT_HIGHBITDEPTH) == 0);
2110 FOREACH_STREAM(encode_frame(stream, &global,
2111 frame_avail ? frame_to_encode : NULL,
2115 vpx_usec_timer_start(&timer);
2116 FOREACH_STREAM(encode_frame(stream, &global, frame_avail ? &raw : NULL,
2119 vpx_usec_timer_mark(&timer);
2120 cx_time += vpx_usec_timer_elapsed(&timer);
2122 FOREACH_STREAM(update_quantizer_histogram(stream));
2125 FOREACH_STREAM(get_cx_data(stream, &global, &got_data));
2127 if (!got_data && input.length && streams != NULL &&
2128 !streams->frames_out) {
2129 lagged_count = global.limit ? seen_frames : ftello(input.file);
2130 } else if (input.length) {
2135 const int64_t frame_in_lagged = (seen_frames - lagged_count) * 1000;
2137 rate = cx_time ? frame_in_lagged * (int64_t)1000000 / cx_time : 0;
2138 remaining = 1000 * (global.limit - global.skip_frames -
2139 seen_frames + lagged_count);
2141 const int64_t input_pos = ftello(input.file);
2142 const int64_t input_pos_lagged = input_pos - lagged_count;
2143 const int64_t limit = input.length;
2145 rate = cx_time ? input_pos_lagged * (int64_t)1000000 / cx_time : 0;
2146 remaining = limit - input_pos + lagged_count;
2150 (average_rate <= 0) ? rate : (average_rate * 7 + rate) / 8;
2151 estimated_time_left = average_rate ? remaining / average_rate : -1;
2154 if (got_data && global.test_decode != TEST_DECODE_OFF)
2155 FOREACH_STREAM(test_decode(stream, global.test_decode, global.codec));
2159 if (!global.quiet) fprintf(stderr, "\033[K");
2162 if (stream_cnt > 1) fprintf(stderr, "\n");
2164 if (!global.quiet) {
2165 FOREACH_STREAM(fprintf(
2166 stderr, "\rPass %d/%d frame %4d/%-4d %7" PRId64 "B %7" PRId64
2167 "b/f %7" PRId64 "b/s"
2168 " %7" PRId64 " %s (%.2f fps)\033[K\n",
2169 pass + 1, global.passes, frames_in, stream->frames_out,
2170 (int64_t)stream->nbytes,
2171 seen_frames ? (int64_t)(stream->nbytes * 8 / seen_frames) : 0,
2173 ? (int64_t)stream->nbytes * 8 * (int64_t)global.framerate.num /
2174 global.framerate.den / seen_frames
2176 stream->cx_time > 9999999 ? stream->cx_time / 1000 : stream->cx_time,
2177 stream->cx_time > 9999999 ? "ms" : "us",
2178 usec_to_fps(stream->cx_time, seen_frames)));
2181 if (global.show_psnr) {
2182 if (global.codec->fourcc == VP9_FOURCC) {
2184 show_psnr(stream, (1 << stream->config.cfg.g_input_bit_depth) - 1));
2186 FOREACH_STREAM(show_psnr(stream, 255.0));
2190 FOREACH_STREAM(vpx_codec_destroy(&stream->encoder));
2192 if (global.test_decode != TEST_DECODE_OFF) {
2193 FOREACH_STREAM(vpx_codec_destroy(&stream->decoder));
2196 close_input_file(&input);
2198 if (global.test_decode == TEST_DECODE_FATAL) {
2199 FOREACH_STREAM(res |= stream->mismatch_seen);
2201 FOREACH_STREAM(close_output_file(stream, global.codec->fourcc));
2203 FOREACH_STREAM(stats_close(&stream->stats, global.passes - 1));
2205 #if CONFIG_FP_MB_STATS
2206 FOREACH_STREAM(stats_close(&stream->fpmb_stats, global.passes - 1));
2209 if (global.pass) break;
2212 if (global.show_q_hist_buckets)
2214 show_q_histogram(stream->counts, global.show_q_hist_buckets));
2216 if (global.show_rate_hist_buckets)
2217 FOREACH_STREAM(show_rate_histogram(stream->rate_hist, &stream->config.cfg,
2218 global.show_rate_hist_buckets));
2219 FOREACH_STREAM(destroy_rate_histogram(stream->rate_hist));
2221 #if CONFIG_INTERNAL_STATS
2222 /* TODO(jkoleszar): This doesn't belong in this executable. Do it for now,
2223 * to match some existing utilities.
2225 if (!(global.pass == 1 && global.passes == 2))
2227 FILE *f = fopen("opsnr.stt", "a");
2228 if (stream->mismatch_seen) {
2229 fprintf(f, "First mismatch occurred in frame %d\n",
2230 stream->mismatch_seen);
2232 fprintf(f, "No mismatch detected in recon buffers\n");
2238 #if CONFIG_VP9_HIGHBITDEPTH
2239 if (allocated_raw_shift) vpx_img_free(&raw_shift);
2244 return res ? EXIT_FAILURE : EXIT_SUCCESS;