2
0

vp9_spatial_svc_encoder.c 48 KB

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