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"
26 #include "vpx/vpx_decoder.h"
28 #include <sys/types.h>
35 #if CONFIG_VP8_ENCODER || CONFIG_VP9_ENCODER
36 #include "vpx/vp8cx.h"
38 #if CONFIG_VP8_DECODER || CONFIG_VP9_DECODER
39 #include "vpx/vp8dx.h"
42 #include "vpx_ports/mem_ops.h"
43 #include "vpx_ports/vpx_timer.h"
44 #include "tools_common.h"
46 #include "libmkv/EbmlWriter.h"
47 #include "libmkv/EbmlIDs.h"
49 /* Need special handling of these functions on Windows */
51 /* MSVS doesn't define off_t, and uses _f{seek,tell}i64 */
52 typedef __int64 off_t;
53 #define fseeko _fseeki64
54 #define ftello _ftelli64
56 /* MinGW defines off_t as long
57 and uses f{seek,tell}o64/off64_t for large files */
58 #define fseeko fseeko64
59 #define ftello ftello64
63 #define LITERALU64(hi,lo) ((((uint64_t)hi)<<32)|lo)
65 /* We should use 32-bit file operations in WebM file format
66 * when building ARM executable file (.axf) with RVCT */
67 #if !CONFIG_OS_SUPPORT
73 /* Swallow warnings about unused results of fread/fwrite */
74 static size_t wrap_fread(void *ptr, size_t size, size_t nmemb,
76 return fread(ptr, size, nmemb, stream);
78 #define fread wrap_fread
80 static size_t wrap_fwrite(const void *ptr, size_t size, size_t nmemb,
82 return fwrite(ptr, size, nmemb, stream);
84 #define fwrite wrap_fwrite
87 static const char *exec_name;
89 static const struct codec_item {
91 const vpx_codec_iface_t *(*iface)(void);
92 const vpx_codec_iface_t *(*dx_iface)(void);
95 #if CONFIG_VP8_ENCODER && CONFIG_VP8_DECODER
96 {"vp8", &vpx_codec_vp8_cx, &vpx_codec_vp8_dx, 0x30385056},
97 #elif CONFIG_VP9_ENCODER && !CONFIG_VP9_DECODER
98 {"vp8", &vpx_codec_vp8_cx, NULL, 0x30385056},
100 #if CONFIG_VP9_ENCODER && CONFIG_VP9_DECODER
101 {"vp9", &vpx_codec_vp8_cx, &vpx_codec_vp8_dx, 0x30385056},
102 #elif CONFIG_VP9_ENCODER && !CONFIG_VP9_DECODER
103 {"vp9", &vpx_codec_vp8_cx, NULL, 0x30385056},
107 static void usage_exit();
109 #define LOG_ERROR(label) do \
111 const char *l=label;\
115 fprintf(stderr, "%s: ", l);\
116 vfprintf(stderr, fmt, ap);\
117 fprintf(stderr, "\n");\
121 void die(const char *fmt, ...) {
127 void fatal(const char *fmt, ...) {
133 void warn(const char *fmt, ...) {
134 LOG_ERROR("Warning");
138 static void ctx_exit_on_error(vpx_codec_ctx_t *ctx, const char *s, ...) {
143 const char *detail = vpx_codec_error_detail(ctx);
145 vfprintf(stderr, s, ap);
146 fprintf(stderr, ": %s\n", vpx_codec_error(ctx));
149 fprintf(stderr, " %s\n", detail);
155 /* This structure is used to abstract the different ways of handling
156 * first pass statistics.
166 int stats_open_file(stats_io_t *stats, const char *fpf, int pass) {
172 stats->file = fopen(fpf, "wb");
174 stats->buf.buf = NULL,
175 res = (stats->file != NULL);
179 struct stat stat_buf;
182 fd = open(fpf, O_RDONLY);
183 stats->file = fdopen(fd, "rb");
184 fstat(fd, &stat_buf);
185 stats->buf.sz = stat_buf.st_size;
186 stats->buf.buf = mmap(NULL, stats->buf.sz, PROT_READ, MAP_PRIVATE,
188 res = (stats->buf.buf != NULL);
192 stats->file = fopen(fpf, "rb");
194 if (fseek(stats->file, 0, SEEK_END))
195 fatal("First-pass stats file must be seekable!");
197 stats->buf.sz = stats->buf_alloc_sz = ftell(stats->file);
200 stats->buf.buf = malloc(stats->buf_alloc_sz);
203 fatal("Failed to allocate first-pass stats buffer (%lu bytes)",
204 (unsigned long)stats->buf_alloc_sz);
206 nbytes = fread(stats->buf.buf, 1, stats->buf.sz, stats->file);
207 res = (nbytes == stats->buf.sz);
214 int stats_open_mem(stats_io_t *stats, int pass) {
220 stats->buf_alloc_sz = 64 * 1024;
221 stats->buf.buf = malloc(stats->buf_alloc_sz);
224 stats->buf_ptr = stats->buf.buf;
225 res = (stats->buf.buf != NULL);
230 void stats_close(stats_io_t *stats, int last_pass) {
232 if (stats->pass == last_pass) {
235 munmap(stats->buf.buf, stats->buf.sz);
237 free(stats->buf.buf);
244 if (stats->pass == last_pass)
245 free(stats->buf.buf);
249 void stats_write(stats_io_t *stats, const void *pkt, size_t len) {
251 (void) fwrite(pkt, 1, len, stats->file);
253 if (stats->buf.sz + len > stats->buf_alloc_sz) {
254 size_t new_sz = stats->buf_alloc_sz + 64 * 1024;
255 char *new_ptr = realloc(stats->buf.buf, new_sz);
258 stats->buf_ptr = new_ptr + (stats->buf_ptr - (char *)stats->buf.buf);
259 stats->buf.buf = new_ptr;
260 stats->buf_alloc_sz = new_sz;
262 fatal("Failed to realloc firstpass stats buffer.");
265 memcpy(stats->buf_ptr, pkt, len);
266 stats->buf.sz += len;
267 stats->buf_ptr += len;
271 vpx_fixed_buf_t stats_get(stats_io_t *stats) {
275 /* Stereo 3D packed frame format */
276 typedef enum stereo_format {
277 STEREO_FORMAT_MONO = 0,
278 STEREO_FORMAT_LEFT_RIGHT = 1,
279 STEREO_FORMAT_BOTTOM_TOP = 2,
280 STEREO_FORMAT_TOP_BOTTOM = 3,
281 STEREO_FORMAT_RIGHT_LEFT = 11
284 enum video_file_type {
290 struct detect_buffer {
301 struct detect_buffer detect;
302 enum video_file_type file_type;
305 struct vpx_rational framerate;
310 #define IVF_FRAME_HDR_SZ (4+8) /* 4 byte size + 8 byte timestamp */
311 static int read_frame(struct input_state *input, vpx_image_t *img) {
312 FILE *f = input->file;
313 enum video_file_type file_type = input->file_type;
314 y4m_input *y4m = &input->y4m;
315 struct detect_buffer *detect = &input->detect;
319 if (file_type == FILE_TYPE_Y4M) {
320 if (y4m_input_fetch_frame(y4m, f, img) < 1)
323 if (file_type == FILE_TYPE_IVF) {
324 char junk[IVF_FRAME_HDR_SZ];
326 /* Skip the frame header. We know how big the frame should be. See
327 * write_ivf_frame_header() for documentation on the frame header
330 (void) fread(junk, 1, IVF_FRAME_HDR_SZ, f);
333 for (plane = 0; plane < 3; plane++) {
335 int w = (plane ? (1 + img->d_w) / 2 : img->d_w);
336 int h = (plane ? (1 + img->d_h) / 2 : img->d_h);
339 /* Determine the correct plane based on the image format. The for-loop
340 * always counts in Y,U,V order, but this may not match the order of
345 ptr = img->planes[img->fmt == VPX_IMG_FMT_YV12 ? VPX_PLANE_V : VPX_PLANE_U];
348 ptr = img->planes[img->fmt == VPX_IMG_FMT_YV12 ? VPX_PLANE_U : VPX_PLANE_V];
351 ptr = img->planes[plane];
354 for (r = 0; r < h; r++) {
356 size_t buf_position = 0;
357 const size_t left = detect->buf_read - detect->position;
359 const size_t more = (left < needed) ? left : needed;
360 memcpy(ptr, detect->buf + detect->position, more);
363 detect->position += more;
366 shortread |= (fread(ptr + buf_position, 1, needed, f) < needed);
369 ptr += img->stride[plane];
378 unsigned int file_is_y4m(FILE *infile,
381 if (memcmp(detect, "YUV4", 4) == 0) {
387 #define IVF_FILE_HDR_SZ (32)
388 unsigned int file_is_ivf(struct input_state *input,
389 unsigned int *fourcc) {
390 char raw_hdr[IVF_FILE_HDR_SZ];
392 FILE *infile = input->file;
393 unsigned int *width = &input->w;
394 unsigned int *height = &input->h;
395 struct detect_buffer *detect = &input->detect;
397 if (memcmp(detect->buf, "DKIF", 4) != 0)
400 /* See write_ivf_file_header() for more documentation on the file header
403 if (fread(raw_hdr + 4, 1, IVF_FILE_HDR_SZ - 4, infile)
404 == IVF_FILE_HDR_SZ - 4) {
408 if (mem_get_le16(raw_hdr + 4) != 0)
409 warn("Unrecognized IVF version! This file may not decode "
412 *fourcc = mem_get_le32(raw_hdr + 8);
417 *width = mem_get_le16(raw_hdr + 12);
418 *height = mem_get_le16(raw_hdr + 14);
419 detect->position = 4;
426 static void write_ivf_file_header(FILE *outfile,
427 const vpx_codec_enc_cfg_t *cfg,
432 if (cfg->g_pass != VPX_RC_ONE_PASS && cfg->g_pass != VPX_RC_LAST_PASS)
439 mem_put_le16(header + 4, 0); /* version */
440 mem_put_le16(header + 6, 32); /* headersize */
441 mem_put_le32(header + 8, fourcc); /* headersize */
442 mem_put_le16(header + 12, cfg->g_w); /* width */
443 mem_put_le16(header + 14, cfg->g_h); /* height */
444 mem_put_le32(header + 16, cfg->g_timebase.den); /* rate */
445 mem_put_le32(header + 20, cfg->g_timebase.num); /* scale */
446 mem_put_le32(header + 24, frame_cnt); /* length */
447 mem_put_le32(header + 28, 0); /* unused */
449 (void) fwrite(header, 1, 32, outfile);
453 static void write_ivf_frame_header(FILE *outfile,
454 const vpx_codec_cx_pkt_t *pkt) {
458 if (pkt->kind != VPX_CODEC_CX_FRAME_PKT)
461 pts = pkt->data.frame.pts;
462 mem_put_le32(header, (int)pkt->data.frame.sz);
463 mem_put_le32(header + 4, pts & 0xFFFFFFFF);
464 mem_put_le32(header + 8, pts >> 32);
466 (void) fwrite(header, 1, 12, outfile);
469 static void write_ivf_frame_size(FILE *outfile, size_t size) {
471 mem_put_le32(header, (int)size);
472 (void) fwrite(header, 1, 4, outfile);
476 typedef off_t EbmlLoc;
490 vpx_rational_t framerate;
492 /* These pointers are to the start of an element */
493 off_t position_reference;
495 off_t segment_info_pos;
500 /* This pointer is to a specific element to be serialized */
503 /* These pointers are to the size field of the element */
504 EbmlLoc startSegment;
505 EbmlLoc startCluster;
507 uint32_t cluster_timecode;
510 struct cue_entry *cue_list;
516 void Ebml_Write(EbmlGlobal *glob, const void *buffer_in, unsigned long len) {
517 (void) fwrite(buffer_in, 1, len, glob->stream);
520 #define WRITE_BUFFER(s) \
521 for(i = len-1; i>=0; i--)\
523 x = (char)(*(const s *)buffer_in >> (i * CHAR_BIT)); \
524 Ebml_Write(glob, &x, 1); \
526 void Ebml_Serialize(EbmlGlobal *glob, const void *buffer_in, int buffer_size, unsigned long len) {
536 switch (buffer_size) {
541 WRITE_BUFFER(int16_t)
544 WRITE_BUFFER(int32_t)
547 WRITE_BUFFER(int64_t)
555 /* Need a fixed size serializer for the track ID. libmkv provides a 64 bit
556 * one, but not a 32 bit one.
558 static void Ebml_SerializeUnsigned32(EbmlGlobal *glob, unsigned long class_id, uint64_t ui) {
559 unsigned char sizeSerialized = 4 | 0x80;
560 Ebml_WriteID(glob, class_id);
561 Ebml_Serialize(glob, &sizeSerialized, sizeof(sizeSerialized), 1);
562 Ebml_Serialize(glob, &ui, sizeof(ui), 4);
567 Ebml_StartSubElement(EbmlGlobal *glob, EbmlLoc *ebmlLoc,
568 unsigned long class_id) {
569 /* todo this is always taking 8 bytes, this may need later optimization */
570 /* this is a key that says length unknown */
571 uint64_t unknownLen = LITERALU64(0x01FFFFFF, 0xFFFFFFFF);
573 Ebml_WriteID(glob, class_id);
574 *ebmlLoc = ftello(glob->stream);
575 Ebml_Serialize(glob, &unknownLen, sizeof(unknownLen), 8);
579 Ebml_EndSubElement(EbmlGlobal *glob, EbmlLoc *ebmlLoc) {
583 /* Save the current stream pointer */
584 pos = ftello(glob->stream);
586 /* Calculate the size of this element */
587 size = pos - *ebmlLoc - 8;
588 size |= LITERALU64(0x01000000, 0x00000000);
590 /* Seek back to the beginning of the element and write the new size */
591 fseeko(glob->stream, *ebmlLoc, SEEK_SET);
592 Ebml_Serialize(glob, &size, sizeof(size), 8);
594 /* Reset the stream pointer */
595 fseeko(glob->stream, pos, SEEK_SET);
600 write_webm_seek_element(EbmlGlobal *ebml, unsigned long id, off_t pos) {
601 uint64_t offset = pos - ebml->position_reference;
603 Ebml_StartSubElement(ebml, &start, Seek);
604 Ebml_SerializeBinary(ebml, SeekID, id);
605 Ebml_SerializeUnsigned64(ebml, SeekPosition, offset);
606 Ebml_EndSubElement(ebml, &start);
611 write_webm_seek_info(EbmlGlobal *ebml) {
615 /* Save the current stream pointer */
616 pos = ftello(ebml->stream);
618 if (ebml->seek_info_pos)
619 fseeko(ebml->stream, ebml->seek_info_pos, SEEK_SET);
621 ebml->seek_info_pos = pos;
626 Ebml_StartSubElement(ebml, &start, SeekHead);
627 write_webm_seek_element(ebml, Tracks, ebml->track_pos);
628 write_webm_seek_element(ebml, Cues, ebml->cue_pos);
629 write_webm_seek_element(ebml, Info, ebml->segment_info_pos);
630 Ebml_EndSubElement(ebml, &start);
636 char version_string[64];
638 /* Assemble version string */
640 strcpy(version_string, "vpxenc");
642 strcpy(version_string, "vpxenc ");
643 strncat(version_string,
644 vpx_codec_version_str(),
645 sizeof(version_string) - 1 - strlen(version_string));
648 frame_time = (uint64_t)1000 * ebml->framerate.den
649 / ebml->framerate.num;
650 ebml->segment_info_pos = ftello(ebml->stream);
651 Ebml_StartSubElement(ebml, &startInfo, Info);
652 Ebml_SerializeUnsigned(ebml, TimecodeScale, 1000000);
653 Ebml_SerializeFloat(ebml, Segment_Duration,
654 (double)(ebml->last_pts_ms + frame_time));
655 Ebml_SerializeString(ebml, 0x4D80, version_string);
656 Ebml_SerializeString(ebml, 0x5741, version_string);
657 Ebml_EndSubElement(ebml, &startInfo);
663 write_webm_file_header(EbmlGlobal *glob,
664 const vpx_codec_enc_cfg_t *cfg,
665 const struct vpx_rational *fps,
666 stereo_format_t stereo_fmt) {
669 Ebml_StartSubElement(glob, &start, EBML);
670 Ebml_SerializeUnsigned(glob, EBMLVersion, 1);
671 Ebml_SerializeUnsigned(glob, EBMLReadVersion, 1);
672 Ebml_SerializeUnsigned(glob, EBMLMaxIDLength, 4);
673 Ebml_SerializeUnsigned(glob, EBMLMaxSizeLength, 8);
674 Ebml_SerializeString(glob, DocType, "webm");
675 Ebml_SerializeUnsigned(glob, DocTypeVersion, 2);
676 Ebml_SerializeUnsigned(glob, DocTypeReadVersion, 2);
677 Ebml_EndSubElement(glob, &start);
680 Ebml_StartSubElement(glob, &glob->startSegment, Segment);
681 glob->position_reference = ftello(glob->stream);
682 glob->framerate = *fps;
683 write_webm_seek_info(glob);
687 glob->track_pos = ftello(glob->stream);
688 Ebml_StartSubElement(glob, &trackStart, Tracks);
690 unsigned int trackNumber = 1;
691 uint64_t trackID = 0;
694 Ebml_StartSubElement(glob, &start, TrackEntry);
695 Ebml_SerializeUnsigned(glob, TrackNumber, trackNumber);
696 glob->track_id_pos = ftello(glob->stream);
697 Ebml_SerializeUnsigned32(glob, TrackUID, trackID);
698 Ebml_SerializeUnsigned(glob, TrackType, 1);
699 Ebml_SerializeString(glob, CodecID, "V_VP8");
701 unsigned int pixelWidth = cfg->g_w;
702 unsigned int pixelHeight = cfg->g_h;
703 float frameRate = (float)fps->num / (float)fps->den;
706 Ebml_StartSubElement(glob, &videoStart, Video);
707 Ebml_SerializeUnsigned(glob, PixelWidth, pixelWidth);
708 Ebml_SerializeUnsigned(glob, PixelHeight, pixelHeight);
709 Ebml_SerializeUnsigned(glob, StereoMode, stereo_fmt);
710 Ebml_SerializeFloat(glob, FrameRate, frameRate);
711 Ebml_EndSubElement(glob, &videoStart);
713 Ebml_EndSubElement(glob, &start); /* Track Entry */
715 Ebml_EndSubElement(glob, &trackStart);
717 /* segment element is open */
723 write_webm_block(EbmlGlobal *glob,
724 const vpx_codec_enc_cfg_t *cfg,
725 const vpx_codec_cx_pkt_t *pkt) {
726 unsigned long block_length;
727 unsigned char track_number;
728 unsigned short block_timecode = 0;
731 int start_cluster = 0, is_keyframe;
733 /* Calculate the PTS of this frame in milliseconds */
734 pts_ms = pkt->data.frame.pts * 1000
735 * (uint64_t)cfg->g_timebase.num / (uint64_t)cfg->g_timebase.den;
736 if (pts_ms <= glob->last_pts_ms)
737 pts_ms = glob->last_pts_ms + 1;
738 glob->last_pts_ms = pts_ms;
740 /* Calculate the relative time of this block */
741 if (pts_ms - glob->cluster_timecode > SHRT_MAX)
744 block_timecode = (unsigned short)pts_ms - glob->cluster_timecode;
746 is_keyframe = (pkt->data.frame.flags & VPX_FRAME_IS_KEY);
747 if (start_cluster || is_keyframe) {
748 if (glob->cluster_open)
749 Ebml_EndSubElement(glob, &glob->startCluster);
751 /* Open the new cluster */
753 glob->cluster_open = 1;
754 glob->cluster_timecode = (uint32_t)pts_ms;
755 glob->cluster_pos = ftello(glob->stream);
756 Ebml_StartSubElement(glob, &glob->startCluster, Cluster); /* cluster */
757 Ebml_SerializeUnsigned(glob, Timecode, glob->cluster_timecode);
759 /* Save a cue point if this is a keyframe. */
761 struct cue_entry *cue, *new_cue_list;
763 new_cue_list = realloc(glob->cue_list,
764 (glob->cues + 1) * sizeof(struct cue_entry));
766 glob->cue_list = new_cue_list;
768 fatal("Failed to realloc cue list.");
770 cue = &glob->cue_list[glob->cues];
771 cue->time = glob->cluster_timecode;
772 cue->loc = glob->cluster_pos;
777 /* Write the Simple Block */
778 Ebml_WriteID(glob, SimpleBlock);
780 block_length = (unsigned long)pkt->data.frame.sz + 4;
781 block_length |= 0x10000000;
782 Ebml_Serialize(glob, &block_length, sizeof(block_length), 4);
785 track_number |= 0x80;
786 Ebml_Write(glob, &track_number, 1);
788 Ebml_Serialize(glob, &block_timecode, sizeof(block_timecode), 2);
793 if (pkt->data.frame.flags & VPX_FRAME_IS_INVISIBLE)
795 Ebml_Write(glob, &flags, 1);
797 Ebml_Write(glob, pkt->data.frame.buf, (unsigned long)pkt->data.frame.sz);
802 write_webm_file_footer(EbmlGlobal *glob, long hash) {
804 if (glob->cluster_open)
805 Ebml_EndSubElement(glob, &glob->startCluster);
811 glob->cue_pos = ftello(glob->stream);
812 Ebml_StartSubElement(glob, &start, Cues);
813 for (i = 0; i < glob->cues; i++) {
814 struct cue_entry *cue = &glob->cue_list[i];
817 Ebml_StartSubElement(glob, &start, CuePoint);
821 Ebml_SerializeUnsigned(glob, CueTime, cue->time);
823 Ebml_StartSubElement(glob, &start, CueTrackPositions);
824 Ebml_SerializeUnsigned(glob, CueTrack, 1);
825 Ebml_SerializeUnsigned64(glob, CueClusterPosition,
826 cue->loc - glob->position_reference);
827 Ebml_EndSubElement(glob, &start);
829 Ebml_EndSubElement(glob, &start);
831 Ebml_EndSubElement(glob, &start);
834 Ebml_EndSubElement(glob, &glob->startSegment);
836 /* Patch up the seek info block */
837 write_webm_seek_info(glob);
839 /* Patch up the track id */
840 fseeko(glob->stream, glob->track_id_pos, SEEK_SET);
841 Ebml_SerializeUnsigned32(glob, TrackUID, glob->debug ? 0xDEADBEEF : hash);
843 fseeko(glob->stream, 0, SEEK_END);
847 /* Murmur hash derived from public domain reference implementation at
848 * http:// sites.google.com/site/murmurhash/
850 static unsigned int murmur(const void *key, int len, unsigned int seed) {
851 const unsigned int m = 0x5bd1e995;
854 unsigned int h = seed ^ len;
856 const unsigned char *data = (const unsigned char *)key;
896 static double vp8_mse2psnr(double Samples, double Peak, double Mse) {
899 if ((double)Mse > 0.0)
900 psnr = 10.0 * log10(Peak * Peak * Samples / Mse);
902 psnr = MAX_PSNR; /* Limit to prevent / 0 */
912 static const arg_def_t debugmode = ARG_DEF("D", "debug", 0,
913 "Debug mode (makes output deterministic)");
914 static const arg_def_t outputfile = ARG_DEF("o", "output", 1,
916 static const arg_def_t use_yv12 = ARG_DEF(NULL, "yv12", 0,
917 "Input file is YV12 ");
918 static const arg_def_t use_i420 = ARG_DEF(NULL, "i420", 0,
919 "Input file is I420 (default)");
920 static const arg_def_t codecarg = ARG_DEF(NULL, "codec", 1,
922 static const arg_def_t passes = ARG_DEF("p", "passes", 1,
923 "Number of passes (1/2)");
924 static const arg_def_t pass_arg = ARG_DEF(NULL, "pass", 1,
925 "Pass to execute (1/2)");
926 static const arg_def_t fpf_name = ARG_DEF(NULL, "fpf", 1,
927 "First pass statistics file name");
928 static const arg_def_t limit = ARG_DEF(NULL, "limit", 1,
929 "Stop encoding after n input frames");
930 static const arg_def_t skip = ARG_DEF(NULL, "skip", 1,
931 "Skip the first n input frames");
932 static const arg_def_t deadline = ARG_DEF("d", "deadline", 1,
933 "Deadline per frame (usec)");
934 static const arg_def_t best_dl = ARG_DEF(NULL, "best", 0,
935 "Use Best Quality Deadline");
936 static const arg_def_t good_dl = ARG_DEF(NULL, "good", 0,
937 "Use Good Quality Deadline");
938 static const arg_def_t rt_dl = ARG_DEF(NULL, "rt", 0,
939 "Use Realtime Quality Deadline");
940 static const arg_def_t quietarg = ARG_DEF("q", "quiet", 0,
941 "Do not print encode progress");
942 static const arg_def_t verbosearg = ARG_DEF("v", "verbose", 0,
943 "Show encoder parameters");
944 static const arg_def_t psnrarg = ARG_DEF(NULL, "psnr", 0,
945 "Show PSNR in status line");
946 static const arg_def_t recontest = ARG_DEF(NULL, "test-decode", 0,
947 "Test encode/decode mismatch");
948 static const arg_def_t framerate = ARG_DEF(NULL, "fps", 1,
949 "Stream frame rate (rate/scale)");
950 static const arg_def_t use_ivf = ARG_DEF(NULL, "ivf", 0,
951 "Output IVF (default is WebM)");
952 static const arg_def_t out_part = ARG_DEF("P", "output-partitions", 0,
953 "Makes encoder output partitions. Requires IVF output!");
954 static const arg_def_t q_hist_n = ARG_DEF(NULL, "q-hist", 1,
955 "Show quantizer histogram (n-buckets)");
956 static const arg_def_t rate_hist_n = ARG_DEF(NULL, "rate-hist", 1,
957 "Show rate histogram (n-buckets)");
958 static const arg_def_t *main_args[] = {
960 &outputfile, &codecarg, &passes, &pass_arg, &fpf_name, &limit, &skip,
961 &deadline, &best_dl, &good_dl, &rt_dl,
962 &quietarg, &verbosearg, &psnrarg, &use_ivf, &out_part, &q_hist_n, &rate_hist_n,
966 static const arg_def_t usage = ARG_DEF("u", "usage", 1,
967 "Usage profile number to use");
968 static const arg_def_t threads = ARG_DEF("t", "threads", 1,
969 "Max number of threads to use");
970 static const arg_def_t profile = ARG_DEF(NULL, "profile", 1,
971 "Bitstream profile number to use");
972 static const arg_def_t width = ARG_DEF("w", "width", 1,
974 static const arg_def_t height = ARG_DEF("h", "height", 1,
976 static const struct arg_enum_list stereo_mode_enum[] = {
977 {"mono", STEREO_FORMAT_MONO},
978 {"left-right", STEREO_FORMAT_LEFT_RIGHT},
979 {"bottom-top", STEREO_FORMAT_BOTTOM_TOP},
980 {"top-bottom", STEREO_FORMAT_TOP_BOTTOM},
981 {"right-left", STEREO_FORMAT_RIGHT_LEFT},
984 static const arg_def_t stereo_mode = ARG_DEF_ENUM(NULL, "stereo-mode", 1,
985 "Stereo 3D video format", stereo_mode_enum);
986 static const arg_def_t timebase = ARG_DEF(NULL, "timebase", 1,
987 "Output timestamp precision (fractional seconds)");
988 static const arg_def_t error_resilient = ARG_DEF(NULL, "error-resilient", 1,
989 "Enable error resiliency features");
990 static const arg_def_t lag_in_frames = ARG_DEF(NULL, "lag-in-frames", 1,
991 "Max number of frames to lag");
993 static const arg_def_t *global_args[] = {
994 &use_yv12, &use_i420, &usage, &threads, &profile,
995 &width, &height, &stereo_mode, &timebase, &framerate, &error_resilient,
999 static const arg_def_t dropframe_thresh = ARG_DEF(NULL, "drop-frame", 1,
1000 "Temporal resampling threshold (buf %)");
1001 static const arg_def_t resize_allowed = ARG_DEF(NULL, "resize-allowed", 1,
1002 "Spatial resampling enabled (bool)");
1003 static const arg_def_t resize_up_thresh = ARG_DEF(NULL, "resize-up", 1,
1004 "Upscale threshold (buf %)");
1005 static const arg_def_t resize_down_thresh = ARG_DEF(NULL, "resize-down", 1,
1006 "Downscale threshold (buf %)");
1007 static const struct arg_enum_list end_usage_enum[] = {
1013 static const arg_def_t end_usage = ARG_DEF_ENUM(NULL, "end-usage", 1,
1014 "Rate control mode", end_usage_enum);
1015 static const arg_def_t target_bitrate = ARG_DEF(NULL, "target-bitrate", 1,
1017 static const arg_def_t min_quantizer = ARG_DEF(NULL, "min-q", 1,
1018 "Minimum (best) quantizer");
1019 static const arg_def_t max_quantizer = ARG_DEF(NULL, "max-q", 1,
1020 "Maximum (worst) quantizer");
1021 static const arg_def_t undershoot_pct = ARG_DEF(NULL, "undershoot-pct", 1,
1022 "Datarate undershoot (min) target (%)");
1023 static const arg_def_t overshoot_pct = ARG_DEF(NULL, "overshoot-pct", 1,
1024 "Datarate overshoot (max) target (%)");
1025 static const arg_def_t buf_sz = ARG_DEF(NULL, "buf-sz", 1,
1026 "Client buffer size (ms)");
1027 static const arg_def_t buf_initial_sz = ARG_DEF(NULL, "buf-initial-sz", 1,
1028 "Client initial buffer size (ms)");
1029 static const arg_def_t buf_optimal_sz = ARG_DEF(NULL, "buf-optimal-sz", 1,
1030 "Client optimal buffer size (ms)");
1031 static const arg_def_t *rc_args[] = {
1032 &dropframe_thresh, &resize_allowed, &resize_up_thresh, &resize_down_thresh,
1033 &end_usage, &target_bitrate, &min_quantizer, &max_quantizer,
1034 &undershoot_pct, &overshoot_pct, &buf_sz, &buf_initial_sz, &buf_optimal_sz,
1039 static const arg_def_t bias_pct = ARG_DEF(NULL, "bias-pct", 1,
1040 "CBR/VBR bias (0=CBR, 100=VBR)");
1041 static const arg_def_t minsection_pct = ARG_DEF(NULL, "minsection-pct", 1,
1042 "GOP min bitrate (% of target)");
1043 static const arg_def_t maxsection_pct = ARG_DEF(NULL, "maxsection-pct", 1,
1044 "GOP max bitrate (% of target)");
1045 static const arg_def_t *rc_twopass_args[] = {
1046 &bias_pct, &minsection_pct, &maxsection_pct, NULL
1050 static const arg_def_t kf_min_dist = ARG_DEF(NULL, "kf-min-dist", 1,
1051 "Minimum keyframe interval (frames)");
1052 static const arg_def_t kf_max_dist = ARG_DEF(NULL, "kf-max-dist", 1,
1053 "Maximum keyframe interval (frames)");
1054 static const arg_def_t kf_disabled = ARG_DEF(NULL, "disable-kf", 0,
1055 "Disable keyframe placement");
1056 static const arg_def_t *kf_args[] = {
1057 &kf_min_dist, &kf_max_dist, &kf_disabled, NULL
1061 #if CONFIG_VP8_ENCODER || CONFIG_VP9_ENCODER
1062 static const arg_def_t noise_sens = ARG_DEF(NULL, "noise-sensitivity", 1,
1063 "Noise sensitivity (frames to blur)");
1064 static const arg_def_t sharpness = ARG_DEF(NULL, "sharpness", 1,
1065 "Filter sharpness (0-7)");
1066 static const arg_def_t static_thresh = ARG_DEF(NULL, "static-thresh", 1,
1067 "Motion detection threshold");
1070 #if CONFIG_VP8_ENCODER || CONFIG_VP9_ENCODER
1071 static const arg_def_t cpu_used = ARG_DEF(NULL, "cpu-used", 1,
1072 "CPU Used (-16..16)");
1076 #if CONFIG_VP8_ENCODER || CONFIG_VP9_ENCODER
1077 static const arg_def_t token_parts = ARG_DEF(NULL, "token-parts", 1,
1078 "Number of token partitions to use, log2");
1079 static const arg_def_t auto_altref = ARG_DEF(NULL, "auto-alt-ref", 1,
1080 "Enable automatic alt reference frames");
1081 static const arg_def_t arnr_maxframes = ARG_DEF(NULL, "arnr-maxframes", 1,
1082 "AltRef Max Frames");
1083 static const arg_def_t arnr_strength = ARG_DEF(NULL, "arnr-strength", 1,
1085 static const arg_def_t arnr_type = ARG_DEF(NULL, "arnr-type", 1,
1087 static const struct arg_enum_list tuning_enum[] = {
1088 {"psnr", VP8_TUNE_PSNR},
1089 {"ssim", VP8_TUNE_SSIM},
1092 static const arg_def_t tune_ssim = ARG_DEF_ENUM(NULL, "tune", 1,
1093 "Material to favor", tuning_enum);
1094 static const arg_def_t cq_level = ARG_DEF(NULL, "cq-level", 1,
1095 "Constrained Quality Level");
1096 static const arg_def_t max_intra_rate_pct = ARG_DEF(NULL, "max-intra-rate", 1,
1097 "Max I-frame bitrate (pct)");
1099 static const arg_def_t lossless = ARG_DEF(NULL, "lossless", 1, "Lossless mode");
1102 static const arg_def_t *vp8_args[] = {
1103 &cpu_used, &auto_altref, &noise_sens, &sharpness, &static_thresh,
1104 &token_parts, &arnr_maxframes, &arnr_strength, &arnr_type,
1105 &tune_ssim, &cq_level, &max_intra_rate_pct,
1111 static const int vp8_arg_ctrl_map[] = {
1112 VP8E_SET_CPUUSED, VP8E_SET_ENABLEAUTOALTREF,
1113 VP8E_SET_NOISE_SENSITIVITY, VP8E_SET_SHARPNESS, VP8E_SET_STATIC_THRESHOLD,
1114 VP8E_SET_TOKEN_PARTITIONS,
1115 VP8E_SET_ARNR_MAXFRAMES, VP8E_SET_ARNR_STRENGTH, VP8E_SET_ARNR_TYPE,
1116 VP8E_SET_TUNING, VP8E_SET_CQ_LEVEL, VP8E_SET_MAX_INTRA_BITRATE_PCT,
1124 static const arg_def_t *no_args[] = { NULL };
1126 static void usage_exit() {
1129 fprintf(stderr, "Usage: %s <options> -o dst_filename src_filename \n",
1132 fprintf(stderr, "\nOptions:\n");
1133 arg_show_usage(stdout, main_args);
1134 fprintf(stderr, "\nEncoder Global Options:\n");
1135 arg_show_usage(stdout, global_args);
1136 fprintf(stderr, "\nRate Control Options:\n");
1137 arg_show_usage(stdout, rc_args);
1138 fprintf(stderr, "\nTwopass Rate Control Options:\n");
1139 arg_show_usage(stdout, rc_twopass_args);
1140 fprintf(stderr, "\nKeyframe Placement Options:\n");
1141 arg_show_usage(stdout, kf_args);
1142 #if CONFIG_VP8_ENCODER || CONFIG_VP9_ENCODER
1143 fprintf(stderr, "\nVP8 Specific Options:\n");
1144 arg_show_usage(stdout, vp8_args);
1146 fprintf(stderr, "\nStream timebase (--timebase):\n"
1147 " The desired precision of timestamps in the output, expressed\n"
1148 " in fractional seconds. Default is 1/1000.\n");
1149 fprintf(stderr, "\n"
1150 "Included encoders:\n"
1153 for (i = 0; i < sizeof(codecs) / sizeof(codecs[0]); i++)
1154 fprintf(stderr, " %-6s - %s\n",
1156 vpx_codec_iface_name(codecs[i].iface()));
1162 #define HIST_BAR_MAX 40
1163 struct hist_bucket {
1164 int low, high, count;
1168 static int merge_hist_buckets(struct hist_bucket *bucket,
1171 int small_bucket = 0, merge_bucket = INT_MAX, big_bucket = 0;
1172 int buckets = *buckets_;
1175 /* Find the extrema for this list of buckets */
1176 big_bucket = small_bucket = 0;
1177 for (i = 0; i < buckets; i++) {
1178 if (bucket[i].count < bucket[small_bucket].count)
1180 if (bucket[i].count > bucket[big_bucket].count)
1184 /* If we have too many buckets, merge the smallest with an adjacent
1187 while (buckets > max_buckets) {
1188 int last_bucket = buckets - 1;
1190 /* merge the small bucket with an adjacent one. */
1191 if (small_bucket == 0)
1193 else if (small_bucket == last_bucket)
1194 merge_bucket = last_bucket - 1;
1195 else if (bucket[small_bucket - 1].count < bucket[small_bucket + 1].count)
1196 merge_bucket = small_bucket - 1;
1198 merge_bucket = small_bucket + 1;
1200 assert(abs(merge_bucket - small_bucket) <= 1);
1201 assert(small_bucket < buckets);
1202 assert(big_bucket < buckets);
1203 assert(merge_bucket < buckets);
1205 if (merge_bucket < small_bucket) {
1206 bucket[merge_bucket].high = bucket[small_bucket].high;
1207 bucket[merge_bucket].count += bucket[small_bucket].count;
1209 bucket[small_bucket].high = bucket[merge_bucket].high;
1210 bucket[small_bucket].count += bucket[merge_bucket].count;
1211 merge_bucket = small_bucket;
1214 assert(bucket[merge_bucket].low != bucket[merge_bucket].high);
1218 /* Remove the merge_bucket from the list, and find the new small
1219 * and big buckets while we're at it
1221 big_bucket = small_bucket = 0;
1222 for (i = 0; i < buckets; i++) {
1223 if (i > merge_bucket)
1224 bucket[i] = bucket[i + 1];
1226 if (bucket[i].count < bucket[small_bucket].count)
1228 if (bucket[i].count > bucket[big_bucket].count)
1234 *buckets_ = buckets;
1235 return bucket[big_bucket].count;
1239 static void show_histogram(const struct hist_bucket *bucket,
1243 const char *pat1, *pat2;
1246 switch ((int)(log(bucket[buckets - 1].high) / log(10)) + 1) {
1273 pat1 = "%12d %10s: ";
1274 pat2 = "%12d-%10d: ";
1278 for (i = 0; i < buckets; i++) {
1283 pct = (float)(100.0 * bucket[i].count / total);
1284 len = HIST_BAR_MAX * bucket[i].count / scale;
1287 assert(len <= HIST_BAR_MAX);
1289 if (bucket[i].low == bucket[i].high)
1290 fprintf(stderr, pat1, bucket[i].low, "");
1292 fprintf(stderr, pat2, bucket[i].low, bucket[i].high);
1294 for (j = 0; j < HIST_BAR_MAX; j++)
1295 fprintf(stderr, j < len ? "=" : " ");
1296 fprintf(stderr, "\t%5d (%6.2f%%)\n", bucket[i].count, pct);
1301 static void show_q_histogram(const int counts[64], int max_buckets) {
1302 struct hist_bucket bucket[64];
1309 for (i = 0; i < 64; i++) {
1311 bucket[buckets].low = bucket[buckets].high = i;
1312 bucket[buckets].count = counts[i];
1318 fprintf(stderr, "\nQuantizer Selection:\n");
1319 scale = merge_hist_buckets(bucket, &buckets, max_buckets);
1320 show_histogram(bucket, buckets, total, scale);
1324 #define RATE_BINS (100)
1330 struct hist_bucket bucket[RATE_BINS];
1335 static void init_rate_histogram(struct rate_hist *hist,
1336 const vpx_codec_enc_cfg_t *cfg,
1337 const vpx_rational_t *fps) {
1340 /* Determine the number of samples in the buffer. Use the file's framerate
1341 * to determine the number of frames in rc_buf_sz milliseconds, with an
1342 * adjustment (5/4) to account for alt-refs
1344 hist->samples = cfg->rc_buf_sz * 5 / 4 * fps->num / fps->den / 1000;
1346 /* prevent division by zero */
1347 if (hist->samples == 0)
1350 hist->pts = calloc(hist->samples, sizeof(*hist->pts));
1351 hist->sz = calloc(hist->samples, sizeof(*hist->sz));
1352 for (i = 0; i < RATE_BINS; i++) {
1353 hist->bucket[i].low = INT_MAX;
1354 hist->bucket[i].high = 0;
1355 hist->bucket[i].count = 0;
1360 static void destroy_rate_histogram(struct rate_hist *hist) {
1366 static void update_rate_histogram(struct rate_hist *hist,
1367 const vpx_codec_enc_cfg_t *cfg,
1368 const vpx_codec_cx_pkt_t *pkt) {
1370 int64_t now, then, sum_sz = 0, avg_bitrate;
1372 now = pkt->data.frame.pts * 1000
1373 * (uint64_t)cfg->g_timebase.num / (uint64_t)cfg->g_timebase.den;
1375 idx = hist->frames++ % hist->samples;
1376 hist->pts[idx] = now;
1377 hist->sz[idx] = (int)pkt->data.frame.sz;
1379 if (now < cfg->rc_buf_initial_sz)
1384 /* Sum the size over the past rc_buf_sz ms */
1385 for (i = hist->frames; i > 0 && hist->frames - i < hist->samples; i--) {
1386 int i_idx = (i - 1) % hist->samples;
1388 then = hist->pts[i_idx];
1389 if (now - then > cfg->rc_buf_sz)
1391 sum_sz += hist->sz[i_idx];
1397 avg_bitrate = sum_sz * 8 * 1000 / (now - then);
1398 idx = (int)(avg_bitrate * (RATE_BINS / 2) / (cfg->rc_target_bitrate * 1000));
1401 if (idx > RATE_BINS - 1)
1402 idx = RATE_BINS - 1;
1403 if (hist->bucket[idx].low > avg_bitrate)
1404 hist->bucket[idx].low = (int)avg_bitrate;
1405 if (hist->bucket[idx].high < avg_bitrate)
1406 hist->bucket[idx].high = (int)avg_bitrate;
1407 hist->bucket[idx].count++;
1412 static void show_rate_histogram(struct rate_hist *hist,
1413 const vpx_codec_enc_cfg_t *cfg,
1418 for (i = 0; i < RATE_BINS; i++) {
1419 if (hist->bucket[i].low == INT_MAX)
1421 hist->bucket[buckets++] = hist->bucket[i];
1424 fprintf(stderr, "\nRate (over %dms window):\n", cfg->rc_buf_sz);
1425 scale = merge_hist_buckets(hist->bucket, &buckets, max_buckets);
1426 show_histogram(hist->bucket, buckets, hist->total, scale);
1430 static int compare_img(vpx_image_t *img1, vpx_image_t *img2)
1435 match &= (img1->fmt == img2->fmt);
1436 match &= (img1->w == img2->w);
1437 match &= (img1->h == img2->h);
1439 for (i = 0; i < img1->d_h; i++)
1440 match &= (memcmp(img1->planes[VPX_PLANE_Y]+i*img1->stride[VPX_PLANE_Y],
1441 img2->planes[VPX_PLANE_Y]+i*img2->stride[VPX_PLANE_Y],
1444 for (i = 0; i < img1->d_h/2; i++)
1445 match &= (memcmp(img1->planes[VPX_PLANE_U]+i*img1->stride[VPX_PLANE_U],
1446 img2->planes[VPX_PLANE_U]+i*img2->stride[VPX_PLANE_U],
1447 (img1->d_w + 1) / 2) == 0);
1449 for (i = 0; i < img1->d_h/2; i++)
1450 match &= (memcmp(img1->planes[VPX_PLANE_V]+i*img1->stride[VPX_PLANE_U],
1451 img2->planes[VPX_PLANE_V]+i*img2->stride[VPX_PLANE_U],
1452 (img1->d_w + 1) / 2) == 0);
1458 #define NELEMENTS(x) (sizeof(x)/sizeof(x[0]))
1459 #define ARG_CTRL_CNT_MAX NELEMENTS(vp8_arg_ctrl_map)
1462 /* Configuration elements common to all streams */
1463 struct global_config {
1464 const struct codec_item *codec;
1477 struct vpx_rational framerate;
1480 int show_q_hist_buckets;
1481 int show_rate_hist_buckets;
1485 /* Per-stream configuration */
1486 struct stream_config {
1487 struct vpx_codec_enc_cfg cfg;
1489 const char *stats_fn;
1490 stereo_format_t stereo_fmt;
1491 int arg_ctrls[ARG_CTRL_CNT_MAX][2];
1494 int have_kf_max_dist;
1498 struct stream_state {
1500 struct stream_state *next;
1501 struct stream_config config;
1503 struct rate_hist rate_hist;
1506 uint64_t psnr_sse_total;
1507 uint64_t psnr_samples_total;
1508 double psnr_totals[4];
1511 vpx_codec_ctx_t encoder;
1512 unsigned int frames_out;
1516 vpx_codec_ctx_t decoder;
1517 vpx_ref_frame_t ref_enc;
1518 vpx_ref_frame_t ref_dec;
1523 void validate_positive_rational(const char *msg,
1524 struct vpx_rational *rat) {
1531 die("Error: %s must be positive\n", msg);
1534 die("Error: %s has zero denominator\n", msg);
1538 static void parse_global_config(struct global_config *global, char **argv) {
1539 char **argi, **argj;
1542 /* Initialize default parameters */
1543 memset(global, 0, sizeof(*global));
1544 global->codec = codecs;
1546 global->use_i420 = 1;
1548 for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step) {
1551 if (arg_match(&arg, &codecarg, argi)) {
1554 for (j = 0; j < sizeof(codecs) / sizeof(codecs[0]); j++)
1555 if (!strcmp(codecs[j].name, arg.val))
1559 global->codec = codecs + k;
1561 die("Error: Unrecognized argument (%s) to --codec\n",
1564 } else if (arg_match(&arg, &passes, argi)) {
1565 global->passes = arg_parse_uint(&arg);
1567 if (global->passes < 1 || global->passes > 2)
1568 die("Error: Invalid number of passes (%d)\n", global->passes);
1569 } else if (arg_match(&arg, &pass_arg, argi)) {
1570 global->pass = arg_parse_uint(&arg);
1572 if (global->pass < 1 || global->pass > 2)
1573 die("Error: Invalid pass selected (%d)\n",
1575 } else if (arg_match(&arg, &usage, argi))
1576 global->usage = arg_parse_uint(&arg);
1577 else if (arg_match(&arg, &deadline, argi))
1578 global->deadline = arg_parse_uint(&arg);
1579 else if (arg_match(&arg, &best_dl, argi))
1580 global->deadline = VPX_DL_BEST_QUALITY;
1581 else if (arg_match(&arg, &good_dl, argi))
1582 global->deadline = VPX_DL_GOOD_QUALITY;
1583 else if (arg_match(&arg, &rt_dl, argi))
1584 global->deadline = VPX_DL_REALTIME;
1585 else if (arg_match(&arg, &use_yv12, argi))
1586 global->use_i420 = 0;
1587 else if (arg_match(&arg, &use_i420, argi))
1588 global->use_i420 = 1;
1589 else if (arg_match(&arg, &quietarg, argi))
1591 else if (arg_match(&arg, &verbosearg, argi))
1592 global->verbose = 1;
1593 else if (arg_match(&arg, &limit, argi))
1594 global->limit = arg_parse_uint(&arg);
1595 else if (arg_match(&arg, &skip, argi))
1596 global->skip_frames = arg_parse_uint(&arg);
1597 else if (arg_match(&arg, &psnrarg, argi))
1598 global->show_psnr = 1;
1599 else if (arg_match(&arg, &recontest, argi))
1600 global->test_decode = 1;
1601 else if (arg_match(&arg, &framerate, argi)) {
1602 global->framerate = arg_parse_rational(&arg);
1603 validate_positive_rational(arg.name, &global->framerate);
1604 global->have_framerate = 1;
1605 } else if (arg_match(&arg, &out_part, argi))
1606 global->out_part = 1;
1607 else if (arg_match(&arg, &debugmode, argi))
1609 else if (arg_match(&arg, &q_hist_n, argi))
1610 global->show_q_hist_buckets = arg_parse_uint(&arg);
1611 else if (arg_match(&arg, &rate_hist_n, argi))
1612 global->show_rate_hist_buckets = arg_parse_uint(&arg);
1617 /* Validate global config */
1620 /* DWIM: Assume the user meant passes=2 if pass=2 is specified */
1621 if (global->pass > global->passes) {
1622 warn("Assuming --pass=%d implies --passes=%d\n",
1623 global->pass, global->pass);
1624 global->passes = global->pass;
1630 void open_input_file(struct input_state *input) {
1631 unsigned int fourcc;
1633 /* Parse certain options from the input file, if possible */
1634 input->file = strcmp(input->fn, "-") ? fopen(input->fn, "rb")
1635 : set_binary_mode(stdin);
1638 fatal("Failed to open input file");
1640 /* For RAW input sources, these bytes will applied on the first frame
1643 input->detect.buf_read = fread(input->detect.buf, 1, 4, input->file);
1644 input->detect.position = 0;
1646 if (input->detect.buf_read == 4
1647 && file_is_y4m(input->file, &input->y4m, input->detect.buf)) {
1648 if (y4m_input_open(&input->y4m, input->file, input->detect.buf, 4) >= 0) {
1649 input->file_type = FILE_TYPE_Y4M;
1650 input->w = input->y4m.pic_w;
1651 input->h = input->y4m.pic_h;
1652 input->framerate.num = input->y4m.fps_n;
1653 input->framerate.den = input->y4m.fps_d;
1654 input->use_i420 = 0;
1656 fatal("Unsupported Y4M stream.");
1657 } else if (input->detect.buf_read == 4 && file_is_ivf(input, &fourcc)) {
1658 input->file_type = FILE_TYPE_IVF;
1661 input->use_i420 = 0;
1664 input->use_i420 = 1;
1667 fatal("Unsupported fourcc (%08x) in IVF", fourcc);
1670 input->file_type = FILE_TYPE_RAW;
1675 static void close_input_file(struct input_state *input) {
1676 fclose(input->file);
1677 if (input->file_type == FILE_TYPE_Y4M)
1678 y4m_input_close(&input->y4m);
1681 static struct stream_state *new_stream(struct global_config *global,
1682 struct stream_state *prev) {
1683 struct stream_state *stream;
1685 stream = calloc(1, sizeof(*stream));
1687 fatal("Failed to allocate new stream.");
1689 memcpy(stream, prev, sizeof(*stream));
1691 prev->next = stream;
1693 vpx_codec_err_t res;
1695 /* Populate encoder configuration */
1696 res = vpx_codec_enc_config_default(global->codec->iface(),
1697 &stream->config.cfg,
1700 fatal("Failed to get config: %s\n", vpx_codec_err_to_string(res));
1702 /* Change the default timebase to a high enough value so that the
1703 * encoder will always create strictly increasing timestamps.
1705 stream->config.cfg.g_timebase.den = 1000;
1707 /* Never use the library's default resolution, require it be parsed
1708 * from the file or set on the command line.
1710 stream->config.cfg.g_w = 0;
1711 stream->config.cfg.g_h = 0;
1713 /* Initialize remaining stream parameters */
1714 stream->config.stereo_fmt = STEREO_FORMAT_MONO;
1715 stream->config.write_webm = 1;
1716 stream->ebml.last_pts_ms = -1;
1718 /* Allows removal of the application version from the EBML tags */
1719 stream->ebml.debug = global->debug;
1722 /* Output files must be specified for each stream */
1723 stream->config.out_fn = NULL;
1725 stream->next = NULL;
1730 static int parse_stream_params(struct global_config *global,
1731 struct stream_state *stream,
1733 char **argi, **argj;
1735 static const arg_def_t **ctrl_args = no_args;
1736 static const int *ctrl_args_map = NULL;
1737 struct stream_config *config = &stream->config;
1738 int eos_mark_found = 0;
1740 /* Handle codec specific options */
1741 if (global->codec->iface == vpx_codec_vp8_cx) {
1742 ctrl_args = vp8_args;
1743 ctrl_args_map = vp8_arg_ctrl_map;
1746 for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step) {
1749 /* Once we've found an end-of-stream marker (--) we want to continue
1750 * shifting arguments but not consuming them.
1752 if (eos_mark_found) {
1755 } else if (!strcmp(*argj, "--")) {
1761 else if (arg_match(&arg, &outputfile, argi))
1762 config->out_fn = arg.val;
1763 else if (arg_match(&arg, &fpf_name, argi))
1764 config->stats_fn = arg.val;
1765 else if (arg_match(&arg, &use_ivf, argi))
1766 config->write_webm = 0;
1767 else if (arg_match(&arg, &threads, argi))
1768 config->cfg.g_threads = arg_parse_uint(&arg);
1769 else if (arg_match(&arg, &profile, argi))
1770 config->cfg.g_profile = arg_parse_uint(&arg);
1771 else if (arg_match(&arg, &width, argi))
1772 config->cfg.g_w = arg_parse_uint(&arg);
1773 else if (arg_match(&arg, &height, argi))
1774 config->cfg.g_h = arg_parse_uint(&arg);
1775 else if (arg_match(&arg, &stereo_mode, argi))
1776 config->stereo_fmt = arg_parse_enum_or_int(&arg);
1777 else if (arg_match(&arg, &timebase, argi)) {
1778 config->cfg.g_timebase = arg_parse_rational(&arg);
1779 validate_positive_rational(arg.name, &config->cfg.g_timebase);
1780 } else if (arg_match(&arg, &error_resilient, argi))
1781 config->cfg.g_error_resilient = arg_parse_uint(&arg);
1782 else if (arg_match(&arg, &lag_in_frames, argi))
1783 config->cfg.g_lag_in_frames = arg_parse_uint(&arg);
1784 else if (arg_match(&arg, &dropframe_thresh, argi))
1785 config->cfg.rc_dropframe_thresh = arg_parse_uint(&arg);
1786 else if (arg_match(&arg, &resize_allowed, argi))
1787 config->cfg.rc_resize_allowed = arg_parse_uint(&arg);
1788 else if (arg_match(&arg, &resize_up_thresh, argi))
1789 config->cfg.rc_resize_up_thresh = arg_parse_uint(&arg);
1790 else if (arg_match(&arg, &resize_down_thresh, argi))
1791 config->cfg.rc_resize_down_thresh = arg_parse_uint(&arg);
1792 else if (arg_match(&arg, &end_usage, argi))
1793 config->cfg.rc_end_usage = arg_parse_enum_or_int(&arg);
1794 else if (arg_match(&arg, &target_bitrate, argi))
1795 config->cfg.rc_target_bitrate = arg_parse_uint(&arg);
1796 else if (arg_match(&arg, &min_quantizer, argi))
1797 config->cfg.rc_min_quantizer = arg_parse_uint(&arg);
1798 else if (arg_match(&arg, &max_quantizer, argi))
1799 config->cfg.rc_max_quantizer = arg_parse_uint(&arg);
1800 else if (arg_match(&arg, &undershoot_pct, argi))
1801 config->cfg.rc_undershoot_pct = arg_parse_uint(&arg);
1802 else if (arg_match(&arg, &overshoot_pct, argi))
1803 config->cfg.rc_overshoot_pct = arg_parse_uint(&arg);
1804 else if (arg_match(&arg, &buf_sz, argi))
1805 config->cfg.rc_buf_sz = arg_parse_uint(&arg);
1806 else if (arg_match(&arg, &buf_initial_sz, argi))
1807 config->cfg.rc_buf_initial_sz = arg_parse_uint(&arg);
1808 else if (arg_match(&arg, &buf_optimal_sz, argi))
1809 config->cfg.rc_buf_optimal_sz = arg_parse_uint(&arg);
1810 else if (arg_match(&arg, &bias_pct, argi)) {
1811 config->cfg.rc_2pass_vbr_bias_pct = arg_parse_uint(&arg);
1813 if (global->passes < 2)
1814 warn("option %s ignored in one-pass mode.\n", arg.name);
1815 } else if (arg_match(&arg, &minsection_pct, argi)) {
1816 config->cfg.rc_2pass_vbr_minsection_pct = arg_parse_uint(&arg);
1818 if (global->passes < 2)
1819 warn("option %s ignored in one-pass mode.\n", arg.name);
1820 } else if (arg_match(&arg, &maxsection_pct, argi)) {
1821 config->cfg.rc_2pass_vbr_maxsection_pct = arg_parse_uint(&arg);
1823 if (global->passes < 2)
1824 warn("option %s ignored in one-pass mode.\n", arg.name);
1825 } else if (arg_match(&arg, &kf_min_dist, argi))
1826 config->cfg.kf_min_dist = arg_parse_uint(&arg);
1827 else if (arg_match(&arg, &kf_max_dist, argi)) {
1828 config->cfg.kf_max_dist = arg_parse_uint(&arg);
1829 config->have_kf_max_dist = 1;
1830 } else if (arg_match(&arg, &kf_disabled, argi))
1831 config->cfg.kf_mode = VPX_KF_DISABLED;
1835 for (i = 0; ctrl_args[i]; i++) {
1836 if (arg_match(&arg, ctrl_args[i], argi)) {
1840 /* Point either to the next free element or the first
1841 * instance of this control.
1843 for (j = 0; j < config->arg_ctrl_cnt; j++)
1844 if (config->arg_ctrls[j][0] == ctrl_args_map[i])
1848 assert(j < ARG_CTRL_CNT_MAX);
1849 if (j < ARG_CTRL_CNT_MAX) {
1850 config->arg_ctrls[j][0] = ctrl_args_map[i];
1851 config->arg_ctrls[j][1] = arg_parse_enum_or_int(&arg);
1852 if (j == config->arg_ctrl_cnt)
1853 config->arg_ctrl_cnt++;
1864 return eos_mark_found;
1868 #define FOREACH_STREAM(func)\
1871 struct stream_state *stream;\
1873 for(stream = streams; stream; stream = stream->next)\
1878 static void validate_stream_config(struct stream_state *stream) {
1879 struct stream_state *streami;
1881 if (!stream->config.cfg.g_w || !stream->config.cfg.g_h)
1882 fatal("Stream %d: Specify stream dimensions with --width (-w) "
1883 " and --height (-h)", stream->index);
1885 for (streami = stream; streami; streami = streami->next) {
1886 /* All streams require output files */
1887 if (!streami->config.out_fn)
1888 fatal("Stream %d: Output file is required (specify with -o)",
1891 /* Check for two streams outputting to the same file */
1892 if (streami != stream) {
1893 const char *a = stream->config.out_fn;
1894 const char *b = streami->config.out_fn;
1895 if (!strcmp(a, b) && strcmp(a, "/dev/null") && strcmp(a, ":nul"))
1896 fatal("Stream %d: duplicate output file (from stream %d)",
1897 streami->index, stream->index);
1900 /* Check for two streams sharing a stats file. */
1901 if (streami != stream) {
1902 const char *a = stream->config.stats_fn;
1903 const char *b = streami->config.stats_fn;
1904 if (a && b && !strcmp(a, b))
1905 fatal("Stream %d: duplicate stats file (from stream %d)",
1906 streami->index, stream->index);
1912 static void set_stream_dimensions(struct stream_state *stream,
1915 if ((stream->config.cfg.g_w && stream->config.cfg.g_w != w)
1916 || (stream->config.cfg.g_h && stream->config.cfg.g_h != h))
1917 fatal("Stream %d: Resizing not yet supported", stream->index);
1918 stream->config.cfg.g_w = w;
1919 stream->config.cfg.g_h = h;
1923 static void set_default_kf_interval(struct stream_state *stream,
1924 struct global_config *global) {
1925 /* Use a max keyframe interval of 5 seconds, if none was
1926 * specified on the command line.
1928 if (!stream->config.have_kf_max_dist) {
1929 double framerate = (double)global->framerate.num / global->framerate.den;
1930 if (framerate > 0.0)
1931 stream->config.cfg.kf_max_dist = (unsigned int)(5.0 * framerate);
1936 static void show_stream_config(struct stream_state *stream,
1937 struct global_config *global,
1938 struct input_state *input) {
1940 #define SHOW(field) \
1941 fprintf(stderr, " %-28s = %d\n", #field, stream->config.cfg.field)
1943 if (stream->index == 0) {
1944 fprintf(stderr, "Codec: %s\n",
1945 vpx_codec_iface_name(global->codec->iface()));
1946 fprintf(stderr, "Source file: %s Format: %s\n", input->fn,
1947 input->use_i420 ? "I420" : "YV12");
1949 if (stream->next || stream->index)
1950 fprintf(stderr, "\nStream Index: %d\n", stream->index);
1951 fprintf(stderr, "Destination file: %s\n", stream->config.out_fn);
1952 fprintf(stderr, "Encoder parameters:\n");
1959 SHOW(g_timebase.num);
1960 SHOW(g_timebase.den);
1961 SHOW(g_error_resilient);
1963 SHOW(g_lag_in_frames);
1964 SHOW(rc_dropframe_thresh);
1965 SHOW(rc_resize_allowed);
1966 SHOW(rc_resize_up_thresh);
1967 SHOW(rc_resize_down_thresh);
1969 SHOW(rc_target_bitrate);
1970 SHOW(rc_min_quantizer);
1971 SHOW(rc_max_quantizer);
1972 SHOW(rc_undershoot_pct);
1973 SHOW(rc_overshoot_pct);
1975 SHOW(rc_buf_initial_sz);
1976 SHOW(rc_buf_optimal_sz);
1977 SHOW(rc_2pass_vbr_bias_pct);
1978 SHOW(rc_2pass_vbr_minsection_pct);
1979 SHOW(rc_2pass_vbr_maxsection_pct);
1986 static void open_output_file(struct stream_state *stream,
1987 struct global_config *global) {
1988 const char *fn = stream->config.out_fn;
1990 stream->file = strcmp(fn, "-") ? fopen(fn, "wb") : set_binary_mode(stdout);
1993 fatal("Failed to open output file");
1995 if (stream->config.write_webm && fseek(stream->file, 0, SEEK_CUR))
1996 fatal("WebM output to pipes not supported.");
1998 if (stream->config.write_webm) {
1999 stream->ebml.stream = stream->file;
2000 write_webm_file_header(&stream->ebml, &stream->config.cfg,
2002 stream->config.stereo_fmt);
2004 write_ivf_file_header(stream->file, &stream->config.cfg,
2005 global->codec->fourcc, 0);
2009 static void close_output_file(struct stream_state *stream,
2010 unsigned int fourcc) {
2011 if (stream->config.write_webm) {
2012 write_webm_file_footer(&stream->ebml, stream->hash);
2013 free(stream->ebml.cue_list);
2014 stream->ebml.cue_list = NULL;
2016 if (!fseek(stream->file, 0, SEEK_SET))
2017 write_ivf_file_header(stream->file, &stream->config.cfg,
2019 stream->frames_out);
2022 fclose(stream->file);
2026 static void setup_pass(struct stream_state *stream,
2027 struct global_config *global,
2029 if (stream->config.stats_fn) {
2030 if (!stats_open_file(&stream->stats, stream->config.stats_fn,
2032 fatal("Failed to open statistics store");
2034 if (!stats_open_mem(&stream->stats, pass))
2035 fatal("Failed to open statistics store");
2038 stream->config.cfg.g_pass = global->passes == 2
2039 ? pass ? VPX_RC_LAST_PASS : VPX_RC_FIRST_PASS
2042 stream->config.cfg.rc_twopass_stats_in = stats_get(&stream->stats);
2044 stream->cx_time = 0;
2046 stream->frames_out = 0;
2050 static void initialize_encoder(struct stream_state *stream,
2051 struct global_config *global) {
2055 flags |= global->show_psnr ? VPX_CODEC_USE_PSNR : 0;
2056 flags |= global->out_part ? VPX_CODEC_USE_OUTPUT_PARTITION : 0;
2058 /* Construct Encoder Context */
2059 vpx_codec_enc_init(&stream->encoder, global->codec->iface(),
2060 &stream->config.cfg, flags);
2061 ctx_exit_on_error(&stream->encoder, "Failed to initialize encoder");
2063 /* Note that we bypass the vpx_codec_control wrapper macro because
2064 * we're being clever to store the control IDs in an array. Real
2065 * applications will want to make use of the enumerations directly
2067 for (i = 0; i < stream->config.arg_ctrl_cnt; i++) {
2068 int ctrl = stream->config.arg_ctrls[i][0];
2069 int value = stream->config.arg_ctrls[i][1];
2070 if (vpx_codec_control_(&stream->encoder, ctrl, value))
2071 fprintf(stderr, "Error: Tried to set control %d = %d\n",
2074 ctx_exit_on_error(&stream->encoder, "Failed to control codec");
2077 if (global->test_decode) {
2080 vpx_codec_dec_init(&stream->decoder, global->codec->dx_iface(), NULL, 0);
2082 width = (stream->config.cfg.g_w + 15) & ~15;
2083 height = (stream->config.cfg.g_h + 15) & ~15;
2084 vpx_img_alloc(&stream->ref_enc.img, VPX_IMG_FMT_I420, width, height, 1);
2085 vpx_img_alloc(&stream->ref_dec.img, VPX_IMG_FMT_I420, width, height, 1);
2086 stream->ref_enc.frame_type = VP8_LAST_FRAME;
2087 stream->ref_dec.frame_type = VP8_LAST_FRAME;
2092 static void encode_frame(struct stream_state *stream,
2093 struct global_config *global,
2094 struct vpx_image *img,
2095 unsigned int frames_in) {
2096 vpx_codec_pts_t frame_start, next_frame_start;
2097 struct vpx_codec_enc_cfg *cfg = &stream->config.cfg;
2098 struct vpx_usec_timer timer;
2100 frame_start = (cfg->g_timebase.den * (int64_t)(frames_in - 1)
2101 * global->framerate.den)
2102 / cfg->g_timebase.num / global->framerate.num;
2103 next_frame_start = (cfg->g_timebase.den * (int64_t)(frames_in)
2104 * global->framerate.den)
2105 / cfg->g_timebase.num / global->framerate.num;
2106 vpx_usec_timer_start(&timer);
2107 vpx_codec_encode(&stream->encoder, img, frame_start,
2108 (unsigned long)(next_frame_start - frame_start),
2109 0, global->deadline);
2110 vpx_usec_timer_mark(&timer);
2111 stream->cx_time += vpx_usec_timer_elapsed(&timer);
2112 ctx_exit_on_error(&stream->encoder, "Stream %d: Failed to encode frame",
2117 static void update_quantizer_histogram(struct stream_state *stream) {
2118 if (stream->config.cfg.g_pass != VPX_RC_FIRST_PASS) {
2121 vpx_codec_control(&stream->encoder, VP8E_GET_LAST_QUANTIZER_64, &q);
2122 ctx_exit_on_error(&stream->encoder, "Failed to read quantizer");
2123 stream->counts[q]++;
2128 static void get_cx_data(struct stream_state *stream,
2129 struct global_config *global,
2131 const vpx_codec_cx_pkt_t *pkt;
2132 const struct vpx_codec_enc_cfg *cfg = &stream->config.cfg;
2133 vpx_codec_iter_t iter = NULL;
2135 while ((pkt = vpx_codec_get_cx_data(&stream->encoder, &iter))) {
2136 static size_t fsize = 0;
2137 static off_t ivf_header_pos = 0;
2141 switch (pkt->kind) {
2142 case VPX_CODEC_CX_FRAME_PKT:
2143 if (!(pkt->data.frame.flags & VPX_FRAME_IS_FRAGMENT)) {
2144 stream->frames_out++;
2147 fprintf(stderr, " %6luF",
2148 (unsigned long)pkt->data.frame.sz);
2150 update_rate_histogram(&stream->rate_hist, cfg, pkt);
2151 if (stream->config.write_webm) {
2152 /* Update the hash */
2153 if (!stream->ebml.debug)
2154 stream->hash = murmur(pkt->data.frame.buf,
2155 (int)pkt->data.frame.sz,
2158 write_webm_block(&stream->ebml, cfg, pkt);
2160 if (pkt->data.frame.partition_id <= 0) {
2161 ivf_header_pos = ftello(stream->file);
2162 fsize = pkt->data.frame.sz;
2164 write_ivf_frame_header(stream->file, pkt);
2166 fsize += pkt->data.frame.sz;
2168 if (!(pkt->data.frame.flags & VPX_FRAME_IS_FRAGMENT)) {
2169 off_t currpos = ftello(stream->file);
2170 fseeko(stream->file, ivf_header_pos, SEEK_SET);
2171 write_ivf_frame_size(stream->file, fsize);
2172 fseeko(stream->file, currpos, SEEK_SET);
2176 (void) fwrite(pkt->data.frame.buf, 1, pkt->data.frame.sz,
2179 stream->nbytes += pkt->data.raw.sz;
2181 if (global->test_decode) {
2182 vpx_codec_decode(&stream->decoder, pkt->data.frame.buf,
2183 pkt->data.frame.sz, NULL, 0);
2184 ctx_exit_on_error(&stream->decoder, "Failed to decode frame");
2187 case VPX_CODEC_STATS_PKT:
2188 stream->frames_out++;
2189 fprintf(stderr, " %6luS",
2190 (unsigned long)pkt->data.twopass_stats.sz);
2191 stats_write(&stream->stats,
2192 pkt->data.twopass_stats.buf,
2193 pkt->data.twopass_stats.sz);
2194 stream->nbytes += pkt->data.raw.sz;
2196 case VPX_CODEC_PSNR_PKT:
2198 if (global->show_psnr) {
2201 stream->psnr_sse_total += pkt->data.psnr.sse[0];
2202 stream->psnr_samples_total += pkt->data.psnr.samples[0];
2203 for (i = 0; i < 4; i++) {
2205 fprintf(stderr, "%.3f ", pkt->data.psnr.psnr[i]);
2206 stream->psnr_totals[i] += pkt->data.psnr.psnr[i];
2208 stream->psnr_count++;
2219 static void show_psnr(struct stream_state *stream) {
2223 if (!stream->psnr_count)
2226 fprintf(stderr, "Stream %d PSNR (Overall/Avg/Y/U/V)", stream->index);
2227 ovpsnr = vp8_mse2psnr((double)stream->psnr_samples_total, 255.0,
2228 (double)stream->psnr_sse_total);
2229 fprintf(stderr, " %.3f", ovpsnr);
2231 for (i = 0; i < 4; i++) {
2232 fprintf(stderr, " %.3f", stream->psnr_totals[i] / stream->psnr_count);
2234 fprintf(stderr, "\n");
2238 float usec_to_fps(uint64_t usec, unsigned int frames) {
2239 return (float)(usec > 0 ? frames * 1000000.0 / (float)usec : 0);
2243 static void test_decode(struct stream_state *stream, unsigned int frames_in) {
2244 vpx_codec_control(&stream->encoder, VP8_COPY_REFERENCE, &stream->ref_enc);
2245 ctx_exit_on_error(&stream->encoder, "Failed to get encoder reference frame");
2246 vpx_codec_control(&stream->decoder, VP8_COPY_REFERENCE, &stream->ref_dec);
2247 ctx_exit_on_error(&stream->decoder, "Failed to get decoder reference frame");
2249 if (!stream->mismatch_seen
2250 && !compare_img(&stream->ref_enc.img, &stream->ref_dec.img)) {
2251 /* TODO(jkoleszar): make fatal. */
2252 warn("Stream %d: Encode/decode mismatch on frame %d",
2253 stream->index, frames_in);
2254 stream->mismatch_seen = frames_in;
2258 int main(int argc, const char **argv_) {
2261 int frame_avail, got_data;
2263 struct input_state input = {0};
2264 struct global_config global;
2265 struct stream_state *streams = NULL;
2266 char **argv, **argi;
2267 unsigned long cx_time = 0;
2270 exec_name = argv_[0];
2275 /* Setup default input stream settings */
2276 input.framerate.num = 30;
2277 input.framerate.den = 1;
2280 /* First parse the global configuration values, because we want to apply
2281 * other parameters on top of the default configuration provided by the
2284 argv = argv_dup(argc - 1, argv_ + 1);
2285 parse_global_config(&global, argv);
2288 /* Now parse each stream's parameters. Using a local scope here
2289 * due to the use of 'stream' as loop variable in FOREACH_STREAM
2292 struct stream_state *stream = NULL;
2295 stream = new_stream(&global, stream);
2299 } while (parse_stream_params(&global, stream, argv));
2302 /* Check for unrecognized options */
2303 for (argi = argv; *argi; argi++)
2304 if (argi[0][0] == '-' && argi[0][1])
2305 die("Error: Unrecognized option %s\n", *argi);
2307 /* Handle non-option arguments */
2313 for (pass = global.pass ? global.pass - 1 : 0; pass < global.passes; pass++) {
2316 open_input_file(&input);
2318 /* If the input file doesn't specify its w/h (raw files), try to get
2319 * the data from the first stream's configuration.
2321 if (!input.w || !input.h)
2323 if (stream->config.cfg.g_w && stream->config.cfg.g_h) {
2324 input.w = stream->config.cfg.g_w;
2325 input.h = stream->config.cfg.g_h;
2330 /* Update stream configurations from the input file's parameters */
2331 FOREACH_STREAM(set_stream_dimensions(stream, input.w, input.h));
2332 FOREACH_STREAM(validate_stream_config(stream));
2334 /* Ensure that --passes and --pass are consistent. If --pass is set and
2335 * --passes=2, ensure --fpf was set.
2337 if (global.pass && global.passes == 2)
2339 if (!stream->config.stats_fn)
2340 die("Stream %d: Must specify --fpf when --pass=%d"
2341 " and --passes=2\n", stream->index, global.pass);
2345 /* Use the frame rate from the file only if none was specified
2346 * on the command-line.
2348 if (!global.have_framerate)
2349 global.framerate = input.framerate;
2351 FOREACH_STREAM(set_default_kf_interval(stream, &global));
2353 /* Show configuration */
2354 if (global.verbose && pass == 0)
2355 FOREACH_STREAM(show_stream_config(stream, &global, &input));
2357 if (pass == (global.pass ? global.pass - 1 : 0)) {
2358 if (input.file_type == FILE_TYPE_Y4M)
2359 /*The Y4M reader does its own allocation.
2360 Just initialize this here to avoid problems if we never read any
2362 memset(&raw, 0, sizeof(raw));
2365 input.use_i420 ? VPX_IMG_FMT_I420
2367 input.w, input.h, 32);
2369 FOREACH_STREAM(init_rate_histogram(&stream->rate_hist,
2370 &stream->config.cfg,
2371 &global.framerate));
2374 FOREACH_STREAM(open_output_file(stream, &global));
2375 FOREACH_STREAM(setup_pass(stream, &global, pass));
2376 FOREACH_STREAM(initialize_encoder(stream, &global));
2381 while (frame_avail || got_data) {
2382 struct vpx_usec_timer timer;
2384 if (!global.limit || frames_in < global.limit) {
2385 frame_avail = read_frame(&input, &raw);
2390 if (!global.quiet) {
2391 if (stream_cnt == 1)
2393 "\rPass %d/%d frame %4d/%-4d %7"PRId64"B \033[K",
2394 pass + 1, global.passes, frames_in,
2395 streams->frames_out, (int64_t)streams->nbytes);
2398 "\rPass %d/%d frame %4d %7lu %s (%.2f fps)\033[K",
2399 pass + 1, global.passes, frames_in,
2400 cx_time > 9999999 ? cx_time / 1000 : cx_time,
2401 cx_time > 9999999 ? "ms" : "us",
2402 usec_to_fps(cx_time, frames_in));
2408 if (frames_in > global.skip_frames) {
2409 vpx_usec_timer_start(&timer);
2410 FOREACH_STREAM(encode_frame(stream, &global,
2411 frame_avail ? &raw : NULL,
2413 vpx_usec_timer_mark(&timer);
2414 cx_time += (unsigned long)vpx_usec_timer_elapsed(&timer);
2416 FOREACH_STREAM(update_quantizer_histogram(stream));
2419 FOREACH_STREAM(get_cx_data(stream, &global, &got_data));
2421 if (global.test_decode)
2422 FOREACH_STREAM(test_decode(stream, frames_in));
2429 fprintf(stderr, "\n");
2432 FOREACH_STREAM(fprintf(
2434 "\rPass %d/%d frame %4d/%-4d %7"PRId64"B %7lub/f %7"PRId64"b/s"
2435 " %7"PRId64" %s (%.2f fps)\033[K\n", pass + 1,
2436 global.passes, frames_in, stream->frames_out, (int64_t)stream->nbytes,
2437 frames_in ? (unsigned long)(stream->nbytes * 8 / frames_in) : 0,
2438 frames_in ? (int64_t)stream->nbytes * 8
2439 * (int64_t)global.framerate.num / global.framerate.den
2442 stream->cx_time > 9999999 ? stream->cx_time / 1000 : stream->cx_time,
2443 stream->cx_time > 9999999 ? "ms" : "us",
2444 usec_to_fps(stream->cx_time, frames_in));
2447 if (global.show_psnr)
2448 FOREACH_STREAM(show_psnr(stream));
2450 FOREACH_STREAM(vpx_codec_destroy(&stream->encoder));
2452 if (global.test_decode) {
2453 FOREACH_STREAM(vpx_codec_destroy(&stream->decoder));
2454 FOREACH_STREAM(vpx_img_free(&stream->ref_enc.img));
2455 FOREACH_STREAM(vpx_img_free(&stream->ref_dec.img));
2458 close_input_file(&input);
2460 FOREACH_STREAM(close_output_file(stream, global.codec->fourcc));
2462 FOREACH_STREAM(stats_close(&stream->stats, global.passes - 1));
2468 if (global.show_q_hist_buckets)
2469 FOREACH_STREAM(show_q_histogram(stream->counts,
2470 global.show_q_hist_buckets));
2472 if (global.show_rate_hist_buckets)
2473 FOREACH_STREAM(show_rate_histogram(&stream->rate_hist,
2474 &stream->config.cfg,
2475 global.show_rate_hist_buckets));
2476 FOREACH_STREAM(destroy_rate_histogram(&stream->rate_hist));
2478 #if CONFIG_INTERNAL_STATS
2479 /* TODO(jkoleszar): This doesn't belong in this executable. Do it for now,
2480 * to match some existing utilities.
2483 FILE *f = fopen("opsnr.stt", "a");
2484 if (stream->mismatch_seen) {
2485 fprintf(f, "First mismatch occurred in frame %d\n",
2486 stream->mismatch_seen);
2488 fprintf(f, "No mismatch detected in recon buffers\n");
2497 return EXIT_SUCCESS;