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