build_js.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. #!/usr/bin/env python
  2. import os, sys, subprocess, argparse, shutil, glob, re, multiprocessing
  3. import logging as log
  4. SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
  5. class Fail(Exception):
  6. def __init__(self, text=None):
  7. self.t = text
  8. def __str__(self):
  9. return "ERROR" if self.t is None else self.t
  10. def execute(cmd, shell=False):
  11. try:
  12. log.info("Executing: %s" % cmd)
  13. env = os.environ.copy()
  14. env['VERBOSE'] = '1'
  15. retcode = subprocess.call(cmd, shell=shell, env=env)
  16. if retcode < 0:
  17. raise Fail("Child was terminated by signal: %s" % -retcode)
  18. elif retcode > 0:
  19. raise Fail("Child returned: %s" % retcode)
  20. except OSError as e:
  21. raise Fail("Execution failed: %d / %s" % (e.errno, e.strerror))
  22. def rm_one(d):
  23. d = os.path.abspath(d)
  24. if os.path.exists(d):
  25. if os.path.isdir(d):
  26. log.info("Removing dir: %s", d)
  27. shutil.rmtree(d)
  28. elif os.path.isfile(d):
  29. log.info("Removing file: %s", d)
  30. os.remove(d)
  31. def check_dir(d, create=False, clean=False):
  32. d = os.path.abspath(d)
  33. log.info("Check dir %s (create: %s, clean: %s)", d, create, clean)
  34. if os.path.exists(d):
  35. if not os.path.isdir(d):
  36. raise Fail("Not a directory: %s" % d)
  37. if clean:
  38. for x in glob.glob(os.path.join(d, "*")):
  39. rm_one(x)
  40. else:
  41. if create:
  42. os.makedirs(d)
  43. return d
  44. def check_file(d):
  45. d = os.path.abspath(d)
  46. if os.path.exists(d):
  47. if os.path.isfile(d):
  48. return True
  49. else:
  50. return False
  51. return False
  52. def find_file(name, path):
  53. for root, dirs, files in os.walk(path):
  54. if name in files:
  55. return os.path.join(root, name)
  56. class Builder:
  57. def __init__(self, options):
  58. self.options = options
  59. self.build_dir = check_dir(options.build_dir, create=True)
  60. self.opencv_dir = check_dir(options.opencv_dir)
  61. print('-----------------------------------------------------------')
  62. print('options.opencv_dir:', options.opencv_dir)
  63. self.emscripten_dir = check_dir(options.emscripten_dir)
  64. def get_toolchain_file(self):
  65. return os.path.join(self.emscripten_dir, "cmake", "Modules", "Platform", "Emscripten.cmake")
  66. def clean_build_dir(self):
  67. for d in ["CMakeCache.txt", "CMakeFiles/", "bin/", "libs/", "lib/", "modules"]:
  68. rm_one(d)
  69. def get_cmake_cmd(self):
  70. cmd = [
  71. "cmake",
  72. "-DPYTHON_DEFAULT_EXECUTABLE=%s" % sys.executable,
  73. "-DENABLE_PIC=FALSE", # To workaround emscripten upstream backend issue https://github.com/emscripten-core/emscripten/issues/8761
  74. "-DCMAKE_BUILD_TYPE=Release",
  75. "-DCMAKE_TOOLCHAIN_FILE='%s'" % self.get_toolchain_file(),
  76. "-DCPU_BASELINE=''",
  77. "-DCMAKE_INSTALL_PREFIX=/usr/local",
  78. "-DCPU_DISPATCH=''",
  79. "-DCV_TRACE=OFF",
  80. "-DBUILD_SHARED_LIBS=OFF",
  81. "-DWITH_1394=OFF",
  82. "-DWITH_ADE=OFF",
  83. "-DWITH_VTK=OFF",
  84. "-DWITH_EIGEN=OFF",
  85. "-DWITH_FFMPEG=OFF",
  86. "-DWITH_GSTREAMER=OFF",
  87. "-DWITH_GTK=OFF",
  88. "-DWITH_GTK_2_X=OFF",
  89. "-DWITH_IPP=OFF",
  90. "-DWITH_JASPER=OFF",
  91. "-DWITH_JPEG=OFF",
  92. "-DWITH_WEBP=OFF",
  93. "-DWITH_OPENEXR=OFF",
  94. "-DWITH_OPENGL=OFF",
  95. "-DWITH_OPENVX=OFF",
  96. "-DWITH_OPENNI=OFF",
  97. "-DWITH_OPENNI2=OFF",
  98. "-DWITH_PNG=OFF",
  99. "-DWITH_TBB=OFF",
  100. "-DWITH_TIFF=OFF",
  101. "-DWITH_V4L=OFF",
  102. "-DWITH_OPENCL=OFF",
  103. "-DWITH_OPENCL_SVM=OFF",
  104. "-DWITH_OPENCLAMDFFT=OFF",
  105. "-DWITH_OPENCLAMDBLAS=OFF",
  106. "-DWITH_GPHOTO2=OFF",
  107. "-DWITH_LAPACK=OFF",
  108. "-DWITH_ITT=OFF",
  109. "-DWITH_QUIRC=ON",
  110. "-DBUILD_ZLIB=ON",
  111. "-DBUILD_opencv_apps=OFF",
  112. "-DBUILD_opencv_calib3d=ON",
  113. "-DBUILD_opencv_dnn=ON",
  114. "-DBUILD_opencv_features2d=ON",
  115. "-DBUILD_opencv_flann=ON", # No bindings provided. This module is used as a dependency for other modules.
  116. "-DBUILD_opencv_gapi=OFF",
  117. "-DBUILD_opencv_ml=OFF",
  118. "-DBUILD_opencv_photo=ON",
  119. "-DBUILD_opencv_imgcodecs=OFF",
  120. "-DBUILD_opencv_shape=OFF",
  121. "-DBUILD_opencv_videoio=OFF",
  122. "-DBUILD_opencv_videostab=OFF",
  123. "-DBUILD_opencv_highgui=OFF",
  124. "-DBUILD_opencv_superres=OFF",
  125. "-DBUILD_opencv_stitching=OFF",
  126. "-DBUILD_opencv_java=OFF",
  127. "-DBUILD_opencv_js=ON",
  128. "-DBUILD_opencv_python2=OFF",
  129. "-DBUILD_opencv_python3=OFF",
  130. "-DBUILD_EXAMPLES=ON",
  131. "-DBUILD_PACKAGE=OFF",
  132. "-DBUILD_TESTS=ON",
  133. "-DBUILD_PERF_TESTS=ON"]
  134. if self.options.cmake_option:
  135. cmd += self.options.cmake_option
  136. if self.options.build_doc:
  137. cmd.append("-DBUILD_DOCS=ON")
  138. else:
  139. cmd.append("-DBUILD_DOCS=OFF")
  140. if self.options.threads:
  141. cmd.append("-DWITH_PTHREADS_PF=ON")
  142. else:
  143. cmd.append("-DWITH_PTHREADS_PF=OFF")
  144. if self.options.simd:
  145. cmd.append("-DCV_ENABLE_INTRINSICS=ON")
  146. else:
  147. cmd.append("-DCV_ENABLE_INTRINSICS=OFF")
  148. if self.options.build_wasm_intrin_test:
  149. cmd.append("-DBUILD_WASM_INTRIN_TESTS=ON")
  150. else:
  151. cmd.append("-DBUILD_WASM_INTRIN_TESTS=OFF")
  152. if self.options.webnn:
  153. cmd.append("-DWITH_WEBNN=ON")
  154. flags = self.get_build_flags()
  155. if flags:
  156. cmd += ["-DCMAKE_C_FLAGS='%s'" % flags,
  157. "-DCMAKE_CXX_FLAGS='%s'" % flags]
  158. return cmd
  159. def get_build_flags(self):
  160. flags = ""
  161. if self.options.build_wasm:
  162. flags += "-s WASM=1 "
  163. elif self.options.disable_wasm:
  164. flags += "-s WASM=0 "
  165. if self.options.threads:
  166. flags += "-s USE_PTHREADS=1 -s PTHREAD_POOL_SIZE=4 "
  167. else:
  168. flags += "-s USE_PTHREADS=0 "
  169. if self.options.enable_exception:
  170. flags += "-s DISABLE_EXCEPTION_CATCHING=0 "
  171. if self.options.simd:
  172. flags += "-msimd128 "
  173. if self.options.build_flags:
  174. flags += self.options.build_flags
  175. if self.options.webnn:
  176. flags += "-s USE_WEBNN=1 "
  177. return flags
  178. def config(self):
  179. cmd = self.get_cmake_cmd()
  180. cmd.append(self.opencv_dir)
  181. execute(cmd)
  182. def build_opencvjs(self):
  183. execute(["make", "-j", str(multiprocessing.cpu_count()), "opencv.js"])
  184. def build_test(self):
  185. execute(["make", "-j", str(multiprocessing.cpu_count()), "opencv_js_test"])
  186. def build_perf(self):
  187. execute(["make", "-j", str(multiprocessing.cpu_count()), "opencv_js_perf"])
  188. def build_doc(self):
  189. execute(["make", "-j", str(multiprocessing.cpu_count()), "doxygen"])
  190. def build_loader(self):
  191. execute(["make", "-j", str(multiprocessing.cpu_count()), "opencv_js_loader"])
  192. #===================================================================================================
  193. if __name__ == "__main__":
  194. log.basicConfig(format='%(message)s', level=log.DEBUG)
  195. opencv_dir = os.path.abspath(os.path.join(SCRIPT_DIR, '../..'))
  196. emscripten_dir = None
  197. if "EMSCRIPTEN" in os.environ:
  198. emscripten_dir = os.environ["EMSCRIPTEN"]
  199. else:
  200. log.warning("EMSCRIPTEN environment variable is not available. Please properly activate Emscripten SDK and consider using 'emcmake' launcher")
  201. parser = argparse.ArgumentParser(description='Build OpenCV.js by Emscripten')
  202. parser.add_argument("build_dir", help="Building directory (and output)")
  203. parser.add_argument('--opencv_dir', default=opencv_dir, help='Opencv source directory (default is "../.." relative to script location)')
  204. parser.add_argument('--emscripten_dir', default=emscripten_dir, help="Path to Emscripten to use for build (deprecated in favor of 'emcmake' launcher)")
  205. parser.add_argument('--build_wasm', action="store_true", help="Build OpenCV.js in WebAssembly format")
  206. parser.add_argument('--disable_wasm', action="store_true", help="Build OpenCV.js in Asm.js format")
  207. parser.add_argument('--threads', action="store_true", help="Build OpenCV.js with threads optimization")
  208. parser.add_argument('--simd', action="store_true", help="Build OpenCV.js with SIMD optimization")
  209. parser.add_argument('--build_test', action="store_true", help="Build tests")
  210. parser.add_argument('--build_perf', action="store_true", help="Build performance tests")
  211. parser.add_argument('--build_doc', action="store_true", help="Build tutorials")
  212. parser.add_argument('--build_loader', action="store_true", help="Build OpenCV.js loader")
  213. parser.add_argument('--clean_build_dir', action="store_true", help="Clean build dir")
  214. parser.add_argument('--skip_config', action="store_true", help="Skip cmake config")
  215. parser.add_argument('--config_only', action="store_true", help="Only do cmake config")
  216. parser.add_argument('--enable_exception', action="store_true", help="Enable exception handling")
  217. # Use flag --cmake option="-D...=ON" only for one argument, if you would add more changes write new cmake_option flags
  218. parser.add_argument('--cmake_option', action='append', help="Append CMake options")
  219. # Use flag --build_flags="-s USE_PTHREADS=0 -Os" for one and more arguments as in the example
  220. parser.add_argument('--build_flags', help="Append Emscripten build options")
  221. parser.add_argument('--build_wasm_intrin_test', default=False, action="store_true", help="Build WASM intrin tests")
  222. # Write a path to modify file like argument of this flag
  223. parser.add_argument('--config', default=os.path.join(os.path.dirname(os.path.abspath(__file__)), 'opencv_js.config.py'),
  224. help="Specify configuration file with own list of exported into JS functions")
  225. parser.add_argument('--webnn', action="store_true", help="Enable WebNN Backend")
  226. args = parser.parse_args()
  227. log.debug("Args: %s", args)
  228. os.environ["OPENCV_JS_WHITELIST"] = os.path.abspath(args.config)
  229. if 'EMMAKEN_JUST_CONFIGURE' in os.environ:
  230. del os.environ['EMMAKEN_JUST_CONFIGURE'] # avoid linker errors with NODERAWFS message then using 'emcmake' launcher
  231. if args.emscripten_dir is None:
  232. log.error("Cannot get Emscripten path, please use 'emcmake' launcher or specify it either by EMSCRIPTEN environment variable or --emscripten_dir option.")
  233. sys.exit(-1)
  234. builder = Builder(args)
  235. os.chdir(builder.build_dir)
  236. if args.clean_build_dir:
  237. log.info("=====")
  238. log.info("===== Clean build dir %s", builder.build_dir)
  239. log.info("=====")
  240. builder.clean_build_dir()
  241. if not args.skip_config:
  242. target = "default target"
  243. if args.build_wasm:
  244. target = "wasm"
  245. elif args.disable_wasm:
  246. target = "asm.js"
  247. log.info("=====")
  248. log.info("===== Config OpenCV.js build for %s" % target)
  249. log.info("=====")
  250. builder.config()
  251. if args.config_only:
  252. sys.exit(0)
  253. log.info("=====")
  254. log.info("===== Building OpenCV.js")
  255. log.info("=====")
  256. builder.build_opencvjs()
  257. if args.build_test:
  258. log.info("=====")
  259. log.info("===== Building OpenCV.js tests")
  260. log.info("=====")
  261. builder.build_test()
  262. if args.build_perf:
  263. log.info("=====")
  264. log.info("===== Building OpenCV.js performance tests")
  265. log.info("=====")
  266. builder.build_perf()
  267. if args.build_doc:
  268. log.info("=====")
  269. log.info("===== Building OpenCV.js tutorials")
  270. log.info("=====")
  271. builder.build_doc()
  272. if args.build_loader:
  273. log.info("=====")
  274. log.info("===== Building OpenCV.js loader")
  275. log.info("=====")
  276. builder.build_loader()
  277. log.info("=====")
  278. log.info("===== Build finished")
  279. log.info("=====")
  280. opencvjs_path = os.path.join(builder.build_dir, "bin", "opencv.js")
  281. if check_file(opencvjs_path):
  282. log.info("OpenCV.js location: %s", opencvjs_path)
  283. if args.build_test:
  284. opencvjs_test_path = os.path.join(builder.build_dir, "bin", "tests.html")
  285. if check_file(opencvjs_test_path):
  286. log.info("OpenCV.js tests location: %s", opencvjs_test_path)
  287. if args.build_perf:
  288. opencvjs_perf_path = os.path.join(builder.build_dir, "bin", "perf")
  289. opencvjs_perf_base_path = os.path.join(builder.build_dir, "bin", "perf", "base.js")
  290. if check_file(opencvjs_perf_base_path):
  291. log.info("OpenCV.js performance tests location: %s", opencvjs_perf_path)
  292. if args.build_doc:
  293. opencvjs_tutorial_path = find_file("tutorial_js_root.html", os.path.join(builder.build_dir, "doc", "doxygen", "html"))
  294. if check_file(opencvjs_tutorial_path):
  295. log.info("OpenCV.js tutorials location: %s", opencvjs_tutorial_path)
  296. if args.build_loader:
  297. opencvjs_loader_path = os.path.join(builder.build_dir, "bin", "loader.js")
  298. if check_file(opencvjs_loader_path):
  299. log.info("OpenCV.js loader location: %s", opencvjs_loader_path)