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"
22 #include "vpx/vpx_encoder.h"
24 #include "vpx/vpx_decoder.h"
27 #include "third_party/libyuv/include/libyuv/scale.h"
32 #if CONFIG_VP8_ENCODER || CONFIG_VP9_ENCODER
33 #include "vpx/vp8cx.h"
35 #if CONFIG_VP8_DECODER || CONFIG_VP9_DECODER
36 #include "vpx/vp8dx.h"
39 #include "./tools_common.h"
40 #include "vpx_ports/mem_ops.h"
41 #include "vpx_ports/vpx_timer.h"
42 #include "./vpxstats.h"
43 #include "./warnings.h"
44 #include "./webmenc.h"
45 #include "./y4minput.h"
47 /* Swallow warnings about unused results of fread/fwrite */
48 static size_t wrap_fread(void *ptr, size_t size, size_t nmemb,
50 return fread(ptr, size, nmemb, stream);
52 #define fread wrap_fread
54 static size_t wrap_fwrite(const void *ptr, size_t size, size_t nmemb,
56 return fwrite(ptr, size, nmemb, stream);
58 #define fwrite wrap_fwrite
61 static const char *exec_name;
63 static const struct codec_item {
65 const vpx_codec_iface_t *(*iface)(void);
66 const vpx_codec_iface_t *(*dx_iface)(void);
69 #if CONFIG_VP8_ENCODER && CONFIG_VP8_DECODER
70 {"vp8", &vpx_codec_vp8_cx, &vpx_codec_vp8_dx, VP8_FOURCC},
71 #elif CONFIG_VP8_ENCODER && !CONFIG_VP8_DECODER
72 {"vp8", &vpx_codec_vp8_cx, NULL, VP8_FOURCC},
74 #if CONFIG_VP9_ENCODER && CONFIG_VP9_DECODER
75 {"vp9", &vpx_codec_vp9_cx, &vpx_codec_vp9_dx, VP9_FOURCC},
76 #elif CONFIG_VP9_ENCODER && !CONFIG_VP9_DECODER
77 {"vp9", &vpx_codec_vp9_cx, NULL, VP9_FOURCC},
81 static void warn_or_exit_on_errorv(vpx_codec_ctx_t *ctx, int fatal,
82 const char *s, va_list ap) {
84 const char *detail = vpx_codec_error_detail(ctx);
86 vfprintf(stderr, s, ap);
87 fprintf(stderr, ": %s\n", vpx_codec_error(ctx));
90 fprintf(stderr, " %s\n", detail);
97 static void ctx_exit_on_error(vpx_codec_ctx_t *ctx, const char *s, ...) {
101 warn_or_exit_on_errorv(ctx, 1, s, ap);
105 static void warn_or_exit_on_error(vpx_codec_ctx_t *ctx, int fatal,
106 const char *s, ...) {
110 warn_or_exit_on_errorv(ctx, fatal, s, ap);
114 int read_frame(struct VpxInputContext *input_ctx, vpx_image_t *img) {
115 FILE *f = input_ctx->file;
116 y4m_input *y4m = &input_ctx->y4m;
119 if (input_ctx->file_type == FILE_TYPE_Y4M) {
120 if (y4m_input_fetch_frame(y4m, f, img) < 1)
123 shortread = read_yuv_frame(input_ctx, img);
129 int file_is_y4m(FILE *infile, y4m_input *y4m, const char detect[4]) {
130 if (memcmp(detect, "YUV4", 4) == 0) {
137 /* Murmur hash derived from public domain reference implementation at
138 * http:// sites.google.com/site/murmurhash/
140 static unsigned int murmur(const void *key, int len, unsigned int seed) {
141 const unsigned int m = 0x5bd1e995;
144 unsigned int h = seed ^ len;
146 const unsigned char *data = (const unsigned char *)key;
151 k = (unsigned int)data[0];
152 k |= (unsigned int)data[1] << 8;
153 k |= (unsigned int)data[2] << 16;
154 k |= (unsigned int)data[3] << 24;
185 static const arg_def_t debugmode = ARG_DEF("D", "debug", 0,
186 "Debug mode (makes output deterministic)");
187 static const arg_def_t outputfile = ARG_DEF("o", "output", 1,
189 static const arg_def_t use_yv12 = ARG_DEF(NULL, "yv12", 0,
190 "Input file is YV12 ");
191 static const arg_def_t use_i420 = ARG_DEF(NULL, "i420", 0,
192 "Input file is I420 (default)");
193 static const arg_def_t codecarg = ARG_DEF(NULL, "codec", 1,
195 static const arg_def_t passes = ARG_DEF("p", "passes", 1,
196 "Number of passes (1/2)");
197 static const arg_def_t pass_arg = ARG_DEF(NULL, "pass", 1,
198 "Pass to execute (1/2)");
199 static const arg_def_t fpf_name = ARG_DEF(NULL, "fpf", 1,
200 "First pass statistics file name");
201 static const arg_def_t limit = ARG_DEF(NULL, "limit", 1,
202 "Stop encoding after n input frames");
203 static const arg_def_t skip = ARG_DEF(NULL, "skip", 1,
204 "Skip the first n input frames");
205 static const arg_def_t deadline = ARG_DEF("d", "deadline", 1,
206 "Deadline per frame (usec)");
207 static const arg_def_t best_dl = ARG_DEF(NULL, "best", 0,
208 "Use Best Quality Deadline");
209 static const arg_def_t good_dl = ARG_DEF(NULL, "good", 0,
210 "Use Good Quality Deadline");
211 static const arg_def_t rt_dl = ARG_DEF(NULL, "rt", 0,
212 "Use Realtime Quality Deadline");
213 static const arg_def_t quietarg = ARG_DEF("q", "quiet", 0,
214 "Do not print encode progress");
215 static const arg_def_t verbosearg = ARG_DEF("v", "verbose", 0,
216 "Show encoder parameters");
217 static const arg_def_t psnrarg = ARG_DEF(NULL, "psnr", 0,
218 "Show PSNR in status line");
220 static const struct arg_enum_list test_decode_enum[] = {
221 {"off", TEST_DECODE_OFF},
222 {"fatal", TEST_DECODE_FATAL},
223 {"warn", TEST_DECODE_WARN},
226 static const arg_def_t recontest = ARG_DEF_ENUM(NULL, "test-decode", 1,
227 "Test encode/decode mismatch",
229 static const arg_def_t framerate = ARG_DEF(NULL, "fps", 1,
230 "Stream frame rate (rate/scale)");
231 static const arg_def_t use_ivf = ARG_DEF(NULL, "ivf", 0,
232 "Output IVF (default is WebM)");
233 static const arg_def_t out_part = ARG_DEF("P", "output-partitions", 0,
234 "Makes encoder output partitions. Requires IVF output!");
235 static const arg_def_t q_hist_n = ARG_DEF(NULL, "q-hist", 1,
236 "Show quantizer histogram (n-buckets)");
237 static const arg_def_t rate_hist_n = ARG_DEF(NULL, "rate-hist", 1,
238 "Show rate histogram (n-buckets)");
239 static const arg_def_t disable_warnings =
240 ARG_DEF(NULL, "disable-warnings", 0,
241 "Disable warnings about potentially incorrect encode settings.");
242 static const arg_def_t disable_warning_prompt =
243 ARG_DEF("y", "disable-warning-prompt", 0,
244 "Display warnings, but do not prompt user to continue.");
246 static const arg_def_t *main_args[] = {
248 &outputfile, &codecarg, &passes, &pass_arg, &fpf_name, &limit, &skip,
249 &deadline, &best_dl, &good_dl, &rt_dl,
250 &quietarg, &verbosearg, &psnrarg, &use_ivf, &out_part, &q_hist_n,
251 &rate_hist_n, &disable_warnings, &disable_warning_prompt,
255 static const arg_def_t usage = ARG_DEF("u", "usage", 1,
256 "Usage profile number to use");
257 static const arg_def_t threads = ARG_DEF("t", "threads", 1,
258 "Max number of threads to use");
259 static const arg_def_t profile = ARG_DEF(NULL, "profile", 1,
260 "Bitstream profile number to use");
261 static const arg_def_t width = ARG_DEF("w", "width", 1,
263 static const arg_def_t height = ARG_DEF("h", "height", 1,
265 static const struct arg_enum_list stereo_mode_enum[] = {
266 {"mono", STEREO_FORMAT_MONO},
267 {"left-right", STEREO_FORMAT_LEFT_RIGHT},
268 {"bottom-top", STEREO_FORMAT_BOTTOM_TOP},
269 {"top-bottom", STEREO_FORMAT_TOP_BOTTOM},
270 {"right-left", STEREO_FORMAT_RIGHT_LEFT},
273 static const arg_def_t stereo_mode = ARG_DEF_ENUM(NULL, "stereo-mode", 1,
274 "Stereo 3D video format", stereo_mode_enum);
275 static const arg_def_t timebase = ARG_DEF(NULL, "timebase", 1,
276 "Output timestamp precision (fractional seconds)");
277 static const arg_def_t error_resilient = ARG_DEF(NULL, "error-resilient", 1,
278 "Enable error resiliency features");
279 static const arg_def_t lag_in_frames = ARG_DEF(NULL, "lag-in-frames", 1,
280 "Max number of frames to lag");
282 static const arg_def_t *global_args[] = {
283 &use_yv12, &use_i420, &usage, &threads, &profile,
284 &width, &height, &stereo_mode, &timebase, &framerate,
289 static const arg_def_t dropframe_thresh = ARG_DEF(NULL, "drop-frame", 1,
290 "Temporal resampling threshold (buf %)");
291 static const arg_def_t resize_allowed = ARG_DEF(NULL, "resize-allowed", 1,
292 "Spatial resampling enabled (bool)");
293 static const arg_def_t resize_up_thresh = ARG_DEF(NULL, "resize-up", 1,
294 "Upscale threshold (buf %)");
295 static const arg_def_t resize_down_thresh = ARG_DEF(NULL, "resize-down", 1,
296 "Downscale threshold (buf %)");
297 static const struct arg_enum_list end_usage_enum[] = {
304 static const arg_def_t end_usage = ARG_DEF_ENUM(NULL, "end-usage", 1,
305 "Rate control mode", end_usage_enum);
306 static const arg_def_t target_bitrate = ARG_DEF(NULL, "target-bitrate", 1,
308 static const arg_def_t min_quantizer = ARG_DEF(NULL, "min-q", 1,
309 "Minimum (best) quantizer");
310 static const arg_def_t max_quantizer = ARG_DEF(NULL, "max-q", 1,
311 "Maximum (worst) quantizer");
312 static const arg_def_t undershoot_pct = ARG_DEF(NULL, "undershoot-pct", 1,
313 "Datarate undershoot (min) target (%)");
314 static const arg_def_t overshoot_pct = ARG_DEF(NULL, "overshoot-pct", 1,
315 "Datarate overshoot (max) target (%)");
316 static const arg_def_t buf_sz = ARG_DEF(NULL, "buf-sz", 1,
317 "Client buffer size (ms)");
318 static const arg_def_t buf_initial_sz = ARG_DEF(NULL, "buf-initial-sz", 1,
319 "Client initial buffer size (ms)");
320 static const arg_def_t buf_optimal_sz = ARG_DEF(NULL, "buf-optimal-sz", 1,
321 "Client optimal buffer size (ms)");
322 static const arg_def_t *rc_args[] = {
323 &dropframe_thresh, &resize_allowed, &resize_up_thresh, &resize_down_thresh,
324 &end_usage, &target_bitrate, &min_quantizer, &max_quantizer,
325 &undershoot_pct, &overshoot_pct, &buf_sz, &buf_initial_sz, &buf_optimal_sz,
330 static const arg_def_t bias_pct = ARG_DEF(NULL, "bias-pct", 1,
331 "CBR/VBR bias (0=CBR, 100=VBR)");
332 static const arg_def_t minsection_pct = ARG_DEF(NULL, "minsection-pct", 1,
333 "GOP min bitrate (% of target)");
334 static const arg_def_t maxsection_pct = ARG_DEF(NULL, "maxsection-pct", 1,
335 "GOP max bitrate (% of target)");
336 static const arg_def_t *rc_twopass_args[] = {
337 &bias_pct, &minsection_pct, &maxsection_pct, NULL
341 static const arg_def_t kf_min_dist = ARG_DEF(NULL, "kf-min-dist", 1,
342 "Minimum keyframe interval (frames)");
343 static const arg_def_t kf_max_dist = ARG_DEF(NULL, "kf-max-dist", 1,
344 "Maximum keyframe interval (frames)");
345 static const arg_def_t kf_disabled = ARG_DEF(NULL, "disable-kf", 0,
346 "Disable keyframe placement");
347 static const arg_def_t *kf_args[] = {
348 &kf_min_dist, &kf_max_dist, &kf_disabled, NULL
352 static const arg_def_t noise_sens = ARG_DEF(NULL, "noise-sensitivity", 1,
353 "Noise sensitivity (frames to blur)");
354 static const arg_def_t sharpness = ARG_DEF(NULL, "sharpness", 1,
355 "Filter sharpness (0-7)");
356 static const arg_def_t static_thresh = ARG_DEF(NULL, "static-thresh", 1,
357 "Motion detection threshold");
358 static const arg_def_t cpu_used = ARG_DEF(NULL, "cpu-used", 1,
359 "CPU Used (-16..16)");
360 static const arg_def_t token_parts = ARG_DEF(NULL, "token-parts", 1,
361 "Number of token partitions to use, log2");
362 static const arg_def_t tile_cols = ARG_DEF(NULL, "tile-columns", 1,
363 "Number of tile columns to use, log2");
364 static const arg_def_t tile_rows = ARG_DEF(NULL, "tile-rows", 1,
365 "Number of tile rows to use, log2");
366 static const arg_def_t auto_altref = ARG_DEF(NULL, "auto-alt-ref", 1,
367 "Enable automatic alt reference frames");
368 static const arg_def_t arnr_maxframes = ARG_DEF(NULL, "arnr-maxframes", 1,
369 "AltRef Max Frames");
370 static const arg_def_t arnr_strength = ARG_DEF(NULL, "arnr-strength", 1,
372 static const arg_def_t arnr_type = ARG_DEF(NULL, "arnr-type", 1,
374 static const struct arg_enum_list tuning_enum[] = {
375 {"psnr", VP8_TUNE_PSNR},
376 {"ssim", VP8_TUNE_SSIM},
379 static const arg_def_t tune_ssim = ARG_DEF_ENUM(NULL, "tune", 1,
380 "Material to favor", tuning_enum);
381 static const arg_def_t cq_level = ARG_DEF(NULL, "cq-level", 1,
382 "Constant/Constrained Quality level");
383 static const arg_def_t max_intra_rate_pct = ARG_DEF(NULL, "max-intra-rate", 1,
384 "Max I-frame bitrate (pct)");
385 static const arg_def_t lossless = ARG_DEF(NULL, "lossless", 1, "Lossless mode");
386 #if CONFIG_VP9_ENCODER
387 static const arg_def_t frame_parallel_decoding = ARG_DEF(
388 NULL, "frame-parallel", 1, "Enable frame parallel decodability features");
389 static const arg_def_t aq_mode = ARG_DEF(
391 "Adaptive q mode (0: off (by default), 1: variance 2: complexity)");
394 #if CONFIG_VP8_ENCODER
395 static const arg_def_t *vp8_args[] = {
396 &cpu_used, &auto_altref, &noise_sens, &sharpness, &static_thresh,
397 &token_parts, &arnr_maxframes, &arnr_strength, &arnr_type,
398 &tune_ssim, &cq_level, &max_intra_rate_pct,
401 static const int vp8_arg_ctrl_map[] = {
402 VP8E_SET_CPUUSED, VP8E_SET_ENABLEAUTOALTREF,
403 VP8E_SET_NOISE_SENSITIVITY, VP8E_SET_SHARPNESS, VP8E_SET_STATIC_THRESHOLD,
404 VP8E_SET_TOKEN_PARTITIONS,
405 VP8E_SET_ARNR_MAXFRAMES, VP8E_SET_ARNR_STRENGTH, VP8E_SET_ARNR_TYPE,
406 VP8E_SET_TUNING, VP8E_SET_CQ_LEVEL, VP8E_SET_MAX_INTRA_BITRATE_PCT,
411 #if CONFIG_VP9_ENCODER
412 static const arg_def_t *vp9_args[] = {
413 &cpu_used, &auto_altref, &noise_sens, &sharpness, &static_thresh,
414 &tile_cols, &tile_rows, &arnr_maxframes, &arnr_strength, &arnr_type,
415 &tune_ssim, &cq_level, &max_intra_rate_pct, &lossless,
416 &frame_parallel_decoding, &aq_mode,
419 static const int vp9_arg_ctrl_map[] = {
420 VP8E_SET_CPUUSED, VP8E_SET_ENABLEAUTOALTREF,
421 VP8E_SET_NOISE_SENSITIVITY, VP8E_SET_SHARPNESS, VP8E_SET_STATIC_THRESHOLD,
422 VP9E_SET_TILE_COLUMNS, VP9E_SET_TILE_ROWS,
423 VP8E_SET_ARNR_MAXFRAMES, VP8E_SET_ARNR_STRENGTH, VP8E_SET_ARNR_TYPE,
424 VP8E_SET_TUNING, VP8E_SET_CQ_LEVEL, VP8E_SET_MAX_INTRA_BITRATE_PCT,
425 VP9E_SET_LOSSLESS, VP9E_SET_FRAME_PARALLEL_DECODING, VP9E_SET_AQ_MODE,
430 static const arg_def_t *no_args[] = { NULL };
435 fprintf(stderr, "Usage: %s <options> -o dst_filename src_filename \n",
438 fprintf(stderr, "\nOptions:\n");
439 arg_show_usage(stderr, main_args);
440 fprintf(stderr, "\nEncoder Global Options:\n");
441 arg_show_usage(stderr, global_args);
442 fprintf(stderr, "\nRate Control Options:\n");
443 arg_show_usage(stderr, rc_args);
444 fprintf(stderr, "\nTwopass Rate Control Options:\n");
445 arg_show_usage(stderr, rc_twopass_args);
446 fprintf(stderr, "\nKeyframe Placement Options:\n");
447 arg_show_usage(stderr, kf_args);
448 #if CONFIG_VP8_ENCODER
449 fprintf(stderr, "\nVP8 Specific Options:\n");
450 arg_show_usage(stderr, vp8_args);
452 #if CONFIG_VP9_ENCODER
453 fprintf(stderr, "\nVP9 Specific Options:\n");
454 arg_show_usage(stderr, vp9_args);
456 fprintf(stderr, "\nStream timebase (--timebase):\n"
457 " The desired precision of timestamps in the output, expressed\n"
458 " in fractional seconds. Default is 1/1000.\n");
460 "Included encoders:\n"
463 for (i = 0; i < sizeof(codecs) / sizeof(codecs[0]); i++)
464 fprintf(stderr, " %-6s - %s\n",
466 vpx_codec_iface_name(codecs[i].iface()));
472 #define HIST_BAR_MAX 40
474 int low, high, count;
478 static int merge_hist_buckets(struct hist_bucket *bucket,
481 int small_bucket = 0, merge_bucket = INT_MAX, big_bucket = 0;
482 int buckets = *buckets_;
485 /* Find the extrema for this list of buckets */
486 big_bucket = small_bucket = 0;
487 for (i = 0; i < buckets; i++) {
488 if (bucket[i].count < bucket[small_bucket].count)
490 if (bucket[i].count > bucket[big_bucket].count)
494 /* If we have too many buckets, merge the smallest with an adjacent
497 while (buckets > max_buckets) {
498 int last_bucket = buckets - 1;
500 /* merge the small bucket with an adjacent one. */
501 if (small_bucket == 0)
503 else if (small_bucket == last_bucket)
504 merge_bucket = last_bucket - 1;
505 else if (bucket[small_bucket - 1].count < bucket[small_bucket + 1].count)
506 merge_bucket = small_bucket - 1;
508 merge_bucket = small_bucket + 1;
510 assert(abs(merge_bucket - small_bucket) <= 1);
511 assert(small_bucket < buckets);
512 assert(big_bucket < buckets);
513 assert(merge_bucket < buckets);
515 if (merge_bucket < small_bucket) {
516 bucket[merge_bucket].high = bucket[small_bucket].high;
517 bucket[merge_bucket].count += bucket[small_bucket].count;
519 bucket[small_bucket].high = bucket[merge_bucket].high;
520 bucket[small_bucket].count += bucket[merge_bucket].count;
521 merge_bucket = small_bucket;
524 assert(bucket[merge_bucket].low != bucket[merge_bucket].high);
528 /* Remove the merge_bucket from the list, and find the new small
529 * and big buckets while we're at it
531 big_bucket = small_bucket = 0;
532 for (i = 0; i < buckets; i++) {
533 if (i > merge_bucket)
534 bucket[i] = bucket[i + 1];
536 if (bucket[i].count < bucket[small_bucket].count)
538 if (bucket[i].count > bucket[big_bucket].count)
545 return bucket[big_bucket].count;
549 static void show_histogram(const struct hist_bucket *bucket,
553 const char *pat1, *pat2;
556 switch ((int)(log(bucket[buckets - 1].high) / log(10)) + 1) {
583 pat1 = "%12d %10s: ";
584 pat2 = "%12d-%10d: ";
588 for (i = 0; i < buckets; i++) {
593 pct = (float)(100.0 * bucket[i].count / total);
594 len = HIST_BAR_MAX * bucket[i].count / scale;
597 assert(len <= HIST_BAR_MAX);
599 if (bucket[i].low == bucket[i].high)
600 fprintf(stderr, pat1, bucket[i].low, "");
602 fprintf(stderr, pat2, bucket[i].low, bucket[i].high);
604 for (j = 0; j < HIST_BAR_MAX; j++)
605 fprintf(stderr, j < len ? "=" : " ");
606 fprintf(stderr, "\t%5d (%6.2f%%)\n", bucket[i].count, pct);
611 static void show_q_histogram(const int counts[64], int max_buckets) {
612 struct hist_bucket bucket[64];
619 for (i = 0; i < 64; i++) {
621 bucket[buckets].low = bucket[buckets].high = i;
622 bucket[buckets].count = counts[i];
628 fprintf(stderr, "\nQuantizer Selection:\n");
629 scale = merge_hist_buckets(bucket, &buckets, max_buckets);
630 show_histogram(bucket, buckets, total, scale);
634 #define RATE_BINS (100)
640 struct hist_bucket bucket[RATE_BINS];
645 static void init_rate_histogram(struct rate_hist *hist,
646 const vpx_codec_enc_cfg_t *cfg,
647 const vpx_rational_t *fps) {
650 /* Determine the number of samples in the buffer. Use the file's framerate
651 * to determine the number of frames in rc_buf_sz milliseconds, with an
652 * adjustment (5/4) to account for alt-refs
654 hist->samples = cfg->rc_buf_sz * 5 / 4 * fps->num / fps->den / 1000;
656 /* prevent division by zero */
657 if (hist->samples == 0)
660 hist->pts = calloc(hist->samples, sizeof(*hist->pts));
661 hist->sz = calloc(hist->samples, sizeof(*hist->sz));
662 for (i = 0; i < RATE_BINS; i++) {
663 hist->bucket[i].low = INT_MAX;
664 hist->bucket[i].high = 0;
665 hist->bucket[i].count = 0;
670 static void destroy_rate_histogram(struct rate_hist *hist) {
676 static void update_rate_histogram(struct rate_hist *hist,
677 const vpx_codec_enc_cfg_t *cfg,
678 const vpx_codec_cx_pkt_t *pkt) {
680 int64_t now, then, sum_sz = 0, avg_bitrate;
682 now = pkt->data.frame.pts * 1000
683 * (uint64_t)cfg->g_timebase.num / (uint64_t)cfg->g_timebase.den;
685 idx = hist->frames++ % hist->samples;
686 hist->pts[idx] = now;
687 hist->sz[idx] = (int)pkt->data.frame.sz;
689 if (now < cfg->rc_buf_initial_sz)
694 /* Sum the size over the past rc_buf_sz ms */
695 for (i = hist->frames; i > 0 && hist->frames - i < hist->samples; i--) {
696 int i_idx = (i - 1) % hist->samples;
698 then = hist->pts[i_idx];
699 if (now - then > cfg->rc_buf_sz)
701 sum_sz += hist->sz[i_idx];
707 avg_bitrate = sum_sz * 8 * 1000 / (now - then);
708 idx = (int)(avg_bitrate * (RATE_BINS / 2) / (cfg->rc_target_bitrate * 1000));
711 if (idx > RATE_BINS - 1)
713 if (hist->bucket[idx].low > avg_bitrate)
714 hist->bucket[idx].low = (int)avg_bitrate;
715 if (hist->bucket[idx].high < avg_bitrate)
716 hist->bucket[idx].high = (int)avg_bitrate;
717 hist->bucket[idx].count++;
722 static void show_rate_histogram(struct rate_hist *hist,
723 const vpx_codec_enc_cfg_t *cfg,
728 for (i = 0; i < RATE_BINS; i++) {
729 if (hist->bucket[i].low == INT_MAX)
731 hist->bucket[buckets++] = hist->bucket[i];
734 fprintf(stderr, "\nRate (over %dms window):\n", cfg->rc_buf_sz);
735 scale = merge_hist_buckets(hist->bucket, &buckets, max_buckets);
736 show_histogram(hist->bucket, buckets, hist->total, scale);
739 #define mmin(a, b) ((a) < (b) ? (a) : (b))
740 static void find_mismatch(vpx_image_t *img1, vpx_image_t *img2,
741 int yloc[4], int uloc[4], int vloc[4]) {
742 const unsigned int bsize = 64;
743 const unsigned int bsizey = bsize >> img1->y_chroma_shift;
744 const unsigned int bsizex = bsize >> img1->x_chroma_shift;
745 const int c_w = (img1->d_w + img1->x_chroma_shift) >> img1->x_chroma_shift;
746 const int c_h = (img1->d_h + img1->y_chroma_shift) >> img1->y_chroma_shift;
747 unsigned int match = 1;
749 yloc[0] = yloc[1] = yloc[2] = yloc[3] = -1;
750 for (i = 0, match = 1; match && i < img1->d_h; i += bsize) {
751 for (j = 0; match && j < img1->d_w; j += bsize) {
753 int si = mmin(i + bsize, img1->d_h) - i;
754 int sj = mmin(j + bsize, img1->d_w) - j;
755 for (k = 0; match && k < si; k++)
756 for (l = 0; match && l < sj; l++) {
757 if (*(img1->planes[VPX_PLANE_Y] +
758 (i + k) * img1->stride[VPX_PLANE_Y] + j + l) !=
759 *(img2->planes[VPX_PLANE_Y] +
760 (i + k) * img2->stride[VPX_PLANE_Y] + j + l)) {
763 yloc[2] = *(img1->planes[VPX_PLANE_Y] +
764 (i + k) * img1->stride[VPX_PLANE_Y] + j + l);
765 yloc[3] = *(img2->planes[VPX_PLANE_Y] +
766 (i + k) * img2->stride[VPX_PLANE_Y] + j + l);
774 uloc[0] = uloc[1] = uloc[2] = uloc[3] = -1;
775 for (i = 0, match = 1; match && i < c_h; i += bsizey) {
776 for (j = 0; match && j < c_w; j += bsizex) {
778 int si = mmin(i + bsizey, c_h - i);
779 int sj = mmin(j + bsizex, c_w - j);
780 for (k = 0; match && k < si; k++)
781 for (l = 0; match && l < sj; l++) {
782 if (*(img1->planes[VPX_PLANE_U] +
783 (i + k) * img1->stride[VPX_PLANE_U] + j + l) !=
784 *(img2->planes[VPX_PLANE_U] +
785 (i + k) * img2->stride[VPX_PLANE_U] + j + l)) {
788 uloc[2] = *(img1->planes[VPX_PLANE_U] +
789 (i + k) * img1->stride[VPX_PLANE_U] + j + l);
790 uloc[3] = *(img2->planes[VPX_PLANE_U] +
791 (i + k) * img2->stride[VPX_PLANE_V] + j + l);
798 vloc[0] = vloc[1] = vloc[2] = vloc[3] = -1;
799 for (i = 0, match = 1; match && i < c_h; i += bsizey) {
800 for (j = 0; match && j < c_w; j += bsizex) {
802 int si = mmin(i + bsizey, c_h - i);
803 int sj = mmin(j + bsizex, c_w - j);
804 for (k = 0; match && k < si; k++)
805 for (l = 0; match && l < sj; l++) {
806 if (*(img1->planes[VPX_PLANE_V] +
807 (i + k) * img1->stride[VPX_PLANE_V] + j + l) !=
808 *(img2->planes[VPX_PLANE_V] +
809 (i + k) * img2->stride[VPX_PLANE_V] + j + l)) {
812 vloc[2] = *(img1->planes[VPX_PLANE_V] +
813 (i + k) * img1->stride[VPX_PLANE_V] + j + l);
814 vloc[3] = *(img2->planes[VPX_PLANE_V] +
815 (i + k) * img2->stride[VPX_PLANE_V] + j + l);
824 static int compare_img(vpx_image_t *img1, vpx_image_t *img2)
826 const int c_w = (img1->d_w + img1->x_chroma_shift) >> img1->x_chroma_shift;
827 const int c_h = (img1->d_h + img1->y_chroma_shift) >> img1->y_chroma_shift;
831 match &= (img1->fmt == img2->fmt);
832 match &= (img1->w == img2->w);
833 match &= (img1->h == img2->h);
835 for (i = 0; i < img1->d_h; i++)
836 match &= (memcmp(img1->planes[VPX_PLANE_Y]+i*img1->stride[VPX_PLANE_Y],
837 img2->planes[VPX_PLANE_Y]+i*img2->stride[VPX_PLANE_Y],
840 for (i = 0; i < c_h; i++)
841 match &= (memcmp(img1->planes[VPX_PLANE_U]+i*img1->stride[VPX_PLANE_U],
842 img2->planes[VPX_PLANE_U]+i*img2->stride[VPX_PLANE_U],
845 for (i = 0; i < c_h; i++)
846 match &= (memcmp(img1->planes[VPX_PLANE_V]+i*img1->stride[VPX_PLANE_U],
847 img2->planes[VPX_PLANE_V]+i*img2->stride[VPX_PLANE_U],
854 #define NELEMENTS(x) (sizeof(x)/sizeof(x[0]))
855 #define MAX(x,y) ((x)>(y)?(x):(y))
856 #if CONFIG_VP8_ENCODER && !CONFIG_VP9_ENCODER
857 #define ARG_CTRL_CNT_MAX NELEMENTS(vp8_arg_ctrl_map)
858 #elif !CONFIG_VP8_ENCODER && CONFIG_VP9_ENCODER
859 #define ARG_CTRL_CNT_MAX NELEMENTS(vp9_arg_ctrl_map)
861 #define ARG_CTRL_CNT_MAX MAX(NELEMENTS(vp8_arg_ctrl_map), \
862 NELEMENTS(vp9_arg_ctrl_map))
865 /* Per-stream configuration */
866 struct stream_config {
867 struct vpx_codec_enc_cfg cfg;
869 const char *stats_fn;
870 stereo_format_t stereo_fmt;
871 int arg_ctrls[ARG_CTRL_CNT_MAX][2];
874 int have_kf_max_dist;
878 struct stream_state {
880 struct stream_state *next;
881 struct stream_config config;
883 struct rate_hist rate_hist;
884 struct EbmlGlobal ebml;
886 uint64_t psnr_sse_total;
887 uint64_t psnr_samples_total;
888 double psnr_totals[4];
891 vpx_codec_ctx_t encoder;
892 unsigned int frames_out;
896 struct vpx_image *img;
897 vpx_codec_ctx_t decoder;
902 void validate_positive_rational(const char *msg,
903 struct vpx_rational *rat) {
910 die("Error: %s must be positive\n", msg);
913 die("Error: %s has zero denominator\n", msg);
917 static void parse_global_config(struct VpxEncoderConfig *global, char **argv) {
921 /* Initialize default parameters */
922 memset(global, 0, sizeof(*global));
923 global->codec = codecs;
925 global->use_i420 = 1;
926 /* Assign default deadline to good quality */
927 global->deadline = VPX_DL_GOOD_QUALITY;
929 for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step) {
932 if (arg_match(&arg, &codecarg, argi)) {
935 for (j = 0; j < sizeof(codecs) / sizeof(codecs[0]); j++)
936 if (!strcmp(codecs[j].name, arg.val))
940 global->codec = codecs + k;
942 die("Error: Unrecognized argument (%s) to --codec\n",
945 } else if (arg_match(&arg, &passes, argi)) {
946 global->passes = arg_parse_uint(&arg);
948 if (global->passes < 1 || global->passes > 2)
949 die("Error: Invalid number of passes (%d)\n", global->passes);
950 } else if (arg_match(&arg, &pass_arg, argi)) {
951 global->pass = arg_parse_uint(&arg);
953 if (global->pass < 1 || global->pass > 2)
954 die("Error: Invalid pass selected (%d)\n",
956 } else if (arg_match(&arg, &usage, argi))
957 global->usage = arg_parse_uint(&arg);
958 else if (arg_match(&arg, &deadline, argi))
959 global->deadline = arg_parse_uint(&arg);
960 else if (arg_match(&arg, &best_dl, argi))
961 global->deadline = VPX_DL_BEST_QUALITY;
962 else if (arg_match(&arg, &good_dl, argi))
963 global->deadline = VPX_DL_GOOD_QUALITY;
964 else if (arg_match(&arg, &rt_dl, argi))
965 global->deadline = VPX_DL_REALTIME;
966 else if (arg_match(&arg, &use_yv12, argi))
967 global->use_i420 = 0;
968 else if (arg_match(&arg, &use_i420, argi))
969 global->use_i420 = 1;
970 else if (arg_match(&arg, &quietarg, argi))
972 else if (arg_match(&arg, &verbosearg, argi))
974 else if (arg_match(&arg, &limit, argi))
975 global->limit = arg_parse_uint(&arg);
976 else if (arg_match(&arg, &skip, argi))
977 global->skip_frames = arg_parse_uint(&arg);
978 else if (arg_match(&arg, &psnrarg, argi))
979 global->show_psnr = 1;
980 else if (arg_match(&arg, &recontest, argi))
981 global->test_decode = arg_parse_enum_or_int(&arg);
982 else if (arg_match(&arg, &framerate, argi)) {
983 global->framerate = arg_parse_rational(&arg);
984 validate_positive_rational(arg.name, &global->framerate);
985 global->have_framerate = 1;
986 } else if (arg_match(&arg, &out_part, argi))
987 global->out_part = 1;
988 else if (arg_match(&arg, &debugmode, argi))
990 else if (arg_match(&arg, &q_hist_n, argi))
991 global->show_q_hist_buckets = arg_parse_uint(&arg);
992 else if (arg_match(&arg, &rate_hist_n, argi))
993 global->show_rate_hist_buckets = arg_parse_uint(&arg);
994 else if (arg_match(&arg, &disable_warnings, argi))
995 global->disable_warnings = 1;
996 else if (arg_match(&arg, &disable_warning_prompt, argi))
997 global->disable_warning_prompt = 1;
1002 /* Validate global config */
1003 if (global->passes == 0) {
1004 #if CONFIG_VP9_ENCODER
1005 // Make default VP9 passes = 2 until there is a better quality 1-pass
1007 global->passes = (global->codec->iface == vpx_codec_vp9_cx ? 2 : 1);
1014 /* DWIM: Assume the user meant passes=2 if pass=2 is specified */
1015 if (global->pass > global->passes) {
1016 warn("Assuming --pass=%d implies --passes=%d\n",
1017 global->pass, global->pass);
1018 global->passes = global->pass;
1024 void open_input_file(struct VpxInputContext *input) {
1025 /* Parse certain options from the input file, if possible */
1026 input->file = strcmp(input->filename, "-")
1027 ? fopen(input->filename, "rb") : set_binary_mode(stdin);
1030 fatal("Failed to open input file");
1032 if (!fseeko(input->file, 0, SEEK_END)) {
1033 /* Input file is seekable. Figure out how long it is, so we can get
1036 input->length = ftello(input->file);
1037 rewind(input->file);
1040 /* For RAW input sources, these bytes will applied on the first frame
1043 input->detect.buf_read = fread(input->detect.buf, 1, 4, input->file);
1044 input->detect.position = 0;
1046 if (input->detect.buf_read == 4
1047 && file_is_y4m(input->file, &input->y4m, input->detect.buf)) {
1048 if (y4m_input_open(&input->y4m, input->file, input->detect.buf, 4,
1049 input->only_i420) >= 0) {
1050 input->file_type = FILE_TYPE_Y4M;
1051 input->width = input->y4m.pic_w;
1052 input->height = input->y4m.pic_h;
1053 input->framerate.numerator = input->y4m.fps_n;
1054 input->framerate.denominator = input->y4m.fps_d;
1055 input->use_i420 = 0;
1057 fatal("Unsupported Y4M stream.");
1058 } else if (input->detect.buf_read == 4 && file_is_ivf(input)) {
1059 fatal("IVF is not supported as input.");
1061 input->file_type = FILE_TYPE_RAW;
1066 static void close_input_file(struct VpxInputContext *input) {
1067 fclose(input->file);
1068 if (input->file_type == FILE_TYPE_Y4M)
1069 y4m_input_close(&input->y4m);
1072 static struct stream_state *new_stream(struct VpxEncoderConfig *global,
1073 struct stream_state *prev) {
1074 struct stream_state *stream;
1076 stream = calloc(1, sizeof(*stream));
1078 fatal("Failed to allocate new stream.");
1080 memcpy(stream, prev, sizeof(*stream));
1082 prev->next = stream;
1084 vpx_codec_err_t res;
1086 /* Populate encoder configuration */
1087 res = vpx_codec_enc_config_default(global->codec->iface(),
1088 &stream->config.cfg,
1091 fatal("Failed to get config: %s\n", vpx_codec_err_to_string(res));
1093 /* Change the default timebase to a high enough value so that the
1094 * encoder will always create strictly increasing timestamps.
1096 stream->config.cfg.g_timebase.den = 1000;
1098 /* Never use the library's default resolution, require it be parsed
1099 * from the file or set on the command line.
1101 stream->config.cfg.g_w = 0;
1102 stream->config.cfg.g_h = 0;
1104 /* Initialize remaining stream parameters */
1105 stream->config.stereo_fmt = STEREO_FORMAT_MONO;
1106 stream->config.write_webm = 1;
1107 stream->ebml.last_pts_ms = -1;
1109 /* Allows removal of the application version from the EBML tags */
1110 stream->ebml.debug = global->debug;
1113 /* Output files must be specified for each stream */
1114 stream->config.out_fn = NULL;
1116 stream->next = NULL;
1121 static int parse_stream_params(struct VpxEncoderConfig *global,
1122 struct stream_state *stream,
1124 char **argi, **argj;
1126 static const arg_def_t **ctrl_args = no_args;
1127 static const int *ctrl_args_map = NULL;
1128 struct stream_config *config = &stream->config;
1129 int eos_mark_found = 0;
1131 /* Handle codec specific options */
1133 #if CONFIG_VP8_ENCODER
1134 } else if (global->codec->iface == vpx_codec_vp8_cx) {
1135 ctrl_args = vp8_args;
1136 ctrl_args_map = vp8_arg_ctrl_map;
1138 #if CONFIG_VP9_ENCODER
1139 } else if (global->codec->iface == vpx_codec_vp9_cx) {
1140 ctrl_args = vp9_args;
1141 ctrl_args_map = vp9_arg_ctrl_map;
1145 for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step) {
1148 /* Once we've found an end-of-stream marker (--) we want to continue
1149 * shifting arguments but not consuming them.
1151 if (eos_mark_found) {
1154 } else if (!strcmp(*argj, "--")) {
1160 else if (arg_match(&arg, &outputfile, argi))
1161 config->out_fn = arg.val;
1162 else if (arg_match(&arg, &fpf_name, argi))
1163 config->stats_fn = arg.val;
1164 else if (arg_match(&arg, &use_ivf, argi))
1165 config->write_webm = 0;
1166 else if (arg_match(&arg, &threads, argi))
1167 config->cfg.g_threads = arg_parse_uint(&arg);
1168 else if (arg_match(&arg, &profile, argi))
1169 config->cfg.g_profile = arg_parse_uint(&arg);
1170 else if (arg_match(&arg, &width, argi))
1171 config->cfg.g_w = arg_parse_uint(&arg);
1172 else if (arg_match(&arg, &height, argi))
1173 config->cfg.g_h = arg_parse_uint(&arg);
1174 else if (arg_match(&arg, &stereo_mode, argi))
1175 config->stereo_fmt = arg_parse_enum_or_int(&arg);
1176 else if (arg_match(&arg, &timebase, argi)) {
1177 config->cfg.g_timebase = arg_parse_rational(&arg);
1178 validate_positive_rational(arg.name, &config->cfg.g_timebase);
1179 } else if (arg_match(&arg, &error_resilient, argi))
1180 config->cfg.g_error_resilient = arg_parse_uint(&arg);
1181 else if (arg_match(&arg, &lag_in_frames, argi))
1182 config->cfg.g_lag_in_frames = arg_parse_uint(&arg);
1183 else if (arg_match(&arg, &dropframe_thresh, argi))
1184 config->cfg.rc_dropframe_thresh = arg_parse_uint(&arg);
1185 else if (arg_match(&arg, &resize_allowed, argi))
1186 config->cfg.rc_resize_allowed = arg_parse_uint(&arg);
1187 else if (arg_match(&arg, &resize_up_thresh, argi))
1188 config->cfg.rc_resize_up_thresh = arg_parse_uint(&arg);
1189 else if (arg_match(&arg, &resize_down_thresh, argi))
1190 config->cfg.rc_resize_down_thresh = arg_parse_uint(&arg);
1191 else if (arg_match(&arg, &end_usage, argi))
1192 config->cfg.rc_end_usage = arg_parse_enum_or_int(&arg);
1193 else if (arg_match(&arg, &target_bitrate, argi))
1194 config->cfg.rc_target_bitrate = arg_parse_uint(&arg);
1195 else if (arg_match(&arg, &min_quantizer, argi))
1196 config->cfg.rc_min_quantizer = arg_parse_uint(&arg);
1197 else if (arg_match(&arg, &max_quantizer, argi))
1198 config->cfg.rc_max_quantizer = arg_parse_uint(&arg);
1199 else if (arg_match(&arg, &undershoot_pct, argi))
1200 config->cfg.rc_undershoot_pct = arg_parse_uint(&arg);
1201 else if (arg_match(&arg, &overshoot_pct, argi))
1202 config->cfg.rc_overshoot_pct = arg_parse_uint(&arg);
1203 else if (arg_match(&arg, &buf_sz, argi))
1204 config->cfg.rc_buf_sz = arg_parse_uint(&arg);
1205 else if (arg_match(&arg, &buf_initial_sz, argi))
1206 config->cfg.rc_buf_initial_sz = arg_parse_uint(&arg);
1207 else if (arg_match(&arg, &buf_optimal_sz, argi))
1208 config->cfg.rc_buf_optimal_sz = arg_parse_uint(&arg);
1209 else if (arg_match(&arg, &bias_pct, argi)) {
1210 config->cfg.rc_2pass_vbr_bias_pct = arg_parse_uint(&arg);
1212 if (global->passes < 2)
1213 warn("option %s ignored in one-pass mode.\n", arg.name);
1214 } else if (arg_match(&arg, &minsection_pct, argi)) {
1215 config->cfg.rc_2pass_vbr_minsection_pct = arg_parse_uint(&arg);
1217 if (global->passes < 2)
1218 warn("option %s ignored in one-pass mode.\n", arg.name);
1219 } else if (arg_match(&arg, &maxsection_pct, argi)) {
1220 config->cfg.rc_2pass_vbr_maxsection_pct = arg_parse_uint(&arg);
1222 if (global->passes < 2)
1223 warn("option %s ignored in one-pass mode.\n", arg.name);
1224 } else if (arg_match(&arg, &kf_min_dist, argi))
1225 config->cfg.kf_min_dist = arg_parse_uint(&arg);
1226 else if (arg_match(&arg, &kf_max_dist, argi)) {
1227 config->cfg.kf_max_dist = arg_parse_uint(&arg);
1228 config->have_kf_max_dist = 1;
1229 } else if (arg_match(&arg, &kf_disabled, argi))
1230 config->cfg.kf_mode = VPX_KF_DISABLED;
1234 for (i = 0; ctrl_args[i]; i++) {
1235 if (arg_match(&arg, ctrl_args[i], argi)) {
1239 /* Point either to the next free element or the first
1240 * instance of this control.
1242 for (j = 0; j < config->arg_ctrl_cnt; j++)
1243 if (config->arg_ctrls[j][0] == ctrl_args_map[i])
1247 assert(j < ARG_CTRL_CNT_MAX);
1248 if (j < ARG_CTRL_CNT_MAX) {
1249 config->arg_ctrls[j][0] = ctrl_args_map[i];
1250 config->arg_ctrls[j][1] = arg_parse_enum_or_int(&arg);
1251 if (j == config->arg_ctrl_cnt)
1252 config->arg_ctrl_cnt++;
1263 return eos_mark_found;
1267 #define FOREACH_STREAM(func) \
1269 struct stream_state *stream; \
1270 for (stream = streams; stream; stream = stream->next) { \
1276 static void validate_stream_config(struct stream_state *stream) {
1277 struct stream_state *streami;
1279 if (!stream->config.cfg.g_w || !stream->config.cfg.g_h)
1280 fatal("Stream %d: Specify stream dimensions with --width (-w) "
1281 " and --height (-h)", stream->index);
1283 for (streami = stream; streami; streami = streami->next) {
1284 /* All streams require output files */
1285 if (!streami->config.out_fn)
1286 fatal("Stream %d: Output file is required (specify with -o)",
1289 /* Check for two streams outputting to the same file */
1290 if (streami != stream) {
1291 const char *a = stream->config.out_fn;
1292 const char *b = streami->config.out_fn;
1293 if (!strcmp(a, b) && strcmp(a, "/dev/null") && strcmp(a, ":nul"))
1294 fatal("Stream %d: duplicate output file (from stream %d)",
1295 streami->index, stream->index);
1298 /* Check for two streams sharing a stats file. */
1299 if (streami != stream) {
1300 const char *a = stream->config.stats_fn;
1301 const char *b = streami->config.stats_fn;
1302 if (a && b && !strcmp(a, b))
1303 fatal("Stream %d: duplicate stats file (from stream %d)",
1304 streami->index, stream->index);
1310 static void set_stream_dimensions(struct stream_state *stream,
1313 if (!stream->config.cfg.g_w) {
1314 if (!stream->config.cfg.g_h)
1315 stream->config.cfg.g_w = w;
1317 stream->config.cfg.g_w = w * stream->config.cfg.g_h / h;
1319 if (!stream->config.cfg.g_h) {
1320 stream->config.cfg.g_h = h * stream->config.cfg.g_w / w;
1325 static void set_default_kf_interval(struct stream_state *stream,
1326 struct VpxEncoderConfig *global) {
1327 /* Use a max keyframe interval of 5 seconds, if none was
1328 * specified on the command line.
1330 if (!stream->config.have_kf_max_dist) {
1331 double framerate = (double)global->framerate.num / global->framerate.den;
1332 if (framerate > 0.0)
1333 stream->config.cfg.kf_max_dist = (unsigned int)(5.0 * framerate);
1338 static void show_stream_config(struct stream_state *stream,
1339 struct VpxEncoderConfig *global,
1340 struct VpxInputContext *input) {
1342 #define SHOW(field) \
1343 fprintf(stderr, " %-28s = %d\n", #field, stream->config.cfg.field)
1345 if (stream->index == 0) {
1346 fprintf(stderr, "Codec: %s\n",
1347 vpx_codec_iface_name(global->codec->iface()));
1348 fprintf(stderr, "Source file: %s Format: %s\n", input->filename,
1349 input->use_i420 ? "I420" : "YV12");
1351 if (stream->next || stream->index)
1352 fprintf(stderr, "\nStream Index: %d\n", stream->index);
1353 fprintf(stderr, "Destination file: %s\n", stream->config.out_fn);
1354 fprintf(stderr, "Encoder parameters:\n");
1361 SHOW(g_timebase.num);
1362 SHOW(g_timebase.den);
1363 SHOW(g_error_resilient);
1365 SHOW(g_lag_in_frames);
1366 SHOW(rc_dropframe_thresh);
1367 SHOW(rc_resize_allowed);
1368 SHOW(rc_resize_up_thresh);
1369 SHOW(rc_resize_down_thresh);
1371 SHOW(rc_target_bitrate);
1372 SHOW(rc_min_quantizer);
1373 SHOW(rc_max_quantizer);
1374 SHOW(rc_undershoot_pct);
1375 SHOW(rc_overshoot_pct);
1377 SHOW(rc_buf_initial_sz);
1378 SHOW(rc_buf_optimal_sz);
1379 SHOW(rc_2pass_vbr_bias_pct);
1380 SHOW(rc_2pass_vbr_minsection_pct);
1381 SHOW(rc_2pass_vbr_maxsection_pct);
1388 static void open_output_file(struct stream_state *stream,
1389 struct VpxEncoderConfig *global) {
1390 const char *fn = stream->config.out_fn;
1392 stream->file = strcmp(fn, "-") ? fopen(fn, "wb") : set_binary_mode(stdout);
1395 fatal("Failed to open output file");
1397 if (stream->config.write_webm && fseek(stream->file, 0, SEEK_CUR))
1398 fatal("WebM output to pipes not supported.");
1400 if (stream->config.write_webm) {
1401 stream->ebml.stream = stream->file;
1402 write_webm_file_header(&stream->ebml, &stream->config.cfg,
1404 stream->config.stereo_fmt,
1405 global->codec->fourcc);
1407 ivf_write_file_header(stream->file, &stream->config.cfg,
1408 global->codec->fourcc, 0);
1412 static void close_output_file(struct stream_state *stream,
1413 unsigned int fourcc) {
1414 if (stream->config.write_webm) {
1415 write_webm_file_footer(&stream->ebml, stream->hash);
1416 free(stream->ebml.cue_list);
1417 stream->ebml.cue_list = NULL;
1419 if (!fseek(stream->file, 0, SEEK_SET))
1420 ivf_write_file_header(stream->file, &stream->config.cfg,
1422 stream->frames_out);
1425 fclose(stream->file);
1429 static void setup_pass(struct stream_state *stream,
1430 struct VpxEncoderConfig *global,
1432 if (stream->config.stats_fn) {
1433 if (!stats_open_file(&stream->stats, stream->config.stats_fn,
1435 fatal("Failed to open statistics store");
1437 if (!stats_open_mem(&stream->stats, pass))
1438 fatal("Failed to open statistics store");
1441 stream->config.cfg.g_pass = global->passes == 2
1442 ? pass ? VPX_RC_LAST_PASS : VPX_RC_FIRST_PASS
1445 stream->config.cfg.rc_twopass_stats_in = stats_get(&stream->stats);
1447 stream->cx_time = 0;
1449 stream->frames_out = 0;
1453 static void initialize_encoder(struct stream_state *stream,
1454 struct VpxEncoderConfig *global) {
1458 flags |= global->show_psnr ? VPX_CODEC_USE_PSNR : 0;
1459 flags |= global->out_part ? VPX_CODEC_USE_OUTPUT_PARTITION : 0;
1461 /* Construct Encoder Context */
1462 vpx_codec_enc_init(&stream->encoder, global->codec->iface(),
1463 &stream->config.cfg, flags);
1464 ctx_exit_on_error(&stream->encoder, "Failed to initialize encoder");
1466 /* Note that we bypass the vpx_codec_control wrapper macro because
1467 * we're being clever to store the control IDs in an array. Real
1468 * applications will want to make use of the enumerations directly
1470 for (i = 0; i < stream->config.arg_ctrl_cnt; i++) {
1471 int ctrl = stream->config.arg_ctrls[i][0];
1472 int value = stream->config.arg_ctrls[i][1];
1473 if (vpx_codec_control_(&stream->encoder, ctrl, value))
1474 fprintf(stderr, "Error: Tried to set control %d = %d\n",
1477 ctx_exit_on_error(&stream->encoder, "Failed to control codec");
1481 if (global->test_decode != TEST_DECODE_OFF) {
1482 vpx_codec_dec_init(&stream->decoder, global->codec->dx_iface(), NULL, 0);
1488 static void encode_frame(struct stream_state *stream,
1489 struct VpxEncoderConfig *global,
1490 struct vpx_image *img,
1491 unsigned int frames_in) {
1492 vpx_codec_pts_t frame_start, next_frame_start;
1493 struct vpx_codec_enc_cfg *cfg = &stream->config.cfg;
1494 struct vpx_usec_timer timer;
1496 frame_start = (cfg->g_timebase.den * (int64_t)(frames_in - 1)
1497 * global->framerate.den)
1498 / cfg->g_timebase.num / global->framerate.num;
1499 next_frame_start = (cfg->g_timebase.den * (int64_t)(frames_in)
1500 * global->framerate.den)
1501 / cfg->g_timebase.num / global->framerate.num;
1503 /* Scale if necessary */
1504 if (img && (img->d_w != cfg->g_w || img->d_h != cfg->g_h)) {
1506 stream->img = vpx_img_alloc(NULL, VPX_IMG_FMT_I420,
1507 cfg->g_w, cfg->g_h, 16);
1508 I420Scale(img->planes[VPX_PLANE_Y], img->stride[VPX_PLANE_Y],
1509 img->planes[VPX_PLANE_U], img->stride[VPX_PLANE_U],
1510 img->planes[VPX_PLANE_V], img->stride[VPX_PLANE_V],
1512 stream->img->planes[VPX_PLANE_Y],
1513 stream->img->stride[VPX_PLANE_Y],
1514 stream->img->planes[VPX_PLANE_U],
1515 stream->img->stride[VPX_PLANE_U],
1516 stream->img->planes[VPX_PLANE_V],
1517 stream->img->stride[VPX_PLANE_V],
1518 stream->img->d_w, stream->img->d_h,
1524 vpx_usec_timer_start(&timer);
1525 vpx_codec_encode(&stream->encoder, img, frame_start,
1526 (unsigned long)(next_frame_start - frame_start),
1527 0, global->deadline);
1528 vpx_usec_timer_mark(&timer);
1529 stream->cx_time += vpx_usec_timer_elapsed(&timer);
1530 ctx_exit_on_error(&stream->encoder, "Stream %d: Failed to encode frame",
1535 static void update_quantizer_histogram(struct stream_state *stream) {
1536 if (stream->config.cfg.g_pass != VPX_RC_FIRST_PASS) {
1539 vpx_codec_control(&stream->encoder, VP8E_GET_LAST_QUANTIZER_64, &q);
1540 ctx_exit_on_error(&stream->encoder, "Failed to read quantizer");
1541 stream->counts[q]++;
1546 static void get_cx_data(struct stream_state *stream,
1547 struct VpxEncoderConfig *global,
1549 const vpx_codec_cx_pkt_t *pkt;
1550 const struct vpx_codec_enc_cfg *cfg = &stream->config.cfg;
1551 vpx_codec_iter_t iter = NULL;
1554 while ((pkt = vpx_codec_get_cx_data(&stream->encoder, &iter))) {
1555 static size_t fsize = 0;
1556 static off_t ivf_header_pos = 0;
1558 switch (pkt->kind) {
1559 case VPX_CODEC_CX_FRAME_PKT:
1560 if (!(pkt->data.frame.flags & VPX_FRAME_IS_FRAGMENT)) {
1561 stream->frames_out++;
1564 fprintf(stderr, " %6luF", (unsigned long)pkt->data.frame.sz);
1566 update_rate_histogram(&stream->rate_hist, cfg, pkt);
1567 if (stream->config.write_webm) {
1568 /* Update the hash */
1569 if (!stream->ebml.debug)
1570 stream->hash = murmur(pkt->data.frame.buf,
1571 (int)pkt->data.frame.sz,
1574 write_webm_block(&stream->ebml, cfg, pkt);
1576 if (pkt->data.frame.partition_id <= 0) {
1577 ivf_header_pos = ftello(stream->file);
1578 fsize = pkt->data.frame.sz;
1580 ivf_write_frame_header(stream->file, pkt);
1582 fsize += pkt->data.frame.sz;
1584 if (!(pkt->data.frame.flags & VPX_FRAME_IS_FRAGMENT)) {
1585 off_t currpos = ftello(stream->file);
1586 fseeko(stream->file, ivf_header_pos, SEEK_SET);
1587 ivf_write_frame_size(stream->file, fsize);
1588 fseeko(stream->file, currpos, SEEK_SET);
1592 (void) fwrite(pkt->data.frame.buf, 1, pkt->data.frame.sz,
1595 stream->nbytes += pkt->data.raw.sz;
1599 if (global->test_decode != TEST_DECODE_OFF && !stream->mismatch_seen) {
1600 vpx_codec_decode(&stream->decoder, pkt->data.frame.buf,
1601 pkt->data.frame.sz, NULL, 0);
1602 if (stream->decoder.err) {
1603 warn_or_exit_on_error(&stream->decoder,
1604 global->test_decode == TEST_DECODE_FATAL,
1605 "Failed to decode frame %d in stream %d",
1606 stream->frames_out + 1, stream->index);
1607 stream->mismatch_seen = stream->frames_out + 1;
1612 case VPX_CODEC_STATS_PKT:
1613 stream->frames_out++;
1614 stats_write(&stream->stats,
1615 pkt->data.twopass_stats.buf,
1616 pkt->data.twopass_stats.sz);
1617 stream->nbytes += pkt->data.raw.sz;
1619 case VPX_CODEC_PSNR_PKT:
1621 if (global->show_psnr) {
1624 stream->psnr_sse_total += pkt->data.psnr.sse[0];
1625 stream->psnr_samples_total += pkt->data.psnr.samples[0];
1626 for (i = 0; i < 4; i++) {
1628 fprintf(stderr, "%.3f ", pkt->data.psnr.psnr[i]);
1629 stream->psnr_totals[i] += pkt->data.psnr.psnr[i];
1631 stream->psnr_count++;
1642 static void show_psnr(struct stream_state *stream) {
1646 if (!stream->psnr_count)
1649 fprintf(stderr, "Stream %d PSNR (Overall/Avg/Y/U/V)", stream->index);
1650 ovpsnr = vp8_mse2psnr((double)stream->psnr_samples_total, 255.0,
1651 (double)stream->psnr_sse_total);
1652 fprintf(stderr, " %.3f", ovpsnr);
1654 for (i = 0; i < 4; i++) {
1655 fprintf(stderr, " %.3f", stream->psnr_totals[i] / stream->psnr_count);
1657 fprintf(stderr, "\n");
1661 static float usec_to_fps(uint64_t usec, unsigned int frames) {
1662 return (float)(usec > 0 ? frames * 1000000.0 / (float)usec : 0);
1666 static void test_decode(struct stream_state *stream,
1667 enum TestDecodeFatality fatal,
1668 const struct codec_item *codec) {
1669 vpx_image_t enc_img, dec_img;
1671 if (stream->mismatch_seen)
1674 /* Get the internal reference frame */
1675 if (codec->fourcc == VP8_FOURCC) {
1676 struct vpx_ref_frame ref_enc, ref_dec;
1679 width = (stream->config.cfg.g_w + 15) & ~15;
1680 height = (stream->config.cfg.g_h + 15) & ~15;
1681 vpx_img_alloc(&ref_enc.img, VPX_IMG_FMT_I420, width, height, 1);
1682 enc_img = ref_enc.img;
1683 vpx_img_alloc(&ref_dec.img, VPX_IMG_FMT_I420, width, height, 1);
1684 dec_img = ref_dec.img;
1686 ref_enc.frame_type = VP8_LAST_FRAME;
1687 ref_dec.frame_type = VP8_LAST_FRAME;
1688 vpx_codec_control(&stream->encoder, VP8_COPY_REFERENCE, &ref_enc);
1689 vpx_codec_control(&stream->decoder, VP8_COPY_REFERENCE, &ref_dec);
1691 struct vp9_ref_frame ref;
1694 vpx_codec_control(&stream->encoder, VP9_GET_REFERENCE, &ref);
1696 vpx_codec_control(&stream->decoder, VP9_GET_REFERENCE, &ref);
1699 ctx_exit_on_error(&stream->encoder, "Failed to get encoder reference frame");
1700 ctx_exit_on_error(&stream->decoder, "Failed to get decoder reference frame");
1702 if (!compare_img(&enc_img, &dec_img)) {
1703 int y[4], u[4], v[4];
1704 find_mismatch(&enc_img, &dec_img, y, u, v);
1705 stream->decoder.err = 1;
1706 warn_or_exit_on_error(&stream->decoder, fatal == TEST_DECODE_FATAL,
1707 "Stream %d: Encode/decode mismatch on frame %d at"
1708 " Y[%d, %d] {%d/%d},"
1709 " U[%d, %d] {%d/%d},"
1710 " V[%d, %d] {%d/%d}",
1711 stream->index, stream->frames_out,
1712 y[0], y[1], y[2], y[3],
1713 u[0], u[1], u[2], u[3],
1714 v[0], v[1], v[2], v[3]);
1715 stream->mismatch_seen = stream->frames_out;
1718 vpx_img_free(&enc_img);
1719 vpx_img_free(&dec_img);
1723 static void print_time(const char *label, int64_t etl) {
1724 int hours, mins, secs;
1728 etl -= hours * 3600;
1733 fprintf(stderr, "[%3s %2d:%02d:%02d] ",
1734 label, hours, mins, secs);
1736 fprintf(stderr, "[%3s unknown] ", label);
1741 int main(int argc, const char **argv_) {
1744 int frame_avail, got_data;
1746 struct VpxInputContext input = {0};
1747 struct VpxEncoderConfig global;
1748 struct stream_state *streams = NULL;
1749 char **argv, **argi;
1750 uint64_t cx_time = 0;
1754 exec_name = argv_[0];
1759 /* Setup default input stream settings */
1760 input.framerate.numerator = 30;
1761 input.framerate.denominator = 1;
1763 input.only_i420 = 1;
1765 /* First parse the global configuration values, because we want to apply
1766 * other parameters on top of the default configuration provided by the
1769 argv = argv_dup(argc - 1, argv_ + 1);
1770 parse_global_config(&global, argv);
1774 /* Now parse each stream's parameters. Using a local scope here
1775 * due to the use of 'stream' as loop variable in FOREACH_STREAM
1778 struct stream_state *stream = NULL;
1781 stream = new_stream(&global, stream);
1785 } while (parse_stream_params(&global, stream, argv));
1788 /* Check for unrecognized options */
1789 for (argi = argv; *argi; argi++)
1790 if (argi[0][0] == '-' && argi[0][1])
1791 die("Error: Unrecognized option %s\n", *argi);
1793 FOREACH_STREAM(check_encoder_config(global.disable_warning_prompt,
1794 &global, &stream->config.cfg););
1796 /* Handle non-option arguments */
1797 input.filename = argv[0];
1799 if (!input.filename)
1803 /* Decide if other chroma subsamplings than 4:2:0 are supported */
1804 if (global.codec->fourcc == VP9_FOURCC)
1805 input.only_i420 = 0;
1808 for (pass = global.pass ? global.pass - 1 : 0; pass < global.passes; pass++) {
1809 int frames_in = 0, seen_frames = 0;
1810 int64_t estimated_time_left = -1;
1811 int64_t average_rate = -1;
1812 off_t lagged_count = 0;
1814 open_input_file(&input);
1816 /* If the input file doesn't specify its w/h (raw files), try to get
1817 * the data from the first stream's configuration.
1819 if (!input.width || !input.height)
1821 if (stream->config.cfg.g_w && stream->config.cfg.g_h) {
1822 input.width = stream->config.cfg.g_w;
1823 input.height = stream->config.cfg.g_h;
1828 /* Update stream configurations from the input file's parameters */
1829 if (!input.width || !input.height)
1830 fatal("Specify stream dimensions with --width (-w) "
1831 " and --height (-h)");
1832 FOREACH_STREAM(set_stream_dimensions(stream, input.width, input.height));
1833 FOREACH_STREAM(validate_stream_config(stream));
1835 /* Ensure that --passes and --pass are consistent. If --pass is set and
1836 * --passes=2, ensure --fpf was set.
1838 if (global.pass && global.passes == 2)
1840 if (!stream->config.stats_fn)
1841 die("Stream %d: Must specify --fpf when --pass=%d"
1842 " and --passes=2\n", stream->index, global.pass);
1845 /* Use the frame rate from the file only if none was specified
1846 * on the command-line.
1848 if (!global.have_framerate) {
1849 global.framerate.num = input.framerate.numerator;
1850 global.framerate.den = input.framerate.denominator;
1853 FOREACH_STREAM(set_default_kf_interval(stream, &global));
1855 /* Show configuration */
1856 if (global.verbose && pass == 0)
1857 FOREACH_STREAM(show_stream_config(stream, &global, &input));
1859 if (pass == (global.pass ? global.pass - 1 : 0)) {
1860 if (input.file_type == FILE_TYPE_Y4M)
1861 /*The Y4M reader does its own allocation.
1862 Just initialize this here to avoid problems if we never read any
1864 memset(&raw, 0, sizeof(raw));
1867 input.use_i420 ? VPX_IMG_FMT_I420
1869 input.width, input.height, 32);
1871 FOREACH_STREAM(init_rate_histogram(&stream->rate_hist,
1872 &stream->config.cfg,
1873 &global.framerate));
1876 FOREACH_STREAM(setup_pass(stream, &global, pass));
1877 FOREACH_STREAM(open_output_file(stream, &global));
1878 FOREACH_STREAM(initialize_encoder(stream, &global));
1883 while (frame_avail || got_data) {
1884 struct vpx_usec_timer timer;
1886 if (!global.limit || frames_in < global.limit) {
1887 frame_avail = read_frame(&input, &raw);
1891 seen_frames = frames_in > global.skip_frames ?
1892 frames_in - global.skip_frames : 0;
1894 if (!global.quiet) {
1895 float fps = usec_to_fps(cx_time, seen_frames);
1896 fprintf(stderr, "\rPass %d/%d ", pass + 1, global.passes);
1898 if (stream_cnt == 1)
1900 "frame %4d/%-4d %7"PRId64"B ",
1901 frames_in, streams->frames_out, (int64_t)streams->nbytes);
1903 fprintf(stderr, "frame %4d ", frames_in);
1905 fprintf(stderr, "%7"PRId64" %s %.2f %s ",
1906 cx_time > 9999999 ? cx_time / 1000 : cx_time,
1907 cx_time > 9999999 ? "ms" : "us",
1908 fps >= 1.0 ? fps : fps * 60,
1909 fps >= 1.0 ? "fps" : "fpm");
1910 print_time("ETA", estimated_time_left);
1911 fprintf(stderr, "\033[K");
1917 if (frames_in > global.skip_frames) {
1918 vpx_usec_timer_start(&timer);
1919 FOREACH_STREAM(encode_frame(stream, &global,
1920 frame_avail ? &raw : NULL,
1922 vpx_usec_timer_mark(&timer);
1923 cx_time += vpx_usec_timer_elapsed(&timer);
1925 FOREACH_STREAM(update_quantizer_histogram(stream));
1928 FOREACH_STREAM(get_cx_data(stream, &global, &got_data));
1930 if (!got_data && input.length && !streams->frames_out) {
1931 lagged_count = global.limit ? seen_frames : ftello(input.file);
1932 } else if (input.length) {
1937 int frame_in_lagged = (seen_frames - lagged_count) * 1000;
1939 rate = cx_time ? frame_in_lagged * (int64_t)1000000 / cx_time : 0;
1940 remaining = 1000 * (global.limit - global.skip_frames
1941 - seen_frames + lagged_count);
1943 off_t input_pos = ftello(input.file);
1944 off_t input_pos_lagged = input_pos - lagged_count;
1945 int64_t limit = input.length;
1947 rate = cx_time ? input_pos_lagged * (int64_t)1000000 / cx_time : 0;
1948 remaining = limit - input_pos + lagged_count;
1951 average_rate = (average_rate <= 0)
1953 : (average_rate * 7 + rate) / 8;
1954 estimated_time_left = average_rate ? remaining / average_rate : -1;
1957 if (got_data && global.test_decode != TEST_DECODE_OFF)
1958 FOREACH_STREAM(test_decode(stream, global.test_decode, global.codec));
1965 fprintf(stderr, "\n");
1968 FOREACH_STREAM(fprintf(
1970 "\rPass %d/%d frame %4d/%-4d %7"PRId64"B %7lub/f %7"PRId64"b/s"
1971 " %7"PRId64" %s (%.2f fps)\033[K\n", pass + 1,
1972 global.passes, frames_in, stream->frames_out, (int64_t)stream->nbytes,
1973 seen_frames ? (unsigned long)(stream->nbytes * 8 / seen_frames) : 0,
1974 seen_frames ? (int64_t)stream->nbytes * 8
1975 * (int64_t)global.framerate.num / global.framerate.den
1978 stream->cx_time > 9999999 ? stream->cx_time / 1000 : stream->cx_time,
1979 stream->cx_time > 9999999 ? "ms" : "us",
1980 usec_to_fps(stream->cx_time, seen_frames));
1983 if (global.show_psnr)
1984 FOREACH_STREAM(show_psnr(stream));
1986 FOREACH_STREAM(vpx_codec_destroy(&stream->encoder));
1988 if (global.test_decode != TEST_DECODE_OFF) {
1989 FOREACH_STREAM(vpx_codec_destroy(&stream->decoder));
1992 close_input_file(&input);
1994 if (global.test_decode == TEST_DECODE_FATAL) {
1995 FOREACH_STREAM(res |= stream->mismatch_seen);
1997 FOREACH_STREAM(close_output_file(stream, global.codec->fourcc));
1999 FOREACH_STREAM(stats_close(&stream->stats, global.passes - 1));
2005 if (global.show_q_hist_buckets)
2006 FOREACH_STREAM(show_q_histogram(stream->counts,
2007 global.show_q_hist_buckets));
2009 if (global.show_rate_hist_buckets)
2010 FOREACH_STREAM(show_rate_histogram(&stream->rate_hist,
2011 &stream->config.cfg,
2012 global.show_rate_hist_buckets));
2013 FOREACH_STREAM(destroy_rate_histogram(&stream->rate_hist));
2015 #if CONFIG_INTERNAL_STATS
2016 /* TODO(jkoleszar): This doesn't belong in this executable. Do it for now,
2017 * to match some existing utilities.
2019 if (!(global.pass == 1 && global.passes == 2))
2021 FILE *f = fopen("opsnr.stt", "a");
2022 if (stream->mismatch_seen) {
2023 fprintf(f, "First mismatch occurred in frame %d\n",
2024 stream->mismatch_seen);
2026 fprintf(f, "No mismatch detected in recon buffers\n");
2035 return res ? EXIT_FAILURE : EXIT_SUCCESS;