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