98dc3f5f9c32051cb5b3d211ff225bd1c4576223
[platform/framework/web/crosswalk.git] / src / third_party / libvpx / source / libvpx / examples / vp9_spatial_scalable_encoder.c
1 /*
2  *  Copyright (c) 2012 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 /*
12  * This is an example demonstrating how to implement a multi-layer
13  * VP9 encoding scheme based on spatial scalability for video applications
14  * that benefit from a scalable bitstream.
15  */
16
17 #include <stdarg.h>
18 #include <stdlib.h>
19 #include <string.h>
20 #include <time.h>
21
22 #include "./args.h"
23 #include "./tools_common.h"
24 #include "./video_writer.h"
25
26 #include "vpx/svc_context.h"
27 #include "vpx/vp8cx.h"
28 #include "vpx/vpx_encoder.h"
29
30 static const struct arg_enum_list encoding_mode_enum[] = {
31   {"i", INTER_LAYER_PREDICTION_I},
32   {"alt-ip", ALT_INTER_LAYER_PREDICTION_IP},
33   {"ip", INTER_LAYER_PREDICTION_IP},
34   {"gf", USE_GOLDEN_FRAME},
35   {NULL, 0}
36 };
37
38 static const arg_def_t encoding_mode_arg = ARG_DEF_ENUM(
39     "m", "encoding-mode", 1, "Encoding mode algorithm", encoding_mode_enum);
40 static const arg_def_t skip_frames_arg =
41     ARG_DEF("s", "skip-frames", 1, "input frames to skip");
42 static const arg_def_t frames_arg =
43     ARG_DEF("f", "frames", 1, "number of frames to encode");
44 static const arg_def_t width_arg = ARG_DEF("w", "width", 1, "source width");
45 static const arg_def_t height_arg = ARG_DEF("h", "height", 1, "source height");
46 static const arg_def_t timebase_arg =
47     ARG_DEF("t", "timebase", 1, "timebase (num/den)");
48 static const arg_def_t bitrate_arg = ARG_DEF(
49     "b", "target-bitrate", 1, "encoding bitrate, in kilobits per second");
50 static const arg_def_t layers_arg =
51     ARG_DEF("l", "layers", 1, "number of SVC layers");
52 static const arg_def_t kf_dist_arg =
53     ARG_DEF("k", "kf-dist", 1, "number of frames between keyframes");
54 static const arg_def_t scale_factors_arg =
55     ARG_DEF("r", "scale-factors", 1, "scale factors (lowest to highest layer)");
56 static const arg_def_t quantizers_arg =
57     ARG_DEF("q", "quantizers", 1, "quantizers for non key frames, also will "
58             "be applied to key frames if -qn is not specified (lowest to "
59             "highest layer)");
60 static const arg_def_t quantizers_keyframe_arg =
61     ARG_DEF("qn", "quantizers-keyframe", 1, "quantizers for key frames (lowest "
62         "to highest layer)");
63
64 static const arg_def_t *svc_args[] = {
65   &encoding_mode_arg, &frames_arg,        &width_arg,       &height_arg,
66   &timebase_arg,      &bitrate_arg,       &skip_frames_arg, &layers_arg,
67   &kf_dist_arg,       &scale_factors_arg, &quantizers_arg,
68   &quantizers_keyframe_arg, NULL
69 };
70
71 static const SVC_ENCODING_MODE default_encoding_mode =
72     INTER_LAYER_PREDICTION_IP;
73 static const uint32_t default_frames_to_skip = 0;
74 static const uint32_t default_frames_to_code = 60 * 60;
75 static const uint32_t default_width = 1920;
76 static const uint32_t default_height = 1080;
77 static const uint32_t default_timebase_num = 1;
78 static const uint32_t default_timebase_den = 60;
79 static const uint32_t default_bitrate = 1000;
80 static const uint32_t default_spatial_layers = 5;
81 static const uint32_t default_kf_dist = 100;
82
83 typedef struct {
84   const char *input_filename;
85   const char *output_filename;
86   uint32_t frames_to_code;
87   uint32_t frames_to_skip;
88 } AppInput;
89
90 static const char *exec_name;
91
92 void usage_exit() {
93   fprintf(stderr, "Usage: %s <options> input_filename output_filename\n",
94           exec_name);
95   fprintf(stderr, "Options:\n");
96   arg_show_usage(stderr, svc_args);
97   exit(EXIT_FAILURE);
98 }
99
100 static void parse_command_line(int argc, const char **argv_,
101                                AppInput *app_input, SvcContext *svc_ctx,
102                                vpx_codec_enc_cfg_t *enc_cfg) {
103   struct arg arg = {0};
104   char **argv = NULL;
105   char **argi = NULL;
106   char **argj = NULL;
107   vpx_codec_err_t res;
108
109   // initialize SvcContext with parameters that will be passed to vpx_svc_init
110   svc_ctx->log_level = SVC_LOG_DEBUG;
111   svc_ctx->spatial_layers = default_spatial_layers;
112   svc_ctx->encoding_mode = default_encoding_mode;
113
114   // start with default encoder configuration
115   res = vpx_codec_enc_config_default(vpx_codec_vp9_cx(), enc_cfg, 0);
116   if (res) {
117     die("Failed to get config: %s\n", vpx_codec_err_to_string(res));
118   }
119   // update enc_cfg with app default values
120   enc_cfg->g_w = default_width;
121   enc_cfg->g_h = default_height;
122   enc_cfg->g_timebase.num = default_timebase_num;
123   enc_cfg->g_timebase.den = default_timebase_den;
124   enc_cfg->rc_target_bitrate = default_bitrate;
125   enc_cfg->kf_min_dist = default_kf_dist;
126   enc_cfg->kf_max_dist = default_kf_dist;
127
128   // initialize AppInput with default values
129   app_input->frames_to_code = default_frames_to_code;
130   app_input->frames_to_skip = default_frames_to_skip;
131
132   // process command line options
133   argv = argv_dup(argc - 1, argv_ + 1);
134   for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step) {
135     arg.argv_step = 1;
136
137     if (arg_match(&arg, &encoding_mode_arg, argi)) {
138       svc_ctx->encoding_mode = arg_parse_enum_or_int(&arg);
139     } else if (arg_match(&arg, &frames_arg, argi)) {
140       app_input->frames_to_code = arg_parse_uint(&arg);
141     } else if (arg_match(&arg, &width_arg, argi)) {
142       enc_cfg->g_w = arg_parse_uint(&arg);
143     } else if (arg_match(&arg, &height_arg, argi)) {
144       enc_cfg->g_h = arg_parse_uint(&arg);
145     } else if (arg_match(&arg, &timebase_arg, argi)) {
146       enc_cfg->g_timebase = arg_parse_rational(&arg);
147     } else if (arg_match(&arg, &bitrate_arg, argi)) {
148       enc_cfg->rc_target_bitrate = arg_parse_uint(&arg);
149     } else if (arg_match(&arg, &skip_frames_arg, argi)) {
150       app_input->frames_to_skip = arg_parse_uint(&arg);
151     } else if (arg_match(&arg, &layers_arg, argi)) {
152       svc_ctx->spatial_layers = arg_parse_uint(&arg);
153     } else if (arg_match(&arg, &kf_dist_arg, argi)) {
154       enc_cfg->kf_min_dist = arg_parse_uint(&arg);
155       enc_cfg->kf_max_dist = enc_cfg->kf_min_dist;
156     } else if (arg_match(&arg, &scale_factors_arg, argi)) {
157       vpx_svc_set_scale_factors(svc_ctx, arg.val);
158     } else if (arg_match(&arg, &quantizers_arg, argi)) {
159       vpx_svc_set_quantizers(svc_ctx, arg.val, 0);
160     } else if (arg_match(&arg, &quantizers_keyframe_arg, argi)) {
161       vpx_svc_set_quantizers(svc_ctx, arg.val, 1);
162     } else {
163       ++argj;
164     }
165   }
166
167   // Check for unrecognized options
168   for (argi = argv; *argi; ++argi)
169     if (argi[0][0] == '-' && strlen(argi[0]) > 1)
170       die("Error: Unrecognized option %s\n", *argi);
171
172   if (argv[0] == NULL || argv[1] == 0) {
173     usage_exit();
174   }
175   app_input->input_filename = argv[0];
176   app_input->output_filename = argv[1];
177   free(argv);
178
179   if (enc_cfg->g_w < 16 || enc_cfg->g_w % 2 || enc_cfg->g_h < 16 ||
180       enc_cfg->g_h % 2)
181     die("Invalid resolution: %d x %d\n", enc_cfg->g_w, enc_cfg->g_h);
182
183   printf(
184       "Codec %s\nframes: %d, skip: %d\n"
185       "mode: %d, layers: %d\n"
186       "width %d, height: %d,\n"
187       "num: %d, den: %d, bitrate: %d,\n"
188       "gop size: %d\n",
189       vpx_codec_iface_name(vpx_codec_vp9_cx()), app_input->frames_to_code,
190       app_input->frames_to_skip, svc_ctx->encoding_mode,
191       svc_ctx->spatial_layers, enc_cfg->g_w, enc_cfg->g_h,
192       enc_cfg->g_timebase.num, enc_cfg->g_timebase.den,
193       enc_cfg->rc_target_bitrate, enc_cfg->kf_max_dist);
194 }
195
196 int main(int argc, const char **argv) {
197   AppInput app_input = {0};
198   VpxVideoWriter *writer = NULL;
199   VpxVideoInfo info = {0};
200   vpx_codec_ctx_t codec;
201   vpx_codec_enc_cfg_t enc_cfg;
202   SvcContext svc_ctx;
203   uint32_t i;
204   uint32_t frame_cnt = 0;
205   vpx_image_t raw;
206   vpx_codec_err_t res;
207   int pts = 0;            /* PTS starts at 0 */
208   int frame_duration = 1; /* 1 timebase tick per frame */
209   FILE *infile = NULL;
210
211   memset(&svc_ctx, 0, sizeof(svc_ctx));
212   svc_ctx.log_print = 1;
213   exec_name = argv[0];
214   parse_command_line(argc, argv, &app_input, &svc_ctx, &enc_cfg);
215
216   // Allocate image buffer
217   if (!vpx_img_alloc(&raw, VPX_IMG_FMT_I420, enc_cfg.g_w, enc_cfg.g_h, 32))
218     die("Failed to allocate image %dx%d\n", enc_cfg.g_w, enc_cfg.g_h);
219
220   if (!(infile = fopen(app_input.input_filename, "rb")))
221     die("Failed to open %s for reading\n", app_input.input_filename);
222
223   // Initialize codec
224   if (vpx_svc_init(&svc_ctx, &codec, vpx_codec_vp9_cx(), &enc_cfg) !=
225       VPX_CODEC_OK)
226     die("Failed to initialize encoder\n");
227
228   info.codec_fourcc = VP9_FOURCC;
229   info.time_base.numerator = enc_cfg.g_timebase.num;
230   info.time_base.denominator = enc_cfg.g_timebase.den;
231   if (vpx_svc_get_layer_resolution(&svc_ctx, svc_ctx.spatial_layers - 1,
232                                    (unsigned int *)&info.frame_width,
233                                    (unsigned int *)&info.frame_height) !=
234       VPX_CODEC_OK) {
235     die("Failed to get output resolution");
236   }
237   writer = vpx_video_writer_open(app_input.output_filename, kContainerIVF,
238                                  &info);
239   if (!writer)
240     die("Failed to open %s for writing\n", app_input.output_filename);
241
242   // skip initial frames
243   for (i = 0; i < app_input.frames_to_skip; ++i)
244     vpx_img_read(&raw, infile);
245
246   // Encode frames
247   while (frame_cnt < app_input.frames_to_code) {
248     if (!vpx_img_read(&raw, infile))
249       break;
250
251     res = vpx_svc_encode(&svc_ctx, &codec, &raw, pts, frame_duration,
252                          VPX_DL_REALTIME);
253     printf("%s", vpx_svc_get_message(&svc_ctx));
254     if (res != VPX_CODEC_OK) {
255       die_codec(&codec, "Failed to encode frame");
256     }
257     if (vpx_svc_get_frame_size(&svc_ctx) > 0) {
258       vpx_video_writer_write_frame(writer,
259                                    vpx_svc_get_buffer(&svc_ctx),
260                                    vpx_svc_get_frame_size(&svc_ctx),
261                                    pts);
262     }
263     ++frame_cnt;
264     pts += frame_duration;
265   }
266
267   printf("Processed %d frames\n", frame_cnt);
268
269   fclose(infile);
270   if (vpx_codec_destroy(&codec)) die_codec(&codec, "Failed to destroy codec");
271
272   vpx_video_writer_close(writer);
273
274   vpx_img_free(&raw);
275
276   // display average size, psnr
277   printf("%s", vpx_svc_dump_statistics(&svc_ctx));
278
279   vpx_svc_release(&svc_ctx);
280
281   return EXIT_SUCCESS;
282 }