simple_encoder

00001 /*
00002  *  Copyright (c) 2010 The WebM 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 // Simple Encoder
00012 // ==============
00013 //
00014 // This is an example of a simple encoder loop. It takes an input file in
00015 // YV12 format, passes it through the encoder, and writes the compressed
00016 // frames to disk in IVF format. Other decoder examples build upon this
00017 // one.
00018 //
00019 // The details of the IVF format have been elided from this example for
00020 // simplicity of presentation, as IVF files will not generally be used by
00021 // your application. In general, an IVF file consists of a file header,
00022 // followed by a variable number of frames. Each frame consists of a frame
00023 // header followed by a variable length payload. The length of the payload
00024 // is specified in the first four bytes of the frame header. The payload is
00025 // the raw compressed data.
00026 //
00027 // Standard Includes
00028 // -----------------
00029 // For encoders, you only have to include `vpx_encoder.h` and then any
00030 // header files for the specific codecs you use. In this case, we're using
00031 // vp8.
00032 //
00033 // Getting The Default Configuration
00034 // ---------------------------------
00035 // Encoders have the notion of "usage profiles." For example, an encoder
00036 // may want to publish default configurations for both a video
00037 // conferencing application and a best quality offline encoder. These
00038 // obviously have very different default settings. Consult the
00039 // documentation for your codec to see if it provides any default
00040 // configurations. All codecs provide a default configuration, number 0,
00041 // which is valid for material in the vacinity of QCIF/QVGA.
00042 //
00043 // Updating The Configuration
00044 // ---------------------------------
00045 // Almost all applications will want to update the default configuration
00046 // with settings specific to their usage. Here we set the width and height
00047 // of the video file to that specified on the command line. We also scale
00048 // the default bitrate based on the ratio between the default resolution
00049 // and the resolution specified on the command line.
00050 //
00051 // Initializing The Codec
00052 // ----------------------
00053 // The encoder is initialized by the following code.
00054 //
00055 // Encoding A Frame
00056 // ----------------
00057 // The frame is read as a continuous block (size width * height * 3 / 2)
00058 // from the input file. If a frame was read (the input file has not hit
00059 // EOF) then the frame is passed to the encoder. Otherwise, a NULL
00060 // is passed, indicating the End-Of-Stream condition to the encoder. The
00061 // `frame_cnt` is reused as the presentation time stamp (PTS) and each
00062 // frame is shown for one frame-time in duration. The flags parameter is
00063 // unused in this example. The deadline is set to VPX_DL_REALTIME to
00064 // make the example run as quickly as possible.
00065 
00066 // Forced Keyframes
00067 // ----------------
00068 // Keyframes can be forced by setting the VPX_EFLAG_FORCE_KF bit of the
00069 // flags passed to `vpx_codec_control()`. In this example, we force a
00070 // keyframe every <keyframe-interval> frames. Note, the output stream can
00071 // contain additional keyframes beyond those that have been forced using the
00072 // VPX_EFLAG_FORCE_KF flag because of automatic keyframe placement by the
00073 // encoder.
00074 //
00075 // Processing The Encoded Data
00076 // ---------------------------
00077 // Each packet of type `VPX_CODEC_CX_FRAME_PKT` contains the encoded data
00078 // for this frame. We write a IVF frame header, followed by the raw data.
00079 //
00080 // Cleanup
00081 // -------
00082 // The `vpx_codec_destroy` call frees any memory allocated by the codec.
00083 //
00084 // Error Handling
00085 // --------------
00086 // This example does not special case any error return codes. If there was
00087 // an error, a descriptive message is printed and the program exits. With
00088 // few exeptions, vpx_codec functions return an enumerated error status,
00089 // with the value `0` indicating success.
00090 //
00091 // Error Resiliency Features
00092 // -------------------------
00093 // Error resiliency is controlled by the g_error_resilient member of the
00094 // configuration structure. Use the `decode_with_drops` example to decode with
00095 // frames 5-10 dropped. Compare the output for a file encoded with this example
00096 // versus one encoded with the `simple_encoder` example.
00097 
00098 #include <stdio.h>
00099 #include <stdlib.h>
00100 #include <string.h>
00101 
00102 #include "vpx/vpx_encoder.h"
00103 
00104 #include "../tools_common.h"
00105 #include "../video_writer.h"
00106 
00107 static const char *exec_name;
00108 
00109 void usage_exit(void) {
00110   fprintf(stderr,
00111           "Usage: %s <codec> <width> <height> <infile> <outfile> "
00112           "<keyframe-interval> <error-resilient> <frames to encode>\n"
00113           "See comments in simple_encoder.c for more information.\n",
00114           exec_name);
00115   exit(EXIT_FAILURE);
00116 }
00117 
00118 static int encode_frame(vpx_codec_ctx_t *codec, vpx_image_t *img,
00119                         int frame_index, int flags, VpxVideoWriter *writer) {
00120   int got_pkts = 0;
00121   vpx_codec_iter_t iter = NULL;
00122   const vpx_codec_cx_pkt_t *pkt = NULL;
00123   const vpx_codec_err_t res =
00124       vpx_codec_encode(codec, img, frame_index, 1, flags, VPX_DL_GOOD_QUALITY);
00125   if (res != VPX_CODEC_OK) die_codec(codec, "Failed to encode frame");
00126 
00127   while ((pkt = vpx_codec_get_cx_data(codec, &iter)) != NULL) {
00128     got_pkts = 1;
00129 
00130     if (pkt->kind == VPX_CODEC_CX_FRAME_PKT) {
00131       const int keyframe = (pkt->data.frame.flags & VPX_FRAME_IS_KEY) != 0;
00132       if (!vpx_video_writer_write_frame(writer, pkt->data.frame.buf,
00133                                         pkt->data.frame.sz,
00134                                         pkt->data.frame.pts)) {
00135         die_codec(codec, "Failed to write compressed frame");
00136       }
00137       printf(keyframe ? "K" : ".");
00138       fflush(stdout);
00139     }
00140   }
00141 
00142   return got_pkts;
00143 }
00144 
00145 // TODO(tomfinegan): Improve command line parsing and add args for bitrate/fps.
00146 int main(int argc, char **argv) {
00147   FILE *infile = NULL;
00148   vpx_codec_ctx_t codec;
00149   vpx_codec_enc_cfg_t cfg;
00150   int frame_count = 0;
00151   vpx_image_t raw;
00152   vpx_codec_err_t res;
00153   VpxVideoInfo info = { 0, 0, 0, { 0, 0 } };
00154   VpxVideoWriter *writer = NULL;
00155   const VpxInterface *encoder = NULL;
00156   const int fps = 30;
00157   const int bitrate = 200;
00158   int keyframe_interval = 0;
00159   int max_frames = 0;
00160   int frames_encoded = 0;
00161   const char *codec_arg = NULL;
00162   const char *width_arg = NULL;
00163   const char *height_arg = NULL;
00164   const char *infile_arg = NULL;
00165   const char *outfile_arg = NULL;
00166   const char *keyframe_interval_arg = NULL;
00167 
00168   exec_name = argv[0];
00169 
00170   if (argc != 9) die("Invalid number of arguments");
00171 
00172   codec_arg = argv[1];
00173   width_arg = argv[2];
00174   height_arg = argv[3];
00175   infile_arg = argv[4];
00176   outfile_arg = argv[5];
00177   keyframe_interval_arg = argv[6];
00178   max_frames = (int)strtol(argv[8], NULL, 0);
00179 
00180   encoder = get_vpx_encoder_by_name(codec_arg);
00181   if (!encoder) die("Unsupported codec.");
00182 
00183   info.codec_fourcc = encoder->fourcc;
00184   info.frame_width = (int)strtol(width_arg, NULL, 0);
00185   info.frame_height = (int)strtol(height_arg, NULL, 0);
00186   info.time_base.numerator = 1;
00187   info.time_base.denominator = fps;
00188 
00189   if (info.frame_width <= 0 || info.frame_height <= 0 ||
00190       (info.frame_width % 2) != 0 || (info.frame_height % 2) != 0) {
00191     die("Invalid frame size: %dx%d", info.frame_width, info.frame_height);
00192   }
00193 
00194   if (!vpx_img_alloc(&raw, VPX_IMG_FMT_I420, info.frame_width,
00195                      info.frame_height, 1)) {
00196     die("Failed to allocate image.");
00197   }
00198 
00199   keyframe_interval = (int)strtol(keyframe_interval_arg, NULL, 0);
00200   if (keyframe_interval < 0) die("Invalid keyframe interval value.");
00201 
00202   printf("Using %s\n", vpx_codec_iface_name(encoder->codec_interface()));
00203 
00204   res = vpx_codec_enc_config_default(encoder->codec_interface(), &cfg, 0);
00205   if (res) die_codec(&codec, "Failed to get default codec config.");
00206 
00207   cfg.g_w = info.frame_width;
00208   cfg.g_h = info.frame_height;
00209   cfg.g_timebase.num = info.time_base.numerator;
00210   cfg.g_timebase.den = info.time_base.denominator;
00211   cfg.rc_target_bitrate = bitrate;
00212   cfg.g_error_resilient = (vpx_codec_er_flags_t)strtoul(argv[7], NULL, 0);
00213 
00214   writer = vpx_video_writer_open(outfile_arg, kContainerIVF, &info);
00215   if (!writer) die("Failed to open %s for writing.", outfile_arg);
00216 
00217   if (!(infile = fopen(infile_arg, "rb")))
00218     die("Failed to open %s for reading.", infile_arg);
00219 
00220   if (vpx_codec_enc_init(&codec, encoder->codec_interface(), &cfg, 0))
00221     die_codec(&codec, "Failed to initialize encoder");
00222 
00223   // Encode frames.
00224   while (vpx_img_read(&raw, infile)) {
00225     int flags = 0;
00226     if (keyframe_interval > 0 && frame_count % keyframe_interval == 0)
00227       flags |= VPX_EFLAG_FORCE_KF;
00228     encode_frame(&codec, &raw, frame_count++, flags, writer);
00229     frames_encoded++;
00230     if (max_frames > 0 && frames_encoded >= max_frames) break;
00231   }
00232 
00233   // Flush encoder.
00234   while (encode_frame(&codec, NULL, -1, 0, writer)) {
00235   }
00236 
00237   printf("\n");
00238   fclose(infile);
00239   printf("Processed %d frames.\n", frame_count);
00240 
00241   vpx_img_free(&raw);
00242   if (vpx_codec_destroy(&codec)) die_codec(&codec, "Failed to destroy codec.");
00243 
00244   vpx_video_writer_close(writer);
00245 
00246   return EXIT_SUCCESS;
00247 }

Generated on 16 Jun 2017 for WebM Codec SDK by  doxygen 1.6.1