blob: d0f4c23482dd94c3f3332f3a690f39b4bd97d90a [file] [log] [blame]
John Koleszar0ea50ce2010-05-18 11:58:33 -04001/*
John Koleszarc2140b82010-09-09 08:16:39 -04002 * Copyright (c) 2010 The WebM project authors. All Rights Reserved.
John Koleszar0ea50ce2010-05-18 11:58:33 -04003 *
John Koleszar3245d462010-06-10 17:10:12 -04004 * Use of this source code is governed by a BSD-style license
John Koleszar09202d82010-06-04 16:19:40 -04005 * 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
John Koleszar3245d462010-06-10 17:10:12 -04007 * in the file PATENTS. All contributing project authors may
John Koleszar09202d82010-06-04 16:19:40 -04008 * be found in the AUTHORS file in the root of the source tree.
John Koleszar0ea50ce2010-05-18 11:58:33 -04009 */
10
11
12/* This is a simple program that encodes YV12 files and generates ivf
13 * files using the new interface.
14 */
Tero Rintaluoma11a222f2011-01-24 11:21:40 +020015#if defined(_WIN32) || !CONFIG_OS_SUPPORT
John Koleszar1df03142010-05-20 14:44:18 -040016#define USE_POSIX_MMAP 0
17#else
18#define USE_POSIX_MMAP 1
19#endif
John Koleszar0ea50ce2010-05-18 11:58:33 -040020
21#include <stdio.h>
22#include <stdlib.h>
23#include <stdarg.h>
24#include <string.h>
John Koleszardc666302010-10-20 12:05:48 -040025#include <limits.h>
John Koleszarb7492342010-05-24 11:39:59 -040026#include "vpx/vpx_encoder.h"
John Koleszar0ea50ce2010-05-18 11:58:33 -040027#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
John Koleszardc666302010-10-20 12:05:48 -040034#include "vpx_version.h"
John Koleszarb7492342010-05-24 11:39:59 -040035#include "vpx/vp8cx.h"
John Koleszar0ea50ce2010-05-18 11:58:33 -040036#include "vpx_ports/mem_ops.h"
37#include "vpx_ports/vpx_timer.h"
John Koleszarc377bf02010-11-02 09:11:57 -040038#include "tools_common.h"
Timothy B. Terriberry44d89492010-05-26 18:27:51 -040039#include "y4minput.h"
John Koleszardc666302010-10-20 12:05:48 -040040#include "libmkv/EbmlWriter.h"
41#include "libmkv/EbmlIDs.h"
42
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 */
46typedef __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
54
55#if defined(_MSC_VER)
56#define LITERALU64(n) n
57#else
58#define LITERALU64(n) n##LLU
59#endif
John Koleszar0ea50ce2010-05-18 11:58:33 -040060
Tero Rintaluoma11a222f2011-01-24 11:21:40 +020061/* 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
64typedef long off_t;
65#define fseeko fseek
66#define ftello ftell
67#endif
68
John Koleszar0ea50ce2010-05-18 11:58:33 -040069static const char *exec_name;
70
71static const struct codec_item
72{
73 char const *name;
74 const vpx_codec_iface_t *iface;
75 unsigned int fourcc;
76} codecs[] =
77{
78#if CONFIG_VP8_ENCODER
79 {"vp8", &vpx_codec_vp8_cx_algo, 0x30385056},
80#endif
81};
82
83static void usage_exit();
84
85void die(const char *fmt, ...)
86{
87 va_list ap;
88 va_start(ap, fmt);
John Koleszar3245d462010-06-10 17:10:12 -040089 vfprintf(stderr, fmt, ap);
90 fprintf(stderr, "\n");
John Koleszar0ea50ce2010-05-18 11:58:33 -040091 usage_exit();
92}
93
94static void ctx_exit_on_error(vpx_codec_ctx_t *ctx, const char *s)
95{
96 if (ctx->err)
97 {
98 const char *detail = vpx_codec_error_detail(ctx);
99
John Koleszar3245d462010-06-10 17:10:12 -0400100 fprintf(stderr, "%s: %s\n", s, vpx_codec_error(ctx));
John Koleszar0ea50ce2010-05-18 11:58:33 -0400101
102 if (detail)
John Koleszar3245d462010-06-10 17:10:12 -0400103 fprintf(stderr, " %s\n", detail);
John Koleszar0ea50ce2010-05-18 11:58:33 -0400104
105 exit(EXIT_FAILURE);
106 }
107}
108
109/* This structure is used to abstract the different ways of handling
110 * first pass statistics.
111 */
112typedef struct
113{
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;
120
121int stats_open_file(stats_io_t *stats, const char *fpf, int pass)
122{
123 int res;
124
125 stats->pass = pass;
126
127 if (pass == 0)
128 {
129 stats->file = fopen(fpf, "wb");
130 stats->buf.sz = 0;
131 stats->buf.buf = NULL,
132 res = (stats->file != NULL);
133 }
134 else
135 {
136#if 0
137#elif USE_POSIX_MMAP
138 struct stat stat_buf;
139 int fd;
140
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;
150
151 stats->file = fopen(fpf, "rb");
152
153 if (fseek(stats->file, 0, SEEK_END))
154 {
155 fprintf(stderr, "First-pass stats file must be seekable!\n");
156 exit(EXIT_FAILURE);
157 }
158
159 stats->buf.sz = stats->buf_alloc_sz = ftell(stats->file);
160 rewind(stats->file);
161
162 stats->buf.buf = malloc(stats->buf_alloc_sz);
163
164 if (!stats->buf.buf)
165 {
166 fprintf(stderr, "Failed to allocate first-pass stats buffer (%d bytes)\n",
167 stats->buf_alloc_sz);
168 exit(EXIT_FAILURE);
169 }
170
171 nbytes = fread(stats->buf.buf, 1, stats->buf.sz, stats->file);
172 res = (nbytes == stats->buf.sz);
173#endif
174 }
175
176 return res;
177}
178
179int stats_open_mem(stats_io_t *stats, int pass)
180{
181 int res;
182 stats->pass = pass;
183
184 if (!pass)
185 {
186 stats->buf.sz = 0;
187 stats->buf_alloc_sz = 64 * 1024;
188 stats->buf.buf = malloc(stats->buf_alloc_sz);
189 }
190
191 stats->buf_ptr = stats->buf.buf;
192 res = (stats->buf.buf != NULL);
193 return res;
194}
195
196
James Berry74e84462010-12-23 14:47:56 -0500197void stats_close(stats_io_t *stats, int last_pass)
John Koleszar0ea50ce2010-05-18 11:58:33 -0400198{
199 if (stats->file)
200 {
James Berry74e84462010-12-23 14:47:56 -0500201 if (stats->pass == last_pass)
John Koleszar0ea50ce2010-05-18 11:58:33 -0400202 {
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
209 }
210
211 fclose(stats->file);
212 stats->file = NULL;
213 }
214 else
215 {
James Berry74e84462010-12-23 14:47:56 -0500216 if (stats->pass == last_pass)
John Koleszar0ea50ce2010-05-18 11:58:33 -0400217 free(stats->buf.buf);
218 }
219}
220
221void stats_write(stats_io_t *stats, const void *pkt, size_t len)
222{
223 if (stats->file)
224 {
Timothy B. Terriberryc4d7e5e2010-10-27 16:04:02 -0700225 if(fwrite(pkt, 1, len, stats->file));
John Koleszar0ea50ce2010-05-18 11:58:33 -0400226 }
227 else
228 {
229 if (stats->buf.sz + len > stats->buf_alloc_sz)
230 {
231 size_t new_sz = stats->buf_alloc_sz + 64 * 1024;
232 char *new_ptr = realloc(stats->buf.buf, new_sz);
233
234 if (new_ptr)
235 {
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;
239 } /* else ... */
240 }
241
242 memcpy(stats->buf_ptr, pkt, len);
243 stats->buf.sz += len;
244 stats->buf_ptr += len;
245 }
246}
247
248vpx_fixed_buf_t stats_get(stats_io_t *stats)
249{
250 return stats->buf;
251}
252
Timothy B. Terriberry44d89492010-05-26 18:27:51 -0400253enum video_file_type
254{
255 FILE_TYPE_RAW,
256 FILE_TYPE_IVF,
257 FILE_TYPE_Y4M
258};
259
John Koleszar3245d462010-06-10 17:10:12 -0400260struct detect_buffer {
261 char buf[4];
Pascal Massiminofd9f9dc2010-11-24 00:22:59 -0800262 size_t buf_read;
263 size_t position;
John Koleszar3245d462010-06-10 17:10:12 -0400264};
265
266
John Koleszar0ea50ce2010-05-18 11:58:33 -0400267#define IVF_FRAME_HDR_SZ (4+8) /* 4 byte size + 8 byte timestamp */
Timothy B. Terriberry44d89492010-05-26 18:27:51 -0400268static int read_frame(FILE *f, vpx_image_t *img, unsigned int file_type,
John Koleszar3245d462010-06-10 17:10:12 -0400269 y4m_input *y4m, struct detect_buffer *detect)
John Koleszar0ea50ce2010-05-18 11:58:33 -0400270{
271 int plane = 0;
Timothy B. Terriberryc4d7e5e2010-10-27 16:04:02 -0700272 int shortread = 0;
John Koleszar0ea50ce2010-05-18 11:58:33 -0400273
Timothy B. Terriberry44d89492010-05-26 18:27:51 -0400274 if (file_type == FILE_TYPE_Y4M)
John Koleszar0ea50ce2010-05-18 11:58:33 -0400275 {
Timothy B. Terriberryc4d7e5e2010-10-27 16:04:02 -0700276 if (y4m_input_fetch_frame(y4m, f, img) < 1)
Timothy B. Terriberry44d89492010-05-26 18:27:51 -0400277 return 0;
John Koleszar0ea50ce2010-05-18 11:58:33 -0400278 }
Timothy B. Terriberry44d89492010-05-26 18:27:51 -0400279 else
John Koleszar0ea50ce2010-05-18 11:58:33 -0400280 {
Timothy B. Terriberry44d89492010-05-26 18:27:51 -0400281 if (file_type == FILE_TYPE_IVF)
John Koleszar0ea50ce2010-05-18 11:58:33 -0400282 {
Timothy B. Terriberry44d89492010-05-26 18:27:51 -0400283 char junk[IVF_FRAME_HDR_SZ];
284
285 /* Skip the frame header. We know how big the frame should be. See
286 * write_ivf_frame_header() for documentation on the frame header
287 * layout.
288 */
Timothy B. Terriberryc4d7e5e2010-10-27 16:04:02 -0700289 if(fread(junk, 1, IVF_FRAME_HDR_SZ, f));
John Koleszar0ea50ce2010-05-18 11:58:33 -0400290 }
291
Timothy B. Terriberry44d89492010-05-26 18:27:51 -0400292 for (plane = 0; plane < 3; plane++)
John Koleszar0ea50ce2010-05-18 11:58:33 -0400293 {
Timothy B. Terriberry44d89492010-05-26 18:27:51 -0400294 unsigned char *ptr;
295 int w = (plane ? (1 + img->d_w) / 2 : img->d_w);
296 int h = (plane ? (1 + img->d_h) / 2 : img->d_h);
297 int r;
298
299 /* Determine the correct plane based on the image format. The for-loop
300 * always counts in Y,U,V order, but this may not match the order of
301 * the data on disk.
302 */
303 switch (plane)
304 {
305 case 1:
306 ptr = img->planes[img->fmt==VPX_IMG_FMT_YV12? VPX_PLANE_V : VPX_PLANE_U];
307 break;
308 case 2:
309 ptr = img->planes[img->fmt==VPX_IMG_FMT_YV12?VPX_PLANE_U : VPX_PLANE_V];
310 break;
311 default:
312 ptr = img->planes[plane];
313 }
314
315 for (r = 0; r < h; r++)
316 {
Pascal Massiminofd9f9dc2010-11-24 00:22:59 -0800317 size_t needed = w;
318 size_t buf_position = 0;
319 const size_t left = detect->buf_read - detect->position;
320 if (left > 0)
John Koleszar3245d462010-06-10 17:10:12 -0400321 {
Pascal Massiminofd9f9dc2010-11-24 00:22:59 -0800322 const size_t more = (left < needed) ? left : needed;
323 memcpy(ptr, detect->buf + detect->position, more);
324 buf_position = more;
325 needed -= more;
326 detect->position += more;
John Koleszar3245d462010-06-10 17:10:12 -0400327 }
Pascal Massiminofd9f9dc2010-11-24 00:22:59 -0800328 if (needed > 0)
329 {
330 shortread |= (fread(ptr + buf_position, 1, needed, f) < needed);
331 }
John Koleszar3245d462010-06-10 17:10:12 -0400332
Timothy B. Terriberry44d89492010-05-26 18:27:51 -0400333 ptr += img->stride[plane];
334 }
John Koleszar0ea50ce2010-05-18 11:58:33 -0400335 }
336 }
337
Timothy B. Terriberryc4d7e5e2010-10-27 16:04:02 -0700338 return !shortread;
John Koleszar0ea50ce2010-05-18 11:58:33 -0400339}
340
341
Tom Finegane703af92010-06-16 13:24:55 -0400342unsigned int file_is_y4m(FILE *infile,
John Koleszar3245d462010-06-10 17:10:12 -0400343 y4m_input *y4m,
344 char detect[4])
Timothy B. Terriberry44d89492010-05-26 18:27:51 -0400345{
Tom Finegane703af92010-06-16 13:24:55 -0400346 if(memcmp(detect, "YUV4", 4) == 0)
Timothy B. Terriberry44d89492010-05-26 18:27:51 -0400347 {
348 return 1;
349 }
Timothy B. Terriberry44d89492010-05-26 18:27:51 -0400350 return 0;
351}
352
John Koleszar0ea50ce2010-05-18 11:58:33 -0400353#define IVF_FILE_HDR_SZ (32)
354unsigned int file_is_ivf(FILE *infile,
355 unsigned int *fourcc,
356 unsigned int *width,
John Koleszar3245d462010-06-10 17:10:12 -0400357 unsigned int *height,
James Berry136bd242010-12-13 13:10:58 -0500358 struct detect_buffer *detect)
John Koleszar0ea50ce2010-05-18 11:58:33 -0400359{
360 char raw_hdr[IVF_FILE_HDR_SZ];
361 int is_ivf = 0;
362
James Berry136bd242010-12-13 13:10:58 -0500363 if(memcmp(detect->buf, "DKIF", 4) != 0)
John Koleszar3245d462010-06-10 17:10:12 -0400364 return 0;
365
John Koleszar0ea50ce2010-05-18 11:58:33 -0400366 /* See write_ivf_file_header() for more documentation on the file header
367 * layout.
368 */
John Koleszar3245d462010-06-10 17:10:12 -0400369 if (fread(raw_hdr + 4, 1, IVF_FILE_HDR_SZ - 4, infile)
370 == IVF_FILE_HDR_SZ - 4)
John Koleszar0ea50ce2010-05-18 11:58:33 -0400371 {
John Koleszar0ea50ce2010-05-18 11:58:33 -0400372 {
373 is_ivf = 1;
374
375 if (mem_get_le16(raw_hdr + 4) != 0)
376 fprintf(stderr, "Error: Unrecognized IVF version! This file may not"
377 " decode properly.");
378
379 *fourcc = mem_get_le32(raw_hdr + 8);
380 }
381 }
382
383 if (is_ivf)
384 {
385 *width = mem_get_le16(raw_hdr + 12);
386 *height = mem_get_le16(raw_hdr + 14);
James Berry136bd242010-12-13 13:10:58 -0500387 detect->position = 4;
John Koleszar0ea50ce2010-05-18 11:58:33 -0400388 }
John Koleszar0ea50ce2010-05-18 11:58:33 -0400389
390 return is_ivf;
391}
392
393
394static void write_ivf_file_header(FILE *outfile,
395 const vpx_codec_enc_cfg_t *cfg,
396 unsigned int fourcc,
397 int frame_cnt)
398{
399 char header[32];
400
401 if (cfg->g_pass != VPX_RC_ONE_PASS && cfg->g_pass != VPX_RC_LAST_PASS)
402 return;
403
404 header[0] = 'D';
405 header[1] = 'K';
406 header[2] = 'I';
407 header[3] = 'F';
408 mem_put_le16(header + 4, 0); /* version */
409 mem_put_le16(header + 6, 32); /* headersize */
410 mem_put_le32(header + 8, fourcc); /* headersize */
411 mem_put_le16(header + 12, cfg->g_w); /* width */
412 mem_put_le16(header + 14, cfg->g_h); /* height */
413 mem_put_le32(header + 16, cfg->g_timebase.den); /* rate */
414 mem_put_le32(header + 20, cfg->g_timebase.num); /* scale */
415 mem_put_le32(header + 24, frame_cnt); /* length */
416 mem_put_le32(header + 28, 0); /* unused */
417
Timothy B. Terriberryc4d7e5e2010-10-27 16:04:02 -0700418 if(fwrite(header, 1, 32, outfile));
John Koleszar0ea50ce2010-05-18 11:58:33 -0400419}
420
421
422static void write_ivf_frame_header(FILE *outfile,
423 const vpx_codec_cx_pkt_t *pkt)
424{
425 char header[12];
426 vpx_codec_pts_t pts;
427
428 if (pkt->kind != VPX_CODEC_CX_FRAME_PKT)
429 return;
430
431 pts = pkt->data.frame.pts;
432 mem_put_le32(header, pkt->data.frame.sz);
433 mem_put_le32(header + 4, pts & 0xFFFFFFFF);
434 mem_put_le32(header + 8, pts >> 32);
435
Timothy B. Terriberryc4d7e5e2010-10-27 16:04:02 -0700436 if(fwrite(header, 1, 12, outfile));
John Koleszar0ea50ce2010-05-18 11:58:33 -0400437}
438
John Koleszardc666302010-10-20 12:05:48 -0400439
440typedef off_t EbmlLoc;
441
442
443struct cue_entry
444{
445 unsigned int time;
446 uint64_t loc;
447};
448
449
450struct EbmlGlobal
451{
John Koleszar75afcee2010-10-26 16:22:22 -0400452 int debug;
453
John Koleszardc666302010-10-20 12:05:48 -0400454 FILE *stream;
Frank Galligan8c2dfde2010-11-03 23:33:00 -0400455 int64_t last_pts_ms;
John Koleszardc666302010-10-20 12:05:48 -0400456 vpx_rational_t framerate;
457
458 /* These pointers are to the start of an element */
459 off_t position_reference;
460 off_t seek_info_pos;
461 off_t segment_info_pos;
462 off_t track_pos;
463 off_t cue_pos;
464 off_t cluster_pos;
465
John Koleszarc7c0c052010-10-27 10:05:55 -0400466 /* This pointer is to a specific element to be serialized */
467 off_t track_id_pos;
468
John Koleszardc666302010-10-20 12:05:48 -0400469 /* These pointers are to the size field of the element */
470 EbmlLoc startSegment;
471 EbmlLoc startCluster;
472
473 uint32_t cluster_timecode;
474 int cluster_open;
475
476 struct cue_entry *cue_list;
477 unsigned int cues;
478
479};
480
481
482void Ebml_Write(EbmlGlobal *glob, const void *buffer_in, unsigned long len)
483{
Timothy B. Terriberryc4d7e5e2010-10-27 16:04:02 -0700484 if(fwrite(buffer_in, 1, len, glob->stream));
John Koleszardc666302010-10-20 12:05:48 -0400485}
486
487
488void Ebml_Serialize(EbmlGlobal *glob, const void *buffer_in, unsigned long len)
489{
490 const unsigned char *q = (const unsigned char *)buffer_in + len - 1;
491
492 for(; len; len--)
493 Ebml_Write(glob, q--, 1);
494}
495
496
John Koleszarc7c0c052010-10-27 10:05:55 -0400497/* Need a fixed size serializer for the track ID. libmkv provdes a 64 bit
498 * one, but not a 32 bit one.
499 */
500static void Ebml_SerializeUnsigned32(EbmlGlobal *glob, unsigned long class_id, uint64_t ui)
501{
502 unsigned char sizeSerialized = 4 | 0x80;
503 Ebml_WriteID(glob, class_id);
504 Ebml_Serialize(glob, &sizeSerialized, 1);
505 Ebml_Serialize(glob, &ui, 4);
506}
507
508
John Koleszardc666302010-10-20 12:05:48 -0400509static void
510Ebml_StartSubElement(EbmlGlobal *glob, EbmlLoc *ebmlLoc,
511 unsigned long class_id)
512{
513 //todo this is always taking 8 bytes, this may need later optimization
514 //this is a key that says lenght unknown
515 unsigned long long unknownLen = LITERALU64(0x01FFFFFFFFFFFFFF);
516
517 Ebml_WriteID(glob, class_id);
518 *ebmlLoc = ftello(glob->stream);
519 Ebml_Serialize(glob, &unknownLen, 8);
520}
521
522static void
523Ebml_EndSubElement(EbmlGlobal *glob, EbmlLoc *ebmlLoc)
524{
525 off_t pos;
526 uint64_t size;
527
528 /* Save the current stream pointer */
529 pos = ftello(glob->stream);
530
531 /* Calculate the size of this element */
532 size = pos - *ebmlLoc - 8;
533 size |= LITERALU64(0x0100000000000000);
534
535 /* Seek back to the beginning of the element and write the new size */
536 fseeko(glob->stream, *ebmlLoc, SEEK_SET);
537 Ebml_Serialize(glob, &size, 8);
538
539 /* Reset the stream pointer */
540 fseeko(glob->stream, pos, SEEK_SET);
541}
542
543
544static void
545write_webm_seek_element(EbmlGlobal *ebml, unsigned long id, off_t pos)
546{
547 uint64_t offset = pos - ebml->position_reference;
548 EbmlLoc start;
549 Ebml_StartSubElement(ebml, &start, Seek);
550 Ebml_SerializeBinary(ebml, SeekID, id);
551 Ebml_SerializeUnsigned64(ebml, SeekPosition, offset);
552 Ebml_EndSubElement(ebml, &start);
553}
554
555
556static void
557write_webm_seek_info(EbmlGlobal *ebml)
558{
559
560 off_t pos;
561
562 /* Save the current stream pointer */
563 pos = ftello(ebml->stream);
564
565 if(ebml->seek_info_pos)
566 fseeko(ebml->stream, ebml->seek_info_pos, SEEK_SET);
567 else
568 ebml->seek_info_pos = pos;
569
570 {
571 EbmlLoc start;
572
573 Ebml_StartSubElement(ebml, &start, SeekHead);
574 write_webm_seek_element(ebml, Tracks, ebml->track_pos);
575 write_webm_seek_element(ebml, Cues, ebml->cue_pos);
576 write_webm_seek_element(ebml, Info, ebml->segment_info_pos);
577 Ebml_EndSubElement(ebml, &start);
578 }
579 {
580 //segment info
581 EbmlLoc startInfo;
582 uint64_t frame_time;
583
584 frame_time = (uint64_t)1000 * ebml->framerate.den
585 / ebml->framerate.num;
586 ebml->segment_info_pos = ftello(ebml->stream);
587 Ebml_StartSubElement(ebml, &startInfo, Info);
588 Ebml_SerializeUnsigned(ebml, TimecodeScale, 1000000);
589 Ebml_SerializeFloat(ebml, Segment_Duration,
590 ebml->last_pts_ms + frame_time);
John Koleszar75afcee2010-10-26 16:22:22 -0400591 Ebml_SerializeString(ebml, 0x4D80,
592 ebml->debug ? "vpxenc" : "vpxenc" VERSION_STRING);
593 Ebml_SerializeString(ebml, 0x5741,
594 ebml->debug ? "vpxenc" : "vpxenc" VERSION_STRING);
John Koleszardc666302010-10-20 12:05:48 -0400595 Ebml_EndSubElement(ebml, &startInfo);
596 }
597}
598
599
600static void
601write_webm_file_header(EbmlGlobal *glob,
602 const vpx_codec_enc_cfg_t *cfg,
603 const struct vpx_rational *fps)
604{
605 {
606 EbmlLoc start;
607 Ebml_StartSubElement(glob, &start, EBML);
608 Ebml_SerializeUnsigned(glob, EBMLVersion, 1);
609 Ebml_SerializeUnsigned(glob, EBMLReadVersion, 1); //EBML Read Version
610 Ebml_SerializeUnsigned(glob, EBMLMaxIDLength, 4); //EBML Max ID Length
611 Ebml_SerializeUnsigned(glob, EBMLMaxSizeLength, 8); //EBML Max Size Length
612 Ebml_SerializeString(glob, DocType, "webm"); //Doc Type
613 Ebml_SerializeUnsigned(glob, DocTypeVersion, 2); //Doc Type Version
614 Ebml_SerializeUnsigned(glob, DocTypeReadVersion, 2); //Doc Type Read Version
615 Ebml_EndSubElement(glob, &start);
616 }
617 {
618 Ebml_StartSubElement(glob, &glob->startSegment, Segment); //segment
619 glob->position_reference = ftello(glob->stream);
620 glob->framerate = *fps;
621 write_webm_seek_info(glob);
622
623 {
624 EbmlLoc trackStart;
625 glob->track_pos = ftello(glob->stream);
626 Ebml_StartSubElement(glob, &trackStart, Tracks);
627 {
628 unsigned int trackNumber = 1;
629 uint64_t trackID = 0;
630
631 EbmlLoc start;
632 Ebml_StartSubElement(glob, &start, TrackEntry);
633 Ebml_SerializeUnsigned(glob, TrackNumber, trackNumber);
John Koleszarc7c0c052010-10-27 10:05:55 -0400634 glob->track_id_pos = ftello(glob->stream);
635 Ebml_SerializeUnsigned32(glob, TrackUID, trackID);
John Koleszardc666302010-10-20 12:05:48 -0400636 Ebml_SerializeUnsigned(glob, TrackType, 1); //video is always 1
637 Ebml_SerializeString(glob, CodecID, "V_VP8");
638 {
639 unsigned int pixelWidth = cfg->g_w;
640 unsigned int pixelHeight = cfg->g_h;
641 float frameRate = (float)fps->num/(float)fps->den;
642
643 EbmlLoc videoStart;
644 Ebml_StartSubElement(glob, &videoStart, Video);
645 Ebml_SerializeUnsigned(glob, PixelWidth, pixelWidth);
646 Ebml_SerializeUnsigned(glob, PixelHeight, pixelHeight);
647 Ebml_SerializeFloat(glob, FrameRate, frameRate);
648 Ebml_EndSubElement(glob, &videoStart); //Video
649 }
650 Ebml_EndSubElement(glob, &start); //Track Entry
651 }
652 Ebml_EndSubElement(glob, &trackStart);
653 }
654 // segment element is open
655 }
656}
657
658
659static void
660write_webm_block(EbmlGlobal *glob,
661 const vpx_codec_enc_cfg_t *cfg,
662 const vpx_codec_cx_pkt_t *pkt)
663{
664 unsigned long block_length;
665 unsigned char track_number;
666 unsigned short block_timecode = 0;
667 unsigned char flags;
Frank Galligan8c2dfde2010-11-03 23:33:00 -0400668 int64_t pts_ms;
John Koleszardc666302010-10-20 12:05:48 -0400669 int start_cluster = 0, is_keyframe;
670
671 /* Calculate the PTS of this frame in milliseconds */
672 pts_ms = pkt->data.frame.pts * 1000
673 * (uint64_t)cfg->g_timebase.num / (uint64_t)cfg->g_timebase.den;
674 if(pts_ms <= glob->last_pts_ms)
675 pts_ms = glob->last_pts_ms + 1;
676 glob->last_pts_ms = pts_ms;
677
678 /* Calculate the relative time of this block */
679 if(pts_ms - glob->cluster_timecode > SHRT_MAX)
680 start_cluster = 1;
681 else
682 block_timecode = pts_ms - glob->cluster_timecode;
683
684 is_keyframe = (pkt->data.frame.flags & VPX_FRAME_IS_KEY);
685 if(start_cluster || is_keyframe)
686 {
687 if(glob->cluster_open)
688 Ebml_EndSubElement(glob, &glob->startCluster);
689
690 /* Open the new cluster */
691 block_timecode = 0;
692 glob->cluster_open = 1;
693 glob->cluster_timecode = pts_ms;
694 glob->cluster_pos = ftello(glob->stream);
695 Ebml_StartSubElement(glob, &glob->startCluster, Cluster); //cluster
696 Ebml_SerializeUnsigned(glob, Timecode, glob->cluster_timecode);
697
698 /* Save a cue point if this is a keyframe. */
699 if(is_keyframe)
700 {
701 struct cue_entry *cue;
702
703 glob->cue_list = realloc(glob->cue_list,
704 (glob->cues+1) * sizeof(struct cue_entry));
705 cue = &glob->cue_list[glob->cues];
706 cue->time = glob->cluster_timecode;
707 cue->loc = glob->cluster_pos;
708 glob->cues++;
709 }
710 }
711
712 /* Write the Simple Block */
713 Ebml_WriteID(glob, SimpleBlock);
714
715 block_length = pkt->data.frame.sz + 4;
716 block_length |= 0x10000000;
717 Ebml_Serialize(glob, &block_length, 4);
718
719 track_number = 1;
720 track_number |= 0x80;
721 Ebml_Write(glob, &track_number, 1);
722
723 Ebml_Serialize(glob, &block_timecode, 2);
724
725 flags = 0;
726 if(is_keyframe)
727 flags |= 0x80;
728 if(pkt->data.frame.flags & VPX_FRAME_IS_INVISIBLE)
729 flags |= 0x08;
730 Ebml_Write(glob, &flags, 1);
731
732 Ebml_Write(glob, pkt->data.frame.buf, pkt->data.frame.sz);
733}
734
735
736static void
John Koleszarc7c0c052010-10-27 10:05:55 -0400737write_webm_file_footer(EbmlGlobal *glob, long hash)
John Koleszardc666302010-10-20 12:05:48 -0400738{
739
740 if(glob->cluster_open)
741 Ebml_EndSubElement(glob, &glob->startCluster);
742
743 {
744 EbmlLoc start;
745 int i;
746
747 glob->cue_pos = ftello(glob->stream);
748 Ebml_StartSubElement(glob, &start, Cues);
749 for(i=0; i<glob->cues; i++)
750 {
751 struct cue_entry *cue = &glob->cue_list[i];
752 EbmlLoc start;
753
754 Ebml_StartSubElement(glob, &start, CuePoint);
755 {
756 EbmlLoc start;
757
758 Ebml_SerializeUnsigned(glob, CueTime, cue->time);
759
760 Ebml_StartSubElement(glob, &start, CueTrackPositions);
761 Ebml_SerializeUnsigned(glob, CueTrack, 1);
762 Ebml_SerializeUnsigned64(glob, CueClusterPosition,
763 cue->loc - glob->position_reference);
764 //Ebml_SerializeUnsigned(glob, CueBlockNumber, cue->blockNumber);
765 Ebml_EndSubElement(glob, &start);
766 }
767 Ebml_EndSubElement(glob, &start);
768 }
769 Ebml_EndSubElement(glob, &start);
770 }
771
772 Ebml_EndSubElement(glob, &glob->startSegment);
773
774 /* Patch up the seek info block */
775 write_webm_seek_info(glob);
John Koleszarc7c0c052010-10-27 10:05:55 -0400776
777 /* Patch up the track id */
778 fseeko(glob->stream, glob->track_id_pos, SEEK_SET);
779 Ebml_SerializeUnsigned32(glob, TrackUID, glob->debug ? 0xDEADBEEF : hash);
780
John Koleszardc666302010-10-20 12:05:48 -0400781 fseeko(glob->stream, 0, SEEK_END);
782}
783
784
John Koleszarc7c0c052010-10-27 10:05:55 -0400785/* Murmur hash derived from public domain reference implementation at
786 * http://sites.google.com/site/murmurhash/
787 */
788static unsigned int murmur ( const void * key, int len, unsigned int seed )
789{
790 const unsigned int m = 0x5bd1e995;
791 const int r = 24;
792
793 unsigned int h = seed ^ len;
794
795 const unsigned char * data = (const unsigned char *)key;
796
797 while(len >= 4)
798 {
799 unsigned int k;
800
801 k = data[0];
802 k |= data[1] << 8;
803 k |= data[2] << 16;
804 k |= data[3] << 24;
805
806 k *= m;
807 k ^= k >> r;
808 k *= m;
809
810 h *= m;
811 h ^= k;
812
813 data += 4;
814 len -= 4;
815 }
816
817 switch(len)
818 {
819 case 3: h ^= data[2] << 16;
820 case 2: h ^= data[1] << 8;
821 case 1: h ^= data[0];
822 h *= m;
823 };
824
825 h ^= h >> 13;
826 h *= m;
827 h ^= h >> 15;
828
829 return h;
830}
831
Frank Galligan3d84da62010-10-27 11:28:56 -0400832#include "math.h"
833
834static double vp8_mse2psnr(double Samples, double Peak, double Mse)
835{
836 double psnr;
837
838 if ((double)Mse > 0.0)
839 psnr = 10.0 * log10(Peak * Peak * Samples / Mse);
840 else
841 psnr = 60; // Limit to prevent / 0
842
843 if (psnr > 60)
844 psnr = 60;
845
846 return psnr;
847}
848
John Koleszarc7c0c052010-10-27 10:05:55 -0400849
John Koleszar0ea50ce2010-05-18 11:58:33 -0400850#include "args.h"
851
John Koleszar75afcee2010-10-26 16:22:22 -0400852static const arg_def_t debugmode = ARG_DEF("D", "debug", 0,
853 "Debug mode (makes output deterministic)");
John Koleszar53291892010-10-22 14:48:21 -0400854static const arg_def_t outputfile = ARG_DEF("o", "output", 1,
855 "Output filename");
John Koleszar0ea50ce2010-05-18 11:58:33 -0400856static const arg_def_t use_yv12 = ARG_DEF(NULL, "yv12", 0,
857 "Input file is YV12 ");
858static const arg_def_t use_i420 = ARG_DEF(NULL, "i420", 0,
859 "Input file is I420 (default)");
860static const arg_def_t codecarg = ARG_DEF(NULL, "codec", 1,
861 "Codec to use");
862static const arg_def_t passes = ARG_DEF("p", "passes", 1,
863 "Number of passes (1/2)");
864static const arg_def_t pass_arg = ARG_DEF(NULL, "pass", 1,
865 "Pass to execute (1/2)");
866static const arg_def_t fpf_name = ARG_DEF(NULL, "fpf", 1,
867 "First pass statistics file name");
868static const arg_def_t limit = ARG_DEF(NULL, "limit", 1,
869 "Stop encoding after n input frames");
870static const arg_def_t deadline = ARG_DEF("d", "deadline", 1,
871 "Deadline per frame (usec)");
872static const arg_def_t best_dl = ARG_DEF(NULL, "best", 0,
873 "Use Best Quality Deadline");
874static const arg_def_t good_dl = ARG_DEF(NULL, "good", 0,
875 "Use Good Quality Deadline");
876static const arg_def_t rt_dl = ARG_DEF(NULL, "rt", 0,
877 "Use Realtime Quality Deadline");
878static const arg_def_t verbosearg = ARG_DEF("v", "verbose", 0,
879 "Show encoder parameters");
880static const arg_def_t psnrarg = ARG_DEF(NULL, "psnr", 0,
881 "Show PSNR in status line");
John Koleszar28f177c2010-10-21 16:52:14 -0400882static const arg_def_t framerate = ARG_DEF(NULL, "fps", 1,
Frank Galligan1258cf62010-10-06 12:51:00 -0400883 "Stream frame rate (rate/scale)");
John Koleszar456bfb12010-10-21 16:23:20 -0400884static const arg_def_t use_ivf = ARG_DEF(NULL, "ivf", 0,
885 "Output IVF (default is WebM)");
John Koleszar0ea50ce2010-05-18 11:58:33 -0400886static const arg_def_t *main_args[] =
887{
John Koleszar75afcee2010-10-26 16:22:22 -0400888 &debugmode,
John Koleszar53291892010-10-22 14:48:21 -0400889 &outputfile, &codecarg, &passes, &pass_arg, &fpf_name, &limit, &deadline,
890 &best_dl, &good_dl, &rt_dl,
John Koleszar456bfb12010-10-21 16:23:20 -0400891 &verbosearg, &psnrarg, &use_ivf, &framerate,
John Koleszar0ea50ce2010-05-18 11:58:33 -0400892 NULL
893};
894
895static const arg_def_t usage = ARG_DEF("u", "usage", 1,
896 "Usage profile number to use");
897static const arg_def_t threads = ARG_DEF("t", "threads", 1,
898 "Max number of threads to use");
899static const arg_def_t profile = ARG_DEF(NULL, "profile", 1,
900 "Bitstream profile number to use");
901static const arg_def_t width = ARG_DEF("w", "width", 1,
902 "Frame width");
903static const arg_def_t height = ARG_DEF("h", "height", 1,
904 "Frame height");
905static const arg_def_t timebase = ARG_DEF(NULL, "timebase", 1,
906 "Stream timebase (frame duration)");
907static const arg_def_t error_resilient = ARG_DEF(NULL, "error-resilient", 1,
908 "Enable error resiliency features");
909static const arg_def_t lag_in_frames = ARG_DEF(NULL, "lag-in-frames", 1,
910 "Max number of frames to lag");
911
912static const arg_def_t *global_args[] =
913{
914 &use_yv12, &use_i420, &usage, &threads, &profile,
Frank Galligan1258cf62010-10-06 12:51:00 -0400915 &width, &height, &timebase, &framerate, &error_resilient,
John Koleszar0ea50ce2010-05-18 11:58:33 -0400916 &lag_in_frames, NULL
917};
918
919static const arg_def_t dropframe_thresh = ARG_DEF(NULL, "drop-frame", 1,
920 "Temporal resampling threshold (buf %)");
921static const arg_def_t resize_allowed = ARG_DEF(NULL, "resize-allowed", 1,
922 "Spatial resampling enabled (bool)");
923static const arg_def_t resize_up_thresh = ARG_DEF(NULL, "resize-up", 1,
924 "Upscale threshold (buf %)");
925static const arg_def_t resize_down_thresh = ARG_DEF(NULL, "resize-down", 1,
926 "Downscale threshold (buf %)");
927static const arg_def_t end_usage = ARG_DEF(NULL, "end-usage", 1,
Paul Wilkinse0846c92011-01-07 18:29:37 +0000928 "VBR=0 | CBR=1 | CQ=2");
John Koleszar0ea50ce2010-05-18 11:58:33 -0400929static const arg_def_t target_bitrate = ARG_DEF(NULL, "target-bitrate", 1,
930 "Bitrate (kbps)");
931static const arg_def_t min_quantizer = ARG_DEF(NULL, "min-q", 1,
932 "Minimum (best) quantizer");
933static const arg_def_t max_quantizer = ARG_DEF(NULL, "max-q", 1,
934 "Maximum (worst) quantizer");
935static const arg_def_t undershoot_pct = ARG_DEF(NULL, "undershoot-pct", 1,
936 "Datarate undershoot (min) target (%)");
937static const arg_def_t overshoot_pct = ARG_DEF(NULL, "overshoot-pct", 1,
938 "Datarate overshoot (max) target (%)");
939static const arg_def_t buf_sz = ARG_DEF(NULL, "buf-sz", 1,
940 "Client buffer size (ms)");
941static const arg_def_t buf_initial_sz = ARG_DEF(NULL, "buf-initial-sz", 1,
942 "Client initial buffer size (ms)");
943static const arg_def_t buf_optimal_sz = ARG_DEF(NULL, "buf-optimal-sz", 1,
944 "Client optimal buffer size (ms)");
945static const arg_def_t *rc_args[] =
946{
947 &dropframe_thresh, &resize_allowed, &resize_up_thresh, &resize_down_thresh,
948 &end_usage, &target_bitrate, &min_quantizer, &max_quantizer,
949 &undershoot_pct, &overshoot_pct, &buf_sz, &buf_initial_sz, &buf_optimal_sz,
950 NULL
951};
952
953
954static const arg_def_t bias_pct = ARG_DEF(NULL, "bias-pct", 1,
955 "CBR/VBR bias (0=CBR, 100=VBR)");
956static const arg_def_t minsection_pct = ARG_DEF(NULL, "minsection-pct", 1,
957 "GOP min bitrate (% of target)");
958static const arg_def_t maxsection_pct = ARG_DEF(NULL, "maxsection-pct", 1,
959 "GOP max bitrate (% of target)");
960static const arg_def_t *rc_twopass_args[] =
961{
962 &bias_pct, &minsection_pct, &maxsection_pct, NULL
963};
964
965
966static const arg_def_t kf_min_dist = ARG_DEF(NULL, "kf-min-dist", 1,
967 "Minimum keyframe interval (frames)");
968static const arg_def_t kf_max_dist = ARG_DEF(NULL, "kf-max-dist", 1,
969 "Maximum keyframe interval (frames)");
John Koleszarb1e36f22010-06-24 08:41:51 -0400970static const arg_def_t kf_disabled = ARG_DEF(NULL, "disable-kf", 0,
971 "Disable keyframe placement");
John Koleszar0ea50ce2010-05-18 11:58:33 -0400972static const arg_def_t *kf_args[] =
973{
John Koleszarb1e36f22010-06-24 08:41:51 -0400974 &kf_min_dist, &kf_max_dist, &kf_disabled, NULL
John Koleszar0ea50ce2010-05-18 11:58:33 -0400975};
976
977
978#if CONFIG_VP8_ENCODER
979static const arg_def_t noise_sens = ARG_DEF(NULL, "noise-sensitivity", 1,
980 "Noise sensitivity (frames to blur)");
981static const arg_def_t sharpness = ARG_DEF(NULL, "sharpness", 1,
982 "Filter sharpness (0-7)");
983static const arg_def_t static_thresh = ARG_DEF(NULL, "static-thresh", 1,
984 "Motion detection threshold");
985#endif
986
987#if CONFIG_VP8_ENCODER
988static const arg_def_t cpu_used = ARG_DEF(NULL, "cpu-used", 1,
989 "CPU Used (-16..16)");
990#endif
991
992
993#if CONFIG_VP8_ENCODER
994static const arg_def_t token_parts = ARG_DEF(NULL, "token-parts", 1,
995 "Number of token partitions to use, log2");
996static const arg_def_t auto_altref = ARG_DEF(NULL, "auto-alt-ref", 1,
997 "Enable automatic alt reference frames");
998static const arg_def_t arnr_maxframes = ARG_DEF(NULL, "arnr-maxframes", 1,
John Koleszar0684c642010-10-29 11:07:31 -0400999 "AltRef Max Frames");
John Koleszar0ea50ce2010-05-18 11:58:33 -04001000static const arg_def_t arnr_strength = ARG_DEF(NULL, "arnr-strength", 1,
John Koleszar0684c642010-10-29 11:07:31 -04001001 "AltRef Strength");
John Koleszar0ea50ce2010-05-18 11:58:33 -04001002static const arg_def_t arnr_type = ARG_DEF(NULL, "arnr-type", 1,
John Koleszar0684c642010-10-29 11:07:31 -04001003 "AltRef Type");
John Koleszarb0da9b32010-12-17 09:43:39 -05001004static const struct arg_enum_list tuning_enum[] = {
1005 {"psnr", VP8_TUNE_PSNR},
1006 {"ssim", VP8_TUNE_SSIM},
1007 {NULL, 0}
1008};
1009static const arg_def_t tune_ssim = ARG_DEF_ENUM(NULL, "tune", 1,
1010 "Material to favor", tuning_enum);
Paul Wilkinse0846c92011-01-07 18:29:37 +00001011static const arg_def_t cq_level = ARG_DEF(NULL, "cq-level", 1,
1012 "Constrained Quality Level");
John Koleszar0ea50ce2010-05-18 11:58:33 -04001013
1014static const arg_def_t *vp8_args[] =
1015{
1016 &cpu_used, &auto_altref, &noise_sens, &sharpness, &static_thresh,
John Koleszarb0da9b32010-12-17 09:43:39 -05001017 &token_parts, &arnr_maxframes, &arnr_strength, &arnr_type,
Paul Wilkinse0846c92011-01-07 18:29:37 +00001018 &tune_ssim, &cq_level, NULL
John Koleszar0ea50ce2010-05-18 11:58:33 -04001019};
1020static const int vp8_arg_ctrl_map[] =
1021{
1022 VP8E_SET_CPUUSED, VP8E_SET_ENABLEAUTOALTREF,
1023 VP8E_SET_NOISE_SENSITIVITY, VP8E_SET_SHARPNESS, VP8E_SET_STATIC_THRESHOLD,
1024 VP8E_SET_TOKEN_PARTITIONS,
John Koleszarb0da9b32010-12-17 09:43:39 -05001025 VP8E_SET_ARNR_MAXFRAMES, VP8E_SET_ARNR_STRENGTH , VP8E_SET_ARNR_TYPE,
Paul Wilkinse0846c92011-01-07 18:29:37 +00001026 VP8E_SET_TUNING, VP8E_SET_CQ_LEVEL, 0
John Koleszar0ea50ce2010-05-18 11:58:33 -04001027};
1028#endif
1029
1030static const arg_def_t *no_args[] = { NULL };
1031
1032static void usage_exit()
1033{
1034 int i;
1035
John Koleszar53291892010-10-22 14:48:21 -04001036 fprintf(stderr, "Usage: %s <options> -o dst_filename src_filename \n",
1037 exec_name);
John Koleszar0ea50ce2010-05-18 11:58:33 -04001038
John Koleszar78f2d3e2010-10-11 09:41:14 -04001039 fprintf(stderr, "\nOptions:\n");
John Koleszar0ea50ce2010-05-18 11:58:33 -04001040 arg_show_usage(stdout, main_args);
John Koleszar78f2d3e2010-10-11 09:41:14 -04001041 fprintf(stderr, "\nEncoder Global Options:\n");
John Koleszar0ea50ce2010-05-18 11:58:33 -04001042 arg_show_usage(stdout, global_args);
John Koleszar78f2d3e2010-10-11 09:41:14 -04001043 fprintf(stderr, "\nRate Control Options:\n");
John Koleszar0ea50ce2010-05-18 11:58:33 -04001044 arg_show_usage(stdout, rc_args);
John Koleszar78f2d3e2010-10-11 09:41:14 -04001045 fprintf(stderr, "\nTwopass Rate Control Options:\n");
John Koleszar0ea50ce2010-05-18 11:58:33 -04001046 arg_show_usage(stdout, rc_twopass_args);
John Koleszar78f2d3e2010-10-11 09:41:14 -04001047 fprintf(stderr, "\nKeyframe Placement Options:\n");
John Koleszar0ea50ce2010-05-18 11:58:33 -04001048 arg_show_usage(stdout, kf_args);
1049#if CONFIG_VP8_ENCODER
John Koleszar78f2d3e2010-10-11 09:41:14 -04001050 fprintf(stderr, "\nVP8 Specific Options:\n");
John Koleszar0ea50ce2010-05-18 11:58:33 -04001051 arg_show_usage(stdout, vp8_args);
1052#endif
John Koleszar3245d462010-06-10 17:10:12 -04001053 fprintf(stderr, "\n"
John Koleszar0ea50ce2010-05-18 11:58:33 -04001054 "Included encoders:\n"
1055 "\n");
1056
1057 for (i = 0; i < sizeof(codecs) / sizeof(codecs[0]); i++)
John Koleszar3245d462010-06-10 17:10:12 -04001058 fprintf(stderr, " %-6s - %s\n",
John Koleszar0ea50ce2010-05-18 11:58:33 -04001059 codecs[i].name,
1060 vpx_codec_iface_name(codecs[i].iface));
1061
1062 exit(EXIT_FAILURE);
1063}
1064
1065#define ARG_CTRL_CNT_MAX 10
1066
1067
1068int main(int argc, const char **argv_)
1069{
1070 vpx_codec_ctx_t encoder;
1071 const char *in_fn = NULL, *out_fn = NULL, *stats_fn = NULL;
1072 int i;
1073 FILE *infile, *outfile;
1074 vpx_codec_enc_cfg_t cfg;
1075 vpx_codec_err_t res;
1076 int pass, one_pass_only = 0;
1077 stats_io_t stats;
1078 vpx_image_t raw;
1079 const struct codec_item *codec = codecs;
1080 int frame_avail, got_data;
1081
1082 struct arg arg;
1083 char **argv, **argi, **argj;
1084 int arg_usage = 0, arg_passes = 1, arg_deadline = 0;
1085 int arg_ctrls[ARG_CTRL_CNT_MAX][2], arg_ctrl_cnt = 0;
1086 int arg_limit = 0;
1087 static const arg_def_t **ctrl_args = no_args;
1088 static const int *ctrl_args_map = NULL;
1089 int verbose = 0, show_psnr = 0;
1090 int arg_use_i420 = 1;
1091 unsigned long cx_time = 0;
Timothy B. Terriberry44d89492010-05-26 18:27:51 -04001092 unsigned int file_type, fourcc;
1093 y4m_input y4m;
Frank Galligan1258cf62010-10-06 12:51:00 -04001094 struct vpx_rational arg_framerate = {30, 1};
1095 int arg_have_framerate = 0;
John Koleszar456bfb12010-10-21 16:23:20 -04001096 int write_webm = 1;
John Koleszardc666302010-10-20 12:05:48 -04001097 EbmlGlobal ebml = {0};
John Koleszarc7c0c052010-10-27 10:05:55 -04001098 uint32_t hash = 0;
Frank Galligan3d84da62010-10-27 11:28:56 -04001099 uint64_t psnr_sse_total = 0;
1100 uint64_t psnr_samples_total = 0;
1101 double psnr_totals[4] = {0, 0, 0, 0};
1102 int psnr_count = 0;
John Koleszar0ea50ce2010-05-18 11:58:33 -04001103
1104 exec_name = argv_[0];
Frank Galligan8c2dfde2010-11-03 23:33:00 -04001105 ebml.last_pts_ms = -1;
John Koleszar0ea50ce2010-05-18 11:58:33 -04001106
1107 if (argc < 3)
1108 usage_exit();
1109
1110
1111 /* First parse the codec and usage values, because we want to apply other
1112 * parameters on top of the default configuration provided by the codec.
1113 */
1114 argv = argv_dup(argc - 1, argv_ + 1);
1115
1116 for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step)
1117 {
1118 arg.argv_step = 1;
1119
1120 if (arg_match(&arg, &codecarg, argi))
1121 {
1122 int j, k = -1;
1123
1124 for (j = 0; j < sizeof(codecs) / sizeof(codecs[0]); j++)
1125 if (!strcmp(codecs[j].name, arg.val))
1126 k = j;
1127
1128 if (k >= 0)
1129 codec = codecs + k;
1130 else
1131 die("Error: Unrecognized argument (%s) to --codec\n",
1132 arg.val);
1133
1134 }
1135 else if (arg_match(&arg, &passes, argi))
1136 {
1137 arg_passes = arg_parse_uint(&arg);
1138
1139 if (arg_passes < 1 || arg_passes > 2)
1140 die("Error: Invalid number of passes (%d)\n", arg_passes);
1141 }
1142 else if (arg_match(&arg, &pass_arg, argi))
1143 {
1144 one_pass_only = arg_parse_uint(&arg);
1145
1146 if (one_pass_only < 1 || one_pass_only > 2)
1147 die("Error: Invalid pass selected (%d)\n", one_pass_only);
1148 }
1149 else if (arg_match(&arg, &fpf_name, argi))
1150 stats_fn = arg.val;
1151 else if (arg_match(&arg, &usage, argi))
1152 arg_usage = arg_parse_uint(&arg);
1153 else if (arg_match(&arg, &deadline, argi))
1154 arg_deadline = arg_parse_uint(&arg);
1155 else if (arg_match(&arg, &best_dl, argi))
1156 arg_deadline = VPX_DL_BEST_QUALITY;
1157 else if (arg_match(&arg, &good_dl, argi))
1158 arg_deadline = VPX_DL_GOOD_QUALITY;
1159 else if (arg_match(&arg, &rt_dl, argi))
1160 arg_deadline = VPX_DL_REALTIME;
1161 else if (arg_match(&arg, &use_yv12, argi))
1162 {
1163 arg_use_i420 = 0;
1164 }
1165 else if (arg_match(&arg, &use_i420, argi))
1166 {
1167 arg_use_i420 = 1;
1168 }
1169 else if (arg_match(&arg, &verbosearg, argi))
1170 verbose = 1;
1171 else if (arg_match(&arg, &limit, argi))
1172 arg_limit = arg_parse_uint(&arg);
1173 else if (arg_match(&arg, &psnrarg, argi))
1174 show_psnr = 1;
Frank Galligan1258cf62010-10-06 12:51:00 -04001175 else if (arg_match(&arg, &framerate, argi))
1176 {
1177 arg_framerate = arg_parse_rational(&arg);
1178 arg_have_framerate = 1;
1179 }
John Koleszar456bfb12010-10-21 16:23:20 -04001180 else if (arg_match(&arg, &use_ivf, argi))
1181 write_webm = 0;
John Koleszar53291892010-10-22 14:48:21 -04001182 else if (arg_match(&arg, &outputfile, argi))
1183 out_fn = arg.val;
John Koleszar75afcee2010-10-26 16:22:22 -04001184 else if (arg_match(&arg, &debugmode, argi))
1185 ebml.debug = 1;
John Koleszar0ea50ce2010-05-18 11:58:33 -04001186 else
1187 argj++;
1188 }
1189
1190 /* Ensure that --passes and --pass are consistent. If --pass is set and --passes=2,
1191 * ensure --fpf was set.
1192 */
1193 if (one_pass_only)
1194 {
1195 /* DWIM: Assume the user meant passes=2 if pass=2 is specified */
1196 if (one_pass_only > arg_passes)
1197 {
John Koleszar3245d462010-06-10 17:10:12 -04001198 fprintf(stderr, "Warning: Assuming --pass=%d implies --passes=%d\n",
John Koleszar0ea50ce2010-05-18 11:58:33 -04001199 one_pass_only, one_pass_only);
1200 arg_passes = one_pass_only;
1201 }
1202
1203 if (arg_passes == 2 && !stats_fn)
1204 die("Must specify --fpf when --pass=%d and --passes=2\n", one_pass_only);
1205 }
1206
1207 /* Populate encoder configuration */
1208 res = vpx_codec_enc_config_default(codec->iface, &cfg, arg_usage);
1209
1210 if (res)
1211 {
John Koleszar3245d462010-06-10 17:10:12 -04001212 fprintf(stderr, "Failed to get config: %s\n",
1213 vpx_codec_err_to_string(res));
John Koleszar0ea50ce2010-05-18 11:58:33 -04001214 return EXIT_FAILURE;
1215 }
1216
Frank Galligan1258cf62010-10-06 12:51:00 -04001217 /* Change the default timebase to a high enough value so that the encoder
1218 * will always create strictly increasing timestamps.
1219 */
John Koleszarf7e187d2010-11-04 15:05:45 -04001220 cfg.g_timebase.den = 1000;
Frank Galligan1258cf62010-10-06 12:51:00 -04001221
John Koleszar77e6b452010-11-03 13:58:40 -04001222 /* Never use the library's default resolution, require it be parsed
1223 * from the file or set on the command line.
1224 */
1225 cfg.g_w = 0;
1226 cfg.g_h = 0;
1227
John Koleszar0ea50ce2010-05-18 11:58:33 -04001228 /* Now parse the remainder of the parameters. */
1229 for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step)
1230 {
1231 arg.argv_step = 1;
1232
1233 if (0);
1234 else if (arg_match(&arg, &threads, argi))
1235 cfg.g_threads = arg_parse_uint(&arg);
1236 else if (arg_match(&arg, &profile, argi))
1237 cfg.g_profile = arg_parse_uint(&arg);
1238 else if (arg_match(&arg, &width, argi))
1239 cfg.g_w = arg_parse_uint(&arg);
1240 else if (arg_match(&arg, &height, argi))
1241 cfg.g_h = arg_parse_uint(&arg);
1242 else if (arg_match(&arg, &timebase, argi))
1243 cfg.g_timebase = arg_parse_rational(&arg);
1244 else if (arg_match(&arg, &error_resilient, argi))
1245 cfg.g_error_resilient = arg_parse_uint(&arg);
1246 else if (arg_match(&arg, &lag_in_frames, argi))
1247 cfg.g_lag_in_frames = arg_parse_uint(&arg);
1248 else if (arg_match(&arg, &dropframe_thresh, argi))
1249 cfg.rc_dropframe_thresh = arg_parse_uint(&arg);
1250 else if (arg_match(&arg, &resize_allowed, argi))
1251 cfg.rc_resize_allowed = arg_parse_uint(&arg);
1252 else if (arg_match(&arg, &resize_up_thresh, argi))
1253 cfg.rc_resize_up_thresh = arg_parse_uint(&arg);
1254 else if (arg_match(&arg, &resize_down_thresh, argi))
1255 cfg.rc_resize_down_thresh = arg_parse_uint(&arg);
1256 else if (arg_match(&arg, &resize_down_thresh, argi))
1257 cfg.rc_resize_down_thresh = arg_parse_uint(&arg);
1258 else if (arg_match(&arg, &end_usage, argi))
1259 cfg.rc_end_usage = arg_parse_uint(&arg);
1260 else if (arg_match(&arg, &target_bitrate, argi))
1261 cfg.rc_target_bitrate = arg_parse_uint(&arg);
1262 else if (arg_match(&arg, &min_quantizer, argi))
1263 cfg.rc_min_quantizer = arg_parse_uint(&arg);
1264 else if (arg_match(&arg, &max_quantizer, argi))
1265 cfg.rc_max_quantizer = arg_parse_uint(&arg);
1266 else if (arg_match(&arg, &undershoot_pct, argi))
1267 cfg.rc_undershoot_pct = arg_parse_uint(&arg);
1268 else if (arg_match(&arg, &overshoot_pct, argi))
1269 cfg.rc_overshoot_pct = arg_parse_uint(&arg);
1270 else if (arg_match(&arg, &buf_sz, argi))
1271 cfg.rc_buf_sz = arg_parse_uint(&arg);
1272 else if (arg_match(&arg, &buf_initial_sz, argi))
1273 cfg.rc_buf_initial_sz = arg_parse_uint(&arg);
1274 else if (arg_match(&arg, &buf_optimal_sz, argi))
1275 cfg.rc_buf_optimal_sz = arg_parse_uint(&arg);
1276 else if (arg_match(&arg, &bias_pct, argi))
1277 {
1278 cfg.rc_2pass_vbr_bias_pct = arg_parse_uint(&arg);
1279
1280 if (arg_passes < 2)
John Koleszar3245d462010-06-10 17:10:12 -04001281 fprintf(stderr,
1282 "Warning: option %s ignored in one-pass mode.\n",
1283 arg.name);
John Koleszar0ea50ce2010-05-18 11:58:33 -04001284 }
1285 else if (arg_match(&arg, &minsection_pct, argi))
1286 {
1287 cfg.rc_2pass_vbr_minsection_pct = arg_parse_uint(&arg);
1288
1289 if (arg_passes < 2)
John Koleszar3245d462010-06-10 17:10:12 -04001290 fprintf(stderr,
1291 "Warning: option %s ignored in one-pass mode.\n",
1292 arg.name);
John Koleszar0ea50ce2010-05-18 11:58:33 -04001293 }
1294 else if (arg_match(&arg, &maxsection_pct, argi))
1295 {
1296 cfg.rc_2pass_vbr_maxsection_pct = arg_parse_uint(&arg);
1297
1298 if (arg_passes < 2)
John Koleszar3245d462010-06-10 17:10:12 -04001299 fprintf(stderr,
1300 "Warning: option %s ignored in one-pass mode.\n",
1301 arg.name);
John Koleszar0ea50ce2010-05-18 11:58:33 -04001302 }
1303 else if (arg_match(&arg, &kf_min_dist, argi))
1304 cfg.kf_min_dist = arg_parse_uint(&arg);
1305 else if (arg_match(&arg, &kf_max_dist, argi))
1306 cfg.kf_max_dist = arg_parse_uint(&arg);
John Koleszarb1e36f22010-06-24 08:41:51 -04001307 else if (arg_match(&arg, &kf_disabled, argi))
1308 cfg.kf_mode = VPX_KF_DISABLED;
John Koleszar0ea50ce2010-05-18 11:58:33 -04001309 else
1310 argj++;
1311 }
1312
1313 /* Handle codec specific options */
1314#if CONFIG_VP8_ENCODER
1315
1316 if (codec->iface == &vpx_codec_vp8_cx_algo)
1317 {
1318 ctrl_args = vp8_args;
1319 ctrl_args_map = vp8_arg_ctrl_map;
1320 }
1321
1322#endif
1323
1324 for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step)
1325 {
1326 int match = 0;
1327
1328 arg.argv_step = 1;
1329
1330 for (i = 0; ctrl_args[i]; i++)
1331 {
1332 if (arg_match(&arg, ctrl_args[i], argi))
1333 {
1334 match = 1;
1335
1336 if (arg_ctrl_cnt < ARG_CTRL_CNT_MAX)
1337 {
1338 arg_ctrls[arg_ctrl_cnt][0] = ctrl_args_map[i];
John Koleszarb0da9b32010-12-17 09:43:39 -05001339 arg_ctrls[arg_ctrl_cnt][1] = arg_parse_enum_or_int(&arg);
John Koleszar0ea50ce2010-05-18 11:58:33 -04001340 arg_ctrl_cnt++;
1341 }
1342 }
1343 }
1344
1345 if (!match)
1346 argj++;
1347 }
1348
1349 /* Check for unrecognized options */
1350 for (argi = argv; *argi; argi++)
John Koleszar3245d462010-06-10 17:10:12 -04001351 if (argi[0][0] == '-' && argi[0][1])
John Koleszar0ea50ce2010-05-18 11:58:33 -04001352 die("Error: Unrecognized option %s\n", *argi);
1353
1354 /* Handle non-option arguments */
1355 in_fn = argv[0];
John Koleszar0ea50ce2010-05-18 11:58:33 -04001356
John Koleszar53291892010-10-22 14:48:21 -04001357 if (!in_fn)
John Koleszar0ea50ce2010-05-18 11:58:33 -04001358 usage_exit();
1359
John Koleszar53291892010-10-22 14:48:21 -04001360 if(!out_fn)
1361 die("Error: Output file is required (specify with -o)\n");
1362
John Koleszar0ea50ce2010-05-18 11:58:33 -04001363 memset(&stats, 0, sizeof(stats));
1364
1365 for (pass = one_pass_only ? one_pass_only - 1 : 0; pass < arg_passes; pass++)
1366 {
1367 int frames_in = 0, frames_out = 0;
1368 unsigned long nbytes = 0;
John Koleszar3245d462010-06-10 17:10:12 -04001369 struct detect_buffer detect;
John Koleszar0ea50ce2010-05-18 11:58:33 -04001370
John Koleszar3245d462010-06-10 17:10:12 -04001371 /* Parse certain options from the input file, if possible */
John Koleszarc377bf02010-11-02 09:11:57 -04001372 infile = strcmp(in_fn, "-") ? fopen(in_fn, "rb")
1373 : set_binary_mode(stdin);
John Koleszar0ea50ce2010-05-18 11:58:33 -04001374
1375 if (!infile)
1376 {
John Koleszar3245d462010-06-10 17:10:12 -04001377 fprintf(stderr, "Failed to open input file\n");
John Koleszar0ea50ce2010-05-18 11:58:33 -04001378 return EXIT_FAILURE;
1379 }
1380
Timothy B. Terriberryc4d7e5e2010-10-27 16:04:02 -07001381 /* For RAW input sources, these bytes will applied on the first frame
1382 * in read_frame().
Timothy B. Terriberryc4d7e5e2010-10-27 16:04:02 -07001383 */
Pascal Massiminofd9f9dc2010-11-24 00:22:59 -08001384 detect.buf_read = fread(detect.buf, 1, 4, infile);
1385 detect.position = 0;
John Koleszar3245d462010-06-10 17:10:12 -04001386
Pascal Massiminofd9f9dc2010-11-24 00:22:59 -08001387 if (detect.buf_read == 4 && file_is_y4m(infile, &y4m, detect.buf))
Timothy B. Terriberry44d89492010-05-26 18:27:51 -04001388 {
Tom Finegane703af92010-06-16 13:24:55 -04001389 if (y4m_input_open(&y4m, infile, detect.buf, 4) >= 0)
John Koleszar3245d462010-06-10 17:10:12 -04001390 {
Tom Finegane703af92010-06-16 13:24:55 -04001391 file_type = FILE_TYPE_Y4M;
1392 cfg.g_w = y4m.pic_w;
1393 cfg.g_h = y4m.pic_h;
Frank Galligan1258cf62010-10-06 12:51:00 -04001394
Tom Finegane703af92010-06-16 13:24:55 -04001395 /* Use the frame rate from the file only if none was specified
1396 * on the command-line.
1397 */
Frank Galligan1258cf62010-10-06 12:51:00 -04001398 if (!arg_have_framerate)
Tom Finegane703af92010-06-16 13:24:55 -04001399 {
Frank Galligan1258cf62010-10-06 12:51:00 -04001400 arg_framerate.num = y4m.fps_n;
1401 arg_framerate.den = y4m.fps_d;
Tom Finegane703af92010-06-16 13:24:55 -04001402 }
Frank Galligan1258cf62010-10-06 12:51:00 -04001403
Tom Finegane703af92010-06-16 13:24:55 -04001404 arg_use_i420 = 0;
John Koleszar3245d462010-06-10 17:10:12 -04001405 }
Tom Finegane703af92010-06-16 13:24:55 -04001406 else
1407 {
1408 fprintf(stderr, "Unsupported Y4M stream.\n");
1409 return EXIT_FAILURE;
1410 }
Timothy B. Terriberry44d89492010-05-26 18:27:51 -04001411 }
Pascal Massiminofd9f9dc2010-11-24 00:22:59 -08001412 else if (detect.buf_read == 4 &&
James Berry136bd242010-12-13 13:10:58 -05001413 file_is_ivf(infile, &fourcc, &cfg.g_w, &cfg.g_h, &detect))
Timothy B. Terriberry44d89492010-05-26 18:27:51 -04001414 {
John Koleszar3245d462010-06-10 17:10:12 -04001415 file_type = FILE_TYPE_IVF;
1416 switch (fourcc)
1417 {
1418 case 0x32315659:
1419 arg_use_i420 = 0;
1420 break;
1421 case 0x30323449:
1422 arg_use_i420 = 1;
1423 break;
1424 default:
1425 fprintf(stderr, "Unsupported fourcc (%08x) in IVF\n", fourcc);
1426 return EXIT_FAILURE;
1427 }
1428 }
1429 else
1430 {
1431 file_type = FILE_TYPE_RAW;
John Koleszar3245d462010-06-10 17:10:12 -04001432 }
John Koleszar77e6b452010-11-03 13:58:40 -04001433
1434 if(!cfg.g_w || !cfg.g_h)
1435 {
1436 fprintf(stderr, "Specify stream dimensions with --width (-w) "
1437 " and --height (-h).\n");
1438 return EXIT_FAILURE;
1439 }
1440
John Koleszar3245d462010-06-10 17:10:12 -04001441#define SHOW(field) fprintf(stderr, " %-28s = %d\n", #field, cfg.field)
1442
1443 if (verbose && pass == 0)
1444 {
1445 fprintf(stderr, "Codec: %s\n", vpx_codec_iface_name(codec->iface));
1446 fprintf(stderr, "Source file: %s Format: %s\n", in_fn,
1447 arg_use_i420 ? "I420" : "YV12");
1448 fprintf(stderr, "Destination file: %s\n", out_fn);
1449 fprintf(stderr, "Encoder parameters:\n");
1450
1451 SHOW(g_usage);
1452 SHOW(g_threads);
1453 SHOW(g_profile);
1454 SHOW(g_w);
1455 SHOW(g_h);
1456 SHOW(g_timebase.num);
1457 SHOW(g_timebase.den);
1458 SHOW(g_error_resilient);
1459 SHOW(g_pass);
1460 SHOW(g_lag_in_frames);
1461 SHOW(rc_dropframe_thresh);
1462 SHOW(rc_resize_allowed);
1463 SHOW(rc_resize_up_thresh);
1464 SHOW(rc_resize_down_thresh);
1465 SHOW(rc_end_usage);
1466 SHOW(rc_target_bitrate);
1467 SHOW(rc_min_quantizer);
1468 SHOW(rc_max_quantizer);
1469 SHOW(rc_undershoot_pct);
1470 SHOW(rc_overshoot_pct);
1471 SHOW(rc_buf_sz);
1472 SHOW(rc_buf_initial_sz);
1473 SHOW(rc_buf_optimal_sz);
1474 SHOW(rc_2pass_vbr_bias_pct);
1475 SHOW(rc_2pass_vbr_minsection_pct);
1476 SHOW(rc_2pass_vbr_maxsection_pct);
1477 SHOW(kf_mode);
1478 SHOW(kf_min_dist);
1479 SHOW(kf_max_dist);
Timothy B. Terriberry44d89492010-05-26 18:27:51 -04001480 }
1481
John Koleszardf2c62d2010-06-14 08:33:54 -04001482 if(pass == (one_pass_only ? one_pass_only - 1 : 0)) {
John Koleszar3245d462010-06-10 17:10:12 -04001483 if (file_type == FILE_TYPE_Y4M)
1484 /*The Y4M reader does its own allocation.
1485 Just initialize this here to avoid problems if we never read any
1486 frames.*/
1487 memset(&raw, 0, sizeof(raw));
1488 else
1489 vpx_img_alloc(&raw, arg_use_i420 ? VPX_IMG_FMT_I420 : VPX_IMG_FMT_YV12,
1490 cfg.g_w, cfg.g_h, 1);
John Koleszar3245d462010-06-10 17:10:12 -04001491 }
1492
John Koleszarc377bf02010-11-02 09:11:57 -04001493 outfile = strcmp(out_fn, "-") ? fopen(out_fn, "wb")
1494 : set_binary_mode(stdout);
John Koleszar0ea50ce2010-05-18 11:58:33 -04001495
1496 if (!outfile)
1497 {
John Koleszar3245d462010-06-10 17:10:12 -04001498 fprintf(stderr, "Failed to open output file\n");
John Koleszar0ea50ce2010-05-18 11:58:33 -04001499 return EXIT_FAILURE;
1500 }
1501
John Koleszar0a6bf292010-10-22 14:57:02 -04001502 if(write_webm && fseek(outfile, 0, SEEK_CUR))
1503 {
1504 fprintf(stderr, "WebM output to pipes not supported.\n");
1505 return EXIT_FAILURE;
1506 }
1507
John Koleszar0ea50ce2010-05-18 11:58:33 -04001508 if (stats_fn)
1509 {
1510 if (!stats_open_file(&stats, stats_fn, pass))
1511 {
John Koleszar3245d462010-06-10 17:10:12 -04001512 fprintf(stderr, "Failed to open statistics store\n");
John Koleszar0ea50ce2010-05-18 11:58:33 -04001513 return EXIT_FAILURE;
1514 }
1515 }
1516 else
1517 {
1518 if (!stats_open_mem(&stats, pass))
1519 {
John Koleszar3245d462010-06-10 17:10:12 -04001520 fprintf(stderr, "Failed to open statistics store\n");
John Koleszar0ea50ce2010-05-18 11:58:33 -04001521 return EXIT_FAILURE;
1522 }
1523 }
1524
1525 cfg.g_pass = arg_passes == 2
1526 ? pass ? VPX_RC_LAST_PASS : VPX_RC_FIRST_PASS
1527 : VPX_RC_ONE_PASS;
1528#if VPX_ENCODER_ABI_VERSION > (1 + VPX_CODEC_ABI_VERSION)
1529
1530 if (pass)
1531 {
1532 cfg.rc_twopass_stats_in = stats_get(&stats);
1533 }
1534
1535#endif
1536
John Koleszardc666302010-10-20 12:05:48 -04001537 if(write_webm)
1538 {
1539 ebml.stream = outfile;
1540 write_webm_file_header(&ebml, &cfg, &arg_framerate);
1541 }
1542 else
1543 write_ivf_file_header(outfile, &cfg, codec->fourcc, 0);
John Koleszar0ea50ce2010-05-18 11:58:33 -04001544
1545
1546 /* Construct Encoder Context */
John Koleszar0ea50ce2010-05-18 11:58:33 -04001547 vpx_codec_enc_init(&encoder, codec->iface, &cfg,
1548 show_psnr ? VPX_CODEC_USE_PSNR : 0);
1549 ctx_exit_on_error(&encoder, "Failed to initialize encoder");
1550
1551 /* Note that we bypass the vpx_codec_control wrapper macro because
1552 * we're being clever to store the control IDs in an array. Real
1553 * applications will want to make use of the enumerations directly
1554 */
1555 for (i = 0; i < arg_ctrl_cnt; i++)
1556 {
1557 if (vpx_codec_control_(&encoder, arg_ctrls[i][0], arg_ctrls[i][1]))
John Koleszar3245d462010-06-10 17:10:12 -04001558 fprintf(stderr, "Error: Tried to set control %d = %d\n",
1559 arg_ctrls[i][0], arg_ctrls[i][1]);
John Koleszar0ea50ce2010-05-18 11:58:33 -04001560
1561 ctx_exit_on_error(&encoder, "Failed to control codec");
1562 }
1563
1564 frame_avail = 1;
1565 got_data = 0;
1566
1567 while (frame_avail || got_data)
1568 {
1569 vpx_codec_iter_t iter = NULL;
1570 const vpx_codec_cx_pkt_t *pkt;
1571 struct vpx_usec_timer timer;
John Koleszarf7e187d2010-11-04 15:05:45 -04001572 int64_t frame_start, next_frame_start;
John Koleszar0ea50ce2010-05-18 11:58:33 -04001573
1574 if (!arg_limit || frames_in < arg_limit)
1575 {
John Koleszar3245d462010-06-10 17:10:12 -04001576 frame_avail = read_frame(infile, &raw, file_type, &y4m,
1577 &detect);
John Koleszar0ea50ce2010-05-18 11:58:33 -04001578
1579 if (frame_avail)
1580 frames_in++;
1581
John Koleszar3245d462010-06-10 17:10:12 -04001582 fprintf(stderr,
1583 "\rPass %d/%d frame %4d/%-4d %7ldB \033[K", pass + 1,
1584 arg_passes, frames_in, frames_out, nbytes);
John Koleszar0ea50ce2010-05-18 11:58:33 -04001585 }
1586 else
1587 frame_avail = 0;
1588
1589 vpx_usec_timer_start(&timer);
1590
Frank Galligan1258cf62010-10-06 12:51:00 -04001591 frame_start = (cfg.g_timebase.den * (int64_t)(frames_in - 1)
1592 * arg_framerate.den) / cfg.g_timebase.num / arg_framerate.num;
John Koleszarf7e187d2010-11-04 15:05:45 -04001593 next_frame_start = (cfg.g_timebase.den * (int64_t)(frames_in)
1594 * arg_framerate.den)
1595 / cfg.g_timebase.num / arg_framerate.num;
Frank Galligan1258cf62010-10-06 12:51:00 -04001596 vpx_codec_encode(&encoder, frame_avail ? &raw : NULL, frame_start,
John Koleszarf7e187d2010-11-04 15:05:45 -04001597 next_frame_start - frame_start,
Frank Galligan1258cf62010-10-06 12:51:00 -04001598 0, arg_deadline);
John Koleszar0ea50ce2010-05-18 11:58:33 -04001599 vpx_usec_timer_mark(&timer);
1600 cx_time += vpx_usec_timer_elapsed(&timer);
1601 ctx_exit_on_error(&encoder, "Failed to encode frame");
1602 got_data = 0;
1603
1604 while ((pkt = vpx_codec_get_cx_data(&encoder, &iter)))
1605 {
1606 got_data = 1;
John Koleszar0ea50ce2010-05-18 11:58:33 -04001607
1608 switch (pkt->kind)
1609 {
1610 case VPX_CODEC_CX_FRAME_PKT:
1611 frames_out++;
John Koleszar3245d462010-06-10 17:10:12 -04001612 fprintf(stderr, " %6luF",
1613 (unsigned long)pkt->data.frame.sz);
John Koleszarc7c0c052010-10-27 10:05:55 -04001614
John Koleszardc666302010-10-20 12:05:48 -04001615 if(write_webm)
1616 {
John Koleszarc7c0c052010-10-27 10:05:55 -04001617 /* Update the hash */
1618 if(!ebml.debug)
1619 hash = murmur(pkt->data.frame.buf,
1620 pkt->data.frame.sz, hash);
1621
John Koleszardc666302010-10-20 12:05:48 -04001622 write_webm_block(&ebml, &cfg, pkt);
1623 }
1624 else
1625 {
1626 write_ivf_frame_header(outfile, pkt);
Timothy B. Terriberryc4d7e5e2010-10-27 16:04:02 -07001627 if(fwrite(pkt->data.frame.buf, 1,
1628 pkt->data.frame.sz, outfile));
John Koleszardc666302010-10-20 12:05:48 -04001629 }
Yaowu Xua7bb3362010-05-27 10:32:40 -07001630 nbytes += pkt->data.raw.sz;
John Koleszar0ea50ce2010-05-18 11:58:33 -04001631 break;
1632 case VPX_CODEC_STATS_PKT:
1633 frames_out++;
John Koleszar3245d462010-06-10 17:10:12 -04001634 fprintf(stderr, " %6luS",
John Koleszar0ea50ce2010-05-18 11:58:33 -04001635 (unsigned long)pkt->data.twopass_stats.sz);
1636 stats_write(&stats,
1637 pkt->data.twopass_stats.buf,
1638 pkt->data.twopass_stats.sz);
Yaowu Xua7bb3362010-05-27 10:32:40 -07001639 nbytes += pkt->data.raw.sz;
John Koleszar0ea50ce2010-05-18 11:58:33 -04001640 break;
1641 case VPX_CODEC_PSNR_PKT:
1642
1643 if (show_psnr)
1644 {
1645 int i;
1646
Frank Galligan3d84da62010-10-27 11:28:56 -04001647 psnr_sse_total += pkt->data.psnr.sse[0];
1648 psnr_samples_total += pkt->data.psnr.samples[0];
John Koleszar0ea50ce2010-05-18 11:58:33 -04001649 for (i = 0; i < 4; i++)
Frank Galligan3d84da62010-10-27 11:28:56 -04001650 {
John Koleszar3245d462010-06-10 17:10:12 -04001651 fprintf(stderr, "%.3lf ", pkt->data.psnr.psnr[i]);
Frank Galligan3d84da62010-10-27 11:28:56 -04001652 psnr_totals[i] += pkt->data.psnr.psnr[i];
1653 }
1654 psnr_count++;
John Koleszar0ea50ce2010-05-18 11:58:33 -04001655 }
1656
1657 break;
1658 default:
1659 break;
1660 }
1661 }
1662
1663 fflush(stdout);
1664 }
1665
John Koleszar3245d462010-06-10 17:10:12 -04001666 fprintf(stderr,
1667 "\rPass %d/%d frame %4d/%-4d %7ldB %7ldb/f %7"PRId64"b/s"
John Koleszar0ea50ce2010-05-18 11:58:33 -04001668 " %7lu %s (%.2f fps)\033[K", pass + 1,
1669 arg_passes, frames_in, frames_out, nbytes, nbytes * 8 / frames_in,
Frank Galligan1258cf62010-10-06 12:51:00 -04001670 nbytes * 8 *(int64_t)arg_framerate.num / arg_framerate.den / frames_in,
John Koleszar0ea50ce2010-05-18 11:58:33 -04001671 cx_time > 9999999 ? cx_time / 1000 : cx_time,
1672 cx_time > 9999999 ? "ms" : "us",
1673 (float)frames_in * 1000000.0 / (float)cx_time);
1674
Frank Galligan3d84da62010-10-27 11:28:56 -04001675 if ( (show_psnr) && (psnr_count>0) )
1676 {
1677 int i;
1678 double ovpsnr = vp8_mse2psnr(psnr_samples_total, 255.0,
1679 psnr_sse_total);
1680
1681 fprintf(stderr, "\nPSNR (Overall/Avg/Y/U/V)");
1682
1683 fprintf(stderr, " %.3lf", ovpsnr);
1684 for (i = 0; i < 4; i++)
1685 {
1686 fprintf(stderr, " %.3lf", psnr_totals[i]/psnr_count);
1687 }
1688 }
1689
John Koleszar0ea50ce2010-05-18 11:58:33 -04001690 vpx_codec_destroy(&encoder);
1691
1692 fclose(infile);
1693
John Koleszardc666302010-10-20 12:05:48 -04001694 if(write_webm)
1695 {
John Koleszarc7c0c052010-10-27 10:05:55 -04001696 write_webm_file_footer(&ebml, hash);
John Koleszardc666302010-10-20 12:05:48 -04001697 }
1698 else
1699 {
1700 if (!fseek(outfile, 0, SEEK_SET))
1701 write_ivf_file_header(outfile, &cfg, codec->fourcc, frames_out);
1702 }
John Koleszar0ea50ce2010-05-18 11:58:33 -04001703
1704 fclose(outfile);
James Berry74e84462010-12-23 14:47:56 -05001705 stats_close(&stats, arg_passes-1);
John Koleszar3245d462010-06-10 17:10:12 -04001706 fprintf(stderr, "\n");
John Koleszar0ea50ce2010-05-18 11:58:33 -04001707
1708 if (one_pass_only)
1709 break;
1710 }
1711
1712 vpx_img_free(&raw);
1713 free(argv);
1714 return EXIT_SUCCESS;
1715}