build_sdk.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  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. #===================================================================================================
  128. class Builder:
  129. def __init__(self, workdir, opencvdir, config):
  130. self.workdir = check_dir(workdir, create=True)
  131. self.opencvdir = check_dir(opencvdir)
  132. self.config = config
  133. self.libdest = check_dir(os.path.join(self.workdir, "o4a"), create=True, clean=True)
  134. self.resultdest = check_dir(os.path.join(self.workdir, 'OpenCV-android-sdk'), create=True, clean=True)
  135. self.docdest = check_dir(os.path.join(self.workdir, 'OpenCV-android-sdk', 'sdk', 'java', 'javadoc'), create=True, clean=True)
  136. self.extra_packs = []
  137. self.opencv_version = determine_opencv_version(os.path.join(self.opencvdir, "modules", "core", "include", "opencv2", "core", "version.hpp"))
  138. self.use_ccache = False if config.no_ccache else True
  139. self.cmake_path = self.get_cmake()
  140. self.ninja_path = self.get_ninja()
  141. self.debug = True if config.debug else False
  142. self.debug_info = True if config.debug_info else False
  143. self.no_samples_build = True if config.no_samples_build else False
  144. self.opencl = True if config.opencl else False
  145. self.no_kotlin = True if config.no_kotlin else False
  146. def get_cmake(self):
  147. if not self.config.use_android_buildtools and check_executable(['cmake', '--version']):
  148. log.info("Using cmake from PATH")
  149. return 'cmake'
  150. # look to see if Android SDK's cmake is installed
  151. android_cmake = os.path.join(os.environ['ANDROID_SDK'], 'cmake')
  152. if os.path.exists(android_cmake):
  153. cmake_subdirs = [f for f in os.listdir(android_cmake) if check_executable([os.path.join(android_cmake, f, 'bin', 'cmake'), '--version'])]
  154. if len(cmake_subdirs) > 0:
  155. # there could be more than one - get the most recent
  156. cmake_from_sdk = os.path.join(android_cmake, get_highest_version(cmake_subdirs), 'bin', 'cmake')
  157. log.info("Using cmake from Android SDK: %s", cmake_from_sdk)
  158. return cmake_from_sdk
  159. raise Fail("Can't find cmake")
  160. def get_ninja(self):
  161. if not self.config.use_android_buildtools and check_executable(['ninja', '--version']):
  162. log.info("Using ninja from PATH")
  163. return 'ninja'
  164. # Android SDK's cmake includes a copy of ninja - look to see if its there
  165. android_cmake = os.path.join(os.environ['ANDROID_SDK'], 'cmake')
  166. if os.path.exists(android_cmake):
  167. cmake_subdirs = [f for f in os.listdir(android_cmake) if check_executable([os.path.join(android_cmake, f, 'bin', 'ninja'), '--version'])]
  168. if len(cmake_subdirs) > 0:
  169. # there could be more than one - just take the first one
  170. ninja_from_sdk = os.path.join(android_cmake, cmake_subdirs[0], 'bin', 'ninja')
  171. log.info("Using ninja from Android SDK: %s", ninja_from_sdk)
  172. return ninja_from_sdk
  173. raise Fail("Can't find ninja")
  174. def get_toolchain_file(self):
  175. if not self.config.force_opencv_toolchain:
  176. toolchain = os.path.join(os.environ['ANDROID_NDK'], 'build', 'cmake', 'android.toolchain.cmake')
  177. if os.path.exists(toolchain):
  178. return toolchain
  179. toolchain = os.path.join(SCRIPT_DIR, "android.toolchain.cmake")
  180. if os.path.exists(toolchain):
  181. return toolchain
  182. else:
  183. raise Fail("Can't find toolchain")
  184. def get_engine_apk_dest(self, engdest):
  185. return os.path.join(engdest, "platforms", "android", "service", "engine", ".build")
  186. def add_extra_pack(self, ver, path):
  187. if path is None:
  188. return
  189. self.extra_packs.append((ver, check_dir(path)))
  190. def clean_library_build_dir(self):
  191. for d in ["CMakeCache.txt", "CMakeFiles/", "bin/", "libs/", "lib/", "package/", "install/samples/"]:
  192. rm_one(d)
  193. def build_library(self, abi, do_install):
  194. cmd = [self.cmake_path, "-GNinja"]
  195. cmake_vars = dict(
  196. CMAKE_TOOLCHAIN_FILE=self.get_toolchain_file(),
  197. INSTALL_CREATE_DISTRIB="ON",
  198. WITH_OPENCL="OFF",
  199. BUILD_KOTLIN_EXTENSIONS="ON",
  200. WITH_IPP=("ON" if abi.haveIPP() else "OFF"),
  201. WITH_TBB="ON",
  202. BUILD_EXAMPLES="OFF",
  203. BUILD_TESTS="OFF",
  204. BUILD_PERF_TESTS="OFF",
  205. BUILD_DOCS="OFF",
  206. BUILD_ANDROID_EXAMPLES=("OFF" if self.no_samples_build else "ON"),
  207. INSTALL_ANDROID_EXAMPLES=("OFF" if self.no_samples_build else "ON"),
  208. )
  209. if self.ninja_path != 'ninja':
  210. cmake_vars['CMAKE_MAKE_PROGRAM'] = self.ninja_path
  211. if self.debug:
  212. cmake_vars['CMAKE_BUILD_TYPE'] = "Debug"
  213. if self.debug_info: # Release with debug info
  214. cmake_vars['BUILD_WITH_DEBUG_INFO'] = "ON"
  215. if self.opencl:
  216. cmake_vars['WITH_OPENCL'] = "ON"
  217. if self.no_kotlin:
  218. cmake_vars['BUILD_KOTLIN_EXTENSIONS'] = "OFF"
  219. if self.config.modules_list is not None:
  220. cmd.append("-DBUILD_LIST='%s'" % self.config.modules_list)
  221. if self.config.extra_modules_path is not None:
  222. cmd.append("-DOPENCV_EXTRA_MODULES_PATH='%s'" % self.config.extra_modules_path)
  223. if self.use_ccache == True:
  224. cmd.append("-DNDK_CCACHE=ccache")
  225. if do_install:
  226. cmd.extend(["-DBUILD_TESTS=ON", "-DINSTALL_TESTS=ON"])
  227. cmake_vars.update(abi.cmake_vars)
  228. cmd += [ "-D%s='%s'" % (k, v) for (k, v) in cmake_vars.items() if v is not None]
  229. cmd.append(self.opencvdir)
  230. execute(cmd)
  231. # full parallelism for C++ compilation tasks
  232. execute([self.ninja_path, "opencv_modules"])
  233. # limit parallelism for building samples (avoid huge memory consumption)
  234. if self.no_samples_build:
  235. execute([self.ninja_path, "install" if (self.debug_info or self.debug) else "install/strip"])
  236. else:
  237. execute([self.ninja_path, "-j1" if (self.debug_info or self.debug) else "-j3", "install" if (self.debug_info or self.debug) else "install/strip"])
  238. def build_javadoc(self):
  239. classpaths = []
  240. for dir, _, files in os.walk(os.environ["ANDROID_SDK"]):
  241. for f in files:
  242. if f == "android.jar" or f == "annotations.jar":
  243. classpaths.append(os.path.join(dir, f))
  244. srcdir = os.path.join(self.resultdest, 'sdk', 'java', 'src')
  245. dstdir = self.docdest
  246. # synchronize with modules/java/jar/build.xml.in
  247. shutil.copy2(os.path.join(SCRIPT_DIR, '../../doc/mymath.js'), dstdir)
  248. cmd = [
  249. "javadoc",
  250. '-windowtitle', 'OpenCV %s Java documentation' % self.opencv_version,
  251. '-doctitle', 'OpenCV Java documentation (%s)' % self.opencv_version,
  252. "-nodeprecated",
  253. "-public",
  254. '-sourcepath', srcdir,
  255. '-encoding', 'UTF-8',
  256. '-charset', 'UTF-8',
  257. '-docencoding', 'UTF-8',
  258. '--allow-script-in-comments',
  259. '-header',
  260. '''
  261. <script>
  262. var url = window.location.href;
  263. var pos = url.lastIndexOf('/javadoc/');
  264. url = pos >= 0 ? (url.substring(0, pos) + '/javadoc/mymath.js') : (window.location.origin + '/mymath.js');
  265. var script = document.createElement('script');
  266. script.src = '%s/MathJax.js?config=TeX-AMS-MML_HTMLorMML,' + url;
  267. document.getElementsByTagName('head')[0].appendChild(script);
  268. </script>
  269. ''' % 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0',
  270. '-bottom', 'Generated on %s / OpenCV %s' % (time.strftime("%Y-%m-%d %H:%M:%S"), self.opencv_version),
  271. "-d", dstdir,
  272. "-classpath", ":".join(classpaths),
  273. '-subpackages', 'org.opencv',
  274. ]
  275. execute(cmd)
  276. def gather_results(self):
  277. # Copy all files
  278. root = os.path.join(self.libdest, "install")
  279. for item in os.listdir(root):
  280. src = os.path.join(root, item)
  281. dst = os.path.join(self.resultdest, item)
  282. if os.path.isdir(src):
  283. log.info("Copy dir: %s", item)
  284. if self.config.force_copy:
  285. copytree_smart(src, dst)
  286. else:
  287. move_smart(src, dst)
  288. elif os.path.isfile(src):
  289. log.info("Copy file: %s", item)
  290. if self.config.force_copy:
  291. shutil.copy2(src, dst)
  292. else:
  293. shutil.move(src, dst)
  294. def get_ndk_dir():
  295. # look to see if Android NDK is installed
  296. android_sdk_ndk = os.path.join(os.environ["ANDROID_SDK"], 'ndk')
  297. android_sdk_ndk_bundle = os.path.join(os.environ["ANDROID_SDK"], 'ndk-bundle')
  298. if os.path.exists(android_sdk_ndk):
  299. ndk_subdirs = [f for f in os.listdir(android_sdk_ndk) if os.path.exists(os.path.join(android_sdk_ndk, f, 'package.xml'))]
  300. if len(ndk_subdirs) > 0:
  301. # there could be more than one - get the most recent
  302. ndk_from_sdk = os.path.join(android_sdk_ndk, get_highest_version(ndk_subdirs))
  303. log.info("Using NDK (side-by-side) from Android SDK: %s", ndk_from_sdk)
  304. return ndk_from_sdk
  305. if os.path.exists(os.path.join(android_sdk_ndk_bundle, 'package.xml')):
  306. log.info("Using NDK bundle from Android SDK: %s", android_sdk_ndk_bundle)
  307. return android_sdk_ndk_bundle
  308. return None
  309. #===================================================================================================
  310. if __name__ == "__main__":
  311. parser = argparse.ArgumentParser(description='Build OpenCV for Android SDK')
  312. parser.add_argument("work_dir", nargs='?', default='.', help="Working directory (and output)")
  313. parser.add_argument("opencv_dir", nargs='?', default=os.path.join(SCRIPT_DIR, '../..'), help="Path to OpenCV source dir")
  314. parser.add_argument('--config', default='ndk-18-api-level-21.config.py', type=str, help="Package build configuration", )
  315. parser.add_argument('--ndk_path', help="Path to Android NDK to use for build")
  316. parser.add_argument('--sdk_path', help="Path to Android SDK to use for build")
  317. parser.add_argument('--use_android_buildtools', action="store_true", help='Use cmake/ninja build tools from Android SDK')
  318. parser.add_argument("--modules_list", help="List of modules to include for build")
  319. parser.add_argument("--extra_modules_path", help="Path to extra modules to use for build")
  320. parser.add_argument('--sign_with', help="Certificate to sign the Manager apk")
  321. parser.add_argument('--build_doc', action="store_true", help="Build javadoc")
  322. parser.add_argument('--no_ccache', action="store_true", help="Do not use ccache during library build")
  323. parser.add_argument('--force_copy', action="store_true", help="Do not use file move during library build (useful for debug)")
  324. parser.add_argument('--force_opencv_toolchain', action="store_true", help="Do not use toolchain from Android NDK")
  325. parser.add_argument('--debug', action="store_true", help="Build 'Debug' binaries (CMAKE_BUILD_TYPE=Debug)")
  326. parser.add_argument('--debug_info', action="store_true", help="Build with debug information (useful for Release mode: BUILD_WITH_DEBUG_INFO=ON)")
  327. parser.add_argument('--no_samples_build', action="store_true", help="Do not build samples (speeds up build)")
  328. parser.add_argument('--opencl', action="store_true", help="Enable OpenCL support")
  329. parser.add_argument('--no_kotlin', action="store_true", help="Disable Kotlin extensions")
  330. args = parser.parse_args()
  331. log.basicConfig(format='%(message)s', level=log.DEBUG)
  332. log.debug("Args: %s", args)
  333. if args.ndk_path is not None:
  334. os.environ["ANDROID_NDK"] = args.ndk_path
  335. if args.sdk_path is not None:
  336. os.environ["ANDROID_SDK"] = args.sdk_path
  337. if not 'ANDROID_HOME' in os.environ and 'ANDROID_SDK' in os.environ:
  338. os.environ['ANDROID_HOME'] = os.environ["ANDROID_SDK"]
  339. if not 'ANDROID_SDK' in os.environ:
  340. raise Fail("SDK location not set. Either pass --sdk_path or set ANDROID_SDK environment variable")
  341. # look for an NDK installed with the Android SDK
  342. if not 'ANDROID_NDK' in os.environ and 'ANDROID_SDK' in os.environ:
  343. sdk_ndk_dir = get_ndk_dir()
  344. if sdk_ndk_dir:
  345. os.environ['ANDROID_NDK'] = sdk_ndk_dir
  346. if not 'ANDROID_NDK' in os.environ:
  347. raise Fail("NDK location not set. Either pass --ndk_path or set ANDROID_NDK environment variable")
  348. show_samples_build_warning = False
  349. #also set ANDROID_NDK_HOME (needed by the gradle build)
  350. if not 'ANDROID_NDK_HOME' in os.environ and 'ANDROID_NDK' in os.environ:
  351. os.environ['ANDROID_NDK_HOME'] = os.environ["ANDROID_NDK"]
  352. show_samples_build_warning = True
  353. if not check_executable(['ccache', '--version']):
  354. log.info("ccache not found - disabling ccache support")
  355. args.no_ccache = True
  356. if os.path.realpath(args.work_dir) == os.path.realpath(SCRIPT_DIR):
  357. raise Fail("Specify workdir (building from script directory is not supported)")
  358. if os.path.realpath(args.work_dir) == os.path.realpath(args.opencv_dir):
  359. raise Fail("Specify workdir (building from OpenCV source directory is not supported)")
  360. # Relative paths become invalid in sub-directories
  361. if args.opencv_dir is not None and not os.path.isabs(args.opencv_dir):
  362. args.opencv_dir = os.path.abspath(args.opencv_dir)
  363. if args.extra_modules_path is not None and not os.path.isabs(args.extra_modules_path):
  364. args.extra_modules_path = os.path.abspath(args.extra_modules_path)
  365. cpath = args.config
  366. if not os.path.exists(cpath):
  367. cpath = os.path.join(SCRIPT_DIR, cpath)
  368. if not os.path.exists(cpath):
  369. raise Fail('Config "%s" is missing' % args.config)
  370. with open(cpath, 'r') as f:
  371. cfg = f.read()
  372. print("Package configuration:")
  373. print('=' * 80)
  374. print(cfg.strip())
  375. print('=' * 80)
  376. ABIs = None # make flake8 happy
  377. exec(compile(cfg, cpath, 'exec'))
  378. log.info("Android NDK path: %s", os.environ["ANDROID_NDK"])
  379. log.info("Android SDK path: %s", os.environ["ANDROID_SDK"])
  380. builder = Builder(args.work_dir, args.opencv_dir, args)
  381. log.info("Detected OpenCV version: %s", builder.opencv_version)
  382. for i, abi in enumerate(ABIs):
  383. do_install = (i == 0)
  384. log.info("=====")
  385. log.info("===== Building library for %s", abi)
  386. log.info("=====")
  387. os.chdir(builder.libdest)
  388. builder.clean_library_build_dir()
  389. builder.build_library(abi, do_install)
  390. builder.gather_results()
  391. if args.build_doc:
  392. builder.build_javadoc()
  393. log.info("=====")
  394. log.info("===== Build finished")
  395. log.info("=====")
  396. if show_samples_build_warning:
  397. #give a hint how to solve "Gradle sync failed: NDK not configured."
  398. log.info("ANDROID_NDK_HOME environment variable required by the samples project is not set")
  399. log.info("SDK location: %s", builder.resultdest)
  400. log.info("Documentation location: %s", builder.docdest)