2 * Copyright (c) 2010 The WebM 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.
11 #include "vpx_config.h"
13 #if defined(_WIN32) || !CONFIG_OS_SUPPORT
14 #define USE_POSIX_MMAP 0
16 #define USE_POSIX_MMAP 1
25 #include "vpx/vpx_encoder.h"
27 #include "vpx/vpx_decoder.h"
30 #include <sys/types.h>
37 #if CONFIG_VP8_ENCODER || CONFIG_VP9_ENCODER
38 #include "vpx/vp8cx.h"
40 #if CONFIG_VP8_DECODER || CONFIG_VP9_DECODER
41 #include "vpx/vp8dx.h"
44 #include "vpx_ports/mem_ops.h"
45 #include "vpx_ports/vpx_timer.h"
46 #include "tools_common.h"
48 #include "libmkv/EbmlWriter.h"
49 #include "libmkv/EbmlIDs.h"
51 /* Need special handling of these functions on Windows */
53 /* MSVS doesn't define off_t, and uses _f{seek,tell}i64 */
54 typedef __int64 off_t;
55 #define fseeko _fseeki64
56 #define ftello _ftelli64
58 /* MinGW defines off_t as long
59 and uses f{seek,tell}o64/off64_t for large files */
60 #define fseeko fseeko64
61 #define ftello ftello64
65 #define LITERALU64(hi,lo) ((((uint64_t)hi)<<32)|lo)
67 /* We should use 32-bit file operations in WebM file format
68 * when building ARM executable file (.axf) with RVCT */
69 #if !CONFIG_OS_SUPPORT
75 /* Swallow warnings about unused results of fread/fwrite */
76 static size_t wrap_fread(void *ptr, size_t size, size_t nmemb,
78 return fread(ptr, size, nmemb, stream);
80 #define fread wrap_fread
82 static size_t wrap_fwrite(const void *ptr, size_t size, size_t nmemb,
84 return fwrite(ptr, size, nmemb, stream);
86 #define fwrite wrap_fwrite
89 static const char *exec_name;
91 #define VP8_FOURCC (0x00385056)
92 #define VP9_FOURCC (0x00395056)
93 static const struct codec_item {
95 const vpx_codec_iface_t *(*iface)(void);
96 const vpx_codec_iface_t *(*dx_iface)(void);
99 #if CONFIG_VP8_ENCODER && CONFIG_VP8_DECODER
100 {"vp8", &vpx_codec_vp8_cx, &vpx_codec_vp8_dx, VP8_FOURCC},
101 #elif CONFIG_VP8_ENCODER && !CONFIG_VP8_DECODER
102 {"vp8", &vpx_codec_vp8_cx, NULL, VP8_FOURCC},
104 #if CONFIG_VP9_ENCODER && CONFIG_VP9_DECODER
105 {"vp9", &vpx_codec_vp9_cx, &vpx_codec_vp9_dx, VP9_FOURCC},
106 #elif CONFIG_VP9_ENCODER && !CONFIG_VP9_DECODER
107 {"vp9", &vpx_codec_vp9_cx, NULL, VP9_FOURCC},
111 static void usage_exit();
113 #define LOG_ERROR(label) do \
115 const char *l=label;\
119 fprintf(stderr, "%s: ", l);\
120 vfprintf(stderr, fmt, ap);\
121 fprintf(stderr, "\n");\
125 void die(const char *fmt, ...) {
131 void fatal(const char *fmt, ...) {
137 void warn(const char *fmt, ...) {
138 LOG_ERROR("Warning");
142 static void ctx_exit_on_error(vpx_codec_ctx_t *ctx, const char *s, ...) {
147 const char *detail = vpx_codec_error_detail(ctx);
149 vfprintf(stderr, s, ap);
150 fprintf(stderr, ": %s\n", vpx_codec_error(ctx));
153 fprintf(stderr, " %s\n", detail);
159 /* This structure is used to abstract the different ways of handling
160 * first pass statistics.
170 int stats_open_file(stats_io_t *stats, const char *fpf, int pass) {
176 stats->file = fopen(fpf, "wb");
178 stats->buf.buf = NULL,
179 res = (stats->file != NULL);
183 struct stat stat_buf;
186 fd = open(fpf, O_RDONLY);
187 stats->file = fdopen(fd, "rb");
188 fstat(fd, &stat_buf);
189 stats->buf.sz = stat_buf.st_size;
190 stats->buf.buf = mmap(NULL, stats->buf.sz, PROT_READ, MAP_PRIVATE,
192 res = (stats->buf.buf != NULL);
196 stats->file = fopen(fpf, "rb");
198 if (fseek(stats->file, 0, SEEK_END))
199 fatal("First-pass stats file must be seekable!");
201 stats->buf.sz = stats->buf_alloc_sz = ftell(stats->file);
204 stats->buf.buf = malloc(stats->buf_alloc_sz);
207 fatal("Failed to allocate first-pass stats buffer (%lu bytes)",
208 (unsigned long)stats->buf_alloc_sz);
210 nbytes = fread(stats->buf.buf, 1, stats->buf.sz, stats->file);
211 res = (nbytes == stats->buf.sz);
218 int stats_open_mem(stats_io_t *stats, int pass) {
224 stats->buf_alloc_sz = 64 * 1024;
225 stats->buf.buf = malloc(stats->buf_alloc_sz);
228 stats->buf_ptr = stats->buf.buf;
229 res = (stats->buf.buf != NULL);
234 void stats_close(stats_io_t *stats, int last_pass) {
236 if (stats->pass == last_pass) {
239 munmap(stats->buf.buf, stats->buf.sz);
241 free(stats->buf.buf);
248 if (stats->pass == last_pass)
249 free(stats->buf.buf);
253 void stats_write(stats_io_t *stats, const void *pkt, size_t len) {
255 (void) fwrite(pkt, 1, len, stats->file);
257 if (stats->buf.sz + len > stats->buf_alloc_sz) {
258 size_t new_sz = stats->buf_alloc_sz + 64 * 1024;
259 char *new_ptr = realloc(stats->buf.buf, new_sz);
262 stats->buf_ptr = new_ptr + (stats->buf_ptr - (char *)stats->buf.buf);
263 stats->buf.buf = new_ptr;
264 stats->buf_alloc_sz = new_sz;
266 fatal("Failed to realloc firstpass stats buffer.");
269 memcpy(stats->buf_ptr, pkt, len);
270 stats->buf.sz += len;
271 stats->buf_ptr += len;
275 vpx_fixed_buf_t stats_get(stats_io_t *stats) {
279 /* Stereo 3D packed frame format */
280 typedef enum stereo_format {
281 STEREO_FORMAT_MONO = 0,
282 STEREO_FORMAT_LEFT_RIGHT = 1,
283 STEREO_FORMAT_BOTTOM_TOP = 2,
284 STEREO_FORMAT_TOP_BOTTOM = 3,
285 STEREO_FORMAT_RIGHT_LEFT = 11
288 enum video_file_type {
294 struct detect_buffer {
305 struct detect_buffer detect;
306 enum video_file_type file_type;
309 struct vpx_rational framerate;
314 #define IVF_FRAME_HDR_SZ (4+8) /* 4 byte size + 8 byte timestamp */
315 static int read_frame(struct input_state *input, vpx_image_t *img) {
316 FILE *f = input->file;
317 enum video_file_type file_type = input->file_type;
318 y4m_input *y4m = &input->y4m;
319 struct detect_buffer *detect = &input->detect;
323 if (file_type == FILE_TYPE_Y4M) {
324 if (y4m_input_fetch_frame(y4m, f, img) < 1)
327 if (file_type == FILE_TYPE_IVF) {
328 char junk[IVF_FRAME_HDR_SZ];
330 /* Skip the frame header. We know how big the frame should be. See
331 * write_ivf_frame_header() for documentation on the frame header
334 (void) fread(junk, 1, IVF_FRAME_HDR_SZ, f);
337 for (plane = 0; plane < 3; plane++) {
339 int w = (plane ? (1 + img->d_w) / 2 : img->d_w);
340 int h = (plane ? (1 + img->d_h) / 2 : img->d_h);
343 /* Determine the correct plane based on the image format. The for-loop
344 * always counts in Y,U,V order, but this may not match the order of
349 ptr = img->planes[img->fmt == VPX_IMG_FMT_YV12 ? VPX_PLANE_V : VPX_PLANE_U];
352 ptr = img->planes[img->fmt == VPX_IMG_FMT_YV12 ? VPX_PLANE_U : VPX_PLANE_V];
355 ptr = img->planes[plane];
358 for (r = 0; r < h; r++) {
360 size_t buf_position = 0;
361 const size_t left = detect->buf_read - detect->position;
363 const size_t more = (left < needed) ? left : needed;
364 memcpy(ptr, detect->buf + detect->position, more);
367 detect->position += more;
370 shortread |= (fread(ptr + buf_position, 1, needed, f) < needed);
373 ptr += img->stride[plane];
382 unsigned int file_is_y4m(FILE *infile,
385 if (memcmp(detect, "YUV4", 4) == 0) {
391 #define IVF_FILE_HDR_SZ (32)
392 unsigned int file_is_ivf(struct input_state *input,
393 unsigned int *fourcc) {
394 char raw_hdr[IVF_FILE_HDR_SZ];
396 FILE *infile = input->file;
397 unsigned int *width = &input->w;
398 unsigned int *height = &input->h;
399 struct detect_buffer *detect = &input->detect;
401 if (memcmp(detect->buf, "DKIF", 4) != 0)
404 /* See write_ivf_file_header() for more documentation on the file header
407 if (fread(raw_hdr + 4, 1, IVF_FILE_HDR_SZ - 4, infile)
408 == IVF_FILE_HDR_SZ - 4) {
412 if (mem_get_le16(raw_hdr + 4) != 0)
413 warn("Unrecognized IVF version! This file may not decode "
416 *fourcc = mem_get_le32(raw_hdr + 8);
421 *width = mem_get_le16(raw_hdr + 12);
422 *height = mem_get_le16(raw_hdr + 14);
423 detect->position = 4;
430 static void write_ivf_file_header(FILE *outfile,
431 const vpx_codec_enc_cfg_t *cfg,
436 if (cfg->g_pass != VPX_RC_ONE_PASS && cfg->g_pass != VPX_RC_LAST_PASS)
443 mem_put_le16(header + 4, 0); /* version */
444 mem_put_le16(header + 6, 32); /* headersize */
445 mem_put_le32(header + 8, fourcc); /* headersize */
446 mem_put_le16(header + 12, cfg->g_w); /* width */
447 mem_put_le16(header + 14, cfg->g_h); /* height */
448 mem_put_le32(header + 16, cfg->g_timebase.den); /* rate */
449 mem_put_le32(header + 20, cfg->g_timebase.num); /* scale */
450 mem_put_le32(header + 24, frame_cnt); /* length */
451 mem_put_le32(header + 28, 0); /* unused */
453 (void) fwrite(header, 1, 32, outfile);
457 static void write_ivf_frame_header(FILE *outfile,
458 const vpx_codec_cx_pkt_t *pkt) {
462 if (pkt->kind != VPX_CODEC_CX_FRAME_PKT)
465 pts = pkt->data.frame.pts;
466 mem_put_le32(header, (int)pkt->data.frame.sz);
467 mem_put_le32(header + 4, pts & 0xFFFFFFFF);
468 mem_put_le32(header + 8, pts >> 32);
470 (void) fwrite(header, 1, 12, outfile);
473 static void write_ivf_frame_size(FILE *outfile, size_t size) {
475 mem_put_le32(header, (int)size);
476 (void) fwrite(header, 1, 4, outfile);
480 typedef off_t EbmlLoc;
494 vpx_rational_t framerate;
496 /* These pointers are to the start of an element */
497 off_t position_reference;
499 off_t segment_info_pos;
504 /* This pointer is to a specific element to be serialized */
507 /* These pointers are to the size field of the element */
508 EbmlLoc startSegment;
509 EbmlLoc startCluster;
511 uint32_t cluster_timecode;
514 struct cue_entry *cue_list;
520 void Ebml_Write(EbmlGlobal *glob, const void *buffer_in, unsigned long len) {
521 (void) fwrite(buffer_in, 1, len, glob->stream);
524 #define WRITE_BUFFER(s) \
525 for(i = len-1; i>=0; i--)\
527 x = (char)(*(const s *)buffer_in >> (i * CHAR_BIT)); \
528 Ebml_Write(glob, &x, 1); \
530 void Ebml_Serialize(EbmlGlobal *glob, const void *buffer_in, int buffer_size, unsigned long len) {
540 switch (buffer_size) {
545 WRITE_BUFFER(int16_t)
548 WRITE_BUFFER(int32_t)
551 WRITE_BUFFER(int64_t)
559 /* Need a fixed size serializer for the track ID. libmkv provides a 64 bit
560 * one, but not a 32 bit one.
562 static void Ebml_SerializeUnsigned32(EbmlGlobal *glob, unsigned long class_id, uint64_t ui) {
563 unsigned char sizeSerialized = 4 | 0x80;
564 Ebml_WriteID(glob, class_id);
565 Ebml_Serialize(glob, &sizeSerialized, sizeof(sizeSerialized), 1);
566 Ebml_Serialize(glob, &ui, sizeof(ui), 4);
571 Ebml_StartSubElement(EbmlGlobal *glob, EbmlLoc *ebmlLoc,
572 unsigned long class_id) {
573 /* todo this is always taking 8 bytes, this may need later optimization */
574 /* this is a key that says length unknown */
575 uint64_t unknownLen = LITERALU64(0x01FFFFFF, 0xFFFFFFFF);
577 Ebml_WriteID(glob, class_id);
578 *ebmlLoc = ftello(glob->stream);
579 Ebml_Serialize(glob, &unknownLen, sizeof(unknownLen), 8);
583 Ebml_EndSubElement(EbmlGlobal *glob, EbmlLoc *ebmlLoc) {
587 /* Save the current stream pointer */
588 pos = ftello(glob->stream);
590 /* Calculate the size of this element */
591 size = pos - *ebmlLoc - 8;
592 size |= LITERALU64(0x01000000, 0x00000000);
594 /* Seek back to the beginning of the element and write the new size */
595 fseeko(glob->stream, *ebmlLoc, SEEK_SET);
596 Ebml_Serialize(glob, &size, sizeof(size), 8);
598 /* Reset the stream pointer */
599 fseeko(glob->stream, pos, SEEK_SET);
604 write_webm_seek_element(EbmlGlobal *ebml, unsigned long id, off_t pos) {
605 uint64_t offset = pos - ebml->position_reference;
607 Ebml_StartSubElement(ebml, &start, Seek);
608 Ebml_SerializeBinary(ebml, SeekID, id);
609 Ebml_SerializeUnsigned64(ebml, SeekPosition, offset);
610 Ebml_EndSubElement(ebml, &start);
615 write_webm_seek_info(EbmlGlobal *ebml) {
619 /* Save the current stream pointer */
620 pos = ftello(ebml->stream);
622 if (ebml->seek_info_pos)
623 fseeko(ebml->stream, ebml->seek_info_pos, SEEK_SET);
625 ebml->seek_info_pos = pos;
630 Ebml_StartSubElement(ebml, &start, SeekHead);
631 write_webm_seek_element(ebml, Tracks, ebml->track_pos);
632 write_webm_seek_element(ebml, Cues, ebml->cue_pos);
633 write_webm_seek_element(ebml, Info, ebml->segment_info_pos);
634 Ebml_EndSubElement(ebml, &start);
640 char version_string[64];
642 /* Assemble version string */
644 strcpy(version_string, "vpxenc");
646 strcpy(version_string, "vpxenc ");
647 strncat(version_string,
648 vpx_codec_version_str(),
649 sizeof(version_string) - 1 - strlen(version_string));
652 frame_time = (uint64_t)1000 * ebml->framerate.den
653 / ebml->framerate.num;
654 ebml->segment_info_pos = ftello(ebml->stream);
655 Ebml_StartSubElement(ebml, &startInfo, Info);
656 Ebml_SerializeUnsigned(ebml, TimecodeScale, 1000000);
657 Ebml_SerializeFloat(ebml, Segment_Duration,
658 (double)(ebml->last_pts_ms + frame_time));
659 Ebml_SerializeString(ebml, 0x4D80, version_string);
660 Ebml_SerializeString(ebml, 0x5741, version_string);
661 Ebml_EndSubElement(ebml, &startInfo);
667 write_webm_file_header(EbmlGlobal *glob,
668 const vpx_codec_enc_cfg_t *cfg,
669 const struct vpx_rational *fps,
670 stereo_format_t stereo_fmt,
671 unsigned int fourcc) {
674 Ebml_StartSubElement(glob, &start, EBML);
675 Ebml_SerializeUnsigned(glob, EBMLVersion, 1);
676 Ebml_SerializeUnsigned(glob, EBMLReadVersion, 1);
677 Ebml_SerializeUnsigned(glob, EBMLMaxIDLength, 4);
678 Ebml_SerializeUnsigned(glob, EBMLMaxSizeLength, 8);
679 Ebml_SerializeString(glob, DocType, "webm");
680 Ebml_SerializeUnsigned(glob, DocTypeVersion, 2);
681 Ebml_SerializeUnsigned(glob, DocTypeReadVersion, 2);
682 Ebml_EndSubElement(glob, &start);
685 Ebml_StartSubElement(glob, &glob->startSegment, Segment);
686 glob->position_reference = ftello(glob->stream);
687 glob->framerate = *fps;
688 write_webm_seek_info(glob);
692 glob->track_pos = ftello(glob->stream);
693 Ebml_StartSubElement(glob, &trackStart, Tracks);
695 unsigned int trackNumber = 1;
696 uint64_t trackID = 0;
699 Ebml_StartSubElement(glob, &start, TrackEntry);
700 Ebml_SerializeUnsigned(glob, TrackNumber, trackNumber);
701 glob->track_id_pos = ftello(glob->stream);
702 Ebml_SerializeUnsigned32(glob, TrackUID, trackID);
703 Ebml_SerializeUnsigned(glob, TrackType, 1);
704 Ebml_SerializeString(glob, CodecID,
705 fourcc == VP8_FOURCC ? "V_VP8" : "V_VP9");
707 unsigned int pixelWidth = cfg->g_w;
708 unsigned int pixelHeight = cfg->g_h;
709 float frameRate = (float)fps->num / (float)fps->den;
712 Ebml_StartSubElement(glob, &videoStart, Video);
713 Ebml_SerializeUnsigned(glob, PixelWidth, pixelWidth);
714 Ebml_SerializeUnsigned(glob, PixelHeight, pixelHeight);
715 Ebml_SerializeUnsigned(glob, StereoMode, stereo_fmt);
716 Ebml_SerializeFloat(glob, FrameRate, frameRate);
717 Ebml_EndSubElement(glob, &videoStart);
719 Ebml_EndSubElement(glob, &start); /* Track Entry */
721 Ebml_EndSubElement(glob, &trackStart);
723 /* segment element is open */
729 write_webm_block(EbmlGlobal *glob,
730 const vpx_codec_enc_cfg_t *cfg,
731 const vpx_codec_cx_pkt_t *pkt) {
732 unsigned long block_length;
733 unsigned char track_number;
734 unsigned short block_timecode = 0;
737 int start_cluster = 0, is_keyframe;
739 /* Calculate the PTS of this frame in milliseconds */
740 pts_ms = pkt->data.frame.pts * 1000
741 * (uint64_t)cfg->g_timebase.num / (uint64_t)cfg->g_timebase.den;
742 if (pts_ms <= glob->last_pts_ms)
743 pts_ms = glob->last_pts_ms + 1;
744 glob->last_pts_ms = pts_ms;
746 /* Calculate the relative time of this block */
747 if (pts_ms - glob->cluster_timecode > SHRT_MAX)
750 block_timecode = (unsigned short)pts_ms - glob->cluster_timecode;
752 is_keyframe = (pkt->data.frame.flags & VPX_FRAME_IS_KEY);
753 if (start_cluster || is_keyframe) {
754 if (glob->cluster_open)
755 Ebml_EndSubElement(glob, &glob->startCluster);
757 /* Open the new cluster */
759 glob->cluster_open = 1;
760 glob->cluster_timecode = (uint32_t)pts_ms;
761 glob->cluster_pos = ftello(glob->stream);
762 Ebml_StartSubElement(glob, &glob->startCluster, Cluster); /* cluster */
763 Ebml_SerializeUnsigned(glob, Timecode, glob->cluster_timecode);
765 /* Save a cue point if this is a keyframe. */
767 struct cue_entry *cue, *new_cue_list;
769 new_cue_list = realloc(glob->cue_list,
770 (glob->cues + 1) * sizeof(struct cue_entry));
772 glob->cue_list = new_cue_list;
774 fatal("Failed to realloc cue list.");
776 cue = &glob->cue_list[glob->cues];
777 cue->time = glob->cluster_timecode;
778 cue->loc = glob->cluster_pos;
783 /* Write the Simple Block */
784 Ebml_WriteID(glob, SimpleBlock);
786 block_length = (unsigned long)pkt->data.frame.sz + 4;
787 block_length |= 0x10000000;
788 Ebml_Serialize(glob, &block_length, sizeof(block_length), 4);
791 track_number |= 0x80;
792 Ebml_Write(glob, &track_number, 1);
794 Ebml_Serialize(glob, &block_timecode, sizeof(block_timecode), 2);
799 if (pkt->data.frame.flags & VPX_FRAME_IS_INVISIBLE)
801 Ebml_Write(glob, &flags, 1);
803 Ebml_Write(glob, pkt->data.frame.buf, (unsigned long)pkt->data.frame.sz);
808 write_webm_file_footer(EbmlGlobal *glob, long hash) {
810 if (glob->cluster_open)
811 Ebml_EndSubElement(glob, &glob->startCluster);
817 glob->cue_pos = ftello(glob->stream);
818 Ebml_StartSubElement(glob, &start, Cues);
819 for (i = 0; i < glob->cues; i++) {
820 struct cue_entry *cue = &glob->cue_list[i];
823 Ebml_StartSubElement(glob, &start, CuePoint);
827 Ebml_SerializeUnsigned(glob, CueTime, cue->time);
829 Ebml_StartSubElement(glob, &start, CueTrackPositions);
830 Ebml_SerializeUnsigned(glob, CueTrack, 1);
831 Ebml_SerializeUnsigned64(glob, CueClusterPosition,
832 cue->loc - glob->position_reference);
833 Ebml_EndSubElement(glob, &start);
835 Ebml_EndSubElement(glob, &start);
837 Ebml_EndSubElement(glob, &start);
840 Ebml_EndSubElement(glob, &glob->startSegment);
842 /* Patch up the seek info block */
843 write_webm_seek_info(glob);
845 /* Patch up the track id */
846 fseeko(glob->stream, glob->track_id_pos, SEEK_SET);
847 Ebml_SerializeUnsigned32(glob, TrackUID, glob->debug ? 0xDEADBEEF : hash);
849 fseeko(glob->stream, 0, SEEK_END);
853 /* Murmur hash derived from public domain reference implementation at
854 * http:// sites.google.com/site/murmurhash/
856 static unsigned int murmur(const void *key, int len, unsigned int seed) {
857 const unsigned int m = 0x5bd1e995;
860 unsigned int h = seed ^ len;
862 const unsigned char *data = (const unsigned char *)key;
902 static double vp8_mse2psnr(double Samples, double Peak, double Mse) {
905 if ((double)Mse > 0.0)
906 psnr = 10.0 * log10(Peak * Peak * Samples / Mse);
908 psnr = MAX_PSNR; /* Limit to prevent / 0 */
918 static const arg_def_t debugmode = ARG_DEF("D", "debug", 0,
919 "Debug mode (makes output deterministic)");
920 static const arg_def_t outputfile = ARG_DEF("o", "output", 1,
922 static const arg_def_t use_yv12 = ARG_DEF(NULL, "yv12", 0,
923 "Input file is YV12 ");
924 static const arg_def_t use_i420 = ARG_DEF(NULL, "i420", 0,
925 "Input file is I420 (default)");
926 static const arg_def_t codecarg = ARG_DEF(NULL, "codec", 1,
928 static const arg_def_t passes = ARG_DEF("p", "passes", 1,
929 "Number of passes (1/2)");
930 static const arg_def_t pass_arg = ARG_DEF(NULL, "pass", 1,
931 "Pass to execute (1/2)");
932 static const arg_def_t fpf_name = ARG_DEF(NULL, "fpf", 1,
933 "First pass statistics file name");
934 static const arg_def_t limit = ARG_DEF(NULL, "limit", 1,
935 "Stop encoding after n input frames");
936 static const arg_def_t skip = ARG_DEF(NULL, "skip", 1,
937 "Skip the first n input frames");
938 static const arg_def_t deadline = ARG_DEF("d", "deadline", 1,
939 "Deadline per frame (usec)");
940 static const arg_def_t best_dl = ARG_DEF(NULL, "best", 0,
941 "Use Best Quality Deadline");
942 static const arg_def_t good_dl = ARG_DEF(NULL, "good", 0,
943 "Use Good Quality Deadline");
944 static const arg_def_t rt_dl = ARG_DEF(NULL, "rt", 0,
945 "Use Realtime Quality Deadline");
946 static const arg_def_t quietarg = ARG_DEF("q", "quiet", 0,
947 "Do not print encode progress");
948 static const arg_def_t verbosearg = ARG_DEF("v", "verbose", 0,
949 "Show encoder parameters");
950 static const arg_def_t psnrarg = ARG_DEF(NULL, "psnr", 0,
951 "Show PSNR in status line");
952 static const arg_def_t recontest = ARG_DEF(NULL, "test-decode", 0,
953 "Test encode/decode mismatch");
954 static const arg_def_t framerate = ARG_DEF(NULL, "fps", 1,
955 "Stream frame rate (rate/scale)");
956 static const arg_def_t use_ivf = ARG_DEF(NULL, "ivf", 0,
957 "Output IVF (default is WebM)");
958 static const arg_def_t out_part = ARG_DEF("P", "output-partitions", 0,
959 "Makes encoder output partitions. Requires IVF output!");
960 static const arg_def_t q_hist_n = ARG_DEF(NULL, "q-hist", 1,
961 "Show quantizer histogram (n-buckets)");
962 static const arg_def_t rate_hist_n = ARG_DEF(NULL, "rate-hist", 1,
963 "Show rate histogram (n-buckets)");
964 static const arg_def_t *main_args[] = {
966 &outputfile, &codecarg, &passes, &pass_arg, &fpf_name, &limit, &skip,
967 &deadline, &best_dl, &good_dl, &rt_dl,
968 &quietarg, &verbosearg, &psnrarg, &use_ivf, &out_part, &q_hist_n, &rate_hist_n,
972 static const arg_def_t usage = ARG_DEF("u", "usage", 1,
973 "Usage profile number to use");
974 static const arg_def_t threads = ARG_DEF("t", "threads", 1,
975 "Max number of threads to use");
976 static const arg_def_t profile = ARG_DEF(NULL, "profile", 1,
977 "Bitstream profile number to use");
978 static const arg_def_t width = ARG_DEF("w", "width", 1,
980 static const arg_def_t height = ARG_DEF("h", "height", 1,
982 static const struct arg_enum_list stereo_mode_enum[] = {
983 {"mono", STEREO_FORMAT_MONO},
984 {"left-right", STEREO_FORMAT_LEFT_RIGHT},
985 {"bottom-top", STEREO_FORMAT_BOTTOM_TOP},
986 {"top-bottom", STEREO_FORMAT_TOP_BOTTOM},
987 {"right-left", STEREO_FORMAT_RIGHT_LEFT},
990 static const arg_def_t stereo_mode = ARG_DEF_ENUM(NULL, "stereo-mode", 1,
991 "Stereo 3D video format", stereo_mode_enum);
992 static const arg_def_t timebase = ARG_DEF(NULL, "timebase", 1,
993 "Output timestamp precision (fractional seconds)");
994 static const arg_def_t error_resilient = ARG_DEF(NULL, "error-resilient", 1,
995 "Enable error resiliency features");
996 static const arg_def_t lag_in_frames = ARG_DEF(NULL, "lag-in-frames", 1,
997 "Max number of frames to lag");
999 static const arg_def_t *global_args[] = {
1000 &use_yv12, &use_i420, &usage, &threads, &profile,
1001 &width, &height, &stereo_mode, &timebase, &framerate, &error_resilient,
1002 &lag_in_frames, NULL
1005 static const arg_def_t dropframe_thresh = ARG_DEF(NULL, "drop-frame", 1,
1006 "Temporal resampling threshold (buf %)");
1007 static const arg_def_t resize_allowed = ARG_DEF(NULL, "resize-allowed", 1,
1008 "Spatial resampling enabled (bool)");
1009 static const arg_def_t resize_up_thresh = ARG_DEF(NULL, "resize-up", 1,
1010 "Upscale threshold (buf %)");
1011 static const arg_def_t resize_down_thresh = ARG_DEF(NULL, "resize-down", 1,
1012 "Downscale threshold (buf %)");
1013 static const struct arg_enum_list end_usage_enum[] = {
1019 static const arg_def_t end_usage = ARG_DEF_ENUM(NULL, "end-usage", 1,
1020 "Rate control mode", end_usage_enum);
1021 static const arg_def_t target_bitrate = ARG_DEF(NULL, "target-bitrate", 1,
1023 static const arg_def_t min_quantizer = ARG_DEF(NULL, "min-q", 1,
1024 "Minimum (best) quantizer");
1025 static const arg_def_t max_quantizer = ARG_DEF(NULL, "max-q", 1,
1026 "Maximum (worst) quantizer");
1027 static const arg_def_t undershoot_pct = ARG_DEF(NULL, "undershoot-pct", 1,
1028 "Datarate undershoot (min) target (%)");
1029 static const arg_def_t overshoot_pct = ARG_DEF(NULL, "overshoot-pct", 1,
1030 "Datarate overshoot (max) target (%)");
1031 static const arg_def_t buf_sz = ARG_DEF(NULL, "buf-sz", 1,
1032 "Client buffer size (ms)");
1033 static const arg_def_t buf_initial_sz = ARG_DEF(NULL, "buf-initial-sz", 1,
1034 "Client initial buffer size (ms)");
1035 static const arg_def_t buf_optimal_sz = ARG_DEF(NULL, "buf-optimal-sz", 1,
1036 "Client optimal buffer size (ms)");
1037 static const arg_def_t *rc_args[] = {
1038 &dropframe_thresh, &resize_allowed, &resize_up_thresh, &resize_down_thresh,
1039 &end_usage, &target_bitrate, &min_quantizer, &max_quantizer,
1040 &undershoot_pct, &overshoot_pct, &buf_sz, &buf_initial_sz, &buf_optimal_sz,
1045 static const arg_def_t bias_pct = ARG_DEF(NULL, "bias-pct", 1,
1046 "CBR/VBR bias (0=CBR, 100=VBR)");
1047 static const arg_def_t minsection_pct = ARG_DEF(NULL, "minsection-pct", 1,
1048 "GOP min bitrate (% of target)");
1049 static const arg_def_t maxsection_pct = ARG_DEF(NULL, "maxsection-pct", 1,
1050 "GOP max bitrate (% of target)");
1051 static const arg_def_t *rc_twopass_args[] = {
1052 &bias_pct, &minsection_pct, &maxsection_pct, NULL
1056 static const arg_def_t kf_min_dist = ARG_DEF(NULL, "kf-min-dist", 1,
1057 "Minimum keyframe interval (frames)");
1058 static const arg_def_t kf_max_dist = ARG_DEF(NULL, "kf-max-dist", 1,
1059 "Maximum keyframe interval (frames)");
1060 static const arg_def_t kf_disabled = ARG_DEF(NULL, "disable-kf", 0,
1061 "Disable keyframe placement");
1062 static const arg_def_t *kf_args[] = {
1063 &kf_min_dist, &kf_max_dist, &kf_disabled, NULL
1067 static const arg_def_t noise_sens = ARG_DEF(NULL, "noise-sensitivity", 1,
1068 "Noise sensitivity (frames to blur)");
1069 static const arg_def_t sharpness = ARG_DEF(NULL, "sharpness", 1,
1070 "Filter sharpness (0-7)");
1071 static const arg_def_t static_thresh = ARG_DEF(NULL, "static-thresh", 1,
1072 "Motion detection threshold");
1073 static const arg_def_t cpu_used = ARG_DEF(NULL, "cpu-used", 1,
1074 "CPU Used (-16..16)");
1075 static const arg_def_t token_parts = ARG_DEF(NULL, "token-parts", 1,
1076 "Number of token partitions to use, log2");
1077 static const arg_def_t auto_altref = ARG_DEF(NULL, "auto-alt-ref", 1,
1078 "Enable automatic alt reference frames");
1079 static const arg_def_t arnr_maxframes = ARG_DEF(NULL, "arnr-maxframes", 1,
1080 "AltRef Max Frames");
1081 static const arg_def_t arnr_strength = ARG_DEF(NULL, "arnr-strength", 1,
1083 static const arg_def_t arnr_type = ARG_DEF(NULL, "arnr-type", 1,
1085 static const struct arg_enum_list tuning_enum[] = {
1086 {"psnr", VP8_TUNE_PSNR},
1087 {"ssim", VP8_TUNE_SSIM},
1090 static const arg_def_t tune_ssim = ARG_DEF_ENUM(NULL, "tune", 1,
1091 "Material to favor", tuning_enum);
1092 static const arg_def_t cq_level = ARG_DEF(NULL, "cq-level", 1,
1093 "Constrained Quality Level");
1094 static const arg_def_t max_intra_rate_pct = ARG_DEF(NULL, "max-intra-rate", 1,
1095 "Max I-frame bitrate (pct)");
1097 static const arg_def_t lossless = ARG_DEF(NULL, "lossless", 1, "Lossless mode");
1100 #if CONFIG_VP8_ENCODER
1101 static const arg_def_t *vp8_args[] = {
1102 &cpu_used, &auto_altref, &noise_sens, &sharpness, &static_thresh,
1103 &token_parts, &arnr_maxframes, &arnr_strength, &arnr_type,
1104 &tune_ssim, &cq_level, &max_intra_rate_pct,
1107 static const int vp8_arg_ctrl_map[] = {
1108 VP8E_SET_CPUUSED, VP8E_SET_ENABLEAUTOALTREF,
1109 VP8E_SET_NOISE_SENSITIVITY, VP8E_SET_SHARPNESS, VP8E_SET_STATIC_THRESHOLD,
1110 VP8E_SET_TOKEN_PARTITIONS,
1111 VP8E_SET_ARNR_MAXFRAMES, VP8E_SET_ARNR_STRENGTH, VP8E_SET_ARNR_TYPE,
1112 VP8E_SET_TUNING, VP8E_SET_CQ_LEVEL, VP8E_SET_MAX_INTRA_BITRATE_PCT,
1117 #if CONFIG_VP9_ENCODER
1118 static const arg_def_t *vp9_args[] = {
1119 &cpu_used, &auto_altref, &noise_sens, &sharpness, &static_thresh,
1120 &token_parts, &arnr_maxframes, &arnr_strength, &arnr_type,
1121 &tune_ssim, &cq_level, &max_intra_rate_pct,
1127 static const int vp9_arg_ctrl_map[] = {
1128 VP8E_SET_CPUUSED, VP8E_SET_ENABLEAUTOALTREF,
1129 VP8E_SET_NOISE_SENSITIVITY, VP8E_SET_SHARPNESS, VP8E_SET_STATIC_THRESHOLD,
1130 VP8E_SET_TOKEN_PARTITIONS,
1131 VP8E_SET_ARNR_MAXFRAMES, VP8E_SET_ARNR_STRENGTH, VP8E_SET_ARNR_TYPE,
1132 VP8E_SET_TUNING, VP8E_SET_CQ_LEVEL, VP8E_SET_MAX_INTRA_BITRATE_PCT,
1140 static const arg_def_t *no_args[] = { NULL };
1142 static void usage_exit() {
1145 fprintf(stderr, "Usage: %s <options> -o dst_filename src_filename \n",
1148 fprintf(stderr, "\nOptions:\n");
1149 arg_show_usage(stdout, main_args);
1150 fprintf(stderr, "\nEncoder Global Options:\n");
1151 arg_show_usage(stdout, global_args);
1152 fprintf(stderr, "\nRate Control Options:\n");
1153 arg_show_usage(stdout, rc_args);
1154 fprintf(stderr, "\nTwopass Rate Control Options:\n");
1155 arg_show_usage(stdout, rc_twopass_args);
1156 fprintf(stderr, "\nKeyframe Placement Options:\n");
1157 arg_show_usage(stdout, kf_args);
1158 #if CONFIG_VP8_ENCODER
1159 fprintf(stderr, "\nVP8 Specific Options:\n");
1160 arg_show_usage(stdout, vp8_args);
1162 #if CONFIG_VP9_ENCODER
1163 fprintf(stderr, "\nVP9 Specific Options:\n");
1164 arg_show_usage(stdout, vp9_args);
1166 fprintf(stderr, "\nStream timebase (--timebase):\n"
1167 " The desired precision of timestamps in the output, expressed\n"
1168 " in fractional seconds. Default is 1/1000.\n");
1169 fprintf(stderr, "\n"
1170 "Included encoders:\n"
1173 for (i = 0; i < sizeof(codecs) / sizeof(codecs[0]); i++)
1174 fprintf(stderr, " %-6s - %s\n",
1176 vpx_codec_iface_name(codecs[i].iface()));
1182 #define HIST_BAR_MAX 40
1183 struct hist_bucket {
1184 int low, high, count;
1188 static int merge_hist_buckets(struct hist_bucket *bucket,
1191 int small_bucket = 0, merge_bucket = INT_MAX, big_bucket = 0;
1192 int buckets = *buckets_;
1195 /* Find the extrema for this list of buckets */
1196 big_bucket = small_bucket = 0;
1197 for (i = 0; i < buckets; i++) {
1198 if (bucket[i].count < bucket[small_bucket].count)
1200 if (bucket[i].count > bucket[big_bucket].count)
1204 /* If we have too many buckets, merge the smallest with an adjacent
1207 while (buckets > max_buckets) {
1208 int last_bucket = buckets - 1;
1210 /* merge the small bucket with an adjacent one. */
1211 if (small_bucket == 0)
1213 else if (small_bucket == last_bucket)
1214 merge_bucket = last_bucket - 1;
1215 else if (bucket[small_bucket - 1].count < bucket[small_bucket + 1].count)
1216 merge_bucket = small_bucket - 1;
1218 merge_bucket = small_bucket + 1;
1220 assert(abs(merge_bucket - small_bucket) <= 1);
1221 assert(small_bucket < buckets);
1222 assert(big_bucket < buckets);
1223 assert(merge_bucket < buckets);
1225 if (merge_bucket < small_bucket) {
1226 bucket[merge_bucket].high = bucket[small_bucket].high;
1227 bucket[merge_bucket].count += bucket[small_bucket].count;
1229 bucket[small_bucket].high = bucket[merge_bucket].high;
1230 bucket[small_bucket].count += bucket[merge_bucket].count;
1231 merge_bucket = small_bucket;
1234 assert(bucket[merge_bucket].low != bucket[merge_bucket].high);
1238 /* Remove the merge_bucket from the list, and find the new small
1239 * and big buckets while we're at it
1241 big_bucket = small_bucket = 0;
1242 for (i = 0; i < buckets; i++) {
1243 if (i > merge_bucket)
1244 bucket[i] = bucket[i + 1];
1246 if (bucket[i].count < bucket[small_bucket].count)
1248 if (bucket[i].count > bucket[big_bucket].count)
1254 *buckets_ = buckets;
1255 return bucket[big_bucket].count;
1259 static void show_histogram(const struct hist_bucket *bucket,
1263 const char *pat1, *pat2;
1266 switch ((int)(log(bucket[buckets - 1].high) / log(10)) + 1) {
1293 pat1 = "%12d %10s: ";
1294 pat2 = "%12d-%10d: ";
1298 for (i = 0; i < buckets; i++) {
1303 pct = (float)(100.0 * bucket[i].count / total);
1304 len = HIST_BAR_MAX * bucket[i].count / scale;
1307 assert(len <= HIST_BAR_MAX);
1309 if (bucket[i].low == bucket[i].high)
1310 fprintf(stderr, pat1, bucket[i].low, "");
1312 fprintf(stderr, pat2, bucket[i].low, bucket[i].high);
1314 for (j = 0; j < HIST_BAR_MAX; j++)
1315 fprintf(stderr, j < len ? "=" : " ");
1316 fprintf(stderr, "\t%5d (%6.2f%%)\n", bucket[i].count, pct);
1321 static void show_q_histogram(const int counts[64], int max_buckets) {
1322 struct hist_bucket bucket[64];
1329 for (i = 0; i < 64; i++) {
1331 bucket[buckets].low = bucket[buckets].high = i;
1332 bucket[buckets].count = counts[i];
1338 fprintf(stderr, "\nQuantizer Selection:\n");
1339 scale = merge_hist_buckets(bucket, &buckets, max_buckets);
1340 show_histogram(bucket, buckets, total, scale);
1344 #define RATE_BINS (100)
1350 struct hist_bucket bucket[RATE_BINS];
1355 static void init_rate_histogram(struct rate_hist *hist,
1356 const vpx_codec_enc_cfg_t *cfg,
1357 const vpx_rational_t *fps) {
1360 /* Determine the number of samples in the buffer. Use the file's framerate
1361 * to determine the number of frames in rc_buf_sz milliseconds, with an
1362 * adjustment (5/4) to account for alt-refs
1364 hist->samples = cfg->rc_buf_sz * 5 / 4 * fps->num / fps->den / 1000;
1366 /* prevent division by zero */
1367 if (hist->samples == 0)
1370 hist->pts = calloc(hist->samples, sizeof(*hist->pts));
1371 hist->sz = calloc(hist->samples, sizeof(*hist->sz));
1372 for (i = 0; i < RATE_BINS; i++) {
1373 hist->bucket[i].low = INT_MAX;
1374 hist->bucket[i].high = 0;
1375 hist->bucket[i].count = 0;
1380 static void destroy_rate_histogram(struct rate_hist *hist) {
1386 static void update_rate_histogram(struct rate_hist *hist,
1387 const vpx_codec_enc_cfg_t *cfg,
1388 const vpx_codec_cx_pkt_t *pkt) {
1390 int64_t now, then, sum_sz = 0, avg_bitrate;
1392 now = pkt->data.frame.pts * 1000
1393 * (uint64_t)cfg->g_timebase.num / (uint64_t)cfg->g_timebase.den;
1395 idx = hist->frames++ % hist->samples;
1396 hist->pts[idx] = now;
1397 hist->sz[idx] = (int)pkt->data.frame.sz;
1399 if (now < cfg->rc_buf_initial_sz)
1404 /* Sum the size over the past rc_buf_sz ms */
1405 for (i = hist->frames; i > 0 && hist->frames - i < hist->samples; i--) {
1406 int i_idx = (i - 1) % hist->samples;
1408 then = hist->pts[i_idx];
1409 if (now - then > cfg->rc_buf_sz)
1411 sum_sz += hist->sz[i_idx];
1417 avg_bitrate = sum_sz * 8 * 1000 / (now - then);
1418 idx = (int)(avg_bitrate * (RATE_BINS / 2) / (cfg->rc_target_bitrate * 1000));
1421 if (idx > RATE_BINS - 1)
1422 idx = RATE_BINS - 1;
1423 if (hist->bucket[idx].low > avg_bitrate)
1424 hist->bucket[idx].low = (int)avg_bitrate;
1425 if (hist->bucket[idx].high < avg_bitrate)
1426 hist->bucket[idx].high = (int)avg_bitrate;
1427 hist->bucket[idx].count++;
1432 static void show_rate_histogram(struct rate_hist *hist,
1433 const vpx_codec_enc_cfg_t *cfg,
1438 for (i = 0; i < RATE_BINS; i++) {
1439 if (hist->bucket[i].low == INT_MAX)
1441 hist->bucket[buckets++] = hist->bucket[i];
1444 fprintf(stderr, "\nRate (over %dms window):\n", cfg->rc_buf_sz);
1445 scale = merge_hist_buckets(hist->bucket, &buckets, max_buckets);
1446 show_histogram(hist->bucket, buckets, hist->total, scale);
1449 #define mmin(a, b) ((a) < (b) ? (a) : (b))
1450 static void find_mismatch(vpx_image_t *img1, vpx_image_t *img2,
1451 int yloc[2], int uloc[2], int vloc[2]) {
1454 yloc[0] = yloc[1] = -1;
1455 for (i = 0, match = 1; match && i < img1->d_h; i+=32) {
1456 for (j = 0; match && j < img1->d_w; j+=32) {
1458 int si = mmin(i + 32, img1->d_h) - i;
1459 int sj = mmin(j + 32, img1->d_w) - j;
1460 for (k = 0; match && k < si; k++)
1461 for (l = 0; match && l < sj; l++) {
1462 if (*(img1->planes[VPX_PLANE_Y] +
1463 (i + k) * img1->stride[VPX_PLANE_Y] + j + l) !=
1464 *(img2->planes[VPX_PLANE_Y] +
1465 (i + k) * img2->stride[VPX_PLANE_Y] + j + l)) {
1474 uloc[0] = uloc[1] = -1;
1475 for (i = 0, match = 1; match && i < (img1->d_h + 1) / 2; i+=16) {
1476 for (j = 0; j < match && (img1->d_w + 1) / 2; j+=16) {
1478 int si = mmin(i + 16, (img1->d_h + 1) / 2) - i;
1479 int sj = mmin(j + 16, (img1->d_w + 1) / 2) - j;
1480 for (k = 0; match && k < si; k++)
1481 for (l = 0; match && l < sj; l++) {
1482 if (*(img1->planes[VPX_PLANE_U] +
1483 (i + k) * img1->stride[VPX_PLANE_U] + j + l) !=
1484 *(img2->planes[VPX_PLANE_U] +
1485 (i + k) * img2->stride[VPX_PLANE_U] + j + l)) {
1494 vloc[0] = vloc[1] = -1;
1495 for (i = 0, match = 1; match && i < (img1->d_h + 1) / 2; i+=16) {
1496 for (j = 0; j < match && (img1->d_w + 1) / 2; j+=16) {
1498 int si = mmin(i + 16, (img1->d_h + 1) / 2) - i;
1499 int sj = mmin(j + 16, (img1->d_w + 1) / 2) - j;
1500 for (k = 0; match && k < si; k++)
1501 for (l = 0; match && l < sj; l++) {
1502 if (*(img1->planes[VPX_PLANE_V] +
1503 (i + k) * img1->stride[VPX_PLANE_V] + j + l) !=
1504 *(img2->planes[VPX_PLANE_V] +
1505 (i + k) * img2->stride[VPX_PLANE_V] + j + l)) {
1516 static int compare_img(vpx_image_t *img1, vpx_image_t *img2)
1521 match &= (img1->fmt == img2->fmt);
1522 match &= (img1->w == img2->w);
1523 match &= (img1->h == img2->h);
1525 for (i = 0; i < img1->d_h; i++)
1526 match &= (memcmp(img1->planes[VPX_PLANE_Y]+i*img1->stride[VPX_PLANE_Y],
1527 img2->planes[VPX_PLANE_Y]+i*img2->stride[VPX_PLANE_Y],
1530 for (i = 0; i < img1->d_h/2; i++)
1531 match &= (memcmp(img1->planes[VPX_PLANE_U]+i*img1->stride[VPX_PLANE_U],
1532 img2->planes[VPX_PLANE_U]+i*img2->stride[VPX_PLANE_U],
1533 (img1->d_w + 1) / 2) == 0);
1535 for (i = 0; i < img1->d_h/2; i++)
1536 match &= (memcmp(img1->planes[VPX_PLANE_V]+i*img1->stride[VPX_PLANE_U],
1537 img2->planes[VPX_PLANE_V]+i*img2->stride[VPX_PLANE_U],
1538 (img1->d_w + 1) / 2) == 0);
1544 #define NELEMENTS(x) (sizeof(x)/sizeof(x[0]))
1545 #define MAX(x,y) ((x)>(y)?(x):(y))
1546 #if CONFIG_VP8_ENCODER && !CONFIG_VP9_ENCODER
1547 #define ARG_CTRL_CNT_MAX NELEMENTS(vp8_arg_ctrl_map)
1548 #elif !CONFIG_VP8_ENCODER && CONFIG_VP9_ENCODER
1549 #define ARG_CTRL_CNT_MAX NELEMENTS(vp9_arg_ctrl_map)
1551 #define ARG_CTRL_CNT_MAX MAX(NELEMENTS(vp8_arg_ctrl_map), \
1552 NELEMENTS(vp9_arg_ctrl_map))
1555 /* Configuration elements common to all streams */
1556 struct global_config {
1557 const struct codec_item *codec;
1570 struct vpx_rational framerate;
1573 int show_q_hist_buckets;
1574 int show_rate_hist_buckets;
1578 /* Per-stream configuration */
1579 struct stream_config {
1580 struct vpx_codec_enc_cfg cfg;
1582 const char *stats_fn;
1583 stereo_format_t stereo_fmt;
1584 int arg_ctrls[ARG_CTRL_CNT_MAX][2];
1587 int have_kf_max_dist;
1591 struct stream_state {
1593 struct stream_state *next;
1594 struct stream_config config;
1596 struct rate_hist rate_hist;
1599 uint64_t psnr_sse_total;
1600 uint64_t psnr_samples_total;
1601 double psnr_totals[4];
1604 vpx_codec_ctx_t encoder;
1605 unsigned int frames_out;
1609 vpx_codec_ctx_t decoder;
1610 vpx_ref_frame_t ref_enc;
1611 vpx_ref_frame_t ref_dec;
1616 void validate_positive_rational(const char *msg,
1617 struct vpx_rational *rat) {
1624 die("Error: %s must be positive\n", msg);
1627 die("Error: %s has zero denominator\n", msg);
1631 static void parse_global_config(struct global_config *global, char **argv) {
1632 char **argi, **argj;
1635 /* Initialize default parameters */
1636 memset(global, 0, sizeof(*global));
1637 global->codec = codecs;
1639 global->use_i420 = 1;
1641 for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step) {
1644 if (arg_match(&arg, &codecarg, argi)) {
1647 for (j = 0; j < sizeof(codecs) / sizeof(codecs[0]); j++)
1648 if (!strcmp(codecs[j].name, arg.val))
1652 global->codec = codecs + k;
1654 die("Error: Unrecognized argument (%s) to --codec\n",
1657 } else if (arg_match(&arg, &passes, argi)) {
1658 global->passes = arg_parse_uint(&arg);
1660 if (global->passes < 1 || global->passes > 2)
1661 die("Error: Invalid number of passes (%d)\n", global->passes);
1662 } else if (arg_match(&arg, &pass_arg, argi)) {
1663 global->pass = arg_parse_uint(&arg);
1665 if (global->pass < 1 || global->pass > 2)
1666 die("Error: Invalid pass selected (%d)\n",
1668 } else if (arg_match(&arg, &usage, argi))
1669 global->usage = arg_parse_uint(&arg);
1670 else if (arg_match(&arg, &deadline, argi))
1671 global->deadline = arg_parse_uint(&arg);
1672 else if (arg_match(&arg, &best_dl, argi))
1673 global->deadline = VPX_DL_BEST_QUALITY;
1674 else if (arg_match(&arg, &good_dl, argi))
1675 global->deadline = VPX_DL_GOOD_QUALITY;
1676 else if (arg_match(&arg, &rt_dl, argi))
1677 global->deadline = VPX_DL_REALTIME;
1678 else if (arg_match(&arg, &use_yv12, argi))
1679 global->use_i420 = 0;
1680 else if (arg_match(&arg, &use_i420, argi))
1681 global->use_i420 = 1;
1682 else if (arg_match(&arg, &quietarg, argi))
1684 else if (arg_match(&arg, &verbosearg, argi))
1685 global->verbose = 1;
1686 else if (arg_match(&arg, &limit, argi))
1687 global->limit = arg_parse_uint(&arg);
1688 else if (arg_match(&arg, &skip, argi))
1689 global->skip_frames = arg_parse_uint(&arg);
1690 else if (arg_match(&arg, &psnrarg, argi))
1691 global->show_psnr = 1;
1692 else if (arg_match(&arg, &recontest, argi))
1693 global->test_decode = 1;
1694 else if (arg_match(&arg, &framerate, argi)) {
1695 global->framerate = arg_parse_rational(&arg);
1696 validate_positive_rational(arg.name, &global->framerate);
1697 global->have_framerate = 1;
1698 } else if (arg_match(&arg, &out_part, argi))
1699 global->out_part = 1;
1700 else if (arg_match(&arg, &debugmode, argi))
1702 else if (arg_match(&arg, &q_hist_n, argi))
1703 global->show_q_hist_buckets = arg_parse_uint(&arg);
1704 else if (arg_match(&arg, &rate_hist_n, argi))
1705 global->show_rate_hist_buckets = arg_parse_uint(&arg);
1710 /* Validate global config */
1713 /* DWIM: Assume the user meant passes=2 if pass=2 is specified */
1714 if (global->pass > global->passes) {
1715 warn("Assuming --pass=%d implies --passes=%d\n",
1716 global->pass, global->pass);
1717 global->passes = global->pass;
1723 void open_input_file(struct input_state *input) {
1724 unsigned int fourcc;
1726 /* Parse certain options from the input file, if possible */
1727 input->file = strcmp(input->fn, "-") ? fopen(input->fn, "rb")
1728 : set_binary_mode(stdin);
1731 fatal("Failed to open input file");
1733 /* For RAW input sources, these bytes will applied on the first frame
1736 input->detect.buf_read = fread(input->detect.buf, 1, 4, input->file);
1737 input->detect.position = 0;
1739 if (input->detect.buf_read == 4
1740 && file_is_y4m(input->file, &input->y4m, input->detect.buf)) {
1741 if (y4m_input_open(&input->y4m, input->file, input->detect.buf, 4) >= 0) {
1742 input->file_type = FILE_TYPE_Y4M;
1743 input->w = input->y4m.pic_w;
1744 input->h = input->y4m.pic_h;
1745 input->framerate.num = input->y4m.fps_n;
1746 input->framerate.den = input->y4m.fps_d;
1747 input->use_i420 = 0;
1749 fatal("Unsupported Y4M stream.");
1750 } else if (input->detect.buf_read == 4 && file_is_ivf(input, &fourcc)) {
1751 input->file_type = FILE_TYPE_IVF;
1754 input->use_i420 = 0;
1757 input->use_i420 = 1;
1760 fatal("Unsupported fourcc (%08x) in IVF", fourcc);
1763 input->file_type = FILE_TYPE_RAW;
1768 static void close_input_file(struct input_state *input) {
1769 fclose(input->file);
1770 if (input->file_type == FILE_TYPE_Y4M)
1771 y4m_input_close(&input->y4m);
1774 static struct stream_state *new_stream(struct global_config *global,
1775 struct stream_state *prev) {
1776 struct stream_state *stream;
1778 stream = calloc(1, sizeof(*stream));
1780 fatal("Failed to allocate new stream.");
1782 memcpy(stream, prev, sizeof(*stream));
1784 prev->next = stream;
1786 vpx_codec_err_t res;
1788 /* Populate encoder configuration */
1789 res = vpx_codec_enc_config_default(global->codec->iface(),
1790 &stream->config.cfg,
1793 fatal("Failed to get config: %s\n", vpx_codec_err_to_string(res));
1795 /* Change the default timebase to a high enough value so that the
1796 * encoder will always create strictly increasing timestamps.
1798 stream->config.cfg.g_timebase.den = 1000;
1800 /* Never use the library's default resolution, require it be parsed
1801 * from the file or set on the command line.
1803 stream->config.cfg.g_w = 0;
1804 stream->config.cfg.g_h = 0;
1806 /* Initialize remaining stream parameters */
1807 stream->config.stereo_fmt = STEREO_FORMAT_MONO;
1808 stream->config.write_webm = 1;
1809 stream->ebml.last_pts_ms = -1;
1811 /* Allows removal of the application version from the EBML tags */
1812 stream->ebml.debug = global->debug;
1815 /* Output files must be specified for each stream */
1816 stream->config.out_fn = NULL;
1818 stream->next = NULL;
1823 static int parse_stream_params(struct global_config *global,
1824 struct stream_state *stream,
1826 char **argi, **argj;
1828 static const arg_def_t **ctrl_args = no_args;
1829 static const int *ctrl_args_map = NULL;
1830 struct stream_config *config = &stream->config;
1831 int eos_mark_found = 0;
1833 /* Handle codec specific options */
1835 #if CONFIG_VP8_ENCODER
1836 } else if (global->codec->iface == vpx_codec_vp8_cx) {
1837 ctrl_args = vp8_args;
1838 ctrl_args_map = vp8_arg_ctrl_map;
1840 #if CONFIG_VP9_ENCODER
1841 } else if (global->codec->iface == vpx_codec_vp9_cx) {
1842 ctrl_args = vp9_args;
1843 ctrl_args_map = vp9_arg_ctrl_map;
1847 for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step) {
1850 /* Once we've found an end-of-stream marker (--) we want to continue
1851 * shifting arguments but not consuming them.
1853 if (eos_mark_found) {
1856 } else if (!strcmp(*argj, "--")) {
1862 else if (arg_match(&arg, &outputfile, argi))
1863 config->out_fn = arg.val;
1864 else if (arg_match(&arg, &fpf_name, argi))
1865 config->stats_fn = arg.val;
1866 else if (arg_match(&arg, &use_ivf, argi))
1867 config->write_webm = 0;
1868 else if (arg_match(&arg, &threads, argi))
1869 config->cfg.g_threads = arg_parse_uint(&arg);
1870 else if (arg_match(&arg, &profile, argi))
1871 config->cfg.g_profile = arg_parse_uint(&arg);
1872 else if (arg_match(&arg, &width, argi))
1873 config->cfg.g_w = arg_parse_uint(&arg);
1874 else if (arg_match(&arg, &height, argi))
1875 config->cfg.g_h = arg_parse_uint(&arg);
1876 else if (arg_match(&arg, &stereo_mode, argi))
1877 config->stereo_fmt = arg_parse_enum_or_int(&arg);
1878 else if (arg_match(&arg, &timebase, argi)) {
1879 config->cfg.g_timebase = arg_parse_rational(&arg);
1880 validate_positive_rational(arg.name, &config->cfg.g_timebase);
1881 } else if (arg_match(&arg, &error_resilient, argi))
1882 config->cfg.g_error_resilient = arg_parse_uint(&arg);
1883 else if (arg_match(&arg, &lag_in_frames, argi))
1884 config->cfg.g_lag_in_frames = arg_parse_uint(&arg);
1885 else if (arg_match(&arg, &dropframe_thresh, argi))
1886 config->cfg.rc_dropframe_thresh = arg_parse_uint(&arg);
1887 else if (arg_match(&arg, &resize_allowed, argi))
1888 config->cfg.rc_resize_allowed = arg_parse_uint(&arg);
1889 else if (arg_match(&arg, &resize_up_thresh, argi))
1890 config->cfg.rc_resize_up_thresh = arg_parse_uint(&arg);
1891 else if (arg_match(&arg, &resize_down_thresh, argi))
1892 config->cfg.rc_resize_down_thresh = arg_parse_uint(&arg);
1893 else if (arg_match(&arg, &end_usage, argi))
1894 config->cfg.rc_end_usage = arg_parse_enum_or_int(&arg);
1895 else if (arg_match(&arg, &target_bitrate, argi))
1896 config->cfg.rc_target_bitrate = arg_parse_uint(&arg);
1897 else if (arg_match(&arg, &min_quantizer, argi))
1898 config->cfg.rc_min_quantizer = arg_parse_uint(&arg);
1899 else if (arg_match(&arg, &max_quantizer, argi))
1900 config->cfg.rc_max_quantizer = arg_parse_uint(&arg);
1901 else if (arg_match(&arg, &undershoot_pct, argi))
1902 config->cfg.rc_undershoot_pct = arg_parse_uint(&arg);
1903 else if (arg_match(&arg, &overshoot_pct, argi))
1904 config->cfg.rc_overshoot_pct = arg_parse_uint(&arg);
1905 else if (arg_match(&arg, &buf_sz, argi))
1906 config->cfg.rc_buf_sz = arg_parse_uint(&arg);
1907 else if (arg_match(&arg, &buf_initial_sz, argi))
1908 config->cfg.rc_buf_initial_sz = arg_parse_uint(&arg);
1909 else if (arg_match(&arg, &buf_optimal_sz, argi))
1910 config->cfg.rc_buf_optimal_sz = arg_parse_uint(&arg);
1911 else if (arg_match(&arg, &bias_pct, argi)) {
1912 config->cfg.rc_2pass_vbr_bias_pct = arg_parse_uint(&arg);
1914 if (global->passes < 2)
1915 warn("option %s ignored in one-pass mode.\n", arg.name);
1916 } else if (arg_match(&arg, &minsection_pct, argi)) {
1917 config->cfg.rc_2pass_vbr_minsection_pct = arg_parse_uint(&arg);
1919 if (global->passes < 2)
1920 warn("option %s ignored in one-pass mode.\n", arg.name);
1921 } else if (arg_match(&arg, &maxsection_pct, argi)) {
1922 config->cfg.rc_2pass_vbr_maxsection_pct = arg_parse_uint(&arg);
1924 if (global->passes < 2)
1925 warn("option %s ignored in one-pass mode.\n", arg.name);
1926 } else if (arg_match(&arg, &kf_min_dist, argi))
1927 config->cfg.kf_min_dist = arg_parse_uint(&arg);
1928 else if (arg_match(&arg, &kf_max_dist, argi)) {
1929 config->cfg.kf_max_dist = arg_parse_uint(&arg);
1930 config->have_kf_max_dist = 1;
1931 } else if (arg_match(&arg, &kf_disabled, argi))
1932 config->cfg.kf_mode = VPX_KF_DISABLED;
1936 for (i = 0; ctrl_args[i]; i++) {
1937 if (arg_match(&arg, ctrl_args[i], argi)) {
1941 /* Point either to the next free element or the first
1942 * instance of this control.
1944 for (j = 0; j < config->arg_ctrl_cnt; j++)
1945 if (config->arg_ctrls[j][0] == ctrl_args_map[i])
1949 assert(j < ARG_CTRL_CNT_MAX);
1950 if (j < ARG_CTRL_CNT_MAX) {
1951 config->arg_ctrls[j][0] = ctrl_args_map[i];
1952 config->arg_ctrls[j][1] = arg_parse_enum_or_int(&arg);
1953 if (j == config->arg_ctrl_cnt)
1954 config->arg_ctrl_cnt++;
1965 return eos_mark_found;
1969 #define FOREACH_STREAM(func)\
1972 struct stream_state *stream;\
1974 for(stream = streams; stream; stream = stream->next)\
1979 static void validate_stream_config(struct stream_state *stream) {
1980 struct stream_state *streami;
1982 if (!stream->config.cfg.g_w || !stream->config.cfg.g_h)
1983 fatal("Stream %d: Specify stream dimensions with --width (-w) "
1984 " and --height (-h)", stream->index);
1986 for (streami = stream; streami; streami = streami->next) {
1987 /* All streams require output files */
1988 if (!streami->config.out_fn)
1989 fatal("Stream %d: Output file is required (specify with -o)",
1992 /* Check for two streams outputting to the same file */
1993 if (streami != stream) {
1994 const char *a = stream->config.out_fn;
1995 const char *b = streami->config.out_fn;
1996 if (!strcmp(a, b) && strcmp(a, "/dev/null") && strcmp(a, ":nul"))
1997 fatal("Stream %d: duplicate output file (from stream %d)",
1998 streami->index, stream->index);
2001 /* Check for two streams sharing a stats file. */
2002 if (streami != stream) {
2003 const char *a = stream->config.stats_fn;
2004 const char *b = streami->config.stats_fn;
2005 if (a && b && !strcmp(a, b))
2006 fatal("Stream %d: duplicate stats file (from stream %d)",
2007 streami->index, stream->index);
2013 static void set_stream_dimensions(struct stream_state *stream,
2016 if ((stream->config.cfg.g_w && stream->config.cfg.g_w != w)
2017 || (stream->config.cfg.g_h && stream->config.cfg.g_h != h))
2018 fatal("Stream %d: Resizing not yet supported", stream->index);
2019 stream->config.cfg.g_w = w;
2020 stream->config.cfg.g_h = h;
2024 static void set_default_kf_interval(struct stream_state *stream,
2025 struct global_config *global) {
2026 /* Use a max keyframe interval of 5 seconds, if none was
2027 * specified on the command line.
2029 if (!stream->config.have_kf_max_dist) {
2030 double framerate = (double)global->framerate.num / global->framerate.den;
2031 if (framerate > 0.0)
2032 stream->config.cfg.kf_max_dist = (unsigned int)(5.0 * framerate);
2037 static void show_stream_config(struct stream_state *stream,
2038 struct global_config *global,
2039 struct input_state *input) {
2041 #define SHOW(field) \
2042 fprintf(stderr, " %-28s = %d\n", #field, stream->config.cfg.field)
2044 if (stream->index == 0) {
2045 fprintf(stderr, "Codec: %s\n",
2046 vpx_codec_iface_name(global->codec->iface()));
2047 fprintf(stderr, "Source file: %s Format: %s\n", input->fn,
2048 input->use_i420 ? "I420" : "YV12");
2050 if (stream->next || stream->index)
2051 fprintf(stderr, "\nStream Index: %d\n", stream->index);
2052 fprintf(stderr, "Destination file: %s\n", stream->config.out_fn);
2053 fprintf(stderr, "Encoder parameters:\n");
2060 SHOW(g_timebase.num);
2061 SHOW(g_timebase.den);
2062 SHOW(g_error_resilient);
2064 SHOW(g_lag_in_frames);
2065 SHOW(rc_dropframe_thresh);
2066 SHOW(rc_resize_allowed);
2067 SHOW(rc_resize_up_thresh);
2068 SHOW(rc_resize_down_thresh);
2070 SHOW(rc_target_bitrate);
2071 SHOW(rc_min_quantizer);
2072 SHOW(rc_max_quantizer);
2073 SHOW(rc_undershoot_pct);
2074 SHOW(rc_overshoot_pct);
2076 SHOW(rc_buf_initial_sz);
2077 SHOW(rc_buf_optimal_sz);
2078 SHOW(rc_2pass_vbr_bias_pct);
2079 SHOW(rc_2pass_vbr_minsection_pct);
2080 SHOW(rc_2pass_vbr_maxsection_pct);
2087 static void open_output_file(struct stream_state *stream,
2088 struct global_config *global) {
2089 const char *fn = stream->config.out_fn;
2091 stream->file = strcmp(fn, "-") ? fopen(fn, "wb") : set_binary_mode(stdout);
2094 fatal("Failed to open output file");
2096 if (stream->config.write_webm && fseek(stream->file, 0, SEEK_CUR))
2097 fatal("WebM output to pipes not supported.");
2099 if (stream->config.write_webm) {
2100 stream->ebml.stream = stream->file;
2101 write_webm_file_header(&stream->ebml, &stream->config.cfg,
2103 stream->config.stereo_fmt,
2104 global->codec->fourcc);
2106 write_ivf_file_header(stream->file, &stream->config.cfg,
2107 global->codec->fourcc, 0);
2111 static void close_output_file(struct stream_state *stream,
2112 unsigned int fourcc) {
2113 if (stream->config.write_webm) {
2114 write_webm_file_footer(&stream->ebml, stream->hash);
2115 free(stream->ebml.cue_list);
2116 stream->ebml.cue_list = NULL;
2118 if (!fseek(stream->file, 0, SEEK_SET))
2119 write_ivf_file_header(stream->file, &stream->config.cfg,
2121 stream->frames_out);
2124 fclose(stream->file);
2128 static void setup_pass(struct stream_state *stream,
2129 struct global_config *global,
2131 if (stream->config.stats_fn) {
2132 if (!stats_open_file(&stream->stats, stream->config.stats_fn,
2134 fatal("Failed to open statistics store");
2136 if (!stats_open_mem(&stream->stats, pass))
2137 fatal("Failed to open statistics store");
2140 stream->config.cfg.g_pass = global->passes == 2
2141 ? pass ? VPX_RC_LAST_PASS : VPX_RC_FIRST_PASS
2144 stream->config.cfg.rc_twopass_stats_in = stats_get(&stream->stats);
2146 stream->cx_time = 0;
2148 stream->frames_out = 0;
2152 static void initialize_encoder(struct stream_state *stream,
2153 struct global_config *global) {
2157 flags |= global->show_psnr ? VPX_CODEC_USE_PSNR : 0;
2158 flags |= global->out_part ? VPX_CODEC_USE_OUTPUT_PARTITION : 0;
2160 /* Construct Encoder Context */
2161 vpx_codec_enc_init(&stream->encoder, global->codec->iface(),
2162 &stream->config.cfg, flags);
2163 ctx_exit_on_error(&stream->encoder, "Failed to initialize encoder");
2165 /* Note that we bypass the vpx_codec_control wrapper macro because
2166 * we're being clever to store the control IDs in an array. Real
2167 * applications will want to make use of the enumerations directly
2169 for (i = 0; i < stream->config.arg_ctrl_cnt; i++) {
2170 int ctrl = stream->config.arg_ctrls[i][0];
2171 int value = stream->config.arg_ctrls[i][1];
2172 if (vpx_codec_control_(&stream->encoder, ctrl, value))
2173 fprintf(stderr, "Error: Tried to set control %d = %d\n",
2176 ctx_exit_on_error(&stream->encoder, "Failed to control codec");
2180 if (global->test_decode) {
2183 vpx_codec_dec_init(&stream->decoder, global->codec->dx_iface(), NULL, 0);
2185 width = (stream->config.cfg.g_w + 15) & ~15;
2186 height = (stream->config.cfg.g_h + 15) & ~15;
2187 vpx_img_alloc(&stream->ref_enc.img, VPX_IMG_FMT_I420, width, height, 1);
2188 vpx_img_alloc(&stream->ref_dec.img, VPX_IMG_FMT_I420, width, height, 1);
2189 stream->ref_enc.frame_type = VP8_LAST_FRAME;
2190 stream->ref_dec.frame_type = VP8_LAST_FRAME;
2196 static void encode_frame(struct stream_state *stream,
2197 struct global_config *global,
2198 struct vpx_image *img,
2199 unsigned int frames_in) {
2200 vpx_codec_pts_t frame_start, next_frame_start;
2201 struct vpx_codec_enc_cfg *cfg = &stream->config.cfg;
2202 struct vpx_usec_timer timer;
2204 frame_start = (cfg->g_timebase.den * (int64_t)(frames_in - 1)
2205 * global->framerate.den)
2206 / cfg->g_timebase.num / global->framerate.num;
2207 next_frame_start = (cfg->g_timebase.den * (int64_t)(frames_in)
2208 * global->framerate.den)
2209 / cfg->g_timebase.num / global->framerate.num;
2210 vpx_usec_timer_start(&timer);
2211 vpx_codec_encode(&stream->encoder, img, frame_start,
2212 (unsigned long)(next_frame_start - frame_start),
2213 0, global->deadline);
2214 vpx_usec_timer_mark(&timer);
2215 stream->cx_time += vpx_usec_timer_elapsed(&timer);
2216 ctx_exit_on_error(&stream->encoder, "Stream %d: Failed to encode frame",
2221 static void update_quantizer_histogram(struct stream_state *stream) {
2222 if (stream->config.cfg.g_pass != VPX_RC_FIRST_PASS) {
2225 vpx_codec_control(&stream->encoder, VP8E_GET_LAST_QUANTIZER_64, &q);
2226 ctx_exit_on_error(&stream->encoder, "Failed to read quantizer");
2227 stream->counts[q]++;
2232 static void get_cx_data(struct stream_state *stream,
2233 struct global_config *global,
2235 const vpx_codec_cx_pkt_t *pkt;
2236 const struct vpx_codec_enc_cfg *cfg = &stream->config.cfg;
2237 vpx_codec_iter_t iter = NULL;
2240 while ((pkt = vpx_codec_get_cx_data(&stream->encoder, &iter))) {
2241 static size_t fsize = 0;
2242 static off_t ivf_header_pos = 0;
2244 switch (pkt->kind) {
2245 case VPX_CODEC_CX_FRAME_PKT:
2246 if (!(pkt->data.frame.flags & VPX_FRAME_IS_FRAGMENT)) {
2247 stream->frames_out++;
2250 fprintf(stderr, " %6luF",
2251 (unsigned long)pkt->data.frame.sz);
2253 update_rate_histogram(&stream->rate_hist, cfg, pkt);
2254 if (stream->config.write_webm) {
2255 /* Update the hash */
2256 if (!stream->ebml.debug)
2257 stream->hash = murmur(pkt->data.frame.buf,
2258 (int)pkt->data.frame.sz,
2261 write_webm_block(&stream->ebml, cfg, pkt);
2263 if (pkt->data.frame.partition_id <= 0) {
2264 ivf_header_pos = ftello(stream->file);
2265 fsize = pkt->data.frame.sz;
2267 write_ivf_frame_header(stream->file, pkt);
2269 fsize += pkt->data.frame.sz;
2271 if (!(pkt->data.frame.flags & VPX_FRAME_IS_FRAGMENT)) {
2272 off_t currpos = ftello(stream->file);
2273 fseeko(stream->file, ivf_header_pos, SEEK_SET);
2274 write_ivf_frame_size(stream->file, fsize);
2275 fseeko(stream->file, currpos, SEEK_SET);
2279 (void) fwrite(pkt->data.frame.buf, 1, pkt->data.frame.sz,
2282 stream->nbytes += pkt->data.raw.sz;
2286 if (global->test_decode) {
2287 vpx_codec_decode(&stream->decoder, pkt->data.frame.buf,
2288 pkt->data.frame.sz, NULL, 0);
2289 ctx_exit_on_error(&stream->decoder, "Failed to decode frame");
2293 case VPX_CODEC_STATS_PKT:
2294 stream->frames_out++;
2296 fprintf(stderr, " %6luS",
2297 (unsigned long)pkt->data.twopass_stats.sz);
2298 stats_write(&stream->stats,
2299 pkt->data.twopass_stats.buf,
2300 pkt->data.twopass_stats.sz);
2301 stream->nbytes += pkt->data.raw.sz;
2303 case VPX_CODEC_PSNR_PKT:
2305 if (global->show_psnr) {
2308 stream->psnr_sse_total += pkt->data.psnr.sse[0];
2309 stream->psnr_samples_total += pkt->data.psnr.samples[0];
2310 for (i = 0; i < 4; i++) {
2312 fprintf(stderr, "%.3f ", pkt->data.psnr.psnr[i]);
2313 stream->psnr_totals[i] += pkt->data.psnr.psnr[i];
2315 stream->psnr_count++;
2326 static void show_psnr(struct stream_state *stream) {
2330 if (!stream->psnr_count)
2333 fprintf(stderr, "Stream %d PSNR (Overall/Avg/Y/U/V)", stream->index);
2334 ovpsnr = vp8_mse2psnr((double)stream->psnr_samples_total, 255.0,
2335 (double)stream->psnr_sse_total);
2336 fprintf(stderr, " %.3f", ovpsnr);
2338 for (i = 0; i < 4; i++) {
2339 fprintf(stderr, " %.3f", stream->psnr_totals[i] / stream->psnr_count);
2341 fprintf(stderr, "\n");
2345 float usec_to_fps(uint64_t usec, unsigned int frames) {
2346 return (float)(usec > 0 ? frames * 1000000.0 / (float)usec : 0);
2350 static void test_decode(struct stream_state *stream) {
2351 vpx_codec_control(&stream->encoder, VP8_COPY_REFERENCE, &stream->ref_enc);
2352 ctx_exit_on_error(&stream->encoder, "Failed to get encoder reference frame");
2353 vpx_codec_control(&stream->decoder, VP8_COPY_REFERENCE, &stream->ref_dec);
2354 ctx_exit_on_error(&stream->decoder, "Failed to get decoder reference frame");
2356 if (!stream->mismatch_seen
2357 && !compare_img(&stream->ref_enc.img, &stream->ref_dec.img)) {
2358 /* TODO(jkoleszar): make fatal. */
2359 int y[2], u[2], v[2];
2360 find_mismatch(&stream->ref_enc.img, &stream->ref_dec.img,
2362 warn("Stream %d: Encode/decode mismatch on frame %d"
2363 " at Y[%d, %d], U[%d, %d], V[%d, %d]",
2364 stream->index, stream->frames_out,
2365 y[0], y[1], u[0], u[1], v[0], v[1]);
2366 stream->mismatch_seen = stream->frames_out;
2370 int main(int argc, const char **argv_) {
2373 int frame_avail, got_data;
2375 struct input_state input = {0};
2376 struct global_config global;
2377 struct stream_state *streams = NULL;
2378 char **argv, **argi;
2379 unsigned long cx_time = 0;
2382 exec_name = argv_[0];
2387 /* Setup default input stream settings */
2388 input.framerate.num = 30;
2389 input.framerate.den = 1;
2392 /* First parse the global configuration values, because we want to apply
2393 * other parameters on top of the default configuration provided by the
2396 argv = argv_dup(argc - 1, argv_ + 1);
2397 parse_global_config(&global, argv);
2400 /* Now parse each stream's parameters. Using a local scope here
2401 * due to the use of 'stream' as loop variable in FOREACH_STREAM
2404 struct stream_state *stream = NULL;
2407 stream = new_stream(&global, stream);
2411 } while (parse_stream_params(&global, stream, argv));
2414 /* Check for unrecognized options */
2415 for (argi = argv; *argi; argi++)
2416 if (argi[0][0] == '-' && argi[0][1])
2417 die("Error: Unrecognized option %s\n", *argi);
2419 /* Handle non-option arguments */
2425 for (pass = global.pass ? global.pass - 1 : 0; pass < global.passes; pass++) {
2428 open_input_file(&input);
2430 /* If the input file doesn't specify its w/h (raw files), try to get
2431 * the data from the first stream's configuration.
2433 if (!input.w || !input.h)
2435 if (stream->config.cfg.g_w && stream->config.cfg.g_h) {
2436 input.w = stream->config.cfg.g_w;
2437 input.h = stream->config.cfg.g_h;
2442 /* Update stream configurations from the input file's parameters */
2443 FOREACH_STREAM(set_stream_dimensions(stream, input.w, input.h));
2444 FOREACH_STREAM(validate_stream_config(stream));
2446 /* Ensure that --passes and --pass are consistent. If --pass is set and
2447 * --passes=2, ensure --fpf was set.
2449 if (global.pass && global.passes == 2)
2451 if (!stream->config.stats_fn)
2452 die("Stream %d: Must specify --fpf when --pass=%d"
2453 " and --passes=2\n", stream->index, global.pass);
2457 /* Use the frame rate from the file only if none was specified
2458 * on the command-line.
2460 if (!global.have_framerate)
2461 global.framerate = input.framerate;
2463 FOREACH_STREAM(set_default_kf_interval(stream, &global));
2465 /* Show configuration */
2466 if (global.verbose && pass == 0)
2467 FOREACH_STREAM(show_stream_config(stream, &global, &input));
2469 if (pass == (global.pass ? global.pass - 1 : 0)) {
2470 if (input.file_type == FILE_TYPE_Y4M)
2471 /*The Y4M reader does its own allocation.
2472 Just initialize this here to avoid problems if we never read any
2474 memset(&raw, 0, sizeof(raw));
2477 input.use_i420 ? VPX_IMG_FMT_I420
2479 input.w, input.h, 32);
2481 FOREACH_STREAM(init_rate_histogram(&stream->rate_hist,
2482 &stream->config.cfg,
2483 &global.framerate));
2486 FOREACH_STREAM(open_output_file(stream, &global));
2487 FOREACH_STREAM(setup_pass(stream, &global, pass));
2488 FOREACH_STREAM(initialize_encoder(stream, &global));
2493 while (frame_avail || got_data) {
2494 struct vpx_usec_timer timer;
2496 if (!global.limit || frames_in < global.limit) {
2497 frame_avail = read_frame(&input, &raw);
2502 if (!global.quiet) {
2503 if (stream_cnt == 1)
2505 "\rPass %d/%d frame %4d/%-4d %7"PRId64"B \033[K",
2506 pass + 1, global.passes, frames_in,
2507 streams->frames_out, (int64_t)streams->nbytes);
2510 "\rPass %d/%d frame %4d %7lu %s (%.2f fps)\033[K",
2511 pass + 1, global.passes, frames_in,
2512 cx_time > 9999999 ? cx_time / 1000 : cx_time,
2513 cx_time > 9999999 ? "ms" : "us",
2514 usec_to_fps(cx_time, frames_in));
2520 if (frames_in > global.skip_frames) {
2521 vpx_usec_timer_start(&timer);
2522 FOREACH_STREAM(encode_frame(stream, &global,
2523 frame_avail ? &raw : NULL,
2525 vpx_usec_timer_mark(&timer);
2526 cx_time += (unsigned long)vpx_usec_timer_elapsed(&timer);
2528 FOREACH_STREAM(update_quantizer_histogram(stream));
2531 FOREACH_STREAM(get_cx_data(stream, &global, &got_data));
2533 if (got_data && global.test_decode)
2534 FOREACH_STREAM(test_decode(stream));
2541 fprintf(stderr, "\n");
2544 FOREACH_STREAM(fprintf(
2546 "\rPass %d/%d frame %4d/%-4d %7"PRId64"B %7lub/f %7"PRId64"b/s"
2547 " %7"PRId64" %s (%.2f fps)\033[K\n", pass + 1,
2548 global.passes, frames_in, stream->frames_out, (int64_t)stream->nbytes,
2549 frames_in ? (unsigned long)(stream->nbytes * 8 / frames_in) : 0,
2550 frames_in ? (int64_t)stream->nbytes * 8
2551 * (int64_t)global.framerate.num / global.framerate.den
2554 stream->cx_time > 9999999 ? stream->cx_time / 1000 : stream->cx_time,
2555 stream->cx_time > 9999999 ? "ms" : "us",
2556 usec_to_fps(stream->cx_time, frames_in));
2559 if (global.show_psnr)
2560 FOREACH_STREAM(show_psnr(stream));
2562 FOREACH_STREAM(vpx_codec_destroy(&stream->encoder));
2564 if (global.test_decode) {
2565 FOREACH_STREAM(vpx_codec_destroy(&stream->decoder));
2566 FOREACH_STREAM(vpx_img_free(&stream->ref_enc.img));
2567 FOREACH_STREAM(vpx_img_free(&stream->ref_dec.img));
2570 close_input_file(&input);
2572 FOREACH_STREAM(close_output_file(stream, global.codec->fourcc));
2574 FOREACH_STREAM(stats_close(&stream->stats, global.passes - 1));
2580 if (global.show_q_hist_buckets)
2581 FOREACH_STREAM(show_q_histogram(stream->counts,
2582 global.show_q_hist_buckets));
2584 if (global.show_rate_hist_buckets)
2585 FOREACH_STREAM(show_rate_histogram(&stream->rate_hist,
2586 &stream->config.cfg,
2587 global.show_rate_hist_buckets));
2588 FOREACH_STREAM(destroy_rate_histogram(&stream->rate_hist));
2590 #if CONFIG_INTERNAL_STATS
2591 /* TODO(jkoleszar): This doesn't belong in this executable. Do it for now,
2592 * to match some existing utilities.
2595 FILE *f = fopen("opsnr.stt", "a");
2596 if (stream->mismatch_seen) {
2597 fprintf(f, "First mismatch occurred in frame %d\n",
2598 stream->mismatch_seen);
2600 fprintf(f, "No mismatch detected in recon buffers\n");
2609 return EXIT_SUCCESS;