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 "./webmenc.h"
44 #include "./y4minput.h"
46 /* Swallow warnings about unused results of fread/fwrite */
47 static size_t wrap_fread(void *ptr, size_t size, size_t nmemb,
49 return fread(ptr, size, nmemb, stream);
51 #define fread wrap_fread
53 static size_t wrap_fwrite(const void *ptr, size_t size, size_t nmemb,
55 return fwrite(ptr, size, nmemb, stream);
57 #define fwrite wrap_fwrite
60 static const char *exec_name;
62 static const struct codec_item {
64 const vpx_codec_iface_t *(*iface)(void);
65 const vpx_codec_iface_t *(*dx_iface)(void);
68 #if CONFIG_VP8_ENCODER && CONFIG_VP8_DECODER
69 {"vp8", &vpx_codec_vp8_cx, &vpx_codec_vp8_dx, VP8_FOURCC},
70 #elif CONFIG_VP8_ENCODER && !CONFIG_VP8_DECODER
71 {"vp8", &vpx_codec_vp8_cx, NULL, VP8_FOURCC},
73 #if CONFIG_VP9_ENCODER && CONFIG_VP9_DECODER
74 {"vp9", &vpx_codec_vp9_cx, &vpx_codec_vp9_dx, VP9_FOURCC},
75 #elif CONFIG_VP9_ENCODER && !CONFIG_VP9_DECODER
76 {"vp9", &vpx_codec_vp9_cx, NULL, VP9_FOURCC},
80 static void warn_or_exit_on_errorv(vpx_codec_ctx_t *ctx, int fatal,
81 const char *s, va_list ap) {
83 const char *detail = vpx_codec_error_detail(ctx);
85 vfprintf(stderr, s, ap);
86 fprintf(stderr, ": %s\n", vpx_codec_error(ctx));
89 fprintf(stderr, " %s\n", detail);
96 static void ctx_exit_on_error(vpx_codec_ctx_t *ctx, const char *s, ...) {
100 warn_or_exit_on_errorv(ctx, 1, s, ap);
104 static void warn_or_exit_on_error(vpx_codec_ctx_t *ctx, int fatal,
105 const char *s, ...) {
109 warn_or_exit_on_errorv(ctx, fatal, s, ap);
113 int read_frame(struct VpxInputContext *input_ctx, vpx_image_t *img) {
114 FILE *f = input_ctx->file;
115 y4m_input *y4m = &input_ctx->y4m;
118 if (input_ctx->file_type == FILE_TYPE_Y4M) {
119 if (y4m_input_fetch_frame(y4m, f, img) < 1)
122 shortread = read_yuv_frame(input_ctx, img);
128 int file_is_y4m(FILE *infile, y4m_input *y4m, const char detect[4]) {
129 if (memcmp(detect, "YUV4", 4) == 0) {
136 /* Murmur hash derived from public domain reference implementation at
137 * http:// sites.google.com/site/murmurhash/
139 static unsigned int murmur(const void *key, int len, unsigned int seed) {
140 const unsigned int m = 0x5bd1e995;
143 unsigned int h = seed ^ len;
145 const unsigned char *data = (const unsigned char *)key;
150 k = (unsigned int)data[0];
151 k |= (unsigned int)data[1] << 8;
152 k |= (unsigned int)data[2] << 16;
153 k |= (unsigned int)data[3] << 24;
184 static const arg_def_t debugmode = ARG_DEF("D", "debug", 0,
185 "Debug mode (makes output deterministic)");
186 static const arg_def_t outputfile = ARG_DEF("o", "output", 1,
188 static const arg_def_t use_yv12 = ARG_DEF(NULL, "yv12", 0,
189 "Input file is YV12 ");
190 static const arg_def_t use_i420 = ARG_DEF(NULL, "i420", 0,
191 "Input file is I420 (default)");
192 static const arg_def_t codecarg = ARG_DEF(NULL, "codec", 1,
194 static const arg_def_t passes = ARG_DEF("p", "passes", 1,
195 "Number of passes (1/2)");
196 static const arg_def_t pass_arg = ARG_DEF(NULL, "pass", 1,
197 "Pass to execute (1/2)");
198 static const arg_def_t fpf_name = ARG_DEF(NULL, "fpf", 1,
199 "First pass statistics file name");
200 static const arg_def_t limit = ARG_DEF(NULL, "limit", 1,
201 "Stop encoding after n input frames");
202 static const arg_def_t skip = ARG_DEF(NULL, "skip", 1,
203 "Skip the first n input frames");
204 static const arg_def_t deadline = ARG_DEF("d", "deadline", 1,
205 "Deadline per frame (usec)");
206 static const arg_def_t best_dl = ARG_DEF(NULL, "best", 0,
207 "Use Best Quality Deadline");
208 static const arg_def_t good_dl = ARG_DEF(NULL, "good", 0,
209 "Use Good Quality Deadline");
210 static const arg_def_t rt_dl = ARG_DEF(NULL, "rt", 0,
211 "Use Realtime Quality Deadline");
212 static const arg_def_t quietarg = ARG_DEF("q", "quiet", 0,
213 "Do not print encode progress");
214 static const arg_def_t verbosearg = ARG_DEF("v", "verbose", 0,
215 "Show encoder parameters");
216 static const arg_def_t psnrarg = ARG_DEF(NULL, "psnr", 0,
217 "Show PSNR in status line");
219 static const struct arg_enum_list test_decode_enum[] = {
220 {"off", TEST_DECODE_OFF},
221 {"fatal", TEST_DECODE_FATAL},
222 {"warn", TEST_DECODE_WARN},
225 static const arg_def_t recontest = ARG_DEF_ENUM(NULL, "test-decode", 1,
226 "Test encode/decode mismatch",
228 static const arg_def_t framerate = ARG_DEF(NULL, "fps", 1,
229 "Stream frame rate (rate/scale)");
230 static const arg_def_t use_ivf = ARG_DEF(NULL, "ivf", 0,
231 "Output IVF (default is WebM)");
232 static const arg_def_t out_part = ARG_DEF("P", "output-partitions", 0,
233 "Makes encoder output partitions. Requires IVF output!");
234 static const arg_def_t q_hist_n = ARG_DEF(NULL, "q-hist", 1,
235 "Show quantizer histogram (n-buckets)");
236 static const arg_def_t rate_hist_n = ARG_DEF(NULL, "rate-hist", 1,
237 "Show rate histogram (n-buckets)");
238 static const arg_def_t disable_warnings =
239 ARG_DEF(NULL, "disable-warnings", 0,
240 "Disable warnings about potentially incorrect encode settings.");
242 static const arg_def_t *main_args[] = {
244 &outputfile, &codecarg, &passes, &pass_arg, &fpf_name, &limit, &skip,
245 &deadline, &best_dl, &good_dl, &rt_dl,
246 &quietarg, &verbosearg, &psnrarg, &use_ivf, &out_part, &q_hist_n,
247 &rate_hist_n, &disable_warnings,
251 static const arg_def_t usage = ARG_DEF("u", "usage", 1,
252 "Usage profile number to use");
253 static const arg_def_t threads = ARG_DEF("t", "threads", 1,
254 "Max number of threads to use");
255 static const arg_def_t profile = ARG_DEF(NULL, "profile", 1,
256 "Bitstream profile number to use");
257 static const arg_def_t width = ARG_DEF("w", "width", 1,
259 static const arg_def_t height = ARG_DEF("h", "height", 1,
261 static const struct arg_enum_list stereo_mode_enum[] = {
262 {"mono", STEREO_FORMAT_MONO},
263 {"left-right", STEREO_FORMAT_LEFT_RIGHT},
264 {"bottom-top", STEREO_FORMAT_BOTTOM_TOP},
265 {"top-bottom", STEREO_FORMAT_TOP_BOTTOM},
266 {"right-left", STEREO_FORMAT_RIGHT_LEFT},
269 static const arg_def_t stereo_mode = ARG_DEF_ENUM(NULL, "stereo-mode", 1,
270 "Stereo 3D video format", stereo_mode_enum);
271 static const arg_def_t timebase = ARG_DEF(NULL, "timebase", 1,
272 "Output timestamp precision (fractional seconds)");
273 static const arg_def_t error_resilient = ARG_DEF(NULL, "error-resilient", 1,
274 "Enable error resiliency features");
275 static const arg_def_t lag_in_frames = ARG_DEF(NULL, "lag-in-frames", 1,
276 "Max number of frames to lag");
278 static const arg_def_t *global_args[] = {
279 &use_yv12, &use_i420, &usage, &threads, &profile,
280 &width, &height, &stereo_mode, &timebase, &framerate,
285 static const arg_def_t dropframe_thresh = ARG_DEF(NULL, "drop-frame", 1,
286 "Temporal resampling threshold (buf %)");
287 static const arg_def_t resize_allowed = ARG_DEF(NULL, "resize-allowed", 1,
288 "Spatial resampling enabled (bool)");
289 static const arg_def_t resize_up_thresh = ARG_DEF(NULL, "resize-up", 1,
290 "Upscale threshold (buf %)");
291 static const arg_def_t resize_down_thresh = ARG_DEF(NULL, "resize-down", 1,
292 "Downscale threshold (buf %)");
293 static const struct arg_enum_list end_usage_enum[] = {
300 static const arg_def_t end_usage = ARG_DEF_ENUM(NULL, "end-usage", 1,
301 "Rate control mode", end_usage_enum);
302 static const arg_def_t target_bitrate = ARG_DEF(NULL, "target-bitrate", 1,
304 static const arg_def_t min_quantizer = ARG_DEF(NULL, "min-q", 1,
305 "Minimum (best) quantizer");
306 static const arg_def_t max_quantizer = ARG_DEF(NULL, "max-q", 1,
307 "Maximum (worst) quantizer");
308 static const arg_def_t undershoot_pct = ARG_DEF(NULL, "undershoot-pct", 1,
309 "Datarate undershoot (min) target (%)");
310 static const arg_def_t overshoot_pct = ARG_DEF(NULL, "overshoot-pct", 1,
311 "Datarate overshoot (max) target (%)");
312 static const arg_def_t buf_sz = ARG_DEF(NULL, "buf-sz", 1,
313 "Client buffer size (ms)");
314 static const arg_def_t buf_initial_sz = ARG_DEF(NULL, "buf-initial-sz", 1,
315 "Client initial buffer size (ms)");
316 static const arg_def_t buf_optimal_sz = ARG_DEF(NULL, "buf-optimal-sz", 1,
317 "Client optimal buffer size (ms)");
318 static const arg_def_t *rc_args[] = {
319 &dropframe_thresh, &resize_allowed, &resize_up_thresh, &resize_down_thresh,
320 &end_usage, &target_bitrate, &min_quantizer, &max_quantizer,
321 &undershoot_pct, &overshoot_pct, &buf_sz, &buf_initial_sz, &buf_optimal_sz,
326 static const arg_def_t bias_pct = ARG_DEF(NULL, "bias-pct", 1,
327 "CBR/VBR bias (0=CBR, 100=VBR)");
328 static const arg_def_t minsection_pct = ARG_DEF(NULL, "minsection-pct", 1,
329 "GOP min bitrate (% of target)");
330 static const arg_def_t maxsection_pct = ARG_DEF(NULL, "maxsection-pct", 1,
331 "GOP max bitrate (% of target)");
332 static const arg_def_t *rc_twopass_args[] = {
333 &bias_pct, &minsection_pct, &maxsection_pct, NULL
337 static const arg_def_t kf_min_dist = ARG_DEF(NULL, "kf-min-dist", 1,
338 "Minimum keyframe interval (frames)");
339 static const arg_def_t kf_max_dist = ARG_DEF(NULL, "kf-max-dist", 1,
340 "Maximum keyframe interval (frames)");
341 static const arg_def_t kf_disabled = ARG_DEF(NULL, "disable-kf", 0,
342 "Disable keyframe placement");
343 static const arg_def_t *kf_args[] = {
344 &kf_min_dist, &kf_max_dist, &kf_disabled, NULL
348 static const arg_def_t noise_sens = ARG_DEF(NULL, "noise-sensitivity", 1,
349 "Noise sensitivity (frames to blur)");
350 static const arg_def_t sharpness = ARG_DEF(NULL, "sharpness", 1,
351 "Filter sharpness (0-7)");
352 static const arg_def_t static_thresh = ARG_DEF(NULL, "static-thresh", 1,
353 "Motion detection threshold");
354 static const arg_def_t cpu_used = ARG_DEF(NULL, "cpu-used", 1,
355 "CPU Used (-16..16)");
356 static const arg_def_t token_parts = ARG_DEF(NULL, "token-parts", 1,
357 "Number of token partitions to use, log2");
358 static const arg_def_t tile_cols = ARG_DEF(NULL, "tile-columns", 1,
359 "Number of tile columns to use, log2");
360 static const arg_def_t tile_rows = ARG_DEF(NULL, "tile-rows", 1,
361 "Number of tile rows to use, log2");
362 static const arg_def_t auto_altref = ARG_DEF(NULL, "auto-alt-ref", 1,
363 "Enable automatic alt reference frames");
364 static const arg_def_t arnr_maxframes = ARG_DEF(NULL, "arnr-maxframes", 1,
365 "AltRef Max Frames");
366 static const arg_def_t arnr_strength = ARG_DEF(NULL, "arnr-strength", 1,
368 static const arg_def_t arnr_type = ARG_DEF(NULL, "arnr-type", 1,
370 static const struct arg_enum_list tuning_enum[] = {
371 {"psnr", VP8_TUNE_PSNR},
372 {"ssim", VP8_TUNE_SSIM},
375 static const arg_def_t tune_ssim = ARG_DEF_ENUM(NULL, "tune", 1,
376 "Material to favor", tuning_enum);
377 static const arg_def_t cq_level = ARG_DEF(NULL, "cq-level", 1,
378 "Constant/Constrained Quality level");
379 static const arg_def_t max_intra_rate_pct = ARG_DEF(NULL, "max-intra-rate", 1,
380 "Max I-frame bitrate (pct)");
381 static const arg_def_t lossless = ARG_DEF(NULL, "lossless", 1, "Lossless mode");
382 #if CONFIG_VP9_ENCODER
383 static const arg_def_t frame_parallel_decoding = ARG_DEF(
384 NULL, "frame-parallel", 1, "Enable frame parallel decodability features");
385 static const arg_def_t aq_mode = ARG_DEF(
387 "Adaptive quantization mode (0: disabled (by default), 1: variance based)");
390 #if CONFIG_VP8_ENCODER
391 static const arg_def_t *vp8_args[] = {
392 &cpu_used, &auto_altref, &noise_sens, &sharpness, &static_thresh,
393 &token_parts, &arnr_maxframes, &arnr_strength, &arnr_type,
394 &tune_ssim, &cq_level, &max_intra_rate_pct,
397 static const int vp8_arg_ctrl_map[] = {
398 VP8E_SET_CPUUSED, VP8E_SET_ENABLEAUTOALTREF,
399 VP8E_SET_NOISE_SENSITIVITY, VP8E_SET_SHARPNESS, VP8E_SET_STATIC_THRESHOLD,
400 VP8E_SET_TOKEN_PARTITIONS,
401 VP8E_SET_ARNR_MAXFRAMES, VP8E_SET_ARNR_STRENGTH, VP8E_SET_ARNR_TYPE,
402 VP8E_SET_TUNING, VP8E_SET_CQ_LEVEL, VP8E_SET_MAX_INTRA_BITRATE_PCT,
407 #if CONFIG_VP9_ENCODER
408 static const arg_def_t *vp9_args[] = {
409 &cpu_used, &auto_altref, &noise_sens, &sharpness, &static_thresh,
410 &tile_cols, &tile_rows, &arnr_maxframes, &arnr_strength, &arnr_type,
411 &tune_ssim, &cq_level, &max_intra_rate_pct, &lossless,
412 &frame_parallel_decoding, &aq_mode,
415 static const int vp9_arg_ctrl_map[] = {
416 VP8E_SET_CPUUSED, VP8E_SET_ENABLEAUTOALTREF,
417 VP8E_SET_NOISE_SENSITIVITY, VP8E_SET_SHARPNESS, VP8E_SET_STATIC_THRESHOLD,
418 VP9E_SET_TILE_COLUMNS, VP9E_SET_TILE_ROWS,
419 VP8E_SET_ARNR_MAXFRAMES, VP8E_SET_ARNR_STRENGTH, VP8E_SET_ARNR_TYPE,
420 VP8E_SET_TUNING, VP8E_SET_CQ_LEVEL, VP8E_SET_MAX_INTRA_BITRATE_PCT,
421 VP9E_SET_LOSSLESS, VP9E_SET_FRAME_PARALLEL_DECODING, VP9E_SET_AQ_MODE,
426 static const arg_def_t *no_args[] = { NULL };
431 fprintf(stderr, "Usage: %s <options> -o dst_filename src_filename \n",
434 fprintf(stderr, "\nOptions:\n");
435 arg_show_usage(stderr, main_args);
436 fprintf(stderr, "\nEncoder Global Options:\n");
437 arg_show_usage(stderr, global_args);
438 fprintf(stderr, "\nRate Control Options:\n");
439 arg_show_usage(stderr, rc_args);
440 fprintf(stderr, "\nTwopass Rate Control Options:\n");
441 arg_show_usage(stderr, rc_twopass_args);
442 fprintf(stderr, "\nKeyframe Placement Options:\n");
443 arg_show_usage(stderr, kf_args);
444 #if CONFIG_VP8_ENCODER
445 fprintf(stderr, "\nVP8 Specific Options:\n");
446 arg_show_usage(stderr, vp8_args);
448 #if CONFIG_VP9_ENCODER
449 fprintf(stderr, "\nVP9 Specific Options:\n");
450 arg_show_usage(stderr, vp9_args);
452 fprintf(stderr, "\nStream timebase (--timebase):\n"
453 " The desired precision of timestamps in the output, expressed\n"
454 " in fractional seconds. Default is 1/1000.\n");
456 "Included encoders:\n"
459 for (i = 0; i < sizeof(codecs) / sizeof(codecs[0]); i++)
460 fprintf(stderr, " %-6s - %s\n",
462 vpx_codec_iface_name(codecs[i].iface()));
468 #define HIST_BAR_MAX 40
470 int low, high, count;
474 static int merge_hist_buckets(struct hist_bucket *bucket,
477 int small_bucket = 0, merge_bucket = INT_MAX, big_bucket = 0;
478 int buckets = *buckets_;
481 /* Find the extrema for this list of buckets */
482 big_bucket = small_bucket = 0;
483 for (i = 0; i < buckets; i++) {
484 if (bucket[i].count < bucket[small_bucket].count)
486 if (bucket[i].count > bucket[big_bucket].count)
490 /* If we have too many buckets, merge the smallest with an adjacent
493 while (buckets > max_buckets) {
494 int last_bucket = buckets - 1;
496 /* merge the small bucket with an adjacent one. */
497 if (small_bucket == 0)
499 else if (small_bucket == last_bucket)
500 merge_bucket = last_bucket - 1;
501 else if (bucket[small_bucket - 1].count < bucket[small_bucket + 1].count)
502 merge_bucket = small_bucket - 1;
504 merge_bucket = small_bucket + 1;
506 assert(abs(merge_bucket - small_bucket) <= 1);
507 assert(small_bucket < buckets);
508 assert(big_bucket < buckets);
509 assert(merge_bucket < buckets);
511 if (merge_bucket < small_bucket) {
512 bucket[merge_bucket].high = bucket[small_bucket].high;
513 bucket[merge_bucket].count += bucket[small_bucket].count;
515 bucket[small_bucket].high = bucket[merge_bucket].high;
516 bucket[small_bucket].count += bucket[merge_bucket].count;
517 merge_bucket = small_bucket;
520 assert(bucket[merge_bucket].low != bucket[merge_bucket].high);
524 /* Remove the merge_bucket from the list, and find the new small
525 * and big buckets while we're at it
527 big_bucket = small_bucket = 0;
528 for (i = 0; i < buckets; i++) {
529 if (i > merge_bucket)
530 bucket[i] = bucket[i + 1];
532 if (bucket[i].count < bucket[small_bucket].count)
534 if (bucket[i].count > bucket[big_bucket].count)
541 return bucket[big_bucket].count;
545 static void show_histogram(const struct hist_bucket *bucket,
549 const char *pat1, *pat2;
552 switch ((int)(log(bucket[buckets - 1].high) / log(10)) + 1) {
579 pat1 = "%12d %10s: ";
580 pat2 = "%12d-%10d: ";
584 for (i = 0; i < buckets; i++) {
589 pct = (float)(100.0 * bucket[i].count / total);
590 len = HIST_BAR_MAX * bucket[i].count / scale;
593 assert(len <= HIST_BAR_MAX);
595 if (bucket[i].low == bucket[i].high)
596 fprintf(stderr, pat1, bucket[i].low, "");
598 fprintf(stderr, pat2, bucket[i].low, bucket[i].high);
600 for (j = 0; j < HIST_BAR_MAX; j++)
601 fprintf(stderr, j < len ? "=" : " ");
602 fprintf(stderr, "\t%5d (%6.2f%%)\n", bucket[i].count, pct);
607 static void show_q_histogram(const int counts[64], int max_buckets) {
608 struct hist_bucket bucket[64];
615 for (i = 0; i < 64; i++) {
617 bucket[buckets].low = bucket[buckets].high = i;
618 bucket[buckets].count = counts[i];
624 fprintf(stderr, "\nQuantizer Selection:\n");
625 scale = merge_hist_buckets(bucket, &buckets, max_buckets);
626 show_histogram(bucket, buckets, total, scale);
630 #define RATE_BINS (100)
636 struct hist_bucket bucket[RATE_BINS];
641 static void init_rate_histogram(struct rate_hist *hist,
642 const vpx_codec_enc_cfg_t *cfg,
643 const vpx_rational_t *fps) {
646 /* Determine the number of samples in the buffer. Use the file's framerate
647 * to determine the number of frames in rc_buf_sz milliseconds, with an
648 * adjustment (5/4) to account for alt-refs
650 hist->samples = cfg->rc_buf_sz * 5 / 4 * fps->num / fps->den / 1000;
652 /* prevent division by zero */
653 if (hist->samples == 0)
656 hist->pts = calloc(hist->samples, sizeof(*hist->pts));
657 hist->sz = calloc(hist->samples, sizeof(*hist->sz));
658 for (i = 0; i < RATE_BINS; i++) {
659 hist->bucket[i].low = INT_MAX;
660 hist->bucket[i].high = 0;
661 hist->bucket[i].count = 0;
666 static void destroy_rate_histogram(struct rate_hist *hist) {
672 static void update_rate_histogram(struct rate_hist *hist,
673 const vpx_codec_enc_cfg_t *cfg,
674 const vpx_codec_cx_pkt_t *pkt) {
676 int64_t now, then, sum_sz = 0, avg_bitrate;
678 now = pkt->data.frame.pts * 1000
679 * (uint64_t)cfg->g_timebase.num / (uint64_t)cfg->g_timebase.den;
681 idx = hist->frames++ % hist->samples;
682 hist->pts[idx] = now;
683 hist->sz[idx] = (int)pkt->data.frame.sz;
685 if (now < cfg->rc_buf_initial_sz)
690 /* Sum the size over the past rc_buf_sz ms */
691 for (i = hist->frames; i > 0 && hist->frames - i < hist->samples; i--) {
692 int i_idx = (i - 1) % hist->samples;
694 then = hist->pts[i_idx];
695 if (now - then > cfg->rc_buf_sz)
697 sum_sz += hist->sz[i_idx];
703 avg_bitrate = sum_sz * 8 * 1000 / (now - then);
704 idx = (int)(avg_bitrate * (RATE_BINS / 2) / (cfg->rc_target_bitrate * 1000));
707 if (idx > RATE_BINS - 1)
709 if (hist->bucket[idx].low > avg_bitrate)
710 hist->bucket[idx].low = (int)avg_bitrate;
711 if (hist->bucket[idx].high < avg_bitrate)
712 hist->bucket[idx].high = (int)avg_bitrate;
713 hist->bucket[idx].count++;
718 static void show_rate_histogram(struct rate_hist *hist,
719 const vpx_codec_enc_cfg_t *cfg,
724 for (i = 0; i < RATE_BINS; i++) {
725 if (hist->bucket[i].low == INT_MAX)
727 hist->bucket[buckets++] = hist->bucket[i];
730 fprintf(stderr, "\nRate (over %dms window):\n", cfg->rc_buf_sz);
731 scale = merge_hist_buckets(hist->bucket, &buckets, max_buckets);
732 show_histogram(hist->bucket, buckets, hist->total, scale);
735 #define mmin(a, b) ((a) < (b) ? (a) : (b))
736 static void find_mismatch(vpx_image_t *img1, vpx_image_t *img2,
737 int yloc[4], int uloc[4], int vloc[4]) {
738 const unsigned int bsize = 64;
739 const unsigned int bsizey = bsize >> img1->y_chroma_shift;
740 const unsigned int bsizex = bsize >> img1->x_chroma_shift;
741 const int c_w = (img1->d_w + img1->x_chroma_shift) >> img1->x_chroma_shift;
742 const int c_h = (img1->d_h + img1->y_chroma_shift) >> img1->y_chroma_shift;
743 unsigned int match = 1;
745 yloc[0] = yloc[1] = yloc[2] = yloc[3] = -1;
746 for (i = 0, match = 1; match && i < img1->d_h; i += bsize) {
747 for (j = 0; match && j < img1->d_w; j += bsize) {
749 int si = mmin(i + bsize, img1->d_h) - i;
750 int sj = mmin(j + bsize, img1->d_w) - j;
751 for (k = 0; match && k < si; k++)
752 for (l = 0; match && l < sj; l++) {
753 if (*(img1->planes[VPX_PLANE_Y] +
754 (i + k) * img1->stride[VPX_PLANE_Y] + j + l) !=
755 *(img2->planes[VPX_PLANE_Y] +
756 (i + k) * img2->stride[VPX_PLANE_Y] + j + l)) {
759 yloc[2] = *(img1->planes[VPX_PLANE_Y] +
760 (i + k) * img1->stride[VPX_PLANE_Y] + j + l);
761 yloc[3] = *(img2->planes[VPX_PLANE_Y] +
762 (i + k) * img2->stride[VPX_PLANE_Y] + j + l);
770 uloc[0] = uloc[1] = uloc[2] = uloc[3] = -1;
771 for (i = 0, match = 1; match && i < c_h; i += bsizey) {
772 for (j = 0; match && j < c_w; j += bsizex) {
774 int si = mmin(i + bsizey, c_h - i);
775 int sj = mmin(j + bsizex, c_w - j);
776 for (k = 0; match && k < si; k++)
777 for (l = 0; match && l < sj; l++) {
778 if (*(img1->planes[VPX_PLANE_U] +
779 (i + k) * img1->stride[VPX_PLANE_U] + j + l) !=
780 *(img2->planes[VPX_PLANE_U] +
781 (i + k) * img2->stride[VPX_PLANE_U] + j + l)) {
784 uloc[2] = *(img1->planes[VPX_PLANE_U] +
785 (i + k) * img1->stride[VPX_PLANE_U] + j + l);
786 uloc[3] = *(img2->planes[VPX_PLANE_U] +
787 (i + k) * img2->stride[VPX_PLANE_V] + j + l);
794 vloc[0] = vloc[1] = vloc[2] = vloc[3] = -1;
795 for (i = 0, match = 1; match && i < c_h; i += bsizey) {
796 for (j = 0; match && j < c_w; j += bsizex) {
798 int si = mmin(i + bsizey, c_h - i);
799 int sj = mmin(j + bsizex, c_w - j);
800 for (k = 0; match && k < si; k++)
801 for (l = 0; match && l < sj; l++) {
802 if (*(img1->planes[VPX_PLANE_V] +
803 (i + k) * img1->stride[VPX_PLANE_V] + j + l) !=
804 *(img2->planes[VPX_PLANE_V] +
805 (i + k) * img2->stride[VPX_PLANE_V] + j + l)) {
808 vloc[2] = *(img1->planes[VPX_PLANE_V] +
809 (i + k) * img1->stride[VPX_PLANE_V] + j + l);
810 vloc[3] = *(img2->planes[VPX_PLANE_V] +
811 (i + k) * img2->stride[VPX_PLANE_V] + j + l);
820 static int compare_img(vpx_image_t *img1, vpx_image_t *img2)
822 const int c_w = (img1->d_w + img1->x_chroma_shift) >> img1->x_chroma_shift;
823 const int c_h = (img1->d_h + img1->y_chroma_shift) >> img1->y_chroma_shift;
827 match &= (img1->fmt == img2->fmt);
828 match &= (img1->w == img2->w);
829 match &= (img1->h == img2->h);
831 for (i = 0; i < img1->d_h; i++)
832 match &= (memcmp(img1->planes[VPX_PLANE_Y]+i*img1->stride[VPX_PLANE_Y],
833 img2->planes[VPX_PLANE_Y]+i*img2->stride[VPX_PLANE_Y],
836 for (i = 0; i < c_h; i++)
837 match &= (memcmp(img1->planes[VPX_PLANE_U]+i*img1->stride[VPX_PLANE_U],
838 img2->planes[VPX_PLANE_U]+i*img2->stride[VPX_PLANE_U],
841 for (i = 0; i < c_h; i++)
842 match &= (memcmp(img1->planes[VPX_PLANE_V]+i*img1->stride[VPX_PLANE_U],
843 img2->planes[VPX_PLANE_V]+i*img2->stride[VPX_PLANE_U],
850 #define NELEMENTS(x) (sizeof(x)/sizeof(x[0]))
851 #define MAX(x,y) ((x)>(y)?(x):(y))
852 #if CONFIG_VP8_ENCODER && !CONFIG_VP9_ENCODER
853 #define ARG_CTRL_CNT_MAX NELEMENTS(vp8_arg_ctrl_map)
854 #elif !CONFIG_VP8_ENCODER && CONFIG_VP9_ENCODER
855 #define ARG_CTRL_CNT_MAX NELEMENTS(vp9_arg_ctrl_map)
857 #define ARG_CTRL_CNT_MAX MAX(NELEMENTS(vp8_arg_ctrl_map), \
858 NELEMENTS(vp9_arg_ctrl_map))
861 /* Per-stream configuration */
862 struct stream_config {
863 struct vpx_codec_enc_cfg cfg;
865 const char *stats_fn;
866 stereo_format_t stereo_fmt;
867 int arg_ctrls[ARG_CTRL_CNT_MAX][2];
870 int have_kf_max_dist;
874 struct stream_state {
876 struct stream_state *next;
877 struct stream_config config;
879 struct rate_hist rate_hist;
880 struct EbmlGlobal ebml;
882 uint64_t psnr_sse_total;
883 uint64_t psnr_samples_total;
884 double psnr_totals[4];
887 vpx_codec_ctx_t encoder;
888 unsigned int frames_out;
892 struct vpx_image *img;
893 vpx_codec_ctx_t decoder;
898 void validate_positive_rational(const char *msg,
899 struct vpx_rational *rat) {
906 die("Error: %s must be positive\n", msg);
909 die("Error: %s has zero denominator\n", msg);
913 static void parse_global_config(struct VpxEncoderConfig *global, char **argv) {
917 /* Initialize default parameters */
918 memset(global, 0, sizeof(*global));
919 global->codec = codecs;
921 global->use_i420 = 1;
922 /* Assign default deadline to good quality */
923 global->deadline = VPX_DL_GOOD_QUALITY;
925 for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step) {
928 if (arg_match(&arg, &codecarg, argi)) {
931 for (j = 0; j < sizeof(codecs) / sizeof(codecs[0]); j++)
932 if (!strcmp(codecs[j].name, arg.val))
936 global->codec = codecs + k;
938 die("Error: Unrecognized argument (%s) to --codec\n",
941 } else if (arg_match(&arg, &passes, argi)) {
942 global->passes = arg_parse_uint(&arg);
944 if (global->passes < 1 || global->passes > 2)
945 die("Error: Invalid number of passes (%d)\n", global->passes);
946 } else if (arg_match(&arg, &pass_arg, argi)) {
947 global->pass = arg_parse_uint(&arg);
949 if (global->pass < 1 || global->pass > 2)
950 die("Error: Invalid pass selected (%d)\n",
952 } else if (arg_match(&arg, &usage, argi))
953 global->usage = arg_parse_uint(&arg);
954 else if (arg_match(&arg, &deadline, argi))
955 global->deadline = arg_parse_uint(&arg);
956 else if (arg_match(&arg, &best_dl, argi))
957 global->deadline = VPX_DL_BEST_QUALITY;
958 else if (arg_match(&arg, &good_dl, argi))
959 global->deadline = VPX_DL_GOOD_QUALITY;
960 else if (arg_match(&arg, &rt_dl, argi))
961 global->deadline = VPX_DL_REALTIME;
962 else if (arg_match(&arg, &use_yv12, argi))
963 global->use_i420 = 0;
964 else if (arg_match(&arg, &use_i420, argi))
965 global->use_i420 = 1;
966 else if (arg_match(&arg, &quietarg, argi))
968 else if (arg_match(&arg, &verbosearg, argi))
970 else if (arg_match(&arg, &limit, argi))
971 global->limit = arg_parse_uint(&arg);
972 else if (arg_match(&arg, &skip, argi))
973 global->skip_frames = arg_parse_uint(&arg);
974 else if (arg_match(&arg, &psnrarg, argi))
975 global->show_psnr = 1;
976 else if (arg_match(&arg, &recontest, argi))
977 global->test_decode = arg_parse_enum_or_int(&arg);
978 else if (arg_match(&arg, &framerate, argi)) {
979 global->framerate = arg_parse_rational(&arg);
980 validate_positive_rational(arg.name, &global->framerate);
981 global->have_framerate = 1;
982 } else if (arg_match(&arg, &out_part, argi))
983 global->out_part = 1;
984 else if (arg_match(&arg, &debugmode, argi))
986 else if (arg_match(&arg, &q_hist_n, argi))
987 global->show_q_hist_buckets = arg_parse_uint(&arg);
988 else if (arg_match(&arg, &rate_hist_n, argi))
989 global->show_rate_hist_buckets = arg_parse_uint(&arg);
994 /* Validate global config */
995 if (global->passes == 0) {
996 #if CONFIG_VP9_ENCODER
997 // Make default VP9 passes = 2 until there is a better quality 1-pass
999 global->passes = (global->codec->iface == vpx_codec_vp9_cx ? 2 : 1);
1006 /* DWIM: Assume the user meant passes=2 if pass=2 is specified */
1007 if (global->pass > global->passes) {
1008 warn("Assuming --pass=%d implies --passes=%d\n",
1009 global->pass, global->pass);
1010 global->passes = global->pass;
1016 void open_input_file(struct VpxInputContext *input) {
1017 /* Parse certain options from the input file, if possible */
1018 input->file = strcmp(input->filename, "-")
1019 ? fopen(input->filename, "rb") : set_binary_mode(stdin);
1022 fatal("Failed to open input file");
1024 if (!fseeko(input->file, 0, SEEK_END)) {
1025 /* Input file is seekable. Figure out how long it is, so we can get
1028 input->length = ftello(input->file);
1029 rewind(input->file);
1032 /* For RAW input sources, these bytes will applied on the first frame
1035 input->detect.buf_read = fread(input->detect.buf, 1, 4, input->file);
1036 input->detect.position = 0;
1038 if (input->detect.buf_read == 4
1039 && file_is_y4m(input->file, &input->y4m, input->detect.buf)) {
1040 if (y4m_input_open(&input->y4m, input->file, input->detect.buf, 4,
1041 input->only_i420) >= 0) {
1042 input->file_type = FILE_TYPE_Y4M;
1043 input->width = input->y4m.pic_w;
1044 input->height = input->y4m.pic_h;
1045 input->framerate.numerator = input->y4m.fps_n;
1046 input->framerate.denominator = input->y4m.fps_d;
1047 input->use_i420 = 0;
1049 fatal("Unsupported Y4M stream.");
1050 } else if (input->detect.buf_read == 4 && file_is_ivf(input)) {
1051 fatal("IVF is not supported as input.");
1053 input->file_type = FILE_TYPE_RAW;
1058 static void close_input_file(struct VpxInputContext *input) {
1059 fclose(input->file);
1060 if (input->file_type == FILE_TYPE_Y4M)
1061 y4m_input_close(&input->y4m);
1064 static struct stream_state *new_stream(struct VpxEncoderConfig *global,
1065 struct stream_state *prev) {
1066 struct stream_state *stream;
1068 stream = calloc(1, sizeof(*stream));
1070 fatal("Failed to allocate new stream.");
1072 memcpy(stream, prev, sizeof(*stream));
1074 prev->next = stream;
1076 vpx_codec_err_t res;
1078 /* Populate encoder configuration */
1079 res = vpx_codec_enc_config_default(global->codec->iface(),
1080 &stream->config.cfg,
1083 fatal("Failed to get config: %s\n", vpx_codec_err_to_string(res));
1085 /* Change the default timebase to a high enough value so that the
1086 * encoder will always create strictly increasing timestamps.
1088 stream->config.cfg.g_timebase.den = 1000;
1090 /* Never use the library's default resolution, require it be parsed
1091 * from the file or set on the command line.
1093 stream->config.cfg.g_w = 0;
1094 stream->config.cfg.g_h = 0;
1096 /* Initialize remaining stream parameters */
1097 stream->config.stereo_fmt = STEREO_FORMAT_MONO;
1098 stream->config.write_webm = 1;
1099 stream->ebml.last_pts_ms = -1;
1101 /* Allows removal of the application version from the EBML tags */
1102 stream->ebml.debug = global->debug;
1105 /* Output files must be specified for each stream */
1106 stream->config.out_fn = NULL;
1108 stream->next = NULL;
1113 static int parse_stream_params(struct VpxEncoderConfig *global,
1114 struct stream_state *stream,
1116 char **argi, **argj;
1118 static const arg_def_t **ctrl_args = no_args;
1119 static const int *ctrl_args_map = NULL;
1120 struct stream_config *config = &stream->config;
1121 int eos_mark_found = 0;
1123 /* Handle codec specific options */
1125 #if CONFIG_VP8_ENCODER
1126 } else if (global->codec->iface == vpx_codec_vp8_cx) {
1127 ctrl_args = vp8_args;
1128 ctrl_args_map = vp8_arg_ctrl_map;
1130 #if CONFIG_VP9_ENCODER
1131 } else if (global->codec->iface == vpx_codec_vp9_cx) {
1132 ctrl_args = vp9_args;
1133 ctrl_args_map = vp9_arg_ctrl_map;
1137 for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step) {
1140 /* Once we've found an end-of-stream marker (--) we want to continue
1141 * shifting arguments but not consuming them.
1143 if (eos_mark_found) {
1146 } else if (!strcmp(*argj, "--")) {
1152 else if (arg_match(&arg, &outputfile, argi))
1153 config->out_fn = arg.val;
1154 else if (arg_match(&arg, &fpf_name, argi))
1155 config->stats_fn = arg.val;
1156 else if (arg_match(&arg, &use_ivf, argi))
1157 config->write_webm = 0;
1158 else if (arg_match(&arg, &threads, argi))
1159 config->cfg.g_threads = arg_parse_uint(&arg);
1160 else if (arg_match(&arg, &profile, argi))
1161 config->cfg.g_profile = arg_parse_uint(&arg);
1162 else if (arg_match(&arg, &width, argi))
1163 config->cfg.g_w = arg_parse_uint(&arg);
1164 else if (arg_match(&arg, &height, argi))
1165 config->cfg.g_h = arg_parse_uint(&arg);
1166 else if (arg_match(&arg, &stereo_mode, argi))
1167 config->stereo_fmt = arg_parse_enum_or_int(&arg);
1168 else if (arg_match(&arg, &timebase, argi)) {
1169 config->cfg.g_timebase = arg_parse_rational(&arg);
1170 validate_positive_rational(arg.name, &config->cfg.g_timebase);
1171 } else if (arg_match(&arg, &error_resilient, argi))
1172 config->cfg.g_error_resilient = arg_parse_uint(&arg);
1173 else if (arg_match(&arg, &lag_in_frames, argi))
1174 config->cfg.g_lag_in_frames = arg_parse_uint(&arg);
1175 else if (arg_match(&arg, &dropframe_thresh, argi))
1176 config->cfg.rc_dropframe_thresh = arg_parse_uint(&arg);
1177 else if (arg_match(&arg, &resize_allowed, argi))
1178 config->cfg.rc_resize_allowed = arg_parse_uint(&arg);
1179 else if (arg_match(&arg, &resize_up_thresh, argi))
1180 config->cfg.rc_resize_up_thresh = arg_parse_uint(&arg);
1181 else if (arg_match(&arg, &resize_down_thresh, argi))
1182 config->cfg.rc_resize_down_thresh = arg_parse_uint(&arg);
1183 else if (arg_match(&arg, &end_usage, argi))
1184 config->cfg.rc_end_usage = arg_parse_enum_or_int(&arg);
1185 else if (arg_match(&arg, &target_bitrate, argi))
1186 config->cfg.rc_target_bitrate = arg_parse_uint(&arg);
1187 else if (arg_match(&arg, &min_quantizer, argi))
1188 config->cfg.rc_min_quantizer = arg_parse_uint(&arg);
1189 else if (arg_match(&arg, &max_quantizer, argi))
1190 config->cfg.rc_max_quantizer = arg_parse_uint(&arg);
1191 else if (arg_match(&arg, &undershoot_pct, argi))
1192 config->cfg.rc_undershoot_pct = arg_parse_uint(&arg);
1193 else if (arg_match(&arg, &overshoot_pct, argi))
1194 config->cfg.rc_overshoot_pct = arg_parse_uint(&arg);
1195 else if (arg_match(&arg, &buf_sz, argi))
1196 config->cfg.rc_buf_sz = arg_parse_uint(&arg);
1197 else if (arg_match(&arg, &buf_initial_sz, argi))
1198 config->cfg.rc_buf_initial_sz = arg_parse_uint(&arg);
1199 else if (arg_match(&arg, &buf_optimal_sz, argi))
1200 config->cfg.rc_buf_optimal_sz = arg_parse_uint(&arg);
1201 else if (arg_match(&arg, &bias_pct, argi)) {
1202 config->cfg.rc_2pass_vbr_bias_pct = arg_parse_uint(&arg);
1204 if (global->passes < 2)
1205 warn("option %s ignored in one-pass mode.\n", arg.name);
1206 } else if (arg_match(&arg, &minsection_pct, argi)) {
1207 config->cfg.rc_2pass_vbr_minsection_pct = arg_parse_uint(&arg);
1209 if (global->passes < 2)
1210 warn("option %s ignored in one-pass mode.\n", arg.name);
1211 } else if (arg_match(&arg, &maxsection_pct, argi)) {
1212 config->cfg.rc_2pass_vbr_maxsection_pct = arg_parse_uint(&arg);
1214 if (global->passes < 2)
1215 warn("option %s ignored in one-pass mode.\n", arg.name);
1216 } else if (arg_match(&arg, &kf_min_dist, argi))
1217 config->cfg.kf_min_dist = arg_parse_uint(&arg);
1218 else if (arg_match(&arg, &kf_max_dist, argi)) {
1219 config->cfg.kf_max_dist = arg_parse_uint(&arg);
1220 config->have_kf_max_dist = 1;
1221 } else if (arg_match(&arg, &kf_disabled, argi))
1222 config->cfg.kf_mode = VPX_KF_DISABLED;
1226 for (i = 0; ctrl_args[i]; i++) {
1227 if (arg_match(&arg, ctrl_args[i], argi)) {
1231 /* Point either to the next free element or the first
1232 * instance of this control.
1234 for (j = 0; j < config->arg_ctrl_cnt; j++)
1235 if (config->arg_ctrls[j][0] == ctrl_args_map[i])
1239 assert(j < ARG_CTRL_CNT_MAX);
1240 if (j < ARG_CTRL_CNT_MAX) {
1241 config->arg_ctrls[j][0] = ctrl_args_map[i];
1242 config->arg_ctrls[j][1] = arg_parse_enum_or_int(&arg);
1243 if (j == config->arg_ctrl_cnt)
1244 config->arg_ctrl_cnt++;
1255 return eos_mark_found;
1259 #define FOREACH_STREAM(func) \
1261 struct stream_state *stream; \
1262 for(stream = streams; stream; stream = stream->next) { \
1268 static void validate_stream_config(struct stream_state *stream) {
1269 struct stream_state *streami;
1271 if (!stream->config.cfg.g_w || !stream->config.cfg.g_h)
1272 fatal("Stream %d: Specify stream dimensions with --width (-w) "
1273 " and --height (-h)", stream->index);
1275 for (streami = stream; streami; streami = streami->next) {
1276 /* All streams require output files */
1277 if (!streami->config.out_fn)
1278 fatal("Stream %d: Output file is required (specify with -o)",
1281 /* Check for two streams outputting to the same file */
1282 if (streami != stream) {
1283 const char *a = stream->config.out_fn;
1284 const char *b = streami->config.out_fn;
1285 if (!strcmp(a, b) && strcmp(a, "/dev/null") && strcmp(a, ":nul"))
1286 fatal("Stream %d: duplicate output file (from stream %d)",
1287 streami->index, stream->index);
1290 /* Check for two streams sharing a stats file. */
1291 if (streami != stream) {
1292 const char *a = stream->config.stats_fn;
1293 const char *b = streami->config.stats_fn;
1294 if (a && b && !strcmp(a, b))
1295 fatal("Stream %d: duplicate stats file (from stream %d)",
1296 streami->index, stream->index);
1302 static void set_stream_dimensions(struct stream_state *stream,
1305 if (!stream->config.cfg.g_w) {
1306 if (!stream->config.cfg.g_h)
1307 stream->config.cfg.g_w = w;
1309 stream->config.cfg.g_w = w * stream->config.cfg.g_h / h;
1311 if (!stream->config.cfg.g_h) {
1312 stream->config.cfg.g_h = h * stream->config.cfg.g_w / w;
1317 static void set_default_kf_interval(struct stream_state *stream,
1318 struct VpxEncoderConfig *global) {
1319 /* Use a max keyframe interval of 5 seconds, if none was
1320 * specified on the command line.
1322 if (!stream->config.have_kf_max_dist) {
1323 double framerate = (double)global->framerate.num / global->framerate.den;
1324 if (framerate > 0.0)
1325 stream->config.cfg.kf_max_dist = (unsigned int)(5.0 * framerate);
1330 static void show_stream_config(struct stream_state *stream,
1331 struct VpxEncoderConfig *global,
1332 struct VpxInputContext *input) {
1334 #define SHOW(field) \
1335 fprintf(stderr, " %-28s = %d\n", #field, stream->config.cfg.field)
1337 if (stream->index == 0) {
1338 fprintf(stderr, "Codec: %s\n",
1339 vpx_codec_iface_name(global->codec->iface()));
1340 fprintf(stderr, "Source file: %s Format: %s\n", input->filename,
1341 input->use_i420 ? "I420" : "YV12");
1343 if (stream->next || stream->index)
1344 fprintf(stderr, "\nStream Index: %d\n", stream->index);
1345 fprintf(stderr, "Destination file: %s\n", stream->config.out_fn);
1346 fprintf(stderr, "Encoder parameters:\n");
1353 SHOW(g_timebase.num);
1354 SHOW(g_timebase.den);
1355 SHOW(g_error_resilient);
1357 SHOW(g_lag_in_frames);
1358 SHOW(rc_dropframe_thresh);
1359 SHOW(rc_resize_allowed);
1360 SHOW(rc_resize_up_thresh);
1361 SHOW(rc_resize_down_thresh);
1363 SHOW(rc_target_bitrate);
1364 SHOW(rc_min_quantizer);
1365 SHOW(rc_max_quantizer);
1366 SHOW(rc_undershoot_pct);
1367 SHOW(rc_overshoot_pct);
1369 SHOW(rc_buf_initial_sz);
1370 SHOW(rc_buf_optimal_sz);
1371 SHOW(rc_2pass_vbr_bias_pct);
1372 SHOW(rc_2pass_vbr_minsection_pct);
1373 SHOW(rc_2pass_vbr_maxsection_pct);
1380 static void open_output_file(struct stream_state *stream,
1381 struct VpxEncoderConfig *global) {
1382 const char *fn = stream->config.out_fn;
1384 stream->file = strcmp(fn, "-") ? fopen(fn, "wb") : set_binary_mode(stdout);
1387 fatal("Failed to open output file");
1389 if (stream->config.write_webm && fseek(stream->file, 0, SEEK_CUR))
1390 fatal("WebM output to pipes not supported.");
1392 if (stream->config.write_webm) {
1393 stream->ebml.stream = stream->file;
1394 write_webm_file_header(&stream->ebml, &stream->config.cfg,
1396 stream->config.stereo_fmt,
1397 global->codec->fourcc);
1399 ivf_write_file_header(stream->file, &stream->config.cfg,
1400 global->codec->fourcc, 0);
1404 static void close_output_file(struct stream_state *stream,
1405 unsigned int fourcc) {
1406 if (stream->config.write_webm) {
1407 write_webm_file_footer(&stream->ebml, stream->hash);
1408 free(stream->ebml.cue_list);
1409 stream->ebml.cue_list = NULL;
1411 if (!fseek(stream->file, 0, SEEK_SET))
1412 ivf_write_file_header(stream->file, &stream->config.cfg,
1414 stream->frames_out);
1417 fclose(stream->file);
1421 static void setup_pass(struct stream_state *stream,
1422 struct VpxEncoderConfig *global,
1424 if (stream->config.stats_fn) {
1425 if (!stats_open_file(&stream->stats, stream->config.stats_fn,
1427 fatal("Failed to open statistics store");
1429 if (!stats_open_mem(&stream->stats, pass))
1430 fatal("Failed to open statistics store");
1433 stream->config.cfg.g_pass = global->passes == 2
1434 ? pass ? VPX_RC_LAST_PASS : VPX_RC_FIRST_PASS
1437 stream->config.cfg.rc_twopass_stats_in = stats_get(&stream->stats);
1439 stream->cx_time = 0;
1441 stream->frames_out = 0;
1445 static void initialize_encoder(struct stream_state *stream,
1446 struct VpxEncoderConfig *global) {
1450 flags |= global->show_psnr ? VPX_CODEC_USE_PSNR : 0;
1451 flags |= global->out_part ? VPX_CODEC_USE_OUTPUT_PARTITION : 0;
1453 /* Construct Encoder Context */
1454 vpx_codec_enc_init(&stream->encoder, global->codec->iface(),
1455 &stream->config.cfg, flags);
1456 ctx_exit_on_error(&stream->encoder, "Failed to initialize encoder");
1458 /* Note that we bypass the vpx_codec_control wrapper macro because
1459 * we're being clever to store the control IDs in an array. Real
1460 * applications will want to make use of the enumerations directly
1462 for (i = 0; i < stream->config.arg_ctrl_cnt; i++) {
1463 int ctrl = stream->config.arg_ctrls[i][0];
1464 int value = stream->config.arg_ctrls[i][1];
1465 if (vpx_codec_control_(&stream->encoder, ctrl, value))
1466 fprintf(stderr, "Error: Tried to set control %d = %d\n",
1469 ctx_exit_on_error(&stream->encoder, "Failed to control codec");
1473 if (global->test_decode != TEST_DECODE_OFF) {
1474 vpx_codec_dec_init(&stream->decoder, global->codec->dx_iface(), NULL, 0);
1480 static void encode_frame(struct stream_state *stream,
1481 struct VpxEncoderConfig *global,
1482 struct vpx_image *img,
1483 unsigned int frames_in) {
1484 vpx_codec_pts_t frame_start, next_frame_start;
1485 struct vpx_codec_enc_cfg *cfg = &stream->config.cfg;
1486 struct vpx_usec_timer timer;
1488 frame_start = (cfg->g_timebase.den * (int64_t)(frames_in - 1)
1489 * global->framerate.den)
1490 / cfg->g_timebase.num / global->framerate.num;
1491 next_frame_start = (cfg->g_timebase.den * (int64_t)(frames_in)
1492 * global->framerate.den)
1493 / cfg->g_timebase.num / global->framerate.num;
1495 /* Scale if necessary */
1496 if (img && (img->d_w != cfg->g_w || img->d_h != cfg->g_h)) {
1498 stream->img = vpx_img_alloc(NULL, VPX_IMG_FMT_I420,
1499 cfg->g_w, cfg->g_h, 16);
1500 I420Scale(img->planes[VPX_PLANE_Y], img->stride[VPX_PLANE_Y],
1501 img->planes[VPX_PLANE_U], img->stride[VPX_PLANE_U],
1502 img->planes[VPX_PLANE_V], img->stride[VPX_PLANE_V],
1504 stream->img->planes[VPX_PLANE_Y],
1505 stream->img->stride[VPX_PLANE_Y],
1506 stream->img->planes[VPX_PLANE_U],
1507 stream->img->stride[VPX_PLANE_U],
1508 stream->img->planes[VPX_PLANE_V],
1509 stream->img->stride[VPX_PLANE_V],
1510 stream->img->d_w, stream->img->d_h,
1516 vpx_usec_timer_start(&timer);
1517 vpx_codec_encode(&stream->encoder, img, frame_start,
1518 (unsigned long)(next_frame_start - frame_start),
1519 0, global->deadline);
1520 vpx_usec_timer_mark(&timer);
1521 stream->cx_time += vpx_usec_timer_elapsed(&timer);
1522 ctx_exit_on_error(&stream->encoder, "Stream %d: Failed to encode frame",
1527 static void update_quantizer_histogram(struct stream_state *stream) {
1528 if (stream->config.cfg.g_pass != VPX_RC_FIRST_PASS) {
1531 vpx_codec_control(&stream->encoder, VP8E_GET_LAST_QUANTIZER_64, &q);
1532 ctx_exit_on_error(&stream->encoder, "Failed to read quantizer");
1533 stream->counts[q]++;
1538 static void get_cx_data(struct stream_state *stream,
1539 struct VpxEncoderConfig *global,
1541 const vpx_codec_cx_pkt_t *pkt;
1542 const struct vpx_codec_enc_cfg *cfg = &stream->config.cfg;
1543 vpx_codec_iter_t iter = NULL;
1546 while ((pkt = vpx_codec_get_cx_data(&stream->encoder, &iter))) {
1547 static size_t fsize = 0;
1548 static off_t ivf_header_pos = 0;
1550 switch (pkt->kind) {
1551 case VPX_CODEC_CX_FRAME_PKT:
1552 if (!(pkt->data.frame.flags & VPX_FRAME_IS_FRAGMENT)) {
1553 stream->frames_out++;
1556 fprintf(stderr, " %6luF", (unsigned long)pkt->data.frame.sz);
1558 update_rate_histogram(&stream->rate_hist, cfg, pkt);
1559 if (stream->config.write_webm) {
1560 /* Update the hash */
1561 if (!stream->ebml.debug)
1562 stream->hash = murmur(pkt->data.frame.buf,
1563 (int)pkt->data.frame.sz,
1566 write_webm_block(&stream->ebml, cfg, pkt);
1568 if (pkt->data.frame.partition_id <= 0) {
1569 ivf_header_pos = ftello(stream->file);
1570 fsize = pkt->data.frame.sz;
1572 ivf_write_frame_header(stream->file, pkt);
1574 fsize += pkt->data.frame.sz;
1576 if (!(pkt->data.frame.flags & VPX_FRAME_IS_FRAGMENT)) {
1577 off_t currpos = ftello(stream->file);
1578 fseeko(stream->file, ivf_header_pos, SEEK_SET);
1579 ivf_write_frame_size(stream->file, fsize);
1580 fseeko(stream->file, currpos, SEEK_SET);
1584 (void) fwrite(pkt->data.frame.buf, 1, pkt->data.frame.sz,
1587 stream->nbytes += pkt->data.raw.sz;
1591 if (global->test_decode != TEST_DECODE_OFF && !stream->mismatch_seen) {
1592 vpx_codec_decode(&stream->decoder, pkt->data.frame.buf,
1593 pkt->data.frame.sz, NULL, 0);
1594 if (stream->decoder.err) {
1595 warn_or_exit_on_error(&stream->decoder,
1596 global->test_decode == TEST_DECODE_FATAL,
1597 "Failed to decode frame %d in stream %d",
1598 stream->frames_out + 1, stream->index);
1599 stream->mismatch_seen = stream->frames_out + 1;
1604 case VPX_CODEC_STATS_PKT:
1605 stream->frames_out++;
1606 stats_write(&stream->stats,
1607 pkt->data.twopass_stats.buf,
1608 pkt->data.twopass_stats.sz);
1609 stream->nbytes += pkt->data.raw.sz;
1611 case VPX_CODEC_PSNR_PKT:
1613 if (global->show_psnr) {
1616 stream->psnr_sse_total += pkt->data.psnr.sse[0];
1617 stream->psnr_samples_total += pkt->data.psnr.samples[0];
1618 for (i = 0; i < 4; i++) {
1620 fprintf(stderr, "%.3f ", pkt->data.psnr.psnr[i]);
1621 stream->psnr_totals[i] += pkt->data.psnr.psnr[i];
1623 stream->psnr_count++;
1634 static void show_psnr(struct stream_state *stream) {
1638 if (!stream->psnr_count)
1641 fprintf(stderr, "Stream %d PSNR (Overall/Avg/Y/U/V)", stream->index);
1642 ovpsnr = vp8_mse2psnr((double)stream->psnr_samples_total, 255.0,
1643 (double)stream->psnr_sse_total);
1644 fprintf(stderr, " %.3f", ovpsnr);
1646 for (i = 0; i < 4; i++) {
1647 fprintf(stderr, " %.3f", stream->psnr_totals[i] / stream->psnr_count);
1649 fprintf(stderr, "\n");
1653 static float usec_to_fps(uint64_t usec, unsigned int frames) {
1654 return (float)(usec > 0 ? frames * 1000000.0 / (float)usec : 0);
1658 static void test_decode(struct stream_state *stream,
1659 enum TestDecodeFatality fatal,
1660 const struct codec_item *codec) {
1661 vpx_image_t enc_img, dec_img;
1663 if (stream->mismatch_seen)
1666 /* Get the internal reference frame */
1667 if (codec->fourcc == VP8_FOURCC) {
1668 struct vpx_ref_frame ref_enc, ref_dec;
1671 width = (stream->config.cfg.g_w + 15) & ~15;
1672 height = (stream->config.cfg.g_h + 15) & ~15;
1673 vpx_img_alloc(&ref_enc.img, VPX_IMG_FMT_I420, width, height, 1);
1674 enc_img = ref_enc.img;
1675 vpx_img_alloc(&ref_dec.img, VPX_IMG_FMT_I420, width, height, 1);
1676 dec_img = ref_dec.img;
1678 ref_enc.frame_type = VP8_LAST_FRAME;
1679 ref_dec.frame_type = VP8_LAST_FRAME;
1680 vpx_codec_control(&stream->encoder, VP8_COPY_REFERENCE, &ref_enc);
1681 vpx_codec_control(&stream->decoder, VP8_COPY_REFERENCE, &ref_dec);
1683 struct vp9_ref_frame ref;
1686 vpx_codec_control(&stream->encoder, VP9_GET_REFERENCE, &ref);
1688 vpx_codec_control(&stream->decoder, VP9_GET_REFERENCE, &ref);
1691 ctx_exit_on_error(&stream->encoder, "Failed to get encoder reference frame");
1692 ctx_exit_on_error(&stream->decoder, "Failed to get decoder reference frame");
1694 if (!compare_img(&enc_img, &dec_img)) {
1695 int y[4], u[4], v[4];
1696 find_mismatch(&enc_img, &dec_img, y, u, v);
1697 stream->decoder.err = 1;
1698 warn_or_exit_on_error(&stream->decoder, fatal == TEST_DECODE_FATAL,
1699 "Stream %d: Encode/decode mismatch on frame %d at"
1700 " Y[%d, %d] {%d/%d},"
1701 " U[%d, %d] {%d/%d},"
1702 " V[%d, %d] {%d/%d}",
1703 stream->index, stream->frames_out,
1704 y[0], y[1], y[2], y[3],
1705 u[0], u[1], u[2], u[3],
1706 v[0], v[1], v[2], v[3]);
1707 stream->mismatch_seen = stream->frames_out;
1710 vpx_img_free(&enc_img);
1711 vpx_img_free(&dec_img);
1715 static void print_time(const char *label, int64_t etl) {
1716 int hours, mins, secs;
1720 etl -= hours * 3600;
1725 fprintf(stderr, "[%3s %2d:%02d:%02d] ",
1726 label, hours, mins, secs);
1728 fprintf(stderr, "[%3s unknown] ", label);
1732 int continue_prompt() {
1734 fprintf(stderr, "Continue? (y to continue) ");
1739 void check_quantizer(struct VpxEncoderConfig* config, int min_q, int max_q) {
1740 int check_failed = 0;
1742 if (config->disable_warnings)
1745 if (min_q == max_q || abs(max_q - min_q) < 8) {
1750 warn("Bad quantizer values. Quantizer values must not be equal, and "
1751 "should differ by at least 8.");
1753 if (!continue_prompt())
1758 int main(int argc, const char **argv_) {
1761 int frame_avail, got_data;
1763 struct VpxInputContext input = {0};
1764 struct VpxEncoderConfig global;
1765 struct stream_state *streams = NULL;
1766 char **argv, **argi;
1767 uint64_t cx_time = 0;
1771 exec_name = argv_[0];
1776 /* Setup default input stream settings */
1777 input.framerate.numerator = 30;
1778 input.framerate.denominator = 1;
1780 input.only_i420 = 1;
1782 /* First parse the global configuration values, because we want to apply
1783 * other parameters on top of the default configuration provided by the
1786 argv = argv_dup(argc - 1, argv_ + 1);
1787 parse_global_config(&global, argv);
1791 /* Now parse each stream's parameters. Using a local scope here
1792 * due to the use of 'stream' as loop variable in FOREACH_STREAM
1795 struct stream_state *stream = NULL;
1798 stream = new_stream(&global, stream);
1802 } while (parse_stream_params(&global, stream, argv));
1805 /* Check for unrecognized options */
1806 for (argi = argv; *argi; argi++)
1807 if (argi[0][0] == '-' && argi[0][1])
1808 die("Error: Unrecognized option %s\n", *argi);
1811 check_quantizer(&global,
1812 stream->config.cfg.rc_min_quantizer,
1813 stream->config.cfg.rc_max_quantizer););
1814 /* Handle non-option arguments */
1815 input.filename = argv[0];
1817 if (!input.filename)
1821 /* Decide if other chroma subsamplings than 4:2:0 are supported */
1822 if (global.codec->fourcc == VP9_FOURCC)
1823 input.only_i420 = 0;
1826 for (pass = global.pass ? global.pass - 1 : 0; pass < global.passes; pass++) {
1827 int frames_in = 0, seen_frames = 0;
1828 int64_t estimated_time_left = -1;
1829 int64_t average_rate = -1;
1830 off_t lagged_count = 0;
1832 open_input_file(&input);
1834 /* If the input file doesn't specify its w/h (raw files), try to get
1835 * the data from the first stream's configuration.
1837 if (!input.width || !input.height)
1839 if (stream->config.cfg.g_w && stream->config.cfg.g_h) {
1840 input.width = stream->config.cfg.g_w;
1841 input.height = stream->config.cfg.g_h;
1846 /* Update stream configurations from the input file's parameters */
1847 if (!input.width || !input.height)
1848 fatal("Specify stream dimensions with --width (-w) "
1849 " and --height (-h)");
1850 FOREACH_STREAM(set_stream_dimensions(stream, input.width, input.height));
1851 FOREACH_STREAM(validate_stream_config(stream));
1853 /* Ensure that --passes and --pass are consistent. If --pass is set and
1854 * --passes=2, ensure --fpf was set.
1856 if (global.pass && global.passes == 2)
1858 if (!stream->config.stats_fn)
1859 die("Stream %d: Must specify --fpf when --pass=%d"
1860 " and --passes=2\n", stream->index, global.pass);
1863 /* Use the frame rate from the file only if none was specified
1864 * on the command-line.
1866 if (!global.have_framerate) {
1867 global.framerate.num = input.framerate.numerator;
1868 global.framerate.den = input.framerate.denominator;
1871 FOREACH_STREAM(set_default_kf_interval(stream, &global));
1873 /* Show configuration */
1874 if (global.verbose && pass == 0)
1875 FOREACH_STREAM(show_stream_config(stream, &global, &input));
1877 if (pass == (global.pass ? global.pass - 1 : 0)) {
1878 if (input.file_type == FILE_TYPE_Y4M)
1879 /*The Y4M reader does its own allocation.
1880 Just initialize this here to avoid problems if we never read any
1882 memset(&raw, 0, sizeof(raw));
1885 input.use_i420 ? VPX_IMG_FMT_I420
1887 input.width, input.height, 32);
1889 FOREACH_STREAM(init_rate_histogram(&stream->rate_hist,
1890 &stream->config.cfg,
1891 &global.framerate));
1894 FOREACH_STREAM(setup_pass(stream, &global, pass));
1895 FOREACH_STREAM(open_output_file(stream, &global));
1896 FOREACH_STREAM(initialize_encoder(stream, &global));
1901 while (frame_avail || got_data) {
1902 struct vpx_usec_timer timer;
1904 if (!global.limit || frames_in < global.limit) {
1905 frame_avail = read_frame(&input, &raw);
1909 seen_frames = frames_in > global.skip_frames ?
1910 frames_in - global.skip_frames : 0;
1912 if (!global.quiet) {
1913 float fps = usec_to_fps(cx_time, seen_frames);
1914 fprintf(stderr, "\rPass %d/%d ", pass + 1, global.passes);
1916 if (stream_cnt == 1)
1918 "frame %4d/%-4d %7"PRId64"B ",
1919 frames_in, streams->frames_out, (int64_t)streams->nbytes);
1921 fprintf(stderr, "frame %4d ", frames_in);
1923 fprintf(stderr, "%7"PRId64" %s %.2f %s ",
1924 cx_time > 9999999 ? cx_time / 1000 : cx_time,
1925 cx_time > 9999999 ? "ms" : "us",
1926 fps >= 1.0 ? fps : fps * 60,
1927 fps >= 1.0 ? "fps" : "fpm");
1928 print_time("ETA", estimated_time_left);
1929 fprintf(stderr, "\033[K");
1935 if (frames_in > global.skip_frames) {
1936 vpx_usec_timer_start(&timer);
1937 FOREACH_STREAM(encode_frame(stream, &global,
1938 frame_avail ? &raw : NULL,
1940 vpx_usec_timer_mark(&timer);
1941 cx_time += vpx_usec_timer_elapsed(&timer);
1943 FOREACH_STREAM(update_quantizer_histogram(stream));
1946 FOREACH_STREAM(get_cx_data(stream, &global, &got_data));
1948 if (!got_data && input.length && !streams->frames_out) {
1949 lagged_count = global.limit ? seen_frames : ftello(input.file);
1950 } else if (input.length) {
1955 int frame_in_lagged = (seen_frames - lagged_count) * 1000;
1957 rate = cx_time ? frame_in_lagged * (int64_t)1000000 / cx_time : 0;
1958 remaining = 1000 * (global.limit - global.skip_frames
1959 - seen_frames + lagged_count);
1961 off_t input_pos = ftello(input.file);
1962 off_t input_pos_lagged = input_pos - lagged_count;
1963 int64_t limit = input.length;
1965 rate = cx_time ? input_pos_lagged * (int64_t)1000000 / cx_time : 0;
1966 remaining = limit - input_pos + lagged_count;
1969 average_rate = (average_rate <= 0)
1971 : (average_rate * 7 + rate) / 8;
1972 estimated_time_left = average_rate ? remaining / average_rate : -1;
1975 if (got_data && global.test_decode != TEST_DECODE_OFF)
1976 FOREACH_STREAM(test_decode(stream, global.test_decode, global.codec));
1983 fprintf(stderr, "\n");
1986 FOREACH_STREAM(fprintf(
1988 "\rPass %d/%d frame %4d/%-4d %7"PRId64"B %7lub/f %7"PRId64"b/s"
1989 " %7"PRId64" %s (%.2f fps)\033[K\n", pass + 1,
1990 global.passes, frames_in, stream->frames_out, (int64_t)stream->nbytes,
1991 seen_frames ? (unsigned long)(stream->nbytes * 8 / seen_frames) : 0,
1992 seen_frames ? (int64_t)stream->nbytes * 8
1993 * (int64_t)global.framerate.num / global.framerate.den
1996 stream->cx_time > 9999999 ? stream->cx_time / 1000 : stream->cx_time,
1997 stream->cx_time > 9999999 ? "ms" : "us",
1998 usec_to_fps(stream->cx_time, seen_frames));
2001 if (global.show_psnr)
2002 FOREACH_STREAM(show_psnr(stream));
2004 FOREACH_STREAM(vpx_codec_destroy(&stream->encoder));
2006 if (global.test_decode != TEST_DECODE_OFF) {
2007 FOREACH_STREAM(vpx_codec_destroy(&stream->decoder));
2010 close_input_file(&input);
2012 if (global.test_decode == TEST_DECODE_FATAL) {
2013 FOREACH_STREAM(res |= stream->mismatch_seen);
2015 FOREACH_STREAM(close_output_file(stream, global.codec->fourcc));
2017 FOREACH_STREAM(stats_close(&stream->stats, global.passes - 1));
2023 if (global.show_q_hist_buckets)
2024 FOREACH_STREAM(show_q_histogram(stream->counts,
2025 global.show_q_hist_buckets));
2027 if (global.show_rate_hist_buckets)
2028 FOREACH_STREAM(show_rate_histogram(&stream->rate_hist,
2029 &stream->config.cfg,
2030 global.show_rate_hist_buckets));
2031 FOREACH_STREAM(destroy_rate_histogram(&stream->rate_hist));
2033 #if CONFIG_INTERNAL_STATS
2034 /* TODO(jkoleszar): This doesn't belong in this executable. Do it for now,
2035 * to match some existing utilities.
2037 if (!(global.pass == 1 && global.passes == 2))
2039 FILE *f = fopen("opsnr.stt", "a");
2040 if (stream->mismatch_seen) {
2041 fprintf(f, "First mismatch occurred in frame %d\n",
2042 stream->mismatch_seen);
2044 fprintf(f, "No mismatch detected in recon buffers\n");
2053 return res ? EXIT_FAILURE : EXIT_SUCCESS;