WebM Codec SDK: vp9_spatial_svc_encoder

WebM Codec SDK

vp9_spatial_svc_encoder
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 <math.h>
18#include <stdarg.h>
19#include <stdio.h>
20#include <stdlib.h>
21#include <string.h>
22#include <time.h>
23
24#include "../args.h"
25#include "../tools_common.h"
26#include "../video_writer.h"
27
28#include "../vpx_ports/vpx_timer.h"
29#include "./svc_context.h"
30#include "vpx/vp8cx.h"
31#include "vpx/vpx_encoder.h"
32#include "../vpxstats.h"
33#include "vp9/encoder/vp9_encoder.h"
34#include "./y4minput.h"
35
36#define OUTPUT_FRAME_STATS 0
37#define OUTPUT_RC_STATS 1
38
39#define SIMULCAST_MODE 0
40
41static const arg_def_t outputfile =
42 ARG_DEF("o", "output", 1, "Output filename");
43static const arg_def_t skip_frames_arg =
44 ARG_DEF("s", "skip-frames", 1, "input frames to skip");
45static const arg_def_t frames_arg =
46 ARG_DEF("f", "frames", 1, "number of frames to encode");
47static const arg_def_t threads_arg =
48 ARG_DEF("th", "threads", 1, "number of threads to use");
49#if OUTPUT_RC_STATS
50static const arg_def_t output_rc_stats_arg =
51 ARG_DEF("rcstat", "output_rc_stats", 1, "output rc stats");
52#endif
53static const arg_def_t width_arg = ARG_DEF("w", "width", 1, "source width");
54static const arg_def_t height_arg = ARG_DEF("h", "height", 1, "source height");
55static const arg_def_t timebase_arg =
56 ARG_DEF("t", "timebase", 1, "timebase (num/den)");
57static const arg_def_t bitrate_arg = ARG_DEF(
58 "b", "target-bitrate", 1, "encoding bitrate, in kilobits per second");
59static const arg_def_t spatial_layers_arg =
60 ARG_DEF("sl", "spatial-layers", 1, "number of spatial SVC layers");
61static const arg_def_t temporal_layers_arg =
62 ARG_DEF("tl", "temporal-layers", 1, "number of temporal SVC layers");
63static const arg_def_t temporal_layering_mode_arg =
64 ARG_DEF("tlm", "temporal-layering-mode", 1,
65 "temporal layering scheme."
66 "VP9E_TEMPORAL_LAYERING_MODE");
67static const arg_def_t kf_dist_arg =
68 ARG_DEF("k", "kf-dist", 1, "number of frames between keyframes");
69static const arg_def_t scale_factors_arg =
70 ARG_DEF("r", "scale-factors", 1, "scale factors (lowest to highest layer)");
71static const arg_def_t min_q_arg =
72 ARG_DEF(NULL, "min-q", 1, "Minimum quantizer");
73static const arg_def_t max_q_arg =
74 ARG_DEF(NULL, "max-q", 1, "Maximum quantizer");
75static const arg_def_t min_bitrate_arg =
76 ARG_DEF(NULL, "min-bitrate", 1, "Minimum bitrate");
77static const arg_def_t max_bitrate_arg =
78 ARG_DEF(NULL, "max-bitrate", 1, "Maximum bitrate");
79static const arg_def_t lag_in_frame_arg =
80 ARG_DEF(NULL, "lag-in-frames", 1,
81 "Number of frame to input before "
82 "generating any outputs");
83static const arg_def_t rc_end_usage_arg =
84 ARG_DEF(NULL, "rc-end-usage", 1, "0 - 3: VBR, CBR, CQ, Q");
85static const arg_def_t speed_arg =
86 ARG_DEF("sp", "speed", 1, "speed configuration");
87static const arg_def_t aqmode_arg =
88 ARG_DEF("aq", "aqmode", 1, "aq-mode off/on");
89static const arg_def_t bitrates_arg =
90 ARG_DEF("bl", "bitrates", 1, "bitrates[sl * num_tl + tl]");
91static const arg_def_t dropframe_thresh_arg =
92 ARG_DEF(NULL, "drop-frame", 1, "Temporal resampling threshold (buf %)");
93static const struct arg_enum_list tune_content_enum[] = {
94 { "default", VP9E_CONTENT_DEFAULT },
95 { "screen", VP9E_CONTENT_SCREEN },
96 { "film", VP9E_CONTENT_FILM },
97 { NULL, 0 }
98};
99
100static const arg_def_t tune_content_arg = ARG_DEF_ENUM(
101 NULL, "tune-content", 1, "Tune content type", tune_content_enum);
102static const arg_def_t inter_layer_pred_arg = ARG_DEF(
103 NULL, "inter-layer-pred", 1, "0 - 3: On, Off, Key-frames, Constrained");
104
105#if CONFIG_VP9_HIGHBITDEPTH
106static const struct arg_enum_list bitdepth_enum[] = {
107 { "8", VPX_BITS_8 }, { "10", VPX_BITS_10 }, { "12", VPX_BITS_12 }, { NULL, 0 }
108};
109
110static const arg_def_t bitdepth_arg = ARG_DEF_ENUM(
111 "d", "bit-depth", 1, "Bit depth for codec 8, 10 or 12. ", bitdepth_enum);
112#endif // CONFIG_VP9_HIGHBITDEPTH
113
114static const arg_def_t *svc_args[] = { &frames_arg,
115 &outputfile,
116 &width_arg,
117 &height_arg,
118 &timebase_arg,
119 &bitrate_arg,
120 &skip_frames_arg,
121 &spatial_layers_arg,
122 &kf_dist_arg,
123 &scale_factors_arg,
124 &min_q_arg,
125 &max_q_arg,
126 &min_bitrate_arg,
127 &max_bitrate_arg,
128 &temporal_layers_arg,
129 &temporal_layering_mode_arg,
130 &lag_in_frame_arg,
131 &threads_arg,
132 &aqmode_arg,
133#if OUTPUT_RC_STATS
134 &output_rc_stats_arg,
135#endif
136
137#if CONFIG_VP9_HIGHBITDEPTH
138 &bitdepth_arg,
139#endif
140 &speed_arg,
141 &rc_end_usage_arg,
142 &bitrates_arg,
143 &dropframe_thresh_arg,
144 &tune_content_arg,
145 &inter_layer_pred_arg,
146 NULL };
147
148static const uint32_t default_frames_to_skip = 0;
149static const uint32_t default_frames_to_code = 60 * 60;
150static const uint32_t default_width = 1920;
151static const uint32_t default_height = 1080;
152static const uint32_t default_timebase_num = 1;
153static const uint32_t default_timebase_den = 60;
154static const uint32_t default_bitrate = 1000;
155static const uint32_t default_spatial_layers = 5;
156static const uint32_t default_temporal_layers = 1;
157static const uint32_t default_kf_dist = 100;
158static const uint32_t default_temporal_layering_mode = 0;
159static const uint32_t default_output_rc_stats = 0;
160static const int32_t default_speed = -1; // -1 means use library default.
161static const uint32_t default_threads = 0; // zero means use library default.
162
163typedef struct {
164 const char *output_filename;
165 uint32_t frames_to_code;
166 uint32_t frames_to_skip;
167 struct VpxInputContext input_ctx;
168 stats_io_t rc_stats;
169 int tune_content;
170 int inter_layer_pred;
171} AppInput;
172
173static const char *exec_name;
174
175void usage_exit(void) {
176 fprintf(stderr, "Usage: %s <options> input_filename -o output_filename\n",
177 exec_name);
178 fprintf(stderr, "Options:\n");
179 arg_show_usage(stderr, svc_args);
180 exit(EXIT_FAILURE);
181}
182
183static void parse_command_line(int argc, const char **argv_,
184 AppInput *app_input, SvcContext *svc_ctx,
185 vpx_codec_enc_cfg_t *enc_cfg) {
186 struct arg arg;
187 char **argv = NULL;
188 char **argi = NULL;
189 char **argj = NULL;
190 vpx_codec_err_t res;
191 unsigned int min_bitrate = 0;
192 unsigned int max_bitrate = 0;
193 char string_options[1024] = { 0 };
194
195 // initialize SvcContext with parameters that will be passed to vpx_svc_init
196 svc_ctx->log_level = SVC_LOG_DEBUG;
197 svc_ctx->spatial_layers = default_spatial_layers;
198 svc_ctx->temporal_layers = default_temporal_layers;
199 svc_ctx->temporal_layering_mode = default_temporal_layering_mode;
200#if OUTPUT_RC_STATS
201 svc_ctx->output_rc_stat = default_output_rc_stats;
202#endif
203 svc_ctx->speed = default_speed;
204 svc_ctx->threads = default_threads;
205
206 // start with default encoder configuration
207 res = vpx_codec_enc_config_default(vpx_codec_vp9_cx(), enc_cfg, 0);
208 if (res) {
209 die("Failed to get config: %s\n", vpx_codec_err_to_string(res));
210 }
211 // update enc_cfg with app default values
212 enc_cfg->g_w = default_width;
213 enc_cfg->g_h = default_height;
214 enc_cfg->g_timebase.num = default_timebase_num;
215 enc_cfg->g_timebase.den = default_timebase_den;
216 enc_cfg->rc_target_bitrate = default_bitrate;
217 enc_cfg->kf_min_dist = default_kf_dist;
218 enc_cfg->kf_max_dist = default_kf_dist;
219 enc_cfg->rc_end_usage = VPX_CQ;
220
221 // initialize AppInput with default values
222 app_input->frames_to_code = default_frames_to_code;
223 app_input->frames_to_skip = default_frames_to_skip;
224
225 // process command line options
226 argv = argv_dup(argc - 1, argv_ + 1);
227 if (!argv) {
228 fprintf(stderr, "Error allocating argument list\n");
229 exit(EXIT_FAILURE);
230 }
231 for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step) {
232 arg.argv_step = 1;
233
234 if (arg_match(&arg, &frames_arg, argi)) {
235 app_input->frames_to_code = arg_parse_uint(&arg);
236 } else if (arg_match(&arg, &outputfile, argi)) {
237 app_input->output_filename = arg.val;
238 } else if (arg_match(&arg, &width_arg, argi)) {
239 enc_cfg->g_w = arg_parse_uint(&arg);
240 } else if (arg_match(&arg, &height_arg, argi)) {
241 enc_cfg->g_h = arg_parse_uint(&arg);
242 } else if (arg_match(&arg, &timebase_arg, argi)) {
243 enc_cfg->g_timebase = arg_parse_rational(&arg);
244 } else if (arg_match(&arg, &bitrate_arg, argi)) {
245 enc_cfg->rc_target_bitrate = arg_parse_uint(&arg);
246 } else if (arg_match(&arg, &skip_frames_arg, argi)) {
247 app_input->frames_to_skip = arg_parse_uint(&arg);
248 } else if (arg_match(&arg, &spatial_layers_arg, argi)) {
249 svc_ctx->spatial_layers = arg_parse_uint(&arg);
250 } else if (arg_match(&arg, &temporal_layers_arg, argi)) {
251 svc_ctx->temporal_layers = arg_parse_uint(&arg);
252#if OUTPUT_RC_STATS
253 } else if (arg_match(&arg, &output_rc_stats_arg, argi)) {
254 svc_ctx->output_rc_stat = arg_parse_uint(&arg);
255#endif
256 } else if (arg_match(&arg, &speed_arg, argi)) {
257 svc_ctx->speed = arg_parse_uint(&arg);
258 if (svc_ctx->speed > 9) {
259 warn("Mapping speed %d to speed 9.\n", svc_ctx->speed);
260 }
261 } else if (arg_match(&arg, &aqmode_arg, argi)) {
262 svc_ctx->aqmode = arg_parse_uint(&arg);
263 } else if (arg_match(&arg, &threads_arg, argi)) {
264 svc_ctx->threads = arg_parse_uint(&arg);
265 } else if (arg_match(&arg, &temporal_layering_mode_arg, argi)) {
266 svc_ctx->temporal_layering_mode = enc_cfg->temporal_layering_mode =
267 arg_parse_int(&arg);
268 if (svc_ctx->temporal_layering_mode) {
269 enc_cfg->g_error_resilient = 1;
270 }
271 } else if (arg_match(&arg, &kf_dist_arg, argi)) {
272 enc_cfg->kf_min_dist = arg_parse_uint(&arg);
273 enc_cfg->kf_max_dist = enc_cfg->kf_min_dist;
274 } else if (arg_match(&arg, &scale_factors_arg, argi)) {
275 strncat(string_options, " scale-factors=",
276 sizeof(string_options) - strlen(string_options) - 1);
277 strncat(string_options, arg.val,
278 sizeof(string_options) - strlen(string_options) - 1);
279 } else if (arg_match(&arg, &bitrates_arg, argi)) {
280 strncat(string_options, " bitrates=",
281 sizeof(string_options) - strlen(string_options) - 1);
282 strncat(string_options, arg.val,
283 sizeof(string_options) - strlen(string_options) - 1);
284 } else if (arg_match(&arg, &min_q_arg, argi)) {
285 strncat(string_options, " min-quantizers=",
286 sizeof(string_options) - strlen(string_options) - 1);
287 strncat(string_options, arg.val,
288 sizeof(string_options) - strlen(string_options) - 1);
289 } else if (arg_match(&arg, &max_q_arg, argi)) {
290 strncat(string_options, " max-quantizers=",
291 sizeof(string_options) - strlen(string_options) - 1);
292 strncat(string_options, arg.val,
293 sizeof(string_options) - strlen(string_options) - 1);
294 } else if (arg_match(&arg, &min_bitrate_arg, argi)) {
295 min_bitrate = arg_parse_uint(&arg);
296 } else if (arg_match(&arg, &max_bitrate_arg, argi)) {
297 max_bitrate = arg_parse_uint(&arg);
298 } else if (arg_match(&arg, &lag_in_frame_arg, argi)) {
299 enc_cfg->g_lag_in_frames = arg_parse_uint(&arg);
300 } else if (arg_match(&arg, &rc_end_usage_arg, argi)) {
301 enc_cfg->rc_end_usage = arg_parse_uint(&arg);
302#if CONFIG_VP9_HIGHBITDEPTH
303 } else if (arg_match(&arg, &bitdepth_arg, argi)) {
304 enc_cfg->g_bit_depth = arg_parse_enum_or_int(&arg);
305 switch (enc_cfg->g_bit_depth) {
306 case VPX_BITS_8:
307 enc_cfg->g_input_bit_depth = 8;
308 enc_cfg->g_profile = 0;
309 break;
310 case VPX_BITS_10:
311 enc_cfg->g_input_bit_depth = 10;
312 enc_cfg->g_profile = 2;
313 break;
314 case VPX_BITS_12:
315 enc_cfg->g_input_bit_depth = 12;
316 enc_cfg->g_profile = 2;
317 break;
318 default:
319 die("Error: Invalid bit depth selected (%d)\n", enc_cfg->g_bit_depth);
320 }
321#endif // CONFIG_VP9_HIGHBITDEPTH
322 } else if (arg_match(&arg, &dropframe_thresh_arg, argi)) {
323 enc_cfg->rc_dropframe_thresh = arg_parse_uint(&arg);
324 } else if (arg_match(&arg, &tune_content_arg, argi)) {
325 app_input->tune_content = arg_parse_uint(&arg);
326 } else if (arg_match(&arg, &inter_layer_pred_arg, argi)) {
327 app_input->inter_layer_pred = arg_parse_uint(&arg);
328 } else {
329 ++argj;
330 }
331 }
332
333 // There will be a space in front of the string options
334 if (strlen(string_options) > 0)
335 vpx_svc_set_options(svc_ctx, string_options + 1);
336
337 enc_cfg->g_pass = VPX_RC_ONE_PASS;
338
339 if (enc_cfg->rc_target_bitrate > 0) {
340 if (min_bitrate > 0) {
341 enc_cfg->rc_2pass_vbr_minsection_pct =
342 min_bitrate * 100 / enc_cfg->rc_target_bitrate;
343 }
344 if (max_bitrate > 0) {
345 enc_cfg->rc_2pass_vbr_maxsection_pct =
346 max_bitrate * 100 / enc_cfg->rc_target_bitrate;
347 }
348 }
349
350 // Check for unrecognized options
351 for (argi = argv; *argi; ++argi)
352 if (argi[0][0] == '-' && strlen(argi[0]) > 1)
353 die("Error: Unrecognized option %s\n", *argi);
354
355 if (argv[0] == NULL) {
356 usage_exit();
357 }
358 app_input->input_ctx.filename = argv[0];
359 free(argv);
360
361 open_input_file(&app_input->input_ctx);
362 if (app_input->input_ctx.file_type == FILE_TYPE_Y4M) {
363 enc_cfg->g_w = app_input->input_ctx.width;
364 enc_cfg->g_h = app_input->input_ctx.height;
365 enc_cfg->g_timebase.den = app_input->input_ctx.framerate.numerator;
366 enc_cfg->g_timebase.num = app_input->input_ctx.framerate.denominator;
367 }
368
369 if (enc_cfg->g_w < 16 || enc_cfg->g_w % 2 || enc_cfg->g_h < 16 ||
370 enc_cfg->g_h % 2)
371 die("Invalid resolution: %d x %d\n", enc_cfg->g_w, enc_cfg->g_h);
372
373 printf(
374 "Codec %s\nframes: %d, skip: %d\n"
375 "layers: %d\n"
376 "width %d, height: %d,\n"
377 "num: %d, den: %d, bitrate: %d,\n"
378 "gop size: %d\n",
379 vpx_codec_iface_name(vpx_codec_vp9_cx()), app_input->frames_to_code,
380 app_input->frames_to_skip, svc_ctx->spatial_layers, enc_cfg->g_w,
381 enc_cfg->g_h, enc_cfg->g_timebase.num, enc_cfg->g_timebase.den,
382 enc_cfg->rc_target_bitrate, enc_cfg->kf_max_dist);
383}
384
385#if OUTPUT_RC_STATS
386// For rate control encoding stats.
387struct RateControlStats {
388 // Number of input frames per layer.
389 int layer_input_frames[VPX_MAX_LAYERS];
390 // Total (cumulative) number of encoded frames per layer.
391 int layer_tot_enc_frames[VPX_MAX_LAYERS];
392 // Number of encoded non-key frames per layer.
393 int layer_enc_frames[VPX_MAX_LAYERS];
394 // Framerate per layer (cumulative).
395 double layer_framerate[VPX_MAX_LAYERS];
396 // Target average frame size per layer (per-frame-bandwidth per layer).
397 double layer_pfb[VPX_MAX_LAYERS];
398 // Actual average frame size per layer.
399 double layer_avg_frame_size[VPX_MAX_LAYERS];
400 // Average rate mismatch per layer (|target - actual| / target).
401 double layer_avg_rate_mismatch[VPX_MAX_LAYERS];
402 // Actual encoding bitrate per layer (cumulative).
403 double layer_encoding_bitrate[VPX_MAX_LAYERS];
404 // Average of the short-time encoder actual bitrate.
405 // TODO(marpan): Should we add these short-time stats for each layer?
406 double avg_st_encoding_bitrate;
407 // Variance of the short-time encoder actual bitrate.
408 double variance_st_encoding_bitrate;
409 // Window (number of frames) for computing short-time encoding bitrate.
410 int window_size;
411 // Number of window measurements.
412 int window_count;
413};
414
415// Note: these rate control stats assume only 1 key frame in the
416// sequence (i.e., first frame only).
417static void set_rate_control_stats(struct RateControlStats *rc,
418 vpx_codec_enc_cfg_t *cfg) {
419 unsigned int sl, tl;
420 // Set the layer (cumulative) framerate and the target layer (non-cumulative)
421 // per-frame-bandwidth, for the rate control encoding stats below.
422 const double framerate = cfg->g_timebase.den / cfg->g_timebase.num;
423
424 for (sl = 0; sl < cfg->ss_number_layers; ++sl) {
425 for (tl = 0; tl < cfg->ts_number_layers; ++tl) {
426 const int layer = sl * cfg->ts_number_layers + tl;
427 if (cfg->ts_number_layers == 1)
428 rc->layer_framerate[layer] = framerate;
429 else
430 rc->layer_framerate[layer] = framerate / cfg->ts_rate_decimator[tl];
431 if (tl > 0) {
432 rc->layer_pfb[layer] =
433 1000.0 *
434 (cfg->layer_target_bitrate[layer] -
435 cfg->layer_target_bitrate[layer - 1]) /
436 (rc->layer_framerate[layer] - rc->layer_framerate[layer - 1]);
437 } else {
438 rc->layer_pfb[layer] = 1000.0 * cfg->layer_target_bitrate[layer] /
439 rc->layer_framerate[layer];
440 }
441 rc->layer_input_frames[layer] = 0;
442 rc->layer_enc_frames[layer] = 0;
443 rc->layer_tot_enc_frames[layer] = 0;
444 rc->layer_encoding_bitrate[layer] = 0.0;
445 rc->layer_avg_frame_size[layer] = 0.0;
446 rc->layer_avg_rate_mismatch[layer] = 0.0;
447 }
448 }
449 rc->window_count = 0;
450 rc->window_size = 15;
451 rc->avg_st_encoding_bitrate = 0.0;
452 rc->variance_st_encoding_bitrate = 0.0;
453}
454
455static void printout_rate_control_summary(struct RateControlStats *rc,
456 vpx_codec_enc_cfg_t *cfg,
457 int frame_cnt) {
458 unsigned int sl, tl;
459 double perc_fluctuation = 0.0;
460 int tot_num_frames = 0;
461 printf("Total number of processed frames: %d\n\n", frame_cnt - 1);
462 printf("Rate control layer stats for sl%d tl%d layer(s):\n\n",
463 cfg->ss_number_layers, cfg->ts_number_layers);
464 for (sl = 0; sl < cfg->ss_number_layers; ++sl) {
465 tot_num_frames = 0;
466 for (tl = 0; tl < cfg->ts_number_layers; ++tl) {
467 const int layer = sl * cfg->ts_number_layers + tl;
468 const int num_dropped =
469 (tl > 0)
470 ? (rc->layer_input_frames[layer] - rc->layer_enc_frames[layer])
471 : (rc->layer_input_frames[layer] - rc->layer_enc_frames[layer] -
472 1);
473 tot_num_frames += rc->layer_input_frames[layer];
474 rc->layer_encoding_bitrate[layer] = 0.001 * rc->layer_framerate[layer] *
475 rc->layer_encoding_bitrate[layer] /
476 tot_num_frames;
477 rc->layer_avg_frame_size[layer] =
478 rc->layer_avg_frame_size[layer] / rc->layer_enc_frames[layer];
479 rc->layer_avg_rate_mismatch[layer] = 100.0 *
480 rc->layer_avg_rate_mismatch[layer] /
481 rc->layer_enc_frames[layer];
482 printf("For layer#: sl%d tl%d \n", sl, tl);
483 printf("Bitrate (target vs actual): %d %f.0 kbps\n",
484 cfg->layer_target_bitrate[layer],
485 rc->layer_encoding_bitrate[layer]);
486 printf("Average frame size (target vs actual): %f %f bits\n",
487 rc->layer_pfb[layer], rc->layer_avg_frame_size[layer]);
488 printf("Average rate_mismatch: %f\n", rc->layer_avg_rate_mismatch[layer]);
489 printf(
490 "Number of input frames, encoded (non-key) frames, "
491 "and percent dropped frames: %d %d %f.0 \n",
492 rc->layer_input_frames[layer], rc->layer_enc_frames[layer],
493 100.0 * num_dropped / rc->layer_input_frames[layer]);
494 printf("\n");
495 }
496 }
497 rc->avg_st_encoding_bitrate = rc->avg_st_encoding_bitrate / rc->window_count;
498 rc->variance_st_encoding_bitrate =
499 rc->variance_st_encoding_bitrate / rc->window_count -
500 (rc->avg_st_encoding_bitrate * rc->avg_st_encoding_bitrate);
501 perc_fluctuation = 100.0 * sqrt(rc->variance_st_encoding_bitrate) /
502 rc->avg_st_encoding_bitrate;
503 printf("Short-time stats, for window of %d frames: \n", rc->window_size);
504 printf("Average, rms-variance, and percent-fluct: %f %f %f \n",
505 rc->avg_st_encoding_bitrate, sqrt(rc->variance_st_encoding_bitrate),
506 perc_fluctuation);
507 printf("Num of input, num of encoded (super) frames: %d %d \n", frame_cnt,
508 tot_num_frames);
509}
510
511static vpx_codec_err_t parse_superframe_index(const uint8_t *data,
512 size_t data_sz, uint64_t sizes[8],
513 int *count) {
514 // A chunk ending with a byte matching 0xc0 is an invalid chunk unless
515 // it is a super frame index. If the last byte of real video compression
516 // data is 0xc0 the encoder must add a 0 byte. If we have the marker but
517 // not the associated matching marker byte at the front of the index we have
518 // an invalid bitstream and need to return an error.
519
520 uint8_t marker;
521
522 marker = *(data + data_sz - 1);
523 *count = 0;
524
525 if ((marker & 0xe0) == 0xc0) {
526 const uint32_t frames = (marker & 0x7) + 1;
527 const uint32_t mag = ((marker >> 3) & 0x3) + 1;
528 const size_t index_sz = 2 + mag * frames;
529
530 // This chunk is marked as having a superframe index but doesn't have
531 // enough data for it, thus it's an invalid superframe index.
532 if (data_sz < index_sz) return VPX_CODEC_CORRUPT_FRAME;
533
534 {
535 const uint8_t marker2 = *(data + data_sz - index_sz);
536
537 // This chunk is marked as having a superframe index but doesn't have
538 // the matching marker byte at the front of the index therefore it's an
539 // invalid chunk.
540 if (marker != marker2) return VPX_CODEC_CORRUPT_FRAME;
541 }
542
543 {
544 // Found a valid superframe index.
545 uint32_t i, j;
546 const uint8_t *x = &data[data_sz - index_sz + 1];
547
548 for (i = 0; i < frames; ++i) {
549 uint32_t this_sz = 0;
550
551 for (j = 0; j < mag; ++j) this_sz |= (*x++) << (j * 8);
552 sizes[i] = this_sz;
553 }
554 *count = frames;
555 }
556 }
557 return VPX_CODEC_OK;
558}
559#endif
560
561// Example pattern for spatial layers and 2 temporal layers used in the
562// bypass/flexible mode. The pattern corresponds to the pattern
563// VP9E_TEMPORAL_LAYERING_MODE_0101 (temporal_layering_mode == 2) used in
564// non-flexible mode.
565static void set_frame_flags_bypass_mode_ex0(
566 int tl, int num_spatial_layers, int is_key_frame,
567 vpx_svc_ref_frame_config_t *ref_frame_config) {
568 int sl;
569 for (sl = 0; sl < num_spatial_layers; ++sl)
570 ref_frame_config->update_buffer_slot[sl] = 0;
571
572 for (sl = 0; sl < num_spatial_layers; ++sl) {
573 // Set the buffer idx.
574 if (tl == 0) {
575 ref_frame_config->lst_fb_idx[sl] = sl;
576 if (sl) {
577 if (is_key_frame) {
578 ref_frame_config->lst_fb_idx[sl] = sl - 1;
579 ref_frame_config->gld_fb_idx[sl] = sl;
580 } else {
581 ref_frame_config->gld_fb_idx[sl] = sl - 1;
582 }
583 } else {
584 ref_frame_config->gld_fb_idx[sl] = 0;
585 }
586 ref_frame_config->alt_fb_idx[sl] = 0;
587 } else if (tl == 1) {
588 ref_frame_config->lst_fb_idx[sl] = sl;
589 ref_frame_config->gld_fb_idx[sl] =
590 (sl == 0) ? 0 : num_spatial_layers + sl - 1;
591 ref_frame_config->alt_fb_idx[sl] = num_spatial_layers + sl;
592 }
593 // Set the reference and update flags.
594 if (!tl) {
595 if (!sl) {
596 // Base spatial and base temporal (sl = 0, tl = 0)
597 ref_frame_config->reference_last[sl] = 1;
598 ref_frame_config->reference_golden[sl] = 0;
599 ref_frame_config->reference_alt_ref[sl] = 0;
600 ref_frame_config->update_buffer_slot[sl] |=
601 1 << ref_frame_config->lst_fb_idx[sl];
602 } else {
603 if (is_key_frame) {
604 ref_frame_config->reference_last[sl] = 1;
605 ref_frame_config->reference_golden[sl] = 0;
606 ref_frame_config->reference_alt_ref[sl] = 0;
607 ref_frame_config->update_buffer_slot[sl] |=
608 1 << ref_frame_config->gld_fb_idx[sl];
609 } else {
610 // Non-zero spatiall layer.
611 ref_frame_config->reference_last[sl] = 1;
612 ref_frame_config->reference_golden[sl] = 1;
613 ref_frame_config->reference_alt_ref[sl] = 1;
614 ref_frame_config->update_buffer_slot[sl] |=
615 1 << ref_frame_config->lst_fb_idx[sl];
616 }
617 }
618 } else if (tl == 1) {
619 if (!sl) {
620 // Base spatial and top temporal (tl = 1)
621 ref_frame_config->reference_last[sl] = 1;
622 ref_frame_config->reference_golden[sl] = 0;
623 ref_frame_config->reference_alt_ref[sl] = 0;
624 ref_frame_config->update_buffer_slot[sl] |=
625 1 << ref_frame_config->alt_fb_idx[sl];
626 } else {
627 // Non-zero spatial.
628 if (sl < num_spatial_layers - 1) {
629 ref_frame_config->reference_last[sl] = 1;
630 ref_frame_config->reference_golden[sl] = 1;
631 ref_frame_config->reference_alt_ref[sl] = 0;
632 ref_frame_config->update_buffer_slot[sl] |=
633 1 << ref_frame_config->alt_fb_idx[sl];
634 } else if (sl == num_spatial_layers - 1) {
635 // Top spatial and top temporal (non-reference -- doesn't update any
636 // reference buffers)
637 ref_frame_config->reference_last[sl] = 1;
638 ref_frame_config->reference_golden[sl] = 1;
639 ref_frame_config->reference_alt_ref[sl] = 0;
640 }
641 }
642 }
643 }
644}
645
646// Example pattern for 2 spatial layers and 2 temporal layers used in the
647// bypass/flexible mode, except only 1 spatial layer when temporal_layer_id = 1.
648static void set_frame_flags_bypass_mode_ex1(
649 int tl, int num_spatial_layers, int is_key_frame,
650 vpx_svc_ref_frame_config_t *ref_frame_config) {
651 int sl;
652 for (sl = 0; sl < num_spatial_layers; ++sl)
653 ref_frame_config->update_buffer_slot[sl] = 0;
654
655 if (tl == 0) {
656 if (is_key_frame) {
657 ref_frame_config->lst_fb_idx[1] = 0;
658 ref_frame_config->gld_fb_idx[1] = 1;
659 } else {
660 ref_frame_config->lst_fb_idx[1] = 1;
661 ref_frame_config->gld_fb_idx[1] = 0;
662 }
663 ref_frame_config->alt_fb_idx[1] = 0;
664
665 ref_frame_config->lst_fb_idx[0] = 0;
666 ref_frame_config->gld_fb_idx[0] = 0;
667 ref_frame_config->alt_fb_idx[0] = 0;
668 }
669 if (tl == 1) {
670 ref_frame_config->lst_fb_idx[0] = 0;
671 ref_frame_config->gld_fb_idx[0] = 1;
672 ref_frame_config->alt_fb_idx[0] = 2;
673
674 ref_frame_config->lst_fb_idx[1] = 1;
675 ref_frame_config->gld_fb_idx[1] = 2;
676 ref_frame_config->alt_fb_idx[1] = 3;
677 }
678 // Set the reference and update flags.
679 if (tl == 0) {
680 // Base spatial and base temporal (sl = 0, tl = 0)
681 ref_frame_config->reference_last[0] = 1;
682 ref_frame_config->reference_golden[0] = 0;
683 ref_frame_config->reference_alt_ref[0] = 0;
684 ref_frame_config->update_buffer_slot[0] |=
685 1 << ref_frame_config->lst_fb_idx[0];
686
687 if (is_key_frame) {
688 ref_frame_config->reference_last[1] = 1;
689 ref_frame_config->reference_golden[1] = 0;
690 ref_frame_config->reference_alt_ref[1] = 0;
691 ref_frame_config->update_buffer_slot[1] |=
692 1 << ref_frame_config->gld_fb_idx[1];
693 } else {
694 // Non-zero spatiall layer.
695 ref_frame_config->reference_last[1] = 1;
696 ref_frame_config->reference_golden[1] = 1;
697 ref_frame_config->reference_alt_ref[1] = 1;
698 ref_frame_config->update_buffer_slot[1] |=
699 1 << ref_frame_config->lst_fb_idx[1];
700 }
701 }
702 if (tl == 1) {
703 // Top spatial and top temporal (non-reference -- doesn't update any
704 // reference buffers)
705 ref_frame_config->reference_last[1] = 1;
706 ref_frame_config->reference_golden[1] = 0;
707 ref_frame_config->reference_alt_ref[1] = 0;
708 }
709}
710
711#if CONFIG_VP9_DECODER && !SIMULCAST_MODE
712static void test_decode(vpx_codec_ctx_t *encoder, vpx_codec_ctx_t *decoder,
713 const int frames_out, int *mismatch_seen) {
714 vpx_image_t enc_img, dec_img;
715 struct vp9_ref_frame ref_enc, ref_dec;
716 if (*mismatch_seen) return;
717 /* Get the internal reference frame */
718 ref_enc.idx = 0;
719 ref_dec.idx = 0;
720 vpx_codec_control(encoder, VP9_GET_REFERENCE, &ref_enc);
721 enc_img = ref_enc.img;
722 vpx_codec_control(decoder, VP9_GET_REFERENCE, &ref_dec);
723 dec_img = ref_dec.img;
724#if CONFIG_VP9_HIGHBITDEPTH
725 if ((enc_img.fmt & VPX_IMG_FMT_HIGHBITDEPTH) !=
726 (dec_img.fmt & VPX_IMG_FMT_HIGHBITDEPTH)) {
727 if (enc_img.fmt & VPX_IMG_FMT_HIGHBITDEPTH) {
728 vpx_img_alloc(&enc_img, enc_img.fmt - VPX_IMG_FMT_HIGHBITDEPTH,
729 enc_img.d_w, enc_img.d_h, 16);
730 vpx_img_truncate_16_to_8(&enc_img, &ref_enc.img);
731 }
732 if (dec_img.fmt & VPX_IMG_FMT_HIGHBITDEPTH) {
733 vpx_img_alloc(&dec_img, dec_img.fmt - VPX_IMG_FMT_HIGHBITDEPTH,
734 dec_img.d_w, dec_img.d_h, 16);
735 vpx_img_truncate_16_to_8(&dec_img, &ref_dec.img);
736 }
737 }
738#endif
739
740 if (!compare_img(&enc_img, &dec_img)) {
741 int y[4], u[4], v[4];
742#if CONFIG_VP9_HIGHBITDEPTH
743 if (enc_img.fmt & VPX_IMG_FMT_HIGHBITDEPTH) {
744 find_mismatch_high(&enc_img, &dec_img, y, u, v);
745 } else {
746 find_mismatch(&enc_img, &dec_img, y, u, v);
747 }
748#else
749 find_mismatch(&enc_img, &dec_img, y, u, v);
750#endif
751 decoder->err = 1;
752 printf(
753 "Encode/decode mismatch on frame %d at"
754 " Y[%d, %d] {%d/%d},"
755 " U[%d, %d] {%d/%d},"
756 " V[%d, %d] {%d/%d}\n",
757 frames_out, y[0], y[1], y[2], y[3], u[0], u[1], u[2], u[3], v[0], v[1],
758 v[2], v[3]);
759 *mismatch_seen = frames_out;
760 }
761
762 vpx_img_free(&enc_img);
763 vpx_img_free(&dec_img);
764}
765#endif
766
767#if OUTPUT_RC_STATS
768static void svc_output_rc_stats(
769 vpx_codec_ctx_t *codec, vpx_codec_enc_cfg_t *enc_cfg,
770 vpx_svc_layer_id_t *layer_id, const vpx_codec_cx_pkt_t *cx_pkt,
771 struct RateControlStats *rc, VpxVideoWriter **outfile,
772 const uint32_t frame_cnt, const double framerate) {
773 int num_layers_encoded = 0;
774 unsigned int sl, tl;
775 uint64_t sizes[8];
776 uint64_t sizes_parsed[8];
777 int count = 0;
778 double sum_bitrate = 0.0;
779 double sum_bitrate2 = 0.0;
780 vp9_zero(sizes);
781 vp9_zero(sizes_parsed);
782 vpx_codec_control(codec, VP9E_GET_SVC_LAYER_ID, layer_id);
783 parse_superframe_index(cx_pkt->data.frame.buf, cx_pkt->data.frame.sz,
784 sizes_parsed, &count);
785 if (enc_cfg->ss_number_layers == 1) {
786 sizes[0] = cx_pkt->data.frame.sz;
787 } else {
788 for (sl = 0; sl < enc_cfg->ss_number_layers; ++sl) {
789 sizes[sl] = 0;
790 if (cx_pkt->data.frame.spatial_layer_encoded[sl]) {
791 sizes[sl] = sizes_parsed[num_layers_encoded];
792 num_layers_encoded++;
793 }
794 }
795 }
796 for (sl = 0; sl < enc_cfg->ss_number_layers; ++sl) {
797 unsigned int sl2;
798 uint64_t tot_size = 0;
799#if SIMULCAST_MODE
800 for (sl2 = 0; sl2 < sl; ++sl2) {
801 if (cx_pkt->data.frame.spatial_layer_encoded[sl2]) tot_size += sizes[sl2];
802 }
803 vpx_video_writer_write_frame(outfile[sl],
804 (uint8_t *)(cx_pkt->data.frame.buf) + tot_size,
805 (size_t)(sizes[sl]), cx_pkt->data.frame.pts);
806#else
807 for (sl2 = 0; sl2 <= sl; ++sl2) {
808 if (cx_pkt->data.frame.spatial_layer_encoded[sl2]) tot_size += sizes[sl2];
809 }
810 if (tot_size > 0)
811 vpx_video_writer_write_frame(outfile[sl], cx_pkt->data.frame.buf,
812 (size_t)(tot_size), cx_pkt->data.frame.pts);
813#endif // SIMULCAST_MODE
814 }
815 for (sl = 0; sl < enc_cfg->ss_number_layers; ++sl) {
816 if (cx_pkt->data.frame.spatial_layer_encoded[sl]) {
817 for (tl = layer_id->temporal_layer_id; tl < enc_cfg->ts_number_layers;
818 ++tl) {
819 const int layer = sl * enc_cfg->ts_number_layers + tl;
820 ++rc->layer_tot_enc_frames[layer];
821 rc->layer_encoding_bitrate[layer] += 8.0 * sizes[sl];
822 // Keep count of rate control stats per layer, for non-key
823 // frames.
824 if (tl == (unsigned int)layer_id->temporal_layer_id &&
825 !(cx_pkt->data.frame.flags & VPX_FRAME_IS_KEY)) {
826 rc->layer_avg_frame_size[layer] += 8.0 * sizes[sl];
827 rc->layer_avg_rate_mismatch[layer] +=
828 fabs(8.0 * sizes[sl] - rc->layer_pfb[layer]) /
829 rc->layer_pfb[layer];
830 ++rc->layer_enc_frames[layer];
831 }
832 }
833 }
834 }
835
836 // Update for short-time encoding bitrate states, for moving
837 // window of size rc->window, shifted by rc->window / 2.
838 // Ignore first window segment, due to key frame.
839 if (frame_cnt > (unsigned int)rc->window_size) {
840 for (sl = 0; sl < enc_cfg->ss_number_layers; ++sl) {
841 if (cx_pkt->data.frame.spatial_layer_encoded[sl])
842 sum_bitrate += 0.001 * 8.0 * sizes[sl] * framerate;
843 }
844 if (frame_cnt % rc->window_size == 0) {
845 rc->window_count += 1;
846 rc->avg_st_encoding_bitrate += sum_bitrate / rc->window_size;
847 rc->variance_st_encoding_bitrate +=
848 (sum_bitrate / rc->window_size) * (sum_bitrate / rc->window_size);
849 }
850 }
851
852 // Second shifted window.
853 if (frame_cnt > (unsigned int)(rc->window_size + rc->window_size / 2)) {
854 for (sl = 0; sl < enc_cfg->ss_number_layers; ++sl) {
855 sum_bitrate2 += 0.001 * 8.0 * sizes[sl] * framerate;
856 }
857
858 if (frame_cnt > (unsigned int)(2 * rc->window_size) &&
859 frame_cnt % rc->window_size == 0) {
860 rc->window_count += 1;
861 rc->avg_st_encoding_bitrate += sum_bitrate2 / rc->window_size;
862 rc->variance_st_encoding_bitrate +=
863 (sum_bitrate2 / rc->window_size) * (sum_bitrate2 / rc->window_size);
864 }
865 }
866}
867#endif
868
869int main(int argc, const char **argv) {
870 AppInput app_input;
871 VpxVideoWriter *writer = NULL;
872 VpxVideoInfo info;
873 vpx_codec_ctx_t encoder;
874 vpx_codec_enc_cfg_t enc_cfg;
875 SvcContext svc_ctx;
876 vpx_svc_frame_drop_t svc_drop_frame;
877 uint32_t i;
878 uint32_t frame_cnt = 0;
879 vpx_image_t raw;
880 vpx_codec_err_t res;
881 int pts = 0; /* PTS starts at 0 */
882 int frame_duration = 1; /* 1 timebase tick per frame */
883 int end_of_stream = 0;
884#if OUTPUT_FRAME_STATS
885 int frames_received = 0;
886#endif
887#if OUTPUT_RC_STATS
888 VpxVideoWriter *outfile[VPX_SS_MAX_LAYERS] = { NULL };
889 struct RateControlStats rc;
890 vpx_svc_layer_id_t layer_id;
891 vpx_svc_ref_frame_config_t ref_frame_config;
892 unsigned int sl;
893 double framerate = 30.0;
894#endif
895 struct vpx_usec_timer timer;
896 int64_t cx_time = 0;
897#if CONFIG_INTERNAL_STATS
898 FILE *f = fopen("opsnr.stt", "a");
899#endif
900#if CONFIG_VP9_DECODER && !SIMULCAST_MODE
901 int mismatch_seen = 0;
902 vpx_codec_ctx_t decoder;
903#endif
904 memset(&svc_ctx, 0, sizeof(svc_ctx));
905 memset(&app_input, 0, sizeof(AppInput));
906 memset(&info, 0, sizeof(VpxVideoInfo));
907 memset(&layer_id, 0, sizeof(vpx_svc_layer_id_t));
908 memset(&rc, 0, sizeof(struct RateControlStats));
909 exec_name = argv[0];
910
911 /* Setup default input stream settings */
912 app_input.input_ctx.framerate.numerator = 30;
913 app_input.input_ctx.framerate.denominator = 1;
914 app_input.input_ctx.only_i420 = 1;
915 app_input.input_ctx.bit_depth = 0;
916
917 parse_command_line(argc, argv, &app_input, &svc_ctx, &enc_cfg);
918
919 // Y4M reader handles its own allocation.
920 if (app_input.input_ctx.file_type != FILE_TYPE_Y4M) {
921// Allocate image buffer
922#if CONFIG_VP9_HIGHBITDEPTH
923 if (!vpx_img_alloc(&raw,
924 enc_cfg.g_input_bit_depth == 8 ? VPX_IMG_FMT_I420
925 : VPX_IMG_FMT_I42016,
926 enc_cfg.g_w, enc_cfg.g_h, 32)) {
927 die("Failed to allocate image %dx%d\n", enc_cfg.g_w, enc_cfg.g_h);
928 }
929#else
930 if (!vpx_img_alloc(&raw, VPX_IMG_FMT_I420, enc_cfg.g_w, enc_cfg.g_h, 32)) {
931 die("Failed to allocate image %dx%d\n", enc_cfg.g_w, enc_cfg.g_h);
932 }
933#endif // CONFIG_VP9_HIGHBITDEPTH
934 }
935
936 // Initialize codec
937 if (vpx_svc_init(&svc_ctx, &encoder, vpx_codec_vp9_cx(), &enc_cfg) !=
938 VPX_CODEC_OK)
939 die("Failed to initialize encoder\n");
940#if CONFIG_VP9_DECODER && !SIMULCAST_MODE
941 if (vpx_codec_dec_init(
942 &decoder, get_vpx_decoder_by_name("vp9")->codec_interface(), NULL, 0))
943 die("Failed to initialize decoder\n");
944#endif
945
946#if OUTPUT_RC_STATS
947 rc.window_count = 1;
948 rc.window_size = 15; // Silence a static analysis warning.
949 rc.avg_st_encoding_bitrate = 0.0;
950 rc.variance_st_encoding_bitrate = 0.0;
951 if (svc_ctx.output_rc_stat) {
952 set_rate_control_stats(&rc, &enc_cfg);
953 framerate = enc_cfg.g_timebase.den / enc_cfg.g_timebase.num;
954 }
955#endif
956
957 info.codec_fourcc = VP9_FOURCC;
958 info.frame_width = enc_cfg.g_w;
959 info.frame_height = enc_cfg.g_h;
960 info.time_base.numerator = enc_cfg.g_timebase.num;
961 info.time_base.denominator = enc_cfg.g_timebase.den;
962
963 writer =
964 vpx_video_writer_open(app_input.output_filename, kContainerIVF, &info);
965 if (!writer)
966 die("Failed to open %s for writing\n", app_input.output_filename);
967
968#if OUTPUT_RC_STATS
969 // Write out spatial layer stream.
970 // TODO(marpan/jianj): allow for writing each spatial and temporal stream.
971 if (svc_ctx.output_rc_stat) {
972 for (sl = 0; sl < enc_cfg.ss_number_layers; ++sl) {
973 char file_name[PATH_MAX];
974
975 snprintf(file_name, sizeof(file_name), "%s_s%d.ivf",
976 app_input.output_filename, sl);
977 outfile[sl] = vpx_video_writer_open(file_name, kContainerIVF, &info);
978 if (!outfile[sl]) die("Failed to open %s for writing", file_name);
979 }
980 }
981#endif
982
983 // skip initial frames
984 for (i = 0; i < app_input.frames_to_skip; ++i)
985 read_frame(&app_input.input_ctx, &raw);
986
987 if (svc_ctx.speed != -1)
988 vpx_codec_control(&encoder, VP8E_SET_CPUUSED, svc_ctx.speed);
989 if (svc_ctx.threads) {
990 vpx_codec_control(&encoder, VP9E_SET_TILE_COLUMNS,
991 get_msb(svc_ctx.threads));
992 if (svc_ctx.threads > 1)
993 vpx_codec_control(&encoder, VP9E_SET_ROW_MT, 1);
994 else
995 vpx_codec_control(&encoder, VP9E_SET_ROW_MT, 0);
996 }
997 if (svc_ctx.speed >= 5 && svc_ctx.aqmode == 1)
998 vpx_codec_control(&encoder, VP9E_SET_AQ_MODE, 3);
999 if (svc_ctx.speed >= 5)
1000 vpx_codec_control(&encoder, VP8E_SET_STATIC_THRESHOLD, 1);
1001 vpx_codec_control(&encoder, VP8E_SET_MAX_INTRA_BITRATE_PCT, 900);
1002
1003 vpx_codec_control(&encoder, VP9E_SET_SVC_INTER_LAYER_PRED,
1004 app_input.inter_layer_pred);
1005
1006 vpx_codec_control(&encoder, VP9E_SET_NOISE_SENSITIVITY, 0);
1007
1008 vpx_codec_control(&encoder, VP9E_SET_TUNE_CONTENT, app_input.tune_content);
1009
1010 vpx_codec_control(&encoder, VP9E_SET_DISABLE_OVERSHOOT_MAXQ_CBR, 0);
1011 vpx_codec_control(&encoder, VP9E_SET_DISABLE_LOOPFILTER, 0);
1012
1013 svc_drop_frame.framedrop_mode = FULL_SUPERFRAME_DROP;
1014 for (sl = 0; sl < (unsigned int)svc_ctx.spatial_layers; ++sl)
1015 svc_drop_frame.framedrop_thresh[sl] = enc_cfg.rc_dropframe_thresh;
1016 svc_drop_frame.max_consec_drop = INT_MAX;
1017 vpx_codec_control(&encoder, VP9E_SET_SVC_FRAME_DROP_LAYER, &svc_drop_frame);
1018
1019 // Encode frames
1020 while (!end_of_stream) {
1021 vpx_codec_iter_t iter = NULL;
1022 const vpx_codec_cx_pkt_t *cx_pkt;
1023 // Example patterns for bypass/flexible mode:
1024 // example_pattern = 0: 2 temporal layers, and spatial_layers = 1,2,3. Exact
1025 // to fixed SVC patterns. example_pattern = 1: 2 spatial and 2 temporal
1026 // layers, with SL0 only has TL0, and SL1 has both TL0 and TL1. This example
1027 // uses the extended API.
1028 int example_pattern = 0;
1029 if (frame_cnt >= app_input.frames_to_code ||
1030 !read_frame(&app_input.input_ctx, &raw)) {
1031 // We need one extra vpx_svc_encode call at end of stream to flush
1032 // encoder and get remaining data
1033 end_of_stream = 1;
1034 }
1035
1036 // For BYPASS/FLEXIBLE mode, set the frame flags (reference and updates)
1037 // and the buffer indices for each spatial layer of the current
1038 // (super)frame to be encoded. The spatial and temporal layer_id for the
1039 // current frame also needs to be set.
1040 // TODO(marpan): Should rename the "VP9E_TEMPORAL_LAYERING_MODE_BYPASS"
1041 // mode to "VP9E_LAYERING_MODE_BYPASS".
1042 if (svc_ctx.temporal_layering_mode == VP9E_TEMPORAL_LAYERING_MODE_BYPASS) {
1043 layer_id.spatial_layer_id = 0;
1044 // Example for 2 temporal layers.
1045 if (frame_cnt % 2 == 0) {
1046 layer_id.temporal_layer_id = 0;
1047 for (i = 0; i < VPX_SS_MAX_LAYERS; i++)
1048 layer_id.temporal_layer_id_per_spatial[i] = 0;
1049 } else {
1050 layer_id.temporal_layer_id = 1;
1051 for (i = 0; i < VPX_SS_MAX_LAYERS; i++)
1052 layer_id.temporal_layer_id_per_spatial[i] = 1;
1053 }
1054 if (example_pattern == 1) {
1055 // example_pattern 1 is hard-coded for 2 spatial and 2 temporal layers.
1056 assert(svc_ctx.spatial_layers == 2);
1057 assert(svc_ctx.temporal_layers == 2);
1058 if (frame_cnt % 2 == 0) {
1059 // Spatial layer 0 and 1 are encoded.
1060 layer_id.temporal_layer_id_per_spatial[0] = 0;
1061 layer_id.temporal_layer_id_per_spatial[1] = 0;
1062 layer_id.spatial_layer_id = 0;
1063 } else {
1064 // Only spatial layer 1 is encoded here.
1065 layer_id.temporal_layer_id_per_spatial[1] = 1;
1066 layer_id.spatial_layer_id = 1;
1067 }
1068 }
1069 vpx_codec_control(&encoder, VP9E_SET_SVC_LAYER_ID, &layer_id);
1070 // TODO(jianj): Fix the parameter passing for "is_key_frame" in
1071 // set_frame_flags_bypass_model() for case of periodic key frames.
1072 if (example_pattern == 0) {
1073 set_frame_flags_bypass_mode_ex0(layer_id.temporal_layer_id,
1074 svc_ctx.spatial_layers, frame_cnt == 0,
1075 &ref_frame_config);
1076 } else if (example_pattern == 1) {
1077 set_frame_flags_bypass_mode_ex1(layer_id.temporal_layer_id,
1078 svc_ctx.spatial_layers, frame_cnt == 0,
1079 &ref_frame_config);
1080 }
1081 ref_frame_config.duration[0] = frame_duration * 1;
1082 ref_frame_config.duration[1] = frame_duration * 1;
1083
1084 vpx_codec_control(&encoder, VP9E_SET_SVC_REF_FRAME_CONFIG,
1085 &ref_frame_config);
1086 // Keep track of input frames, to account for frame drops in rate control
1087 // stats/metrics.
1088 for (sl = 0; sl < enc_cfg.ss_number_layers; ++sl) {
1089 ++rc.layer_input_frames[sl * enc_cfg.ts_number_layers +
1090 layer_id.temporal_layer_id];
1091 }
1092 } else {
1093 // For the fixed pattern SVC, temporal layer is given by superframe count.
1094 unsigned int tl = 0;
1095 if (enc_cfg.ts_number_layers == 2)
1096 tl = (frame_cnt % 2 != 0);
1097 else if (enc_cfg.ts_number_layers == 3) {
1098 if (frame_cnt % 2 != 0) tl = 2;
1099 if ((frame_cnt > 1) && ((frame_cnt - 2) % 4 == 0)) tl = 1;
1100 }
1101 for (sl = 0; sl < enc_cfg.ss_number_layers; ++sl)
1102 ++rc.layer_input_frames[sl * enc_cfg.ts_number_layers + tl];
1103 }
1104
1105 vpx_usec_timer_start(&timer);
1106 res = vpx_svc_encode(
1107 &svc_ctx, &encoder, (end_of_stream ? NULL : &raw), pts, frame_duration,
1108 svc_ctx.speed >= 5 ? VPX_DL_REALTIME : VPX_DL_GOOD_QUALITY);
1109 vpx_usec_timer_mark(&timer);
1110 cx_time += vpx_usec_timer_elapsed(&timer);
1111
1112 fflush(stdout);
1113 if (res != VPX_CODEC_OK) {
1114 die_codec(&encoder, "Failed to encode frame");
1115 }
1116
1117 while ((cx_pkt = vpx_codec_get_cx_data(&encoder, &iter)) != NULL) {
1118 switch (cx_pkt->kind) {
1119 case VPX_CODEC_CX_FRAME_PKT: {
1120 SvcInternal_t *const si = (SvcInternal_t *)svc_ctx.internal;
1121 if (cx_pkt->data.frame.sz > 0) {
1122 vpx_video_writer_write_frame(writer, cx_pkt->data.frame.buf,
1123 cx_pkt->data.frame.sz,
1124 cx_pkt->data.frame.pts);
1125#if OUTPUT_RC_STATS
1126 if (svc_ctx.output_rc_stat) {
1127 svc_output_rc_stats(&encoder, &enc_cfg, &layer_id, cx_pkt, &rc,
1128 outfile, frame_cnt, framerate);
1129 }
1130#endif
1131 }
1132#if OUTPUT_FRAME_STATS
1133 printf("SVC frame: %d, kf: %d, size: %d, pts: %d\n", frames_received,
1134 !!(cx_pkt->data.frame.flags & VPX_FRAME_IS_KEY),
1135 (int)cx_pkt->data.frame.sz, (int)cx_pkt->data.frame.pts);
1136 ++frames_received;
1137#endif
1138 if (enc_cfg.ss_number_layers == 1 && enc_cfg.ts_number_layers == 1)
1139 si->bytes_sum[0] += (int)cx_pkt->data.frame.sz;
1140#if CONFIG_VP9_DECODER && !SIMULCAST_MODE
1141 if (vpx_codec_decode(&decoder, cx_pkt->data.frame.buf,
1142 (unsigned int)cx_pkt->data.frame.sz, NULL, 0))
1143 die_codec(&decoder, "Failed to decode frame.");
1144#endif
1145 break;
1146 }
1147 case VPX_CODEC_STATS_PKT: {
1148 stats_write(&app_input.rc_stats, cx_pkt->data.twopass_stats.buf,
1149 cx_pkt->data.twopass_stats.sz);
1150 break;
1151 }
1152 default: {
1153 break;
1154 }
1155 }
1156
1157#if CONFIG_VP9_DECODER && !SIMULCAST_MODE
1158 vpx_codec_control(&encoder, VP9E_GET_SVC_LAYER_ID, &layer_id);
1159 // Don't look for mismatch on top spatial and top temporal layers as they
1160 // are non reference frames. Don't look at frames whose top spatial layer
1161 // is dropped.
1162 if ((enc_cfg.ss_number_layers > 1 || enc_cfg.ts_number_layers > 1) &&
1163 cx_pkt->data.frame
1164 .spatial_layer_encoded[enc_cfg.ss_number_layers - 1] &&
1165 !(layer_id.temporal_layer_id > 0 &&
1166 layer_id.temporal_layer_id == (int)enc_cfg.ts_number_layers - 1)) {
1167 test_decode(&encoder, &decoder, frame_cnt, &mismatch_seen);
1168 }
1169#endif
1170 }
1171
1172 if (!end_of_stream) {
1173 ++frame_cnt;
1174 pts += frame_duration;
1175 }
1176 }
1177
1178 printf("Processed %d frames\n", frame_cnt);
1179
1180 close_input_file(&app_input.input_ctx);
1181
1182#if OUTPUT_RC_STATS
1183 if (svc_ctx.output_rc_stat) {
1184 printout_rate_control_summary(&rc, &enc_cfg, frame_cnt);
1185 printf("\n");
1186 }
1187#endif
1188 if (vpx_codec_destroy(&encoder))
1189 die_codec(&encoder, "Failed to destroy codec");
1190 if (writer) {
1191 vpx_video_writer_close(writer);
1192 }
1193#if OUTPUT_RC_STATS
1194 if (svc_ctx.output_rc_stat) {
1195 for (sl = 0; sl < enc_cfg.ss_number_layers; ++sl) {
1196 vpx_video_writer_close(outfile[sl]);
1197 }
1198 }
1199#endif
1200#if CONFIG_INTERNAL_STATS
1201 if (mismatch_seen) {
1202 fprintf(f, "First mismatch occurred in frame %d\n", mismatch_seen);
1203 } else {
1204 fprintf(f, "No mismatch detected in recon buffers\n");
1205 }
1206 fclose(f);
1207#endif
1208 printf("Frame cnt and encoding time/FPS stats for encoding: %d %f %f \n",
1209 frame_cnt, 1000 * (float)cx_time / (double)(frame_cnt * 1000000),
1210 1000000 * (double)frame_cnt / (double)cx_time);
1211 if (app_input.input_ctx.file_type != FILE_TYPE_Y4M) {
1212 vpx_img_free(&raw);
1213 }
1214 // display average size, psnr
1215 vpx_svc_dump_statistics(&svc_ctx);
1216 vpx_svc_release(&svc_ctx);
1217 return EXIT_SUCCESS;
1218}
vpx_codec_err_to_string
const char * vpx_codec_err_to_string(vpx_codec_err_t err)
Convert error number to printable string.
vpx_codec_destroy
vpx_codec_err_t vpx_codec_destroy(vpx_codec_ctx_t *ctx)
Destroy a codec instance.
vpx_codec_iter_t
const void * vpx_codec_iter_t
Iterator.
Definition vpx_codec.h:190
vpx_codec_iface_name
const char * vpx_codec_iface_name(vpx_codec_iface_t *iface)
Return the name for a given interface.
vpx_codec_control
#define vpx_codec_control(ctx, id, data)
vpx_codec_control wrapper macro
Definition vpx_codec.h:408
vpx_codec_err_t
vpx_codec_err_t
Algorithm return codes.
Definition vpx_codec.h:93
VPX_CODEC_CORRUPT_FRAME
@ VPX_CODEC_CORRUPT_FRAME
The coded data for this stream is corrupt or incomplete.
Definition vpx_codec.h:133
VPX_CODEC_OK
@ VPX_CODEC_OK
Operation completed without error.
Definition vpx_codec.h:95
VPX_BITS_8
@ VPX_BITS_8
Definition vpx_codec.h:221
VPX_BITS_12
@ VPX_BITS_12
Definition vpx_codec.h:223
VPX_BITS_10
@ VPX_BITS_10
Definition vpx_codec.h:222
vpx_codec_decode
vpx_codec_err_t vpx_codec_decode(vpx_codec_ctx_t *ctx, const uint8_t *data, unsigned int data_sz, void *user_priv, long deadline)
Decode data.
vpx_codec_dec_init
#define vpx_codec_dec_init(ctx, iface, cfg, flags)
Convenience macro for vpx_codec_dec_init_ver()
Definition vpx_decoder.h:143
VPX_DL_REALTIME
#define VPX_DL_REALTIME
deadline parameter analogous to VPx REALTIME mode.
Definition vpx_encoder.h:1004
VPX_DL_GOOD_QUALITY
#define VPX_DL_GOOD_QUALITY
deadline parameter analogous to VPx GOOD QUALITY mode.
Definition vpx_encoder.h:1006
vpx_codec_get_cx_data
const vpx_codec_cx_pkt_t * vpx_codec_get_cx_data(vpx_codec_ctx_t *ctx, vpx_codec_iter_t *iter)
Encoded data iterator.
VPX_MAX_LAYERS
#define VPX_MAX_LAYERS
Definition vpx_encoder.h:44
VPX_FRAME_IS_KEY
#define VPX_FRAME_IS_KEY
Definition vpx_encoder.h:123
VPX_SS_MAX_LAYERS
#define VPX_SS_MAX_LAYERS
Definition vpx_encoder.h:47
vpx_codec_enc_config_default
vpx_codec_err_t vpx_codec_enc_config_default(vpx_codec_iface_t *iface, vpx_codec_enc_cfg_t *cfg, unsigned int usage)
Get a default configuration.
VPX_CODEC_CX_FRAME_PKT
@ VPX_CODEC_CX_FRAME_PKT
Definition vpx_encoder.h:155
VPX_CODEC_STATS_PKT
@ VPX_CODEC_STATS_PKT
Definition vpx_encoder.h:156
VPX_RC_ONE_PASS
@ VPX_RC_ONE_PASS
Definition vpx_encoder.h:233
VPX_CQ
@ VPX_CQ
Definition vpx_encoder.h:242
vpx_codec_vp9_cx
vpx_codec_iface_t * vpx_codec_vp9_cx(void)
The interface to the VP9 encoder.
FULL_SUPERFRAME_DROP
@ FULL_SUPERFRAME_DROP
Definition vp8cx.h:941
VP9E_SET_SVC_LAYER_ID
@ VP9E_SET_SVC_LAYER_ID
Codec control function to set svc layer for spatial and temporal.
Definition vp8cx.h:471
VP8E_SET_MAX_INTRA_BITRATE_PCT
@ VP8E_SET_MAX_INTRA_BITRATE_PCT
Codec control function to set Max data rate for Intra frames.
Definition vp8cx.h:275
VP9E_SET_SVC_INTER_LAYER_PRED
@ VP9E_SET_SVC_INTER_LAYER_PRED
Codec control function to constrain the inter-layer prediction (prediction of lower spatial resolutio...
Definition vp8cx.h:625
VP9E_SET_AQ_MODE
@ VP9E_SET_AQ_MODE
Codec control function to set adaptive quantization mode.
Definition vp8cx.h:416
VP9E_SET_DISABLE_OVERSHOOT_MAXQ_CBR
@ VP9E_SET_DISABLE_OVERSHOOT_MAXQ_CBR
Codec control function to disable increase Q on overshoot in CBR.
Definition vp8cx.h:708
VP9E_SET_TUNE_CONTENT
@ VP9E_SET_TUNE_CONTENT
Codec control function to set content type.
Definition vp8cx.h:481
VP9E_SET_ROW_MT
@ VP9E_SET_ROW_MT
Codec control function to set row level multi-threading.
Definition vp8cx.h:576
VP8E_SET_CPUUSED
@ VP8E_SET_CPUUSED
Codec control function to set encoder internal speed settings.
Definition vp8cx.h:173
VP9E_SET_TILE_COLUMNS
@ VP9E_SET_TILE_COLUMNS
Codec control function to set number of tile columns.
Definition vp8cx.h:369
VP9E_SET_SVC_FRAME_DROP_LAYER
@ VP9E_SET_SVC_FRAME_DROP_LAYER
Codec control function to set mode and thresholds for frame dropping in SVC. Drop frame thresholds ar...
Definition vp8cx.h:634
VP9E_SET_SVC_REF_FRAME_CONFIG
@ VP9E_SET_SVC_REF_FRAME_CONFIG
Codec control function to set the frame flags and buffer indices for spatial layers....
Definition vp8cx.h:551
VP8E_SET_STATIC_THRESHOLD
@ VP8E_SET_STATIC_THRESHOLD
Codec control function to set the threshold for MBs treated static.
Definition vp8cx.h:206
VP9E_SET_DISABLE_LOOPFILTER
@ VP9E_SET_DISABLE_LOOPFILTER
Codec control function to disable loopfilter.
Definition vp8cx.h:717
VP9E_SET_NOISE_SENSITIVITY
@ VP9E_SET_NOISE_SENSITIVITY
Codec control function to set noise sensitivity.
Definition vp8cx.h:439
VP9E_GET_SVC_LAYER_ID
@ VP9E_GET_SVC_LAYER_ID
Codec control function to get svc layer ID.
Definition vp8cx.h:489
VP9E_TEMPORAL_LAYERING_MODE_BYPASS
@ VP9E_TEMPORAL_LAYERING_MODE_BYPASS
Bypass mode. Used when application needs to control temporal layering. This will only work when the n...
Definition vp8cx.h:808
VP9_GET_REFERENCE
@ VP9_GET_REFERENCE
Definition vp8.h:55
vp9_ref_frame
VP9 specific reference frame data struct.
Definition vp8.h:110
vp9_ref_frame::idx
int idx
Definition vp8.h:111
vpx_codec_ctx
Codec context structure.
Definition vpx_codec.h:200
vpx_codec_ctx::err
vpx_codec_err_t err
Definition vpx_codec.h:203
vpx_codec_cx_pkt
Encoder output packet.
Definition vpx_encoder.h:167
vpx_codec_cx_pkt::flags
vpx_codec_frame_flags_t flags
Definition vpx_encoder.h:177
vpx_codec_cx_pkt::twopass_stats
vpx_fixed_buf_t twopass_stats
Definition vpx_encoder.h:190
vpx_codec_cx_pkt::kind
enum vpx_codec_cx_pkt_kind kind
Definition vpx_encoder.h:168
vpx_codec_cx_pkt::frame
struct vpx_codec_cx_pkt::@1::@2 frame
vpx_codec_cx_pkt::spatial_layer_encoded
uint8_t spatial_layer_encoded[5]
Flag to indicate if spatial layer frame in this packet is encoded or dropped. VP8 will always be set ...
Definition vpx_encoder.h:188
vpx_codec_cx_pkt::sz
size_t sz
Definition vpx_encoder.h:172
vpx_codec_cx_pkt::buf
void * buf
Definition vpx_encoder.h:171
vpx_codec_cx_pkt::pts
vpx_codec_pts_t pts
time stamp to show frame (in timebase units)
Definition vpx_encoder.h:174
vpx_codec_cx_pkt::data
union vpx_codec_cx_pkt::@1 data
vpx_codec_enc_cfg
Encoder configuration structure.
Definition vpx_encoder.h:276
vpx_codec_enc_cfg::temporal_layering_mode
int temporal_layering_mode
Temporal layering mode indicating which temporal layering scheme to use.
Definition vpx_encoder.h:703
vpx_codec_enc_cfg::kf_min_dist
unsigned int kf_min_dist
Keyframe minimum interval.
Definition vpx_encoder.h:615
vpx_codec_enc_cfg::ts_number_layers
unsigned int ts_number_layers
Number of temporal coding layers.
Definition vpx_encoder.h:654
vpx_codec_enc_cfg::ss_number_layers
unsigned int ss_number_layers
Number of spatial coding layers.
Definition vpx_encoder.h:634
vpx_codec_enc_cfg::rc_2pass_vbr_minsection_pct
unsigned int rc_2pass_vbr_minsection_pct
Two-pass mode per-GOP minimum bitrate.
Definition vpx_encoder.h:580
vpx_codec_enc_cfg::g_profile
unsigned int g_profile
Bitstream profile to use.
Definition vpx_encoder.h:303
vpx_codec_enc_cfg::layer_target_bitrate
unsigned int layer_target_bitrate[12]
Target bitrate for each spatial/temporal layer.
Definition vpx_encoder.h:694
vpx_codec_enc_cfg::g_h
unsigned int g_h
Height of the frame.
Definition vpx_encoder.h:321
vpx_codec_enc_cfg::g_error_resilient
vpx_codec_er_flags_t g_error_resilient
Enable error resilient modes.
Definition vpx_encoder.h:359
vpx_codec_enc_cfg::g_w
unsigned int g_w
Width of the frame.
Definition vpx_encoder.h:312
vpx_codec_enc_cfg::rc_dropframe_thresh
unsigned int rc_dropframe_thresh
Temporal resampling configuration, if supported by the codec.
Definition vpx_encoder.h:399
vpx_codec_enc_cfg::g_timebase
struct vpx_rational g_timebase
Stream timebase units.
Definition vpx_encoder.h:351
vpx_codec_enc_cfg::g_pass
enum vpx_enc_pass g_pass
Multi-pass Encoding Mode.
Definition vpx_encoder.h:366
vpx_codec_enc_cfg::g_lag_in_frames
unsigned int g_lag_in_frames
Allow lagged encoding.
Definition vpx_encoder.h:380
vpx_codec_enc_cfg::rc_end_usage
enum vpx_rc_mode rc_end_usage
Rate control algorithm to use.
Definition vpx_encoder.h:448
vpx_codec_enc_cfg::g_bit_depth
vpx_bit_depth_t g_bit_depth
Bit-depth of the codec.
Definition vpx_encoder.h:329
vpx_codec_enc_cfg::rc_2pass_vbr_maxsection_pct
unsigned int rc_2pass_vbr_maxsection_pct
Two-pass mode per-GOP maximum bitrate.
Definition vpx_encoder.h:587
vpx_codec_enc_cfg::rc_target_bitrate
unsigned int rc_target_bitrate
Target data rate.
Definition vpx_encoder.h:470
vpx_codec_enc_cfg::g_input_bit_depth
unsigned int g_input_bit_depth
Bit-depth of the input frames.
Definition vpx_encoder.h:337
vpx_codec_enc_cfg::ts_rate_decimator
unsigned int ts_rate_decimator[5]
Frame rate decimation factor for each temporal layer.
Definition vpx_encoder.h:668
vpx_codec_enc_cfg::kf_max_dist
unsigned int kf_max_dist
Keyframe maximum interval.
Definition vpx_encoder.h:624
vpx_fixed_buf::sz
size_t sz
Definition vpx_encoder.h:105
vpx_fixed_buf::buf
void * buf
Definition vpx_encoder.h:104
vpx_image
Image Descriptor.
Definition vpx_image.h:76
vpx_image::fmt
vpx_img_fmt_t fmt
Definition vpx_image.h:77
vpx_image::d_h
unsigned int d_h
Definition vpx_image.h:88
vpx_image::d_w
unsigned int d_w
Definition vpx_image.h:87
vpx_rational::den
int den
Definition vpx_encoder.h:228
vpx_rational::num
int num
Definition vpx_encoder.h:227
vpx_svc_frame_drop
vp9 svc frame dropping parameters.
Definition vp8cx.h:953
vpx_svc_frame_drop::framedrop_thresh
int framedrop_thresh[5]
Definition vp8cx.h:954
vpx_svc_frame_drop::framedrop_mode
SVC_LAYER_DROP_MODE framedrop_mode
Definition vp8cx.h:956
vpx_svc_frame_drop::max_consec_drop
int max_consec_drop
Definition vp8cx.h:957
vpx_svc_layer_id
vp9 svc layer parameters
Definition vp8cx.h:902
vpx_svc_layer_id::temporal_layer_id
int temporal_layer_id
Definition vp8cx.h:905
vpx_svc_ref_frame_config
vp9 svc frame flag parameters.
Definition vp8cx.h:917
vpx_svc_ref_frame_config::lst_fb_idx
int lst_fb_idx[5]
Definition vp8cx.h:918
vpx_svc_ref_frame_config::update_buffer_slot
int update_buffer_slot[5]
Definition vp8cx.h:921
vpx_svc_ref_frame_config::gld_fb_idx
int gld_fb_idx[5]
Definition vp8cx.h:919
vpx_svc_ref_frame_config::reference_last
int reference_last[5]
Definition vp8cx.h:926
vpx_svc_ref_frame_config::reference_golden
int reference_golden[5]
Definition vp8cx.h:927
vpx_svc_ref_frame_config::reference_alt_ref
int reference_alt_ref[5]
Definition vp8cx.h:928
vpx_svc_ref_frame_config::duration
int64_t duration[5]
Definition vp8cx.h:929
vpx_svc_ref_frame_config::alt_fb_idx
int alt_fb_idx[5]
Definition vp8cx.h:920
vp8cx.h
Provides definitions for using VP8 or VP9 encoder algorithm within the vpx Codec Interface.
vpx_encoder.h
Describes the encoder algorithm interface to applications.
vpx_img_alloc
vpx_image_t * vpx_img_alloc(vpx_image_t *img, vpx_img_fmt_t fmt, unsigned int d_w, unsigned int d_h, unsigned int align)
Open a descriptor, allocating storage for the underlying image.
VPX_IMG_FMT_HIGHBITDEPTH
#define VPX_IMG_FMT_HIGHBITDEPTH
Definition vpx_image.h:35
VPX_IMG_FMT_I42016
@ VPX_IMG_FMT_I42016
Definition vpx_image.h:47
VPX_IMG_FMT_I420
@ VPX_IMG_FMT_I420
Definition vpx_image.h:42
vpx_img_free
void vpx_img_free(vpx_image_t *img)
Close an image descriptor.