# @@ (maybe/later): Use Windows resource script (upstream/win/jpeg.rc.in).
#    Looks like mostly version info, product name, copyright, etc.

linux   = ($c.target.class == 'linux')
bsd     = ($c.target.class == 'bsd')
macos   = ($c.target.class == 'macos')
windows = ($c.target.class == 'windows')
msvc    = ($c.class == 'msvc')

# Windows with 64-bit size_t but 32-bit long (LLP64).
#
win64 = ($windows && $regex.match($c.target.cpu, 'x86_64|aarch64'))

# The emulated libjpeg API/ABI version (note: not the package or upstream
# project version), as upstream's JPEG_LIB_VERSION in CMakeLists.txt: 62 for
# libjpeg v6b (the default) or 70/80 for v7/v8 (see build/root.build).
#
jpeg_lib_version = 62
if $config.libjpeg_turbo.jpeg7
  jpeg_lib_version = 70
if $config.libjpeg_turbo.jpeg8
  jpeg_lib_version = 80

# The SIMD extensions to build, as upstream's SIMD_ARCHITECTURE (see
# simd/CMakeLists.txt): NONE if disabled or not supported by this package on
# the target CPU (see build/root.build).
#
simd_arch = NONE
if $config.libjpeg_turbo.simd
{
  switch $c.target.cpu: regex.match
  {
    case 'x86_64'
      simd_arch = X86_64
    case 'i[3-6]86'
      simd_arch = I386
    case 'aarch64|arm64'
      simd_arch = ARM64
  }
}
simd = ($simd_arch != NONE)

# Sources that are included by other sources instead of being compiled
# (mostly the data precision-dependent ones, see below).
#
src_adhoc = jcapistd jccoefct jccolext jccolor jcdctmgr jcdiffct jclossls   \
            jcmainct jcprepct jcsample jdapistd jdcoefct jdcol565 jdcolext  \
            jdcolor jddctmgr jddiffct jdlossls jdmainct jdmerge jdmrg565    \
            jdmrgext jdpostct jdsample jfdctfst jfdctint jidctflt jidctfst  \
            jidctint jidctred jquant1 jquant2 jstdhuff jutils

# The data precision-dependent sources are compiled once for each precision
# they support via the wrappers in src/wrapper/, which define BITS_IN_JSAMPLE
# and include the source from src/. These are the libjpeg API library ones
# (see upstream's JPEG_SOURCES in CMakeLists.txt).
#
src_wrapper = jcapistd-8 jcapistd-12 jcapistd-16                            \
              jccoefct-8 jccoefct-12                                        \
              jccolor-8 jccolor-12 jccolor-16                               \
              jcdctmgr-8 jcdctmgr-12                                        \
              jcdiffct-8 jcdiffct-12 jcdiffct-16                            \
              jclossls-8 jclossls-12 jclossls-16                            \
              jcmainct-8 jcmainct-12 jcmainct-16                            \
              jcprepct-8 jcprepct-12 jcprepct-16                            \
              jcsample-8 jcsample-12 jcsample-16                            \
              jdapistd-8 jdapistd-12 jdapistd-16                            \
              jdcoefct-8 jdcoefct-12                                        \
              jdcolor-8 jdcolor-12 jdcolor-16                               \
              jddctmgr-8 jddctmgr-12                                        \
              jddiffct-8 jddiffct-12 jddiffct-16                            \
              jdlossls-8 jdlossls-12 jdlossls-16                            \
              jdmainct-8 jdmainct-12 jdmainct-16                            \
              jdmerge-8 jdmerge-12                                          \
              jdpostct-8 jdpostct-12 jdpostct-16                            \
              jdsample-8 jdsample-12 jdsample-16                            \
              jfdctfst-8 jfdctfst-12                                        \
              jfdctint-8 jfdctint-12                                        \
              jidctflt-8 jidctflt-12                                        \
              jidctfst-8 jidctfst-12                                        \
              jidctint-8 jidctint-12                                        \
              jidctred-8 jidctred-12                                        \
              jquant1-8 jquant1-12                                          \
              jquant2-8 jquant2-12                                          \
              jutils-8 jutils-12 jutils-16

# Headers and source files.
#
# Note that arithmetic coding is enabled (c{jaricom jcarith jdarith}).
#
lib{jpeg}: src/h{* -jconfig -jversion -jconfigint}                          \
           src/h{jconfig jversion jconfigint}                               \
           src/c{* -{$src_adhoc}} src/wrapper/c{$src_wrapper}

# Ensure included source files and CMakeLists.txt are distributed.
#
lib{jpeg}: src/c{$src_adhoc}: include = adhoc
lib{jpeg}: file{CMakeLists.txt}

# Linker version script and module definition files.
#
define vsc: file
vsc{*}: extension = map
libs{jpeg}: src/vsc{libjpeg}: include = ($linux || $bsd ? adhoc : false)

# As upstream, the module definition file is win/jpeg<N>.def where <N> is
# the shared library major version (SO_MAJOR_VERSION): 62, 7, or 8.
#
lib{jpeg}: win/def{jpeg62}: include = ($windows && $jpeg_lib_version == 62)
lib{jpeg}: win/def{jpeg7}:  include = ($windows && $jpeg_lib_version == 70)
lib{jpeg}: win/def{jpeg8}:  include = ($windows && $jpeg_lib_version == 80)

# SIMD extensions.
#
# The SIMD dispatcher (simd/jsimd.c) selects the best extensions for the CPU
# at run time.
#
lib{jpeg}: simd/c{jsimd} simd/h{* -neon-compat}: include = $simd

# The x86-64 and i386 extensions are NASM sources (see SIMD_SOURCES in
# simd/CMakeLists.txt).
#
nasm_simd = ($simd_arch == X86_64 || $simd_arch == I386)

if $nasm_simd
  import! nasm = nasm%exe{nasm}

define asm: file
asm{*}: extension = asm

asm_x86_64 = jsimdcpu jfdctflt-sse                                          \
             jccolor-sse2 jcgray-sse2 jchuff-sse2 jcphuff-sse2              \
             jcsample-sse2 jdcolor-sse2 jdmerge-sse2 jdsample-sse2          \
             jfdctfst-sse2 jfdctint-sse2 jidctflt-sse2 jidctfst-sse2        \
             jidctint-sse2 jidctred-sse2 jquantf-sse2 jquanti-sse2          \
             jccolor-avx2 jcgray-avx2 jcsample-avx2 jdcolor-avx2            \
             jdmerge-avx2 jdsample-avx2 jfdctint-avx2 jidctint-avx2         \
             jquanti-avx2

asm_i386 = jsimdcpu jfdctflt-3dn jidctflt-3dn jquantf-3dn                   \
           jccolor-mmx jcgray-mmx jcsample-mmx jdcolor-mmx jdmerge-mmx      \
           jdsample-mmx jfdctfst-mmx jfdctint-mmx jidctfst-mmx jidctint-mmx \
           jidctred-mmx jquanti-mmx                                         \
           jfdctflt-sse jidctflt-sse jquantf-sse                            \
           jccolor-sse2 jcgray-sse2 jchuff-sse2 jcphuff-sse2 jcsample-sse2  \
           jdcolor-sse2 jdmerge-sse2 jdsample-sse2 jfdctfst-sse2            \
           jfdctint-sse2 jidctflt-sse2 jidctfst-sse2 jidctint-sse2          \
           jidctred-sse2 jquantf-sse2 jquanti-sse2                          \
           jccolor-avx2 jcgray-avx2 jcsample-avx2 jdcolor-avx2              \
           jdmerge-avx2 jdsample-avx2 jfdctint-avx2 jidctint-avx2           \
           jquanti-avx2

# The NASM options, as upstream's simd/CMakeLists.txt sets them. Position-
# independent code (PIC) is always enabled outside Windows since upstream
# uses the same objects for the shared and static libraries.
#
# Note that upstream only defines __CET__ if the C compiler enables Intel
# CET. It is safe to always define it: it only adds ENDBR64 (a NOP on CPUs
# without CET) and an ELF property note, which the linker drops unless all
# the objects (including the C ones) have it.
#
nasm_options =
switch $simd_arch
{
  case 'X86_64'
  {
    if $windows
      nasm_options = -fwin64 -DWIN64
    elif $macos
      nasm_options = -fmacho64 -DMACHO -DPIC
    elif ($c.target.system == 'linux-gnux32')
      nasm_options = -felfx32 -DELF -DPIC -D__CET__
    else
      nasm_options = -felf64 -DELF -DPIC -D__CET__

    nasm_options += -D__x86_64__ "-I$src_base/simd/x86_64/"
  }
  case 'I386'
  {
    if $windows
      nasm_options = -fwin32 -DWIN32
    elif $macos
      nasm_options = -fmacho32 -DMACHO -DPIC
    else
      nasm_options = -felf32 -DELF -DPIC

    nasm_options += "-I$src_base/simd/i386/"
  }
}
nasm_options += "-I$src_base/simd/nasm/"

# Assemble a NASM source into a static or shared object. The objects are
# distinct (and so are the rules) to prevent the static and shared libraries
# from clobbering each other's objects.
#
# The included files (simd/nasm/*.inc and the *ext-*.asm sources) are
# extracted from the NASM dependency output.
#
obja{~'/(.+)\.asm\.a/'}: asm{~'/\1/'} $nasm
{{
  o = $path($>[0])
  t = $(o).t
  depdb dyndep --byproduct --what=include --default-type=file --file $t
  diag nasm ($<[0]) -> ($>[0])
  $nasm $nasm_options -MD $t -o $o $path($<[0])
}}

objs{~'/(.+)\.asm\.so/'}: asm{~'/\1/'} $nasm
{{
  o = $path($>[0])
  t = $(o).t
  depdb dyndep --byproduct --what=include --default-type=file --file $t
  diag nasm ($<[0]) -> ($>[0])
  $nasm $nasm_options -MD $t -o $o $path($<[0])
}}

for n: $asm_x86_64
{
  simd/x86_64/obja{$(n).asm.a.o}:  simd/x86_64/asm{$n} $nasm
  simd/x86_64/objs{$(n).asm.so.o}: simd/x86_64/asm{$n} $nasm

  liba{jpeg}: simd/x86_64/obja{$(n).asm.a.o}:  include = ($simd_arch == X86_64)
  libs{jpeg}: simd/x86_64/objs{$(n).asm.so.o}: include = ($simd_arch == X86_64)
}

for n: $asm_i386
{
  simd/i386/obja{$(n).asm.a.o}:  simd/i386/asm{$n} $nasm
  simd/i386/objs{$(n).asm.so.o}: simd/i386/asm{$n} $nasm

  liba{jpeg}: simd/i386/obja{$(n).asm.a.o}:  include = ($simd_arch == I386)
  libs{jpeg}: simd/i386/objs{$(n).asm.so.o}: include = ($simd_arch == I386)
}

# Ensure the included NASM sources are distributed.
#
lib{jpeg}: simd/x86_64/asm{*} simd/i386/asm{*} simd/nasm/file{*.inc}:       \
  include = adhoc

# The AArch64 extensions are Neon intrinsics. The included sources are
# distributed but not compiled.
#
neon_arm64 = jccolor-neon jcgray-neon jcphuff-neon jcsample-neon            \
             jdcolor-neon jdmerge-neon jdsample-neon jfdctfst-neon          \
             jfdctint-neon jidctfst-neon jidctint-neon jidctred-neon        \
             jquanti-neon

lib{jpeg}: simd/arm/c{$neon_arm64} simd/arm/aarch64/c{jchuff-neon jsimdcpu} \
           simd/arm/h{*} simd/h{neon-compat}: include = ($simd_arch == ARM64)

lib{jpeg}: simd/arm/c{jcgryext-neon jdcolext-neon jdmrgext-neon}            \
           simd/arm/aarch64/c{jccolext-neon}: include = adhoc

# Don't install the private SIMD headers.
#
simd/h{*}: install = false

# Generated headers.
#
# See the .in files and CMakeLists.txt for more information about specific
# variables.
#
using autoconf

# Create a numeric version of the package version number. The format is
# <major><minor><patch> where the minor and patch numbers are left-padded with
# zeros to three digits. For example, 3.2.1 becomes 3002001.
#
vp = $version.patch
vm = $version.minor
for i : 0 1
{
  if ($size($vp) < 3)
    vp = "0$vp"
  if ($size($vm) < 3)
    vm = "0$vm"
}
ver_num = "$version.major$vm$vp"

src/h{jconfig}: src/in{jconfig}
{
  # The JPEG library version ID (used, for example, in feature checks).
  #
  JPEG_LIB_VERSION = $jpeg_lib_version

  # The project version number.
  #
  LIBJPEG_TURBO_VERSION_NUMBER = $ver_num

  # "Define if your (broken) compiler shifts signed values as if they were
  # unsigned."
  #
  RIGHT_SHIFT_IS_UNSIGNED = false
}

# Extract values from the upstream CMakeLists.txt. Parse the file only once,
# saving the lines of interest in memory, then extract the value from each
# line.
#
re1 = '^\s*project\((.+) .+\)'
re2 = '^\s*set\(COPYRIGHT_YEAR\s+"(.+)"\)'
re3 = '^\s*set\(MEM_SRCDST_FUNCTIONS\s+"(.+)"\)'
lines = $process.run_regex(cat $src_base/CMakeLists.txt, "$re1|$re2|$re3")
projname       = $regex.merge($lines, $re1, '\1', '', format_first_only format_no_copy)
copyright      = $regex.merge($lines, $re2, '\1', '', format_first_only format_no_copy)
exported_funcs = $regex.merge($lines, $re3, '\1', '', format_first_only format_no_copy)

# Internal library configuration header.
#
src/h{jconfigint}: src/in{jconfigint}
{
  # Used as part of the libjpeg version string. The upstream default is
  # `%Y%m%d`.
  #
  # Note that upstream always uses it in combination with version so we
  # will make it just the stapshot part (if any).
  #
  BUILD = "$version.snapshot_string"

  # How to hide the global symbols that are not part of the API. Upstream
  # only uses the visibility attribute and not on Windows.
  #
  HIDDEN = ($c.class == 'gcc' && !$windows                                  \
            ? '__attribute__((visibility("hidden")))'                       \
            : '')

  # Upstream forces function inlining by default (FORCE_INLINE).
  #
  INLINE = ($msvc                                                           \
            ? '__forceinline'                                               \
            : ($c.class == 'gcc'                                            \
               ? 'inline __attribute__((always_inline))'                    \
               : 'inline'))

  # This is only used in the implementation of the TurboJPEG API (which we
  # disable).
  #
  THREAD_LOCAL =

  # Defines the `PACKAGE_NAME` macro which is embedded inside images by the
  # compressor.
  #
  CMAKE_PROJECT_NAME = $projname

  # The size of size_t. GCC and Clang predefine it while MSVC only targets
  # ILP32 and LLP64.
  #
  SIZE_T = ($msvc ? ($win64 ? 8 : 4) : __SIZEOF_SIZE_T__)

  # Upstream only uses __builtin_ctzl() if unsigned long and size_t have the
  # same size, which is not the case on 64-bit Windows.
  #
  HAVE_BUILTIN_CTZL = ($c.class == 'gcc' && !$win64)

  # Upstream only checks for <intrin.h> with MSVC-like compilers (cl and
  # clang-cl). Don't use the autoconf built-in check since it currently
  # tests _MSV_VER instead of _MSC_VER and so misses cl.
  #
  HAVE_INTRIN_H = $msvc

  SIMD_ARCHITECTURE = $simd_arch
  WITH_SIMDE = false

  WITH_PROFILE = false
}

src/h{jversion}: src/in{jversion}
{
  COPYRIGHT_YEAR = $copyright
}

# Common generated header variables/settings.
#
src/h{jconfig} src/h{jconfigint}:
{
  autoconf.flavor = cmake
  VERSION = "$version.major.$version.minor.$version.patch"

  # WITH_ARITH_DEC and WITH_ARITH_ENC are defined by default in the upstream
  # build (which causes the variables below to be defined to 1); see
  # BUILDING.md, section `Arithmetic Coding Support` for details.
  #
  # Note: If these are ever disabled, remove c{jaricom jcarith jdarith} from
  #       the build.
  #
  C_ARITH_CODING_SUPPORTED = true
  D_ARITH_CODING_SUPPORTED = true

  WITH_SIMD = $simd
}

# The HAVE_VLD1_* Neon intrinsics checks are project checks (see
# build/autoconf/checks/) since there are no builtin ones.
#
simd/h{neon-compat}: simd/arm/in{neon-compat}
{
  autoconf.flavor = cmake
}

# Linker version script.
#
src/vsc{libjpeg}: src/in{libjpeg}
{
  # The library version number in the <major>.<minor> form (upstream's
  # JPEG_LIB_VERSION_DIV10 and JPEG_LIB_VERSION_MOD10).
  #
  JPEG_LIB_VERSION_DECIMAL = $regex.replace($jpeg_lib_version, '(\d)(\d)', '\1.\2')

  # Functions exported by name. As upstream, not when emulating v8, whose API
  # already includes them.
  #
  MEM_SRCDST_FUNCTIONS = ($jpeg_lib_version != 80 ? $exported_funcs : '')
}

# Build options.
#
c.poptions =+ "-I$out_base/src" "-I$src_base/src" "-I$out_base/simd"

if $msvc
  c.poptions += -D_CRT_NONSTDC_NO_WARNINGS
elif ($linux || $bsd)
  c.loptions += "-Wl,--version-script=$out_base/src/libjpeg.map"

# Silence the harmless warnings that upstream code triggers with extra
# warnings enabled (-Wextra, -W4): unused parameters of the module method
# implementations and a signedness change in src/jdphuff.c.
#
if $msvc
  c.coptions += -wd4100
else
  c.coptions += -Wno-unused-parameter -Wno-sign-compare

# Export options.
#
lib{jpeg}: c.export.poptions = "-I$out_base/src" "-I$src_base/src"

# For pre-releases use the complete version to make sure they cannot be used
# in place of another pre-release or the final version. See the version module
# for details on the version.* variable values.
#
if $version.pre_release
  lib{jpeg}: bin.lib.version = "-$version.project_id"
else
  lib{jpeg}: bin.lib.version = "-$version.major.$version.minor"

# Install public headers directly into, say, /usr/include/.
#
src/h{*}: install = false
src/h{jconfig} src/h{jerror}@./src/ src/h{jmorecfg}@./src/                  \
src/h{jpeglib}@./src/: install = include/
