Update-FFmpeg.ps1

#requires -Version 5.1
param(
    [guid]$OperationId = [guid]::NewGuid(),
    [uri]$SourceUrl,
    [ValidatePattern('\A[a-fA-F0-9]{64}\z')][string]$ArchiveSha256,
    [switch]$Executables
)

$ErrorActionPreference = 'Stop'
$ProgressPreference = 'SilentlyContinue'
if (![Environment]::Is64BitProcess) { throw 'FFmpeg updates require 64-bit Windows PowerShell.' }
$principal = [Security.Principal.WindowsPrincipal]::new([Security.Principal.WindowsIdentity]::GetCurrent())
if ($principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
    throw 'Run the FFmpeg updater as a standard user.'
}
if ($SourceUrl -and (!$SourceUrl.IsAbsoluteUri -or $SourceUrl.Scheme -ne 'https' -or $SourceUrl.UserInfo -or $SourceUrl.Fragment)) {
    throw 'Specify an absolute HTTPS archive URL without credentials or a fragment.'
}

function Get-FFmpegExecutableBuild([string]$Path, [string]$Program) {
    $process = [Diagnostics.Process]::new()
    try {
        $process.StartInfo.FileName = $Path
        $process.StartInfo.Arguments = '-version'
        $process.StartInfo.UseShellExecute = $false
        $process.StartInfo.CreateNoWindow = $true
        $process.StartInfo.RedirectStandardOutput = $true
        $process.StartInfo.RedirectStandardError = $true
        if (!$process.Start()) { throw "Could not start $Program." }
        $output = $process.StandardOutput.ReadToEndAsync()
        $errors = $process.StandardError.ReadToEndAsync()
        if (!$process.WaitForExit(10000)) {
            $process.Kill()
            throw "$Program did not respond to its version check."
        }
        $version = [regex]::Match($output.Result, ('\A' + $Program + ' version (?<version>\S+)'))
        $configuration = [regex]::Match($output.Result, '(?m)^configuration:\s*(?<config>[^\r\n]+)')
        if ($process.ExitCode -ne 0 -or !$version.Success -or !$configuration.Success) {
            throw "The downloaded $Program failed its version check. $($errors.Result)"
        }
        [pscustomobject]@{ Version=$version.Groups['version'].Value; Configuration=$configuration.Groups['config'].Value }
    }
    finally { $process.Dispose() }
}

$storePath = if ($Executables) { 'Hacksoft\VideoTools\FFmpegTools' } else { 'Hacksoft\VideoTools\FFmpeg' }
$root = [IO.Directory]::CreateDirectory((Join-Path ([Environment]::GetFolderPath('LocalApplicationData')) $storePath))
$lockPath = Join-Path $root.FullName 'update.lock'
try { $lock = [IO.File]::Open($lockPath, 'OpenOrCreate', 'ReadWrite', 'None') }
catch [IO.IOException] { throw 'Another FFmpeg library update is in progress or the update store is unavailable.' }

try {
    $stage = $root.CreateSubdirectory('download-' + $OperationId.ToString('N'))
    $payload = $stage.CreateSubdirectory('payload')
    $archiveName = if ($Executables) { 'ffmpeg-master-latest-win64-gpl.zip' } else { 'ffmpeg-master-latest-win64-gpl-shared.zip' }
    $provider = 'https://github.com/FFmpeg-Builds/FFmpeg-Builds'
    $releaseUri = 'https://api.github.com/repos/FFmpeg-Builds/FFmpeg-Builds/releases/tags/latest'
    $archiveUri = "$provider/releases/download/latest/$archiveName"
    [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
    if ($SourceUrl -and $SourceUrl.AbsoluteUri -cne $archiveUri) {
        if (!$ArchiveSha256) { throw 'An alternate FFmpeg archive requires a trusted SHA-256.' }
        $archiveUri = $SourceUrl.AbsoluteUri
        $provider = $SourceUrl.GetLeftPart([UriPartial]::Authority)
        $digest = $ArchiveSha256.ToLowerInvariant()
    }
    else {
        $release = Invoke-RestMethod -Uri $releaseUri -UserAgent 'VideoTools-FFmpeg' -TimeoutSec 25
        $assets = @($release.assets | Where-Object name -ceq $archiveName)
        if ($release.tag_name -cne 'latest' -or $assets.Count -ne 1) { throw 'The provider did not list the expected FFmpeg archive.' }
        $asset = $assets[0]
        if ($asset.browser_download_url -cne $archiveUri -or $asset.size -le 0 -or $asset.size -gt 250MB -or
            $asset.digest -cnotmatch '^sha256:([a-f0-9]{64})$') {
            throw 'The FFmpeg archive metadata is missing a valid size, download URL or SHA-256.'
        }
        $digest = $Matches[1]
        if ($ArchiveSha256 -and $digest -ne $ArchiveSha256) { throw 'The requested SHA-256 did not match the provider metadata.' }
    }
    $archivePath = Join-Path $stage.FullName $archiveName
    Invoke-WebRequest -Uri $archiveUri -OutFile $archivePath -UseBasicParsing -TimeoutSec 180
    $length = (Get-Item -LiteralPath $archivePath).Length
    if ($length -le 0 -or $length -gt 250MB -or ($asset -and $length -ne $asset.size) -or
        (Get-FileHash -LiteralPath $archivePath -Algorithm SHA256).Hash -ne $digest) {
        throw 'The FFmpeg archive size or SHA-256 did not match the provider metadata.'
    }

    Add-Type -AssemblyName System.IO.Compression.FileSystem
    $archiveRoot = [IO.Path]::GetFileNameWithoutExtension($archiveName)
    $patterns = @("^$archiveRoot/LICENSE\.txt$")
    if ($Executables) { $patterns += "^$archiveRoot/bin/ffmpeg\.exe$", "^$archiveRoot/bin/ffprobe\.exe$" }
    else {
        $patterns += @(foreach ($component in 'avutil', 'swresample', 'swscale', 'avcodec', 'avformat', 'avfilter', 'avdevice') {
            "^$archiveRoot/bin/$component-[0-9]+\.dll$"
        })
    }
    $files = [ordered]@{}
    $archive = [IO.Compression.ZipFile]::OpenRead($archivePath)
    try {
        foreach ($pattern in $patterns) {
            $matches = @($archive.Entries | Where-Object FullName -cmatch $pattern)
            if ($matches.Count -ne 1 -or $matches[0].Length -le 0 -or $matches[0].Length -gt 200MB) {
                throw "Invalid or missing FFmpeg archive member for $pattern."
            }
            $name = if ($Executables -and $matches[0].Name -eq 'LICENSE.txt') { 'FFmpeg-LICENSE.txt' } else { $matches[0].Name }
            $destination = Join-Path $payload.FullName $name
            [IO.Compression.ZipFileExtensions]::ExtractToFile($matches[0], $destination, $false)
            $files[$name] = (Get-FileHash -LiteralPath $destination -Algorithm SHA256).Hash.ToLowerInvariant()
        }
        if ($Executables) {
            $docs = @($archive.Entries | Where-Object FullName -cmatch "^$archiveRoot/doc/[A-Za-z0-9._-]+$")
            if (!$docs.Count -or $docs.Count -gt 256 -or ($docs | Measure-Object Length -Sum).Sum -gt 48MB) {
                throw 'The FFmpeg documentation payload is missing or too large.'
            }
            $docDirectory = $payload.CreateSubdirectory('FFmpeg-doc')
            foreach ($entry in $docs) {
                if ($entry.Name -in '.','..') { throw 'Invalid FFmpeg documentation entry.' }
                $destination = Join-Path $docDirectory.FullName $entry.Name
                [IO.Compression.ZipFileExtensions]::ExtractToFile($entry, $destination, $false)
                $files['FFmpeg-doc/' + $entry.Name] = (Get-FileHash -LiteralPath $destination -Algorithm SHA256).Hash.ToLowerInvariant()
            }
        }
    }
    finally { $archive.Dispose() }

    if ($Executables) {
        $capabilities = Get-FFmpegExecutableBuild (Join-Path $payload.FullName 'ffmpeg.exe') 'ffmpeg'
        $probeBuild = Get-FFmpegExecutableBuild (Join-Path $payload.FullName 'ffprobe.exe') 'ffprobe'
        if ($probeBuild.Version -cne $capabilities.Version -or $probeBuild.Configuration -cne $capabilities.Configuration) {
            throw 'FFmpeg and FFprobe report different builds.'
        }
    }
    else { $capabilities = & (Join-Path $PSScriptRoot 'Read-FFmpegLibraries.ps1') -Directory $payload.FullName | ConvertFrom-Json }
    $sourceRevision = [regex]::Match([string]$capabilities.Version, '-g([a-f0-9]{7,40})(?:-|$)')
    if (!$sourceRevision.Success -or
        $capabilities.Configuration -notmatch '(?:^| )--enable-gpl(?: |$)' -or
        $capabilities.Configuration -match '(?:^| )--enable-nonfree(?: |$)') {
        throw 'The installed FFmpeg build did not report the expected version and GPL configuration.'
    }
    $revision = $sourceRevision.Groups[1].Value
    $manifest = [ordered]@{
        SchemaVersion = 1
        ArchiveDigest = $digest
        AssetId = $asset.id
        Provider = $provider
        Release = $release.html_url
        Source = "https://github.com/FFmpeg/FFmpeg/commit/$revision"
        SourceRevision = $revision
        Version = $capabilities.Version
        DownloadUrl = ([uri]$archiveUri).GetLeftPart([UriPartial]::Path)
        Files = $files
        Capabilities = $capabilities
    }
    $encoding = [Text.UTF8Encoding]::new($false)
    $metadata = $manifest | ConvertTo-Json -Depth 8 -Compress
    [IO.File]::WriteAllText((Join-Path $payload.FullName 'bundle.json'), $metadata, $encoding)

    $store = $root.CreateSubdirectory('bundles')
    $installed = Join-Path $store.FullName $digest
    if ([IO.Directory]::Exists($installed)) {
        foreach ($name in $files.Keys) {
            $existing = Join-Path $installed $name
            if (!(Test-Path -LiteralPath $existing -PathType Leaf) -or
                (Get-FileHash -LiteralPath $existing -Algorithm SHA256).Hash -ne $files[$name]) {
                throw 'A file in the existing FFmpeg version differs from the verified archive.'
            }
        }
        $saved = Get-Content -LiteralPath (Join-Path $installed 'bundle.json') -Encoding UTF8 -Raw | ConvertFrom-Json
        if ($saved.ArchiveDigest -cne $digest -or $saved.Version -cne $capabilities.Version) {
            throw 'The existing FFmpeg bundle metadata is invalid.'
        }
    }
    else { [IO.Directory]::Move($payload.FullName, $installed) }

    $newPointer = Join-Path $stage.FullName 'current'
    $pointer = Join-Path $root.FullName 'current'
    [IO.File]::WriteAllText($newPointer, $digest, $encoding)
    if ([IO.File]::Exists($pointer)) { [IO.File]::Replace($newPointer, $pointer, [NullString]::Value) }
    else { [IO.File]::Move($newPointer, $pointer) }

    [Console]::OutputEncoding = $encoding
    [Console]::WriteLine((@{
        Path = $installed
        Version = $capabilities.Version
        Source = $manifest.Source
        Capabilities = $capabilities
    } | ConvertTo-Json -Depth 8 -Compress))
}
finally {
    $lock.Dispose()
    if ($stage -and $stage.Parent.FullName -eq $root.FullName -and $stage.Name -match '^download-[a-f0-9]{32}$') {
        Remove-Item -LiteralPath $stage.FullName -Recurse -Force
    }
}