2
0

vp9_spatial_svc_encoder.c 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906
  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. * This is an example demonstrating how to implement a multi-layer
  12. * VP9 encoding scheme based on spatial scalability for video applications
  13. * that benefit from a scalable bitstream.
  14. */
  15. #include <math.h>
  16. #include <stdarg.h>
  17. #include <stdlib.h>
  18. #include <string.h>
  19. #include <time.h>
  20. #include "../args.h"
  21. #include "../tools_common.h"
  22. #include "../video_writer.h"
  23. #include "../vpx_ports/vpx_timer.h"
  24. #include "vpx/svc_context.h"
  25. #include "vpx/vp8cx.h"
  26. #include "vpx/vpx_encoder.h"
  27. #include "../vpxstats.h"
  28. #include "vp9/encoder/vp9_encoder.h"
  29. #define OUTPUT_RC_STATS 1
  30. static const arg_def_t skip_frames_arg =
  31. ARG_DEF("s", "skip-frames", 1, "input frames to skip");
  32. static const arg_def_t frames_arg =
  33. ARG_DEF("f", "frames", 1, "number of frames to encode");
  34. static const arg_def_t threads_arg =
  35. ARG_DEF("th", "threads", 1, "number of threads to use");
  36. #if OUTPUT_RC_STATS
  37. static const arg_def_t output_rc_stats_arg =
  38. ARG_DEF("rcstat", "output_rc_stats", 1, "output rc stats");
  39. #endif
  40. static const arg_def_t width_arg = ARG_DEF("w", "width", 1, "source width");
  41. static const arg_def_t height_arg = ARG_DEF("h", "height", 1, "source height");
  42. static const arg_def_t timebase_arg =
  43. ARG_DEF("t", "timebase", 1, "timebase (num/den)");
  44. static const arg_def_t bitrate_arg = ARG_DEF(
  45. "b", "target-bitrate", 1, "encoding bitrate, in kilobits per second");
  46. static const arg_def_t spatial_layers_arg =
  47. ARG_DEF("sl", "spatial-layers", 1, "number of spatial SVC layers");
  48. static const arg_def_t temporal_layers_arg =
  49. ARG_DEF("tl", "temporal-layers", 1, "number of temporal SVC layers");
  50. static const arg_def_t temporal_layering_mode_arg =
  51. ARG_DEF("tlm", "temporal-layering-mode", 1,
  52. "temporal layering scheme."
  53. "VP9E_TEMPORAL_LAYERING_MODE");
  54. static const arg_def_t kf_dist_arg =
  55. ARG_DEF("k", "kf-dist", 1, "number of frames between keyframes");
  56. static const arg_def_t scale_factors_arg =
  57. ARG_DEF("r", "scale-factors", 1, "scale factors (lowest to highest layer)");
  58. static const arg_def_t passes_arg =
  59. ARG_DEF("p", "passes", 1, "Number of passes (1/2)");
  60. static const arg_def_t pass_arg =
  61. ARG_DEF(NULL, "pass", 1, "Pass to execute (1/2)");
  62. static const arg_def_t fpf_name_arg =
  63. ARG_DEF(NULL, "fpf", 1, "First pass statistics file name");
  64. static const arg_def_t min_q_arg =
  65. ARG_DEF(NULL, "min-q", 1, "Minimum quantizer");
  66. static const arg_def_t max_q_arg =
  67. ARG_DEF(NULL, "max-q", 1, "Maximum quantizer");
  68. static const arg_def_t min_bitrate_arg =
  69. ARG_DEF(NULL, "min-bitrate", 1, "Minimum bitrate");
  70. static const arg_def_t max_bitrate_arg =
  71. ARG_DEF(NULL, "max-bitrate", 1, "Maximum bitrate");
  72. static const arg_def_t lag_in_frame_arg =
  73. ARG_DEF(NULL, "lag-in-frames", 1,
  74. "Number of frame to input before "
  75. "generating any outputs");
  76. static const arg_def_t rc_end_usage_arg =
  77. ARG_DEF(NULL, "rc-end-usage", 1, "0 - 3: VBR, CBR, CQ, Q");
  78. static const arg_def_t speed_arg =
  79. ARG_DEF("sp", "speed", 1, "speed configuration");
  80. static const arg_def_t aqmode_arg =
  81. ARG_DEF("aq", "aqmode", 1, "aq-mode off/on");
  82. #if CONFIG_VP9_HIGHBITDEPTH
  83. static const struct arg_enum_list bitdepth_enum[] = {
  84. { "8", VPX_BITS_8 }, { "10", VPX_BITS_10 }, { "12", VPX_BITS_12 }, { NULL, 0 }
  85. };
  86. static const arg_def_t bitdepth_arg = ARG_DEF_ENUM(
  87. "d", "bit-depth", 1, "Bit depth for codec 8, 10 or 12. ", bitdepth_enum);
  88. #endif // CONFIG_VP9_HIGHBITDEPTH
  89. static const arg_def_t *svc_args[] = { &frames_arg,
  90. &width_arg,
  91. &height_arg,
  92. &timebase_arg,
  93. &bitrate_arg,
  94. &skip_frames_arg,
  95. &spatial_layers_arg,
  96. &kf_dist_arg,
  97. &scale_factors_arg,
  98. &passes_arg,
  99. &pass_arg,
  100. &fpf_name_arg,
  101. &min_q_arg,
  102. &max_q_arg,
  103. &min_bitrate_arg,
  104. &max_bitrate_arg,
  105. &temporal_layers_arg,
  106. &temporal_layering_mode_arg,
  107. &lag_in_frame_arg,
  108. &threads_arg,
  109. &aqmode_arg,
  110. #if OUTPUT_RC_STATS
  111. &output_rc_stats_arg,
  112. #endif
  113. #if CONFIG_VP9_HIGHBITDEPTH
  114. &bitdepth_arg,
  115. #endif
  116. &speed_arg,
  117. &rc_end_usage_arg,
  118. NULL };
  119. static const uint32_t default_frames_to_skip = 0;
  120. static const uint32_t default_frames_to_code = 60 * 60;
  121. static const uint32_t default_width = 1920;
  122. static const uint32_t default_height = 1080;
  123. static const uint32_t default_timebase_num = 1;
  124. static const uint32_t default_timebase_den = 60;
  125. static const uint32_t default_bitrate = 1000;
  126. static const uint32_t default_spatial_layers = 5;
  127. static const uint32_t default_temporal_layers = 1;
  128. static const uint32_t default_kf_dist = 100;
  129. static const uint32_t default_temporal_layering_mode = 0;
  130. static const uint32_t default_output_rc_stats = 0;
  131. static const int32_t default_speed = -1; // -1 means use library default.
  132. static const uint32_t default_threads = 0; // zero means use library default.
  133. typedef struct {
  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;
  139. stats_io_t rc_stats;
  140. int passes;
  141. int pass;
  142. } AppInput;
  143. static const char *exec_name;
  144. void usage_exit(void) {
  145. fprintf(stderr, "Usage: %s <options> input_filename output_filename\n",
  146. exec_name);
  147. fprintf(stderr, "Options:\n");
  148. arg_show_usage(stderr, svc_args);
  149. exit(EXIT_FAILURE);
  150. }
  151. static void parse_command_line(int argc, const char **argv_,
  152. AppInput *app_input, SvcContext *svc_ctx,
  153. vpx_codec_enc_cfg_t *enc_cfg) {
  154. struct arg arg = { 0 };
  155. char **argv = NULL;
  156. char **argi = NULL;
  157. char **argj = NULL;
  158. vpx_codec_err_t res;
  159. int passes = 0;
  160. int pass = 0;
  161. const char *fpf_file_name = NULL;
  162. unsigned int min_bitrate = 0;
  163. unsigned int max_bitrate = 0;
  164. char string_options[1024] = { 0 };
  165. // initialize SvcContext with parameters that will be passed to vpx_svc_init
  166. svc_ctx->log_level = SVC_LOG_DEBUG;
  167. svc_ctx->spatial_layers = default_spatial_layers;
  168. svc_ctx->temporal_layers = default_temporal_layers;
  169. svc_ctx->temporal_layering_mode = default_temporal_layering_mode;
  170. #if OUTPUT_RC_STATS
  171. svc_ctx->output_rc_stat = default_output_rc_stats;
  172. #endif
  173. svc_ctx->speed = default_speed;
  174. svc_ctx->threads = default_threads;
  175. // start with default encoder configuration
  176. res = vpx_codec_enc_config_default(vpx_codec_vp9_cx(), enc_cfg, 0);
  177. if (res) {
  178. die("Failed to get config: %s\n", vpx_codec_err_to_string(res));
  179. }
  180. // update enc_cfg with app default values
  181. enc_cfg->g_w = default_width;
  182. enc_cfg->g_h = default_height;
  183. enc_cfg->g_timebase.num = default_timebase_num;
  184. enc_cfg->g_timebase.den = default_timebase_den;
  185. enc_cfg->rc_target_bitrate = default_bitrate;
  186. enc_cfg->kf_min_dist = default_kf_dist;
  187. enc_cfg->kf_max_dist = default_kf_dist;
  188. enc_cfg->rc_end_usage = VPX_CQ;
  189. // initialize AppInput with default values
  190. app_input->frames_to_code = default_frames_to_code;
  191. app_input->frames_to_skip = default_frames_to_skip;
  192. // process command line options
  193. argv = argv_dup(argc - 1, argv_ + 1);
  194. for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step) {
  195. arg.argv_step = 1;
  196. if (arg_match(&arg, &frames_arg, argi)) {
  197. app_input->frames_to_code = arg_parse_uint(&arg);
  198. } else if (arg_match(&arg, &width_arg, argi)) {
  199. enc_cfg->g_w = arg_parse_uint(&arg);
  200. } else if (arg_match(&arg, &height_arg, argi)) {
  201. enc_cfg->g_h = arg_parse_uint(&arg);
  202. } else if (arg_match(&arg, &timebase_arg, argi)) {
  203. enc_cfg->g_timebase = arg_parse_rational(&arg);
  204. } else if (arg_match(&arg, &bitrate_arg, argi)) {
  205. enc_cfg->rc_target_bitrate = arg_parse_uint(&arg);
  206. } else if (arg_match(&arg, &skip_frames_arg, argi)) {
  207. app_input->frames_to_skip = arg_parse_uint(&arg);
  208. } else if (arg_match(&arg, &spatial_layers_arg, argi)) {
  209. svc_ctx->spatial_layers = arg_parse_uint(&arg);
  210. } else if (arg_match(&arg, &temporal_layers_arg, argi)) {
  211. svc_ctx->temporal_layers = arg_parse_uint(&arg);
  212. #if OUTPUT_RC_STATS
  213. } else if (arg_match(&arg, &output_rc_stats_arg, argi)) {
  214. svc_ctx->output_rc_stat = arg_parse_uint(&arg);
  215. #endif
  216. } else if (arg_match(&arg, &speed_arg, argi)) {
  217. svc_ctx->speed = arg_parse_uint(&arg);
  218. } else if (arg_match(&arg, &aqmode_arg, argi)) {
  219. svc_ctx->aqmode = arg_parse_uint(&arg);
  220. } else if (arg_match(&arg, &threads_arg, argi)) {
  221. svc_ctx->threads = arg_parse_uint(&arg);
  222. } else if (arg_match(&arg, &temporal_layering_mode_arg, argi)) {
  223. svc_ctx->temporal_layering_mode = enc_cfg->temporal_layering_mode =
  224. arg_parse_int(&arg);
  225. if (svc_ctx->temporal_layering_mode) {
  226. enc_cfg->g_error_resilient = 1;
  227. }
  228. } else if (arg_match(&arg, &kf_dist_arg, argi)) {
  229. enc_cfg->kf_min_dist = arg_parse_uint(&arg);
  230. enc_cfg->kf_max_dist = enc_cfg->kf_min_dist;
  231. } else if (arg_match(&arg, &scale_factors_arg, argi)) {
  232. snprintf(string_options, sizeof(string_options), "%s scale-factors=%s",
  233. string_options, arg.val);
  234. } else if (arg_match(&arg, &passes_arg, argi)) {
  235. passes = arg_parse_uint(&arg);
  236. if (passes < 1 || passes > 2) {
  237. die("Error: Invalid number of passes (%d)\n", passes);
  238. }
  239. } else if (arg_match(&arg, &pass_arg, argi)) {
  240. pass = arg_parse_uint(&arg);
  241. if (pass < 1 || pass > 2) {
  242. die("Error: Invalid pass selected (%d)\n", pass);
  243. }
  244. } else if (arg_match(&arg, &fpf_name_arg, argi)) {
  245. fpf_file_name = arg.val;
  246. } else if (arg_match(&arg, &min_q_arg, argi)) {
  247. snprintf(string_options, sizeof(string_options), "%s min-quantizers=%s",
  248. string_options, arg.val);
  249. } else if (arg_match(&arg, &max_q_arg, argi)) {
  250. snprintf(string_options, sizeof(string_options), "%s max-quantizers=%s",
  251. string_options, arg.val);
  252. } else if (arg_match(&arg, &min_bitrate_arg, argi)) {
  253. min_bitrate = arg_parse_uint(&arg);
  254. } else if (arg_match(&arg, &max_bitrate_arg, argi)) {
  255. max_bitrate = arg_parse_uint(&arg);
  256. } else if (arg_match(&arg, &lag_in_frame_arg, argi)) {
  257. enc_cfg->g_lag_in_frames = arg_parse_uint(&arg);
  258. } else if (arg_match(&arg, &rc_end_usage_arg, argi)) {
  259. enc_cfg->rc_end_usage = arg_parse_uint(&arg);
  260. #if CONFIG_VP9_HIGHBITDEPTH
  261. } else if (arg_match(&arg, &bitdepth_arg, argi)) {
  262. enc_cfg->g_bit_depth = arg_parse_enum_or_int(&arg);
  263. switch (enc_cfg->g_bit_depth) {
  264. case VPX_BITS_8:
  265. enc_cfg->g_input_bit_depth = 8;
  266. enc_cfg->g_profile = 0;
  267. break;
  268. case VPX_BITS_10:
  269. enc_cfg->g_input_bit_depth = 10;
  270. enc_cfg->g_profile = 2;
  271. break;
  272. case VPX_BITS_12:
  273. enc_cfg->g_input_bit_depth = 12;
  274. enc_cfg->g_profile = 2;
  275. break;
  276. default:
  277. die("Error: Invalid bit depth selected (%d)\n", enc_cfg->g_bit_depth);
  278. break;
  279. }
  280. #endif // CONFIG_VP9_HIGHBITDEPTH
  281. } else {
  282. ++argj;
  283. }
  284. }
  285. // There will be a space in front of the string options
  286. if (strlen(string_options) > 0)
  287. vpx_svc_set_options(svc_ctx, string_options + 1);
  288. if (passes == 0 || passes == 1) {
  289. if (pass) {
  290. fprintf(stderr, "pass is ignored since there's only one pass\n");
  291. }
  292. enc_cfg->g_pass = VPX_RC_ONE_PASS;
  293. } else {
  294. if (pass == 0) {
  295. die("pass must be specified when passes is 2\n");
  296. }
  297. if (fpf_file_name == NULL) {
  298. die("fpf must be specified when passes is 2\n");
  299. }
  300. if (pass == 1) {
  301. enc_cfg->g_pass = VPX_RC_FIRST_PASS;
  302. if (!stats_open_file(&app_input->rc_stats, fpf_file_name, 0)) {
  303. fatal("Failed to open statistics store");
  304. }
  305. } else {
  306. enc_cfg->g_pass = VPX_RC_LAST_PASS;
  307. if (!stats_open_file(&app_input->rc_stats, fpf_file_name, 1)) {
  308. fatal("Failed to open statistics store");
  309. }
  310. enc_cfg->rc_twopass_stats_in = stats_get(&app_input->rc_stats);
  311. }
  312. app_input->passes = passes;
  313. app_input->pass = pass;
  314. }
  315. if (enc_cfg->rc_target_bitrate > 0) {
  316. if (min_bitrate > 0) {
  317. enc_cfg->rc_2pass_vbr_minsection_pct =
  318. min_bitrate * 100 / enc_cfg->rc_target_bitrate;
  319. }
  320. if (max_bitrate > 0) {
  321. enc_cfg->rc_2pass_vbr_maxsection_pct =
  322. max_bitrate * 100 / enc_cfg->rc_target_bitrate;
  323. }
  324. }
  325. // Check for unrecognized options
  326. for (argi = argv; *argi; ++argi)
  327. if (argi[0][0] == '-' && strlen(argi[0]) > 1)
  328. die("Error: Unrecognized option %s\n", *argi);
  329. if (argv[0] == NULL || argv[1] == 0) {
  330. usage_exit();
  331. }
  332. app_input->input_filename = argv[0];
  333. app_input->output_filename = argv[1];
  334. free(argv);
  335. if (enc_cfg->g_w < 16 || enc_cfg->g_w % 2 || enc_cfg->g_h < 16 ||
  336. enc_cfg->g_h % 2)
  337. die("Invalid resolution: %d x %d\n", enc_cfg->g_w, enc_cfg->g_h);
  338. printf(
  339. "Codec %s\nframes: %d, skip: %d\n"
  340. "layers: %d\n"
  341. "width %d, height: %d,\n"
  342. "num: %d, den: %d, bitrate: %d,\n"
  343. "gop size: %d\n",
  344. vpx_codec_iface_name(vpx_codec_vp9_cx()), app_input->frames_to_code,
  345. app_input->frames_to_skip, svc_ctx->spatial_layers, enc_cfg->g_w,
  346. enc_cfg->g_h, enc_cfg->g_timebase.num, enc_cfg->g_timebase.den,
  347. enc_cfg->rc_target_bitrate, enc_cfg->kf_max_dist);
  348. }
  349. #if OUTPUT_RC_STATS
  350. // For rate control encoding stats.
  351. struct RateControlStats {
  352. // Number of input frames per layer.
  353. int layer_input_frames[VPX_MAX_LAYERS];
  354. // Total (cumulative) number of encoded frames per layer.
  355. int layer_tot_enc_frames[VPX_MAX_LAYERS];
  356. // Number of encoded non-key frames per layer.
  357. int layer_enc_frames[VPX_MAX_LAYERS];
  358. // Framerate per layer (cumulative).
  359. double layer_framerate[VPX_MAX_LAYERS];
  360. // Target average frame size per layer (per-frame-bandwidth per layer).
  361. double layer_pfb[VPX_MAX_LAYERS];
  362. // Actual average frame size per layer.
  363. double layer_avg_frame_size[VPX_MAX_LAYERS];
  364. // Average rate mismatch per layer (|target - actual| / target).
  365. double layer_avg_rate_mismatch[VPX_MAX_LAYERS];
  366. // Actual encoding bitrate per layer (cumulative).
  367. double layer_encoding_bitrate[VPX_MAX_LAYERS];
  368. // Average of the short-time encoder actual bitrate.
  369. // TODO(marpan): Should we add these short-time stats for each layer?
  370. double avg_st_encoding_bitrate;
  371. // Variance of the short-time encoder actual bitrate.
  372. double variance_st_encoding_bitrate;
  373. // Window (number of frames) for computing short-time encoding bitrate.
  374. int window_size;
  375. // Number of window measurements.
  376. int window_count;
  377. };
  378. // Note: these rate control stats assume only 1 key frame in the
  379. // sequence (i.e., first frame only).
  380. static void set_rate_control_stats(struct RateControlStats *rc,
  381. vpx_codec_enc_cfg_t *cfg) {
  382. unsigned int sl, tl;
  383. // Set the layer (cumulative) framerate and the target layer (non-cumulative)
  384. // per-frame-bandwidth, for the rate control encoding stats below.
  385. const double framerate = cfg->g_timebase.den / cfg->g_timebase.num;
  386. for (sl = 0; sl < cfg->ss_number_layers; ++sl) {
  387. for (tl = 0; tl < cfg->ts_number_layers; ++tl) {
  388. const int layer = sl * cfg->ts_number_layers + tl;
  389. const int tlayer0 = sl * cfg->ts_number_layers;
  390. if (cfg->ts_number_layers == 1)
  391. rc->layer_framerate[layer] = framerate;
  392. else
  393. rc->layer_framerate[layer] = framerate / cfg->ts_rate_decimator[tl];
  394. if (tl > 0) {
  395. rc->layer_pfb[layer] =
  396. 1000.0 * (cfg->layer_target_bitrate[layer] -
  397. cfg->layer_target_bitrate[layer - 1]) /
  398. (rc->layer_framerate[layer] - rc->layer_framerate[layer - 1]);
  399. } else {
  400. rc->layer_pfb[tlayer0] = 1000.0 * cfg->layer_target_bitrate[tlayer0] /
  401. rc->layer_framerate[tlayer0];
  402. }
  403. rc->layer_input_frames[layer] = 0;
  404. rc->layer_enc_frames[layer] = 0;
  405. rc->layer_tot_enc_frames[layer] = 0;
  406. rc->layer_encoding_bitrate[layer] = 0.0;
  407. rc->layer_avg_frame_size[layer] = 0.0;
  408. rc->layer_avg_rate_mismatch[layer] = 0.0;
  409. }
  410. }
  411. rc->window_count = 0;
  412. rc->window_size = 15;
  413. rc->avg_st_encoding_bitrate = 0.0;
  414. rc->variance_st_encoding_bitrate = 0.0;
  415. }
  416. static void printout_rate_control_summary(struct RateControlStats *rc,
  417. vpx_codec_enc_cfg_t *cfg,
  418. int frame_cnt) {
  419. unsigned int sl, tl;
  420. int tot_num_frames = 0;
  421. double perc_fluctuation = 0.0;
  422. printf("Total number of processed frames: %d\n\n", frame_cnt - 1);
  423. printf("Rate control layer stats for sl%d tl%d layer(s):\n\n",
  424. cfg->ss_number_layers, cfg->ts_number_layers);
  425. for (sl = 0; sl < cfg->ss_number_layers; ++sl) {
  426. for (tl = 0; tl < cfg->ts_number_layers; ++tl) {
  427. const int layer = sl * cfg->ts_number_layers + tl;
  428. const int num_dropped =
  429. (tl > 0)
  430. ? (rc->layer_input_frames[layer] - rc->layer_enc_frames[layer])
  431. : (rc->layer_input_frames[layer] - rc->layer_enc_frames[layer] -
  432. 1);
  433. if (!sl) tot_num_frames += rc->layer_input_frames[layer];
  434. rc->layer_encoding_bitrate[layer] = 0.001 * rc->layer_framerate[layer] *
  435. rc->layer_encoding_bitrate[layer] /
  436. tot_num_frames;
  437. rc->layer_avg_frame_size[layer] =
  438. rc->layer_avg_frame_size[layer] / rc->layer_enc_frames[layer];
  439. rc->layer_avg_rate_mismatch[layer] = 100.0 *
  440. rc->layer_avg_rate_mismatch[layer] /
  441. rc->layer_enc_frames[layer];
  442. printf("For layer#: sl%d tl%d \n", sl, tl);
  443. printf("Bitrate (target vs actual): %d %f.0 kbps\n",
  444. cfg->layer_target_bitrate[layer],
  445. rc->layer_encoding_bitrate[layer]);
  446. printf("Average frame size (target vs actual): %f %f bits\n",
  447. rc->layer_pfb[layer], rc->layer_avg_frame_size[layer]);
  448. printf("Average rate_mismatch: %f\n", rc->layer_avg_rate_mismatch[layer]);
  449. printf(
  450. "Number of input frames, encoded (non-key) frames, "
  451. "and percent dropped frames: %d %d %f.0 \n",
  452. rc->layer_input_frames[layer], rc->layer_enc_frames[layer],
  453. 100.0 * num_dropped / rc->layer_input_frames[layer]);
  454. printf("\n");
  455. }
  456. }
  457. rc->avg_st_encoding_bitrate = rc->avg_st_encoding_bitrate / rc->window_count;
  458. rc->variance_st_encoding_bitrate =
  459. rc->variance_st_encoding_bitrate / rc->window_count -
  460. (rc->avg_st_encoding_bitrate * rc->avg_st_encoding_bitrate);
  461. perc_fluctuation = 100.0 * sqrt(rc->variance_st_encoding_bitrate) /
  462. rc->avg_st_encoding_bitrate;
  463. printf("Short-time stats, for window of %d frames: \n", rc->window_size);
  464. printf("Average, rms-variance, and percent-fluct: %f %f %f \n",
  465. rc->avg_st_encoding_bitrate, sqrt(rc->variance_st_encoding_bitrate),
  466. perc_fluctuation);
  467. if (frame_cnt != tot_num_frames)
  468. die("Error: Number of input frames not equal to output encoded frames != "
  469. "%d tot_num_frames = %d\n",
  470. frame_cnt, tot_num_frames);
  471. }
  472. vpx_codec_err_t parse_superframe_index(const uint8_t *data, size_t data_sz,
  473. uint32_t sizes[8], int *count) {
  474. // A chunk ending with a byte matching 0xc0 is an invalid chunk unless
  475. // it is a super frame index. If the last byte of real video compression
  476. // data is 0xc0 the encoder must add a 0 byte. If we have the marker but
  477. // not the associated matching marker byte at the front of the index we have
  478. // an invalid bitstream and need to return an error.
  479. uint8_t marker;
  480. marker = *(data + data_sz - 1);
  481. *count = 0;
  482. if ((marker & 0xe0) == 0xc0) {
  483. const uint32_t frames = (marker & 0x7) + 1;
  484. const uint32_t mag = ((marker >> 3) & 0x3) + 1;
  485. const size_t index_sz = 2 + mag * frames;
  486. // This chunk is marked as having a superframe index but doesn't have
  487. // enough data for it, thus it's an invalid superframe index.
  488. if (data_sz < index_sz) return VPX_CODEC_CORRUPT_FRAME;
  489. {
  490. const uint8_t marker2 = *(data + data_sz - index_sz);
  491. // This chunk is marked as having a superframe index but doesn't have
  492. // the matching marker byte at the front of the index therefore it's an
  493. // invalid chunk.
  494. if (marker != marker2) return VPX_CODEC_CORRUPT_FRAME;
  495. }
  496. {
  497. // Found a valid superframe index.
  498. uint32_t i, j;
  499. const uint8_t *x = &data[data_sz - index_sz + 1];
  500. for (i = 0; i < frames; ++i) {
  501. uint32_t this_sz = 0;
  502. for (j = 0; j < mag; ++j) this_sz |= (*x++) << (j * 8);
  503. sizes[i] = this_sz;
  504. }
  505. *count = frames;
  506. }
  507. }
  508. return VPX_CODEC_OK;
  509. }
  510. #endif
  511. // Example pattern for spatial layers and 2 temporal layers used in the
  512. // bypass/flexible mode. The pattern corresponds to the pattern
  513. // VP9E_TEMPORAL_LAYERING_MODE_0101 (temporal_layering_mode == 2) used in
  514. // non-flexible mode.
  515. void set_frame_flags_bypass_mode(int sl, int tl, int num_spatial_layers,
  516. int is_key_frame,
  517. vpx_svc_ref_frame_config_t *ref_frame_config) {
  518. for (sl = 0; sl < num_spatial_layers; ++sl) {
  519. if (!tl) {
  520. if (!sl) {
  521. ref_frame_config->frame_flags[sl] =
  522. VP8_EFLAG_NO_REF_GF | VP8_EFLAG_NO_REF_ARF | VP8_EFLAG_NO_UPD_GF |
  523. VP8_EFLAG_NO_UPD_ARF;
  524. } else {
  525. if (is_key_frame) {
  526. ref_frame_config->frame_flags[sl] =
  527. VP8_EFLAG_NO_REF_LAST | VP8_EFLAG_NO_REF_ARF |
  528. VP8_EFLAG_NO_UPD_GF | VP8_EFLAG_NO_UPD_ARF;
  529. } else {
  530. ref_frame_config->frame_flags[sl] =
  531. VP8_EFLAG_NO_REF_ARF | VP8_EFLAG_NO_UPD_GF | VP8_EFLAG_NO_UPD_ARF;
  532. }
  533. }
  534. } else if (tl == 1) {
  535. if (!sl) {
  536. ref_frame_config->frame_flags[sl] =
  537. VP8_EFLAG_NO_REF_GF | VP8_EFLAG_NO_REF_ARF | VP8_EFLAG_NO_UPD_LAST |
  538. VP8_EFLAG_NO_UPD_GF;
  539. } else {
  540. ref_frame_config->frame_flags[sl] =
  541. VP8_EFLAG_NO_REF_ARF | VP8_EFLAG_NO_UPD_LAST | VP8_EFLAG_NO_UPD_GF;
  542. }
  543. }
  544. if (tl == 0) {
  545. ref_frame_config->lst_fb_idx[sl] = sl;
  546. if (sl)
  547. ref_frame_config->gld_fb_idx[sl] = sl - 1;
  548. else
  549. ref_frame_config->gld_fb_idx[sl] = 0;
  550. ref_frame_config->alt_fb_idx[sl] = 0;
  551. } else if (tl == 1) {
  552. ref_frame_config->lst_fb_idx[sl] = sl;
  553. ref_frame_config->gld_fb_idx[sl] = num_spatial_layers + sl - 1;
  554. ref_frame_config->alt_fb_idx[sl] = num_spatial_layers + sl;
  555. }
  556. }
  557. }
  558. int main(int argc, const char **argv) {
  559. AppInput app_input = { 0 };
  560. VpxVideoWriter *writer = NULL;
  561. VpxVideoInfo info = { 0 };
  562. vpx_codec_ctx_t codec;
  563. vpx_codec_enc_cfg_t enc_cfg;
  564. SvcContext svc_ctx;
  565. uint32_t i;
  566. uint32_t frame_cnt = 0;
  567. vpx_image_t raw;
  568. vpx_codec_err_t res;
  569. int pts = 0; /* PTS starts at 0 */
  570. int frame_duration = 1; /* 1 timebase tick per frame */
  571. FILE *infile = NULL;
  572. int end_of_stream = 0;
  573. int frames_received = 0;
  574. #if OUTPUT_RC_STATS
  575. VpxVideoWriter *outfile[VPX_TS_MAX_LAYERS] = { NULL };
  576. struct RateControlStats rc;
  577. vpx_svc_layer_id_t layer_id;
  578. vpx_svc_ref_frame_config_t ref_frame_config;
  579. int sl, tl;
  580. double sum_bitrate = 0.0;
  581. double sum_bitrate2 = 0.0;
  582. double framerate = 30.0;
  583. #endif
  584. struct vpx_usec_timer timer;
  585. int64_t cx_time = 0;
  586. memset(&svc_ctx, 0, sizeof(svc_ctx));
  587. svc_ctx.log_print = 1;
  588. exec_name = argv[0];
  589. parse_command_line(argc, argv, &app_input, &svc_ctx, &enc_cfg);
  590. // Allocate image buffer
  591. #if CONFIG_VP9_HIGHBITDEPTH
  592. if (!vpx_img_alloc(&raw, enc_cfg.g_input_bit_depth == 8 ? VPX_IMG_FMT_I420
  593. : VPX_IMG_FMT_I42016,
  594. enc_cfg.g_w, enc_cfg.g_h, 32)) {
  595. die("Failed to allocate image %dx%d\n", enc_cfg.g_w, enc_cfg.g_h);
  596. }
  597. #else
  598. if (!vpx_img_alloc(&raw, VPX_IMG_FMT_I420, enc_cfg.g_w, enc_cfg.g_h, 32)) {
  599. die("Failed to allocate image %dx%d\n", enc_cfg.g_w, enc_cfg.g_h);
  600. }
  601. #endif // CONFIG_VP9_HIGHBITDEPTH
  602. if (!(infile = fopen(app_input.input_filename, "rb")))
  603. die("Failed to open %s for reading\n", app_input.input_filename);
  604. // Initialize codec
  605. if (vpx_svc_init(&svc_ctx, &codec, vpx_codec_vp9_cx(), &enc_cfg) !=
  606. VPX_CODEC_OK)
  607. die("Failed to initialize encoder\n");
  608. #if OUTPUT_RC_STATS
  609. if (svc_ctx.output_rc_stat) {
  610. set_rate_control_stats(&rc, &enc_cfg);
  611. framerate = enc_cfg.g_timebase.den / enc_cfg.g_timebase.num;
  612. }
  613. #endif
  614. info.codec_fourcc = VP9_FOURCC;
  615. info.time_base.numerator = enc_cfg.g_timebase.num;
  616. info.time_base.denominator = enc_cfg.g_timebase.den;
  617. if (!(app_input.passes == 2 && app_input.pass == 1)) {
  618. // We don't save the bitstream for the 1st pass on two pass rate control
  619. writer =
  620. vpx_video_writer_open(app_input.output_filename, kContainerIVF, &info);
  621. if (!writer)
  622. die("Failed to open %s for writing\n", app_input.output_filename);
  623. }
  624. #if OUTPUT_RC_STATS
  625. // For now, just write temporal layer streams.
  626. // TODO(wonkap): do spatial by re-writing superframe.
  627. if (svc_ctx.output_rc_stat) {
  628. for (tl = 0; tl < enc_cfg.ts_number_layers; ++tl) {
  629. char file_name[PATH_MAX];
  630. snprintf(file_name, sizeof(file_name), "%s_t%d.ivf",
  631. app_input.output_filename, tl);
  632. outfile[tl] = vpx_video_writer_open(file_name, kContainerIVF, &info);
  633. if (!outfile[tl]) die("Failed to open %s for writing", file_name);
  634. }
  635. }
  636. #endif
  637. // skip initial frames
  638. for (i = 0; i < app_input.frames_to_skip; ++i) vpx_img_read(&raw, infile);
  639. if (svc_ctx.speed != -1)
  640. vpx_codec_control(&codec, VP8E_SET_CPUUSED, svc_ctx.speed);
  641. if (svc_ctx.threads)
  642. vpx_codec_control(&codec, VP9E_SET_TILE_COLUMNS, (svc_ctx.threads >> 1));
  643. if (svc_ctx.speed >= 5 && svc_ctx.aqmode == 1)
  644. vpx_codec_control(&codec, VP9E_SET_AQ_MODE, 3);
  645. // Encode frames
  646. while (!end_of_stream) {
  647. vpx_codec_iter_t iter = NULL;
  648. const vpx_codec_cx_pkt_t *cx_pkt;
  649. if (frame_cnt >= app_input.frames_to_code || !vpx_img_read(&raw, infile)) {
  650. // We need one extra vpx_svc_encode call at end of stream to flush
  651. // encoder and get remaining data
  652. end_of_stream = 1;
  653. }
  654. // For BYPASS/FLEXIBLE mode, set the frame flags (reference and updates)
  655. // and the buffer indices for each spatial layer of the current
  656. // (super)frame to be encoded. The temporal layer_id for the current frame
  657. // also needs to be set.
  658. // TODO(marpan): Should rename the "VP9E_TEMPORAL_LAYERING_MODE_BYPASS"
  659. // mode to "VP9E_LAYERING_MODE_BYPASS".
  660. if (svc_ctx.temporal_layering_mode == VP9E_TEMPORAL_LAYERING_MODE_BYPASS) {
  661. layer_id.spatial_layer_id = 0;
  662. // Example for 2 temporal layers.
  663. if (frame_cnt % 2 == 0)
  664. layer_id.temporal_layer_id = 0;
  665. else
  666. layer_id.temporal_layer_id = 1;
  667. // Note that we only set the temporal layer_id, since we are calling
  668. // the encode for the whole superframe. The encoder will internally loop
  669. // over all the spatial layers for the current superframe.
  670. vpx_codec_control(&codec, VP9E_SET_SVC_LAYER_ID, &layer_id);
  671. set_frame_flags_bypass_mode(sl, layer_id.temporal_layer_id,
  672. svc_ctx.spatial_layers, frame_cnt == 0,
  673. &ref_frame_config);
  674. vpx_codec_control(&codec, VP9E_SET_SVC_REF_FRAME_CONFIG,
  675. &ref_frame_config);
  676. // Keep track of input frames, to account for frame drops in rate control
  677. // stats/metrics.
  678. for (sl = 0; sl < enc_cfg.ss_number_layers; ++sl) {
  679. ++rc.layer_input_frames[sl * enc_cfg.ts_number_layers +
  680. layer_id.temporal_layer_id];
  681. }
  682. }
  683. vpx_usec_timer_start(&timer);
  684. res = vpx_svc_encode(
  685. &svc_ctx, &codec, (end_of_stream ? NULL : &raw), pts, frame_duration,
  686. svc_ctx.speed >= 5 ? VPX_DL_REALTIME : VPX_DL_GOOD_QUALITY);
  687. vpx_usec_timer_mark(&timer);
  688. cx_time += vpx_usec_timer_elapsed(&timer);
  689. printf("%s", vpx_svc_get_message(&svc_ctx));
  690. fflush(stdout);
  691. if (res != VPX_CODEC_OK) {
  692. die_codec(&codec, "Failed to encode frame");
  693. }
  694. while ((cx_pkt = vpx_codec_get_cx_data(&codec, &iter)) != NULL) {
  695. switch (cx_pkt->kind) {
  696. case VPX_CODEC_CX_FRAME_PKT: {
  697. SvcInternal_t *const si = (SvcInternal_t *)svc_ctx.internal;
  698. if (cx_pkt->data.frame.sz > 0) {
  699. #if OUTPUT_RC_STATS
  700. uint32_t sizes[8];
  701. int count = 0;
  702. #endif
  703. vpx_video_writer_write_frame(writer, cx_pkt->data.frame.buf,
  704. cx_pkt->data.frame.sz,
  705. cx_pkt->data.frame.pts);
  706. #if OUTPUT_RC_STATS
  707. // TODO(marpan/wonkap): Put this (to line728) in separate function.
  708. if (svc_ctx.output_rc_stat) {
  709. vpx_codec_control(&codec, VP9E_GET_SVC_LAYER_ID, &layer_id);
  710. parse_superframe_index(cx_pkt->data.frame.buf,
  711. cx_pkt->data.frame.sz, sizes, &count);
  712. // Note computing input_layer_frames here won't account for frame
  713. // drops in rate control stats.
  714. // TODO(marpan): Fix this for non-bypass mode so we can get stats
  715. // for dropped frames.
  716. if (svc_ctx.temporal_layering_mode !=
  717. VP9E_TEMPORAL_LAYERING_MODE_BYPASS) {
  718. for (sl = 0; sl < enc_cfg.ss_number_layers; ++sl) {
  719. ++rc.layer_input_frames[sl * enc_cfg.ts_number_layers +
  720. layer_id.temporal_layer_id];
  721. }
  722. }
  723. for (tl = layer_id.temporal_layer_id;
  724. tl < enc_cfg.ts_number_layers; ++tl) {
  725. vpx_video_writer_write_frame(
  726. outfile[tl], cx_pkt->data.frame.buf, cx_pkt->data.frame.sz,
  727. cx_pkt->data.frame.pts);
  728. }
  729. for (sl = 0; sl < enc_cfg.ss_number_layers; ++sl) {
  730. for (tl = layer_id.temporal_layer_id;
  731. tl < enc_cfg.ts_number_layers; ++tl) {
  732. const int layer = sl * enc_cfg.ts_number_layers + tl;
  733. ++rc.layer_tot_enc_frames[layer];
  734. rc.layer_encoding_bitrate[layer] += 8.0 * sizes[sl];
  735. // Keep count of rate control stats per layer, for non-key
  736. // frames.
  737. if (tl == layer_id.temporal_layer_id &&
  738. !(cx_pkt->data.frame.flags & VPX_FRAME_IS_KEY)) {
  739. rc.layer_avg_frame_size[layer] += 8.0 * sizes[sl];
  740. rc.layer_avg_rate_mismatch[layer] +=
  741. fabs(8.0 * sizes[sl] - rc.layer_pfb[layer]) /
  742. rc.layer_pfb[layer];
  743. ++rc.layer_enc_frames[layer];
  744. }
  745. }
  746. }
  747. // Update for short-time encoding bitrate states, for moving
  748. // window of size rc->window, shifted by rc->window / 2.
  749. // Ignore first window segment, due to key frame.
  750. if (frame_cnt > rc.window_size) {
  751. tl = layer_id.temporal_layer_id;
  752. for (sl = 0; sl < enc_cfg.ss_number_layers; ++sl) {
  753. sum_bitrate += 0.001 * 8.0 * sizes[sl] * framerate;
  754. }
  755. if (frame_cnt % rc.window_size == 0) {
  756. rc.window_count += 1;
  757. rc.avg_st_encoding_bitrate += sum_bitrate / rc.window_size;
  758. rc.variance_st_encoding_bitrate +=
  759. (sum_bitrate / rc.window_size) *
  760. (sum_bitrate / rc.window_size);
  761. sum_bitrate = 0.0;
  762. }
  763. }
  764. // Second shifted window.
  765. if (frame_cnt > rc.window_size + rc.window_size / 2) {
  766. tl = layer_id.temporal_layer_id;
  767. for (sl = 0; sl < enc_cfg.ss_number_layers; ++sl) {
  768. sum_bitrate2 += 0.001 * 8.0 * sizes[sl] * framerate;
  769. }
  770. if (frame_cnt > 2 * rc.window_size &&
  771. frame_cnt % rc.window_size == 0) {
  772. rc.window_count += 1;
  773. rc.avg_st_encoding_bitrate += sum_bitrate2 / rc.window_size;
  774. rc.variance_st_encoding_bitrate +=
  775. (sum_bitrate2 / rc.window_size) *
  776. (sum_bitrate2 / rc.window_size);
  777. sum_bitrate2 = 0.0;
  778. }
  779. }
  780. }
  781. #endif
  782. }
  783. printf("SVC frame: %d, kf: %d, size: %d, pts: %d\n", frames_received,
  784. !!(cx_pkt->data.frame.flags & VPX_FRAME_IS_KEY),
  785. (int)cx_pkt->data.frame.sz, (int)cx_pkt->data.frame.pts);
  786. if (enc_cfg.ss_number_layers == 1 && enc_cfg.ts_number_layers == 1)
  787. si->bytes_sum[0] += (int)cx_pkt->data.frame.sz;
  788. ++frames_received;
  789. break;
  790. }
  791. case VPX_CODEC_STATS_PKT: {
  792. stats_write(&app_input.rc_stats, cx_pkt->data.twopass_stats.buf,
  793. cx_pkt->data.twopass_stats.sz);
  794. break;
  795. }
  796. default: { break; }
  797. }
  798. }
  799. if (!end_of_stream) {
  800. ++frame_cnt;
  801. pts += frame_duration;
  802. }
  803. }
  804. // Compensate for the extra frame count for the bypass mode.
  805. if (svc_ctx.temporal_layering_mode == VP9E_TEMPORAL_LAYERING_MODE_BYPASS) {
  806. for (sl = 0; sl < enc_cfg.ss_number_layers; ++sl) {
  807. const int layer =
  808. sl * enc_cfg.ts_number_layers + layer_id.temporal_layer_id;
  809. --rc.layer_input_frames[layer];
  810. }
  811. }
  812. printf("Processed %d frames\n", frame_cnt);
  813. fclose(infile);
  814. #if OUTPUT_RC_STATS
  815. if (svc_ctx.output_rc_stat) {
  816. printout_rate_control_summary(&rc, &enc_cfg, frame_cnt);
  817. printf("\n");
  818. }
  819. #endif
  820. if (vpx_codec_destroy(&codec)) die_codec(&codec, "Failed to destroy codec");
  821. if (app_input.passes == 2) stats_close(&app_input.rc_stats, 1);
  822. if (writer) {
  823. vpx_video_writer_close(writer);
  824. }
  825. #if OUTPUT_RC_STATS
  826. if (svc_ctx.output_rc_stat) {
  827. for (tl = 0; tl < enc_cfg.ts_number_layers; ++tl) {
  828. vpx_video_writer_close(outfile[tl]);
  829. }
  830. }
  831. #endif
  832. printf("Frame cnt and encoding time/FPS stats for encoding: %d %f %f \n",
  833. frame_cnt, 1000 * (float)cx_time / (double)(frame_cnt * 1000000),
  834. 1000000 * (double)frame_cnt / (double)cx_time);
  835. vpx_img_free(&raw);
  836. // display average size, psnr
  837. printf("%s", vpx_svc_dump_statistics(&svc_ctx));
  838. vpx_svc_release(&svc_ctx);
  839. return EXIT_SUCCESS;
  840. }