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