2 * Copyright (c) 2012 The WebM project authors. All Rights Reserved.
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.
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.
25 #include "../tools_common.h"
26 #include "../video_writer.h"
28 #include "../vpx_ports/vpx_timer.h"
29 #include "vpx/svc_context.h"
30 #include "vpx/vp8cx.h"
31 #include "vpx/vpx_encoder.h"
32 #include "../vpxstats.h"
33 #define OUTPUT_RC_STATS 1
35 static const arg_def_t skip_frames_arg =
36 ARG_DEF("s", "skip-frames", 1, "input frames to skip");
37 static const arg_def_t frames_arg =
38 ARG_DEF("f", "frames", 1, "number of frames to encode");
39 static const arg_def_t threads_arg =
40 ARG_DEF("th", "threads", 1, "number of threads to use");
42 static const arg_def_t output_rc_stats_arg =
43 ARG_DEF("rcstat", "output_rc_stats", 1, "output rc stats");
45 static const arg_def_t width_arg = ARG_DEF("w", "width", 1, "source width");
46 static const arg_def_t height_arg = ARG_DEF("h", "height", 1, "source height");
47 static const arg_def_t timebase_arg =
48 ARG_DEF("t", "timebase", 1, "timebase (num/den)");
49 static const arg_def_t bitrate_arg = ARG_DEF(
50 "b", "target-bitrate", 1, "encoding bitrate, in kilobits per second");
51 static const arg_def_t spatial_layers_arg =
52 ARG_DEF("sl", "spatial-layers", 1, "number of spatial SVC layers");
53 static const arg_def_t temporal_layers_arg =
54 ARG_DEF("tl", "temporal-layers", 1, "number of temporal SVC layers");
55 static const arg_def_t temporal_layering_mode_arg =
56 ARG_DEF("tlm", "temporal-layering-mode", 1, "temporal layering scheme."
57 "VP9E_TEMPORAL_LAYERING_MODE");
58 static const arg_def_t kf_dist_arg =
59 ARG_DEF("k", "kf-dist", 1, "number of frames between keyframes");
60 static const arg_def_t scale_factors_arg =
61 ARG_DEF("r", "scale-factors", 1, "scale factors (lowest to highest layer)");
62 static const arg_def_t passes_arg =
63 ARG_DEF("p", "passes", 1, "Number of passes (1/2)");
64 static const arg_def_t pass_arg =
65 ARG_DEF(NULL, "pass", 1, "Pass to execute (1/2)");
66 static const arg_def_t fpf_name_arg =
67 ARG_DEF(NULL, "fpf", 1, "First pass statistics file name");
68 static const arg_def_t min_q_arg =
69 ARG_DEF(NULL, "min-q", 1, "Minimum quantizer");
70 static const arg_def_t max_q_arg =
71 ARG_DEF(NULL, "max-q", 1, "Maximum quantizer");
72 static const arg_def_t min_bitrate_arg =
73 ARG_DEF(NULL, "min-bitrate", 1, "Minimum bitrate");
74 static const arg_def_t max_bitrate_arg =
75 ARG_DEF(NULL, "max-bitrate", 1, "Maximum bitrate");
76 static const arg_def_t lag_in_frame_arg =
77 ARG_DEF(NULL, "lag-in-frames", 1, "Number of frame to input before "
78 "generating any outputs");
79 static const arg_def_t rc_end_usage_arg =
80 ARG_DEF(NULL, "rc-end-usage", 1, "0 - 3: VBR, CBR, CQ, Q");
81 static const arg_def_t speed_arg =
82 ARG_DEF("sp", "speed", 1, "speed configuration");
83 static const arg_def_t aqmode_arg =
84 ARG_DEF("aq", "aqmode", 1, "aq-mode off/on");
86 #if CONFIG_VP9_HIGHBITDEPTH
87 static const struct arg_enum_list bitdepth_enum[] = {
94 static const arg_def_t bitdepth_arg =
95 ARG_DEF_ENUM("d", "bit-depth", 1, "Bit depth for codec 8, 10 or 12. ",
97 #endif // CONFIG_VP9_HIGHBITDEPTH
100 static const arg_def_t *svc_args[] = {
101 &frames_arg, &width_arg, &height_arg,
102 &timebase_arg, &bitrate_arg, &skip_frames_arg, &spatial_layers_arg,
103 &kf_dist_arg, &scale_factors_arg, &passes_arg, &pass_arg,
104 &fpf_name_arg, &min_q_arg, &max_q_arg, &min_bitrate_arg,
105 &max_bitrate_arg, &temporal_layers_arg, &temporal_layering_mode_arg,
106 &lag_in_frame_arg, &threads_arg, &aqmode_arg,
108 &output_rc_stats_arg,
111 #if CONFIG_VP9_HIGHBITDEPTH
115 &rc_end_usage_arg, NULL
118 static const uint32_t default_frames_to_skip = 0;
119 static const uint32_t default_frames_to_code = 60 * 60;
120 static const uint32_t default_width = 1920;
121 static const uint32_t default_height = 1080;
122 static const uint32_t default_timebase_num = 1;
123 static const uint32_t default_timebase_den = 60;
124 static const uint32_t default_bitrate = 1000;
125 static const uint32_t default_spatial_layers = 5;
126 static const uint32_t default_temporal_layers = 1;
127 static const uint32_t default_kf_dist = 100;
128 static const uint32_t default_temporal_layering_mode = 0;
129 static const uint32_t default_output_rc_stats = 0;
130 static const int32_t default_speed = -1; // -1 means use library default.
131 static const uint32_t default_threads = 0; // zero means use library default.
134 const char *input_filename;
135 const char *output_filename;
136 uint32_t frames_to_code;
137 uint32_t frames_to_skip;
138 struct VpxInputContext input_ctx;
144 static const char *exec_name;
146 void usage_exit(void) {
147 fprintf(stderr, "Usage: %s <options> input_filename output_filename\n",
149 fprintf(stderr, "Options:\n");
150 arg_show_usage(stderr, svc_args);
154 static void parse_command_line(int argc, const char **argv_,
155 AppInput *app_input, SvcContext *svc_ctx,
156 vpx_codec_enc_cfg_t *enc_cfg) {
157 struct arg arg = {0};
164 const char *fpf_file_name = NULL;
165 unsigned int min_bitrate = 0;
166 unsigned int max_bitrate = 0;
167 char string_options[1024] = {0};
169 // initialize SvcContext with parameters that will be passed to vpx_svc_init
170 svc_ctx->log_level = SVC_LOG_DEBUG;
171 svc_ctx->spatial_layers = default_spatial_layers;
172 svc_ctx->temporal_layers = default_temporal_layers;
173 svc_ctx->temporal_layering_mode = default_temporal_layering_mode;
175 svc_ctx->output_rc_stat = default_output_rc_stats;
177 svc_ctx->speed = default_speed;
178 svc_ctx->threads = default_threads;
180 // start with default encoder configuration
181 res = vpx_codec_enc_config_default(vpx_codec_vp9_cx(), enc_cfg, 0);
183 die("Failed to get config: %s\n", vpx_codec_err_to_string(res));
185 // update enc_cfg with app default values
186 enc_cfg->g_w = default_width;
187 enc_cfg->g_h = default_height;
188 enc_cfg->g_timebase.num = default_timebase_num;
189 enc_cfg->g_timebase.den = default_timebase_den;
190 enc_cfg->rc_target_bitrate = default_bitrate;
191 enc_cfg->kf_min_dist = default_kf_dist;
192 enc_cfg->kf_max_dist = default_kf_dist;
193 enc_cfg->rc_end_usage = VPX_CQ;
195 // initialize AppInput with default values
196 app_input->frames_to_code = default_frames_to_code;
197 app_input->frames_to_skip = default_frames_to_skip;
199 // process command line options
200 argv = argv_dup(argc - 1, argv_ + 1);
201 for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step) {
204 if (arg_match(&arg, &frames_arg, argi)) {
205 app_input->frames_to_code = arg_parse_uint(&arg);
206 } else if (arg_match(&arg, &width_arg, argi)) {
207 enc_cfg->g_w = arg_parse_uint(&arg);
208 } else if (arg_match(&arg, &height_arg, argi)) {
209 enc_cfg->g_h = arg_parse_uint(&arg);
210 } else if (arg_match(&arg, &timebase_arg, argi)) {
211 enc_cfg->g_timebase = arg_parse_rational(&arg);
212 } else if (arg_match(&arg, &bitrate_arg, argi)) {
213 enc_cfg->rc_target_bitrate = arg_parse_uint(&arg);
214 } else if (arg_match(&arg, &skip_frames_arg, argi)) {
215 app_input->frames_to_skip = arg_parse_uint(&arg);
216 } else if (arg_match(&arg, &spatial_layers_arg, argi)) {
217 svc_ctx->spatial_layers = arg_parse_uint(&arg);
218 } else if (arg_match(&arg, &temporal_layers_arg, argi)) {
219 svc_ctx->temporal_layers = arg_parse_uint(&arg);
221 } else if (arg_match(&arg, &output_rc_stats_arg, argi)) {
222 svc_ctx->output_rc_stat = arg_parse_uint(&arg);
224 } else if (arg_match(&arg, &speed_arg, argi)) {
225 svc_ctx->speed = arg_parse_uint(&arg);
226 } else if (arg_match(&arg, &aqmode_arg, argi)) {
227 svc_ctx->aqmode = arg_parse_uint(&arg);
228 } else if (arg_match(&arg, &threads_arg, argi)) {
229 svc_ctx->threads = arg_parse_uint(&arg);
230 } else if (arg_match(&arg, &temporal_layering_mode_arg, argi)) {
231 svc_ctx->temporal_layering_mode =
232 enc_cfg->temporal_layering_mode = arg_parse_int(&arg);
233 if (svc_ctx->temporal_layering_mode) {
234 enc_cfg->g_error_resilient = 1;
236 } else if (arg_match(&arg, &kf_dist_arg, argi)) {
237 enc_cfg->kf_min_dist = arg_parse_uint(&arg);
238 enc_cfg->kf_max_dist = enc_cfg->kf_min_dist;
239 } else if (arg_match(&arg, &scale_factors_arg, argi)) {
240 snprintf(string_options, sizeof(string_options), "%s scale-factors=%s",
241 string_options, arg.val);
242 } else if (arg_match(&arg, &passes_arg, argi)) {
243 passes = arg_parse_uint(&arg);
244 if (passes < 1 || passes > 2) {
245 die("Error: Invalid number of passes (%d)\n", passes);
247 } else if (arg_match(&arg, &pass_arg, argi)) {
248 pass = arg_parse_uint(&arg);
249 if (pass < 1 || pass > 2) {
250 die("Error: Invalid pass selected (%d)\n", pass);
252 } else if (arg_match(&arg, &fpf_name_arg, argi)) {
253 fpf_file_name = arg.val;
254 } else if (arg_match(&arg, &min_q_arg, argi)) {
255 snprintf(string_options, sizeof(string_options), "%s min-quantizers=%s",
256 string_options, arg.val);
257 } else if (arg_match(&arg, &max_q_arg, argi)) {
258 snprintf(string_options, sizeof(string_options), "%s max-quantizers=%s",
259 string_options, arg.val);
260 } else if (arg_match(&arg, &min_bitrate_arg, argi)) {
261 min_bitrate = arg_parse_uint(&arg);
262 } else if (arg_match(&arg, &max_bitrate_arg, argi)) {
263 max_bitrate = arg_parse_uint(&arg);
264 } else if (arg_match(&arg, &lag_in_frame_arg, argi)) {
265 enc_cfg->g_lag_in_frames = arg_parse_uint(&arg);
266 } else if (arg_match(&arg, &rc_end_usage_arg, argi)) {
267 enc_cfg->rc_end_usage = arg_parse_uint(&arg);
268 #if CONFIG_VP9_HIGHBITDEPTH
269 } else if (arg_match(&arg, &bitdepth_arg, argi)) {
270 enc_cfg->g_bit_depth = arg_parse_enum_or_int(&arg);
271 switch (enc_cfg->g_bit_depth) {
273 enc_cfg->g_input_bit_depth = 8;
274 enc_cfg->g_profile = 0;
277 enc_cfg->g_input_bit_depth = 10;
278 enc_cfg->g_profile = 2;
281 enc_cfg->g_input_bit_depth = 12;
282 enc_cfg->g_profile = 2;
285 die("Error: Invalid bit depth selected (%d)\n", enc_cfg->g_bit_depth);
288 #endif // CONFIG_VP9_HIGHBITDEPTH
294 // There will be a space in front of the string options
295 if (strlen(string_options) > 0)
296 vpx_svc_set_options(svc_ctx, string_options + 1);
298 if (passes == 0 || passes == 1) {
300 fprintf(stderr, "pass is ignored since there's only one pass\n");
302 enc_cfg->g_pass = VPX_RC_ONE_PASS;
305 die("pass must be specified when passes is 2\n");
308 if (fpf_file_name == NULL) {
309 die("fpf must be specified when passes is 2\n");
313 enc_cfg->g_pass = VPX_RC_FIRST_PASS;
314 if (!stats_open_file(&app_input->rc_stats, fpf_file_name, 0)) {
315 fatal("Failed to open statistics store");
318 enc_cfg->g_pass = VPX_RC_LAST_PASS;
319 if (!stats_open_file(&app_input->rc_stats, fpf_file_name, 1)) {
320 fatal("Failed to open statistics store");
322 enc_cfg->rc_twopass_stats_in = stats_get(&app_input->rc_stats);
324 app_input->passes = passes;
325 app_input->pass = pass;
328 if (enc_cfg->rc_target_bitrate > 0) {
329 if (min_bitrate > 0) {
330 enc_cfg->rc_2pass_vbr_minsection_pct =
331 min_bitrate * 100 / enc_cfg->rc_target_bitrate;
333 if (max_bitrate > 0) {
334 enc_cfg->rc_2pass_vbr_maxsection_pct =
335 max_bitrate * 100 / enc_cfg->rc_target_bitrate;
339 // Check for unrecognized options
340 for (argi = argv; *argi; ++argi)
341 if (argi[0][0] == '-' && strlen(argi[0]) > 1)
342 die("Error: Unrecognized option %s\n", *argi);
344 if (argv[0] == NULL || argv[1] == 0) {
347 app_input->input_filename = argv[0];
348 app_input->output_filename = argv[1];
351 if (enc_cfg->g_w < 16 || enc_cfg->g_w % 2 || enc_cfg->g_h < 16 ||
353 die("Invalid resolution: %d x %d\n", enc_cfg->g_w, enc_cfg->g_h);
356 "Codec %s\nframes: %d, skip: %d\n"
358 "width %d, height: %d,\n"
359 "num: %d, den: %d, bitrate: %d,\n"
361 vpx_codec_iface_name(vpx_codec_vp9_cx()), app_input->frames_to_code,
362 app_input->frames_to_skip,
363 svc_ctx->spatial_layers, enc_cfg->g_w, enc_cfg->g_h,
364 enc_cfg->g_timebase.num, enc_cfg->g_timebase.den,
365 enc_cfg->rc_target_bitrate, enc_cfg->kf_max_dist);
369 // For rate control encoding stats.
370 struct RateControlStats {
371 // Number of input frames per layer.
372 int layer_input_frames[VPX_MAX_LAYERS];
373 // Total (cumulative) number of encoded frames per layer.
374 int layer_tot_enc_frames[VPX_MAX_LAYERS];
375 // Number of encoded non-key frames per layer.
376 int layer_enc_frames[VPX_MAX_LAYERS];
377 // Framerate per layer (cumulative).
378 double layer_framerate[VPX_MAX_LAYERS];
379 // Target average frame size per layer (per-frame-bandwidth per layer).
380 double layer_pfb[VPX_MAX_LAYERS];
381 // Actual average frame size per layer.
382 double layer_avg_frame_size[VPX_MAX_LAYERS];
383 // Average rate mismatch per layer (|target - actual| / target).
384 double layer_avg_rate_mismatch[VPX_MAX_LAYERS];
385 // Actual encoding bitrate per layer (cumulative).
386 double layer_encoding_bitrate[VPX_MAX_LAYERS];
387 // Average of the short-time encoder actual bitrate.
388 // TODO(marpan): Should we add these short-time stats for each layer?
389 double avg_st_encoding_bitrate;
390 // Variance of the short-time encoder actual bitrate.
391 double variance_st_encoding_bitrate;
392 // Window (number of frames) for computing short-time encoding bitrate.
394 // Number of window measurements.
398 // Note: these rate control stats assume only 1 key frame in the
399 // sequence (i.e., first frame only).
400 static void set_rate_control_stats(struct RateControlStats *rc,
401 vpx_codec_enc_cfg_t *cfg) {
403 // Set the layer (cumulative) framerate and the target layer (non-cumulative)
404 // per-frame-bandwidth, for the rate control encoding stats below.
405 const double framerate = cfg->g_timebase.den / cfg->g_timebase.num;
407 for (sl = 0; sl < cfg->ss_number_layers; ++sl) {
408 for (tl = 0; tl < cfg->ts_number_layers; ++tl) {
409 const int layer = sl * cfg->ts_number_layers + tl;
410 const int tlayer0 = sl * cfg->ts_number_layers;
411 if (cfg->ts_number_layers == 1)
412 rc->layer_framerate[layer] = framerate;
414 rc->layer_framerate[layer] =
415 framerate / cfg->ts_rate_decimator[tl];
417 rc->layer_pfb[layer] = 1000.0 *
418 (cfg->layer_target_bitrate[layer] -
419 cfg->layer_target_bitrate[layer - 1]) /
420 (rc->layer_framerate[layer] -
421 rc->layer_framerate[layer - 1]);
423 rc->layer_pfb[tlayer0] = 1000.0 *
424 cfg->layer_target_bitrate[tlayer0] /
425 rc->layer_framerate[tlayer0];
427 rc->layer_input_frames[layer] = 0;
428 rc->layer_enc_frames[layer] = 0;
429 rc->layer_tot_enc_frames[layer] = 0;
430 rc->layer_encoding_bitrate[layer] = 0.0;
431 rc->layer_avg_frame_size[layer] = 0.0;
432 rc->layer_avg_rate_mismatch[layer] = 0.0;
435 rc->window_count = 0;
436 rc->window_size = 15;
437 rc->avg_st_encoding_bitrate = 0.0;
438 rc->variance_st_encoding_bitrate = 0.0;
441 static void printout_rate_control_summary(struct RateControlStats *rc,
442 vpx_codec_enc_cfg_t *cfg,
445 int tot_num_frames = 0;
446 double perc_fluctuation = 0.0;
447 printf("Total number of processed frames: %d\n\n", frame_cnt - 1);
448 printf("Rate control layer stats for sl%d tl%d layer(s):\n\n",
449 cfg->ss_number_layers, cfg->ts_number_layers);
450 for (sl = 0; sl < cfg->ss_number_layers; ++sl) {
451 for (tl = 0; tl < cfg->ts_number_layers; ++tl) {
452 const int layer = sl * cfg->ts_number_layers + tl;
453 const int num_dropped = (tl > 0) ?
454 (rc->layer_input_frames[layer] - rc->layer_enc_frames[layer]) :
455 (rc->layer_input_frames[layer] - rc->layer_enc_frames[layer] - 1);
457 tot_num_frames += rc->layer_input_frames[layer];
458 rc->layer_encoding_bitrate[layer] = 0.001 * rc->layer_framerate[layer] *
459 rc->layer_encoding_bitrate[layer] / tot_num_frames;
460 rc->layer_avg_frame_size[layer] = rc->layer_avg_frame_size[layer] /
461 rc->layer_enc_frames[layer];
462 rc->layer_avg_rate_mismatch[layer] =
463 100.0 * rc->layer_avg_rate_mismatch[layer] /
464 rc->layer_enc_frames[layer];
465 printf("For layer#: sl%d tl%d \n", sl, tl);
466 printf("Bitrate (target vs actual): %d %f.0 kbps\n",
467 cfg->layer_target_bitrate[layer],
468 rc->layer_encoding_bitrate[layer]);
469 printf("Average frame size (target vs actual): %f %f bits\n",
470 rc->layer_pfb[layer], rc->layer_avg_frame_size[layer]);
471 printf("Average rate_mismatch: %f\n",
472 rc->layer_avg_rate_mismatch[layer]);
473 printf("Number of input frames, encoded (non-key) frames, "
474 "and percent dropped frames: %d %d %f.0 \n",
475 rc->layer_input_frames[layer], rc->layer_enc_frames[layer],
476 100.0 * num_dropped / rc->layer_input_frames[layer]);
480 rc->avg_st_encoding_bitrate = rc->avg_st_encoding_bitrate / rc->window_count;
481 rc->variance_st_encoding_bitrate =
482 rc->variance_st_encoding_bitrate / rc->window_count -
483 (rc->avg_st_encoding_bitrate * rc->avg_st_encoding_bitrate);
484 perc_fluctuation = 100.0 * sqrt(rc->variance_st_encoding_bitrate) /
485 rc->avg_st_encoding_bitrate;
486 printf("Short-time stats, for window of %d frames: \n", rc->window_size);
487 printf("Average, rms-variance, and percent-fluct: %f %f %f \n",
488 rc->avg_st_encoding_bitrate,
489 sqrt(rc->variance_st_encoding_bitrate),
491 if (frame_cnt != tot_num_frames)
492 die("Error: Number of input frames not equal to output encoded frames != "
493 "%d tot_num_frames = %d\n", frame_cnt, tot_num_frames);
496 vpx_codec_err_t parse_superframe_index(const uint8_t *data,
498 uint32_t sizes[8], int *count) {
499 // A chunk ending with a byte matching 0xc0 is an invalid chunk unless
500 // it is a super frame index. If the last byte of real video compression
501 // data is 0xc0 the encoder must add a 0 byte. If we have the marker but
502 // not the associated matching marker byte at the front of the index we have
503 // an invalid bitstream and need to return an error.
507 marker = *(data + data_sz - 1);
511 if ((marker & 0xe0) == 0xc0) {
512 const uint32_t frames = (marker & 0x7) + 1;
513 const uint32_t mag = ((marker >> 3) & 0x3) + 1;
514 const size_t index_sz = 2 + mag * frames;
516 // This chunk is marked as having a superframe index but doesn't have
517 // enough data for it, thus it's an invalid superframe index.
518 if (data_sz < index_sz)
519 return VPX_CODEC_CORRUPT_FRAME;
522 const uint8_t marker2 = *(data + data_sz - index_sz);
524 // This chunk is marked as having a superframe index but doesn't have
525 // the matching marker byte at the front of the index therefore it's an
527 if (marker != marker2)
528 return VPX_CODEC_CORRUPT_FRAME;
532 // Found a valid superframe index.
534 const uint8_t *x = &data[data_sz - index_sz + 1];
536 for (i = 0; i < frames; ++i) {
537 uint32_t this_sz = 0;
539 for (j = 0; j < mag; ++j)
540 this_sz |= (*x++) << (j * 8);
550 // Example pattern for spatial layers and 2 temporal layers used in the
551 // bypass/flexible mode. The pattern corresponds to the pattern
552 // VP9E_TEMPORAL_LAYERING_MODE_0101 (temporal_layering_mode == 2) used in
553 // non-flexible mode.
554 void set_frame_flags_bypass_mode(int sl, int tl, int num_spatial_layers,
556 vpx_svc_ref_frame_config_t *ref_frame_config) {
557 for (sl = 0; sl < num_spatial_layers; ++sl) {
560 ref_frame_config->frame_flags[sl] = VP8_EFLAG_NO_REF_GF |
561 VP8_EFLAG_NO_REF_ARF |
562 VP8_EFLAG_NO_UPD_GF |
563 VP8_EFLAG_NO_UPD_ARF;
566 ref_frame_config->frame_flags[sl] = VP8_EFLAG_NO_REF_LAST |
567 VP8_EFLAG_NO_REF_ARF |
568 VP8_EFLAG_NO_UPD_GF |
569 VP8_EFLAG_NO_UPD_ARF;
571 ref_frame_config->frame_flags[sl] = VP8_EFLAG_NO_REF_ARF |
572 VP8_EFLAG_NO_UPD_GF |
573 VP8_EFLAG_NO_UPD_ARF;
576 } else if (tl == 1) {
578 ref_frame_config->frame_flags[sl] = VP8_EFLAG_NO_REF_GF |
579 VP8_EFLAG_NO_REF_ARF |
580 VP8_EFLAG_NO_UPD_LAST |
583 ref_frame_config->frame_flags[sl] = VP8_EFLAG_NO_REF_ARF |
584 VP8_EFLAG_NO_UPD_LAST |
589 ref_frame_config->lst_fb_idx[sl] = sl;
591 ref_frame_config->gld_fb_idx[sl] = sl - 1;
593 ref_frame_config->gld_fb_idx[sl] = 0;
594 ref_frame_config->alt_fb_idx[sl] = 0;
595 } else if (tl == 1) {
596 ref_frame_config->lst_fb_idx[sl] = sl;
597 ref_frame_config->gld_fb_idx[sl] = num_spatial_layers + sl - 1;
598 ref_frame_config->alt_fb_idx[sl] = num_spatial_layers + sl;
603 int main(int argc, const char **argv) {
604 AppInput app_input = {0};
605 VpxVideoWriter *writer = NULL;
606 VpxVideoInfo info = {0};
607 vpx_codec_ctx_t codec;
608 vpx_codec_enc_cfg_t enc_cfg;
611 uint32_t frame_cnt = 0;
614 int pts = 0; /* PTS starts at 0 */
615 int frame_duration = 1; /* 1 timebase tick per frame */
617 int end_of_stream = 0;
618 int frames_received = 0;
620 VpxVideoWriter *outfile[VPX_TS_MAX_LAYERS] = {NULL};
621 struct RateControlStats rc;
622 vpx_svc_layer_id_t layer_id;
623 vpx_svc_ref_frame_config_t ref_frame_config;
625 double sum_bitrate = 0.0;
626 double sum_bitrate2 = 0.0;
627 double framerate = 30.0;
629 struct vpx_usec_timer timer;
631 memset(&svc_ctx, 0, sizeof(svc_ctx));
632 svc_ctx.log_print = 1;
634 parse_command_line(argc, argv, &app_input, &svc_ctx, &enc_cfg);
636 // Allocate image buffer
637 #if CONFIG_VP9_HIGHBITDEPTH
638 if (!vpx_img_alloc(&raw, enc_cfg.g_input_bit_depth == 8 ?
639 VPX_IMG_FMT_I420 : VPX_IMG_FMT_I42016,
640 enc_cfg.g_w, enc_cfg.g_h, 32)) {
641 die("Failed to allocate image %dx%d\n", enc_cfg.g_w, enc_cfg.g_h);
644 if (!vpx_img_alloc(&raw, VPX_IMG_FMT_I420, enc_cfg.g_w, enc_cfg.g_h, 32)) {
645 die("Failed to allocate image %dx%d\n", enc_cfg.g_w, enc_cfg.g_h);
647 #endif // CONFIG_VP9_HIGHBITDEPTH
649 if (!(infile = fopen(app_input.input_filename, "rb")))
650 die("Failed to open %s for reading\n", app_input.input_filename);
653 if (vpx_svc_init(&svc_ctx, &codec, vpx_codec_vp9_cx(), &enc_cfg) !=
655 die("Failed to initialize encoder\n");
658 if (svc_ctx.output_rc_stat) {
659 set_rate_control_stats(&rc, &enc_cfg);
660 framerate = enc_cfg.g_timebase.den / enc_cfg.g_timebase.num;
664 info.codec_fourcc = VP9_FOURCC;
665 info.time_base.numerator = enc_cfg.g_timebase.num;
666 info.time_base.denominator = enc_cfg.g_timebase.den;
668 if (!(app_input.passes == 2 && app_input.pass == 1)) {
669 // We don't save the bitstream for the 1st pass on two pass rate control
670 writer = vpx_video_writer_open(app_input.output_filename, kContainerIVF,
673 die("Failed to open %s for writing\n", app_input.output_filename);
676 // For now, just write temporal layer streams.
677 // TODO(wonkap): do spatial by re-writing superframe.
678 if (svc_ctx.output_rc_stat) {
679 for (tl = 0; tl < enc_cfg.ts_number_layers; ++tl) {
680 char file_name[PATH_MAX];
682 snprintf(file_name, sizeof(file_name), "%s_t%d.ivf",
683 app_input.output_filename, tl);
684 outfile[tl] = vpx_video_writer_open(file_name, kContainerIVF, &info);
686 die("Failed to open %s for writing", file_name);
691 // skip initial frames
692 for (i = 0; i < app_input.frames_to_skip; ++i)
693 vpx_img_read(&raw, infile);
695 if (svc_ctx.speed != -1)
696 vpx_codec_control(&codec, VP8E_SET_CPUUSED, svc_ctx.speed);
698 vpx_codec_control(&codec, VP9E_SET_TILE_COLUMNS, (svc_ctx.threads >> 1));
699 if (svc_ctx.speed >= 5 && svc_ctx.aqmode == 1)
700 vpx_codec_control(&codec, VP9E_SET_AQ_MODE, 3);
704 while (!end_of_stream) {
705 vpx_codec_iter_t iter = NULL;
706 const vpx_codec_cx_pkt_t *cx_pkt;
707 if (frame_cnt >= app_input.frames_to_code || !vpx_img_read(&raw, infile)) {
708 // We need one extra vpx_svc_encode call at end of stream to flush
709 // encoder and get remaining data
713 // For BYPASS/FLEXIBLE mode, set the frame flags (reference and updates)
714 // and the buffer indices for each spatial layer of the current
715 // (super)frame to be encoded. The temporal layer_id for the current frame
716 // also needs to be set.
717 // TODO(marpan): Should rename the "VP9E_TEMPORAL_LAYERING_MODE_BYPASS"
718 // mode to "VP9E_LAYERING_MODE_BYPASS".
719 if (svc_ctx.temporal_layering_mode == VP9E_TEMPORAL_LAYERING_MODE_BYPASS) {
720 layer_id.spatial_layer_id = 0;
721 // Example for 2 temporal layers.
722 if (frame_cnt % 2 == 0)
723 layer_id.temporal_layer_id = 0;
725 layer_id.temporal_layer_id = 1;
726 // Note that we only set the temporal layer_id, since we are calling
727 // the encode for the whole superframe. The encoder will internally loop
728 // over all the spatial layers for the current superframe.
729 vpx_codec_control(&codec, VP9E_SET_SVC_LAYER_ID, &layer_id);
730 set_frame_flags_bypass_mode(sl, layer_id.temporal_layer_id,
731 svc_ctx.spatial_layers,
734 vpx_codec_control(&codec, VP9E_SET_SVC_REF_FRAME_CONFIG,
736 // Keep track of input frames, to account for frame drops in rate control
738 for (sl = 0; sl < enc_cfg.ss_number_layers; ++sl) {
739 ++rc.layer_input_frames[sl * enc_cfg.ts_number_layers +
740 layer_id.temporal_layer_id];
744 vpx_usec_timer_start(&timer);
745 res = vpx_svc_encode(&svc_ctx, &codec, (end_of_stream ? NULL : &raw),
746 pts, frame_duration, svc_ctx.speed >= 5 ?
747 VPX_DL_REALTIME : VPX_DL_GOOD_QUALITY);
748 vpx_usec_timer_mark(&timer);
749 cx_time += vpx_usec_timer_elapsed(&timer);
751 printf("%s", vpx_svc_get_message(&svc_ctx));
752 if (res != VPX_CODEC_OK) {
753 die_codec(&codec, "Failed to encode frame");
756 while ((cx_pkt = vpx_codec_get_cx_data(&codec, &iter)) != NULL) {
757 switch (cx_pkt->kind) {
758 case VPX_CODEC_CX_FRAME_PKT: {
759 if (cx_pkt->data.frame.sz > 0) {
764 vpx_video_writer_write_frame(writer,
765 cx_pkt->data.frame.buf,
766 cx_pkt->data.frame.sz,
767 cx_pkt->data.frame.pts);
769 // TODO(marpan/wonkap): Put this (to line728) in separate function.
770 if (svc_ctx.output_rc_stat) {
771 vpx_codec_control(&codec, VP9E_GET_SVC_LAYER_ID, &layer_id);
772 parse_superframe_index(cx_pkt->data.frame.buf,
773 cx_pkt->data.frame.sz, sizes, &count);
774 // Note computing input_layer_frames here won't account for frame
775 // drops in rate control stats.
776 // TODO(marpan): Fix this for non-bypass mode so we can get stats
777 // for dropped frames.
778 if (svc_ctx.temporal_layering_mode !=
779 VP9E_TEMPORAL_LAYERING_MODE_BYPASS) {
780 for (sl = 0; sl < enc_cfg.ss_number_layers; ++sl) {
781 ++rc.layer_input_frames[sl * enc_cfg.ts_number_layers +
782 layer_id.temporal_layer_id];
785 for (tl = layer_id.temporal_layer_id;
786 tl < enc_cfg.ts_number_layers; ++tl) {
787 vpx_video_writer_write_frame(outfile[tl],
788 cx_pkt->data.frame.buf,
789 cx_pkt->data.frame.sz,
790 cx_pkt->data.frame.pts);
793 for (sl = 0; sl < enc_cfg.ss_number_layers; ++sl) {
794 for (tl = layer_id.temporal_layer_id;
795 tl < enc_cfg.ts_number_layers; ++tl) {
796 const int layer = sl * enc_cfg.ts_number_layers + tl;
797 ++rc.layer_tot_enc_frames[layer];
798 rc.layer_encoding_bitrate[layer] += 8.0 * sizes[sl];
799 // Keep count of rate control stats per layer, for non-key
801 if (tl == layer_id.temporal_layer_id &&
802 !(cx_pkt->data.frame.flags & VPX_FRAME_IS_KEY)) {
803 rc.layer_avg_frame_size[layer] += 8.0 * sizes[sl];
804 rc.layer_avg_rate_mismatch[layer] +=
805 fabs(8.0 * sizes[sl] - rc.layer_pfb[layer]) /
807 ++rc.layer_enc_frames[layer];
812 // Update for short-time encoding bitrate states, for moving
813 // window of size rc->window, shifted by rc->window / 2.
814 // Ignore first window segment, due to key frame.
815 if (frame_cnt > rc.window_size) {
816 tl = layer_id.temporal_layer_id;
817 for (sl = 0; sl < enc_cfg.ss_number_layers; ++sl) {
818 sum_bitrate += 0.001 * 8.0 * sizes[sl] * framerate;
820 if (frame_cnt % rc.window_size == 0) {
821 rc.window_count += 1;
822 rc.avg_st_encoding_bitrate += sum_bitrate / rc.window_size;
823 rc.variance_st_encoding_bitrate +=
824 (sum_bitrate / rc.window_size) *
825 (sum_bitrate / rc.window_size);
830 // Second shifted window.
831 if (frame_cnt > rc.window_size + rc.window_size / 2) {
832 tl = layer_id.temporal_layer_id;
833 for (sl = 0; sl < enc_cfg.ss_number_layers; ++sl) {
834 sum_bitrate2 += 0.001 * 8.0 * sizes[sl] * framerate;
837 if (frame_cnt > 2 * rc.window_size &&
838 frame_cnt % rc.window_size == 0) {
839 rc.window_count += 1;
840 rc.avg_st_encoding_bitrate += sum_bitrate2 / rc.window_size;
841 rc.variance_st_encoding_bitrate +=
842 (sum_bitrate2 / rc.window_size) *
843 (sum_bitrate2 / rc.window_size);
851 printf("SVC frame: %d, kf: %d, size: %d, pts: %d\n", frames_received,
852 !!(cx_pkt->data.frame.flags & VPX_FRAME_IS_KEY),
853 (int)cx_pkt->data.frame.sz, (int)cx_pkt->data.frame.pts);
857 case VPX_CODEC_STATS_PKT: {
858 stats_write(&app_input.rc_stats,
859 cx_pkt->data.twopass_stats.buf,
860 cx_pkt->data.twopass_stats.sz);
869 if (!end_of_stream) {
871 pts += frame_duration;
875 // Compensate for the extra frame count for the bypass mode.
876 if (svc_ctx.temporal_layering_mode == VP9E_TEMPORAL_LAYERING_MODE_BYPASS) {
877 for (sl = 0; sl < enc_cfg.ss_number_layers; ++sl) {
878 const int layer = sl * enc_cfg.ts_number_layers +
879 layer_id.temporal_layer_id;
880 --rc.layer_input_frames[layer];
884 printf("Processed %d frames\n", frame_cnt);
887 if (svc_ctx.output_rc_stat) {
888 printout_rate_control_summary(&rc, &enc_cfg, frame_cnt);
892 if (vpx_codec_destroy(&codec)) die_codec(&codec, "Failed to destroy codec");
893 if (app_input.passes == 2)
894 stats_close(&app_input.rc_stats, 1);
896 vpx_video_writer_close(writer);
899 if (svc_ctx.output_rc_stat) {
900 for (tl = 0; tl < enc_cfg.ts_number_layers; ++tl) {
901 vpx_video_writer_close(outfile[tl]);
905 printf("Frame cnt and encoding time/FPS stats for encoding: %d %f %f \n",
907 1000 * (float)cx_time / (double)(frame_cnt * 1000000),
908 1000000 * (double)frame_cnt / (double)cx_time);
910 // display average size, psnr
911 printf("%s", vpx_svc_dump_statistics(&svc_ctx));
912 vpx_svc_release(&svc_ctx);