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