Repository navigation
Expand file tree
/
Copy pathVidKit.psm1
More file actions
624 lines (505 loc) · 20.3 KB
/
Copy pathVidKit.psm1
File metadata and controls
624 lines (505 loc) · 20.3 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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
#Requires -Version 5.1
# VidKit - a thin, sane PowerShell layer over ffmpeg for the video chores
# you actually do: trim, compress, GIF, extract audio, resize, inspect.
$script:ToolCache = @{}
$script:EncoderCache = $null
#region Internal helpers
function Resolve-FFTool {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[ValidateSet('ffmpeg', 'ffprobe')]
[string]$Name
)
if ($script:ToolCache.ContainsKey($Name)) { return $script:ToolCache[$Name] }
$cmd = Get-Command $Name -CommandType Application -ErrorAction SilentlyContinue |
Select-Object -First 1
if ($cmd) {
$script:ToolCache[$Name] = $cmd.Source
return $cmd.Source
}
$candidates = @(
"$env:ProgramFiles\ffmpeg\bin\$Name.exe"
"${env:ProgramFiles(x86)}\ffmpeg\bin\$Name.exe"
"$env:LOCALAPPDATA\Microsoft\WinGet\Links\$Name.exe"
"$env:ChocolateyInstall\bin\$Name.exe"
"$env:ProgramData\chocolatey\bin\$Name.exe"
"C:\ffmpeg\bin\$Name.exe"
)
foreach ($c in $candidates) {
if ($c -and (Test-Path -LiteralPath $c)) {
$script:ToolCache[$Name] = $c
return $c
}
}
throw "$Name was not found. Install it with 'winget install Gyan.FFmpeg' (then restart your shell), or add it to PATH."
}
function Invoke-FF {
[CmdletBinding()]
param(
[Parameter(Mandatory)][string[]]$Arguments,
[switch]$Quiet
)
$ffmpeg = Resolve-FFTool -Name ffmpeg
$full = @('-hide_banner') + $Arguments
if ($Quiet) { $full += @('-loglevel', 'error') }
else { $full += @('-loglevel', 'warning', '-stats') }
Write-Verbose "ffmpeg $($full -join ' ')"
# ffmpeg reports progress and warnings on stderr even on success. PowerShell
# turns native stderr into error records, which aborts the pipeline under
# $ErrorActionPreference = 'Stop', so relax it for the duration of the call
# and rely on the exit code instead.
$previousPreference = $ErrorActionPreference
$ErrorActionPreference = 'Continue'
try {
if ($Quiet) {
& $ffmpeg @full 2>&1 | Out-Null
}
else {
& $ffmpeg @full 2>&1 | ForEach-Object { Write-Host $_.ToString() }
}
$exitCode = $LASTEXITCODE
}
finally {
$ErrorActionPreference = $previousPreference
}
if ($exitCode -ne 0) {
throw "ffmpeg exited with code $exitCode."
}
}
function ConvertTo-FFTime {
<#
Accepts 90, '90', '1:30', '00:01:30.5' and normalises to something
ffmpeg understands. Returns $null for empty input.
#>
[CmdletBinding()]
param([string]$Value)
if ([string]::IsNullOrWhiteSpace($Value)) { return $null }
$v = $Value.Trim()
if ($v -match '^\d+(\.\d+)?$') { return $v }
if ($v -match '^(\d+:)?\d{1,2}:\d{1,2}(\.\d+)?$') { return $v }
throw "Unrecognised time '$Value'. Use seconds (90), mm:ss (1:30) or hh:mm:ss.ms (00:01:30.5)."
}
function Get-JsonProp {
param($Object, [string]$Name, $Default = $null)
if ($null -eq $Object) { return $Default }
$prop = $Object.PSObject.Properties[$Name]
if ($null -eq $prop -or $null -eq $prop.Value) { return $Default }
return $prop.Value
}
function Resolve-OutputPath {
[CmdletBinding()]
param(
[Parameter(Mandatory)][string]$InputPath,
[string]$Destination,
[AllowEmptyString()]
[string]$Suffix = '',
[string]$Extension
)
$item = Get-Item -LiteralPath $InputPath
if ($Destination) {
# A bare directory means "same name, put it in here".
if (Test-Path -LiteralPath $Destination -PathType Container) {
$ext = if ($Extension) { $Extension } else { $item.Extension }
return Join-Path $Destination ($item.BaseName + $Suffix + $ext)
}
return $Destination
}
$ext = if ($Extension) { $Extension } else { $item.Extension }
return Join-Path $item.DirectoryName ($item.BaseName + $Suffix + $ext)
}
function Test-NvencAvailable {
if ($null -ne $script:EncoderCache) { return $script:EncoderCache }
try {
$ffmpeg = Resolve-FFTool -Name ffmpeg
$previousPreference = $ErrorActionPreference
$ErrorActionPreference = 'Continue'
try {
$encoders = & $ffmpeg -hide_banner -loglevel error -encoders 2>&1 | Out-String
}
finally {
$ErrorActionPreference = $previousPreference
}
$script:EncoderCache = $encoders -match 'h264_nvenc'
}
catch {
$script:EncoderCache = $false
}
return $script:EncoderCache
}
function Format-Bytes {
param([double]$Bytes)
$units = 'B', 'KB', 'MB', 'GB', 'TB'
$i = 0
while ($Bytes -ge 1024 -and $i -lt ($units.Count - 1)) {
$Bytes /= 1024
$i++
}
return ('{0:N2} {1}' -f $Bytes, $units[$i])
}
#endregion
#region Public commands
function Get-VidInfo {
<#
.SYNOPSIS
Reports duration, resolution, fps, codecs and bitrate for a video.
.EXAMPLE
Get-VidInfo .\clip.mp4
.EXAMPLE
Get-ChildItem *.mp4 | Get-VidInfo | Format-Table
#>
[CmdletBinding()]
param(
[Parameter(Mandatory, Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName)]
[Alias('FullName')]
[string[]]$Path
)
process {
foreach ($p in $Path) {
$resolved = (Resolve-Path -LiteralPath $p -ErrorAction Stop).ProviderPath
$ffprobe = Resolve-FFTool -Name ffprobe
$previousPreference = $ErrorActionPreference
$ErrorActionPreference = 'Continue'
try {
$json = & $ffprobe -v error -print_format json -show_format -show_streams -- $resolved 2>&1 | Out-String
$exitCode = $LASTEXITCODE
}
finally {
$ErrorActionPreference = $previousPreference
}
if ($exitCode -ne 0) {
Write-Error "ffprobe could not read '$p'."
continue
}
$data = $json | ConvertFrom-Json
$format = Get-JsonProp $data 'format'
$streams = @(Get-JsonProp $data 'streams' @())
$video = $streams | Where-Object { (Get-JsonProp $_ 'codec_type') -eq 'video' } | Select-Object -First 1
$audio = $streams | Where-Object { (Get-JsonProp $_ 'codec_type') -eq 'audio' } | Select-Object -First 1
# Frame rate arrives as a rational string like "60000/1001".
$fps = $null
$rate = Get-JsonProp $video 'avg_frame_rate'
if ($rate -and $rate -match '^(\d+)/(\d+)$' -and [int]$Matches[2] -ne 0) {
$fps = [math]::Round([int]$Matches[1] / [int]$Matches[2], 3)
}
$durationRaw = Get-JsonProp $format 'duration'
$duration = if ($durationRaw) { [timespan]::FromSeconds([double]$durationRaw) } else { $null }
$sizeRaw = Get-JsonProp $format 'size'
$bitrateRaw = Get-JsonProp $format 'bit_rate'
[pscustomobject]@{
PSTypeName = 'VidKit.VideoInfo'
Name = Split-Path $resolved -Leaf
Path = $resolved
Duration = $duration
Width = Get-JsonProp $video 'width'
Height = Get-JsonProp $video 'height'
Fps = $fps
VideoCodec = Get-JsonProp $video 'codec_name'
AudioCodec = Get-JsonProp $audio 'codec_name'
BitrateMbps = if ($bitrateRaw) { [math]::Round([double]$bitrateRaw / 1MB, 2) } else { $null }
Size = if ($sizeRaw) { Format-Bytes ([double]$sizeRaw) } else { $null }
SizeBytes = if ($sizeRaw) { [long]$sizeRaw } else { $null }
}
}
}
}
function Export-VidClip {
<#
.SYNOPSIS
Trims a section out of a video. Stream-copies by default, so it is
near-instant and lossless.
.DESCRIPTION
Stream copy can only cut on keyframes, so the result may drift by up to
a second. Use -Reencode when you need the cut to land exactly.
.EXAMPLE
Export-VidClip .\gameplay.mp4 -Start 1:30 -End 2:15
.EXAMPLE
Export-VidClip .\gameplay.mp4 -Start 90 -Duration 45 -Reencode
#>
[CmdletBinding(SupportsShouldProcess, DefaultParameterSetName = 'End')]
param(
[Parameter(Mandatory, Position = 0, ValueFromPipelineByPropertyName)]
[Alias('FullName')]
[string]$Path,
[Parameter(Mandatory)]
[string]$Start,
[Parameter(ParameterSetName = 'End')]
[string]$End,
[Parameter(ParameterSetName = 'Duration')]
[string]$Duration,
[string]$Destination,
[switch]$Reencode,
[switch]$Force
)
$resolved = (Resolve-Path -LiteralPath $Path -ErrorAction Stop).ProviderPath
$out = Resolve-OutputPath -InputPath $resolved -Destination $Destination -Suffix '.clip'
if ((Test-Path -LiteralPath $out) -and -not $Force) {
throw "'$out' already exists. Use -Force to overwrite."
}
if (-not $PSCmdlet.ShouldProcess($out, 'Export clip')) { return }
$startTime = ConvertTo-FFTime $Start
$ffArgs = @('-y', '-ss', $startTime, '-i', $resolved)
if ($PSCmdlet.ParameterSetName -eq 'End' -and $End) {
$ffArgs += @('-to', (ConvertTo-FFTime $End))
}
elseif ($Duration) {
$ffArgs += @('-t', (ConvertTo-FFTime $Duration))
}
if ($Reencode) {
$ffArgs += @('-c:v', 'libx264', '-preset', 'medium', '-crf', '18', '-c:a', 'aac', '-b:a', '192k')
}
else {
# -avoid_negative_ts keeps stream-copied cuts from starting with a
# negative timestamp, which breaks some players.
$ffArgs += @('-c', 'copy', '-avoid_negative_ts', 'make_zero')
}
$ffArgs += $out
Invoke-FF -Arguments $ffArgs
Get-Item -LiteralPath $out
}
function Compress-Vid {
<#
.SYNOPSIS
Shrinks a video with a quality target rather than a bitrate guess.
.DESCRIPTION
Uses CRF (constant quality). Lower Quality values look better and
produce bigger files; 18 is visually lossless, 23 is a sensible
default, 28 is small-and-noticeably-soft.
Hardware NVENC encoding is used automatically when available; pass
-Software to force libx264.
.EXAMPLE
Compress-Vid .\raw-4k.mp4 -Quality 23
.EXAMPLE
Get-ChildItem *.mkv | Compress-Vid -Destination .\compressed -Codec hevc
#>
[CmdletBinding(SupportsShouldProcess)]
param(
[Parameter(Mandatory, Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName)]
[Alias('FullName')]
[string[]]$Path,
[ValidateRange(0, 51)]
[int]$Quality = 23,
[ValidateSet('h264', 'hevc')]
[string]$Codec = 'h264',
[ValidateSet('fast', 'medium', 'slow')]
[string]$Preset = 'medium',
[string]$Destination,
[switch]$Software,
[switch]$Force
)
process {
foreach ($p in $Path) {
$resolved = (Resolve-Path -LiteralPath $p -ErrorAction Stop).ProviderPath
$out = Resolve-OutputPath -InputPath $resolved -Destination $Destination -Suffix '.small' -Extension '.mp4'
if ($resolved -eq $out) {
Write-Error "Refusing to overwrite the source file '$resolved' in place."
continue
}
if ((Test-Path -LiteralPath $out) -and -not $Force) {
Write-Error "'$out' already exists. Use -Force to overwrite."
continue
}
if (-not $PSCmdlet.ShouldProcess($out, 'Compress video')) { continue }
$before = (Get-Item -LiteralPath $resolved).Length
$useHw = (-not $Software) -and (Test-NvencAvailable)
if ($useHw) {
$encoder = if ($Codec -eq 'hevc') { 'hevc_nvenc' } else { 'h264_nvenc' }
$hwPreset = switch ($Preset) { 'fast' { 'p1' } 'slow' { 'p7' } default { 'p4' } }
$videoArgs = @('-c:v', $encoder, '-preset', $hwPreset, '-rc', 'vbr', '-cq', "$Quality", '-b:v', '0')
}
else {
$encoder = if ($Codec -eq 'hevc') { 'libx265' } else { 'libx264' }
$videoArgs = @('-c:v', $encoder, '-preset', $Preset, '-crf', "$Quality")
}
Write-Verbose "Encoding with $encoder (hardware: $useHw)"
$ffArgs = @('-y', '-i', $resolved) + $videoArgs +
@('-c:a', 'aac', '-b:a', '160k', '-movflags', '+faststart', $out)
Invoke-FF -Arguments $ffArgs
$after = (Get-Item -LiteralPath $out).Length
$delta = if ($before -gt 0) { [math]::Round((1 - ($after / $before)) * 100, 1) } else { 0 }
if ($delta -ge 0) {
Write-Host ("{0} {1} -> {2} ({3}% smaller)" -f (Split-Path $out -Leaf), (Format-Bytes $before), (Format-Bytes $after), $delta) -ForegroundColor Green
}
else {
# Re-encoding an already well-compressed source can grow it.
Write-Host ("{0} {1} -> {2} ({3}% LARGER - source was already well compressed; try a higher -Quality)" -f (Split-Path $out -Leaf), (Format-Bytes $before), (Format-Bytes $after), [math]::Abs($delta)) -ForegroundColor Yellow
}
Get-Item -LiteralPath $out
}
}
}
function Convert-VidToGif {
<#
.SYNOPSIS
Turns a video (or a slice of one) into a GIF that does not look awful.
.DESCRIPTION
Runs the two-pass palette workflow: generate an optimal palette for the
clip, then map frames onto it. Single-pass GIFs dither against a fixed
216-colour web palette and look muddy, which is why most ffmpeg GIF
one-liners disappoint.
.EXAMPLE
Convert-VidToGif .\clip.mp4 -Start 5 -Duration 6 -Width 640 -Fps 15
#>
[CmdletBinding(SupportsShouldProcess)]
param(
[Parameter(Mandatory, Position = 0, ValueFromPipelineByPropertyName)]
[Alias('FullName')]
[string]$Path,
[string]$Start,
[string]$Duration,
[ValidateRange(16, 3840)]
[int]$Width = 640,
[ValidateRange(1, 60)]
[int]$Fps = 15,
[string]$Destination,
[switch]$Force
)
$resolved = (Resolve-Path -LiteralPath $Path -ErrorAction Stop).ProviderPath
$out = Resolve-OutputPath -InputPath $resolved -Destination $Destination -Suffix '' -Extension '.gif'
if ((Test-Path -LiteralPath $out) -and -not $Force) {
throw "'$out' already exists. Use -Force to overwrite."
}
if (-not $PSCmdlet.ShouldProcess($out, 'Convert to GIF')) { return }
$trim = @()
if ($Start) { $trim += @('-ss', (ConvertTo-FFTime $Start)) }
if ($Duration) { $trim += @('-t', (ConvertTo-FFTime $Duration)) }
$palette = Join-Path ([System.IO.Path]::GetTempPath()) ("vidkit-palette-{0}.png" -f ([guid]::NewGuid().ToString('N')))
$filter = "fps=$Fps,scale=${Width}:-1:flags=lanczos"
try {
Invoke-FF -Arguments (@('-y') + $trim + @('-i', $resolved, '-vf', "$filter,palettegen=stats_mode=diff", $palette)) -Quiet
Invoke-FF -Arguments (@('-y') + $trim + @(
'-i', $resolved,
'-i', $palette,
'-lavfi', "$filter [x]; [x][1:v] paletteuse=dither=bayer:bayer_scale=5:diff_mode=rectangle",
'-loop', '0',
$out
))
}
finally {
if (Test-Path -LiteralPath $palette) { Remove-Item -LiteralPath $palette -Force -ErrorAction SilentlyContinue }
}
$item = Get-Item -LiteralPath $out
Write-Host ("{0} {1}" -f $item.Name, (Format-Bytes $item.Length)) -ForegroundColor Green
$item
}
function Export-VidAudio {
<#
.SYNOPSIS
Pulls the audio track out of a video.
.DESCRIPTION
Defaults to mp3. Use -Format copy to extract the original stream
without re-encoding (fastest, lossless, but the container extension
has to match whatever codec is inside).
.EXAMPLE
Export-VidAudio .\lecture.mp4 -Format mp3 -Bitrate 192
.EXAMPLE
Get-ChildItem *.mp4 | Export-VidAudio -Format wav
#>
[CmdletBinding(SupportsShouldProcess)]
param(
[Parameter(Mandatory, Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName)]
[Alias('FullName')]
[string[]]$Path,
[ValidateSet('mp3', 'wav', 'flac', 'm4a', 'copy')]
[string]$Format = 'mp3',
[ValidateRange(32, 320)]
[int]$Bitrate = 192,
[string]$Destination,
[switch]$Force
)
process {
foreach ($p in $Path) {
$resolved = (Resolve-Path -LiteralPath $p -ErrorAction Stop).ProviderPath
$ext = if ($Format -eq 'copy') { '.m4a' } else { ".$Format" }
$out = Resolve-OutputPath -InputPath $resolved -Destination $Destination -Suffix '' -Extension $ext
if ((Test-Path -LiteralPath $out) -and -not $Force) {
Write-Error "'$out' already exists. Use -Force to overwrite."
continue
}
if (-not $PSCmdlet.ShouldProcess($out, 'Extract audio')) { continue }
$codecArgs = switch ($Format) {
'copy' { @('-c:a', 'copy') }
'wav' { @('-c:a', 'pcm_s16le') }
'flac' { @('-c:a', 'flac') }
'm4a' { @('-c:a', 'aac', '-b:a', "${Bitrate}k") }
default { @('-c:a', 'libmp3lame', '-b:a', "${Bitrate}k") }
}
Invoke-FF -Arguments (@('-y', '-i', $resolved, '-vn') + $codecArgs + @($out))
Get-Item -LiteralPath $out
}
}
}
function Resize-Vid {
<#
.SYNOPSIS
Rescales a video to a target height (or an explicit width x height).
.DESCRIPTION
Aspect ratio is preserved by default and dimensions are snapped to even
numbers, because most H.264/HEVC encoders reject odd ones. If you pass
both -Width and -Height without -Stretch, height wins and width is
derived from the source aspect ratio.
.EXAMPLE
Resize-Vid .\4k.mp4 -Height 1080
.EXAMPLE
Resize-Vid .\clip.mp4 -Width 1280 -Height 720 -Stretch
#>
[CmdletBinding(SupportsShouldProcess)]
param(
[Parameter(Mandatory, Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName)]
[Alias('FullName')]
[string[]]$Path,
[ValidateRange(16, 7680)]
[int]$Width,
[ValidateRange(16, 4320)]
[int]$Height,
[ValidateRange(0, 51)]
[int]$Quality = 21,
[string]$Destination,
[switch]$Stretch,
[switch]$Force
)
begin {
if (-not $Width -and -not $Height) {
throw 'Specify at least one of -Width or -Height.'
}
}
process {
foreach ($p in $Path) {
$resolved = (Resolve-Path -LiteralPath $p -ErrorAction Stop).ProviderPath
$label = if ($Height) { "${Height}p" } else { "${Width}w" }
$out = Resolve-OutputPath -InputPath $resolved -Destination $Destination -Suffix ".$label" -Extension '.mp4'
if ($resolved -eq $out) {
Write-Error "Refusing to overwrite the source file '$resolved' in place."
continue
}
if ((Test-Path -LiteralPath $out) -and -not $Force) {
Write-Error "'$out' already exists. Use -Force to overwrite."
continue
}
if (-not $PSCmdlet.ShouldProcess($out, "Resize to $label")) { continue }
# -2 tells ffmpeg to derive that axis from the aspect ratio and
# round it to the nearest even number.
$scale = if ($Stretch -and $Width -and $Height) {
"scale=${Width}:${Height}"
}
elseif ($Height) {
"scale=-2:${Height}"
}
else {
"scale=${Width}:-2"
}
$scale += ':flags=lanczos'
Invoke-FF -Arguments @(
'-y', '-i', $resolved,
'-vf', $scale,
'-c:v', 'libx264', '-preset', 'medium', '-crf', "$Quality",
'-c:a', 'copy',
'-movflags', '+faststart',
$out
)
Get-Item -LiteralPath $out
}
}
}
#endregion
Export-ModuleMember -Function Get-VidInfo, Export-VidClip, Compress-Vid, Convert-VidToGif, Export-VidAudio, Resize-Vid