build_framework.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611
  1. #!/usr/bin/env python
  2. """
  3. The script builds OpenCV.framework for iOS.
  4. The built framework is universal, it can be used to build app and run it on either iOS simulator or real device.
  5. Usage:
  6. ./build_framework.py <outputdir>
  7. By cmake conventions (and especially if you work with OpenCV repository),
  8. the output dir should not be a subdirectory of OpenCV source tree.
  9. Script will create <outputdir>, if it's missing, and a few its subdirectories:
  10. <outputdir>
  11. build/
  12. iPhoneOS-*/
  13. [cmake-generated build tree for an iOS device target]
  14. iPhoneSimulator-*/
  15. [cmake-generated build tree for iOS simulator]
  16. {framework_name}.framework/
  17. [the framework content]
  18. samples/
  19. [sample projects]
  20. docs/
  21. [documentation]
  22. The script should handle minor OpenCV updates efficiently
  23. - it does not recompile the library from scratch each time.
  24. However, {framework_name}.framework directory is erased and recreated on each run.
  25. Adding --dynamic parameter will build {framework_name}.framework as App Store dynamic framework. Only iOS 8+ versions are supported.
  26. """
  27. from __future__ import print_function, unicode_literals
  28. import glob, os, os.path, shutil, string, sys, argparse, traceback, multiprocessing, codecs, io
  29. from subprocess import check_call, check_output, CalledProcessError
  30. if sys.version_info >= (3, 8): # Python 3.8+
  31. def copy_tree(src, dst):
  32. shutil.copytree(src, dst, dirs_exist_ok=True)
  33. else:
  34. from distutils.dir_util import copy_tree
  35. sys.path.insert(0, os.path.abspath(os.path.abspath(os.path.dirname(__file__))+'/../apple'))
  36. from cv_build_utils import execute, print_error, get_xcode_major, get_xcode_setting, get_xcode_version, get_cmake_version
  37. IPHONEOS_DEPLOYMENT_TARGET='9.0' # default, can be changed via command line options or environment variable
  38. CURRENT_FILE_DIR = os.path.dirname(__file__)
  39. class Builder:
  40. def __init__(self, opencv, contrib, dynamic, embed_bitcode, exclude, disable, enablenonfree, targets, debug, debug_info, framework_name, run_tests, build_docs, swiftdisabled):
  41. self.opencv = os.path.abspath(opencv)
  42. self.contrib = None
  43. if contrib:
  44. modpath = os.path.join(contrib, "modules")
  45. if os.path.isdir(modpath):
  46. self.contrib = os.path.abspath(modpath)
  47. else:
  48. print("Note: contrib repository is bad - modules subfolder not found", file=sys.stderr)
  49. self.dynamic = dynamic
  50. self.embed_bitcode = embed_bitcode
  51. self.exclude = exclude
  52. self.build_objc_wrapper = not "objc" in self.exclude
  53. self.disable = disable
  54. self.enablenonfree = enablenonfree
  55. self.targets = targets
  56. self.debug = debug
  57. self.debug_info = debug_info
  58. self.framework_name = framework_name
  59. self.run_tests = run_tests
  60. self.build_docs = build_docs
  61. self.swiftdisabled = swiftdisabled
  62. def checkCMakeVersion(self):
  63. if get_xcode_version() >= (12, 2):
  64. assert get_cmake_version() >= (3, 19), "CMake 3.19 or later is required when building with Xcode 12.2 or greater. Current version is {}".format(get_cmake_version())
  65. else:
  66. assert get_cmake_version() >= (3, 17), "CMake 3.17 or later is required. Current version is {}".format(get_cmake_version())
  67. def getBuildDir(self, parent, target):
  68. res = os.path.join(parent, 'build-%s-%s' % (target[0].lower(), target[1].lower()))
  69. if not os.path.isdir(res):
  70. os.makedirs(res)
  71. return os.path.abspath(res)
  72. def _build(self, outdir):
  73. self.checkCMakeVersion()
  74. outdir = os.path.abspath(outdir)
  75. if not os.path.isdir(outdir):
  76. os.makedirs(outdir)
  77. main_working_dir = os.path.join(outdir, "build")
  78. dirs = []
  79. xcode_ver = get_xcode_major()
  80. # build each architecture separately
  81. alltargets = []
  82. for target_group in self.targets:
  83. for arch in target_group[0]:
  84. current = ( arch, target_group[1] )
  85. alltargets.append(current)
  86. for target in alltargets:
  87. main_build_dir = self.getBuildDir(main_working_dir, target)
  88. dirs.append(main_build_dir)
  89. cmake_flags = []
  90. if self.contrib:
  91. cmake_flags.append("-DOPENCV_EXTRA_MODULES_PATH=%s" % self.contrib)
  92. if xcode_ver >= 7 and target[1] == 'iPhoneOS' and self.embed_bitcode:
  93. cmake_flags.append("-DCMAKE_C_FLAGS=-fembed-bitcode")
  94. cmake_flags.append("-DCMAKE_CXX_FLAGS=-fembed-bitcode")
  95. if xcode_ver >= 7 and target[1] == 'Catalyst':
  96. sdk_path = check_output(["xcodebuild", "-version", "-sdk", "macosx", "Path"]).decode('utf-8').rstrip()
  97. c_flags = [
  98. "-target %s-apple-ios14.0-macabi" % target[0], # e.g. x86_64-apple-ios13.2-macabi # -mmacosx-version-min=10.15
  99. "-isysroot %s" % sdk_path,
  100. "-iframework %s/System/iOSSupport/System/Library/Frameworks" % sdk_path,
  101. "-isystem %s/System/iOSSupport/usr/include" % sdk_path,
  102. ]
  103. if self.embed_bitcode:
  104. c_flags.append("-fembed-bitcode")
  105. cmake_flags.append("-DCMAKE_C_FLAGS=" + " ".join(c_flags))
  106. cmake_flags.append("-DCMAKE_CXX_FLAGS=" + " ".join(c_flags))
  107. cmake_flags.append("-DCMAKE_EXE_LINKER_FLAGS=" + " ".join(c_flags))
  108. # CMake cannot compile Swift for Catalyst https://gitlab.kitware.com/cmake/cmake/-/issues/21436
  109. # cmake_flags.append("-DCMAKE_Swift_FLAGS=" + " " + target_flag)
  110. cmake_flags.append("-DSWIFT_DISABLED=1")
  111. cmake_flags.append("-DIOS=1") # Build the iOS codebase
  112. cmake_flags.append("-DMAC_CATALYST=1") # Set a flag for Mac Catalyst, just in case we need it
  113. cmake_flags.append("-DWITH_OPENCL=OFF") # Disable OpenCL; it isn't compatible with iOS
  114. cmake_flags.append("-DCMAKE_OSX_SYSROOT=%s" % sdk_path)
  115. cmake_flags.append("-DCMAKE_CXX_COMPILER_WORKS=TRUE")
  116. cmake_flags.append("-DCMAKE_C_COMPILER_WORKS=TRUE")
  117. print("::group::Building target", target[0], target[1], flush=True)
  118. self.buildOne(target[0], target[1], main_build_dir, cmake_flags)
  119. print("::endgroup::", flush=True)
  120. if not self.dynamic:
  121. print("::group::Merge libs", target[0], target[1], flush=True)
  122. self.mergeLibs(main_build_dir)
  123. print("::endgroup::", flush=True)
  124. else:
  125. print("::group::Make dynamic lib", target[0], target[1], flush=True)
  126. self.makeDynamicLib(main_build_dir)
  127. print("::endgroup::", flush=True)
  128. self.makeFramework(outdir, dirs)
  129. if self.build_objc_wrapper:
  130. if self.run_tests:
  131. check_call([sys.argv[0].replace("build_framework", "run_tests"), "--framework_dir=" + outdir, "--framework_name=" + self.framework_name, dirs[0] + "/modules/objc_bindings_generator/{}/test".format(self.getObjcTarget(target[1]))])
  132. else:
  133. print("To run tests call:")
  134. print(sys.argv[0].replace("build_framework", "run_tests") + " --framework_dir=" + outdir + " --framework_name=" + self.framework_name + " " + dirs[0] + "/modules/objc_bindings_generator/{}/test".format(self.getObjcTarget(target[1])))
  135. if self.build_docs:
  136. check_call([sys.argv[0].replace("build_framework", "build_docs"), dirs[0] + "/modules/objc/framework_build"])
  137. doc_path = os.path.join(dirs[0], "modules", "objc", "doc_build", "docs")
  138. if os.path.exists(doc_path):
  139. shutil.copytree(doc_path, os.path.join(outdir, "docs"))
  140. shutil.copyfile(os.path.join(self.opencv, "doc", "opencv.ico"), os.path.join(outdir, "docs", "favicon.ico"))
  141. else:
  142. print("To build docs call:")
  143. print(sys.argv[0].replace("build_framework", "build_docs") + " " + dirs[0] + "/modules/objc/framework_build")
  144. self.copy_samples(outdir)
  145. if self.swiftdisabled:
  146. swift_sources_dir = os.path.join(outdir, "SwiftSources")
  147. if not os.path.exists(swift_sources_dir):
  148. os.makedirs(swift_sources_dir)
  149. for root, dirs, files in os.walk(dirs[0]):
  150. for file in files:
  151. if file.endswith(".swift") and file.find("Test") == -1:
  152. with io.open(os.path.join(root, file), encoding="utf-8", errors="ignore") as file_in:
  153. body = file_in.read()
  154. if body.find("import Foundation") != -1:
  155. insert_pos = body.find("import Foundation") + len("import Foundation") + 1
  156. body = body[:insert_pos] + "import " + self.framework_name + "\n" + body[insert_pos:]
  157. else:
  158. body = "import " + self.framework_name + "\n\n" + body
  159. with codecs.open(os.path.join(swift_sources_dir, file), "w", "utf-8") as file_out:
  160. file_out.write(body)
  161. def build(self, outdir):
  162. try:
  163. self._build(outdir)
  164. except Exception as e:
  165. print_error(e)
  166. traceback.print_exc(file=sys.stderr)
  167. sys.exit(1)
  168. def getToolchain(self, arch, target):
  169. return None
  170. def getConfiguration(self):
  171. return "Debug" if self.debug else "Release"
  172. def getCMakeArgs(self, arch, target):
  173. args = [
  174. "cmake",
  175. "-GXcode",
  176. "-DAPPLE_FRAMEWORK=ON",
  177. "-DCMAKE_INSTALL_PREFIX=install",
  178. "-DCMAKE_BUILD_TYPE=%s" % self.getConfiguration(),
  179. "-DOPENCV_INCLUDE_INSTALL_PATH=include",
  180. "-DOPENCV_3P_LIB_INSTALL_PATH=lib/3rdparty",
  181. "-DFRAMEWORK_NAME=%s" % self.framework_name,
  182. ]
  183. if self.dynamic:
  184. args += [
  185. "-DDYNAMIC_PLIST=ON"
  186. ]
  187. if self.enablenonfree:
  188. args += [
  189. "-DOPENCV_ENABLE_NONFREE=ON"
  190. ]
  191. if self.debug_info:
  192. args += [
  193. "-DBUILD_WITH_DEBUG_INFO=ON"
  194. ]
  195. if len(self.exclude) > 0:
  196. args += ["-DBUILD_opencv_%s=OFF" % m for m in self.exclude]
  197. if len(self.disable) > 0:
  198. args += ["-DWITH_%s=OFF" % f for f in self.disable]
  199. return args
  200. def getBuildCommand(self, arch, target):
  201. buildcmd = [
  202. "xcodebuild",
  203. ]
  204. if (self.dynamic or self.build_objc_wrapper) and self.embed_bitcode and target == "iPhoneOS":
  205. buildcmd.append("BITCODE_GENERATION_MODE=bitcode")
  206. buildcmd += [
  207. "IPHONEOS_DEPLOYMENT_TARGET=" + os.environ['IPHONEOS_DEPLOYMENT_TARGET'],
  208. "ARCHS=%s" % arch,
  209. "-sdk", target.lower(),
  210. "-configuration", self.getConfiguration(),
  211. "-parallelizeTargets",
  212. "-jobs", str(multiprocessing.cpu_count()),
  213. ]
  214. return buildcmd
  215. def getInfoPlist(self, builddirs):
  216. return os.path.join(builddirs[0], "ios", "Info.plist")
  217. def getObjcTarget(self, target):
  218. # Obj-C generation target
  219. return 'ios'
  220. def makeCMakeCmd(self, arch, target, dir, cmakeargs = []):
  221. toolchain = self.getToolchain(arch, target)
  222. cmakecmd = self.getCMakeArgs(arch, target) + \
  223. (["-DCMAKE_TOOLCHAIN_FILE=%s" % toolchain] if toolchain is not None else [])
  224. if target.lower().startswith("iphoneos") or target.lower().startswith("xros"):
  225. cmakecmd.append("-DCPU_BASELINE=DETECT")
  226. if target.lower().startswith("iphonesimulator") or target.lower().startswith("xrsimulator"):
  227. build_arch = check_output(["uname", "-m"]).decode('utf-8').rstrip()
  228. if build_arch != arch:
  229. print("build_arch (%s) != arch (%s)" % (build_arch, arch))
  230. cmakecmd.append("-DCMAKE_SYSTEM_PROCESSOR=" + arch)
  231. cmakecmd.append("-DCMAKE_OSX_ARCHITECTURES=" + arch)
  232. cmakecmd.append("-DCPU_BASELINE=DETECT")
  233. cmakecmd.append("-DCMAKE_CROSSCOMPILING=ON")
  234. cmakecmd.append("-DOPENCV_WORKAROUND_CMAKE_20989=ON")
  235. if target.lower() == "catalyst":
  236. build_arch = check_output(["uname", "-m"]).decode('utf-8').rstrip()
  237. if build_arch != arch:
  238. print("build_arch (%s) != arch (%s)" % (build_arch, arch))
  239. cmakecmd.append("-DCMAKE_SYSTEM_PROCESSOR=" + arch)
  240. cmakecmd.append("-DCMAKE_OSX_ARCHITECTURES=" + arch)
  241. cmakecmd.append("-DCPU_BASELINE=DETECT")
  242. cmakecmd.append("-DCMAKE_CROSSCOMPILING=ON")
  243. cmakecmd.append("-DOPENCV_WORKAROUND_CMAKE_20989=ON")
  244. if target.lower() == "macosx":
  245. build_arch = check_output(["uname", "-m"]).decode('utf-8').rstrip()
  246. if build_arch != arch:
  247. print("build_arch (%s) != arch (%s)" % (build_arch, arch))
  248. cmakecmd.append("-DCMAKE_SYSTEM_PROCESSOR=" + arch)
  249. cmakecmd.append("-DCMAKE_OSX_ARCHITECTURES=" + arch)
  250. cmakecmd.append("-DCPU_BASELINE=DETECT")
  251. cmakecmd.append("-DCMAKE_CROSSCOMPILING=ON")
  252. cmakecmd.append("-DOPENCV_WORKAROUND_CMAKE_20989=ON")
  253. cmakecmd.append(dir)
  254. cmakecmd.extend(cmakeargs)
  255. return cmakecmd
  256. def buildOne(self, arch, target, builddir, cmakeargs = []):
  257. # Run cmake
  258. #toolchain = self.getToolchain(arch, target)
  259. #cmakecmd = self.getCMakeArgs(arch, target) + \
  260. # (["-DCMAKE_TOOLCHAIN_FILE=%s" % toolchain] if toolchain is not None else [])
  261. #if target.lower().startswith("iphoneos"):
  262. # cmakecmd.append("-DCPU_BASELINE=DETECT")
  263. #cmakecmd.append(self.opencv)
  264. #cmakecmd.extend(cmakeargs)
  265. cmakecmd = self.makeCMakeCmd(arch, target, self.opencv, cmakeargs)
  266. print("")
  267. print("=================================")
  268. print("CMake")
  269. print("=================================")
  270. print("")
  271. execute(cmakecmd, cwd = builddir)
  272. print("")
  273. print("=================================")
  274. print("Xcodebuild")
  275. print("=================================")
  276. print("")
  277. # Clean and build
  278. clean_dir = os.path.join(builddir, "install")
  279. if os.path.isdir(clean_dir):
  280. shutil.rmtree(clean_dir)
  281. buildcmd = self.getBuildCommand(arch, target)
  282. execute(buildcmd + ["-target", "ALL_BUILD", "build"], cwd = builddir)
  283. execute(["cmake", "-DBUILD_TYPE=%s" % self.getConfiguration(), "-P", "cmake_install.cmake"], cwd = builddir)
  284. if self.build_objc_wrapper:
  285. cmakecmd = self.makeCMakeCmd(arch, target, builddir + "/modules/objc_bindings_generator/{}/gen".format(self.getObjcTarget(target)), cmakeargs)
  286. if self.swiftdisabled:
  287. cmakecmd.append("-DSWIFT_DISABLED=1")
  288. cmakecmd.append("-DBUILD_ROOT=%s" % builddir)
  289. cmakecmd.append("-DCMAKE_INSTALL_NAME_TOOL=install_name_tool")
  290. cmakecmd.append("--no-warn-unused-cli")
  291. execute(cmakecmd, cwd = builddir + "/modules/objc/framework_build")
  292. execute(buildcmd + ["-target", "ALL_BUILD", "build"], cwd = builddir + "/modules/objc/framework_build")
  293. execute(["cmake", "-DBUILD_TYPE=%s" % self.getConfiguration(), "-DCMAKE_INSTALL_PREFIX=%s" % (builddir + "/install"), "-P", "cmake_install.cmake"], cwd = builddir + "/modules/objc/framework_build")
  294. def mergeLibs(self, builddir):
  295. res = os.path.join(builddir, "lib", self.getConfiguration(), "libopencv_merged.a")
  296. libs = glob.glob(os.path.join(builddir, "install", "lib", "*.a"))
  297. module = [os.path.join(builddir, "install", "lib", self.framework_name + ".framework", self.framework_name)] if self.build_objc_wrapper else []
  298. libs3 = glob.glob(os.path.join(builddir, "install", "lib", "3rdparty", "*.a"))
  299. print("Merging libraries:\n\t%s" % "\n\t".join(libs + libs3 + module), file=sys.stderr)
  300. execute(["libtool", "-static", "-o", res] + libs + libs3 + module)
  301. def makeDynamicLib(self, builddir):
  302. target = builddir[(builddir.rfind("build-") + 6):]
  303. target_platform = target[(target.rfind("-") + 1):]
  304. is_device = target_platform == "iphoneos" or target_platform == "visionos" or target_platform == "catalyst"
  305. framework_dir = os.path.join(builddir, "install", "lib", self.framework_name + ".framework")
  306. if not os.path.exists(framework_dir):
  307. os.makedirs(framework_dir)
  308. res = os.path.join(framework_dir, self.framework_name)
  309. libs = glob.glob(os.path.join(builddir, "install", "lib", "*.a"))
  310. if self.build_objc_wrapper:
  311. module = [os.path.join(builddir, "lib", self.getConfiguration(), self.framework_name + ".framework", self.framework_name)]
  312. else:
  313. module = []
  314. libs3 = glob.glob(os.path.join(builddir, "install", "lib", "3rdparty", "*.a"))
  315. if os.environ.get('IPHONEOS_DEPLOYMENT_TARGET'):
  316. link_target = target[:target.find("-")] + "-apple-ios" + os.environ['IPHONEOS_DEPLOYMENT_TARGET'] + ("-simulator" if target.endswith("simulator") else "")
  317. else:
  318. if target_platform == "catalyst":
  319. link_target = "%s-apple-ios14.0-macabi" % target[:target.find("-")]
  320. else:
  321. link_target = "%s-apple-darwin" % target[:target.find("-")]
  322. bitcode_flags = ["-fembed-bitcode", "-Xlinker", "-bitcode_verify"] if is_device and self.embed_bitcode else []
  323. toolchain_dir = get_xcode_setting("TOOLCHAIN_DIR", builddir)
  324. sdk_dir = get_xcode_setting("SDK_DIR", builddir)
  325. framework_options = []
  326. swift_link_dirs = ["-L" + toolchain_dir + "/usr/lib/swift/" + target_platform, "-L/usr/lib/swift"]
  327. if target_platform == "catalyst":
  328. swift_link_dirs = ["-L" + toolchain_dir + "/usr/lib/swift/" + "maccatalyst", "-L/usr/lib/swift"]
  329. framework_options = [
  330. "-iframework", "%s/System/iOSSupport/System/Library/Frameworks" % sdk_dir,
  331. "-framework", "AVFoundation", "-framework", "UIKit", "-framework", "CoreGraphics",
  332. "-framework", "CoreImage", "-framework", "CoreMedia", "-framework", "QuartzCore",
  333. ]
  334. elif target_platform == "macosx":
  335. framework_options = [
  336. "-framework", "AVFoundation", "-framework", "AppKit", "-framework", "CoreGraphics",
  337. "-framework", "CoreImage", "-framework", "CoreMedia", "-framework", "QuartzCore",
  338. "-framework", "Accelerate", "-framework", "OpenCL",
  339. ]
  340. elif target_platform == "iphoneos" or target_platform == "iphonesimulator" or target_platform == "xros" or target_platform == "xrsimulator":
  341. framework_options = [
  342. "-iframework", "%s/System/iOSSupport/System/Library/Frameworks" % sdk_dir,
  343. "-framework", "AVFoundation", "-framework", "CoreGraphics",
  344. "-framework", "CoreImage", "-framework", "CoreMedia", "-framework", "QuartzCore",
  345. "-framework", "Accelerate", "-framework", "UIKit", "-framework", "CoreVideo",
  346. ]
  347. execute([
  348. "clang++",
  349. "-Xlinker", "-rpath",
  350. "-Xlinker", "/usr/lib/swift",
  351. "-target", link_target,
  352. "-isysroot", sdk_dir,] +
  353. framework_options + [
  354. "-install_name", "@rpath/" + self.framework_name + ".framework/" + self.framework_name,
  355. "-dynamiclib", "-dead_strip", "-fobjc-link-runtime", "-all_load",
  356. "-o", res
  357. ] + swift_link_dirs + bitcode_flags + module + libs + libs3)
  358. def makeFramework(self, outdir, builddirs):
  359. name = self.framework_name
  360. # set the current dir to the dst root
  361. framework_dir = os.path.join(outdir, "%s.framework" % name)
  362. if os.path.isdir(framework_dir):
  363. shutil.rmtree(framework_dir)
  364. os.makedirs(framework_dir)
  365. if self.dynamic:
  366. dstdir = framework_dir
  367. else:
  368. dstdir = os.path.join(framework_dir, "Versions", "A")
  369. # copy headers from one of build folders
  370. shutil.copytree(os.path.join(builddirs[0], "install", "include", "opencv2"), os.path.join(dstdir, "Headers"))
  371. if name != "opencv2":
  372. for dirname, dirs, files in os.walk(os.path.join(dstdir, "Headers")):
  373. for filename in files:
  374. filepath = os.path.join(dirname, filename)
  375. with codecs.open(filepath, "r", "utf-8") as file:
  376. body = file.read()
  377. body = body.replace("include \"opencv2/", "include \"" + name + "/")
  378. body = body.replace("include <opencv2/", "include <" + name + "/")
  379. with codecs.open(filepath, "w", "utf-8") as file:
  380. file.write(body)
  381. if self.build_objc_wrapper:
  382. copy_tree(os.path.join(builddirs[0], "install", "lib", name + ".framework", "Headers"), os.path.join(dstdir, "Headers"))
  383. platform_name_map = {
  384. "arm": "armv7-apple-ios",
  385. "arm64": "arm64-apple-ios",
  386. "i386": "i386-apple-ios-simulator",
  387. "x86_64": "x86_64-apple-ios-simulator",
  388. } if builddirs[0].find("iphone") != -1 else {
  389. "x86_64": "x86_64-apple-macos",
  390. "arm64": "arm64-apple-macos",
  391. }
  392. for d in builddirs:
  393. copy_tree(os.path.join(d, "install", "lib", name + ".framework", "Modules"), os.path.join(dstdir, "Modules"))
  394. for dirname, dirs, files in os.walk(os.path.join(dstdir, "Modules")):
  395. for filename in files:
  396. filestem = os.path.splitext(filename)[0]
  397. fileext = os.path.splitext(filename)[1]
  398. if filestem in platform_name_map:
  399. os.rename(os.path.join(dirname, filename), os.path.join(dirname, platform_name_map[filestem] + fileext))
  400. # make universal static lib
  401. if self.dynamic:
  402. libs = [os.path.join(d, "install", "lib", name + ".framework", name) for d in builddirs]
  403. else:
  404. libs = [os.path.join(d, "lib", self.getConfiguration(), "libopencv_merged.a") for d in builddirs]
  405. lipocmd = ["lipo", "-create"]
  406. lipocmd.extend(libs)
  407. lipocmd.extend(["-o", os.path.join(dstdir, name)])
  408. print("Creating universal library from:\n\t%s" % "\n\t".join(libs), file=sys.stderr)
  409. execute(lipocmd)
  410. # dynamic framework has different structure, just copy the Plist directly
  411. if self.dynamic:
  412. resdir = dstdir
  413. shutil.copyfile(self.getInfoPlist(builddirs), os.path.join(resdir, "Info.plist"))
  414. else:
  415. # copy Info.plist
  416. resdir = os.path.join(dstdir, "Resources")
  417. os.makedirs(resdir)
  418. shutil.copyfile(self.getInfoPlist(builddirs), os.path.join(resdir, "Info.plist"))
  419. # make symbolic links
  420. links = [
  421. (["A"], ["Versions", "Current"]),
  422. (["Versions", "Current", "Headers"], ["Headers"]),
  423. (["Versions", "Current", "Resources"], ["Resources"]),
  424. (["Versions", "Current", "Modules"], ["Modules"]),
  425. (["Versions", "Current", name], [name])
  426. ]
  427. for l in links:
  428. s = os.path.join(*l[0])
  429. d = os.path.join(framework_dir, *l[1])
  430. os.symlink(s, d)
  431. # Copy Apple privacy manifest
  432. shutil.copyfile(os.path.join(CURRENT_FILE_DIR, "PrivacyInfo.xcprivacy"),
  433. os.path.join(resdir, "PrivacyInfo.xcprivacy"))
  434. def copy_samples(self, outdir):
  435. return
  436. class iOSBuilder(Builder):
  437. def getToolchain(self, arch, target):
  438. toolchain = os.path.join(self.opencv, "platforms", "ios", "cmake", "Toolchains", "Toolchain-%s_Xcode.cmake" % target)
  439. return toolchain
  440. def getCMakeArgs(self, arch, target):
  441. args = Builder.getCMakeArgs(self, arch, target)
  442. args = args + [
  443. '-DIOS_ARCH=%s' % arch
  444. ]
  445. return args
  446. def copy_samples(self, outdir):
  447. print('Copying samples to: ' + outdir)
  448. samples_dir = os.path.join(outdir, "samples")
  449. if os.path.exists(samples_dir):
  450. shutil.rmtree(samples_dir)
  451. shutil.copytree(os.path.join(self.opencv, "samples", "swift", "ios"), samples_dir)
  452. if self.framework_name != "OpenCV":
  453. for dirname, dirs, files in os.walk(samples_dir):
  454. for filename in files:
  455. if not filename.endswith((".h", ".swift", ".pbxproj")):
  456. continue
  457. filepath = os.path.join(dirname, filename)
  458. with open(filepath) as file:
  459. body = file.read()
  460. body = body.replace("import OpenCV", "import " + self.framework_name)
  461. body = body.replace("#import <OpenCV/OpenCV.h>", "#import <" + self.framework_name + "/" + self.framework_name + ".h>")
  462. body = body.replace("OpenCV.framework", self.framework_name + ".framework")
  463. body = body.replace("../../OpenCV/**", "../../" + self.framework_name + "/**")
  464. with open(filepath, "w") as file:
  465. file.write(body)
  466. if __name__ == "__main__":
  467. folder = os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]), "../.."))
  468. parser = argparse.ArgumentParser(description='The script builds OpenCV.framework for iOS.')
  469. # TODO: When we can make breaking changes, we should make the out argument explicit and required like in build_xcframework.py.
  470. parser.add_argument('out', metavar='OUTDIR', help='folder to put built framework')
  471. parser.add_argument('--opencv', metavar='DIR', default=folder, help='folder with opencv repository (default is "../.." relative to script location)')
  472. parser.add_argument('--contrib', metavar='DIR', default=None, help='folder with opencv_contrib repository (default is "None" - build only main framework)')
  473. parser.add_argument('--without', metavar='MODULE', default=[], action='append', help='OpenCV modules to exclude from the framework. To exclude multiple, specify this flag again, e.g. "--without video --without objc"')
  474. 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"')
  475. parser.add_argument('--dynamic', default=False, action='store_true', help='build dynamic framework (default is "False" - builds static framework)')
  476. parser.add_argument('--embed_bitcode', default=False, dest='embed_bitcode', action='store_true', help='disable bitcode (enabled by default)')
  477. parser.add_argument('--iphoneos_deployment_target', default=os.environ.get('IPHONEOS_DEPLOYMENT_TARGET', IPHONEOS_DEPLOYMENT_TARGET), help='specify IPHONEOS_DEPLOYMENT_TARGET')
  478. parser.add_argument('--build_only_specified_archs', default=False, action='store_true', help='if enabled, only directly specified archs are built and defaults are ignored')
  479. parser.add_argument('--iphoneos_archs', default=None, help='select iPhoneOS target ARCHS. Default is "armv7,armv7s,arm64"')
  480. parser.add_argument('--iphonesimulator_archs', default=None, help='select iPhoneSimulator target ARCHS. Default is "i386,x86_64"')
  481. parser.add_argument('--enable_nonfree', default=False, dest='enablenonfree', action='store_true', help='enable non-free modules (disabled by default)')
  482. parser.add_argument('--debug', default=False, dest='debug', action='store_true', help='Build "Debug" binaries (disabled by default)')
  483. parser.add_argument('--debug_info', default=False, dest='debug_info', action='store_true', help='Build with debug information (useful for Release mode: BUILD_WITH_DEBUG_INFO=ON)')
  484. parser.add_argument('--framework_name', default='opencv2', dest='framework_name', help='Name of OpenCV framework (default: opencv2, will change to OpenCV in future version)')
  485. parser.add_argument('--legacy_build', default=False, dest='legacy_build', action='store_true', help='Build legacy opencv2 framework (default: False, equivalent to "--framework_name=opencv2 --without=objc")')
  486. parser.add_argument('--run_tests', default=False, dest='run_tests', action='store_true', help='Run tests')
  487. parser.add_argument('--build_docs', default=False, dest='build_docs', action='store_true', help='Build docs')
  488. parser.add_argument('--disable-swift', default=False, dest='swiftdisabled', action='store_true', help='Disable building of Swift extensions')
  489. args, unknown_args = parser.parse_known_args()
  490. if unknown_args:
  491. print("The following args are not recognized and will not be used: %s" % unknown_args)
  492. os.environ['IPHONEOS_DEPLOYMENT_TARGET'] = args.iphoneos_deployment_target
  493. print('Using IPHONEOS_DEPLOYMENT_TARGET=' + os.environ['IPHONEOS_DEPLOYMENT_TARGET'])
  494. iphoneos_archs = None
  495. if args.iphoneos_archs:
  496. iphoneos_archs = args.iphoneos_archs.split(',')
  497. elif not args.build_only_specified_archs:
  498. # Supply defaults
  499. iphoneos_archs = ["armv7", "armv7s", "arm64"]
  500. print('Using iPhoneOS ARCHS=' + str(iphoneos_archs))
  501. iphonesimulator_archs = None
  502. if args.iphonesimulator_archs:
  503. iphonesimulator_archs = args.iphonesimulator_archs.split(',')
  504. elif not args.build_only_specified_archs:
  505. # Supply defaults
  506. iphonesimulator_archs = ["i386", "x86_64"]
  507. print('Using iPhoneSimulator ARCHS=' + str(iphonesimulator_archs))
  508. # Prevent the build from happening if the same architecture is specified for multiple platforms.
  509. # When `lipo` is run to stitch the frameworks together into a fat framework, it'll fail, so it's
  510. # better to stop here while we're ahead.
  511. if iphoneos_archs and iphonesimulator_archs:
  512. duplicate_archs = set(iphoneos_archs).intersection(iphonesimulator_archs)
  513. if duplicate_archs:
  514. print_error("Cannot have the same architecture for multiple platforms in a fat framework! Consider using build_xcframework.py in the apple platform folder instead. Duplicate archs are %s" % duplicate_archs)
  515. exit(1)
  516. if args.legacy_build:
  517. args.framework_name = "opencv2"
  518. if not "objc" in args.without:
  519. args.without.append("objc")
  520. targets = []
  521. if os.environ.get('BUILD_PRECOMMIT', None):
  522. if not iphoneos_archs:
  523. print_error("--iphoneos_archs must have at least one value")
  524. sys.exit(1)
  525. targets.append((iphoneos_archs, "iPhoneOS"))
  526. else:
  527. if not iphoneos_archs and not iphonesimulator_archs:
  528. print_error("--iphoneos_archs and --iphonesimulator_archs are undefined; nothing will be built.")
  529. sys.exit(1)
  530. if iphoneos_archs:
  531. targets.append((iphoneos_archs, "iPhoneOS"))
  532. if iphonesimulator_archs:
  533. targets.append((iphonesimulator_archs, "iPhoneSimulator"))
  534. b = iOSBuilder(args.opencv, args.contrib, args.dynamic, args.embed_bitcode, args.without, args.disable, args.enablenonfree, targets, args.debug, args.debug_info, args.framework_name, args.run_tests, args.build_docs, args.swiftdisabled)
  535. b.build(args.out)