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/vp8cx.h"
36 #include "vpx_ports/mem_ops.h"
37 #include "vpx_ports/vpx_timer.h"
38 #include "tools_common.h"
40 #include "libmkv/EbmlWriter.h"
41 #include "libmkv/EbmlIDs.h"
43 /* Need special handling of these functions on Windows */
45 /* MSVS doesn't define off_t, and uses _f{seek,tell}i64 */
46 typedef __int64 off_t;
47 #define fseeko _fseeki64
48 #define ftello _ftelli64
50 /* MinGW defines off_t as long
51 and uses f{seek,tell}o64/off64_t for large files */
52 #define fseeko fseeko64
53 #define ftello ftello64
58 #define LITERALU64(n) n
60 #define LITERALU64(n) n##LLU
63 /* We should use 32-bit file operations in WebM file format
64 * when building ARM executable file (.axf) with RVCT */
65 #if !CONFIG_OS_SUPPORT
71 static const char *exec_name;
73 static const struct codec_item
76 const vpx_codec_iface_t *iface;
80 #if CONFIG_VP8_ENCODER
81 {"vp8", &vpx_codec_vp8_cx_algo, 0x30385056},
85 static void usage_exit();
87 #define LOG_ERROR(label) do \
93 fprintf(stderr, "%s: ", l);\
94 vfprintf(stderr, fmt, ap);\
95 fprintf(stderr, "\n");\
99 void die(const char *fmt, ...)
106 void fatal(const char *fmt, ...)
113 void warn(const char *fmt, ...)
115 LOG_ERROR("Warning");
119 static void ctx_exit_on_error(vpx_codec_ctx_t *ctx, const char *s, ...)
126 const char *detail = vpx_codec_error_detail(ctx);
128 vfprintf(stderr, s, ap);
129 fprintf(stderr, ": %s\n", vpx_codec_error(ctx));
132 fprintf(stderr, " %s\n", detail);
138 /* This structure is used to abstract the different ways of handling
139 * first pass statistics.
150 int stats_open_file(stats_io_t *stats, const char *fpf, int pass)
158 stats->file = fopen(fpf, "wb");
160 stats->buf.buf = NULL,
161 res = (stats->file != NULL);
167 struct stat stat_buf;
170 fd = open(fpf, O_RDONLY);
171 stats->file = fdopen(fd, "rb");
172 fstat(fd, &stat_buf);
173 stats->buf.sz = stat_buf.st_size;
174 stats->buf.buf = mmap(NULL, stats->buf.sz, PROT_READ, MAP_PRIVATE,
176 res = (stats->buf.buf != NULL);
180 stats->file = fopen(fpf, "rb");
182 if (fseek(stats->file, 0, SEEK_END))
183 fatal("First-pass stats file must be seekable!");
185 stats->buf.sz = stats->buf_alloc_sz = ftell(stats->file);
188 stats->buf.buf = malloc(stats->buf_alloc_sz);
191 fatal("Failed to allocate first-pass stats buffer (%lu bytes)",
192 (unsigned long)stats->buf_alloc_sz);
194 nbytes = fread(stats->buf.buf, 1, stats->buf.sz, stats->file);
195 res = (nbytes == stats->buf.sz);
202 int stats_open_mem(stats_io_t *stats, int pass)
210 stats->buf_alloc_sz = 64 * 1024;
211 stats->buf.buf = malloc(stats->buf_alloc_sz);
214 stats->buf_ptr = stats->buf.buf;
215 res = (stats->buf.buf != NULL);
220 void stats_close(stats_io_t *stats, int last_pass)
224 if (stats->pass == last_pass)
228 munmap(stats->buf.buf, stats->buf.sz);
230 free(stats->buf.buf);
239 if (stats->pass == last_pass)
240 free(stats->buf.buf);
244 void stats_write(stats_io_t *stats, const void *pkt, size_t len)
248 (void) fwrite(pkt, 1, len, stats->file);
252 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);
259 stats->buf_ptr = new_ptr + (stats->buf_ptr - (char *)stats->buf.buf);
260 stats->buf.buf = new_ptr;
261 stats->buf_alloc_sz = new_sz;
264 fatal("Failed to realloc firstpass stats buffer.");
267 memcpy(stats->buf_ptr, pkt, len);
268 stats->buf.sz += len;
269 stats->buf_ptr += len;
273 vpx_fixed_buf_t stats_get(stats_io_t *stats)
278 /* Stereo 3D packed frame format */
279 typedef enum stereo_format
281 STEREO_FORMAT_MONO = 0,
282 STEREO_FORMAT_LEFT_RIGHT = 1,
283 STEREO_FORMAT_BOTTOM_TOP = 2,
284 STEREO_FORMAT_TOP_BOTTOM = 3,
285 STEREO_FORMAT_RIGHT_LEFT = 11
295 struct detect_buffer {
307 struct detect_buffer detect;
308 enum video_file_type file_type;
311 struct vpx_rational framerate;
316 #define IVF_FRAME_HDR_SZ (4+8) /* 4 byte size + 8 byte timestamp */
317 static int read_frame(struct input_state *input, vpx_image_t *img)
319 FILE *f = input->file;
320 enum video_file_type file_type = input->file_type;
321 y4m_input *y4m = &input->y4m;
322 struct detect_buffer *detect = &input->detect;
326 if (file_type == FILE_TYPE_Y4M)
328 if (y4m_input_fetch_frame(y4m, f, img) < 1)
333 if (file_type == FILE_TYPE_IVF)
335 char junk[IVF_FRAME_HDR_SZ];
337 /* Skip the frame header. We know how big the frame should be. See
338 * write_ivf_frame_header() for documentation on the frame header
341 (void) fread(junk, 1, IVF_FRAME_HDR_SZ, f);
344 for (plane = 0; plane < 3; plane++)
347 int w = (plane ? (1 + img->d_w) / 2 : img->d_w);
348 int h = (plane ? (1 + img->d_h) / 2 : img->d_h);
351 /* Determine the correct plane based on the image format. The for-loop
352 * always counts in Y,U,V order, but this may not match the order of
358 ptr = img->planes[img->fmt==VPX_IMG_FMT_YV12? VPX_PLANE_V : VPX_PLANE_U];
361 ptr = img->planes[img->fmt==VPX_IMG_FMT_YV12?VPX_PLANE_U : VPX_PLANE_V];
364 ptr = img->planes[plane];
367 for (r = 0; r < h; r++)
370 size_t buf_position = 0;
371 const size_t left = detect->buf_read - detect->position;
374 const size_t more = (left < needed) ? left : needed;
375 memcpy(ptr, detect->buf + detect->position, more);
378 detect->position += more;
382 shortread |= (fread(ptr + buf_position, 1, needed, f) < needed);
385 ptr += img->stride[plane];
394 unsigned int file_is_y4m(FILE *infile,
398 if(memcmp(detect, "YUV4", 4) == 0)
405 #define IVF_FILE_HDR_SZ (32)
406 unsigned int file_is_ivf(struct input_state *input,
407 unsigned int *fourcc)
409 char raw_hdr[IVF_FILE_HDR_SZ];
411 FILE *infile = input->file;
412 unsigned int *width = &input->w;
413 unsigned int *height = &input->h;
414 struct detect_buffer *detect = &input->detect;
416 if(memcmp(detect->buf, "DKIF", 4) != 0)
419 /* See write_ivf_file_header() for more documentation on the file header
422 if (fread(raw_hdr + 4, 1, IVF_FILE_HDR_SZ - 4, infile)
423 == IVF_FILE_HDR_SZ - 4)
428 if (mem_get_le16(raw_hdr + 4) != 0)
429 warn("Unrecognized IVF version! This file may not decode "
432 *fourcc = mem_get_le32(raw_hdr + 8);
438 *width = mem_get_le16(raw_hdr + 12);
439 *height = mem_get_le16(raw_hdr + 14);
440 detect->position = 4;
447 static void write_ivf_file_header(FILE *outfile,
448 const vpx_codec_enc_cfg_t *cfg,
454 if (cfg->g_pass != VPX_RC_ONE_PASS && cfg->g_pass != VPX_RC_LAST_PASS)
461 mem_put_le16(header + 4, 0); /* version */
462 mem_put_le16(header + 6, 32); /* headersize */
463 mem_put_le32(header + 8, fourcc); /* headersize */
464 mem_put_le16(header + 12, cfg->g_w); /* width */
465 mem_put_le16(header + 14, cfg->g_h); /* height */
466 mem_put_le32(header + 16, cfg->g_timebase.den); /* rate */
467 mem_put_le32(header + 20, cfg->g_timebase.num); /* scale */
468 mem_put_le32(header + 24, frame_cnt); /* length */
469 mem_put_le32(header + 28, 0); /* unused */
471 (void) fwrite(header, 1, 32, outfile);
475 static void write_ivf_frame_header(FILE *outfile,
476 const vpx_codec_cx_pkt_t *pkt)
481 if (pkt->kind != VPX_CODEC_CX_FRAME_PKT)
484 pts = pkt->data.frame.pts;
485 mem_put_le32(header, pkt->data.frame.sz);
486 mem_put_le32(header + 4, pts & 0xFFFFFFFF);
487 mem_put_le32(header + 8, pts >> 32);
489 (void) fwrite(header, 1, 12, outfile);
492 static void write_ivf_frame_size(FILE *outfile, size_t size)
495 mem_put_le32(header, size);
496 (void) fwrite(header, 1, 4, outfile);
500 typedef off_t EbmlLoc;
516 vpx_rational_t framerate;
518 /* These pointers are to the start of an element */
519 off_t position_reference;
521 off_t segment_info_pos;
526 /* This pointer is to a specific element to be serialized */
529 /* These pointers are to the size field of the element */
530 EbmlLoc startSegment;
531 EbmlLoc startCluster;
533 uint32_t cluster_timecode;
536 struct cue_entry *cue_list;
542 void Ebml_Write(EbmlGlobal *glob, const void *buffer_in, unsigned long len)
544 (void) fwrite(buffer_in, 1, len, glob->stream);
547 #define WRITE_BUFFER(s) \
548 for(i = len-1; i>=0; i--)\
550 x = *(const s *)buffer_in >> (i * CHAR_BIT); \
551 Ebml_Write(glob, &x, 1); \
553 void Ebml_Serialize(EbmlGlobal *glob, const void *buffer_in, int buffer_size, unsigned long len)
570 WRITE_BUFFER(int16_t)
573 WRITE_BUFFER(int32_t)
576 WRITE_BUFFER(int64_t)
584 /* Need a fixed size serializer for the track ID. libmkv provides a 64 bit
585 * one, but not a 32 bit one.
587 static void Ebml_SerializeUnsigned32(EbmlGlobal *glob, unsigned long class_id, uint64_t ui)
589 unsigned char sizeSerialized = 4 | 0x80;
590 Ebml_WriteID(glob, class_id);
591 Ebml_Serialize(glob, &sizeSerialized, sizeof(sizeSerialized), 1);
592 Ebml_Serialize(glob, &ui, sizeof(ui), 4);
597 Ebml_StartSubElement(EbmlGlobal *glob, EbmlLoc *ebmlLoc,
598 unsigned long class_id)
600 //todo this is always taking 8 bytes, this may need later optimization
601 //this is a key that says length unknown
602 uint64_t unknownLen = LITERALU64(0x01FFFFFFFFFFFFFF);
604 Ebml_WriteID(glob, class_id);
605 *ebmlLoc = ftello(glob->stream);
606 Ebml_Serialize(glob, &unknownLen, sizeof(unknownLen), 8);
610 Ebml_EndSubElement(EbmlGlobal *glob, EbmlLoc *ebmlLoc)
615 /* Save the current stream pointer */
616 pos = ftello(glob->stream);
618 /* Calculate the size of this element */
619 size = pos - *ebmlLoc - 8;
620 size |= LITERALU64(0x0100000000000000);
622 /* Seek back to the beginning of the element and write the new size */
623 fseeko(glob->stream, *ebmlLoc, SEEK_SET);
624 Ebml_Serialize(glob, &size, sizeof(size), 8);
626 /* Reset the stream pointer */
627 fseeko(glob->stream, pos, SEEK_SET);
632 write_webm_seek_element(EbmlGlobal *ebml, unsigned long id, off_t pos)
634 uint64_t offset = pos - ebml->position_reference;
636 Ebml_StartSubElement(ebml, &start, Seek);
637 Ebml_SerializeBinary(ebml, SeekID, id);
638 Ebml_SerializeUnsigned64(ebml, SeekPosition, offset);
639 Ebml_EndSubElement(ebml, &start);
644 write_webm_seek_info(EbmlGlobal *ebml)
649 /* Save the current stream pointer */
650 pos = ftello(ebml->stream);
652 if(ebml->seek_info_pos)
653 fseeko(ebml->stream, ebml->seek_info_pos, SEEK_SET);
655 ebml->seek_info_pos = pos;
660 Ebml_StartSubElement(ebml, &start, SeekHead);
661 write_webm_seek_element(ebml, Tracks, ebml->track_pos);
662 write_webm_seek_element(ebml, Cues, ebml->cue_pos);
663 write_webm_seek_element(ebml, Info, ebml->segment_info_pos);
664 Ebml_EndSubElement(ebml, &start);
670 char version_string[64];
672 /* Assemble version string */
674 strcpy(version_string, "vpxenc");
677 strcpy(version_string, "vpxenc ");
678 strncat(version_string,
679 vpx_codec_version_str(),
680 sizeof(version_string) - 1 - strlen(version_string));
683 frame_time = (uint64_t)1000 * ebml->framerate.den
684 / ebml->framerate.num;
685 ebml->segment_info_pos = ftello(ebml->stream);
686 Ebml_StartSubElement(ebml, &startInfo, Info);
687 Ebml_SerializeUnsigned(ebml, TimecodeScale, 1000000);
688 Ebml_SerializeFloat(ebml, Segment_Duration,
689 ebml->last_pts_ms + frame_time);
690 Ebml_SerializeString(ebml, 0x4D80, version_string);
691 Ebml_SerializeString(ebml, 0x5741, version_string);
692 Ebml_EndSubElement(ebml, &startInfo);
698 write_webm_file_header(EbmlGlobal *glob,
699 const vpx_codec_enc_cfg_t *cfg,
700 const struct vpx_rational *fps,
701 stereo_format_t stereo_fmt)
705 Ebml_StartSubElement(glob, &start, EBML);
706 Ebml_SerializeUnsigned(glob, EBMLVersion, 1);
707 Ebml_SerializeUnsigned(glob, EBMLReadVersion, 1); //EBML Read Version
708 Ebml_SerializeUnsigned(glob, EBMLMaxIDLength, 4); //EBML Max ID Length
709 Ebml_SerializeUnsigned(glob, EBMLMaxSizeLength, 8); //EBML Max Size Length
710 Ebml_SerializeString(glob, DocType, "webm"); //Doc Type
711 Ebml_SerializeUnsigned(glob, DocTypeVersion, 2); //Doc Type Version
712 Ebml_SerializeUnsigned(glob, DocTypeReadVersion, 2); //Doc Type Read Version
713 Ebml_EndSubElement(glob, &start);
716 Ebml_StartSubElement(glob, &glob->startSegment, Segment); //segment
717 glob->position_reference = ftello(glob->stream);
718 glob->framerate = *fps;
719 write_webm_seek_info(glob);
723 glob->track_pos = ftello(glob->stream);
724 Ebml_StartSubElement(glob, &trackStart, Tracks);
726 unsigned int trackNumber = 1;
727 uint64_t trackID = 0;
730 Ebml_StartSubElement(glob, &start, TrackEntry);
731 Ebml_SerializeUnsigned(glob, TrackNumber, trackNumber);
732 glob->track_id_pos = ftello(glob->stream);
733 Ebml_SerializeUnsigned32(glob, TrackUID, trackID);
734 Ebml_SerializeUnsigned(glob, TrackType, 1); //video is always 1
735 Ebml_SerializeString(glob, CodecID, "V_VP8");
737 unsigned int pixelWidth = cfg->g_w;
738 unsigned int pixelHeight = cfg->g_h;
739 float frameRate = (float)fps->num/(float)fps->den;
742 Ebml_StartSubElement(glob, &videoStart, Video);
743 Ebml_SerializeUnsigned(glob, PixelWidth, pixelWidth);
744 Ebml_SerializeUnsigned(glob, PixelHeight, pixelHeight);
745 Ebml_SerializeUnsigned(glob, StereoMode, stereo_fmt);
746 Ebml_SerializeFloat(glob, FrameRate, frameRate);
747 Ebml_EndSubElement(glob, &videoStart); //Video
749 Ebml_EndSubElement(glob, &start); //Track Entry
751 Ebml_EndSubElement(glob, &trackStart);
753 // segment element is open
759 write_webm_block(EbmlGlobal *glob,
760 const vpx_codec_enc_cfg_t *cfg,
761 const vpx_codec_cx_pkt_t *pkt)
763 unsigned long block_length;
764 unsigned char track_number;
765 unsigned short block_timecode = 0;
768 int start_cluster = 0, is_keyframe;
770 /* Calculate the PTS of this frame in milliseconds */
771 pts_ms = pkt->data.frame.pts * 1000
772 * (uint64_t)cfg->g_timebase.num / (uint64_t)cfg->g_timebase.den;
773 if(pts_ms <= glob->last_pts_ms)
774 pts_ms = glob->last_pts_ms + 1;
775 glob->last_pts_ms = pts_ms;
777 /* Calculate the relative time of this block */
778 if(pts_ms - glob->cluster_timecode > SHRT_MAX)
781 block_timecode = pts_ms - glob->cluster_timecode;
783 is_keyframe = (pkt->data.frame.flags & VPX_FRAME_IS_KEY);
784 if(start_cluster || is_keyframe)
786 if(glob->cluster_open)
787 Ebml_EndSubElement(glob, &glob->startCluster);
789 /* Open the new cluster */
791 glob->cluster_open = 1;
792 glob->cluster_timecode = pts_ms;
793 glob->cluster_pos = ftello(glob->stream);
794 Ebml_StartSubElement(glob, &glob->startCluster, Cluster); //cluster
795 Ebml_SerializeUnsigned(glob, Timecode, glob->cluster_timecode);
797 /* Save a cue point if this is a keyframe. */
800 struct cue_entry *cue, *new_cue_list;
802 new_cue_list = realloc(glob->cue_list,
803 (glob->cues+1) * sizeof(struct cue_entry));
805 glob->cue_list = new_cue_list;
807 fatal("Failed to realloc cue list.");
809 cue = &glob->cue_list[glob->cues];
810 cue->time = glob->cluster_timecode;
811 cue->loc = glob->cluster_pos;
816 /* Write the Simple Block */
817 Ebml_WriteID(glob, SimpleBlock);
819 block_length = pkt->data.frame.sz + 4;
820 block_length |= 0x10000000;
821 Ebml_Serialize(glob, &block_length, sizeof(block_length), 4);
824 track_number |= 0x80;
825 Ebml_Write(glob, &track_number, 1);
827 Ebml_Serialize(glob, &block_timecode, sizeof(block_timecode), 2);
832 if(pkt->data.frame.flags & VPX_FRAME_IS_INVISIBLE)
834 Ebml_Write(glob, &flags, 1);
836 Ebml_Write(glob, pkt->data.frame.buf, pkt->data.frame.sz);
841 write_webm_file_footer(EbmlGlobal *glob, long hash)
844 if(glob->cluster_open)
845 Ebml_EndSubElement(glob, &glob->startCluster);
851 glob->cue_pos = ftello(glob->stream);
852 Ebml_StartSubElement(glob, &start, Cues);
853 for(i=0; i<glob->cues; i++)
855 struct cue_entry *cue = &glob->cue_list[i];
858 Ebml_StartSubElement(glob, &start, CuePoint);
862 Ebml_SerializeUnsigned(glob, CueTime, cue->time);
864 Ebml_StartSubElement(glob, &start, CueTrackPositions);
865 Ebml_SerializeUnsigned(glob, CueTrack, 1);
866 Ebml_SerializeUnsigned64(glob, CueClusterPosition,
867 cue->loc - glob->position_reference);
868 //Ebml_SerializeUnsigned(glob, CueBlockNumber, cue->blockNumber);
869 Ebml_EndSubElement(glob, &start);
871 Ebml_EndSubElement(glob, &start);
873 Ebml_EndSubElement(glob, &start);
876 Ebml_EndSubElement(glob, &glob->startSegment);
878 /* Patch up the seek info block */
879 write_webm_seek_info(glob);
881 /* Patch up the track id */
882 fseeko(glob->stream, glob->track_id_pos, SEEK_SET);
883 Ebml_SerializeUnsigned32(glob, TrackUID, glob->debug ? 0xDEADBEEF : hash);
885 fseeko(glob->stream, 0, SEEK_END);
889 /* Murmur hash derived from public domain reference implementation at
890 * http://sites.google.com/site/murmurhash/
892 static unsigned int murmur ( const void * key, int len, unsigned int seed )
894 const unsigned int m = 0x5bd1e995;
897 unsigned int h = seed ^ len;
899 const unsigned char * data = (const unsigned char *)key;
923 case 3: h ^= data[2] << 16;
924 case 2: h ^= data[1] << 8;
925 case 1: h ^= data[0];
938 static double vp8_mse2psnr(double Samples, double Peak, double Mse)
942 if ((double)Mse > 0.0)
943 psnr = 10.0 * log10(Peak * Peak * Samples / Mse);
945 psnr = 60; // Limit to prevent / 0
955 static const arg_def_t debugmode = ARG_DEF("D", "debug", 0,
956 "Debug mode (makes output deterministic)");
957 static const arg_def_t outputfile = ARG_DEF("o", "output", 1,
959 static const arg_def_t use_yv12 = ARG_DEF(NULL, "yv12", 0,
960 "Input file is YV12 ");
961 static const arg_def_t use_i420 = ARG_DEF(NULL, "i420", 0,
962 "Input file is I420 (default)");
963 static const arg_def_t codecarg = ARG_DEF(NULL, "codec", 1,
965 static const arg_def_t passes = ARG_DEF("p", "passes", 1,
966 "Number of passes (1/2)");
967 static const arg_def_t pass_arg = ARG_DEF(NULL, "pass", 1,
968 "Pass to execute (1/2)");
969 static const arg_def_t fpf_name = ARG_DEF(NULL, "fpf", 1,
970 "First pass statistics file name");
971 static const arg_def_t limit = ARG_DEF(NULL, "limit", 1,
972 "Stop encoding after n input frames");
973 static const arg_def_t deadline = ARG_DEF("d", "deadline", 1,
974 "Deadline per frame (usec)");
975 static const arg_def_t best_dl = ARG_DEF(NULL, "best", 0,
976 "Use Best Quality Deadline");
977 static const arg_def_t good_dl = ARG_DEF(NULL, "good", 0,
978 "Use Good Quality Deadline");
979 static const arg_def_t rt_dl = ARG_DEF(NULL, "rt", 0,
980 "Use Realtime Quality Deadline");
981 static const arg_def_t verbosearg = ARG_DEF("v", "verbose", 0,
982 "Show encoder parameters");
983 static const arg_def_t psnrarg = ARG_DEF(NULL, "psnr", 0,
984 "Show PSNR in status line");
985 static const arg_def_t framerate = ARG_DEF(NULL, "fps", 1,
986 "Stream frame rate (rate/scale)");
987 static const arg_def_t use_ivf = ARG_DEF(NULL, "ivf", 0,
988 "Output IVF (default is WebM)");
989 static const arg_def_t out_part = ARG_DEF("P", "output-partitions", 0,
990 "Makes encoder output partitions. Requires IVF output!");
991 static const arg_def_t q_hist_n = ARG_DEF(NULL, "q-hist", 1,
992 "Show quantizer histogram (n-buckets)");
993 static const arg_def_t rate_hist_n = ARG_DEF(NULL, "rate-hist", 1,
994 "Show rate histogram (n-buckets)");
995 static const arg_def_t *main_args[] =
998 &outputfile, &codecarg, &passes, &pass_arg, &fpf_name, &limit, &deadline,
999 &best_dl, &good_dl, &rt_dl,
1000 &verbosearg, &psnrarg, &use_ivf, &out_part, &q_hist_n, &rate_hist_n,
1004 static const arg_def_t usage = ARG_DEF("u", "usage", 1,
1005 "Usage profile number to use");
1006 static const arg_def_t threads = ARG_DEF("t", "threads", 1,
1007 "Max number of threads to use");
1008 static const arg_def_t profile = ARG_DEF(NULL, "profile", 1,
1009 "Bitstream profile number to use");
1010 static const arg_def_t width = ARG_DEF("w", "width", 1,
1012 static const arg_def_t height = ARG_DEF("h", "height", 1,
1014 static const struct arg_enum_list stereo_mode_enum[] = {
1015 {"mono" , STEREO_FORMAT_MONO},
1016 {"left-right", STEREO_FORMAT_LEFT_RIGHT},
1017 {"bottom-top", STEREO_FORMAT_BOTTOM_TOP},
1018 {"top-bottom", STEREO_FORMAT_TOP_BOTTOM},
1019 {"right-left", STEREO_FORMAT_RIGHT_LEFT},
1022 static const arg_def_t stereo_mode = ARG_DEF_ENUM(NULL, "stereo-mode", 1,
1023 "Stereo 3D video format", stereo_mode_enum);
1024 static const arg_def_t timebase = ARG_DEF(NULL, "timebase", 1,
1025 "Output timestamp precision (fractional seconds)");
1026 static const arg_def_t error_resilient = ARG_DEF(NULL, "error-resilient", 1,
1027 "Enable error resiliency features");
1028 static const arg_def_t lag_in_frames = ARG_DEF(NULL, "lag-in-frames", 1,
1029 "Max number of frames to lag");
1031 static const arg_def_t *global_args[] =
1033 &use_yv12, &use_i420, &usage, &threads, &profile,
1034 &width, &height, &stereo_mode, &timebase, &framerate, &error_resilient,
1035 &lag_in_frames, NULL
1038 static const arg_def_t dropframe_thresh = ARG_DEF(NULL, "drop-frame", 1,
1039 "Temporal resampling threshold (buf %)");
1040 static const arg_def_t resize_allowed = ARG_DEF(NULL, "resize-allowed", 1,
1041 "Spatial resampling enabled (bool)");
1042 static const arg_def_t resize_up_thresh = ARG_DEF(NULL, "resize-up", 1,
1043 "Upscale threshold (buf %)");
1044 static const arg_def_t resize_down_thresh = ARG_DEF(NULL, "resize-down", 1,
1045 "Downscale threshold (buf %)");
1046 static const struct arg_enum_list end_usage_enum[] = {
1052 static const arg_def_t end_usage = ARG_DEF_ENUM(NULL, "end-usage", 1,
1053 "Rate control mode", end_usage_enum);
1054 static const arg_def_t target_bitrate = ARG_DEF(NULL, "target-bitrate", 1,
1056 static const arg_def_t min_quantizer = ARG_DEF(NULL, "min-q", 1,
1057 "Minimum (best) quantizer");
1058 static const arg_def_t max_quantizer = ARG_DEF(NULL, "max-q", 1,
1059 "Maximum (worst) quantizer");
1060 static const arg_def_t undershoot_pct = ARG_DEF(NULL, "undershoot-pct", 1,
1061 "Datarate undershoot (min) target (%)");
1062 static const arg_def_t overshoot_pct = ARG_DEF(NULL, "overshoot-pct", 1,
1063 "Datarate overshoot (max) target (%)");
1064 static const arg_def_t buf_sz = ARG_DEF(NULL, "buf-sz", 1,
1065 "Client buffer size (ms)");
1066 static const arg_def_t buf_initial_sz = ARG_DEF(NULL, "buf-initial-sz", 1,
1067 "Client initial buffer size (ms)");
1068 static const arg_def_t buf_optimal_sz = ARG_DEF(NULL, "buf-optimal-sz", 1,
1069 "Client optimal buffer size (ms)");
1070 static const arg_def_t *rc_args[] =
1072 &dropframe_thresh, &resize_allowed, &resize_up_thresh, &resize_down_thresh,
1073 &end_usage, &target_bitrate, &min_quantizer, &max_quantizer,
1074 &undershoot_pct, &overshoot_pct, &buf_sz, &buf_initial_sz, &buf_optimal_sz,
1079 static const arg_def_t bias_pct = ARG_DEF(NULL, "bias-pct", 1,
1080 "CBR/VBR bias (0=CBR, 100=VBR)");
1081 static const arg_def_t minsection_pct = ARG_DEF(NULL, "minsection-pct", 1,
1082 "GOP min bitrate (% of target)");
1083 static const arg_def_t maxsection_pct = ARG_DEF(NULL, "maxsection-pct", 1,
1084 "GOP max bitrate (% of target)");
1085 static const arg_def_t *rc_twopass_args[] =
1087 &bias_pct, &minsection_pct, &maxsection_pct, NULL
1091 static const arg_def_t kf_min_dist = ARG_DEF(NULL, "kf-min-dist", 1,
1092 "Minimum keyframe interval (frames)");
1093 static const arg_def_t kf_max_dist = ARG_DEF(NULL, "kf-max-dist", 1,
1094 "Maximum keyframe interval (frames)");
1095 static const arg_def_t kf_disabled = ARG_DEF(NULL, "disable-kf", 0,
1096 "Disable keyframe placement");
1097 static const arg_def_t *kf_args[] =
1099 &kf_min_dist, &kf_max_dist, &kf_disabled, NULL
1103 #if CONFIG_VP8_ENCODER
1104 static const arg_def_t noise_sens = ARG_DEF(NULL, "noise-sensitivity", 1,
1105 "Noise sensitivity (frames to blur)");
1106 static const arg_def_t sharpness = ARG_DEF(NULL, "sharpness", 1,
1107 "Filter sharpness (0-7)");
1108 static const arg_def_t static_thresh = ARG_DEF(NULL, "static-thresh", 1,
1109 "Motion detection threshold");
1112 #if CONFIG_VP8_ENCODER
1113 static const arg_def_t cpu_used = ARG_DEF(NULL, "cpu-used", 1,
1114 "CPU Used (-16..16)");
1118 #if CONFIG_VP8_ENCODER
1119 static const arg_def_t token_parts = ARG_DEF(NULL, "token-parts", 1,
1120 "Number of token partitions to use, log2");
1121 static const arg_def_t auto_altref = ARG_DEF(NULL, "auto-alt-ref", 1,
1122 "Enable automatic alt reference frames");
1123 static const arg_def_t arnr_maxframes = ARG_DEF(NULL, "arnr-maxframes", 1,
1124 "AltRef Max Frames");
1125 static const arg_def_t arnr_strength = ARG_DEF(NULL, "arnr-strength", 1,
1127 static const arg_def_t arnr_type = ARG_DEF(NULL, "arnr-type", 1,
1129 static const struct arg_enum_list tuning_enum[] = {
1130 {"psnr", VP8_TUNE_PSNR},
1131 {"ssim", VP8_TUNE_SSIM},
1134 static const arg_def_t tune_ssim = ARG_DEF_ENUM(NULL, "tune", 1,
1135 "Material to favor", tuning_enum);
1136 static const arg_def_t cq_level = ARG_DEF(NULL, "cq-level", 1,
1137 "Constrained Quality Level");
1138 static const arg_def_t max_intra_rate_pct = ARG_DEF(NULL, "max-intra-rate", 1,
1139 "Max I-frame bitrate (pct)");
1141 static const arg_def_t *vp8_args[] =
1143 &cpu_used, &auto_altref, &noise_sens, &sharpness, &static_thresh,
1144 &token_parts, &arnr_maxframes, &arnr_strength, &arnr_type,
1145 &tune_ssim, &cq_level, &max_intra_rate_pct, NULL
1147 static const int vp8_arg_ctrl_map[] =
1149 VP8E_SET_CPUUSED, VP8E_SET_ENABLEAUTOALTREF,
1150 VP8E_SET_NOISE_SENSITIVITY, VP8E_SET_SHARPNESS, VP8E_SET_STATIC_THRESHOLD,
1151 VP8E_SET_TOKEN_PARTITIONS,
1152 VP8E_SET_ARNR_MAXFRAMES, VP8E_SET_ARNR_STRENGTH , VP8E_SET_ARNR_TYPE,
1153 VP8E_SET_TUNING, VP8E_SET_CQ_LEVEL, VP8E_SET_MAX_INTRA_BITRATE_PCT, 0
1157 static const arg_def_t *no_args[] = { NULL };
1159 static void usage_exit()
1163 fprintf(stderr, "Usage: %s <options> -o dst_filename src_filename \n",
1166 fprintf(stderr, "\nOptions:\n");
1167 arg_show_usage(stdout, main_args);
1168 fprintf(stderr, "\nEncoder Global Options:\n");
1169 arg_show_usage(stdout, global_args);
1170 fprintf(stderr, "\nRate Control Options:\n");
1171 arg_show_usage(stdout, rc_args);
1172 fprintf(stderr, "\nTwopass Rate Control Options:\n");
1173 arg_show_usage(stdout, rc_twopass_args);
1174 fprintf(stderr, "\nKeyframe Placement Options:\n");
1175 arg_show_usage(stdout, kf_args);
1176 #if CONFIG_VP8_ENCODER
1177 fprintf(stderr, "\nVP8 Specific Options:\n");
1178 arg_show_usage(stdout, vp8_args);
1180 fprintf(stderr, "\nStream timebase (--timebase):\n"
1181 " The desired precision of timestamps in the output, expressed\n"
1182 " in fractional seconds. Default is 1/1000.\n");
1183 fprintf(stderr, "\n"
1184 "Included encoders:\n"
1187 for (i = 0; i < sizeof(codecs) / sizeof(codecs[0]); i++)
1188 fprintf(stderr, " %-6s - %s\n",
1190 vpx_codec_iface_name(codecs[i].iface));
1196 #define HIST_BAR_MAX 40
1199 int low, high, count;
1203 static int merge_hist_buckets(struct hist_bucket *bucket,
1207 int small_bucket = 0, merge_bucket = INT_MAX, big_bucket=0;
1208 int buckets = *buckets_;
1211 /* Find the extrema for this list of buckets */
1212 big_bucket = small_bucket = 0;
1213 for(i=0; i < buckets; i++)
1215 if(bucket[i].count < bucket[small_bucket].count)
1217 if(bucket[i].count > bucket[big_bucket].count)
1221 /* If we have too many buckets, merge the smallest with an adjacent
1224 while(buckets > max_buckets)
1226 int last_bucket = buckets - 1;
1228 // merge the small bucket with an adjacent one.
1229 if(small_bucket == 0)
1231 else if(small_bucket == last_bucket)
1232 merge_bucket = last_bucket - 1;
1233 else if(bucket[small_bucket - 1].count < bucket[small_bucket + 1].count)
1234 merge_bucket = small_bucket - 1;
1236 merge_bucket = small_bucket + 1;
1238 assert(abs(merge_bucket - small_bucket) <= 1);
1239 assert(small_bucket < buckets);
1240 assert(big_bucket < buckets);
1241 assert(merge_bucket < buckets);
1243 if(merge_bucket < small_bucket)
1245 bucket[merge_bucket].high = bucket[small_bucket].high;
1246 bucket[merge_bucket].count += bucket[small_bucket].count;
1250 bucket[small_bucket].high = bucket[merge_bucket].high;
1251 bucket[small_bucket].count += bucket[merge_bucket].count;
1252 merge_bucket = small_bucket;
1255 assert(bucket[merge_bucket].low != bucket[merge_bucket].high);
1259 /* Remove the merge_bucket from the list, and find the new small
1260 * and big buckets while we're at it
1262 big_bucket = small_bucket = 0;
1263 for(i=0; i < buckets; i++)
1265 if(i > merge_bucket)
1266 bucket[i] = bucket[i+1];
1268 if(bucket[i].count < bucket[small_bucket].count)
1270 if(bucket[i].count > bucket[big_bucket].count)
1276 *buckets_ = buckets;
1277 return bucket[big_bucket].count;
1281 static void show_histogram(const struct hist_bucket *bucket,
1286 const char *pat1, *pat2;
1289 switch((int)(log(bucket[buckets-1].high)/log(10))+1)
1317 pat1 = "%12d %10s: ";
1318 pat2 = "%12d-%10d: ";
1322 for(i=0; i<buckets; i++)
1328 pct = 100.0 * (float)bucket[i].count / (float)total;
1329 len = HIST_BAR_MAX * bucket[i].count / scale;
1332 assert(len <= HIST_BAR_MAX);
1334 if(bucket[i].low == bucket[i].high)
1335 fprintf(stderr, pat1, bucket[i].low, "");
1337 fprintf(stderr, pat2, bucket[i].low, bucket[i].high);
1339 for(j=0; j<HIST_BAR_MAX; j++)
1340 fprintf(stderr, j<len?"=":" ");
1341 fprintf(stderr, "\t%5d (%6.2f%%)\n",bucket[i].count,pct);
1346 static void show_q_histogram(const int counts[64], int max_buckets)
1348 struct hist_bucket bucket[64];
1359 bucket[buckets].low = bucket[buckets].high = i;
1360 bucket[buckets].count = counts[i];
1366 fprintf(stderr, "\nQuantizer Selection:\n");
1367 scale = merge_hist_buckets(bucket, &buckets, max_buckets);
1368 show_histogram(bucket, buckets, total, scale);
1372 #define RATE_BINS (100)
1379 struct hist_bucket bucket[RATE_BINS];
1384 static void init_rate_histogram(struct rate_hist *hist,
1385 const vpx_codec_enc_cfg_t *cfg,
1386 const vpx_rational_t *fps)
1390 /* Determine the number of samples in the buffer. Use the file's framerate
1391 * to determine the number of frames in rc_buf_sz milliseconds, with an
1392 * adjustment (5/4) to account for alt-refs
1394 hist->samples = cfg->rc_buf_sz * 5 / 4 * fps->num / fps->den / 1000;
1396 // prevent division by zero
1397 if (hist->samples == 0)
1400 hist->pts = calloc(hist->samples, sizeof(*hist->pts));
1401 hist->sz = calloc(hist->samples, sizeof(*hist->sz));
1402 for(i=0; i<RATE_BINS; i++)
1404 hist->bucket[i].low = INT_MAX;
1405 hist->bucket[i].high = 0;
1406 hist->bucket[i].count = 0;
1411 static void destroy_rate_histogram(struct rate_hist *hist)
1418 static void update_rate_histogram(struct rate_hist *hist,
1419 const vpx_codec_enc_cfg_t *cfg,
1420 const vpx_codec_cx_pkt_t *pkt)
1423 int64_t now, then, sum_sz = 0, avg_bitrate;
1425 now = pkt->data.frame.pts * 1000
1426 * (uint64_t)cfg->g_timebase.num / (uint64_t)cfg->g_timebase.den;
1428 idx = hist->frames++ % hist->samples;
1429 hist->pts[idx] = now;
1430 hist->sz[idx] = pkt->data.frame.sz;
1432 if(now < cfg->rc_buf_initial_sz)
1437 /* Sum the size over the past rc_buf_sz ms */
1438 for(i = hist->frames; i > 0 && hist->frames - i < hist->samples; i--)
1440 int i_idx = (i-1) % hist->samples;
1442 then = hist->pts[i_idx];
1443 if(now - then > cfg->rc_buf_sz)
1445 sum_sz += hist->sz[i_idx];
1451 avg_bitrate = sum_sz * 8 * 1000 / (now - then);
1452 idx = avg_bitrate * (RATE_BINS/2) / (cfg->rc_target_bitrate * 1000);
1455 if(idx > RATE_BINS-1)
1457 if(hist->bucket[idx].low > avg_bitrate)
1458 hist->bucket[idx].low = avg_bitrate;
1459 if(hist->bucket[idx].high < avg_bitrate)
1460 hist->bucket[idx].high = avg_bitrate;
1461 hist->bucket[idx].count++;
1466 static void show_rate_histogram(struct rate_hist *hist,
1467 const vpx_codec_enc_cfg_t *cfg,
1473 for(i = 0; i < RATE_BINS; i++)
1475 if(hist->bucket[i].low == INT_MAX)
1477 hist->bucket[buckets++] = hist->bucket[i];
1480 fprintf(stderr, "\nRate (over %dms window):\n", cfg->rc_buf_sz);
1481 scale = merge_hist_buckets(hist->bucket, &buckets, max_buckets);
1482 show_histogram(hist->bucket, buckets, hist->total, scale);
1485 #define NELEMENTS(x) (sizeof(x)/sizeof(x[0]))
1486 #define ARG_CTRL_CNT_MAX NELEMENTS(vp8_arg_ctrl_map)
1489 /* Configuration elements common to all streams */
1490 struct global_config
1492 const struct codec_item *codec;
1502 struct vpx_rational framerate;
1505 int show_q_hist_buckets;
1506 int show_rate_hist_buckets;
1510 /* Per-stream configuration */
1511 struct stream_config
1513 struct vpx_codec_enc_cfg cfg;
1515 const char *stats_fn;
1516 stereo_format_t stereo_fmt;
1517 int arg_ctrls[ARG_CTRL_CNT_MAX][2];
1520 int have_kf_max_dist;
1527 struct stream_state *next;
1528 struct stream_config config;
1530 struct rate_hist rate_hist;
1533 uint64_t psnr_sse_total;
1534 uint64_t psnr_samples_total;
1535 double psnr_totals[4];
1538 vpx_codec_ctx_t encoder;
1539 unsigned int frames_out;
1546 void validate_positive_rational(const char *msg,
1547 struct vpx_rational *rat)
1556 die("Error: %s must be positive\n", msg);
1559 die("Error: %s has zero denominator\n", msg);
1563 static void parse_global_config(struct global_config *global, char **argv)
1565 char **argi, **argj;
1568 /* Initialize default parameters */
1569 memset(global, 0, sizeof(*global));
1570 global->codec = codecs;
1572 global->use_i420 = 1;
1574 for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step)
1578 if (arg_match(&arg, &codecarg, argi))
1582 for (j = 0; j < sizeof(codecs) / sizeof(codecs[0]); j++)
1583 if (!strcmp(codecs[j].name, arg.val))
1587 global->codec = codecs + k;
1589 die("Error: Unrecognized argument (%s) to --codec\n",
1593 else if (arg_match(&arg, &passes, argi))
1595 global->passes = arg_parse_uint(&arg);
1597 if (global->passes < 1 || global->passes > 2)
1598 die("Error: Invalid number of passes (%d)\n", global->passes);
1600 else if (arg_match(&arg, &pass_arg, argi))
1602 global->pass = arg_parse_uint(&arg);
1604 if (global->pass < 1 || global->pass > 2)
1605 die("Error: Invalid pass selected (%d)\n",
1608 else if (arg_match(&arg, &usage, argi))
1609 global->usage = arg_parse_uint(&arg);
1610 else if (arg_match(&arg, &deadline, argi))
1611 global->deadline = arg_parse_uint(&arg);
1612 else if (arg_match(&arg, &best_dl, argi))
1613 global->deadline = VPX_DL_BEST_QUALITY;
1614 else if (arg_match(&arg, &good_dl, argi))
1615 global->deadline = VPX_DL_GOOD_QUALITY;
1616 else if (arg_match(&arg, &rt_dl, argi))
1617 global->deadline = VPX_DL_REALTIME;
1618 else if (arg_match(&arg, &use_yv12, argi))
1619 global->use_i420 = 0;
1620 else if (arg_match(&arg, &use_i420, argi))
1621 global->use_i420 = 1;
1622 else if (arg_match(&arg, &verbosearg, argi))
1623 global->verbose = 1;
1624 else if (arg_match(&arg, &limit, argi))
1625 global->limit = arg_parse_uint(&arg);
1626 else if (arg_match(&arg, &psnrarg, argi))
1627 global->show_psnr = 1;
1628 else if (arg_match(&arg, &framerate, argi))
1630 global->framerate = arg_parse_rational(&arg);
1631 validate_positive_rational(arg.name, &global->framerate);
1632 global->have_framerate = 1;
1634 else if (arg_match(&arg,&out_part, argi))
1635 global->out_part = 1;
1636 else if (arg_match(&arg, &debugmode, argi))
1638 else if (arg_match(&arg, &q_hist_n, argi))
1639 global->show_q_hist_buckets = arg_parse_uint(&arg);
1640 else if (arg_match(&arg, &rate_hist_n, argi))
1641 global->show_rate_hist_buckets = arg_parse_uint(&arg);
1646 /* Validate global config */
1650 /* DWIM: Assume the user meant passes=2 if pass=2 is specified */
1651 if (global->pass > global->passes)
1653 warn("Assuming --pass=%d implies --passes=%d\n",
1654 global->pass, global->pass);
1655 global->passes = global->pass;
1661 void open_input_file(struct input_state *input)
1663 unsigned int fourcc;
1665 /* Parse certain options from the input file, if possible */
1666 input->file = strcmp(input->fn, "-") ? fopen(input->fn, "rb")
1667 : set_binary_mode(stdin);
1670 fatal("Failed to open input file");
1672 /* For RAW input sources, these bytes will applied on the first frame
1675 input->detect.buf_read = fread(input->detect.buf, 1, 4, input->file);
1676 input->detect.position = 0;
1678 if (input->detect.buf_read == 4
1679 && file_is_y4m(input->file, &input->y4m, input->detect.buf))
1681 if (y4m_input_open(&input->y4m, input->file, input->detect.buf, 4) >= 0)
1683 input->file_type = FILE_TYPE_Y4M;
1684 input->w = input->y4m.pic_w;
1685 input->h = input->y4m.pic_h;
1686 input->framerate.num = input->y4m.fps_n;
1687 input->framerate.den = input->y4m.fps_d;
1688 input->use_i420 = 0;
1691 fatal("Unsupported Y4M stream.");
1693 else if (input->detect.buf_read == 4 && file_is_ivf(input, &fourcc))
1695 input->file_type = FILE_TYPE_IVF;
1699 input->use_i420 = 0;
1702 input->use_i420 = 1;
1705 fatal("Unsupported fourcc (%08x) in IVF", fourcc);
1710 input->file_type = FILE_TYPE_RAW;
1715 static void close_input_file(struct input_state *input)
1717 fclose(input->file);
1718 if (input->file_type == FILE_TYPE_Y4M)
1719 y4m_input_close(&input->y4m);
1722 static struct stream_state *new_stream(struct global_config *global,
1723 struct stream_state *prev)
1725 struct stream_state *stream;
1727 stream = calloc(1, sizeof(*stream));
1729 fatal("Failed to allocate new stream.");
1732 memcpy(stream, prev, sizeof(*stream));
1734 prev->next = stream;
1738 vpx_codec_err_t res;
1740 /* Populate encoder configuration */
1741 res = vpx_codec_enc_config_default(global->codec->iface,
1742 &stream->config.cfg,
1745 fatal("Failed to get config: %s\n", vpx_codec_err_to_string(res));
1747 /* Change the default timebase to a high enough value so that the
1748 * encoder will always create strictly increasing timestamps.
1750 stream->config.cfg.g_timebase.den = 1000;
1752 /* Never use the library's default resolution, require it be parsed
1753 * from the file or set on the command line.
1755 stream->config.cfg.g_w = 0;
1756 stream->config.cfg.g_h = 0;
1758 /* Initialize remaining stream parameters */
1759 stream->config.stereo_fmt = STEREO_FORMAT_MONO;
1760 stream->config.write_webm = 1;
1761 stream->ebml.last_pts_ms = -1;
1763 /* Allows removal of the application version from the EBML tags */
1764 stream->ebml.debug = global->debug;
1767 /* Output files must be specified for each stream */
1768 stream->config.out_fn = NULL;
1770 stream->next = NULL;
1775 static int parse_stream_params(struct global_config *global,
1776 struct stream_state *stream,
1779 char **argi, **argj;
1781 static const arg_def_t **ctrl_args = no_args;
1782 static const int *ctrl_args_map = NULL;
1783 struct stream_config *config = &stream->config;
1784 int eos_mark_found = 0;
1786 /* Handle codec specific options */
1787 if (global->codec->iface == &vpx_codec_vp8_cx_algo)
1789 ctrl_args = vp8_args;
1790 ctrl_args_map = vp8_arg_ctrl_map;
1793 for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step)
1797 /* Once we've found an end-of-stream marker (--) we want to continue
1798 * shifting arguments but not consuming them.
1805 else if (!strcmp(*argj, "--"))
1812 else if (arg_match(&arg, &outputfile, argi))
1813 config->out_fn = arg.val;
1814 else if (arg_match(&arg, &fpf_name, argi))
1815 config->stats_fn = arg.val;
1816 else if (arg_match(&arg, &use_ivf, argi))
1817 config->write_webm = 0;
1818 else if (arg_match(&arg, &threads, argi))
1819 config->cfg.g_threads = arg_parse_uint(&arg);
1820 else if (arg_match(&arg, &profile, argi))
1821 config->cfg.g_profile = arg_parse_uint(&arg);
1822 else if (arg_match(&arg, &width, argi))
1823 config->cfg.g_w = arg_parse_uint(&arg);
1824 else if (arg_match(&arg, &height, argi))
1825 config->cfg.g_h = arg_parse_uint(&arg);
1826 else if (arg_match(&arg, &stereo_mode, argi))
1827 config->stereo_fmt = arg_parse_enum_or_int(&arg);
1828 else if (arg_match(&arg, &timebase, argi))
1830 config->cfg.g_timebase = arg_parse_rational(&arg);
1831 validate_positive_rational(arg.name, &config->cfg.g_timebase);
1833 else if (arg_match(&arg, &error_resilient, argi))
1834 config->cfg.g_error_resilient = arg_parse_uint(&arg);
1835 else if (arg_match(&arg, &lag_in_frames, argi))
1836 config->cfg.g_lag_in_frames = arg_parse_uint(&arg);
1837 else if (arg_match(&arg, &dropframe_thresh, argi))
1838 config->cfg.rc_dropframe_thresh = arg_parse_uint(&arg);
1839 else if (arg_match(&arg, &resize_allowed, argi))
1840 config->cfg.rc_resize_allowed = arg_parse_uint(&arg);
1841 else if (arg_match(&arg, &resize_up_thresh, argi))
1842 config->cfg.rc_resize_up_thresh = arg_parse_uint(&arg);
1843 else if (arg_match(&arg, &resize_down_thresh, argi))
1844 config->cfg.rc_resize_down_thresh = arg_parse_uint(&arg);
1845 else if (arg_match(&arg, &end_usage, argi))
1846 config->cfg.rc_end_usage = arg_parse_enum_or_int(&arg);
1847 else if (arg_match(&arg, &target_bitrate, argi))
1848 config->cfg.rc_target_bitrate = arg_parse_uint(&arg);
1849 else if (arg_match(&arg, &min_quantizer, argi))
1850 config->cfg.rc_min_quantizer = arg_parse_uint(&arg);
1851 else if (arg_match(&arg, &max_quantizer, argi))
1852 config->cfg.rc_max_quantizer = arg_parse_uint(&arg);
1853 else if (arg_match(&arg, &undershoot_pct, argi))
1854 config->cfg.rc_undershoot_pct = arg_parse_uint(&arg);
1855 else if (arg_match(&arg, &overshoot_pct, argi))
1856 config->cfg.rc_overshoot_pct = arg_parse_uint(&arg);
1857 else if (arg_match(&arg, &buf_sz, argi))
1858 config->cfg.rc_buf_sz = arg_parse_uint(&arg);
1859 else if (arg_match(&arg, &buf_initial_sz, argi))
1860 config->cfg.rc_buf_initial_sz = arg_parse_uint(&arg);
1861 else if (arg_match(&arg, &buf_optimal_sz, argi))
1862 config->cfg.rc_buf_optimal_sz = arg_parse_uint(&arg);
1863 else if (arg_match(&arg, &bias_pct, argi))
1865 config->cfg.rc_2pass_vbr_bias_pct = arg_parse_uint(&arg);
1867 if (global->passes < 2)
1868 warn("option %s ignored in one-pass mode.\n", arg.name);
1870 else if (arg_match(&arg, &minsection_pct, argi))
1872 config->cfg.rc_2pass_vbr_minsection_pct = arg_parse_uint(&arg);
1874 if (global->passes < 2)
1875 warn("option %s ignored in one-pass mode.\n", arg.name);
1877 else if (arg_match(&arg, &maxsection_pct, argi))
1879 config->cfg.rc_2pass_vbr_maxsection_pct = arg_parse_uint(&arg);
1881 if (global->passes < 2)
1882 warn("option %s ignored in one-pass mode.\n", arg.name);
1884 else if (arg_match(&arg, &kf_min_dist, argi))
1885 config->cfg.kf_min_dist = arg_parse_uint(&arg);
1886 else if (arg_match(&arg, &kf_max_dist, argi))
1888 config->cfg.kf_max_dist = arg_parse_uint(&arg);
1889 config->have_kf_max_dist = 1;
1891 else if (arg_match(&arg, &kf_disabled, argi))
1892 config->cfg.kf_mode = VPX_KF_DISABLED;
1897 for (i = 0; ctrl_args[i]; i++)
1899 if (arg_match(&arg, ctrl_args[i], argi))
1904 /* Point either to the next free element or the first
1905 * instance of this control.
1907 for(j=0; j<config->arg_ctrl_cnt; j++)
1908 if(config->arg_ctrls[j][0] == ctrl_args_map[i])
1912 assert(j < ARG_CTRL_CNT_MAX);
1913 if (j < ARG_CTRL_CNT_MAX)
1915 config->arg_ctrls[j][0] = ctrl_args_map[i];
1916 config->arg_ctrls[j][1] = arg_parse_enum_or_int(&arg);
1917 if(j == config->arg_ctrl_cnt)
1918 config->arg_ctrl_cnt++;
1929 return eos_mark_found;
1933 #define FOREACH_STREAM(func)\
1936 struct stream_state *stream;\
1938 for(stream = streams; stream; stream = stream->next)\
1943 static void validate_stream_config(struct stream_state *stream)
1945 struct stream_state *streami;
1947 if(!stream->config.cfg.g_w || !stream->config.cfg.g_h)
1948 fatal("Stream %d: Specify stream dimensions with --width (-w) "
1949 " and --height (-h)", stream->index);
1951 for(streami = stream; streami; streami = streami->next)
1953 /* All streams require output files */
1954 if(!streami->config.out_fn)
1955 fatal("Stream %d: Output file is required (specify with -o)",
1958 /* Check for two streams outputting to the same file */
1959 if(streami != stream)
1961 const char *a = stream->config.out_fn;
1962 const char *b = streami->config.out_fn;
1963 if(!strcmp(a,b) && strcmp(a, "/dev/null") && strcmp(a, ":nul"))
1964 fatal("Stream %d: duplicate output file (from stream %d)",
1965 streami->index, stream->index);
1968 /* Check for two streams sharing a stats file. */
1969 if(streami != stream)
1971 const char *a = stream->config.stats_fn;
1972 const char *b = streami->config.stats_fn;
1973 if(a && b && !strcmp(a,b))
1974 fatal("Stream %d: duplicate stats file (from stream %d)",
1975 streami->index, stream->index);
1981 static void set_stream_dimensions(struct stream_state *stream,
1985 if ((stream->config.cfg.g_w && stream->config.cfg.g_w != w)
1986 ||(stream->config.cfg.g_h && stream->config.cfg.g_h != h))
1987 fatal("Stream %d: Resizing not yet supported", stream->index);
1988 stream->config.cfg.g_w = w;
1989 stream->config.cfg.g_h = h;
1993 static void set_default_kf_interval(struct stream_state *stream,
1994 struct global_config *global)
1996 /* Use a max keyframe interval of 5 seconds, if none was
1997 * specified on the command line.
1999 if (!stream->config.have_kf_max_dist)
2001 double framerate = (double)global->framerate.num/global->framerate.den;
2002 if (framerate > 0.0)
2003 stream->config.cfg.kf_max_dist = 5.0*framerate;
2008 static void show_stream_config(struct stream_state *stream,
2009 struct global_config *global,
2010 struct input_state *input)
2013 #define SHOW(field) \
2014 fprintf(stderr, " %-28s = %d\n", #field, stream->config.cfg.field)
2016 if(stream->index == 0)
2018 fprintf(stderr, "Codec: %s\n",
2019 vpx_codec_iface_name(global->codec->iface));
2020 fprintf(stderr, "Source file: %s Format: %s\n", input->fn,
2021 input->use_i420 ? "I420" : "YV12");
2023 if(stream->next || stream->index)
2024 fprintf(stderr, "\nStream Index: %d\n", stream->index);
2025 fprintf(stderr, "Destination file: %s\n", stream->config.out_fn);
2026 fprintf(stderr, "Encoder parameters:\n");
2033 SHOW(g_timebase.num);
2034 SHOW(g_timebase.den);
2035 SHOW(g_error_resilient);
2037 SHOW(g_lag_in_frames);
2038 SHOW(rc_dropframe_thresh);
2039 SHOW(rc_resize_allowed);
2040 SHOW(rc_resize_up_thresh);
2041 SHOW(rc_resize_down_thresh);
2043 SHOW(rc_target_bitrate);
2044 SHOW(rc_min_quantizer);
2045 SHOW(rc_max_quantizer);
2046 SHOW(rc_undershoot_pct);
2047 SHOW(rc_overshoot_pct);
2049 SHOW(rc_buf_initial_sz);
2050 SHOW(rc_buf_optimal_sz);
2051 SHOW(rc_2pass_vbr_bias_pct);
2052 SHOW(rc_2pass_vbr_minsection_pct);
2053 SHOW(rc_2pass_vbr_maxsection_pct);
2060 static void open_output_file(struct stream_state *stream,
2061 struct global_config *global)
2063 const char *fn = stream->config.out_fn;
2065 stream->file = strcmp(fn, "-") ? fopen(fn, "wb") : set_binary_mode(stdout);
2068 fatal("Failed to open output file");
2070 if(stream->config.write_webm && fseek(stream->file, 0, SEEK_CUR))
2071 fatal("WebM output to pipes not supported.");
2073 if(stream->config.write_webm)
2075 stream->ebml.stream = stream->file;
2076 write_webm_file_header(&stream->ebml, &stream->config.cfg,
2078 stream->config.stereo_fmt);
2081 write_ivf_file_header(stream->file, &stream->config.cfg,
2082 global->codec->fourcc, 0);
2086 static void close_output_file(struct stream_state *stream,
2087 unsigned int fourcc)
2089 if(stream->config.write_webm)
2091 write_webm_file_footer(&stream->ebml, stream->hash);
2092 free(stream->ebml.cue_list);
2093 stream->ebml.cue_list = NULL;
2097 if (!fseek(stream->file, 0, SEEK_SET))
2098 write_ivf_file_header(stream->file, &stream->config.cfg,
2100 stream->frames_out);
2103 fclose(stream->file);
2107 static void setup_pass(struct stream_state *stream,
2108 struct global_config *global,
2111 if (stream->config.stats_fn)
2113 if (!stats_open_file(&stream->stats, stream->config.stats_fn,
2115 fatal("Failed to open statistics store");
2119 if (!stats_open_mem(&stream->stats, pass))
2120 fatal("Failed to open statistics store");
2123 stream->config.cfg.g_pass = global->passes == 2
2124 ? pass ? VPX_RC_LAST_PASS : VPX_RC_FIRST_PASS
2127 stream->config.cfg.rc_twopass_stats_in = stats_get(&stream->stats);
2129 stream->cx_time = 0;
2131 stream->frames_out = 0;
2135 static void initialize_encoder(struct stream_state *stream,
2136 struct global_config *global)
2141 flags |= global->show_psnr ? VPX_CODEC_USE_PSNR : 0;
2142 flags |= global->out_part ? VPX_CODEC_USE_OUTPUT_PARTITION : 0;
2144 /* Construct Encoder Context */
2145 vpx_codec_enc_init(&stream->encoder, global->codec->iface,
2146 &stream->config.cfg, flags);
2147 ctx_exit_on_error(&stream->encoder, "Failed to initialize encoder");
2149 /* Note that we bypass the vpx_codec_control wrapper macro because
2150 * we're being clever to store the control IDs in an array. Real
2151 * applications will want to make use of the enumerations directly
2153 for (i = 0; i < stream->config.arg_ctrl_cnt; i++)
2155 int ctrl = stream->config.arg_ctrls[i][0];
2156 int value = stream->config.arg_ctrls[i][1];
2157 if (vpx_codec_control_(&stream->encoder, ctrl, value))
2158 fprintf(stderr, "Error: Tried to set control %d = %d\n",
2161 ctx_exit_on_error(&stream->encoder, "Failed to control codec");
2166 static void encode_frame(struct stream_state *stream,
2167 struct global_config *global,
2168 struct vpx_image *img,
2169 unsigned int frames_in)
2171 vpx_codec_pts_t frame_start, next_frame_start;
2172 struct vpx_codec_enc_cfg *cfg = &stream->config.cfg;
2173 struct vpx_usec_timer timer;
2175 frame_start = (cfg->g_timebase.den * (int64_t)(frames_in - 1)
2176 * global->framerate.den)
2177 / cfg->g_timebase.num / global->framerate.num;
2178 next_frame_start = (cfg->g_timebase.den * (int64_t)(frames_in)
2179 * global->framerate.den)
2180 / cfg->g_timebase.num / global->framerate.num;
2181 vpx_usec_timer_start(&timer);
2182 vpx_codec_encode(&stream->encoder, img, frame_start,
2183 next_frame_start - frame_start,
2184 0, global->deadline);
2185 vpx_usec_timer_mark(&timer);
2186 stream->cx_time += vpx_usec_timer_elapsed(&timer);
2187 ctx_exit_on_error(&stream->encoder, "Stream %d: Failed to encode frame",
2192 static void update_quantizer_histogram(struct stream_state *stream)
2194 if(stream->config.cfg.g_pass != VPX_RC_FIRST_PASS)
2198 vpx_codec_control(&stream->encoder, VP8E_GET_LAST_QUANTIZER_64, &q);
2199 ctx_exit_on_error(&stream->encoder, "Failed to read quantizer");
2200 stream->counts[q]++;
2205 static void get_cx_data(struct stream_state *stream,
2206 struct global_config *global,
2209 const vpx_codec_cx_pkt_t *pkt;
2210 const struct vpx_codec_enc_cfg *cfg = &stream->config.cfg;
2211 vpx_codec_iter_t iter = NULL;
2213 while ((pkt = vpx_codec_get_cx_data(&stream->encoder, &iter)))
2215 static size_t fsize = 0;
2216 static off_t ivf_header_pos = 0;
2222 case VPX_CODEC_CX_FRAME_PKT:
2223 if (!(pkt->data.frame.flags & VPX_FRAME_IS_FRAGMENT))
2225 stream->frames_out++;
2227 fprintf(stderr, " %6luF",
2228 (unsigned long)pkt->data.frame.sz);
2230 update_rate_histogram(&stream->rate_hist, cfg, pkt);
2231 if(stream->config.write_webm)
2233 /* Update the hash */
2234 if(!stream->ebml.debug)
2235 stream->hash = murmur(pkt->data.frame.buf,
2236 pkt->data.frame.sz, stream->hash);
2238 write_webm_block(&stream->ebml, cfg, pkt);
2242 if (pkt->data.frame.partition_id <= 0)
2244 ivf_header_pos = ftello(stream->file);
2245 fsize = pkt->data.frame.sz;
2247 write_ivf_frame_header(stream->file, pkt);
2251 fsize += pkt->data.frame.sz;
2253 if (!(pkt->data.frame.flags & VPX_FRAME_IS_FRAGMENT))
2255 off_t currpos = ftello(stream->file);
2256 fseeko(stream->file, ivf_header_pos, SEEK_SET);
2257 write_ivf_frame_size(stream->file, fsize);
2258 fseeko(stream->file, currpos, SEEK_SET);
2262 (void) fwrite(pkt->data.frame.buf, 1, pkt->data.frame.sz,
2265 stream->nbytes += pkt->data.raw.sz;
2267 case VPX_CODEC_STATS_PKT:
2268 stream->frames_out++;
2269 fprintf(stderr, " %6luS",
2270 (unsigned long)pkt->data.twopass_stats.sz);
2271 stats_write(&stream->stats,
2272 pkt->data.twopass_stats.buf,
2273 pkt->data.twopass_stats.sz);
2274 stream->nbytes += pkt->data.raw.sz;
2276 case VPX_CODEC_PSNR_PKT:
2278 if (global->show_psnr)
2282 stream->psnr_sse_total += pkt->data.psnr.sse[0];
2283 stream->psnr_samples_total += pkt->data.psnr.samples[0];
2284 for (i = 0; i < 4; i++)
2286 fprintf(stderr, "%.3lf ", pkt->data.psnr.psnr[i]);
2287 stream->psnr_totals[i] += pkt->data.psnr.psnr[i];
2289 stream->psnr_count++;
2300 static void show_psnr(struct stream_state *stream)
2305 if (!stream->psnr_count)
2308 fprintf(stderr, "Stream %d PSNR (Overall/Avg/Y/U/V)", stream->index);
2309 ovpsnr = vp8_mse2psnr(stream->psnr_samples_total, 255.0,
2310 stream->psnr_sse_total);
2311 fprintf(stderr, " %.3lf", ovpsnr);
2313 for (i = 0; i < 4; i++)
2315 fprintf(stderr, " %.3lf", stream->psnr_totals[i]/stream->psnr_count);
2317 fprintf(stderr, "\n");
2321 float usec_to_fps(uint64_t usec, unsigned int frames)
2323 return usec > 0 ? (float)frames * 1000000.0 / (float)usec : 0;
2327 int main(int argc, const char **argv_)
2331 int frame_avail, got_data;
2333 struct input_state input = {0};
2334 struct global_config global;
2335 struct stream_state *streams = NULL;
2336 char **argv, **argi;
2337 unsigned long cx_time = 0;
2340 exec_name = argv_[0];
2345 /* Setup default input stream settings */
2346 input.framerate.num = 30;
2347 input.framerate.den = 1;
2350 /* First parse the global configuration values, because we want to apply
2351 * other parameters on top of the default configuration provided by the
2354 argv = argv_dup(argc - 1, argv_ + 1);
2355 parse_global_config(&global, argv);
2358 /* Now parse each stream's parameters. Using a local scope here
2359 * due to the use of 'stream' as loop variable in FOREACH_STREAM
2362 struct stream_state *stream = NULL;
2366 stream = new_stream(&global, stream);
2370 } while(parse_stream_params(&global, stream, argv));
2373 /* Check for unrecognized options */
2374 for (argi = argv; *argi; argi++)
2375 if (argi[0][0] == '-' && argi[0][1])
2376 die("Error: Unrecognized option %s\n", *argi);
2378 /* Handle non-option arguments */
2384 for (pass = global.pass ? global.pass - 1 : 0; pass < global.passes; pass++)
2388 open_input_file(&input);
2390 /* If the input file doesn't specify its w/h (raw files), try to get
2391 * the data from the first stream's configuration.
2393 if(!input.w || !input.h)
2395 if(stream->config.cfg.g_w && stream->config.cfg.g_h)
2397 input.w = stream->config.cfg.g_w;
2398 input.h = stream->config.cfg.g_h;
2403 /* Update stream configurations from the input file's parameters */
2404 FOREACH_STREAM(set_stream_dimensions(stream, input.w, input.h));
2405 FOREACH_STREAM(validate_stream_config(stream));
2407 /* Ensure that --passes and --pass are consistent. If --pass is set and
2408 * --passes=2, ensure --fpf was set.
2410 if (global.pass && global.passes == 2)
2412 if(!stream->config.stats_fn)
2413 die("Stream %d: Must specify --fpf when --pass=%d"
2414 " and --passes=2\n", stream->index, global.pass);
2418 /* Use the frame rate from the file only if none was specified
2419 * on the command-line.
2421 if (!global.have_framerate)
2422 global.framerate = input.framerate;
2424 FOREACH_STREAM(set_default_kf_interval(stream, &global));
2426 /* Show configuration */
2427 if (global.verbose && pass == 0)
2428 FOREACH_STREAM(show_stream_config(stream, &global, &input));
2430 if(pass == (global.pass ? global.pass - 1 : 0)) {
2431 if (input.file_type == FILE_TYPE_Y4M)
2432 /*The Y4M reader does its own allocation.
2433 Just initialize this here to avoid problems if we never read any
2435 memset(&raw, 0, sizeof(raw));
2438 input.use_i420 ? VPX_IMG_FMT_I420
2440 input.w, input.h, 32);
2442 FOREACH_STREAM(init_rate_histogram(&stream->rate_hist,
2443 &stream->config.cfg,
2444 &global.framerate));
2447 FOREACH_STREAM(open_output_file(stream, &global));
2448 FOREACH_STREAM(setup_pass(stream, &global, pass));
2449 FOREACH_STREAM(initialize_encoder(stream, &global));
2454 while (frame_avail || got_data)
2456 struct vpx_usec_timer timer;
2458 if (!global.limit || frames_in < global.limit)
2460 frame_avail = read_frame(&input, &raw);
2467 "\rPass %d/%d frame %4d/%-4d %7"PRId64"B \033[K",
2468 pass + 1, global.passes, frames_in,
2469 streams->frames_out, (int64_t)streams->nbytes);
2472 "\rPass %d/%d frame %4d %7lu %s (%.2f fps)\033[K",
2473 pass + 1, global.passes, frames_in,
2474 cx_time > 9999999 ? cx_time / 1000 : cx_time,
2475 cx_time > 9999999 ? "ms" : "us",
2476 usec_to_fps(cx_time, frames_in));
2482 vpx_usec_timer_start(&timer);
2483 FOREACH_STREAM(encode_frame(stream, &global,
2484 frame_avail ? &raw : NULL,
2486 vpx_usec_timer_mark(&timer);
2487 cx_time += vpx_usec_timer_elapsed(&timer);
2489 FOREACH_STREAM(update_quantizer_histogram(stream));
2492 FOREACH_STREAM(get_cx_data(stream, &global, &got_data));
2498 fprintf(stderr, "\n");
2500 FOREACH_STREAM(fprintf(
2502 "\rPass %d/%d frame %4d/%-4d %7"PRId64"B %7lub/f %7"PRId64"b/s"
2503 " %7"PRId64" %s (%.2f fps)\033[K\n", pass + 1,
2504 global.passes, frames_in, stream->frames_out, (int64_t)stream->nbytes,
2505 frames_in ? (unsigned long)(stream->nbytes * 8 / frames_in) : 0,
2506 frames_in ? (int64_t)stream->nbytes * 8
2507 * (int64_t)global.framerate.num / global.framerate.den
2510 stream->cx_time > 9999999 ? stream->cx_time / 1000 : stream->cx_time,
2511 stream->cx_time > 9999999 ? "ms" : "us",
2512 usec_to_fps(stream->cx_time, frames_in));
2515 if (global.show_psnr)
2516 FOREACH_STREAM(show_psnr(stream));
2518 FOREACH_STREAM(vpx_codec_destroy(&stream->encoder));
2520 close_input_file(&input);
2522 FOREACH_STREAM(close_output_file(stream, global.codec->fourcc));
2524 FOREACH_STREAM(stats_close(&stream->stats, global.passes-1));
2530 if (global.show_q_hist_buckets)
2531 FOREACH_STREAM(show_q_histogram(stream->counts,
2532 global.show_q_hist_buckets));
2534 if (global.show_rate_hist_buckets)
2535 FOREACH_STREAM(show_rate_histogram(&stream->rate_hist,
2536 &stream->config.cfg,
2537 global.show_rate_hist_buckets));
2538 FOREACH_STREAM(destroy_rate_histogram(&stream->rate_hist));
2543 return EXIT_SUCCESS;