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