Skip to content

Instantly share code, notes, and snippets.

@go2tom42
Last active May 11, 2024 18:02
Show Gist options
  • Save go2tom42/c5dff6e506893425dae8066b358ec9e7 to your computer and use it in GitHub Desktop.
Save go2tom42/c5dff6e506893425dae8066b358ec9e7 to your computer and use it in GitHub Desktop.
Normalize Default audio track, inserts it in Video file, original audio remains
function Start-Normalize {
<#
.SYNOPSIS
Normalized Default audio track, inserts it in Video file, original audio remains a different audio track
.DESCRIPTION
Normalized Default audio track, inserts it in Video file, original audio remains a different audio track
.PARAMETER file
Path to video file that needs normalizing
.PARAMETER codec
Codec for normalized track. Default is 'ac3', use 'ffmpeg -codecs' for full list
.PARAMETER audioext
Audio file extension for normalized track. Default is 'ac3', use 'ffmpeg -codecs' for full list
.PARAMETER bitrate
bitrate for normalized track. Default is '384k'
.PARAMETER freq
Freqency for normalized track. Default is '48000'
.PARAMETER defaultlang
language of track to be normalized. Default is 'eng', All tracks of this type are included in final file, but all other languages are stripped
.PARAMETER 2ndLang
2nd language type to keep in final file, These tracks are not normalized, just included in the final file. Default is none
.PARAMETER keepall
Keeps all languages tracks
.PARAMETER delete
Removes orginal video file after new one is created
.PARAMETER inplace
Removes orginal video file and names new file same original name
.EXAMPLE
Start-Normalize "c:\some\path\to\a\file.mkv", this will generate a file called "c:\some\path\to\a\file.NORMALIZED.mkv" with default settings
.EXAMPLE
Start-Normalize "c:\some\path\to\a\file.mkv" -codec "aac" -audioext "aac" -bitrate "128k" -freq "48000" -defaultlang "eng" -2ndLang "jpn" -delete
.NOTES
Name: Start-Normalize
Author: tom42
Version: 0.0.1
DateCreated: 2024
#>
[CmdletBinding()]
param (
[parameter(Mandatory = $true)]
[alias("f")]
$file,
[parameter(Mandatory = $false)]
[Alias('c')]
[String]$codec = "ac3",
[parameter(Mandatory = $false)]
[Alias('ext')]
[String]$audioext = "ac3" ,
[parameter(Mandatory = $false)]
[Alias('b')]
[String]$bitrate = "384k",
[parameter(Mandatory = $false)]
[Alias('ar')]
[String]$freq = "48000",
[parameter(Mandatory = $false)]
[Alias('l')]
[String]$DefaultLang = 'eng',
[parameter(Mandatory = $false)]
[Alias('lang')]
[String]$2ndLang = '',
[parameter(Mandatory = $false)]
[Alias('2nlang')]
[switch]$keepall,
[parameter(Mandatory = $false)]
[Alias('k')]
[switch]$delete,
[parameter(Mandatory = $false)]
[Alias('i')]
[switch]$InPlace
)
BEGIN {
function Remove-File {
param (
$file
)
# Wait until the file is unlocked
while (($val -le 5) -and (Test-Path $file)) {
Start-Sleep -Seconds 1
Remove-Item -Path $file -Force -ErrorAction Continue
$val++
}
}
function Confirm-Input {
param (
$file
)
if (![System.IO.File]::Exists($file)) {
Write-Host "ERROR file does not exist"
break
}
if ($IsWindows) {
Confirm-choco -exe "ffmpeg.exe" -package "ffmpeg" | Out-Null
Confirm-choco -exe "mkvmerge.exe" -package "mkvtoolnix" | Out-Null
return "\"
}
if ($IsLinux) {
return "/"
}
}
function Start-MKVFilter {
param (
$file,
$DefaultLang,
$2ndLang,
$slash,
$keepall
)
if ($2ndLang) {
$DefaultLang = "$DefaultLang,$2ndLang,und"
} else {
$DefaultLang = "$DefaultLang,und"
}
$mkvmergeEXE = Get-Item (get-command "mkvmerge").source
$Extcheck = Get-Childitem -LiteralPath $file -ErrorAction Stop
write-progress -id 1 -activity "Normalizing audio" -status "Stage 1/5" -PercentComplete 0
write-progress -parentId 1 -Activity "Mkvmerge"
if (Test-Path ("$($Extcheck.DirectoryName)$slash$($Extcheck.BaseName).NORMALIZED$($Extcheck.Extension)")) {
Write-Warning "Normalized file already exists"
exit
}
[string]$IntroSTDOUT_FILE = Join-Path -Path ([IO.Path]::GetTempPath()) -ChildPath ([System.IO.Path]::GetRandomFileName().Split('.')[0] + ".txt")
[string]$IntroSTDERROUT_FILE = Join-Path -Path ([IO.Path]::GetTempPath()) -ChildPath ([System.IO.Path]::GetRandomFileName().Split('.')[0] + ".txt")
if ($keepall) {
$keepallcheck = ' '
}
else {
$keepallcheck = " --atracks $DefaultLang --stracks $DefaultLang "
}
if ($Extcheck.Extension -eq ".avi") {
$mkvmergePROS = Start-Process $mkvmergeEXE -ArgumentList ("-o `"$($Extcheck.FullName.Replace('.avi', '.mkv'))`"$keepallcheck`"$file`"") -RedirectStandardError $IntroSTDERROUT_FILE -RedirectStandardOutput $IntroSTDOUT_FILE -PassThru -NoNewWindow
Start-Sleep -m 1
Do {
Start-Sleep -m 1
$MKVProgress = (Get-content $IntroSTDOUT_FILE | Select-Object -Last 1) | Where-Object { $_ -like "Progress*" }
If ($MKVProgress) {
$MKVPercent = $MKVProgress -replace '\D+'
write-progress -parentId 1 -Activity "MKVmerge" -PercentComplete $MKVPercent -Status ("Filtering video file {0:n2}% completed..." -f $MKVPercent)
}
}Until ($mkvmergePROS.HasExited)
write-progress -parentId 1 -Activity "MKVmerge" -PercentComplete 100 -Status ("Filtering video file {0:n2}% completed..." -f 100)
if (Test-Path ($Extcheck.FullName.Replace('.avi', '.mkv'))) {
Remove-File $file
}
$File = $Extcheck.FullName.Replace('.avi', '.mkv')
Remove-File $IntroSTDERROUT_FILE
Remove-File $IntroSTDOUT_FILE
return Get-Childitem -LiteralPath $file -ErrorAction Stop
} elseif ($Extcheck.Extension -eq ".mp4") {
$mkvmergePROS = Start-Process $mkvmergeEXE -ArgumentList ("-o `"$($Extcheck.FullName.Replace('.mp4', '.mkv'))`"$keepallcheck`"$file`"") -RedirectStandardError $IntroSTDERROUT_FILE -RedirectStandardOutput $IntroSTDOUT_FILE -PassThru -NoNewWindow
Start-Sleep -m 1
Do {
Start-Sleep -m 1
$MKVProgress = (Get-content $IntroSTDOUT_FILE | Select-Object -Last 1) | Where-Object { $_ -like "Progress*" }
If ($MKVProgress) {
$MKVPercent = $MKVProgress -replace '\D+'
write-progress -parentId 1 -Activity "MKVmerge" -PercentComplete $MKVPercent -Status ("Filtering video file {0:n2}% completed..." -f $MKVPercent)
}
}Until ($mkvmergePROS.HasExited)
write-progress -parentId 1 -Activity "MKVmerge" -PercentComplete 100 -Status ("Filtering video file {0:n2}% completed..." -f 100)
if (Test-Path ($Extcheck.FullName.Replace('.mp4', '.mkv'))) {
Remove-File $file
}
$File = $Extcheck.FullName.Replace('.mp4', '.mkv')
Remove-File $IntroSTDERROUT_FILE
Remove-File $IntroSTDOUT_FILE
return Get-Childitem -LiteralPath $file -ErrorAction Stop
} elseif (($Extcheck.Extension -eq ".mkv") -and (!$keepall)) {
$mkvmergePROS = Start-Process $mkvmergeEXE -ArgumentList ("-o `"$($Extcheck.DirectoryName)$slash$($Extcheck.BaseName)~$($Extcheck.Extension)`" --atracks $DefaultLang --stracks $DefaultLang `"$file`"") -RedirectStandardError $IntroSTDERROUT_FILE -RedirectStandardOutput $IntroSTDOUT_FILE -PassThru -NoNewWindow
Start-Sleep -m 1
Do {
Start-Sleep -m 1
$MKVProgress = (Get-content $IntroSTDOUT_FILE | Select-Object -Last 1) | Where-Object { $_ -like "Progress*" }
If ($MKVProgress) {
$MKVPercent = $MKVProgress -replace '\D+'
write-progress -parentId 1 -Activity "MKVmerge" -PercentComplete $MKVPercent -Status ("Filtering video file {0:n2}% completed..." -f $MKVPercent)
}
}Until ($mkvmergePROS.HasExited)
write-progress -parentId 1 -Activity "MKVmerge" -PercentComplete 100 -Status ("Filtering video file {0:n2}% completed..." -f 100)
if (Test-Path "$($Extcheck.DirectoryName)$slash$($Extcheck.BaseName)~$($Extcheck.Extension)") {
Remove-File $file
Move-Item "$($Extcheck.DirectoryName)$slash$($Extcheck.BaseName)~$($Extcheck.Extension)" $file -Force
if (!(Test-Path $file)) {
exit
}
}
Remove-File $IntroSTDERROUT_FILE
Remove-File $IntroSTDOUT_FILE
return Get-Childitem -LiteralPath $file -ErrorAction Stop
} else {
Remove-File $IntroSTDERROUT_FILE
Remove-File $IntroSTDOUT_FILE
return Get-Childitem -LiteralPath $file -ErrorAction Stop
}
}
function Get-Params {
Param(
[parameter(Mandatory = $true)]
$file,
$slash
)
$mkvmergeEXE = Get-Item (get-command "mkvmerge").source
$ffmpegEXE = Get-Item (get-command "ffmpeg").source
$mkv = (& $mkvmergeEXE --ui-language en -J $File | ConvertFrom-Json)
$AudioTrackID = ($mkv.tracks | where-Object { $_.properties.codec_id.StartsWith('A_') }).id
$SubtitleTrackID = ($mkv.tracks | where-Object { $_.properties.codec_id.StartsWith('S_') }).id
$AudioTrack = @()
foreach ($item in $AudioTrackID) {
$d = [ordered]@{ID = $item; Delay = ($(($mkv.tracks | where-Object { $_.ID -eq $item }).properties.minimum_timestamp) / 1000000); track_name = $(($mkv.tracks | where-Object { $_.ID -eq $item }).properties.track_name); Language = $(($mkv.tracks | where-Object { $_.ID -eq $item }).properties.language) }
$Asset = New-Object -TypeName PSObject
$Asset | Add-Member -NotePropertyMembers $d -TypeName Asset
$AudioTrack += $Asset
}
$SubtitleTrack = @()
foreach ($item in $SubtitleTrackID) {
$d = [ordered]@{ID = $item; Delay = ($(($mkv.tracks | where-Object { $_.ID -eq $item }).properties.minimum_timestamp) / 1000000); track_name = $(($mkv.tracks | where-Object { $_.ID -eq $item }).properties.track_name); encoding = $(($mkv.tracks | where-Object { $_.ID -eq $item }).properties.encoding) }
$Asset = New-Object -TypeName PSObject
$Asset | Add-Member -NotePropertyMembers $d -TypeName Asset
$SubtitleTrack += $Asset
}
$VideoTrackInfo = @()
foreach ($item in (($mkv.tracks | where-Object { $_.properties.codec_id.StartsWith('V_') }).id)) {
$d = [ordered]@{ID = $item; Delay = ($(($mkv.tracks | where-Object { $_.ID -eq $item }).properties.minimum_timestamp) / 1000000); track_name = $(($mkv.tracks | where-Object { $_.ID -eq $item }).properties.track_name); display_dimensions = $(($mkv.tracks | where-Object { $_.ID -eq $item }).properties.display_dimensions); color_matrix_coefficients = $(($mkv.tracks | where-Object { $_.ID -eq $item }).properties.color_matrix_coefficients); color_transfer_characteristics = $(($mkv.tracks | where-Object { $_.ID -eq $item }).properties.color_transfer_characteristics); color_primaries = $(($mkv.tracks | where-Object { $_.ID -eq $item }).properties.color_primaries) }
$Asset = New-Object -TypeName PSObject
$Asset | Add-Member -NotePropertyMembers $d -TypeName Asset
$VideoTrackInfo += $Asset
}
function Get-DefaultID {
Param(
[parameter(Mandatory = $false)]
$mkv
)
if ($mkv.tracks | where-Object { $_.properties.codec_id.StartsWith('A_') } | where-object { ($_.properties.language -eq "$DefaultLang") -and ($_.properties.default_track -eq $true) }) {
return ($mkv.tracks | where-Object { $_.properties.codec_id.StartsWith('A_') } | where-object { ($_.properties.language -eq "$DefaultLang") -and ($_.properties.default_track -eq $true) })[0].id
} elseif ($mkv.tracks | where-Object { $_.properties.codec_id.StartsWith('A_') } | where-object { ($_.properties.language -eq "$DefaultLang") -and ($_.properties.default_track -eq $false) }) {
return ($mkv.tracks | where-Object { $_.properties.codec_id.StartsWith('A_') } | where-object { ($_.properties.language -eq "$DefaultLang") -and ($_.properties.default_track -eq $false) })[0].id
} elseif ($mkv.tracks | where-Object { $_.properties.codec_id.StartsWith('A_') } | where-object { $_.properties.default_track -eq $true }) {
return ($mkv.tracks | where-Object { $_.properties.codec_id.StartsWith('A_') } | where-object { $_.properties.default_track -eq $true })[0].id
} else {
return ($mkv.tracks | where-Object { $_.properties.codec_id.StartsWith('A_') } | where-object { $_.properties.default_track -eq $false })[0].id
}
}
$params = [ordered]@{
File = $file
ffmpegEXE = $ffmpegEXE
mkvmergeEXE = $mkvmergeEXE
TotalTracks = $mkv.tracks.count
VideoTrackInfo = $VideoTrackInfo
AudioTrack = $AudioTrack
SubtitleTrack = $SubtitleTrack
DefaultAudio = Get-DefaultID $mkv
DefaultLang = $DefaultLang
OGfile = Get-Childitem -LiteralPath $file -ErrorAction Stop
FinalFile = "$($file.DirectoryName)$slash$($file.BaseName).NORMALIZED$($file.Extension)"
codec = $codec
audioext = $audioext
bitrate = $bitrate
freq = $freq
duration = $($mkv.container.properties.duration / 1000000000)
mkvSTDOUT_FILE = Join-Path -Path ([IO.Path]::GetTempPath()) -ChildPath ([System.IO.Path]::GetRandomFileName().Split('.')[0] + ".txt")
mkvSTDERROUT_FILE = Join-Path -Path ([IO.Path]::GetTempPath()) -ChildPath ([System.IO.Path]::GetRandomFileName().Split('.')[0] + ".txt")
AudioExtJson = Join-Path -Path ([IO.Path]::GetTempPath()) -ChildPath ([System.IO.Path]::GetRandomFileName().Split('.')[0] + ".json")
STDOUT_FILE = Join-Path -Path ([IO.Path]::GetTempPath()) -ChildPath ([System.IO.Path]::GetRandomFileName().Split('.')[0] + ".txt")
STDERR_FILE = Join-Path -Path ([IO.Path]::GetTempPath()) -ChildPath ([System.IO.Path]::GetRandomFileName().Split('.')[0] + ".txt")
AudioMid = Join-Path ([IO.Path]::GetTempPath()) ($file.BaseName + '.AUDIO.mkv')
AudioRaw = Join-Path ([IO.Path]::GetTempPath()) ($file.BaseName + ".$audioext")
}
return $params
}
function Get-DefaultAudio {
Param(
[parameter(Mandatory = $true)]
$params
)
$mkvmergeEXE = Get-Item (get-command "mkvmerge").source
write-progress -id 1 -activity "Normalizing audio" -status "Stage 2/5" -PercentComplete 7
write-progress -parentId 1 -Activity "Mkvmerge"
$json = "--output" , "$($params.AudioMid)"
$json = $json += "--audio-tracks"
$json = $json += "$($params.DefaultAudio)"
$json = $json += "--no-video", "--no-subtitles", "--no-chapters", "--language"
$json = $json += "$($params.DefaultAudio)" + ":" + "$($params.DefaultLang)"
$json = $json += "(", $($params.File.FullName) , ")"
$json | ConvertTo-Json -depth 100 | Out-File -LiteralPath $($params.AudioExtJson)
$nid = (Get-Process mkvmerge -ErrorAction SilentlyContinue).id
if ($nid) {
Write-Output "Waiting for MKVMERGE to finish"
Wait-Process -Id $nid
Start-Sleep 5
#Clear-Host
}
$mkvmergePROS = Start-Process -FilePath $mkvmergeEXE -ArgumentList ('"' + "@$($params.AudioExtJson)" + '"') -RedirectStandardError $($params.mkvSTDERROUT_FILE) -RedirectStandardOutput $($params.mkvSTDOUT_FILE) -PassThru -NoNewWindow
Start-Sleep -m 1
Do {
Start-Sleep -m 1
$MKVProgress = (Get-content $($params.mkvSTDOUT_FILE) | Select-Object -Last 1) | Where-Object { $_ -like "Progress*" }
If ($MKVProgress) {
$MKVPercent = $MKVProgress -replace '\D+'
write-progress -parentId 1 -Activity "MKVmerge" -PercentComplete $MKVPercent -Status ("Extracting audio file {0:n2}% completed..." -f $MKVPercent)
}
}Until ($mkvmergePROS.HasExited)
write-progress -parentId 1 -Activity "MKVmerge" -PercentComplete 100 -Status ("Extracting audio file {0:n2}% completed..." -f 100)
Remove-File $($params.mkvSTDOUT_FILE)
Remove-File $($params.mkvSTDERROUT_FILE)
Remove-File $($params.AudioExtJson)
}
function Start-Normalize {
Param(
[parameter(Mandatory = $true)]
$params
)
$ffmpegEXE = Get-Item (get-command "ffmpeg").source
write-progress -id 1 -activity "Normalizing audio" -status "Stage 3/5" -PercentComplete 8
write-progress -parentId 1 -Activity "2 pass loudnorm" -Status "Pass 1 of 2"
$ArgumentList = "-progress - -nostats -nostdin -y -i `"$($params.AudioMid)`" -af loudnorm=i=-23.0:lra=7.0:tp=-2.0:offset=0.0:print_format=json -hide_banner -f null -"
$totalTime = $($params.duration)
$ffmpeg = Start-Process -FilePath $ffmpegEXE -ArgumentList $ArgumentList -RedirectStandardError $($params.STDERR_FILE) -RedirectStandardOutput $($params.STDOUT_FILE) -PassThru -NoNewWindow
Start-Sleep 1
Do {
Start-Sleep 1
$ffmpegProgress = [regex]::split((Get-content $($params.STDOUT_FILE) | Select-Object -Last 9), '(,|\s+)') | Where-Object { $_ -like "out_time=*" }
If ($ffmpegProgress) {
$gettimevalue = [TimeSpan]::Parse(($ffmpegProgress.Split("=")[1]))
$starttime = $gettimevalue.ToString("hh\:mm\:ss\,fff")
$a = [datetime]::ParseExact($starttime, "HH:mm:ss,fff", $null)
$ffmpegTimelapse = (New-TimeSpan -Start (Get-Date).Date -End $a).TotalSeconds
$ffmpegPercent = $ffmpegTimelapse / $totalTime * 100
write-progress -parentId 1 -Activity "2 pass loudnorm" -PercentComplete $ffmpegPercent -Status ("Pass 1 of 2 is {0:n2}% completed..." -f $ffmpegPercent)
}
}Until ($ffmpeg.HasExited)
$input_i = (((Get-Content -LiteralPath $($params.STDERR_FILE) | Where-Object { $_ -Like '*input_i*' }).Split(" "))[2]).Replace('"', "").Replace(',', "")
$input_tp = (((Get-Content -LiteralPath $($params.STDERR_FILE) | Where-Object { $_ -Like '*input_tp*' }).Split(" "))[2]).Replace('"', "").Replace(',', "")
$input_lra = (((Get-Content -LiteralPath $($params.STDERR_FILE) | Where-Object { $_ -Like '*input_lra*' }).Split(" "))[2]).Replace('"', "").Replace(',', "")
$input_thresh = (((Get-Content -LiteralPath $($params.STDERR_FILE) | Where-Object { $_ -Like '*input_thresh*' }).Split(" "))[2]).Replace('"', "").Replace(',', "")
$target_offset = (((Get-Content -LiteralPath $($params.STDERR_FILE) | Where-Object { $_ -Like '*target_offset*' }).Split(" "))[2]).Replace('"', "").Replace(',', "")
Remove-File $($params.STDOUT_FILE)
Remove-File $($params.STDERR_FILE)
$ArgumentList = "-progress - -nostats -nostdin -y -i `"$($params.AudioMid)`" -threads 0 -hide_banner -filter_complex `"[0:0]loudnorm=I=-23:TP=-2.0:LRA=7:measured_I=""$input_i"":measured_LRA=""$input_lra"":measured_TP=""$input_tp"":measured_thresh=""$input_thresh"":offset=""$target_offset"":linear=true:print_format=json[norm0]`" -map_metadata 0 -map_metadata:s:a:0 0:s:a:0 -map_chapters 0 -c:v copy -map [norm0] -c:a $($params.codec) -b:a $($params.bitrate) -ar $($params.freq) -c:s copy -ac 2 `"$($params.AudioRaw)`""
write-progress -id 1 -activity "Normalizing audio" -status "Stage 4/5" -PercentComplete 52
$ffmpeg = Start-Process -FilePath $ffmpegEXE -ArgumentList $ArgumentList -RedirectStandardError $($params.STDERR_FILE) -RedirectStandardOutput $($params.STDOUT_FILE) -PassThru -NoNewWindow
Start-Sleep 1
Do {
Start-Sleep 1
$ffmpegProgress = [regex]::split((Get-content $($params.STDOUT_FILE) | Select-Object -Last 9), '(,|\s+)') | Where-Object { $_ -like "out_time=*" }
If ($ffmpegProgress) {
$gettimevalue = [TimeSpan]::Parse(($ffmpegProgress.Split("=")[1]))
$starttime = $gettimevalue.ToString("hh\:mm\:ss\,fff")
$a = [datetime]::ParseExact($starttime, "HH:mm:ss,fff", $null)
$ffmpegTimelapse = (New-TimeSpan -Start (Get-Date).Date -End $a).TotalSeconds
$ffmpegPercent = $ffmpegTimelapse / $totalTime * 100
write-progress -parentId 1 -Activity "2 pass loudnorm" -PercentComplete $ffmpegPercent -Status ("Pass 2 of 2 is {0:n2}% completed..." -f $ffmpegPercent)
}
}Until ($ffmpeg.HasExited)
Remove-File $($params.STDERR_FILE)
Remove-File $($params.STDOUT_FILE)
Remove-File $($params.AudioMid)
}
function Start-Remux {
Param(
[parameter(Mandatory = $true)]
$params
)
$mkvmergeEXE = Get-Item (get-command "mkvmerge").source
write-progress -id 1 -activity "Normalizing audio" -status "Stage 5/5" -PercentComplete 96
write-progress -parentId 1 -Activity "Mkvmerge"
$track_order = ''
$json = ''
####Outputfile
$json = "--ui-language", "en", "--priority", "lower", "--output" , ($params.FinalFile)
##ORIGINAL FILE
####Video info
$json = $json += "--language", "$($params.VideoTrackInfo[0].ID):und", "--display-dimensions", "$($params.VideoTrackInfo[0].ID):$($params.VideoTrackInfo[0].display_dimensions)"
if ($($params.VideoTrackInfo[0].color_matrix_coefficients)) {
$json = $json += "--color-matrix-coefficients", "$($params.VideoTrackInfo[0].ID):$($params.VideoTrackInfo[0].color_matrix_coefficients)"
}
if ($($params.VideoTrackInfo[0].color_transfer_characteristics)) {
$json = $json += "--color-transfer-characteristics", "$($params.VideoTrackInfo[0].ID):$($params.VideoTrackInfo[0].color_transfer_characteristics)"
}
if ($($params.VideoTrackInfo[0].color_primaries)) {
$json = $json += "--color-primaries", "$($params.VideoTrackInfo[0].ID):$($params.VideoTrackInfo[0].color_primaries)"
}
$track_order = $track_order + "0:$($params.VideoTrackInfo[0].ID)"
$track_order = $track_order + ",1:0"
####Audio Info
foreach ($Item in $($params.AudioTrack)) {
$json = $json += "--language" , "$($Item.ID):en"
if ($null -ne $Item.track_name) {
$json = $json += "--track-name", "$($Item.ID):$($Item.track_name)"
}
if ($Item.Delay -ne "0") {
$json = $json += "--sync", "$($Item.ID):$($Item.Delay)"
}
$track_order = $track_order + ",0:$($Item.ID)"
}
####Subtitle Info
foreach ($Item in $($params.SubtitleTrack)) {
$json = $json += "--language" , "$($Item.ID):en"
if ($null -ne $Item.track_name) {
$json = $json += "--track-name", "$($Item.ID):$($Item.track_name)"
}
if ($null -ne $Item.encoding) {
$json = $json += "--sub-charset", "$($Item.ID):$($Item.encoding)"
}
$track_order = $track_order + ",0:$($Item.ID)"
}
$json = $json += "(" , $params.File.FullName , ")" # Source file
##Audio FILE
$json = $json += "--language", "0:en", "--track-name", "0:NORMALIZED"
if ((($params.AudioTrack | where-object { $_.ID -eq $params.DefaultAudio }).delay) -ne "0") {
$json = $json += "--sync", "0:$(($params.AudioTrack | where-object {$_.ID -eq $params.DefaultAudio}).delay)"
}
$json = $json += "(", $params.AudioRaw, ")"
##Track order
$json = $json += "--track-order", $track_order
$json | ConvertTo-Json -depth 100 | Out-File -LiteralPath $($params.AudioExtJson)
$nid = (Get-Process mkvmerge -ErrorAction SilentlyContinue).id
if ($nid) {
Write-Output "Waiting for MKVMERGE to finish"
Wait-Process -Id $nid
Start-Sleep 3
#Clear-Host
}
$mkvmergePROS = Start-Process -FilePath $mkvmergeEXE -ArgumentList ('"' + "@$($params.AudioExtJson)" + '"') -RedirectStandardError $($params.mkvSTDERROUT_FILE) -RedirectStandardOutput $($params.mkvSTDOUT_FILE) -PassThru -NoNewWindow
Start-Sleep -m 1
Do {
Start-Sleep -m 1
$MKVProgress = (Get-content $($params.mkvSTDOUT_FILE) | Select-Object -Last 1) | Where-Object { $_ -like "Progress*" }
If ($MKVProgress) {
$MKVPercent = $MKVProgress -replace '\D+'
write-progress -parentId 1 -Activity "MKVmerge" -PercentComplete $MKVPercent -Status ("Muxing video file {0:n2}% completed..." -f $MKVPercent)
}
}Until ($mkvmergePROS.HasExited)
write-progress -parentId 1 -Activity "MKVmerge" -PercentComplete 100 -Status ("Muxing video file {0:n2}% completed..." -f 100)
Remove-File $($params.mkvSTDERROUT_FILE)
Remove-File $($params.mkvSTDOUT_FILE)
Remove-File $($params.AudioRaw)
Remove-File $($params.AudioExtJson)
}
}
PROCESS {
#check if file exists & gets OS slash type
$slash = Confirm-Input $file
#Strip all Languages but choosen, and convert avi & mp4 to MKV
$file = Start-MKVFilter $file $DefaultLang $2ndLang $slash $keepall
#get need info for work
$params = Get-Params $file $slash
#extract eng default audio track, 1st eng track if none flagged default
Get-DefaultAudio $params
#normalizes extracted audio track to given specs
Start-Normalize $params
#inserts new audio fin into video file setting normalized track as default
Start-Remux $params
if ($delete -or $InPlace) {
if (Test-Path $params.FinalFile) {
Remove-File $params.OGfile
if ($InPlace) {
Move-Item -Path $params.FinalFile -Destination $params.OGfile
}
}
}
}
END {
Start-Sleep -Seconds 5
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment