Skip to content

Commit 9b00429

Browse files
Merge pull request #10 from patrickenfuego/progress-bug-fix
Progress bug fix
2 parents 4b709d6 + 8f3c6bb commit 9b00429

File tree

5 files changed

+134
-50
lines changed

5 files changed

+134
-50
lines changed

modules/FFTools/FFTools.psd1

+2-1
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,8 @@ AliasesToExport = 'iffmpeg', 'cropfile', 'cropdim'
9191
FileList = 'FFTools.psd1', 'FFTools.psm1', 'Private\Set-AudioPreference.ps1', 'Private\Get-SubtitleStream', 'Private\Set-SubtitlePreference',
9292
'Private\Get-HDRMetadata.ps1', 'Public\Invoke-FFMpeg.ps1', 'Public\Invoke-TwoPassFFMpeg.ps1', 'Public\New-CropFile.ps1', 'Public\Measure-CropDimensions.ps1', 'Public\Invoke-VMAF.ps1',
9393
'Private\ConvertTo-Stereo.ps1', 'Private\Set-PresetParameters.ps1', 'Private\Set-FFMPegArgs.ps1', 'Private\Set-VideoFilter.ps1', 'Private\Set-TestParameters.ps1',
94-
'Private\Confirm-Parameters.ps1', 'Private\Set-DVArgs.ps1', 'Utils\Invoke-DeeEncoder.ps1','Utils\Confirm-ScaleFilter.ps1','Utils\Write-Report.ps1',
94+
'Private\Watch-ScriptTerminated.ps1', 'Private\Confirm-Parameters.ps1', 'Private\Set-DVArgs.ps1',
95+
'Utils\Invoke-DeeEncoder.ps1','Utils\Confirm-ScaleFilter.ps1','Utils\Write-Report.ps1',
9596
'Utils\Invoke-MkvMerge.ps1', 'Utils\Confirm-HDR10Plus.ps1', 'Utils\Confirm-DolbyVision.ps1', 'Utils\Remove-FilePrompt.ps1', 'Utils\Read-Config.ps1'
9697

9798
# Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell.

modules/FFTools/FFTools.psm1

+5-1
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,10 @@ $Script:dee = @{
6666
DeeArgs = @('dee_ddp', 'dee_eac3', 'dee_dd', 'dee_ac3', 'dee_thd', 'dee_ddp_51', 'dee_eac3_51')
6767
DeeUsed = $false
6868
}
69+
# Keep track of frame count for 2-pass encodes
70+
$Script:frame = @{
71+
FrameCount = 0
72+
}
6973

7074
# Detect operating system info
7175
if ($isMacOs) {
@@ -133,7 +137,7 @@ ___________ .__ __ .__ ______________________
133137
'@
134138

135139
# Current script release version
136-
[version]$release = '2.2.0'
140+
[version]$release = '2.2.1'
137141

138142

139143
#### End module variables ####
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
<#
2+
.SYNOPSIS
3+
Watches for CTRL+C interrupts and clean exits all running jobs and scripts
4+
#>
5+
function Watch-ScriptTerminated {
6+
[CmdletBinding()]
7+
param (
8+
[Parameter(Mandatory = $true, Position = 0)]
9+
[string]$Message
10+
)
11+
12+
if ($Host.UI.RawUI.KeyAvailable -and ($key = $Host.UI.RawUI.ReadKey("AllowCtrlC,NoEcho,IncludeKeyUp"))) {
13+
# If user hits Ctrl+C
14+
if ([int]$key.Character -eq 3) {
15+
Write-Progress "Terminated" -Completed
16+
Write-Warning "CTRL+C was detected - shutting down all running jobs before exiting the script"
17+
# Clean up all running jobs before exiting
18+
Get-Job | Stop-Job -PassThru | Remove-Job -Force -Confirm:$false
19+
20+
$psReq ? (Write-Host "$($aRed)$Message$($reset)") :
21+
(Write-Host $Message @errColors)
22+
23+
$console.WindowTitle = $currentTitle
24+
[console]::TreatControlCAsInput = $false
25+
exit 77
26+
}
27+
28+
# Flush the key buffer again for the next loop
29+
$Host.UI.RawUI.FlushInputBuffer()
30+
}
31+
}

modules/FFTools/Private/Write-EncodeProgress.ps1

+20-38
Original file line numberDiff line numberDiff line change
@@ -31,53 +31,35 @@ function Write-EncodeProgress {
3131
[bool]$DolbyVision
3232
)
3333

34-
<#
35-
.SYNOPSIS
36-
Watches for CTRL+C interrupts and clean exits all running jobs and scripts
37-
#>
38-
function Watch-ScriptTerminated ([string]$Message) {
39-
if ($Host.UI.RawUI.KeyAvailable -and ($Key = $Host.UI.RawUI.ReadKey("AllowCtrlC,NoEcho,IncludeKeyUp"))) {
40-
# If user hits Ctrl+C
41-
if ([int]$Key.Character -eq 3) {
42-
Write-Progress "Terminated" -Completed
43-
Write-Warning "CTRL+C was detected - shutting down all running jobs before exiting the script"
44-
# Clean up all running jobs before exiting
45-
Get-Job | Stop-Job -PassThru | Remove-Job -Force -Confirm:$false
46-
47-
$psReq ? (Write-Host "$($aRed)$Message$($reset)") :
48-
(Write-Host $Message @errColors)
49-
$console.WindowTitle = $currentTitle
50-
[console]::TreatControlCAsInput = $False
51-
exit 77
52-
}
53-
# Flush the key buffer again for the next loop
54-
$Host.UI.RawUI.FlushInputBuffer()
55-
}
56-
}
57-
5834
# Intercept ctrl+C for graceful shutdown of jobs
59-
[console]::TreatControlCAsInput = $True
35+
[console]::TreatControlCAsInput = $true
6036
Start-Sleep -Milliseconds 500
6137
$Host.UI.RawUI.FlushInputBuffer()
6238

6339
if ($PSBoundParameters['TestFrames']) {
64-
$frameCount = $TestFrames
40+
$frame['FrameCount'] = $TestFrames
6541
}
66-
# Gather total frame count without demuxing
67-
else {
68-
if (!$SecondPass) {
69-
Write-Progress "Gathering frame count for progress display..."
70-
$frameStr = ffmpeg -hide_banner -i $InputFile -map 0:v:0 -c:v copy -f null - 2>&1
71-
}
42+
elseif (!$SecondPass -or ($frame['FrameCount'] -le 0)) {
43+
Write-Progress "Gathering frame count for progress display..."
44+
$frameStr = ffmpeg -hide_banner -i $InputFile -map 0:v:0 -c:v copy -f null - 2>&1
45+
7246
# Select-String does not work on this output for some reason?
7347
$tmp = $frameStr | Select-Object -Index ($frameStr.Count - 2)
74-
[int]$frameCount = $tmp |
48+
[int]$frame['FrameCount'] = $tmp |
7549
Select-String -Pattern '^frame=\s*(\d+)\s.*' |
7650
ForEach-Object { $_.Matches.Groups[1].Value }
7751

78-
if (!$frameCount) {
79-
Write-Progress "Could not retrieve frame count" -Completed
80-
return
52+
if (!$frame['FrameCount']) {
53+
Write-Progress "Error" -Completed
54+
$msg = "Failed to parse frame count from string"
55+
$PSCmdlet.ThrowTerminatingError(
56+
[System.Management.Automation.ErrorRecord]::new(
57+
([System.ArgumentNullException]$msg),
58+
'frame',
59+
[System.Management.Automation.ErrorCategory]::InvalidResult,
60+
$frame['FrameCount']
61+
)
62+
)
8163
}
8264
}
8365

@@ -123,9 +105,9 @@ function Write-EncodeProgress {
123105
}
124106

125107
if ($currentFrame -and $fps) {
126-
$progress = ($currentFrame / $frameCount) * 100
108+
$progress = ($currentFrame / $frame['FrameCount']) * 100
127109
$status = '{0:N1}% Complete' -f $progress
128-
$activity = "Encoding Frame $currentFrame of $frameCount, $('{0:N2}' -f $fps) FPS"
110+
$activity = "Encoding Frame $currentFrame of $($frame['FrameCount']), $('{0:N2}' -f $fps) FPS"
129111

130112
$params = @{
131113
PercentComplete = $progress

modules/FFTools/Public/Invoke-FFMpeg.ps1

+76-10
Original file line numberDiff line numberDiff line change
@@ -213,7 +213,10 @@ function Invoke-FFMpeg {
213213
[switch]$DisableProgress
214214
)
215215

216-
# Writes the banner information during encoding
216+
<#
217+
.SYNOPSIS
218+
Writes the banner information during encoding
219+
#>
217220
function Write-Banner {
218221
if ($TestFrames) {
219222
$startStr = switch -Wildcard ($TestStart) {
@@ -247,6 +250,31 @@ function Invoke-FFMpeg {
247250
}
248251
}
249252

253+
<#
254+
.SYNOPSIS
255+
Wait for encode jobs to finish if progress bar returns an error
256+
.DESCRIPTION
257+
If the progress bar function returns an error, this function will wait for the job
258+
to complete while intercepting CTRL+C and gracefully exiting if needed
259+
#>
260+
function Wait-Completed ($JobName, $Exception) {
261+
Write-Host "ERROR: The progress bar failed to initialize`n" @errColors
262+
Write-Verbose "ERROR: $($Exception.Message)"
263+
Write-Verbose "LINE: $($Exception.InvocationInfo.ScriptLineNumber)"
264+
265+
# Intercept ctrl+C for graceful shutdown of jobs
266+
[console]::TreatControlCAsInput = $true
267+
Start-Sleep -Milliseconds 500
268+
$Host.UI.RawUI.FlushInputBuffer()
269+
270+
while ((Get-Job -Name $JobName).State -ne 'Completed') {
271+
Watch-ScriptTerminated -Message $exitBanner
272+
Start-Sleep -Milliseconds 750
273+
}
274+
275+
return
276+
}
277+
250278
# Infer primary language based on streams (for muxing) - NOT always accurate, but pretty close
251279
$streams = ffprobe $Paths.InputFile -show_entries stream=index:stream_tags=language `
252280
-select_streams a -v 0 -of compact=p=0:nk=1
@@ -279,7 +307,8 @@ function Invoke-FFMpeg {
279307
$HDR = Get-HDRMetadata @params
280308
}
281309
catch [System.ArgumentNullException] {
282-
Write-Host "`u{203C} Failed to get HDR metadata: $($_.Exception.Message). Metadata will not be copied" @errColors
310+
$err = $_.Exception.Message
311+
Write-Host "`u{203C} Failed to get HDR metadata: $err. Metadata will not be copied" @errColors
283312
$HDR = $null
284313
}
285314
}
@@ -397,7 +426,13 @@ function Invoke-FFMpeg {
397426
RCLookahead = $RCLookahead
398427
}
399428
# Set preset based arguments based on user input
400-
$presetParams = Set-PresetParameters -Settings $presetArgs -Preset $Preset -Encoder $Encoder -Verbose:$setVerbose
429+
$params = @{
430+
Settings = $presetArgs
431+
Preset = $Preset
432+
Encoder = $Encoder
433+
Verbose = $setVerbose
434+
}
435+
$presetParams = Set-PresetParameters @params
401436
Write-Verbose "PRESET PARAMETER VALUES:`n$($presetParams | Out-String)`n"
402437

403438
<#
@@ -558,7 +593,12 @@ function Invoke-FFMpeg {
558593
DolbyVision = $dovi
559594
Verbose = $setVerbose
560595
}
561-
Write-EncodeProgress @params
596+
try {
597+
Write-EncodeProgress @params
598+
}
599+
catch {
600+
Wait-Completed -JobName '1st Pass' -Exception $_.Exception
601+
}
562602
}
563603

564604
Write-Host
@@ -584,7 +624,12 @@ function Invoke-FFMpeg {
584624
DolbyVision = $dovi
585625
Verbose = $setVerbose
586626
}
587-
Write-EncodeProgress @params
627+
try {
628+
Write-EncodeProgress @params
629+
}
630+
catch {
631+
Wait-Completed -JobName '2nd Pass' -Exception $_.Exception
632+
}
588633
}
589634
}
590635
# CRF/One pass x265 encode
@@ -625,7 +670,12 @@ function Invoke-FFMpeg {
625670
DolbyVision = $dovi
626671
Verbose = $setVerbose
627672
}
628-
Write-EncodeProgress @params
673+
try {
674+
Write-EncodeProgress @params
675+
}
676+
catch {
677+
Wait-Completed -JobName 'crf' -Exception $_.Exception
678+
}
629679
}
630680
}
631681
# Mux/convert audio and subtitle streams separately from elementary hevc stream
@@ -727,7 +777,12 @@ function Invoke-FFMpeg {
727777
Verbose = $setVerbose
728778
DolbyVision = $dovi
729779
}
730-
Write-EncodeProgress @params
780+
try {
781+
Write-EncodeProgress @params
782+
}
783+
catch {
784+
Wait-Completed -JobName 'ffmpeg 1st Pass' -Exception $_.Exception
785+
}
731786
}
732787
}
733788

@@ -753,7 +808,12 @@ function Invoke-FFMpeg {
753808
Verbose = $setVerbose
754809
DolbyVision = $dovi
755810
}
756-
Write-EncodeProgress @params
811+
try {
812+
Write-EncodeProgress @params
813+
}
814+
catch {
815+
Wait-Completed -JobName 'ffmpeg 2nd Pass' -Exception $_.Exception
816+
}
757817
}
758818
}
759819
# CRF encode
@@ -792,8 +852,9 @@ function Invoke-FFMpeg {
792852
}
793853
# Should be unreachable. Throw error and exit script if rate control cannot be detected
794854
else {
855+
$msg = 'Rate control method could not be determined from input parameters'
795856
$params = @{
796-
Exception = [System.FieldAccessException]::new('Rate control method could not be determined from input parameters')
857+
Exception = [System.FieldAccessException]::new($msg)
797858
Category = 'InvalidResult'
798859
TargetObject = $RateControl
799860
ErrorId = 101
@@ -821,7 +882,12 @@ function Invoke-FFMpeg {
821882
DolbyVision = $dovi
822883
Verbose = $setVerbose
823884
}
824-
Write-EncodeProgress @params
885+
try {
886+
Write-EncodeProgress @params
887+
}
888+
catch {
889+
Wait-Completed -JobName 'ffmpeg' -Exception $_.Exception
890+
}
825891
}
826892

827893
# Remove ffmpeg jobs

0 commit comments

Comments
 (0)