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