cmake_minimum_required(VERSION 3.24)
if(CMAKE_SOURCE_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR)
  project(SampledexMp3Encoder VERSION 3.100 LANGUAGES C)
endif()

# Keep a complete, unmodified source archive in each customer package. No
# network fetch or opaque prebuilt encoder is part of this build.
set(lame_archive "${CMAKE_CURRENT_SOURCE_DIR}/lame-3.100.tar.gz")
file(SHA256 "${lame_archive}" lame_hash)
if(NOT lame_hash STREQUAL "ddfe36cab873794038ae2c1210557ad34857a4b6bdc515785d1da9e175b1da1e")
  message(FATAL_ERROR "The bundled LAME 3.100 source archive failed its SHA-256 check")
endif()
set(lame_source "${CMAKE_CURRENT_BINARY_DIR}/source/lame-3.100")
if(NOT EXISTS "${lame_source}/libmp3lame/lame.c")
  file(ARCHIVE_EXTRACT INPUT "${lame_archive}" DESTINATION "${CMAKE_CURRENT_BINARY_DIR}/source")
endif()
include(CheckTypeSize)
check_type_size("long" LAME_SIZEOF_LONG LANGUAGE C)
check_type_size("long double" LAME_SIZEOF_LONG_DOUBLE LANGUAGE C)
configure_file(config.h.in "${CMAKE_CURRENT_BINARY_DIR}/config.h" @ONLY)
set(lame_units VbrTag bitstream encoder fft gain_analysis id3tag lame newmdct
  presets psymodel quantize quantize_pvt reservoir set_get tables takehiro util
  vbrquantize version mpglib_interface)
set(lame_sources)
foreach(unit IN LISTS lame_units)
  list(APPEND lame_sources "${lame_source}/libmp3lame/${unit}.c")
endforeach()
# A replaceable shared library is required. Use scalar upstream code on every
# architecture; no NASM executable, CLI, decoder or bundled platform binary.
add_library(sampledex_mp3 SHARED ${lame_sources})
set_target_properties(sampledex_mp3 PROPERTIES OUTPUT_NAME mp3lame
  WINDOWS_EXPORT_ALL_SYMBOLS ON C_STANDARD 99 C_STANDARD_REQUIRED YES)
if(WIN32)
  set_target_properties(sampledex_mp3 PROPERTIES PREFIX lib)
endif()
target_include_directories(sampledex_mp3 PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/include"
  PRIVATE "${CMAKE_CURRENT_BINARY_DIR}" "${lame_source}/include"
          "${lame_source}/libmp3lame" "${lame_source}/mpglib")
target_compile_definitions(sampledex_mp3 PRIVATE HAVE_CONFIG_H=1)
if(MSVC)
  target_compile_definitions(sampledex_mp3 PRIVATE _CRT_SECURE_NO_WARNINGS NOMINMAX)
else()
  target_link_libraries(sampledex_mp3 PRIVATE m)
endif()
