Merge "Modified the inverse walsh to output directly"
[profile/ivi/libvpx.git] / vpxenc.c
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,
637                     vpx_codec_version_str(),
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         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 {
1109     VP8E_SET_CPUUSED, VP8E_SET_ENABLEAUTOALTREF,
1110     VP8E_SET_NOISE_SENSITIVITY, VP8E_SET_SHARPNESS, VP8E_SET_STATIC_THRESHOLD,
1111     VP8E_SET_TOKEN_PARTITIONS,
1112     VP8E_SET_ARNR_MAXFRAMES, VP8E_SET_ARNR_STRENGTH , VP8E_SET_ARNR_TYPE,
1113     VP8E_SET_TUNING, VP8E_SET_CQ_LEVEL, VP8E_SET_MAX_INTRA_BITRATE_PCT, 0
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 ARG_CTRL_CNT_MAX 10
1446
1447 int main(int argc, const char **argv_)
1448 {
1449     vpx_codec_ctx_t        encoder;
1450     const char                  *in_fn = NULL, *out_fn = NULL, *stats_fn = NULL;
1451     int                    i;
1452     FILE                  *infile, *outfile;
1453     vpx_codec_enc_cfg_t    cfg;
1454     vpx_codec_err_t        res;
1455     int                    pass, one_pass_only = 0;
1456     stats_io_t             stats;
1457     vpx_image_t            raw;
1458     const struct codec_item  *codec = codecs;
1459     int                    frame_avail, got_data;
1460
1461     struct arg               arg;
1462     char                   **argv, **argi, **argj;
1463     int                      arg_usage = 0, arg_passes = 1, arg_deadline = 0;
1464     int                      arg_ctrls[ARG_CTRL_CNT_MAX][2], arg_ctrl_cnt = 0;
1465     int                      arg_limit = 0;
1466     static const arg_def_t **ctrl_args = no_args;
1467     static const int        *ctrl_args_map = NULL;
1468     int                      verbose = 0, show_psnr = 0;
1469     int                      arg_use_i420 = 1;
1470     unsigned long            cx_time = 0;
1471     unsigned int             file_type, fourcc;
1472     y4m_input                y4m;
1473     struct vpx_rational      arg_framerate = {30, 1};
1474     int                      arg_have_framerate = 0;
1475     int                      write_webm = 1;
1476     EbmlGlobal               ebml = {0};
1477     uint32_t                 hash = 0;
1478     uint64_t                 psnr_sse_total = 0;
1479     uint64_t                 psnr_samples_total = 0;
1480     double                   psnr_totals[4] = {0, 0, 0, 0};
1481     int                      psnr_count = 0;
1482     stereo_format_t          stereo_fmt = STEREO_FORMAT_MONO;
1483     int                      counts[64]={0};
1484     int                      show_q_hist_buckets=0;
1485     int                      show_rate_hist_buckets=0;
1486     struct rate_hist         rate_hist={0};
1487
1488     exec_name = argv_[0];
1489     ebml.last_pts_ms = -1;
1490
1491     if (argc < 3)
1492         usage_exit();
1493
1494
1495     /* First parse the codec and usage values, because we want to apply other
1496      * parameters on top of the default configuration provided by the codec.
1497      */
1498     argv = argv_dup(argc - 1, argv_ + 1);
1499
1500     for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step)
1501     {
1502         arg.argv_step = 1;
1503
1504         if (arg_match(&arg, &codecarg, argi))
1505         {
1506             int j, k = -1;
1507
1508             for (j = 0; j < sizeof(codecs) / sizeof(codecs[0]); j++)
1509                 if (!strcmp(codecs[j].name, arg.val))
1510                     k = j;
1511
1512             if (k >= 0)
1513                 codec = codecs + k;
1514             else
1515                 die("Error: Unrecognized argument (%s) to --codec\n",
1516                     arg.val);
1517
1518         }
1519         else if (arg_match(&arg, &passes, argi))
1520         {
1521             arg_passes = arg_parse_uint(&arg);
1522
1523             if (arg_passes < 1 || arg_passes > 2)
1524                 die("Error: Invalid number of passes (%d)\n", arg_passes);
1525         }
1526         else if (arg_match(&arg, &pass_arg, argi))
1527         {
1528             one_pass_only = arg_parse_uint(&arg);
1529
1530             if (one_pass_only < 1 || one_pass_only > 2)
1531                 die("Error: Invalid pass selected (%d)\n", one_pass_only);
1532         }
1533         else if (arg_match(&arg, &fpf_name, argi))
1534             stats_fn = arg.val;
1535         else if (arg_match(&arg, &usage, argi))
1536             arg_usage = arg_parse_uint(&arg);
1537         else if (arg_match(&arg, &deadline, argi))
1538             arg_deadline = arg_parse_uint(&arg);
1539         else if (arg_match(&arg, &best_dl, argi))
1540             arg_deadline = VPX_DL_BEST_QUALITY;
1541         else if (arg_match(&arg, &good_dl, argi))
1542             arg_deadline = VPX_DL_GOOD_QUALITY;
1543         else if (arg_match(&arg, &rt_dl, argi))
1544             arg_deadline = VPX_DL_REALTIME;
1545         else if (arg_match(&arg, &use_yv12, argi))
1546         {
1547             arg_use_i420 = 0;
1548         }
1549         else if (arg_match(&arg, &use_i420, argi))
1550         {
1551             arg_use_i420 = 1;
1552         }
1553         else if (arg_match(&arg, &verbosearg, argi))
1554             verbose = 1;
1555         else if (arg_match(&arg, &limit, argi))
1556             arg_limit = arg_parse_uint(&arg);
1557         else if (arg_match(&arg, &psnrarg, argi))
1558             show_psnr = 1;
1559         else if (arg_match(&arg, &framerate, argi))
1560         {
1561             arg_framerate = arg_parse_rational(&arg);
1562             arg_have_framerate = 1;
1563         }
1564         else if (arg_match(&arg, &use_ivf, argi))
1565             write_webm = 0;
1566         else if (arg_match(&arg, &outputfile, argi))
1567             out_fn = arg.val;
1568         else if (arg_match(&arg, &debugmode, argi))
1569             ebml.debug = 1;
1570         else if (arg_match(&arg, &q_hist_n, argi))
1571             show_q_hist_buckets = arg_parse_uint(&arg);
1572         else if (arg_match(&arg, &rate_hist_n, argi))
1573             show_rate_hist_buckets = arg_parse_uint(&arg);
1574         else
1575             argj++;
1576     }
1577
1578     /* Ensure that --passes and --pass are consistent. If --pass is set and --passes=2,
1579      * ensure --fpf was set.
1580      */
1581     if (one_pass_only)
1582     {
1583         /* DWIM: Assume the user meant passes=2 if pass=2 is specified */
1584         if (one_pass_only > arg_passes)
1585         {
1586             fprintf(stderr, "Warning: Assuming --pass=%d implies --passes=%d\n",
1587                    one_pass_only, one_pass_only);
1588             arg_passes = one_pass_only;
1589         }
1590
1591         if (arg_passes == 2 && !stats_fn)
1592             die("Must specify --fpf when --pass=%d and --passes=2\n", one_pass_only);
1593     }
1594
1595     /* Populate encoder configuration */
1596     res = vpx_codec_enc_config_default(codec->iface, &cfg, arg_usage);
1597
1598     if (res)
1599     {
1600         fprintf(stderr, "Failed to get config: %s\n",
1601                 vpx_codec_err_to_string(res));
1602         return EXIT_FAILURE;
1603     }
1604
1605     /* Change the default timebase to a high enough value so that the encoder
1606      * will always create strictly increasing timestamps.
1607      */
1608     cfg.g_timebase.den = 1000;
1609
1610     /* Never use the library's default resolution, require it be parsed
1611      * from the file or set on the command line.
1612      */
1613     cfg.g_w = 0;
1614     cfg.g_h = 0;
1615
1616     /* Now parse the remainder of the parameters. */
1617     for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step)
1618     {
1619         arg.argv_step = 1;
1620
1621         if (0);
1622         else if (arg_match(&arg, &threads, argi))
1623             cfg.g_threads = arg_parse_uint(&arg);
1624         else if (arg_match(&arg, &profile, argi))
1625             cfg.g_profile = arg_parse_uint(&arg);
1626         else if (arg_match(&arg, &width, argi))
1627             cfg.g_w = arg_parse_uint(&arg);
1628         else if (arg_match(&arg, &height, argi))
1629             cfg.g_h = arg_parse_uint(&arg);
1630         else if (arg_match(&arg, &stereo_mode, argi))
1631             stereo_fmt = arg_parse_enum_or_int(&arg);
1632         else if (arg_match(&arg, &timebase, argi))
1633             cfg.g_timebase = arg_parse_rational(&arg);
1634         else if (arg_match(&arg, &error_resilient, argi))
1635             cfg.g_error_resilient = arg_parse_uint(&arg);
1636         else if (arg_match(&arg, &lag_in_frames, argi))
1637             cfg.g_lag_in_frames = arg_parse_uint(&arg);
1638         else if (arg_match(&arg, &dropframe_thresh, argi))
1639             cfg.rc_dropframe_thresh = arg_parse_uint(&arg);
1640         else if (arg_match(&arg, &resize_allowed, argi))
1641             cfg.rc_resize_allowed = arg_parse_uint(&arg);
1642         else if (arg_match(&arg, &resize_up_thresh, argi))
1643             cfg.rc_resize_up_thresh = arg_parse_uint(&arg);
1644         else if (arg_match(&arg, &resize_down_thresh, argi))
1645             cfg.rc_resize_down_thresh = arg_parse_uint(&arg);
1646         else if (arg_match(&arg, &resize_down_thresh, argi))
1647             cfg.rc_resize_down_thresh = arg_parse_uint(&arg);
1648         else if (arg_match(&arg, &end_usage, argi))
1649             cfg.rc_end_usage = arg_parse_enum_or_int(&arg);
1650         else if (arg_match(&arg, &target_bitrate, argi))
1651             cfg.rc_target_bitrate = arg_parse_uint(&arg);
1652         else if (arg_match(&arg, &min_quantizer, argi))
1653             cfg.rc_min_quantizer = arg_parse_uint(&arg);
1654         else if (arg_match(&arg, &max_quantizer, argi))
1655             cfg.rc_max_quantizer = arg_parse_uint(&arg);
1656         else if (arg_match(&arg, &undershoot_pct, argi))
1657             cfg.rc_undershoot_pct = arg_parse_uint(&arg);
1658         else if (arg_match(&arg, &overshoot_pct, argi))
1659             cfg.rc_overshoot_pct = arg_parse_uint(&arg);
1660         else if (arg_match(&arg, &buf_sz, argi))
1661             cfg.rc_buf_sz = arg_parse_uint(&arg);
1662         else if (arg_match(&arg, &buf_initial_sz, argi))
1663             cfg.rc_buf_initial_sz = arg_parse_uint(&arg);
1664         else if (arg_match(&arg, &buf_optimal_sz, argi))
1665             cfg.rc_buf_optimal_sz = arg_parse_uint(&arg);
1666         else if (arg_match(&arg, &bias_pct, argi))
1667         {
1668             cfg.rc_2pass_vbr_bias_pct = arg_parse_uint(&arg);
1669
1670             if (arg_passes < 2)
1671                 fprintf(stderr,
1672                         "Warning: option %s ignored in one-pass mode.\n",
1673                         arg.name);
1674         }
1675         else if (arg_match(&arg, &minsection_pct, argi))
1676         {
1677             cfg.rc_2pass_vbr_minsection_pct = arg_parse_uint(&arg);
1678
1679             if (arg_passes < 2)
1680                 fprintf(stderr,
1681                         "Warning: option %s ignored in one-pass mode.\n",
1682                         arg.name);
1683         }
1684         else if (arg_match(&arg, &maxsection_pct, argi))
1685         {
1686             cfg.rc_2pass_vbr_maxsection_pct = arg_parse_uint(&arg);
1687
1688             if (arg_passes < 2)
1689                 fprintf(stderr,
1690                         "Warning: option %s ignored in one-pass mode.\n",
1691                         arg.name);
1692         }
1693         else if (arg_match(&arg, &kf_min_dist, argi))
1694             cfg.kf_min_dist = arg_parse_uint(&arg);
1695         else if (arg_match(&arg, &kf_max_dist, argi))
1696             cfg.kf_max_dist = arg_parse_uint(&arg);
1697         else if (arg_match(&arg, &kf_disabled, argi))
1698             cfg.kf_mode = VPX_KF_DISABLED;
1699         else
1700             argj++;
1701     }
1702
1703     /* Handle codec specific options */
1704 #if CONFIG_VP8_ENCODER
1705
1706     if (codec->iface == &vpx_codec_vp8_cx_algo)
1707     {
1708         ctrl_args = vp8_args;
1709         ctrl_args_map = vp8_arg_ctrl_map;
1710     }
1711
1712 #endif
1713
1714     for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step)
1715     {
1716         int match = 0;
1717
1718         arg.argv_step = 1;
1719
1720         for (i = 0; ctrl_args[i]; i++)
1721         {
1722             if (arg_match(&arg, ctrl_args[i], argi))
1723             {
1724                 match = 1;
1725
1726                 if (arg_ctrl_cnt < ARG_CTRL_CNT_MAX)
1727                 {
1728                     arg_ctrls[arg_ctrl_cnt][0] = ctrl_args_map[i];
1729                     arg_ctrls[arg_ctrl_cnt][1] = arg_parse_enum_or_int(&arg);
1730                     arg_ctrl_cnt++;
1731                 }
1732             }
1733         }
1734
1735         if (!match)
1736             argj++;
1737     }
1738
1739     /* Check for unrecognized options */
1740     for (argi = argv; *argi; argi++)
1741         if (argi[0][0] == '-' && argi[0][1])
1742             die("Error: Unrecognized option %s\n", *argi);
1743
1744     /* Handle non-option arguments */
1745     in_fn = argv[0];
1746
1747     if (!in_fn)
1748         usage_exit();
1749
1750     if(!out_fn)
1751         die("Error: Output file is required (specify with -o)\n");
1752
1753     memset(&stats, 0, sizeof(stats));
1754
1755     for (pass = one_pass_only ? one_pass_only - 1 : 0; pass < arg_passes; pass++)
1756     {
1757         int frames_in = 0, frames_out = 0;
1758         int64_t nbytes = 0;
1759         struct detect_buffer detect;
1760
1761         /* Parse certain options from the input file, if possible */
1762         infile = strcmp(in_fn, "-") ? fopen(in_fn, "rb")
1763                                     : set_binary_mode(stdin);
1764
1765         if (!infile)
1766         {
1767             fprintf(stderr, "Failed to open input file\n");
1768             return EXIT_FAILURE;
1769         }
1770
1771         /* For RAW input sources, these bytes will applied on the first frame
1772          *  in read_frame().
1773          */
1774         detect.buf_read = fread(detect.buf, 1, 4, infile);
1775         detect.position = 0;
1776
1777         if (detect.buf_read == 4 && file_is_y4m(infile, &y4m, detect.buf))
1778         {
1779             if (y4m_input_open(&y4m, infile, detect.buf, 4) >= 0)
1780             {
1781                 file_type = FILE_TYPE_Y4M;
1782                 cfg.g_w = y4m.pic_w;
1783                 cfg.g_h = y4m.pic_h;
1784
1785                 /* Use the frame rate from the file only if none was specified
1786                  * on the command-line.
1787                  */
1788                 if (!arg_have_framerate)
1789                 {
1790                     arg_framerate.num = y4m.fps_n;
1791                     arg_framerate.den = y4m.fps_d;
1792                 }
1793
1794                 arg_use_i420 = 0;
1795             }
1796             else
1797             {
1798                 fprintf(stderr, "Unsupported Y4M stream.\n");
1799                 return EXIT_FAILURE;
1800             }
1801         }
1802         else if (detect.buf_read == 4 &&
1803                  file_is_ivf(infile, &fourcc, &cfg.g_w, &cfg.g_h, &detect))
1804         {
1805             file_type = FILE_TYPE_IVF;
1806             switch (fourcc)
1807             {
1808             case 0x32315659:
1809                 arg_use_i420 = 0;
1810                 break;
1811             case 0x30323449:
1812                 arg_use_i420 = 1;
1813                 break;
1814             default:
1815                 fprintf(stderr, "Unsupported fourcc (%08x) in IVF\n", fourcc);
1816                 return EXIT_FAILURE;
1817             }
1818         }
1819         else
1820         {
1821             file_type = FILE_TYPE_RAW;
1822         }
1823
1824         if(!cfg.g_w || !cfg.g_h)
1825         {
1826             fprintf(stderr, "Specify stream dimensions with --width (-w) "
1827                             " and --height (-h).\n");
1828             return EXIT_FAILURE;
1829         }
1830
1831 #define SHOW(field) fprintf(stderr, "    %-28s = %d\n", #field, cfg.field)
1832
1833         if (verbose && pass == 0)
1834         {
1835             fprintf(stderr, "Codec: %s\n", vpx_codec_iface_name(codec->iface));
1836             fprintf(stderr, "Source file: %s Format: %s\n", in_fn,
1837                     arg_use_i420 ? "I420" : "YV12");
1838             fprintf(stderr, "Destination file: %s\n", out_fn);
1839             fprintf(stderr, "Encoder parameters:\n");
1840
1841             SHOW(g_usage);
1842             SHOW(g_threads);
1843             SHOW(g_profile);
1844             SHOW(g_w);
1845             SHOW(g_h);
1846             SHOW(g_timebase.num);
1847             SHOW(g_timebase.den);
1848             SHOW(g_error_resilient);
1849             SHOW(g_pass);
1850             SHOW(g_lag_in_frames);
1851             SHOW(rc_dropframe_thresh);
1852             SHOW(rc_resize_allowed);
1853             SHOW(rc_resize_up_thresh);
1854             SHOW(rc_resize_down_thresh);
1855             SHOW(rc_end_usage);
1856             SHOW(rc_target_bitrate);
1857             SHOW(rc_min_quantizer);
1858             SHOW(rc_max_quantizer);
1859             SHOW(rc_undershoot_pct);
1860             SHOW(rc_overshoot_pct);
1861             SHOW(rc_buf_sz);
1862             SHOW(rc_buf_initial_sz);
1863             SHOW(rc_buf_optimal_sz);
1864             SHOW(rc_2pass_vbr_bias_pct);
1865             SHOW(rc_2pass_vbr_minsection_pct);
1866             SHOW(rc_2pass_vbr_maxsection_pct);
1867             SHOW(kf_mode);
1868             SHOW(kf_min_dist);
1869             SHOW(kf_max_dist);
1870         }
1871
1872         if(pass == (one_pass_only ? one_pass_only - 1 : 0)) {
1873             if (file_type == FILE_TYPE_Y4M)
1874                 /*The Y4M reader does its own allocation.
1875                   Just initialize this here to avoid problems if we never read any
1876                    frames.*/
1877                 memset(&raw, 0, sizeof(raw));
1878             else
1879                 vpx_img_alloc(&raw, arg_use_i420 ? VPX_IMG_FMT_I420 : VPX_IMG_FMT_YV12,
1880                               cfg.g_w, cfg.g_h, 1);
1881
1882             init_rate_histogram(&rate_hist, &cfg, &arg_framerate);
1883         }
1884
1885         outfile = strcmp(out_fn, "-") ? fopen(out_fn, "wb")
1886                                       : set_binary_mode(stdout);
1887
1888         if (!outfile)
1889         {
1890             fprintf(stderr, "Failed to open output file\n");
1891             return EXIT_FAILURE;
1892         }
1893
1894         if(write_webm && fseek(outfile, 0, SEEK_CUR))
1895         {
1896             fprintf(stderr, "WebM output to pipes not supported.\n");
1897             return EXIT_FAILURE;
1898         }
1899
1900         if (stats_fn)
1901         {
1902             if (!stats_open_file(&stats, stats_fn, pass))
1903             {
1904                 fprintf(stderr, "Failed to open statistics store\n");
1905                 return EXIT_FAILURE;
1906             }
1907         }
1908         else
1909         {
1910             if (!stats_open_mem(&stats, pass))
1911             {
1912                 fprintf(stderr, "Failed to open statistics store\n");
1913                 return EXIT_FAILURE;
1914             }
1915         }
1916
1917         cfg.g_pass = arg_passes == 2
1918                      ? pass ? VPX_RC_LAST_PASS : VPX_RC_FIRST_PASS
1919                  : VPX_RC_ONE_PASS;
1920 #if VPX_ENCODER_ABI_VERSION > (1 + VPX_CODEC_ABI_VERSION)
1921
1922         if (pass)
1923         {
1924             cfg.rc_twopass_stats_in = stats_get(&stats);
1925         }
1926
1927 #endif
1928
1929         if(write_webm)
1930         {
1931             ebml.stream = outfile;
1932             write_webm_file_header(&ebml, &cfg, &arg_framerate, stereo_fmt);
1933         }
1934         else
1935             write_ivf_file_header(outfile, &cfg, codec->fourcc, 0);
1936
1937
1938         /* Construct Encoder Context */
1939         vpx_codec_enc_init(&encoder, codec->iface, &cfg,
1940                            show_psnr ? VPX_CODEC_USE_PSNR : 0);
1941         ctx_exit_on_error(&encoder, "Failed to initialize encoder");
1942
1943         /* Note that we bypass the vpx_codec_control wrapper macro because
1944          * we're being clever to store the control IDs in an array. Real
1945          * applications will want to make use of the enumerations directly
1946          */
1947         for (i = 0; i < arg_ctrl_cnt; i++)
1948         {
1949             if (vpx_codec_control_(&encoder, arg_ctrls[i][0], arg_ctrls[i][1]))
1950                 fprintf(stderr, "Error: Tried to set control %d = %d\n",
1951                         arg_ctrls[i][0], arg_ctrls[i][1]);
1952
1953             ctx_exit_on_error(&encoder, "Failed to control codec");
1954         }
1955
1956         frame_avail = 1;
1957         got_data = 0;
1958
1959         while (frame_avail || got_data)
1960         {
1961             vpx_codec_iter_t iter = NULL;
1962             const vpx_codec_cx_pkt_t *pkt;
1963             struct vpx_usec_timer timer;
1964             int64_t frame_start, next_frame_start;
1965
1966             if (!arg_limit || frames_in < arg_limit)
1967             {
1968                 frame_avail = read_frame(infile, &raw, file_type, &y4m,
1969                                          &detect);
1970
1971                 if (frame_avail)
1972                     frames_in++;
1973
1974                 fprintf(stderr,
1975                         "\rPass %d/%d frame %4d/%-4d %7"PRId64"B \033[K",
1976                         pass + 1, arg_passes, frames_in, frames_out, nbytes);
1977             }
1978             else
1979                 frame_avail = 0;
1980
1981             vpx_usec_timer_start(&timer);
1982
1983             frame_start = (cfg.g_timebase.den * (int64_t)(frames_in - 1)
1984                           * arg_framerate.den) / cfg.g_timebase.num / arg_framerate.num;
1985             next_frame_start = (cfg.g_timebase.den * (int64_t)(frames_in)
1986                                 * arg_framerate.den)
1987                                 / cfg.g_timebase.num / arg_framerate.num;
1988             vpx_codec_encode(&encoder, frame_avail ? &raw : NULL, frame_start,
1989                              next_frame_start - frame_start,
1990                              0, arg_deadline);
1991             vpx_usec_timer_mark(&timer);
1992             cx_time += vpx_usec_timer_elapsed(&timer);
1993             ctx_exit_on_error(&encoder, "Failed to encode frame");
1994
1995             if(cfg.g_pass != VPX_RC_FIRST_PASS)
1996             {
1997                 int q;
1998
1999                 vpx_codec_control(&encoder, VP8E_GET_LAST_QUANTIZER_64, &q);
2000                 ctx_exit_on_error(&encoder, "Failed to read quantizer");
2001                 counts[q]++;
2002             }
2003
2004             got_data = 0;
2005
2006             while ((pkt = vpx_codec_get_cx_data(&encoder, &iter)))
2007             {
2008                 got_data = 1;
2009
2010                 switch (pkt->kind)
2011                 {
2012                 case VPX_CODEC_CX_FRAME_PKT:
2013                     frames_out++;
2014                     fprintf(stderr, " %6luF",
2015                             (unsigned long)pkt->data.frame.sz);
2016
2017                     update_rate_histogram(&rate_hist, &cfg, pkt);
2018                     if(write_webm)
2019                     {
2020                         /* Update the hash */
2021                         if(!ebml.debug)
2022                             hash = murmur(pkt->data.frame.buf,
2023                                           pkt->data.frame.sz, hash);
2024
2025                         write_webm_block(&ebml, &cfg, pkt);
2026                     }
2027                     else
2028                     {
2029                         write_ivf_frame_header(outfile, pkt);
2030                         if(fwrite(pkt->data.frame.buf, 1,
2031                                   pkt->data.frame.sz, outfile));
2032                     }
2033                     nbytes += pkt->data.raw.sz;
2034                     break;
2035                 case VPX_CODEC_STATS_PKT:
2036                     frames_out++;
2037                     fprintf(stderr, " %6luS",
2038                            (unsigned long)pkt->data.twopass_stats.sz);
2039                     stats_write(&stats,
2040                                 pkt->data.twopass_stats.buf,
2041                                 pkt->data.twopass_stats.sz);
2042                     nbytes += pkt->data.raw.sz;
2043                     break;
2044                 case VPX_CODEC_PSNR_PKT:
2045
2046                     if (show_psnr)
2047                     {
2048                         int i;
2049
2050                         psnr_sse_total += pkt->data.psnr.sse[0];
2051                         psnr_samples_total += pkt->data.psnr.samples[0];
2052                         for (i = 0; i < 4; i++)
2053                         {
2054                             fprintf(stderr, "%.3lf ", pkt->data.psnr.psnr[i]);
2055                             psnr_totals[i] += pkt->data.psnr.psnr[i];
2056                         }
2057                         psnr_count++;
2058                     }
2059
2060                     break;
2061                 default:
2062                     break;
2063                 }
2064             }
2065
2066             fflush(stdout);
2067         }
2068
2069         fprintf(stderr,
2070                "\rPass %d/%d frame %4d/%-4d %7"PRId64"B %7lub/f %7"PRId64"b/s"
2071                " %7lu %s (%.2f fps)\033[K", pass + 1,
2072                arg_passes, frames_in, frames_out, nbytes,
2073                frames_in ? (unsigned long)(nbytes * 8 / frames_in) : 0,
2074                frames_in ? nbytes * 8 *(int64_t)arg_framerate.num / arg_framerate.den / frames_in : 0,
2075                cx_time > 9999999 ? cx_time / 1000 : cx_time,
2076                cx_time > 9999999 ? "ms" : "us",
2077                cx_time > 0 ? (float)frames_in * 1000000.0 / (float)cx_time : 0);
2078
2079         if ( (show_psnr) && (psnr_count>0) )
2080         {
2081             int i;
2082             double ovpsnr = vp8_mse2psnr(psnr_samples_total, 255.0,
2083                                          psnr_sse_total);
2084
2085             fprintf(stderr, "\nPSNR (Overall/Avg/Y/U/V)");
2086
2087             fprintf(stderr, " %.3lf", ovpsnr);
2088             for (i = 0; i < 4; i++)
2089             {
2090                 fprintf(stderr, " %.3lf", psnr_totals[i]/psnr_count);
2091             }
2092         }
2093
2094         vpx_codec_destroy(&encoder);
2095
2096         fclose(infile);
2097         if (file_type == FILE_TYPE_Y4M)
2098             y4m_input_close(&y4m);
2099
2100         if(write_webm)
2101         {
2102             write_webm_file_footer(&ebml, hash);
2103             free(ebml.cue_list);
2104             ebml.cue_list = NULL;
2105         }
2106         else
2107         {
2108             if (!fseek(outfile, 0, SEEK_SET))
2109                 write_ivf_file_header(outfile, &cfg, codec->fourcc, frames_out);
2110         }
2111
2112         fclose(outfile);
2113         stats_close(&stats, arg_passes-1);
2114         fprintf(stderr, "\n");
2115
2116         if (one_pass_only)
2117             break;
2118     }
2119
2120     if (show_q_hist_buckets)
2121         show_q_histogram(counts, show_q_hist_buckets);
2122
2123     if (show_rate_hist_buckets)
2124         show_rate_histogram(&rate_hist, &cfg, show_rate_hist_buckets);
2125     destroy_rate_histogram(&rate_hist);
2126
2127     vpx_img_free(&raw);
2128     free(argv);
2129     return EXIT_SUCCESS;
2130 }