Celerium.YTdlp.psm1

#Region './Private/Process/ConvertTo-YTdlpArgumentList.ps1' -1

function ConvertTo-YTdlpArgumentList {
<#
.NOTES
    Copyright 1990-2026 Celerium

    NAME: ConvertTo-YTdlpArgumentList
    Type: Private

        AUTHOR: David Schulte
        DATE: 2025-11-11
        EMAIL: celerium@Celerium.org

    TODO:

.SYNOPSIS
    Converts Invoke-YTdlp parameters into yt-dlp command line arguments

.DESCRIPTION
    The ConvertTo-YTdlpArgumentList function translates the PowerShell parameters
    used by Invoke-YTdlp into the matching yt-dlp command line options.

    - Value parameters become [ --option value ]
    - Switch parameters become [ --option ] only when they are set to true
    - Array values are joined with a comma

.PARAMETER BoundParameter
    The bound parameters ($PSBoundParameters) to convert

.EXAMPLE
    ConvertTo-YTdlpArgumentList -BoundParameter @{ ExtractAudio = [switch]$true; AudioFormat = 'mp3' }

    Returns: --extract-audio --audio-format mp3

.INPUTS
    N/A

.OUTPUTS
    System.String[]

.LINK
    https://github.com/yt-dlp/yt-dlp#usage-and-options
#>


    [CmdletBinding()]
    [OutputType([string[]])]
    param (
        [Parameter(Mandatory = $true)]
        [System.Collections.IDictionary]$BoundParameter
    )

    $ValueOptions = [ordered]@{
        Format              = '--format'
        FormatSort          = '--format-sort'
        MergeOutputFormat   = '--merge-output-format'
        RemuxVideo          = '--remux-video'
        AudioFormat         = '--audio-format'
        AudioQuality        = '--audio-quality'
        OutputTemplate      = '--output'
        OutputPath          = '--paths'
        ConcurrentFragments = '--concurrent-fragments'
        LimitRate           = '--limit-rate'
        Retries             = '--retries'
        PlaylistItems       = '--playlist-items'
        SubtitleLanguages   = '--sub-langs'
        ConvertThumbnails   = '--convert-thumbnails'
        CookiesFromBrowser  = '--cookies-from-browser'
        CookiesFile         = '--cookies'
        DownloadArchive     = '--download-archive'
        Proxy               = '--proxy'
        FfmpegLocation      = '--ffmpeg-location'
    }

    $SwitchOptions = [ordered]@{
        ExtractAudio        = '--extract-audio'
        NoOverwrites        = '--no-overwrites'
        ForceOverwrites     = '--force-overwrites'
        NoPlaylist          = '--no-playlist'
        EmbedMetadata       = '--embed-metadata'
        EmbedThumbnail      = '--embed-thumbnail'
        EmbedChapters       = '--embed-chapters'
        EmbedSubtitles      = '--embed-subs'
        WriteSubtitles      = '--write-subs'
        WriteAutoSubtitles  = '--write-auto-subs'
        WriteThumbnail      = '--write-thumbnail'
        RestrictFilenames   = '--restrict-filenames'
        WindowsFilenames    = '--windows-filenames'
        IgnoreErrors        = '--ignore-errors'
        Simulate            = '--simulate'
        Quiet               = '--quiet'
        NoProgress          = '--no-progress'
    }

    $Arguments = [System.Collections.Generic.List[string]]::new()

    foreach ($Name in $ValueOptions.Keys) {

        if ($BoundParameter.Keys -contains $Name -and $null -ne $BoundParameter[$Name]) {
            $Arguments.Add($ValueOptions[$Name])
            $Arguments.Add(( @($BoundParameter[$Name]) -join ',' ))
        }

    }

    foreach ($Name in $SwitchOptions.Keys) {

        if ($BoundParameter.Keys -contains $Name -and [bool]$BoundParameter[$Name]) {
            $Arguments.Add($SwitchOptions[$Name])
        }

    }

    @($Arguments.ToArray())

}
#EndRegion './Private/Process/ConvertTo-YTdlpArgumentList.ps1' 115
#Region './Private/Process/ConvertTo-YTdlpArgumentString.ps1' -1

function ConvertTo-YTdlpArgumentString {
<#
.NOTES
    Copyright 1990-2026 Celerium

    NAME: ConvertTo-YTdlpArgumentString
    Type: Private

        AUTHOR: David Schulte
        DATE: 2025-11-11
        EMAIL: celerium@Celerium.org

    TODO:

.SYNOPSIS
    Converts an array of arguments into a single command line string

.DESCRIPTION
    The ConvertTo-YTdlpArgumentString function converts an array of arguments into a
    single command line string which is safe to hand to System.Diagnostics.Process.

    Windows PowerShell 5.1 (.NET Framework) does not support ProcessStartInfo.ArgumentList
    so every argument is quoted & escaped using the CommandLineToArgvW rules which
    are also understood by .NET on Linux & macOS.

.PARAMETER Argument
    One or more arguments to convert

.EXAMPLE
    ConvertTo-YTdlpArgumentString -Argument '--output', '%(title)s - %(id)s.%(ext)s'

    Returns: --output "%(title)s - %(id)s.%(ext)s"

.INPUTS
    System.String[]

.OUTPUTS
    System.String

.LINK
    https://github.com/Celerium/Celerium.YTdlp
#>


    [CmdletBinding()]
    [OutputType([string])]
    param (
        [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
        [AllowEmptyString()]
        [string[]]$Argument
    )

    begin {
        $QuotedArguments = [System.Collections.Generic.List[string]]::new()
    }

    process {

        foreach ($Item in $Argument) {

            if ($Item.Length -eq 0) {
                $QuotedArguments.Add('""')
            }
            elseif ($Item -notmatch '[\s"]') {
                $QuotedArguments.Add($Item)
            }
            else {
                #Double the backslashes in front of a quote, escape the quote, then double any trailing backslashes
                $Escaped = $Item -replace '(\\*)"', '$1$1\"'
                $Escaped = $Escaped -replace '(\\+)$', '$1$1'
                $QuotedArguments.Add('"{0}"' -f $Escaped)
            }

        }

    }

    end {
        $QuotedArguments -join ' '
    }

}
#EndRegion './Private/Process/ConvertTo-YTdlpArgumentString.ps1' 82
#Region './Private/Process/Get-YTdlpExecutable.ps1' -1

function Get-YTdlpExecutable {
<#
.NOTES
    Copyright 1990-2026 Celerium

    NAME: Get-YTdlpExecutable
    Type: Private

        AUTHOR: David Schulte
        DATE: 2025-11-11
        EMAIL: celerium@Celerium.org

    TODO:

.SYNOPSIS
    Finds the yt-dlp executable

.DESCRIPTION
    The Get-YTdlpExecutable function finds the yt-dlp executable. If a path
    is supplied it is validated, otherwise the PATH is searched & on Windows the
    default winget locations are checked as well because a freshly installed winget
    package is not always on the PATH of the current session.

.PARAMETER Path
    Defines an explicit path to the yt-dlp executable

.PARAMETER ErrorIfMissing
    Throws an error instead of returning nothing when the executable is not found

.EXAMPLE
    Get-YTdlpExecutable

    Returns the full path to yt-dlp or nothing if yt-dlp is not installed

.EXAMPLE
    Get-YTdlpExecutable -ErrorIfMissing

    Returns the full path to yt-dlp or throws an error if yt-dlp is not installed

.INPUTS
    N/A

.OUTPUTS
    System.String

.LINK
    https://github.com/Celerium/Celerium.YTdlp
#>


    [CmdletBinding()]
    [OutputType([string])]
    param (
        [Parameter(Mandatory = $false)]
        [ValidateNotNullOrEmpty()]
        [string]$Path,

        [Parameter(Mandatory = $false)]
        [switch]$ErrorIfMissing
    )

    if ($Path) {

        if (Test-Path -Path $Path -PathType Leaf) {
            return (Resolve-Path -Path $Path).ProviderPath
        }

        throw "The yt-dlp executable was not found at [ $Path ]"

    }

    $Command = Get-Command -Name 'yt-dlp' -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1
    if ($Command) {
        return $Command.Source
    }

    if ($IsWindows -or $PSEdition -eq 'Desktop') {

        $WingetLinks = Join-Path -Path $env:LOCALAPPDATA -ChildPath 'Microsoft\WinGet\Links\yt-dlp.exe'
        if (Test-Path -Path $WingetLinks -PathType Leaf) {
            return $WingetLinks
        }

        $WingetPackages = Join-Path -Path $env:LOCALAPPDATA -ChildPath 'Microsoft\WinGet\Packages'
        if (Test-Path -Path $WingetPackages -PathType Container) {

            $Package = Get-ChildItem -Path $WingetPackages -Filter 'yt-dlp.yt-dlp*' -Directory -ErrorAction SilentlyContinue |
                        ForEach-Object { Get-ChildItem -Path $_.FullName -Filter 'yt-dlp.exe' -File -ErrorAction SilentlyContinue } |
                            Select-Object -First 1

            if ($Package) {
                return $Package.FullName
            }

        }

    }

    if ($ErrorIfMissing) {
        throw 'yt-dlp was not found. Run Install-YTdlp to install it with winget or use the -ExecutablePath parameter'
    }

}
#EndRegion './Private/Process/Get-YTdlpExecutable.ps1' 103
#Region './Private/Process/Invoke-YTdlpProcess.ps1' -1

function Invoke-YTdlpProcess {
<#
.NOTES
    Copyright 1990-2026 Celerium

    NAME: Invoke-YTdlpProcess
    Type: Private

        AUTHOR: David Schulte
        DATE: 2025-11-11
        EMAIL: celerium@Celerium.org

    TODO:

.SYNOPSIS
    Runs an executable & streams its output

.DESCRIPTION
    The Invoke-YTdlpProcess function runs an executable using System.Diagnostics.Process
    so that the behavior is identical in Windows PowerShell 5.1 & PowerShell 7+ on
    Windows, Linux, & macOS.

    - Output is read as UTF-8 so non-ASCII video titles are not corrupted
    - Standard output is streamed as it arrives, either to the information stream or to the pipeline
    - Standard error is converted to warning, verbose, & error messages
    - A non-zero exit code throws an error

    The information stream is only visible when $InformationPreference is Continue,
    Invoke-YTdlp sets it unless -InformationAction is supplied by the caller.

.PARAMETER FilePath
    The full path to the executable to run

.PARAMETER ArgumentList
    The arguments to pass to the executable

.PARAMETER CaptureOutput
    Returns the standard output lines to the pipeline instead of writing them to the information stream

.PARAMETER IgnoreExitCode
    Defines exit codes which should not be treated as an error

.EXAMPLE
    Invoke-YTdlpProcess -FilePath 'C:\yt-dlp.exe' -ArgumentList '--version' -CaptureOutput

    Runs yt-dlp --version & returns the output

.INPUTS
    N/A

.OUTPUTS
    System.String

.LINK
    https://github.com/Celerium/Celerium.YTdlp
#>


    [CmdletBinding()]
    [OutputType([string])]
    param (
        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [string]$FilePath,

        [Parameter(Mandatory = $false)]
        [AllowEmptyCollection()]
        [string[]]$ArgumentList = @(),

        [Parameter(Mandatory = $false)]
        [switch]$CaptureOutput,

        [Parameter(Mandatory = $false)]
        [int[]]$IgnoreExitCode = @()
    )

    $StartInfo = [System.Diagnostics.ProcessStartInfo]::new()
    $StartInfo.FileName               = $FilePath
    $StartInfo.Arguments              = ConvertTo-YTdlpArgumentString -Argument $ArgumentList
    $StartInfo.UseShellExecute        = $false
    $StartInfo.CreateNoWindow         = $true
    $StartInfo.RedirectStandardOutput = $true
    $StartInfo.RedirectStandardError  = $true
    $StartInfo.StandardOutputEncoding = [System.Text.UTF8Encoding]::new($false)
    $StartInfo.StandardErrorEncoding  = [System.Text.UTF8Encoding]::new($false)

    Write-Verbose "Running [ $FilePath $($StartInfo.Arguments) ]"

    $Process = [System.Diagnostics.Process]::new()
    $Process.StartInfo = $StartInfo

    $ErrorLines = [System.Collections.Generic.List[string]]::new()
    $Started    = $false

    try {

        $Started = $Process.Start()

        #Polling both streams avoids deadlocks & script blocks running on threads without a runspace
        $OutTask = $Process.StandardOutput.ReadLineAsync()
        $ErrTask = $Process.StandardError.ReadLineAsync()

        while ($null -ne $OutTask -or $null -ne $ErrTask) {

            $Idle = $true

            if ($null -ne $OutTask -and $OutTask.IsCompleted) {

                $Idle = $false
                $Line = $OutTask.Result

                if ($null -eq $Line) {
                    $OutTask = $null
                }
                else {
                    if ($CaptureOutput) { $Line } else { Write-Information -MessageData $Line }
                    $OutTask = $Process.StandardOutput.ReadLineAsync()
                }

            }

            if ($null -ne $ErrTask -and $ErrTask.IsCompleted) {

                $Idle = $false
                $Line = $ErrTask.Result

                if ($null -eq $Line) {
                    $ErrTask = $null
                }
                else {

                    switch -Regex ($Line) {
                        '^ERROR:'   { $ErrorLines.Add(($Line -replace '^ERROR:\s*', '')) }
                        '^WARNING:' { Write-Warning ($Line -replace '^WARNING:\s*', '') }
                        default     { Write-Verbose $Line }
                    }

                    $ErrTask = $Process.StandardError.ReadLineAsync()

                }

            }

            if ($Idle) { Start-Sleep -Milliseconds 20 }

        }

        $Process.WaitForExit()
        $ExitCode = $Process.ExitCode

    }
    finally {

        if ($Started -and -not $Process.HasExited) {
            $Process.Kill()
        }
        $Process.Dispose()

    }

    if ($ExitCode -ne 0 -and $ExitCode -notin $IgnoreExitCode) {

        $Message = "The process [ $(Split-Path -Path $FilePath -Leaf) ] exited with code [ $ExitCode ]"
        if ($ErrorLines.Count -gt 0) {
            $Message = "$Message : $($ErrorLines -join ' | ')"
        }

        throw $Message

    }

}
#EndRegion './Private/Process/Invoke-YTdlpProcess.ps1' 172
#Region './Private/Release/Get-YTdlpLatestRelease.ps1' -1

function Get-YTdlpLatestRelease {
<#
.NOTES
    Copyright 1990-2026 Celerium

    NAME: Get-YTdlpLatestRelease
    Type: Private

        AUTHOR: David Schulte
        DATE: 2025-11-11
        EMAIL: celerium@Celerium.org

    TODO:

.SYNOPSIS
    Gets the latest stable yt-dlp release from GitHub

.DESCRIPTION
    The Get-YTdlpLatestRelease function queries the GitHub releases API of the
    yt-dlp project for the latest stable release. The GitHub "latest" release
    never includes pre-releases, drafts, or the separate nightly & master builds.

    When the GITHUB_TOKEN environment variable is present it is used to avoid
    the low anonymous API rate limit, which is helpful on shared CI runners.

.PARAMETER Repository
    The GitHub repository to query

    Default value: yt-dlp/yt-dlp

.EXAMPLE
    Get-YTdlpLatestRelease

    Returns the version, release url, publish date, & asset names of the latest stable release

.INPUTS
    N/A

.OUTPUTS
    System.Management.Automation.PSCustomObject

.LINK
    https://github.com/yt-dlp/yt-dlp/releases/latest
#>


    [CmdletBinding()]
    [OutputType([pscustomobject])]
    param (
        [Parameter(Mandatory = $false)]
        [ValidateNotNullOrEmpty()]
        [string]$Repository = 'yt-dlp/yt-dlp'
    )

    #Windows PowerShell 5.1 does not always negotiate TLS 1.2 which GitHub requires
    if ($PSEdition -eq 'Desktop') {
        [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12
    }

    $Headers = @{
        'Accept'     = 'application/vnd.github+json'
        'User-Agent' = 'Celerium.YTdlp'
    }

    if ($env:GITHUB_TOKEN) {
        $Headers['Authorization'] = "Bearer $env:GITHUB_TOKEN"
    }

    $Uri = "https://api.github.com/repos/$Repository/releases/latest"

    try {
        $Release = Invoke-RestMethod -Uri $Uri -Headers $Headers -Method Get -ErrorAction Stop
    }
    catch {
        throw "Unable to retrieve the latest release from [ $Uri ] - $($_.Exception.Message)"
    }

    [pscustomobject]@{
        Version     = [string]$Release.tag_name
        Url         = [string]$Release.html_url
        PublishedAt = $Release.published_at
        Assets      = @($Release.assets.name)
    }

}
#EndRegion './Private/Release/Get-YTdlpLatestRelease.ps1' 85
#Region './Private/Winget/Invoke-YTdlpWinget.ps1' -1

function Invoke-YTdlpWinget {
<#
.NOTES
    Copyright 1990-2026 Celerium

    NAME: Invoke-YTdlpWinget
    Type: Private

        AUTHOR: David Schulte
        DATE: 2025-11-11
        EMAIL: celerium@Celerium.org

    TODO:

.SYNOPSIS
    Runs the Windows Package Manager (winget)

.DESCRIPTION
    The Invoke-YTdlpWinget function runs winget with the supplied arguments & returns
    the exit code. winget is only available on Windows so an error is thrown on
    any other platform or if winget is not installed.

    These winget exit codes are not treated as failures by callers:
        -1978335189 (0x8A15002B) - No applicable update found
        -1978335135 (0x8A150061) - Package already installed

.PARAMETER ArgumentList
    The arguments to pass to winget

.EXAMPLE
    Invoke-YTdlpWinget -ArgumentList 'install', '--id', 'yt-dlp.yt-dlp', '--exact'

    Installs yt-dlp using winget & returns the winget exit code

.INPUTS
    N/A

.OUTPUTS
    System.Int32

.LINK
    https://learn.microsoft.com/en-us/windows/package-manager/winget/
#>


    [CmdletBinding()]
    [OutputType([int])]
    param (
        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [string[]]$ArgumentList
    )

    if (-not ($IsWindows -or $PSEdition -eq 'Desktop')) {
        throw 'winget is only available on Windows'
    }

    $Winget = Get-Command -Name 'winget' -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1
    if (-not $Winget) {
        throw 'winget was not found. Install the Windows App Installer from the Microsoft Store or https://aka.ms/getwinget'
    }

    Write-Verbose "Running [ winget $($ArgumentList -join ' ') ]"

    & $Winget.Source @ArgumentList | Out-Host

    $LASTEXITCODE

}
#EndRegion './Private/Winget/Invoke-YTdlpWinget.ps1' 69
#Region './Public/Get-YTdlpVersion.ps1' -1

function Get-YTdlpVersion {
<#
.NOTES
    Copyright 1990-2026 Celerium

    NAME: Get-YTdlpVersion
    Type: Public

        AUTHOR: David Schulte
        DATE: 2025-11-11
        EMAIL: celerium@Celerium.org

    TODO:

.SYNOPSIS
    Compares the local yt-dlp version to the latest stable version

.DESCRIPTION
    The Get-YTdlpVersion function gets the version of the locally installed yt-dlp,
    gets the version of the latest stable yt-dlp release from GitHub, & compares them.

    The status property will be one of:
        NotInstalled - yt-dlp could not be found
        UpToDate - The local version is the same as, or newer than, the latest stable release
        UpdateAvailable - A newer stable release is available
        Unknown - The versions could not be compared, for example when offline

.PARAMETER ExecutablePath
    Defines an explicit path to the yt-dlp executable

    By default yt-dlp is found using the PATH & the default winget locations

.PARAMETER SkipOnlineCheck
    Only get the local version & do not contact GitHub

.EXAMPLE
    Get-YTdlpVersion

    Returns the installed version, the latest stable version, & whether an update is available

.EXAMPLE
    (Get-YTdlpVersion).UpdateAvailable

    Returns true if a newer stable version of yt-dlp has been released

.EXAMPLE
    Get-YTdlpVersion -SkipOnlineCheck

    Returns only the local version information without contacting GitHub

.INPUTS
    N/A

.OUTPUTS
    Celerium.YTdlp.Version

.LINK
    https://github.com/yt-dlp/yt-dlp/releases/latest

.LINK
    https://github.com/Celerium/Celerium.YTdlp
#>


    [CmdletBinding()]
    [OutputType('Celerium.YTdlp.Version')]
    param (
        [Parameter(Mandatory = $false)]
        [ValidateNotNullOrEmpty()]
        [string]$ExecutablePath,

        [Parameter(Mandatory = $false)]
        [switch]$SkipOnlineCheck
    )

    $ExecutableParameter = @{}
    if ($ExecutablePath) { $ExecutableParameter['Path'] = $ExecutablePath }

    $Path = Get-YTdlpExecutable @ExecutableParameter

    $InstalledVersion = $null
    if ($Path) {
        $InstalledVersion = (Invoke-YTdlpProcess -FilePath $Path -ArgumentList '--version' -CaptureOutput | Select-Object -First 1).Trim()
    }

    $LatestVersion = $null
    $ReleaseUrl    = $null

    if (-not $SkipOnlineCheck) {

        try {
            $Release       = Get-YTdlpLatestRelease
            $LatestVersion = $Release.Version
            $ReleaseUrl    = $Release.Url
        }
        catch {
            Write-Warning "Unable to check for the latest yt-dlp version - $($_.Exception.Message)"
        }

    }

    $Status          = 'Unknown'
    $UpdateAvailable = $false

    if (-not $Path) {
        $Status = 'NotInstalled'
    }
    else {

        $Installed = $null
        $Latest    = $null

        if ([version]::TryParse($InstalledVersion, [ref]$Installed) -and [version]::TryParse($LatestVersion, [ref]$Latest)) {

            if ($Installed -lt $Latest) {
                $Status          = 'UpdateAvailable'
                $UpdateAvailable = $true
            }
            else {
                $Status = 'UpToDate'
            }

        }

    }

    [pscustomobject]@{
        PSTypeName       = 'Celerium.YTdlp.Version'
        InstalledVersion = $InstalledVersion
        LatestVersion    = $LatestVersion
        UpdateAvailable  = $UpdateAvailable
        Status           = $Status
        Path             = $Path
        ReleaseUrl       = $ReleaseUrl
    }

}
#EndRegion './Public/Get-YTdlpVersion.ps1' 137
#Region './Public/Get-YTdlpVideoInfo.ps1' -1

function Get-YTdlpVideoInfo {
<#
.NOTES
    Copyright 1990-2026 Celerium

    NAME: Get-YTdlpVideoInfo
    Type: Public

        AUTHOR: David Schulte
        DATE: 2025-11-11
        EMAIL: celerium@Celerium.org

    TODO:

.SYNOPSIS
    Gets the metadata of a video without downloading it

.DESCRIPTION
    The Get-YTdlpVideoInfo function gets the metadata of a video, such as the title,
    uploader, duration, & available formats, as a PowerShell object without downloading
    the video. It uses the yt-dlp --dump-single-json option.

.PARAMETER Url
    One or more URLs to get metadata for

.PARAMETER NoPlaylist
    Only get the video if the URL refers to a video & a playlist

.PARAMETER CookiesFromBrowser
    The browser to load cookies from

    Example: firefox or chrome:Profile 1

.PARAMETER ExecutablePath
    Defines an explicit path to the yt-dlp executable

.PARAMETER AdditionalArguments
    Any additional raw yt-dlp command line arguments

.EXAMPLE
    Get-YTdlpVideoInfo -Url 'https://www.youtube.com/watch?v=cE0wfjsybIQ'

    Returns the metadata of the video

.EXAMPLE
    (Get-YTdlpVideoInfo -Url 'https://www.youtube.com/watch?v=cE0wfjsybIQ').formats | Select-Object format_id, resolution, vcodec, acodec

    Lists the formats available for the video

.INPUTS
    System.String

.OUTPUTS
    System.Management.Automation.PSCustomObject

.LINK
    https://github.com/yt-dlp/yt-dlp#output-template

.LINK
    https://github.com/Celerium/Celerium.YTdlp
#>


    [CmdletBinding()]
    [OutputType([pscustomobject])]
    param (
        [Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
        [ValidateNotNullOrEmpty()]
        [Alias('Uri')]
        [string[]]$Url,

        [Parameter(Mandatory = $false)]
        [switch]$NoPlaylist,

        [Parameter(Mandatory = $false)]
        [ValidateNotNullOrEmpty()]
        [string]$CookiesFromBrowser,

        [Parameter(Mandatory = $false)]
        [ValidateNotNullOrEmpty()]
        [string]$ExecutablePath,

        [Parameter(Mandatory = $false)]
        [string[]]$AdditionalArguments
    )

    begin {

        $ExecutableParameter = @{ ErrorIfMissing = $true }
        if ($ExecutablePath) { $ExecutableParameter['Path'] = $ExecutablePath }

        $Executable = Get-YTdlpExecutable @ExecutableParameter

    }

    process {

        $Arguments = [System.Collections.Generic.List[string]]::new()
        $Arguments.AddRange([string[]]@(ConvertTo-YTdlpArgumentList -BoundParameter $PSBoundParameters))
        $Arguments.Add('--dump-single-json')

        if ($AdditionalArguments) {
            $Arguments.AddRange([string[]]$AdditionalArguments)
        }

        foreach ($Item in $Url) {

            $Json = Invoke-YTdlpProcess -FilePath $Executable -ArgumentList ($Arguments.ToArray() + '--', $Item) -CaptureOutput

            ($Json -join "`n") | ConvertFrom-Json

        }

    }

}
#EndRegion './Public/Get-YTdlpVideoInfo.ps1' 116
#Region './Public/Install-YTdlp.ps1' -1

function Install-YTdlp {
<#
.NOTES
    Copyright 1990-2026 Celerium

    NAME: Install-YTdlp
    Type: Public

        AUTHOR: David Schulte
        DATE: 2025-11-11
        EMAIL: celerium@Celerium.org

    TODO:

.SYNOPSIS
    Installs yt-dlp using winget

.DESCRIPTION
    The Install-YTdlp function installs yt-dlp using the Windows Package Manager (winget)
    package [ yt-dlp.yt-dlp ].

    The winget package declares FFmpeg & Deno as dependencies so they are installed
    alongside yt-dlp. FFmpeg is required to merge video & audio streams, convert audio,
    & embed metadata. A JavaScript runtime is required by some sites.

    winget is only available on Windows. On Linux & macOS install yt-dlp with the package
    manager of the platform, for example [ brew install yt-dlp ].

    The current session PATH is not always updated by winget, the module also searches
    the default winget locations so the other functions work immediately after install.

.PARAMETER Force
    Reinstall yt-dlp even if it is already installed

.EXAMPLE
    Install-YTdlp

    Installs yt-dlp using winget if it is not already installed

.EXAMPLE
    Install-YTdlp -Force -Verbose

    Reinstalls yt-dlp using winget & shows the winget command that is run

.EXAMPLE
    Install-YTdlp -WhatIf

    Shows what would happen without installing anything

.INPUTS
    N/A

.OUTPUTS
    Celerium.YTdlp.Version

.LINK
    https://github.com/yt-dlp/yt-dlp/wiki/Installation

.LINK
    https://github.com/Celerium/Celerium.YTdlp
#>


    [CmdletBinding(SupportsShouldProcess = $true)]
    [OutputType('Celerium.YTdlp.Version')]
    param (
        [Parameter(Mandatory = $false)]
        [switch]$Force
    )

    if (-not ($IsWindows -or $PSEdition -eq 'Desktop')) {
        throw 'Install-YTdlp uses winget which is only available on Windows. Install yt-dlp with your package manager, for example [ brew install yt-dlp ], see https://github.com/yt-dlp/yt-dlp/wiki/Installation'
    }

    $Current = Get-YTdlpVersion -SkipOnlineCheck

    if ($Current.Path -and -not $Force) {
        Write-Verbose "yt-dlp [ $($Current.InstalledVersion) ] is already installed at [ $($Current.Path) ]. Use -Force to reinstall"
        return $Current
    }

    $WingetArguments = @(
        'install'
        '--id', 'yt-dlp.yt-dlp'
        '--exact'
        '--source', 'winget'
        '--silent'
        '--accept-package-agreements'
        '--accept-source-agreements'
    )

    if ($Force) { $WingetArguments += '--force' }

    if ($PSCmdlet.ShouldProcess('yt-dlp.yt-dlp', 'Install with winget')) {

        $ExitCode = Invoke-YTdlpWinget -ArgumentList $WingetArguments

        #-1978335135 = package already installed
        if ($ExitCode -ne 0 -and $ExitCode -ne -1978335135) {
            throw "winget failed to install yt-dlp with exit code [ $ExitCode ]"
        }

        Get-YTdlpVersion

    }

}
#EndRegion './Public/Install-YTdlp.ps1' 107
#Region './Public/Invoke-YTdlp.ps1' -1

function Invoke-YTdlp {
<#
.NOTES
    Copyright 1990-2026 Celerium

    NAME: Invoke-YTdlp
    Type: Public

        AUTHOR: David Schulte
        DATE: 2025-11-11
        EMAIL: celerium@Celerium.org

    TODO:

.SYNOPSIS
    Runs yt-dlp with PowerShell parameters

.DESCRIPTION
    The Invoke-YTdlp function is the core wrapper around the yt-dlp command line
    tool. The most commonly used yt-dlp options are exposed as PowerShell parameters &
    any other option can be supplied with the -AdditionalArguments parameter.

    - Progress is written to the information stream, use -Quiet to hide it
    - Using -Verbose adds the yt-dlp --verbose option
    - A non-zero yt-dlp exit code throws an error
    - Relative paths are resolved against the current PowerShell location
    - URLs are always passed after [ -- ] so a URL can never be treated as an option

    The Save-YTdlpVideo & Save-YTdlpAudio functions use this function with
    pre-configured highest quality settings.

.PARAMETER Url
    One or more URLs (or yt-dlp search strings such as ytsearch:) to process

.PARAMETER ExecutablePath
    Defines an explicit path to the yt-dlp executable

.PARAMETER Format
    Video format selection

    Example: bestvideo*+bestaudio/best

.PARAMETER FormatSort
    Sort order used to pick the best format

    Example: res,fps,hdr,vcodec,acodec,br

.PARAMETER MergeOutputFormat
    Container used when video & audio streams are merged

    Allowed values:
        'avi', 'flv', 'mkv', 'mov', 'mp4', 'webm'

.PARAMETER RemuxVideo
    Remux the video into another container if necessary

    Example: mp4

.PARAMETER ExtractAudio
    Convert the video to an audio only file

.PARAMETER AudioFormat
    Audio format used when -ExtractAudio is set

    Allowed values:
        'best', 'aac', 'alac', 'flac', 'm4a', 'mp3', 'opus', 'vorbis', 'wav'

.PARAMETER AudioQuality
    Audio quality used when -ExtractAudio is set

    A value from 0 (best) to 10 (worst) for variable bitrate, or a bitrate such as 128K

.PARAMETER OutputTemplate
    The yt-dlp output filename template

    Example: %(title)s.%(ext)s

.PARAMETER OutputPath
    The directory files are saved to

    Default value: The current PowerShell location

.PARAMETER ConcurrentFragments
    The number of fragments of a DASH/HLS video to download concurrently

.PARAMETER LimitRate
    The maximum download rate in bytes per second

    Example: 50K or 4.2M

.PARAMETER Retries
    The number of retries

.PARAMETER PlaylistItems
    The playlist items to download

    Example: 1:3,7,-5::2

.PARAMETER NoOverwrites
    Do not overwrite files that already exist

.PARAMETER ForceOverwrites
    Overwrite all video & metadata files

.PARAMETER NoPlaylist
    Download only the video if the URL refers to a video & a playlist

.PARAMETER EmbedMetadata
    Embed metadata & chapters in the file

.PARAMETER EmbedThumbnail
    Embed the thumbnail in the file as cover art

.PARAMETER EmbedChapters
    Add chapter markers to the file

.PARAMETER EmbedSubtitles
    Embed subtitles in the file

.PARAMETER WriteSubtitles
    Write subtitle files

.PARAMETER WriteAutoSubtitles
    Write automatically generated subtitle files

.PARAMETER SubtitleLanguages
    The subtitle languages to download

    Example: en.*,ja

.PARAMETER WriteThumbnail
    Write the thumbnail image to disk

.PARAMETER ConvertThumbnails
    Convert the thumbnails to another format

    Example: jpg

.PARAMETER CookiesFromBrowser
    The browser to load cookies from

    Example: firefox or chrome:Profile 1

.PARAMETER CookiesFile
    A Netscape formatted cookies file

.PARAMETER DownloadArchive
    A file used to record & skip videos that have already been downloaded

.PARAMETER Proxy
    A HTTP, HTTPS, or SOCKS proxy URL

.PARAMETER FfmpegLocation
    The location of the ffmpeg binary or its directory

.PARAMETER RestrictFilenames
    Restrict filenames to only ASCII characters

.PARAMETER WindowsFilenames
    Force filenames to be Windows compatible

.PARAMETER IgnoreErrors
    Ignore download & post-processing errors

.PARAMETER Simulate
    Do not download or write anything to disk

.PARAMETER Quiet
    Hide yt-dlp progress & informational output

.PARAMETER NoProgress
    Do not show the yt-dlp progress bar

.PARAMETER AdditionalArguments
    Any additional raw yt-dlp command line arguments

    Example: '--sponsorblock-remove', 'sponsor'

.PARAMETER PassThru
    Returns a file object for every file that was saved

.EXAMPLE
    Invoke-YTdlp -Url 'https://www.youtube.com/watch?v=cE0wfjsybIQ' -Format 'bestvideo*+bestaudio/best' -MergeOutputFormat mkv

    Downloads the best quality video & audio and merges them into a mkv file in the current directory

.EXAMPLE
    Invoke-YTdlp -Url 'https://www.youtube.com/watch?v=cE0wfjsybIQ' -ExtractAudio -AudioFormat mp3 -ConcurrentFragments 12 -NoOverwrites -EmbedMetadata -OutputTemplate '%(title)s.%(ext)s' -Verbose

    Matches the yt-dlp command [ yt-dlp $Url -x --audio-format mp3 -N 12 -w -v --embed-metadata -o "%(title)s.%(ext)s" ]

.EXAMPLE
    Invoke-YTdlp -Url 'https://www.youtube.com/watch?v=cE0wfjsybIQ' -Simulate -AdditionalArguments '--print', 'title'

    Prints the title of the video without downloading it

.EXAMPLE
    Invoke-YTdlp -Url 'https://www.youtube.com/watch?v=cE0wfjsybIQ' -Format 'bestaudio' -WhatIf

    Shows the yt-dlp command line that would be run without running it

.INPUTS
    System.String

.OUTPUTS
    System.IO.FileInfo

.LINK
    https://github.com/yt-dlp/yt-dlp#usage-and-options

.LINK
    https://github.com/Celerium/Celerium.YTdlp
#>


    [CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'Low')]
    [OutputType([System.IO.FileInfo])]
    param (
        [Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
        [ValidateNotNullOrEmpty()]
        [Alias('Uri')]
        [string[]]$Url,

        [Parameter(Mandatory = $false)]
        [ValidateNotNullOrEmpty()]
        [string]$ExecutablePath,

        [Parameter(Mandatory = $false)]
        [ValidateNotNullOrEmpty()]
        [string]$Format,

        [Parameter(Mandatory = $false)]
        [ValidateNotNullOrEmpty()]
        [string]$FormatSort,

        [Parameter(Mandatory = $false)]
        [ValidateSet('avi', 'flv', 'mkv', 'mov', 'mp4', 'webm')]
        [string]$MergeOutputFormat,

        [Parameter(Mandatory = $false)]
        [ValidateNotNullOrEmpty()]
        [string]$RemuxVideo,

        [Parameter(Mandatory = $false)]
        [switch]$ExtractAudio,

        [Parameter(Mandatory = $false)]
        [ValidateSet('best', 'aac', 'alac', 'flac', 'm4a', 'mp3', 'opus', 'vorbis', 'wav')]
        [string]$AudioFormat,

        [Parameter(Mandatory = $false)]
        [ValidatePattern('^(10|[0-9])$|^\d+[kK]$')]
        [string]$AudioQuality,

        [Parameter(Mandatory = $false)]
        [ValidateNotNullOrEmpty()]
        [string]$OutputTemplate,

        [Parameter(Mandatory = $false)]
        [ValidateNotNullOrEmpty()]
        [string]$OutputPath,

        [Parameter(Mandatory = $false)]
        [ValidateRange(1, 64)]
        [int]$ConcurrentFragments,

        [Parameter(Mandatory = $false)]
        [ValidateNotNullOrEmpty()]
        [string]$LimitRate,

        [Parameter(Mandatory = $false)]
        [ValidateRange(0, 1000)]
        [int]$Retries,

        [Parameter(Mandatory = $false)]
        [ValidateNotNullOrEmpty()]
        [string]$PlaylistItems,

        [Parameter(Mandatory = $false)]
        [switch]$NoOverwrites,

        [Parameter(Mandatory = $false)]
        [switch]$ForceOverwrites,

        [Parameter(Mandatory = $false)]
        [switch]$NoPlaylist,

        [Parameter(Mandatory = $false)]
        [switch]$EmbedMetadata,

        [Parameter(Mandatory = $false)]
        [switch]$EmbedThumbnail,

        [Parameter(Mandatory = $false)]
        [switch]$EmbedChapters,

        [Parameter(Mandatory = $false)]
        [switch]$EmbedSubtitles,

        [Parameter(Mandatory = $false)]
        [switch]$WriteSubtitles,

        [Parameter(Mandatory = $false)]
        [switch]$WriteAutoSubtitles,

        [Parameter(Mandatory = $false)]
        [ValidateNotNullOrEmpty()]
        [string[]]$SubtitleLanguages,

        [Parameter(Mandatory = $false)]
        [switch]$WriteThumbnail,

        [Parameter(Mandatory = $false)]
        [ValidateSet('jpg', 'png', 'webp')]
        [string]$ConvertThumbnails,

        [Parameter(Mandatory = $false)]
        [ValidateNotNullOrEmpty()]
        [string]$CookiesFromBrowser,

        [Parameter(Mandatory = $false)]
        [ValidateNotNullOrEmpty()]
        [string]$CookiesFile,

        [Parameter(Mandatory = $false)]
        [ValidateNotNullOrEmpty()]
        [string]$DownloadArchive,

        [Parameter(Mandatory = $false)]
        [ValidateNotNullOrEmpty()]
        [string]$Proxy,

        [Parameter(Mandatory = $false)]
        [ValidateNotNullOrEmpty()]
        [string]$FfmpegLocation,

        [Parameter(Mandatory = $false)]
        [switch]$RestrictFilenames,

        [Parameter(Mandatory = $false)]
        [switch]$WindowsFilenames,

        [Parameter(Mandatory = $false)]
        [switch]$IgnoreErrors,

        [Parameter(Mandatory = $false)]
        [switch]$Simulate,

        [Parameter(Mandatory = $false)]
        [switch]$Quiet,

        [Parameter(Mandatory = $false)]
        [switch]$NoProgress,

        [Parameter(Mandatory = $false)]
        [string[]]$AdditionalArguments,

        [Parameter(Mandatory = $false)]
        [switch]$PassThru
    )

    begin {

        $ExecutableParameter = @{ ErrorIfMissing = $true }
        if ($ExecutablePath) { $ExecutableParameter['Path'] = $ExecutablePath }

        $Executable = Get-YTdlpExecutable @ExecutableParameter

        #yt-dlp runs in the process working directory which is not the PowerShell location
        $ResolvePath = { param ($Path) $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Path) }

        #Show yt-dlp progress by default, -InformationAction SilentlyContinue or -Quiet hides it
        if (-not $PSBoundParameters.ContainsKey('InformationAction')) {
            $InformationPreference = 'Continue'
        }

    }

    process {

        $Bound = @{}
        foreach ($Key in $PSBoundParameters.Keys) { $Bound[$Key] = $PSBoundParameters[$Key] }

        if (-not $Bound.ContainsKey('OutputPath')) {
            $Bound['OutputPath'] = (Get-Location).ProviderPath
        }

        foreach ($Key in 'OutputPath', 'CookiesFile', 'DownloadArchive') {
            if ($Bound.ContainsKey($Key)) { $Bound[$Key] = & $ResolvePath $Bound[$Key] }
        }

        $Arguments = [System.Collections.Generic.List[string]]::new()
        $Arguments.AddRange([string[]]@(ConvertTo-YTdlpArgumentList -BoundParameter $Bound))

        #Progress as individual lines instead of a carriage return rewritten line
        $Arguments.Add('--newline')

        if ($VerbosePreference -eq 'Continue') {
            $Arguments.Add('--verbose')
        }

        $TempFile = $null
        if ($PassThru -and -not $Simulate) {
            $TempFile = [System.IO.Path]::GetTempFileName()
            $Arguments.Add('--print-to-file')
            $Arguments.Add('after_move:filepath')
            $Arguments.Add($TempFile)
        }

        if ($AdditionalArguments) {
            $Arguments.AddRange([string[]]$AdditionalArguments)
        }

        $Arguments.Add('--')
        $Arguments.AddRange([string[]]$Url)

        try {

            if ($PSCmdlet.ShouldProcess(($Url -join ', '), "yt-dlp $(ConvertTo-YTdlpArgumentString -Argument $Arguments.ToArray())")) {

                Invoke-YTdlpProcess -FilePath $Executable -ArgumentList $Arguments.ToArray()

                if ($TempFile -and (Test-Path -Path $TempFile -PathType Leaf)) {

                    Get-Content -Path $TempFile -Encoding UTF8 |
                        Where-Object { $_ -and (Test-Path -LiteralPath $_ -PathType Leaf) } |
                            ForEach-Object { Get-Item -LiteralPath $_ }

                }

            }

        }
        finally {

            if ($TempFile -and (Test-Path -Path $TempFile)) {
                Remove-Item -Path $TempFile -Force -ErrorAction SilentlyContinue -WhatIf:$false
            }

        }

    }

}
#EndRegion './Public/Invoke-YTdlp.ps1' 444
#Region './Public/Save-YTdlpAudio.ps1' -1

function Save-YTdlpAudio {
<#
.NOTES
    Copyright 1990-2026 Celerium

    NAME: Save-YTdlpAudio
    Type: Public

        AUTHOR: David Schulte
        DATE: 2025-11-11
        EMAIL: celerium@Celerium.org

    TODO:

.SYNOPSIS
    Downloads a video as an audio file using the highest quality settings

.DESCRIPTION
    The Save-YTdlpAudio function downloads the best available audio of a video &
    converts it to an audio format such as mp3 using the highest quality settings.

    The following yt-dlp options are used:
        --format "bestaudio/best"
        --extract-audio --audio-format mp3 --audio-quality 0
        --concurrent-fragments 12
        --embed-metadata --embed-thumbnail --convert-thumbnails jpg

    FFmpeg is required to convert the audio, use Install-YTdlp to
    install yt-dlp along with FFmpeg using winget.

.PARAMETER Url
    One or more URLs of the videos to download

.PARAMETER OutputPath
    The directory files are saved to

    Default value: The current PowerShell location

.PARAMETER OutputTemplate
    The yt-dlp output filename template

    Default value: %(title)s.%(ext)s

.PARAMETER AudioFormat
    The audio format to convert to

    Default value: mp3

    Allowed values:
        'best', 'aac', 'alac', 'flac', 'm4a', 'mp3', 'opus', 'vorbis', 'wav'

.PARAMETER AudioQuality
    A value from 0 (best) to 10 (worst) for variable bitrate, or a bitrate such as 320K

    Default value: 0

.PARAMETER ConcurrentFragments
    The number of fragments of a DASH/HLS video to download concurrently

    Default value: 12

.PARAMETER NoOverwrites
    Do not overwrite files that already exist

.PARAMETER NoPlaylist
    Download only the video if the URL refers to a video & a playlist

.PARAMETER CookiesFromBrowser
    The browser to load cookies from

    Example: firefox or chrome:Profile 1

.PARAMETER ExecutablePath
    Defines an explicit path to the yt-dlp executable

.PARAMETER FfmpegLocation
    The location of the ffmpeg binary or its directory

    Only needed when ffmpeg is not found on the PATH

.PARAMETER AdditionalArguments
    Any additional raw yt-dlp command line arguments

.EXAMPLE
    Save-YTdlpAudio -Url 'https://www.youtube.com/watch?v=cE0wfjsybIQ'

    Downloads the audio of the video as the highest quality mp3 into the current directory

.EXAMPLE
    Save-YTdlpAudio -Url 'https://www.youtube.com/watch?v=cE0wfjsybIQ' -AudioFormat flac -OutputPath 'C:\Music' -NoOverwrites -Verbose

    Downloads the audio as a flac file, saves it to C:\Music, & skips files that already exist

.EXAMPLE
    'https://www.youtube.com/watch?v=cE0wfjsybIQ' | Save-YTdlpAudio -WhatIf

    Shows the yt-dlp command line that would be run without downloading anything

.INPUTS
    System.String

.OUTPUTS
    System.IO.FileInfo

.LINK
    https://github.com/yt-dlp/yt-dlp#post-processing-options

.LINK
    https://github.com/Celerium/Celerium.YTdlp
#>


    [CmdletBinding(SupportsShouldProcess = $true)]
    [OutputType([System.IO.FileInfo])]
    param (
        [Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
        [ValidateNotNullOrEmpty()]
        [Alias('Uri')]
        [string[]]$Url,

        [Parameter(Mandatory = $false)]
        [ValidateNotNullOrEmpty()]
        [string]$OutputPath,

        [Parameter(Mandatory = $false)]
        [ValidateNotNullOrEmpty()]
        [string]$OutputTemplate = '%(title)s.%(ext)s',

        [Parameter(Mandatory = $false)]
        [ValidateSet('best', 'aac', 'alac', 'flac', 'm4a', 'mp3', 'opus', 'vorbis', 'wav')]
        [string]$AudioFormat = 'mp3',

        [Parameter(Mandatory = $false)]
        [ValidatePattern('^(10|[0-9])$|^\d+[kK]$')]
        [string]$AudioQuality = '0',

        [Parameter(Mandatory = $false)]
        [ValidateRange(1, 64)]
        [int]$ConcurrentFragments = 12,

        [Parameter(Mandatory = $false)]
        [switch]$NoOverwrites,

        [Parameter(Mandatory = $false)]
        [switch]$NoPlaylist,

        [Parameter(Mandatory = $false)]
        [ValidateNotNullOrEmpty()]
        [string]$CookiesFromBrowser,

        [Parameter(Mandatory = $false)]
        [ValidateNotNullOrEmpty()]
        [string]$ExecutablePath,

        [Parameter(Mandatory = $false)]
        [ValidateNotNullOrEmpty()]
        [string]$FfmpegLocation,

        [Parameter(Mandatory = $false)]
        [string[]]$AdditionalArguments
    )

    process {

        $InvokeParameter = @{
            Url                 = $Url
            Format              = 'bestaudio/best'
            ExtractAudio        = $true
            AudioFormat         = $AudioFormat
            AudioQuality        = $AudioQuality
            OutputTemplate      = $OutputTemplate
            ConcurrentFragments = $ConcurrentFragments
            EmbedMetadata       = $true
            EmbedThumbnail      = $true
            ConvertThumbnails   = 'jpg'
            PassThru            = $true
        }

        $OptionalParameters = 'OutputPath', 'NoOverwrites', 'NoPlaylist', 'CookiesFromBrowser', 'ExecutablePath', 'FfmpegLocation', 'AdditionalArguments', 'InformationAction'
        foreach ($Name in $OptionalParameters) {
            if ($PSBoundParameters.ContainsKey($Name)) { $InvokeParameter[$Name] = $PSBoundParameters[$Name] }
        }

        if ($PSCmdlet.ShouldProcess(($Url -join ', '), 'Download the highest quality audio')) {
            Invoke-YTdlp @InvokeParameter -Confirm:$false
        }

    }

}
#EndRegion './Public/Save-YTdlpAudio.ps1' 190
#Region './Public/Save-YTdlpVideo.ps1' -1

function Save-YTdlpVideo {
<#
.NOTES
    Copyright 1990-2026 Celerium

    NAME: Save-YTdlpVideo
    Type: Public

        AUTHOR: David Schulte
        DATE: 2025-11-11
        EMAIL: celerium@Celerium.org

    TODO:

.SYNOPSIS
    Downloads a video using the highest quality settings

.DESCRIPTION
    The Save-YTdlpVideo function downloads a video using the highest quality settings.

    The following yt-dlp options are used:
        --format "bestvideo*+bestaudio/best"
        --format-sort "res,fps,hdr,vcodec,acodec,br"
        --merge-output-format mkv
        --concurrent-fragments 12
        --embed-metadata --embed-chapters --embed-thumbnail --convert-thumbnails jpg

    FFmpeg is required to merge the video & audio streams, use Install-YTdlp to
    install yt-dlp along with FFmpeg using winget.

.PARAMETER Url
    One or more URLs of the videos to download

.PARAMETER OutputPath
    The directory files are saved to

    Default value: The current PowerShell location

.PARAMETER OutputTemplate
    The yt-dlp output filename template

    Default value: %(title)s.%(ext)s

.PARAMETER MergeOutputFormat
    Container used when video & audio streams are merged

    mkv supports every codec so it is the default to avoid re-encoding

    Default value: mkv

    Allowed values:
        'avi', 'flv', 'mkv', 'mov', 'mp4', 'webm'

.PARAMETER FormatSort
    Sort order used to pick the best format

    Default value: res,fps,hdr,vcodec,acodec,br

.PARAMETER ConcurrentFragments
    The number of fragments of a DASH/HLS video to download concurrently

    Default value: 12

.PARAMETER NoOverwrites
    Do not overwrite files that already exist

.PARAMETER NoPlaylist
    Download only the video if the URL refers to a video & a playlist

.PARAMETER EmbedSubtitles
    Embed subtitles in the file

.PARAMETER SubtitleLanguages
    The subtitle languages to download

    Example: en.*,ja

.PARAMETER CookiesFromBrowser
    The browser to load cookies from

    Example: firefox or chrome:Profile 1

.PARAMETER ExecutablePath
    Defines an explicit path to the yt-dlp executable

.PARAMETER FfmpegLocation
    The location of the ffmpeg binary or its directory

    Only needed when ffmpeg is not found on the PATH

.PARAMETER AdditionalArguments
    Any additional raw yt-dlp command line arguments

.EXAMPLE
    Save-YTdlpVideo -Url 'https://www.youtube.com/watch?v=cE0wfjsybIQ'

    Downloads the video using the highest settings into the current directory

.EXAMPLE
    Save-YTdlpVideo -Url 'https://www.youtube.com/watch?v=cE0wfjsybIQ' -OutputPath 'C:\Videos' -MergeOutputFormat mp4 -NoPlaylist

    Downloads the video, merges it into a mp4, & saves it to C:\Videos

.EXAMPLE
    'https://www.youtube.com/watch?v=cE0wfjsybIQ' | Save-YTdlpVideo -WhatIf

    Shows the yt-dlp command line that would be run without downloading anything

.INPUTS
    System.String

.OUTPUTS
    System.IO.FileInfo

.LINK
    https://github.com/yt-dlp/yt-dlp#format-selection

.LINK
    https://github.com/Celerium/Celerium.YTdlp
#>


    [CmdletBinding(SupportsShouldProcess = $true)]
    [OutputType([System.IO.FileInfo])]
    param (
        [Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
        [ValidateNotNullOrEmpty()]
        [Alias('Uri')]
        [string[]]$Url,

        [Parameter(Mandatory = $false)]
        [ValidateNotNullOrEmpty()]
        [string]$OutputPath,

        [Parameter(Mandatory = $false)]
        [ValidateNotNullOrEmpty()]
        [string]$OutputTemplate = '%(title)s.%(ext)s',

        [Parameter(Mandatory = $false)]
        [ValidateSet('avi', 'flv', 'mkv', 'mov', 'mp4', 'webm')]
        [string]$MergeOutputFormat = 'mkv',

        [Parameter(Mandatory = $false)]
        [ValidateNotNullOrEmpty()]
        [string]$FormatSort = 'res,fps,hdr,vcodec,acodec,br',

        [Parameter(Mandatory = $false)]
        [ValidateRange(1, 64)]
        [int]$ConcurrentFragments = 12,

        [Parameter(Mandatory = $false)]
        [switch]$NoOverwrites,

        [Parameter(Mandatory = $false)]
        [switch]$NoPlaylist,

        [Parameter(Mandatory = $false)]
        [switch]$EmbedSubtitles,

        [Parameter(Mandatory = $false)]
        [ValidateNotNullOrEmpty()]
        [string[]]$SubtitleLanguages,

        [Parameter(Mandatory = $false)]
        [ValidateNotNullOrEmpty()]
        [string]$CookiesFromBrowser,

        [Parameter(Mandatory = $false)]
        [ValidateNotNullOrEmpty()]
        [string]$ExecutablePath,

        [Parameter(Mandatory = $false)]
        [ValidateNotNullOrEmpty()]
        [string]$FfmpegLocation,

        [Parameter(Mandatory = $false)]
        [string[]]$AdditionalArguments
    )

    process {

        $InvokeParameter = @{
            Url                 = $Url
            Format              = 'bestvideo*+bestaudio/best'
            FormatSort          = $FormatSort
            MergeOutputFormat   = $MergeOutputFormat
            OutputTemplate      = $OutputTemplate
            ConcurrentFragments = $ConcurrentFragments
            EmbedMetadata       = $true
            EmbedChapters       = $true
            EmbedThumbnail      = $true
            ConvertThumbnails   = 'jpg'
            PassThru            = $true
        }

        $OptionalParameters = 'OutputPath', 'NoOverwrites', 'NoPlaylist', 'EmbedSubtitles', 'SubtitleLanguages', 'CookiesFromBrowser', 'ExecutablePath', 'FfmpegLocation', 'AdditionalArguments', 'InformationAction'
        foreach ($Name in $OptionalParameters) {
            if ($PSBoundParameters.ContainsKey($Name)) { $InvokeParameter[$Name] = $PSBoundParameters[$Name] }
        }

        if ($PSCmdlet.ShouldProcess(($Url -join ', '), 'Download the highest quality video')) {
            Invoke-YTdlp @InvokeParameter -Confirm:$false
        }

    }

}
#EndRegion './Public/Save-YTdlpVideo.ps1' 207
#Region './Public/Update-YTdlp.ps1' -1

function Update-YTdlp {
<#
.NOTES
    Copyright 1990-2026 Celerium

    NAME: Update-YTdlp
    Type: Public

        AUTHOR: David Schulte
        DATE: 2025-11-11
        EMAIL: celerium@Celerium.org

    TODO:

.SYNOPSIS
    Updates yt-dlp to the latest stable version

.DESCRIPTION
    The Update-YTdlp function compares the local yt-dlp version to the latest stable
    release on GitHub & updates the local installation when a newer version exists.

    Update methods:
        Winget - Uses [ winget upgrade ] (default on Windows)
        SelfUpdate - Uses [ yt-dlp --update-to stable ] (default on Linux & macOS)

    The winget repository is updated by a community process & can trail a GitHub release
    by a few hours. When that happens a warning is shown & the update can be run again later.

.PARAMETER ExecutablePath
    Defines an explicit path to the yt-dlp executable

.PARAMETER Method
    Defines how yt-dlp is updated

    Default value: Auto

    Allowed values:
        'Auto', 'Winget', 'SelfUpdate'

.PARAMETER Force
    Run the update even if the local version is already the latest stable version

.EXAMPLE
    Update-YTdlp

    Updates yt-dlp only if a newer stable version has been released

.EXAMPLE
    Update-YTdlp -Method SelfUpdate

    Updates yt-dlp using its built-in updater

.EXAMPLE
    Update-YTdlp -WhatIf

    Shows what would happen without updating anything

.INPUTS
    N/A

.OUTPUTS
    Celerium.YTdlp.Version

.LINK
    https://github.com/yt-dlp/yt-dlp#update

.LINK
    https://github.com/Celerium/Celerium.YTdlp
#>


    [CmdletBinding(SupportsShouldProcess = $true)]
    [OutputType('Celerium.YTdlp.Version')]
    param (
        [Parameter(Mandatory = $false)]
        [ValidateNotNullOrEmpty()]
        [string]$ExecutablePath,

        [Parameter(Mandatory = $false)]
        [ValidateSet('Auto', 'Winget', 'SelfUpdate')]
        [string]$Method = 'Auto',

        [Parameter(Mandatory = $false)]
        [switch]$Force
    )

    $VersionParameter = @{}
    if ($ExecutablePath) { $VersionParameter['ExecutablePath'] = $ExecutablePath }

    $Current = Get-YTdlpVersion @VersionParameter

    if ($Current.Status -eq 'NotInstalled') {
        throw 'yt-dlp is not installed. Run Install-YTdlp first'
    }

    if ($Current.Status -eq 'UpToDate' -and -not $Force) {
        Write-Verbose "yt-dlp [ $($Current.InstalledVersion) ] is already the latest stable version"
        return $Current
    }

    if ($Method -eq 'Auto') {
        if ($IsWindows -or $PSEdition -eq 'Desktop') { $Method = 'Winget' } else { $Method = 'SelfUpdate' }
    }

    if ($PSCmdlet.ShouldProcess("yt-dlp [ $($Current.InstalledVersion) --> $($Current.LatestVersion) ]", "Update using $Method")) {

        switch ($Method) {

            'Winget' {

                $WingetArguments = @(
                    'upgrade'
                    '--id', 'yt-dlp.yt-dlp'
                    '--exact'
                    '--source', 'winget'
                    '--silent'
                    '--accept-package-agreements'
                    '--accept-source-agreements'
                )

                if ($Force) { $WingetArguments += '--force' }

                $ExitCode = Invoke-YTdlpWinget -ArgumentList $WingetArguments

                #-1978335189 = no applicable update found
                if ($ExitCode -ne 0 -and $ExitCode -ne -1978335189) {
                    throw "winget failed to update yt-dlp with exit code [ $ExitCode ]"
                }

            }

            'SelfUpdate' {
                Invoke-YTdlpProcess -FilePath $Current.Path -ArgumentList '--update-to', 'stable'
            }

        }

        $Updated = Get-YTdlpVersion @VersionParameter

        if ($Updated.UpdateAvailable) {
            Write-Warning "yt-dlp is [ $($Updated.InstalledVersion) ] but [ $($Updated.LatestVersion) ] is available. The $Method source may not have published the latest release yet, try again later"
        }

        $Updated

    }

}
#EndRegion './Public/Update-YTdlp.ps1' 148