vp9_spatial_svc_encoder.c 36 KB

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