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