Merge "Resolves some lint errors"
[platform/upstream/libvpx.git] / examples / vp9_spatial_svc_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 #include "./vpxstats.h"
30
31 static const arg_def_t skip_frames_arg =
32     ARG_DEF("s", "skip-frames", 1, "input frames to skip");
33 static const arg_def_t frames_arg =
34     ARG_DEF("f", "frames", 1, "number of frames to encode");
35 static const arg_def_t width_arg = ARG_DEF("w", "width", 1, "source width");
36 static const arg_def_t height_arg = ARG_DEF("h", "height", 1, "source height");
37 static const arg_def_t timebase_arg =
38     ARG_DEF("t", "timebase", 1, "timebase (num/den)");
39 static const arg_def_t bitrate_arg = ARG_DEF(
40     "b", "target-bitrate", 1, "encoding bitrate, in kilobits per second");
41 static const arg_def_t spatial_layers_arg =
42     ARG_DEF("sl", "spatial-layers", 1, "number of spatial SVC layers");
43 static const arg_def_t temporal_layers_arg =
44     ARG_DEF("tl", "temporal-layers", 1, "number of temporal SVC layers");
45 static const arg_def_t kf_dist_arg =
46     ARG_DEF("k", "kf-dist", 1, "number of frames between keyframes");
47 static const arg_def_t scale_factors_arg =
48     ARG_DEF("r", "scale-factors", 1, "scale factors (lowest to highest layer)");
49 static const arg_def_t passes_arg =
50     ARG_DEF("p", "passes", 1, "Number of passes (1/2)");
51 static const arg_def_t pass_arg =
52     ARG_DEF(NULL, "pass", 1, "Pass to execute (1/2)");
53 static const arg_def_t fpf_name_arg =
54     ARG_DEF(NULL, "fpf", 1, "First pass statistics file name");
55 static const arg_def_t min_q_arg =
56     ARG_DEF(NULL, "min-q", 1, "Minimum quantizer");
57 static const arg_def_t max_q_arg =
58     ARG_DEF(NULL, "max-q", 1, "Maximum quantizer");
59 static const arg_def_t min_bitrate_arg =
60     ARG_DEF(NULL, "min-bitrate", 1, "Minimum bitrate");
61 static const arg_def_t max_bitrate_arg =
62     ARG_DEF(NULL, "max-bitrate", 1, "Maximum bitrate");
63
64 #if CONFIG_VP9_HIGHBITDEPTH
65 static const struct arg_enum_list bitdepth_enum[] = {
66   {"8",  VPX_BITS_8},
67   {"10", VPX_BITS_10},
68   {"12", VPX_BITS_12},
69   {NULL, 0}
70 };
71
72 static const arg_def_t bitdepth_arg =
73     ARG_DEF_ENUM("d", "bit-depth", 1, "Bit depth for codec 8, 10 or 12. ",
74                  bitdepth_enum);
75 #endif  // CONFIG_VP9_HIGHBITDEPTH
76
77
78 static const arg_def_t *svc_args[] = {
79   &frames_arg,        &width_arg,         &height_arg,
80   &timebase_arg,      &bitrate_arg,       &skip_frames_arg, &spatial_layers_arg,
81   &kf_dist_arg,       &scale_factors_arg, &passes_arg,      &pass_arg,
82   &fpf_name_arg,      &min_q_arg,         &max_q_arg,       &min_bitrate_arg,
83   &max_bitrate_arg,   &temporal_layers_arg,
84 #if CONFIG_VP9_HIGHBITDEPTH
85   &bitdepth_arg,
86 #endif
87   NULL
88 };
89
90 static const uint32_t default_frames_to_skip = 0;
91 static const uint32_t default_frames_to_code = 60 * 60;
92 static const uint32_t default_width = 1920;
93 static const uint32_t default_height = 1080;
94 static const uint32_t default_timebase_num = 1;
95 static const uint32_t default_timebase_den = 60;
96 static const uint32_t default_bitrate = 1000;
97 static const uint32_t default_spatial_layers = 5;
98 static const uint32_t default_temporal_layers = 1;
99 static const uint32_t default_kf_dist = 100;
100
101 typedef struct {
102   const char *input_filename;
103   const char *output_filename;
104   uint32_t frames_to_code;
105   uint32_t frames_to_skip;
106   struct VpxInputContext input_ctx;
107   stats_io_t rc_stats;
108   int passes;
109   int pass;
110 } AppInput;
111
112 static const char *exec_name;
113
114 void usage_exit() {
115   fprintf(stderr, "Usage: %s <options> input_filename output_filename\n",
116           exec_name);
117   fprintf(stderr, "Options:\n");
118   arg_show_usage(stderr, svc_args);
119   exit(EXIT_FAILURE);
120 }
121
122 static void parse_command_line(int argc, const char **argv_,
123                                AppInput *app_input, SvcContext *svc_ctx,
124                                vpx_codec_enc_cfg_t *enc_cfg) {
125   struct arg arg = {0};
126   char **argv = NULL;
127   char **argi = NULL;
128   char **argj = NULL;
129   vpx_codec_err_t res;
130   int passes = 0;
131   int pass = 0;
132   const char *fpf_file_name = NULL;
133   unsigned int min_bitrate = 0;
134   unsigned int max_bitrate = 0;
135   char string_options[1024] = {0};
136
137   // initialize SvcContext with parameters that will be passed to vpx_svc_init
138   svc_ctx->log_level = SVC_LOG_DEBUG;
139   svc_ctx->spatial_layers = default_spatial_layers;
140   svc_ctx->temporal_layers = default_temporal_layers;
141
142   // start with default encoder configuration
143   res = vpx_codec_enc_config_default(vpx_codec_vp9_cx(), enc_cfg, 0);
144   if (res) {
145     die("Failed to get config: %s\n", vpx_codec_err_to_string(res));
146   }
147   // update enc_cfg with app default values
148   enc_cfg->g_w = default_width;
149   enc_cfg->g_h = default_height;
150   enc_cfg->g_timebase.num = default_timebase_num;
151   enc_cfg->g_timebase.den = default_timebase_den;
152   enc_cfg->rc_target_bitrate = default_bitrate;
153   enc_cfg->kf_min_dist = default_kf_dist;
154   enc_cfg->kf_max_dist = default_kf_dist;
155   enc_cfg->rc_end_usage = VPX_CQ;
156
157   // initialize AppInput with default values
158   app_input->frames_to_code = default_frames_to_code;
159   app_input->frames_to_skip = default_frames_to_skip;
160
161   // process command line options
162   argv = argv_dup(argc - 1, argv_ + 1);
163   for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step) {
164     arg.argv_step = 1;
165
166     if (arg_match(&arg, &frames_arg, argi)) {
167       app_input->frames_to_code = arg_parse_uint(&arg);
168     } else if (arg_match(&arg, &width_arg, argi)) {
169       enc_cfg->g_w = arg_parse_uint(&arg);
170     } else if (arg_match(&arg, &height_arg, argi)) {
171       enc_cfg->g_h = arg_parse_uint(&arg);
172     } else if (arg_match(&arg, &timebase_arg, argi)) {
173       enc_cfg->g_timebase = arg_parse_rational(&arg);
174     } else if (arg_match(&arg, &bitrate_arg, argi)) {
175       enc_cfg->rc_target_bitrate = arg_parse_uint(&arg);
176     } else if (arg_match(&arg, &skip_frames_arg, argi)) {
177       app_input->frames_to_skip = arg_parse_uint(&arg);
178     } else if (arg_match(&arg, &spatial_layers_arg, argi)) {
179       svc_ctx->spatial_layers = arg_parse_uint(&arg);
180     } else if (arg_match(&arg, &temporal_layers_arg, argi)) {
181       svc_ctx->temporal_layers = arg_parse_uint(&arg);
182     } else if (arg_match(&arg, &kf_dist_arg, argi)) {
183       enc_cfg->kf_min_dist = arg_parse_uint(&arg);
184       enc_cfg->kf_max_dist = enc_cfg->kf_min_dist;
185     } else if (arg_match(&arg, &scale_factors_arg, argi)) {
186       snprintf(string_options, sizeof(string_options), "%s scale-factors=%s",
187                string_options, arg.val);
188     } else if (arg_match(&arg, &passes_arg, argi)) {
189       passes = arg_parse_uint(&arg);
190       if (passes < 1 || passes > 2) {
191         die("Error: Invalid number of passes (%d)\n", passes);
192       }
193     } else if (arg_match(&arg, &pass_arg, argi)) {
194       pass = arg_parse_uint(&arg);
195       if (pass < 1 || pass > 2) {
196         die("Error: Invalid pass selected (%d)\n", pass);
197       }
198     } else if (arg_match(&arg, &fpf_name_arg, argi)) {
199       fpf_file_name = arg.val;
200     } else if (arg_match(&arg, &min_q_arg, argi)) {
201       snprintf(string_options, sizeof(string_options), "%s min-quantizers=%s",
202                string_options, arg.val);
203     } else if (arg_match(&arg, &max_q_arg, argi)) {
204       snprintf(string_options, sizeof(string_options), "%s max-quantizers=%s",
205                string_options, arg.val);
206     } else if (arg_match(&arg, &min_bitrate_arg, argi)) {
207       min_bitrate = arg_parse_uint(&arg);
208     } else if (arg_match(&arg, &max_bitrate_arg, argi)) {
209       max_bitrate = arg_parse_uint(&arg);
210 #if CONFIG_VP9_HIGHBITDEPTH
211     } else if (arg_match(&arg, &bitdepth_arg, argi)) {
212       enc_cfg->g_bit_depth = arg_parse_enum_or_int(&arg);
213       switch (enc_cfg->g_bit_depth) {
214         case VPX_BITS_8:
215           enc_cfg->g_input_bit_depth = 8;
216           enc_cfg->g_profile = 0;
217           break;
218         case VPX_BITS_10:
219           enc_cfg->g_input_bit_depth = 10;
220           enc_cfg->g_profile = 2;
221           break;
222          case VPX_BITS_12:
223           enc_cfg->g_input_bit_depth = 12;
224           enc_cfg->g_profile = 2;
225           break;
226         default:
227           die("Error: Invalid bit depth selected (%d)\n", enc_cfg->g_bit_depth);
228           break;
229       }
230 #endif  // CONFIG_VP9_HIGHBITDEPTH
231     } else {
232       ++argj;
233     }
234   }
235
236   // There will be a space in front of the string options
237   if (strlen(string_options) > 0)
238     vpx_svc_set_options(svc_ctx, string_options + 1);
239
240   if (passes == 0 || passes == 1) {
241     if (pass) {
242       fprintf(stderr, "pass is ignored since there's only one pass\n");
243     }
244     enc_cfg->g_pass = VPX_RC_ONE_PASS;
245   } else {
246     if (pass == 0) {
247       die("pass must be specified when passes is 2\n");
248     }
249
250     if (fpf_file_name == NULL) {
251       die("fpf must be specified when passes is 2\n");
252     }
253
254     if (pass == 1) {
255       enc_cfg->g_pass = VPX_RC_FIRST_PASS;
256       if (!stats_open_file(&app_input->rc_stats, fpf_file_name, 0)) {
257         fatal("Failed to open statistics store");
258       }
259     } else {
260       enc_cfg->g_pass = VPX_RC_LAST_PASS;
261       if (!stats_open_file(&app_input->rc_stats, fpf_file_name, 1)) {
262         fatal("Failed to open statistics store");
263       }
264       enc_cfg->rc_twopass_stats_in = stats_get(&app_input->rc_stats);
265     }
266     app_input->passes = passes;
267     app_input->pass = pass;
268   }
269
270   if (enc_cfg->rc_target_bitrate > 0) {
271     if (min_bitrate > 0) {
272       enc_cfg->rc_2pass_vbr_minsection_pct =
273           min_bitrate * 100 / enc_cfg->rc_target_bitrate;
274     }
275     if (max_bitrate > 0) {
276       enc_cfg->rc_2pass_vbr_maxsection_pct =
277           max_bitrate * 100 / enc_cfg->rc_target_bitrate;
278     }
279   }
280
281   // Check for unrecognized options
282   for (argi = argv; *argi; ++argi)
283     if (argi[0][0] == '-' && strlen(argi[0]) > 1)
284       die("Error: Unrecognized option %s\n", *argi);
285
286   if (argv[0] == NULL || argv[1] == 0) {
287     usage_exit();
288   }
289   app_input->input_filename = argv[0];
290   app_input->output_filename = argv[1];
291   free(argv);
292
293   if (enc_cfg->g_w < 16 || enc_cfg->g_w % 2 || enc_cfg->g_h < 16 ||
294       enc_cfg->g_h % 2)
295     die("Invalid resolution: %d x %d\n", enc_cfg->g_w, enc_cfg->g_h);
296
297   printf(
298       "Codec %s\nframes: %d, skip: %d\n"
299       "layers: %d\n"
300       "width %d, height: %d,\n"
301       "num: %d, den: %d, bitrate: %d,\n"
302       "gop size: %d\n",
303       vpx_codec_iface_name(vpx_codec_vp9_cx()), app_input->frames_to_code,
304       app_input->frames_to_skip,
305       svc_ctx->spatial_layers, enc_cfg->g_w, enc_cfg->g_h,
306       enc_cfg->g_timebase.num, enc_cfg->g_timebase.den,
307       enc_cfg->rc_target_bitrate, enc_cfg->kf_max_dist);
308 }
309
310 int main(int argc, const char **argv) {
311   AppInput app_input = {0};
312   VpxVideoWriter *writer = NULL;
313   VpxVideoInfo info = {0};
314   vpx_codec_ctx_t codec;
315   vpx_codec_enc_cfg_t enc_cfg;
316   SvcContext svc_ctx;
317   uint32_t i;
318   uint32_t frame_cnt = 0;
319   vpx_image_t raw;
320   vpx_codec_err_t res;
321   int pts = 0;            /* PTS starts at 0 */
322   int frame_duration = 1; /* 1 timebase tick per frame */
323   FILE *infile = NULL;
324   int end_of_stream = 0;
325   int frames_received = 0;
326
327   memset(&svc_ctx, 0, sizeof(svc_ctx));
328   svc_ctx.log_print = 1;
329   exec_name = argv[0];
330   parse_command_line(argc, argv, &app_input, &svc_ctx, &enc_cfg);
331
332   // Allocate image buffer
333 #if CONFIG_VP9_HIGHBITDEPTH
334   if (!vpx_img_alloc(&raw, enc_cfg.g_input_bit_depth == 8 ?
335                          VPX_IMG_FMT_I420 : VPX_IMG_FMT_I42016,
336                      enc_cfg.g_w, enc_cfg.g_h, 32)) {
337     die("Failed to allocate image %dx%d\n", enc_cfg.g_w, enc_cfg.g_h);
338   }
339 #else
340   if (!vpx_img_alloc(&raw, VPX_IMG_FMT_I420, enc_cfg.g_w, enc_cfg.g_h, 32)) {
341     die("Failed to allocate image %dx%d\n", enc_cfg.g_w, enc_cfg.g_h);
342   }
343 #endif  // CONFIG_VP9_HIGHBITDEPTH
344
345   if (!(infile = fopen(app_input.input_filename, "rb")))
346     die("Failed to open %s for reading\n", app_input.input_filename);
347
348   // Initialize codec
349   if (vpx_svc_init(&svc_ctx, &codec, vpx_codec_vp9_cx(), &enc_cfg) !=
350       VPX_CODEC_OK)
351     die("Failed to initialize encoder\n");
352
353   info.codec_fourcc = VP9_FOURCC;
354   info.time_base.numerator = enc_cfg.g_timebase.num;
355   info.time_base.denominator = enc_cfg.g_timebase.den;
356
357   if (!(app_input.passes == 2 && app_input.pass == 1)) {
358     // We don't save the bitstream for the 1st pass on two pass rate control
359     writer = vpx_video_writer_open(app_input.output_filename, kContainerIVF,
360                                    &info);
361     if (!writer)
362       die("Failed to open %s for writing\n", app_input.output_filename);
363   }
364
365   // skip initial frames
366   for (i = 0; i < app_input.frames_to_skip; ++i)
367     vpx_img_read(&raw, infile);
368
369   // Encode frames
370   while (!end_of_stream) {
371     vpx_codec_iter_t iter = NULL;
372     const vpx_codec_cx_pkt_t *cx_pkt;
373     if (frame_cnt >= app_input.frames_to_code || !vpx_img_read(&raw, infile)) {
374       // We need one extra vpx_svc_encode call at end of stream to flush
375       // encoder and get remaining data
376       end_of_stream = 1;
377     }
378
379     res = vpx_svc_encode(&svc_ctx, &codec, (end_of_stream ? NULL : &raw),
380                          pts, frame_duration, VPX_DL_GOOD_QUALITY);
381     printf("%s", vpx_svc_get_message(&svc_ctx));
382     if (res != VPX_CODEC_OK) {
383       die_codec(&codec, "Failed to encode frame");
384     }
385
386     while ((cx_pkt = vpx_codec_get_cx_data(&codec, &iter)) != NULL) {
387       switch (cx_pkt->kind) {
388         case VPX_CODEC_CX_FRAME_PKT: {
389           if (cx_pkt->data.frame.sz > 0)
390             vpx_video_writer_write_frame(writer,
391                                          cx_pkt->data.frame.buf,
392                                          cx_pkt->data.frame.sz,
393                                          cx_pkt->data.frame.pts);
394
395           printf("SVC frame: %d, kf: %d, size: %d, pts: %d\n", frames_received,
396                  !!(cx_pkt->data.frame.flags & VPX_FRAME_IS_KEY),
397                  (int)cx_pkt->data.frame.sz, (int)cx_pkt->data.frame.pts);
398           ++frames_received;
399           break;
400         }
401         case VPX_CODEC_STATS_PKT: {
402           stats_write(&app_input.rc_stats,
403                       cx_pkt->data.twopass_stats.buf,
404                       cx_pkt->data.twopass_stats.sz);
405           break;
406         }
407         default: {
408           break;
409         }
410       }
411     }
412
413     if (!end_of_stream) {
414       ++frame_cnt;
415       pts += frame_duration;
416     }
417   }
418
419   printf("Processed %d frames\n", frame_cnt);
420
421   fclose(infile);
422   if (vpx_codec_destroy(&codec)) die_codec(&codec, "Failed to destroy codec");
423
424   if (app_input.passes == 2)
425     stats_close(&app_input.rc_stats, 1);
426
427   if (writer) {
428     vpx_video_writer_close(writer);
429   }
430
431   vpx_img_free(&raw);
432
433   // display average size, psnr
434   printf("%s", vpx_svc_dump_statistics(&svc_ctx));
435
436   vpx_svc_release(&svc_ctx);
437
438   return EXIT_SUCCESS;
439 }