vpxenc.c 82 KB

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