2
0

simple_encoder.c 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. /*
  2. * Copyright (c) 2010 The WebM project authors. All Rights Reserved.
  3. *
  4. * Use of this source code is governed by a BSD-style license
  5. * that can be found in the LICENSE file in the root of the source
  6. * tree. An additional intellectual property rights grant can be found
  7. * in the file PATENTS. All contributing project authors may
  8. * be found in the AUTHORS file in the root of the source tree.
  9. */
  10. // Simple Encoder
  11. // ==============
  12. //
  13. // This is an example of a simple encoder loop. It takes an input file in
  14. // YV12 format, passes it through the encoder, and writes the compressed
  15. // frames to disk in IVF format. Other decoder examples build upon this
  16. // one.
  17. //
  18. // The details of the IVF format have been elided from this example for
  19. // simplicity of presentation, as IVF files will not generally be used by
  20. // your application. In general, an IVF file consists of a file header,
  21. // followed by a variable number of frames. Each frame consists of a frame
  22. // header followed by a variable length payload. The length of the payload
  23. // is specified in the first four bytes of the frame header. The payload is
  24. // the raw compressed data.
  25. //
  26. // Standard Includes
  27. // -----------------
  28. // For encoders, you only have to include `vpx_encoder.h` and then any
  29. // header files for the specific codecs you use. In this case, we're using
  30. // vp8.
  31. //
  32. // Getting The Default Configuration
  33. // ---------------------------------
  34. // Encoders have the notion of "usage profiles." For example, an encoder
  35. // may want to publish default configurations for both a video
  36. // conferencing application and a best quality offline encoder. These
  37. // obviously have very different default settings. Consult the
  38. // documentation for your codec to see if it provides any default
  39. // configurations. All codecs provide a default configuration, number 0,
  40. // which is valid for material in the vacinity of QCIF/QVGA.
  41. //
  42. // Updating The Configuration
  43. // ---------------------------------
  44. // Almost all applications will want to update the default configuration
  45. // with settings specific to their usage. Here we set the width and height
  46. // of the video file to that specified on the command line. We also scale
  47. // the default bitrate based on the ratio between the default resolution
  48. // and the resolution specified on the command line.
  49. //
  50. // Initializing The Codec
  51. // ----------------------
  52. // The encoder is initialized by the following code.
  53. //
  54. // Encoding A Frame
  55. // ----------------
  56. // The frame is read as a continuous block (size width * height * 3 / 2)
  57. // from the input file. If a frame was read (the input file has not hit
  58. // EOF) then the frame is passed to the encoder. Otherwise, a NULL
  59. // is passed, indicating the End-Of-Stream condition to the encoder. The
  60. // `frame_cnt` is reused as the presentation time stamp (PTS) and each
  61. // frame is shown for one frame-time in duration. The flags parameter is
  62. // unused in this example. The deadline is set to VPX_DL_REALTIME to
  63. // make the example run as quickly as possible.
  64. // Forced Keyframes
  65. // ----------------
  66. // Keyframes can be forced by setting the VPX_EFLAG_FORCE_KF bit of the
  67. // flags passed to `vpx_codec_control()`. In this example, we force a
  68. // keyframe every <keyframe-interval> frames. Note, the output stream can
  69. // contain additional keyframes beyond those that have been forced using the
  70. // VPX_EFLAG_FORCE_KF flag because of automatic keyframe placement by the
  71. // encoder.
  72. //
  73. // Processing The Encoded Data
  74. // ---------------------------
  75. // Each packet of type `VPX_CODEC_CX_FRAME_PKT` contains the encoded data
  76. // for this frame. We write a IVF frame header, followed by the raw data.
  77. //
  78. // Cleanup
  79. // -------
  80. // The `vpx_codec_destroy` call frees any memory allocated by the codec.
  81. //
  82. // Error Handling
  83. // --------------
  84. // This example does not special case any error return codes. If there was
  85. // an error, a descriptive message is printed and the program exits. With
  86. // few exeptions, vpx_codec functions return an enumerated error status,
  87. // with the value `0` indicating success.
  88. //
  89. // Error Resiliency Features
  90. // -------------------------
  91. // Error resiliency is controlled by the g_error_resilient member of the
  92. // configuration structure. Use the `decode_with_drops` example to decode with
  93. // frames 5-10 dropped. Compare the output for a file encoded with this example
  94. // versus one encoded with the `simple_encoder` example.
  95. #include <stdio.h>
  96. #include <stdlib.h>
  97. #include <string.h>
  98. #include "vpx/vpx_encoder.h"
  99. #include "../tools_common.h"
  100. #include "../video_writer.h"
  101. static const char *exec_name;
  102. void usage_exit(void) {
  103. fprintf(stderr,
  104. "Usage: %s <codec> <width> <height> <infile> <outfile> "
  105. "<keyframe-interval> <error-resilient> <frames to encode>\n"
  106. "See comments in simple_encoder.c for more information.\n",
  107. exec_name);
  108. exit(EXIT_FAILURE);
  109. }
  110. static int encode_frame(vpx_codec_ctx_t *codec, vpx_image_t *img,
  111. int frame_index, int flags, VpxVideoWriter *writer) {
  112. int got_pkts = 0;
  113. vpx_codec_iter_t iter = NULL;
  114. const vpx_codec_cx_pkt_t *pkt = NULL;
  115. const vpx_codec_err_t res =
  116. vpx_codec_encode(codec, img, frame_index, 1, flags, VPX_DL_GOOD_QUALITY);
  117. if (res != VPX_CODEC_OK) die_codec(codec, "Failed to encode frame");
  118. while ((pkt = vpx_codec_get_cx_data(codec, &iter)) != NULL) {
  119. got_pkts = 1;
  120. if (pkt->kind == VPX_CODEC_CX_FRAME_PKT) {
  121. const int keyframe = (pkt->data.frame.flags & VPX_FRAME_IS_KEY) != 0;
  122. if (!vpx_video_writer_write_frame(writer, pkt->data.frame.buf,
  123. pkt->data.frame.sz,
  124. pkt->data.frame.pts)) {
  125. die_codec(codec, "Failed to write compressed frame");
  126. }
  127. printf(keyframe ? "K" : ".");
  128. fflush(stdout);
  129. }
  130. }
  131. return got_pkts;
  132. }
  133. // TODO(tomfinegan): Improve command line parsing and add args for bitrate/fps.
  134. int main(int argc, char **argv) {
  135. FILE *infile = NULL;
  136. vpx_codec_ctx_t codec;
  137. vpx_codec_enc_cfg_t cfg;
  138. int frame_count = 0;
  139. vpx_image_t raw;
  140. vpx_codec_err_t res;
  141. VpxVideoInfo info = { 0, 0, 0, { 0, 0 } };
  142. VpxVideoWriter *writer = NULL;
  143. const VpxInterface *encoder = NULL;
  144. const int fps = 30;
  145. const int bitrate = 200;
  146. int keyframe_interval = 0;
  147. int max_frames = 0;
  148. int frames_encoded = 0;
  149. const char *codec_arg = NULL;
  150. const char *width_arg = NULL;
  151. const char *height_arg = NULL;
  152. const char *infile_arg = NULL;
  153. const char *outfile_arg = NULL;
  154. const char *keyframe_interval_arg = NULL;
  155. exec_name = argv[0];
  156. if (argc != 9) die("Invalid number of arguments");
  157. codec_arg = argv[1];
  158. width_arg = argv[2];
  159. height_arg = argv[3];
  160. infile_arg = argv[4];
  161. outfile_arg = argv[5];
  162. keyframe_interval_arg = argv[6];
  163. max_frames = (int)strtol(argv[8], NULL, 0);
  164. encoder = get_vpx_encoder_by_name(codec_arg);
  165. if (!encoder) die("Unsupported codec.");
  166. info.codec_fourcc = encoder->fourcc;
  167. info.frame_width = (int)strtol(width_arg, NULL, 0);
  168. info.frame_height = (int)strtol(height_arg, NULL, 0);
  169. info.time_base.numerator = 1;
  170. info.time_base.denominator = fps;
  171. if (info.frame_width <= 0 || info.frame_height <= 0 ||
  172. (info.frame_width % 2) != 0 || (info.frame_height % 2) != 0) {
  173. die("Invalid frame size: %dx%d", info.frame_width, info.frame_height);
  174. }
  175. if (!vpx_img_alloc(&raw, VPX_IMG_FMT_I420, info.frame_width,
  176. info.frame_height, 1)) {
  177. die("Failed to allocate image.");
  178. }
  179. keyframe_interval = (int)strtol(keyframe_interval_arg, NULL, 0);
  180. if (keyframe_interval < 0) die("Invalid keyframe interval value.");
  181. printf("Using %s\n", vpx_codec_iface_name(encoder->codec_interface()));
  182. res = vpx_codec_enc_config_default(encoder->codec_interface(), &cfg, 0);
  183. if (res) die_codec(&codec, "Failed to get default codec config.");
  184. cfg.g_w = info.frame_width;
  185. cfg.g_h = info.frame_height;
  186. cfg.g_timebase.num = info.time_base.numerator;
  187. cfg.g_timebase.den = info.time_base.denominator;
  188. cfg.rc_target_bitrate = bitrate;
  189. cfg.g_error_resilient = (vpx_codec_er_flags_t)strtoul(argv[7], NULL, 0);
  190. writer = vpx_video_writer_open(outfile_arg, kContainerIVF, &info);
  191. if (!writer) die("Failed to open %s for writing.", outfile_arg);
  192. if (!(infile = fopen(infile_arg, "rb")))
  193. die("Failed to open %s for reading.", infile_arg);
  194. if (vpx_codec_enc_init(&codec, encoder->codec_interface(), &cfg, 0))
  195. die_codec(&codec, "Failed to initialize encoder");
  196. // Encode frames.
  197. while (vpx_img_read(&raw, infile)) {
  198. int flags = 0;
  199. if (keyframe_interval > 0 && frame_count % keyframe_interval == 0)
  200. flags |= VPX_EFLAG_FORCE_KF;
  201. encode_frame(&codec, &raw, frame_count++, flags, writer);
  202. frames_encoded++;
  203. if (max_frames > 0 && frames_encoded >= max_frames) break;
  204. }
  205. // Flush encoder.
  206. while (encode_frame(&codec, NULL, -1, 0, writer)) {
  207. }
  208. printf("\n");
  209. fclose(infile);
  210. printf("Processed %d frames.\n", frame_count);
  211. vpx_img_free(&raw);
  212. if (vpx_codec_destroy(&codec)) die_codec(&codec, "Failed to destroy codec.");
  213. vpx_video_writer_close(writer);
  214. return EXIT_SUCCESS;
  215. }