Skip to content

Instantly share code, notes, and snippets.

@Diyagi
Last active January 7, 2025 10:45
Show Gist options
  • Save Diyagi/bdcf1f16bc0d8f449763fd56505e952f to your computer and use it in GitHub Desktop.
Save Diyagi/bdcf1f16bc0d8f449763fd56505e952f to your computer and use it in GitHub Desktop.
Merge Episodes that are in multiple parts into one
# Path to the directory containing your MKV files
$inputDirectory = "F:\MasterChichi\MasterChef3"
$outputDirectory = "F:\MasterChichi\MasterMergedCu"
$tempDirectory = "F:\MasterChichi\MasterTemp"
if (-not (Test-Path -Path $outputDirectory)) {
New-Item -ItemType Directory -Path $outputDirectory
}
if (-not (Test-Path -Path $tempDirectory)) {
New-Item -ItemType Directory -Path $tempDirectory
}
# Get all MKV files in the input directory
$files = Get-ChildItem -Path $inputDirectory -Filter "*.mkv"
# Group files by episode
$groupedFiles = $files | Group-Object {
$_.BaseName -replace " - \d+⧸\d+.*$", ""
}
# Process each episode group
foreach ($group in $groupedFiles) {
$shouldFail = $false
$episodeName = $group.Name
$episodeFiles = $group.Group | Sort-Object Name
# Trim each part
$trimmedFiles = @()
foreach ($file in $episodeFiles) {
$codec = ffprobe -v error -select_streams v:0 -show_entries stream=codec_name -of default=nw=1:nk=1 $file.FullName
$trimmedFile = Join-Path $tempDirectory $file.Name
if ($codec -eq "av1") {
ffmpeg -ss 00:00:06.100 -i $file.FullName -c copy $trimmedFile
$trimmedFiles += $trimmedFile
} else {
Write-Host "$file.FullName is not AV1 encoded, this episode will be skipped..."
$shouldFail = $true
}
}
if ($shouldFail) {
# Clean up the temporary trimmed files
Remove-Item -Path $trimmedFiles -Force
Remove-Item -Path $fileListPath -Force
continue
}
# Create a temporary text file for FFmpeg
$fileListPath = Join-Path $tempDirectory "file_list.txt"
$fileListContent = $trimmedFiles | ForEach-Object {
"file '$($_)'`n"
}
$fileListContent | Set-Content -Path $fileListPath -NoNewline -Encoding utf8NoBOM
$outputFile = Join-Path $outputDirectory "$episodeName.mkv"
Write-Host "$outputFile"
# Merge the files using FFmpeg
ffmpeg -f concat -safe 0 -i $fileListPath -c copy -map_metadata 0 $outputFile
# Clean up the temporary trimmed files
Remove-Item -Path $trimmedFiles -Force
Remove-Item -Path $fileListPath -Force
}
Write-Host "Merging complete. Check the output directory: $outputDirectory"
Remove-Item -Path $tempDirectory -Recurse -Force
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment