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