ivfenc

00001 /*
00002  *  Copyright (c) 2010 The VP8 project authors. All Rights Reserved.
00003  *
00004  *  Use of this source code is governed by a BSD-style license
00005  *  that can be found in the LICENSE file in the root of the source
00006  *  tree. An additional intellectual property rights grant can be found
00007  *  in the file PATENTS.  All contributing project authors may
00008  *  be found in the AUTHORS file in the root of the source tree.
00009  */
00010 
00011 
00012 /* This is a simple program that encodes YV12 files and generates ivf
00013  * files using the new interface.
00014  */
00015 #if defined(_WIN32)
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 "vpx/vpx_encoder.h"
00026 #if USE_POSIX_MMAP
00027 #include <sys/types.h>
00028 #include <sys/stat.h>
00029 #include <sys/mman.h>
00030 #include <fcntl.h>
00031 #include <unistd.h>
00032 #endif
00033 #include "vpx/vp8cx.h"
00034 #include "vpx_ports/mem_ops.h"
00035 #include "vpx_ports/vpx_timer.h"
00036 #include "y4minput.h"
00037 
00038 static const char *exec_name;
00039 
00040 static const struct codec_item
00041 {
00042     char const              *name;
00043     const vpx_codec_iface_t *iface;
00044     unsigned int             fourcc;
00045 } codecs[] =
00046 {
00047 #if CONFIG_VP8_ENCODER
00048     {"vp8",  &vpx_codec_vp8_cx_algo, 0x30385056},
00049 #endif
00050 };
00051 
00052 static void usage_exit();
00053 
00054 void die(const char *fmt, ...)
00055 {
00056     va_list ap;
00057     va_start(ap, fmt);
00058     vfprintf(stderr, fmt, ap);
00059     fprintf(stderr, "\n");
00060     usage_exit();
00061 }
00062 
00063 static void ctx_exit_on_error(vpx_codec_ctx_t *ctx, const char *s)
00064 {
00065     if (ctx->err)
00066     {
00067         const char *detail = vpx_codec_error_detail(ctx);
00068 
00069         fprintf(stderr, "%s: %s\n", s, vpx_codec_error(ctx));
00070 
00071         if (detail)
00072             fprintf(stderr, "    %s\n", detail);
00073 
00074         exit(EXIT_FAILURE);
00075     }
00076 }
00077 
00078 /* This structure is used to abstract the different ways of handling
00079  * first pass statistics.
00080  */
00081 typedef struct
00082 {
00083     vpx_fixed_buf_t buf;
00084     int             pass;
00085     FILE           *file;
00086     char           *buf_ptr;
00087     size_t          buf_alloc_sz;
00088 } stats_io_t;
00089 
00090 int stats_open_file(stats_io_t *stats, const char *fpf, int pass)
00091 {
00092     int res;
00093 
00094     stats->pass = pass;
00095 
00096     if (pass == 0)
00097     {
00098         stats->file = fopen(fpf, "wb");
00099         stats->buf.sz = 0;
00100         stats->buf.buf = NULL,
00101                    res = (stats->file != NULL);
00102     }
00103     else
00104     {
00105 #if 0
00106 #elif USE_POSIX_MMAP
00107         struct stat stat_buf;
00108         int fd;
00109 
00110         fd = open(fpf, O_RDONLY);
00111         stats->file = fdopen(fd, "rb");
00112         fstat(fd, &stat_buf);
00113         stats->buf.sz = stat_buf.st_size;
00114         stats->buf.buf = mmap(NULL, stats->buf.sz, PROT_READ, MAP_PRIVATE,
00115                               fd, 0);
00116         res = (stats->buf.buf != NULL);
00117 #else
00118         size_t nbytes;
00119 
00120         stats->file = fopen(fpf, "rb");
00121 
00122         if (fseek(stats->file, 0, SEEK_END))
00123         {
00124             fprintf(stderr, "First-pass stats file must be seekable!\n");
00125             exit(EXIT_FAILURE);
00126         }
00127 
00128         stats->buf.sz = stats->buf_alloc_sz = ftell(stats->file);
00129         rewind(stats->file);
00130 
00131         stats->buf.buf = malloc(stats->buf_alloc_sz);
00132 
00133         if (!stats->buf.buf)
00134         {
00135             fprintf(stderr, "Failed to allocate first-pass stats buffer (%d bytes)\n",
00136                     stats->buf_alloc_sz);
00137             exit(EXIT_FAILURE);
00138         }
00139 
00140         nbytes = fread(stats->buf.buf, 1, stats->buf.sz, stats->file);
00141         res = (nbytes == stats->buf.sz);
00142 #endif
00143     }
00144 
00145     return res;
00146 }
00147 
00148 int stats_open_mem(stats_io_t *stats, int pass)
00149 {
00150     int res;
00151     stats->pass = pass;
00152 
00153     if (!pass)
00154     {
00155         stats->buf.sz = 0;
00156         stats->buf_alloc_sz = 64 * 1024;
00157         stats->buf.buf = malloc(stats->buf_alloc_sz);
00158     }
00159 
00160     stats->buf_ptr = stats->buf.buf;
00161     res = (stats->buf.buf != NULL);
00162     return res;
00163 }
00164 
00165 
00166 void stats_close(stats_io_t *stats)
00167 {
00168     if (stats->file)
00169     {
00170         if (stats->pass == 1)
00171         {
00172 #if 0
00173 #elif USE_POSIX_MMAP
00174             munmap(stats->buf.buf, stats->buf.sz);
00175 #else
00176             free(stats->buf.buf);
00177 #endif
00178         }
00179 
00180         fclose(stats->file);
00181         stats->file = NULL;
00182     }
00183     else
00184     {
00185         if (stats->pass == 1)
00186             free(stats->buf.buf);
00187     }
00188 }
00189 
00190 void stats_write(stats_io_t *stats, const void *pkt, size_t len)
00191 {
00192     if (stats->file)
00193     {
00194         fwrite(pkt, 1, len, stats->file);
00195     }
00196     else
00197     {
00198         if (stats->buf.sz + len > stats->buf_alloc_sz)
00199         {
00200             size_t  new_sz = stats->buf_alloc_sz + 64 * 1024;
00201             char   *new_ptr = realloc(stats->buf.buf, new_sz);
00202 
00203             if (new_ptr)
00204             {
00205                 stats->buf_ptr = new_ptr + (stats->buf_ptr - (char *)stats->buf.buf);
00206                 stats->buf.buf = new_ptr;
00207                 stats->buf_alloc_sz = new_sz;
00208             } /* else ... */
00209         }
00210 
00211         memcpy(stats->buf_ptr, pkt, len);
00212         stats->buf.sz += len;
00213         stats->buf_ptr += len;
00214     }
00215 }
00216 
00217 vpx_fixed_buf_t stats_get(stats_io_t *stats)
00218 {
00219     return stats->buf;
00220 }
00221 
00222 enum video_file_type
00223 {
00224     FILE_TYPE_RAW,
00225     FILE_TYPE_IVF,
00226     FILE_TYPE_Y4M
00227 };
00228 
00229 struct detect_buffer {
00230     char buf[4];
00231     int  valid;
00232 };
00233 
00234 
00235 #define IVF_FRAME_HDR_SZ (4+8) /* 4 byte size + 8 byte timestamp */
00236 static int read_frame(FILE *f, vpx_image_t *img, unsigned int file_type,
00237                       y4m_input *y4m, struct detect_buffer *detect)
00238 {
00239     int plane = 0;
00240 
00241     if (file_type == FILE_TYPE_Y4M)
00242     {
00243         if (y4m_input_fetch_frame(y4m, f, img) < 0)
00244            return 0;
00245     }
00246     else
00247     {
00248         if (file_type == FILE_TYPE_IVF)
00249         {
00250             char junk[IVF_FRAME_HDR_SZ];
00251 
00252             /* Skip the frame header. We know how big the frame should be. See
00253              * write_ivf_frame_header() for documentation on the frame header
00254              * layout.
00255              */
00256             fread(junk, 1, IVF_FRAME_HDR_SZ, f);
00257         }
00258 
00259         for (plane = 0; plane < 3; plane++)
00260         {
00261             unsigned char *ptr;
00262             int w = (plane ? (1 + img->d_w) / 2 : img->d_w);
00263             int h = (plane ? (1 + img->d_h) / 2 : img->d_h);
00264             int r;
00265 
00266             /* Determine the correct plane based on the image format. The for-loop
00267              * always counts in Y,U,V order, but this may not match the order of
00268              * the data on disk.
00269              */
00270             switch (plane)
00271             {
00272             case 1:
00273                 ptr = img->planes[img->fmt==VPX_IMG_FMT_YV12? VPX_PLANE_V : VPX_PLANE_U];
00274                 break;
00275             case 2:
00276                 ptr = img->planes[img->fmt==VPX_IMG_FMT_YV12?VPX_PLANE_U : VPX_PLANE_V];
00277                 break;
00278             default:
00279                 ptr = img->planes[plane];
00280             }
00281 
00282             for (r = 0; r < h; r++)
00283             {
00284                 if (detect->valid)
00285                 {
00286                     memcpy(ptr, detect->buf, 4);
00287                     fread(ptr+4, 1, w-4, f);
00288                     detect->valid = 0;
00289                 }
00290                 else
00291                     fread(ptr, 1, w, f);
00292 
00293                 ptr += img->stride[plane];
00294             }
00295         }
00296     }
00297 
00298     return !feof(f);
00299 }
00300 
00301 
00302 unsigned int file_is_y4m(FILE      *infile,
00303                          y4m_input *y4m,
00304                          char       detect[4])
00305 {
00306     if(memcmp(detect, "YUV4", 4) == 0)
00307     {
00308         return 1;
00309     }
00310     return 0;
00311 }
00312 
00313 #define IVF_FILE_HDR_SZ (32)
00314 unsigned int file_is_ivf(FILE *infile,
00315                          unsigned int *fourcc,
00316                          unsigned int *width,
00317                          unsigned int *height,
00318                          char          detect[4])
00319 {
00320     char raw_hdr[IVF_FILE_HDR_SZ];
00321     int is_ivf = 0;
00322 
00323     if(memcmp(detect, "DKIF", 4) != 0)
00324         return 0;
00325 
00326     /* See write_ivf_file_header() for more documentation on the file header
00327      * layout.
00328      */
00329     if (fread(raw_hdr + 4, 1, IVF_FILE_HDR_SZ - 4, infile)
00330         == IVF_FILE_HDR_SZ - 4)
00331     {
00332         {
00333             is_ivf = 1;
00334 
00335             if (mem_get_le16(raw_hdr + 4) != 0)
00336                 fprintf(stderr, "Error: Unrecognized IVF version! This file may not"
00337                         " decode properly.");
00338 
00339             *fourcc = mem_get_le32(raw_hdr + 8);
00340         }
00341     }
00342 
00343     if (is_ivf)
00344     {
00345         *width = mem_get_le16(raw_hdr + 12);
00346         *height = mem_get_le16(raw_hdr + 14);
00347     }
00348 
00349     return is_ivf;
00350 }
00351 
00352 
00353 static void write_ivf_file_header(FILE *outfile,
00354                                   const vpx_codec_enc_cfg_t *cfg,
00355                                   unsigned int fourcc,
00356                                   int frame_cnt)
00357 {
00358     char header[32];
00359 
00360     if (cfg->g_pass != VPX_RC_ONE_PASS && cfg->g_pass != VPX_RC_LAST_PASS)
00361         return;
00362 
00363     header[0] = 'D';
00364     header[1] = 'K';
00365     header[2] = 'I';
00366     header[3] = 'F';
00367     mem_put_le16(header + 4,  0);                 /* version */
00368     mem_put_le16(header + 6,  32);                /* headersize */
00369     mem_put_le32(header + 8,  fourcc);            /* headersize */
00370     mem_put_le16(header + 12, cfg->g_w);          /* width */
00371     mem_put_le16(header + 14, cfg->g_h);          /* height */
00372     mem_put_le32(header + 16, cfg->g_timebase.den); /* rate */
00373     mem_put_le32(header + 20, cfg->g_timebase.num); /* scale */
00374     mem_put_le32(header + 24, frame_cnt);         /* length */
00375     mem_put_le32(header + 28, 0);                 /* unused */
00376 
00377     fwrite(header, 1, 32, outfile);
00378 }
00379 
00380 
00381 static void write_ivf_frame_header(FILE *outfile,
00382                                    const vpx_codec_cx_pkt_t *pkt)
00383 {
00384     char             header[12];
00385     vpx_codec_pts_t  pts;
00386 
00387     if (pkt->kind != VPX_CODEC_CX_FRAME_PKT)
00388         return;
00389 
00390     pts = pkt->data.frame.pts;
00391     mem_put_le32(header, pkt->data.frame.sz);
00392     mem_put_le32(header + 4, pts & 0xFFFFFFFF);
00393     mem_put_le32(header + 8, pts >> 32);
00394 
00395     fwrite(header, 1, 12, outfile);
00396 }
00397 
00398 #include "args.h"
00399 
00400 static const arg_def_t use_yv12 = ARG_DEF(NULL, "yv12", 0,
00401                                   "Input file is YV12 ");
00402 static const arg_def_t use_i420 = ARG_DEF(NULL, "i420", 0,
00403                                   "Input file is I420 (default)");
00404 static const arg_def_t codecarg = ARG_DEF(NULL, "codec", 1,
00405                                   "Codec to use");
00406 static const arg_def_t passes           = ARG_DEF("p", "passes", 1,
00407         "Number of passes (1/2)");
00408 static const arg_def_t pass_arg         = ARG_DEF(NULL, "pass", 1,
00409         "Pass to execute (1/2)");
00410 static const arg_def_t fpf_name         = ARG_DEF(NULL, "fpf", 1,
00411         "First pass statistics file name");
00412 static const arg_def_t limit = ARG_DEF(NULL, "limit", 1,
00413                                        "Stop encoding after n input frames");
00414 static const arg_def_t deadline         = ARG_DEF("d", "deadline", 1,
00415         "Deadline per frame (usec)");
00416 static const arg_def_t best_dl          = ARG_DEF(NULL, "best", 0,
00417         "Use Best Quality Deadline");
00418 static const arg_def_t good_dl          = ARG_DEF(NULL, "good", 0,
00419         "Use Good Quality Deadline");
00420 static const arg_def_t rt_dl            = ARG_DEF(NULL, "rt", 0,
00421         "Use Realtime Quality Deadline");
00422 static const arg_def_t verbosearg       = ARG_DEF("v", "verbose", 0,
00423         "Show encoder parameters");
00424 static const arg_def_t psnrarg          = ARG_DEF(NULL, "psnr", 0,
00425         "Show PSNR in status line");
00426 static const arg_def_t *main_args[] =
00427 {
00428     &codecarg, &passes, &pass_arg, &fpf_name, &limit, &deadline, &best_dl, &good_dl, &rt_dl,
00429     &verbosearg, &psnrarg,
00430     NULL
00431 };
00432 
00433 static const arg_def_t usage            = ARG_DEF("u", "usage", 1,
00434         "Usage profile number to use");
00435 static const arg_def_t threads          = ARG_DEF("t", "threads", 1,
00436         "Max number of threads to use");
00437 static const arg_def_t profile          = ARG_DEF(NULL, "profile", 1,
00438         "Bitstream profile number to use");
00439 static const arg_def_t width            = ARG_DEF("w", "width", 1,
00440         "Frame width");
00441 static const arg_def_t height           = ARG_DEF("h", "height", 1,
00442         "Frame height");
00443 static const arg_def_t timebase         = ARG_DEF(NULL, "timebase", 1,
00444         "Stream timebase (frame duration)");
00445 static const arg_def_t error_resilient  = ARG_DEF(NULL, "error-resilient", 1,
00446         "Enable error resiliency features");
00447 static const arg_def_t lag_in_frames    = ARG_DEF(NULL, "lag-in-frames", 1,
00448         "Max number of frames to lag");
00449 
00450 static const arg_def_t *global_args[] =
00451 {
00452     &use_yv12, &use_i420, &usage, &threads, &profile,
00453     &width, &height, &timebase, &error_resilient,
00454     &lag_in_frames, NULL
00455 };
00456 
00457 static const arg_def_t dropframe_thresh   = ARG_DEF(NULL, "drop-frame", 1,
00458         "Temporal resampling threshold (buf %)");
00459 static const arg_def_t resize_allowed     = ARG_DEF(NULL, "resize-allowed", 1,
00460         "Spatial resampling enabled (bool)");
00461 static const arg_def_t resize_up_thresh   = ARG_DEF(NULL, "resize-up", 1,
00462         "Upscale threshold (buf %)");
00463 static const arg_def_t resize_down_thresh = ARG_DEF(NULL, "resize-down", 1,
00464         "Downscale threshold (buf %)");
00465 static const arg_def_t end_usage          = ARG_DEF(NULL, "end-usage", 1,
00466         "VBR=0 | CBR=1");
00467 static const arg_def_t target_bitrate     = ARG_DEF(NULL, "target-bitrate", 1,
00468         "Bitrate (kbps)");
00469 static const arg_def_t min_quantizer      = ARG_DEF(NULL, "min-q", 1,
00470         "Minimum (best) quantizer");
00471 static const arg_def_t max_quantizer      = ARG_DEF(NULL, "max-q", 1,
00472         "Maximum (worst) quantizer");
00473 static const arg_def_t undershoot_pct     = ARG_DEF(NULL, "undershoot-pct", 1,
00474         "Datarate undershoot (min) target (%)");
00475 static const arg_def_t overshoot_pct      = ARG_DEF(NULL, "overshoot-pct", 1,
00476         "Datarate overshoot (max) target (%)");
00477 static const arg_def_t buf_sz             = ARG_DEF(NULL, "buf-sz", 1,
00478         "Client buffer size (ms)");
00479 static const arg_def_t buf_initial_sz     = ARG_DEF(NULL, "buf-initial-sz", 1,
00480         "Client initial buffer size (ms)");
00481 static const arg_def_t buf_optimal_sz     = ARG_DEF(NULL, "buf-optimal-sz", 1,
00482         "Client optimal buffer size (ms)");
00483 static const arg_def_t *rc_args[] =
00484 {
00485     &dropframe_thresh, &resize_allowed, &resize_up_thresh, &resize_down_thresh,
00486     &end_usage, &target_bitrate, &min_quantizer, &max_quantizer,
00487     &undershoot_pct, &overshoot_pct, &buf_sz, &buf_initial_sz, &buf_optimal_sz,
00488     NULL
00489 };
00490 
00491 
00492 static const arg_def_t bias_pct = ARG_DEF(NULL, "bias-pct", 1,
00493                                   "CBR/VBR bias (0=CBR, 100=VBR)");
00494 static const arg_def_t minsection_pct = ARG_DEF(NULL, "minsection-pct", 1,
00495                                         "GOP min bitrate (% of target)");
00496 static const arg_def_t maxsection_pct = ARG_DEF(NULL, "maxsection-pct", 1,
00497                                         "GOP max bitrate (% of target)");
00498 static const arg_def_t *rc_twopass_args[] =
00499 {
00500     &bias_pct, &minsection_pct, &maxsection_pct, NULL
00501 };
00502 
00503 
00504 static const arg_def_t kf_min_dist = ARG_DEF(NULL, "kf-min-dist", 1,
00505                                      "Minimum keyframe interval (frames)");
00506 static const arg_def_t kf_max_dist = ARG_DEF(NULL, "kf-max-dist", 1,
00507                                      "Maximum keyframe interval (frames)");
00508 static const arg_def_t *kf_args[] =
00509 {
00510     &kf_min_dist, &kf_max_dist, NULL
00511 };
00512 
00513 
00514 #if CONFIG_VP8_ENCODER
00515 static const arg_def_t noise_sens = ARG_DEF(NULL, "noise-sensitivity", 1,
00516                                     "Noise sensitivity (frames to blur)");
00517 static const arg_def_t sharpness = ARG_DEF(NULL, "sharpness", 1,
00518                                    "Filter sharpness (0-7)");
00519 static const arg_def_t static_thresh = ARG_DEF(NULL, "static-thresh", 1,
00520                                        "Motion detection threshold");
00521 #endif
00522 
00523 #if CONFIG_VP8_ENCODER
00524 static const arg_def_t cpu_used = ARG_DEF(NULL, "cpu-used", 1,
00525                                   "CPU Used (-16..16)");
00526 #endif
00527 
00528 
00529 #if CONFIG_VP8_ENCODER
00530 static const arg_def_t token_parts = ARG_DEF(NULL, "token-parts", 1,
00531                                      "Number of token partitions to use, log2");
00532 static const arg_def_t auto_altref = ARG_DEF(NULL, "auto-alt-ref", 1,
00533                                      "Enable automatic alt reference frames");
00534 static const arg_def_t arnr_maxframes = ARG_DEF(NULL, "arnr-maxframes", 1,
00535                                         "alt_ref Max Frames");
00536 static const arg_def_t arnr_strength = ARG_DEF(NULL, "arnr-strength", 1,
00537                                        "alt_ref Strength");
00538 static const arg_def_t arnr_type = ARG_DEF(NULL, "arnr-type", 1,
00539                                    "alt_ref Type");
00540 
00541 static const arg_def_t *vp8_args[] =
00542 {
00543     &cpu_used, &auto_altref, &noise_sens, &sharpness, &static_thresh,
00544     &token_parts, &arnr_maxframes, &arnr_strength, &arnr_type, NULL
00545 };
00546 static const int vp8_arg_ctrl_map[] =
00547 {
00548     VP8E_SET_CPUUSED, VP8E_SET_ENABLEAUTOALTREF,
00549     VP8E_SET_NOISE_SENSITIVITY, VP8E_SET_SHARPNESS, VP8E_SET_STATIC_THRESHOLD,
00550     VP8E_SET_TOKEN_PARTITIONS,
00551     VP8E_SET_ARNR_MAXFRAMES, VP8E_SET_ARNR_STRENGTH , VP8E_SET_ARNR_TYPE, 0
00552 };
00553 #endif
00554 
00555 static const arg_def_t *no_args[] = { NULL };
00556 
00557 static void usage_exit()
00558 {
00559     int i;
00560 
00561     fprintf(stderr, "Usage: %s <options> src_filename dst_filename\n", exec_name);
00562 
00563     fprintf(stderr, "\n_options:\n");
00564     arg_show_usage(stdout, main_args);
00565     fprintf(stderr, "\n_encoder Global Options:\n");
00566     arg_show_usage(stdout, global_args);
00567     fprintf(stderr, "\n_rate Control Options:\n");
00568     arg_show_usage(stdout, rc_args);
00569     fprintf(stderr, "\n_twopass Rate Control Options:\n");
00570     arg_show_usage(stdout, rc_twopass_args);
00571     fprintf(stderr, "\n_keyframe Placement Options:\n");
00572     arg_show_usage(stdout, kf_args);
00573 #if CONFIG_VP8_ENCODER
00574     fprintf(stderr, "\n_vp8 Specific Options:\n");
00575     arg_show_usage(stdout, vp8_args);
00576 #endif
00577     fprintf(stderr, "\n"
00578            "Included encoders:\n"
00579            "\n");
00580 
00581     for (i = 0; i < sizeof(codecs) / sizeof(codecs[0]); i++)
00582         fprintf(stderr, "    %-6s - %s\n",
00583                codecs[i].name,
00584                vpx_codec_iface_name(codecs[i].iface));
00585 
00586     exit(EXIT_FAILURE);
00587 }
00588 
00589 #define ARG_CTRL_CNT_MAX 10
00590 
00591 
00592 int main(int argc, const char **argv_)
00593 {
00594     vpx_codec_ctx_t        encoder;
00595     const char                  *in_fn = NULL, *out_fn = NULL, *stats_fn = NULL;
00596     int                    i;
00597     FILE                  *infile, *outfile;
00598     vpx_codec_enc_cfg_t    cfg;
00599     vpx_codec_err_t        res;
00600     int                    pass, one_pass_only = 0;
00601     stats_io_t             stats;
00602     vpx_image_t            raw;
00603     const struct codec_item  *codec = codecs;
00604     int                    frame_avail, got_data;
00605 
00606     struct arg               arg;
00607     char                   **argv, **argi, **argj;
00608     int                      arg_usage = 0, arg_passes = 1, arg_deadline = 0;
00609     int                      arg_ctrls[ARG_CTRL_CNT_MAX][2], arg_ctrl_cnt = 0;
00610     int                      arg_limit = 0;
00611     static const arg_def_t **ctrl_args = no_args;
00612     static const int        *ctrl_args_map = NULL;
00613     int                      verbose = 0, show_psnr = 0;
00614     int                      arg_use_i420 = 1;
00615     int                      arg_have_timebase = 0;
00616     unsigned long            cx_time = 0;
00617     unsigned int             file_type, fourcc;
00618     y4m_input                y4m;
00619 
00620     exec_name = argv_[0];
00621 
00622     if (argc < 3)
00623         usage_exit();
00624 
00625 
00626     /* First parse the codec and usage values, because we want to apply other
00627      * parameters on top of the default configuration provided by the codec.
00628      */
00629     argv = argv_dup(argc - 1, argv_ + 1);
00630 
00631     for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step)
00632     {
00633         arg.argv_step = 1;
00634 
00635         if (arg_match(&arg, &codecarg, argi))
00636         {
00637             int j, k = -1;
00638 
00639             for (j = 0; j < sizeof(codecs) / sizeof(codecs[0]); j++)
00640                 if (!strcmp(codecs[j].name, arg.val))
00641                     k = j;
00642 
00643             if (k >= 0)
00644                 codec = codecs + k;
00645             else
00646                 die("Error: Unrecognized argument (%s) to --codec\n",
00647                     arg.val);
00648 
00649         }
00650         else if (arg_match(&arg, &passes, argi))
00651         {
00652             arg_passes = arg_parse_uint(&arg);
00653 
00654             if (arg_passes < 1 || arg_passes > 2)
00655                 die("Error: Invalid number of passes (%d)\n", arg_passes);
00656         }
00657         else if (arg_match(&arg, &pass_arg, argi))
00658         {
00659             one_pass_only = arg_parse_uint(&arg);
00660 
00661             if (one_pass_only < 1 || one_pass_only > 2)
00662                 die("Error: Invalid pass selected (%d)\n", one_pass_only);
00663         }
00664         else if (arg_match(&arg, &fpf_name, argi))
00665             stats_fn = arg.val;
00666         else if (arg_match(&arg, &usage, argi))
00667             arg_usage = arg_parse_uint(&arg);
00668         else if (arg_match(&arg, &deadline, argi))
00669             arg_deadline = arg_parse_uint(&arg);
00670         else if (arg_match(&arg, &best_dl, argi))
00671             arg_deadline = VPX_DL_BEST_QUALITY;
00672         else if (arg_match(&arg, &good_dl, argi))
00673             arg_deadline = VPX_DL_GOOD_QUALITY;
00674         else if (arg_match(&arg, &rt_dl, argi))
00675             arg_deadline = VPX_DL_REALTIME;
00676         else if (arg_match(&arg, &use_yv12, argi))
00677         {
00678             arg_use_i420 = 0;
00679         }
00680         else if (arg_match(&arg, &use_i420, argi))
00681         {
00682             arg_use_i420 = 1;
00683         }
00684         else if (arg_match(&arg, &verbosearg, argi))
00685             verbose = 1;
00686         else if (arg_match(&arg, &limit, argi))
00687             arg_limit = arg_parse_uint(&arg);
00688         else if (arg_match(&arg, &psnrarg, argi))
00689             show_psnr = 1;
00690         else
00691             argj++;
00692     }
00693 
00694     /* Ensure that --passes and --pass are consistent. If --pass is set and --passes=2,
00695      * ensure --fpf was set.
00696      */
00697     if (one_pass_only)
00698     {
00699         /* DWIM: Assume the user meant passes=2 if pass=2 is specified */
00700         if (one_pass_only > arg_passes)
00701         {
00702             fprintf(stderr, "Warning: Assuming --pass=%d implies --passes=%d\n",
00703                    one_pass_only, one_pass_only);
00704             arg_passes = one_pass_only;
00705         }
00706 
00707         if (arg_passes == 2 && !stats_fn)
00708             die("Must specify --fpf when --pass=%d and --passes=2\n", one_pass_only);
00709     }
00710 
00711     /* Populate encoder configuration */
00712     res = vpx_codec_enc_config_default(codec->iface, &cfg, arg_usage);
00713 
00714     if (res)
00715     {
00716         fprintf(stderr, "Failed to get config: %s\n",
00717                 vpx_codec_err_to_string(res));
00718         return EXIT_FAILURE;
00719     }
00720 
00721     /* Now parse the remainder of the parameters. */
00722     for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step)
00723     {
00724         arg.argv_step = 1;
00725 
00726         if (0);
00727         else if (arg_match(&arg, &threads, argi))
00728             cfg.g_threads = arg_parse_uint(&arg);
00729         else if (arg_match(&arg, &profile, argi))
00730             cfg.g_profile = arg_parse_uint(&arg);
00731         else if (arg_match(&arg, &width, argi))
00732             cfg.g_w = arg_parse_uint(&arg);
00733         else if (arg_match(&arg, &height, argi))
00734             cfg.g_h = arg_parse_uint(&arg);
00735         else if (arg_match(&arg, &timebase, argi))
00736         {
00737             cfg.g_timebase = arg_parse_rational(&arg);
00738             arg_have_timebase = 1;
00739         }
00740         else if (arg_match(&arg, &error_resilient, argi))
00741             cfg.g_error_resilient = arg_parse_uint(&arg);
00742         else if (arg_match(&arg, &lag_in_frames, argi))
00743             cfg.g_lag_in_frames = arg_parse_uint(&arg);
00744         else if (arg_match(&arg, &dropframe_thresh, argi))
00745             cfg.rc_dropframe_thresh = arg_parse_uint(&arg);
00746         else if (arg_match(&arg, &resize_allowed, argi))
00747             cfg.rc_resize_allowed = arg_parse_uint(&arg);
00748         else if (arg_match(&arg, &resize_up_thresh, argi))
00749             cfg.rc_resize_up_thresh = arg_parse_uint(&arg);
00750         else if (arg_match(&arg, &resize_down_thresh, argi))
00751             cfg.rc_resize_down_thresh = arg_parse_uint(&arg);
00752         else if (arg_match(&arg, &resize_down_thresh, argi))
00753             cfg.rc_resize_down_thresh = arg_parse_uint(&arg);
00754         else if (arg_match(&arg, &end_usage, argi))
00755             cfg.rc_end_usage = arg_parse_uint(&arg);
00756         else if (arg_match(&arg, &target_bitrate, argi))
00757             cfg.rc_target_bitrate = arg_parse_uint(&arg);
00758         else if (arg_match(&arg, &min_quantizer, argi))
00759             cfg.rc_min_quantizer = arg_parse_uint(&arg);
00760         else if (arg_match(&arg, &max_quantizer, argi))
00761             cfg.rc_max_quantizer = arg_parse_uint(&arg);
00762         else if (arg_match(&arg, &undershoot_pct, argi))
00763             cfg.rc_undershoot_pct = arg_parse_uint(&arg);
00764         else if (arg_match(&arg, &overshoot_pct, argi))
00765             cfg.rc_overshoot_pct = arg_parse_uint(&arg);
00766         else if (arg_match(&arg, &buf_sz, argi))
00767             cfg.rc_buf_sz = arg_parse_uint(&arg);
00768         else if (arg_match(&arg, &buf_initial_sz, argi))
00769             cfg.rc_buf_initial_sz = arg_parse_uint(&arg);
00770         else if (arg_match(&arg, &buf_optimal_sz, argi))
00771             cfg.rc_buf_optimal_sz = arg_parse_uint(&arg);
00772         else if (arg_match(&arg, &bias_pct, argi))
00773         {
00774             cfg.rc_2pass_vbr_bias_pct = arg_parse_uint(&arg);
00775 
00776             if (arg_passes < 2)
00777                 fprintf(stderr,
00778                         "Warning: option %s ignored in one-pass mode.\n",
00779                         arg.name);
00780         }
00781         else if (arg_match(&arg, &minsection_pct, argi))
00782         {
00783             cfg.rc_2pass_vbr_minsection_pct = arg_parse_uint(&arg);
00784 
00785             if (arg_passes < 2)
00786                 fprintf(stderr,
00787                         "Warning: option %s ignored in one-pass mode.\n",
00788                         arg.name);
00789         }
00790         else if (arg_match(&arg, &maxsection_pct, argi))
00791         {
00792             cfg.rc_2pass_vbr_maxsection_pct = arg_parse_uint(&arg);
00793 
00794             if (arg_passes < 2)
00795                 fprintf(stderr,
00796                         "Warning: option %s ignored in one-pass mode.\n",
00797                         arg.name);
00798         }
00799         else if (arg_match(&arg, &kf_min_dist, argi))
00800             cfg.kf_min_dist = arg_parse_uint(&arg);
00801         else if (arg_match(&arg, &kf_max_dist, argi))
00802             cfg.kf_max_dist = arg_parse_uint(&arg);
00803         else
00804             argj++;
00805     }
00806 
00807     /* Handle codec specific options */
00808 #if CONFIG_VP8_ENCODER
00809 
00810     if (codec->iface == &vpx_codec_vp8_cx_algo)
00811     {
00812         ctrl_args = vp8_args;
00813         ctrl_args_map = vp8_arg_ctrl_map;
00814     }
00815 
00816 #endif
00817 
00818     for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step)
00819     {
00820         int match = 0;
00821 
00822         arg.argv_step = 1;
00823 
00824         for (i = 0; ctrl_args[i]; i++)
00825         {
00826             if (arg_match(&arg, ctrl_args[i], argi))
00827             {
00828                 match = 1;
00829 
00830                 if (arg_ctrl_cnt < ARG_CTRL_CNT_MAX)
00831                 {
00832                     arg_ctrls[arg_ctrl_cnt][0] = ctrl_args_map[i];
00833                     arg_ctrls[arg_ctrl_cnt][1] = arg_parse_int(&arg);
00834                     arg_ctrl_cnt++;
00835                 }
00836             }
00837         }
00838 
00839         if (!match)
00840             argj++;
00841     }
00842 
00843     /* Check for unrecognized options */
00844     for (argi = argv; *argi; argi++)
00845         if (argi[0][0] == '-' && argi[0][1])
00846             die("Error: Unrecognized option %s\n", *argi);
00847 
00848     /* Handle non-option arguments */
00849     in_fn = argv[0];
00850     out_fn = argv[1];
00851 
00852     if (!in_fn || !out_fn)
00853         usage_exit();
00854 
00855     memset(&stats, 0, sizeof(stats));
00856 
00857     for (pass = one_pass_only ? one_pass_only - 1 : 0; pass < arg_passes; pass++)
00858     {
00859         int frames_in = 0, frames_out = 0;
00860         unsigned long nbytes = 0;
00861         struct detect_buffer detect;
00862 
00863         /* Parse certain options from the input file, if possible */
00864         infile = strcmp(in_fn, "-") ? fopen(in_fn, "rb") : stdin;
00865 
00866         if (!infile)
00867         {
00868             fprintf(stderr, "Failed to open input file\n");
00869             return EXIT_FAILURE;
00870         }
00871 
00872         fread(detect.buf, 1, 4, infile);
00873         detect.valid = 0;
00874 
00875         if (file_is_y4m(infile, &y4m, detect.buf))
00876         {
00877             if (y4m_input_open(&y4m, infile, detect.buf, 4) >= 0)
00878             {
00879                 file_type = FILE_TYPE_Y4M;
00880                 cfg.g_w = y4m.pic_w;
00881                 cfg.g_h = y4m.pic_h;
00882                 /* Use the frame rate from the file only if none was specified
00883                  * on the command-line.
00884                  */
00885                 if (!arg_have_timebase)
00886                 {
00887                     cfg.g_timebase.num = y4m.fps_d;
00888                     cfg.g_timebase.den = y4m.fps_n;
00889                 }
00890                 arg_use_i420 = 0;
00891             }
00892             else
00893             {
00894                 fprintf(stderr, "Unsupported Y4M stream.\n");
00895                 return EXIT_FAILURE;
00896             }
00897         }
00898         else if (file_is_ivf(infile, &fourcc, &cfg.g_w, &cfg.g_h, detect.buf))
00899         {
00900             file_type = FILE_TYPE_IVF;
00901             switch (fourcc)
00902             {
00903             case 0x32315659:
00904                 arg_use_i420 = 0;
00905                 break;
00906             case 0x30323449:
00907                 arg_use_i420 = 1;
00908                 break;
00909             default:
00910                 fprintf(stderr, "Unsupported fourcc (%08x) in IVF\n", fourcc);
00911                 return EXIT_FAILURE;
00912             }
00913         }
00914         else
00915         {
00916             file_type = FILE_TYPE_RAW;
00917             detect.valid = 1;
00918         }
00919 #define SHOW(field) fprintf(stderr, "    %-28s = %d\n", #field, cfg.field)
00920 
00921         if (verbose && pass == 0)
00922         {
00923             fprintf(stderr, "Codec: %s\n", vpx_codec_iface_name(codec->iface));
00924             fprintf(stderr, "Source file: %s Format: %s\n", in_fn,
00925                     arg_use_i420 ? "I420" : "YV12");
00926             fprintf(stderr, "Destination file: %s\n", out_fn);
00927             fprintf(stderr, "Encoder parameters:\n");
00928 
00929             SHOW(g_usage);
00930             SHOW(g_threads);
00931             SHOW(g_profile);
00932             SHOW(g_w);
00933             SHOW(g_h);
00934             SHOW(g_timebase.num);
00935             SHOW(g_timebase.den);
00936             SHOW(g_error_resilient);
00937             SHOW(g_pass);
00938             SHOW(g_lag_in_frames);
00939             SHOW(rc_dropframe_thresh);
00940             SHOW(rc_resize_allowed);
00941             SHOW(rc_resize_up_thresh);
00942             SHOW(rc_resize_down_thresh);
00943             SHOW(rc_end_usage);
00944             SHOW(rc_target_bitrate);
00945             SHOW(rc_min_quantizer);
00946             SHOW(rc_max_quantizer);
00947             SHOW(rc_undershoot_pct);
00948             SHOW(rc_overshoot_pct);
00949             SHOW(rc_buf_sz);
00950             SHOW(rc_buf_initial_sz);
00951             SHOW(rc_buf_optimal_sz);
00952             SHOW(rc_2pass_vbr_bias_pct);
00953             SHOW(rc_2pass_vbr_minsection_pct);
00954             SHOW(rc_2pass_vbr_maxsection_pct);
00955             SHOW(kf_mode);
00956             SHOW(kf_min_dist);
00957             SHOW(kf_max_dist);
00958         }
00959 
00960         if(pass == (one_pass_only ? one_pass_only - 1 : 0)) {
00961             if (file_type == FILE_TYPE_Y4M)
00962                 /*The Y4M reader does its own allocation.
00963                   Just initialize this here to avoid problems if we never read any
00964                    frames.*/
00965                 memset(&raw, 0, sizeof(raw));
00966             else
00967                 vpx_img_alloc(&raw, arg_use_i420 ? VPX_IMG_FMT_I420 : VPX_IMG_FMT_YV12,
00968                               cfg.g_w, cfg.g_h, 1);
00969 
00970             // This was added so that ivfenc will create monotically increasing
00971             // timestamps.  Since we create new timestamps for alt-reference frames
00972             // we need to make room in the series of timestamps.  Since there can
00973             // only be 1 alt-ref frame ( current bitstream) multiplying by 2
00974             // gives us enough room.
00975             cfg.g_timebase.den *= 2;
00976         }
00977 
00978         outfile = strcmp(out_fn, "-") ? fopen(out_fn, "wb") : stdout;
00979 
00980         if (!outfile)
00981         {
00982             fprintf(stderr, "Failed to open output file\n");
00983             return EXIT_FAILURE;
00984         }
00985 
00986         if (stats_fn)
00987         {
00988             if (!stats_open_file(&stats, stats_fn, pass))
00989             {
00990                 fprintf(stderr, "Failed to open statistics store\n");
00991                 return EXIT_FAILURE;
00992             }
00993         }
00994         else
00995         {
00996             if (!stats_open_mem(&stats, pass))
00997             {
00998                 fprintf(stderr, "Failed to open statistics store\n");
00999                 return EXIT_FAILURE;
01000             }
01001         }
01002 
01003         cfg.g_pass = arg_passes == 2
01004                      ? pass ? VPX_RC_LAST_PASS : VPX_RC_FIRST_PASS
01005                  : VPX_RC_ONE_PASS;
01006 #if VPX_ENCODER_ABI_VERSION > (1 + VPX_CODEC_ABI_VERSION)
01007 
01008         if (pass)
01009         {
01010             cfg.rc_twopass_stats_in = stats_get(&stats);
01011         }
01012 
01013 #endif
01014 
01015         write_ivf_file_header(outfile, &cfg, codec->fourcc, 0);
01016 
01017 
01018         /* Construct Encoder Context */
01019         if (cfg.kf_min_dist == cfg.kf_max_dist)
01020             cfg.kf_mode = VPX_KF_FIXED;
01021 
01022         vpx_codec_enc_init(&encoder, codec->iface, &cfg,
01023                            show_psnr ? VPX_CODEC_USE_PSNR : 0);
01024         ctx_exit_on_error(&encoder, "Failed to initialize encoder");
01025 
01026         /* Note that we bypass the vpx_codec_control wrapper macro because
01027          * we're being clever to store the control IDs in an array. Real
01028          * applications will want to make use of the enumerations directly
01029          */
01030         for (i = 0; i < arg_ctrl_cnt; i++)
01031         {
01032             if (vpx_codec_control_(&encoder, arg_ctrls[i][0], arg_ctrls[i][1]))
01033                 fprintf(stderr, "Error: Tried to set control %d = %d\n",
01034                         arg_ctrls[i][0], arg_ctrls[i][1]);
01035 
01036             ctx_exit_on_error(&encoder, "Failed to control codec");
01037         }
01038 
01039         frame_avail = 1;
01040         got_data = 0;
01041 
01042         while (frame_avail || got_data)
01043         {
01044             vpx_codec_iter_t iter = NULL;
01045             const vpx_codec_cx_pkt_t *pkt;
01046             struct vpx_usec_timer timer;
01047 
01048             if (!arg_limit || frames_in < arg_limit)
01049             {
01050                 frame_avail = read_frame(infile, &raw, file_type, &y4m,
01051                                          &detect);
01052 
01053                 if (frame_avail)
01054                     frames_in++;
01055 
01056                 fprintf(stderr,
01057                         "\rPass %d/%d frame %4d/%-4d %7ldB \033[K", pass + 1,
01058                         arg_passes, frames_in, frames_out, nbytes);
01059             }
01060             else
01061                 frame_avail = 0;
01062 
01063             vpx_usec_timer_start(&timer);
01064 
01065             // since we halved our timebase we need to double the timestamps
01066             // and duration we pass in.
01067             vpx_codec_encode(&encoder, frame_avail ? &raw : NULL, (frames_in - 1) * 2,
01068                              2, 0, arg_deadline);
01069             vpx_usec_timer_mark(&timer);
01070             cx_time += vpx_usec_timer_elapsed(&timer);
01071             ctx_exit_on_error(&encoder, "Failed to encode frame");
01072             got_data = 0;
01073 
01074             while ((pkt = vpx_codec_get_cx_data(&encoder, &iter)))
01075             {
01076                 got_data = 1;
01077 
01078                 switch (pkt->kind)
01079                 {
01080                 case VPX_CODEC_CX_FRAME_PKT:
01081                     frames_out++;
01082                     fprintf(stderr, " %6luF",
01083                             (unsigned long)pkt->data.frame.sz);
01084                     write_ivf_frame_header(outfile, pkt);
01085                     fwrite(pkt->data.frame.buf, 1, pkt->data.frame.sz, outfile);
01086                     nbytes += pkt->data.raw.sz;
01087                     break;
01088                 case VPX_CODEC_STATS_PKT:
01089                     frames_out++;
01090                     fprintf(stderr, " %6luS",
01091                            (unsigned long)pkt->data.twopass_stats.sz);
01092                     stats_write(&stats,
01093                                 pkt->data.twopass_stats.buf,
01094                                 pkt->data.twopass_stats.sz);
01095                     nbytes += pkt->data.raw.sz;
01096                     break;
01097                 case VPX_CODEC_PSNR_PKT:
01098 
01099                     if (show_psnr)
01100                     {
01101                         int i;
01102 
01103                         for (i = 0; i < 4; i++)
01104                             fprintf(stderr, "%.3lf ", pkt->data.psnr.psnr[i]);
01105                     }
01106 
01107                     break;
01108                 default:
01109                     break;
01110                 }
01111             }
01112 
01113             fflush(stdout);
01114         }
01115 
01116         /* this bitrate calc is simplified and relies on the fact that this
01117          * application uses 1/timebase for framerate.
01118          */
01119         fprintf(stderr,
01120                "\rPass %d/%d frame %4d/%-4d %7ldB %7ldb/f %7"PRId64"b/s"
01121                " %7lu %s (%.2f fps)\033[K", pass + 1,
01122                arg_passes, frames_in, frames_out, nbytes, nbytes * 8 / frames_in,
01123                nbytes * 8 *(int64_t)cfg.g_timebase.den/2/ cfg.g_timebase.num / frames_in,
01124                cx_time > 9999999 ? cx_time / 1000 : cx_time,
01125                cx_time > 9999999 ? "ms" : "us",
01126                (float)frames_in * 1000000.0 / (float)cx_time);
01127 
01128         vpx_codec_destroy(&encoder);
01129 
01130         fclose(infile);
01131 
01132         if (!fseek(outfile, 0, SEEK_SET))
01133             write_ivf_file_header(outfile, &cfg, codec->fourcc, frames_out);
01134 
01135         fclose(outfile);
01136         stats_close(&stats);
01137         fprintf(stderr, "\n");
01138 
01139         if (one_pass_only)
01140             break;
01141     }
01142 
01143     vpx_img_free(&raw);
01144     free(argv);
01145     return EXIT_SUCCESS;
01146 }
Generated on Fri Aug 27 07:01:09 2010 for WebM VP8 Codec SDK by  doxygen 1.6.3