-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInvoke-FFmpeg.ps1
More file actions
1453 lines (1230 loc) · 60.9 KB
/
Copy pathInvoke-FFmpeg.ps1
File metadata and controls
1453 lines (1230 loc) · 60.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
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
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
function Invoke-FFmpeg
{
<#
.SYNOPSIS
Converts video files using Samsung-friendly encoding settings with H.264 or H.265 video encoding.
.DESCRIPTION
This function processes video files in a specified directory using Samsung-friendly encoding settings.
For H.264: Supports 4K30 with High profile, Level 5.1, up to 100 Mbps bitrate for optimal Samsung TV compatibility.
For H.265: Supports 4K60 with Level 5.2, up to 100 Mbps bitrate for better compression.
Audio is intelligently converted based on source characteristics: E-AC-3 for multichannel content,
enhanced AAC-LC for stereo, preserving original channel layout and sample rate when possible.
Optimized for Samsung Neo QLED QN70F (2025) and web streaming via built-in browser.
Source files are preserved by default unless -DeleteSourceFile is specified.
.PARAMETER Path
The directory containing the video files to be processed, or individual video file paths.
Accepts an array of paths and supports pipeline input.
.PARAMETER Extension
The file extension of input video files. Defaults to 'mkv'.
.PARAMETER FFmpegPath
Path to the FFmpeg executable. If not specified, attempts to use 'ffmpeg' from PATH,
then falls back to platform-specific default locations.
.PARAMETER Force
If specified, overwrites output files that already exist.
.PARAMETER DeleteSourceFile
If specified, input file(s) will be deleted after successful conversion.
.PARAMETER PauseOnError
If specified, the function will wait for user input when an error occurs instead of automatically continuing to the next file.
.PARAMETER Recurse
If specified, enables recursive searching through all subdirectories.
By default, search is non-recursive (current directory only).
.PARAMETER Exclude
Specifies directories to exclude when searching recursively.
Only applies when -Recurse is specified.
Defaults to @('.git', 'node_modules').
.PARAMETER VideoEncoder
Specifies the video encoder to use. Valid values are 'H.264' and 'H.265'.
H.264 provides faster encoding with 4K30 support, while H.265 offers better compression with 4K60 support.
Defaults to 'H.264' for Samsung TV compatibility.
This parameter cannot be used with -PassthroughVideo.
.PARAMETER PassthroughVideo
If specified, passes through video without re-encoding while still processing audio according to other settings.
This is faster but doesn't apply Samsung-friendly video encoding settings.
This parameter cannot be used with -VideoEncoder.
.PARAMETER PassthroughAudio
If specified, passes through audio without re-encoding while still processing video according to other settings.
This is faster but doesn't apply Samsung-friendly audio encoding settings.
.PARAMETER ClearMetadata
If specified, removes all metadata from the output file. This includes title, artist, album,
comment, creation time, and other metadata tags. Useful for creating clean output files
without any identifying information or unnecessary metadata that can increase file size.
Note: Essential stream metadata required for playback is preserved.
.PARAMETER IncludeSubtitles
Controls subtitle handling behavior. Valid values are:
- 'Auto': Include text-based subtitles only (default for MP4 compatibility)
- 'All': Include all subtitles (may cause errors with bitmap subtitles in MP4)
- 'None': Exclude all subtitles from output
Defaults to 'Auto'.
The 'Auto' mode intelligently detects subtitle types and only includes text-based
subtitles (SRT, ASS, WebVTT) and closed captions (CEA-608/708) that are compatible
with MP4, while skipping
bitmap subtitles (PGS, DVD) that can cause encoding errors. This resolves
the common "Subtitle encoding currently only possible from text to text or
bitmap to bitmap" error when processing files with PGS subtitles.
.PARAMETER OutputPath
Specifies the output file path or directory for the converted video.
If a file path is provided (with extension), the output will be saved to that exact location.
If a directory path is provided, the output file will be saved in that directory with the
original filename but with .mp4 extension.
If not specified, the output file will be created in the same directory as the input file
with .mp4 extension (existing behavior).
This parameter only applies when processing individual files. When processing directories,
the original directory structure is preserved.
.PARAMETER WhatIf
If specified, shows what operations would be performed without actually executing them.
Useful for previewing the conversion process before running it.
.EXAMPLE
PS > Invoke-FFmpeg -Path "C:\Videos" -Extension "mkv"
Processes all .mkv files in C:\Videos using H.264 encoding (default) with Samsung-friendly settings.
.EXAMPLE
PS > Invoke-FFmpeg -Path "C:\Videos" -VideoEncoder "H.265" -Force
Processes videos using H.265 encoding for better compression and overwrites existing output files.
.EXAMPLE
PS > Invoke-FFmpeg -Path "D:\Movies" -Extension "avi" -VideoEncoder "H.264"
Processes all .avi files using H.264 encoding and preserves the input files.
.EXAMPLE
PS > Invoke-FFmpeg -Path "D:\Movies"
Processes only the .mkv files directly in D:\Movies without searching subdirectories (default behavior).
.EXAMPLE
PS > Invoke-FFmpeg -Path "D:\Movies" -Recurse
Processes all .mkv files in D:\Movies and all subdirectories recursively.
.EXAMPLE
PS > Invoke-FFmpeg -Path "D:\Movies" -PassthroughVideo -DeleteSourceFile
Processes all .mkv files using video passthrough (no video re-encoding) and deletes the source files after successful conversion.
.EXAMPLE
PS > Invoke-FFmpeg -Path "D:\Movies" -PassthroughAudio -VideoEncoder "H.265"
Processes all .mkv files using H.265 video encoding while passing through the audio without re-encoding.
.EXAMPLE
PS > Invoke-FFmpeg -Path "C:\Videos" -WhatIf
Shows what operations would be performed on all target files in C:\Videos without actually executing them.
.EXAMPLE
PS > Invoke-FFmpeg -Path "C:\Videos" -IncludeSubtitles "None"
Processes all .mkv files in C:\Videos while excluding all subtitle streams from the output.
.EXAMPLE
PS > Invoke-FFmpeg -Path "C:\Videos" -IncludeSubtitles "All" -PassthroughVideo -PassthroughAudio
Processes videos with passthrough for video/audio and attempts to include all subtitle types (may fail with bitmap subtitles in MP4).
.EXAMPLE
PS > Invoke-FFmpeg -Path @("C:\Videos", "D:\Movies") -Extension "mkv"
Processes all .mkv files in multiple directories by passing an array to the Path parameter.
.EXAMPLE
PS > @("C:\Videos", "D:\Movies") | Invoke-FFmpeg -Extension "mkv"
Processes all .mkv files in multiple directories using pipeline input.
.EXAMPLE
PS > Invoke-FFmpeg -Path ".\Blazing Saddles.mkv" -PassthroughVideo -PassthroughAudio
Processes a single video file with both video and audio passthrough (no re-encoding) and preserves the source file.
.EXAMPLE
PS > Get-ChildItem -Directory | Invoke-FFmpeg -VideoEncoder "H.265"
Processes videos in all subdirectories using H.265 encoding via pipeline input.
.EXAMPLE
PS > Invoke-FFmpeg -Path "C:\Videos" -IncludeSubtitles "None"
Processes all .mkv files in C:\Videos while excluding all subtitle streams from the output.
.EXAMPLE
PS > Invoke-FFmpeg -Path "C:\Videos" -IncludeSubtitles "All" -PassthroughVideo -PassthroughAudio
Processes videos with passthrough for video/audio and attempts to include all subtitle types (may fail with bitmap subtitles in MP4).
.EXAMPLE
PS > Invoke-FFmpeg -Path "movie.mkv" -ClearMetadata
Converts a movie file using default H.264 encoding and removes all metadata from the output file.
.EXAMPLE
PS > Invoke-FFmpeg -Path "C:\Videos" -Recurse -ClearMetadata -VideoEncoder "H.265"
Recursively processes all videos with H.265 encoding and strips all metadata tags for clean output files.
.EXAMPLE
PS > Invoke-FFmpeg -Path "C:\Movies" -VideoEncoder "H.264" -Verbose
Processes movies with H.264 encoding and shows detailed audio codec selection reasoning:
- Files with 5.1/7.1 surround sound: Automatically uses E-AC-3 at 640k for Samsung Neo QLED
- Stereo files: Uses enhanced AAC-LC at 256k-320k (vs legacy 192k)
- Preserves original sample rates ≥48kHz and channel layouts
.EXAMPLE
PS > Invoke-FFmpeg -Path "D:\TV Shows" -Extension "mkv" -Recurse -VideoEncoder "H.265"
Recursively processes TV show files with H.265 encoding and intelligent audio optimization:
- Multichannel episodes: Converted to E-AC-3 for surround sound preservation
- Stereo episodes: Enhanced to high-quality AAC-LC encoding
- All optimized for Samsung Neo QLED QN70F (2025) and web streaming
.EXAMPLE
PS > Invoke-FFmpeg -Path "movie-with-dts.mkv" -PassthroughVideo
Processes a single movie file with video passthrough while intelligently handling audio:
- If source has DTS 5.1: Converts to E-AC-3 640k for Samsung compatibility
- If source has stereo: Upgrades to AAC-LC 256k+ for better quality
- Maintains web streaming optimization with +faststart
.EXAMPLE
PS > Invoke-FFmpeg -Path "movie.mkv" -OutputPath "converted\movie.mp4"
Converts a single movie file and saves it to the specified output path.
.EXAMPLE
PS > Invoke-FFmpeg -Path "video.mkv" -OutputPath "C:\Converted"
Converts a single video file and saves it to the specified directory with the original filename but .mp4 extension.
.EXAMPLE
PS > Invoke-FFmpeg -Path "source.mkv" -OutputPath "final-output.mp4" -VideoEncoder "H.265"
Converts a video using H.265 encoding and saves it with a custom filename.
.EXAMPLE
PS > Invoke-FFmpeg -Path "movie.mkv" -OutputPath "~/Desktop/converted.mp4" -PassthroughVideo
Converts a video with video passthrough and saves it to the user's Desktop with a custom filename.
.EXAMPLE
PS > Invoke-FFmpeg -Path "~/Downloads/sample.mkv" -OutputPath "~/Videos/converted-sample.mp4" -VideoEncoder "H.265"
Converts a specific video file from the Downloads folder using H.265 encoding and saves it to the Videos folder with a new filename.
.LINK
https://ffmpeg.org/documentation.html
.NOTES
Author: Jon LaBelle
License: MIT
Source: https://github.com/jonlabelle/pwsh-profile/blob/main/Functions/MediaProcessing/Invoke-FFmpeg.ps1
.LINK
https://github.com/jonlabelle/pwsh-profile/blob/main/Functions/MediaProcessing/Invoke-FFmpeg.ps1
#>
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingWriteHost', '')]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidGlobalVars', '')]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '')]
[CmdletBinding(DefaultParameterSetName = 'Encode', SupportsShouldProcess)]
[OutputType([System.Boolean])]
param(
[Parameter(Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName)]
[Alias('Directory', 'Folder', 'Location')]
[ValidateNotNullOrEmpty()]
[string[]]
$Path = (Get-Location),
[Parameter(Position = 1)]
[ValidateNotNullOrEmpty()]
[string]
$Extension = 'mkv',
[Parameter(Position = 2)]
[ValidateNotNullOrEmpty()]
[string]
$FFmpegPath,
[Parameter()]
[switch]
$Force,
[Parameter()]
[switch]
$DeleteSourceFile,
[Parameter()]
[switch]
$PauseOnError,
[Parameter()]
[switch]
$Recurse,
[Parameter()]
[string[]]
$Exclude = @('.git', 'node_modules'),
[Parameter(ParameterSetName = 'Encode')]
[ValidateSet('H.264', 'H.265')]
[string]
$VideoEncoder = 'H.264',
[Parameter(ParameterSetName = 'VideoPassthrough')]
[switch]
$PassthroughVideo,
[Parameter()]
[switch]
$PassthroughAudio,
[Parameter()]
[switch]
$ClearMetadata,
[Parameter()]
[ValidateSet('Auto', 'All', 'None')]
[string]
$IncludeSubtitles = 'Auto',
[Parameter()]
[ValidateNotNullOrEmpty()]
[string]
$OutputPath
)
begin
{
# Platform detection
if ($PSVersionTable.PSVersion.Major -lt 6)
{
# PowerShell 5.1 - Windows only
$script:IsWindowsPlatform = $true
$script:IsMacOSPlatform = $false
$script:IsLinuxPlatform = $false
}
else
{
# PowerShell Core - cross-platform
$script:IsWindowsPlatform = $IsWindows
$script:IsMacOSPlatform = $IsMacOS
$script:IsLinuxPlatform = $IsLinux
}
function Write-VerboseMessage
{
param([string]$Message)
if ($VerbosePreference -eq 'Continue')
{
Write-Host $Message -ForegroundColor Cyan
}
}
# The time will be display as:
# - 10 seconds
# - 1 minute 30 seconds
# - 1 day, 3 hours, 20 minutes and 10 seconds
function Format-ElapsedTime
{
param(
[DateTime]$StartTime,
[DateTime]$EndTime
)
$elapsedTime = $EndTime - $StartTime
$timeFormatted = ''
if ($elapsedTime.Days -gt 0)
{
$timeFormatted += "$($elapsedTime.Days) day$(if ($elapsedTime.Days -ne 1) { 's' }), "
}
if ($elapsedTime.Hours -gt 0)
{
$timeFormatted += "$($elapsedTime.Hours) hour$(if ($elapsedTime.Hours -ne 1) { 's' }), "
}
if ($elapsedTime.Minutes -gt 0)
{
$timeFormatted += "$($elapsedTime.Minutes) minute$(if ($elapsedTime.Minutes -ne 1) { 's' }) and "
}
$seconds = [math]::Round($elapsedTime.TotalSeconds - ($elapsedTime.Days * 86400) - ($elapsedTime.Hours * 3600) - ($elapsedTime.Minutes * 60))
$timeFormatted += "$seconds second$(if ($seconds -ne 1) { 's' })"
return $timeFormatted
}
# Function to format file size in human-readable format
function Format-FileSize
{
param([long]$SizeInBytes)
if ($SizeInBytes -eq 0) { return '0 B' }
$units = @('B', 'KB', 'MB', 'GB', 'TB')
$index = 0
$size = [double]$SizeInBytes
while ($size -ge 1024 -and $index -lt ($units.Length - 1))
{
$size /= 1024
$index++
}
return '{0:N2} {1}' -f $size, $units[$index]
}
# Function to estimate remaining time based on current progress
function Get-EstimatedTimeRemaining
{
param(
[DateTime]$StartTime,
[int]$CompletedItems,
[int]$TotalItems
)
if ($CompletedItems -eq 0) { return 'Calculating...' }
$elapsedTime = (Get-Date) - $StartTime
$averageTimePerItem = $elapsedTime.TotalSeconds / $CompletedItems
$remainingItems = $TotalItems - $CompletedItems
$estimatedRemainingSeconds = $averageTimePerItem * $remainingItems
$remainingTime = [TimeSpan]::FromSeconds($estimatedRemainingSeconds)
if ($remainingTime.TotalHours -ge 1)
{
return '{0:D2}h {1:D2}m {2:D2}s' -f $remainingTime.Hours, $remainingTime.Minutes, $remainingTime.Seconds
}
elseif ($remainingTime.TotalMinutes -ge 1)
{
return '{0:D2}m {1:D2}s' -f $remainingTime.Minutes, $remainingTime.Seconds
}
else
{
return '{0:D2}s' -f $remainingTime.Seconds
}
}
# Function to analyze audio streams and determine optimal encoding strategy for Samsung Neo QLED QN70F (2025)
function Get-AudioEncodingStrategy
{
param(
[String]$FilePath,
[String]$FFmpegPath
)
try
{
# Helper function to load Get-VideoDetails dependency if needed
function Import-DependencyIfNeeded
{
param(
[Parameter(Mandatory)]
[String]$FunctionName,
[Parameter(Mandatory)]
[String]$RelativePath
)
if (-not (Get-Command -Name $FunctionName -ErrorAction SilentlyContinue))
{
Write-Verbose "$FunctionName is required - attempting to load it"
# Resolve path from current script location
$dependencyPath = Join-Path -Path $PSScriptRoot -ChildPath $RelativePath
$dependencyPath = [System.IO.Path]::GetFullPath($dependencyPath)
if (Test-Path -Path $dependencyPath -PathType Leaf)
{
try
{
. $dependencyPath
Write-Verbose "Loaded $FunctionName from: $dependencyPath"
}
catch
{
throw "Failed to load required dependency '$FunctionName' from '$dependencyPath': $($_.Exception.Message)"
}
}
else
{
throw "Required function '$FunctionName' could not be found. Expected location: $dependencyPath"
}
}
else
{
Write-Verbose "$FunctionName is already loaded"
}
}
# Load Get-MediaInfo if needed
Import-DependencyIfNeeded -FunctionName 'Get-MediaInfo' -RelativePath 'Get-MediaInfo.ps1'
# Try to find ffprobe path for Get-MediaInfo
$ffprobeExecutable = $FFmpegPath -replace 'ffmpeg(\.exe)?$', 'ffprobe$1'
if (-not (Test-Path $ffprobeExecutable))
{
# Fallback: try ffprobe in PATH
$ffprobeCommand = Get-Command -Name 'ffprobe' -ErrorAction SilentlyContinue
if ($ffprobeCommand)
{
$ffprobeExecutable = $ffprobeCommand.Source
}
else
{
Write-Verbose 'FFprobe not found - using fallback audio settings'
return @{
Codec = 'aac'
Bitrate = '256k'
Channels = '2'
SampleRate = '48000'
Reasoning = 'Fallback: FFprobe unavailable'
}
}
}
# Use Get-MediaInfo to analyze the file
$mediaInfo = Get-MediaInfo -Path $FilePath -FFprobePath $ffprobeExecutable -Extended -ErrorAction SilentlyContinue
if (-not $mediaInfo -or -not $mediaInfo.Audio -or $mediaInfo.Audio.Count -eq 0)
{
Write-Verbose 'No audio stream detected - using default settings'
return @{
Codec = 'aac'
Bitrate = '256k'
Channels = '2'
SampleRate = '48000'
Reasoning = 'No audio stream detected'
}
}
# Analyze primary audio stream (first audio track)
$primaryAudio = $mediaInfo.Audio[0]
$channels = [int]$primaryAudio.Channels
$sampleRate = [int]$primaryAudio.SampleRate
$sourceCodec = $primaryAudio.Codec.ToLower()
Write-Verbose "Source audio: $sourceCodec, $channels channels, $sampleRate Hz"
# Samsung Neo QLED QN70F (2025) intelligent codec selection
if ($channels -gt 2)
{
# Multichannel content: Use E-AC-3 for Samsung Neo QLED optimal support
$targetChannels = [Math]::Min($channels, 8) # Cap at 7.1 (8 channels)
return @{
Codec = 'eac3'
Bitrate = '640k' # E-AC-3 supports up to 640k efficiently
Channels = $targetChannels.ToString()
SampleRate = ([Math]::Max($sampleRate, 48000)).ToString()
Reasoning = "Multichannel ($channels ch) → E-AC-3 for Samsung Neo QLED surround support"
}
}
else
{
# Stereo content: Use enhanced AAC-LC with higher bitrate than legacy 192k
$targetBitrate = if ($sampleRate -ge 96000) { '320k' } elseif ($sampleRate -ge 48000) { '256k' } else { '224k' }
return @{
Codec = 'aac'
Bitrate = $targetBitrate
Channels = '2'
SampleRate = ([Math]::Max($sampleRate, 48000)).ToString()
Reasoning = "Stereo → Enhanced AAC-LC ($targetBitrate) for Samsung Neo QLED quality"
}
}
}
catch
{
Write-Verbose "Error analyzing audio stream: $($_.Exception.Message)"
return @{
Codec = 'aac'
Bitrate = '256k'
Channels = '2'
SampleRate = '48000'
Reasoning = 'Error during analysis - using enhanced fallback'
}
}
}
# Function to analyze subtitle streams and determine handling strategy
function Get-SubtitleHandlingStrategy
{
param(
[String]$FilePath,
[String]$FFmpegPath,
[String]$IncludeSubtitles
)
if ($IncludeSubtitles -eq 'None')
{
return @{
IncludeSubtitles = $false
SubtitleArgs = @()
WarningMessage = $null
}
}
try
{
$fallbackSubtitleHandling = {
param([string]$Reason)
return @{
IncludeSubtitles = $true
SubtitleArgs = @('-c:s', 'mov_text', '-map', '0:s?')
WarningMessage = "$Reason - falling back to re-encoding all subtitle streams to mov_text (bitmap subtitles may fail in MP4)"
}
}
# Use the existing Get-MediaInfo function to get subtitle information
# Helper function to load Get-MediaInfo dependency if needed
function Import-DependencyIfNeeded
{
param(
[Parameter(Mandatory)]
[String]$FunctionName,
[Parameter(Mandatory)]
[String]$RelativePath
)
if (-not (Get-Command -Name $FunctionName -ErrorAction SilentlyContinue))
{
Write-Verbose "$FunctionName is required - attempting to load it"
# Resolve path from current script location
$dependencyPath = Join-Path -Path $PSScriptRoot -ChildPath $RelativePath
$dependencyPath = [System.IO.Path]::GetFullPath($dependencyPath)
if (Test-Path -Path $dependencyPath -PathType Leaf)
{
try
{
. $dependencyPath
Write-Verbose "Loaded $FunctionName from: $dependencyPath"
}
catch
{
throw "Failed to load required dependency '$FunctionName' from '$dependencyPath': $($_.Exception.Message)"
}
}
else
{
throw "Required function '$FunctionName' could not be found. Expected location: $dependencyPath"
}
}
else
{
Write-Verbose "$FunctionName is already loaded"
}
}
# Load Get-MediaInfo if needed
Import-DependencyIfNeeded -FunctionName 'Get-MediaInfo' -RelativePath 'Get-MediaInfo.ps1'
# Try to find ffprobe path for Get-MediaInfo
$ffprobeExecutable = $FFmpegPath -replace 'ffmpeg(\.exe)?$', 'ffprobe$1'
if (-not (Test-Path $ffprobeExecutable))
{
# Fallback: try ffprobe in PATH
$ffprobeCommand = Get-Command -Name 'ffprobe' -ErrorAction SilentlyContinue
if ($ffprobeCommand)
{
$ffprobeExecutable = $ffprobeCommand.Source
}
else
{
Write-Verbose 'FFprobe not found - subtitle analysis skipped'
return $fallbackSubtitleHandling.Invoke('Subtitle analysis unavailable (ffprobe not found)')
}
}
# Use Get-MediaInfo to analyze the file
$mediaInfo = Get-MediaInfo -Path $FilePath -FFprobePath $ffprobeExecutable -Extended -ErrorAction SilentlyContinue
if (-not $mediaInfo -or -not $mediaInfo.Subtitles -or $mediaInfo.Subtitles.Count -eq 0)
{
return $fallbackSubtitleHandling.Invoke('Subtitle analysis returned no subtitle streams')
}
# Categorize subtitle streams using the detailed subtitle information
$textBasedCodecs = @('subrip', 'ass', 'ssa', 'webvtt', 'mov_text', 'srt', 'text')
$closedCaptionCodecs = @('eia_608', 'eia_708', 'cea_608', 'cea_708', 'cc_dec', 'scc')
$bitmapCodecs = @('hdmv_pgs_subtitle', 'dvd_subtitle', 'pgssub', 'dvdsub', 'pgs')
$textSubtitles = @()
$bitmapSubtitles = @()
$closedCaptionSubtitles = @()
foreach ($subtitle in $mediaInfo.Subtitles)
{
$codecName = if ($subtitle.Codec) { $subtitle.Codec.ToLower() } else { '' }
if ($codecName -in $closedCaptionCodecs)
{
$closedCaptionSubtitles += $subtitle
}
elseif ($codecName -in $textBasedCodecs)
{
$textSubtitles += $subtitle
}
elseif ($codecName -in $bitmapCodecs)
{
$bitmapSubtitles += $subtitle
}
else
{
# Unknown codec, treat as bitmap for safety
$bitmapSubtitles += $subtitle
}
}
$warningMessage = $null
$subtitleArgs = @()
$includeSubtitles = $false
$subtitleCodecArgs = @()
$subtitleMapArgs = @()
$subtitleOutputIndex = 0
if ($closedCaptionSubtitles.Count -gt 0)
{
Write-Verbose "Detected $($closedCaptionSubtitles.Count) closed caption stream(s); including for output"
}
if ($IncludeSubtitles -eq 'All')
{
if ($bitmapSubtitles.Count -gt 0)
{
$warningMessage = "Warning: File contains $($bitmapSubtitles.Count) bitmap subtitle stream(s) (e.g., PGS/DVD subtitles) which may not be compatible with MP4. Consider using -IncludeSubtitles 'Auto' or 'None'."
}
foreach ($subtitle in ($textSubtitles + $closedCaptionSubtitles + $bitmapSubtitles))
{
$subtitleMapArgs += @('-map', "0:$($subtitle.Index)")
if ($subtitle -in $textSubtitles)
{
$subtitleCodecArgs += @("-c:s:$subtitleOutputIndex", 'mov_text')
}
else
{
# Preserve closed captions and bitmap subtitles without re-encoding
$subtitleCodecArgs += @("-c:s:$subtitleOutputIndex", 'copy')
}
$subtitleOutputIndex++
}
if ($subtitleMapArgs.Count -gt 0)
{
$subtitleArgs = $subtitleCodecArgs + $subtitleMapArgs
$includeSubtitles = $true
}
}
elseif ($IncludeSubtitles -eq 'Auto')
{
foreach ($subtitle in $textSubtitles)
{
# Re-encode text subtitles to mov_text for MP4 compatibility
$subtitleMapArgs += @('-map', "0:$($subtitle.Index)")
$subtitleCodecArgs += @("-c:s:$subtitleOutputIndex", 'mov_text')
$subtitleOutputIndex++
}
foreach ($subtitle in $closedCaptionSubtitles)
{
# Preserve closed captions without re-encoding
$subtitleMapArgs += @('-map', "0:$($subtitle.Index)")
$subtitleCodecArgs += @("-c:s:$subtitleOutputIndex", 'copy')
$subtitleOutputIndex++
}
if ($subtitleMapArgs.Count -gt 0)
{
$subtitleArgs = $subtitleCodecArgs + $subtitleMapArgs
$includeSubtitles = $true
}
if ($bitmapSubtitles.Count -gt 0)
{
$skippedMessage = "Skipping $($bitmapSubtitles.Count) bitmap subtitle stream(s) for MP4 compatibility"
if ($textSubtitles.Count -gt 0)
{
$warningMessage = "$skippedMessage (including $($textSubtitles.Count) compatible text subtitle(s))"
}
else
{
$warningMessage = $skippedMessage
}
}
}
return @{
IncludeSubtitles = $includeSubtitles
SubtitleArgs = $subtitleArgs
WarningMessage = $warningMessage
}
}
catch
{
Write-Verbose "Error analyzing subtitle streams: $($_.Exception.Message)"
return @{
IncludeSubtitles = $false
SubtitleArgs = @()
WarningMessage = $null
}
}
}
# Function to validate and resolve FFmpeg path
function Get-ValidFFmpegPath
{
param([string]$ProvidedPath)
$resolvedPath = $ProvidedPath
# Normalize FFmpeg path if provided (handles ~, relative paths)
if ($resolvedPath)
{
$resolvedPath = $PSCmdlet.SessionState.Path.GetUnresolvedProviderPathFromPSPath($resolvedPath)
}
if (-not $resolvedPath)
{
# Try to find in PATH first
$ffmpegCommand = Get-Command 'ffmpeg' -ErrorAction SilentlyContinue
if ($ffmpegCommand)
{
$resolvedPath = $ffmpegCommand.Path
Write-VerboseMessage "Using FFmpeg from PATH: $resolvedPath"
}
else
{
# Platform-specific default locations
if ($script:IsWindowsPlatform)
{
# Try common Windows locations
$commonPaths = @(
'C:\ffmpeg\bin\ffmpeg.exe',
'C:\Program Files\ffmpeg\bin\ffmpeg.exe',
'C:\Program Files (x86)\ffmpeg\bin\ffmpeg.exe',
"$env:USERPROFILE\ffmpeg\bin\ffmpeg.exe",
"$env:LOCALAPPDATA\ffmpeg\bin\ffmpeg.exe",
'C:\tools\ffmpeg\bin\ffmpeg.exe',
'C:\ProgramData\chocolatey\lib\ffmpeg\tools\ffmpeg\bin\ffmpeg.exe',
"$env:USERPROFILE\scoop\apps\ffmpeg\current\bin\ffmpeg.exe",
"$env:USERPROFILE\Documents\ffmpeg\bin\ffmpeg.exe",
'D:\ffmpeg\bin\ffmpeg.exe'
)
$foundPath = $null
foreach ($path in $commonPaths)
{
if (Test-Path $path -PathType Leaf)
{
$foundPath = $path
break
}
}
if ($foundPath)
{
$resolvedPath = $foundPath
Write-VerboseMessage "Found FFmpeg at: $resolvedPath"
}
else
{
$resolvedPath = 'C:\ffmpeg\bin\ffmpeg.exe'
Write-VerboseMessage "Using default Windows path (may not exist): $resolvedPath"
}
}
elseif ($script:IsMacOSPlatform)
{
# Try common macOS locations
$commonPaths = @(
'/usr/local/bin/ffmpeg',
'/opt/homebrew/bin/ffmpeg',
'/usr/bin/ffmpeg',
'/opt/local/bin/ffmpeg',
"$env:HOME/.local/bin/ffmpeg",
'/Applications/ffmpeg/ffmpeg',
'/usr/local/opt/ffmpeg/bin/ffmpeg'
)
$foundPath = $null
foreach ($path in $commonPaths)
{
if (Test-Path $path -PathType Leaf)
{
$foundPath = $path
break
}
}
if ($foundPath)
{
$resolvedPath = $foundPath
Write-VerboseMessage "Found FFmpeg at: $resolvedPath"
}
else
{
$resolvedPath = '/usr/local/bin/ffmpeg'
Write-VerboseMessage "Using default macOS path (may not exist): $resolvedPath"
}
}
else
{
# Try common Linux locations
$commonPaths = @(
'/usr/bin/ffmpeg',
'/usr/local/bin/ffmpeg',
'/snap/bin/ffmpeg',
'/opt/ffmpeg/bin/ffmpeg',
"$env:HOME/.local/bin/ffmpeg",
"$env:HOME/bin/ffmpeg",
'/usr/local/share/ffmpeg/ffmpeg'
)
$foundPath = $null
foreach ($path in $commonPaths)
{
if (Test-Path $path -PathType Leaf)
{
$foundPath = $path
break
}
}
if ($foundPath)
{
$resolvedPath = $foundPath
Write-VerboseMessage "Found FFmpeg at: $resolvedPath"
}
else
{
$resolvedPath = '/usr/bin/ffmpeg'
Write-VerboseMessage "Using default Linux path (may not exist): $resolvedPath"
}
}
}
}
if (-not (Test-Path -Path $resolvedPath -PathType Leaf))
{
throw "FFmpeg executable not found at: '$resolvedPath'"
}
return $resolvedPath
}
# Validate FFmpeg path once in begin block
try
{
$script:ValidatedFFmpegPath = Get-ValidFFmpegPath -ProvidedPath $FFmpegPath
}
catch
{
# Write error and throw to completely stop function execution
Write-Error $_.Exception.Message -ErrorAction Stop
}
# Initialize counters for summary
$script:totalProcessed = 0
$script:totalSuccessful = 0
$script:totalSkipped = 0
$script:totalFailed = 0
$script:scriptStartTime = Get-Date
$script:globalFileCounter = 0
$script:totalFilesAcrossAllPaths = 0
# Normalize file extension (ensure it has no leading dot)
$Extension = $Extension.TrimStart('.')
}
process
{
# First pass: collect all files to get total count for progress reporting
$allFilesToProcess = @()
foreach ($currentPath in $Path)
{
# Normalize path first (handles ~, relative paths)
$normalizedPath = $PSCmdlet.SessionState.Path.GetUnresolvedProviderPathFromPSPath($currentPath)
Write-Verbose "Scanning path: $normalizedPath"
# Validate that the path exists
if (-not (Test-Path -LiteralPath $normalizedPath))
{
Write-Error "Path not found: '$normalizedPath'"
$script:totalFailed++
continue
}
$pathItem = Get-Item -LiteralPath $normalizedPath -ErrorAction Stop
if ($pathItem.PSIsContainer)
{
# Handle directory - search for video files with optional recursion
Write-VerboseMessage "Processing directory: $normalizedPath"
# Find files to process
if ($Recurse)
{
Write-VerboseMessage "Searching recursively for *.$Extension files (excluding $($Exclude -join ', '))"
$filesToProcess = Get-ChildItem -Path $normalizedPath -Recurse -Filter "*.$Extension" -File | Where-Object {
$fullPath = $_.FullName
-not ($Exclude | Where-Object { $fullPath -like "*$_*" })
}
}
else