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