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.
12 /* This is a simple program that encodes YV12 files and generates ivf
13 * files using the new interface.
15 #if defined(_WIN32) || !CONFIG_OS_SUPPORT
16 #define USE_POSIX_MMAP 0
18 #define USE_POSIX_MMAP 1
27 #include "vpx/vpx_encoder.h"
29 #include <sys/types.h>
35 #include "vpx_version.h"
36 #include "vpx/vp8cx.h"
37 #include "vpx_ports/mem_ops.h"
38 #include "vpx_ports/vpx_timer.h"
39 #include "tools_common.h"
41 #include "libmkv/EbmlWriter.h"
42 #include "libmkv/EbmlIDs.h"
44 /* Need special handling of these functions on Windows */
46 /* MSVS doesn't define off_t, and uses _f{seek,tell}i64 */
47 typedef __int64 off_t;
48 #define fseeko _fseeki64
49 #define ftello _ftelli64
51 /* MinGW defines off_t, and uses f{seek,tell}o64 */
52 #define fseeko fseeko64
53 #define ftello ftello64
57 #define LITERALU64(n) n
59 #define LITERALU64(n) n##LLU
62 /* We should use 32-bit file operations in WebM file format
63 * when building ARM executable file (.axf) with RVCT */
64 #if !CONFIG_OS_SUPPORT
70 static const char *exec_name;
72 static const struct codec_item
75 const vpx_codec_iface_t *iface;
79 #if CONFIG_VP8_ENCODER
80 {"vp8", &vpx_codec_vp8_cx_algo, 0x30385056},
84 static void usage_exit();
86 void die(const char *fmt, ...)
90 vfprintf(stderr, fmt, ap);
91 fprintf(stderr, "\n");
95 static void ctx_exit_on_error(vpx_codec_ctx_t *ctx, const char *s)
99 const char *detail = vpx_codec_error_detail(ctx);
101 fprintf(stderr, "%s: %s\n", s, vpx_codec_error(ctx));
104 fprintf(stderr, " %s\n", detail);
110 /* This structure is used to abstract the different ways of handling
111 * first pass statistics.
122 int stats_open_file(stats_io_t *stats, const char *fpf, int pass)
130 stats->file = fopen(fpf, "wb");
132 stats->buf.buf = NULL,
133 res = (stats->file != NULL);
139 struct stat stat_buf;
142 fd = open(fpf, O_RDONLY);
143 stats->file = fdopen(fd, "rb");
144 fstat(fd, &stat_buf);
145 stats->buf.sz = stat_buf.st_size;
146 stats->buf.buf = mmap(NULL, stats->buf.sz, PROT_READ, MAP_PRIVATE,
148 res = (stats->buf.buf != NULL);
152 stats->file = fopen(fpf, "rb");
154 if (fseek(stats->file, 0, SEEK_END))
156 fprintf(stderr, "First-pass stats file must be seekable!\n");
160 stats->buf.sz = stats->buf_alloc_sz = ftell(stats->file);
163 stats->buf.buf = malloc(stats->buf_alloc_sz);
167 fprintf(stderr, "Failed to allocate first-pass stats buffer (%lu bytes)\n",
168 (unsigned long)stats->buf_alloc_sz);
172 nbytes = fread(stats->buf.buf, 1, stats->buf.sz, stats->file);
173 res = (nbytes == stats->buf.sz);
180 int stats_open_mem(stats_io_t *stats, int pass)
188 stats->buf_alloc_sz = 64 * 1024;
189 stats->buf.buf = malloc(stats->buf_alloc_sz);
192 stats->buf_ptr = stats->buf.buf;
193 res = (stats->buf.buf != NULL);
198 void stats_close(stats_io_t *stats, int last_pass)
202 if (stats->pass == last_pass)
206 munmap(stats->buf.buf, stats->buf.sz);
208 free(stats->buf.buf);
217 if (stats->pass == last_pass)
218 free(stats->buf.buf);
222 void stats_write(stats_io_t *stats, const void *pkt, size_t len)
226 if(fwrite(pkt, 1, len, stats->file));
230 if (stats->buf.sz + len > stats->buf_alloc_sz)
232 size_t new_sz = stats->buf_alloc_sz + 64 * 1024;
233 char *new_ptr = realloc(stats->buf.buf, new_sz);
237 stats->buf_ptr = new_ptr + (stats->buf_ptr - (char *)stats->buf.buf);
238 stats->buf.buf = new_ptr;
239 stats->buf_alloc_sz = new_sz;
244 "\nFailed to realloc firstpass stats buffer.\n");
249 memcpy(stats->buf_ptr, pkt, len);
250 stats->buf.sz += len;
251 stats->buf_ptr += len;
255 vpx_fixed_buf_t stats_get(stats_io_t *stats)
260 /* Stereo 3D packed frame format */
261 typedef enum stereo_format
263 STEREO_FORMAT_MONO = 0,
264 STEREO_FORMAT_LEFT_RIGHT = 1,
265 STEREO_FORMAT_BOTTOM_TOP = 2,
266 STEREO_FORMAT_TOP_BOTTOM = 3,
267 STEREO_FORMAT_RIGHT_LEFT = 11
277 struct detect_buffer {
284 #define IVF_FRAME_HDR_SZ (4+8) /* 4 byte size + 8 byte timestamp */
285 static int read_frame(FILE *f, vpx_image_t *img, unsigned int file_type,
286 y4m_input *y4m, struct detect_buffer *detect)
291 if (file_type == FILE_TYPE_Y4M)
293 if (y4m_input_fetch_frame(y4m, f, img) < 1)
298 if (file_type == FILE_TYPE_IVF)
300 char junk[IVF_FRAME_HDR_SZ];
302 /* Skip the frame header. We know how big the frame should be. See
303 * write_ivf_frame_header() for documentation on the frame header
306 if(fread(junk, 1, IVF_FRAME_HDR_SZ, f));
309 for (plane = 0; plane < 3; plane++)
312 int w = (plane ? (1 + img->d_w) / 2 : img->d_w);
313 int h = (plane ? (1 + img->d_h) / 2 : img->d_h);
316 /* Determine the correct plane based on the image format. The for-loop
317 * always counts in Y,U,V order, but this may not match the order of
323 ptr = img->planes[img->fmt==VPX_IMG_FMT_YV12? VPX_PLANE_V : VPX_PLANE_U];
326 ptr = img->planes[img->fmt==VPX_IMG_FMT_YV12?VPX_PLANE_U : VPX_PLANE_V];
329 ptr = img->planes[plane];
332 for (r = 0; r < h; r++)
335 size_t buf_position = 0;
336 const size_t left = detect->buf_read - detect->position;
339 const size_t more = (left < needed) ? left : needed;
340 memcpy(ptr, detect->buf + detect->position, more);
343 detect->position += more;
347 shortread |= (fread(ptr + buf_position, 1, needed, f) < needed);
350 ptr += img->stride[plane];
359 unsigned int file_is_y4m(FILE *infile,
363 if(memcmp(detect, "YUV4", 4) == 0)
370 #define IVF_FILE_HDR_SZ (32)
371 unsigned int file_is_ivf(FILE *infile,
372 unsigned int *fourcc,
374 unsigned int *height,
375 struct detect_buffer *detect)
377 char raw_hdr[IVF_FILE_HDR_SZ];
380 if(memcmp(detect->buf, "DKIF", 4) != 0)
383 /* See write_ivf_file_header() for more documentation on the file header
386 if (fread(raw_hdr + 4, 1, IVF_FILE_HDR_SZ - 4, infile)
387 == IVF_FILE_HDR_SZ - 4)
392 if (mem_get_le16(raw_hdr + 4) != 0)
393 fprintf(stderr, "Error: Unrecognized IVF version! This file may not"
394 " decode properly.");
396 *fourcc = mem_get_le32(raw_hdr + 8);
402 *width = mem_get_le16(raw_hdr + 12);
403 *height = mem_get_le16(raw_hdr + 14);
404 detect->position = 4;
411 static void write_ivf_file_header(FILE *outfile,
412 const vpx_codec_enc_cfg_t *cfg,
418 if (cfg->g_pass != VPX_RC_ONE_PASS && cfg->g_pass != VPX_RC_LAST_PASS)
425 mem_put_le16(header + 4, 0); /* version */
426 mem_put_le16(header + 6, 32); /* headersize */
427 mem_put_le32(header + 8, fourcc); /* headersize */
428 mem_put_le16(header + 12, cfg->g_w); /* width */
429 mem_put_le16(header + 14, cfg->g_h); /* height */
430 mem_put_le32(header + 16, cfg->g_timebase.den); /* rate */
431 mem_put_le32(header + 20, cfg->g_timebase.num); /* scale */
432 mem_put_le32(header + 24, frame_cnt); /* length */
433 mem_put_le32(header + 28, 0); /* unused */
435 if(fwrite(header, 1, 32, outfile));
439 static void write_ivf_frame_header(FILE *outfile,
440 const vpx_codec_cx_pkt_t *pkt)
445 if (pkt->kind != VPX_CODEC_CX_FRAME_PKT)
448 pts = pkt->data.frame.pts;
449 mem_put_le32(header, pkt->data.frame.sz);
450 mem_put_le32(header + 4, pts & 0xFFFFFFFF);
451 mem_put_le32(header + 8, pts >> 32);
453 if(fwrite(header, 1, 12, outfile));
457 typedef off_t EbmlLoc;
473 vpx_rational_t framerate;
475 /* These pointers are to the start of an element */
476 off_t position_reference;
478 off_t segment_info_pos;
483 /* This pointer is to a specific element to be serialized */
486 /* These pointers are to the size field of the element */
487 EbmlLoc startSegment;
488 EbmlLoc startCluster;
490 uint32_t cluster_timecode;
493 struct cue_entry *cue_list;
499 void Ebml_Write(EbmlGlobal *glob, const void *buffer_in, unsigned long len)
501 if(fwrite(buffer_in, 1, len, glob->stream));
505 void Ebml_Serialize(EbmlGlobal *glob, const void *buffer_in, unsigned long len)
507 const unsigned char *q = (const unsigned char *)buffer_in + len - 1;
510 Ebml_Write(glob, q--, 1);
514 /* Need a fixed size serializer for the track ID. libmkv provdes a 64 bit
515 * one, but not a 32 bit one.
517 static void Ebml_SerializeUnsigned32(EbmlGlobal *glob, unsigned long class_id, uint64_t ui)
519 unsigned char sizeSerialized = 4 | 0x80;
520 Ebml_WriteID(glob, class_id);
521 Ebml_Serialize(glob, &sizeSerialized, 1);
522 Ebml_Serialize(glob, &ui, 4);
527 Ebml_StartSubElement(EbmlGlobal *glob, EbmlLoc *ebmlLoc,
528 unsigned long class_id)
530 //todo this is always taking 8 bytes, this may need later optimization
531 //this is a key that says lenght unknown
532 unsigned long long unknownLen = LITERALU64(0x01FFFFFFFFFFFFFF);
534 Ebml_WriteID(glob, class_id);
535 *ebmlLoc = ftello(glob->stream);
536 Ebml_Serialize(glob, &unknownLen, 8);
540 Ebml_EndSubElement(EbmlGlobal *glob, EbmlLoc *ebmlLoc)
545 /* Save the current stream pointer */
546 pos = ftello(glob->stream);
548 /* Calculate the size of this element */
549 size = pos - *ebmlLoc - 8;
550 size |= LITERALU64(0x0100000000000000);
552 /* Seek back to the beginning of the element and write the new size */
553 fseeko(glob->stream, *ebmlLoc, SEEK_SET);
554 Ebml_Serialize(glob, &size, 8);
556 /* Reset the stream pointer */
557 fseeko(glob->stream, pos, SEEK_SET);
562 write_webm_seek_element(EbmlGlobal *ebml, unsigned long id, off_t pos)
564 uint64_t offset = pos - ebml->position_reference;
566 Ebml_StartSubElement(ebml, &start, Seek);
567 Ebml_SerializeBinary(ebml, SeekID, id);
568 Ebml_SerializeUnsigned64(ebml, SeekPosition, offset);
569 Ebml_EndSubElement(ebml, &start);
574 write_webm_seek_info(EbmlGlobal *ebml)
579 /* Save the current stream pointer */
580 pos = ftello(ebml->stream);
582 if(ebml->seek_info_pos)
583 fseeko(ebml->stream, ebml->seek_info_pos, SEEK_SET);
585 ebml->seek_info_pos = pos;
590 Ebml_StartSubElement(ebml, &start, SeekHead);
591 write_webm_seek_element(ebml, Tracks, ebml->track_pos);
592 write_webm_seek_element(ebml, Cues, ebml->cue_pos);
593 write_webm_seek_element(ebml, Info, ebml->segment_info_pos);
594 Ebml_EndSubElement(ebml, &start);
601 frame_time = (uint64_t)1000 * ebml->framerate.den
602 / ebml->framerate.num;
603 ebml->segment_info_pos = ftello(ebml->stream);
604 Ebml_StartSubElement(ebml, &startInfo, Info);
605 Ebml_SerializeUnsigned(ebml, TimecodeScale, 1000000);
606 Ebml_SerializeFloat(ebml, Segment_Duration,
607 ebml->last_pts_ms + frame_time);
608 Ebml_SerializeString(ebml, 0x4D80,
609 ebml->debug ? "vpxenc" : "vpxenc" VERSION_STRING);
610 Ebml_SerializeString(ebml, 0x5741,
611 ebml->debug ? "vpxenc" : "vpxenc" VERSION_STRING);
612 Ebml_EndSubElement(ebml, &startInfo);
618 write_webm_file_header(EbmlGlobal *glob,
619 const vpx_codec_enc_cfg_t *cfg,
620 const struct vpx_rational *fps,
621 stereo_format_t stereo_fmt)
625 Ebml_StartSubElement(glob, &start, EBML);
626 Ebml_SerializeUnsigned(glob, EBMLVersion, 1);
627 Ebml_SerializeUnsigned(glob, EBMLReadVersion, 1); //EBML Read Version
628 Ebml_SerializeUnsigned(glob, EBMLMaxIDLength, 4); //EBML Max ID Length
629 Ebml_SerializeUnsigned(glob, EBMLMaxSizeLength, 8); //EBML Max Size Length
630 Ebml_SerializeString(glob, DocType, "webm"); //Doc Type
631 Ebml_SerializeUnsigned(glob, DocTypeVersion, 2); //Doc Type Version
632 Ebml_SerializeUnsigned(glob, DocTypeReadVersion, 2); //Doc Type Read Version
633 Ebml_EndSubElement(glob, &start);
636 Ebml_StartSubElement(glob, &glob->startSegment, Segment); //segment
637 glob->position_reference = ftello(glob->stream);
638 glob->framerate = *fps;
639 write_webm_seek_info(glob);
643 glob->track_pos = ftello(glob->stream);
644 Ebml_StartSubElement(glob, &trackStart, Tracks);
646 unsigned int trackNumber = 1;
647 uint64_t trackID = 0;
650 Ebml_StartSubElement(glob, &start, TrackEntry);
651 Ebml_SerializeUnsigned(glob, TrackNumber, trackNumber);
652 glob->track_id_pos = ftello(glob->stream);
653 Ebml_SerializeUnsigned32(glob, TrackUID, trackID);
654 Ebml_SerializeUnsigned(glob, TrackType, 1); //video is always 1
655 Ebml_SerializeString(glob, CodecID, "V_VP8");
657 unsigned int pixelWidth = cfg->g_w;
658 unsigned int pixelHeight = cfg->g_h;
659 float frameRate = (float)fps->num/(float)fps->den;
662 Ebml_StartSubElement(glob, &videoStart, Video);
663 Ebml_SerializeUnsigned(glob, PixelWidth, pixelWidth);
664 Ebml_SerializeUnsigned(glob, PixelHeight, pixelHeight);
665 Ebml_SerializeUnsigned(glob, StereoMode, stereo_fmt);
666 Ebml_SerializeFloat(glob, FrameRate, frameRate);
667 Ebml_EndSubElement(glob, &videoStart); //Video
669 Ebml_EndSubElement(glob, &start); //Track Entry
671 Ebml_EndSubElement(glob, &trackStart);
673 // segment element is open
679 write_webm_block(EbmlGlobal *glob,
680 const vpx_codec_enc_cfg_t *cfg,
681 const vpx_codec_cx_pkt_t *pkt)
683 unsigned long block_length;
684 unsigned char track_number;
685 unsigned short block_timecode = 0;
688 int start_cluster = 0, is_keyframe;
690 /* Calculate the PTS of this frame in milliseconds */
691 pts_ms = pkt->data.frame.pts * 1000
692 * (uint64_t)cfg->g_timebase.num / (uint64_t)cfg->g_timebase.den;
693 if(pts_ms <= glob->last_pts_ms)
694 pts_ms = glob->last_pts_ms + 1;
695 glob->last_pts_ms = pts_ms;
697 /* Calculate the relative time of this block */
698 if(pts_ms - glob->cluster_timecode > SHRT_MAX)
701 block_timecode = pts_ms - glob->cluster_timecode;
703 is_keyframe = (pkt->data.frame.flags & VPX_FRAME_IS_KEY);
704 if(start_cluster || is_keyframe)
706 if(glob->cluster_open)
707 Ebml_EndSubElement(glob, &glob->startCluster);
709 /* Open the new cluster */
711 glob->cluster_open = 1;
712 glob->cluster_timecode = pts_ms;
713 glob->cluster_pos = ftello(glob->stream);
714 Ebml_StartSubElement(glob, &glob->startCluster, Cluster); //cluster
715 Ebml_SerializeUnsigned(glob, Timecode, glob->cluster_timecode);
717 /* Save a cue point if this is a keyframe. */
720 struct cue_entry *cue, *new_cue_list;
722 new_cue_list = realloc(glob->cue_list,
723 (glob->cues+1) * sizeof(struct cue_entry));
725 glob->cue_list = new_cue_list;
728 fprintf(stderr, "\nFailed to realloc cue list.\n");
732 cue = &glob->cue_list[glob->cues];
733 cue->time = glob->cluster_timecode;
734 cue->loc = glob->cluster_pos;
739 /* Write the Simple Block */
740 Ebml_WriteID(glob, SimpleBlock);
742 block_length = pkt->data.frame.sz + 4;
743 block_length |= 0x10000000;
744 Ebml_Serialize(glob, &block_length, 4);
747 track_number |= 0x80;
748 Ebml_Write(glob, &track_number, 1);
750 Ebml_Serialize(glob, &block_timecode, 2);
755 if(pkt->data.frame.flags & VPX_FRAME_IS_INVISIBLE)
757 Ebml_Write(glob, &flags, 1);
759 Ebml_Write(glob, pkt->data.frame.buf, pkt->data.frame.sz);
764 write_webm_file_footer(EbmlGlobal *glob, long hash)
767 if(glob->cluster_open)
768 Ebml_EndSubElement(glob, &glob->startCluster);
774 glob->cue_pos = ftello(glob->stream);
775 Ebml_StartSubElement(glob, &start, Cues);
776 for(i=0; i<glob->cues; i++)
778 struct cue_entry *cue = &glob->cue_list[i];
781 Ebml_StartSubElement(glob, &start, CuePoint);
785 Ebml_SerializeUnsigned(glob, CueTime, cue->time);
787 Ebml_StartSubElement(glob, &start, CueTrackPositions);
788 Ebml_SerializeUnsigned(glob, CueTrack, 1);
789 Ebml_SerializeUnsigned64(glob, CueClusterPosition,
790 cue->loc - glob->position_reference);
791 //Ebml_SerializeUnsigned(glob, CueBlockNumber, cue->blockNumber);
792 Ebml_EndSubElement(glob, &start);
794 Ebml_EndSubElement(glob, &start);
796 Ebml_EndSubElement(glob, &start);
799 Ebml_EndSubElement(glob, &glob->startSegment);
801 /* Patch up the seek info block */
802 write_webm_seek_info(glob);
804 /* Patch up the track id */
805 fseeko(glob->stream, glob->track_id_pos, SEEK_SET);
806 Ebml_SerializeUnsigned32(glob, TrackUID, glob->debug ? 0xDEADBEEF : hash);
808 fseeko(glob->stream, 0, SEEK_END);
812 /* Murmur hash derived from public domain reference implementation at
813 * http://sites.google.com/site/murmurhash/
815 static unsigned int murmur ( const void * key, int len, unsigned int seed )
817 const unsigned int m = 0x5bd1e995;
820 unsigned int h = seed ^ len;
822 const unsigned char * data = (const unsigned char *)key;
846 case 3: h ^= data[2] << 16;
847 case 2: h ^= data[1] << 8;
848 case 1: h ^= data[0];
861 static double vp8_mse2psnr(double Samples, double Peak, double Mse)
865 if ((double)Mse > 0.0)
866 psnr = 10.0 * log10(Peak * Peak * Samples / Mse);
868 psnr = 60; // Limit to prevent / 0
879 static const arg_def_t debugmode = ARG_DEF("D", "debug", 0,
880 "Debug mode (makes output deterministic)");
881 static const arg_def_t outputfile = ARG_DEF("o", "output", 1,
883 static const arg_def_t use_yv12 = ARG_DEF(NULL, "yv12", 0,
884 "Input file is YV12 ");
885 static const arg_def_t use_i420 = ARG_DEF(NULL, "i420", 0,
886 "Input file is I420 (default)");
887 static const arg_def_t codecarg = ARG_DEF(NULL, "codec", 1,
889 static const arg_def_t passes = ARG_DEF("p", "passes", 1,
890 "Number of passes (1/2)");
891 static const arg_def_t pass_arg = ARG_DEF(NULL, "pass", 1,
892 "Pass to execute (1/2)");
893 static const arg_def_t fpf_name = ARG_DEF(NULL, "fpf", 1,
894 "First pass statistics file name");
895 static const arg_def_t limit = ARG_DEF(NULL, "limit", 1,
896 "Stop encoding after n input frames");
897 static const arg_def_t deadline = ARG_DEF("d", "deadline", 1,
898 "Deadline per frame (usec)");
899 static const arg_def_t best_dl = ARG_DEF(NULL, "best", 0,
900 "Use Best Quality Deadline");
901 static const arg_def_t good_dl = ARG_DEF(NULL, "good", 0,
902 "Use Good Quality Deadline");
903 static const arg_def_t rt_dl = ARG_DEF(NULL, "rt", 0,
904 "Use Realtime Quality Deadline");
905 static const arg_def_t verbosearg = ARG_DEF("v", "verbose", 0,
906 "Show encoder parameters");
907 static const arg_def_t psnrarg = ARG_DEF(NULL, "psnr", 0,
908 "Show PSNR in status line");
909 static const arg_def_t framerate = ARG_DEF(NULL, "fps", 1,
910 "Stream frame rate (rate/scale)");
911 static const arg_def_t use_ivf = ARG_DEF(NULL, "ivf", 0,
912 "Output IVF (default is WebM)");
913 static const arg_def_t q_hist_n = ARG_DEF(NULL, "q-hist", 1,
914 "Show quantizer histogram (n-buckets)");
915 static const arg_def_t *main_args[] =
918 &outputfile, &codecarg, &passes, &pass_arg, &fpf_name, &limit, &deadline,
919 &best_dl, &good_dl, &rt_dl,
920 &verbosearg, &psnrarg, &use_ivf, &q_hist_n,
924 static const arg_def_t usage = ARG_DEF("u", "usage", 1,
925 "Usage profile number to use");
926 static const arg_def_t threads = ARG_DEF("t", "threads", 1,
927 "Max number of threads to use");
928 static const arg_def_t profile = ARG_DEF(NULL, "profile", 1,
929 "Bitstream profile number to use");
930 static const arg_def_t width = ARG_DEF("w", "width", 1,
932 static const arg_def_t height = ARG_DEF("h", "height", 1,
934 static const struct arg_enum_list stereo_mode_enum[] = {
935 {"mono" , STEREO_FORMAT_MONO},
936 {"left-right", STEREO_FORMAT_LEFT_RIGHT},
937 {"bottom-top", STEREO_FORMAT_BOTTOM_TOP},
938 {"top-bottom", STEREO_FORMAT_TOP_BOTTOM},
939 {"right-left", STEREO_FORMAT_RIGHT_LEFT},
942 static const arg_def_t stereo_mode = ARG_DEF_ENUM(NULL, "stereo-mode", 1,
943 "Stereo 3D video format", stereo_mode_enum);
944 static const arg_def_t timebase = ARG_DEF(NULL, "timebase", 1,
945 "Stream timebase (frame duration)");
946 static const arg_def_t error_resilient = ARG_DEF(NULL, "error-resilient", 1,
947 "Enable error resiliency features");
948 static const arg_def_t lag_in_frames = ARG_DEF(NULL, "lag-in-frames", 1,
949 "Max number of frames to lag");
951 static const arg_def_t *global_args[] =
953 &use_yv12, &use_i420, &usage, &threads, &profile,
954 &width, &height, &stereo_mode, &timebase, &framerate, &error_resilient,
958 static const arg_def_t dropframe_thresh = ARG_DEF(NULL, "drop-frame", 1,
959 "Temporal resampling threshold (buf %)");
960 static const arg_def_t resize_allowed = ARG_DEF(NULL, "resize-allowed", 1,
961 "Spatial resampling enabled (bool)");
962 static const arg_def_t resize_up_thresh = ARG_DEF(NULL, "resize-up", 1,
963 "Upscale threshold (buf %)");
964 static const arg_def_t resize_down_thresh = ARG_DEF(NULL, "resize-down", 1,
965 "Downscale threshold (buf %)");
966 static const struct arg_enum_list end_usage_enum[] = {
972 static const arg_def_t end_usage = ARG_DEF_ENUM(NULL, "end-usage", 1,
973 "Rate control mode", end_usage_enum);
974 static const arg_def_t target_bitrate = ARG_DEF(NULL, "target-bitrate", 1,
976 static const arg_def_t min_quantizer = ARG_DEF(NULL, "min-q", 1,
977 "Minimum (best) quantizer");
978 static const arg_def_t max_quantizer = ARG_DEF(NULL, "max-q", 1,
979 "Maximum (worst) quantizer");
980 static const arg_def_t undershoot_pct = ARG_DEF(NULL, "undershoot-pct", 1,
981 "Datarate undershoot (min) target (%)");
982 static const arg_def_t overshoot_pct = ARG_DEF(NULL, "overshoot-pct", 1,
983 "Datarate overshoot (max) target (%)");
984 static const arg_def_t buf_sz = ARG_DEF(NULL, "buf-sz", 1,
985 "Client buffer size (ms)");
986 static const arg_def_t buf_initial_sz = ARG_DEF(NULL, "buf-initial-sz", 1,
987 "Client initial buffer size (ms)");
988 static const arg_def_t buf_optimal_sz = ARG_DEF(NULL, "buf-optimal-sz", 1,
989 "Client optimal buffer size (ms)");
990 static const arg_def_t max_intra_rate_pct = ARG_DEF(NULL, "max-intra-rate", 1,
991 "Max I-frame bitrate (pct)");
992 static const arg_def_t *rc_args[] =
994 &dropframe_thresh, &resize_allowed, &resize_up_thresh, &resize_down_thresh,
995 &end_usage, &target_bitrate, &min_quantizer, &max_quantizer,
996 &undershoot_pct, &overshoot_pct, &buf_sz, &buf_initial_sz, &buf_optimal_sz,
1002 static const arg_def_t bias_pct = ARG_DEF(NULL, "bias-pct", 1,
1003 "CBR/VBR bias (0=CBR, 100=VBR)");
1004 static const arg_def_t minsection_pct = ARG_DEF(NULL, "minsection-pct", 1,
1005 "GOP min bitrate (% of target)");
1006 static const arg_def_t maxsection_pct = ARG_DEF(NULL, "maxsection-pct", 1,
1007 "GOP max bitrate (% of target)");
1008 static const arg_def_t *rc_twopass_args[] =
1010 &bias_pct, &minsection_pct, &maxsection_pct, NULL
1014 static const arg_def_t kf_min_dist = ARG_DEF(NULL, "kf-min-dist", 1,
1015 "Minimum keyframe interval (frames)");
1016 static const arg_def_t kf_max_dist = ARG_DEF(NULL, "kf-max-dist", 1,
1017 "Maximum keyframe interval (frames)");
1018 static const arg_def_t kf_disabled = ARG_DEF(NULL, "disable-kf", 0,
1019 "Disable keyframe placement");
1020 static const arg_def_t *kf_args[] =
1022 &kf_min_dist, &kf_max_dist, &kf_disabled, NULL
1026 #if CONFIG_VP8_ENCODER
1027 static const arg_def_t noise_sens = ARG_DEF(NULL, "noise-sensitivity", 1,
1028 "Noise sensitivity (frames to blur)");
1029 static const arg_def_t sharpness = ARG_DEF(NULL, "sharpness", 1,
1030 "Filter sharpness (0-7)");
1031 static const arg_def_t static_thresh = ARG_DEF(NULL, "static-thresh", 1,
1032 "Motion detection threshold");
1035 #if CONFIG_VP8_ENCODER
1036 static const arg_def_t cpu_used = ARG_DEF(NULL, "cpu-used", 1,
1037 "CPU Used (-16..16)");
1041 #if CONFIG_VP8_ENCODER
1042 static const arg_def_t token_parts = ARG_DEF(NULL, "token-parts", 1,
1043 "Number of token partitions to use, log2");
1044 static const arg_def_t auto_altref = ARG_DEF(NULL, "auto-alt-ref", 1,
1045 "Enable automatic alt reference frames");
1046 static const arg_def_t arnr_maxframes = ARG_DEF(NULL, "arnr-maxframes", 1,
1047 "AltRef Max Frames");
1048 static const arg_def_t arnr_strength = ARG_DEF(NULL, "arnr-strength", 1,
1050 static const arg_def_t arnr_type = ARG_DEF(NULL, "arnr-type", 1,
1052 static const struct arg_enum_list tuning_enum[] = {
1053 {"psnr", VP8_TUNE_PSNR},
1054 {"ssim", VP8_TUNE_SSIM},
1057 static const arg_def_t tune_ssim = ARG_DEF_ENUM(NULL, "tune", 1,
1058 "Material to favor", tuning_enum);
1059 static const arg_def_t cq_level = ARG_DEF(NULL, "cq-level", 1,
1060 "Constrained Quality Level");
1062 static const arg_def_t *vp8_args[] =
1064 &cpu_used, &auto_altref, &noise_sens, &sharpness, &static_thresh,
1065 &token_parts, &arnr_maxframes, &arnr_strength, &arnr_type,
1066 &tune_ssim, &cq_level, NULL
1068 static const int vp8_arg_ctrl_map[] =
1070 VP8E_SET_CPUUSED, VP8E_SET_ENABLEAUTOALTREF,
1071 VP8E_SET_NOISE_SENSITIVITY, VP8E_SET_SHARPNESS, VP8E_SET_STATIC_THRESHOLD,
1072 VP8E_SET_TOKEN_PARTITIONS,
1073 VP8E_SET_ARNR_MAXFRAMES, VP8E_SET_ARNR_STRENGTH , VP8E_SET_ARNR_TYPE,
1074 VP8E_SET_TUNING, VP8E_SET_CQ_LEVEL, 0
1078 static const arg_def_t *no_args[] = { NULL };
1080 static void usage_exit()
1084 fprintf(stderr, "Usage: %s <options> -o dst_filename src_filename \n",
1087 fprintf(stderr, "\nOptions:\n");
1088 arg_show_usage(stdout, main_args);
1089 fprintf(stderr, "\nEncoder Global Options:\n");
1090 arg_show_usage(stdout, global_args);
1091 fprintf(stderr, "\nRate Control Options:\n");
1092 arg_show_usage(stdout, rc_args);
1093 fprintf(stderr, "\nTwopass Rate Control Options:\n");
1094 arg_show_usage(stdout, rc_twopass_args);
1095 fprintf(stderr, "\nKeyframe Placement Options:\n");
1096 arg_show_usage(stdout, kf_args);
1097 #if CONFIG_VP8_ENCODER
1098 fprintf(stderr, "\nVP8 Specific Options:\n");
1099 arg_show_usage(stdout, vp8_args);
1101 fprintf(stderr, "\n"
1102 "Included encoders:\n"
1105 for (i = 0; i < sizeof(codecs) / sizeof(codecs[0]); i++)
1106 fprintf(stderr, " %-6s - %s\n",
1108 vpx_codec_iface_name(codecs[i].iface));
1114 #define HIST_BAR_MAX 40
1117 int low, high, count;
1121 static int merge_hist_buckets(struct hist_bucket *bucket,
1125 int small_bucket = 0, merge_bucket = INT_MAX, big_bucket=0;
1126 int buckets = *buckets_;
1129 /* Find the extrema for this list of buckets */
1130 big_bucket = small_bucket = 0;
1131 for(i=0; i < buckets; i++)
1133 if(bucket[i].count < bucket[small_bucket].count)
1135 if(bucket[i].count > bucket[big_bucket].count)
1139 /* If we have too many buckets, merge the smallest with an ajacent
1142 while(buckets > max_buckets)
1144 int last_bucket = buckets - 1;
1146 // merge the small bucket with an adjacent one.
1147 if(small_bucket == 0)
1149 else if(small_bucket == last_bucket)
1150 merge_bucket = last_bucket - 1;
1151 else if(bucket[small_bucket - 1].count < bucket[small_bucket + 1].count)
1152 merge_bucket = small_bucket - 1;
1154 merge_bucket = small_bucket + 1;
1156 assert(abs(merge_bucket - small_bucket) <= 1);
1157 assert(small_bucket < buckets);
1158 assert(big_bucket < buckets);
1159 assert(merge_bucket < buckets);
1161 if(merge_bucket < small_bucket)
1163 bucket[merge_bucket].high = bucket[small_bucket].high;
1164 bucket[merge_bucket].count += bucket[small_bucket].count;
1168 bucket[small_bucket].high = bucket[merge_bucket].high;
1169 bucket[small_bucket].count += bucket[merge_bucket].count;
1170 merge_bucket = small_bucket;
1173 assert(bucket[merge_bucket].low != bucket[merge_bucket].high);
1177 /* Remove the merge_bucket from the list, and find the new small
1178 * and big buckets while we're at it
1180 big_bucket = small_bucket = 0;
1181 for(i=0; i < buckets; i++)
1183 if(i > merge_bucket)
1184 bucket[i] = bucket[i+1];
1186 if(bucket[i].count < bucket[small_bucket].count)
1188 if(bucket[i].count > bucket[big_bucket].count)
1194 *buckets_ = buckets;
1195 return bucket[big_bucket].count;
1199 static void show_histogram(const struct hist_bucket *bucket,
1206 for(i=0; i<buckets; i++)
1212 pct = 100.0 * (float)bucket[i].count / (float)total;
1213 len = HIST_BAR_MAX * bucket[i].count / scale;
1216 assert(len <= HIST_BAR_MAX);
1218 if(bucket[i].low == bucket[i].high)
1219 fprintf(stderr, "%4d : ", bucket[i].low);
1221 fprintf(stderr, "%4d-%2d: ", bucket[i].low, bucket[i].high);
1223 for(j=0; j<HIST_BAR_MAX; j++)
1224 fprintf(stderr, j<len?"=":" ");
1225 fprintf(stderr, "\t%5d (%6.2f%%)\n",bucket[i].count,pct);
1230 static void show_q_histogram(const int counts[64], int max_buckets)
1232 struct hist_bucket bucket[64];
1243 bucket[buckets].low = bucket[buckets].high = i;
1244 bucket[buckets].count = counts[i];
1250 fprintf(stderr, "Quantizer Selection:\n");
1251 scale = merge_hist_buckets(bucket, &buckets, max_buckets);
1252 show_histogram(bucket, buckets, total, scale);
1256 #define ARG_CTRL_CNT_MAX 10
1258 int main(int argc, const char **argv_)
1260 vpx_codec_ctx_t encoder;
1261 const char *in_fn = NULL, *out_fn = NULL, *stats_fn = NULL;
1263 FILE *infile, *outfile;
1264 vpx_codec_enc_cfg_t cfg;
1265 vpx_codec_err_t res;
1266 int pass, one_pass_only = 0;
1269 const struct codec_item *codec = codecs;
1270 int frame_avail, got_data;
1273 char **argv, **argi, **argj;
1274 int arg_usage = 0, arg_passes = 1, arg_deadline = 0;
1275 int arg_ctrls[ARG_CTRL_CNT_MAX][2], arg_ctrl_cnt = 0;
1277 static const arg_def_t **ctrl_args = no_args;
1278 static const int *ctrl_args_map = NULL;
1279 int verbose = 0, show_psnr = 0;
1280 int arg_use_i420 = 1;
1281 unsigned long cx_time = 0;
1282 unsigned int file_type, fourcc;
1284 struct vpx_rational arg_framerate = {30, 1};
1285 int arg_have_framerate = 0;
1287 EbmlGlobal ebml = {0};
1289 uint64_t psnr_sse_total = 0;
1290 uint64_t psnr_samples_total = 0;
1291 double psnr_totals[4] = {0, 0, 0, 0};
1293 stereo_format_t stereo_fmt = STEREO_FORMAT_MONO;
1295 int show_q_hist_buckets=0;
1297 exec_name = argv_[0];
1298 ebml.last_pts_ms = -1;
1304 /* First parse the codec and usage values, because we want to apply other
1305 * parameters on top of the default configuration provided by the codec.
1307 argv = argv_dup(argc - 1, argv_ + 1);
1309 for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step)
1313 if (arg_match(&arg, &codecarg, argi))
1317 for (j = 0; j < sizeof(codecs) / sizeof(codecs[0]); j++)
1318 if (!strcmp(codecs[j].name, arg.val))
1324 die("Error: Unrecognized argument (%s) to --codec\n",
1328 else if (arg_match(&arg, &passes, argi))
1330 arg_passes = arg_parse_uint(&arg);
1332 if (arg_passes < 1 || arg_passes > 2)
1333 die("Error: Invalid number of passes (%d)\n", arg_passes);
1335 else if (arg_match(&arg, &pass_arg, argi))
1337 one_pass_only = arg_parse_uint(&arg);
1339 if (one_pass_only < 1 || one_pass_only > 2)
1340 die("Error: Invalid pass selected (%d)\n", one_pass_only);
1342 else if (arg_match(&arg, &fpf_name, argi))
1344 else if (arg_match(&arg, &usage, argi))
1345 arg_usage = arg_parse_uint(&arg);
1346 else if (arg_match(&arg, &deadline, argi))
1347 arg_deadline = arg_parse_uint(&arg);
1348 else if (arg_match(&arg, &best_dl, argi))
1349 arg_deadline = VPX_DL_BEST_QUALITY;
1350 else if (arg_match(&arg, &good_dl, argi))
1351 arg_deadline = VPX_DL_GOOD_QUALITY;
1352 else if (arg_match(&arg, &rt_dl, argi))
1353 arg_deadline = VPX_DL_REALTIME;
1354 else if (arg_match(&arg, &use_yv12, argi))
1358 else if (arg_match(&arg, &use_i420, argi))
1362 else if (arg_match(&arg, &verbosearg, argi))
1364 else if (arg_match(&arg, &limit, argi))
1365 arg_limit = arg_parse_uint(&arg);
1366 else if (arg_match(&arg, &psnrarg, argi))
1368 else if (arg_match(&arg, &framerate, argi))
1370 arg_framerate = arg_parse_rational(&arg);
1371 arg_have_framerate = 1;
1373 else if (arg_match(&arg, &use_ivf, argi))
1375 else if (arg_match(&arg, &outputfile, argi))
1377 else if (arg_match(&arg, &debugmode, argi))
1379 else if (arg_match(&arg, &q_hist_n, argi))
1380 show_q_hist_buckets = arg_parse_uint(&arg);
1385 /* Ensure that --passes and --pass are consistent. If --pass is set and --passes=2,
1386 * ensure --fpf was set.
1390 /* DWIM: Assume the user meant passes=2 if pass=2 is specified */
1391 if (one_pass_only > arg_passes)
1393 fprintf(stderr, "Warning: Assuming --pass=%d implies --passes=%d\n",
1394 one_pass_only, one_pass_only);
1395 arg_passes = one_pass_only;
1398 if (arg_passes == 2 && !stats_fn)
1399 die("Must specify --fpf when --pass=%d and --passes=2\n", one_pass_only);
1402 /* Populate encoder configuration */
1403 res = vpx_codec_enc_config_default(codec->iface, &cfg, arg_usage);
1407 fprintf(stderr, "Failed to get config: %s\n",
1408 vpx_codec_err_to_string(res));
1409 return EXIT_FAILURE;
1412 /* Change the default timebase to a high enough value so that the encoder
1413 * will always create strictly increasing timestamps.
1415 cfg.g_timebase.den = 1000;
1417 /* Never use the library's default resolution, require it be parsed
1418 * from the file or set on the command line.
1423 /* Now parse the remainder of the parameters. */
1424 for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step)
1429 else if (arg_match(&arg, &threads, argi))
1430 cfg.g_threads = arg_parse_uint(&arg);
1431 else if (arg_match(&arg, &profile, argi))
1432 cfg.g_profile = arg_parse_uint(&arg);
1433 else if (arg_match(&arg, &width, argi))
1434 cfg.g_w = arg_parse_uint(&arg);
1435 else if (arg_match(&arg, &height, argi))
1436 cfg.g_h = arg_parse_uint(&arg);
1437 else if (arg_match(&arg, &stereo_mode, argi))
1438 stereo_fmt = arg_parse_enum_or_int(&arg);
1439 else if (arg_match(&arg, &timebase, argi))
1440 cfg.g_timebase = arg_parse_rational(&arg);
1441 else if (arg_match(&arg, &error_resilient, argi))
1442 cfg.g_error_resilient = arg_parse_uint(&arg);
1443 else if (arg_match(&arg, &lag_in_frames, argi))
1444 cfg.g_lag_in_frames = arg_parse_uint(&arg);
1445 else if (arg_match(&arg, &dropframe_thresh, argi))
1446 cfg.rc_dropframe_thresh = arg_parse_uint(&arg);
1447 else if (arg_match(&arg, &resize_allowed, argi))
1448 cfg.rc_resize_allowed = arg_parse_uint(&arg);
1449 else if (arg_match(&arg, &resize_up_thresh, argi))
1450 cfg.rc_resize_up_thresh = arg_parse_uint(&arg);
1451 else if (arg_match(&arg, &resize_down_thresh, argi))
1452 cfg.rc_resize_down_thresh = arg_parse_uint(&arg);
1453 else if (arg_match(&arg, &resize_down_thresh, argi))
1454 cfg.rc_resize_down_thresh = arg_parse_uint(&arg);
1455 else if (arg_match(&arg, &end_usage, argi))
1456 cfg.rc_end_usage = arg_parse_enum_or_int(&arg);
1457 else if (arg_match(&arg, &target_bitrate, argi))
1458 cfg.rc_target_bitrate = arg_parse_uint(&arg);
1459 else if (arg_match(&arg, &max_intra_rate_pct, argi))
1460 cfg.rc_max_intra_bitrate_pct = arg_parse_uint(&arg);
1461 else if (arg_match(&arg, &min_quantizer, argi))
1462 cfg.rc_min_quantizer = arg_parse_uint(&arg);
1463 else if (arg_match(&arg, &max_quantizer, argi))
1464 cfg.rc_max_quantizer = arg_parse_uint(&arg);
1465 else if (arg_match(&arg, &undershoot_pct, argi))
1466 cfg.rc_undershoot_pct = arg_parse_uint(&arg);
1467 else if (arg_match(&arg, &overshoot_pct, argi))
1468 cfg.rc_overshoot_pct = arg_parse_uint(&arg);
1469 else if (arg_match(&arg, &buf_sz, argi))
1470 cfg.rc_buf_sz = arg_parse_uint(&arg);
1471 else if (arg_match(&arg, &buf_initial_sz, argi))
1472 cfg.rc_buf_initial_sz = arg_parse_uint(&arg);
1473 else if (arg_match(&arg, &buf_optimal_sz, argi))
1474 cfg.rc_buf_optimal_sz = arg_parse_uint(&arg);
1475 else if (arg_match(&arg, &bias_pct, argi))
1477 cfg.rc_2pass_vbr_bias_pct = arg_parse_uint(&arg);
1481 "Warning: option %s ignored in one-pass mode.\n",
1484 else if (arg_match(&arg, &minsection_pct, argi))
1486 cfg.rc_2pass_vbr_minsection_pct = arg_parse_uint(&arg);
1490 "Warning: option %s ignored in one-pass mode.\n",
1493 else if (arg_match(&arg, &maxsection_pct, argi))
1495 cfg.rc_2pass_vbr_maxsection_pct = arg_parse_uint(&arg);
1499 "Warning: option %s ignored in one-pass mode.\n",
1502 else if (arg_match(&arg, &kf_min_dist, argi))
1503 cfg.kf_min_dist = arg_parse_uint(&arg);
1504 else if (arg_match(&arg, &kf_max_dist, argi))
1505 cfg.kf_max_dist = arg_parse_uint(&arg);
1506 else if (arg_match(&arg, &kf_disabled, argi))
1507 cfg.kf_mode = VPX_KF_DISABLED;
1512 /* Handle codec specific options */
1513 #if CONFIG_VP8_ENCODER
1515 if (codec->iface == &vpx_codec_vp8_cx_algo)
1517 ctrl_args = vp8_args;
1518 ctrl_args_map = vp8_arg_ctrl_map;
1523 for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step)
1529 for (i = 0; ctrl_args[i]; i++)
1531 if (arg_match(&arg, ctrl_args[i], argi))
1535 if (arg_ctrl_cnt < ARG_CTRL_CNT_MAX)
1537 arg_ctrls[arg_ctrl_cnt][0] = ctrl_args_map[i];
1538 arg_ctrls[arg_ctrl_cnt][1] = arg_parse_enum_or_int(&arg);
1548 /* Check for unrecognized options */
1549 for (argi = argv; *argi; argi++)
1550 if (argi[0][0] == '-' && argi[0][1])
1551 die("Error: Unrecognized option %s\n", *argi);
1553 /* Handle non-option arguments */
1560 die("Error: Output file is required (specify with -o)\n");
1562 memset(&stats, 0, sizeof(stats));
1564 for (pass = one_pass_only ? one_pass_only - 1 : 0; pass < arg_passes; pass++)
1566 int frames_in = 0, frames_out = 0;
1567 unsigned long nbytes = 0;
1568 struct detect_buffer detect;
1570 /* Parse certain options from the input file, if possible */
1571 infile = strcmp(in_fn, "-") ? fopen(in_fn, "rb")
1572 : set_binary_mode(stdin);
1576 fprintf(stderr, "Failed to open input file\n");
1577 return EXIT_FAILURE;
1580 /* For RAW input sources, these bytes will applied on the first frame
1583 detect.buf_read = fread(detect.buf, 1, 4, infile);
1584 detect.position = 0;
1586 if (detect.buf_read == 4 && file_is_y4m(infile, &y4m, detect.buf))
1588 if (y4m_input_open(&y4m, infile, detect.buf, 4) >= 0)
1590 file_type = FILE_TYPE_Y4M;
1591 cfg.g_w = y4m.pic_w;
1592 cfg.g_h = y4m.pic_h;
1594 /* Use the frame rate from the file only if none was specified
1595 * on the command-line.
1597 if (!arg_have_framerate)
1599 arg_framerate.num = y4m.fps_n;
1600 arg_framerate.den = y4m.fps_d;
1607 fprintf(stderr, "Unsupported Y4M stream.\n");
1608 return EXIT_FAILURE;
1611 else if (detect.buf_read == 4 &&
1612 file_is_ivf(infile, &fourcc, &cfg.g_w, &cfg.g_h, &detect))
1614 file_type = FILE_TYPE_IVF;
1624 fprintf(stderr, "Unsupported fourcc (%08x) in IVF\n", fourcc);
1625 return EXIT_FAILURE;
1630 file_type = FILE_TYPE_RAW;
1633 if(!cfg.g_w || !cfg.g_h)
1635 fprintf(stderr, "Specify stream dimensions with --width (-w) "
1636 " and --height (-h).\n");
1637 return EXIT_FAILURE;
1640 #define SHOW(field) fprintf(stderr, " %-28s = %d\n", #field, cfg.field)
1642 if (verbose && pass == 0)
1644 fprintf(stderr, "Codec: %s\n", vpx_codec_iface_name(codec->iface));
1645 fprintf(stderr, "Source file: %s Format: %s\n", in_fn,
1646 arg_use_i420 ? "I420" : "YV12");
1647 fprintf(stderr, "Destination file: %s\n", out_fn);
1648 fprintf(stderr, "Encoder parameters:\n");
1655 SHOW(g_timebase.num);
1656 SHOW(g_timebase.den);
1657 SHOW(g_error_resilient);
1659 SHOW(g_lag_in_frames);
1660 SHOW(rc_dropframe_thresh);
1661 SHOW(rc_resize_allowed);
1662 SHOW(rc_resize_up_thresh);
1663 SHOW(rc_resize_down_thresh);
1665 SHOW(rc_target_bitrate);
1666 SHOW(rc_min_quantizer);
1667 SHOW(rc_max_quantizer);
1668 SHOW(rc_undershoot_pct);
1669 SHOW(rc_overshoot_pct);
1671 SHOW(rc_buf_initial_sz);
1672 SHOW(rc_buf_optimal_sz);
1673 SHOW(rc_2pass_vbr_bias_pct);
1674 SHOW(rc_2pass_vbr_minsection_pct);
1675 SHOW(rc_2pass_vbr_maxsection_pct);
1681 if(pass == (one_pass_only ? one_pass_only - 1 : 0)) {
1682 if (file_type == FILE_TYPE_Y4M)
1683 /*The Y4M reader does its own allocation.
1684 Just initialize this here to avoid problems if we never read any
1686 memset(&raw, 0, sizeof(raw));
1688 vpx_img_alloc(&raw, arg_use_i420 ? VPX_IMG_FMT_I420 : VPX_IMG_FMT_YV12,
1689 cfg.g_w, cfg.g_h, 1);
1692 outfile = strcmp(out_fn, "-") ? fopen(out_fn, "wb")
1693 : set_binary_mode(stdout);
1697 fprintf(stderr, "Failed to open output file\n");
1698 return EXIT_FAILURE;
1701 if(write_webm && fseek(outfile, 0, SEEK_CUR))
1703 fprintf(stderr, "WebM output to pipes not supported.\n");
1704 return EXIT_FAILURE;
1709 if (!stats_open_file(&stats, stats_fn, pass))
1711 fprintf(stderr, "Failed to open statistics store\n");
1712 return EXIT_FAILURE;
1717 if (!stats_open_mem(&stats, pass))
1719 fprintf(stderr, "Failed to open statistics store\n");
1720 return EXIT_FAILURE;
1724 cfg.g_pass = arg_passes == 2
1725 ? pass ? VPX_RC_LAST_PASS : VPX_RC_FIRST_PASS
1727 #if VPX_ENCODER_ABI_VERSION > (1 + VPX_CODEC_ABI_VERSION)
1731 cfg.rc_twopass_stats_in = stats_get(&stats);
1738 ebml.stream = outfile;
1739 write_webm_file_header(&ebml, &cfg, &arg_framerate, stereo_fmt);
1742 write_ivf_file_header(outfile, &cfg, codec->fourcc, 0);
1745 /* Construct Encoder Context */
1746 vpx_codec_enc_init(&encoder, codec->iface, &cfg,
1747 show_psnr ? VPX_CODEC_USE_PSNR : 0);
1748 ctx_exit_on_error(&encoder, "Failed to initialize encoder");
1750 /* Note that we bypass the vpx_codec_control wrapper macro because
1751 * we're being clever to store the control IDs in an array. Real
1752 * applications will want to make use of the enumerations directly
1754 for (i = 0; i < arg_ctrl_cnt; i++)
1756 if (vpx_codec_control_(&encoder, arg_ctrls[i][0], arg_ctrls[i][1]))
1757 fprintf(stderr, "Error: Tried to set control %d = %d\n",
1758 arg_ctrls[i][0], arg_ctrls[i][1]);
1760 ctx_exit_on_error(&encoder, "Failed to control codec");
1766 while (frame_avail || got_data)
1768 vpx_codec_iter_t iter = NULL;
1769 const vpx_codec_cx_pkt_t *pkt;
1770 struct vpx_usec_timer timer;
1771 int64_t frame_start, next_frame_start;
1773 if (!arg_limit || frames_in < arg_limit)
1775 frame_avail = read_frame(infile, &raw, file_type, &y4m,
1782 "\rPass %d/%d frame %4d/%-4d %7ldB \033[K", pass + 1,
1783 arg_passes, frames_in, frames_out, nbytes);
1788 vpx_usec_timer_start(&timer);
1790 frame_start = (cfg.g_timebase.den * (int64_t)(frames_in - 1)
1791 * arg_framerate.den) / cfg.g_timebase.num / arg_framerate.num;
1792 next_frame_start = (cfg.g_timebase.den * (int64_t)(frames_in)
1793 * arg_framerate.den)
1794 / cfg.g_timebase.num / arg_framerate.num;
1795 vpx_codec_encode(&encoder, frame_avail ? &raw : NULL, frame_start,
1796 next_frame_start - frame_start,
1798 vpx_usec_timer_mark(&timer);
1799 cx_time += vpx_usec_timer_elapsed(&timer);
1800 ctx_exit_on_error(&encoder, "Failed to encode frame");
1802 if(cfg.g_pass != VPX_RC_FIRST_PASS)
1806 vpx_codec_control(&encoder, VP8E_GET_LAST_QUANTIZER_64, &q);
1807 ctx_exit_on_error(&encoder, "Failed to read quantizer");
1813 while ((pkt = vpx_codec_get_cx_data(&encoder, &iter)))
1819 case VPX_CODEC_CX_FRAME_PKT:
1821 fprintf(stderr, " %6luF",
1822 (unsigned long)pkt->data.frame.sz);
1826 /* Update the hash */
1828 hash = murmur(pkt->data.frame.buf,
1829 pkt->data.frame.sz, hash);
1831 write_webm_block(&ebml, &cfg, pkt);
1835 write_ivf_frame_header(outfile, pkt);
1836 if(fwrite(pkt->data.frame.buf, 1,
1837 pkt->data.frame.sz, outfile));
1839 nbytes += pkt->data.raw.sz;
1841 case VPX_CODEC_STATS_PKT:
1843 fprintf(stderr, " %6luS",
1844 (unsigned long)pkt->data.twopass_stats.sz);
1846 pkt->data.twopass_stats.buf,
1847 pkt->data.twopass_stats.sz);
1848 nbytes += pkt->data.raw.sz;
1850 case VPX_CODEC_PSNR_PKT:
1856 psnr_sse_total += pkt->data.psnr.sse[0];
1857 psnr_samples_total += pkt->data.psnr.samples[0];
1858 for (i = 0; i < 4; i++)
1860 fprintf(stderr, "%.3lf ", pkt->data.psnr.psnr[i]);
1861 psnr_totals[i] += pkt->data.psnr.psnr[i];
1876 "\rPass %d/%d frame %4d/%-4d %7ldB %7ldb/f %7"PRId64"b/s"
1877 " %7lu %s (%.2f fps)\033[K", pass + 1,
1878 arg_passes, frames_in, frames_out, nbytes, nbytes * 8 / frames_in,
1879 nbytes * 8 *(int64_t)arg_framerate.num / arg_framerate.den / frames_in,
1880 cx_time > 9999999 ? cx_time / 1000 : cx_time,
1881 cx_time > 9999999 ? "ms" : "us",
1882 (float)frames_in * 1000000.0 / (float)cx_time);
1884 if ( (show_psnr) && (psnr_count>0) )
1887 double ovpsnr = vp8_mse2psnr(psnr_samples_total, 255.0,
1890 fprintf(stderr, "\nPSNR (Overall/Avg/Y/U/V)");
1892 fprintf(stderr, " %.3lf", ovpsnr);
1893 for (i = 0; i < 4; i++)
1895 fprintf(stderr, " %.3lf", psnr_totals[i]/psnr_count);
1899 vpx_codec_destroy(&encoder);
1905 write_webm_file_footer(&ebml, hash);
1909 if (!fseek(outfile, 0, SEEK_SET))
1910 write_ivf_file_header(outfile, &cfg, codec->fourcc, frames_out);
1914 stats_close(&stats, arg_passes-1);
1915 fprintf(stderr, "\n");
1921 if (show_q_hist_buckets)
1922 show_q_histogram(counts, show_q_hist_buckets);
1926 return EXIT_SUCCESS;