WebM VP8 Codec SDK
vpxenc
1 /*
2  * Copyright (c) 2010 The WebM project authors. All Rights Reserved.
3  *
4  * Use of this source code is governed by a BSD-style license
5  * that can be found in the LICENSE file in the root of the source
6  * tree. An additional intellectual property rights grant can be found
7  * in the file PATENTS. All contributing project authors may
8  * be found in the AUTHORS file in the root of the source tree.
9  */
10 
11 #include "vpx_config.h"
12 
13 #if defined(_WIN32) || defined(__OS2__) || !CONFIG_OS_SUPPORT
14 #define USE_POSIX_MMAP 0
15 #else
16 #define USE_POSIX_MMAP 1
17 #endif
18 
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <stdarg.h>
22 #include <string.h>
23 #include <limits.h>
24 #include <assert.h>
25 #include "vpx/vpx_encoder.h"
26 #if CONFIG_DECODERS
27 #include "vpx/vpx_decoder.h"
28 #endif
29 #if USE_POSIX_MMAP
30 #include <sys/types.h>
31 #include <sys/stat.h>
32 #include <sys/mman.h>
33 #include <fcntl.h>
34 #include <unistd.h>
35 #endif
36 
37 #if CONFIG_VP8_ENCODER || CONFIG_VP9_ENCODER
38 #include "vpx/vp8cx.h"
39 #endif
40 #if CONFIG_VP8_DECODER || CONFIG_VP9_DECODER
41 #include "vpx/vp8dx.h"
42 #endif
43 
44 #include "vpx_ports/mem_ops.h"
45 #include "vpx_ports/vpx_timer.h"
46 #include "tools_common.h"
47 #include "y4minput.h"
48 #include "libmkv/EbmlWriter.h"
49 #include "libmkv/EbmlIDs.h"
50 #include "third_party/libyuv/include/libyuv/scale.h"
51 
52 /* Need special handling of these functions on Windows */
53 #if defined(_MSC_VER)
54 /* MSVS doesn't define off_t, and uses _f{seek,tell}i64 */
55 typedef __int64 off_t;
56 #define fseeko _fseeki64
57 #define ftello _ftelli64
58 #elif defined(_WIN32)
59 /* MinGW defines off_t as long
60  and uses f{seek,tell}o64/off64_t for large files */
61 #define fseeko fseeko64
62 #define ftello ftello64
63 #define off_t off64_t
64 #endif
65 
66 #define LITERALU64(hi,lo) ((((uint64_t)hi)<<32)|lo)
67 
68 /* We should use 32-bit file operations in WebM file format
69  * when building ARM executable file (.axf) with RVCT */
70 #if !CONFIG_OS_SUPPORT
71 typedef long off_t;
72 #define fseeko fseek
73 #define ftello ftell
74 #endif
75 
76 /* Swallow warnings about unused results of fread/fwrite */
77 static size_t wrap_fread(void *ptr, size_t size, size_t nmemb,
78  FILE *stream) {
79  return fread(ptr, size, nmemb, stream);
80 }
81 #define fread wrap_fread
82 
83 static size_t wrap_fwrite(const void *ptr, size_t size, size_t nmemb,
84  FILE *stream) {
85  return fwrite(ptr, size, nmemb, stream);
86 }
87 #define fwrite wrap_fwrite
88 
89 
90 static const char *exec_name;
91 
92 #define VP8_FOURCC (0x30385056)
93 #define VP9_FOURCC (0x30395056)
94 static const struct codec_item {
95  char const *name;
96  const vpx_codec_iface_t *(*iface)(void);
97  const vpx_codec_iface_t *(*dx_iface)(void);
98  unsigned int fourcc;
99 } codecs[] = {
100 #if CONFIG_VP8_ENCODER && CONFIG_VP8_DECODER
101  {"vp8", &vpx_codec_vp8_cx, &vpx_codec_vp8_dx, VP8_FOURCC},
102 #elif CONFIG_VP8_ENCODER && !CONFIG_VP8_DECODER
103  {"vp8", &vpx_codec_vp8_cx, NULL, VP8_FOURCC},
104 #endif
105 #if CONFIG_VP9_ENCODER && CONFIG_VP9_DECODER
106  {"vp9", &vpx_codec_vp9_cx, &vpx_codec_vp9_dx, VP9_FOURCC},
107 #elif CONFIG_VP9_ENCODER && !CONFIG_VP9_DECODER
108  {"vp9", &vpx_codec_vp9_cx, NULL, VP9_FOURCC},
109 #endif
110 };
111 
112 static void usage_exit();
113 
114 #define LOG_ERROR(label) do \
115  {\
116  const char *l=label;\
117  va_list ap;\
118  va_start(ap, fmt);\
119  if(l)\
120  fprintf(stderr, "%s: ", l);\
121  vfprintf(stderr, fmt, ap);\
122  fprintf(stderr, "\n");\
123  va_end(ap);\
124  } while(0)
125 
126 void die(const char *fmt, ...) {
127  LOG_ERROR(NULL);
128  usage_exit();
129 }
130 
131 
132 void fatal(const char *fmt, ...) {
133  LOG_ERROR("Fatal");
134  exit(EXIT_FAILURE);
135 }
136 
137 
138 void warn(const char *fmt, ...) {
139  LOG_ERROR("Warning");
140 }
141 
142 
143 static void warn_or_exit_on_errorv(vpx_codec_ctx_t *ctx, int fatal,
144  const char *s, va_list ap) {
145  if (ctx->err) {
146  const char *detail = vpx_codec_error_detail(ctx);
147 
148  vfprintf(stderr, s, ap);
149  fprintf(stderr, ": %s\n", vpx_codec_error(ctx));
150 
151  if (detail)
152  fprintf(stderr, " %s\n", detail);
153 
154  if (fatal)
155  exit(EXIT_FAILURE);
156  }
157 }
158 
159 static void ctx_exit_on_error(vpx_codec_ctx_t *ctx, const char *s, ...) {
160  va_list ap;
161 
162  va_start(ap, s);
163  warn_or_exit_on_errorv(ctx, 1, s, ap);
164  va_end(ap);
165 }
166 
167 static void warn_or_exit_on_error(vpx_codec_ctx_t *ctx, int fatal,
168  const char *s, ...) {
169  va_list ap;
170 
171  va_start(ap, s);
172  warn_or_exit_on_errorv(ctx, fatal, s, ap);
173  va_end(ap);
174 }
175 
176 /* This structure is used to abstract the different ways of handling
177  * first pass statistics.
178  */
179 typedef struct {
180  vpx_fixed_buf_t buf;
181  int pass;
182  FILE *file;
183  char *buf_ptr;
184  size_t buf_alloc_sz;
185 } stats_io_t;
186 
187 int stats_open_file(stats_io_t *stats, const char *fpf, int pass) {
188  int res;
189 
190  stats->pass = pass;
191 
192  if (pass == 0) {
193  stats->file = fopen(fpf, "wb");
194  stats->buf.sz = 0;
195  stats->buf.buf = NULL,
196  res = (stats->file != NULL);
197  } else {
198 #if 0
199 #elif USE_POSIX_MMAP
200  struct stat stat_buf;
201  int fd;
202 
203  fd = open(fpf, O_RDONLY);
204  stats->file = fdopen(fd, "rb");
205  fstat(fd, &stat_buf);
206  stats->buf.sz = stat_buf.st_size;
207  stats->buf.buf = mmap(NULL, stats->buf.sz, PROT_READ, MAP_PRIVATE,
208  fd, 0);
209  res = (stats->buf.buf != NULL);
210 #else
211  size_t nbytes;
212 
213  stats->file = fopen(fpf, "rb");
214 
215  if (fseek(stats->file, 0, SEEK_END))
216  fatal("First-pass stats file must be seekable!");
217 
218  stats->buf.sz = stats->buf_alloc_sz = ftell(stats->file);
219  rewind(stats->file);
220 
221  stats->buf.buf = malloc(stats->buf_alloc_sz);
222 
223  if (!stats->buf.buf)
224  fatal("Failed to allocate first-pass stats buffer (%lu bytes)",
225  (unsigned long)stats->buf_alloc_sz);
226 
227  nbytes = fread(stats->buf.buf, 1, stats->buf.sz, stats->file);
228  res = (nbytes == stats->buf.sz);
229 #endif
230  }
231 
232  return res;
233 }
234 
235 int stats_open_mem(stats_io_t *stats, int pass) {
236  int res;
237  stats->pass = pass;
238 
239  if (!pass) {
240  stats->buf.sz = 0;
241  stats->buf_alloc_sz = 64 * 1024;
242  stats->buf.buf = malloc(stats->buf_alloc_sz);
243  }
244 
245  stats->buf_ptr = stats->buf.buf;
246  res = (stats->buf.buf != NULL);
247  return res;
248 }
249 
250 
251 void stats_close(stats_io_t *stats, int last_pass) {
252  if (stats->file) {
253  if (stats->pass == last_pass) {
254 #if 0
255 #elif USE_POSIX_MMAP
256  munmap(stats->buf.buf, stats->buf.sz);
257 #else
258  free(stats->buf.buf);
259 #endif
260  }
261 
262  fclose(stats->file);
263  stats->file = NULL;
264  } else {
265  if (stats->pass == last_pass)
266  free(stats->buf.buf);
267  }
268 }
269 
270 void stats_write(stats_io_t *stats, const void *pkt, size_t len) {
271  if (stats->file) {
272  (void) fwrite(pkt, 1, len, stats->file);
273  } else {
274  if (stats->buf.sz + len > stats->buf_alloc_sz) {
275  size_t new_sz = stats->buf_alloc_sz + 64 * 1024;
276  char *new_ptr = realloc(stats->buf.buf, new_sz);
277 
278  if (new_ptr) {
279  stats->buf_ptr = new_ptr + (stats->buf_ptr - (char *)stats->buf.buf);
280  stats->buf.buf = new_ptr;
281  stats->buf_alloc_sz = new_sz;
282  } else
283  fatal("Failed to realloc firstpass stats buffer.");
284  }
285 
286  memcpy(stats->buf_ptr, pkt, len);
287  stats->buf.sz += len;
288  stats->buf_ptr += len;
289  }
290 }
291 
292 vpx_fixed_buf_t stats_get(stats_io_t *stats) {
293  return stats->buf;
294 }
295 
296 /* Stereo 3D packed frame format */
297 typedef enum stereo_format {
298  STEREO_FORMAT_MONO = 0,
299  STEREO_FORMAT_LEFT_RIGHT = 1,
300  STEREO_FORMAT_BOTTOM_TOP = 2,
301  STEREO_FORMAT_TOP_BOTTOM = 3,
302  STEREO_FORMAT_RIGHT_LEFT = 11
303 } stereo_format_t;
304 
305 enum video_file_type {
306  FILE_TYPE_RAW,
307  FILE_TYPE_IVF,
308  FILE_TYPE_Y4M
309 };
310 
311 struct detect_buffer {
312  char buf[4];
313  size_t buf_read;
314  size_t position;
315 };
316 
317 
318 struct input_state {
319  char *fn;
320  FILE *file;
321  off_t length;
322  y4m_input y4m;
323  struct detect_buffer detect;
324  enum video_file_type file_type;
325  unsigned int w;
326  unsigned int h;
327  struct vpx_rational framerate;
328  int use_i420;
329 };
330 
331 
332 #define IVF_FRAME_HDR_SZ (4+8) /* 4 byte size + 8 byte timestamp */
333 static int read_frame(struct input_state *input, vpx_image_t *img) {
334  FILE *f = input->file;
335  enum video_file_type file_type = input->file_type;
336  y4m_input *y4m = &input->y4m;
337  struct detect_buffer *detect = &input->detect;
338  int plane = 0;
339  int shortread = 0;
340 
341  if (file_type == FILE_TYPE_Y4M) {
342  if (y4m_input_fetch_frame(y4m, f, img) < 1)
343  return 0;
344  } else {
345  if (file_type == FILE_TYPE_IVF) {
346  char junk[IVF_FRAME_HDR_SZ];
347 
348  /* Skip the frame header. We know how big the frame should be. See
349  * write_ivf_frame_header() for documentation on the frame header
350  * layout.
351  */
352  (void) fread(junk, 1, IVF_FRAME_HDR_SZ, f);
353  }
354 
355  for (plane = 0; plane < 3; plane++) {
356  unsigned char *ptr;
357  int w = (plane ? (1 + img->d_w) / 2 : img->d_w);
358  int h = (plane ? (1 + img->d_h) / 2 : img->d_h);
359  int r;
360 
361  /* Determine the correct plane based on the image format. The for-loop
362  * always counts in Y,U,V order, but this may not match the order of
363  * the data on disk.
364  */
365  switch (plane) {
366  case 1:
367  ptr = img->planes[img->fmt == VPX_IMG_FMT_YV12 ? VPX_PLANE_V : VPX_PLANE_U];
368  break;
369  case 2:
370  ptr = img->planes[img->fmt == VPX_IMG_FMT_YV12 ? VPX_PLANE_U : VPX_PLANE_V];
371  break;
372  default:
373  ptr = img->planes[plane];
374  }
375 
376  for (r = 0; r < h; r++) {
377  size_t needed = w;
378  size_t buf_position = 0;
379  const size_t left = detect->buf_read - detect->position;
380  if (left > 0) {
381  const size_t more = (left < needed) ? left : needed;
382  memcpy(ptr, detect->buf + detect->position, more);
383  buf_position = more;
384  needed -= more;
385  detect->position += more;
386  }
387  if (needed > 0) {
388  shortread |= (fread(ptr + buf_position, 1, needed, f) < needed);
389  }
390 
391  ptr += img->stride[plane];
392  }
393  }
394  }
395 
396  return !shortread;
397 }
398 
399 
400 unsigned int file_is_y4m(FILE *infile,
401  y4m_input *y4m,
402  char detect[4]) {
403  if (memcmp(detect, "YUV4", 4) == 0) {
404  return 1;
405  }
406  return 0;
407 }
408 
409 #define IVF_FILE_HDR_SZ (32)
410 unsigned int file_is_ivf(struct input_state *input,
411  unsigned int *fourcc) {
412  char raw_hdr[IVF_FILE_HDR_SZ];
413  int is_ivf = 0;
414  FILE *infile = input->file;
415  unsigned int *width = &input->w;
416  unsigned int *height = &input->h;
417  struct detect_buffer *detect = &input->detect;
418 
419  if (memcmp(detect->buf, "DKIF", 4) != 0)
420  return 0;
421 
422  /* See write_ivf_file_header() for more documentation on the file header
423  * layout.
424  */
425  if (fread(raw_hdr + 4, 1, IVF_FILE_HDR_SZ - 4, infile)
426  == IVF_FILE_HDR_SZ - 4) {
427  {
428  is_ivf = 1;
429 
430  if (mem_get_le16(raw_hdr + 4) != 0)
431  warn("Unrecognized IVF version! This file may not decode "
432  "properly.");
433 
434  *fourcc = mem_get_le32(raw_hdr + 8);
435  }
436  }
437 
438  if (is_ivf) {
439  *width = mem_get_le16(raw_hdr + 12);
440  *height = mem_get_le16(raw_hdr + 14);
441  detect->position = 4;
442  }
443 
444  return is_ivf;
445 }
446 
447 
448 static void write_ivf_file_header(FILE *outfile,
449  const vpx_codec_enc_cfg_t *cfg,
450  unsigned int fourcc,
451  int frame_cnt) {
452  char header[32];
453 
454  if (cfg->g_pass != VPX_RC_ONE_PASS && cfg->g_pass != VPX_RC_LAST_PASS)
455  return;
456 
457  header[0] = 'D';
458  header[1] = 'K';
459  header[2] = 'I';
460  header[3] = 'F';
461  mem_put_le16(header + 4, 0); /* version */
462  mem_put_le16(header + 6, 32); /* headersize */
463  mem_put_le32(header + 8, fourcc); /* headersize */
464  mem_put_le16(header + 12, cfg->g_w); /* width */
465  mem_put_le16(header + 14, cfg->g_h); /* height */
466  mem_put_le32(header + 16, cfg->g_timebase.den); /* rate */
467  mem_put_le32(header + 20, cfg->g_timebase.num); /* scale */
468  mem_put_le32(header + 24, frame_cnt); /* length */
469  mem_put_le32(header + 28, 0); /* unused */
470 
471  (void) fwrite(header, 1, 32, outfile);
472 }
473 
474 
475 static void write_ivf_frame_header(FILE *outfile,
476  const vpx_codec_cx_pkt_t *pkt) {
477  char header[12];
478  vpx_codec_pts_t pts;
479 
480  if (pkt->kind != VPX_CODEC_CX_FRAME_PKT)
481  return;
482 
483  pts = pkt->data.frame.pts;
484  mem_put_le32(header, (int)pkt->data.frame.sz);
485  mem_put_le32(header + 4, pts & 0xFFFFFFFF);
486  mem_put_le32(header + 8, pts >> 32);
487 
488  (void) fwrite(header, 1, 12, outfile);
489 }
490 
491 static void write_ivf_frame_size(FILE *outfile, size_t size) {
492  char header[4];
493  mem_put_le32(header, (int)size);
494  (void) fwrite(header, 1, 4, outfile);
495 }
496 
497 
498 typedef off_t EbmlLoc;
499 
500 
501 struct cue_entry {
502  unsigned int time;
503  uint64_t loc;
504 };
505 
506 
507 struct EbmlGlobal {
508  int debug;
509 
510  FILE *stream;
511  int64_t last_pts_ms;
512  vpx_rational_t framerate;
513 
514  /* These pointers are to the start of an element */
515  off_t position_reference;
516  off_t seek_info_pos;
517  off_t segment_info_pos;
518  off_t track_pos;
519  off_t cue_pos;
520  off_t cluster_pos;
521 
522  /* This pointer is to a specific element to be serialized */
523  off_t track_id_pos;
524 
525  /* These pointers are to the size field of the element */
526  EbmlLoc startSegment;
527  EbmlLoc startCluster;
528 
529  uint32_t cluster_timecode;
530  int cluster_open;
531 
532  struct cue_entry *cue_list;
533  unsigned int cues;
534 
535 };
536 
537 
538 void Ebml_Write(EbmlGlobal *glob, const void *buffer_in, unsigned long len) {
539  (void) fwrite(buffer_in, 1, len, glob->stream);
540 }
541 
542 #define WRITE_BUFFER(s) \
543  for(i = len-1; i>=0; i--)\
544  { \
545  x = (char)(*(const s *)buffer_in >> (i * CHAR_BIT)); \
546  Ebml_Write(glob, &x, 1); \
547  }
548 void Ebml_Serialize(EbmlGlobal *glob, const void *buffer_in, int buffer_size, unsigned long len) {
549  char x;
550  int i;
551 
552  /* buffer_size:
553  * 1 - int8_t;
554  * 2 - int16_t;
555  * 3 - int32_t;
556  * 4 - int64_t;
557  */
558  switch (buffer_size) {
559  case 1:
560  WRITE_BUFFER(int8_t)
561  break;
562  case 2:
563  WRITE_BUFFER(int16_t)
564  break;
565  case 4:
566  WRITE_BUFFER(int32_t)
567  break;
568  case 8:
569  WRITE_BUFFER(int64_t)
570  break;
571  default:
572  break;
573  }
574 }
575 #undef WRITE_BUFFER
576 
577 /* Need a fixed size serializer for the track ID. libmkv provides a 64 bit
578  * one, but not a 32 bit one.
579  */
580 static void Ebml_SerializeUnsigned32(EbmlGlobal *glob, unsigned long class_id, uint64_t ui) {
581  unsigned char sizeSerialized = 4 | 0x80;
582  Ebml_WriteID(glob, class_id);
583  Ebml_Serialize(glob, &sizeSerialized, sizeof(sizeSerialized), 1);
584  Ebml_Serialize(glob, &ui, sizeof(ui), 4);
585 }
586 
587 
588 static void
589 Ebml_StartSubElement(EbmlGlobal *glob, EbmlLoc *ebmlLoc,
590  unsigned long class_id) {
591  /* todo this is always taking 8 bytes, this may need later optimization */
592  /* this is a key that says length unknown */
593  uint64_t unknownLen = LITERALU64(0x01FFFFFF, 0xFFFFFFFF);
594 
595  Ebml_WriteID(glob, class_id);
596  *ebmlLoc = ftello(glob->stream);
597  Ebml_Serialize(glob, &unknownLen, sizeof(unknownLen), 8);
598 }
599 
600 static void
601 Ebml_EndSubElement(EbmlGlobal *glob, EbmlLoc *ebmlLoc) {
602  off_t pos;
603  uint64_t size;
604 
605  /* Save the current stream pointer */
606  pos = ftello(glob->stream);
607 
608  /* Calculate the size of this element */
609  size = pos - *ebmlLoc - 8;
610  size |= LITERALU64(0x01000000, 0x00000000);
611 
612  /* Seek back to the beginning of the element and write the new size */
613  fseeko(glob->stream, *ebmlLoc, SEEK_SET);
614  Ebml_Serialize(glob, &size, sizeof(size), 8);
615 
616  /* Reset the stream pointer */
617  fseeko(glob->stream, pos, SEEK_SET);
618 }
619 
620 
621 static void
622 write_webm_seek_element(EbmlGlobal *ebml, unsigned long id, off_t pos) {
623  uint64_t offset = pos - ebml->position_reference;
624  EbmlLoc start;
625  Ebml_StartSubElement(ebml, &start, Seek);
626  Ebml_SerializeBinary(ebml, SeekID, id);
627  Ebml_SerializeUnsigned64(ebml, SeekPosition, offset);
628  Ebml_EndSubElement(ebml, &start);
629 }
630 
631 
632 static void
633 write_webm_seek_info(EbmlGlobal *ebml) {
634 
635  off_t pos;
636 
637  /* Save the current stream pointer */
638  pos = ftello(ebml->stream);
639 
640  if (ebml->seek_info_pos)
641  fseeko(ebml->stream, ebml->seek_info_pos, SEEK_SET);
642  else
643  ebml->seek_info_pos = pos;
644 
645  {
646  EbmlLoc start;
647 
648  Ebml_StartSubElement(ebml, &start, SeekHead);
649  write_webm_seek_element(ebml, Tracks, ebml->track_pos);
650  write_webm_seek_element(ebml, Cues, ebml->cue_pos);
651  write_webm_seek_element(ebml, Info, ebml->segment_info_pos);
652  Ebml_EndSubElement(ebml, &start);
653  }
654  {
655  /* segment info */
656  EbmlLoc startInfo;
657  uint64_t frame_time;
658  char version_string[64];
659 
660  /* Assemble version string */
661  if (ebml->debug)
662  strcpy(version_string, "vpxenc");
663  else {
664  strcpy(version_string, "vpxenc ");
665  strncat(version_string,
667  sizeof(version_string) - 1 - strlen(version_string));
668  }
669 
670  frame_time = (uint64_t)1000 * ebml->framerate.den
671  / ebml->framerate.num;
672  ebml->segment_info_pos = ftello(ebml->stream);
673  Ebml_StartSubElement(ebml, &startInfo, Info);
674  Ebml_SerializeUnsigned(ebml, TimecodeScale, 1000000);
675  Ebml_SerializeFloat(ebml, Segment_Duration,
676  (double)(ebml->last_pts_ms + frame_time));
677  Ebml_SerializeString(ebml, 0x4D80, version_string);
678  Ebml_SerializeString(ebml, 0x5741, version_string);
679  Ebml_EndSubElement(ebml, &startInfo);
680  }
681 }
682 
683 
684 static void
685 write_webm_file_header(EbmlGlobal *glob,
686  const vpx_codec_enc_cfg_t *cfg,
687  const struct vpx_rational *fps,
688  stereo_format_t stereo_fmt,
689  unsigned int fourcc) {
690  {
691  EbmlLoc start;
692  Ebml_StartSubElement(glob, &start, EBML);
693  Ebml_SerializeUnsigned(glob, EBMLVersion, 1);
694  Ebml_SerializeUnsigned(glob, EBMLReadVersion, 1);
695  Ebml_SerializeUnsigned(glob, EBMLMaxIDLength, 4);
696  Ebml_SerializeUnsigned(glob, EBMLMaxSizeLength, 8);
697  Ebml_SerializeString(glob, DocType, "webm");
698  Ebml_SerializeUnsigned(glob, DocTypeVersion, 2);
699  Ebml_SerializeUnsigned(glob, DocTypeReadVersion, 2);
700  Ebml_EndSubElement(glob, &start);
701  }
702  {
703  Ebml_StartSubElement(glob, &glob->startSegment, Segment);
704  glob->position_reference = ftello(glob->stream);
705  glob->framerate = *fps;
706  write_webm_seek_info(glob);
707 
708  {
709  EbmlLoc trackStart;
710  glob->track_pos = ftello(glob->stream);
711  Ebml_StartSubElement(glob, &trackStart, Tracks);
712  {
713  unsigned int trackNumber = 1;
714  uint64_t trackID = 0;
715 
716  EbmlLoc start;
717  Ebml_StartSubElement(glob, &start, TrackEntry);
718  Ebml_SerializeUnsigned(glob, TrackNumber, trackNumber);
719  glob->track_id_pos = ftello(glob->stream);
720  Ebml_SerializeUnsigned32(glob, TrackUID, trackID);
721  Ebml_SerializeUnsigned(glob, TrackType, 1);
722  Ebml_SerializeString(glob, CodecID,
723  fourcc == VP8_FOURCC ? "V_VP8" : "V_VP9");
724  {
725  unsigned int pixelWidth = cfg->g_w;
726  unsigned int pixelHeight = cfg->g_h;
727  float frameRate = (float)fps->num / (float)fps->den;
728 
729  EbmlLoc videoStart;
730  Ebml_StartSubElement(glob, &videoStart, Video);
731  Ebml_SerializeUnsigned(glob, PixelWidth, pixelWidth);
732  Ebml_SerializeUnsigned(glob, PixelHeight, pixelHeight);
733  Ebml_SerializeUnsigned(glob, StereoMode, stereo_fmt);
734  Ebml_SerializeFloat(glob, FrameRate, frameRate);
735  Ebml_EndSubElement(glob, &videoStart);
736  }
737  Ebml_EndSubElement(glob, &start); /* Track Entry */
738  }
739  Ebml_EndSubElement(glob, &trackStart);
740  }
741  /* segment element is open */
742  }
743 }
744 
745 
746 static void
747 write_webm_block(EbmlGlobal *glob,
748  const vpx_codec_enc_cfg_t *cfg,
749  const vpx_codec_cx_pkt_t *pkt) {
750  unsigned long block_length;
751  unsigned char track_number;
752  unsigned short block_timecode = 0;
753  unsigned char flags;
754  int64_t pts_ms;
755  int start_cluster = 0, is_keyframe;
756 
757  /* Calculate the PTS of this frame in milliseconds */
758  pts_ms = pkt->data.frame.pts * 1000
759  * (uint64_t)cfg->g_timebase.num / (uint64_t)cfg->g_timebase.den;
760  if (pts_ms <= glob->last_pts_ms)
761  pts_ms = glob->last_pts_ms + 1;
762  glob->last_pts_ms = pts_ms;
763 
764  /* Calculate the relative time of this block */
765  if (pts_ms - glob->cluster_timecode > SHRT_MAX)
766  start_cluster = 1;
767  else
768  block_timecode = (unsigned short)pts_ms - glob->cluster_timecode;
769 
770  is_keyframe = (pkt->data.frame.flags & VPX_FRAME_IS_KEY);
771  if (start_cluster || is_keyframe) {
772  if (glob->cluster_open)
773  Ebml_EndSubElement(glob, &glob->startCluster);
774 
775  /* Open the new cluster */
776  block_timecode = 0;
777  glob->cluster_open = 1;
778  glob->cluster_timecode = (uint32_t)pts_ms;
779  glob->cluster_pos = ftello(glob->stream);
780  Ebml_StartSubElement(glob, &glob->startCluster, Cluster); /* cluster */
781  Ebml_SerializeUnsigned(glob, Timecode, glob->cluster_timecode);
782 
783  /* Save a cue point if this is a keyframe. */
784  if (is_keyframe) {
785  struct cue_entry *cue, *new_cue_list;
786 
787  new_cue_list = realloc(glob->cue_list,
788  (glob->cues + 1) * sizeof(struct cue_entry));
789  if (new_cue_list)
790  glob->cue_list = new_cue_list;
791  else
792  fatal("Failed to realloc cue list.");
793 
794  cue = &glob->cue_list[glob->cues];
795  cue->time = glob->cluster_timecode;
796  cue->loc = glob->cluster_pos;
797  glob->cues++;
798  }
799  }
800 
801  /* Write the Simple Block */
802  Ebml_WriteID(glob, SimpleBlock);
803 
804  block_length = (unsigned long)pkt->data.frame.sz + 4;
805  block_length |= 0x10000000;
806  Ebml_Serialize(glob, &block_length, sizeof(block_length), 4);
807 
808  track_number = 1;
809  track_number |= 0x80;
810  Ebml_Write(glob, &track_number, 1);
811 
812  Ebml_Serialize(glob, &block_timecode, sizeof(block_timecode), 2);
813 
814  flags = 0;
815  if (is_keyframe)
816  flags |= 0x80;
817  if (pkt->data.frame.flags & VPX_FRAME_IS_INVISIBLE)
818  flags |= 0x08;
819  Ebml_Write(glob, &flags, 1);
820 
821  Ebml_Write(glob, pkt->data.frame.buf, (unsigned long)pkt->data.frame.sz);
822 }
823 
824 
825 static void
826 write_webm_file_footer(EbmlGlobal *glob, long hash) {
827 
828  if (glob->cluster_open)
829  Ebml_EndSubElement(glob, &glob->startCluster);
830 
831  {
832  EbmlLoc start;
833  unsigned int i;
834 
835  glob->cue_pos = ftello(glob->stream);
836  Ebml_StartSubElement(glob, &start, Cues);
837  for (i = 0; i < glob->cues; i++) {
838  struct cue_entry *cue = &glob->cue_list[i];
839  EbmlLoc start;
840 
841  Ebml_StartSubElement(glob, &start, CuePoint);
842  {
843  EbmlLoc start;
844 
845  Ebml_SerializeUnsigned(glob, CueTime, cue->time);
846 
847  Ebml_StartSubElement(glob, &start, CueTrackPositions);
848  Ebml_SerializeUnsigned(glob, CueTrack, 1);
849  Ebml_SerializeUnsigned64(glob, CueClusterPosition,
850  cue->loc - glob->position_reference);
851  Ebml_EndSubElement(glob, &start);
852  }
853  Ebml_EndSubElement(glob, &start);
854  }
855  Ebml_EndSubElement(glob, &start);
856  }
857 
858  Ebml_EndSubElement(glob, &glob->startSegment);
859 
860  /* Patch up the seek info block */
861  write_webm_seek_info(glob);
862 
863  /* Patch up the track id */
864  fseeko(glob->stream, glob->track_id_pos, SEEK_SET);
865  Ebml_SerializeUnsigned32(glob, TrackUID, glob->debug ? 0xDEADBEEF : hash);
866 
867  fseeko(glob->stream, 0, SEEK_END);
868 }
869 
870 
871 /* Murmur hash derived from public domain reference implementation at
872  * http:// sites.google.com/site/murmurhash/
873  */
874 static unsigned int murmur(const void *key, int len, unsigned int seed) {
875  const unsigned int m = 0x5bd1e995;
876  const int r = 24;
877 
878  unsigned int h = seed ^ len;
879 
880  const unsigned char *data = (const unsigned char *)key;
881 
882  while (len >= 4) {
883  unsigned int k;
884 
885  k = data[0];
886  k |= data[1] << 8;
887  k |= data[2] << 16;
888  k |= data[3] << 24;
889 
890  k *= m;
891  k ^= k >> r;
892  k *= m;
893 
894  h *= m;
895  h ^= k;
896 
897  data += 4;
898  len -= 4;
899  }
900 
901  switch (len) {
902  case 3:
903  h ^= data[2] << 16;
904  case 2:
905  h ^= data[1] << 8;
906  case 1:
907  h ^= data[0];
908  h *= m;
909  };
910 
911  h ^= h >> 13;
912  h *= m;
913  h ^= h >> 15;
914 
915  return h;
916 }
917 
918 #include "math.h"
919 #define MAX_PSNR 100
920 static double vp8_mse2psnr(double Samples, double Peak, double Mse) {
921  double psnr;
922 
923  if ((double)Mse > 0.0)
924  psnr = 10.0 * log10(Peak * Peak * Samples / Mse);
925  else
926  psnr = MAX_PSNR; /* Limit to prevent / 0 */
927 
928  if (psnr > MAX_PSNR)
929  psnr = MAX_PSNR;
930 
931  return psnr;
932 }
933 
934 
935 #include "args.h"
936 static const arg_def_t debugmode = ARG_DEF("D", "debug", 0,
937  "Debug mode (makes output deterministic)");
938 static const arg_def_t outputfile = ARG_DEF("o", "output", 1,
939  "Output filename");
940 static const arg_def_t use_yv12 = ARG_DEF(NULL, "yv12", 0,
941  "Input file is YV12 ");
942 static const arg_def_t use_i420 = ARG_DEF(NULL, "i420", 0,
943  "Input file is I420 (default)");
944 static const arg_def_t codecarg = ARG_DEF(NULL, "codec", 1,
945  "Codec to use");
946 static const arg_def_t passes = ARG_DEF("p", "passes", 1,
947  "Number of passes (1/2)");
948 static const arg_def_t pass_arg = ARG_DEF(NULL, "pass", 1,
949  "Pass to execute (1/2)");
950 static const arg_def_t fpf_name = ARG_DEF(NULL, "fpf", 1,
951  "First pass statistics file name");
952 static const arg_def_t limit = ARG_DEF(NULL, "limit", 1,
953  "Stop encoding after n input frames");
954 static const arg_def_t skip = ARG_DEF(NULL, "skip", 1,
955  "Skip the first n input frames");
956 static const arg_def_t deadline = ARG_DEF("d", "deadline", 1,
957  "Deadline per frame (usec)");
958 static const arg_def_t best_dl = ARG_DEF(NULL, "best", 0,
959  "Use Best Quality Deadline");
960 static const arg_def_t good_dl = ARG_DEF(NULL, "good", 0,
961  "Use Good Quality Deadline");
962 static const arg_def_t rt_dl = ARG_DEF(NULL, "rt", 0,
963  "Use Realtime Quality Deadline");
964 static const arg_def_t quietarg = ARG_DEF("q", "quiet", 0,
965  "Do not print encode progress");
966 static const arg_def_t verbosearg = ARG_DEF("v", "verbose", 0,
967  "Show encoder parameters");
968 static const arg_def_t psnrarg = ARG_DEF(NULL, "psnr", 0,
969  "Show PSNR in status line");
970 enum TestDecodeFatality {
971  TEST_DECODE_OFF,
972  TEST_DECODE_FATAL,
973  TEST_DECODE_WARN,
974 };
975 static const struct arg_enum_list test_decode_enum[] = {
976  {"off", TEST_DECODE_OFF},
977  {"fatal", TEST_DECODE_FATAL},
978  {"warn", TEST_DECODE_WARN},
979  {NULL, 0}
980 };
981 static const arg_def_t recontest = ARG_DEF_ENUM(NULL, "test-decode", 1,
982  "Test encode/decode mismatch",
983  test_decode_enum);
984 static const arg_def_t framerate = ARG_DEF(NULL, "fps", 1,
985  "Stream frame rate (rate/scale)");
986 static const arg_def_t use_ivf = ARG_DEF(NULL, "ivf", 0,
987  "Output IVF (default is WebM)");
988 static const arg_def_t out_part = ARG_DEF("P", "output-partitions", 0,
989  "Makes encoder output partitions. Requires IVF output!");
990 static const arg_def_t q_hist_n = ARG_DEF(NULL, "q-hist", 1,
991  "Show quantizer histogram (n-buckets)");
992 static const arg_def_t rate_hist_n = ARG_DEF(NULL, "rate-hist", 1,
993  "Show rate histogram (n-buckets)");
994 static const arg_def_t *main_args[] = {
995  &debugmode,
996  &outputfile, &codecarg, &passes, &pass_arg, &fpf_name, &limit, &skip,
997  &deadline, &best_dl, &good_dl, &rt_dl,
998  &quietarg, &verbosearg, &psnrarg, &use_ivf, &out_part, &q_hist_n, &rate_hist_n,
999  NULL
1000 };
1001 
1002 static const arg_def_t usage = ARG_DEF("u", "usage", 1,
1003  "Usage profile number to use");
1004 static const arg_def_t threads = ARG_DEF("t", "threads", 1,
1005  "Max number of threads to use");
1006 static const arg_def_t profile = ARG_DEF(NULL, "profile", 1,
1007  "Bitstream profile number to use");
1008 static const arg_def_t width = ARG_DEF("w", "width", 1,
1009  "Frame width");
1010 static const arg_def_t height = ARG_DEF("h", "height", 1,
1011  "Frame height");
1012 static const struct arg_enum_list stereo_mode_enum[] = {
1013  {"mono", STEREO_FORMAT_MONO},
1014  {"left-right", STEREO_FORMAT_LEFT_RIGHT},
1015  {"bottom-top", STEREO_FORMAT_BOTTOM_TOP},
1016  {"top-bottom", STEREO_FORMAT_TOP_BOTTOM},
1017  {"right-left", STEREO_FORMAT_RIGHT_LEFT},
1018  {NULL, 0}
1019 };
1020 static const arg_def_t stereo_mode = ARG_DEF_ENUM(NULL, "stereo-mode", 1,
1021  "Stereo 3D video format", stereo_mode_enum);
1022 static const arg_def_t timebase = ARG_DEF(NULL, "timebase", 1,
1023  "Output timestamp precision (fractional seconds)");
1024 static const arg_def_t error_resilient = ARG_DEF(NULL, "error-resilient", 1,
1025  "Enable error resiliency features");
1026 static const arg_def_t lag_in_frames = ARG_DEF(NULL, "lag-in-frames", 1,
1027  "Max number of frames to lag");
1028 
1029 static const arg_def_t *global_args[] = {
1030  &use_yv12, &use_i420, &usage, &threads, &profile,
1031  &width, &height, &stereo_mode, &timebase, &framerate,
1032  &error_resilient,
1033  &lag_in_frames, NULL
1034 };
1035 
1036 static const arg_def_t dropframe_thresh = ARG_DEF(NULL, "drop-frame", 1,
1037  "Temporal resampling threshold (buf %)");
1038 static const arg_def_t resize_allowed = ARG_DEF(NULL, "resize-allowed", 1,
1039  "Spatial resampling enabled (bool)");
1040 static const arg_def_t resize_up_thresh = ARG_DEF(NULL, "resize-up", 1,
1041  "Upscale threshold (buf %)");
1042 static const arg_def_t resize_down_thresh = ARG_DEF(NULL, "resize-down", 1,
1043  "Downscale threshold (buf %)");
1044 static const struct arg_enum_list end_usage_enum[] = {
1045  {"vbr", VPX_VBR},
1046  {"cbr", VPX_CBR},
1047  {"cq", VPX_CQ},
1048  {NULL, 0}
1049 };
1050 static const arg_def_t end_usage = ARG_DEF_ENUM(NULL, "end-usage", 1,
1051  "Rate control mode", end_usage_enum);
1052 static const arg_def_t target_bitrate = ARG_DEF(NULL, "target-bitrate", 1,
1053  "Bitrate (kbps)");
1054 static const arg_def_t min_quantizer = ARG_DEF(NULL, "min-q", 1,
1055  "Minimum (best) quantizer");
1056 static const arg_def_t max_quantizer = ARG_DEF(NULL, "max-q", 1,
1057  "Maximum (worst) quantizer");
1058 static const arg_def_t undershoot_pct = ARG_DEF(NULL, "undershoot-pct", 1,
1059  "Datarate undershoot (min) target (%)");
1060 static const arg_def_t overshoot_pct = ARG_DEF(NULL, "overshoot-pct", 1,
1061  "Datarate overshoot (max) target (%)");
1062 static const arg_def_t buf_sz = ARG_DEF(NULL, "buf-sz", 1,
1063  "Client buffer size (ms)");
1064 static const arg_def_t buf_initial_sz = ARG_DEF(NULL, "buf-initial-sz", 1,
1065  "Client initial buffer size (ms)");
1066 static const arg_def_t buf_optimal_sz = ARG_DEF(NULL, "buf-optimal-sz", 1,
1067  "Client optimal buffer size (ms)");
1068 static const arg_def_t *rc_args[] = {
1069  &dropframe_thresh, &resize_allowed, &resize_up_thresh, &resize_down_thresh,
1070  &end_usage, &target_bitrate, &min_quantizer, &max_quantizer,
1071  &undershoot_pct, &overshoot_pct, &buf_sz, &buf_initial_sz, &buf_optimal_sz,
1072  NULL
1073 };
1074 
1075 
1076 static const arg_def_t bias_pct = ARG_DEF(NULL, "bias-pct", 1,
1077  "CBR/VBR bias (0=CBR, 100=VBR)");
1078 static const arg_def_t minsection_pct = ARG_DEF(NULL, "minsection-pct", 1,
1079  "GOP min bitrate (% of target)");
1080 static const arg_def_t maxsection_pct = ARG_DEF(NULL, "maxsection-pct", 1,
1081  "GOP max bitrate (% of target)");
1082 static const arg_def_t *rc_twopass_args[] = {
1083  &bias_pct, &minsection_pct, &maxsection_pct, NULL
1084 };
1085 
1086 
1087 static const arg_def_t kf_min_dist = ARG_DEF(NULL, "kf-min-dist", 1,
1088  "Minimum keyframe interval (frames)");
1089 static const arg_def_t kf_max_dist = ARG_DEF(NULL, "kf-max-dist", 1,
1090  "Maximum keyframe interval (frames)");
1091 static const arg_def_t kf_disabled = ARG_DEF(NULL, "disable-kf", 0,
1092  "Disable keyframe placement");
1093 static const arg_def_t *kf_args[] = {
1094  &kf_min_dist, &kf_max_dist, &kf_disabled, NULL
1095 };
1096 
1097 
1098 static const arg_def_t noise_sens = ARG_DEF(NULL, "noise-sensitivity", 1,
1099  "Noise sensitivity (frames to blur)");
1100 static const arg_def_t sharpness = ARG_DEF(NULL, "sharpness", 1,
1101  "Filter sharpness (0-7)");
1102 static const arg_def_t static_thresh = ARG_DEF(NULL, "static-thresh", 1,
1103  "Motion detection threshold");
1104 static const arg_def_t cpu_used = ARG_DEF(NULL, "cpu-used", 1,
1105  "CPU Used (-16..16)");
1106 static const arg_def_t token_parts = ARG_DEF(NULL, "token-parts", 1,
1107  "Number of token partitions to use, log2");
1108 static const arg_def_t tile_cols = ARG_DEF(NULL, "tile-columns", 1,
1109  "Number of tile columns to use, log2");
1110 static const arg_def_t tile_rows = ARG_DEF(NULL, "tile-rows", 1,
1111  "Number of tile rows to use, log2");
1112 static const arg_def_t auto_altref = ARG_DEF(NULL, "auto-alt-ref", 1,
1113  "Enable automatic alt reference frames");
1114 static const arg_def_t arnr_maxframes = ARG_DEF(NULL, "arnr-maxframes", 1,
1115  "AltRef Max Frames");
1116 static const arg_def_t arnr_strength = ARG_DEF(NULL, "arnr-strength", 1,
1117  "AltRef Strength");
1118 static const arg_def_t arnr_type = ARG_DEF(NULL, "arnr-type", 1,
1119  "AltRef Type");
1120 static const struct arg_enum_list tuning_enum[] = {
1121  {"psnr", VP8_TUNE_PSNR},
1122  {"ssim", VP8_TUNE_SSIM},
1123  {NULL, 0}
1124 };
1125 static const arg_def_t tune_ssim = ARG_DEF_ENUM(NULL, "tune", 1,
1126  "Material to favor", tuning_enum);
1127 static const arg_def_t cq_level = ARG_DEF(NULL, "cq-level", 1,
1128  "Constrained Quality Level");
1129 static const arg_def_t max_intra_rate_pct = ARG_DEF(NULL, "max-intra-rate", 1,
1130  "Max I-frame bitrate (pct)");
1131 static const arg_def_t lossless = ARG_DEF(NULL, "lossless", 1, "Lossless mode");
1132 #if CONFIG_VP9_ENCODER
1133 static const arg_def_t frame_parallel_decoding = ARG_DEF(
1134  NULL, "frame-parallel", 1, "Enable frame parallel decodability features");
1135 #endif
1136 
1137 #if CONFIG_VP8_ENCODER
1138 static const arg_def_t *vp8_args[] = {
1139  &cpu_used, &auto_altref, &noise_sens, &sharpness, &static_thresh,
1140  &token_parts, &arnr_maxframes, &arnr_strength, &arnr_type,
1141  &tune_ssim, &cq_level, &max_intra_rate_pct,
1142  NULL
1143 };
1144 static const int vp8_arg_ctrl_map[] = {
1150  0
1151 };
1152 #endif
1153 
1154 #if CONFIG_VP9_ENCODER
1155 static const arg_def_t *vp9_args[] = {
1156  &cpu_used, &auto_altref, &noise_sens, &sharpness, &static_thresh,
1157  &tile_cols, &tile_rows, &arnr_maxframes, &arnr_strength, &arnr_type,
1158  &tune_ssim, &cq_level, &max_intra_rate_pct, &lossless,
1159  &frame_parallel_decoding,
1160  NULL
1161 };
1162 static const int vp9_arg_ctrl_map[] = {
1165  VP9E_SET_TILE_COLUMNS, VP9E_SET_TILE_ROWS,
1168  VP9E_SET_LOSSLESS, VP9E_SET_FRAME_PARALLEL_DECODING,
1169  0
1170 };
1171 #endif
1172 
1173 static const arg_def_t *no_args[] = { NULL };
1174 
1175 static void usage_exit() {
1176  int i;
1177 
1178  fprintf(stderr, "Usage: %s <options> -o dst_filename src_filename \n",
1179  exec_name);
1180 
1181  fprintf(stderr, "\nOptions:\n");
1182  arg_show_usage(stdout, main_args);
1183  fprintf(stderr, "\nEncoder Global Options:\n");
1184  arg_show_usage(stdout, global_args);
1185  fprintf(stderr, "\nRate Control Options:\n");
1186  arg_show_usage(stdout, rc_args);
1187  fprintf(stderr, "\nTwopass Rate Control Options:\n");
1188  arg_show_usage(stdout, rc_twopass_args);
1189  fprintf(stderr, "\nKeyframe Placement Options:\n");
1190  arg_show_usage(stdout, kf_args);
1191 #if CONFIG_VP8_ENCODER
1192  fprintf(stderr, "\nVP8 Specific Options:\n");
1193  arg_show_usage(stdout, vp8_args);
1194 #endif
1195 #if CONFIG_VP9_ENCODER
1196  fprintf(stderr, "\nVP9 Specific Options:\n");
1197  arg_show_usage(stdout, vp9_args);
1198 #endif
1199  fprintf(stderr, "\nStream timebase (--timebase):\n"
1200  " The desired precision of timestamps in the output, expressed\n"
1201  " in fractional seconds. Default is 1/1000.\n");
1202  fprintf(stderr, "\n"
1203  "Included encoders:\n"
1204  "\n");
1205 
1206  for (i = 0; i < sizeof(codecs) / sizeof(codecs[0]); i++)
1207  fprintf(stderr, " %-6s - %s\n",
1208  codecs[i].name,
1209  vpx_codec_iface_name(codecs[i].iface()));
1210 
1211  exit(EXIT_FAILURE);
1212 }
1213 
1214 
1215 #define HIST_BAR_MAX 40
1216 struct hist_bucket {
1217  int low, high, count;
1218 };
1219 
1220 
1221 static int merge_hist_buckets(struct hist_bucket *bucket,
1222  int *buckets_,
1223  int max_buckets) {
1224  int small_bucket = 0, merge_bucket = INT_MAX, big_bucket = 0;
1225  int buckets = *buckets_;
1226  int i;
1227 
1228  /* Find the extrema for this list of buckets */
1229  big_bucket = small_bucket = 0;
1230  for (i = 0; i < buckets; i++) {
1231  if (bucket[i].count < bucket[small_bucket].count)
1232  small_bucket = i;
1233  if (bucket[i].count > bucket[big_bucket].count)
1234  big_bucket = i;
1235  }
1236 
1237  /* If we have too many buckets, merge the smallest with an adjacent
1238  * bucket.
1239  */
1240  while (buckets > max_buckets) {
1241  int last_bucket = buckets - 1;
1242 
1243  /* merge the small bucket with an adjacent one. */
1244  if (small_bucket == 0)
1245  merge_bucket = 1;
1246  else if (small_bucket == last_bucket)
1247  merge_bucket = last_bucket - 1;
1248  else if (bucket[small_bucket - 1].count < bucket[small_bucket + 1].count)
1249  merge_bucket = small_bucket - 1;
1250  else
1251  merge_bucket = small_bucket + 1;
1252 
1253  assert(abs(merge_bucket - small_bucket) <= 1);
1254  assert(small_bucket < buckets);
1255  assert(big_bucket < buckets);
1256  assert(merge_bucket < buckets);
1257 
1258  if (merge_bucket < small_bucket) {
1259  bucket[merge_bucket].high = bucket[small_bucket].high;
1260  bucket[merge_bucket].count += bucket[small_bucket].count;
1261  } else {
1262  bucket[small_bucket].high = bucket[merge_bucket].high;
1263  bucket[small_bucket].count += bucket[merge_bucket].count;
1264  merge_bucket = small_bucket;
1265  }
1266 
1267  assert(bucket[merge_bucket].low != bucket[merge_bucket].high);
1268 
1269  buckets--;
1270 
1271  /* Remove the merge_bucket from the list, and find the new small
1272  * and big buckets while we're at it
1273  */
1274  big_bucket = small_bucket = 0;
1275  for (i = 0; i < buckets; i++) {
1276  if (i > merge_bucket)
1277  bucket[i] = bucket[i + 1];
1278 
1279  if (bucket[i].count < bucket[small_bucket].count)
1280  small_bucket = i;
1281  if (bucket[i].count > bucket[big_bucket].count)
1282  big_bucket = i;
1283  }
1284 
1285  }
1286 
1287  *buckets_ = buckets;
1288  return bucket[big_bucket].count;
1289 }
1290 
1291 
1292 static void show_histogram(const struct hist_bucket *bucket,
1293  int buckets,
1294  int total,
1295  int scale) {
1296  const char *pat1, *pat2;
1297  int i;
1298 
1299  switch ((int)(log(bucket[buckets - 1].high) / log(10)) + 1) {
1300  case 1:
1301  case 2:
1302  pat1 = "%4d %2s: ";
1303  pat2 = "%4d-%2d: ";
1304  break;
1305  case 3:
1306  pat1 = "%5d %3s: ";
1307  pat2 = "%5d-%3d: ";
1308  break;
1309  case 4:
1310  pat1 = "%6d %4s: ";
1311  pat2 = "%6d-%4d: ";
1312  break;
1313  case 5:
1314  pat1 = "%7d %5s: ";
1315  pat2 = "%7d-%5d: ";
1316  break;
1317  case 6:
1318  pat1 = "%8d %6s: ";
1319  pat2 = "%8d-%6d: ";
1320  break;
1321  case 7:
1322  pat1 = "%9d %7s: ";
1323  pat2 = "%9d-%7d: ";
1324  break;
1325  default:
1326  pat1 = "%12d %10s: ";
1327  pat2 = "%12d-%10d: ";
1328  break;
1329  }
1330 
1331  for (i = 0; i < buckets; i++) {
1332  int len;
1333  int j;
1334  float pct;
1335 
1336  pct = (float)(100.0 * bucket[i].count / total);
1337  len = HIST_BAR_MAX * bucket[i].count / scale;
1338  if (len < 1)
1339  len = 1;
1340  assert(len <= HIST_BAR_MAX);
1341 
1342  if (bucket[i].low == bucket[i].high)
1343  fprintf(stderr, pat1, bucket[i].low, "");
1344  else
1345  fprintf(stderr, pat2, bucket[i].low, bucket[i].high);
1346 
1347  for (j = 0; j < HIST_BAR_MAX; j++)
1348  fprintf(stderr, j < len ? "=" : " ");
1349  fprintf(stderr, "\t%5d (%6.2f%%)\n", bucket[i].count, pct);
1350  }
1351 }
1352 
1353 
1354 static void show_q_histogram(const int counts[64], int max_buckets) {
1355  struct hist_bucket bucket[64];
1356  int buckets = 0;
1357  int total = 0;
1358  int scale;
1359  int i;
1360 
1361 
1362  for (i = 0; i < 64; i++) {
1363  if (counts[i]) {
1364  bucket[buckets].low = bucket[buckets].high = i;
1365  bucket[buckets].count = counts[i];
1366  buckets++;
1367  total += counts[i];
1368  }
1369  }
1370 
1371  fprintf(stderr, "\nQuantizer Selection:\n");
1372  scale = merge_hist_buckets(bucket, &buckets, max_buckets);
1373  show_histogram(bucket, buckets, total, scale);
1374 }
1375 
1376 
1377 #define RATE_BINS (100)
1378 struct rate_hist {
1379  int64_t *pts;
1380  int *sz;
1381  int samples;
1382  int frames;
1383  struct hist_bucket bucket[RATE_BINS];
1384  int total;
1385 };
1386 
1387 
1388 static void init_rate_histogram(struct rate_hist *hist,
1389  const vpx_codec_enc_cfg_t *cfg,
1390  const vpx_rational_t *fps) {
1391  int i;
1392 
1393  /* Determine the number of samples in the buffer. Use the file's framerate
1394  * to determine the number of frames in rc_buf_sz milliseconds, with an
1395  * adjustment (5/4) to account for alt-refs
1396  */
1397  hist->samples = cfg->rc_buf_sz * 5 / 4 * fps->num / fps->den / 1000;
1398 
1399  /* prevent division by zero */
1400  if (hist->samples == 0)
1401  hist->samples = 1;
1402 
1403  hist->pts = calloc(hist->samples, sizeof(*hist->pts));
1404  hist->sz = calloc(hist->samples, sizeof(*hist->sz));
1405  for (i = 0; i < RATE_BINS; i++) {
1406  hist->bucket[i].low = INT_MAX;
1407  hist->bucket[i].high = 0;
1408  hist->bucket[i].count = 0;
1409  }
1410 }
1411 
1412 
1413 static void destroy_rate_histogram(struct rate_hist *hist) {
1414  free(hist->pts);
1415  free(hist->sz);
1416 }
1417 
1418 
1419 static void update_rate_histogram(struct rate_hist *hist,
1420  const vpx_codec_enc_cfg_t *cfg,
1421  const vpx_codec_cx_pkt_t *pkt) {
1422  int i, idx;
1423  int64_t now, then, sum_sz = 0, avg_bitrate;
1424 
1425  now = pkt->data.frame.pts * 1000
1426  * (uint64_t)cfg->g_timebase.num / (uint64_t)cfg->g_timebase.den;
1427 
1428  idx = hist->frames++ % hist->samples;
1429  hist->pts[idx] = now;
1430  hist->sz[idx] = (int)pkt->data.frame.sz;
1431 
1432  if (now < cfg->rc_buf_initial_sz)
1433  return;
1434 
1435  then = now;
1436 
1437  /* Sum the size over the past rc_buf_sz ms */
1438  for (i = hist->frames; i > 0 && hist->frames - i < hist->samples; i--) {
1439  int i_idx = (i - 1) % hist->samples;
1440 
1441  then = hist->pts[i_idx];
1442  if (now - then > cfg->rc_buf_sz)
1443  break;
1444  sum_sz += hist->sz[i_idx];
1445  }
1446 
1447  if (now == then)
1448  return;
1449 
1450  avg_bitrate = sum_sz * 8 * 1000 / (now - then);
1451  idx = (int)(avg_bitrate * (RATE_BINS / 2) / (cfg->rc_target_bitrate * 1000));
1452  if (idx < 0)
1453  idx = 0;
1454  if (idx > RATE_BINS - 1)
1455  idx = RATE_BINS - 1;
1456  if (hist->bucket[idx].low > avg_bitrate)
1457  hist->bucket[idx].low = (int)avg_bitrate;
1458  if (hist->bucket[idx].high < avg_bitrate)
1459  hist->bucket[idx].high = (int)avg_bitrate;
1460  hist->bucket[idx].count++;
1461  hist->total++;
1462 }
1463 
1464 
1465 static void show_rate_histogram(struct rate_hist *hist,
1466  const vpx_codec_enc_cfg_t *cfg,
1467  int max_buckets) {
1468  int i, scale;
1469  int buckets = 0;
1470 
1471  for (i = 0; i < RATE_BINS; i++) {
1472  if (hist->bucket[i].low == INT_MAX)
1473  continue;
1474  hist->bucket[buckets++] = hist->bucket[i];
1475  }
1476 
1477  fprintf(stderr, "\nRate (over %dms window):\n", cfg->rc_buf_sz);
1478  scale = merge_hist_buckets(hist->bucket, &buckets, max_buckets);
1479  show_histogram(hist->bucket, buckets, hist->total, scale);
1480 }
1481 
1482 #define mmin(a, b) ((a) < (b) ? (a) : (b))
1483 static void find_mismatch(vpx_image_t *img1, vpx_image_t *img2,
1484  int yloc[2], int uloc[2], int vloc[2]) {
1485  const unsigned int bsize = 64;
1486  const unsigned int bsize2 = bsize >> 1;
1487  unsigned int match = 1;
1488  unsigned int i, j;
1489  yloc[0] = yloc[1] = yloc[2] = yloc[3] = -1;
1490  for (i = 0, match = 1; match && i < img1->d_h; i += bsize) {
1491  for (j = 0; match && j < img1->d_w; j += bsize) {
1492  int k, l;
1493  int si = mmin(i + bsize, img1->d_h) - i;
1494  int sj = mmin(j + bsize, img1->d_w) - j;
1495  for (k = 0; match && k < si; k++)
1496  for (l = 0; match && l < sj; l++) {
1497  if (*(img1->planes[VPX_PLANE_Y] +
1498  (i + k) * img1->stride[VPX_PLANE_Y] + j + l) !=
1499  *(img2->planes[VPX_PLANE_Y] +
1500  (i + k) * img2->stride[VPX_PLANE_Y] + j + l)) {
1501  yloc[0] = i + k;
1502  yloc[1] = j + l;
1503  yloc[2] = *(img1->planes[VPX_PLANE_Y] +
1504  (i + k) * img1->stride[VPX_PLANE_Y] + j + l);
1505  yloc[3] = *(img2->planes[VPX_PLANE_Y] +
1506  (i + k) * img2->stride[VPX_PLANE_Y] + j + l);
1507  match = 0;
1508  break;
1509  }
1510  }
1511  }
1512  }
1513  uloc[0] = uloc[1] = uloc[2] = uloc[3] = -1;
1514  for (i = 0, match = 1; match && i < (img1->d_h + 1) / 2; i += bsize2) {
1515  for (j = 0; j < match && (img1->d_w + 1) / 2; j += bsize2) {
1516  int k, l;
1517  int si = mmin(i + bsize2, (img1->d_h + 1) / 2) - i;
1518  int sj = mmin(j + bsize2, (img1->d_w + 1) / 2) - j;
1519  for (k = 0; match && k < si; k++)
1520  for (l = 0; match && l < sj; l++) {
1521  if (*(img1->planes[VPX_PLANE_U] +
1522  (i + k) * img1->stride[VPX_PLANE_U] + j + l) !=
1523  *(img2->planes[VPX_PLANE_U] +
1524  (i + k) * img2->stride[VPX_PLANE_U] + j + l)) {
1525  uloc[0] = i + k;
1526  uloc[1] = j + l;
1527  uloc[2] = *(img1->planes[VPX_PLANE_U] +
1528  (i + k) * img1->stride[VPX_PLANE_U] + j + l);
1529  uloc[3] = *(img2->planes[VPX_PLANE_U] +
1530  (i + k) * img2->stride[VPX_PLANE_V] + j + l);
1531  match = 0;
1532  break;
1533  }
1534  }
1535  }
1536  }
1537  vloc[0] = vloc[1] = vloc[2] = vloc[3] = -1;
1538  for (i = 0, match = 1; match && i < (img1->d_h + 1) / 2; i += bsize2) {
1539  for (j = 0; j < match && (img1->d_w + 1) / 2; j += bsize2) {
1540  int k, l;
1541  int si = mmin(i + bsize2, (img1->d_h + 1) / 2) - i;
1542  int sj = mmin(j + bsize2, (img1->d_w + 1) / 2) - j;
1543  for (k = 0; match && k < si; k++)
1544  for (l = 0; match && l < sj; l++) {
1545  if (*(img1->planes[VPX_PLANE_V] +
1546  (i + k) * img1->stride[VPX_PLANE_V] + j + l) !=
1547  *(img2->planes[VPX_PLANE_V] +
1548  (i + k) * img2->stride[VPX_PLANE_V] + j + l)) {
1549  vloc[0] = i + k;
1550  vloc[1] = j + l;
1551  vloc[2] = *(img1->planes[VPX_PLANE_V] +
1552  (i + k) * img1->stride[VPX_PLANE_V] + j + l);
1553  vloc[3] = *(img2->planes[VPX_PLANE_V] +
1554  (i + k) * img2->stride[VPX_PLANE_V] + j + l);
1555  match = 0;
1556  break;
1557  }
1558  }
1559  }
1560  }
1561 }
1562 
1563 static int compare_img(vpx_image_t *img1, vpx_image_t *img2)
1564 {
1565  int match = 1;
1566  unsigned int i;
1567 
1568  match &= (img1->fmt == img2->fmt);
1569  match &= (img1->w == img2->w);
1570  match &= (img1->h == img2->h);
1571 
1572  for (i = 0; i < img1->d_h; i++)
1573  match &= (memcmp(img1->planes[VPX_PLANE_Y]+i*img1->stride[VPX_PLANE_Y],
1574  img2->planes[VPX_PLANE_Y]+i*img2->stride[VPX_PLANE_Y],
1575  img1->d_w) == 0);
1576 
1577  for (i = 0; i < img1->d_h/2; i++)
1578  match &= (memcmp(img1->planes[VPX_PLANE_U]+i*img1->stride[VPX_PLANE_U],
1579  img2->planes[VPX_PLANE_U]+i*img2->stride[VPX_PLANE_U],
1580  (img1->d_w + 1) / 2) == 0);
1581 
1582  for (i = 0; i < img1->d_h/2; i++)
1583  match &= (memcmp(img1->planes[VPX_PLANE_V]+i*img1->stride[VPX_PLANE_U],
1584  img2->planes[VPX_PLANE_V]+i*img2->stride[VPX_PLANE_U],
1585  (img1->d_w + 1) / 2) == 0);
1586 
1587  return match;
1588 }
1589 
1590 
1591 #define NELEMENTS(x) (sizeof(x)/sizeof(x[0]))
1592 #define MAX(x,y) ((x)>(y)?(x):(y))
1593 #if CONFIG_VP8_ENCODER && !CONFIG_VP9_ENCODER
1594 #define ARG_CTRL_CNT_MAX NELEMENTS(vp8_arg_ctrl_map)
1595 #elif !CONFIG_VP8_ENCODER && CONFIG_VP9_ENCODER
1596 #define ARG_CTRL_CNT_MAX NELEMENTS(vp9_arg_ctrl_map)
1597 #else
1598 #define ARG_CTRL_CNT_MAX MAX(NELEMENTS(vp8_arg_ctrl_map), \
1599  NELEMENTS(vp9_arg_ctrl_map))
1600 #endif
1601 
1602 /* Configuration elements common to all streams */
1603 struct global_config {
1604  const struct codec_item *codec;
1605  int passes;
1606  int pass;
1607  int usage;
1608  int deadline;
1609  int use_i420;
1610  int quiet;
1611  int verbose;
1612  int limit;
1613  int skip_frames;
1614  int show_psnr;
1615  enum TestDecodeFatality test_decode;
1616  int have_framerate;
1617  struct vpx_rational framerate;
1618  int out_part;
1619  int debug;
1620  int show_q_hist_buckets;
1621  int show_rate_hist_buckets;
1622 };
1623 
1624 
1625 /* Per-stream configuration */
1626 struct stream_config {
1627  struct vpx_codec_enc_cfg cfg;
1628  const char *out_fn;
1629  const char *stats_fn;
1630  stereo_format_t stereo_fmt;
1631  int arg_ctrls[ARG_CTRL_CNT_MAX][2];
1632  int arg_ctrl_cnt;
1633  int write_webm;
1634  int have_kf_max_dist;
1635 };
1636 
1637 
1638 struct stream_state {
1639  int index;
1640  struct stream_state *next;
1641  struct stream_config config;
1642  FILE *file;
1643  struct rate_hist rate_hist;
1644  EbmlGlobal ebml;
1645  uint32_t hash;
1646  uint64_t psnr_sse_total;
1647  uint64_t psnr_samples_total;
1648  double psnr_totals[4];
1649  int psnr_count;
1650  int counts[64];
1651  vpx_codec_ctx_t encoder;
1652  unsigned int frames_out;
1653  uint64_t cx_time;
1654  size_t nbytes;
1655  stats_io_t stats;
1656  struct vpx_image *img;
1657  vpx_codec_ctx_t decoder;
1658  int mismatch_seen;
1659 };
1660 
1661 
1662 void validate_positive_rational(const char *msg,
1663  struct vpx_rational *rat) {
1664  if (rat->den < 0) {
1665  rat->num *= -1;
1666  rat->den *= -1;
1667  }
1668 
1669  if (rat->num < 0)
1670  die("Error: %s must be positive\n", msg);
1671 
1672  if (!rat->den)
1673  die("Error: %s has zero denominator\n", msg);
1674 }
1675 
1676 
1677 static void parse_global_config(struct global_config *global, char **argv) {
1678  char **argi, **argj;
1679  struct arg arg;
1680 
1681  /* Initialize default parameters */
1682  memset(global, 0, sizeof(*global));
1683  global->codec = codecs;
1684  global->passes = 1;
1685  global->use_i420 = 1;
1686 
1687  for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step) {
1688  arg.argv_step = 1;
1689 
1690  if (arg_match(&arg, &codecarg, argi)) {
1691  int j, k = -1;
1692 
1693  for (j = 0; j < sizeof(codecs) / sizeof(codecs[0]); j++)
1694  if (!strcmp(codecs[j].name, arg.val))
1695  k = j;
1696 
1697  if (k >= 0)
1698  global->codec = codecs + k;
1699  else
1700  die("Error: Unrecognized argument (%s) to --codec\n",
1701  arg.val);
1702 
1703  } else if (arg_match(&arg, &passes, argi)) {
1704  global->passes = arg_parse_uint(&arg);
1705 
1706  if (global->passes < 1 || global->passes > 2)
1707  die("Error: Invalid number of passes (%d)\n", global->passes);
1708  } else if (arg_match(&arg, &pass_arg, argi)) {
1709  global->pass = arg_parse_uint(&arg);
1710 
1711  if (global->pass < 1 || global->pass > 2)
1712  die("Error: Invalid pass selected (%d)\n",
1713  global->pass);
1714  } else if (arg_match(&arg, &usage, argi))
1715  global->usage = arg_parse_uint(&arg);
1716  else if (arg_match(&arg, &deadline, argi))
1717  global->deadline = arg_parse_uint(&arg);
1718  else if (arg_match(&arg, &best_dl, argi))
1719  global->deadline = VPX_DL_BEST_QUALITY;
1720  else if (arg_match(&arg, &good_dl, argi))
1721  global->deadline = VPX_DL_GOOD_QUALITY;
1722  else if (arg_match(&arg, &rt_dl, argi))
1723  global->deadline = VPX_DL_REALTIME;
1724  else if (arg_match(&arg, &use_yv12, argi))
1725  global->use_i420 = 0;
1726  else if (arg_match(&arg, &use_i420, argi))
1727  global->use_i420 = 1;
1728  else if (arg_match(&arg, &quietarg, argi))
1729  global->quiet = 1;
1730  else if (arg_match(&arg, &verbosearg, argi))
1731  global->verbose = 1;
1732  else if (arg_match(&arg, &limit, argi))
1733  global->limit = arg_parse_uint(&arg);
1734  else if (arg_match(&arg, &skip, argi))
1735  global->skip_frames = arg_parse_uint(&arg);
1736  else if (arg_match(&arg, &psnrarg, argi))
1737  global->show_psnr = 1;
1738  else if (arg_match(&arg, &recontest, argi))
1739  global->test_decode = arg_parse_enum_or_int(&arg);
1740  else if (arg_match(&arg, &framerate, argi)) {
1741  global->framerate = arg_parse_rational(&arg);
1742  validate_positive_rational(arg.name, &global->framerate);
1743  global->have_framerate = 1;
1744  } else if (arg_match(&arg, &out_part, argi))
1745  global->out_part = 1;
1746  else if (arg_match(&arg, &debugmode, argi))
1747  global->debug = 1;
1748  else if (arg_match(&arg, &q_hist_n, argi))
1749  global->show_q_hist_buckets = arg_parse_uint(&arg);
1750  else if (arg_match(&arg, &rate_hist_n, argi))
1751  global->show_rate_hist_buckets = arg_parse_uint(&arg);
1752  else
1753  argj++;
1754  }
1755 
1756  /* Validate global config */
1757 
1758  if (global->pass) {
1759  /* DWIM: Assume the user meant passes=2 if pass=2 is specified */
1760  if (global->pass > global->passes) {
1761  warn("Assuming --pass=%d implies --passes=%d\n",
1762  global->pass, global->pass);
1763  global->passes = global->pass;
1764  }
1765  }
1766 }
1767 
1768 
1769 void open_input_file(struct input_state *input) {
1770  unsigned int fourcc;
1771 
1772  /* Parse certain options from the input file, if possible */
1773  input->file = strcmp(input->fn, "-") ? fopen(input->fn, "rb")
1774  : set_binary_mode(stdin);
1775 
1776  if (!input->file)
1777  fatal("Failed to open input file");
1778 
1779  if (!fseeko(input->file, 0, SEEK_END)) {
1780  /* Input file is seekable. Figure out how long it is, so we can get
1781  * progress info.
1782  */
1783  input->length = ftello(input->file);
1784  rewind(input->file);
1785  }
1786 
1787  /* For RAW input sources, these bytes will applied on the first frame
1788  * in read_frame().
1789  */
1790  input->detect.buf_read = fread(input->detect.buf, 1, 4, input->file);
1791  input->detect.position = 0;
1792 
1793  if (input->detect.buf_read == 4
1794  && file_is_y4m(input->file, &input->y4m, input->detect.buf)) {
1795  if (y4m_input_open(&input->y4m, input->file, input->detect.buf, 4) >= 0) {
1796  input->file_type = FILE_TYPE_Y4M;
1797  input->w = input->y4m.pic_w;
1798  input->h = input->y4m.pic_h;
1799  input->framerate.num = input->y4m.fps_n;
1800  input->framerate.den = input->y4m.fps_d;
1801  input->use_i420 = 0;
1802  } else
1803  fatal("Unsupported Y4M stream.");
1804  } else if (input->detect.buf_read == 4 && file_is_ivf(input, &fourcc)) {
1805  input->file_type = FILE_TYPE_IVF;
1806  switch (fourcc) {
1807  case 0x32315659:
1808  input->use_i420 = 0;
1809  break;
1810  case 0x30323449:
1811  input->use_i420 = 1;
1812  break;
1813  default:
1814  fatal("Unsupported fourcc (%08x) in IVF", fourcc);
1815  }
1816  } else {
1817  input->file_type = FILE_TYPE_RAW;
1818  }
1819 }
1820 
1821 
1822 static void close_input_file(struct input_state *input) {
1823  fclose(input->file);
1824  if (input->file_type == FILE_TYPE_Y4M)
1825  y4m_input_close(&input->y4m);
1826 }
1827 
1828 static struct stream_state *new_stream(struct global_config *global,
1829  struct stream_state *prev) {
1830  struct stream_state *stream;
1831 
1832  stream = calloc(1, sizeof(*stream));
1833  if (!stream)
1834  fatal("Failed to allocate new stream.");
1835  if (prev) {
1836  memcpy(stream, prev, sizeof(*stream));
1837  stream->index++;
1838  prev->next = stream;
1839  } else {
1840  vpx_codec_err_t res;
1841 
1842  /* Populate encoder configuration */
1843  res = vpx_codec_enc_config_default(global->codec->iface(),
1844  &stream->config.cfg,
1845  global->usage);
1846  if (res)
1847  fatal("Failed to get config: %s\n", vpx_codec_err_to_string(res));
1848 
1849  /* Change the default timebase to a high enough value so that the
1850  * encoder will always create strictly increasing timestamps.
1851  */
1852  stream->config.cfg.g_timebase.den = 1000;
1853 
1854  /* Never use the library's default resolution, require it be parsed
1855  * from the file or set on the command line.
1856  */
1857  stream->config.cfg.g_w = 0;
1858  stream->config.cfg.g_h = 0;
1859 
1860  /* Initialize remaining stream parameters */
1861  stream->config.stereo_fmt = STEREO_FORMAT_MONO;
1862  stream->config.write_webm = 1;
1863  stream->ebml.last_pts_ms = -1;
1864 
1865  /* Allows removal of the application version from the EBML tags */
1866  stream->ebml.debug = global->debug;
1867  }
1868 
1869  /* Output files must be specified for each stream */
1870  stream->config.out_fn = NULL;
1871 
1872  stream->next = NULL;
1873  return stream;
1874 }
1875 
1876 
1877 static int parse_stream_params(struct global_config *global,
1878  struct stream_state *stream,
1879  char **argv) {
1880  char **argi, **argj;
1881  struct arg arg;
1882  static const arg_def_t **ctrl_args = no_args;
1883  static const int *ctrl_args_map = NULL;
1884  struct stream_config *config = &stream->config;
1885  int eos_mark_found = 0;
1886 
1887  /* Handle codec specific options */
1888  if (0) {
1889 #if CONFIG_VP8_ENCODER
1890  } else if (global->codec->iface == vpx_codec_vp8_cx) {
1891  ctrl_args = vp8_args;
1892  ctrl_args_map = vp8_arg_ctrl_map;
1893 #endif
1894 #if CONFIG_VP9_ENCODER
1895  } else if (global->codec->iface == vpx_codec_vp9_cx) {
1896  ctrl_args = vp9_args;
1897  ctrl_args_map = vp9_arg_ctrl_map;
1898 #endif
1899  }
1900 
1901  for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step) {
1902  arg.argv_step = 1;
1903 
1904  /* Once we've found an end-of-stream marker (--) we want to continue
1905  * shifting arguments but not consuming them.
1906  */
1907  if (eos_mark_found) {
1908  argj++;
1909  continue;
1910  } else if (!strcmp(*argj, "--")) {
1911  eos_mark_found = 1;
1912  continue;
1913  }
1914 
1915  if (0);
1916  else if (arg_match(&arg, &outputfile, argi))
1917  config->out_fn = arg.val;
1918  else if (arg_match(&arg, &fpf_name, argi))
1919  config->stats_fn = arg.val;
1920  else if (arg_match(&arg, &use_ivf, argi))
1921  config->write_webm = 0;
1922  else if (arg_match(&arg, &threads, argi))
1923  config->cfg.g_threads = arg_parse_uint(&arg);
1924  else if (arg_match(&arg, &profile, argi))
1925  config->cfg.g_profile = arg_parse_uint(&arg);
1926  else if (arg_match(&arg, &width, argi))
1927  config->cfg.g_w = arg_parse_uint(&arg);
1928  else if (arg_match(&arg, &height, argi))
1929  config->cfg.g_h = arg_parse_uint(&arg);
1930  else if (arg_match(&arg, &stereo_mode, argi))
1931  config->stereo_fmt = arg_parse_enum_or_int(&arg);
1932  else if (arg_match(&arg, &timebase, argi)) {
1933  config->cfg.g_timebase = arg_parse_rational(&arg);
1934  validate_positive_rational(arg.name, &config->cfg.g_timebase);
1935  } else if (arg_match(&arg, &error_resilient, argi))
1936  config->cfg.g_error_resilient = arg_parse_uint(&arg);
1937  else if (arg_match(&arg, &lag_in_frames, argi))
1938  config->cfg.g_lag_in_frames = arg_parse_uint(&arg);
1939  else if (arg_match(&arg, &dropframe_thresh, argi))
1940  config->cfg.rc_dropframe_thresh = arg_parse_uint(&arg);
1941  else if (arg_match(&arg, &resize_allowed, argi))
1942  config->cfg.rc_resize_allowed = arg_parse_uint(&arg);
1943  else if (arg_match(&arg, &resize_up_thresh, argi))
1944  config->cfg.rc_resize_up_thresh = arg_parse_uint(&arg);
1945  else if (arg_match(&arg, &resize_down_thresh, argi))
1946  config->cfg.rc_resize_down_thresh = arg_parse_uint(&arg);
1947  else if (arg_match(&arg, &end_usage, argi))
1948  config->cfg.rc_end_usage = arg_parse_enum_or_int(&arg);
1949  else if (arg_match(&arg, &target_bitrate, argi))
1950  config->cfg.rc_target_bitrate = arg_parse_uint(&arg);
1951  else if (arg_match(&arg, &min_quantizer, argi))
1952  config->cfg.rc_min_quantizer = arg_parse_uint(&arg);
1953  else if (arg_match(&arg, &max_quantizer, argi))
1954  config->cfg.rc_max_quantizer = arg_parse_uint(&arg);
1955  else if (arg_match(&arg, &undershoot_pct, argi))
1956  config->cfg.rc_undershoot_pct = arg_parse_uint(&arg);
1957  else if (arg_match(&arg, &overshoot_pct, argi))
1958  config->cfg.rc_overshoot_pct = arg_parse_uint(&arg);
1959  else if (arg_match(&arg, &buf_sz, argi))
1960  config->cfg.rc_buf_sz = arg_parse_uint(&arg);
1961  else if (arg_match(&arg, &buf_initial_sz, argi))
1962  config->cfg.rc_buf_initial_sz = arg_parse_uint(&arg);
1963  else if (arg_match(&arg, &buf_optimal_sz, argi))
1964  config->cfg.rc_buf_optimal_sz = arg_parse_uint(&arg);
1965  else if (arg_match(&arg, &bias_pct, argi)) {
1966  config->cfg.rc_2pass_vbr_bias_pct = arg_parse_uint(&arg);
1967 
1968  if (global->passes < 2)
1969  warn("option %s ignored in one-pass mode.\n", arg.name);
1970  } else if (arg_match(&arg, &minsection_pct, argi)) {
1971  config->cfg.rc_2pass_vbr_minsection_pct = arg_parse_uint(&arg);
1972 
1973  if (global->passes < 2)
1974  warn("option %s ignored in one-pass mode.\n", arg.name);
1975  } else if (arg_match(&arg, &maxsection_pct, argi)) {
1976  config->cfg.rc_2pass_vbr_maxsection_pct = arg_parse_uint(&arg);
1977 
1978  if (global->passes < 2)
1979  warn("option %s ignored in one-pass mode.\n", arg.name);
1980  } else if (arg_match(&arg, &kf_min_dist, argi))
1981  config->cfg.kf_min_dist = arg_parse_uint(&arg);
1982  else if (arg_match(&arg, &kf_max_dist, argi)) {
1983  config->cfg.kf_max_dist = arg_parse_uint(&arg);
1984  config->have_kf_max_dist = 1;
1985  } else if (arg_match(&arg, &kf_disabled, argi))
1986  config->cfg.kf_mode = VPX_KF_DISABLED;
1987  else {
1988  int i, match = 0;
1989 
1990  for (i = 0; ctrl_args[i]; i++) {
1991  if (arg_match(&arg, ctrl_args[i], argi)) {
1992  int j;
1993  match = 1;
1994 
1995  /* Point either to the next free element or the first
1996  * instance of this control.
1997  */
1998  for (j = 0; j < config->arg_ctrl_cnt; j++)
1999  if (config->arg_ctrls[j][0] == ctrl_args_map[i])
2000  break;
2001 
2002  /* Update/insert */
2003  assert(j < ARG_CTRL_CNT_MAX);
2004  if (j < ARG_CTRL_CNT_MAX) {
2005  config->arg_ctrls[j][0] = ctrl_args_map[i];
2006  config->arg_ctrls[j][1] = arg_parse_enum_or_int(&arg);
2007  if (j == config->arg_ctrl_cnt)
2008  config->arg_ctrl_cnt++;
2009  }
2010 
2011  }
2012  }
2013 
2014  if (!match)
2015  argj++;
2016  }
2017  }
2018 
2019  return eos_mark_found;
2020 }
2021 
2022 
2023 #define FOREACH_STREAM(func)\
2024  do\
2025  {\
2026  struct stream_state *stream;\
2027  \
2028  for(stream = streams; stream; stream = stream->next)\
2029  func;\
2030  }while(0)
2031 
2032 
2033 static void validate_stream_config(struct stream_state *stream) {
2034  struct stream_state *streami;
2035 
2036  if (!stream->config.cfg.g_w || !stream->config.cfg.g_h)
2037  fatal("Stream %d: Specify stream dimensions with --width (-w) "
2038  " and --height (-h)", stream->index);
2039 
2040  for (streami = stream; streami; streami = streami->next) {
2041  /* All streams require output files */
2042  if (!streami->config.out_fn)
2043  fatal("Stream %d: Output file is required (specify with -o)",
2044  streami->index);
2045 
2046  /* Check for two streams outputting to the same file */
2047  if (streami != stream) {
2048  const char *a = stream->config.out_fn;
2049  const char *b = streami->config.out_fn;
2050  if (!strcmp(a, b) && strcmp(a, "/dev/null") && strcmp(a, ":nul"))
2051  fatal("Stream %d: duplicate output file (from stream %d)",
2052  streami->index, stream->index);
2053  }
2054 
2055  /* Check for two streams sharing a stats file. */
2056  if (streami != stream) {
2057  const char *a = stream->config.stats_fn;
2058  const char *b = streami->config.stats_fn;
2059  if (a && b && !strcmp(a, b))
2060  fatal("Stream %d: duplicate stats file (from stream %d)",
2061  streami->index, stream->index);
2062  }
2063  }
2064 }
2065 
2066 
2067 static void set_stream_dimensions(struct stream_state *stream,
2068  unsigned int w,
2069  unsigned int h) {
2070  if (!stream->config.cfg.g_w) {
2071  if (!stream->config.cfg.g_h)
2072  stream->config.cfg.g_w = w;
2073  else
2074  stream->config.cfg.g_w = w * stream->config.cfg.g_h / h;
2075  }
2076  if (!stream->config.cfg.g_h) {
2077  stream->config.cfg.g_h = h * stream->config.cfg.g_w / w;
2078  }
2079 }
2080 
2081 
2082 static void set_default_kf_interval(struct stream_state *stream,
2083  struct global_config *global) {
2084  /* Use a max keyframe interval of 5 seconds, if none was
2085  * specified on the command line.
2086  */
2087  if (!stream->config.have_kf_max_dist) {
2088  double framerate = (double)global->framerate.num / global->framerate.den;
2089  if (framerate > 0.0)
2090  stream->config.cfg.kf_max_dist = (unsigned int)(5.0 * framerate);
2091  }
2092 }
2093 
2094 
2095 static void show_stream_config(struct stream_state *stream,
2096  struct global_config *global,
2097  struct input_state *input) {
2098 
2099 #define SHOW(field) \
2100  fprintf(stderr, " %-28s = %d\n", #field, stream->config.cfg.field)
2101 
2102  if (stream->index == 0) {
2103  fprintf(stderr, "Codec: %s\n",
2104  vpx_codec_iface_name(global->codec->iface()));
2105  fprintf(stderr, "Source file: %s Format: %s\n", input->fn,
2106  input->use_i420 ? "I420" : "YV12");
2107  }
2108  if (stream->next || stream->index)
2109  fprintf(stderr, "\nStream Index: %d\n", stream->index);
2110  fprintf(stderr, "Destination file: %s\n", stream->config.out_fn);
2111  fprintf(stderr, "Encoder parameters:\n");
2112 
2113  SHOW(g_usage);
2114  SHOW(g_threads);
2115  SHOW(g_profile);
2116  SHOW(g_w);
2117  SHOW(g_h);
2118  SHOW(g_timebase.num);
2119  SHOW(g_timebase.den);
2120  SHOW(g_error_resilient);
2121  SHOW(g_pass);
2122  SHOW(g_lag_in_frames);
2123  SHOW(rc_dropframe_thresh);
2124  SHOW(rc_resize_allowed);
2125  SHOW(rc_resize_up_thresh);
2126  SHOW(rc_resize_down_thresh);
2127  SHOW(rc_end_usage);
2128  SHOW(rc_target_bitrate);
2129  SHOW(rc_min_quantizer);
2130  SHOW(rc_max_quantizer);
2131  SHOW(rc_undershoot_pct);
2132  SHOW(rc_overshoot_pct);
2133  SHOW(rc_buf_sz);
2134  SHOW(rc_buf_initial_sz);
2135  SHOW(rc_buf_optimal_sz);
2136  SHOW(rc_2pass_vbr_bias_pct);
2137  SHOW(rc_2pass_vbr_minsection_pct);
2138  SHOW(rc_2pass_vbr_maxsection_pct);
2139  SHOW(kf_mode);
2140  SHOW(kf_min_dist);
2141  SHOW(kf_max_dist);
2142 }
2143 
2144 
2145 static void open_output_file(struct stream_state *stream,
2146  struct global_config *global) {
2147  const char *fn = stream->config.out_fn;
2148 
2149  stream->file = strcmp(fn, "-") ? fopen(fn, "wb") : set_binary_mode(stdout);
2150 
2151  if (!stream->file)
2152  fatal("Failed to open output file");
2153 
2154  if (stream->config.write_webm && fseek(stream->file, 0, SEEK_CUR))
2155  fatal("WebM output to pipes not supported.");
2156 
2157  if (stream->config.write_webm) {
2158  stream->ebml.stream = stream->file;
2159  write_webm_file_header(&stream->ebml, &stream->config.cfg,
2160  &global->framerate,
2161  stream->config.stereo_fmt,
2162  global->codec->fourcc);
2163  } else
2164  write_ivf_file_header(stream->file, &stream->config.cfg,
2165  global->codec->fourcc, 0);
2166 }
2167 
2168 
2169 static void close_output_file(struct stream_state *stream,
2170  unsigned int fourcc) {
2171  if (stream->config.write_webm) {
2172  write_webm_file_footer(&stream->ebml, stream->hash);
2173  free(stream->ebml.cue_list);
2174  stream->ebml.cue_list = NULL;
2175  } else {
2176  if (!fseek(stream->file, 0, SEEK_SET))
2177  write_ivf_file_header(stream->file, &stream->config.cfg,
2178  fourcc,
2179  stream->frames_out);
2180  }
2181 
2182  fclose(stream->file);
2183 }
2184 
2185 
2186 static void setup_pass(struct stream_state *stream,
2187  struct global_config *global,
2188  int pass) {
2189  if (stream->config.stats_fn) {
2190  if (!stats_open_file(&stream->stats, stream->config.stats_fn,
2191  pass))
2192  fatal("Failed to open statistics store");
2193  } else {
2194  if (!stats_open_mem(&stream->stats, pass))
2195  fatal("Failed to open statistics store");
2196  }
2197 
2198  stream->config.cfg.g_pass = global->passes == 2
2200  : VPX_RC_ONE_PASS;
2201  if (pass)
2202  stream->config.cfg.rc_twopass_stats_in = stats_get(&stream->stats);
2203 
2204  stream->cx_time = 0;
2205  stream->nbytes = 0;
2206  stream->frames_out = 0;
2207 }
2208 
2209 
2210 static void initialize_encoder(struct stream_state *stream,
2211  struct global_config *global) {
2212  int i;
2213  int flags = 0;
2214 
2215  flags |= global->show_psnr ? VPX_CODEC_USE_PSNR : 0;
2216  flags |= global->out_part ? VPX_CODEC_USE_OUTPUT_PARTITION : 0;
2217 
2218  /* Construct Encoder Context */
2219  vpx_codec_enc_init(&stream->encoder, global->codec->iface(),
2220  &stream->config.cfg, flags);
2221  ctx_exit_on_error(&stream->encoder, "Failed to initialize encoder");
2222 
2223  /* Note that we bypass the vpx_codec_control wrapper macro because
2224  * we're being clever to store the control IDs in an array. Real
2225  * applications will want to make use of the enumerations directly
2226  */
2227  for (i = 0; i < stream->config.arg_ctrl_cnt; i++) {
2228  int ctrl = stream->config.arg_ctrls[i][0];
2229  int value = stream->config.arg_ctrls[i][1];
2230  if (vpx_codec_control_(&stream->encoder, ctrl, value))
2231  fprintf(stderr, "Error: Tried to set control %d = %d\n",
2232  ctrl, value);
2233 
2234  ctx_exit_on_error(&stream->encoder, "Failed to control codec");
2235  }
2236 
2237 #if CONFIG_DECODERS
2238  if (global->test_decode != TEST_DECODE_OFF) {
2239  vpx_codec_dec_init(&stream->decoder, global->codec->dx_iface(), NULL, 0);
2240  }
2241 #endif
2242 }
2243 
2244 
2245 static void encode_frame(struct stream_state *stream,
2246  struct global_config *global,
2247  struct vpx_image *img,
2248  unsigned int frames_in) {
2249  vpx_codec_pts_t frame_start, next_frame_start;
2250  struct vpx_codec_enc_cfg *cfg = &stream->config.cfg;
2251  struct vpx_usec_timer timer;
2252 
2253  frame_start = (cfg->g_timebase.den * (int64_t)(frames_in - 1)
2254  * global->framerate.den)
2255  / cfg->g_timebase.num / global->framerate.num;
2256  next_frame_start = (cfg->g_timebase.den * (int64_t)(frames_in)
2257  * global->framerate.den)
2258  / cfg->g_timebase.num / global->framerate.num;
2259 
2260  /* Scale if necessary */
2261  if (img && (img->d_w != cfg->g_w || img->d_h != cfg->g_h)) {
2262  if (!stream->img)
2263  stream->img = vpx_img_alloc(NULL, VPX_IMG_FMT_I420,
2264  cfg->g_w, cfg->g_h, 16);
2265  I420Scale(img->planes[VPX_PLANE_Y], img->stride[VPX_PLANE_Y],
2266  img->planes[VPX_PLANE_U], img->stride[VPX_PLANE_U],
2267  img->planes[VPX_PLANE_V], img->stride[VPX_PLANE_V],
2268  img->d_w, img->d_h,
2269  stream->img->planes[VPX_PLANE_Y],
2270  stream->img->stride[VPX_PLANE_Y],
2271  stream->img->planes[VPX_PLANE_U],
2272  stream->img->stride[VPX_PLANE_U],
2273  stream->img->planes[VPX_PLANE_V],
2274  stream->img->stride[VPX_PLANE_V],
2275  stream->img->d_w, stream->img->d_h,
2276  kFilterBox);
2277 
2278  img = stream->img;
2279  }
2280 
2281  vpx_usec_timer_start(&timer);
2282  vpx_codec_encode(&stream->encoder, img, frame_start,
2283  (unsigned long)(next_frame_start - frame_start),
2284  0, global->deadline);
2285  vpx_usec_timer_mark(&timer);
2286  stream->cx_time += vpx_usec_timer_elapsed(&timer);
2287  ctx_exit_on_error(&stream->encoder, "Stream %d: Failed to encode frame",
2288  stream->index);
2289 }
2290 
2291 
2292 static void update_quantizer_histogram(struct stream_state *stream) {
2293  if (stream->config.cfg.g_pass != VPX_RC_FIRST_PASS) {
2294  int q;
2295 
2296  vpx_codec_control(&stream->encoder, VP8E_GET_LAST_QUANTIZER_64, &q);
2297  ctx_exit_on_error(&stream->encoder, "Failed to read quantizer");
2298  stream->counts[q]++;
2299  }
2300 }
2301 
2302 
2303 static void get_cx_data(struct stream_state *stream,
2304  struct global_config *global,
2305  int *got_data) {
2306  const vpx_codec_cx_pkt_t *pkt;
2307  const struct vpx_codec_enc_cfg *cfg = &stream->config.cfg;
2308  vpx_codec_iter_t iter = NULL;
2309 
2310  *got_data = 0;
2311  while ((pkt = vpx_codec_get_cx_data(&stream->encoder, &iter))) {
2312  static size_t fsize = 0;
2313  static off_t ivf_header_pos = 0;
2314 
2315  switch (pkt->kind) {
2317  if (!(pkt->data.frame.flags & VPX_FRAME_IS_FRAGMENT)) {
2318  stream->frames_out++;
2319  }
2320  if (!global->quiet)
2321  fprintf(stderr, " %6luF", (unsigned long)pkt->data.frame.sz);
2322 
2323  update_rate_histogram(&stream->rate_hist, cfg, pkt);
2324  if (stream->config.write_webm) {
2325  /* Update the hash */
2326  if (!stream->ebml.debug)
2327  stream->hash = murmur(pkt->data.frame.buf,
2328  (int)pkt->data.frame.sz,
2329  stream->hash);
2330 
2331  write_webm_block(&stream->ebml, cfg, pkt);
2332  } else {
2333  if (pkt->data.frame.partition_id <= 0) {
2334  ivf_header_pos = ftello(stream->file);
2335  fsize = pkt->data.frame.sz;
2336 
2337  write_ivf_frame_header(stream->file, pkt);
2338  } else {
2339  fsize += pkt->data.frame.sz;
2340 
2341  if (!(pkt->data.frame.flags & VPX_FRAME_IS_FRAGMENT)) {
2342  off_t currpos = ftello(stream->file);
2343  fseeko(stream->file, ivf_header_pos, SEEK_SET);
2344  write_ivf_frame_size(stream->file, fsize);
2345  fseeko(stream->file, currpos, SEEK_SET);
2346  }
2347  }
2348 
2349  (void) fwrite(pkt->data.frame.buf, 1, pkt->data.frame.sz,
2350  stream->file);
2351  }
2352  stream->nbytes += pkt->data.raw.sz;
2353 
2354  *got_data = 1;
2355 #if CONFIG_DECODERS
2356  if (global->test_decode != TEST_DECODE_OFF && !stream->mismatch_seen) {
2357  vpx_codec_decode(&stream->decoder, pkt->data.frame.buf,
2358  pkt->data.frame.sz, NULL, 0);
2359  if (stream->decoder.err) {
2360  warn_or_exit_on_error(&stream->decoder,
2361  global->test_decode == TEST_DECODE_FATAL,
2362  "Failed to decode frame %d in stream %d",
2363  stream->frames_out + 1, stream->index);
2364  stream->mismatch_seen = stream->frames_out + 1;
2365  }
2366  }
2367 #endif
2368  break;
2369  case VPX_CODEC_STATS_PKT:
2370  stream->frames_out++;
2371  stats_write(&stream->stats,
2372  pkt->data.twopass_stats.buf,
2373  pkt->data.twopass_stats.sz);
2374  stream->nbytes += pkt->data.raw.sz;
2375  break;
2376  case VPX_CODEC_PSNR_PKT:
2377 
2378  if (global->show_psnr) {
2379  int i;
2380 
2381  stream->psnr_sse_total += pkt->data.psnr.sse[0];
2382  stream->psnr_samples_total += pkt->data.psnr.samples[0];
2383  for (i = 0; i < 4; i++) {
2384  if (!global->quiet)
2385  fprintf(stderr, "%.3f ", pkt->data.psnr.psnr[i]);
2386  stream->psnr_totals[i] += pkt->data.psnr.psnr[i];
2387  }
2388  stream->psnr_count++;
2389  }
2390 
2391  break;
2392  default:
2393  break;
2394  }
2395  }
2396 }
2397 
2398 
2399 static void show_psnr(struct stream_state *stream) {
2400  int i;
2401  double ovpsnr;
2402 
2403  if (!stream->psnr_count)
2404  return;
2405 
2406  fprintf(stderr, "Stream %d PSNR (Overall/Avg/Y/U/V)", stream->index);
2407  ovpsnr = vp8_mse2psnr((double)stream->psnr_samples_total, 255.0,
2408  (double)stream->psnr_sse_total);
2409  fprintf(stderr, " %.3f", ovpsnr);
2410 
2411  for (i = 0; i < 4; i++) {
2412  fprintf(stderr, " %.3f", stream->psnr_totals[i] / stream->psnr_count);
2413  }
2414  fprintf(stderr, "\n");
2415 }
2416 
2417 
2418 static float usec_to_fps(uint64_t usec, unsigned int frames) {
2419  return (float)(usec > 0 ? frames * 1000000.0 / (float)usec : 0);
2420 }
2421 
2422 
2423 static void test_decode(struct stream_state *stream,
2424  enum TestDecodeFatality fatal,
2425  const struct codec_item *codec) {
2426  vpx_image_t enc_img, dec_img;
2427 
2428  if (stream->mismatch_seen)
2429  return;
2430 
2431  /* Get the internal reference frame */
2432  if (codec->fourcc == VP8_FOURCC) {
2433  struct vpx_ref_frame ref_enc, ref_dec;
2434  int width, height;
2435 
2436  width = (stream->config.cfg.g_w + 15) & ~15;
2437  height = (stream->config.cfg.g_h + 15) & ~15;
2438  vpx_img_alloc(&ref_enc.img, VPX_IMG_FMT_I420, width, height, 1);
2439  enc_img = ref_enc.img;
2440  vpx_img_alloc(&ref_dec.img, VPX_IMG_FMT_I420, width, height, 1);
2441  dec_img = ref_dec.img;
2442 
2443  ref_enc.frame_type = VP8_LAST_FRAME;
2444  ref_dec.frame_type = VP8_LAST_FRAME;
2445  vpx_codec_control(&stream->encoder, VP8_COPY_REFERENCE, &ref_enc);
2446  vpx_codec_control(&stream->decoder, VP8_COPY_REFERENCE, &ref_dec);
2447  } else {
2448  struct vp9_ref_frame ref;
2449 
2450  ref.idx = 0;
2451  vpx_codec_control(&stream->encoder, VP9_GET_REFERENCE, &ref);
2452  enc_img = ref.img;
2453  vpx_codec_control(&stream->decoder, VP9_GET_REFERENCE, &ref);
2454  dec_img = ref.img;
2455  }
2456  ctx_exit_on_error(&stream->encoder, "Failed to get encoder reference frame");
2457  ctx_exit_on_error(&stream->decoder, "Failed to get decoder reference frame");
2458 
2459  if (!compare_img(&enc_img, &dec_img)) {
2460  int y[4], u[4], v[4];
2461  find_mismatch(&enc_img, &dec_img, y, u, v);
2462  stream->decoder.err = 1;
2463  warn_or_exit_on_error(&stream->decoder, fatal == TEST_DECODE_FATAL,
2464  "Stream %d: Encode/decode mismatch on frame %d at"
2465  " Y[%d, %d] {%d/%d},"
2466  " U[%d, %d] {%d/%d},"
2467  " V[%d, %d] {%d/%d}",
2468  stream->index, stream->frames_out,
2469  y[0], y[1], y[2], y[3],
2470  u[0], u[1], u[2], u[3],
2471  v[0], v[1], v[2], v[3]);
2472  stream->mismatch_seen = stream->frames_out;
2473  }
2474 
2475  vpx_img_free(&enc_img);
2476  vpx_img_free(&dec_img);
2477 }
2478 
2479 
2480 static void print_time(const char *label, int64_t etl) {
2481  int hours, mins, secs;
2482 
2483  if (etl >= 0) {
2484  hours = etl / 3600;
2485  etl -= hours * 3600;
2486  mins = etl / 60;
2487  etl -= mins * 60;
2488  secs = etl;
2489 
2490  fprintf(stderr, "[%3s %2d:%02d:%02d] ",
2491  label, hours, mins, secs);
2492  } else {
2493  fprintf(stderr, "[%3s unknown] ", label);
2494  }
2495 }
2496 
2497 int main(int argc, const char **argv_) {
2498  int pass;
2499  vpx_image_t raw;
2500  int frame_avail, got_data;
2501 
2502  struct input_state input = {0};
2503  struct global_config global;
2504  struct stream_state *streams = NULL;
2505  char **argv, **argi;
2506  uint64_t cx_time = 0;
2507  int stream_cnt = 0;
2508  int res = 0;
2509 
2510  exec_name = argv_[0];
2511 
2512  if (argc < 3)
2513  usage_exit();
2514 
2515  /* Setup default input stream settings */
2516  input.framerate.num = 30;
2517  input.framerate.den = 1;
2518  input.use_i420 = 1;
2519 
2520  /* First parse the global configuration values, because we want to apply
2521  * other parameters on top of the default configuration provided by the
2522  * codec.
2523  */
2524  argv = argv_dup(argc - 1, argv_ + 1);
2525  parse_global_config(&global, argv);
2526 
2527  {
2528  /* Now parse each stream's parameters. Using a local scope here
2529  * due to the use of 'stream' as loop variable in FOREACH_STREAM
2530  * loops
2531  */
2532  struct stream_state *stream = NULL;
2533 
2534  do {
2535  stream = new_stream(&global, stream);
2536  stream_cnt++;
2537  if (!streams)
2538  streams = stream;
2539  } while (parse_stream_params(&global, stream, argv));
2540  }
2541 
2542  /* Check for unrecognized options */
2543  for (argi = argv; *argi; argi++)
2544  if (argi[0][0] == '-' && argi[0][1])
2545  die("Error: Unrecognized option %s\n", *argi);
2546 
2547  /* Handle non-option arguments */
2548  input.fn = argv[0];
2549 
2550  if (!input.fn)
2551  usage_exit();
2552 
2553  for (pass = global.pass ? global.pass - 1 : 0; pass < global.passes; pass++) {
2554  int frames_in = 0, seen_frames = 0;
2555  int64_t estimated_time_left = -1;
2556  int64_t average_rate = -1;
2557  off_t lagged_count = 0;
2558 
2559  open_input_file(&input);
2560 
2561  /* If the input file doesn't specify its w/h (raw files), try to get
2562  * the data from the first stream's configuration.
2563  */
2564  if (!input.w || !input.h)
2565  FOREACH_STREAM( {
2566  if (stream->config.cfg.g_w && stream->config.cfg.g_h) {
2567  input.w = stream->config.cfg.g_w;
2568  input.h = stream->config.cfg.g_h;
2569  break;
2570  }
2571  });
2572 
2573  /* Update stream configurations from the input file's parameters */
2574  if (!input.w || !input.h)
2575  fatal("Specify stream dimensions with --width (-w) "
2576  " and --height (-h)");
2577  FOREACH_STREAM(set_stream_dimensions(stream, input.w, input.h));
2578  FOREACH_STREAM(validate_stream_config(stream));
2579 
2580  /* Ensure that --passes and --pass are consistent. If --pass is set and
2581  * --passes=2, ensure --fpf was set.
2582  */
2583  if (global.pass && global.passes == 2)
2584  FOREACH_STREAM( {
2585  if (!stream->config.stats_fn)
2586  die("Stream %d: Must specify --fpf when --pass=%d"
2587  " and --passes=2\n", stream->index, global.pass);
2588  });
2589 
2590  /* Use the frame rate from the file only if none was specified
2591  * on the command-line.
2592  */
2593  if (!global.have_framerate)
2594  global.framerate = input.framerate;
2595 
2596  FOREACH_STREAM(set_default_kf_interval(stream, &global));
2597 
2598  /* Show configuration */
2599  if (global.verbose && pass == 0)
2600  FOREACH_STREAM(show_stream_config(stream, &global, &input));
2601 
2602  if (pass == (global.pass ? global.pass - 1 : 0)) {
2603  if (input.file_type == FILE_TYPE_Y4M)
2604  /*The Y4M reader does its own allocation.
2605  Just initialize this here to avoid problems if we never read any
2606  frames.*/
2607  memset(&raw, 0, sizeof(raw));
2608  else
2609  vpx_img_alloc(&raw,
2610  input.use_i420 ? VPX_IMG_FMT_I420
2611  : VPX_IMG_FMT_YV12,
2612  input.w, input.h, 32);
2613 
2614  FOREACH_STREAM(init_rate_histogram(&stream->rate_hist,
2615  &stream->config.cfg,
2616  &global.framerate));
2617  }
2618 
2619  FOREACH_STREAM(open_output_file(stream, &global));
2620  FOREACH_STREAM(setup_pass(stream, &global, pass));
2621  FOREACH_STREAM(initialize_encoder(stream, &global));
2622 
2623  frame_avail = 1;
2624  got_data = 0;
2625 
2626  while (frame_avail || got_data) {
2627  struct vpx_usec_timer timer;
2628 
2629  if (!global.limit || frames_in < global.limit) {
2630  frame_avail = read_frame(&input, &raw);
2631 
2632  if (frame_avail)
2633  frames_in++;
2634  seen_frames = frames_in > global.skip_frames ?
2635  frames_in - global.skip_frames : 0;
2636 
2637  if (!global.quiet) {
2638  float fps = usec_to_fps(cx_time, seen_frames);
2639  fprintf(stderr, "\rPass %d/%d ", pass + 1, global.passes);
2640 
2641  if (stream_cnt == 1)
2642  fprintf(stderr,
2643  "frame %4d/%-4d %7"PRId64"B ",
2644  frames_in, streams->frames_out, (int64_t)streams->nbytes);
2645  else
2646  fprintf(stderr, "frame %4d ", frames_in);
2647 
2648  fprintf(stderr, "%7"PRId64" %s %.2f %s ",
2649  cx_time > 9999999 ? cx_time / 1000 : cx_time,
2650  cx_time > 9999999 ? "ms" : "us",
2651  fps >= 1.0 ? fps : 1000.0 / fps,
2652  fps >= 1.0 ? "fps" : "ms/f");
2653  print_time("ETA", estimated_time_left);
2654  fprintf(stderr, "\033[K");
2655  }
2656 
2657  } else
2658  frame_avail = 0;
2659 
2660  if (frames_in > global.skip_frames) {
2661  vpx_usec_timer_start(&timer);
2662  FOREACH_STREAM(encode_frame(stream, &global,
2663  frame_avail ? &raw : NULL,
2664  frames_in));
2665  vpx_usec_timer_mark(&timer);
2666  cx_time += vpx_usec_timer_elapsed(&timer);
2667 
2668  FOREACH_STREAM(update_quantizer_histogram(stream));
2669 
2670  got_data = 0;
2671  FOREACH_STREAM(get_cx_data(stream, &global, &got_data));
2672 
2673  if (!got_data && input.length && !streams->frames_out) {
2674  lagged_count = global.limit ? seen_frames : ftello(input.file);
2675  } else if (input.length) {
2676  int64_t remaining;
2677  int64_t rate;
2678 
2679  if (global.limit) {
2680  int frame_in_lagged = (seen_frames - lagged_count) * 1000;
2681 
2682  rate = cx_time ? frame_in_lagged * (int64_t)1000000 / cx_time : 0;
2683  remaining = 1000 * (global.limit - global.skip_frames
2684  - seen_frames + lagged_count);
2685  } else {
2686  off_t input_pos = ftello(input.file);
2687  off_t input_pos_lagged = input_pos - lagged_count;
2688  int64_t limit = input.length;
2689 
2690  rate = cx_time ? input_pos_lagged * (int64_t)1000000 / cx_time : 0;
2691  remaining = limit - input_pos + lagged_count;
2692  }
2693 
2694  average_rate = (average_rate <= 0)
2695  ? rate
2696  : (average_rate * 7 + rate) / 8;
2697  estimated_time_left = average_rate ? remaining / average_rate : -1;
2698  }
2699 
2700  if (got_data && global.test_decode != TEST_DECODE_OFF)
2701  FOREACH_STREAM(test_decode(stream, global.test_decode, global.codec));
2702  }
2703 
2704  fflush(stdout);
2705  }
2706 
2707  if (stream_cnt > 1)
2708  fprintf(stderr, "\n");
2709 
2710  if (!global.quiet)
2711  FOREACH_STREAM(fprintf(
2712  stderr,
2713  "\rPass %d/%d frame %4d/%-4d %7"PRId64"B %7lub/f %7"PRId64"b/s"
2714  " %7"PRId64" %s (%.2f fps)\033[K\n", pass + 1,
2715  global.passes, frames_in, stream->frames_out, (int64_t)stream->nbytes,
2716  seen_frames ? (unsigned long)(stream->nbytes * 8 / seen_frames) : 0,
2717  seen_frames ? (int64_t)stream->nbytes * 8
2718  * (int64_t)global.framerate.num / global.framerate.den
2719  / seen_frames
2720  : 0,
2721  stream->cx_time > 9999999 ? stream->cx_time / 1000 : stream->cx_time,
2722  stream->cx_time > 9999999 ? "ms" : "us",
2723  usec_to_fps(stream->cx_time, seen_frames));
2724  );
2725 
2726  if (global.show_psnr)
2727  FOREACH_STREAM(show_psnr(stream));
2728 
2729  FOREACH_STREAM(vpx_codec_destroy(&stream->encoder));
2730 
2731  if (global.test_decode != TEST_DECODE_OFF) {
2732  FOREACH_STREAM(vpx_codec_destroy(&stream->decoder));
2733  }
2734 
2735  close_input_file(&input);
2736 
2737  if (global.test_decode == TEST_DECODE_FATAL) {
2738  FOREACH_STREAM(res |= stream->mismatch_seen);
2739  }
2740  FOREACH_STREAM(close_output_file(stream, global.codec->fourcc));
2741 
2742  FOREACH_STREAM(stats_close(&stream->stats, global.passes - 1));
2743 
2744  if (global.pass)
2745  break;
2746  }
2747 
2748  if (global.show_q_hist_buckets)
2749  FOREACH_STREAM(show_q_histogram(stream->counts,
2750  global.show_q_hist_buckets));
2751 
2752  if (global.show_rate_hist_buckets)
2753  FOREACH_STREAM(show_rate_histogram(&stream->rate_hist,
2754  &stream->config.cfg,
2755  global.show_rate_hist_buckets));
2756  FOREACH_STREAM(destroy_rate_histogram(&stream->rate_hist));
2757 
2758 #if CONFIG_INTERNAL_STATS
2759  /* TODO(jkoleszar): This doesn't belong in this executable. Do it for now,
2760  * to match some existing utilities.
2761  */
2762  FOREACH_STREAM({
2763  FILE *f = fopen("opsnr.stt", "a");
2764  if (stream->mismatch_seen) {
2765  fprintf(f, "First mismatch occurred in frame %d\n",
2766  stream->mismatch_seen);
2767  } else {
2768  fprintf(f, "No mismatch detected in recon buffers\n");
2769  }
2770  fclose(f);
2771  });
2772 #endif
2773 
2774  vpx_img_free(&raw);
2775  free(argv);
2776  free(streams);
2777  return res ? EXIT_FAILURE : EXIT_SUCCESS;
2778 }
Rational Number.
Definition: vpx_encoder.h:217
struct vpx_fixed_buf twopass_stats
Definition: vpx_encoder.h:195
struct vpx_codec_iface vpx_codec_iface_t
Codec interface structure.
Definition: vpx_codec.h:174
control function to set vp8 encoder cpuused
Definition: vp8cx.h:149
Image Descriptor.
Definition: vpx_image.h:97
Describes the decoder algorithm interface to applications.
Describes the encoder algorithm interface to applications.
const char * vpx_codec_iface_name(vpx_codec_iface_t *iface)
Return the name for a given interface.
Definition: vpx_image.h:55
const char * vpx_codec_err_to_string(vpx_codec_err_t err)
Convert error number to printable string.
struct vpx_rational g_timebase
Stream timebase units.
Definition: vpx_encoder.h:339
Definition: vpx_encoder.h:234
unsigned int rc_buf_sz
Decoder Buffer Size.
Definition: vpx_encoder.h:523
struct vpx_fixed_buf raw
Definition: vpx_encoder.h:201
int den
Definition: vpx_encoder.h:219
vpx_codec_err_t vpx_codec_encode(vpx_codec_ctx_t *ctx, const vpx_image_t *img, vpx_codec_pts_t pts, unsigned long duration, vpx_enc_frame_flags_t flags, unsigned long deadline)
Encode a frame.
Definition: vpx_encoder.h:165
Provides definitions for using the VP8 algorithm within the vpx Decoder interface.
Encoder configuration structure.
Definition: vpx_encoder.h:271
Definition: vp8cx.h:165
control function to set constrained quality level
Definition: vp8cx.h:172
Definition: vp8cx.h:164
Definition: vpx_encoder.h:166
#define VPX_PLANE_Y
Definition: vpx_image.h:114
Max data rate for Intra frames.
Definition: vp8cx.h:186
Encoder output packet.
Definition: vpx_encoder.h:176
void * buf
Definition: vpx_encoder.h:97
#define VPX_PLANE_V
Definition: vpx_image.h:116
Generic fixed size buffer structure.
Definition: vpx_encoder.h:96
Definition: vpx_encoder.h:226
Definition: vpx_encoder.h:227
struct vpx_codec_cx_pkt::@1::@2 frame
Definition: vp8.h:41
vpx_image_t * vpx_img_alloc(vpx_image_t *img, vpx_img_fmt_t fmt, unsigned int d_w, unsigned int d_h, unsigned int align)
Open a descriptor, allocating storage for the underlying image.
Definition: vpx_image.h:56
unsigned int d_w
Definition: vpx_image.h:105
#define vpx_codec_dec_init(ctx, iface, cfg, flags)
Convenience macro for vpx_codec_dec_init_ver()
Definition: vpx_decoder.h:155
unsigned int g_w
Width of the frame.
Definition: vpx_encoder.h:314
vpx_codec_err_t vpx_codec_decode(vpx_codec_ctx_t *ctx, const uint8_t *data, unsigned int data_sz, void *user_priv, long deadline)
Decode data.
unsigned int g_h
Height of the frame.
Definition: vpx_encoder.h:324
int stride[4]
Definition: vpx_image.h:126
enum vpx_codec_cx_pkt_kind kind
Definition: vpx_encoder.h:177
Definition: vp8cx.h:158
void vpx_img_free(vpx_image_t *img)
Close an image descriptor.
#define VPX_CODEC_USE_OUTPUT_PARTITION
Definition: vpx_encoder.h:87
vpx_img_fmt_t fmt
Definition: vpx_image.h:98
unsigned char * planes[4]
Definition: vpx_image.h:125
Definition: vp8cx.h:154
unsigned int rc_target_bitrate
Target data rate.
Definition: vpx_encoder.h:448
#define VPX_DL_REALTIME
Definition: vpx_encoder.h:792
int num
Definition: vpx_encoder.h:218
Definition: vp8cx.h:151
#define VPX_DL_BEST_QUALITY
Definition: vpx_encoder.h:798
vpx_codec_err_t vpx_codec_enc_config_default(vpx_codec_iface_t *iface, vpx_codec_enc_cfg_t *cfg, unsigned int usage)
Get a default configuration.
Definition: vpx_encoder.h:233
enum vpx_enc_pass g_pass
Multi-pass Encoding Mode.
Definition: vpx_encoder.h:356
double psnr[4]
Definition: vpx_encoder.h:199
#define VPX_CODEC_USE_PSNR
Initialization-time Feature Enabling.
Definition: vpx_encoder.h:86
#define VPX_DL_GOOD_QUALITY
Definition: vpx_encoder.h:795
const char * vpx_codec_error_detail(vpx_codec_ctx_t *ctx)
Retrieve detailed error information for codec context.
const char * vpx_codec_version_str(void)
Return the version information (as a string)
Provides definitions for using the VP8 encoder algorithm within the vpx Codec Interface.
#define VPX_PLANE_U
Definition: vpx_image.h:115
#define vpx_codec_enc_init(ctx, iface, cfg, flags)
Convenience macro for vpx_codec_enc_init_ver()
Definition: vpx_encoder.h:690
unsigned int h
Definition: vpx_image.h:102
vpx_codec_err_t
Algorithm return codes.
Definition: vpx_codec.h:88
const vpx_codec_cx_pkt_t * vpx_codec_get_cx_data(vpx_codec_ctx_t *ctx, vpx_codec_iter_t *iter)
Encoded data iterator.
union vpx_codec_cx_pkt::@1 data
Definition: vp8cx.h:162
Definition: vp8.h:106
Definition: vpx_encoder.h:250
Definition: vp8cx.h:163
int64_t vpx_codec_pts_t
Time Stamp Type.
Definition: vpx_encoder.h:107
Definition: vp8cx.h:150
vpx_codec_err_t vpx_codec_control_(vpx_codec_ctx_t *ctx, int ctrl_id,...)
Control algorithm.
reference frame data struct
Definition: vp8.h:101
Definition: vpx_encoder.h:235
int idx
Definition: vp8.h:107
#define vpx_codec_control(ctx, id, data)
vpx_codec_control wrapper macro
Definition: vpx_codec.h:397
vpx_codec_err_t vpx_codec_destroy(vpx_codec_ctx_t *ctx)
Destroy a codec instance.
unsigned int d_h
Definition: vpx_image.h:106
size_t sz
Definition: vpx_encoder.h:98
unsigned int w
Definition: vpx_image.h:101
vpx_codec_err_t err
Definition: vpx_codec.h:203
Definition: vp8.h:52
Definition: vp8cx.h:153
const char * vpx_codec_error(vpx_codec_ctx_t *ctx)
Retrieve error synopsis for codec context.
#define VPX_FRAME_IS_KEY
Definition: vpx_encoder.h:118
const void * vpx_codec_iter_t
Iterator.
Definition: vpx_codec.h:189
Definition: vp8cx.h:152
Definition: vpx_encoder.h:164
#define VPX_FRAME_IS_FRAGMENT
Definition: vpx_encoder.h:127
#define VPX_FRAME_IS_INVISIBLE
Definition: vpx_encoder.h:124
Definition: vpx_encoder.h:225
Codec context structure.
Definition: vpx_codec.h:200