build_framework.py 30 KB

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