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