# -*- coding: utf-8; mode: tcl; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- vim:fenc=utf-8:filetype=tcl:et:sw=4:ts=4:sts=4

PortSystem              1.0
PortGroup               active_variants 1.1
PortGroup               ffmpeg 1.0
PortGroup               github 1.0
PortGroup               legacysupport 1.1
PortGroup               meson 1.0

# Note, clean build is desirable, since the build system may not respect disabling x11
# and link to xorg libs opportunistically.

# When updating linked ffmpeg port, check if mpv needs a revbump.

github.setup            mpv-player mpv 0.41.0 v
revision                6
conflicts               mpv-cocoa mpv-devel mpv-legacy
categories              multimedia
license                 GPL-2+
maintainers             {@barracuda156 macos-powerpc.org:barracuda} openmaintainer

description             ${name} is a movie player, based on MPlayer and mplayer2
long_description        {*}${description}. It plays most MPEG/VOB, AVI, Ogg/OGM, \
                        VIVO, ASF/WMA/WMV, QT/MOV/MP4, RealMedia, Matroska, \
                        NUT, NuppelVideo, FLI, YUV4MPEG, FILM, RoQ, PVA files, \
                        supported by many native, XAnim and Win32 DLL codecs. \
                        You can watch VideoCD, SVCD, DVD, 3ivx, DivX 3/4/5, WMV \
                        and even H.264 movies.
homepage                https://www.mpv.io

checksums               rmd160  a2cb64c08db8fb90caced4e0fde3d10b8ab7fc0f \
                        sha256  ee21092a5ee427353392360929dc64645c54479aefdb5babc5cfbb5fad626209 \
                        size    7262018
github.tarball_from     archive

# This port is meant for legacy systems and will not work as-is on modern ones
# due to bugs in upstream code (sdl2 implementation is broken, cocoa without swift
# is broken). Use either mpv-cocoa or mpv-legacy, if this one fails.
# See also: https://trac.macports.org/ticket/72953
# TODO: pure X11 can work on modern systems, but needs some adjustments here.
if {${os.major} >= 11} {
    known_fail          yes
    pre-fetch {
        ui_error "${subport} is only supported on macOS 10.6 or below. Try mpv-cocoa or mpv-legacy instead."
        return -code error "incompatible Mac OS X version"
    }
}

ffmpeg.version          8

depends_build-append    path:bin/pkg-config:pkgconfig

depends_lib-append      path:lib/pkgconfig/libass.pc:libass \
                        port:lcms2 \
                        port:libiconv \
                        port:libplacebo \
                        port:libsdl2 \
                        port:libsixel \
                        path:bin/perl:perl5 \
                        port:zimg \
                        port:zlib

universal_variant       no

configure.args-append   --buildtype=release \
                        -Dandroid-media-ndk=disabled \
                        -Daudiounit=disabled \
                        -Dcaca=disabled \
                        -Dcdda=disabled \
                        -Dcoreaudio=enabled \
                        -Dcocoa=disabled \
                        -Dcplugins=enabled \
                        -Dcuda-hwaccel=disabled \
                        -Ddirect3d=disabled \
                        -Ddvbin=disabled \
                        -Ddvdnav=disabled \
                        -Degl=disabled \
                        -Degl-angle=disabled \
                        -Degl-angle-lib=disabled \
                        -Degl-drm=disabled \
                        -Degl-wayland=disabled \
                        -Degl-x11=disabled \
                        -Dgl=disabled \
                        -Dgl-cocoa=disabled \
                        -Dgl-x11=disabled \
                        -Dgpl=true \
                        -Dhtml-build=disabled \
                        -Diconv=enabled \
                        -Dios-gl=disabled \
                        -Djack=disabled \
                        -Djavascript=disabled \
                        -Djpeg=disabled \
                        -Dlibarchive=disabled \
                        -Dlibbluray=disabled \
                        -Dlibmpv=false \
                        -Dlua=disabled \
                        -Dmanpage-build=enabled \
                        -Dopenal=disabled \
                        -Dopensles=disabled \
                        -Dpdf-build=disabled \
                        -Dplain-gl=disabled \
                        -Dpulse=disabled \
                        -Dpthread-debug=disabled \
                        -Drubberband=disabled \
                        -Dsdl2-audio=enabled \
                        -Dsdl2-gamepad=disabled \
                        -Dsdl2-video=enabled \
                        -Dshaderc=disabled \
                        -Dsixel=enabled \
                        -Dswift-build=disabled \
                        -Duchardet=disabled \
                        -Dvapoursynth=disabled \
                        -Dvideotoolbox-gl=disabled \
                        -Dvideotoolbox-pl=disabled \
                        -Dvulkan=disabled \
                        -Dwayland=disabled \
                        -Dx11=disabled \
                        -Dxv=disabled \
                        -Dzimg=enabled \
                        -Dzlib=enabled

patch.pre_args-replace  -p0 -p1

patchfiles-append       0001-opengl-add-gl-2.0-support.patch \
                        0002-sdl-context.patch \
                        0003-player-clipboard-make-mac-clipboard-conditional.patch \
                        0004-audio-coreaudio-add-macos-10.6-compatibility.patch \
                        0005-osdep-mac-fix-app-bridge-for-non-swift-builds.patch \
                        0006-unbreak-x11-gl.patch \
                        0007-fix-big-endian.patch \
                        0008-fix-environ.patch \
                        0009-youtubedl-edl-track-error.patch \
                        0010-meson-build-system-changes-for-macos-10.6.patch \
                        0011-vo-gpu-default.patch \
                        0012-wayland-input.patch \
                        0013-video-repack-fix-packed-word-repacking-on-big-endian.patch

if {[string match *gcc* ${configure.compiler}]} {
    # ao_coreaudio_properties.c:36:61: error: passing argument 5 of 'AudioObjectGetPropertyData'
    # from incompatible pointer type [-Wincompatible-pointer-types]
    configure.cflags-append \
                        -Wno-error=incompatible-pointer-types
}

# Fix picking up the correct talloc version.
# -isystem has the added benefit of moving the include
# directory specified to the end of the include path list.
# This will help the build system respect custom include
# paths correctly (i.e., searching them before the MP include
# directory.)
configure.cppflags-replace \
                        -I${prefix}/include \
                        -isystem${prefix}/include

platform darwin {
    notes-append [subst {
                    The maintainer ships his personal config file in
                    * ${prefix}/share/doc/${name}/examples/config-maintainer.

                    You are strongly encouraged to copy this file to either
                    * ${prefix}/etc/${name}/${name}.conf (globally for all users of the system) or
                    * ~/.config/${name}/mpv.conf (only for your current user)
                    and adjust it to your needs.

                    If you previously had your configuration file in
                    * ~/.${name}/config or ~/.config/${name}/config
                    please migrate it to
                    * ~/.config/${name}/mpv.conf
                    which is the location preferred by upstream.
    }]

    notes-append {
                    This config file already defines the necessary video output settings to make\
                    use of the hardware acceleration features provided by your operating system.
    }

    # C11 atomics is mandatory from version 0.33.0
    compiler.c_standard     2011
    compiler.cxx_standard   2020
    compiler.blacklist-append \
                    {clang < 700} cc

    post-extract {
        xinstall -m 0644 -W "${filespath}" config-maintainer "${worksrcpath}/TOOLS/"
    }

    pre-configure {
        if {${configure.sdkroot} ne ""} {
            configure.sdk_version [exec /usr/libexec/PlistBuddy -c Print:ProductVersion ${configure.sdkroot}/System/Library/CoreServices/SystemVersion.plist]
        }
        if {[llength [split ${configure.sdk_version} .]] < 2} {
            configure.sdk_version ${configure.sdk_version}.0
        }
        configure.env-append \
                        MACOS_SDK=${configure.sdkroot} \
                        MACOS_SDK_VERSION=${configure.sdk_version}

        if {[variant_isset network] || [variant_isset network_ytdlp]} {
            reinplace -W "${worksrcpath}/TOOLS" "s/@@NETWORK@@//" config-maintainer
        } else {
            reinplace -W "${worksrcpath}/TOOLS" "/@@NETWORK@@/d" config-maintainer
        }

        if {${os.major} > 11} {
            reinplace -W "${worksrcpath}/TOOLS" "s/@@HWDEC@@//" config-maintainer
        } else {
            reinplace -W "${worksrcpath}/TOOLS" "/@@HWDEC@@/d" config-maintainer
        }

        if {${os.major} > 12} {
            reinplace -W "${worksrcpath}/TOOLS" "s/@@HWDEC_CUDA@@//" config-maintainer
        } else {
            reinplace -W "${worksrcpath}/TOOLS" "/@@HWDEC_CUDA@@/d" config-maintainer
        }

        if {${os.major} < 11} {
            reinplace -W "${worksrcpath}/TOOLS" "/@@VO@@/d" config-maintainer
        } else {
            reinplace -W "${worksrcpath}/TOOLS" "s/@@VO@@//" config-maintainer
        }

        if {[variant_isset x11]} {
            reinplace -W "${worksrcpath}/TOOLS" "s/@@BACKEND@@/x11/" config-maintainer
        } else {
            reinplace -W "${worksrcpath}/TOOLS" "/@@BACKEND@@/d" config-maintainer
        }
    }
}

# TODO: get rid of this zoo, just use one python consistently.
# Shameless copy from ipe-tools.
set python.versions         {39 310 311 312 313 314}
dict set python.legacy_versions 38 39

set python.default_version  314
set python.version          ""

# Create python variants.
foreach ver ${python.versions} {
    set variant_line {variant python${ver} description }
    set python_branch [string index $ver 0].[string range $ver 1 end]
    append variant_line " {Use Python ${python_branch} to build ${name} and generate man pages}"

    foreach over ${python.versions} {
        if {${ver} == ${over}} {
            continue
        }

        append variant_line " conflicts python${over}"
    }

    append variant_line " {
        depends_build-append    port:py${ver}-docutils
        license_noconflict      py${ver}-docutils
    }"
    eval $variant_line
}

# Create legacy python variants, mapping to the replacement version.
dict for {legacy_ver replace_ver} ${python.legacy_versions} {
    set variant_line {variant python${legacy_ver} description }
    set legacy_branch [join [split ${legacy_ver} {}] "."]
    set replace_branch [join [split ${replace_ver} {}] "."]
    append variant_line " {Legacy variant for Python ${legacy_branch} mapping to Python ${replace_branch}}"
    append variant_line " requires python${replace_ver}"

    foreach over ${python.versions} {
        if {${legacy_ver} == ${over} || ${replace_ver} == ${over}} {
            continue
        }

        append variant_line " conflicts python${over}"
    }

    append variant_line " { }"
    eval $variant_line
}

# Set default python variant.
set variant_none true
foreach ver ${python.versions} {
    if {[variant_isset python${ver}]} {
        set variant_none [expr $variant_none && ![variant_isset python${ver}]]
    }
}

if {${variant_none}} {
    default_variants-append "+python${python.default_version}"
}

# Set ${python.version} to the currently active variant.
foreach ver ${python.versions} {
    if {[variant_isset python${ver}]} {
        set python.version ${ver}
        set python_branch [string index ${python.version} 0].[string range ${python.version} 1 end]
    }
}

if {[string length ${python.version}] == 0} {
    ui_error "No python variant selected. You must select at least one. The highest value will be used."
    error "Select a python variant."
}

meson.native.binaries-append \
                        rst2man=${prefix}/bin/rst2man-${python_branch}

configure.python        ${prefix}/bin/python${python_branch}

post-patch {
    # For some reason, there is no issue on 10.6, but on 10.5 ppc64 the build needed this patch.
    if {${os.platform} eq "darwin" && ${os.major} < 10} {
        reinplace "s|rst2man.py|rst2man-${python_branch}|" ${worksrcpath}/meson.build
    }

    fs-traverse f ${worksrcpath}/TOOLS {
        if {[string match *.py ${f}]} {
            reinplace "s|/usr/bin/env python3$|${configure.python}|" ${f}
        }
    }
}

post-destroot {
    # Since we don't have conffiles handling, install mpv.conf as mpv.conf.example
    # to not overwrite this file on each (re-)build.
    file rename ${worksrcpath}/etc/mpv.conf ${worksrcpath}/etc/mpv.conf.example

    xinstall -d -m 0755 ${destroot}${prefix}/etc/${name}
    foreach etcfile {encoding-profiles.conf mpv.conf.example input.conf} {
        xinstall -m 0644 ${worksrcpath}/etc/${etcfile} \
            ${destroot}${prefix}/etc/${name}/${etcfile}
    }
    xinstall -d -m 0755 ${destroot}${prefix}/share/doc/${name}/examples
    copy {*}[glob ${worksrcpath}/TOOLS/lua ${worksrcpath}/TOOLS/*.pl \
                  ${worksrcpath}/TOOLS/*.sh ${worksrcpath}/TOOLS/*.py \
                  ${worksrcpath}/TOOLS/umpv ${worksrcpath}/TOOLS/lib] \
         ${destroot}${prefix}/share/doc/${name}/examples

    if {${os.platform} eq "darwin"} {
        xinstall -m 0644 ${worksrcpath}/TOOLS/config-maintainer \
                         ${destroot}${prefix}/share/doc/${name}/examples
    }
}

# When enabling features, make sure to replace the "disabled" flags with
# "enabled" flags in order to make the meson build system error out in case
# a feature cannot be used/found. Problems like that indicate a missing
# runtime dependency.

variant audiocd description "Enable Audio CD support via libcdio-paranoia" {
    depends_lib-append      port:libcdio-paranoia
    configure.args-replace  -Dcdda=disabled \
                            -Dcdda=enabled
}

variant bluray description "Enable Bluray and AACS/BD+ encryption support" {
    depends_lib-append     port:libbluray
    depends_run-append     port:libaacs \
                           port:libbdplus
    configure.args-replace -Dlibbluray=disabled \
                           -Dlibbluray=enabled
    notes-append "
                    To play Bluray discs with AACS encryption, decryption key database file `keydb.cfg` needs to be placed at:
                    * ~/Library/Preferences/aacs/ (on macOS, or)
                    * ~/.config/aacs/ (on other darwin).
                    You can easily find this file on the internet.
    "
}

variant caca description "Enable animated ASCII art video output" {
    depends_lib-append      port:libcaca
    configure.args-replace  -Dcaca=disabled \
                            -Dcaca=enabled
}

variant debug description "Compile with debugging symbols" {
    configure.args-replace  --buildtype=release \
                            --buildtype=debug
    configure.args-replace  -Dpthread-debug=disabled \
                            -Dpthread-debug=enabled
}

variant dvd description "Enable DVD and DeCSS support" {
    depends_lib-append      port:libdvdnav \
                            port:libdvdread
    configure.args-replace  -Ddvdnav=disabled \
                            -Ddvdnav=enabled
}

variant jack description "Enable Jack Audio Connection Kit support" {
    depends_lib-append      port:jack
    configure.args-replace  -Djack=disabled \
                            -Djack=enabled
}

variant libarchive description "Enable transparent handling of Zip files and other compressed formats" {
    depends_lib-append      port:libarchive
    configure.args-replace  -Dlibarchive=disabled \
                            -Dlibarchive=enabled
}

variant libmpv description "Enable the libmpv library" {
    configure.args-replace  -Dlibmpv=false \
                            -Dlibmpv=true
}

variant network conflicts network_ytdlp description "Enable networking support via youtube-dl (supports wide variety of pages)" {
    depends_run-append      port:youtube-dl
}

variant network_ytdlp conflicts network description "Enable networking support via yt-dlp instead of youtube-dl (supports wide variety of pages)" {
    depends_run-append      port:yt-dlp
}

# TODO: switch that to openal-soft? Leave it as-is?
variant openal description "Enable OpenAL support" {
    depends_lib-append      port:openal
    configure.args-replace  -Dopenal=disabled \
                            -Dopenal=enabled
}

variant opengl description "Enable OpenGL output support. Both the CoreVideo and X11 (GLX) outputs are supported" {
    require_active_variants libplacebo opengl

    configure.args-replace  -Dgl=disabled \
                            -Dgl=enabled

    configure.args-delete   -Dplain-gl=disabled

    if {[variant_isset x11]} {
        depends_lib-append      port:mesa
        configure.args-replace  -Dgl-x11=disabled \
                                -Dgl-x11=enabled

        # FIXME: add EGL? Leave it disabled? Test!
        # As far as testing went, EGL is not available on macOS yet.
        #configure.args-replace  -Degl-x11=disabled \
        #                        -Degl-x11=enabled

        # TODO: see if EGL via angle can work with this.
    }
}

variant osd description "Enable onscreen display and TrueType font support" {
    depends_lib-append      port:lua52
    configure.args-replace  -Dlua=disabled \
                            -Dlua=lua5.2
}

variant pulseaudio description "Enable PulseAudio support" {
    depends_lib-append      port:pulseaudio
    configure.args-replace  -Dpulse=disabled \
                            -Dpulse=enabled
}

variant rubberband description "Enable support for the Rubber Band library, adding audio pitch and speed control" {
    depends_lib-append      port:rubberband
    configure.args-replace  -Drubberband=disabled \
                            -Drubberband=enabled
}

variant screenshot description "Enable optional screenshot support" {
    depends_lib-append      path:include/turbojpeg.h:libjpeg-turbo
    configure.args-replace  -Djpeg=disabled \
                            -Djpeg=enabled
}

variant uchardet description "Enable the uchardet encoding detector" {
    depends_lib-append      port:uchardet
    configure.args-replace  -Duchardet=disabled \
                            -Duchardet=enabled
}

variant vapoursynth description "Enable vapoursynth support" {
    depends_lib-append      port:vapoursynth
    configure.args-replace  -Dvapoursynth=disabled \
                            -Dvapoursynth=enabled
}

# TODO: does it conflict with X11?
variant wayland description "Enable Wayland support" {
    depends_build-append    port:wayland-protocols
    depends_lib-append      port:libxkbcommon \
                            port:wayland
    configure.args-replace  -Dwayland=disabled \
                            -Dwayland=enabled
}

# This implies sdl2 with +x11, which currently is libsdl2-x11 port.
# TODO: add a logic to check for consistency.
# See: https://github.com/macos-powerpc/powerpc-ports/issues/17
variant x11 {
    require_active_variants ffmpeg${ffmpeg_ver} x11

    depends_lib-append      port:xorg-libXext \
                            port:xorg-libXfixes \
                            port:xorg-libXinerama \
                            port:xorg-libXpresent \
                            port:xorg-libXrandr \
                            port:xorg-libXScrnSaver \
                            port:xorg-libXv

    depends_lib-replace     port:libsdl2 \
                            port:libsdl2-x11

    configure.args-replace  -Dx11=disabled \
                            -Dx11=enabled
    configure.args-replace  -Dxv=disabled \
                            -Dxv=enabled
}

# Disable +x11 by default, since it is preferable to use sdl2 with Cocoa backend.
default_variants    +audiocd +bluray +dvd +libarchive +libmpv +opengl +osd

if {![variant_isset network]} {
    default_variants-append \
                    +network_ytdlp
}

platform darwin {
    default_variants-append \
                    +rubberband
}

notes "
Notice that video playback via SDL2 Cocoa backend may not work with ATI GPUs.\
If you have an ATI GPU and get video output failure, consider using X11-based\
version of mpv (and libsdl2-x11 instead of libsdl2-cocoa). Also notice that\
specifically 10.6.8 A5 image needs libsdl2-cocoa with +oldapi variant.
"
