chore: import upstream snapshot with attribution
This commit is contained in:
@@ -0,0 +1 @@
|
||||
See http://opencv.org/platforms/android
|
||||
@@ -0,0 +1,117 @@
|
||||
plugins {
|
||||
id 'com.android.library'
|
||||
id 'maven-publish'
|
||||
id 'kotlin-android'
|
||||
}
|
||||
|
||||
android {
|
||||
namespace 'org.opencv'
|
||||
compileSdk ${COMPILE_SDK}
|
||||
ndkVersion "${NDK_VERSION}"
|
||||
|
||||
defaultConfig {
|
||||
minSdk ${MIN_SDK}
|
||||
targetSdk ${TARGET_SDK}
|
||||
|
||||
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
||||
externalNativeBuild {
|
||||
cmake {
|
||||
cppFlags ""
|
||||
arguments "-DANDROID_STL=${LIB_TYPE}"
|
||||
}
|
||||
}
|
||||
ndk {
|
||||
abiFilters ${ABI_FILTERS}
|
||||
}
|
||||
}
|
||||
|
||||
buildTypes {
|
||||
release {
|
||||
minifyEnabled false
|
||||
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
|
||||
}
|
||||
}
|
||||
compileOptions {
|
||||
sourceCompatibility JavaVersion.VERSION_${JAVA_VERSION}
|
||||
targetCompatibility JavaVersion.VERSION_${JAVA_VERSION}
|
||||
}
|
||||
externalNativeBuild {
|
||||
cmake {
|
||||
path file('src/main/cpp/CMakeLists.txt')
|
||||
}
|
||||
}
|
||||
buildFeatures {
|
||||
prefabPublishing true
|
||||
buildConfig true
|
||||
}
|
||||
prefab {
|
||||
${LIB_NAME} {
|
||||
headers "src/main/cpp/include"
|
||||
}
|
||||
}
|
||||
sourceSets {
|
||||
main {
|
||||
java.srcDirs = ['src/main/java']
|
||||
//jniLibs.srcDirs = ['libs']
|
||||
}
|
||||
}
|
||||
|
||||
publishing {
|
||||
singleVariant('release') {
|
||||
withSourcesJar()
|
||||
withJavadocJar()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
publishing {
|
||||
publications {
|
||||
release(MavenPublication) {
|
||||
// Builds aar, sources jar and javadoc jar from project sources and creates maven
|
||||
groupId = 'org.opencv'
|
||||
artifactId = '${PACKAGE_NAME}'
|
||||
version = '${OPENCV_VERSION}'
|
||||
afterEvaluate {
|
||||
from components.release
|
||||
}
|
||||
}
|
||||
modified(MavenPublication) {
|
||||
// Creates maven from opencv-release.aar
|
||||
groupId = 'org.opencv'
|
||||
artifactId = '${PACKAGE_NAME}'
|
||||
version = '${OPENCV_VERSION}'
|
||||
artifact("opencv-release.aar")
|
||||
pom {
|
||||
name = "OpenCV"
|
||||
description = "Open Source Computer Vision Library"
|
||||
url = "https://opencv.org/"
|
||||
licenses {
|
||||
license {
|
||||
name = "The Apache License, Version 2.0"
|
||||
url = "https://github.com/opencv/opencv/blob/master/LICENSE"
|
||||
}
|
||||
}
|
||||
developers {
|
||||
developer {
|
||||
id = "admin"
|
||||
name = "OpenCV Team"
|
||||
email = "admin@opencv.org"
|
||||
}
|
||||
}
|
||||
scm {
|
||||
connection = "scm:git:https://github.com/opencv/opencv.git"
|
||||
url = "https://github.com/opencv/opencv"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
repositories {
|
||||
maven {
|
||||
name = 'myrepo'
|
||||
url = "${project.buildDir}/repo"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
# Add project specific ProGuard rules here.
|
||||
# You can control the set of applied configuration files using the
|
||||
# proguardFiles setting in build.gradle.
|
||||
#
|
||||
# For more details, see
|
||||
# http://developer.android.com/guide/developing/tools/proguard.html
|
||||
|
||||
# If your project uses WebView with JS, uncomment the following
|
||||
# and specify the fully qualified class name to the JavaScript interface
|
||||
# class:
|
||||
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
|
||||
# public *;
|
||||
#}
|
||||
|
||||
# Uncomment this to preserve the line number information for
|
||||
# debugging stack traces.
|
||||
#-keepattributes SourceFile,LineNumberTable
|
||||
|
||||
# If you keep the line number information, uncomment this to
|
||||
# hide the original source file name.
|
||||
#-renamesourcefileattribute SourceFile
|
||||
@@ -0,0 +1,4 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
|
||||
</manifest>
|
||||
@@ -0,0 +1,5 @@
|
||||
cmake_minimum_required(VERSION 3.6)
|
||||
|
||||
project("opencv")
|
||||
|
||||
add_library(${LIB_NAME} ${LIB_TYPE} native-lib.cpp)
|
||||
@@ -0,0 +1 @@
|
||||
// This empty .h file is used for creating an AAR with empty C++ lib that will be replaced with OpenCV C++ lib
|
||||
@@ -0,0 +1 @@
|
||||
// This empty .cpp file is used for creating an AAR with empty C++ lib that will be replaced with OpenCV C++ lib
|
||||
@@ -0,0 +1,29 @@
|
||||
## Scripts for creating an AAR package and a local Maven repository with OpenCV libraries for Android
|
||||
|
||||
### How to run the scripts
|
||||
1. Set JAVA_HOME and ANDROID_HOME environment variables. For example:
|
||||
```
|
||||
export JAVA_HOME=~/Android Studio/jbr
|
||||
export ANDROID_HOME=~/Android/SDK
|
||||
```
|
||||
2. Download OpenCV SDK for Android
|
||||
3. Run build script for version with Java and a shared C++ library:
|
||||
```
|
||||
python build_java_shared_aar.py "~/opencv-4.7.0-android-sdk/OpenCV-android-sdk"
|
||||
```
|
||||
4. Run build script for version with static C++ libraries:
|
||||
```
|
||||
python build_static_aar.py "~/opencv-4.7.0-android-sdk/OpenCV-android-sdk"
|
||||
```
|
||||
The AAR libraries and the local Maven repository will be created in the **outputs** directory
|
||||
### Technical details
|
||||
The scripts consist of 5 steps:
|
||||
1. Preparing Android AAR library project template
|
||||
2. Adding Java code to the project. Adding C++ public headers for shared version to the project.
|
||||
3. Compiling the project to build an AAR package
|
||||
4. Adding C++ binary libraries to the AAR package. Adding C++ public headers for static version to the AAR package.
|
||||
5. Creating Maven repository with the AAR package
|
||||
|
||||
There are a few minor limitations:
|
||||
1. Due to the AAR design the Java + shared C++ AAR package contains duplicates of C++ binary libraries, but the final user's Android application contains only one library instance.
|
||||
2. The compile definitions from cmake configs are skipped, but it shouldn't affect the library because the script uses precompiled C++ binaries from SDK.
|
||||
@@ -0,0 +1,5 @@
|
||||
// Top-level build file where you can add configuration options common to all sub-projects/modules.
|
||||
plugins {
|
||||
id 'com.android.library' version '8.6.0' apply false
|
||||
id 'org.jetbrains.kotlin.android' version '1.8.20' apply false
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
# Project-wide Gradle settings.
|
||||
# IDE (e.g. Android Studio) users:
|
||||
# Gradle settings configured through the IDE *will override*
|
||||
# any settings specified in this file.
|
||||
# For more details on how to configure your build environment visit
|
||||
# http://www.gradle.org/docs/current/userguide/build_environment.html
|
||||
# Specifies the JVM arguments used for the daemon process.
|
||||
# The setting is particularly useful for tweaking memory settings.
|
||||
org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
|
||||
# When configured, Gradle will run in incubating parallel mode.
|
||||
# This option should only be used with decoupled projects. More details, visit
|
||||
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
|
||||
# org.gradle.parallel=true
|
||||
# AndroidX package structure to make it clearer which packages are bundled with the
|
||||
# Android operating system, and which are packaged with your app's APK
|
||||
# https://developer.android.com/topic/libraries/support-library/androidx-rn
|
||||
android.useAndroidX=true
|
||||
# Enables namespacing of each library's R class so that its R class includes only the
|
||||
# resources declared in the library itself and none from the library's dependencies,
|
||||
# thereby reducing the size of the R class for that library
|
||||
android.nonTransitiveRClass=true
|
||||
Binary file not shown.
@@ -0,0 +1,6 @@
|
||||
#Mon Jul 10 11:57:38 SGT 2023
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.11.1-bin.zip
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
+185
@@ -0,0 +1,185 @@
|
||||
#!/usr/bin/env sh
|
||||
|
||||
#
|
||||
# Copyright 2015 the original author or authors.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
|
||||
##############################################################################
|
||||
##
|
||||
## Gradle start up script for UN*X
|
||||
##
|
||||
##############################################################################
|
||||
|
||||
# Attempt to set APP_HOME
|
||||
# Resolve links: $0 may be a link
|
||||
PRG="$0"
|
||||
# Need this for relative symlinks.
|
||||
while [ -h "$PRG" ] ; do
|
||||
ls=`ls -ld "$PRG"`
|
||||
link=`expr "$ls" : '.*-> \(.*\)$'`
|
||||
if expr "$link" : '/.*' > /dev/null; then
|
||||
PRG="$link"
|
||||
else
|
||||
PRG=`dirname "$PRG"`"/$link"
|
||||
fi
|
||||
done
|
||||
SAVED="`pwd`"
|
||||
cd "`dirname \"$PRG\"`/" >/dev/null
|
||||
APP_HOME="`pwd -P`"
|
||||
cd "$SAVED" >/dev/null
|
||||
|
||||
APP_NAME="Gradle"
|
||||
APP_BASE_NAME=`basename "$0"`
|
||||
|
||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD="maximum"
|
||||
|
||||
warn () {
|
||||
echo "$*"
|
||||
}
|
||||
|
||||
die () {
|
||||
echo
|
||||
echo "$*"
|
||||
echo
|
||||
exit 1
|
||||
}
|
||||
|
||||
# OS specific support (must be 'true' or 'false').
|
||||
cygwin=false
|
||||
msys=false
|
||||
darwin=false
|
||||
nonstop=false
|
||||
case "`uname`" in
|
||||
CYGWIN* )
|
||||
cygwin=true
|
||||
;;
|
||||
Darwin* )
|
||||
darwin=true
|
||||
;;
|
||||
MINGW* )
|
||||
msys=true
|
||||
;;
|
||||
NONSTOP* )
|
||||
nonstop=true
|
||||
;;
|
||||
esac
|
||||
|
||||
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
|
||||
|
||||
|
||||
# Determine the Java command to use to start the JVM.
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD="$JAVA_HOME/jre/sh/java"
|
||||
else
|
||||
JAVACMD="$JAVA_HOME/bin/java"
|
||||
fi
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
else
|
||||
JAVACMD="java"
|
||||
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
|
||||
# Increase the maximum file descriptors if we can.
|
||||
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
|
||||
MAX_FD_LIMIT=`ulimit -H -n`
|
||||
if [ $? -eq 0 ] ; then
|
||||
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
|
||||
MAX_FD="$MAX_FD_LIMIT"
|
||||
fi
|
||||
ulimit -n $MAX_FD
|
||||
if [ $? -ne 0 ] ; then
|
||||
warn "Could not set maximum file descriptor limit: $MAX_FD"
|
||||
fi
|
||||
else
|
||||
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
|
||||
fi
|
||||
fi
|
||||
|
||||
# For Darwin, add options to specify how the application appears in the dock
|
||||
if $darwin; then
|
||||
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
|
||||
fi
|
||||
|
||||
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
|
||||
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
|
||||
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
|
||||
|
||||
JAVACMD=`cygpath --unix "$JAVACMD"`
|
||||
|
||||
# We build the pattern for arguments to be converted via cygpath
|
||||
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
|
||||
SEP=""
|
||||
for dir in $ROOTDIRSRAW ; do
|
||||
ROOTDIRS="$ROOTDIRS$SEP$dir"
|
||||
SEP="|"
|
||||
done
|
||||
OURCYGPATTERN="(^($ROOTDIRS))"
|
||||
# Add a user-defined pattern to the cygpath arguments
|
||||
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
|
||||
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
|
||||
fi
|
||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||
i=0
|
||||
for arg in "$@" ; do
|
||||
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
|
||||
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
|
||||
|
||||
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
|
||||
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
|
||||
else
|
||||
eval `echo args$i`="\"$arg\""
|
||||
fi
|
||||
i=`expr $i + 1`
|
||||
done
|
||||
case $i in
|
||||
0) set -- ;;
|
||||
1) set -- "$args0" ;;
|
||||
2) set -- "$args0" "$args1" ;;
|
||||
3) set -- "$args0" "$args1" "$args2" ;;
|
||||
4) set -- "$args0" "$args1" "$args2" "$args3" ;;
|
||||
5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
|
||||
6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
|
||||
7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
|
||||
8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
|
||||
9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
|
||||
esac
|
||||
fi
|
||||
|
||||
# Escape application args
|
||||
save () {
|
||||
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
|
||||
echo " "
|
||||
}
|
||||
APP_ARGS=`save "$@"`
|
||||
|
||||
# Collect all arguments for the java command, following the shell quoting and substitution rules
|
||||
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
|
||||
|
||||
exec "$JAVACMD" "$@"
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
@rem
|
||||
@rem Copyright 2015 the original author or authors.
|
||||
@rem
|
||||
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||
@rem you may not use this file except in compliance with the License.
|
||||
@rem You may obtain a copy of the License at
|
||||
@rem
|
||||
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||
@rem
|
||||
@rem Unless required by applicable law or agreed to in writing, software
|
||||
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
@rem See the License for the specific language governing permissions and
|
||||
@rem limitations under the License.
|
||||
@rem
|
||||
|
||||
@if "%DEBUG%" == "" @echo off
|
||||
@rem ##########################################################################
|
||||
@rem
|
||||
@rem Gradle startup script for Windows
|
||||
@rem
|
||||
@rem ##########################################################################
|
||||
|
||||
@rem Set local scope for the variables with windows NT shell
|
||||
if "%OS%"=="Windows_NT" setlocal
|
||||
|
||||
set DIRNAME=%~dp0
|
||||
if "%DIRNAME%" == "" set DIRNAME=.
|
||||
set APP_BASE_NAME=%~n0
|
||||
set APP_HOME=%DIRNAME%
|
||||
|
||||
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
||||
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
||||
|
||||
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
||||
|
||||
@rem Find java.exe
|
||||
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||
|
||||
set JAVA_EXE=java.exe
|
||||
%JAVA_EXE% -version >NUL 2>&1
|
||||
if "%ERRORLEVEL%" == "0" goto execute
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:findJavaFromJavaHome
|
||||
set JAVA_HOME=%JAVA_HOME:"=%
|
||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||
|
||||
if exist "%JAVA_EXE%" goto execute
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:execute
|
||||
@rem Setup the command line
|
||||
|
||||
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
|
||||
|
||||
|
||||
@rem Execute Gradle
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
|
||||
|
||||
:end
|
||||
@rem End local scope for the variables with windows NT shell
|
||||
if "%ERRORLEVEL%"=="0" goto mainEnd
|
||||
|
||||
:fail
|
||||
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||
rem the _cmd.exe /c_ return code!
|
||||
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
|
||||
exit /b 1
|
||||
|
||||
:mainEnd
|
||||
if "%OS%"=="Windows_NT" endlocal
|
||||
|
||||
:omega
|
||||
@@ -0,0 +1,16 @@
|
||||
pluginManagement {
|
||||
repositories {
|
||||
google()
|
||||
mavenCentral()
|
||||
gradlePluginPortal()
|
||||
}
|
||||
}
|
||||
dependencyResolutionManagement {
|
||||
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
|
||||
repositories {
|
||||
google()
|
||||
mavenCentral()
|
||||
}
|
||||
}
|
||||
rootProject.name = "OpenCV"
|
||||
include ':OpenCV'
|
||||
@@ -0,0 +1,154 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
import unittest
|
||||
import os, sys, subprocess, argparse, shutil, re
|
||||
import logging as log
|
||||
|
||||
log.basicConfig(format='%(message)s', level=log.DEBUG)
|
||||
|
||||
CMAKE_TEMPLATE='''\
|
||||
CMAKE_MINIMUM_REQUIRED(VERSION 3.5)
|
||||
|
||||
# Enable C++11
|
||||
set(CMAKE_CXX_STANDARD 11)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED TRUE)
|
||||
|
||||
SET(PROJECT_NAME hello-android)
|
||||
PROJECT(${PROJECT_NAME})
|
||||
|
||||
FIND_PACKAGE(OpenCV REQUIRED %(libset)s)
|
||||
FILE(GLOB srcs "*.cpp")
|
||||
|
||||
ADD_EXECUTABLE(${PROJECT_NAME} ${srcs})
|
||||
TARGET_LINK_LIBRARIES(${PROJECT_NAME} ${OpenCV_LIBS} dl z)
|
||||
'''
|
||||
|
||||
CPP_TEMPLATE = '''\
|
||||
#include <opencv2/core.hpp>
|
||||
#include <opencv2/highgui.hpp>
|
||||
#include <opencv2/imgproc.hpp>
|
||||
using namespace cv;
|
||||
const char* message = "Hello Android!";
|
||||
int main(int argc, char* argv[])
|
||||
{
|
||||
(void)argc; (void)argv;
|
||||
printf("%s\\n", message);
|
||||
Size textsize = getTextSize(message, FONT_HERSHEY_COMPLEX, 3, 5, 0);
|
||||
Mat img(textsize.height + 20, textsize.width + 20, CV_32FC1, Scalar(230,230,230));
|
||||
putText(img, message, Point(10, img.rows - 10), FONT_HERSHEY_COMPLEX, 3, Scalar(0, 0, 0), 5);
|
||||
imwrite("/mnt/sdcard/HelloAndroid.png", img);
|
||||
return 0;
|
||||
}
|
||||
'''
|
||||
|
||||
#===================================================================================================
|
||||
|
||||
class TestCmakeBuild(unittest.TestCase):
|
||||
def __init__(self, libset, abi, cmake_vars, opencv_cmake_path, workdir, *args, **kwargs):
|
||||
unittest.TestCase.__init__(self, *args, **kwargs)
|
||||
self.libset = libset
|
||||
self.abi = abi
|
||||
self.cmake_vars = cmake_vars
|
||||
self.opencv_cmake_path = opencv_cmake_path
|
||||
self.workdir = workdir
|
||||
self.srcdir = os.path.join(self.workdir, "src")
|
||||
self.bindir = os.path.join(self.workdir, "build")
|
||||
|
||||
def shortDescription(self):
|
||||
return "ABI: %s, LIBSET: %s" % (self.abi, self.libset)
|
||||
|
||||
def getCMakeToolchain(self):
|
||||
if True:
|
||||
toolchain = os.path.join(os.environ['ANDROID_NDK'], 'build', 'cmake', 'android.toolchain.cmake')
|
||||
if os.path.exists(toolchain):
|
||||
return toolchain
|
||||
toolchain = os.path.join(self.opencv_cmake_path, "android.toolchain.cmake")
|
||||
if os.path.exists(toolchain):
|
||||
return toolchain
|
||||
else:
|
||||
raise Exception("Can't find toolchain")
|
||||
|
||||
def gen_cmakelists(self):
|
||||
return CMAKE_TEMPLATE % {"libset": self.libset}
|
||||
|
||||
def gen_code(self):
|
||||
return CPP_TEMPLATE
|
||||
|
||||
def write_src_file(self, fname, content):
|
||||
with open(os.path.join(self.srcdir, fname), "w") as f:
|
||||
f.write(content)
|
||||
|
||||
def setUp(self):
|
||||
if os.path.exists(self.workdir):
|
||||
shutil.rmtree(self.workdir)
|
||||
os.mkdir(self.workdir)
|
||||
os.mkdir(self.srcdir)
|
||||
os.mkdir(self.bindir)
|
||||
self.write_src_file("CMakeLists.txt", self.gen_cmakelists())
|
||||
self.write_src_file("main.cpp", self.gen_code())
|
||||
os.chdir(self.bindir)
|
||||
|
||||
def tearDown(self):
|
||||
pass
|
||||
#if os.path.exists(self.workdir):
|
||||
# shutil.rmtree(self.workdir)
|
||||
|
||||
def runTest(self):
|
||||
cmd = [
|
||||
"cmake",
|
||||
"-GNinja",
|
||||
"-DOpenCV_DIR=%s" % self.opencv_cmake_path,
|
||||
"-DCMAKE_TOOLCHAIN_FILE=%s" % self.getCMakeToolchain(),
|
||||
self.srcdir
|
||||
] + [ "-D{}={}".format(key, value) for key, value in self.cmake_vars.items() ]
|
||||
log.info("Executing: %s" % cmd)
|
||||
retcode = subprocess.call(cmd)
|
||||
self.assertEqual(retcode, 0, "cmake failed")
|
||||
|
||||
cmd = ["ninja", "-v"]
|
||||
log.info("Executing: %s" % cmd)
|
||||
retcode = subprocess.call(cmd)
|
||||
self.assertEqual(retcode, 0, "make failed")
|
||||
|
||||
def suite(workdir, opencv_cmake_path):
|
||||
abis = {
|
||||
"armeabi-v7a": { "ANDROID_ABI": "armeabi-v7a", "ANDROID_TOOLCHAIN": "clang", "ANDROID_STL": "c++_shared", 'ANDROID_NATIVE_API_LEVEL': "21" },
|
||||
"arm64-v8a": { "ANDROID_ABI": "arm64-v8a", "ANDROID_TOOLCHAIN": "clang", "ANDROID_STL": "c++_shared", 'ANDROID_NATIVE_API_LEVEL': "21" },
|
||||
"x86": { "ANDROID_ABI": "x86", "ANDROID_TOOLCHAIN": "clang", "ANDROID_STL": "c++_shared", 'ANDROID_NATIVE_API_LEVEL': "21" },
|
||||
"x86_64": { "ANDROID_ABI": "x86_64", "ANDROID_TOOLCHAIN": "clang", "ANDROID_STL": "c++_shared", 'ANDROID_NATIVE_API_LEVEL': "21" },
|
||||
}
|
||||
|
||||
suite = unittest.TestSuite()
|
||||
for libset in ["", "opencv_java"]:
|
||||
for abi, cmake_vars in abis.items():
|
||||
suite.addTest(TestCmakeBuild(libset, abi, cmake_vars, opencv_cmake_path,
|
||||
os.path.join(workdir, "{}-{}".format(abi, "static" if libset == "" else "shared"))))
|
||||
return suite
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser(description='Test OpenCV for Android SDK with cmake')
|
||||
parser.add_argument('--sdk_path', help="Path to Android SDK to use for build")
|
||||
parser.add_argument('--ndk_path', help="Path to Android NDK to use for build")
|
||||
parser.add_argument("--workdir", default="testspace", help="Working directory (and output)")
|
||||
parser.add_argument("opencv_cmake_path", help="Path to folder with OpenCVConfig.cmake and android.toolchain.cmake (usually <SDK>/sdk/native/jni/")
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.sdk_path is not None:
|
||||
os.environ["ANDROID_SDK"] = os.path.abspath(args.sdk_path)
|
||||
if args.ndk_path is not None:
|
||||
os.environ["ANDROID_NDK"] = os.path.abspath(args.ndk_path)
|
||||
|
||||
if not 'ANDROID_HOME' in os.environ and 'ANDROID_SDK' in os.environ:
|
||||
os.environ['ANDROID_HOME'] = os.environ["ANDROID_SDK"]
|
||||
|
||||
print("Using SDK: %s" % os.environ["ANDROID_SDK"])
|
||||
print("Using NDK: %s" % os.environ["ANDROID_NDK"])
|
||||
|
||||
workdir = os.path.abspath(args.workdir)
|
||||
if not os.path.exists(workdir):
|
||||
os.mkdir(workdir)
|
||||
res = unittest.TextTestRunner(verbosity=3).run(suite(workdir, os.path.abspath(args.opencv_cmake_path)))
|
||||
if not res.wasSuccessful():
|
||||
sys.exit(res)
|
||||
Executable
+43
@@ -0,0 +1,43 @@
|
||||
#!/bin/bash -e
|
||||
SDK_DIR=$1
|
||||
|
||||
echo "OpenCV Android SDK path: ${SDK_DIR}"
|
||||
|
||||
ANDROID_HOME=${ANDROID_HOME:-${ANDROID_SDK_ROOT:-${ANDROID_SDK?Required ANDROID_HOME/ANDROID_SDK/ANDROID_SDK_ROOT}}}
|
||||
ANDROID_NDK=${ANDROID_NDK_HOME-${ANDROID_NDK:-${NDKROOT?Required ANDROID_NDK_HOME/ANDROID_NDK/NDKROOT}}}
|
||||
OPENCV_GRADLE_VERBOSE_OPTIONS=${OPENCV_GRADLE_VERBOSE_OPTIONS:-'-i'}
|
||||
|
||||
echo "Android SDK: ${ANDROID_HOME}"
|
||||
echo "Android NDK: ${ANDROID_NDK}"
|
||||
|
||||
if [ ! -d "${ANDROID_HOME}" ]; then
|
||||
echo "FATAL: Missing Android SDK directory"
|
||||
exit 1
|
||||
fi
|
||||
if [ ! -d "${ANDROID_NDK}" ]; then
|
||||
echo "FATAL: Missing Android NDK directory"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
export ANDROID_HOME=${ANDROID_HOME}
|
||||
export ANDROID_SDK=${ANDROID_HOME}
|
||||
export ANDROID_SDK_ROOT=${ANDROID_HOME}
|
||||
|
||||
export ANDROID_NDK=${ANDROID_NDK}
|
||||
export ANDROID_NDK_HOME=${ANDROID_NDK}
|
||||
|
||||
echo "Cloning OpenCV Android SDK ..."
|
||||
rm -rf "test-gradle"
|
||||
cp -rp "${SDK_DIR}" "test-gradle"
|
||||
echo "Cloning OpenCV Android SDK ... Done!"
|
||||
|
||||
# drop cmake bin name and "bin" folder from path
|
||||
echo "ndk.dir=${ANDROID_NDK}" > "test-gradle/samples/local.properties"
|
||||
echo "cmake.dir=$(dirname $(dirname $(which cmake)))" >> "test-gradle/samples/local.properties"
|
||||
|
||||
echo "Run gradle ..."
|
||||
(cd "test-gradle/samples"; ./gradlew ${OPENCV_GRADLE_VERBOSE_OPTIONS} assemble)
|
||||
|
||||
echo "#"
|
||||
echo "# Done!"
|
||||
echo "#"
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
#!/bin/bash -e
|
||||
SDK_DIR=$1
|
||||
LOCAL_MAVEN_REPO=$2
|
||||
echo "OpenCV Android SDK path: ${SDK_DIR}"
|
||||
echo "Use local maven repo from $LOCAL_MAVEN_REPO"
|
||||
|
||||
ANDROID_HOME=${ANDROID_HOME:-${ANDROID_SDK_ROOT:-${ANDROID_SDK?Required ANDROID_HOME/ANDROID_SDK/ANDROID_SDK_ROOT}}}
|
||||
ANDROID_NDK=${ANDROID_NDK_HOME-${ANDROID_NDK:-${NDKROOT?Required ANDROID_NDK_HOME/ANDROID_NDK/NDKROOT}}}
|
||||
OPENCV_GRADLE_VERBOSE_OPTIONS=${OPENCV_GRADLE_VERBOSE_OPTIONS:-'-i'}
|
||||
|
||||
echo "Android SDK: ${ANDROID_HOME}"
|
||||
echo "Android NDK: ${ANDROID_NDK}"
|
||||
|
||||
if [ ! -d "${ANDROID_HOME}" ]; then
|
||||
echo "FATAL: Missing Android SDK directory"
|
||||
exit 1
|
||||
fi
|
||||
if [ ! -d "${ANDROID_NDK}" ]; then
|
||||
echo "FATAL: Missing Android NDK directory"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
export ANDROID_HOME=${ANDROID_HOME}
|
||||
export ANDROID_SDK=${ANDROID_HOME}
|
||||
export ANDROID_SDK_ROOT=${ANDROID_HOME}
|
||||
|
||||
export ANDROID_NDK=${ANDROID_NDK}
|
||||
export ANDROID_NDK_HOME=${ANDROID_NDK}
|
||||
|
||||
echo "Cloning OpenCV Android SDK ..."
|
||||
rm -rf "test-gradle-aar"
|
||||
mkdir test-gradle-aar
|
||||
cp -rp ${SDK_DIR}/samples/* test-gradle-aar/
|
||||
echo "Cloning OpenCV Android SDK ... Done!"
|
||||
|
||||
# drop cmake bin name and "bin" folder from path
|
||||
echo "ndk.dir=${ANDROID_NDK}" > "test-gradle-aar/local.properties"
|
||||
echo "cmake.dir=$(dirname $(dirname $(which cmake)))" >> "test-gradle-aar/local.properties"
|
||||
|
||||
sed -i "s/opencv_source = 'sdk_path'/opencv_source = 'maven_local'/g" test-gradle-aar/settings.gradle
|
||||
sed -i "s+opencv_maven_path = '<path_to_maven_repo>'+opencv_maven_path = 'file\\://$LOCAL_MAVEN_REPO'+g" test-gradle-aar/settings.gradle
|
||||
|
||||
echo "Run gradle ..."
|
||||
(cd "test-gradle-aar"; ./gradlew ${OPENCV_GRADLE_VERBOSE_OPTIONS} assemble)
|
||||
|
||||
echo "#"
|
||||
echo "# Done!"
|
||||
echo "#"
|
||||
Executable
+46
@@ -0,0 +1,46 @@
|
||||
#!/bin/bash -e
|
||||
SDK_DIR=$1
|
||||
|
||||
echo "OpenCV Android SDK path: ${SDK_DIR}"
|
||||
|
||||
ANDROID_HOME=${ANDROID_HOME:-${ANDROID_SDK_ROOT:-${ANDROID_SDK?Required ANDROID_HOME/ANDROID_SDK/ANDROID_SDK_ROOT}}}
|
||||
ANDROID_NDK=${ANDROID_NDK_HOME-${ANDROID_NDK:-${NDKROOT?Required ANDROID_NDK_HOME/ANDROID_NDK/NDKROOT}}}
|
||||
OPENCV_GRADLE_VERBOSE_OPTIONS=${OPENCV_GRADLE_VERBOSE_OPTIONS:-'-i'}
|
||||
|
||||
echo "Android SDK: ${ANDROID_HOME}"
|
||||
echo "Android NDK: ${ANDROID_NDK}"
|
||||
|
||||
if [ ! -d "${ANDROID_HOME}" ]; then
|
||||
echo "FATAL: Missing Android SDK directory"
|
||||
exit 1
|
||||
fi
|
||||
if [ ! -d "${ANDROID_NDK}" ]; then
|
||||
echo "FATAL: Missing Android NDK directory"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
export ANDROID_HOME=${ANDROID_HOME}
|
||||
export ANDROID_SDK=${ANDROID_HOME}
|
||||
export ANDROID_SDK_ROOT=${ANDROID_HOME}
|
||||
|
||||
export ANDROID_NDK=${ANDROID_NDK}
|
||||
export ANDROID_NDK_HOME=${ANDROID_NDK}
|
||||
|
||||
echo "Cloning OpenCV Android SDK ..."
|
||||
rm -rf "aar-build"
|
||||
cp -rp "${SDK_DIR}" "aar-build"
|
||||
echo "Cloning OpenCV Android SDK ... Done!"
|
||||
|
||||
# drop cmake bin name and "bin" folder from path
|
||||
echo "ndk.dir=${ANDROID_NDK}" > "aar-build/samples/local.properties"
|
||||
echo "cmake.dir=$(dirname $(dirname $(which cmake)))" >> "aar-build/samples/local.properties"
|
||||
|
||||
echo "Run gradle ..."
|
||||
(cd "aar-build/samples"; ./gradlew ${OPENCV_GRADLE_VERBOSE_OPTIONS} opencv:publishReleasePublicationToMyrepoRepository)
|
||||
|
||||
mkdir "maven_repo"
|
||||
cp -r aar-build/sdk/build/repo/* ./maven_repo/
|
||||
|
||||
echo "#"
|
||||
echo "# Done!"
|
||||
echo "#"
|
||||
Executable
+193
@@ -0,0 +1,193 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
import argparse
|
||||
from os import path
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import string
|
||||
import subprocess
|
||||
|
||||
|
||||
COPY_FROM_SDK_TO_ANDROID_PROJECT = [
|
||||
["sdk/native/jni/include", "OpenCV/src/main/cpp/include"],
|
||||
["sdk/java/src/org", "OpenCV/src/main/java/org"],
|
||||
["sdk/java/res", "OpenCV/src/main/res"]
|
||||
]
|
||||
|
||||
COPY_FROM_SDK_TO_APK = [
|
||||
["sdk/native/libs/<ABI>/lib<LIB_NAME>.so", "jni/<ABI>/lib<LIB_NAME>.so"],
|
||||
["sdk/native/libs/<ABI>/lib<LIB_NAME>.so", "prefab/modules/<LIB_NAME>/libs/android.<ABI>/lib<LIB_NAME>.so"],
|
||||
]
|
||||
|
||||
ANDROID_PROJECT_TEMPLATE_DIR = path.join(path.dirname(__file__), "aar-template")
|
||||
TEMP_DIR = "build_java_shared"
|
||||
ANDROID_PROJECT_DIR = path.join(TEMP_DIR, "AndroidProject")
|
||||
COMPILED_AAR_PATH_1 = path.join(ANDROID_PROJECT_DIR, "OpenCV/build/outputs/aar/OpenCV-release.aar") # original package name
|
||||
COMPILED_AAR_PATH_2 = path.join(ANDROID_PROJECT_DIR, "OpenCV/build/outputs/aar/opencv-release.aar") # lower case package name
|
||||
AAR_UNZIPPED_DIR = path.join(TEMP_DIR, "aar_unzipped")
|
||||
FINAL_AAR_PATH_TEMPLATE = "outputs/opencv_java_shared_<OPENCV_VERSION>.aar"
|
||||
FINAL_REPO_PATH = "outputs/maven_repo"
|
||||
MAVEN_PACKAGE_NAME = "opencv"
|
||||
|
||||
def fill_template(src_path, dst_path, args_dict):
|
||||
with open(src_path, "r") as f:
|
||||
template_text = f.read()
|
||||
template = string.Template(template_text)
|
||||
text = template.safe_substitute(args_dict)
|
||||
with open(dst_path, "w") as f:
|
||||
f.write(text)
|
||||
|
||||
def get_opencv_version(opencv_sdk_path):
|
||||
version_hpp_path = path.join(opencv_sdk_path, "sdk/native/jni/include/opencv2/core/version.hpp")
|
||||
with open(version_hpp_path, "rt") as f:
|
||||
data = f.read()
|
||||
major = re.search(r'^#define\W+CV_VERSION_MAJOR\W+(\d+)$', data, re.MULTILINE).group(1)
|
||||
minor = re.search(r'^#define\W+CV_VERSION_MINOR\W+(\d+)$', data, re.MULTILINE).group(1)
|
||||
revision = re.search(r'^#define\W+CV_VERSION_REVISION\W+(\d+)$', data, re.MULTILINE).group(1)
|
||||
return "%(major)s.%(minor)s.%(revision)s" % locals()
|
||||
|
||||
def get_ndk_version(ndk_path):
|
||||
props_path = path.join(ndk_path, "source.properties")
|
||||
with open(props_path, "rt") as f:
|
||||
data = f.read()
|
||||
version = re.search(r'Pkg\.Revision\W+=\W+(\d+\.\d+\.\d+)', data).group(1)
|
||||
return version.strip()
|
||||
|
||||
|
||||
def get_compiled_aar_path(path1, path2):
|
||||
if path.exists(path1):
|
||||
return path1
|
||||
elif path.exists(path2):
|
||||
return path2
|
||||
else:
|
||||
raise Exception("Can't find compiled AAR path in [" + path1 + ", " + path2 + "]")
|
||||
|
||||
def cleanup(paths_to_remove):
|
||||
exists = False
|
||||
for p in paths_to_remove:
|
||||
if path.exists(p):
|
||||
exists = True
|
||||
if path.isdir(p):
|
||||
shutil.rmtree(p)
|
||||
else:
|
||||
os.remove(p)
|
||||
print("Removed", p)
|
||||
if not exists:
|
||||
print("Nothing to remove")
|
||||
|
||||
def main(args):
|
||||
opencv_version = get_opencv_version(args.opencv_sdk_path)
|
||||
ndk_version = get_ndk_version(args.ndk_location)
|
||||
print("Detected ndk_version:", ndk_version)
|
||||
abis = os.listdir(path.join(args.opencv_sdk_path, "sdk/native/libs"))
|
||||
lib_name = "opencv_java" + opencv_version.split(".")[0]
|
||||
final_aar_path = FINAL_AAR_PATH_TEMPLATE.replace("<OPENCV_VERSION>", opencv_version)
|
||||
|
||||
print("Removing data from previous runs...")
|
||||
cleanup([TEMP_DIR, final_aar_path, path.join(FINAL_REPO_PATH, "org/opencv", MAVEN_PACKAGE_NAME)])
|
||||
|
||||
print("Preparing Android project...")
|
||||
# ANDROID_PROJECT_TEMPLATE_DIR contains an Android project template that creates AAR
|
||||
shutil.copytree(ANDROID_PROJECT_TEMPLATE_DIR, ANDROID_PROJECT_DIR)
|
||||
|
||||
# Configuring the Android project to Java + shared C++ lib version
|
||||
shutil.rmtree(path.join(ANDROID_PROJECT_DIR, "OpenCV/src/main/cpp/include"))
|
||||
|
||||
fill_template(path.join(ANDROID_PROJECT_DIR, "OpenCV/build.gradle.template"),
|
||||
path.join(ANDROID_PROJECT_DIR, "OpenCV/build.gradle"),
|
||||
{"LIB_NAME": lib_name,
|
||||
"LIB_TYPE": "c++_shared",
|
||||
"PACKAGE_NAME": MAVEN_PACKAGE_NAME,
|
||||
"OPENCV_VERSION": opencv_version,
|
||||
"NDK_VERSION": ndk_version,
|
||||
"COMPILE_SDK": args.android_compile_sdk,
|
||||
"MIN_SDK": args.android_min_sdk,
|
||||
"TARGET_SDK": args.android_target_sdk,
|
||||
"ABI_FILTERS": ", ".join(['"' + x + '"' for x in abis]),
|
||||
"JAVA_VERSION": args.java_version,
|
||||
})
|
||||
fill_template(path.join(ANDROID_PROJECT_DIR, "OpenCV/src/main/cpp/CMakeLists.txt.template"),
|
||||
path.join(ANDROID_PROJECT_DIR, "OpenCV/src/main/cpp/CMakeLists.txt"),
|
||||
{"LIB_NAME": lib_name, "LIB_TYPE": "SHARED"})
|
||||
|
||||
local_props = ""
|
||||
if args.ndk_location:
|
||||
local_props += "ndk.dir=" + args.ndk_location + "\n"
|
||||
if args.cmake_location:
|
||||
local_props += "cmake.dir=" + args.cmake_location + "\n"
|
||||
|
||||
if local_props:
|
||||
with open(path.join(ANDROID_PROJECT_DIR, "local.properties"), "wt") as f:
|
||||
f.write(local_props)
|
||||
|
||||
# Copying Java code and C++ public headers from SDK to the Android project
|
||||
for src, dst in COPY_FROM_SDK_TO_ANDROID_PROJECT:
|
||||
shutil.copytree(path.join(args.opencv_sdk_path, src),
|
||||
path.join(ANDROID_PROJECT_DIR, dst))
|
||||
|
||||
print("Running gradle assembleRelease...")
|
||||
# Running gradle to build the Android project
|
||||
cmd = ["./gradlew", "assembleRelease"]
|
||||
if args.offline:
|
||||
cmd = cmd + ["--offline"]
|
||||
subprocess.run(cmd, shell=False, cwd=ANDROID_PROJECT_DIR, check=True)
|
||||
|
||||
print("Adding libs to AAR...")
|
||||
# The created AAR package doesn't contain C++ shared libs.
|
||||
# We need to add them manually.
|
||||
# AAR package is just a zip archive.
|
||||
complied_aar_path = get_compiled_aar_path(COMPILED_AAR_PATH_1, COMPILED_AAR_PATH_2) # two possible paths
|
||||
shutil.unpack_archive(complied_aar_path, AAR_UNZIPPED_DIR, "zip")
|
||||
|
||||
for abi in abis:
|
||||
for src, dst in COPY_FROM_SDK_TO_APK:
|
||||
src = src.replace("<ABI>", abi).replace("<LIB_NAME>", lib_name)
|
||||
dst = dst.replace("<ABI>", abi).replace("<LIB_NAME>", lib_name)
|
||||
shutil.copy(path.join(args.opencv_sdk_path, src),
|
||||
path.join(AAR_UNZIPPED_DIR, dst))
|
||||
|
||||
# Creating final AAR zip archive
|
||||
os.makedirs("outputs", exist_ok=True)
|
||||
shutil.make_archive(final_aar_path, "zip", AAR_UNZIPPED_DIR, ".")
|
||||
os.rename(final_aar_path + ".zip", final_aar_path)
|
||||
|
||||
print("Creating local maven repo...")
|
||||
|
||||
shutil.copy(final_aar_path, path.join(ANDROID_PROJECT_DIR, "OpenCV/opencv-release.aar"))
|
||||
|
||||
print("Creating a maven repo from project sources (with sources jar and javadoc jar)...")
|
||||
cmd = ["./gradlew", "publishReleasePublicationToMyrepoRepository"]
|
||||
if args.offline:
|
||||
cmd = cmd + ["--offline"]
|
||||
subprocess.run(cmd, shell=False, cwd=ANDROID_PROJECT_DIR, check=True)
|
||||
|
||||
os.makedirs(path.join(FINAL_REPO_PATH, "org/opencv"), exist_ok=True)
|
||||
shutil.move(path.join(ANDROID_PROJECT_DIR, "OpenCV/build/repo/org/opencv", MAVEN_PACKAGE_NAME),
|
||||
path.join(FINAL_REPO_PATH, "org/opencv", MAVEN_PACKAGE_NAME))
|
||||
|
||||
print("Creating a maven repo from modified AAR (with cpp libraries)...")
|
||||
cmd = ["./gradlew", "publishModifiedPublicationToMyrepoRepository"]
|
||||
if args.offline:
|
||||
cmd = cmd + ["--offline"]
|
||||
subprocess.run(cmd, shell=False, cwd=ANDROID_PROJECT_DIR, check=True)
|
||||
|
||||
# Replacing AAR from the first maven repo with modified AAR from the second maven repo
|
||||
shutil.copytree(path.join(ANDROID_PROJECT_DIR, "OpenCV/build/repo/org/opencv", MAVEN_PACKAGE_NAME),
|
||||
path.join(FINAL_REPO_PATH, "org/opencv", MAVEN_PACKAGE_NAME),
|
||||
dirs_exist_ok=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser(description="Builds AAR with Java and shared C++ libs from OpenCV SDK")
|
||||
parser.add_argument('opencv_sdk_path')
|
||||
parser.add_argument('--android_compile_sdk', default="34")
|
||||
parser.add_argument('--android_min_sdk', default="21")
|
||||
parser.add_argument('--android_target_sdk', default="34")
|
||||
parser.add_argument('--java_version', default="17")
|
||||
parser.add_argument('--ndk_location', default="")
|
||||
parser.add_argument('--cmake_location', default="")
|
||||
parser.add_argument('--offline', action="store_true", help="Force Gradle use offline mode")
|
||||
args = parser.parse_args()
|
||||
|
||||
main(args)
|
||||
Executable
+547
@@ -0,0 +1,547 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
import os, sys
|
||||
import argparse
|
||||
import glob
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import time
|
||||
|
||||
import logging as log
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||
|
||||
class Fail(Exception):
|
||||
def __init__(self, text=None):
|
||||
self.t = text
|
||||
def __str__(self):
|
||||
return "ERROR" if self.t is None else self.t
|
||||
|
||||
def execute(cmd, shell=False):
|
||||
try:
|
||||
log.debug("Executing: %s" % cmd)
|
||||
log.info('Executing: ' + ' '.join(cmd))
|
||||
retcode = subprocess.call(cmd, shell=shell)
|
||||
if retcode < 0:
|
||||
raise Fail("Child was terminated by signal: %s" % -retcode)
|
||||
elif retcode > 0:
|
||||
raise Fail("Child returned: %s" % retcode)
|
||||
except OSError as e:
|
||||
raise Fail("Execution failed: %d / %s" % (e.errno, e.strerror))
|
||||
|
||||
def rm_one(d):
|
||||
d = os.path.abspath(d)
|
||||
if os.path.exists(d):
|
||||
if os.path.isdir(d):
|
||||
log.info("Removing dir: %s", d)
|
||||
shutil.rmtree(d)
|
||||
elif os.path.isfile(d):
|
||||
log.info("Removing file: %s", d)
|
||||
os.remove(d)
|
||||
|
||||
def check_dir(d, create=False, clean=False):
|
||||
d = os.path.abspath(d)
|
||||
log.info("Check dir %s (create: %s, clean: %s)", d, create, clean)
|
||||
if os.path.exists(d):
|
||||
if not os.path.isdir(d):
|
||||
raise Fail("Not a directory: %s" % d)
|
||||
if clean:
|
||||
for x in glob.glob(os.path.join(d, "*")):
|
||||
rm_one(x)
|
||||
else:
|
||||
if create:
|
||||
os.makedirs(d)
|
||||
return d
|
||||
|
||||
def check_executable(cmd):
|
||||
try:
|
||||
log.debug("Executing: %s" % cmd)
|
||||
result = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
|
||||
if not isinstance(result, str):
|
||||
result = result.decode("utf-8")
|
||||
log.debug("Result: %s" % (result+'\n').split('\n')[0])
|
||||
return True
|
||||
except Exception as e:
|
||||
log.debug('Failed: %s' % e)
|
||||
return False
|
||||
|
||||
def determine_opencv_version(version_hpp_path):
|
||||
# version in 2.4 - CV_VERSION_EPOCH.CV_VERSION_MAJOR.CV_VERSION_MINOR.CV_VERSION_REVISION
|
||||
# version in master - CV_VERSION_MAJOR.CV_VERSION_MINOR.CV_VERSION_REVISION-CV_VERSION_STATUS
|
||||
with open(version_hpp_path, "rt") as f:
|
||||
data = f.read()
|
||||
major = re.search(r'^#define\W+CV_VERSION_MAJOR\W+(\d+)$', data, re.MULTILINE).group(1)
|
||||
minor = re.search(r'^#define\W+CV_VERSION_MINOR\W+(\d+)$', data, re.MULTILINE).group(1)
|
||||
revision = re.search(r'^#define\W+CV_VERSION_REVISION\W+(\d+)$', data, re.MULTILINE).group(1)
|
||||
version_status = re.search(r'^#define\W+CV_VERSION_STATUS\W+"([^"]*)"$', data, re.MULTILINE).group(1)
|
||||
return "%(major)s.%(minor)s.%(revision)s%(version_status)s" % locals()
|
||||
|
||||
# shutil.move fails if dst exists
|
||||
def move_smart(src, dst):
|
||||
def move_recurse(subdir):
|
||||
s = os.path.join(src, subdir)
|
||||
d = os.path.join(dst, subdir)
|
||||
if os.path.exists(d):
|
||||
if os.path.isdir(d):
|
||||
for item in os.listdir(s):
|
||||
move_recurse(os.path.join(subdir, item))
|
||||
elif os.path.isfile(s):
|
||||
shutil.move(s, d)
|
||||
else:
|
||||
shutil.move(s, d)
|
||||
move_recurse('')
|
||||
|
||||
# shutil.copytree fails if dst exists
|
||||
def copytree_smart(src, dst):
|
||||
def copy_recurse(subdir):
|
||||
s = os.path.join(src, subdir)
|
||||
d = os.path.join(dst, subdir)
|
||||
if os.path.exists(d):
|
||||
if os.path.isdir(d):
|
||||
for item in os.listdir(s):
|
||||
copy_recurse(os.path.join(subdir, item))
|
||||
elif os.path.isfile(s):
|
||||
shutil.copy2(s, d)
|
||||
else:
|
||||
if os.path.isdir(s):
|
||||
shutil.copytree(s, d)
|
||||
elif os.path.isfile(s):
|
||||
shutil.copy2(s, d)
|
||||
copy_recurse('')
|
||||
|
||||
def get_highest_version(subdirs):
|
||||
return max(subdirs, key=lambda dir: [int(comp) for comp in os.path.split(dir)[-1].split('.')])
|
||||
|
||||
|
||||
#===================================================================================================
|
||||
|
||||
class ABI:
|
||||
def __init__(self, platform_id, name, toolchain, ndk_api_level = None, cmake_vars = dict()):
|
||||
self.platform_id = platform_id # platform code to add to apk version (for cmake)
|
||||
self.name = name # general name (official Android ABI identifier)
|
||||
self.toolchain = toolchain # toolchain identifier (for cmake)
|
||||
self.cmake_vars = dict(
|
||||
ANDROID_STL="gnustl_static",
|
||||
ANDROID_ABI=self.name,
|
||||
ANDROID_PLATFORM_ID=platform_id,
|
||||
)
|
||||
if toolchain is not None:
|
||||
self.cmake_vars['ANDROID_TOOLCHAIN_NAME'] = toolchain
|
||||
else:
|
||||
self.cmake_vars['ANDROID_TOOLCHAIN'] = 'clang'
|
||||
self.cmake_vars['ANDROID_STL'] = 'c++_shared'
|
||||
if ndk_api_level:
|
||||
self.cmake_vars['ANDROID_NATIVE_API_LEVEL'] = ndk_api_level
|
||||
self.cmake_vars.update(cmake_vars)
|
||||
def __str__(self):
|
||||
return "%s (%s)" % (self.name, self.toolchain)
|
||||
def haveIPP(self):
|
||||
return self.name == "x86" or self.name == "x86_64"
|
||||
def haveKleidiCV(self):
|
||||
return self.name == "arm64-v8a"
|
||||
|
||||
#===================================================================================================
|
||||
|
||||
class Builder:
|
||||
def __init__(self, workdir, opencvdir, config):
|
||||
self.workdir = check_dir(workdir, create=True)
|
||||
self.opencvdir = check_dir(opencvdir)
|
||||
self.config = config
|
||||
self.libdest = check_dir(os.path.join(self.workdir, "o4a"), create=True, clean=True)
|
||||
self.resultdest = check_dir(os.path.join(self.workdir, 'OpenCV-android-sdk'), create=True, clean=True)
|
||||
self.docdest = check_dir(os.path.join(self.workdir, 'OpenCV-android-sdk', 'sdk', 'java', 'javadoc'), create=True, clean=True)
|
||||
self.extra_packs = []
|
||||
self.opencv_version = determine_opencv_version(os.path.join(self.opencvdir, "modules", "core", "include", "opencv2", "core", "version.hpp"))
|
||||
self.use_ccache = False if config.no_ccache else True
|
||||
self.cmake_path = self.get_cmake()
|
||||
self.ninja_path = self.get_ninja()
|
||||
self.debug = True if config.debug else False
|
||||
self.debug_info = True if config.debug_info else False
|
||||
self.no_samples_build = True if config.no_samples_build else False
|
||||
self.hwasan = True if config.hwasan else False
|
||||
self.opencl = True if config.opencl else False
|
||||
self.no_kotlin = True if config.no_kotlin else False
|
||||
self.shared = True if config.shared else False
|
||||
self.disable = args.disable
|
||||
|
||||
def get_cmake(self):
|
||||
if not self.config.use_android_buildtools and check_executable(['cmake', '--version']):
|
||||
log.info("Using cmake from PATH")
|
||||
return 'cmake'
|
||||
# look to see if Android SDK's cmake is installed
|
||||
android_cmake = os.path.join(os.environ['ANDROID_SDK'], 'cmake')
|
||||
if os.path.exists(android_cmake):
|
||||
cmake_subdirs = [f for f in os.listdir(android_cmake) if check_executable([os.path.join(android_cmake, f, 'bin', 'cmake'), '--version'])]
|
||||
if len(cmake_subdirs) > 0:
|
||||
# there could be more than one - get the most recent
|
||||
cmake_from_sdk = os.path.join(android_cmake, get_highest_version(cmake_subdirs), 'bin', 'cmake')
|
||||
log.info("Using cmake from Android SDK: %s", cmake_from_sdk)
|
||||
return cmake_from_sdk
|
||||
raise Fail("Can't find cmake")
|
||||
|
||||
def get_ninja(self):
|
||||
if not self.config.use_android_buildtools and check_executable(['ninja', '--version']):
|
||||
log.info("Using ninja from PATH")
|
||||
return 'ninja'
|
||||
# Android SDK's cmake includes a copy of ninja - look to see if its there
|
||||
android_cmake = os.path.join(os.environ['ANDROID_SDK'], 'cmake')
|
||||
if os.path.exists(android_cmake):
|
||||
cmake_subdirs = [f for f in os.listdir(android_cmake) if check_executable([os.path.join(android_cmake, f, 'bin', 'ninja'), '--version'])]
|
||||
if len(cmake_subdirs) > 0:
|
||||
# there could be more than one - just take the first one
|
||||
ninja_from_sdk = os.path.join(android_cmake, cmake_subdirs[0], 'bin', 'ninja')
|
||||
log.info("Using ninja from Android SDK: %s", ninja_from_sdk)
|
||||
return ninja_from_sdk
|
||||
raise Fail("Can't find ninja")
|
||||
|
||||
def get_toolchain_file(self):
|
||||
if not self.config.force_opencv_toolchain:
|
||||
toolchain = os.path.join(os.environ['ANDROID_NDK'], 'build', 'cmake', 'android.toolchain.cmake')
|
||||
if os.path.exists(toolchain):
|
||||
return toolchain
|
||||
toolchain = os.path.join(SCRIPT_DIR, "android.toolchain.cmake")
|
||||
if os.path.exists(toolchain):
|
||||
return toolchain
|
||||
else:
|
||||
raise Fail("Can't find toolchain")
|
||||
|
||||
def get_engine_apk_dest(self, engdest):
|
||||
return os.path.join(engdest, "platforms", "android", "service", "engine", ".build")
|
||||
|
||||
def add_extra_pack(self, ver, path):
|
||||
if path is None:
|
||||
return
|
||||
self.extra_packs.append((ver, check_dir(path)))
|
||||
|
||||
def clean_library_build_dir(self):
|
||||
for d in ["CMakeCache.txt", "CMakeFiles/", "bin/", "libs/", "lib/", "package/", "install/samples/"]:
|
||||
rm_one(d)
|
||||
|
||||
def build_library(self, abi, do_install, no_media_ndk):
|
||||
cmd = [self.cmake_path, "-GNinja"]
|
||||
cmake_vars = dict(
|
||||
CMAKE_TOOLCHAIN_FILE=self.get_toolchain_file(),
|
||||
INSTALL_CREATE_DISTRIB="ON",
|
||||
WITH_OPENCL="OFF",
|
||||
BUILD_KOTLIN_EXTENSIONS="ON",
|
||||
WITH_IPP=("ON" if abi.haveIPP() else "OFF"),
|
||||
WITH_TBB="ON",
|
||||
BUILD_EXAMPLES="OFF",
|
||||
BUILD_TESTS="OFF",
|
||||
BUILD_PERF_TESTS="OFF",
|
||||
BUILD_DOCS="OFF",
|
||||
BUILD_ANDROID_EXAMPLES=("OFF" if self.no_samples_build else "ON"),
|
||||
INSTALL_ANDROID_EXAMPLES=("OFF" if self.no_samples_build else "ON"),
|
||||
)
|
||||
if self.ninja_path != 'ninja':
|
||||
cmake_vars['CMAKE_MAKE_PROGRAM'] = self.ninja_path
|
||||
|
||||
if self.debug:
|
||||
cmake_vars['CMAKE_BUILD_TYPE'] = "Debug"
|
||||
|
||||
if self.debug_info: # Release with debug info
|
||||
cmake_vars['BUILD_WITH_DEBUG_INFO'] = "ON"
|
||||
|
||||
if self.opencl:
|
||||
cmake_vars['WITH_OPENCL'] = "ON"
|
||||
|
||||
if self.no_kotlin:
|
||||
cmake_vars['BUILD_KOTLIN_EXTENSIONS'] = "OFF"
|
||||
|
||||
if self.shared:
|
||||
cmake_vars['BUILD_SHARED_LIBS'] = "ON"
|
||||
|
||||
if self.config.modules_list is not None:
|
||||
cmake_vars['BUILD_LIST'] = '%s' % self.config.modules_list
|
||||
|
||||
if self.config.extra_modules_path is not None:
|
||||
cmake_vars['OPENCV_EXTRA_MODULES_PATH'] = '%s' % self.config.extra_modules_path
|
||||
|
||||
if self.use_ccache == True:
|
||||
cmake_vars['NDK_CCACHE'] = 'ccache'
|
||||
if do_install:
|
||||
cmake_vars['BUILD_TESTS'] = "ON"
|
||||
cmake_vars['INSTALL_TESTS'] = "ON"
|
||||
|
||||
if no_media_ndk:
|
||||
cmake_vars['WITH_ANDROID_MEDIANDK'] = "OFF"
|
||||
|
||||
if self.hwasan and "arm64" in abi.name:
|
||||
cmake_vars['OPENCV_ENABLE_MEMORY_SANITIZER'] = "ON"
|
||||
hwasan_flags = "-fno-omit-frame-pointer -fsanitize=hwaddress"
|
||||
for s in ['OPENCV_EXTRA_C_FLAGS', 'OPENCV_EXTRA_CXX_FLAGS', 'OPENCV_EXTRA_EXE_LINKER_FLAGS',
|
||||
'OPENCV_EXTRA_SHARED_LINKER_FLAGS', 'OPENCV_EXTRA_MODULE_LINKER_FLAGS']:
|
||||
if s in cmake_vars.keys():
|
||||
cmake_vars[s] = cmake_vars[s] + ' ' + hwasan_flags
|
||||
else:
|
||||
cmake_vars[s] = hwasan_flags
|
||||
|
||||
cmake_vars.update(abi.cmake_vars)
|
||||
|
||||
if len(self.disable) > 0:
|
||||
cmake_vars.update({'WITH_%s' % f : "OFF" for f in self.disable})
|
||||
|
||||
cmd += [ "-D%s='%s'" % (k, v) for (k, v) in cmake_vars.items() if v is not None]
|
||||
cmd.append(self.opencvdir)
|
||||
execute(cmd)
|
||||
# full parallelism for C++ compilation tasks
|
||||
build_targets = ["opencv_modules"]
|
||||
if do_install:
|
||||
build_targets.append("opencv_tests")
|
||||
execute([self.ninja_path, *build_targets])
|
||||
# limit parallelism for building samples (avoid huge memory consumption)
|
||||
if self.no_samples_build:
|
||||
execute([self.ninja_path, "install" if (self.debug_info or self.debug) else "install/strip"])
|
||||
else:
|
||||
execute([self.ninja_path, "-j1", "install" if (self.debug_info or self.debug) else "install/strip"])
|
||||
|
||||
def build_javadoc(self):
|
||||
classpaths = []
|
||||
for dir, _, files in os.walk(os.environ["ANDROID_SDK"]):
|
||||
for f in files:
|
||||
if f == "android.jar" or f == "annotations.jar":
|
||||
classpaths.append(os.path.join(dir, f))
|
||||
srcdir = os.path.join(self.resultdest, 'sdk', 'java', 'src')
|
||||
dstdir = self.docdest
|
||||
# HACK: create stubs for auto-generated files to satisfy imports
|
||||
with open(os.path.join(srcdir, 'org', 'opencv', 'BuildConfig.java'), 'wt') as fs:
|
||||
fs.write("package org.opencv;\n public class BuildConfig {\n}")
|
||||
fs.close()
|
||||
with open(os.path.join(srcdir, 'org', 'opencv', 'R.java'), 'wt') as fs:
|
||||
fs.write("package org.opencv;\n public class R {\n}")
|
||||
fs.close()
|
||||
|
||||
# synchronize with modules/java/jar/build.xml.in
|
||||
shutil.copy2(os.path.join(SCRIPT_DIR, '../../doc/mymath.js'), dstdir)
|
||||
cmd = [
|
||||
"javadoc",
|
||||
'-windowtitle', 'OpenCV %s Java documentation' % self.opencv_version,
|
||||
'-doctitle', 'OpenCV Java documentation (%s)' % self.opencv_version,
|
||||
"-nodeprecated",
|
||||
"-public",
|
||||
'-sourcepath', srcdir,
|
||||
'-encoding', 'UTF-8',
|
||||
'-charset', 'UTF-8',
|
||||
'-docencoding', 'UTF-8',
|
||||
'--allow-script-in-comments',
|
||||
'-header',
|
||||
'''
|
||||
<script>
|
||||
var url = window.location.href;
|
||||
var pos = url.lastIndexOf('/javadoc/');
|
||||
url = pos >= 0 ? (url.substring(0, pos) + '/javadoc/mymath.js') : (window.location.origin + '/mymath.js');
|
||||
var script = document.createElement('script');
|
||||
script.src = '%s/MathJax.js?config=TeX-AMS-MML_HTMLorMML,' + url;
|
||||
document.getElementsByTagName('head')[0].appendChild(script);
|
||||
</script>
|
||||
''' % 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0',
|
||||
'-bottom', 'Generated on %s / OpenCV %s' % (time.strftime("%Y-%m-%d %H:%M:%S"), self.opencv_version),
|
||||
"-d", dstdir,
|
||||
"-classpath", ":".join(classpaths),
|
||||
'-subpackages', 'org.opencv'
|
||||
]
|
||||
execute(cmd)
|
||||
# HACK: remove temporary files needed to satisfy javadoc imports
|
||||
os.remove(os.path.join(srcdir, 'org', 'opencv', 'BuildConfig.java'))
|
||||
os.remove(os.path.join(srcdir, 'org', 'opencv', 'R.java'))
|
||||
|
||||
def gather_results(self):
|
||||
# Copy all files
|
||||
root = os.path.join(self.libdest, "install")
|
||||
for item in os.listdir(root):
|
||||
src = os.path.join(root, item)
|
||||
dst = os.path.join(self.resultdest, item)
|
||||
if os.path.isdir(src):
|
||||
log.info("Copy dir: %s", item)
|
||||
if self.config.force_copy:
|
||||
copytree_smart(src, dst)
|
||||
else:
|
||||
move_smart(src, dst)
|
||||
elif os.path.isfile(src):
|
||||
log.info("Copy file: %s", item)
|
||||
if self.config.force_copy:
|
||||
shutil.copy2(src, dst)
|
||||
else:
|
||||
shutil.move(src, dst)
|
||||
|
||||
def get_ndk_dir():
|
||||
# look to see if Android NDK is installed
|
||||
android_sdk_ndk = os.path.join(os.environ["ANDROID_SDK"], 'ndk')
|
||||
android_sdk_ndk_bundle = os.path.join(os.environ["ANDROID_SDK"], 'ndk-bundle')
|
||||
if os.path.exists(android_sdk_ndk):
|
||||
ndk_subdirs = [f for f in os.listdir(android_sdk_ndk) if os.path.exists(os.path.join(android_sdk_ndk, f, 'package.xml'))]
|
||||
if len(ndk_subdirs) > 0:
|
||||
# there could be more than one - get the most recent
|
||||
ndk_from_sdk = os.path.join(android_sdk_ndk, get_highest_version(ndk_subdirs))
|
||||
log.info("Using NDK (side-by-side) from Android SDK: %s", ndk_from_sdk)
|
||||
return ndk_from_sdk
|
||||
if os.path.exists(os.path.join(android_sdk_ndk_bundle, 'package.xml')):
|
||||
log.info("Using NDK bundle from Android SDK: %s", android_sdk_ndk_bundle)
|
||||
return android_sdk_ndk_bundle
|
||||
return None
|
||||
|
||||
def check_cmake_flag_enabled(cmake_file, flag_name, strict=True):
|
||||
print(f"Checking build flag '{flag_name}' in: {cmake_file}")
|
||||
|
||||
if not os.path.isfile(cmake_file):
|
||||
msg = f"ERROR: File {cmake_file} does not exist."
|
||||
if strict:
|
||||
print(msg)
|
||||
sys.exit(1)
|
||||
else:
|
||||
print("WARNING:", msg)
|
||||
return
|
||||
|
||||
with open(cmake_file, 'r') as file:
|
||||
for line in file:
|
||||
if line.strip().startswith(f"{flag_name}="):
|
||||
value = line.strip().split('=')[1]
|
||||
if value == '1' or value == 'ON':
|
||||
print(f"{flag_name}=1 found. Support is enabled.")
|
||||
return
|
||||
else:
|
||||
msg = f"ERROR: {flag_name} is set to {value}, expected 1."
|
||||
if strict:
|
||||
print(msg)
|
||||
sys.exit(1)
|
||||
else:
|
||||
print("WARNING:", msg)
|
||||
return
|
||||
msg = f"ERROR: {flag_name} not found in {os.path.basename(cmake_file)}."
|
||||
if strict:
|
||||
print(msg)
|
||||
sys.exit(1)
|
||||
else:
|
||||
print("WARNING:", msg)
|
||||
|
||||
#===================================================================================================
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser(description='Build OpenCV for Android SDK')
|
||||
parser.add_argument("work_dir", nargs='?', default='.', help="Working directory (and output)")
|
||||
parser.add_argument("opencv_dir", nargs='?', default=os.path.join(SCRIPT_DIR, '../..'), help="Path to OpenCV source dir")
|
||||
parser.add_argument('--config', default='ndk-18-api-level-21.config.py', type=str, help="Package build configuration", )
|
||||
parser.add_argument('--ndk_path', help="Path to Android NDK to use for build")
|
||||
parser.add_argument('--sdk_path', help="Path to Android SDK to use for build")
|
||||
parser.add_argument('--use_android_buildtools', action="store_true", help='Use cmake/ninja build tools from Android SDK')
|
||||
parser.add_argument("--modules_list", help="List of modules to include for build")
|
||||
parser.add_argument("--extra_modules_path", help="Path to extra modules to use for build")
|
||||
parser.add_argument('--sign_with', help="Certificate to sign the Manager apk")
|
||||
parser.add_argument('--build_doc', action="store_true", help="Build javadoc")
|
||||
parser.add_argument('--no_ccache', action="store_true", help="Do not use ccache during library build")
|
||||
parser.add_argument('--force_copy', action="store_true", help="Do not use file move during library build (useful for debug)")
|
||||
parser.add_argument('--force_opencv_toolchain', action="store_true", help="Do not use toolchain from Android NDK")
|
||||
parser.add_argument('--debug', action="store_true", help="Build 'Debug' binaries (CMAKE_BUILD_TYPE=Debug)")
|
||||
parser.add_argument('--debug_info', action="store_true", help="Build with debug information (useful for Release mode: BUILD_WITH_DEBUG_INFO=ON)")
|
||||
parser.add_argument('--no_samples_build', action="store_true", help="Do not build samples (speeds up build)")
|
||||
parser.add_argument('--opencl', action="store_true", help="Enable OpenCL support")
|
||||
parser.add_argument('--no_kotlin', action="store_true", help="Disable Kotlin extensions")
|
||||
parser.add_argument('--shared', action="store_true", help="Build shared libraries")
|
||||
parser.add_argument('--no_media_ndk', action="store_true", help="Do not link Media NDK (required for video I/O support)")
|
||||
parser.add_argument('--hwasan', action="store_true", help="Enable Hardware Address Sanitizer on ARM64")
|
||||
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"')
|
||||
parser.add_argument('--no-strict-dependencies',action='store_false',dest='strict_dependencies',help='Disable strict dependency checking (default: strict mode ON)')
|
||||
args = parser.parse_args()
|
||||
|
||||
log.basicConfig(format='%(message)s', level=log.DEBUG)
|
||||
log.debug("Args: %s", args)
|
||||
|
||||
if args.ndk_path is not None:
|
||||
os.environ["ANDROID_NDK"] = args.ndk_path
|
||||
if args.sdk_path is not None:
|
||||
os.environ["ANDROID_SDK"] = args.sdk_path
|
||||
|
||||
if not 'ANDROID_HOME' in os.environ and 'ANDROID_SDK' in os.environ:
|
||||
os.environ['ANDROID_HOME'] = os.environ["ANDROID_SDK"]
|
||||
|
||||
if not 'ANDROID_SDK' in os.environ:
|
||||
raise Fail("SDK location not set. Either pass --sdk_path or set ANDROID_SDK environment variable")
|
||||
|
||||
# look for an NDK installed with the Android SDK
|
||||
if not 'ANDROID_NDK' in os.environ and 'ANDROID_SDK' in os.environ:
|
||||
sdk_ndk_dir = get_ndk_dir()
|
||||
if sdk_ndk_dir:
|
||||
os.environ['ANDROID_NDK'] = sdk_ndk_dir
|
||||
|
||||
if not 'ANDROID_NDK' in os.environ:
|
||||
raise Fail("NDK location not set. Either pass --ndk_path or set ANDROID_NDK environment variable")
|
||||
|
||||
show_samples_build_warning = False
|
||||
#also set ANDROID_NDK_HOME (needed by the gradle build)
|
||||
if not 'ANDROID_NDK_HOME' in os.environ and 'ANDROID_NDK' in os.environ:
|
||||
os.environ['ANDROID_NDK_HOME'] = os.environ["ANDROID_NDK"]
|
||||
show_samples_build_warning = True
|
||||
|
||||
if not check_executable(['ccache', '--version']):
|
||||
log.info("ccache not found - disabling ccache support")
|
||||
args.no_ccache = True
|
||||
|
||||
if os.path.realpath(args.work_dir) == os.path.realpath(SCRIPT_DIR):
|
||||
raise Fail("Specify workdir (building from script directory is not supported)")
|
||||
if os.path.realpath(args.work_dir) == os.path.realpath(args.opencv_dir):
|
||||
raise Fail("Specify workdir (building from OpenCV source directory is not supported)")
|
||||
|
||||
# Relative paths become invalid in sub-directories
|
||||
if args.opencv_dir is not None and not os.path.isabs(args.opencv_dir):
|
||||
args.opencv_dir = os.path.abspath(args.opencv_dir)
|
||||
if args.extra_modules_path is not None and not os.path.isabs(args.extra_modules_path):
|
||||
args.extra_modules_path = os.path.abspath(args.extra_modules_path)
|
||||
|
||||
cpath = args.config
|
||||
if not os.path.exists(cpath):
|
||||
cpath = os.path.join(SCRIPT_DIR, cpath)
|
||||
if not os.path.exists(cpath):
|
||||
raise Fail('Config "%s" is missing' % args.config)
|
||||
with open(cpath, 'r') as f:
|
||||
cfg = f.read()
|
||||
print("Package configuration:")
|
||||
print('=' * 80)
|
||||
print(cfg.strip())
|
||||
print('=' * 80)
|
||||
|
||||
ABIs = None # make flake8 happy
|
||||
exec(compile(cfg, cpath, 'exec'))
|
||||
|
||||
log.info("Android NDK path: %s", os.environ["ANDROID_NDK"])
|
||||
log.info("Android SDK path: %s", os.environ["ANDROID_SDK"])
|
||||
|
||||
builder = Builder(args.work_dir, args.opencv_dir, args)
|
||||
|
||||
log.info("Detected OpenCV version: %s", builder.opencv_version)
|
||||
|
||||
for i, abi in enumerate(ABIs):
|
||||
do_install = (i == 0)
|
||||
|
||||
log.info("=====")
|
||||
log.info("===== Building library for %s", abi)
|
||||
log.info("=====")
|
||||
|
||||
os.chdir(builder.libdest)
|
||||
builder.clean_library_build_dir()
|
||||
builder.build_library(abi, do_install, args.no_media_ndk)
|
||||
|
||||
#Check HAVE_IPP x86 / x86_64
|
||||
if abi.haveIPP():
|
||||
log.info("Checking HAVE_IPP for ABI: %s", abi.name)
|
||||
check_cmake_flag_enabled(os.path.join(builder.libdest,"CMakeVars.txt"), "HAVE_IPP", strict=args.strict_dependencies)
|
||||
|
||||
#Check HAVE_KLEIDICV for armv8
|
||||
if abi.haveKleidiCV():
|
||||
log.info("Checking HAVE_KLEIDICV for ABI: %s", abi.name)
|
||||
check_cmake_flag_enabled(os.path.join(builder.libdest,"CMakeVars.txt"), "HAVE_KLEIDICV", strict=args.strict_dependencies)
|
||||
|
||||
builder.gather_results()
|
||||
|
||||
if args.build_doc:
|
||||
builder.build_javadoc()
|
||||
|
||||
log.info("=====")
|
||||
log.info("===== Build finished")
|
||||
log.info("=====")
|
||||
if show_samples_build_warning:
|
||||
#give a hint how to solve "Gradle sync failed: NDK not configured."
|
||||
log.info("ANDROID_NDK_HOME environment variable required by the samples project is not set")
|
||||
log.info("SDK location: %s", builder.resultdest)
|
||||
log.info("Documentation location: %s", builder.docdest)
|
||||
Executable
+258
@@ -0,0 +1,258 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
import argparse
|
||||
import json
|
||||
from os import path
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
|
||||
from build_java_shared_aar import cleanup, fill_template, get_compiled_aar_path, get_opencv_version, get_ndk_version
|
||||
|
||||
|
||||
ANDROID_PROJECT_TEMPLATE_DIR = path.join(path.dirname(__file__), "aar-template")
|
||||
TEMP_DIR = "build_static"
|
||||
ANDROID_PROJECT_DIR = path.join(TEMP_DIR, "AndroidProject")
|
||||
COMPILED_AAR_PATH_1 = path.join(ANDROID_PROJECT_DIR, "OpenCV/build/outputs/aar/OpenCV-release.aar") # original package name
|
||||
COMPILED_AAR_PATH_2 = path.join(ANDROID_PROJECT_DIR, "OpenCV/build/outputs/aar/opencv-release.aar") # lower case package name
|
||||
AAR_UNZIPPED_DIR = path.join(TEMP_DIR, "aar_unzipped")
|
||||
FINAL_AAR_PATH_TEMPLATE = "outputs/opencv_static_<OPENCV_VERSION>.aar"
|
||||
FINAL_REPO_PATH = "outputs/maven_repo"
|
||||
MAVEN_PACKAGE_NAME = "opencv-static"
|
||||
|
||||
|
||||
def get_list_of_opencv_libs(sdk_dir):
|
||||
files = os.listdir(path.join(sdk_dir, "sdk/native/staticlibs/arm64-v8a"))
|
||||
libs = [f[3:-2] for f in files if f[:3] == "lib" and f[-2:] == ".a"]
|
||||
return libs
|
||||
|
||||
def get_list_of_3rdparty_libs(sdk_dir, abis):
|
||||
libs = []
|
||||
for abi in abis:
|
||||
files = os.listdir(path.join(sdk_dir, "sdk/native/3rdparty/libs/" + abi))
|
||||
cur_libs = [f[3:-2] for f in files if f[:3] == "lib" and f[-2:] == ".a"]
|
||||
for lib in cur_libs:
|
||||
if lib not in libs:
|
||||
libs.append(lib)
|
||||
return libs
|
||||
|
||||
def add_printing_linked_libs(sdk_dir, opencv_libs):
|
||||
"""
|
||||
Modifies CMakeLists.txt file in Android project, so it prints linked libraries for each OpenCV library"
|
||||
"""
|
||||
sdk_jni_dir = sdk_dir + "/sdk/native/jni"
|
||||
with open(path.join(ANDROID_PROJECT_DIR, "OpenCV/src/main/cpp/CMakeLists.txt"), "a") as f:
|
||||
f.write('\nset(OpenCV_DIR "' + sdk_jni_dir + '")\n')
|
||||
f.write('find_package(OpenCV REQUIRED)\n')
|
||||
for lib_name in opencv_libs:
|
||||
output_filename_prefix = "linkedlibs." + lib_name + "."
|
||||
f.write('get_target_property(OUT "' + lib_name + '" INTERFACE_LINK_LIBRARIES)\n')
|
||||
f.write('file(WRITE "' + output_filename_prefix + '${ANDROID_ABI}.txt" "${OUT}")\n')
|
||||
|
||||
def read_linked_libs(lib_name, abis):
|
||||
"""
|
||||
Reads linked libs for each OpenCV library from files, that was generated by gradle. See add_printing_linked_libs()
|
||||
"""
|
||||
deps_lists = []
|
||||
for abi in abis:
|
||||
with open(path.join(ANDROID_PROJECT_DIR, "OpenCV/src/main/cpp", f"linkedlibs.{lib_name}.{abi}.txt")) as f:
|
||||
text = f.read()
|
||||
linked_libs = text.split(";")
|
||||
linked_libs = [x.replace("$<LINK_ONLY:", "").replace(">", "") for x in linked_libs]
|
||||
deps_lists.append(linked_libs)
|
||||
|
||||
return merge_dependencies_lists(deps_lists)
|
||||
|
||||
def merge_dependencies_lists(deps_lists):
|
||||
"""
|
||||
One library may have different dependencies for different ABIS.
|
||||
We need to merge them into one list with all the dependencies preserving the order.
|
||||
"""
|
||||
result = []
|
||||
for d_list in deps_lists:
|
||||
for i in range(len(d_list)):
|
||||
if d_list[i] not in result:
|
||||
if i == 0:
|
||||
result.append(d_list[i])
|
||||
else:
|
||||
index = result.index(d_list[i-1])
|
||||
result = result[:index + 1] + [d_list[i]] + result[index + 1:]
|
||||
|
||||
return result
|
||||
|
||||
def convert_deps_list_to_prefab(linked_libs, opencv_libs, external_libs):
|
||||
"""
|
||||
Converting list of dependencies into prefab format.
|
||||
"""
|
||||
prefab_linked_libs = []
|
||||
for lib in linked_libs:
|
||||
if (lib in opencv_libs) or (lib in external_libs):
|
||||
prefab_linked_libs.append(":" + lib)
|
||||
elif (lib[:3] == "lib" and lib[3:] in external_libs):
|
||||
prefab_linked_libs.append(":" + lib[3:])
|
||||
elif lib == "ocv.3rdparty.android_mediandk":
|
||||
prefab_linked_libs += ["-landroid", "-llog", "-lmediandk"]
|
||||
print("Warning: manualy handled ocv.3rdparty.android_mediandk dependency")
|
||||
elif lib == "ocv.3rdparty.flatbuffers":
|
||||
print("Warning: manualy handled ocv.3rdparty.flatbuffers dependency")
|
||||
elif lib.startswith("ocv.3rdparty"):
|
||||
raise Exception("Unknown lib " + lib)
|
||||
else:
|
||||
prefab_linked_libs.append("-l" + lib)
|
||||
return prefab_linked_libs
|
||||
|
||||
def main(args):
|
||||
opencv_version = get_opencv_version(args.opencv_sdk_path)
|
||||
ndk_version = get_ndk_version(args.ndk_location)
|
||||
print("Detected ndk_version:", ndk_version)
|
||||
abis = os.listdir(path.join(args.opencv_sdk_path, "sdk/native/libs"))
|
||||
final_aar_path = FINAL_AAR_PATH_TEMPLATE.replace("<OPENCV_VERSION>", opencv_version)
|
||||
sdk_dir = args.opencv_sdk_path
|
||||
|
||||
print("Removing data from previous runs...")
|
||||
cleanup([TEMP_DIR, final_aar_path, path.join(FINAL_REPO_PATH, "org/opencv", MAVEN_PACKAGE_NAME)])
|
||||
|
||||
print("Preparing Android project...")
|
||||
# ANDROID_PROJECT_TEMPLATE_DIR contains an Android project template that creates AAR
|
||||
shutil.copytree(ANDROID_PROJECT_TEMPLATE_DIR, ANDROID_PROJECT_DIR)
|
||||
|
||||
# Configuring the Android project to static C++ libs version
|
||||
fill_template(path.join(ANDROID_PROJECT_DIR, "OpenCV/build.gradle.template"),
|
||||
path.join(ANDROID_PROJECT_DIR, "OpenCV/build.gradle"),
|
||||
{"LIB_NAME": "templib",
|
||||
"LIB_TYPE": "c++_static",
|
||||
"PACKAGE_NAME": MAVEN_PACKAGE_NAME,
|
||||
"OPENCV_VERSION": opencv_version,
|
||||
"NDK_VERSION": ndk_version,
|
||||
"COMPILE_SDK": args.android_compile_sdk,
|
||||
"MIN_SDK": args.android_min_sdk,
|
||||
"TARGET_SDK": args.android_target_sdk,
|
||||
"ABI_FILTERS": ", ".join(['"' + x + '"' for x in abis]),
|
||||
"JAVA_VERSION": args.java_version,
|
||||
})
|
||||
fill_template(path.join(ANDROID_PROJECT_DIR, "OpenCV/src/main/cpp/CMakeLists.txt.template"),
|
||||
path.join(ANDROID_PROJECT_DIR, "OpenCV/src/main/cpp/CMakeLists.txt"),
|
||||
{"LIB_NAME": "templib", "LIB_TYPE": "STATIC"})
|
||||
|
||||
local_props = ""
|
||||
if args.ndk_location:
|
||||
local_props += "ndk.dir=" + args.ndk_location + "\n"
|
||||
if args.cmake_location:
|
||||
local_props += "cmake.dir=" + args.cmake_location + "\n"
|
||||
|
||||
if local_props:
|
||||
with open(path.join(ANDROID_PROJECT_DIR, "local.properties"), "wt") as f:
|
||||
f.write(local_props)
|
||||
|
||||
opencv_libs = get_list_of_opencv_libs(sdk_dir)
|
||||
external_libs = get_list_of_3rdparty_libs(sdk_dir, abis)
|
||||
|
||||
add_printing_linked_libs(sdk_dir, opencv_libs)
|
||||
|
||||
print("Running gradle assembleRelease...")
|
||||
cmd = ["./gradlew", "assembleRelease"]
|
||||
if args.offline:
|
||||
cmd = cmd + ["--offline"]
|
||||
# Running gradle to build the Android project
|
||||
subprocess.run(cmd, shell=False, cwd=ANDROID_PROJECT_DIR, check=True)
|
||||
|
||||
# The created AAR package contains only one empty libtemplib.a library.
|
||||
# We need to add OpenCV libraries manually.
|
||||
# AAR package is just a zip archive
|
||||
complied_aar_path = get_compiled_aar_path(COMPILED_AAR_PATH_1, COMPILED_AAR_PATH_2) # two possible paths
|
||||
shutil.unpack_archive(complied_aar_path, AAR_UNZIPPED_DIR, "zip")
|
||||
|
||||
print("Adding libs to AAR...")
|
||||
|
||||
# Copying 3rdparty libs from SDK into the AAR
|
||||
for lib in external_libs:
|
||||
for abi in abis:
|
||||
os.makedirs(path.join(AAR_UNZIPPED_DIR, "prefab/modules/" + lib + "/libs/android." + abi))
|
||||
if path.exists(path.join(sdk_dir, "sdk/native/3rdparty/libs/" + abi, "lib" + lib + ".a")):
|
||||
shutil.copy(path.join(sdk_dir, "sdk/native/3rdparty/libs/" + abi, "lib" + lib + ".a"),
|
||||
path.join(AAR_UNZIPPED_DIR, "prefab/modules/" + lib + "/libs/android." + abi, "lib" + lib + ".a"))
|
||||
else:
|
||||
# One OpenCV library may have different dependency lists for different ABIs, but we can write only one
|
||||
# full dependency list for all ABIs. So we just add empty .a library if this ABI doesn't have this dependency.
|
||||
shutil.copy(path.join(AAR_UNZIPPED_DIR, "prefab/modules/templib/libs/android." + abi, "libtemplib.a"),
|
||||
path.join(AAR_UNZIPPED_DIR, "prefab/modules/" + lib + "/libs/android." + abi, "lib" + lib + ".a"))
|
||||
shutil.copy(path.join(AAR_UNZIPPED_DIR, "prefab/modules/templib/libs/android." + abi + "/abi.json"),
|
||||
path.join(AAR_UNZIPPED_DIR, "prefab/modules/" + lib + "/libs/android." + abi + "/abi.json"))
|
||||
shutil.copy(path.join(AAR_UNZIPPED_DIR, "prefab/modules/templib/module.json"),
|
||||
path.join(AAR_UNZIPPED_DIR, "prefab/modules/" + lib + "/module.json"))
|
||||
|
||||
# Copying OpenV libs from SDK into the AAR
|
||||
for lib in opencv_libs:
|
||||
for abi in abis:
|
||||
os.makedirs(path.join(AAR_UNZIPPED_DIR, "prefab/modules/" + lib + "/libs/android." + abi))
|
||||
shutil.copy(path.join(sdk_dir, "sdk/native/staticlibs/" + abi, "lib" + lib + ".a"),
|
||||
path.join(AAR_UNZIPPED_DIR, "prefab/modules/" + lib + "/libs/android." + abi, "lib" + lib + ".a"))
|
||||
shutil.copy(path.join(AAR_UNZIPPED_DIR, "prefab/modules/templib/libs/android." + abi + "/abi.json"),
|
||||
path.join(AAR_UNZIPPED_DIR, "prefab/modules/" + lib + "/libs/android." + abi + "/abi.json"))
|
||||
os.makedirs(path.join(AAR_UNZIPPED_DIR, "prefab/modules/" + lib + "/include/opencv2"))
|
||||
shutil.copy(path.join(sdk_dir, "sdk/native/jni/include/opencv2/" + lib.replace("opencv_", "") + ".hpp"),
|
||||
path.join(AAR_UNZIPPED_DIR, "prefab/modules/" + lib + "/include/opencv2/" + lib.replace("opencv_", "") + ".hpp"))
|
||||
shutil.copytree(path.join(sdk_dir, "sdk/native/jni/include/opencv2/" + lib.replace("opencv_", "")),
|
||||
path.join(AAR_UNZIPPED_DIR, "prefab/modules/" + lib + "/include/opencv2/" + lib.replace("opencv_", "")))
|
||||
|
||||
# Adding dependencies list
|
||||
module_json_text = {
|
||||
"export_libraries": convert_deps_list_to_prefab(read_linked_libs(lib, abis), opencv_libs, external_libs),
|
||||
"android": {},
|
||||
}
|
||||
with open(path.join(AAR_UNZIPPED_DIR, "prefab/modules/" + lib + "/module.json"), "w") as f:
|
||||
json.dump(module_json_text, f)
|
||||
|
||||
for h_file in ("cvconfig.h", "opencv.hpp", "opencv_modules.hpp"):
|
||||
shutil.copy(path.join(sdk_dir, "sdk/native/jni/include/opencv2/" + h_file),
|
||||
path.join(AAR_UNZIPPED_DIR, "prefab/modules/opencv_core/include/opencv2/" + h_file))
|
||||
|
||||
|
||||
shutil.rmtree(path.join(AAR_UNZIPPED_DIR, "prefab/modules/templib"))
|
||||
|
||||
# Creating final AAR zip archive
|
||||
os.makedirs("outputs", exist_ok=True)
|
||||
shutil.make_archive(final_aar_path, "zip", AAR_UNZIPPED_DIR, ".")
|
||||
os.rename(final_aar_path + ".zip", final_aar_path)
|
||||
|
||||
print("Creating local maven repo...")
|
||||
|
||||
shutil.copy(final_aar_path, path.join(ANDROID_PROJECT_DIR, "OpenCV/opencv-release.aar"))
|
||||
|
||||
print("Creating a maven repo from project sources (with sources jar and javadoc jar)...")
|
||||
cmd = ["./gradlew", "publishReleasePublicationToMyrepoRepository"]
|
||||
if args.offline:
|
||||
cmd = cmd + ["--offline"]
|
||||
subprocess.run(cmd, shell=False, cwd=ANDROID_PROJECT_DIR, check=True)
|
||||
|
||||
os.makedirs(path.join(FINAL_REPO_PATH, "org/opencv"), exist_ok=True)
|
||||
shutil.move(path.join(ANDROID_PROJECT_DIR, "OpenCV/build/repo/org/opencv", MAVEN_PACKAGE_NAME),
|
||||
path.join(FINAL_REPO_PATH, "org/opencv", MAVEN_PACKAGE_NAME))
|
||||
|
||||
print("Creating a maven repo from modified AAR (with cpp libraries)...")
|
||||
cmd = ["./gradlew", "publishModifiedPublicationToMyrepoRepository"]
|
||||
if args.offline:
|
||||
cmd = cmd + ["--offline"]
|
||||
subprocess.run(cmd, shell=False, cwd=ANDROID_PROJECT_DIR, check=True)
|
||||
|
||||
# Replacing AAR from the first maven repo with modified AAR from the second maven repo
|
||||
shutil.copytree(path.join(ANDROID_PROJECT_DIR, "OpenCV/build/repo/org/opencv", MAVEN_PACKAGE_NAME),
|
||||
path.join(FINAL_REPO_PATH, "org/opencv", MAVEN_PACKAGE_NAME),
|
||||
dirs_exist_ok=True)
|
||||
|
||||
print("Done")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser(description="Builds AAR with static C++ libs from OpenCV SDK")
|
||||
parser.add_argument('opencv_sdk_path')
|
||||
parser.add_argument('--android_compile_sdk', default="34")
|
||||
parser.add_argument('--android_min_sdk', default="21")
|
||||
parser.add_argument('--android_target_sdk', default="34")
|
||||
parser.add_argument('--java_version', default="1_8")
|
||||
parser.add_argument('--ndk_location', default="")
|
||||
parser.add_argument('--cmake_location', default="")
|
||||
parser.add_argument('--offline', action="store_true", help="Force Gradle use offline mode")
|
||||
args = parser.parse_args()
|
||||
|
||||
main(args)
|
||||
@@ -0,0 +1,6 @@
|
||||
ABIs = [
|
||||
ABI("2", "armeabi-v7a", None, 21, cmake_vars=dict(ANDROID_ABI='armeabi-v7a with NEON')),
|
||||
ABI("3", "arm64-v8a", None, 21, cmake_vars=dict(ANDROID_SUPPORT_FLEXIBLE_PAGE_SIZES='ON')),
|
||||
ABI("5", "x86_64", None, 21, cmake_vars=dict(ANDROID_SUPPORT_FLEXIBLE_PAGE_SIZES='ON')),
|
||||
ABI("4", "x86", None, 21),
|
||||
]
|
||||
@@ -0,0 +1,6 @@
|
||||
ABIs = [
|
||||
ABI("2", "armeabi-v7a", None, 21, cmake_vars=dict(ANDROID_ABI='armeabi-v7a with NEON', WITH_FASTCV='ON')),
|
||||
ABI("3", "arm64-v8a", None, 21, cmake_vars=dict(ANDROID_SUPPORT_FLEXIBLE_PAGE_SIZES='ON', WITH_FASTCV='ON')),
|
||||
ABI("5", "x86_64", None, 21, cmake_vars=dict(ANDROID_SUPPORT_FLEXIBLE_PAGE_SIZES='ON')),
|
||||
ABI("4", "x86", None, 21),
|
||||
]
|
||||
@@ -0,0 +1,17 @@
|
||||
# Project-wide Gradle settings.
|
||||
|
||||
# IDE (e.g. Android Studio) users:
|
||||
# Gradle settings configured through the IDE *will override*
|
||||
# any settings specified in this file.
|
||||
|
||||
# For more details on how to configure your build environment visit
|
||||
# http://www.gradle.org/docs/current/userguide/build_environment.html
|
||||
|
||||
# Specifies the JVM arguments used for the daemon process.
|
||||
# The setting is particularly useful for tweaking memory settings.
|
||||
org.gradle.jvmargs=-Xmx2g
|
||||
|
||||
# When configured, Gradle will run in incubating parallel mode.
|
||||
# This option should only be used with decoupled projects. More details, visit
|
||||
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
|
||||
# org.gradle.parallel=true
|
||||
Binary file not shown.
@@ -0,0 +1,5 @@
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-@GRADLE_VERSION@-all.zip
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
+172
@@ -0,0 +1,172 @@
|
||||
#!/usr/bin/env sh
|
||||
|
||||
##############################################################################
|
||||
##
|
||||
## Gradle start up script for UN*X
|
||||
##
|
||||
##############################################################################
|
||||
|
||||
# Attempt to set APP_HOME
|
||||
# Resolve links: $0 may be a link
|
||||
PRG="$0"
|
||||
# Need this for relative symlinks.
|
||||
while [ -h "$PRG" ] ; do
|
||||
ls=`ls -ld "$PRG"`
|
||||
link=`expr "$ls" : '.*-> \(.*\)$'`
|
||||
if expr "$link" : '/.*' > /dev/null; then
|
||||
PRG="$link"
|
||||
else
|
||||
PRG=`dirname "$PRG"`"/$link"
|
||||
fi
|
||||
done
|
||||
SAVED="`pwd`"
|
||||
cd "`dirname \"$PRG\"`/" >/dev/null
|
||||
APP_HOME="`pwd -P`"
|
||||
cd "$SAVED" >/dev/null
|
||||
|
||||
APP_NAME="Gradle"
|
||||
APP_BASE_NAME=`basename "$0"`
|
||||
|
||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS='-Dfile.encoding=UTF-8 "-Xmx64m"'
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD="maximum"
|
||||
|
||||
warn () {
|
||||
echo "$*"
|
||||
}
|
||||
|
||||
die () {
|
||||
echo
|
||||
echo "$*"
|
||||
echo
|
||||
exit 1
|
||||
}
|
||||
|
||||
# OS specific support (must be 'true' or 'false').
|
||||
cygwin=false
|
||||
msys=false
|
||||
darwin=false
|
||||
nonstop=false
|
||||
case "`uname`" in
|
||||
CYGWIN* )
|
||||
cygwin=true
|
||||
;;
|
||||
Darwin* )
|
||||
darwin=true
|
||||
;;
|
||||
MINGW* )
|
||||
msys=true
|
||||
;;
|
||||
NONSTOP* )
|
||||
nonstop=true
|
||||
;;
|
||||
esac
|
||||
|
||||
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
|
||||
|
||||
# Determine the Java command to use to start the JVM.
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD="$JAVA_HOME/jre/sh/java"
|
||||
else
|
||||
JAVACMD="$JAVA_HOME/bin/java"
|
||||
fi
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
else
|
||||
JAVACMD="java"
|
||||
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
|
||||
# Increase the maximum file descriptors if we can.
|
||||
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
|
||||
MAX_FD_LIMIT=`ulimit -H -n`
|
||||
if [ $? -eq 0 ] ; then
|
||||
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
|
||||
MAX_FD="$MAX_FD_LIMIT"
|
||||
fi
|
||||
ulimit -n $MAX_FD
|
||||
if [ $? -ne 0 ] ; then
|
||||
warn "Could not set maximum file descriptor limit: $MAX_FD"
|
||||
fi
|
||||
else
|
||||
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
|
||||
fi
|
||||
fi
|
||||
|
||||
# For Darwin, add options to specify how the application appears in the dock
|
||||
if $darwin; then
|
||||
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
|
||||
fi
|
||||
|
||||
# For Cygwin, switch paths to Windows format before running java
|
||||
if $cygwin ; then
|
||||
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
|
||||
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
|
||||
JAVACMD=`cygpath --unix "$JAVACMD"`
|
||||
|
||||
# We build the pattern for arguments to be converted via cygpath
|
||||
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
|
||||
SEP=""
|
||||
for dir in $ROOTDIRSRAW ; do
|
||||
ROOTDIRS="$ROOTDIRS$SEP$dir"
|
||||
SEP="|"
|
||||
done
|
||||
OURCYGPATTERN="(^($ROOTDIRS))"
|
||||
# Add a user-defined pattern to the cygpath arguments
|
||||
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
|
||||
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
|
||||
fi
|
||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||
i=0
|
||||
for arg in "$@" ; do
|
||||
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
|
||||
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
|
||||
|
||||
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
|
||||
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
|
||||
else
|
||||
eval `echo args$i`="\"$arg\""
|
||||
fi
|
||||
i=$((i+1))
|
||||
done
|
||||
case $i in
|
||||
(0) set -- ;;
|
||||
(1) set -- "$args0" ;;
|
||||
(2) set -- "$args0" "$args1" ;;
|
||||
(3) set -- "$args0" "$args1" "$args2" ;;
|
||||
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
|
||||
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
|
||||
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
|
||||
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
|
||||
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
|
||||
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
|
||||
esac
|
||||
fi
|
||||
|
||||
# Escape application args
|
||||
save () {
|
||||
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
|
||||
echo " "
|
||||
}
|
||||
APP_ARGS=$(save "$@")
|
||||
|
||||
# Collect all arguments for the java command, following the shell quoting and substitution rules
|
||||
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
|
||||
|
||||
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
|
||||
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
|
||||
cd "$(dirname "$0")"
|
||||
fi
|
||||
|
||||
exec "$JAVACMD" "$@"
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
@if "%DEBUG%" == "" @echo off
|
||||
@rem ##########################################################################
|
||||
@rem
|
||||
@rem Gradle startup script for Windows
|
||||
@rem
|
||||
@rem ##########################################################################
|
||||
|
||||
@rem Set local scope for the variables with windows NT shell
|
||||
if "%OS%"=="Windows_NT" setlocal
|
||||
|
||||
set DIRNAME=%~dp0
|
||||
if "%DIRNAME%" == "" set DIRNAME=.
|
||||
set APP_BASE_NAME=%~n0
|
||||
set APP_HOME=%DIRNAME%
|
||||
|
||||
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
set DEFAULT_JVM_OPTS=-Dfile.encoding=UTF-8 "-Xmx64m"
|
||||
|
||||
@rem Find java.exe
|
||||
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||
|
||||
set JAVA_EXE=java.exe
|
||||
%JAVA_EXE% -version >NUL 2>&1
|
||||
if "%ERRORLEVEL%" == "0" goto init
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:findJavaFromJavaHome
|
||||
set JAVA_HOME=%JAVA_HOME:"=%
|
||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||
|
||||
if exist "%JAVA_EXE%" goto init
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:init
|
||||
@rem Get command-line arguments, handling Windows variants
|
||||
|
||||
if not "%OS%" == "Windows_NT" goto win9xME_args
|
||||
|
||||
:win9xME_args
|
||||
@rem Slurp the command line arguments.
|
||||
set CMD_LINE_ARGS=
|
||||
set _SKIP=2
|
||||
|
||||
:win9xME_args_slurp
|
||||
if "x%~1" == "x" goto execute
|
||||
|
||||
set CMD_LINE_ARGS=%*
|
||||
|
||||
:execute
|
||||
@rem Setup the command line
|
||||
|
||||
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
|
||||
|
||||
@rem Execute Gradle
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
|
||||
|
||||
:end
|
||||
@rem End local scope for the variables with windows NT shell
|
||||
if "%ERRORLEVEL%"=="0" goto mainEnd
|
||||
|
||||
:fail
|
||||
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||
rem the _cmd.exe /c_ return code!
|
||||
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
|
||||
exit /b 1
|
||||
|
||||
:mainEnd
|
||||
if "%OS%"=="Windows_NT" endlocal
|
||||
|
||||
:omega
|
||||
@@ -0,0 +1,9 @@
|
||||
ABIs = [
|
||||
ABI("2", "armeabi-v7a", "arm-linux-androideabi-4.8", cmake_vars=dict(ANDROID_ABI='armeabi-v7a with NEON')),
|
||||
ABI("1", "armeabi", "arm-linux-androideabi-4.8"),
|
||||
ABI("3", "arm64-v8a", "aarch64-linux-android-4.9"),
|
||||
ABI("5", "x86_64", "x86_64-4.9"),
|
||||
ABI("4", "x86", "x86-4.8"),
|
||||
ABI("7", "mips64", "mips64el-linux-android-4.9"),
|
||||
ABI("6", "mips", "mipsel-linux-android-4.8")
|
||||
]
|
||||
@@ -0,0 +1,7 @@
|
||||
ABIs = [
|
||||
ABI("2", "armeabi-v7a", "arm-linux-androideabi-4.9", cmake_vars=dict(ANDROID_ABI='armeabi-v7a with NEON')),
|
||||
ABI("1", "armeabi", "arm-linux-androideabi-4.9", cmake_vars=dict(WITH_TBB='OFF')),
|
||||
ABI("3", "arm64-v8a", "aarch64-linux-android-4.9"),
|
||||
ABI("5", "x86_64", "x86_64-4.9"),
|
||||
ABI("4", "x86", "x86-4.9"),
|
||||
]
|
||||
@@ -0,0 +1,6 @@
|
||||
ABIs = [
|
||||
ABI("2", "armeabi-v7a", None, cmake_vars=dict(ANDROID_ABI='armeabi-v7a with NEON')),
|
||||
ABI("3", "arm64-v8a", None),
|
||||
ABI("5", "x86_64", None),
|
||||
ABI("4", "x86", None),
|
||||
]
|
||||
@@ -0,0 +1,6 @@
|
||||
ABIs = [
|
||||
ABI("2", "armeabi-v7a", None, 21, cmake_vars=dict(ANDROID_ABI='armeabi-v7a with NEON')),
|
||||
ABI("3", "arm64-v8a", None, 21),
|
||||
ABI("5", "x86_64", None, 21),
|
||||
ABI("4", "x86", None, 21),
|
||||
]
|
||||
@@ -0,0 +1,6 @@
|
||||
ABIs = [
|
||||
ABI("2", "armeabi-v7a", None, 24, cmake_vars=dict(ANDROID_ABI='armeabi-v7a with NEON')),
|
||||
ABI("3", "arm64-v8a", None, 24),
|
||||
ABI("5", "x86_64", None, 24),
|
||||
ABI("4", "x86", None, 24),
|
||||
]
|
||||
@@ -0,0 +1,6 @@
|
||||
ABIs = [
|
||||
ABI("2", "armeabi-v7a", None, cmake_vars=dict(ANDROID_ABI='armeabi-v7a with NEON')),
|
||||
ABI("3", "arm64-v8a", None),
|
||||
ABI("5", "x86_64", None),
|
||||
ABI("4", "x86", None),
|
||||
]
|
||||
@@ -0,0 +1,6 @@
|
||||
ABIs = [
|
||||
ABI("2", "armeabi-v7a", None, cmake_vars=dict(ANDROID_ABI='armeabi-v7a with NEON', ANDROID_GRADLE_PLUGIN_VERSION='4.1.2', GRADLE_VERSION='6.5', KOTLIN_PLUGIN_VERSION='1.5.10')),
|
||||
ABI("3", "arm64-v8a", None, cmake_vars=dict(ANDROID_GRADLE_PLUGIN_VERSION='4.1.2', GRADLE_VERSION='6.5', KOTLIN_PLUGIN_VERSION='1.5.10')),
|
||||
ABI("5", "x86_64", None, cmake_vars=dict(ANDROID_GRADLE_PLUGIN_VERSION='4.1.2', GRADLE_VERSION='6.5', KOTLIN_PLUGIN_VERSION='1.5.10')),
|
||||
ABI("4", "x86", None, cmake_vars=dict(ANDROID_GRADLE_PLUGIN_VERSION='4.1.2', GRADLE_VERSION='6.5', KOTLIN_PLUGIN_VERSION='1.5.10')),
|
||||
]
|
||||
@@ -0,0 +1,19 @@
|
||||
# Docs: https://developer.android.com/ndk/guides/cmake#android_native_api_level
|
||||
ANDROID_NATIVE_API_LEVEL = int(os.environ.get('ANDROID_NATIVE_API_LEVEL', 32))
|
||||
cmake_common_vars = {
|
||||
# Docs: https://source.android.com/docs/setup/about/build-numbers
|
||||
# Docs: https://developer.android.com/studio/publish/versioning
|
||||
'ANDROID_COMPILE_SDK_VERSION': os.environ.get('ANDROID_COMPILE_SDK_VERSION', 32),
|
||||
'ANDROID_TARGET_SDK_VERSION': os.environ.get('ANDROID_TARGET_SDK_VERSION', 32),
|
||||
'ANDROID_MIN_SDK_VERSION': os.environ.get('ANDROID_MIN_SDK_VERSION', ANDROID_NATIVE_API_LEVEL),
|
||||
# Docs: https://developer.android.com/studio/releases/gradle-plugin
|
||||
'ANDROID_GRADLE_PLUGIN_VERSION': '7.3.1',
|
||||
'GRADLE_VERSION': '7.5.1',
|
||||
'KOTLIN_PLUGIN_VERSION': '1.8.20',
|
||||
}
|
||||
ABIs = [
|
||||
ABI("2", "armeabi-v7a", None, ndk_api_level=ANDROID_NATIVE_API_LEVEL, cmake_vars=cmake_common_vars),
|
||||
ABI("3", "arm64-v8a", None, ndk_api_level=ANDROID_NATIVE_API_LEVEL, cmake_vars=cmake_common_vars),
|
||||
ABI("5", "x86_64", None, ndk_api_level=ANDROID_NATIVE_API_LEVEL, cmake_vars=cmake_common_vars),
|
||||
ABI("4", "x86", None, ndk_api_level=ANDROID_NATIVE_API_LEVEL, cmake_vars=cmake_common_vars),
|
||||
]
|
||||
Reference in New Issue
Block a user