#! /bin/sh
#
# Original version (C) 2000 Pontscho/fresh!mindworkz pontscho@makacs.poliod.hu
# Cleanups all over the place (c) 2001 pl
# Rewritten for mpv in 2014.
#
# This configure script is *not* autoconf-based and has different semantics.
# It attempts to autodetect all settings and options where possible. It is
# possible to override autodetection with the --enable-option/--disable-option
# command line parameters.  --enable-option forces the option on skipping
# autodetection. Yes, this means that compilation may fail and yes, this is not
# how autoconf-based configure scripts behave.
#
# configure generates a series of configuration files:
#  - config.h contains #defines that are used in the C code.
#  - config.mak is included from the Makefiles.
#
# If you want to add a new check for $feature, look at the existing checks
# and try to use helper functions where you can.
#############################################################################

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

# Store the configure line that was used
configuration="$*"

# Prefer these macros to full length text !
# These macros only return an error code - NO display is done
command_check() {
  echo >> "$TMPLOG"
  echo "$@" >> "$TMPLOG"
  "$@" >> "$TMPLOG" 2>&1
  TMPRES="$?"
  echo >> "$TMPLOG"
  return "$TMPRES"
}

compile_check() {
  source="$1"
  shift
  echo >> "$TMPLOG"
  cat "$source" >> "$TMPLOG"
  echo >> "$TMPLOG"
  echo "$_cc $OURCFLAGS $CFLAGS $source $extra_cflags $_ld_static $extra_ldflags $libs_mplayer -o $TMPEXE $@" >> "$TMPLOG"
  rm -f "$TMPEXE"
  $_cc $OURCFLAGS $CFLAGS "$source" $extra_cflags $_ld_static $extra_ldflags $libs_mplayer -o "$TMPEXE" $@ >> "$TMPLOG" 2>&1
  TMPRES="$?"
  echo >> "$TMPLOG"
  echo >> "$TMPLOG"
  return "$TMPRES"
}

cflag_check() {
    echo "int main(void) { return 0; }" > $TMPC
    compile_check $TMPC $@
}

statement_check() {
    echo "" > $TMPC
    for _header in $1 ; do echo "#include <$_header>" >> $TMPC ; done
    echo "int main(void) { $2; return 0; }" >> $TMPC
    shift 2
    compile_check $TMPC $@
}

pkg_config_add() {
  echo >> "$TMPLOG"
  echo "$_pkg_config --cflags $@" >> "$TMPLOG"
  ctmp=$($_pkg_config --cflags "$@" 2>> "$TMPLOG") || return $?
  echo >> "$TMPLOG"
  echo "$_pkg_config --libs $@" >> "$TMPLOG"
  ltmp=$($_pkg_config --libs "$@" 2>> "$TMPLOG") || return $?
  echo >> "$TMPLOG"
  echo "cflags: $ctmp" >> "$TMPLOG"
  echo "libs: $ltmp" >> "$TMPLOG"
  echo >> "$TMPLOG"
  extra_cflags="$extra_cflags $ctmp"
  libs_mplayer="$libs_mplayer $ltmp"
}

# Display error message, flushes tempfile, exit
die () {
  echo
  echo "Error: $@" >&2
  echo >&2
  rm -f "$TMPEXE" "$TMPC"
  echo "Check \"$TMPLOG\" if you do not understand why it failed."
  exit 1
}

# Use this before starting a check
echocheck() {
  echo "============ Checking for $@ ============" >> "$TMPLOG"
  echo ${_echo_n} "Checking for $@ ... ${_echo_c}"
}

# Use this to echo the results of a check
echores() {
  test "$res_comment" && res_comment="($res_comment)"
  echo "Result is: $@ $res_comment" >> "$TMPLOG"
  echo "##########################################" >> "$TMPLOG"
  echo "" >> "$TMPLOG"
  echo "$@ $res_comment"
  res_comment=""
}

# Check how echo works in this /bin/sh
case $(echo -n) in
  -n)   _echo_n=        _echo_c='\c'    ;;      # SysV echo
  *)    _echo_n='-n '   _echo_c=        ;;      # BSD echo
esac

# setind $a b sets the variable named by the value of the variable a to b
setind() { eval "$1=\"\$2\"" ; }

# Generate --enable-NAME/--disable-NAME options, set $1 to the option value.
# Since shell has no data structures, do a weird statemachine thing.
# Arguments: "_name"($1) "description"($2) "default"($3)
# If "default"($3) is empty, use "auto"
# Option name: a leading "_" in name is stripped, further "_" are changed to "-"
opt_yes_no() {
    _name=$(echo "$1" | sed 's/^_//' | tr _ -)
    _defval="$3"
    test -z "$_defval" && _defval=auto

    case "$_opt_state_mode" in
    init)
        setind "$1" "$_defval"
        ;;
    help)
        if test "$_defval" = yes || test "$_defval" = auto ; then
            _defdesc=enable
            test "$_defval" = auto && _defdesc=auto
            printf "  %-21s  disable $2 [$_defdesc]\n" "--disable-$_name"
            unset _defdesc
        else
            printf "  %-21s  enable $2 [disable]\n" "--enable-$_name"
        fi
        ;;
    parse)
        if test "$_opt_state_name" = "--enable-$_name" ; then
            setind "$1" yes
            _opt_state_known=yes
        elif test "$_opt_state_name" = "--disable-$_name" ; then
            setind "$1" no
            _opt_state_known=yes
        elif test "$_opt_state_name" = "--auto-$_name" ; then
            setind "$1" auto
            _opt_state_known=yes
        fi
        ;;
    esac
    unset _name
    unset _defval
}

options_state_machine() {
    _opt_state_mode=$1
    _opt_state_name=$2
    _opt_state_known=no

    opt_yes_no _gl          "OpenGL video output"
    opt_yes_no _libguess    "libguess"
    opt_yes_no _terminfo    "terminfo database for key codes" no
    opt_yes_no _termcap     "termcap database for key codes" no
    opt_yes_no _termios     "termios database for key codes"
    opt_yes_no _iconv       "iconv for encoding conversion"
    opt_yes_no _lirc        "LIRC (remote control) support"
    opt_yes_no _joystick    "joystick support" no
    opt_yes_no _vm          "X video mode extensions"
    opt_yes_no _dvb         "DVB input"
    opt_yes_no _tv          "TV interface (TV/DVB grabbers)" yes
    opt_yes_no _tv_v4l2     "Video4Linux2 TV interface"
    opt_yes_no _libv4l2     "libv4l2"
    opt_yes_no _pvr         "Video4Linux2 MPEG PVR"
    opt_yes_no _smb         "Samba (SMB) input"
    opt_yes_no _libquvi4    "libquvi 0.4.x"
    opt_yes_no _libquvi9    "libquvi 0.9.x"
    opt_yes_no _lcms2       "LCMS2 support"
    opt_yes_no _bluray      "Blu-ray support"
    opt_yes_no _dvdread     "libdvdread"
    opt_yes_no _dvdnav      "libdvdnav"
    opt_yes_no _enca        "ENCA charset oracle library"
    opt_yes_no _libass      "subtitle rendering with libass"
    opt_yes_no _libpostproc "postprocess filter (vf_pp)"
    opt_yes_no _libavdevice "libavdevice demuxers"
    opt_yes_no _libavfilter "libavfilter"
    opt_yes_no _vapoursynth "VapourSynth filter bridge"
    opt_yes_no _jpeg        "support for writing JPEG screenshots"
    opt_yes_no _libcdio     "libcdio support"
    opt_yes_no _ffmpeg      "skip FFmpeg/Libav autodetection"
    opt_yes_no _ladspa      "LADSPA plugin support"
    opt_yes_no _libbs2b     "libbs2b audio filter support"
    opt_yes_no _mpg123      " libmpg123 MP3 decoding support"
    opt_yes_no _libavresample "libavresample (preferred over libswresample)"
    opt_yes_no _libswresample "libswresample"
    opt_yes_no _caca        "CACA  video output"
    opt_yes_no _sdl2        "SDL2 video and audio outputs" no
    opt_yes_no _xv          "Xv video output"
    opt_yes_no _vdpau       "VDPAU acceleration"
    opt_yes_no _vaapi       "VAAPI acceleration"
    opt_yes_no _xrandr      "Xrandr support (used for monitor FPS detection)"
    opt_yes_no _xinerama    "Xinerama support"
    opt_yes_no _x11         "X11 video output"
    opt_yes_no _wayland     "Wayland video output"
    opt_yes_no _xss         "support for disabling screensaver via xss"
    opt_yes_no _alsa        "ALSA audio output"
    opt_yes_no _ossaudio    "OSS audio output"
    opt_yes_no _rsound      "RSound audio output"
    opt_yes_no _sndio       "sndio audio output"
    opt_yes_no _pulse       "Pulseaudio audio output"
    opt_yes_no _portaudio   "PortAudio audio output"
    opt_yes_no _jack        "JACK audio output"
    opt_yes_no _openal      "OpenAL audio output"
    opt_yes_no _shm         "X11/Xv shared memory"
    opt_yes_no _lua         "Lua scripting"
    opt_yes_no _encoding    "encoding functionality" yes
    opt_yes_no _build_man   "building manpage"
}

show_help(){
cat << EOF
Usage: $0 [OPTIONS]...

Configuration:
  -h, --help             display this help and exit

Installation directories:
  --prefix=DIR           prefix directory for installation [/usr/local]
  --bindir=DIR           directory for installing binaries [PREFIX/bin]
  --datadir=DIR          directory for installing machine independent
                         data files (skins, etc) [PREFIX/share/mpv]
  --mandir=DIR           directory for installing man pages [PREFIX/share/man]
  --confdir=DIR          directory for installing configuration files
                         [PREFIX/etc/mpv]

Compilation options:
  --cc=COMPILER          C compiler to build mpv [gcc]
  --pkg-config=PKGCONFIG pkg-config to find some libraries [pkg-config]
  --enable-static        build a statically linked binary
  --disable-debug        compile-in debugging information [enable]
  --disable-optimization compile without -O2 [enable]

Use these options if autodetection fails:
  --extra-cflags=FLAGS   extra CFLAGS
  --extra-ldflags=FLAGS  extra LDFLAGS
  --extra-libs=FLAGS     extra linker flags

Features:
EOF
options_state_machine help
cat << EOF

This configure script is NOT autoconf-based, even though its output is similar.
It will try to autodetect all configuration options. If you --enable an option
it will be forcefully turned on, skipping autodetection. This can break
compilation, so you need to know what you are doing.
EOF
exit 0
} #show_help()

# GOTCHA: the variables below defines the default behavior for autodetection
# and have - unless stated otherwise - at least 2 states : yes no
# If autodetection is available then the third state is: auto
_pkg_config=auto
_cc=auto
test -n "$CC" && _cc="$CC"
_opt=-O2
_prefix="/usr/local"
options_state_machine init
for ac_option do
  case "$ac_option" in
  --help|-help|-h)
    show_help
    ;;
  --prefix=*)
    _prefix=$(echo $ac_option | cut -d '=' -f 2)
    ;;
  --bindir=*)
    _bindir=$(echo $ac_option | cut -d '=' -f 2)
    ;;
  --mandir=*)
    _mandir=$(echo $ac_option | cut -d '=' -f 2)
    ;;
  --confdir=*)
    _confdir=$(echo $ac_option | cut -d '=' -f 2)
    ;;
  --extra-cflags=*)
    extra_cflags="$extra_cflags $(echo $ac_option | cut -d '=' -f 2-)"
    ;;
  --extra-ldflags=*)
    extra_ldflags="$extra_ldflags $(echo $ac_option | cut -d '=' -f 2-)"
    ;;
  --extra-libs=*)
    libs_mplayer=$(echo $ac_option | cut -d '=' -f 2)
    ;;
  --cc=*)
    _cc=$(echo $ac_option | cut -d '=' -f 2)
    ;;
  --pkg-config=*)
    _pkg_config=$(echo $ac_option | cut -d '=' -f 2)
    ;;
  --enable-static)
    _ld_static='-static'
    ;;
  --disable-static)
    _ld_static=''
    ;;
  --enable-optimization)
    _opt='-O2'
    ;;
  --enable-optimization=*)
    _opt=$(echo $_echo_n '-O'$_echo_c; echo $ac_option | cut -d '=' -f 2)
    ;;
  --disable-optimization)
    _opt=
    ;;
  *)
    options_state_machine parse "$ac_option"
    if test "$_opt_state_known" != yes ; then
        echo "Unknown parameter: $ac_option" >&2
        exit 1
    fi
    ;;

  esac
done

test -z "$_bindir"  && _bindir="$_prefix/bin"
test -z "$_mandir"  && _mandir="$_prefix/share/man"
test -z "$_confdir" && _confdir="$_prefix/etc/mpv"

mplayer_tmpdir=$(mktemp -d --tmpdir mpv-configure-XXXX)
test -n "$mplayer_tmpdir" || die "Unable to create tmpdir."

TMPLOG="config.log"

rm -f "$TMPLOG"
echo Parameters configure was run with: > "$TMPLOG"
echo CFLAGS="'$CFLAGS'" PKG_CONFIG_PATH="'$PKG_CONFIG_PATH'" ./configure $configuration >> "$TMPLOG"
echo >> "$TMPLOG"

TMPC="$mplayer_tmpdir/tmp.c"
TMPEXE="$mplayer_tmpdir/tmp"
CONFIG_MAK="$mplayer_tmpdir/config.mak"
CONFIG_H="$mplayer_tmpdir/config.h"

echo > $CONFIG_MAK
echo > $CONFIG_H

test "$_pkg_config" = auto && _pkg_config=pkg-config
test "$_cc" = auto && _cc=cc

extra_cflags="-I. -D_GNU_SOURCE $extra_cflags"

_rst2man=rst2man
test -f "$(which rst2man.py)" && _rst2man=rst2man.py

echocheck "whether to build manpages with rst2man"
if test "$_build_man" = auto ; then
    _build_man=no
    command_check "$_rst2man" --version && _build_man=yes
fi
echores "$_build_man"

echocheck "working compiler"
cflag_check "" || die "Compiler is not functioning correctly. Check your installation and custom CFLAGS $CFLAGS ."
echores "yes"

echocheck "perl"
command_check perl -Mv5.8 -e';' || die "Perl is not functioning correctly or is ancient. Install the latest perl available."
echores yes

echocheck "compiler support of -pipe option"
cflag_check -pipe -I. && _pipe="-pipe" && echores "yes" || echores "no"

addcflags() { cflag_check "$@" && OURCFLAGS="$OURCFLAGS $@" ; }

OURCFLAGS="-std=c99 -Wall $_opt"

addcflags -g -g3 -ggdb
addcflags -Wundef -Wmissing-prototypes -Wshadow -Wno-switch -Wno-parentheses -Wpointer-arith -Wredundant-decls -Wno-pointer-sign -Werror=implicit-function-declaration -Wno-error=deprecated-declarations -Wno-error=unused-function -Wempty-body
# clang
addcflags -Wno-logical-op-parentheses -fcolor-diagnostics -Wno-tautological-compare -Wno-tautological-constant-out-of-range-compare

cflag_check -MD -MP && DEPFLAGS="-MD -MP"
cflag_check -lm && _ld_lm="-lm"

extra_ldflags="$extra_ldflags $LDFLAGS"
extra_cflags="$extra_cflags $CPPFLAGS"

# If $1 is "yes", define $2 as 1 in config.h, else define it as 0
define_yes_no() {
    if test "$1" = yes ; then
        echo "#define $2 1" >> $CONFIG_H
    else
        echo "#define $2 0" >> $CONFIG_H
    fi
}

# Write the results of a check to config.mak/.h.
# Arguments: "yes/no"($1) "name"($2)
check_yes_no() {
    define_yes_no $1 "HAVE_$2"
    echo "$2 = $1" >> $CONFIG_MAK
}

check_trivial() {
    echocheck "$1"
    check_yes_no $2 $3
    echores "$2"
}

# Arguments: "message"($1) "setting"($2) "name"($3) "code"($4)
# Also, $5 - $N can be libraries needed - it'll try each separately.
# Use " " as first entry if you want to try with no libraries too.
check_compile() {
    _res="$2"
    _name="$3"
    _code="$4"
    echocheck "$1"
    if test $_res = auto ; then
        _res=no
        if test $# -gt 4 ; then
            shift 4
        else
            shift $#
        fi
        while true ; do
            compile_check "$_code" "$1" && libs_mplayer="$libs_mplayer $1" && _res=yes && break
            test -z "$1" && break
            shift
        done
    fi
    check_yes_no $_res $_name
    echores $_res
    test $_res = yes && return 0 || return 1
}

# Arguments: "message"($1) "setting"($2) "name"($3) "include"($4) "statement"($5)
# Also, $6 - $N can be libraries needed - it'll try each separately.
# Use " " as first entry if you want to try with no libraries too.
check_statement_libs() {
    _res="$2"
    _name="$3"
    _inc="$4"
    _st="$5"
    echocheck "$1"
    if test $_res = auto ; then
        _res=no
        if test $# -gt 5 ; then
            shift 5
        else
            shift $#
        fi
        while true ; do
            statement_check "$_inc" "$_st" "$1" && libs_mplayer="$libs_mplayer $1" && _res=yes && break
            test -z "$1" && break
            shift
        done
    fi
    check_yes_no $_res $_name
    echores $_res
    test $_res = yes && return 0 || return 1
}

# Print "yes" if previous command succeeded, else "no"
defretval() { # shell is retarded?
    if test $? = 0 ; then
        echo "yes"
    else
        echo "no"
    fi
}

echocheck "dynamic loader"
_dl=no
for _ld_tmp in "" "-ldl"; do
  statement_check dlfcn.h 'dlopen("", 0)' $_ld_tmp && _ld_dl="$_ld_tmp" && _dl=yes && break
done
define_yes_no $_dl HAVE_LIBDL
echores "$_dl"

echocheck "pthread"
cflag_check -pthread && _ld_pthread="$_ld_pthread -pthread"
cflag_check -lpthread && _ld_pthread="$_ld_pthread -lpthread"
cflag_check -lrt && _ld_pthread="$_ld_pthread -lrt"
extra_cflags="$extra_cflags -D_REENTRANT -D_THREAD_SAFE"
compile_check waftools/fragments/pthreads.c "$_ld_pthread" || die "Unable to find pthreads support."
echores "yes"

check_statement_libs "support for stdatomic.h" auto STDATOMIC \
    stdatomic.h 'atomic_int_least64_t test = ATOMIC_VAR_INIT(123); int test2 = atomic_load(&test)' \
    " " "-latomic"
_stdatomic=$(defretval)

_atomic=auto
test "$_stdatomic" = yes && _atomic=no
check_statement_libs "compiler support for __atomic built-ins" $_atomic ATOMIC_BUILTINS \
    stdint.h 'int64_t test = 0; test = __atomic_add_fetch(&test, 1, __ATOMIC_SEQ_CST)' \
    " " "-latomic"
_atomic=$(defretval)

_sync=auto
(test "$_atomic" = yes || test "$_stdatomic" = yes ) && _sync=no
check_statement_libs "compiler support for __sync built-ins" $_sync SYNC_BUILTINS \
    stdint.h 'int64_t test = 0; test = __sync_add_and_fetch(&test, 1)'
_sync=$(defretval)

if test "$_atomic" = no && test "$_sync" = no && test "$_stdatomic" = no ; then
  die "your compiler must support either stdatomic.h, or __atomic, or __sync built-ins."
fi

check_compile "iconv" $_iconv ICONV waftools/fragments/iconv.c " " "-liconv" "-liconv $_ld_dl"
_iconv=$(defretval)
if test "$_iconv" != yes ; then
    die "Unable to find iconv which should be part of standard compilation environment. Aborting. If you really mean to compile without iconv support use --disable-iconv."
fi

_soundcard_header=sys/soundcard.h
_check_snd=yes
check_statement_libs "sys/soundcard.h" auto SYS_SOUNDCARD_H sys/soundcard.h
test $(defretval) = yes && _soundcard_header=sys/soundcard.h && _check_snd=no
check_statement_libs "soundcard.h" $_check_snd SOUNDCARD_H soundcard.h
test $(defretval) = yes && _soundcard_header=soundcard.h

check_statement_libs "sys/videoio.h" auto SYS_VIDEOIO_H sys/videoio.h

check_statement_libs "terminfo" $_terminfo TERMINFO term.h 'setupterm(0, 1, 0)' "-lncurses" "-lncursesw"

check_statement_libs "termcap" $_termcap TERMCAP term.h 'tgetent(0, 0)' " " "-lncurses" "-ltinfo" "-ltermcap"

_termios_ok=no
check_statement_libs "termios.h" $_termios TERMIOS_H termios.h
test $(defretval) = yes && _termios_ok=yes && _termios=no
check_statement_libs "sys/termios.h" $_termios SYS_TERMIOS_H 'sys/termios.h'
test $(defretval) = yes && _termios_ok=yes
define_yes_no $_termios_ok HAVE_TERMIOS

check_statement_libs "shm" $_shm SHM "sys/types.h sys/ipc.h sys/shm.h" \
    "shmget(0, 0, 0); shmat(0, 0, 0); shmctl(0, 0, 0);"

echocheck "pkg-config"
if $($_pkg_config --version > /dev/null 2>&1); then
  if test "$_ld_static"; then
    _pkg_config="$_pkg_config --static"
  fi
  echores "yes"
else
  _pkg_config=false
  echores "no"
fi

# Arguments: "message"($1) "setting"($2) "name"($3) "pkg-config string"($4)
# The name will be used as "#define HAVE_$name 1/0" in config.h, and as
# "$name = yes/no" in config.mak
# "setting"($2) is yes/no/auto and represents the --enable/--disable option
check_pkg_config() {
    echocheck "$1"
    _res=$2
    if test "$2" = auto ; then
        _res=no
        if pkg_config_add "$4" ; then
            _res=yes
        fi
    fi
    check_yes_no $_res $3
    echores "$_res"
    test $_res = yes && return 0 || return 1
}

check_pkg_config "libguess support" $_libguess LIBGUESS 'libguess >= 1.0'

check_pkg_config "Samba support (libsmbclient)" $_smb LIBSMBCLIENT 'smbclient >= 0.2.0'

check_pkg_config "libquvi 0.4.x support" $_libquvi4 LIBQUVI4 'libquvi >= 0.4.1'
_libquvi4=$(defretval)

test $_libquvi4 = yes && _libquvi9=no
check_pkg_config "libquvi 0.9.x support" $_libquvi9 LIBQUVI9 'libquvi-0.9 >= 0.9.0'
_libquvi9=$(defretval)

_libquvi=no
(test "$_libquvi9" = yes || test "$_libquvi4" = yes) && _libquvi=yes
define_yes_no $_libquvi HAVE_LIBQUVI

_wlver="1.6.0"
check_pkg_config "Wayland" $_wayland WAYLAND "wayland-client >= $_wlver wayland-cursor >= $_wlver xkbcommon >= 0.3.0"
_wayland=$(defretval)

check_pkg_config "X11" $_x11 X11 "x11"
_x11=$(defretval)

# Disable X11 dependencies
_xext=auto
if test "$_x11" = no ; then
    _xss=no
    _xext=no
    _xv=no
    _vdpau=no
    _vaapi=no
    _xinerama=no
    _vm=no
fi

check_pkg_config "Xss screensaver extensions" $_xss XSS "xscrnsaver"

check_pkg_config "X extensions" $_xext XEXT "xext"

check_pkg_config "Xv" $_xv XV "xv"

check_pkg_config "VDPAU" $_vdpau VDPAU "vdpau >= 0.2"
_vdpau=$(defretval)
define_yes_no $_vdpau HAVE_VDPAU_HWACCEL

check_pkg_config "VAAPI" $_vaapi VAAPI 'libva >= 0.32.0 libva-x11 >= 0.32.0'
_vaapi=$(defretval)
define_yes_no $_vaapi HAVE_VAAPI_HWACCEL

if test "$_vaapi" = yes ; then
    check_pkg_config "VAAPI VPP" auto VAAPI_VPP 'libva >= 0.34.0'

    check_pkg_config "VAAPI GLX" auto VAAPI_GLX 'libva-glx >= 0.32.0'
    _vaapi_glx=$(defretval)
else
    check_yes_no no VAAPI_VPP
    check_yes_no no VAAPI_GLX
    _vaapi_glx=no
fi

check_pkg_config "Xinerama" $_xinerama XINERAMA 'xinerama'

check_pkg_config "Xrandr" $_xrandr XRANDR 'xrandr >= 1.2.0'

check_pkg_config "CACA" $_caca CACA 'caca >= 0.99.beta18'

check_compile "DVB" $_dvb DVB waftools/fragments/dvb.c
_dvbin=$(defretval)
check_yes_no $_dvbin DVBIN

check_statement_libs "JPEG support" $_jpeg JPEG "stdio.h jpeglib.h" "" "-ljpeg $_ld_lm"

(test "$_x11" = no && test "$_wayland" = no) && _gl=no
echocheck "OpenGL"
#Note: this test is run even with --enable-gl since we autodetect linker flags
if test "$_gl" != no ; then
  cat > $TMPC << EOF
#if defined(GL_WAYLAND)
#include <EGL/egl.h>
#else
#include <X11/Xlib.h>
#include <GL/glx.h>
#endif
#include <GL/gl.h>
#include <GL/glext.h>
int main(int argc, char *argv[]) {
#if defined(GL_WAYLAND)
  eglCreateContext(NULL, NULL, EGL_NO_CONTEXT, NULL);
#else
  glXCreateContext(NULL, NULL, NULL, True);
#endif
  glFinish();
  return !GL_INVALID_FRAMEBUFFER_OPERATION; // check correct glext.h
}
EOF
  _gl=no
  if test "$_x11" = yes ; then
    for _ld_tmp in "" -lGL "-lGL -lXdamage" "-lGL $_ld_pthread" ; do
      if compile_check $TMPC $_ld_tmp $_ld_lm ; then
        _gl=yes
        _gl_x11=yes
        libs_mplayer="$libs_mplayer $_ld_tmp $_ld_dl"
        test "$_gl_x11" = yes && res_comment="$res_comment x11"
        break
      fi
    done
  fi
  if test "$_wayland" = yes && compile_check $TMPC -DGL_WAYLAND -lGL -lEGL &&
      pkg_config_add "wayland-egl >= 9.0.0"; then
    _gl=yes
    _gl_wayland=yes
    libs_mplayer="$libs_mplayer -lGL -lEGL"
    test "$_gl_wayland" = yes && res_comment="$res_comment wayland"
  fi
else
  _gl=no
fi

if test "$_gl" = no ; then
    _gl_x11=no
    _gl_wayland=no
fi
check_yes_no $_gl GL
check_yes_no $_gl_x11 GL_X11
check_yes_no $_gl_wayland GL_WAYLAND
echores "$_gl"

echocheck "VDPAU with OpenGL/X11"
_vdpau_gl_x11=no
(test "$_gl_x11" = yes && test "$_vdpau" = yes) && _vdpau_gl_x11=yes
check_yes_no $_vdpau_gl_x11 VDPAU_GL_X11
echores "$_vdpau_gl_x11"

check_pkg_config "SDL 2.0" $_sdl2 SDL2 'sdl2'

check_statement_libs "OSS Audio" $_ossaudio OSS_AUDIO $_soundcard_header "int x = SNDCTL_DSP_SETFRAGMENT;"

check_statement_libs "RSound" $_rsound RSOUND rsound.h 'rsd_init(NULL);' -lrsound

check_statement_libs "sndio" $_sndio SNDIO sndio.h 'struct sio_par par; sio_initpar(&par); const char *s = SIO_DEVANY' -lsndio

check_pkg_config "PulseAudio" $_pulse PULSE 'libpulse >= 1.0'

check_pkg_config "PortAudio" $_portaudio PORTAUDIO 'portaudio-2.0 >= 19'

check_pkg_config "JACK" $_jack JACK 'jack'

check_pkg_config "OpenAL" $_openal OPENAL 'openal >= 1.13'

check_pkg_config "ALSA audio" $_alsa ALSA 'alsa >= 1.0.9'

check_pkg_config "Blu-ray support" $_bluray LIBBLURAY 'libbluray >= 0.2.1'

check_pkg_config "dvdread" $_dvdread DVDREAD 'dvdread >= 4.1.0'

check_pkg_config "dvdnav" $_dvdnav DVDNAV 'dvdnav >= 4.2.0'

check_pkg_config "libcdio" $_libcdio CDDA 'libcdio_paranoia'

_oldass=$_libass
check_pkg_config "SSA/ASS support" $_libass LIBASS 'libass'
_libass=$(defretval)
if test $_oldass != no && test $_libass = no ; then
    die "Unable to find development files for libass. Aborting. If you really mean to compile without libass support use --disable-libass."
fi

_dummy_osd=yes
test $_libass = yes && _dummy_osd=no
echo "LIBASS_OSD = $_libass" >> $CONFIG_MAK
echo "DUMMY_OSD = $_dummy_osd" >> $CONFIG_MAK

check_pkg_config "ENCA" $_enca ENCA 'enca'

check_pkg_config "zlib" auto ZLIB 'zlib'
test $(defretval) = no && die "Unable to find development files for zlib."

check_pkg_config "mpg123 support" $_mpg123 MPG123 'libmpg123 >= 1.14.0'

test "$_dl" = no && _ladspa=no
check_statement_libs "LADSPA plugin support" $_ladspa LADSPA ladspa.h 'LADSPA_Descriptor ld = {0}'

check_pkg_config "libbs2b audio filter support" $_libbs2b LIBBS2B 'libbs2b'

check_pkg_config "LCMS2 support" $_lcms2 LCMS2 'lcms2 >= 2.6'

check_pkg_config "VapourSynth support" $_vapoursynth VAPOURSYNTH 'vapoursynth >= 23 vapoursynth-script >= 23'

check_pkg_config "FFmpeg/Libav" $_ffmpeg FFMPEG \
    "libavutil >= 52.48.101 libavcodec >= 55.34.1 libavformat >= 55.12.0 libswscale >= 2.1.2"
test $(defretval) = no && die "Unable to find development files for some of the required Libav libraries above. Aborting."

check_pkg_config "Libavresample" $_libavresample LIBAVRESAMPLE 'libavresample >= 1.1.0'
_libavresample=$(defretval)

_libswresample=auto
test $_libavresample = yes && _libswresample=no
check_pkg_config "Libswresample" $_libswresample LIBSWRESAMPLE 'libswresample >= 0.17.104'
_libswresample=$(defretval)

if test "$_libswresample" = no && test "$_libavresample" = no ; then
  die "No resampler found. Install libavresample or libswresample (FFmpeg)."
fi

# Arguments: "message"($1) "define"($2) "header"($3) "code"($4)
api_statement_check() {
    echocheck "$1"
    _res=no
    statement_check "$3" "$4" && _res=yes
    define_yes_no $_res "$2"
    echores "$_res"
}

api_statement_check \
    "libavcodec avcodec_enum_to_chroma_pos API" \
    HAVE_AVCODEC_CHROMA_POS_API \
    libavcodec/avcodec.h \
    'int x, y; avcodec_enum_to_chroma_pos(&x, &y, AVCHROMA_LOC_UNSPECIFIED)'

api_statement_check \
    "libavcodec avcol_spc_bt2020 available" \
    HAVE_AVCOL_SPC_BT2020 \
    libavcodec/avcodec.h \
    'int x = AVCOL_SPC_BT2020_NCL'

api_statement_check \
    "libavcodec metadata update side data" \
    HAVE_AVCODEC_METADATA_UPDATE_SIDE_DATA \
    libavcodec/avcodec.h \
    'enum AVPacketSideDataType type = AV_PKT_DATA_METADATA_UPDATE'

api_statement_check \
    "libavformat metadata update flags" \
    HAVE_AVFORMAT_METADATA_UPDATE_FLAG \
    libavformat/avformat.h \
    'int x = AVFMT_EVENT_FLAG_METADATA_UPDATED'

api_statement_check \
    "libavcodec replaygain side data" \
    HAVE_AVCODEC_REPLAYGAIN_SIDE_DATA \
    libavcodec/avcodec.h \
    'enum AVPacketSideDataType type = AV_PKT_DATA_REPLAYGAIN'

api_statement_check \
    "libavutil/libavcodec display matrix side data" \
    HAVE_AV_DISPLAYMATRIX \
    libavutil/frame.h \
    'enum AVFrameSideDataType type = AV_FRAME_DATA_DISPLAYMATRIX'

api_statement_check \
    "libavutil AVFrame metadata" \
    HAVE_AVFRAME_METADATA \
    libavutil/frame.h \
    'av_frame_get_metadata(NULL)'

api_statement_check \
    "libavutil QP API" \
    HAVE_AVUTIL_QP_API \
    libavutil/frame.h \
    'av_frame_get_qp_table(NULL, NULL, NULL)'

api_statement_check \
    "libavcodec av_vdpau_alloc_context()" \
    HAVE_AVCODEC_VDPAU_ALLOC_CONTEXT \
    libavcodec/vdpau.h \
    'AVVDPAUContext *x = av_vdpau_alloc_context()'

check_pkg_config "libavfilter" $_libavfilter LIBAVFILTER 'libavfilter >= 3.90.100'

check_pkg_config "libavdevice" $_libavdevice LIBAVDEVICE 'libavdevice >= 54.0.0'

check_pkg_config "libpostproc" $_libpostproc LIBPOSTPROC 'libpostproc >= 52.0.0'

check_trivial "TV interface" $_tv TV

check_statement_libs "Video 4 Linux 2 TV interface" $_tv_v4l2 TV_V4L2 \
    "sys/time.h linux/videodev2.h"
_tv_v4l2=$(defretval)
check_trivial "TV audio input" $_tv_v4l2 AUDIO_INPUT

test $_tv_v4l2 = no && _libv4l2=no
check_pkg_config "libv4l2 support" $_libv4l2 LIBV4L2 'libv4l2'

test "$_tv_v4l2" = no && _pvr=no
check_compile "Video 4 Linux 2 MPEG PVR interface" $_pvr PVR waftools/fragments/pvr.c

# Note: Lua has no official .pc file, so there are different OS-specific ones.
# Also, we support luajit, which is compatible to 5.1.

test_lua() {
    if test "$_lua" = auto && $_pkg_config "$1" ; then
        check_pkg_config "Lua ($1)" $_lua LUA "$1"
        _lua=$(defretval)
    fi
}

test_lua "lua >= 5.1.0 lua < 5.2.0"
test_lua "lua5.1 >= 5.1.0" # debian
test_lua "luajit >= 2.0.0"
test_lua "lua >= 5.2.0"
test_lua "lua5.2 >= 5.2.0" # debian

test "$_lua" != yes && check_yes_no no LUA

check_trivial "joystick" $_joystick JOYSTICK

check_statement_libs "lirc" $_lirc LIRC lirc/lirc_client.h "" -llirc_client

check_trivial "encoding" $_encoding ENCODING

# needs dlopen on unix
_dlopen="$_dl"
check_yes_no $_dlopen DLOPEN

extra_ldflags="$extra_ldflags $_ld_pthread"
libs_mplayer="$libs_mplayer $_ld_dl"

CFLAGS="$CFLAGS -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -D_LARGEFILE64_SOURCE"

# This is done so waf builds won't conflict with this. In fact, waf and old
# build system can coexist in parallel, at the same time. This is because
# waf always does out-of-tree builds, while this build system does always
# in-tree builds.

if test ! -f Makefile ; then
    ln -s old-makefile Makefile
fi
mkdir old_build 2> /dev/null

cat > old_build/config.mak << EOF
# -------- Generated by configure -----------
export LC_ALL = C

CONFIGURATION = $configuration

prefix  = \$(DESTDIR)$_prefix
BINDIR  = \$(DESTDIR)$_bindir
MANDIR  = \$(DESTDIR)$_mandir
CONFDIR = \$(DESTDIR)$_confdir

CC      = $_cc
INSTALL = install

CFLAGS   = -Iold_build $OURCFLAGS $CFLAGS $extra_cflags
DEPFLAGS = $DEPFLAGS

EXTRALIBS = $extra_ldflags $_ld_static $_ld_lm $libs_mplayer $end_ldflags

RST2MAN = $_rst2man
BUILD_MAN = $_build_man

# features
EOF
cat $CONFIG_MAK >> old_build/config.mak

cat > $TMPC << EOF
/*----------------------------------------------------------------------------
** This file has been automatically generated by configure any changes in it
** will be lost when you run configure again.
** Instead of modifying definitions here, use the --enable/--disable options
** of the configure script! See ./configure --help for details.
*---------------------------------------------------------------------------*/

#ifndef MPV_CONFIG_H
#define MPV_CONFIG_H

#define CONFIGURATION "$configuration"

#define MPLAYER_CONFDIR "$_confdir"

/* we didn't bother to add actual config checks for this, or they are
   for platforms not supported by this configure script */
#define HAVE_BSD_FSTATFS 0
#define HAVE_LINUX_FSTATFS 0
#define HAVE_VDA_AV_VDA_ALLOC_CONTEXT 0
#define HAVE_VDA_HWACCEL 0
#define HAVE_VDA_LIBAVCODEC_REFCOUNTING 0
#define HAVE_VDA_GL 0
#define HAVE_GL_COCOA 0
#define HAVE_COCOA 0
#define HAVE_COCOA_APPLICATION 0
#define HAVE_COREVIDEO 0
#define HAVE_COREAUDIO 0
#define HAVE_GL_WIN32 0
#define HAVE_DIRECT3D 0
#define HAVE_DSOUND 0
#define HAVE_WASAPI 0
#define HAVE_DOS_PATHS 0
#define HAVE_PRIORITY 0
#define HAVE_GLOB 1
#define HAVE_SYS_MMAN_H 1
#define HAVE_NANOSLEEP 1
#define HAVE_SDL1 0
#define HAVE_WAIO 0

#define DEFAULT_CDROM_DEVICE "/dev/cdrom"
#define DEFAULT_DVD_DEVICE   "/dev/dvd"
#define PATH_DEV_DSP "/dev/dsp"
#define PATH_DEV_MIXER "/dev/mixer"

EOF
cat $CONFIG_H >> $TMPC
echo '#endif /* MPV_CONFIG_H */' >> $TMPC

# Do not overwrite an unchanged config.h to avoid superfluous rebuilds.
cmp -s "$TMPC" old_build/config.h || mv -f "$TMPC" old_build/config.h

cat <<EOF

Configuration successful. See $TMPLOG for details.

NOTE: The --enable-* parameters unconditionally force options on, completely
skipping autodetection. This behavior is unlike what you may be used to from
autoconf-based configure scripts that can decide to override you. This greater
level of control comes at a price. You may have to provide the correct compiler
and linker flags yourself.
If you used one of these options and experience a compilation or
linking failure, make sure you have passed the necessary compiler/linker flags
to configure.

WARNING: The ./old-configure + make build system you are using is deprecated in
favour of waf and will be removed in a future version of mpv. Check the
README for instructions on how to build mpv with the new build system.
This will not work correctly on MinGW, Cygwin, OSX, and other systems.

EOF

# Last move:
rm -rf "$mplayer_tmpdir"