AOMedia Codec SDK

simple_encoder
1 /*
2 * Copyright (c) 2016, Alliance for Open Media. All rights reserved
3 *
4 * This source code is subject to the terms of the BSD 2 Clause License and
5 * the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
6 * was not distributed with this source code in the LICENSE file, you can
7 * obtain it at www.aomedia.org/license/software. If the Alliance for Open
8 * Media Patent License 1.0 was not distributed with this source code in the
9 * PATENTS file, you can obtain it at www.aomedia.org/license/patent.
10 */
11
12 // Simple Encoder
13 // ==============
14 //
15 // This is an example of a simple encoder loop. It takes an input file in
16 // YV12 format, passes it through the encoder, and writes the compressed
17 // frames to disk in IVF format. Other decoder examples build upon this
18 // one.
19 //
20 // The details of the IVF format have been elided from this example for
21 // simplicity of presentation, as IVF files will not generally be used by
22 // your application. In general, an IVF file consists of a file header,
23 // followed by a variable number of frames. Each frame consists of a frame
24 // header followed by a variable length payload. The length of the payload
25 // is specified in the first four bytes of the frame header. The payload is
26 // the raw compressed data.
27 //
28 // Standard Includes
29 // -----------------
30 // For encoders, you only have to include `aom_encoder.h` and then any
31 // header files for the specific codecs you use. In this case, we're using
32 // aom.
33 //
34 // Getting The Default Configuration
35 // ---------------------------------
36 // Encoders have the notion of "usage profiles." For example, an encoder
37 // may want to publish default configurations for both a video
38 // conferencing application and a best quality offline encoder. These
39 // obviously have very different default settings. Consult the
40 // documentation for your codec to see if it provides any default
41 // configurations. All codecs provide a default configuration, number 0,
42 // which is valid for material in the vacinity of QCIF/QVGA.
43 //
44 // Updating The Configuration
45 // ---------------------------------
46 // Almost all applications will want to update the default configuration
47 // with settings specific to their usage. Here we set the width and height
48 // of the video file to that specified on the command line. We also scale
49 // the default bitrate based on the ratio between the default resolution
50 // and the resolution specified on the command line.
51 //
52 // Initializing The Codec
53 // ----------------------
54 // The encoder is initialized by the following code.
55 //
56 // Encoding A Frame
57 // ----------------
58 // The frame is read as a continuous block (size width * height * 3 / 2)
59 // from the input file. If a frame was read (the input file has not hit
60 // EOF) then the frame is passed to the encoder. Otherwise, a NULL
61 // is passed, indicating the End-Of-Stream condition to the encoder. The
62 // `frame_cnt` is reused as the presentation time stamp (PTS) and each
63 // frame is shown for one frame-time in duration. The flags parameter is
64 // unused in this example.
65
66 // Forced Keyframes
67 // ----------------
68 // Keyframes can be forced by setting the AOM_EFLAG_FORCE_KF bit of the
69 // flags passed to `aom_codec_control()`. In this example, we force a
70 // keyframe every <keyframe-interval> frames. Note, the output stream can
71 // contain additional keyframes beyond those that have been forced using the
72 // AOM_EFLAG_FORCE_KF flag because of automatic keyframe placement by the
73 // encoder.
74 //
75 // Processing The Encoded Data
76 // ---------------------------
77 // Each packet of type `AOM_CODEC_CX_FRAME_PKT` contains the encoded data
78 // for this frame. We write a IVF frame header, followed by the raw data.
79 //
80 // Cleanup
81 // -------
82 // The `aom_codec_destroy` call frees any memory allocated by the codec.
83 //
84 // Error Handling
85 // --------------
86 // This example does not special case any error return codes. If there was
87 // an error, a descriptive message is printed and the program exits. With
88 // few exeptions, aom_codec functions return an enumerated error status,
89 // with the value `0` indicating success.
90 //
91 // Error Resiliency Features
92 // -------------------------
93 // Error resiliency is controlled by the g_error_resilient member of the
94 // configuration structure. Use the `decode_with_drops` example to decode with
95 // frames 5-10 dropped. Compare the output for a file encoded with this example
96 // versus one encoded with the `simple_encoder` example.
97
98 #include <stdio.h>
99 #include <stdlib.h>
100 #include <string.h>
101
102 #include "aom/aom_encoder.h"
103 #include "common/tools_common.h"
104 #include "common/video_writer.h"
105
106 static const char *exec_name;
107
108 void usage_exit(void) {
109 fprintf(stderr,
110 "Usage: %s <codec> <width> <height> <infile> <outfile> "
111 "<keyframe-interval> <error-resilient> <frames to encode>\n"
112 "See comments in simple_encoder.c for more information.\n",
113 exec_name);
114 exit(EXIT_FAILURE);
115 }
116
117 static int encode_frame(aom_codec_ctx_t *codec, aom_image_t *img,
118 int frame_index, int flags, AvxVideoWriter *writer) {
119 int got_pkts = 0;
120 aom_codec_iter_t iter = NULL;
121 const aom_codec_cx_pkt_t *pkt = NULL;
122 const aom_codec_err_t res =
123 aom_codec_encode(codec, img, frame_index, 1, flags);
124 if (res != AOM_CODEC_OK) die_codec(codec, "Failed to encode frame");
125
126 while ((pkt = aom_codec_get_cx_data(codec, &iter)) != NULL) {
127 got_pkts = 1;
128
129 if (pkt->kind == AOM_CODEC_CX_FRAME_PKT) {
130 const int keyframe = (pkt->data.frame.flags & AOM_FRAME_IS_KEY) != 0;
131 if (!aom_video_writer_write_frame(writer, pkt->data.frame.buf,
132 pkt->data.frame.sz,
133 pkt->data.frame.pts)) {
134 die_codec(codec, "Failed to write compressed frame");
135 }
136 printf(keyframe ? "K" : ".");
137 fflush(stdout);
138 }
139 }
140
141 return got_pkts;
142 }
143
144 // TODO(tomfinegan): Improve command line parsing and add args for bitrate/fps.
145 int main(int argc, char **argv) {
146 FILE *infile = NULL;
147 aom_codec_ctx_t codec;
148 aom_codec_enc_cfg_t cfg;
149 int frame_count = 0;
150 aom_image_t raw;
151 aom_codec_err_t res;
152 AvxVideoInfo info;
153 AvxVideoWriter *writer = NULL;
154 const AvxInterface *encoder = NULL;
155 const int fps = 30;
156 const int bitrate = 200;
157 int keyframe_interval = 0;
158 int max_frames = 0;
159 int frames_encoded = 0;
160 const char *codec_arg = NULL;
161 const char *width_arg = NULL;
162 const char *height_arg = NULL;
163 const char *infile_arg = NULL;
164 const char *outfile_arg = NULL;
165 const char *keyframe_interval_arg = NULL;
166
167 exec_name = argv[0];
168
169 // Clear explicitly, as simply assigning "{ 0 }" generates
170 // "missing-field-initializers" warning in some compilers.
171 memset(&info, 0, sizeof(info));
172
173 if (argc != 9) die("Invalid number of arguments");
174
175 codec_arg = argv[1];
176 width_arg = argv[2];
177 height_arg = argv[3];
178 infile_arg = argv[4];
179 outfile_arg = argv[5];
180 keyframe_interval_arg = argv[6];
181 max_frames = (int)strtol(argv[8], NULL, 0);
182
183 encoder = get_aom_encoder_by_name(codec_arg);
184 if (!encoder) die("Unsupported codec.");
185
186 info.codec_fourcc = encoder->fourcc;
187 info.frame_width = (int)strtol(width_arg, NULL, 0);
188 info.frame_height = (int)strtol(height_arg, NULL, 0);
189 info.time_base.numerator = 1;
190 info.time_base.denominator = fps;
191
192 if (info.frame_width <= 0 || info.frame_height <= 0 ||
193 (info.frame_width % 2) != 0 || (info.frame_height % 2) != 0) {
194 die("Invalid frame size: %dx%d", info.frame_width, info.frame_height);
195 }
196
197 if (!aom_img_alloc(&raw, AOM_IMG_FMT_I420, info.frame_width,
198 info.frame_height, 1)) {
199 die("Failed to allocate image.");
200 }
201
202 keyframe_interval = (int)strtol(keyframe_interval_arg, NULL, 0);
203 if (keyframe_interval < 0) die("Invalid keyframe interval value.");
204
205 printf("Using %s\n", aom_codec_iface_name(encoder->codec_interface()));
206
207 res = aom_codec_enc_config_default(encoder->codec_interface(), &cfg, 0);
208 if (res) die_codec(&codec, "Failed to get default codec config.");
209
210 cfg.g_w = info.frame_width;
211 cfg.g_h = info.frame_height;
212 cfg.g_timebase.num = info.time_base.numerator;
213 cfg.g_timebase.den = info.time_base.denominator;
214 cfg.rc_target_bitrate = bitrate;
215 cfg.g_error_resilient = (aom_codec_er_flags_t)strtoul(argv[7], NULL, 0);
216
217 writer = aom_video_writer_open(outfile_arg, kContainerIVF, &info);
218 if (!writer) die("Failed to open %s for writing.", outfile_arg);
219
220 if (!(infile = fopen(infile_arg, "rb")))
221 die("Failed to open %s for reading.", infile_arg);
222
223 if (aom_codec_enc_init(&codec, encoder->codec_interface(), &cfg, 0))
224 die_codec(&codec, "Failed to initialize encoder");
225
226 // Encode frames.
227 while (aom_img_read(&raw, infile)) {
228 int flags = 0;
229 if (keyframe_interval > 0 && frame_count % keyframe_interval == 0)
230 flags |= AOM_EFLAG_FORCE_KF;
231 encode_frame(&codec, &raw, frame_count++, flags, writer);
232 frames_encoded++;
233 if (max_frames > 0 && frames_encoded >= max_frames) break;
234 }
235
236 // Flush encoder.
237 while (encode_frame(&codec, NULL, -1, 0, writer)) continue;
238
239 printf("\n");
240 fclose(infile);
241 printf("Processed %d frames.\n", frame_count);
242
243 aom_img_free(&raw);
244 if (aom_codec_destroy(&codec)) die_codec(&codec, "Failed to destroy codec.");
245
246 aom_video_writer_close(writer);
247
248 return EXIT_SUCCESS;
249 }
AOM_CODEC_OK
Operation completed without error.
Definition: aom_codec.h:103
aom_codec_enc_cfg::g_w
unsigned int g_w
Width of the frame.
Definition: aom_encoder.h:276
aom_codec_enc_cfg::rc_target_bitrate
unsigned int rc_target_bitrate
Target data rate.
Definition: aom_encoder.h:491
aom_codec_er_flags_t
uint32_t aom_codec_er_flags_t
Error Resilient flags.
Definition: aom_encoder.h:119
aom_encoder.h
Describes the encoder algorithm interface to applications.
aom_codec_enc_init
#define aom_codec_enc_init(ctx, iface, cfg, flags)
Convenience macro for aom_codec_enc_init_ver()
Definition: aom_encoder.h:774
aom_codec_enc_cfg
Encoder configuration structure.
Definition: aom_encoder.h:237
aom_codec_enc_cfg::g_error_resilient
aom_codec_er_flags_t g_error_resilient
Enable error resilient modes.
Definition: aom_encoder.h:342
aom_codec_ctx
Codec context structure.
Definition: aom_codec.h:204
AOM_FRAME_IS_KEY
#define AOM_FRAME_IS_KEY
Definition: aom_encoder.h:104
aom_codec_enc_config_default
aom_codec_err_t aom_codec_enc_config_default(aom_codec_iface_t *iface, aom_codec_enc_cfg_t *cfg, unsigned int reserved)
Get a default configuration.
aom_image
Image Descriptor.
Definition: aom_image.h:141
aom_img_alloc
aom_image_t * aom_img_alloc(aom_image_t *img, aom_img_fmt_t fmt, unsigned int d_w, unsigned int d_h, unsigned int align)
Open a descriptor, allocating storage for the underlying image.
aom_codec_get_cx_data
const aom_codec_cx_pkt_t * aom_codec_get_cx_data(aom_codec_ctx_t *ctx, aom_codec_iter_t *iter)
Encoded data iterator.
aom_codec_encode
aom_codec_err_t aom_codec_encode(aom_codec_ctx_t *ctx, const aom_image_t *img, aom_codec_pts_t pts, unsigned long duration, aom_enc_frame_flags_t flags)
Encode a frame.
aom_codec_iface_name
const char * aom_codec_iface_name(aom_codec_iface_t *iface)
Return the name for a given interface.
aom_codec_enc_cfg::g_timebase
struct aom_rational g_timebase
Stream timebase units.
Definition: aom_encoder.h:334
aom_codec_destroy
aom_codec_err_t aom_codec_destroy(aom_codec_ctx_t *ctx)
Destroy a codec instance.
aom_codec_cx_pkt::kind
enum aom_codec_cx_pkt_kind kind
Definition: aom_encoder.h:148
aom_img_free
void aom_img_free(aom_image_t *img)
Close an image descriptor.
aom_codec_cx_pkt::frame
struct aom_codec_cx_pkt::@1::@2 frame
AOM_CODEC_CX_FRAME_PKT
Definition: aom_encoder.h:135
aom_codec_iter_t
const void * aom_codec_iter_t
Iterator.
Definition: aom_codec.h:194
aom_codec_err_t
aom_codec_err_t
Algorithm return codes.
Definition: aom_codec.h:101
aom_rational::den
int den
Definition: aom_encoder.h:189
aom_codec_cx_pkt
Encoder output packet.
Definition: aom_encoder.h:147
aom_rational::num
int num
Definition: aom_encoder.h:188
AOM_IMG_FMT_I420
Definition: aom_image.h:45
aom_codec_cx_pkt::data
union aom_codec_cx_pkt::@1 data
AOM_EFLAG_FORCE_KF
#define AOM_EFLAG_FORCE_KF
Definition: aom_encoder.h:229
aom_codec_enc_cfg::g_h
unsigned int g_h
Height of the frame.
Definition: aom_encoder.h:285