00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015 #if defined(_WIN32) || !CONFIG_OS_SUPPORT
00016 #define USE_POSIX_MMAP 0
00017 #else
00018 #define USE_POSIX_MMAP 1
00019 #endif
00020
00021 #include <stdio.h>
00022 #include <stdlib.h>
00023 #include <stdarg.h>
00024 #include <string.h>
00025 #include <limits.h>
00026 #include <assert.h>
00027 #include "vpx/vpx_encoder.h"
00028 #if USE_POSIX_MMAP
00029 #include <sys/types.h>
00030 #include <sys/stat.h>
00031 #include <sys/mman.h>
00032 #include <fcntl.h>
00033 #include <unistd.h>
00034 #endif
00035 #include "vpx/vp8cx.h"
00036 #include "vpx_ports/mem_ops.h"
00037 #include "vpx_ports/vpx_timer.h"
00038 #include "tools_common.h"
00039 #include "y4minput.h"
00040 #include "libmkv/EbmlWriter.h"
00041 #include "libmkv/EbmlIDs.h"
00042
00043
00044 #if defined(_MSC_VER)
00045
00046 typedef __int64 off_t;
00047 #define fseeko _fseeki64
00048 #define ftello _ftelli64
00049 #elif defined(_WIN32)
00050
00051
00052 #define fseeko fseeko64
00053 #define ftello ftello64
00054 #define off_t off64_t
00055 #endif
00056
00057 #if defined(_MSC_VER)
00058 #define LITERALU64(n) n
00059 #else
00060 #define LITERALU64(n) n##LLU
00061 #endif
00062
00063
00064
00065 #if !CONFIG_OS_SUPPORT
00066 typedef long off_t;
00067 #define fseeko fseek
00068 #define ftello ftell
00069 #endif
00070
00071 static const char *exec_name;
00072
00073 static const struct codec_item
00074 {
00075 char const *name;
00076 const vpx_codec_iface_t *iface;
00077 unsigned int fourcc;
00078 } codecs[] =
00079 {
00080 #if CONFIG_VP8_ENCODER
00081 {"vp8", &vpx_codec_vp8_cx_algo, 0x30385056},
00082 #endif
00083 };
00084
00085 static void usage_exit();
00086
00087 void die(const char *fmt, ...)
00088 {
00089 va_list ap;
00090 va_start(ap, fmt);
00091 vfprintf(stderr, fmt, ap);
00092 fprintf(stderr, "\n");
00093 usage_exit();
00094 }
00095
00096 static void ctx_exit_on_error(vpx_codec_ctx_t *ctx, const char *s)
00097 {
00098 if (ctx->err)
00099 {
00100 const char *detail = vpx_codec_error_detail(ctx);
00101
00102 fprintf(stderr, "%s: %s\n", s, vpx_codec_error(ctx));
00103
00104 if (detail)
00105 fprintf(stderr, " %s\n", detail);
00106
00107 exit(EXIT_FAILURE);
00108 }
00109 }
00110
00111
00112
00113
00114 typedef struct
00115 {
00116 vpx_fixed_buf_t buf;
00117 int pass;
00118 FILE *file;
00119 char *buf_ptr;
00120 size_t buf_alloc_sz;
00121 } stats_io_t;
00122
00123 int stats_open_file(stats_io_t *stats, const char *fpf, int pass)
00124 {
00125 int res;
00126
00127 stats->pass = pass;
00128
00129 if (pass == 0)
00130 {
00131 stats->file = fopen(fpf, "wb");
00132 stats->buf.sz = 0;
00133 stats->buf.buf = NULL,
00134 res = (stats->file != NULL);
00135 }
00136 else
00137 {
00138 #if 0
00139 #elif USE_POSIX_MMAP
00140 struct stat stat_buf;
00141 int fd;
00142
00143 fd = open(fpf, O_RDONLY);
00144 stats->file = fdopen(fd, "rb");
00145 fstat(fd, &stat_buf);
00146 stats->buf.sz = stat_buf.st_size;
00147 stats->buf.buf = mmap(NULL, stats->buf.sz, PROT_READ, MAP_PRIVATE,
00148 fd, 0);
00149 res = (stats->buf.buf != NULL);
00150 #else
00151 size_t nbytes;
00152
00153 stats->file = fopen(fpf, "rb");
00154
00155 if (fseek(stats->file, 0, SEEK_END))
00156 {
00157 fprintf(stderr, "First-pass stats file must be seekable!\n");
00158 exit(EXIT_FAILURE);
00159 }
00160
00161 stats->buf.sz = stats->buf_alloc_sz = ftell(stats->file);
00162 rewind(stats->file);
00163
00164 stats->buf.buf = malloc(stats->buf_alloc_sz);
00165
00166 if (!stats->buf.buf)
00167 {
00168 fprintf(stderr, "Failed to allocate first-pass stats buffer (%lu bytes)\n",
00169 (unsigned long)stats->buf_alloc_sz);
00170 exit(EXIT_FAILURE);
00171 }
00172
00173 nbytes = fread(stats->buf.buf, 1, stats->buf.sz, stats->file);
00174 res = (nbytes == stats->buf.sz);
00175 #endif
00176 }
00177
00178 return res;
00179 }
00180
00181 int stats_open_mem(stats_io_t *stats, int pass)
00182 {
00183 int res;
00184 stats->pass = pass;
00185
00186 if (!pass)
00187 {
00188 stats->buf.sz = 0;
00189 stats->buf_alloc_sz = 64 * 1024;
00190 stats->buf.buf = malloc(stats->buf_alloc_sz);
00191 }
00192
00193 stats->buf_ptr = stats->buf.buf;
00194 res = (stats->buf.buf != NULL);
00195 return res;
00196 }
00197
00198
00199 void stats_close(stats_io_t *stats, int last_pass)
00200 {
00201 if (stats->file)
00202 {
00203 if (stats->pass == last_pass)
00204 {
00205 #if 0
00206 #elif USE_POSIX_MMAP
00207 munmap(stats->buf.buf, stats->buf.sz);
00208 #else
00209 free(stats->buf.buf);
00210 #endif
00211 }
00212
00213 fclose(stats->file);
00214 stats->file = NULL;
00215 }
00216 else
00217 {
00218 if (stats->pass == last_pass)
00219 free(stats->buf.buf);
00220 }
00221 }
00222
00223 void stats_write(stats_io_t *stats, const void *pkt, size_t len)
00224 {
00225 if (stats->file)
00226 {
00227 if(fwrite(pkt, 1, len, stats->file));
00228 }
00229 else
00230 {
00231 if (stats->buf.sz + len > stats->buf_alloc_sz)
00232 {
00233 size_t new_sz = stats->buf_alloc_sz + 64 * 1024;
00234 char *new_ptr = realloc(stats->buf.buf, new_sz);
00235
00236 if (new_ptr)
00237 {
00238 stats->buf_ptr = new_ptr + (stats->buf_ptr - (char *)stats->buf.buf);
00239 stats->buf.buf = new_ptr;
00240 stats->buf_alloc_sz = new_sz;
00241 }
00242 else
00243 {
00244 fprintf(stderr,
00245 "\nFailed to realloc firstpass stats buffer.\n");
00246 exit(EXIT_FAILURE);
00247 }
00248 }
00249
00250 memcpy(stats->buf_ptr, pkt, len);
00251 stats->buf.sz += len;
00252 stats->buf_ptr += len;
00253 }
00254 }
00255
00256 vpx_fixed_buf_t stats_get(stats_io_t *stats)
00257 {
00258 return stats->buf;
00259 }
00260
00261
00262 typedef enum stereo_format
00263 {
00264 STEREO_FORMAT_MONO = 0,
00265 STEREO_FORMAT_LEFT_RIGHT = 1,
00266 STEREO_FORMAT_BOTTOM_TOP = 2,
00267 STEREO_FORMAT_TOP_BOTTOM = 3,
00268 STEREO_FORMAT_RIGHT_LEFT = 11
00269 } stereo_format_t;
00270
00271 enum video_file_type
00272 {
00273 FILE_TYPE_RAW,
00274 FILE_TYPE_IVF,
00275 FILE_TYPE_Y4M
00276 };
00277
00278 struct detect_buffer {
00279 char buf[4];
00280 size_t buf_read;
00281 size_t position;
00282 };
00283
00284
00285 #define IVF_FRAME_HDR_SZ (4+8)
00286 static int read_frame(FILE *f, vpx_image_t *img, unsigned int file_type,
00287 y4m_input *y4m, struct detect_buffer *detect)
00288 {
00289 int plane = 0;
00290 int shortread = 0;
00291
00292 if (file_type == FILE_TYPE_Y4M)
00293 {
00294 if (y4m_input_fetch_frame(y4m, f, img) < 1)
00295 return 0;
00296 }
00297 else
00298 {
00299 if (file_type == FILE_TYPE_IVF)
00300 {
00301 char junk[IVF_FRAME_HDR_SZ];
00302
00303
00304
00305
00306
00307 if(fread(junk, 1, IVF_FRAME_HDR_SZ, f));
00308 }
00309
00310 for (plane = 0; plane < 3; plane++)
00311 {
00312 unsigned char *ptr;
00313 int w = (plane ? (1 + img->d_w) / 2 : img->d_w);
00314 int h = (plane ? (1 + img->d_h) / 2 : img->d_h);
00315 int r;
00316
00317
00318
00319
00320
00321 switch (plane)
00322 {
00323 case 1:
00324 ptr = img->planes[img->fmt==VPX_IMG_FMT_YV12? VPX_PLANE_V : VPX_PLANE_U];
00325 break;
00326 case 2:
00327 ptr = img->planes[img->fmt==VPX_IMG_FMT_YV12?VPX_PLANE_U : VPX_PLANE_V];
00328 break;
00329 default:
00330 ptr = img->planes[plane];
00331 }
00332
00333 for (r = 0; r < h; r++)
00334 {
00335 size_t needed = w;
00336 size_t buf_position = 0;
00337 const size_t left = detect->buf_read - detect->position;
00338 if (left > 0)
00339 {
00340 const size_t more = (left < needed) ? left : needed;
00341 memcpy(ptr, detect->buf + detect->position, more);
00342 buf_position = more;
00343 needed -= more;
00344 detect->position += more;
00345 }
00346 if (needed > 0)
00347 {
00348 shortread |= (fread(ptr + buf_position, 1, needed, f) < needed);
00349 }
00350
00351 ptr += img->stride[plane];
00352 }
00353 }
00354 }
00355
00356 return !shortread;
00357 }
00358
00359
00360 unsigned int file_is_y4m(FILE *infile,
00361 y4m_input *y4m,
00362 char detect[4])
00363 {
00364 if(memcmp(detect, "YUV4", 4) == 0)
00365 {
00366 return 1;
00367 }
00368 return 0;
00369 }
00370
00371 #define IVF_FILE_HDR_SZ (32)
00372 unsigned int file_is_ivf(FILE *infile,
00373 unsigned int *fourcc,
00374 unsigned int *width,
00375 unsigned int *height,
00376 struct detect_buffer *detect)
00377 {
00378 char raw_hdr[IVF_FILE_HDR_SZ];
00379 int is_ivf = 0;
00380
00381 if(memcmp(detect->buf, "DKIF", 4) != 0)
00382 return 0;
00383
00384
00385
00386
00387 if (fread(raw_hdr + 4, 1, IVF_FILE_HDR_SZ - 4, infile)
00388 == IVF_FILE_HDR_SZ - 4)
00389 {
00390 {
00391 is_ivf = 1;
00392
00393 if (mem_get_le16(raw_hdr + 4) != 0)
00394 fprintf(stderr, "Error: Unrecognized IVF version! This file may not"
00395 " decode properly.");
00396
00397 *fourcc = mem_get_le32(raw_hdr + 8);
00398 }
00399 }
00400
00401 if (is_ivf)
00402 {
00403 *width = mem_get_le16(raw_hdr + 12);
00404 *height = mem_get_le16(raw_hdr + 14);
00405 detect->position = 4;
00406 }
00407
00408 return is_ivf;
00409 }
00410
00411
00412 static void write_ivf_file_header(FILE *outfile,
00413 const vpx_codec_enc_cfg_t *cfg,
00414 unsigned int fourcc,
00415 int frame_cnt)
00416 {
00417 char header[32];
00418
00419 if (cfg->g_pass != VPX_RC_ONE_PASS && cfg->g_pass != VPX_RC_LAST_PASS)
00420 return;
00421
00422 header[0] = 'D';
00423 header[1] = 'K';
00424 header[2] = 'I';
00425 header[3] = 'F';
00426 mem_put_le16(header + 4, 0);
00427 mem_put_le16(header + 6, 32);
00428 mem_put_le32(header + 8, fourcc);
00429 mem_put_le16(header + 12, cfg->g_w);
00430 mem_put_le16(header + 14, cfg->g_h);
00431 mem_put_le32(header + 16, cfg->g_timebase.den);
00432 mem_put_le32(header + 20, cfg->g_timebase.num);
00433 mem_put_le32(header + 24, frame_cnt);
00434 mem_put_le32(header + 28, 0);
00435
00436 if(fwrite(header, 1, 32, outfile));
00437 }
00438
00439
00440 static void write_ivf_frame_header(FILE *outfile,
00441 const vpx_codec_cx_pkt_t *pkt)
00442 {
00443 char header[12];
00444 vpx_codec_pts_t pts;
00445
00446 if (pkt->kind != VPX_CODEC_CX_FRAME_PKT)
00447 return;
00448
00449 pts = pkt->data.frame.pts;
00450 mem_put_le32(header, pkt->data.frame.sz);
00451 mem_put_le32(header + 4, pts & 0xFFFFFFFF);
00452 mem_put_le32(header + 8, pts >> 32);
00453
00454 if(fwrite(header, 1, 12, outfile));
00455 }
00456
00457
00458 typedef off_t EbmlLoc;
00459
00460
00461 struct cue_entry
00462 {
00463 unsigned int time;
00464 uint64_t loc;
00465 };
00466
00467
00468 struct EbmlGlobal
00469 {
00470 int debug;
00471
00472 FILE *stream;
00473 int64_t last_pts_ms;
00474 vpx_rational_t framerate;
00475
00476
00477 off_t position_reference;
00478 off_t seek_info_pos;
00479 off_t segment_info_pos;
00480 off_t track_pos;
00481 off_t cue_pos;
00482 off_t cluster_pos;
00483
00484
00485 off_t track_id_pos;
00486
00487
00488 EbmlLoc startSegment;
00489 EbmlLoc startCluster;
00490
00491 uint32_t cluster_timecode;
00492 int cluster_open;
00493
00494 struct cue_entry *cue_list;
00495 unsigned int cues;
00496
00497 };
00498
00499
00500 void Ebml_Write(EbmlGlobal *glob, const void *buffer_in, unsigned long len)
00501 {
00502 if(fwrite(buffer_in, 1, len, glob->stream));
00503 }
00504
00505 #define WRITE_BUFFER(s) \
00506 for(i = len-1; i>=0; i--)\
00507 { \
00508 x = *(const s *)buffer_in >> (i * CHAR_BIT); \
00509 Ebml_Write(glob, &x, 1); \
00510 }
00511 void Ebml_Serialize(EbmlGlobal *glob, const void *buffer_in, int buffer_size, unsigned long len)
00512 {
00513 char x;
00514 int i;
00515
00516
00517
00518
00519
00520
00521
00522 switch (buffer_size)
00523 {
00524 case 1:
00525 WRITE_BUFFER(int8_t)
00526 break;
00527 case 2:
00528 WRITE_BUFFER(int16_t)
00529 break;
00530 case 4:
00531 WRITE_BUFFER(int32_t)
00532 break;
00533 case 8:
00534 WRITE_BUFFER(int64_t)
00535 break;
00536 default:
00537 break;
00538 }
00539 }
00540 #undef WRITE_BUFFER
00541
00542
00543
00544
00545 static void Ebml_SerializeUnsigned32(EbmlGlobal *glob, unsigned long class_id, uint64_t ui)
00546 {
00547 unsigned char sizeSerialized = 4 | 0x80;
00548 Ebml_WriteID(glob, class_id);
00549 Ebml_Serialize(glob, &sizeSerialized, sizeof(sizeSerialized), 1);
00550 Ebml_Serialize(glob, &ui, sizeof(ui), 4);
00551 }
00552
00553
00554 static void
00555 Ebml_StartSubElement(EbmlGlobal *glob, EbmlLoc *ebmlLoc,
00556 unsigned long class_id)
00557 {
00558
00559
00560 uint64_t unknownLen = LITERALU64(0x01FFFFFFFFFFFFFF);
00561
00562 Ebml_WriteID(glob, class_id);
00563 *ebmlLoc = ftello(glob->stream);
00564 Ebml_Serialize(glob, &unknownLen, sizeof(unknownLen), 8);
00565 }
00566
00567 static void
00568 Ebml_EndSubElement(EbmlGlobal *glob, EbmlLoc *ebmlLoc)
00569 {
00570 off_t pos;
00571 uint64_t size;
00572
00573
00574 pos = ftello(glob->stream);
00575
00576
00577 size = pos - *ebmlLoc - 8;
00578 size |= LITERALU64(0x0100000000000000);
00579
00580
00581 fseeko(glob->stream, *ebmlLoc, SEEK_SET);
00582 Ebml_Serialize(glob, &size, sizeof(size), 8);
00583
00584
00585 fseeko(glob->stream, pos, SEEK_SET);
00586 }
00587
00588
00589 static void
00590 write_webm_seek_element(EbmlGlobal *ebml, unsigned long id, off_t pos)
00591 {
00592 uint64_t offset = pos - ebml->position_reference;
00593 EbmlLoc start;
00594 Ebml_StartSubElement(ebml, &start, Seek);
00595 Ebml_SerializeBinary(ebml, SeekID, id);
00596 Ebml_SerializeUnsigned64(ebml, SeekPosition, offset);
00597 Ebml_EndSubElement(ebml, &start);
00598 }
00599
00600
00601 static void
00602 write_webm_seek_info(EbmlGlobal *ebml)
00603 {
00604
00605 off_t pos;
00606
00607
00608 pos = ftello(ebml->stream);
00609
00610 if(ebml->seek_info_pos)
00611 fseeko(ebml->stream, ebml->seek_info_pos, SEEK_SET);
00612 else
00613 ebml->seek_info_pos = pos;
00614
00615 {
00616 EbmlLoc start;
00617
00618 Ebml_StartSubElement(ebml, &start, SeekHead);
00619 write_webm_seek_element(ebml, Tracks, ebml->track_pos);
00620 write_webm_seek_element(ebml, Cues, ebml->cue_pos);
00621 write_webm_seek_element(ebml, Info, ebml->segment_info_pos);
00622 Ebml_EndSubElement(ebml, &start);
00623 }
00624 {
00625
00626 EbmlLoc startInfo;
00627 uint64_t frame_time;
00628 char version_string[64];
00629
00630
00631 if(ebml->debug)
00632 strcpy(version_string, "vpxenc");
00633 else
00634 {
00635 strcpy(version_string, "vpxenc ");
00636 strncat(version_string,
00637 vpx_codec_version_str(),
00638 sizeof(version_string) - 1 - strlen(version_string));
00639 }
00640
00641 frame_time = (uint64_t)1000 * ebml->framerate.den
00642 / ebml->framerate.num;
00643 ebml->segment_info_pos = ftello(ebml->stream);
00644 Ebml_StartSubElement(ebml, &startInfo, Info);
00645 Ebml_SerializeUnsigned(ebml, TimecodeScale, 1000000);
00646 Ebml_SerializeFloat(ebml, Segment_Duration,
00647 ebml->last_pts_ms + frame_time);
00648 Ebml_SerializeString(ebml, 0x4D80, version_string);
00649 Ebml_SerializeString(ebml, 0x5741, version_string);
00650 Ebml_EndSubElement(ebml, &startInfo);
00651 }
00652 }
00653
00654
00655 static void
00656 write_webm_file_header(EbmlGlobal *glob,
00657 const vpx_codec_enc_cfg_t *cfg,
00658 const struct vpx_rational *fps,
00659 stereo_format_t stereo_fmt)
00660 {
00661 {
00662 EbmlLoc start;
00663 Ebml_StartSubElement(glob, &start, EBML);
00664 Ebml_SerializeUnsigned(glob, EBMLVersion, 1);
00665 Ebml_SerializeUnsigned(glob, EBMLReadVersion, 1);
00666 Ebml_SerializeUnsigned(glob, EBMLMaxIDLength, 4);
00667 Ebml_SerializeUnsigned(glob, EBMLMaxSizeLength, 8);
00668 Ebml_SerializeString(glob, DocType, "webm");
00669 Ebml_SerializeUnsigned(glob, DocTypeVersion, 2);
00670 Ebml_SerializeUnsigned(glob, DocTypeReadVersion, 2);
00671 Ebml_EndSubElement(glob, &start);
00672 }
00673 {
00674 Ebml_StartSubElement(glob, &glob->startSegment, Segment);
00675 glob->position_reference = ftello(glob->stream);
00676 glob->framerate = *fps;
00677 write_webm_seek_info(glob);
00678
00679 {
00680 EbmlLoc trackStart;
00681 glob->track_pos = ftello(glob->stream);
00682 Ebml_StartSubElement(glob, &trackStart, Tracks);
00683 {
00684 unsigned int trackNumber = 1;
00685 uint64_t trackID = 0;
00686
00687 EbmlLoc start;
00688 Ebml_StartSubElement(glob, &start, TrackEntry);
00689 Ebml_SerializeUnsigned(glob, TrackNumber, trackNumber);
00690 glob->track_id_pos = ftello(glob->stream);
00691 Ebml_SerializeUnsigned32(glob, TrackUID, trackID);
00692 Ebml_SerializeUnsigned(glob, TrackType, 1);
00693 Ebml_SerializeString(glob, CodecID, "V_VP8");
00694 {
00695 unsigned int pixelWidth = cfg->g_w;
00696 unsigned int pixelHeight = cfg->g_h;
00697 float frameRate = (float)fps->num/(float)fps->den;
00698
00699 EbmlLoc videoStart;
00700 Ebml_StartSubElement(glob, &videoStart, Video);
00701 Ebml_SerializeUnsigned(glob, PixelWidth, pixelWidth);
00702 Ebml_SerializeUnsigned(glob, PixelHeight, pixelHeight);
00703 Ebml_SerializeUnsigned(glob, StereoMode, stereo_fmt);
00704 Ebml_SerializeFloat(glob, FrameRate, frameRate);
00705 Ebml_EndSubElement(glob, &videoStart);
00706 }
00707 Ebml_EndSubElement(glob, &start);
00708 }
00709 Ebml_EndSubElement(glob, &trackStart);
00710 }
00711
00712 }
00713 }
00714
00715
00716 static void
00717 write_webm_block(EbmlGlobal *glob,
00718 const vpx_codec_enc_cfg_t *cfg,
00719 const vpx_codec_cx_pkt_t *pkt)
00720 {
00721 unsigned long block_length;
00722 unsigned char track_number;
00723 unsigned short block_timecode = 0;
00724 unsigned char flags;
00725 int64_t pts_ms;
00726 int start_cluster = 0, is_keyframe;
00727
00728
00729 pts_ms = pkt->data.frame.pts * 1000
00730 * (uint64_t)cfg->g_timebase.num / (uint64_t)cfg->g_timebase.den;
00731 if(pts_ms <= glob->last_pts_ms)
00732 pts_ms = glob->last_pts_ms + 1;
00733 glob->last_pts_ms = pts_ms;
00734
00735
00736 if(pts_ms - glob->cluster_timecode > SHRT_MAX)
00737 start_cluster = 1;
00738 else
00739 block_timecode = pts_ms - glob->cluster_timecode;
00740
00741 is_keyframe = (pkt->data.frame.flags & VPX_FRAME_IS_KEY);
00742 if(start_cluster || is_keyframe)
00743 {
00744 if(glob->cluster_open)
00745 Ebml_EndSubElement(glob, &glob->startCluster);
00746
00747
00748 block_timecode = 0;
00749 glob->cluster_open = 1;
00750 glob->cluster_timecode = pts_ms;
00751 glob->cluster_pos = ftello(glob->stream);
00752 Ebml_StartSubElement(glob, &glob->startCluster, Cluster);
00753 Ebml_SerializeUnsigned(glob, Timecode, glob->cluster_timecode);
00754
00755
00756 if(is_keyframe)
00757 {
00758 struct cue_entry *cue, *new_cue_list;
00759
00760 new_cue_list = realloc(glob->cue_list,
00761 (glob->cues+1) * sizeof(struct cue_entry));
00762 if(new_cue_list)
00763 glob->cue_list = new_cue_list;
00764 else
00765 {
00766 fprintf(stderr, "\nFailed to realloc cue list.\n");
00767 exit(EXIT_FAILURE);
00768 }
00769
00770 cue = &glob->cue_list[glob->cues];
00771 cue->time = glob->cluster_timecode;
00772 cue->loc = glob->cluster_pos;
00773 glob->cues++;
00774 }
00775 }
00776
00777
00778 Ebml_WriteID(glob, SimpleBlock);
00779
00780 block_length = pkt->data.frame.sz + 4;
00781 block_length |= 0x10000000;
00782 Ebml_Serialize(glob, &block_length, sizeof(block_length), 4);
00783
00784 track_number = 1;
00785 track_number |= 0x80;
00786 Ebml_Write(glob, &track_number, 1);
00787
00788 Ebml_Serialize(glob, &block_timecode, sizeof(block_timecode), 2);
00789
00790 flags = 0;
00791 if(is_keyframe)
00792 flags |= 0x80;
00793 if(pkt->data.frame.flags & VPX_FRAME_IS_INVISIBLE)
00794 flags |= 0x08;
00795 Ebml_Write(glob, &flags, 1);
00796
00797 Ebml_Write(glob, pkt->data.frame.buf, pkt->data.frame.sz);
00798 }
00799
00800
00801 static void
00802 write_webm_file_footer(EbmlGlobal *glob, long hash)
00803 {
00804
00805 if(glob->cluster_open)
00806 Ebml_EndSubElement(glob, &glob->startCluster);
00807
00808 {
00809 EbmlLoc start;
00810 unsigned int i;
00811
00812 glob->cue_pos = ftello(glob->stream);
00813 Ebml_StartSubElement(glob, &start, Cues);
00814 for(i=0; i<glob->cues; i++)
00815 {
00816 struct cue_entry *cue = &glob->cue_list[i];
00817 EbmlLoc start;
00818
00819 Ebml_StartSubElement(glob, &start, CuePoint);
00820 {
00821 EbmlLoc start;
00822
00823 Ebml_SerializeUnsigned(glob, CueTime, cue->time);
00824
00825 Ebml_StartSubElement(glob, &start, CueTrackPositions);
00826 Ebml_SerializeUnsigned(glob, CueTrack, 1);
00827 Ebml_SerializeUnsigned64(glob, CueClusterPosition,
00828 cue->loc - glob->position_reference);
00829
00830 Ebml_EndSubElement(glob, &start);
00831 }
00832 Ebml_EndSubElement(glob, &start);
00833 }
00834 Ebml_EndSubElement(glob, &start);
00835 }
00836
00837 Ebml_EndSubElement(glob, &glob->startSegment);
00838
00839
00840 write_webm_seek_info(glob);
00841
00842
00843 fseeko(glob->stream, glob->track_id_pos, SEEK_SET);
00844 Ebml_SerializeUnsigned32(glob, TrackUID, glob->debug ? 0xDEADBEEF : hash);
00845
00846 fseeko(glob->stream, 0, SEEK_END);
00847 }
00848
00849
00850
00851
00852
00853 static unsigned int murmur ( const void * key, int len, unsigned int seed )
00854 {
00855 const unsigned int m = 0x5bd1e995;
00856 const int r = 24;
00857
00858 unsigned int h = seed ^ len;
00859
00860 const unsigned char * data = (const unsigned char *)key;
00861
00862 while(len >= 4)
00863 {
00864 unsigned int k;
00865
00866 k = data[0];
00867 k |= data[1] << 8;
00868 k |= data[2] << 16;
00869 k |= data[3] << 24;
00870
00871 k *= m;
00872 k ^= k >> r;
00873 k *= m;
00874
00875 h *= m;
00876 h ^= k;
00877
00878 data += 4;
00879 len -= 4;
00880 }
00881
00882 switch(len)
00883 {
00884 case 3: h ^= data[2] << 16;
00885 case 2: h ^= data[1] << 8;
00886 case 1: h ^= data[0];
00887 h *= m;
00888 };
00889
00890 h ^= h >> 13;
00891 h *= m;
00892 h ^= h >> 15;
00893
00894 return h;
00895 }
00896
00897 #include "math.h"
00898
00899 static double vp8_mse2psnr(double Samples, double Peak, double Mse)
00900 {
00901 double psnr;
00902
00903 if ((double)Mse > 0.0)
00904 psnr = 10.0 * log10(Peak * Peak * Samples / Mse);
00905 else
00906 psnr = 60;
00907
00908 if (psnr > 60)
00909 psnr = 60;
00910
00911 return psnr;
00912 }
00913
00914
00915 #include "args.h"
00916
00917 static const arg_def_t debugmode = ARG_DEF("D", "debug", 0,
00918 "Debug mode (makes output deterministic)");
00919 static const arg_def_t outputfile = ARG_DEF("o", "output", 1,
00920 "Output filename");
00921 static const arg_def_t use_yv12 = ARG_DEF(NULL, "yv12", 0,
00922 "Input file is YV12 ");
00923 static const arg_def_t use_i420 = ARG_DEF(NULL, "i420", 0,
00924 "Input file is I420 (default)");
00925 static const arg_def_t codecarg = ARG_DEF(NULL, "codec", 1,
00926 "Codec to use");
00927 static const arg_def_t passes = ARG_DEF("p", "passes", 1,
00928 "Number of passes (1/2)");
00929 static const arg_def_t pass_arg = ARG_DEF(NULL, "pass", 1,
00930 "Pass to execute (1/2)");
00931 static const arg_def_t fpf_name = ARG_DEF(NULL, "fpf", 1,
00932 "First pass statistics file name");
00933 static const arg_def_t limit = ARG_DEF(NULL, "limit", 1,
00934 "Stop encoding after n input frames");
00935 static const arg_def_t deadline = ARG_DEF("d", "deadline", 1,
00936 "Deadline per frame (usec)");
00937 static const arg_def_t best_dl = ARG_DEF(NULL, "best", 0,
00938 "Use Best Quality Deadline");
00939 static const arg_def_t good_dl = ARG_DEF(NULL, "good", 0,
00940 "Use Good Quality Deadline");
00941 static const arg_def_t rt_dl = ARG_DEF(NULL, "rt", 0,
00942 "Use Realtime Quality Deadline");
00943 static const arg_def_t verbosearg = ARG_DEF("v", "verbose", 0,
00944 "Show encoder parameters");
00945 static const arg_def_t psnrarg = ARG_DEF(NULL, "psnr", 0,
00946 "Show PSNR in status line");
00947 static const arg_def_t framerate = ARG_DEF(NULL, "fps", 1,
00948 "Stream frame rate (rate/scale)");
00949 static const arg_def_t use_ivf = ARG_DEF(NULL, "ivf", 0,
00950 "Output IVF (default is WebM)");
00951 static const arg_def_t q_hist_n = ARG_DEF(NULL, "q-hist", 1,
00952 "Show quantizer histogram (n-buckets)");
00953 static const arg_def_t rate_hist_n = ARG_DEF(NULL, "rate-hist", 1,
00954 "Show rate histogram (n-buckets)");
00955 static const arg_def_t *main_args[] =
00956 {
00957 &debugmode,
00958 &outputfile, &codecarg, &passes, &pass_arg, &fpf_name, &limit, &deadline,
00959 &best_dl, &good_dl, &rt_dl,
00960 &verbosearg, &psnrarg, &use_ivf, &q_hist_n, &rate_hist_n,
00961 NULL
00962 };
00963
00964 static const arg_def_t usage = ARG_DEF("u", "usage", 1,
00965 "Usage profile number to use");
00966 static const arg_def_t threads = ARG_DEF("t", "threads", 1,
00967 "Max number of threads to use");
00968 static const arg_def_t profile = ARG_DEF(NULL, "profile", 1,
00969 "Bitstream profile number to use");
00970 static const arg_def_t width = ARG_DEF("w", "width", 1,
00971 "Frame width");
00972 static const arg_def_t height = ARG_DEF("h", "height", 1,
00973 "Frame height");
00974 static const struct arg_enum_list stereo_mode_enum[] = {
00975 {"mono" , STEREO_FORMAT_MONO},
00976 {"left-right", STEREO_FORMAT_LEFT_RIGHT},
00977 {"bottom-top", STEREO_FORMAT_BOTTOM_TOP},
00978 {"top-bottom", STEREO_FORMAT_TOP_BOTTOM},
00979 {"right-left", STEREO_FORMAT_RIGHT_LEFT},
00980 {NULL, 0}
00981 };
00982 static const arg_def_t stereo_mode = ARG_DEF_ENUM(NULL, "stereo-mode", 1,
00983 "Stereo 3D video format", stereo_mode_enum);
00984 static const arg_def_t timebase = ARG_DEF(NULL, "timebase", 1,
00985 "Output timestamp precision (fractional seconds)");
00986 static const arg_def_t error_resilient = ARG_DEF(NULL, "error-resilient", 1,
00987 "Enable error resiliency features");
00988 static const arg_def_t lag_in_frames = ARG_DEF(NULL, "lag-in-frames", 1,
00989 "Max number of frames to lag");
00990
00991 static const arg_def_t *global_args[] =
00992 {
00993 &use_yv12, &use_i420, &usage, &threads, &profile,
00994 &width, &height, &stereo_mode, &timebase, &framerate, &error_resilient,
00995 &lag_in_frames, NULL
00996 };
00997
00998 static const arg_def_t dropframe_thresh = ARG_DEF(NULL, "drop-frame", 1,
00999 "Temporal resampling threshold (buf %)");
01000 static const arg_def_t resize_allowed = ARG_DEF(NULL, "resize-allowed", 1,
01001 "Spatial resampling enabled (bool)");
01002 static const arg_def_t resize_up_thresh = ARG_DEF(NULL, "resize-up", 1,
01003 "Upscale threshold (buf %)");
01004 static const arg_def_t resize_down_thresh = ARG_DEF(NULL, "resize-down", 1,
01005 "Downscale threshold (buf %)");
01006 static const struct arg_enum_list end_usage_enum[] = {
01007 {"vbr", VPX_VBR},
01008 {"cbr", VPX_CBR},
01009 {"cq", VPX_CQ},
01010 {NULL, 0}
01011 };
01012 static const arg_def_t end_usage = ARG_DEF_ENUM(NULL, "end-usage", 1,
01013 "Rate control mode", end_usage_enum);
01014 static const arg_def_t target_bitrate = ARG_DEF(NULL, "target-bitrate", 1,
01015 "Bitrate (kbps)");
01016 static const arg_def_t min_quantizer = ARG_DEF(NULL, "min-q", 1,
01017 "Minimum (best) quantizer");
01018 static const arg_def_t max_quantizer = ARG_DEF(NULL, "max-q", 1,
01019 "Maximum (worst) quantizer");
01020 static const arg_def_t undershoot_pct = ARG_DEF(NULL, "undershoot-pct", 1,
01021 "Datarate undershoot (min) target (%)");
01022 static const arg_def_t overshoot_pct = ARG_DEF(NULL, "overshoot-pct", 1,
01023 "Datarate overshoot (max) target (%)");
01024 static const arg_def_t buf_sz = ARG_DEF(NULL, "buf-sz", 1,
01025 "Client buffer size (ms)");
01026 static const arg_def_t buf_initial_sz = ARG_DEF(NULL, "buf-initial-sz", 1,
01027 "Client initial buffer size (ms)");
01028 static const arg_def_t buf_optimal_sz = ARG_DEF(NULL, "buf-optimal-sz", 1,
01029 "Client optimal buffer size (ms)");
01030 static const arg_def_t *rc_args[] =
01031 {
01032 &dropframe_thresh, &resize_allowed, &resize_up_thresh, &resize_down_thresh,
01033 &end_usage, &target_bitrate, &min_quantizer, &max_quantizer,
01034 &undershoot_pct, &overshoot_pct, &buf_sz, &buf_initial_sz, &buf_optimal_sz,
01035 NULL
01036 };
01037
01038
01039 static const arg_def_t bias_pct = ARG_DEF(NULL, "bias-pct", 1,
01040 "CBR/VBR bias (0=CBR, 100=VBR)");
01041 static const arg_def_t minsection_pct = ARG_DEF(NULL, "minsection-pct", 1,
01042 "GOP min bitrate (% of target)");
01043 static const arg_def_t maxsection_pct = ARG_DEF(NULL, "maxsection-pct", 1,
01044 "GOP max bitrate (% of target)");
01045 static const arg_def_t *rc_twopass_args[] =
01046 {
01047 &bias_pct, &minsection_pct, &maxsection_pct, NULL
01048 };
01049
01050
01051 static const arg_def_t kf_min_dist = ARG_DEF(NULL, "kf-min-dist", 1,
01052 "Minimum keyframe interval (frames)");
01053 static const arg_def_t kf_max_dist = ARG_DEF(NULL, "kf-max-dist", 1,
01054 "Maximum keyframe interval (frames)");
01055 static const arg_def_t kf_disabled = ARG_DEF(NULL, "disable-kf", 0,
01056 "Disable keyframe placement");
01057 static const arg_def_t *kf_args[] =
01058 {
01059 &kf_min_dist, &kf_max_dist, &kf_disabled, NULL
01060 };
01061
01062
01063 #if CONFIG_VP8_ENCODER
01064 static const arg_def_t noise_sens = ARG_DEF(NULL, "noise-sensitivity", 1,
01065 "Noise sensitivity (frames to blur)");
01066 static const arg_def_t sharpness = ARG_DEF(NULL, "sharpness", 1,
01067 "Filter sharpness (0-7)");
01068 static const arg_def_t static_thresh = ARG_DEF(NULL, "static-thresh", 1,
01069 "Motion detection threshold");
01070 #endif
01071
01072 #if CONFIG_VP8_ENCODER
01073 static const arg_def_t cpu_used = ARG_DEF(NULL, "cpu-used", 1,
01074 "CPU Used (-16..16)");
01075 #endif
01076
01077
01078 #if CONFIG_VP8_ENCODER
01079 static const arg_def_t token_parts = ARG_DEF(NULL, "token-parts", 1,
01080 "Number of token partitions to use, log2");
01081 static const arg_def_t auto_altref = ARG_DEF(NULL, "auto-alt-ref", 1,
01082 "Enable automatic alt reference frames");
01083 static const arg_def_t arnr_maxframes = ARG_DEF(NULL, "arnr-maxframes", 1,
01084 "AltRef Max Frames");
01085 static const arg_def_t arnr_strength = ARG_DEF(NULL, "arnr-strength", 1,
01086 "AltRef Strength");
01087 static const arg_def_t arnr_type = ARG_DEF(NULL, "arnr-type", 1,
01088 "AltRef Type");
01089 static const struct arg_enum_list tuning_enum[] = {
01090 {"psnr", VP8_TUNE_PSNR},
01091 {"ssim", VP8_TUNE_SSIM},
01092 {NULL, 0}
01093 };
01094 static const arg_def_t tune_ssim = ARG_DEF_ENUM(NULL, "tune", 1,
01095 "Material to favor", tuning_enum);
01096 static const arg_def_t cq_level = ARG_DEF(NULL, "cq-level", 1,
01097 "Constrained Quality Level");
01098 static const arg_def_t max_intra_rate_pct = ARG_DEF(NULL, "max-intra-rate", 1,
01099 "Max I-frame bitrate (pct)");
01100
01101 static const arg_def_t *vp8_args[] =
01102 {
01103 &cpu_used, &auto_altref, &noise_sens, &sharpness, &static_thresh,
01104 &token_parts, &arnr_maxframes, &arnr_strength, &arnr_type,
01105 &tune_ssim, &cq_level, &max_intra_rate_pct, NULL
01106 };
01107 static const int vp8_arg_ctrl_map[] =
01108 {
01109 VP8E_SET_CPUUSED, VP8E_SET_ENABLEAUTOALTREF,
01110 VP8E_SET_NOISE_SENSITIVITY, VP8E_SET_SHARPNESS, VP8E_SET_STATIC_THRESHOLD,
01111 VP8E_SET_TOKEN_PARTITIONS,
01112 VP8E_SET_ARNR_MAXFRAMES, VP8E_SET_ARNR_STRENGTH , VP8E_SET_ARNR_TYPE,
01113 VP8E_SET_TUNING, VP8E_SET_CQ_LEVEL, VP8E_SET_MAX_INTRA_BITRATE_PCT, 0
01114 };
01115 #endif
01116
01117 static const arg_def_t *no_args[] = { NULL };
01118
01119 static void usage_exit()
01120 {
01121 int i;
01122
01123 fprintf(stderr, "Usage: %s <options> -o dst_filename src_filename \n",
01124 exec_name);
01125
01126 fprintf(stderr, "\nOptions:\n");
01127 arg_show_usage(stdout, main_args);
01128 fprintf(stderr, "\nEncoder Global Options:\n");
01129 arg_show_usage(stdout, global_args);
01130 fprintf(stderr, "\nRate Control Options:\n");
01131 arg_show_usage(stdout, rc_args);
01132 fprintf(stderr, "\nTwopass Rate Control Options:\n");
01133 arg_show_usage(stdout, rc_twopass_args);
01134 fprintf(stderr, "\nKeyframe Placement Options:\n");
01135 arg_show_usage(stdout, kf_args);
01136 #if CONFIG_VP8_ENCODER
01137 fprintf(stderr, "\nVP8 Specific Options:\n");
01138 arg_show_usage(stdout, vp8_args);
01139 #endif
01140 fprintf(stderr, "\nStream timebase (--timebase):\n"
01141 " The desired precision of timestamps in the output, expressed\n"
01142 " in fractional seconds. Default is 1/1000.\n");
01143 fprintf(stderr, "\n"
01144 "Included encoders:\n"
01145 "\n");
01146
01147 for (i = 0; i < sizeof(codecs) / sizeof(codecs[0]); i++)
01148 fprintf(stderr, " %-6s - %s\n",
01149 codecs[i].name,
01150 vpx_codec_iface_name(codecs[i].iface));
01151
01152 exit(EXIT_FAILURE);
01153 }
01154
01155
01156 #define HIST_BAR_MAX 40
01157 struct hist_bucket
01158 {
01159 int low, high, count;
01160 };
01161
01162
01163 static int merge_hist_buckets(struct hist_bucket *bucket,
01164 int *buckets_,
01165 int max_buckets)
01166 {
01167 int small_bucket = 0, merge_bucket = INT_MAX, big_bucket=0;
01168 int buckets = *buckets_;
01169 int i;
01170
01171
01172 big_bucket = small_bucket = 0;
01173 for(i=0; i < buckets; i++)
01174 {
01175 if(bucket[i].count < bucket[small_bucket].count)
01176 small_bucket = i;
01177 if(bucket[i].count > bucket[big_bucket].count)
01178 big_bucket = i;
01179 }
01180
01181
01182
01183
01184 while(buckets > max_buckets)
01185 {
01186 int last_bucket = buckets - 1;
01187
01188
01189 if(small_bucket == 0)
01190 merge_bucket = 1;
01191 else if(small_bucket == last_bucket)
01192 merge_bucket = last_bucket - 1;
01193 else if(bucket[small_bucket - 1].count < bucket[small_bucket + 1].count)
01194 merge_bucket = small_bucket - 1;
01195 else
01196 merge_bucket = small_bucket + 1;
01197
01198 assert(abs(merge_bucket - small_bucket) <= 1);
01199 assert(small_bucket < buckets);
01200 assert(big_bucket < buckets);
01201 assert(merge_bucket < buckets);
01202
01203 if(merge_bucket < small_bucket)
01204 {
01205 bucket[merge_bucket].high = bucket[small_bucket].high;
01206 bucket[merge_bucket].count += bucket[small_bucket].count;
01207 }
01208 else
01209 {
01210 bucket[small_bucket].high = bucket[merge_bucket].high;
01211 bucket[small_bucket].count += bucket[merge_bucket].count;
01212 merge_bucket = small_bucket;
01213 }
01214
01215 assert(bucket[merge_bucket].low != bucket[merge_bucket].high);
01216
01217 buckets--;
01218
01219
01220
01221
01222 big_bucket = small_bucket = 0;
01223 for(i=0; i < buckets; i++)
01224 {
01225 if(i > merge_bucket)
01226 bucket[i] = bucket[i+1];
01227
01228 if(bucket[i].count < bucket[small_bucket].count)
01229 small_bucket = i;
01230 if(bucket[i].count > bucket[big_bucket].count)
01231 big_bucket = i;
01232 }
01233
01234 }
01235
01236 *buckets_ = buckets;
01237 return bucket[big_bucket].count;
01238 }
01239
01240
01241 static void show_histogram(const struct hist_bucket *bucket,
01242 int buckets,
01243 int total,
01244 int scale)
01245 {
01246 const char *pat1, *pat2;
01247 int i;
01248
01249 switch((int)(log(bucket[buckets-1].high)/log(10))+1)
01250 {
01251 case 1:
01252 case 2:
01253 pat1 = "%4d %2s: ";
01254 pat2 = "%4d-%2d: ";
01255 break;
01256 case 3:
01257 pat1 = "%5d %3s: ";
01258 pat2 = "%5d-%3d: ";
01259 break;
01260 case 4:
01261 pat1 = "%6d %4s: ";
01262 pat2 = "%6d-%4d: ";
01263 break;
01264 case 5:
01265 pat1 = "%7d %5s: ";
01266 pat2 = "%7d-%5d: ";
01267 break;
01268 case 6:
01269 pat1 = "%8d %6s: ";
01270 pat2 = "%8d-%6d: ";
01271 break;
01272 case 7:
01273 pat1 = "%9d %7s: ";
01274 pat2 = "%9d-%7d: ";
01275 break;
01276 default:
01277 pat1 = "%12d %10s: ";
01278 pat2 = "%12d-%10d: ";
01279 break;
01280 }
01281
01282 for(i=0; i<buckets; i++)
01283 {
01284 int len;
01285 int j;
01286 float pct;
01287
01288 pct = 100.0 * (float)bucket[i].count / (float)total;
01289 len = HIST_BAR_MAX * bucket[i].count / scale;
01290 if(len < 1)
01291 len = 1;
01292 assert(len <= HIST_BAR_MAX);
01293
01294 if(bucket[i].low == bucket[i].high)
01295 fprintf(stderr, pat1, bucket[i].low, "");
01296 else
01297 fprintf(stderr, pat2, bucket[i].low, bucket[i].high);
01298
01299 for(j=0; j<HIST_BAR_MAX; j++)
01300 fprintf(stderr, j<len?"=":" ");
01301 fprintf(stderr, "\t%5d (%6.2f%%)\n",bucket[i].count,pct);
01302 }
01303 }
01304
01305
01306 static void show_q_histogram(const int counts[64], int max_buckets)
01307 {
01308 struct hist_bucket bucket[64];
01309 int buckets = 0;
01310 int total = 0;
01311 int scale;
01312 int i;
01313
01314
01315 for(i=0; i<64; i++)
01316 {
01317 if(counts[i])
01318 {
01319 bucket[buckets].low = bucket[buckets].high = i;
01320 bucket[buckets].count = counts[i];
01321 buckets++;
01322 total += counts[i];
01323 }
01324 }
01325
01326 fprintf(stderr, "\nQuantizer Selection:\n");
01327 scale = merge_hist_buckets(bucket, &buckets, max_buckets);
01328 show_histogram(bucket, buckets, total, scale);
01329 }
01330
01331
01332 #define RATE_BINS (100)
01333 struct rate_hist
01334 {
01335 int64_t *pts;
01336 int *sz;
01337 int samples;
01338 int frames;
01339 struct hist_bucket bucket[RATE_BINS];
01340 int total;
01341 };
01342
01343
01344 static void init_rate_histogram(struct rate_hist *hist,
01345 const vpx_codec_enc_cfg_t *cfg,
01346 const vpx_rational_t *fps)
01347 {
01348 int i;
01349
01350
01351
01352
01353
01354 hist->samples = cfg->rc_buf_sz * 5 / 4 * fps->num / fps->den / 1000;
01355
01356
01357 if (hist->samples == 0)
01358 hist->samples=1;
01359
01360 hist->pts = calloc(hist->samples, sizeof(*hist->pts));
01361 hist->sz = calloc(hist->samples, sizeof(*hist->sz));
01362 for(i=0; i<RATE_BINS; i++)
01363 {
01364 hist->bucket[i].low = INT_MAX;
01365 hist->bucket[i].high = 0;
01366 hist->bucket[i].count = 0;
01367 }
01368 }
01369
01370
01371 static void destroy_rate_histogram(struct rate_hist *hist)
01372 {
01373 free(hist->pts);
01374 free(hist->sz);
01375 }
01376
01377
01378 static void update_rate_histogram(struct rate_hist *hist,
01379 const vpx_codec_enc_cfg_t *cfg,
01380 const vpx_codec_cx_pkt_t *pkt)
01381 {
01382 int i, idx;
01383 int64_t now, then, sum_sz = 0, avg_bitrate;
01384
01385 now = pkt->data.frame.pts * 1000
01386 * (uint64_t)cfg->g_timebase.num / (uint64_t)cfg->g_timebase.den;
01387
01388 idx = hist->frames++ % hist->samples;
01389 hist->pts[idx] = now;
01390 hist->sz[idx] = pkt->data.frame.sz;
01391
01392 if(now < cfg->rc_buf_initial_sz)
01393 return;
01394
01395 then = now;
01396
01397
01398 for(i = hist->frames; i > 0 && hist->frames - i < hist->samples; i--)
01399 {
01400 int i_idx = (i-1) % hist->samples;
01401
01402 then = hist->pts[i_idx];
01403 if(now - then > cfg->rc_buf_sz)
01404 break;
01405 sum_sz += hist->sz[i_idx];
01406 }
01407
01408 if (now == then)
01409 return;
01410
01411 avg_bitrate = sum_sz * 8 * 1000 / (now - then);
01412 idx = avg_bitrate * (RATE_BINS/2) / (cfg->rc_target_bitrate * 1000);
01413 if(idx < 0)
01414 idx = 0;
01415 if(idx > RATE_BINS-1)
01416 idx = RATE_BINS-1;
01417 if(hist->bucket[idx].low > avg_bitrate)
01418 hist->bucket[idx].low = avg_bitrate;
01419 if(hist->bucket[idx].high < avg_bitrate)
01420 hist->bucket[idx].high = avg_bitrate;
01421 hist->bucket[idx].count++;
01422 hist->total++;
01423 }
01424
01425
01426 static void show_rate_histogram(struct rate_hist *hist,
01427 const vpx_codec_enc_cfg_t *cfg,
01428 int max_buckets)
01429 {
01430 int i, scale;
01431 int buckets = 0;
01432
01433 for(i = 0; i < RATE_BINS; i++)
01434 {
01435 if(hist->bucket[i].low == INT_MAX)
01436 continue;
01437 hist->bucket[buckets++] = hist->bucket[i];
01438 }
01439
01440 fprintf(stderr, "\nRate (over %dms window):\n", cfg->rc_buf_sz);
01441 scale = merge_hist_buckets(hist->bucket, &buckets, max_buckets);
01442 show_histogram(hist->bucket, buckets, hist->total, scale);
01443 }
01444
01445 #define NELEMENTS(x) (sizeof(x)/sizeof(x[0]))
01446 #define ARG_CTRL_CNT_MAX NELEMENTS(vp8_arg_ctrl_map)
01447
01448 int main(int argc, const char **argv_)
01449 {
01450 vpx_codec_ctx_t encoder;
01451 const char *in_fn = NULL, *out_fn = NULL, *stats_fn = NULL;
01452 int i;
01453 FILE *infile, *outfile;
01454 vpx_codec_enc_cfg_t cfg;
01455 vpx_codec_err_t res;
01456 int pass, one_pass_only = 0;
01457 stats_io_t stats;
01458 vpx_image_t raw;
01459 const struct codec_item *codec = codecs;
01460 int frame_avail, got_data;
01461
01462 struct arg arg;
01463 char **argv, **argi, **argj;
01464 int arg_usage = 0, arg_passes = 1, arg_deadline = 0;
01465 int arg_ctrls[ARG_CTRL_CNT_MAX][2], arg_ctrl_cnt = 0;
01466 int arg_limit = 0;
01467 static const arg_def_t **ctrl_args = no_args;
01468 static const int *ctrl_args_map = NULL;
01469 int verbose = 0, show_psnr = 0;
01470 int arg_use_i420 = 1;
01471 unsigned long cx_time = 0;
01472 unsigned int file_type, fourcc;
01473 y4m_input y4m;
01474 struct vpx_rational arg_framerate = {30, 1};
01475 int arg_have_framerate = 0;
01476 int write_webm = 1;
01477 EbmlGlobal ebml = {0};
01478 uint32_t hash = 0;
01479 uint64_t psnr_sse_total = 0;
01480 uint64_t psnr_samples_total = 0;
01481 double psnr_totals[4] = {0, 0, 0, 0};
01482 int psnr_count = 0;
01483 stereo_format_t stereo_fmt = STEREO_FORMAT_MONO;
01484 int counts[64]={0};
01485 int show_q_hist_buckets=0;
01486 int show_rate_hist_buckets=0;
01487 struct rate_hist rate_hist={0};
01488
01489 exec_name = argv_[0];
01490 ebml.last_pts_ms = -1;
01491
01492 if (argc < 3)
01493 usage_exit();
01494
01495
01496
01497
01498
01499 argv = argv_dup(argc - 1, argv_ + 1);
01500
01501 for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step)
01502 {
01503 arg.argv_step = 1;
01504
01505 if (arg_match(&arg, &codecarg, argi))
01506 {
01507 int j, k = -1;
01508
01509 for (j = 0; j < sizeof(codecs) / sizeof(codecs[0]); j++)
01510 if (!strcmp(codecs[j].name, arg.val))
01511 k = j;
01512
01513 if (k >= 0)
01514 codec = codecs + k;
01515 else
01516 die("Error: Unrecognized argument (%s) to --codec\n",
01517 arg.val);
01518
01519 }
01520 else if (arg_match(&arg, &passes, argi))
01521 {
01522 arg_passes = arg_parse_uint(&arg);
01523
01524 if (arg_passes < 1 || arg_passes > 2)
01525 die("Error: Invalid number of passes (%d)\n", arg_passes);
01526 }
01527 else if (arg_match(&arg, &pass_arg, argi))
01528 {
01529 one_pass_only = arg_parse_uint(&arg);
01530
01531 if (one_pass_only < 1 || one_pass_only > 2)
01532 die("Error: Invalid pass selected (%d)\n", one_pass_only);
01533 }
01534 else if (arg_match(&arg, &fpf_name, argi))
01535 stats_fn = arg.val;
01536 else if (arg_match(&arg, &usage, argi))
01537 arg_usage = arg_parse_uint(&arg);
01538 else if (arg_match(&arg, &deadline, argi))
01539 arg_deadline = arg_parse_uint(&arg);
01540 else if (arg_match(&arg, &best_dl, argi))
01541 arg_deadline = VPX_DL_BEST_QUALITY;
01542 else if (arg_match(&arg, &good_dl, argi))
01543 arg_deadline = VPX_DL_GOOD_QUALITY;
01544 else if (arg_match(&arg, &rt_dl, argi))
01545 arg_deadline = VPX_DL_REALTIME;
01546 else if (arg_match(&arg, &use_yv12, argi))
01547 {
01548 arg_use_i420 = 0;
01549 }
01550 else if (arg_match(&arg, &use_i420, argi))
01551 {
01552 arg_use_i420 = 1;
01553 }
01554 else if (arg_match(&arg, &verbosearg, argi))
01555 verbose = 1;
01556 else if (arg_match(&arg, &limit, argi))
01557 arg_limit = arg_parse_uint(&arg);
01558 else if (arg_match(&arg, &psnrarg, argi))
01559 show_psnr = 1;
01560 else if (arg_match(&arg, &framerate, argi))
01561 {
01562 arg_framerate = arg_parse_rational(&arg);
01563 arg_have_framerate = 1;
01564 }
01565 else if (arg_match(&arg, &use_ivf, argi))
01566 write_webm = 0;
01567 else if (arg_match(&arg, &outputfile, argi))
01568 out_fn = arg.val;
01569 else if (arg_match(&arg, &debugmode, argi))
01570 ebml.debug = 1;
01571 else if (arg_match(&arg, &q_hist_n, argi))
01572 show_q_hist_buckets = arg_parse_uint(&arg);
01573 else if (arg_match(&arg, &rate_hist_n, argi))
01574 show_rate_hist_buckets = arg_parse_uint(&arg);
01575 else
01576 argj++;
01577 }
01578
01579
01580
01581
01582 if (one_pass_only)
01583 {
01584
01585 if (one_pass_only > arg_passes)
01586 {
01587 fprintf(stderr, "Warning: Assuming --pass=%d implies --passes=%d\n",
01588 one_pass_only, one_pass_only);
01589 arg_passes = one_pass_only;
01590 }
01591
01592 if (arg_passes == 2 && !stats_fn)
01593 die("Must specify --fpf when --pass=%d and --passes=2\n", one_pass_only);
01594 }
01595
01596
01597 res = vpx_codec_enc_config_default(codec->iface, &cfg, arg_usage);
01598
01599 if (res)
01600 {
01601 fprintf(stderr, "Failed to get config: %s\n",
01602 vpx_codec_err_to_string(res));
01603 return EXIT_FAILURE;
01604 }
01605
01606
01607
01608
01609 cfg.g_timebase.den = 1000;
01610
01611
01612
01613
01614 cfg.g_w = 0;
01615 cfg.g_h = 0;
01616
01617
01618 for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step)
01619 {
01620 arg.argv_step = 1;
01621
01622 if (0);
01623 else if (arg_match(&arg, &threads, argi))
01624 cfg.g_threads = arg_parse_uint(&arg);
01625 else if (arg_match(&arg, &profile, argi))
01626 cfg.g_profile = arg_parse_uint(&arg);
01627 else if (arg_match(&arg, &width, argi))
01628 cfg.g_w = arg_parse_uint(&arg);
01629 else if (arg_match(&arg, &height, argi))
01630 cfg.g_h = arg_parse_uint(&arg);
01631 else if (arg_match(&arg, &stereo_mode, argi))
01632 stereo_fmt = arg_parse_enum_or_int(&arg);
01633 else if (arg_match(&arg, &timebase, argi))
01634 cfg.g_timebase = arg_parse_rational(&arg);
01635 else if (arg_match(&arg, &error_resilient, argi))
01636 cfg.g_error_resilient = arg_parse_uint(&arg);
01637 else if (arg_match(&arg, &lag_in_frames, argi))
01638 cfg.g_lag_in_frames = arg_parse_uint(&arg);
01639 else if (arg_match(&arg, &dropframe_thresh, argi))
01640 cfg.rc_dropframe_thresh = arg_parse_uint(&arg);
01641 else if (arg_match(&arg, &resize_allowed, argi))
01642 cfg.rc_resize_allowed = arg_parse_uint(&arg);
01643 else if (arg_match(&arg, &resize_up_thresh, argi))
01644 cfg.rc_resize_up_thresh = arg_parse_uint(&arg);
01645 else if (arg_match(&arg, &resize_down_thresh, argi))
01646 cfg.rc_resize_down_thresh = arg_parse_uint(&arg);
01647 else if (arg_match(&arg, &end_usage, argi))
01648 cfg.rc_end_usage = arg_parse_enum_or_int(&arg);
01649 else if (arg_match(&arg, &target_bitrate, argi))
01650 cfg.rc_target_bitrate = arg_parse_uint(&arg);
01651 else if (arg_match(&arg, &min_quantizer, argi))
01652 cfg.rc_min_quantizer = arg_parse_uint(&arg);
01653 else if (arg_match(&arg, &max_quantizer, argi))
01654 cfg.rc_max_quantizer = arg_parse_uint(&arg);
01655 else if (arg_match(&arg, &undershoot_pct, argi))
01656 cfg.rc_undershoot_pct = arg_parse_uint(&arg);
01657 else if (arg_match(&arg, &overshoot_pct, argi))
01658 cfg.rc_overshoot_pct = arg_parse_uint(&arg);
01659 else if (arg_match(&arg, &buf_sz, argi))
01660 cfg.rc_buf_sz = arg_parse_uint(&arg);
01661 else if (arg_match(&arg, &buf_initial_sz, argi))
01662 cfg.rc_buf_initial_sz = arg_parse_uint(&arg);
01663 else if (arg_match(&arg, &buf_optimal_sz, argi))
01664 cfg.rc_buf_optimal_sz = arg_parse_uint(&arg);
01665 else if (arg_match(&arg, &bias_pct, argi))
01666 {
01667 cfg.rc_2pass_vbr_bias_pct = arg_parse_uint(&arg);
01668
01669 if (arg_passes < 2)
01670 fprintf(stderr,
01671 "Warning: option %s ignored in one-pass mode.\n",
01672 arg.name);
01673 }
01674 else if (arg_match(&arg, &minsection_pct, argi))
01675 {
01676 cfg.rc_2pass_vbr_minsection_pct = arg_parse_uint(&arg);
01677
01678 if (arg_passes < 2)
01679 fprintf(stderr,
01680 "Warning: option %s ignored in one-pass mode.\n",
01681 arg.name);
01682 }
01683 else if (arg_match(&arg, &maxsection_pct, argi))
01684 {
01685 cfg.rc_2pass_vbr_maxsection_pct = arg_parse_uint(&arg);
01686
01687 if (arg_passes < 2)
01688 fprintf(stderr,
01689 "Warning: option %s ignored in one-pass mode.\n",
01690 arg.name);
01691 }
01692 else if (arg_match(&arg, &kf_min_dist, argi))
01693 cfg.kf_min_dist = arg_parse_uint(&arg);
01694 else if (arg_match(&arg, &kf_max_dist, argi))
01695 cfg.kf_max_dist = arg_parse_uint(&arg);
01696 else if (arg_match(&arg, &kf_disabled, argi))
01697 cfg.kf_mode = VPX_KF_DISABLED;
01698 else
01699 argj++;
01700 }
01701
01702
01703 #if CONFIG_VP8_ENCODER
01704
01705 if (codec->iface == &vpx_codec_vp8_cx_algo)
01706 {
01707 ctrl_args = vp8_args;
01708 ctrl_args_map = vp8_arg_ctrl_map;
01709 }
01710
01711 #endif
01712
01713 for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step)
01714 {
01715 int match = 0;
01716
01717 arg.argv_step = 1;
01718
01719 for (i = 0; ctrl_args[i]; i++)
01720 {
01721 if (arg_match(&arg, ctrl_args[i], argi))
01722 {
01723 int j;
01724 match = 1;
01725
01726
01727
01728
01729 for(j=0; j<arg_ctrl_cnt; j++)
01730 if(arg_ctrls[j][0] == ctrl_args_map[i])
01731 break;
01732
01733
01734 assert(j < ARG_CTRL_CNT_MAX);
01735 if (j < ARG_CTRL_CNT_MAX)
01736 {
01737 arg_ctrls[j][0] = ctrl_args_map[i];
01738 arg_ctrls[j][1] = arg_parse_enum_or_int(&arg);
01739 if(j == arg_ctrl_cnt)
01740 arg_ctrl_cnt++;
01741 }
01742
01743 }
01744 }
01745
01746 if (!match)
01747 argj++;
01748 }
01749
01750
01751 for (argi = argv; *argi; argi++)
01752 if (argi[0][0] == '-' && argi[0][1])
01753 die("Error: Unrecognized option %s\n", *argi);
01754
01755
01756 in_fn = argv[0];
01757
01758 if (!in_fn)
01759 usage_exit();
01760
01761 if(!out_fn)
01762 die("Error: Output file is required (specify with -o)\n");
01763
01764 memset(&stats, 0, sizeof(stats));
01765
01766 for (pass = one_pass_only ? one_pass_only - 1 : 0; pass < arg_passes; pass++)
01767 {
01768 int frames_in = 0, frames_out = 0;
01769 int64_t nbytes = 0;
01770 struct detect_buffer detect;
01771
01772
01773 infile = strcmp(in_fn, "-") ? fopen(in_fn, "rb")
01774 : set_binary_mode(stdin);
01775
01776 if (!infile)
01777 {
01778 fprintf(stderr, "Failed to open input file\n");
01779 return EXIT_FAILURE;
01780 }
01781
01782
01783
01784
01785 detect.buf_read = fread(detect.buf, 1, 4, infile);
01786 detect.position = 0;
01787
01788 if (detect.buf_read == 4 && file_is_y4m(infile, &y4m, detect.buf))
01789 {
01790 if (y4m_input_open(&y4m, infile, detect.buf, 4) >= 0)
01791 {
01792 file_type = FILE_TYPE_Y4M;
01793 cfg.g_w = y4m.pic_w;
01794 cfg.g_h = y4m.pic_h;
01795
01796
01797
01798
01799 if (!arg_have_framerate)
01800 {
01801 arg_framerate.num = y4m.fps_n;
01802 arg_framerate.den = y4m.fps_d;
01803 }
01804
01805 arg_use_i420 = 0;
01806 }
01807 else
01808 {
01809 fprintf(stderr, "Unsupported Y4M stream.\n");
01810 return EXIT_FAILURE;
01811 }
01812 }
01813 else if (detect.buf_read == 4 &&
01814 file_is_ivf(infile, &fourcc, &cfg.g_w, &cfg.g_h, &detect))
01815 {
01816 file_type = FILE_TYPE_IVF;
01817 switch (fourcc)
01818 {
01819 case 0x32315659:
01820 arg_use_i420 = 0;
01821 break;
01822 case 0x30323449:
01823 arg_use_i420 = 1;
01824 break;
01825 default:
01826 fprintf(stderr, "Unsupported fourcc (%08x) in IVF\n", fourcc);
01827 return EXIT_FAILURE;
01828 }
01829 }
01830 else
01831 {
01832 file_type = FILE_TYPE_RAW;
01833 }
01834
01835 if(!cfg.g_w || !cfg.g_h)
01836 {
01837 fprintf(stderr, "Specify stream dimensions with --width (-w) "
01838 " and --height (-h).\n");
01839 return EXIT_FAILURE;
01840 }
01841
01842 #define SHOW(field) fprintf(stderr, " %-28s = %d\n", #field, cfg.field)
01843
01844 if (verbose && pass == 0)
01845 {
01846 fprintf(stderr, "Codec: %s\n", vpx_codec_iface_name(codec->iface));
01847 fprintf(stderr, "Source file: %s Format: %s\n", in_fn,
01848 arg_use_i420 ? "I420" : "YV12");
01849 fprintf(stderr, "Destination file: %s\n", out_fn);
01850 fprintf(stderr, "Encoder parameters:\n");
01851
01852 SHOW(g_usage);
01853 SHOW(g_threads);
01854 SHOW(g_profile);
01855 SHOW(g_w);
01856 SHOW(g_h);
01857 SHOW(g_timebase.num);
01858 SHOW(g_timebase.den);
01859 SHOW(g_error_resilient);
01860 SHOW(g_pass);
01861 SHOW(g_lag_in_frames);
01862 SHOW(rc_dropframe_thresh);
01863 SHOW(rc_resize_allowed);
01864 SHOW(rc_resize_up_thresh);
01865 SHOW(rc_resize_down_thresh);
01866 SHOW(rc_end_usage);
01867 SHOW(rc_target_bitrate);
01868 SHOW(rc_min_quantizer);
01869 SHOW(rc_max_quantizer);
01870 SHOW(rc_undershoot_pct);
01871 SHOW(rc_overshoot_pct);
01872 SHOW(rc_buf_sz);
01873 SHOW(rc_buf_initial_sz);
01874 SHOW(rc_buf_optimal_sz);
01875 SHOW(rc_2pass_vbr_bias_pct);
01876 SHOW(rc_2pass_vbr_minsection_pct);
01877 SHOW(rc_2pass_vbr_maxsection_pct);
01878 SHOW(kf_mode);
01879 SHOW(kf_min_dist);
01880 SHOW(kf_max_dist);
01881 }
01882
01883 if(pass == (one_pass_only ? one_pass_only - 1 : 0)) {
01884 if (file_type == FILE_TYPE_Y4M)
01885
01886
01887
01888 memset(&raw, 0, sizeof(raw));
01889 else
01890 vpx_img_alloc(&raw, arg_use_i420 ? VPX_IMG_FMT_I420 : VPX_IMG_FMT_YV12,
01891 cfg.g_w, cfg.g_h, 1);
01892
01893 init_rate_histogram(&rate_hist, &cfg, &arg_framerate);
01894 }
01895
01896 outfile = strcmp(out_fn, "-") ? fopen(out_fn, "wb")
01897 : set_binary_mode(stdout);
01898
01899 if (!outfile)
01900 {
01901 fprintf(stderr, "Failed to open output file\n");
01902 return EXIT_FAILURE;
01903 }
01904
01905 if(write_webm && fseek(outfile, 0, SEEK_CUR))
01906 {
01907 fprintf(stderr, "WebM output to pipes not supported.\n");
01908 return EXIT_FAILURE;
01909 }
01910
01911 if (stats_fn)
01912 {
01913 if (!stats_open_file(&stats, stats_fn, pass))
01914 {
01915 fprintf(stderr, "Failed to open statistics store\n");
01916 return EXIT_FAILURE;
01917 }
01918 }
01919 else
01920 {
01921 if (!stats_open_mem(&stats, pass))
01922 {
01923 fprintf(stderr, "Failed to open statistics store\n");
01924 return EXIT_FAILURE;
01925 }
01926 }
01927
01928 cfg.g_pass = arg_passes == 2
01929 ? pass ? VPX_RC_LAST_PASS : VPX_RC_FIRST_PASS
01930 : VPX_RC_ONE_PASS;
01931 #if VPX_ENCODER_ABI_VERSION > (1 + VPX_CODEC_ABI_VERSION)
01932
01933 if (pass)
01934 {
01935 cfg.rc_twopass_stats_in = stats_get(&stats);
01936 }
01937
01938 #endif
01939
01940 if(write_webm)
01941 {
01942 ebml.stream = outfile;
01943 write_webm_file_header(&ebml, &cfg, &arg_framerate, stereo_fmt);
01944 }
01945 else
01946 write_ivf_file_header(outfile, &cfg, codec->fourcc, 0);
01947
01948
01949
01950 vpx_codec_enc_init(&encoder, codec->iface, &cfg,
01951 show_psnr ? VPX_CODEC_USE_PSNR : 0);
01952 ctx_exit_on_error(&encoder, "Failed to initialize encoder");
01953
01954
01955
01956
01957
01958 for (i = 0; i < arg_ctrl_cnt; i++)
01959 {
01960 if (vpx_codec_control_(&encoder, arg_ctrls[i][0], arg_ctrls[i][1]))
01961 fprintf(stderr, "Error: Tried to set control %d = %d\n",
01962 arg_ctrls[i][0], arg_ctrls[i][1]);
01963
01964 ctx_exit_on_error(&encoder, "Failed to control codec");
01965 }
01966
01967 frame_avail = 1;
01968 got_data = 0;
01969
01970 while (frame_avail || got_data)
01971 {
01972 vpx_codec_iter_t iter = NULL;
01973 const vpx_codec_cx_pkt_t *pkt;
01974 struct vpx_usec_timer timer;
01975 int64_t frame_start, next_frame_start;
01976
01977 if (!arg_limit || frames_in < arg_limit)
01978 {
01979 frame_avail = read_frame(infile, &raw, file_type, &y4m,
01980 &detect);
01981
01982 if (frame_avail)
01983 frames_in++;
01984
01985 fprintf(stderr,
01986 "\rPass %d/%d frame %4d/%-4d %7"PRId64"B \033[K",
01987 pass + 1, arg_passes, frames_in, frames_out, nbytes);
01988 }
01989 else
01990 frame_avail = 0;
01991
01992 vpx_usec_timer_start(&timer);
01993
01994 frame_start = (cfg.g_timebase.den * (int64_t)(frames_in - 1)
01995 * arg_framerate.den) / cfg.g_timebase.num / arg_framerate.num;
01996 next_frame_start = (cfg.g_timebase.den * (int64_t)(frames_in)
01997 * arg_framerate.den)
01998 / cfg.g_timebase.num / arg_framerate.num;
01999 vpx_codec_encode(&encoder, frame_avail ? &raw : NULL, frame_start,
02000 next_frame_start - frame_start,
02001 0, arg_deadline);
02002 vpx_usec_timer_mark(&timer);
02003 cx_time += vpx_usec_timer_elapsed(&timer);
02004 ctx_exit_on_error(&encoder, "Failed to encode frame");
02005
02006 if(cfg.g_pass != VPX_RC_FIRST_PASS)
02007 {
02008 int q;
02009
02010 vpx_codec_control(&encoder, VP8E_GET_LAST_QUANTIZER_64, &q);
02011 ctx_exit_on_error(&encoder, "Failed to read quantizer");
02012 counts[q]++;
02013 }
02014
02015 got_data = 0;
02016
02017 while ((pkt = vpx_codec_get_cx_data(&encoder, &iter)))
02018 {
02019 got_data = 1;
02020
02021 switch (pkt->kind)
02022 {
02023 case VPX_CODEC_CX_FRAME_PKT:
02024 frames_out++;
02025 fprintf(stderr, " %6luF",
02026 (unsigned long)pkt->data.frame.sz);
02027
02028 update_rate_histogram(&rate_hist, &cfg, pkt);
02029 if(write_webm)
02030 {
02031
02032 if(!ebml.debug)
02033 hash = murmur(pkt->data.frame.buf,
02034 pkt->data.frame.sz, hash);
02035
02036 write_webm_block(&ebml, &cfg, pkt);
02037 }
02038 else
02039 {
02040 write_ivf_frame_header(outfile, pkt);
02041 if(fwrite(pkt->data.frame.buf, 1,
02042 pkt->data.frame.sz, outfile));
02043 }
02044 nbytes += pkt->data.raw.sz;
02045 break;
02046 case VPX_CODEC_STATS_PKT:
02047 frames_out++;
02048 fprintf(stderr, " %6luS",
02049 (unsigned long)pkt->data.twopass_stats.sz);
02050 stats_write(&stats,
02051 pkt->data.twopass_stats.buf,
02052 pkt->data.twopass_stats.sz);
02053 nbytes += pkt->data.raw.sz;
02054 break;
02055 case VPX_CODEC_PSNR_PKT:
02056
02057 if (show_psnr)
02058 {
02059 int i;
02060
02061 psnr_sse_total += pkt->data.psnr.sse[0];
02062 psnr_samples_total += pkt->data.psnr.samples[0];
02063 for (i = 0; i < 4; i++)
02064 {
02065 fprintf(stderr, "%.3lf ", pkt->data.psnr.psnr[i]);
02066 psnr_totals[i] += pkt->data.psnr.psnr[i];
02067 }
02068 psnr_count++;
02069 }
02070
02071 break;
02072 default:
02073 break;
02074 }
02075 }
02076
02077 fflush(stdout);
02078 }
02079
02080 fprintf(stderr,
02081 "\rPass %d/%d frame %4d/%-4d %7"PRId64"B %7lub/f %7"PRId64"b/s"
02082 " %7lu %s (%.2f fps)\033[K", pass + 1,
02083 arg_passes, frames_in, frames_out, nbytes,
02084 frames_in ? (unsigned long)(nbytes * 8 / frames_in) : 0,
02085 frames_in ? nbytes * 8 *(int64_t)arg_framerate.num / arg_framerate.den / frames_in : 0,
02086 cx_time > 9999999 ? cx_time / 1000 : cx_time,
02087 cx_time > 9999999 ? "ms" : "us",
02088 cx_time > 0 ? (float)frames_in * 1000000.0 / (float)cx_time : 0);
02089
02090 if ( (show_psnr) && (psnr_count>0) )
02091 {
02092 int i;
02093 double ovpsnr = vp8_mse2psnr(psnr_samples_total, 255.0,
02094 psnr_sse_total);
02095
02096 fprintf(stderr, "\nPSNR (Overall/Avg/Y/U/V)");
02097
02098 fprintf(stderr, " %.3lf", ovpsnr);
02099 for (i = 0; i < 4; i++)
02100 {
02101 fprintf(stderr, " %.3lf", psnr_totals[i]/psnr_count);
02102 }
02103 }
02104
02105 vpx_codec_destroy(&encoder);
02106
02107 fclose(infile);
02108 if (file_type == FILE_TYPE_Y4M)
02109 y4m_input_close(&y4m);
02110
02111 if(write_webm)
02112 {
02113 write_webm_file_footer(&ebml, hash);
02114 free(ebml.cue_list);
02115 ebml.cue_list = NULL;
02116 }
02117 else
02118 {
02119 if (!fseek(outfile, 0, SEEK_SET))
02120 write_ivf_file_header(outfile, &cfg, codec->fourcc, frames_out);
02121 }
02122
02123 fclose(outfile);
02124 stats_close(&stats, arg_passes-1);
02125 fprintf(stderr, "\n");
02126
02127 if (one_pass_only)
02128 break;
02129 }
02130
02131 if (show_q_hist_buckets)
02132 show_q_histogram(counts, show_q_hist_buckets);
02133
02134 if (show_rate_hist_buckets)
02135 show_rate_histogram(&rate_hist, &cfg, show_rate_hist_buckets);
02136 destroy_rate_histogram(&rate_hist);
02137
02138 vpx_img_free(&raw);
02139 free(argv);
02140 return EXIT_SUCCESS;
02141 }