Functions/GenXdev.Software/EnsureFFMPEG.ps1

<##############################################################################
Part of PowerShell module : GenXdev.Software
Original cmdlet filename : EnsureFFMPEG.ps1
Original author : René Vaessen / GenXdev
Version : 3.28.2026
################################################################################
Copyright (c) 2026 René Vaessen / GenXdev

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
################################################################################>


###############################################################################
<#
.SYNOPSIS
Ensures FFmpeg is installed and available on the PATH.

.DESCRIPTION
This function verifies if FFmpeg is installed on the system by checking both
the PATH and the default WinGet installation locations. If not found, it
attempts to install FFmpeg via winget after obtaining user consent. Adds the
FFmpeg directory to the session PATH so that ffmpeg.exe can be invoked
directly.

.EXAMPLE
EnsureFFMPEG
ffmpeg -i input.mp4 -ac 1 -ar 16000 output.wav
#>

function EnsureFFMPEG {

    [CmdletBinding()]
    [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseBOMForUnicodeEncodedFile', '')]
    param(
        #######################################################################
        [Parameter(
            Mandatory = $false,
            HelpMessage = ('Automatically consent to FFmpeg installation ' +
                'and set persistent flag.')
        )]
        [switch] $AutoConsent,

        #######################################################################
        [Parameter(
            Mandatory = $false,
            HelpMessage = ('Automatically consent to third-party software ' +
                'installation and set persistent flag for all packages.')
        )]
        [switch] $AutoConsentAllPackages,

        #######################################################################
        [Parameter(
            Mandatory = $false,
            HelpMessage = ('Only auto consent during session')
        )]
        [switch] $SessionOnly
        #######################################################################
    )

    begin {

        Microsoft.PowerShell.Utility\Write-Verbose 'Ensuring FFmpeg is installed...'

        # known installation locations for ffmpeg via winget
        $wingetLinksPath = "${env:LOCALAPPDATA}\Microsoft\WinGet\Links"
        $ffmpegSymlink = "${wingetLinksPath}\ffmpeg.exe"
    }

    process {

        # check if ffmpeg is available in PATH
        if ((Microsoft.PowerShell.Core\Get-Command 'ffmpeg' -ErrorAction SilentlyContinue).Length -eq 0) {

            $ffmpegFound = $false

            # try the symlink location (fastest)
            if ([System.IO.File]::Exists($ffmpegSymlink)) {

                $ffmpegFound = $true
                $ffmpegDir = $wingetLinksPath
            }

            # fallback to recursive search in winget directory
            if (-not $ffmpegFound) {

                $foundExe = Microsoft.PowerShell.Management\Get-ChildItem `
                    -LiteralPath "${env:LOCALAPPDATA}\Microsoft\WinGet" `
                    -Filter "ffmpeg.exe" `
                    -Recurse -ErrorAction SilentlyContinue |
                    Microsoft.PowerShell.Utility\Select-Object -First 1

                if ($foundExe) {

                    $ffmpegFound = $true
                    $ffmpegDir = [System.IO.Path]::GetDirectoryName(
                        $foundExe.FullName
                    )
                }
            }

            if (-not $ffmpegFound) {

                # FFmpeg not found — need to install
                Microsoft.PowerShell.Utility\Write-Verbose 'FFmpeg not found, attempting installation...'
                Microsoft.PowerShell.Utility\Write-Host 'FFmpeg not found. Installing FFmpeg...'

                # verify winget is available for installation
                if ((Microsoft.PowerShell.Core\Get-Command winget -ErrorAction SilentlyContinue).Length -eq 0) {
                    throw 'FFmpeg is not installed and winget is not available. Please install FFmpeg or winget first.'
                }

                try {
                    # request consent before installing FFmpeg
                    $consentParams = GenXdev\Copy-IdenticalParamValues `
                        -BoundParameters $PSBoundParameters `
                        -FunctionName 'GenXdev\Confirm-InstallationConsent'

                    $consent = GenXdev\Confirm-InstallationConsent `
                        @consentParams `
                        -ApplicationName 'FFmpeg' `
                        -Source 'Winget' `
                        -Description ('Audio/video processing library ' +
                            'required for converting media files to formats ' +
                            'compatible with speech recognition and other ' +
                            'media operations') `
                        -Publisher 'Gyan'

                    if (-not $consent) {
                        throw 'FFmpeg installation was denied by user.'
                    }

                    # install FFmpeg via winget
                    Microsoft.PowerShell.Utility\Write-Verbose 'Installing FFmpeg via winget...'
                    winget install Gyan.FFmpeg

                    # re-check the symlink location after installation
                    if (-not [System.IO.File]::Exists($ffmpegSymlink)) {
                        throw 'FFmpeg installation completed but ffmpeg.exe was not found at the expected location.'
                    }

                    $ffmpegDir = $wingetLinksPath
                    Microsoft.PowerShell.Utility\Write-Host 'FFmpeg installed successfully.'
                }
                catch {
                    Microsoft.PowerShell.Utility\Write-Error "Failed to install FFmpeg. Error: $PSItem"
                    throw
                }
            }

            # add the ffmpeg directory to the session PATH
            if ($ffmpegDir -and ($env:Path -notlike "*${ffmpegDir}*")) {
                $env:Path = "${ffmpegDir};${env:Path}"
                Microsoft.PowerShell.Utility\Write-Verbose "Added FFmpeg directory to PATH: ${ffmpegDir}"
            }
        }

        Microsoft.PowerShell.Utility\Write-Verbose 'FFmpeg is available on PATH.'
    }

    end {
    }
}