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