#!/bin/sh
#
# MythTV configure script, based on the FFmpeg configure script
#
# Copyright (c) 2000-2002 Fabrice Bellard
# Copyright (c) 2005-2008 Diego Biurrun
# Copyright (c) 2005-2008 Mans Rullgard
#

#
# All versioning information needed to create a release of MythTV.
#
MYTHTV_VERSION_MAJMIN="35.0"
MYTHTV_LIBVERSION="35"
# See mythtv/libs/libmythbase/mythversion.h.in
MYTHTV_BINARY_VERSION="35.20220913-1"
# See bindings/python/MythTV/static.py.in
MYTHTV_PYTHON_OWN_VERSION="(35,0,-1,0)"
# See python/MythTV/services_api/send.py.in
MYTHTV_PYTHON_VERSION_LIST="('0.27', '0.28', '29', '30', '31', '32', '33', '34', '35')"

# Prevent locale nonsense from breaking basic text processing.
LC_ALL=C
export LC_ALL

CPP_STANDARD=c++17

# make sure we are running under a compatible shell
# try to make this part work with most shells

try_exec(){
    echo "Trying shell $1"
    type "$1" > /dev/null 2>&1 && exec "$@"
}

unset foo
(: ${foo%%bar}) 2> /dev/null
E1="$?"

(: ${foo?}) 2> /dev/null
E2="$?"

if test "$E1" != 0 || test "$E2" = 0; then
    echo "Broken shell detected.  Trying alternatives."
    export FF_CONF_EXEC
    if test "0$FF_CONF_EXEC" -lt 1; then
        FF_CONF_EXEC=1
        try_exec bash "$0" "$@"
    fi
    if test "0$FF_CONF_EXEC" -lt 2; then
        FF_CONF_EXEC=2
        try_exec ksh "$0" "$@"
    fi
    if test "0$FF_CONF_EXEC" -lt 3; then
        FF_CONF_EXEC=3
        try_exec /usr/xpg4/bin/sh "$0" "$@"
    fi
    echo "No compatible shell script interpreter found."
    echo "This configure script requires a POSIX-compatible shell"
    echo "such as bash or ksh."
    echo "THIS IS NOT A BUG IN FFMPEG, DO NOT REPORT IT AS SUCH."
    echo "Instead, install a working POSIX-compatible shell."
    echo "Disabling this configure test will create a broken MythTV."
    if test "$BASH_VERSION" = '2.04.0(1)-release'; then
        echo "This bash version ($BASH_VERSION) is broken on your platform."
        echo "Upgrade to a later version if available."
    fi
    exit 1
fi

test -d /usr/xpg4/bin && PATH=/usr/xpg4/bin:$PATH

show_help(){
    cat <<EOF
Usage: configure [options]
Options: [defaults in brackets after descriptions]

Standard options:
  --help                   print this message
  --previous               use previous configure parameters if possible
  --compile-type=CTYPE     one of release, profile, debug [$compile_type]
                           NOTE: profile is for sampling profilers
  --prefix=PREFIX          install in PREFIX [$prefix]
  --runprefix=PREFIX       prefix to be used at runtime (e.g. .. or /myth/latest)
  --libdir-name=LIBNAME    search/install libraries in PREFIX/LIBNAME [$libdir_name]
  --disable-ccache         disable compiler cache (ccache)
  --disable-distcc         disable distributed compilation (distcc)

Advanced options (experts only):
  --cross-prefix=PREFIX    use PREFIX for compilation tools [$cross_prefix]
  --cross-prefix-cc=PREFIX use PREFIX for compiler compilation tools [$cross_prefix_cc]
  --enable-cross-compile   assume a cross-compiler is used
  --sysroot=PATH           root of cross-build tree
  --sysinclude=PATH        location of cross-build system headers
  --cc=CC                  use C compiler CC [$cc_default]
  --cxx=CXX                use C++ compiler CXX [$cxx_default]
  --enable-set-cc-default  set cc_default and cxx_default to that provided by --cc= and -cxx
  --ld=LD                  use linker LD
  --qmake=QMAKE            use specified qmake [$qmake_default]
  --qmakespecs=PATH        use specified mkspecs
  --extra-cflags=ECFLAGS   add ECFLAGS to CFLAGS [$CFLAGS]
  --extra-cxxflags=ECXFLAGS add ECXXFLAGS to list of flags for C++ compile
  --extra-ldflags=ELDFLAGS add ELDFLAGS to LDFLAGS [$LDFLAGS]
  --disable-symbol-visibility disables symbol visibility options
  --disable-deprecation-warnings disables deprecated declaration warnings
  --arch=ARCH              select architecture [$arch]
  --tune=CPU               tune instruction usage for a particular CPU [$tune]
  --cpu=CPU                select the minimum required CPU (affects
                           instruction selection, may crash on older CPUs)
  --disable-altivec        disable AltiVec optimizations
  --disable-amd3dnow       disable 3DNow! optimizations
  --disable-amd3dnowext    disable 3DNow! extended optimizations
  --disable-mmx            disable MMX optimizations
  --disable-mmx2           disable MMX2 optimizations
  --disable-sse            disable SSE optimizations
  --disable-ssse3          disable SSSE3 optimizations
  --disable-avx            disable AVX optimizations
  --disable-yasm           disable use of yasm assembler
  --enable-pic             build position-independent code
  --enable-proc-opt        enable processor specific compilation
  --enable-compdb          enable clang compiler database

  --disable-audio-oss      disable OSS audio support
  --disable-audio-alsa     disable ALSA audio support
  --disable-audio-jack     disable JACK audio support
  --disable-audio-pulseoutput disable PulseAudio audio output support
  --enable-valgrind        disables timeouts for valgrind memory debugging
  --disable-lirc           disable lirc support (Infrared Remotes)
  --disable-joystick-menu  disable joystick menu
  --disable-libcec         disable libCEC device support
  --libcec-path=HDRLOC     location of directory containing
                           'libcec/cec.h', not the directory
                           with 'cec.h' [$libcec_path_default]
  --firewire-sdk           specify location for mac FireWire SDK [mac only]
  --disable-firewire       disable support for FireWire cable boxes
  --disable-hdhomerun      disable support for HDHomeRun boxes
  --disable-vbox           disable support for V@Box TV Gateway boxes
  --disable-ceton          disable support for Ceton cards
  --disable-satip          disable support for Sat>IP
  --disable-v4l2           disable Video4Linux support
  --disable-dvb            disable DVB support
  --dvb-path=HDRLOC        location of directory containing
                           'linux/dvb/frontend.h', not the
                           directory with frontend.h [$dvb_path_default]
  --disable-asi            disable support for DVEO ASI recorder
  --disable-x11            disable X11 support
  --enable-opengles        link to OpenGL ES (auto)
  --enable-vulkan          enable Vulkan rendering
  --disable-waylandextras  disable optional Wayland integrations (requires Qt private headers)
  --enable-libglslang      enable runtime GLSL compilation for Vulkan (development only)
  --x11-path=X11LOC        location of X11 include files [$x11_path_default]
  --disable-vdpau          disable NVidia VDPAU hardware acceleration.
  --disable-vaapi          disable VAAPI hardware accelerated video decoding
  --disable-nvdec          disable NVDEC (CUVID) hardware accelerated video decoding
  --disable-dxva2          disable hardware accelerated decoding on windows
  --disable-mediacodec     disable hardware accelerated decoding on android
  --disable-mmal           disable hardware accelerated decoding on Raspberry Pi
  --disable-libass         disable libass SSA/ASS subtitle support
  --disable-systemd_notify disable systemd notify support
  --disable-systemd_journal disable systemd journal support

  --enable-mac-bundle      produce standalone OS X apps (e.g. mythfrontend.app)

  --disable-libxml2        disable libxml2 support (disc metadata)
  --libxml2-path=HDRLOC    location of directory containing
                           'libxml/parser.h', not the
                           directory with parser.h [$libxml2_path_default]
  --disable-libdns-sd      disable DNS Service Discovery (Bonjour/Zeroconf/Avahi)
  --disable-libcrypto      disable use of the OpenSSL cryptographic library
  --disable-gnutls         disable use of GnuTLS for SSL/TLS protocol support in ffmpeg

  --with-bindings=LIST     install the bindings specified in the
                           comma-separated list
                           Supported bindings: perl, python, php
                           comma-separated list
  --python=PATH            Force a specific python executable to use [$python_default]
  --perl-config-opts=OPTS  Additional options to pass when generating
                           Makefile.perl for building Perl bindings.
  --enable-bdjava          Enable BD-J support for Blu-ray discs

External codec library options (used for mythffmpeg and streaming transcode):
  --enable-libmp3lame      enable MP3 encoding via libmp3lame [no]
  --enable-libx264         enable H.264 encoding via x264 [no]
  --enable-libx265         enable H.265 encoding via x265 [no]
  --enable-libvpx          enable VP8 encoding via libvpx [no]
  --enable-libxvid         enable Xvid encoding via xvidcore,
                           native MPEG-4/Xvid encoder exists [no]
EOF

  exit 0
}

quotes='""'
if test -t 1 && which tput >/dev/null 2>&1; then
    ncolors=$(tput colors)
    if test -n "$ncolors" && test $ncolors -ge 8; then
        bold_color=$(tput bold)
        warn_color=$(tput setaf 3)
        error_color=$(tput setaf 1)
        reset_color=$(tput sgr0)
    fi
    # 72 used instead of 80 since that's the default of pr
    ncols=$(tput cols)
fi
: ${ncols:=72}

log(){
    echo "$@" >> $logfile
}

log_file(){
    log BEGIN $1
    pr -n -t $1 >> $logfile
    log END $1
}

warn(){
    log "WARNING: $*"
    WARNINGS="${WARNINGS}WARNING: $*\n"
}

die(){
    log "$@"
    echo "$error_color$bold_color$@$reset_color"
    cat <<EOF

If you think configure made a mistake, make sure that you are using the latest
version of MythTV from git.  If the latest version fails, report the problem to the
mythtv-dev@mythtv.org mailing list or IRC #mythtv on irc.libera.chat
EOF
    if disabled logging; then
        cat <<EOF
Rerun configure with logging enabled (do not use --disable-logging), and
include the log this produces with your report.
EOF
    else
        cat <<EOF
Include the log file "$logfile" produced by configure as this will help
solve the problem.
EOF
    fi
    exit 1
}

# Avoid locale weirdness, besides we really just want to translate ASCII.
toupper(){
    echo "$@" | tr abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ
}

tolower(){
    echo "$@" | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz
}

c_escape(){
    echo "$*" | sed 's/["\\]/\\\0/g'
}

sh_quote(){
    v=$(echo "$1" | sed "s/'/'\\\\''/g")
    test "x$v" = "x${v#*[!A-Za-z0-9_/.+-]}" || v="'$v'"
    echo "$v"
}

cleanws(){
    echo "$@" | sed 's/^ *//;s/[[:space:]][[:space:]]*/ /g;s/ *$//'
}

filter(){
    pat=$1
    shift
    for v; do
        eval "case $v in $pat) printf '%s ' $v ;; esac"
    done
}

filter_out(){
    pat=$1
    shift
    for v; do
        eval "case $v in $pat) ;; *) printf '%s ' $v ;; esac"
    done
}

map(){
    m=$1
    shift
    for v; do eval $m; done
}

add_suffix(){
    suffix=$1
    shift
    for v; do echo ${v}${suffix}; done
}

set_all(){
    value=$1
    shift
    for var in $*; do
        eval $var=$value
    done
}

set_weak(){
    value=$1
    shift
    for var; do
        eval : \${$var:=$value}
    done
}

sanitize_var_name(){
    echo $@ | sed 's/[^A-Za-z0-9_]/_/g'
}

set_safe(){
    var=$1
    shift
    eval $(sanitize_var_name "$var")='$*'
}

get_safe(){
    eval echo \$$(sanitize_var_name "$1")
}

pushvar(){
    for pvar in $*; do
        eval level=\${${pvar}_level:=0}
        eval ${pvar}_${level}="\$$pvar"
        eval ${pvar}_level=$(($level+1))
    done
}

popvar(){
    for pvar in $*; do
        eval level=\${${pvar}_level:-0}
        test $level = 0 && continue
        eval level=$(($level-1))
        eval $pvar="\${${pvar}_${level}}"
        eval ${pvar}_level=$level
        eval unset ${pvar}_${level}
    done
}

request(){
    for var in $*; do
        eval ${var}_requested=yes
        eval $var=
    done
}

enable(){
    set_all yes $*
}

disable(){
    set_all no $*
}

enable_weak(){
    set_weak yes $*
}

disable_weak(){
    set_weak no $*
}

enable_safe(){
    for var; do
        enable $(echo "$var" | sed 's/[^A-Za-z0-9_]/_/g')
    done
}

disable_safe(){
    for var; do
        disable $(echo "$var" | sed 's/[^A-Za-z0-9_]/_/g')
    done
}

do_enable_deep(){
    for var; do
        enabled $var && continue
        eval sel="\$${var}_select"
        eval sgs="\$${var}_suggest"
        pushvar var sgs
        enable_deep $sel
        popvar sgs
        enable_deep_weak $sgs
        popvar var
    done
}

enable_deep(){
    do_enable_deep $*
    enable $*
}

enable_deep_weak(){
    for var; do
        disabled $var && continue
        pushvar var
        do_enable_deep $var
        popvar var
        enable_weak $var
    done
}

requested(){
    test "${1#!}" = "$1" && op='=' || op=!=
    eval test "x\$${1#!}_requested" $op "xyes"
}

enabled(){
    test "${1#!}" = "$1" && op='=' || op=!=
    eval test "x\$${1#!}" $op "xyes"
}

disabled(){
    test "${1#!}" = "$1" && op='=' || op=!=
    eval test "x\$${1#!}" $op "xno"
}

enabled_all(){
    for opt; do
        enabled $opt || return 1
    done
}

disabled_all(){
    for opt; do
        disabled $opt || return 1
    done
}

enabled_any(){
    for opt; do
        enabled $opt && return 0
    done
}

disabled_any(){
    for opt; do
        disabled $opt && return 0
    done
    return 1
}

set_default(){
    for opt; do
        eval : \${$opt:=\$${opt}_default}
    done
}

is_in(){
    value=$1
    shift
    for var in $*; do
        [ $var = $value ] && return 0
    done
    return 1
}

do_check_deps(){
    for cfg; do
        enabled ${cfg}_checking && die "Circular dependency for $cfg."
        disabled ${cfg}_checking && continue
        enable ${cfg}_checking
        append allopts $cfg

        eval dep_all="\$${cfg}_deps"
        eval dep_any="\$${cfg}_deps_any"
        eval dep_con="\$${cfg}_conflict"
        eval dep_sel="\$${cfg}_select"
        eval dep_sgs="\$${cfg}_suggest"
        eval dep_ifa="\$${cfg}_if"
        eval dep_ifn="\$${cfg}_if_any"

        pushvar cfg dep_all dep_any dep_con dep_sel dep_sgs dep_ifa dep_ifn
        do_check_deps $dep_all $dep_any $dep_con $dep_sel $dep_sgs $dep_ifa $dep_ifn
        popvar cfg dep_all dep_any dep_con dep_sel dep_sgs dep_ifa dep_ifn

        [ -n "$dep_ifa" ] && { enabled_all $dep_ifa && enable_weak $cfg; }
        [ -n "$dep_ifn" ] && { enabled_any $dep_ifn && enable_weak $cfg; }
        enabled_all  $dep_all || { disable $cfg && requested $cfg && die "ERROR: $cfg requested, but not all dependencies are satisfied: $dep_all"; }
        enabled_any  $dep_any || { disable $cfg && requested $cfg && die "ERROR: $cfg requested, but not any dependency is satisfied: $dep_any"; }
        disabled_all $dep_con || { disable $cfg && requested $cfg && die "ERROR: $cfg requested, but some conflicting dependencies are unsatisfied: $dep_con"; }
        disabled_any $dep_sel && { disable $cfg && requested $cfg && die "ERROR: $cfg requested, but some selected dependency is unsatisfied: $dep_sel"; }

        if enabled $cfg; then
            enable_deep $dep_sel
            enable_deep_weak $dep_sgs
        fi

        disable ${cfg}_checking
    done
}

check_deps(){
    unset allopts

    do_check_deps "$@"

    for cfg in $allopts; do
        enabled $cfg || continue
        eval dep_extralibs="\$${cfg}_extralibs"
        test -n "$dep_extralibs" && add_extralibs $dep_extralibs
    done
}

print_config(){
    pfx=$1
    files=$2
    shift 2
    map 'eval echo "$v \${$v:-no}"' "$@" |
    awk "BEGIN { split(\"$files\", files) }
        {
            c = \"$pfx\" toupper(\$1);
            v = \$2;
            sub(/yes/, 1, v);
            sub(/no/,  0, v);
            for (f in files) {
                file = files[f];
                if (file ~ /\\.h\$/) {
                    printf(\"#define %s %d\\n\", c, v) >>file;
                } else if (file ~ /\\.asm\$/) {
                    printf(\"%%define %s %d\\n\", c, v) >>file;
                } else if (file ~ /\\.mak\$/) {
                    n = -v ? \"\" : \"!\";
                    printf(\"%s%s=yes\\n\", n, c) >>file;
                } else if (file ~ /\\.texi\$/) {
                    pre = -v ? \"\" : \"@c \";
                    yesno = \$2;
                    c2 = tolower(c);
                    gsub(/_/, \"-\", c2);
                    printf(\"%s@set %s %s\\n\", pre, c2, yesno) >>file;
                }
            }
        }"
}

print_enabled(){
    suf=$1
    shift
    for v; do
        enabled $v && printf "%s\n" ${v%$suf}
    done
}

append(){
    var=$1
    shift
    eval "$var=\"\$$var $*\""
}

prepend(){
    var=$1
    shift
    eval "$var=\"$* \$$var\""
}

unique(){
    var=$1
    uniq_list=""
    for tok in $(eval echo \$$var); do
        uniq_list="$(filter_out $tok $uniq_list) $tok"
    done
    eval "$var=\"${uniq_list}\""
}

unique2(){
    var=$1
    r=$(echo $(eval echo \$$var) | awk '{for (i=1;i<=NF;i++) if (!a[$i]++) printf("%s%s",$i,FS)}{printf("\n")}')
    eval "$var=\"${r}\""
}

add_cppflags(){
    append CPPFLAGS "$@"
}

add_cflags(){
    append CFLAGS $($cflags_filter "$@")
}

add_cflags_headers(){
    append CFLAGS_HEADERS $($cflags_filter "$@")
}

add_cxxflags(){
    append CXXFLAGS "$@"
}

add_ecxxflags(){
    append ECXXFLAGS "$@"
}

add_asflags(){
    append ASFLAGS $($asflags_filter "$@")
}

add_objcflags(){
    append OBJCFLAGS $($objcflags_filter "$@")
}

add_ldflags(){
    append LDFLAGS $($ldflags_filter "$@")
}

add_ldexeflags(){
    append LDEXEFLAGS $($ldflags_filter "$@")
}

add_ldlibflags(){
    append LDLIBFLAGS $($ldflags_filter "$@")
}

add_extralibs(){
    prepend extralibs $($ldflags_filter "$@")
}

add_host_cppflags(){
    append host_cppflags "$@"
}

add_host_cflags(){
    append host_cflags $($host_cflags_filter "$@")
}

add_host_ldflags(){
    append host_ldflags $($host_ldflags_filter "$@")
}

add_compat(){
    append compat_objs $1
    shift
    map 'add_cppflags -D$v' "$@"
}

check_cmd(){
    log "$@"
    "$@" >> $logfile 2>&1
}

check_stat(){
    log check_stat "$@"
    stat "$1" >> $logfile 2>&1
}

cc_o(){
    eval printf '%s\\n' $CC_O
}

cc_e(){
    eval printf '%s\\n' $CC_E
}

check_cc(){
    log check_cc "$@"
    cat > $TMPC
    log_file $TMPC
    check_cmd $cc $CPPFLAGS $CFLAGS "$@" $CC_C $(cc_o $TMPO) $TMPC
}

check_cxx(){
    log check_cxx "$@"
    cat > $TMPCPP
    log_file $TMPCPP
    check_cmd $cxx $CPPFLAGS $CXXFLAGS "$@" $CXX_C -o $TMPO $TMPCPP
}

check_ecxx(){
    log check_cxx "$@"
    cat > $TMPCPP
    log_file $TMPCPP
    check_cmd $cxx $CPPFLAGS $CXXFLAGS $ECXXFLAGS "$@" $CXX_C -o $TMPO $TMPCPP
}

check_objcc(){
    log check_objcc "$@"
    cat > $TMPM
    log_file $TMPM
    check_cmd $objcc -Werror=missing-prototypes $CPPFLAGS $CFLAGS $OBJCFLAGS "$@" $OBJCC_C $(cc_o $TMPO) $TMPM
}

check_cpp(){
    log check_cpp "$@"
    cat > $TMPC
    log_file $TMPC
    check_cmd $cc $CPPFLAGS $CFLAGS "$@" $(cc_e $TMPO) $TMPC
}

as_o(){
    eval printf '%s\\n' $AS_O
}

check_as(){
    log check_as "$@"
    cat > $TMPS
    log_file $TMPS
    check_cmd $as $CPPFLAGS $ASFLAGS "$@" $AS_C $(as_o $TMPO) $TMPS
}

check_inline_asm(){
    log check_inline_asm "$@"
    name="$1"
    code="$2"
    shift 2
    disable $name
    check_cc "$@" <<EOF && enable $name
void foo(void){ __asm__ volatile($code); }
EOF
}

check_inline_asm_flags(){
    log check_inline_asm_flags "$@"
    name="$1"
    code="$2"
    flags=''
    shift 2
    while [ "$1" != "" ]; do
      append flags $1
      shift
    done;
    disable $name
    cat > $TMPC <<EOF
void foo(void){ __asm__ volatile($code); }
EOF
    log_file $TMPC
    check_cmd $cc $CPPFLAGS $CFLAGS $flags "$@" $CC_C $(cc_o $TMPO) $TMPC &&
    enable $name && add_cflags $flags && add_asflags $flags && add_ldflags $flags
}

check_insn(){
    log check_insn "$@"
    check_inline_asm ${1}_inline "\"$2\""
    echo "$2" | check_as && enable ${1}_external || disable ${1}_external
}

check_x86asm(){
    log check_x86asm "$@"
    echo "$1" > $TMPS
    log_file $TMPS
    shift 1
    check_cmd $x86asmexe $X86ASMFLAGS -Werror "$@" -o $TMPO $TMPS
}

ld_o(){
    eval printf '%s\\n' $LD_O
}

check_ld(){
    log check_ld "$@"
    type=$1
    shift 1
    flags=$(filter_out '-l*|*.so' $@)
    libs=$(filter '-l*|*.so' $@)
    check_$type $($cflags_filter $flags) || return
    flags=$($ldflags_filter $flags)
    libs=$($ldflags_filter $libs)
    check_cmd $ld $LDFLAGS $LDEXEFLAGS $flags $(ld_o $TMPE) $TMPO $libs $extralibs
}

print_include(){
    hdr=$1
    test "${hdr%.h}" = "${hdr}" &&
        echo "#include $hdr"    ||
        echo "#include <$hdr>"
}

check_code(){
    log check_code "$@"
    check=$1
    headers=$2
    code=$3
    shift 3
    {
        for hdr in $headers; do
            print_include $hdr
        done
        echo "int main(void) { $code; return 0; }"
    } | check_$check "$@"
}

check_cppflags(){
    log check_cppflags "$@"
    check_cpp "$@" <<EOF && append CPPFLAGS "$@"
#include <stdlib.h>
EOF
}

test_cflags(){
    log test_cflags "$@"
    set -- $($cflags_filter "$@")
    check_cc "$@" <<EOF
int x;
EOF
}

check_cflags(){
    log check_cflags "$@"
    test_cflags "$@" && add_cflags "$@"
}

check_cxxflags(){
    log check_cxxflags "$@"
    check_cxx "$@" <<EOF && add_cxxflags "$@" || log "WARNING! An unknown C++ compiler flag in: \"$@\". Option(s) will be ignored."
class X {};
int x;
EOF
}

test_objcflags(){
    log test_objcflags "$@"
    set -- $($objcflags_filter "$@")
    check_objcc "$@" <<EOF
int x;
EOF
}

check_objcflags(){
    log check_objcflags "$@"
    test_objcflags "$@" && add_objcflags "$@"
}

test_ldflags(){
    log test_ldflags "$@"
    check_ld "cc" "$@" <<EOF
int main(void){ return 0; }
EOF
}

check_ldflags(){
    log check_ldflags "$@"
    test_ldflags "$@" && add_ldflags "$@"
}

check_header(){
    log check_header "$@"
    header=$1
    shift
    disable_safe $header
    check_cpp "$@" <<EOF && enable_safe $header
#include <$header>
int x;
EOF
}

check_header_objcc(){
    log check_header_objcc "$@"
    rm -f -- "$TMPO"
    header=$1
    shift
    disable_safe $header
    {
       echo "#include <$header>"
       echo "int main(void) { return 0; }"
    } | check_objcc && check_stat "$TMPO" && enable_safe $header
}

check_apple_framework(){
    log check_apple_framework "$@"
    framework="$1"
    name="$(tolower $framework)"
    header="${framework}/${framework}.h"
    disable $name
    check_header_objcc $header && enable $name && add_extralibs "-framework $framework"
}

check_func(){
    log check_func "$@"
    func=$1
    shift
    disable $func
    check_ld "cc" "$@" <<EOF && enable $func
extern int $func();
int main(void){ $func(); }
EOF
}

check_func_headers(){
    log check_func_headers "$@"
    headers=$1
    funcs=$2
    shift 2
    {
        echo "#include <stdint.h>"
        for hdr in $headers; do
            print_include $hdr
        done
        for func in $funcs; do
            echo "long check_$func(void) { return (long) $func; }"
        done
        echo "int main(void) { int ret = 0;"
        # LTO could optimize out the test functions without this
        for func in $funcs; do
            echo " ret |= ((intptr_t)check_$func) & 0xFFFF;"
        done
        echo "return ret; }"
    } | check_ld "cc" "$@" && enable $funcs && enable_safe $headers
}

check_class_headers_cpp(){
    log check_class_headers_cpp "$@"
    headers=$1
    classes=$2
    shift 2
    {
        for hdr in $headers; do
            echo "#include <$hdr>"
        done
        echo "int main(void) { "
        i=1
        for class in $classes; do
            echo "$class obj$i;"
            i=$(expr $i + 1)
        done
        echo "return 0; }"
    } | check_ld "cxx" "$@" && enable_safe $headers
}

check_cpp_condition(){
    log check_cpp_condition "$@"
    header=$1
    condition=$2
    shift 2
    check_cpp "$@" <<EOF
#include <$header>
#if !($condition)
#error "unsatisfied condition: $condition"
#endif
EOF
}

test_cflags_cc(){
    log test_cflags_cc "$@"
    flags=$1
    header=$2
    condition=$3
    shift 3
    set -- $($cflags_filter "$flags")
    check_cc "$@" <<EOF
#include <$header>
#if !($condition)
#error "unsatisfied condition: $condition"
#endif
EOF
}

check_lib(){
    log check_lib "$@"
    name="$1"
    headers="$2"
    funcs="$3"
    shift 3
    disable $name
    check_func_headers "$headers" "$funcs" "$@" &&
        enable $name && add_extralibs "$@"
}

check_lib_cpp(){
    log check_lib_cpp "$@"
    headers="$1"
    classes="$2"
    shift 2
    check_class_headers_cpp "$headers" "$classes" "$@" && add_extralibs "$@"
}

check_pkg_config(){
    log check_pkg_config "$@"
    name="$1"
    pkg_version="$2"
    pkg="${2%% *}"
    headers="$3"
    funcs="$4"
    shift 4
    disable $name
    check_cmd $pkg_config --exists --print-errors $pkg_version || return
    pkg_cflags=$($pkg_config --cflags $pkg_config_flags $pkg)
    pkg_libs=$($pkg_config --libs $pkg_config_flags $pkg)
    check_func_headers "$headers" "$funcs" $pkg_cflags $pkg_libs "$@" &&
        enable $name &&
        set_safe "${pkg}_cflags"    $pkg_cflags &&
        set_safe "${pkg}_extralibs" $pkg_libs
}

check_exec(){
    check_ld "cc" "$@" && { enabled cross_compile || $TMPE >> $logfile 2>&1; }
}

check_exec_crash(){
    log check_exec_crash "$@"
    code=$(cat)

    # exit() is not async signal safe.  _Exit (C99) and _exit (POSIX)
    # are safe but may not be available everywhere.  Thus we use
    # raise(SIGTERM) instead.  The check is run in a subshell so we
    # can redirect the "Terminated" message from the shell.  SIGBUS
    # is not defined by standard C so it is used conditionally.

    (check_exec "$@") >> $logfile 2>&1 <<EOF
#include <signal.h>
static void sighandler(int sig){
    raise(SIGTERM);
}
int foo(void){
    $code
}
int (*func_ptr)(void) = foo;
int main(void){
    signal(SIGILL, sighandler);
    signal(SIGFPE, sighandler);
    signal(SIGSEGV, sighandler);
#ifdef SIGBUS
    signal(SIGBUS, sighandler);
#endif
    return func_ptr();
}
EOF
}

check_type(){
    log check_type "$@"
    headers=$1
    type=$2
    shift 2
    disable_safe "$type"
    check_code cc "$headers" "$type v" "$@" && enable_safe "$type"
}

check_struct(){
    log check_struct "$@"
    headers=$1
    struct=$2
    member=$3
    shift 3
    disable_safe "${struct}_${member}"
    check_code cc "$headers" "const void *p = &(($struct *)0)->$member" "$@" &&
        enable_safe "${struct}_${member}"
}

check_builtin(){
    log check_builtin "$@"
    name=$1
    headers=$2
    builtin=$3
    shift 3
    disable "$name"
    check_code ld "$headers" "$builtin" "cc" "$@" && enable "$name"
}

require(){
    log require "$@"
    name_version="$1"
    name="${1%% *}"
    headers="$2"
    func="$3"
    shift 3
    check_lib $name "$headers" $func "$@" || die "ERROR: $name_version not found"
}

require_cpp(){
    name="$1"
    headers="$2"
    classes="$3"
    shift 3
    check_lib_cpp "$headers" "$classes" "$@" || die "ERROR: $name not found"
}

require_header(){
    log require "$@"
    header="$1"
    shift
    check_header "$header" "$@" || die "ERROR: $header header not found"
}

require_cpp_condition(){
    log require "$@"
    header="$1"
    condition="$2"
    shift 2
    check_cpp_condition "$header" "$condition" "$@" || die "ERROR: $condition not satisfied"
}

use_pkg_config(){
    log use_pkg_config "$@"
    pkg="${2%% *}"
    check_pkg_config "$@" || return 1
    add_cflags    $(get_safe "${pkg}_cflags")
    add_extralibs $(get_safe "${pkg}_extralibs")
}

require_pkg_config(){
    log require_pkg_config "$@"
    pkg_version="$2"
    use_pkg_config "$@" || die "ERROR: $pkg_version not found using pkg-config$pkg_config_fail_message"
}

hostcc_e(){
    eval printf '%s\\n' $HOSTCC_E
}

hostcc_o(){
    eval printf '%s\\n' $HOSTCC_O
}

check_host_cc(){
    log check_host_cc "$@"
    cat > $TMPC
    log_file $TMPC
    check_cmd $host_cc $host_cflags "$@" $HOSTCC_C $(hostcc_o $TMPO) $TMPC
}

check_host_cpp(){
    log check_host_cpp "$@"
    cat > $TMPC
    log_file $TMPC
    check_cmd $host_cc $host_cppflags $host_cflags "$@" $(hostcc_e $TMPO) $TMPC
}

check_host_cppflags(){
    log check_host_cppflags "$@"
    check_host_cpp "$@" <<EOF && append host_cppflags "$@"
#include <stdlib.h>
EOF
}

check_host_cflags(){
    log check_host_cflags "$@"
    set -- $($host_cflags_filter "$@")
    check_host_cc "$@" <<EOF && append host_cflags "$@"
int x;
EOF
}

check_host_cpp_condition(){
    log check_host_cpp_condition "$@"
    header=$1
    condition=$2
    shift 2
    check_host_cpp "$@" <<EOF
#include <$header>
#if !($condition)
#error "unsatisfied condition: $condition"
#endif
EOF
}

cp_if_changed(){
    cmp -s "$1" "$2" && { test "$quiet" != "yes" && echo "$2 is unchanged"; } && return
    mkdir -p "$(dirname $2)"
    cp -f "$1" "$2"
    echo "Created $2"
}

# MythTV Custom Tests
disable_bindings_python(){
    echo "WARNING: disabling Python bindings; missing $1"
    disable bindings_python
}

disable_bindings_perl(){
    echo "WARNING: disabling Perl bindings; missing $1"
    disable bindings_perl
}

disable_bindings_php(){
    echo "WARNING: disabling PHP bindings; missing $1"
    disable bindings_php
}

append_uniq(){
    log append_uniq "$@"
    var=$1
    shift
for value; do
eval tmpvar='$'$var
        echo "$tmpvar" | grep -q ".$value" || append $var $value
    done
}

add_cxxppflags(){
    append CXXPPFLAGS $($cxxppflags_filter "$@")
}

is_python3() {
    log is_python3
    check_cmd $python << EOF
import sys
if sys.version_info > (3,0):
    sys.exit(0)
else:
    sys.exit(1)
EOF
}

check_python(){
    log check_python "$@"
    version=${1}
    check_cmd $python <<EOF
import sys
if sys.version_info < $version:
    sys.exit(1)
EOF
}

check_py_lib(){
    log check_py_lib "$@"
    lib=${1}
    check_cmd $python <<EOF
import sys
try:
    import $lib
except:
    sys.exit(1)
sys.exit(0)
EOF
}

check_py_lib_version(){
    log check_py_lib_version "$@"
    lib=${1}
    version=${2}
    check_cmd $python <<EOF
import sys
try:
    # see PEP 440
    import $lib
    vlist = [int(x) for x in $lib.__version__.split('.') if x.isnumeric()]
    if tuple(vlist) < $version:
        raise
except:
    sys.exit(1)
sys.exit(0)
EOF
}

check_pl_lib(){
    log check_pl_lib "$@"
    check_cmd perl -e "use ${1};"
}

check_ld_cxx(){
    log check_ld_cxx "$@"
    flags=''
    libs=''
    for f; do
        test "${f}" = "${f#-l}" && flags="$flags $f" || libs="$libs $f"
    done
    check_cxx $($cflags_filter $flags) || return
    check_cmd $cxx $LDFLAGS $flags -o $TMPE $TMPO $extralibs $libs
}

check_cxxppflags(){
    log check_cxxppflags "$@"
    set -- $($filter_cxxppflags "$@")
    check_cxx "$@" <<EOF && append CXXPPFLAGS "$@"
int x;
EOF
}

check_libx(){
    log check_libx "$@"
    libvar="$1"
    headers="$2"
    func="$3"
    shift 3
    check_func_headers "$headers" $func "$@" && append_uniq $libvar "$@"
}

check_exec_cxx(){
    check_ld_cxx "$@" && { enabled cross_compile || $TMPE >> $logfile 2>&1; }
}

non_standard_header(){
    test x"$1" != "x/usr/include" -a  x"$1" != "x/usr/local/include"
}

x86_mmx_cpus="pentium-mmx,pentium2,pentium3,pentium3m,pentium-m"
x86_mmx_cpus="$x86_mmx_cpus,pentium4,pentium4m,prescott"
x86_mmx_cpus="$x86_mmx_cpus,athlon,athlon-xp,athlon-tbird,athlon-4,athlon-mp,"
x86_mmx_cpus="$x86_mmx_cpus,c3,c3-2,k6,k6-2,k6-3"

x86_cpus="i386,i486,i586,i686,pentium,pentiumpro,${x86_mmx_cpus}"

x86_64_cpus="x86-64,athlon64,k8,opteron,athlon64-sse3,k8-sse3,opteron-sse3"
x86_64_cpus="$x86_64_cpus,barcelona,athlon-fx,nocona,core2"

is_x86_cpu() {
    expr ",${x86_cpus}," : ".*,$1," > /dev/null
}

is_x86_64_cpu() {
    expr ",${x86_64_cpus}," : ".*,$1," > /dev/null
}

is_x86_mmx() {
    expr ",${x86_mmx_cpus}," : ".*,$1," > /dev/null || is_x86_64_cpu "$1"
}


# CONFIG_LIST contains configurable options, while HAVE_LIST is for
# system-dependent things.

AVCODEC_COMPONENTS="
"

AVDEVICE_COMPONENTS="
"

AVFILTER_COMPONENTS="
"

AVFORMAT_COMPONENTS="
"

AVRESAMPLE_COMPONENTS=""

AVUTIL_COMPONENTS=""

COMPONENT_LIST="
"

EXTERNAL_AUTODETECT_LIBRARY_LIST="
    alsa
    jack
    xlib
    zlib
"

EXTERNAL_LIBRARY_GPL_LIST="
    libx264
    libx265
    libxvid
"

EXTERNAL_LIBRARY_NONFREE_LIST="
"

EXTERNAL_LIBRARY_VERSION3_LIST="
"

EXTERNAL_LIBRARY_GPLV3_LIST="
"

EXTERNAL_LIBRARY_LIST="
    $EXTERNAL_AUTODETECT_LIBRARY_LIST
    $EXTERNAL_LIBRARY_GPL_LIST
    $EXTERNAL_LIBRARY_NONFREE_LIST
    $EXTERNAL_LIBRARY_VERSION3_LIST
    $EXTERNAL_LIBRARY_GPLV3_LIST
    jni
    libaom
    libass
    libdav1d
    libfontconfig
    libfreetype
    libiec61883
    libmp3lame
    libpulse
    libvpx
    libxml2
    mediacodec
    opengl
    sdl
    sdl2
    vaapi
    nvdec
"

HWACCEL_AUTODETECT_LIBRARY_LIST="
    dxva2
    vdpau
"

HWACCEL_LIBRARY_NONFREE_LIST="
"

HWACCEL_LIBRARY_LIST="
    $HWACCEL_AUTODETECT_LIBRARY_LIST
    $HWACCEL_LIBRARY_NONFREE_LIST
"

FEATURE_LIST="
    shared
    small
    static
    swscale_alpha
"

# needed for get_version for linking to *.so.
LIBRARY_LIST="
    avcodec
    avdevice
    avfilter
    avformat
    avutil
    postproc
    swresample
    swscale
"

LICENSE_LIST="
    gpl
    nonfree
    version3
"

PROGRAM_LIST="
    ffprobe
    ffmpeg
    ffplay
"

SUBSYSTEM_LIST="
"

# COMPONENT_LIST needs to come last to ensure correct dependency checking
CONFIG_LIST="
    $EXTERNAL_LIBRARY_LIST
    $HWACCEL_LIBRARY_LIST
    $FEATURE_LIST
    $LICENSE_LIST
    $PROGRAM_LIST
    $SUBSYSTEM_LIST
    autodetect
    fontconfig
    linux_perf
    memory_poisoning
    neon_clobber_test
    ossfuzz
    pic
    compdb
    thumb
    valgrind_backtrace
    xmm_clobber_test
    $COMPONENT_LIST
"

THREADS_LIST="
    pthreads
    os2threads
    w32threads
"

ATOMICS_LIST="
    atomics_gcc
    atomics_suncc
    atomics_win32
"

AUTODETECT_LIBS="
    $EXTERNAL_AUTODETECT_LIBRARY_LIST
    $HWACCEL_AUTODETECT_LIBRARY_LIST
    $THREADS_LIST
"

ARCH_LIST="
    aarch64
    alpha
    arm
    avr32
    avr32_ap
    avr32_uc
    bfin
    ia64
    m68k
    mips
    mips64
    parisc
    ppc
    ppc64
    s390
    sh4
    sparc
    sparc64
    tilegx
    tilepro
    tomi
    x86
    x86_32
    x86_64
"

ARCH_EXT_LIST_ARM="
    armv5te
    armv6
    armv6t2
    armv8
    neon
    vfp
    vfpv3
    setend
"

ARCH_EXT_LIST_MIPS="
    mipsfpu
    mips32r2
    mips32r5
    mips64r2
    mips32r6
    mips64r6
    mipsdsp
    mipsdspr2
    msa
"

ARCH_EXT_LIST_LOONGSON="
    loongson2
    loongson3
    mmi
"

ARCH_EXT_LIST_X86_SIMD="
    aesni
    amd3dnow
    amd3dnowext
    avx
    avx2
    fma3
    fma4
    mmx
    mmxext
    sse
    sse2
    sse3
    sse4
    sse42
    ssse3
    xop
"

ARCH_EXT_LIST_PPC="
    altivec
    dcbzl
    ldbrx
    power8
    ppc4xx
    vsx
"

ARCH_EXT_LIST_X86="
    $ARCH_EXT_LIST_X86_SIMD
    cpunop
    i686
"

ARCH_EXT_LIST="
    $ARCH_EXT_LIST_ARM
    $ARCH_EXT_LIST_PPC
    $ARCH_EXT_LIST_X86
    $ARCH_EXT_LIST_MIPS
    $ARCH_EXT_LIST_LOONGSON
"

ARCH_FEATURES="
    aligned_stack
    fast_64bit
    fast_clz
    fast_cmov
    local_aligned_8
    local_aligned_16
    local_aligned_32
    simd_align_16
    simd_align_32
"

BUILTIN_LIST="
    atomic_cas_ptr
    machine_rw_barrier
    MemoryBarrier
    mm_empty
    rdtsc
    sarestart
    sem_timedwait
    sync_val_compare_and_swap
"
HAVE_LIST_CMDLINE="
    inline_asm
    symver
    x86asm
"

HAVE_LIST_PUB="
    bigendian
    fast_unaligned
"

HEADERS_LIST_BLURAY="
    dirent_h
    dlfcn_h
    mntent_h
    pthread_h
    strings_h
    sys_dl_h
    sys_time_h
"

HEADERS_LIST_UDFREAD="
    fcntl_h
    pthread_h
    unistd_h
"

HEADERS_LIST_DVDNAV="
    dlfcn_h
    sys_param_h
"

HEADERS_LIST_LIBMPEG2="
    altivec_h
"

HEADERS_LIST="
    altivec_h
    dirent_h
    dlfcn_h
    fcntl_h
    mntent_h
    pthread_h
    strings_h
    sys_dl_h
    sys_param_h
    sys_time_h
    unistd_h
"

INTRINSICS_LIST="
    intrinsics_neon
"

SYSTEM_FUNCS_BLURAY="
    getmntent_r
"

SYSTEM_FUNCS_DVDNAV="
    gettimeofday
"

SYSTEM_FUNCS="
    $SYSTEM_FUNCS_BLURAY
    $SYSTEM_FUNCS_DVDNAV
"

TOOLCHAIN_FEATURES="
    as_dn_directive
    as_fpu_directive
    as_func
    as_object_arch
    asm_mod_q
    attribute_may_alias
    attribute_packed
    blocks_extension
    ebp_available
    ebx_available
    gnu_as
    gnu_windres
    ibm_asm
    inline_asm_direct_symbol_refs
    inline_asm_labels
    inline_asm_nonlocal_labels
    pragma_deprecated
    rsync_contimeout
    symver_asm_label
    symver_gnu_asm
    vfp_args
    xform_asm
    xmm_clobbers
"

TYPES_LIST="
    struct_hdr_metadata_infoframe
"

HAVE_LIST="
    $ARCH_EXT_LIST
    $(add_suffix _external $ARCH_EXT_LIST)
    $(add_suffix _inline   $ARCH_EXT_LIST)
    $ARCH_FEATURES
    $ATOMICS_LIST
    $BUILTIN_LIST
    $HAVE_LIST_CMDLINE
    $HAVE_LIST_PUB
    $HEADERS_LIST
    $INTRINSICS_LIST
    $SYSTEM_FUNCS
    $THREADS_LIST
    $TOOLCHAIN_FEATURES
    $TYPES_LIST
    atomics_native
    dos_paths
    libc_msvcrt
    makeinfo
    makeinfo_html
    MMAL_PARAMETER_VIDEO_MAX_NUM_CALLBACKS
    perl
    pod2man
    section_data_rel_ro
    texi2html
    threads
    uwp
    vaapi_drm
    vaapi_x11
    vdpau_x11
    winrt
"

# options emitted with CONFIG_ prefix but not available on the command line
CONFIG_EXTRA="
"

MYTHTV_CONFIG_LIST='
    backend
    bdjava
    bindings_perl
    bindings_python
    bindings_php
    cygwin
    darwin
    disable_mmx_for_debugging
    dvb
    firewire
    frontend
    hdhomerun
    satip
    vbox
    ceton
    asi
    joystick_menu
    libcec
    libcrypto
    gnutls
    libdns_sd
    libmpeg2external
    libxml2
    lirc
    mheg
    mmal
    opengl
    egl
    qtwebkit
    qtscript
    qtdbus
    sqlite3
    taglib
    v4l2
    v4l2prime
    valgrind
    x11
    system_libexiv2
    system_libbluray
    system_libudfread
    systemd_notify
    systemd_journal
    drm
    force_loglong
'

MYTHTV_HAVE_LIST='
    bdj_j2me
    fe_can_2g_modulation
    ftime
    getifaddrs
    gettimeofday
    posix_fadvise
    libudev
    stdint_h
    sync_file_range
    close_range
'

MYTHTV_LIST='
    audio_pulse
    audio_pulseoutput
    audio_alsa
    audio_jack
    audio_oss
    ffmpeg_pthreads
    mac_bundle
    proc_opt
    silent_cc
    symbol_visibility
    deprecation_warnings
'

USING_LIST='
    appleremote
    bdjava
    bindings_perl
    bindings_python
    bindings_php
    compdb
    darwin_da
    fontconfig
    freetype2
    mythtranscode
    dxva2
    opengl
    opengles
    egl
    drm
    vaapi
    nvdec
    vdpau
    mediacodec
    mmal
    vulkan
    libglslang
    videotoolbox
    waylandextras
    qtprivateheaders
'

CMDLINE_SELECT="
    $ARCH_EXT_LIST
    $CONFIG_LIST
    $HAVE_LIST_CMDLINE
    $THREADS_LIST
    asm
    cross_compile
    debug
    extra_warnings
    logging
    lto
    optimizations
    rpath
    set_cc_default
    $MYTHTV_LIST
    $MYTHTV_CONFIG_LIST
"

PATHS_LIST="
    bindir
    datadir
    docdir
    incdir
    libdir
    mandir
    pkgconfigdir
    prefix
    shlibdir
    install_name_dir
"

MYTHTV_PATHS_LIST='
    dvb_path
    libcec_path
    runprefix
    x11_path
    libxml2_path
    firewiresdk_path
'

MYTHTV_CMDLINE_SET='
    compile_type
    logging
    python
    qmake
    qmakespecs
    samples
    source_path
    bdj_type
    JDK_HOME
'

CMDLINE_SET="
    $PATHS_LIST
    ar
    arch
    as
    assert_level
    build_suffix
    cc
    objcc
    cpu
    cross_prefix
    cross_prefix_cc
    custom_allocator
    cxx
    dep_cc
    doxygen
    env
    extra_version
    gas
    host_cc
    host_cflags
    host_extralibs
    host_ld
    host_ldflags
    host_os
    ignore_tests
    install
    ld
    ln_s
    logfile
    malloc_prefix
    nm
    optflags
    nvccflags
    pkg_config
    pkg_config_flags
    progs_suffix
    random_seed
    ranlib
    samples
    sws_max_filter_size
    sysinclude
    sysroot
    target_exec
    target_os
    target_path
    target_samples
    tempprefix
    toolchain
    valgrind
    x86asmexe
    $MYTHTV_PATHS_LIST
    $MYTHTV_CMDLINE_SET
"

CMDLINE_APPEND="
    extra_cflags
    extra_cxxflags
    extra_objcflags
    host_cppflags
"

# code dependency declarations

# architecture extensions

armv5te_deps="arm"
armv6_deps="arm"
armv6t2_deps="arm"
armv7_a_deps="arm"
armv8_deps="aarch64"
neon_deps_any="aarch64 arm"
intrinsics_neon_deps="neon"
vfp_deps_any="aarch64 arm"
vfpv3_deps="vfp"
setend_deps="arm"

map 'eval ${v}_inline_deps=inline_asm' $ARCH_EXT_LIST_ARM

loongson2_deps="mips"
loongson3_deps="mips"
mipsfpu_deps="mips"
mipsdsp_deps="mips"
mipsdspr2_deps="mips"
mips32r2_deps="mips"
mips32r5_deps="mips"
mips32r6_deps="mips"
mips64r2_deps="mips"
mips64r6_deps="mips"
msa_deps="mipsfpu"
mmi_deps="mips"

altivec_deps="ppc"
dcbzl_deps="ppc"
ldbrx_deps="ppc"
ppc4xx_deps="ppc"
vsx_deps="altivec"
power8_deps="vsx"

cpunop_deps="i686"
x86_64_select="i686"
x86_64_suggest="fast_cmov"

amd3dnow_deps="mmx"
amd3dnowext_deps="amd3dnow"
i686_deps="x86"
mmx_deps="x86"
mmxext_deps="mmx"
sse_deps="mmxext"
sse2_deps="sse"
sse3_deps="sse2"
ssse3_deps="sse3"
sse4_deps="ssse3"
sse42_deps="sse4"
aesni_deps="sse42"
avx_deps="sse42"
xop_deps="avx"
fma3_deps="avx"
fma4_deps="avx"
avx2_deps="avx"

mmx_external_deps="x86asm"
mmx_inline_deps="inline_asm"
mmx_suggest="mmx_external mmx_inline"

for ext in $(filter_out mmx $ARCH_EXT_LIST_X86_SIMD); do
    eval dep=\$${ext}_deps
    eval ${ext}_external_deps='"${dep}_external"'
    eval ${ext}_inline_deps='"${dep}_inline"'
    eval ${ext}_suggest='"${ext}_external ${ext}_inline"'
done

aligned_stack_if_any="aarch64 ppc x86"
fast_64bit_if_any="aarch64 alpha ia64 mips64 parisc64 ppc64 sparc64 x86_64"
fast_clz_if_any="aarch64 alpha avr32 mips ppc x86"
fast_unaligned_if_any="aarch64 ppc x86"
simd_align_16_if_any="altivec neon sse"
simd_align_32_if_any="avx"

# system capabilities
symver_if_any="symver_asm_label symver_gnu_asm"
valgrind_backtrace_conflict="optimizations"
valgrind_backtrace_deps="valgrind_valgrind_h"

# threading support
atomics_gcc_if="sync_val_compare_and_swap"
atomics_suncc_if="atomic_cas_ptr machine_rw_barrier"
atomics_win32_if="MemoryBarrier"
atomics_native_if_any="$ATOMICS_LIST"
w32threads_deps="atomics_native"
threads_if_any="$THREADS_LIST"

# hardware accelerators
dxva2_deps="dxva2api_h DXVA2_ConfigPictureDecode ole32"
dxva2_extralibs="-luser32"

# external libraries
libmp3lame_encoder_deps="libmp3lame"
libmp3lame_encoder_select="audio_frame_queue mpegaudioheader"
libx262_encoder_deps="libx262"
libx264_encoder_deps="libx264"
libx264rgb_encoder_deps="libx264 x264_csp_bgr"
libx264rgb_encoder_select="libx264_encoder"

# ffmpeg setting - value for image utils - 32 recommended, 1 used for now
image_align=1

# mythtv dependencies
audio_oss_deps_any="soundcard_h sys_soundcard_h"
dvb_deps="backend"
firewire_deps="backend"
hdhomerun_deps="backend"
satip_deps="backend"
vbox_deps="backend"
ceton_deps="backend"
mythtranscode_deps="backend frontend"
opengl_deps_any="agl_h GL_gl_h EGL_egl_h GLES2_gl2_h darwin windows x11"
opengles_deps="GLES2_gl2_h"
egl_deps="EGL_egl_h"
v4l2_deps="linux_videodev2_h"
v4l2prime_deps="v4l2 drm"
vulkan_deps="vulkan_vulkan_core_h"
asi_deps="backend"
waylandextras_deps="wayland_client_h"

# default parameters

pre_logfile="config.ep"
logfile="$pre_logfile"
compile_type="profile"

# installation paths
prefix_default="/usr/local"
bindir_default='${prefix}/bin'
datadir_default='${prefix}/share/mythtv'
docdir_default='${prefix}/share/doc/mythtv'
incdir_default='${prefix}/include/mythtv'
libdir_default='${prefix}/lib'
mandir_default='${prefix}/share/man'

libdir_name='lib'

# toolchain
ar_default="ar"
cc_default="gcc"
cxx_default="g++"
host_cc_default="gcc"
doxygen_default="doxygen"
install="install"
ln_s_default="ln -s -f"
nm_default="nm -g"
pkg_config_default=pkg-config
ranlib_default="ranlib"
version_script='--version-script'
x86asmexe_default="nasm"
windres_default="windres"
nvcc_default="nvcc"
nvccflags_default="-gencode arch=compute_30,code=sm_30 -O2"

# MythTV toolchain
ccache="yes"
distcc="yes"
qmake_default="qmake"
qmakespecs_default=""
python_default="python3"

#Bluray
bdj_type="j2se"
disable bdj_j2me

# machine
arch_default=$(uname -m)
cpu="generic"
processor=`uname -p 2>/dev/null`
processor_flags=""
tune="generic"

if test -f /proc/cpuinfo ; then
    if test x"$processor" = x"" -o x"$processor" = x"$arch_default" -o \
            x"$processor" = x"unknown" ; then
        processor=`cat /proc/cpuinfo | grep "model name" | head -n 1`
    fi
    processor_flags=`cat /proc/cpuinfo | grep "flags" | head -n 1`
fi

# Mac OS X equivalent
if test -f /usr/bin/hostinfo ; then
    arch=`arch`
    if test x"$arch" = x"ppc" -o x"$arch" = x"ppc64" ; then
        processor=`/usr/bin/hostinfo | grep "Processor type:"`
        processor=${processor#Processor type: *}
        processor=${processor% (*}
        tune=$processor
    else
            # 10.4 only:
            processor=`/usr/sbin/sysctl -n machdep.cpu.model_string 2>/dev/null`
            if test x"$processor" = x"" ; then
                # On 10.5, this contains the type of CPU also:
                processor=`/usr/sbin/sysctl -n machdep.cpu.brand_string`
            fi
            processor_flags=`/usr/sbin/sysctl -n machdep.cpu.features`
            processor_flags=`echo $processor_flags | tr "[A-Z]" "[a-z]"`
    fi
fi

# OS
target_os_default=$(tolower $(uname -s))
host_os=$target_os_default

# machine
if test "$target_os_default" = aix; then
    arch_default=$(uname -p)
else
    arch_default=$(uname -m)
fi
cpu="generic"
intrinsics="none"

# configurable options
enable $PROGRAM_LIST
enable $LIBRARY_LIST

enable asm
enable debug
enable faan faandct faanidct
enable optimizations
enable swscale_alpha
enable valgrind_backtrace

sws_max_filter_size_default=256
set_default sws_max_filter_size

# mythtv settings
enable gpl
disable sdl2
disable sdl
disable ffplay

CONFIG_DEFINES=""
CONFIG_INCLUDEPATH=""
PROFILEFLAGS=""

audio_pulse="default"
audio_pulseoutput="default"
audio_alsa="default"
audio_jack="default"

enable audio_oss
enable bindings_perl
enable bindings_python
enable bindings_php
enable dvb
enable ffmpeg_pthreads
enable firewire
enable frontend
enable hdhomerun
enable satip
enable vbox
enable ceton
enable asi
enable lamemp3
enable libaom
enable libass
enable libcec
enable libcrypto
enable gnutls
enable libdav1d
enable libdns_sd
enable libxml2
enable lirc
enable mediacodec
enable vaapi
enable nvdec
enable mheg
enable mmal
enable mythtranscode
enable opengl
enable egl
enable symbol_visibility
enable deprecation_warnings
enable v4l2
enable v4l2prime
enable x11
disable indevs
enable taglib
enable systemd_notify
enable systemd_journal
enable system_libexiv2
enable system_libbluray
enable system_libudfread
enable waylandextras
# Enable by default so that we can explicitly disable using --disable-qtwebkit
enable qtwebkit
enable qtscript

# mythtv paths
dvb_path_default="${sysinclude:-$sysroot/usr/include}"
x11_path_default="${sysinclude:-$sysroot/usr/include}/X11"
libcec_path_default="${sysinclude:-$sysroot/usr/include}"
libxml2_path_default="${sysinclude:-$sysroot/usr/include}/libxml2"
firewiresdk_path_default=""
# build settings
SHFLAGS='-shared -Wl,-soname,$$(@F)'
LIBPREF="libmyth"
LIBSUF=".a"
FULLNAME='$(NAME)$(BUILDSUF)'
LIBNAME='$(LIBPREF)$(FULLNAME)$(LIBSUF)'
SLIBPREF="libmyth"
SLIBSUF=".so"
SLIBNAME='$(SLIBPREF)$(FULLNAME)$(SLIBSUF)'
SLIBNAME_WITH_VERSION='$(SLIBNAME).$(LIBVERSION)'
SLIBNAME_WITH_MAJOR='$(SLIBNAME).$(LIBMAJOR)'
LIB_INSTALL_EXTRA_CMD='$$(RANLIB) "$(LIBDIR)/$(LIBNAME)"'
SLIB_INSTALL_NAME='$(SLIBNAME_WITH_VERSION)'
SLIB_INSTALL_LINKS='$(SLIBNAME_WITH_MAJOR) $(SLIBNAME)'
VERSION_SCRIPT_POSTPROCESS_CMD="cat"

asflags_filter=echo
cflags_filter=echo
ldflags_filter=echo
cxxppflags_filter=echo

AS_C='-c'
AS_O='-o $@'
CC_C='-c'
CC_E='-E -o $@'
CC_O='-o $@'
CXX_C='-c'
CXX_O='-o $@'
OBJCC_C='-c'
OBJCC_E='-E -o $@'
OBJCC_O='-o $@'
X86ASM_O='-o $@'
LD_O='-o $@'
LD_LIB='-l%'
LD_MYTH_LIB='-lmyth%'
LD_PATH='-L'
HOSTCC_C='-c'
HOSTCC_O='-o $@'
HOSTLD_O='-o $@'
NVCC_C='-c'
NVCC_O='-o $@'

host_extralibs='-lm'
host_cflags_filter=echo
host_ldflags_filter=echo

target_path='$(CURDIR)'

# since the object filename is not given with the -MM flag, the compiler
# is only able to print the basename, and we must add the path ourselves
DEPCMD='$(DEP$(1)) $(DEP$(1)FLAGS) $($(1)DEP_FLAGS) $< 2>/dev/null | sed -e "/^\#.*/d" -e "s,^[[:space:]]*$(@F),$(@D)/$(@F)," > $(@:.o=.d)'
DEPFLAGS='-MM'

# find source path
source_path="$(dirname "$0")"
enable source_path_used
if test -f configure; then
    source_path="$(pwd)"
    disable source_path_used
else
    source_path="$(cd "$source_path"; pwd)"
    case "$source_path" in
        *[[:blank:]]*) die "Out of tree builds are impossible with whitespace in source path." ;;
    esac
    test -e "$source_path/config.h" &&
        die "Out of tree builds are impossible with config.h in source dir."
fi

for v in "$@"; do
    MYTHTV_CONFIGURATION="${MYTHTV_CONFIGURATION# } ${v}"
done

find_things(){
    thing=$1
    pattern=$2
    file=$source_path/$3
    sed -n "s/^[^#]*$pattern.*([^,]*, *\([^,]*\)\(,.*\)*).*/\1_$thing/p" "$file"
}

find_things_extern(){
    thing=$1
    pattern=$2
    file=$source_path/$3
    sed -n "s/^[^#]*extern.*$pattern *ff_\([^ ]*\)_$thing;/\1_$thing/p" "$file"
}

for n in $COMPONENT_LIST; do
    v=$(toupper ${n%s})_LIST
    eval enable \$$v
    eval ${n}_if_any="\$$v"
done

enable $ARCH_EXT_LIST

die_unknown(){
    echo "Unknown option \"$1\"."
    echo "See $0 --help for available options."
    exit 1
}

print_in_columns() {
    cols=$(expr $ncols / 24)
    cat | tr ' ' '\n' | sort | pr -r "-$cols" -w $ncols -t
}

show_list() {
    suffix=_$1
    shift
    echo $* | sed s/$suffix//g | print_in_columns
    exit 0
}

rand_list(){
    IFS=', '
    set -- $*
    unset IFS
    for thing; do
        comp=${thing%:*}
        prob=${thing#$comp}
        prob=${prob#:}
        is_in ${comp} $COMPONENT_LIST && eval comp=\$$(toupper ${comp%s})_LIST
        echo "prob ${prob:-0.5}"
        printf '%s\n' $comp
    done
}

do_random(){
    action=$1
    shift
    random_seed=$(awk "BEGIN { srand($random_seed); print srand() }")
    $action $(rand_list "$@" | awk "BEGIN { srand($random_seed) } \$1 == \"prob\" { prob = \$2; next } rand() < prob { print }")
}

if [ -e config.log ] ; then
    PCONF=$(tail -n 1 config.log | grep configure | sed 's/.\/configure//g')
    for opt in "$@" ; do
        if test x"$opt" != x"--prev" -a x"$opt" != x"--previous" ; then
            OTHOPT="${OTHOPT# }${opt}"
        fi
        if test x"$opt" = x"--prev" -o x"$opt" = x"--previous" ; then
            if test x"$PCONF" != "--prev" ; then
                PREV="yes";
            fi
        fi
    done
    if test x"$PREV" = x"yes"; then
        echo "Options: $PCONF $OTHOPT"
        ./configure $PCONF $OTHOPT
        exit
    fi
fi

for opt do
    optval="${opt#*=}"
    case "$opt" in
#Myth options
        --compile-type=*) compile_type=$optval
        ;;
        --libdir-name=*) libdir_name=$optval
        ;;
        --extra-cxxflags=*) add_ecxxflags $optval
        ;;
        --firewire-sdk=*) firewiresdk_path="${optval}"
        ;;
        --arch=*) arch=$optval && enable cpu_override
        ;;
        --cpu=*) cpu=$optval && enable cpu_override
        ;;
        --tune=*) tune=$optval
        ;;
        --disable-ccache) disable ccache
        ;;
        --disable-distcc) disable distcc
        ;;
# disabled due to abuse in Gentoo ebuild
        --disable-frontend)
        ;;
# disabled due to abuse in Gentoo ebuild
        --disable-backend)
        ;;
        --enable-mac-bundle) enable mac_bundle
        ;;
        --enable-opengles) enable opengles && disable opengl
        ;;
        --enable-vulkan) enable vulkan
        ;;
        --disable-waylandextras) disable waylandextras
        ;;
        --enable-libglslang) enable libglslang
        ;;
        --previous|--prev)
            echo "No history of previous configure parameters."
        ;;
        --with-bindings=*)
            tmp_bindings=`echo ${optval} | sed -e 's/,/ /g'`
            for binding in ${tmp_bindings} ; do
                if test x"${binding}" = x"perl"; then
                    bindings_perl="yes"
                fi
                if test x"${binding}" = x"python"; then
                    bindings_python="yes"
                fi
                if test x"${binding}" = x"php"; then
                    bindings_php="yes"
                fi
            done
        ;;
        --without-bindings=*)
            tmp_bindings=`echo ${optval} | sed -e 's/,/ /g'`
            for binding in ${tmp_bindings} ; do
                if test x"${binding}" = x"perl"; then
                    bindings_perl="no"
                fi
                if test x"${binding}" = x"python"; then
                    bindings_python="no"
                fi
                if test x"${binding}" = x"php"; then
                    bindings_php="no"
                fi
            done
        ;;
        --perl-config-opts=*)
          PERL_CONFIG_OPTS=`echo ${optval}`
        ;;
#FFmpeg original
        --extra-ldflags=*)
            add_ldflags $optval
	    ffmpeg_extra_ldflags="$optval"
        ;;
        --extra-ldexeflags=*)
            add_ldexeflags $optval
        ;;
        --extra-ldlibflags=*)
            add_ldlibflags $optval
        ;;
        --extra-libs=*)
            add_extralibs $optval
        ;;
        --disable-devices)
            disable $INDEV_LIST $OUTDEV_LIST
        ;;
        --enable-debug=*)
            debuglevel="$optval"
        ;;
        --disable-programs)
            disable $PROGRAM_LIST
        ;;
        --disable-everything)
            map 'eval unset \${$(toupper ${v%s})_LIST}' $COMPONENT_LIST
        ;;
        --disable-all)
            map 'eval unset \${$(toupper ${v%s})_LIST}' $COMPONENT_LIST
            disable $LIBRARY_LIST $PROGRAM_LIST doc
            enable avutil
        ;;
        --enable-random|--disable-random)
            action=${opt%%-random}
            do_random ${action#--} $COMPONENT_LIST
        ;;
        --enable-random=*|--disable-random=*)
            action=${opt%%-random=*}
            do_random ${action#--} $optval
        ;;
        --enable-*=*|--disable-*=*)
            eval $(echo "${opt%%=*}" | sed 's/--/action=/;s/-/ thing=/')
            is_in "${thing}s" $COMPONENT_LIST || die_unknown "$opt"
            eval list=\$$(toupper $thing)_LIST
            name=$(echo "${optval}" | sed "s/,/_${thing}|/g")_${thing}
            list=$(filter "$name" $list)
            [ "$list" = "" ] && warn "Option $opt did not match anything"
            $action $list
        ;;
        --enable-yasm|--disable-yasm)
            warn "The ${opt} option is only provided for compatibility and will be\n"\
                 "removed in the future. Use --enable-x86asm / --disable-x86asm instead."
            test $opt = --enable-yasm && x86asm=yes || x86asm=no
        ;;
        --yasmexe=*)
            warn "The --yasmexe option is only provided for compatibility and will be\n"\
                 "removed in the future. Use --x86asmexe instead."
            x86asmexe="$optval"
        ;;
        --enable-?*|--disable-?*)
            eval $(echo "$opt" | sed 's/--/action=/;s/-/ option=/;s/-/_/g')
            if is_in $option $COMPONENT_LIST; then
                test $action = disable && action=unset
                eval $action \$$(toupper ${option%s})_LIST
            elif is_in $option $CMDLINE_SELECT; then
                $action $option
            else
                die_unknown $opt
            fi
        ;;
        --list-*)
            NAME="${opt#--list-}"
            is_in $NAME $COMPONENT_LIST || die_unknown $opt
            NAME=${NAME%s}
            eval show_list $NAME \$$(toupper $NAME)_LIST
        ;;
        --help|-h) show_help
        ;;
        --quiet|-q) quiet=yes
        ;;
        --fatal-warnings) enable fatal_warnings
        ;;
        --libfuzzer=*)
            libfuzzer_path="$optval"
        ;;
        *)
            optname="${opt%%=*}"
            optname="${optname#--}"
            optname=$(echo "$optname" | sed 's/-/_/g')
            if is_in $optname $CMDLINE_SET; then
                eval $optname='$optval'
            elif is_in $optname $CMDLINE_APPEND; then
                append $optname "$optval"
            else
                die_unknown $opt
            fi
        ;;
    esac
done

if enabled sdl ; then
    enable sdl2
    enable ffplay
fi

#setting default runtime prefix and libdir
if test -n "${prefix}"; then
    runprefix_default=${prefix}
    libdir_default="${prefix}/${libdir_name}"
    shlibdir_default="${prefix}/${libdir_name}"
else
    runprefix_default=${prefix_default}
    libdir_default="${prefix_default}/${libdir_name}"
    shlibdir_default="${prefix_default}/${libdir_name}"
fi

if enabled_any cpu_override cross_compile || test x"$tune" != x"generic" &&
    enabled proc_opt; then
    echo "Warning! --enable-proc-opt shouldn't be used with --arch, --cpu or --tune"
    echo "Disabling it now."
    disable proc_opt
fi

for e in $env; do
    eval "export $e"
done

if disabled autodetect; then

    disable_weak $EXTERNAL_AUTODETECT_LIBRARY_LIST
    disable_weak $HWACCEL_AUTODETECT_LIBRARY_LIST
fi
# Mark specifically enabled, but normally autodetected libraries as requested.
for lib in $AUTODETECT_LIBS; do
    enabled $lib && request $lib
done
#TODO: switch to $AUTODETECT_LIBS when $THREADS_LIST is supported the same way
enable_weak $EXTERNAL_AUTODETECT_LIBRARY_LIST
enable_weak $HWACCEL_AUTODETECT_LIBRARY_LIST

disabled logging && logfile=/dev/null

die_license_disabled() {
    enabled $1 || { enabled $v && die "$v is $1 and --enable-$1 is not specified."; }
}

die_license_disabled_gpl() {
    enabled $1 || { enabled $v && die "$v is incompatible with the gpl and --enable-$1 is not specified."; }
}

map "die_license_disabled gpl"      $EXTERNAL_LIBRARY_GPL_LIST $EXTERNAL_LIBRARY_GPLV3_LIST
map "die_license_disabled version3" $EXTERNAL_LIBRARY_VERSION3_LIST $EXTERNAL_LIBRARY_GPLV3_LIST

enabled gpl && map "die_license_disabled_gpl nonfree" $EXTERNAL_LIBRARY_NONFREE_LIST
map "die_license_disabled nonfree" $HWACCEL_LIBRARY_NONFREE_LIST

enabled version3 && { enabled gpl && enable gplv3 || enable lgplv3; }

# Disable all the library-specific components if the library itself
# is disabled, see AVCODEC_LIST and following _LIST variables.

disable_components(){
    disabled ${1} && disable $(
        eval components="\$$(toupper ${1})_COMPONENTS"
        map 'eval echo \${$(toupper ${v%s})_LIST}' $components
    )
}

map 'disable_components $v' $LIBRARY_LIST

echo "# $0 $MYTHTV_CONFIGURATION" > $logfile
set >> $logfile

test -n "$valgrind" && toolchain="valgrind-memcheck"

enabled ossfuzz && {
    add_cflags  -fsanitize=address,undefined -fsanitize-coverage=trace-pc-guard,trace-cmp -fno-omit-frame-pointer
    add_ldflags -fsanitize=address,undefined -fsanitize-coverage=trace-pc-guard,trace-cmp
}

case "$toolchain" in
    *-asan)
        cc_default="${toolchain%-asan}"
        add_cflags  -fsanitize=address
        add_ldflags -fsanitize=address
    ;;
    *-msan)
        cc_default="${toolchain%-msan}"
        add_cflags  -fsanitize=memory -fsanitize-memory-track-origins
        add_ldflags -fsanitize=memory
    ;;
    *-tsan)
        cc_default="${toolchain%-tsan}"
        add_cflags  -fsanitize=thread -fPIE
        add_ldflags -fsanitize=thread -pie
        case "$toolchain" in
            gcc-tsan)
                add_cflags  -fPIC
                add_ldflags -fPIC
                ;;
        esac
    ;;
    *-usan)
        cc_default="${toolchain%-usan}"
        add_cflags  -fsanitize=undefined
        add_ldflags -fsanitize=undefined
    ;;
    valgrind-*)
        target_exec_default="valgrind"
        case "$toolchain" in
            valgrind-massif)
                target_exec_args="--tool=massif --alloc-fn=av_malloc --alloc-fn=av_mallocz --alloc-fn=av_calloc --alloc-fn=av_fast_padded_malloc --alloc-fn=av_fast_malloc --alloc-fn=av_realloc_f --alloc-fn=av_fast_realloc --alloc-fn=av_realloc"
                ;;
            valgrind-memcheck)
                target_exec_args="--error-exitcode=1 --malloc-fill=0x2a --track-origins=yes --leak-check=full --gen-suppressions=all"
                ;;
        esac
    ;;
    msvc)
        # Check whether the current MSVC version needs the C99 converter.
        # From MSVC 2013 (compiler major version 18) onwards, it does actually
        # support enough of C99 to build ffmpeg. Default to the new
        # behaviour if the regexp was unable to match anything, since this
        # successfully parses the version number of existing supported
        # versions that require the converter (MSVC 2010 and 2012).
        cl_major_ver=$(cl 2>&1 | sed -n 's/.*Version \([[:digit:]]\{1,\}\)\..*/\1/p')
        if [ -z "$cl_major_ver" ] || [ $cl_major_ver -ge 18 ]; then
            cc_default="cl"
            cxx_default="cl"
        else
            cc_default="c99wrap cl"
            cxx_default="c99wrap cl"
        fi
        ld_default="$source_path/compat/windows/mslink"
        nm_default="dumpbin -symbols"
        ar_default="lib"
        case "$arch" in
        arm*)
            as_default="armasm"
            ;;
        esac
        target_os_default="win32"
        # Use a relative path for TMPDIR. This makes sure all the
        # ffconf temp files are written with a relative path, avoiding
        # issues with msys/win32 path conversion for MSVC parameters
        # such as -Fo<file> or -out:<file>.
        TMPDIR=.
    ;;
    icl)
        cc_default="icl"
        ld_default="xilink"
        nm_default="dumpbin -symbols"
        ar_default="xilib"
        target_os_default="win32"
        TMPDIR=.
    ;;
    gcov)
        add_cflags   -fprofile-arcs -ftest-coverage
        add_cxxflags -fprofile-arcs -ftest-coverage
        add_ldflags  --coverage
    ;;
    llvm-cov)
        add_cflags   -fprofile-instr-generate -fcoverage-mapping
        add_cxxflags -fprofile-instr-generate -fcoverage-mapping
        add_ldflags  --coverage
    ;;
    hardened)
        add_cppflags -O2 -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=2
        add_cxxflags -O2 -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=2
        add_cflags   -fno-strict-overflow -fstack-protector-all
        add_cxxflags -fno-strict-overflow -fstack-protector-all
        add_ldflags  -Wl,-z,relro -Wl,-z,now
        add_cflags   -fPIE
        add_cxxflags -fPIE
        add_ldexeflags -fPIE -pie
    ;;
    ?*)
        die "Unknown toolchain $toolchain"
    ;;
esac

test -n "$cross_prefix" && enable cross_compile

if enabled cross_compile; then
    test -n "$arch" && test -n "$target_os" ||
        die "Must specify target arch (--arch) and OS (--target-os) when cross-compiling"
fi
test -z "$cross_prefix_cc" && cross_prefix_cc="$cross_prefix"

if enabled set_cc_default; then
    test -n "$cc" && cc_default="$cc"
    test -n "$cxx" && cxx_default="$cxx"
fi
ar_default="${cross_prefix}${ar_default}"
cc_default="${cross_prefix_cc}${cc_default}"
cxx_default="${cross_prefix_cc}${cxx_default}"
if enabled set_cc_default; then
    cc="$cc_default"
    cxx="$cxx_default"
fi
nm_default="${cross_prefix}${nm_default}"
pkg_config_default="${cross_prefix}${pkg_config_default}"
if ${cross_prefix}${ranlib_default} 2>&1 | grep -q "\-D "; then
    ranlib_default="${cross_prefix}${ranlib_default} -D"
else
    ranlib_default="${cross_prefix}${ranlib_default}"
fi
windres_default="${cross_prefix}${windres_default}"

sysinclude_default="${sysroot}/usr/include"

set_default arch cc cxx doxygen pkg_config ranlib sysinclude \
    target_exec target_os x86asmexe nvcc
enabled cross_compile || host_cc_default=$cc
set_default host_cc

pkg_config_fail_message=""
if ! $pkg_config --version >/dev/null 2>&1; then
    warn "$pkg_config not found, library detection may fail."
    pkg_config=false
elif is_in -static $cc $LDFLAGS && ! is_in --static $pkg_config $pkg_config_flags; then
    pkg_config_fail_message="
Note: When building a static binary, add --pkg-config-flags=\"--static\"."
fi

set_default qmake qmakespecs python x86asmexe

if test $doxygen != $doxygen_default && \
  ! $doxygen --version >/dev/null 2>&1; then
    warn "Specified doxygen \"$doxygen\" not found, API documentation will fail to build."
fi

exesuf() {
    case $1 in
        mingw32*|mingw64*|win32|win64|cygwin*|*-dos|freedos|opendos|os/2*|symbian) echo .exe ;;
    esac
}

EXESUF=$(exesuf $target_os)
HOSTEXESUF=$(exesuf $host_os)

# set temporary file name
: ${TMPDIR:=$TEMPDIR}
: ${TMPDIR:=$TMP}
: ${TMPDIR:=/tmp}

if [ -n "$tempprefix" ] ; then
    mktemp(){
        tmpname="$tempprefix.${HOSTNAME}.${UID}"
        echo "$tmpname"
        mkdir "$tmpname"
    }
elif ! check_cmd mktemp -u XXXXXX; then
    # simple replacement for missing mktemp
    # NOT SAFE FOR GENERAL USE
    mktemp(){
        tmpname="${2%%XXX*}.${HOSTNAME}.${UID}.$$"
        echo "$tmpname"
        mkdir "$tmpname"
    }
fi

FFTMPDIR=$(mktemp -d "${TMPDIR}/ffconf.XXXXXXXX" 2> /dev/null) ||
    die "Unable to create temporary directory in $TMPDIR."

tmpfile(){
    tmp="${FFTMPDIR}/test"$2
    (set -C; exec > $tmp) 2> /dev/null ||
        die "Unable to create temporary file in $FFTMPDIR."
    eval $1=$tmp
}

trap 'rm -rf -- "$FFTMPDIR"' EXIT
trap 'exit 2' HUP INT TERM

tmpfile TMPC  .c
tmpfile TMPCPP .cpp
tmpfile TMPE  $EXESUF
tmpfile TMPH  .h
tmpfile TMPM   .m
tmpfile TMPO  .o
tmpfile TMPS  .S
tmpfile TMPSH .sh
tmpfile TMPV  .ver
tmpfile TMPMAK .mak
tmpfile TMPPRO .pro

unset -f mktemp

chmod +x $TMPE

# make sure we can execute files in $TMPDIR
cat > $TMPSH 2>> $logfile <<EOF
#! /bin/sh
EOF
chmod +x $TMPSH >> $logfile 2>&1
if ! $TMPSH >> $logfile 2>&1; then
    cat <<EOF
Unable to create and execute files in $TMPDIR.  Set the TMPDIR environment
variable to another directory and make sure that it is not mounted noexec.
EOF
    die "Sanity test failed."
fi

armasm_flags(){
    for flag; do
        case $flag in
            # Filter out MSVC cl.exe options from cflags that shouldn't
            # be passed to gas-preprocessor
            -M[TD]*)                                            ;;
            *)                  echo $flag                      ;;
        esac
   done
}

ccc_flags(){
    for flag; do
        case $flag in
            -std=c99)           echo -c99                       ;;
            -mcpu=*)            echo -arch ${flag#*=}           ;;
            -mieee)             echo -ieee                      ;;
            -O*|-fast)          echo $flag                      ;;
            -fno-math-errno)    echo -assume nomath_errno       ;;
            -g)                 echo -g3                        ;;
            -Wall)              echo -msg_enable level2         ;;
            -Wno-pointer-sign)  echo -msg_disable ptrmismatch1  ;;
            -Wl,*)              echo $flag                      ;;
            -f*|-W*)                                            ;;
            *)                  echo $flag                      ;;
        esac
   done
}

cparser_flags(){
    for flag; do
        case $flag in
            -Wno-switch)             echo -Wno-switch-enum ;;
            -Wno-format-zero-length) ;;
            -Wdisabled-optimization) ;;
            -Wno-pointer-sign)       echo -Wno-other ;;
            *)                       echo $flag ;;
        esac
    done
}

msvc_common_flags(){
    for flag; do
        case $flag in
            # In addition to specifying certain flags under the compiler
            # specific filters, they must be specified here as well or else the
            # generic catch all at the bottom will print the original flag.
            -Wall)                ;;
            -Wextra)              ;;
            -std=c99)             ;;
            # Common flags
            -fomit-frame-pointer) ;;
            -g)                   echo -Z7 ;;
            -fno-math-errno)      ;;
            -fno-common)          ;;
            -fno-signed-zeros)    ;;
            -fPIC)                ;;
            -mthumb)              ;;
            -march=*)             ;;
            -lz)                  echo zlib.lib ;;
            -lx264)               echo libx264.lib ;;
            -lstdc++)             ;;
            -l*)                  echo ${flag#-l}.lib ;;
            -LARGEADDRESSAWARE)   echo $flag ;;
            -L*)                  echo -libpath:${flag#-L} ;;
            *)                    echo $flag ;;
        esac
    done
}

msvc_flags(){
    msvc_common_flags "$@"
    for flag; do
        case $flag in
            -Wall)                echo -W3 -wd4018 -wd4146 -wd4244 -wd4305     \
                                       -wd4554 ;;
            -Wextra)              echo -W4 -wd4244 -wd4127 -wd4018 -wd4389     \
                                       -wd4146 -wd4057 -wd4204 -wd4706 -wd4305 \
                                       -wd4152 -wd4324 -we4013 -wd4100 -wd4214 \
                                       -wd4307 \
                                       -wd4273 -wd4554 -wd4701 -wd4703 ;;
        esac
    done
}

icl_flags(){
    msvc_common_flags "$@"
    for flag; do
        case $flag in
            # Despite what Intel's documentation says -Wall, which is supported
            # on Windows, does enable remarks so disable them here.
            -Wall)                echo $flag -Qdiag-disable:remark ;;
            -std=c99)             echo -Qstd=c99 ;;
            -flto)                echo -ipo ;;
        esac
    done
}

icc_flags(){
    for flag; do
        case $flag in
            -flto)                echo -ipo ;;
            *)                    echo $flag ;;
        esac
    done
}

pgi_flags(){
    for flag; do
        case $flag in
            -flto)                echo -Mipa=fast,libopt,libinline,vestigial ;;
            -fomit-frame-pointer) echo -Mnoframe ;;
            -g)                   echo -gopt ;;
            *)                    echo $flag ;;
        esac
    done
}

suncc_flags(){
    for flag; do
        case $flag in
            -march=*|-mcpu=*)
                case "${flag#*=}" in
                    native)                   echo -xtarget=native       ;;
                    v9|niagara)               echo -xarch=sparc          ;;
                    ultrasparc)               echo -xarch=sparcvis       ;;
                    ultrasparc3|niagara2)     echo -xarch=sparcvis2      ;;
                    i586|pentium)             echo -xchip=pentium        ;;
                    i686|pentiumpro|pentium2) echo -xtarget=pentium_pro  ;;
                    pentium3*|c3-2)           echo -xtarget=pentium3     ;;
                    pentium-m)          echo -xarch=sse2 -xchip=pentium3 ;;
                    pentium4*)          echo -xtarget=pentium4           ;;
                    prescott|nocona)    echo -xarch=sse3 -xchip=pentium4 ;;
                    *-sse3)             echo -xarch=sse3                 ;;
                    core2)              echo -xarch=ssse3 -xchip=core2   ;;
                    bonnell)                   echo -xarch=ssse3         ;;
                    corei7|nehalem)            echo -xtarget=nehalem     ;;
                    westmere)                  echo -xtarget=westmere    ;;
                    silvermont)                echo -xarch=sse4_2        ;;
                    corei7-avx|sandybridge)    echo -xtarget=sandybridge ;;
                    core-avx*|ivybridge|haswell|broadwell|skylake*|knl)
                                               echo -xarch=avx           ;;
                    amdfam10|barcelona)        echo -xtarget=barcelona   ;;
                    btver1)                    echo -xarch=amdsse4a      ;;
                    btver2|bdver*|znver*)      echo -xarch=avx           ;;
                    athlon-4|athlon-[mx]p)     echo -xarch=ssea          ;;
                    k8|opteron|athlon64|athlon-fx)
                                               echo -xarch=sse2a         ;;
                    athlon*)                   echo -xarch=pentium_proa  ;;
                esac
                ;;
            -std=c99)             echo -xc99              ;;
            -fomit-frame-pointer) echo -xregs=frameptr    ;;
            -fPIC)                echo -KPIC -xcode=pic32 ;;
            -W*,*)                echo $flag              ;;
            -f*-*|-W*|-mimpure-text)                      ;;
            -shared)              echo -G                 ;;
            *)                    echo $flag              ;;
        esac
    done
}

tms470_flags(){
    for flag; do
        case $flag in
            -march=*|-mcpu=*)
                case "${flag#*=}" in
                    armv7-a|cortex-a*)      echo -mv=7a8 ;;
                    armv7-r|cortex-r*)      echo -mv=7r4 ;;
                    armv7-m|cortex-m*)      echo -mv=7m3 ;;
                    armv6*|arm11*)          echo -mv=6   ;;
                    armv5*e|arm[79]*e*|arm9[24]6*|arm96*|arm102[26])
                                            echo -mv=5e  ;;
                    armv4*|arm7*|arm9[24]*) echo -mv=4   ;;
                esac
                ;;
            -mfpu=neon)     echo --float_support=vfpv3 --neon ;;
            -mfpu=vfp)      echo --float_support=vfpv2        ;;
            -mfpu=vfpv3)    echo --float_support=vfpv3        ;;
            -mfpu=vfpv3-d16) echo --float_support=vfpv3d16    ;;
            -msoft-float)   echo --float_support=vfplib       ;;
            -O[0-3]|-mf=*)  echo $flag                        ;;
            -g)             echo -g -mn                       ;;
            -pds=*)         echo $flag                        ;;
            -D*|-I*)        echo $flag                        ;;
            --gcc|--abi=*)  echo $flag                        ;;
            -me)            echo $flag                        ;;
        esac
    done
}

probe_cc(){
    pfx=$1
    _cc=$2
    first=$3

    unset _type _ident _cc_c _cc_e _cc_o _flags _cflags
    unset _ld_o _ldflags _ld_lib _ld_path
    unset _depflags _DEPCMD _DEPFLAGS
    _flags_filter=echo

    if $_cc --version 2>&1 | grep -q '^GNU assembler'; then
        true # no-op to avoid reading stdin in following checks
    elif $_cc -v 2>&1 | grep -q '^gcc.*LLVM'; then
        _type=llvm_gcc
        gcc_extra_ver=$(expr "$($_cc --version 2>/dev/null | head -n1)" : '.*\((.*)\)')
        _ident="llvm-gcc $($_cc -dumpversion 2>/dev/null) $gcc_extra_ver"
        _depflags='-MMD -MF $(@:.o=.d) -MT $@'
        _cflags_speed='-O3'
        _cflags_size='-Os'
    elif $_cc -v 2>&1 | grep -qi ^gcc; then
        _type=gcc
        gcc_version=$($_cc --version | head -n1)
        gcc_basever=$($_cc -dumpversion)
        gcc_pkg_ver=$(expr "$gcc_version" : '[^ ]* \(([^)]*)\)')
        gcc_ext_ver=$(expr "$gcc_version" : ".*$gcc_pkg_ver $gcc_basever \\(.*\\)")
        _ident=$(cleanws "gcc $gcc_basever $gcc_pkg_ver $gcc_ext_ver")
        case $gcc_basever in
            2) ;;
            2.*) ;;
            *) _depflags='-MMD -MF $(@:.o=.d) -MT $@' ;;
        esac
        if [ "$first" = true ]; then
            case $gcc_basever in
                4.2*)
                warn "gcc 4.2 is outdated and may miscompile FFmpeg. Please use a newer compiler." ;;
            esac
        fi
        _cflags_speed='-O3'
        _cflags_size='-Os'
    elif $_cc --version 2>/dev/null | grep -q ^icc; then
        _type=icc
        _ident=$($_cc --version | head -n1)
        _depflags='-MMD'
        _cflags_speed='-O3'
        _cflags_size='-Os'
        _cflags_noopt='-O1'
        _flags_filter=icc_flags
    elif $_cc -v 2>&1 | grep -q xlc; then
        _type=xlc
        _ident=$($_cc -qversion 2>/dev/null | head -n1)
        _cflags_speed='-O5'
        _cflags_size='-O5 -qcompact'
    elif $_cc -V 2>/dev/null | grep -q Compaq; then
        _type=ccc
        _ident=$($_cc -V | head -n1 | cut -d' ' -f1-3)
        _DEPFLAGS='-M'
        _cflags_speed='-fast'
        _cflags_size='-O1'
        _flags_filter=ccc_flags
    elif $_cc --vsn 2>/dev/null | grep -Eq "ARM (C/C\+\+ )?Compiler"; then
        test -d "$sysroot" || die "No valid sysroot specified."
        _type=armcc
        _ident=$($_cc --vsn | grep -i build | head -n1 | sed 's/.*: //')
        armcc_conf="$PWD/armcc.conf"
        $_cc --arm_linux_configure                 \
             --arm_linux_config_file="$armcc_conf" \
             --configure_sysroot="$sysroot"        \
             --configure_cpp_headers="$sysinclude" >>$logfile 2>&1 ||
             die "Error creating armcc configuration file."
        $_cc --vsn | grep -q RVCT && armcc_opt=rvct || armcc_opt=armcc
        _flags="--arm_linux_config_file=$armcc_conf --translate_gcc"
        as_default="${cross_prefix}gcc"
        _depflags='-MMD'
        _cflags_speed='-O3'
        _cflags_size='-Os'
    elif $_cc -version 2>/dev/null | grep -Eq 'TMS470|TI ARM'; then
        _type=tms470
        _ident=$($_cc -version | head -n1 | tr -s ' ')
        _flags='--gcc --abi=eabi -me'
        _cc_e='-ppl -fe=$@'
        _cc_o='-fe=$@'
        _depflags='-ppa -ppd=$(@:.o=.d)'
        _cflags_speed='-O3 -mf=5'
        _cflags_size='-O3 -mf=2'
        _flags_filter=tms470_flags
    elif $_cc -v 2>&1 | grep -q clang; then
        _type=clang
        _ident=$($_cc --version 2>/dev/null | head -n1)
        _depflags='-MMD -MF $(@:.o=.d) -MT $@'
        _cflags_speed='-O3'
        _cflags_size='-Oz'
    elif $_cc -V 2>&1 | grep -q Sun; then
        _type=suncc
        _ident=$($_cc -V 2>&1 | head -n1 | cut -d' ' -f 2-)
        _DEPCMD='$(DEP$(1)) $(DEP$(1)FLAGS) $($(1)DEP_FLAGS) $< | sed -e "1s,^.*: ,$@: ," -e "\$$!s,\$$, \\\," -e "1!s,^.*: , ," > $(@:.o=.d)'
        _DEPFLAGS='-xM1 -xc99'
        _ldflags='-std=c99'
        _cflags_speed='-O5'
        _cflags_size='-O5 -xspace'
        _flags_filter=suncc_flags
    elif $_cc -v 2>&1 | grep -q 'PathScale\|Path64'; then
        _type=pathscale
        _ident=$($_cc -v 2>&1 | head -n1 | tr -d :)
        _depflags='-MMD -MF $(@:.o=.d) -MT $@'
        _cflags_speed='-O2'
        _cflags_size='-Os'
        _flags_filter='filter_out -Wdisabled-optimization'
    elif $_cc -v 2>&1 | grep -q Open64; then
        _type=open64
        _ident=$($_cc -v 2>&1 | head -n1 | tr -d :)
        _depflags='-MMD -MF $(@:.o=.d) -MT $@'
        _cflags_speed='-O2'
        _cflags_size='-Os'
        _flags_filter='filter_out -Wdisabled-optimization|-Wtype-limits|-fno-signed-zeros'
    elif $_cc -V 2>&1 | grep -q Portland; then
        _type=pgi
        _ident="PGI $($_cc -V 2>&1 | awk '/^pgcc/ { print $2; exit }')"
        opt_common='-alias=ansi -Mdse -Mlre -Mpre'
        _cflags_speed="-O3 -Mautoinline -Munroll=c:4 $opt_common"
        _cflags_size="-O2 -Munroll=c:1 $opt_common"
        _cflags_noopt="-O"
        _flags_filter=pgi_flags
    elif $_cc 2>&1 | grep -q 'Microsoft.*ARM.*Assembler'; then
        _type=armasm
        _ident=$($_cc | head -n1)
        # 4509: "This form of conditional instruction is deprecated"
        _flags="-nologo -ignore 4509"
        _flags_filter=armasm_flags
    elif $_cc 2>&1 | grep -q Intel; then
        _type=icl
        _ident=$($_cc 2>&1 | head -n1)
        _depflags='-QMMD -QMF$(@:.o=.d) -QMT$@'
        # Not only is O3 broken on 13.x+ but it is slower on all previous
        # versions (tested) as well.
        _cflags_speed="-O2"
        _cflags_size="-O1 -Oi" # -O1 without -Oi miscompiles stuff
        if $_cc 2>&1 | grep -q Linker; then
            _ld_o='-out:$@'
        else
            _ld_o='-Fe$@'
        fi
        _cc_o='-Fo$@'
        _cc_e='-P'
        _flags_filter=icl_flags
        _ld_lib='lib%.a'
        _ld_path='-libpath:'
        # -Qdiag-error to make icl error when seeing certain unknown arguments
        _flags='-nologo -Qdiag-error:4044,10157'
        # -Qvec- -Qsimd- to prevent miscompilation, -GS, fp:precise for consistency
        # with MSVC which enables it by default.
        _cflags='-Qms0 -Qvec- -Qsimd- -GS -fp:precise'
    elif $_cc -? 2>/dev/null | grep -q 'LLVM.*Linker'; then
        # lld can emulate multiple different linkers; in ms link.exe mode,
        # the -? parameter gives the help output which contains an identifyable
        # string, while it gives an error in other modes.
        _type=lld-link
        # The link.exe mode doesn't have a switch for getting the version,
        # but we can force it back to gnu mode and get the version from there.
        _ident=$($_cc -flavor gnu --version 2>/dev/null)
        _ld_o='-out:$@'
        _flags_filter=msvc_flags
        _ld_lib='lib%.a'
        _ld_path='-libpath:'
    elif $_cc -nologo- 2>&1 | grep -q Microsoft; then
        _type=msvc
        _ident=$($_cc 2>&1 | head -n1)
        _DEPCMD='$(DEP$(1)) $(DEP$(1)FLAGS) $($(1)DEP_FLAGS) $< 2>&1 | awk '\''/including/ { sub(/^.*file: */, ""); gsub(/\\/, "/"); if (!match($$0, / /)) print "$@:", $$0 }'\'' > $(@:.o=.d)'
        _DEPFLAGS='$(CPPFLAGS) $(CFLAGS) -showIncludes -Zs'
        _cflags_speed="-O2"
        _cflags_size="-O1"
        _cflags_noopt="-O1"
        if $_cc -nologo- 2>&1 | grep -q Linker; then
            _ld_o='-out:$@'
        else
            _ld_o='-Fe$@'
        fi
        _cc_o='-Fo$@'
        _cc_e='-P -Fi$@'
        _flags_filter=msvc_flags
        _ld_lib='lib%.a'
        _ld_path='-libpath:'
        _flags='-nologo'
    elif $_cc --version 2>/dev/null | grep -q ^cparser; then
        _type=cparser
        _ident=$($_cc --version | head -n1)
        _depflags='-MMD'
        _cflags_speed='-O4'
        _cflags_size='-O2'
        _flags_filter=cparser_flags
    fi

    eval ${pfx}_type=\$_type
    eval ${pfx}_ident=\$_ident
}

set_ccvars(){
    eval ${1}_C=\${_cc_c-\${${1}_C}}
    eval ${1}_E=\${_cc_e-\${${1}_E}}
    eval ${1}_O=\${_cc_o-\${${1}_O}}

    if [ -n "$_depflags" ]; then
        eval ${1}_DEPFLAGS=\$_depflags
    else
        eval ${1}DEP=\${_DEPCMD:-\$DEPCMD}
        eval ${1}DEP_FLAGS=\${_DEPFLAGS:-\$DEPFLAGS}
        eval DEP${1}FLAGS=\$_flags
    fi
}

probe_cc cc "$cc" "true"
cflags_filter=$_flags_filter
cflags_speed=$_cflags_speed
cflags_size=$_cflags_size
cflags_noopt=$_cflags_noopt
add_cflags $_flags $_cflags
cc_ldflags=$_ldflags
set_ccvars CC
set_ccvars CXX

probe_cc hostcc "$host_cc"
host_cflags_filter=$_flags_filter
host_cflags_speed=$_cflags_speed
add_host_cflags  $_flags $_cflags
set_ccvars HOSTCC

test -n "$cc_type" && enable $cc_type ||
    warn "Unknown C compiler $cc, unable to select optimal CFLAGS"


if $cxx -v 2>&1 | grep -qi ^gcc; then
    cxx_type=gxx
    gxx_version=$($cxx -dumpversion)
    gxx_major=$(echo $gxx_version | sed "s/\([0-9]*\).*/\\1/")
    if test $gxx_major -lt 8; then
        die "MythTV requires GCC 8 or better."
    fi
elif $cxx --version 2>/dev/null | grep -q Intel; then
    cxx_type=icpc
    gxx_version="AV_STRINGIFY(__INTEL_COMPILER)"
    cxx_ident=$($cxx --version | head -n1)
    icpc_version=$($cxx -dumpversion)
    speed_cxxflags='-O3'
    size_cxxflags='-Os'
    noopt_cxxflags='-O1'
elif $cxx --version 2>/dev/null | grep -q clang; then
    cxx_type=clangxx
    gxx_version="AV_STRINGIFY(__CLANG_COMPILER)"
    cxx_ident=$($cxx --version | head -n1)
    clangxx_version=$($cxx -dumpversion) # GCC equivalent version
    clangxx_major=$(echo $cxx_ident | sed "s/.*version \([0-9]*\).*/\\1/")
    speed_cxxflags='-O3'
    size_cxxflags='-Os'
    noopt_cxxflags='-O1'
fi

test -n "$cxx_type" && enable $cxx_type ||
    warn "Unknown C++ compiler $cxx, unable to select optimal CXXFLAGS"

: ${as_default:=$cc}
: ${objcc_default:=$cc}
: ${dep_cc_default:=$cc}
: ${ld_default:=$cc}
: ${host_ld_default:=$host_cc}
set_default ar as objcc dep_cc ld ln_s host_ld windres

probe_cc as "$as"
asflags_filter=$_flags_filter
add_asflags $_flags $_cflags
set_ccvars AS

probe_cc objcc "$objcc"
objcflags_filter=$_flags_filter
add_objcflags $_flags $_cflags
set_ccvars OBJC

probe_cc ld "$ld"
ldflags_filter=$_flags_filter
add_ldflags $_flags $_ldflags
test "$cc_type" != "$ld_type" && add_ldflags $cc_ldflags
LD_O=${_ld_o-$LD_O}
LD_LIB=${_ld_lib-$LD_LIB}
LD_PATH=${_ld_path-$LD_PATH}

probe_cc hostld "$host_ld"
host_ldflags_filter=$_flags_filter
add_host_ldflags $_flags $_ldflags
HOSTLD_O=${_ld_o-$HOSTLD_O}

if [ -z "$CC_DEPFLAGS" ] && [ "$dep_cc" != "$cc" ]; then
    probe_cc depcc "$dep_cc"
    CCDEP=${_DEPCMD:-$DEPCMD}
    CCDEP_FLAGS=${_DEPFLAGS:=$DEPFLAGS}
    DEPCCFLAGS=$_flags
fi

if $ar 2>&1 | grep -q Microsoft; then
    arflags="-nologo"
    ar_o='-out:$@'
elif $ar 2>&1 | grep -q 'Texas Instruments'; then
    arflags="rq"
    ar_o='$@'
elif $ar 2>&1 | grep -q 'Usage: ar.*-X.*any'; then
    arflags='-Xany -r -c'
    ar_o='$@'
elif $ar 2>&1 | grep -q "\[D\] "; then
    arflags="rcD"
    ar_o='$@'
else
    arflags="rc"
    ar_o='$@'
fi

add_cflags $extra_cflags
add_cxxflags $extra_cxxflags
add_objcflags $extra_objcflags
add_asflags $extra_cflags

if test -n "$sysroot"; then
    case "$cc_type" in
        gcc|llvm_gcc|clang)
            add_cppflags --sysroot="$sysroot"
            add_ldflags --sysroot="$sysroot"
# On Darwin --sysroot may be ignored, -isysroot always affects headers and linking
            add_cppflags -isysroot "$sysroot"
            add_ldflags -isysroot "$sysroot"
            add_cxxppflags --sysroot="$sysroot"
        ;;
        tms470)
            add_cppflags -I"$sysinclude"
            add_ldflags  --sysroot="$sysroot"
            add_cxxppflags -I"$sysinclude"
        ;;
    esac
fi

if test "$cpu" = host; then
    enabled cross_compile &&
        die "--cpu=host makes no sense when cross-compiling."

    case "$cc_type" in
        gcc|llvm_gcc)
            check_native(){
                $cc $1=native -v -c -o $TMPO $TMPC >$TMPE 2>&1 || return
                sed -n "/cc1.*$1=/{
                            s/.*$1=\\([^ ]*\\).*/\\1/
                            p
                            q
                        }" $TMPE
            }
            cpu=$(check_native -march || check_native -mcpu)
        ;;
        clang)
            check_native(){
                $cc $1=native -v -c -o $TMPO $TMPC >$TMPE 2>&1 || return
                sed -n "/cc1.*-target-cpu /{
                            s/.*-target-cpu \\([^ ]*\\).*/\\1/
                            p
                            q
                        }" $TMPE
            }
            cpu=$(check_native -march)
        ;;
    esac

    if test "${cpu:-host}" = host ; then
        enable proc_opt_old
        cpu="$arch"
    fi

    test "${cpu:-host}" = host &&
        die "--cpu=host not supported with compiler $cc"
fi

# Deal with common $arch aliases
case "$arch" in
    aarch64|arm64)
        arch="aarch64"
    ;;
    arm*|iPad*|iPhone*)
        arch="arm"
    ;;
    mips*|IP*)
        case "$arch" in
        *el)
            add_cppflags -EL
            add_ldflags -EL
        ;;
        *eb)
            add_cppflags -EB
            add_ldflags -EB
        ;;
        esac
        arch="mips"
    ;;
    parisc*|hppa*)
        arch="parisc"
    ;;
    "Power Macintosh"|ppc*|powerpc*)
        arch="ppc"
    ;;
    s390|s390x)
        arch="s390"
    ;;
    sh4|sh)
        arch="sh4"
    ;;
    sun4*|sparc*)
        arch="sparc"
    ;;
    tilegx|tile-gx)
        arch="tilegx"
    ;;
    i[3-6]86*|i86pc|BePC|x86pc|x86_64|x86_32|amd64)
        arch="x86"
    ;;
esac

is_in $arch $ARCH_LIST || warn "unknown architecture $arch"
enable $arch

# if no tune setting and we know cpu class look at $processor
if enabled proc_opt_old; then
# first try to tune based on processor info
# Intel i3, i5, i7 processors (EMT64T capable)
   if expr "$processor" : ".*Intel(R).*Core(TM) i[357] CPU.*" > /dev/null ; then
       cpu="core2"
# EM64T era Intel Xeon
   elif expr "$processor" : ".*Intel(R) Xeon(R) CPU.*51[1-6][08]" > /dev/null ; then
       cpu="core2"
   elif expr "$processor" : ".*Intel(R) Xeon(R) CPU.*54[0-9][025]" > /dev/null ; then
       cpu="core2"
   elif expr "$processor" : ".*Intel(R) Xeon(R) CPU.*33[2567]0" > /dev/null ; then
       cpu="core2"
   elif expr "$processor" : ".*Intel(R) Xeon(R) CPU.*X32[123]0" > /dev/null ; then
       cpu="core2"
# Various Intel Duo processors (EMT64T capable)
   elif expr "$processor" : ".*Intel(R).*Core(TM)2.*CPU" > /dev/null ; then
       cpu="core2"
   elif expr "$processor" : "*.Pentium(R) 5 CPU" > /dev/null ; then
       cpu="nocona"
# EM64T compatible Intel Celeron
   elif expr "$processor" : ".*Celeron(R) D CPU" > /dev/null ; then
       cpu="nocona"
       enable small
# Intel Core2 Duo
   elif expr "$processor" : ".*Genuine.*Intel.*CPU.*2160" > /dev/null ; then
       cpu="core2"
# Intel Atom
   elif expr "$processor" : ".*Intel(R) Atom(TM)" > /dev/null ; then
       cpu="nocona"
       enable small
# Reportedly Intel Duo, but we assume 32 bit P3 due to generic name
   elif expr "$processor" : ".*Genuine.*Intel.*CPU" > /dev/null ; then
       cpu="pentium3"
# Pentium-M derivative in AppleTV, assume 32 bit P3 due to generic name
   elif expr "$processor" : ".*Genuine.*Intel.*processor" > /dev/null ; then
       cpu="pentium3"
# P4
   elif expr "$processor" : ".*Xeon(TM) CPU" > /dev/null ; then
       cpu="pentium4"
   elif expr "$processor" : ".*XEON(TM) CPU" > /dev/null ; then
       cpu="pentium4"
   elif expr "$processor" : ".*XEON(TM) MP CPU" > /dev/null ; then
       cpu="pentium4"
   elif expr "$processor" : "pentium4" > /dev/null ; then
       cpu="pentium4"
   elif expr "$processor" : ".*Pentium(R) [4D]" > /dev/null ; then
       cpu="pentium4"
   elif expr "$processor" : ".*Celeron(R) CPU" > /dev/null ; then
       cpu="pentium4"
       enable small
# P6, which includes Intel Core
   elif expr "$processor" : ".*Intel P6 Family" > /dev/null ; then
       cpu="pentium4"
# P3
   elif expr "$processor" : "pentium3" > /dev/null ; then
       cpu="pentium3"
   elif expr "$processor" : ".*Pentium.* III" > /dev/null ; then
       cpu="pentium3"
   elif expr "$processor" : ".*Coppermine" > /dev/null ; then
       cpu="pentium3"
       enable small
   elif expr "$processor" : ".*Celeron(TM) CPU" > /dev/null ; then
       cpu="pentium3"
       enable small
   elif expr "$processor" : ".*Pentium(R) M" > /dev/null ; then
       cpu="pentium3"
   elif expr "$processor" : ".*Celeron(R) M processor" > /dev/null ; then
       cpu="pentium3"
       enable small
# P2
   elif expr "$processor" : "pentium2" > /dev/null ; then
       cpu="pentium2"
   elif expr "$processor" : ".*Mendocino" > /dev/null ; then
       cpu="pentium2"
       enable small
   elif expr "$processor" : ".*Klamath" > /dev/null ; then
       cpu="pentium2"
       enable small
   elif expr "$processor" : ".*Deschutes" > /dev/null ; then
       cpu="pentium2"
       enable small
   elif expr "$processor" : ".*Pentium II" > /dev/null ; then
       cpu="pentium2"
       enable small
# AMD Turion
   elif expr "$processor" : ".*AMD Turion(tm) 64" > /dev/null ; then
       cpu="k8"
# AMD Geode NX
   elif expr "$processor" : ".*AMD Geode(tm) NX" > /dev/null ; then
       cpu="athlon"
       enable small
# Athlon 64
   elif expr "$processor" : ".*AMD Athlon(tm) II" > /dev/null ; then
       cpu="k8"
   elif expr "$processor" : ".*AMD Athlon(tm) 64" > /dev/null ; then
       cpu="k8"
   elif expr "$processor" : ".*AMD Athlon(tm) Dual Core" > /dev/null ; then
       cpu="k8"
   elif expr "$processor" : ".*Athlon LE-16" > /dev/null ; then
       cpu="k8"
# AMD Phenom
   elif expr "$processor" : ".*AMD Phenom(tm)" > /dev/null ; then
       cpu="barcelona"
# AMD Opteron
   elif expr "$processor" : ".*AMD Opteron(tm)" >/dev/null ; then
       cpu="k8"
# Athlon MP
   elif expr "$processor" : ".*AMD Athlon(tm) MP.*" > /dev/null ; then
       cpu="athlon-mp"
# Athlon XP
   elif expr "$processor" : "athlon-xp" > /dev/null ; then
       cpu="athlon-xp"
   elif expr "$processor" : ".*AMD Athlon(tm) XP" > /dev/null ; then
       cpu="athlon-xp"
   elif expr "$processor" : ".*AMD Sempron(tm)" > /dev/null ; then
       cpu="athlon-xp"
# Athlon
   elif expr "$processor" : "athlon" > /dev/null ; then
       cpu="athlon"
   elif expr "$processor" : ".*AMD Athlon(..)" > /dev/null ; then
       cpu="athlon"
   elif expr "$processor" : ".*AMD Duron(..)" > /dev/null ; then
       cpu="athlon"
       enable small
# K6
   elif expr "$processor" : ".*AMD-K6(tm) 3D" > /dev/null ; then
       cpu="k6"
       enable small
# Transmeta Crusoe
   elif expr "$processor" : ".*Crusoe(m) Processor TM5600" > /dev/null ; then
       cpu="pentium2"
# c3-2
   elif expr "$processor" : ".*VIA Esther" > /dev/null ; then
       cpu="c3-2"
       enable small
   elif expr "$processor" : ".*VIA Nehemiah" > /dev/null ; then
       cpu="c3-2"
       enable small
# c3
   elif expr "$processor" : ".*VIA.*Ezra" > /dev/null ; then
       cpu="c3"
       enable small
   elif expr "$processor" : ".*VIA Samuel" > /dev/null ; then
       cpu="c3"
       enable small
# if no known processor info, tune base on uname -m info
   else
       enable proc_error_msg
   fi
fi

if enabled proc_error_msg; then
    UNAME_M_INFO=` uname -m 2> /dev/null`
    UNAME_P_INFO=` uname -p 2> /dev/null`
    PROC_INFO=`cat /proc/cpuinfo | grep "model name" | head -n 1 | sed s/"\t"//g 2>/dev/null`
    PROC_FLAG=`cat /proc/cpuinfo | grep "flags" | head -n 1 | sed s/"\t"//g 2>/dev/null`
    echo ""
    echo " *** WARNING *** "
    echo " Your CPU was not detected properly:"
    echo "   uname -m: $UNAME_M_INFO"
    echo "   uname -p: $UNAME_P_INFO"
    echo " $PROC_INFO"
    echo "      $PROC_FLAG"
    echo ""
    echo " If you are using a recent checkout from "
    echo "   https://github.com/MythTV/mythtv "
    echo " please e-mail the above to mythtv-dev@mythtv.org"
    echo " With the subject \"configure did not detect my cpu\""
    echo ""
fi

if test $target_os = "darwin"; then
     # Apple GCC doesn't support march=core2 yet:
    if test $cpu = "core2"; then
        cpu="nocona"
    fi
    # Core Duo might be identified as march=pentium3, which errors:
    # ...MachineExceptions.h:... error: '__m128i' does not name a type
    # ...MachineExceptions.h:... error: '__m128i' does not name a type
    if test $cpu = "pentium3"; then
        cpu=prescott
    fi
fi

# Add processor-specific flags
if enabled aarch64; then

    case $cpu in
        armv*)
            cpuflags="-march=$cpu"
        ;;
        *)
            cpuflags="-mcpu=$cpu"
        ;;
    esac

elif enabled alpha; then

    cpuflags="-mcpu=$cpu"

elif enabled arm; then

    check_arm_arch() {
        check_cpp_condition stddef.h \
            "defined __ARM_ARCH_${1}__ || defined __TARGET_ARCH_${2:-$1}" \
            $cpuflags
    }

    probe_arm_arch() {
        if   check_arm_arch 4;        then echo armv4
        elif check_arm_arch 4T;       then echo armv4t
        elif check_arm_arch 5;        then echo armv5
        elif check_arm_arch 5E;       then echo armv5e
        elif check_arm_arch 5T;       then echo armv5t
        elif check_arm_arch 5TE;      then echo armv5te
        elif check_arm_arch 5TEJ;     then echo armv5te
        elif check_arm_arch 6;        then echo armv6
        elif check_arm_arch 6J;       then echo armv6j
        elif check_arm_arch 6K;       then echo armv6k
        elif check_arm_arch 6Z;       then echo armv6z
        elif check_arm_arch 6ZK;      then echo armv6zk
        elif check_arm_arch 6T2;      then echo armv6t2
        elif check_arm_arch 7;        then echo armv7
        elif check_arm_arch 7A  7_A;  then echo armv7-a
        elif check_arm_arch 7S;       then echo armv7-a
        elif check_arm_arch 7R  7_R;  then echo armv7-r
        elif check_arm_arch 7M  7_M;  then echo armv7-m
        elif check_arm_arch 7EM 7E_M; then echo armv7-m
        elif check_arm_arch 8A  8_A;  then echo armv8-a
        fi
    }

    case $cpu in
        generic)
            subarch=$(probe_arm_arch | sed 's/[^a-z0-9]//g')
        ;;
        armv*)
            cpuflags="-march=$cpu"
            subarch=$(echo $cpu | sed 's/[^a-z0-9]//g')
        ;;
        *)
            cpuflags="-mcpu=$cpu"
            case $cpu in
                cortex-a*)                               subarch=armv7a  ;;
                cortex-r*)                               subarch=armv7r  ;;
                cortex-m*)                 enable thumb; subarch=armv7m  ;;
                arm11*)                                  subarch=armv6   ;;
                arm[79]*e*|arm9[24]6*|arm96*|arm102[26]) subarch=armv5te ;;
                armv4*|arm7*|arm9[24]*)                  subarch=armv4   ;;
                *)                             subarch=$(probe_arm_arch) ;;
            esac
        ;;
    esac

    case "$subarch" in
        armv5t*)    enable fast_clz                ;;
        armv[6-8]*)
            enable fast_clz
            disabled fast_unaligned || enable fast_unaligned
            ;;
    esac

elif enabled avr32; then

    case $cpu in
        ap7[02]0[0-2])
            subarch="avr32_ap"
            cpuflags="-mpart=$cpu"
        ;;
        ap)
            subarch="avr32_ap"
            cpuflags="-march=$cpu"
        ;;
        uc3[ab]*)
            subarch="avr32_uc"
            cpuflags="-mcpu=$cpu"
        ;;
        uc)
            subarch="avr32_uc"
            cpuflags="-march=$cpu"
        ;;
    esac

elif enabled bfin; then

    cpuflags="-mcpu=$cpu"

elif enabled mips; then

    cpuflags="-march=$cpu"

    if [ "$cpu" != "generic" ]; then
        disable mips32r2
        disable mips32r5
        disable mips64r2
        disable mips32r6
        disable mips64r6
        disable loongson2
        disable loongson3

        case $cpu in
            24kc|24kf*|24kec|34kc|1004kc|24kef*|34kf*|1004kf*|74kc|74kf)
                enable mips32r2
                disable msa
            ;;
            p5600|i6400|p6600)
                disable mipsdsp
                disable mipsdspr2
            ;;
            loongson*)
                enable loongson2
                enable loongson3
                enable local_aligned_8 local_aligned_16 local_aligned_32
                enable simd_align_16
                enable fast_64bit
                enable fast_clz
                enable fast_cmov
                enable fast_unaligned
                disable aligned_stack
                disable mipsfpu
                disable mipsdsp
                disable mipsdspr2
                case $cpu in
                    loongson3*)
                        cpuflags="-march=loongson3a -mhard-float -fno-expensive-optimizations"
                    ;;
                    loongson2e)
                        cpuflags="-march=loongson2e -mhard-float -fno-expensive-optimizations"
                    ;;
                    loongson2f)
                        cpuflags="-march=loongson2f -mhard-float -fno-expensive-optimizations"
                    ;;
                esac
            ;;
            *)
                # Unknown CPU. Disable everything.
                warn "unknown CPU. Disabling all MIPS optimizations."
                disable mipsfpu
                disable mipsdsp
                disable mipsdspr2
                disable msa
                disable mmi
            ;;
        esac

        case $cpu in
            24kc)
                disable mipsfpu
                disable mipsdsp
                disable mipsdspr2
            ;;
            24kf*)
                disable mipsdsp
                disable mipsdspr2
            ;;
            24kec|34kc|1004kc)
                disable mipsfpu
                disable mipsdspr2
            ;;
            24kef*|34kf*|1004kf*)
                disable mipsdspr2
            ;;
            74kc)
                disable mipsfpu
            ;;
            p5600)
                enable mips32r5
                check_cflags "-mtune=p5600" && check_cflags "-msched-weight -mload-store-pairs -funroll-loops"
            ;;
            i6400)
                enable mips64r6
                check_cflags "-mtune=i6400 -mabi=64" && check_cflags "-msched-weight -mload-store-pairs -funroll-loops" && check_ldflags "-mabi=64"
            ;;
            p6600)
                enable mips64r6
                check_cflags "-mtune=p6600 -mabi=64" && check_cflags "-msched-weight -mload-store-pairs -funroll-loops" && check_ldflags "-mabi=64"
            ;;
        esac
    else
        # We do not disable anything. Is up to the user to disable the unwanted features.
        warn 'generic cpu selected'
    fi

elif enabled ppc; then

    disable ldbrx

    case $(tolower $cpu) in
        601|ppc601|powerpc601)
            cpuflags="-mcpu=601"
            disable altivec
        ;;
        603*|ppc603*|powerpc603*)
            cpuflags="-mcpu=603"
            disable altivec
        ;;
        604*|ppc604*|powerpc604*)
            cpuflags="-mcpu=604"
            disable altivec
        ;;
        g3|75*|ppc75*|powerpc75*)
            cpuflags="-mcpu=750"
            disable altivec
        ;;
        g4|745*|ppc745*|powerpc745*)
            cpuflags="-mcpu=7450"
            disable vsx
        ;;
        74*|ppc74*|powerpc74*)
            cpuflags="-mcpu=7400"
            disable vsx
        ;;
        g5|970|ppc970|powerpc970)
            cpuflags="-mcpu=970"
            disable vsx
        ;;
        power[3-6]*)
            cpuflags="-mcpu=$cpu"
            disable vsx
        ;;
        power[7-8]*)
            cpuflags="-mcpu=$cpu"
        ;;
        cell)
            cpuflags="-mcpu=cell"
            enable ldbrx
            disable vsx
        ;;
        e500mc)
            cpuflags="-mcpu=e500mc"
            disable altivec
        ;;
        e500v2)
            cpuflags="-mcpu=8548 -mhard-float -mfloat-gprs=double"
            disable altivec
            disable dcbzl
        ;;
        e500)
            cpuflags="-mcpu=8540 -mhard-float"
            disable altivec
            disable dcbzl
        ;;
    esac

elif enabled sparc; then

    case $cpu in
        cypress|f93[04]|tsc701|sparcl*|supersparc|hypersparc|niagara|v[789])
            cpuflags="-mcpu=$cpu"
        ;;
        ultrasparc*|niagara[234])
            cpuflags="-mcpu=$cpu"
        ;;
    esac

elif enabled x86; then

    case $cpu in
        i[345]86|pentium)
            cpuflags="-march=$cpu"
            disable i686
            disable mmx
        ;;
        # targets that do NOT support nopl and conditional mov (cmov)
        pentium-mmx|k6|k6-[23]|winchip-c6|winchip2|c3)
            cpuflags="-march=$cpu"
            disable i686
        ;;
        # targets that do support nopl and conditional mov (cmov)
        i686|pentiumpro|pentium[23]|pentium-m|athlon|athlon-tbird|athlon-4|athlon-[mx]p|athlon64*|k8*|opteron*|athlon-fx\
        |core*|atom|bonnell|nehalem|westmere|silvermont|sandybridge|ivybridge|haswell|broadwell|skylake*|knl\
        |amdfam10|barcelona|b[dt]ver*|znver*)
            cpuflags="-march=$cpu"
            enable i686
            enable fast_cmov
        ;;
        # targets that do support conditional mov but on which it's slow
        pentium4|pentium4m|prescott|nocona)
            cpuflags="-march=$cpu"
            enable i686
            disable fast_cmov
        ;;
    esac

fi


# if architecture specific flags don't work blank them
if test -n "$cpuflags"; then
    tmp_cpuflags="$cpuflags"
    check_cc $cpuflags <<EOF || cpuflags=""
int main( void ) { return 0; }
EOF
    if test -z "$cpuflags"; then
        if enabled cpu_override || enabled proc_opt || test x"$tune" != x"generic"; then
            echo "ERROR: CPU specific ./configure options failed compile test"
            echo "       Removing CPU specific compilation options. ($tmp_cpuflags)"
            echo ""
        fi
    fi
fi

if [ "$cpu" != generic ]; then
    add_cflags  $cpuflags
    add_asflags $cpuflags
    add_cxxflags $cpuflags
    test "$cc_type" = "$ld_type" && add_ldflags $cpuflags
fi

# compiler sanity check
check_exec <<EOF
int main(void){ return 0; }
EOF
if test "$?" != 0; then
    echo "$cc is unable to create an executable file."
    echo "Check your ECFLAGS: [$ECFLAGS]"
    if test -z "$cross_prefix" && ! enabled cross_compile ; then
        echo "If $cc is a cross-compiler, use the --enable-cross-compile option."
        echo "Only do this if you know what cross compiling means."
    fi
    die "C compiler test failed."
fi

check_cxxflags -std=$CPP_STANDARD -faligned-new

# some compilers silently accept -std=c11, so we also need to check that the
# version macro is defined properly
test_cflags_cc -std=c11 ctype.h "__STDC_VERSION__ >= 201112L" &&
    add_cflags -std=c11 ||
    check_cflags -std=c99

# C++ compiler sanity check
check_exec_cxx <<EOF
int main(void){ return 0; }
EOF
if test "$?" != 0; then
    echo "$cxx is unable to create an executable file."
    echo "Check your ECXXFLAGS: [$ECXXFLAGS]"
    if test -z "$cross_prefix" && ! enabled cross_compile ; then
        echo "If $cxx is a cross-compiler, use the --enable-cross-compile option."
        echo "Only do this if you know what cross compiling means."
    fi
    die "C++ compiler test failed."
fi


check_cppflags -D_FILE_OFFSET_BITS=64
check_cxx -D_FILE_OFFSET_BITS=64 <<EOF && add_cxxppflags -D_FILE_OFFSET_BITS=64
#include <stdlib.h>
EOF

check_host_cflags -Wall
check_host_cflags $host_cflags_speed

check_64bit(){
    arch32=$1
    arch64=$2
    expr=$3
    check_code cc "" "int test[2*($expr) - 1]" &&
        subarch=$arch64 || subarch=$arch32
}

case "$arch" in
    aarch64|alpha|ia64)
        spic=$shared
    ;;
    mips)
        check_64bit mips mips64 '_MIPS_SIM > 1'
        spic=$shared
    ;;
    parisc)
        check_64bit parisc parisc64 'sizeof(void *) > 4'
        spic=$shared
    ;;
    ppc)
        check_64bit ppc ppc64 'sizeof(void *) > 4'
        spic=$shared
    ;;
    s390)
        check_64bit s390 s390x 'sizeof(void *) > 4'
        spic=$shared
    ;;
    sparc)
        check_64bit sparc sparc64 'sizeof(void *) > 4'
        spic=$shared
    ;;
    x86)
        check_64bit x86_32 x86_64 'sizeof(void *) > 4'
        # Treat x32 as x64 for now. Note it also needs spic=$shared
        test "$subarch" = "x86_32" && check_cpp_condition stddef.h 'defined(__x86_64__)' &&
            subarch=x86_64
        if test "$subarch" = "x86_64"; then
            spic=$shared
        fi
    ;;
    ppc)
        check_cc <<EOF && subarch="ppc64"
        int test[(int)sizeof(char*) - 7];
EOF
    ;;
esac

enable $subarch
enabled spic && enable_weak pic

enabled x86_64 && objformat=elf64 || objformat="elf32"

# OS specific
case $target_os in
    aix)
        SHFLAGS=-shared
        add_cppflags '-I\$(SRC_PATH)/compat/aix'
        enabled shared && add_ldflags -Wl,-brtl
        ;;
    android)
        disable symver
        enable section_data_rel_ro
        disable qtdbus
        SLIB_INSTALL_NAME='$(SLIBNAME)'
        SLIB_INSTALL_LINKS=
        # soname not set on purpose
        SHFLAGS=-shared
        enable pic
        ;;
    haiku)
        prefix_default="/boot/common"
        network_extralibs="-lnetwork"
        host_extralibs=
        ;;
    sunos)
        SHFLAGS='-shared -Wl,-h,$$(@F)'
        enabled x86 && SHFLAGS="-mimpure-text $SHFLAGS"
        network_extralibs="-lsocket -lnsl"
        add_cppflags -D__EXTENSIONS__
        # When using suncc to build, the Solaris linker will mark
        # an executable with each instruction set encountered by
        # the Solaris assembler.  As our libraries contain their own
        # guards for processor-specific code, instead suppress
        # generation of the HWCAPS ELF section on Solaris x86 only.
        enabled_all suncc x86 &&
            echo "hwcap_1 = OVERRIDE;" > mapfile &&
            add_ldflags -Wl,-M,mapfile
        add_cxxppflags -D__EXTENSIONS__
        nm_default='nm -P -g'
        version_script='-M'
        VERSION_SCRIPT_POSTPROCESS_CMD='perl $(SRC_PATH)/compat/solaris/make_sunver.pl - $(OBJS)'
        ;;
    netbsd)
        disable symver
        oss_indev_extralibs="-lossaudio"
        oss_outdev_extralibs="-lossaudio"
        enabled gcc || check_ldflags -Wl,-zmuldefs
        ;;
    openbsd|bitrig)
        disable symver
        SHFLAGS='-shared'
        SLIB_INSTALL_NAME='$(SLIBNAME).$(LIBMAJOR).$(LIBMINOR)'
        SLIB_INSTALL_LINKS=
        oss_indev_extralibs="-lossaudio"
        oss_outdev_extralibs="-lossaudio"
        ;;
    dragonfly)
        disable symver
        ;;
    freebsd)
        append CCONFIG "freebsd"
        # Workaround compile errors from missing u_int/uint def
        CPPFLAGS=`echo $CPPFLAGS | sed 's/-D_POSIX_C_SOURCE=200112//'`
        # disable ivtv
        enable backend
        enable pic
        enable drm
        ;;
    bsd/os)
        add_extralibs -lpoll -lgnugetopt
        ;;
    darwin)
        enable  appleremote
        enable  backend
        enable  darwin
        enable  videotoolbox
        disable dvb
        disable v4l2
        disable v4l2prime
        disable x11
        # Workaround compile errors from missing u_int/uint def
        CFLAGS=`echo $CFLAGS | sed 's/-D_POSIX_C_SOURCE=200112//'`
        CPPFLAGS=`echo $CPPFLAGS | sed 's/-D_POSIX_C_SOURCE=200112//'`
        # Workaround compile errors from missing ru_maxrss
        add_cppflags -D_DARWIN_C_SOURCE

        ###### Standard ffmpeg configure stuff follows:
        enabled ppc && add_asflags -force_cpusubtype_ALL
        install_name_dir_default='$(SHLIBDIR)'

        #Need to add @rpath in front of install name so test unit can use non-installed lib
        SHFLAGS='-headerpad_max_install_names -dynamiclib -Wl,-single_module -Wl,-install_name,@rpath/$(SLIBNAME),-current_version,$(LIBVERSION),-compatibility_version,$(LIBMAJOR)'
        enabled x86_32 && append SHFLAGS -Wl,-read_only_relocs,suppress
        add_ldflags -Wl,-dynamic,-search_paths_first
        SLIBSUF=".dylib"
        SLIBNAME_WITH_VERSION='$(SLIBPREF)$(FULLNAME).$(LIBVERSION)$(SLIBSUF)'
        SLIBNAME_WITH_MAJOR='$(SLIBPREF)$(FULLNAME).$(LIBMAJOR)$(SLIBSUF)'
        objformat="macho"
        enabled x86_64 && objformat="macho64" || objformat="macho32"
        enabled_any pic shared x86_64 ||
            { check_cflags -mdynamic-no-pic && add_asflags -mdynamic-no-pic; }
        version_script='-exported_symbols_list'
        VERSION_SCRIPT_POSTPROCESS_CMD='tr " " "\n" | sed -n /global:/,/local:/p | grep ";" | tr ";" "\n" | sed -E "s/(.+)/_\1/g" | sed -E "s/(.+[^*])$$$$/\1*/"'
        ;;
    msys*)
        die "Native MSYS builds are discouraged, please use the MINGW environment."
        ;;
    mingw32*|mingw64*)
        enable  backend
        disable bindings_perl
        disable bindings_python
        disable bindings_php
        disable dv1394
        disable dvb
        disable ceton
        disable mythtranscode
        disable network
        enable opengl
        if enabled wince; then
            disable protocols
        fi
        disable symver
        disable v4l2
        disable v4l2prime
        enable  windows
        disable x11
        disable qtdbus
        ###### Standard ffmpeg configure stuff follows:
        if test $target_os = "mingw32ce"; then
            disable network
        else
            target_os=mingw32
        fi
        LIBTARGET=i386
        if enabled x86_64; then
            LIBTARGET="i386:x86-64"
        elif enabled arm; then
            LIBTARGET=arm-wince
        fi
        enabled shared && ! enabled small && check_cmd $windres --version && enable gnu_windres
        enabled x86_32 && check_ldflags -Wl,--large-address-aware
        shlibdir_default="$bindir_default"
        SLIBPREF="libmyth"
        SLIBSUF=".dll"
        SLIBNAME_WITH_VERSION='$(SLIBPREF)$(NAME)-$(LIBVERSION)$(SLIBSUF)'
        SLIBNAME_WITH_MAJOR='$(SLIBPREF)$(NAME)-$(LIBMAJOR)$(SLIBSUF)'
        dlltool="${cross_prefix}dlltool"
        if check_cmd lib.exe -list ; then
            SLIB_EXTRA_CMD=-'sed -e "s/ @[^ ]*//" $$(@:$(SLIBSUF)=.orig.def) > $$(@:$(SLIBSUF)=.def); lib.exe -nologo -machine:$(LIBTARGET) -def:$$(@:$(SLIBSUF)=.def) -out:$(SUBDIR)$(SLIBNAME:$(SLIBSUF)=.lib)'
        else
            SLIB_EXTRA_CMD=-'sed -e "s/ @[^ ]*//" $$(@:$(SLIBSUF)=.orig.def) > $$(@:$(SLIBSUF)=.def); $(DLLTOOL) -m $(LIBTARGET) -d $$(@:$(SLIBSUF)=.def) -l $(SUBDIR)$(SLIBNAME:$(SLIBSUF)=.lib) -D $(SLIBNAME_WITH_MAJOR)'
        fi
        SLIB_INSTALL_EXTRA_CMD='-install -m 644 $(SUBDIR)$(SLIBNAME_WITH_MAJOR:$(SLIBSUF)=.lib) "$(SHLIBDIR)/$(SLIBNAME:$(SLIBSUF)=.lib)"; \
            install -m 644 $(SUBDIR)$(SLIBNAME_WITH_MAJOR:$(SLIBSUF)=.lib) "$(SHLIBDIR)/$(SLIBNAME_WITH_MAJOR:$(SLIBSUF)=.lib)"; \
            install -d "$(LIBDIR)"; \
            install -m 644 $(SUBDIR)lib$(SLIBNAME:$(SLIBSUF)=.dll.a) "$(LIBDIR)/lib$(SLIBNAME:$(SLIBSUF)=.dll.a)"'
        SLIB_UNINSTALL_EXTRA_CMD='rm -f "$(SHLIBDIR)/$(SLIBNAME:$(SLIBSUF)=.lib)"'
        SHFLAGS='-shared -Wl,--output-def,$$(@:$(SLIBSUF)=.orig.def) -Wl,--out-implib,$(SUBDIR)lib$(SLIBNAME:$(SLIBSUF)=.dll.a) -Wl,--enable-runtime-pseudo-reloc -Wl,--enable-auto-image-base'
        ranlib=:
        enable dos_paths
        check_ldflags -Wl,--nxcompat,--dynamicbase
        # Lets work around some stupidity in binutils.
        # ld will strip relocations from executables even though we need them
        # for dynamicbase (ASLR).  Using -pie does retain the reloc section
        # however ld then forgets what the entry point should be (oops) so we
        # have to manually (re)set it.
        if enabled x86_32; then
            disabled debug && add_ldexeflags -Wl,--pic-executable,-e,_mainCRTStartup
        elif enabled x86_64; then
            disabled debug && add_ldexeflags -Wl,--pic-executable,-e,mainCRTStartup
            check_ldflags -Wl,--high-entropy-va # binutils 2.25
            # Set image base >4GB for extra entropy with HEASLR
            add_ldexeflags -Wl,--image-base,0x140000000
            append SHFLAGS -Wl,--image-base,0x180000000
        fi
        add_extralibs -lws2_32
        # Workaround compile errors due -std=c++98 incompatible system headers
        ECXXFLAGS=`echo $ECXXFLAGS | sed 's/-std=c++98//'`
        ;;
    win32|win64)
        disable symver
        if enabled shared; then
            # Link to the import library instead of the normal static library
            # for shared libs.
            LD_LIB='%.lib'
            # Cannot build both shared and static libs with MSVC or icl.
            disable static
        fi
        enabled x86_32 && check_ldflags -LARGEADDRESSAWARE
        shlibdir_default="$bindir_default"
        SLIBPREF="libmyth"
        SLIBSUF=".dll"
        SLIBNAME_WITH_VERSION='$(SLIBPREF)$(FULLNAME)-$(LIBVERSION)$(SLIBSUF)'
        SLIBNAME_WITH_MAJOR='$(SLIBPREF)$(FULLNAME)-$(LIBMAJOR)$(SLIBSUF)'
        SLIB_CREATE_DEF_CMD='$(SRC_PATH)/compat/windows/makedef $(SUBDIR)lib$(NAME).ver $(OBJS) > $$(@:$(SLIBSUF)=.def)'
        SLIB_INSTALL_NAME='$(SLIBNAME_WITH_MAJOR)'
        SLIB_INSTALL_LINKS=
        SLIB_INSTALL_EXTRA_SHLIB='$(SLIBNAME:$(SLIBSUF)=.lib)'
        SLIB_INSTALL_EXTRA_LIB='$(SLIBNAME_WITH_MAJOR:$(SLIBSUF)=.def)'
        SHFLAGS='-dll -def:$$(@:$(SLIBSUF)=.def) -implib:$(SUBDIR)$(SLIBNAME:$(SLIBSUF)=.lib)'
        enabled x86_64 && objformat="win64" || objformat="win32"
        ranlib=:
        enable dos_paths
        ;;
    cygwin*)
        enable cygwin
        enable windows
        target_os=cygwin
        shlibdir_default="$bindir_default"
        SLIBPREF="cygmyth"
        SLIBSUF=".dll"
        SLIBNAME_WITH_VERSION='$(SLIBPREF)$(FULLNAME)-$(LIBVERSION)$(SLIBSUF)'
        SLIBNAME_WITH_MAJOR='$(SLIBPREF)$(FULLNAME)-$(LIBMAJOR)$(SLIBSUF)'
        SLIB_INSTALL_NAME='$(SLIBNAME_WITH_MAJOR)'
        SLIB_INSTALL_LINKS=
        SLIB_INSTALL_EXTRA_LIB='lib$(FULLNAME).dll.a'
        SHFLAGS='-shared -Wl,--out-implib,$(SUBDIR)lib$(FULLNAME).dll.a'
        enabled x86_64 && objformat="win64" || objformat="win32"
        enable dos_paths
        enabled shared && ! enabled small && check_cmd $windres --version && enable gnu_windres
        ;;
    *-dos|freedos|opendos)
        network_extralibs="-lsocket"
        objformat="coff"
        enable dos_paths
        add_cppflags -U__STRICT_ANSI__
        ;;
    linux)
        enable section_data_rel_ro
        enabled_any arm aarch64 && enable_weak linux_perf
        append CCONFIG "linux"
        enable backend
        ! disabled joystick_menu && enable joystick_menu
        enable libudev
        enable pic
        enable drm
        enable qtprivateheaders
	if [ x`uname -m` = x"armv7l" ]; then
	    disable vaapi
	fi
        ;;
    irix*)
        target_os=irix
        ranlib="echo ignoring ranlib"
        ;;
    os/2*)
        objformat="aout"
        add_ldflags -Zomf -Zbin-files -Zargs-wild -Zhigh-mem -Zmap
        SHFLAGS='$(SUBDIR)$(NAME).def -Zdll -Zomf'
        LIBSUF="_s.a"
        SLIBPREF="myth"
        SLIBSUF=".dll"
        SLIBNAME_WITH_VERSION='$(SLIBPREF)$(FULLNAME)-$(LIBVERSION)$(SLIBSUF)'
        SLIBNAME_WITH_MAJOR='$(SLIBPREF)$(shell echo $(FULLNAME) | cut -c1-6)$(LIBMAJOR)$(SLIBSUF)'
        SLIB_CREATE_DEF_CMD='echo LIBRARY $(SLIBNAME_WITH_MAJOR:$(SLIBSUF)=) INITINSTANCE TERMINSTANCE > $(SUBDIR)$(FULLNAME).def; \
            echo CODE PRELOAD MOVEABLE DISCARDABLE >> $(SUBDIR)$(FULLNAME).def; \
            echo DATA PRELOAD MOVEABLE MULTIPLE NONSHARED >> $(SUBDIR)$(FULLNAME).def; \
            echo EXPORTS >> $(SUBDIR)$(FULLNAME).def; \
            emxexp $(OBJS) >> $(SUBDIR)$(FULLNAME).def'
        SLIB_EXTRA_CMD='emximp -o $(SUBDIR)$(LIBPREF)$(FULLNAME)_dll.a $(SUBDIR)$(FULLNAME).def; \
            emximp -o $(SUBDIR)$(LIBPREF)$(FULLNAME)_dll.lib $(SUBDIR)$(FULLNAME).def;'
        SLIB_INSTALL_NAME='$(SLIBNAME_WITH_MAJOR)'
        SLIB_INSTALL_LINKS=
        SLIB_INSTALL_EXTRA_LIB='$(LIBPREF)$(FULLNAME)_dll.a $(LIBPREF)$(FULLNAME)_dll.lib'
        enable dos_paths
        enable_weak os2threads
        ;;
    gnu/kfreebsd)
        add_cppflags -D_BSD_SOURCE
        ;;
    gnu)
        ;;
    qnx)
        add_cppflags -D_QNX_SOURCE
        network_extralibs="-lsocket"
        ;;
    symbian)
        SLIBSUF=".dll"
        enable dos_paths
        add_cflags --include=$sysinclude/gcce/gcce.h -fvisibility=default
        add_cppflags -D__GCCE__ -D__SYMBIAN32__ -DSYMBIAN_OE_POSIX_SIGNALS
        add_ldflags -Wl,--target1-abs,--no-undefined \
                    -Wl,-Ttext,0x80000,-Tdata,0x1000000 -shared \
                    -Wl,--entry=_E32Startup -Wl,-u,_E32Startup
        add_extralibs -l:eexe.lib -l:usrt2_2.lib -l:dfpaeabi.dso \
                      -l:drtaeabi.dso -l:scppnwdl.dso -lsupc++ -lgcc \
                      -l:libc.dso -l:libm.dso -l:euser.dso -l:libcrt0.lib
        ;;
    osf1)
        add_cppflags -D_OSF_SOURCE -D_POSIX_PII -D_REENTRANT
        ;;
    minix)
        ;;
    none)
        ;;
    *)
        die "Unknown OS '$target_os'."
        ;;
esac

# test if creating links works
link_dest=$(mktemp -u $TMPDIR/dest_XXXXXXXX)
link_name=$(mktemp -u $TMPDIR/name_XXXXXXXX)
mkdir "$link_dest"
$ln_s "$link_dest" "$link_name"
touch "$link_dest/test_file"
if [ "$source_path" != "." ] && ([ ! -d src ] || [ -L src ]) && [ -e "$link_name/test_file" ]; then
    # create link to source path
    [ -e src ] && rm src
    $ln_s "$source_path" src
    source_link=src
else
    # creating directory links doesn't work
    # fall back to using the full source path
    source_link="$source_path"
fi
# cleanup
rm -r "$link_dest"
rm -r "$link_name"

# determine libc flavour

probe_libc(){
    pfx=$1
    pfx_no_=${pfx%_}
    # uclibc defines __GLIBC__, so it needs to be checked before glibc.
    if check_${pfx}cpp_condition features.h "defined __UCLIBC__"; then
        eval ${pfx}libc_type=uclibc
        add_${pfx}cppflags -D_POSIX_C_SOURCE=200112 -D_XOPEN_SOURCE=600
    elif check_${pfx}cpp_condition features.h "defined __GLIBC__"; then
        eval ${pfx}libc_type=glibc
        add_${pfx}cppflags -D_POSIX_C_SOURCE=200112 -D_XOPEN_SOURCE=600
    # MinGW headers can be installed on Cygwin, so check for newlib first.
    elif check_${pfx}cpp_condition newlib.h "defined _NEWLIB_VERSION"; then
        eval ${pfx}libc_type=newlib
        add_${pfx}cppflags -U__STRICT_ANSI__ -D_XOPEN_SOURCE=600
    # MinGW64 is backwards compatible with MinGW32, so check for it first.
    elif check_${pfx}cpp_condition _mingw.h "defined __MINGW64_VERSION_MAJOR"; then
        eval ${pfx}libc_type=mingw64
        if check_${pfx}cpp_condition _mingw.h "__MINGW64_VERSION_MAJOR < 3"; then
            add_compat msvcrt/snprintf.o
            add_cflags "-include $source_path/compat/msvcrt/snprintf.h"
        fi
        add_${pfx}cppflags -U__STRICT_ANSI__ -D__USE_MINGW_ANSI_STDIO=1
        eval test \$${pfx_no_}cc_type = "gcc" &&
            add_${pfx}cppflags -D__printf__=__gnu_printf__
    elif check_${pfx}cpp_condition _mingw.h "defined __MINGW_VERSION"  ||
         check_${pfx}cpp_condition _mingw.h "defined __MINGW32_VERSION"; then
        eval ${pfx}libc_type=mingw32
        check_${pfx}cpp_condition _mingw.h "__MINGW32_MAJOR_VERSION > 3 || \
            (__MINGW32_MAJOR_VERSION == 3 && __MINGW32_MINOR_VERSION >= 15)" ||
            die "ERROR: MinGW32 runtime version must be >= 3.15."
        add_${pfx}cppflags -U__STRICT_ANSI__ -D__USE_MINGW_ANSI_STDIO=1
        check_${pfx}cpp_condition _mingw.h "defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x0502" ||
            add_${pfx}cppflags -D_WIN32_WINNT=0x0502
        check_${pfx}cpp_condition _mingw.h "__MSVCRT_VERSION__ < 0x0700" &&
            add_${pfx}cppflags -D__MSVCRT_VERSION__=0x0700
        eval test \$${pfx_no_}cc_type = "gcc" &&
            add_${pfx}cppflags -D__printf__=__gnu_printf__
    elif check_${pfx}cpp_condition crtversion.h "defined _VC_CRT_MAJOR_VERSION"; then
        eval ${pfx}libc_type=msvcrt
        if check_${pfx}cpp_condition crtversion.h "_VC_CRT_MAJOR_VERSION < 14"; then
            if [ "$pfx" = host_ ]; then
                add_host_cppflags -Dsnprintf=_snprintf
            else
                add_compat strtod.o strtod=avpriv_strtod
                add_compat msvcrt/snprintf.o snprintf=avpriv_snprintf   \
                                             _snprintf=avpriv_snprintf  \
                                             vsnprintf=avpriv_vsnprintf
            fi
        fi
        add_${pfx}cppflags -D_USE_MATH_DEFINES -D_CRT_SECURE_NO_WARNINGS -D_CRT_NONSTDC_NO_WARNINGS
        # The MSVC 2010 headers (Win 7.0 SDK) set _WIN32_WINNT to
        # 0x601 by default unless something else is set by the user.
        # This can easily lead to us detecting functions only present
        # in such new versions and producing binaries requiring windows 7.0.
        # Therefore explicitly set the default to XP unless the user has
        # set something else on the command line.
        # Don't do this if WINAPI_FAMILY is set and is set to a non-desktop
        # family. For these cases, configure is free to use any functions
        # found in the SDK headers by default. (Alternatively, we could force
        # _WIN32_WINNT to 0x0602 in that case.)
        check_${pfx}cpp_condition stdlib.h "defined(_WIN32_WINNT)" ||
            { check_${pfx}cpp <<EOF && add_${pfx}cppflags -D_WIN32_WINNT=0x0502; }
#ifdef WINAPI_FAMILY
#include <winapifamily.h>
#if !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
#error not desktop
#endif
#endif
EOF
        if [ "$pfx" = "" ]; then
            check_func strtoll || add_cflags -Dstrtoll=_strtoi64
            check_func strtoull || add_cflags -Dstrtoull=_strtoui64
        fi
    elif check_${pfx}cpp_condition stddef.h "defined __KLIBC__"; then
        eval ${pfx}libc_type=klibc
    elif check_${pfx}cpp_condition sys/cdefs.h "defined __BIONIC__"; then
        eval ${pfx}libc_type=bionic
    elif check_${pfx}cpp_condition sys/brand.h "defined LABELED_BRAND_NAME"; then
        eval ${pfx}libc_type=solaris
        add_${pfx}cppflags -D__EXTENSIONS__
    fi
    check_${pfx}cc <<EOF
#include <time.h>
void *v = localtime_r;
EOF
test "$?" != 0 && check_${pfx}cc -D_POSIX_C_SOURCE=200112 -D_XOPEN_SOURCE=600 <<EOF && add_${pfx}cppflags -D_POSIX_C_SOURCE=200112 -D_XOPEN_SOURCE=600
#include <time.h>
void *v = localtime_r;
EOF

}

probe_libc
test -n "$libc_type" && enable libc_$libc_type
probe_libc host_
test -n "$host_libc_type" && enable host_libc_$host_libc_type

# hacks for compiler/libc/os combinations

case $libc_type in
    bionic)
        if test $target_os != android ; then
            add_compat strtod.o strtod=avpriv_strtod
        fi
        ;;
    glibc)
        if enabled tms470; then
            CPPFLAGS="-I${source_path}/compat/tms470 ${CPPFLAGS}"
            add_cppflags -D__USER_LABEL_PREFIX__=
            add_cppflags -D__builtin_memset=memset
            add_cppflags -D__gnuc_va_list=va_list -D_VA_LIST_DEFINED
            add_cflags   -pds=48    # incompatible redefinition of macro
        elif enabled ccc; then
            add_ldflags -Wl,-z,now  # calls to libots crash without this
        fi
        ;;
esac

esc(){
    echo "$*" | sed 's/%/%25/g;s/:/%3a/g'
}

echo "config:$arch:$subarch:$cpu:$target_os:$(esc $cc_ident):$(esc $MYTHTV_CONFIGURATION)" > config.fate

check_cpp_condition stdlib.h "defined(__PIC__) || defined(__pic__) || defined(PIC)" && enable_weak pic

set_default libdir
: ${shlibdir_default:="$libdir"}
: ${pkgconfigdir_default:="$libdir/pkgconfig"}

set_default $PATHS_LIST
set_default nm

set_default $MYTHTV_PATHS_LIST
if test $target_os = android ; then
    append CONFIG_INCLUDEPATH $sysinclude "${sysroot}${prefix}"
fi

enable debug
append CCONFIG "$compile_type"
if test x$compile_type = x"release" ; then
    add_cflags   -DNDEBUG
    add_cxxflags -DNDEBUG
    check_cxxflags -O2
elif test x$compile_type = x"profile" ; then
    add_cflags   -DNDEBUG
    add_cxxflags -DNDEBUG
    check_cxxflags -O2
elif test x$compile_type = x"debug"; then
    disable optimizations
fi

if [ -z "$optflags" ]; then
    if enabled small; then
        optflags=$cflags_size
    elif enabled optimizations; then
        optflags=$cflags_speed
    else
        optflags=$cflags_noopt
    fi
fi

check_optflags(){
    check_cflags "$@"
    enabled lto && check_ldflags "$@"
}

check_optflags $optflags
check_optflags -fno-math-errno
check_optflags -fno-signed-zeros

if enabled lto; then
    test "$cc_type" != "$ld_type" && die "LTO requires same compiler and linker"
    check_cflags  -flto
    check_cxxflags -flto
    check_ldflags -flto $cpuflags
    disable inline_asm_direct_symbol_refs
fi


enabled silent_cc && append CCONFIG "silent"

disabled optimizations || enabled ossfuzz || check_cflags -fomit-frame-pointer
# backward compatibility layer for incompatible_libav/fork_abi
enabled incompatible_fork_abi  && enable incompatible_libav_abi
enabled incompatible_libav_abi && enable incompatible_fork_abi

disabled static && LIBNAME=""

disabled optimizations || check_cxxflags -fomit-frame-pointer

enable_weak_pic() {
    disabled pic && return
    enable pic
    add_cppflags -DPIC
    add_cxxppflags -DPIC
    case "$target_os" in
    mingw*|cygwin*)
        ;;
    *)
        add_cflags -fPIC
        add_cxxflags -fPIC
        ;;
    esac
    add_asflags  -fPIC
}

enabled pic && enable_weak_pic

version2num10(){
    # accepts version as in 3.12.4 and turns it into 3012004 which can be compared as a number
    echo $1 | awk -F. '{ print ( ( $1 * 1000 ) + $2 ) * 1000 + $3; };'
}

version2num(){
    # accepts version as in 1.10.4 and turns it into 0x010A04 which can be compared as a number
    echo $1 | awk -F. '{ print ( ( $1 * 256 ) + $2 ) * 256 + $3; };'
}

# Minimum supported Qt version
QT5_MIN_VERSION_STR="5.15.2"
QT6_MIN_VERSION_STR="6.4"

# qmake-qt5 /usr/lib64/qt5/bin/qmake /usr/lib/x86_64-linux-gnu/qt5/bin/qmake
if [ x"$qmake" = "xqmake" ]; then
    CHECK_QMAKE=`which qmake-qt5 2>/dev/null`" /usr/lib64/qt5/bin/qmake /usr/lib/x86_64-linux-gnu/qt5/bin/qmake /usr/lib/i386-linux-gnu/qt5/bin/qmake /usr/lib/arm-linux-gnueabihf/qt5/bin/qmake /usr/local/lib/qt5/bin/qmake `which $qmake 2>/dev/null`"
else
    CHECK_QMAKE=`which $qmake 2>/dev/null`" "`which qmake-qt5 2>/dev/null`" /usr/lib64/qt5/bin/qmake /usr/lib/x86_64-linux-gnu/qt5/bin/qmake /usr/lib/i386-linux-gnu/qt5/bin/qmake /usr/lib/arm-linux-gnueabihf/qt5/bin/qmake /usr/local/lib/qt5/bin/qmake"
fi
# try to find a qt5 qmake to use
found_qmake=''
for i in $CHECK_QMAKE; do
    if test -e $i ; then
        qt_version_str=`$i -query QT_VERSION`
        qt_version=$(version2num $qt_version_str)
        qt_version_hex=$(printf "0x%06x" $qt_version)
        case $qt_version_str in
            6*) QT_MIN_VERSION_STR=$QT6_MIN_VERSION_STR ;;
            *)  QT_MIN_VERSION_STR=$QT5_MIN_VERSION_STR ;;
        esac
        QT_MIN_VERSION=$(version2num $QT_MIN_VERSION_STR)
        QT_MIN_VERSION_HEX=$(printf "0x%06x" $QT_MIN_VERSION)
        if [ $qt_version -ge $QT_MIN_VERSION ]; then
            found_qmake=$i
            check_cxxflags -DQT_DISABLE_DEPRECATED_BEFORE=$QT_MIN_VERSION_HEX
#            check_cxxflags -DQT_DISABLE_DEPRECATED_BEFORE=$qt_version_hex
            break;
        else
            echo "found qmake at $i but version failed"
            echo "got version: $qt_version_str"
        fi
    fi
done
if [ x"$found_qmake" = "x" ]; then
    die "qmake for Qt $QT5_MIN_VERSION_STR or newer not found.  Please specify the correct qmake with --qmake="
else
    qmake=$found_qmake
fi

if test x"$qmakespecs" != x; then
    qmakeconf="$qmake -spec $qmakespecs"
else
    qmakeconf="$qmake"
fi

check_cc <<EOF || die "Symbol mangling check failed."
int ff_extern;
EOF
sym=$($nm $TMPO | awk '/ff_extern/{ print substr($0, match($0, /[^ \t]*ff_extern/)) }')
extern_prefix=${sym%%ff_extern*}

check_inline_asm inline_asm '"" ::'

_restrict=
for restrict_keyword in restrict __restrict__ __restrict; do
    check_cxx <<EOF && _restrict=$restrict_keyword && break
void foo(char * $restrict_keyword p);
EOF
done

check_cc <<EOF && enable pragma_deprecated
void foo(void) { _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"") }
EOF

check_cc <<EOF && enable attribute_packed
struct { int x; } __attribute__((packed)) x;
EOF

check_cc <<EOF && enable attribute_may_alias
union { int x; } __attribute__((may_alias)) x;
EOF

check_cc <<EOF || die "endian test failed"
unsigned int endian = 'B' << 24 | 'I' << 16 | 'G' << 8 | 'E';
EOF
od -t x1 $TMPO | grep -q '42 *49 *47 *45' && enable bigendian

check_cc <<EOF && enable const_nan
#include <math.h>
void foo(void) { struct { double d; } static const bar[] = { { NAN } }; }
EOF

if ! enabled ppc64 || enabled bigendian; then
    disable vsx
fi

check_gas() {
    log "check_gas using '$as' as AS"
    # :vararg is used on aarch64, arm and ppc altivec
    check_as <<EOF || return 1
.macro m n, y:vararg=0
\n: .int \y
.endm
m x
EOF
    # .altmacro is only used in arm asm
    ! enabled arm || check_as <<EOF || return 1
.altmacro
EOF
    enable gnu_as
    return 0
}

if enabled_any arm aarch64 || enabled_all ppc altivec && enabled asm; then
    nogas=:
    enabled_any arm aarch64 && nogas=die
    enabled_all ppc altivec && [ $target_os_default != aix ] && nogas=warn
    as_noop=-v

    case $as_type in
        arm*) gaspp_as_type=armasm; as_noop=-h ;;
        gcc)  gaspp_as_type=gas ;;
        *)    gaspp_as_type=$as_type ;;
    esac

    [ $target_os = "darwin" ] && gaspp_as_type="apple-$gaspp_as_type"

    test "${as#*gas-preprocessor.pl}" != "$as" ||
    check_cmd gas-preprocessor.pl -arch $arch -as-type $gaspp_as_type -- ${as:=$cc} $as_noop &&
        gas="${gas:=gas-preprocessor.pl} -arch $arch -as-type $gaspp_as_type -- ${as:=$cc}"

    if ! check_gas ; then
        as=${gas:=$as}
        check_gas || \
            $nogas "GNU assembler not found, install/update gas-preprocessor"
    fi

    check_as <<EOF && enable as_func
.func test
.endfunc
EOF
fi

check_inline_asm inline_asm_labels '"1:\n"'

check_inline_asm inline_asm_nonlocal_labels '"Label:\n"'

if enabled aarch64; then
    enabled armv8 && check_insn armv8 'prfm   pldl1strm, [x0]'
    # internal assembler in clang 3.3 does not support this instruction
    enabled neon && check_insn neon 'ext   v0.8B, v0.8B, v1.8B, #1'
    enabled vfp  && check_insn vfp  'fmadd d0,    d0,    d1,    d2'

    map 'enabled_any ${v}_external ${v}_inline || disable $v' $ARCH_EXT_LIST_ARM

elif enabled alpha; then

    check_cflags -mieee

elif enabled arm; then

    enabled msvc && check_cpp_condition stddef.h "defined _M_ARMT" && enable thumb

    check_cpp_condition stddef.h "defined __thumb__" && check_cc <<EOF && enable_weak thumb
float func(float a, float b){ return a+b; }
EOF

    enabled thumb && check_cflags -mthumb || check_cflags -marm

    if     check_cpp_condition stddef.h "defined __ARM_PCS_VFP"; then
        enable vfp_args
    elif check_cpp_condition stddef.h "defined _M_ARM_FP && _M_ARM_FP >= 30"; then
        enable vfp_args
    elif ! check_cpp_condition stddef.h "defined __ARM_PCS || defined __SOFTFP__" && [ $target_os != darwin ]; then
        case "${cross_prefix:-$cc}" in
            *hardfloat*)         enable vfp_args;   fpabi=vfp ;;
            *) check_ld "cc" <<EOF && enable vfp_args && fpabi=vfp || fpabi=soft ;;
__asm__ (".eabi_attribute 28, 1");
int main(void) { return 0; }
EOF
        esac
        warn "Compiler does not indicate floating-point ABI, guessing $fpabi."
    fi

    enabled armv5te && check_insn armv5te 'qadd r0, r0, r0'
    enabled armv6   && check_insn armv6   'sadd16 r0, r0, r0'
    enabled armv6t2 && check_insn armv6t2 'movt r0, #0'
    enabled neon    && check_insn neon    'vadd.i16 q0, q0, q0'
    enabled vfp     && check_insn vfp     'fadds s0, s0, s0'
    enabled vfpv3   && check_insn vfpv3   'vmov.f32 s0, #1.0'
    enabled setend  && check_insn setend  'setend be'

    [ $target_os = linux ] || [ $target_os = android ] ||
        map 'enabled_any ${v}_external ${v}_inline || disable $v' \
            $ARCH_EXT_LIST_ARM

    check_inline_asm asm_mod_q '"add r0, %Q0, %R0" :: "r"((long long)0)'

    check_as <<EOF && enable as_dn_directive
ra .dn d0.i16
.unreq ra
EOF
    check_as <<EOF && enable as_fpu_directive
.fpu neon
EOF

    # llvm's integrated assembler supports .object_arch from llvm 3.5
    [ "$objformat" = elf32 ] || [ "$objformat" = elf64 ] &&
        check_as <<EOF && enable as_object_arch
.object_arch armv4
EOF

    [ $target_os != win32 ] && enabled_all armv6t2 shared !pic && enable_weak_pic

elif enabled mips; then

    enabled loongson2 && check_inline_asm loongson2 '"dmult.g $8, $9, $10"'
    enabled loongson3 && check_inline_asm loongson3 '"gsldxc1 $f0, 0($2, $3)"'
    enabled mmi && check_inline_asm mmi '"punpcklhw $f0, $f0, $f0"'

    # Enable minimum ISA based on selected options
    if enabled mips64; then
        enabled mips64r6 && check_inline_asm_flags mips64r6 '"dlsa $0, $0, $0, 1"' '-mips64r6'
        enabled mips64r2 && check_inline_asm_flags mips64r2 '"dext $0, $0, 0, 1"' '-mips64r2'
        disabled mips64r6 && disabled mips64r2 && check_inline_asm_flags mips64r1 '"daddi $0, $0, 0"' '-mips64'
    else
        enabled mips32r6 && check_inline_asm_flags mips32r6 '"aui $0, $0, 0"' '-mips32r6'
        enabled mips32r5 && check_inline_asm_flags mips32r5 '"eretnc"' '-mips32r5'
        enabled mips32r2 && check_inline_asm_flags mips32r2 '"ext $0, $0, 0, 1"' '-mips32r2'
        disabled mips32r6 && disabled mips32r5 && disabled mips32r2 && check_inline_asm_flags mips32r1 '"addi $0, $0, 0"' '-mips32'
    fi

    enabled mipsfpu && check_inline_asm_flags mipsfpu '"cvt.d.l $f0, $f2"' '-mhard-float'
    enabled mipsfpu && (enabled mips32r5 || enabled mips32r6 || enabled mips64r6) && check_inline_asm_flags mipsfpu '"cvt.d.l $f0, $f1"' '-mfp64'
    enabled mipsfpu && enabled msa && check_inline_asm_flags msa '"addvi.b $w0, $w1, 1"' '-mmsa' && check_header msa.h || disable msa
    enabled mipsdsp && check_inline_asm_flags mipsdsp '"addu.qb $t0, $t1, $t2"' '-mdsp'
    enabled mipsdspr2 && check_inline_asm_flags mipsdspr2 '"absq_s.qb $t0, $t1"' '-mdspr2'

    if enabled bigendian && enabled msa; then
        disable msa
    fi

elif enabled parisc; then

    if enabled gcc; then
        case $($cc -dumpversion) in
            4.[3-9].*) check_cflags -fno-optimize-sibling-calls ;;
        esac
    fi

elif enabled ppc; then

    enable local_aligned_8 local_aligned_16 local_aligned_32

    check_inline_asm dcbzl     '"dcbzl 0, %0" :: "r"(0)'
    check_inline_asm ibm_asm   '"add 0, 0, 0"'
    check_inline_asm ppc4xx    '"maclhw r10, r11, r12"'
    check_inline_asm xform_asm '"lwzx %1, %y0" :: "Z"(*(int*)0), "r"(0)'

    # AltiVec flags: The FSF version of GCC differs from the Apple version
    if enabled altivec; then
        check_cflags -maltivec -mabi=altivec &&
        { check_header altivec.h && inc_altivec_h="#include <altivec.h>" ; } ||
        check_cflags -faltivec
        check_cxxflags -maltivec -mabi=altivec &&
        { check_header altivec.h && inc_altivec_h="#include <altivec.h>" ; } ||
        check_cxxflags -faltivec

        # check if our compiler supports Motorola AltiVec C API
        check_cc <<EOF || disable altivec
$inc_altivec_h
int main(void) {
    vector signed int v1 = (vector signed int) { 0 };
    vector signed int v2 = (vector signed int) { 1 };
    v1 = vec_add(v1, v2);
    return 0;
}
EOF

        enabled altivec || warn "Altivec disabled, possibly missing --cpu flag"
    fi

    if enabled vsx; then
        check_cflags -mvsx &&
        check_builtin vec_vsx_ld "altivec.h" "__builtin_vec_vsx_ld" || disable vsx
    fi

    if enabled power8; then
        check_cpp_condition "altivec.h" "defined(_ARCH_PWR8)" || disable power8
    fi

elif enabled x86; then

    check_builtin rdtsc    intrin.h   "__rdtsc()"
    check_builtin mm_empty mmintrin.h "_mm_empty()"

    enable local_aligned_8 local_aligned_16 local_aligned_32

    # check whether EBP is available on x86
    # As 'i' is stored on the stack, this program will crash
    # if the base pointer is used to access it because the
    # base pointer is cleared in the inline assembly code.
    check_exec_crash <<EOF && enable ebp_available
volatile int i=0;
__asm__ volatile ("xorl %%ebp, %%ebp" ::: "%ebp");
return i;
EOF

    # check whether EBX is available on x86
    check_inline_asm ebx_available '""::"b"(0)' &&
        check_inline_asm ebx_available '"":::"%ebx"'

    # check whether xmm clobbers are supported
    check_inline_asm xmm_clobbers '"":::"%xmm0"'

    check_inline_asm inline_asm_direct_symbol_refs '"movl '$extern_prefix'test, %eax"' ||
        check_inline_asm inline_asm_direct_symbol_refs '"movl '$extern_prefix'test(%rip), %eax"'

    # check whether binutils is new enough to compile SSSE3/MMXEXT
    enabled ssse3  && check_inline_asm ssse3_inline  '"pabsw %xmm0, %xmm0"'
    enabled mmxext && check_inline_asm mmxext_inline '"pmaxub %mm0, %mm1"'

    probe_x86asm(){
        x86asmexe_probe=$1
        if check_cmd $x86asmexe_probe -v; then
            x86asmexe=$x86asmexe_probe
            x86asm_type=nasm
            x86asm_debug="-g -F dwarf"
        elif check_cmd $x86asmexe_probe --version; then
            x86asmexe=$x86asmexe_probe
            x86asm_type=yasm
            x86asm_debug="-g dwarf2"
        fi
        check_x86asm "movbe ecx, [5]" && enable x86asm
    }

    if ! disabled_any asm mmx x86asm; then
        disable x86asm
        for program in $x86asmexe nasm yasm; do
            probe_x86asm $program && break
        done
        disabled x86asm && die "nasm/yasm not found or too old. Use --disable-x86asm for a crippled build."
        test $x86asm_type = 'nasm' && X86ASM_DEPFLAGS='-MD $(@:.o=.d)'
        test $x86asm_type = 'yasm' && X86ASMDEP='$(DEPX86ASM) $(X86ASMFLAGS) -M $(X86ASM_O) $< > $(@:.o=.d)'
        X86ASMFLAGS="-f $objformat"
        enabled pic               && append X86ASMFLAGS "-DPIC"
        test -n "$extern_prefix"  && append X86ASMFLAGS "-DPREFIX"
        case "$objformat" in
            elf*) enabled debug && append X86ASMFLAGS $x86asm_debug ;;
        esac

        check_x86asm "vextracti128 xmm0, ymm0, 0"      || disable avx2_external
        check_x86asm "vpmacsdd xmm0, xmm1, xmm2, xmm3" || disable xop_external
        check_x86asm "vfmaddps ymm0, ymm1, ymm2, ymm3" || disable fma4_external
        check_x86asm "CPU amdnop" || disable cpunop
    fi

    case "$cpu" in
        athlon*|opteron*|k8*|pentium|pentium-mmx|prescott|nocona|atom|geode)
            disable fast_clz
        ;;
    esac

fi

check_code cc arm_neon.h "int16x8_t test = vdupq_n_s16(0)" && enable intrinsics_neon

check_ldflags -Wl,--as-needed
check_ldflags -Wl,-z,noexecstack

use_pkg_config sqlite3 sqlite3 "sqlite3.h" sqlite3_load_extension && enable sqlite3
require_pkg_config samplerate samplerate samplerate.h src_get_version -lm

# required to compile inline sse with some compilers
enabled x86 && enabled sse2 && add_cxxflags "-msse"

# test for distcc
enabled distcc && check_cmd distcc --version || disable distcc
if enabled distcc; then
    XYZ=`which $cc`
    if test x"$XYZ" != x"" -a x"`ls -l $XYZ | grep distcc`" != x""; then
        distcc="symlink"
        distcc_txt=" $cc"
    fi
fi

# test for ccache
enabled ccache && check_cmd ccache -V || disable ccache
if enabled ccache; then
    XYZ=`which $cc`
    if test x"$XYZ" != x"" -a x"`ls -l $XYZ | grep ccache`" != x""; then
        ccache="symlink"
        ccache_txt=" $cc"
    fi
fi

# ccache should be used before distcc for better cache coherency
if enabled distcc; then
    if disabled ccache; then
        cc="distcc $cc"
        cxx="distcc $cxx"
    elif enabled ccache; then
        cc="ccache distcc $cc"
        cxx="ccache distcc $cxx"
    else
        disable distcc
        distcc_txt="t using distcc explicitly, since ccache symlink is present"
    fi
else
    if enabled ccache; then
        cc="ccache $cc"
        cxx="ccache $cxx"
    fi
fi

check_builtin atomic_cas_ptr atomic.h "void **ptr; void *oldval, *newval; atomic_cas_ptr(ptr, oldval, newval)"
check_builtin machine_rw_barrier mbarrier.h "__machine_rw_barrier()"
check_builtin MemoryBarrier windows.h "MemoryBarrier()"
check_builtin sarestart signal.h "SA_RESTART"
check_builtin sem_timedwait semaphore.h "sem_t *s; sem_init(s,0,0); sem_timedwait(s,0); sem_destroy(s)" -lpthread
check_builtin sync_val_compare_and_swap "" "int *ptr; int oldval, newval; __sync_val_compare_and_swap(ptr, oldval, newval)"
check_builtin x264_csp_bgr x264.h X264_CSP_BGR

check_func  gettimeofday

check_header dirent.h
check_header dlfcn.h
check_header dxva2api.h -D_WIN32_WINNT=0x0600
check_header fcntl.h
check_header mntent.h
check_func_headers mntent.h getmntent_r
check_header pthread.h
check_header strings.h
check_header sys/dl.h
check_header sys/param.h
check_header sys/time.h
check_header unistd.h
check_header valgrind/valgrind.h
check_header vulkan/vulkan_core.h
check_header linux/videodev2.h

#Myth check for MYTHTV_HAVE_LIST
check_header va/va.h
check_header va/va_x11.h
check_header va/va_glx.h
check_struct dxva2api.h DXVA_PictureParameters wDecodedPictureIndex
check_func posix_fadvise
check_func_headers sys/timeb.h ftime
check_func_headers "sys/types.h sys/socket.h ifaddrs.h" getifaddrs
check_func_headers sys/time.h gettimeofday
#End MythTV check

check_type "d3d9.h dxva2api.h" DXVA2_ConfigPictureDecode -D_WIN32_WINNT=0x0602

check_type "va/va.h va/va_dec_hevc.h" "VAPictureParameterBufferHEVC"
check_struct "va/va.h" "VADecPictureParameterBufferVP9" bit_depth
check_type "va/va.h va/va_vpp.h" "VAProcPipelineParameterBuffer"
check_type "va/va.h va/va_enc_h264.h" "VAEncPictureParameterBufferH264"
check_type "va/va.h va/va_enc_hevc.h" "VAEncPictureParameterBufferHEVC"
check_type "va/va.h va/va_enc_jpeg.h" "VAEncPictureParameterBufferJPEG"
check_type "va/va.h va/va_enc_mpeg2.h" "VAEncPictureParameterBufferMPEG2"
check_type "va/va.h va/va_enc_vp8.h"  "VAEncPictureParameterBufferVP8"
check_type "va/va.h va/va_enc_vp9.h"  "VAEncPictureParameterBufferVP9"

check_type "vdpau/vdpau.h" "VdpPictureInfoHEVC"

check_cpp_condition windows.h "!WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)" && enable winrt || disable winrt

if ! disabled w32threads && ! enabled pthreads; then
    check_func_headers "windows.h process.h" _beginthreadex &&
        enable w32threads || disable w32threads
    if ! enabled w32threads && enabled winrt; then
        check_func_headers "windows.h" CreateThread &&
            enable w32threads || disable w32threads
    fi
fi

# check for some common methods of building with pthread support
# do this before the optional library checks as some of them require pthreads
if ! disabled pthreads && ! enabled w32threads && ! enabled os2threads; then
    if check_lib pthreads pthread.h pthread_join   -pthread &&
       check_lib pthreads pthread.h pthread_create -pthread; then
        add_cflags -pthread
        add_cxxflags -pthread
    elif check_lib pthreads pthread.h pthread_join   -pthreads &&
         check_lib pthreads pthread.h pthread_create -pthreads; then
        add_cflags -pthreads
        add_cxxflags -pthread
    elif check_lib pthreads pthread.h pthread_join   -ldl -pthread &&
         check_lib pthreads pthread.h pthread_create -ldl -pthread; then
        add_cflags -ldl -pthread
    elif check_lib pthreads pthread.h pthread_join   -lpthreadGC2 &&
         check_lib pthreads pthread.h pthread_create -lpthreadGC2; then
        :
    elif check_lib pthreads pthread.h pthread_join   -lpthread &&
         check_lib pthreads pthread.h pthread_create -lpthread; then
        :
    elif check_func pthread_join && check_func pthread_create; then
        enable pthreads
    fi
    check_code cc "pthread.h" "static pthread_mutex_t atomic_lock = PTHREAD_MUTEX_INITIALIZER" || disable pthreads
fi

enabled ffmpeg_pthreads && enable pthreads

# Check for taglib for libmythmetadata. MSYS2 uses taglib-config.cmd
TAGLIB_CONFIG=""
if enabled taglib; then
    taglib_verstring="nothing"
    taglib_version=0
    if test $pkg_config ; then
        taglib_verstring=`$pkg_config --modversion taglib`
        taglib_version=$(version2num10 $taglib_verstring)
        if test $target_os = android ; then
            tagprefix=`$pkg_config --variable=prefix taglib`
        else
            tagprefix=${sysroot}`$pkg_config --variable=prefix taglib`
        fi
        tagincludes="-I${tagprefix}/include"
        taglibs=`$pkg_config --libs taglib`
        if test $target_os = android ; then
            taglibs="$taglibs -lz -lm"
        fi
    fi

    if test $taglib_version -lt 1011001 || \
            ! check_class_headers_cpp "taglib/fileref.h stdlib.h" TagLib::FileRef $tagincludes $taglibs -lstdc++; then
        die "ERROR: cannot find taglib 1.11.1 or later (found $taglib_verstring)."
    fi
fi

# Attempt to use libudev for mediamonitor
enabled libudev && check_lib udev libudev.h udev_new -ludev || disable libudev

# libexiv2
if enabled system_libexiv2 ; then
    if $(pkg-config --atleast-version="0.28" exiv2); then
        use_pkg_config exiv2 exiv2 exiv2/exiv2.hpp versionNumber
    elif [ $target_os != "android" ] ; then
        disable system_libexiv2
    fi
fi

# soundtouch
if $($pkg_config --atleast-version="1.8.0" soundtouch); then
    # use_pkg_config does not add cxxflags
    add_cxxflags $($pkg_config --cflags soundtouch)
    add_extralibs $($pkg_config --libs soundtouch)
else
    die "ERROR: cannot find soundtouch 1.8.0 or later."
fi

if [ $target_os = "linux" ] ; then
    . /etc/os-release
fi

# libudfread
if enabled system_libudfread ; then
    if $(pkg-config --atleast-version="1.1.1" libudfread); then
        use_pkg_config libudfread libudfread udfread/udfread.h udfread_init
    else
        disable system_libudfread
    fi
fi

# libmythbluray!
if enabled system_libbluray; then
    if $(pkg-config --atleast-version="0.9.3" libbluray); then
        use_pkg_config libbluray libbluray libbluray/bluray.h bd_open
    else
        case $target_os in
            linux)
                # Some older supported linux versions don't have a
                # libbluray current enough to support MythTV.  Allow
                # only those systems to reach the bottom of the
                # following case statement.  This list should only
                # shrink over time.
                case $ID in
                    centos|rocky|almalinux)
                        if test ${VERSION_ID%\.*} -gt 8; then
                            die "ERROR: can not find libbluray."
                        fi
                        ;;
                    rhel)
                        # RHEL8 doesn't ship libbluray-devel because of
                        # some issue between RedHat and EPEL.
                        #
                        # Allow the internel libbluray to compile.
                        if test ${VERSION_ID%\.*} -gt 8; then
                            die "ERROR: can not find libbluray."
                        fi
                        ;;
                    *)
                        die "ERROR: can not find libbluray."
                        ;;
                esac
                disable system_libbluray
                ;;
            *)
                # FreeBSD provides libbluray 1.0.2
                # All others unknown.
                die "ERROR: can not find libbluray."
                ;;
        esac
    fi
fi

antbin=""
java_code_version=""
if enabled bdjava; then
    enabled x86_64 && java_arch=amd64
    enabled x86_32 && java_arch=i386
    enabled arm    && java_arch=arm

    antbin=`which ant`
    if test x"$antbin" = x"" ; then
        die "ERROR: BD-J requires ANT, but ant was not found. Please install it."
    fi

    # Probably makes little sense to try to process Bluray menus without fontconfig
    enable fontconfig

    if test "$bdj_type" = "j2me"; then
        enable bdj_j2me
    else
        if test "x${JAVA_HOME}" = "x"; then
            JAVAC=`which javac`
        else
            JAVAC=${JAVA_HOME}/bin/javac
        fi

        test -f ${JAVAC} -a -x ${JAVAC} || die "ERROR: javac not found but required by BD-J"

        java_code_version=1.4

        javac_version=`"${JAVAC}" -version 2>&1 | head -n 1`

        echo "${javac_version}" | grep -E -q '^javac (9|1[0-1])' && java_code_version=1.6
        echo "${javac_version}" | grep -E -q '^javac (1[2-9])' && java_code_version=1.7
        echo "${javac_version}" | grep -E -q '^javac (2.*)' && java_code_version=1.7
    fi
fi

enabled pthreads &&
    check_builtin sem_timedwait semaphore.h "sem_t *s; sem_init(s,0,0); sem_timedwait(s,0); sem_destroy(s)"

require zlib zlib.h zlibVersion -lz
require zip zip.h zip_open -lzip

# On some systems dynamic loading requires no extra linker flags
check_lib libdl dlfcn.h "dlopen dlsym" || check_lib libdl dlfcn.h "dlopen dlsym" -ldl

# these are off by default, so fail if requested and not available
enabled jni               && { [ $target_os = "android" ] && check_header jni.h && enabled pthreads || die "ERROR: jni not found"; }
enabled libiec61883       && require libiec61883 libiec61883/iec61883.h iec61883_cmp_connect -lraw1394 -lavc1394 -lrom1394 -liec61883
enabled fontconfig        && enable libfontconfig
enabled libfontconfig     && require_pkg_config libfontconfig fontconfig "fontconfig/fontconfig.h" FcInit
enabled libfreetype       && require_pkg_config libfreetype2 freetype2 "ft2build.h FT_FREETYPE_H" FT_Init_FreeType
enabled libmp3lame        && require "libmp3lame >= 3.98.3" lame/lame.h lame_set_VBR_quality -lmp3lame
enabled libpulse          && require_pkg_config libpulse libpulse pulse/pulseaudio.h pa_context_new
enabled libv4l2           && require_pkg_config libv4l2 libv4l2 libv4l2.h v4l2_ioctl

enabled libx264           && { use_pkg_config libx264 x264 x264.h x264_encoder_encode ||
                               { require libx264 x264.h x264_encoder_encode -lx264 &&
                                 warn "using libx264 without pkg-config"; } } &&
                             require_cpp_condition x264.h "X264_BUILD >= 118" &&
                             { check_cpp_condition x264.h "X264_MPEG2" &&
                               enable libx262; }
enabled libxml2           && require_pkg_config libxml2 libxml-2.0 libxml2/libxml/xmlversion.h xmlCheckVersion

enabled drm && use_pkg_config libdrm libdrm xf86drm.h drmGetVersion || disable drm
enabled drm && check_cpp_condition drm_fourcc.h 'defined(DRM_FORMAT_MOD_LINEAR)' || disable drm
enabled drm && check_type drm_mode.h "struct hdr_metadata_infoframe"

if enabled libmpeg2external; then
    check_lib libmpeg2external "stdint.h mpeg2dec/mpeg2.h" mpeg2_init -lmpeg2 || disable libmpeg2external
    if disabled libmpeg2external; then
        die "Warning! No suitable external libmpeg2 found, use internal copy."
    fi
    disable mythtranscode
fi

if enabled hdhomerun; then
    # Fedora and Debian/Ubuntu use different include directories.  So does OSX.
    if check_header hdhomerun.h ; then
	HDHOMERUN_PREFIX=
    elif check_header hdhomerun/hdhomerun.h ; then
	HDHOMERUN_PREFIX=hdhomerun/
    elif check_header libhdhomerun/hdhomerun.h ; then
	HDHOMERUN_PREFIX=libhdhomerun/
    else
        disable hdhomerun
    fi

    # Figure out the API version
    if check_lib libhdhomerun ${HDHOMERUN_PREFIX}hdhomerun.h hdhomerun_discover2_find_devices_broadcast -lhdhomerun; then
        HDHOMERUN_VERSION=20221010
    else
        HDHOMERUN_VERSION=0
    fi
fi

check_header stdint.h

# test for lrint in math.h
check_exec <<EOF && lrint=yes || lrint=no
#define _ISOC9X_SOURCE  1
#include <math.h>
int main( void ) { return (lrint(3.999f) > 0)?0:1; }
EOF

#test for round()
check_exec <<EOF && round=yes || round=no
#define _ISOC9X_SOURCE  1
#include <math.h>
int main( void ) { return (round(3.999f) > 0)?0:1; }
EOF

# test for sync_file_range (linux only system call since 2.6.17)
check_ld "cc" <<EOF #&& enable sync_file_range
#define _GNU_SOURCE
#include <fcntl.h>

int main(int argc, char **argv){
    sync_file_range(0,0,0,0);
    return 0;
}
EOF

# test for close_range (linux system call since 5.9 and also FreeBSD)
check_ld "cc" <<EOF && enable close_range
#define _GNU_SOURCE
#include <unistd.h>

int main(int argc, char **argv){
    close_range(0,0,0);
    return 0;
}
EOF

# test for sizeof(int)
for sizeof in 1 2 4 8 16; do
    check_cc <<EOF && _sizeof_int=$sizeof && break
void foo(){switch (0) case 0: case (sizeof(int) == $sizeof):;}
EOF
done

# test for sizeof(long)
for sizeof in 1 2 4 8 16; do
  check_cc <<EOF && _sizeof_long=$sizeof && break
void foo(){switch (0) case 0: case (sizeof(long) == $sizeof):;}
EOF
done

if require_pkg_config libfreetype2 freetype2 "ft2build.h FT_FREETYPE_H" FT_Init_FreeType ; then
    enable freetype2
else
    disable freetype2
fi

enabled freetype2 ||
    die "ERROR! You must have FreeType installed to compile MythTV."


##########################################

makeinfo --version > /dev/null 2>&1 && enable makeinfo  || disable makeinfo
enabled makeinfo \
    && [ 0$(makeinfo --version | grep "texinfo" | sed 's/.*texinfo[^0-9]*\([0-9]*\)\..*/\1/') -ge 5 ] \
    && enable makeinfo_html || disable makeinfo_html
disabled makeinfo_html && texi2html --help 2> /dev/null | grep -q 'init-file' && enable texi2html || disable texi2html
perl -v            > /dev/null 2>&1 && enable perl      || disable perl
pod2man --help     > /dev/null 2>&1 && enable pod2man   || disable pod2man
rsync --help 2> /dev/null | grep -q 'contimeout' && enable rsync_contimeout || disable rsync_contimeout

check_lib user32 "windows.h winuser.h" GetShellWindow -luser32
check_lib vfw32 "windows.h vfw.h" capCreateCaptureWindow -lvfw32
# check that WM_CAP_DRIVER_CONNECT is defined to the proper value
# w32api 3.12 had it defined wrong
check_cpp_condition vfw.h "WM_CAP_DRIVER_CONNECT > WM_USER" && enable vfwcap_defines

check_type "dshow.h" IBaseFilter

if check_struct sys/soundcard.h audio_buf_info bytes; then
    enable_safe sys/soundcard.h
else
    check_cc -D__BSD_VISIBLE -D__XSI_VISIBLE <<EOF && add_cppflags -D__BSD_VISIBLE -D__XSI_VISIBLE && enable_safe sys/soundcard.h
    #include <sys/soundcard.h>
    audio_buf_info abc;
EOF
fi
check_header soundcard.h

enabled alsa && check_lib alsa alsa/asoundlib.h snd_pcm_htimestamp -lasound

enabled jack && use_pkg_config libjack jack jack/jack.h jack_port_get_latency_range && enable audio_jack || disable audio_jack

# PulseAudio probe
! disabled audio_pulse &&
    check_lib pulse pulse/version.h pa_get_library_version -lpulse &&
    $(pkg-config --atleast-version=0.9.7 libpulse) &&
    enable  audio_pulse ||
    disable audio_pulse

# Enable Pulse Audio output iff not disabled and pulse audio is available
if ! enabled audio_pulse ; then
    disable audio_pulseoutput
elif ! disabled audio_pulseoutput ; then
    enable audio_pulseoutput
fi

# ALSA probe
! disabled audio_alsa &&
    check_lib asound alsa/asoundlib.h snd_asoundlib_version  &&
    check_cpp_condition alsa/asoundlib.h "(defined(SND_PCM_NO_AUTO_RESAMPLE))" &&
    enable  audio_alsa ||
    { { ! enabled audio_alsa || die "ERROR: Alsa >= 1.0.16 required"; } &&
    disable audio_alsa; }

check_func_headers "windows.h" CreateDIBSection "$gdigrab_indev_extralibs"

# Check VA1 support before enabling in FFmpeg
enabled libaom   && use_pkg_config libaom "aom >= 2.0.0" aom/aom_codec.h aom_codec_version || disable libaom
enabled libdav1d && use_pkg_config libdav1d "dav1d >= 0.4.0" "dav1d/dav1d.h" dav1d_version || disable libdav1d

enabled vaapi && enabled opengl &&
    check_header GL/glx.h &&
    check_lib vaapi va/va.h vaInitialize -lva

enabled vaapi &&
    check_code cc "va/va.h" "vaCreateSurfaces(0, 0, 0, 0, 0, 0, 0, 0)" ||
    disable vaapi

enabled vaapi &&
    check_lib vaapi_drm "va/va.h va/va_drm.h" vaGetDisplayDRM -lva -lva-drm

enabled vaapi &&
    check_lib vaapi_x11 "va/va.h va/va_x11.h" vaGetDisplay -lva -lva-x11 -lX11

enabled vaapi &&
    check_cpp_condition "va/va.h" "VA_CHECK_VERSION(1, 0, 0)" &&
    enable vaapi_1

enabled vdpau &&
    check_cpp_condition vdpau/vdpau.h "defined VDP_DECODER_PROFILE_MPEG4_PART2_ASP" ||
    disable vdpau

enabled vdpau &&
    check_lib vdpau_x11 "vdpau/vdpau.h vdpau/vdpau_x11.h" vdp_device_create_x11 -lvdpau -lX11

if test $target_os = linux ; then
    enabled mmal && { check_func_headers interface/mmal/mmal.h mmal_port_connect -lmmal_core -lmmal_util -lmmal_vc_client -lbcm_host ||
                    { ! enabled cross_compile &&
                        add_cflags -isystem/opt/vc/include/ -isystem/opt/vc/include/interface/vmcs_host/linux -isystem/opt/vc/include/interface/vcos/pthreads -fgnu89-inline &&
                        add_ldflags -L/opt/vc/lib/ &&
                        check_func_headers interface/mmal/mmal.h mmal_port_connect -lmmal_core -lmmal_util -lmmal_vc_client -lbcm_host; }
                        check_func_headers interface/mmal/mmal.h "MMAL_PARAMETER_VIDEO_MAX_NUM_CALLBACKS"; } || disable mmal
else
    disable mmal
fi

enabled debug && add_cflags -g"$debuglevel" && add_asflags -g"$debuglevel"
enabled debug && add_cxxflags -g"$debuglevel"

# add some useful compiler flags if supported
#check_cflags -Wdeclaration-after-statement
check_cflags -Wall
check_cflags -Wextra
if disabled deprecation_warnings; then
    check_cflags -Wno-deprecated-declarations
fi
! disabled optimizations && check_cflags -Wdisabled-optimization
check_cflags -Wpointer-arith
disabled icc && check_cflags -Wredundant-decls
check_cflags -Wwrite-strings
check_cflags -Wundef
#-Wmissing-prototypes breaks zeromq compilation in universal mode
if [ "$target_os" != "darwin" ]; then
    check_cflags -Wmissing-prototypes
fi
check_cflags -Wno-pointer-to-int-cast
check_cflags -Wstrict-prototypes

if enabled extra_warnings; then
    check_cflags -Wcast-qual
    check_cflags -Wextra
    check_cflags -Wpedantic
fi

check_disable_warning(){
    warning_flag=-W${1#-Wno-}
    test_cflags $unknown_warning_flags $warning_flag && add_cflags $1
}

test_cflags -Werror=unused-command-line-argument &&
    append unknown_warning_flags "-Werror=unused-command-line-argument"
test_cflags -Werror=unknown-warning-option &&
    append unknown_warning_flags "-Werror=unknown-warning-option"

check_disable_warning -Wno-parentheses
disabled icc && check_disable_warning -Wno-switch
check_disable_warning -Wno-format-zero-length
check_disable_warning -Wno-pointer-sign
check_disable_warning -Wno-unused-const-variable
check_disable_warning -Wno-bool-operation

check_disable_warning_headers(){
    warning_flag=-W${1#-Wno-}
    test_cflags $warning_flag && add_cflags_headers $1
}

check_disable_warning_headers -Wno-deprecated-declarations
check_disable_warning_headers -Wno-unused-variable

check_cc <<EOF && enable blocks_extension
void (^block)(void);
EOF

# C++ Flags
check_cxxflags -Wall
check_cxxflags -Wextra
check_cxxflags -Wpointer-arith
check_cxxflags -Wundef
check_cxxflags -Wno-unknown-pragmas
if disabled deprecation_warnings; then
    check_cxxflags -Wno-deprecated-declarations
fi

# add some linker flags
check_ldflags -Wl,--warn-common
check_ldflags '-Wl,-rpath-link,\$\${SRC_PATH_BARE}/external/FFmpeg/libpostproc:\$\${SRC_PATH_BARE}/external/FFmpeg/libswresample:\$\${SRC_PATH_BARE}/external/FFmpeg/libswscale:\$\${SRC_PATH_BARE}/external/FFmpeg/libavfilter:\$\${SRC_PATH_BARE}/external/FFmpeg/libavdevice:\$\${SRC_PATH_BARE}/external/FFmpeg/libavformat:\$\${SRC_PATH_BARE}/external/FFmpeg/libavcodec:\$\${SRC_PATH_BARE}/external/FFmpeg/libavutil'
enabled rpath && add_ldexeflags -Wl,-rpath,$libdir
enabled rpath && add_ldlibflags -Wl,-rpath,$libdir
test_ldflags -Wl,-Bsymbolic && append SHFLAGS -Wl,-Bsymbolic

enabled neon_clobber_test &&
    check_ldflags -Wl,--wrap,avcodec_open2              \
                  -Wl,--wrap,avcodec_decode_audio4      \
                  -Wl,--wrap,avcodec_decode_video2      \
                  -Wl,--wrap,avcodec_decode_subtitle2   \
                  -Wl,--wrap,avcodec_encode_audio2      \
                  -Wl,--wrap,avcodec_encode_video2      \
                  -Wl,--wrap,avcodec_encode_subtitle    \
                  -Wl,--wrap,avcodec_send_packet        \
                  -Wl,--wrap,avcodec_receive_packet     \
                  -Wl,--wrap,avcodec_send_frame         \
                  -Wl,--wrap,avcodec_receive_frame      \
                  -Wl,--wrap,swr_convert        ||
    disable neon_clobber_test

enabled xmm_clobber_test &&
    check_ldflags -Wl,--wrap,avcodec_open2              \
                  -Wl,--wrap,avcodec_decode_audio4      \
                  -Wl,--wrap,avcodec_decode_video2      \
                  -Wl,--wrap,avcodec_decode_subtitle2   \
                  -Wl,--wrap,avcodec_encode_audio2      \
                  -Wl,--wrap,avcodec_encode_video2      \
                  -Wl,--wrap,avcodec_encode_subtitle    \
                  -Wl,--wrap,avcodec_send_packet        \
                  -Wl,--wrap,avcodec_receive_packet     \
                  -Wl,--wrap,avcodec_send_frame         \
                  -Wl,--wrap,avcodec_receive_frame      \
                  -Wl,--wrap,swr_convert                \
                  -Wl,--wrap,sws_scale ||
    disable xmm_clobber_test

check_ld "cc" <<EOF && enable proper_dce
extern const int array[512];
static inline int func(void) { return array[0]; }
int main(void) { return 0; }
EOF

if enabled proper_dce; then
    echo "X { local: *; };" > $TMPV
    if test_ldflags -Wl,${version_script},$TMPV; then
        append SHFLAGS '-Wl,${version_script},\$(SUBDIR)lib\$(NAME).ver'
        check_cc <<EOF && enable symver_asm_label
void ff_foo(void) __asm__ ("av_foo@VERSION");
void ff_foo(void) { ${inline_asm+__asm__($quotes);} }
EOF
        check_cc <<EOF && enable symver_gnu_asm
__asm__(".symver ff_foo,av_foo@VERSION");
void ff_foo(void) {}
EOF
    fi
fi

if [ -z "$nvccflags" ]; then
    nvccflags=$nvccflags_default
fi

if enabled x86_64 || enabled ppc64 || enabled aarch64; then
    nvccflags="$nvccflags -m64"
else
    nvccflags="$nvccflags -m32"
fi


if enabled dvb; then
    [ -d "$dvb_path" ] || dvb_path="${sysroot}/usr/include"
    if test -f "$dvb_path"/linux/dvb/frontend.h ; then
        if test -f "$dvb_path"/../MAINTAINERS ; then
            echo "Warning: DVB location in kernel. May not compile."
        fi
    else
        KERNEL_RELEASE=`uname -r 2>/dev/null`
        if test x"$KERNEL_RELEASE" != x"" ; then
            dvb_path="${sysroot}/usr/src/linux-$KERNEL_RELEASE/include"
            [ -d "$dvb_path" ] ||\
                dvb_path="${sysroot}/usr/src/linux-headers-$KERNEL_RELEASE/include/uapi"
        else
            dvb_path="${sysroot}/usr/src/linux/include"
        fi

        if test -f "$dvb_path"/linux/dvb/frontend.h ; then
            if test -f "$dvb_path"/../MAINTAINERS ; then
                echo "Warning: DVB location in kernel. May not compile."
            fi
        else
            echo "DVB location needs to have linux/dvb/frontend.h [$dvb_path]"
            disable dvb
        fi
    fi
fi


enabled dvb && check_cc -I"$dvb_path" <<EOF && enable fe_can_2g_modulation
#include <linux/dvb/frontend.h>
int main(void) {
    if (FE_CAN_2G_MODULATION)
        return 1;
    return 0;
}
EOF

enabled asi && check_cc <<EOF || disable asi
#include <dveo/asi.h>
#include <dveo/master.h>
int main(void) { return 1; }
EOF

if enabled systemd_notify ; then
    if check_pkg_config systemd_notify libsystemd-daemon systemd/sd-daemon.h sd_notify ; then
        require_pkg_config systemd_notify libsystemd-daemon systemd/sd-daemon.h sd_notify
    elif check_pkg_config systemd_notify libsystemd systemd/sd-daemon.h sd_notify ; then
        require_pkg_config systemd_notify libsystemd systemd/sd-daemon.h sd_notify
    else
        disable systemd_notify
    fi
fi

if enabled systemd_journal ; then
   if check_pkg_config systemd_journal libsystemd systemd/sd-journal.h sd_journal_send ; then
        require_pkg_config systemd_journal libsystemd systemd/sd-journal.h sd_journal_send
   else
        disable systemd_journal
   fi
fi

# Check that all MythTV build "requirements" are met:
if enabled system_libexiv2 ; then
    if ! $(pkg-config --exists exiv2) ; then
       die "ERROR! You must have the Exiv2 image tag reader library installed to compile MythTV."
    fi
fi

# Qt dependency checks
if test $target_os = mingw32 ; then
    qt_inc="-I`cd $(${qmake} -query QT_INSTALL_HEADERS); pwd`"
    qt_libs="-L`cd $(${qmake} -query QT_INSTALL_LIBS) ; pwd`"
elif test $target_os = darwin ; then
    qt_inc="-I`cd $(${qmake} -query QT_INSTALL_HEADERS); pwd` -F`cd $(${qmake} -query QT_INSTALL_LIBS); pwd`"
    qt_libs="-L`cd $(${qmake} -query QT_INSTALL_LIBS) ; pwd`"
else
    qt_inc="-I$(${qmake} -query QT_INSTALL_HEADERS)"
    qt_libs="-L$(${qmake} -query QT_INSTALL_LIBS)"
fi

qt_compiler_check() {
    log "qt_compiler_check $@"
    "qt_compiler_check $@" >> $logfile 2>&1
    check_ecxx ${qt_inc} <<EOF
#include <QtCore/QtCore>
#ifndef $1
   Fail this test compile with garbage!!!
#endif
int x;
EOF
}

qt_compiler_check Q_COMPILER_NULLPTR && enable enforce_nullptr
case "$cc_type" in
    clang)
        # Clang on FreeBSD doesn't ignore warnings in system headers.
        # A trivial test shows that Clang defaults /usr/local/include
        # to a system directory, but somehow this gets messed up in
        # MythTV builds.
        if test $target_os = "freebsd"; then
            disable enforce_nullptr
        fi
        ## Clang on MacOSX also doesn't ignore warnings in system headers.
        if test $target_os = "darwin"; then
            disable enforce_nullptr
        fi
        if enabled compdb; then
            warn "Enabling clang's compdb support will disable ccache."
        fi
        ;;
esac

# we need either OpenGL or OpenGL ES and 'ideally' the same version that Qt was
# configured with. Linking to both can cause problems on some systems.
# opengl is enabled by default (and hence opengles is disabled by default)

qt_opengles_check() {
    log "qt_opengles_check $@"
    "qt_opengles_check $@" >> $logfile 2>&1
    check_ecxx ${qt_inc} <<EOF
#include <QtCore/QtCore>
#include <QtGui/qtguiglobal.h>
#if !defined(QT_OPENGL_ES_2) && (QT_FEATURE_opengles2 < 1)
No OpenGL ES here!
#endif
int x;
EOF
}

qt_opengles_check && enable opengles && disable opengl && echo Qt built for OpenGL ES

enabled opengl && { check_lib opengl GL/glx.h glXGetProcAddress "-lGL" ||
                    check_lib opengl windows.h wglGetProcAddress "-lopengl32 -lgdi32" ||
                    check_lib opengl OpenGL/gl3.h glGetError "-Wl,-framework,OpenGL" || disable opengl
                  }

disabled opengl || enabled opengles && {
                    check_lib opengl ES2/gl.h glGetError "-isysroot=${sysroot} -Wl,-framework,OpenGLES" ||
                    check_lib opengl GLES/gl.h glGetError "-Wl,-framework,OpenGLES" ||
                    { check_pkg_config GLESv2 glesv2 GLES2/gl2.h glGetError &&
                      check_pkg_config EGL egl EGL/egl.h eglGetProcAddress &&
                      enable opengles
                    } ||
                    { check_lib GLESv2 GLES2/gl2.h glGetError "-lGLESv2" &&
                      check_lib EGL EGL/egl.h eglGetProcAddress "-lEGL" &&
                      enable opengles
                    } ||
                      disable opengles
                  }

enabled opengles && enable opengl

# Vulkan requires Qt >5.10 and the Vulkan headers - Qt dynamically loads the libs
# (but we may need to link to Vulkan if we use any external/helper libraries (e.g. VMA).

qt_vulkan_check() {
    log "qt_vulkan_check $@"
    "qt_vulkan_check $@" >> $logfile 2>&1
    check_ecxx ${qt_inc} <<EOF
#include <QtCore/QtCore>
#include <QtGui/qtguiglobal.h>
#if QT_CONFIG(vulkan) != 1
No vulkan here!
#endif
int x;
EOF
}

if enabled vulkan ; then
    if !(qt_vulkan_check); then
        disable vulkan && disable libglslang && echo Vulkan is not supported with this version of Qt
    fi
fi

if ! (enabled opengl || enabled vulkan); then
    die "Need either OpenGL, OpenGLES or Vulkan. None found!"
fi

enabled egl &&  { check_lib EGL EGL/egl.h eglGetProcAddress "-lEGL" ||
                  {
                    check_pkg_config EGL egl EGL/egl.h eglGetProcAddress && enable egl
                  }
                }

case $ID in
    fedora|debian|raspbian)
        EXTRA_GLSLANG_LIBS="-lMachineIndependent -lGenericCodeGen" ;;
    ubuntu)
        case $VERSION_ID in
            2[1-9]*) EXTRA_GLSLANG_LIBS="-lMachineIndependent -lGenericCodeGen" ;;
       esac
esac

if enabled vulkan && enabled libglslang ; then
    # Debian sid no longer ships the OSDependent and HLSL libraries,
    # but vulkan support on that platform compiles fine without them.
    # Test to see if these libraries are present, and if not, test
    # again to see if the compile works without them.
    GLSLANG_LIBS="${EXTRA_GLSLANG_LIBS:-} -lSPVRemapper -lSPIRV -lSPIRV-Tools-opt -lSPIRV-Tools -lpthread"
    check_lib_cpp glslang/SPIRV/GlslangToSpv.h "glslang::TIntermediate*" -lglslang ${GLSLANG_LIBS} -lHLSL -lOGLCompiler -lOSDependent \
    || check_lib_cpp glslang/SPIRV/GlslangToSpv.h "glslang::TIntermediate*" -lglslang ${GLSLANG_LIBS} -lHLSL -lOGLCompiler \
    || check_lib_cpp glslang/SPIRV/GlslangToSpv.h "glslang::TIntermediate*" -lglslang ${GLSLANG_LIBS}  \
    || die "ERROR: libglslang (or dependent) library not found"
fi

# Qt private headers are required for wayland extras and some DRM functionality on linux
if enabled qtprivateheaders ; then
cat >$TMPPRO <<EOF
QT += gui-private
EOF
qt_private_headers_incpath=`${qmakeconf} -makefile -Wnone -nocache -nomoc -nodepend -norecursive -o - $TMPPRO 2>/dev/null | sed -n -e 's/^\s*INCPATH\s*=//p'`
check_ecxx $qt_private_headers_incpath <<EOF || disable qtprivateheaders
#include <QGuiApplication>
#include <qpa/qplatformnativeinterface.h>
int x;
EOF
fi

# Check for Wayland support
enabled waylandextras && enabled qtprivateheaders || disable waylandextras
enabled waylandextras && use_pkg_config wayland_client wayland-client "wayland-client.h" wl_surface_set_opaque_region || disable waylandextras

enable enforce_wshadow
case $target_os in
    android)
        disable enforce_wshadow
        ;;
esac

# Omit Qt5 modules that aren't in Qt6.
# qtwebkit and qtscript are enabled by default.
# if either is disabled om the command line we will
# not enable it here.
if [ $qt_version -lt $(version2num "6.0.0") ]; then
    if enabled qtwebkit ; then
        if ! pkg-config --exists Qt5WebKit && ! pkg-config --exists QtWebKit ; then
            check_ecxx ${qt_inc} ${qt_inc}/QtCore <<EOF || disable qtwebkit
#include <QtWebKit/QtWebKit>
int main(void){ return 0; }
EOF
        fi
    fi

    enabled qtwebkit || warn "QtWebkit disabled."

    if enabled qtscript ; then
        if ! pkg-config --exists Qt5Script && ! pkg-config --exists QtScript ; then
            check_ecxx ${qt_inc} <<EOF || disable qtscript
#include <QtScript/QtScript>
int main(void){ return 0; }
EOF
        fi
    fi

    enabled qtscript || warn "QtScript disabled."
else
    # Disable for QT6 and above
    disable qtwebkit
    disable qtscript
fi

# Check if Qt was built with DBus support:
if ! disabled qtdbus; then
    if $(pkg-config --exists QtDBus) ; then
        enable qtdbus
    else
        check_ecxx ${qt_inc} <<EOF && enable qtdbus
#include <QtDBus/QDBusInterface>
int main(void)
{
    QDBusInterface test("org.kde.test", "/test", "org.kde.blah");
    return 0;
}
EOF
    fi
fi

if enabled firewire; then
    fwlibs=""
    check_libx fwlibs libavc1394/avc1394.h avc1394_transaction_block2 -lavc1394 && check_libx fwlibs libiec61883/iec61883.h iec61883_cmp_reconnect -liec61883 || disable firewire

    if test $target_os = darwin; then
        if [ -n "$firewiresdk_path" ] ; then
            mac_avc="$firewiresdk_path"
        else
            # This should pick the newest. e.g. FireWireSDK21 instead of 20
            # Unfortunately, the location keeps changing:
            #/Developer/FireWireSDK20/Examples/AVCVideoServices/Framework
            #/Developer/FireWireSDK21/Examples/Framework
            mac_avc=`find /Developer/FireWireSDK* -name Framework 2> /dev/null \
                    | tail -n 1`
        fi
        if test -d "$mac_avc" ; then
            firewire="yes"
        else
            echo Firewire being disabled. FireWire SDK missing
        fi
    fi
fi

# ass_flush_events was added in 0.9.10
if test $target_os = "android"; then
	ASS_EXTRA_LIBS="-liconv -lfribidi -lfreetype"
fi
enabled libass && check_lib ass ass/ass.h ass_flush_events "-lass $ASS_EXTRA_LIBS" || disable libass

if enabled libcec ; then
    if pkg-config --exists libcec; then
        libcec_path=`pkg-config --variable includedir libcec`
    else
        check_cxx -I"$libcec_path" <<EOF || { disable libcec; }
#include <libcec/cec.h>
#include <libcec/cecloader.h>
int main(void) {
    #if (CEC_LIB_VERSION_MAJOR < 2)
        #error libcec version to old
    #endif
    return 1;
}
EOF
    fi
fi

enabled libcrypto && check_lib crypto openssl/rsa.h RSA_new -lcrypto || disable libcrypto

if enabled gnutls ; then
    if ! $(pkg-config --exists gnutls) ; then
       disable gnutls
    fi
fi

if test $target_os != darwin ; then
    enabled libdns_sd && check_lib dns_sd dns_sd.h DNSServiceRegister -ldns_sd || disable libdns_sd
fi

if enabled libxml2 ; then
   if pkg-config --exists libxml-2.0 ; then
        libxml2_path=`pkg-config --cflags-only-I libxml-2.0|sed -n "s/-I\([^ ]*\) *$/\1/p"`
   else
        disable libxml2
   fi
fi
enabled libxml2 && check_cc -I"$libxml2_path" <<EOF && add_extralibs "-lxml2" || disable libxml2
#include <libxml/xmlversion.h>
int main(void) {
    #if (LIBXML_VERSION < 20600)
        #error libxml2 version to old
    #endif
    return 0;
}
EOF

if enabled taglib; then
    taglib_include=`$pkg_config --variable=prefix taglib`/include/taglib
    taglib_libs=`$pkg_config --libs taglib`
fi

enabled x11 && check_lib X11 "X11/Xdefs.h X11/Xlib.h" XQueryExtension  -lX11 || disable x11

if enabled x11; then
    require libXext "X11/Xdefs.h X11/Xlib.h X11/extensions/Xext.h" XMissingExtension -lXext
    require libXrandr "X11/Xdefs.h X11/Xlib.h X11/extensions/Xrandr.h" XRRSelectInput -lXrandr
fi

if test $target_os = darwin; then
    # So far, only OS X 10.4 has this as a non-private framework
    if test -d /System/Library/Frameworks/DiskArbitration.framework/Headers ; then
        darwin_da="yes"
    fi
fi


check_cc -mno-red-zone <<EOF && noredzone_flags="-mno-red-zone"
int x;
EOF


if enabled icc; then
    # Just warnings, no remarks
    check_cflags -w1
    # -wd: Disable following warnings
    # 144, 167, 556: -Wno-pointer-sign
    # 188: enumerated type mixed with another type
    # 1292: attribute "foo" ignored
    # 1419: external declaration in primary source file
    # 10006: ignoring unknown option -fno-signed-zeros
    # 10148: ignoring unknown option -Wno-parentheses
    # 10156: ignoring option '-W'; no argument required
    # 13200: No EMMS instruction before call to function
    # 13203: No EMMS instruction before return from function
    check_cflags -wd144,167,188,556,1292,1419,10006,10148,10156,13200,13203
    # 11030: Warning unknown option --as-needed
    # 10156: ignoring option '-export'; no argument required
    check_ldflags -wd10156,11030
    # -wd: Disable the following warnings for MythTV
    # 177: function declared but never referenced (triggers on Q_OBJECT)
    # 592: variable is used before its value is set (triggers on (void)x;)
    # 913: ignoring invalid multibyte character sequence,
    #      icpc and g++ do the right thing for char 0x80-0xFF
    # 13200: ignore EMMS instruction required, filters do the right thing
    check_cflags -wd177,592,913,13200
    # -wd: Disable the following warnings for MythTV
    # 10159: ignore invalid argument for option '-m'
    check_ldflags -wd10159
    # icc 11.0 and 11.1 work with ebp_available, but don't pass the test
    enable ebp_available
    # The test above does not test linking
    enabled lto && disable symver_asm_label
    if enabled x86_32; then
        icc_version=$($cc -dumpversion)
        test ${icc_version%%.*} -ge 11 &&
            check_cflags -falign-stack=maintain-16-byte ||
            disable aligned_stack
    fi
elif enabled ccc; then
    # disable some annoying warnings
    add_cflags -msg_disable bitnotint
    add_cflags -msg_disable mixfuncvoid
    add_cflags -msg_disable nonstandcast
    add_cflags -msg_disable unsupieee
elif enabled gcc; then
    check_optflags -fno-tree-vectorize
    check_cflags -Werror=format-security
    check_cflags -Werror=implicit-function-declaration
#    check_cflags -Werror=missing-prototypes
    check_cflags -Werror=return-type
    check_cflags -Werror=vla
    check_cflags -fdiagnostics-color=auto
    enabled extra_warnings || check_disable_warning -Wno-maybe-uninitialized
    check_cflags -Wdouble-promotion
    #check_cflags -Wduplicated-branches
    check_cflags -Wduplicated-cond
    check_cflags -Wjump-misses-init
    check_cflags -Wlogical-op
    check_cflags -Wnull-dereference
    if enabled enforce_wshadow ; then
        check_cflags -Wshadow
    fi
elif enabled llvm_gcc; then
    check_cflags -mllvm -mstack-alignment=16
elif enabled clang; then
    check_cflags -mllvm -mstack-alignment=16
    check_cflags -mstack-alignment=16
    check_cflags -Qunused-arguments
    check_cflags -Werror=implicit-function-declaration
#   check_cflags -Werror=missing-prototypes
    check_cflags -Werror=return-type
elif enabled cparser; then
    add_cflags -Wno-missing-variable-declarations
    add_cflags -Wno-empty-statement
elif enabled armcc; then
    add_cflags -W${armcc_opt},--diag_suppress=4343 # hardfp compat
    add_cflags -W${armcc_opt},--diag_suppress=3036 # using . as system include dir
    # 2523: use of inline assembly is deprecated
    add_cflags -W${armcc_opt},--diag_suppress=2523
    add_cflags -W${armcc_opt},--diag_suppress=1207
    add_cflags -W${armcc_opt},--diag_suppress=1293 # assignment in condition
    add_cflags -W${armcc_opt},--diag_suppress=3343 # hardfp compat
    add_cflags -W${armcc_opt},--diag_suppress=167  # pointer sign
    add_cflags -W${armcc_opt},--diag_suppress=513  # pointer sign
elif enabled tms470; then
    add_cflags -pds=824 -pds=837
    disable inline_asm
elif enabled pathscale; then
    add_cflags -fstrict-overflow -OPT:wrap_around_unsafe_opt=OFF
elif enabled_any msvc icl; then
    enabled x86_32 && disable aligned_stack
    enabled_all x86_32 debug && add_cflags -Oy-
    enabled debug && add_ldflags -debug
    enable pragma_deprecated
    if enabled icl; then
        # -Qansi-alias is basically -fstrict-aliasing, but does not work
        # (correctly) on icl 13.x.
        check_cpp_condition "windows.h" "__ICL < 1300 || __ICL >= 1400" &&
            add_cflags -Qansi-alias
        # Some inline asm is not compilable in debug
        if enabled debug; then
            disable ebp_available
            disable ebx_available
        fi
    fi
    # msvcrt10 x64 incorrectly enables log2, only msvcrt12 (MSVC 2013) onwards actually has log2.
    check_cpp_condition crtversion.h "_VC_CRT_MAJOR_VERSION >= 12" || disable log2
    # The CRT headers contain __declspec(restrict) in a few places, but if redefining
    # restrict, this might break. MSVC 2010 and 2012 fail with __declspec(__restrict)
    # (as it ends up if the restrict redefine is done before including stdlib.h), while
    # MSVC 2013 and newer can handle it fine.
    # If this declspec fails, force including stdlib.h before the restrict redefinition
    # happens in config.h.
    if [ $_restrict != restrict ]; then
        check_cc <<EOF || add_cflags -FIstdlib.h
__declspec($_restrict) void* foo(int);
EOF
    fi
    # the new SSA optimzer in VS2015 U3 is mis-optimizing some parts of the code
    # Issue has been fixed in MSVC v19.00.24218.
    check_cpp_condition windows.h "_MSC_FULL_VER >= 190024218" ||
        check_cflags -d2SSAOptimizer-
    # enable utf-8 source processing on VS2015 U2 and newer
    check_cpp_condition windows.h "_MSC_FULL_VER >= 190023918" &&
        add_cflags -utf-8
fi

for pfx in "" host_; do
    varname=${pfx%_}cc_type
    eval "type=\$$varname"
    if [ "$type" = "msvc" ]; then
        check_${pfx}cc <<EOF || add_${pfx}cflags -Dinline=__inline
static inline int foo(int a) { return a; }
EOF
    fi
done

case $as_type in
    clang)
        add_asflags -Qunused-arguments
    ;;
esac

case $ld_type in
    clang)
        check_ldflags -Qunused-arguments
    ;;
esac

if enabled gxx; then
    if enabled symbol_visibility; then
        check_cxxflags -fvisibility-inlines-hidden
        append CCONFIG "use_hidesyms"
    fi
    check_cxxflags -Wdouble-promotion
    #check_cxxflags -Wduplicated-branches
    check_cxxflags -Wduplicated-cond
    check_cxxflags -Wlogical-op
    check_cxxflags -Wmissing-declarations
    check_cxxflags -Wnull-dereference
    check_cxxflags -Woverloaded-virtual
    if enabled enforce_wshadow ; then
        check_cxxflags -Wshadow
    fi

    # This warning flag isn't enabled yet because it will require a
    # large number of changes to the code to eliminate all the
    # warnings.
    #check_cxxflags -Wold-style-cast

    # This warning flag can't be enabled because the Qt5 moc compiler
    # produces files that contain "useless" casts.
    #check_cxxflags -Wuseless-cast

    check_cxxflags -funit-at-a-time
    # Don't complain about over-aligned types
    check_cxxflags -faligned-new
    if enabled enforce_nullptr; then
        check_cxxflags -Wzero-as-null-pointer-constant
    fi
    # The Q_OBJECT macro gets included in every subclass that is based
    # on QOBject, and has a couple of functions marked as "virtual"
    # instead of "override". Apparently earlier version of GCC didn't
    # warn about this because the errors were in the /usr/include
    # directory. GCC11 does print these warnings. A ton of
    # them. Disable this warning to make it easier to find real
    # errors.
    if [ $qt_version -ge $(version2num "11.0.0") ]; then
        check_cxxflags -Wsuggest-override
    fi
elif enabled icpc; then
    # 177: function declared but never referenced (triggers on Q_OBJECT)
    # 192: icpc confused by Qt %0-%99 in strings
    # 592: variable is used before its value is set (triggers on (void)x;)
    # 913: ignoring invalid multibyte character sequence,
    #      icpc and g++ do the right thing for char 0x80-0xFF
    # 10181: ignore warning about -fomit-frame-pointer being ignored
    # 13200: ignore EMMS instruction required, RTjpegN.cpp does the right thing
    check_cxxflags -wd177,192,592,913,10181,13200
elif enabled clangxx; then
    # The constant-logical-operand only gives use false positives
    # for constant logical operands meant to be optimized away.
    check_cxxflags -Wno-constant-logical-operand
    # Unfortunately clang's unused-value warning is smart enough to notice
    # that ZMQ_ASSERT expressions don't use the values unless it is a debug
    # build. So lets rely on other compilers to report on unused values.
    check_cxxflags -Wno-unused-value
    # clang complains about every unused -I unless you pass it this.
    check_cxxflags -Qunused-arguments
    # Flag implicit fallthrough in case statements
    check_cxxflags -Wimplicit-fallthrough
    # Clang needs this to link on Fedora
    if [ $target_os != "android" ] ; then
        add_extralibs -lstdc++
    fi
    # Don't complain about over-aligned types.
    case $target_os in
        freebsd)
            # The libc++ library on FreeBSD 10 is missing the required
            # new() function and doesn't work with this flag enabled.
            if test $(uname -K) -gt 1100000; then
                check_cxxflags -faligned-allocation
            fi
            ;;
        darwin)
            # OSX compiles aren't happy with aligned allocation.
            ;;
        *)
            check_cxxflags -faligned-allocation
            ;;
    esac
    if enabled enforce_nullptr; then
        check_cxxflags -Wzero-as-null-pointer-constant
    fi
fi

# Check for python dependencies
if enabled bindings_python; then
    check_python "(3,8,0)"     || disable_bindings_python "Python 3.8 or greater"
    check_py_lib MySQLdb       || disable_bindings_python "MySQLdb"
    check_py_lib lxml          || disable_bindings_python "lxml"
    check_py_lib requests      || disable_bindings_python "requests"
    check_python "(3,11,1)" && check_py_lib wheel && check_py_lib_version pip "(23,0,1)" && USE_PYTHON_PIP="yes"
    test x"$USE_PYTHON_PIP" = x"" && check_python "(3,12,0)" && disable_bindings_python "pip, wheel"
fi

# Check for perl dependencies
# Modules distributed in Perl core
if enabled bindings_perl; then
    check_pl_lib "ExtUtils::MakeMaker" ||
        disable_bindings_perl "ExtUtils::MakeMaker"
    check_pl_lib Config           || disable_bindings_perl Config
    check_pl_lib Exporter         || disable_bindings_perl Exporter
    check_pl_lib Fcntl            || disable_bindings_perl Fcntl
    check_pl_lib "File::Copy"     || disable_bindings_perl "File::Copy"
    check_pl_lib "Sys::Hostname"  || disable_bindings_perl "Sys::Hostname"
# Modules not distributed in Perl core
    check_pl_lib DBI              || disable_bindings_perl DBI
    check_pl_lib "DBD::mysql"     || disable_bindings_perl "DBD::mysql"
    check_pl_lib "HTTP::Request"  || disable_bindings_perl "HTTP::Request"
    check_pl_lib "LWP::UserAgent" || disable_bindings_perl "LWP::UserAgent"
    check_pl_lib "Net::UPnP::QueryResponse" ||
        disable_bindings_perl "Net::UPnP::QueryResponse"
    check_pl_lib "Net::UPnP::ControlPoint"  ||
        disable_bindings_perl "Net::UPnP::ControlPoint"
    check_pl_lib "IO::Socket::INET6"  ||
        disable_bindings_perl "IO::Socket::INET6"
    check_pl_lib "XML::Simple"  || disable_bindings_perl "XML::Simple"
fi

# Check for php dependencies
# none at this time

# nvdec processing
here="$PWD"
cd external/nv-codec-headers
if enabled nvdec ; then
    if test $target_os = "freebsd"; then
        gmake install PREFIX=$PWD/install
    else
        make install PREFIX=$PWD/install
    fi
    if [ "$?" != 0 ] ; then die "Build of nv-codec-headers failed." ; fi
    PKG_CONFIG_PATH="$PKG_CONFIG_PATH:$PWD/install/lib/pkgconfig"
    export PKG_CONFIG_PATH
else
    rm -rf install ffnvcodec.pc
fi
cd "$here"

case $target_os in
    osf1)
        enabled ccc && add_ldflags '-Wl,-expect_unresolved,*'
    ;;
esac

enable frame_thread_encoder

enabled asm || { arch=c; disable $ARCH_LIST $ARCH_EXT_LIST; }

check_deps $CONFIG_LIST       \
           $CONFIG_EXTRA      \
           $HAVE_LIST         \
           $MYTHTV_LIST       \
           $MYTHTV_CONFIG_LIST \
           $MYTHTV_HAVE_LIST  \
           $USING_LIST        \

enabled threads && ! enabled pthreads && ! enabled atomics_native && die "non pthread threading without atomics not supported, try adding --enable-pthreads or --cpu=i486 or higher if you are on x86"

# add_dep lib dep
# -> enable ${lib}_deps_${dep}
# -> add $dep to ${lib}_deps only once
add_dep() {
    lib=$1
    dep=$2
    enabled "${lib}_deps_${dep}" && return 0
    enable  "${lib}_deps_${dep}"
    prepend "${lib}_deps" $dep
}

# merge deps lib components
# merge all ${component}_deps into ${lib}_deps and ${lib}_deps_*
merge_deps() {
    lib=$1
    shift
    for comp in $*; do
        enabled $comp || continue
        eval "dep=\"\$${comp}_deps\""
        for d in $dep; do
            add_dep $lib $d
        done
    done
}

map 'enabled $v && intrinsics=${v#intrinsics_}' $INTRINSICS_LIST

for thread in $THREADS_LIST; do
    if enabled $thread; then
        test -n "$thread_type" &&
            die "ERROR: Only one thread type must be selected." ||
            thread_type="$thread"
    fi
done

# Check if requested libraries were found.
for lib in $AUTODETECT_LIBS; do
    requested $lib && ! enabled $lib && die "ERROR: $lib requested but not found";
done

enabled zlib && add_cppflags -DZLIB_CONST

if enabled x86 && (disabled mmx && ! enabled disable_mmx_for_debugging); then
    die "ERROR: MMX disabled on x86, MythTV will be very slow.\n\tDisable this check with --enable-disable-mmx-for-debugging"
fi

enabled asm || { arch=c; disable $ARCH_LIST $ARCH_EXT_LIST; }

license="LGPL version 2.1 or later"
if enabled nonfree; then
    license="nonfree and unredistributable"
elif enabled gplv3; then
    license="GPL version 3 or later"
elif enabled lgplv3; then
    license="LGPL version 3 or later"
elif enabled gpl; then
    license="GPL version 2 or later"
fi

# Set up FFmpeg configure options that are derived from
# MythTV configure options

ffmpeg_optset() {
    while test -n "$1" ; do
        val=$(eval "echo \$$1")
        if test -n "$val" ; then
            ffopts="$ffopts '--$1=$(echo "$val")'"
        fi
        shift
    done
}

ffmpeg_optenable() {
    while test -n "$1" ; do
        val=$(eval "echo \$$1")
        if enabled "$1" ; then
            ffopts="$ffopts --enable-"$(echo "$1" | sed 's/_/-/g')
        else
            ffopts="$ffopts --disable-"$(echo "$1" | sed 's/_/-/g')
        fi
        shift
    done
}

ffmpeg_optenableif() {
    while test -n "$1" ; do
        val=$(eval "echo \$$1")
        if enabled "$1" ; then
            ffopts="$ffopts --enable-"$(echo "$1" | sed 's/_/-/g')
        fi
        shift
    done
}

ffopts=
ffmpeg_optset arch cross_prefix sysroot sysinclude cc cxx ld cpu
ffmpeg_optset extra_cxxflags extra_ldflags target_os
ffmpeg_optset pkg_config prefix libdir as objcc dep_cc host_cc
ffmpeg_optset host_ld
ffmpeg_optset ar nm ranlib
ffmpeg_optenable cross_compile libmp3lame libx264 libx265 libvpx libxvid
ffmpeg_optenable vdpau libxml2 libass dxva2
ffmpeg_optenable libbluray libfontconfig libfreetype libiec61883
ffmpeg_optenable sdl2 ffplay

if test $target_os = "android"; then
    enabled mediacodec && enable jni
    ffmpeg_optenable mediacodec jni
    # udp is causing compile errors on android and it is not needed
    ffopts="$ffopts --disable-protocol=udp --disable-protocol=udplite"
else
    disable mediacodec
fi

ffmpeg_optenableif vaapi mmal libaom libdav1d gnutls lto

if enabled drm; then
    ffopts="$ffopts --enable-libdrm"
fi


if test "$ID" = "raspbian"; then
    case $cpu in
        armv*) ffmpeg_extra_ldflags="$ffmpeg_extra_libs -latomic" ;;
    esac
fi

# FFmpeg on FreeBSD build breaks with clang >= 16. This is because the
# incompatible function pointer waring has been promoted to an error.
# Demoting it back to a warning allows the builds to work again.
# https://lists.ffmpeg.org/pipermail/ffmpeg-devel/2023-March/307515.html
if test $target_os = "freebsd" &&
	enabled clangxx &&
	test $clangxx_major -ge 16; then
   ffmpeg_extra_cflags="$ffmpeg_extra_cflags -Wno-error=incompatible-function-pointer-types"
fi

append ffopts \
--extra-cflags=\'"$ffmpeg_extra_cflags"\' \
--extra-ldflags=\'"$ffmpeg_extra_ldflags"\' \
--extra-libs=\'"$ffmpeg_extra_ldflags"\' \
--disable-stripping \
--disable-manpages  \
--disable-podpages  \
--disable-doc \
--disable-nvenc \
--enable-shared \
--disable-static \
--enable-gpl \
--enable-pic \
--disable-demuxer=mpegtsraw \
--disable-indev=dshow
echo
echo "ffopts = $ffopts"
## Call FFmpeg configure here
echo
echo '#### FFmpeg CONFIGURATION ####'
currentpwd="$PWD"
cd external/FFmpeg
eval ./configure $ffopts
rc=$?
if [ $rc != 0 ] ; then
    echo "ERROR FFmpeg configure failed"
    exit $rc
fi
cd "$currentpwd"

# If ffmpeg disabled nvdec then disable it for mythtv
if ! grep "^CONFIG_NVDEC=yes$" external/FFmpeg/ffbuild/config.mak ; then
    disable nvdec
fi

# If ffmpeg disabled videotoolbox then disable it
if test x"$target_os" = x"darwin" ; then
    if ! grep "^CONFIG_VIDEOTOOLBOX=yes$" external/FFmpeg/ffbuild/config.mak ; then
        disable videotoolbox
    fi
fi

if test "$quiet" != "yes"; then

echo
echo '#### MythTV CONFIGURATION ####'
echo "# Basic Settings"
echo "Qt minimum version        $QT_MIN_VERSION_STR"
echo "Qt installed version      `$qmake -query QT_VERSION`"
echo "Compile type              $compile_type"
echo "Compiler cache            $ccache$ccache_txt"
echo "DistCC                    $distcc$distcc_txt"
echo "qmake                     $(which $qmake)"
echo "install prefix            $prefix"
echo "runtime prefix            $runprefix"
echo
if enabled cpu_override && test x"$cpu" != x"generic"; then
    echo "CPU override              $arch $subarch ($cpu)"
elif test x"$processor" != x"" ; then
    echo "CPU                       $arch $subarch ($processor)"
else
    echo "CPU                       $arch $subarch"
fi

if enabled x86; then
    echo "standalone assembly       ${x86asm-no}"
    echo "x86 assembler             ${x86asmexe}"
    echo "MMX enabled               ${mmx-no}"
    echo "MMXEXT enabled            ${mmxext-no}"
    echo "3DNow! enabled            ${amd3dnow-no}"
    echo "3DNow! extended enabled   ${amd3dnowext-no}"
    echo "SSE enabled               ${sse-no}"
    echo "SSSE3 enabled             ${ssse3-no}"
    echo "AESNI enabled             ${aesni-no}"
    echo "AVX enabled               ${avx-no}"
    echo "AVX2 enabled              ${avx2-no}"
    echo "XOP enabled               ${xop-no}"
    echo "FMA3 enabled              ${fma3-no}"
    echo "FMA4 enabled              ${fma4-no}"
    echo "i686 features enabled     ${i686-no}"

fi
if enabled aarch64; then
    echo "NEON enabled              ${neon-no} (Intrinsics ${intrinsics_neon-no})"
    echo "VFP enabled               ${vfp-no}"
fi
if enabled arm; then
    echo "ARMv5TE enabled           ${armv5te-no}"
    echo "ARMv6 enabled             ${armv6-no}"
    echo "ARMv6T2 enabled           ${armv6t2-no}"
    echo "VFP enabled               ${vfp-no}"
    echo "NEON enabled              ${neon-no} (Intrinsics ${intrinsics_neon-no})"
    echo "THUMB enabled             ${thumb-no}"
fi
if enabled mips; then
    echo "MIPS FPU enabled          ${mipsfpu-no}"
    echo "MIPS DSP R1 enabled       ${mipsdsp-no}"
    echo "MIPS DSP R2 enabled       ${mipsdspr2-no}"
    echo "MIPS MSA enabled          ${msa-no}"
    echo "LOONGSON MMI enabled      ${mmi-no}"
fi
if enabled ppc; then
    echo "AltiVec enabled           ${altivec-no}"
    echo "VSX enabled               ${vsx-no}"
    echo "POWER8 enabled            ${power8-no}"
    echo "PPC 4xx optimizations     ${ppc4xx-no}"
    echo "dcbzl available           ${dcbzl-no}"
fi
echo
echo "Creating configuration files ..."

fi # test "$quiet" != "yes"

echo
if enabled frontend; then
  echo "# Input Support"
  echo "Joystick menu             ${joystick_menu-no}"
  echo "lirc support              ${lirc-no}"
  echo "libCEC device support     ${libcec-no} [$libcec_path]"
  if test x"$target_os" = x"darwin" ; then
    echo "Apple Remote              ${appleremote-no}"
  fi
fi

#ignore
# build tree in object directory if source path is different from current one
if enabled source_path_used; then
    DIRS="
        doc
        libavcodec
        libavcodec/$arch
        libavdevice
        libavfilter
        libavformat
        libavutil
        libavutil/$arch
        libpostproc
        libswscale
        libswscale/$arch
        tests
        tools
        external/libmythbluray
        external/libmythdvdnav
        external/libudfread
    "
    FILES="
        Makefile
        common.mak
        subdir.mak
        doc/texi2pod.pl
        libavcodec/Makefile
        libavcodec/${arch}/Makefile
        libavdevice/Makefile
        libavfilter/Makefile
        libavformat/Makefile
        libavutil/Makefile
        libpostproc/Makefile
        libswscale/Makefile
        external/libmythbluray/Makefile
        external/libmythdvdnav/Makefile
        external/libudfread/Makefile
    "
    map 'mkdir -p $v' $DIRS;
    map 'test -f "$source_path/$v" && $ln_s "$source_path/$v" $v' $FILES
fi

config_files="$TMPH $TMPMAK"

if enabled backend; then
  echo "Video4Linux support       ${v4l2-no}"
  echo "FireWire support          ${firewire-no}"
  echo "DVB support               ${dvb-no} [$dvb_path]"
  echo "DVB-S2 support            ${fe_can_2g_modulation-no}"
  echo "HDHomeRun support         ${hdhomerun-no}"
  echo "Sat>IP support            ${satip-no}"
  echo "V@Box TV Gateway support  ${vbox-no}"
  echo "Ceton support             ${ceton-no}"
  echo "DVEO ASI support          ${asi-no}"
  echo
fi

if enabled frontend; then
  echo "# Sound Output Support"
  echo "PulseAudio support        ${audio_pulseoutput-no}"
  echo "OSS support               ${audio_oss-no}"
  echo "ALSA support              ${audio_alsa-no}"
  echo "JACK support              ${audio_jack-no}"
  if test x"$target_os" = x"mingw32" ; then
    echo "Windows (Windows audio)   yes"
    echo "Windows (DirectX)         yes"
  fi
  echo
  echo "# Video Output Support"
  echo "x11/xrandr support        ${x11-no}"
  if enabled x11 ; then
    echo "VDPAU support             ${vdpau-no}"
    echo "NVDEC support             ${nvdec-no}"
  fi
  if test x"$target_os" = x"darwin" ; then
    echo "VideoToolBox support      ${videotoolbox-no}"
  fi
  echo "VAAPI support             ${vaapi-no}"
  echo "DRM support               ${drm-no}"
  if enabled drm; then
    echo "DRM Qt integration        ${qtprivateheaders-no}"
  fi
  echo "Video4Linux codecs        ${v4l2-no} (DRM ${v4l2prime-no})"
  echo "MMAL decoder support      ${mmal-no}"
  echo "OpenGL                    ${opengl-no} (OpenGLES ${opengles-no})"
  echo "EGL support               ${egl-no}"
  if test x"$target_os" = x"mingw32" ; then
    echo "Windows (Direct3D)        yes"
    echo "DXVA2 support             ${dxva2-no}"
  fi
  echo "Vulkan                    ${vulkan-no} (libglslang ${libglslang-no})"
  echo "MHEG support              ${mheg}"
  echo "libass subtitle support   ${libass-no}"
  echo
fi

echo "# Misc Features"
echo "Frontend                  ${frontend-no}"
echo "Backend                   ${backend-no}"
echo "Qt private headers        ${qtprivateheaders-no}"
echo "Wayland extras            ${waylandextras-no}"
echo "multi threaded libavcodec ${threads-no}"
if enabled frontend; then
  echo "libxml2 support           ${libxml2-no} [$libxml2_path]"
fi
echo "libdns_sd (Bonjour)       ${libdns_sd-no}"
echo "libcrypto                 ${libcrypto-no}"
echo "gnutls                    ${gnutls-no}"
if enabled system_libexiv2; then
    echo "exiv2 support             yes (system)"
else
    echo "exiv2 support             yes (internal)"
fi
if enabled system_libudfread; then
    echo "udfread support           yes (system)"
else
    echo "udfread support           yes (internal)"
fi
if enabled system_libbluray; then
    echo "bluray support            yes (system)"
else
    echo "bluray support            yes (internal)"
    echo "BD-J (Bluray java)        ${bdjava-no}"
    echo "BD-J type                 ${bdj_type}"
fi
echo "systemd_notify            ${systemd_notify-no}"
echo "systemd_journal           ${systemd_journal-no}"
echo

echo "# Bindings"
echo "bindings_perl             ${bindings_perl-no}"
if test x"$PERL_CONFIG_OPTS" != x""; then
  echo "Perl config options       $PERL_CONFIG_OPTS"
fi
echo "bindings_python           ${bindings_python-no}"
echo "bindings_php              ${bindings_php-no}"
echo ""

echo "# External Codec Options"
echo "mp3lame                   ${libmp3lame-no}"
echo "xvid                      ${libxvid-no}"
echo "x264                      ${libx264-no}"
echo "x265 (HEVC)               ${libx265-no}"
echo "vpx                       ${libvpx-no}"
echo "libaom   (AV1)            ${libaom-no}"
echo "libdav1d (AV1)            ${libdav1d-no}"
echo ""

echo "# Compilation Options"
echo "C++ standard supported    ${CPP_STANDARD}"
echo "Enforce c++11 nullptr     ${enforce_nullptr-no}"
echo "Enforce shadowed vars     ${enforce_wshadow-no}"
echo ""

# Remove redundant elements from variables
# keep first instance
unique2 CFLAGS
# keep last instance for correct lib ordering
unique extralibs

if test $target_os = "freebsd"; then
    #Strip certain paths (qmake will add them back at the end of the list)
    LDFLAGS=`echo $LDFLAGS | sed -e 's/-L\/usr\/local\/lib$//'     -e 's/-L\/usr\/local\/lib / /'`
    CFLAGS=`echo $CFLAGS   | sed -e 's/-I\/usr\/local\/include$//' -e 's/-I\/usr\/local\/include / /'`
fi

MYTH_CONFIG_H=libs/libmythbase/mythconfig.h
MYTH_CONFIG_MAK=libs/libmythbase/mythconfig.mak
echo "Creating $MYTH_CONFIG_H and $MYTH_CONFIG_MAK"

date >> config.log
echo "   $0 $MYTHTV_CONFIGURATION" >> config.log

cat > $TMPMAK <<EOF
# Automatically generated by configure - do not modify!
MYTHTV_VERSION_MAJMIN=$MYTHTV_VERSION_MAJMIN
MYTHTV_LIBVERSION=$MYTHTV_LIBVERSION
QT_MIN_VERSION_STR=$QT_MIN_VERSION_STR
QT_MIN_VERSION_HEX=$QT_MIN_VERSION_HEX
QT_MIN_VERSION=$QT_MIN_VERSION
MYTHTV_CONFIGURATION=$MYTHTV_CONFIGURATION
MYTHTV_CONFIG_MAK=1
COMPILE_TYPE=$compile_type
PREFIX=$prefix
prefix=$prefix
LIBDIRNAME=$libdir_name
LIBDIR=$libdir
SHLIBDIR=$shlibdir
INCDIR=$incdir
BINDIR=$bindir
DATADIR=$datadir
MANDIR=$mandir
PKGCONFIGDIR=\$(DESTDIR)$pkgconfigdir
SRC_PATH="$source_path"
SRC_LINK=$source_link
SRC_PATH_BARE=$source_path
BUILD_ROOT="$PWD"
CC_IDENT=$cc_ident
ARCH=$arch
INTRINSICS=$intrinsics
CC=$cc
CXX=$cxx
AS=$as
OBJCC=$objcc
QMAKE=$qmakeconf
QMAKE_CC=$cc
QMAKE_CXX=$cxx
QMAKE_LINK=$cxx
PYTHON=$python
LD=$ld
DEPCC=$dep_cc
DEPCCFLAGS=$DEPCCFLAGS \$(CPPFLAGS)
DEPAS=$as
DEPASFLAGS=$DEPASFLAGS \$(CPPFLAGS)
X86ASM=$x86asmexe
DEPX86ASM=$x86asmexe
DEPX86ASMFLAGS=\$(X86ASMFLAGS)
AR=$ar
ARFLAGS=$arflags
AR_O=$ar_o
QMAKE_AR=$ar $arflags
RANLIB=$ranlib
QMAKE_RANLIB=$ranlib
NVCC=$nvcc
CP=cp -p
LN_S=$ln_s
CPPFLAGS=$CPPFLAGS
CFLAGS=$CFLAGS
CXXFLAGS=$CXXFLAGS
OBJCFLAGS=$OBJCFLAGS
ASFLAGS=$ASFLAGS
NVCCFLAGS=$nvccflags
AS_C=$AS_C
AS_O=$AS_O
OBJCC_C=$OBJCC_C
OBJCC_E=$OBJCC_E
OBJCC_O=$OBJCC_O
CC_C=$CC_C
CC_E=$CC_E
CC_O=$CC_O
CXX_C=$CXX_C
CXX_O=$CXX_O
NVCC_C=$NVCC_C
NVCC_O=$NVCC_O
LD_O=$LD_O
X86ASM_O=$X86ASM_O
LD_LIB=$LD_LIB
LD_MYTH_LIB=$LD_MYTH_LIB
LD_PATH=$LD_PATH
DLLTOOL=$dlltool
WINDRES=$windres
DEPWINDRES=$dep_cc
CXXPPFLAGS=$CXXPPFLAGS
ECXXFLAGS=$ECXXFLAGS
DOXYGEN=$doxygen
LDFLAGS=$LDFLAGS
LDEXEFLAGS=$LDEXEFLAGS
LDLIBFLAGS=$LDLIBFLAGS
X86ASMFLAGS=$X86ASMFLAGS
BUILDSUF=$build_suffix
PROGSSUF=$progs_suffix
FULLNAME=$FULLNAME
LIBPREF=$LIBPREF
LIBSUF=$LIBSUF
LIBNAME=$LIBNAME
SLIBPREF=$SLIBPREF
SLIBSUF=$SLIBSUF
EXESUF=$EXESUF
EXTRA_VERSION=$extra_version
CCDEP=$CCDEP
CXXDEP=$CXXDEP
CCDEP_FLAGS=$CCDEP_FLAGS
ASDEP=$ASDEP
ASDEP_FLAGS=$ASDEP_FLAGS
X86ASMDEP=$X86ASMDEP
X86ASMDEP_FLAGS=$X86ASMDEP_FLAGS
CC_DEPFLAGS=$CC_DEPFLAGS
AS_DEPFLAGS=$AS_DEPFLAGS
X86ASM_DEPFLAGS=$X86ASM_DEPFLAGS
HOSTCC=$host_cc
HOSTLD=$host_ld
HOSTCFLAGS=$host_cflags
HOSTCPPFLAGS=$host_cppflags
HOSTEXESUF=$HOSTEXESUF
HOSTLDFLAGS=$host_ldflags
HOSTEXTRALIBS=$host_extralibs
DEPHOSTCC=$host_cc
DEPHOSTCCFLAGS=$DEPHOSTCCFLAGS \$(HOSTCCFLAGS)
HOSTCCDEP=$HOSTCCDEP
HOSTCCDEP_FLAGS=$HOSTCCDEP_FLAGS
HOSTCC_DEPFLAGS=$HOSTCC_DEPFLAGS
HOSTCC_C=$HOSTCC_C
HOSTCC_O=$HOSTCC_O
HOSTLD_O=$HOSTLD_O
TARGET_EXEC=$target_exec $target_exec_args
TARGET_PATH=$target_path
TARGET_SAMPLES=${target_samples:-\$(SAMPLES)}
CFLAGS_HEADERS=$CFLAGS_HEADERS
ZLIB=$($ldflags_filter -lz)
EXTRALIBS=$extralibs $ldl
COMPAT_OBJS=$compat_objs
INSTALL=$install
LIBTARGET=${LIBTARGET}
SLIBNAME=${SLIBNAME}
SLIBNAME_WITH_VERSION=${SLIBNAME_WITH_VERSION}
SLIBNAME_WITH_MAJOR=${SLIBNAME_WITH_MAJOR}
SLIBNAME_QT=$(echo ${SLIBNAME} | sed 's/\$(\(\(FULL\)*NAME\))/\1/;s/\$(\([A-Z]*\))/$${\1}/g')
SLIBNAME_WITH_MAJOR_QT=$(echo ${SLIBNAME_WITH_MAJOR} | sed 's/\$(\(\(FULL\)*NAME\))/\1/;s/\$(\(LIBMAJOR\))/\1/;s/\$(\(SLIBNAME\))/$${\1_QT}/;s/\$(\([A-Z]*\))/$${\1}/g')
SLIB_INSTALL_NAME=${SLIB_INSTALL_NAME}
SLIB_INSTALL_LINKS=${SLIB_INSTALL_LINKS}
SLIB_INSTALL_EXTRA_LIB=${SLIB_INSTALL_EXTRA_LIB}
SLIB_INSTALL_EXTRA_SHLIB=${SLIB_INSTALL_EXTRA_SHLIB}
VERSION_SCRIPT_POSTPROCESS_CMD=${VERSION_SCRIPT_POSTPROCESS_CMD}
SAMPLES=$samples
NOREDZONE_FLAGS=$noredzone_flags
LIBFUZZER_PATH=$libfuzzer_path
IGNORE_TESTS=$ignore_tests
ANTBIN=$antbin
BDJ_TYPE=$bdj_type
JDK_HOME=$JDK_HOME
JAVA_ARCH=$java_arch
JAVA_CODE_VERSION=$java_code_version
EOF

# Parse the FFmpeg version headers for linking to the correct shared object file
get_version(){
    lcname=lib${1}
    name=$(toupper $lcname)
    # FFmpeg split its version.h into version_major.h and version.h.
    # Of note, libavutil's version_major.h is empty, so we need to parse both
    # version.h AND version_major.h regardless of whether or not we only need
    # the major version number.
    # So, to keep the prior behavior of parsing the entire version number,
    # pass both files to awk, which will test each file line by line.
    file=$source_path/external/FFmpeg/$lcname/version.h
    file_major=$source_path/external/FFmpeg/$lcname/version_major.h
    eval $(awk "/#define ${name}_VERSION_M/ { print \$2 \"=\" \$3 }" "$file_major" "$file")
    enabled raise_major && eval ${name}_VERSION_MAJOR=$((${name}_VERSION_MAJOR+100))
    eval ${name}_VERSION=\$${name}_VERSION_MAJOR.\$${name}_VERSION_MINOR.\$${name}_VERSION_MICRO
    eval echo "${lcname}_VERSION=\$${name}_VERSION" >> $TMPMAK
    eval echo "${lcname}_VERSION_MAJOR=\$${name}_VERSION_MAJOR" >> $TMPMAK
    eval echo "${lcname}_VERSION_MINOR=\$${name}_VERSION_MINOR" >> $TMPMAK
}

map 'get_version $v' $LIBRARY_LIST

echo "RUNPREFIX=$runprefix" >> $TMPMAK
echo "SYSROOT=$sysroot" >> $TMPMAK

enabled audio_alsa        && append CCONFIG "using_alsa"
enabled audio_jack        && append CCONFIG "using_jack"
enabled audio_oss         && append CCONFIG "using_oss"
enabled audio_pulse       && append CCONFIG "using_pulse"
enabled audio_pulseoutput && append CCONFIG "using_pulseoutput"

if enabled darwin_da; then
  append CCONFIG "darwin_da"
  echo "SLIB_UNINSTALL_EXTRA_CMD=${SLIB_UNINSTALL_EXTRA_CMD}" >> $TMPMAK
fi

if enabled freetype2; then
    if test $target_os = "freebsd"; then
        echo "FREETYPE_CFLAGS=$($pkg_config --cflags $pkg_config_flags freetype2 | sed -E -e 's#-I/usr/local/include ##g' -e 's#-I/usr/local/include$##g')" >> $TMPMAK
    else
        echo "FREETYPE_CFLAGS=$($pkg_config --cflags $pkg_config_flags freetype2)" >> $TMPMAK
    fi
    echo "FREETYPE_LIBS=$($pkg_config --libs $pkg_config_flags freetype2)" >> $TMPMAK
fi

if enabled drm; then
    echo "LIBDRM_CFLAGS=$($pkg_config --cflags $pkg_config_flags libdrm)" >> $TMPMAK
fi

if enabled waylandextras; then
    echo "LIBWAYLAND_CFLAGS=$($pkg_config --cflags $pkg_config_flags wayland-client)" >> $TMPMAK
fi

if enabled system_libudfread; then
    # from check_pkg_config via use_pkg_config above
    echo "LIBUDFREAD_CFLAGS=$libudfread_cflags" >> $TMPMAK
    echo "LIBUDFREAD_LIBS=$libudfread_extralibs" >> $TMPMAK
fi

if test $target_os = darwin; then
  # Qt, by default builds .app bundles everywhere. Prevent this.
  enabled mac_bundle || echo "CONFIG-=app_bundle" >> $TMPMAK
fi

cat > $TMPH <<EOF
/* Automatically generated by configure - do not modify! */
#ifndef MYTHTV_CONFIG_H
#define MYTHTV_CONFIG_H

/* NOLINTBEGIN(cppcoreguidelines-macro-usage,modernize-macro-to-enum) */

#define QT_MIN_VERSION_STR "$QT_MIN_VERSION_STR"
#define QT_MIN_VERSION_HEX $QT_MIN_VERSION_HEX
#define QT_MIN_VERSION $QT_MIN_VERSION
#define COMPILE_TYPE "$compile_type"
#define av_restrict $_restrict
#define EXTERN_PREFIX "${extern_prefix}"
#define EXTERN_ASM ${extern_prefix}
#define BUILDSUF "$build_suffix"
#define SLIBSUF "$SLIBSUF"
#define HAVE_MMX2 HAVE_MMXEXT
#define JDK_HOME "$JDK_HOME"
#define JAVA_ARCH "$java_arch"
#define IMAGE_ALIGN $image_align
#define PYTHON_EXE "${python}"
EOF

test -n "$assert_level" &&
    echo "#define ASSERT_LEVEL $assert_level" >>$TMPH

if enabled cygwin ; then
  echo "#ifndef llrint" >> $TMPH
  echo "#define llrint llrint  // make sure not to define twice" >> $TMPH
  echo "static inline long long int llrint (double x)" >> $TMPH
  echo "{" >> $TMPH
  echo "    long long int llrintres;" >> $TMPH
  echo "    asm" >> $TMPH
  echo "    (\"fistpll %0\"" >> $TMPH
  echo "    : \"=m\" (llrintres) : \"t\" (x) : \"st\");" >> $TMPH
  echo "    return llrintres;" >> $TMPH
  echo "}" >> $TMPH
  echo "#endif" >> $TMPH
fi

print_config ARCH_   "$config_files" $ARCH_LIST
print_config HAVE_   "$config_files" $HAVE_LIST
print_config HAVE_   "$config_files" $MYTHTV_HAVE_LIST
print_config CONFIG_ "$config_files" $CONFIG_LIST       \
                                     $CONFIG_EXTRA      \
                                     $MYTHTV_LIST       \
                                     $MYTHTV_CONFIG_LIST \


for opt in $MYTHTV_CONFIG_LIST $USING_LIST; do
    enabled $opt && append CCONFIG "using_$opt"
done

enabled threads && append CCONFIG "using_ffmpeg_threads"

if disabled frontend; then
    echo
    echo "WARNING: --disable-frontend is only intended to aid porting."
    echo "WARNING: THIS WILL BREAK THINGS. You are on your own now."
fi

if disabled backend; then
    echo
    echo "WARNING: --disable-backend is only intended to aid porting."
    echo "WARNING: You are on your own now."
fi

if enabled proc_opt; then
    echo
    echo "WARNING: When using --enable-proc-opt you must include the "
    echo "         output of ./configure along with any bug report."
fi

if enabled cpu_override; then
    echo
    echo "WARNING: When using --arch=X or --cpu=X you must include the "
    echo "         output of ./configure along with any bug report."
fi

echo # add a newline after any warnings.

if enabled mmx; then
  CONFIG_DEFINES="$CONFIG_DEFINES MMX"
  if enabled x86_32 ; then
    CONFIG_DEFINES="$CONFIG_DEFINES i386"
  fi
fi

if enabled firewire; then
  if test $target_os = darwin; then
      echo "CONFIG_MAC_AVC=$mac_avc" >> $TMPMAK
  else
      echo "CONFIG_FIREWIRE_LIBS=-lraw1394 -liec61883 -lavc1394 -lrom1394" >> $TMPMAK
  fi
fi

if enabled mheg; then
    append CCONFIG "using_mheg"
fi

if enabled libass; then
    append CCONFIG "using_libass"
fi

if enabled appleremote; then
  append CONFIG_DEFINES "USING_APPLEREMOTE"
fi

if enabled dvb && non_standard_header $dvb_path; then
  append CONFIG_INCLUDEPATH "$dvb_path"
fi

if enabled libcec; then
  append CONFIG_DEFINES "using_libcec"
  if non_standard_header $libcec_path; then
    append CONFIG_INCLUDEPATH "$libcec_path"
  fi
fi

if enabled libxml2; then
  if [ -d $libxml2_path ] ; then
    if non_standard_header $libxml2_path; then
      append CONFIG_INCLUDEPATH "$libxml2_path"
    fi
    append CCONFIG "using_libxml2"
  fi
fi

if enabled libmp3lame; then
  append CCONFIG "using_libmp3lame"
fi

if enabled taglib; then
    echo "CONFIG_TAGLIB_INCLUDES=$taglib_include" >> $TMPMAK
    echo "CONFIG_TAGLIB_LIBS=$taglib_libs" >> $TMPMAK
fi

if enabled x11; then
  if [ -d $x11_path ] ; then
    append CONFIG_INCLUDEPATH "$x11_path"
  fi
fi

if ! enabled darwin && enabled opengl; then
  echo "CONFIG_OPENGL_LIBS=$gl_lib $glu_lib" >> $TMPMAK
fi

if test x"$PERL_CONFIG_OPTS" != x"" ; then
  echo "PERL_CONFIG_OPTS=$PERL_CONFIG_OPTS" >> $TMPMAK
fi

if test x"$CCONFIG" != x"" ; then
  echo "CCONFIG=$CCONFIG" >> $TMPMAK
  echo "#define MYTH_BUILD_CONFIG \"$CCONFIG\"" >>$TMPH
fi

if test x"$CONFIG_DEFINES" != x"" ; then
  echo "CONFIG_DEFINES=$CONFIG_DEFINES" >> $TMPMAK
fi

if test x"$CONFIG_INCLUDEPATH" != x"" ; then
  echo "CONFIG_INCLUDEPATH=$CONFIG_INCLUDEPATH" >> $TMPMAK
fi

if test x"$USE_PYTHON_PIP" != x"" ; then
  echo "USE_PYTHON_PIP=$USE_PYTHON_PIP" >> $TMPMAK
fi

cat >> $TMPH <<EOF

/* NOLINTEND(cppcoreguidelines-macro-usage,modernize-macro-to-enum) */

#endif /* MYTHTV_CONFIG_H */
EOF

enabled hdhomerun && cat >> $TMPMAK <<EOF
HDHOMERUN_PREFIX=$HDHOMERUN_PREFIX
HDHOMERUN_VERSION=$HDHOMERUN_VERSION
EOF

#echo "endif # FFMPEG_CONFIG_MAK" >> $TMPMAK

echo "QMAKE_LFLAGS+=\"$LDFLAGS\"" >> $TMPMAK

cp_if_changed $TMPH $MYTH_CONFIG_H

if ! test -L config.h ; then
  ${ln_s} $MYTH_CONFIG_H config.h
fi

if [ ! -e config.h ] ; then
  ${ln_s} $MYTH_CONFIG_H config.h
fi

cat $TMPMAK | sed -e 's/^!/#/' > $TMPPRO

cp_if_changed $TMPPRO $MYTH_CONFIG_MAK

if ! test -L config.mak ; then
  ${ln_s} $MYTH_CONFIG_MAK config.mak
fi

if [ ! -e config.mak ] ; then
  ${ln_s} $MYTH_CONFIG_MAK config.mak
fi

# delete old myth config files in old location
if [ -e libs/libmyth/mythconfig.mak ] ; then
    rm -f libs/libmyth/mythconfig.mak
fi
if [ -e libs/libmyth/mythconfig.h ] ; then
    rm -f libs/libmyth/mythconfig.h
fi

#
# More file generation
#

echo "Creating settings2.pro"
sed -e "s/@MYTHTV_VERSION_MAJMIN@/${MYTHTV_VERSION_MAJMIN}/g" \
    -e "s/@MYTHTV_LIBVERSION@/${MYTHTV_LIBVERSION}/g" \
    settings2.pro.in > $TMPPRO
cp_if_changed $TMPPRO settings2.pro

echo "Creating libs/libmythbase/mythversion.h"
sed -e "s/@MYTHTV_BINARY_VERSION@/${MYTHTV_BINARY_VERSION}/g" \
    -e "s/@MYTHTV_VERSION_MAJMIN@/${MYTHTV_VERSION_MAJMIN}/g" \
    libs/libmythbase/mythversion.h.in > $TMPH
cp_if_changed $TMPH libs/libmythbase/mythversion.h

echo "Creating bindings/perl/Makefile.PL"
sed -e "s/@MYTHTV_VERSION_MAJMIN@/${MYTHTV_VERSION_MAJMIN}/g" \
    bindings/perl/Makefile.PL.in > $TMPPRO
cp_if_changed $TMPPRO bindings/perl/Makefile.PL

echo "Creating bindings/python/setup.cfg"
sed -e "s/@MYTHTV_VERSION_MAJMIN@/${MYTHTV_VERSION_MAJMIN}/g" \
    bindings/python/setup.cfg.in > $TMPPRO
cp_if_changed $TMPPRO bindings/python/setup.cfg

echo "Creating bindings/python/MythTV/_versions.py"
sed -e "s/@MYTHTV_PYTHON_OWN_VERSION@/${MYTHTV_PYTHON_OWN_VERSION}/g" \
    -e "s!@MYTHTV_INSTALL_PREFIX@!${prefix}!g" \
    bindings/python/MythTV/_versions.py.in > $TMPPRO
cp_if_changed $TMPPRO bindings/python/MythTV/_versions.py

echo "Creating bindings/python/MythTV/services_api/mythversions.py"
sed -e "s/@MYTHTV_PYTHON_VERSION_LIST@/${MYTHTV_PYTHON_VERSION_LIST}/g" \
    bindings/python/MythTV/services_api/mythversions.py.in > $TMPPRO
cp_if_changed $TMPPRO bindings/python/MythTV/services_api/mythversions.py

#
# Configure subdirs
#
if ! enabled system_libudfread; then
    echo "Configuring libudfread..."
    (cd external/libudfread ; \
           ${qmakeconf} -o Makefile)
fi
if ! enabled system_libbluray; then
    echo "Configuring libmythbluray..."
    (cd external/libmythbluray ; \
           ${qmakeconf} -o Makefile)
fi
if ! enabled system_libexiv2; then
    echo "Configuring libexiv2..."
    (cd external/libexiv2 ; \
           ${qmakeconf} -o Makefile)
fi
echo "Configuring libmythdvdnav..."
(cd external/libmythdvdnav ; \
       ${qmakeconf} -o Makefile)

test -n "$WARNINGS" && printf "\n$WARNINGS" || exit 0
