2 * Copyright (c) 2010 The WebM project authors. All Rights Reserved.
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
11 #include "vpx_config.h"
13 #if defined(_WIN32) || defined(__OS2__) || !CONFIG_OS_SUPPORT
14 #define USE_POSIX_MMAP 0
16 #define USE_POSIX_MMAP 1
25 #include "vpx/vpx_encoder.h"
27 #include "vpx/vpx_decoder.h"
30 #include <sys/types.h>
37 #if CONFIG_VP8_ENCODER || CONFIG_VP9_ENCODER
38 #include "vpx/vp8cx.h"
40 #if CONFIG_VP8_DECODER || CONFIG_VP9_DECODER
41 #include "vpx/vp8dx.h"
44 #include "vpx_ports/mem_ops.h"
45 #include "vpx_ports/vpx_timer.h"
46 #include "tools_common.h"
48 #include "libmkv/EbmlWriter.h"
49 #include "libmkv/EbmlIDs.h"
50 #include "third_party/libyuv/include/libyuv/scale.h"
52 /* Need special handling of these functions on Windows */
54 /* MSVS doesn't define off_t, and uses _f{seek,tell}i64 */
55 typedef __int64 off_t
;
56 #define fseeko _fseeki64
57 #define ftello _ftelli64
59 /* MinGW defines off_t as long
60 and uses f{seek,tell}o64/off64_t for large files */
61 #define fseeko fseeko64
62 #define ftello ftello64
66 #define LITERALU64(hi,lo) ((((uint64_t)hi)<<32)|lo)
68 /* We should use 32-bit file operations in WebM file format
69 * when building ARM executable file (.axf) with RVCT */
70 #if !CONFIG_OS_SUPPORT
76 /* Swallow warnings about unused results of fread/fwrite */
77 static size_t wrap_fread(void *ptr
, size_t size
, size_t nmemb
,
79 return fread(ptr
, size
, nmemb
, stream
);
81 #define fread wrap_fread
83 static size_t wrap_fwrite(const void *ptr
, size_t size
, size_t nmemb
,
85 return fwrite(ptr
, size
, nmemb
, stream
);
87 #define fwrite wrap_fwrite
90 static const char *exec_name
;
92 #define VP8_FOURCC (0x30385056)
93 #define VP9_FOURCC (0x30395056)
94 static const struct codec_item
{
96 const vpx_codec_iface_t
*(*iface
)(void);
97 const vpx_codec_iface_t
*(*dx_iface
)(void);
100 #if CONFIG_VP8_ENCODER && CONFIG_VP8_DECODER
101 {"vp8", &vpx_codec_vp8_cx
, &vpx_codec_vp8_dx
, VP8_FOURCC
},
102 #elif CONFIG_VP8_ENCODER && !CONFIG_VP8_DECODER
103 {"vp8", &vpx_codec_vp8_cx
, NULL
, VP8_FOURCC
},
105 #if CONFIG_VP9_ENCODER && CONFIG_VP9_DECODER
106 {"vp9", &vpx_codec_vp9_cx
, &vpx_codec_vp9_dx
, VP9_FOURCC
},
107 #elif CONFIG_VP9_ENCODER && !CONFIG_VP9_DECODER
108 {"vp9", &vpx_codec_vp9_cx
, NULL
, VP9_FOURCC
},
112 static void usage_exit();
114 #define LOG_ERROR(label) do \
116 const char *l=label;\
120 fprintf(stderr, "%s: ", l);\
121 vfprintf(stderr, fmt, ap);\
122 fprintf(stderr, "\n");\
126 void die(const char *fmt
, ...) {
132 void fatal(const char *fmt
, ...) {
138 void warn(const char *fmt
, ...) {
139 LOG_ERROR("Warning");
143 static void warn_or_exit_on_errorv(vpx_codec_ctx_t
*ctx
, int fatal
,
144 const char *s
, va_list ap
) {
146 const char *detail
= vpx_codec_error_detail(ctx
);
148 vfprintf(stderr
, s
, ap
);
149 fprintf(stderr
, ": %s\n", vpx_codec_error(ctx
));
152 fprintf(stderr
, " %s\n", detail
);
159 static void ctx_exit_on_error(vpx_codec_ctx_t
*ctx
, const char *s
, ...) {
163 warn_or_exit_on_errorv(ctx
, 1, s
, ap
);
167 static void warn_or_exit_on_error(vpx_codec_ctx_t
*ctx
, int fatal
,
168 const char *s
, ...) {
172 warn_or_exit_on_errorv(ctx
, fatal
, s
, ap
);
176 /* This structure is used to abstract the different ways of handling
177 * first pass statistics.
187 int stats_open_file(stats_io_t
*stats
, const char *fpf
, int pass
) {
193 stats
->file
= fopen(fpf
, "wb");
195 stats
->buf
.buf
= NULL
,
196 res
= (stats
->file
!= NULL
);
200 struct stat stat_buf
;
203 fd
= open(fpf
, O_RDONLY
);
204 stats
->file
= fdopen(fd
, "rb");
205 fstat(fd
, &stat_buf
);
206 stats
->buf
.sz
= stat_buf
.st_size
;
207 stats
->buf
.buf
= mmap(NULL
, stats
->buf
.sz
, PROT_READ
, MAP_PRIVATE
,
209 res
= (stats
->buf
.buf
!= NULL
);
213 stats
->file
= fopen(fpf
, "rb");
215 if (fseek(stats
->file
, 0, SEEK_END
))
216 fatal("First-pass stats file must be seekable!");
218 stats
->buf
.sz
= stats
->buf_alloc_sz
= ftell(stats
->file
);
221 stats
->buf
.buf
= malloc(stats
->buf_alloc_sz
);
224 fatal("Failed to allocate first-pass stats buffer (%lu bytes)",
225 (unsigned long)stats
->buf_alloc_sz
);
227 nbytes
= fread(stats
->buf
.buf
, 1, stats
->buf
.sz
, stats
->file
);
228 res
= (nbytes
== stats
->buf
.sz
);
235 int stats_open_mem(stats_io_t
*stats
, int pass
) {
241 stats
->buf_alloc_sz
= 64 * 1024;
242 stats
->buf
.buf
= malloc(stats
->buf_alloc_sz
);
245 stats
->buf_ptr
= stats
->buf
.buf
;
246 res
= (stats
->buf
.buf
!= NULL
);
251 void stats_close(stats_io_t
*stats
, int last_pass
) {
253 if (stats
->pass
== last_pass
) {
256 munmap(stats
->buf
.buf
, stats
->buf
.sz
);
258 free(stats
->buf
.buf
);
265 if (stats
->pass
== last_pass
)
266 free(stats
->buf
.buf
);
270 void stats_write(stats_io_t
*stats
, const void *pkt
, size_t len
) {
272 (void) fwrite(pkt
, 1, len
, stats
->file
);
274 if (stats
->buf
.sz
+ len
> stats
->buf_alloc_sz
) {
275 size_t new_sz
= stats
->buf_alloc_sz
+ 64 * 1024;
276 char *new_ptr
= realloc(stats
->buf
.buf
, new_sz
);
279 stats
->buf_ptr
= new_ptr
+ (stats
->buf_ptr
- (char *)stats
->buf
.buf
);
280 stats
->buf
.buf
= new_ptr
;
281 stats
->buf_alloc_sz
= new_sz
;
283 fatal("Failed to realloc firstpass stats buffer.");
286 memcpy(stats
->buf_ptr
, pkt
, len
);
287 stats
->buf
.sz
+= len
;
288 stats
->buf_ptr
+= len
;
292 vpx_fixed_buf_t
stats_get(stats_io_t
*stats
) {
296 /* Stereo 3D packed frame format */
297 typedef enum stereo_format
{
298 STEREO_FORMAT_MONO
= 0,
299 STEREO_FORMAT_LEFT_RIGHT
= 1,
300 STEREO_FORMAT_BOTTOM_TOP
= 2,
301 STEREO_FORMAT_TOP_BOTTOM
= 3,
302 STEREO_FORMAT_RIGHT_LEFT
= 11
305 enum video_file_type
{
311 struct detect_buffer
{
323 struct detect_buffer detect
;
324 enum video_file_type file_type
;
327 struct vpx_rational framerate
;
333 #define IVF_FRAME_HDR_SZ (4+8) /* 4 byte size + 8 byte timestamp */
334 static int read_frame(struct input_state
*input
, vpx_image_t
*img
) {
335 FILE *f
= input
->file
;
336 enum video_file_type file_type
= input
->file_type
;
337 y4m_input
*y4m
= &input
->y4m
;
338 struct detect_buffer
*detect
= &input
->detect
;
342 if (file_type
== FILE_TYPE_Y4M
) {
343 if (y4m_input_fetch_frame(y4m
, f
, img
) < 1)
346 if (file_type
== FILE_TYPE_IVF
) {
347 char junk
[IVF_FRAME_HDR_SZ
];
349 /* Skip the frame header. We know how big the frame should be. See
350 * write_ivf_frame_header() for documentation on the frame header
353 (void) fread(junk
, 1, IVF_FRAME_HDR_SZ
, f
);
356 for (plane
= 0; plane
< 3; plane
++) {
358 int w
= (plane
? (1 + img
->d_w
) / 2 : img
->d_w
);
359 int h
= (plane
? (1 + img
->d_h
) / 2 : img
->d_h
);
362 /* Determine the correct plane based on the image format. The for-loop
363 * always counts in Y,U,V order, but this may not match the order of
368 ptr
= img
->planes
[img
->fmt
== VPX_IMG_FMT_YV12
? VPX_PLANE_V
: VPX_PLANE_U
];
371 ptr
= img
->planes
[img
->fmt
== VPX_IMG_FMT_YV12
? VPX_PLANE_U
: VPX_PLANE_V
];
374 ptr
= img
->planes
[plane
];
377 for (r
= 0; r
< h
; r
++) {
379 size_t buf_position
= 0;
380 const size_t left
= detect
->buf_read
- detect
->position
;
382 const size_t more
= (left
< needed
) ? left
: needed
;
383 memcpy(ptr
, detect
->buf
+ detect
->position
, more
);
386 detect
->position
+= more
;
389 shortread
|= (fread(ptr
+ buf_position
, 1, needed
, f
) < needed
);
392 ptr
+= img
->stride
[plane
];
401 unsigned int file_is_y4m(FILE *infile
,
404 if (memcmp(detect
, "YUV4", 4) == 0) {
410 #define IVF_FILE_HDR_SZ (32)
411 unsigned int file_is_ivf(struct input_state
*input
,
412 unsigned int *fourcc
) {
413 char raw_hdr
[IVF_FILE_HDR_SZ
];
415 FILE *infile
= input
->file
;
416 unsigned int *width
= &input
->w
;
417 unsigned int *height
= &input
->h
;
418 struct detect_buffer
*detect
= &input
->detect
;
420 if (memcmp(detect
->buf
, "DKIF", 4) != 0)
423 /* See write_ivf_file_header() for more documentation on the file header
426 if (fread(raw_hdr
+ 4, 1, IVF_FILE_HDR_SZ
- 4, infile
)
427 == IVF_FILE_HDR_SZ
- 4) {
431 if (mem_get_le16(raw_hdr
+ 4) != 0)
432 warn("Unrecognized IVF version! This file may not decode "
435 *fourcc
= mem_get_le32(raw_hdr
+ 8);
440 *width
= mem_get_le16(raw_hdr
+ 12);
441 *height
= mem_get_le16(raw_hdr
+ 14);
442 detect
->position
= 4;
449 static void write_ivf_file_header(FILE *outfile
,
450 const vpx_codec_enc_cfg_t
*cfg
,
455 if (cfg
->g_pass
!= VPX_RC_ONE_PASS
&& cfg
->g_pass
!= VPX_RC_LAST_PASS
)
462 mem_put_le16(header
+ 4, 0); /* version */
463 mem_put_le16(header
+ 6, 32); /* headersize */
464 mem_put_le32(header
+ 8, fourcc
); /* headersize */
465 mem_put_le16(header
+ 12, cfg
->g_w
); /* width */
466 mem_put_le16(header
+ 14, cfg
->g_h
); /* height */
467 mem_put_le32(header
+ 16, cfg
->g_timebase
.den
); /* rate */
468 mem_put_le32(header
+ 20, cfg
->g_timebase
.num
); /* scale */
469 mem_put_le32(header
+ 24, frame_cnt
); /* length */
470 mem_put_le32(header
+ 28, 0); /* unused */
472 (void) fwrite(header
, 1, 32, outfile
);
476 static void write_ivf_frame_header(FILE *outfile
,
477 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
, (int)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
) {
494 mem_put_le32(header
, (int)size
);
495 (void) fwrite(header
, 1, 4, outfile
);
499 typedef off_t EbmlLoc
;
513 vpx_rational_t framerate
;
515 /* These pointers are to the start of an element */
516 off_t position_reference
;
518 off_t segment_info_pos
;
523 /* This pointer is to a specific element to be serialized */
526 /* These pointers are to the size field of the element */
527 EbmlLoc startSegment
;
528 EbmlLoc startCluster
;
530 uint32_t cluster_timecode
;
533 struct cue_entry
*cue_list
;
539 void Ebml_Write(EbmlGlobal
*glob
, const void *buffer_in
, unsigned long len
) {
540 (void) fwrite(buffer_in
, 1, len
, glob
->stream
);
543 #define WRITE_BUFFER(s) \
544 for(i = len-1; i>=0; i--)\
546 x = (char)(*(const s *)buffer_in >> (i * CHAR_BIT)); \
547 Ebml_Write(glob, &x, 1); \
549 void Ebml_Serialize(EbmlGlobal
*glob
, const void *buffer_in
, int buffer_size
, unsigned long len
) {
559 switch (buffer_size
) {
564 WRITE_BUFFER(int16_t)
567 WRITE_BUFFER(int32_t)
570 WRITE_BUFFER(int64_t)
578 /* Need a fixed size serializer for the track ID. libmkv provides a 64 bit
579 * one, but not a 32 bit one.
581 static void Ebml_SerializeUnsigned32(EbmlGlobal
*glob
, unsigned long class_id
, uint64_t ui
) {
582 unsigned char sizeSerialized
= 4 | 0x80;
583 Ebml_WriteID(glob
, class_id
);
584 Ebml_Serialize(glob
, &sizeSerialized
, sizeof(sizeSerialized
), 1);
585 Ebml_Serialize(glob
, &ui
, sizeof(ui
), 4);
590 Ebml_StartSubElement(EbmlGlobal
*glob
, EbmlLoc
*ebmlLoc
,
591 unsigned long class_id
) {
592 /* todo this is always taking 8 bytes, this may need later optimization */
593 /* this is a key that says length unknown */
594 uint64_t unknownLen
= LITERALU64(0x01FFFFFF, 0xFFFFFFFF);
596 Ebml_WriteID(glob
, class_id
);
597 *ebmlLoc
= ftello(glob
->stream
);
598 Ebml_Serialize(glob
, &unknownLen
, sizeof(unknownLen
), 8);
602 Ebml_EndSubElement(EbmlGlobal
*glob
, EbmlLoc
*ebmlLoc
) {
606 /* Save the current stream pointer */
607 pos
= ftello(glob
->stream
);
609 /* Calculate the size of this element */
610 size
= pos
- *ebmlLoc
- 8;
611 size
|= LITERALU64(0x01000000, 0x00000000);
613 /* Seek back to the beginning of the element and write the new size */
614 fseeko(glob
->stream
, *ebmlLoc
, SEEK_SET
);
615 Ebml_Serialize(glob
, &size
, sizeof(size
), 8);
617 /* Reset the stream pointer */
618 fseeko(glob
->stream
, pos
, SEEK_SET
);
623 write_webm_seek_element(EbmlGlobal
*ebml
, unsigned long id
, off_t pos
) {
624 uint64_t offset
= pos
- ebml
->position_reference
;
626 Ebml_StartSubElement(ebml
, &start
, Seek
);
627 Ebml_SerializeBinary(ebml
, SeekID
, id
);
628 Ebml_SerializeUnsigned64(ebml
, SeekPosition
, offset
);
629 Ebml_EndSubElement(ebml
, &start
);
634 write_webm_seek_info(EbmlGlobal
*ebml
) {
638 /* Save the current stream pointer */
639 pos
= ftello(ebml
->stream
);
641 if (ebml
->seek_info_pos
)
642 fseeko(ebml
->stream
, ebml
->seek_info_pos
, SEEK_SET
);
644 ebml
->seek_info_pos
= pos
;
649 Ebml_StartSubElement(ebml
, &start
, SeekHead
);
650 write_webm_seek_element(ebml
, Tracks
, ebml
->track_pos
);
651 write_webm_seek_element(ebml
, Cues
, ebml
->cue_pos
);
652 write_webm_seek_element(ebml
, Info
, ebml
->segment_info_pos
);
653 Ebml_EndSubElement(ebml
, &start
);
659 char version_string
[64];
661 /* Assemble version string */
663 strcpy(version_string
, "vpxenc");
665 strcpy(version_string
, "vpxenc ");
666 strncat(version_string
,
667 vpx_codec_version_str(),
668 sizeof(version_string
) - 1 - strlen(version_string
));
671 frame_time
= (uint64_t)1000 * ebml
->framerate
.den
672 / ebml
->framerate
.num
;
673 ebml
->segment_info_pos
= ftello(ebml
->stream
);
674 Ebml_StartSubElement(ebml
, &startInfo
, Info
);
675 Ebml_SerializeUnsigned(ebml
, TimecodeScale
, 1000000);
676 Ebml_SerializeFloat(ebml
, Segment_Duration
,
677 (double)(ebml
->last_pts_ms
+ frame_time
));
678 Ebml_SerializeString(ebml
, 0x4D80, version_string
);
679 Ebml_SerializeString(ebml
, 0x5741, version_string
);
680 Ebml_EndSubElement(ebml
, &startInfo
);
686 write_webm_file_header(EbmlGlobal
*glob
,
687 const vpx_codec_enc_cfg_t
*cfg
,
688 const struct vpx_rational
*fps
,
689 stereo_format_t stereo_fmt
,
690 unsigned int fourcc
) {
693 Ebml_StartSubElement(glob
, &start
, EBML
);
694 Ebml_SerializeUnsigned(glob
, EBMLVersion
, 1);
695 Ebml_SerializeUnsigned(glob
, EBMLReadVersion
, 1);
696 Ebml_SerializeUnsigned(glob
, EBMLMaxIDLength
, 4);
697 Ebml_SerializeUnsigned(glob
, EBMLMaxSizeLength
, 8);
698 Ebml_SerializeString(glob
, DocType
, "webm");
699 Ebml_SerializeUnsigned(glob
, DocTypeVersion
, 2);
700 Ebml_SerializeUnsigned(glob
, DocTypeReadVersion
, 2);
701 Ebml_EndSubElement(glob
, &start
);
704 Ebml_StartSubElement(glob
, &glob
->startSegment
, Segment
);
705 glob
->position_reference
= ftello(glob
->stream
);
706 glob
->framerate
= *fps
;
707 write_webm_seek_info(glob
);
711 glob
->track_pos
= ftello(glob
->stream
);
712 Ebml_StartSubElement(glob
, &trackStart
, Tracks
);
714 unsigned int trackNumber
= 1;
715 uint64_t trackID
= 0;
718 Ebml_StartSubElement(glob
, &start
, TrackEntry
);
719 Ebml_SerializeUnsigned(glob
, TrackNumber
, trackNumber
);
720 glob
->track_id_pos
= ftello(glob
->stream
);
721 Ebml_SerializeUnsigned32(glob
, TrackUID
, trackID
);
722 Ebml_SerializeUnsigned(glob
, TrackType
, 1);
723 Ebml_SerializeString(glob
, CodecID
,
724 fourcc
== VP8_FOURCC
? "V_VP8" : "V_VP9");
726 unsigned int pixelWidth
= cfg
->g_w
;
727 unsigned int pixelHeight
= cfg
->g_h
;
728 float frameRate
= (float)fps
->num
/ (float)fps
->den
;
731 Ebml_StartSubElement(glob
, &videoStart
, Video
);
732 Ebml_SerializeUnsigned(glob
, PixelWidth
, pixelWidth
);
733 Ebml_SerializeUnsigned(glob
, PixelHeight
, pixelHeight
);
734 Ebml_SerializeUnsigned(glob
, StereoMode
, stereo_fmt
);
735 Ebml_SerializeFloat(glob
, FrameRate
, frameRate
);
736 Ebml_EndSubElement(glob
, &videoStart
);
738 Ebml_EndSubElement(glob
, &start
); /* Track Entry */
740 Ebml_EndSubElement(glob
, &trackStart
);
742 /* segment element is open */
748 write_webm_block(EbmlGlobal
*glob
,
749 const vpx_codec_enc_cfg_t
*cfg
,
750 const vpx_codec_cx_pkt_t
*pkt
) {
751 unsigned long block_length
;
752 unsigned char track_number
;
753 unsigned short block_timecode
= 0;
756 int start_cluster
= 0, is_keyframe
;
758 /* Calculate the PTS of this frame in milliseconds */
759 pts_ms
= pkt
->data
.frame
.pts
* 1000
760 * (uint64_t)cfg
->g_timebase
.num
/ (uint64_t)cfg
->g_timebase
.den
;
761 if (pts_ms
<= glob
->last_pts_ms
)
762 pts_ms
= glob
->last_pts_ms
+ 1;
763 glob
->last_pts_ms
= pts_ms
;
765 /* Calculate the relative time of this block */
766 if (pts_ms
- glob
->cluster_timecode
> SHRT_MAX
)
769 block_timecode
= (unsigned short)pts_ms
- glob
->cluster_timecode
;
771 is_keyframe
= (pkt
->data
.frame
.flags
& VPX_FRAME_IS_KEY
);
772 if (start_cluster
|| is_keyframe
) {
773 if (glob
->cluster_open
)
774 Ebml_EndSubElement(glob
, &glob
->startCluster
);
776 /* Open the new cluster */
778 glob
->cluster_open
= 1;
779 glob
->cluster_timecode
= (uint32_t)pts_ms
;
780 glob
->cluster_pos
= ftello(glob
->stream
);
781 Ebml_StartSubElement(glob
, &glob
->startCluster
, Cluster
); /* cluster */
782 Ebml_SerializeUnsigned(glob
, Timecode
, glob
->cluster_timecode
);
784 /* Save a cue point if this is a keyframe. */
786 struct cue_entry
*cue
, *new_cue_list
;
788 new_cue_list
= realloc(glob
->cue_list
,
789 (glob
->cues
+ 1) * sizeof(struct cue_entry
));
791 glob
->cue_list
= new_cue_list
;
793 fatal("Failed to realloc cue list.");
795 cue
= &glob
->cue_list
[glob
->cues
];
796 cue
->time
= glob
->cluster_timecode
;
797 cue
->loc
= glob
->cluster_pos
;
802 /* Write the Simple Block */
803 Ebml_WriteID(glob
, SimpleBlock
);
805 block_length
= (unsigned long)pkt
->data
.frame
.sz
+ 4;
806 block_length
|= 0x10000000;
807 Ebml_Serialize(glob
, &block_length
, sizeof(block_length
), 4);
810 track_number
|= 0x80;
811 Ebml_Write(glob
, &track_number
, 1);
813 Ebml_Serialize(glob
, &block_timecode
, sizeof(block_timecode
), 2);
818 if (pkt
->data
.frame
.flags
& VPX_FRAME_IS_INVISIBLE
)
820 Ebml_Write(glob
, &flags
, 1);
822 Ebml_Write(glob
, pkt
->data
.frame
.buf
, (unsigned long)pkt
->data
.frame
.sz
);
827 write_webm_file_footer(EbmlGlobal
*glob
, long hash
) {
829 if (glob
->cluster_open
)
830 Ebml_EndSubElement(glob
, &glob
->startCluster
);
836 glob
->cue_pos
= ftello(glob
->stream
);
837 Ebml_StartSubElement(glob
, &start
, Cues
);
838 for (i
= 0; i
< glob
->cues
; i
++) {
839 struct cue_entry
*cue
= &glob
->cue_list
[i
];
842 Ebml_StartSubElement(glob
, &start
, CuePoint
);
846 Ebml_SerializeUnsigned(glob
, CueTime
, cue
->time
);
848 Ebml_StartSubElement(glob
, &start
, CueTrackPositions
);
849 Ebml_SerializeUnsigned(glob
, CueTrack
, 1);
850 Ebml_SerializeUnsigned64(glob
, CueClusterPosition
,
851 cue
->loc
- glob
->position_reference
);
852 Ebml_EndSubElement(glob
, &start
);
854 Ebml_EndSubElement(glob
, &start
);
856 Ebml_EndSubElement(glob
, &start
);
859 Ebml_EndSubElement(glob
, &glob
->startSegment
);
861 /* Patch up the seek info block */
862 write_webm_seek_info(glob
);
864 /* Patch up the track id */
865 fseeko(glob
->stream
, glob
->track_id_pos
, SEEK_SET
);
866 Ebml_SerializeUnsigned32(glob
, TrackUID
, glob
->debug
? 0xDEADBEEF : hash
);
868 fseeko(glob
->stream
, 0, SEEK_END
);
872 /* Murmur hash derived from public domain reference implementation at
873 * http:// sites.google.com/site/murmurhash/
875 static unsigned int murmur(const void *key
, int len
, unsigned int seed
) {
876 const unsigned int m
= 0x5bd1e995;
879 unsigned int h
= seed
^ len
;
881 const unsigned char *data
= (const unsigned char *)key
;
921 static double vp8_mse2psnr(double Samples
, double Peak
, double Mse
) {
924 if ((double)Mse
> 0.0)
925 psnr
= 10.0 * log10(Peak
* Peak
* Samples
/ Mse
);
927 psnr
= MAX_PSNR
; /* Limit to prevent / 0 */
937 static const arg_def_t debugmode
= ARG_DEF("D", "debug", 0,
938 "Debug mode (makes output deterministic)");
939 static const arg_def_t outputfile
= ARG_DEF("o", "output", 1,
941 static const arg_def_t use_yv12
= ARG_DEF(NULL
, "yv12", 0,
942 "Input file is YV12 ");
943 static const arg_def_t use_i420
= ARG_DEF(NULL
, "i420", 0,
944 "Input file is I420 (default)");
945 static const arg_def_t codecarg
= ARG_DEF(NULL
, "codec", 1,
947 static const arg_def_t passes
= ARG_DEF("p", "passes", 1,
948 "Number of passes (1/2)");
949 static const arg_def_t pass_arg
= ARG_DEF(NULL
, "pass", 1,
950 "Pass to execute (1/2)");
951 static const arg_def_t fpf_name
= ARG_DEF(NULL
, "fpf", 1,
952 "First pass statistics file name");
953 static const arg_def_t limit
= ARG_DEF(NULL
, "limit", 1,
954 "Stop encoding after n input frames");
955 static const arg_def_t skip
= ARG_DEF(NULL
, "skip", 1,
956 "Skip the first n input frames");
957 static const arg_def_t deadline
= ARG_DEF("d", "deadline", 1,
958 "Deadline per frame (usec)");
959 static const arg_def_t best_dl
= ARG_DEF(NULL
, "best", 0,
960 "Use Best Quality Deadline");
961 static const arg_def_t good_dl
= ARG_DEF(NULL
, "good", 0,
962 "Use Good Quality Deadline");
963 static const arg_def_t rt_dl
= ARG_DEF(NULL
, "rt", 0,
964 "Use Realtime Quality Deadline");
965 static const arg_def_t quietarg
= ARG_DEF("q", "quiet", 0,
966 "Do not print encode progress");
967 static const arg_def_t verbosearg
= ARG_DEF("v", "verbose", 0,
968 "Show encoder parameters");
969 static const arg_def_t psnrarg
= ARG_DEF(NULL
, "psnr", 0,
970 "Show PSNR in status line");
971 enum TestDecodeFatality
{
976 static const struct arg_enum_list test_decode_enum
[] = {
977 {"off", TEST_DECODE_OFF
},
978 {"fatal", TEST_DECODE_FATAL
},
979 {"warn", TEST_DECODE_WARN
},
982 static const arg_def_t recontest
= ARG_DEF_ENUM(NULL
, "test-decode", 1,
983 "Test encode/decode mismatch",
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
[] = {
997 &outputfile
, &codecarg
, &passes
, &pass_arg
, &fpf_name
, &limit
, &skip
,
998 &deadline
, &best_dl
, &good_dl
, &rt_dl
,
999 &quietarg
, &verbosearg
, &psnrarg
, &use_ivf
, &out_part
, &q_hist_n
, &rate_hist_n
,
1003 static const arg_def_t usage
= ARG_DEF("u", "usage", 1,
1004 "Usage profile number to use");
1005 static const arg_def_t threads
= ARG_DEF("t", "threads", 1,
1006 "Max number of threads to use");
1007 static const arg_def_t profile
= ARG_DEF(NULL
, "profile", 1,
1008 "Bitstream profile number to use");
1009 static const arg_def_t width
= ARG_DEF("w", "width", 1,
1011 static const arg_def_t height
= ARG_DEF("h", "height", 1,
1013 static const struct arg_enum_list stereo_mode_enum
[] = {
1014 {"mono", STEREO_FORMAT_MONO
},
1015 {"left-right", STEREO_FORMAT_LEFT_RIGHT
},
1016 {"bottom-top", STEREO_FORMAT_BOTTOM_TOP
},
1017 {"top-bottom", STEREO_FORMAT_TOP_BOTTOM
},
1018 {"right-left", STEREO_FORMAT_RIGHT_LEFT
},
1021 static const arg_def_t stereo_mode
= ARG_DEF_ENUM(NULL
, "stereo-mode", 1,
1022 "Stereo 3D video format", stereo_mode_enum
);
1023 static const arg_def_t timebase
= ARG_DEF(NULL
, "timebase", 1,
1024 "Output timestamp precision (fractional seconds)");
1025 static const arg_def_t error_resilient
= ARG_DEF(NULL
, "error-resilient", 1,
1026 "Enable error resiliency features");
1027 static const arg_def_t lag_in_frames
= ARG_DEF(NULL
, "lag-in-frames", 1,
1028 "Max number of frames to lag");
1030 static const arg_def_t
*global_args
[] = {
1031 &use_yv12
, &use_i420
, &usage
, &threads
, &profile
,
1032 &width
, &height
, &stereo_mode
, &timebase
, &framerate
,
1034 &lag_in_frames
, NULL
1037 static const arg_def_t dropframe_thresh
= ARG_DEF(NULL
, "drop-frame", 1,
1038 "Temporal resampling threshold (buf %)");
1039 static const arg_def_t resize_allowed
= ARG_DEF(NULL
, "resize-allowed", 1,
1040 "Spatial resampling enabled (bool)");
1041 static const arg_def_t resize_up_thresh
= ARG_DEF(NULL
, "resize-up", 1,
1042 "Upscale threshold (buf %)");
1043 static const arg_def_t resize_down_thresh
= ARG_DEF(NULL
, "resize-down", 1,
1044 "Downscale threshold (buf %)");
1045 static const struct arg_enum_list end_usage_enum
[] = {
1051 static const arg_def_t end_usage
= ARG_DEF_ENUM(NULL
, "end-usage", 1,
1052 "Rate control mode", end_usage_enum
);
1053 static const arg_def_t target_bitrate
= ARG_DEF(NULL
, "target-bitrate", 1,
1055 static const arg_def_t min_quantizer
= ARG_DEF(NULL
, "min-q", 1,
1056 "Minimum (best) quantizer");
1057 static const arg_def_t max_quantizer
= ARG_DEF(NULL
, "max-q", 1,
1058 "Maximum (worst) quantizer");
1059 static const arg_def_t undershoot_pct
= ARG_DEF(NULL
, "undershoot-pct", 1,
1060 "Datarate undershoot (min) target (%)");
1061 static const arg_def_t overshoot_pct
= ARG_DEF(NULL
, "overshoot-pct", 1,
1062 "Datarate overshoot (max) target (%)");
1063 static const arg_def_t buf_sz
= ARG_DEF(NULL
, "buf-sz", 1,
1064 "Client buffer size (ms)");
1065 static const arg_def_t buf_initial_sz
= ARG_DEF(NULL
, "buf-initial-sz", 1,
1066 "Client initial buffer size (ms)");
1067 static const arg_def_t buf_optimal_sz
= ARG_DEF(NULL
, "buf-optimal-sz", 1,
1068 "Client optimal buffer size (ms)");
1069 static const arg_def_t
*rc_args
[] = {
1070 &dropframe_thresh
, &resize_allowed
, &resize_up_thresh
, &resize_down_thresh
,
1071 &end_usage
, &target_bitrate
, &min_quantizer
, &max_quantizer
,
1072 &undershoot_pct
, &overshoot_pct
, &buf_sz
, &buf_initial_sz
, &buf_optimal_sz
,
1077 static const arg_def_t bias_pct
= ARG_DEF(NULL
, "bias-pct", 1,
1078 "CBR/VBR bias (0=CBR, 100=VBR)");
1079 static const arg_def_t minsection_pct
= ARG_DEF(NULL
, "minsection-pct", 1,
1080 "GOP min bitrate (% of target)");
1081 static const arg_def_t maxsection_pct
= ARG_DEF(NULL
, "maxsection-pct", 1,
1082 "GOP max bitrate (% of target)");
1083 static const arg_def_t
*rc_twopass_args
[] = {
1084 &bias_pct
, &minsection_pct
, &maxsection_pct
, NULL
1088 static const arg_def_t kf_min_dist
= ARG_DEF(NULL
, "kf-min-dist", 1,
1089 "Minimum keyframe interval (frames)");
1090 static const arg_def_t kf_max_dist
= ARG_DEF(NULL
, "kf-max-dist", 1,
1091 "Maximum keyframe interval (frames)");
1092 static const arg_def_t kf_disabled
= ARG_DEF(NULL
, "disable-kf", 0,
1093 "Disable keyframe placement");
1094 static const arg_def_t
*kf_args
[] = {
1095 &kf_min_dist
, &kf_max_dist
, &kf_disabled
, NULL
1099 static const arg_def_t noise_sens
= ARG_DEF(NULL
, "noise-sensitivity", 1,
1100 "Noise sensitivity (frames to blur)");
1101 static const arg_def_t sharpness
= ARG_DEF(NULL
, "sharpness", 1,
1102 "Filter sharpness (0-7)");
1103 static const arg_def_t static_thresh
= ARG_DEF(NULL
, "static-thresh", 1,
1104 "Motion detection threshold");
1105 static const arg_def_t cpu_used
= ARG_DEF(NULL
, "cpu-used", 1,
1106 "CPU Used (-16..16)");
1107 static const arg_def_t token_parts
= ARG_DEF(NULL
, "token-parts", 1,
1108 "Number of token partitions to use, log2");
1109 static const arg_def_t tile_cols
= ARG_DEF(NULL
, "tile-columns", 1,
1110 "Number of tile columns to use, log2");
1111 static const arg_def_t tile_rows
= ARG_DEF(NULL
, "tile-rows", 1,
1112 "Number of tile rows to use, log2");
1113 static const arg_def_t auto_altref
= ARG_DEF(NULL
, "auto-alt-ref", 1,
1114 "Enable automatic alt reference frames");
1115 static const arg_def_t arnr_maxframes
= ARG_DEF(NULL
, "arnr-maxframes", 1,
1116 "AltRef Max Frames");
1117 static const arg_def_t arnr_strength
= ARG_DEF(NULL
, "arnr-strength", 1,
1119 static const arg_def_t arnr_type
= ARG_DEF(NULL
, "arnr-type", 1,
1121 static const struct arg_enum_list tuning_enum
[] = {
1122 {"psnr", VP8_TUNE_PSNR
},
1123 {"ssim", VP8_TUNE_SSIM
},
1126 static const arg_def_t tune_ssim
= ARG_DEF_ENUM(NULL
, "tune", 1,
1127 "Material to favor", tuning_enum
);
1128 static const arg_def_t cq_level
= ARG_DEF(NULL
, "cq-level", 1,
1129 "Constrained Quality Level");
1130 static const arg_def_t max_intra_rate_pct
= ARG_DEF(NULL
, "max-intra-rate", 1,
1131 "Max I-frame bitrate (pct)");
1132 static const arg_def_t lossless
= ARG_DEF(NULL
, "lossless", 1, "Lossless mode");
1133 #if CONFIG_VP9_ENCODER
1134 static const arg_def_t frame_parallel_decoding
= ARG_DEF(
1135 NULL
, "frame-parallel", 1, "Enable frame parallel decodability features");
1138 #if CONFIG_VP8_ENCODER
1139 static const arg_def_t
*vp8_args
[] = {
1140 &cpu_used
, &auto_altref
, &noise_sens
, &sharpness
, &static_thresh
,
1141 &token_parts
, &arnr_maxframes
, &arnr_strength
, &arnr_type
,
1142 &tune_ssim
, &cq_level
, &max_intra_rate_pct
,
1145 static const int vp8_arg_ctrl_map
[] = {
1146 VP8E_SET_CPUUSED
, VP8E_SET_ENABLEAUTOALTREF
,
1147 VP8E_SET_NOISE_SENSITIVITY
, VP8E_SET_SHARPNESS
, VP8E_SET_STATIC_THRESHOLD
,
1148 VP8E_SET_TOKEN_PARTITIONS
,
1149 VP8E_SET_ARNR_MAXFRAMES
, VP8E_SET_ARNR_STRENGTH
, VP8E_SET_ARNR_TYPE
,
1150 VP8E_SET_TUNING
, VP8E_SET_CQ_LEVEL
, VP8E_SET_MAX_INTRA_BITRATE_PCT
,
1155 #if CONFIG_VP9_ENCODER
1156 static const arg_def_t
*vp9_args
[] = {
1157 &cpu_used
, &auto_altref
, &noise_sens
, &sharpness
, &static_thresh
,
1158 &tile_cols
, &tile_rows
, &arnr_maxframes
, &arnr_strength
, &arnr_type
,
1159 &tune_ssim
, &cq_level
, &max_intra_rate_pct
, &lossless
,
1160 &frame_parallel_decoding
,
1163 static const int vp9_arg_ctrl_map
[] = {
1164 VP8E_SET_CPUUSED
, VP8E_SET_ENABLEAUTOALTREF
,
1165 VP8E_SET_NOISE_SENSITIVITY
, VP8E_SET_SHARPNESS
, VP8E_SET_STATIC_THRESHOLD
,
1166 VP9E_SET_TILE_COLUMNS
, VP9E_SET_TILE_ROWS
,
1167 VP8E_SET_ARNR_MAXFRAMES
, VP8E_SET_ARNR_STRENGTH
, VP8E_SET_ARNR_TYPE
,
1168 VP8E_SET_TUNING
, VP8E_SET_CQ_LEVEL
, VP8E_SET_MAX_INTRA_BITRATE_PCT
,
1169 VP9E_SET_LOSSLESS
, VP9E_SET_FRAME_PARALLEL_DECODING
,
1174 static const arg_def_t
*no_args
[] = { NULL
};
1176 static void usage_exit() {
1179 fprintf(stderr
, "Usage: %s <options> -o dst_filename src_filename \n",
1182 fprintf(stderr
, "\nOptions:\n");
1183 arg_show_usage(stdout
, main_args
);
1184 fprintf(stderr
, "\nEncoder Global Options:\n");
1185 arg_show_usage(stdout
, global_args
);
1186 fprintf(stderr
, "\nRate Control Options:\n");
1187 arg_show_usage(stdout
, rc_args
);
1188 fprintf(stderr
, "\nTwopass Rate Control Options:\n");
1189 arg_show_usage(stdout
, rc_twopass_args
);
1190 fprintf(stderr
, "\nKeyframe Placement Options:\n");
1191 arg_show_usage(stdout
, kf_args
);
1192 #if CONFIG_VP8_ENCODER
1193 fprintf(stderr
, "\nVP8 Specific Options:\n");
1194 arg_show_usage(stdout
, vp8_args
);
1196 #if CONFIG_VP9_ENCODER
1197 fprintf(stderr
, "\nVP9 Specific Options:\n");
1198 arg_show_usage(stdout
, vp9_args
);
1200 fprintf(stderr
, "\nStream timebase (--timebase):\n"
1201 " The desired precision of timestamps in the output, expressed\n"
1202 " in fractional seconds. Default is 1/1000.\n");
1203 fprintf(stderr
, "\n"
1204 "Included encoders:\n"
1207 for (i
= 0; i
< sizeof(codecs
) / sizeof(codecs
[0]); i
++)
1208 fprintf(stderr
, " %-6s - %s\n",
1210 vpx_codec_iface_name(codecs
[i
].iface()));
1216 #define HIST_BAR_MAX 40
1217 struct hist_bucket
{
1218 int low
, high
, count
;
1222 static int merge_hist_buckets(struct hist_bucket
*bucket
,
1225 int small_bucket
= 0, merge_bucket
= INT_MAX
, big_bucket
= 0;
1226 int buckets
= *buckets_
;
1229 /* Find the extrema for this list of buckets */
1230 big_bucket
= small_bucket
= 0;
1231 for (i
= 0; i
< buckets
; i
++) {
1232 if (bucket
[i
].count
< bucket
[small_bucket
].count
)
1234 if (bucket
[i
].count
> bucket
[big_bucket
].count
)
1238 /* If we have too many buckets, merge the smallest with an adjacent
1241 while (buckets
> max_buckets
) {
1242 int last_bucket
= buckets
- 1;
1244 /* merge the small bucket with an adjacent one. */
1245 if (small_bucket
== 0)
1247 else if (small_bucket
== last_bucket
)
1248 merge_bucket
= last_bucket
- 1;
1249 else if (bucket
[small_bucket
- 1].count
< bucket
[small_bucket
+ 1].count
)
1250 merge_bucket
= small_bucket
- 1;
1252 merge_bucket
= small_bucket
+ 1;
1254 assert(abs(merge_bucket
- small_bucket
) <= 1);
1255 assert(small_bucket
< buckets
);
1256 assert(big_bucket
< buckets
);
1257 assert(merge_bucket
< buckets
);
1259 if (merge_bucket
< small_bucket
) {
1260 bucket
[merge_bucket
].high
= bucket
[small_bucket
].high
;
1261 bucket
[merge_bucket
].count
+= bucket
[small_bucket
].count
;
1263 bucket
[small_bucket
].high
= bucket
[merge_bucket
].high
;
1264 bucket
[small_bucket
].count
+= bucket
[merge_bucket
].count
;
1265 merge_bucket
= small_bucket
;
1268 assert(bucket
[merge_bucket
].low
!= bucket
[merge_bucket
].high
);
1272 /* Remove the merge_bucket from the list, and find the new small
1273 * and big buckets while we're at it
1275 big_bucket
= small_bucket
= 0;
1276 for (i
= 0; i
< buckets
; i
++) {
1277 if (i
> merge_bucket
)
1278 bucket
[i
] = bucket
[i
+ 1];
1280 if (bucket
[i
].count
< bucket
[small_bucket
].count
)
1282 if (bucket
[i
].count
> bucket
[big_bucket
].count
)
1288 *buckets_
= buckets
;
1289 return bucket
[big_bucket
].count
;
1293 static void show_histogram(const struct hist_bucket
*bucket
,
1297 const char *pat1
, *pat2
;
1300 switch ((int)(log(bucket
[buckets
- 1].high
) / log(10)) + 1) {
1327 pat1
= "%12d %10s: ";
1328 pat2
= "%12d-%10d: ";
1332 for (i
= 0; i
< buckets
; i
++) {
1337 pct
= (float)(100.0 * bucket
[i
].count
/ total
);
1338 len
= HIST_BAR_MAX
* bucket
[i
].count
/ scale
;
1341 assert(len
<= HIST_BAR_MAX
);
1343 if (bucket
[i
].low
== bucket
[i
].high
)
1344 fprintf(stderr
, pat1
, bucket
[i
].low
, "");
1346 fprintf(stderr
, pat2
, bucket
[i
].low
, bucket
[i
].high
);
1348 for (j
= 0; j
< HIST_BAR_MAX
; j
++)
1349 fprintf(stderr
, j
< len
? "=" : " ");
1350 fprintf(stderr
, "\t%5d (%6.2f%%)\n", bucket
[i
].count
, pct
);
1355 static void show_q_histogram(const int counts
[64], int max_buckets
) {
1356 struct hist_bucket bucket
[64];
1363 for (i
= 0; i
< 64; i
++) {
1365 bucket
[buckets
].low
= bucket
[buckets
].high
= i
;
1366 bucket
[buckets
].count
= counts
[i
];
1372 fprintf(stderr
, "\nQuantizer Selection:\n");
1373 scale
= merge_hist_buckets(bucket
, &buckets
, max_buckets
);
1374 show_histogram(bucket
, buckets
, total
, scale
);
1378 #define RATE_BINS (100)
1384 struct hist_bucket bucket
[RATE_BINS
];
1389 static void init_rate_histogram(struct rate_hist
*hist
,
1390 const vpx_codec_enc_cfg_t
*cfg
,
1391 const vpx_rational_t
*fps
) {
1394 /* Determine the number of samples in the buffer. Use the file's framerate
1395 * to determine the number of frames in rc_buf_sz milliseconds, with an
1396 * adjustment (5/4) to account for alt-refs
1398 hist
->samples
= cfg
->rc_buf_sz
* 5 / 4 * fps
->num
/ fps
->den
/ 1000;
1400 /* prevent division by zero */
1401 if (hist
->samples
== 0)
1404 hist
->pts
= calloc(hist
->samples
, sizeof(*hist
->pts
));
1405 hist
->sz
= calloc(hist
->samples
, sizeof(*hist
->sz
));
1406 for (i
= 0; i
< RATE_BINS
; i
++) {
1407 hist
->bucket
[i
].low
= INT_MAX
;
1408 hist
->bucket
[i
].high
= 0;
1409 hist
->bucket
[i
].count
= 0;
1414 static void destroy_rate_histogram(struct rate_hist
*hist
) {
1420 static void update_rate_histogram(struct rate_hist
*hist
,
1421 const vpx_codec_enc_cfg_t
*cfg
,
1422 const vpx_codec_cx_pkt_t
*pkt
) {
1424 int64_t now
, then
, sum_sz
= 0, avg_bitrate
;
1426 now
= pkt
->data
.frame
.pts
* 1000
1427 * (uint64_t)cfg
->g_timebase
.num
/ (uint64_t)cfg
->g_timebase
.den
;
1429 idx
= hist
->frames
++ % hist
->samples
;
1430 hist
->pts
[idx
] = now
;
1431 hist
->sz
[idx
] = (int)pkt
->data
.frame
.sz
;
1433 if (now
< cfg
->rc_buf_initial_sz
)
1438 /* Sum the size over the past rc_buf_sz ms */
1439 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
= (int)(avg_bitrate
* (RATE_BINS
/ 2) / (cfg
->rc_target_bitrate
* 1000));
1455 if (idx
> RATE_BINS
- 1)
1456 idx
= RATE_BINS
- 1;
1457 if (hist
->bucket
[idx
].low
> avg_bitrate
)
1458 hist
->bucket
[idx
].low
= (int)avg_bitrate
;
1459 if (hist
->bucket
[idx
].high
< avg_bitrate
)
1460 hist
->bucket
[idx
].high
= (int)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
,
1472 for (i
= 0; i
< RATE_BINS
; i
++) {
1473 if (hist
->bucket
[i
].low
== INT_MAX
)
1475 hist
->bucket
[buckets
++] = hist
->bucket
[i
];
1478 fprintf(stderr
, "\nRate (over %dms window):\n", cfg
->rc_buf_sz
);
1479 scale
= merge_hist_buckets(hist
->bucket
, &buckets
, max_buckets
);
1480 show_histogram(hist
->bucket
, buckets
, hist
->total
, scale
);
1483 #define mmin(a, b) ((a) < (b) ? (a) : (b))
1484 static void find_mismatch(vpx_image_t
*img1
, vpx_image_t
*img2
,
1485 int yloc
[4], int uloc
[4], int vloc
[4]) {
1486 const unsigned int bsize
= 64;
1487 const unsigned int bsizey
= bsize
>> img1
->y_chroma_shift
;
1488 const unsigned int bsizex
= bsize
>> img1
->x_chroma_shift
;
1489 const int c_w
= (img1
->d_w
+ img1
->x_chroma_shift
) >> img1
->x_chroma_shift
;
1490 const int c_h
= (img1
->d_h
+ img1
->y_chroma_shift
) >> img1
->y_chroma_shift
;
1491 unsigned int match
= 1;
1493 yloc
[0] = yloc
[1] = yloc
[2] = yloc
[3] = -1;
1494 for (i
= 0, match
= 1; match
&& i
< img1
->d_h
; i
+= bsize
) {
1495 for (j
= 0; match
&& j
< img1
->d_w
; j
+= bsize
) {
1497 int si
= mmin(i
+ bsize
, img1
->d_h
) - i
;
1498 int sj
= mmin(j
+ bsize
, img1
->d_w
) - j
;
1499 for (k
= 0; match
&& k
< si
; k
++)
1500 for (l
= 0; match
&& l
< sj
; l
++) {
1501 if (*(img1
->planes
[VPX_PLANE_Y
] +
1502 (i
+ k
) * img1
->stride
[VPX_PLANE_Y
] + j
+ l
) !=
1503 *(img2
->planes
[VPX_PLANE_Y
] +
1504 (i
+ k
) * img2
->stride
[VPX_PLANE_Y
] + j
+ l
)) {
1507 yloc
[2] = *(img1
->planes
[VPX_PLANE_Y
] +
1508 (i
+ k
) * img1
->stride
[VPX_PLANE_Y
] + j
+ l
);
1509 yloc
[3] = *(img2
->planes
[VPX_PLANE_Y
] +
1510 (i
+ k
) * img2
->stride
[VPX_PLANE_Y
] + j
+ l
);
1518 uloc
[0] = uloc
[1] = uloc
[2] = uloc
[3] = -1;
1519 for (i
= 0, match
= 1; match
&& i
< c_h
; i
+= bsizey
) {
1520 for (j
= 0; j
< match
&& c_w
; j
+= bsizex
) {
1522 int si
= mmin(i
+ bsizey
, c_h
- i
);
1523 int sj
= mmin(j
+ bsizex
, c_w
- j
);
1524 for (k
= 0; match
&& k
< si
; k
++)
1525 for (l
= 0; match
&& l
< sj
; l
++) {
1526 if (*(img1
->planes
[VPX_PLANE_U
] +
1527 (i
+ k
) * img1
->stride
[VPX_PLANE_U
] + j
+ l
) !=
1528 *(img2
->planes
[VPX_PLANE_U
] +
1529 (i
+ k
) * img2
->stride
[VPX_PLANE_U
] + j
+ l
)) {
1532 uloc
[2] = *(img1
->planes
[VPX_PLANE_U
] +
1533 (i
+ k
) * img1
->stride
[VPX_PLANE_U
] + j
+ l
);
1534 uloc
[3] = *(img2
->planes
[VPX_PLANE_U
] +
1535 (i
+ k
) * img2
->stride
[VPX_PLANE_V
] + j
+ l
);
1542 vloc
[0] = vloc
[1] = vloc
[2] = vloc
[3] = -1;
1543 for (i
= 0, match
= 1; match
&& i
< c_h
; i
+= bsizey
) {
1544 for (j
= 0; j
< match
&& c_w
; j
+= bsizex
) {
1546 int si
= mmin(i
+ bsizey
, c_h
- i
);
1547 int sj
= mmin(j
+ bsizex
, c_w
- j
);
1548 for (k
= 0; match
&& k
< si
; k
++)
1549 for (l
= 0; match
&& l
< sj
; l
++) {
1550 if (*(img1
->planes
[VPX_PLANE_V
] +
1551 (i
+ k
) * img1
->stride
[VPX_PLANE_V
] + j
+ l
) !=
1552 *(img2
->planes
[VPX_PLANE_V
] +
1553 (i
+ k
) * img2
->stride
[VPX_PLANE_V
] + j
+ l
)) {
1556 vloc
[2] = *(img1
->planes
[VPX_PLANE_V
] +
1557 (i
+ k
) * img1
->stride
[VPX_PLANE_V
] + j
+ l
);
1558 vloc
[3] = *(img2
->planes
[VPX_PLANE_V
] +
1559 (i
+ k
) * img2
->stride
[VPX_PLANE_V
] + j
+ l
);
1568 static int compare_img(vpx_image_t
*img1
, vpx_image_t
*img2
)
1570 const int c_w
= (img1
->d_w
+ img1
->x_chroma_shift
) >> img1
->x_chroma_shift
;
1571 const int c_h
= (img1
->d_h
+ img1
->y_chroma_shift
) >> img1
->y_chroma_shift
;
1575 match
&= (img1
->fmt
== img2
->fmt
);
1576 match
&= (img1
->w
== img2
->w
);
1577 match
&= (img1
->h
== img2
->h
);
1579 for (i
= 0; i
< img1
->d_h
; i
++)
1580 match
&= (memcmp(img1
->planes
[VPX_PLANE_Y
]+i
*img1
->stride
[VPX_PLANE_Y
],
1581 img2
->planes
[VPX_PLANE_Y
]+i
*img2
->stride
[VPX_PLANE_Y
],
1584 for (i
= 0; i
< c_h
; i
++)
1585 match
&= (memcmp(img1
->planes
[VPX_PLANE_U
]+i
*img1
->stride
[VPX_PLANE_U
],
1586 img2
->planes
[VPX_PLANE_U
]+i
*img2
->stride
[VPX_PLANE_U
],
1589 for (i
= 0; i
< c_h
; i
++)
1590 match
&= (memcmp(img1
->planes
[VPX_PLANE_V
]+i
*img1
->stride
[VPX_PLANE_U
],
1591 img2
->planes
[VPX_PLANE_V
]+i
*img2
->stride
[VPX_PLANE_U
],
1598 #define NELEMENTS(x) (sizeof(x)/sizeof(x[0]))
1599 #define MAX(x,y) ((x)>(y)?(x):(y))
1600 #if CONFIG_VP8_ENCODER && !CONFIG_VP9_ENCODER
1601 #define ARG_CTRL_CNT_MAX NELEMENTS(vp8_arg_ctrl_map)
1602 #elif !CONFIG_VP8_ENCODER && CONFIG_VP9_ENCODER
1603 #define ARG_CTRL_CNT_MAX NELEMENTS(vp9_arg_ctrl_map)
1605 #define ARG_CTRL_CNT_MAX MAX(NELEMENTS(vp8_arg_ctrl_map), \
1606 NELEMENTS(vp9_arg_ctrl_map))
1609 /* Configuration elements common to all streams */
1610 struct global_config
{
1611 const struct codec_item
*codec
;
1622 enum TestDecodeFatality test_decode
;
1624 struct vpx_rational framerate
;
1627 int show_q_hist_buckets
;
1628 int show_rate_hist_buckets
;
1632 /* Per-stream configuration */
1633 struct stream_config
{
1634 struct vpx_codec_enc_cfg cfg
;
1636 const char *stats_fn
;
1637 stereo_format_t stereo_fmt
;
1638 int arg_ctrls
[ARG_CTRL_CNT_MAX
][2];
1641 int have_kf_max_dist
;
1645 struct stream_state
{
1647 struct stream_state
*next
;
1648 struct stream_config config
;
1650 struct rate_hist rate_hist
;
1653 uint64_t psnr_sse_total
;
1654 uint64_t psnr_samples_total
;
1655 double psnr_totals
[4];
1658 vpx_codec_ctx_t encoder
;
1659 unsigned int frames_out
;
1663 struct vpx_image
*img
;
1664 vpx_codec_ctx_t decoder
;
1669 void validate_positive_rational(const char *msg
,
1670 struct vpx_rational
*rat
) {
1677 die("Error: %s must be positive\n", msg
);
1680 die("Error: %s has zero denominator\n", msg
);
1684 static void parse_global_config(struct global_config
*global
, char **argv
) {
1685 char **argi
, **argj
;
1688 /* Initialize default parameters */
1689 memset(global
, 0, sizeof(*global
));
1690 global
->codec
= codecs
;
1692 global
->use_i420
= 1;
1694 for (argi
= argj
= argv
; (*argj
= *argi
); argi
+= arg
.argv_step
) {
1697 if (arg_match(&arg
, &codecarg
, argi
)) {
1700 for (j
= 0; j
< sizeof(codecs
) / sizeof(codecs
[0]); j
++)
1701 if (!strcmp(codecs
[j
].name
, arg
.val
))
1705 global
->codec
= codecs
+ k
;
1707 die("Error: Unrecognized argument (%s) to --codec\n",
1710 } else if (arg_match(&arg
, &passes
, argi
)) {
1711 global
->passes
= arg_parse_uint(&arg
);
1713 if (global
->passes
< 1 || global
->passes
> 2)
1714 die("Error: Invalid number of passes (%d)\n", global
->passes
);
1715 } else if (arg_match(&arg
, &pass_arg
, argi
)) {
1716 global
->pass
= arg_parse_uint(&arg
);
1718 if (global
->pass
< 1 || global
->pass
> 2)
1719 die("Error: Invalid pass selected (%d)\n",
1721 } else if (arg_match(&arg
, &usage
, argi
))
1722 global
->usage
= arg_parse_uint(&arg
);
1723 else if (arg_match(&arg
, &deadline
, argi
))
1724 global
->deadline
= arg_parse_uint(&arg
);
1725 else if (arg_match(&arg
, &best_dl
, argi
))
1726 global
->deadline
= VPX_DL_BEST_QUALITY
;
1727 else if (arg_match(&arg
, &good_dl
, argi
))
1728 global
->deadline
= VPX_DL_GOOD_QUALITY
;
1729 else if (arg_match(&arg
, &rt_dl
, argi
))
1730 global
->deadline
= VPX_DL_REALTIME
;
1731 else if (arg_match(&arg
, &use_yv12
, argi
))
1732 global
->use_i420
= 0;
1733 else if (arg_match(&arg
, &use_i420
, argi
))
1734 global
->use_i420
= 1;
1735 else if (arg_match(&arg
, &quietarg
, argi
))
1737 else if (arg_match(&arg
, &verbosearg
, argi
))
1738 global
->verbose
= 1;
1739 else if (arg_match(&arg
, &limit
, argi
))
1740 global
->limit
= arg_parse_uint(&arg
);
1741 else if (arg_match(&arg
, &skip
, argi
))
1742 global
->skip_frames
= arg_parse_uint(&arg
);
1743 else if (arg_match(&arg
, &psnrarg
, argi
))
1744 global
->show_psnr
= 1;
1745 else if (arg_match(&arg
, &recontest
, argi
))
1746 global
->test_decode
= arg_parse_enum_or_int(&arg
);
1747 else if (arg_match(&arg
, &framerate
, argi
)) {
1748 global
->framerate
= arg_parse_rational(&arg
);
1749 validate_positive_rational(arg
.name
, &global
->framerate
);
1750 global
->have_framerate
= 1;
1751 } else if (arg_match(&arg
, &out_part
, argi
))
1752 global
->out_part
= 1;
1753 else if (arg_match(&arg
, &debugmode
, argi
))
1755 else if (arg_match(&arg
, &q_hist_n
, argi
))
1756 global
->show_q_hist_buckets
= arg_parse_uint(&arg
);
1757 else if (arg_match(&arg
, &rate_hist_n
, argi
))
1758 global
->show_rate_hist_buckets
= arg_parse_uint(&arg
);
1763 /* Validate global config */
1766 /* DWIM: Assume the user meant passes=2 if pass=2 is specified */
1767 if (global
->pass
> global
->passes
) {
1768 warn("Assuming --pass=%d implies --passes=%d\n",
1769 global
->pass
, global
->pass
);
1770 global
->passes
= global
->pass
;
1776 void open_input_file(struct input_state
*input
) {
1777 unsigned int fourcc
;
1779 /* Parse certain options from the input file, if possible */
1780 input
->file
= strcmp(input
->fn
, "-") ? fopen(input
->fn
, "rb")
1781 : set_binary_mode(stdin
);
1784 fatal("Failed to open input file");
1786 if (!fseeko(input
->file
, 0, SEEK_END
)) {
1787 /* Input file is seekable. Figure out how long it is, so we can get
1790 input
->length
= ftello(input
->file
);
1791 rewind(input
->file
);
1794 /* For RAW input sources, these bytes will applied on the first frame
1797 input
->detect
.buf_read
= fread(input
->detect
.buf
, 1, 4, input
->file
);
1798 input
->detect
.position
= 0;
1800 if (input
->detect
.buf_read
== 4
1801 && file_is_y4m(input
->file
, &input
->y4m
, input
->detect
.buf
)) {
1802 if (y4m_input_open(&input
->y4m
, input
->file
, input
->detect
.buf
, 4,
1803 input
->only_i420
) >= 0) {
1804 input
->file_type
= FILE_TYPE_Y4M
;
1805 input
->w
= input
->y4m
.pic_w
;
1806 input
->h
= input
->y4m
.pic_h
;
1807 input
->framerate
.num
= input
->y4m
.fps_n
;
1808 input
->framerate
.den
= input
->y4m
.fps_d
;
1809 input
->use_i420
= 0;
1811 fatal("Unsupported Y4M stream.");
1812 } else if (input
->detect
.buf_read
== 4 && file_is_ivf(input
, &fourcc
)) {
1813 input
->file_type
= FILE_TYPE_IVF
;
1816 input
->use_i420
= 0;
1819 input
->use_i420
= 1;
1822 fatal("Unsupported fourcc (%08x) in IVF", fourcc
);
1825 input
->file_type
= FILE_TYPE_RAW
;
1830 static void close_input_file(struct input_state
*input
) {
1831 fclose(input
->file
);
1832 if (input
->file_type
== FILE_TYPE_Y4M
)
1833 y4m_input_close(&input
->y4m
);
1836 static struct stream_state
*new_stream(struct global_config
*global
,
1837 struct stream_state
*prev
) {
1838 struct stream_state
*stream
;
1840 stream
= calloc(1, sizeof(*stream
));
1842 fatal("Failed to allocate new stream.");
1844 memcpy(stream
, prev
, sizeof(*stream
));
1846 prev
->next
= stream
;
1848 vpx_codec_err_t res
;
1850 /* Populate encoder configuration */
1851 res
= vpx_codec_enc_config_default(global
->codec
->iface(),
1852 &stream
->config
.cfg
,
1855 fatal("Failed to get config: %s\n", vpx_codec_err_to_string(res
));
1857 /* Change the default timebase to a high enough value so that the
1858 * encoder will always create strictly increasing timestamps.
1860 stream
->config
.cfg
.g_timebase
.den
= 1000;
1862 /* Never use the library's default resolution, require it be parsed
1863 * from the file or set on the command line.
1865 stream
->config
.cfg
.g_w
= 0;
1866 stream
->config
.cfg
.g_h
= 0;
1868 /* Initialize remaining stream parameters */
1869 stream
->config
.stereo_fmt
= STEREO_FORMAT_MONO
;
1870 stream
->config
.write_webm
= 1;
1871 stream
->ebml
.last_pts_ms
= -1;
1873 /* Allows removal of the application version from the EBML tags */
1874 stream
->ebml
.debug
= global
->debug
;
1877 /* Output files must be specified for each stream */
1878 stream
->config
.out_fn
= NULL
;
1880 stream
->next
= NULL
;
1885 static int parse_stream_params(struct global_config
*global
,
1886 struct stream_state
*stream
,
1888 char **argi
, **argj
;
1890 static const arg_def_t
**ctrl_args
= no_args
;
1891 static const int *ctrl_args_map
= NULL
;
1892 struct stream_config
*config
= &stream
->config
;
1893 int eos_mark_found
= 0;
1895 /* Handle codec specific options */
1897 #if CONFIG_VP8_ENCODER
1898 } else if (global
->codec
->iface
== vpx_codec_vp8_cx
) {
1899 ctrl_args
= vp8_args
;
1900 ctrl_args_map
= vp8_arg_ctrl_map
;
1902 #if CONFIG_VP9_ENCODER
1903 } else if (global
->codec
->iface
== vpx_codec_vp9_cx
) {
1904 ctrl_args
= vp9_args
;
1905 ctrl_args_map
= vp9_arg_ctrl_map
;
1909 for (argi
= argj
= argv
; (*argj
= *argi
); argi
+= arg
.argv_step
) {
1912 /* Once we've found an end-of-stream marker (--) we want to continue
1913 * shifting arguments but not consuming them.
1915 if (eos_mark_found
) {
1918 } else if (!strcmp(*argj
, "--")) {
1924 else if (arg_match(&arg
, &outputfile
, argi
))
1925 config
->out_fn
= arg
.val
;
1926 else if (arg_match(&arg
, &fpf_name
, argi
))
1927 config
->stats_fn
= arg
.val
;
1928 else if (arg_match(&arg
, &use_ivf
, argi
))
1929 config
->write_webm
= 0;
1930 else if (arg_match(&arg
, &threads
, argi
))
1931 config
->cfg
.g_threads
= arg_parse_uint(&arg
);
1932 else if (arg_match(&arg
, &profile
, argi
))
1933 config
->cfg
.g_profile
= arg_parse_uint(&arg
);
1934 else if (arg_match(&arg
, &width
, argi
))
1935 config
->cfg
.g_w
= arg_parse_uint(&arg
);
1936 else if (arg_match(&arg
, &height
, argi
))
1937 config
->cfg
.g_h
= arg_parse_uint(&arg
);
1938 else if (arg_match(&arg
, &stereo_mode
, argi
))
1939 config
->stereo_fmt
= arg_parse_enum_or_int(&arg
);
1940 else if (arg_match(&arg
, &timebase
, argi
)) {
1941 config
->cfg
.g_timebase
= arg_parse_rational(&arg
);
1942 validate_positive_rational(arg
.name
, &config
->cfg
.g_timebase
);
1943 } else if (arg_match(&arg
, &error_resilient
, argi
))
1944 config
->cfg
.g_error_resilient
= arg_parse_uint(&arg
);
1945 else if (arg_match(&arg
, &lag_in_frames
, argi
))
1946 config
->cfg
.g_lag_in_frames
= arg_parse_uint(&arg
);
1947 else if (arg_match(&arg
, &dropframe_thresh
, argi
))
1948 config
->cfg
.rc_dropframe_thresh
= arg_parse_uint(&arg
);
1949 else if (arg_match(&arg
, &resize_allowed
, argi
))
1950 config
->cfg
.rc_resize_allowed
= arg_parse_uint(&arg
);
1951 else if (arg_match(&arg
, &resize_up_thresh
, argi
))
1952 config
->cfg
.rc_resize_up_thresh
= arg_parse_uint(&arg
);
1953 else if (arg_match(&arg
, &resize_down_thresh
, argi
))
1954 config
->cfg
.rc_resize_down_thresh
= arg_parse_uint(&arg
);
1955 else if (arg_match(&arg
, &end_usage
, argi
))
1956 config
->cfg
.rc_end_usage
= arg_parse_enum_or_int(&arg
);
1957 else if (arg_match(&arg
, &target_bitrate
, argi
))
1958 config
->cfg
.rc_target_bitrate
= arg_parse_uint(&arg
);
1959 else if (arg_match(&arg
, &min_quantizer
, argi
))
1960 config
->cfg
.rc_min_quantizer
= arg_parse_uint(&arg
);
1961 else if (arg_match(&arg
, &max_quantizer
, argi
))
1962 config
->cfg
.rc_max_quantizer
= arg_parse_uint(&arg
);
1963 else if (arg_match(&arg
, &undershoot_pct
, argi
))
1964 config
->cfg
.rc_undershoot_pct
= arg_parse_uint(&arg
);
1965 else if (arg_match(&arg
, &overshoot_pct
, argi
))
1966 config
->cfg
.rc_overshoot_pct
= arg_parse_uint(&arg
);
1967 else if (arg_match(&arg
, &buf_sz
, argi
))
1968 config
->cfg
.rc_buf_sz
= arg_parse_uint(&arg
);
1969 else if (arg_match(&arg
, &buf_initial_sz
, argi
))
1970 config
->cfg
.rc_buf_initial_sz
= arg_parse_uint(&arg
);
1971 else if (arg_match(&arg
, &buf_optimal_sz
, argi
))
1972 config
->cfg
.rc_buf_optimal_sz
= arg_parse_uint(&arg
);
1973 else if (arg_match(&arg
, &bias_pct
, argi
)) {
1974 config
->cfg
.rc_2pass_vbr_bias_pct
= arg_parse_uint(&arg
);
1976 if (global
->passes
< 2)
1977 warn("option %s ignored in one-pass mode.\n", arg
.name
);
1978 } else if (arg_match(&arg
, &minsection_pct
, argi
)) {
1979 config
->cfg
.rc_2pass_vbr_minsection_pct
= arg_parse_uint(&arg
);
1981 if (global
->passes
< 2)
1982 warn("option %s ignored in one-pass mode.\n", arg
.name
);
1983 } else if (arg_match(&arg
, &maxsection_pct
, argi
)) {
1984 config
->cfg
.rc_2pass_vbr_maxsection_pct
= arg_parse_uint(&arg
);
1986 if (global
->passes
< 2)
1987 warn("option %s ignored in one-pass mode.\n", arg
.name
);
1988 } else if (arg_match(&arg
, &kf_min_dist
, argi
))
1989 config
->cfg
.kf_min_dist
= arg_parse_uint(&arg
);
1990 else if (arg_match(&arg
, &kf_max_dist
, argi
)) {
1991 config
->cfg
.kf_max_dist
= arg_parse_uint(&arg
);
1992 config
->have_kf_max_dist
= 1;
1993 } else if (arg_match(&arg
, &kf_disabled
, argi
))
1994 config
->cfg
.kf_mode
= VPX_KF_DISABLED
;
1998 for (i
= 0; ctrl_args
[i
]; i
++) {
1999 if (arg_match(&arg
, ctrl_args
[i
], argi
)) {
2003 /* Point either to the next free element or the first
2004 * instance of this control.
2006 for (j
= 0; j
< config
->arg_ctrl_cnt
; j
++)
2007 if (config
->arg_ctrls
[j
][0] == ctrl_args_map
[i
])
2011 assert(j
< ARG_CTRL_CNT_MAX
);
2012 if (j
< ARG_CTRL_CNT_MAX
) {
2013 config
->arg_ctrls
[j
][0] = ctrl_args_map
[i
];
2014 config
->arg_ctrls
[j
][1] = arg_parse_enum_or_int(&arg
);
2015 if (j
== config
->arg_ctrl_cnt
)
2016 config
->arg_ctrl_cnt
++;
2027 return eos_mark_found
;
2031 #define FOREACH_STREAM(func)\
2034 struct stream_state *stream;\
2036 for(stream = streams; stream; stream = stream->next)\
2041 static void validate_stream_config(struct stream_state
*stream
) {
2042 struct stream_state
*streami
;
2044 if (!stream
->config
.cfg
.g_w
|| !stream
->config
.cfg
.g_h
)
2045 fatal("Stream %d: Specify stream dimensions with --width (-w) "
2046 " and --height (-h)", stream
->index
);
2048 for (streami
= stream
; streami
; streami
= streami
->next
) {
2049 /* All streams require output files */
2050 if (!streami
->config
.out_fn
)
2051 fatal("Stream %d: Output file is required (specify with -o)",
2054 /* Check for two streams outputting to the same file */
2055 if (streami
!= stream
) {
2056 const char *a
= stream
->config
.out_fn
;
2057 const char *b
= streami
->config
.out_fn
;
2058 if (!strcmp(a
, b
) && strcmp(a
, "/dev/null") && strcmp(a
, ":nul"))
2059 fatal("Stream %d: duplicate output file (from stream %d)",
2060 streami
->index
, stream
->index
);
2063 /* Check for two streams sharing a stats file. */
2064 if (streami
!= stream
) {
2065 const char *a
= stream
->config
.stats_fn
;
2066 const char *b
= streami
->config
.stats_fn
;
2067 if (a
&& b
&& !strcmp(a
, b
))
2068 fatal("Stream %d: duplicate stats file (from stream %d)",
2069 streami
->index
, stream
->index
);
2075 static void set_stream_dimensions(struct stream_state
*stream
,
2078 if (!stream
->config
.cfg
.g_w
) {
2079 if (!stream
->config
.cfg
.g_h
)
2080 stream
->config
.cfg
.g_w
= w
;
2082 stream
->config
.cfg
.g_w
= w
* stream
->config
.cfg
.g_h
/ h
;
2084 if (!stream
->config
.cfg
.g_h
) {
2085 stream
->config
.cfg
.g_h
= h
* stream
->config
.cfg
.g_w
/ w
;
2090 static void set_default_kf_interval(struct stream_state
*stream
,
2091 struct global_config
*global
) {
2092 /* Use a max keyframe interval of 5 seconds, if none was
2093 * specified on the command line.
2095 if (!stream
->config
.have_kf_max_dist
) {
2096 double framerate
= (double)global
->framerate
.num
/ global
->framerate
.den
;
2097 if (framerate
> 0.0)
2098 stream
->config
.cfg
.kf_max_dist
= (unsigned int)(5.0 * framerate
);
2103 static void show_stream_config(struct stream_state
*stream
,
2104 struct global_config
*global
,
2105 struct input_state
*input
) {
2107 #define SHOW(field) \
2108 fprintf(stderr, " %-28s = %d\n", #field, stream->config.cfg.field)
2110 if (stream
->index
== 0) {
2111 fprintf(stderr
, "Codec: %s\n",
2112 vpx_codec_iface_name(global
->codec
->iface()));
2113 fprintf(stderr
, "Source file: %s Format: %s\n", input
->fn
,
2114 input
->use_i420
? "I420" : "YV12");
2116 if (stream
->next
|| stream
->index
)
2117 fprintf(stderr
, "\nStream Index: %d\n", stream
->index
);
2118 fprintf(stderr
, "Destination file: %s\n", stream
->config
.out_fn
);
2119 fprintf(stderr
, "Encoder parameters:\n");
2126 SHOW(g_timebase
.num
);
2127 SHOW(g_timebase
.den
);
2128 SHOW(g_error_resilient
);
2130 SHOW(g_lag_in_frames
);
2131 SHOW(rc_dropframe_thresh
);
2132 SHOW(rc_resize_allowed
);
2133 SHOW(rc_resize_up_thresh
);
2134 SHOW(rc_resize_down_thresh
);
2136 SHOW(rc_target_bitrate
);
2137 SHOW(rc_min_quantizer
);
2138 SHOW(rc_max_quantizer
);
2139 SHOW(rc_undershoot_pct
);
2140 SHOW(rc_overshoot_pct
);
2142 SHOW(rc_buf_initial_sz
);
2143 SHOW(rc_buf_optimal_sz
);
2144 SHOW(rc_2pass_vbr_bias_pct
);
2145 SHOW(rc_2pass_vbr_minsection_pct
);
2146 SHOW(rc_2pass_vbr_maxsection_pct
);
2153 static void open_output_file(struct stream_state
*stream
,
2154 struct global_config
*global
) {
2155 const char *fn
= stream
->config
.out_fn
;
2157 stream
->file
= strcmp(fn
, "-") ? fopen(fn
, "wb") : set_binary_mode(stdout
);
2160 fatal("Failed to open output file");
2162 if (stream
->config
.write_webm
&& fseek(stream
->file
, 0, SEEK_CUR
))
2163 fatal("WebM output to pipes not supported.");
2165 if (stream
->config
.write_webm
) {
2166 stream
->ebml
.stream
= stream
->file
;
2167 write_webm_file_header(&stream
->ebml
, &stream
->config
.cfg
,
2169 stream
->config
.stereo_fmt
,
2170 global
->codec
->fourcc
);
2172 write_ivf_file_header(stream
->file
, &stream
->config
.cfg
,
2173 global
->codec
->fourcc
, 0);
2177 static void close_output_file(struct stream_state
*stream
,
2178 unsigned int fourcc
) {
2179 if (stream
->config
.write_webm
) {
2180 write_webm_file_footer(&stream
->ebml
, stream
->hash
);
2181 free(stream
->ebml
.cue_list
);
2182 stream
->ebml
.cue_list
= NULL
;
2184 if (!fseek(stream
->file
, 0, SEEK_SET
))
2185 write_ivf_file_header(stream
->file
, &stream
->config
.cfg
,
2187 stream
->frames_out
);
2190 fclose(stream
->file
);
2194 static void setup_pass(struct stream_state
*stream
,
2195 struct global_config
*global
,
2197 if (stream
->config
.stats_fn
) {
2198 if (!stats_open_file(&stream
->stats
, stream
->config
.stats_fn
,
2200 fatal("Failed to open statistics store");
2202 if (!stats_open_mem(&stream
->stats
, pass
))
2203 fatal("Failed to open statistics store");
2206 stream
->config
.cfg
.g_pass
= global
->passes
== 2
2207 ? pass
? VPX_RC_LAST_PASS
: VPX_RC_FIRST_PASS
2210 stream
->config
.cfg
.rc_twopass_stats_in
= stats_get(&stream
->stats
);
2212 stream
->cx_time
= 0;
2214 stream
->frames_out
= 0;
2218 static void initialize_encoder(struct stream_state
*stream
,
2219 struct global_config
*global
) {
2223 flags
|= global
->show_psnr
? VPX_CODEC_USE_PSNR
: 0;
2224 flags
|= global
->out_part
? VPX_CODEC_USE_OUTPUT_PARTITION
: 0;
2226 /* Construct Encoder Context */
2227 vpx_codec_enc_init(&stream
->encoder
, global
->codec
->iface(),
2228 &stream
->config
.cfg
, flags
);
2229 ctx_exit_on_error(&stream
->encoder
, "Failed to initialize encoder");
2231 /* Note that we bypass the vpx_codec_control wrapper macro because
2232 * we're being clever to store the control IDs in an array. Real
2233 * applications will want to make use of the enumerations directly
2235 for (i
= 0; i
< stream
->config
.arg_ctrl_cnt
; i
++) {
2236 int ctrl
= stream
->config
.arg_ctrls
[i
][0];
2237 int value
= stream
->config
.arg_ctrls
[i
][1];
2238 if (vpx_codec_control_(&stream
->encoder
, ctrl
, value
))
2239 fprintf(stderr
, "Error: Tried to set control %d = %d\n",
2242 ctx_exit_on_error(&stream
->encoder
, "Failed to control codec");
2246 if (global
->test_decode
!= TEST_DECODE_OFF
) {
2247 vpx_codec_dec_init(&stream
->decoder
, global
->codec
->dx_iface(), NULL
, 0);
2253 static void encode_frame(struct stream_state
*stream
,
2254 struct global_config
*global
,
2255 struct vpx_image
*img
,
2256 unsigned int frames_in
) {
2257 vpx_codec_pts_t frame_start
, next_frame_start
;
2258 struct vpx_codec_enc_cfg
*cfg
= &stream
->config
.cfg
;
2259 struct vpx_usec_timer timer
;
2261 frame_start
= (cfg
->g_timebase
.den
* (int64_t)(frames_in
- 1)
2262 * global
->framerate
.den
)
2263 / cfg
->g_timebase
.num
/ global
->framerate
.num
;
2264 next_frame_start
= (cfg
->g_timebase
.den
* (int64_t)(frames_in
)
2265 * global
->framerate
.den
)
2266 / cfg
->g_timebase
.num
/ global
->framerate
.num
;
2268 /* Scale if necessary */
2269 if (img
&& (img
->d_w
!= cfg
->g_w
|| img
->d_h
!= cfg
->g_h
)) {
2271 stream
->img
= vpx_img_alloc(NULL
, VPX_IMG_FMT_I420
,
2272 cfg
->g_w
, cfg
->g_h
, 16);
2273 I420Scale(img
->planes
[VPX_PLANE_Y
], img
->stride
[VPX_PLANE_Y
],
2274 img
->planes
[VPX_PLANE_U
], img
->stride
[VPX_PLANE_U
],
2275 img
->planes
[VPX_PLANE_V
], img
->stride
[VPX_PLANE_V
],
2277 stream
->img
->planes
[VPX_PLANE_Y
],
2278 stream
->img
->stride
[VPX_PLANE_Y
],
2279 stream
->img
->planes
[VPX_PLANE_U
],
2280 stream
->img
->stride
[VPX_PLANE_U
],
2281 stream
->img
->planes
[VPX_PLANE_V
],
2282 stream
->img
->stride
[VPX_PLANE_V
],
2283 stream
->img
->d_w
, stream
->img
->d_h
,
2289 vpx_usec_timer_start(&timer
);
2290 vpx_codec_encode(&stream
->encoder
, img
, frame_start
,
2291 (unsigned long)(next_frame_start
- frame_start
),
2292 0, global
->deadline
);
2293 vpx_usec_timer_mark(&timer
);
2294 stream
->cx_time
+= vpx_usec_timer_elapsed(&timer
);
2295 ctx_exit_on_error(&stream
->encoder
, "Stream %d: Failed to encode frame",
2300 static void update_quantizer_histogram(struct stream_state
*stream
) {
2301 if (stream
->config
.cfg
.g_pass
!= VPX_RC_FIRST_PASS
) {
2304 vpx_codec_control(&stream
->encoder
, VP8E_GET_LAST_QUANTIZER_64
, &q
);
2305 ctx_exit_on_error(&stream
->encoder
, "Failed to read quantizer");
2306 stream
->counts
[q
]++;
2311 static void get_cx_data(struct stream_state
*stream
,
2312 struct global_config
*global
,
2314 const vpx_codec_cx_pkt_t
*pkt
;
2315 const struct vpx_codec_enc_cfg
*cfg
= &stream
->config
.cfg
;
2316 vpx_codec_iter_t iter
= NULL
;
2319 while ((pkt
= vpx_codec_get_cx_data(&stream
->encoder
, &iter
))) {
2320 static size_t fsize
= 0;
2321 static off_t ivf_header_pos
= 0;
2323 switch (pkt
->kind
) {
2324 case VPX_CODEC_CX_FRAME_PKT
:
2325 if (!(pkt
->data
.frame
.flags
& VPX_FRAME_IS_FRAGMENT
)) {
2326 stream
->frames_out
++;
2329 fprintf(stderr
, " %6luF", (unsigned long)pkt
->data
.frame
.sz
);
2331 update_rate_histogram(&stream
->rate_hist
, cfg
, pkt
);
2332 if (stream
->config
.write_webm
) {
2333 /* Update the hash */
2334 if (!stream
->ebml
.debug
)
2335 stream
->hash
= murmur(pkt
->data
.frame
.buf
,
2336 (int)pkt
->data
.frame
.sz
,
2339 write_webm_block(&stream
->ebml
, cfg
, pkt
);
2341 if (pkt
->data
.frame
.partition_id
<= 0) {
2342 ivf_header_pos
= ftello(stream
->file
);
2343 fsize
= pkt
->data
.frame
.sz
;
2345 write_ivf_frame_header(stream
->file
, pkt
);
2347 fsize
+= pkt
->data
.frame
.sz
;
2349 if (!(pkt
->data
.frame
.flags
& VPX_FRAME_IS_FRAGMENT
)) {
2350 off_t currpos
= ftello(stream
->file
);
2351 fseeko(stream
->file
, ivf_header_pos
, SEEK_SET
);
2352 write_ivf_frame_size(stream
->file
, fsize
);
2353 fseeko(stream
->file
, currpos
, SEEK_SET
);
2357 (void) fwrite(pkt
->data
.frame
.buf
, 1, pkt
->data
.frame
.sz
,
2360 stream
->nbytes
+= pkt
->data
.raw
.sz
;
2364 if (global
->test_decode
!= TEST_DECODE_OFF
&& !stream
->mismatch_seen
) {
2365 vpx_codec_decode(&stream
->decoder
, pkt
->data
.frame
.buf
,
2366 pkt
->data
.frame
.sz
, NULL
, 0);
2367 if (stream
->decoder
.err
) {
2368 warn_or_exit_on_error(&stream
->decoder
,
2369 global
->test_decode
== TEST_DECODE_FATAL
,
2370 "Failed to decode frame %d in stream %d",
2371 stream
->frames_out
+ 1, stream
->index
);
2372 stream
->mismatch_seen
= stream
->frames_out
+ 1;
2377 case VPX_CODEC_STATS_PKT
:
2378 stream
->frames_out
++;
2379 stats_write(&stream
->stats
,
2380 pkt
->data
.twopass_stats
.buf
,
2381 pkt
->data
.twopass_stats
.sz
);
2382 stream
->nbytes
+= pkt
->data
.raw
.sz
;
2384 case VPX_CODEC_PSNR_PKT
:
2386 if (global
->show_psnr
) {
2389 stream
->psnr_sse_total
+= pkt
->data
.psnr
.sse
[0];
2390 stream
->psnr_samples_total
+= pkt
->data
.psnr
.samples
[0];
2391 for (i
= 0; i
< 4; i
++) {
2393 fprintf(stderr
, "%.3f ", pkt
->data
.psnr
.psnr
[i
]);
2394 stream
->psnr_totals
[i
] += pkt
->data
.psnr
.psnr
[i
];
2396 stream
->psnr_count
++;
2407 static void show_psnr(struct stream_state
*stream
) {
2411 if (!stream
->psnr_count
)
2414 fprintf(stderr
, "Stream %d PSNR (Overall/Avg/Y/U/V)", stream
->index
);
2415 ovpsnr
= vp8_mse2psnr((double)stream
->psnr_samples_total
, 255.0,
2416 (double)stream
->psnr_sse_total
);
2417 fprintf(stderr
, " %.3f", ovpsnr
);
2419 for (i
= 0; i
< 4; i
++) {
2420 fprintf(stderr
, " %.3f", stream
->psnr_totals
[i
] / stream
->psnr_count
);
2422 fprintf(stderr
, "\n");
2426 static float usec_to_fps(uint64_t usec
, unsigned int frames
) {
2427 return (float)(usec
> 0 ? frames
* 1000000.0 / (float)usec
: 0);
2431 static void test_decode(struct stream_state
*stream
,
2432 enum TestDecodeFatality fatal
,
2433 const struct codec_item
*codec
) {
2434 vpx_image_t enc_img
, dec_img
;
2436 if (stream
->mismatch_seen
)
2439 /* Get the internal reference frame */
2440 if (codec
->fourcc
== VP8_FOURCC
) {
2441 struct vpx_ref_frame ref_enc
, ref_dec
;
2444 width
= (stream
->config
.cfg
.g_w
+ 15) & ~15;
2445 height
= (stream
->config
.cfg
.g_h
+ 15) & ~15;
2446 vpx_img_alloc(&ref_enc
.img
, VPX_IMG_FMT_I420
, width
, height
, 1);
2447 enc_img
= ref_enc
.img
;
2448 vpx_img_alloc(&ref_dec
.img
, VPX_IMG_FMT_I420
, width
, height
, 1);
2449 dec_img
= ref_dec
.img
;
2451 ref_enc
.frame_type
= VP8_LAST_FRAME
;
2452 ref_dec
.frame_type
= VP8_LAST_FRAME
;
2453 vpx_codec_control(&stream
->encoder
, VP8_COPY_REFERENCE
, &ref_enc
);
2454 vpx_codec_control(&stream
->decoder
, VP8_COPY_REFERENCE
, &ref_dec
);
2456 struct vp9_ref_frame ref
;
2459 vpx_codec_control(&stream
->encoder
, VP9_GET_REFERENCE
, &ref
);
2461 vpx_codec_control(&stream
->decoder
, VP9_GET_REFERENCE
, &ref
);
2464 ctx_exit_on_error(&stream
->encoder
, "Failed to get encoder reference frame");
2465 ctx_exit_on_error(&stream
->decoder
, "Failed to get decoder reference frame");
2467 if (!compare_img(&enc_img
, &dec_img
)) {
2468 int y
[4], u
[4], v
[4];
2469 find_mismatch(&enc_img
, &dec_img
, y
, u
, v
);
2470 stream
->decoder
.err
= 1;
2471 warn_or_exit_on_error(&stream
->decoder
, fatal
== TEST_DECODE_FATAL
,
2472 "Stream %d: Encode/decode mismatch on frame %d at"
2473 " Y[%d, %d] {%d/%d},"
2474 " U[%d, %d] {%d/%d},"
2475 " V[%d, %d] {%d/%d}",
2476 stream
->index
, stream
->frames_out
,
2477 y
[0], y
[1], y
[2], y
[3],
2478 u
[0], u
[1], u
[2], u
[3],
2479 v
[0], v
[1], v
[2], v
[3]);
2480 stream
->mismatch_seen
= stream
->frames_out
;
2483 vpx_img_free(&enc_img
);
2484 vpx_img_free(&dec_img
);
2488 static void print_time(const char *label
, int64_t etl
) {
2489 int hours
, mins
, secs
;
2493 etl
-= hours
* 3600;
2498 fprintf(stderr
, "[%3s %2d:%02d:%02d] ",
2499 label
, hours
, mins
, secs
);
2501 fprintf(stderr
, "[%3s unknown] ", label
);
2505 int main(int argc
, const char **argv_
) {
2508 int frame_avail
, got_data
;
2510 struct input_state input
= {0};
2511 struct global_config global
;
2512 struct stream_state
*streams
= NULL
;
2513 char **argv
, **argi
;
2514 uint64_t cx_time
= 0;
2518 exec_name
= argv_
[0];
2523 /* Setup default input stream settings */
2524 input
.framerate
.num
= 30;
2525 input
.framerate
.den
= 1;
2527 input
.only_i420
= 1;
2529 /* First parse the global configuration values, because we want to apply
2530 * other parameters on top of the default configuration provided by the
2533 argv
= argv_dup(argc
- 1, argv_
+ 1);
2534 parse_global_config(&global
, argv
);
2537 /* Now parse each stream's parameters. Using a local scope here
2538 * due to the use of 'stream' as loop variable in FOREACH_STREAM
2541 struct stream_state
*stream
= NULL
;
2544 stream
= new_stream(&global
, stream
);
2548 } while (parse_stream_params(&global
, stream
, argv
));
2551 /* Check for unrecognized options */
2552 for (argi
= argv
; *argi
; argi
++)
2553 if (argi
[0][0] == '-' && argi
[0][1])
2554 die("Error: Unrecognized option %s\n", *argi
);
2556 /* Handle non-option arguments */
2563 /* Decide if other chroma subsamplings than 4:2:0 are supported */
2564 if (global
.codec
->fourcc
== VP9_FOURCC
)
2565 input
.only_i420
= 0;
2568 for (pass
= global
.pass
? global
.pass
- 1 : 0; pass
< global
.passes
; pass
++) {
2569 int frames_in
= 0, seen_frames
= 0;
2570 int64_t estimated_time_left
= -1;
2571 int64_t average_rate
= -1;
2572 off_t lagged_count
= 0;
2574 open_input_file(&input
);
2576 /* If the input file doesn't specify its w/h (raw files), try to get
2577 * the data from the first stream's configuration.
2579 if (!input
.w
|| !input
.h
)
2581 if (stream
->config
.cfg
.g_w
&& stream
->config
.cfg
.g_h
) {
2582 input
.w
= stream
->config
.cfg
.g_w
;
2583 input
.h
= stream
->config
.cfg
.g_h
;
2588 /* Update stream configurations from the input file's parameters */
2589 if (!input
.w
|| !input
.h
)
2590 fatal("Specify stream dimensions with --width (-w) "
2591 " and --height (-h)");
2592 FOREACH_STREAM(set_stream_dimensions(stream
, input
.w
, input
.h
));
2593 FOREACH_STREAM(validate_stream_config(stream
));
2595 /* Ensure that --passes and --pass are consistent. If --pass is set and
2596 * --passes=2, ensure --fpf was set.
2598 if (global
.pass
&& global
.passes
== 2)
2600 if (!stream
->config
.stats_fn
)
2601 die("Stream %d: Must specify --fpf when --pass=%d"
2602 " and --passes=2\n", stream
->index
, global
.pass
);
2605 /* Use the frame rate from the file only if none was specified
2606 * on the command-line.
2608 if (!global
.have_framerate
)
2609 global
.framerate
= input
.framerate
;
2611 FOREACH_STREAM(set_default_kf_interval(stream
, &global
));
2613 /* Show configuration */
2614 if (global
.verbose
&& pass
== 0)
2615 FOREACH_STREAM(show_stream_config(stream
, &global
, &input
));
2617 if (pass
== (global
.pass
? global
.pass
- 1 : 0)) {
2618 if (input
.file_type
== FILE_TYPE_Y4M
)
2619 /*The Y4M reader does its own allocation.
2620 Just initialize this here to avoid problems if we never read any
2622 memset(&raw
, 0, sizeof(raw
));
2625 input
.use_i420
? VPX_IMG_FMT_I420
2627 input
.w
, input
.h
, 32);
2629 FOREACH_STREAM(init_rate_histogram(&stream
->rate_hist
,
2630 &stream
->config
.cfg
,
2631 &global
.framerate
));
2634 FOREACH_STREAM(open_output_file(stream
, &global
));
2635 FOREACH_STREAM(setup_pass(stream
, &global
, pass
));
2636 FOREACH_STREAM(initialize_encoder(stream
, &global
));
2641 while (frame_avail
|| got_data
) {
2642 struct vpx_usec_timer timer
;
2644 if (!global
.limit
|| frames_in
< global
.limit
) {
2645 frame_avail
= read_frame(&input
, &raw
);
2649 seen_frames
= frames_in
> global
.skip_frames
?
2650 frames_in
- global
.skip_frames
: 0;
2652 if (!global
.quiet
) {
2653 float fps
= usec_to_fps(cx_time
, seen_frames
);
2654 fprintf(stderr
, "\rPass %d/%d ", pass
+ 1, global
.passes
);
2656 if (stream_cnt
== 1)
2658 "frame %4d/%-4d %7"PRId64
"B ",
2659 frames_in
, streams
->frames_out
, (int64_t)streams
->nbytes
);
2661 fprintf(stderr
, "frame %4d ", frames_in
);
2663 fprintf(stderr
, "%7"PRId64
" %s %.2f %s ",
2664 cx_time
> 9999999 ? cx_time
/ 1000 : cx_time
,
2665 cx_time
> 9999999 ? "ms" : "us",
2666 fps
>= 1.0 ? fps
: 1000.0 / fps
,
2667 fps
>= 1.0 ? "fps" : "ms/f");
2668 print_time("ETA", estimated_time_left
);
2669 fprintf(stderr
, "\033[K");
2675 if (frames_in
> global
.skip_frames
) {
2676 vpx_usec_timer_start(&timer
);
2677 FOREACH_STREAM(encode_frame(stream
, &global
,
2678 frame_avail
? &raw
: NULL
,
2680 vpx_usec_timer_mark(&timer
);
2681 cx_time
+= vpx_usec_timer_elapsed(&timer
);
2683 FOREACH_STREAM(update_quantizer_histogram(stream
));
2686 FOREACH_STREAM(get_cx_data(stream
, &global
, &got_data
));
2688 if (!got_data
&& input
.length
&& !streams
->frames_out
) {
2689 lagged_count
= global
.limit
? seen_frames
: ftello(input
.file
);
2690 } else if (input
.length
) {
2695 int frame_in_lagged
= (seen_frames
- lagged_count
) * 1000;
2697 rate
= cx_time
? frame_in_lagged
* (int64_t)1000000 / cx_time
: 0;
2698 remaining
= 1000 * (global
.limit
- global
.skip_frames
2699 - seen_frames
+ lagged_count
);
2701 off_t input_pos
= ftello(input
.file
);
2702 off_t input_pos_lagged
= input_pos
- lagged_count
;
2703 int64_t limit
= input
.length
;
2705 rate
= cx_time
? input_pos_lagged
* (int64_t)1000000 / cx_time
: 0;
2706 remaining
= limit
- input_pos
+ lagged_count
;
2709 average_rate
= (average_rate
<= 0)
2711 : (average_rate
* 7 + rate
) / 8;
2712 estimated_time_left
= average_rate
? remaining
/ average_rate
: -1;
2715 if (got_data
&& global
.test_decode
!= TEST_DECODE_OFF
)
2716 FOREACH_STREAM(test_decode(stream
, global
.test_decode
, global
.codec
));
2723 fprintf(stderr
, "\n");
2726 FOREACH_STREAM(fprintf(
2728 "\rPass %d/%d frame %4d/%-4d %7"PRId64
"B %7lub/f %7"PRId64
"b/s"
2729 " %7"PRId64
" %s (%.2f fps)\033[K\n", pass
+ 1,
2730 global
.passes
, frames_in
, stream
->frames_out
, (int64_t)stream
->nbytes
,
2731 seen_frames
? (unsigned long)(stream
->nbytes
* 8 / seen_frames
) : 0,
2732 seen_frames
? (int64_t)stream
->nbytes
* 8
2733 * (int64_t)global
.framerate
.num
/ global
.framerate
.den
2736 stream
->cx_time
> 9999999 ? stream
->cx_time
/ 1000 : stream
->cx_time
,
2737 stream
->cx_time
> 9999999 ? "ms" : "us",
2738 usec_to_fps(stream
->cx_time
, seen_frames
));
2741 if (global
.show_psnr
)
2742 FOREACH_STREAM(show_psnr(stream
));
2744 FOREACH_STREAM(vpx_codec_destroy(&stream
->encoder
));
2746 if (global
.test_decode
!= TEST_DECODE_OFF
) {
2747 FOREACH_STREAM(vpx_codec_destroy(&stream
->decoder
));
2750 close_input_file(&input
);
2752 if (global
.test_decode
== TEST_DECODE_FATAL
) {
2753 FOREACH_STREAM(res
|= stream
->mismatch_seen
);
2755 FOREACH_STREAM(close_output_file(stream
, global
.codec
->fourcc
));
2757 FOREACH_STREAM(stats_close(&stream
->stats
, global
.passes
- 1));
2763 if (global
.show_q_hist_buckets
)
2764 FOREACH_STREAM(show_q_histogram(stream
->counts
,
2765 global
.show_q_hist_buckets
));
2767 if (global
.show_rate_hist_buckets
)
2768 FOREACH_STREAM(show_rate_histogram(&stream
->rate_hist
,
2769 &stream
->config
.cfg
,
2770 global
.show_rate_hist_buckets
));
2771 FOREACH_STREAM(destroy_rate_histogram(&stream
->rate_hist
));
2773 #if CONFIG_INTERNAL_STATS
2774 /* TODO(jkoleszar): This doesn't belong in this executable. Do it for now,
2775 * to match some existing utilities.
2778 FILE *f
= fopen("opsnr.stt", "a");
2779 if (stream
->mismatch_seen
) {
2780 fprintf(f
, "First mismatch occurred in frame %d\n",
2781 stream
->mismatch_seen
);
2783 fprintf(f
, "No mismatch detected in recon buffers\n");
2792 return res
? EXIT_FAILURE
: EXIT_SUCCESS
;