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 /* This is a simple program that encodes YV12 files and generates ivf
14 * files using the new interface.
16 #if defined(_WIN32) || !CONFIG_OS_SUPPORT
17 #define USE_POSIX_MMAP 0
19 #define USE_POSIX_MMAP 1
28 #include "vpx/vpx_encoder.h"
30 #include <sys/types.h>
36 #include "vpx_config.h"
37 #include "vpx_version.h"
38 #include "vpx/vp8cx.h"
39 #include "vpx/vp8dx.h"
40 #include "vpx/vpx_decoder.h"
41 #include "vpx_ports/mem_ops.h"
42 #include "vpx_ports/vpx_timer.h"
43 #include "tools_common.h"
45 #include "libmkv/EbmlWriter.h"
46 #include "libmkv/EbmlIDs.h"
48 /* Need special handling of these functions on Windows */
50 /* MSVS doesn't define off_t, and uses _f{seek,tell}i64 */
51 typedef __int64 off_t;
52 #define fseeko _fseeki64
53 #define ftello _ftelli64
55 /* MinGW defines off_t, and uses f{seek,tell}o64 */
56 #define fseeko fseeko64
57 #define ftello ftello64
61 #define LITERALU64(n) n
63 #define LITERALU64(n) n##LLU
66 /* We should use 32-bit file operations in WebM file format
67 * when building ARM executable file (.axf) with RVCT */
68 #if !CONFIG_OS_SUPPORT
74 static const char *exec_name;
78 #define VP8_FOURCC (0x78385056)
81 const vpx_codec_iface_t *(*iface)(void);
83 unsigned int fourcc_mask;
85 #if CONFIG_VP8_DECODER
86 {"vp8", &vpx_codec_vp8_dx, VP8_FOURCC, 0x00FFFFFF},
90 static const struct codec_item {
92 const vpx_codec_iface_t *(*iface)(void);
94 unsigned int fourcc_mask;
96 #if CONFIG_VP8_ENCODER
97 {"vp8", vpx_codec_vp8x_cx, VP8_FOURCC, 0x00FFFFFF},
102 static void usage_exit();
104 void die(const char *fmt, ...) {
107 vfprintf(stderr, fmt, ap);
108 fprintf(stderr, "\n");
112 static void ctx_exit_on_error(vpx_codec_ctx_t *ctx, const char *s) {
114 const char *detail = vpx_codec_error_detail(ctx);
116 fprintf(stderr, "%s: %s\n", s, vpx_codec_error(ctx));
119 fprintf(stderr, " %s\n", detail);
125 /* This structure is used to abstract the different ways of handling
126 * first pass statistics.
136 int stats_open_file(stats_io_t *stats, const char *fpf, int pass) {
142 stats->file = fopen(fpf, "wb");
144 stats->buf.buf = NULL,
145 res = (stats->file != NULL);
149 struct stat stat_buf;
152 fd = open(fpf, O_RDONLY);
153 stats->file = fdopen(fd, "rb");
154 fstat(fd, &stat_buf);
155 stats->buf.sz = stat_buf.st_size;
156 stats->buf.buf = mmap(NULL, stats->buf.sz, PROT_READ, MAP_PRIVATE,
158 res = (stats->buf.buf != NULL);
162 stats->file = fopen(fpf, "rb");
164 if (fseek(stats->file, 0, SEEK_END)) {
165 fprintf(stderr, "First-pass stats file must be seekable!\n");
169 stats->buf.sz = stats->buf_alloc_sz = ftell(stats->file);
172 stats->buf.buf = malloc(stats->buf_alloc_sz);
174 if (!stats->buf.buf) {
175 fprintf(stderr, "Failed to allocate first-pass stats buffer (%lu bytes)\n",
176 (unsigned long)stats->buf_alloc_sz);
180 nbytes = fread(stats->buf.buf, 1, stats->buf.sz, stats->file);
181 res = (nbytes == stats->buf.sz);
188 int stats_open_mem(stats_io_t *stats, int pass) {
194 stats->buf_alloc_sz = 64 * 1024;
195 stats->buf.buf = malloc(stats->buf_alloc_sz);
198 stats->buf_ptr = stats->buf.buf;
199 res = (stats->buf.buf != NULL);
204 void stats_close(stats_io_t *stats, int last_pass) {
206 if (stats->pass == last_pass) {
209 munmap(stats->buf.buf, stats->buf.sz);
211 free(stats->buf.buf);
218 if (stats->pass == last_pass)
219 free(stats->buf.buf);
223 void stats_write(stats_io_t *stats, const void *pkt, size_t len) {
225 if (fwrite(pkt, 1, len, stats->file));
227 if (stats->buf.sz + len > stats->buf_alloc_sz) {
228 size_t new_sz = stats->buf_alloc_sz + 64 * 1024;
229 char *new_ptr = realloc(stats->buf.buf, new_sz);
232 stats->buf_ptr = new_ptr + (stats->buf_ptr - (char *)stats->buf.buf);
233 stats->buf.buf = new_ptr;
234 stats->buf_alloc_sz = new_sz;
237 "\nFailed to realloc firstpass stats buffer.\n");
242 memcpy(stats->buf_ptr, pkt, len);
243 stats->buf.sz += len;
244 stats->buf_ptr += len;
248 vpx_fixed_buf_t stats_get(stats_io_t *stats) {
252 /* Stereo 3D packed frame format */
253 typedef enum stereo_format {
254 STEREO_FORMAT_MONO = 0,
255 STEREO_FORMAT_LEFT_RIGHT = 1,
256 STEREO_FORMAT_BOTTOM_TOP = 2,
257 STEREO_FORMAT_TOP_BOTTOM = 3,
258 STEREO_FORMAT_RIGHT_LEFT = 11
261 enum video_file_type {
267 struct detect_buffer {
274 #define IVF_FRAME_HDR_SZ (4+8) /* 4 byte size + 8 byte timestamp */
275 static int read_frame(FILE *f, vpx_image_t *img, unsigned int file_type,
276 y4m_input *y4m, struct detect_buffer *detect) {
280 if (file_type == FILE_TYPE_Y4M) {
281 if (y4m_input_fetch_frame(y4m, f, img) < 1)
284 if (file_type == FILE_TYPE_IVF) {
285 char junk[IVF_FRAME_HDR_SZ];
287 /* Skip the frame header. We know how big the frame should be. See
288 * write_ivf_frame_header() for documentation on the frame header
291 if (fread(junk, 1, IVF_FRAME_HDR_SZ, f));
294 for (plane = 0; plane < 3; plane++) {
296 int w = (plane ? (1 + img->d_w) / 2 : img->d_w);
297 int h = (plane ? (1 + img->d_h) / 2 : img->d_h);
300 /* Determine the correct plane based on the image format. The for-loop
301 * always counts in Y,U,V order, but this may not match the order of
306 ptr = img->planes[img->fmt == VPX_IMG_FMT_YV12 ? VPX_PLANE_V : VPX_PLANE_U];
309 ptr = img->planes[img->fmt == VPX_IMG_FMT_YV12 ? VPX_PLANE_U : VPX_PLANE_V];
312 ptr = img->planes[plane];
315 for (r = 0; r < h; r++) {
317 size_t buf_position = 0;
318 const size_t left = detect->buf_read - detect->position;
320 const size_t more = (left < needed) ? left : needed;
321 memcpy(ptr, detect->buf + detect->position, more);
324 detect->position += more;
327 shortread |= (fread(ptr + buf_position, 1, needed, f) < needed);
330 ptr += img->stride[plane];
339 unsigned int file_is_y4m(FILE *infile,
342 if (memcmp(detect, "YUV4", 4) == 0) {
348 #define IVF_FILE_HDR_SZ (32)
349 unsigned int file_is_ivf(FILE *infile,
350 unsigned int *fourcc,
352 unsigned int *height,
353 struct detect_buffer *detect) {
354 char raw_hdr[IVF_FILE_HDR_SZ];
357 if (memcmp(detect->buf, "DKIF", 4) != 0)
360 /* See write_ivf_file_header() for more documentation on the file header
363 if (fread(raw_hdr + 4, 1, IVF_FILE_HDR_SZ - 4, infile)
364 == IVF_FILE_HDR_SZ - 4) {
368 if (mem_get_le16(raw_hdr + 4) != 0)
369 fprintf(stderr, "Error: Unrecognized IVF version! This file may not"
370 " decode properly.");
372 *fourcc = mem_get_le32(raw_hdr + 8);
377 *width = mem_get_le16(raw_hdr + 12);
378 *height = mem_get_le16(raw_hdr + 14);
379 detect->position = 4;
386 static void write_ivf_file_header(FILE *outfile,
387 const vpx_codec_enc_cfg_t *cfg,
392 if (cfg->g_pass != VPX_RC_ONE_PASS && cfg->g_pass != VPX_RC_LAST_PASS)
399 mem_put_le16(header + 4, 0); /* version */
400 mem_put_le16(header + 6, 32); /* headersize */
401 mem_put_le32(header + 8, fourcc); /* headersize */
402 mem_put_le16(header + 12, cfg->g_w); /* width */
403 mem_put_le16(header + 14, cfg->g_h); /* height */
404 mem_put_le32(header + 16, cfg->g_timebase.den); /* rate */
405 mem_put_le32(header + 20, cfg->g_timebase.num); /* scale */
406 mem_put_le32(header + 24, frame_cnt); /* length */
407 mem_put_le32(header + 28, 0); /* unused */
409 if (fwrite(header, 1, 32, outfile));
413 static void write_ivf_frame_header(FILE *outfile,
414 const vpx_codec_cx_pkt_t *pkt) {
418 if (pkt->kind != VPX_CODEC_CX_FRAME_PKT)
421 pts = pkt->data.frame.pts;
422 mem_put_le32(header, pkt->data.frame.sz);
423 mem_put_le32(header + 4, pts & 0xFFFFFFFF);
424 mem_put_le32(header + 8, pts >> 32);
426 if (fwrite(header, 1, 12, outfile));
430 typedef off_t EbmlLoc;
444 vpx_rational_t framerate;
446 /* These pointers are to the start of an element */
447 off_t position_reference;
449 off_t segment_info_pos;
454 /* This pointer is to a specific element to be serialized */
457 /* These pointers are to the size field of the element */
458 EbmlLoc startSegment;
459 EbmlLoc startCluster;
461 uint32_t cluster_timecode;
464 struct cue_entry *cue_list;
470 void Ebml_Write(EbmlGlobal *glob, const void *buffer_in, unsigned long len) {
471 if (fwrite(buffer_in, 1, len, glob->stream));
474 #define WRITE_BUFFER(s) \
475 for(i = len-1; i>=0; i--)\
477 x = *(const s *)buffer_in >> (i * CHAR_BIT); \
478 Ebml_Write(glob, &x, 1); \
480 void Ebml_Serialize(EbmlGlobal *glob, const void *buffer_in, int buffer_size, unsigned long len) {
490 switch (buffer_size) {
495 WRITE_BUFFER(int16_t)
498 WRITE_BUFFER(int32_t)
501 WRITE_BUFFER(int64_t)
509 /* Need a fixed size serializer for the track ID. libmkv provides a 64 bit
510 * one, but not a 32 bit one.
512 static void Ebml_SerializeUnsigned32(EbmlGlobal *glob, unsigned long class_id, uint64_t ui) {
513 unsigned char sizeSerialized = 4 | 0x80;
514 Ebml_WriteID(glob, class_id);
515 Ebml_Serialize(glob, &sizeSerialized, sizeof(sizeSerialized), 1);
516 Ebml_Serialize(glob, &ui, sizeof(ui), 4);
521 Ebml_StartSubElement(EbmlGlobal *glob, EbmlLoc *ebmlLoc,
522 unsigned long class_id) {
523 // todo this is always taking 8 bytes, this may need later optimization
524 // this is a key that says length unknown
525 uint64_t unknownLen = LITERALU64(0x01FFFFFFFFFFFFFF);
527 Ebml_WriteID(glob, class_id);
528 *ebmlLoc = ftello(glob->stream);
529 Ebml_Serialize(glob, &unknownLen, sizeof(unknownLen), 8);
533 Ebml_EndSubElement(EbmlGlobal *glob, EbmlLoc *ebmlLoc) {
537 /* Save the current stream pointer */
538 pos = ftello(glob->stream);
540 /* Calculate the size of this element */
541 size = pos - *ebmlLoc - 8;
542 size |= LITERALU64(0x0100000000000000);
544 /* Seek back to the beginning of the element and write the new size */
545 fseeko(glob->stream, *ebmlLoc, SEEK_SET);
546 Ebml_Serialize(glob, &size, sizeof(size), 8);
548 /* Reset the stream pointer */
549 fseeko(glob->stream, pos, SEEK_SET);
554 write_webm_seek_element(EbmlGlobal *ebml, unsigned long id, off_t pos) {
555 uint64_t offset = pos - ebml->position_reference;
557 Ebml_StartSubElement(ebml, &start, Seek);
558 Ebml_SerializeBinary(ebml, SeekID, id);
559 Ebml_SerializeUnsigned64(ebml, SeekPosition, offset);
560 Ebml_EndSubElement(ebml, &start);
565 write_webm_seek_info(EbmlGlobal *ebml) {
569 /* Save the current stream pointer */
570 pos = ftello(ebml->stream);
572 if (ebml->seek_info_pos)
573 fseeko(ebml->stream, ebml->seek_info_pos, SEEK_SET);
575 ebml->seek_info_pos = pos;
580 Ebml_StartSubElement(ebml, &start, SeekHead);
581 write_webm_seek_element(ebml, Tracks, ebml->track_pos);
582 write_webm_seek_element(ebml, Cues, ebml->cue_pos);
583 write_webm_seek_element(ebml, Info, ebml->segment_info_pos);
584 Ebml_EndSubElement(ebml, &start);
591 frame_time = (uint64_t)1000 * ebml->framerate.den
592 / ebml->framerate.num;
593 ebml->segment_info_pos = ftello(ebml->stream);
594 Ebml_StartSubElement(ebml, &startInfo, Info);
595 Ebml_SerializeUnsigned(ebml, TimecodeScale, 1000000);
596 Ebml_SerializeFloat(ebml, Segment_Duration,
597 ebml->last_pts_ms + frame_time);
598 Ebml_SerializeString(ebml, 0x4D80,
599 ebml->debug ? "vpxenc" : "vpxenc" VERSION_STRING);
600 Ebml_SerializeString(ebml, 0x5741,
601 ebml->debug ? "vpxenc" : "vpxenc" VERSION_STRING);
602 Ebml_EndSubElement(ebml, &startInfo);
608 write_webm_file_header(EbmlGlobal *glob,
609 const vpx_codec_enc_cfg_t *cfg,
610 const struct vpx_rational *fps,
611 stereo_format_t stereo_fmt) {
614 Ebml_StartSubElement(glob, &start, EBML);
615 Ebml_SerializeUnsigned(glob, EBMLVersion, 1);
616 Ebml_SerializeUnsigned(glob, EBMLReadVersion, 1); // EBML Read Version
617 Ebml_SerializeUnsigned(glob, EBMLMaxIDLength, 4); // EBML Max ID Length
618 Ebml_SerializeUnsigned(glob, EBMLMaxSizeLength, 8); // EBML Max Size Length
619 Ebml_SerializeString(glob, DocType, "webm"); // Doc Type
620 Ebml_SerializeUnsigned(glob, DocTypeVersion, 2); // Doc Type Version
621 Ebml_SerializeUnsigned(glob, DocTypeReadVersion, 2); // Doc Type Read Version
622 Ebml_EndSubElement(glob, &start);
625 Ebml_StartSubElement(glob, &glob->startSegment, Segment); // segment
626 glob->position_reference = ftello(glob->stream);
627 glob->framerate = *fps;
628 write_webm_seek_info(glob);
632 glob->track_pos = ftello(glob->stream);
633 Ebml_StartSubElement(glob, &trackStart, Tracks);
635 unsigned int trackNumber = 1;
636 uint64_t trackID = 0;
639 Ebml_StartSubElement(glob, &start, TrackEntry);
640 Ebml_SerializeUnsigned(glob, TrackNumber, trackNumber);
641 glob->track_id_pos = ftello(glob->stream);
642 Ebml_SerializeUnsigned32(glob, TrackUID, trackID);
643 Ebml_SerializeUnsigned(glob, TrackType, 1); // video is always 1
644 Ebml_SerializeString(glob, CodecID, "V_VP8");
646 unsigned int pixelWidth = cfg->g_w;
647 unsigned int pixelHeight = cfg->g_h;
648 float frameRate = (float)fps->num / (float)fps->den;
651 Ebml_StartSubElement(glob, &videoStart, Video);
652 Ebml_SerializeUnsigned(glob, PixelWidth, pixelWidth);
653 Ebml_SerializeUnsigned(glob, PixelHeight, pixelHeight);
654 Ebml_SerializeUnsigned(glob, StereoMode, stereo_fmt);
655 Ebml_SerializeFloat(glob, FrameRate, frameRate);
656 Ebml_EndSubElement(glob, &videoStart); // Video
658 Ebml_EndSubElement(glob, &start); // Track Entry
660 Ebml_EndSubElement(glob, &trackStart);
662 // segment element is open
668 write_webm_block(EbmlGlobal *glob,
669 const vpx_codec_enc_cfg_t *cfg,
670 const vpx_codec_cx_pkt_t *pkt) {
671 unsigned long block_length;
672 unsigned char track_number;
673 unsigned short block_timecode = 0;
676 int start_cluster = 0, is_keyframe;
678 /* Calculate the PTS of this frame in milliseconds */
679 pts_ms = pkt->data.frame.pts * 1000
680 * (uint64_t)cfg->g_timebase.num / (uint64_t)cfg->g_timebase.den;
681 if (pts_ms <= glob->last_pts_ms)
682 pts_ms = glob->last_pts_ms + 1;
683 glob->last_pts_ms = pts_ms;
685 /* Calculate the relative time of this block */
686 if (pts_ms - glob->cluster_timecode > SHRT_MAX)
689 block_timecode = pts_ms - glob->cluster_timecode;
691 is_keyframe = (pkt->data.frame.flags & VPX_FRAME_IS_KEY);
692 if (start_cluster || is_keyframe) {
693 if (glob->cluster_open)
694 Ebml_EndSubElement(glob, &glob->startCluster);
696 /* Open the new cluster */
698 glob->cluster_open = 1;
699 glob->cluster_timecode = pts_ms;
700 glob->cluster_pos = ftello(glob->stream);
701 Ebml_StartSubElement(glob, &glob->startCluster, Cluster); // cluster
702 Ebml_SerializeUnsigned(glob, Timecode, glob->cluster_timecode);
704 /* Save a cue point if this is a keyframe. */
706 struct cue_entry *cue, *new_cue_list;
708 new_cue_list = realloc(glob->cue_list,
709 (glob->cues + 1) * sizeof(struct cue_entry));
711 glob->cue_list = new_cue_list;
713 fprintf(stderr, "\nFailed to realloc cue list.\n");
717 cue = &glob->cue_list[glob->cues];
718 cue->time = glob->cluster_timecode;
719 cue->loc = glob->cluster_pos;
724 /* Write the Simple Block */
725 Ebml_WriteID(glob, SimpleBlock);
727 block_length = pkt->data.frame.sz + 4;
728 block_length |= 0x10000000;
729 Ebml_Serialize(glob, &block_length, sizeof(block_length), 4);
732 track_number |= 0x80;
733 Ebml_Write(glob, &track_number, 1);
735 Ebml_Serialize(glob, &block_timecode, sizeof(block_timecode), 2);
740 if (pkt->data.frame.flags & VPX_FRAME_IS_INVISIBLE)
742 Ebml_Write(glob, &flags, 1);
744 Ebml_Write(glob, pkt->data.frame.buf, pkt->data.frame.sz);
749 write_webm_file_footer(EbmlGlobal *glob, long hash) {
751 if (glob->cluster_open)
752 Ebml_EndSubElement(glob, &glob->startCluster);
758 glob->cue_pos = ftello(glob->stream);
759 Ebml_StartSubElement(glob, &start, Cues);
760 for (i = 0; i < glob->cues; i++) {
761 struct cue_entry *cue = &glob->cue_list[i];
764 Ebml_StartSubElement(glob, &start, CuePoint);
768 Ebml_SerializeUnsigned(glob, CueTime, cue->time);
770 Ebml_StartSubElement(glob, &start, CueTrackPositions);
771 Ebml_SerializeUnsigned(glob, CueTrack, 1);
772 Ebml_SerializeUnsigned64(glob, CueClusterPosition,
773 cue->loc - glob->position_reference);
774 // Ebml_SerializeUnsigned(glob, CueBlockNumber, cue->blockNumber);
775 Ebml_EndSubElement(glob, &start);
777 Ebml_EndSubElement(glob, &start);
779 Ebml_EndSubElement(glob, &start);
782 Ebml_EndSubElement(glob, &glob->startSegment);
784 /* Patch up the seek info block */
785 write_webm_seek_info(glob);
787 /* Patch up the track id */
788 fseeko(glob->stream, glob->track_id_pos, SEEK_SET);
789 Ebml_SerializeUnsigned32(glob, TrackUID, glob->debug ? 0xDEADBEEF : hash);
791 fseeko(glob->stream, 0, SEEK_END);
795 /* Murmur hash derived from public domain reference implementation at
796 * http:// sites.google.com/site/murmurhash/
798 static unsigned int murmur(const void *key, int len, unsigned int seed) {
799 const unsigned int m = 0x5bd1e995;
802 unsigned int h = seed ^ len;
804 const unsigned char *data = (const unsigned char *)key;
844 static double vp8_mse2psnr(double Samples, double Peak, double Mse) {
847 if ((double)Mse > 0.0)
848 psnr = 10.0 * log10(Peak * Peak * Samples / Mse);
850 psnr = MAX_PSNR; // Limit to prevent / 0
861 static const arg_def_t debugmode = ARG_DEF("D", "debug", 0,
862 "Debug mode (makes output deterministic)");
863 static const arg_def_t outputfile = ARG_DEF("o", "output", 1,
865 static const arg_def_t use_yv12 = ARG_DEF(NULL, "yv12", 0,
866 "Input file is YV12 ");
867 static const arg_def_t use_i420 = ARG_DEF(NULL, "i420", 0,
868 "Input file is I420 (default)");
869 static const arg_def_t codecarg = ARG_DEF(NULL, "codec", 1,
871 static const arg_def_t passes = ARG_DEF("p", "passes", 1,
872 "Number of passes (1/2)");
873 static const arg_def_t pass_arg = ARG_DEF(NULL, "pass", 1,
874 "Pass to execute (1/2)");
875 static const arg_def_t fpf_name = ARG_DEF(NULL, "fpf", 1,
876 "First pass statistics file name");
877 static const arg_def_t limit = ARG_DEF(NULL, "limit", 1,
878 "Stop encoding after n input frames");
879 static const arg_def_t skip = ARG_DEF(NULL, "skip", 1,
880 "Skip the first n input frames");
881 static const arg_def_t deadline = ARG_DEF("d", "deadline", 1,
882 "Deadline per frame (usec)");
883 static const arg_def_t best_dl = ARG_DEF(NULL, "best", 0,
884 "Use Best Quality Deadline");
885 static const arg_def_t good_dl = ARG_DEF(NULL, "good", 0,
886 "Use Good Quality Deadline");
887 static const arg_def_t rt_dl = ARG_DEF(NULL, "rt", 0,
888 "Use Realtime Quality Deadline");
889 static const arg_def_t verbosearg = ARG_DEF("v", "verbose", 0,
890 "Show encoder parameters");
891 static const arg_def_t psnrarg = ARG_DEF(NULL, "psnr", 0,
892 "Show PSNR in status line");
893 static const arg_def_t recontest = ARG_DEF(NULL, "test-decode", 0,
894 "Test enocde/decode have machted recon buffer");
895 static const arg_def_t framerate = ARG_DEF(NULL, "fps", 1,
896 "Stream frame rate (rate/scale)");
897 static const arg_def_t use_ivf = ARG_DEF(NULL, "ivf", 0,
898 "Output IVF (default is WebM)");
899 static const arg_def_t q_hist_n = ARG_DEF(NULL, "q-hist", 1,
900 "Show quantizer histogram (n-buckets)");
901 static const arg_def_t rate_hist_n = ARG_DEF(NULL, "rate-hist", 1,
902 "Show rate histogram (n-buckets)");
904 static const arg_def_t lossless_enabled = ARG_DEF(NULL, "lossless", 0,
905 "Enable lossless compression");
907 static const arg_def_t *main_args[] = {
909 &outputfile, &codecarg, &passes, &pass_arg, &fpf_name, &limit, &skip,
911 &best_dl, &good_dl, &rt_dl,
912 &verbosearg, &psnrarg, &recontest, &use_ivf, &q_hist_n, &rate_hist_n,
919 static const arg_def_t usage = ARG_DEF("u", "usage", 1,
920 "Usage profile number to use");
921 static const arg_def_t threads = ARG_DEF("t", "threads", 1,
922 "Max number of threads to use");
923 static const arg_def_t profile = ARG_DEF(NULL, "profile", 1,
924 "Bitstream profile number to use");
925 static const arg_def_t width = ARG_DEF("w", "width", 1,
927 static const arg_def_t height = ARG_DEF("h", "height", 1,
929 static const struct arg_enum_list stereo_mode_enum[] = {
930 {"mono", STEREO_FORMAT_MONO},
931 {"left-right", STEREO_FORMAT_LEFT_RIGHT},
932 {"bottom-top", STEREO_FORMAT_BOTTOM_TOP},
933 {"top-bottom", STEREO_FORMAT_TOP_BOTTOM},
934 {"right-left", STEREO_FORMAT_RIGHT_LEFT},
937 static const arg_def_t stereo_mode = ARG_DEF_ENUM(NULL, "stereo-mode", 1,
938 "Stereo 3D video format", stereo_mode_enum);
939 static const arg_def_t timebase = ARG_DEF(NULL, "timebase", 1,
940 "Output timestamp precision (fractional seconds)");
941 static const arg_def_t error_resilient = ARG_DEF(NULL, "error-resilient", 1,
942 "Enable error resiliency features");
943 static const arg_def_t lag_in_frames = ARG_DEF(NULL, "lag-in-frames", 1,
944 "Max number of frames to lag");
946 static const arg_def_t *global_args[] = {
947 &use_yv12, &use_i420, &usage, &threads, &profile,
948 &width, &height, &stereo_mode, &timebase, &framerate, &error_resilient,
952 static const arg_def_t dropframe_thresh = ARG_DEF(NULL, "drop-frame", 1,
953 "Temporal resampling threshold (buf %)");
954 static const arg_def_t resize_allowed = ARG_DEF(NULL, "resize-allowed", 1,
955 "Spatial resampling enabled (bool)");
956 static const arg_def_t resize_up_thresh = ARG_DEF(NULL, "resize-up", 1,
957 "Upscale threshold (buf %)");
958 static const arg_def_t resize_down_thresh = ARG_DEF(NULL, "resize-down", 1,
959 "Downscale threshold (buf %)");
960 static const struct arg_enum_list end_usage_enum[] = {
966 static const arg_def_t end_usage = ARG_DEF_ENUM(NULL, "end-usage", 1,
967 "Rate control mode", end_usage_enum);
968 static const arg_def_t target_bitrate = ARG_DEF(NULL, "target-bitrate", 1,
970 static const arg_def_t min_quantizer = ARG_DEF(NULL, "min-q", 1,
971 "Minimum (best) quantizer");
972 static const arg_def_t max_quantizer = ARG_DEF(NULL, "max-q", 1,
973 "Maximum (worst) quantizer");
974 static const arg_def_t undershoot_pct = ARG_DEF(NULL, "undershoot-pct", 1,
975 "Datarate undershoot (min) target (%)");
976 static const arg_def_t overshoot_pct = ARG_DEF(NULL, "overshoot-pct", 1,
977 "Datarate overshoot (max) target (%)");
978 static const arg_def_t buf_sz = ARG_DEF(NULL, "buf-sz", 1,
979 "Client buffer size (ms)");
980 static const arg_def_t buf_initial_sz = ARG_DEF(NULL, "buf-initial-sz", 1,
981 "Client initial buffer size (ms)");
982 static const arg_def_t buf_optimal_sz = ARG_DEF(NULL, "buf-optimal-sz", 1,
983 "Client optimal buffer size (ms)");
984 static const arg_def_t *rc_args[] = {
985 &dropframe_thresh, &resize_allowed, &resize_up_thresh, &resize_down_thresh,
986 &end_usage, &target_bitrate, &min_quantizer, &max_quantizer,
987 &undershoot_pct, &overshoot_pct, &buf_sz, &buf_initial_sz, &buf_optimal_sz,
992 static const arg_def_t bias_pct = ARG_DEF(NULL, "bias-pct", 1,
993 "CBR/VBR bias (0=CBR, 100=VBR)");
994 static const arg_def_t minsection_pct = ARG_DEF(NULL, "minsection-pct", 1,
995 "GOP min bitrate (% of target)");
996 static const arg_def_t maxsection_pct = ARG_DEF(NULL, "maxsection-pct", 1,
997 "GOP max bitrate (% of target)");
998 static const arg_def_t *rc_twopass_args[] = {
999 &bias_pct, &minsection_pct, &maxsection_pct, NULL
1003 static const arg_def_t kf_min_dist = ARG_DEF(NULL, "kf-min-dist", 1,
1004 "Minimum keyframe interval (frames)");
1005 static const arg_def_t kf_max_dist = ARG_DEF(NULL, "kf-max-dist", 1,
1006 "Maximum keyframe interval (frames)");
1007 static const arg_def_t kf_disabled = ARG_DEF(NULL, "disable-kf", 0,
1008 "Disable keyframe placement");
1009 static const arg_def_t *kf_args[] = {
1010 &kf_min_dist, &kf_max_dist, &kf_disabled, NULL
1014 #if CONFIG_VP8_ENCODER
1015 static const arg_def_t noise_sens = ARG_DEF(NULL, "noise-sensitivity", 1,
1016 "Noise sensitivity (frames to blur)");
1017 static const arg_def_t sharpness = ARG_DEF(NULL, "sharpness", 1,
1018 "Filter sharpness (0-7)");
1019 static const arg_def_t static_thresh = ARG_DEF(NULL, "static-thresh", 1,
1020 "Motion detection threshold");
1023 #if CONFIG_VP8_ENCODER
1024 static const arg_def_t cpu_used = ARG_DEF(NULL, "cpu-used", 1,
1025 "CPU Used (-16..16)");
1029 #if CONFIG_VP8_ENCODER
1030 static const arg_def_t token_parts = ARG_DEF(NULL, "token-parts", 1,
1031 "Number of token partitions to use, log2");
1032 static const arg_def_t auto_altref = ARG_DEF(NULL, "auto-alt-ref", 1,
1033 "Enable automatic alt reference frames");
1034 static const arg_def_t arnr_maxframes = ARG_DEF(NULL, "arnr-maxframes", 1,
1035 "AltRef Max Frames");
1036 static const arg_def_t arnr_strength = ARG_DEF(NULL, "arnr-strength", 1,
1038 static const arg_def_t arnr_type = ARG_DEF(NULL, "arnr-type", 1,
1040 static const struct arg_enum_list tuning_enum[] = {
1041 {"psnr", VP8_TUNE_PSNR},
1042 {"ssim", VP8_TUNE_SSIM},
1045 static const arg_def_t tune_ssim = ARG_DEF_ENUM(NULL, "tune", 1,
1046 "Material to favor", tuning_enum);
1047 static const arg_def_t cq_level = ARG_DEF(NULL, "cq-level", 1,
1048 "Constrained Quality Level");
1049 static const arg_def_t max_intra_rate_pct = ARG_DEF(NULL, "max-intra-rate", 1,
1050 "Max I-frame bitrate (pct)");
1052 static const arg_def_t *vp8_args[] = {
1053 &cpu_used, &auto_altref, &noise_sens, &sharpness, &static_thresh,
1054 &token_parts, &arnr_maxframes, &arnr_strength, &arnr_type,
1055 &tune_ssim, &cq_level, &max_intra_rate_pct, NULL
1057 static const int vp8_arg_ctrl_map[] = {
1058 VP8E_SET_CPUUSED, VP8E_SET_ENABLEAUTOALTREF,
1059 VP8E_SET_NOISE_SENSITIVITY, VP8E_SET_SHARPNESS, VP8E_SET_STATIC_THRESHOLD,
1060 VP8E_SET_TOKEN_PARTITIONS,
1061 VP8E_SET_ARNR_MAXFRAMES, VP8E_SET_ARNR_STRENGTH, VP8E_SET_ARNR_TYPE,
1062 VP8E_SET_TUNING, VP8E_SET_CQ_LEVEL, VP8E_SET_MAX_INTRA_BITRATE_PCT, 0
1066 static const arg_def_t *no_args[] = { NULL };
1068 static void usage_exit() {
1071 fprintf(stderr, "Usage: %s <options> -o dst_filename src_filename \n",
1074 fprintf(stderr, "\nOptions:\n");
1075 arg_show_usage(stdout, main_args);
1076 fprintf(stderr, "\nEncoder Global Options:\n");
1077 arg_show_usage(stdout, global_args);
1078 fprintf(stderr, "\nRate Control Options:\n");
1079 arg_show_usage(stdout, rc_args);
1080 fprintf(stderr, "\nTwopass Rate Control Options:\n");
1081 arg_show_usage(stdout, rc_twopass_args);
1082 fprintf(stderr, "\nKeyframe Placement Options:\n");
1083 arg_show_usage(stdout, kf_args);
1084 #if CONFIG_VP8_ENCODER
1085 fprintf(stderr, "\nVP8 Specific Options:\n");
1086 arg_show_usage(stdout, vp8_args);
1088 fprintf(stderr, "\nStream timebase (--timebase):\n"
1089 " The desired precision of timestamps in the output, expressed\n"
1090 " in fractional seconds. Default is 1/1000.\n");
1091 fprintf(stderr, "\n"
1092 "Included encoders:\n"
1095 for (i = 0; i < sizeof(codecs) / sizeof(codecs[0]); i++)
1096 fprintf(stderr, " %-6s - %s\n",
1098 vpx_codec_iface_name(codecs[i].iface()));
1104 #define HIST_BAR_MAX 40
1105 struct hist_bucket {
1106 int low, high, count;
1110 static int merge_hist_buckets(struct hist_bucket *bucket,
1113 int small_bucket = 0, merge_bucket = INT_MAX, big_bucket = 0;
1114 int buckets = *buckets_;
1117 /* Find the extrema for this list of buckets */
1118 big_bucket = small_bucket = 0;
1119 for (i = 0; i < buckets; i++) {
1120 if (bucket[i].count < bucket[small_bucket].count)
1122 if (bucket[i].count > bucket[big_bucket].count)
1126 /* If we have too many buckets, merge the smallest with an adjacent
1129 while (buckets > max_buckets) {
1130 int last_bucket = buckets - 1;
1132 // merge the small bucket with an adjacent one.
1133 if (small_bucket == 0)
1135 else if (small_bucket == last_bucket)
1136 merge_bucket = last_bucket - 1;
1137 else if (bucket[small_bucket - 1].count < bucket[small_bucket + 1].count)
1138 merge_bucket = small_bucket - 1;
1140 merge_bucket = small_bucket + 1;
1142 assert(abs(merge_bucket - small_bucket) <= 1);
1143 assert(small_bucket < buckets);
1144 assert(big_bucket < buckets);
1145 assert(merge_bucket < buckets);
1147 if (merge_bucket < small_bucket) {
1148 bucket[merge_bucket].high = bucket[small_bucket].high;
1149 bucket[merge_bucket].count += bucket[small_bucket].count;
1151 bucket[small_bucket].high = bucket[merge_bucket].high;
1152 bucket[small_bucket].count += bucket[merge_bucket].count;
1153 merge_bucket = small_bucket;
1156 assert(bucket[merge_bucket].low != bucket[merge_bucket].high);
1160 /* Remove the merge_bucket from the list, and find the new small
1161 * and big buckets while we're at it
1163 big_bucket = small_bucket = 0;
1164 for (i = 0; i < buckets; i++) {
1165 if (i > merge_bucket)
1166 bucket[i] = bucket[i + 1];
1168 if (bucket[i].count < bucket[small_bucket].count)
1170 if (bucket[i].count > bucket[big_bucket].count)
1176 *buckets_ = buckets;
1177 return bucket[big_bucket].count;
1181 static void show_histogram(const struct hist_bucket *bucket,
1185 const char *pat1, *pat2;
1188 switch ((int)(log(bucket[buckets - 1].high) / log(10)) + 1) {
1215 pat1 = "%12d %10s: ";
1216 pat2 = "%12d-%10d: ";
1220 for (i = 0; i < buckets; i++) {
1225 pct = 100.0 * (float)bucket[i].count / (float)total;
1226 len = HIST_BAR_MAX * bucket[i].count / scale;
1229 assert(len <= HIST_BAR_MAX);
1231 if (bucket[i].low == bucket[i].high)
1232 fprintf(stderr, pat1, bucket[i].low, "");
1234 fprintf(stderr, pat2, bucket[i].low, bucket[i].high);
1236 for (j = 0; j < HIST_BAR_MAX; j++)
1237 fprintf(stderr, j < len ? "=" : " ");
1238 fprintf(stderr, "\t%5d (%6.2f%%)\n", bucket[i].count, pct);
1243 static void show_q_histogram(const int counts[64], int max_buckets) {
1244 struct hist_bucket bucket[64];
1251 for (i = 0; i < 64; i++) {
1253 bucket[buckets].low = bucket[buckets].high = i;
1254 bucket[buckets].count = counts[i];
1260 fprintf(stderr, "\nQuantizer Selection:\n");
1261 scale = merge_hist_buckets(bucket, &buckets, max_buckets);
1262 show_histogram(bucket, buckets, total, scale);
1266 #define RATE_BINS (100)
1272 struct hist_bucket bucket[RATE_BINS];
1277 static void init_rate_histogram(struct rate_hist *hist,
1278 const vpx_codec_enc_cfg_t *cfg,
1279 const vpx_rational_t *fps) {
1282 /* Determine the number of samples in the buffer. Use the file's framerate
1283 * to determine the number of frames in rc_buf_sz milliseconds, with an
1284 * adjustment (5/4) to account for alt-refs
1286 hist->samples = cfg->rc_buf_sz * 5 / 4 * fps->num / fps->den / 1000;
1288 // prevent division by zero
1289 if (hist->samples == 0)
1292 hist->pts = calloc(hist->samples, sizeof(*hist->pts));
1293 hist->sz = calloc(hist->samples, sizeof(*hist->sz));
1294 for (i = 0; i < RATE_BINS; i++) {
1295 hist->bucket[i].low = INT_MAX;
1296 hist->bucket[i].high = 0;
1297 hist->bucket[i].count = 0;
1302 static void destroy_rate_histogram(struct rate_hist *hist) {
1308 static void update_rate_histogram(struct rate_hist *hist,
1309 const vpx_codec_enc_cfg_t *cfg,
1310 const vpx_codec_cx_pkt_t *pkt) {
1312 int64_t now, then, sum_sz = 0, avg_bitrate;
1314 now = pkt->data.frame.pts * 1000
1315 * (uint64_t)cfg->g_timebase.num / (uint64_t)cfg->g_timebase.den;
1317 idx = hist->frames++ % hist->samples;
1318 hist->pts[idx] = now;
1319 hist->sz[idx] = pkt->data.frame.sz;
1321 if (now < cfg->rc_buf_initial_sz)
1326 /* Sum the size over the past rc_buf_sz ms */
1327 for (i = hist->frames; i > 0 && hist->frames - i < hist->samples; i--) {
1328 int i_idx = (i - 1) % hist->samples;
1330 then = hist->pts[i_idx];
1331 if (now - then > cfg->rc_buf_sz)
1333 sum_sz += hist->sz[i_idx];
1339 avg_bitrate = sum_sz * 8 * 1000 / (now - then);
1340 idx = avg_bitrate * (RATE_BINS / 2) / (cfg->rc_target_bitrate * 1000);
1343 if (idx > RATE_BINS - 1)
1344 idx = RATE_BINS - 1;
1345 if (hist->bucket[idx].low > avg_bitrate)
1346 hist->bucket[idx].low = avg_bitrate;
1347 if (hist->bucket[idx].high < avg_bitrate)
1348 hist->bucket[idx].high = avg_bitrate;
1349 hist->bucket[idx].count++;
1354 static void show_rate_histogram(struct rate_hist *hist,
1355 const vpx_codec_enc_cfg_t *cfg,
1360 for (i = 0; i < RATE_BINS; i++) {
1361 if (hist->bucket[i].low == INT_MAX)
1363 hist->bucket[buckets++] = hist->bucket[i];
1366 fprintf(stderr, "\nRate (over %dms window):\n", cfg->rc_buf_sz);
1367 scale = merge_hist_buckets(hist->bucket, &buckets, max_buckets);
1368 show_histogram(hist->bucket, buckets, hist->total, scale);
1372 static int compare_img(vpx_image_t *img1, vpx_image_t *img2) {
1376 match &= (img1->fmt == img2->fmt);
1377 match &= (img1->w == img2->w);
1378 match &= (img1->h == img2->h);
1380 for (i = 0; i < img1->d_h; i++)
1381 match &= (memcmp(img1->planes[VPX_PLANE_Y] + i * img1->stride[VPX_PLANE_Y],
1382 img2->planes[VPX_PLANE_Y] + i * img2->stride[VPX_PLANE_Y],
1385 for (i = 0; i < img1->d_h / 2; i++)
1386 match &= (memcmp(img1->planes[VPX_PLANE_U] + i * img1->stride[VPX_PLANE_U],
1387 img2->planes[VPX_PLANE_U] + i * img2->stride[VPX_PLANE_U],
1388 img1->d_w / 2) == 0);
1390 for (i = 0; i < img1->d_h / 2; i++)
1391 match &= (memcmp(img1->planes[VPX_PLANE_V] + i * img1->stride[VPX_PLANE_U],
1392 img2->planes[VPX_PLANE_V] + i * img2->stride[VPX_PLANE_U],
1393 img1->d_w / 2) == 0);
1399 #define ARG_CTRL_CNT_MAX 10
1401 int main(int argc, const char **argv_) {
1402 vpx_codec_ctx_t encoder;
1403 const char *in_fn = NULL, *out_fn = NULL, *stats_fn = NULL;
1405 FILE *infile, *outfile;
1406 vpx_codec_enc_cfg_t cfg;
1407 vpx_codec_err_t res;
1408 int pass, one_pass_only = 0;
1411 const struct codec_item *codec = codecs;
1412 int frame_avail, got_data;
1415 char **argv, **argi, **argj;
1416 int arg_usage = 0, arg_passes = 1, arg_deadline = 0;
1417 int arg_ctrls[ARG_CTRL_CNT_MAX][2], arg_ctrl_cnt = 0;
1420 static const arg_def_t **ctrl_args = no_args;
1421 static const int *ctrl_args_map = NULL;
1422 int verbose = 0, show_psnr = 0, test_decode = 0;
1423 int arg_use_i420 = 1;
1424 unsigned long cx_time = 0;
1425 unsigned int file_type, fourcc;
1427 struct vpx_rational arg_framerate = {30, 1};
1428 int arg_have_framerate = 0;
1430 EbmlGlobal ebml = {0};
1432 uint64_t psnr_sse_total = 0;
1433 uint64_t psnr_samples_total = 0;
1434 double psnr_totals[4] = {0, 0, 0, 0};
1436 stereo_format_t stereo_fmt = STEREO_FORMAT_MONO;
1437 int counts[64] = {0};
1438 int show_q_hist_buckets = 0;
1439 int show_rate_hist_buckets = 0;
1440 struct rate_hist rate_hist = {0};
1442 vpx_codec_ctx_t decoder;
1443 vpx_ref_frame_t ref_enc;
1444 vpx_ref_frame_t ref_dec;
1445 vpx_codec_dec_cfg_t dec_cfg = {0};
1446 int enc_dec_match = 1;
1447 int first_bad_frame = -1;
1448 int test_decode_frame = 0;
1450 exec_name = argv_[0];
1451 ebml.last_pts_ms = -1;
1457 /* First parse the codec and usage values, because we want to apply other
1458 * parameters on top of the default configuration provided by the codec.
1460 argv = argv_dup(argc - 1, argv_ + 1);
1462 for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step) {
1465 if (arg_match(&arg, &codecarg, argi)) {
1468 for (j = 0; j < sizeof(codecs) / sizeof(codecs[0]); j++)
1469 if (!strcmp(codecs[j].name, arg.val))
1475 die("Error: Unrecognized argument (%s) to --codec\n",
1478 } else if (arg_match(&arg, &passes, argi)) {
1479 arg_passes = arg_parse_uint(&arg);
1481 if (arg_passes < 1 || arg_passes > 2)
1482 die("Error: Invalid number of passes (%d)\n", arg_passes);
1483 } else if (arg_match(&arg, &pass_arg, argi)) {
1484 one_pass_only = arg_parse_uint(&arg);
1486 if (one_pass_only < 1 || one_pass_only > 2)
1487 die("Error: Invalid pass selected (%d)\n", one_pass_only);
1488 } else if (arg_match(&arg, &fpf_name, argi))
1490 else if (arg_match(&arg, &usage, argi))
1491 arg_usage = arg_parse_uint(&arg);
1492 else if (arg_match(&arg, &deadline, argi))
1493 arg_deadline = arg_parse_uint(&arg);
1494 else if (arg_match(&arg, &best_dl, argi))
1495 arg_deadline = VPX_DL_BEST_QUALITY;
1496 else if (arg_match(&arg, &good_dl, argi))
1497 arg_deadline = VPX_DL_GOOD_QUALITY;
1498 else if (arg_match(&arg, &rt_dl, argi))
1499 arg_deadline = VPX_DL_REALTIME;
1500 else if (arg_match(&arg, &use_yv12, argi)) {
1502 } else if (arg_match(&arg, &use_i420, argi)) {
1504 } else if (arg_match(&arg, &verbosearg, argi))
1506 else if (arg_match(&arg, &limit, argi))
1507 arg_limit = arg_parse_uint(&arg);
1508 else if (arg_match(&arg, &skip, argi))
1509 arg_skip = arg_parse_uint(&arg);
1510 else if (arg_match(&arg, &psnrarg, argi))
1512 else if (arg_match(&arg, &recontest, argi))
1514 else if (arg_match(&arg, &framerate, argi)) {
1515 arg_framerate = arg_parse_rational(&arg);
1516 arg_have_framerate = 1;
1517 } else if (arg_match(&arg, &use_ivf, argi))
1519 else if (arg_match(&arg, &outputfile, argi))
1521 else if (arg_match(&arg, &debugmode, argi))
1523 else if (arg_match(&arg, &q_hist_n, argi))
1524 show_q_hist_buckets = arg_parse_uint(&arg);
1525 else if (arg_match(&arg, &rate_hist_n, argi))
1526 show_rate_hist_buckets = arg_parse_uint(&arg);
1531 /* Ensure that --passes and --pass are consistent. If --pass is set and --passes=2,
1532 * ensure --fpf was set.
1534 if (one_pass_only) {
1535 /* DWIM: Assume the user meant passes=2 if pass=2 is specified */
1536 if (one_pass_only > arg_passes) {
1537 fprintf(stderr, "Warning: Assuming --pass=%d implies --passes=%d\n",
1538 one_pass_only, one_pass_only);
1539 arg_passes = one_pass_only;
1542 if (arg_passes == 2 && !stats_fn)
1543 die("Must specify --fpf when --pass=%d and --passes=2\n", one_pass_only);
1546 /* Populate encoder configuration */
1547 res = vpx_codec_enc_config_default(codec->iface(), &cfg, arg_usage);
1550 fprintf(stderr, "Failed to get config: %s\n",
1551 vpx_codec_err_to_string(res));
1552 return EXIT_FAILURE;
1555 /* Change the default timebase to a high enough value so that the encoder
1556 * will always create strictly increasing timestamps.
1558 cfg.g_timebase.den = 1000;
1560 /* Never use the library's default resolution, require it be parsed
1561 * from the file or set on the command line.
1570 /* Now parse the remainder of the parameters. */
1571 for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step) {
1575 else if (arg_match(&arg, &threads, argi))
1576 cfg.g_threads = arg_parse_uint(&arg);
1577 else if (arg_match(&arg, &profile, argi))
1578 cfg.g_profile = arg_parse_uint(&arg);
1579 else if (arg_match(&arg, &width, argi))
1580 cfg.g_w = arg_parse_uint(&arg);
1581 else if (arg_match(&arg, &height, argi))
1582 cfg.g_h = arg_parse_uint(&arg);
1583 else if (arg_match(&arg, &stereo_mode, argi))
1584 stereo_fmt = arg_parse_enum_or_int(&arg);
1585 else if (arg_match(&arg, &timebase, argi))
1586 cfg.g_timebase = arg_parse_rational(&arg);
1587 else if (arg_match(&arg, &error_resilient, argi))
1588 cfg.g_error_resilient = arg_parse_uint(&arg);
1589 else if (arg_match(&arg, &lag_in_frames, argi))
1590 cfg.g_lag_in_frames = arg_parse_uint(&arg);
1591 else if (arg_match(&arg, &dropframe_thresh, argi))
1592 cfg.rc_dropframe_thresh = arg_parse_uint(&arg);
1593 else if (arg_match(&arg, &resize_allowed, argi))
1594 cfg.rc_resize_allowed = arg_parse_uint(&arg);
1595 else if (arg_match(&arg, &resize_up_thresh, argi))
1596 cfg.rc_resize_up_thresh = arg_parse_uint(&arg);
1597 else if (arg_match(&arg, &resize_down_thresh, argi))
1598 cfg.rc_resize_down_thresh = arg_parse_uint(&arg);
1599 else if (arg_match(&arg, &resize_down_thresh, argi))
1600 cfg.rc_resize_down_thresh = arg_parse_uint(&arg);
1601 else if (arg_match(&arg, &end_usage, argi))
1602 cfg.rc_end_usage = arg_parse_enum_or_int(&arg);
1603 else if (arg_match(&arg, &target_bitrate, argi))
1604 cfg.rc_target_bitrate = arg_parse_uint(&arg);
1605 else if (arg_match(&arg, &min_quantizer, argi))
1606 cfg.rc_min_quantizer = arg_parse_uint(&arg);
1607 else if (arg_match(&arg, &max_quantizer, argi))
1608 cfg.rc_max_quantizer = arg_parse_uint(&arg);
1609 else if (arg_match(&arg, &undershoot_pct, argi))
1610 cfg.rc_undershoot_pct = arg_parse_uint(&arg);
1611 else if (arg_match(&arg, &overshoot_pct, argi))
1612 cfg.rc_overshoot_pct = arg_parse_uint(&arg);
1613 else if (arg_match(&arg, &buf_sz, argi))
1614 cfg.rc_buf_sz = arg_parse_uint(&arg);
1615 else if (arg_match(&arg, &buf_initial_sz, argi))
1616 cfg.rc_buf_initial_sz = arg_parse_uint(&arg);
1617 else if (arg_match(&arg, &buf_optimal_sz, argi))
1618 cfg.rc_buf_optimal_sz = arg_parse_uint(&arg);
1619 else if (arg_match(&arg, &bias_pct, argi)) {
1620 cfg.rc_2pass_vbr_bias_pct = arg_parse_uint(&arg);
1624 "Warning: option %s ignored in one-pass mode.\n",
1626 } else if (arg_match(&arg, &minsection_pct, argi)) {
1627 cfg.rc_2pass_vbr_minsection_pct = arg_parse_uint(&arg);
1631 "Warning: option %s ignored in one-pass mode.\n",
1633 } else if (arg_match(&arg, &maxsection_pct, argi)) {
1634 cfg.rc_2pass_vbr_maxsection_pct = arg_parse_uint(&arg);
1638 "Warning: option %s ignored in one-pass mode.\n",
1640 } else if (arg_match(&arg, &kf_min_dist, argi))
1641 cfg.kf_min_dist = arg_parse_uint(&arg);
1642 else if (arg_match(&arg, &kf_max_dist, argi))
1643 cfg.kf_max_dist = arg_parse_uint(&arg);
1644 else if (arg_match(&arg, &kf_disabled, argi))
1645 cfg.kf_mode = VPX_KF_DISABLED;
1647 else if (arg_match(&arg, &lossless_enabled, argi))
1656 cfg.rc_min_quantizer = 0;
1657 cfg.rc_max_quantizer = 0;
1661 /* Handle codec specific options */
1662 #if CONFIG_VP8_ENCODER
1664 if (codec->fourcc == VP8_FOURCC) {
1665 ctrl_args = vp8_args;
1666 ctrl_args_map = vp8_arg_ctrl_map;
1671 for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step) {
1676 for (i = 0; ctrl_args[i]; i++) {
1677 if (arg_match(&arg, ctrl_args[i], argi)) {
1680 if (arg_ctrl_cnt < ARG_CTRL_CNT_MAX) {
1681 arg_ctrls[arg_ctrl_cnt][0] = ctrl_args_map[i];
1682 arg_ctrls[arg_ctrl_cnt][1] = arg_parse_enum_or_int(&arg);
1692 /* Check for unrecognized options */
1693 for (argi = argv; *argi; argi++)
1694 if (argi[0][0] == '-' && argi[0][1])
1695 die("Error: Unrecognized option %s\n", *argi);
1697 /* Handle non-option arguments */
1704 die("Error: Output file is required (specify with -o)\n");
1706 memset(&stats, 0, sizeof(stats));
1708 for (pass = one_pass_only ? one_pass_only - 1 : 0; pass < arg_passes; pass++) {
1709 int frames_in = 0, frames_out = 0;
1710 unsigned long nbytes = 0;
1711 int skip_frames = 0;
1712 struct detect_buffer detect;
1714 /* Parse certain options from the input file, if possible */
1715 infile = strcmp(in_fn, "-") ? fopen(in_fn, "rb")
1716 : set_binary_mode(stdin);
1719 fprintf(stderr, "Failed to open input file\n");
1720 return EXIT_FAILURE;
1723 /* For RAW input sources, these bytes will applied on the first frame
1726 detect.buf_read = fread(detect.buf, 1, 4, infile);
1727 detect.position = 0;
1729 if (detect.buf_read == 4 && file_is_y4m(infile, &y4m, detect.buf)) {
1730 if (y4m_input_open(&y4m, infile, detect.buf, 4) >= 0) {
1731 file_type = FILE_TYPE_Y4M;
1732 cfg.g_w = y4m.pic_w;
1733 cfg.g_h = y4m.pic_h;
1735 /* Use the frame rate from the file only if none was specified
1736 * on the command-line.
1738 if (!arg_have_framerate) {
1739 arg_framerate.num = y4m.fps_n;
1740 arg_framerate.den = y4m.fps_d;
1745 fprintf(stderr, "Unsupported Y4M stream.\n");
1746 return EXIT_FAILURE;
1748 } else if (detect.buf_read == 4 &&
1749 file_is_ivf(infile, &fourcc, &cfg.g_w, &cfg.g_h, &detect)) {
1750 file_type = FILE_TYPE_IVF;
1759 fprintf(stderr, "Unsupported fourcc (%08x) in IVF\n", fourcc);
1760 return EXIT_FAILURE;
1763 file_type = FILE_TYPE_RAW;
1766 if (!cfg.g_w || !cfg.g_h) {
1767 fprintf(stderr, "Specify stream dimensions with --width (-w) "
1768 " and --height (-h).\n");
1769 return EXIT_FAILURE;
1772 #define SHOW(field) fprintf(stderr, " %-28s = %d\n", #field, cfg.field)
1774 if (verbose && pass == 0) {
1775 fprintf(stderr, "Codec: %s\n", vpx_codec_iface_name(codec->iface()));
1776 fprintf(stderr, "Source file: %s Format: %s\n", in_fn,
1777 arg_use_i420 ? "I420" : "YV12");
1778 fprintf(stderr, "Destination file: %s\n", out_fn);
1779 fprintf(stderr, "Encoder parameters:\n");
1786 SHOW(g_timebase.num);
1787 SHOW(g_timebase.den);
1788 SHOW(g_error_resilient);
1790 SHOW(g_lag_in_frames);
1791 SHOW(rc_dropframe_thresh);
1792 SHOW(rc_resize_allowed);
1793 SHOW(rc_resize_up_thresh);
1794 SHOW(rc_resize_down_thresh);
1796 SHOW(rc_target_bitrate);
1797 SHOW(rc_min_quantizer);
1798 SHOW(rc_max_quantizer);
1799 SHOW(rc_undershoot_pct);
1800 SHOW(rc_overshoot_pct);
1802 SHOW(rc_buf_initial_sz);
1803 SHOW(rc_buf_optimal_sz);
1804 SHOW(rc_2pass_vbr_bias_pct);
1805 SHOW(rc_2pass_vbr_minsection_pct);
1806 SHOW(rc_2pass_vbr_maxsection_pct);
1815 if (pass == (one_pass_only ? one_pass_only - 1 : 0)) {
1816 if (file_type == FILE_TYPE_Y4M)
1817 /*The Y4M reader does its own allocation.
1818 Just initialize this here to avoid problems if we never read any
1820 memset(&raw, 0, sizeof(raw));
1822 vpx_img_alloc(&raw, arg_use_i420 ? VPX_IMG_FMT_I420 : VPX_IMG_FMT_YV12,
1823 cfg.g_w, cfg.g_h, 1);
1826 init_rate_histogram(&rate_hist, &cfg, &arg_framerate);
1830 int width = cfg.g_w;
1831 int height = cfg.g_h;
1832 width = (width + 15)& ~15;
1833 height = (height + 15) & ~15;
1835 vpx_img_alloc(&ref_enc.img, VPX_IMG_FMT_I420,
1837 vpx_img_alloc(&ref_dec.img, VPX_IMG_FMT_I420,
1841 outfile = strcmp(out_fn, "-") ? fopen(out_fn, "wb")
1842 : set_binary_mode(stdout);
1845 fprintf(stderr, "Failed to open output file\n");
1846 return EXIT_FAILURE;
1849 if (write_webm && fseek(outfile, 0, SEEK_CUR)) {
1850 fprintf(stderr, "WebM output to pipes not supported.\n");
1851 return EXIT_FAILURE;
1855 if (!stats_open_file(&stats, stats_fn, pass)) {
1856 fprintf(stderr, "Failed to open statistics store\n");
1857 return EXIT_FAILURE;
1860 if (!stats_open_mem(&stats, pass)) {
1861 fprintf(stderr, "Failed to open statistics store\n");
1862 return EXIT_FAILURE;
1866 cfg.g_pass = arg_passes == 2
1867 ? pass ? VPX_RC_LAST_PASS : VPX_RC_FIRST_PASS
1869 #if VPX_ENCODER_ABI_VERSION > (1 + VPX_CODEC_ABI_VERSION)
1872 cfg.rc_twopass_stats_in = stats_get(&stats);
1878 ebml.stream = outfile;
1879 write_webm_file_header(&ebml, &cfg, &arg_framerate, stereo_fmt);
1881 write_ivf_file_header(outfile, &cfg, codec->fourcc, 0);
1884 /* Construct Encoder Context */
1885 vpx_codec_enc_init(&encoder, codec->iface(), &cfg,
1886 show_psnr ? VPX_CODEC_USE_PSNR : 0);
1887 ctx_exit_on_error(&encoder, "Failed to initialize encoder");
1890 vpx_codec_dec_init(&decoder, ifaces[0].iface(), &dec_cfg, 0)) {
1892 "Failed to initialize decoder: %s\n",
1893 vpx_codec_error(&decoder));
1894 return EXIT_FAILURE;
1896 /* Note that we bypass the vpx_codec_control wrapper macro because
1897 * we're being clever to store the control IDs in an array. Real
1898 * applications will want to make use of the enumerations directly
1900 for (i = 0; i < arg_ctrl_cnt; i++) {
1901 if (vpx_codec_control_(&encoder, arg_ctrls[i][0], arg_ctrls[i][1]))
1902 fprintf(stderr, "Error: Tried to set control %d = %d\n",
1903 arg_ctrls[i][0], arg_ctrls[i][1]);
1904 ctx_exit_on_error(&encoder, "Failed to control codec");
1910 skip_frames = arg_skip;
1911 while (skip_frames) {
1912 frame_avail = read_frame(infile, &raw, file_type, &y4m, &detect);
1917 "\rPass %d/%d frame %4d/%-4d %7ldB \033[K", pass + 1,
1918 arg_passes, skip_frames, frames_out, nbytes);
1921 while (frame_avail || got_data) {
1922 vpx_codec_iter_t iter = NULL;
1923 vpx_codec_iter_t dec_iter = NULL;
1924 const vpx_codec_cx_pkt_t *pkt;
1925 struct vpx_usec_timer timer;
1926 int64_t frame_start, next_frame_start;
1928 if (!arg_limit || frames_in < arg_limit) {
1929 frame_avail = read_frame(infile, &raw, file_type, &y4m,
1936 vpx_usec_timer_start(&timer);
1938 frame_start = (cfg.g_timebase.den * (int64_t)(frames_in - 1)
1939 * arg_framerate.den) / cfg.g_timebase.num / arg_framerate.num;
1940 next_frame_start = (cfg.g_timebase.den * (int64_t)(frames_in)
1941 * arg_framerate.den)
1942 / cfg.g_timebase.num / arg_framerate.num;
1943 vpx_codec_encode(&encoder, frame_avail ? &raw : NULL, frame_start,
1944 next_frame_start - frame_start,
1946 vpx_usec_timer_mark(&timer);
1947 cx_time += vpx_usec_timer_elapsed(&timer);
1948 ctx_exit_on_error(&encoder, "Failed to encode frame");
1950 if (cfg.g_pass != VPX_RC_FIRST_PASS) {
1953 vpx_codec_control(&encoder, VP8E_GET_LAST_QUANTIZER_64, &q);
1954 ctx_exit_on_error(&encoder, "Failed to read quantizer");
1959 test_decode_frame = 0;
1960 while ((pkt = vpx_codec_get_cx_data(&encoder, &iter))) {
1963 switch (pkt->kind) {
1964 case VPX_CODEC_CX_FRAME_PKT:
1966 "\rPass %d/%d frame %4d/%-4d %7ldB \033[K", pass + 1,
1967 arg_passes, frames_in, frames_out, nbytes);
1969 fprintf(stderr, " %6luF",
1970 (unsigned long)pkt->data.frame.sz);
1973 if (!vpx_codec_decode(&decoder,
1974 pkt->data.frame.buf,
1977 vpx_codec_get_frame(&decoder, &dec_iter);
1978 test_decode_frame = 1;
1980 const char *detail = vpx_codec_error_detail(&decoder);
1981 fprintf(stderr, "Failed to decode frame: %s\n",
1982 vpx_codec_error(&decoder));
1985 " Additional information: %s\n",
1990 update_rate_histogram(&rate_hist, &cfg, pkt);
1992 /* Update the hash */
1994 hash = murmur(pkt->data.frame.buf,
1995 pkt->data.frame.sz, hash);
1997 write_webm_block(&ebml, &cfg, pkt);
1999 write_ivf_frame_header(outfile, pkt);
2000 if (fwrite(pkt->data.frame.buf, 1,
2001 pkt->data.frame.sz, outfile));
2003 nbytes += pkt->data.raw.sz;
2005 case VPX_CODEC_STATS_PKT:
2007 "\rPass %d/%d frame %4d/%-4d %7ldB \033[K", pass + 1,
2008 arg_passes, frames_in, frames_out, nbytes);
2010 fprintf(stderr, " %6luS",
2011 (unsigned long)pkt->data.twopass_stats.sz);
2013 pkt->data.twopass_stats.buf,
2014 pkt->data.twopass_stats.sz);
2015 nbytes += pkt->data.raw.sz;
2017 case VPX_CODEC_PSNR_PKT:
2022 psnr_sse_total += pkt->data.psnr.sse[0];
2023 psnr_samples_total += pkt->data.psnr.samples[0];
2024 for (i = 0; i < 4; i++) {
2025 fprintf(stderr, "%.3lf ", pkt->data.psnr.psnr[i]);
2026 psnr_totals[i] += pkt->data.psnr.psnr[i];
2036 if (test_decode && test_decode_frame) {
2037 ref_enc.frame_type = VP8_LAST_FRAME;
2038 ref_dec.frame_type = VP8_LAST_FRAME;
2040 vpx_codec_control(&encoder,
2043 vpx_codec_control(&decoder,
2047 enc_dec_match &= compare_img(&ref_enc.img,
2049 if (!enc_dec_match && first_bad_frame < 0) {
2050 first_bad_frame = frames_out - 1;
2058 "\rPass %d/%d frame %4d/%-4d %7ldB %7ldb/f %7"PRId64"b/s"
2059 " %7lu %s (%.2f fps)\033[K", pass + 1,
2060 arg_passes, frames_in, frames_out, nbytes, nbytes * 8 / frames_in,
2061 nbytes * 8 * (int64_t)arg_framerate.num / arg_framerate.den / frames_in,
2062 cx_time > 9999999 ? cx_time / 1000 : cx_time,
2063 cx_time > 9999999 ? "ms" : "us",
2064 (float)frames_in * 1000000.0 / (float)cx_time);
2066 if ((show_psnr) && (psnr_count > 0)) {
2068 double ovpsnr = vp8_mse2psnr(psnr_samples_total, 255.0,
2071 fprintf(stderr, "\nPSNR (Overall/Avg/Y/U/V)");
2073 fprintf(stderr, " %.3lf", ovpsnr);
2074 for (i = 0; i < 4; i++) {
2075 fprintf(stderr, " %.3lf", psnr_totals[i] / psnr_count);
2079 vpx_codec_destroy(&encoder);
2082 vpx_codec_destroy(&decoder);
2085 if (file_type == FILE_TYPE_Y4M)
2086 y4m_input_close(&y4m);
2089 write_webm_file_footer(&ebml, hash);
2090 free(ebml.cue_list);
2091 ebml.cue_list = NULL;
2093 if (!fseek(outfile, 0, SEEK_SET))
2094 write_ivf_file_header(outfile, &cfg, codec->fourcc, frames_out);
2098 stats_close(&stats, arg_passes - 1);
2099 fprintf(stderr, "\n");
2106 #if CONFIG_INTERNAL_STATS
2107 FILE *f = fopen("opsnr.stt", "a");
2109 fprintf(stderr, "\n");
2110 if (enc_dec_match) {
2111 fprintf(stderr, "No mismatch detected in recon buffers\n");
2112 #if CONFIG_INTERNAL_STATS
2113 fprintf(f, "No mismatch detected in recon buffers\n");
2116 fprintf(stderr, "First mismatch occurred in frame %d\n",
2118 #if CONFIG_INTERNAL_STATS
2119 fprintf(f, "First mismatch occurred in frame %d\n",
2123 #if CONFIG_INTERNAL_STATS
2128 if (show_q_hist_buckets)
2129 show_q_histogram(counts, show_q_hist_buckets);
2131 if (show_rate_hist_buckets)
2132 show_rate_histogram(&rate_hist, &cfg, show_rate_hist_buckets);
2133 destroy_rate_histogram(&rate_hist);
2137 vpx_img_free(&ref_enc.img);
2138 vpx_img_free(&ref_dec.img);
2141 return EXIT_SUCCESS;