]> granicus.if.org Git - libvpx/blob - examples/twopass_encoder.c
74291f920b12b72078556217eb78ce17db67cf0d
[libvpx] / examples / twopass_encoder.c
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, except the deadline is set to VPX_DL_BEST_QUALITY to get the
32 // best quality possible. VPX_DL_GOOD_QUALITY could also be used.
33 //
34 //
35 // Processing Statistics Packets
36 // -----------------------------
37 // Each packet of type `VPX_CODEC_CX_FRAME_PKT` contains the encoded data
38 // for this frame. We write a IVF frame header, followed by the raw data.
39 //
40 //
41 // Pass Progress Reporting
42 // -----------------------------
43 // It's sometimes helpful to see when each pass completes.
44 //
45 //
46 // Clean-up
47 // -----------------------------
48 // Destruction of the encoder instance must be done on each pass. The
49 // raw image should be destroyed at the end as usual.
50
51 #include <stdio.h>
52 #include <stdlib.h>
53 #include <string.h>
54
55 #define VPX_CODEC_DISABLE_COMPAT 1
56 #include "vpx/vpx_encoder.h"
57
58 #include "./tools_common.h"
59 #include "./video_writer.h"
60
61 static const char *exec_name;
62
63 void usage_exit() {
64   fprintf(stderr, "Usage: %s <codec> <width> <height> <infile> <outfile>\n",
65           exec_name);
66   exit(EXIT_FAILURE);
67 }
68
69 static void get_frame_stats(vpx_codec_ctx_t *ctx,
70                             const vpx_image_t *img,
71                             vpx_codec_pts_t pts,
72                             unsigned int duration,
73                             vpx_enc_frame_flags_t flags,
74                             unsigned int deadline,
75                             vpx_fixed_buf_t *stats) {
76   vpx_codec_iter_t iter = NULL;
77   const vpx_codec_cx_pkt_t *pkt = NULL;
78   const vpx_codec_err_t res = vpx_codec_encode(ctx, img, pts, duration, flags,
79                                                deadline);
80   if (res != VPX_CODEC_OK)
81     die_codec(ctx, "Failed to get frame stats.");
82
83   while ((pkt = vpx_codec_get_cx_data(ctx, &iter)) != NULL) {
84     if (pkt->kind == VPX_CODEC_STATS_PKT) {
85       const uint8_t *const pkt_buf = pkt->data.twopass_stats.buf;
86       const size_t pkt_size = pkt->data.twopass_stats.sz;
87       stats->buf = realloc(stats->buf, stats->sz + pkt_size);
88       memcpy((uint8_t *)stats->buf + stats->sz, pkt_buf, pkt_size);
89       stats->sz += pkt_size;
90     }
91   }
92 }
93
94 static void encode_frame(vpx_codec_ctx_t *ctx,
95                          const vpx_image_t *img,
96                          vpx_codec_pts_t pts,
97                          unsigned int duration,
98                          vpx_enc_frame_flags_t flags,
99                          unsigned int deadline,
100                          VpxVideoWriter *writer) {
101   vpx_codec_iter_t iter = NULL;
102   const vpx_codec_cx_pkt_t *pkt = NULL;
103   const vpx_codec_err_t res = vpx_codec_encode(ctx, img, pts, duration, flags,
104                                                deadline);
105   if (res != VPX_CODEC_OK)
106     die_codec(ctx, "Failed to encode frame.");
107
108   while ((pkt = vpx_codec_get_cx_data(ctx, &iter)) != NULL) {
109     if (pkt->kind == VPX_CODEC_CX_FRAME_PKT) {
110       const int keyframe = (pkt->data.frame.flags & VPX_FRAME_IS_KEY) != 0;
111
112       if (!vpx_video_writer_write_frame(writer, pkt->data.frame.buf,
113                                                 pkt->data.frame.sz,
114                                                 pkt->data.frame.pts))
115         die_codec(ctx, "Failed to write compressed frame.");
116       printf(keyframe ? "K" : ".");
117       fflush(stdout);
118     }
119   }
120 }
121
122 static vpx_fixed_buf_t pass0(vpx_image_t *raw,
123                              FILE *infile,
124                              const VpxInterface *encoder,
125                              vpx_codec_enc_cfg_t *cfg) {
126   vpx_codec_ctx_t codec;
127   int frame_count = 0;
128   vpx_fixed_buf_t stats = {NULL, 0};
129
130   if (vpx_codec_enc_init(&codec, encoder->codec_interface(), cfg, 0))
131     die_codec(&codec, "Failed to initialize encoder");
132
133   while (vpx_img_read(raw, infile)) {
134     ++frame_count;
135     get_frame_stats(&codec, raw, frame_count, 1, 0, VPX_DL_BEST_QUALITY,
136                     &stats);
137   }
138
139   get_frame_stats(&codec, NULL, frame_count, 1, 0, VPX_DL_BEST_QUALITY, &stats);
140
141   printf("Pass 0 complete. Processed %d frames.\n", frame_count);
142   if (vpx_codec_destroy(&codec))
143     die_codec(&codec, "Failed to destroy codec.");
144
145   return stats;
146 }
147
148 static void pass1(vpx_image_t *raw,
149                   FILE *infile,
150                   const char *outfile_name,
151                   const VpxInterface *encoder,
152                   vpx_codec_enc_cfg_t *cfg) {
153   VpxVideoInfo info = {
154     encoder->fourcc,
155     cfg->g_w,
156     cfg->g_h,
157     {cfg->g_timebase.num, cfg->g_timebase.den}
158   };
159   VpxVideoWriter *writer = NULL;
160   vpx_codec_ctx_t codec;
161   int frame_count = 0;
162
163   writer = vpx_video_writer_open(outfile_name, kContainerIVF, &info);
164   if (!writer)
165     die("Failed to open %s for writing", outfile_name);
166
167   if (vpx_codec_enc_init(&codec, encoder->codec_interface(), cfg, 0))
168     die_codec(&codec, "Failed to initialize encoder");
169
170   while (vpx_img_read(raw, infile)) {
171     ++frame_count;
172     encode_frame(&codec, raw, frame_count, 1, 0, VPX_DL_BEST_QUALITY, writer);
173   }
174
175   printf("\n");
176
177   if (vpx_codec_destroy(&codec))
178     die_codec(&codec, "Failed to destroy codec.");
179
180   vpx_video_writer_close(writer);
181
182   printf("Pass 1 complete. Processed %d frames.\n", frame_count);
183 }
184
185 int main(int argc, char **argv) {
186   FILE *infile = NULL;
187   int w, h;
188   vpx_codec_ctx_t codec;
189   vpx_codec_enc_cfg_t cfg;
190   vpx_image_t raw;
191   vpx_codec_err_t res;
192   vpx_fixed_buf_t stats;
193
194   const VpxInterface *encoder = NULL;
195   const int fps = 30;        // TODO(dkovalev) add command line argument
196   const int bitrate = 200;   // kbit/s TODO(dkovalev) add command line argument
197   const char *const codec_arg = argv[1];
198   const char *const width_arg = argv[2];
199   const char *const height_arg = argv[3];
200   const char *const infile_arg = argv[4];
201   const char *const outfile_arg = argv[5];
202   exec_name = argv[0];
203
204   if (argc != 6)
205     die("Invalid number of arguments.");
206
207   encoder = get_vpx_encoder_by_name(codec_arg);
208   if (!encoder)
209     die("Unsupported codec.");
210
211   w = strtol(width_arg, NULL, 0);
212   h = strtol(height_arg, NULL, 0);
213
214   if (w  <= 0 || h <= 0 || (w % 2) != 0 || (h  % 2) != 0)
215     die("Invalid frame size: %dx%d", w, h);
216
217   if (!vpx_img_alloc(&raw, VPX_IMG_FMT_I420, w, h, 1))
218     die("Failed to allocate image", w, h);
219
220   printf("Using %s\n", vpx_codec_iface_name(encoder->codec_interface()));
221
222   // Configuration
223   res = vpx_codec_enc_config_default(encoder->codec_interface(), &cfg, 0);
224   if (res)
225     die_codec(&codec, "Failed to get default codec config.");
226
227   cfg.g_w = w;
228   cfg.g_h = h;
229   cfg.g_timebase.num = 1;
230   cfg.g_timebase.den = fps;
231   cfg.rc_target_bitrate = bitrate;
232
233   if (!(infile = fopen(infile_arg, "rb")))
234     die("Failed to open %s for reading", infile_arg);
235
236   // Pass 0
237   cfg.g_pass = VPX_RC_FIRST_PASS;
238   stats = pass0(&raw, infile, encoder, &cfg);
239
240   // Pass 1
241   rewind(infile);
242   cfg.g_pass = VPX_RC_LAST_PASS;
243   cfg.rc_twopass_stats_in = stats;
244   pass1(&raw, infile, outfile_arg, encoder, &cfg);
245   free(stats.buf);
246
247   vpx_img_free(&raw);
248   fclose(infile);
249
250   return EXIT_SUCCESS;
251 }