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