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