WebM VP8 Codec SDK
vpxenc
1 /*
2  * Copyright (c) 2010 The WebM project authors. All Rights Reserved.
3  *
4  * Use of this source code is governed by a BSD-style license
5  * that can be found in the LICENSE file in the root of the source
6  * tree. An additional intellectual property rights grant can be found
7  * in the file PATENTS. All contributing project authors may
8  * be found in the AUTHORS file in the root of the source tree.
9  */
10 
11 #include "./vpx_config.h"
12 
13 #if defined(_WIN32) || defined(__OS2__) || !CONFIG_OS_SUPPORT
14 #define USE_POSIX_MMAP 0
15 #else
16 #define USE_POSIX_MMAP 1
17 #endif
18 
19 #include <math.h>
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <stdarg.h>
23 #include <string.h>
24 #include <limits.h>
25 #include <assert.h>
26 #include "vpx/vpx_encoder.h"
27 #if CONFIG_DECODERS
28 #include "vpx/vpx_decoder.h"
29 #endif
30 #if USE_POSIX_MMAP
31 #include <sys/types.h>
32 #include <sys/stat.h>
33 #include <sys/mman.h>
34 #include <fcntl.h>
35 #include <unistd.h>
36 #endif
37 
38 #include "third_party/libyuv/include/libyuv/scale.h"
39 
40 #if CONFIG_VP8_ENCODER || CONFIG_VP9_ENCODER
41 #include "vpx/vp8cx.h"
42 #endif
43 #if CONFIG_VP8_DECODER || CONFIG_VP9_DECODER
44 #include "vpx/vp8dx.h"
45 #endif
46 
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"
53 
54 /* Swallow warnings about unused results of fread/fwrite */
55 static size_t wrap_fread(void *ptr, size_t size, size_t nmemb,
56  FILE *stream) {
57  return fread(ptr, size, nmemb, stream);
58 }
59 #define fread wrap_fread
60 
61 static size_t wrap_fwrite(const void *ptr, size_t size, size_t nmemb,
62  FILE *stream) {
63  return fwrite(ptr, size, nmemb, stream);
64 }
65 #define fwrite wrap_fwrite
66 
67 
68 static const char *exec_name;
69 
70 static const struct codec_item {
71  char const *name;
72  const vpx_codec_iface_t *(*iface)(void);
73  const vpx_codec_iface_t *(*dx_iface)(void);
74  unsigned int fourcc;
75 } codecs[] = {
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},
80 #endif
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},
85 #endif
86 };
87 
88 static void warn_or_exit_on_errorv(vpx_codec_ctx_t *ctx, int fatal,
89  const char *s, va_list ap) {
90  if (ctx->err) {
91  const char *detail = vpx_codec_error_detail(ctx);
92 
93  vfprintf(stderr, s, ap);
94  fprintf(stderr, ": %s\n", vpx_codec_error(ctx));
95 
96  if (detail)
97  fprintf(stderr, " %s\n", detail);
98 
99  if (fatal)
100  exit(EXIT_FAILURE);
101  }
102 }
103 
104 static void ctx_exit_on_error(vpx_codec_ctx_t *ctx, const char *s, ...) {
105  va_list ap;
106 
107  va_start(ap, s);
108  warn_or_exit_on_errorv(ctx, 1, s, ap);
109  va_end(ap);
110 }
111 
112 static void warn_or_exit_on_error(vpx_codec_ctx_t *ctx, int fatal,
113  const char *s, ...) {
114  va_list ap;
115 
116  va_start(ap, s);
117  warn_or_exit_on_errorv(ctx, fatal, s, ap);
118  va_end(ap);
119 }
120 
121 enum video_file_type {
122  FILE_TYPE_RAW,
123  FILE_TYPE_IVF,
124  FILE_TYPE_Y4M
125 };
126 
127 struct detect_buffer {
128  char buf[4];
129  size_t buf_read;
130  size_t position;
131 };
132 
133 
134 struct input_state {
135  char *fn;
136  FILE *file;
137  off_t length;
138  y4m_input y4m;
139  struct detect_buffer detect;
140  enum video_file_type file_type;
141  unsigned int w;
142  unsigned int h;
143  struct vpx_rational framerate;
144  int use_i420;
145  int only_i420;
146 };
147 
148 #define IVF_FRAME_HDR_SZ (4+8) /* 4 byte size + 8 byte timestamp */
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;
154  int plane = 0;
155  int shortread = 0;
156 
157  if (file_type == FILE_TYPE_Y4M) {
158  if (y4m_input_fetch_frame(y4m, f, img) < 1)
159  return 0;
160  } else {
161  if (file_type == FILE_TYPE_IVF) {
162  char junk[IVF_FRAME_HDR_SZ];
163 
164  /* Skip the frame header. We know how big the frame should be. See
165  * write_ivf_frame_header() for documentation on the frame header
166  * layout.
167  */
168  (void) fread(junk, 1, IVF_FRAME_HDR_SZ, f);
169  }
170 
171  for (plane = 0; plane < 3; plane++) {
172  unsigned char *ptr;
173  int w = (plane ? (1 + img->d_w) / 2 : img->d_w);
174  int h = (plane ? (1 + img->d_h) / 2 : img->d_h);
175  int r;
176 
177  /* Determine the correct plane based on the image format. The for-loop
178  * always counts in Y,U,V order, but this may not match the order of
179  * the data on disk.
180  */
181  switch (plane) {
182  case 1:
183  ptr = img->planes[img->fmt == VPX_IMG_FMT_YV12 ? VPX_PLANE_V : VPX_PLANE_U];
184  break;
185  case 2:
186  ptr = img->planes[img->fmt == VPX_IMG_FMT_YV12 ? VPX_PLANE_U : VPX_PLANE_V];
187  break;
188  default:
189  ptr = img->planes[plane];
190  }
191 
192  for (r = 0; r < h; r++) {
193  size_t needed = w;
194  size_t buf_position = 0;
195  const size_t left = detect->buf_read - detect->position;
196  if (left > 0) {
197  const size_t more = (left < needed) ? left : needed;
198  memcpy(ptr, detect->buf + detect->position, more);
199  buf_position = more;
200  needed -= more;
201  detect->position += more;
202  }
203  if (needed > 0) {
204  shortread |= (fread(ptr + buf_position, 1, needed, f) < needed);
205  }
206 
207  ptr += img->stride[plane];
208  }
209  }
210  }
211 
212  return !shortread;
213 }
214 
215 
216 unsigned int file_is_y4m(FILE *infile,
217  y4m_input *y4m,
218  char detect[4]) {
219  if (memcmp(detect, "YUV4", 4) == 0) {
220  return 1;
221  }
222  return 0;
223 }
224 
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];
229  int is_ivf = 0;
230  FILE *infile = input->file;
231  unsigned int *width = &input->w;
232  unsigned int *height = &input->h;
233  struct detect_buffer *detect = &input->detect;
234 
235  if (memcmp(detect->buf, "DKIF", 4) != 0)
236  return 0;
237 
238  /* See write_ivf_file_header() for more documentation on the file header
239  * layout.
240  */
241  if (fread(raw_hdr + 4, 1, IVF_FILE_HDR_SZ - 4, infile)
242  == IVF_FILE_HDR_SZ - 4) {
243  {
244  is_ivf = 1;
245 
246  if (mem_get_le16(raw_hdr + 4) != 0)
247  warn("Unrecognized IVF version! This file may not decode "
248  "properly.");
249 
250  *fourcc = mem_get_le32(raw_hdr + 8);
251  }
252  }
253 
254  if (is_ivf) {
255  *width = mem_get_le16(raw_hdr + 12);
256  *height = mem_get_le16(raw_hdr + 14);
257  detect->position = 4;
258  }
259 
260  return is_ivf;
261 }
262 
263 
264 static void write_ivf_file_header(FILE *outfile,
265  const vpx_codec_enc_cfg_t *cfg,
266  unsigned int fourcc,
267  int frame_cnt) {
268  char header[32];
269 
270  if (cfg->g_pass != VPX_RC_ONE_PASS && cfg->g_pass != VPX_RC_LAST_PASS)
271  return;
272 
273  header[0] = 'D';
274  header[1] = 'K';
275  header[2] = 'I';
276  header[3] = 'F';
277  mem_put_le16(header + 4, 0); /* version */
278  mem_put_le16(header + 6, 32); /* headersize */
279  mem_put_le32(header + 8, fourcc); /* headersize */
280  mem_put_le16(header + 12, cfg->g_w); /* width */
281  mem_put_le16(header + 14, cfg->g_h); /* height */
282  mem_put_le32(header + 16, cfg->g_timebase.den); /* rate */
283  mem_put_le32(header + 20, cfg->g_timebase.num); /* scale */
284  mem_put_le32(header + 24, frame_cnt); /* length */
285  mem_put_le32(header + 28, 0); /* unused */
286 
287  (void) fwrite(header, 1, 32, outfile);
288 }
289 
290 
291 static void write_ivf_frame_header(FILE *outfile,
292  const vpx_codec_cx_pkt_t *pkt) {
293  char header[12];
294  vpx_codec_pts_t pts;
295 
296  if (pkt->kind != VPX_CODEC_CX_FRAME_PKT)
297  return;
298 
299  pts = pkt->data.frame.pts;
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);
303 
304  (void) fwrite(header, 1, 12, outfile);
305 }
306 
307 static void write_ivf_frame_size(FILE *outfile, size_t size) {
308  char header[4];
309  mem_put_le32(header, (int)size);
310  (void) fwrite(header, 1, 4, outfile);
311 }
312 
313 
314 
315 /* Murmur hash derived from public domain reference implementation at
316  * http:// sites.google.com/site/murmurhash/
317  */
318 static unsigned int murmur(const void *key, int len, unsigned int seed) {
319  const unsigned int m = 0x5bd1e995;
320  const int r = 24;
321 
322  unsigned int h = seed ^ len;
323 
324  const unsigned char *data = (const unsigned char *)key;
325 
326  while (len >= 4) {
327  unsigned int k;
328 
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;
333 
334  k *= m;
335  k ^= k >> r;
336  k *= m;
337 
338  h *= m;
339  h ^= k;
340 
341  data += 4;
342  len -= 4;
343  }
344 
345  switch (len) {
346  case 3:
347  h ^= data[2] << 16;
348  case 2:
349  h ^= data[1] << 8;
350  case 1:
351  h ^= data[0];
352  h *= m;
353  };
354 
355  h ^= h >> 13;
356  h *= m;
357  h ^= h >> 15;
358 
359  return h;
360 }
361 
362 
363 #include "args.h"
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,
367  "Output filename");
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,
373  "Codec to use");
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 {
399  TEST_DECODE_OFF,
400  TEST_DECODE_FATAL,
401  TEST_DECODE_WARN,
402 };
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},
407  {NULL, 0}
408 };
409 static const arg_def_t recontest = ARG_DEF_ENUM(NULL, "test-decode", 1,
410  "Test encode/decode mismatch",
411  test_decode_enum);
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[] = {
423  &debugmode,
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,
427  NULL
428 };
429 
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,
437  "Frame width");
438 static const arg_def_t height = ARG_DEF("h", "height", 1,
439  "Frame height");
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},
446  {NULL, 0}
447 };
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");
456 
457 static const arg_def_t *global_args[] = {
458  &use_yv12, &use_i420, &usage, &threads, &profile,
459  &width, &height, &stereo_mode, &timebase, &framerate,
460  &error_resilient,
461  &lag_in_frames, NULL
462 };
463 
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[] = {
473  {"vbr", VPX_VBR},
474  {"cbr", VPX_CBR},
475  {"cq", VPX_CQ},
476  {"q", VPX_Q},
477  {NULL, 0}
478 };
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,
482  "Bitrate (kbps)");
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,
501  NULL
502 };
503 
504 
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
513 };
514 
515 
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
524 };
525 
526 
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,
546  "AltRef Strength");
547 static const arg_def_t arnr_type = ARG_DEF(NULL, "arnr-type", 1,
548  "AltRef Type");
549 static const struct arg_enum_list tuning_enum[] = {
550  {"psnr", VP8_TUNE_PSNR},
551  {"ssim", VP8_TUNE_SSIM},
552  {NULL, 0}
553 };
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(
565  NULL, "aq-mode", 1,
566  "Adaptive quantization mode (0: disabled (by default), 1: variance based)");
567 #endif
568 
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,
574  NULL
575 };
576 static const int vp8_arg_ctrl_map[] = {
582  0
583 };
584 #endif
585 
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,
592  NULL
593 };
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,
601  0
602 };
603 #endif
604 
605 static const arg_def_t *no_args[] = { NULL };
606 
607 void usage_exit() {
608  int i;
609 
610  fprintf(stderr, "Usage: %s <options> -o dst_filename src_filename \n",
611  exec_name);
612 
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);
626 #endif
627 #if CONFIG_VP9_ENCODER
628  fprintf(stderr, "\nVP9 Specific Options:\n");
629  arg_show_usage(stderr, vp9_args);
630 #endif
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");
634  fprintf(stderr, "\n"
635  "Included encoders:\n"
636  "\n");
637 
638  for (i = 0; i < sizeof(codecs) / sizeof(codecs[0]); i++)
639  fprintf(stderr, " %-6s - %s\n",
640  codecs[i].name,
641  vpx_codec_iface_name(codecs[i].iface()));
642 
643  exit(EXIT_FAILURE);
644 }
645 
646 
647 #define HIST_BAR_MAX 40
648 struct hist_bucket {
649  int low, high, count;
650 };
651 
652 
653 static int merge_hist_buckets(struct hist_bucket *bucket,
654  int *buckets_,
655  int max_buckets) {
656  int small_bucket = 0, merge_bucket = INT_MAX, big_bucket = 0;
657  int buckets = *buckets_;
658  int i;
659 
660  /* Find the extrema for this list of buckets */
661  big_bucket = small_bucket = 0;
662  for (i = 0; i < buckets; i++) {
663  if (bucket[i].count < bucket[small_bucket].count)
664  small_bucket = i;
665  if (bucket[i].count > bucket[big_bucket].count)
666  big_bucket = i;
667  }
668 
669  /* If we have too many buckets, merge the smallest with an adjacent
670  * bucket.
671  */
672  while (buckets > max_buckets) {
673  int last_bucket = buckets - 1;
674 
675  /* merge the small bucket with an adjacent one. */
676  if (small_bucket == 0)
677  merge_bucket = 1;
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;
682  else
683  merge_bucket = small_bucket + 1;
684 
685  assert(abs(merge_bucket - small_bucket) <= 1);
686  assert(small_bucket < buckets);
687  assert(big_bucket < buckets);
688  assert(merge_bucket < buckets);
689 
690  if (merge_bucket < small_bucket) {
691  bucket[merge_bucket].high = bucket[small_bucket].high;
692  bucket[merge_bucket].count += bucket[small_bucket].count;
693  } else {
694  bucket[small_bucket].high = bucket[merge_bucket].high;
695  bucket[small_bucket].count += bucket[merge_bucket].count;
696  merge_bucket = small_bucket;
697  }
698 
699  assert(bucket[merge_bucket].low != bucket[merge_bucket].high);
700 
701  buckets--;
702 
703  /* Remove the merge_bucket from the list, and find the new small
704  * and big buckets while we're at it
705  */
706  big_bucket = small_bucket = 0;
707  for (i = 0; i < buckets; i++) {
708  if (i > merge_bucket)
709  bucket[i] = bucket[i + 1];
710 
711  if (bucket[i].count < bucket[small_bucket].count)
712  small_bucket = i;
713  if (bucket[i].count > bucket[big_bucket].count)
714  big_bucket = i;
715  }
716 
717  }
718 
719  *buckets_ = buckets;
720  return bucket[big_bucket].count;
721 }
722 
723 
724 static void show_histogram(const struct hist_bucket *bucket,
725  int buckets,
726  int total,
727  int scale) {
728  const char *pat1, *pat2;
729  int i;
730 
731  switch ((int)(log(bucket[buckets - 1].high) / log(10)) + 1) {
732  case 1:
733  case 2:
734  pat1 = "%4d %2s: ";
735  pat2 = "%4d-%2d: ";
736  break;
737  case 3:
738  pat1 = "%5d %3s: ";
739  pat2 = "%5d-%3d: ";
740  break;
741  case 4:
742  pat1 = "%6d %4s: ";
743  pat2 = "%6d-%4d: ";
744  break;
745  case 5:
746  pat1 = "%7d %5s: ";
747  pat2 = "%7d-%5d: ";
748  break;
749  case 6:
750  pat1 = "%8d %6s: ";
751  pat2 = "%8d-%6d: ";
752  break;
753  case 7:
754  pat1 = "%9d %7s: ";
755  pat2 = "%9d-%7d: ";
756  break;
757  default:
758  pat1 = "%12d %10s: ";
759  pat2 = "%12d-%10d: ";
760  break;
761  }
762 
763  for (i = 0; i < buckets; i++) {
764  int len;
765  int j;
766  float pct;
767 
768  pct = (float)(100.0 * bucket[i].count / total);
769  len = HIST_BAR_MAX * bucket[i].count / scale;
770  if (len < 1)
771  len = 1;
772  assert(len <= HIST_BAR_MAX);
773 
774  if (bucket[i].low == bucket[i].high)
775  fprintf(stderr, pat1, bucket[i].low, "");
776  else
777  fprintf(stderr, pat2, bucket[i].low, bucket[i].high);
778 
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);
782  }
783 }
784 
785 
786 static void show_q_histogram(const int counts[64], int max_buckets) {
787  struct hist_bucket bucket[64];
788  int buckets = 0;
789  int total = 0;
790  int scale;
791  int i;
792 
793 
794  for (i = 0; i < 64; i++) {
795  if (counts[i]) {
796  bucket[buckets].low = bucket[buckets].high = i;
797  bucket[buckets].count = counts[i];
798  buckets++;
799  total += counts[i];
800  }
801  }
802 
803  fprintf(stderr, "\nQuantizer Selection:\n");
804  scale = merge_hist_buckets(bucket, &buckets, max_buckets);
805  show_histogram(bucket, buckets, total, scale);
806 }
807 
808 
809 #define RATE_BINS (100)
810 struct rate_hist {
811  int64_t *pts;
812  int *sz;
813  int samples;
814  int frames;
815  struct hist_bucket bucket[RATE_BINS];
816  int total;
817 };
818 
819 
820 static void init_rate_histogram(struct rate_hist *hist,
821  const vpx_codec_enc_cfg_t *cfg,
822  const vpx_rational_t *fps) {
823  int i;
824 
825  /* Determine the number of samples in the buffer. Use the file's framerate
826  * to determine the number of frames in rc_buf_sz milliseconds, with an
827  * adjustment (5/4) to account for alt-refs
828  */
829  hist->samples = cfg->rc_buf_sz * 5 / 4 * fps->num / fps->den / 1000;
830 
831  /* prevent division by zero */
832  if (hist->samples == 0)
833  hist->samples = 1;
834 
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;
841  }
842 }
843 
844 
845 static void destroy_rate_histogram(struct rate_hist *hist) {
846  free(hist->pts);
847  free(hist->sz);
848 }
849 
850 
851 static void update_rate_histogram(struct rate_hist *hist,
852  const vpx_codec_enc_cfg_t *cfg,
853  const vpx_codec_cx_pkt_t *pkt) {
854  int i, idx;
855  int64_t now, then, sum_sz = 0, avg_bitrate;
856 
857  now = pkt->data.frame.pts * 1000
858  * (uint64_t)cfg->g_timebase.num / (uint64_t)cfg->g_timebase.den;
859 
860  idx = hist->frames++ % hist->samples;
861  hist->pts[idx] = now;
862  hist->sz[idx] = (int)pkt->data.frame.sz;
863 
864  if (now < cfg->rc_buf_initial_sz)
865  return;
866 
867  then = now;
868 
869  /* Sum the size over the past rc_buf_sz ms */
870  for (i = hist->frames; i > 0 && hist->frames - i < hist->samples; i--) {
871  int i_idx = (i - 1) % hist->samples;
872 
873  then = hist->pts[i_idx];
874  if (now - then > cfg->rc_buf_sz)
875  break;
876  sum_sz += hist->sz[i_idx];
877  }
878 
879  if (now == then)
880  return;
881 
882  avg_bitrate = sum_sz * 8 * 1000 / (now - then);
883  idx = (int)(avg_bitrate * (RATE_BINS / 2) / (cfg->rc_target_bitrate * 1000));
884  if (idx < 0)
885  idx = 0;
886  if (idx > RATE_BINS - 1)
887  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++;
893  hist->total++;
894 }
895 
896 
897 static void show_rate_histogram(struct rate_hist *hist,
898  const vpx_codec_enc_cfg_t *cfg,
899  int max_buckets) {
900  int i, scale;
901  int buckets = 0;
902 
903  for (i = 0; i < RATE_BINS; i++) {
904  if (hist->bucket[i].low == INT_MAX)
905  continue;
906  hist->bucket[buckets++] = hist->bucket[i];
907  }
908 
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);
912 }
913 
914 #define mmin(a, b) ((a) < (b) ? (a) : (b))
915 static void find_mismatch(vpx_image_t *img1, vpx_image_t *img2,
916  int yloc[4], int uloc[4], int vloc[4]) {
917  const unsigned int bsize = 64;
918  const unsigned int bsizey = bsize >> img1->y_chroma_shift;
919  const unsigned int bsizex = bsize >> img1->x_chroma_shift;
920  const int c_w = (img1->d_w + img1->x_chroma_shift) >> img1->x_chroma_shift;
921  const int c_h = (img1->d_h + img1->y_chroma_shift) >> img1->y_chroma_shift;
922  unsigned int match = 1;
923  unsigned int i, j;
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) {
927  int k, l;
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)) {
936  yloc[0] = i + k;
937  yloc[1] = j + l;
938  yloc[2] = *(img1->planes[VPX_PLANE_Y] +
939  (i + k) * img1->stride[VPX_PLANE_Y] + j + l);
940  yloc[3] = *(img2->planes[VPX_PLANE_Y] +
941  (i + k) * img2->stride[VPX_PLANE_Y] + j + l);
942  match = 0;
943  break;
944  }
945  }
946  }
947  }
948 
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) {
952  int k, l;
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)) {
961  uloc[0] = i + k;
962  uloc[1] = j + l;
963  uloc[2] = *(img1->planes[VPX_PLANE_U] +
964  (i + k) * img1->stride[VPX_PLANE_U] + j + l);
965  uloc[3] = *(img2->planes[VPX_PLANE_U] +
966  (i + k) * img2->stride[VPX_PLANE_V] + j + l);
967  match = 0;
968  break;
969  }
970  }
971  }
972  }
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) {
976  int k, l;
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++) {
981  if (*(img1->planes[VPX_PLANE_V] +
982  (i + k) * img1->stride[VPX_PLANE_V] + j + l) !=
983  *(img2->planes[VPX_PLANE_V] +
984  (i + k) * img2->stride[VPX_PLANE_V] + j + l)) {
985  vloc[0] = i + k;
986  vloc[1] = j + l;
987  vloc[2] = *(img1->planes[VPX_PLANE_V] +
988  (i + k) * img1->stride[VPX_PLANE_V] + j + l);
989  vloc[3] = *(img2->planes[VPX_PLANE_V] +
990  (i + k) * img2->stride[VPX_PLANE_V] + j + l);
991  match = 0;
992  break;
993  }
994  }
995  }
996  }
997 }
998 
999 static int compare_img(vpx_image_t *img1, vpx_image_t *img2)
1000 {
1001  const int c_w = (img1->d_w + img1->x_chroma_shift) >> img1->x_chroma_shift;
1002  const int c_h = (img1->d_h + img1->y_chroma_shift) >> img1->y_chroma_shift;
1003  int match = 1;
1004  unsigned int i;
1005 
1006  match &= (img1->fmt == img2->fmt);
1007  match &= (img1->w == img2->w);
1008  match &= (img1->h == img2->h);
1009 
1010  for (i = 0; i < img1->d_h; i++)
1011  match &= (memcmp(img1->planes[VPX_PLANE_Y]+i*img1->stride[VPX_PLANE_Y],
1012  img2->planes[VPX_PLANE_Y]+i*img2->stride[VPX_PLANE_Y],
1013  img1->d_w) == 0);
1014 
1015  for (i = 0; i < c_h; i++)
1016  match &= (memcmp(img1->planes[VPX_PLANE_U]+i*img1->stride[VPX_PLANE_U],
1017  img2->planes[VPX_PLANE_U]+i*img2->stride[VPX_PLANE_U],
1018  c_w) == 0);
1019 
1020  for (i = 0; i < c_h; i++)
1021  match &= (memcmp(img1->planes[VPX_PLANE_V]+i*img1->stride[VPX_PLANE_U],
1022  img2->planes[VPX_PLANE_V]+i*img2->stride[VPX_PLANE_U],
1023  c_w) == 0);
1024 
1025  return match;
1026 }
1027 
1028 
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)
1035 #else
1036 #define ARG_CTRL_CNT_MAX MAX(NELEMENTS(vp8_arg_ctrl_map), \
1037  NELEMENTS(vp9_arg_ctrl_map))
1038 #endif
1039 
1040 /* Configuration elements common to all streams */
1041 struct global_config {
1042  const struct codec_item *codec;
1043  int passes;
1044  int pass;
1045  int usage;
1046  int deadline;
1047  int use_i420;
1048  int quiet;
1049  int verbose;
1050  int limit;
1051  int skip_frames;
1052  int show_psnr;
1053  enum TestDecodeFatality test_decode;
1054  int have_framerate;
1055  struct vpx_rational framerate;
1056  int out_part;
1057  int debug;
1058  int show_q_hist_buckets;
1059  int show_rate_hist_buckets;
1060 };
1061 
1062 
1063 /* Per-stream configuration */
1064 struct stream_config {
1065  struct vpx_codec_enc_cfg cfg;
1066  const char *out_fn;
1067  const char *stats_fn;
1068  stereo_format_t stereo_fmt;
1069  int arg_ctrls[ARG_CTRL_CNT_MAX][2];
1070  int arg_ctrl_cnt;
1071  int write_webm;
1072  int have_kf_max_dist;
1073 };
1074 
1075 
1076 struct stream_state {
1077  int index;
1078  struct stream_state *next;
1079  struct stream_config config;
1080  FILE *file;
1081  struct rate_hist rate_hist;
1082  struct EbmlGlobal ebml;
1083  uint32_t hash;
1084  uint64_t psnr_sse_total;
1085  uint64_t psnr_samples_total;
1086  double psnr_totals[4];
1087  int psnr_count;
1088  int counts[64];
1089  vpx_codec_ctx_t encoder;
1090  unsigned int frames_out;
1091  uint64_t cx_time;
1092  size_t nbytes;
1093  stats_io_t stats;
1094  struct vpx_image *img;
1095  vpx_codec_ctx_t decoder;
1096  int mismatch_seen;
1097 };
1098 
1099 
1100 void validate_positive_rational(const char *msg,
1101  struct vpx_rational *rat) {
1102  if (rat->den < 0) {
1103  rat->num *= -1;
1104  rat->den *= -1;
1105  }
1106 
1107  if (rat->num < 0)
1108  die("Error: %s must be positive\n", msg);
1109 
1110  if (!rat->den)
1111  die("Error: %s has zero denominator\n", msg);
1112 }
1113 
1114 
1115 static void parse_global_config(struct global_config *global, char **argv) {
1116  char **argi, **argj;
1117  struct arg arg;
1118 
1119  /* Initialize default parameters */
1120  memset(global, 0, sizeof(*global));
1121  global->codec = codecs;
1122  global->passes = 0;
1123  global->use_i420 = 1;
1124  /* Assign default deadline to good quality */
1125  global->deadline = VPX_DL_GOOD_QUALITY;
1126 
1127  for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step) {
1128  arg.argv_step = 1;
1129 
1130  if (arg_match(&arg, &codecarg, argi)) {
1131  int j, k = -1;
1132 
1133  for (j = 0; j < sizeof(codecs) / sizeof(codecs[0]); j++)
1134  if (!strcmp(codecs[j].name, arg.val))
1135  k = j;
1136 
1137  if (k >= 0)
1138  global->codec = codecs + k;
1139  else
1140  die("Error: Unrecognized argument (%s) to --codec\n",
1141  arg.val);
1142 
1143  } else if (arg_match(&arg, &passes, argi)) {
1144  global->passes = arg_parse_uint(&arg);
1145 
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);
1150 
1151  if (global->pass < 1 || global->pass > 2)
1152  die("Error: Invalid pass selected (%d)\n",
1153  global->pass);
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))
1159  global->deadline = VPX_DL_BEST_QUALITY;
1160  else if (arg_match(&arg, &good_dl, argi))
1161  global->deadline = VPX_DL_GOOD_QUALITY;
1162  else if (arg_match(&arg, &rt_dl, argi))
1163  global->deadline = VPX_DL_REALTIME;
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))
1169  global->quiet = 1;
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))
1187  global->debug = 1;
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);
1192  else
1193  argj++;
1194  }
1195 
1196  /* Validate global config */
1197  if (global->passes == 0) {
1198 #if CONFIG_VP9_ENCODER
1199  // Make default VP9 passes = 2 until there is a better quality 1-pass
1200  // encoder
1201  global->passes = (global->codec->iface == vpx_codec_vp9_cx ? 2 : 1);
1202 #else
1203  global->passes = 1;
1204 #endif
1205  }
1206 
1207  if (global->pass) {
1208  /* DWIM: Assume the user meant passes=2 if pass=2 is specified */
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;
1213  }
1214  }
1215 }
1216 
1217 
1218 void open_input_file(struct input_state *input) {
1219  unsigned int fourcc;
1220 
1221  /* Parse certain options from the input file, if possible */
1222  input->file = strcmp(input->fn, "-") ? fopen(input->fn, "rb")
1223  : set_binary_mode(stdin);
1224 
1225  if (!input->file)
1226  fatal("Failed to open input file");
1227 
1228  if (!fseeko(input->file, 0, SEEK_END)) {
1229  /* Input file is seekable. Figure out how long it is, so we can get
1230  * progress info.
1231  */
1232  input->length = ftello(input->file);
1233  rewind(input->file);
1234  }
1235 
1236  /* For RAW input sources, these bytes will applied on the first frame
1237  * in read_frame().
1238  */
1239  input->detect.buf_read = fread(input->detect.buf, 1, 4, input->file);
1240  input->detect.position = 0;
1241 
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;
1252  } else
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.");
1256  } else {
1257  input->file_type = FILE_TYPE_RAW;
1258  }
1259 }
1260 
1261 
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);
1266 }
1267 
1268 static struct stream_state *new_stream(struct global_config *global,
1269  struct stream_state *prev) {
1270  struct stream_state *stream;
1271 
1272  stream = calloc(1, sizeof(*stream));
1273  if (!stream)
1274  fatal("Failed to allocate new stream.");
1275  if (prev) {
1276  memcpy(stream, prev, sizeof(*stream));
1277  stream->index++;
1278  prev->next = stream;
1279  } else {
1280  vpx_codec_err_t res;
1281 
1282  /* Populate encoder configuration */
1283  res = vpx_codec_enc_config_default(global->codec->iface(),
1284  &stream->config.cfg,
1285  global->usage);
1286  if (res)
1287  fatal("Failed to get config: %s\n", vpx_codec_err_to_string(res));
1288 
1289  /* Change the default timebase to a high enough value so that the
1290  * encoder will always create strictly increasing timestamps.
1291  */
1292  stream->config.cfg.g_timebase.den = 1000;
1293 
1294  /* Never use the library's default resolution, require it be parsed
1295  * from the file or set on the command line.
1296  */
1297  stream->config.cfg.g_w = 0;
1298  stream->config.cfg.g_h = 0;
1299 
1300  /* Initialize remaining stream parameters */
1301  stream->config.stereo_fmt = STEREO_FORMAT_MONO;
1302  stream->config.write_webm = 1;
1303  stream->ebml.last_pts_ms = -1;
1304 
1305  /* Allows removal of the application version from the EBML tags */
1306  stream->ebml.debug = global->debug;
1307  }
1308 
1309  /* Output files must be specified for each stream */
1310  stream->config.out_fn = NULL;
1311 
1312  stream->next = NULL;
1313  return stream;
1314 }
1315 
1316 
1317 static int parse_stream_params(struct global_config *global,
1318  struct stream_state *stream,
1319  char **argv) {
1320  char **argi, **argj;
1321  struct arg arg;
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;
1326 
1327  /* Handle codec specific options */
1328  if (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;
1333 #endif
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;
1338 #endif
1339  }
1340 
1341  for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step) {
1342  arg.argv_step = 1;
1343 
1344  /* Once we've found an end-of-stream marker (--) we want to continue
1345  * shifting arguments but not consuming them.
1346  */
1347  if (eos_mark_found) {
1348  argj++;
1349  continue;
1350  } else if (!strcmp(*argj, "--")) {
1351  eos_mark_found = 1;
1352  continue;
1353  }
1354 
1355  if (0);
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);
1407 
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);
1412 
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);
1417 
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))
1426  config->cfg.kf_mode = VPX_KF_DISABLED;
1427  else {
1428  int i, match = 0;
1429 
1430  for (i = 0; ctrl_args[i]; i++) {
1431  if (arg_match(&arg, ctrl_args[i], argi)) {
1432  int j;
1433  match = 1;
1434 
1435  /* Point either to the next free element or the first
1436  * instance of this control.
1437  */
1438  for (j = 0; j < config->arg_ctrl_cnt; j++)
1439  if (config->arg_ctrls[j][0] == ctrl_args_map[i])
1440  break;
1441 
1442  /* Update/insert */
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++;
1449  }
1450 
1451  }
1452  }
1453 
1454  if (!match)
1455  argj++;
1456  }
1457  }
1458 
1459  return eos_mark_found;
1460 }
1461 
1462 
1463 #define FOREACH_STREAM(func)\
1464  do\
1465  {\
1466  struct stream_state *stream;\
1467  \
1468  for(stream = streams; stream; stream = stream->next)\
1469  func;\
1470  }while(0)
1471 
1472 
1473 static void validate_stream_config(struct stream_state *stream) {
1474  struct stream_state *streami;
1475 
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);
1479 
1480  for (streami = stream; streami; streami = streami->next) {
1481  /* All streams require output files */
1482  if (!streami->config.out_fn)
1483  fatal("Stream %d: Output file is required (specify with -o)",
1484  streami->index);
1485 
1486  /* Check for two streams outputting to the same file */
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);
1493  }
1494 
1495  /* Check for two streams sharing a stats file. */
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);
1502  }
1503  }
1504 }
1505 
1506 
1507 static void set_stream_dimensions(struct stream_state *stream,
1508  unsigned int w,
1509  unsigned int h) {
1510  if (!stream->config.cfg.g_w) {
1511  if (!stream->config.cfg.g_h)
1512  stream->config.cfg.g_w = w;
1513  else
1514  stream->config.cfg.g_w = w * stream->config.cfg.g_h / h;
1515  }
1516  if (!stream->config.cfg.g_h) {
1517  stream->config.cfg.g_h = h * stream->config.cfg.g_w / w;
1518  }
1519 }
1520 
1521 
1522 static void set_default_kf_interval(struct stream_state *stream,
1523  struct global_config *global) {
1524  /* Use a max keyframe interval of 5 seconds, if none was
1525  * specified on the command line.
1526  */
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);
1531  }
1532 }
1533 
1534 
1535 static void show_stream_config(struct stream_state *stream,
1536  struct global_config *global,
1537  struct input_state *input) {
1538 
1539 #define SHOW(field) \
1540  fprintf(stderr, " %-28s = %d\n", #field, stream->config.cfg.field)
1541 
1542  if (stream->index == 0) {
1543  fprintf(stderr, "Codec: %s\n",
1544  vpx_codec_iface_name(global->codec->iface()));
1545  fprintf(stderr, "Source file: %s Format: %s\n", input->fn,
1546  input->use_i420 ? "I420" : "YV12");
1547  }
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");
1552 
1553  SHOW(g_usage);
1554  SHOW(g_threads);
1555  SHOW(g_profile);
1556  SHOW(g_w);
1557  SHOW(g_h);
1558  SHOW(g_timebase.num);
1559  SHOW(g_timebase.den);
1560  SHOW(g_error_resilient);
1561  SHOW(g_pass);
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);
1567  SHOW(rc_end_usage);
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);
1573  SHOW(rc_buf_sz);
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);
1579  SHOW(kf_mode);
1580  SHOW(kf_min_dist);
1581  SHOW(kf_max_dist);
1582 }
1583 
1584 
1585 static void open_output_file(struct stream_state *stream,
1586  struct global_config *global) {
1587  const char *fn = stream->config.out_fn;
1588 
1589  stream->file = strcmp(fn, "-") ? fopen(fn, "wb") : set_binary_mode(stdout);
1590 
1591  if (!stream->file)
1592  fatal("Failed to open output file");
1593 
1594  if (stream->config.write_webm && fseek(stream->file, 0, SEEK_CUR))
1595  fatal("WebM output to pipes not supported.");
1596 
1597  if (stream->config.write_webm) {
1598  stream->ebml.stream = stream->file;
1599  write_webm_file_header(&stream->ebml, &stream->config.cfg,
1600  &global->framerate,
1601  stream->config.stereo_fmt,
1602  global->codec->fourcc);
1603  } else
1604  write_ivf_file_header(stream->file, &stream->config.cfg,
1605  global->codec->fourcc, 0);
1606 }
1607 
1608 
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;
1615  } else {
1616  if (!fseek(stream->file, 0, SEEK_SET))
1617  write_ivf_file_header(stream->file, &stream->config.cfg,
1618  fourcc,
1619  stream->frames_out);
1620  }
1621 
1622  fclose(stream->file);
1623 }
1624 
1625 
1626 static void setup_pass(struct stream_state *stream,
1627  struct global_config *global,
1628  int pass) {
1629  if (stream->config.stats_fn) {
1630  if (!stats_open_file(&stream->stats, stream->config.stats_fn,
1631  pass))
1632  fatal("Failed to open statistics store");
1633  } else {
1634  if (!stats_open_mem(&stream->stats, pass))
1635  fatal("Failed to open statistics store");
1636  }
1637 
1638  stream->config.cfg.g_pass = global->passes == 2
1640  : VPX_RC_ONE_PASS;
1641  if (pass)
1642  stream->config.cfg.rc_twopass_stats_in = stats_get(&stream->stats);
1643 
1644  stream->cx_time = 0;
1645  stream->nbytes = 0;
1646  stream->frames_out = 0;
1647 }
1648 
1649 
1650 static void initialize_encoder(struct stream_state *stream,
1651  struct global_config *global) {
1652  int i;
1653  int flags = 0;
1654 
1655  flags |= global->show_psnr ? VPX_CODEC_USE_PSNR : 0;
1656  flags |= global->out_part ? VPX_CODEC_USE_OUTPUT_PARTITION : 0;
1657 
1658  /* Construct Encoder Context */
1659  vpx_codec_enc_init(&stream->encoder, global->codec->iface(),
1660  &stream->config.cfg, flags);
1661  ctx_exit_on_error(&stream->encoder, "Failed to initialize encoder");
1662 
1663  /* Note that we bypass the vpx_codec_control wrapper macro because
1664  * we're being clever to store the control IDs in an array. Real
1665  * applications will want to make use of the enumerations directly
1666  */
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];
1670  if (vpx_codec_control_(&stream->encoder, ctrl, value))
1671  fprintf(stderr, "Error: Tried to set control %d = %d\n",
1672  ctrl, value);
1673 
1674  ctx_exit_on_error(&stream->encoder, "Failed to control codec");
1675  }
1676 
1677 #if CONFIG_DECODERS
1678  if (global->test_decode != TEST_DECODE_OFF) {
1679  vpx_codec_dec_init(&stream->decoder, global->codec->dx_iface(), NULL, 0);
1680  }
1681 #endif
1682 }
1683 
1684 
1685 static void encode_frame(struct stream_state *stream,
1686  struct global_config *global,
1687  struct vpx_image *img,
1688  unsigned int frames_in) {
1689  vpx_codec_pts_t frame_start, next_frame_start;
1690  struct vpx_codec_enc_cfg *cfg = &stream->config.cfg;
1691  struct vpx_usec_timer timer;
1692 
1693  frame_start = (cfg->g_timebase.den * (int64_t)(frames_in - 1)
1694  * global->framerate.den)
1695  / cfg->g_timebase.num / global->framerate.num;
1696  next_frame_start = (cfg->g_timebase.den * (int64_t)(frames_in)
1697  * global->framerate.den)
1698  / cfg->g_timebase.num / global->framerate.num;
1699 
1700  /* Scale if necessary */
1701  if (img && (img->d_w != cfg->g_w || img->d_h != cfg->g_h)) {
1702  if (!stream->img)
1703  stream->img = vpx_img_alloc(NULL, VPX_IMG_FMT_I420,
1704  cfg->g_w, cfg->g_h, 16);
1705  I420Scale(img->planes[VPX_PLANE_Y], img->stride[VPX_PLANE_Y],
1706  img->planes[VPX_PLANE_U], img->stride[VPX_PLANE_U],
1707  img->planes[VPX_PLANE_V], img->stride[VPX_PLANE_V],
1708  img->d_w, img->d_h,
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],
1713  stream->img->planes[VPX_PLANE_V],
1714  stream->img->stride[VPX_PLANE_V],
1715  stream->img->d_w, stream->img->d_h,
1716  kFilterBox);
1717 
1718  img = stream->img;
1719  }
1720 
1721  vpx_usec_timer_start(&timer);
1722  vpx_codec_encode(&stream->encoder, img, frame_start,
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",
1728  stream->index);
1729 }
1730 
1731 
1732 static void update_quantizer_histogram(struct stream_state *stream) {
1733  if (stream->config.cfg.g_pass != VPX_RC_FIRST_PASS) {
1734  int q;
1735 
1736  vpx_codec_control(&stream->encoder, VP8E_GET_LAST_QUANTIZER_64, &q);
1737  ctx_exit_on_error(&stream->encoder, "Failed to read quantizer");
1738  stream->counts[q]++;
1739  }
1740 }
1741 
1742 
1743 static void get_cx_data(struct stream_state *stream,
1744  struct global_config *global,
1745  int *got_data) {
1746  const vpx_codec_cx_pkt_t *pkt;
1747  const struct vpx_codec_enc_cfg *cfg = &stream->config.cfg;
1748  vpx_codec_iter_t iter = NULL;
1749 
1750  *got_data = 0;
1751  while ((pkt = vpx_codec_get_cx_data(&stream->encoder, &iter))) {
1752  static size_t fsize = 0;
1753  static off_t ivf_header_pos = 0;
1754 
1755  switch (pkt->kind) {
1757  if (!(pkt->data.frame.flags & VPX_FRAME_IS_FRAGMENT)) {
1758  stream->frames_out++;
1759  }
1760  if (!global->quiet)
1761  fprintf(stderr, " %6luF", (unsigned long)pkt->data.frame.sz);
1762 
1763  update_rate_histogram(&stream->rate_hist, cfg, pkt);
1764  if (stream->config.write_webm) {
1765  /* Update the hash */
1766  if (!stream->ebml.debug)
1767  stream->hash = murmur(pkt->data.frame.buf,
1768  (int)pkt->data.frame.sz,
1769  stream->hash);
1770 
1771  write_webm_block(&stream->ebml, cfg, pkt);
1772  } else {
1773  if (pkt->data.frame.partition_id <= 0) {
1774  ivf_header_pos = ftello(stream->file);
1775  fsize = pkt->data.frame.sz;
1776 
1777  write_ivf_frame_header(stream->file, pkt);
1778  } else {
1779  fsize += pkt->data.frame.sz;
1780 
1781  if (!(pkt->data.frame.flags & VPX_FRAME_IS_FRAGMENT)) {
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);
1786  }
1787  }
1788 
1789  (void) fwrite(pkt->data.frame.buf, 1, pkt->data.frame.sz,
1790  stream->file);
1791  }
1792  stream->nbytes += pkt->data.raw.sz;
1793 
1794  *got_data = 1;
1795 #if CONFIG_DECODERS
1796  if (global->test_decode != TEST_DECODE_OFF && !stream->mismatch_seen) {
1797  vpx_codec_decode(&stream->decoder, pkt->data.frame.buf,
1798  pkt->data.frame.sz, NULL, 0);
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;
1805  }
1806  }
1807 #endif
1808  break;
1809  case VPX_CODEC_STATS_PKT:
1810  stream->frames_out++;
1811  stats_write(&stream->stats,
1812  pkt->data.twopass_stats.buf,
1813  pkt->data.twopass_stats.sz);
1814  stream->nbytes += pkt->data.raw.sz;
1815  break;
1816  case VPX_CODEC_PSNR_PKT:
1817 
1818  if (global->show_psnr) {
1819  int i;
1820 
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++) {
1824  if (!global->quiet)
1825  fprintf(stderr, "%.3f ", pkt->data.psnr.psnr[i]);
1826  stream->psnr_totals[i] += pkt->data.psnr.psnr[i];
1827  }
1828  stream->psnr_count++;
1829  }
1830 
1831  break;
1832  default:
1833  break;
1834  }
1835  }
1836 }
1837 
1838 
1839 static void show_psnr(struct stream_state *stream) {
1840  int i;
1841  double ovpsnr;
1842 
1843  if (!stream->psnr_count)
1844  return;
1845 
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);
1850 
1851  for (i = 0; i < 4; i++) {
1852  fprintf(stderr, " %.3f", stream->psnr_totals[i] / stream->psnr_count);
1853  }
1854  fprintf(stderr, "\n");
1855 }
1856 
1857 
1858 static float usec_to_fps(uint64_t usec, unsigned int frames) {
1859  return (float)(usec > 0 ? frames * 1000000.0 / (float)usec : 0);
1860 }
1861 
1862 
1863 static void test_decode(struct stream_state *stream,
1864  enum TestDecodeFatality fatal,
1865  const struct codec_item *codec) {
1866  vpx_image_t enc_img, dec_img;
1867 
1868  if (stream->mismatch_seen)
1869  return;
1870 
1871  /* Get the internal reference frame */
1872  if (codec->fourcc == VP8_FOURCC) {
1873  struct vpx_ref_frame ref_enc, ref_dec;
1874  int width, height;
1875 
1876  width = (stream->config.cfg.g_w + 15) & ~15;
1877  height = (stream->config.cfg.g_h + 15) & ~15;
1878  vpx_img_alloc(&ref_enc.img, VPX_IMG_FMT_I420, width, height, 1);
1879  enc_img = ref_enc.img;
1880  vpx_img_alloc(&ref_dec.img, VPX_IMG_FMT_I420, width, height, 1);
1881  dec_img = ref_dec.img;
1882 
1883  ref_enc.frame_type = VP8_LAST_FRAME;
1884  ref_dec.frame_type = VP8_LAST_FRAME;
1885  vpx_codec_control(&stream->encoder, VP8_COPY_REFERENCE, &ref_enc);
1886  vpx_codec_control(&stream->decoder, VP8_COPY_REFERENCE, &ref_dec);
1887  } else {
1888  struct vp9_ref_frame ref;
1889 
1890  ref.idx = 0;
1891  vpx_codec_control(&stream->encoder, VP9_GET_REFERENCE, &ref);
1892  enc_img = ref.img;
1893  vpx_codec_control(&stream->decoder, VP9_GET_REFERENCE, &ref);
1894  dec_img = ref.img;
1895  }
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");
1898 
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;
1913  }
1914 
1915  vpx_img_free(&enc_img);
1916  vpx_img_free(&dec_img);
1917 }
1918 
1919 
1920 static void print_time(const char *label, int64_t etl) {
1921  int hours, mins, secs;
1922 
1923  if (etl >= 0) {
1924  hours = etl / 3600;
1925  etl -= hours * 3600;
1926  mins = etl / 60;
1927  etl -= mins * 60;
1928  secs = etl;
1929 
1930  fprintf(stderr, "[%3s %2d:%02d:%02d] ",
1931  label, hours, mins, secs);
1932  } else {
1933  fprintf(stderr, "[%3s unknown] ", label);
1934  }
1935 }
1936 
1937 int main(int argc, const char **argv_) {
1938  int pass;
1939  vpx_image_t raw;
1940  int frame_avail, got_data;
1941 
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;
1947  int stream_cnt = 0;
1948  int res = 0;
1949 
1950  exec_name = argv_[0];
1951 
1952  if (argc < 3)
1953  usage_exit();
1954 
1955  /* Setup default input stream settings */
1956  input.framerate.num = 30;
1957  input.framerate.den = 1;
1958  input.use_i420 = 1;
1959  input.only_i420 = 1;
1960 
1961  /* First parse the global configuration values, because we want to apply
1962  * other parameters on top of the default configuration provided by the
1963  * codec.
1964  */
1965  argv = argv_dup(argc - 1, argv_ + 1);
1966  parse_global_config(&global, argv);
1967 
1968  {
1969  /* Now parse each stream's parameters. Using a local scope here
1970  * due to the use of 'stream' as loop variable in FOREACH_STREAM
1971  * loops
1972  */
1973  struct stream_state *stream = NULL;
1974 
1975  do {
1976  stream = new_stream(&global, stream);
1977  stream_cnt++;
1978  if (!streams)
1979  streams = stream;
1980  } while (parse_stream_params(&global, stream, argv));
1981  }
1982 
1983  /* Check for unrecognized options */
1984  for (argi = argv; *argi; argi++)
1985  if (argi[0][0] == '-' && argi[0][1])
1986  die("Error: Unrecognized option %s\n", *argi);
1987 
1988  /* Handle non-option arguments */
1989  input.fn = argv[0];
1990 
1991  if (!input.fn)
1992  usage_exit();
1993 
1994 #if CONFIG_NON420
1995  /* Decide if other chroma subsamplings than 4:2:0 are supported */
1996  if (global.codec->fourcc == VP9_FOURCC)
1997  input.only_i420 = 0;
1998 #endif
1999 
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;
2005 
2006  open_input_file(&input);
2007 
2008  /* If the input file doesn't specify its w/h (raw files), try to get
2009  * the data from the first stream's configuration.
2010  */
2011  if (!input.w || !input.h)
2012  FOREACH_STREAM( {
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;
2016  break;
2017  }
2018  });
2019 
2020  /* Update stream configurations from the input file's parameters */
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));
2026 
2027  /* Ensure that --passes and --pass are consistent. If --pass is set and
2028  * --passes=2, ensure --fpf was set.
2029  */
2030  if (global.pass && global.passes == 2)
2031  FOREACH_STREAM( {
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);
2035  });
2036 
2037  /* Use the frame rate from the file only if none was specified
2038  * on the command-line.
2039  */
2040  if (!global.have_framerate)
2041  global.framerate = input.framerate;
2042 
2043  FOREACH_STREAM(set_default_kf_interval(stream, &global));
2044 
2045  /* Show configuration */
2046  if (global.verbose && pass == 0)
2047  FOREACH_STREAM(show_stream_config(stream, &global, &input));
2048 
2049  if (pass == (global.pass ? global.pass - 1 : 0)) {
2050  if (input.file_type == FILE_TYPE_Y4M)
2051  /*The Y4M reader does its own allocation.
2052  Just initialize this here to avoid problems if we never read any
2053  frames.*/
2054  memset(&raw, 0, sizeof(raw));
2055  else
2056  vpx_img_alloc(&raw,
2057  input.use_i420 ? VPX_IMG_FMT_I420
2058  : VPX_IMG_FMT_YV12,
2059  input.w, input.h, 32);
2060 
2061  FOREACH_STREAM(init_rate_histogram(&stream->rate_hist,
2062  &stream->config.cfg,
2063  &global.framerate));
2064  }
2065 
2066  FOREACH_STREAM(setup_pass(stream, &global, pass));
2067  FOREACH_STREAM(open_output_file(stream, &global));
2068  FOREACH_STREAM(initialize_encoder(stream, &global));
2069 
2070  frame_avail = 1;
2071  got_data = 0;
2072 
2073  while (frame_avail || got_data) {
2074  struct vpx_usec_timer timer;
2075 
2076  if (!global.limit || frames_in < global.limit) {
2077  frame_avail = read_frame(&input, &raw);
2078 
2079  if (frame_avail)
2080  frames_in++;
2081  seen_frames = frames_in > global.skip_frames ?
2082  frames_in - global.skip_frames : 0;
2083 
2084  if (!global.quiet) {
2085  float fps = usec_to_fps(cx_time, seen_frames);
2086  fprintf(stderr, "\rPass %d/%d ", pass + 1, global.passes);
2087 
2088  if (stream_cnt == 1)
2089  fprintf(stderr,
2090  "frame %4d/%-4d %7"PRId64"B ",
2091  frames_in, streams->frames_out, (int64_t)streams->nbytes);
2092  else
2093  fprintf(stderr, "frame %4d ", frames_in);
2094 
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");
2102  }
2103 
2104  } else
2105  frame_avail = 0;
2106 
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,
2111  frames_in));
2112  vpx_usec_timer_mark(&timer);
2113  cx_time += vpx_usec_timer_elapsed(&timer);
2114 
2115  FOREACH_STREAM(update_quantizer_histogram(stream));
2116 
2117  got_data = 0;
2118  FOREACH_STREAM(get_cx_data(stream, &global, &got_data));
2119 
2120  if (!got_data && input.length && !streams->frames_out) {
2121  lagged_count = global.limit ? seen_frames : ftello(input.file);
2122  } else if (input.length) {
2123  int64_t remaining;
2124  int64_t rate;
2125 
2126  if (global.limit) {
2127  int frame_in_lagged = (seen_frames - lagged_count) * 1000;
2128 
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);
2132  } else {
2133  off_t input_pos = ftello(input.file);
2134  off_t input_pos_lagged = input_pos - lagged_count;
2135  int64_t limit = input.length;
2136 
2137  rate = cx_time ? input_pos_lagged * (int64_t)1000000 / cx_time : 0;
2138  remaining = limit - input_pos + lagged_count;
2139  }
2140 
2141  average_rate = (average_rate <= 0)
2142  ? rate
2143  : (average_rate * 7 + rate) / 8;
2144  estimated_time_left = average_rate ? remaining / average_rate : -1;
2145  }
2146 
2147  if (got_data && global.test_decode != TEST_DECODE_OFF)
2148  FOREACH_STREAM(test_decode(stream, global.test_decode, global.codec));
2149  }
2150 
2151  fflush(stdout);
2152  }
2153 
2154  if (stream_cnt > 1)
2155  fprintf(stderr, "\n");
2156 
2157  if (!global.quiet)
2158  FOREACH_STREAM(fprintf(
2159  stderr,
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
2166  / seen_frames
2167  : 0,
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));
2171  );
2172 
2173  if (global.show_psnr)
2174  FOREACH_STREAM(show_psnr(stream));
2175 
2176  FOREACH_STREAM(vpx_codec_destroy(&stream->encoder));
2177 
2178  if (global.test_decode != TEST_DECODE_OFF) {
2179  FOREACH_STREAM(vpx_codec_destroy(&stream->decoder));
2180  }
2181 
2182  close_input_file(&input);
2183 
2184  if (global.test_decode == TEST_DECODE_FATAL) {
2185  FOREACH_STREAM(res |= stream->mismatch_seen);
2186  }
2187  FOREACH_STREAM(close_output_file(stream, global.codec->fourcc));
2188 
2189  FOREACH_STREAM(stats_close(&stream->stats, global.passes - 1));
2190 
2191  if (global.pass)
2192  break;
2193  }
2194 
2195  if (global.show_q_hist_buckets)
2196  FOREACH_STREAM(show_q_histogram(stream->counts,
2197  global.show_q_hist_buckets));
2198 
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));
2204 
2205 #if CONFIG_INTERNAL_STATS
2206  /* TODO(jkoleszar): This doesn't belong in this executable. Do it for now,
2207  * to match some existing utilities.
2208  */
2209  if (!(global.pass == 1 && global.passes == 2))
2210  FOREACH_STREAM({
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);
2215  } else {
2216  fprintf(f, "No mismatch detected in recon buffers\n");
2217  }
2218  fclose(f);
2219  });
2220 #endif
2221 
2222  vpx_img_free(&raw);
2223  free(argv);
2224  free(streams);
2225  return res ? EXIT_FAILURE : EXIT_SUCCESS;
2226 }
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
Definition: vp8cx.h:167
control function to set constrained quality level
Definition: vp8cx.h:174
Definition: vp8cx.h:166
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
Definition: vp8.h:46
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
Definition: vp8cx.h:160
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
Definition: vp8cx.h:156
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
Definition: vp8cx.h:153
#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
Definition: vp8cx.h:164
VP9 specific reference frame data struct.
Definition: vp8.h:114
Definition: vpx_encoder.h:256
Definition: vp8cx.h:165
int64_t vpx_codec_pts_t
Time Stamp Type.
Definition: vpx_encoder.h:112
Definition: vp8cx.h:152
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
Definition: vp8.h:57
Definition: vp8cx.h:155
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: vp8cx.h:154
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