]> granicus.if.org Git - libvpx/blob - ivfenc.c
setup experimental infrastructure
[libvpx] / ivfenc.c
1 /*
2  *  Copyright (c) 2010 The VP8 project authors. All Rights Reserved.
3  *
4  *  Use of this source code is governed by a BSD-style license and patent
5  *  grant that can be found in the LICENSE file in the root of the source
6  *  tree. All contributing project authors may be found in the AUTHORS
7  *  file in the root of the source tree.
8  */
9
10
11 /* This is a simple program that encodes YV12 files and generates ivf
12  * files using the new interface.
13  */
14 #if defined(_MSC_VER)
15 #define USE_POSIX_MMAP 0
16 #else
17 #define USE_POSIX_MMAP 1
18 #endif
19
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <stdarg.h>
23 #include <string.h>
24 #include "vpx/vpx_encoder.h"
25 #if USE_POSIX_MMAP
26 #include <sys/types.h>
27 #include <sys/stat.h>
28 #include <sys/mman.h>
29 #include <fcntl.h>
30 #include <unistd.h>
31 #endif
32 #include "vpx_config.h"
33 #include "vpx/vp8cx.h"
34 #include "vpx_ports/mem_ops.h"
35 #include "vpx_ports/vpx_timer.h"
36
37 static const char *exec_name;
38
39 static const struct codec_item
40 {
41     char const              *name;
42     const vpx_codec_iface_t *iface;
43     unsigned int             fourcc;
44 } codecs[] =
45 {
46 #if CONFIG_EXPERIMENTAL && CONFIG_VP8_ENCODER
47     {"vp8x",  &vpx_codec_vp8x_cx_algo, 0x78385056},
48 #endif
49 #if CONFIG_VP8_ENCODER
50     {"vp8",  &vpx_codec_vp8_cx_algo, 0x30385056},
51 #endif
52 };
53
54 static void usage_exit();
55
56 void die(const char *fmt, ...)
57 {
58     va_list ap;
59     va_start(ap, fmt);
60     vprintf(fmt, ap);
61     printf("\n");
62     usage_exit();
63 }
64
65 static void ctx_exit_on_error(vpx_codec_ctx_t *ctx, const char *s)
66 {
67     if (ctx->err)
68     {
69         const char *detail = vpx_codec_error_detail(ctx);
70
71         printf("%s: %s\n", s, vpx_codec_error(ctx));
72
73         if (detail)
74             printf("    %s\n", detail);
75
76         exit(EXIT_FAILURE);
77     }
78 }
79
80 /* This structure is used to abstract the different ways of handling
81  * first pass statistics.
82  */
83 typedef struct
84 {
85     vpx_fixed_buf_t buf;
86     int             pass;
87     FILE           *file;
88     char           *buf_ptr;
89     size_t          buf_alloc_sz;
90 } stats_io_t;
91
92 int stats_open_file(stats_io_t *stats, const char *fpf, int pass)
93 {
94     int res;
95
96     stats->pass = pass;
97
98     if (pass == 0)
99     {
100         stats->file = fopen(fpf, "wb");
101         stats->buf.sz = 0;
102         stats->buf.buf = NULL,
103                    res = (stats->file != NULL);
104     }
105     else
106     {
107 #if 0
108 #elif USE_POSIX_MMAP
109         struct stat stat_buf;
110         int fd;
111
112         fd = open(fpf, O_RDONLY);
113         stats->file = fdopen(fd, "rb");
114         fstat(fd, &stat_buf);
115         stats->buf.sz = stat_buf.st_size;
116         stats->buf.buf = mmap(NULL, stats->buf.sz, PROT_READ, MAP_PRIVATE,
117                               fd, 0);
118         res = (stats->buf.buf != NULL);
119 #else
120         size_t nbytes;
121
122         stats->file = fopen(fpf, "rb");
123
124         if (fseek(stats->file, 0, SEEK_END))
125         {
126             fprintf(stderr, "First-pass stats file must be seekable!\n");
127             exit(EXIT_FAILURE);
128         }
129
130         stats->buf.sz = stats->buf_alloc_sz = ftell(stats->file);
131         rewind(stats->file);
132
133         stats->buf.buf = malloc(stats->buf_alloc_sz);
134
135         if (!stats->buf.buf)
136         {
137             fprintf(stderr, "Failed to allocate first-pass stats buffer (%d bytes)\n",
138                     stats->buf_alloc_sz);
139             exit(EXIT_FAILURE);
140         }
141
142         nbytes = fread(stats->buf.buf, 1, stats->buf.sz, stats->file);
143         res = (nbytes == stats->buf.sz);
144 #endif
145     }
146
147     return res;
148 }
149
150 int stats_open_mem(stats_io_t *stats, int pass)
151 {
152     int res;
153     stats->pass = pass;
154
155     if (!pass)
156     {
157         stats->buf.sz = 0;
158         stats->buf_alloc_sz = 64 * 1024;
159         stats->buf.buf = malloc(stats->buf_alloc_sz);
160     }
161
162     stats->buf_ptr = stats->buf.buf;
163     res = (stats->buf.buf != NULL);
164     return res;
165 }
166
167
168 void stats_close(stats_io_t *stats)
169 {
170     if (stats->file)
171     {
172         if (stats->pass == 1)
173         {
174 #if 0
175 #elif USE_POSIX_MMAP
176             munmap(stats->buf.buf, stats->buf.sz);
177 #else
178             free(stats->buf.buf);
179 #endif
180         }
181
182         fclose(stats->file);
183         stats->file = NULL;
184     }
185     else
186     {
187         if (stats->pass == 1)
188             free(stats->buf.buf);
189     }
190 }
191
192 void stats_write(stats_io_t *stats, const void *pkt, size_t len)
193 {
194     if (stats->file)
195     {
196         fwrite(pkt, 1, len, stats->file);
197     }
198     else
199     {
200         if (stats->buf.sz + len > stats->buf_alloc_sz)
201         {
202             size_t  new_sz = stats->buf_alloc_sz + 64 * 1024;
203             char   *new_ptr = realloc(stats->buf.buf, new_sz);
204
205             if (new_ptr)
206             {
207                 stats->buf_ptr = new_ptr + (stats->buf_ptr - (char *)stats->buf.buf);
208                 stats->buf.buf = new_ptr;
209                 stats->buf_alloc_sz = new_sz;
210             } /* else ... */
211         }
212
213         memcpy(stats->buf_ptr, pkt, len);
214         stats->buf.sz += len;
215         stats->buf_ptr += len;
216     }
217 }
218
219 vpx_fixed_buf_t stats_get(stats_io_t *stats)
220 {
221     return stats->buf;
222 }
223
224 #define IVF_FRAME_HDR_SZ (4+8) /* 4 byte size + 8 byte timestamp */
225 static int read_frame(FILE *f, vpx_image_t *img, unsigned int is_ivf)
226 {
227     int plane = 0;
228
229     if (is_ivf)
230     {
231         char junk[IVF_FRAME_HDR_SZ];
232
233         /* Skip the frame header. We know how big the frame should be. See
234          * write_ivf_frame_header() for documentation on the frame header
235          * layout.
236          */
237         fread(junk, 1, IVF_FRAME_HDR_SZ, f);
238     }
239
240     for (plane = 0; plane < 3; plane++)
241     {
242         unsigned char *ptr;
243         int w = (plane ? (1 + img->d_w) / 2 : img->d_w);
244         int h = (plane ? (1 + img->d_h) / 2 : img->d_h);
245         int r;
246
247         /* Determine the correct plane based on the image format. The for-loop
248          * always counts in Y,U,V order, but this may not match the order of
249          * the data on disk.
250          */
251         switch (plane)
252         {
253         case 1:
254             ptr = img->planes[img->fmt==VPX_IMG_FMT_YV12? VPX_PLANE_V : VPX_PLANE_U];
255             break;
256         case 2:
257             ptr = img->planes[img->fmt==VPX_IMG_FMT_YV12?VPX_PLANE_U : VPX_PLANE_V];
258             break;
259         default:
260             ptr = img->planes[plane];
261         }
262
263         for (r = 0; r < h; r++)
264         {
265             fread(ptr, 1, w, f);
266             ptr += img->stride[plane];
267         }
268     }
269
270     return !feof(f);
271 }
272
273
274 #define IVF_FILE_HDR_SZ (32)
275 unsigned int file_is_ivf(FILE *infile,
276                          unsigned int *fourcc,
277                          unsigned int *width,
278                          unsigned int *height)
279 {
280     char raw_hdr[IVF_FILE_HDR_SZ];
281     int is_ivf = 0;
282
283     /* See write_ivf_file_header() for more documentation on the file header
284      * layout.
285      */
286     if (fread(raw_hdr, 1, IVF_FILE_HDR_SZ, infile) == IVF_FILE_HDR_SZ)
287     {
288         if (raw_hdr[0] == 'D' && raw_hdr[1] == 'K'
289             && raw_hdr[2] == 'I' && raw_hdr[3] == 'F')
290         {
291             is_ivf = 1;
292
293             if (mem_get_le16(raw_hdr + 4) != 0)
294                 fprintf(stderr, "Error: Unrecognized IVF version! This file may not"
295                         " decode properly.");
296
297             *fourcc = mem_get_le32(raw_hdr + 8);
298         }
299     }
300
301     if (is_ivf)
302     {
303         *width = mem_get_le16(raw_hdr + 12);
304         *height = mem_get_le16(raw_hdr + 14);
305     }
306     else
307         rewind(infile);
308
309     return is_ivf;
310 }
311
312
313 static void write_ivf_file_header(FILE *outfile,
314                                   const vpx_codec_enc_cfg_t *cfg,
315                                   unsigned int fourcc,
316                                   int frame_cnt)
317 {
318     char header[32];
319
320     if (cfg->g_pass != VPX_RC_ONE_PASS && cfg->g_pass != VPX_RC_LAST_PASS)
321         return;
322
323     header[0] = 'D';
324     header[1] = 'K';
325     header[2] = 'I';
326     header[3] = 'F';
327     mem_put_le16(header + 4,  0);                 /* version */
328     mem_put_le16(header + 6,  32);                /* headersize */
329     mem_put_le32(header + 8,  fourcc);            /* headersize */
330     mem_put_le16(header + 12, cfg->g_w);          /* width */
331     mem_put_le16(header + 14, cfg->g_h);          /* height */
332     mem_put_le32(header + 16, cfg->g_timebase.den); /* rate */
333     mem_put_le32(header + 20, cfg->g_timebase.num); /* scale */
334     mem_put_le32(header + 24, frame_cnt);         /* length */
335     mem_put_le32(header + 28, 0);                 /* unused */
336
337     fwrite(header, 1, 32, outfile);
338 }
339
340
341 static void write_ivf_frame_header(FILE *outfile,
342                                    const vpx_codec_cx_pkt_t *pkt)
343 {
344     char             header[12];
345     vpx_codec_pts_t  pts;
346
347     if (pkt->kind != VPX_CODEC_CX_FRAME_PKT)
348         return;
349
350     pts = pkt->data.frame.pts;
351     mem_put_le32(header, pkt->data.frame.sz);
352     mem_put_le32(header + 4, pts & 0xFFFFFFFF);
353     mem_put_le32(header + 8, pts >> 32);
354
355     fwrite(header, 1, 12, outfile);
356 }
357
358 #include "args.h"
359
360 static const arg_def_t use_yv12 = ARG_DEF(NULL, "yv12", 0,
361                                   "Input file is YV12 ");
362 static const arg_def_t use_i420 = ARG_DEF(NULL, "i420", 0,
363                                   "Input file is I420 (default)");
364 static const arg_def_t codecarg = ARG_DEF(NULL, "codec", 1,
365                                   "Codec to use");
366 static const arg_def_t passes           = ARG_DEF("p", "passes", 1,
367         "Number of passes (1/2)");
368 static const arg_def_t pass_arg         = ARG_DEF(NULL, "pass", 1,
369         "Pass to execute (1/2)");
370 static const arg_def_t fpf_name         = ARG_DEF(NULL, "fpf", 1,
371         "First pass statistics file name");
372 static const arg_def_t limit = ARG_DEF(NULL, "limit", 1,
373                                        "Stop encoding after n input frames");
374 static const arg_def_t deadline         = ARG_DEF("d", "deadline", 1,
375         "Deadline per frame (usec)");
376 static const arg_def_t best_dl          = ARG_DEF(NULL, "best", 0,
377         "Use Best Quality Deadline");
378 static const arg_def_t good_dl          = ARG_DEF(NULL, "good", 0,
379         "Use Good Quality Deadline");
380 static const arg_def_t rt_dl            = ARG_DEF(NULL, "rt", 0,
381         "Use Realtime Quality Deadline");
382 static const arg_def_t verbosearg       = ARG_DEF("v", "verbose", 0,
383         "Show encoder parameters");
384 static const arg_def_t psnrarg          = ARG_DEF(NULL, "psnr", 0,
385         "Show PSNR in status line");
386 static const arg_def_t *main_args[] =
387 {
388     &codecarg, &passes, &pass_arg, &fpf_name, &limit, &deadline, &best_dl, &good_dl, &rt_dl,
389     &verbosearg, &psnrarg,
390     NULL
391 };
392
393 static const arg_def_t usage            = ARG_DEF("u", "usage", 1,
394         "Usage profile number to use");
395 static const arg_def_t threads          = ARG_DEF("t", "threads", 1,
396         "Max number of threads to use");
397 static const arg_def_t profile          = ARG_DEF(NULL, "profile", 1,
398         "Bitstream profile number to use");
399 static const arg_def_t width            = ARG_DEF("w", "width", 1,
400         "Frame width");
401 static const arg_def_t height           = ARG_DEF("h", "height", 1,
402         "Frame height");
403 static const arg_def_t timebase         = ARG_DEF(NULL, "timebase", 1,
404         "Stream timebase (frame duration)");
405 static const arg_def_t error_resilient  = ARG_DEF(NULL, "error-resilient", 1,
406         "Enable error resiliency features");
407 static const arg_def_t lag_in_frames    = ARG_DEF(NULL, "lag-in-frames", 1,
408         "Max number of frames to lag");
409
410 static const arg_def_t *global_args[] =
411 {
412     &use_yv12, &use_i420, &usage, &threads, &profile,
413     &width, &height, &timebase, &error_resilient,
414     &lag_in_frames, NULL
415 };
416
417 static const arg_def_t dropframe_thresh   = ARG_DEF(NULL, "drop-frame", 1,
418         "Temporal resampling threshold (buf %)");
419 static const arg_def_t resize_allowed     = ARG_DEF(NULL, "resize-allowed", 1,
420         "Spatial resampling enabled (bool)");
421 static const arg_def_t resize_up_thresh   = ARG_DEF(NULL, "resize-up", 1,
422         "Upscale threshold (buf %)");
423 static const arg_def_t resize_down_thresh = ARG_DEF(NULL, "resize-down", 1,
424         "Downscale threshold (buf %)");
425 static const arg_def_t end_usage          = ARG_DEF(NULL, "end-usage", 1,
426         "VBR=0 | CBR=1");
427 static const arg_def_t target_bitrate     = ARG_DEF(NULL, "target-bitrate", 1,
428         "Bitrate (kbps)");
429 static const arg_def_t min_quantizer      = ARG_DEF(NULL, "min-q", 1,
430         "Minimum (best) quantizer");
431 static const arg_def_t max_quantizer      = ARG_DEF(NULL, "max-q", 1,
432         "Maximum (worst) quantizer");
433 static const arg_def_t undershoot_pct     = ARG_DEF(NULL, "undershoot-pct", 1,
434         "Datarate undershoot (min) target (%)");
435 static const arg_def_t overshoot_pct      = ARG_DEF(NULL, "overshoot-pct", 1,
436         "Datarate overshoot (max) target (%)");
437 static const arg_def_t buf_sz             = ARG_DEF(NULL, "buf-sz", 1,
438         "Client buffer size (ms)");
439 static const arg_def_t buf_initial_sz     = ARG_DEF(NULL, "buf-initial-sz", 1,
440         "Client initial buffer size (ms)");
441 static const arg_def_t buf_optimal_sz     = ARG_DEF(NULL, "buf-optimal-sz", 1,
442         "Client optimal buffer size (ms)");
443 static const arg_def_t *rc_args[] =
444 {
445     &dropframe_thresh, &resize_allowed, &resize_up_thresh, &resize_down_thresh,
446     &end_usage, &target_bitrate, &min_quantizer, &max_quantizer,
447     &undershoot_pct, &overshoot_pct, &buf_sz, &buf_initial_sz, &buf_optimal_sz,
448     NULL
449 };
450
451
452 static const arg_def_t bias_pct = ARG_DEF(NULL, "bias-pct", 1,
453                                   "CBR/VBR bias (0=CBR, 100=VBR)");
454 static const arg_def_t minsection_pct = ARG_DEF(NULL, "minsection-pct", 1,
455                                         "GOP min bitrate (% of target)");
456 static const arg_def_t maxsection_pct = ARG_DEF(NULL, "maxsection-pct", 1,
457                                         "GOP max bitrate (% of target)");
458 static const arg_def_t *rc_twopass_args[] =
459 {
460     &bias_pct, &minsection_pct, &maxsection_pct, NULL
461 };
462
463
464 static const arg_def_t kf_min_dist = ARG_DEF(NULL, "kf-min-dist", 1,
465                                      "Minimum keyframe interval (frames)");
466 static const arg_def_t kf_max_dist = ARG_DEF(NULL, "kf-max-dist", 1,
467                                      "Maximum keyframe interval (frames)");
468 static const arg_def_t *kf_args[] =
469 {
470     &kf_min_dist, &kf_max_dist, NULL
471 };
472
473
474 #if CONFIG_VP8_ENCODER
475 static const arg_def_t noise_sens = ARG_DEF(NULL, "noise-sensitivity", 1,
476                                     "Noise sensitivity (frames to blur)");
477 static const arg_def_t sharpness = ARG_DEF(NULL, "sharpness", 1,
478                                    "Filter sharpness (0-7)");
479 static const arg_def_t static_thresh = ARG_DEF(NULL, "static-thresh", 1,
480                                        "Motion detection threshold");
481 #endif
482
483 #if CONFIG_VP8_ENCODER
484 static const arg_def_t cpu_used = ARG_DEF(NULL, "cpu-used", 1,
485                                   "CPU Used (-16..16)");
486 #endif
487
488
489 #if CONFIG_VP8_ENCODER
490 static const arg_def_t token_parts = ARG_DEF(NULL, "token-parts", 1,
491                                      "Number of token partitions to use, log2");
492 static const arg_def_t auto_altref = ARG_DEF(NULL, "auto-alt-ref", 1,
493                                      "Enable automatic alt reference frames");
494 static const arg_def_t arnr_maxframes = ARG_DEF(NULL, "arnr-maxframes", 1,
495                                         "alt_ref Max Frames");
496 static const arg_def_t arnr_strength = ARG_DEF(NULL, "arnr-strength", 1,
497                                        "alt_ref Strength");
498 static const arg_def_t arnr_type = ARG_DEF(NULL, "arnr-type", 1,
499                                    "alt_ref Type");
500
501 static const arg_def_t *vp8_args[] =
502 {
503     &cpu_used, &auto_altref, &noise_sens, &sharpness, &static_thresh,
504     &token_parts, &arnr_maxframes, &arnr_strength, &arnr_type, NULL
505 };
506 static const int vp8_arg_ctrl_map[] =
507 {
508     VP8E_SET_CPUUSED, VP8E_SET_ENABLEAUTOALTREF,
509     VP8E_SET_NOISE_SENSITIVITY, VP8E_SET_SHARPNESS, VP8E_SET_STATIC_THRESHOLD,
510     VP8E_SET_TOKEN_PARTITIONS,
511     VP8E_SET_ARNR_MAXFRAMES, VP8E_SET_ARNR_STRENGTH , VP8E_SET_ARNR_TYPE, 0
512 };
513 #endif
514
515 static const arg_def_t *no_args[] = { NULL };
516
517 static void usage_exit()
518 {
519     int i;
520
521     printf("Usage: %s <options> src_filename dst_filename\n", exec_name);
522
523     printf("\n_options:\n");
524     arg_show_usage(stdout, main_args);
525     printf("\n_encoder Global Options:\n");
526     arg_show_usage(stdout, global_args);
527     printf("\n_rate Control Options:\n");
528     arg_show_usage(stdout, rc_args);
529     printf("\n_twopass Rate Control Options:\n");
530     arg_show_usage(stdout, rc_twopass_args);
531     printf("\n_keyframe Placement Options:\n");
532     arg_show_usage(stdout, kf_args);
533 #if CONFIG_VP8_ENCODER
534     printf("\n_vp8 Specific Options:\n");
535     arg_show_usage(stdout, vp8_args);
536 #endif
537     printf("\n"
538            "Included encoders:\n"
539            "\n");
540
541     for (i = 0; i < sizeof(codecs) / sizeof(codecs[0]); i++)
542         printf("    %-6s - %s\n",
543                codecs[i].name,
544                vpx_codec_iface_name(codecs[i].iface));
545
546     exit(EXIT_FAILURE);
547 }
548
549 #define ARG_CTRL_CNT_MAX 10
550
551
552 int main(int argc, const char **argv_)
553 {
554     vpx_codec_ctx_t        encoder;
555     const char                  *in_fn = NULL, *out_fn = NULL, *stats_fn = NULL;
556     int                    i;
557     FILE                  *infile, *outfile;
558     vpx_codec_enc_cfg_t    cfg;
559     vpx_codec_err_t        res;
560     int                    pass, one_pass_only = 0;
561     stats_io_t             stats;
562     vpx_image_t            raw;
563     const struct codec_item  *codec = codecs;
564     int                    frame_avail, got_data;
565
566     struct arg               arg;
567     char                   **argv, **argi, **argj;
568     int                      arg_usage = 0, arg_passes = 1, arg_deadline = 0;
569     int                      arg_ctrls[ARG_CTRL_CNT_MAX][2], arg_ctrl_cnt = 0;
570     int                      arg_limit = 0;
571     static const arg_def_t **ctrl_args = no_args;
572     static const int        *ctrl_args_map = NULL;
573     int                      verbose = 0, show_psnr = 0;
574     int                      arg_use_i420 = 1;
575     unsigned long            cx_time = 0;
576     unsigned int             is_ivf, fourcc;
577
578     exec_name = argv_[0];
579
580     if (argc < 3)
581         usage_exit();
582
583
584     /* First parse the codec and usage values, because we want to apply other
585      * parameters on top of the default configuration provided by the codec.
586      */
587     argv = argv_dup(argc - 1, argv_ + 1);
588
589     for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step)
590     {
591         arg.argv_step = 1;
592
593         if (arg_match(&arg, &codecarg, argi))
594         {
595             int j, k = -1;
596
597             for (j = 0; j < sizeof(codecs) / sizeof(codecs[0]); j++)
598                 if (!strcmp(codecs[j].name, arg.val))
599                     k = j;
600
601             if (k >= 0)
602                 codec = codecs + k;
603             else
604                 die("Error: Unrecognized argument (%s) to --codec\n",
605                     arg.val);
606
607         }
608         else if (arg_match(&arg, &passes, argi))
609         {
610             arg_passes = arg_parse_uint(&arg);
611
612             if (arg_passes < 1 || arg_passes > 2)
613                 die("Error: Invalid number of passes (%d)\n", arg_passes);
614         }
615         else if (arg_match(&arg, &pass_arg, argi))
616         {
617             one_pass_only = arg_parse_uint(&arg);
618
619             if (one_pass_only < 1 || one_pass_only > 2)
620                 die("Error: Invalid pass selected (%d)\n", one_pass_only);
621         }
622         else if (arg_match(&arg, &fpf_name, argi))
623             stats_fn = arg.val;
624         else if (arg_match(&arg, &usage, argi))
625             arg_usage = arg_parse_uint(&arg);
626         else if (arg_match(&arg, &deadline, argi))
627             arg_deadline = arg_parse_uint(&arg);
628         else if (arg_match(&arg, &best_dl, argi))
629             arg_deadline = VPX_DL_BEST_QUALITY;
630         else if (arg_match(&arg, &good_dl, argi))
631             arg_deadline = VPX_DL_GOOD_QUALITY;
632         else if (arg_match(&arg, &rt_dl, argi))
633             arg_deadline = VPX_DL_REALTIME;
634         else if (arg_match(&arg, &use_yv12, argi))
635         {
636             arg_use_i420 = 0;
637         }
638         else if (arg_match(&arg, &use_i420, argi))
639         {
640             arg_use_i420 = 1;
641         }
642         else if (arg_match(&arg, &verbosearg, argi))
643             verbose = 1;
644         else if (arg_match(&arg, &limit, argi))
645             arg_limit = arg_parse_uint(&arg);
646         else if (arg_match(&arg, &psnrarg, argi))
647             show_psnr = 1;
648         else
649             argj++;
650     }
651
652     /* Ensure that --passes and --pass are consistent. If --pass is set and --passes=2,
653      * ensure --fpf was set.
654      */
655     if (one_pass_only)
656     {
657         /* DWIM: Assume the user meant passes=2 if pass=2 is specified */
658         if (one_pass_only > arg_passes)
659         {
660             printf("Warning: Assuming --pass=%d implies --passes=%d\n",
661                    one_pass_only, one_pass_only);
662             arg_passes = one_pass_only;
663         }
664
665         if (arg_passes == 2 && !stats_fn)
666             die("Must specify --fpf when --pass=%d and --passes=2\n", one_pass_only);
667     }
668
669     /* Populate encoder configuration */
670     res = vpx_codec_enc_config_default(codec->iface, &cfg, arg_usage);
671
672     if (res)
673     {
674         printf("Failed to get config: %s\n", vpx_codec_err_to_string(res));
675         return EXIT_FAILURE;
676     }
677
678     /* Now parse the remainder of the parameters. */
679     for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step)
680     {
681         arg.argv_step = 1;
682
683         if (0);
684         else if (arg_match(&arg, &threads, argi))
685             cfg.g_threads = arg_parse_uint(&arg);
686         else if (arg_match(&arg, &profile, argi))
687             cfg.g_profile = arg_parse_uint(&arg);
688         else if (arg_match(&arg, &width, argi))
689             cfg.g_w = arg_parse_uint(&arg);
690         else if (arg_match(&arg, &height, argi))
691             cfg.g_h = arg_parse_uint(&arg);
692         else if (arg_match(&arg, &timebase, argi))
693             cfg.g_timebase = arg_parse_rational(&arg);
694         else if (arg_match(&arg, &error_resilient, argi))
695             cfg.g_error_resilient = arg_parse_uint(&arg);
696         else if (arg_match(&arg, &lag_in_frames, argi))
697             cfg.g_lag_in_frames = arg_parse_uint(&arg);
698         else if (arg_match(&arg, &dropframe_thresh, argi))
699             cfg.rc_dropframe_thresh = arg_parse_uint(&arg);
700         else if (arg_match(&arg, &resize_allowed, argi))
701             cfg.rc_resize_allowed = arg_parse_uint(&arg);
702         else if (arg_match(&arg, &resize_up_thresh, argi))
703             cfg.rc_resize_up_thresh = arg_parse_uint(&arg);
704         else if (arg_match(&arg, &resize_down_thresh, argi))
705             cfg.rc_resize_down_thresh = arg_parse_uint(&arg);
706         else if (arg_match(&arg, &resize_down_thresh, argi))
707             cfg.rc_resize_down_thresh = arg_parse_uint(&arg);
708         else if (arg_match(&arg, &end_usage, argi))
709             cfg.rc_end_usage = arg_parse_uint(&arg);
710         else if (arg_match(&arg, &target_bitrate, argi))
711             cfg.rc_target_bitrate = arg_parse_uint(&arg);
712         else if (arg_match(&arg, &min_quantizer, argi))
713             cfg.rc_min_quantizer = arg_parse_uint(&arg);
714         else if (arg_match(&arg, &max_quantizer, argi))
715             cfg.rc_max_quantizer = arg_parse_uint(&arg);
716         else if (arg_match(&arg, &undershoot_pct, argi))
717             cfg.rc_undershoot_pct = arg_parse_uint(&arg);
718         else if (arg_match(&arg, &overshoot_pct, argi))
719             cfg.rc_overshoot_pct = arg_parse_uint(&arg);
720         else if (arg_match(&arg, &buf_sz, argi))
721             cfg.rc_buf_sz = arg_parse_uint(&arg);
722         else if (arg_match(&arg, &buf_initial_sz, argi))
723             cfg.rc_buf_initial_sz = arg_parse_uint(&arg);
724         else if (arg_match(&arg, &buf_optimal_sz, argi))
725             cfg.rc_buf_optimal_sz = arg_parse_uint(&arg);
726         else if (arg_match(&arg, &bias_pct, argi))
727         {
728             cfg.rc_2pass_vbr_bias_pct = arg_parse_uint(&arg);
729
730             if (arg_passes < 2)
731                 printf("Warning: option %s ignored in one-pass mode.\n",
732                        arg.name);
733         }
734         else if (arg_match(&arg, &minsection_pct, argi))
735         {
736             cfg.rc_2pass_vbr_minsection_pct = arg_parse_uint(&arg);
737
738             if (arg_passes < 2)
739                 printf("Warning: option %s ignored in one-pass mode.\n",
740                        arg.name);
741         }
742         else if (arg_match(&arg, &maxsection_pct, argi))
743         {
744             cfg.rc_2pass_vbr_maxsection_pct = arg_parse_uint(&arg);
745
746             if (arg_passes < 2)
747                 printf("Warning: option %s ignored in one-pass mode.\n",
748                        arg.name);
749         }
750         else if (arg_match(&arg, &kf_min_dist, argi))
751             cfg.kf_min_dist = arg_parse_uint(&arg);
752         else if (arg_match(&arg, &kf_max_dist, argi))
753             cfg.kf_max_dist = arg_parse_uint(&arg);
754         else
755             argj++;
756     }
757
758     /* Handle codec specific options */
759 #if CONFIG_VP8_ENCODER
760
761     if (codec->iface == &vpx_codec_vp8_cx_algo)
762     {
763         ctrl_args = vp8_args;
764         ctrl_args_map = vp8_arg_ctrl_map;
765     }
766
767 #endif
768
769     for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step)
770     {
771         int match = 0;
772
773         arg.argv_step = 1;
774
775         for (i = 0; ctrl_args[i]; i++)
776         {
777             if (arg_match(&arg, ctrl_args[i], argi))
778             {
779                 match = 1;
780
781                 if (arg_ctrl_cnt < ARG_CTRL_CNT_MAX)
782                 {
783                     arg_ctrls[arg_ctrl_cnt][0] = ctrl_args_map[i];
784                     arg_ctrls[arg_ctrl_cnt][1] = arg_parse_int(&arg);
785                     arg_ctrl_cnt++;
786                 }
787             }
788         }
789
790         if (!match)
791             argj++;
792     }
793
794     /* Check for unrecognized options */
795     for (argi = argv; *argi; argi++)
796         if (argi[0][0] == '-')
797             die("Error: Unrecognized option %s\n", *argi);
798
799     /* Handle non-option arguments */
800     in_fn = argv[0];
801     out_fn = argv[1];
802
803     if (!in_fn || !out_fn)
804         usage_exit();
805
806     /* Parse certain options from the input file, if possible */
807     infile = fopen(in_fn, "rb");
808
809     if (!infile)
810     {
811         printf("Failed to open input file");
812         return EXIT_FAILURE;
813     }
814
815     is_ivf = file_is_ivf(infile, &fourcc, &cfg.g_w, &cfg.g_h);
816
817     if (is_ivf)
818     {
819         switch (fourcc)
820         {
821         case 0x32315659:
822             arg_use_i420 = 0;
823             break;
824         case 0x30323449:
825             arg_use_i420 = 1;
826             break;
827         default:
828             printf("Unsupported fourcc (%08x) in IVF\n", fourcc);
829             return EXIT_FAILURE;
830         }
831     }
832
833     fclose(infile);
834
835
836 #define SHOW(field) printf("    %-28s = %d\n", #field, cfg.field)
837
838     if (verbose)
839     {
840         printf("Codec: %s\n", vpx_codec_iface_name(codec->iface));
841         printf("Source file: %s Format: %s\n", in_fn, arg_use_i420 ? "I420" : "YV12");
842         printf("Destination file: %s\n", out_fn);
843         printf("Encoder parameters:\n");
844
845         SHOW(g_usage);
846         SHOW(g_threads);
847         SHOW(g_profile);
848         SHOW(g_w);
849         SHOW(g_h);
850         SHOW(g_timebase.num);
851         SHOW(g_timebase.den);
852         SHOW(g_error_resilient);
853         SHOW(g_pass);
854         SHOW(g_lag_in_frames);
855         SHOW(rc_dropframe_thresh);
856         SHOW(rc_resize_allowed);
857         SHOW(rc_resize_up_thresh);
858         SHOW(rc_resize_down_thresh);
859         SHOW(rc_end_usage);
860         SHOW(rc_target_bitrate);
861         SHOW(rc_min_quantizer);
862         SHOW(rc_max_quantizer);
863         SHOW(rc_undershoot_pct);
864         SHOW(rc_overshoot_pct);
865         SHOW(rc_buf_sz);
866         SHOW(rc_buf_initial_sz);
867         SHOW(rc_buf_optimal_sz);
868         SHOW(rc_2pass_vbr_bias_pct);
869         SHOW(rc_2pass_vbr_minsection_pct);
870         SHOW(rc_2pass_vbr_maxsection_pct);
871         SHOW(kf_mode);
872         SHOW(kf_min_dist);
873         SHOW(kf_max_dist);
874     }
875
876     vpx_img_alloc(&raw, arg_use_i420 ? VPX_IMG_FMT_I420 : VPX_IMG_FMT_YV12,
877                   cfg.g_w, cfg.g_h, 1);
878
879     // This was added so that ivfenc will create monotically increasing
880     // timestamps.  Since we create new timestamps for alt-reference frames
881     // we need to make room in the series of timestamps.  Since there can
882     // only be 1 alt-ref frame ( current bitstream) multiplying by 2
883     // gives us enough room.
884     cfg.g_timebase.den *= 2;
885
886     memset(&stats, 0, sizeof(stats));
887
888     for (pass = one_pass_only ? one_pass_only - 1 : 0; pass < arg_passes; pass++)
889     {
890         int frames_in = 0, frames_out = 0;
891         unsigned long nbytes = 0;
892
893         infile = fopen(in_fn, "rb");
894
895         if (!infile)
896         {
897             printf("Failed to open input file");
898             return EXIT_FAILURE;
899         }
900
901         outfile = fopen(out_fn, "wb");
902
903         if (!outfile)
904         {
905             printf("Failed to open output file");
906             return EXIT_FAILURE;
907         }
908
909         if (stats_fn)
910         {
911             if (!stats_open_file(&stats, stats_fn, pass))
912             {
913                 printf("Failed to open statistics store\n");
914                 return EXIT_FAILURE;
915             }
916         }
917         else
918         {
919             if (!stats_open_mem(&stats, pass))
920             {
921                 printf("Failed to open statistics store\n");
922                 return EXIT_FAILURE;
923             }
924         }
925
926         cfg.g_pass = arg_passes == 2
927                      ? pass ? VPX_RC_LAST_PASS : VPX_RC_FIRST_PASS
928                  : VPX_RC_ONE_PASS;
929 #if VPX_ENCODER_ABI_VERSION > (1 + VPX_CODEC_ABI_VERSION)
930
931         if (pass)
932         {
933             cfg.rc_twopass_stats_in = stats_get(&stats);
934         }
935
936 #endif
937
938         write_ivf_file_header(outfile, &cfg, codec->fourcc, 0);
939
940
941         /* Construct Encoder Context */
942         if (cfg.kf_min_dist == cfg.kf_max_dist)
943             cfg.kf_mode = VPX_KF_FIXED;
944
945         vpx_codec_enc_init(&encoder, codec->iface, &cfg,
946                            show_psnr ? VPX_CODEC_USE_PSNR : 0);
947         ctx_exit_on_error(&encoder, "Failed to initialize encoder");
948
949         /* Note that we bypass the vpx_codec_control wrapper macro because
950          * we're being clever to store the control IDs in an array. Real
951          * applications will want to make use of the enumerations directly
952          */
953         for (i = 0; i < arg_ctrl_cnt; i++)
954         {
955             if (vpx_codec_control_(&encoder, arg_ctrls[i][0], arg_ctrls[i][1]))
956                 printf("Error: Tried to set control %d = %d\n",
957                        arg_ctrls[i][0], arg_ctrls[i][1]);
958
959             ctx_exit_on_error(&encoder, "Failed to control codec");
960         }
961
962         frame_avail = 1;
963         got_data = 0;
964
965         while (frame_avail || got_data)
966         {
967             vpx_codec_iter_t iter = NULL;
968             const vpx_codec_cx_pkt_t *pkt;
969             struct vpx_usec_timer timer;
970
971             if (!arg_limit || frames_in < arg_limit)
972             {
973                 frame_avail = read_frame(infile, &raw, is_ivf);
974
975                 if (frame_avail)
976                     frames_in++;
977
978                 printf("\rPass %d/%d frame %4d/%-4d %7ldB \033[K", pass + 1,
979                        arg_passes, frames_in, frames_out, nbytes);
980             }
981             else
982                 frame_avail = 0;
983
984             vpx_usec_timer_start(&timer);
985
986             // since we halved our timebase we need to double the timestamps
987             // and duration we pass in.
988             vpx_codec_encode(&encoder, frame_avail ? &raw : NULL, (frames_in - 1) * 2,
989                              2, 0, arg_deadline);
990             vpx_usec_timer_mark(&timer);
991             cx_time += vpx_usec_timer_elapsed(&timer);
992             ctx_exit_on_error(&encoder, "Failed to encode frame");
993             got_data = 0;
994
995             while ((pkt = vpx_codec_get_cx_data(&encoder, &iter)))
996             {
997                 got_data = 1;
998
999                 switch (pkt->kind)
1000                 {
1001                 case VPX_CODEC_CX_FRAME_PKT:
1002                     frames_out++;
1003                     printf(" %6luF",
1004                            (unsigned long)pkt->data.frame.sz);
1005                     write_ivf_frame_header(outfile, pkt);
1006                     fwrite(pkt->data.frame.buf, 1, pkt->data.frame.sz, outfile);
1007                     nbytes += pkt->data.raw.sz;
1008                     break;
1009                 case VPX_CODEC_STATS_PKT:
1010                     frames_out++;
1011                     printf(" %6luS",
1012                            (unsigned long)pkt->data.twopass_stats.sz);
1013                     stats_write(&stats,
1014                                 pkt->data.twopass_stats.buf,
1015                                 pkt->data.twopass_stats.sz);
1016                     nbytes += pkt->data.raw.sz;
1017                     break;
1018                 case VPX_CODEC_PSNR_PKT:
1019
1020                     if (show_psnr)
1021                     {
1022                         int i;
1023
1024                         for (i = 0; i < 4; i++)
1025                             printf("%.3lf ", pkt->data.psnr.psnr[i]);
1026                     }
1027
1028                     break;
1029                 default:
1030                     break;
1031                 }
1032             }
1033
1034             fflush(stdout);
1035         }
1036
1037         /* this bitrate calc is simplified and relies on the fact that this
1038          * application uses 1/timebase for framerate.
1039          */
1040         printf("\rPass %d/%d frame %4d/%-4d %7ldB %7ldb/f %7"PRId64"b/s"
1041                " %7lu %s (%.2f fps)\033[K", pass + 1,
1042                arg_passes, frames_in, frames_out, nbytes, nbytes * 8 / frames_in,
1043                nbytes * 8 *(int64_t)cfg.g_timebase.den/2/ cfg.g_timebase.num / frames_in,
1044                cx_time > 9999999 ? cx_time / 1000 : cx_time,
1045                cx_time > 9999999 ? "ms" : "us",
1046                (float)frames_in * 1000000.0 / (float)cx_time);
1047
1048         vpx_codec_destroy(&encoder);
1049
1050         fclose(infile);
1051
1052         if (!fseek(outfile, 0, SEEK_SET))
1053             write_ivf_file_header(outfile, &cfg, codec->fourcc, frames_out);
1054
1055         fclose(outfile);
1056         stats_close(&stats);
1057         printf("\n");
1058
1059         if (one_pass_only)
1060             break;
1061     }
1062
1063     vpx_img_free(&raw);
1064     free(argv);
1065     return EXIT_SUCCESS;
1066 }