Skip to content

Instantly share code, notes, and snippets.

@zhongfly
Last active November 18, 2023 02:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zhongfly/5998b75852b1bde192a306ceb9090beb to your computer and use it in GitHub Desktop.
Save zhongfly/5998b75852b1bde192a306ceb9090beb to your computer and use it in GitHub Desktop.
Auto update libmpv
# https://github.com/shinchiro/mpv-packaging/blob/master/mpv-root/installer/updater.ps1
$fallback7z = Join-Path (Get-Location) "\7z\7zr.exe";
$useragent = "mpv-win-updater"
function Get-7z {
$7z_command = Get-Command -CommandType Application -ErrorAction Ignore 7z.exe
if ($7z_command) {
return $7z_command.Source
}
$7zdir = Get-ItemPropertyValue -ErrorAction Ignore "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\7-Zip" "InstallLocation"
if ($7zdir -and (Test-Path (Join-Path $7zdir "7z.exe"))) {
return Join-Path $7zdir "7z.exe"
}
if (Test-Path $fallback7z) {
return $fallback7z
}
return $null
}
function Check-7z {
if (-not (Get-7z))
{
$null = New-Item -ItemType Directory -Force (Split-Path $fallback7z)
$download_file = $fallback7z
Write-Host "Downloading 7z" -ForegroundColor Green
Invoke-WebRequest -Uri "https://www.7-zip.org/a/7zr.exe" -UserAgent $useragent -OutFile $download_file
}
else
{
Write-Host "7z already exist. Skipped download" -ForegroundColor Green
}
}
function Check-PowershellVersion {
$version = $PSVersionTable.PSVersion.Major
Write-Host "Checking Windows PowerShell version -- $version" -ForegroundColor Green
if ($version -le 2)
{
Write-Host "Using Windows PowerShell $version is unsupported. Upgrade your Windows PowerShell." -ForegroundColor Red
throw
}
}
function Check-Mpv {
$mpv = (Get-Location).Path + "\libmpv-2.dll"
$is_exist = Test-Path $mpv
return $is_exist
}
function Download-Mpv ($filename, $download_link) {
Write-Host "Downloading $filename from $download_link" -ForegroundColor Green
Invoke-WebRequest -Uri $download_link -UserAgent $useragent -OutFile $filename
}
function Extract-Mpv ($file) {
$7z = Get-7z
Write-Host "Extracting" $file -ForegroundColor Green
& $7z x $file -o".\" "libmpv-2.dll" -y
}
function Get-Latest-MpvFromGithub($Arch) {
$releases_link = "https://api.github.com/repos/zhongfly/mpv-winbuild/releases/latest"
$i686_pattern = "mpv-dev-i686-[0-9]{8}"
$x86_64_pattern = "mpv-dev-x86_64-v3-[0-9]{8}"
$pattern = ''
switch ($Arch)
{
i686 { $pattern = $i686_pattern}
x86_64 { $pattern = $x86_64_pattern }
}
Write-Host "Fetching Releases for mpv" -ForegroundColor Green
$json = Invoke-WebRequest $releases_link -MaximumRedirection 0 -ErrorAction Ignore -UseBasicParsing | ConvertFrom-Json
$filename = $json.assets | where { $_.name -Match $pattern } | Select-Object -ExpandProperty name
$download_link = $json.assets | where { $_.name -Match $pattern } | Select-Object -ExpandProperty browser_download_url
return $filename, $download_link
}
function Get-Arch {
# Reference: http://superuser.com/a/891443
$FilePath = [System.IO.Path]::Combine((Get-Location).Path, 'libmpv-2.dll')
[int32]$MACHINE_OFFSET = 4
[int32]$PE_POINTER_OFFSET = 60
[byte[]]$data = New-Object -TypeName System.Byte[] -ArgumentList 4096
$stream = New-Object -TypeName System.IO.FileStream -ArgumentList ($FilePath, 'Open', 'Read')
$stream.Read($data, 0, 4096) | Out-Null
# DOS header is 64 bytes, last element, long (4 bytes) is the address of the PE header
[int32]$PE_HEADER_ADDR = [System.BitConverter]::ToInt32($data, $PE_POINTER_OFFSET)
[int32]$machineUint = [System.BitConverter]::ToUInt16($data, $PE_HEADER_ADDR + $MACHINE_OFFSET)
$result = "" | select FilePath, FileType
$result.FilePath = $FilePath
switch ($machineUint)
{
0 { $result.FileType = 'Native' }
0x014c { $result.FileType = 'i686' } # 32bit
0x0200 { $result.FileType = 'Itanium' }
0x8664 { $result.FileType = 'x86_64' } # 64bit
}
$stream.Close()
$result
}
function ExtractGitFromFile {
$stripped = Get-ChildItem ./libmpv-2.dll | Select-Object -ExpandProperty VersionInfo | Select-Object FileVersion | Select-Object -ExpandProperty FileVersion
$pattern = "-g([a-z0-9-]{7})"
$bool = $stripped -match $pattern
return $matches[1]
}
function ExtractGitFromURL($filename) {
$pattern = "-git-([a-z0-9-]{7})"
$bool = $filename -match $pattern
return $matches[1]
}
function ExtractDateFromFile {
$date = (Get-Item ./libmpv-2.dll).LastWriteTimeUtc
$day = $date.Day.ToString("00")
$month = $date.Month.ToString("00")
$year = $date.Year.ToString("0000")
return "$year$month$day"
}
function ExtractDateFromURL($filename) {
$pattern = "-([0-9]{8})-git-([a-z0-9-]{7})"
$bool = $filename -match $pattern
return $matches[1]
}
function Test-Admin
{
$user = [Security.Principal.WindowsIdentity]::GetCurrent();
(New-Object Security.Principal.WindowsPrincipal $user).IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
}
function Upgrade-Mpv {
$need_download = $false
$remoteName = ""
$arch = ""
if (Check-Mpv) {
$arch = (Get-Arch).FileType
$remoteName, $download_link= Get-Latest-MpvFromGithub $arch
$localgit = ExtractGitFromFile
$localdate = ExtractDateFromFile
$remotegit = ExtractGitFromURL $remoteName
$remotedate = ExtractDateFromURL $remoteName
if ($localgit -match $remotegit)
{
if ($localdate -match $remotedate)
{
Write-Host "You are already using latest mpv build -- $remoteName" -ForegroundColor Green
$need_download = $false
}
else {
Write-Host "Newer mpv build available" -ForegroundColor Green
$need_download = $true
}
}
else {
Write-Host "Newer mpv build available" -ForegroundColor Green
$need_download = $true
}
}
else {
Write-Host "mpv doesn't exist. " -ForegroundColor Green -NoNewline
$result = Read-KeyOrTimeout "Proceed with downloading? [Y/n] (default=y)" "Y"
Write-Host ""
if ($result -eq "Y") {
$need_download = $true
if (Test-Path (Join-Path $env:windir "SysWow64")) {
Write-Host "Detecting System Type is 64-bit" -ForegroundColor Green
$arch = "x86_64"
}
else {
Write-Host "Detecting System Type is 32-bit" -ForegroundColor Green
$arch = "i686"
}
$remoteName, $download_link = Get-Latest-MpvFromGithub $arch
}
else {
$need_download = $false
}
}
if ($need_download) {
Download-Mpv $remoteName $download_link
Check-7z
Extract-Mpv $remoteName
}
}
function Read-KeyOrTimeout ($prompt, $key){
$seconds = 9
$startTime = Get-Date
$timeOut = New-TimeSpan -Seconds $seconds
Write-Host "$prompt " -ForegroundColor Green
# Basic progress bar
[Console]::CursorLeft = 0
[Console]::Write("[")
[Console]::CursorLeft = $seconds + 2
[Console]::Write("]")
[Console]::CursorLeft = 1
while (-not [System.Console]::KeyAvailable) {
$currentTime = Get-Date
Start-Sleep -s 1
Write-Host "#" -ForegroundColor Green -NoNewline
if ($currentTime -gt $startTime + $timeOut) {
Break
}
}
if ([System.Console]::KeyAvailable) {
$response = [System.Console]::ReadKey($true).Key
}
else {
$response = $key
}
return $response.ToString()
}
#
# Main script entry point
#
if (Test-Admin) {
Write-Host "Running script with administrator privileges" -ForegroundColor Yellow
}
else {
Write-Host "Running script without administrator privileges" -ForegroundColor Red
}
try {
Check-PowershellVersion
# Sourceforge only support TLS 1.2
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$global:progressPreference = 'silentlyContinue'
Upgrade-Mpv
Write-Host "Operation completed" -ForegroundColor Magenta
}
catch [System.Exception] {
Write-Host $_.Exception.Message -ForegroundColor Red
exit 1
}
@GH0STDATA
Copy link

Hey @zhongfly, the ffmpeg update function included in https://github.com/zhongfly/mpv-winbuild is currently broken and keeps throwing a "Cannot index to null array" error. I've managed to fix it.

function Upgrade-FFmpeg {
    $get_ffmpeg = Check-GetFFmpeg
    if ($get_ffmpeg -eq "false") {
        return
    }

    if (Test-Path (Join-Path $env:windir "SysWow64")) {
        $original_arch = "x86_64"
        $arch = Check-Arch $original_arch
    }
    else {
        $arch = "i686"
    }

    $need_download = $false
    $remote_name, $download_link = Get-Latest-FFmpeg $arch
    $remote_build = $remote_name.replace("ffmpeg-$arch-git-", "").replace(".7z", "")
    $ffmpeg = (Get-Location).Path + "\ffmpeg.exe"
    $ffmpeg_exist = Test-Path $ffmpeg

    if ($ffmpeg_exist) {
        $ffmpeg_version = .\ffmpeg -version | select-string "ffmpeg" | select-object -First 1

        if ($ffmpeg_version -like "*$remote_build*") {
            Write-Host "You are already using latest ffmpeg build -- $remote_name" -ForegroundColor Green
            $need_download = $false
        }
        else {
            Write-Host "Newer ffmpeg build available" -ForegroundColor Green
            $need_download = $true
        }
    }
    else {
        $need_download = $true
    }

    if ($need_download) {
        Download-Archive $remote_name $download_link
        Check-7z
        Extract-Archive $remote_name
    }
    Check-Autodelete $remote_name
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment