]> granicus.if.org Git - libvpx/blob - vpxenc.c
Merge changes I58a5af33,Ied9b0392
[libvpx] / vpxenc.c
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 "./vpxenc.h"
12 #include "./vpx_config.h"
13
14 #include <assert.h>
15 #include <limits.h>
16 #include <math.h>
17 #include <stdarg.h>
18 #include <stdio.h>
19 #include <stdlib.h>
20 #include <string.h>
21
22 #include "vpx/vpx_encoder.h"
23 #if CONFIG_DECODERS
24 #include "vpx/vpx_decoder.h"
25 #endif
26
27 #include "third_party/libyuv/include/libyuv/scale.h"
28 #include "./args.h"
29 #include "./ivfenc.h"
30 #include "./tools_common.h"
31
32 #if CONFIG_VP8_ENCODER || CONFIG_VP9_ENCODER
33 #include "vpx/vp8cx.h"
34 #endif
35 #if CONFIG_VP8_DECODER || CONFIG_VP9_DECODER
36 #include "vpx/vp8dx.h"
37 #endif
38
39 #include "vpx/vpx_integer.h"
40 #include "vpx_ports/mem_ops.h"
41 #include "vpx_ports/vpx_timer.h"
42 #include "./rate_hist.h"
43 #include "./vpxstats.h"
44 #include "./warnings.h"
45 #if CONFIG_WEBM_IO
46 #include "./webmenc.h"
47 #endif
48 #include "./y4minput.h"
49
50 /* Swallow warnings about unused results of fread/fwrite */
51 static size_t wrap_fread(void *ptr, size_t size, size_t nmemb,
52                          FILE *stream) {
53   return fread(ptr, size, nmemb, stream);
54 }
55 #define fread wrap_fread
56
57 static size_t wrap_fwrite(const void *ptr, size_t size, size_t nmemb,
58                           FILE *stream) {
59   return fwrite(ptr, size, nmemb, stream);
60 }
61 #define fwrite wrap_fwrite
62
63
64 static const char *exec_name;
65
66 static void warn_or_exit_on_errorv(vpx_codec_ctx_t *ctx, int fatal,
67                                    const char *s, va_list ap) {
68   if (ctx->err) {
69     const char *detail = vpx_codec_error_detail(ctx);
70
71     vfprintf(stderr, s, ap);
72     fprintf(stderr, ": %s\n", vpx_codec_error(ctx));
73
74     if (detail)
75       fprintf(stderr, "    %s\n", detail);
76
77     if (fatal)
78       exit(EXIT_FAILURE);
79   }
80 }
81
82 static void ctx_exit_on_error(vpx_codec_ctx_t *ctx, const char *s, ...) {
83   va_list ap;
84
85   va_start(ap, s);
86   warn_or_exit_on_errorv(ctx, 1, s, ap);
87   va_end(ap);
88 }
89
90 static void warn_or_exit_on_error(vpx_codec_ctx_t *ctx, int fatal,
91                                   const char *s, ...) {
92   va_list ap;
93
94   va_start(ap, s);
95   warn_or_exit_on_errorv(ctx, fatal, s, ap);
96   va_end(ap);
97 }
98
99 int read_frame(struct VpxInputContext *input_ctx, vpx_image_t *img) {
100   FILE *f = input_ctx->file;
101   y4m_input *y4m = &input_ctx->y4m;
102   int shortread = 0;
103
104   if (input_ctx->file_type == FILE_TYPE_Y4M) {
105     if (y4m_input_fetch_frame(y4m, f, img) < 1)
106       return 0;
107   } else {
108     shortread = read_yuv_frame(input_ctx, img);
109   }
110
111   return !shortread;
112 }
113
114 int file_is_y4m(const char detect[4]) {
115   if (memcmp(detect, "YUV4", 4) == 0) {
116     return 1;
117   }
118   return 0;
119 }
120
121 int fourcc_is_ivf(const char detect[4]) {
122   if (memcmp(detect, "DKIF", 4) == 0) {
123     return 1;
124   }
125   return 0;
126 }
127
128 static const arg_def_t debugmode = ARG_DEF("D", "debug", 0,
129                                            "Debug mode (makes output deterministic)");
130 static const arg_def_t outputfile = ARG_DEF("o", "output", 1,
131                                             "Output filename");
132 static const arg_def_t use_yv12 = ARG_DEF(NULL, "yv12", 0,
133                                           "Input file is YV12 ");
134 static const arg_def_t use_i420 = ARG_DEF(NULL, "i420", 0,
135                                           "Input file is I420 (default)");
136 static const arg_def_t codecarg = ARG_DEF(NULL, "codec", 1,
137                                           "Codec to use");
138 static const arg_def_t passes           = ARG_DEF("p", "passes", 1,
139                                                   "Number of passes (1/2)");
140 static const arg_def_t pass_arg         = ARG_DEF(NULL, "pass", 1,
141                                                   "Pass to execute (1/2)");
142 static const arg_def_t fpf_name         = ARG_DEF(NULL, "fpf", 1,
143                                                   "First pass statistics file name");
144 #if CONFIG_FP_MB_STATS
145 static const arg_def_t fpmbf_name         = ARG_DEF(NULL, "fpmbf", 1,
146                                       "First pass block statistics file name");
147 #endif
148 static const arg_def_t limit = ARG_DEF(NULL, "limit", 1,
149                                        "Stop encoding after n input frames");
150 static const arg_def_t skip = ARG_DEF(NULL, "skip", 1,
151                                       "Skip the first n input frames");
152 static const arg_def_t deadline         = ARG_DEF("d", "deadline", 1,
153                                                   "Deadline per frame (usec)");
154 static const arg_def_t best_dl          = ARG_DEF(NULL, "best", 0,
155                                                   "Use Best Quality Deadline");
156 static const arg_def_t good_dl          = ARG_DEF(NULL, "good", 0,
157                                                   "Use Good Quality Deadline");
158 static const arg_def_t rt_dl            = ARG_DEF(NULL, "rt", 0,
159                                                   "Use Realtime Quality Deadline");
160 static const arg_def_t quietarg         = ARG_DEF("q", "quiet", 0,
161                                                   "Do not print encode progress");
162 static const arg_def_t verbosearg       = ARG_DEF("v", "verbose", 0,
163                                                   "Show encoder parameters");
164 static const arg_def_t psnrarg          = ARG_DEF(NULL, "psnr", 0,
165                                                   "Show PSNR in status line");
166
167 static const struct arg_enum_list test_decode_enum[] = {
168   {"off",   TEST_DECODE_OFF},
169   {"fatal", TEST_DECODE_FATAL},
170   {"warn",  TEST_DECODE_WARN},
171   {NULL, 0}
172 };
173 static const arg_def_t recontest = ARG_DEF_ENUM(NULL, "test-decode", 1,
174                                                 "Test encode/decode mismatch",
175                                                 test_decode_enum);
176 static const arg_def_t framerate        = ARG_DEF(NULL, "fps", 1,
177                                                   "Stream frame rate (rate/scale)");
178 static const arg_def_t use_ivf          = ARG_DEF(NULL, "ivf", 0,
179                                                   "Output IVF (default is WebM if WebM IO is enabled)");
180 static const arg_def_t out_part = ARG_DEF("P", "output-partitions", 0,
181                                           "Makes encoder output partitions. Requires IVF output!");
182 static const arg_def_t q_hist_n         = ARG_DEF(NULL, "q-hist", 1,
183                                                   "Show quantizer histogram (n-buckets)");
184 static const arg_def_t rate_hist_n         = ARG_DEF(NULL, "rate-hist", 1,
185                                                      "Show rate histogram (n-buckets)");
186 static const arg_def_t disable_warnings =
187     ARG_DEF(NULL, "disable-warnings", 0,
188             "Disable warnings about potentially incorrect encode settings.");
189 static const arg_def_t disable_warning_prompt =
190     ARG_DEF("y", "disable-warning-prompt", 0,
191             "Display warnings, but do not prompt user to continue.");
192 static const arg_def_t experimental_bitstream =
193     ARG_DEF(NULL, "experimental-bitstream", 0,
194             "Allow experimental bitstream features.");
195
196
197 static const arg_def_t *main_args[] = {
198   &debugmode,
199   &outputfile, &codecarg, &passes, &pass_arg, &fpf_name, &limit, &skip,
200   &deadline, &best_dl, &good_dl, &rt_dl,
201   &quietarg, &verbosearg, &psnrarg, &use_ivf, &out_part, &q_hist_n,
202   &rate_hist_n, &disable_warnings, &disable_warning_prompt,
203   NULL
204 };
205
206 static const arg_def_t usage            = ARG_DEF("u", "usage", 1,
207                                                   "Usage profile number to use");
208 static const arg_def_t threads          = ARG_DEF("t", "threads", 1,
209                                                   "Max number of threads to use");
210 static const arg_def_t profile          = ARG_DEF(NULL, "profile", 1,
211                                                   "Bitstream profile number to use");
212 static const arg_def_t width            = ARG_DEF("w", "width", 1,
213                                                   "Frame width");
214 static const arg_def_t height           = ARG_DEF("h", "height", 1,
215                                                   "Frame height");
216 #if CONFIG_WEBM_IO
217 static const struct arg_enum_list stereo_mode_enum[] = {
218   {"mono", STEREO_FORMAT_MONO},
219   {"left-right", STEREO_FORMAT_LEFT_RIGHT},
220   {"bottom-top", STEREO_FORMAT_BOTTOM_TOP},
221   {"top-bottom", STEREO_FORMAT_TOP_BOTTOM},
222   {"right-left", STEREO_FORMAT_RIGHT_LEFT},
223   {NULL, 0}
224 };
225 static const arg_def_t stereo_mode      = ARG_DEF_ENUM(NULL, "stereo-mode", 1,
226                                                        "Stereo 3D video format", stereo_mode_enum);
227 #endif
228 static const arg_def_t timebase         = ARG_DEF(NULL, "timebase", 1,
229                                                   "Output timestamp precision (fractional seconds)");
230 static const arg_def_t error_resilient  = ARG_DEF(NULL, "error-resilient", 1,
231                                                   "Enable error resiliency features");
232 static const arg_def_t lag_in_frames    = ARG_DEF(NULL, "lag-in-frames", 1,
233                                                   "Max number of frames to lag");
234
235 static const arg_def_t *global_args[] = {
236   &use_yv12, &use_i420, &usage, &threads, &profile,
237   &width, &height,
238 #if CONFIG_WEBM_IO
239   &stereo_mode,
240 #endif
241   &timebase, &framerate,
242   &error_resilient,
243   &lag_in_frames, NULL
244 };
245
246 static const arg_def_t dropframe_thresh   = ARG_DEF(NULL, "drop-frame", 1,
247                                                     "Temporal resampling threshold (buf %)");
248 static const arg_def_t resize_allowed     = ARG_DEF(NULL, "resize-allowed", 1,
249                                                     "Spatial resampling enabled (bool)");
250 static const arg_def_t resize_width       = ARG_DEF(NULL, "resize-width", 1,
251                                                     "Width of encoded frame");
252 static const arg_def_t resize_height      = ARG_DEF(NULL, "resize-height", 1,
253                                                     "Height of encoded frame");
254 static const arg_def_t resize_up_thresh   = ARG_DEF(NULL, "resize-up", 1,
255                                                     "Upscale threshold (buf %)");
256 static const arg_def_t resize_down_thresh = ARG_DEF(NULL, "resize-down", 1,
257                                                     "Downscale threshold (buf %)");
258 static const struct arg_enum_list end_usage_enum[] = {
259   {"vbr", VPX_VBR},
260   {"cbr", VPX_CBR},
261   {"cq",  VPX_CQ},
262   {"q",   VPX_Q},
263   {NULL, 0}
264 };
265 static const arg_def_t end_usage          = ARG_DEF_ENUM(NULL, "end-usage", 1,
266                                                          "Rate control mode", end_usage_enum);
267 static const arg_def_t target_bitrate     = ARG_DEF(NULL, "target-bitrate", 1,
268                                                     "Bitrate (kbps)");
269 static const arg_def_t min_quantizer      = ARG_DEF(NULL, "min-q", 1,
270                                                     "Minimum (best) quantizer");
271 static const arg_def_t max_quantizer      = ARG_DEF(NULL, "max-q", 1,
272                                                     "Maximum (worst) quantizer");
273 static const arg_def_t undershoot_pct     = ARG_DEF(NULL, "undershoot-pct", 1,
274                                                     "Datarate undershoot (min) target (%)");
275 static const arg_def_t overshoot_pct      = ARG_DEF(NULL, "overshoot-pct", 1,
276                                                     "Datarate overshoot (max) target (%)");
277 static const arg_def_t buf_sz             = ARG_DEF(NULL, "buf-sz", 1,
278                                                     "Client buffer size (ms)");
279 static const arg_def_t buf_initial_sz     = ARG_DEF(NULL, "buf-initial-sz", 1,
280                                                     "Client initial buffer size (ms)");
281 static const arg_def_t buf_optimal_sz     = ARG_DEF(NULL, "buf-optimal-sz", 1,
282                                                     "Client optimal buffer size (ms)");
283 static const arg_def_t *rc_args[] = {
284   &dropframe_thresh, &resize_allowed, &resize_width, &resize_height,
285   &resize_up_thresh, &resize_down_thresh, &end_usage, &target_bitrate,
286   &min_quantizer, &max_quantizer, &undershoot_pct, &overshoot_pct, &buf_sz,
287   &buf_initial_sz, &buf_optimal_sz, NULL
288 };
289
290
291 static const arg_def_t bias_pct = ARG_DEF(NULL, "bias-pct", 1,
292                                           "CBR/VBR bias (0=CBR, 100=VBR)");
293 static const arg_def_t minsection_pct = ARG_DEF(NULL, "minsection-pct", 1,
294                                                 "GOP min bitrate (% of target)");
295 static const arg_def_t maxsection_pct = ARG_DEF(NULL, "maxsection-pct", 1,
296                                                 "GOP max bitrate (% of target)");
297 static const arg_def_t *rc_twopass_args[] = {
298   &bias_pct, &minsection_pct, &maxsection_pct, NULL
299 };
300
301
302 static const arg_def_t kf_min_dist = ARG_DEF(NULL, "kf-min-dist", 1,
303                                              "Minimum keyframe interval (frames)");
304 static const arg_def_t kf_max_dist = ARG_DEF(NULL, "kf-max-dist", 1,
305                                              "Maximum keyframe interval (frames)");
306 static const arg_def_t kf_disabled = ARG_DEF(NULL, "disable-kf", 0,
307                                              "Disable keyframe placement");
308 static const arg_def_t *kf_args[] = {
309   &kf_min_dist, &kf_max_dist, &kf_disabled, NULL
310 };
311
312
313 static const arg_def_t noise_sens = ARG_DEF(NULL, "noise-sensitivity", 1,
314                                             "Noise sensitivity (frames to blur)");
315 static const arg_def_t sharpness = ARG_DEF(NULL, "sharpness", 1,
316                                            "Filter sharpness (0-7)");
317 static const arg_def_t static_thresh = ARG_DEF(NULL, "static-thresh", 1,
318                                                "Motion detection threshold");
319 static const arg_def_t cpu_used = ARG_DEF(NULL, "cpu-used", 1,
320                                           "CPU Used (-16..16)");
321 static const arg_def_t auto_altref = ARG_DEF(NULL, "auto-alt-ref", 1,
322                                              "Enable automatic alt reference frames");
323 static const arg_def_t arnr_maxframes = ARG_DEF(NULL, "arnr-maxframes", 1,
324                                                 "AltRef Max Frames");
325 static const arg_def_t arnr_strength = ARG_DEF(NULL, "arnr-strength", 1,
326                                                "AltRef Strength");
327 static const arg_def_t arnr_type = ARG_DEF(NULL, "arnr-type", 1,
328                                            "AltRef Type");
329 static const struct arg_enum_list tuning_enum[] = {
330   {"psnr", VP8_TUNE_PSNR},
331   {"ssim", VP8_TUNE_SSIM},
332   {NULL, 0}
333 };
334 static const arg_def_t tune_ssim = ARG_DEF_ENUM(NULL, "tune", 1,
335                                                 "Material to favor", tuning_enum);
336 static const arg_def_t cq_level = ARG_DEF(NULL, "cq-level", 1,
337                                           "Constant/Constrained Quality level");
338 static const arg_def_t max_intra_rate_pct = ARG_DEF(NULL, "max-intra-rate", 1,
339                                                     "Max I-frame bitrate (pct)");
340
341 #if CONFIG_VP8_ENCODER
342 static const arg_def_t token_parts =
343     ARG_DEF(NULL, "token-parts", 1, "Number of token partitions to use, log2");
344 static const arg_def_t *vp8_args[] = {
345   &cpu_used, &auto_altref, &noise_sens, &sharpness, &static_thresh,
346   &token_parts, &arnr_maxframes, &arnr_strength, &arnr_type,
347   &tune_ssim, &cq_level, &max_intra_rate_pct,
348   NULL
349 };
350 static const int vp8_arg_ctrl_map[] = {
351   VP8E_SET_CPUUSED, VP8E_SET_ENABLEAUTOALTREF,
352   VP8E_SET_NOISE_SENSITIVITY, VP8E_SET_SHARPNESS, VP8E_SET_STATIC_THRESHOLD,
353   VP8E_SET_TOKEN_PARTITIONS,
354   VP8E_SET_ARNR_MAXFRAMES, VP8E_SET_ARNR_STRENGTH, VP8E_SET_ARNR_TYPE,
355   VP8E_SET_TUNING, VP8E_SET_CQ_LEVEL, VP8E_SET_MAX_INTRA_BITRATE_PCT,
356   0
357 };
358 #endif
359
360 #if CONFIG_VP9_ENCODER
361 static const arg_def_t tile_cols =
362     ARG_DEF(NULL, "tile-columns", 1, "Number of tile columns to use, log2");
363 static const arg_def_t tile_rows =
364     ARG_DEF(NULL, "tile-rows", 1, "Number of tile rows to use, log2");
365 static const arg_def_t lossless = ARG_DEF(NULL, "lossless", 1, "Lossless mode");
366 static const arg_def_t frame_parallel_decoding = ARG_DEF(
367     NULL, "frame-parallel", 1, "Enable frame parallel decodability features");
368 static const arg_def_t aq_mode = ARG_DEF(
369     NULL, "aq-mode", 1,
370     "Adaptive quantization mode (0: off (default), 1: variance 2: complexity, "
371     "3: cyclic refresh)");
372 static const arg_def_t frame_periodic_boost = ARG_DEF(
373     NULL, "frame_boost", 1,
374     "Enable frame periodic boost (0: off (default), 1: on)");
375
376 static const arg_def_t *vp9_args[] = {
377   &cpu_used, &auto_altref, &noise_sens, &sharpness, &static_thresh,
378   &tile_cols, &tile_rows, &arnr_maxframes, &arnr_strength, &arnr_type,
379   &tune_ssim, &cq_level, &max_intra_rate_pct, &lossless,
380   &frame_parallel_decoding, &aq_mode, &frame_periodic_boost,
381   NULL
382 };
383 static const int vp9_arg_ctrl_map[] = {
384   VP8E_SET_CPUUSED, VP8E_SET_ENABLEAUTOALTREF,
385   VP8E_SET_NOISE_SENSITIVITY, VP8E_SET_SHARPNESS, VP8E_SET_STATIC_THRESHOLD,
386   VP9E_SET_TILE_COLUMNS, VP9E_SET_TILE_ROWS,
387   VP8E_SET_ARNR_MAXFRAMES, VP8E_SET_ARNR_STRENGTH, VP8E_SET_ARNR_TYPE,
388   VP8E_SET_TUNING, VP8E_SET_CQ_LEVEL, VP8E_SET_MAX_INTRA_BITRATE_PCT,
389   VP9E_SET_LOSSLESS, VP9E_SET_FRAME_PARALLEL_DECODING, VP9E_SET_AQ_MODE,
390   VP9E_SET_FRAME_PERIODIC_BOOST,
391   0
392 };
393 #endif
394
395 static const arg_def_t *no_args[] = { NULL };
396
397 void usage_exit() {
398   int i;
399
400   fprintf(stderr, "Usage: %s <options> -o dst_filename src_filename \n",
401           exec_name);
402
403   fprintf(stderr, "\nOptions:\n");
404   arg_show_usage(stderr, main_args);
405   fprintf(stderr, "\nEncoder Global Options:\n");
406   arg_show_usage(stderr, global_args);
407   fprintf(stderr, "\nRate Control Options:\n");
408   arg_show_usage(stderr, rc_args);
409   fprintf(stderr, "\nTwopass Rate Control Options:\n");
410   arg_show_usage(stderr, rc_twopass_args);
411   fprintf(stderr, "\nKeyframe Placement Options:\n");
412   arg_show_usage(stderr, kf_args);
413 #if CONFIG_VP8_ENCODER
414   fprintf(stderr, "\nVP8 Specific Options:\n");
415   arg_show_usage(stderr, vp8_args);
416 #endif
417 #if CONFIG_VP9_ENCODER
418   fprintf(stderr, "\nVP9 Specific Options:\n");
419   arg_show_usage(stderr, vp9_args);
420 #endif
421   fprintf(stderr, "\nStream timebase (--timebase):\n"
422           "  The desired precision of timestamps in the output, expressed\n"
423           "  in fractional seconds. Default is 1/1000.\n");
424   fprintf(stderr, "\nIncluded encoders:\n\n");
425
426   for (i = 0; i < get_vpx_encoder_count(); ++i) {
427     const VpxInterface *const encoder = get_vpx_encoder_by_index(i);
428     fprintf(stderr, "    %-6s - %s\n",
429             encoder->name, vpx_codec_iface_name(encoder->interface()));
430   }
431
432   exit(EXIT_FAILURE);
433 }
434
435 #define mmin(a, b)  ((a) < (b) ? (a) : (b))
436 static void find_mismatch(const vpx_image_t *const img1,
437                           const vpx_image_t *const img2,
438                           int yloc[4], int uloc[4], int vloc[4]) {
439   const uint32_t bsize = 64;
440   const uint32_t bsizey = bsize >> img1->y_chroma_shift;
441   const uint32_t bsizex = bsize >> img1->x_chroma_shift;
442   const uint32_t c_w =
443       (img1->d_w + img1->x_chroma_shift) >> img1->x_chroma_shift;
444   const uint32_t c_h =
445       (img1->d_h + img1->y_chroma_shift) >> img1->y_chroma_shift;
446   int match = 1;
447   uint32_t i, j;
448   yloc[0] = yloc[1] = yloc[2] = yloc[3] = -1;
449   for (i = 0, match = 1; match && i < img1->d_h; i += bsize) {
450     for (j = 0; match && j < img1->d_w; j += bsize) {
451       int k, l;
452       const int si = mmin(i + bsize, img1->d_h) - i;
453       const int sj = mmin(j + bsize, img1->d_w) - j;
454       for (k = 0; match && k < si; ++k) {
455         for (l = 0; match && l < sj; ++l) {
456           if (*(img1->planes[VPX_PLANE_Y] +
457                 (i + k) * img1->stride[VPX_PLANE_Y] + j + l) !=
458               *(img2->planes[VPX_PLANE_Y] +
459                 (i + k) * img2->stride[VPX_PLANE_Y] + j + l)) {
460             yloc[0] = i + k;
461             yloc[1] = j + l;
462             yloc[2] = *(img1->planes[VPX_PLANE_Y] +
463                         (i + k) * img1->stride[VPX_PLANE_Y] + j + l);
464             yloc[3] = *(img2->planes[VPX_PLANE_Y] +
465                         (i + k) * img2->stride[VPX_PLANE_Y] + j + l);
466             match = 0;
467             break;
468           }
469         }
470       }
471     }
472   }
473
474   uloc[0] = uloc[1] = uloc[2] = uloc[3] = -1;
475   for (i = 0, match = 1; match && i < c_h; i += bsizey) {
476     for (j = 0; match && j < c_w; j += bsizex) {
477       int k, l;
478       const int si = mmin(i + bsizey, c_h - i);
479       const int sj = mmin(j + bsizex, c_w - j);
480       for (k = 0; match && k < si; ++k) {
481         for (l = 0; match && l < sj; ++l) {
482           if (*(img1->planes[VPX_PLANE_U] +
483                 (i + k) * img1->stride[VPX_PLANE_U] + j + l) !=
484               *(img2->planes[VPX_PLANE_U] +
485                 (i + k) * img2->stride[VPX_PLANE_U] + j + l)) {
486             uloc[0] = i + k;
487             uloc[1] = j + l;
488             uloc[2] = *(img1->planes[VPX_PLANE_U] +
489                         (i + k) * img1->stride[VPX_PLANE_U] + j + l);
490             uloc[3] = *(img2->planes[VPX_PLANE_U] +
491                         (i + k) * img2->stride[VPX_PLANE_U] + j + l);
492             match = 0;
493             break;
494           }
495         }
496       }
497     }
498   }
499   vloc[0] = vloc[1] = vloc[2] = vloc[3] = -1;
500   for (i = 0, match = 1; match && i < c_h; i += bsizey) {
501     for (j = 0; match && j < c_w; j += bsizex) {
502       int k, l;
503       const int si = mmin(i + bsizey, c_h - i);
504       const int sj = mmin(j + bsizex, c_w - j);
505       for (k = 0; match && k < si; ++k) {
506         for (l = 0; match && l < sj; ++l) {
507           if (*(img1->planes[VPX_PLANE_V] +
508                 (i + k) * img1->stride[VPX_PLANE_V] + j + l) !=
509               *(img2->planes[VPX_PLANE_V] +
510                 (i + k) * img2->stride[VPX_PLANE_V] + j + l)) {
511             vloc[0] = i + k;
512             vloc[1] = j + l;
513             vloc[2] = *(img1->planes[VPX_PLANE_V] +
514                         (i + k) * img1->stride[VPX_PLANE_V] + j + l);
515             vloc[3] = *(img2->planes[VPX_PLANE_V] +
516                         (i + k) * img2->stride[VPX_PLANE_V] + j + l);
517             match = 0;
518             break;
519           }
520         }
521       }
522     }
523   }
524 }
525
526 static int compare_img(const vpx_image_t *const img1,
527                        const vpx_image_t *const img2) {
528   const uint32_t c_w =
529       (img1->d_w + img1->x_chroma_shift) >> img1->x_chroma_shift;
530   const uint32_t c_h =
531       (img1->d_h + img1->y_chroma_shift) >> img1->y_chroma_shift;
532   uint32_t i;
533   int match = 1;
534
535   match &= (img1->fmt == img2->fmt);
536   match &= (img1->d_w == img2->d_w);
537   match &= (img1->d_h == img2->d_h);
538
539   for (i = 0; i < img1->d_h; ++i)
540     match &= (memcmp(img1->planes[VPX_PLANE_Y] + i * img1->stride[VPX_PLANE_Y],
541                      img2->planes[VPX_PLANE_Y] + i * img2->stride[VPX_PLANE_Y],
542                      img1->d_w) == 0);
543
544   for (i = 0; i < c_h; ++i)
545     match &= (memcmp(img1->planes[VPX_PLANE_U] + i * img1->stride[VPX_PLANE_U],
546                      img2->planes[VPX_PLANE_U] + i * img2->stride[VPX_PLANE_U],
547                      c_w) == 0);
548
549   for (i = 0; i < c_h; ++i)
550     match &= (memcmp(img1->planes[VPX_PLANE_V] + i * img1->stride[VPX_PLANE_V],
551                      img2->planes[VPX_PLANE_V] + i * img2->stride[VPX_PLANE_V],
552                      c_w) == 0);
553
554   return match;
555 }
556
557
558 #define NELEMENTS(x) (sizeof(x)/sizeof(x[0]))
559 #define MAX(x,y) ((x)>(y)?(x):(y))
560 #if CONFIG_VP8_ENCODER && !CONFIG_VP9_ENCODER
561 #define ARG_CTRL_CNT_MAX NELEMENTS(vp8_arg_ctrl_map)
562 #elif !CONFIG_VP8_ENCODER && CONFIG_VP9_ENCODER
563 #define ARG_CTRL_CNT_MAX NELEMENTS(vp9_arg_ctrl_map)
564 #else
565 #define ARG_CTRL_CNT_MAX MAX(NELEMENTS(vp8_arg_ctrl_map), \
566                              NELEMENTS(vp9_arg_ctrl_map))
567 #endif
568
569 #if !CONFIG_WEBM_IO
570 typedef int stereo_format_t;
571 struct EbmlGlobal { int debug; };
572 #endif
573
574 /* Per-stream configuration */
575 struct stream_config {
576   struct vpx_codec_enc_cfg  cfg;
577   const char               *out_fn;
578   const char               *stats_fn;
579 #if CONFIG_FP_MB_STATS
580   const char               *fpmb_stats_fn;
581 #endif
582   stereo_format_t           stereo_fmt;
583   int                       arg_ctrls[ARG_CTRL_CNT_MAX][2];
584   int                       arg_ctrl_cnt;
585   int                       write_webm;
586   int                       have_kf_max_dist;
587 };
588
589
590 struct stream_state {
591   int                       index;
592   struct stream_state      *next;
593   struct stream_config      config;
594   FILE                     *file;
595   struct rate_hist         *rate_hist;
596   struct EbmlGlobal         ebml;
597   uint64_t                  psnr_sse_total;
598   uint64_t                  psnr_samples_total;
599   double                    psnr_totals[4];
600   int                       psnr_count;
601   int                       counts[64];
602   vpx_codec_ctx_t           encoder;
603   unsigned int              frames_out;
604   uint64_t                  cx_time;
605   size_t                    nbytes;
606   stats_io_t                stats;
607 #if CONFIG_FP_MB_STATS
608   stats_io_t                fpmb_stats;
609 #endif
610   struct vpx_image         *img;
611   vpx_codec_ctx_t           decoder;
612   int                       mismatch_seen;
613 };
614
615
616 void validate_positive_rational(const char          *msg,
617                                 struct vpx_rational *rat) {
618   if (rat->den < 0) {
619     rat->num *= -1;
620     rat->den *= -1;
621   }
622
623   if (rat->num < 0)
624     die("Error: %s must be positive\n", msg);
625
626   if (!rat->den)
627     die("Error: %s has zero denominator\n", msg);
628 }
629
630
631 static void parse_global_config(struct VpxEncoderConfig *global, char **argv) {
632   char       **argi, **argj;
633   struct arg   arg;
634
635   /* Initialize default parameters */
636   memset(global, 0, sizeof(*global));
637   global->codec = get_vpx_encoder_by_index(0);
638   global->passes = 0;
639   global->use_i420 = 1;
640   /* Assign default deadline to good quality */
641   global->deadline = VPX_DL_GOOD_QUALITY;
642
643   for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step) {
644     arg.argv_step = 1;
645
646     if (arg_match(&arg, &codecarg, argi)) {
647       global->codec = get_vpx_encoder_by_name(arg.val);
648       if (!global->codec)
649         die("Error: Unrecognized argument (%s) to --codec\n", arg.val);
650     } else if (arg_match(&arg, &passes, argi)) {
651       global->passes = arg_parse_uint(&arg);
652
653       if (global->passes < 1 || global->passes > 2)
654         die("Error: Invalid number of passes (%d)\n", global->passes);
655     } else if (arg_match(&arg, &pass_arg, argi)) {
656       global->pass = arg_parse_uint(&arg);
657
658       if (global->pass < 1 || global->pass > 2)
659         die("Error: Invalid pass selected (%d)\n",
660             global->pass);
661     } else if (arg_match(&arg, &usage, argi))
662       global->usage = arg_parse_uint(&arg);
663     else if (arg_match(&arg, &deadline, argi))
664       global->deadline = arg_parse_uint(&arg);
665     else if (arg_match(&arg, &best_dl, argi))
666       global->deadline = VPX_DL_BEST_QUALITY;
667     else if (arg_match(&arg, &good_dl, argi))
668       global->deadline = VPX_DL_GOOD_QUALITY;
669     else if (arg_match(&arg, &rt_dl, argi))
670       global->deadline = VPX_DL_REALTIME;
671     else if (arg_match(&arg, &use_yv12, argi))
672       global->use_i420 = 0;
673     else if (arg_match(&arg, &use_i420, argi))
674       global->use_i420 = 1;
675     else if (arg_match(&arg, &quietarg, argi))
676       global->quiet = 1;
677     else if (arg_match(&arg, &verbosearg, argi))
678       global->verbose = 1;
679     else if (arg_match(&arg, &limit, argi))
680       global->limit = arg_parse_uint(&arg);
681     else if (arg_match(&arg, &skip, argi))
682       global->skip_frames = arg_parse_uint(&arg);
683     else if (arg_match(&arg, &psnrarg, argi))
684       global->show_psnr = 1;
685     else if (arg_match(&arg, &recontest, argi))
686       global->test_decode = arg_parse_enum_or_int(&arg);
687     else if (arg_match(&arg, &framerate, argi)) {
688       global->framerate = arg_parse_rational(&arg);
689       validate_positive_rational(arg.name, &global->framerate);
690       global->have_framerate = 1;
691     } else if (arg_match(&arg, &out_part, argi))
692       global->out_part = 1;
693     else if (arg_match(&arg, &debugmode, argi))
694       global->debug = 1;
695     else if (arg_match(&arg, &q_hist_n, argi))
696       global->show_q_hist_buckets = arg_parse_uint(&arg);
697     else if (arg_match(&arg, &rate_hist_n, argi))
698       global->show_rate_hist_buckets = arg_parse_uint(&arg);
699     else if (arg_match(&arg, &disable_warnings, argi))
700       global->disable_warnings = 1;
701     else if (arg_match(&arg, &disable_warning_prompt, argi))
702       global->disable_warning_prompt = 1;
703     else if (arg_match(&arg, &experimental_bitstream, argi))
704       global->experimental_bitstream = 1;
705     else
706       argj++;
707   }
708
709   if (global->pass) {
710     /* DWIM: Assume the user meant passes=2 if pass=2 is specified */
711     if (global->pass > global->passes) {
712       warn("Assuming --pass=%d implies --passes=%d\n",
713            global->pass, global->pass);
714       global->passes = global->pass;
715     }
716   }
717   /* Validate global config */
718   if (global->passes == 0) {
719 #if CONFIG_VP9_ENCODER
720     // Make default VP9 passes = 2 until there is a better quality 1-pass
721     // encoder
722     global->passes = (strcmp(global->codec->name, "vp9") == 0 &&
723                       global->deadline != VPX_DL_REALTIME) ? 2 : 1;
724 #else
725     global->passes = 1;
726 #endif
727   }
728
729   if (global->deadline == VPX_DL_REALTIME &&
730       global->passes > 1) {
731     warn("Enforcing one-pass encoding in realtime mode\n");
732     global->passes = 1;
733   }
734 }
735
736
737 void open_input_file(struct VpxInputContext *input) {
738   /* Parse certain options from the input file, if possible */
739   input->file = strcmp(input->filename, "-")
740       ? fopen(input->filename, "rb") : set_binary_mode(stdin);
741
742   if (!input->file)
743     fatal("Failed to open input file");
744
745   if (!fseeko(input->file, 0, SEEK_END)) {
746     /* Input file is seekable. Figure out how long it is, so we can get
747      * progress info.
748      */
749     input->length = ftello(input->file);
750     rewind(input->file);
751   }
752
753   /* For RAW input sources, these bytes will applied on the first frame
754    *  in read_frame().
755    */
756   input->detect.buf_read = fread(input->detect.buf, 1, 4, input->file);
757   input->detect.position = 0;
758
759   if (input->detect.buf_read == 4
760       && file_is_y4m(input->detect.buf)) {
761     if (y4m_input_open(&input->y4m, input->file, input->detect.buf, 4,
762                        input->only_i420) >= 0) {
763       input->file_type = FILE_TYPE_Y4M;
764       input->width = input->y4m.pic_w;
765       input->height = input->y4m.pic_h;
766       input->framerate.numerator = input->y4m.fps_n;
767       input->framerate.denominator = input->y4m.fps_d;
768       input->fmt = input->y4m.vpx_fmt;
769       input->bit_depth = input->y4m.bit_depth;
770     } else
771       fatal("Unsupported Y4M stream.");
772   } else if (input->detect.buf_read == 4 && fourcc_is_ivf(input->detect.buf)) {
773     fatal("IVF is not supported as input.");
774   } else {
775     input->file_type = FILE_TYPE_RAW;
776   }
777 }
778
779
780 static void close_input_file(struct VpxInputContext *input) {
781   fclose(input->file);
782   if (input->file_type == FILE_TYPE_Y4M)
783     y4m_input_close(&input->y4m);
784 }
785
786 static struct stream_state *new_stream(struct VpxEncoderConfig *global,
787                                        struct stream_state *prev) {
788   struct stream_state *stream;
789
790   stream = calloc(1, sizeof(*stream));
791   if (!stream)
792     fatal("Failed to allocate new stream.");
793   if (prev) {
794     memcpy(stream, prev, sizeof(*stream));
795     stream->index++;
796     prev->next = stream;
797   } else {
798     vpx_codec_err_t  res;
799
800     /* Populate encoder configuration */
801     res = vpx_codec_enc_config_default(global->codec->interface(),
802                                        &stream->config.cfg,
803                                        global->usage);
804     if (res)
805       fatal("Failed to get config: %s\n", vpx_codec_err_to_string(res));
806
807     /* Change the default timebase to a high enough value so that the
808      * encoder will always create strictly increasing timestamps.
809      */
810     stream->config.cfg.g_timebase.den = 1000;
811
812     /* Never use the library's default resolution, require it be parsed
813      * from the file or set on the command line.
814      */
815     stream->config.cfg.g_w = 0;
816     stream->config.cfg.g_h = 0;
817
818     /* Initialize remaining stream parameters */
819     stream->config.write_webm = 1;
820 #if CONFIG_WEBM_IO
821     stream->config.stereo_fmt = STEREO_FORMAT_MONO;
822     stream->ebml.last_pts_ns = -1;
823     stream->ebml.writer = NULL;
824     stream->ebml.segment = NULL;
825 #endif
826
827     /* Allows removal of the application version from the EBML tags */
828     stream->ebml.debug = global->debug;
829
830     /* Default lag_in_frames is 0 in realtime mode */
831     if (global->deadline == VPX_DL_REALTIME)
832       stream->config.cfg.g_lag_in_frames = 0;
833   }
834
835   /* Output files must be specified for each stream */
836   stream->config.out_fn = NULL;
837
838   stream->next = NULL;
839   return stream;
840 }
841
842
843 static int parse_stream_params(struct VpxEncoderConfig *global,
844                                struct stream_state  *stream,
845                                char **argv) {
846   char                   **argi, **argj;
847   struct arg               arg;
848   static const arg_def_t **ctrl_args = no_args;
849   static const int        *ctrl_args_map = NULL;
850   struct stream_config    *config = &stream->config;
851   int                      eos_mark_found = 0;
852
853   // Handle codec specific options
854   if (0) {
855 #if CONFIG_VP8_ENCODER
856   } else if (strcmp(global->codec->name, "vp8") == 0) {
857     ctrl_args = vp8_args;
858     ctrl_args_map = vp8_arg_ctrl_map;
859 #endif
860 #if CONFIG_VP9_ENCODER
861   } else if (strcmp(global->codec->name, "vp9") == 0) {
862     ctrl_args = vp9_args;
863     ctrl_args_map = vp9_arg_ctrl_map;
864 #endif
865   }
866
867   for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step) {
868     arg.argv_step = 1;
869
870     /* Once we've found an end-of-stream marker (--) we want to continue
871      * shifting arguments but not consuming them.
872      */
873     if (eos_mark_found) {
874       argj++;
875       continue;
876     } else if (!strcmp(*argj, "--")) {
877       eos_mark_found = 1;
878       continue;
879     }
880
881     if (0) {
882     } else if (arg_match(&arg, &outputfile, argi)) {
883       config->out_fn = arg.val;
884     } else if (arg_match(&arg, &fpf_name, argi)) {
885       config->stats_fn = arg.val;
886 #if CONFIG_FP_MB_STATS
887     } else if (arg_match(&arg, &fpmbf_name, argi)) {
888       config->fpmb_stats_fn = arg.val;
889 #endif
890     } else if (arg_match(&arg, &use_ivf, argi)) {
891       config->write_webm = 0;
892     } else if (arg_match(&arg, &threads, argi)) {
893       config->cfg.g_threads = arg_parse_uint(&arg);
894     } else if (arg_match(&arg, &profile, argi)) {
895       config->cfg.g_profile = arg_parse_uint(&arg);
896     } else if (arg_match(&arg, &width, argi)) {
897       config->cfg.g_w = arg_parse_uint(&arg);
898     } else if (arg_match(&arg, &height, argi)) {
899       config->cfg.g_h = arg_parse_uint(&arg);
900 #if CONFIG_WEBM_IO
901     } else if (arg_match(&arg, &stereo_mode, argi)) {
902       config->stereo_fmt = arg_parse_enum_or_int(&arg);
903 #endif
904     } else if (arg_match(&arg, &timebase, argi)) {
905       config->cfg.g_timebase = arg_parse_rational(&arg);
906       validate_positive_rational(arg.name, &config->cfg.g_timebase);
907     } else if (arg_match(&arg, &error_resilient, argi)) {
908       config->cfg.g_error_resilient = arg_parse_uint(&arg);
909     } else if (arg_match(&arg, &lag_in_frames, argi)) {
910       config->cfg.g_lag_in_frames = arg_parse_uint(&arg);
911       if (global->deadline == VPX_DL_REALTIME &&
912           config->cfg.g_lag_in_frames != 0) {
913         warn("non-zero %s option ignored in realtime mode.\n", arg.name);
914         config->cfg.g_lag_in_frames = 0;
915       }
916     } else if (arg_match(&arg, &dropframe_thresh, argi)) {
917       config->cfg.rc_dropframe_thresh = arg_parse_uint(&arg);
918     } else if (arg_match(&arg, &resize_allowed, argi)) {
919       config->cfg.rc_resize_allowed = arg_parse_uint(&arg);
920     } else if (arg_match(&arg, &resize_width, argi)) {
921       config->cfg.rc_scaled_width = arg_parse_uint(&arg);
922     } else if (arg_match(&arg, &resize_height, argi)) {
923       config->cfg.rc_scaled_height = arg_parse_uint(&arg);
924     } else if (arg_match(&arg, &resize_up_thresh, argi)) {
925       config->cfg.rc_resize_up_thresh = arg_parse_uint(&arg);
926     } else if (arg_match(&arg, &resize_down_thresh, argi)) {
927       config->cfg.rc_resize_down_thresh = arg_parse_uint(&arg);
928     } else if (arg_match(&arg, &end_usage, argi)) {
929       config->cfg.rc_end_usage = arg_parse_enum_or_int(&arg);
930     } else if (arg_match(&arg, &target_bitrate, argi)) {
931       config->cfg.rc_target_bitrate = arg_parse_uint(&arg);
932     } else if (arg_match(&arg, &min_quantizer, argi)) {
933       config->cfg.rc_min_quantizer = arg_parse_uint(&arg);
934     } else if (arg_match(&arg, &max_quantizer, argi)) {
935       config->cfg.rc_max_quantizer = arg_parse_uint(&arg);
936     } else if (arg_match(&arg, &undershoot_pct, argi)) {
937       config->cfg.rc_undershoot_pct = arg_parse_uint(&arg);
938     } else if (arg_match(&arg, &overshoot_pct, argi)) {
939       config->cfg.rc_overshoot_pct = arg_parse_uint(&arg);
940     } else if (arg_match(&arg, &buf_sz, argi)) {
941       config->cfg.rc_buf_sz = arg_parse_uint(&arg);
942     } else if (arg_match(&arg, &buf_initial_sz, argi)) {
943       config->cfg.rc_buf_initial_sz = arg_parse_uint(&arg);
944     } else if (arg_match(&arg, &buf_optimal_sz, argi)) {
945       config->cfg.rc_buf_optimal_sz = arg_parse_uint(&arg);
946     } else if (arg_match(&arg, &bias_pct, argi)) {
947         config->cfg.rc_2pass_vbr_bias_pct = arg_parse_uint(&arg);
948       if (global->passes < 2)
949         warn("option %s ignored in one-pass mode.\n", arg.name);
950     } else if (arg_match(&arg, &minsection_pct, argi)) {
951       config->cfg.rc_2pass_vbr_minsection_pct = arg_parse_uint(&arg);
952
953       if (global->passes < 2)
954         warn("option %s ignored in one-pass mode.\n", arg.name);
955     } else if (arg_match(&arg, &maxsection_pct, argi)) {
956       config->cfg.rc_2pass_vbr_maxsection_pct = arg_parse_uint(&arg);
957
958       if (global->passes < 2)
959         warn("option %s ignored in one-pass mode.\n", arg.name);
960     } else if (arg_match(&arg, &kf_min_dist, argi)) {
961       config->cfg.kf_min_dist = arg_parse_uint(&arg);
962     } else if (arg_match(&arg, &kf_max_dist, argi)) {
963       config->cfg.kf_max_dist = arg_parse_uint(&arg);
964       config->have_kf_max_dist = 1;
965     } else if (arg_match(&arg, &kf_disabled, argi)) {
966       config->cfg.kf_mode = VPX_KF_DISABLED;
967     } else {
968       int i, match = 0;
969       for (i = 0; ctrl_args[i]; i++) {
970         if (arg_match(&arg, ctrl_args[i], argi)) {
971           int j;
972           match = 1;
973
974           /* Point either to the next free element or the first
975           * instance of this control.
976           */
977           for (j = 0; j < config->arg_ctrl_cnt; j++)
978             if (config->arg_ctrls[j][0] == ctrl_args_map[i])
979               break;
980
981           /* Update/insert */
982           assert(j < (int)ARG_CTRL_CNT_MAX);
983           if (j < (int)ARG_CTRL_CNT_MAX) {
984             config->arg_ctrls[j][0] = ctrl_args_map[i];
985             config->arg_ctrls[j][1] = arg_parse_enum_or_int(&arg);
986             if (j == config->arg_ctrl_cnt)
987               config->arg_ctrl_cnt++;
988           }
989
990         }
991       }
992       if (!match)
993         argj++;
994     }
995   }
996   return eos_mark_found;
997 }
998
999
1000 #define FOREACH_STREAM(func) \
1001   do { \
1002     struct stream_state *stream; \
1003     for (stream = streams; stream; stream = stream->next) { \
1004       func; \
1005     } \
1006   } while (0)
1007
1008
1009 static void validate_stream_config(const struct stream_state *stream,
1010                                    const struct VpxEncoderConfig *global) {
1011   const struct stream_state *streami;
1012
1013   if (!stream->config.cfg.g_w || !stream->config.cfg.g_h)
1014     fatal("Stream %d: Specify stream dimensions with --width (-w) "
1015           " and --height (-h)", stream->index);
1016
1017   if (stream->config.cfg.g_profile != 0 && !global->experimental_bitstream) {
1018     fatal("Stream %d: profile %d is experimental and requires the --%s flag",
1019           stream->index, stream->config.cfg.g_profile,
1020           experimental_bitstream.long_name);
1021   }
1022
1023   for (streami = stream; streami; streami = streami->next) {
1024     /* All streams require output files */
1025     if (!streami->config.out_fn)
1026       fatal("Stream %d: Output file is required (specify with -o)",
1027             streami->index);
1028
1029     /* Check for two streams outputting to the same file */
1030     if (streami != stream) {
1031       const char *a = stream->config.out_fn;
1032       const char *b = streami->config.out_fn;
1033       if (!strcmp(a, b) && strcmp(a, "/dev/null") && strcmp(a, ":nul"))
1034         fatal("Stream %d: duplicate output file (from stream %d)",
1035               streami->index, stream->index);
1036     }
1037
1038     /* Check for two streams sharing a stats file. */
1039     if (streami != stream) {
1040       const char *a = stream->config.stats_fn;
1041       const char *b = streami->config.stats_fn;
1042       if (a && b && !strcmp(a, b))
1043         fatal("Stream %d: duplicate stats file (from stream %d)",
1044               streami->index, stream->index);
1045     }
1046
1047 #if CONFIG_FP_MB_STATS
1048     /* Check for two streams sharing a mb stats file. */
1049     if (streami != stream) {
1050       const char *a = stream->config.fpmb_stats_fn;
1051       const char *b = streami->config.fpmb_stats_fn;
1052       if (a && b && !strcmp(a, b))
1053         fatal("Stream %d: duplicate mb stats file (from stream %d)",
1054               streami->index, stream->index);
1055     }
1056 #endif
1057   }
1058 }
1059
1060
1061 static void set_stream_dimensions(struct stream_state *stream,
1062                                   unsigned int w,
1063                                   unsigned int h) {
1064   if (!stream->config.cfg.g_w) {
1065     if (!stream->config.cfg.g_h)
1066       stream->config.cfg.g_w = w;
1067     else
1068       stream->config.cfg.g_w = w * stream->config.cfg.g_h / h;
1069   }
1070   if (!stream->config.cfg.g_h) {
1071     stream->config.cfg.g_h = h * stream->config.cfg.g_w / w;
1072   }
1073 }
1074
1075
1076 static void set_default_kf_interval(struct stream_state *stream,
1077                                     struct VpxEncoderConfig *global) {
1078   /* Use a max keyframe interval of 5 seconds, if none was
1079    * specified on the command line.
1080    */
1081   if (!stream->config.have_kf_max_dist) {
1082     double framerate = (double)global->framerate.num / global->framerate.den;
1083     if (framerate > 0.0)
1084       stream->config.cfg.kf_max_dist = (unsigned int)(5.0 * framerate);
1085   }
1086 }
1087
1088 static const char* file_type_to_string(enum VideoFileType t) {
1089   switch (t) {
1090     case FILE_TYPE_RAW: return "RAW";
1091     case FILE_TYPE_Y4M: return "Y4M";
1092     default: return "Other";
1093   }
1094 }
1095
1096 static const char* image_format_to_string(vpx_img_fmt_t f) {
1097   switch (f) {
1098     case VPX_IMG_FMT_I420: return "I420";
1099     case VPX_IMG_FMT_I422: return "I422";
1100     case VPX_IMG_FMT_I444: return "I444";
1101     case VPX_IMG_FMT_YV12: return "YV12";
1102     default: return "Other";
1103   }
1104 }
1105
1106 static void show_stream_config(struct stream_state *stream,
1107                                struct VpxEncoderConfig *global,
1108                                struct VpxInputContext *input) {
1109
1110 #define SHOW(field) \
1111   fprintf(stderr, "    %-28s = %d\n", #field, stream->config.cfg.field)
1112
1113   if (stream->index == 0) {
1114     fprintf(stderr, "Codec: %s\n",
1115             vpx_codec_iface_name(global->codec->interface()));
1116     fprintf(stderr, "Source file: %s File Type: %s Format: %s\n",
1117             input->filename,
1118             file_type_to_string(input->file_type),
1119             image_format_to_string(input->fmt));
1120   }
1121   if (stream->next || stream->index)
1122     fprintf(stderr, "\nStream Index: %d\n", stream->index);
1123   fprintf(stderr, "Destination file: %s\n", stream->config.out_fn);
1124   fprintf(stderr, "Encoder parameters:\n");
1125
1126   SHOW(g_usage);
1127   SHOW(g_threads);
1128   SHOW(g_profile);
1129   SHOW(g_w);
1130   SHOW(g_h);
1131   SHOW(g_timebase.num);
1132   SHOW(g_timebase.den);
1133   SHOW(g_error_resilient);
1134   SHOW(g_pass);
1135   SHOW(g_lag_in_frames);
1136   SHOW(rc_dropframe_thresh);
1137   SHOW(rc_resize_allowed);
1138   SHOW(rc_scaled_width);
1139   SHOW(rc_scaled_height);
1140   SHOW(rc_resize_up_thresh);
1141   SHOW(rc_resize_down_thresh);
1142   SHOW(rc_end_usage);
1143   SHOW(rc_target_bitrate);
1144   SHOW(rc_min_quantizer);
1145   SHOW(rc_max_quantizer);
1146   SHOW(rc_undershoot_pct);
1147   SHOW(rc_overshoot_pct);
1148   SHOW(rc_buf_sz);
1149   SHOW(rc_buf_initial_sz);
1150   SHOW(rc_buf_optimal_sz);
1151   SHOW(rc_2pass_vbr_bias_pct);
1152   SHOW(rc_2pass_vbr_minsection_pct);
1153   SHOW(rc_2pass_vbr_maxsection_pct);
1154   SHOW(kf_mode);
1155   SHOW(kf_min_dist);
1156   SHOW(kf_max_dist);
1157 }
1158
1159
1160 static void open_output_file(struct stream_state *stream,
1161                              struct VpxEncoderConfig *global) {
1162   const char *fn = stream->config.out_fn;
1163   const struct vpx_codec_enc_cfg *const cfg = &stream->config.cfg;
1164
1165   if (cfg->g_pass == VPX_RC_FIRST_PASS)
1166     return;
1167
1168   stream->file = strcmp(fn, "-") ? fopen(fn, "wb") : set_binary_mode(stdout);
1169
1170   if (!stream->file)
1171     fatal("Failed to open output file");
1172
1173   if (stream->config.write_webm && fseek(stream->file, 0, SEEK_CUR))
1174     fatal("WebM output to pipes not supported.");
1175
1176 #if CONFIG_WEBM_IO
1177   if (stream->config.write_webm) {
1178     stream->ebml.stream = stream->file;
1179     write_webm_file_header(&stream->ebml, cfg,
1180                            &global->framerate,
1181                            stream->config.stereo_fmt,
1182                            global->codec->fourcc);
1183   }
1184 #endif
1185
1186   if (!stream->config.write_webm) {
1187     ivf_write_file_header(stream->file, cfg, global->codec->fourcc, 0);
1188   }
1189 }
1190
1191
1192 static void close_output_file(struct stream_state *stream,
1193                               unsigned int fourcc) {
1194   const struct vpx_codec_enc_cfg *const cfg = &stream->config.cfg;
1195
1196   if (cfg->g_pass == VPX_RC_FIRST_PASS)
1197     return;
1198
1199 #if CONFIG_WEBM_IO
1200   if (stream->config.write_webm) {
1201     write_webm_file_footer(&stream->ebml);
1202   }
1203 #endif
1204
1205   if (!stream->config.write_webm) {
1206     if (!fseek(stream->file, 0, SEEK_SET))
1207       ivf_write_file_header(stream->file, &stream->config.cfg,
1208                             fourcc,
1209                             stream->frames_out);
1210   }
1211
1212   fclose(stream->file);
1213 }
1214
1215
1216 static void setup_pass(struct stream_state *stream,
1217                        struct VpxEncoderConfig *global,
1218                        int pass) {
1219   if (stream->config.stats_fn) {
1220     if (!stats_open_file(&stream->stats, stream->config.stats_fn,
1221                          pass))
1222       fatal("Failed to open statistics store");
1223   } else {
1224     if (!stats_open_mem(&stream->stats, pass))
1225       fatal("Failed to open statistics store");
1226   }
1227
1228 #if CONFIG_FP_MB_STATS
1229   if (stream->config.fpmb_stats_fn) {
1230     if (!stats_open_file(&stream->fpmb_stats,
1231                          stream->config.fpmb_stats_fn, pass))
1232       fatal("Failed to open mb statistics store");
1233   } else {
1234     if (!stats_open_mem(&stream->fpmb_stats, pass))
1235       fatal("Failed to open mb statistics store");
1236   }
1237 #endif
1238
1239   stream->config.cfg.g_pass = global->passes == 2
1240                               ? pass ? VPX_RC_LAST_PASS : VPX_RC_FIRST_PASS
1241                             : VPX_RC_ONE_PASS;
1242   if (pass) {
1243     stream->config.cfg.rc_twopass_stats_in = stats_get(&stream->stats);
1244 #if CONFIG_FP_MB_STATS
1245     stream->config.cfg.rc_firstpass_mb_stats_in =
1246         stats_get(&stream->fpmb_stats);
1247 #endif
1248   }
1249
1250   stream->cx_time = 0;
1251   stream->nbytes = 0;
1252   stream->frames_out = 0;
1253 }
1254
1255
1256 static void initialize_encoder(struct stream_state *stream,
1257                                struct VpxEncoderConfig *global) {
1258   int i;
1259   int flags = 0;
1260
1261   flags |= global->show_psnr ? VPX_CODEC_USE_PSNR : 0;
1262   flags |= global->out_part ? VPX_CODEC_USE_OUTPUT_PARTITION : 0;
1263
1264   /* Construct Encoder Context */
1265   vpx_codec_enc_init(&stream->encoder, global->codec->interface(),
1266                      &stream->config.cfg, flags);
1267   ctx_exit_on_error(&stream->encoder, "Failed to initialize encoder");
1268
1269   /* Note that we bypass the vpx_codec_control wrapper macro because
1270    * we're being clever to store the control IDs in an array. Real
1271    * applications will want to make use of the enumerations directly
1272    */
1273   for (i = 0; i < stream->config.arg_ctrl_cnt; i++) {
1274     int ctrl = stream->config.arg_ctrls[i][0];
1275     int value = stream->config.arg_ctrls[i][1];
1276     if (vpx_codec_control_(&stream->encoder, ctrl, value))
1277       fprintf(stderr, "Error: Tried to set control %d = %d\n",
1278               ctrl, value);
1279
1280     ctx_exit_on_error(&stream->encoder, "Failed to control codec");
1281   }
1282
1283 #if CONFIG_DECODERS
1284   if (global->test_decode != TEST_DECODE_OFF) {
1285     const VpxInterface *decoder = get_vpx_decoder_by_name(global->codec->name);
1286     vpx_codec_dec_init(&stream->decoder, decoder->interface(), NULL, 0);
1287   }
1288 #endif
1289 }
1290
1291
1292 static void encode_frame(struct stream_state *stream,
1293                          struct VpxEncoderConfig *global,
1294                          struct vpx_image *img,
1295                          unsigned int frames_in) {
1296   vpx_codec_pts_t frame_start, next_frame_start;
1297   struct vpx_codec_enc_cfg *cfg = &stream->config.cfg;
1298   struct vpx_usec_timer timer;
1299
1300   frame_start = (cfg->g_timebase.den * (int64_t)(frames_in - 1)
1301                  * global->framerate.den)
1302                 / cfg->g_timebase.num / global->framerate.num;
1303   next_frame_start = (cfg->g_timebase.den * (int64_t)(frames_in)
1304                       * global->framerate.den)
1305                      / cfg->g_timebase.num / global->framerate.num;
1306
1307   /* Scale if necessary */
1308   if (img && (img->d_w != cfg->g_w || img->d_h != cfg->g_h)) {
1309     if (img->fmt != VPX_IMG_FMT_I420 && img->fmt != VPX_IMG_FMT_YV12) {
1310       fprintf(stderr, "%s can only scale 4:2:0 8bpp inputs\n", exec_name);
1311       exit(EXIT_FAILURE);
1312     }
1313 #if CONFIG_LIBYUV
1314     if (!stream->img)
1315       stream->img = vpx_img_alloc(NULL, VPX_IMG_FMT_I420,
1316                                   cfg->g_w, cfg->g_h, 16);
1317     I420Scale(img->planes[VPX_PLANE_Y], img->stride[VPX_PLANE_Y],
1318               img->planes[VPX_PLANE_U], img->stride[VPX_PLANE_U],
1319               img->planes[VPX_PLANE_V], img->stride[VPX_PLANE_V],
1320               img->d_w, img->d_h,
1321               stream->img->planes[VPX_PLANE_Y],
1322               stream->img->stride[VPX_PLANE_Y],
1323               stream->img->planes[VPX_PLANE_U],
1324               stream->img->stride[VPX_PLANE_U],
1325               stream->img->planes[VPX_PLANE_V],
1326               stream->img->stride[VPX_PLANE_V],
1327               stream->img->d_w, stream->img->d_h,
1328               kFilterBox);
1329     img = stream->img;
1330 #else
1331     stream->encoder.err = 1;
1332     ctx_exit_on_error(&stream->encoder,
1333                       "Stream %d: Failed to encode frame.\n"
1334                       "Scaling disabled in this configuration. \n"
1335                       "To enable, configure with --enable-libyuv\n",
1336                       stream->index);
1337 #endif
1338   }
1339
1340   vpx_usec_timer_start(&timer);
1341   vpx_codec_encode(&stream->encoder, img, frame_start,
1342                    (unsigned long)(next_frame_start - frame_start),
1343                    0, global->deadline);
1344   vpx_usec_timer_mark(&timer);
1345   stream->cx_time += vpx_usec_timer_elapsed(&timer);
1346   ctx_exit_on_error(&stream->encoder, "Stream %d: Failed to encode frame",
1347                     stream->index);
1348 }
1349
1350
1351 static void update_quantizer_histogram(struct stream_state *stream) {
1352   if (stream->config.cfg.g_pass != VPX_RC_FIRST_PASS) {
1353     int q;
1354
1355     vpx_codec_control(&stream->encoder, VP8E_GET_LAST_QUANTIZER_64, &q);
1356     ctx_exit_on_error(&stream->encoder, "Failed to read quantizer");
1357     stream->counts[q]++;
1358   }
1359 }
1360
1361
1362 static void get_cx_data(struct stream_state *stream,
1363                         struct VpxEncoderConfig *global,
1364                         int *got_data) {
1365   const vpx_codec_cx_pkt_t *pkt;
1366   const struct vpx_codec_enc_cfg *cfg = &stream->config.cfg;
1367   vpx_codec_iter_t iter = NULL;
1368
1369   *got_data = 0;
1370   while ((pkt = vpx_codec_get_cx_data(&stream->encoder, &iter))) {
1371     static size_t fsize = 0;
1372     static int64_t ivf_header_pos = 0;
1373
1374     switch (pkt->kind) {
1375       case VPX_CODEC_CX_FRAME_PKT:
1376         if (!(pkt->data.frame.flags & VPX_FRAME_IS_FRAGMENT)) {
1377           stream->frames_out++;
1378         }
1379         if (!global->quiet)
1380           fprintf(stderr, " %6luF", (unsigned long)pkt->data.frame.sz);
1381
1382         update_rate_histogram(stream->rate_hist, cfg, pkt);
1383 #if CONFIG_WEBM_IO
1384         if (stream->config.write_webm) {
1385           write_webm_block(&stream->ebml, cfg, pkt);
1386         }
1387 #endif
1388         if (!stream->config.write_webm) {
1389           if (pkt->data.frame.partition_id <= 0) {
1390             ivf_header_pos = ftello(stream->file);
1391             fsize = pkt->data.frame.sz;
1392
1393             ivf_write_frame_header(stream->file, pkt->data.frame.pts, fsize);
1394           } else {
1395             fsize += pkt->data.frame.sz;
1396
1397             if (!(pkt->data.frame.flags & VPX_FRAME_IS_FRAGMENT)) {
1398               const int64_t currpos = ftello(stream->file);
1399               fseeko(stream->file, ivf_header_pos, SEEK_SET);
1400               ivf_write_frame_size(stream->file, fsize);
1401               fseeko(stream->file, currpos, SEEK_SET);
1402             }
1403           }
1404
1405           (void) fwrite(pkt->data.frame.buf, 1, pkt->data.frame.sz,
1406                         stream->file);
1407         }
1408         stream->nbytes += pkt->data.raw.sz;
1409
1410         *got_data = 1;
1411 #if CONFIG_DECODERS
1412         if (global->test_decode != TEST_DECODE_OFF && !stream->mismatch_seen) {
1413           vpx_codec_decode(&stream->decoder, pkt->data.frame.buf,
1414                            (unsigned int)pkt->data.frame.sz, NULL, 0);
1415           if (stream->decoder.err) {
1416             warn_or_exit_on_error(&stream->decoder,
1417                                   global->test_decode == TEST_DECODE_FATAL,
1418                                   "Failed to decode frame %d in stream %d",
1419                                   stream->frames_out + 1, stream->index);
1420             stream->mismatch_seen = stream->frames_out + 1;
1421           }
1422         }
1423 #endif
1424         break;
1425       case VPX_CODEC_STATS_PKT:
1426         stream->frames_out++;
1427         stats_write(&stream->stats,
1428                     pkt->data.twopass_stats.buf,
1429                     pkt->data.twopass_stats.sz);
1430         stream->nbytes += pkt->data.raw.sz;
1431         break;
1432 #if CONFIG_FP_MB_STATS
1433       case VPX_CODEC_FPMB_STATS_PKT:
1434         stats_write(&stream->fpmb_stats,
1435                     pkt->data.firstpass_mb_stats.buf,
1436                     pkt->data.firstpass_mb_stats.sz);
1437         stream->nbytes += pkt->data.raw.sz;
1438         break;
1439 #endif
1440       case VPX_CODEC_PSNR_PKT:
1441
1442         if (global->show_psnr) {
1443           int i;
1444
1445           stream->psnr_sse_total += pkt->data.psnr.sse[0];
1446           stream->psnr_samples_total += pkt->data.psnr.samples[0];
1447           for (i = 0; i < 4; i++) {
1448             if (!global->quiet)
1449               fprintf(stderr, "%.3f ", pkt->data.psnr.psnr[i]);
1450             stream->psnr_totals[i] += pkt->data.psnr.psnr[i];
1451           }
1452           stream->psnr_count++;
1453         }
1454
1455         break;
1456       default:
1457         break;
1458     }
1459   }
1460 }
1461
1462
1463 static void show_psnr(struct stream_state  *stream) {
1464   int i;
1465   double ovpsnr;
1466
1467   if (!stream->psnr_count)
1468     return;
1469
1470   fprintf(stderr, "Stream %d PSNR (Overall/Avg/Y/U/V)", stream->index);
1471   ovpsnr = sse_to_psnr((double)stream->psnr_samples_total, 255.0,
1472                        (double)stream->psnr_sse_total);
1473   fprintf(stderr, " %.3f", ovpsnr);
1474
1475   for (i = 0; i < 4; i++) {
1476     fprintf(stderr, " %.3f", stream->psnr_totals[i] / stream->psnr_count);
1477   }
1478   fprintf(stderr, "\n");
1479 }
1480
1481
1482 static float usec_to_fps(uint64_t usec, unsigned int frames) {
1483   return (float)(usec > 0 ? frames * 1000000.0 / (float)usec : 0);
1484 }
1485
1486
1487 static void test_decode(struct stream_state  *stream,
1488                         enum TestDecodeFatality fatal,
1489                         const VpxInterface *codec) {
1490   vpx_image_t enc_img, dec_img;
1491
1492   if (stream->mismatch_seen)
1493     return;
1494
1495   /* Get the internal reference frame */
1496   if (strcmp(codec->name, "vp8") == 0) {
1497     struct vpx_ref_frame ref_enc, ref_dec;
1498     int width, height;
1499
1500     width = (stream->config.cfg.g_w + 15) & ~15;
1501     height = (stream->config.cfg.g_h + 15) & ~15;
1502     vpx_img_alloc(&ref_enc.img, VPX_IMG_FMT_I420, width, height, 1);
1503     enc_img = ref_enc.img;
1504     vpx_img_alloc(&ref_dec.img, VPX_IMG_FMT_I420, width, height, 1);
1505     dec_img = ref_dec.img;
1506
1507     ref_enc.frame_type = VP8_LAST_FRAME;
1508     ref_dec.frame_type = VP8_LAST_FRAME;
1509     vpx_codec_control(&stream->encoder, VP8_COPY_REFERENCE, &ref_enc);
1510     vpx_codec_control(&stream->decoder, VP8_COPY_REFERENCE, &ref_dec);
1511   } else {
1512     struct vp9_ref_frame ref;
1513
1514     ref.idx = 0;
1515     vpx_codec_control(&stream->encoder, VP9_GET_REFERENCE, &ref);
1516     enc_img = ref.img;
1517     vpx_codec_control(&stream->decoder, VP9_GET_REFERENCE, &ref);
1518     dec_img = ref.img;
1519   }
1520   ctx_exit_on_error(&stream->encoder, "Failed to get encoder reference frame");
1521   ctx_exit_on_error(&stream->decoder, "Failed to get decoder reference frame");
1522
1523   if (!compare_img(&enc_img, &dec_img)) {
1524     int y[4], u[4], v[4];
1525     find_mismatch(&enc_img, &dec_img, y, u, v);
1526     stream->decoder.err = 1;
1527     warn_or_exit_on_error(&stream->decoder, fatal == TEST_DECODE_FATAL,
1528                           "Stream %d: Encode/decode mismatch on frame %d at"
1529                           " Y[%d, %d] {%d/%d},"
1530                           " U[%d, %d] {%d/%d},"
1531                           " V[%d, %d] {%d/%d}",
1532                           stream->index, stream->frames_out,
1533                           y[0], y[1], y[2], y[3],
1534                           u[0], u[1], u[2], u[3],
1535                           v[0], v[1], v[2], v[3]);
1536     stream->mismatch_seen = stream->frames_out;
1537   }
1538
1539   vpx_img_free(&enc_img);
1540   vpx_img_free(&dec_img);
1541 }
1542
1543
1544 static void print_time(const char *label, int64_t etl) {
1545   int64_t hours;
1546   int64_t mins;
1547   int64_t secs;
1548
1549   if (etl >= 0) {
1550     hours = etl / 3600;
1551     etl -= hours * 3600;
1552     mins = etl / 60;
1553     etl -= mins * 60;
1554     secs = etl;
1555
1556     fprintf(stderr, "[%3s %2"PRId64":%02"PRId64":%02"PRId64"] ",
1557             label, hours, mins, secs);
1558   } else {
1559     fprintf(stderr, "[%3s  unknown] ", label);
1560   }
1561 }
1562
1563
1564 int main(int argc, const char **argv_) {
1565   int pass;
1566   vpx_image_t raw;
1567   int frame_avail, got_data;
1568
1569   struct VpxInputContext input;
1570   struct VpxEncoderConfig global;
1571   struct stream_state *streams = NULL;
1572   char **argv, **argi;
1573   uint64_t cx_time = 0;
1574   int stream_cnt = 0;
1575   int res = 0;
1576
1577   memset(&input, 0, sizeof(input));
1578   exec_name = argv_[0];
1579
1580   if (argc < 3)
1581     usage_exit();
1582
1583   /* Setup default input stream settings */
1584   input.framerate.numerator = 30;
1585   input.framerate.denominator = 1;
1586   input.only_i420 = 1;
1587   input.bit_depth = 0;
1588
1589   /* First parse the global configuration values, because we want to apply
1590    * other parameters on top of the default configuration provided by the
1591    * codec.
1592    */
1593   argv = argv_dup(argc - 1, argv_ + 1);
1594   parse_global_config(&global, argv);
1595
1596   input.fmt = global.use_i420 ? VPX_IMG_FMT_I420 : VPX_IMG_FMT_YV12;
1597
1598   {
1599     /* Now parse each stream's parameters. Using a local scope here
1600      * due to the use of 'stream' as loop variable in FOREACH_STREAM
1601      * loops
1602      */
1603     struct stream_state *stream = NULL;
1604
1605     do {
1606       stream = new_stream(&global, stream);
1607       stream_cnt++;
1608       if (!streams)
1609         streams = stream;
1610     } while (parse_stream_params(&global, stream, argv));
1611   }
1612
1613   /* Check for unrecognized options */
1614   for (argi = argv; *argi; argi++)
1615     if (argi[0][0] == '-' && argi[0][1])
1616       die("Error: Unrecognized option %s\n", *argi);
1617
1618   FOREACH_STREAM(check_encoder_config(global.disable_warning_prompt,
1619                                       &global, &stream->config.cfg););
1620
1621   /* Handle non-option arguments */
1622   input.filename = argv[0];
1623
1624   if (!input.filename)
1625     usage_exit();
1626
1627   /* Decide if other chroma subsamplings than 4:2:0 are supported */
1628   if (global.codec->fourcc == VP9_FOURCC)
1629     input.only_i420 = 0;
1630
1631   for (pass = global.pass ? global.pass - 1 : 0; pass < global.passes; pass++) {
1632     int frames_in = 0, seen_frames = 0;
1633     int64_t estimated_time_left = -1;
1634     int64_t average_rate = -1;
1635     int64_t lagged_count = 0;
1636
1637     open_input_file(&input);
1638
1639     /* If the input file doesn't specify its w/h (raw files), try to get
1640      * the data from the first stream's configuration.
1641      */
1642     if (!input.width || !input.height)
1643       FOREACH_STREAM( {
1644       if (stream->config.cfg.g_w && stream->config.cfg.g_h) {
1645         input.width = stream->config.cfg.g_w;
1646         input.height = stream->config.cfg.g_h;
1647         break;
1648       }
1649     });
1650
1651     /* Update stream configurations from the input file's parameters */
1652     if (!input.width || !input.height)
1653       fatal("Specify stream dimensions with --width (-w) "
1654             " and --height (-h)");
1655     FOREACH_STREAM(set_stream_dimensions(stream, input.width, input.height));
1656     FOREACH_STREAM(validate_stream_config(stream, &global));
1657
1658     /* Ensure that --passes and --pass are consistent. If --pass is set and
1659      * --passes=2, ensure --fpf was set.
1660      */
1661     if (global.pass && global.passes == 2)
1662       FOREACH_STREAM( {
1663       if (!stream->config.stats_fn)
1664         die("Stream %d: Must specify --fpf when --pass=%d"
1665         " and --passes=2\n", stream->index, global.pass);
1666     });
1667
1668 #if !CONFIG_WEBM_IO
1669     FOREACH_STREAM({
1670       stream->config.write_webm = 0;
1671       warn("vpxenc was compiled without WebM container support."
1672            "Producing IVF output");
1673     });
1674 #endif
1675
1676     /* Use the frame rate from the file only if none was specified
1677      * on the command-line.
1678      */
1679     if (!global.have_framerate) {
1680       global.framerate.num = input.framerate.numerator;
1681       global.framerate.den = input.framerate.denominator;
1682     }
1683
1684     FOREACH_STREAM(set_default_kf_interval(stream, &global));
1685
1686     /* Show configuration */
1687     if (global.verbose && pass == 0)
1688       FOREACH_STREAM(show_stream_config(stream, &global, &input));
1689
1690     if (pass == (global.pass ? global.pass - 1 : 0)) {
1691       if (input.file_type == FILE_TYPE_Y4M)
1692         /*The Y4M reader does its own allocation.
1693           Just initialize this here to avoid problems if we never read any
1694            frames.*/
1695         memset(&raw, 0, sizeof(raw));
1696       else
1697         vpx_img_alloc(&raw, input.fmt, input.width, input.height, 32);
1698
1699       FOREACH_STREAM(stream->rate_hist =
1700                          init_rate_histogram(&stream->config.cfg,
1701                                              &global.framerate));
1702     }
1703
1704     FOREACH_STREAM(setup_pass(stream, &global, pass));
1705     FOREACH_STREAM(open_output_file(stream, &global));
1706     FOREACH_STREAM(initialize_encoder(stream, &global));
1707
1708     frame_avail = 1;
1709     got_data = 0;
1710
1711     while (frame_avail || got_data) {
1712       struct vpx_usec_timer timer;
1713
1714       if (!global.limit || frames_in < global.limit) {
1715         frame_avail = read_frame(&input, &raw);
1716
1717         if (frame_avail)
1718           frames_in++;
1719         seen_frames = frames_in > global.skip_frames ?
1720                           frames_in - global.skip_frames : 0;
1721
1722         if (!global.quiet) {
1723           float fps = usec_to_fps(cx_time, seen_frames);
1724           fprintf(stderr, "\rPass %d/%d ", pass + 1, global.passes);
1725
1726           if (stream_cnt == 1)
1727             fprintf(stderr,
1728                     "frame %4d/%-4d %7"PRId64"B ",
1729                     frames_in, streams->frames_out, (int64_t)streams->nbytes);
1730           else
1731             fprintf(stderr, "frame %4d ", frames_in);
1732
1733           fprintf(stderr, "%7"PRId64" %s %.2f %s ",
1734                   cx_time > 9999999 ? cx_time / 1000 : cx_time,
1735                   cx_time > 9999999 ? "ms" : "us",
1736                   fps >= 1.0 ? fps : fps * 60,
1737                   fps >= 1.0 ? "fps" : "fpm");
1738           print_time("ETA", estimated_time_left);
1739         }
1740
1741       } else
1742         frame_avail = 0;
1743
1744       if (frames_in > global.skip_frames) {
1745         vpx_usec_timer_start(&timer);
1746         FOREACH_STREAM(encode_frame(stream, &global,
1747                                     frame_avail ? &raw : NULL,
1748                                     frames_in));
1749         vpx_usec_timer_mark(&timer);
1750         cx_time += vpx_usec_timer_elapsed(&timer);
1751
1752         FOREACH_STREAM(update_quantizer_histogram(stream));
1753
1754         got_data = 0;
1755         FOREACH_STREAM(get_cx_data(stream, &global, &got_data));
1756
1757         if (!got_data && input.length && !streams->frames_out) {
1758           lagged_count = global.limit ? seen_frames : ftello(input.file);
1759         } else if (input.length) {
1760           int64_t remaining;
1761           int64_t rate;
1762
1763           if (global.limit) {
1764             const int64_t frame_in_lagged = (seen_frames - lagged_count) * 1000;
1765
1766             rate = cx_time ? frame_in_lagged * (int64_t)1000000 / cx_time : 0;
1767             remaining = 1000 * (global.limit - global.skip_frames
1768                                 - seen_frames + lagged_count);
1769           } else {
1770             const int64_t input_pos = ftello(input.file);
1771             const int64_t input_pos_lagged = input_pos - lagged_count;
1772             const int64_t limit = input.length;
1773
1774             rate = cx_time ? input_pos_lagged * (int64_t)1000000 / cx_time : 0;
1775             remaining = limit - input_pos + lagged_count;
1776           }
1777
1778           average_rate = (average_rate <= 0)
1779               ? rate
1780               : (average_rate * 7 + rate) / 8;
1781           estimated_time_left = average_rate ? remaining / average_rate : -1;
1782         }
1783
1784         if (got_data && global.test_decode != TEST_DECODE_OFF)
1785           FOREACH_STREAM(test_decode(stream, global.test_decode, global.codec));
1786       }
1787
1788       fflush(stdout);
1789       if (!global.quiet)
1790         fprintf(stderr, "\033[K");
1791     }
1792
1793     if (stream_cnt > 1)
1794       fprintf(stderr, "\n");
1795
1796     if (!global.quiet)
1797       FOREACH_STREAM(fprintf(
1798                        stderr,
1799                        "\rPass %d/%d frame %4d/%-4d %7"PRId64"B %7lub/f %7"PRId64"b/s"
1800                        " %7"PRId64" %s (%.2f fps)\033[K\n", pass + 1,
1801                        global.passes, frames_in, stream->frames_out, (int64_t)stream->nbytes,
1802                        seen_frames ? (unsigned long)(stream->nbytes * 8 / seen_frames) : 0,
1803                        seen_frames ? (int64_t)stream->nbytes * 8
1804                        * (int64_t)global.framerate.num / global.framerate.den
1805                        / seen_frames
1806                        : 0,
1807                        stream->cx_time > 9999999 ? stream->cx_time / 1000 : stream->cx_time,
1808                        stream->cx_time > 9999999 ? "ms" : "us",
1809                        usec_to_fps(stream->cx_time, seen_frames));
1810                     );
1811
1812     if (global.show_psnr)
1813       FOREACH_STREAM(show_psnr(stream));
1814
1815     FOREACH_STREAM(vpx_codec_destroy(&stream->encoder));
1816
1817     if (global.test_decode != TEST_DECODE_OFF) {
1818       FOREACH_STREAM(vpx_codec_destroy(&stream->decoder));
1819     }
1820
1821     close_input_file(&input);
1822
1823     if (global.test_decode == TEST_DECODE_FATAL) {
1824       FOREACH_STREAM(res |= stream->mismatch_seen);
1825     }
1826     FOREACH_STREAM(close_output_file(stream, global.codec->fourcc));
1827
1828     FOREACH_STREAM(stats_close(&stream->stats, global.passes - 1));
1829
1830 #if CONFIG_FP_MB_STATS
1831     FOREACH_STREAM(stats_close(&stream->fpmb_stats, global.passes - 1));
1832 #endif
1833
1834     if (global.pass)
1835       break;
1836   }
1837
1838   if (global.show_q_hist_buckets)
1839     FOREACH_STREAM(show_q_histogram(stream->counts,
1840                                     global.show_q_hist_buckets));
1841
1842   if (global.show_rate_hist_buckets)
1843     FOREACH_STREAM(show_rate_histogram(stream->rate_hist,
1844                                        &stream->config.cfg,
1845                                        global.show_rate_hist_buckets));
1846   FOREACH_STREAM(destroy_rate_histogram(stream->rate_hist));
1847
1848 #if CONFIG_INTERNAL_STATS
1849   /* TODO(jkoleszar): This doesn't belong in this executable. Do it for now,
1850    * to match some existing utilities.
1851    */
1852   if (!(global.pass == 1 && global.passes == 2))
1853     FOREACH_STREAM({
1854       FILE *f = fopen("opsnr.stt", "a");
1855       if (stream->mismatch_seen) {
1856         fprintf(f, "First mismatch occurred in frame %d\n",
1857                 stream->mismatch_seen);
1858       } else {
1859         fprintf(f, "No mismatch detected in recon buffers\n");
1860       }
1861       fclose(f);
1862     });
1863 #endif
1864
1865   vpx_img_free(&raw);
1866   free(argv);
1867   free(streams);
1868   return res ? EXIT_FAILURE : EXIT_SUCCESS;
1869 }