How to Minimize libavif Binary Size
To deploy the libavif library in resource-constrained environments like mobile apps, IoT devices, or WebAssembly, developers must minimize its compiled footprint. This article provides a direct, actionable guide on how to reduce the binary size of libavif by selecting lightweight codecs, configuring CMake compilation flags to disable unused features, and applying aggressive compiler optimizations.
1. Select the Right AV1 Codecs
The choice of underlying AV1 encoder and decoder libraries has the most significant impact on the final binary size of libavif.
- Use dav1d for Decoding Only: If your application
only needs to read AVIF images, use dav1d as the
decoder. It is highly optimized, fast, and significantly smaller than
the reference aom library. Disable all other codecs by
setting their respective CMake flags to
OFF. - Configure aom for Encoding: If you must encode AVIF
images, use libaom but compile it with reduced
features. Alternatively, avoid compiling both
aomanddav1dtogether if a single codec likeaomcan handle both encoding and decoding (thoughaom’s decoding binary footprint is larger thandav1d’s).
2. Disable Unused Features in CMake
By default, libavif may compile auxiliary tools, tests, and support for multiple image formats. You can disable these using CMake flags during the configuration step:
Disable Command-Line Tools: Turn off the compilation of
avifencandavifdecunless you explicitly need them.-DAVIF_BUILD_APPS=OFFDisable Tests and Benchmarks: Ensure unit tests and performance benchmarks are excluded from the build.
-DAVIF_BUILD_TESTS=OFFLimit Codec Integration: Explicitly enable only the codecs you need. For a decode-only build using
dav1d:-DAVIF_CODEC_DAV1D=ON -DAVIF_CODEC_AOM=OFF -DAVIF_CODEC_RAV1E=OFF -DAVIF_CODEC_SVT=OFF
3. Apply Compiler Optimization Flags
Adjusting how the compiler builds the binary can yield massive size reductions without changing the source code.
Set the Build Type to MinSizeRel: Instruct CMake to optimize specifically for binary size. This applies the
-Osflag (or-Ozon Clang) automatically.-DCMAKE_BUILD_TYPE=MinSizeRelEnable Link-Time Optimization (LTO): LTO allows the compiler to perform optimizations across different translation units, enabling it to discard unused functions (dead code elimination) globally.
-DCMAKE_INTERPROCEDURAL_OPTIMIZATION=ON(Note: For older CMake versions, you can pass
-fltodirectly to the compiler flags).
4. Strip Symbols from the Output Binary
Debug symbols and unused symbol tables take up substantial space in the compiled binary.
Strip Debug Symbols: After compilation, use the
stripcommand-line utility to remove all symbols from the shared library or executable.strip --strip-all libavif.soHidden Visibility: Build the library with hidden symbol visibility so that only the public API is exported, allowing the compiler to optimize internal functions more aggressively.
-DCMAKE_C_VISIBILITY_PRESET=hidden