cmake_minimum_required(VERSION 3.22.1 FATAL_ERROR)
project(matinee_ffmpeg C CXX)
set(CMAKE_CXX_STANDARD 17)

# Static FFmpeg built by native/ffmpeg/build.sh (LGPL-2.1+, allowlist.txt).
set(ffmpeg_out "${CMAKE_CURRENT_SOURCE_DIR}/../../../out/${ANDROID_ABI}")

# Link order matters for static archives: dependents first.
set(ffmpeg_libs avformat avcodec swscale swresample avutil)
set(ffmpeg_link "")
foreach(name ${ffmpeg_libs})
  if(EXISTS "${ffmpeg_out}/lib/lib${name}.a")
    add_library(${name} STATIC IMPORTED)
    set_target_properties(${name} PROPERTIES IMPORTED_LOCATION "${ffmpeg_out}/lib/lib${name}.a")
    list(APPEND ffmpeg_link ${name})
  endif()
endforeach()

add_library(matinee_ffmpeg SHARED matinee_ffmpeg_jni.cc matinee_ffmpeg_demux.cc matinee_ffmpeg_video.cc matinee_ffmpeg_pcm.cc)
target_include_directories(matinee_ffmpeg PRIVATE "${ffmpeg_out}/include")
set_target_properties(matinee_ffmpeg PROPERTIES CXX_VISIBILITY_PRESET hidden VISIBILITY_INLINES_HIDDEN ON)
target_compile_options(matinee_ffmpeg PRIVATE -Os -fno-exceptions -fno-rtti)

# 16 KB page size (Android 15+ devices): segment alignment is set explicitly so NDK r26 is enough.
# --exclude-libs hides every FFmpeg symbol; only JNI_OnLoad is exported. Relinking is possible from
# the static archives built by build.sh (see LICENSES.md).
target_link_options(matinee_ffmpeg PRIVATE
  -Wl,-z,max-page-size=16384 -Wl,-z,common-page-size=16384
  -Wl,--exclude-libs,ALL -Wl,--gc-sections -Wl,-z,relro -Wl,-z,now -Wl,--build-id=sha1)
if(ANDROID_ABI STREQUAL "arm64-v8a")
  target_link_options(matinee_ffmpeg PRIVATE -Wl,-Bsymbolic)
endif()

find_library(log_lib log)
# jnigraphics (platform NDK library): AndroidBitmap_* for the thumbnail frame grab (R2 A8).
# z: the platform's zlib (FFmpeg is configured with --enable-zlib for PNG, Flash Screen Video, ZMBV...).
target_link_libraries(matinee_ffmpeg PRIVATE ${ffmpeg_link} android jnigraphics EGL GLESv2 z ${log_lib})
