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_disabled = ARG_DEF(NULL, "disable-kf", 0,
00509                                      "Disable keyframe placement");
00510 static const arg_def_t *kf_args[] =
00511 {
00512     &kf_min_dist, &kf_max_dist, &kf_disabled, NULL
00513 };
00514 
00515 
00516 #if CONFIG_VP8_ENCODER
00517 static const arg_def_t noise_sens = ARG_DEF(NULL, "noise-sensitivity", 1,
00518                                     "Noise sensitivity (frames to blur)");
00519 static const arg_def_t sharpness = ARG_DEF(NULL, "sharpness", 1,
00520                                    "Filter sharpness (0-7)");
00521 static const arg_def_t static_thresh = ARG_DEF(NULL, "static-thresh", 1,
00522                                        "Motion detection threshold");
00523 #endif
00524 
00525 #if CONFIG_VP8_ENCODER
00526 static const arg_def_t cpu_used = ARG_DEF(NULL, "cpu-used", 1,
00527                                   "CPU Used (-16..16)");
00528 #endif
00529 
00530 
00531 #if CONFIG_VP8_ENCODER
00532 static const arg_def_t token_parts = ARG_DEF(NULL, "token-parts", 1,
00533                                      "Number of token partitions to use, log2");
00534 static const arg_def_t auto_altref = ARG_DEF(NULL, "auto-alt-ref", 1,
00535                                      "Enable automatic alt reference frames");
00536 static const arg_def_t arnr_maxframes = ARG_DEF(NULL, "arnr-maxframes", 1,
00537                                         "alt_ref Max Frames");
00538 static const arg_def_t arnr_strength = ARG_DEF(NULL, "arnr-strength", 1,
00539                                        "alt_ref Strength");
00540 static const arg_def_t arnr_type = ARG_DEF(NULL, "arnr-type", 1,
00541                                    "alt_ref Type");
00542 
00543 static const arg_def_t *vp8_args[] =
00544 {
00545     &cpu_used, &auto_altref, &noise_sens, &sharpness, &static_thresh,
00546     &token_parts, &arnr_maxframes, &arnr_strength, &arnr_type, NULL
00547 };
00548 static const int vp8_arg_ctrl_map[] =
00549 {
00550     VP8E_SET_CPUUSED, VP8E_SET_ENABLEAUTOALTREF,
00551     VP8E_SET_NOISE_SENSITIVITY, VP8E_SET_SHARPNESS, VP8E_SET_STATIC_THRESHOLD,
00552     VP8E_SET_TOKEN_PARTITIONS,
00553     VP8E_SET_ARNR_MAXFRAMES, VP8E_SET_ARNR_STRENGTH , VP8E_SET_ARNR_TYPE, 0
00554 };
00555 #endif
00556 
00557 static const arg_def_t *no_args[] = { NULL };
00558 
00559 static void usage_exit()
00560 {
00561     int i;
00562 
00563     fprintf(stderr, "Usage: %s <options> src_filename dst_filename\n", exec_name);
00564 
00565     fprintf(stderr, "\n_options:\n");
00566     arg_show_usage(stdout, main_args);
00567     fprintf(stderr, "\n_encoder Global Options:\n");
00568     arg_show_usage(stdout, global_args);
00569     fprintf(stderr, "\n_rate Control Options:\n");
00570     arg_show_usage(stdout, rc_args);
00571     fprintf(stderr, "\n_twopass Rate Control Options:\n");
00572     arg_show_usage(stdout, rc_twopass_args);
00573     fprintf(stderr, "\n_keyframe Placement Options:\n");
00574     arg_show_usage(stdout, kf_args);
00575 #if CONFIG_VP8_ENCODER
00576     fprintf(stderr, "\n_vp8 Specific Options:\n");
00577     arg_show_usage(stdout, vp8_args);
00578 #endif
00579     fprintf(stderr, "\n"
00580            "Included encoders:\n"
00581            "\n");
00582 
00583     for (i = 0; i < sizeof(codecs) / sizeof(codecs[0]); i++)
00584         fprintf(stderr, "    %-6s - %s\n",
00585                codecs[i].name,
00586                vpx_codec_iface_name(codecs[i].iface));
00587 
00588     exit(EXIT_FAILURE);
00589 }
00590 
00591 #define ARG_CTRL_CNT_MAX 10
00592 
00593 
00594 int main(int argc, const char **argv_)
00595 {
00596     vpx_codec_ctx_t        encoder;
00597     const char                  *in_fn = NULL, *out_fn = NULL, *stats_fn = NULL;
00598     int                    i;
00599     FILE                  *infile, *outfile;
00600     vpx_codec_enc_cfg_t    cfg;
00601     vpx_codec_err_t        res;
00602     int                    pass, one_pass_only = 0;
00603     stats_io_t             stats;
00604     vpx_image_t            raw;
00605     const struct codec_item  *codec = codecs;
00606     int                    frame_avail, got_data;
00607 
00608     struct arg               arg;
00609     char                   **argv, **argi, **argj;
00610     int                      arg_usage = 0, arg_passes = 1, arg_deadline = 0;
00611     int                      arg_ctrls[ARG_CTRL_CNT_MAX][2], arg_ctrl_cnt = 0;
00612     int                      arg_limit = 0;
00613     static const arg_def_t **ctrl_args = no_args;
00614     static const int        *ctrl_args_map = NULL;
00615     int                      verbose = 0, show_psnr = 0;
00616     int                      arg_use_i420 = 1;
00617     int                      arg_have_timebase = 0;
00618     unsigned long            cx_time = 0;
00619     unsigned int             file_type, fourcc;
00620     y4m_input                y4m;
00621 
00622     exec_name = argv_[0];
00623 
00624     if (argc < 3)
00625         usage_exit();
00626 
00627 
00628     /* First parse the codec and usage values, because we want to apply other
00629      * parameters on top of the default configuration provided by the codec.
00630      */
00631     argv = argv_dup(argc - 1, argv_ + 1);
00632 
00633     for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step)
00634     {
00635         arg.argv_step = 1;
00636 
00637         if (arg_match(&arg, &codecarg, argi))
00638         {
00639             int j, k = -1;
00640 
00641             for (j = 0; j < sizeof(codecs) / sizeof(codecs[0]); j++)
00642                 if (!strcmp(codecs[j].name, arg.val))
00643                     k = j;
00644 
00645             if (k >= 0)
00646                 codec = codecs + k;
00647             else
00648                 die("Error: Unrecognized argument (%s) to --codec\n",
00649                     arg.val);
00650 
00651         }
00652         else if (arg_match(&arg, &passes, argi))
00653         {
00654             arg_passes = arg_parse_uint(&arg);
00655 
00656             if (arg_passes < 1 || arg_passes > 2)
00657                 die("Error: Invalid number of passes (%d)\n", arg_passes);
00658         }
00659         else if (arg_match(&arg, &pass_arg, argi))
00660         {
00661             one_pass_only = arg_parse_uint(&arg);
00662 
00663             if (one_pass_only < 1 || one_pass_only > 2)
00664                 die("Error: Invalid pass selected (%d)\n", one_pass_only);
00665         }
00666         else if (arg_match(&arg, &fpf_name, argi))
00667             stats_fn = arg.val;
00668         else if (arg_match(&arg, &usage, argi))
00669             arg_usage = arg_parse_uint(&arg);
00670         else if (arg_match(&arg, &deadline, argi))
00671             arg_deadline = arg_parse_uint(&arg);
00672         else if (arg_match(&arg, &best_dl, argi))
00673             arg_deadline = VPX_DL_BEST_QUALITY;
00674         else if (arg_match(&arg, &good_dl, argi))
00675             arg_deadline = VPX_DL_GOOD_QUALITY;
00676         else if (arg_match(&arg, &rt_dl, argi))
00677             arg_deadline = VPX_DL_REALTIME;
00678         else if (arg_match(&arg, &use_yv12, argi))
00679         {
00680             arg_use_i420 = 0;
00681         }
00682         else if (arg_match(&arg, &use_i420, argi))
00683         {
00684             arg_use_i420 = 1;
00685         }
00686         else if (arg_match(&arg, &verbosearg, argi))
00687             verbose = 1;
00688         else if (arg_match(&arg, &limit, argi))
00689             arg_limit = arg_parse_uint(&arg);
00690         else if (arg_match(&arg, &psnrarg, argi))
00691             show_psnr = 1;
00692         else
00693             argj++;
00694     }
00695 
00696     /* Ensure that --passes and --pass are consistent. If --pass is set and --passes=2,
00697      * ensure --fpf was set.
00698      */
00699     if (one_pass_only)
00700     {
00701         /* DWIM: Assume the user meant passes=2 if pass=2 is specified */
00702         if (one_pass_only > arg_passes)
00703         {
00704             fprintf(stderr, "Warning: Assuming --pass=%d implies --passes=%d\n",
00705                    one_pass_only, one_pass_only);
00706             arg_passes = one_pass_only;
00707         }
00708 
00709         if (arg_passes == 2 && !stats_fn)
00710             die("Must specify --fpf when --pass=%d and --passes=2\n", one_pass_only);
00711     }
00712 
00713     /* Populate encoder configuration */
00714     res = vpx_codec_enc_config_default(codec->iface, &cfg, arg_usage);
00715 
00716     if (res)
00717     {
00718         fprintf(stderr, "Failed to get config: %s\n",
00719                 vpx_codec_err_to_string(res));
00720         return EXIT_FAILURE;
00721     }
00722 
00723     /* Now parse the remainder of the parameters. */
00724     for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step)
00725     {
00726         arg.argv_step = 1;
00727 
00728         if (0);
00729         else if (arg_match(&arg, &threads, argi))
00730             cfg.g_threads = arg_parse_uint(&arg);
00731         else if (arg_match(&arg, &profile, argi))
00732             cfg.g_profile = arg_parse_uint(&arg);
00733         else if (arg_match(&arg, &width, argi))
00734             cfg.g_w = arg_parse_uint(&arg);
00735         else if (arg_match(&arg, &height, argi))
00736             cfg.g_h = arg_parse_uint(&arg);
00737         else if (arg_match(&arg, &timebase, argi))
00738         {
00739             cfg.g_timebase = arg_parse_rational(&arg);
00740             arg_have_timebase = 1;
00741         }
00742         else if (arg_match(&arg, &error_resilient, argi))
00743             cfg.g_error_resilient = arg_parse_uint(&arg);
00744         else if (arg_match(&arg, &lag_in_frames, argi))
00745             cfg.g_lag_in_frames = arg_parse_uint(&arg);
00746         else if (arg_match(&arg, &dropframe_thresh, argi))
00747             cfg.rc_dropframe_thresh = arg_parse_uint(&arg);
00748         else if (arg_match(&arg, &resize_allowed, argi))
00749             cfg.rc_resize_allowed = arg_parse_uint(&arg);
00750         else if (arg_match(&arg, &resize_up_thresh, argi))
00751             cfg.rc_resize_up_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, &resize_down_thresh, argi))
00755             cfg.rc_resize_down_thresh = arg_parse_uint(&arg);
00756         else if (arg_match(&arg, &end_usage, argi))
00757             cfg.rc_end_usage = arg_parse_uint(&arg);
00758         else if (arg_match(&arg, &target_bitrate, argi))
00759             cfg.rc_target_bitrate = arg_parse_uint(&arg);
00760         else if (arg_match(&arg, &min_quantizer, argi))
00761             cfg.rc_min_quantizer = arg_parse_uint(&arg);
00762         else if (arg_match(&arg, &max_quantizer, argi))
00763             cfg.rc_max_quantizer = arg_parse_uint(&arg);
00764         else if (arg_match(&arg, &undershoot_pct, argi))
00765             cfg.rc_undershoot_pct = arg_parse_uint(&arg);
00766         else if (arg_match(&arg, &overshoot_pct, argi))
00767             cfg.rc_overshoot_pct = arg_parse_uint(&arg);
00768         else if (arg_match(&arg, &buf_sz, argi))
00769             cfg.rc_buf_sz = arg_parse_uint(&arg);
00770         else if (arg_match(&arg, &buf_initial_sz, argi))
00771             cfg.rc_buf_initial_sz = arg_parse_uint(&arg);
00772         else if (arg_match(&arg, &buf_optimal_sz, argi))
00773             cfg.rc_buf_optimal_sz = arg_parse_uint(&arg);
00774         else if (arg_match(&arg, &bias_pct, argi))
00775         {
00776             cfg.rc_2pass_vbr_bias_pct = arg_parse_uint(&arg);
00777 
00778             if (arg_passes < 2)
00779                 fprintf(stderr,
00780                         "Warning: option %s ignored in one-pass mode.\n",
00781                         arg.name);
00782         }
00783         else if (arg_match(&arg, &minsection_pct, argi))
00784         {
00785             cfg.rc_2pass_vbr_minsection_pct = arg_parse_uint(&arg);
00786 
00787             if (arg_passes < 2)
00788                 fprintf(stderr,
00789                         "Warning: option %s ignored in one-pass mode.\n",
00790                         arg.name);
00791         }
00792         else if (arg_match(&arg, &maxsection_pct, argi))
00793         {
00794             cfg.rc_2pass_vbr_maxsection_pct = arg_parse_uint(&arg);
00795 
00796             if (arg_passes < 2)
00797                 fprintf(stderr,
00798                         "Warning: option %s ignored in one-pass mode.\n",
00799                         arg.name);
00800         }
00801         else if (arg_match(&arg, &kf_min_dist, argi))
00802             cfg.kf_min_dist = arg_parse_uint(&arg);
00803         else if (arg_match(&arg, &kf_max_dist, argi))
00804             cfg.kf_max_dist = arg_parse_uint(&arg);
00805         else if (arg_match(&arg, &kf_disabled, argi))
00806             cfg.kf_mode = VPX_KF_DISABLED;
00807         else
00808             argj++;
00809     }
00810 
00811     /* Handle codec specific options */
00812 #if CONFIG_VP8_ENCODER
00813 
00814     if (codec->iface == &vpx_codec_vp8_cx_algo)
00815     {
00816         ctrl_args = vp8_args;
00817         ctrl_args_map = vp8_arg_ctrl_map;
00818     }
00819 
00820 #endif
00821 
00822     for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step)
00823     {
00824         int match = 0;
00825 
00826         arg.argv_step = 1;
00827 
00828         for (i = 0; ctrl_args[i]; i++)
00829         {
00830             if (arg_match(&arg, ctrl_args[i], argi))
00831             {
00832                 match = 1;
00833 
00834                 if (arg_ctrl_cnt < ARG_CTRL_CNT_MAX)
00835                 {
00836                     arg_ctrls[arg_ctrl_cnt][0] = ctrl_args_map[i];
00837                     arg_ctrls[arg_ctrl_cnt][1] = arg_parse_int(&arg);
00838                     arg_ctrl_cnt++;
00839                 }
00840             }
00841         }
00842 
00843         if (!match)
00844             argj++;
00845     }
00846 
00847     /* Check for unrecognized options */
00848     for (argi = argv; *argi; argi++)
00849         if (argi[0][0] == '-' && argi[0][1])
00850             die("Error: Unrecognized option %s\n", *argi);
00851 
00852     /* Handle non-option arguments */
00853     in_fn = argv[0];
00854     out_fn = argv[1];
00855 
00856     if (!in_fn || !out_fn)
00857         usage_exit();
00858 
00859     memset(&stats, 0, sizeof(stats));
00860 
00861     for (pass = one_pass_only ? one_pass_only - 1 : 0; pass < arg_passes; pass++)
00862     {
00863         int frames_in = 0, frames_out = 0;
00864         unsigned long nbytes = 0;
00865         struct detect_buffer detect;
00866 
00867         /* Parse certain options from the input file, if possible */
00868         infile = strcmp(in_fn, "-") ? fopen(in_fn, "rb") : stdin;
00869 
00870         if (!infile)
00871         {
00872             fprintf(stderr, "Failed to open input file\n");
00873             return EXIT_FAILURE;
00874         }
00875 
00876         fread(detect.buf, 1, 4, infile);
00877         detect.valid = 0;
00878 
00879         if (file_is_y4m(infile, &y4m, detect.buf))
00880         {
00881             if (y4m_input_open(&y4m, infile, detect.buf, 4) >= 0)
00882             {
00883                 file_type = FILE_TYPE_Y4M;
00884                 cfg.g_w = y4m.pic_w;
00885                 cfg.g_h = y4m.pic_h;
00886                 /* Use the frame rate from the file only if none was specified
00887                  * on the command-line.
00888                  */
00889                 if (!arg_have_timebase)
00890                 {
00891                     cfg.g_timebase.num = y4m.fps_d;
00892                     cfg.g_timebase.den = y4m.fps_n;
00893                     /* And don't reset it in the second pass.*/
00894                     arg_have_timebase = 1;
00895                 }
00896                 arg_use_i420 = 0;
00897             }
00898             else
00899             {
00900                 fprintf(stderr, "Unsupported Y4M stream.\n");
00901                 return EXIT_FAILURE;
00902             }
00903         }
00904         else if (file_is_ivf(infile, &fourcc, &cfg.g_w, &cfg.g_h, detect.buf))
00905         {
00906             file_type = FILE_TYPE_IVF;
00907             switch (fourcc)
00908             {
00909             case 0x32315659:
00910                 arg_use_i420 = 0;
00911                 break;
00912             case 0x30323449:
00913                 arg_use_i420 = 1;
00914                 break;
00915             default:
00916                 fprintf(stderr, "Unsupported fourcc (%08x) in IVF\n", fourcc);
00917                 return EXIT_FAILURE;
00918             }
00919         }
00920         else
00921         {
00922             file_type = FILE_TYPE_RAW;
00923             detect.valid = 1;
00924         }
00925 #define SHOW(field) fprintf(stderr, "    %-28s = %d\n", #field, cfg.field)
00926 
00927         if (verbose && pass == 0)
00928         {
00929             fprintf(stderr, "Codec: %s\n", vpx_codec_iface_name(codec->iface));
00930             fprintf(stderr, "Source file: %s Format: %s\n", in_fn,
00931                     arg_use_i420 ? "I420" : "YV12");
00932             fprintf(stderr, "Destination file: %s\n", out_fn);
00933             fprintf(stderr, "Encoder parameters:\n");
00934 
00935             SHOW(g_usage);
00936             SHOW(g_threads);
00937             SHOW(g_profile);
00938             SHOW(g_w);
00939             SHOW(g_h);
00940             SHOW(g_timebase.num);
00941             SHOW(g_timebase.den);
00942             SHOW(g_error_resilient);
00943             SHOW(g_pass);
00944             SHOW(g_lag_in_frames);
00945             SHOW(rc_dropframe_thresh);
00946             SHOW(rc_resize_allowed);
00947             SHOW(rc_resize_up_thresh);
00948             SHOW(rc_resize_down_thresh);
00949             SHOW(rc_end_usage);
00950             SHOW(rc_target_bitrate);
00951             SHOW(rc_min_quantizer);
00952             SHOW(rc_max_quantizer);
00953             SHOW(rc_undershoot_pct);
00954             SHOW(rc_overshoot_pct);
00955             SHOW(rc_buf_sz);
00956             SHOW(rc_buf_initial_sz);
00957             SHOW(rc_buf_optimal_sz);
00958             SHOW(rc_2pass_vbr_bias_pct);
00959             SHOW(rc_2pass_vbr_minsection_pct);
00960             SHOW(rc_2pass_vbr_maxsection_pct);
00961             SHOW(kf_mode);
00962             SHOW(kf_min_dist);
00963             SHOW(kf_max_dist);
00964         }
00965 
00966         if(pass == (one_pass_only ? one_pass_only - 1 : 0)) {
00967             if (file_type == FILE_TYPE_Y4M)
00968                 /*The Y4M reader does its own allocation.
00969                   Just initialize this here to avoid problems if we never read any
00970                    frames.*/
00971                 memset(&raw, 0, sizeof(raw));
00972             else
00973                 vpx_img_alloc(&raw, arg_use_i420 ? VPX_IMG_FMT_I420 : VPX_IMG_FMT_YV12,
00974                               cfg.g_w, cfg.g_h, 1);
00975 
00976             // This was added so that ivfenc will create monotically increasing
00977             // timestamps.  Since we create new timestamps for alt-reference frames
00978             // we need to make room in the series of timestamps.  Since there can
00979             // only be 1 alt-ref frame ( current bitstream) multiplying by 2
00980             // gives us enough room.
00981             cfg.g_timebase.den *= 2;
00982         }
00983 
00984         outfile = strcmp(out_fn, "-") ? fopen(out_fn, "wb") : stdout;
00985 
00986         if (!outfile)
00987         {
00988             fprintf(stderr, "Failed to open output file\n");
00989             return EXIT_FAILURE;
00990         }
00991 
00992         if (stats_fn)
00993         {
00994             if (!stats_open_file(&stats, stats_fn, pass))
00995             {
00996                 fprintf(stderr, "Failed to open statistics store\n");
00997                 return EXIT_FAILURE;
00998             }
00999         }
01000         else
01001         {
01002             if (!stats_open_mem(&stats, pass))
01003             {
01004                 fprintf(stderr, "Failed to open statistics store\n");
01005                 return EXIT_FAILURE;
01006             }
01007         }
01008 
01009         cfg.g_pass = arg_passes == 2
01010                      ? pass ? VPX_RC_LAST_PASS : VPX_RC_FIRST_PASS
01011                  : VPX_RC_ONE_PASS;
01012 #if VPX_ENCODER_ABI_VERSION > (1 + VPX_CODEC_ABI_VERSION)
01013 
01014         if (pass)
01015         {
01016             cfg.rc_twopass_stats_in = stats_get(&stats);
01017         }
01018 
01019 #endif
01020 
01021         write_ivf_file_header(outfile, &cfg, codec->fourcc, 0);
01022 
01023 
01024         /* Construct Encoder Context */
01025         vpx_codec_enc_init(&encoder, codec->iface, &cfg,
01026                            show_psnr ? VPX_CODEC_USE_PSNR : 0);
01027         ctx_exit_on_error(&encoder, "Failed to initialize encoder");
01028 
01029         /* Note that we bypass the vpx_codec_control wrapper macro because
01030          * we're being clever to store the control IDs in an array. Real
01031          * applications will want to make use of the enumerations directly
01032          */
01033         for (i = 0; i < arg_ctrl_cnt; i++)
01034         {
01035             if (vpx_codec_control_(&encoder, arg_ctrls[i][0], arg_ctrls[i][1]))
01036                 fprintf(stderr, "Error: Tried to set control %d = %d\n",
01037                         arg_ctrls[i][0], arg_ctrls[i][1]);
01038 
01039             ctx_exit_on_error(&encoder, "Failed to control codec");
01040         }
01041 
01042         frame_avail = 1;
01043         got_data = 0;
01044 
01045         while (frame_avail || got_data)
01046         {
01047             vpx_codec_iter_t iter = NULL;
01048             const vpx_codec_cx_pkt_t *pkt;
01049             struct vpx_usec_timer timer;
01050 
01051             if (!arg_limit || frames_in < arg_limit)
01052             {
01053                 frame_avail = read_frame(infile, &raw, file_type, &y4m,
01054                                          &detect);
01055 
01056                 if (frame_avail)
01057                     frames_in++;
01058 
01059                 fprintf(stderr,
01060                         "\rPass %d/%d frame %4d/%-4d %7ldB \033[K", pass + 1,
01061                         arg_passes, frames_in, frames_out, nbytes);
01062             }
01063             else
01064                 frame_avail = 0;
01065 
01066             vpx_usec_timer_start(&timer);
01067 
01068             // since we halved our timebase we need to double the timestamps
01069             // and duration we pass in.
01070             vpx_codec_encode(&encoder, frame_avail ? &raw : NULL, (frames_in - 1) * 2,
01071                              2, 0, arg_deadline);
01072             vpx_usec_timer_mark(&timer);
01073             cx_time += vpx_usec_timer_elapsed(&timer);
01074             ctx_exit_on_error(&encoder, "Failed to encode frame");
01075             got_data = 0;
01076 
01077             while ((pkt = vpx_codec_get_cx_data(&encoder, &iter)))
01078             {
01079                 got_data = 1;
01080 
01081                 switch (pkt->kind)
01082                 {
01083                 case VPX_CODEC_CX_FRAME_PKT:
01084                     frames_out++;
01085                     fprintf(stderr, " %6luF",
01086                             (unsigned long)pkt->data.frame.sz);
01087                     write_ivf_frame_header(outfile, pkt);
01088                     fwrite(pkt->data.frame.buf, 1, pkt->data.frame.sz, outfile);
01089                     nbytes += pkt->data.raw.sz;
01090                     break;
01091                 case VPX_CODEC_STATS_PKT:
01092                     frames_out++;
01093                     fprintf(stderr, " %6luS",
01094                            (unsigned long)pkt->data.twopass_stats.sz);
01095                     stats_write(&stats,
01096                                 pkt->data.twopass_stats.buf,
01097                                 pkt->data.twopass_stats.sz);
01098                     nbytes += pkt->data.raw.sz;
01099                     break;
01100                 case VPX_CODEC_PSNR_PKT:
01101 
01102                     if (show_psnr)
01103                     {
01104                         int i;
01105 
01106                         for (i = 0; i < 4; i++)
01107                             fprintf(stderr, "%.3lf ", pkt->data.psnr.psnr[i]);
01108                     }
01109 
01110                     break;
01111                 default:
01112                     break;
01113                 }
01114             }
01115 
01116             fflush(stdout);
01117         }
01118 
01119         /* this bitrate calc is simplified and relies on the fact that this
01120          * application uses 1/timebase for framerate.
01121          */
01122         fprintf(stderr,
01123                "\rPass %d/%d frame %4d/%-4d %7ldB %7ldb/f %7"PRId64"b/s"
01124                " %7lu %s (%.2f fps)\033[K", pass + 1,
01125                arg_passes, frames_in, frames_out, nbytes, nbytes * 8 / frames_in,
01126                nbytes * 8 *(int64_t)cfg.g_timebase.den/2/ cfg.g_timebase.num / frames_in,
01127                cx_time > 9999999 ? cx_time / 1000 : cx_time,
01128                cx_time > 9999999 ? "ms" : "us",
01129                (float)frames_in * 1000000.0 / (float)cx_time);
01130 
01131         vpx_codec_destroy(&encoder);
01132 
01133         fclose(infile);
01134 
01135         if (!fseek(outfile, 0, SEEK_SET))
01136             write_ivf_file_header(outfile, &cfg, codec->fourcc, frames_out);
01137 
01138         fclose(outfile);
01139         stats_close(&stats);
01140         fprintf(stderr, "\n");
01141 
01142         if (one_pass_only)
01143             break;
01144     }
01145 
01146     vpx_img_free(&raw);
01147     free(argv);
01148     return EXIT_SUCCESS;
01149 }
Generated on Mon Nov 8 23:26:34 2010 for WebM VP8 Codec SDK by  doxygen 1.6.3