More on "some XMM registers are non-volatile on windows x64 ABI"
[libvpx.git] / ivfenc.c
blobe9a49cddd46205694a9068b0326a0c16851f008b
1 /*
2 * Copyright (c) 2010 The VP8 project authors. All Rights Reserved.
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 */
12 /* This is a simple program that encodes YV12 files and generates ivf
13 * files using the new interface.
15 #if defined(_WIN32)
16 #define USE_POSIX_MMAP 0
17 #else
18 #define USE_POSIX_MMAP 1
19 #endif
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/vp8cx.h"
34 #include "vpx_ports/mem_ops.h"
35 #include "vpx_ports/vpx_timer.h"
36 #include "y4minput.h"
38 static const char *exec_name;
40 static const struct codec_item
42 char const *name;
43 const vpx_codec_iface_t *iface;
44 unsigned int fourcc;
45 } codecs[] =
47 #if CONFIG_VP8_ENCODER
48 {"vp8", &vpx_codec_vp8_cx_algo, 0x30385056},
49 #endif
52 static void usage_exit();
54 void die(const char *fmt, ...)
56 va_list ap;
57 va_start(ap, fmt);
58 vfprintf(stderr, fmt, ap);
59 fprintf(stderr, "\n");
60 usage_exit();
63 static void ctx_exit_on_error(vpx_codec_ctx_t *ctx, const char *s)
65 if (ctx->err)
67 const char *detail = vpx_codec_error_detail(ctx);
69 fprintf(stderr, "%s: %s\n", s, vpx_codec_error(ctx));
71 if (detail)
72 fprintf(stderr, " %s\n", detail);
74 exit(EXIT_FAILURE);
78 /* This structure is used to abstract the different ways of handling
79 * first pass statistics.
81 typedef struct
83 vpx_fixed_buf_t buf;
84 int pass;
85 FILE *file;
86 char *buf_ptr;
87 size_t buf_alloc_sz;
88 } stats_io_t;
90 int stats_open_file(stats_io_t *stats, const char *fpf, int pass)
92 int res;
94 stats->pass = pass;
96 if (pass == 0)
98 stats->file = fopen(fpf, "wb");
99 stats->buf.sz = 0;
100 stats->buf.buf = NULL,
101 res = (stats->file != NULL);
103 else
105 #if 0
106 #elif USE_POSIX_MMAP
107 struct stat stat_buf;
108 int fd;
110 fd = open(fpf, O_RDONLY);
111 stats->file = fdopen(fd, "rb");
112 fstat(fd, &stat_buf);
113 stats->buf.sz = stat_buf.st_size;
114 stats->buf.buf = mmap(NULL, stats->buf.sz, PROT_READ, MAP_PRIVATE,
115 fd, 0);
116 res = (stats->buf.buf != NULL);
117 #else
118 size_t nbytes;
120 stats->file = fopen(fpf, "rb");
122 if (fseek(stats->file, 0, SEEK_END))
124 fprintf(stderr, "First-pass stats file must be seekable!\n");
125 exit(EXIT_FAILURE);
128 stats->buf.sz = stats->buf_alloc_sz = ftell(stats->file);
129 rewind(stats->file);
131 stats->buf.buf = malloc(stats->buf_alloc_sz);
133 if (!stats->buf.buf)
135 fprintf(stderr, "Failed to allocate first-pass stats buffer (%d bytes)\n",
136 stats->buf_alloc_sz);
137 exit(EXIT_FAILURE);
140 nbytes = fread(stats->buf.buf, 1, stats->buf.sz, stats->file);
141 res = (nbytes == stats->buf.sz);
142 #endif
145 return res;
148 int stats_open_mem(stats_io_t *stats, int pass)
150 int res;
151 stats->pass = pass;
153 if (!pass)
155 stats->buf.sz = 0;
156 stats->buf_alloc_sz = 64 * 1024;
157 stats->buf.buf = malloc(stats->buf_alloc_sz);
160 stats->buf_ptr = stats->buf.buf;
161 res = (stats->buf.buf != NULL);
162 return res;
166 void stats_close(stats_io_t *stats)
168 if (stats->file)
170 if (stats->pass == 1)
172 #if 0
173 #elif USE_POSIX_MMAP
174 munmap(stats->buf.buf, stats->buf.sz);
175 #else
176 free(stats->buf.buf);
177 #endif
180 fclose(stats->file);
181 stats->file = NULL;
183 else
185 if (stats->pass == 1)
186 free(stats->buf.buf);
190 void stats_write(stats_io_t *stats, const void *pkt, size_t len)
192 if (stats->file)
194 fwrite(pkt, 1, len, stats->file);
196 else
198 if (stats->buf.sz + len > stats->buf_alloc_sz)
200 size_t new_sz = stats->buf_alloc_sz + 64 * 1024;
201 char *new_ptr = realloc(stats->buf.buf, new_sz);
203 if (new_ptr)
205 stats->buf_ptr = new_ptr + (stats->buf_ptr - (char *)stats->buf.buf);
206 stats->buf.buf = new_ptr;
207 stats->buf_alloc_sz = new_sz;
208 } /* else ... */
211 memcpy(stats->buf_ptr, pkt, len);
212 stats->buf.sz += len;
213 stats->buf_ptr += len;
217 vpx_fixed_buf_t stats_get(stats_io_t *stats)
219 return stats->buf;
222 enum video_file_type
224 FILE_TYPE_RAW,
225 FILE_TYPE_IVF,
226 FILE_TYPE_Y4M
229 struct detect_buffer {
230 char buf[4];
231 int valid;
235 #define IVF_FRAME_HDR_SZ (4+8) /* 4 byte size + 8 byte timestamp */
236 static int read_frame(FILE *f, vpx_image_t *img, unsigned int file_type,
237 y4m_input *y4m, struct detect_buffer *detect)
239 int plane = 0;
241 if (file_type == FILE_TYPE_Y4M)
243 if (y4m_input_fetch_frame(y4m, f, img) < 0)
244 return 0;
246 else
248 if (file_type == FILE_TYPE_IVF)
250 char junk[IVF_FRAME_HDR_SZ];
252 /* Skip the frame header. We know how big the frame should be. See
253 * write_ivf_frame_header() for documentation on the frame header
254 * layout.
256 fread(junk, 1, IVF_FRAME_HDR_SZ, f);
259 for (plane = 0; plane < 3; plane++)
261 unsigned char *ptr;
262 int w = (plane ? (1 + img->d_w) / 2 : img->d_w);
263 int h = (plane ? (1 + img->d_h) / 2 : img->d_h);
264 int r;
266 /* Determine the correct plane based on the image format. The for-loop
267 * always counts in Y,U,V order, but this may not match the order of
268 * the data on disk.
270 switch (plane)
272 case 1:
273 ptr = img->planes[img->fmt==VPX_IMG_FMT_YV12? VPX_PLANE_V : VPX_PLANE_U];
274 break;
275 case 2:
276 ptr = img->planes[img->fmt==VPX_IMG_FMT_YV12?VPX_PLANE_U : VPX_PLANE_V];
277 break;
278 default:
279 ptr = img->planes[plane];
282 for (r = 0; r < h; r++)
284 if (detect->valid)
286 memcpy(ptr, detect->buf, 4);
287 fread(ptr+4, 1, w-4, f);
288 detect->valid = 0;
290 else
291 fread(ptr, 1, w, f);
293 ptr += img->stride[plane];
298 return !feof(f);
302 unsigned int file_is_y4m(FILE *infile,
303 y4m_input *y4m,
304 char detect[4])
306 if(memcmp(detect, "YUV4", 4) == 0 &&
307 y4m_input_open(y4m, infile, detect, 4) >= 0)
309 return 1;
311 return 0;
314 #define IVF_FILE_HDR_SZ (32)
315 unsigned int file_is_ivf(FILE *infile,
316 unsigned int *fourcc,
317 unsigned int *width,
318 unsigned int *height,
319 char detect[4])
321 char raw_hdr[IVF_FILE_HDR_SZ];
322 int is_ivf = 0;
324 if(memcmp(detect, "DKIF", 4) != 0)
325 return 0;
327 /* See write_ivf_file_header() for more documentation on the file header
328 * layout.
330 if (fread(raw_hdr + 4, 1, IVF_FILE_HDR_SZ - 4, infile)
331 == IVF_FILE_HDR_SZ - 4)
334 is_ivf = 1;
336 if (mem_get_le16(raw_hdr + 4) != 0)
337 fprintf(stderr, "Error: Unrecognized IVF version! This file may not"
338 " decode properly.");
340 *fourcc = mem_get_le32(raw_hdr + 8);
344 if (is_ivf)
346 *width = mem_get_le16(raw_hdr + 12);
347 *height = mem_get_le16(raw_hdr + 14);
350 return is_ivf;
354 static void write_ivf_file_header(FILE *outfile,
355 const vpx_codec_enc_cfg_t *cfg,
356 unsigned int fourcc,
357 int frame_cnt)
359 char header[32];
361 if (cfg->g_pass != VPX_RC_ONE_PASS && cfg->g_pass != VPX_RC_LAST_PASS)
362 return;
364 header[0] = 'D';
365 header[1] = 'K';
366 header[2] = 'I';
367 header[3] = 'F';
368 mem_put_le16(header + 4, 0); /* version */
369 mem_put_le16(header + 6, 32); /* headersize */
370 mem_put_le32(header + 8, fourcc); /* headersize */
371 mem_put_le16(header + 12, cfg->g_w); /* width */
372 mem_put_le16(header + 14, cfg->g_h); /* height */
373 mem_put_le32(header + 16, cfg->g_timebase.den); /* rate */
374 mem_put_le32(header + 20, cfg->g_timebase.num); /* scale */
375 mem_put_le32(header + 24, frame_cnt); /* length */
376 mem_put_le32(header + 28, 0); /* unused */
378 fwrite(header, 1, 32, outfile);
382 static void write_ivf_frame_header(FILE *outfile,
383 const vpx_codec_cx_pkt_t *pkt)
385 char header[12];
386 vpx_codec_pts_t pts;
388 if (pkt->kind != VPX_CODEC_CX_FRAME_PKT)
389 return;
391 pts = pkt->data.frame.pts;
392 mem_put_le32(header, pkt->data.frame.sz);
393 mem_put_le32(header + 4, pts & 0xFFFFFFFF);
394 mem_put_le32(header + 8, pts >> 32);
396 fwrite(header, 1, 12, outfile);
399 #include "args.h"
401 static const arg_def_t use_yv12 = ARG_DEF(NULL, "yv12", 0,
402 "Input file is YV12 ");
403 static const arg_def_t use_i420 = ARG_DEF(NULL, "i420", 0,
404 "Input file is I420 (default)");
405 static const arg_def_t codecarg = ARG_DEF(NULL, "codec", 1,
406 "Codec to use");
407 static const arg_def_t passes = ARG_DEF("p", "passes", 1,
408 "Number of passes (1/2)");
409 static const arg_def_t pass_arg = ARG_DEF(NULL, "pass", 1,
410 "Pass to execute (1/2)");
411 static const arg_def_t fpf_name = ARG_DEF(NULL, "fpf", 1,
412 "First pass statistics file name");
413 static const arg_def_t limit = ARG_DEF(NULL, "limit", 1,
414 "Stop encoding after n input frames");
415 static const arg_def_t deadline = ARG_DEF("d", "deadline", 1,
416 "Deadline per frame (usec)");
417 static const arg_def_t best_dl = ARG_DEF(NULL, "best", 0,
418 "Use Best Quality Deadline");
419 static const arg_def_t good_dl = ARG_DEF(NULL, "good", 0,
420 "Use Good Quality Deadline");
421 static const arg_def_t rt_dl = ARG_DEF(NULL, "rt", 0,
422 "Use Realtime Quality Deadline");
423 static const arg_def_t verbosearg = ARG_DEF("v", "verbose", 0,
424 "Show encoder parameters");
425 static const arg_def_t psnrarg = ARG_DEF(NULL, "psnr", 0,
426 "Show PSNR in status line");
427 static const arg_def_t *main_args[] =
429 &codecarg, &passes, &pass_arg, &fpf_name, &limit, &deadline, &best_dl, &good_dl, &rt_dl,
430 &verbosearg, &psnrarg,
431 NULL
434 static const arg_def_t usage = ARG_DEF("u", "usage", 1,
435 "Usage profile number to use");
436 static const arg_def_t threads = ARG_DEF("t", "threads", 1,
437 "Max number of threads to use");
438 static const arg_def_t profile = ARG_DEF(NULL, "profile", 1,
439 "Bitstream profile number to use");
440 static const arg_def_t width = ARG_DEF("w", "width", 1,
441 "Frame width");
442 static const arg_def_t height = ARG_DEF("h", "height", 1,
443 "Frame height");
444 static const arg_def_t timebase = ARG_DEF(NULL, "timebase", 1,
445 "Stream timebase (frame duration)");
446 static const arg_def_t error_resilient = ARG_DEF(NULL, "error-resilient", 1,
447 "Enable error resiliency features");
448 static const arg_def_t lag_in_frames = ARG_DEF(NULL, "lag-in-frames", 1,
449 "Max number of frames to lag");
451 static const arg_def_t *global_args[] =
453 &use_yv12, &use_i420, &usage, &threads, &profile,
454 &width, &height, &timebase, &error_resilient,
455 &lag_in_frames, NULL
458 static const arg_def_t dropframe_thresh = ARG_DEF(NULL, "drop-frame", 1,
459 "Temporal resampling threshold (buf %)");
460 static const arg_def_t resize_allowed = ARG_DEF(NULL, "resize-allowed", 1,
461 "Spatial resampling enabled (bool)");
462 static const arg_def_t resize_up_thresh = ARG_DEF(NULL, "resize-up", 1,
463 "Upscale threshold (buf %)");
464 static const arg_def_t resize_down_thresh = ARG_DEF(NULL, "resize-down", 1,
465 "Downscale threshold (buf %)");
466 static const arg_def_t end_usage = ARG_DEF(NULL, "end-usage", 1,
467 "VBR=0 | CBR=1");
468 static const arg_def_t target_bitrate = ARG_DEF(NULL, "target-bitrate", 1,
469 "Bitrate (kbps)");
470 static const arg_def_t min_quantizer = ARG_DEF(NULL, "min-q", 1,
471 "Minimum (best) quantizer");
472 static const arg_def_t max_quantizer = ARG_DEF(NULL, "max-q", 1,
473 "Maximum (worst) quantizer");
474 static const arg_def_t undershoot_pct = ARG_DEF(NULL, "undershoot-pct", 1,
475 "Datarate undershoot (min) target (%)");
476 static const arg_def_t overshoot_pct = ARG_DEF(NULL, "overshoot-pct", 1,
477 "Datarate overshoot (max) target (%)");
478 static const arg_def_t buf_sz = ARG_DEF(NULL, "buf-sz", 1,
479 "Client buffer size (ms)");
480 static const arg_def_t buf_initial_sz = ARG_DEF(NULL, "buf-initial-sz", 1,
481 "Client initial buffer size (ms)");
482 static const arg_def_t buf_optimal_sz = ARG_DEF(NULL, "buf-optimal-sz", 1,
483 "Client optimal buffer size (ms)");
484 static const arg_def_t *rc_args[] =
486 &dropframe_thresh, &resize_allowed, &resize_up_thresh, &resize_down_thresh,
487 &end_usage, &target_bitrate, &min_quantizer, &max_quantizer,
488 &undershoot_pct, &overshoot_pct, &buf_sz, &buf_initial_sz, &buf_optimal_sz,
489 NULL
493 static const arg_def_t bias_pct = ARG_DEF(NULL, "bias-pct", 1,
494 "CBR/VBR bias (0=CBR, 100=VBR)");
495 static const arg_def_t minsection_pct = ARG_DEF(NULL, "minsection-pct", 1,
496 "GOP min bitrate (% of target)");
497 static const arg_def_t maxsection_pct = ARG_DEF(NULL, "maxsection-pct", 1,
498 "GOP max bitrate (% of target)");
499 static const arg_def_t *rc_twopass_args[] =
501 &bias_pct, &minsection_pct, &maxsection_pct, NULL
505 static const arg_def_t kf_min_dist = ARG_DEF(NULL, "kf-min-dist", 1,
506 "Minimum keyframe interval (frames)");
507 static const arg_def_t kf_max_dist = ARG_DEF(NULL, "kf-max-dist", 1,
508 "Maximum keyframe interval (frames)");
509 static const arg_def_t *kf_args[] =
511 &kf_min_dist, &kf_max_dist, NULL
515 #if CONFIG_VP8_ENCODER
516 static const arg_def_t noise_sens = ARG_DEF(NULL, "noise-sensitivity", 1,
517 "Noise sensitivity (frames to blur)");
518 static const arg_def_t sharpness = ARG_DEF(NULL, "sharpness", 1,
519 "Filter sharpness (0-7)");
520 static const arg_def_t static_thresh = ARG_DEF(NULL, "static-thresh", 1,
521 "Motion detection threshold");
522 #endif
524 #if CONFIG_VP8_ENCODER
525 static const arg_def_t cpu_used = ARG_DEF(NULL, "cpu-used", 1,
526 "CPU Used (-16..16)");
527 #endif
530 #if CONFIG_VP8_ENCODER
531 static const arg_def_t token_parts = ARG_DEF(NULL, "token-parts", 1,
532 "Number of token partitions to use, log2");
533 static const arg_def_t auto_altref = ARG_DEF(NULL, "auto-alt-ref", 1,
534 "Enable automatic alt reference frames");
535 static const arg_def_t arnr_maxframes = ARG_DEF(NULL, "arnr-maxframes", 1,
536 "alt_ref Max Frames");
537 static const arg_def_t arnr_strength = ARG_DEF(NULL, "arnr-strength", 1,
538 "alt_ref Strength");
539 static const arg_def_t arnr_type = ARG_DEF(NULL, "arnr-type", 1,
540 "alt_ref Type");
542 static const arg_def_t *vp8_args[] =
544 &cpu_used, &auto_altref, &noise_sens, &sharpness, &static_thresh,
545 &token_parts, &arnr_maxframes, &arnr_strength, &arnr_type, NULL
547 static const int vp8_arg_ctrl_map[] =
549 VP8E_SET_CPUUSED, VP8E_SET_ENABLEAUTOALTREF,
550 VP8E_SET_NOISE_SENSITIVITY, VP8E_SET_SHARPNESS, VP8E_SET_STATIC_THRESHOLD,
551 VP8E_SET_TOKEN_PARTITIONS,
552 VP8E_SET_ARNR_MAXFRAMES, VP8E_SET_ARNR_STRENGTH , VP8E_SET_ARNR_TYPE, 0
554 #endif
556 static const arg_def_t *no_args[] = { NULL };
558 static void usage_exit()
560 int i;
562 fprintf(stderr, "Usage: %s <options> src_filename dst_filename\n", exec_name);
564 fprintf(stderr, "\n_options:\n");
565 arg_show_usage(stdout, main_args);
566 fprintf(stderr, "\n_encoder Global Options:\n");
567 arg_show_usage(stdout, global_args);
568 fprintf(stderr, "\n_rate Control Options:\n");
569 arg_show_usage(stdout, rc_args);
570 fprintf(stderr, "\n_twopass Rate Control Options:\n");
571 arg_show_usage(stdout, rc_twopass_args);
572 fprintf(stderr, "\n_keyframe Placement Options:\n");
573 arg_show_usage(stdout, kf_args);
574 #if CONFIG_VP8_ENCODER
575 fprintf(stderr, "\n_vp8 Specific Options:\n");
576 arg_show_usage(stdout, vp8_args);
577 #endif
578 fprintf(stderr, "\n"
579 "Included encoders:\n"
580 "\n");
582 for (i = 0; i < sizeof(codecs) / sizeof(codecs[0]); i++)
583 fprintf(stderr, " %-6s - %s\n",
584 codecs[i].name,
585 vpx_codec_iface_name(codecs[i].iface));
587 exit(EXIT_FAILURE);
590 #define ARG_CTRL_CNT_MAX 10
593 int main(int argc, const char **argv_)
595 vpx_codec_ctx_t encoder;
596 const char *in_fn = NULL, *out_fn = NULL, *stats_fn = NULL;
597 int i;
598 FILE *infile, *outfile;
599 vpx_codec_enc_cfg_t cfg;
600 vpx_codec_err_t res;
601 int pass, one_pass_only = 0;
602 stats_io_t stats;
603 vpx_image_t raw;
604 const struct codec_item *codec = codecs;
605 int frame_avail, got_data;
607 struct arg arg;
608 char **argv, **argi, **argj;
609 int arg_usage = 0, arg_passes = 1, arg_deadline = 0;
610 int arg_ctrls[ARG_CTRL_CNT_MAX][2], arg_ctrl_cnt = 0;
611 int arg_limit = 0;
612 static const arg_def_t **ctrl_args = no_args;
613 static const int *ctrl_args_map = NULL;
614 int verbose = 0, show_psnr = 0;
615 int arg_use_i420 = 1;
616 int arg_have_timebase = 0;
617 unsigned long cx_time = 0;
618 unsigned int file_type, fourcc;
619 y4m_input y4m;
621 exec_name = argv_[0];
623 if (argc < 3)
624 usage_exit();
627 /* First parse the codec and usage values, because we want to apply other
628 * parameters on top of the default configuration provided by the codec.
630 argv = argv_dup(argc - 1, argv_ + 1);
632 for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step)
634 arg.argv_step = 1;
636 if (arg_match(&arg, &codecarg, argi))
638 int j, k = -1;
640 for (j = 0; j < sizeof(codecs) / sizeof(codecs[0]); j++)
641 if (!strcmp(codecs[j].name, arg.val))
642 k = j;
644 if (k >= 0)
645 codec = codecs + k;
646 else
647 die("Error: Unrecognized argument (%s) to --codec\n",
648 arg.val);
651 else if (arg_match(&arg, &passes, argi))
653 arg_passes = arg_parse_uint(&arg);
655 if (arg_passes < 1 || arg_passes > 2)
656 die("Error: Invalid number of passes (%d)\n", arg_passes);
658 else if (arg_match(&arg, &pass_arg, argi))
660 one_pass_only = arg_parse_uint(&arg);
662 if (one_pass_only < 1 || one_pass_only > 2)
663 die("Error: Invalid pass selected (%d)\n", one_pass_only);
665 else if (arg_match(&arg, &fpf_name, argi))
666 stats_fn = arg.val;
667 else if (arg_match(&arg, &usage, argi))
668 arg_usage = arg_parse_uint(&arg);
669 else if (arg_match(&arg, &deadline, argi))
670 arg_deadline = arg_parse_uint(&arg);
671 else if (arg_match(&arg, &best_dl, argi))
672 arg_deadline = VPX_DL_BEST_QUALITY;
673 else if (arg_match(&arg, &good_dl, argi))
674 arg_deadline = VPX_DL_GOOD_QUALITY;
675 else if (arg_match(&arg, &rt_dl, argi))
676 arg_deadline = VPX_DL_REALTIME;
677 else if (arg_match(&arg, &use_yv12, argi))
679 arg_use_i420 = 0;
681 else if (arg_match(&arg, &use_i420, argi))
683 arg_use_i420 = 1;
685 else if (arg_match(&arg, &verbosearg, argi))
686 verbose = 1;
687 else if (arg_match(&arg, &limit, argi))
688 arg_limit = arg_parse_uint(&arg);
689 else if (arg_match(&arg, &psnrarg, argi))
690 show_psnr = 1;
691 else
692 argj++;
695 /* Ensure that --passes and --pass are consistent. If --pass is set and --passes=2,
696 * ensure --fpf was set.
698 if (one_pass_only)
700 /* DWIM: Assume the user meant passes=2 if pass=2 is specified */
701 if (one_pass_only > arg_passes)
703 fprintf(stderr, "Warning: Assuming --pass=%d implies --passes=%d\n",
704 one_pass_only, one_pass_only);
705 arg_passes = one_pass_only;
708 if (arg_passes == 2 && !stats_fn)
709 die("Must specify --fpf when --pass=%d and --passes=2\n", one_pass_only);
712 /* Populate encoder configuration */
713 res = vpx_codec_enc_config_default(codec->iface, &cfg, arg_usage);
715 if (res)
717 fprintf(stderr, "Failed to get config: %s\n",
718 vpx_codec_err_to_string(res));
719 return EXIT_FAILURE;
722 /* Now parse the remainder of the parameters. */
723 for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step)
725 arg.argv_step = 1;
727 if (0);
728 else if (arg_match(&arg, &threads, argi))
729 cfg.g_threads = arg_parse_uint(&arg);
730 else if (arg_match(&arg, &profile, argi))
731 cfg.g_profile = arg_parse_uint(&arg);
732 else if (arg_match(&arg, &width, argi))
733 cfg.g_w = arg_parse_uint(&arg);
734 else if (arg_match(&arg, &height, argi))
735 cfg.g_h = arg_parse_uint(&arg);
736 else if (arg_match(&arg, &timebase, argi))
738 cfg.g_timebase = arg_parse_rational(&arg);
739 arg_have_timebase = 1;
741 else if (arg_match(&arg, &error_resilient, argi))
742 cfg.g_error_resilient = arg_parse_uint(&arg);
743 else if (arg_match(&arg, &lag_in_frames, argi))
744 cfg.g_lag_in_frames = arg_parse_uint(&arg);
745 else if (arg_match(&arg, &dropframe_thresh, argi))
746 cfg.rc_dropframe_thresh = arg_parse_uint(&arg);
747 else if (arg_match(&arg, &resize_allowed, argi))
748 cfg.rc_resize_allowed = arg_parse_uint(&arg);
749 else if (arg_match(&arg, &resize_up_thresh, argi))
750 cfg.rc_resize_up_thresh = arg_parse_uint(&arg);
751 else if (arg_match(&arg, &resize_down_thresh, argi))
752 cfg.rc_resize_down_thresh = arg_parse_uint(&arg);
753 else if (arg_match(&arg, &resize_down_thresh, argi))
754 cfg.rc_resize_down_thresh = arg_parse_uint(&arg);
755 else if (arg_match(&arg, &end_usage, argi))
756 cfg.rc_end_usage = arg_parse_uint(&arg);
757 else if (arg_match(&arg, &target_bitrate, argi))
758 cfg.rc_target_bitrate = arg_parse_uint(&arg);
759 else if (arg_match(&arg, &min_quantizer, argi))
760 cfg.rc_min_quantizer = arg_parse_uint(&arg);
761 else if (arg_match(&arg, &max_quantizer, argi))
762 cfg.rc_max_quantizer = arg_parse_uint(&arg);
763 else if (arg_match(&arg, &undershoot_pct, argi))
764 cfg.rc_undershoot_pct = arg_parse_uint(&arg);
765 else if (arg_match(&arg, &overshoot_pct, argi))
766 cfg.rc_overshoot_pct = arg_parse_uint(&arg);
767 else if (arg_match(&arg, &buf_sz, argi))
768 cfg.rc_buf_sz = arg_parse_uint(&arg);
769 else if (arg_match(&arg, &buf_initial_sz, argi))
770 cfg.rc_buf_initial_sz = arg_parse_uint(&arg);
771 else if (arg_match(&arg, &buf_optimal_sz, argi))
772 cfg.rc_buf_optimal_sz = arg_parse_uint(&arg);
773 else if (arg_match(&arg, &bias_pct, argi))
775 cfg.rc_2pass_vbr_bias_pct = arg_parse_uint(&arg);
777 if (arg_passes < 2)
778 fprintf(stderr,
779 "Warning: option %s ignored in one-pass mode.\n",
780 arg.name);
782 else if (arg_match(&arg, &minsection_pct, argi))
784 cfg.rc_2pass_vbr_minsection_pct = arg_parse_uint(&arg);
786 if (arg_passes < 2)
787 fprintf(stderr,
788 "Warning: option %s ignored in one-pass mode.\n",
789 arg.name);
791 else if (arg_match(&arg, &maxsection_pct, argi))
793 cfg.rc_2pass_vbr_maxsection_pct = arg_parse_uint(&arg);
795 if (arg_passes < 2)
796 fprintf(stderr,
797 "Warning: option %s ignored in one-pass mode.\n",
798 arg.name);
800 else if (arg_match(&arg, &kf_min_dist, argi))
801 cfg.kf_min_dist = arg_parse_uint(&arg);
802 else if (arg_match(&arg, &kf_max_dist, argi))
803 cfg.kf_max_dist = arg_parse_uint(&arg);
804 else
805 argj++;
808 /* Handle codec specific options */
809 #if CONFIG_VP8_ENCODER
811 if (codec->iface == &vpx_codec_vp8_cx_algo)
813 ctrl_args = vp8_args;
814 ctrl_args_map = vp8_arg_ctrl_map;
817 #endif
819 for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step)
821 int match = 0;
823 arg.argv_step = 1;
825 for (i = 0; ctrl_args[i]; i++)
827 if (arg_match(&arg, ctrl_args[i], argi))
829 match = 1;
831 if (arg_ctrl_cnt < ARG_CTRL_CNT_MAX)
833 arg_ctrls[arg_ctrl_cnt][0] = ctrl_args_map[i];
834 arg_ctrls[arg_ctrl_cnt][1] = arg_parse_int(&arg);
835 arg_ctrl_cnt++;
840 if (!match)
841 argj++;
844 /* Check for unrecognized options */
845 for (argi = argv; *argi; argi++)
846 if (argi[0][0] == '-' && argi[0][1])
847 die("Error: Unrecognized option %s\n", *argi);
849 /* Handle non-option arguments */
850 in_fn = argv[0];
851 out_fn = argv[1];
853 if (!in_fn || !out_fn)
854 usage_exit();
856 memset(&stats, 0, sizeof(stats));
858 for (pass = one_pass_only ? one_pass_only - 1 : 0; pass < arg_passes; pass++)
860 int frames_in = 0, frames_out = 0;
861 unsigned long nbytes = 0;
862 struct detect_buffer detect;
864 /* Parse certain options from the input file, if possible */
865 infile = strcmp(in_fn, "-") ? fopen(in_fn, "rb") : stdin;
867 if (!infile)
869 fprintf(stderr, "Failed to open input file\n");
870 return EXIT_FAILURE;
873 fread(detect.buf, 1, 4, infile);
874 detect.valid = 0;
876 if (file_is_y4m(infile, &y4m, detect.buf))
878 file_type = FILE_TYPE_Y4M;
879 cfg.g_w = y4m.pic_w;
880 cfg.g_h = y4m.pic_h;
881 /* Use the frame rate from the file only if none was specified on the
882 * command-line.
884 if (!arg_have_timebase)
886 cfg.g_timebase.num = y4m.fps_d;
887 cfg.g_timebase.den = y4m.fps_n;
889 arg_use_i420 = 0;
891 else if (file_is_ivf(infile, &fourcc, &cfg.g_w, &cfg.g_h, detect.buf))
893 file_type = FILE_TYPE_IVF;
894 switch (fourcc)
896 case 0x32315659:
897 arg_use_i420 = 0;
898 break;
899 case 0x30323449:
900 arg_use_i420 = 1;
901 break;
902 default:
903 fprintf(stderr, "Unsupported fourcc (%08x) in IVF\n", fourcc);
904 return EXIT_FAILURE;
907 else
909 file_type = FILE_TYPE_RAW;
910 detect.valid = 1;
912 #define SHOW(field) fprintf(stderr, " %-28s = %d\n", #field, cfg.field)
914 if (verbose && pass == 0)
916 fprintf(stderr, "Codec: %s\n", vpx_codec_iface_name(codec->iface));
917 fprintf(stderr, "Source file: %s Format: %s\n", in_fn,
918 arg_use_i420 ? "I420" : "YV12");
919 fprintf(stderr, "Destination file: %s\n", out_fn);
920 fprintf(stderr, "Encoder parameters:\n");
922 SHOW(g_usage);
923 SHOW(g_threads);
924 SHOW(g_profile);
925 SHOW(g_w);
926 SHOW(g_h);
927 SHOW(g_timebase.num);
928 SHOW(g_timebase.den);
929 SHOW(g_error_resilient);
930 SHOW(g_pass);
931 SHOW(g_lag_in_frames);
932 SHOW(rc_dropframe_thresh);
933 SHOW(rc_resize_allowed);
934 SHOW(rc_resize_up_thresh);
935 SHOW(rc_resize_down_thresh);
936 SHOW(rc_end_usage);
937 SHOW(rc_target_bitrate);
938 SHOW(rc_min_quantizer);
939 SHOW(rc_max_quantizer);
940 SHOW(rc_undershoot_pct);
941 SHOW(rc_overshoot_pct);
942 SHOW(rc_buf_sz);
943 SHOW(rc_buf_initial_sz);
944 SHOW(rc_buf_optimal_sz);
945 SHOW(rc_2pass_vbr_bias_pct);
946 SHOW(rc_2pass_vbr_minsection_pct);
947 SHOW(rc_2pass_vbr_maxsection_pct);
948 SHOW(kf_mode);
949 SHOW(kf_min_dist);
950 SHOW(kf_max_dist);
953 if(pass == (one_pass_only ? one_pass_only - 1 : 0)) {
954 if (file_type == FILE_TYPE_Y4M)
955 /*The Y4M reader does its own allocation.
956 Just initialize this here to avoid problems if we never read any
957 frames.*/
958 memset(&raw, 0, sizeof(raw));
959 else
960 vpx_img_alloc(&raw, arg_use_i420 ? VPX_IMG_FMT_I420 : VPX_IMG_FMT_YV12,
961 cfg.g_w, cfg.g_h, 1);
963 // This was added so that ivfenc will create monotically increasing
964 // timestamps. Since we create new timestamps for alt-reference frames
965 // we need to make room in the series of timestamps. Since there can
966 // only be 1 alt-ref frame ( current bitstream) multiplying by 2
967 // gives us enough room.
968 cfg.g_timebase.den *= 2;
971 outfile = strcmp(out_fn, "-") ? fopen(out_fn, "wb") : stdout;
973 if (!outfile)
975 fprintf(stderr, "Failed to open output file\n");
976 return EXIT_FAILURE;
979 if (stats_fn)
981 if (!stats_open_file(&stats, stats_fn, pass))
983 fprintf(stderr, "Failed to open statistics store\n");
984 return EXIT_FAILURE;
987 else
989 if (!stats_open_mem(&stats, pass))
991 fprintf(stderr, "Failed to open statistics store\n");
992 return EXIT_FAILURE;
996 cfg.g_pass = arg_passes == 2
997 ? pass ? VPX_RC_LAST_PASS : VPX_RC_FIRST_PASS
998 : VPX_RC_ONE_PASS;
999 #if VPX_ENCODER_ABI_VERSION > (1 + VPX_CODEC_ABI_VERSION)
1001 if (pass)
1003 cfg.rc_twopass_stats_in = stats_get(&stats);
1006 #endif
1008 write_ivf_file_header(outfile, &cfg, codec->fourcc, 0);
1011 /* Construct Encoder Context */
1012 if (cfg.kf_min_dist == cfg.kf_max_dist)
1013 cfg.kf_mode = VPX_KF_FIXED;
1015 vpx_codec_enc_init(&encoder, codec->iface, &cfg,
1016 show_psnr ? VPX_CODEC_USE_PSNR : 0);
1017 ctx_exit_on_error(&encoder, "Failed to initialize encoder");
1019 /* Note that we bypass the vpx_codec_control wrapper macro because
1020 * we're being clever to store the control IDs in an array. Real
1021 * applications will want to make use of the enumerations directly
1023 for (i = 0; i < arg_ctrl_cnt; i++)
1025 if (vpx_codec_control_(&encoder, arg_ctrls[i][0], arg_ctrls[i][1]))
1026 fprintf(stderr, "Error: Tried to set control %d = %d\n",
1027 arg_ctrls[i][0], arg_ctrls[i][1]);
1029 ctx_exit_on_error(&encoder, "Failed to control codec");
1032 frame_avail = 1;
1033 got_data = 0;
1035 while (frame_avail || got_data)
1037 vpx_codec_iter_t iter = NULL;
1038 const vpx_codec_cx_pkt_t *pkt;
1039 struct vpx_usec_timer timer;
1041 if (!arg_limit || frames_in < arg_limit)
1043 frame_avail = read_frame(infile, &raw, file_type, &y4m,
1044 &detect);
1046 if (frame_avail)
1047 frames_in++;
1049 fprintf(stderr,
1050 "\rPass %d/%d frame %4d/%-4d %7ldB \033[K", pass + 1,
1051 arg_passes, frames_in, frames_out, nbytes);
1053 else
1054 frame_avail = 0;
1056 vpx_usec_timer_start(&timer);
1058 // since we halved our timebase we need to double the timestamps
1059 // and duration we pass in.
1060 vpx_codec_encode(&encoder, frame_avail ? &raw : NULL, (frames_in - 1) * 2,
1061 2, 0, arg_deadline);
1062 vpx_usec_timer_mark(&timer);
1063 cx_time += vpx_usec_timer_elapsed(&timer);
1064 ctx_exit_on_error(&encoder, "Failed to encode frame");
1065 got_data = 0;
1067 while ((pkt = vpx_codec_get_cx_data(&encoder, &iter)))
1069 got_data = 1;
1071 switch (pkt->kind)
1073 case VPX_CODEC_CX_FRAME_PKT:
1074 frames_out++;
1075 fprintf(stderr, " %6luF",
1076 (unsigned long)pkt->data.frame.sz);
1077 write_ivf_frame_header(outfile, pkt);
1078 fwrite(pkt->data.frame.buf, 1, pkt->data.frame.sz, outfile);
1079 nbytes += pkt->data.raw.sz;
1080 break;
1081 case VPX_CODEC_STATS_PKT:
1082 frames_out++;
1083 fprintf(stderr, " %6luS",
1084 (unsigned long)pkt->data.twopass_stats.sz);
1085 stats_write(&stats,
1086 pkt->data.twopass_stats.buf,
1087 pkt->data.twopass_stats.sz);
1088 nbytes += pkt->data.raw.sz;
1089 break;
1090 case VPX_CODEC_PSNR_PKT:
1092 if (show_psnr)
1094 int i;
1096 for (i = 0; i < 4; i++)
1097 fprintf(stderr, "%.3lf ", pkt->data.psnr.psnr[i]);
1100 break;
1101 default:
1102 break;
1106 fflush(stdout);
1109 /* this bitrate calc is simplified and relies on the fact that this
1110 * application uses 1/timebase for framerate.
1112 fprintf(stderr,
1113 "\rPass %d/%d frame %4d/%-4d %7ldB %7ldb/f %7"PRId64"b/s"
1114 " %7lu %s (%.2f fps)\033[K", pass + 1,
1115 arg_passes, frames_in, frames_out, nbytes, nbytes * 8 / frames_in,
1116 nbytes * 8 *(int64_t)cfg.g_timebase.den/2/ cfg.g_timebase.num / frames_in,
1117 cx_time > 9999999 ? cx_time / 1000 : cx_time,
1118 cx_time > 9999999 ? "ms" : "us",
1119 (float)frames_in * 1000000.0 / (float)cx_time);
1121 vpx_codec_destroy(&encoder);
1123 fclose(infile);
1125 if (!fseek(outfile, 0, SEEK_SET))
1126 write_ivf_file_header(outfile, &cfg, codec->fourcc, frames_out);
1128 fclose(outfile);
1129 stats_close(&stats);
1130 fprintf(stderr, "\n");
1132 if (one_pass_only)
1133 break;
1136 vpx_img_free(&raw);
1137 free(argv);
1138 return EXIT_SUCCESS;