11 #include "./vpx_config.h"
13 #if defined(_WIN32) || defined(__OS2__) || !CONFIG_OS_SUPPORT
14 #define USE_POSIX_MMAP 0
16 #define USE_POSIX_MMAP 1
31 #include <sys/types.h>
38 #include "third_party/libyuv/include/libyuv/scale.h"
40 #if CONFIG_VP8_ENCODER || CONFIG_VP9_ENCODER
43 #if CONFIG_VP8_DECODER || CONFIG_VP9_DECODER
47 #include "./tools_common.h"
48 #include "vpx_ports/mem_ops.h"
49 #include "vpx_ports/vpx_timer.h"
50 #include "./vpxstats.h"
51 #include "./webmenc.h"
52 #include "./y4minput.h"
55 static size_t wrap_fread(
void *ptr,
size_t size,
size_t nmemb,
57 return fread(ptr, size, nmemb, stream);
59 #define fread wrap_fread
61 static size_t wrap_fwrite(
const void *ptr,
size_t size,
size_t nmemb,
63 return fwrite(ptr, size, nmemb, stream);
65 #define fwrite wrap_fwrite
68 static const char *exec_name;
70 static const struct codec_item {
76 #if CONFIG_VP8_ENCODER && CONFIG_VP8_DECODER
77 {
"vp8", &vpx_codec_vp8_cx, &vpx_codec_vp8_dx, VP8_FOURCC},
78 #elif CONFIG_VP8_ENCODER && !CONFIG_VP8_DECODER
79 {
"vp8", &vpx_codec_vp8_cx, NULL, VP8_FOURCC},
81 #if CONFIG_VP9_ENCODER && CONFIG_VP9_DECODER
82 {
"vp9", &vpx_codec_vp9_cx, &vpx_codec_vp9_dx, VP9_FOURCC},
83 #elif CONFIG_VP9_ENCODER && !CONFIG_VP9_DECODER
84 {
"vp9", &vpx_codec_vp9_cx, NULL, VP9_FOURCC},
89 const char *s, va_list ap) {
93 vfprintf(stderr, s, ap);
97 fprintf(stderr,
" %s\n", detail);
104 static void ctx_exit_on_error(
vpx_codec_ctx_t *ctx,
const char *s, ...) {
108 warn_or_exit_on_errorv(ctx, 1, s, ap);
113 const char *s, ...) {
117 warn_or_exit_on_errorv(ctx, fatal, s, ap);
121 enum video_file_type {
127 struct detect_buffer {
139 struct detect_buffer detect;
140 enum video_file_type file_type;
148 #define IVF_FRAME_HDR_SZ (4+8)
149 static int read_frame(
struct input_state *input,
vpx_image_t *img) {
150 FILE *f = input->file;
151 enum video_file_type file_type = input->file_type;
152 y4m_input *y4m = &input->y4m;
153 struct detect_buffer *detect = &input->detect;
157 if (file_type == FILE_TYPE_Y4M) {
158 if (y4m_input_fetch_frame(y4m, f, img) < 1)
161 if (file_type == FILE_TYPE_IVF) {
162 char junk[IVF_FRAME_HDR_SZ];
168 (void) fread(junk, 1, IVF_FRAME_HDR_SZ, f);
171 for (plane = 0; plane < 3; plane++) {
173 int w = (plane ? (1 + img->
d_w) / 2 : img->
d_w);
174 int h = (plane ? (1 + img->
d_h) / 2 : img->
d_h);
192 for (r = 0; r < h; r++) {
194 size_t buf_position = 0;
195 const size_t left = detect->buf_read - detect->position;
197 const size_t more = (left < needed) ? left : needed;
198 memcpy(ptr, detect->buf + detect->position, more);
201 detect->position += more;
204 shortread |= (fread(ptr + buf_position, 1, needed, f) < needed);
207 ptr += img->
stride[plane];
216 unsigned int file_is_y4m(FILE *infile,
219 if (memcmp(detect,
"YUV4", 4) == 0) {
225 #define IVF_FILE_HDR_SZ (32)
226 unsigned int file_is_ivf(
struct input_state *input,
227 unsigned int *fourcc) {
228 char raw_hdr[IVF_FILE_HDR_SZ];
230 FILE *infile = input->file;
231 unsigned int *width = &input->w;
232 unsigned int *height = &input->h;
233 struct detect_buffer *detect = &input->detect;
235 if (memcmp(detect->buf,
"DKIF", 4) != 0)
241 if (fread(raw_hdr + 4, 1, IVF_FILE_HDR_SZ - 4, infile)
242 == IVF_FILE_HDR_SZ - 4) {
246 if (mem_get_le16(raw_hdr + 4) != 0)
247 warn(
"Unrecognized IVF version! This file may not decode "
250 *fourcc = mem_get_le32(raw_hdr + 8);
255 *width = mem_get_le16(raw_hdr + 12);
256 *height = mem_get_le16(raw_hdr + 14);
257 detect->position = 4;
264 static void write_ivf_file_header(FILE *outfile,
277 mem_put_le16(header + 4, 0);
278 mem_put_le16(header + 6, 32);
279 mem_put_le32(header + 8, fourcc);
280 mem_put_le16(header + 12, cfg->
g_w);
281 mem_put_le16(header + 14, cfg->
g_h);
284 mem_put_le32(header + 24, frame_cnt);
285 mem_put_le32(header + 28, 0);
287 (void) fwrite(header, 1, 32, outfile);
291 static void write_ivf_frame_header(FILE *outfile,
300 mem_put_le32(header, (
int)pkt->
data.
frame.sz);
301 mem_put_le32(header + 4, pts & 0xFFFFFFFF);
302 mem_put_le32(header + 8, pts >> 32);
304 (void) fwrite(header, 1, 12, outfile);
307 static void write_ivf_frame_size(FILE *outfile,
size_t size) {
309 mem_put_le32(header, (
int)size);
310 (void) fwrite(header, 1, 4, outfile);
318 static unsigned int murmur(
const void *key,
int len,
unsigned int seed) {
319 const unsigned int m = 0x5bd1e995;
322 unsigned int h = seed ^ len;
324 const unsigned char *data = (
const unsigned char *)key;
329 k = (
unsigned int)data[0];
330 k |= (
unsigned int)data[1] << 8;
331 k |= (
unsigned int)data[2] << 16;
332 k |= (
unsigned int)data[3] << 24;
364 static const arg_def_t debugmode = ARG_DEF(
"D",
"debug", 0,
365 "Debug mode (makes output deterministic)");
366 static const arg_def_t outputfile = ARG_DEF(
"o",
"output", 1,
368 static const arg_def_t use_yv12 = ARG_DEF(NULL,
"yv12", 0,
369 "Input file is YV12 ");
370 static const arg_def_t use_i420 = ARG_DEF(NULL,
"i420", 0,
371 "Input file is I420 (default)");
372 static const arg_def_t codecarg = ARG_DEF(NULL,
"codec", 1,
374 static const arg_def_t passes = ARG_DEF(
"p",
"passes", 1,
375 "Number of passes (1/2)");
376 static const arg_def_t pass_arg = ARG_DEF(NULL,
"pass", 1,
377 "Pass to execute (1/2)");
378 static const arg_def_t fpf_name = ARG_DEF(NULL,
"fpf", 1,
379 "First pass statistics file name");
380 static const arg_def_t limit = ARG_DEF(NULL,
"limit", 1,
381 "Stop encoding after n input frames");
382 static const arg_def_t skip = ARG_DEF(NULL,
"skip", 1,
383 "Skip the first n input frames");
384 static const arg_def_t deadline = ARG_DEF(
"d",
"deadline", 1,
385 "Deadline per frame (usec)");
386 static const arg_def_t best_dl = ARG_DEF(NULL,
"best", 0,
387 "Use Best Quality Deadline");
388 static const arg_def_t good_dl = ARG_DEF(NULL,
"good", 0,
389 "Use Good Quality Deadline");
390 static const arg_def_t rt_dl = ARG_DEF(NULL,
"rt", 0,
391 "Use Realtime Quality Deadline");
392 static const arg_def_t quietarg = ARG_DEF(
"q",
"quiet", 0,
393 "Do not print encode progress");
394 static const arg_def_t verbosearg = ARG_DEF(
"v",
"verbose", 0,
395 "Show encoder parameters");
396 static const arg_def_t psnrarg = ARG_DEF(NULL,
"psnr", 0,
397 "Show PSNR in status line");
398 enum TestDecodeFatality {
403 static const struct arg_enum_list test_decode_enum[] = {
404 {
"off", TEST_DECODE_OFF},
405 {
"fatal", TEST_DECODE_FATAL},
406 {
"warn", TEST_DECODE_WARN},
409 static const arg_def_t recontest = ARG_DEF_ENUM(NULL,
"test-decode", 1,
410 "Test encode/decode mismatch",
412 static const arg_def_t framerate = ARG_DEF(NULL,
"fps", 1,
413 "Stream frame rate (rate/scale)");
414 static const arg_def_t use_ivf = ARG_DEF(NULL,
"ivf", 0,
415 "Output IVF (default is WebM)");
416 static const arg_def_t out_part = ARG_DEF(
"P",
"output-partitions", 0,
417 "Makes encoder output partitions. Requires IVF output!");
418 static const arg_def_t q_hist_n = ARG_DEF(NULL,
"q-hist", 1,
419 "Show quantizer histogram (n-buckets)");
420 static const arg_def_t rate_hist_n = ARG_DEF(NULL,
"rate-hist", 1,
421 "Show rate histogram (n-buckets)");
422 static const arg_def_t *main_args[] = {
424 &outputfile, &codecarg, &passes, &pass_arg, &fpf_name, &limit, &skip,
425 &deadline, &best_dl, &good_dl, &rt_dl,
426 &quietarg, &verbosearg, &psnrarg, &use_ivf, &out_part, &q_hist_n, &rate_hist_n,
430 static const arg_def_t usage = ARG_DEF(
"u",
"usage", 1,
431 "Usage profile number to use");
432 static const arg_def_t threads = ARG_DEF(
"t",
"threads", 1,
433 "Max number of threads to use");
434 static const arg_def_t profile = ARG_DEF(NULL,
"profile", 1,
435 "Bitstream profile number to use");
436 static const arg_def_t width = ARG_DEF(
"w",
"width", 1,
438 static const arg_def_t height = ARG_DEF(
"h",
"height", 1,
440 static const struct arg_enum_list stereo_mode_enum[] = {
441 {
"mono", STEREO_FORMAT_MONO},
442 {
"left-right", STEREO_FORMAT_LEFT_RIGHT},
443 {
"bottom-top", STEREO_FORMAT_BOTTOM_TOP},
444 {
"top-bottom", STEREO_FORMAT_TOP_BOTTOM},
445 {
"right-left", STEREO_FORMAT_RIGHT_LEFT},
448 static const arg_def_t stereo_mode = ARG_DEF_ENUM(NULL,
"stereo-mode", 1,
449 "Stereo 3D video format", stereo_mode_enum);
450 static const arg_def_t timebase = ARG_DEF(NULL,
"timebase", 1,
451 "Output timestamp precision (fractional seconds)");
452 static const arg_def_t error_resilient = ARG_DEF(NULL,
"error-resilient", 1,
453 "Enable error resiliency features");
454 static const arg_def_t lag_in_frames = ARG_DEF(NULL,
"lag-in-frames", 1,
455 "Max number of frames to lag");
457 static const arg_def_t *global_args[] = {
458 &use_yv12, &use_i420, &usage, &threads, &profile,
459 &width, &height, &stereo_mode, &timebase, &framerate,
464 static const arg_def_t dropframe_thresh = ARG_DEF(NULL,
"drop-frame", 1,
465 "Temporal resampling threshold (buf %)");
466 static const arg_def_t resize_allowed = ARG_DEF(NULL,
"resize-allowed", 1,
467 "Spatial resampling enabled (bool)");
468 static const arg_def_t resize_up_thresh = ARG_DEF(NULL,
"resize-up", 1,
469 "Upscale threshold (buf %)");
470 static const arg_def_t resize_down_thresh = ARG_DEF(NULL,
"resize-down", 1,
471 "Downscale threshold (buf %)");
472 static const struct arg_enum_list end_usage_enum[] = {
479 static const arg_def_t end_usage = ARG_DEF_ENUM(NULL,
"end-usage", 1,
480 "Rate control mode", end_usage_enum);
481 static const arg_def_t target_bitrate = ARG_DEF(NULL,
"target-bitrate", 1,
483 static const arg_def_t min_quantizer = ARG_DEF(NULL,
"min-q", 1,
484 "Minimum (best) quantizer");
485 static const arg_def_t max_quantizer = ARG_DEF(NULL,
"max-q", 1,
486 "Maximum (worst) quantizer");
487 static const arg_def_t undershoot_pct = ARG_DEF(NULL,
"undershoot-pct", 1,
488 "Datarate undershoot (min) target (%)");
489 static const arg_def_t overshoot_pct = ARG_DEF(NULL,
"overshoot-pct", 1,
490 "Datarate overshoot (max) target (%)");
491 static const arg_def_t buf_sz = ARG_DEF(NULL,
"buf-sz", 1,
492 "Client buffer size (ms)");
493 static const arg_def_t buf_initial_sz = ARG_DEF(NULL,
"buf-initial-sz", 1,
494 "Client initial buffer size (ms)");
495 static const arg_def_t buf_optimal_sz = ARG_DEF(NULL,
"buf-optimal-sz", 1,
496 "Client optimal buffer size (ms)");
497 static const arg_def_t *rc_args[] = {
498 &dropframe_thresh, &resize_allowed, &resize_up_thresh, &resize_down_thresh,
499 &end_usage, &target_bitrate, &min_quantizer, &max_quantizer,
500 &undershoot_pct, &overshoot_pct, &buf_sz, &buf_initial_sz, &buf_optimal_sz,
505 static const arg_def_t bias_pct = ARG_DEF(NULL,
"bias-pct", 1,
506 "CBR/VBR bias (0=CBR, 100=VBR)");
507 static const arg_def_t minsection_pct = ARG_DEF(NULL,
"minsection-pct", 1,
508 "GOP min bitrate (% of target)");
509 static const arg_def_t maxsection_pct = ARG_DEF(NULL,
"maxsection-pct", 1,
510 "GOP max bitrate (% of target)");
511 static const arg_def_t *rc_twopass_args[] = {
512 &bias_pct, &minsection_pct, &maxsection_pct, NULL
516 static const arg_def_t kf_min_dist = ARG_DEF(NULL,
"kf-min-dist", 1,
517 "Minimum keyframe interval (frames)");
518 static const arg_def_t kf_max_dist = ARG_DEF(NULL,
"kf-max-dist", 1,
519 "Maximum keyframe interval (frames)");
520 static const arg_def_t kf_disabled = ARG_DEF(NULL,
"disable-kf", 0,
521 "Disable keyframe placement");
522 static const arg_def_t *kf_args[] = {
523 &kf_min_dist, &kf_max_dist, &kf_disabled, NULL
527 static const arg_def_t noise_sens = ARG_DEF(NULL,
"noise-sensitivity", 1,
528 "Noise sensitivity (frames to blur)");
529 static const arg_def_t sharpness = ARG_DEF(NULL,
"sharpness", 1,
530 "Filter sharpness (0-7)");
531 static const arg_def_t static_thresh = ARG_DEF(NULL,
"static-thresh", 1,
532 "Motion detection threshold");
533 static const arg_def_t cpu_used = ARG_DEF(NULL,
"cpu-used", 1,
534 "CPU Used (-16..16)");
535 static const arg_def_t token_parts = ARG_DEF(NULL,
"token-parts", 1,
536 "Number of token partitions to use, log2");
537 static const arg_def_t tile_cols = ARG_DEF(NULL,
"tile-columns", 1,
538 "Number of tile columns to use, log2");
539 static const arg_def_t tile_rows = ARG_DEF(NULL,
"tile-rows", 1,
540 "Number of tile rows to use, log2");
541 static const arg_def_t auto_altref = ARG_DEF(NULL,
"auto-alt-ref", 1,
542 "Enable automatic alt reference frames");
543 static const arg_def_t arnr_maxframes = ARG_DEF(NULL,
"arnr-maxframes", 1,
544 "AltRef Max Frames");
545 static const arg_def_t arnr_strength = ARG_DEF(NULL,
"arnr-strength", 1,
547 static const arg_def_t arnr_type = ARG_DEF(NULL,
"arnr-type", 1,
549 static const struct arg_enum_list tuning_enum[] = {
550 {
"psnr", VP8_TUNE_PSNR},
551 {
"ssim", VP8_TUNE_SSIM},
554 static const arg_def_t tune_ssim = ARG_DEF_ENUM(NULL,
"tune", 1,
555 "Material to favor", tuning_enum);
556 static const arg_def_t cq_level = ARG_DEF(NULL,
"cq-level", 1,
557 "Constant/Constrained Quality level");
558 static const arg_def_t max_intra_rate_pct = ARG_DEF(NULL,
"max-intra-rate", 1,
559 "Max I-frame bitrate (pct)");
560 static const arg_def_t lossless = ARG_DEF(NULL,
"lossless", 1,
"Lossless mode");
561 #if CONFIG_VP9_ENCODER
562 static const arg_def_t frame_parallel_decoding = ARG_DEF(
563 NULL,
"frame-parallel", 1,
"Enable frame parallel decodability features");
564 static const arg_def_t aq_mode = ARG_DEF(
566 "Adaptive quantization mode (0: disabled (by default), 1: variance based)");
569 #if CONFIG_VP8_ENCODER
570 static const arg_def_t *vp8_args[] = {
571 &cpu_used, &auto_altref, &noise_sens, &sharpness, &static_thresh,
572 &token_parts, &arnr_maxframes, &arnr_strength, &arnr_type,
573 &tune_ssim, &cq_level, &max_intra_rate_pct,
576 static const int vp8_arg_ctrl_map[] = {
586 #if CONFIG_VP9_ENCODER
587 static const arg_def_t *vp9_args[] = {
588 &cpu_used, &auto_altref, &noise_sens, &sharpness, &static_thresh,
589 &tile_cols, &tile_rows, &arnr_maxframes, &arnr_strength, &arnr_type,
590 &tune_ssim, &cq_level, &max_intra_rate_pct, &lossless,
591 &frame_parallel_decoding, &aq_mode,
594 static const int vp9_arg_ctrl_map[] = {
597 VP9E_SET_TILE_COLUMNS, VP9E_SET_TILE_ROWS,
600 VP9E_SET_LOSSLESS, VP9E_SET_FRAME_PARALLEL_DECODING, VP9E_SET_AQ_MODE,
605 static const arg_def_t *no_args[] = { NULL };
610 fprintf(stderr,
"Usage: %s <options> -o dst_filename src_filename \n",
613 fprintf(stderr,
"\nOptions:\n");
614 arg_show_usage(stderr, main_args);
615 fprintf(stderr,
"\nEncoder Global Options:\n");
616 arg_show_usage(stderr, global_args);
617 fprintf(stderr,
"\nRate Control Options:\n");
618 arg_show_usage(stderr, rc_args);
619 fprintf(stderr,
"\nTwopass Rate Control Options:\n");
620 arg_show_usage(stderr, rc_twopass_args);
621 fprintf(stderr,
"\nKeyframe Placement Options:\n");
622 arg_show_usage(stderr, kf_args);
623 #if CONFIG_VP8_ENCODER
624 fprintf(stderr,
"\nVP8 Specific Options:\n");
625 arg_show_usage(stderr, vp8_args);
627 #if CONFIG_VP9_ENCODER
628 fprintf(stderr,
"\nVP9 Specific Options:\n");
629 arg_show_usage(stderr, vp9_args);
631 fprintf(stderr,
"\nStream timebase (--timebase):\n"
632 " The desired precision of timestamps in the output, expressed\n"
633 " in fractional seconds. Default is 1/1000.\n");
635 "Included encoders:\n"
638 for (i = 0; i <
sizeof(codecs) /
sizeof(codecs[0]); i++)
639 fprintf(stderr,
" %-6s - %s\n",
647 #define HIST_BAR_MAX 40
649 int low, high, count;
653 static int merge_hist_buckets(
struct hist_bucket *bucket,
656 int small_bucket = 0, merge_bucket = INT_MAX, big_bucket = 0;
657 int buckets = *buckets_;
661 big_bucket = small_bucket = 0;
662 for (i = 0; i < buckets; i++) {
663 if (bucket[i].count < bucket[small_bucket].count)
665 if (bucket[i].count > bucket[big_bucket].count)
672 while (buckets > max_buckets) {
673 int last_bucket = buckets - 1;
676 if (small_bucket == 0)
678 else if (small_bucket == last_bucket)
679 merge_bucket = last_bucket - 1;
680 else if (bucket[small_bucket - 1].count < bucket[small_bucket + 1].count)
681 merge_bucket = small_bucket - 1;
683 merge_bucket = small_bucket + 1;
685 assert(abs(merge_bucket - small_bucket) <= 1);
686 assert(small_bucket < buckets);
687 assert(big_bucket < buckets);
688 assert(merge_bucket < buckets);
690 if (merge_bucket < small_bucket) {
691 bucket[merge_bucket].high = bucket[small_bucket].high;
692 bucket[merge_bucket].count += bucket[small_bucket].count;
694 bucket[small_bucket].high = bucket[merge_bucket].high;
695 bucket[small_bucket].count += bucket[merge_bucket].count;
696 merge_bucket = small_bucket;
699 assert(bucket[merge_bucket].low != bucket[merge_bucket].high);
706 big_bucket = small_bucket = 0;
707 for (i = 0; i < buckets; i++) {
708 if (i > merge_bucket)
709 bucket[i] = bucket[i + 1];
711 if (bucket[i].count < bucket[small_bucket].count)
713 if (bucket[i].count > bucket[big_bucket].count)
720 return bucket[big_bucket].count;
724 static void show_histogram(
const struct hist_bucket *bucket,
728 const char *pat1, *pat2;
731 switch ((
int)(log(bucket[buckets - 1].high) / log(10)) + 1) {
758 pat1 =
"%12d %10s: ";
759 pat2 =
"%12d-%10d: ";
763 for (i = 0; i < buckets; i++) {
768 pct = (float)(100.0 * bucket[i].count / total);
769 len = HIST_BAR_MAX * bucket[i].count / scale;
772 assert(len <= HIST_BAR_MAX);
774 if (bucket[i].low == bucket[i].high)
775 fprintf(stderr, pat1, bucket[i].low,
"");
777 fprintf(stderr, pat2, bucket[i].low, bucket[i].high);
779 for (j = 0; j < HIST_BAR_MAX; j++)
780 fprintf(stderr, j < len ?
"=" :
" ");
781 fprintf(stderr,
"\t%5d (%6.2f%%)\n", bucket[i].count, pct);
786 static void show_q_histogram(
const int counts[64],
int max_buckets) {
787 struct hist_bucket bucket[64];
794 for (i = 0; i < 64; i++) {
796 bucket[buckets].low = bucket[buckets].high = i;
797 bucket[buckets].count = counts[i];
803 fprintf(stderr,
"\nQuantizer Selection:\n");
804 scale = merge_hist_buckets(bucket, &buckets, max_buckets);
805 show_histogram(bucket, buckets, total, scale);
809 #define RATE_BINS (100)
815 struct hist_bucket bucket[RATE_BINS];
820 static void init_rate_histogram(
struct rate_hist *hist,
832 if (hist->samples == 0)
835 hist->pts = calloc(hist->samples,
sizeof(*hist->pts));
836 hist->sz = calloc(hist->samples,
sizeof(*hist->sz));
837 for (i = 0; i < RATE_BINS; i++) {
838 hist->bucket[i].low = INT_MAX;
839 hist->bucket[i].high = 0;
840 hist->bucket[i].count = 0;
845 static void destroy_rate_histogram(
struct rate_hist *hist) {
851 static void update_rate_histogram(
struct rate_hist *hist,
855 int64_t now, then, sum_sz = 0, avg_bitrate;
860 idx = hist->frames++ % hist->samples;
861 hist->pts[idx] = now;
864 if (now < cfg->rc_buf_initial_sz)
870 for (i = hist->frames; i > 0 && hist->frames - i < hist->samples; i--) {
871 int i_idx = (i - 1) % hist->samples;
873 then = hist->pts[i_idx];
876 sum_sz += hist->sz[i_idx];
882 avg_bitrate = sum_sz * 8 * 1000 / (now - then);
886 if (idx > RATE_BINS - 1)
888 if (hist->bucket[idx].low > avg_bitrate)
889 hist->bucket[idx].low = (int)avg_bitrate;
890 if (hist->bucket[idx].high < avg_bitrate)
891 hist->bucket[idx].high = (int)avg_bitrate;
892 hist->bucket[idx].count++;
897 static void show_rate_histogram(
struct rate_hist *hist,
903 for (i = 0; i < RATE_BINS; i++) {
904 if (hist->bucket[i].low == INT_MAX)
906 hist->bucket[buckets++] = hist->bucket[i];
909 fprintf(stderr,
"\nRate (over %dms window):\n", cfg->
rc_buf_sz);
910 scale = merge_hist_buckets(hist->bucket, &buckets, max_buckets);
911 show_histogram(hist->bucket, buckets, hist->total, scale);
914 #define mmin(a, b) ((a) < (b) ? (a) : (b))
916 int yloc[4],
int uloc[4],
int vloc[4]) {
917 const unsigned int bsize = 64;
922 unsigned int match = 1;
924 yloc[0] = yloc[1] = yloc[2] = yloc[3] = -1;
925 for (i = 0, match = 1; match && i < img1->
d_h; i += bsize) {
926 for (j = 0; match && j < img1->
d_w; j += bsize) {
928 int si = mmin(i + bsize, img1->
d_h) - i;
929 int sj = mmin(j + bsize, img1->
d_w) - j;
930 for (k = 0; match && k < si; k++)
931 for (l = 0; match && l < sj; l++) {
932 if (*(img1->
planes[VPX_PLANE_Y] +
933 (i + k) * img1->
stride[VPX_PLANE_Y] + j + l) !=
934 *(img2->
planes[VPX_PLANE_Y] +
935 (i + k) * img2->
stride[VPX_PLANE_Y] + j + l)) {
939 (i + k) * img1->
stride[VPX_PLANE_Y] + j + l);
941 (i + k) * img2->
stride[VPX_PLANE_Y] + j + l);
949 uloc[0] = uloc[1] = uloc[2] = uloc[3] = -1;
950 for (i = 0, match = 1; match && i < c_h; i += bsizey) {
951 for (j = 0; match && j < c_w; j += bsizex) {
953 int si = mmin(i + bsizey, c_h - i);
954 int sj = mmin(j + bsizex, c_w - j);
955 for (k = 0; match && k < si; k++)
956 for (l = 0; match && l < sj; l++) {
957 if (*(img1->
planes[VPX_PLANE_U] +
958 (i + k) * img1->
stride[VPX_PLANE_U] + j + l) !=
959 *(img2->
planes[VPX_PLANE_U] +
960 (i + k) * img2->
stride[VPX_PLANE_U] + j + l)) {
964 (i + k) * img1->
stride[VPX_PLANE_U] + j + l);
973 vloc[0] = vloc[1] = vloc[2] = vloc[3] = -1;
974 for (i = 0, match = 1; match && i < c_h; i += bsizey) {
975 for (j = 0; match && j < c_w; j += bsizex) {
977 int si = mmin(i + bsizey, c_h - i);
978 int sj = mmin(j + bsizex, c_w - j);
979 for (k = 0; match && k < si; k++)
980 for (l = 0; match && l < sj; l++) {
1006 match &= (img1->
fmt == img2->
fmt);
1007 match &= (img1->
w == img2->
w);
1008 match &= (img1->
h == img2->
h);
1010 for (i = 0; i < img1->
d_h; i++)
1011 match &= (memcmp(img1->
planes[VPX_PLANE_Y]+i*img1->
stride[VPX_PLANE_Y],
1015 for (i = 0; i < c_h; i++)
1016 match &= (memcmp(img1->
planes[VPX_PLANE_U]+i*img1->
stride[VPX_PLANE_U],
1020 for (i = 0; i < c_h; i++)
1029 #define NELEMENTS(x) (sizeof(x)/sizeof(x[0]))
1030 #define MAX(x,y) ((x)>(y)?(x):(y))
1031 #if CONFIG_VP8_ENCODER && !CONFIG_VP9_ENCODER
1032 #define ARG_CTRL_CNT_MAX NELEMENTS(vp8_arg_ctrl_map)
1033 #elif !CONFIG_VP8_ENCODER && CONFIG_VP9_ENCODER
1034 #define ARG_CTRL_CNT_MAX NELEMENTS(vp9_arg_ctrl_map)
1036 #define ARG_CTRL_CNT_MAX MAX(NELEMENTS(vp8_arg_ctrl_map), \
1037 NELEMENTS(vp9_arg_ctrl_map))
1041 struct global_config {
1042 const struct codec_item *codec;
1053 enum TestDecodeFatality test_decode;
1058 int show_q_hist_buckets;
1059 int show_rate_hist_buckets;
1064 struct stream_config {
1067 const char *stats_fn;
1068 stereo_format_t stereo_fmt;
1069 int arg_ctrls[ARG_CTRL_CNT_MAX][2];
1072 int have_kf_max_dist;
1076 struct stream_state {
1078 struct stream_state *next;
1079 struct stream_config config;
1081 struct rate_hist rate_hist;
1082 struct EbmlGlobal ebml;
1084 uint64_t psnr_sse_total;
1085 uint64_t psnr_samples_total;
1086 double psnr_totals[4];
1090 unsigned int frames_out;
1100 void validate_positive_rational(
const char *msg,
1108 die(
"Error: %s must be positive\n", msg);
1111 die(
"Error: %s has zero denominator\n", msg);
1115 static void parse_global_config(
struct global_config *global,
char **argv) {
1116 char **argi, **argj;
1120 memset(global, 0,
sizeof(*global));
1121 global->codec = codecs;
1123 global->use_i420 = 1;
1127 for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step) {
1130 if (arg_match(&arg, &codecarg, argi)) {
1133 for (j = 0; j <
sizeof(codecs) /
sizeof(codecs[0]); j++)
1134 if (!strcmp(codecs[j].name, arg.val))
1138 global->codec = codecs + k;
1140 die(
"Error: Unrecognized argument (%s) to --codec\n",
1143 }
else if (arg_match(&arg, &passes, argi)) {
1144 global->passes = arg_parse_uint(&arg);
1146 if (global->passes < 1 || global->passes > 2)
1147 die(
"Error: Invalid number of passes (%d)\n", global->passes);
1148 }
else if (arg_match(&arg, &pass_arg, argi)) {
1149 global->pass = arg_parse_uint(&arg);
1151 if (global->pass < 1 || global->pass > 2)
1152 die(
"Error: Invalid pass selected (%d)\n",
1154 }
else if (arg_match(&arg, &usage, argi))
1155 global->usage = arg_parse_uint(&arg);
1156 else if (arg_match(&arg, &deadline, argi))
1157 global->deadline = arg_parse_uint(&arg);
1158 else if (arg_match(&arg, &best_dl, argi))
1160 else if (arg_match(&arg, &good_dl, argi))
1162 else if (arg_match(&arg, &rt_dl, argi))
1164 else if (arg_match(&arg, &use_yv12, argi))
1165 global->use_i420 = 0;
1166 else if (arg_match(&arg, &use_i420, argi))
1167 global->use_i420 = 1;
1168 else if (arg_match(&arg, &quietarg, argi))
1170 else if (arg_match(&arg, &verbosearg, argi))
1171 global->verbose = 1;
1172 else if (arg_match(&arg, &limit, argi))
1173 global->limit = arg_parse_uint(&arg);
1174 else if (arg_match(&arg, &skip, argi))
1175 global->skip_frames = arg_parse_uint(&arg);
1176 else if (arg_match(&arg, &psnrarg, argi))
1177 global->show_psnr = 1;
1178 else if (arg_match(&arg, &recontest, argi))
1179 global->test_decode = arg_parse_enum_or_int(&arg);
1180 else if (arg_match(&arg, &framerate, argi)) {
1181 global->framerate = arg_parse_rational(&arg);
1182 validate_positive_rational(arg.name, &global->framerate);
1183 global->have_framerate = 1;
1184 }
else if (arg_match(&arg, &out_part, argi))
1185 global->out_part = 1;
1186 else if (arg_match(&arg, &debugmode, argi))
1188 else if (arg_match(&arg, &q_hist_n, argi))
1189 global->show_q_hist_buckets = arg_parse_uint(&arg);
1190 else if (arg_match(&arg, &rate_hist_n, argi))
1191 global->show_rate_hist_buckets = arg_parse_uint(&arg);
1197 if (global->passes == 0) {
1198 #if CONFIG_VP9_ENCODER
1201 global->passes = (global->codec->iface == vpx_codec_vp9_cx ? 2 : 1);
1209 if (global->pass > global->passes) {
1210 warn(
"Assuming --pass=%d implies --passes=%d\n",
1211 global->pass, global->pass);
1212 global->passes = global->pass;
1218 void open_input_file(
struct input_state *input) {
1219 unsigned int fourcc;
1222 input->file = strcmp(input->fn,
"-") ? fopen(input->fn,
"rb")
1223 : set_binary_mode(stdin);
1226 fatal(
"Failed to open input file");
1228 if (!fseeko(input->file, 0, SEEK_END)) {
1232 input->length = ftello(input->file);
1233 rewind(input->file);
1239 input->detect.buf_read = fread(input->detect.buf, 1, 4, input->file);
1240 input->detect.position = 0;
1242 if (input->detect.buf_read == 4
1243 && file_is_y4m(input->file, &input->y4m, input->detect.buf)) {
1244 if (y4m_input_open(&input->y4m, input->file, input->detect.buf, 4,
1245 input->only_i420) >= 0) {
1246 input->file_type = FILE_TYPE_Y4M;
1247 input->w = input->y4m.pic_w;
1248 input->h = input->y4m.pic_h;
1249 input->framerate.num = input->y4m.fps_n;
1250 input->framerate.den = input->y4m.fps_d;
1251 input->use_i420 = 0;
1253 fatal(
"Unsupported Y4M stream.");
1254 }
else if (input->detect.buf_read == 4 && file_is_ivf(input, &fourcc)) {
1255 fatal(
"IVF is not supported as input.");
1257 input->file_type = FILE_TYPE_RAW;
1262 static void close_input_file(
struct input_state *input) {
1263 fclose(input->file);
1264 if (input->file_type == FILE_TYPE_Y4M)
1265 y4m_input_close(&input->y4m);
1268 static struct stream_state *new_stream(
struct global_config *global,
1269 struct stream_state *prev) {
1270 struct stream_state *stream;
1272 stream = calloc(1,
sizeof(*stream));
1274 fatal(
"Failed to allocate new stream.");
1276 memcpy(stream, prev,
sizeof(*stream));
1278 prev->next = stream;
1284 &stream->config.cfg,
1292 stream->config.cfg.g_timebase.den = 1000;
1297 stream->config.cfg.g_w = 0;
1298 stream->config.cfg.g_h = 0;
1301 stream->config.stereo_fmt = STEREO_FORMAT_MONO;
1302 stream->config.write_webm = 1;
1303 stream->ebml.last_pts_ms = -1;
1306 stream->ebml.debug = global->debug;
1310 stream->config.out_fn = NULL;
1312 stream->next = NULL;
1317 static int parse_stream_params(
struct global_config *global,
1318 struct stream_state *stream,
1320 char **argi, **argj;
1322 static const arg_def_t **ctrl_args = no_args;
1323 static const int *ctrl_args_map = NULL;
1324 struct stream_config *config = &stream->config;
1325 int eos_mark_found = 0;
1329 #if CONFIG_VP8_ENCODER
1330 }
else if (global->codec->iface == vpx_codec_vp8_cx) {
1331 ctrl_args = vp8_args;
1332 ctrl_args_map = vp8_arg_ctrl_map;
1334 #if CONFIG_VP9_ENCODER
1335 }
else if (global->codec->iface == vpx_codec_vp9_cx) {
1336 ctrl_args = vp9_args;
1337 ctrl_args_map = vp9_arg_ctrl_map;
1341 for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step) {
1347 if (eos_mark_found) {
1350 }
else if (!strcmp(*argj,
"--")) {
1356 else if (arg_match(&arg, &outputfile, argi))
1357 config->out_fn = arg.val;
1358 else if (arg_match(&arg, &fpf_name, argi))
1359 config->stats_fn = arg.val;
1360 else if (arg_match(&arg, &use_ivf, argi))
1361 config->write_webm = 0;
1362 else if (arg_match(&arg, &threads, argi))
1363 config->cfg.g_threads = arg_parse_uint(&arg);
1364 else if (arg_match(&arg, &profile, argi))
1365 config->cfg.g_profile = arg_parse_uint(&arg);
1366 else if (arg_match(&arg, &width, argi))
1367 config->cfg.g_w = arg_parse_uint(&arg);
1368 else if (arg_match(&arg, &height, argi))
1369 config->cfg.g_h = arg_parse_uint(&arg);
1370 else if (arg_match(&arg, &stereo_mode, argi))
1371 config->stereo_fmt = arg_parse_enum_or_int(&arg);
1372 else if (arg_match(&arg, &timebase, argi)) {
1373 config->cfg.g_timebase = arg_parse_rational(&arg);
1374 validate_positive_rational(arg.name, &config->cfg.g_timebase);
1375 }
else if (arg_match(&arg, &error_resilient, argi))
1376 config->cfg.g_error_resilient = arg_parse_uint(&arg);
1377 else if (arg_match(&arg, &lag_in_frames, argi))
1378 config->cfg.g_lag_in_frames = arg_parse_uint(&arg);
1379 else if (arg_match(&arg, &dropframe_thresh, argi))
1380 config->cfg.rc_dropframe_thresh = arg_parse_uint(&arg);
1381 else if (arg_match(&arg, &resize_allowed, argi))
1382 config->cfg.rc_resize_allowed = arg_parse_uint(&arg);
1383 else if (arg_match(&arg, &resize_up_thresh, argi))
1384 config->cfg.rc_resize_up_thresh = arg_parse_uint(&arg);
1385 else if (arg_match(&arg, &resize_down_thresh, argi))
1386 config->cfg.rc_resize_down_thresh = arg_parse_uint(&arg);
1387 else if (arg_match(&arg, &end_usage, argi))
1388 config->cfg.rc_end_usage = arg_parse_enum_or_int(&arg);
1389 else if (arg_match(&arg, &target_bitrate, argi))
1390 config->cfg.rc_target_bitrate = arg_parse_uint(&arg);
1391 else if (arg_match(&arg, &min_quantizer, argi))
1392 config->cfg.rc_min_quantizer = arg_parse_uint(&arg);
1393 else if (arg_match(&arg, &max_quantizer, argi))
1394 config->cfg.rc_max_quantizer = arg_parse_uint(&arg);
1395 else if (arg_match(&arg, &undershoot_pct, argi))
1396 config->cfg.rc_undershoot_pct = arg_parse_uint(&arg);
1397 else if (arg_match(&arg, &overshoot_pct, argi))
1398 config->cfg.rc_overshoot_pct = arg_parse_uint(&arg);
1399 else if (arg_match(&arg, &buf_sz, argi))
1400 config->cfg.rc_buf_sz = arg_parse_uint(&arg);
1401 else if (arg_match(&arg, &buf_initial_sz, argi))
1402 config->cfg.rc_buf_initial_sz = arg_parse_uint(&arg);
1403 else if (arg_match(&arg, &buf_optimal_sz, argi))
1404 config->cfg.rc_buf_optimal_sz = arg_parse_uint(&arg);
1405 else if (arg_match(&arg, &bias_pct, argi)) {
1406 config->cfg.rc_2pass_vbr_bias_pct = arg_parse_uint(&arg);
1408 if (global->passes < 2)
1409 warn(
"option %s ignored in one-pass mode.\n", arg.name);
1410 }
else if (arg_match(&arg, &minsection_pct, argi)) {
1411 config->cfg.rc_2pass_vbr_minsection_pct = arg_parse_uint(&arg);
1413 if (global->passes < 2)
1414 warn(
"option %s ignored in one-pass mode.\n", arg.name);
1415 }
else if (arg_match(&arg, &maxsection_pct, argi)) {
1416 config->cfg.rc_2pass_vbr_maxsection_pct = arg_parse_uint(&arg);
1418 if (global->passes < 2)
1419 warn(
"option %s ignored in one-pass mode.\n", arg.name);
1420 }
else if (arg_match(&arg, &kf_min_dist, argi))
1421 config->cfg.kf_min_dist = arg_parse_uint(&arg);
1422 else if (arg_match(&arg, &kf_max_dist, argi)) {
1423 config->cfg.kf_max_dist = arg_parse_uint(&arg);
1424 config->have_kf_max_dist = 1;
1425 }
else if (arg_match(&arg, &kf_disabled, argi))
1430 for (i = 0; ctrl_args[i]; i++) {
1431 if (arg_match(&arg, ctrl_args[i], argi)) {
1438 for (j = 0; j < config->arg_ctrl_cnt; j++)
1439 if (config->arg_ctrls[j][0] == ctrl_args_map[i])
1443 assert(j < ARG_CTRL_CNT_MAX);
1444 if (j < ARG_CTRL_CNT_MAX) {
1445 config->arg_ctrls[j][0] = ctrl_args_map[i];
1446 config->arg_ctrls[j][1] = arg_parse_enum_or_int(&arg);
1447 if (j == config->arg_ctrl_cnt)
1448 config->arg_ctrl_cnt++;
1459 return eos_mark_found;
1463 #define FOREACH_STREAM(func)\
1466 struct stream_state *stream;\
1468 for(stream = streams; stream; stream = stream->next)\
1473 static void validate_stream_config(
struct stream_state *stream) {
1474 struct stream_state *streami;
1476 if (!stream->config.cfg.g_w || !stream->config.cfg.g_h)
1477 fatal(
"Stream %d: Specify stream dimensions with --width (-w) "
1478 " and --height (-h)", stream->index);
1480 for (streami = stream; streami; streami = streami->next) {
1482 if (!streami->config.out_fn)
1483 fatal(
"Stream %d: Output file is required (specify with -o)",
1487 if (streami != stream) {
1488 const char *a = stream->config.out_fn;
1489 const char *b = streami->config.out_fn;
1490 if (!strcmp(a, b) && strcmp(a,
"/dev/null") && strcmp(a,
":nul"))
1491 fatal(
"Stream %d: duplicate output file (from stream %d)",
1492 streami->index, stream->index);
1496 if (streami != stream) {
1497 const char *a = stream->config.stats_fn;
1498 const char *b = streami->config.stats_fn;
1499 if (a && b && !strcmp(a, b))
1500 fatal(
"Stream %d: duplicate stats file (from stream %d)",
1501 streami->index, stream->index);
1507 static void set_stream_dimensions(
struct stream_state *stream,
1510 if (!stream->config.cfg.g_w) {
1511 if (!stream->config.cfg.g_h)
1512 stream->config.cfg.g_w = w;
1514 stream->config.cfg.g_w = w * stream->config.cfg.g_h / h;
1516 if (!stream->config.cfg.g_h) {
1517 stream->config.cfg.g_h = h * stream->config.cfg.g_w / w;
1522 static void set_default_kf_interval(
struct stream_state *stream,
1523 struct global_config *global) {
1527 if (!stream->config.have_kf_max_dist) {
1528 double framerate = (double)global->framerate.num / global->framerate.den;
1529 if (framerate > 0.0)
1530 stream->config.cfg.kf_max_dist = (
unsigned int)(5.0 * framerate);
1535 static void show_stream_config(
struct stream_state *stream,
1536 struct global_config *global,
1537 struct input_state *input) {
1539 #define SHOW(field) \
1540 fprintf(stderr, " %-28s = %d\n", #field, stream->config.cfg.field)
1542 if (stream->index == 0) {
1543 fprintf(stderr,
"Codec: %s\n",
1545 fprintf(stderr,
"Source file: %s Format: %s\n", input->fn,
1546 input->use_i420 ?
"I420" :
"YV12");
1548 if (stream->next || stream->index)
1549 fprintf(stderr,
"\nStream Index: %d\n", stream->index);
1550 fprintf(stderr,
"Destination file: %s\n", stream->config.out_fn);
1551 fprintf(stderr,
"Encoder parameters:\n");
1558 SHOW(g_timebase.num);
1559 SHOW(g_timebase.den);
1560 SHOW(g_error_resilient);
1562 SHOW(g_lag_in_frames);
1563 SHOW(rc_dropframe_thresh);
1564 SHOW(rc_resize_allowed);
1565 SHOW(rc_resize_up_thresh);
1566 SHOW(rc_resize_down_thresh);
1568 SHOW(rc_target_bitrate);
1569 SHOW(rc_min_quantizer);
1570 SHOW(rc_max_quantizer);
1571 SHOW(rc_undershoot_pct);
1572 SHOW(rc_overshoot_pct);
1574 SHOW(rc_buf_initial_sz);
1575 SHOW(rc_buf_optimal_sz);
1576 SHOW(rc_2pass_vbr_bias_pct);
1577 SHOW(rc_2pass_vbr_minsection_pct);
1578 SHOW(rc_2pass_vbr_maxsection_pct);
1585 static void open_output_file(
struct stream_state *stream,
1586 struct global_config *global) {
1587 const char *fn = stream->config.out_fn;
1589 stream->file = strcmp(fn,
"-") ? fopen(fn,
"wb") : set_binary_mode(stdout);
1592 fatal(
"Failed to open output file");
1594 if (stream->config.write_webm && fseek(stream->file, 0, SEEK_CUR))
1595 fatal(
"WebM output to pipes not supported.");
1597 if (stream->config.write_webm) {
1598 stream->ebml.stream = stream->file;
1599 write_webm_file_header(&stream->ebml, &stream->config.cfg,
1601 stream->config.stereo_fmt,
1602 global->codec->fourcc);
1604 write_ivf_file_header(stream->file, &stream->config.cfg,
1605 global->codec->fourcc, 0);
1609 static void close_output_file(
struct stream_state *stream,
1610 unsigned int fourcc) {
1611 if (stream->config.write_webm) {
1612 write_webm_file_footer(&stream->ebml, stream->hash);
1613 free(stream->ebml.cue_list);
1614 stream->ebml.cue_list = NULL;
1616 if (!fseek(stream->file, 0, SEEK_SET))
1617 write_ivf_file_header(stream->file, &stream->config.cfg,
1619 stream->frames_out);
1622 fclose(stream->file);
1626 static void setup_pass(
struct stream_state *stream,
1627 struct global_config *global,
1629 if (stream->config.stats_fn) {
1630 if (!stats_open_file(&stream->stats, stream->config.stats_fn,
1632 fatal(
"Failed to open statistics store");
1634 if (!stats_open_mem(&stream->stats, pass))
1635 fatal(
"Failed to open statistics store");
1638 stream->config.cfg.g_pass = global->passes == 2
1642 stream->config.cfg.rc_twopass_stats_in = stats_get(&stream->stats);
1644 stream->cx_time = 0;
1646 stream->frames_out = 0;
1650 static void initialize_encoder(
struct stream_state *stream,
1651 struct global_config *global) {
1660 &stream->config.cfg, flags);
1661 ctx_exit_on_error(&stream->encoder,
"Failed to initialize encoder");
1667 for (i = 0; i < stream->config.arg_ctrl_cnt; i++) {
1668 int ctrl = stream->config.arg_ctrls[i][0];
1669 int value = stream->config.arg_ctrls[i][1];
1671 fprintf(stderr,
"Error: Tried to set control %d = %d\n",
1674 ctx_exit_on_error(&stream->encoder,
"Failed to control codec");
1678 if (global->test_decode != TEST_DECODE_OFF) {
1685 static void encode_frame(
struct stream_state *stream,
1686 struct global_config *global,
1688 unsigned int frames_in) {
1691 struct vpx_usec_timer timer;
1693 frame_start = (cfg->
g_timebase.
den * (int64_t)(frames_in - 1)
1694 * global->framerate.den)
1696 next_frame_start = (cfg->
g_timebase.
den * (int64_t)(frames_in)
1697 * global->framerate.den)
1701 if (img && (img->
d_w != cfg->
g_w || img->
d_h != cfg->
g_h)) {
1705 I420Scale(img->
planes[VPX_PLANE_Y], img->
stride[VPX_PLANE_Y],
1709 stream->img->planes[VPX_PLANE_Y],
1710 stream->img->stride[VPX_PLANE_Y],
1711 stream->img->planes[VPX_PLANE_U],
1712 stream->img->stride[VPX_PLANE_U],
1715 stream->img->d_w, stream->img->d_h,
1721 vpx_usec_timer_start(&timer);
1723 (
unsigned long)(next_frame_start - frame_start),
1724 0, global->deadline);
1725 vpx_usec_timer_mark(&timer);
1726 stream->cx_time += vpx_usec_timer_elapsed(&timer);
1727 ctx_exit_on_error(&stream->encoder,
"Stream %d: Failed to encode frame",
1732 static void update_quantizer_histogram(
struct stream_state *stream) {
1737 ctx_exit_on_error(&stream->encoder,
"Failed to read quantizer");
1738 stream->counts[q]++;
1743 static void get_cx_data(
struct stream_state *stream,
1744 struct global_config *global,
1752 static size_t fsize = 0;
1753 static off_t ivf_header_pos = 0;
1755 switch (pkt->
kind) {
1758 stream->frames_out++;
1761 fprintf(stderr,
" %6luF", (
unsigned long)pkt->
data.
frame.sz);
1763 update_rate_histogram(&stream->rate_hist, cfg, pkt);
1764 if (stream->config.write_webm) {
1766 if (!stream->ebml.debug)
1767 stream->hash = murmur(pkt->
data.
frame.buf,
1771 write_webm_block(&stream->ebml, cfg, pkt);
1773 if (pkt->
data.
frame.partition_id <= 0) {
1774 ivf_header_pos = ftello(stream->file);
1777 write_ivf_frame_header(stream->file, pkt);
1782 off_t currpos = ftello(stream->file);
1783 fseeko(stream->file, ivf_header_pos, SEEK_SET);
1784 write_ivf_frame_size(stream->file, fsize);
1785 fseeko(stream->file, currpos, SEEK_SET);
1796 if (global->test_decode != TEST_DECODE_OFF && !stream->mismatch_seen) {
1799 if (stream->decoder.err) {
1800 warn_or_exit_on_error(&stream->decoder,
1801 global->test_decode == TEST_DECODE_FATAL,
1802 "Failed to decode frame %d in stream %d",
1803 stream->frames_out + 1, stream->index);
1804 stream->mismatch_seen = stream->frames_out + 1;
1810 stream->frames_out++;
1811 stats_write(&stream->stats,
1818 if (global->show_psnr) {
1821 stream->psnr_sse_total += pkt->
data.
psnr.sse[0];
1822 stream->psnr_samples_total += pkt->
data.
psnr.samples[0];
1823 for (i = 0; i < 4; i++) {
1825 fprintf(stderr,
"%.3f ", pkt->
data.
psnr.psnr[i]);
1826 stream->psnr_totals[i] += pkt->
data.
psnr.psnr[i];
1828 stream->psnr_count++;
1839 static void show_psnr(
struct stream_state *stream) {
1843 if (!stream->psnr_count)
1846 fprintf(stderr,
"Stream %d PSNR (Overall/Avg/Y/U/V)", stream->index);
1847 ovpsnr = vp8_mse2psnr((
double)stream->psnr_samples_total, 255.0,
1848 (
double)stream->psnr_sse_total);
1849 fprintf(stderr,
" %.3f", ovpsnr);
1851 for (i = 0; i < 4; i++) {
1852 fprintf(stderr,
" %.3f", stream->psnr_totals[i] / stream->psnr_count);
1854 fprintf(stderr,
"\n");
1858 static float usec_to_fps(uint64_t usec,
unsigned int frames) {
1859 return (
float)(usec > 0 ? frames * 1000000.0 / (float)usec : 0);
1863 static void test_decode(
struct stream_state *stream,
1864 enum TestDecodeFatality fatal,
1865 const struct codec_item *codec) {
1868 if (stream->mismatch_seen)
1872 if (codec->fourcc == VP8_FOURCC) {
1876 width = (stream->config.cfg.g_w + 15) & ~15;
1877 height = (stream->config.cfg.g_h + 15) & ~15;
1879 enc_img = ref_enc.img;
1881 dec_img = ref_dec.img;
1883 ref_enc.frame_type = VP8_LAST_FRAME;
1884 ref_dec.frame_type = VP8_LAST_FRAME;
1896 ctx_exit_on_error(&stream->encoder,
"Failed to get encoder reference frame");
1897 ctx_exit_on_error(&stream->decoder,
"Failed to get decoder reference frame");
1899 if (!compare_img(&enc_img, &dec_img)) {
1900 int y[4], u[4], v[4];
1901 find_mismatch(&enc_img, &dec_img, y, u, v);
1902 stream->decoder.err = 1;
1903 warn_or_exit_on_error(&stream->decoder, fatal == TEST_DECODE_FATAL,
1904 "Stream %d: Encode/decode mismatch on frame %d at"
1905 " Y[%d, %d] {%d/%d},"
1906 " U[%d, %d] {%d/%d},"
1907 " V[%d, %d] {%d/%d}",
1908 stream->index, stream->frames_out,
1909 y[0], y[1], y[2], y[3],
1910 u[0], u[1], u[2], u[3],
1911 v[0], v[1], v[2], v[3]);
1912 stream->mismatch_seen = stream->frames_out;
1920 static void print_time(
const char *label, int64_t etl) {
1921 int hours, mins, secs;
1925 etl -= hours * 3600;
1930 fprintf(stderr,
"[%3s %2d:%02d:%02d] ",
1931 label, hours, mins, secs);
1933 fprintf(stderr,
"[%3s unknown] ", label);
1937 int main(
int argc,
const char **argv_) {
1940 int frame_avail, got_data;
1942 struct input_state input = {0};
1943 struct global_config global;
1944 struct stream_state *streams = NULL;
1945 char **argv, **argi;
1946 uint64_t cx_time = 0;
1950 exec_name = argv_[0];
1956 input.framerate.num = 30;
1957 input.framerate.den = 1;
1959 input.only_i420 = 1;
1965 argv = argv_dup(argc - 1, argv_ + 1);
1966 parse_global_config(&global, argv);
1973 struct stream_state *stream = NULL;
1976 stream = new_stream(&global, stream);
1980 }
while (parse_stream_params(&global, stream, argv));
1984 for (argi = argv; *argi; argi++)
1985 if (argi[0][0] ==
'-' && argi[0][1])
1986 die(
"Error: Unrecognized option %s\n", *argi);
1996 if (global.codec->fourcc == VP9_FOURCC)
1997 input.only_i420 = 0;
2000 for (pass = global.pass ? global.pass - 1 : 0; pass < global.passes; pass++) {
2001 int frames_in = 0, seen_frames = 0;
2002 int64_t estimated_time_left = -1;
2003 int64_t average_rate = -1;
2004 off_t lagged_count = 0;
2006 open_input_file(&input);
2011 if (!input.w || !input.h)
2013 if (stream->config.cfg.g_w && stream->config.cfg.g_h) {
2014 input.w = stream->config.cfg.g_w;
2015 input.h = stream->config.cfg.g_h;
2021 if (!input.w || !input.h)
2022 fatal(
"Specify stream dimensions with --width (-w) "
2023 " and --height (-h)");
2024 FOREACH_STREAM(set_stream_dimensions(stream, input.w, input.h));
2025 FOREACH_STREAM(validate_stream_config(stream));
2030 if (global.pass && global.passes == 2)
2032 if (!stream->config.stats_fn)
2033 die(
"Stream %d: Must specify --fpf when --pass=%d"
2034 " and --passes=2\n", stream->index, global.pass);
2040 if (!global.have_framerate)
2041 global.framerate = input.framerate;
2043 FOREACH_STREAM(set_default_kf_interval(stream, &global));
2046 if (global.verbose && pass == 0)
2047 FOREACH_STREAM(show_stream_config(stream, &global, &input));
2049 if (pass == (global.pass ? global.pass - 1 : 0)) {
2050 if (input.file_type == FILE_TYPE_Y4M)
2054 memset(&raw, 0,
sizeof(raw));
2059 input.w, input.h, 32);
2061 FOREACH_STREAM(init_rate_histogram(&stream->rate_hist,
2062 &stream->config.cfg,
2063 &global.framerate));
2066 FOREACH_STREAM(setup_pass(stream, &global, pass));
2067 FOREACH_STREAM(open_output_file(stream, &global));
2068 FOREACH_STREAM(initialize_encoder(stream, &global));
2073 while (frame_avail || got_data) {
2074 struct vpx_usec_timer timer;
2076 if (!global.limit || frames_in < global.limit) {
2077 frame_avail = read_frame(&input, &raw);
2081 seen_frames = frames_in > global.skip_frames ?
2082 frames_in - global.skip_frames : 0;
2084 if (!global.quiet) {
2085 float fps = usec_to_fps(cx_time, seen_frames);
2086 fprintf(stderr,
"\rPass %d/%d ", pass + 1, global.passes);
2088 if (stream_cnt == 1)
2090 "frame %4d/%-4d %7"PRId64
"B ",
2091 frames_in, streams->frames_out, (int64_t)streams->nbytes);
2093 fprintf(stderr,
"frame %4d ", frames_in);
2095 fprintf(stderr,
"%7"PRId64
" %s %.2f %s ",
2096 cx_time > 9999999 ? cx_time / 1000 : cx_time,
2097 cx_time > 9999999 ?
"ms" :
"us",
2098 fps >= 1.0 ? fps : fps * 60,
2099 fps >= 1.0 ?
"fps" :
"fpm");
2100 print_time(
"ETA", estimated_time_left);
2101 fprintf(stderr,
"\033[K");
2107 if (frames_in > global.skip_frames) {
2108 vpx_usec_timer_start(&timer);
2109 FOREACH_STREAM(encode_frame(stream, &global,
2110 frame_avail ? &raw : NULL,
2112 vpx_usec_timer_mark(&timer);
2113 cx_time += vpx_usec_timer_elapsed(&timer);
2115 FOREACH_STREAM(update_quantizer_histogram(stream));
2118 FOREACH_STREAM(get_cx_data(stream, &global, &got_data));
2120 if (!got_data && input.length && !streams->frames_out) {
2121 lagged_count = global.limit ? seen_frames : ftello(input.file);
2122 }
else if (input.length) {
2127 int frame_in_lagged = (seen_frames - lagged_count) * 1000;
2129 rate = cx_time ? frame_in_lagged * (int64_t)1000000 / cx_time : 0;
2130 remaining = 1000 * (global.limit - global.skip_frames
2131 - seen_frames + lagged_count);
2133 off_t input_pos = ftello(input.file);
2134 off_t input_pos_lagged = input_pos - lagged_count;
2135 int64_t limit = input.length;
2137 rate = cx_time ? input_pos_lagged * (int64_t)1000000 / cx_time : 0;
2138 remaining = limit - input_pos + lagged_count;
2141 average_rate = (average_rate <= 0)
2143 : (average_rate * 7 + rate) / 8;
2144 estimated_time_left = average_rate ? remaining / average_rate : -1;
2147 if (got_data && global.test_decode != TEST_DECODE_OFF)
2148 FOREACH_STREAM(test_decode(stream, global.test_decode, global.codec));
2155 fprintf(stderr,
"\n");
2158 FOREACH_STREAM(fprintf(
2160 "\rPass %d/%d frame %4d/%-4d %7"PRId64
"B %7lub/f %7"PRId64
"b/s"
2161 " %7"PRId64
" %s (%.2f fps)\033[K\n", pass + 1,
2162 global.passes, frames_in, stream->frames_out, (int64_t)stream->nbytes,
2163 seen_frames ? (
unsigned long)(stream->nbytes * 8 / seen_frames) : 0,
2164 seen_frames ? (int64_t)stream->nbytes * 8
2165 * (int64_t)global.framerate.num / global.framerate.den
2168 stream->cx_time > 9999999 ? stream->cx_time / 1000 : stream->cx_time,
2169 stream->cx_time > 9999999 ?
"ms" :
"us",
2170 usec_to_fps(stream->cx_time, seen_frames));
2173 if (global.show_psnr)
2174 FOREACH_STREAM(show_psnr(stream));
2178 if (global.test_decode != TEST_DECODE_OFF) {
2182 close_input_file(&input);
2184 if (global.test_decode == TEST_DECODE_FATAL) {
2185 FOREACH_STREAM(res |= stream->mismatch_seen);
2187 FOREACH_STREAM(close_output_file(stream, global.codec->fourcc));
2189 FOREACH_STREAM(stats_close(&stream->stats, global.passes - 1));
2195 if (global.show_q_hist_buckets)
2196 FOREACH_STREAM(show_q_histogram(stream->counts,
2197 global.show_q_hist_buckets));
2199 if (global.show_rate_hist_buckets)
2200 FOREACH_STREAM(show_rate_histogram(&stream->rate_hist,
2201 &stream->config.cfg,
2202 global.show_rate_hist_buckets));
2203 FOREACH_STREAM(destroy_rate_histogram(&stream->rate_hist));
2205 #if CONFIG_INTERNAL_STATS
2209 if (!(global.pass == 1 && global.passes == 2))
2211 FILE *f = fopen(
"opsnr.stt",
"a");
2212 if (stream->mismatch_seen) {
2213 fprintf(f,
"First mismatch occurred in frame %d\n",
2214 stream->mismatch_seen);
2216 fprintf(f,
"No mismatch detected in recon buffers\n");
2225 return res ? EXIT_FAILURE : EXIT_SUCCESS;
Rational Number.
Definition: vpx_encoder.h:222
struct vpx_fixed_buf twopass_stats
Definition: vpx_encoder.h:200
struct vpx_codec_iface vpx_codec_iface_t
Codec interface structure.
Definition: vpx_codec.h:175
control function to set vp8 encoder cpuused
Definition: vp8cx.h:151
Definition: vpx_encoder.h:241
Image Descriptor.
Definition: vpx_image.h:99
Describes the decoder algorithm interface to applications.
Describes the encoder algorithm interface to applications.
const char * vpx_codec_iface_name(vpx_codec_iface_t *iface)
Return the name for a given interface.
Definition: vpx_image.h:55
const char * vpx_codec_err_to_string(vpx_codec_err_t err)
Convert error number to printable string.
struct vpx_rational g_timebase
Stream timebase units.
Definition: vpx_encoder.h:345
Definition: vpx_encoder.h:239
unsigned int rc_buf_sz
Decoder Buffer Size.
Definition: vpx_encoder.h:529
struct vpx_fixed_buf raw
Definition: vpx_encoder.h:206
int den
Definition: vpx_encoder.h:224
vpx_codec_err_t vpx_codec_encode(vpx_codec_ctx_t *ctx, const vpx_image_t *img, vpx_codec_pts_t pts, unsigned long duration, vpx_enc_frame_flags_t flags, unsigned long deadline)
Encode a frame.
Definition: vpx_encoder.h:170
Provides definitions for using the VP8 algorithm within the vpx Decoder interface.
Encoder configuration structure.
Definition: vpx_encoder.h:277
control function to set constrained quality level
Definition: vp8cx.h:174
Definition: vpx_encoder.h:171
#define VPX_PLANE_Y
Definition: vpx_image.h:116
Max data rate for Intra frames.
Definition: vp8cx.h:188
Encoder output packet.
Definition: vpx_encoder.h:181
void * buf
Definition: vpx_encoder.h:102
#define VPX_PLANE_V
Definition: vpx_image.h:118
Definition: vpx_encoder.h:231
Definition: vpx_encoder.h:232
unsigned int x_chroma_shift
Definition: vpx_image.h:111
unsigned int y_chroma_shift
Definition: vpx_image.h:112
struct vpx_codec_cx_pkt::@1::@2 frame
vpx_image_t * vpx_img_alloc(vpx_image_t *img, vpx_img_fmt_t fmt, unsigned int d_w, unsigned int d_h, unsigned int align)
Open a descriptor, allocating storage for the underlying image.
Definition: vpx_image.h:56
unsigned int d_w
Definition: vpx_image.h:107
#define vpx_codec_dec_init(ctx, iface, cfg, flags)
Convenience macro for vpx_codec_dec_init_ver()
Definition: vpx_decoder.h:154
unsigned int g_w
Width of the frame.
Definition: vpx_encoder.h:320
vpx_codec_err_t vpx_codec_decode(vpx_codec_ctx_t *ctx, const uint8_t *data, unsigned int data_sz, void *user_priv, long deadline)
Decode data.
unsigned int g_h
Height of the frame.
Definition: vpx_encoder.h:330
int stride[4]
Definition: vpx_image.h:128
enum vpx_codec_cx_pkt_kind kind
Definition: vpx_encoder.h:182
void vpx_img_free(vpx_image_t *img)
Close an image descriptor.
#define VPX_CODEC_USE_OUTPUT_PARTITION
Definition: vpx_encoder.h:92
vpx_img_fmt_t fmt
Definition: vpx_image.h:100
unsigned char * planes[4]
Definition: vpx_image.h:127
unsigned int rc_target_bitrate
Target data rate.
Definition: vpx_encoder.h:454
#define VPX_DL_REALTIME
Definition: vpx_encoder.h:804
int num
Definition: vpx_encoder.h:223
#define VPX_DL_BEST_QUALITY
Definition: vpx_encoder.h:810
vpx_codec_err_t vpx_codec_enc_config_default(vpx_codec_iface_t *iface, vpx_codec_enc_cfg_t *cfg, unsigned int usage)
Get a default configuration.
Definition: vpx_encoder.h:238
enum vpx_enc_pass g_pass
Multi-pass Encoding Mode.
Definition: vpx_encoder.h:362
double psnr[4]
Definition: vpx_encoder.h:204
#define VPX_CODEC_USE_PSNR
Initialization-time Feature Enabling.
Definition: vpx_encoder.h:91
#define VPX_DL_GOOD_QUALITY
Definition: vpx_encoder.h:807
const char * vpx_codec_error_detail(vpx_codec_ctx_t *ctx)
Retrieve detailed error information for codec context.
Provides definitions for using the VP8 encoder algorithm within the vpx Codec Interface.
#define VPX_PLANE_U
Definition: vpx_image.h:117
#define vpx_codec_enc_init(ctx, iface, cfg, flags)
Convenience macro for vpx_codec_enc_init_ver()
Definition: vpx_encoder.h:702
unsigned int h
Definition: vpx_image.h:104
vpx_codec_err_t
Algorithm return codes.
Definition: vpx_codec.h:89
const vpx_codec_cx_pkt_t * vpx_codec_get_cx_data(vpx_codec_ctx_t *ctx, vpx_codec_iter_t *iter)
Encoded data iterator.
union vpx_codec_cx_pkt::@1 data
VP9 specific reference frame data struct.
Definition: vp8.h:114
Definition: vpx_encoder.h:256
int64_t vpx_codec_pts_t
Time Stamp Type.
Definition: vpx_encoder.h:112
vpx_codec_err_t vpx_codec_control_(vpx_codec_ctx_t *ctx, int ctrl_id,...)
Control algorithm.
reference frame data struct
Definition: vp8.h:105
Definition: vpx_encoder.h:240
int idx
Definition: vp8.h:115
#define vpx_codec_control(ctx, id, data)
vpx_codec_control wrapper macro
Definition: vpx_codec.h:398
vpx_codec_err_t vpx_codec_destroy(vpx_codec_ctx_t *ctx)
Destroy a codec instance.
unsigned int d_h
Definition: vpx_image.h:108
size_t sz
Definition: vpx_encoder.h:103
unsigned int w
Definition: vpx_image.h:103
vpx_codec_err_t err
Definition: vpx_codec.h:204
const char * vpx_codec_error(vpx_codec_ctx_t *ctx)
Retrieve error synopsis for codec context.
const void * vpx_codec_iter_t
Iterator.
Definition: vpx_codec.h:190
Definition: vpx_encoder.h:169
#define VPX_FRAME_IS_FRAGMENT
Definition: vpx_encoder.h:132
Definition: vpx_encoder.h:230
Codec context structure.
Definition: vpx_codec.h:201