Bug when a simple "remux" should be done

This commit is contained in:
2025-07-19 10:49:46 +02:00
parent 7452a97e64
commit 98ea4baaad

View File

@@ -127,19 +127,7 @@ def main():
DIR_ORIGINAL.mkdir(exist_ok=True) DIR_ORIGINAL.mkdir(exist_ok=True)
DIR_LOGS.mkdir(exist_ok=True) DIR_LOGS.mkdir(exist_ok=True)
while True: for file_path in files_to_process:
# Re-check for files in case new ones were added
files_to_process = sorted(
f for f in current_dir.glob("*.mkv")
if not f.name.startswith("temp-output-")
)
if not files_to_process:
print("No more .mkv files found to process. Exiting.")
break
file_path = files_to_process[0]
# Setup logging # Setup logging
log_file_path = DIR_LOGS / f"{file_path.name}.log" log_file_path = DIR_LOGS / f"{file_path.name}.log"
log_file = open(log_file_path, 'w', encoding='utf-8') log_file = open(log_file_path, 'w', encoding='utf-8')
@@ -171,7 +159,7 @@ def main():
# 4. --- Prepare for Final mkvmerge Command --- # 4. --- Prepare for Final mkvmerge Command ---
processed_audio_files = [] processed_audio_files = []
audio_tracks_to_remux = [] tids_of_reencoded_tracks = []
# 5. --- Process Each Audio Stream --- # 5. --- Process Each Audio Stream ---
audio_streams = [s for s in ffprobe_info.get("streams", []) if s.get("codec_type") == "audio"] audio_streams = [s for s in ffprobe_info.get("streams", []) if s.get("codec_type") == "audio"]
@@ -182,18 +170,27 @@ def main():
continue continue
mkv_tracks_list = mkv_info.get("tracks", []) mkv_tracks_list = mkv_info.get("tracks", [])
mkv_audio_tracks = [t for t in mkv_tracks_list if t.get("type") == "audio"]
media_tracks_data = media_info.get("media", {}).get("track", []) media_tracks_data = media_info.get("media", {}).get("track", [])
mediainfo_audio_tracks = {int(t.get("StreamOrder", -1)): t for t in media_tracks_data if t.get("@type") == "Audio"} mediainfo_audio_tracks = {int(t.get("StreamOrder", -1)): t for t in media_tracks_data if t.get("@type") == "Audio"}
print("\n=== Audio Track Analysis ===") print("\n=== Audio Track Analysis ===")
for stream in audio_streams: for audio_stream_idx, stream in enumerate(audio_streams):
stream_index = stream["index"] stream_index = stream["index"]
codec = stream.get("codec_name") codec = stream.get("codec_name")
channels = stream.get("channels", 2) channels = stream.get("channels", 2)
language = stream.get("tags", {}).get("language", "und") language = stream.get("tags", {}).get("language", "und")
mkv_track = next((t for t in mkv_tracks_list if t.get("properties", {}).get("stream_id") == stream_index), {}) track_id = -1
mkv_track = {}
if audio_stream_idx < len(mkv_audio_tracks):
mkv_track = mkv_audio_tracks[audio_stream_idx]
track_id = mkv_track.get("id", -1) track_id = mkv_track.get("id", -1)
if track_id == -1:
print(f" -> Warning: Could not map ffprobe audio stream index {stream_index} to an mkvmerge track ID. Skipping this track.")
continue
track_title = mkv_track.get("properties", {}).get("track_name", "") track_title = mkv_track.get("properties", {}).get("track_name", "")
track_delay = 0 track_delay = 0
@@ -239,7 +236,7 @@ def main():
if codec in {"aac", "opus"}: if codec in {"aac", "opus"}:
print(f" -> Action: Remuxing track (keeping original {codec.upper()} {bitrate})") print(f" -> Action: Remuxing track (keeping original {codec.upper()} {bitrate})")
audio_tracks_to_remux.append(str(track_id)) # This track will be kept from the original file, so we don't need to add it to a special list.
else: else:
bitrate_info = f"{codec.upper()} {bitrate}" bitrate_info = f"{codec.upper()} {bitrate}"
print(f" -> Action: Re-encoding codec '{codec}' to Opus") print(f" -> Action: Re-encoding codec '{codec}' to Opus")
@@ -252,20 +249,23 @@ def main():
"Title": track_title, "Title": track_title,
"Delay": track_delay "Delay": track_delay
}) })
tids_of_reencoded_tracks.append(str(track_id))
# 6. --- Construct and Execute Final mkvmerge Command --- # 6. --- Construct and Execute Final mkvmerge Command ---
print("\n=== Final MKV Creation ===") print("\n=== Final MKV Creation ===")
print("Assembling final mkvmerge command...") print("Assembling final mkvmerge command...")
mkvmerge_args = ["mkvmerge", "-o", str(intermediate_output_file)] mkvmerge_args = ["mkvmerge", "-o", str(intermediate_output_file)]
# Part 1: Copy non-audio tracks (video, subs, etc.) from the source file. # If no audio was re-encoded, we are just doing a full remux of the original file.
mkvmerge_args.extend(["--no-audio", str(file_path)]) if not processed_audio_files:
print(" -> All audio tracks are in the desired format. Performing a full remux.")
mkvmerge_args.append(str(file_path))
else:
# If we re-encoded audio, copy everything from the source EXCEPT the original audio tracks that we replaced.
mkvmerge_args.extend(["--audio-tracks", "!" + ",".join(tids_of_reencoded_tracks)])
mkvmerge_args.append(str(file_path))
# Part 2: Copy audio tracks that should be remuxed from the same source file. # Add the newly encoded Opus audio files.
if audio_tracks_to_remux:
mkvmerge_args.extend(["--audio-tracks", ",".join(audio_tracks_to_remux), str(file_path)])
# Part 3: Add the newly encoded Opus audio files.
for file_info in processed_audio_files: for file_info in processed_audio_files:
mkvmerge_args.extend(["--language", f"0:{file_info['Language']}"]) mkvmerge_args.extend(["--language", f"0:{file_info['Language']}"])
if file_info['Title']: if file_info['Title']: