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 
12 /* This is a simple program that encodes YV12 files and generates ivf
13  * files using the new interface.
14  */
15 #if defined(_WIN32) || !CONFIG_OS_SUPPORT
16 #define USE_POSIX_MMAP 0
17 #else
18 #define USE_POSIX_MMAP 1
19 #endif
20 
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <stdarg.h>
24 #include <string.h>
25 #include <limits.h>
26 #include <assert.h>
27 #include "vpx/vpx_encoder.h"
28 #if USE_POSIX_MMAP
29 #include <sys/types.h>
30 #include <sys/stat.h>
31 #include <sys/mman.h>
32 #include <fcntl.h>
33 #include <unistd.h>
34 #endif
35 #include "vpx/vp8cx.h"
36 #include "vpx_ports/mem_ops.h"
37 #include "vpx_ports/vpx_timer.h"
38 #include "tools_common.h"
39 #include "y4minput.h"
40 #include "libmkv/EbmlWriter.h"
41 #include "libmkv/EbmlIDs.h"
42 
43 /* Need special handling of these functions on Windows */
44 #if defined(_MSC_VER)
45 /* MSVS doesn't define off_t, and uses _f{seek,tell}i64 */
46 typedef __int64 off_t;
47 #define fseeko _fseeki64
48 #define ftello _ftelli64
49 #elif defined(_WIN32)
50 /* MinGW defines off_t as long
51  and uses f{seek,tell}o64/off64_t for large files */
52 #define fseeko fseeko64
53 #define ftello ftello64
54 #define off_t off64_t
55 #endif
56 
57 #if defined(_MSC_VER)
58 #define LITERALU64(n) n
59 #else
60 #define LITERALU64(n) n##LLU
61 #endif
62 
63 /* We should use 32-bit file operations in WebM file format
64  * when building ARM executable file (.axf) with RVCT */
65 #if !CONFIG_OS_SUPPORT
66 typedef long off_t;
67 #define fseeko fseek
68 #define ftello ftell
69 #endif
70 
71 static const char *exec_name;
72 
73 static const struct codec_item
74 {
75  char const *name;
76  const vpx_codec_iface_t *iface;
77  unsigned int fourcc;
78 } codecs[] =
79 {
80 #if CONFIG_VP8_ENCODER
81  {"vp8", &vpx_codec_vp8_cx_algo, 0x30385056},
82 #endif
83 };
84 
85 static void usage_exit();
86 
87 void die(const char *fmt, ...)
88 {
89  va_list ap;
90  va_start(ap, fmt);
91  vfprintf(stderr, fmt, ap);
92  fprintf(stderr, "\n");
93  usage_exit();
94 }
95 
96 static void ctx_exit_on_error(vpx_codec_ctx_t *ctx, const char *s)
97 {
98  if (ctx->err)
99  {
100  const char *detail = vpx_codec_error_detail(ctx);
101 
102  fprintf(stderr, "%s: %s\n", s, vpx_codec_error(ctx));
103 
104  if (detail)
105  fprintf(stderr, " %s\n", detail);
106 
107  exit(EXIT_FAILURE);
108  }
109 }
110 
111 /* This structure is used to abstract the different ways of handling
112  * first pass statistics.
113  */
114 typedef struct
115 {
116  vpx_fixed_buf_t buf;
117  int pass;
118  FILE *file;
119  char *buf_ptr;
120  size_t buf_alloc_sz;
121 } stats_io_t;
122 
123 int stats_open_file(stats_io_t *stats, const char *fpf, int pass)
124 {
125  int res;
126 
127  stats->pass = pass;
128 
129  if (pass == 0)
130  {
131  stats->file = fopen(fpf, "wb");
132  stats->buf.sz = 0;
133  stats->buf.buf = NULL,
134  res = (stats->file != NULL);
135  }
136  else
137  {
138 #if 0
139 #elif USE_POSIX_MMAP
140  struct stat stat_buf;
141  int fd;
142 
143  fd = open(fpf, O_RDONLY);
144  stats->file = fdopen(fd, "rb");
145  fstat(fd, &stat_buf);
146  stats->buf.sz = stat_buf.st_size;
147  stats->buf.buf = mmap(NULL, stats->buf.sz, PROT_READ, MAP_PRIVATE,
148  fd, 0);
149  res = (stats->buf.buf != NULL);
150 #else
151  size_t nbytes;
152 
153  stats->file = fopen(fpf, "rb");
154 
155  if (fseek(stats->file, 0, SEEK_END))
156  {
157  fprintf(stderr, "First-pass stats file must be seekable!\n");
158  exit(EXIT_FAILURE);
159  }
160 
161  stats->buf.sz = stats->buf_alloc_sz = ftell(stats->file);
162  rewind(stats->file);
163 
164  stats->buf.buf = malloc(stats->buf_alloc_sz);
165 
166  if (!stats->buf.buf)
167  {
168  fprintf(stderr, "Failed to allocate first-pass stats buffer (%lu bytes)\n",
169  (unsigned long)stats->buf_alloc_sz);
170  exit(EXIT_FAILURE);
171  }
172 
173  nbytes = fread(stats->buf.buf, 1, stats->buf.sz, stats->file);
174  res = (nbytes == stats->buf.sz);
175 #endif
176  }
177 
178  return res;
179 }
180 
181 int stats_open_mem(stats_io_t *stats, int pass)
182 {
183  int res;
184  stats->pass = pass;
185 
186  if (!pass)
187  {
188  stats->buf.sz = 0;
189  stats->buf_alloc_sz = 64 * 1024;
190  stats->buf.buf = malloc(stats->buf_alloc_sz);
191  }
192 
193  stats->buf_ptr = stats->buf.buf;
194  res = (stats->buf.buf != NULL);
195  return res;
196 }
197 
198 
199 void stats_close(stats_io_t *stats, int last_pass)
200 {
201  if (stats->file)
202  {
203  if (stats->pass == last_pass)
204  {
205 #if 0
206 #elif USE_POSIX_MMAP
207  munmap(stats->buf.buf, stats->buf.sz);
208 #else
209  free(stats->buf.buf);
210 #endif
211  }
212 
213  fclose(stats->file);
214  stats->file = NULL;
215  }
216  else
217  {
218  if (stats->pass == last_pass)
219  free(stats->buf.buf);
220  }
221 }
222 
223 void stats_write(stats_io_t *stats, const void *pkt, size_t len)
224 {
225  if (stats->file)
226  {
227  if(fwrite(pkt, 1, len, stats->file));
228  }
229  else
230  {
231  if (stats->buf.sz + len > stats->buf_alloc_sz)
232  {
233  size_t new_sz = stats->buf_alloc_sz + 64 * 1024;
234  char *new_ptr = realloc(stats->buf.buf, new_sz);
235 
236  if (new_ptr)
237  {
238  stats->buf_ptr = new_ptr + (stats->buf_ptr - (char *)stats->buf.buf);
239  stats->buf.buf = new_ptr;
240  stats->buf_alloc_sz = new_sz;
241  }
242  else
243  {
244  fprintf(stderr,
245  "\nFailed to realloc firstpass stats buffer.\n");
246  exit(EXIT_FAILURE);
247  }
248  }
249 
250  memcpy(stats->buf_ptr, pkt, len);
251  stats->buf.sz += len;
252  stats->buf_ptr += len;
253  }
254 }
255 
256 vpx_fixed_buf_t stats_get(stats_io_t *stats)
257 {
258  return stats->buf;
259 }
260 
261 /* Stereo 3D packed frame format */
262 typedef enum stereo_format
263 {
264  STEREO_FORMAT_MONO = 0,
265  STEREO_FORMAT_LEFT_RIGHT = 1,
266  STEREO_FORMAT_BOTTOM_TOP = 2,
267  STEREO_FORMAT_TOP_BOTTOM = 3,
268  STEREO_FORMAT_RIGHT_LEFT = 11
269 } stereo_format_t;
270 
271 enum video_file_type
272 {
273  FILE_TYPE_RAW,
274  FILE_TYPE_IVF,
275  FILE_TYPE_Y4M
276 };
277 
278 struct detect_buffer {
279  char buf[4];
280  size_t buf_read;
281  size_t position;
282 };
283 
284 
285 #define IVF_FRAME_HDR_SZ (4+8) /* 4 byte size + 8 byte timestamp */
286 static int read_frame(FILE *f, vpx_image_t *img, unsigned int file_type,
287  y4m_input *y4m, struct detect_buffer *detect)
288 {
289  int plane = 0;
290  int shortread = 0;
291 
292  if (file_type == FILE_TYPE_Y4M)
293  {
294  if (y4m_input_fetch_frame(y4m, f, img) < 1)
295  return 0;
296  }
297  else
298  {
299  if (file_type == FILE_TYPE_IVF)
300  {
301  char junk[IVF_FRAME_HDR_SZ];
302 
303  /* Skip the frame header. We know how big the frame should be. See
304  * write_ivf_frame_header() for documentation on the frame header
305  * layout.
306  */
307  if(fread(junk, 1, IVF_FRAME_HDR_SZ, f));
308  }
309 
310  for (plane = 0; plane < 3; plane++)
311  {
312  unsigned char *ptr;
313  int w = (plane ? (1 + img->d_w) / 2 : img->d_w);
314  int h = (plane ? (1 + img->d_h) / 2 : img->d_h);
315  int r;
316 
317  /* Determine the correct plane based on the image format. The for-loop
318  * always counts in Y,U,V order, but this may not match the order of
319  * the data on disk.
320  */
321  switch (plane)
322  {
323  case 1:
324  ptr = img->planes[img->fmt==VPX_IMG_FMT_YV12? VPX_PLANE_V : VPX_PLANE_U];
325  break;
326  case 2:
327  ptr = img->planes[img->fmt==VPX_IMG_FMT_YV12?VPX_PLANE_U : VPX_PLANE_V];
328  break;
329  default:
330  ptr = img->planes[plane];
331  }
332 
333  for (r = 0; r < h; r++)
334  {
335  size_t needed = w;
336  size_t buf_position = 0;
337  const size_t left = detect->buf_read - detect->position;
338  if (left > 0)
339  {
340  const size_t more = (left < needed) ? left : needed;
341  memcpy(ptr, detect->buf + detect->position, more);
342  buf_position = more;
343  needed -= more;
344  detect->position += more;
345  }
346  if (needed > 0)
347  {
348  shortread |= (fread(ptr + buf_position, 1, needed, f) < needed);
349  }
350 
351  ptr += img->stride[plane];
352  }
353  }
354  }
355 
356  return !shortread;
357 }
358 
359 
360 unsigned int file_is_y4m(FILE *infile,
361  y4m_input *y4m,
362  char detect[4])
363 {
364  if(memcmp(detect, "YUV4", 4) == 0)
365  {
366  return 1;
367  }
368  return 0;
369 }
370 
371 #define IVF_FILE_HDR_SZ (32)
372 unsigned int file_is_ivf(FILE *infile,
373  unsigned int *fourcc,
374  unsigned int *width,
375  unsigned int *height,
376  struct detect_buffer *detect)
377 {
378  char raw_hdr[IVF_FILE_HDR_SZ];
379  int is_ivf = 0;
380 
381  if(memcmp(detect->buf, "DKIF", 4) != 0)
382  return 0;
383 
384  /* See write_ivf_file_header() for more documentation on the file header
385  * layout.
386  */
387  if (fread(raw_hdr + 4, 1, IVF_FILE_HDR_SZ - 4, infile)
388  == IVF_FILE_HDR_SZ - 4)
389  {
390  {
391  is_ivf = 1;
392 
393  if (mem_get_le16(raw_hdr + 4) != 0)
394  fprintf(stderr, "Error: Unrecognized IVF version! This file may not"
395  " decode properly.");
396 
397  *fourcc = mem_get_le32(raw_hdr + 8);
398  }
399  }
400 
401  if (is_ivf)
402  {
403  *width = mem_get_le16(raw_hdr + 12);
404  *height = mem_get_le16(raw_hdr + 14);
405  detect->position = 4;
406  }
407 
408  return is_ivf;
409 }
410 
411 
412 static void write_ivf_file_header(FILE *outfile,
413  const vpx_codec_enc_cfg_t *cfg,
414  unsigned int fourcc,
415  int frame_cnt)
416 {
417  char header[32];
418 
419  if (cfg->g_pass != VPX_RC_ONE_PASS && cfg->g_pass != VPX_RC_LAST_PASS)
420  return;
421 
422  header[0] = 'D';
423  header[1] = 'K';
424  header[2] = 'I';
425  header[3] = 'F';
426  mem_put_le16(header + 4, 0); /* version */
427  mem_put_le16(header + 6, 32); /* headersize */
428  mem_put_le32(header + 8, fourcc); /* headersize */
429  mem_put_le16(header + 12, cfg->g_w); /* width */
430  mem_put_le16(header + 14, cfg->g_h); /* height */
431  mem_put_le32(header + 16, cfg->g_timebase.den); /* rate */
432  mem_put_le32(header + 20, cfg->g_timebase.num); /* scale */
433  mem_put_le32(header + 24, frame_cnt); /* length */
434  mem_put_le32(header + 28, 0); /* unused */
435 
436  if(fwrite(header, 1, 32, outfile));
437 }
438 
439 
440 static void write_ivf_frame_header(FILE *outfile,
441  const vpx_codec_cx_pkt_t *pkt)
442 {
443  char header[12];
444  vpx_codec_pts_t pts;
445 
446  if (pkt->kind != VPX_CODEC_CX_FRAME_PKT)
447  return;
448 
449  pts = pkt->data.frame.pts;
450  mem_put_le32(header, pkt->data.frame.sz);
451  mem_put_le32(header + 4, pts & 0xFFFFFFFF);
452  mem_put_le32(header + 8, pts >> 32);
453 
454  if(fwrite(header, 1, 12, outfile));
455 }
456 
457 
458 typedef off_t EbmlLoc;
459 
460 
461 struct cue_entry
462 {
463  unsigned int time;
464  uint64_t loc;
465 };
466 
467 
468 struct EbmlGlobal
469 {
470  int debug;
471 
472  FILE *stream;
473  int64_t last_pts_ms;
474  vpx_rational_t framerate;
475 
476  /* These pointers are to the start of an element */
477  off_t position_reference;
478  off_t seek_info_pos;
479  off_t segment_info_pos;
480  off_t track_pos;
481  off_t cue_pos;
482  off_t cluster_pos;
483 
484  /* This pointer is to a specific element to be serialized */
485  off_t track_id_pos;
486 
487  /* These pointers are to the size field of the element */
488  EbmlLoc startSegment;
489  EbmlLoc startCluster;
490 
491  uint32_t cluster_timecode;
492  int cluster_open;
493 
494  struct cue_entry *cue_list;
495  unsigned int cues;
496 
497 };
498 
499 
500 void Ebml_Write(EbmlGlobal *glob, const void *buffer_in, unsigned long len)
501 {
502  if(fwrite(buffer_in, 1, len, glob->stream));
503 }
504 
505 #define WRITE_BUFFER(s) \
506 for(i = len-1; i>=0; i--)\
507 { \
508  x = *(const s *)buffer_in >> (i * CHAR_BIT); \
509  Ebml_Write(glob, &x, 1); \
510 }
511 void Ebml_Serialize(EbmlGlobal *glob, const void *buffer_in, int buffer_size, unsigned long len)
512 {
513  char x;
514  int i;
515 
516  /* buffer_size:
517  * 1 - int8_t;
518  * 2 - int16_t;
519  * 3 - int32_t;
520  * 4 - int64_t;
521  */
522  switch (buffer_size)
523  {
524  case 1:
525  WRITE_BUFFER(int8_t)
526  break;
527  case 2:
528  WRITE_BUFFER(int16_t)
529  break;
530  case 4:
531  WRITE_BUFFER(int32_t)
532  break;
533  case 8:
534  WRITE_BUFFER(int64_t)
535  break;
536  default:
537  break;
538  }
539 }
540 #undef WRITE_BUFFER
541 
542 /* Need a fixed size serializer for the track ID. libmkv provides a 64 bit
543  * one, but not a 32 bit one.
544  */
545 static void Ebml_SerializeUnsigned32(EbmlGlobal *glob, unsigned long class_id, uint64_t ui)
546 {
547  unsigned char sizeSerialized = 4 | 0x80;
548  Ebml_WriteID(glob, class_id);
549  Ebml_Serialize(glob, &sizeSerialized, sizeof(sizeSerialized), 1);
550  Ebml_Serialize(glob, &ui, sizeof(ui), 4);
551 }
552 
553 
554 static void
555 Ebml_StartSubElement(EbmlGlobal *glob, EbmlLoc *ebmlLoc,
556  unsigned long class_id)
557 {
558  //todo this is always taking 8 bytes, this may need later optimization
559  //this is a key that says length unknown
560  uint64_t unknownLen = LITERALU64(0x01FFFFFFFFFFFFFF);
561 
562  Ebml_WriteID(glob, class_id);
563  *ebmlLoc = ftello(glob->stream);
564  Ebml_Serialize(glob, &unknownLen, sizeof(unknownLen), 8);
565 }
566 
567 static void
568 Ebml_EndSubElement(EbmlGlobal *glob, EbmlLoc *ebmlLoc)
569 {
570  off_t pos;
571  uint64_t size;
572 
573  /* Save the current stream pointer */
574  pos = ftello(glob->stream);
575 
576  /* Calculate the size of this element */
577  size = pos - *ebmlLoc - 8;
578  size |= LITERALU64(0x0100000000000000);
579 
580  /* Seek back to the beginning of the element and write the new size */
581  fseeko(glob->stream, *ebmlLoc, SEEK_SET);
582  Ebml_Serialize(glob, &size, sizeof(size), 8);
583 
584  /* Reset the stream pointer */
585  fseeko(glob->stream, pos, SEEK_SET);
586 }
587 
588 
589 static void
590 write_webm_seek_element(EbmlGlobal *ebml, unsigned long id, off_t pos)
591 {
592  uint64_t offset = pos - ebml->position_reference;
593  EbmlLoc start;
594  Ebml_StartSubElement(ebml, &start, Seek);
595  Ebml_SerializeBinary(ebml, SeekID, id);
596  Ebml_SerializeUnsigned64(ebml, SeekPosition, offset);
597  Ebml_EndSubElement(ebml, &start);
598 }
599 
600 
601 static void
602 write_webm_seek_info(EbmlGlobal *ebml)
603 {
604 
605  off_t pos;
606 
607  /* Save the current stream pointer */
608  pos = ftello(ebml->stream);
609 
610  if(ebml->seek_info_pos)
611  fseeko(ebml->stream, ebml->seek_info_pos, SEEK_SET);
612  else
613  ebml->seek_info_pos = pos;
614 
615  {
616  EbmlLoc start;
617 
618  Ebml_StartSubElement(ebml, &start, SeekHead);
619  write_webm_seek_element(ebml, Tracks, ebml->track_pos);
620  write_webm_seek_element(ebml, Cues, ebml->cue_pos);
621  write_webm_seek_element(ebml, Info, ebml->segment_info_pos);
622  Ebml_EndSubElement(ebml, &start);
623  }
624  {
625  //segment info
626  EbmlLoc startInfo;
627  uint64_t frame_time;
628  char version_string[64];
629 
630  /* Assemble version string */
631  if(ebml->debug)
632  strcpy(version_string, "vpxenc");
633  else
634  {
635  strcpy(version_string, "vpxenc ");
636  strncat(version_string,
638  sizeof(version_string) - 1 - strlen(version_string));
639  }
640 
641  frame_time = (uint64_t)1000 * ebml->framerate.den
642  / ebml->framerate.num;
643  ebml->segment_info_pos = ftello(ebml->stream);
644  Ebml_StartSubElement(ebml, &startInfo, Info);
645  Ebml_SerializeUnsigned(ebml, TimecodeScale, 1000000);
646  Ebml_SerializeFloat(ebml, Segment_Duration,
647  ebml->last_pts_ms + frame_time);
648  Ebml_SerializeString(ebml, 0x4D80, version_string);
649  Ebml_SerializeString(ebml, 0x5741, version_string);
650  Ebml_EndSubElement(ebml, &startInfo);
651  }
652 }
653 
654 
655 static void
656 write_webm_file_header(EbmlGlobal *glob,
657  const vpx_codec_enc_cfg_t *cfg,
658  const struct vpx_rational *fps,
659  stereo_format_t stereo_fmt)
660 {
661  {
662  EbmlLoc start;
663  Ebml_StartSubElement(glob, &start, EBML);
664  Ebml_SerializeUnsigned(glob, EBMLVersion, 1);
665  Ebml_SerializeUnsigned(glob, EBMLReadVersion, 1); //EBML Read Version
666  Ebml_SerializeUnsigned(glob, EBMLMaxIDLength, 4); //EBML Max ID Length
667  Ebml_SerializeUnsigned(glob, EBMLMaxSizeLength, 8); //EBML Max Size Length
668  Ebml_SerializeString(glob, DocType, "webm"); //Doc Type
669  Ebml_SerializeUnsigned(glob, DocTypeVersion, 2); //Doc Type Version
670  Ebml_SerializeUnsigned(glob, DocTypeReadVersion, 2); //Doc Type Read Version
671  Ebml_EndSubElement(glob, &start);
672  }
673  {
674  Ebml_StartSubElement(glob, &glob->startSegment, Segment); //segment
675  glob->position_reference = ftello(glob->stream);
676  glob->framerate = *fps;
677  write_webm_seek_info(glob);
678 
679  {
680  EbmlLoc trackStart;
681  glob->track_pos = ftello(glob->stream);
682  Ebml_StartSubElement(glob, &trackStart, Tracks);
683  {
684  unsigned int trackNumber = 1;
685  uint64_t trackID = 0;
686 
687  EbmlLoc start;
688  Ebml_StartSubElement(glob, &start, TrackEntry);
689  Ebml_SerializeUnsigned(glob, TrackNumber, trackNumber);
690  glob->track_id_pos = ftello(glob->stream);
691  Ebml_SerializeUnsigned32(glob, TrackUID, trackID);
692  Ebml_SerializeUnsigned(glob, TrackType, 1); //video is always 1
693  Ebml_SerializeString(glob, CodecID, "V_VP8");
694  {
695  unsigned int pixelWidth = cfg->g_w;
696  unsigned int pixelHeight = cfg->g_h;
697  float frameRate = (float)fps->num/(float)fps->den;
698 
699  EbmlLoc videoStart;
700  Ebml_StartSubElement(glob, &videoStart, Video);
701  Ebml_SerializeUnsigned(glob, PixelWidth, pixelWidth);
702  Ebml_SerializeUnsigned(glob, PixelHeight, pixelHeight);
703  Ebml_SerializeUnsigned(glob, StereoMode, stereo_fmt);
704  Ebml_SerializeFloat(glob, FrameRate, frameRate);
705  Ebml_EndSubElement(glob, &videoStart); //Video
706  }
707  Ebml_EndSubElement(glob, &start); //Track Entry
708  }
709  Ebml_EndSubElement(glob, &trackStart);
710  }
711  // segment element is open
712  }
713 }
714 
715 
716 static void
717 write_webm_block(EbmlGlobal *glob,
718  const vpx_codec_enc_cfg_t *cfg,
719  const vpx_codec_cx_pkt_t *pkt)
720 {
721  unsigned long block_length;
722  unsigned char track_number;
723  unsigned short block_timecode = 0;
724  unsigned char flags;
725  int64_t pts_ms;
726  int start_cluster = 0, is_keyframe;
727 
728  /* Calculate the PTS of this frame in milliseconds */
729  pts_ms = pkt->data.frame.pts * 1000
730  * (uint64_t)cfg->g_timebase.num / (uint64_t)cfg->g_timebase.den;
731  if(pts_ms <= glob->last_pts_ms)
732  pts_ms = glob->last_pts_ms + 1;
733  glob->last_pts_ms = pts_ms;
734 
735  /* Calculate the relative time of this block */
736  if(pts_ms - glob->cluster_timecode > SHRT_MAX)
737  start_cluster = 1;
738  else
739  block_timecode = pts_ms - glob->cluster_timecode;
740 
741  is_keyframe = (pkt->data.frame.flags & VPX_FRAME_IS_KEY);
742  if(start_cluster || is_keyframe)
743  {
744  if(glob->cluster_open)
745  Ebml_EndSubElement(glob, &glob->startCluster);
746 
747  /* Open the new cluster */
748  block_timecode = 0;
749  glob->cluster_open = 1;
750  glob->cluster_timecode = pts_ms;
751  glob->cluster_pos = ftello(glob->stream);
752  Ebml_StartSubElement(glob, &glob->startCluster, Cluster); //cluster
753  Ebml_SerializeUnsigned(glob, Timecode, glob->cluster_timecode);
754 
755  /* Save a cue point if this is a keyframe. */
756  if(is_keyframe)
757  {
758  struct cue_entry *cue, *new_cue_list;
759 
760  new_cue_list = realloc(glob->cue_list,
761  (glob->cues+1) * sizeof(struct cue_entry));
762  if(new_cue_list)
763  glob->cue_list = new_cue_list;
764  else
765  {
766  fprintf(stderr, "\nFailed to realloc cue list.\n");
767  exit(EXIT_FAILURE);
768  }
769 
770  cue = &glob->cue_list[glob->cues];
771  cue->time = glob->cluster_timecode;
772  cue->loc = glob->cluster_pos;
773  glob->cues++;
774  }
775  }
776 
777  /* Write the Simple Block */
778  Ebml_WriteID(glob, SimpleBlock);
779 
780  block_length = pkt->data.frame.sz + 4;
781  block_length |= 0x10000000;
782  Ebml_Serialize(glob, &block_length, sizeof(block_length), 4);
783 
784  track_number = 1;
785  track_number |= 0x80;
786  Ebml_Write(glob, &track_number, 1);
787 
788  Ebml_Serialize(glob, &block_timecode, sizeof(block_timecode), 2);
789 
790  flags = 0;
791  if(is_keyframe)
792  flags |= 0x80;
793  if(pkt->data.frame.flags & VPX_FRAME_IS_INVISIBLE)
794  flags |= 0x08;
795  Ebml_Write(glob, &flags, 1);
796 
797  Ebml_Write(glob, pkt->data.frame.buf, pkt->data.frame.sz);
798 }
799 
800 
801 static void
802 write_webm_file_footer(EbmlGlobal *glob, long hash)
803 {
804 
805  if(glob->cluster_open)
806  Ebml_EndSubElement(glob, &glob->startCluster);
807 
808  {
809  EbmlLoc start;
810  unsigned int i;
811 
812  glob->cue_pos = ftello(glob->stream);
813  Ebml_StartSubElement(glob, &start, Cues);
814  for(i=0; i<glob->cues; i++)
815  {
816  struct cue_entry *cue = &glob->cue_list[i];
817  EbmlLoc start;
818 
819  Ebml_StartSubElement(glob, &start, CuePoint);
820  {
821  EbmlLoc start;
822 
823  Ebml_SerializeUnsigned(glob, CueTime, cue->time);
824 
825  Ebml_StartSubElement(glob, &start, CueTrackPositions);
826  Ebml_SerializeUnsigned(glob, CueTrack, 1);
827  Ebml_SerializeUnsigned64(glob, CueClusterPosition,
828  cue->loc - glob->position_reference);
829  //Ebml_SerializeUnsigned(glob, CueBlockNumber, cue->blockNumber);
830  Ebml_EndSubElement(glob, &start);
831  }
832  Ebml_EndSubElement(glob, &start);
833  }
834  Ebml_EndSubElement(glob, &start);
835  }
836 
837  Ebml_EndSubElement(glob, &glob->startSegment);
838 
839  /* Patch up the seek info block */
840  write_webm_seek_info(glob);
841 
842  /* Patch up the track id */
843  fseeko(glob->stream, glob->track_id_pos, SEEK_SET);
844  Ebml_SerializeUnsigned32(glob, TrackUID, glob->debug ? 0xDEADBEEF : hash);
845 
846  fseeko(glob->stream, 0, SEEK_END);
847 }
848 
849 
850 /* Murmur hash derived from public domain reference implementation at
851  * http://sites.google.com/site/murmurhash/
852  */
853 static unsigned int murmur ( const void * key, int len, unsigned int seed )
854 {
855  const unsigned int m = 0x5bd1e995;
856  const int r = 24;
857 
858  unsigned int h = seed ^ len;
859 
860  const unsigned char * data = (const unsigned char *)key;
861 
862  while(len >= 4)
863  {
864  unsigned int k;
865 
866  k = data[0];
867  k |= data[1] << 8;
868  k |= data[2] << 16;
869  k |= data[3] << 24;
870 
871  k *= m;
872  k ^= k >> r;
873  k *= m;
874 
875  h *= m;
876  h ^= k;
877 
878  data += 4;
879  len -= 4;
880  }
881 
882  switch(len)
883  {
884  case 3: h ^= data[2] << 16;
885  case 2: h ^= data[1] << 8;
886  case 1: h ^= data[0];
887  h *= m;
888  };
889 
890  h ^= h >> 13;
891  h *= m;
892  h ^= h >> 15;
893 
894  return h;
895 }
896 
897 #include "math.h"
898 
899 static double vp8_mse2psnr(double Samples, double Peak, double Mse)
900 {
901  double psnr;
902 
903  if ((double)Mse > 0.0)
904  psnr = 10.0 * log10(Peak * Peak * Samples / Mse);
905  else
906  psnr = 60; // Limit to prevent / 0
907 
908  if (psnr > 60)
909  psnr = 60;
910 
911  return psnr;
912 }
913 
914 
915 #include "args.h"
916 
917 static const arg_def_t debugmode = ARG_DEF("D", "debug", 0,
918  "Debug mode (makes output deterministic)");
919 static const arg_def_t outputfile = ARG_DEF("o", "output", 1,
920  "Output filename");
921 static const arg_def_t use_yv12 = ARG_DEF(NULL, "yv12", 0,
922  "Input file is YV12 ");
923 static const arg_def_t use_i420 = ARG_DEF(NULL, "i420", 0,
924  "Input file is I420 (default)");
925 static const arg_def_t codecarg = ARG_DEF(NULL, "codec", 1,
926  "Codec to use");
927 static const arg_def_t passes = ARG_DEF("p", "passes", 1,
928  "Number of passes (1/2)");
929 static const arg_def_t pass_arg = ARG_DEF(NULL, "pass", 1,
930  "Pass to execute (1/2)");
931 static const arg_def_t fpf_name = ARG_DEF(NULL, "fpf", 1,
932  "First pass statistics file name");
933 static const arg_def_t limit = ARG_DEF(NULL, "limit", 1,
934  "Stop encoding after n input frames");
935 static const arg_def_t deadline = ARG_DEF("d", "deadline", 1,
936  "Deadline per frame (usec)");
937 static const arg_def_t best_dl = ARG_DEF(NULL, "best", 0,
938  "Use Best Quality Deadline");
939 static const arg_def_t good_dl = ARG_DEF(NULL, "good", 0,
940  "Use Good Quality Deadline");
941 static const arg_def_t rt_dl = ARG_DEF(NULL, "rt", 0,
942  "Use Realtime Quality Deadline");
943 static const arg_def_t verbosearg = ARG_DEF("v", "verbose", 0,
944  "Show encoder parameters");
945 static const arg_def_t psnrarg = ARG_DEF(NULL, "psnr", 0,
946  "Show PSNR in status line");
947 static const arg_def_t framerate = ARG_DEF(NULL, "fps", 1,
948  "Stream frame rate (rate/scale)");
949 static const arg_def_t use_ivf = ARG_DEF(NULL, "ivf", 0,
950  "Output IVF (default is WebM)");
951 static const arg_def_t q_hist_n = ARG_DEF(NULL, "q-hist", 1,
952  "Show quantizer histogram (n-buckets)");
953 static const arg_def_t rate_hist_n = ARG_DEF(NULL, "rate-hist", 1,
954  "Show rate histogram (n-buckets)");
955 static const arg_def_t *main_args[] =
956 {
957  &debugmode,
958  &outputfile, &codecarg, &passes, &pass_arg, &fpf_name, &limit, &deadline,
959  &best_dl, &good_dl, &rt_dl,
960  &verbosearg, &psnrarg, &use_ivf, &q_hist_n, &rate_hist_n,
961  NULL
962 };
963 
964 static const arg_def_t usage = ARG_DEF("u", "usage", 1,
965  "Usage profile number to use");
966 static const arg_def_t threads = ARG_DEF("t", "threads", 1,
967  "Max number of threads to use");
968 static const arg_def_t profile = ARG_DEF(NULL, "profile", 1,
969  "Bitstream profile number to use");
970 static const arg_def_t width = ARG_DEF("w", "width", 1,
971  "Frame width");
972 static const arg_def_t height = ARG_DEF("h", "height", 1,
973  "Frame height");
974 static const struct arg_enum_list stereo_mode_enum[] = {
975  {"mono" , STEREO_FORMAT_MONO},
976  {"left-right", STEREO_FORMAT_LEFT_RIGHT},
977  {"bottom-top", STEREO_FORMAT_BOTTOM_TOP},
978  {"top-bottom", STEREO_FORMAT_TOP_BOTTOM},
979  {"right-left", STEREO_FORMAT_RIGHT_LEFT},
980  {NULL, 0}
981 };
982 static const arg_def_t stereo_mode = ARG_DEF_ENUM(NULL, "stereo-mode", 1,
983  "Stereo 3D video format", stereo_mode_enum);
984 static const arg_def_t timebase = ARG_DEF(NULL, "timebase", 1,
985  "Output timestamp precision (fractional seconds)");
986 static const arg_def_t error_resilient = ARG_DEF(NULL, "error-resilient", 1,
987  "Enable error resiliency features");
988 static const arg_def_t lag_in_frames = ARG_DEF(NULL, "lag-in-frames", 1,
989  "Max number of frames to lag");
990 
991 static const arg_def_t *global_args[] =
992 {
993  &use_yv12, &use_i420, &usage, &threads, &profile,
994  &width, &height, &stereo_mode, &timebase, &framerate, &error_resilient,
995  &lag_in_frames, NULL
996 };
997 
998 static const arg_def_t dropframe_thresh = ARG_DEF(NULL, "drop-frame", 1,
999  "Temporal resampling threshold (buf %)");
1000 static const arg_def_t resize_allowed = ARG_DEF(NULL, "resize-allowed", 1,
1001  "Spatial resampling enabled (bool)");
1002 static const arg_def_t resize_up_thresh = ARG_DEF(NULL, "resize-up", 1,
1003  "Upscale threshold (buf %)");
1004 static const arg_def_t resize_down_thresh = ARG_DEF(NULL, "resize-down", 1,
1005  "Downscale threshold (buf %)");
1006 static const struct arg_enum_list end_usage_enum[] = {
1007  {"vbr", VPX_VBR},
1008  {"cbr", VPX_CBR},
1009  {"cq", VPX_CQ},
1010  {NULL, 0}
1011 };
1012 static const arg_def_t end_usage = ARG_DEF_ENUM(NULL, "end-usage", 1,
1013  "Rate control mode", end_usage_enum);
1014 static const arg_def_t target_bitrate = ARG_DEF(NULL, "target-bitrate", 1,
1015  "Bitrate (kbps)");
1016 static const arg_def_t min_quantizer = ARG_DEF(NULL, "min-q", 1,
1017  "Minimum (best) quantizer");
1018 static const arg_def_t max_quantizer = ARG_DEF(NULL, "max-q", 1,
1019  "Maximum (worst) quantizer");
1020 static const arg_def_t undershoot_pct = ARG_DEF(NULL, "undershoot-pct", 1,
1021  "Datarate undershoot (min) target (%)");
1022 static const arg_def_t overshoot_pct = ARG_DEF(NULL, "overshoot-pct", 1,
1023  "Datarate overshoot (max) target (%)");
1024 static const arg_def_t buf_sz = ARG_DEF(NULL, "buf-sz", 1,
1025  "Client buffer size (ms)");
1026 static const arg_def_t buf_initial_sz = ARG_DEF(NULL, "buf-initial-sz", 1,
1027  "Client initial buffer size (ms)");
1028 static const arg_def_t buf_optimal_sz = ARG_DEF(NULL, "buf-optimal-sz", 1,
1029  "Client optimal buffer size (ms)");
1030 static const arg_def_t *rc_args[] =
1031 {
1032  &dropframe_thresh, &resize_allowed, &resize_up_thresh, &resize_down_thresh,
1033  &end_usage, &target_bitrate, &min_quantizer, &max_quantizer,
1034  &undershoot_pct, &overshoot_pct, &buf_sz, &buf_initial_sz, &buf_optimal_sz,
1035  NULL
1036 };
1037 
1038 
1039 static const arg_def_t bias_pct = ARG_DEF(NULL, "bias-pct", 1,
1040  "CBR/VBR bias (0=CBR, 100=VBR)");
1041 static const arg_def_t minsection_pct = ARG_DEF(NULL, "minsection-pct", 1,
1042  "GOP min bitrate (% of target)");
1043 static const arg_def_t maxsection_pct = ARG_DEF(NULL, "maxsection-pct", 1,
1044  "GOP max bitrate (% of target)");
1045 static const arg_def_t *rc_twopass_args[] =
1046 {
1047  &bias_pct, &minsection_pct, &maxsection_pct, NULL
1048 };
1049 
1050 
1051 static const arg_def_t kf_min_dist = ARG_DEF(NULL, "kf-min-dist", 1,
1052  "Minimum keyframe interval (frames)");
1053 static const arg_def_t kf_max_dist = ARG_DEF(NULL, "kf-max-dist", 1,
1054  "Maximum keyframe interval (frames)");
1055 static const arg_def_t kf_disabled = ARG_DEF(NULL, "disable-kf", 0,
1056  "Disable keyframe placement");
1057 static const arg_def_t *kf_args[] =
1058 {
1059  &kf_min_dist, &kf_max_dist, &kf_disabled, NULL
1060 };
1061 
1062 
1063 #if CONFIG_VP8_ENCODER
1064 static const arg_def_t noise_sens = ARG_DEF(NULL, "noise-sensitivity", 1,
1065  "Noise sensitivity (frames to blur)");
1066 static const arg_def_t sharpness = ARG_DEF(NULL, "sharpness", 1,
1067  "Filter sharpness (0-7)");
1068 static const arg_def_t static_thresh = ARG_DEF(NULL, "static-thresh", 1,
1069  "Motion detection threshold");
1070 #endif
1071 
1072 #if CONFIG_VP8_ENCODER
1073 static const arg_def_t cpu_used = ARG_DEF(NULL, "cpu-used", 1,
1074  "CPU Used (-16..16)");
1075 #endif
1076 
1077 
1078 #if CONFIG_VP8_ENCODER
1079 static const arg_def_t token_parts = ARG_DEF(NULL, "token-parts", 1,
1080  "Number of token partitions to use, log2");
1081 static const arg_def_t auto_altref = ARG_DEF(NULL, "auto-alt-ref", 1,
1082  "Enable automatic alt reference frames");
1083 static const arg_def_t arnr_maxframes = ARG_DEF(NULL, "arnr-maxframes", 1,
1084  "AltRef Max Frames");
1085 static const arg_def_t arnr_strength = ARG_DEF(NULL, "arnr-strength", 1,
1086  "AltRef Strength");
1087 static const arg_def_t arnr_type = ARG_DEF(NULL, "arnr-type", 1,
1088  "AltRef Type");
1089 static const struct arg_enum_list tuning_enum[] = {
1090  {"psnr", VP8_TUNE_PSNR},
1091  {"ssim", VP8_TUNE_SSIM},
1092  {NULL, 0}
1093 };
1094 static const arg_def_t tune_ssim = ARG_DEF_ENUM(NULL, "tune", 1,
1095  "Material to favor", tuning_enum);
1096 static const arg_def_t cq_level = ARG_DEF(NULL, "cq-level", 1,
1097  "Constrained Quality Level");
1098 static const arg_def_t max_intra_rate_pct = ARG_DEF(NULL, "max-intra-rate", 1,
1099  "Max I-frame bitrate (pct)");
1100 
1101 static const arg_def_t *vp8_args[] =
1102 {
1103  &cpu_used, &auto_altref, &noise_sens, &sharpness, &static_thresh,
1104  &token_parts, &arnr_maxframes, &arnr_strength, &arnr_type,
1105  &tune_ssim, &cq_level, &max_intra_rate_pct, NULL
1106 };
1107 static const int vp8_arg_ctrl_map[] =
1108 {
1114 };
1115 #endif
1116 
1117 static const arg_def_t *no_args[] = { NULL };
1118 
1119 static void usage_exit()
1120 {
1121  int i;
1122 
1123  fprintf(stderr, "Usage: %s <options> -o dst_filename src_filename \n",
1124  exec_name);
1125 
1126  fprintf(stderr, "\nOptions:\n");
1127  arg_show_usage(stdout, main_args);
1128  fprintf(stderr, "\nEncoder Global Options:\n");
1129  arg_show_usage(stdout, global_args);
1130  fprintf(stderr, "\nRate Control Options:\n");
1131  arg_show_usage(stdout, rc_args);
1132  fprintf(stderr, "\nTwopass Rate Control Options:\n");
1133  arg_show_usage(stdout, rc_twopass_args);
1134  fprintf(stderr, "\nKeyframe Placement Options:\n");
1135  arg_show_usage(stdout, kf_args);
1136 #if CONFIG_VP8_ENCODER
1137  fprintf(stderr, "\nVP8 Specific Options:\n");
1138  arg_show_usage(stdout, vp8_args);
1139 #endif
1140  fprintf(stderr, "\nStream timebase (--timebase):\n"
1141  " The desired precision of timestamps in the output, expressed\n"
1142  " in fractional seconds. Default is 1/1000.\n");
1143  fprintf(stderr, "\n"
1144  "Included encoders:\n"
1145  "\n");
1146 
1147  for (i = 0; i < sizeof(codecs) / sizeof(codecs[0]); i++)
1148  fprintf(stderr, " %-6s - %s\n",
1149  codecs[i].name,
1150  vpx_codec_iface_name(codecs[i].iface));
1151 
1152  exit(EXIT_FAILURE);
1153 }
1154 
1155 
1156 #define HIST_BAR_MAX 40
1157 struct hist_bucket
1158 {
1159  int low, high, count;
1160 };
1161 
1162 
1163 static int merge_hist_buckets(struct hist_bucket *bucket,
1164  int *buckets_,
1165  int max_buckets)
1166 {
1167  int small_bucket = 0, merge_bucket = INT_MAX, big_bucket=0;
1168  int buckets = *buckets_;
1169  int i;
1170 
1171  /* Find the extrema for this list of buckets */
1172  big_bucket = small_bucket = 0;
1173  for(i=0; i < buckets; i++)
1174  {
1175  if(bucket[i].count < bucket[small_bucket].count)
1176  small_bucket = i;
1177  if(bucket[i].count > bucket[big_bucket].count)
1178  big_bucket = i;
1179  }
1180 
1181  /* If we have too many buckets, merge the smallest with an adjacent
1182  * bucket.
1183  */
1184  while(buckets > max_buckets)
1185  {
1186  int last_bucket = buckets - 1;
1187 
1188  // merge the small bucket with an adjacent one.
1189  if(small_bucket == 0)
1190  merge_bucket = 1;
1191  else if(small_bucket == last_bucket)
1192  merge_bucket = last_bucket - 1;
1193  else if(bucket[small_bucket - 1].count < bucket[small_bucket + 1].count)
1194  merge_bucket = small_bucket - 1;
1195  else
1196  merge_bucket = small_bucket + 1;
1197 
1198  assert(abs(merge_bucket - small_bucket) <= 1);
1199  assert(small_bucket < buckets);
1200  assert(big_bucket < buckets);
1201  assert(merge_bucket < buckets);
1202 
1203  if(merge_bucket < small_bucket)
1204  {
1205  bucket[merge_bucket].high = bucket[small_bucket].high;
1206  bucket[merge_bucket].count += bucket[small_bucket].count;
1207  }
1208  else
1209  {
1210  bucket[small_bucket].high = bucket[merge_bucket].high;
1211  bucket[small_bucket].count += bucket[merge_bucket].count;
1212  merge_bucket = small_bucket;
1213  }
1214 
1215  assert(bucket[merge_bucket].low != bucket[merge_bucket].high);
1216 
1217  buckets--;
1218 
1219  /* Remove the merge_bucket from the list, and find the new small
1220  * and big buckets while we're at it
1221  */
1222  big_bucket = small_bucket = 0;
1223  for(i=0; i < buckets; i++)
1224  {
1225  if(i > merge_bucket)
1226  bucket[i] = bucket[i+1];
1227 
1228  if(bucket[i].count < bucket[small_bucket].count)
1229  small_bucket = i;
1230  if(bucket[i].count > bucket[big_bucket].count)
1231  big_bucket = i;
1232  }
1233 
1234  }
1235 
1236  *buckets_ = buckets;
1237  return bucket[big_bucket].count;
1238 }
1239 
1240 
1241 static void show_histogram(const struct hist_bucket *bucket,
1242  int buckets,
1243  int total,
1244  int scale)
1245 {
1246  const char *pat1, *pat2;
1247  int i;
1248 
1249  switch((int)(log(bucket[buckets-1].high)/log(10))+1)
1250  {
1251  case 1:
1252  case 2:
1253  pat1 = "%4d %2s: ";
1254  pat2 = "%4d-%2d: ";
1255  break;
1256  case 3:
1257  pat1 = "%5d %3s: ";
1258  pat2 = "%5d-%3d: ";
1259  break;
1260  case 4:
1261  pat1 = "%6d %4s: ";
1262  pat2 = "%6d-%4d: ";
1263  break;
1264  case 5:
1265  pat1 = "%7d %5s: ";
1266  pat2 = "%7d-%5d: ";
1267  break;
1268  case 6:
1269  pat1 = "%8d %6s: ";
1270  pat2 = "%8d-%6d: ";
1271  break;
1272  case 7:
1273  pat1 = "%9d %7s: ";
1274  pat2 = "%9d-%7d: ";
1275  break;
1276  default:
1277  pat1 = "%12d %10s: ";
1278  pat2 = "%12d-%10d: ";
1279  break;
1280  }
1281 
1282  for(i=0; i<buckets; i++)
1283  {
1284  int len;
1285  int j;
1286  float pct;
1287 
1288  pct = 100.0 * (float)bucket[i].count / (float)total;
1289  len = HIST_BAR_MAX * bucket[i].count / scale;
1290  if(len < 1)
1291  len = 1;
1292  assert(len <= HIST_BAR_MAX);
1293 
1294  if(bucket[i].low == bucket[i].high)
1295  fprintf(stderr, pat1, bucket[i].low, "");
1296  else
1297  fprintf(stderr, pat2, bucket[i].low, bucket[i].high);
1298 
1299  for(j=0; j<HIST_BAR_MAX; j++)
1300  fprintf(stderr, j<len?"=":" ");
1301  fprintf(stderr, "\t%5d (%6.2f%%)\n",bucket[i].count,pct);
1302  }
1303 }
1304 
1305 
1306 static void show_q_histogram(const int counts[64], int max_buckets)
1307 {
1308  struct hist_bucket bucket[64];
1309  int buckets = 0;
1310  int total = 0;
1311  int scale;
1312  int i;
1313 
1314 
1315  for(i=0; i<64; i++)
1316  {
1317  if(counts[i])
1318  {
1319  bucket[buckets].low = bucket[buckets].high = i;
1320  bucket[buckets].count = counts[i];
1321  buckets++;
1322  total += counts[i];
1323  }
1324  }
1325 
1326  fprintf(stderr, "\nQuantizer Selection:\n");
1327  scale = merge_hist_buckets(bucket, &buckets, max_buckets);
1328  show_histogram(bucket, buckets, total, scale);
1329 }
1330 
1331 
1332 #define RATE_BINS (100)
1333 struct rate_hist
1334 {
1335  int64_t *pts;
1336  int *sz;
1337  int samples;
1338  int frames;
1339  struct hist_bucket bucket[RATE_BINS];
1340  int total;
1341 };
1342 
1343 
1344 static void init_rate_histogram(struct rate_hist *hist,
1345  const vpx_codec_enc_cfg_t *cfg,
1346  const vpx_rational_t *fps)
1347 {
1348  int i;
1349 
1350  /* Determine the number of samples in the buffer. Use the file's framerate
1351  * to determine the number of frames in rc_buf_sz milliseconds, with an
1352  * adjustment (5/4) to account for alt-refs
1353  */
1354  hist->samples = cfg->rc_buf_sz * 5 / 4 * fps->num / fps->den / 1000;
1355 
1356  // prevent division by zero
1357  if (hist->samples == 0)
1358  hist->samples=1;
1359 
1360  hist->pts = calloc(hist->samples, sizeof(*hist->pts));
1361  hist->sz = calloc(hist->samples, sizeof(*hist->sz));
1362  for(i=0; i<RATE_BINS; i++)
1363  {
1364  hist->bucket[i].low = INT_MAX;
1365  hist->bucket[i].high = 0;
1366  hist->bucket[i].count = 0;
1367  }
1368 }
1369 
1370 
1371 static void destroy_rate_histogram(struct rate_hist *hist)
1372 {
1373  free(hist->pts);
1374  free(hist->sz);
1375 }
1376 
1377 
1378 static void update_rate_histogram(struct rate_hist *hist,
1379  const vpx_codec_enc_cfg_t *cfg,
1380  const vpx_codec_cx_pkt_t *pkt)
1381 {
1382  int i, idx;
1383  int64_t now, then, sum_sz = 0, avg_bitrate;
1384 
1385  now = pkt->data.frame.pts * 1000
1386  * (uint64_t)cfg->g_timebase.num / (uint64_t)cfg->g_timebase.den;
1387 
1388  idx = hist->frames++ % hist->samples;
1389  hist->pts[idx] = now;
1390  hist->sz[idx] = pkt->data.frame.sz;
1391 
1392  if(now < cfg->rc_buf_initial_sz)
1393  return;
1394 
1395  then = now;
1396 
1397  /* Sum the size over the past rc_buf_sz ms */
1398  for(i = hist->frames; i > 0 && hist->frames - i < hist->samples; i--)
1399  {
1400  int i_idx = (i-1) % hist->samples;
1401 
1402  then = hist->pts[i_idx];
1403  if(now - then > cfg->rc_buf_sz)
1404  break;
1405  sum_sz += hist->sz[i_idx];
1406  }
1407 
1408  if (now == then)
1409  return;
1410 
1411  avg_bitrate = sum_sz * 8 * 1000 / (now - then);
1412  idx = avg_bitrate * (RATE_BINS/2) / (cfg->rc_target_bitrate * 1000);
1413  if(idx < 0)
1414  idx = 0;
1415  if(idx > RATE_BINS-1)
1416  idx = RATE_BINS-1;
1417  if(hist->bucket[idx].low > avg_bitrate)
1418  hist->bucket[idx].low = avg_bitrate;
1419  if(hist->bucket[idx].high < avg_bitrate)
1420  hist->bucket[idx].high = avg_bitrate;
1421  hist->bucket[idx].count++;
1422  hist->total++;
1423 }
1424 
1425 
1426 static void show_rate_histogram(struct rate_hist *hist,
1427  const vpx_codec_enc_cfg_t *cfg,
1428  int max_buckets)
1429 {
1430  int i, scale;
1431  int buckets = 0;
1432 
1433  for(i = 0; i < RATE_BINS; i++)
1434  {
1435  if(hist->bucket[i].low == INT_MAX)
1436  continue;
1437  hist->bucket[buckets++] = hist->bucket[i];
1438  }
1439 
1440  fprintf(stderr, "\nRate (over %dms window):\n", cfg->rc_buf_sz);
1441  scale = merge_hist_buckets(hist->bucket, &buckets, max_buckets);
1442  show_histogram(hist->bucket, buckets, hist->total, scale);
1443 }
1444 
1445 #define NELEMENTS(x) (sizeof(x)/sizeof(x[0]))
1446 #define ARG_CTRL_CNT_MAX NELEMENTS(vp8_arg_ctrl_map)
1447 
1448 int main(int argc, const char **argv_)
1449 {
1450  vpx_codec_ctx_t encoder;
1451  const char *in_fn = NULL, *out_fn = NULL, *stats_fn = NULL;
1452  int i;
1453  FILE *infile, *outfile;
1454  vpx_codec_enc_cfg_t cfg;
1455  vpx_codec_err_t res;
1456  int pass, one_pass_only = 0;
1457  stats_io_t stats;
1458  vpx_image_t raw;
1459  const struct codec_item *codec = codecs;
1460  int frame_avail, got_data;
1461 
1462  struct arg arg;
1463  char **argv, **argi, **argj;
1464  int arg_usage = 0, arg_passes = 1, arg_deadline = 0;
1465  int arg_ctrls[ARG_CTRL_CNT_MAX][2], arg_ctrl_cnt = 0;
1466  int arg_limit = 0;
1467  static const arg_def_t **ctrl_args = no_args;
1468  static const int *ctrl_args_map = NULL;
1469  int verbose = 0, show_psnr = 0;
1470  int arg_use_i420 = 1;
1471  unsigned long cx_time = 0;
1472  unsigned int file_type, fourcc;
1473  y4m_input y4m;
1474  struct vpx_rational arg_framerate = {30, 1};
1475  int arg_have_framerate = 0;
1476  int write_webm = 1;
1477  EbmlGlobal ebml = {0};
1478  uint32_t hash = 0;
1479  uint64_t psnr_sse_total = 0;
1480  uint64_t psnr_samples_total = 0;
1481  double psnr_totals[4] = {0, 0, 0, 0};
1482  int psnr_count = 0;
1483  stereo_format_t stereo_fmt = STEREO_FORMAT_MONO;
1484  int counts[64]={0};
1485  int show_q_hist_buckets=0;
1486  int show_rate_hist_buckets=0;
1487  struct rate_hist rate_hist={0};
1488 
1489  exec_name = argv_[0];
1490  ebml.last_pts_ms = -1;
1491 
1492  if (argc < 3)
1493  usage_exit();
1494 
1495 
1496  /* First parse the codec and usage values, because we want to apply other
1497  * parameters on top of the default configuration provided by the codec.
1498  */
1499  argv = argv_dup(argc - 1, argv_ + 1);
1500 
1501  for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step)
1502  {
1503  arg.argv_step = 1;
1504 
1505  if (arg_match(&arg, &codecarg, argi))
1506  {
1507  int j, k = -1;
1508 
1509  for (j = 0; j < sizeof(codecs) / sizeof(codecs[0]); j++)
1510  if (!strcmp(codecs[j].name, arg.val))
1511  k = j;
1512 
1513  if (k >= 0)
1514  codec = codecs + k;
1515  else
1516  die("Error: Unrecognized argument (%s) to --codec\n",
1517  arg.val);
1518 
1519  }
1520  else if (arg_match(&arg, &passes, argi))
1521  {
1522  arg_passes = arg_parse_uint(&arg);
1523 
1524  if (arg_passes < 1 || arg_passes > 2)
1525  die("Error: Invalid number of passes (%d)\n", arg_passes);
1526  }
1527  else if (arg_match(&arg, &pass_arg, argi))
1528  {
1529  one_pass_only = arg_parse_uint(&arg);
1530 
1531  if (one_pass_only < 1 || one_pass_only > 2)
1532  die("Error: Invalid pass selected (%d)\n", one_pass_only);
1533  }
1534  else if (arg_match(&arg, &fpf_name, argi))
1535  stats_fn = arg.val;
1536  else if (arg_match(&arg, &usage, argi))
1537  arg_usage = arg_parse_uint(&arg);
1538  else if (arg_match(&arg, &deadline, argi))
1539  arg_deadline = arg_parse_uint(&arg);
1540  else if (arg_match(&arg, &best_dl, argi))
1541  arg_deadline = VPX_DL_BEST_QUALITY;
1542  else if (arg_match(&arg, &good_dl, argi))
1543  arg_deadline = VPX_DL_GOOD_QUALITY;
1544  else if (arg_match(&arg, &rt_dl, argi))
1545  arg_deadline = VPX_DL_REALTIME;
1546  else if (arg_match(&arg, &use_yv12, argi))
1547  {
1548  arg_use_i420 = 0;
1549  }
1550  else if (arg_match(&arg, &use_i420, argi))
1551  {
1552  arg_use_i420 = 1;
1553  }
1554  else if (arg_match(&arg, &verbosearg, argi))
1555  verbose = 1;
1556  else if (arg_match(&arg, &limit, argi))
1557  arg_limit = arg_parse_uint(&arg);
1558  else if (arg_match(&arg, &psnrarg, argi))
1559  show_psnr = 1;
1560  else if (arg_match(&arg, &framerate, argi))
1561  {
1562  arg_framerate = arg_parse_rational(&arg);
1563  arg_have_framerate = 1;
1564  }
1565  else if (arg_match(&arg, &use_ivf, argi))
1566  write_webm = 0;
1567  else if (arg_match(&arg, &outputfile, argi))
1568  out_fn = arg.val;
1569  else if (arg_match(&arg, &debugmode, argi))
1570  ebml.debug = 1;
1571  else if (arg_match(&arg, &q_hist_n, argi))
1572  show_q_hist_buckets = arg_parse_uint(&arg);
1573  else if (arg_match(&arg, &rate_hist_n, argi))
1574  show_rate_hist_buckets = arg_parse_uint(&arg);
1575  else
1576  argj++;
1577  }
1578 
1579  /* Ensure that --passes and --pass are consistent. If --pass is set and --passes=2,
1580  * ensure --fpf was set.
1581  */
1582  if (one_pass_only)
1583  {
1584  /* DWIM: Assume the user meant passes=2 if pass=2 is specified */
1585  if (one_pass_only > arg_passes)
1586  {
1587  fprintf(stderr, "Warning: Assuming --pass=%d implies --passes=%d\n",
1588  one_pass_only, one_pass_only);
1589  arg_passes = one_pass_only;
1590  }
1591 
1592  if (arg_passes == 2 && !stats_fn)
1593  die("Must specify --fpf when --pass=%d and --passes=2\n", one_pass_only);
1594  }
1595 
1596  /* Populate encoder configuration */
1597  res = vpx_codec_enc_config_default(codec->iface, &cfg, arg_usage);
1598 
1599  if (res)
1600  {
1601  fprintf(stderr, "Failed to get config: %s\n",
1603  return EXIT_FAILURE;
1604  }
1605 
1606  /* Change the default timebase to a high enough value so that the encoder
1607  * will always create strictly increasing timestamps.
1608  */
1609  cfg.g_timebase.den = 1000;
1610 
1611  /* Never use the library's default resolution, require it be parsed
1612  * from the file or set on the command line.
1613  */
1614  cfg.g_w = 0;
1615  cfg.g_h = 0;
1616 
1617  /* Now parse the remainder of the parameters. */
1618  for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step)
1619  {
1620  arg.argv_step = 1;
1621 
1622  if (0);
1623  else if (arg_match(&arg, &threads, argi))
1624  cfg.g_threads = arg_parse_uint(&arg);
1625  else if (arg_match(&arg, &profile, argi))
1626  cfg.g_profile = arg_parse_uint(&arg);
1627  else if (arg_match(&arg, &width, argi))
1628  cfg.g_w = arg_parse_uint(&arg);
1629  else if (arg_match(&arg, &height, argi))
1630  cfg.g_h = arg_parse_uint(&arg);
1631  else if (arg_match(&arg, &stereo_mode, argi))
1632  stereo_fmt = arg_parse_enum_or_int(&arg);
1633  else if (arg_match(&arg, &timebase, argi))
1634  cfg.g_timebase = arg_parse_rational(&arg);
1635  else if (arg_match(&arg, &error_resilient, argi))
1636  cfg.g_error_resilient = arg_parse_uint(&arg);
1637  else if (arg_match(&arg, &lag_in_frames, argi))
1638  cfg.g_lag_in_frames = arg_parse_uint(&arg);
1639  else if (arg_match(&arg, &dropframe_thresh, argi))
1640  cfg.rc_dropframe_thresh = arg_parse_uint(&arg);
1641  else if (arg_match(&arg, &resize_allowed, argi))
1642  cfg.rc_resize_allowed = arg_parse_uint(&arg);
1643  else if (arg_match(&arg, &resize_up_thresh, argi))
1644  cfg.rc_resize_up_thresh = arg_parse_uint(&arg);
1645  else if (arg_match(&arg, &resize_down_thresh, argi))
1646  cfg.rc_resize_down_thresh = arg_parse_uint(&arg);
1647  else if (arg_match(&arg, &end_usage, argi))
1648  cfg.rc_end_usage = arg_parse_enum_or_int(&arg);
1649  else if (arg_match(&arg, &target_bitrate, argi))
1650  cfg.rc_target_bitrate = arg_parse_uint(&arg);
1651  else if (arg_match(&arg, &min_quantizer, argi))
1652  cfg.rc_min_quantizer = arg_parse_uint(&arg);
1653  else if (arg_match(&arg, &max_quantizer, argi))
1654  cfg.rc_max_quantizer = arg_parse_uint(&arg);
1655  else if (arg_match(&arg, &undershoot_pct, argi))
1656  cfg.rc_undershoot_pct = arg_parse_uint(&arg);
1657  else if (arg_match(&arg, &overshoot_pct, argi))
1658  cfg.rc_overshoot_pct = arg_parse_uint(&arg);
1659  else if (arg_match(&arg, &buf_sz, argi))
1660  cfg.rc_buf_sz = arg_parse_uint(&arg);
1661  else if (arg_match(&arg, &buf_initial_sz, argi))
1662  cfg.rc_buf_initial_sz = arg_parse_uint(&arg);
1663  else if (arg_match(&arg, &buf_optimal_sz, argi))
1664  cfg.rc_buf_optimal_sz = arg_parse_uint(&arg);
1665  else if (arg_match(&arg, &bias_pct, argi))
1666  {
1667  cfg.rc_2pass_vbr_bias_pct = arg_parse_uint(&arg);
1668 
1669  if (arg_passes < 2)
1670  fprintf(stderr,
1671  "Warning: option %s ignored in one-pass mode.\n",
1672  arg.name);
1673  }
1674  else if (arg_match(&arg, &minsection_pct, argi))
1675  {
1676  cfg.rc_2pass_vbr_minsection_pct = arg_parse_uint(&arg);
1677 
1678  if (arg_passes < 2)
1679  fprintf(stderr,
1680  "Warning: option %s ignored in one-pass mode.\n",
1681  arg.name);
1682  }
1683  else if (arg_match(&arg, &maxsection_pct, argi))
1684  {
1685  cfg.rc_2pass_vbr_maxsection_pct = arg_parse_uint(&arg);
1686 
1687  if (arg_passes < 2)
1688  fprintf(stderr,
1689  "Warning: option %s ignored in one-pass mode.\n",
1690  arg.name);
1691  }
1692  else if (arg_match(&arg, &kf_min_dist, argi))
1693  cfg.kf_min_dist = arg_parse_uint(&arg);
1694  else if (arg_match(&arg, &kf_max_dist, argi))
1695  cfg.kf_max_dist = arg_parse_uint(&arg);
1696  else if (arg_match(&arg, &kf_disabled, argi))
1697  cfg.kf_mode = VPX_KF_DISABLED;
1698  else
1699  argj++;
1700  }
1701 
1702  /* Handle codec specific options */
1703 #if CONFIG_VP8_ENCODER
1704 
1705  if (codec->iface == &vpx_codec_vp8_cx_algo)
1706  {
1707  ctrl_args = vp8_args;
1708  ctrl_args_map = vp8_arg_ctrl_map;
1709  }
1710 
1711 #endif
1712 
1713  for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step)
1714  {
1715  int match = 0;
1716 
1717  arg.argv_step = 1;
1718 
1719  for (i = 0; ctrl_args[i]; i++)
1720  {
1721  if (arg_match(&arg, ctrl_args[i], argi))
1722  {
1723  int j;
1724  match = 1;
1725 
1726  /* Point either to the next free element or the first
1727  * instance of this control.
1728  */
1729  for(j=0; j<arg_ctrl_cnt; j++)
1730  if(arg_ctrls[j][0] == ctrl_args_map[i])
1731  break;
1732 
1733  /* Update/insert */
1734  assert(j < ARG_CTRL_CNT_MAX);
1735  if (j < ARG_CTRL_CNT_MAX)
1736  {
1737  arg_ctrls[j][0] = ctrl_args_map[i];
1738  arg_ctrls[j][1] = arg_parse_enum_or_int(&arg);
1739  if(j == arg_ctrl_cnt)
1740  arg_ctrl_cnt++;
1741  }
1742 
1743  }
1744  }
1745 
1746  if (!match)
1747  argj++;
1748  }
1749 
1750  /* Check for unrecognized options */
1751  for (argi = argv; *argi; argi++)
1752  if (argi[0][0] == '-' && argi[0][1])
1753  die("Error: Unrecognized option %s\n", *argi);
1754 
1755  /* Handle non-option arguments */
1756  in_fn = argv[0];
1757 
1758  if (!in_fn)
1759  usage_exit();
1760 
1761  if(!out_fn)
1762  die("Error: Output file is required (specify with -o)\n");
1763 
1764  memset(&stats, 0, sizeof(stats));
1765 
1766  for (pass = one_pass_only ? one_pass_only - 1 : 0; pass < arg_passes; pass++)
1767  {
1768  int frames_in = 0, frames_out = 0;
1769  int64_t nbytes = 0;
1770  struct detect_buffer detect;
1771 
1772  /* Parse certain options from the input file, if possible */
1773  infile = strcmp(in_fn, "-") ? fopen(in_fn, "rb")
1774  : set_binary_mode(stdin);
1775 
1776  if (!infile)
1777  {
1778  fprintf(stderr, "Failed to open input file\n");
1779  return EXIT_FAILURE;
1780  }
1781 
1782  /* For RAW input sources, these bytes will applied on the first frame
1783  * in read_frame().
1784  */
1785  detect.buf_read = fread(detect.buf, 1, 4, infile);
1786  detect.position = 0;
1787 
1788  if (detect.buf_read == 4 && file_is_y4m(infile, &y4m, detect.buf))
1789  {
1790  if (y4m_input_open(&y4m, infile, detect.buf, 4) >= 0)
1791  {
1792  file_type = FILE_TYPE_Y4M;
1793  cfg.g_w = y4m.pic_w;
1794  cfg.g_h = y4m.pic_h;
1795 
1796  /* Use the frame rate from the file only if none was specified
1797  * on the command-line.
1798  */
1799  if (!arg_have_framerate)
1800  {
1801  arg_framerate.num = y4m.fps_n;
1802  arg_framerate.den = y4m.fps_d;
1803  }
1804 
1805  arg_use_i420 = 0;
1806  }
1807  else
1808  {
1809  fprintf(stderr, "Unsupported Y4M stream.\n");
1810  return EXIT_FAILURE;
1811  }
1812  }
1813  else if (detect.buf_read == 4 &&
1814  file_is_ivf(infile, &fourcc, &cfg.g_w, &cfg.g_h, &detect))
1815  {
1816  file_type = FILE_TYPE_IVF;
1817  switch (fourcc)
1818  {
1819  case 0x32315659:
1820  arg_use_i420 = 0;
1821  break;
1822  case 0x30323449:
1823  arg_use_i420 = 1;
1824  break;
1825  default:
1826  fprintf(stderr, "Unsupported fourcc (%08x) in IVF\n", fourcc);
1827  return EXIT_FAILURE;
1828  }
1829  }
1830  else
1831  {
1832  file_type = FILE_TYPE_RAW;
1833  }
1834 
1835  if(!cfg.g_w || !cfg.g_h)
1836  {
1837  fprintf(stderr, "Specify stream dimensions with --width (-w) "
1838  " and --height (-h).\n");
1839  return EXIT_FAILURE;
1840  }
1841 
1842 #define SHOW(field) fprintf(stderr, " %-28s = %d\n", #field, cfg.field)
1843 
1844  if (verbose && pass == 0)
1845  {
1846  fprintf(stderr, "Codec: %s\n", vpx_codec_iface_name(codec->iface));
1847  fprintf(stderr, "Source file: %s Format: %s\n", in_fn,
1848  arg_use_i420 ? "I420" : "YV12");
1849  fprintf(stderr, "Destination file: %s\n", out_fn);
1850  fprintf(stderr, "Encoder parameters:\n");
1851 
1852  SHOW(g_usage);
1853  SHOW(g_threads);
1854  SHOW(g_profile);
1855  SHOW(g_w);
1856  SHOW(g_h);
1857  SHOW(g_timebase.num);
1858  SHOW(g_timebase.den);
1859  SHOW(g_error_resilient);
1860  SHOW(g_pass);
1861  SHOW(g_lag_in_frames);
1862  SHOW(rc_dropframe_thresh);
1863  SHOW(rc_resize_allowed);
1864  SHOW(rc_resize_up_thresh);
1865  SHOW(rc_resize_down_thresh);
1866  SHOW(rc_end_usage);
1867  SHOW(rc_target_bitrate);
1868  SHOW(rc_min_quantizer);
1869  SHOW(rc_max_quantizer);
1870  SHOW(rc_undershoot_pct);
1871  SHOW(rc_overshoot_pct);
1872  SHOW(rc_buf_sz);
1873  SHOW(rc_buf_initial_sz);
1874  SHOW(rc_buf_optimal_sz);
1875  SHOW(rc_2pass_vbr_bias_pct);
1876  SHOW(rc_2pass_vbr_minsection_pct);
1877  SHOW(rc_2pass_vbr_maxsection_pct);
1878  SHOW(kf_mode);
1879  SHOW(kf_min_dist);
1880  SHOW(kf_max_dist);
1881  }
1882 
1883  if(pass == (one_pass_only ? one_pass_only - 1 : 0)) {
1884  if (file_type == FILE_TYPE_Y4M)
1885  /*The Y4M reader does its own allocation.
1886  Just initialize this here to avoid problems if we never read any
1887  frames.*/
1888  memset(&raw, 0, sizeof(raw));
1889  else
1890  vpx_img_alloc(&raw, arg_use_i420 ? VPX_IMG_FMT_I420 : VPX_IMG_FMT_YV12,
1891  cfg.g_w, cfg.g_h, 1);
1892 
1893  init_rate_histogram(&rate_hist, &cfg, &arg_framerate);
1894  }
1895 
1896  outfile = strcmp(out_fn, "-") ? fopen(out_fn, "wb")
1897  : set_binary_mode(stdout);
1898 
1899  if (!outfile)
1900  {
1901  fprintf(stderr, "Failed to open output file\n");
1902  return EXIT_FAILURE;
1903  }
1904 
1905  if(write_webm && fseek(outfile, 0, SEEK_CUR))
1906  {
1907  fprintf(stderr, "WebM output to pipes not supported.\n");
1908  return EXIT_FAILURE;
1909  }
1910 
1911  if (stats_fn)
1912  {
1913  if (!stats_open_file(&stats, stats_fn, pass))
1914  {
1915  fprintf(stderr, "Failed to open statistics store\n");
1916  return EXIT_FAILURE;
1917  }
1918  }
1919  else
1920  {
1921  if (!stats_open_mem(&stats, pass))
1922  {
1923  fprintf(stderr, "Failed to open statistics store\n");
1924  return EXIT_FAILURE;
1925  }
1926  }
1927 
1928  cfg.g_pass = arg_passes == 2
1930  : VPX_RC_ONE_PASS;
1931 #if VPX_ENCODER_ABI_VERSION > (1 + VPX_CODEC_ABI_VERSION)
1932 
1933  if (pass)
1934  {
1935  cfg.rc_twopass_stats_in = stats_get(&stats);
1936  }
1937 
1938 #endif
1939 
1940  if(write_webm)
1941  {
1942  ebml.stream = outfile;
1943  write_webm_file_header(&ebml, &cfg, &arg_framerate, stereo_fmt);
1944  }
1945  else
1946  write_ivf_file_header(outfile, &cfg, codec->fourcc, 0);
1947 
1948 
1949  /* Construct Encoder Context */
1950  vpx_codec_enc_init(&encoder, codec->iface, &cfg,
1951  show_psnr ? VPX_CODEC_USE_PSNR : 0);
1952  ctx_exit_on_error(&encoder, "Failed to initialize encoder");
1953 
1954  /* Note that we bypass the vpx_codec_control wrapper macro because
1955  * we're being clever to store the control IDs in an array. Real
1956  * applications will want to make use of the enumerations directly
1957  */
1958  for (i = 0; i < arg_ctrl_cnt; i++)
1959  {
1960  if (vpx_codec_control_(&encoder, arg_ctrls[i][0], arg_ctrls[i][1]))
1961  fprintf(stderr, "Error: Tried to set control %d = %d\n",
1962  arg_ctrls[i][0], arg_ctrls[i][1]);
1963 
1964  ctx_exit_on_error(&encoder, "Failed to control codec");
1965  }
1966 
1967  frame_avail = 1;
1968  got_data = 0;
1969 
1970  while (frame_avail || got_data)
1971  {
1972  vpx_codec_iter_t iter = NULL;
1973  const vpx_codec_cx_pkt_t *pkt;
1974  struct vpx_usec_timer timer;
1975  int64_t frame_start, next_frame_start;
1976 
1977  if (!arg_limit || frames_in < arg_limit)
1978  {
1979  frame_avail = read_frame(infile, &raw, file_type, &y4m,
1980  &detect);
1981 
1982  if (frame_avail)
1983  frames_in++;
1984 
1985  fprintf(stderr,
1986  "\rPass %d/%d frame %4d/%-4d %7"PRId64"B \033[K",
1987  pass + 1, arg_passes, frames_in, frames_out, nbytes);
1988  }
1989  else
1990  frame_avail = 0;
1991 
1992  vpx_usec_timer_start(&timer);
1993 
1994  frame_start = (cfg.g_timebase.den * (int64_t)(frames_in - 1)
1995  * arg_framerate.den) / cfg.g_timebase.num / arg_framerate.num;
1996  next_frame_start = (cfg.g_timebase.den * (int64_t)(frames_in)
1997  * arg_framerate.den)
1998  / cfg.g_timebase.num / arg_framerate.num;
1999  vpx_codec_encode(&encoder, frame_avail ? &raw : NULL, frame_start,
2000  next_frame_start - frame_start,
2001  0, arg_deadline);
2002  vpx_usec_timer_mark(&timer);
2003  cx_time += vpx_usec_timer_elapsed(&timer);
2004  ctx_exit_on_error(&encoder, "Failed to encode frame");
2005 
2006  if(cfg.g_pass != VPX_RC_FIRST_PASS)
2007  {
2008  int q;
2009 
2011  ctx_exit_on_error(&encoder, "Failed to read quantizer");
2012  counts[q]++;
2013  }
2014 
2015  got_data = 0;
2016 
2017  while ((pkt = vpx_codec_get_cx_data(&encoder, &iter)))
2018  {
2019  got_data = 1;
2020 
2021  switch (pkt->kind)
2022  {
2024  frames_out++;
2025  fprintf(stderr, " %6luF",
2026  (unsigned long)pkt->data.frame.sz);
2027 
2028  update_rate_histogram(&rate_hist, &cfg, pkt);
2029  if(write_webm)
2030  {
2031  /* Update the hash */
2032  if(!ebml.debug)
2033  hash = murmur(pkt->data.frame.buf,
2034  pkt->data.frame.sz, hash);
2035 
2036  write_webm_block(&ebml, &cfg, pkt);
2037  }
2038  else
2039  {
2040  write_ivf_frame_header(outfile, pkt);
2041  if(fwrite(pkt->data.frame.buf, 1,
2042  pkt->data.frame.sz, outfile));
2043  }
2044  nbytes += pkt->data.raw.sz;
2045  break;
2046  case VPX_CODEC_STATS_PKT:
2047  frames_out++;
2048  fprintf(stderr, " %6luS",
2049  (unsigned long)pkt->data.twopass_stats.sz);
2050  stats_write(&stats,
2051  pkt->data.twopass_stats.buf,
2052  pkt->data.twopass_stats.sz);
2053  nbytes += pkt->data.raw.sz;
2054  break;
2055  case VPX_CODEC_PSNR_PKT:
2056 
2057  if (show_psnr)
2058  {
2059  int i;
2060 
2061  psnr_sse_total += pkt->data.psnr.sse[0];
2062  psnr_samples_total += pkt->data.psnr.samples[0];
2063  for (i = 0; i < 4; i++)
2064  {
2065  fprintf(stderr, "%.3lf ", pkt->data.psnr.psnr[i]);
2066  psnr_totals[i] += pkt->data.psnr.psnr[i];
2067  }
2068  psnr_count++;
2069  }
2070 
2071  break;
2072  default:
2073  break;
2074  }
2075  }
2076 
2077  fflush(stdout);
2078  }
2079 
2080  fprintf(stderr,
2081  "\rPass %d/%d frame %4d/%-4d %7"PRId64"B %7lub/f %7"PRId64"b/s"
2082  " %7lu %s (%.2f fps)\033[K", pass + 1,
2083  arg_passes, frames_in, frames_out, nbytes,
2084  frames_in ? (unsigned long)(nbytes * 8 / frames_in) : 0,
2085  frames_in ? nbytes * 8 *(int64_t)arg_framerate.num / arg_framerate.den / frames_in : 0,
2086  cx_time > 9999999 ? cx_time / 1000 : cx_time,
2087  cx_time > 9999999 ? "ms" : "us",
2088  cx_time > 0 ? (float)frames_in * 1000000.0 / (float)cx_time : 0);
2089 
2090  if ( (show_psnr) && (psnr_count>0) )
2091  {
2092  int i;
2093  double ovpsnr = vp8_mse2psnr(psnr_samples_total, 255.0,
2094  psnr_sse_total);
2095 
2096  fprintf(stderr, "\nPSNR (Overall/Avg/Y/U/V)");
2097 
2098  fprintf(stderr, " %.3lf", ovpsnr);
2099  for (i = 0; i < 4; i++)
2100  {
2101  fprintf(stderr, " %.3lf", psnr_totals[i]/psnr_count);
2102  }
2103  }
2104 
2105  vpx_codec_destroy(&encoder);
2106 
2107  fclose(infile);
2108  if (file_type == FILE_TYPE_Y4M)
2109  y4m_input_close(&y4m);
2110 
2111  if(write_webm)
2112  {
2113  write_webm_file_footer(&ebml, hash);
2114  free(ebml.cue_list);
2115  ebml.cue_list = NULL;
2116  }
2117  else
2118  {
2119  if (!fseek(outfile, 0, SEEK_SET))
2120  write_ivf_file_header(outfile, &cfg, codec->fourcc, frames_out);
2121  }
2122 
2123  fclose(outfile);
2124  stats_close(&stats, arg_passes-1);
2125  fprintf(stderr, "\n");
2126 
2127  if (one_pass_only)
2128  break;
2129  }
2130 
2131  if (show_q_hist_buckets)
2132  show_q_histogram(counts, show_q_hist_buckets);
2133 
2134  if (show_rate_hist_buckets)
2135  show_rate_histogram(&rate_hist, &cfg, show_rate_hist_buckets);
2136  destroy_rate_histogram(&rate_hist);
2137 
2138  vpx_img_free(&raw);
2139  free(argv);
2140  return EXIT_SUCCESS;
2141 }
Rational Number.
Definition: vpx_encoder.h:212
unsigned int rc_buf_initial_sz
Decoder Buffer Initial Size.
Definition: vpx_encoder.h:533
struct vpx_fixed_buf twopass_stats
Definition: vpx_encoder.h:189
struct vpx_codec_iface vpx_codec_iface_t
Codec interface structure.
Definition: vpx_codec.h:167
control function to set vp8 encoder cpuused
Definition: vp8cx.h:143
Image Descriptor.
Definition: vpx_image.h:97
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
struct vpx_fixed_buf rc_twopass_stats_in
Two-pass stats buffer.
Definition: vpx_encoder.h:441
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:232
unsigned int rc_buf_sz
Decoder Buffer Size.
Definition: vpx_encoder.h:523
struct vpx_fixed_buf raw
Definition: vpx_encoder.h:196
enum vpx_kf_mode kf_mode
Keyframe placement mode.
Definition: vpx_encoder.h:588
int den
Definition: vpx_encoder.h:215
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.
unsigned int rc_max_quantizer
Maximum (Worst Quality) Quantizer.
Definition: vpx_encoder.h:475
unsigned int rc_min_quantizer
Minimum (Best Quality) Quantizer.
Definition: vpx_encoder.h:464
Definition: vpx_encoder.h:156
unsigned int kf_max_dist
Keyframe maximum interval.
Definition: vpx_encoder.h:608
unsigned int g_lag_in_frames
Allow lagged encoding.
Definition: vpx_encoder.h:371
Encoder configuration structure.
Definition: vpx_encoder.h:270
Definition: vp8cx.h:159
control function to set constrained quality level
Definition: vp8cx.h:166
Definition: vp8cx.h:158
Definition: vpx_encoder.h:157
Max data rate for Intra frames.
Definition: vp8cx.h:180
Encoder output packet.
Definition: vpx_encoder.h:167
unsigned int rc_overshoot_pct
Rate control adaptation overshoot control.
Definition: vpx_encoder.h:506
void * buf
Definition: vpx_encoder.h:87
unsigned int rc_2pass_vbr_bias_pct
Two-pass mode CBR/VBR bias.
Definition: vpx_encoder.h:559
unsigned int rc_buf_optimal_sz
Decoder Buffer Optimal Size.
Definition: vpx_encoder.h:543
#define VPX_PLANE_V
Definition: vpx_image.h:117
Generic fixed size buffer structure.
Definition: vpx_encoder.h:85
unsigned int kf_min_dist
Keyframe minimum interval.
Definition: vpx_encoder.h:598
Definition: vpx_encoder.h:223
unsigned int g_profile
Bitstream profile to use.
Definition: vpx_encoder.h:303
Definition: vpx_encoder.h:224
struct vpx_codec_cx_pkt::@1::@2 frame
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:106
unsigned int g_w
Width of the frame.
Definition: vpx_encoder.h:314
unsigned int rc_undershoot_pct
Rate control adaptation undershoot control.
Definition: vpx_encoder.h:493
unsigned int g_h
Height of the frame.
Definition: vpx_encoder.h:324
int stride[4]
Definition: vpx_image.h:127
enum vpx_codec_cx_pkt_kind kind
Definition: vpx_encoder.h:169
unsigned int rc_dropframe_thresh
Temporal resampling configuration, if supported by the codec.
Definition: vpx_encoder.h:394
Definition: vp8cx.h:152
void vpx_img_free(vpx_image_t *img)
Close an image descriptor.
vpx_img_fmt_t fmt
Definition: vpx_image.h:99
unsigned char * planes[4]
Definition: vpx_image.h:126
Definition: vp8cx.h:148
unsigned int rc_target_bitrate
Target data rate.
Definition: vpx_encoder.h:448
#define VPX_DL_REALTIME
Definition: vpx_encoder.h:788
int num
Definition: vpx_encoder.h:214
Definition: vp8cx.h:145
#define VPX_DL_BEST_QUALITY
Definition: vpx_encoder.h:794
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:231
enum vpx_enc_pass g_pass
Multi-pass Encoding Mode.
Definition: vpx_encoder.h:356
double psnr[4]
Definition: vpx_encoder.h:194
#define VPX_CODEC_USE_PSNR
Initialization-time Feature Enabling.
Definition: vpx_encoder.h:75
unsigned int g_threads
Maximum number of threads to use.
Definition: vpx_encoder.h:292
#define VPX_DL_GOOD_QUALITY
Definition: vpx_encoder.h:791
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:116
#define vpx_codec_enc_init(ctx, iface, cfg, flags)
Convenience macro for vpx_codec_enc_init_ver()
Definition: vpx_encoder.h:686
unsigned int rc_resize_allowed
Enable/disable spatial resampling, if supported by the codec.
Definition: vpx_encoder.h:404
vpx_codec_err_t
Algorithm return codes.
Definition: vpx_codec.h:81
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:156
Definition: vpx_encoder.h:249
Definition: vp8cx.h:157
int64_t vpx_codec_pts_t
Time Stamp Type.
Definition: vpx_encoder.h:97
Definition: vp8cx.h:144
vpx_codec_err_t vpx_codec_control_(vpx_codec_ctx_t *ctx, int ctrl_id,...)
Control algorithm.
Definition: vpx_encoder.h:233
#define vpx_codec_control(ctx, id, data)
vpx_codec_control wrapper macro
Definition: vpx_codec.h:392
vpx_codec_err_t vpx_codec_destroy(vpx_codec_ctx_t *ctx)
Destroy a codec instance.
unsigned int d_h
Definition: vpx_image.h:107
size_t sz
Definition: vpx_encoder.h:88
unsigned int rc_resize_down_thresh
Spatial resampling down watermark.
Definition: vpx_encoder.h:422
vpx_codec_err_t err
Definition: vpx_codec.h:197
Definition: vp8cx.h:147
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:108
const void * vpx_codec_iter_t
Iterator.
Definition: vpx_codec.h:182
Definition: vp8cx.h:146
Definition: vpx_encoder.h:155
unsigned int rc_2pass_vbr_maxsection_pct
Two-pass mode per-GOP maximum bitrate.
Definition: vpx_encoder.h:575
vpx_codec_er_flags_t g_error_resilient
Enable error resilient modes.
Definition: vpx_encoder.h:348
unsigned int rc_2pass_vbr_minsection_pct
Two-pass mode per-GOP minimum bitrate.
Definition: vpx_encoder.h:567
#define VPX_FRAME_IS_INVISIBLE
Definition: vpx_encoder.h:114
unsigned int rc_resize_up_thresh
Spatial resampling up watermark.
Definition: vpx_encoder.h:413
enum vpx_rc_mode rc_end_usage
Rate control algorithm to use.
Definition: vpx_encoder.h:433
Definition: vpx_encoder.h:222
Codec context structure.
Definition: vpx_codec.h:193