2
0

vpxenc.c 81 KB

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