You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

234 lines
7.7 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. #!/usr/bin/env python
  2. # Copyright (c) 2017 The WebRTC project authors. All Rights Reserved.
  3. #
  4. # Use of this source code is governed by a BSD-style license
  5. # that can be found in the LICENSE file in the root of the source
  6. # tree. An additional intellectual property rights grant can be found
  7. # in the file PATENTS. All contributing project authors may
  8. # be found in the AUTHORS file in the root of the source tree.
  9. """Script to generate libwebrtc.aar for distribution.
  10. The script has to be run from the root src folder.
  11. ./tools_webrtc/android/build_aar.py
  12. .aar-file is just a zip-archive containing the files of the library. The file
  13. structure generated by this script looks like this:
  14. - AndroidManifest.xml
  15. - classes.jar
  16. - libs/
  17. - armeabi-v7a/
  18. - libjingle_peerconnection_so.so
  19. - x86/
  20. - libjingle_peerconnection_so.so
  21. """
  22. import argparse
  23. import logging
  24. import os
  25. import shutil
  26. import subprocess
  27. import sys
  28. import tempfile
  29. import zipfile
  30. SCRIPT_DIR = os.path.dirname(os.path.realpath(sys.argv[0]))
  31. SRC_DIR = os.path.normpath(os.path.join(SCRIPT_DIR, os.pardir, os.pardir))
  32. DEFAULT_ARCHS = ['armeabi-v7a', 'arm64-v8a', 'x86', 'x86_64']
  33. NEEDED_SO_FILES = ['libjingle_peerconnection_so.so']
  34. JAR_FILE = 'lib.java/sdk/android/libwebrtc.jar'
  35. MANIFEST_FILE = 'sdk/android/AndroidManifest.xml'
  36. TARGETS = [
  37. 'sdk/android:libwebrtc',
  38. 'sdk/android:libjingle_peerconnection_so',
  39. ]
  40. sys.path.append(os.path.join(SCRIPT_DIR, '..', 'libs'))
  41. from generate_licenses import LicenseBuilder
  42. sys.path.append(os.path.join(SRC_DIR, 'build'))
  43. import find_depot_tools
  44. def _ParseArgs():
  45. parser = argparse.ArgumentParser(description='libwebrtc.aar generator.')
  46. parser.add_argument('--build-dir',
  47. help='Build dir. By default will create and use temporary dir.')
  48. parser.add_argument('--output', default='libwebrtc.aar',
  49. help='Output file of the script.')
  50. parser.add_argument('--arch', default=DEFAULT_ARCHS, nargs='*',
  51. help='Architectures to build. Defaults to %(default)s.')
  52. parser.add_argument('--use-goma', action='store_true', default=False,
  53. help='Use goma.')
  54. parser.add_argument('--verbose', action='store_true', default=False,
  55. help='Debug logging.')
  56. parser.add_argument('--extra-gn-args', default=[], nargs='*',
  57. help="""Additional GN arguments to be used during Ninja generation.
  58. These are passed to gn inside `--args` switch and
  59. applied after any other arguments and will
  60. override any values defined by the script.
  61. Example of building debug aar file:
  62. build_aar.py --extra-gn-args='is_debug=true'""")
  63. parser.add_argument('--extra-ninja-switches', default=[], nargs='*',
  64. help="""Additional Ninja switches to be used during compilation.
  65. These are applied after any other Ninja switches.
  66. Example of enabling verbose Ninja output:
  67. build_aar.py --extra-ninja-switches='-v'""")
  68. parser.add_argument('--extra-gn-switches', default=[], nargs='*',
  69. help="""Additional GN switches to be used during compilation.
  70. These are applied after any other GN switches.
  71. Example of enabling verbose GN output:
  72. build_aar.py --extra-gn-switches='-v'""")
  73. return parser.parse_args()
  74. def _RunGN(args):
  75. cmd = [sys.executable,
  76. os.path.join(find_depot_tools.DEPOT_TOOLS_PATH, 'gn.py')]
  77. cmd.extend(args)
  78. logging.debug('Running: %r', cmd)
  79. subprocess.check_call(cmd)
  80. def _RunNinja(output_directory, args):
  81. cmd = [os.path.join(find_depot_tools.DEPOT_TOOLS_PATH, 'ninja'),
  82. '-C', output_directory]
  83. cmd.extend(args)
  84. logging.debug('Running: %r', cmd)
  85. subprocess.check_call(cmd)
  86. def _EncodeForGN(value):
  87. """Encodes value as a GN literal."""
  88. if isinstance(value, str):
  89. return '"' + value + '"'
  90. elif isinstance(value, bool):
  91. return repr(value).lower()
  92. else:
  93. return repr(value)
  94. def _GetOutputDirectory(build_dir, arch):
  95. """Returns the GN output directory for the target architecture."""
  96. return os.path.join(build_dir, arch)
  97. def _GetTargetCpu(arch):
  98. """Returns target_cpu for the GN build with the given architecture."""
  99. if arch in ['armeabi', 'armeabi-v7a']:
  100. return 'arm'
  101. elif arch == 'arm64-v8a':
  102. return 'arm64'
  103. elif arch == 'x86':
  104. return 'x86'
  105. elif arch == 'x86_64':
  106. return 'x64'
  107. else:
  108. raise Exception('Unknown arch: ' + arch)
  109. def _GetArmVersion(arch):
  110. """Returns arm_version for the GN build with the given architecture."""
  111. if arch == 'armeabi':
  112. return 6
  113. elif arch == 'armeabi-v7a':
  114. return 7
  115. elif arch in ['arm64-v8a', 'x86', 'x86_64']:
  116. return None
  117. else:
  118. raise Exception('Unknown arch: ' + arch)
  119. def Build(build_dir, arch, use_goma, extra_gn_args, extra_gn_switches,
  120. extra_ninja_switches):
  121. """Generates target architecture using GN and builds it using ninja."""
  122. logging.info('Building: %s', arch)
  123. output_directory = _GetOutputDirectory(build_dir, arch)
  124. gn_args = {
  125. 'target_os': 'android',
  126. 'is_debug': False,
  127. 'is_component_build': False,
  128. 'rtc_include_tests': False,
  129. 'target_cpu': _GetTargetCpu(arch),
  130. 'use_goma': use_goma
  131. }
  132. arm_version = _GetArmVersion(arch)
  133. if arm_version:
  134. gn_args['arm_version'] = arm_version
  135. gn_args_str = '--args=' + ' '.join([
  136. k + '=' + _EncodeForGN(v) for k, v in gn_args.items()] + extra_gn_args)
  137. gn_args_list = ['gen', output_directory, gn_args_str]
  138. gn_args_list.extend(extra_gn_switches)
  139. _RunGN(gn_args_list)
  140. ninja_args = TARGETS[:]
  141. if use_goma:
  142. ninja_args.extend(['-j', '200'])
  143. ninja_args.extend(extra_ninja_switches)
  144. _RunNinja(output_directory, ninja_args)
  145. def CollectCommon(aar_file, build_dir, arch):
  146. """Collects architecture independent files into the .aar-archive."""
  147. logging.info('Collecting common files.')
  148. output_directory = _GetOutputDirectory(build_dir, arch)
  149. aar_file.write(MANIFEST_FILE, 'AndroidManifest.xml')
  150. aar_file.write(os.path.join(output_directory, JAR_FILE), 'classes.jar')
  151. def Collect(aar_file, build_dir, arch):
  152. """Collects architecture specific files into the .aar-archive."""
  153. logging.info('Collecting: %s', arch)
  154. output_directory = _GetOutputDirectory(build_dir, arch)
  155. abi_dir = os.path.join('jni', arch)
  156. for so_file in NEEDED_SO_FILES:
  157. aar_file.write(os.path.join(output_directory, so_file),
  158. os.path.join(abi_dir, so_file))
  159. def GenerateLicenses(output_dir, build_dir, archs):
  160. builder = LicenseBuilder(
  161. [_GetOutputDirectory(build_dir, arch) for arch in archs], TARGETS)
  162. builder.GenerateLicenseText(output_dir)
  163. def BuildAar(archs, output_file, use_goma=False, extra_gn_args=None,
  164. ext_build_dir=None, extra_gn_switches=None,
  165. extra_ninja_switches=None):
  166. extra_gn_args = extra_gn_args or []
  167. extra_gn_switches = extra_gn_switches or []
  168. extra_ninja_switches = extra_ninja_switches or []
  169. build_dir = ext_build_dir if ext_build_dir else tempfile.mkdtemp()
  170. for arch in archs:
  171. Build(build_dir, arch, use_goma, extra_gn_args, extra_gn_switches,
  172. extra_ninja_switches)
  173. with zipfile.ZipFile(output_file, 'w') as aar_file:
  174. # Architecture doesn't matter here, arbitrarily using the first one.
  175. CollectCommon(aar_file, build_dir, archs[0])
  176. for arch in archs:
  177. Collect(aar_file, build_dir, arch)
  178. license_dir = os.path.dirname(os.path.realpath(output_file))
  179. GenerateLicenses(license_dir, build_dir, archs)
  180. if not ext_build_dir:
  181. shutil.rmtree(build_dir, True)
  182. def main():
  183. args = _ParseArgs()
  184. logging.basicConfig(level=logging.DEBUG if args.verbose else logging.INFO)
  185. BuildAar(args.arch, args.output, args.use_goma, args.extra_gn_args,
  186. args.build_dir, args.extra_gn_switches, args.extra_ninja_switches)
  187. if __name__ == '__main__':
  188. sys.exit(main())