Merge "bug fix: do not set noise sensitivity in vp8_scalable_patterns.c"
[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     int                       have_kf_max_dist;
1521 };
1522
1523
1524 struct stream_state
1525 {
1526     int                       index;
1527     struct stream_state      *next;
1528     struct stream_config      config;
1529     FILE                     *file;
1530     struct rate_hist          rate_hist;
1531     EbmlGlobal                ebml;
1532     uint32_t                  hash;
1533     uint64_t                  psnr_sse_total;
1534     uint64_t                  psnr_samples_total;
1535     double                    psnr_totals[4];
1536     int                       psnr_count;
1537     int                       counts[64];
1538     vpx_codec_ctx_t           encoder;
1539     unsigned int              frames_out;
1540     uint64_t                  cx_time;
1541     size_t                    nbytes;
1542     stats_io_t                stats;
1543 };
1544
1545
1546 void validate_positive_rational(const char          *msg,
1547                                 struct vpx_rational *rat)
1548 {
1549     if (rat->den < 0)
1550     {
1551         rat->num *= -1;
1552         rat->den *= -1;
1553     }
1554
1555     if (rat->num < 0)
1556         die("Error: %s must be positive\n", msg);
1557
1558     if (!rat->den)
1559         die("Error: %s has zero denominator\n", msg);
1560 }
1561
1562
1563 static void parse_global_config(struct global_config *global, char **argv)
1564 {
1565     char       **argi, **argj;
1566     struct arg   arg;
1567
1568     /* Initialize default parameters */
1569     memset(global, 0, sizeof(*global));
1570     global->codec = codecs;
1571     global->passes = 1;
1572     global->use_i420 = 1;
1573
1574     for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step)
1575     {
1576         arg.argv_step = 1;
1577
1578         if (arg_match(&arg, &codecarg, argi))
1579         {
1580             int j, k = -1;
1581
1582             for (j = 0; j < sizeof(codecs) / sizeof(codecs[0]); j++)
1583                 if (!strcmp(codecs[j].name, arg.val))
1584                     k = j;
1585
1586             if (k >= 0)
1587                 global->codec = codecs + k;
1588             else
1589                 die("Error: Unrecognized argument (%s) to --codec\n",
1590                     arg.val);
1591
1592         }
1593         else if (arg_match(&arg, &passes, argi))
1594         {
1595             global->passes = arg_parse_uint(&arg);
1596
1597             if (global->passes < 1 || global->passes > 2)
1598                 die("Error: Invalid number of passes (%d)\n", global->passes);
1599         }
1600         else if (arg_match(&arg, &pass_arg, argi))
1601         {
1602             global->pass = arg_parse_uint(&arg);
1603
1604             if (global->pass < 1 || global->pass > 2)
1605                 die("Error: Invalid pass selected (%d)\n",
1606                     global->pass);
1607         }
1608         else if (arg_match(&arg, &usage, argi))
1609             global->usage = arg_parse_uint(&arg);
1610         else if (arg_match(&arg, &deadline, argi))
1611             global->deadline = arg_parse_uint(&arg);
1612         else if (arg_match(&arg, &best_dl, argi))
1613             global->deadline = VPX_DL_BEST_QUALITY;
1614         else if (arg_match(&arg, &good_dl, argi))
1615             global->deadline = VPX_DL_GOOD_QUALITY;
1616         else if (arg_match(&arg, &rt_dl, argi))
1617             global->deadline = VPX_DL_REALTIME;
1618         else if (arg_match(&arg, &use_yv12, argi))
1619             global->use_i420 = 0;
1620         else if (arg_match(&arg, &use_i420, argi))
1621             global->use_i420 = 1;
1622         else if (arg_match(&arg, &verbosearg, argi))
1623             global->verbose = 1;
1624         else if (arg_match(&arg, &limit, argi))
1625             global->limit = arg_parse_uint(&arg);
1626         else if (arg_match(&arg, &psnrarg, argi))
1627             global->show_psnr = 1;
1628         else if (arg_match(&arg, &framerate, argi))
1629         {
1630             global->framerate = arg_parse_rational(&arg);
1631             validate_positive_rational(arg.name, &global->framerate);
1632             global->have_framerate = 1;
1633         }
1634         else if (arg_match(&arg,&out_part, argi))
1635             global->out_part = 1;
1636         else if (arg_match(&arg, &debugmode, argi))
1637             global->debug = 1;
1638         else if (arg_match(&arg, &q_hist_n, argi))
1639             global->show_q_hist_buckets = arg_parse_uint(&arg);
1640         else if (arg_match(&arg, &rate_hist_n, argi))
1641             global->show_rate_hist_buckets = arg_parse_uint(&arg);
1642         else
1643             argj++;
1644     }
1645
1646     /* Validate global config */
1647
1648     if (global->pass)
1649     {
1650         /* DWIM: Assume the user meant passes=2 if pass=2 is specified */
1651         if (global->pass > global->passes)
1652         {
1653             warn("Assuming --pass=%d implies --passes=%d\n",
1654                  global->pass, global->pass);
1655             global->passes = global->pass;
1656         }
1657     }
1658 }
1659
1660
1661 void open_input_file(struct input_state *input)
1662 {
1663     unsigned int fourcc;
1664
1665     /* Parse certain options from the input file, if possible */
1666     input->file = strcmp(input->fn, "-") ? fopen(input->fn, "rb")
1667                                          : set_binary_mode(stdin);
1668
1669     if (!input->file)
1670         fatal("Failed to open input file");
1671
1672     /* For RAW input sources, these bytes will applied on the first frame
1673      *  in read_frame().
1674      */
1675     input->detect.buf_read = fread(input->detect.buf, 1, 4, input->file);
1676     input->detect.position = 0;
1677
1678     if (input->detect.buf_read == 4
1679         && file_is_y4m(input->file, &input->y4m, input->detect.buf))
1680     {
1681         if (y4m_input_open(&input->y4m, input->file, input->detect.buf, 4) >= 0)
1682         {
1683             input->file_type = FILE_TYPE_Y4M;
1684             input->w = input->y4m.pic_w;
1685             input->h = input->y4m.pic_h;
1686             input->framerate.num = input->y4m.fps_n;
1687             input->framerate.den = input->y4m.fps_d;
1688             input->use_i420 = 0;
1689         }
1690         else
1691             fatal("Unsupported Y4M stream.");
1692     }
1693     else if (input->detect.buf_read == 4 && file_is_ivf(input, &fourcc))
1694     {
1695         input->file_type = FILE_TYPE_IVF;
1696         switch (fourcc)
1697         {
1698         case 0x32315659:
1699             input->use_i420 = 0;
1700             break;
1701         case 0x30323449:
1702             input->use_i420 = 1;
1703             break;
1704         default:
1705             fatal("Unsupported fourcc (%08x) in IVF", fourcc);
1706         }
1707     }
1708     else
1709     {
1710         input->file_type = FILE_TYPE_RAW;
1711     }
1712 }
1713
1714
1715 static void close_input_file(struct input_state *input)
1716 {
1717     fclose(input->file);
1718     if (input->file_type == FILE_TYPE_Y4M)
1719         y4m_input_close(&input->y4m);
1720 }
1721
1722 static struct stream_state *new_stream(struct global_config *global,
1723                                        struct stream_state  *prev)
1724 {
1725     struct stream_state *stream;
1726
1727     stream = calloc(1, sizeof(*stream));
1728     if(!stream)
1729         fatal("Failed to allocate new stream.");
1730     if(prev)
1731     {
1732         memcpy(stream, prev, sizeof(*stream));
1733         stream->index++;
1734         prev->next = stream;
1735     }
1736     else
1737     {
1738         vpx_codec_err_t  res;
1739
1740         /* Populate encoder configuration */
1741         res = vpx_codec_enc_config_default(global->codec->iface,
1742                                            &stream->config.cfg,
1743                                            global->usage);
1744         if (res)
1745             fatal("Failed to get config: %s\n", vpx_codec_err_to_string(res));
1746
1747         /* Change the default timebase to a high enough value so that the
1748          * encoder will always create strictly increasing timestamps.
1749          */
1750         stream->config.cfg.g_timebase.den = 1000;
1751
1752         /* Never use the library's default resolution, require it be parsed
1753          * from the file or set on the command line.
1754          */
1755         stream->config.cfg.g_w = 0;
1756         stream->config.cfg.g_h = 0;
1757
1758         /* Initialize remaining stream parameters */
1759         stream->config.stereo_fmt = STEREO_FORMAT_MONO;
1760         stream->config.write_webm = 1;
1761         stream->ebml.last_pts_ms = -1;
1762
1763         /* Allows removal of the application version from the EBML tags */
1764         stream->ebml.debug = global->debug;
1765     }
1766
1767     /* Output files must be specified for each stream */
1768     stream->config.out_fn = NULL;
1769
1770     stream->next = NULL;
1771     return stream;
1772 }
1773
1774
1775 static int parse_stream_params(struct global_config *global,
1776                                struct stream_state  *stream,
1777                                char **argv)
1778 {
1779     char                   **argi, **argj;
1780     struct arg               arg;
1781     static const arg_def_t **ctrl_args = no_args;
1782     static const int        *ctrl_args_map = NULL;
1783     struct stream_config    *config = &stream->config;
1784     int                      eos_mark_found = 0;
1785
1786     /* Handle codec specific options */
1787     if (global->codec->iface == &vpx_codec_vp8_cx_algo)
1788     {
1789         ctrl_args = vp8_args;
1790         ctrl_args_map = vp8_arg_ctrl_map;
1791     }
1792
1793     for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step)
1794     {
1795         arg.argv_step = 1;
1796
1797         /* Once we've found an end-of-stream marker (--) we want to continue
1798          * shifting arguments but not consuming them.
1799          */
1800         if (eos_mark_found)
1801         {
1802             argj++;
1803             continue;
1804         }
1805         else if (!strcmp(*argj, "--"))
1806         {
1807             eos_mark_found = 1;
1808             continue;
1809         }
1810
1811         if (0);
1812         else if (arg_match(&arg, &outputfile, argi))
1813             config->out_fn = arg.val;
1814         else if (arg_match(&arg, &fpf_name, argi))
1815             config->stats_fn = arg.val;
1816         else if (arg_match(&arg, &use_ivf, argi))
1817             config->write_webm = 0;
1818         else if (arg_match(&arg, &threads, argi))
1819             config->cfg.g_threads = arg_parse_uint(&arg);
1820         else if (arg_match(&arg, &profile, argi))
1821             config->cfg.g_profile = arg_parse_uint(&arg);
1822         else if (arg_match(&arg, &width, argi))
1823             config->cfg.g_w = arg_parse_uint(&arg);
1824         else if (arg_match(&arg, &height, argi))
1825             config->cfg.g_h = arg_parse_uint(&arg);
1826         else if (arg_match(&arg, &stereo_mode, argi))
1827             config->stereo_fmt = arg_parse_enum_or_int(&arg);
1828         else if (arg_match(&arg, &timebase, argi))
1829         {
1830             config->cfg.g_timebase = arg_parse_rational(&arg);
1831             validate_positive_rational(arg.name, &config->cfg.g_timebase);
1832         }
1833         else if (arg_match(&arg, &error_resilient, argi))
1834             config->cfg.g_error_resilient = arg_parse_uint(&arg);
1835         else if (arg_match(&arg, &lag_in_frames, argi))
1836             config->cfg.g_lag_in_frames = arg_parse_uint(&arg);
1837         else if (arg_match(&arg, &dropframe_thresh, argi))
1838             config->cfg.rc_dropframe_thresh = arg_parse_uint(&arg);
1839         else if (arg_match(&arg, &resize_allowed, argi))
1840             config->cfg.rc_resize_allowed = arg_parse_uint(&arg);
1841         else if (arg_match(&arg, &resize_up_thresh, argi))
1842             config->cfg.rc_resize_up_thresh = arg_parse_uint(&arg);
1843         else if (arg_match(&arg, &resize_down_thresh, argi))
1844             config->cfg.rc_resize_down_thresh = arg_parse_uint(&arg);
1845         else if (arg_match(&arg, &end_usage, argi))
1846             config->cfg.rc_end_usage = arg_parse_enum_or_int(&arg);
1847         else if (arg_match(&arg, &target_bitrate, argi))
1848             config->cfg.rc_target_bitrate = arg_parse_uint(&arg);
1849         else if (arg_match(&arg, &min_quantizer, argi))
1850             config->cfg.rc_min_quantizer = arg_parse_uint(&arg);
1851         else if (arg_match(&arg, &max_quantizer, argi))
1852             config->cfg.rc_max_quantizer = arg_parse_uint(&arg);
1853         else if (arg_match(&arg, &undershoot_pct, argi))
1854             config->cfg.rc_undershoot_pct = arg_parse_uint(&arg);
1855         else if (arg_match(&arg, &overshoot_pct, argi))
1856             config->cfg.rc_overshoot_pct = arg_parse_uint(&arg);
1857         else if (arg_match(&arg, &buf_sz, argi))
1858             config->cfg.rc_buf_sz = arg_parse_uint(&arg);
1859         else if (arg_match(&arg, &buf_initial_sz, argi))
1860             config->cfg.rc_buf_initial_sz = arg_parse_uint(&arg);
1861         else if (arg_match(&arg, &buf_optimal_sz, argi))
1862             config->cfg.rc_buf_optimal_sz = arg_parse_uint(&arg);
1863         else if (arg_match(&arg, &bias_pct, argi))
1864         {
1865             config->cfg.rc_2pass_vbr_bias_pct = arg_parse_uint(&arg);
1866
1867             if (global->passes < 2)
1868                 warn("option %s ignored in one-pass mode.\n", arg.name);
1869         }
1870         else if (arg_match(&arg, &minsection_pct, argi))
1871         {
1872             config->cfg.rc_2pass_vbr_minsection_pct = arg_parse_uint(&arg);
1873
1874             if (global->passes < 2)
1875                 warn("option %s ignored in one-pass mode.\n", arg.name);
1876         }
1877         else if (arg_match(&arg, &maxsection_pct, argi))
1878         {
1879             config->cfg.rc_2pass_vbr_maxsection_pct = arg_parse_uint(&arg);
1880
1881             if (global->passes < 2)
1882                 warn("option %s ignored in one-pass mode.\n", arg.name);
1883         }
1884         else if (arg_match(&arg, &kf_min_dist, argi))
1885             config->cfg.kf_min_dist = arg_parse_uint(&arg);
1886         else if (arg_match(&arg, &kf_max_dist, argi))
1887         {
1888             config->cfg.kf_max_dist = arg_parse_uint(&arg);
1889             config->have_kf_max_dist = 1;
1890         }
1891         else if (arg_match(&arg, &kf_disabled, argi))
1892             config->cfg.kf_mode = VPX_KF_DISABLED;
1893         else
1894         {
1895             int i, match = 0;
1896
1897             for (i = 0; ctrl_args[i]; i++)
1898             {
1899                 if (arg_match(&arg, ctrl_args[i], argi))
1900                 {
1901                     int j;
1902                     match = 1;
1903
1904                     /* Point either to the next free element or the first
1905                     * instance of this control.
1906                     */
1907                     for(j=0; j<config->arg_ctrl_cnt; j++)
1908                         if(config->arg_ctrls[j][0] == ctrl_args_map[i])
1909                             break;
1910
1911                     /* Update/insert */
1912                     assert(j < ARG_CTRL_CNT_MAX);
1913                     if (j < ARG_CTRL_CNT_MAX)
1914                     {
1915                         config->arg_ctrls[j][0] = ctrl_args_map[i];
1916                         config->arg_ctrls[j][1] = arg_parse_enum_or_int(&arg);
1917                         if(j == config->arg_ctrl_cnt)
1918                             config->arg_ctrl_cnt++;
1919                     }
1920
1921                 }
1922             }
1923
1924             if (!match)
1925                 argj++;
1926         }
1927     }
1928
1929     return eos_mark_found;
1930 }
1931
1932
1933 #define FOREACH_STREAM(func)\
1934 do\
1935 {\
1936     struct stream_state  *stream;\
1937 \
1938     for(stream = streams; stream; stream = stream->next)\
1939         func;\
1940 }while(0)
1941
1942
1943 static void validate_stream_config(struct stream_state *stream)
1944 {
1945     struct stream_state *streami;
1946
1947     if(!stream->config.cfg.g_w || !stream->config.cfg.g_h)
1948         fatal("Stream %d: Specify stream dimensions with --width (-w) "
1949               " and --height (-h)", stream->index);
1950
1951     for(streami = stream; streami; streami = streami->next)
1952     {
1953         /* All streams require output files */
1954         if(!streami->config.out_fn)
1955             fatal("Stream %d: Output file is required (specify with -o)",
1956                   streami->index);
1957
1958         /* Check for two streams outputting to the same file */
1959         if(streami != stream)
1960         {
1961             const char *a = stream->config.out_fn;
1962             const char *b = streami->config.out_fn;
1963             if(!strcmp(a,b) && strcmp(a, "/dev/null") && strcmp(a, ":nul"))
1964                 fatal("Stream %d: duplicate output file (from stream %d)",
1965                       streami->index, stream->index);
1966         }
1967
1968         /* Check for two streams sharing a stats file. */
1969         if(streami != stream)
1970         {
1971             const char *a = stream->config.stats_fn;
1972             const char *b = streami->config.stats_fn;
1973             if(a && b && !strcmp(a,b))
1974                 fatal("Stream %d: duplicate stats file (from stream %d)",
1975                       streami->index, stream->index);
1976         }
1977     }
1978 }
1979
1980
1981 static void set_stream_dimensions(struct stream_state *stream,
1982                                   unsigned int w,
1983                                   unsigned int h)
1984 {
1985     if ((stream->config.cfg.g_w && stream->config.cfg.g_w != w)
1986         ||(stream->config.cfg.g_h && stream->config.cfg.g_h != h))
1987         fatal("Stream %d: Resizing not yet supported", stream->index);
1988     stream->config.cfg.g_w = w;
1989     stream->config.cfg.g_h = h;
1990 }
1991
1992
1993 static void set_default_kf_interval(struct stream_state  *stream,
1994                                     struct global_config *global)
1995 {
1996     /* Use a max keyframe interval of 5 seconds, if none was
1997      * specified on the command line.
1998      */
1999     if (!stream->config.have_kf_max_dist)
2000     {
2001         double framerate = (double)global->framerate.num/global->framerate.den;
2002         if (framerate > 0.0)
2003             stream->config.cfg.kf_max_dist = 5.0*framerate;
2004     }
2005 }
2006
2007
2008 static void show_stream_config(struct stream_state  *stream,
2009                                struct global_config *global,
2010                                struct input_state   *input)
2011 {
2012
2013 #define SHOW(field) \
2014     fprintf(stderr, "    %-28s = %d\n", #field, stream->config.cfg.field)
2015
2016     if(stream->index == 0)
2017     {
2018         fprintf(stderr, "Codec: %s\n",
2019                 vpx_codec_iface_name(global->codec->iface));
2020         fprintf(stderr, "Source file: %s Format: %s\n", input->fn,
2021                 input->use_i420 ? "I420" : "YV12");
2022     }
2023     if(stream->next || stream->index)
2024         fprintf(stderr, "\nStream Index: %d\n", stream->index);
2025     fprintf(stderr, "Destination file: %s\n", stream->config.out_fn);
2026     fprintf(stderr, "Encoder parameters:\n");
2027
2028     SHOW(g_usage);
2029     SHOW(g_threads);
2030     SHOW(g_profile);
2031     SHOW(g_w);
2032     SHOW(g_h);
2033     SHOW(g_timebase.num);
2034     SHOW(g_timebase.den);
2035     SHOW(g_error_resilient);
2036     SHOW(g_pass);
2037     SHOW(g_lag_in_frames);
2038     SHOW(rc_dropframe_thresh);
2039     SHOW(rc_resize_allowed);
2040     SHOW(rc_resize_up_thresh);
2041     SHOW(rc_resize_down_thresh);
2042     SHOW(rc_end_usage);
2043     SHOW(rc_target_bitrate);
2044     SHOW(rc_min_quantizer);
2045     SHOW(rc_max_quantizer);
2046     SHOW(rc_undershoot_pct);
2047     SHOW(rc_overshoot_pct);
2048     SHOW(rc_buf_sz);
2049     SHOW(rc_buf_initial_sz);
2050     SHOW(rc_buf_optimal_sz);
2051     SHOW(rc_2pass_vbr_bias_pct);
2052     SHOW(rc_2pass_vbr_minsection_pct);
2053     SHOW(rc_2pass_vbr_maxsection_pct);
2054     SHOW(kf_mode);
2055     SHOW(kf_min_dist);
2056     SHOW(kf_max_dist);
2057 }
2058
2059
2060 static void open_output_file(struct stream_state *stream,
2061                              struct global_config *global)
2062 {
2063     const char *fn = stream->config.out_fn;
2064
2065     stream->file = strcmp(fn, "-") ? fopen(fn, "wb") : set_binary_mode(stdout);
2066
2067     if (!stream->file)
2068         fatal("Failed to open output file");
2069
2070     if(stream->config.write_webm && fseek(stream->file, 0, SEEK_CUR))
2071         fatal("WebM output to pipes not supported.");
2072
2073     if(stream->config.write_webm)
2074     {
2075         stream->ebml.stream = stream->file;
2076         write_webm_file_header(&stream->ebml, &stream->config.cfg,
2077                                &global->framerate,
2078                                stream->config.stereo_fmt);
2079     }
2080     else
2081         write_ivf_file_header(stream->file, &stream->config.cfg,
2082                               global->codec->fourcc, 0);
2083 }
2084
2085
2086 static void close_output_file(struct stream_state *stream,
2087                               unsigned int         fourcc)
2088 {
2089     if(stream->config.write_webm)
2090     {
2091         write_webm_file_footer(&stream->ebml, stream->hash);
2092         free(stream->ebml.cue_list);
2093         stream->ebml.cue_list = NULL;
2094     }
2095     else
2096     {
2097         if (!fseek(stream->file, 0, SEEK_SET))
2098             write_ivf_file_header(stream->file, &stream->config.cfg,
2099                                   fourcc,
2100                                   stream->frames_out);
2101     }
2102
2103     fclose(stream->file);
2104 }
2105
2106
2107 static void setup_pass(struct stream_state  *stream,
2108                        struct global_config *global,
2109                        int                   pass)
2110 {
2111     if (stream->config.stats_fn)
2112     {
2113         if (!stats_open_file(&stream->stats, stream->config.stats_fn,
2114                              pass))
2115             fatal("Failed to open statistics store");
2116     }
2117     else
2118     {
2119         if (!stats_open_mem(&stream->stats, pass))
2120             fatal("Failed to open statistics store");
2121     }
2122
2123     stream->config.cfg.g_pass = global->passes == 2
2124         ? pass ? VPX_RC_LAST_PASS : VPX_RC_FIRST_PASS
2125         : VPX_RC_ONE_PASS;
2126     if (pass)
2127         stream->config.cfg.rc_twopass_stats_in = stats_get(&stream->stats);
2128
2129     stream->cx_time = 0;
2130     stream->nbytes = 0;
2131     stream->frames_out = 0;
2132 }
2133
2134
2135 static void initialize_encoder(struct stream_state  *stream,
2136                                struct global_config *global)
2137 {
2138     int i;
2139     int flags = 0;
2140
2141     flags |= global->show_psnr ? VPX_CODEC_USE_PSNR : 0;
2142     flags |= global->out_part ? VPX_CODEC_USE_OUTPUT_PARTITION : 0;
2143
2144     /* Construct Encoder Context */
2145     vpx_codec_enc_init(&stream->encoder, global->codec->iface,
2146                         &stream->config.cfg, flags);
2147     ctx_exit_on_error(&stream->encoder, "Failed to initialize encoder");
2148
2149     /* Note that we bypass the vpx_codec_control wrapper macro because
2150      * we're being clever to store the control IDs in an array. Real
2151      * applications will want to make use of the enumerations directly
2152      */
2153     for (i = 0; i < stream->config.arg_ctrl_cnt; i++)
2154     {
2155         int ctrl = stream->config.arg_ctrls[i][0];
2156         int value = stream->config.arg_ctrls[i][1];
2157         if (vpx_codec_control_(&stream->encoder, ctrl, value))
2158             fprintf(stderr, "Error: Tried to set control %d = %d\n",
2159                     ctrl, value);
2160
2161         ctx_exit_on_error(&stream->encoder, "Failed to control codec");
2162     }
2163 }
2164
2165
2166 static void encode_frame(struct stream_state  *stream,
2167                          struct global_config *global,
2168                          struct vpx_image     *img,
2169                          unsigned int          frames_in)
2170 {
2171     vpx_codec_pts_t frame_start, next_frame_start;
2172     struct vpx_codec_enc_cfg *cfg = &stream->config.cfg;
2173     struct vpx_usec_timer timer;
2174
2175     frame_start = (cfg->g_timebase.den * (int64_t)(frames_in - 1)
2176                   * global->framerate.den)
2177                   / cfg->g_timebase.num / global->framerate.num;
2178     next_frame_start = (cfg->g_timebase.den * (int64_t)(frames_in)
2179                         * global->framerate.den)
2180                         / cfg->g_timebase.num / global->framerate.num;
2181     vpx_usec_timer_start(&timer);
2182     vpx_codec_encode(&stream->encoder, img, frame_start,
2183                      next_frame_start - frame_start,
2184                      0, global->deadline);
2185     vpx_usec_timer_mark(&timer);
2186     stream->cx_time += vpx_usec_timer_elapsed(&timer);
2187     ctx_exit_on_error(&stream->encoder, "Stream %d: Failed to encode frame",
2188                       stream->index);
2189 }
2190
2191
2192 static void update_quantizer_histogram(struct stream_state *stream)
2193 {
2194     if(stream->config.cfg.g_pass != VPX_RC_FIRST_PASS)
2195     {
2196         int q;
2197
2198         vpx_codec_control(&stream->encoder, VP8E_GET_LAST_QUANTIZER_64, &q);
2199         ctx_exit_on_error(&stream->encoder, "Failed to read quantizer");
2200         stream->counts[q]++;
2201     }
2202 }
2203
2204
2205 static void get_cx_data(struct stream_state  *stream,
2206                         struct global_config *global,
2207                         int                  *got_data)
2208 {
2209     const vpx_codec_cx_pkt_t *pkt;
2210     const struct vpx_codec_enc_cfg *cfg = &stream->config.cfg;
2211     vpx_codec_iter_t iter = NULL;
2212
2213     while ((pkt = vpx_codec_get_cx_data(&stream->encoder, &iter)))
2214     {
2215         static size_t fsize = 0;
2216         static off_t ivf_header_pos = 0;
2217
2218         *got_data = 1;
2219
2220         switch (pkt->kind)
2221         {
2222         case VPX_CODEC_CX_FRAME_PKT:
2223             if (!(pkt->data.frame.flags & VPX_FRAME_IS_FRAGMENT))
2224             {
2225                 stream->frames_out++;
2226             }
2227             fprintf(stderr, " %6luF",
2228                     (unsigned long)pkt->data.frame.sz);
2229
2230             update_rate_histogram(&stream->rate_hist, cfg, pkt);
2231             if(stream->config.write_webm)
2232             {
2233                 /* Update the hash */
2234                 if(!stream->ebml.debug)
2235                     stream->hash = murmur(pkt->data.frame.buf,
2236                                           pkt->data.frame.sz, stream->hash);
2237
2238                 write_webm_block(&stream->ebml, cfg, pkt);
2239             }
2240             else
2241             {
2242                 if (pkt->data.frame.partition_id <= 0)
2243                 {
2244                     ivf_header_pos = ftello(stream->file);
2245                     fsize = pkt->data.frame.sz;
2246
2247                     write_ivf_frame_header(stream->file, pkt);
2248                 }
2249                 else
2250                 {
2251                     fsize += pkt->data.frame.sz;
2252
2253                     if (!(pkt->data.frame.flags & VPX_FRAME_IS_FRAGMENT))
2254                     {
2255                         off_t currpos = ftello(stream->file);
2256                         fseeko(stream->file, ivf_header_pos, SEEK_SET);
2257                         write_ivf_frame_size(stream->file, fsize);
2258                         fseeko(stream->file, currpos, SEEK_SET);
2259                     }
2260                 }
2261
2262                 fwrite(pkt->data.frame.buf, 1,
2263                        pkt->data.frame.sz, stream->file);
2264             }
2265             stream->nbytes += pkt->data.raw.sz;
2266             break;
2267         case VPX_CODEC_STATS_PKT:
2268             stream->frames_out++;
2269             fprintf(stderr, " %6luS",
2270                    (unsigned long)pkt->data.twopass_stats.sz);
2271             stats_write(&stream->stats,
2272                         pkt->data.twopass_stats.buf,
2273                         pkt->data.twopass_stats.sz);
2274             stream->nbytes += pkt->data.raw.sz;
2275             break;
2276         case VPX_CODEC_PSNR_PKT:
2277
2278             if (global->show_psnr)
2279             {
2280                 int i;
2281
2282                 stream->psnr_sse_total += pkt->data.psnr.sse[0];
2283                 stream->psnr_samples_total += pkt->data.psnr.samples[0];
2284                 for (i = 0; i < 4; i++)
2285                 {
2286                     fprintf(stderr, "%.3lf ", pkt->data.psnr.psnr[i]);
2287                     stream->psnr_totals[i] += pkt->data.psnr.psnr[i];
2288                 }
2289                 stream->psnr_count++;
2290             }
2291
2292             break;
2293         default:
2294             break;
2295         }
2296     }
2297 }
2298
2299
2300 static void show_psnr(struct stream_state  *stream)
2301 {
2302     int i;
2303     double ovpsnr;
2304
2305     if (!stream->psnr_count)
2306         return;
2307
2308     fprintf(stderr, "Stream %d PSNR (Overall/Avg/Y/U/V)", stream->index);
2309     ovpsnr = vp8_mse2psnr(stream->psnr_samples_total, 255.0,
2310                           stream->psnr_sse_total);
2311     fprintf(stderr, " %.3lf", ovpsnr);
2312
2313     for (i = 0; i < 4; i++)
2314     {
2315         fprintf(stderr, " %.3lf", stream->psnr_totals[i]/stream->psnr_count);
2316     }
2317     fprintf(stderr, "\n");
2318 }
2319
2320
2321 float usec_to_fps(uint64_t usec, unsigned int frames)
2322 {
2323     return usec > 0 ? (float)frames * 1000000.0 / (float)usec : 0;
2324 }
2325
2326
2327 int main(int argc, const char **argv_)
2328 {
2329     int                    pass;
2330     vpx_image_t            raw;
2331     int                    frame_avail, got_data;
2332
2333     struct input_state       input = {0};
2334     struct global_config     global;
2335     struct stream_state     *streams = NULL;
2336     char                   **argv, **argi;
2337     unsigned long            cx_time = 0;
2338     int                      stream_cnt = 0;
2339
2340     exec_name = argv_[0];
2341
2342     if (argc < 3)
2343         usage_exit();
2344
2345     /* Setup default input stream settings */
2346     input.framerate.num = 30;
2347     input.framerate.den = 1;
2348     input.use_i420 = 1;
2349
2350     /* First parse the global configuration values, because we want to apply
2351      * other parameters on top of the default configuration provided by the
2352      * codec.
2353      */
2354     argv = argv_dup(argc - 1, argv_ + 1);
2355     parse_global_config(&global, argv);
2356
2357     {
2358         /* Now parse each stream's parameters. Using a local scope here
2359          * due to the use of 'stream' as loop variable in FOREACH_STREAM
2360          * loops
2361          */
2362         struct stream_state *stream = NULL;
2363
2364         do
2365         {
2366             stream = new_stream(&global, stream);
2367             stream_cnt++;
2368             if(!streams)
2369                 streams = stream;
2370         } while(parse_stream_params(&global, stream, argv));
2371     }
2372
2373     /* Check for unrecognized options */
2374     for (argi = argv; *argi; argi++)
2375         if (argi[0][0] == '-' && argi[0][1])
2376             die("Error: Unrecognized option %s\n", *argi);
2377
2378     /* Handle non-option arguments */
2379     input.fn = argv[0];
2380
2381     if (!input.fn)
2382         usage_exit();
2383
2384     for (pass = global.pass ? global.pass - 1 : 0; pass < global.passes; pass++)
2385     {
2386         int frames_in = 0;
2387
2388         open_input_file(&input);
2389
2390         /* If the input file doesn't specify its w/h (raw files), try to get
2391          * the data from the first stream's configuration.
2392          */
2393         if(!input.w || !input.h)
2394             FOREACH_STREAM({
2395                 if(stream->config.cfg.g_w && stream->config.cfg.g_h)
2396                 {
2397                     input.w = stream->config.cfg.g_w;
2398                     input.h = stream->config.cfg.g_h;
2399                     break;
2400                 }
2401             });
2402
2403         /* Update stream configurations from the input file's parameters */
2404         FOREACH_STREAM(set_stream_dimensions(stream, input.w, input.h));
2405         FOREACH_STREAM(validate_stream_config(stream));
2406
2407         /* Ensure that --passes and --pass are consistent. If --pass is set and
2408          * --passes=2, ensure --fpf was set.
2409          */
2410         if (global.pass && global.passes == 2)
2411             FOREACH_STREAM({
2412                 if(!stream->config.stats_fn)
2413                     die("Stream %d: Must specify --fpf when --pass=%d"
2414                         " and --passes=2\n", stream->index, global.pass);
2415             });
2416
2417
2418         /* Use the frame rate from the file only if none was specified
2419          * on the command-line.
2420          */
2421         if (!global.have_framerate)
2422             global.framerate = input.framerate;
2423
2424         FOREACH_STREAM(set_default_kf_interval(stream, &global));
2425
2426         /* Show configuration */
2427         if (global.verbose && pass == 0)
2428             FOREACH_STREAM(show_stream_config(stream, &global, &input));
2429
2430         if(pass == (global.pass ? global.pass - 1 : 0)) {
2431             if (input.file_type == FILE_TYPE_Y4M)
2432                 /*The Y4M reader does its own allocation.
2433                   Just initialize this here to avoid problems if we never read any
2434                    frames.*/
2435                 memset(&raw, 0, sizeof(raw));
2436             else
2437                 vpx_img_alloc(&raw,
2438                               input.use_i420 ? VPX_IMG_FMT_I420
2439                                              : VPX_IMG_FMT_YV12,
2440                               input.w, input.h, 32);
2441
2442             FOREACH_STREAM(init_rate_histogram(&stream->rate_hist,
2443                                                &stream->config.cfg,
2444                                                &global.framerate));
2445         }
2446
2447         FOREACH_STREAM(open_output_file(stream, &global));
2448         FOREACH_STREAM(setup_pass(stream, &global, pass));
2449         FOREACH_STREAM(initialize_encoder(stream, &global));
2450
2451         frame_avail = 1;
2452         got_data = 0;
2453
2454         while (frame_avail || got_data)
2455         {
2456             struct vpx_usec_timer timer;
2457
2458             if (!global.limit || frames_in < global.limit)
2459             {
2460                 frame_avail = read_frame(&input, &raw);
2461
2462                 if (frame_avail)
2463                     frames_in++;
2464
2465                 if(stream_cnt == 1)
2466                     fprintf(stderr,
2467                             "\rPass %d/%d frame %4d/%-4d %7"PRId64"B \033[K",
2468                             pass + 1, global.passes, frames_in,
2469                             streams->frames_out, (int64_t)streams->nbytes);
2470                 else
2471                     fprintf(stderr,
2472                             "\rPass %d/%d frame %4d %7lu %s (%.2f fps)\033[K",
2473                             pass + 1, global.passes, frames_in,
2474                             cx_time > 9999999 ? cx_time / 1000 : cx_time,
2475                             cx_time > 9999999 ? "ms" : "us",
2476                             usec_to_fps(cx_time, frames_in));
2477
2478             }
2479             else
2480                 frame_avail = 0;
2481
2482             vpx_usec_timer_start(&timer);
2483             FOREACH_STREAM(encode_frame(stream, &global,
2484                                         frame_avail ? &raw : NULL,
2485                                         frames_in));
2486             vpx_usec_timer_mark(&timer);
2487             cx_time += vpx_usec_timer_elapsed(&timer);
2488
2489             FOREACH_STREAM(update_quantizer_histogram(stream));
2490
2491             got_data = 0;
2492             FOREACH_STREAM(get_cx_data(stream, &global, &got_data));
2493
2494             fflush(stdout);
2495         }
2496
2497         if(stream_cnt > 1)
2498             fprintf(stderr, "\n");
2499
2500         FOREACH_STREAM(fprintf(
2501             stderr,
2502             "\rPass %d/%d frame %4d/%-4d %7"PRId64"B %7lub/f %7"PRId64"b/s"
2503             " %7"PRId64" %s (%.2f fps)\033[K\n", pass + 1,
2504             global.passes, frames_in, stream->frames_out, (int64_t)stream->nbytes,
2505             frames_in ? (unsigned long)(stream->nbytes * 8 / frames_in) : 0,
2506             frames_in ? (int64_t)stream->nbytes * 8
2507                         * (int64_t)global.framerate.num / global.framerate.den
2508                         / frames_in
2509                       : 0,
2510             stream->cx_time > 9999999 ? stream->cx_time / 1000 : stream->cx_time,
2511             stream->cx_time > 9999999 ? "ms" : "us",
2512             usec_to_fps(stream->cx_time, frames_in));
2513         );
2514
2515         if (global.show_psnr)
2516             FOREACH_STREAM(show_psnr(stream));
2517
2518         FOREACH_STREAM(vpx_codec_destroy(&stream->encoder));
2519
2520         close_input_file(&input);
2521
2522         FOREACH_STREAM(close_output_file(stream, global.codec->fourcc));
2523
2524         FOREACH_STREAM(stats_close(&stream->stats, global.passes-1));
2525
2526         if (global.pass)
2527             break;
2528     }
2529
2530     if (global.show_q_hist_buckets)
2531         FOREACH_STREAM(show_q_histogram(stream->counts,
2532                                         global.show_q_hist_buckets));
2533
2534     if (global.show_rate_hist_buckets)
2535         FOREACH_STREAM(show_rate_histogram(&stream->rate_hist,
2536                                            &stream->config.cfg,
2537                                            global.show_rate_hist_buckets));
2538     FOREACH_STREAM(destroy_rate_histogram(&stream->rate_hist));
2539
2540     vpx_img_free(&raw);
2541     free(argv);
2542     free(streams);
2543     return EXIT_SUCCESS;
2544 }