Removed unused variable warnings
[aom.git] / vpxenc.c
blob89cdef01e4ce3993b91c71cac7af5c6c57c0ef41
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) || !CONFIG_OS_SUPPORT
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 "tools_common.h"
39 #include "y4minput.h"
40 #include "libmkv/EbmlWriter.h"
41 #include "libmkv/EbmlIDs.h"
43 /* Need special handling of these functions on Windows */
44 #if defined(_MSC_VER)
45 /* MSVS doesn't define off_t, and uses _f{seek,tell}i64 */
46 typedef __int64 off_t;
47 #define fseeko _fseeki64
48 #define ftello _ftelli64
49 #elif defined(_WIN32)
50 /* MinGW defines off_t, and uses f{seek,tell}o64 */
51 #define fseeko fseeko64
52 #define ftello ftello64
53 #endif
55 #if defined(_MSC_VER)
56 #define LITERALU64(n) n
57 #else
58 #define LITERALU64(n) n##LLU
59 #endif
61 /* We should use 32-bit file operations in WebM file format
62 * when building ARM executable file (.axf) with RVCT */
63 #if !CONFIG_OS_SUPPORT
64 typedef long off_t;
65 #define fseeko fseek
66 #define ftello ftell
67 #endif
69 static const char *exec_name;
71 static const struct codec_item
73 char const *name;
74 const vpx_codec_iface_t *iface;
75 unsigned int fourcc;
76 } codecs[] =
78 #if CONFIG_VP8_ENCODER
79 {"vp8", &vpx_codec_vp8_cx_algo, 0x30385056},
80 #endif
83 static void usage_exit();
85 void die(const char *fmt, ...)
87 va_list ap;
88 va_start(ap, fmt);
89 vfprintf(stderr, fmt, ap);
90 fprintf(stderr, "\n");
91 usage_exit();
94 static void ctx_exit_on_error(vpx_codec_ctx_t *ctx, const char *s)
96 if (ctx->err)
98 const char *detail = vpx_codec_error_detail(ctx);
100 fprintf(stderr, "%s: %s\n", s, vpx_codec_error(ctx));
102 if (detail)
103 fprintf(stderr, " %s\n", detail);
105 exit(EXIT_FAILURE);
109 /* This structure is used to abstract the different ways of handling
110 * first pass statistics.
112 typedef struct
114 vpx_fixed_buf_t buf;
115 int pass;
116 FILE *file;
117 char *buf_ptr;
118 size_t buf_alloc_sz;
119 } stats_io_t;
121 int stats_open_file(stats_io_t *stats, const char *fpf, int pass)
123 int res;
125 stats->pass = pass;
127 if (pass == 0)
129 stats->file = fopen(fpf, "wb");
130 stats->buf.sz = 0;
131 stats->buf.buf = NULL,
132 res = (stats->file != NULL);
134 else
136 #if 0
137 #elif USE_POSIX_MMAP
138 struct stat stat_buf;
139 int fd;
141 fd = open(fpf, O_RDONLY);
142 stats->file = fdopen(fd, "rb");
143 fstat(fd, &stat_buf);
144 stats->buf.sz = stat_buf.st_size;
145 stats->buf.buf = mmap(NULL, stats->buf.sz, PROT_READ, MAP_PRIVATE,
146 fd, 0);
147 res = (stats->buf.buf != NULL);
148 #else
149 size_t nbytes;
151 stats->file = fopen(fpf, "rb");
153 if (fseek(stats->file, 0, SEEK_END))
155 fprintf(stderr, "First-pass stats file must be seekable!\n");
156 exit(EXIT_FAILURE);
159 stats->buf.sz = stats->buf_alloc_sz = ftell(stats->file);
160 rewind(stats->file);
162 stats->buf.buf = malloc(stats->buf_alloc_sz);
164 if (!stats->buf.buf)
166 fprintf(stderr, "Failed to allocate first-pass stats buffer (%lu bytes)\n",
167 (unsigned long)stats->buf_alloc_sz);
168 exit(EXIT_FAILURE);
171 nbytes = fread(stats->buf.buf, 1, stats->buf.sz, stats->file);
172 res = (nbytes == stats->buf.sz);
173 #endif
176 return res;
179 int stats_open_mem(stats_io_t *stats, int pass)
181 int res;
182 stats->pass = pass;
184 if (!pass)
186 stats->buf.sz = 0;
187 stats->buf_alloc_sz = 64 * 1024;
188 stats->buf.buf = malloc(stats->buf_alloc_sz);
191 stats->buf_ptr = stats->buf.buf;
192 res = (stats->buf.buf != NULL);
193 return res;
197 void stats_close(stats_io_t *stats, int last_pass)
199 if (stats->file)
201 if (stats->pass == last_pass)
203 #if 0
204 #elif USE_POSIX_MMAP
205 munmap(stats->buf.buf, stats->buf.sz);
206 #else
207 free(stats->buf.buf);
208 #endif
211 fclose(stats->file);
212 stats->file = NULL;
214 else
216 if (stats->pass == last_pass)
217 free(stats->buf.buf);
221 void stats_write(stats_io_t *stats, const void *pkt, size_t len)
223 if (stats->file)
225 if(fwrite(pkt, 1, len, stats->file));
227 else
229 if (stats->buf.sz + len > stats->buf_alloc_sz)
231 size_t new_sz = stats->buf_alloc_sz + 64 * 1024;
232 char *new_ptr = realloc(stats->buf.buf, new_sz);
234 if (new_ptr)
236 stats->buf_ptr = new_ptr + (stats->buf_ptr - (char *)stats->buf.buf);
237 stats->buf.buf = new_ptr;
238 stats->buf_alloc_sz = new_sz;
240 else
242 fprintf(stderr,
243 "\nFailed to realloc firstpass stats buffer.\n");
244 exit(EXIT_FAILURE);
248 memcpy(stats->buf_ptr, pkt, len);
249 stats->buf.sz += len;
250 stats->buf_ptr += len;
254 vpx_fixed_buf_t stats_get(stats_io_t *stats)
256 return stats->buf;
259 /* Stereo 3D packed frame format */
260 typedef enum stereo_format
262 STEREO_FORMAT_MONO = 0,
263 STEREO_FORMAT_LEFT_RIGHT = 1,
264 STEREO_FORMAT_BOTTOM_TOP = 2,
265 STEREO_FORMAT_TOP_BOTTOM = 3,
266 STEREO_FORMAT_RIGHT_LEFT = 11
267 } stereo_format_t;
269 enum video_file_type
271 FILE_TYPE_RAW,
272 FILE_TYPE_IVF,
273 FILE_TYPE_Y4M
276 struct detect_buffer {
277 char buf[4];
278 size_t buf_read;
279 size_t position;
283 #define IVF_FRAME_HDR_SZ (4+8) /* 4 byte size + 8 byte timestamp */
284 static int read_frame(FILE *f, vpx_image_t *img, unsigned int file_type,
285 y4m_input *y4m, struct detect_buffer *detect)
287 int plane = 0;
288 int shortread = 0;
290 if (file_type == FILE_TYPE_Y4M)
292 if (y4m_input_fetch_frame(y4m, f, img) < 1)
293 return 0;
295 else
297 if (file_type == FILE_TYPE_IVF)
299 char junk[IVF_FRAME_HDR_SZ];
301 /* Skip the frame header. We know how big the frame should be. See
302 * write_ivf_frame_header() for documentation on the frame header
303 * layout.
305 if(fread(junk, 1, IVF_FRAME_HDR_SZ, f));
308 for (plane = 0; plane < 3; plane++)
310 unsigned char *ptr;
311 int w = (plane ? (1 + img->d_w) / 2 : img->d_w);
312 int h = (plane ? (1 + img->d_h) / 2 : img->d_h);
313 int r;
315 /* Determine the correct plane based on the image format. The for-loop
316 * always counts in Y,U,V order, but this may not match the order of
317 * the data on disk.
319 switch (plane)
321 case 1:
322 ptr = img->planes[img->fmt==VPX_IMG_FMT_YV12? VPX_PLANE_V : VPX_PLANE_U];
323 break;
324 case 2:
325 ptr = img->planes[img->fmt==VPX_IMG_FMT_YV12?VPX_PLANE_U : VPX_PLANE_V];
326 break;
327 default:
328 ptr = img->planes[plane];
331 for (r = 0; r < h; r++)
333 size_t needed = w;
334 size_t buf_position = 0;
335 const size_t left = detect->buf_read - detect->position;
336 if (left > 0)
338 const size_t more = (left < needed) ? left : needed;
339 memcpy(ptr, detect->buf + detect->position, more);
340 buf_position = more;
341 needed -= more;
342 detect->position += more;
344 if (needed > 0)
346 shortread |= (fread(ptr + buf_position, 1, needed, f) < needed);
349 ptr += img->stride[plane];
354 return !shortread;
358 unsigned int file_is_y4m(FILE *infile,
359 y4m_input *y4m,
360 char detect[4])
362 if(memcmp(detect, "YUV4", 4) == 0)
364 return 1;
366 return 0;
369 #define IVF_FILE_HDR_SZ (32)
370 unsigned int file_is_ivf(FILE *infile,
371 unsigned int *fourcc,
372 unsigned int *width,
373 unsigned int *height,
374 struct detect_buffer *detect)
376 char raw_hdr[IVF_FILE_HDR_SZ];
377 int is_ivf = 0;
379 if(memcmp(detect->buf, "DKIF", 4) != 0)
380 return 0;
382 /* See write_ivf_file_header() for more documentation on the file header
383 * layout.
385 if (fread(raw_hdr + 4, 1, IVF_FILE_HDR_SZ - 4, infile)
386 == IVF_FILE_HDR_SZ - 4)
389 is_ivf = 1;
391 if (mem_get_le16(raw_hdr + 4) != 0)
392 fprintf(stderr, "Error: Unrecognized IVF version! This file may not"
393 " decode properly.");
395 *fourcc = mem_get_le32(raw_hdr + 8);
399 if (is_ivf)
401 *width = mem_get_le16(raw_hdr + 12);
402 *height = mem_get_le16(raw_hdr + 14);
403 detect->position = 4;
406 return is_ivf;
410 static void write_ivf_file_header(FILE *outfile,
411 const vpx_codec_enc_cfg_t *cfg,
412 unsigned int fourcc,
413 int frame_cnt)
415 char header[32];
417 if (cfg->g_pass != VPX_RC_ONE_PASS && cfg->g_pass != VPX_RC_LAST_PASS)
418 return;
420 header[0] = 'D';
421 header[1] = 'K';
422 header[2] = 'I';
423 header[3] = 'F';
424 mem_put_le16(header + 4, 0); /* version */
425 mem_put_le16(header + 6, 32); /* headersize */
426 mem_put_le32(header + 8, fourcc); /* headersize */
427 mem_put_le16(header + 12, cfg->g_w); /* width */
428 mem_put_le16(header + 14, cfg->g_h); /* height */
429 mem_put_le32(header + 16, cfg->g_timebase.den); /* rate */
430 mem_put_le32(header + 20, cfg->g_timebase.num); /* scale */
431 mem_put_le32(header + 24, frame_cnt); /* length */
432 mem_put_le32(header + 28, 0); /* unused */
434 if(fwrite(header, 1, 32, outfile));
438 static void write_ivf_frame_header(FILE *outfile,
439 const vpx_codec_cx_pkt_t *pkt)
441 char header[12];
442 vpx_codec_pts_t pts;
444 if (pkt->kind != VPX_CODEC_CX_FRAME_PKT)
445 return;
447 pts = pkt->data.frame.pts;
448 mem_put_le32(header, pkt->data.frame.sz);
449 mem_put_le32(header + 4, pts & 0xFFFFFFFF);
450 mem_put_le32(header + 8, pts >> 32);
452 if(fwrite(header, 1, 12, outfile));
456 typedef off_t EbmlLoc;
459 struct cue_entry
461 unsigned int time;
462 uint64_t loc;
466 struct EbmlGlobal
468 int debug;
470 FILE *stream;
471 int64_t last_pts_ms;
472 vpx_rational_t framerate;
474 /* These pointers are to the start of an element */
475 off_t position_reference;
476 off_t seek_info_pos;
477 off_t segment_info_pos;
478 off_t track_pos;
479 off_t cue_pos;
480 off_t cluster_pos;
482 /* This pointer is to a specific element to be serialized */
483 off_t track_id_pos;
485 /* These pointers are to the size field of the element */
486 EbmlLoc startSegment;
487 EbmlLoc startCluster;
489 uint32_t cluster_timecode;
490 int cluster_open;
492 struct cue_entry *cue_list;
493 unsigned int cues;
498 void Ebml_Write(EbmlGlobal *glob, const void *buffer_in, unsigned long len)
500 if(fwrite(buffer_in, 1, len, glob->stream));
504 void Ebml_Serialize(EbmlGlobal *glob, const void *buffer_in, unsigned long len)
506 const unsigned char *q = (const unsigned char *)buffer_in + len - 1;
508 for(; len; len--)
509 Ebml_Write(glob, q--, 1);
513 /* Need a fixed size serializer for the track ID. libmkv provdes a 64 bit
514 * one, but not a 32 bit one.
516 static void Ebml_SerializeUnsigned32(EbmlGlobal *glob, unsigned long class_id, uint64_t ui)
518 unsigned char sizeSerialized = 4 | 0x80;
519 Ebml_WriteID(glob, class_id);
520 Ebml_Serialize(glob, &sizeSerialized, 1);
521 Ebml_Serialize(glob, &ui, 4);
525 static void
526 Ebml_StartSubElement(EbmlGlobal *glob, EbmlLoc *ebmlLoc,
527 unsigned long class_id)
529 //todo this is always taking 8 bytes, this may need later optimization
530 //this is a key that says lenght unknown
531 unsigned long long unknownLen = LITERALU64(0x01FFFFFFFFFFFFFF);
533 Ebml_WriteID(glob, class_id);
534 *ebmlLoc = ftello(glob->stream);
535 Ebml_Serialize(glob, &unknownLen, 8);
538 static void
539 Ebml_EndSubElement(EbmlGlobal *glob, EbmlLoc *ebmlLoc)
541 off_t pos;
542 uint64_t size;
544 /* Save the current stream pointer */
545 pos = ftello(glob->stream);
547 /* Calculate the size of this element */
548 size = pos - *ebmlLoc - 8;
549 size |= LITERALU64(0x0100000000000000);
551 /* Seek back to the beginning of the element and write the new size */
552 fseeko(glob->stream, *ebmlLoc, SEEK_SET);
553 Ebml_Serialize(glob, &size, 8);
555 /* Reset the stream pointer */
556 fseeko(glob->stream, pos, SEEK_SET);
560 static void
561 write_webm_seek_element(EbmlGlobal *ebml, unsigned long id, off_t pos)
563 uint64_t offset = pos - ebml->position_reference;
564 EbmlLoc start;
565 Ebml_StartSubElement(ebml, &start, Seek);
566 Ebml_SerializeBinary(ebml, SeekID, id);
567 Ebml_SerializeUnsigned64(ebml, SeekPosition, offset);
568 Ebml_EndSubElement(ebml, &start);
572 static void
573 write_webm_seek_info(EbmlGlobal *ebml)
576 off_t pos;
578 /* Save the current stream pointer */
579 pos = ftello(ebml->stream);
581 if(ebml->seek_info_pos)
582 fseeko(ebml->stream, ebml->seek_info_pos, SEEK_SET);
583 else
584 ebml->seek_info_pos = pos;
587 EbmlLoc start;
589 Ebml_StartSubElement(ebml, &start, SeekHead);
590 write_webm_seek_element(ebml, Tracks, ebml->track_pos);
591 write_webm_seek_element(ebml, Cues, ebml->cue_pos);
592 write_webm_seek_element(ebml, Info, ebml->segment_info_pos);
593 Ebml_EndSubElement(ebml, &start);
596 //segment info
597 EbmlLoc startInfo;
598 uint64_t frame_time;
600 frame_time = (uint64_t)1000 * ebml->framerate.den
601 / ebml->framerate.num;
602 ebml->segment_info_pos = ftello(ebml->stream);
603 Ebml_StartSubElement(ebml, &startInfo, Info);
604 Ebml_SerializeUnsigned(ebml, TimecodeScale, 1000000);
605 Ebml_SerializeFloat(ebml, Segment_Duration,
606 ebml->last_pts_ms + frame_time);
607 Ebml_SerializeString(ebml, 0x4D80,
608 ebml->debug ? "vpxenc" : "vpxenc" VERSION_STRING);
609 Ebml_SerializeString(ebml, 0x5741,
610 ebml->debug ? "vpxenc" : "vpxenc" VERSION_STRING);
611 Ebml_EndSubElement(ebml, &startInfo);
616 static void
617 write_webm_file_header(EbmlGlobal *glob,
618 const vpx_codec_enc_cfg_t *cfg,
619 const struct vpx_rational *fps,
620 stereo_format_t stereo_fmt)
623 EbmlLoc start;
624 Ebml_StartSubElement(glob, &start, EBML);
625 Ebml_SerializeUnsigned(glob, EBMLVersion, 1);
626 Ebml_SerializeUnsigned(glob, EBMLReadVersion, 1); //EBML Read Version
627 Ebml_SerializeUnsigned(glob, EBMLMaxIDLength, 4); //EBML Max ID Length
628 Ebml_SerializeUnsigned(glob, EBMLMaxSizeLength, 8); //EBML Max Size Length
629 Ebml_SerializeString(glob, DocType, "webm"); //Doc Type
630 Ebml_SerializeUnsigned(glob, DocTypeVersion, 2); //Doc Type Version
631 Ebml_SerializeUnsigned(glob, DocTypeReadVersion, 2); //Doc Type Read Version
632 Ebml_EndSubElement(glob, &start);
635 Ebml_StartSubElement(glob, &glob->startSegment, Segment); //segment
636 glob->position_reference = ftello(glob->stream);
637 glob->framerate = *fps;
638 write_webm_seek_info(glob);
641 EbmlLoc trackStart;
642 glob->track_pos = ftello(glob->stream);
643 Ebml_StartSubElement(glob, &trackStart, Tracks);
645 unsigned int trackNumber = 1;
646 uint64_t trackID = 0;
648 EbmlLoc start;
649 Ebml_StartSubElement(glob, &start, TrackEntry);
650 Ebml_SerializeUnsigned(glob, TrackNumber, trackNumber);
651 glob->track_id_pos = ftello(glob->stream);
652 Ebml_SerializeUnsigned32(glob, TrackUID, trackID);
653 Ebml_SerializeUnsigned(glob, TrackType, 1); //video is always 1
654 Ebml_SerializeString(glob, CodecID, "V_VP8");
656 unsigned int pixelWidth = cfg->g_w;
657 unsigned int pixelHeight = cfg->g_h;
658 float frameRate = (float)fps->num/(float)fps->den;
660 EbmlLoc videoStart;
661 Ebml_StartSubElement(glob, &videoStart, Video);
662 Ebml_SerializeUnsigned(glob, PixelWidth, pixelWidth);
663 Ebml_SerializeUnsigned(glob, PixelHeight, pixelHeight);
664 Ebml_SerializeUnsigned(glob, StereoMode, stereo_fmt);
665 Ebml_SerializeFloat(glob, FrameRate, frameRate);
666 Ebml_EndSubElement(glob, &videoStart); //Video
668 Ebml_EndSubElement(glob, &start); //Track Entry
670 Ebml_EndSubElement(glob, &trackStart);
672 // segment element is open
677 static void
678 write_webm_block(EbmlGlobal *glob,
679 const vpx_codec_enc_cfg_t *cfg,
680 const vpx_codec_cx_pkt_t *pkt)
682 unsigned long block_length;
683 unsigned char track_number;
684 unsigned short block_timecode = 0;
685 unsigned char flags;
686 int64_t pts_ms;
687 int start_cluster = 0, is_keyframe;
689 /* Calculate the PTS of this frame in milliseconds */
690 pts_ms = pkt->data.frame.pts * 1000
691 * (uint64_t)cfg->g_timebase.num / (uint64_t)cfg->g_timebase.den;
692 if(pts_ms <= glob->last_pts_ms)
693 pts_ms = glob->last_pts_ms + 1;
694 glob->last_pts_ms = pts_ms;
696 /* Calculate the relative time of this block */
697 if(pts_ms - glob->cluster_timecode > SHRT_MAX)
698 start_cluster = 1;
699 else
700 block_timecode = pts_ms - glob->cluster_timecode;
702 is_keyframe = (pkt->data.frame.flags & VPX_FRAME_IS_KEY);
703 if(start_cluster || is_keyframe)
705 if(glob->cluster_open)
706 Ebml_EndSubElement(glob, &glob->startCluster);
708 /* Open the new cluster */
709 block_timecode = 0;
710 glob->cluster_open = 1;
711 glob->cluster_timecode = pts_ms;
712 glob->cluster_pos = ftello(glob->stream);
713 Ebml_StartSubElement(glob, &glob->startCluster, Cluster); //cluster
714 Ebml_SerializeUnsigned(glob, Timecode, glob->cluster_timecode);
716 /* Save a cue point if this is a keyframe. */
717 if(is_keyframe)
719 struct cue_entry *cue, *new_cue_list;
721 new_cue_list = realloc(glob->cue_list,
722 (glob->cues+1) * sizeof(struct cue_entry));
723 if(new_cue_list)
724 glob->cue_list = new_cue_list;
725 else
727 fprintf(stderr, "\nFailed to realloc cue list.\n");
728 exit(EXIT_FAILURE);
731 cue = &glob->cue_list[glob->cues];
732 cue->time = glob->cluster_timecode;
733 cue->loc = glob->cluster_pos;
734 glob->cues++;
738 /* Write the Simple Block */
739 Ebml_WriteID(glob, SimpleBlock);
741 block_length = pkt->data.frame.sz + 4;
742 block_length |= 0x10000000;
743 Ebml_Serialize(glob, &block_length, 4);
745 track_number = 1;
746 track_number |= 0x80;
747 Ebml_Write(glob, &track_number, 1);
749 Ebml_Serialize(glob, &block_timecode, 2);
751 flags = 0;
752 if(is_keyframe)
753 flags |= 0x80;
754 if(pkt->data.frame.flags & VPX_FRAME_IS_INVISIBLE)
755 flags |= 0x08;
756 Ebml_Write(glob, &flags, 1);
758 Ebml_Write(glob, pkt->data.frame.buf, pkt->data.frame.sz);
762 static void
763 write_webm_file_footer(EbmlGlobal *glob, long hash)
766 if(glob->cluster_open)
767 Ebml_EndSubElement(glob, &glob->startCluster);
770 EbmlLoc start;
771 int i;
773 glob->cue_pos = ftello(glob->stream);
774 Ebml_StartSubElement(glob, &start, Cues);
775 for(i=0; i<glob->cues; i++)
777 struct cue_entry *cue = &glob->cue_list[i];
778 EbmlLoc start;
780 Ebml_StartSubElement(glob, &start, CuePoint);
782 EbmlLoc start;
784 Ebml_SerializeUnsigned(glob, CueTime, cue->time);
786 Ebml_StartSubElement(glob, &start, CueTrackPositions);
787 Ebml_SerializeUnsigned(glob, CueTrack, 1);
788 Ebml_SerializeUnsigned64(glob, CueClusterPosition,
789 cue->loc - glob->position_reference);
790 //Ebml_SerializeUnsigned(glob, CueBlockNumber, cue->blockNumber);
791 Ebml_EndSubElement(glob, &start);
793 Ebml_EndSubElement(glob, &start);
795 Ebml_EndSubElement(glob, &start);
798 Ebml_EndSubElement(glob, &glob->startSegment);
800 /* Patch up the seek info block */
801 write_webm_seek_info(glob);
803 /* Patch up the track id */
804 fseeko(glob->stream, glob->track_id_pos, SEEK_SET);
805 Ebml_SerializeUnsigned32(glob, TrackUID, glob->debug ? 0xDEADBEEF : hash);
807 fseeko(glob->stream, 0, SEEK_END);
811 /* Murmur hash derived from public domain reference implementation at
812 * http://sites.google.com/site/murmurhash/
814 static unsigned int murmur ( const void * key, int len, unsigned int seed )
816 const unsigned int m = 0x5bd1e995;
817 const int r = 24;
819 unsigned int h = seed ^ len;
821 const unsigned char * data = (const unsigned char *)key;
823 while(len >= 4)
825 unsigned int k;
827 k = data[0];
828 k |= data[1] << 8;
829 k |= data[2] << 16;
830 k |= data[3] << 24;
832 k *= m;
833 k ^= k >> r;
834 k *= m;
836 h *= m;
837 h ^= k;
839 data += 4;
840 len -= 4;
843 switch(len)
845 case 3: h ^= data[2] << 16;
846 case 2: h ^= data[1] << 8;
847 case 1: h ^= data[0];
848 h *= m;
851 h ^= h >> 13;
852 h *= m;
853 h ^= h >> 15;
855 return h;
858 #include "math.h"
860 static double vp8_mse2psnr(double Samples, double Peak, double Mse)
862 double psnr;
864 if ((double)Mse > 0.0)
865 psnr = 10.0 * log10(Peak * Peak * Samples / Mse);
866 else
867 psnr = 60; // Limit to prevent / 0
869 if (psnr > 60)
870 psnr = 60;
872 return psnr;
876 #include "args.h"
878 static const arg_def_t debugmode = ARG_DEF("D", "debug", 0,
879 "Debug mode (makes output deterministic)");
880 static const arg_def_t outputfile = ARG_DEF("o", "output", 1,
881 "Output filename");
882 static const arg_def_t use_yv12 = ARG_DEF(NULL, "yv12", 0,
883 "Input file is YV12 ");
884 static const arg_def_t use_i420 = ARG_DEF(NULL, "i420", 0,
885 "Input file is I420 (default)");
886 static const arg_def_t codecarg = ARG_DEF(NULL, "codec", 1,
887 "Codec to use");
888 static const arg_def_t passes = ARG_DEF("p", "passes", 1,
889 "Number of passes (1/2)");
890 static const arg_def_t pass_arg = ARG_DEF(NULL, "pass", 1,
891 "Pass to execute (1/2)");
892 static const arg_def_t fpf_name = ARG_DEF(NULL, "fpf", 1,
893 "First pass statistics file name");
894 static const arg_def_t limit = ARG_DEF(NULL, "limit", 1,
895 "Stop encoding after n input frames");
896 static const arg_def_t deadline = ARG_DEF("d", "deadline", 1,
897 "Deadline per frame (usec)");
898 static const arg_def_t best_dl = ARG_DEF(NULL, "best", 0,
899 "Use Best Quality Deadline");
900 static const arg_def_t good_dl = ARG_DEF(NULL, "good", 0,
901 "Use Good Quality Deadline");
902 static const arg_def_t rt_dl = ARG_DEF(NULL, "rt", 0,
903 "Use Realtime Quality Deadline");
904 static const arg_def_t verbosearg = ARG_DEF("v", "verbose", 0,
905 "Show encoder parameters");
906 static const arg_def_t psnrarg = ARG_DEF(NULL, "psnr", 0,
907 "Show PSNR in status line");
908 static const arg_def_t framerate = ARG_DEF(NULL, "fps", 1,
909 "Stream frame rate (rate/scale)");
910 static const arg_def_t use_ivf = ARG_DEF(NULL, "ivf", 0,
911 "Output IVF (default is WebM)");
912 static const arg_def_t *main_args[] =
914 &debugmode,
915 &outputfile, &codecarg, &passes, &pass_arg, &fpf_name, &limit, &deadline,
916 &best_dl, &good_dl, &rt_dl,
917 &verbosearg, &psnrarg, &use_ivf,
918 NULL
921 static const arg_def_t usage = ARG_DEF("u", "usage", 1,
922 "Usage profile number to use");
923 static const arg_def_t threads = ARG_DEF("t", "threads", 1,
924 "Max number of threads to use");
925 static const arg_def_t profile = ARG_DEF(NULL, "profile", 1,
926 "Bitstream profile number to use");
927 static const arg_def_t width = ARG_DEF("w", "width", 1,
928 "Frame width");
929 static const arg_def_t height = ARG_DEF("h", "height", 1,
930 "Frame height");
931 static const struct arg_enum_list stereo_mode_enum[] = {
932 {"mono" , STEREO_FORMAT_MONO},
933 {"left-right", STEREO_FORMAT_LEFT_RIGHT},
934 {"bottom-top", STEREO_FORMAT_BOTTOM_TOP},
935 {"top-bottom", STEREO_FORMAT_TOP_BOTTOM},
936 {"right-left", STEREO_FORMAT_RIGHT_LEFT},
937 {NULL, 0}
939 static const arg_def_t stereo_mode = ARG_DEF_ENUM(NULL, "stereo-mode", 1,
940 "Stereo 3D video format", stereo_mode_enum);
941 static const arg_def_t timebase = ARG_DEF(NULL, "timebase", 1,
942 "Stream timebase (frame duration)");
943 static const arg_def_t error_resilient = ARG_DEF(NULL, "error-resilient", 1,
944 "Enable error resiliency features");
945 static const arg_def_t lag_in_frames = ARG_DEF(NULL, "lag-in-frames", 1,
946 "Max number of frames to lag");
948 static const arg_def_t *global_args[] =
950 &use_yv12, &use_i420, &usage, &threads, &profile,
951 &width, &height, &stereo_mode, &timebase, &framerate, &error_resilient,
952 &lag_in_frames, NULL
955 static const arg_def_t dropframe_thresh = ARG_DEF(NULL, "drop-frame", 1,
956 "Temporal resampling threshold (buf %)");
957 static const arg_def_t resize_allowed = ARG_DEF(NULL, "resize-allowed", 1,
958 "Spatial resampling enabled (bool)");
959 static const arg_def_t resize_up_thresh = ARG_DEF(NULL, "resize-up", 1,
960 "Upscale threshold (buf %)");
961 static const arg_def_t resize_down_thresh = ARG_DEF(NULL, "resize-down", 1,
962 "Downscale threshold (buf %)");
963 static const struct arg_enum_list end_usage_enum[] = {
964 {"vbr", VPX_VBR},
965 {"cbr", VPX_CBR},
966 {"cq", VPX_CQ},
967 {NULL, 0}
969 static const arg_def_t end_usage = ARG_DEF_ENUM(NULL, "end-usage", 1,
970 "Rate control mode", end_usage_enum);
971 static const arg_def_t target_bitrate = ARG_DEF(NULL, "target-bitrate", 1,
972 "Bitrate (kbps)");
973 static const arg_def_t min_quantizer = ARG_DEF(NULL, "min-q", 1,
974 "Minimum (best) quantizer");
975 static const arg_def_t max_quantizer = ARG_DEF(NULL, "max-q", 1,
976 "Maximum (worst) quantizer");
977 static const arg_def_t undershoot_pct = ARG_DEF(NULL, "undershoot-pct", 1,
978 "Datarate undershoot (min) target (%)");
979 static const arg_def_t overshoot_pct = ARG_DEF(NULL, "overshoot-pct", 1,
980 "Datarate overshoot (max) target (%)");
981 static const arg_def_t buf_sz = ARG_DEF(NULL, "buf-sz", 1,
982 "Client buffer size (ms)");
983 static const arg_def_t buf_initial_sz = ARG_DEF(NULL, "buf-initial-sz", 1,
984 "Client initial buffer size (ms)");
985 static const arg_def_t buf_optimal_sz = ARG_DEF(NULL, "buf-optimal-sz", 1,
986 "Client optimal buffer size (ms)");
987 static const arg_def_t max_intra_rate_pct = ARG_DEF(NULL, "max-intra-rate", 1,
988 "Max I-frame bitrate (pct)");
989 static const arg_def_t *rc_args[] =
991 &dropframe_thresh, &resize_allowed, &resize_up_thresh, &resize_down_thresh,
992 &end_usage, &target_bitrate, &min_quantizer, &max_quantizer,
993 &undershoot_pct, &overshoot_pct, &buf_sz, &buf_initial_sz, &buf_optimal_sz,
994 &max_intra_rate_pct,
995 NULL
999 static const arg_def_t bias_pct = ARG_DEF(NULL, "bias-pct", 1,
1000 "CBR/VBR bias (0=CBR, 100=VBR)");
1001 static const arg_def_t minsection_pct = ARG_DEF(NULL, "minsection-pct", 1,
1002 "GOP min bitrate (% of target)");
1003 static const arg_def_t maxsection_pct = ARG_DEF(NULL, "maxsection-pct", 1,
1004 "GOP max bitrate (% of target)");
1005 static const arg_def_t *rc_twopass_args[] =
1007 &bias_pct, &minsection_pct, &maxsection_pct, NULL
1011 static const arg_def_t kf_min_dist = ARG_DEF(NULL, "kf-min-dist", 1,
1012 "Minimum keyframe interval (frames)");
1013 static const arg_def_t kf_max_dist = ARG_DEF(NULL, "kf-max-dist", 1,
1014 "Maximum keyframe interval (frames)");
1015 static const arg_def_t kf_disabled = ARG_DEF(NULL, "disable-kf", 0,
1016 "Disable keyframe placement");
1017 static const arg_def_t *kf_args[] =
1019 &kf_min_dist, &kf_max_dist, &kf_disabled, NULL
1023 #if CONFIG_VP8_ENCODER
1024 static const arg_def_t noise_sens = ARG_DEF(NULL, "noise-sensitivity", 1,
1025 "Noise sensitivity (frames to blur)");
1026 static const arg_def_t sharpness = ARG_DEF(NULL, "sharpness", 1,
1027 "Filter sharpness (0-7)");
1028 static const arg_def_t static_thresh = ARG_DEF(NULL, "static-thresh", 1,
1029 "Motion detection threshold");
1030 #endif
1032 #if CONFIG_VP8_ENCODER
1033 static const arg_def_t cpu_used = ARG_DEF(NULL, "cpu-used", 1,
1034 "CPU Used (-16..16)");
1035 #endif
1038 #if CONFIG_VP8_ENCODER
1039 static const arg_def_t token_parts = ARG_DEF(NULL, "token-parts", 1,
1040 "Number of token partitions to use, log2");
1041 static const arg_def_t auto_altref = ARG_DEF(NULL, "auto-alt-ref", 1,
1042 "Enable automatic alt reference frames");
1043 static const arg_def_t arnr_maxframes = ARG_DEF(NULL, "arnr-maxframes", 1,
1044 "AltRef Max Frames");
1045 static const arg_def_t arnr_strength = ARG_DEF(NULL, "arnr-strength", 1,
1046 "AltRef Strength");
1047 static const arg_def_t arnr_type = ARG_DEF(NULL, "arnr-type", 1,
1048 "AltRef Type");
1049 static const struct arg_enum_list tuning_enum[] = {
1050 {"psnr", VP8_TUNE_PSNR},
1051 {"ssim", VP8_TUNE_SSIM},
1052 {NULL, 0}
1054 static const arg_def_t tune_ssim = ARG_DEF_ENUM(NULL, "tune", 1,
1055 "Material to favor", tuning_enum);
1056 static const arg_def_t cq_level = ARG_DEF(NULL, "cq-level", 1,
1057 "Constrained Quality Level");
1059 static const arg_def_t *vp8_args[] =
1061 &cpu_used, &auto_altref, &noise_sens, &sharpness, &static_thresh,
1062 &token_parts, &arnr_maxframes, &arnr_strength, &arnr_type,
1063 &tune_ssim, &cq_level, NULL
1065 static const int vp8_arg_ctrl_map[] =
1067 VP8E_SET_CPUUSED, VP8E_SET_ENABLEAUTOALTREF,
1068 VP8E_SET_NOISE_SENSITIVITY, VP8E_SET_SHARPNESS, VP8E_SET_STATIC_THRESHOLD,
1069 VP8E_SET_TOKEN_PARTITIONS,
1070 VP8E_SET_ARNR_MAXFRAMES, VP8E_SET_ARNR_STRENGTH , VP8E_SET_ARNR_TYPE,
1071 VP8E_SET_TUNING, VP8E_SET_CQ_LEVEL, 0
1073 #endif
1075 static const arg_def_t *no_args[] = { NULL };
1077 static void usage_exit()
1079 int i;
1081 fprintf(stderr, "Usage: %s <options> -o dst_filename src_filename \n",
1082 exec_name);
1084 fprintf(stderr, "\nOptions:\n");
1085 arg_show_usage(stdout, main_args);
1086 fprintf(stderr, "\nEncoder Global Options:\n");
1087 arg_show_usage(stdout, global_args);
1088 fprintf(stderr, "\nRate Control Options:\n");
1089 arg_show_usage(stdout, rc_args);
1090 fprintf(stderr, "\nTwopass Rate Control Options:\n");
1091 arg_show_usage(stdout, rc_twopass_args);
1092 fprintf(stderr, "\nKeyframe Placement Options:\n");
1093 arg_show_usage(stdout, kf_args);
1094 #if CONFIG_VP8_ENCODER
1095 fprintf(stderr, "\nVP8 Specific Options:\n");
1096 arg_show_usage(stdout, vp8_args);
1097 #endif
1098 fprintf(stderr, "\n"
1099 "Included encoders:\n"
1100 "\n");
1102 for (i = 0; i < sizeof(codecs) / sizeof(codecs[0]); i++)
1103 fprintf(stderr, " %-6s - %s\n",
1104 codecs[i].name,
1105 vpx_codec_iface_name(codecs[i].iface));
1107 exit(EXIT_FAILURE);
1110 #define ARG_CTRL_CNT_MAX 10
1112 int main(int argc, const char **argv_)
1114 vpx_codec_ctx_t encoder;
1115 const char *in_fn = NULL, *out_fn = NULL, *stats_fn = NULL;
1116 int i;
1117 FILE *infile, *outfile;
1118 vpx_codec_enc_cfg_t cfg;
1119 vpx_codec_err_t res;
1120 int pass, one_pass_only = 0;
1121 stats_io_t stats;
1122 vpx_image_t raw;
1123 const struct codec_item *codec = codecs;
1124 int frame_avail, got_data;
1126 struct arg arg;
1127 char **argv, **argi, **argj;
1128 int arg_usage = 0, arg_passes = 1, arg_deadline = 0;
1129 int arg_ctrls[ARG_CTRL_CNT_MAX][2], arg_ctrl_cnt = 0;
1130 int arg_limit = 0;
1131 static const arg_def_t **ctrl_args = no_args;
1132 static const int *ctrl_args_map = NULL;
1133 int verbose = 0, show_psnr = 0;
1134 int arg_use_i420 = 1;
1135 unsigned long cx_time = 0;
1136 unsigned int file_type, fourcc;
1137 y4m_input y4m;
1138 struct vpx_rational arg_framerate = {30, 1};
1139 int arg_have_framerate = 0;
1140 int write_webm = 1;
1141 EbmlGlobal ebml = {0};
1142 uint32_t hash = 0;
1143 uint64_t psnr_sse_total = 0;
1144 uint64_t psnr_samples_total = 0;
1145 double psnr_totals[4] = {0, 0, 0, 0};
1146 int psnr_count = 0;
1147 stereo_format_t stereo_fmt = STEREO_FORMAT_MONO;
1149 exec_name = argv_[0];
1150 ebml.last_pts_ms = -1;
1152 if (argc < 3)
1153 usage_exit();
1156 /* First parse the codec and usage values, because we want to apply other
1157 * parameters on top of the default configuration provided by the codec.
1159 argv = argv_dup(argc - 1, argv_ + 1);
1161 for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step)
1163 arg.argv_step = 1;
1165 if (arg_match(&arg, &codecarg, argi))
1167 int j, k = -1;
1169 for (j = 0; j < sizeof(codecs) / sizeof(codecs[0]); j++)
1170 if (!strcmp(codecs[j].name, arg.val))
1171 k = j;
1173 if (k >= 0)
1174 codec = codecs + k;
1175 else
1176 die("Error: Unrecognized argument (%s) to --codec\n",
1177 arg.val);
1180 else if (arg_match(&arg, &passes, argi))
1182 arg_passes = arg_parse_uint(&arg);
1184 if (arg_passes < 1 || arg_passes > 2)
1185 die("Error: Invalid number of passes (%d)\n", arg_passes);
1187 else if (arg_match(&arg, &pass_arg, argi))
1189 one_pass_only = arg_parse_uint(&arg);
1191 if (one_pass_only < 1 || one_pass_only > 2)
1192 die("Error: Invalid pass selected (%d)\n", one_pass_only);
1194 else if (arg_match(&arg, &fpf_name, argi))
1195 stats_fn = arg.val;
1196 else if (arg_match(&arg, &usage, argi))
1197 arg_usage = arg_parse_uint(&arg);
1198 else if (arg_match(&arg, &deadline, argi))
1199 arg_deadline = arg_parse_uint(&arg);
1200 else if (arg_match(&arg, &best_dl, argi))
1201 arg_deadline = VPX_DL_BEST_QUALITY;
1202 else if (arg_match(&arg, &good_dl, argi))
1203 arg_deadline = VPX_DL_GOOD_QUALITY;
1204 else if (arg_match(&arg, &rt_dl, argi))
1205 arg_deadline = VPX_DL_REALTIME;
1206 else if (arg_match(&arg, &use_yv12, argi))
1208 arg_use_i420 = 0;
1210 else if (arg_match(&arg, &use_i420, argi))
1212 arg_use_i420 = 1;
1214 else if (arg_match(&arg, &verbosearg, argi))
1215 verbose = 1;
1216 else if (arg_match(&arg, &limit, argi))
1217 arg_limit = arg_parse_uint(&arg);
1218 else if (arg_match(&arg, &psnrarg, argi))
1219 show_psnr = 1;
1220 else if (arg_match(&arg, &framerate, argi))
1222 arg_framerate = arg_parse_rational(&arg);
1223 arg_have_framerate = 1;
1225 else if (arg_match(&arg, &use_ivf, argi))
1226 write_webm = 0;
1227 else if (arg_match(&arg, &outputfile, argi))
1228 out_fn = arg.val;
1229 else if (arg_match(&arg, &debugmode, argi))
1230 ebml.debug = 1;
1231 else
1232 argj++;
1235 /* Ensure that --passes and --pass are consistent. If --pass is set and --passes=2,
1236 * ensure --fpf was set.
1238 if (one_pass_only)
1240 /* DWIM: Assume the user meant passes=2 if pass=2 is specified */
1241 if (one_pass_only > arg_passes)
1243 fprintf(stderr, "Warning: Assuming --pass=%d implies --passes=%d\n",
1244 one_pass_only, one_pass_only);
1245 arg_passes = one_pass_only;
1248 if (arg_passes == 2 && !stats_fn)
1249 die("Must specify --fpf when --pass=%d and --passes=2\n", one_pass_only);
1252 /* Populate encoder configuration */
1253 res = vpx_codec_enc_config_default(codec->iface, &cfg, arg_usage);
1255 if (res)
1257 fprintf(stderr, "Failed to get config: %s\n",
1258 vpx_codec_err_to_string(res));
1259 return EXIT_FAILURE;
1262 /* Change the default timebase to a high enough value so that the encoder
1263 * will always create strictly increasing timestamps.
1265 cfg.g_timebase.den = 1000;
1267 /* Never use the library's default resolution, require it be parsed
1268 * from the file or set on the command line.
1270 cfg.g_w = 0;
1271 cfg.g_h = 0;
1273 /* Now parse the remainder of the parameters. */
1274 for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step)
1276 arg.argv_step = 1;
1278 if (0);
1279 else if (arg_match(&arg, &threads, argi))
1280 cfg.g_threads = arg_parse_uint(&arg);
1281 else if (arg_match(&arg, &profile, argi))
1282 cfg.g_profile = arg_parse_uint(&arg);
1283 else if (arg_match(&arg, &width, argi))
1284 cfg.g_w = arg_parse_uint(&arg);
1285 else if (arg_match(&arg, &height, argi))
1286 cfg.g_h = arg_parse_uint(&arg);
1287 else if (arg_match(&arg, &stereo_mode, argi))
1288 stereo_fmt = arg_parse_enum_or_int(&arg);
1289 else if (arg_match(&arg, &timebase, argi))
1290 cfg.g_timebase = arg_parse_rational(&arg);
1291 else if (arg_match(&arg, &error_resilient, argi))
1292 cfg.g_error_resilient = arg_parse_uint(&arg);
1293 else if (arg_match(&arg, &lag_in_frames, argi))
1294 cfg.g_lag_in_frames = arg_parse_uint(&arg);
1295 else if (arg_match(&arg, &dropframe_thresh, argi))
1296 cfg.rc_dropframe_thresh = arg_parse_uint(&arg);
1297 else if (arg_match(&arg, &resize_allowed, argi))
1298 cfg.rc_resize_allowed = arg_parse_uint(&arg);
1299 else if (arg_match(&arg, &resize_up_thresh, argi))
1300 cfg.rc_resize_up_thresh = arg_parse_uint(&arg);
1301 else if (arg_match(&arg, &resize_down_thresh, argi))
1302 cfg.rc_resize_down_thresh = arg_parse_uint(&arg);
1303 else if (arg_match(&arg, &resize_down_thresh, argi))
1304 cfg.rc_resize_down_thresh = arg_parse_uint(&arg);
1305 else if (arg_match(&arg, &end_usage, argi))
1306 cfg.rc_end_usage = arg_parse_enum_or_int(&arg);
1307 else if (arg_match(&arg, &target_bitrate, argi))
1308 cfg.rc_target_bitrate = arg_parse_uint(&arg);
1309 else if (arg_match(&arg, &max_intra_rate_pct, argi))
1310 cfg.rc_max_intra_bitrate_pct = arg_parse_uint(&arg);
1311 else if (arg_match(&arg, &min_quantizer, argi))
1312 cfg.rc_min_quantizer = arg_parse_uint(&arg);
1313 else if (arg_match(&arg, &max_quantizer, argi))
1314 cfg.rc_max_quantizer = arg_parse_uint(&arg);
1315 else if (arg_match(&arg, &undershoot_pct, argi))
1316 cfg.rc_undershoot_pct = arg_parse_uint(&arg);
1317 else if (arg_match(&arg, &overshoot_pct, argi))
1318 cfg.rc_overshoot_pct = arg_parse_uint(&arg);
1319 else if (arg_match(&arg, &buf_sz, argi))
1320 cfg.rc_buf_sz = arg_parse_uint(&arg);
1321 else if (arg_match(&arg, &buf_initial_sz, argi))
1322 cfg.rc_buf_initial_sz = arg_parse_uint(&arg);
1323 else if (arg_match(&arg, &buf_optimal_sz, argi))
1324 cfg.rc_buf_optimal_sz = arg_parse_uint(&arg);
1325 else if (arg_match(&arg, &bias_pct, argi))
1327 cfg.rc_2pass_vbr_bias_pct = arg_parse_uint(&arg);
1329 if (arg_passes < 2)
1330 fprintf(stderr,
1331 "Warning: option %s ignored in one-pass mode.\n",
1332 arg.name);
1334 else if (arg_match(&arg, &minsection_pct, argi))
1336 cfg.rc_2pass_vbr_minsection_pct = arg_parse_uint(&arg);
1338 if (arg_passes < 2)
1339 fprintf(stderr,
1340 "Warning: option %s ignored in one-pass mode.\n",
1341 arg.name);
1343 else if (arg_match(&arg, &maxsection_pct, argi))
1345 cfg.rc_2pass_vbr_maxsection_pct = arg_parse_uint(&arg);
1347 if (arg_passes < 2)
1348 fprintf(stderr,
1349 "Warning: option %s ignored in one-pass mode.\n",
1350 arg.name);
1352 else if (arg_match(&arg, &kf_min_dist, argi))
1353 cfg.kf_min_dist = arg_parse_uint(&arg);
1354 else if (arg_match(&arg, &kf_max_dist, argi))
1355 cfg.kf_max_dist = arg_parse_uint(&arg);
1356 else if (arg_match(&arg, &kf_disabled, argi))
1357 cfg.kf_mode = VPX_KF_DISABLED;
1358 else
1359 argj++;
1362 /* Handle codec specific options */
1363 #if CONFIG_VP8_ENCODER
1365 if (codec->iface == &vpx_codec_vp8_cx_algo)
1367 ctrl_args = vp8_args;
1368 ctrl_args_map = vp8_arg_ctrl_map;
1371 #endif
1373 for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step)
1375 int match = 0;
1377 arg.argv_step = 1;
1379 for (i = 0; ctrl_args[i]; i++)
1381 if (arg_match(&arg, ctrl_args[i], argi))
1383 match = 1;
1385 if (arg_ctrl_cnt < ARG_CTRL_CNT_MAX)
1387 arg_ctrls[arg_ctrl_cnt][0] = ctrl_args_map[i];
1388 arg_ctrls[arg_ctrl_cnt][1] = arg_parse_enum_or_int(&arg);
1389 arg_ctrl_cnt++;
1394 if (!match)
1395 argj++;
1398 /* Check for unrecognized options */
1399 for (argi = argv; *argi; argi++)
1400 if (argi[0][0] == '-' && argi[0][1])
1401 die("Error: Unrecognized option %s\n", *argi);
1403 /* Handle non-option arguments */
1404 in_fn = argv[0];
1406 if (!in_fn)
1407 usage_exit();
1409 if(!out_fn)
1410 die("Error: Output file is required (specify with -o)\n");
1412 memset(&stats, 0, sizeof(stats));
1414 for (pass = one_pass_only ? one_pass_only - 1 : 0; pass < arg_passes; pass++)
1416 int frames_in = 0, frames_out = 0;
1417 unsigned long nbytes = 0;
1418 struct detect_buffer detect;
1420 /* Parse certain options from the input file, if possible */
1421 infile = strcmp(in_fn, "-") ? fopen(in_fn, "rb")
1422 : set_binary_mode(stdin);
1424 if (!infile)
1426 fprintf(stderr, "Failed to open input file\n");
1427 return EXIT_FAILURE;
1430 /* For RAW input sources, these bytes will applied on the first frame
1431 * in read_frame().
1433 detect.buf_read = fread(detect.buf, 1, 4, infile);
1434 detect.position = 0;
1436 if (detect.buf_read == 4 && file_is_y4m(infile, &y4m, detect.buf))
1438 if (y4m_input_open(&y4m, infile, detect.buf, 4) >= 0)
1440 file_type = FILE_TYPE_Y4M;
1441 cfg.g_w = y4m.pic_w;
1442 cfg.g_h = y4m.pic_h;
1444 /* Use the frame rate from the file only if none was specified
1445 * on the command-line.
1447 if (!arg_have_framerate)
1449 arg_framerate.num = y4m.fps_n;
1450 arg_framerate.den = y4m.fps_d;
1453 arg_use_i420 = 0;
1455 else
1457 fprintf(stderr, "Unsupported Y4M stream.\n");
1458 return EXIT_FAILURE;
1461 else if (detect.buf_read == 4 &&
1462 file_is_ivf(infile, &fourcc, &cfg.g_w, &cfg.g_h, &detect))
1464 file_type = FILE_TYPE_IVF;
1465 switch (fourcc)
1467 case 0x32315659:
1468 arg_use_i420 = 0;
1469 break;
1470 case 0x30323449:
1471 arg_use_i420 = 1;
1472 break;
1473 default:
1474 fprintf(stderr, "Unsupported fourcc (%08x) in IVF\n", fourcc);
1475 return EXIT_FAILURE;
1478 else
1480 file_type = FILE_TYPE_RAW;
1483 if(!cfg.g_w || !cfg.g_h)
1485 fprintf(stderr, "Specify stream dimensions with --width (-w) "
1486 " and --height (-h).\n");
1487 return EXIT_FAILURE;
1490 #define SHOW(field) fprintf(stderr, " %-28s = %d\n", #field, cfg.field)
1492 if (verbose && pass == 0)
1494 fprintf(stderr, "Codec: %s\n", vpx_codec_iface_name(codec->iface));
1495 fprintf(stderr, "Source file: %s Format: %s\n", in_fn,
1496 arg_use_i420 ? "I420" : "YV12");
1497 fprintf(stderr, "Destination file: %s\n", out_fn);
1498 fprintf(stderr, "Encoder parameters:\n");
1500 SHOW(g_usage);
1501 SHOW(g_threads);
1502 SHOW(g_profile);
1503 SHOW(g_w);
1504 SHOW(g_h);
1505 SHOW(g_timebase.num);
1506 SHOW(g_timebase.den);
1507 SHOW(g_error_resilient);
1508 SHOW(g_pass);
1509 SHOW(g_lag_in_frames);
1510 SHOW(rc_dropframe_thresh);
1511 SHOW(rc_resize_allowed);
1512 SHOW(rc_resize_up_thresh);
1513 SHOW(rc_resize_down_thresh);
1514 SHOW(rc_end_usage);
1515 SHOW(rc_target_bitrate);
1516 SHOW(rc_min_quantizer);
1517 SHOW(rc_max_quantizer);
1518 SHOW(rc_undershoot_pct);
1519 SHOW(rc_overshoot_pct);
1520 SHOW(rc_buf_sz);
1521 SHOW(rc_buf_initial_sz);
1522 SHOW(rc_buf_optimal_sz);
1523 SHOW(rc_2pass_vbr_bias_pct);
1524 SHOW(rc_2pass_vbr_minsection_pct);
1525 SHOW(rc_2pass_vbr_maxsection_pct);
1526 SHOW(kf_mode);
1527 SHOW(kf_min_dist);
1528 SHOW(kf_max_dist);
1531 if(pass == (one_pass_only ? one_pass_only - 1 : 0)) {
1532 if (file_type == FILE_TYPE_Y4M)
1533 /*The Y4M reader does its own allocation.
1534 Just initialize this here to avoid problems if we never read any
1535 frames.*/
1536 memset(&raw, 0, sizeof(raw));
1537 else
1538 vpx_img_alloc(&raw, arg_use_i420 ? VPX_IMG_FMT_I420 : VPX_IMG_FMT_YV12,
1539 cfg.g_w, cfg.g_h, 1);
1542 outfile = strcmp(out_fn, "-") ? fopen(out_fn, "wb")
1543 : set_binary_mode(stdout);
1545 if (!outfile)
1547 fprintf(stderr, "Failed to open output file\n");
1548 return EXIT_FAILURE;
1551 if(write_webm && fseek(outfile, 0, SEEK_CUR))
1553 fprintf(stderr, "WebM output to pipes not supported.\n");
1554 return EXIT_FAILURE;
1557 if (stats_fn)
1559 if (!stats_open_file(&stats, stats_fn, pass))
1561 fprintf(stderr, "Failed to open statistics store\n");
1562 return EXIT_FAILURE;
1565 else
1567 if (!stats_open_mem(&stats, pass))
1569 fprintf(stderr, "Failed to open statistics store\n");
1570 return EXIT_FAILURE;
1574 cfg.g_pass = arg_passes == 2
1575 ? pass ? VPX_RC_LAST_PASS : VPX_RC_FIRST_PASS
1576 : VPX_RC_ONE_PASS;
1577 #if VPX_ENCODER_ABI_VERSION > (1 + VPX_CODEC_ABI_VERSION)
1579 if (pass)
1581 cfg.rc_twopass_stats_in = stats_get(&stats);
1584 #endif
1586 if(write_webm)
1588 ebml.stream = outfile;
1589 write_webm_file_header(&ebml, &cfg, &arg_framerate, stereo_fmt);
1591 else
1592 write_ivf_file_header(outfile, &cfg, codec->fourcc, 0);
1595 /* Construct Encoder Context */
1596 vpx_codec_enc_init(&encoder, codec->iface, &cfg,
1597 show_psnr ? VPX_CODEC_USE_PSNR : 0);
1598 ctx_exit_on_error(&encoder, "Failed to initialize encoder");
1600 /* Note that we bypass the vpx_codec_control wrapper macro because
1601 * we're being clever to store the control IDs in an array. Real
1602 * applications will want to make use of the enumerations directly
1604 for (i = 0; i < arg_ctrl_cnt; i++)
1606 if (vpx_codec_control_(&encoder, arg_ctrls[i][0], arg_ctrls[i][1]))
1607 fprintf(stderr, "Error: Tried to set control %d = %d\n",
1608 arg_ctrls[i][0], arg_ctrls[i][1]);
1610 ctx_exit_on_error(&encoder, "Failed to control codec");
1613 frame_avail = 1;
1614 got_data = 0;
1616 while (frame_avail || got_data)
1618 vpx_codec_iter_t iter = NULL;
1619 const vpx_codec_cx_pkt_t *pkt;
1620 struct vpx_usec_timer timer;
1621 int64_t frame_start, next_frame_start;
1623 if (!arg_limit || frames_in < arg_limit)
1625 frame_avail = read_frame(infile, &raw, file_type, &y4m,
1626 &detect);
1628 if (frame_avail)
1629 frames_in++;
1631 fprintf(stderr,
1632 "\rPass %d/%d frame %4d/%-4d %7ldB \033[K", pass + 1,
1633 arg_passes, frames_in, frames_out, nbytes);
1635 else
1636 frame_avail = 0;
1638 vpx_usec_timer_start(&timer);
1640 frame_start = (cfg.g_timebase.den * (int64_t)(frames_in - 1)
1641 * arg_framerate.den) / cfg.g_timebase.num / arg_framerate.num;
1642 next_frame_start = (cfg.g_timebase.den * (int64_t)(frames_in)
1643 * arg_framerate.den)
1644 / cfg.g_timebase.num / arg_framerate.num;
1645 vpx_codec_encode(&encoder, frame_avail ? &raw : NULL, frame_start,
1646 next_frame_start - frame_start,
1647 0, arg_deadline);
1648 vpx_usec_timer_mark(&timer);
1649 cx_time += vpx_usec_timer_elapsed(&timer);
1650 ctx_exit_on_error(&encoder, "Failed to encode frame");
1651 got_data = 0;
1653 while ((pkt = vpx_codec_get_cx_data(&encoder, &iter)))
1655 got_data = 1;
1657 switch (pkt->kind)
1659 case VPX_CODEC_CX_FRAME_PKT:
1660 frames_out++;
1661 fprintf(stderr, " %6luF",
1662 (unsigned long)pkt->data.frame.sz);
1664 if(write_webm)
1666 /* Update the hash */
1667 if(!ebml.debug)
1668 hash = murmur(pkt->data.frame.buf,
1669 pkt->data.frame.sz, hash);
1671 write_webm_block(&ebml, &cfg, pkt);
1673 else
1675 write_ivf_frame_header(outfile, pkt);
1676 if(fwrite(pkt->data.frame.buf, 1,
1677 pkt->data.frame.sz, outfile));
1679 nbytes += pkt->data.raw.sz;
1680 break;
1681 case VPX_CODEC_STATS_PKT:
1682 frames_out++;
1683 fprintf(stderr, " %6luS",
1684 (unsigned long)pkt->data.twopass_stats.sz);
1685 stats_write(&stats,
1686 pkt->data.twopass_stats.buf,
1687 pkt->data.twopass_stats.sz);
1688 nbytes += pkt->data.raw.sz;
1689 break;
1690 case VPX_CODEC_PSNR_PKT:
1692 if (show_psnr)
1694 int i;
1696 psnr_sse_total += pkt->data.psnr.sse[0];
1697 psnr_samples_total += pkt->data.psnr.samples[0];
1698 for (i = 0; i < 4; i++)
1700 fprintf(stderr, "%.3lf ", pkt->data.psnr.psnr[i]);
1701 psnr_totals[i] += pkt->data.psnr.psnr[i];
1703 psnr_count++;
1706 break;
1707 default:
1708 break;
1712 fflush(stdout);
1715 fprintf(stderr,
1716 "\rPass %d/%d frame %4d/%-4d %7ldB %7ldb/f %7"PRId64"b/s"
1717 " %7lu %s (%.2f fps)\033[K", pass + 1,
1718 arg_passes, frames_in, frames_out, nbytes, nbytes * 8 / frames_in,
1719 nbytes * 8 *(int64_t)arg_framerate.num / arg_framerate.den / frames_in,
1720 cx_time > 9999999 ? cx_time / 1000 : cx_time,
1721 cx_time > 9999999 ? "ms" : "us",
1722 (float)frames_in * 1000000.0 / (float)cx_time);
1724 if ( (show_psnr) && (psnr_count>0) )
1726 int i;
1727 double ovpsnr = vp8_mse2psnr(psnr_samples_total, 255.0,
1728 psnr_sse_total);
1730 fprintf(stderr, "\nPSNR (Overall/Avg/Y/U/V)");
1732 fprintf(stderr, " %.3lf", ovpsnr);
1733 for (i = 0; i < 4; i++)
1735 fprintf(stderr, " %.3lf", psnr_totals[i]/psnr_count);
1739 vpx_codec_destroy(&encoder);
1741 fclose(infile);
1743 if(write_webm)
1745 write_webm_file_footer(&ebml, hash);
1747 else
1749 if (!fseek(outfile, 0, SEEK_SET))
1750 write_ivf_file_header(outfile, &cfg, codec->fourcc, frames_out);
1753 fclose(outfile);
1754 stats_close(&stats, arg_passes-1);
1755 fprintf(stderr, "\n");
1757 if (one_pass_only)
1758 break;
1761 vpx_img_free(&raw);
1762 free(argv);
1763 return EXIT_SUCCESS;