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