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

PortSystem          1.0
PortGroup           xcodeversion 1.0
PortGroup           muniversal 1.0
PortGroup           compiler_blacklist_versions 1.0
PortGroup           active_variants 1.1

# For 'TARGET_OS_OSX', 'TARGET_CPU_ARM64' macros
PortGroup           legacysupport 1.1

# https://trac.macports.org/ticket/59246
# https://trac.macports.org/ticket/59308
PortGroup           xcode_workaround 1.0

name                ffmpeg
set my_name         ffmpeg
conflicts           ffmpeg-devel ffmpeg-upstream

# Please increase the revision of mpv whenever ffmpeg's version is updated.
version             4.4.2
revision            3
epoch               1

license             LGPL-2.1+
categories          multimedia
maintainers         {mascguy @mascguy} {devans @dbevans} {jeremyhu @jeremyhu} openmaintainer

description         FFmpeg is a complete solution to play, record, convert and \
                    stream audio and video.

long_description    FFmpeg is a complete solution to record, convert and \
                    stream audio and video. It includes libavcodec, the \
                    leading audio/video codec library. \
                    \
                    The project is made of several components: \
                    \
                    ffmpeg is a command line tool to convert one video \
                    file format to another. It also supports grabbing and \
                    encoding in real time from a TV card. \
                    \
                    ffserver is an HTTP (RTSP is being developed) \
                    multimedia streaming server for live broadcasts. Time \
                    shifting of live broadcast is also supported. \
                    \
                    ffplay is a simple media player based on SDL and on \
                    the ffmpeg libraries. \
                    \
                    ffprobe gathers information from multimedia streams and \
                    prints it in human- and machine-readable fashion. \
                    \
                    libavcodec is a library containing all the ffmpeg \
                    audio/video encoders and decoders. Most codecs were \
                    developed from scratch to ensure best performance \
                    and high code reusability. \
                    \
                    libavformat is a library containing parsers and \
                    generators for all common audio/video formats.

homepage            https://ffmpeg.org/
master_sites        ${homepage}releases/
distname            ${my_name}-${version}
dist_subdir         ${my_name}
use_xz              yes

checksums           rmd160  22a690edfad74f25de0d24557f8edf4b2366b1a0 \
                    sha256  af419a7f88adbc56c758ab19b4c708afbcae15ef09606b82b855291f6a6faa93 \
                    size    9562968

depends_build-append \
                    port:pkgconfig \
                    port:gmake \
                    port:cctools \
                    port:texinfo

depends_lib-append \
                    port:lame \
                    port:libiconv \
                    port:libvorbis \
                    port:libopus \
                    port:libogg \
                    path:lib/pkgconfig/librsvg-2.0.pc:librsvg \
                    port:libtheora \
                    port:libmodplug \
                    port:libass \
                    port:libbluray \
                    path:lib/pkgconfig/vpx.pc:libvpx \
                    path:lib/pkgconfig/gnutls.pc:gnutls \
                    port:openh264 \
                    port:snappy \
                    port:openjpeg \
                    port:zvbi \
                    port:fontconfig \
                    port:freetype \
                    port:fribidi \
                    path:lib/libspeex.dylib:speex \
                    port:soxr \
                    port:bzip2 \
                    port:xz \
                    port:zimg \
                    port:zlib

patchfiles-append   patch-libavcodec-audiotoolboxenc.c.diff

# Fix an upstream bug that overrides the max_b_frames setting
# https://trac.ffmpeg.org/ticket/9231
# Fixed via upstream commit: 55d9d6767967794edcdd6e1bbd8840fc6f4e9315
patchfiles-append   patch-libavcodec-videotoolboxenc.c.diff

# Patch for upstream bug related to non-B-frame encoding
# https://trac.ffmpeg.org/ticket/9439
# Fixed via upstream commit: b786bc7433dfe082441a57c1ba9ae9ea47904b78
patchfiles-append   patch-issue-9439-non-b-frame-encoding.diff

# Patch for libsdl2; support newer versions
# https://trac.macports.org/ticket/65703
# Fixed via upstream commit: e5163b1d34381a3319214a902ef1df923dd2eeba
patchfiles-append   patch-libsdl2-version.diff

# enable auto configure of asm optimizations
# requires Xcode 3.1 or better on Leopard
minimum_xcodeversions {9 3.1}

# requires a C11 compiler
compiler.c_standard 2011

# clang-3.1 hits https://trac.macports.org/ticket/30137 (<rdar://problem/11542429>)
# clang-139 hits https://trac.macports.org/ticket/38141
# warning: unknown warning option '-Werror=partial-availability'; did you mean '-Werror=availability'? [-Wunknown-warning-option]
# warning: unknown warning option '-Wno-bool-operation'; did you mean '-Wno-bool-conversion'? [-Wunknown-warning-option]
compiler.blacklist-append {clang < 800}

# gcc > 4.2 is required, https://trac.ffmpeg.org/ticket/1464
# WARNING: gcc 4.2 is outdated and may miscompile FFmpeg. Please use a newer compiler.
compiler.blacklist-append \
                    *gcc-4.0 *gcc-4.2

# The old ffmpeg port was GPL-2+ as base and had a no_gpl variant, so this keeps us consistent
# Also, -gpl2 causes other ports to fail to build due to the missing libpostproc (#35473)
default_variants-append +gpl2

configure.cflags-append \
                    -DHAVE_LRINTF ${configure.cppflags}

configure.args-append \
                    --enable-swscale \
                    --enable-avfilter \
                    --enable-avresample \
                    --enable-libmp3lame \
                    --enable-libvorbis \
                    --enable-libopus \
                    --enable-librsvg \
                    --enable-libtheora \
                    --enable-libopenjpeg \
                    --enable-libopenh264 \
                    --enable-libsnappy \
                    --enable-libmodplug \
                    --enable-libvpx \
                    --enable-libsoxr \
                    --enable-libspeex \
                    --enable-libass \
                    --enable-libbluray \
                    --enable-libzimg \
                    --enable-libzvbi \
                    --enable-lzma \
                    --enable-gnutls \
                    --enable-fontconfig \
                    --enable-libfreetype \
                    --enable-libfribidi \
                    --enable-zlib \
                    --disable-libaom \
                    --disable-libjack \
                    --disable-libopencore-amrnb \
                    --disable-libopencore-amrwb \
                    --disable-libxcb \
                    --disable-libxcb-shm \
                    --disable-libxcb-xfixes \
                    --disable-xlib \
                    --disable-indev=jack \
                    --disable-opencl \
                    --disable-outdev=xv \
                    --disable-audiotoolbox \
                    --disable-videotoolbox \
                    --disable-sdl2 \
                    --disable-securetransport \
                    --mandir=${prefix}/share/man \
                    --enable-shared \
                    --enable-pthreads \
                    --cxx=${configure.cxx} \
                    --cc=${configure.cc}

platform darwin {
    # disable asm on Tiger
    # libblueray doesn't build on Tiger so disable for now (#39442)
    if {${os.major} < 9} {
        depends_lib-delete    port:libbluray
        configure.args-replace --enable-libbluray --disable-libbluray
        configure.args-append --disable-asm
    }

    # as of 1.6.0 libvpx only supports darwin 10 or later
    if {${os.major} < 10} {
        depends_lib-delete path:lib/pkgconfig/vpx.pc:libvpx
        configure.args-replace --enable-libvpx --disable-libvpx
    }

    # filters coreimage and coreimagesrc don't build on 10.6
    # and earlier due to use of bridged casts in Objective C (#51823)
    if {${os.major} < 11} {
        configure.args-append --disable-filter=coreimage \
                              --disable-filter=coreimagesrc
    }

    # AudioToolbox support requires CoreMedia Framework available on 10.7+
    if {${os.major} > 10} {
        configure.args-replace --disable-audiotoolbox --enable-audiotoolbox
    }

    if {${os.major} > 9} {
        # libsdl2 requires minimum Xcode 10.7 SDK to build successfully
        # but builds on Snow Leopard
        configure.args-replace --disable-sdl2 --enable-sdl2
        depends_lib-append     port:libsdl2

        # Dav1d: 10.6+ No PowerPC or Apple Silicon (for now)
        if {![regexp -all (arm64|ppc*) [get_canonical_archs]]} {
            configure.args-append   --enable-libdav1d
            depends_lib-append      port:dav1d
        }
    }

    # VideoToolbox, a new hardware acceleration framework, is supported on 10.8+ and "here to stay".
    # It provides support for H264, H263, MPEG1, MPEG2 and MPEG4.
    if {${os.major} > 11} {
        configure.args-replace --disable-videotoolbox --enable-videotoolbox
    }

    # OpenCL support requires version 1.2 available 10.8+
    if {${os.major} > 11} {
        configure.args-replace --disable-opencl --enable-opencl
    }

    # Apple GCC has problems with SIMD intrinsics and -Werror=no-missing-prototypes.
    if {${os.major} < 11} {
        patchfiles-append patch-configure-no-error-on-missing-prototypes.diff
    }

    # avfoundation is only available on 10.7+
    # as of ffmpeg 3.4.1 build fails on 10.7 as well
    # libavdevice/avfoundation.m:207:14: error: expected method to read dictionary element not found on object of type 'NSDictionary *'
    if {${os.major} < 12} {
        configure.args-append --disable-indev=avfoundation
    }

    # av1 codecs, available on 10.7+
    if {${os.major} >= 11} {
        configure.args-append \
                        --enable-libaom \
                        --enable-librav1e \
                        --enable-libsvtav1
        depends_lib-append \
                        port:aom \
                        port:rav1e \
                        port:svt-av1
    }
}

build.cmd           ${prefix}/bin/gmake
build.env-append    V=1

test.run            yes

destroot.env-append V=1

post-extract {
    # fix file perms; tarball contents deny group and world read
    system "find ${worksrcpath} -type d -print0 | xargs -0 chmod a+rx"
    system "find ${worksrcpath} -type f -print0 | xargs -0 chmod a+r"
}

post-extract {
    if {${configure.cxx_stdlib} eq "libc++"} {
        # fix configure, which contains many references to libstdc++
        reinplace -E {s|-lstdc|-lc|g} ${worksrcpath}/configure
    }
}

post-configure {
    if {[variant_isset universal]} {
        # fix *.pc for universal build (i386 version may miss these extra bits on Leopard)
        foreach arch ${universal_archs_to_use} {
            foreach fixfile [exec find ${worksrcpath}-${arch} -name "*.pc"] {
                reinplace -E {s|Libs.private: -l|Libs.private: -framework QTKit -framework Foundation -framework QuartzCore -l|g} ${fixfile}
            }
        }
    }
}

post-destroot {
    file mkdir ${destroot}${prefix}/share/doc/ffmpeg
    file copy ${worksrcpath}/doc/APIchanges ${destroot}${prefix}/share/doc/ffmpeg
    foreach f [glob ${worksrcpath}/doc/*.txt] {
        file copy $f ${destroot}${prefix}/share/doc/ffmpeg
    }
}

platform powerpc {
    # absence of altivec is not automatically detected
    if {[catch {sysctl hw.vectorunit} result] || $result == 0} {
        configure.args-append --disable-altivec

        # as this machine is a G3, force a local build so we don't download a buildbot-built
        # version possibly built on a G4+ or cross-compiled from an Intel system
        archive_sites
    }

    # might be needed for any gcc build...
    #Undefined symbols:
    #  "___atomic_fetch_sub_8", referenced from:
    #      _fifo_thread_dispatch_message.part.4 in fifo.o
    configure.ldflags-append -latomic
}

platform darwin 8 {
    post-patch {
        reinplace "s:,-compatibility_version,$\(LIBMAJOR\)::" ${worksrcpath}/configure
    }
}

# configure isn't autoconf and they do use a dep cache
configure.universal_args-delete --disable-dependency-tracking

if {${universal_possible} && [variant_isset universal]} {
    # the following is inspired by the icu Portfile
    # if we can't run executables for the target arch, mark it as a cross-compile
    foreach arch ${configure.universal_archs} {
        if {((${os.major} < 9 || [sysctl hw.cpu64bit_capable] == 0) && ($arch == "x86_64" || $arch == "ppc64")) 
            || (${os.arch} == "powerpc" && ($arch == "x86_64" || $arch == "i386"))
            || (${os.arch} == "i386" && ($arch == "ppc" || $arch == "ppc64"))} {
            set merger_configure_args($arch) "--enable-cross-compile --target-os=${os.platform}"
        }
    }
    foreach arch ${configure.universal_archs} {
        set merger_host($arch) ""
        lappend merger_configure_args($arch) --arch=${arch}
        lappend merger_configure_env($arch)  ASFLAGS='-arch ${arch}'
    }
    if {[string match "*86*" ${configure.universal_archs}]} {
        depends_build-append port:nasm
    }
    lappend merger_configure_args(i386) --enable-x86asm
    lappend merger_configure_args(x86_64) --enable-x86asm
} else {
    configure.args-append --arch=${configure.build_arch}
    configure.env-append  ASFLAGS=[get_canonical_archflags]
    if {${build_arch} eq "i386" || ${build_arch} eq "x86_64"} {
        depends_build-append port:nasm
        configure.args-append --enable-x86asm
    }
}

variant x11 {
    # enable x11grab_xcb input device
    depends_lib-append      port:xorg-libxcb \
                            port:xorg-libXext \
                            port:xorg-libXfixes
    configure.args-delete   --disable-libxcb \
                            --disable-libxcb-shm \
                            --disable-libxcb-xfixes
}

variant natronmini requires highbitdepth aom conflicts x11 description {Minimal FFmpeg for Natron, without bluray, subtitles, network, display support.} {

    depends_lib-delete \
                    port:libiconv \
                    port:libass \
                    port:libbluray \
                    port:gnutls \
                    port:fontconfig \
                    port:freetype \
                    port:fribidi \
                    port:libsdl2 \
                    port:zimg

    configure.args-delete \
                    --enable-libass \
                    --enable-libbluray \
                    --enable-gnutls \
                    --enable-fontconfig \
                    --enable-libfreetype \
                    --enable-libfribidi \
                    --enable-sdl2 \
                    --enable-libzimg \
                    --cc=${configure.cc} \
                    --cxx=${configure.cxx}

    configure.args-append \
                    --disable-libass \
                    --disable-libbluray \
                    --disable-gnutls \
                    --disable-fontconfig \
                    --disable-libfreetype \
                    --disable-libfribidi \
                    --disable-sdl2 \
                    --disable-securetransport \
                    --disable-iconv \
                    --cc=${configure.cc} \
                    --cxx=${configure.cxx}

}

if {[variant_isset x11]} {
    require_active_variants libsdl2 x11
} else {
    require_active_variants libsdl2 "" x11
}


variant libdc1394 description {Enable IIDC-1394 frame grabbing using libdc1394 (experimental)} {
    depends_lib-append port:libdc1394
    configure.args-append --enable-libdc1394
}

# Allow use of librtmp instead of ffmpeg's internal rtmp implementation
# May address interoperability issues with CRtmpServer and others
# https://trac.macports.org/ticket/32219
# https://groups.google.com/forum/#!topic/c-rtmp-server/ywQPjvciPgc
# https://trac.ffmpeg.org/ticket/1700

variant librtmp description {Use librtmp (from rtmpdump) as rtmp[t][es]:// protocol handler} {
    configure.args-append   --enable-librtmp
    depends_lib-append      port:rtmpdump
}

variant jack description {Enable jack library and indev support} {
    # jack will autoconfigure if not disabled
    depends_lib-append      port:jack
    configure.args-replace  --disable-libjack    --enable-libjack
    configure.args-replace  --disable-indev=jack --enable-indev=jack
}

variant darwinssl description {Enable https support using Apple built-in TLS library instead of GNU TLS} {
    configure.args-delete   --disable-securetransport
    configure.args-delete   --enable-gnutls
    depends_lib-delete      path:lib/pkgconfig/gnutls.pc:gnutls
}

variant aom description {Enable Alliance for Open Media AV1 Codec} {
    depends_lib-append      port:aom
    configure.args-delete   --disable-libaom
    configure.args-append   --enable-libaom
}

variant highbitdepth description {Build using libvpx with 10/12-bit output} {}

if {[variant_isset highbitdepth]} {
    require_active_variants libvpx highbitdepth
} else {
    require_active_variants libvpx "" highbitdepth
}

variant gpl2 description {Enable GPL code, license will be GPL-2+} {
    configure.args-append   --enable-gpl \
                            --enable-postproc \
                            --enable-libx264 \
                            --enable-libx265 \
                            --enable-libxvid \
                            --enable-libvidstab
    depends_lib-append      port:XviD \
                            port:x264 \
                            port:x265 \
                            port:libvidstab
    license                 GPL-2+
}

variant gpl3 requires gpl2 description {Enable GPL code, license will be GPL-3+} {
    configure.args-append   --enable-version3 \
                            --enable-libsmbclient \
                            --enable-libaribb24
    depends_lib-append      path:lib/pkgconfig/smbclient.pc:samba3 \
                            port:libaribb24
    license                 GPL-3+

    # samba3 cannot be built universal (http://trac.macports.org/ticket/34558)
    if {[variant_isset universal]} {
        depends_lib-delete    port:samba3
        configure.args-delete --enable-libsmbclient
    }
}

# the build server uses the default variants, and we want distributable binaries
# nonfree code is disabled by default but can be enabled using the +nonfree variant

variant nonfree description {enable nonfree code, libraries and binaries will not be redistributable} {
    configure.args-append   --enable-nonfree \
                            --enable-libfdk-aac
    depends_lib-append      port:libfdk-aac
    license                 Restrictive
}

if {[variant_isset nonfree]} {
notes "
This build of ${name} includes nonfree code as follows:
  libfdk-aac
The following libraries and binaries may not be redistributed:
  ffmpeg
  libavcodec
  libavdevice
  libavfilter
  libavformat
  libavutil
To remove this restriction remove the variant +nonfree
"
} elseif {[variant_isset gpl3]} {
notes "
This build of ${name} includes GPLed code and is therefore licensed under GPL v3 or later.
The following modules are GPLed:
  postproc
  libsambaclient
  libvidstab
  libx264
  libx265
  libxvid
To include all nonfree, GPLed and LGPL code use variant +nonfree.
To remove nonfree and GPLed code leaving only LGPL code remove the +gpl2 and +gpl3 variants.
"
} elseif {[variant_isset gpl2]} {
notes "
This build of ${name} includes GPLed code and is therefore licensed under GPL v2 or later.
The following modules are GPLed:
  postproc
  libvidstab
  libx264
  libx265
  libxvid
To include all nonfree, GPLed and LGPL code use variant +nonfree.
To remove nonfree and GPLed code leaving only LGPL code remove the +gpl2 variant.
"
} else {
notes "
This build of ${name} includes no GPLed or nonfree code\
and is therefore licensed under LGPL v2.1 or later.
"
}

livecheck.type      regex
livecheck.url       ${master_sites}
livecheck.regex     "${my_name}-(\\d+(?:\\.\\d+)*)${extract.suffix}"
