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.
16 #define USE_POSIX_MMAP 0
18 #define USE_POSIX_MMAP 1
26 #include "vpx/vpx_encoder.h"
28 #include <sys/types.h>
34 #include "vpx_version.h"
35 #include "vpx/vp8cx.h"
36 #include "vpx_ports/mem_ops.h"
37 #include "vpx_ports/vpx_timer.h"
39 #include "libmkv/EbmlWriter.h"
40 #include "libmkv/EbmlIDs.h"
42 /* Need special handling of these functions on Windows */
44 /* MSVS doesn't define off_t, and uses _f{seek,tell}i64 */
45 typedef __int64 off_t;
46 #define fseeko _fseeki64
47 #define ftello _ftelli64
49 /* MinGW defines off_t, and uses f{seek,tell}o64 */
50 #define fseeko fseeko64
51 #define ftello ftello64
55 #define LITERALU64(n) n
57 #define LITERALU64(n) n##LLU
60 static const char *exec_name;
62 static const struct codec_item
65 const vpx_codec_iface_t *iface;
69 #if CONFIG_VP8_ENCODER
70 {"vp8", &vpx_codec_vp8_cx_algo, 0x30385056},
74 static void usage_exit();
76 void die(const char *fmt, ...)
80 vfprintf(stderr, fmt, ap);
81 fprintf(stderr, "\n");
85 static void ctx_exit_on_error(vpx_codec_ctx_t *ctx, const char *s)
89 const char *detail = vpx_codec_error_detail(ctx);
91 fprintf(stderr, "%s: %s\n", s, vpx_codec_error(ctx));
94 fprintf(stderr, " %s\n", detail);
100 /* This structure is used to abstract the different ways of handling
101 * first pass statistics.
112 int stats_open_file(stats_io_t *stats, const char *fpf, int pass)
120 stats->file = fopen(fpf, "wb");
122 stats->buf.buf = NULL,
123 res = (stats->file != NULL);
129 struct stat stat_buf;
132 fd = open(fpf, O_RDONLY);
133 stats->file = fdopen(fd, "rb");
134 fstat(fd, &stat_buf);
135 stats->buf.sz = stat_buf.st_size;
136 stats->buf.buf = mmap(NULL, stats->buf.sz, PROT_READ, MAP_PRIVATE,
138 res = (stats->buf.buf != NULL);
142 stats->file = fopen(fpf, "rb");
144 if (fseek(stats->file, 0, SEEK_END))
146 fprintf(stderr, "First-pass stats file must be seekable!\n");
150 stats->buf.sz = stats->buf_alloc_sz = ftell(stats->file);
153 stats->buf.buf = malloc(stats->buf_alloc_sz);
157 fprintf(stderr, "Failed to allocate first-pass stats buffer (%d bytes)\n",
158 stats->buf_alloc_sz);
162 nbytes = fread(stats->buf.buf, 1, stats->buf.sz, stats->file);
163 res = (nbytes == stats->buf.sz);
170 int stats_open_mem(stats_io_t *stats, int pass)
178 stats->buf_alloc_sz = 64 * 1024;
179 stats->buf.buf = malloc(stats->buf_alloc_sz);
182 stats->buf_ptr = stats->buf.buf;
183 res = (stats->buf.buf != NULL);
188 void stats_close(stats_io_t *stats)
192 if (stats->pass == 1)
196 munmap(stats->buf.buf, stats->buf.sz);
198 free(stats->buf.buf);
207 if (stats->pass == 1)
208 free(stats->buf.buf);
212 void stats_write(stats_io_t *stats, const void *pkt, size_t len)
216 fwrite(pkt, 1, len, stats->file);
220 if (stats->buf.sz + len > stats->buf_alloc_sz)
222 size_t new_sz = stats->buf_alloc_sz + 64 * 1024;
223 char *new_ptr = realloc(stats->buf.buf, new_sz);
227 stats->buf_ptr = new_ptr + (stats->buf_ptr - (char *)stats->buf.buf);
228 stats->buf.buf = new_ptr;
229 stats->buf_alloc_sz = new_sz;
233 memcpy(stats->buf_ptr, pkt, len);
234 stats->buf.sz += len;
235 stats->buf_ptr += len;
239 vpx_fixed_buf_t stats_get(stats_io_t *stats)
251 struct detect_buffer {
257 #define IVF_FRAME_HDR_SZ (4+8) /* 4 byte size + 8 byte timestamp */
258 static int read_frame(FILE *f, vpx_image_t *img, unsigned int file_type,
259 y4m_input *y4m, struct detect_buffer *detect)
263 if (file_type == FILE_TYPE_Y4M)
265 if (y4m_input_fetch_frame(y4m, f, img) < 0)
270 if (file_type == FILE_TYPE_IVF)
272 char junk[IVF_FRAME_HDR_SZ];
274 /* Skip the frame header. We know how big the frame should be. See
275 * write_ivf_frame_header() for documentation on the frame header
278 fread(junk, 1, IVF_FRAME_HDR_SZ, f);
281 for (plane = 0; plane < 3; plane++)
284 int w = (plane ? (1 + img->d_w) / 2 : img->d_w);
285 int h = (plane ? (1 + img->d_h) / 2 : img->d_h);
288 /* Determine the correct plane based on the image format. The for-loop
289 * always counts in Y,U,V order, but this may not match the order of
295 ptr = img->planes[img->fmt==VPX_IMG_FMT_YV12? VPX_PLANE_V : VPX_PLANE_U];
298 ptr = img->planes[img->fmt==VPX_IMG_FMT_YV12?VPX_PLANE_U : VPX_PLANE_V];
301 ptr = img->planes[plane];
304 for (r = 0; r < h; r++)
308 memcpy(ptr, detect->buf, 4);
309 fread(ptr+4, 1, w-4, f);
315 ptr += img->stride[plane];
324 unsigned int file_is_y4m(FILE *infile,
328 if(memcmp(detect, "YUV4", 4) == 0)
335 #define IVF_FILE_HDR_SZ (32)
336 unsigned int file_is_ivf(FILE *infile,
337 unsigned int *fourcc,
339 unsigned int *height,
342 char raw_hdr[IVF_FILE_HDR_SZ];
345 if(memcmp(detect, "DKIF", 4) != 0)
348 /* See write_ivf_file_header() for more documentation on the file header
351 if (fread(raw_hdr + 4, 1, IVF_FILE_HDR_SZ - 4, infile)
352 == IVF_FILE_HDR_SZ - 4)
357 if (mem_get_le16(raw_hdr + 4) != 0)
358 fprintf(stderr, "Error: Unrecognized IVF version! This file may not"
359 " decode properly.");
361 *fourcc = mem_get_le32(raw_hdr + 8);
367 *width = mem_get_le16(raw_hdr + 12);
368 *height = mem_get_le16(raw_hdr + 14);
375 static void write_ivf_file_header(FILE *outfile,
376 const vpx_codec_enc_cfg_t *cfg,
382 if (cfg->g_pass != VPX_RC_ONE_PASS && cfg->g_pass != VPX_RC_LAST_PASS)
389 mem_put_le16(header + 4, 0); /* version */
390 mem_put_le16(header + 6, 32); /* headersize */
391 mem_put_le32(header + 8, fourcc); /* headersize */
392 mem_put_le16(header + 12, cfg->g_w); /* width */
393 mem_put_le16(header + 14, cfg->g_h); /* height */
394 mem_put_le32(header + 16, cfg->g_timebase.den); /* rate */
395 mem_put_le32(header + 20, cfg->g_timebase.num); /* scale */
396 mem_put_le32(header + 24, frame_cnt); /* length */
397 mem_put_le32(header + 28, 0); /* unused */
399 fwrite(header, 1, 32, outfile);
403 static void write_ivf_frame_header(FILE *outfile,
404 const vpx_codec_cx_pkt_t *pkt)
409 if (pkt->kind != VPX_CODEC_CX_FRAME_PKT)
412 pts = pkt->data.frame.pts;
413 mem_put_le32(header, pkt->data.frame.sz);
414 mem_put_le32(header + 4, pts & 0xFFFFFFFF);
415 mem_put_le32(header + 8, pts >> 32);
417 fwrite(header, 1, 12, outfile);
421 typedef off_t EbmlLoc;
436 uint64_t last_pts_ms;
437 vpx_rational_t framerate;
439 /* These pointers are to the start of an element */
440 off_t position_reference;
442 off_t segment_info_pos;
447 /* This pointer is to a specific element to be serialized */
450 /* These pointers are to the size field of the element */
451 EbmlLoc startSegment;
452 EbmlLoc startCluster;
454 uint32_t cluster_timecode;
457 struct cue_entry *cue_list;
463 void Ebml_Write(EbmlGlobal *glob, const void *buffer_in, unsigned long len)
465 fwrite(buffer_in, 1, len, glob->stream);
469 void Ebml_Serialize(EbmlGlobal *glob, const void *buffer_in, unsigned long len)
471 const unsigned char *q = (const unsigned char *)buffer_in + len - 1;
474 Ebml_Write(glob, q--, 1);
478 /* Need a fixed size serializer for the track ID. libmkv provdes a 64 bit
479 * one, but not a 32 bit one.
481 static void Ebml_SerializeUnsigned32(EbmlGlobal *glob, unsigned long class_id, uint64_t ui)
483 unsigned char sizeSerialized = 4 | 0x80;
484 Ebml_WriteID(glob, class_id);
485 Ebml_Serialize(glob, &sizeSerialized, 1);
486 Ebml_Serialize(glob, &ui, 4);
491 Ebml_StartSubElement(EbmlGlobal *glob, EbmlLoc *ebmlLoc,
492 unsigned long class_id)
494 //todo this is always taking 8 bytes, this may need later optimization
495 //this is a key that says lenght unknown
496 unsigned long long unknownLen = LITERALU64(0x01FFFFFFFFFFFFFF);
498 Ebml_WriteID(glob, class_id);
499 *ebmlLoc = ftello(glob->stream);
500 Ebml_Serialize(glob, &unknownLen, 8);
504 Ebml_EndSubElement(EbmlGlobal *glob, EbmlLoc *ebmlLoc)
509 /* Save the current stream pointer */
510 pos = ftello(glob->stream);
512 /* Calculate the size of this element */
513 size = pos - *ebmlLoc - 8;
514 size |= LITERALU64(0x0100000000000000);
516 /* Seek back to the beginning of the element and write the new size */
517 fseeko(glob->stream, *ebmlLoc, SEEK_SET);
518 Ebml_Serialize(glob, &size, 8);
520 /* Reset the stream pointer */
521 fseeko(glob->stream, pos, SEEK_SET);
526 write_webm_seek_element(EbmlGlobal *ebml, unsigned long id, off_t pos)
528 uint64_t offset = pos - ebml->position_reference;
530 Ebml_StartSubElement(ebml, &start, Seek);
531 Ebml_SerializeBinary(ebml, SeekID, id);
532 Ebml_SerializeUnsigned64(ebml, SeekPosition, offset);
533 Ebml_EndSubElement(ebml, &start);
538 write_webm_seek_info(EbmlGlobal *ebml)
543 /* Save the current stream pointer */
544 pos = ftello(ebml->stream);
546 if(ebml->seek_info_pos)
547 fseeko(ebml->stream, ebml->seek_info_pos, SEEK_SET);
549 ebml->seek_info_pos = pos;
554 Ebml_StartSubElement(ebml, &start, SeekHead);
555 write_webm_seek_element(ebml, Tracks, ebml->track_pos);
556 write_webm_seek_element(ebml, Cues, ebml->cue_pos);
557 write_webm_seek_element(ebml, Info, ebml->segment_info_pos);
558 Ebml_EndSubElement(ebml, &start);
565 frame_time = (uint64_t)1000 * ebml->framerate.den
566 / ebml->framerate.num;
567 ebml->segment_info_pos = ftello(ebml->stream);
568 Ebml_StartSubElement(ebml, &startInfo, Info);
569 Ebml_SerializeUnsigned(ebml, TimecodeScale, 1000000);
570 Ebml_SerializeFloat(ebml, Segment_Duration,
571 ebml->last_pts_ms + frame_time);
572 Ebml_SerializeString(ebml, 0x4D80,
573 ebml->debug ? "vpxenc" : "vpxenc" VERSION_STRING);
574 Ebml_SerializeString(ebml, 0x5741,
575 ebml->debug ? "vpxenc" : "vpxenc" VERSION_STRING);
576 Ebml_EndSubElement(ebml, &startInfo);
582 write_webm_file_header(EbmlGlobal *glob,
583 const vpx_codec_enc_cfg_t *cfg,
584 const struct vpx_rational *fps)
588 Ebml_StartSubElement(glob, &start, EBML);
589 Ebml_SerializeUnsigned(glob, EBMLVersion, 1);
590 Ebml_SerializeUnsigned(glob, EBMLReadVersion, 1); //EBML Read Version
591 Ebml_SerializeUnsigned(glob, EBMLMaxIDLength, 4); //EBML Max ID Length
592 Ebml_SerializeUnsigned(glob, EBMLMaxSizeLength, 8); //EBML Max Size Length
593 Ebml_SerializeString(glob, DocType, "webm"); //Doc Type
594 Ebml_SerializeUnsigned(glob, DocTypeVersion, 2); //Doc Type Version
595 Ebml_SerializeUnsigned(glob, DocTypeReadVersion, 2); //Doc Type Read Version
596 Ebml_EndSubElement(glob, &start);
599 Ebml_StartSubElement(glob, &glob->startSegment, Segment); //segment
600 glob->position_reference = ftello(glob->stream);
601 glob->framerate = *fps;
602 write_webm_seek_info(glob);
606 glob->track_pos = ftello(glob->stream);
607 Ebml_StartSubElement(glob, &trackStart, Tracks);
609 unsigned int trackNumber = 1;
610 uint64_t trackID = 0;
613 Ebml_StartSubElement(glob, &start, TrackEntry);
614 Ebml_SerializeUnsigned(glob, TrackNumber, trackNumber);
615 glob->track_id_pos = ftello(glob->stream);
616 Ebml_SerializeUnsigned32(glob, TrackUID, trackID);
617 Ebml_SerializeUnsigned(glob, TrackType, 1); //video is always 1
618 Ebml_SerializeString(glob, CodecID, "V_VP8");
620 unsigned int pixelWidth = cfg->g_w;
621 unsigned int pixelHeight = cfg->g_h;
622 float frameRate = (float)fps->num/(float)fps->den;
625 Ebml_StartSubElement(glob, &videoStart, Video);
626 Ebml_SerializeUnsigned(glob, PixelWidth, pixelWidth);
627 Ebml_SerializeUnsigned(glob, PixelHeight, pixelHeight);
628 Ebml_SerializeFloat(glob, FrameRate, frameRate);
629 Ebml_EndSubElement(glob, &videoStart); //Video
631 Ebml_EndSubElement(glob, &start); //Track Entry
633 Ebml_EndSubElement(glob, &trackStart);
635 // segment element is open
641 write_webm_block(EbmlGlobal *glob,
642 const vpx_codec_enc_cfg_t *cfg,
643 const vpx_codec_cx_pkt_t *pkt)
645 unsigned long block_length;
646 unsigned char track_number;
647 unsigned short block_timecode = 0;
650 int start_cluster = 0, is_keyframe;
652 /* Calculate the PTS of this frame in milliseconds */
653 pts_ms = pkt->data.frame.pts * 1000
654 * (uint64_t)cfg->g_timebase.num / (uint64_t)cfg->g_timebase.den;
655 if(pts_ms <= glob->last_pts_ms)
656 pts_ms = glob->last_pts_ms + 1;
657 glob->last_pts_ms = pts_ms;
659 /* Calculate the relative time of this block */
660 if(pts_ms - glob->cluster_timecode > SHRT_MAX)
663 block_timecode = pts_ms - glob->cluster_timecode;
665 is_keyframe = (pkt->data.frame.flags & VPX_FRAME_IS_KEY);
666 if(start_cluster || is_keyframe)
668 if(glob->cluster_open)
669 Ebml_EndSubElement(glob, &glob->startCluster);
671 /* Open the new cluster */
673 glob->cluster_open = 1;
674 glob->cluster_timecode = pts_ms;
675 glob->cluster_pos = ftello(glob->stream);
676 Ebml_StartSubElement(glob, &glob->startCluster, Cluster); //cluster
677 Ebml_SerializeUnsigned(glob, Timecode, glob->cluster_timecode);
679 /* Save a cue point if this is a keyframe. */
682 struct cue_entry *cue;
684 glob->cue_list = realloc(glob->cue_list,
685 (glob->cues+1) * sizeof(struct cue_entry));
686 cue = &glob->cue_list[glob->cues];
687 cue->time = glob->cluster_timecode;
688 cue->loc = glob->cluster_pos;
693 /* Write the Simple Block */
694 Ebml_WriteID(glob, SimpleBlock);
696 block_length = pkt->data.frame.sz + 4;
697 block_length |= 0x10000000;
698 Ebml_Serialize(glob, &block_length, 4);
701 track_number |= 0x80;
702 Ebml_Write(glob, &track_number, 1);
704 Ebml_Serialize(glob, &block_timecode, 2);
709 if(pkt->data.frame.flags & VPX_FRAME_IS_INVISIBLE)
711 Ebml_Write(glob, &flags, 1);
713 Ebml_Write(glob, pkt->data.frame.buf, pkt->data.frame.sz);
718 write_webm_file_footer(EbmlGlobal *glob, long hash)
721 if(glob->cluster_open)
722 Ebml_EndSubElement(glob, &glob->startCluster);
728 glob->cue_pos = ftello(glob->stream);
729 Ebml_StartSubElement(glob, &start, Cues);
730 for(i=0; i<glob->cues; i++)
732 struct cue_entry *cue = &glob->cue_list[i];
735 Ebml_StartSubElement(glob, &start, CuePoint);
739 Ebml_SerializeUnsigned(glob, CueTime, cue->time);
741 Ebml_StartSubElement(glob, &start, CueTrackPositions);
742 Ebml_SerializeUnsigned(glob, CueTrack, 1);
743 Ebml_SerializeUnsigned64(glob, CueClusterPosition,
744 cue->loc - glob->position_reference);
745 //Ebml_SerializeUnsigned(glob, CueBlockNumber, cue->blockNumber);
746 Ebml_EndSubElement(glob, &start);
748 Ebml_EndSubElement(glob, &start);
750 Ebml_EndSubElement(glob, &start);
753 Ebml_EndSubElement(glob, &glob->startSegment);
755 /* Patch up the seek info block */
756 write_webm_seek_info(glob);
758 /* Patch up the track id */
759 fseeko(glob->stream, glob->track_id_pos, SEEK_SET);
760 Ebml_SerializeUnsigned32(glob, TrackUID, glob->debug ? 0xDEADBEEF : hash);
762 fseeko(glob->stream, 0, SEEK_END);
766 /* Murmur hash derived from public domain reference implementation at
767 * http://sites.google.com/site/murmurhash/
769 static unsigned int murmur ( const void * key, int len, unsigned int seed )
771 const unsigned int m = 0x5bd1e995;
774 unsigned int h = seed ^ len;
776 const unsigned char * data = (const unsigned char *)key;
800 case 3: h ^= data[2] << 16;
801 case 2: h ^= data[1] << 8;
802 case 1: h ^= data[0];
815 static double vp8_mse2psnr(double Samples, double Peak, double Mse)
819 if ((double)Mse > 0.0)
820 psnr = 10.0 * log10(Peak * Peak * Samples / Mse);
822 psnr = 60; // Limit to prevent / 0
833 static const arg_def_t debugmode = ARG_DEF("D", "debug", 0,
834 "Debug mode (makes output deterministic)");
835 static const arg_def_t outputfile = ARG_DEF("o", "output", 1,
837 static const arg_def_t use_yv12 = ARG_DEF(NULL, "yv12", 0,
838 "Input file is YV12 ");
839 static const arg_def_t use_i420 = ARG_DEF(NULL, "i420", 0,
840 "Input file is I420 (default)");
841 static const arg_def_t codecarg = ARG_DEF(NULL, "codec", 1,
843 static const arg_def_t passes = ARG_DEF("p", "passes", 1,
844 "Number of passes (1/2)");
845 static const arg_def_t pass_arg = ARG_DEF(NULL, "pass", 1,
846 "Pass to execute (1/2)");
847 static const arg_def_t fpf_name = ARG_DEF(NULL, "fpf", 1,
848 "First pass statistics file name");
849 static const arg_def_t limit = ARG_DEF(NULL, "limit", 1,
850 "Stop encoding after n input frames");
851 static const arg_def_t deadline = ARG_DEF("d", "deadline", 1,
852 "Deadline per frame (usec)");
853 static const arg_def_t best_dl = ARG_DEF(NULL, "best", 0,
854 "Use Best Quality Deadline");
855 static const arg_def_t good_dl = ARG_DEF(NULL, "good", 0,
856 "Use Good Quality Deadline");
857 static const arg_def_t rt_dl = ARG_DEF(NULL, "rt", 0,
858 "Use Realtime Quality Deadline");
859 static const arg_def_t verbosearg = ARG_DEF("v", "verbose", 0,
860 "Show encoder parameters");
861 static const arg_def_t psnrarg = ARG_DEF(NULL, "psnr", 0,
862 "Show PSNR in status line");
863 static const arg_def_t framerate = ARG_DEF(NULL, "fps", 1,
864 "Stream frame rate (rate/scale)");
865 static const arg_def_t use_ivf = ARG_DEF(NULL, "ivf", 0,
866 "Output IVF (default is WebM)");
867 static const arg_def_t *main_args[] =
870 &outputfile, &codecarg, &passes, &pass_arg, &fpf_name, &limit, &deadline,
871 &best_dl, &good_dl, &rt_dl,
872 &verbosearg, &psnrarg, &use_ivf, &framerate,
876 static const arg_def_t usage = ARG_DEF("u", "usage", 1,
877 "Usage profile number to use");
878 static const arg_def_t threads = ARG_DEF("t", "threads", 1,
879 "Max number of threads to use");
880 static const arg_def_t profile = ARG_DEF(NULL, "profile", 1,
881 "Bitstream profile number to use");
882 static const arg_def_t width = ARG_DEF("w", "width", 1,
884 static const arg_def_t height = ARG_DEF("h", "height", 1,
886 static const arg_def_t timebase = ARG_DEF(NULL, "timebase", 1,
887 "Stream timebase (frame duration)");
888 static const arg_def_t error_resilient = ARG_DEF(NULL, "error-resilient", 1,
889 "Enable error resiliency features");
890 static const arg_def_t lag_in_frames = ARG_DEF(NULL, "lag-in-frames", 1,
891 "Max number of frames to lag");
893 static const arg_def_t *global_args[] =
895 &use_yv12, &use_i420, &usage, &threads, &profile,
896 &width, &height, &timebase, &framerate, &error_resilient,
900 static const arg_def_t dropframe_thresh = ARG_DEF(NULL, "drop-frame", 1,
901 "Temporal resampling threshold (buf %)");
902 static const arg_def_t resize_allowed = ARG_DEF(NULL, "resize-allowed", 1,
903 "Spatial resampling enabled (bool)");
904 static const arg_def_t resize_up_thresh = ARG_DEF(NULL, "resize-up", 1,
905 "Upscale threshold (buf %)");
906 static const arg_def_t resize_down_thresh = ARG_DEF(NULL, "resize-down", 1,
907 "Downscale threshold (buf %)");
908 static const arg_def_t end_usage = ARG_DEF(NULL, "end-usage", 1,
910 static const arg_def_t target_bitrate = ARG_DEF(NULL, "target-bitrate", 1,
912 static const arg_def_t min_quantizer = ARG_DEF(NULL, "min-q", 1,
913 "Minimum (best) quantizer");
914 static const arg_def_t max_quantizer = ARG_DEF(NULL, "max-q", 1,
915 "Maximum (worst) quantizer");
916 static const arg_def_t undershoot_pct = ARG_DEF(NULL, "undershoot-pct", 1,
917 "Datarate undershoot (min) target (%)");
918 static const arg_def_t overshoot_pct = ARG_DEF(NULL, "overshoot-pct", 1,
919 "Datarate overshoot (max) target (%)");
920 static const arg_def_t buf_sz = ARG_DEF(NULL, "buf-sz", 1,
921 "Client buffer size (ms)");
922 static const arg_def_t buf_initial_sz = ARG_DEF(NULL, "buf-initial-sz", 1,
923 "Client initial buffer size (ms)");
924 static const arg_def_t buf_optimal_sz = ARG_DEF(NULL, "buf-optimal-sz", 1,
925 "Client optimal buffer size (ms)");
926 static const arg_def_t *rc_args[] =
928 &dropframe_thresh, &resize_allowed, &resize_up_thresh, &resize_down_thresh,
929 &end_usage, &target_bitrate, &min_quantizer, &max_quantizer,
930 &undershoot_pct, &overshoot_pct, &buf_sz, &buf_initial_sz, &buf_optimal_sz,
935 static const arg_def_t bias_pct = ARG_DEF(NULL, "bias-pct", 1,
936 "CBR/VBR bias (0=CBR, 100=VBR)");
937 static const arg_def_t minsection_pct = ARG_DEF(NULL, "minsection-pct", 1,
938 "GOP min bitrate (% of target)");
939 static const arg_def_t maxsection_pct = ARG_DEF(NULL, "maxsection-pct", 1,
940 "GOP max bitrate (% of target)");
941 static const arg_def_t *rc_twopass_args[] =
943 &bias_pct, &minsection_pct, &maxsection_pct, NULL
947 static const arg_def_t kf_min_dist = ARG_DEF(NULL, "kf-min-dist", 1,
948 "Minimum keyframe interval (frames)");
949 static const arg_def_t kf_max_dist = ARG_DEF(NULL, "kf-max-dist", 1,
950 "Maximum keyframe interval (frames)");
951 static const arg_def_t kf_disabled = ARG_DEF(NULL, "disable-kf", 0,
952 "Disable keyframe placement");
953 static const arg_def_t *kf_args[] =
955 &kf_min_dist, &kf_max_dist, &kf_disabled, NULL
959 #if CONFIG_VP8_ENCODER
960 static const arg_def_t noise_sens = ARG_DEF(NULL, "noise-sensitivity", 1,
961 "Noise sensitivity (frames to blur)");
962 static const arg_def_t sharpness = ARG_DEF(NULL, "sharpness", 1,
963 "Filter sharpness (0-7)");
964 static const arg_def_t static_thresh = ARG_DEF(NULL, "static-thresh", 1,
965 "Motion detection threshold");
968 #if CONFIG_VP8_ENCODER
969 static const arg_def_t cpu_used = ARG_DEF(NULL, "cpu-used", 1,
970 "CPU Used (-16..16)");
974 #if CONFIG_VP8_ENCODER
975 static const arg_def_t token_parts = ARG_DEF(NULL, "token-parts", 1,
976 "Number of token partitions to use, log2");
977 static const arg_def_t auto_altref = ARG_DEF(NULL, "auto-alt-ref", 1,
978 "Enable automatic alt reference frames");
979 static const arg_def_t arnr_maxframes = ARG_DEF(NULL, "arnr-maxframes", 1,
980 "alt_ref Max Frames");
981 static const arg_def_t arnr_strength = ARG_DEF(NULL, "arnr-strength", 1,
983 static const arg_def_t arnr_type = ARG_DEF(NULL, "arnr-type", 1,
986 static const arg_def_t *vp8_args[] =
988 &cpu_used, &auto_altref, &noise_sens, &sharpness, &static_thresh,
989 &token_parts, &arnr_maxframes, &arnr_strength, &arnr_type, NULL
991 static const int vp8_arg_ctrl_map[] =
993 VP8E_SET_CPUUSED, VP8E_SET_ENABLEAUTOALTREF,
994 VP8E_SET_NOISE_SENSITIVITY, VP8E_SET_SHARPNESS, VP8E_SET_STATIC_THRESHOLD,
995 VP8E_SET_TOKEN_PARTITIONS,
996 VP8E_SET_ARNR_MAXFRAMES, VP8E_SET_ARNR_STRENGTH , VP8E_SET_ARNR_TYPE, 0
1000 static const arg_def_t *no_args[] = { NULL };
1002 static void usage_exit()
1006 fprintf(stderr, "Usage: %s <options> -o dst_filename src_filename \n",
1009 fprintf(stderr, "\nOptions:\n");
1010 arg_show_usage(stdout, main_args);
1011 fprintf(stderr, "\nEncoder Global Options:\n");
1012 arg_show_usage(stdout, global_args);
1013 fprintf(stderr, "\nRate Control Options:\n");
1014 arg_show_usage(stdout, rc_args);
1015 fprintf(stderr, "\nTwopass Rate Control Options:\n");
1016 arg_show_usage(stdout, rc_twopass_args);
1017 fprintf(stderr, "\nKeyframe Placement Options:\n");
1018 arg_show_usage(stdout, kf_args);
1019 #if CONFIG_VP8_ENCODER
1020 fprintf(stderr, "\nVP8 Specific Options:\n");
1021 arg_show_usage(stdout, vp8_args);
1023 fprintf(stderr, "\n"
1024 "Included encoders:\n"
1027 for (i = 0; i < sizeof(codecs) / sizeof(codecs[0]); i++)
1028 fprintf(stderr, " %-6s - %s\n",
1030 vpx_codec_iface_name(codecs[i].iface));
1035 #define ARG_CTRL_CNT_MAX 10
1038 int main(int argc, const char **argv_)
1040 vpx_codec_ctx_t encoder;
1041 const char *in_fn = NULL, *out_fn = NULL, *stats_fn = NULL;
1043 FILE *infile, *outfile;
1044 vpx_codec_enc_cfg_t cfg;
1045 vpx_codec_err_t res;
1046 int pass, one_pass_only = 0;
1049 const struct codec_item *codec = codecs;
1050 int frame_avail, got_data;
1053 char **argv, **argi, **argj;
1054 int arg_usage = 0, arg_passes = 1, arg_deadline = 0;
1055 int arg_ctrls[ARG_CTRL_CNT_MAX][2], arg_ctrl_cnt = 0;
1057 static const arg_def_t **ctrl_args = no_args;
1058 static const int *ctrl_args_map = NULL;
1059 int verbose = 0, show_psnr = 0;
1060 int arg_use_i420 = 1;
1061 unsigned long cx_time = 0;
1062 unsigned int file_type, fourcc;
1064 struct vpx_rational arg_framerate = {30, 1};
1065 int arg_have_framerate = 0;
1067 EbmlGlobal ebml = {0};
1069 uint64_t psnr_sse_total = 0;
1070 uint64_t psnr_samples_total = 0;
1071 double psnr_totals[4] = {0, 0, 0, 0};
1074 exec_name = argv_[0];
1080 /* First parse the codec and usage values, because we want to apply other
1081 * parameters on top of the default configuration provided by the codec.
1083 argv = argv_dup(argc - 1, argv_ + 1);
1085 for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step)
1089 if (arg_match(&arg, &codecarg, argi))
1093 for (j = 0; j < sizeof(codecs) / sizeof(codecs[0]); j++)
1094 if (!strcmp(codecs[j].name, arg.val))
1100 die("Error: Unrecognized argument (%s) to --codec\n",
1104 else if (arg_match(&arg, &passes, argi))
1106 arg_passes = arg_parse_uint(&arg);
1108 if (arg_passes < 1 || arg_passes > 2)
1109 die("Error: Invalid number of passes (%d)\n", arg_passes);
1111 else if (arg_match(&arg, &pass_arg, argi))
1113 one_pass_only = arg_parse_uint(&arg);
1115 if (one_pass_only < 1 || one_pass_only > 2)
1116 die("Error: Invalid pass selected (%d)\n", one_pass_only);
1118 else if (arg_match(&arg, &fpf_name, argi))
1120 else if (arg_match(&arg, &usage, argi))
1121 arg_usage = arg_parse_uint(&arg);
1122 else if (arg_match(&arg, &deadline, argi))
1123 arg_deadline = arg_parse_uint(&arg);
1124 else if (arg_match(&arg, &best_dl, argi))
1125 arg_deadline = VPX_DL_BEST_QUALITY;
1126 else if (arg_match(&arg, &good_dl, argi))
1127 arg_deadline = VPX_DL_GOOD_QUALITY;
1128 else if (arg_match(&arg, &rt_dl, argi))
1129 arg_deadline = VPX_DL_REALTIME;
1130 else if (arg_match(&arg, &use_yv12, argi))
1134 else if (arg_match(&arg, &use_i420, argi))
1138 else if (arg_match(&arg, &verbosearg, argi))
1140 else if (arg_match(&arg, &limit, argi))
1141 arg_limit = arg_parse_uint(&arg);
1142 else if (arg_match(&arg, &psnrarg, argi))
1144 else if (arg_match(&arg, &framerate, argi))
1146 arg_framerate = arg_parse_rational(&arg);
1147 arg_have_framerate = 1;
1149 else if (arg_match(&arg, &use_ivf, argi))
1151 else if (arg_match(&arg, &outputfile, argi))
1153 else if (arg_match(&arg, &debugmode, argi))
1159 /* Ensure that --passes and --pass are consistent. If --pass is set and --passes=2,
1160 * ensure --fpf was set.
1164 /* DWIM: Assume the user meant passes=2 if pass=2 is specified */
1165 if (one_pass_only > arg_passes)
1167 fprintf(stderr, "Warning: Assuming --pass=%d implies --passes=%d\n",
1168 one_pass_only, one_pass_only);
1169 arg_passes = one_pass_only;
1172 if (arg_passes == 2 && !stats_fn)
1173 die("Must specify --fpf when --pass=%d and --passes=2\n", one_pass_only);
1176 /* Populate encoder configuration */
1177 res = vpx_codec_enc_config_default(codec->iface, &cfg, arg_usage);
1181 fprintf(stderr, "Failed to get config: %s\n",
1182 vpx_codec_err_to_string(res));
1183 return EXIT_FAILURE;
1186 /* Change the default timebase to a high enough value so that the encoder
1187 * will always create strictly increasing timestamps.
1189 cfg.g_timebase.den = 1000;
1191 /* Now parse the remainder of the parameters. */
1192 for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step)
1197 else if (arg_match(&arg, &threads, argi))
1198 cfg.g_threads = arg_parse_uint(&arg);
1199 else if (arg_match(&arg, &profile, argi))
1200 cfg.g_profile = arg_parse_uint(&arg);
1201 else if (arg_match(&arg, &width, argi))
1202 cfg.g_w = arg_parse_uint(&arg);
1203 else if (arg_match(&arg, &height, argi))
1204 cfg.g_h = arg_parse_uint(&arg);
1205 else if (arg_match(&arg, &timebase, argi))
1206 cfg.g_timebase = arg_parse_rational(&arg);
1207 else if (arg_match(&arg, &error_resilient, argi))
1208 cfg.g_error_resilient = arg_parse_uint(&arg);
1209 else if (arg_match(&arg, &lag_in_frames, argi))
1210 cfg.g_lag_in_frames = arg_parse_uint(&arg);
1211 else if (arg_match(&arg, &dropframe_thresh, argi))
1212 cfg.rc_dropframe_thresh = arg_parse_uint(&arg);
1213 else if (arg_match(&arg, &resize_allowed, argi))
1214 cfg.rc_resize_allowed = arg_parse_uint(&arg);
1215 else if (arg_match(&arg, &resize_up_thresh, argi))
1216 cfg.rc_resize_up_thresh = arg_parse_uint(&arg);
1217 else if (arg_match(&arg, &resize_down_thresh, argi))
1218 cfg.rc_resize_down_thresh = arg_parse_uint(&arg);
1219 else if (arg_match(&arg, &resize_down_thresh, argi))
1220 cfg.rc_resize_down_thresh = arg_parse_uint(&arg);
1221 else if (arg_match(&arg, &end_usage, argi))
1222 cfg.rc_end_usage = arg_parse_uint(&arg);
1223 else if (arg_match(&arg, &target_bitrate, argi))
1224 cfg.rc_target_bitrate = arg_parse_uint(&arg);
1225 else if (arg_match(&arg, &min_quantizer, argi))
1226 cfg.rc_min_quantizer = arg_parse_uint(&arg);
1227 else if (arg_match(&arg, &max_quantizer, argi))
1228 cfg.rc_max_quantizer = arg_parse_uint(&arg);
1229 else if (arg_match(&arg, &undershoot_pct, argi))
1230 cfg.rc_undershoot_pct = arg_parse_uint(&arg);
1231 else if (arg_match(&arg, &overshoot_pct, argi))
1232 cfg.rc_overshoot_pct = arg_parse_uint(&arg);
1233 else if (arg_match(&arg, &buf_sz, argi))
1234 cfg.rc_buf_sz = arg_parse_uint(&arg);
1235 else if (arg_match(&arg, &buf_initial_sz, argi))
1236 cfg.rc_buf_initial_sz = arg_parse_uint(&arg);
1237 else if (arg_match(&arg, &buf_optimal_sz, argi))
1238 cfg.rc_buf_optimal_sz = arg_parse_uint(&arg);
1239 else if (arg_match(&arg, &bias_pct, argi))
1241 cfg.rc_2pass_vbr_bias_pct = arg_parse_uint(&arg);
1245 "Warning: option %s ignored in one-pass mode.\n",
1248 else if (arg_match(&arg, &minsection_pct, argi))
1250 cfg.rc_2pass_vbr_minsection_pct = arg_parse_uint(&arg);
1254 "Warning: option %s ignored in one-pass mode.\n",
1257 else if (arg_match(&arg, &maxsection_pct, argi))
1259 cfg.rc_2pass_vbr_maxsection_pct = arg_parse_uint(&arg);
1263 "Warning: option %s ignored in one-pass mode.\n",
1266 else if (arg_match(&arg, &kf_min_dist, argi))
1267 cfg.kf_min_dist = arg_parse_uint(&arg);
1268 else if (arg_match(&arg, &kf_max_dist, argi))
1269 cfg.kf_max_dist = arg_parse_uint(&arg);
1270 else if (arg_match(&arg, &kf_disabled, argi))
1271 cfg.kf_mode = VPX_KF_DISABLED;
1276 /* Handle codec specific options */
1277 #if CONFIG_VP8_ENCODER
1279 if (codec->iface == &vpx_codec_vp8_cx_algo)
1281 ctrl_args = vp8_args;
1282 ctrl_args_map = vp8_arg_ctrl_map;
1287 for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step)
1293 for (i = 0; ctrl_args[i]; i++)
1295 if (arg_match(&arg, ctrl_args[i], argi))
1299 if (arg_ctrl_cnt < ARG_CTRL_CNT_MAX)
1301 arg_ctrls[arg_ctrl_cnt][0] = ctrl_args_map[i];
1302 arg_ctrls[arg_ctrl_cnt][1] = arg_parse_int(&arg);
1312 /* Check for unrecognized options */
1313 for (argi = argv; *argi; argi++)
1314 if (argi[0][0] == '-' && argi[0][1])
1315 die("Error: Unrecognized option %s\n", *argi);
1317 /* Handle non-option arguments */
1324 die("Error: Output file is required (specify with -o)\n");
1326 memset(&stats, 0, sizeof(stats));
1328 for (pass = one_pass_only ? one_pass_only - 1 : 0; pass < arg_passes; pass++)
1330 int frames_in = 0, frames_out = 0;
1331 unsigned long nbytes = 0;
1332 struct detect_buffer detect;
1334 /* Parse certain options from the input file, if possible */
1335 infile = strcmp(in_fn, "-") ? fopen(in_fn, "rb") : stdin;
1339 fprintf(stderr, "Failed to open input file\n");
1340 return EXIT_FAILURE;
1343 fread(detect.buf, 1, 4, infile);
1346 if (file_is_y4m(infile, &y4m, detect.buf))
1348 if (y4m_input_open(&y4m, infile, detect.buf, 4) >= 0)
1350 file_type = FILE_TYPE_Y4M;
1351 cfg.g_w = y4m.pic_w;
1352 cfg.g_h = y4m.pic_h;
1354 /* Use the frame rate from the file only if none was specified
1355 * on the command-line.
1357 if (!arg_have_framerate)
1359 arg_framerate.num = y4m.fps_n;
1360 arg_framerate.den = y4m.fps_d;
1367 fprintf(stderr, "Unsupported Y4M stream.\n");
1368 return EXIT_FAILURE;
1371 else if (file_is_ivf(infile, &fourcc, &cfg.g_w, &cfg.g_h, detect.buf))
1373 file_type = FILE_TYPE_IVF;
1383 fprintf(stderr, "Unsupported fourcc (%08x) in IVF\n", fourcc);
1384 return EXIT_FAILURE;
1389 file_type = FILE_TYPE_RAW;
1392 #define SHOW(field) fprintf(stderr, " %-28s = %d\n", #field, cfg.field)
1394 if (verbose && pass == 0)
1396 fprintf(stderr, "Codec: %s\n", vpx_codec_iface_name(codec->iface));
1397 fprintf(stderr, "Source file: %s Format: %s\n", in_fn,
1398 arg_use_i420 ? "I420" : "YV12");
1399 fprintf(stderr, "Destination file: %s\n", out_fn);
1400 fprintf(stderr, "Encoder parameters:\n");
1407 SHOW(g_timebase.num);
1408 SHOW(g_timebase.den);
1409 SHOW(g_error_resilient);
1411 SHOW(g_lag_in_frames);
1412 SHOW(rc_dropframe_thresh);
1413 SHOW(rc_resize_allowed);
1414 SHOW(rc_resize_up_thresh);
1415 SHOW(rc_resize_down_thresh);
1417 SHOW(rc_target_bitrate);
1418 SHOW(rc_min_quantizer);
1419 SHOW(rc_max_quantizer);
1420 SHOW(rc_undershoot_pct);
1421 SHOW(rc_overshoot_pct);
1423 SHOW(rc_buf_initial_sz);
1424 SHOW(rc_buf_optimal_sz);
1425 SHOW(rc_2pass_vbr_bias_pct);
1426 SHOW(rc_2pass_vbr_minsection_pct);
1427 SHOW(rc_2pass_vbr_maxsection_pct);
1433 if(pass == (one_pass_only ? one_pass_only - 1 : 0)) {
1434 if (file_type == FILE_TYPE_Y4M)
1435 /*The Y4M reader does its own allocation.
1436 Just initialize this here to avoid problems if we never read any
1438 memset(&raw, 0, sizeof(raw));
1440 vpx_img_alloc(&raw, arg_use_i420 ? VPX_IMG_FMT_I420 : VPX_IMG_FMT_YV12,
1441 cfg.g_w, cfg.g_h, 1);
1444 outfile = strcmp(out_fn, "-") ? fopen(out_fn, "wb") : stdout;
1448 fprintf(stderr, "Failed to open output file\n");
1449 return EXIT_FAILURE;
1452 if(write_webm && fseek(outfile, 0, SEEK_CUR))
1454 fprintf(stderr, "WebM output to pipes not supported.\n");
1455 return EXIT_FAILURE;
1460 if (!stats_open_file(&stats, stats_fn, pass))
1462 fprintf(stderr, "Failed to open statistics store\n");
1463 return EXIT_FAILURE;
1468 if (!stats_open_mem(&stats, pass))
1470 fprintf(stderr, "Failed to open statistics store\n");
1471 return EXIT_FAILURE;
1475 cfg.g_pass = arg_passes == 2
1476 ? pass ? VPX_RC_LAST_PASS : VPX_RC_FIRST_PASS
1478 #if VPX_ENCODER_ABI_VERSION > (1 + VPX_CODEC_ABI_VERSION)
1482 cfg.rc_twopass_stats_in = stats_get(&stats);
1489 ebml.stream = outfile;
1490 write_webm_file_header(&ebml, &cfg, &arg_framerate);
1493 write_ivf_file_header(outfile, &cfg, codec->fourcc, 0);
1496 /* Construct Encoder Context */
1497 vpx_codec_enc_init(&encoder, codec->iface, &cfg,
1498 show_psnr ? VPX_CODEC_USE_PSNR : 0);
1499 ctx_exit_on_error(&encoder, "Failed to initialize encoder");
1501 /* Note that we bypass the vpx_codec_control wrapper macro because
1502 * we're being clever to store the control IDs in an array. Real
1503 * applications will want to make use of the enumerations directly
1505 for (i = 0; i < arg_ctrl_cnt; i++)
1507 if (vpx_codec_control_(&encoder, arg_ctrls[i][0], arg_ctrls[i][1]))
1508 fprintf(stderr, "Error: Tried to set control %d = %d\n",
1509 arg_ctrls[i][0], arg_ctrls[i][1]);
1511 ctx_exit_on_error(&encoder, "Failed to control codec");
1517 while (frame_avail || got_data)
1519 vpx_codec_iter_t iter = NULL;
1520 const vpx_codec_cx_pkt_t *pkt;
1521 struct vpx_usec_timer timer;
1522 int64_t frame_start;
1524 if (!arg_limit || frames_in < arg_limit)
1526 frame_avail = read_frame(infile, &raw, file_type, &y4m,
1533 "\rPass %d/%d frame %4d/%-4d %7ldB \033[K", pass + 1,
1534 arg_passes, frames_in, frames_out, nbytes);
1539 vpx_usec_timer_start(&timer);
1541 frame_start = (cfg.g_timebase.den * (int64_t)(frames_in - 1)
1542 * arg_framerate.den) / cfg.g_timebase.num / arg_framerate.num;
1543 vpx_codec_encode(&encoder, frame_avail ? &raw : NULL, frame_start,
1544 cfg.g_timebase.den * arg_framerate.den
1545 / cfg.g_timebase.num / arg_framerate.num,
1547 vpx_usec_timer_mark(&timer);
1548 cx_time += vpx_usec_timer_elapsed(&timer);
1549 ctx_exit_on_error(&encoder, "Failed to encode frame");
1552 while ((pkt = vpx_codec_get_cx_data(&encoder, &iter)))
1558 case VPX_CODEC_CX_FRAME_PKT:
1560 fprintf(stderr, " %6luF",
1561 (unsigned long)pkt->data.frame.sz);
1565 /* Update the hash */
1567 hash = murmur(pkt->data.frame.buf,
1568 pkt->data.frame.sz, hash);
1570 write_webm_block(&ebml, &cfg, pkt);
1574 write_ivf_frame_header(outfile, pkt);
1575 fwrite(pkt->data.frame.buf, 1, pkt->data.frame.sz, outfile);
1577 nbytes += pkt->data.raw.sz;
1579 case VPX_CODEC_STATS_PKT:
1581 fprintf(stderr, " %6luS",
1582 (unsigned long)pkt->data.twopass_stats.sz);
1584 pkt->data.twopass_stats.buf,
1585 pkt->data.twopass_stats.sz);
1586 nbytes += pkt->data.raw.sz;
1588 case VPX_CODEC_PSNR_PKT:
1594 psnr_sse_total += pkt->data.psnr.sse[0];
1595 psnr_samples_total += pkt->data.psnr.samples[0];
1596 for (i = 0; i < 4; i++)
1598 fprintf(stderr, "%.3lf ", pkt->data.psnr.psnr[i]);
1599 psnr_totals[i] += pkt->data.psnr.psnr[i];
1614 "\rPass %d/%d frame %4d/%-4d %7ldB %7ldb/f %7"PRId64"b/s"
1615 " %7lu %s (%.2f fps)\033[K", pass + 1,
1616 arg_passes, frames_in, frames_out, nbytes, nbytes * 8 / frames_in,
1617 nbytes * 8 *(int64_t)arg_framerate.num / arg_framerate.den / frames_in,
1618 cx_time > 9999999 ? cx_time / 1000 : cx_time,
1619 cx_time > 9999999 ? "ms" : "us",
1620 (float)frames_in * 1000000.0 / (float)cx_time);
1622 if ( (show_psnr) && (psnr_count>0) )
1625 double ovpsnr = vp8_mse2psnr(psnr_samples_total, 255.0,
1628 fprintf(stderr, "\nPSNR (Overall/Avg/Y/U/V)");
1630 fprintf(stderr, " %.3lf", ovpsnr);
1631 for (i = 0; i < 4; i++)
1633 fprintf(stderr, " %.3lf", psnr_totals[i]/psnr_count);
1637 vpx_codec_destroy(&encoder);
1643 write_webm_file_footer(&ebml, hash);
1647 if (!fseek(outfile, 0, SEEK_SET))
1648 write_ivf_file_header(outfile, &cfg, codec->fourcc, frames_out);
1652 stats_close(&stats);
1653 fprintf(stderr, "\n");
1661 return EXIT_SUCCESS;