blob: a8632b8878b85accf6ec436bb96b4142f9fc2daf [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 */
Frank Galligan3419e4d2010-06-10 16:59:21 -040015#if defined(_WIN32)
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"
Timothy B. Terriberry44d89492010-05-26 18:27:51 -040038#include "y4minput.h"
John Koleszardc666302010-10-20 12:05:48 -040039#include "libmkv/EbmlWriter.h"
40#include "libmkv/EbmlIDs.h"
41
42/* Need special handling of these functions on Windows */
43#if defined(_MSC_VER)
44/* MSVS doesn't define off_t, and uses _f{seek,tell}i64 */
45typedef __int64 off_t;
46#define fseeko _fseeki64
47#define ftello _ftelli64
48#elif defined(_WIN32)
49/* MinGW defines off_t, and uses f{seek,tell}o64 */
50#define fseeko fseeko64
51#define ftello ftello64
52#endif
53
54#if defined(_MSC_VER)
55#define LITERALU64(n) n
56#else
57#define LITERALU64(n) n##LLU
58#endif
John Koleszar0ea50ce2010-05-18 11:58:33 -040059
60static const char *exec_name;
61
62static const struct codec_item
63{
64 char const *name;
65 const vpx_codec_iface_t *iface;
66 unsigned int fourcc;
67} codecs[] =
68{
69#if CONFIG_VP8_ENCODER
70 {"vp8", &vpx_codec_vp8_cx_algo, 0x30385056},
71#endif
72};
73
74static void usage_exit();
75
76void die(const char *fmt, ...)
77{
78 va_list ap;
79 va_start(ap, fmt);
John Koleszar3245d462010-06-10 17:10:12 -040080 vfprintf(stderr, fmt, ap);
81 fprintf(stderr, "\n");
John Koleszar0ea50ce2010-05-18 11:58:33 -040082 usage_exit();
83}
84
85static void ctx_exit_on_error(vpx_codec_ctx_t *ctx, const char *s)
86{
87 if (ctx->err)
88 {
89 const char *detail = vpx_codec_error_detail(ctx);
90
John Koleszar3245d462010-06-10 17:10:12 -040091 fprintf(stderr, "%s: %s\n", s, vpx_codec_error(ctx));
John Koleszar0ea50ce2010-05-18 11:58:33 -040092
93 if (detail)
John Koleszar3245d462010-06-10 17:10:12 -040094 fprintf(stderr, " %s\n", detail);
John Koleszar0ea50ce2010-05-18 11:58:33 -040095
96 exit(EXIT_FAILURE);
97 }
98}
99
100/* This structure is used to abstract the different ways of handling
101 * first pass statistics.
102 */
103typedef struct
104{
105 vpx_fixed_buf_t buf;
106 int pass;
107 FILE *file;
108 char *buf_ptr;
109 size_t buf_alloc_sz;
110} stats_io_t;
111
112int stats_open_file(stats_io_t *stats, const char *fpf, int pass)
113{
114 int res;
115
116 stats->pass = pass;
117
118 if (pass == 0)
119 {
120 stats->file = fopen(fpf, "wb");
121 stats->buf.sz = 0;
122 stats->buf.buf = NULL,
123 res = (stats->file != NULL);
124 }
125 else
126 {
127#if 0
128#elif USE_POSIX_MMAP
129 struct stat stat_buf;
130 int fd;
131
132 fd = open(fpf, O_RDONLY);
133 stats->file = fdopen(fd, "rb");
134 fstat(fd, &stat_buf);
135 stats->buf.sz = stat_buf.st_size;
136 stats->buf.buf = mmap(NULL, stats->buf.sz, PROT_READ, MAP_PRIVATE,
137 fd, 0);
138 res = (stats->buf.buf != NULL);
139#else
140 size_t nbytes;
141
142 stats->file = fopen(fpf, "rb");
143
144 if (fseek(stats->file, 0, SEEK_END))
145 {
146 fprintf(stderr, "First-pass stats file must be seekable!\n");
147 exit(EXIT_FAILURE);
148 }
149
150 stats->buf.sz = stats->buf_alloc_sz = ftell(stats->file);
151 rewind(stats->file);
152
153 stats->buf.buf = malloc(stats->buf_alloc_sz);
154
155 if (!stats->buf.buf)
156 {
157 fprintf(stderr, "Failed to allocate first-pass stats buffer (%d bytes)\n",
158 stats->buf_alloc_sz);
159 exit(EXIT_FAILURE);
160 }
161
162 nbytes = fread(stats->buf.buf, 1, stats->buf.sz, stats->file);
163 res = (nbytes == stats->buf.sz);
164#endif
165 }
166
167 return res;
168}
169
170int stats_open_mem(stats_io_t *stats, int pass)
171{
172 int res;
173 stats->pass = pass;
174
175 if (!pass)
176 {
177 stats->buf.sz = 0;
178 stats->buf_alloc_sz = 64 * 1024;
179 stats->buf.buf = malloc(stats->buf_alloc_sz);
180 }
181
182 stats->buf_ptr = stats->buf.buf;
183 res = (stats->buf.buf != NULL);
184 return res;
185}
186
187
188void stats_close(stats_io_t *stats)
189{
190 if (stats->file)
191 {
192 if (stats->pass == 1)
193 {
194#if 0
195#elif USE_POSIX_MMAP
196 munmap(stats->buf.buf, stats->buf.sz);
197#else
198 free(stats->buf.buf);
199#endif
200 }
201
202 fclose(stats->file);
203 stats->file = NULL;
204 }
205 else
206 {
207 if (stats->pass == 1)
208 free(stats->buf.buf);
209 }
210}
211
212void stats_write(stats_io_t *stats, const void *pkt, size_t len)
213{
214 if (stats->file)
215 {
216 fwrite(pkt, 1, len, stats->file);
217 }
218 else
219 {
220 if (stats->buf.sz + len > stats->buf_alloc_sz)
221 {
222 size_t new_sz = stats->buf_alloc_sz + 64 * 1024;
223 char *new_ptr = realloc(stats->buf.buf, new_sz);
224
225 if (new_ptr)
226 {
227 stats->buf_ptr = new_ptr + (stats->buf_ptr - (char *)stats->buf.buf);
228 stats->buf.buf = new_ptr;
229 stats->buf_alloc_sz = new_sz;
230 } /* else ... */
231 }
232
233 memcpy(stats->buf_ptr, pkt, len);
234 stats->buf.sz += len;
235 stats->buf_ptr += len;
236 }
237}
238
239vpx_fixed_buf_t stats_get(stats_io_t *stats)
240{
241 return stats->buf;
242}
243
Timothy B. Terriberry44d89492010-05-26 18:27:51 -0400244enum video_file_type
245{
246 FILE_TYPE_RAW,
247 FILE_TYPE_IVF,
248 FILE_TYPE_Y4M
249};
250
John Koleszar3245d462010-06-10 17:10:12 -0400251struct detect_buffer {
252 char buf[4];
253 int valid;
254};
255
256
John Koleszar0ea50ce2010-05-18 11:58:33 -0400257#define IVF_FRAME_HDR_SZ (4+8) /* 4 byte size + 8 byte timestamp */
Timothy B. Terriberry44d89492010-05-26 18:27:51 -0400258static int read_frame(FILE *f, vpx_image_t *img, unsigned int file_type,
John Koleszar3245d462010-06-10 17:10:12 -0400259 y4m_input *y4m, struct detect_buffer *detect)
John Koleszar0ea50ce2010-05-18 11:58:33 -0400260{
261 int plane = 0;
262
Timothy B. Terriberry44d89492010-05-26 18:27:51 -0400263 if (file_type == FILE_TYPE_Y4M)
John Koleszar0ea50ce2010-05-18 11:58:33 -0400264 {
Timothy B. Terriberry44d89492010-05-26 18:27:51 -0400265 if (y4m_input_fetch_frame(y4m, f, img) < 0)
266 return 0;
John Koleszar0ea50ce2010-05-18 11:58:33 -0400267 }
Timothy B. Terriberry44d89492010-05-26 18:27:51 -0400268 else
John Koleszar0ea50ce2010-05-18 11:58:33 -0400269 {
Timothy B. Terriberry44d89492010-05-26 18:27:51 -0400270 if (file_type == FILE_TYPE_IVF)
John Koleszar0ea50ce2010-05-18 11:58:33 -0400271 {
Timothy B. Terriberry44d89492010-05-26 18:27:51 -0400272 char junk[IVF_FRAME_HDR_SZ];
273
274 /* Skip the frame header. We know how big the frame should be. See
275 * write_ivf_frame_header() for documentation on the frame header
276 * layout.
277 */
278 fread(junk, 1, IVF_FRAME_HDR_SZ, f);
John Koleszar0ea50ce2010-05-18 11:58:33 -0400279 }
280
Timothy B. Terriberry44d89492010-05-26 18:27:51 -0400281 for (plane = 0; plane < 3; plane++)
John Koleszar0ea50ce2010-05-18 11:58:33 -0400282 {
Timothy B. Terriberry44d89492010-05-26 18:27:51 -0400283 unsigned char *ptr;
284 int w = (plane ? (1 + img->d_w) / 2 : img->d_w);
285 int h = (plane ? (1 + img->d_h) / 2 : img->d_h);
286 int r;
287
288 /* Determine the correct plane based on the image format. The for-loop
289 * always counts in Y,U,V order, but this may not match the order of
290 * the data on disk.
291 */
292 switch (plane)
293 {
294 case 1:
295 ptr = img->planes[img->fmt==VPX_IMG_FMT_YV12? VPX_PLANE_V : VPX_PLANE_U];
296 break;
297 case 2:
298 ptr = img->planes[img->fmt==VPX_IMG_FMT_YV12?VPX_PLANE_U : VPX_PLANE_V];
299 break;
300 default:
301 ptr = img->planes[plane];
302 }
303
304 for (r = 0; r < h; r++)
305 {
John Koleszar3245d462010-06-10 17:10:12 -0400306 if (detect->valid)
307 {
308 memcpy(ptr, detect->buf, 4);
309 fread(ptr+4, 1, w-4, f);
310 detect->valid = 0;
311 }
312 else
313 fread(ptr, 1, w, f);
314
Timothy B. Terriberry44d89492010-05-26 18:27:51 -0400315 ptr += img->stride[plane];
316 }
John Koleszar0ea50ce2010-05-18 11:58:33 -0400317 }
318 }
319
320 return !feof(f);
321}
322
323
Tom Finegane703af92010-06-16 13:24:55 -0400324unsigned int file_is_y4m(FILE *infile,
John Koleszar3245d462010-06-10 17:10:12 -0400325 y4m_input *y4m,
326 char detect[4])
Timothy B. Terriberry44d89492010-05-26 18:27:51 -0400327{
Tom Finegane703af92010-06-16 13:24:55 -0400328 if(memcmp(detect, "YUV4", 4) == 0)
Timothy B. Terriberry44d89492010-05-26 18:27:51 -0400329 {
330 return 1;
331 }
Timothy B. Terriberry44d89492010-05-26 18:27:51 -0400332 return 0;
333}
334
John Koleszar0ea50ce2010-05-18 11:58:33 -0400335#define IVF_FILE_HDR_SZ (32)
336unsigned int file_is_ivf(FILE *infile,
337 unsigned int *fourcc,
338 unsigned int *width,
John Koleszar3245d462010-06-10 17:10:12 -0400339 unsigned int *height,
340 char detect[4])
John Koleszar0ea50ce2010-05-18 11:58:33 -0400341{
342 char raw_hdr[IVF_FILE_HDR_SZ];
343 int is_ivf = 0;
344
John Koleszar3245d462010-06-10 17:10:12 -0400345 if(memcmp(detect, "DKIF", 4) != 0)
346 return 0;
347
John Koleszar0ea50ce2010-05-18 11:58:33 -0400348 /* See write_ivf_file_header() for more documentation on the file header
349 * layout.
350 */
John Koleszar3245d462010-06-10 17:10:12 -0400351 if (fread(raw_hdr + 4, 1, IVF_FILE_HDR_SZ - 4, infile)
352 == IVF_FILE_HDR_SZ - 4)
John Koleszar0ea50ce2010-05-18 11:58:33 -0400353 {
John Koleszar0ea50ce2010-05-18 11:58:33 -0400354 {
355 is_ivf = 1;
356
357 if (mem_get_le16(raw_hdr + 4) != 0)
358 fprintf(stderr, "Error: Unrecognized IVF version! This file may not"
359 " decode properly.");
360
361 *fourcc = mem_get_le32(raw_hdr + 8);
362 }
363 }
364
365 if (is_ivf)
366 {
367 *width = mem_get_le16(raw_hdr + 12);
368 *height = mem_get_le16(raw_hdr + 14);
369 }
John Koleszar0ea50ce2010-05-18 11:58:33 -0400370
371 return is_ivf;
372}
373
374
375static void write_ivf_file_header(FILE *outfile,
376 const vpx_codec_enc_cfg_t *cfg,
377 unsigned int fourcc,
378 int frame_cnt)
379{
380 char header[32];
381
382 if (cfg->g_pass != VPX_RC_ONE_PASS && cfg->g_pass != VPX_RC_LAST_PASS)
383 return;
384
385 header[0] = 'D';
386 header[1] = 'K';
387 header[2] = 'I';
388 header[3] = 'F';
389 mem_put_le16(header + 4, 0); /* version */
390 mem_put_le16(header + 6, 32); /* headersize */
391 mem_put_le32(header + 8, fourcc); /* headersize */
392 mem_put_le16(header + 12, cfg->g_w); /* width */
393 mem_put_le16(header + 14, cfg->g_h); /* height */
394 mem_put_le32(header + 16, cfg->g_timebase.den); /* rate */
395 mem_put_le32(header + 20, cfg->g_timebase.num); /* scale */
396 mem_put_le32(header + 24, frame_cnt); /* length */
397 mem_put_le32(header + 28, 0); /* unused */
398
399 fwrite(header, 1, 32, outfile);
400}
401
402
403static void write_ivf_frame_header(FILE *outfile,
404 const vpx_codec_cx_pkt_t *pkt)
405{
406 char header[12];
407 vpx_codec_pts_t pts;
408
409 if (pkt->kind != VPX_CODEC_CX_FRAME_PKT)
410 return;
411
412 pts = pkt->data.frame.pts;
413 mem_put_le32(header, pkt->data.frame.sz);
414 mem_put_le32(header + 4, pts & 0xFFFFFFFF);
415 mem_put_le32(header + 8, pts >> 32);
416
417 fwrite(header, 1, 12, outfile);
418}
419
John Koleszardc666302010-10-20 12:05:48 -0400420
421typedef off_t EbmlLoc;
422
423
424struct cue_entry
425{
426 unsigned int time;
427 uint64_t loc;
428};
429
430
431struct EbmlGlobal
432{
John Koleszar75afcee2010-10-26 16:22:22 -0400433 int debug;
434
John Koleszardc666302010-10-20 12:05:48 -0400435 FILE *stream;
436 uint64_t last_pts_ms;
437 vpx_rational_t framerate;
438
439 /* These pointers are to the start of an element */
440 off_t position_reference;
441 off_t seek_info_pos;
442 off_t segment_info_pos;
443 off_t track_pos;
444 off_t cue_pos;
445 off_t cluster_pos;
446
John Koleszarc7c0c052010-10-27 10:05:55 -0400447 /* This pointer is to a specific element to be serialized */
448 off_t track_id_pos;
449
John Koleszardc666302010-10-20 12:05:48 -0400450 /* These pointers are to the size field of the element */
451 EbmlLoc startSegment;
452 EbmlLoc startCluster;
453
454 uint32_t cluster_timecode;
455 int cluster_open;
456
457 struct cue_entry *cue_list;
458 unsigned int cues;
459
460};
461
462
463void Ebml_Write(EbmlGlobal *glob, const void *buffer_in, unsigned long len)
464{
465 fwrite(buffer_in, 1, len, glob->stream);
466}
467
468
469void Ebml_Serialize(EbmlGlobal *glob, const void *buffer_in, unsigned long len)
470{
471 const unsigned char *q = (const unsigned char *)buffer_in + len - 1;
472
473 for(; len; len--)
474 Ebml_Write(glob, q--, 1);
475}
476
477
John Koleszarc7c0c052010-10-27 10:05:55 -0400478/* Need a fixed size serializer for the track ID. libmkv provdes a 64 bit
479 * one, but not a 32 bit one.
480 */
481static void Ebml_SerializeUnsigned32(EbmlGlobal *glob, unsigned long class_id, uint64_t ui)
482{
483 unsigned char sizeSerialized = 4 | 0x80;
484 Ebml_WriteID(glob, class_id);
485 Ebml_Serialize(glob, &sizeSerialized, 1);
486 Ebml_Serialize(glob, &ui, 4);
487}
488
489
John Koleszardc666302010-10-20 12:05:48 -0400490static void
491Ebml_StartSubElement(EbmlGlobal *glob, EbmlLoc *ebmlLoc,
492 unsigned long class_id)
493{
494 //todo this is always taking 8 bytes, this may need later optimization
495 //this is a key that says lenght unknown
496 unsigned long long unknownLen = LITERALU64(0x01FFFFFFFFFFFFFF);
497
498 Ebml_WriteID(glob, class_id);
499 *ebmlLoc = ftello(glob->stream);
500 Ebml_Serialize(glob, &unknownLen, 8);
501}
502
503static void
504Ebml_EndSubElement(EbmlGlobal *glob, EbmlLoc *ebmlLoc)
505{
506 off_t pos;
507 uint64_t size;
508
509 /* Save the current stream pointer */
510 pos = ftello(glob->stream);
511
512 /* Calculate the size of this element */
513 size = pos - *ebmlLoc - 8;
514 size |= LITERALU64(0x0100000000000000);
515
516 /* Seek back to the beginning of the element and write the new size */
517 fseeko(glob->stream, *ebmlLoc, SEEK_SET);
518 Ebml_Serialize(glob, &size, 8);
519
520 /* Reset the stream pointer */
521 fseeko(glob->stream, pos, SEEK_SET);
522}
523
524
525static void
526write_webm_seek_element(EbmlGlobal *ebml, unsigned long id, off_t pos)
527{
528 uint64_t offset = pos - ebml->position_reference;
529 EbmlLoc start;
530 Ebml_StartSubElement(ebml, &start, Seek);
531 Ebml_SerializeBinary(ebml, SeekID, id);
532 Ebml_SerializeUnsigned64(ebml, SeekPosition, offset);
533 Ebml_EndSubElement(ebml, &start);
534}
535
536
537static void
538write_webm_seek_info(EbmlGlobal *ebml)
539{
540
541 off_t pos;
542
543 /* Save the current stream pointer */
544 pos = ftello(ebml->stream);
545
546 if(ebml->seek_info_pos)
547 fseeko(ebml->stream, ebml->seek_info_pos, SEEK_SET);
548 else
549 ebml->seek_info_pos = pos;
550
551 {
552 EbmlLoc start;
553
554 Ebml_StartSubElement(ebml, &start, SeekHead);
555 write_webm_seek_element(ebml, Tracks, ebml->track_pos);
556 write_webm_seek_element(ebml, Cues, ebml->cue_pos);
557 write_webm_seek_element(ebml, Info, ebml->segment_info_pos);
558 Ebml_EndSubElement(ebml, &start);
559 }
560 {
561 //segment info
562 EbmlLoc startInfo;
563 uint64_t frame_time;
564
565 frame_time = (uint64_t)1000 * ebml->framerate.den
566 / ebml->framerate.num;
567 ebml->segment_info_pos = ftello(ebml->stream);
568 Ebml_StartSubElement(ebml, &startInfo, Info);
569 Ebml_SerializeUnsigned(ebml, TimecodeScale, 1000000);
570 Ebml_SerializeFloat(ebml, Segment_Duration,
571 ebml->last_pts_ms + frame_time);
John Koleszar75afcee2010-10-26 16:22:22 -0400572 Ebml_SerializeString(ebml, 0x4D80,
573 ebml->debug ? "vpxenc" : "vpxenc" VERSION_STRING);
574 Ebml_SerializeString(ebml, 0x5741,
575 ebml->debug ? "vpxenc" : "vpxenc" VERSION_STRING);
John Koleszardc666302010-10-20 12:05:48 -0400576 Ebml_EndSubElement(ebml, &startInfo);
577 }
578}
579
580
581static void
582write_webm_file_header(EbmlGlobal *glob,
583 const vpx_codec_enc_cfg_t *cfg,
584 const struct vpx_rational *fps)
585{
586 {
587 EbmlLoc start;
588 Ebml_StartSubElement(glob, &start, EBML);
589 Ebml_SerializeUnsigned(glob, EBMLVersion, 1);
590 Ebml_SerializeUnsigned(glob, EBMLReadVersion, 1); //EBML Read Version
591 Ebml_SerializeUnsigned(glob, EBMLMaxIDLength, 4); //EBML Max ID Length
592 Ebml_SerializeUnsigned(glob, EBMLMaxSizeLength, 8); //EBML Max Size Length
593 Ebml_SerializeString(glob, DocType, "webm"); //Doc Type
594 Ebml_SerializeUnsigned(glob, DocTypeVersion, 2); //Doc Type Version
595 Ebml_SerializeUnsigned(glob, DocTypeReadVersion, 2); //Doc Type Read Version
596 Ebml_EndSubElement(glob, &start);
597 }
598 {
599 Ebml_StartSubElement(glob, &glob->startSegment, Segment); //segment
600 glob->position_reference = ftello(glob->stream);
601 glob->framerate = *fps;
602 write_webm_seek_info(glob);
603
604 {
605 EbmlLoc trackStart;
606 glob->track_pos = ftello(glob->stream);
607 Ebml_StartSubElement(glob, &trackStart, Tracks);
608 {
609 unsigned int trackNumber = 1;
610 uint64_t trackID = 0;
611
612 EbmlLoc start;
613 Ebml_StartSubElement(glob, &start, TrackEntry);
614 Ebml_SerializeUnsigned(glob, TrackNumber, trackNumber);
John Koleszarc7c0c052010-10-27 10:05:55 -0400615 glob->track_id_pos = ftello(glob->stream);
616 Ebml_SerializeUnsigned32(glob, TrackUID, trackID);
John Koleszardc666302010-10-20 12:05:48 -0400617 Ebml_SerializeUnsigned(glob, TrackType, 1); //video is always 1
618 Ebml_SerializeString(glob, CodecID, "V_VP8");
619 {
620 unsigned int pixelWidth = cfg->g_w;
621 unsigned int pixelHeight = cfg->g_h;
622 float frameRate = (float)fps->num/(float)fps->den;
623
624 EbmlLoc videoStart;
625 Ebml_StartSubElement(glob, &videoStart, Video);
626 Ebml_SerializeUnsigned(glob, PixelWidth, pixelWidth);
627 Ebml_SerializeUnsigned(glob, PixelHeight, pixelHeight);
628 Ebml_SerializeFloat(glob, FrameRate, frameRate);
629 Ebml_EndSubElement(glob, &videoStart); //Video
630 }
631 Ebml_EndSubElement(glob, &start); //Track Entry
632 }
633 Ebml_EndSubElement(glob, &trackStart);
634 }
635 // segment element is open
636 }
637}
638
639
640static void
641write_webm_block(EbmlGlobal *glob,
642 const vpx_codec_enc_cfg_t *cfg,
643 const vpx_codec_cx_pkt_t *pkt)
644{
645 unsigned long block_length;
646 unsigned char track_number;
647 unsigned short block_timecode = 0;
648 unsigned char flags;
649 uint64_t pts_ms;
650 int start_cluster = 0, is_keyframe;
651
652 /* Calculate the PTS of this frame in milliseconds */
653 pts_ms = pkt->data.frame.pts * 1000
654 * (uint64_t)cfg->g_timebase.num / (uint64_t)cfg->g_timebase.den;
655 if(pts_ms <= glob->last_pts_ms)
656 pts_ms = glob->last_pts_ms + 1;
657 glob->last_pts_ms = pts_ms;
658
659 /* Calculate the relative time of this block */
660 if(pts_ms - glob->cluster_timecode > SHRT_MAX)
661 start_cluster = 1;
662 else
663 block_timecode = pts_ms - glob->cluster_timecode;
664
665 is_keyframe = (pkt->data.frame.flags & VPX_FRAME_IS_KEY);
666 if(start_cluster || is_keyframe)
667 {
668 if(glob->cluster_open)
669 Ebml_EndSubElement(glob, &glob->startCluster);
670
671 /* Open the new cluster */
672 block_timecode = 0;
673 glob->cluster_open = 1;
674 glob->cluster_timecode = pts_ms;
675 glob->cluster_pos = ftello(glob->stream);
676 Ebml_StartSubElement(glob, &glob->startCluster, Cluster); //cluster
677 Ebml_SerializeUnsigned(glob, Timecode, glob->cluster_timecode);
678
679 /* Save a cue point if this is a keyframe. */
680 if(is_keyframe)
681 {
682 struct cue_entry *cue;
683
684 glob->cue_list = realloc(glob->cue_list,
685 (glob->cues+1) * sizeof(struct cue_entry));
686 cue = &glob->cue_list[glob->cues];
687 cue->time = glob->cluster_timecode;
688 cue->loc = glob->cluster_pos;
689 glob->cues++;
690 }
691 }
692
693 /* Write the Simple Block */
694 Ebml_WriteID(glob, SimpleBlock);
695
696 block_length = pkt->data.frame.sz + 4;
697 block_length |= 0x10000000;
698 Ebml_Serialize(glob, &block_length, 4);
699
700 track_number = 1;
701 track_number |= 0x80;
702 Ebml_Write(glob, &track_number, 1);
703
704 Ebml_Serialize(glob, &block_timecode, 2);
705
706 flags = 0;
707 if(is_keyframe)
708 flags |= 0x80;
709 if(pkt->data.frame.flags & VPX_FRAME_IS_INVISIBLE)
710 flags |= 0x08;
711 Ebml_Write(glob, &flags, 1);
712
713 Ebml_Write(glob, pkt->data.frame.buf, pkt->data.frame.sz);
714}
715
716
717static void
John Koleszarc7c0c052010-10-27 10:05:55 -0400718write_webm_file_footer(EbmlGlobal *glob, long hash)
John Koleszardc666302010-10-20 12:05:48 -0400719{
720
721 if(glob->cluster_open)
722 Ebml_EndSubElement(glob, &glob->startCluster);
723
724 {
725 EbmlLoc start;
726 int i;
727
728 glob->cue_pos = ftello(glob->stream);
729 Ebml_StartSubElement(glob, &start, Cues);
730 for(i=0; i<glob->cues; i++)
731 {
732 struct cue_entry *cue = &glob->cue_list[i];
733 EbmlLoc start;
734
735 Ebml_StartSubElement(glob, &start, CuePoint);
736 {
737 EbmlLoc start;
738
739 Ebml_SerializeUnsigned(glob, CueTime, cue->time);
740
741 Ebml_StartSubElement(glob, &start, CueTrackPositions);
742 Ebml_SerializeUnsigned(glob, CueTrack, 1);
743 Ebml_SerializeUnsigned64(glob, CueClusterPosition,
744 cue->loc - glob->position_reference);
745 //Ebml_SerializeUnsigned(glob, CueBlockNumber, cue->blockNumber);
746 Ebml_EndSubElement(glob, &start);
747 }
748 Ebml_EndSubElement(glob, &start);
749 }
750 Ebml_EndSubElement(glob, &start);
751 }
752
753 Ebml_EndSubElement(glob, &glob->startSegment);
754
755 /* Patch up the seek info block */
756 write_webm_seek_info(glob);
John Koleszarc7c0c052010-10-27 10:05:55 -0400757
758 /* Patch up the track id */
759 fseeko(glob->stream, glob->track_id_pos, SEEK_SET);
760 Ebml_SerializeUnsigned32(glob, TrackUID, glob->debug ? 0xDEADBEEF : hash);
761
John Koleszardc666302010-10-20 12:05:48 -0400762 fseeko(glob->stream, 0, SEEK_END);
763}
764
765
John Koleszarc7c0c052010-10-27 10:05:55 -0400766/* Murmur hash derived from public domain reference implementation at
767 * http://sites.google.com/site/murmurhash/
768 */
769static unsigned int murmur ( const void * key, int len, unsigned int seed )
770{
771 const unsigned int m = 0x5bd1e995;
772 const int r = 24;
773
774 unsigned int h = seed ^ len;
775
776 const unsigned char * data = (const unsigned char *)key;
777
778 while(len >= 4)
779 {
780 unsigned int k;
781
782 k = data[0];
783 k |= data[1] << 8;
784 k |= data[2] << 16;
785 k |= data[3] << 24;
786
787 k *= m;
788 k ^= k >> r;
789 k *= m;
790
791 h *= m;
792 h ^= k;
793
794 data += 4;
795 len -= 4;
796 }
797
798 switch(len)
799 {
800 case 3: h ^= data[2] << 16;
801 case 2: h ^= data[1] << 8;
802 case 1: h ^= data[0];
803 h *= m;
804 };
805
806 h ^= h >> 13;
807 h *= m;
808 h ^= h >> 15;
809
810 return h;
811}
812
813
John Koleszar0ea50ce2010-05-18 11:58:33 -0400814#include "args.h"
815
John Koleszar75afcee2010-10-26 16:22:22 -0400816static const arg_def_t debugmode = ARG_DEF("D", "debug", 0,
817 "Debug mode (makes output deterministic)");
John Koleszar53291892010-10-22 14:48:21 -0400818static const arg_def_t outputfile = ARG_DEF("o", "output", 1,
819 "Output filename");
John Koleszar0ea50ce2010-05-18 11:58:33 -0400820static const arg_def_t use_yv12 = ARG_DEF(NULL, "yv12", 0,
821 "Input file is YV12 ");
822static const arg_def_t use_i420 = ARG_DEF(NULL, "i420", 0,
823 "Input file is I420 (default)");
824static const arg_def_t codecarg = ARG_DEF(NULL, "codec", 1,
825 "Codec to use");
826static const arg_def_t passes = ARG_DEF("p", "passes", 1,
827 "Number of passes (1/2)");
828static const arg_def_t pass_arg = ARG_DEF(NULL, "pass", 1,
829 "Pass to execute (1/2)");
830static const arg_def_t fpf_name = ARG_DEF(NULL, "fpf", 1,
831 "First pass statistics file name");
832static const arg_def_t limit = ARG_DEF(NULL, "limit", 1,
833 "Stop encoding after n input frames");
834static const arg_def_t deadline = ARG_DEF("d", "deadline", 1,
835 "Deadline per frame (usec)");
836static const arg_def_t best_dl = ARG_DEF(NULL, "best", 0,
837 "Use Best Quality Deadline");
838static const arg_def_t good_dl = ARG_DEF(NULL, "good", 0,
839 "Use Good Quality Deadline");
840static const arg_def_t rt_dl = ARG_DEF(NULL, "rt", 0,
841 "Use Realtime Quality Deadline");
842static const arg_def_t verbosearg = ARG_DEF("v", "verbose", 0,
843 "Show encoder parameters");
844static const arg_def_t psnrarg = ARG_DEF(NULL, "psnr", 0,
845 "Show PSNR in status line");
John Koleszar28f177c2010-10-21 16:52:14 -0400846static const arg_def_t framerate = ARG_DEF(NULL, "fps", 1,
Frank Galligan1258cf62010-10-06 12:51:00 -0400847 "Stream frame rate (rate/scale)");
John Koleszar456bfb12010-10-21 16:23:20 -0400848static const arg_def_t use_ivf = ARG_DEF(NULL, "ivf", 0,
849 "Output IVF (default is WebM)");
John Koleszar0ea50ce2010-05-18 11:58:33 -0400850static const arg_def_t *main_args[] =
851{
John Koleszar75afcee2010-10-26 16:22:22 -0400852 &debugmode,
John Koleszar53291892010-10-22 14:48:21 -0400853 &outputfile, &codecarg, &passes, &pass_arg, &fpf_name, &limit, &deadline,
854 &best_dl, &good_dl, &rt_dl,
John Koleszar456bfb12010-10-21 16:23:20 -0400855 &verbosearg, &psnrarg, &use_ivf, &framerate,
John Koleszar0ea50ce2010-05-18 11:58:33 -0400856 NULL
857};
858
859static const arg_def_t usage = ARG_DEF("u", "usage", 1,
860 "Usage profile number to use");
861static const arg_def_t threads = ARG_DEF("t", "threads", 1,
862 "Max number of threads to use");
863static const arg_def_t profile = ARG_DEF(NULL, "profile", 1,
864 "Bitstream profile number to use");
865static const arg_def_t width = ARG_DEF("w", "width", 1,
866 "Frame width");
867static const arg_def_t height = ARG_DEF("h", "height", 1,
868 "Frame height");
869static const arg_def_t timebase = ARG_DEF(NULL, "timebase", 1,
870 "Stream timebase (frame duration)");
871static const arg_def_t error_resilient = ARG_DEF(NULL, "error-resilient", 1,
872 "Enable error resiliency features");
873static const arg_def_t lag_in_frames = ARG_DEF(NULL, "lag-in-frames", 1,
874 "Max number of frames to lag");
875
876static const arg_def_t *global_args[] =
877{
878 &use_yv12, &use_i420, &usage, &threads, &profile,
Frank Galligan1258cf62010-10-06 12:51:00 -0400879 &width, &height, &timebase, &framerate, &error_resilient,
John Koleszar0ea50ce2010-05-18 11:58:33 -0400880 &lag_in_frames, NULL
881};
882
883static const arg_def_t dropframe_thresh = ARG_DEF(NULL, "drop-frame", 1,
884 "Temporal resampling threshold (buf %)");
885static const arg_def_t resize_allowed = ARG_DEF(NULL, "resize-allowed", 1,
886 "Spatial resampling enabled (bool)");
887static const arg_def_t resize_up_thresh = ARG_DEF(NULL, "resize-up", 1,
888 "Upscale threshold (buf %)");
889static const arg_def_t resize_down_thresh = ARG_DEF(NULL, "resize-down", 1,
890 "Downscale threshold (buf %)");
891static const arg_def_t end_usage = ARG_DEF(NULL, "end-usage", 1,
892 "VBR=0 | CBR=1");
893static const arg_def_t target_bitrate = ARG_DEF(NULL, "target-bitrate", 1,
894 "Bitrate (kbps)");
895static const arg_def_t min_quantizer = ARG_DEF(NULL, "min-q", 1,
896 "Minimum (best) quantizer");
897static const arg_def_t max_quantizer = ARG_DEF(NULL, "max-q", 1,
898 "Maximum (worst) quantizer");
899static const arg_def_t undershoot_pct = ARG_DEF(NULL, "undershoot-pct", 1,
900 "Datarate undershoot (min) target (%)");
901static const arg_def_t overshoot_pct = ARG_DEF(NULL, "overshoot-pct", 1,
902 "Datarate overshoot (max) target (%)");
903static const arg_def_t buf_sz = ARG_DEF(NULL, "buf-sz", 1,
904 "Client buffer size (ms)");
905static const arg_def_t buf_initial_sz = ARG_DEF(NULL, "buf-initial-sz", 1,
906 "Client initial buffer size (ms)");
907static const arg_def_t buf_optimal_sz = ARG_DEF(NULL, "buf-optimal-sz", 1,
908 "Client optimal buffer size (ms)");
909static const arg_def_t *rc_args[] =
910{
911 &dropframe_thresh, &resize_allowed, &resize_up_thresh, &resize_down_thresh,
912 &end_usage, &target_bitrate, &min_quantizer, &max_quantizer,
913 &undershoot_pct, &overshoot_pct, &buf_sz, &buf_initial_sz, &buf_optimal_sz,
914 NULL
915};
916
917
918static const arg_def_t bias_pct = ARG_DEF(NULL, "bias-pct", 1,
919 "CBR/VBR bias (0=CBR, 100=VBR)");
920static const arg_def_t minsection_pct = ARG_DEF(NULL, "minsection-pct", 1,
921 "GOP min bitrate (% of target)");
922static const arg_def_t maxsection_pct = ARG_DEF(NULL, "maxsection-pct", 1,
923 "GOP max bitrate (% of target)");
924static const arg_def_t *rc_twopass_args[] =
925{
926 &bias_pct, &minsection_pct, &maxsection_pct, NULL
927};
928
929
930static const arg_def_t kf_min_dist = ARG_DEF(NULL, "kf-min-dist", 1,
931 "Minimum keyframe interval (frames)");
932static const arg_def_t kf_max_dist = ARG_DEF(NULL, "kf-max-dist", 1,
933 "Maximum keyframe interval (frames)");
John Koleszarb1e36f22010-06-24 08:41:51 -0400934static const arg_def_t kf_disabled = ARG_DEF(NULL, "disable-kf", 0,
935 "Disable keyframe placement");
John Koleszar0ea50ce2010-05-18 11:58:33 -0400936static const arg_def_t *kf_args[] =
937{
John Koleszarb1e36f22010-06-24 08:41:51 -0400938 &kf_min_dist, &kf_max_dist, &kf_disabled, NULL
John Koleszar0ea50ce2010-05-18 11:58:33 -0400939};
940
941
942#if CONFIG_VP8_ENCODER
943static const arg_def_t noise_sens = ARG_DEF(NULL, "noise-sensitivity", 1,
944 "Noise sensitivity (frames to blur)");
945static const arg_def_t sharpness = ARG_DEF(NULL, "sharpness", 1,
946 "Filter sharpness (0-7)");
947static const arg_def_t static_thresh = ARG_DEF(NULL, "static-thresh", 1,
948 "Motion detection threshold");
949#endif
950
951#if CONFIG_VP8_ENCODER
952static const arg_def_t cpu_used = ARG_DEF(NULL, "cpu-used", 1,
953 "CPU Used (-16..16)");
954#endif
955
956
957#if CONFIG_VP8_ENCODER
958static const arg_def_t token_parts = ARG_DEF(NULL, "token-parts", 1,
959 "Number of token partitions to use, log2");
960static const arg_def_t auto_altref = ARG_DEF(NULL, "auto-alt-ref", 1,
961 "Enable automatic alt reference frames");
962static const arg_def_t arnr_maxframes = ARG_DEF(NULL, "arnr-maxframes", 1,
963 "alt_ref Max Frames");
964static const arg_def_t arnr_strength = ARG_DEF(NULL, "arnr-strength", 1,
965 "alt_ref Strength");
966static const arg_def_t arnr_type = ARG_DEF(NULL, "arnr-type", 1,
967 "alt_ref Type");
968
969static const arg_def_t *vp8_args[] =
970{
971 &cpu_used, &auto_altref, &noise_sens, &sharpness, &static_thresh,
972 &token_parts, &arnr_maxframes, &arnr_strength, &arnr_type, NULL
973};
974static const int vp8_arg_ctrl_map[] =
975{
976 VP8E_SET_CPUUSED, VP8E_SET_ENABLEAUTOALTREF,
977 VP8E_SET_NOISE_SENSITIVITY, VP8E_SET_SHARPNESS, VP8E_SET_STATIC_THRESHOLD,
978 VP8E_SET_TOKEN_PARTITIONS,
979 VP8E_SET_ARNR_MAXFRAMES, VP8E_SET_ARNR_STRENGTH , VP8E_SET_ARNR_TYPE, 0
980};
981#endif
982
983static const arg_def_t *no_args[] = { NULL };
984
985static void usage_exit()
986{
987 int i;
988
John Koleszar53291892010-10-22 14:48:21 -0400989 fprintf(stderr, "Usage: %s <options> -o dst_filename src_filename \n",
990 exec_name);
John Koleszar0ea50ce2010-05-18 11:58:33 -0400991
John Koleszar78f2d3e2010-10-11 09:41:14 -0400992 fprintf(stderr, "\nOptions:\n");
John Koleszar0ea50ce2010-05-18 11:58:33 -0400993 arg_show_usage(stdout, main_args);
John Koleszar78f2d3e2010-10-11 09:41:14 -0400994 fprintf(stderr, "\nEncoder Global Options:\n");
John Koleszar0ea50ce2010-05-18 11:58:33 -0400995 arg_show_usage(stdout, global_args);
John Koleszar78f2d3e2010-10-11 09:41:14 -0400996 fprintf(stderr, "\nRate Control Options:\n");
John Koleszar0ea50ce2010-05-18 11:58:33 -0400997 arg_show_usage(stdout, rc_args);
John Koleszar78f2d3e2010-10-11 09:41:14 -0400998 fprintf(stderr, "\nTwopass Rate Control Options:\n");
John Koleszar0ea50ce2010-05-18 11:58:33 -0400999 arg_show_usage(stdout, rc_twopass_args);
John Koleszar78f2d3e2010-10-11 09:41:14 -04001000 fprintf(stderr, "\nKeyframe Placement Options:\n");
John Koleszar0ea50ce2010-05-18 11:58:33 -04001001 arg_show_usage(stdout, kf_args);
1002#if CONFIG_VP8_ENCODER
John Koleszar78f2d3e2010-10-11 09:41:14 -04001003 fprintf(stderr, "\nVP8 Specific Options:\n");
John Koleszar0ea50ce2010-05-18 11:58:33 -04001004 arg_show_usage(stdout, vp8_args);
1005#endif
John Koleszar3245d462010-06-10 17:10:12 -04001006 fprintf(stderr, "\n"
John Koleszar0ea50ce2010-05-18 11:58:33 -04001007 "Included encoders:\n"
1008 "\n");
1009
1010 for (i = 0; i < sizeof(codecs) / sizeof(codecs[0]); i++)
John Koleszar3245d462010-06-10 17:10:12 -04001011 fprintf(stderr, " %-6s - %s\n",
John Koleszar0ea50ce2010-05-18 11:58:33 -04001012 codecs[i].name,
1013 vpx_codec_iface_name(codecs[i].iface));
1014
1015 exit(EXIT_FAILURE);
1016}
1017
1018#define ARG_CTRL_CNT_MAX 10
1019
1020
1021int main(int argc, const char **argv_)
1022{
1023 vpx_codec_ctx_t encoder;
1024 const char *in_fn = NULL, *out_fn = NULL, *stats_fn = NULL;
1025 int i;
1026 FILE *infile, *outfile;
1027 vpx_codec_enc_cfg_t cfg;
1028 vpx_codec_err_t res;
1029 int pass, one_pass_only = 0;
1030 stats_io_t stats;
1031 vpx_image_t raw;
1032 const struct codec_item *codec = codecs;
1033 int frame_avail, got_data;
1034
1035 struct arg arg;
1036 char **argv, **argi, **argj;
1037 int arg_usage = 0, arg_passes = 1, arg_deadline = 0;
1038 int arg_ctrls[ARG_CTRL_CNT_MAX][2], arg_ctrl_cnt = 0;
1039 int arg_limit = 0;
1040 static const arg_def_t **ctrl_args = no_args;
1041 static const int *ctrl_args_map = NULL;
1042 int verbose = 0, show_psnr = 0;
1043 int arg_use_i420 = 1;
1044 unsigned long cx_time = 0;
Timothy B. Terriberry44d89492010-05-26 18:27:51 -04001045 unsigned int file_type, fourcc;
1046 y4m_input y4m;
Frank Galligan1258cf62010-10-06 12:51:00 -04001047 struct vpx_rational arg_framerate = {30, 1};
1048 int arg_have_framerate = 0;
John Koleszar456bfb12010-10-21 16:23:20 -04001049 int write_webm = 1;
John Koleszardc666302010-10-20 12:05:48 -04001050 EbmlGlobal ebml = {0};
John Koleszarc7c0c052010-10-27 10:05:55 -04001051 uint32_t hash = 0;
John Koleszar0ea50ce2010-05-18 11:58:33 -04001052
1053 exec_name = argv_[0];
1054
1055 if (argc < 3)
1056 usage_exit();
1057
1058
1059 /* First parse the codec and usage values, because we want to apply other
1060 * parameters on top of the default configuration provided by the codec.
1061 */
1062 argv = argv_dup(argc - 1, argv_ + 1);
1063
1064 for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step)
1065 {
1066 arg.argv_step = 1;
1067
1068 if (arg_match(&arg, &codecarg, argi))
1069 {
1070 int j, k = -1;
1071
1072 for (j = 0; j < sizeof(codecs) / sizeof(codecs[0]); j++)
1073 if (!strcmp(codecs[j].name, arg.val))
1074 k = j;
1075
1076 if (k >= 0)
1077 codec = codecs + k;
1078 else
1079 die("Error: Unrecognized argument (%s) to --codec\n",
1080 arg.val);
1081
1082 }
1083 else if (arg_match(&arg, &passes, argi))
1084 {
1085 arg_passes = arg_parse_uint(&arg);
1086
1087 if (arg_passes < 1 || arg_passes > 2)
1088 die("Error: Invalid number of passes (%d)\n", arg_passes);
1089 }
1090 else if (arg_match(&arg, &pass_arg, argi))
1091 {
1092 one_pass_only = arg_parse_uint(&arg);
1093
1094 if (one_pass_only < 1 || one_pass_only > 2)
1095 die("Error: Invalid pass selected (%d)\n", one_pass_only);
1096 }
1097 else if (arg_match(&arg, &fpf_name, argi))
1098 stats_fn = arg.val;
1099 else if (arg_match(&arg, &usage, argi))
1100 arg_usage = arg_parse_uint(&arg);
1101 else if (arg_match(&arg, &deadline, argi))
1102 arg_deadline = arg_parse_uint(&arg);
1103 else if (arg_match(&arg, &best_dl, argi))
1104 arg_deadline = VPX_DL_BEST_QUALITY;
1105 else if (arg_match(&arg, &good_dl, argi))
1106 arg_deadline = VPX_DL_GOOD_QUALITY;
1107 else if (arg_match(&arg, &rt_dl, argi))
1108 arg_deadline = VPX_DL_REALTIME;
1109 else if (arg_match(&arg, &use_yv12, argi))
1110 {
1111 arg_use_i420 = 0;
1112 }
1113 else if (arg_match(&arg, &use_i420, argi))
1114 {
1115 arg_use_i420 = 1;
1116 }
1117 else if (arg_match(&arg, &verbosearg, argi))
1118 verbose = 1;
1119 else if (arg_match(&arg, &limit, argi))
1120 arg_limit = arg_parse_uint(&arg);
1121 else if (arg_match(&arg, &psnrarg, argi))
1122 show_psnr = 1;
Frank Galligan1258cf62010-10-06 12:51:00 -04001123 else if (arg_match(&arg, &framerate, argi))
1124 {
1125 arg_framerate = arg_parse_rational(&arg);
1126 arg_have_framerate = 1;
1127 }
John Koleszar456bfb12010-10-21 16:23:20 -04001128 else if (arg_match(&arg, &use_ivf, argi))
1129 write_webm = 0;
John Koleszar53291892010-10-22 14:48:21 -04001130 else if (arg_match(&arg, &outputfile, argi))
1131 out_fn = arg.val;
John Koleszar75afcee2010-10-26 16:22:22 -04001132 else if (arg_match(&arg, &debugmode, argi))
1133 ebml.debug = 1;
John Koleszar0ea50ce2010-05-18 11:58:33 -04001134 else
1135 argj++;
1136 }
1137
1138 /* Ensure that --passes and --pass are consistent. If --pass is set and --passes=2,
1139 * ensure --fpf was set.
1140 */
1141 if (one_pass_only)
1142 {
1143 /* DWIM: Assume the user meant passes=2 if pass=2 is specified */
1144 if (one_pass_only > arg_passes)
1145 {
John Koleszar3245d462010-06-10 17:10:12 -04001146 fprintf(stderr, "Warning: Assuming --pass=%d implies --passes=%d\n",
John Koleszar0ea50ce2010-05-18 11:58:33 -04001147 one_pass_only, one_pass_only);
1148 arg_passes = one_pass_only;
1149 }
1150
1151 if (arg_passes == 2 && !stats_fn)
1152 die("Must specify --fpf when --pass=%d and --passes=2\n", one_pass_only);
1153 }
1154
1155 /* Populate encoder configuration */
1156 res = vpx_codec_enc_config_default(codec->iface, &cfg, arg_usage);
1157
1158 if (res)
1159 {
John Koleszar3245d462010-06-10 17:10:12 -04001160 fprintf(stderr, "Failed to get config: %s\n",
1161 vpx_codec_err_to_string(res));
John Koleszar0ea50ce2010-05-18 11:58:33 -04001162 return EXIT_FAILURE;
1163 }
1164
Frank Galligan1258cf62010-10-06 12:51:00 -04001165 /* Change the default timebase to a high enough value so that the encoder
1166 * will always create strictly increasing timestamps.
1167 */
1168 cfg.g_timebase.den = 1000;
1169
John Koleszar0ea50ce2010-05-18 11:58:33 -04001170 /* Now parse the remainder of the parameters. */
1171 for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step)
1172 {
1173 arg.argv_step = 1;
1174
1175 if (0);
1176 else if (arg_match(&arg, &threads, argi))
1177 cfg.g_threads = arg_parse_uint(&arg);
1178 else if (arg_match(&arg, &profile, argi))
1179 cfg.g_profile = arg_parse_uint(&arg);
1180 else if (arg_match(&arg, &width, argi))
1181 cfg.g_w = arg_parse_uint(&arg);
1182 else if (arg_match(&arg, &height, argi))
1183 cfg.g_h = arg_parse_uint(&arg);
1184 else if (arg_match(&arg, &timebase, argi))
1185 cfg.g_timebase = arg_parse_rational(&arg);
1186 else if (arg_match(&arg, &error_resilient, argi))
1187 cfg.g_error_resilient = arg_parse_uint(&arg);
1188 else if (arg_match(&arg, &lag_in_frames, argi))
1189 cfg.g_lag_in_frames = arg_parse_uint(&arg);
1190 else if (arg_match(&arg, &dropframe_thresh, argi))
1191 cfg.rc_dropframe_thresh = arg_parse_uint(&arg);
1192 else if (arg_match(&arg, &resize_allowed, argi))
1193 cfg.rc_resize_allowed = arg_parse_uint(&arg);
1194 else if (arg_match(&arg, &resize_up_thresh, argi))
1195 cfg.rc_resize_up_thresh = arg_parse_uint(&arg);
1196 else if (arg_match(&arg, &resize_down_thresh, argi))
1197 cfg.rc_resize_down_thresh = arg_parse_uint(&arg);
1198 else if (arg_match(&arg, &resize_down_thresh, argi))
1199 cfg.rc_resize_down_thresh = arg_parse_uint(&arg);
1200 else if (arg_match(&arg, &end_usage, argi))
1201 cfg.rc_end_usage = arg_parse_uint(&arg);
1202 else if (arg_match(&arg, &target_bitrate, argi))
1203 cfg.rc_target_bitrate = arg_parse_uint(&arg);
1204 else if (arg_match(&arg, &min_quantizer, argi))
1205 cfg.rc_min_quantizer = arg_parse_uint(&arg);
1206 else if (arg_match(&arg, &max_quantizer, argi))
1207 cfg.rc_max_quantizer = arg_parse_uint(&arg);
1208 else if (arg_match(&arg, &undershoot_pct, argi))
1209 cfg.rc_undershoot_pct = arg_parse_uint(&arg);
1210 else if (arg_match(&arg, &overshoot_pct, argi))
1211 cfg.rc_overshoot_pct = arg_parse_uint(&arg);
1212 else if (arg_match(&arg, &buf_sz, argi))
1213 cfg.rc_buf_sz = arg_parse_uint(&arg);
1214 else if (arg_match(&arg, &buf_initial_sz, argi))
1215 cfg.rc_buf_initial_sz = arg_parse_uint(&arg);
1216 else if (arg_match(&arg, &buf_optimal_sz, argi))
1217 cfg.rc_buf_optimal_sz = arg_parse_uint(&arg);
1218 else if (arg_match(&arg, &bias_pct, argi))
1219 {
1220 cfg.rc_2pass_vbr_bias_pct = arg_parse_uint(&arg);
1221
1222 if (arg_passes < 2)
John Koleszar3245d462010-06-10 17:10:12 -04001223 fprintf(stderr,
1224 "Warning: option %s ignored in one-pass mode.\n",
1225 arg.name);
John Koleszar0ea50ce2010-05-18 11:58:33 -04001226 }
1227 else if (arg_match(&arg, &minsection_pct, argi))
1228 {
1229 cfg.rc_2pass_vbr_minsection_pct = arg_parse_uint(&arg);
1230
1231 if (arg_passes < 2)
John Koleszar3245d462010-06-10 17:10:12 -04001232 fprintf(stderr,
1233 "Warning: option %s ignored in one-pass mode.\n",
1234 arg.name);
John Koleszar0ea50ce2010-05-18 11:58:33 -04001235 }
1236 else if (arg_match(&arg, &maxsection_pct, argi))
1237 {
1238 cfg.rc_2pass_vbr_maxsection_pct = arg_parse_uint(&arg);
1239
1240 if (arg_passes < 2)
John Koleszar3245d462010-06-10 17:10:12 -04001241 fprintf(stderr,
1242 "Warning: option %s ignored in one-pass mode.\n",
1243 arg.name);
John Koleszar0ea50ce2010-05-18 11:58:33 -04001244 }
1245 else if (arg_match(&arg, &kf_min_dist, argi))
1246 cfg.kf_min_dist = arg_parse_uint(&arg);
1247 else if (arg_match(&arg, &kf_max_dist, argi))
1248 cfg.kf_max_dist = arg_parse_uint(&arg);
John Koleszarb1e36f22010-06-24 08:41:51 -04001249 else if (arg_match(&arg, &kf_disabled, argi))
1250 cfg.kf_mode = VPX_KF_DISABLED;
John Koleszar0ea50ce2010-05-18 11:58:33 -04001251 else
1252 argj++;
1253 }
1254
1255 /* Handle codec specific options */
1256#if CONFIG_VP8_ENCODER
1257
1258 if (codec->iface == &vpx_codec_vp8_cx_algo)
1259 {
1260 ctrl_args = vp8_args;
1261 ctrl_args_map = vp8_arg_ctrl_map;
1262 }
1263
1264#endif
1265
1266 for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step)
1267 {
1268 int match = 0;
1269
1270 arg.argv_step = 1;
1271
1272 for (i = 0; ctrl_args[i]; i++)
1273 {
1274 if (arg_match(&arg, ctrl_args[i], argi))
1275 {
1276 match = 1;
1277
1278 if (arg_ctrl_cnt < ARG_CTRL_CNT_MAX)
1279 {
1280 arg_ctrls[arg_ctrl_cnt][0] = ctrl_args_map[i];
1281 arg_ctrls[arg_ctrl_cnt][1] = arg_parse_int(&arg);
1282 arg_ctrl_cnt++;
1283 }
1284 }
1285 }
1286
1287 if (!match)
1288 argj++;
1289 }
1290
1291 /* Check for unrecognized options */
1292 for (argi = argv; *argi; argi++)
John Koleszar3245d462010-06-10 17:10:12 -04001293 if (argi[0][0] == '-' && argi[0][1])
John Koleszar0ea50ce2010-05-18 11:58:33 -04001294 die("Error: Unrecognized option %s\n", *argi);
1295
1296 /* Handle non-option arguments */
1297 in_fn = argv[0];
John Koleszar0ea50ce2010-05-18 11:58:33 -04001298
John Koleszar53291892010-10-22 14:48:21 -04001299 if (!in_fn)
John Koleszar0ea50ce2010-05-18 11:58:33 -04001300 usage_exit();
1301
John Koleszar53291892010-10-22 14:48:21 -04001302 if(!out_fn)
1303 die("Error: Output file is required (specify with -o)\n");
1304
John Koleszar0ea50ce2010-05-18 11:58:33 -04001305 memset(&stats, 0, sizeof(stats));
1306
1307 for (pass = one_pass_only ? one_pass_only - 1 : 0; pass < arg_passes; pass++)
1308 {
1309 int frames_in = 0, frames_out = 0;
1310 unsigned long nbytes = 0;
John Koleszar3245d462010-06-10 17:10:12 -04001311 struct detect_buffer detect;
John Koleszar0ea50ce2010-05-18 11:58:33 -04001312
John Koleszar3245d462010-06-10 17:10:12 -04001313 /* Parse certain options from the input file, if possible */
1314 infile = strcmp(in_fn, "-") ? fopen(in_fn, "rb") : stdin;
John Koleszar0ea50ce2010-05-18 11:58:33 -04001315
1316 if (!infile)
1317 {
John Koleszar3245d462010-06-10 17:10:12 -04001318 fprintf(stderr, "Failed to open input file\n");
John Koleszar0ea50ce2010-05-18 11:58:33 -04001319 return EXIT_FAILURE;
1320 }
1321
John Koleszar3245d462010-06-10 17:10:12 -04001322 fread(detect.buf, 1, 4, infile);
1323 detect.valid = 0;
1324
1325 if (file_is_y4m(infile, &y4m, detect.buf))
Timothy B. Terriberry44d89492010-05-26 18:27:51 -04001326 {
Tom Finegane703af92010-06-16 13:24:55 -04001327 if (y4m_input_open(&y4m, infile, detect.buf, 4) >= 0)
John Koleszar3245d462010-06-10 17:10:12 -04001328 {
Tom Finegane703af92010-06-16 13:24:55 -04001329 file_type = FILE_TYPE_Y4M;
1330 cfg.g_w = y4m.pic_w;
1331 cfg.g_h = y4m.pic_h;
Frank Galligan1258cf62010-10-06 12:51:00 -04001332
Tom Finegane703af92010-06-16 13:24:55 -04001333 /* Use the frame rate from the file only if none was specified
1334 * on the command-line.
1335 */
Frank Galligan1258cf62010-10-06 12:51:00 -04001336 if (!arg_have_framerate)
Tom Finegane703af92010-06-16 13:24:55 -04001337 {
Frank Galligan1258cf62010-10-06 12:51:00 -04001338 arg_framerate.num = y4m.fps_n;
1339 arg_framerate.den = y4m.fps_d;
Tom Finegane703af92010-06-16 13:24:55 -04001340 }
Frank Galligan1258cf62010-10-06 12:51:00 -04001341
Tom Finegane703af92010-06-16 13:24:55 -04001342 arg_use_i420 = 0;
John Koleszar3245d462010-06-10 17:10:12 -04001343 }
Tom Finegane703af92010-06-16 13:24:55 -04001344 else
1345 {
1346 fprintf(stderr, "Unsupported Y4M stream.\n");
1347 return EXIT_FAILURE;
1348 }
Timothy B. Terriberry44d89492010-05-26 18:27:51 -04001349 }
John Koleszar3245d462010-06-10 17:10:12 -04001350 else if (file_is_ivf(infile, &fourcc, &cfg.g_w, &cfg.g_h, detect.buf))
Timothy B. Terriberry44d89492010-05-26 18:27:51 -04001351 {
John Koleszar3245d462010-06-10 17:10:12 -04001352 file_type = FILE_TYPE_IVF;
1353 switch (fourcc)
1354 {
1355 case 0x32315659:
1356 arg_use_i420 = 0;
1357 break;
1358 case 0x30323449:
1359 arg_use_i420 = 1;
1360 break;
1361 default:
1362 fprintf(stderr, "Unsupported fourcc (%08x) in IVF\n", fourcc);
1363 return EXIT_FAILURE;
1364 }
1365 }
1366 else
1367 {
1368 file_type = FILE_TYPE_RAW;
1369 detect.valid = 1;
1370 }
1371#define SHOW(field) fprintf(stderr, " %-28s = %d\n", #field, cfg.field)
1372
1373 if (verbose && pass == 0)
1374 {
1375 fprintf(stderr, "Codec: %s\n", vpx_codec_iface_name(codec->iface));
1376 fprintf(stderr, "Source file: %s Format: %s\n", in_fn,
1377 arg_use_i420 ? "I420" : "YV12");
1378 fprintf(stderr, "Destination file: %s\n", out_fn);
1379 fprintf(stderr, "Encoder parameters:\n");
1380
1381 SHOW(g_usage);
1382 SHOW(g_threads);
1383 SHOW(g_profile);
1384 SHOW(g_w);
1385 SHOW(g_h);
1386 SHOW(g_timebase.num);
1387 SHOW(g_timebase.den);
1388 SHOW(g_error_resilient);
1389 SHOW(g_pass);
1390 SHOW(g_lag_in_frames);
1391 SHOW(rc_dropframe_thresh);
1392 SHOW(rc_resize_allowed);
1393 SHOW(rc_resize_up_thresh);
1394 SHOW(rc_resize_down_thresh);
1395 SHOW(rc_end_usage);
1396 SHOW(rc_target_bitrate);
1397 SHOW(rc_min_quantizer);
1398 SHOW(rc_max_quantizer);
1399 SHOW(rc_undershoot_pct);
1400 SHOW(rc_overshoot_pct);
1401 SHOW(rc_buf_sz);
1402 SHOW(rc_buf_initial_sz);
1403 SHOW(rc_buf_optimal_sz);
1404 SHOW(rc_2pass_vbr_bias_pct);
1405 SHOW(rc_2pass_vbr_minsection_pct);
1406 SHOW(rc_2pass_vbr_maxsection_pct);
1407 SHOW(kf_mode);
1408 SHOW(kf_min_dist);
1409 SHOW(kf_max_dist);
Timothy B. Terriberry44d89492010-05-26 18:27:51 -04001410 }
1411
John Koleszardf2c62d2010-06-14 08:33:54 -04001412 if(pass == (one_pass_only ? one_pass_only - 1 : 0)) {
John Koleszar3245d462010-06-10 17:10:12 -04001413 if (file_type == FILE_TYPE_Y4M)
1414 /*The Y4M reader does its own allocation.
1415 Just initialize this here to avoid problems if we never read any
1416 frames.*/
1417 memset(&raw, 0, sizeof(raw));
1418 else
1419 vpx_img_alloc(&raw, arg_use_i420 ? VPX_IMG_FMT_I420 : VPX_IMG_FMT_YV12,
1420 cfg.g_w, cfg.g_h, 1);
John Koleszar3245d462010-06-10 17:10:12 -04001421 }
1422
1423 outfile = strcmp(out_fn, "-") ? fopen(out_fn, "wb") : stdout;
John Koleszar0ea50ce2010-05-18 11:58:33 -04001424
1425 if (!outfile)
1426 {
John Koleszar3245d462010-06-10 17:10:12 -04001427 fprintf(stderr, "Failed to open output file\n");
John Koleszar0ea50ce2010-05-18 11:58:33 -04001428 return EXIT_FAILURE;
1429 }
1430
John Koleszar0a6bf292010-10-22 14:57:02 -04001431 if(write_webm && fseek(outfile, 0, SEEK_CUR))
1432 {
1433 fprintf(stderr, "WebM output to pipes not supported.\n");
1434 return EXIT_FAILURE;
1435 }
1436
John Koleszar0ea50ce2010-05-18 11:58:33 -04001437 if (stats_fn)
1438 {
1439 if (!stats_open_file(&stats, stats_fn, pass))
1440 {
John Koleszar3245d462010-06-10 17:10:12 -04001441 fprintf(stderr, "Failed to open statistics store\n");
John Koleszar0ea50ce2010-05-18 11:58:33 -04001442 return EXIT_FAILURE;
1443 }
1444 }
1445 else
1446 {
1447 if (!stats_open_mem(&stats, pass))
1448 {
John Koleszar3245d462010-06-10 17:10:12 -04001449 fprintf(stderr, "Failed to open statistics store\n");
John Koleszar0ea50ce2010-05-18 11:58:33 -04001450 return EXIT_FAILURE;
1451 }
1452 }
1453
1454 cfg.g_pass = arg_passes == 2
1455 ? pass ? VPX_RC_LAST_PASS : VPX_RC_FIRST_PASS
1456 : VPX_RC_ONE_PASS;
1457#if VPX_ENCODER_ABI_VERSION > (1 + VPX_CODEC_ABI_VERSION)
1458
1459 if (pass)
1460 {
1461 cfg.rc_twopass_stats_in = stats_get(&stats);
1462 }
1463
1464#endif
1465
John Koleszardc666302010-10-20 12:05:48 -04001466 if(write_webm)
1467 {
1468 ebml.stream = outfile;
1469 write_webm_file_header(&ebml, &cfg, &arg_framerate);
1470 }
1471 else
1472 write_ivf_file_header(outfile, &cfg, codec->fourcc, 0);
John Koleszar0ea50ce2010-05-18 11:58:33 -04001473
1474
1475 /* Construct Encoder Context */
John Koleszar0ea50ce2010-05-18 11:58:33 -04001476 vpx_codec_enc_init(&encoder, codec->iface, &cfg,
1477 show_psnr ? VPX_CODEC_USE_PSNR : 0);
1478 ctx_exit_on_error(&encoder, "Failed to initialize encoder");
1479
1480 /* Note that we bypass the vpx_codec_control wrapper macro because
1481 * we're being clever to store the control IDs in an array. Real
1482 * applications will want to make use of the enumerations directly
1483 */
1484 for (i = 0; i < arg_ctrl_cnt; i++)
1485 {
1486 if (vpx_codec_control_(&encoder, arg_ctrls[i][0], arg_ctrls[i][1]))
John Koleszar3245d462010-06-10 17:10:12 -04001487 fprintf(stderr, "Error: Tried to set control %d = %d\n",
1488 arg_ctrls[i][0], arg_ctrls[i][1]);
John Koleszar0ea50ce2010-05-18 11:58:33 -04001489
1490 ctx_exit_on_error(&encoder, "Failed to control codec");
1491 }
1492
1493 frame_avail = 1;
1494 got_data = 0;
1495
1496 while (frame_avail || got_data)
1497 {
1498 vpx_codec_iter_t iter = NULL;
1499 const vpx_codec_cx_pkt_t *pkt;
1500 struct vpx_usec_timer timer;
Frank Galligan1258cf62010-10-06 12:51:00 -04001501 int64_t frame_start;
John Koleszar0ea50ce2010-05-18 11:58:33 -04001502
1503 if (!arg_limit || frames_in < arg_limit)
1504 {
John Koleszar3245d462010-06-10 17:10:12 -04001505 frame_avail = read_frame(infile, &raw, file_type, &y4m,
1506 &detect);
John Koleszar0ea50ce2010-05-18 11:58:33 -04001507
1508 if (frame_avail)
1509 frames_in++;
1510
John Koleszar3245d462010-06-10 17:10:12 -04001511 fprintf(stderr,
1512 "\rPass %d/%d frame %4d/%-4d %7ldB \033[K", pass + 1,
1513 arg_passes, frames_in, frames_out, nbytes);
John Koleszar0ea50ce2010-05-18 11:58:33 -04001514 }
1515 else
1516 frame_avail = 0;
1517
1518 vpx_usec_timer_start(&timer);
1519
Frank Galligan1258cf62010-10-06 12:51:00 -04001520 frame_start = (cfg.g_timebase.den * (int64_t)(frames_in - 1)
1521 * arg_framerate.den) / cfg.g_timebase.num / arg_framerate.num;
1522 vpx_codec_encode(&encoder, frame_avail ? &raw : NULL, frame_start,
1523 cfg.g_timebase.den * arg_framerate.den
1524 / cfg.g_timebase.num / arg_framerate.num,
1525 0, arg_deadline);
John Koleszar0ea50ce2010-05-18 11:58:33 -04001526 vpx_usec_timer_mark(&timer);
1527 cx_time += vpx_usec_timer_elapsed(&timer);
1528 ctx_exit_on_error(&encoder, "Failed to encode frame");
1529 got_data = 0;
1530
1531 while ((pkt = vpx_codec_get_cx_data(&encoder, &iter)))
1532 {
1533 got_data = 1;
John Koleszar0ea50ce2010-05-18 11:58:33 -04001534
1535 switch (pkt->kind)
1536 {
1537 case VPX_CODEC_CX_FRAME_PKT:
1538 frames_out++;
John Koleszar3245d462010-06-10 17:10:12 -04001539 fprintf(stderr, " %6luF",
1540 (unsigned long)pkt->data.frame.sz);
John Koleszarc7c0c052010-10-27 10:05:55 -04001541
John Koleszardc666302010-10-20 12:05:48 -04001542 if(write_webm)
1543 {
John Koleszarc7c0c052010-10-27 10:05:55 -04001544 /* Update the hash */
1545 if(!ebml.debug)
1546 hash = murmur(pkt->data.frame.buf,
1547 pkt->data.frame.sz, hash);
1548
John Koleszardc666302010-10-20 12:05:48 -04001549 write_webm_block(&ebml, &cfg, pkt);
1550 }
1551 else
1552 {
1553 write_ivf_frame_header(outfile, pkt);
1554 fwrite(pkt->data.frame.buf, 1, pkt->data.frame.sz, outfile);
1555 }
Yaowu Xua7bb3362010-05-27 10:32:40 -07001556 nbytes += pkt->data.raw.sz;
John Koleszar0ea50ce2010-05-18 11:58:33 -04001557 break;
1558 case VPX_CODEC_STATS_PKT:
1559 frames_out++;
John Koleszar3245d462010-06-10 17:10:12 -04001560 fprintf(stderr, " %6luS",
John Koleszar0ea50ce2010-05-18 11:58:33 -04001561 (unsigned long)pkt->data.twopass_stats.sz);
1562 stats_write(&stats,
1563 pkt->data.twopass_stats.buf,
1564 pkt->data.twopass_stats.sz);
Yaowu Xua7bb3362010-05-27 10:32:40 -07001565 nbytes += pkt->data.raw.sz;
John Koleszar0ea50ce2010-05-18 11:58:33 -04001566 break;
1567 case VPX_CODEC_PSNR_PKT:
1568
1569 if (show_psnr)
1570 {
1571 int i;
1572
1573 for (i = 0; i < 4; i++)
John Koleszar3245d462010-06-10 17:10:12 -04001574 fprintf(stderr, "%.3lf ", pkt->data.psnr.psnr[i]);
John Koleszar0ea50ce2010-05-18 11:58:33 -04001575 }
1576
1577 break;
1578 default:
1579 break;
1580 }
1581 }
1582
1583 fflush(stdout);
1584 }
1585
John Koleszar3245d462010-06-10 17:10:12 -04001586 fprintf(stderr,
1587 "\rPass %d/%d frame %4d/%-4d %7ldB %7ldb/f %7"PRId64"b/s"
John Koleszar0ea50ce2010-05-18 11:58:33 -04001588 " %7lu %s (%.2f fps)\033[K", pass + 1,
1589 arg_passes, frames_in, frames_out, nbytes, nbytes * 8 / frames_in,
Frank Galligan1258cf62010-10-06 12:51:00 -04001590 nbytes * 8 *(int64_t)arg_framerate.num / arg_framerate.den / frames_in,
John Koleszar0ea50ce2010-05-18 11:58:33 -04001591 cx_time > 9999999 ? cx_time / 1000 : cx_time,
1592 cx_time > 9999999 ? "ms" : "us",
1593 (float)frames_in * 1000000.0 / (float)cx_time);
1594
1595 vpx_codec_destroy(&encoder);
1596
1597 fclose(infile);
1598
John Koleszardc666302010-10-20 12:05:48 -04001599 if(write_webm)
1600 {
John Koleszarc7c0c052010-10-27 10:05:55 -04001601 write_webm_file_footer(&ebml, hash);
John Koleszardc666302010-10-20 12:05:48 -04001602 }
1603 else
1604 {
1605 if (!fseek(outfile, 0, SEEK_SET))
1606 write_ivf_file_header(outfile, &cfg, codec->fourcc, frames_out);
1607 }
John Koleszar0ea50ce2010-05-18 11:58:33 -04001608
1609 fclose(outfile);
1610 stats_close(&stats);
John Koleszar3245d462010-06-10 17:10:12 -04001611 fprintf(stderr, "\n");
John Koleszar0ea50ce2010-05-18 11:58:33 -04001612
1613 if (one_pass_only)
1614 break;
1615 }
1616
1617 vpx_img_free(&raw);
1618 free(argv);
1619 return EXIT_SUCCESS;
1620}