WebM Codec SDK
twopass_encoder
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 
11 // Two Pass Encoder
12 // ================
13 //
14 // This is an example of a two pass encoder loop. It takes an input file in
15 // YV12 format, passes it through the encoder twice, and writes the compressed
16 // frames to disk in IVF format. It builds upon the simple_encoder example.
17 //
18 // Twopass Variables
19 // -----------------
20 // Twopass mode needs to track the current pass number and the buffer of
21 // statistics packets.
22 //
23 // Updating The Configuration
24 // ---------------------------------
25 // In two pass mode, the configuration has to be updated on each pass. The
26 // statistics buffer is passed on the last pass.
27 //
28 // Encoding A Frame
29 // ----------------
30 // Encoding a frame in two pass mode is identical to the simple encoder
31 // example. To increase the quality while sacrificing encoding speed,
32 // VPX_DL_BEST_QUALITY can be used in place of VPX_DL_GOOD_QUALITY.
33 //
34 // Processing Statistics Packets
35 // -----------------------------
36 // Each packet of type `VPX_CODEC_CX_FRAME_PKT` contains the encoded data
37 // for this frame. We write a IVF frame header, followed by the raw data.
38 //
39 //
40 // Pass Progress Reporting
41 // -----------------------------
42 // It's sometimes helpful to see when each pass completes.
43 //
44 //
45 // Clean-up
46 // -----------------------------
47 // Destruction of the encoder instance must be done on each pass. The
48 // raw image should be destroyed at the end as usual.
49 
50 #include <stdio.h>
51 #include <stdlib.h>
52 #include <string.h>
53 
54 #include "vpx/vpx_encoder.h"
55 
56 #include "../tools_common.h"
57 #include "../video_writer.h"
58 
59 static const char *exec_name;
60 
61 void usage_exit(void) {
62  fprintf(stderr,
63  "Usage: %s <codec> <width> <height> <infile> <outfile> "
64  "<frame limit>\n",
65  exec_name);
66  exit(EXIT_FAILURE);
67 }
68 
69 static int get_frame_stats(vpx_codec_ctx_t *ctx,
70  const vpx_image_t *img,
71  vpx_codec_pts_t pts,
72  unsigned int duration,
74  unsigned int deadline,
75  vpx_fixed_buf_t *stats) {
76  int got_pkts = 0;
77  vpx_codec_iter_t iter = NULL;
78  const vpx_codec_cx_pkt_t *pkt = NULL;
79  const vpx_codec_err_t res = vpx_codec_encode(ctx, img, pts, duration, flags,
80  deadline);
81  if (res != VPX_CODEC_OK)
82  die_codec(ctx, "Failed to get frame stats.");
83 
84  while ((pkt = vpx_codec_get_cx_data(ctx, &iter)) != NULL) {
85  got_pkts = 1;
86 
87  if (pkt->kind == VPX_CODEC_STATS_PKT) {
88  const uint8_t *const pkt_buf = pkt->data.twopass_stats.buf;
89  const size_t pkt_size = pkt->data.twopass_stats.sz;
90  stats->buf = realloc(stats->buf, stats->sz + pkt_size);
91  memcpy((uint8_t *)stats->buf + stats->sz, pkt_buf, pkt_size);
92  stats->sz += pkt_size;
93  }
94  }
95 
96  return got_pkts;
97 }
98 
99 static int encode_frame(vpx_codec_ctx_t *ctx,
100  const vpx_image_t *img,
101  vpx_codec_pts_t pts,
102  unsigned int duration,
103  vpx_enc_frame_flags_t flags,
104  unsigned int deadline,
105  VpxVideoWriter *writer) {
106  int got_pkts = 0;
107  vpx_codec_iter_t iter = NULL;
108  const vpx_codec_cx_pkt_t *pkt = NULL;
109  const vpx_codec_err_t res = vpx_codec_encode(ctx, img, pts, duration, flags,
110  deadline);
111  if (res != VPX_CODEC_OK)
112  die_codec(ctx, "Failed to encode frame.");
113 
114  while ((pkt = vpx_codec_get_cx_data(ctx, &iter)) != NULL) {
115  got_pkts = 1;
116  if (pkt->kind == VPX_CODEC_CX_FRAME_PKT) {
117  const int keyframe = (pkt->data.frame.flags & VPX_FRAME_IS_KEY) != 0;
118 
119  if (!vpx_video_writer_write_frame(writer, pkt->data.frame.buf,
120  pkt->data.frame.sz,
121  pkt->data.frame.pts))
122  die_codec(ctx, "Failed to write compressed frame.");
123  printf(keyframe ? "K" : ".");
124  fflush(stdout);
125  }
126  }
127 
128  return got_pkts;
129 }
130 
131 static vpx_fixed_buf_t pass0(vpx_image_t *raw,
132  FILE *infile,
133  const VpxInterface *encoder,
134  const vpx_codec_enc_cfg_t *cfg,
135  int max_frames) {
136  vpx_codec_ctx_t codec;
137  int frame_count = 0;
138  vpx_fixed_buf_t stats = {NULL, 0};
139 
140  if (vpx_codec_enc_init(&codec, encoder->codec_interface(), cfg, 0))
141  die_codec(&codec, "Failed to initialize encoder");
142 
143  // Calculate frame statistics.
144  while (vpx_img_read(raw, infile)) {
145  ++frame_count;
146  get_frame_stats(&codec, raw, frame_count, 1, 0, VPX_DL_GOOD_QUALITY,
147  &stats);
148  if (max_frames > 0 && frame_count >= max_frames)
149  break;
150  }
151 
152  // Flush encoder.
153  while (get_frame_stats(&codec, NULL, frame_count, 1, 0,
154  VPX_DL_GOOD_QUALITY, &stats)) {}
155 
156  printf("Pass 0 complete. Processed %d frames.\n", frame_count);
157  if (vpx_codec_destroy(&codec))
158  die_codec(&codec, "Failed to destroy codec.");
159 
160  return stats;
161 }
162 
163 static void pass1(vpx_image_t *raw,
164  FILE *infile,
165  const char *outfile_name,
166  const VpxInterface *encoder,
167  const vpx_codec_enc_cfg_t *cfg,
168  int max_frames) {
169  VpxVideoInfo info = {
170  encoder->fourcc,
171  cfg->g_w,
172  cfg->g_h,
173  {cfg->g_timebase.num, cfg->g_timebase.den}
174  };
175  VpxVideoWriter *writer = NULL;
176  vpx_codec_ctx_t codec;
177  int frame_count = 0;
178 
179  writer = vpx_video_writer_open(outfile_name, kContainerIVF, &info);
180  if (!writer)
181  die("Failed to open %s for writing", outfile_name);
182 
183  if (vpx_codec_enc_init(&codec, encoder->codec_interface(), cfg, 0))
184  die_codec(&codec, "Failed to initialize encoder");
185 
186  // Encode frames.
187  while (vpx_img_read(raw, infile)) {
188  ++frame_count;
189  encode_frame(&codec, raw, frame_count, 1, 0, VPX_DL_GOOD_QUALITY, writer);
190 
191  if (max_frames > 0 && frame_count >= max_frames)
192  break;
193  }
194 
195  // Flush encoder.
196  while (encode_frame(&codec, NULL, -1, 1, 0, VPX_DL_GOOD_QUALITY, writer)) {}
197 
198  printf("\n");
199 
200  if (vpx_codec_destroy(&codec))
201  die_codec(&codec, "Failed to destroy codec.");
202 
203  vpx_video_writer_close(writer);
204 
205  printf("Pass 1 complete. Processed %d frames.\n", frame_count);
206 }
207 
208 int main(int argc, char **argv) {
209  FILE *infile = NULL;
210  int w, h;
211  vpx_codec_ctx_t codec;
213  vpx_image_t raw;
214  vpx_codec_err_t res;
215  vpx_fixed_buf_t stats;
216 
217  const VpxInterface *encoder = NULL;
218  const int fps = 30; // TODO(dkovalev) add command line argument
219  const int bitrate = 200; // kbit/s TODO(dkovalev) add command line argument
220  const char *const codec_arg = argv[1];
221  const char *const width_arg = argv[2];
222  const char *const height_arg = argv[3];
223  const char *const infile_arg = argv[4];
224  const char *const outfile_arg = argv[5];
225  int max_frames = 0;
226  exec_name = argv[0];
227 
228  if (argc != 7)
229  die("Invalid number of arguments.");
230 
231  max_frames = strtol(argv[6], NULL, 0);
232 
233  encoder = get_vpx_encoder_by_name(codec_arg);
234  if (!encoder)
235  die("Unsupported codec.");
236 
237  w = strtol(width_arg, NULL, 0);
238  h = strtol(height_arg, NULL, 0);
239 
240  if (w <= 0 || h <= 0 || (w % 2) != 0 || (h % 2) != 0)
241  die("Invalid frame size: %dx%d", w, h);
242 
243  if (!vpx_img_alloc(&raw, VPX_IMG_FMT_I420, w, h, 1))
244  die("Failed to allocate image", w, h);
245 
246  printf("Using %s\n", vpx_codec_iface_name(encoder->codec_interface()));
247 
248  // Configuration
249  res = vpx_codec_enc_config_default(encoder->codec_interface(), &cfg, 0);
250  if (res)
251  die_codec(&codec, "Failed to get default codec config.");
252 
253  cfg.g_w = w;
254  cfg.g_h = h;
255  cfg.g_timebase.num = 1;
256  cfg.g_timebase.den = fps;
257  cfg.rc_target_bitrate = bitrate;
258 
259  if (!(infile = fopen(infile_arg, "rb")))
260  die("Failed to open %s for reading", infile_arg);
261 
262  // Pass 0
264  stats = pass0(&raw, infile, encoder, &cfg, max_frames);
265 
266  // Pass 1
267  rewind(infile);
268  cfg.g_pass = VPX_RC_LAST_PASS;
269  cfg.rc_twopass_stats_in = stats;
270  pass1(&raw, infile, outfile_arg, encoder, &cfg, max_frames);
271  free(stats.buf);
272 
273  vpx_img_free(&raw);
274  fclose(infile);
275 
276  return EXIT_SUCCESS;
277 }
vpx_fixed_buf_t twopass_stats
Definition: vpx_encoder.h:214
Image Descriptor.
Definition: vpx_image.h:88
Describes the encoder algorithm interface to applications.
const char * vpx_codec_iface_name(vpx_codec_iface_t *iface)
Return the name for a given interface.
struct vpx_rational g_timebase
Stream timebase units.
Definition: vpx_encoder.h:397
int den
Definition: vpx_encoder.h:261
vpx_codec_err_t vpx_codec_encode(vpx_codec_ctx_t *ctx, const vpx_image_t *img, vpx_codec_pts_t pts, unsigned long duration, vpx_enc_frame_flags_t flags, unsigned long deadline)
Encode a frame.
Definition: vpx_encoder.h:177
Encoder configuration structure.
Definition: vpx_encoder.h:314
Encoder output packet.
Definition: vpx_encoder.h:195
void * buf
Definition: vpx_encoder.h:109
Generic fixed size buffer structure.
Definition: vpx_encoder.h:108
Definition: vpx_encoder.h:268
Definition: vpx_encoder.h:269
struct vpx_codec_cx_pkt::@1::@2 frame
vpx_image_t * vpx_img_alloc(vpx_image_t *img, vpx_img_fmt_t fmt, unsigned int d_w, unsigned int d_h, unsigned int align)
Open a descriptor, allocating storage for the underlying image.
Definition: vpx_image.h:56
unsigned int g_w
Width of the frame.
Definition: vpx_encoder.h:357
unsigned int g_h
Height of the frame.
Definition: vpx_encoder.h:367
enum vpx_codec_cx_pkt_kind kind
Definition: vpx_encoder.h:196
long vpx_enc_frame_flags_t
Encoded Frame Flags.
Definition: vpx_encoder.h:304
Operation completed without error.
Definition: vpx_codec.h:91
void vpx_img_free(vpx_image_t *img)
Close an image descriptor.
unsigned int rc_target_bitrate
Target data rate.
Definition: vpx_encoder.h:525
int num
Definition: vpx_encoder.h:260
enum vpx_enc_pass g_pass
Multi-pass Encoding Mode.
Definition: vpx_encoder.h:414
#define VPX_DL_GOOD_QUALITY
Definition: vpx_encoder.h:914
#define vpx_codec_enc_init(ctx, iface, cfg, flags)
Convenience macro for vpx_codec_enc_init_ver()
Definition: vpx_encoder.h:813
vpx_codec_err_t
Algorithm return codes.
Definition: vpx_codec.h:89
const vpx_codec_cx_pkt_t * vpx_codec_get_cx_data(vpx_codec_ctx_t *ctx, vpx_codec_iter_t *iter)
Encoded data iterator.
union vpx_codec_cx_pkt::@1 data
vpx_fixed_buf_t rc_twopass_stats_in
Two-pass stats buffer.
Definition: vpx_encoder.h:512
int64_t vpx_codec_pts_t
Time Stamp Type.
Definition: vpx_encoder.h:119
vpx_codec_err_t vpx_codec_enc_config_default(vpx_codec_iface_t *iface, vpx_codec_enc_cfg_t *cfg, unsigned int reserved)
Get a default configuration.
vpx_codec_err_t vpx_codec_destroy(vpx_codec_ctx_t *ctx)
Destroy a codec instance.
size_t sz
Definition: vpx_encoder.h:110
#define VPX_FRAME_IS_KEY
Definition: vpx_encoder.h:130
const void * vpx_codec_iter_t
Iterator.
Definition: vpx_codec.h:188
Definition: vpx_encoder.h:176
Codec context structure.
Definition: vpx_codec.h:199