adjust rtc setting and threshold
[aom.git] / vpxenc.c
blob944dfa8b5d119ede32b1da525139b2ea71b57fd8
1 /*
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.
9 */
11 #include "./vpxenc.h"
12 #include "./vpx_config.h"
14 #include <assert.h>
15 #include <limits.h>
16 #include <math.h>
17 #include <stdarg.h>
18 #include <stdio.h>
19 #include <stdlib.h>
20 #include <string.h>
22 #if CONFIG_LIBYUV
23 #include "third_party/libyuv/include/libyuv/scale.h"
24 #endif
26 #include "vpx/vpx_encoder.h"
27 #if CONFIG_DECODERS
28 #include "vpx/vpx_decoder.h"
29 #endif
31 #include "./args.h"
32 #include "./ivfenc.h"
33 #include "./tools_common.h"
35 #if CONFIG_VP8_ENCODER || CONFIG_VP9_ENCODER
36 #include "vpx/vp8cx.h"
37 #endif
38 #if CONFIG_VP8_DECODER || CONFIG_VP9_DECODER
39 #include "vpx/vp8dx.h"
40 #endif
42 #include "vpx/vpx_integer.h"
43 #include "vpx_ports/mem_ops.h"
44 #include "vpx_ports/vpx_timer.h"
45 #include "./rate_hist.h"
46 #include "./vpxstats.h"
47 #include "./warnings.h"
48 #if CONFIG_WEBM_IO
49 #include "./webmenc.h"
50 #endif
51 #include "./y4minput.h"
53 /* Swallow warnings about unused results of fread/fwrite */
54 static size_t wrap_fread(void *ptr, size_t size, size_t nmemb,
55 FILE *stream) {
56 return fread(ptr, size, nmemb, stream);
58 #define fread wrap_fread
60 static size_t wrap_fwrite(const void *ptr, size_t size, size_t nmemb,
61 FILE *stream) {
62 return fwrite(ptr, size, nmemb, stream);
64 #define fwrite wrap_fwrite
67 static const char *exec_name;
69 static void warn_or_exit_on_errorv(vpx_codec_ctx_t *ctx, int fatal,
70 const char *s, va_list ap) {
71 if (ctx->err) {
72 const char *detail = vpx_codec_error_detail(ctx);
74 vfprintf(stderr, s, ap);
75 fprintf(stderr, ": %s\n", vpx_codec_error(ctx));
77 if (detail)
78 fprintf(stderr, " %s\n", detail);
80 if (fatal)
81 exit(EXIT_FAILURE);
85 static void ctx_exit_on_error(vpx_codec_ctx_t *ctx, const char *s, ...) {
86 va_list ap;
88 va_start(ap, s);
89 warn_or_exit_on_errorv(ctx, 1, s, ap);
90 va_end(ap);
93 static void warn_or_exit_on_error(vpx_codec_ctx_t *ctx, int fatal,
94 const char *s, ...) {
95 va_list ap;
97 va_start(ap, s);
98 warn_or_exit_on_errorv(ctx, fatal, s, ap);
99 va_end(ap);
102 int read_frame(struct VpxInputContext *input_ctx, vpx_image_t *img) {
103 FILE *f = input_ctx->file;
104 y4m_input *y4m = &input_ctx->y4m;
105 int shortread = 0;
107 if (input_ctx->file_type == FILE_TYPE_Y4M) {
108 if (y4m_input_fetch_frame(y4m, f, img) < 1)
109 return 0;
110 } else {
111 shortread = read_yuv_frame(input_ctx, img);
114 return !shortread;
117 int file_is_y4m(const char detect[4]) {
118 if (memcmp(detect, "YUV4", 4) == 0) {
119 return 1;
121 return 0;
124 int fourcc_is_ivf(const char detect[4]) {
125 if (memcmp(detect, "DKIF", 4) == 0) {
126 return 1;
128 return 0;
131 static const arg_def_t debugmode = ARG_DEF(
132 "D", "debug", 0, "Debug mode (makes output deterministic)");
133 static const arg_def_t outputfile = ARG_DEF(
134 "o", "output", 1, "Output filename");
135 static const arg_def_t use_yv12 = ARG_DEF(
136 NULL, "yv12", 0, "Input file is YV12 ");
137 static const arg_def_t use_i420 = ARG_DEF(
138 NULL, "i420", 0, "Input file is I420 (default)");
139 static const arg_def_t use_i422 = ARG_DEF(
140 NULL, "i422", 0, "Input file is I422");
141 static const arg_def_t use_i444 = ARG_DEF(
142 NULL, "i444", 0, "Input file is I444");
143 static const arg_def_t use_i440 = ARG_DEF(
144 NULL, "i440", 0, "Input file is I440");
145 static const arg_def_t codecarg = ARG_DEF(
146 NULL, "codec", 1, "Codec to use");
147 static const arg_def_t passes = ARG_DEF(
148 "p", "passes", 1, "Number of passes (1/2)");
149 static const arg_def_t pass_arg = ARG_DEF(
150 NULL, "pass", 1, "Pass to execute (1/2)");
151 static const arg_def_t fpf_name = ARG_DEF(
152 NULL, "fpf", 1, "First pass statistics file name");
153 #if CONFIG_FP_MB_STATS
154 static const arg_def_t fpmbf_name = ARG_DEF(
155 NULL, "fpmbf", 1, "First pass block statistics file name");
156 #endif
157 static const arg_def_t limit = ARG_DEF(
158 NULL, "limit", 1, "Stop encoding after n input frames");
159 static const arg_def_t skip = ARG_DEF(
160 NULL, "skip", 1, "Skip the first n input frames");
161 static const arg_def_t deadline = ARG_DEF(
162 "d", "deadline", 1, "Deadline per frame (usec)");
163 static const arg_def_t best_dl = ARG_DEF(
164 NULL, "best", 0, "Use Best Quality Deadline");
165 static const arg_def_t good_dl = ARG_DEF(
166 NULL, "good", 0, "Use Good Quality Deadline");
167 static const arg_def_t rt_dl = ARG_DEF(
168 NULL, "rt", 0, "Use Realtime Quality Deadline");
169 static const arg_def_t quietarg = ARG_DEF(
170 "q", "quiet", 0, "Do not print encode progress");
171 static const arg_def_t verbosearg = ARG_DEF(
172 "v", "verbose", 0, "Show encoder parameters");
173 static const arg_def_t psnrarg = ARG_DEF(
174 NULL, "psnr", 0, "Show PSNR in status line");
176 static const struct arg_enum_list test_decode_enum[] = {
177 {"off", TEST_DECODE_OFF},
178 {"fatal", TEST_DECODE_FATAL},
179 {"warn", TEST_DECODE_WARN},
180 {NULL, 0}
182 static const arg_def_t recontest = ARG_DEF_ENUM(
183 NULL, "test-decode", 1, "Test encode/decode mismatch", test_decode_enum);
184 static const arg_def_t framerate = ARG_DEF(
185 NULL, "fps", 1, "Stream frame rate (rate/scale)");
186 static const arg_def_t use_ivf = ARG_DEF(
187 NULL, "ivf", 0, "Output IVF (default is WebM if WebM IO is enabled)");
188 static const arg_def_t out_part = ARG_DEF(
189 "P", "output-partitions", 0,
190 "Makes encoder output partitions. Requires IVF output!");
191 static const arg_def_t q_hist_n = ARG_DEF(
192 NULL, "q-hist", 1, "Show quantizer histogram (n-buckets)");
193 static const arg_def_t rate_hist_n = ARG_DEF(
194 NULL, "rate-hist", 1, "Show rate histogram (n-buckets)");
195 static const arg_def_t disable_warnings = ARG_DEF(
196 NULL, "disable-warnings", 0,
197 "Disable warnings about potentially incorrect encode settings.");
198 static const arg_def_t disable_warning_prompt = ARG_DEF(
199 "y", "disable-warning-prompt", 0,
200 "Display warnings, but do not prompt user to continue.");
202 #if CONFIG_VP9 && CONFIG_VP9_HIGHBITDEPTH
203 static const arg_def_t test16bitinternalarg = ARG_DEF(
204 NULL, "test-16bit-internal", 0, "Force use of 16 bit internal buffer");
205 #endif
207 static const arg_def_t *main_args[] = {
208 &debugmode,
209 &outputfile, &codecarg, &passes, &pass_arg, &fpf_name, &limit, &skip,
210 &deadline, &best_dl, &good_dl, &rt_dl,
211 &quietarg, &verbosearg, &psnrarg, &use_ivf, &out_part, &q_hist_n,
212 &rate_hist_n, &disable_warnings, &disable_warning_prompt,
213 NULL
216 static const arg_def_t usage = ARG_DEF(
217 "u", "usage", 1, "Usage profile number to use");
218 static const arg_def_t threads = ARG_DEF(
219 "t", "threads", 1, "Max number of threads to use");
220 static const arg_def_t profile = ARG_DEF(
221 NULL, "profile", 1, "Bitstream profile number to use");
222 static const arg_def_t width = ARG_DEF("w", "width", 1, "Frame width");
223 static const arg_def_t height = ARG_DEF("h", "height", 1, "Frame height");
224 #if CONFIG_WEBM_IO
225 static const struct arg_enum_list stereo_mode_enum[] = {
226 {"mono", STEREO_FORMAT_MONO},
227 {"left-right", STEREO_FORMAT_LEFT_RIGHT},
228 {"bottom-top", STEREO_FORMAT_BOTTOM_TOP},
229 {"top-bottom", STEREO_FORMAT_TOP_BOTTOM},
230 {"right-left", STEREO_FORMAT_RIGHT_LEFT},
231 {NULL, 0}
233 static const arg_def_t stereo_mode = ARG_DEF_ENUM(
234 NULL, "stereo-mode", 1, "Stereo 3D video format", stereo_mode_enum);
235 #endif
236 static const arg_def_t timebase = ARG_DEF(
237 NULL, "timebase", 1, "Output timestamp precision (fractional seconds)");
238 static const arg_def_t error_resilient = ARG_DEF(
239 NULL, "error-resilient", 1, "Enable error resiliency features");
240 static const arg_def_t lag_in_frames = ARG_DEF(
241 NULL, "lag-in-frames", 1, "Max number of frames to lag");
243 static const arg_def_t *global_args[] = {
244 &use_yv12, &use_i420, &use_i422, &use_i444, &use_i440,
245 &usage, &threads, &profile,
246 &width, &height,
247 #if CONFIG_WEBM_IO
248 &stereo_mode,
249 #endif
250 &timebase, &framerate,
251 &error_resilient,
252 #if CONFIG_VP9 && CONFIG_VP9_HIGHBITDEPTH
253 &test16bitinternalarg,
254 #endif
255 &lag_in_frames, NULL
258 static const arg_def_t dropframe_thresh = ARG_DEF(
259 NULL, "drop-frame", 1, "Temporal resampling threshold (buf %)");
260 static const arg_def_t resize_allowed = ARG_DEF(
261 NULL, "resize-allowed", 1, "Spatial resampling enabled (bool)");
262 static const arg_def_t resize_width = ARG_DEF(
263 NULL, "resize-width", 1, "Width of encoded frame");
264 static const arg_def_t resize_height = ARG_DEF(
265 NULL, "resize-height", 1, "Height of encoded frame");
266 static const arg_def_t resize_up_thresh = ARG_DEF(
267 NULL, "resize-up", 1, "Upscale threshold (buf %)");
268 static const arg_def_t resize_down_thresh = ARG_DEF(
269 NULL, "resize-down", 1, "Downscale threshold (buf %)");
270 static const struct arg_enum_list end_usage_enum[] = {
271 {"vbr", VPX_VBR},
272 {"cbr", VPX_CBR},
273 {"cq", VPX_CQ},
274 {"q", VPX_Q},
275 {NULL, 0}
277 static const arg_def_t end_usage = ARG_DEF_ENUM(
278 NULL, "end-usage", 1, "Rate control mode", end_usage_enum);
279 static const arg_def_t target_bitrate = ARG_DEF(
280 NULL, "target-bitrate", 1, "Bitrate (kbps)");
281 static const arg_def_t min_quantizer = ARG_DEF(
282 NULL, "min-q", 1, "Minimum (best) quantizer");
283 static const arg_def_t max_quantizer = ARG_DEF(
284 NULL, "max-q", 1, "Maximum (worst) quantizer");
285 static const arg_def_t undershoot_pct = ARG_DEF(
286 NULL, "undershoot-pct", 1, "Datarate undershoot (min) target (%)");
287 static const arg_def_t overshoot_pct = ARG_DEF(
288 NULL, "overshoot-pct", 1, "Datarate overshoot (max) target (%)");
289 static const arg_def_t buf_sz = ARG_DEF(
290 NULL, "buf-sz", 1, "Client buffer size (ms)");
291 static const arg_def_t buf_initial_sz = ARG_DEF(
292 NULL, "buf-initial-sz", 1, "Client initial buffer size (ms)");
293 static const arg_def_t buf_optimal_sz = ARG_DEF(
294 NULL, "buf-optimal-sz", 1, "Client optimal buffer size (ms)");
295 static const arg_def_t *rc_args[] = {
296 &dropframe_thresh, &resize_allowed, &resize_width, &resize_height,
297 &resize_up_thresh, &resize_down_thresh, &end_usage, &target_bitrate,
298 &min_quantizer, &max_quantizer, &undershoot_pct, &overshoot_pct, &buf_sz,
299 &buf_initial_sz, &buf_optimal_sz, NULL
303 static const arg_def_t bias_pct = ARG_DEF(
304 NULL, "bias-pct", 1, "CBR/VBR bias (0=CBR, 100=VBR)");
305 static const arg_def_t minsection_pct = ARG_DEF(
306 NULL, "minsection-pct", 1, "GOP min bitrate (% of target)");
307 static const arg_def_t maxsection_pct = ARG_DEF(
308 NULL, "maxsection-pct", 1, "GOP max bitrate (% of target)");
309 static const arg_def_t *rc_twopass_args[] = {
310 &bias_pct, &minsection_pct, &maxsection_pct, NULL
314 static const arg_def_t kf_min_dist = ARG_DEF(
315 NULL, "kf-min-dist", 1, "Minimum keyframe interval (frames)");
316 static const arg_def_t kf_max_dist = ARG_DEF(
317 NULL, "kf-max-dist", 1, "Maximum keyframe interval (frames)");
318 static const arg_def_t kf_disabled = ARG_DEF(
319 NULL, "disable-kf", 0, "Disable keyframe placement");
320 static const arg_def_t *kf_args[] = {
321 &kf_min_dist, &kf_max_dist, &kf_disabled, NULL
325 static const arg_def_t noise_sens = ARG_DEF(
326 NULL, "noise-sensitivity", 1, "Noise sensitivity (frames to blur)");
327 static const arg_def_t sharpness = ARG_DEF(
328 NULL, "sharpness", 1, "Loop filter sharpness (0..7)");
329 static const arg_def_t static_thresh = ARG_DEF(
330 NULL, "static-thresh", 1, "Motion detection threshold");
331 static const arg_def_t cpu_used_vp8 = ARG_DEF(
332 NULL, "cpu-used", 1, "CPU Used (-16..16)");
333 static const arg_def_t cpu_used_vp9 = ARG_DEF(
334 NULL, "cpu-used", 1, "CPU Used (-8..8)");
335 static const arg_def_t auto_altref = ARG_DEF(
336 NULL, "auto-alt-ref", 1, "Enable automatic alt reference frames");
337 static const arg_def_t arnr_maxframes = ARG_DEF(
338 NULL, "arnr-maxframes", 1, "AltRef max frames (0..15)");
339 static const arg_def_t arnr_strength = ARG_DEF(
340 NULL, "arnr-strength", 1, "AltRef filter strength (0..6)");
341 static const arg_def_t arnr_type = ARG_DEF(
342 NULL, "arnr-type", 1, "AltRef type");
343 static const struct arg_enum_list tuning_enum[] = {
344 {"psnr", VP8_TUNE_PSNR},
345 {"ssim", VP8_TUNE_SSIM},
346 {NULL, 0}
348 static const arg_def_t tune_ssim = ARG_DEF_ENUM(
349 NULL, "tune", 1, "Material to favor", tuning_enum);
350 static const arg_def_t cq_level = ARG_DEF(
351 NULL, "cq-level", 1, "Constant/Constrained Quality level");
352 static const arg_def_t max_intra_rate_pct = ARG_DEF(
353 NULL, "max-intra-rate", 1, "Max I-frame bitrate (pct)");
354 static const arg_def_t max_inter_rate_pct = ARG_DEF(
355 NULL, "max-inter-rate", 1, "Max P-frame bitrate (pct)");
356 static const arg_def_t gf_cbr_boost_pct = ARG_DEF(
357 NULL, "gf-cbr-boost", 1, "Boost for Golden Frame in CBR mode (pct)");
359 static const arg_def_t screen_content_mode = ARG_DEF(NULL, "screen-content-mode", 1,
360 "Screen content mode");
362 #if CONFIG_VP8_ENCODER
363 static const arg_def_t token_parts = ARG_DEF(
364 NULL, "token-parts", 1, "Number of token partitions to use, log2");
365 static const arg_def_t *vp8_args[] = {
366 &cpu_used_vp8, &auto_altref, &noise_sens, &sharpness, &static_thresh,
367 &token_parts, &arnr_maxframes, &arnr_strength, &arnr_type,
368 &tune_ssim, &cq_level, &max_intra_rate_pct, &screen_content_mode,
369 NULL
371 static const int vp8_arg_ctrl_map[] = {
372 VP8E_SET_CPUUSED, VP8E_SET_ENABLEAUTOALTREF,
373 VP8E_SET_NOISE_SENSITIVITY, VP8E_SET_SHARPNESS, VP8E_SET_STATIC_THRESHOLD,
374 VP8E_SET_TOKEN_PARTITIONS,
375 VP8E_SET_ARNR_MAXFRAMES, VP8E_SET_ARNR_STRENGTH, VP8E_SET_ARNR_TYPE,
376 VP8E_SET_TUNING, VP8E_SET_CQ_LEVEL, VP8E_SET_MAX_INTRA_BITRATE_PCT,
377 VP8E_SET_SCREEN_CONTENT_MODE,
380 #endif
382 #if CONFIG_VP9_ENCODER
383 static const arg_def_t tile_cols = ARG_DEF(
384 NULL, "tile-columns", 1, "Number of tile columns to use, log2");
385 static const arg_def_t tile_rows = ARG_DEF(
386 NULL, "tile-rows", 1, "Number of tile rows to use, log2");
387 static const arg_def_t lossless = ARG_DEF(
388 NULL, "lossless", 1, "Lossless mode");
389 static const arg_def_t frame_parallel_decoding = ARG_DEF(
390 NULL, "frame-parallel", 1, "Enable frame parallel decodability features");
391 static const arg_def_t aq_mode = ARG_DEF(
392 NULL, "aq-mode", 1,
393 "Adaptive quantization mode (0: off (default), 1: variance 2: complexity, "
394 "3: cyclic refresh)");
395 static const arg_def_t frame_periodic_boost = ARG_DEF(
396 NULL, "frame-boost", 1,
397 "Enable frame periodic boost (0: off (default), 1: on)");
399 #if CONFIG_VP9 && CONFIG_VP9_HIGHBITDEPTH
400 static const struct arg_enum_list bitdepth_enum[] = {
401 {"8", VPX_BITS_8},
402 {"10", VPX_BITS_10},
403 {"12", VPX_BITS_12},
404 {NULL, 0}
407 static const arg_def_t bitdeptharg = ARG_DEF_ENUM(
408 "b", "bit-depth", 1,
409 "Bit depth for codec (8 for version <=1, 10 or 12 for version 2)",
410 bitdepth_enum);
411 static const arg_def_t inbitdeptharg = ARG_DEF(
412 NULL, "input-bit-depth", 1, "Bit depth of input");
413 #endif
415 static const struct arg_enum_list tune_content_enum[] = {
416 {"default", VP9E_CONTENT_DEFAULT},
417 {"screen", VP9E_CONTENT_SCREEN},
418 {NULL, 0}
421 static const arg_def_t tune_content = ARG_DEF_ENUM(
422 NULL, "tune-content", 1, "Tune content type", tune_content_enum);
424 static const arg_def_t *vp9_args[] = {
425 &cpu_used_vp9, &auto_altref, &sharpness, &static_thresh,
426 &tile_cols, &tile_rows, &arnr_maxframes, &arnr_strength, &arnr_type,
427 &tune_ssim, &cq_level, &max_intra_rate_pct, &max_inter_rate_pct,
428 &gf_cbr_boost_pct, &lossless,
429 &frame_parallel_decoding, &aq_mode, &frame_periodic_boost,
430 &noise_sens, &tune_content,
431 #if CONFIG_VP9 && CONFIG_VP9_HIGHBITDEPTH
432 &bitdeptharg, &inbitdeptharg,
433 #endif
434 NULL
436 static const int vp9_arg_ctrl_map[] = {
437 VP8E_SET_CPUUSED, VP8E_SET_ENABLEAUTOALTREF,
438 VP8E_SET_SHARPNESS, VP8E_SET_STATIC_THRESHOLD,
439 VP9E_SET_TILE_COLUMNS, VP9E_SET_TILE_ROWS,
440 VP8E_SET_ARNR_MAXFRAMES, VP8E_SET_ARNR_STRENGTH, VP8E_SET_ARNR_TYPE,
441 VP8E_SET_TUNING, VP8E_SET_CQ_LEVEL, VP8E_SET_MAX_INTRA_BITRATE_PCT,
442 VP8E_SET_MAX_INTER_BITRATE_PCT, VP8E_SET_GF_CBR_BOOST_PCT,
443 VP9E_SET_LOSSLESS, VP9E_SET_FRAME_PARALLEL_DECODING, VP9E_SET_AQ_MODE,
444 VP9E_SET_FRAME_PERIODIC_BOOST, VP9E_SET_NOISE_SENSITIVITY,
445 VP9E_SET_TUNE_CONTENT, VP9E_SET_COLOR_SPACE,
448 #endif
450 static const arg_def_t *no_args[] = { NULL };
452 void usage_exit() {
453 int i;
455 fprintf(stderr, "Usage: %s <options> -o dst_filename src_filename \n",
456 exec_name);
458 fprintf(stderr, "\nOptions:\n");
459 arg_show_usage(stderr, main_args);
460 fprintf(stderr, "\nEncoder Global Options:\n");
461 arg_show_usage(stderr, global_args);
462 fprintf(stderr, "\nRate Control Options:\n");
463 arg_show_usage(stderr, rc_args);
464 fprintf(stderr, "\nTwopass Rate Control Options:\n");
465 arg_show_usage(stderr, rc_twopass_args);
466 fprintf(stderr, "\nKeyframe Placement Options:\n");
467 arg_show_usage(stderr, kf_args);
468 #if CONFIG_VP8_ENCODER
469 fprintf(stderr, "\nVP8 Specific Options:\n");
470 arg_show_usage(stderr, vp8_args);
471 #endif
472 #if CONFIG_VP9_ENCODER
473 fprintf(stderr, "\nVP9 Specific Options:\n");
474 arg_show_usage(stderr, vp9_args);
475 #endif
476 fprintf(stderr, "\nStream timebase (--timebase):\n"
477 " The desired precision of timestamps in the output, expressed\n"
478 " in fractional seconds. Default is 1/1000.\n");
479 fprintf(stderr, "\nIncluded encoders:\n\n");
481 for (i = 0; i < get_vpx_encoder_count(); ++i) {
482 const VpxInterface *const encoder = get_vpx_encoder_by_index(i);
483 fprintf(stderr, " %-6s - %s\n",
484 encoder->name, vpx_codec_iface_name(encoder->codec_interface()));
487 exit(EXIT_FAILURE);
490 #define mmin(a, b) ((a) < (b) ? (a) : (b))
492 #if CONFIG_VP9 && CONFIG_VP9_HIGHBITDEPTH
493 static void find_mismatch_high(const vpx_image_t *const img1,
494 const vpx_image_t *const img2,
495 int yloc[4], int uloc[4], int vloc[4]) {
496 uint16_t *plane1, *plane2;
497 uint32_t stride1, stride2;
498 const uint32_t bsize = 64;
499 const uint32_t bsizey = bsize >> img1->y_chroma_shift;
500 const uint32_t bsizex = bsize >> img1->x_chroma_shift;
501 const uint32_t c_w =
502 (img1->d_w + img1->x_chroma_shift) >> img1->x_chroma_shift;
503 const uint32_t c_h =
504 (img1->d_h + img1->y_chroma_shift) >> img1->y_chroma_shift;
505 int match = 1;
506 uint32_t i, j;
507 yloc[0] = yloc[1] = yloc[2] = yloc[3] = -1;
508 plane1 = (uint16_t*)img1->planes[VPX_PLANE_Y];
509 plane2 = (uint16_t*)img2->planes[VPX_PLANE_Y];
510 stride1 = img1->stride[VPX_PLANE_Y]/2;
511 stride2 = img2->stride[VPX_PLANE_Y]/2;
512 for (i = 0, match = 1; match && i < img1->d_h; i += bsize) {
513 for (j = 0; match && j < img1->d_w; j += bsize) {
514 int k, l;
515 const int si = mmin(i + bsize, img1->d_h) - i;
516 const int sj = mmin(j + bsize, img1->d_w) - j;
517 for (k = 0; match && k < si; ++k) {
518 for (l = 0; match && l < sj; ++l) {
519 if (*(plane1 + (i + k) * stride1 + j + l) !=
520 *(plane2 + (i + k) * stride2 + j + l)) {
521 yloc[0] = i + k;
522 yloc[1] = j + l;
523 yloc[2] = *(plane1 + (i + k) * stride1 + j + l);
524 yloc[3] = *(plane2 + (i + k) * stride2 + j + l);
525 match = 0;
526 break;
533 uloc[0] = uloc[1] = uloc[2] = uloc[3] = -1;
534 plane1 = (uint16_t*)img1->planes[VPX_PLANE_U];
535 plane2 = (uint16_t*)img2->planes[VPX_PLANE_U];
536 stride1 = img1->stride[VPX_PLANE_U]/2;
537 stride2 = img2->stride[VPX_PLANE_U]/2;
538 for (i = 0, match = 1; match && i < c_h; i += bsizey) {
539 for (j = 0; match && j < c_w; j += bsizex) {
540 int k, l;
541 const int si = mmin(i + bsizey, c_h - i);
542 const int sj = mmin(j + bsizex, c_w - j);
543 for (k = 0; match && k < si; ++k) {
544 for (l = 0; match && l < sj; ++l) {
545 if (*(plane1 + (i + k) * stride1 + j + l) !=
546 *(plane2 + (i + k) * stride2 + j + l)) {
547 uloc[0] = i + k;
548 uloc[1] = j + l;
549 uloc[2] = *(plane1 + (i + k) * stride1 + j + l);
550 uloc[3] = *(plane2 + (i + k) * stride2 + j + l);
551 match = 0;
552 break;
559 vloc[0] = vloc[1] = vloc[2] = vloc[3] = -1;
560 plane1 = (uint16_t*)img1->planes[VPX_PLANE_V];
561 plane2 = (uint16_t*)img2->planes[VPX_PLANE_V];
562 stride1 = img1->stride[VPX_PLANE_V]/2;
563 stride2 = img2->stride[VPX_PLANE_V]/2;
564 for (i = 0, match = 1; match && i < c_h; i += bsizey) {
565 for (j = 0; match && j < c_w; j += bsizex) {
566 int k, l;
567 const int si = mmin(i + bsizey, c_h - i);
568 const int sj = mmin(j + bsizex, c_w - j);
569 for (k = 0; match && k < si; ++k) {
570 for (l = 0; match && l < sj; ++l) {
571 if (*(plane1 + (i + k) * stride1 + j + l) !=
572 *(plane2 + (i + k) * stride2 + j + l)) {
573 vloc[0] = i + k;
574 vloc[1] = j + l;
575 vloc[2] = *(plane1 + (i + k) * stride1 + j + l);
576 vloc[3] = *(plane2 + (i + k) * stride2 + j + l);
577 match = 0;
578 break;
585 #endif
587 static void find_mismatch(const vpx_image_t *const img1,
588 const vpx_image_t *const img2,
589 int yloc[4], int uloc[4], int vloc[4]) {
590 const uint32_t bsize = 64;
591 const uint32_t bsizey = bsize >> img1->y_chroma_shift;
592 const uint32_t bsizex = bsize >> img1->x_chroma_shift;
593 const uint32_t c_w =
594 (img1->d_w + img1->x_chroma_shift) >> img1->x_chroma_shift;
595 const uint32_t c_h =
596 (img1->d_h + img1->y_chroma_shift) >> img1->y_chroma_shift;
597 int match = 1;
598 uint32_t i, j;
599 yloc[0] = yloc[1] = yloc[2] = yloc[3] = -1;
600 for (i = 0, match = 1; match && i < img1->d_h; i += bsize) {
601 for (j = 0; match && j < img1->d_w; j += bsize) {
602 int k, l;
603 const int si = mmin(i + bsize, img1->d_h) - i;
604 const int sj = mmin(j + bsize, img1->d_w) - j;
605 for (k = 0; match && k < si; ++k) {
606 for (l = 0; match && l < sj; ++l) {
607 if (*(img1->planes[VPX_PLANE_Y] +
608 (i + k) * img1->stride[VPX_PLANE_Y] + j + l) !=
609 *(img2->planes[VPX_PLANE_Y] +
610 (i + k) * img2->stride[VPX_PLANE_Y] + j + l)) {
611 yloc[0] = i + k;
612 yloc[1] = j + l;
613 yloc[2] = *(img1->planes[VPX_PLANE_Y] +
614 (i + k) * img1->stride[VPX_PLANE_Y] + j + l);
615 yloc[3] = *(img2->planes[VPX_PLANE_Y] +
616 (i + k) * img2->stride[VPX_PLANE_Y] + j + l);
617 match = 0;
618 break;
625 uloc[0] = uloc[1] = uloc[2] = uloc[3] = -1;
626 for (i = 0, match = 1; match && i < c_h; i += bsizey) {
627 for (j = 0; match && j < c_w; j += bsizex) {
628 int k, l;
629 const int si = mmin(i + bsizey, c_h - i);
630 const int sj = mmin(j + bsizex, c_w - j);
631 for (k = 0; match && k < si; ++k) {
632 for (l = 0; match && l < sj; ++l) {
633 if (*(img1->planes[VPX_PLANE_U] +
634 (i + k) * img1->stride[VPX_PLANE_U] + j + l) !=
635 *(img2->planes[VPX_PLANE_U] +
636 (i + k) * img2->stride[VPX_PLANE_U] + j + l)) {
637 uloc[0] = i + k;
638 uloc[1] = j + l;
639 uloc[2] = *(img1->planes[VPX_PLANE_U] +
640 (i + k) * img1->stride[VPX_PLANE_U] + j + l);
641 uloc[3] = *(img2->planes[VPX_PLANE_U] +
642 (i + k) * img2->stride[VPX_PLANE_U] + j + l);
643 match = 0;
644 break;
650 vloc[0] = vloc[1] = vloc[2] = vloc[3] = -1;
651 for (i = 0, match = 1; match && i < c_h; i += bsizey) {
652 for (j = 0; match && j < c_w; j += bsizex) {
653 int k, l;
654 const int si = mmin(i + bsizey, c_h - i);
655 const int sj = mmin(j + bsizex, c_w - j);
656 for (k = 0; match && k < si; ++k) {
657 for (l = 0; match && l < sj; ++l) {
658 if (*(img1->planes[VPX_PLANE_V] +
659 (i + k) * img1->stride[VPX_PLANE_V] + j + l) !=
660 *(img2->planes[VPX_PLANE_V] +
661 (i + k) * img2->stride[VPX_PLANE_V] + j + l)) {
662 vloc[0] = i + k;
663 vloc[1] = j + l;
664 vloc[2] = *(img1->planes[VPX_PLANE_V] +
665 (i + k) * img1->stride[VPX_PLANE_V] + j + l);
666 vloc[3] = *(img2->planes[VPX_PLANE_V] +
667 (i + k) * img2->stride[VPX_PLANE_V] + j + l);
668 match = 0;
669 break;
677 static int compare_img(const vpx_image_t *const img1,
678 const vpx_image_t *const img2) {
679 uint32_t l_w = img1->d_w;
680 uint32_t c_w =
681 (img1->d_w + img1->x_chroma_shift) >> img1->x_chroma_shift;
682 const uint32_t c_h =
683 (img1->d_h + img1->y_chroma_shift) >> img1->y_chroma_shift;
684 uint32_t i;
685 int match = 1;
687 match &= (img1->fmt == img2->fmt);
688 match &= (img1->d_w == img2->d_w);
689 match &= (img1->d_h == img2->d_h);
690 #if CONFIG_VP9 && CONFIG_VP9_HIGHBITDEPTH
691 if (img1->fmt & VPX_IMG_FMT_HIGHBITDEPTH) {
692 l_w *= 2;
693 c_w *= 2;
695 #endif
697 for (i = 0; i < img1->d_h; ++i)
698 match &= (memcmp(img1->planes[VPX_PLANE_Y] + i * img1->stride[VPX_PLANE_Y],
699 img2->planes[VPX_PLANE_Y] + i * img2->stride[VPX_PLANE_Y],
700 l_w) == 0);
702 for (i = 0; i < c_h; ++i)
703 match &= (memcmp(img1->planes[VPX_PLANE_U] + i * img1->stride[VPX_PLANE_U],
704 img2->planes[VPX_PLANE_U] + i * img2->stride[VPX_PLANE_U],
705 c_w) == 0);
707 for (i = 0; i < c_h; ++i)
708 match &= (memcmp(img1->planes[VPX_PLANE_V] + i * img1->stride[VPX_PLANE_V],
709 img2->planes[VPX_PLANE_V] + i * img2->stride[VPX_PLANE_V],
710 c_w) == 0);
712 return match;
716 #define NELEMENTS(x) (sizeof(x)/sizeof(x[0]))
717 #define MAX(x,y) ((x)>(y)?(x):(y))
718 #if CONFIG_VP8_ENCODER && !CONFIG_VP9_ENCODER
719 #define ARG_CTRL_CNT_MAX NELEMENTS(vp8_arg_ctrl_map)
720 #elif !CONFIG_VP8_ENCODER && CONFIG_VP9_ENCODER
721 #define ARG_CTRL_CNT_MAX NELEMENTS(vp9_arg_ctrl_map)
722 #else
723 #define ARG_CTRL_CNT_MAX MAX(NELEMENTS(vp8_arg_ctrl_map), \
724 NELEMENTS(vp9_arg_ctrl_map))
725 #endif
727 #if !CONFIG_WEBM_IO
728 typedef int stereo_format_t;
729 struct EbmlGlobal { int debug; };
730 #endif
732 /* Per-stream configuration */
733 struct stream_config {
734 struct vpx_codec_enc_cfg cfg;
735 const char *out_fn;
736 const char *stats_fn;
737 #if CONFIG_FP_MB_STATS
738 const char *fpmb_stats_fn;
739 #endif
740 stereo_format_t stereo_fmt;
741 int arg_ctrls[ARG_CTRL_CNT_MAX][2];
742 int arg_ctrl_cnt;
743 int write_webm;
744 int have_kf_max_dist;
745 #if CONFIG_VP9 && CONFIG_VP9_HIGHBITDEPTH
746 // whether to use 16bit internal buffers
747 int use_16bit_internal;
748 #endif
752 struct stream_state {
753 int index;
754 struct stream_state *next;
755 struct stream_config config;
756 FILE *file;
757 struct rate_hist *rate_hist;
758 struct EbmlGlobal ebml;
759 uint64_t psnr_sse_total;
760 uint64_t psnr_samples_total;
761 double psnr_totals[4];
762 int psnr_count;
763 int counts[64];
764 vpx_codec_ctx_t encoder;
765 unsigned int frames_out;
766 uint64_t cx_time;
767 size_t nbytes;
768 stats_io_t stats;
769 #if CONFIG_FP_MB_STATS
770 stats_io_t fpmb_stats;
771 #endif
772 struct vpx_image *img;
773 vpx_codec_ctx_t decoder;
774 int mismatch_seen;
778 void validate_positive_rational(const char *msg,
779 struct vpx_rational *rat) {
780 if (rat->den < 0) {
781 rat->num *= -1;
782 rat->den *= -1;
785 if (rat->num < 0)
786 die("Error: %s must be positive\n", msg);
788 if (!rat->den)
789 die("Error: %s has zero denominator\n", msg);
793 static void parse_global_config(struct VpxEncoderConfig *global, char **argv) {
794 char **argi, **argj;
795 struct arg arg;
797 /* Initialize default parameters */
798 memset(global, 0, sizeof(*global));
799 global->codec = get_vpx_encoder_by_index(0);
800 global->passes = 0;
801 global->color_type = I420;
802 /* Assign default deadline to good quality */
803 global->deadline = VPX_DL_GOOD_QUALITY;
805 for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step) {
806 arg.argv_step = 1;
808 if (arg_match(&arg, &codecarg, argi)) {
809 global->codec = get_vpx_encoder_by_name(arg.val);
810 if (!global->codec)
811 die("Error: Unrecognized argument (%s) to --codec\n", arg.val);
812 } else if (arg_match(&arg, &passes, argi)) {
813 global->passes = arg_parse_uint(&arg);
815 if (global->passes < 1 || global->passes > 2)
816 die("Error: Invalid number of passes (%d)\n", global->passes);
817 } else if (arg_match(&arg, &pass_arg, argi)) {
818 global->pass = arg_parse_uint(&arg);
820 if (global->pass < 1 || global->pass > 2)
821 die("Error: Invalid pass selected (%d)\n",
822 global->pass);
823 } else if (arg_match(&arg, &usage, argi))
824 global->usage = arg_parse_uint(&arg);
825 else if (arg_match(&arg, &deadline, argi))
826 global->deadline = arg_parse_uint(&arg);
827 else if (arg_match(&arg, &best_dl, argi))
828 global->deadline = VPX_DL_BEST_QUALITY;
829 else if (arg_match(&arg, &good_dl, argi))
830 global->deadline = VPX_DL_GOOD_QUALITY;
831 else if (arg_match(&arg, &rt_dl, argi))
832 global->deadline = VPX_DL_REALTIME;
833 else if (arg_match(&arg, &use_yv12, argi))
834 global->color_type = YV12;
835 else if (arg_match(&arg, &use_i420, argi))
836 global->color_type = I420;
837 else if (arg_match(&arg, &use_i422, argi))
838 global->color_type = I422;
839 else if (arg_match(&arg, &use_i444, argi))
840 global->color_type = I444;
841 else if (arg_match(&arg, &use_i440, argi))
842 global->color_type = I440;
843 else if (arg_match(&arg, &quietarg, argi))
844 global->quiet = 1;
845 else if (arg_match(&arg, &verbosearg, argi))
846 global->verbose = 1;
847 else if (arg_match(&arg, &limit, argi))
848 global->limit = arg_parse_uint(&arg);
849 else if (arg_match(&arg, &skip, argi))
850 global->skip_frames = arg_parse_uint(&arg);
851 else if (arg_match(&arg, &psnrarg, argi))
852 global->show_psnr = 1;
853 else if (arg_match(&arg, &recontest, argi))
854 global->test_decode = arg_parse_enum_or_int(&arg);
855 else if (arg_match(&arg, &framerate, argi)) {
856 global->framerate = arg_parse_rational(&arg);
857 validate_positive_rational(arg.name, &global->framerate);
858 global->have_framerate = 1;
859 } else if (arg_match(&arg, &out_part, argi))
860 global->out_part = 1;
861 else if (arg_match(&arg, &debugmode, argi))
862 global->debug = 1;
863 else if (arg_match(&arg, &q_hist_n, argi))
864 global->show_q_hist_buckets = arg_parse_uint(&arg);
865 else if (arg_match(&arg, &rate_hist_n, argi))
866 global->show_rate_hist_buckets = arg_parse_uint(&arg);
867 else if (arg_match(&arg, &disable_warnings, argi))
868 global->disable_warnings = 1;
869 else if (arg_match(&arg, &disable_warning_prompt, argi))
870 global->disable_warning_prompt = 1;
871 else
872 argj++;
875 if (global->pass) {
876 /* DWIM: Assume the user meant passes=2 if pass=2 is specified */
877 if (global->pass > global->passes) {
878 warn("Assuming --pass=%d implies --passes=%d\n",
879 global->pass, global->pass);
880 global->passes = global->pass;
883 /* Validate global config */
884 if (global->passes == 0) {
885 #if CONFIG_VP9_ENCODER
886 // Make default VP9 passes = 2 until there is a better quality 1-pass
887 // encoder
888 if (global->codec != NULL && global->codec->name != NULL)
889 global->passes = (strcmp(global->codec->name, "vp9") == 0 &&
890 global->deadline != VPX_DL_REALTIME) ? 2 : 1;
891 #else
892 global->passes = 1;
893 #endif
896 if (global->deadline == VPX_DL_REALTIME &&
897 global->passes > 1) {
898 warn("Enforcing one-pass encoding in realtime mode\n");
899 global->passes = 1;
904 void open_input_file(struct VpxInputContext *input) {
905 /* Parse certain options from the input file, if possible */
906 input->file = strcmp(input->filename, "-")
907 ? fopen(input->filename, "rb") : set_binary_mode(stdin);
909 if (!input->file)
910 fatal("Failed to open input file");
912 if (!fseeko(input->file, 0, SEEK_END)) {
913 /* Input file is seekable. Figure out how long it is, so we can get
914 * progress info.
916 input->length = ftello(input->file);
917 rewind(input->file);
920 /* For RAW input sources, these bytes will applied on the first frame
921 * in read_frame().
923 input->detect.buf_read = fread(input->detect.buf, 1, 4, input->file);
924 input->detect.position = 0;
926 if (input->detect.buf_read == 4
927 && file_is_y4m(input->detect.buf)) {
928 if (y4m_input_open(&input->y4m, input->file, input->detect.buf, 4,
929 input->only_i420) >= 0) {
930 input->file_type = FILE_TYPE_Y4M;
931 input->width = input->y4m.pic_w;
932 input->height = input->y4m.pic_h;
933 input->framerate.numerator = input->y4m.fps_n;
934 input->framerate.denominator = input->y4m.fps_d;
935 input->fmt = input->y4m.vpx_fmt;
936 input->bit_depth = input->y4m.bit_depth;
937 } else
938 fatal("Unsupported Y4M stream.");
939 } else if (input->detect.buf_read == 4 && fourcc_is_ivf(input->detect.buf)) {
940 fatal("IVF is not supported as input.");
941 } else {
942 input->file_type = FILE_TYPE_RAW;
947 static void close_input_file(struct VpxInputContext *input) {
948 fclose(input->file);
949 if (input->file_type == FILE_TYPE_Y4M)
950 y4m_input_close(&input->y4m);
953 static struct stream_state *new_stream(struct VpxEncoderConfig *global,
954 struct stream_state *prev) {
955 struct stream_state *stream;
957 stream = calloc(1, sizeof(*stream));
958 if (stream == NULL) {
959 fatal("Failed to allocate new stream.");
962 if (prev) {
963 memcpy(stream, prev, sizeof(*stream));
964 stream->index++;
965 prev->next = stream;
966 } else {
967 vpx_codec_err_t res;
969 /* Populate encoder configuration */
970 res = vpx_codec_enc_config_default(global->codec->codec_interface(),
971 &stream->config.cfg,
972 global->usage);
973 if (res)
974 fatal("Failed to get config: %s\n", vpx_codec_err_to_string(res));
976 /* Change the default timebase to a high enough value so that the
977 * encoder will always create strictly increasing timestamps.
979 stream->config.cfg.g_timebase.den = 1000;
981 /* Never use the library's default resolution, require it be parsed
982 * from the file or set on the command line.
984 stream->config.cfg.g_w = 0;
985 stream->config.cfg.g_h = 0;
987 /* Initialize remaining stream parameters */
988 stream->config.write_webm = 1;
989 #if CONFIG_WEBM_IO
990 stream->config.stereo_fmt = STEREO_FORMAT_MONO;
991 stream->ebml.last_pts_ns = -1;
992 stream->ebml.writer = NULL;
993 stream->ebml.segment = NULL;
994 #endif
996 /* Allows removal of the application version from the EBML tags */
997 stream->ebml.debug = global->debug;
999 /* Default lag_in_frames is 0 in realtime mode */
1000 if (global->deadline == VPX_DL_REALTIME)
1001 stream->config.cfg.g_lag_in_frames = 0;
1004 /* Output files must be specified for each stream */
1005 stream->config.out_fn = NULL;
1007 stream->next = NULL;
1008 return stream;
1012 static int parse_stream_params(struct VpxEncoderConfig *global,
1013 struct stream_state *stream,
1014 char **argv) {
1015 char **argi, **argj;
1016 struct arg arg;
1017 static const arg_def_t **ctrl_args = no_args;
1018 static const int *ctrl_args_map = NULL;
1019 struct stream_config *config = &stream->config;
1020 int eos_mark_found = 0;
1021 #if CONFIG_VP9 && CONFIG_VP9_HIGHBITDEPTH
1022 int test_16bit_internal = 0;
1023 #endif
1025 // Handle codec specific options
1026 if (0) {
1027 #if CONFIG_VP8_ENCODER
1028 } else if (strcmp(global->codec->name, "vp8") == 0) {
1029 ctrl_args = vp8_args;
1030 ctrl_args_map = vp8_arg_ctrl_map;
1031 #endif
1032 #if CONFIG_VP9_ENCODER
1033 } else if (strcmp(global->codec->name, "vp9") == 0) {
1034 ctrl_args = vp9_args;
1035 ctrl_args_map = vp9_arg_ctrl_map;
1036 #endif
1039 for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step) {
1040 arg.argv_step = 1;
1042 /* Once we've found an end-of-stream marker (--) we want to continue
1043 * shifting arguments but not consuming them.
1045 if (eos_mark_found) {
1046 argj++;
1047 continue;
1048 } else if (!strcmp(*argj, "--")) {
1049 eos_mark_found = 1;
1050 continue;
1053 if (0) {
1054 } else if (arg_match(&arg, &outputfile, argi)) {
1055 config->out_fn = arg.val;
1056 } else if (arg_match(&arg, &fpf_name, argi)) {
1057 config->stats_fn = arg.val;
1058 #if CONFIG_FP_MB_STATS
1059 } else if (arg_match(&arg, &fpmbf_name, argi)) {
1060 config->fpmb_stats_fn = arg.val;
1061 #endif
1062 } else if (arg_match(&arg, &use_ivf, argi)) {
1063 config->write_webm = 0;
1064 } else if (arg_match(&arg, &threads, argi)) {
1065 config->cfg.g_threads = arg_parse_uint(&arg);
1066 } else if (arg_match(&arg, &profile, argi)) {
1067 config->cfg.g_profile = arg_parse_uint(&arg);
1068 } else if (arg_match(&arg, &width, argi)) {
1069 config->cfg.g_w = arg_parse_uint(&arg);
1070 } else if (arg_match(&arg, &height, argi)) {
1071 config->cfg.g_h = arg_parse_uint(&arg);
1072 #if CONFIG_VP9 && CONFIG_VP9_HIGHBITDEPTH
1073 } else if (arg_match(&arg, &bitdeptharg, argi)) {
1074 config->cfg.g_bit_depth = arg_parse_enum_or_int(&arg);
1075 } else if (arg_match(&arg, &inbitdeptharg, argi)) {
1076 config->cfg.g_input_bit_depth = arg_parse_uint(&arg);
1077 #endif
1078 #if CONFIG_WEBM_IO
1079 } else if (arg_match(&arg, &stereo_mode, argi)) {
1080 config->stereo_fmt = arg_parse_enum_or_int(&arg);
1081 #endif
1082 } else if (arg_match(&arg, &timebase, argi)) {
1083 config->cfg.g_timebase = arg_parse_rational(&arg);
1084 validate_positive_rational(arg.name, &config->cfg.g_timebase);
1085 } else if (arg_match(&arg, &error_resilient, argi)) {
1086 config->cfg.g_error_resilient = arg_parse_uint(&arg);
1087 } else if (arg_match(&arg, &lag_in_frames, argi)) {
1088 config->cfg.g_lag_in_frames = arg_parse_uint(&arg);
1089 if (global->deadline == VPX_DL_REALTIME &&
1090 config->cfg.g_lag_in_frames != 0) {
1091 warn("non-zero %s option ignored in realtime mode.\n", arg.name);
1092 config->cfg.g_lag_in_frames = 0;
1094 } else if (arg_match(&arg, &dropframe_thresh, argi)) {
1095 config->cfg.rc_dropframe_thresh = arg_parse_uint(&arg);
1096 } else if (arg_match(&arg, &resize_allowed, argi)) {
1097 config->cfg.rc_resize_allowed = arg_parse_uint(&arg);
1098 } else if (arg_match(&arg, &resize_width, argi)) {
1099 config->cfg.rc_scaled_width = arg_parse_uint(&arg);
1100 } else if (arg_match(&arg, &resize_height, argi)) {
1101 config->cfg.rc_scaled_height = arg_parse_uint(&arg);
1102 } else if (arg_match(&arg, &resize_up_thresh, argi)) {
1103 config->cfg.rc_resize_up_thresh = arg_parse_uint(&arg);
1104 } else if (arg_match(&arg, &resize_down_thresh, argi)) {
1105 config->cfg.rc_resize_down_thresh = arg_parse_uint(&arg);
1106 } else if (arg_match(&arg, &end_usage, argi)) {
1107 config->cfg.rc_end_usage = arg_parse_enum_or_int(&arg);
1108 } else if (arg_match(&arg, &target_bitrate, argi)) {
1109 config->cfg.rc_target_bitrate = arg_parse_uint(&arg);
1110 } else if (arg_match(&arg, &min_quantizer, argi)) {
1111 config->cfg.rc_min_quantizer = arg_parse_uint(&arg);
1112 } else if (arg_match(&arg, &max_quantizer, argi)) {
1113 config->cfg.rc_max_quantizer = arg_parse_uint(&arg);
1114 } else if (arg_match(&arg, &undershoot_pct, argi)) {
1115 config->cfg.rc_undershoot_pct = arg_parse_uint(&arg);
1116 } else if (arg_match(&arg, &overshoot_pct, argi)) {
1117 config->cfg.rc_overshoot_pct = arg_parse_uint(&arg);
1118 } else if (arg_match(&arg, &buf_sz, argi)) {
1119 config->cfg.rc_buf_sz = arg_parse_uint(&arg);
1120 } else if (arg_match(&arg, &buf_initial_sz, argi)) {
1121 config->cfg.rc_buf_initial_sz = arg_parse_uint(&arg);
1122 } else if (arg_match(&arg, &buf_optimal_sz, argi)) {
1123 config->cfg.rc_buf_optimal_sz = arg_parse_uint(&arg);
1124 } else if (arg_match(&arg, &bias_pct, argi)) {
1125 config->cfg.rc_2pass_vbr_bias_pct = arg_parse_uint(&arg);
1126 if (global->passes < 2)
1127 warn("option %s ignored in one-pass mode.\n", arg.name);
1128 } else if (arg_match(&arg, &minsection_pct, argi)) {
1129 config->cfg.rc_2pass_vbr_minsection_pct = arg_parse_uint(&arg);
1131 if (global->passes < 2)
1132 warn("option %s ignored in one-pass mode.\n", arg.name);
1133 } else if (arg_match(&arg, &maxsection_pct, argi)) {
1134 config->cfg.rc_2pass_vbr_maxsection_pct = arg_parse_uint(&arg);
1136 if (global->passes < 2)
1137 warn("option %s ignored in one-pass mode.\n", arg.name);
1138 } else if (arg_match(&arg, &kf_min_dist, argi)) {
1139 config->cfg.kf_min_dist = arg_parse_uint(&arg);
1140 } else if (arg_match(&arg, &kf_max_dist, argi)) {
1141 config->cfg.kf_max_dist = arg_parse_uint(&arg);
1142 config->have_kf_max_dist = 1;
1143 } else if (arg_match(&arg, &kf_disabled, argi)) {
1144 config->cfg.kf_mode = VPX_KF_DISABLED;
1145 #if CONFIG_VP9 && CONFIG_VP9_HIGHBITDEPTH
1146 } else if (arg_match(&arg, &test16bitinternalarg, argi)) {
1147 if (strcmp(global->codec->name, "vp9") == 0) {
1148 test_16bit_internal = 1;
1150 #endif
1151 } else {
1152 int i, match = 0;
1153 for (i = 0; ctrl_args[i]; i++) {
1154 if (arg_match(&arg, ctrl_args[i], argi)) {
1155 int j;
1156 match = 1;
1158 /* Point either to the next free element or the first
1159 * instance of this control.
1161 for (j = 0; j < config->arg_ctrl_cnt; j++)
1162 if (ctrl_args_map != NULL &&
1163 config->arg_ctrls[j][0] == ctrl_args_map[i])
1164 break;
1166 /* Update/insert */
1167 assert(j < (int)ARG_CTRL_CNT_MAX);
1168 if (ctrl_args_map != NULL && j < (int)ARG_CTRL_CNT_MAX) {
1169 config->arg_ctrls[j][0] = ctrl_args_map[i];
1170 config->arg_ctrls[j][1] = arg_parse_enum_or_int(&arg);
1171 if (j == config->arg_ctrl_cnt)
1172 config->arg_ctrl_cnt++;
1176 if (!match)
1177 argj++;
1180 #if CONFIG_VP9 && CONFIG_VP9_HIGHBITDEPTH
1181 if (strcmp(global->codec->name, "vp9") == 0) {
1182 config->use_16bit_internal = test_16bit_internal |
1183 (config->cfg.g_profile > 1);
1185 #endif
1186 return eos_mark_found;
1190 #define FOREACH_STREAM(func) \
1191 do { \
1192 struct stream_state *stream; \
1193 for (stream = streams; stream; stream = stream->next) { \
1194 func; \
1196 } while (0)
1199 static void validate_stream_config(const struct stream_state *stream,
1200 const struct VpxEncoderConfig *global) {
1201 const struct stream_state *streami;
1202 (void)global;
1204 if (!stream->config.cfg.g_w || !stream->config.cfg.g_h)
1205 fatal("Stream %d: Specify stream dimensions with --width (-w) "
1206 " and --height (-h)", stream->index);
1208 // Check that the codec bit depth is greater than the input bit depth.
1209 if (stream->config.cfg.g_input_bit_depth >
1210 (unsigned int)stream->config.cfg.g_bit_depth) {
1211 fatal("Stream %d: codec bit depth (%d) less than input bit depth (%d)",
1212 stream->index, (int)stream->config.cfg.g_bit_depth,
1213 stream->config.cfg.g_input_bit_depth);
1216 for (streami = stream; streami; streami = streami->next) {
1217 /* All streams require output files */
1218 if (!streami->config.out_fn)
1219 fatal("Stream %d: Output file is required (specify with -o)",
1220 streami->index);
1222 /* Check for two streams outputting to the same file */
1223 if (streami != stream) {
1224 const char *a = stream->config.out_fn;
1225 const char *b = streami->config.out_fn;
1226 if (!strcmp(a, b) && strcmp(a, "/dev/null") && strcmp(a, ":nul"))
1227 fatal("Stream %d: duplicate output file (from stream %d)",
1228 streami->index, stream->index);
1231 /* Check for two streams sharing a stats file. */
1232 if (streami != stream) {
1233 const char *a = stream->config.stats_fn;
1234 const char *b = streami->config.stats_fn;
1235 if (a && b && !strcmp(a, b))
1236 fatal("Stream %d: duplicate stats file (from stream %d)",
1237 streami->index, stream->index);
1240 #if CONFIG_FP_MB_STATS
1241 /* Check for two streams sharing a mb stats file. */
1242 if (streami != stream) {
1243 const char *a = stream->config.fpmb_stats_fn;
1244 const char *b = streami->config.fpmb_stats_fn;
1245 if (a && b && !strcmp(a, b))
1246 fatal("Stream %d: duplicate mb stats file (from stream %d)",
1247 streami->index, stream->index);
1249 #endif
1254 static void set_stream_dimensions(struct stream_state *stream,
1255 unsigned int w,
1256 unsigned int h) {
1257 if (!stream->config.cfg.g_w) {
1258 if (!stream->config.cfg.g_h)
1259 stream->config.cfg.g_w = w;
1260 else
1261 stream->config.cfg.g_w = w * stream->config.cfg.g_h / h;
1263 if (!stream->config.cfg.g_h) {
1264 stream->config.cfg.g_h = h * stream->config.cfg.g_w / w;
1269 static void set_default_kf_interval(struct stream_state *stream,
1270 struct VpxEncoderConfig *global) {
1271 /* Use a max keyframe interval of 5 seconds, if none was
1272 * specified on the command line.
1274 if (!stream->config.have_kf_max_dist) {
1275 double framerate = (double)global->framerate.num / global->framerate.den;
1276 if (framerate > 0.0)
1277 stream->config.cfg.kf_max_dist = (unsigned int)(5.0 * framerate);
1281 static const char* file_type_to_string(enum VideoFileType t) {
1282 switch (t) {
1283 case FILE_TYPE_RAW: return "RAW";
1284 case FILE_TYPE_Y4M: return "Y4M";
1285 default: return "Other";
1289 static const char* image_format_to_string(vpx_img_fmt_t f) {
1290 switch (f) {
1291 case VPX_IMG_FMT_I420: return "I420";
1292 case VPX_IMG_FMT_I422: return "I422";
1293 case VPX_IMG_FMT_I444: return "I444";
1294 case VPX_IMG_FMT_I440: return "I440";
1295 case VPX_IMG_FMT_YV12: return "YV12";
1296 case VPX_IMG_FMT_I42016: return "I42016";
1297 case VPX_IMG_FMT_I42216: return "I42216";
1298 case VPX_IMG_FMT_I44416: return "I44416";
1299 case VPX_IMG_FMT_I44016: return "I44016";
1300 default: return "Other";
1304 static void show_stream_config(struct stream_state *stream,
1305 struct VpxEncoderConfig *global,
1306 struct VpxInputContext *input) {
1308 #define SHOW(field) \
1309 fprintf(stderr, " %-28s = %d\n", #field, stream->config.cfg.field)
1311 if (stream->index == 0) {
1312 fprintf(stderr, "Codec: %s\n",
1313 vpx_codec_iface_name(global->codec->codec_interface()));
1314 fprintf(stderr, "Source file: %s File Type: %s Format: %s\n",
1315 input->filename,
1316 file_type_to_string(input->file_type),
1317 image_format_to_string(input->fmt));
1319 if (stream->next || stream->index)
1320 fprintf(stderr, "\nStream Index: %d\n", stream->index);
1321 fprintf(stderr, "Destination file: %s\n", stream->config.out_fn);
1322 fprintf(stderr, "Encoder parameters:\n");
1324 SHOW(g_usage);
1325 SHOW(g_threads);
1326 SHOW(g_profile);
1327 SHOW(g_w);
1328 SHOW(g_h);
1329 SHOW(g_bit_depth);
1330 SHOW(g_input_bit_depth);
1331 SHOW(g_timebase.num);
1332 SHOW(g_timebase.den);
1333 SHOW(g_error_resilient);
1334 SHOW(g_pass);
1335 SHOW(g_lag_in_frames);
1336 SHOW(rc_dropframe_thresh);
1337 SHOW(rc_resize_allowed);
1338 SHOW(rc_scaled_width);
1339 SHOW(rc_scaled_height);
1340 SHOW(rc_resize_up_thresh);
1341 SHOW(rc_resize_down_thresh);
1342 SHOW(rc_end_usage);
1343 SHOW(rc_target_bitrate);
1344 SHOW(rc_min_quantizer);
1345 SHOW(rc_max_quantizer);
1346 SHOW(rc_undershoot_pct);
1347 SHOW(rc_overshoot_pct);
1348 SHOW(rc_buf_sz);
1349 SHOW(rc_buf_initial_sz);
1350 SHOW(rc_buf_optimal_sz);
1351 SHOW(rc_2pass_vbr_bias_pct);
1352 SHOW(rc_2pass_vbr_minsection_pct);
1353 SHOW(rc_2pass_vbr_maxsection_pct);
1354 SHOW(kf_mode);
1355 SHOW(kf_min_dist);
1356 SHOW(kf_max_dist);
1360 static void open_output_file(struct stream_state *stream,
1361 struct VpxEncoderConfig *global) {
1362 const char *fn = stream->config.out_fn;
1363 const struct vpx_codec_enc_cfg *const cfg = &stream->config.cfg;
1365 if (cfg->g_pass == VPX_RC_FIRST_PASS)
1366 return;
1368 stream->file = strcmp(fn, "-") ? fopen(fn, "wb") : set_binary_mode(stdout);
1370 if (!stream->file)
1371 fatal("Failed to open output file");
1373 if (stream->config.write_webm && fseek(stream->file, 0, SEEK_CUR))
1374 fatal("WebM output to pipes not supported.");
1376 #if CONFIG_WEBM_IO
1377 if (stream->config.write_webm) {
1378 stream->ebml.stream = stream->file;
1379 write_webm_file_header(&stream->ebml, cfg,
1380 &global->framerate,
1381 stream->config.stereo_fmt,
1382 global->codec->fourcc);
1384 #endif
1386 if (!stream->config.write_webm) {
1387 ivf_write_file_header(stream->file, cfg, global->codec->fourcc, 0);
1392 static void close_output_file(struct stream_state *stream,
1393 unsigned int fourcc) {
1394 const struct vpx_codec_enc_cfg *const cfg = &stream->config.cfg;
1396 if (cfg->g_pass == VPX_RC_FIRST_PASS)
1397 return;
1399 #if CONFIG_WEBM_IO
1400 if (stream->config.write_webm) {
1401 write_webm_file_footer(&stream->ebml);
1403 #endif
1405 if (!stream->config.write_webm) {
1406 if (!fseek(stream->file, 0, SEEK_SET))
1407 ivf_write_file_header(stream->file, &stream->config.cfg,
1408 fourcc,
1409 stream->frames_out);
1412 fclose(stream->file);
1416 static void setup_pass(struct stream_state *stream,
1417 struct VpxEncoderConfig *global,
1418 int pass) {
1419 if (stream->config.stats_fn) {
1420 if (!stats_open_file(&stream->stats, stream->config.stats_fn,
1421 pass))
1422 fatal("Failed to open statistics store");
1423 } else {
1424 if (!stats_open_mem(&stream->stats, pass))
1425 fatal("Failed to open statistics store");
1428 #if CONFIG_FP_MB_STATS
1429 if (stream->config.fpmb_stats_fn) {
1430 if (!stats_open_file(&stream->fpmb_stats,
1431 stream->config.fpmb_stats_fn, pass))
1432 fatal("Failed to open mb statistics store");
1433 } else {
1434 if (!stats_open_mem(&stream->fpmb_stats, pass))
1435 fatal("Failed to open mb statistics store");
1437 #endif
1439 stream->config.cfg.g_pass = global->passes == 2
1440 ? pass ? VPX_RC_LAST_PASS : VPX_RC_FIRST_PASS
1441 : VPX_RC_ONE_PASS;
1442 if (pass) {
1443 stream->config.cfg.rc_twopass_stats_in = stats_get(&stream->stats);
1444 #if CONFIG_FP_MB_STATS
1445 stream->config.cfg.rc_firstpass_mb_stats_in =
1446 stats_get(&stream->fpmb_stats);
1447 #endif
1450 stream->cx_time = 0;
1451 stream->nbytes = 0;
1452 stream->frames_out = 0;
1456 static void initialize_encoder(struct stream_state *stream,
1457 struct VpxEncoderConfig *global) {
1458 int i;
1459 int flags = 0;
1461 flags |= global->show_psnr ? VPX_CODEC_USE_PSNR : 0;
1462 flags |= global->out_part ? VPX_CODEC_USE_OUTPUT_PARTITION : 0;
1463 #if CONFIG_VP9 && CONFIG_VP9_HIGHBITDEPTH
1464 flags |= stream->config.use_16bit_internal ? VPX_CODEC_USE_HIGHBITDEPTH : 0;
1465 #endif
1467 /* Construct Encoder Context */
1468 vpx_codec_enc_init(&stream->encoder, global->codec->codec_interface(),
1469 &stream->config.cfg, flags);
1470 ctx_exit_on_error(&stream->encoder, "Failed to initialize encoder");
1472 /* Note that we bypass the vpx_codec_control wrapper macro because
1473 * we're being clever to store the control IDs in an array. Real
1474 * applications will want to make use of the enumerations directly
1476 for (i = 0; i < stream->config.arg_ctrl_cnt; i++) {
1477 int ctrl = stream->config.arg_ctrls[i][0];
1478 int value = stream->config.arg_ctrls[i][1];
1479 if (vpx_codec_control_(&stream->encoder, ctrl, value))
1480 fprintf(stderr, "Error: Tried to set control %d = %d\n",
1481 ctrl, value);
1483 ctx_exit_on_error(&stream->encoder, "Failed to control codec");
1486 #if CONFIG_DECODERS
1487 if (global->test_decode != TEST_DECODE_OFF) {
1488 const VpxInterface *decoder = get_vpx_decoder_by_name(global->codec->name);
1489 vpx_codec_dec_init(&stream->decoder, decoder->codec_interface(), NULL, 0);
1491 #endif
1495 static void encode_frame(struct stream_state *stream,
1496 struct VpxEncoderConfig *global,
1497 struct vpx_image *img,
1498 unsigned int frames_in) {
1499 vpx_codec_pts_t frame_start, next_frame_start;
1500 struct vpx_codec_enc_cfg *cfg = &stream->config.cfg;
1501 struct vpx_usec_timer timer;
1503 frame_start = (cfg->g_timebase.den * (int64_t)(frames_in - 1)
1504 * global->framerate.den)
1505 / cfg->g_timebase.num / global->framerate.num;
1506 next_frame_start = (cfg->g_timebase.den * (int64_t)(frames_in)
1507 * global->framerate.den)
1508 / cfg->g_timebase.num / global->framerate.num;
1510 /* Scale if necessary */
1511 #if CONFIG_VP9 && CONFIG_VP9_HIGHBITDEPTH
1512 if (img) {
1513 if ((img->fmt & VPX_IMG_FMT_HIGHBITDEPTH) &&
1514 (img->d_w != cfg->g_w || img->d_h != cfg->g_h)) {
1515 if (img->fmt != VPX_IMG_FMT_I42016) {
1516 fprintf(stderr, "%s can only scale 4:2:0 inputs\n", exec_name);
1517 exit(EXIT_FAILURE);
1519 #if CONFIG_LIBYUV
1520 if (!stream->img) {
1521 stream->img = vpx_img_alloc(NULL, VPX_IMG_FMT_I42016,
1522 cfg->g_w, cfg->g_h, 16);
1524 I420Scale_16((uint16*)img->planes[VPX_PLANE_Y],
1525 img->stride[VPX_PLANE_Y]/2,
1526 (uint16*)img->planes[VPX_PLANE_U],
1527 img->stride[VPX_PLANE_U]/2,
1528 (uint16*)img->planes[VPX_PLANE_V],
1529 img->stride[VPX_PLANE_V]/2,
1530 img->d_w, img->d_h,
1531 (uint16*)stream->img->planes[VPX_PLANE_Y],
1532 stream->img->stride[VPX_PLANE_Y]/2,
1533 (uint16*)stream->img->planes[VPX_PLANE_U],
1534 stream->img->stride[VPX_PLANE_U]/2,
1535 (uint16*)stream->img->planes[VPX_PLANE_V],
1536 stream->img->stride[VPX_PLANE_V]/2,
1537 stream->img->d_w, stream->img->d_h,
1538 kFilterBox);
1539 img = stream->img;
1540 #else
1541 stream->encoder.err = 1;
1542 ctx_exit_on_error(&stream->encoder,
1543 "Stream %d: Failed to encode frame.\n"
1544 "Scaling disabled in this configuration. \n"
1545 "To enable, configure with --enable-libyuv\n",
1546 stream->index);
1547 #endif
1550 #endif
1551 if (img && (img->d_w != cfg->g_w || img->d_h != cfg->g_h)) {
1552 if (img->fmt != VPX_IMG_FMT_I420 && img->fmt != VPX_IMG_FMT_YV12) {
1553 fprintf(stderr, "%s can only scale 4:2:0 8bpp inputs\n", exec_name);
1554 exit(EXIT_FAILURE);
1556 #if CONFIG_LIBYUV
1557 if (!stream->img)
1558 stream->img = vpx_img_alloc(NULL, VPX_IMG_FMT_I420,
1559 cfg->g_w, cfg->g_h, 16);
1560 I420Scale(img->planes[VPX_PLANE_Y], img->stride[VPX_PLANE_Y],
1561 img->planes[VPX_PLANE_U], img->stride[VPX_PLANE_U],
1562 img->planes[VPX_PLANE_V], img->stride[VPX_PLANE_V],
1563 img->d_w, img->d_h,
1564 stream->img->planes[VPX_PLANE_Y],
1565 stream->img->stride[VPX_PLANE_Y],
1566 stream->img->planes[VPX_PLANE_U],
1567 stream->img->stride[VPX_PLANE_U],
1568 stream->img->planes[VPX_PLANE_V],
1569 stream->img->stride[VPX_PLANE_V],
1570 stream->img->d_w, stream->img->d_h,
1571 kFilterBox);
1572 img = stream->img;
1573 #else
1574 stream->encoder.err = 1;
1575 ctx_exit_on_error(&stream->encoder,
1576 "Stream %d: Failed to encode frame.\n"
1577 "Scaling disabled in this configuration. \n"
1578 "To enable, configure with --enable-libyuv\n",
1579 stream->index);
1580 #endif
1583 vpx_usec_timer_start(&timer);
1584 vpx_codec_encode(&stream->encoder, img, frame_start,
1585 (unsigned long)(next_frame_start - frame_start),
1586 0, global->deadline);
1587 vpx_usec_timer_mark(&timer);
1588 stream->cx_time += vpx_usec_timer_elapsed(&timer);
1589 ctx_exit_on_error(&stream->encoder, "Stream %d: Failed to encode frame",
1590 stream->index);
1594 static void update_quantizer_histogram(struct stream_state *stream) {
1595 if (stream->config.cfg.g_pass != VPX_RC_FIRST_PASS) {
1596 int q;
1598 vpx_codec_control(&stream->encoder, VP8E_GET_LAST_QUANTIZER_64, &q);
1599 ctx_exit_on_error(&stream->encoder, "Failed to read quantizer");
1600 stream->counts[q]++;
1605 static void get_cx_data(struct stream_state *stream,
1606 struct VpxEncoderConfig *global,
1607 int *got_data) {
1608 const vpx_codec_cx_pkt_t *pkt;
1609 const struct vpx_codec_enc_cfg *cfg = &stream->config.cfg;
1610 vpx_codec_iter_t iter = NULL;
1612 *got_data = 0;
1613 while ((pkt = vpx_codec_get_cx_data(&stream->encoder, &iter))) {
1614 static size_t fsize = 0;
1615 static int64_t ivf_header_pos = 0;
1617 switch (pkt->kind) {
1618 case VPX_CODEC_CX_FRAME_PKT:
1619 if (!(pkt->data.frame.flags & VPX_FRAME_IS_FRAGMENT)) {
1620 stream->frames_out++;
1622 if (!global->quiet)
1623 fprintf(stderr, " %6luF", (unsigned long)pkt->data.frame.sz);
1625 update_rate_histogram(stream->rate_hist, cfg, pkt);
1626 #if CONFIG_WEBM_IO
1627 if (stream->config.write_webm) {
1628 write_webm_block(&stream->ebml, cfg, pkt);
1630 #endif
1631 if (!stream->config.write_webm) {
1632 if (pkt->data.frame.partition_id <= 0) {
1633 ivf_header_pos = ftello(stream->file);
1634 fsize = pkt->data.frame.sz;
1636 ivf_write_frame_header(stream->file, pkt->data.frame.pts, fsize);
1637 } else {
1638 fsize += pkt->data.frame.sz;
1640 if (!(pkt->data.frame.flags & VPX_FRAME_IS_FRAGMENT)) {
1641 const int64_t currpos = ftello(stream->file);
1642 fseeko(stream->file, ivf_header_pos, SEEK_SET);
1643 ivf_write_frame_size(stream->file, fsize);
1644 fseeko(stream->file, currpos, SEEK_SET);
1648 (void) fwrite(pkt->data.frame.buf, 1, pkt->data.frame.sz,
1649 stream->file);
1651 stream->nbytes += pkt->data.raw.sz;
1653 *got_data = 1;
1654 #if CONFIG_DECODERS
1655 if (global->test_decode != TEST_DECODE_OFF && !stream->mismatch_seen) {
1656 vpx_codec_decode(&stream->decoder, pkt->data.frame.buf,
1657 (unsigned int)pkt->data.frame.sz, NULL, 0);
1658 if (stream->decoder.err) {
1659 warn_or_exit_on_error(&stream->decoder,
1660 global->test_decode == TEST_DECODE_FATAL,
1661 "Failed to decode frame %d in stream %d",
1662 stream->frames_out + 1, stream->index);
1663 stream->mismatch_seen = stream->frames_out + 1;
1666 #endif
1667 break;
1668 case VPX_CODEC_STATS_PKT:
1669 stream->frames_out++;
1670 stats_write(&stream->stats,
1671 pkt->data.twopass_stats.buf,
1672 pkt->data.twopass_stats.sz);
1673 stream->nbytes += pkt->data.raw.sz;
1674 break;
1675 #if CONFIG_FP_MB_STATS
1676 case VPX_CODEC_FPMB_STATS_PKT:
1677 stats_write(&stream->fpmb_stats,
1678 pkt->data.firstpass_mb_stats.buf,
1679 pkt->data.firstpass_mb_stats.sz);
1680 stream->nbytes += pkt->data.raw.sz;
1681 break;
1682 #endif
1683 case VPX_CODEC_PSNR_PKT:
1685 if (global->show_psnr) {
1686 int i;
1688 stream->psnr_sse_total += pkt->data.psnr.sse[0];
1689 stream->psnr_samples_total += pkt->data.psnr.samples[0];
1690 for (i = 0; i < 4; i++) {
1691 if (!global->quiet)
1692 fprintf(stderr, "%.3f ", pkt->data.psnr.psnr[i]);
1693 stream->psnr_totals[i] += pkt->data.psnr.psnr[i];
1695 stream->psnr_count++;
1698 break;
1699 default:
1700 break;
1706 static void show_psnr(struct stream_state *stream, double peak) {
1707 int i;
1708 double ovpsnr;
1710 if (!stream->psnr_count)
1711 return;
1713 fprintf(stderr, "Stream %d PSNR (Overall/Avg/Y/U/V)", stream->index);
1714 ovpsnr = sse_to_psnr((double)stream->psnr_samples_total, peak,
1715 (double)stream->psnr_sse_total);
1716 fprintf(stderr, " %.3f", ovpsnr);
1718 for (i = 0; i < 4; i++) {
1719 fprintf(stderr, " %.3f", stream->psnr_totals[i] / stream->psnr_count);
1721 fprintf(stderr, "\n");
1725 static float usec_to_fps(uint64_t usec, unsigned int frames) {
1726 return (float)(usec > 0 ? frames * 1000000.0 / (float)usec : 0);
1729 static void test_decode(struct stream_state *stream,
1730 enum TestDecodeFatality fatal,
1731 const VpxInterface *codec) {
1732 vpx_image_t enc_img, dec_img;
1734 if (stream->mismatch_seen)
1735 return;
1737 /* Get the internal reference frame */
1738 if (strcmp(codec->name, "vp8") == 0) {
1739 struct vpx_ref_frame ref_enc, ref_dec;
1740 int width, height;
1742 width = (stream->config.cfg.g_w + 15) & ~15;
1743 height = (stream->config.cfg.g_h + 15) & ~15;
1744 vpx_img_alloc(&ref_enc.img, VPX_IMG_FMT_I420, width, height, 1);
1745 enc_img = ref_enc.img;
1746 vpx_img_alloc(&ref_dec.img, VPX_IMG_FMT_I420, width, height, 1);
1747 dec_img = ref_dec.img;
1749 ref_enc.frame_type = VP8_LAST_FRAME;
1750 ref_dec.frame_type = VP8_LAST_FRAME;
1751 vpx_codec_control(&stream->encoder, VP8_COPY_REFERENCE, &ref_enc);
1752 vpx_codec_control(&stream->decoder, VP8_COPY_REFERENCE, &ref_dec);
1753 } else {
1754 struct vp9_ref_frame ref_enc, ref_dec;
1756 ref_enc.idx = 0;
1757 ref_dec.idx = 0;
1758 vpx_codec_control(&stream->encoder, VP9_GET_REFERENCE, &ref_enc);
1759 enc_img = ref_enc.img;
1760 vpx_codec_control(&stream->decoder, VP9_GET_REFERENCE, &ref_dec);
1761 dec_img = ref_dec.img;
1762 #if CONFIG_VP9 && CONFIG_VP9_HIGHBITDEPTH
1763 if ((enc_img.fmt & VPX_IMG_FMT_HIGHBITDEPTH) !=
1764 (dec_img.fmt & VPX_IMG_FMT_HIGHBITDEPTH)) {
1765 if (enc_img.fmt & VPX_IMG_FMT_HIGHBITDEPTH) {
1766 vpx_img_alloc(&enc_img, enc_img.fmt - VPX_IMG_FMT_HIGHBITDEPTH,
1767 enc_img.d_w, enc_img.d_h, 16);
1768 vpx_img_truncate_16_to_8(&enc_img, &ref_enc.img);
1770 if (dec_img.fmt & VPX_IMG_FMT_HIGHBITDEPTH) {
1771 vpx_img_alloc(&dec_img, dec_img.fmt - VPX_IMG_FMT_HIGHBITDEPTH,
1772 dec_img.d_w, dec_img.d_h, 16);
1773 vpx_img_truncate_16_to_8(&dec_img, &ref_dec.img);
1776 #endif
1778 ctx_exit_on_error(&stream->encoder, "Failed to get encoder reference frame");
1779 ctx_exit_on_error(&stream->decoder, "Failed to get decoder reference frame");
1781 if (!compare_img(&enc_img, &dec_img)) {
1782 int y[4], u[4], v[4];
1783 #if CONFIG_VP9 && CONFIG_VP9_HIGHBITDEPTH
1784 if (enc_img.fmt & VPX_IMG_FMT_HIGHBITDEPTH) {
1785 find_mismatch_high(&enc_img, &dec_img, y, u, v);
1786 } else {
1787 find_mismatch(&enc_img, &dec_img, y, u, v);
1789 #else
1790 find_mismatch(&enc_img, &dec_img, y, u, v);
1791 #endif
1792 stream->decoder.err = 1;
1793 warn_or_exit_on_error(&stream->decoder, fatal == TEST_DECODE_FATAL,
1794 "Stream %d: Encode/decode mismatch on frame %d at"
1795 " Y[%d, %d] {%d/%d},"
1796 " U[%d, %d] {%d/%d},"
1797 " V[%d, %d] {%d/%d}",
1798 stream->index, stream->frames_out,
1799 y[0], y[1], y[2], y[3],
1800 u[0], u[1], u[2], u[3],
1801 v[0], v[1], v[2], v[3]);
1802 stream->mismatch_seen = stream->frames_out;
1805 vpx_img_free(&enc_img);
1806 vpx_img_free(&dec_img);
1810 static void print_time(const char *label, int64_t etl) {
1811 int64_t hours;
1812 int64_t mins;
1813 int64_t secs;
1815 if (etl >= 0) {
1816 hours = etl / 3600;
1817 etl -= hours * 3600;
1818 mins = etl / 60;
1819 etl -= mins * 60;
1820 secs = etl;
1822 fprintf(stderr, "[%3s %2"PRId64":%02"PRId64":%02"PRId64"] ",
1823 label, hours, mins, secs);
1824 } else {
1825 fprintf(stderr, "[%3s unknown] ", label);
1830 int main(int argc, const char **argv_) {
1831 int pass;
1832 vpx_image_t raw;
1833 #if CONFIG_VP9 && CONFIG_VP9_HIGHBITDEPTH
1834 vpx_image_t raw_shift;
1835 int allocated_raw_shift = 0;
1836 int use_16bit_internal = 0;
1837 int input_shift = 0;
1838 #endif
1839 int frame_avail, got_data;
1841 struct VpxInputContext input;
1842 struct VpxEncoderConfig global;
1843 struct stream_state *streams = NULL;
1844 char **argv, **argi;
1845 uint64_t cx_time = 0;
1846 int stream_cnt = 0;
1847 int res = 0;
1849 memset(&input, 0, sizeof(input));
1850 exec_name = argv_[0];
1852 if (argc < 3)
1853 usage_exit();
1855 /* Setup default input stream settings */
1856 input.framerate.numerator = 30;
1857 input.framerate.denominator = 1;
1858 input.only_i420 = 1;
1859 input.bit_depth = 0;
1861 /* First parse the global configuration values, because we want to apply
1862 * other parameters on top of the default configuration provided by the
1863 * codec.
1865 argv = argv_dup(argc - 1, argv_ + 1);
1866 parse_global_config(&global, argv);
1868 switch (global.color_type) {
1869 case I420:
1870 input.fmt = VPX_IMG_FMT_I420;
1871 break;
1872 case I422:
1873 input.fmt = VPX_IMG_FMT_I422;
1874 break;
1875 case I444:
1876 input.fmt = VPX_IMG_FMT_I444;
1877 break;
1878 case I440:
1879 input.fmt = VPX_IMG_FMT_I440;
1880 break;
1881 case YV12:
1882 input.fmt = VPX_IMG_FMT_YV12;
1883 break;
1887 /* Now parse each stream's parameters. Using a local scope here
1888 * due to the use of 'stream' as loop variable in FOREACH_STREAM
1889 * loops
1891 struct stream_state *stream = NULL;
1893 do {
1894 stream = new_stream(&global, stream);
1895 stream_cnt++;
1896 if (!streams)
1897 streams = stream;
1898 } while (parse_stream_params(&global, stream, argv));
1901 /* Check for unrecognized options */
1902 for (argi = argv; *argi; argi++)
1903 if (argi[0][0] == '-' && argi[0][1])
1904 die("Error: Unrecognized option %s\n", *argi);
1906 FOREACH_STREAM(check_encoder_config(global.disable_warning_prompt,
1907 &global, &stream->config.cfg););
1909 /* Handle non-option arguments */
1910 input.filename = argv[0];
1912 if (!input.filename)
1913 usage_exit();
1915 /* Decide if other chroma subsamplings than 4:2:0 are supported */
1916 if (global.codec->fourcc == VP9_FOURCC)
1917 input.only_i420 = 0;
1919 for (pass = global.pass ? global.pass - 1 : 0; pass < global.passes; pass++) {
1920 int frames_in = 0, seen_frames = 0;
1921 int64_t estimated_time_left = -1;
1922 int64_t average_rate = -1;
1923 int64_t lagged_count = 0;
1925 open_input_file(&input);
1927 /* If the input file doesn't specify its w/h (raw files), try to get
1928 * the data from the first stream's configuration.
1930 if (!input.width || !input.height) {
1931 FOREACH_STREAM({
1932 if (stream->config.cfg.g_w && stream->config.cfg.g_h) {
1933 input.width = stream->config.cfg.g_w;
1934 input.height = stream->config.cfg.g_h;
1935 break;
1940 /* Update stream configurations from the input file's parameters */
1941 if (!input.width || !input.height)
1942 fatal("Specify stream dimensions with --width (-w) "
1943 " and --height (-h)");
1945 /* If input file does not specify bit-depth but input-bit-depth parameter
1946 * exists, assume that to be the input bit-depth. However, if the
1947 * input-bit-depth paramter does not exist, assume the input bit-depth
1948 * to be the same as the codec bit-depth.
1950 if (!input.bit_depth) {
1951 FOREACH_STREAM({
1952 if (stream->config.cfg.g_input_bit_depth)
1953 input.bit_depth = stream->config.cfg.g_input_bit_depth;
1954 else
1955 input.bit_depth = stream->config.cfg.g_input_bit_depth =
1956 (int)stream->config.cfg.g_bit_depth;
1958 if (input.bit_depth > 8) input.fmt |= VPX_IMG_FMT_HIGHBITDEPTH;
1959 } else {
1960 FOREACH_STREAM({
1961 stream->config.cfg.g_input_bit_depth = input.bit_depth;
1965 FOREACH_STREAM(set_stream_dimensions(stream, input.width, input.height));
1966 FOREACH_STREAM(validate_stream_config(stream, &global));
1968 /* Ensure that --passes and --pass are consistent. If --pass is set and
1969 * --passes=2, ensure --fpf was set.
1971 if (global.pass && global.passes == 2)
1972 FOREACH_STREAM( {
1973 if (!stream->config.stats_fn)
1974 die("Stream %d: Must specify --fpf when --pass=%d"
1975 " and --passes=2\n", stream->index, global.pass);
1978 #if !CONFIG_WEBM_IO
1979 FOREACH_STREAM({
1980 stream->config.write_webm = 0;
1981 warn("vpxenc was compiled without WebM container support."
1982 "Producing IVF output");
1984 #endif
1986 /* Use the frame rate from the file only if none was specified
1987 * on the command-line.
1989 if (!global.have_framerate) {
1990 global.framerate.num = input.framerate.numerator;
1991 global.framerate.den = input.framerate.denominator;
1994 FOREACH_STREAM(set_default_kf_interval(stream, &global));
1996 /* Show configuration */
1997 if (global.verbose && pass == 0)
1998 FOREACH_STREAM(show_stream_config(stream, &global, &input));
2000 if (pass == (global.pass ? global.pass - 1 : 0)) {
2001 if (input.file_type == FILE_TYPE_Y4M)
2002 /*The Y4M reader does its own allocation.
2003 Just initialize this here to avoid problems if we never read any
2004 frames.*/
2005 memset(&raw, 0, sizeof(raw));
2006 else
2007 vpx_img_alloc(&raw, input.fmt, input.width, input.height, 32);
2009 FOREACH_STREAM(stream->rate_hist =
2010 init_rate_histogram(&stream->config.cfg,
2011 &global.framerate));
2014 FOREACH_STREAM(setup_pass(stream, &global, pass));
2015 FOREACH_STREAM(open_output_file(stream, &global));
2016 FOREACH_STREAM(initialize_encoder(stream, &global));
2018 #if CONFIG_VP9 && CONFIG_VP9_HIGHBITDEPTH
2019 if (strcmp(global.codec->name, "vp9") == 0) {
2020 // Check to see if at least one stream uses 16 bit internal.
2021 // Currently assume that the bit_depths for all streams using
2022 // highbitdepth are the same.
2023 FOREACH_STREAM({
2024 if (stream->config.use_16bit_internal) {
2025 use_16bit_internal = 1;
2027 if (stream->config.cfg.g_profile == 0) {
2028 input_shift = 0;
2029 } else {
2030 input_shift = (int)stream->config.cfg.g_bit_depth -
2031 stream->config.cfg.g_input_bit_depth;
2035 #endif
2037 frame_avail = 1;
2038 got_data = 0;
2040 while (frame_avail || got_data) {
2041 struct vpx_usec_timer timer;
2043 if (!global.limit || frames_in < global.limit) {
2044 frame_avail = read_frame(&input, &raw);
2046 if (frame_avail)
2047 frames_in++;
2048 seen_frames = frames_in > global.skip_frames ?
2049 frames_in - global.skip_frames : 0;
2051 if (!global.quiet) {
2052 float fps = usec_to_fps(cx_time, seen_frames);
2053 fprintf(stderr, "\rPass %d/%d ", pass + 1, global.passes);
2055 if (stream_cnt == 1)
2056 fprintf(stderr,
2057 "frame %4d/%-4d %7"PRId64"B ",
2058 frames_in, streams->frames_out, (int64_t)streams->nbytes);
2059 else
2060 fprintf(stderr, "frame %4d ", frames_in);
2062 fprintf(stderr, "%7"PRId64" %s %.2f %s ",
2063 cx_time > 9999999 ? cx_time / 1000 : cx_time,
2064 cx_time > 9999999 ? "ms" : "us",
2065 fps >= 1.0 ? fps : fps * 60,
2066 fps >= 1.0 ? "fps" : "fpm");
2067 print_time("ETA", estimated_time_left);
2070 } else
2071 frame_avail = 0;
2073 if (frames_in > global.skip_frames) {
2074 #if CONFIG_VP9 && CONFIG_VP9_HIGHBITDEPTH
2075 vpx_image_t *frame_to_encode;
2076 if (input_shift || (use_16bit_internal && input.bit_depth == 8)) {
2077 assert(use_16bit_internal);
2078 // Input bit depth and stream bit depth do not match, so up
2079 // shift frame to stream bit depth
2080 if (!allocated_raw_shift) {
2081 vpx_img_alloc(&raw_shift, raw.fmt | VPX_IMG_FMT_HIGHBITDEPTH,
2082 input.width, input.height, 32);
2083 allocated_raw_shift = 1;
2085 vpx_img_upshift(&raw_shift, &raw, input_shift);
2086 frame_to_encode = &raw_shift;
2087 } else {
2088 frame_to_encode = &raw;
2090 vpx_usec_timer_start(&timer);
2091 if (use_16bit_internal) {
2092 assert(frame_to_encode->fmt & VPX_IMG_FMT_HIGHBITDEPTH);
2093 FOREACH_STREAM({
2094 if (stream->config.use_16bit_internal)
2095 encode_frame(stream, &global,
2096 frame_avail ? frame_to_encode : NULL,
2097 frames_in);
2098 else
2099 assert(0);
2101 } else {
2102 assert((frame_to_encode->fmt & VPX_IMG_FMT_HIGHBITDEPTH) == 0);
2103 FOREACH_STREAM(encode_frame(stream, &global,
2104 frame_avail ? frame_to_encode : NULL,
2105 frames_in));
2107 #else
2108 vpx_usec_timer_start(&timer);
2109 FOREACH_STREAM(encode_frame(stream, &global,
2110 frame_avail ? &raw : NULL,
2111 frames_in));
2112 #endif
2113 vpx_usec_timer_mark(&timer);
2114 cx_time += vpx_usec_timer_elapsed(&timer);
2116 FOREACH_STREAM(update_quantizer_histogram(stream));
2118 got_data = 0;
2119 FOREACH_STREAM(get_cx_data(stream, &global, &got_data));
2121 if (!got_data && input.length && streams != NULL &&
2122 !streams->frames_out) {
2123 lagged_count = global.limit ? seen_frames : ftello(input.file);
2124 } else if (input.length) {
2125 int64_t remaining;
2126 int64_t rate;
2128 if (global.limit) {
2129 const int64_t frame_in_lagged = (seen_frames - lagged_count) * 1000;
2131 rate = cx_time ? frame_in_lagged * (int64_t)1000000 / cx_time : 0;
2132 remaining = 1000 * (global.limit - global.skip_frames
2133 - seen_frames + lagged_count);
2134 } else {
2135 const int64_t input_pos = ftello(input.file);
2136 const int64_t input_pos_lagged = input_pos - lagged_count;
2137 const int64_t limit = input.length;
2139 rate = cx_time ? input_pos_lagged * (int64_t)1000000 / cx_time : 0;
2140 remaining = limit - input_pos + lagged_count;
2143 average_rate = (average_rate <= 0)
2144 ? rate
2145 : (average_rate * 7 + rate) / 8;
2146 estimated_time_left = average_rate ? remaining / average_rate : -1;
2149 if (got_data && global.test_decode != TEST_DECODE_OFF)
2150 FOREACH_STREAM(test_decode(stream, global.test_decode, global.codec));
2153 fflush(stdout);
2154 if (!global.quiet)
2155 fprintf(stderr, "\033[K");
2158 if (stream_cnt > 1)
2159 fprintf(stderr, "\n");
2161 if (!global.quiet) {
2162 FOREACH_STREAM(fprintf(stderr,
2163 "\rPass %d/%d frame %4d/%-4d %7"PRId64"B %7"PRId64"b/f %7"PRId64"b/s"
2164 " %7"PRId64" %s (%.2f fps)\033[K\n",
2165 pass + 1,
2166 global.passes, frames_in, stream->frames_out, (int64_t)stream->nbytes,
2167 seen_frames ? (int64_t)(stream->nbytes * 8 / seen_frames) : 0,
2168 seen_frames ? (int64_t)stream->nbytes * 8 *
2169 (int64_t)global.framerate.num / global.framerate.den /
2170 seen_frames : 0,
2171 stream->cx_time > 9999999 ? stream->cx_time / 1000 : stream->cx_time,
2172 stream->cx_time > 9999999 ? "ms" : "us",
2173 usec_to_fps(stream->cx_time, seen_frames)));
2176 if (global.show_psnr) {
2177 if (global.codec->fourcc == VP9_FOURCC) {
2178 FOREACH_STREAM(
2179 show_psnr(stream, (1 << stream->config.cfg.g_input_bit_depth) - 1));
2180 } else {
2181 FOREACH_STREAM(show_psnr(stream, 255.0));
2185 FOREACH_STREAM(vpx_codec_destroy(&stream->encoder));
2187 if (global.test_decode != TEST_DECODE_OFF) {
2188 FOREACH_STREAM(vpx_codec_destroy(&stream->decoder));
2191 close_input_file(&input);
2193 if (global.test_decode == TEST_DECODE_FATAL) {
2194 FOREACH_STREAM(res |= stream->mismatch_seen);
2196 FOREACH_STREAM(close_output_file(stream, global.codec->fourcc));
2198 FOREACH_STREAM(stats_close(&stream->stats, global.passes - 1));
2200 #if CONFIG_FP_MB_STATS
2201 FOREACH_STREAM(stats_close(&stream->fpmb_stats, global.passes - 1));
2202 #endif
2204 if (global.pass)
2205 break;
2208 if (global.show_q_hist_buckets)
2209 FOREACH_STREAM(show_q_histogram(stream->counts,
2210 global.show_q_hist_buckets));
2212 if (global.show_rate_hist_buckets)
2213 FOREACH_STREAM(show_rate_histogram(stream->rate_hist,
2214 &stream->config.cfg,
2215 global.show_rate_hist_buckets));
2216 FOREACH_STREAM(destroy_rate_histogram(stream->rate_hist));
2218 #if CONFIG_INTERNAL_STATS
2219 /* TODO(jkoleszar): This doesn't belong in this executable. Do it for now,
2220 * to match some existing utilities.
2222 if (!(global.pass == 1 && global.passes == 2))
2223 FOREACH_STREAM({
2224 FILE *f = fopen("opsnr.stt", "a");
2225 if (stream->mismatch_seen) {
2226 fprintf(f, "First mismatch occurred in frame %d\n",
2227 stream->mismatch_seen);
2228 } else {
2229 fprintf(f, "No mismatch detected in recon buffers\n");
2231 fclose(f);
2233 #endif
2235 #if CONFIG_VP9 && CONFIG_VP9_HIGHBITDEPTH
2236 if (allocated_raw_shift)
2237 vpx_img_free(&raw_shift);
2238 #endif
2239 vpx_img_free(&raw);
2240 free(argv);
2241 free(streams);
2242 return res ? EXIT_FAILURE : EXIT_SUCCESS;