vpxenc.c 73 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999
  1. /*
  2. * Copyright (c) 2010 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. #include "./vpxenc.h"
  11. #include "./vpx_config.h"
  12. #include <assert.h>
  13. #include <limits.h>
  14. #include <math.h>
  15. #include <stdarg.h>
  16. #include <stdio.h>
  17. #include <stdlib.h>
  18. #include <string.h>
  19. #if CONFIG_LIBYUV
  20. #include "third_party/libyuv/include/libyuv/scale.h"
  21. #endif
  22. #include "vpx/vpx_encoder.h"
  23. #if CONFIG_DECODERS
  24. #include "vpx/vpx_decoder.h"
  25. #endif
  26. #include "./args.h"
  27. #include "./ivfenc.h"
  28. #include "./tools_common.h"
  29. #if CONFIG_VP8_ENCODER || CONFIG_VP9_ENCODER
  30. #include "vpx/vp8cx.h"
  31. #endif
  32. #if CONFIG_VP8_DECODER || CONFIG_VP9_DECODER
  33. #include "vpx/vp8dx.h"
  34. #endif
  35. #include "vpx/vpx_integer.h"
  36. #include "vpx_ports/mem_ops.h"
  37. #include "vpx_ports/vpx_timer.h"
  38. #include "./rate_hist.h"
  39. #include "./vpxstats.h"
  40. #include "./warnings.h"
  41. #if CONFIG_WEBM_IO
  42. #include "./webmenc.h"
  43. #endif
  44. #include "./y4minput.h"
  45. static size_t wrap_fwrite(const void *ptr, size_t size, size_t nmemb,
  46. FILE *stream) {
  47. return fwrite(ptr, size, nmemb, stream);
  48. }
  49. #define fwrite wrap_fwrite
  50. static const char *exec_name;
  51. static void warn_or_exit_on_errorv(vpx_codec_ctx_t *ctx, int fatal,
  52. const char *s, va_list ap) {
  53. if (ctx->err) {
  54. const char *detail = vpx_codec_error_detail(ctx);
  55. vfprintf(stderr, s, ap);
  56. fprintf(stderr, ": %s\n", vpx_codec_error(ctx));
  57. if (detail) fprintf(stderr, " %s\n", detail);
  58. if (fatal) exit(EXIT_FAILURE);
  59. }
  60. }
  61. static void ctx_exit_on_error(vpx_codec_ctx_t *ctx, const char *s, ...) {
  62. va_list ap;
  63. va_start(ap, s);
  64. warn_or_exit_on_errorv(ctx, 1, s, ap);
  65. va_end(ap);
  66. }
  67. static void warn_or_exit_on_error(vpx_codec_ctx_t *ctx, int fatal,
  68. const char *s, ...) {
  69. va_list ap;
  70. va_start(ap, s);
  71. warn_or_exit_on_errorv(ctx, fatal, s, ap);
  72. va_end(ap);
  73. }
  74. static const arg_def_t help =
  75. ARG_DEF(NULL, "help", 0, "Show usage options and exit");
  76. static const arg_def_t debugmode =
  77. ARG_DEF("D", "debug", 0, "Debug mode (makes output deterministic)");
  78. static const arg_def_t outputfile =
  79. ARG_DEF("o", "output", 1, "Output filename");
  80. static const arg_def_t use_yv12 =
  81. ARG_DEF(NULL, "yv12", 0, "Input file is YV12 ");
  82. static const arg_def_t use_i420 =
  83. ARG_DEF(NULL, "i420", 0, "Input file is I420 (default)");
  84. static const arg_def_t use_i422 =
  85. ARG_DEF(NULL, "i422", 0, "Input file is I422");
  86. static const arg_def_t use_i444 =
  87. ARG_DEF(NULL, "i444", 0, "Input file is I444");
  88. static const arg_def_t use_i440 =
  89. ARG_DEF(NULL, "i440", 0, "Input file is I440");
  90. static const arg_def_t codecarg = ARG_DEF(NULL, "codec", 1, "Codec to use");
  91. static const arg_def_t passes =
  92. ARG_DEF("p", "passes", 1, "Number of passes (1/2)");
  93. static const arg_def_t pass_arg =
  94. ARG_DEF(NULL, "pass", 1, "Pass to execute (1/2)");
  95. static const arg_def_t fpf_name =
  96. ARG_DEF(NULL, "fpf", 1, "First pass statistics file name");
  97. #if CONFIG_FP_MB_STATS
  98. static const arg_def_t fpmbf_name =
  99. ARG_DEF(NULL, "fpmbf", 1, "First pass block statistics file name");
  100. #endif
  101. static const arg_def_t limit =
  102. ARG_DEF(NULL, "limit", 1, "Stop encoding after n input frames");
  103. static const arg_def_t skip =
  104. ARG_DEF(NULL, "skip", 1, "Skip the first n input frames");
  105. static const arg_def_t deadline =
  106. ARG_DEF("d", "deadline", 1, "Deadline per frame (usec)");
  107. static const arg_def_t best_dl =
  108. ARG_DEF(NULL, "best", 0, "Use Best Quality Deadline");
  109. static const arg_def_t good_dl =
  110. ARG_DEF(NULL, "good", 0, "Use Good Quality Deadline");
  111. static const arg_def_t rt_dl =
  112. ARG_DEF(NULL, "rt", 0, "Use Realtime Quality Deadline");
  113. static const arg_def_t quietarg =
  114. ARG_DEF("q", "quiet", 0, "Do not print encode progress");
  115. static const arg_def_t verbosearg =
  116. ARG_DEF("v", "verbose", 0, "Show encoder parameters");
  117. static const arg_def_t psnrarg =
  118. ARG_DEF(NULL, "psnr", 0, "Show PSNR in status line");
  119. static const struct arg_enum_list test_decode_enum[] = {
  120. { "off", TEST_DECODE_OFF },
  121. { "fatal", TEST_DECODE_FATAL },
  122. { "warn", TEST_DECODE_WARN },
  123. { NULL, 0 }
  124. };
  125. static const arg_def_t recontest = ARG_DEF_ENUM(
  126. NULL, "test-decode", 1, "Test encode/decode mismatch", test_decode_enum);
  127. static const arg_def_t framerate =
  128. ARG_DEF(NULL, "fps", 1, "Stream frame rate (rate/scale)");
  129. static const arg_def_t use_webm =
  130. ARG_DEF(NULL, "webm", 0, "Output WebM (default when WebM IO is enabled)");
  131. static const arg_def_t use_ivf = ARG_DEF(NULL, "ivf", 0, "Output IVF");
  132. static const arg_def_t out_part =
  133. ARG_DEF("P", "output-partitions", 0,
  134. "Makes encoder output partitions. Requires IVF output!");
  135. static const arg_def_t q_hist_n =
  136. ARG_DEF(NULL, "q-hist", 1, "Show quantizer histogram (n-buckets)");
  137. static const arg_def_t rate_hist_n =
  138. ARG_DEF(NULL, "rate-hist", 1, "Show rate histogram (n-buckets)");
  139. static const arg_def_t disable_warnings =
  140. ARG_DEF(NULL, "disable-warnings", 0,
  141. "Disable warnings about potentially incorrect encode settings.");
  142. static const arg_def_t disable_warning_prompt =
  143. ARG_DEF("y", "disable-warning-prompt", 0,
  144. "Display warnings, but do not prompt user to continue.");
  145. #if CONFIG_VP9_HIGHBITDEPTH
  146. static const arg_def_t test16bitinternalarg = ARG_DEF(
  147. NULL, "test-16bit-internal", 0, "Force use of 16 bit internal buffer");
  148. #endif
  149. static const arg_def_t *main_args[] = { &help,
  150. &debugmode,
  151. &outputfile,
  152. &codecarg,
  153. &passes,
  154. &pass_arg,
  155. &fpf_name,
  156. &limit,
  157. &skip,
  158. &deadline,
  159. &best_dl,
  160. &good_dl,
  161. &rt_dl,
  162. &quietarg,
  163. &verbosearg,
  164. &psnrarg,
  165. &use_webm,
  166. &use_ivf,
  167. &out_part,
  168. &q_hist_n,
  169. &rate_hist_n,
  170. &disable_warnings,
  171. &disable_warning_prompt,
  172. &recontest,
  173. NULL };
  174. static const arg_def_t usage =
  175. ARG_DEF("u", "usage", 1, "Usage profile number to use");
  176. static const arg_def_t threads =
  177. ARG_DEF("t", "threads", 1, "Max number of threads to use");
  178. static const arg_def_t profile =
  179. ARG_DEF(NULL, "profile", 1, "Bitstream profile number to use");
  180. static const arg_def_t width = ARG_DEF("w", "width", 1, "Frame width");
  181. static const arg_def_t height = ARG_DEF("h", "height", 1, "Frame height");
  182. #if CONFIG_WEBM_IO
  183. static const struct arg_enum_list stereo_mode_enum[] = {
  184. { "mono", STEREO_FORMAT_MONO },
  185. { "left-right", STEREO_FORMAT_LEFT_RIGHT },
  186. { "bottom-top", STEREO_FORMAT_BOTTOM_TOP },
  187. { "top-bottom", STEREO_FORMAT_TOP_BOTTOM },
  188. { "right-left", STEREO_FORMAT_RIGHT_LEFT },
  189. { NULL, 0 }
  190. };
  191. static const arg_def_t stereo_mode = ARG_DEF_ENUM(
  192. NULL, "stereo-mode", 1, "Stereo 3D video format", stereo_mode_enum);
  193. #endif
  194. static const arg_def_t timebase = ARG_DEF(
  195. NULL, "timebase", 1, "Output timestamp precision (fractional seconds)");
  196. static const arg_def_t error_resilient =
  197. ARG_DEF(NULL, "error-resilient", 1, "Enable error resiliency features");
  198. static const arg_def_t lag_in_frames =
  199. ARG_DEF(NULL, "lag-in-frames", 1, "Max number of frames to lag");
  200. static const arg_def_t *global_args[] = { &use_yv12,
  201. &use_i420,
  202. &use_i422,
  203. &use_i444,
  204. &use_i440,
  205. &usage,
  206. &threads,
  207. &profile,
  208. &width,
  209. &height,
  210. #if CONFIG_WEBM_IO
  211. &stereo_mode,
  212. #endif
  213. &timebase,
  214. &framerate,
  215. &error_resilient,
  216. #if CONFIG_VP9_HIGHBITDEPTH
  217. &test16bitinternalarg,
  218. #endif
  219. &lag_in_frames,
  220. NULL };
  221. static const arg_def_t dropframe_thresh =
  222. ARG_DEF(NULL, "drop-frame", 1, "Temporal resampling threshold (buf %)");
  223. static const arg_def_t resize_allowed =
  224. ARG_DEF(NULL, "resize-allowed", 1, "Spatial resampling enabled (bool)");
  225. static const arg_def_t resize_width =
  226. ARG_DEF(NULL, "resize-width", 1, "Width of encoded frame");
  227. static const arg_def_t resize_height =
  228. ARG_DEF(NULL, "resize-height", 1, "Height of encoded frame");
  229. static const arg_def_t resize_up_thresh =
  230. ARG_DEF(NULL, "resize-up", 1, "Upscale threshold (buf %)");
  231. static const arg_def_t resize_down_thresh =
  232. ARG_DEF(NULL, "resize-down", 1, "Downscale threshold (buf %)");
  233. static const struct arg_enum_list end_usage_enum[] = { { "vbr", VPX_VBR },
  234. { "cbr", VPX_CBR },
  235. { "cq", VPX_CQ },
  236. { "q", VPX_Q },
  237. { NULL, 0 } };
  238. static const arg_def_t end_usage =
  239. ARG_DEF_ENUM(NULL, "end-usage", 1, "Rate control mode", end_usage_enum);
  240. static const arg_def_t target_bitrate =
  241. ARG_DEF(NULL, "target-bitrate", 1, "Bitrate (kbps)");
  242. static const arg_def_t min_quantizer =
  243. ARG_DEF(NULL, "min-q", 1, "Minimum (best) quantizer");
  244. static const arg_def_t max_quantizer =
  245. ARG_DEF(NULL, "max-q", 1, "Maximum (worst) quantizer");
  246. static const arg_def_t undershoot_pct =
  247. ARG_DEF(NULL, "undershoot-pct", 1, "Datarate undershoot (min) target (%)");
  248. static const arg_def_t overshoot_pct =
  249. ARG_DEF(NULL, "overshoot-pct", 1, "Datarate overshoot (max) target (%)");
  250. static const arg_def_t buf_sz =
  251. ARG_DEF(NULL, "buf-sz", 1, "Client buffer size (ms)");
  252. static const arg_def_t buf_initial_sz =
  253. ARG_DEF(NULL, "buf-initial-sz", 1, "Client initial buffer size (ms)");
  254. static const arg_def_t buf_optimal_sz =
  255. ARG_DEF(NULL, "buf-optimal-sz", 1, "Client optimal buffer size (ms)");
  256. static const arg_def_t *rc_args[] = {
  257. &dropframe_thresh, &resize_allowed, &resize_width, &resize_height,
  258. &resize_up_thresh, &resize_down_thresh, &end_usage, &target_bitrate,
  259. &min_quantizer, &max_quantizer, &undershoot_pct, &overshoot_pct,
  260. &buf_sz, &buf_initial_sz, &buf_optimal_sz, NULL
  261. };
  262. static const arg_def_t bias_pct =
  263. ARG_DEF(NULL, "bias-pct", 1, "CBR/VBR bias (0=CBR, 100=VBR)");
  264. static const arg_def_t minsection_pct =
  265. ARG_DEF(NULL, "minsection-pct", 1, "GOP min bitrate (% of target)");
  266. static const arg_def_t maxsection_pct =
  267. ARG_DEF(NULL, "maxsection-pct", 1, "GOP max bitrate (% of target)");
  268. static const arg_def_t corpus_complexity =
  269. ARG_DEF(NULL, "corpus-complexity", 1, "corpus vbr complexity midpoint");
  270. static const arg_def_t *rc_twopass_args[] = { &bias_pct, &minsection_pct,
  271. &maxsection_pct,
  272. &corpus_complexity, NULL };
  273. static const arg_def_t kf_min_dist =
  274. ARG_DEF(NULL, "kf-min-dist", 1, "Minimum keyframe interval (frames)");
  275. static const arg_def_t kf_max_dist =
  276. ARG_DEF(NULL, "kf-max-dist", 1, "Maximum keyframe interval (frames)");
  277. static const arg_def_t kf_disabled =
  278. ARG_DEF(NULL, "disable-kf", 0, "Disable keyframe placement");
  279. static const arg_def_t *kf_args[] = { &kf_min_dist, &kf_max_dist, &kf_disabled,
  280. NULL };
  281. static const arg_def_t noise_sens =
  282. ARG_DEF(NULL, "noise-sensitivity", 1, "Noise sensitivity (frames to blur)");
  283. static const arg_def_t sharpness =
  284. ARG_DEF(NULL, "sharpness", 1,
  285. "Increase sharpness at the expense of lower PSNR. (0..7)");
  286. static const arg_def_t static_thresh =
  287. ARG_DEF(NULL, "static-thresh", 1, "Motion detection threshold");
  288. static const arg_def_t arnr_maxframes =
  289. ARG_DEF(NULL, "arnr-maxframes", 1, "AltRef max frames (0..15)");
  290. static const arg_def_t arnr_strength =
  291. ARG_DEF(NULL, "arnr-strength", 1, "AltRef filter strength (0..6)");
  292. static const arg_def_t arnr_type =
  293. ARG_DEF(NULL, "arnr-type", 1, "AltRef filter type (1..3)");
  294. static const struct arg_enum_list tuning_enum[] = { { "psnr", VP8_TUNE_PSNR },
  295. { "ssim", VP8_TUNE_SSIM },
  296. { NULL, 0 } };
  297. static const arg_def_t tune_ssim =
  298. ARG_DEF_ENUM(NULL, "tune", 1, "Material to favor", tuning_enum);
  299. static const arg_def_t cq_level =
  300. ARG_DEF(NULL, "cq-level", 1, "Constant/Constrained Quality level");
  301. static const arg_def_t max_intra_rate_pct =
  302. ARG_DEF(NULL, "max-intra-rate", 1, "Max I-frame bitrate (pct)");
  303. static const arg_def_t gf_cbr_boost_pct = ARG_DEF(
  304. NULL, "gf-cbr-boost", 1, "Boost for Golden Frame in CBR mode (pct)");
  305. #if CONFIG_VP8_ENCODER
  306. static const arg_def_t cpu_used_vp8 =
  307. ARG_DEF(NULL, "cpu-used", 1, "CPU Used (-16..16)");
  308. static const arg_def_t auto_altref_vp8 = ARG_DEF(
  309. NULL, "auto-alt-ref", 1, "Enable automatic alt reference frames. (0..1)");
  310. static const arg_def_t token_parts =
  311. ARG_DEF(NULL, "token-parts", 1, "Number of token partitions to use, log2");
  312. static const arg_def_t screen_content_mode =
  313. ARG_DEF(NULL, "screen-content-mode", 1, "Screen content mode");
  314. static const arg_def_t *vp8_args[] = { &cpu_used_vp8,
  315. &auto_altref_vp8,
  316. &noise_sens,
  317. &sharpness,
  318. &static_thresh,
  319. &token_parts,
  320. &arnr_maxframes,
  321. &arnr_strength,
  322. &arnr_type,
  323. &tune_ssim,
  324. &cq_level,
  325. &max_intra_rate_pct,
  326. &gf_cbr_boost_pct,
  327. &screen_content_mode,
  328. NULL };
  329. static const int vp8_arg_ctrl_map[] = { VP8E_SET_CPUUSED,
  330. VP8E_SET_ENABLEAUTOALTREF,
  331. VP8E_SET_NOISE_SENSITIVITY,
  332. VP8E_SET_SHARPNESS,
  333. VP8E_SET_STATIC_THRESHOLD,
  334. VP8E_SET_TOKEN_PARTITIONS,
  335. VP8E_SET_ARNR_MAXFRAMES,
  336. VP8E_SET_ARNR_STRENGTH,
  337. VP8E_SET_ARNR_TYPE,
  338. VP8E_SET_TUNING,
  339. VP8E_SET_CQ_LEVEL,
  340. VP8E_SET_MAX_INTRA_BITRATE_PCT,
  341. VP8E_SET_GF_CBR_BOOST_PCT,
  342. VP8E_SET_SCREEN_CONTENT_MODE,
  343. 0 };
  344. #endif
  345. #if CONFIG_VP9_ENCODER
  346. static const arg_def_t cpu_used_vp9 =
  347. ARG_DEF(NULL, "cpu-used", 1, "CPU Used (-9..9)");
  348. static const arg_def_t auto_altref_vp9 = ARG_DEF(
  349. NULL, "auto-alt-ref", 1,
  350. "Enable automatic alt reference frames, 2+ enables multi-layer. (0..6)");
  351. static const arg_def_t tile_cols =
  352. ARG_DEF(NULL, "tile-columns", 1, "Number of tile columns to use, log2");
  353. static const arg_def_t tile_rows =
  354. ARG_DEF(NULL, "tile-rows", 1,
  355. "Number of tile rows to use, log2 (set to 0 while threads > 1)");
  356. static const arg_def_t enable_tpl_model =
  357. ARG_DEF(NULL, "enable-tpl", 1, "Enable temporal dependency model");
  358. static const arg_def_t lossless =
  359. ARG_DEF(NULL, "lossless", 1, "Lossless mode (0: false (default), 1: true)");
  360. static const arg_def_t frame_parallel_decoding = ARG_DEF(
  361. NULL, "frame-parallel", 1, "Enable frame parallel decodability features");
  362. static const arg_def_t aq_mode = ARG_DEF(
  363. NULL, "aq-mode", 1,
  364. "Adaptive quantization mode (0: off (default), 1: variance 2: complexity, "
  365. "3: cyclic refresh, 4: equator360)");
  366. static const arg_def_t alt_ref_aq = ARG_DEF(NULL, "alt-ref-aq", 1,
  367. "Special adaptive quantization for "
  368. "the alternate reference frames.");
  369. static const arg_def_t frame_periodic_boost =
  370. ARG_DEF(NULL, "frame-boost", 1,
  371. "Enable frame periodic boost (0: off (default), 1: on)");
  372. static const arg_def_t max_inter_rate_pct =
  373. ARG_DEF(NULL, "max-inter-rate", 1, "Max P-frame bitrate (pct)");
  374. static const arg_def_t min_gf_interval = ARG_DEF(
  375. NULL, "min-gf-interval", 1,
  376. "min gf/arf frame interval (default 0, indicating in-built behavior)");
  377. static const arg_def_t max_gf_interval = ARG_DEF(
  378. NULL, "max-gf-interval", 1,
  379. "max gf/arf frame interval (default 0, indicating in-built behavior)");
  380. static const struct arg_enum_list color_space_enum[] = {
  381. { "unknown", VPX_CS_UNKNOWN },
  382. { "bt601", VPX_CS_BT_601 },
  383. { "bt709", VPX_CS_BT_709 },
  384. { "smpte170", VPX_CS_SMPTE_170 },
  385. { "smpte240", VPX_CS_SMPTE_240 },
  386. { "bt2020", VPX_CS_BT_2020 },
  387. { "reserved", VPX_CS_RESERVED },
  388. { "sRGB", VPX_CS_SRGB },
  389. { NULL, 0 }
  390. };
  391. static const arg_def_t input_color_space =
  392. ARG_DEF_ENUM(NULL, "color-space", 1,
  393. "The color space of input content:", color_space_enum);
  394. #if CONFIG_VP9_HIGHBITDEPTH
  395. static const struct arg_enum_list bitdepth_enum[] = {
  396. { "8", VPX_BITS_8 }, { "10", VPX_BITS_10 }, { "12", VPX_BITS_12 }, { NULL, 0 }
  397. };
  398. static const arg_def_t bitdeptharg = ARG_DEF_ENUM(
  399. "b", "bit-depth", 1,
  400. "Bit depth for codec (8 for version <=1, 10 or 12 for version 2)",
  401. bitdepth_enum);
  402. static const arg_def_t inbitdeptharg =
  403. ARG_DEF(NULL, "input-bit-depth", 1, "Bit depth of input");
  404. #endif
  405. static const struct arg_enum_list tune_content_enum[] = {
  406. { "default", VP9E_CONTENT_DEFAULT },
  407. { "screen", VP9E_CONTENT_SCREEN },
  408. { "film", VP9E_CONTENT_FILM },
  409. { NULL, 0 }
  410. };
  411. static const arg_def_t tune_content = ARG_DEF_ENUM(
  412. NULL, "tune-content", 1, "Tune content type", tune_content_enum);
  413. static const arg_def_t target_level = ARG_DEF(
  414. NULL, "target-level", 1,
  415. "Target level\n"
  416. " 255: off (default)\n"
  417. " 0: only keep level stats\n"
  418. " 1: adaptively set alt-ref "
  419. "distance and column tile limit based on picture size, and keep"
  420. " level stats\n"
  421. " 10: level 1.0 11: level 1.1 "
  422. "... 62: level 6.2");
  423. static const arg_def_t row_mt =
  424. ARG_DEF(NULL, "row-mt", 1,
  425. "Enable row based non-deterministic multi-threading in VP9");
  426. #endif
  427. #if CONFIG_VP9_ENCODER
  428. static const arg_def_t *vp9_args[] = { &cpu_used_vp9,
  429. &auto_altref_vp9,
  430. &sharpness,
  431. &static_thresh,
  432. &tile_cols,
  433. &tile_rows,
  434. &enable_tpl_model,
  435. &arnr_maxframes,
  436. &arnr_strength,
  437. &arnr_type,
  438. &tune_ssim,
  439. &cq_level,
  440. &max_intra_rate_pct,
  441. &max_inter_rate_pct,
  442. &gf_cbr_boost_pct,
  443. &lossless,
  444. &frame_parallel_decoding,
  445. &aq_mode,
  446. &alt_ref_aq,
  447. &frame_periodic_boost,
  448. &noise_sens,
  449. &tune_content,
  450. &input_color_space,
  451. &min_gf_interval,
  452. &max_gf_interval,
  453. &target_level,
  454. &row_mt,
  455. #if CONFIG_VP9_HIGHBITDEPTH
  456. &bitdeptharg,
  457. &inbitdeptharg,
  458. #endif // CONFIG_VP9_HIGHBITDEPTH
  459. NULL };
  460. static const int vp9_arg_ctrl_map[] = { VP8E_SET_CPUUSED,
  461. VP8E_SET_ENABLEAUTOALTREF,
  462. VP8E_SET_SHARPNESS,
  463. VP8E_SET_STATIC_THRESHOLD,
  464. VP9E_SET_TILE_COLUMNS,
  465. VP9E_SET_TILE_ROWS,
  466. VP9E_SET_TPL,
  467. VP8E_SET_ARNR_MAXFRAMES,
  468. VP8E_SET_ARNR_STRENGTH,
  469. VP8E_SET_ARNR_TYPE,
  470. VP8E_SET_TUNING,
  471. VP8E_SET_CQ_LEVEL,
  472. VP8E_SET_MAX_INTRA_BITRATE_PCT,
  473. VP9E_SET_MAX_INTER_BITRATE_PCT,
  474. VP9E_SET_GF_CBR_BOOST_PCT,
  475. VP9E_SET_LOSSLESS,
  476. VP9E_SET_FRAME_PARALLEL_DECODING,
  477. VP9E_SET_AQ_MODE,
  478. VP9E_SET_ALT_REF_AQ,
  479. VP9E_SET_FRAME_PERIODIC_BOOST,
  480. VP9E_SET_NOISE_SENSITIVITY,
  481. VP9E_SET_TUNE_CONTENT,
  482. VP9E_SET_COLOR_SPACE,
  483. VP9E_SET_MIN_GF_INTERVAL,
  484. VP9E_SET_MAX_GF_INTERVAL,
  485. VP9E_SET_TARGET_LEVEL,
  486. VP9E_SET_ROW_MT,
  487. 0 };
  488. #endif
  489. static const arg_def_t *no_args[] = { NULL };
  490. static void show_help(FILE *fout, int shorthelp) {
  491. int i;
  492. const int num_encoder = get_vpx_encoder_count();
  493. fprintf(fout, "Usage: %s <options> -o dst_filename src_filename \n",
  494. exec_name);
  495. if (shorthelp) {
  496. fprintf(fout, "Use --help to see the full list of options.\n");
  497. return;
  498. }
  499. fprintf(fout, "\nOptions:\n");
  500. arg_show_usage(fout, main_args);
  501. fprintf(fout, "\nEncoder Global Options:\n");
  502. arg_show_usage(fout, global_args);
  503. fprintf(fout, "\nRate Control Options:\n");
  504. arg_show_usage(fout, rc_args);
  505. fprintf(fout, "\nTwopass Rate Control Options:\n");
  506. arg_show_usage(fout, rc_twopass_args);
  507. fprintf(fout, "\nKeyframe Placement Options:\n");
  508. arg_show_usage(fout, kf_args);
  509. #if CONFIG_VP8_ENCODER
  510. fprintf(fout, "\nVP8 Specific Options:\n");
  511. arg_show_usage(fout, vp8_args);
  512. #endif
  513. #if CONFIG_VP9_ENCODER
  514. fprintf(fout, "\nVP9 Specific Options:\n");
  515. arg_show_usage(fout, vp9_args);
  516. #endif
  517. fprintf(fout,
  518. "\nStream timebase (--timebase):\n"
  519. " The desired precision of timestamps in the output, expressed\n"
  520. " in fractional seconds. Default is 1/1000.\n");
  521. fprintf(fout, "\nIncluded encoders:\n\n");
  522. for (i = 0; i < num_encoder; ++i) {
  523. const VpxInterface *const encoder = get_vpx_encoder_by_index(i);
  524. const char *defstr = (i == (num_encoder - 1)) ? "(default)" : "";
  525. fprintf(fout, " %-6s - %s %s\n", encoder->name,
  526. vpx_codec_iface_name(encoder->codec_interface()), defstr);
  527. }
  528. fprintf(fout, "\n ");
  529. fprintf(fout, "Use --codec to switch to a non-default encoder.\n\n");
  530. }
  531. void usage_exit(void) {
  532. show_help(stderr, 1);
  533. exit(EXIT_FAILURE);
  534. }
  535. #define NELEMENTS(x) (sizeof(x) / sizeof(x[0]))
  536. #if CONFIG_VP9_ENCODER
  537. #define ARG_CTRL_CNT_MAX NELEMENTS(vp9_arg_ctrl_map)
  538. #else
  539. #define ARG_CTRL_CNT_MAX NELEMENTS(vp8_arg_ctrl_map)
  540. #endif
  541. #if !CONFIG_WEBM_IO
  542. typedef int stereo_format_t;
  543. struct WebmOutputContext {
  544. int debug;
  545. };
  546. #endif
  547. /* Per-stream configuration */
  548. struct stream_config {
  549. struct vpx_codec_enc_cfg cfg;
  550. const char *out_fn;
  551. const char *stats_fn;
  552. #if CONFIG_FP_MB_STATS
  553. const char *fpmb_stats_fn;
  554. #endif
  555. stereo_format_t stereo_fmt;
  556. int arg_ctrls[ARG_CTRL_CNT_MAX][2];
  557. int arg_ctrl_cnt;
  558. int write_webm;
  559. #if CONFIG_VP9_HIGHBITDEPTH
  560. // whether to use 16bit internal buffers
  561. int use_16bit_internal;
  562. #endif
  563. };
  564. struct stream_state {
  565. int index;
  566. struct stream_state *next;
  567. struct stream_config config;
  568. FILE *file;
  569. struct rate_hist *rate_hist;
  570. struct WebmOutputContext webm_ctx;
  571. uint64_t psnr_sse_total;
  572. uint64_t psnr_samples_total;
  573. double psnr_totals[4];
  574. int psnr_count;
  575. int counts[64];
  576. vpx_codec_ctx_t encoder;
  577. unsigned int frames_out;
  578. uint64_t cx_time;
  579. size_t nbytes;
  580. stats_io_t stats;
  581. #if CONFIG_FP_MB_STATS
  582. stats_io_t fpmb_stats;
  583. #endif
  584. struct vpx_image *img;
  585. vpx_codec_ctx_t decoder;
  586. int mismatch_seen;
  587. };
  588. static void validate_positive_rational(const char *msg,
  589. struct vpx_rational *rat) {
  590. if (rat->den < 0) {
  591. rat->num *= -1;
  592. rat->den *= -1;
  593. }
  594. if (rat->num < 0) die("Error: %s must be positive\n", msg);
  595. if (!rat->den) die("Error: %s has zero denominator\n", msg);
  596. }
  597. static void parse_global_config(struct VpxEncoderConfig *global, char **argv) {
  598. char **argi, **argj;
  599. struct arg arg;
  600. const int num_encoder = get_vpx_encoder_count();
  601. if (num_encoder < 1) die("Error: no valid encoder available\n");
  602. /* Initialize default parameters */
  603. memset(global, 0, sizeof(*global));
  604. global->codec = get_vpx_encoder_by_index(num_encoder - 1);
  605. global->passes = 0;
  606. global->color_type = I420;
  607. /* Assign default deadline to good quality */
  608. global->deadline = VPX_DL_GOOD_QUALITY;
  609. for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step) {
  610. arg.argv_step = 1;
  611. if (arg_match(&arg, &help, argi)) {
  612. show_help(stdout, 0);
  613. exit(EXIT_SUCCESS);
  614. } else if (arg_match(&arg, &codecarg, argi)) {
  615. global->codec = get_vpx_encoder_by_name(arg.val);
  616. if (!global->codec)
  617. die("Error: Unrecognized argument (%s) to --codec\n", arg.val);
  618. } else if (arg_match(&arg, &passes, argi)) {
  619. global->passes = arg_parse_uint(&arg);
  620. if (global->passes < 1 || global->passes > 2)
  621. die("Error: Invalid number of passes (%d)\n", global->passes);
  622. } else if (arg_match(&arg, &pass_arg, argi)) {
  623. global->pass = arg_parse_uint(&arg);
  624. if (global->pass < 1 || global->pass > 2)
  625. die("Error: Invalid pass selected (%d)\n", global->pass);
  626. } else if (arg_match(&arg, &usage, argi))
  627. global->usage = arg_parse_uint(&arg);
  628. else if (arg_match(&arg, &deadline, argi))
  629. global->deadline = arg_parse_uint(&arg);
  630. else if (arg_match(&arg, &best_dl, argi))
  631. global->deadline = VPX_DL_BEST_QUALITY;
  632. else if (arg_match(&arg, &good_dl, argi))
  633. global->deadline = VPX_DL_GOOD_QUALITY;
  634. else if (arg_match(&arg, &rt_dl, argi))
  635. global->deadline = VPX_DL_REALTIME;
  636. else if (arg_match(&arg, &use_yv12, argi))
  637. global->color_type = YV12;
  638. else if (arg_match(&arg, &use_i420, argi))
  639. global->color_type = I420;
  640. else if (arg_match(&arg, &use_i422, argi))
  641. global->color_type = I422;
  642. else if (arg_match(&arg, &use_i444, argi))
  643. global->color_type = I444;
  644. else if (arg_match(&arg, &use_i440, argi))
  645. global->color_type = I440;
  646. else if (arg_match(&arg, &quietarg, argi))
  647. global->quiet = 1;
  648. else if (arg_match(&arg, &verbosearg, argi))
  649. global->verbose = 1;
  650. else if (arg_match(&arg, &limit, argi))
  651. global->limit = arg_parse_uint(&arg);
  652. else if (arg_match(&arg, &skip, argi))
  653. global->skip_frames = arg_parse_uint(&arg);
  654. else if (arg_match(&arg, &psnrarg, argi))
  655. global->show_psnr = 1;
  656. else if (arg_match(&arg, &recontest, argi))
  657. global->test_decode = arg_parse_enum_or_int(&arg);
  658. else if (arg_match(&arg, &framerate, argi)) {
  659. global->framerate = arg_parse_rational(&arg);
  660. validate_positive_rational(arg.name, &global->framerate);
  661. global->have_framerate = 1;
  662. } else if (arg_match(&arg, &out_part, argi))
  663. global->out_part = 1;
  664. else if (arg_match(&arg, &debugmode, argi))
  665. global->debug = 1;
  666. else if (arg_match(&arg, &q_hist_n, argi))
  667. global->show_q_hist_buckets = arg_parse_uint(&arg);
  668. else if (arg_match(&arg, &rate_hist_n, argi))
  669. global->show_rate_hist_buckets = arg_parse_uint(&arg);
  670. else if (arg_match(&arg, &disable_warnings, argi))
  671. global->disable_warnings = 1;
  672. else if (arg_match(&arg, &disable_warning_prompt, argi))
  673. global->disable_warning_prompt = 1;
  674. else
  675. argj++;
  676. }
  677. if (global->pass) {
  678. /* DWIM: Assume the user meant passes=2 if pass=2 is specified */
  679. if (global->pass > global->passes) {
  680. warn("Assuming --pass=%d implies --passes=%d\n", global->pass,
  681. global->pass);
  682. global->passes = global->pass;
  683. }
  684. }
  685. /* Validate global config */
  686. if (global->passes == 0) {
  687. #if CONFIG_VP9_ENCODER
  688. // Make default VP9 passes = 2 until there is a better quality 1-pass
  689. // encoder
  690. if (global->codec != NULL && global->codec->name != NULL)
  691. global->passes = (strcmp(global->codec->name, "vp9") == 0 &&
  692. global->deadline != VPX_DL_REALTIME)
  693. ? 2
  694. : 1;
  695. #else
  696. global->passes = 1;
  697. #endif
  698. }
  699. if (global->deadline == VPX_DL_REALTIME && global->passes > 1) {
  700. warn("Enforcing one-pass encoding in realtime mode\n");
  701. global->passes = 1;
  702. }
  703. }
  704. static struct stream_state *new_stream(struct VpxEncoderConfig *global,
  705. struct stream_state *prev) {
  706. struct stream_state *stream;
  707. stream = calloc(1, sizeof(*stream));
  708. if (stream == NULL) {
  709. fatal("Failed to allocate new stream.");
  710. }
  711. if (prev) {
  712. memcpy(stream, prev, sizeof(*stream));
  713. stream->index++;
  714. prev->next = stream;
  715. } else {
  716. vpx_codec_err_t res;
  717. /* Populate encoder configuration */
  718. res = vpx_codec_enc_config_default(global->codec->codec_interface(),
  719. &stream->config.cfg, global->usage);
  720. if (res) fatal("Failed to get config: %s\n", vpx_codec_err_to_string(res));
  721. /* Change the default timebase to a high enough value so that the
  722. * encoder will always create strictly increasing timestamps.
  723. */
  724. stream->config.cfg.g_timebase.den = 1000;
  725. /* Never use the library's default resolution, require it be parsed
  726. * from the file or set on the command line.
  727. */
  728. stream->config.cfg.g_w = 0;
  729. stream->config.cfg.g_h = 0;
  730. /* Initialize remaining stream parameters */
  731. stream->config.write_webm = 1;
  732. #if CONFIG_WEBM_IO
  733. stream->config.stereo_fmt = STEREO_FORMAT_MONO;
  734. stream->webm_ctx.last_pts_ns = -1;
  735. stream->webm_ctx.writer = NULL;
  736. stream->webm_ctx.segment = NULL;
  737. #endif
  738. /* Allows removal of the application version from the EBML tags */
  739. stream->webm_ctx.debug = global->debug;
  740. /* Default lag_in_frames is 0 in realtime mode CBR mode*/
  741. if (global->deadline == VPX_DL_REALTIME &&
  742. stream->config.cfg.rc_end_usage == 1)
  743. stream->config.cfg.g_lag_in_frames = 0;
  744. }
  745. /* Output files must be specified for each stream */
  746. stream->config.out_fn = NULL;
  747. stream->next = NULL;
  748. return stream;
  749. }
  750. static int parse_stream_params(struct VpxEncoderConfig *global,
  751. struct stream_state *stream, char **argv) {
  752. char **argi, **argj;
  753. struct arg arg;
  754. static const arg_def_t **ctrl_args = no_args;
  755. static const int *ctrl_args_map = NULL;
  756. struct stream_config *config = &stream->config;
  757. int eos_mark_found = 0;
  758. #if CONFIG_VP9_HIGHBITDEPTH
  759. int test_16bit_internal = 0;
  760. #endif
  761. // Handle codec specific options
  762. if (0) {
  763. #if CONFIG_VP8_ENCODER
  764. } else if (strcmp(global->codec->name, "vp8") == 0) {
  765. ctrl_args = vp8_args;
  766. ctrl_args_map = vp8_arg_ctrl_map;
  767. #endif
  768. #if CONFIG_VP9_ENCODER
  769. } else if (strcmp(global->codec->name, "vp9") == 0) {
  770. ctrl_args = vp9_args;
  771. ctrl_args_map = vp9_arg_ctrl_map;
  772. #endif
  773. }
  774. for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step) {
  775. arg.argv_step = 1;
  776. /* Once we've found an end-of-stream marker (--) we want to continue
  777. * shifting arguments but not consuming them.
  778. */
  779. if (eos_mark_found) {
  780. argj++;
  781. continue;
  782. } else if (!strcmp(*argj, "--")) {
  783. eos_mark_found = 1;
  784. continue;
  785. }
  786. if (arg_match(&arg, &outputfile, argi)) {
  787. config->out_fn = arg.val;
  788. } else if (arg_match(&arg, &fpf_name, argi)) {
  789. config->stats_fn = arg.val;
  790. #if CONFIG_FP_MB_STATS
  791. } else if (arg_match(&arg, &fpmbf_name, argi)) {
  792. config->fpmb_stats_fn = arg.val;
  793. #endif
  794. } else if (arg_match(&arg, &use_webm, argi)) {
  795. #if CONFIG_WEBM_IO
  796. config->write_webm = 1;
  797. #else
  798. die("Error: --webm specified but webm is disabled.");
  799. #endif
  800. } else if (arg_match(&arg, &use_ivf, argi)) {
  801. config->write_webm = 0;
  802. } else if (arg_match(&arg, &threads, argi)) {
  803. config->cfg.g_threads = arg_parse_uint(&arg);
  804. } else if (arg_match(&arg, &profile, argi)) {
  805. config->cfg.g_profile = arg_parse_uint(&arg);
  806. } else if (arg_match(&arg, &width, argi)) {
  807. config->cfg.g_w = arg_parse_uint(&arg);
  808. } else if (arg_match(&arg, &height, argi)) {
  809. config->cfg.g_h = arg_parse_uint(&arg);
  810. #if CONFIG_VP9_HIGHBITDEPTH
  811. } else if (arg_match(&arg, &bitdeptharg, argi)) {
  812. config->cfg.g_bit_depth = arg_parse_enum_or_int(&arg);
  813. } else if (arg_match(&arg, &inbitdeptharg, argi)) {
  814. config->cfg.g_input_bit_depth = arg_parse_uint(&arg);
  815. #endif
  816. #if CONFIG_WEBM_IO
  817. } else if (arg_match(&arg, &stereo_mode, argi)) {
  818. config->stereo_fmt = arg_parse_enum_or_int(&arg);
  819. #endif
  820. } else if (arg_match(&arg, &timebase, argi)) {
  821. config->cfg.g_timebase = arg_parse_rational(&arg);
  822. validate_positive_rational(arg.name, &config->cfg.g_timebase);
  823. } else if (arg_match(&arg, &error_resilient, argi)) {
  824. config->cfg.g_error_resilient = arg_parse_uint(&arg);
  825. } else if (arg_match(&arg, &end_usage, argi)) {
  826. config->cfg.rc_end_usage = arg_parse_enum_or_int(&arg);
  827. } else if (arg_match(&arg, &lag_in_frames, argi)) {
  828. config->cfg.g_lag_in_frames = arg_parse_uint(&arg);
  829. if (global->deadline == VPX_DL_REALTIME &&
  830. config->cfg.rc_end_usage == VPX_CBR &&
  831. config->cfg.g_lag_in_frames != 0) {
  832. warn("non-zero %s option ignored in realtime CBR mode.\n", arg.name);
  833. config->cfg.g_lag_in_frames = 0;
  834. }
  835. } else if (arg_match(&arg, &dropframe_thresh, argi)) {
  836. config->cfg.rc_dropframe_thresh = arg_parse_uint(&arg);
  837. } else if (arg_match(&arg, &resize_allowed, argi)) {
  838. config->cfg.rc_resize_allowed = arg_parse_uint(&arg);
  839. } else if (arg_match(&arg, &resize_width, argi)) {
  840. config->cfg.rc_scaled_width = arg_parse_uint(&arg);
  841. } else if (arg_match(&arg, &resize_height, argi)) {
  842. config->cfg.rc_scaled_height = arg_parse_uint(&arg);
  843. } else if (arg_match(&arg, &resize_up_thresh, argi)) {
  844. config->cfg.rc_resize_up_thresh = arg_parse_uint(&arg);
  845. } else if (arg_match(&arg, &resize_down_thresh, argi)) {
  846. config->cfg.rc_resize_down_thresh = arg_parse_uint(&arg);
  847. } else if (arg_match(&arg, &end_usage, argi)) {
  848. config->cfg.rc_end_usage = arg_parse_enum_or_int(&arg);
  849. } else if (arg_match(&arg, &target_bitrate, argi)) {
  850. config->cfg.rc_target_bitrate = arg_parse_uint(&arg);
  851. } else if (arg_match(&arg, &min_quantizer, argi)) {
  852. config->cfg.rc_min_quantizer = arg_parse_uint(&arg);
  853. } else if (arg_match(&arg, &max_quantizer, argi)) {
  854. config->cfg.rc_max_quantizer = arg_parse_uint(&arg);
  855. } else if (arg_match(&arg, &undershoot_pct, argi)) {
  856. config->cfg.rc_undershoot_pct = arg_parse_uint(&arg);
  857. } else if (arg_match(&arg, &overshoot_pct, argi)) {
  858. config->cfg.rc_overshoot_pct = arg_parse_uint(&arg);
  859. } else if (arg_match(&arg, &buf_sz, argi)) {
  860. config->cfg.rc_buf_sz = arg_parse_uint(&arg);
  861. } else if (arg_match(&arg, &buf_initial_sz, argi)) {
  862. config->cfg.rc_buf_initial_sz = arg_parse_uint(&arg);
  863. } else if (arg_match(&arg, &buf_optimal_sz, argi)) {
  864. config->cfg.rc_buf_optimal_sz = arg_parse_uint(&arg);
  865. } else if (arg_match(&arg, &bias_pct, argi)) {
  866. config->cfg.rc_2pass_vbr_bias_pct = arg_parse_uint(&arg);
  867. if (global->passes < 2)
  868. warn("option %s ignored in one-pass mode.\n", arg.name);
  869. } else if (arg_match(&arg, &minsection_pct, argi)) {
  870. config->cfg.rc_2pass_vbr_minsection_pct = arg_parse_uint(&arg);
  871. if (global->passes < 2)
  872. warn("option %s ignored in one-pass mode.\n", arg.name);
  873. } else if (arg_match(&arg, &maxsection_pct, argi)) {
  874. config->cfg.rc_2pass_vbr_maxsection_pct = arg_parse_uint(&arg);
  875. if (global->passes < 2)
  876. warn("option %s ignored in one-pass mode.\n", arg.name);
  877. } else if (arg_match(&arg, &corpus_complexity, argi)) {
  878. config->cfg.rc_2pass_vbr_corpus_complexity = arg_parse_uint(&arg);
  879. if (global->passes < 2)
  880. warn("option %s ignored in one-pass mode.\n", arg.name);
  881. } else if (arg_match(&arg, &kf_min_dist, argi)) {
  882. config->cfg.kf_min_dist = arg_parse_uint(&arg);
  883. } else if (arg_match(&arg, &kf_max_dist, argi)) {
  884. config->cfg.kf_max_dist = arg_parse_uint(&arg);
  885. } else if (arg_match(&arg, &kf_disabled, argi)) {
  886. config->cfg.kf_mode = VPX_KF_DISABLED;
  887. #if CONFIG_VP9_HIGHBITDEPTH
  888. } else if (arg_match(&arg, &test16bitinternalarg, argi)) {
  889. if (strcmp(global->codec->name, "vp9") == 0) {
  890. test_16bit_internal = 1;
  891. }
  892. #endif
  893. } else {
  894. int i, match = 0;
  895. for (i = 0; ctrl_args[i]; i++) {
  896. if (arg_match(&arg, ctrl_args[i], argi)) {
  897. int j;
  898. match = 1;
  899. /* Point either to the next free element or the first
  900. * instance of this control.
  901. */
  902. for (j = 0; j < config->arg_ctrl_cnt; j++)
  903. if (ctrl_args_map != NULL &&
  904. config->arg_ctrls[j][0] == ctrl_args_map[i])
  905. break;
  906. /* Update/insert */
  907. assert(j < (int)ARG_CTRL_CNT_MAX);
  908. if (ctrl_args_map != NULL && j < (int)ARG_CTRL_CNT_MAX) {
  909. config->arg_ctrls[j][0] = ctrl_args_map[i];
  910. config->arg_ctrls[j][1] = arg_parse_enum_or_int(&arg);
  911. if (j == config->arg_ctrl_cnt) config->arg_ctrl_cnt++;
  912. }
  913. }
  914. }
  915. if (!match) argj++;
  916. }
  917. }
  918. #if CONFIG_VP9_HIGHBITDEPTH
  919. if (strcmp(global->codec->name, "vp9") == 0) {
  920. config->use_16bit_internal =
  921. test_16bit_internal | (config->cfg.g_profile > 1);
  922. }
  923. #endif
  924. return eos_mark_found;
  925. }
  926. #define FOREACH_STREAM(func) \
  927. do { \
  928. struct stream_state *stream; \
  929. for (stream = streams; stream; stream = stream->next) { \
  930. func; \
  931. } \
  932. } while (0)
  933. static void validate_stream_config(const struct stream_state *stream,
  934. const struct VpxEncoderConfig *global) {
  935. const struct stream_state *streami;
  936. (void)global;
  937. if (!stream->config.cfg.g_w || !stream->config.cfg.g_h)
  938. fatal(
  939. "Stream %d: Specify stream dimensions with --width (-w) "
  940. " and --height (-h)",
  941. stream->index);
  942. // Check that the codec bit depth is greater than the input bit depth.
  943. if (stream->config.cfg.g_input_bit_depth >
  944. (unsigned int)stream->config.cfg.g_bit_depth) {
  945. fatal("Stream %d: codec bit depth (%d) less than input bit depth (%d)",
  946. stream->index, (int)stream->config.cfg.g_bit_depth,
  947. stream->config.cfg.g_input_bit_depth);
  948. }
  949. for (streami = stream; streami; streami = streami->next) {
  950. /* All streams require output files */
  951. if (!streami->config.out_fn)
  952. fatal("Stream %d: Output file is required (specify with -o)",
  953. streami->index);
  954. /* Check for two streams outputting to the same file */
  955. if (streami != stream) {
  956. const char *a = stream->config.out_fn;
  957. const char *b = streami->config.out_fn;
  958. if (!strcmp(a, b) && strcmp(a, "/dev/null") && strcmp(a, ":nul"))
  959. fatal("Stream %d: duplicate output file (from stream %d)",
  960. streami->index, stream->index);
  961. }
  962. /* Check for two streams sharing a stats file. */
  963. if (streami != stream) {
  964. const char *a = stream->config.stats_fn;
  965. const char *b = streami->config.stats_fn;
  966. if (a && b && !strcmp(a, b))
  967. fatal("Stream %d: duplicate stats file (from stream %d)",
  968. streami->index, stream->index);
  969. }
  970. #if CONFIG_FP_MB_STATS
  971. /* Check for two streams sharing a mb stats file. */
  972. if (streami != stream) {
  973. const char *a = stream->config.fpmb_stats_fn;
  974. const char *b = streami->config.fpmb_stats_fn;
  975. if (a && b && !strcmp(a, b))
  976. fatal("Stream %d: duplicate mb stats file (from stream %d)",
  977. streami->index, stream->index);
  978. }
  979. #endif
  980. }
  981. }
  982. static void set_stream_dimensions(struct stream_state *stream, unsigned int w,
  983. unsigned int h) {
  984. if (!stream->config.cfg.g_w) {
  985. if (!stream->config.cfg.g_h)
  986. stream->config.cfg.g_w = w;
  987. else
  988. stream->config.cfg.g_w = w * stream->config.cfg.g_h / h;
  989. }
  990. if (!stream->config.cfg.g_h) {
  991. stream->config.cfg.g_h = h * stream->config.cfg.g_w / w;
  992. }
  993. }
  994. static const char *file_type_to_string(enum VideoFileType t) {
  995. switch (t) {
  996. case FILE_TYPE_RAW: return "RAW";
  997. case FILE_TYPE_Y4M: return "Y4M";
  998. default: return "Other";
  999. }
  1000. }
  1001. static const char *image_format_to_string(vpx_img_fmt_t f) {
  1002. switch (f) {
  1003. case VPX_IMG_FMT_I420: return "I420";
  1004. case VPX_IMG_FMT_I422: return "I422";
  1005. case VPX_IMG_FMT_I444: return "I444";
  1006. case VPX_IMG_FMT_I440: return "I440";
  1007. case VPX_IMG_FMT_YV12: return "YV12";
  1008. case VPX_IMG_FMT_I42016: return "I42016";
  1009. case VPX_IMG_FMT_I42216: return "I42216";
  1010. case VPX_IMG_FMT_I44416: return "I44416";
  1011. case VPX_IMG_FMT_I44016: return "I44016";
  1012. default: return "Other";
  1013. }
  1014. }
  1015. static void show_stream_config(struct stream_state *stream,
  1016. struct VpxEncoderConfig *global,
  1017. struct VpxInputContext *input) {
  1018. #define SHOW(field) \
  1019. fprintf(stderr, " %-28s = %d\n", #field, stream->config.cfg.field)
  1020. if (stream->index == 0) {
  1021. fprintf(stderr, "Codec: %s\n",
  1022. vpx_codec_iface_name(global->codec->codec_interface()));
  1023. fprintf(stderr, "Source file: %s File Type: %s Format: %s\n",
  1024. input->filename, file_type_to_string(input->file_type),
  1025. image_format_to_string(input->fmt));
  1026. }
  1027. if (stream->next || stream->index)
  1028. fprintf(stderr, "\nStream Index: %d\n", stream->index);
  1029. fprintf(stderr, "Destination file: %s\n", stream->config.out_fn);
  1030. fprintf(stderr, "Encoder parameters:\n");
  1031. SHOW(g_usage);
  1032. SHOW(g_threads);
  1033. SHOW(g_profile);
  1034. SHOW(g_w);
  1035. SHOW(g_h);
  1036. SHOW(g_bit_depth);
  1037. SHOW(g_input_bit_depth);
  1038. SHOW(g_timebase.num);
  1039. SHOW(g_timebase.den);
  1040. SHOW(g_error_resilient);
  1041. SHOW(g_pass);
  1042. SHOW(g_lag_in_frames);
  1043. SHOW(rc_dropframe_thresh);
  1044. SHOW(rc_resize_allowed);
  1045. SHOW(rc_scaled_width);
  1046. SHOW(rc_scaled_height);
  1047. SHOW(rc_resize_up_thresh);
  1048. SHOW(rc_resize_down_thresh);
  1049. SHOW(rc_end_usage);
  1050. SHOW(rc_target_bitrate);
  1051. SHOW(rc_min_quantizer);
  1052. SHOW(rc_max_quantizer);
  1053. SHOW(rc_undershoot_pct);
  1054. SHOW(rc_overshoot_pct);
  1055. SHOW(rc_buf_sz);
  1056. SHOW(rc_buf_initial_sz);
  1057. SHOW(rc_buf_optimal_sz);
  1058. SHOW(rc_2pass_vbr_bias_pct);
  1059. SHOW(rc_2pass_vbr_minsection_pct);
  1060. SHOW(rc_2pass_vbr_maxsection_pct);
  1061. SHOW(rc_2pass_vbr_corpus_complexity);
  1062. SHOW(kf_mode);
  1063. SHOW(kf_min_dist);
  1064. SHOW(kf_max_dist);
  1065. }
  1066. static void open_output_file(struct stream_state *stream,
  1067. struct VpxEncoderConfig *global,
  1068. const struct VpxRational *pixel_aspect_ratio) {
  1069. const char *fn = stream->config.out_fn;
  1070. const struct vpx_codec_enc_cfg *const cfg = &stream->config.cfg;
  1071. if (cfg->g_pass == VPX_RC_FIRST_PASS) return;
  1072. stream->file = strcmp(fn, "-") ? fopen(fn, "wb") : set_binary_mode(stdout);
  1073. if (!stream->file) fatal("Failed to open output file");
  1074. if (stream->config.write_webm && fseek(stream->file, 0, SEEK_CUR))
  1075. fatal("WebM output to pipes not supported.");
  1076. #if CONFIG_WEBM_IO
  1077. if (stream->config.write_webm) {
  1078. stream->webm_ctx.stream = stream->file;
  1079. write_webm_file_header(&stream->webm_ctx, cfg, stream->config.stereo_fmt,
  1080. global->codec->fourcc, pixel_aspect_ratio);
  1081. }
  1082. #else
  1083. (void)pixel_aspect_ratio;
  1084. #endif
  1085. if (!stream->config.write_webm) {
  1086. ivf_write_file_header(stream->file, cfg, global->codec->fourcc, 0);
  1087. }
  1088. }
  1089. static void close_output_file(struct stream_state *stream,
  1090. unsigned int fourcc) {
  1091. const struct vpx_codec_enc_cfg *const cfg = &stream->config.cfg;
  1092. if (cfg->g_pass == VPX_RC_FIRST_PASS) return;
  1093. #if CONFIG_WEBM_IO
  1094. if (stream->config.write_webm) {
  1095. write_webm_file_footer(&stream->webm_ctx);
  1096. }
  1097. #endif
  1098. if (!stream->config.write_webm) {
  1099. if (!fseek(stream->file, 0, SEEK_SET))
  1100. ivf_write_file_header(stream->file, &stream->config.cfg, fourcc,
  1101. stream->frames_out);
  1102. }
  1103. fclose(stream->file);
  1104. }
  1105. static void setup_pass(struct stream_state *stream,
  1106. struct VpxEncoderConfig *global, int pass) {
  1107. if (stream->config.stats_fn) {
  1108. if (!stats_open_file(&stream->stats, stream->config.stats_fn, pass))
  1109. fatal("Failed to open statistics store");
  1110. } else {
  1111. if (!stats_open_mem(&stream->stats, pass))
  1112. fatal("Failed to open statistics store");
  1113. }
  1114. #if CONFIG_FP_MB_STATS
  1115. if (stream->config.fpmb_stats_fn) {
  1116. if (!stats_open_file(&stream->fpmb_stats, stream->config.fpmb_stats_fn,
  1117. pass))
  1118. fatal("Failed to open mb statistics store");
  1119. } else {
  1120. if (!stats_open_mem(&stream->fpmb_stats, pass))
  1121. fatal("Failed to open mb statistics store");
  1122. }
  1123. #endif
  1124. stream->config.cfg.g_pass = global->passes == 2
  1125. ? pass ? VPX_RC_LAST_PASS : VPX_RC_FIRST_PASS
  1126. : VPX_RC_ONE_PASS;
  1127. if (pass) {
  1128. stream->config.cfg.rc_twopass_stats_in = stats_get(&stream->stats);
  1129. #if CONFIG_FP_MB_STATS
  1130. stream->config.cfg.rc_firstpass_mb_stats_in =
  1131. stats_get(&stream->fpmb_stats);
  1132. #endif
  1133. }
  1134. stream->cx_time = 0;
  1135. stream->nbytes = 0;
  1136. stream->frames_out = 0;
  1137. }
  1138. static void initialize_encoder(struct stream_state *stream,
  1139. struct VpxEncoderConfig *global) {
  1140. int i;
  1141. int flags = 0;
  1142. flags |= global->show_psnr ? VPX_CODEC_USE_PSNR : 0;
  1143. flags |= global->out_part ? VPX_CODEC_USE_OUTPUT_PARTITION : 0;
  1144. #if CONFIG_VP9_HIGHBITDEPTH
  1145. flags |= stream->config.use_16bit_internal ? VPX_CODEC_USE_HIGHBITDEPTH : 0;
  1146. #endif
  1147. /* Construct Encoder Context */
  1148. vpx_codec_enc_init(&stream->encoder, global->codec->codec_interface(),
  1149. &stream->config.cfg, flags);
  1150. ctx_exit_on_error(&stream->encoder, "Failed to initialize encoder");
  1151. /* Note that we bypass the vpx_codec_control wrapper macro because
  1152. * we're being clever to store the control IDs in an array. Real
  1153. * applications will want to make use of the enumerations directly
  1154. */
  1155. for (i = 0; i < stream->config.arg_ctrl_cnt; i++) {
  1156. int ctrl = stream->config.arg_ctrls[i][0];
  1157. int value = stream->config.arg_ctrls[i][1];
  1158. if (vpx_codec_control_(&stream->encoder, ctrl, value))
  1159. fprintf(stderr, "Error: Tried to set control %d = %d\n", ctrl, value);
  1160. ctx_exit_on_error(&stream->encoder, "Failed to control codec");
  1161. }
  1162. #if CONFIG_DECODERS
  1163. if (global->test_decode != TEST_DECODE_OFF) {
  1164. const VpxInterface *decoder = get_vpx_decoder_by_name(global->codec->name);
  1165. vpx_codec_dec_init(&stream->decoder, decoder->codec_interface(), NULL, 0);
  1166. }
  1167. #endif
  1168. }
  1169. static void encode_frame(struct stream_state *stream,
  1170. struct VpxEncoderConfig *global, struct vpx_image *img,
  1171. unsigned int frames_in) {
  1172. vpx_codec_pts_t frame_start, next_frame_start;
  1173. struct vpx_codec_enc_cfg *cfg = &stream->config.cfg;
  1174. struct vpx_usec_timer timer;
  1175. frame_start =
  1176. (cfg->g_timebase.den * (int64_t)(frames_in - 1) * global->framerate.den) /
  1177. cfg->g_timebase.num / global->framerate.num;
  1178. next_frame_start =
  1179. (cfg->g_timebase.den * (int64_t)(frames_in)*global->framerate.den) /
  1180. cfg->g_timebase.num / global->framerate.num;
  1181. /* Scale if necessary */
  1182. #if CONFIG_VP9_HIGHBITDEPTH
  1183. if (img) {
  1184. if ((img->fmt & VPX_IMG_FMT_HIGHBITDEPTH) &&
  1185. (img->d_w != cfg->g_w || img->d_h != cfg->g_h)) {
  1186. if (img->fmt != VPX_IMG_FMT_I42016) {
  1187. fprintf(stderr, "%s can only scale 4:2:0 inputs\n", exec_name);
  1188. exit(EXIT_FAILURE);
  1189. }
  1190. #if CONFIG_LIBYUV
  1191. if (!stream->img) {
  1192. stream->img =
  1193. vpx_img_alloc(NULL, VPX_IMG_FMT_I42016, cfg->g_w, cfg->g_h, 16);
  1194. }
  1195. I420Scale_16(
  1196. (uint16_t *)img->planes[VPX_PLANE_Y], img->stride[VPX_PLANE_Y] / 2,
  1197. (uint16_t *)img->planes[VPX_PLANE_U], img->stride[VPX_PLANE_U] / 2,
  1198. (uint16_t *)img->planes[VPX_PLANE_V], img->stride[VPX_PLANE_V] / 2,
  1199. img->d_w, img->d_h, (uint16_t *)stream->img->planes[VPX_PLANE_Y],
  1200. stream->img->stride[VPX_PLANE_Y] / 2,
  1201. (uint16_t *)stream->img->planes[VPX_PLANE_U],
  1202. stream->img->stride[VPX_PLANE_U] / 2,
  1203. (uint16_t *)stream->img->planes[VPX_PLANE_V],
  1204. stream->img->stride[VPX_PLANE_V] / 2, stream->img->d_w,
  1205. stream->img->d_h, kFilterBox);
  1206. img = stream->img;
  1207. #else
  1208. stream->encoder.err = 1;
  1209. ctx_exit_on_error(&stream->encoder,
  1210. "Stream %d: Failed to encode frame.\n"
  1211. "Scaling disabled in this configuration. \n"
  1212. "To enable, configure with --enable-libyuv\n",
  1213. stream->index);
  1214. #endif
  1215. }
  1216. }
  1217. #endif
  1218. if (img && (img->d_w != cfg->g_w || img->d_h != cfg->g_h)) {
  1219. if (img->fmt != VPX_IMG_FMT_I420 && img->fmt != VPX_IMG_FMT_YV12) {
  1220. fprintf(stderr, "%s can only scale 4:2:0 8bpp inputs\n", exec_name);
  1221. exit(EXIT_FAILURE);
  1222. }
  1223. #if CONFIG_LIBYUV
  1224. if (!stream->img)
  1225. stream->img =
  1226. vpx_img_alloc(NULL, VPX_IMG_FMT_I420, cfg->g_w, cfg->g_h, 16);
  1227. I420Scale(
  1228. img->planes[VPX_PLANE_Y], img->stride[VPX_PLANE_Y],
  1229. img->planes[VPX_PLANE_U], img->stride[VPX_PLANE_U],
  1230. img->planes[VPX_PLANE_V], img->stride[VPX_PLANE_V], img->d_w, img->d_h,
  1231. stream->img->planes[VPX_PLANE_Y], stream->img->stride[VPX_PLANE_Y],
  1232. stream->img->planes[VPX_PLANE_U], stream->img->stride[VPX_PLANE_U],
  1233. stream->img->planes[VPX_PLANE_V], stream->img->stride[VPX_PLANE_V],
  1234. stream->img->d_w, stream->img->d_h, kFilterBox);
  1235. img = stream->img;
  1236. #else
  1237. stream->encoder.err = 1;
  1238. ctx_exit_on_error(&stream->encoder,
  1239. "Stream %d: Failed to encode frame.\n"
  1240. "Scaling disabled in this configuration. \n"
  1241. "To enable, configure with --enable-libyuv\n",
  1242. stream->index);
  1243. #endif
  1244. }
  1245. vpx_usec_timer_start(&timer);
  1246. vpx_codec_encode(&stream->encoder, img, frame_start,
  1247. (unsigned long)(next_frame_start - frame_start), 0,
  1248. global->deadline);
  1249. vpx_usec_timer_mark(&timer);
  1250. stream->cx_time += vpx_usec_timer_elapsed(&timer);
  1251. ctx_exit_on_error(&stream->encoder, "Stream %d: Failed to encode frame",
  1252. stream->index);
  1253. }
  1254. static void update_quantizer_histogram(struct stream_state *stream) {
  1255. if (stream->config.cfg.g_pass != VPX_RC_FIRST_PASS) {
  1256. int q;
  1257. vpx_codec_control(&stream->encoder, VP8E_GET_LAST_QUANTIZER_64, &q);
  1258. ctx_exit_on_error(&stream->encoder, "Failed to read quantizer");
  1259. stream->counts[q]++;
  1260. }
  1261. }
  1262. static void get_cx_data(struct stream_state *stream,
  1263. struct VpxEncoderConfig *global, int *got_data) {
  1264. const vpx_codec_cx_pkt_t *pkt;
  1265. const struct vpx_codec_enc_cfg *cfg = &stream->config.cfg;
  1266. vpx_codec_iter_t iter = NULL;
  1267. *got_data = 0;
  1268. while ((pkt = vpx_codec_get_cx_data(&stream->encoder, &iter))) {
  1269. static size_t fsize = 0;
  1270. static FileOffset ivf_header_pos = 0;
  1271. switch (pkt->kind) {
  1272. case VPX_CODEC_CX_FRAME_PKT:
  1273. if (!(pkt->data.frame.flags & VPX_FRAME_IS_FRAGMENT)) {
  1274. stream->frames_out++;
  1275. }
  1276. if (!global->quiet)
  1277. fprintf(stderr, " %6luF", (unsigned long)pkt->data.frame.sz);
  1278. update_rate_histogram(stream->rate_hist, cfg, pkt);
  1279. #if CONFIG_WEBM_IO
  1280. if (stream->config.write_webm) {
  1281. write_webm_block(&stream->webm_ctx, cfg, pkt);
  1282. }
  1283. #endif
  1284. if (!stream->config.write_webm) {
  1285. if (pkt->data.frame.partition_id <= 0) {
  1286. ivf_header_pos = ftello(stream->file);
  1287. fsize = pkt->data.frame.sz;
  1288. ivf_write_frame_header(stream->file, pkt->data.frame.pts, fsize);
  1289. } else {
  1290. fsize += pkt->data.frame.sz;
  1291. if (!(pkt->data.frame.flags & VPX_FRAME_IS_FRAGMENT)) {
  1292. const FileOffset currpos = ftello(stream->file);
  1293. fseeko(stream->file, ivf_header_pos, SEEK_SET);
  1294. ivf_write_frame_size(stream->file, fsize);
  1295. fseeko(stream->file, currpos, SEEK_SET);
  1296. }
  1297. }
  1298. (void)fwrite(pkt->data.frame.buf, 1, pkt->data.frame.sz,
  1299. stream->file);
  1300. }
  1301. stream->nbytes += pkt->data.raw.sz;
  1302. *got_data = 1;
  1303. #if CONFIG_DECODERS
  1304. if (global->test_decode != TEST_DECODE_OFF && !stream->mismatch_seen) {
  1305. vpx_codec_decode(&stream->decoder, pkt->data.frame.buf,
  1306. (unsigned int)pkt->data.frame.sz, NULL, 0);
  1307. if (stream->decoder.err) {
  1308. warn_or_exit_on_error(&stream->decoder,
  1309. global->test_decode == TEST_DECODE_FATAL,
  1310. "Failed to decode frame %d in stream %d",
  1311. stream->frames_out + 1, stream->index);
  1312. stream->mismatch_seen = stream->frames_out + 1;
  1313. }
  1314. }
  1315. #endif
  1316. break;
  1317. case VPX_CODEC_STATS_PKT:
  1318. stream->frames_out++;
  1319. stats_write(&stream->stats, pkt->data.twopass_stats.buf,
  1320. pkt->data.twopass_stats.sz);
  1321. stream->nbytes += pkt->data.raw.sz;
  1322. break;
  1323. #if CONFIG_FP_MB_STATS
  1324. case VPX_CODEC_FPMB_STATS_PKT:
  1325. stats_write(&stream->fpmb_stats, pkt->data.firstpass_mb_stats.buf,
  1326. pkt->data.firstpass_mb_stats.sz);
  1327. stream->nbytes += pkt->data.raw.sz;
  1328. break;
  1329. #endif
  1330. case VPX_CODEC_PSNR_PKT:
  1331. if (global->show_psnr) {
  1332. int i;
  1333. stream->psnr_sse_total += pkt->data.psnr.sse[0];
  1334. stream->psnr_samples_total += pkt->data.psnr.samples[0];
  1335. for (i = 0; i < 4; i++) {
  1336. if (!global->quiet)
  1337. fprintf(stderr, "%.3f ", pkt->data.psnr.psnr[i]);
  1338. stream->psnr_totals[i] += pkt->data.psnr.psnr[i];
  1339. }
  1340. stream->psnr_count++;
  1341. }
  1342. break;
  1343. default: break;
  1344. }
  1345. }
  1346. }
  1347. static void show_psnr(struct stream_state *stream, double peak) {
  1348. int i;
  1349. double ovpsnr;
  1350. if (!stream->psnr_count) return;
  1351. fprintf(stderr, "Stream %d PSNR (Overall/Avg/Y/U/V)", stream->index);
  1352. ovpsnr = sse_to_psnr((double)stream->psnr_samples_total, peak,
  1353. (double)stream->psnr_sse_total);
  1354. fprintf(stderr, " %.3f", ovpsnr);
  1355. for (i = 0; i < 4; i++) {
  1356. fprintf(stderr, " %.3f", stream->psnr_totals[i] / stream->psnr_count);
  1357. }
  1358. fprintf(stderr, "\n");
  1359. }
  1360. static float usec_to_fps(uint64_t usec, unsigned int frames) {
  1361. return (float)(usec > 0 ? frames * 1000000.0 / (float)usec : 0);
  1362. }
  1363. static void test_decode(struct stream_state *stream,
  1364. enum TestDecodeFatality fatal,
  1365. const VpxInterface *codec) {
  1366. vpx_image_t enc_img, dec_img;
  1367. if (stream->mismatch_seen) return;
  1368. /* Get the internal reference frame */
  1369. if (strcmp(codec->name, "vp8") == 0) {
  1370. struct vpx_ref_frame ref_enc, ref_dec;
  1371. int width, height;
  1372. width = (stream->config.cfg.g_w + 15) & ~15;
  1373. height = (stream->config.cfg.g_h + 15) & ~15;
  1374. vpx_img_alloc(&ref_enc.img, VPX_IMG_FMT_I420, width, height, 1);
  1375. enc_img = ref_enc.img;
  1376. vpx_img_alloc(&ref_dec.img, VPX_IMG_FMT_I420, width, height, 1);
  1377. dec_img = ref_dec.img;
  1378. ref_enc.frame_type = VP8_LAST_FRAME;
  1379. ref_dec.frame_type = VP8_LAST_FRAME;
  1380. vpx_codec_control(&stream->encoder, VP8_COPY_REFERENCE, &ref_enc);
  1381. vpx_codec_control(&stream->decoder, VP8_COPY_REFERENCE, &ref_dec);
  1382. } else {
  1383. struct vp9_ref_frame ref_enc, ref_dec;
  1384. ref_enc.idx = 0;
  1385. ref_dec.idx = 0;
  1386. vpx_codec_control(&stream->encoder, VP9_GET_REFERENCE, &ref_enc);
  1387. enc_img = ref_enc.img;
  1388. vpx_codec_control(&stream->decoder, VP9_GET_REFERENCE, &ref_dec);
  1389. dec_img = ref_dec.img;
  1390. #if CONFIG_VP9_HIGHBITDEPTH
  1391. if ((enc_img.fmt & VPX_IMG_FMT_HIGHBITDEPTH) !=
  1392. (dec_img.fmt & VPX_IMG_FMT_HIGHBITDEPTH)) {
  1393. if (enc_img.fmt & VPX_IMG_FMT_HIGHBITDEPTH) {
  1394. vpx_img_alloc(&enc_img, enc_img.fmt - VPX_IMG_FMT_HIGHBITDEPTH,
  1395. enc_img.d_w, enc_img.d_h, 16);
  1396. vpx_img_truncate_16_to_8(&enc_img, &ref_enc.img);
  1397. }
  1398. if (dec_img.fmt & VPX_IMG_FMT_HIGHBITDEPTH) {
  1399. vpx_img_alloc(&dec_img, dec_img.fmt - VPX_IMG_FMT_HIGHBITDEPTH,
  1400. dec_img.d_w, dec_img.d_h, 16);
  1401. vpx_img_truncate_16_to_8(&dec_img, &ref_dec.img);
  1402. }
  1403. }
  1404. #endif
  1405. }
  1406. ctx_exit_on_error(&stream->encoder, "Failed to get encoder reference frame");
  1407. ctx_exit_on_error(&stream->decoder, "Failed to get decoder reference frame");
  1408. if (!compare_img(&enc_img, &dec_img)) {
  1409. int y[4], u[4], v[4];
  1410. #if CONFIG_VP9_HIGHBITDEPTH
  1411. if (enc_img.fmt & VPX_IMG_FMT_HIGHBITDEPTH) {
  1412. find_mismatch_high(&enc_img, &dec_img, y, u, v);
  1413. } else {
  1414. find_mismatch(&enc_img, &dec_img, y, u, v);
  1415. }
  1416. #else
  1417. find_mismatch(&enc_img, &dec_img, y, u, v);
  1418. #endif
  1419. stream->decoder.err = 1;
  1420. warn_or_exit_on_error(&stream->decoder, fatal == TEST_DECODE_FATAL,
  1421. "Stream %d: Encode/decode mismatch on frame %d at"
  1422. " Y[%d, %d] {%d/%d},"
  1423. " U[%d, %d] {%d/%d},"
  1424. " V[%d, %d] {%d/%d}",
  1425. stream->index, stream->frames_out, y[0], y[1], y[2],
  1426. y[3], u[0], u[1], u[2], u[3], v[0], v[1], v[2], v[3]);
  1427. stream->mismatch_seen = stream->frames_out;
  1428. }
  1429. vpx_img_free(&enc_img);
  1430. vpx_img_free(&dec_img);
  1431. }
  1432. static void print_time(const char *label, int64_t etl) {
  1433. int64_t hours;
  1434. int64_t mins;
  1435. int64_t secs;
  1436. if (etl >= 0) {
  1437. hours = etl / 3600;
  1438. etl -= hours * 3600;
  1439. mins = etl / 60;
  1440. etl -= mins * 60;
  1441. secs = etl;
  1442. fprintf(stderr, "[%3s %2" PRId64 ":%02" PRId64 ":%02" PRId64 "] ", label,
  1443. hours, mins, secs);
  1444. } else {
  1445. fprintf(stderr, "[%3s unknown] ", label);
  1446. }
  1447. }
  1448. int main(int argc, const char **argv_) {
  1449. int pass;
  1450. vpx_image_t raw;
  1451. #if CONFIG_VP9_HIGHBITDEPTH
  1452. vpx_image_t raw_shift;
  1453. int allocated_raw_shift = 0;
  1454. int use_16bit_internal = 0;
  1455. int input_shift = 0;
  1456. #endif
  1457. int frame_avail, got_data;
  1458. struct VpxInputContext input;
  1459. struct VpxEncoderConfig global;
  1460. struct stream_state *streams = NULL;
  1461. char **argv, **argi;
  1462. uint64_t cx_time = 0;
  1463. int stream_cnt = 0;
  1464. int res = 0;
  1465. memset(&input, 0, sizeof(input));
  1466. exec_name = argv_[0];
  1467. /* Setup default input stream settings */
  1468. input.framerate.numerator = 30;
  1469. input.framerate.denominator = 1;
  1470. input.only_i420 = 1;
  1471. input.bit_depth = 0;
  1472. /* First parse the global configuration values, because we want to apply
  1473. * other parameters on top of the default configuration provided by the
  1474. * codec.
  1475. */
  1476. argv = argv_dup(argc - 1, argv_ + 1);
  1477. parse_global_config(&global, argv);
  1478. if (argc < 3) usage_exit();
  1479. switch (global.color_type) {
  1480. case I420: input.fmt = VPX_IMG_FMT_I420; break;
  1481. case I422: input.fmt = VPX_IMG_FMT_I422; break;
  1482. case I444: input.fmt = VPX_IMG_FMT_I444; break;
  1483. case I440: input.fmt = VPX_IMG_FMT_I440; break;
  1484. case YV12: input.fmt = VPX_IMG_FMT_YV12; break;
  1485. }
  1486. {
  1487. /* Now parse each stream's parameters. Using a local scope here
  1488. * due to the use of 'stream' as loop variable in FOREACH_STREAM
  1489. * loops
  1490. */
  1491. struct stream_state *stream = NULL;
  1492. do {
  1493. stream = new_stream(&global, stream);
  1494. stream_cnt++;
  1495. if (!streams) streams = stream;
  1496. } while (parse_stream_params(&global, stream, argv));
  1497. }
  1498. /* Check for unrecognized options */
  1499. for (argi = argv; *argi; argi++)
  1500. if (argi[0][0] == '-' && argi[0][1])
  1501. die("Error: Unrecognized option %s\n", *argi);
  1502. FOREACH_STREAM(check_encoder_config(global.disable_warning_prompt, &global,
  1503. &stream->config.cfg););
  1504. /* Handle non-option arguments */
  1505. input.filename = argv[0];
  1506. if (!input.filename) {
  1507. fprintf(stderr, "No input file specified!\n");
  1508. usage_exit();
  1509. }
  1510. /* Decide if other chroma subsamplings than 4:2:0 are supported */
  1511. if (global.codec->fourcc == VP9_FOURCC) input.only_i420 = 0;
  1512. for (pass = global.pass ? global.pass - 1 : 0; pass < global.passes; pass++) {
  1513. int frames_in = 0, seen_frames = 0;
  1514. int64_t estimated_time_left = -1;
  1515. int64_t average_rate = -1;
  1516. int64_t lagged_count = 0;
  1517. open_input_file(&input);
  1518. /* If the input file doesn't specify its w/h (raw files), try to get
  1519. * the data from the first stream's configuration.
  1520. */
  1521. if (!input.width || !input.height) {
  1522. FOREACH_STREAM({
  1523. if (stream->config.cfg.g_w && stream->config.cfg.g_h) {
  1524. input.width = stream->config.cfg.g_w;
  1525. input.height = stream->config.cfg.g_h;
  1526. break;
  1527. }
  1528. });
  1529. }
  1530. /* Update stream configurations from the input file's parameters */
  1531. if (!input.width || !input.height)
  1532. fatal(
  1533. "Specify stream dimensions with --width (-w) "
  1534. " and --height (-h)");
  1535. /* If input file does not specify bit-depth but input-bit-depth parameter
  1536. * exists, assume that to be the input bit-depth. However, if the
  1537. * input-bit-depth paramter does not exist, assume the input bit-depth
  1538. * to be the same as the codec bit-depth.
  1539. */
  1540. if (!input.bit_depth) {
  1541. FOREACH_STREAM({
  1542. if (stream->config.cfg.g_input_bit_depth)
  1543. input.bit_depth = stream->config.cfg.g_input_bit_depth;
  1544. else
  1545. input.bit_depth = stream->config.cfg.g_input_bit_depth =
  1546. (int)stream->config.cfg.g_bit_depth;
  1547. });
  1548. if (input.bit_depth > 8) input.fmt |= VPX_IMG_FMT_HIGHBITDEPTH;
  1549. } else {
  1550. FOREACH_STREAM(
  1551. { stream->config.cfg.g_input_bit_depth = input.bit_depth; });
  1552. }
  1553. FOREACH_STREAM(set_stream_dimensions(stream, input.width, input.height));
  1554. FOREACH_STREAM(validate_stream_config(stream, &global));
  1555. /* Ensure that --passes and --pass are consistent. If --pass is set and
  1556. * --passes=2, ensure --fpf was set.
  1557. */
  1558. if (global.pass && global.passes == 2)
  1559. FOREACH_STREAM({
  1560. if (!stream->config.stats_fn)
  1561. die("Stream %d: Must specify --fpf when --pass=%d"
  1562. " and --passes=2\n",
  1563. stream->index, global.pass);
  1564. });
  1565. #if !CONFIG_WEBM_IO
  1566. FOREACH_STREAM({
  1567. if (stream->config.write_webm) {
  1568. stream->config.write_webm = 0;
  1569. warn(
  1570. "vpxenc was compiled without WebM container support."
  1571. "Producing IVF output");
  1572. }
  1573. });
  1574. #endif
  1575. /* Use the frame rate from the file only if none was specified
  1576. * on the command-line.
  1577. */
  1578. if (!global.have_framerate) {
  1579. global.framerate.num = input.framerate.numerator;
  1580. global.framerate.den = input.framerate.denominator;
  1581. FOREACH_STREAM(stream->config.cfg.g_timebase.den = global.framerate.num;
  1582. stream->config.cfg.g_timebase.num = global.framerate.den);
  1583. }
  1584. /* Show configuration */
  1585. if (global.verbose && pass == 0)
  1586. FOREACH_STREAM(show_stream_config(stream, &global, &input));
  1587. if (pass == (global.pass ? global.pass - 1 : 0)) {
  1588. if (input.file_type == FILE_TYPE_Y4M)
  1589. /*The Y4M reader does its own allocation.
  1590. Just initialize this here to avoid problems if we never read any
  1591. frames.*/
  1592. memset(&raw, 0, sizeof(raw));
  1593. else
  1594. vpx_img_alloc(&raw, input.fmt, input.width, input.height, 32);
  1595. FOREACH_STREAM(stream->rate_hist = init_rate_histogram(
  1596. &stream->config.cfg, &global.framerate));
  1597. }
  1598. FOREACH_STREAM(setup_pass(stream, &global, pass));
  1599. FOREACH_STREAM(
  1600. open_output_file(stream, &global, &input.pixel_aspect_ratio));
  1601. FOREACH_STREAM(initialize_encoder(stream, &global));
  1602. #if CONFIG_VP9_HIGHBITDEPTH
  1603. if (strcmp(global.codec->name, "vp9") == 0) {
  1604. // Check to see if at least one stream uses 16 bit internal.
  1605. // Currently assume that the bit_depths for all streams using
  1606. // highbitdepth are the same.
  1607. FOREACH_STREAM({
  1608. if (stream->config.use_16bit_internal) {
  1609. use_16bit_internal = 1;
  1610. }
  1611. if (stream->config.cfg.g_profile == 0) {
  1612. input_shift = 0;
  1613. } else {
  1614. input_shift = (int)stream->config.cfg.g_bit_depth -
  1615. stream->config.cfg.g_input_bit_depth;
  1616. }
  1617. });
  1618. }
  1619. #endif
  1620. frame_avail = 1;
  1621. got_data = 0;
  1622. while (frame_avail || got_data) {
  1623. struct vpx_usec_timer timer;
  1624. if (!global.limit || frames_in < global.limit) {
  1625. frame_avail = read_frame(&input, &raw);
  1626. if (frame_avail) frames_in++;
  1627. seen_frames =
  1628. frames_in > global.skip_frames ? frames_in - global.skip_frames : 0;
  1629. if (!global.quiet) {
  1630. float fps = usec_to_fps(cx_time, seen_frames);
  1631. fprintf(stderr, "\rPass %d/%d ", pass + 1, global.passes);
  1632. if (stream_cnt == 1)
  1633. fprintf(stderr, "frame %4d/%-4d %7" PRId64 "B ", frames_in,
  1634. streams->frames_out, (int64_t)streams->nbytes);
  1635. else
  1636. fprintf(stderr, "frame %4d ", frames_in);
  1637. fprintf(stderr, "%7" PRId64 " %s %.2f %s ",
  1638. cx_time > 9999999 ? cx_time / 1000 : cx_time,
  1639. cx_time > 9999999 ? "ms" : "us", fps >= 1.0 ? fps : fps * 60,
  1640. fps >= 1.0 ? "fps" : "fpm");
  1641. print_time("ETA", estimated_time_left);
  1642. }
  1643. } else
  1644. frame_avail = 0;
  1645. if (frames_in > global.skip_frames) {
  1646. #if CONFIG_VP9_HIGHBITDEPTH
  1647. vpx_image_t *frame_to_encode;
  1648. if (input_shift || (use_16bit_internal && input.bit_depth == 8)) {
  1649. assert(use_16bit_internal);
  1650. // Input bit depth and stream bit depth do not match, so up
  1651. // shift frame to stream bit depth
  1652. if (!allocated_raw_shift) {
  1653. vpx_img_alloc(&raw_shift, raw.fmt | VPX_IMG_FMT_HIGHBITDEPTH,
  1654. input.width, input.height, 32);
  1655. allocated_raw_shift = 1;
  1656. }
  1657. vpx_img_upshift(&raw_shift, &raw, input_shift);
  1658. frame_to_encode = &raw_shift;
  1659. } else {
  1660. frame_to_encode = &raw;
  1661. }
  1662. vpx_usec_timer_start(&timer);
  1663. if (use_16bit_internal) {
  1664. assert(frame_to_encode->fmt & VPX_IMG_FMT_HIGHBITDEPTH);
  1665. FOREACH_STREAM({
  1666. if (stream->config.use_16bit_internal)
  1667. encode_frame(stream, &global,
  1668. frame_avail ? frame_to_encode : NULL, frames_in);
  1669. else
  1670. assert(0);
  1671. });
  1672. } else {
  1673. assert((frame_to_encode->fmt & VPX_IMG_FMT_HIGHBITDEPTH) == 0);
  1674. FOREACH_STREAM(encode_frame(stream, &global,
  1675. frame_avail ? frame_to_encode : NULL,
  1676. frames_in));
  1677. }
  1678. #else
  1679. vpx_usec_timer_start(&timer);
  1680. FOREACH_STREAM(encode_frame(stream, &global, frame_avail ? &raw : NULL,
  1681. frames_in));
  1682. #endif
  1683. vpx_usec_timer_mark(&timer);
  1684. cx_time += vpx_usec_timer_elapsed(&timer);
  1685. FOREACH_STREAM(update_quantizer_histogram(stream));
  1686. got_data = 0;
  1687. FOREACH_STREAM(get_cx_data(stream, &global, &got_data));
  1688. if (!got_data && input.length && streams != NULL &&
  1689. !streams->frames_out) {
  1690. lagged_count = global.limit ? seen_frames : ftello(input.file);
  1691. } else if (input.length) {
  1692. int64_t remaining;
  1693. int64_t rate;
  1694. if (global.limit) {
  1695. const int64_t frame_in_lagged = (seen_frames - lagged_count) * 1000;
  1696. rate = cx_time ? frame_in_lagged * (int64_t)1000000 / cx_time : 0;
  1697. remaining = 1000 * (global.limit - global.skip_frames -
  1698. seen_frames + lagged_count);
  1699. } else {
  1700. const int64_t input_pos = ftello(input.file);
  1701. const int64_t input_pos_lagged = input_pos - lagged_count;
  1702. const int64_t limit = input.length;
  1703. rate = cx_time ? input_pos_lagged * (int64_t)1000000 / cx_time : 0;
  1704. remaining = limit - input_pos + lagged_count;
  1705. }
  1706. average_rate =
  1707. (average_rate <= 0) ? rate : (average_rate * 7 + rate) / 8;
  1708. estimated_time_left = average_rate ? remaining / average_rate : -1;
  1709. }
  1710. if (got_data && global.test_decode != TEST_DECODE_OFF)
  1711. FOREACH_STREAM(test_decode(stream, global.test_decode, global.codec));
  1712. }
  1713. fflush(stdout);
  1714. if (!global.quiet) fprintf(stderr, "\033[K");
  1715. }
  1716. if (stream_cnt > 1) fprintf(stderr, "\n");
  1717. if (!global.quiet) {
  1718. FOREACH_STREAM(fprintf(
  1719. stderr,
  1720. "\rPass %d/%d frame %4d/%-4d %7" PRId64 "B %7" PRId64 "b/f %7" PRId64
  1721. "b/s %7" PRId64 " %s (%.2f fps)\033[K\n",
  1722. pass + 1, global.passes, frames_in, stream->frames_out,
  1723. (int64_t)stream->nbytes,
  1724. seen_frames ? (int64_t)(stream->nbytes * 8 / seen_frames) : 0,
  1725. seen_frames
  1726. ? (int64_t)stream->nbytes * 8 * (int64_t)global.framerate.num /
  1727. global.framerate.den / seen_frames
  1728. : 0,
  1729. stream->cx_time > 9999999 ? stream->cx_time / 1000 : stream->cx_time,
  1730. stream->cx_time > 9999999 ? "ms" : "us",
  1731. usec_to_fps(stream->cx_time, seen_frames)));
  1732. }
  1733. if (global.show_psnr) {
  1734. if (global.codec->fourcc == VP9_FOURCC) {
  1735. FOREACH_STREAM(
  1736. show_psnr(stream, (1 << stream->config.cfg.g_input_bit_depth) - 1));
  1737. } else {
  1738. FOREACH_STREAM(show_psnr(stream, 255.0));
  1739. }
  1740. }
  1741. FOREACH_STREAM(vpx_codec_destroy(&stream->encoder));
  1742. if (global.test_decode != TEST_DECODE_OFF) {
  1743. FOREACH_STREAM(vpx_codec_destroy(&stream->decoder));
  1744. }
  1745. close_input_file(&input);
  1746. if (global.test_decode == TEST_DECODE_FATAL) {
  1747. FOREACH_STREAM(res |= stream->mismatch_seen);
  1748. }
  1749. FOREACH_STREAM(close_output_file(stream, global.codec->fourcc));
  1750. FOREACH_STREAM(stats_close(&stream->stats, global.passes - 1));
  1751. #if CONFIG_FP_MB_STATS
  1752. FOREACH_STREAM(stats_close(&stream->fpmb_stats, global.passes - 1));
  1753. #endif
  1754. if (global.pass) break;
  1755. }
  1756. if (global.show_q_hist_buckets)
  1757. FOREACH_STREAM(
  1758. show_q_histogram(stream->counts, global.show_q_hist_buckets));
  1759. if (global.show_rate_hist_buckets)
  1760. FOREACH_STREAM(show_rate_histogram(stream->rate_hist, &stream->config.cfg,
  1761. global.show_rate_hist_buckets));
  1762. FOREACH_STREAM(destroy_rate_histogram(stream->rate_hist));
  1763. #if CONFIG_INTERNAL_STATS
  1764. /* TODO(jkoleszar): This doesn't belong in this executable. Do it for now,
  1765. * to match some existing utilities.
  1766. */
  1767. if (!(global.pass == 1 && global.passes == 2))
  1768. FOREACH_STREAM({
  1769. FILE *f = fopen("opsnr.stt", "a");
  1770. if (stream->mismatch_seen) {
  1771. fprintf(f, "First mismatch occurred in frame %d\n",
  1772. stream->mismatch_seen);
  1773. } else {
  1774. fprintf(f, "No mismatch detected in recon buffers\n");
  1775. }
  1776. fclose(f);
  1777. });
  1778. #endif
  1779. #if CONFIG_VP9_HIGHBITDEPTH
  1780. if (allocated_raw_shift) vpx_img_free(&raw_shift);
  1781. #endif
  1782. vpx_img_free(&raw);
  1783. free(argv);
  1784. free(streams);
  1785. return res ? EXIT_FAILURE : EXIT_SUCCESS;
  1786. }