build_sdk.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  1. #!/usr/bin/env python
  2. import os, sys
  3. import argparse
  4. import glob
  5. import re
  6. import shutil
  7. import subprocess
  8. import time
  9. import logging as log
  10. import xml.etree.ElementTree as ET
  11. SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
  12. class Fail(Exception):
  13. def __init__(self, text=None):
  14. self.t = text
  15. def __str__(self):
  16. return "ERROR" if self.t is None else self.t
  17. def execute(cmd, shell=False):
  18. try:
  19. log.debug("Executing: %s" % cmd)
  20. log.info('Executing: ' + ' '.join(cmd))
  21. retcode = subprocess.call(cmd, shell=shell)
  22. if retcode < 0:
  23. raise Fail("Child was terminated by signal: %s" % -retcode)
  24. elif retcode > 0:
  25. raise Fail("Child returned: %s" % retcode)
  26. except OSError as e:
  27. raise Fail("Execution failed: %d / %s" % (e.errno, e.strerror))
  28. def rm_one(d):
  29. d = os.path.abspath(d)
  30. if os.path.exists(d):
  31. if os.path.isdir(d):
  32. log.info("Removing dir: %s", d)
  33. shutil.rmtree(d)
  34. elif os.path.isfile(d):
  35. log.info("Removing file: %s", d)
  36. os.remove(d)
  37. def check_dir(d, create=False, clean=False):
  38. d = os.path.abspath(d)
  39. log.info("Check dir %s (create: %s, clean: %s)", d, create, clean)
  40. if os.path.exists(d):
  41. if not os.path.isdir(d):
  42. raise Fail("Not a directory: %s" % d)
  43. if clean:
  44. for x in glob.glob(os.path.join(d, "*")):
  45. rm_one(x)
  46. else:
  47. if create:
  48. os.makedirs(d)
  49. return d
  50. def check_executable(cmd):
  51. try:
  52. log.debug("Executing: %s" % cmd)
  53. result = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
  54. if not isinstance(result, str):
  55. result = result.decode("utf-8")
  56. log.debug("Result: %s" % (result+'\n').split('\n')[0])
  57. return True
  58. except Exception as e:
  59. log.debug('Failed: %s' % e)
  60. return False
  61. def determine_opencv_version(version_hpp_path):
  62. # version in 2.4 - CV_VERSION_EPOCH.CV_VERSION_MAJOR.CV_VERSION_MINOR.CV_VERSION_REVISION
  63. # version in master - CV_VERSION_MAJOR.CV_VERSION_MINOR.CV_VERSION_REVISION-CV_VERSION_STATUS
  64. with open(version_hpp_path, "rt") as f:
  65. data = f.read()
  66. major = re.search(r'^#define\W+CV_VERSION_MAJOR\W+(\d+)$', data, re.MULTILINE).group(1)
  67. minor = re.search(r'^#define\W+CV_VERSION_MINOR\W+(\d+)$', data, re.MULTILINE).group(1)
  68. revision = re.search(r'^#define\W+CV_VERSION_REVISION\W+(\d+)$', data, re.MULTILINE).group(1)
  69. version_status = re.search(r'^#define\W+CV_VERSION_STATUS\W+"([^"]*)"$', data, re.MULTILINE).group(1)
  70. return "%(major)s.%(minor)s.%(revision)s%(version_status)s" % locals()
  71. # shutil.move fails if dst exists
  72. def move_smart(src, dst):
  73. def move_recurse(subdir):
  74. s = os.path.join(src, subdir)
  75. d = os.path.join(dst, subdir)
  76. if os.path.exists(d):
  77. if os.path.isdir(d):
  78. for item in os.listdir(s):
  79. move_recurse(os.path.join(subdir, item))
  80. elif os.path.isfile(s):
  81. shutil.move(s, d)
  82. else:
  83. shutil.move(s, d)
  84. move_recurse('')
  85. # shutil.copytree fails if dst exists
  86. def copytree_smart(src, dst):
  87. def copy_recurse(subdir):
  88. s = os.path.join(src, subdir)
  89. d = os.path.join(dst, subdir)
  90. if os.path.exists(d):
  91. if os.path.isdir(d):
  92. for item in os.listdir(s):
  93. copy_recurse(os.path.join(subdir, item))
  94. elif os.path.isfile(s):
  95. shutil.copy2(s, d)
  96. else:
  97. if os.path.isdir(s):
  98. shutil.copytree(s, d)
  99. elif os.path.isfile(s):
  100. shutil.copy2(s, d)
  101. copy_recurse('')
  102. def get_highest_version(subdirs):
  103. return max(subdirs, key=lambda dir: [int(comp) for comp in os.path.split(dir)[-1].split('.')])
  104. #===================================================================================================
  105. class ABI:
  106. def __init__(self, platform_id, name, toolchain, ndk_api_level = None, cmake_vars = dict()):
  107. self.platform_id = platform_id # platform code to add to apk version (for cmake)
  108. self.name = name # general name (official Android ABI identifier)
  109. self.toolchain = toolchain # toolchain identifier (for cmake)
  110. self.cmake_vars = dict(
  111. ANDROID_STL="gnustl_static",
  112. ANDROID_ABI=self.name,
  113. ANDROID_PLATFORM_ID=platform_id,
  114. )
  115. if toolchain is not None:
  116. self.cmake_vars['ANDROID_TOOLCHAIN_NAME'] = toolchain
  117. else:
  118. self.cmake_vars['ANDROID_TOOLCHAIN'] = 'clang'
  119. self.cmake_vars['ANDROID_STL'] = 'c++_shared'
  120. if ndk_api_level:
  121. self.cmake_vars['ANDROID_NATIVE_API_LEVEL'] = ndk_api_level
  122. self.cmake_vars.update(cmake_vars)
  123. def __str__(self):
  124. return "%s (%s)" % (self.name, self.toolchain)
  125. def haveIPP(self):
  126. return self.name == "x86" or self.name == "x86_64"
  127. def haveKleidiCV(self):
  128. return self.name == "arm64-v8a"
  129. #===================================================================================================
  130. class Builder:
  131. def __init__(self, workdir, opencvdir, config):
  132. self.workdir = check_dir(workdir, create=True)
  133. self.opencvdir = check_dir(opencvdir)
  134. self.config = config
  135. self.libdest = check_dir(os.path.join(self.workdir, "o4a"), create=True, clean=True)
  136. self.resultdest = check_dir(os.path.join(self.workdir, 'OpenCV-android-sdk'), create=True, clean=True)
  137. self.docdest = check_dir(os.path.join(self.workdir, 'OpenCV-android-sdk', 'sdk', 'java', 'javadoc'), create=True, clean=True)
  138. self.extra_packs = []
  139. self.opencv_version = determine_opencv_version(os.path.join(self.opencvdir, "modules", "core", "include", "opencv2", "core", "version.hpp"))
  140. self.use_ccache = False if config.no_ccache else True
  141. self.cmake_path = self.get_cmake()
  142. self.ninja_path = self.get_ninja()
  143. self.debug = True if config.debug else False
  144. self.debug_info = True if config.debug_info else False
  145. self.no_samples_build = True if config.no_samples_build else False
  146. self.hwasan = True if config.hwasan else False
  147. self.opencl = True if config.opencl else False
  148. self.no_kotlin = True if config.no_kotlin else False
  149. self.shared = True if config.shared else False
  150. self.disable = args.disable
  151. def get_cmake(self):
  152. if not self.config.use_android_buildtools and check_executable(['cmake', '--version']):
  153. log.info("Using cmake from PATH")
  154. return 'cmake'
  155. # look to see if Android SDK's cmake is installed
  156. android_cmake = os.path.join(os.environ['ANDROID_SDK'], 'cmake')
  157. if os.path.exists(android_cmake):
  158. cmake_subdirs = [f for f in os.listdir(android_cmake) if check_executable([os.path.join(android_cmake, f, 'bin', 'cmake'), '--version'])]
  159. if len(cmake_subdirs) > 0:
  160. # there could be more than one - get the most recent
  161. cmake_from_sdk = os.path.join(android_cmake, get_highest_version(cmake_subdirs), 'bin', 'cmake')
  162. log.info("Using cmake from Android SDK: %s", cmake_from_sdk)
  163. return cmake_from_sdk
  164. raise Fail("Can't find cmake")
  165. def get_ninja(self):
  166. if not self.config.use_android_buildtools and check_executable(['ninja', '--version']):
  167. log.info("Using ninja from PATH")
  168. return 'ninja'
  169. # Android SDK's cmake includes a copy of ninja - look to see if its there
  170. android_cmake = os.path.join(os.environ['ANDROID_SDK'], 'cmake')
  171. if os.path.exists(android_cmake):
  172. cmake_subdirs = [f for f in os.listdir(android_cmake) if check_executable([os.path.join(android_cmake, f, 'bin', 'ninja'), '--version'])]
  173. if len(cmake_subdirs) > 0:
  174. # there could be more than one - just take the first one
  175. ninja_from_sdk = os.path.join(android_cmake, cmake_subdirs[0], 'bin', 'ninja')
  176. log.info("Using ninja from Android SDK: %s", ninja_from_sdk)
  177. return ninja_from_sdk
  178. raise Fail("Can't find ninja")
  179. def get_toolchain_file(self):
  180. if not self.config.force_opencv_toolchain:
  181. toolchain = os.path.join(os.environ['ANDROID_NDK'], 'build', 'cmake', 'android.toolchain.cmake')
  182. if os.path.exists(toolchain):
  183. return toolchain
  184. toolchain = os.path.join(SCRIPT_DIR, "android.toolchain.cmake")
  185. if os.path.exists(toolchain):
  186. return toolchain
  187. else:
  188. raise Fail("Can't find toolchain")
  189. def get_engine_apk_dest(self, engdest):
  190. return os.path.join(engdest, "platforms", "android", "service", "engine", ".build")
  191. def add_extra_pack(self, ver, path):
  192. if path is None:
  193. return
  194. self.extra_packs.append((ver, check_dir(path)))
  195. def clean_library_build_dir(self):
  196. for d in ["CMakeCache.txt", "CMakeFiles/", "bin/", "libs/", "lib/", "package/", "install/samples/"]:
  197. rm_one(d)
  198. def build_library(self, abi, do_install, no_media_ndk):
  199. cmd = [self.cmake_path, "-GNinja"]
  200. cmake_vars = dict(
  201. CMAKE_TOOLCHAIN_FILE=self.get_toolchain_file(),
  202. INSTALL_CREATE_DISTRIB="ON",
  203. WITH_OPENCL="OFF",
  204. BUILD_KOTLIN_EXTENSIONS="ON",
  205. WITH_IPP=("ON" if abi.haveIPP() else "OFF"),
  206. WITH_TBB="ON",
  207. BUILD_EXAMPLES="OFF",
  208. BUILD_TESTS="OFF",
  209. BUILD_PERF_TESTS="OFF",
  210. BUILD_DOCS="OFF",
  211. BUILD_ANDROID_EXAMPLES=("OFF" if self.no_samples_build else "ON"),
  212. INSTALL_ANDROID_EXAMPLES=("OFF" if self.no_samples_build else "ON"),
  213. )
  214. if self.ninja_path != 'ninja':
  215. cmake_vars['CMAKE_MAKE_PROGRAM'] = self.ninja_path
  216. if self.debug:
  217. cmake_vars['CMAKE_BUILD_TYPE'] = "Debug"
  218. if self.debug_info: # Release with debug info
  219. cmake_vars['BUILD_WITH_DEBUG_INFO'] = "ON"
  220. if self.opencl:
  221. cmake_vars['WITH_OPENCL'] = "ON"
  222. if self.no_kotlin:
  223. cmake_vars['BUILD_KOTLIN_EXTENSIONS'] = "OFF"
  224. if self.shared:
  225. cmake_vars['BUILD_SHARED_LIBS'] = "ON"
  226. if self.config.modules_list is not None:
  227. cmake_vars['BUILD_LIST'] = '%s' % self.config.modules_list
  228. if self.config.extra_modules_path is not None:
  229. cmake_vars['OPENCV_EXTRA_MODULES_PATH'] = '%s' % self.config.extra_modules_path
  230. if self.use_ccache == True:
  231. cmake_vars['NDK_CCACHE'] = 'ccache'
  232. if do_install:
  233. cmake_vars['BUILD_TESTS'] = "ON"
  234. cmake_vars['INSTALL_TESTS'] = "ON"
  235. if no_media_ndk:
  236. cmake_vars['WITH_ANDROID_MEDIANDK'] = "OFF"
  237. if self.hwasan and "arm64" in abi.name:
  238. cmake_vars['OPENCV_ENABLE_MEMORY_SANITIZER'] = "ON"
  239. hwasan_flags = "-fno-omit-frame-pointer -fsanitize=hwaddress"
  240. for s in ['OPENCV_EXTRA_C_FLAGS', 'OPENCV_EXTRA_CXX_FLAGS', 'OPENCV_EXTRA_EXE_LINKER_FLAGS',
  241. 'OPENCV_EXTRA_SHARED_LINKER_FLAGS', 'OPENCV_EXTRA_MODULE_LINKER_FLAGS']:
  242. if s in cmake_vars.keys():
  243. cmake_vars[s] = cmake_vars[s] + ' ' + hwasan_flags
  244. else:
  245. cmake_vars[s] = hwasan_flags
  246. cmake_vars.update(abi.cmake_vars)
  247. if len(self.disable) > 0:
  248. cmake_vars.update({'WITH_%s' % f : "OFF" for f in self.disable})
  249. cmd += [ "-D%s='%s'" % (k, v) for (k, v) in cmake_vars.items() if v is not None]
  250. cmd.append(self.opencvdir)
  251. execute(cmd)
  252. # full parallelism for C++ compilation tasks
  253. build_targets = ["opencv_modules"]
  254. if do_install:
  255. build_targets.append("opencv_tests")
  256. execute([self.ninja_path, *build_targets])
  257. # limit parallelism for building samples (avoid huge memory consumption)
  258. if self.no_samples_build:
  259. execute([self.ninja_path, "install" if (self.debug_info or self.debug) else "install/strip"])
  260. else:
  261. execute([self.ninja_path, "-j1", "install" if (self.debug_info or self.debug) else "install/strip"])
  262. def build_javadoc(self):
  263. classpaths = []
  264. for dir, _, files in os.walk(os.environ["ANDROID_SDK"]):
  265. for f in files:
  266. if f == "android.jar" or f == "annotations.jar":
  267. classpaths.append(os.path.join(dir, f))
  268. srcdir = os.path.join(self.resultdest, 'sdk', 'java', 'src')
  269. dstdir = self.docdest
  270. # HACK: create stubs for auto-generated files to satisfy imports
  271. with open(os.path.join(srcdir, 'org', 'opencv', 'BuildConfig.java'), 'wt') as fs:
  272. fs.write("package org.opencv;\n public class BuildConfig {\n}")
  273. fs.close()
  274. with open(os.path.join(srcdir, 'org', 'opencv', 'R.java'), 'wt') as fs:
  275. fs.write("package org.opencv;\n public class R {\n}")
  276. fs.close()
  277. # synchronize with modules/java/jar/build.xml.in
  278. shutil.copy2(os.path.join(SCRIPT_DIR, '../../doc/mymath.js'), dstdir)
  279. cmd = [
  280. "javadoc",
  281. '-windowtitle', 'OpenCV %s Java documentation' % self.opencv_version,
  282. '-doctitle', 'OpenCV Java documentation (%s)' % self.opencv_version,
  283. "-nodeprecated",
  284. "-public",
  285. '-sourcepath', srcdir,
  286. '-encoding', 'UTF-8',
  287. '-charset', 'UTF-8',
  288. '-docencoding', 'UTF-8',
  289. '--allow-script-in-comments',
  290. '-header',
  291. '''
  292. <script>
  293. var url = window.location.href;
  294. var pos = url.lastIndexOf('/javadoc/');
  295. url = pos >= 0 ? (url.substring(0, pos) + '/javadoc/mymath.js') : (window.location.origin + '/mymath.js');
  296. var script = document.createElement('script');
  297. script.src = '%s/MathJax.js?config=TeX-AMS-MML_HTMLorMML,' + url;
  298. document.getElementsByTagName('head')[0].appendChild(script);
  299. </script>
  300. ''' % 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0',
  301. '-bottom', 'Generated on %s / OpenCV %s' % (time.strftime("%Y-%m-%d %H:%M:%S"), self.opencv_version),
  302. "-d", dstdir,
  303. "-classpath", ":".join(classpaths),
  304. '-subpackages', 'org.opencv'
  305. ]
  306. execute(cmd)
  307. # HACK: remove temporary files needed to satisfy javadoc imports
  308. os.remove(os.path.join(srcdir, 'org', 'opencv', 'BuildConfig.java'))
  309. os.remove(os.path.join(srcdir, 'org', 'opencv', 'R.java'))
  310. def gather_results(self):
  311. # Copy all files
  312. root = os.path.join(self.libdest, "install")
  313. for item in os.listdir(root):
  314. src = os.path.join(root, item)
  315. dst = os.path.join(self.resultdest, item)
  316. if os.path.isdir(src):
  317. log.info("Copy dir: %s", item)
  318. if self.config.force_copy:
  319. copytree_smart(src, dst)
  320. else:
  321. move_smart(src, dst)
  322. elif os.path.isfile(src):
  323. log.info("Copy file: %s", item)
  324. if self.config.force_copy:
  325. shutil.copy2(src, dst)
  326. else:
  327. shutil.move(src, dst)
  328. def get_ndk_dir():
  329. # look to see if Android NDK is installed
  330. android_sdk_ndk = os.path.join(os.environ["ANDROID_SDK"], 'ndk')
  331. android_sdk_ndk_bundle = os.path.join(os.environ["ANDROID_SDK"], 'ndk-bundle')
  332. if os.path.exists(android_sdk_ndk):
  333. ndk_subdirs = [f for f in os.listdir(android_sdk_ndk) if os.path.exists(os.path.join(android_sdk_ndk, f, 'package.xml'))]
  334. if len(ndk_subdirs) > 0:
  335. # there could be more than one - get the most recent
  336. ndk_from_sdk = os.path.join(android_sdk_ndk, get_highest_version(ndk_subdirs))
  337. log.info("Using NDK (side-by-side) from Android SDK: %s", ndk_from_sdk)
  338. return ndk_from_sdk
  339. if os.path.exists(os.path.join(android_sdk_ndk_bundle, 'package.xml')):
  340. log.info("Using NDK bundle from Android SDK: %s", android_sdk_ndk_bundle)
  341. return android_sdk_ndk_bundle
  342. return None
  343. def check_cmake_flag_enabled(cmake_file, flag_name, strict=True):
  344. print(f"Checking build flag '{flag_name}' in: {cmake_file}")
  345. if not os.path.isfile(cmake_file):
  346. msg = f"ERROR: File {cmake_file} does not exist."
  347. if strict:
  348. print(msg)
  349. sys.exit(1)
  350. else:
  351. print("WARNING:", msg)
  352. return
  353. with open(cmake_file, 'r') as file:
  354. for line in file:
  355. if line.strip().startswith(f"{flag_name}="):
  356. value = line.strip().split('=')[1]
  357. if value == '1' or value == 'ON':
  358. print(f"{flag_name}=1 found. Support is enabled.")
  359. return
  360. else:
  361. msg = f"ERROR: {flag_name} is set to {value}, expected 1."
  362. if strict:
  363. print(msg)
  364. sys.exit(1)
  365. else:
  366. print("WARNING:", msg)
  367. return
  368. msg = f"ERROR: {flag_name} not found in {os.path.basename(cmake_file)}."
  369. if strict:
  370. print(msg)
  371. sys.exit(1)
  372. else:
  373. print("WARNING:", msg)
  374. #===================================================================================================
  375. if __name__ == "__main__":
  376. parser = argparse.ArgumentParser(description='Build OpenCV for Android SDK')
  377. parser.add_argument("work_dir", nargs='?', default='.', help="Working directory (and output)")
  378. parser.add_argument("opencv_dir", nargs='?', default=os.path.join(SCRIPT_DIR, '../..'), help="Path to OpenCV source dir")
  379. parser.add_argument('--config', default='ndk-18-api-level-21.config.py', type=str, help="Package build configuration", )
  380. parser.add_argument('--ndk_path', help="Path to Android NDK to use for build")
  381. parser.add_argument('--sdk_path', help="Path to Android SDK to use for build")
  382. parser.add_argument('--use_android_buildtools', action="store_true", help='Use cmake/ninja build tools from Android SDK')
  383. parser.add_argument("--modules_list", help="List of modules to include for build")
  384. parser.add_argument("--extra_modules_path", help="Path to extra modules to use for build")
  385. parser.add_argument('--sign_with', help="Certificate to sign the Manager apk")
  386. parser.add_argument('--build_doc', action="store_true", help="Build javadoc")
  387. parser.add_argument('--no_ccache', action="store_true", help="Do not use ccache during library build")
  388. parser.add_argument('--force_copy', action="store_true", help="Do not use file move during library build (useful for debug)")
  389. parser.add_argument('--force_opencv_toolchain', action="store_true", help="Do not use toolchain from Android NDK")
  390. parser.add_argument('--debug', action="store_true", help="Build 'Debug' binaries (CMAKE_BUILD_TYPE=Debug)")
  391. parser.add_argument('--debug_info', action="store_true", help="Build with debug information (useful for Release mode: BUILD_WITH_DEBUG_INFO=ON)")
  392. parser.add_argument('--no_samples_build', action="store_true", help="Do not build samples (speeds up build)")
  393. parser.add_argument('--opencl', action="store_true", help="Enable OpenCL support")
  394. parser.add_argument('--no_kotlin', action="store_true", help="Disable Kotlin extensions")
  395. parser.add_argument('--shared', action="store_true", help="Build shared libraries")
  396. parser.add_argument('--no_media_ndk', action="store_true", help="Do not link Media NDK (required for video I/O support)")
  397. parser.add_argument('--hwasan', action="store_true", help="Enable Hardware Address Sanitizer on ARM64")
  398. parser.add_argument('--disable', metavar='FEATURE', default=[], action='append', help='OpenCV features to disable (add WITH_*=OFF). To disable multiple, specify this flag again, e.g. "--disable TBB --disable OPENMP"')
  399. parser.add_argument('--no-strict-dependencies',action='store_false',dest='strict_dependencies',help='Disable strict dependency checking (default: strict mode ON)')
  400. args = parser.parse_args()
  401. log.basicConfig(format='%(message)s', level=log.DEBUG)
  402. log.debug("Args: %s", args)
  403. if args.ndk_path is not None:
  404. os.environ["ANDROID_NDK"] = args.ndk_path
  405. if args.sdk_path is not None:
  406. os.environ["ANDROID_SDK"] = args.sdk_path
  407. if not 'ANDROID_HOME' in os.environ and 'ANDROID_SDK' in os.environ:
  408. os.environ['ANDROID_HOME'] = os.environ["ANDROID_SDK"]
  409. if not 'ANDROID_SDK' in os.environ:
  410. raise Fail("SDK location not set. Either pass --sdk_path or set ANDROID_SDK environment variable")
  411. # look for an NDK installed with the Android SDK
  412. if not 'ANDROID_NDK' in os.environ and 'ANDROID_SDK' in os.environ:
  413. sdk_ndk_dir = get_ndk_dir()
  414. if sdk_ndk_dir:
  415. os.environ['ANDROID_NDK'] = sdk_ndk_dir
  416. if not 'ANDROID_NDK' in os.environ:
  417. raise Fail("NDK location not set. Either pass --ndk_path or set ANDROID_NDK environment variable")
  418. show_samples_build_warning = False
  419. #also set ANDROID_NDK_HOME (needed by the gradle build)
  420. if not 'ANDROID_NDK_HOME' in os.environ and 'ANDROID_NDK' in os.environ:
  421. os.environ['ANDROID_NDK_HOME'] = os.environ["ANDROID_NDK"]
  422. show_samples_build_warning = True
  423. if not check_executable(['ccache', '--version']):
  424. log.info("ccache not found - disabling ccache support")
  425. args.no_ccache = True
  426. if os.path.realpath(args.work_dir) == os.path.realpath(SCRIPT_DIR):
  427. raise Fail("Specify workdir (building from script directory is not supported)")
  428. if os.path.realpath(args.work_dir) == os.path.realpath(args.opencv_dir):
  429. raise Fail("Specify workdir (building from OpenCV source directory is not supported)")
  430. # Relative paths become invalid in sub-directories
  431. if args.opencv_dir is not None and not os.path.isabs(args.opencv_dir):
  432. args.opencv_dir = os.path.abspath(args.opencv_dir)
  433. if args.extra_modules_path is not None and not os.path.isabs(args.extra_modules_path):
  434. args.extra_modules_path = os.path.abspath(args.extra_modules_path)
  435. cpath = args.config
  436. if not os.path.exists(cpath):
  437. cpath = os.path.join(SCRIPT_DIR, cpath)
  438. if not os.path.exists(cpath):
  439. raise Fail('Config "%s" is missing' % args.config)
  440. with open(cpath, 'r') as f:
  441. cfg = f.read()
  442. print("Package configuration:")
  443. print('=' * 80)
  444. print(cfg.strip())
  445. print('=' * 80)
  446. ABIs = None # make flake8 happy
  447. exec(compile(cfg, cpath, 'exec'))
  448. log.info("Android NDK path: %s", os.environ["ANDROID_NDK"])
  449. log.info("Android SDK path: %s", os.environ["ANDROID_SDK"])
  450. builder = Builder(args.work_dir, args.opencv_dir, args)
  451. log.info("Detected OpenCV version: %s", builder.opencv_version)
  452. for i, abi in enumerate(ABIs):
  453. do_install = (i == 0)
  454. log.info("=====")
  455. log.info("===== Building library for %s", abi)
  456. log.info("=====")
  457. os.chdir(builder.libdest)
  458. builder.clean_library_build_dir()
  459. builder.build_library(abi, do_install, args.no_media_ndk)
  460. #Check HAVE_IPP x86 / x86_64
  461. if abi.haveIPP():
  462. log.info("Checking HAVE_IPP for ABI: %s", abi.name)
  463. check_cmake_flag_enabled(os.path.join(builder.libdest,"CMakeVars.txt"), "HAVE_IPP", strict=args.strict_dependencies)
  464. #Check HAVE_KLEIDICV for armv8
  465. if abi.haveKleidiCV():
  466. log.info("Checking HAVE_KLEIDICV for ABI: %s", abi.name)
  467. check_cmake_flag_enabled(os.path.join(builder.libdest,"CMakeVars.txt"), "HAVE_KLEIDICV", strict=args.strict_dependencies)
  468. builder.gather_results()
  469. if args.build_doc:
  470. builder.build_javadoc()
  471. log.info("=====")
  472. log.info("===== Build finished")
  473. log.info("=====")
  474. if show_samples_build_warning:
  475. #give a hint how to solve "Gradle sync failed: NDK not configured."
  476. log.info("ANDROID_NDK_HOME environment variable required by the samples project is not set")
  477. log.info("SDK location: %s", builder.resultdest)
  478. log.info("Documentation location: %s", builder.docdest)