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