postproc: Add mode and refrence frame visualizers.
[libvpx.git] / vpxenc.c
bloba17878217d3daddda67333dda0ac720e12eff646
1 /*
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.
9 */
12 /* This is a simple program that encodes YV12 files and generates ivf
13 * files using the new interface.
15 #if defined(_WIN32)
16 #define USE_POSIX_MMAP 0
17 #else
18 #define USE_POSIX_MMAP 1
19 #endif
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <stdarg.h>
24 #include <string.h>
25 #include <limits.h>
26 #include "vpx/vpx_encoder.h"
27 #if USE_POSIX_MMAP
28 #include <sys/types.h>
29 #include <sys/stat.h>
30 #include <sys/mman.h>
31 #include <fcntl.h>
32 #include <unistd.h>
33 #endif
34 #include "vpx_version.h"
35 #include "vpx/vp8cx.h"
36 #include "vpx_ports/mem_ops.h"
37 #include "vpx_ports/vpx_timer.h"
38 #include "y4minput.h"
39 #include "libmkv/EbmlWriter.h"
40 #include "libmkv/EbmlIDs.h"
42 /* Need special handling of these functions on Windows */
43 #if defined(_MSC_VER)
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
48 #elif defined(_WIN32)
49 /* MinGW defines off_t, and uses f{seek,tell}o64 */
50 #define fseeko fseeko64
51 #define ftello ftello64
52 #endif
54 #if defined(_MSC_VER)
55 #define LITERALU64(n) n
56 #else
57 #define LITERALU64(n) n##LLU
58 #endif
60 static const char *exec_name;
62 static const struct codec_item
64 char const *name;
65 const vpx_codec_iface_t *iface;
66 unsigned int fourcc;
67 } codecs[] =
69 #if CONFIG_VP8_ENCODER
70 {"vp8", &vpx_codec_vp8_cx_algo, 0x30385056},
71 #endif
74 static void usage_exit();
76 void die(const char *fmt, ...)
78 va_list ap;
79 va_start(ap, fmt);
80 vfprintf(stderr, fmt, ap);
81 fprintf(stderr, "\n");
82 usage_exit();
85 static void ctx_exit_on_error(vpx_codec_ctx_t *ctx, const char *s)
87 if (ctx->err)
89 const char *detail = vpx_codec_error_detail(ctx);
91 fprintf(stderr, "%s: %s\n", s, vpx_codec_error(ctx));
93 if (detail)
94 fprintf(stderr, " %s\n", detail);
96 exit(EXIT_FAILURE);
100 /* This structure is used to abstract the different ways of handling
101 * first pass statistics.
103 typedef struct
105 vpx_fixed_buf_t buf;
106 int pass;
107 FILE *file;
108 char *buf_ptr;
109 size_t buf_alloc_sz;
110 } stats_io_t;
112 int stats_open_file(stats_io_t *stats, const char *fpf, int pass)
114 int res;
116 stats->pass = pass;
118 if (pass == 0)
120 stats->file = fopen(fpf, "wb");
121 stats->buf.sz = 0;
122 stats->buf.buf = NULL,
123 res = (stats->file != NULL);
125 else
127 #if 0
128 #elif USE_POSIX_MMAP
129 struct stat stat_buf;
130 int fd;
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,
137 fd, 0);
138 res = (stats->buf.buf != NULL);
139 #else
140 size_t nbytes;
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");
147 exit(EXIT_FAILURE);
150 stats->buf.sz = stats->buf_alloc_sz = ftell(stats->file);
151 rewind(stats->file);
153 stats->buf.buf = malloc(stats->buf_alloc_sz);
155 if (!stats->buf.buf)
157 fprintf(stderr, "Failed to allocate first-pass stats buffer (%d bytes)\n",
158 stats->buf_alloc_sz);
159 exit(EXIT_FAILURE);
162 nbytes = fread(stats->buf.buf, 1, stats->buf.sz, stats->file);
163 res = (nbytes == stats->buf.sz);
164 #endif
167 return res;
170 int stats_open_mem(stats_io_t *stats, int pass)
172 int res;
173 stats->pass = pass;
175 if (!pass)
177 stats->buf.sz = 0;
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);
184 return res;
188 void stats_close(stats_io_t *stats)
190 if (stats->file)
192 if (stats->pass == 1)
194 #if 0
195 #elif USE_POSIX_MMAP
196 munmap(stats->buf.buf, stats->buf.sz);
197 #else
198 free(stats->buf.buf);
199 #endif
202 fclose(stats->file);
203 stats->file = NULL;
205 else
207 if (stats->pass == 1)
208 free(stats->buf.buf);
212 void stats_write(stats_io_t *stats, const void *pkt, size_t len)
214 if (stats->file)
216 fwrite(pkt, 1, len, stats->file);
218 else
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);
225 if (new_ptr)
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;
230 } /* else ... */
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)
241 return stats->buf;
244 enum video_file_type
246 FILE_TYPE_RAW,
247 FILE_TYPE_IVF,
248 FILE_TYPE_Y4M
251 struct detect_buffer {
252 char buf[4];
253 int valid;
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)
261 int plane = 0;
263 if (file_type == FILE_TYPE_Y4M)
265 if (y4m_input_fetch_frame(y4m, f, img) < 0)
266 return 0;
268 else
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
276 * layout.
278 fread(junk, 1, IVF_FRAME_HDR_SZ, f);
281 for (plane = 0; plane < 3; plane++)
283 unsigned char *ptr;
284 int w = (plane ? (1 + img->d_w) / 2 : img->d_w);
285 int h = (plane ? (1 + img->d_h) / 2 : img->d_h);
286 int r;
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
290 * the data on disk.
292 switch (plane)
294 case 1:
295 ptr = img->planes[img->fmt==VPX_IMG_FMT_YV12? VPX_PLANE_V : VPX_PLANE_U];
296 break;
297 case 2:
298 ptr = img->planes[img->fmt==VPX_IMG_FMT_YV12?VPX_PLANE_U : VPX_PLANE_V];
299 break;
300 default:
301 ptr = img->planes[plane];
304 for (r = 0; r < h; r++)
306 if (detect->valid)
308 memcpy(ptr, detect->buf, 4);
309 fread(ptr+4, 1, w-4, f);
310 detect->valid = 0;
312 else
313 fread(ptr, 1, w, f);
315 ptr += img->stride[plane];
320 return !feof(f);
324 unsigned int file_is_y4m(FILE *infile,
325 y4m_input *y4m,
326 char detect[4])
328 if(memcmp(detect, "YUV4", 4) == 0)
330 return 1;
332 return 0;
335 #define IVF_FILE_HDR_SZ (32)
336 unsigned int file_is_ivf(FILE *infile,
337 unsigned int *fourcc,
338 unsigned int *width,
339 unsigned int *height,
340 char detect[4])
342 char raw_hdr[IVF_FILE_HDR_SZ];
343 int is_ivf = 0;
345 if(memcmp(detect, "DKIF", 4) != 0)
346 return 0;
348 /* See write_ivf_file_header() for more documentation on the file header
349 * layout.
351 if (fread(raw_hdr + 4, 1, IVF_FILE_HDR_SZ - 4, infile)
352 == IVF_FILE_HDR_SZ - 4)
355 is_ivf = 1;
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);
365 if (is_ivf)
367 *width = mem_get_le16(raw_hdr + 12);
368 *height = mem_get_le16(raw_hdr + 14);
371 return is_ivf;
375 static void write_ivf_file_header(FILE *outfile,
376 const vpx_codec_enc_cfg_t *cfg,
377 unsigned int fourcc,
378 int frame_cnt)
380 char header[32];
382 if (cfg->g_pass != VPX_RC_ONE_PASS && cfg->g_pass != VPX_RC_LAST_PASS)
383 return;
385 header[0] = 'D';
386 header[1] = 'K';
387 header[2] = 'I';
388 header[3] = 'F';
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)
406 char header[12];
407 vpx_codec_pts_t pts;
409 if (pkt->kind != VPX_CODEC_CX_FRAME_PKT)
410 return;
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;
424 struct cue_entry
426 unsigned int time;
427 uint64_t loc;
431 struct EbmlGlobal
433 FILE *stream;
434 uint64_t last_pts_ms;
435 vpx_rational_t framerate;
437 /* These pointers are to the start of an element */
438 off_t position_reference;
439 off_t seek_info_pos;
440 off_t segment_info_pos;
441 off_t track_pos;
442 off_t cue_pos;
443 off_t cluster_pos;
445 /* These pointers are to the size field of the element */
446 EbmlLoc startSegment;
447 EbmlLoc startCluster;
449 uint32_t cluster_timecode;
450 int cluster_open;
452 struct cue_entry *cue_list;
453 unsigned int cues;
458 void Ebml_Write(EbmlGlobal *glob, const void *buffer_in, unsigned long len)
460 fwrite(buffer_in, 1, len, glob->stream);
464 void Ebml_Serialize(EbmlGlobal *glob, const void *buffer_in, unsigned long len)
466 const unsigned char *q = (const unsigned char *)buffer_in + len - 1;
468 for(; len; len--)
469 Ebml_Write(glob, q--, 1);
473 static void
474 Ebml_StartSubElement(EbmlGlobal *glob, EbmlLoc *ebmlLoc,
475 unsigned long class_id)
477 //todo this is always taking 8 bytes, this may need later optimization
478 //this is a key that says lenght unknown
479 unsigned long long unknownLen = LITERALU64(0x01FFFFFFFFFFFFFF);
481 Ebml_WriteID(glob, class_id);
482 *ebmlLoc = ftello(glob->stream);
483 Ebml_Serialize(glob, &unknownLen, 8);
486 static void
487 Ebml_EndSubElement(EbmlGlobal *glob, EbmlLoc *ebmlLoc)
489 off_t pos;
490 uint64_t size;
492 /* Save the current stream pointer */
493 pos = ftello(glob->stream);
495 /* Calculate the size of this element */
496 size = pos - *ebmlLoc - 8;
497 size |= LITERALU64(0x0100000000000000);
499 /* Seek back to the beginning of the element and write the new size */
500 fseeko(glob->stream, *ebmlLoc, SEEK_SET);
501 Ebml_Serialize(glob, &size, 8);
503 /* Reset the stream pointer */
504 fseeko(glob->stream, pos, SEEK_SET);
508 static void
509 write_webm_seek_element(EbmlGlobal *ebml, unsigned long id, off_t pos)
511 uint64_t offset = pos - ebml->position_reference;
512 EbmlLoc start;
513 Ebml_StartSubElement(ebml, &start, Seek);
514 Ebml_SerializeBinary(ebml, SeekID, id);
515 Ebml_SerializeUnsigned64(ebml, SeekPosition, offset);
516 Ebml_EndSubElement(ebml, &start);
520 static void
521 write_webm_seek_info(EbmlGlobal *ebml)
524 off_t pos;
526 /* Save the current stream pointer */
527 pos = ftello(ebml->stream);
529 if(ebml->seek_info_pos)
530 fseeko(ebml->stream, ebml->seek_info_pos, SEEK_SET);
531 else
532 ebml->seek_info_pos = pos;
535 EbmlLoc start;
537 Ebml_StartSubElement(ebml, &start, SeekHead);
538 write_webm_seek_element(ebml, Tracks, ebml->track_pos);
539 write_webm_seek_element(ebml, Cues, ebml->cue_pos);
540 write_webm_seek_element(ebml, Info, ebml->segment_info_pos);
541 Ebml_EndSubElement(ebml, &start);
544 //segment info
545 EbmlLoc startInfo;
546 uint64_t frame_time;
548 frame_time = (uint64_t)1000 * ebml->framerate.den
549 / ebml->framerate.num;
550 ebml->segment_info_pos = ftello(ebml->stream);
551 Ebml_StartSubElement(ebml, &startInfo, Info);
552 Ebml_SerializeUnsigned(ebml, TimecodeScale, 1000000);
553 Ebml_SerializeFloat(ebml, Segment_Duration,
554 ebml->last_pts_ms + frame_time);
555 Ebml_SerializeString(ebml, 0x4D80, "vpxenc" VERSION_STRING);
556 Ebml_SerializeString(ebml, 0x5741, "vpxenc" VERSION_STRING);
557 Ebml_EndSubElement(ebml, &startInfo);
562 static void
563 write_webm_file_header(EbmlGlobal *glob,
564 const vpx_codec_enc_cfg_t *cfg,
565 const struct vpx_rational *fps)
568 EbmlLoc start;
569 Ebml_StartSubElement(glob, &start, EBML);
570 Ebml_SerializeUnsigned(glob, EBMLVersion, 1);
571 Ebml_SerializeUnsigned(glob, EBMLReadVersion, 1); //EBML Read Version
572 Ebml_SerializeUnsigned(glob, EBMLMaxIDLength, 4); //EBML Max ID Length
573 Ebml_SerializeUnsigned(glob, EBMLMaxSizeLength, 8); //EBML Max Size Length
574 Ebml_SerializeString(glob, DocType, "webm"); //Doc Type
575 Ebml_SerializeUnsigned(glob, DocTypeVersion, 2); //Doc Type Version
576 Ebml_SerializeUnsigned(glob, DocTypeReadVersion, 2); //Doc Type Read Version
577 Ebml_EndSubElement(glob, &start);
580 Ebml_StartSubElement(glob, &glob->startSegment, Segment); //segment
581 glob->position_reference = ftello(glob->stream);
582 glob->framerate = *fps;
583 write_webm_seek_info(glob);
586 EbmlLoc trackStart;
587 glob->track_pos = ftello(glob->stream);
588 Ebml_StartSubElement(glob, &trackStart, Tracks);
590 unsigned int trackNumber = 1;
591 uint64_t trackID = 0;
593 EbmlLoc start;
594 Ebml_StartSubElement(glob, &start, TrackEntry);
595 Ebml_SerializeUnsigned(glob, TrackNumber, trackNumber);
596 Ebml_SerializeUnsigned(glob, TrackUID, trackID);
597 Ebml_SerializeUnsigned(glob, TrackType, 1); //video is always 1
598 Ebml_SerializeString(glob, CodecID, "V_VP8");
600 unsigned int pixelWidth = cfg->g_w;
601 unsigned int pixelHeight = cfg->g_h;
602 float frameRate = (float)fps->num/(float)fps->den;
604 EbmlLoc videoStart;
605 Ebml_StartSubElement(glob, &videoStart, Video);
606 Ebml_SerializeUnsigned(glob, PixelWidth, pixelWidth);
607 Ebml_SerializeUnsigned(glob, PixelHeight, pixelHeight);
608 Ebml_SerializeFloat(glob, FrameRate, frameRate);
609 Ebml_EndSubElement(glob, &videoStart); //Video
611 Ebml_EndSubElement(glob, &start); //Track Entry
613 Ebml_EndSubElement(glob, &trackStart);
615 // segment element is open
620 static void
621 write_webm_block(EbmlGlobal *glob,
622 const vpx_codec_enc_cfg_t *cfg,
623 const vpx_codec_cx_pkt_t *pkt)
625 unsigned long block_length;
626 unsigned char track_number;
627 unsigned short block_timecode = 0;
628 unsigned char flags;
629 uint64_t pts_ms;
630 int start_cluster = 0, is_keyframe;
632 /* Calculate the PTS of this frame in milliseconds */
633 pts_ms = pkt->data.frame.pts * 1000
634 * (uint64_t)cfg->g_timebase.num / (uint64_t)cfg->g_timebase.den;
635 if(pts_ms <= glob->last_pts_ms)
636 pts_ms = glob->last_pts_ms + 1;
637 glob->last_pts_ms = pts_ms;
639 /* Calculate the relative time of this block */
640 if(pts_ms - glob->cluster_timecode > SHRT_MAX)
641 start_cluster = 1;
642 else
643 block_timecode = pts_ms - glob->cluster_timecode;
645 is_keyframe = (pkt->data.frame.flags & VPX_FRAME_IS_KEY);
646 if(start_cluster || is_keyframe)
648 if(glob->cluster_open)
649 Ebml_EndSubElement(glob, &glob->startCluster);
651 /* Open the new cluster */
652 block_timecode = 0;
653 glob->cluster_open = 1;
654 glob->cluster_timecode = pts_ms;
655 glob->cluster_pos = ftello(glob->stream);
656 Ebml_StartSubElement(glob, &glob->startCluster, Cluster); //cluster
657 Ebml_SerializeUnsigned(glob, Timecode, glob->cluster_timecode);
659 /* Save a cue point if this is a keyframe. */
660 if(is_keyframe)
662 struct cue_entry *cue;
664 glob->cue_list = realloc(glob->cue_list,
665 (glob->cues+1) * sizeof(struct cue_entry));
666 cue = &glob->cue_list[glob->cues];
667 cue->time = glob->cluster_timecode;
668 cue->loc = glob->cluster_pos;
669 glob->cues++;
673 /* Write the Simple Block */
674 Ebml_WriteID(glob, SimpleBlock);
676 block_length = pkt->data.frame.sz + 4;
677 block_length |= 0x10000000;
678 Ebml_Serialize(glob, &block_length, 4);
680 track_number = 1;
681 track_number |= 0x80;
682 Ebml_Write(glob, &track_number, 1);
684 Ebml_Serialize(glob, &block_timecode, 2);
686 flags = 0;
687 if(is_keyframe)
688 flags |= 0x80;
689 if(pkt->data.frame.flags & VPX_FRAME_IS_INVISIBLE)
690 flags |= 0x08;
691 Ebml_Write(glob, &flags, 1);
693 Ebml_Write(glob, pkt->data.frame.buf, pkt->data.frame.sz);
697 static void
698 write_webm_file_footer(EbmlGlobal *glob)
701 if(glob->cluster_open)
702 Ebml_EndSubElement(glob, &glob->startCluster);
705 EbmlLoc start;
706 int i;
708 glob->cue_pos = ftello(glob->stream);
709 Ebml_StartSubElement(glob, &start, Cues);
710 for(i=0; i<glob->cues; i++)
712 struct cue_entry *cue = &glob->cue_list[i];
713 EbmlLoc start;
715 Ebml_StartSubElement(glob, &start, CuePoint);
717 EbmlLoc start;
719 Ebml_SerializeUnsigned(glob, CueTime, cue->time);
721 Ebml_StartSubElement(glob, &start, CueTrackPositions);
722 Ebml_SerializeUnsigned(glob, CueTrack, 1);
723 Ebml_SerializeUnsigned64(glob, CueClusterPosition,
724 cue->loc - glob->position_reference);
725 //Ebml_SerializeUnsigned(glob, CueBlockNumber, cue->blockNumber);
726 Ebml_EndSubElement(glob, &start);
728 Ebml_EndSubElement(glob, &start);
730 Ebml_EndSubElement(glob, &start);
733 Ebml_EndSubElement(glob, &glob->startSegment);
735 /* Patch up the seek info block */
736 write_webm_seek_info(glob);
737 fseeko(glob->stream, 0, SEEK_END);
741 #include "args.h"
743 static const arg_def_t outputfile = ARG_DEF("o", "output", 1,
744 "Output filename");
745 static const arg_def_t use_yv12 = ARG_DEF(NULL, "yv12", 0,
746 "Input file is YV12 ");
747 static const arg_def_t use_i420 = ARG_DEF(NULL, "i420", 0,
748 "Input file is I420 (default)");
749 static const arg_def_t codecarg = ARG_DEF(NULL, "codec", 1,
750 "Codec to use");
751 static const arg_def_t passes = ARG_DEF("p", "passes", 1,
752 "Number of passes (1/2)");
753 static const arg_def_t pass_arg = ARG_DEF(NULL, "pass", 1,
754 "Pass to execute (1/2)");
755 static const arg_def_t fpf_name = ARG_DEF(NULL, "fpf", 1,
756 "First pass statistics file name");
757 static const arg_def_t limit = ARG_DEF(NULL, "limit", 1,
758 "Stop encoding after n input frames");
759 static const arg_def_t deadline = ARG_DEF("d", "deadline", 1,
760 "Deadline per frame (usec)");
761 static const arg_def_t best_dl = ARG_DEF(NULL, "best", 0,
762 "Use Best Quality Deadline");
763 static const arg_def_t good_dl = ARG_DEF(NULL, "good", 0,
764 "Use Good Quality Deadline");
765 static const arg_def_t rt_dl = ARG_DEF(NULL, "rt", 0,
766 "Use Realtime Quality Deadline");
767 static const arg_def_t verbosearg = ARG_DEF("v", "verbose", 0,
768 "Show encoder parameters");
769 static const arg_def_t psnrarg = ARG_DEF(NULL, "psnr", 0,
770 "Show PSNR in status line");
771 static const arg_def_t framerate = ARG_DEF(NULL, "fps", 1,
772 "Stream frame rate (rate/scale)");
773 static const arg_def_t use_ivf = ARG_DEF(NULL, "ivf", 0,
774 "Output IVF (default is WebM)");
775 static const arg_def_t *main_args[] =
777 &outputfile, &codecarg, &passes, &pass_arg, &fpf_name, &limit, &deadline,
778 &best_dl, &good_dl, &rt_dl,
779 &verbosearg, &psnrarg, &use_ivf, &framerate,
780 NULL
783 static const arg_def_t usage = ARG_DEF("u", "usage", 1,
784 "Usage profile number to use");
785 static const arg_def_t threads = ARG_DEF("t", "threads", 1,
786 "Max number of threads to use");
787 static const arg_def_t profile = ARG_DEF(NULL, "profile", 1,
788 "Bitstream profile number to use");
789 static const arg_def_t width = ARG_DEF("w", "width", 1,
790 "Frame width");
791 static const arg_def_t height = ARG_DEF("h", "height", 1,
792 "Frame height");
793 static const arg_def_t timebase = ARG_DEF(NULL, "timebase", 1,
794 "Stream timebase (frame duration)");
795 static const arg_def_t error_resilient = ARG_DEF(NULL, "error-resilient", 1,
796 "Enable error resiliency features");
797 static const arg_def_t lag_in_frames = ARG_DEF(NULL, "lag-in-frames", 1,
798 "Max number of frames to lag");
800 static const arg_def_t *global_args[] =
802 &use_yv12, &use_i420, &usage, &threads, &profile,
803 &width, &height, &timebase, &framerate, &error_resilient,
804 &lag_in_frames, NULL
807 static const arg_def_t dropframe_thresh = ARG_DEF(NULL, "drop-frame", 1,
808 "Temporal resampling threshold (buf %)");
809 static const arg_def_t resize_allowed = ARG_DEF(NULL, "resize-allowed", 1,
810 "Spatial resampling enabled (bool)");
811 static const arg_def_t resize_up_thresh = ARG_DEF(NULL, "resize-up", 1,
812 "Upscale threshold (buf %)");
813 static const arg_def_t resize_down_thresh = ARG_DEF(NULL, "resize-down", 1,
814 "Downscale threshold (buf %)");
815 static const arg_def_t end_usage = ARG_DEF(NULL, "end-usage", 1,
816 "VBR=0 | CBR=1");
817 static const arg_def_t target_bitrate = ARG_DEF(NULL, "target-bitrate", 1,
818 "Bitrate (kbps)");
819 static const arg_def_t min_quantizer = ARG_DEF(NULL, "min-q", 1,
820 "Minimum (best) quantizer");
821 static const arg_def_t max_quantizer = ARG_DEF(NULL, "max-q", 1,
822 "Maximum (worst) quantizer");
823 static const arg_def_t undershoot_pct = ARG_DEF(NULL, "undershoot-pct", 1,
824 "Datarate undershoot (min) target (%)");
825 static const arg_def_t overshoot_pct = ARG_DEF(NULL, "overshoot-pct", 1,
826 "Datarate overshoot (max) target (%)");
827 static const arg_def_t buf_sz = ARG_DEF(NULL, "buf-sz", 1,
828 "Client buffer size (ms)");
829 static const arg_def_t buf_initial_sz = ARG_DEF(NULL, "buf-initial-sz", 1,
830 "Client initial buffer size (ms)");
831 static const arg_def_t buf_optimal_sz = ARG_DEF(NULL, "buf-optimal-sz", 1,
832 "Client optimal buffer size (ms)");
833 static const arg_def_t *rc_args[] =
835 &dropframe_thresh, &resize_allowed, &resize_up_thresh, &resize_down_thresh,
836 &end_usage, &target_bitrate, &min_quantizer, &max_quantizer,
837 &undershoot_pct, &overshoot_pct, &buf_sz, &buf_initial_sz, &buf_optimal_sz,
838 NULL
842 static const arg_def_t bias_pct = ARG_DEF(NULL, "bias-pct", 1,
843 "CBR/VBR bias (0=CBR, 100=VBR)");
844 static const arg_def_t minsection_pct = ARG_DEF(NULL, "minsection-pct", 1,
845 "GOP min bitrate (% of target)");
846 static const arg_def_t maxsection_pct = ARG_DEF(NULL, "maxsection-pct", 1,
847 "GOP max bitrate (% of target)");
848 static const arg_def_t *rc_twopass_args[] =
850 &bias_pct, &minsection_pct, &maxsection_pct, NULL
854 static const arg_def_t kf_min_dist = ARG_DEF(NULL, "kf-min-dist", 1,
855 "Minimum keyframe interval (frames)");
856 static const arg_def_t kf_max_dist = ARG_DEF(NULL, "kf-max-dist", 1,
857 "Maximum keyframe interval (frames)");
858 static const arg_def_t kf_disabled = ARG_DEF(NULL, "disable-kf", 0,
859 "Disable keyframe placement");
860 static const arg_def_t *kf_args[] =
862 &kf_min_dist, &kf_max_dist, &kf_disabled, NULL
866 #if CONFIG_VP8_ENCODER
867 static const arg_def_t noise_sens = ARG_DEF(NULL, "noise-sensitivity", 1,
868 "Noise sensitivity (frames to blur)");
869 static const arg_def_t sharpness = ARG_DEF(NULL, "sharpness", 1,
870 "Filter sharpness (0-7)");
871 static const arg_def_t static_thresh = ARG_DEF(NULL, "static-thresh", 1,
872 "Motion detection threshold");
873 #endif
875 #if CONFIG_VP8_ENCODER
876 static const arg_def_t cpu_used = ARG_DEF(NULL, "cpu-used", 1,
877 "CPU Used (-16..16)");
878 #endif
881 #if CONFIG_VP8_ENCODER
882 static const arg_def_t token_parts = ARG_DEF(NULL, "token-parts", 1,
883 "Number of token partitions to use, log2");
884 static const arg_def_t auto_altref = ARG_DEF(NULL, "auto-alt-ref", 1,
885 "Enable automatic alt reference frames");
886 static const arg_def_t arnr_maxframes = ARG_DEF(NULL, "arnr-maxframes", 1,
887 "alt_ref Max Frames");
888 static const arg_def_t arnr_strength = ARG_DEF(NULL, "arnr-strength", 1,
889 "alt_ref Strength");
890 static const arg_def_t arnr_type = ARG_DEF(NULL, "arnr-type", 1,
891 "alt_ref Type");
893 static const arg_def_t *vp8_args[] =
895 &cpu_used, &auto_altref, &noise_sens, &sharpness, &static_thresh,
896 &token_parts, &arnr_maxframes, &arnr_strength, &arnr_type, NULL
898 static const int vp8_arg_ctrl_map[] =
900 VP8E_SET_CPUUSED, VP8E_SET_ENABLEAUTOALTREF,
901 VP8E_SET_NOISE_SENSITIVITY, VP8E_SET_SHARPNESS, VP8E_SET_STATIC_THRESHOLD,
902 VP8E_SET_TOKEN_PARTITIONS,
903 VP8E_SET_ARNR_MAXFRAMES, VP8E_SET_ARNR_STRENGTH , VP8E_SET_ARNR_TYPE, 0
905 #endif
907 static const arg_def_t *no_args[] = { NULL };
909 static void usage_exit()
911 int i;
913 fprintf(stderr, "Usage: %s <options> -o dst_filename src_filename \n",
914 exec_name);
916 fprintf(stderr, "\nOptions:\n");
917 arg_show_usage(stdout, main_args);
918 fprintf(stderr, "\nEncoder Global Options:\n");
919 arg_show_usage(stdout, global_args);
920 fprintf(stderr, "\nRate Control Options:\n");
921 arg_show_usage(stdout, rc_args);
922 fprintf(stderr, "\nTwopass Rate Control Options:\n");
923 arg_show_usage(stdout, rc_twopass_args);
924 fprintf(stderr, "\nKeyframe Placement Options:\n");
925 arg_show_usage(stdout, kf_args);
926 #if CONFIG_VP8_ENCODER
927 fprintf(stderr, "\nVP8 Specific Options:\n");
928 arg_show_usage(stdout, vp8_args);
929 #endif
930 fprintf(stderr, "\n"
931 "Included encoders:\n"
932 "\n");
934 for (i = 0; i < sizeof(codecs) / sizeof(codecs[0]); i++)
935 fprintf(stderr, " %-6s - %s\n",
936 codecs[i].name,
937 vpx_codec_iface_name(codecs[i].iface));
939 exit(EXIT_FAILURE);
942 #define ARG_CTRL_CNT_MAX 10
945 int main(int argc, const char **argv_)
947 vpx_codec_ctx_t encoder;
948 const char *in_fn = NULL, *out_fn = NULL, *stats_fn = NULL;
949 int i;
950 FILE *infile, *outfile;
951 vpx_codec_enc_cfg_t cfg;
952 vpx_codec_err_t res;
953 int pass, one_pass_only = 0;
954 stats_io_t stats;
955 vpx_image_t raw;
956 const struct codec_item *codec = codecs;
957 int frame_avail, got_data;
959 struct arg arg;
960 char **argv, **argi, **argj;
961 int arg_usage = 0, arg_passes = 1, arg_deadline = 0;
962 int arg_ctrls[ARG_CTRL_CNT_MAX][2], arg_ctrl_cnt = 0;
963 int arg_limit = 0;
964 static const arg_def_t **ctrl_args = no_args;
965 static const int *ctrl_args_map = NULL;
966 int verbose = 0, show_psnr = 0;
967 int arg_use_i420 = 1;
968 unsigned long cx_time = 0;
969 unsigned int file_type, fourcc;
970 y4m_input y4m;
971 struct vpx_rational arg_framerate = {30, 1};
972 int arg_have_framerate = 0;
973 int write_webm = 1;
974 EbmlGlobal ebml = {0};
976 exec_name = argv_[0];
978 if (argc < 3)
979 usage_exit();
982 /* First parse the codec and usage values, because we want to apply other
983 * parameters on top of the default configuration provided by the codec.
985 argv = argv_dup(argc - 1, argv_ + 1);
987 for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step)
989 arg.argv_step = 1;
991 if (arg_match(&arg, &codecarg, argi))
993 int j, k = -1;
995 for (j = 0; j < sizeof(codecs) / sizeof(codecs[0]); j++)
996 if (!strcmp(codecs[j].name, arg.val))
997 k = j;
999 if (k >= 0)
1000 codec = codecs + k;
1001 else
1002 die("Error: Unrecognized argument (%s) to --codec\n",
1003 arg.val);
1006 else if (arg_match(&arg, &passes, argi))
1008 arg_passes = arg_parse_uint(&arg);
1010 if (arg_passes < 1 || arg_passes > 2)
1011 die("Error: Invalid number of passes (%d)\n", arg_passes);
1013 else if (arg_match(&arg, &pass_arg, argi))
1015 one_pass_only = arg_parse_uint(&arg);
1017 if (one_pass_only < 1 || one_pass_only > 2)
1018 die("Error: Invalid pass selected (%d)\n", one_pass_only);
1020 else if (arg_match(&arg, &fpf_name, argi))
1021 stats_fn = arg.val;
1022 else if (arg_match(&arg, &usage, argi))
1023 arg_usage = arg_parse_uint(&arg);
1024 else if (arg_match(&arg, &deadline, argi))
1025 arg_deadline = arg_parse_uint(&arg);
1026 else if (arg_match(&arg, &best_dl, argi))
1027 arg_deadline = VPX_DL_BEST_QUALITY;
1028 else if (arg_match(&arg, &good_dl, argi))
1029 arg_deadline = VPX_DL_GOOD_QUALITY;
1030 else if (arg_match(&arg, &rt_dl, argi))
1031 arg_deadline = VPX_DL_REALTIME;
1032 else if (arg_match(&arg, &use_yv12, argi))
1034 arg_use_i420 = 0;
1036 else if (arg_match(&arg, &use_i420, argi))
1038 arg_use_i420 = 1;
1040 else if (arg_match(&arg, &verbosearg, argi))
1041 verbose = 1;
1042 else if (arg_match(&arg, &limit, argi))
1043 arg_limit = arg_parse_uint(&arg);
1044 else if (arg_match(&arg, &psnrarg, argi))
1045 show_psnr = 1;
1046 else if (arg_match(&arg, &framerate, argi))
1048 arg_framerate = arg_parse_rational(&arg);
1049 arg_have_framerate = 1;
1051 else if (arg_match(&arg, &use_ivf, argi))
1052 write_webm = 0;
1053 else if (arg_match(&arg, &outputfile, argi))
1054 out_fn = arg.val;
1055 else
1056 argj++;
1059 /* Ensure that --passes and --pass are consistent. If --pass is set and --passes=2,
1060 * ensure --fpf was set.
1062 if (one_pass_only)
1064 /* DWIM: Assume the user meant passes=2 if pass=2 is specified */
1065 if (one_pass_only > arg_passes)
1067 fprintf(stderr, "Warning: Assuming --pass=%d implies --passes=%d\n",
1068 one_pass_only, one_pass_only);
1069 arg_passes = one_pass_only;
1072 if (arg_passes == 2 && !stats_fn)
1073 die("Must specify --fpf when --pass=%d and --passes=2\n", one_pass_only);
1076 /* Populate encoder configuration */
1077 res = vpx_codec_enc_config_default(codec->iface, &cfg, arg_usage);
1079 if (res)
1081 fprintf(stderr, "Failed to get config: %s\n",
1082 vpx_codec_err_to_string(res));
1083 return EXIT_FAILURE;
1086 /* Change the default timebase to a high enough value so that the encoder
1087 * will always create strictly increasing timestamps.
1089 cfg.g_timebase.den = 1000;
1091 /* Now parse the remainder of the parameters. */
1092 for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step)
1094 arg.argv_step = 1;
1096 if (0);
1097 else if (arg_match(&arg, &threads, argi))
1098 cfg.g_threads = arg_parse_uint(&arg);
1099 else if (arg_match(&arg, &profile, argi))
1100 cfg.g_profile = arg_parse_uint(&arg);
1101 else if (arg_match(&arg, &width, argi))
1102 cfg.g_w = arg_parse_uint(&arg);
1103 else if (arg_match(&arg, &height, argi))
1104 cfg.g_h = arg_parse_uint(&arg);
1105 else if (arg_match(&arg, &timebase, argi))
1106 cfg.g_timebase = arg_parse_rational(&arg);
1107 else if (arg_match(&arg, &error_resilient, argi))
1108 cfg.g_error_resilient = arg_parse_uint(&arg);
1109 else if (arg_match(&arg, &lag_in_frames, argi))
1110 cfg.g_lag_in_frames = arg_parse_uint(&arg);
1111 else if (arg_match(&arg, &dropframe_thresh, argi))
1112 cfg.rc_dropframe_thresh = arg_parse_uint(&arg);
1113 else if (arg_match(&arg, &resize_allowed, argi))
1114 cfg.rc_resize_allowed = arg_parse_uint(&arg);
1115 else if (arg_match(&arg, &resize_up_thresh, argi))
1116 cfg.rc_resize_up_thresh = arg_parse_uint(&arg);
1117 else if (arg_match(&arg, &resize_down_thresh, argi))
1118 cfg.rc_resize_down_thresh = arg_parse_uint(&arg);
1119 else if (arg_match(&arg, &resize_down_thresh, argi))
1120 cfg.rc_resize_down_thresh = arg_parse_uint(&arg);
1121 else if (arg_match(&arg, &end_usage, argi))
1122 cfg.rc_end_usage = arg_parse_uint(&arg);
1123 else if (arg_match(&arg, &target_bitrate, argi))
1124 cfg.rc_target_bitrate = arg_parse_uint(&arg);
1125 else if (arg_match(&arg, &min_quantizer, argi))
1126 cfg.rc_min_quantizer = arg_parse_uint(&arg);
1127 else if (arg_match(&arg, &max_quantizer, argi))
1128 cfg.rc_max_quantizer = arg_parse_uint(&arg);
1129 else if (arg_match(&arg, &undershoot_pct, argi))
1130 cfg.rc_undershoot_pct = arg_parse_uint(&arg);
1131 else if (arg_match(&arg, &overshoot_pct, argi))
1132 cfg.rc_overshoot_pct = arg_parse_uint(&arg);
1133 else if (arg_match(&arg, &buf_sz, argi))
1134 cfg.rc_buf_sz = arg_parse_uint(&arg);
1135 else if (arg_match(&arg, &buf_initial_sz, argi))
1136 cfg.rc_buf_initial_sz = arg_parse_uint(&arg);
1137 else if (arg_match(&arg, &buf_optimal_sz, argi))
1138 cfg.rc_buf_optimal_sz = arg_parse_uint(&arg);
1139 else if (arg_match(&arg, &bias_pct, argi))
1141 cfg.rc_2pass_vbr_bias_pct = arg_parse_uint(&arg);
1143 if (arg_passes < 2)
1144 fprintf(stderr,
1145 "Warning: option %s ignored in one-pass mode.\n",
1146 arg.name);
1148 else if (arg_match(&arg, &minsection_pct, argi))
1150 cfg.rc_2pass_vbr_minsection_pct = arg_parse_uint(&arg);
1152 if (arg_passes < 2)
1153 fprintf(stderr,
1154 "Warning: option %s ignored in one-pass mode.\n",
1155 arg.name);
1157 else if (arg_match(&arg, &maxsection_pct, argi))
1159 cfg.rc_2pass_vbr_maxsection_pct = arg_parse_uint(&arg);
1161 if (arg_passes < 2)
1162 fprintf(stderr,
1163 "Warning: option %s ignored in one-pass mode.\n",
1164 arg.name);
1166 else if (arg_match(&arg, &kf_min_dist, argi))
1167 cfg.kf_min_dist = arg_parse_uint(&arg);
1168 else if (arg_match(&arg, &kf_max_dist, argi))
1169 cfg.kf_max_dist = arg_parse_uint(&arg);
1170 else if (arg_match(&arg, &kf_disabled, argi))
1171 cfg.kf_mode = VPX_KF_DISABLED;
1172 else
1173 argj++;
1176 /* Handle codec specific options */
1177 #if CONFIG_VP8_ENCODER
1179 if (codec->iface == &vpx_codec_vp8_cx_algo)
1181 ctrl_args = vp8_args;
1182 ctrl_args_map = vp8_arg_ctrl_map;
1185 #endif
1187 for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step)
1189 int match = 0;
1191 arg.argv_step = 1;
1193 for (i = 0; ctrl_args[i]; i++)
1195 if (arg_match(&arg, ctrl_args[i], argi))
1197 match = 1;
1199 if (arg_ctrl_cnt < ARG_CTRL_CNT_MAX)
1201 arg_ctrls[arg_ctrl_cnt][0] = ctrl_args_map[i];
1202 arg_ctrls[arg_ctrl_cnt][1] = arg_parse_int(&arg);
1203 arg_ctrl_cnt++;
1208 if (!match)
1209 argj++;
1212 /* Check for unrecognized options */
1213 for (argi = argv; *argi; argi++)
1214 if (argi[0][0] == '-' && argi[0][1])
1215 die("Error: Unrecognized option %s\n", *argi);
1217 /* Handle non-option arguments */
1218 in_fn = argv[0];
1220 if (!in_fn)
1221 usage_exit();
1223 if(!out_fn)
1224 die("Error: Output file is required (specify with -o)\n");
1226 memset(&stats, 0, sizeof(stats));
1228 for (pass = one_pass_only ? one_pass_only - 1 : 0; pass < arg_passes; pass++)
1230 int frames_in = 0, frames_out = 0;
1231 unsigned long nbytes = 0;
1232 struct detect_buffer detect;
1234 /* Parse certain options from the input file, if possible */
1235 infile = strcmp(in_fn, "-") ? fopen(in_fn, "rb") : stdin;
1237 if (!infile)
1239 fprintf(stderr, "Failed to open input file\n");
1240 return EXIT_FAILURE;
1243 fread(detect.buf, 1, 4, infile);
1244 detect.valid = 0;
1246 if (file_is_y4m(infile, &y4m, detect.buf))
1248 if (y4m_input_open(&y4m, infile, detect.buf, 4) >= 0)
1250 file_type = FILE_TYPE_Y4M;
1251 cfg.g_w = y4m.pic_w;
1252 cfg.g_h = y4m.pic_h;
1254 /* Use the frame rate from the file only if none was specified
1255 * on the command-line.
1257 if (!arg_have_framerate)
1259 arg_framerate.num = y4m.fps_n;
1260 arg_framerate.den = y4m.fps_d;
1263 arg_use_i420 = 0;
1265 else
1267 fprintf(stderr, "Unsupported Y4M stream.\n");
1268 return EXIT_FAILURE;
1271 else if (file_is_ivf(infile, &fourcc, &cfg.g_w, &cfg.g_h, detect.buf))
1273 file_type = FILE_TYPE_IVF;
1274 switch (fourcc)
1276 case 0x32315659:
1277 arg_use_i420 = 0;
1278 break;
1279 case 0x30323449:
1280 arg_use_i420 = 1;
1281 break;
1282 default:
1283 fprintf(stderr, "Unsupported fourcc (%08x) in IVF\n", fourcc);
1284 return EXIT_FAILURE;
1287 else
1289 file_type = FILE_TYPE_RAW;
1290 detect.valid = 1;
1292 #define SHOW(field) fprintf(stderr, " %-28s = %d\n", #field, cfg.field)
1294 if (verbose && pass == 0)
1296 fprintf(stderr, "Codec: %s\n", vpx_codec_iface_name(codec->iface));
1297 fprintf(stderr, "Source file: %s Format: %s\n", in_fn,
1298 arg_use_i420 ? "I420" : "YV12");
1299 fprintf(stderr, "Destination file: %s\n", out_fn);
1300 fprintf(stderr, "Encoder parameters:\n");
1302 SHOW(g_usage);
1303 SHOW(g_threads);
1304 SHOW(g_profile);
1305 SHOW(g_w);
1306 SHOW(g_h);
1307 SHOW(g_timebase.num);
1308 SHOW(g_timebase.den);
1309 SHOW(g_error_resilient);
1310 SHOW(g_pass);
1311 SHOW(g_lag_in_frames);
1312 SHOW(rc_dropframe_thresh);
1313 SHOW(rc_resize_allowed);
1314 SHOW(rc_resize_up_thresh);
1315 SHOW(rc_resize_down_thresh);
1316 SHOW(rc_end_usage);
1317 SHOW(rc_target_bitrate);
1318 SHOW(rc_min_quantizer);
1319 SHOW(rc_max_quantizer);
1320 SHOW(rc_undershoot_pct);
1321 SHOW(rc_overshoot_pct);
1322 SHOW(rc_buf_sz);
1323 SHOW(rc_buf_initial_sz);
1324 SHOW(rc_buf_optimal_sz);
1325 SHOW(rc_2pass_vbr_bias_pct);
1326 SHOW(rc_2pass_vbr_minsection_pct);
1327 SHOW(rc_2pass_vbr_maxsection_pct);
1328 SHOW(kf_mode);
1329 SHOW(kf_min_dist);
1330 SHOW(kf_max_dist);
1333 if(pass == (one_pass_only ? one_pass_only - 1 : 0)) {
1334 if (file_type == FILE_TYPE_Y4M)
1335 /*The Y4M reader does its own allocation.
1336 Just initialize this here to avoid problems if we never read any
1337 frames.*/
1338 memset(&raw, 0, sizeof(raw));
1339 else
1340 vpx_img_alloc(&raw, arg_use_i420 ? VPX_IMG_FMT_I420 : VPX_IMG_FMT_YV12,
1341 cfg.g_w, cfg.g_h, 1);
1344 outfile = strcmp(out_fn, "-") ? fopen(out_fn, "wb") : stdout;
1346 if (!outfile)
1348 fprintf(stderr, "Failed to open output file\n");
1349 return EXIT_FAILURE;
1352 if(write_webm && fseek(outfile, 0, SEEK_CUR))
1354 fprintf(stderr, "WebM output to pipes not supported.\n");
1355 return EXIT_FAILURE;
1358 if (stats_fn)
1360 if (!stats_open_file(&stats, stats_fn, pass))
1362 fprintf(stderr, "Failed to open statistics store\n");
1363 return EXIT_FAILURE;
1366 else
1368 if (!stats_open_mem(&stats, pass))
1370 fprintf(stderr, "Failed to open statistics store\n");
1371 return EXIT_FAILURE;
1375 cfg.g_pass = arg_passes == 2
1376 ? pass ? VPX_RC_LAST_PASS : VPX_RC_FIRST_PASS
1377 : VPX_RC_ONE_PASS;
1378 #if VPX_ENCODER_ABI_VERSION > (1 + VPX_CODEC_ABI_VERSION)
1380 if (pass)
1382 cfg.rc_twopass_stats_in = stats_get(&stats);
1385 #endif
1387 if(write_webm)
1389 ebml.stream = outfile;
1390 write_webm_file_header(&ebml, &cfg, &arg_framerate);
1392 else
1393 write_ivf_file_header(outfile, &cfg, codec->fourcc, 0);
1396 /* Construct Encoder Context */
1397 vpx_codec_enc_init(&encoder, codec->iface, &cfg,
1398 show_psnr ? VPX_CODEC_USE_PSNR : 0);
1399 ctx_exit_on_error(&encoder, "Failed to initialize encoder");
1401 /* Note that we bypass the vpx_codec_control wrapper macro because
1402 * we're being clever to store the control IDs in an array. Real
1403 * applications will want to make use of the enumerations directly
1405 for (i = 0; i < arg_ctrl_cnt; i++)
1407 if (vpx_codec_control_(&encoder, arg_ctrls[i][0], arg_ctrls[i][1]))
1408 fprintf(stderr, "Error: Tried to set control %d = %d\n",
1409 arg_ctrls[i][0], arg_ctrls[i][1]);
1411 ctx_exit_on_error(&encoder, "Failed to control codec");
1414 frame_avail = 1;
1415 got_data = 0;
1417 while (frame_avail || got_data)
1419 vpx_codec_iter_t iter = NULL;
1420 const vpx_codec_cx_pkt_t *pkt;
1421 struct vpx_usec_timer timer;
1422 int64_t frame_start;
1424 if (!arg_limit || frames_in < arg_limit)
1426 frame_avail = read_frame(infile, &raw, file_type, &y4m,
1427 &detect);
1429 if (frame_avail)
1430 frames_in++;
1432 fprintf(stderr,
1433 "\rPass %d/%d frame %4d/%-4d %7ldB \033[K", pass + 1,
1434 arg_passes, frames_in, frames_out, nbytes);
1436 else
1437 frame_avail = 0;
1439 vpx_usec_timer_start(&timer);
1441 frame_start = (cfg.g_timebase.den * (int64_t)(frames_in - 1)
1442 * arg_framerate.den) / cfg.g_timebase.num / arg_framerate.num;
1443 vpx_codec_encode(&encoder, frame_avail ? &raw : NULL, frame_start,
1444 cfg.g_timebase.den * arg_framerate.den
1445 / cfg.g_timebase.num / arg_framerate.num,
1446 0, arg_deadline);
1447 vpx_usec_timer_mark(&timer);
1448 cx_time += vpx_usec_timer_elapsed(&timer);
1449 ctx_exit_on_error(&encoder, "Failed to encode frame");
1450 got_data = 0;
1452 while ((pkt = vpx_codec_get_cx_data(&encoder, &iter)))
1454 got_data = 1;
1456 switch (pkt->kind)
1458 case VPX_CODEC_CX_FRAME_PKT:
1459 frames_out++;
1460 fprintf(stderr, " %6luF",
1461 (unsigned long)pkt->data.frame.sz);
1462 if(write_webm)
1464 write_webm_block(&ebml, &cfg, pkt);
1466 else
1468 write_ivf_frame_header(outfile, pkt);
1469 fwrite(pkt->data.frame.buf, 1, pkt->data.frame.sz, outfile);
1471 nbytes += pkt->data.raw.sz;
1472 break;
1473 case VPX_CODEC_STATS_PKT:
1474 frames_out++;
1475 fprintf(stderr, " %6luS",
1476 (unsigned long)pkt->data.twopass_stats.sz);
1477 stats_write(&stats,
1478 pkt->data.twopass_stats.buf,
1479 pkt->data.twopass_stats.sz);
1480 nbytes += pkt->data.raw.sz;
1481 break;
1482 case VPX_CODEC_PSNR_PKT:
1484 if (show_psnr)
1486 int i;
1488 for (i = 0; i < 4; i++)
1489 fprintf(stderr, "%.3lf ", pkt->data.psnr.psnr[i]);
1492 break;
1493 default:
1494 break;
1498 fflush(stdout);
1501 fprintf(stderr,
1502 "\rPass %d/%d frame %4d/%-4d %7ldB %7ldb/f %7"PRId64"b/s"
1503 " %7lu %s (%.2f fps)\033[K", pass + 1,
1504 arg_passes, frames_in, frames_out, nbytes, nbytes * 8 / frames_in,
1505 nbytes * 8 *(int64_t)arg_framerate.num / arg_framerate.den / frames_in,
1506 cx_time > 9999999 ? cx_time / 1000 : cx_time,
1507 cx_time > 9999999 ? "ms" : "us",
1508 (float)frames_in * 1000000.0 / (float)cx_time);
1510 vpx_codec_destroy(&encoder);
1512 fclose(infile);
1514 if(write_webm)
1516 write_webm_file_footer(&ebml);
1518 else
1520 if (!fseek(outfile, 0, SEEK_SET))
1521 write_ivf_file_header(outfile, &cfg, codec->fourcc, frames_out);
1524 fclose(outfile);
1525 stats_close(&stats);
1526 fprintf(stderr, "\n");
1528 if (one_pass_only)
1529 break;
1532 vpx_img_free(&raw);
1533 free(argv);
1534 return EXIT_SUCCESS;