Commit 095d07cbe9

095d07cbe9d03902f3eacb06f4606b0e33f57894

parent: df47e8cfa2

Unsigned

Azin Sharaf <azin.sharaf@icloud.com> · 2026-04-27 22:42 UTC

build(windows): fix mpv setup for cargo install and restricted environments

Two bugs prevented the auto-download from working when using
\cargo install --git\ or running as a non-admin user:

1. \\C:\Users\azin\AppData\Local\Temp\ resolved to C:\\Windows\\Temp (no user write access).
   Fixed by using [System.IO.Path]::GetTempPath() which always returns
   the user-local temp directory.

2. mpv-dev/ was placed relative to the source checkout, which is a
   throwaway directory under cargo install. Fixed by defaulting the
   output to %LOCALAPPDATA%\\youtube-tui\\mpv-dev — a persistent,
   user-writable location that survives across installs.

Changes:
- setup-mpv-dev.ps1: accept -OutputDir param, use GetTempPath()
- build.rs: pass -OutputDir to script, check LOCALAPPDATA location
  before the project-local fallback, add rerun-if-env-changed guard

Layout: unified · split

build.rs +40 −15
@@ -1,29 +1,48 @@
11fn main() {
22 // On Windows, help the linker find mpv.lib when building with the mpv feature.
3 // Priority: MPV_LIB_DIR env var → local mpv-dev/ dir → run setup-mpv-dev.ps1 to create it.
3 //
4 // Priority:
5 // 1. MPV_LIB_DIR env var — CI / custom installs
6 // 2. %LOCALAPPDATA%\youtube-tui\mpv-dev — persistent user location (survives cargo install)
7 // 3. <manifest>/mpv-dev — local project checkout
8 // 4. Run setup-mpv-dev.ps1 — download and generate mpv.lib on first build
49 #[cfg(all(target_os = "windows", feature = "mpv"))]
510 {
6 // Tell Cargo to re-run this script only when these change, not on every build.
7 println!("cargo:rerun-if-changed=mpv-dev/mpv.lib");
811 println!("cargo:rerun-if-env-changed=MPV_LIB_DIR");
12 println!("cargo:rerun-if-env-changed=LOCALAPPDATA");
913
10 let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap();
11 let local_mpv = std::path::Path::new(&manifest_dir).join("mpv-dev");
12 let mpv_lib = local_mpv.join("mpv.lib");
13
14 // 1. Explicit env var override (CI / custom setups)
14 // 1. Explicit env var override (CI / custom installs)
1515 if let Ok(dir) = std::env::var("MPV_LIB_DIR") {
1616 println!("cargo:rustc-link-search=native={}", dir);
1717 return;
1818 }
1919
20 // 2. mpv.lib already exists locally from a previous run — fast path
21 if mpv_lib.exists() {
22 println!("cargo:rustc-link-search=native={}", local_mpv.display());
23 return;
20 // Persistent user-level location — works for both `cargo build` and `cargo install`.
21 // %LOCALAPPDATA%\youtube-tui\mpv-dev is always writable and survives across installs.
22 let persistent_dir = std::env::var("LOCALAPPDATA")
23 .map(|d| {
24 std::path::PathBuf::from(d)
25 .join("youtube-tui")
26 .join("mpv-dev")
27 })
28 .ok();
29
30 // Local project-relative fallback (convenient for development checkouts)
31 let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap();
32 let local_dir = std::path::Path::new(&manifest_dir).join("mpv-dev");
33
34 // 2 & 3. Check both locations for an existing mpv.lib — fast path
35 for candidate in persistent_dir.iter().chain(std::iter::once(&local_dir)) {
36 let lib = candidate.join("mpv.lib");
37 println!("cargo:rerun-if-changed={}", lib.display());
38 if lib.exists() {
39 println!("cargo:rustc-link-search=native={}", candidate.display());
40 return;
41 }
2442 }
2543
26 // 3. Run setup-mpv-dev.ps1 to download and generate mpv.lib automatically
44 // 4. Neither location has mpv.lib — run setup-mpv-dev.ps1 to download it.
45 // Output goes to the persistent user location so subsequent installs are instant.
2746 let script = std::path::Path::new(&manifest_dir).join("setup-mpv-dev.ps1");
2847 if !script.exists() {
2948 panic!(
@@ -34,8 +53,11 @@ fn main() {
3453 );
3554 }
3655
56 // Prefer the persistent directory; fall back to the local project dir.
57 let output_dir = persistent_dir.unwrap_or(local_dir.clone());
58
3759 eprintln!(
38 "cargo:warning=mpv.lib not found — running setup-mpv-dev.ps1 to download it (~30MB)..."
60 "cargo:warning=mpv.lib not found — running setup-mpv-dev.ps1 (~30MB download)..."
3961 );
4062
4163 let status = std::process::Command::new("powershell")
@@ -44,6 +66,8 @@ fn main() {
4466 "Bypass",
4567 "-File",
4668 &script.to_string_lossy(),
69 "-OutputDir",
70 &output_dir.to_string_lossy(),
4771 ])
4872 .status()
4973 .expect("Failed to launch PowerShell to run setup-mpv-dev.ps1");
@@ -58,6 +82,7 @@ fn main() {
5882 );
5983 }
6084
85 let mpv_lib = output_dir.join("mpv.lib");
6186 if !mpv_lib.exists() {
6287 panic!(
6388 "\n\nERROR: setup-mpv-dev.ps1 completed but mpv.lib was not found at:\n {}\n\
@@ -67,6 +92,6 @@ fn main() {
6792 );
6893 }
6994
70 println!("cargo:rustc-link-search=native={}", local_mpv.display());
95 println!("cargo:rustc-link-search=native={}", output_dir.display());
7196 }
7297}
setup-mpv-dev.ps1 +45 −37
@@ -1,17 +1,31 @@
11# Downloads mpv dev library for Windows (required to build with the `mpv` feature)
2# Usage: .\setup-mpv-dev.ps1
3# This downloads ~30MB and extracts mpv.lib + libmpv-2.dll into a local 'mpv-dev' folder.
4# Then sets MPV_LIB_DIR for the current session.
2#
3# Usage:
4# .\setup-mpv-dev.ps1 # outputs to .\mpv-dev\
5# .\setup-mpv-dev.ps1 -OutputDir "C:\some\dir" # outputs to a custom directory
6#
7# When called from build.rs, -OutputDir is set to %LOCALAPPDATA%\youtube-tui\mpv-dev
8# so the files persist across `cargo install` invocations.
9
10param(
11 [string]$OutputDir = ""
12)
513
614$ErrorActionPreference = "Stop"
715
8$mpvDevDir = Join-Path $PSScriptRoot "mpv-dev"
9$mpvLib = Join-Path $mpvDevDir "mpv.lib"
16# Determine output directory:
17# - Explicit -OutputDir argument (used by build.rs)
18# - Otherwise default to a sibling mpv-dev\ next to this script
19if ($OutputDir -eq "") {
20 $OutputDir = Join-Path $PSScriptRoot "mpv-dev"
21}
22
23$mpvLib = Join-Path $OutputDir "mpv.lib"
1024
1125if (Test-Path $mpvLib) {
12 Write-Host "mpv.lib already exists at $mpvDevDir, skipping download."
13 $env:MPV_LIB_DIR = $mpvDevDir
14 Write-Host "MPV_LIB_DIR set to $mpvDevDir"
26 Write-Host "mpv.lib already exists at $OutputDir, skipping download."
27 $env:MPV_LIB_DIR = $OutputDir
28 Write-Host "MPV_LIB_DIR set to $OutputDir"
1529 return
1630}
1731
@@ -19,14 +33,18 @@ if (Test-Path $mpvLib) {
1933$arch = if ([Environment]::Is64BitOperatingSystem) { "x86_64" } else { "i686" }
2034$url = "https://github.com/shinchiro/mpv-winbuild-cmake/releases/download/20260412/mpv-dev-${arch}-20260412-git-062f4bf.7z"
2135
36# Use the user-local temp directory (always writable, unlike C:\Windows\Temp)
37$userTemp = [System.IO.Path]::GetTempPath()
38$tempFile = Join-Path $userTemp "mpv-dev.7z"
39$tempExtract = Join-Path $userTemp "mpv-dev-extract"
40
2241Write-Host "Downloading mpv-dev for $arch..."
23$tempFile = Join-Path $env:TEMP "mpv-dev.7z"
2442Invoke-WebRequest -Uri $url -OutFile $tempFile -UserAgent "Mozilla/5.0"
2543
2644# Create output directory
27New-Item -ItemType Directory -Force -Path $mpvDevDir | Out-Null
45New-Item -ItemType Directory -Force -Path $OutputDir | Out-Null
2846
29# Extract using 7z (ships with scoop, git, or can be installed via scoop install 7zip)
47# Locate 7z — check PATH first, then common install locations
3048$7zPaths = @(
3149 "7z",
3250 "$env:ProgramFiles\7-Zip\7z.exe",
@@ -53,7 +71,6 @@ if (-not $7zExe) {
5371}
5472
5573Write-Host "Extracting mpv-dev..."
56$tempExtract = Join-Path $env:TEMP "mpv-dev-extract"
5774if (Test-Path $tempExtract) { Remove-Item -Recurse -Force $tempExtract }
5875& $7zExe x $tempFile -o"$tempExtract" -y | Out-Null
5976
@@ -63,7 +80,7 @@ $dllFile = Get-ChildItem -Path $tempExtract -Filter "libmpv-2.dll" -Recurse | Se
6380
6481if (-not $libFile) {
6582 # The shinchiro builds ship libmpv.dll.a (GCC format), not mpv.lib (MSVC format).
66 # Generate mpv.lib from the DLL using dumpbin + lib (MSVC tools).
83 # Generate mpv.lib from the DLL using MSVC dumpbin + lib tools.
6784 Write-Host "mpv.lib not found in archive. Generating from libmpv-2.dll..."
6885
6986 $dllForLib = Get-ChildItem -Path $tempExtract -Filter "libmpv-2.dll" -Recurse | Select-Object -First 1
@@ -71,7 +88,7 @@ if (-not $libFile) {
7188 Write-Error "Could not find libmpv-2.dll in the archive!"
7289 }
7390
74 # Find MSVC tools (dumpbin, lib) - they're installed but not in PATH
91 # Find MSVC tools — installed but not in PATH by default
7592 $vsBase = "${env:ProgramFiles(x86)}\Microsoft Visual Studio"
7693 if (-not (Test-Path $vsBase)) { $vsBase = "$env:ProgramFiles\Microsoft Visual Studio" }
7794 $dumpbin = Get-ChildItem -Path $vsBase -Recurse -Filter "dumpbin.exe" -ErrorAction SilentlyContinue |
@@ -85,55 +102,46 @@ if (-not $libFile) {
85102 Write-Error "Could not find MSVC build tools (dumpbin.exe, lib.exe). Install 'Desktop development with C++' workload."
86103 }
87104
88 # Export function names from DLL
89 $defPath = Join-Path $mpvDevDir "mpv.def"
105 # Export function names from DLL and write .def file
106 $defPath = Join-Path $OutputDir "mpv.def"
90107 $exports = & $dumpbin /exports "$($dllForLib.FullName)" 2>&1 |
91108 Select-String "^\s+\d+\s+[0-9A-Fa-f]+\s+[0-9A-Fa-f]+\s+(\S+)" |
92109 ForEach-Object { $_.Matches[0].Groups[1].Value }
93110
94 # Write .def file
95111 $defContent = "LIBRARY libmpv-2`nEXPORTS`n"
96112 $defContent += ($exports | ForEach-Object { " $_" }) -join "`n"
97113 Set-Content -Path $defPath -Value $defContent -Encoding ASCII
98114
99115 # Generate .lib from .def
100116 $machine = if ($arch -eq "x86_64") { "x64" } else { "x86" }
101 & $libExe /def:"$defPath" /machine:$machine /out:"$mpvDevDir\mpv.lib" 2>&1 | Out-Null
117 & $libExe /def:"$defPath" /machine:$machine /out:"$OutputDir\mpv.lib" 2>&1 | Out-Null
102118
103 if (-not (Test-Path "$mpvDevDir\mpv.lib")) {
119 if (-not (Test-Path "$OutputDir\mpv.lib")) {
104120 Write-Error "Failed to generate mpv.lib!"
105121 } else {
106122 Write-Host "Generated mpv.lib successfully."
107123 }
108124} else {
109 Copy-Item $libFile.FullName $mpvDevDir
125 Copy-Item $libFile.FullName $OutputDir
110126}
111127
112128if ($dllFile) {
113 Copy-Item $dllFile.FullName $mpvDevDir
114 # Also copy DLL next to the built binary location
115 $targetRelease = Join-Path $PSScriptRoot "target\release"
116 if (Test-Path $targetRelease) {
117 Copy-Item $dllFile.FullName $targetRelease
118 }
129 Copy-Item $dllFile.FullName $OutputDir
119130}
120131
121# Also grab any other DLLs we might need
132# Also grab any other DLLs from the archive
122133Get-ChildItem -Path $tempExtract -Filter "*.dll" -Recurse | ForEach-Object {
123 Copy-Item $_.FullName $mpvDevDir -Force
134 Copy-Item $_.FullName $OutputDir -Force
124135}
125136
126# Cleanup
137# Cleanup temp files
127138Remove-Item -Force $tempFile -ErrorAction SilentlyContinue
128139Remove-Item -Recurse -Force $tempExtract -ErrorAction SilentlyContinue
129140
130$env:MPV_LIB_DIR = $mpvDevDir
131Write-Host ""
132Write-Host "Done! mpv dev files extracted to: $mpvDevDir"
133Write-Host "MPV_LIB_DIR set to: $mpvDevDir"
141$env:MPV_LIB_DIR = $OutputDir
134142Write-Host ""
135Write-Host "You can now build with:"
136Write-Host " cargo build --release"
143Write-Host "Done! mpv dev files extracted to: $OutputDir"
144Write-Host "MPV_LIB_DIR set to: $OutputDir"
137145Write-Host ""
138Write-Host "To make this permanent, add to your PowerShell profile:"
139Write-Host " `$env:MPV_LIB_DIR = '$mpvDevDir'"
146Write-Host "To make MPV_LIB_DIR permanent, add to your PowerShell profile:"
147Write-Host " `$env:MPV_LIB_DIR = '$OutputDir'"