How to Cross-Compile libavif for Android
This guide provides a step-by-step walkthrough for cross-compiling
the libavif library for the Android platform using the
Android Native Development Kit (NDK) and CMake. You will learn how to
set up your environment, compile a compatible AV1 codec dependency (such
as aom or dav1d), and configure the final
libavif build for Android architectures like
arm64-v8a or armeabi-v7a.
Prerequisites
Before beginning, ensure you have the following tools installed on your development host (Linux, macOS, or Windows):
- CMake (version 3.10 or higher)
- Android NDK (r21 or higher recommended)
- Git
- Ninja (optional, but highly recommended for faster builds)
Define the path to your Android NDK as an environment variable to simplify the commands:
export ANDROID_NDK=/path/to/your/android-ndkStep 1: Clone the libavif Repository
Clone the official libavif repository from GitHub and
navigate into the directory:
git clone https://github.com/AOMediaCodec/libavif.git
cd libavifStep 2: Build an AV1 Codec Dependency
libavif requires at least one underlying AV1 encoder or
decoder library to function. For Android, dav1d (a highly
optimized decoder) or aom (encoder/decoder) are the most
common choices.
Here is how to cross-compile aom for Android as a
dependency:
Navigate to the external directory and clone
aom:git clone https://aomedia.googlesource.com/aom ext/aomCreate a build directory for
aomand configure it using the Android NDK toolchain:mkdir -p ext/aom/build.android cd ext/aom/build.android cmake .. \ -G Ninja \ -DCMAKE_TOOLCHAIN_FILE=$ANDROID_NDK/build/cmake/android.toolchain.cmake \ -DANDROID_ABI=arm64-v8a \ -DANDROID_PLATFORM=android-21 \ -DANDROID_STL=c++_static \ -DENABLE_DOCS=OFF \ -DENABLE_EXAMPLES=OFF \ -DENABLE_TESTS=OFF \ -DENABLE_TOOLS=OFF \ -DCMAKE_BUILD_TYPE=Release ninja cd ../../..(Note: Replace
arm64-v8awitharmeabi-v7a,x86, orx86_64if targeting other architectures).
Step 3: Configure and Build libavif
Now that the AV1 codec is built, you can configure and build
libavif using the same Android NDK toolchain and link it to
the compiled aom library.
Create and navigate to the
libavifbuild directory:mkdir build.android cd build.androidRun CMake to configure the project. Point the configuration to the Android toolchain and enable the
aomlibrary:cmake .. \ -G Ninja \ -DCMAKE_TOOLCHAIN_FILE=$ANDROID_NDK/build/cmake/android.toolchain.cmake \ -DANDROID_ABI=arm64-v8a \ -DANDROID_PLATFORM=android-21 \ -DANDROID_STL=c++_static \ -DCMAKE_BUILD_TYPE=Release \ -DAVIF_CODEC_AOM=LOCAL \ -DAVIF_LOCAL_AOM=ONCompile the library:
ninja
Step 4: Verify the Output
Once the build process completes successfully, you will find the
compiled libraries inside the build.android directory:
libavif.so(Shared library)libavif.a(Static library)
You can now copy these binaries and the header files from the
include/ directory into your Android Studio project’s
cpp folder to utilize AVIF image decoding and encoding via
JNI.