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 @@
1fn main() { 1fn main() {
2 // On Windows, help the linker find mpv.lib when building with the mpv feature. 2 // 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
4 #[cfg(all(target_os = "windows", feature = "mpv"))] 9 #[cfg(all(target_os = "windows", feature = "mpv"))]
5 { 10 {
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");
8 println!("cargo:rerun-if-env-changed=MPV_LIB_DIR"); 11 println!("cargo:rerun-if-env-changed=MPV_LIB_DIR");
12 println!("cargo:rerun-if-env-changed=LOCALAPPDATA");
9 13
10 let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap(); 14 // 1. Explicit env var override (CI / custom installs)
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)
15 if let Ok(dir) = std::env::var("MPV_LIB_DIR") { 15 if let Ok(dir) = std::env::var("MPV_LIB_DIR") {
16 println!("cargo:rustc-link-search=native={}", dir); 16 println!("cargo:rustc-link-search=native={}", dir);
17 return; 17 return;
18 } 18 }
19 19
20 // 2. mpv.lib already exists locally from a previous run — fast path 20 // Persistent user-level location — works for both `cargo build` and `cargo install`.
21 if mpv_lib.exists() { 21 // %LOCALAPPDATA%\youtube-tui\mpv-dev is always writable and survives across installs.
22 println!("cargo:rustc-link-search=native={}", local_mpv.display()); 22 let persistent_dir = std::env::var("LOCALAPPDATA")
23 return; 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 }
24 } 42 }
25 43
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.
27 let script = std::path::Path::new(&manifest_dir).join("setup-mpv-dev.ps1"); 46 let script = std::path::Path::new(&manifest_dir).join("setup-mpv-dev.ps1");
28 if !script.exists() { 47 if !script.exists() {
29 panic!( 48 panic!(
@@ -34,8 +53,11 @@ fn main() {
34 ); 53 );
35 } 54 }
36 55
56 // Prefer the persistent directory; fall back to the local project dir.
57 let output_dir = persistent_dir.unwrap_or(local_dir.clone());
58
37 eprintln!( 59 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)..."
39 ); 61 );
40 62
41 let status = std::process::Command::new("powershell") 63 let status = std::process::Command::new("powershell")
@@ -44,6 +66,8 @@ fn main() {
44 "Bypass", 66 "Bypass",
45 "-File", 67 "-File",
46 &script.to_string_lossy(), 68 &script.to_string_lossy(),
69 "-OutputDir",
70 &output_dir.to_string_lossy(),
47 ]) 71 ])
48 .status() 72 .status()
49 .expect("Failed to launch PowerShell to run setup-mpv-dev.ps1"); 73 .expect("Failed to launch PowerShell to run setup-mpv-dev.ps1");
@@ -58,6 +82,7 @@ fn main() {
58 ); 82 );
59 } 83 }
60 84
85 let mpv_lib = output_dir.join("mpv.lib");
61 if !mpv_lib.exists() { 86 if !mpv_lib.exists() {
62 panic!( 87 panic!(
63 "\n\nERROR: setup-mpv-dev.ps1 completed but mpv.lib was not found at:\n {}\n\ 88 "\n\nERROR: setup-mpv-dev.ps1 completed but mpv.lib was not found at:\n {}\n\
@@ -67,6 +92,6 @@ fn main() {
67 ); 92 );
68 } 93 }
69 94
70 println!("cargo:rustc-link-search=native={}", local_mpv.display()); 95 println!("cargo:rustc-link-search=native={}", output_dir.display());
71 } 96 }
72} 97}
setup-mpv-dev.ps1 +45 −37
@@ -1,17 +1,31 @@
1# Downloads mpv dev library for Windows (required to build with the `mpv` feature) 1# Downloads mpv dev library for Windows (required to build with the `mpv` feature)
2# Usage: .\setup-mpv-dev.ps1 2#
3# This downloads ~30MB and extracts mpv.lib + libmpv-2.dll into a local 'mpv-dev' folder. 3# Usage:
4# Then sets MPV_LIB_DIR for the current session. 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)
5 13
6$ErrorActionPreference = "Stop" 14$ErrorActionPreference = "Stop"
7 15
8$mpvDevDir = Join-Path $PSScriptRoot "mpv-dev" 16# Determine output directory:
9$mpvLib = Join-Path $mpvDevDir "mpv.lib" 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"
10 24
11if (Test-Path $mpvLib) { 25if (Test-Path $mpvLib) {
12 Write-Host "mpv.lib already exists at $mpvDevDir, skipping download." 26 Write-Host "mpv.lib already exists at $OutputDir, skipping download."
13 $env:MPV_LIB_DIR = $mpvDevDir 27 $env:MPV_LIB_DIR = $OutputDir
14 Write-Host "MPV_LIB_DIR set to $mpvDevDir" 28 Write-Host "MPV_LIB_DIR set to $OutputDir"
15 return 29 return
16} 30}
17 31
@@ -19,14 +33,18 @@ if (Test-Path $mpvLib) {
19$arch = if ([Environment]::Is64BitOperatingSystem) { "x86_64" } else { "i686" } 33$arch = if ([Environment]::Is64BitOperatingSystem) { "x86_64" } else { "i686" }
20$url = "https://github.com/shinchiro/mpv-winbuild-cmake/releases/download/20260412/mpv-dev-${arch}-20260412-git-062f4bf.7z" 34$url = "https://github.com/shinchiro/mpv-winbuild-cmake/releases/download/20260412/mpv-dev-${arch}-20260412-git-062f4bf.7z"
21 35
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
22Write-Host "Downloading mpv-dev for $arch..." 41Write-Host "Downloading mpv-dev for $arch..."
23$tempFile = Join-Path $env:TEMP "mpv-dev.7z"
24Invoke-WebRequest -Uri $url -OutFile $tempFile -UserAgent "Mozilla/5.0" 42Invoke-WebRequest -Uri $url -OutFile $tempFile -UserAgent "Mozilla/5.0"
25 43
26# Create output directory 44# Create output directory
27New-Item -ItemType Directory -Force -Path $mpvDevDir | Out-Null 45New-Item -ItemType Directory -Force -Path $OutputDir | Out-Null
28 46
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
30$7zPaths = @( 48$7zPaths = @(
31 "7z", 49 "7z",
32 "$env:ProgramFiles\7-Zip\7z.exe", 50 "$env:ProgramFiles\7-Zip\7z.exe",
@@ -53,7 +71,6 @@ if (-not $7zExe) {
53} 71}
54 72
55Write-Host "Extracting mpv-dev..." 73Write-Host "Extracting mpv-dev..."
56$tempExtract = Join-Path $env:TEMP "mpv-dev-extract"
57if (Test-Path $tempExtract) { Remove-Item -Recurse -Force $tempExtract } 74if (Test-Path $tempExtract) { Remove-Item -Recurse -Force $tempExtract }
58& $7zExe x $tempFile -o"$tempExtract" -y | Out-Null 75& $7zExe x $tempFile -o"$tempExtract" -y | Out-Null
59 76
@@ -63,7 +80,7 @@ $dllFile = Get-ChildItem -Path $tempExtract -Filter "libmpv-2.dll" -Recurse | Se
63 80
64if (-not $libFile) { 81if (-not $libFile) {
65 # The shinchiro builds ship libmpv.dll.a (GCC format), not mpv.lib (MSVC format). 82 # 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.
67 Write-Host "mpv.lib not found in archive. Generating from libmpv-2.dll..." 84 Write-Host "mpv.lib not found in archive. Generating from libmpv-2.dll..."
68 85
69 $dllForLib = Get-ChildItem -Path $tempExtract -Filter "libmpv-2.dll" -Recurse | Select-Object -First 1 86 $dllForLib = Get-ChildItem -Path $tempExtract -Filter "libmpv-2.dll" -Recurse | Select-Object -First 1
@@ -71,7 +88,7 @@ if (-not $libFile) {
71 Write-Error "Could not find libmpv-2.dll in the archive!" 88 Write-Error "Could not find libmpv-2.dll in the archive!"
72 } 89 }
73 90
74 # Find MSVC tools (dumpbin, lib) - they're installed but not in PATH 91 # Find MSVC tools — installed but not in PATH by default
75 $vsBase = "${env:ProgramFiles(x86)}\Microsoft Visual Studio" 92 $vsBase = "${env:ProgramFiles(x86)}\Microsoft Visual Studio"
76 if (-not (Test-Path $vsBase)) { $vsBase = "$env:ProgramFiles\Microsoft Visual Studio" } 93 if (-not (Test-Path $vsBase)) { $vsBase = "$env:ProgramFiles\Microsoft Visual Studio" }
77 $dumpbin = Get-ChildItem -Path $vsBase -Recurse -Filter "dumpbin.exe" -ErrorAction SilentlyContinue | 94 $dumpbin = Get-ChildItem -Path $vsBase -Recurse -Filter "dumpbin.exe" -ErrorAction SilentlyContinue |
@@ -85,55 +102,46 @@ if (-not $libFile) {
85 Write-Error "Could not find MSVC build tools (dumpbin.exe, lib.exe). Install 'Desktop development with C++' workload." 102 Write-Error "Could not find MSVC build tools (dumpbin.exe, lib.exe). Install 'Desktop development with C++' workload."
86 } 103 }
87 104
88 # Export function names from DLL 105 # Export function names from DLL and write .def file
89 $defPath = Join-Path $mpvDevDir "mpv.def" 106 $defPath = Join-Path $OutputDir "mpv.def"
90 $exports = & $dumpbin /exports "$($dllForLib.FullName)" 2>&1 | 107 $exports = & $dumpbin /exports "$($dllForLib.FullName)" 2>&1 |
91 Select-String "^\s+\d+\s+[0-9A-Fa-f]+\s+[0-9A-Fa-f]+\s+(\S+)" | 108 Select-String "^\s+\d+\s+[0-9A-Fa-f]+\s+[0-9A-Fa-f]+\s+(\S+)" |
92 ForEach-Object { $_.Matches[0].Groups[1].Value } 109 ForEach-Object { $_.Matches[0].Groups[1].Value }
93 110
94 # Write .def file
95 $defContent = "LIBRARY libmpv-2`nEXPORTS`n" 111 $defContent = "LIBRARY libmpv-2`nEXPORTS`n"
96 $defContent += ($exports | ForEach-Object { " $_" }) -join "`n" 112 $defContent += ($exports | ForEach-Object { " $_" }) -join "`n"
97 Set-Content -Path $defPath -Value $defContent -Encoding ASCII 113 Set-Content -Path $defPath -Value $defContent -Encoding ASCII
98 114
99 # Generate .lib from .def 115 # Generate .lib from .def
100 $machine = if ($arch -eq "x86_64") { "x64" } else { "x86" } 116 $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
102 118
103 if (-not (Test-Path "$mpvDevDir\mpv.lib")) { 119 if (-not (Test-Path "$OutputDir\mpv.lib")) {
104 Write-Error "Failed to generate mpv.lib!" 120 Write-Error "Failed to generate mpv.lib!"
105 } else { 121 } else {
106 Write-Host "Generated mpv.lib successfully." 122 Write-Host "Generated mpv.lib successfully."
107 } 123 }
108} else { 124} else {
109 Copy-Item $libFile.FullName $mpvDevDir 125 Copy-Item $libFile.FullName $OutputDir
110} 126}
111 127
112if ($dllFile) { 128if ($dllFile) {
113 Copy-Item $dllFile.FullName $mpvDevDir 129 Copy-Item $dllFile.FullName $OutputDir
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 }
119} 130}
120 131
121# Also grab any other DLLs we might need 132# Also grab any other DLLs from the archive
122Get-ChildItem -Path $tempExtract -Filter "*.dll" -Recurse | ForEach-Object { 133Get-ChildItem -Path $tempExtract -Filter "*.dll" -Recurse | ForEach-Object {
123 Copy-Item $_.FullName $mpvDevDir -Force 134 Copy-Item $_.FullName $OutputDir -Force
124} 135}
125 136
126# Cleanup 137# Cleanup temp files
127Remove-Item -Force $tempFile -ErrorAction SilentlyContinue 138Remove-Item -Force $tempFile -ErrorAction SilentlyContinue
128Remove-Item -Recurse -Force $tempExtract -ErrorAction SilentlyContinue 139Remove-Item -Recurse -Force $tempExtract -ErrorAction SilentlyContinue
129 140
130$env:MPV_LIB_DIR = $mpvDevDir 141$env:MPV_LIB_DIR = $OutputDir
131Write-Host ""
132Write-Host "Done! mpv dev files extracted to: $mpvDevDir"
133Write-Host "MPV_LIB_DIR set to: $mpvDevDir"
134Write-Host "" 142Write-Host ""
135Write-Host "You can now build with:" 143Write-Host "Done! mpv dev files extracted to: $OutputDir"
136Write-Host " cargo build --release" 144Write-Host "MPV_LIB_DIR set to: $OutputDir"
137Write-Host "" 145Write-Host ""
138Write-Host "To make this permanent, add to your PowerShell profile:" 146Write-Host "To make MPV_LIB_DIR permanent, add to your PowerShell profile:"
139Write-Host " `$env:MPV_LIB_DIR = '$mpvDevDir'" 147Write-Host " `$env:MPV_LIB_DIR = '$OutputDir'"