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