-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWatch-And-Encode.ps1
More file actions
534 lines (454 loc) · 19.9 KB
/
Watch-And-Encode.ps1
File metadata and controls
534 lines (454 loc) · 19.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
#Requires -Version 5.1
<#
.SYNOPSIS
Watches an incoming directory and encodes video files via HandBrakeCLI
based on detected source resolution (480p, 720p, 1080p).
.DESCRIPTION
Uses FileSystemWatcher to monitor a source directory for new video files.
Scans each file to detect its resolution, then applies an appropriate
HandBrakeCLI encoding profile and delivers the output to a destination
directory. A working directory is used for in-progress encodes to prevent
partial files from appearing in the destination.
.PARAMETER SourceDir
Directory to watch for incoming video files.
.PARAMETER DestDir
Directory where completed encodes are delivered.
.PARAMETER WorkDir
Temporary directory used during encoding. Defaults to DestDir\__working__.
.PARAMETER HandBrakeCLI
Full path to HandBrakeCLI.exe. Defaults to searching PATH.
.PARAMETER FFprobe
Full path to ffprobe.exe. Used for resolution detection.
Defaults to searching PATH.
.PARAMETER Extensions
Array of file extensions to process.
Defaults to mkv, mp4, avi, mov, m4v, ts, wmv, flv, iso.
.PARAMETER PollIntervalSeconds
How often (seconds) to re-scan the source directory for missed files.
Defaults to 60.
.PARAMETER ProgressIntervalSeconds
How often (seconds) to write encode progress to the log while an encode
is running. Defaults to 120.
.EXAMPLE
.\Watch-And-Encode.ps1 -SourceDir "D:\Incoming" -DestDir "D:\Encoded"
.EXAMPLE
.\Watch-And-Encode.ps1 -SourceDir "D:\Incoming" -DestDir "D:\Encoded" `
-HandBrakeCLI "C:\Program Files\HandBrake\HandBrakeCLI.exe"
#>
[CmdletBinding()]
param (
[Parameter(Mandatory)]
[string]$SourceDir,
[Parameter(Mandatory)]
[string]$DestDir,
[string]$WorkDir,
[string]$HandBrakeCLI = "HandBrakeCLI.exe",
[string]$FFprobe = "ffprobe.exe",
[string[]]$Extensions = @("mkv","mp4","avi","mov","m4v","ts","wmv","flv","iso"),
[int]$PollIntervalSeconds = 300,
# How often (seconds) to write encode progress to the log while an encode
# is running. Defaults to every 2 minutes.
[int]$ProgressIntervalSeconds = 120
)
Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"
# ---------------------------------------------------------------------------
# Logging
# ---------------------------------------------------------------------------
$LogFile = Join-Path $DestDir "encode-log.txt"
function Write-Log {
param(
[string]$Message,
[ValidateSet("INFO","WARN","ERROR")][string]$Level = "INFO"
)
$stamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$line = "[$stamp] [$Level] $Message"
Write-Host $line -ForegroundColor $(switch ($Level) {
"WARN" { "Yellow" }
"ERROR" { "Red" }
default { "Cyan" }
})
Add-Content -Path $LogFile -Value $line -Encoding UTF8
}
# ---------------------------------------------------------------------------
# Validate prerequisites
# ---------------------------------------------------------------------------
function Assert-Prerequisites {
$hb = Get-Command $HandBrakeCLI -ErrorAction SilentlyContinue
if (-not $hb) {
Write-Log "HandBrakeCLI not found at '$HandBrakeCLI'. Set -HandBrakeCLI or add it to PATH." ERROR
exit 1
}
$script:HBPath = $hb.Source
Write-Log "HandBrakeCLI found: $($script:HBPath)"
$fp = Get-Command $FFprobe -ErrorAction SilentlyContinue
if (-not $fp) {
Write-Log "ffprobe not found at '$FFprobe'. Install FFmpeg or set -FFprobe." ERROR
exit 1
}
$script:FFprobePath = $fp.Source
Write-Log "ffprobe found: $($script:FFprobePath)"
}
# ---------------------------------------------------------------------------
# Resolution detection via ffprobe
# Reads container metadata only — no frame decode, works in Session 0.
# ---------------------------------------------------------------------------
function Get-VideoResolution {
param([string]$FilePath)
$probeArgs = @(
"-v", "quiet",
"-print_format", "json",
"-show_streams",
"-select_streams", "v:0",
$FilePath
)
$json = (& $script:FFprobePath @probeArgs 2>&1) | Out-String
try {
$streams = ($json | ConvertFrom-Json).streams
if ($streams -and $streams.Count -gt 0) {
return @{ Width = [int]$streams[0].width; Height = [int]$streams[0].height }
}
} catch { }
Write-Log "Could not parse resolution from '$([System.IO.Path]::GetFileName($FilePath))'" WARN
Write-Log "ffprobe output: $json" WARN
return $null
}
# ---------------------------------------------------------------------------
# Classify resolution into a named bucket
# ---------------------------------------------------------------------------
function Get-ResolutionBucket {
param([hashtable]$Resolution)
$h = $Resolution.Height
if ($h -le 480) { return "480p" }
elseif ($h -le 720) { return "720p" }
elseif ($h -le 1080) { return "1080p" }
else { return "4K" }
}
# ---------------------------------------------------------------------------
# Build HandBrakeCLI argument list per resolution bucket
#
# Encoding profiles (adjust RF / preset to taste):
#
# 480p — x264 RF 22 medium 640x480 AAC stereo 128k
# 720p — x264 RF 21 medium 1280x720 AAC stereo 160k
# 1080p — x264 RF 20 medium 1920x1080 AAC stereo 192k
# 4K — x265 RF 18 medium original AAC stereo 192k
# ---------------------------------------------------------------------------
function Get-HandBrakeArgs {
param(
[string]$InputFile,
[string]$OutputFile,
[string]$Bucket
)
$common = @(
"-i", $InputFile,
"-o", $OutputFile,
"--format", "av_mkv",
"--markers" # preserve chapter markers
)
$audioCommon = @(
"--aencoder", "av_aac",
"--mixdown", "stereo",
"--arate", "Auto"
)
$subCommon = @(
"--subtitle", "scan",
"--subtitle-forced"
)
switch ($Bucket) {
"480p" {
return $common + @(
"--encoder", "x264",
"--quality", "22",
"--encoder-preset", "medium",
"--maxWidth", "640",
"--maxHeight", "480",
"--loose-anamorphic",
"--ab", "128"
) + $audioCommon + $subCommon
}
"720p" {
return $common + @(
"--encoder", "x264",
"--quality", "21",
"--encoder-preset", "medium",
"--maxWidth", "1280",
"--maxHeight", "720",
"--loose-anamorphic",
"--ab", "160"
) + $audioCommon + $subCommon
}
"1080p" {
return $common + @(
"--encoder", "x264",
"--quality", "20",
"--encoder-preset", "medium",
"--maxWidth", "1920",
"--maxHeight", "1080",
"--loose-anamorphic",
"--ab", "192"
) + $audioCommon + $subCommon
}
"4K" {
# x265 for 4K; no resize, keep original dimensions
return $common + @(
"--encoder", "x265",
"--quality", "18",
"--encoder-preset", "medium",
"--ab", "192"
) + $audioCommon + $subCommon
}
default { throw "Unknown resolution bucket: $Bucket" }
}
}
# ---------------------------------------------------------------------------
# Extension check helper
# ---------------------------------------------------------------------------
function Test-VideoExtension {
param([string]$FilePath)
$ext = [System.IO.Path]::GetExtension($FilePath).TrimStart('.').ToLower()
return $Extensions -contains $ext
}
# ---------------------------------------------------------------------------
# Track files currently being encoded to prevent duplicate work
# ---------------------------------------------------------------------------
$script:InProgress = [System.Collections.Concurrent.ConcurrentDictionary[string,bool]]::new()
# ---------------------------------------------------------------------------
# Core encode function — called for every qualifying new file
# ---------------------------------------------------------------------------
function Invoke-Encode {
param([string]$FilePath)
# Normalise path
$FilePath = [System.IO.Path]::GetFullPath($FilePath)
$baseName = [System.IO.Path]::GetFileNameWithoutExtension($FilePath)
$outName = "$baseName.mkv"
$workFile = Join-Path $script:WorkDir $outName
$destFile = Join-Path $DestDir $outName
# Guard: already in-progress or already delivered
if ($script:InProgress.ContainsKey($FilePath)) {
Write-Log "Already encoding, skipping: $([System.IO.Path]::GetFileName($FilePath))" WARN
return
}
if (Test-Path $destFile) {
Write-Log "Destination already exists, skipping: $outName" WARN
return
}
[void]$script:InProgress.TryAdd($FilePath, $true)
try {
# ---- Wait for the source file to be fully written / released ----
Write-Log "Waiting for file to become available: $([System.IO.Path]::GetFileName($FilePath))"
$maxWaitSec = 300
$elapsed = 0
$ready = $false
while ($elapsed -lt $maxWaitSec) {
try {
$fs = [System.IO.File]::Open(
$FilePath,
[System.IO.FileMode]::Open,
[System.IO.FileAccess]::Read,
[System.IO.FileShare]::None)
$fs.Close()
$ready = $true
break
} catch {
Start-Sleep -Seconds 3
$elapsed += 3
}
}
if (-not $ready) {
Write-Log "File still locked after ${maxWaitSec}s, skipping: $FilePath" WARN
return
}
# ---- Detect resolution ----
Write-Log "Scanning resolution: $([System.IO.Path]::GetFileName($FilePath))"
$res = Get-VideoResolution -FilePath $FilePath
if (-not $res) { return }
$bucket = Get-ResolutionBucket -Resolution $res
Write-Log ("Detected {0}x{1} → [{2}] | {3}" -f `
$res.Width, $res.Height, $bucket, [System.IO.Path]::GetFileName($FilePath))
# ---- Build args and encode ----
$hbArgs = Get-HandBrakeArgs -InputFile $FilePath -OutputFile $workFile -Bucket $bucket
$hbLog = Join-Path $script:WorkDir "$baseName-hb.log"
$hbLogErr = "$hbLog.err"
Write-Log "Encoding [$bucket]: $([System.IO.Path]::GetFileName($FilePath))"
# Build a manually-quoted argument string for Start-Process.
# Passing a single string (not an array) means it is forwarded verbatim
# to CreateProcess, so spaces inside quoted tokens are preserved.
# Using -PassThru without -Wait gives us a live process handle so we
# can poll stdout for progress while the encode runs.
$argStr = ($hbArgs | ForEach-Object {
if ($_ -match '\s') { '"' + $_ + '"' } else { $_ }
}) -join ' '
$proc = Start-Process -FilePath $script:HBPath `
-ArgumentList $argStr `
-NoNewWindow -PassThru `
-RedirectStandardOutput $hbLog `
-RedirectStandardError $hbLogErr
# Poll for progress while the encode runs.
# HandBrakeCLI writes progress to stdout using \r (not \n), so we
# split on carriage returns to find the latest progress entry.
$lastProgressLog = [datetime]::UtcNow
while (-not $proc.HasExited) {
Start-Sleep -Seconds 5
if (([datetime]::UtcNow - $lastProgressLog).TotalSeconds -ge $ProgressIntervalSeconds) {
try {
$raw = [System.IO.File]::ReadAllText($hbLog)
$progressLine = ($raw -split '\r' |
Where-Object { $_ -match 'Encoding:.*\d+\.\d+\s*%' } |
Select-Object -Last 1)
if ($progressLine -match '(\d+\.\d+)\s*%(?:.*ETA\s+(\S+))?') {
$pct = $Matches[1]
$eta = if ($Matches[2]) { " - ETA $($Matches[2])" } else { '' }
Write-Log "Progress: ${pct}%${eta} [$([System.IO.Path]::GetFileName($FilePath))]"
}
} catch { }
$lastProgressLog = [datetime]::UtcNow
}
}
$proc.WaitForExit()
# HandBrakeCLI on this system exits with code 1 even on success due to
# missing GPU encoder DLLs (nvEncodeAPI64.dll). The exit code is therefore
# not a reliable success signal. Use the presence and size of the output
# file as the primary criterion instead.
$workItem = Get-Item $workFile -ErrorAction SilentlyContinue
if (-not $workItem -or $workItem.Length -eq 0) {
$hbExitCode = $proc.ExitCode
Write-Log "HandBrakeCLI failed (exit $hbExitCode): $([System.IO.Path]::GetFileName($FilePath))" ERROR
# Preserve logs for debugging
Move-Item $hbLog (Join-Path $DestDir "$baseName-hb.log") -Force -EA SilentlyContinue
Move-Item $hbLogErr (Join-Path $DestDir "$baseName-hb.log.err") -Force -EA SilentlyContinue
Remove-Item $workFile -Force -EA SilentlyContinue
return
}
# ---- Deliver to destination ----
Move-Item -LiteralPath $workFile -Destination $destFile -Force
# ---- Archive source so the watch directory does not re-queue it ----
$doneFile = Join-Path $script:DoneDir ([System.IO.Path]::GetFileName($FilePath))
Move-Item -LiteralPath $FilePath -Destination $doneFile -Force
Write-Log "Done: $outName (source archived to __done__)"
# Clean up encode logs on success
Remove-Item $hbLog -Force -EA SilentlyContinue
Remove-Item $hbLogErr -Force -EA SilentlyContinue
} catch {
Write-Log "Unexpected error processing '$([System.IO.Path]::GetFileName($FilePath))': $_" ERROR
} finally {
[void]$script:InProgress.TryRemove($FilePath, [ref]$null)
}
}
# ---------------------------------------------------------------------------
# Startup cleanup — remove orphaned partial files left by a previous run
# that was interrupted mid-encode. The source files remain in SourceDir
# and will be re-queued by the startup scan that follows.
# ---------------------------------------------------------------------------
function Invoke-StartupCleanup {
$orphans = @(Get-ChildItem -LiteralPath $script:WorkDir -File -ErrorAction SilentlyContinue |
Where-Object { Test-VideoExtension -FilePath $_.FullName })
if ($orphans.Count -eq 0) { return }
Write-Log "Found $($orphans.Count) orphaned work file(s) from a previous interrupted run - cleaning up."
foreach ($orphan in $orphans) {
# Try to identify the original source file for a helpful log message
$baseName = [System.IO.Path]::GetFileNameWithoutExtension($orphan.Name)
$sourceMatch = Get-ChildItem -LiteralPath $SourceDir -File -ErrorAction SilentlyContinue |
Where-Object { [System.IO.Path]::GetFileNameWithoutExtension($_.Name) -eq $baseName } |
Select-Object -First 1
if ($sourceMatch) {
Write-Log " Removing partial encode: $($orphan.Name) - source '$($sourceMatch.Name)' will be re-encoded." WARN
} else {
Write-Log " Removing partial encode: $($orphan.Name) - source file no longer in watch directory." WARN
}
Remove-Item -LiteralPath $orphan.FullName -Force -ErrorAction SilentlyContinue
}
}
# ---------------------------------------------------------------------------
# Scan the source directory and encode anything not yet processed
# ---------------------------------------------------------------------------
function Invoke-ScanSource {
$files = Get-ChildItem -LiteralPath $SourceDir -File -ErrorAction SilentlyContinue |
Where-Object { Test-VideoExtension -FilePath $_.FullName }
foreach ($f in $files) {
Invoke-Encode -FilePath $f.FullName
}
}
# ===========================================================================
# MAIN
# ===========================================================================
# Resolve / create required directories
foreach ($dir in @($SourceDir, $DestDir)) {
if (-not (Test-Path $dir)) {
New-Item -ItemType Directory -Path $dir -Force | Out-Null
Write-Log "Created directory: $dir"
}
}
if (-not $WorkDir) { $WorkDir = Join-Path $DestDir "__working__" }
if (-not (Test-Path $WorkDir)) {
New-Item -ItemType Directory -Path $WorkDir -Force | Out-Null
}
$script:WorkDir = $WorkDir
$doneDir = Join-Path $SourceDir "__done__"
if (-not (Test-Path $doneDir)) {
New-Item -ItemType Directory -Path $doneDir -Force | Out-Null
}
$script:DoneDir = $doneDir
# Ensure log file exists
New-Item -ItemType File -Path $LogFile -Force -ErrorAction SilentlyContinue | Out-Null
Assert-Prerequisites
Write-Log "========================================="
Write-Log " Watch-And-Encode started"
Write-Log " Source : $SourceDir"
Write-Log " Done : $doneDir"
Write-Log " Dest : $DestDir"
Write-Log " Work : $WorkDir"
Write-Log " HB CLI : $($script:HBPath)"
Write-Log " Watch : $($Extensions -join ', ')"
Write-Log " Poll : every ${PollIntervalSeconds}s"
Write-Log " Press Ctrl+C to stop."
Write-Log "========================================="
# Clean up any partial work files left by a previous interrupted run,
# then re-queue source files for encoding via the startup scan below.
Invoke-StartupCleanup
# Process files already sitting in the source directory on startup
Write-Log "Scanning source directory for existing files..."
Invoke-ScanSource
# ---------------------------------------------------------------------------
# FileSystemWatcher — react to new / renamed files in real time
# ---------------------------------------------------------------------------
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = $SourceDir
$watcher.IncludeSubdirectories = $false
$watcher.NotifyFilter = [System.IO.NotifyFilters]::FileName -bor
[System.IO.NotifyFilters]::LastWrite
$watcher.EnableRaisingEvents = $true
$onCreated = Register-ObjectEvent -InputObject $watcher -EventName Created -Action {
param($s, $e)
if (Test-VideoExtension -FilePath $e.FullPath) {
Write-Log "New file detected: $($e.Name)"
Invoke-Encode -FilePath $e.FullPath
}
}
$onRenamed = Register-ObjectEvent -InputObject $watcher -EventName Renamed -Action {
param($s, $e)
if (Test-VideoExtension -FilePath $e.FullPath) {
Write-Log "File renamed/moved in: $($e.Name)"
Invoke-Encode -FilePath $e.FullPath
}
}
# ---------------------------------------------------------------------------
# Main loop — also polls periodically as a safety net
# ---------------------------------------------------------------------------
try {
$nextPoll = [datetime]::UtcNow.AddSeconds($PollIntervalSeconds)
while ($true) {
Start-Sleep -Seconds 5
if ([datetime]::UtcNow -ge $nextPoll) {
Write-Log "Polling source directory..."
Invoke-ScanSource
$nextPoll = [datetime]::UtcNow.AddSeconds($PollIntervalSeconds)
}
}
} finally {
Unregister-Event -SubscriptionId $onCreated.Id -ErrorAction SilentlyContinue
Unregister-Event -SubscriptionId $onRenamed.Id -ErrorAction SilentlyContinue
$watcher.EnableRaisingEvents = $false
$watcher.Dispose()
Write-Log "Watch-And-Encode stopped."
}