Add interactive audio extraction, remuxing and encoding tool
This commit is contained in:
1 parent
9c637a67aa
commit
5842d52784
5 files changed
+894
No files matched your search
@@ -0,0 +1,302 @@
|
||||
"""Audio extraction, remuxing, and encoding helpers."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import subprocess
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
from tools.console import ProgressView, prompt_input
|
||||
from tools.filesystem import collect_files
|
||||
from tools.user_config import load_setting, save_setting
|
||||
|
||||
|
||||
COMMON_AUDIO_CODECS = ("aac", "opus", "flac", "mp3")
|
||||
M4A_CODECS = {"aac", "alac", "opus", "flac", "mp3"}
|
||||
NATIVE_EXTENSIONS = {
|
||||
"aac": ".m4a",
|
||||
"alac": ".m4a",
|
||||
"opus": ".opus",
|
||||
"flac": ".flac",
|
||||
"mp3": ".mp3",
|
||||
"vorbis": ".ogg",
|
||||
"pcm_s16le": ".wav",
|
||||
"pcm_s24le": ".wav",
|
||||
"pcm_s32le": ".wav",
|
||||
}
|
||||
POOR_M4A_COMPATIBILITY = M4A_CODECS - {"aac", "alac"}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AudioStream:
|
||||
index: int
|
||||
codec: str
|
||||
channels: int | None
|
||||
sample_rate: int | None
|
||||
bit_rate: int | None
|
||||
|
||||
@property
|
||||
def layout(self) -> tuple[str, int | None, int | None]:
|
||||
return self.codec, self.channels, self.sample_rate
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AudioInput:
|
||||
path: Path
|
||||
container: str
|
||||
streams: list[AudioStream]
|
||||
has_video: bool
|
||||
|
||||
@property
|
||||
def audio_only(self) -> bool:
|
||||
return not self.has_video
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AudioSettings:
|
||||
mode: str
|
||||
codec: str | None
|
||||
container: str
|
||||
matching_action: str
|
||||
encoder: str | None = None
|
||||
bitrate: str | None = None
|
||||
quality: int | None = None
|
||||
compression: int | None = None
|
||||
output_dir: Path | None = None
|
||||
encoder_ffmpeg: str | None = None
|
||||
|
||||
|
||||
def collect_audio_inputs(ffprobe: str, args: list[str]) -> tuple[list[AudioInput], list[Path]]:
|
||||
media, unreadable = [], []
|
||||
files = collect_files(args, print_missing=True)
|
||||
progress = ProgressView(len(files), "Probing files")
|
||||
for index, path in enumerate(files, 1):
|
||||
try:
|
||||
media.append(probe_audio_input(ffprobe, path))
|
||||
except (OSError, subprocess.CalledProcessError, json.JSONDecodeError):
|
||||
unreadable.append(path)
|
||||
progress.update(index)
|
||||
progress.finish(keep=True)
|
||||
return media, unreadable
|
||||
|
||||
|
||||
def probe_audio_input(ffprobe: str, path: Path) -> AudioInput:
|
||||
command = [
|
||||
ffprobe,
|
||||
"-v",
|
||||
"error",
|
||||
"-show_entries",
|
||||
"format=format_name:stream=index,codec_type,codec_name,channels,sample_rate,bit_rate",
|
||||
"-of",
|
||||
"json",
|
||||
str(path),
|
||||
]
|
||||
completed = subprocess.run(command, check=True, capture_output=True, text=True)
|
||||
data = json.loads(completed.stdout)
|
||||
streams = [
|
||||
AudioStream(
|
||||
int(stream["index"]),
|
||||
str(stream.get("codec_name") or "unknown"),
|
||||
_as_int(stream.get("channels")),
|
||||
_as_int(stream.get("sample_rate")),
|
||||
_as_int(stream.get("bit_rate")),
|
||||
)
|
||||
for stream in data.get("streams", [])
|
||||
if stream.get("codec_type") == "audio"
|
||||
]
|
||||
return AudioInput(
|
||||
path.resolve(),
|
||||
str(data.get("format", {}).get("format_name") or "unknown"),
|
||||
streams,
|
||||
any(stream.get("codec_type") == "video" for stream in data.get("streams", [])),
|
||||
)
|
||||
|
||||
|
||||
def ffmpeg_encoders(ffmpeg: str) -> set[str]:
|
||||
completed = subprocess.run(
|
||||
[ffmpeg, "-hide_banner", "-encoders"], check=True, capture_output=True, text=True
|
||||
)
|
||||
return {
|
||||
line.split()[1]
|
||||
for line in completed.stdout.splitlines()
|
||||
if len(line.split()) >= 2 and line.lstrip().startswith("A")
|
||||
}
|
||||
|
||||
|
||||
def universal_containers(codecs: set[str]) -> list[str]:
|
||||
containers = ["MKA"]
|
||||
if codecs and codecs <= M4A_CODECS:
|
||||
containers.append("M4A")
|
||||
return containers
|
||||
|
||||
|
||||
def native_extension(codec: str) -> str:
|
||||
return NATIVE_EXTENSIONS.get(codec, ".mka")
|
||||
|
||||
|
||||
def same_container(source: AudioInput, extension: str) -> bool:
|
||||
if not source.audio_only:
|
||||
return False
|
||||
names = {part.strip().lower() for part in source.container.split(",")}
|
||||
wanted = extension.lower().lstrip(".")
|
||||
return (
|
||||
wanted in names
|
||||
or wanted == "mka" and bool(names & {"matroska", "mka"})
|
||||
or wanted == "m4a" and bool(names & {"mov", "mp4", "m4a", "3gp", "3g2", "mj2"})
|
||||
)
|
||||
|
||||
|
||||
def output_extension(container: str, codec: str) -> str:
|
||||
return native_extension(codec) if container == "Native" else f".{container.lower()}"
|
||||
|
||||
|
||||
def matching_actions(inputs: list[AudioInput], stream_indexes: dict[Path, int], extension: str, codec: str) -> list[str]:
|
||||
matching = [
|
||||
item
|
||||
for item in inputs
|
||||
if item.streams and item.streams[stream_indexes[item.path]].codec == codec
|
||||
]
|
||||
actions = ["re-encode"]
|
||||
if matching:
|
||||
actions.insert(0, "remux")
|
||||
if any(same_container(item, extension) for item in matching):
|
||||
actions.insert(0, "skip")
|
||||
return actions
|
||||
|
||||
|
||||
def select_fdk_ffmpeg(system_ffmpeg: str) -> str:
|
||||
if "libfdk_aac" in ffmpeg_encoders(system_ffmpeg):
|
||||
return system_ffmpeg
|
||||
remembered = load_setting("fdk_aac_ffmpeg")
|
||||
while True:
|
||||
default = f" [{remembered}]" if remembered else ""
|
||||
answer = prompt_input(
|
||||
"FDK AAC needs an FFmpeg build with libfdk_aac. "
|
||||
f"Absolute path{default} (blank = {'use remembered path' if remembered else 'cancel'}): "
|
||||
).strip().strip('"')
|
||||
if not answer and remembered:
|
||||
answer = remembered
|
||||
if not answer:
|
||||
raise RuntimeError("FDK AAC was selected but no FDK-enabled FFmpeg was provided.")
|
||||
path = Path(answer).expanduser()
|
||||
if not path.is_absolute() or not path.is_file():
|
||||
print("Enter an existing absolute FFmpeg path.")
|
||||
continue
|
||||
try:
|
||||
resolved = str(path.resolve())
|
||||
if "libfdk_aac" not in ffmpeg_encoders(resolved):
|
||||
print("That FFmpeg build does not provide libfdk_aac.")
|
||||
continue
|
||||
except (OSError, subprocess.CalledProcessError):
|
||||
print("Could not run that FFmpeg executable.")
|
||||
continue
|
||||
save_setting("fdk_aac_ffmpeg", resolved)
|
||||
return resolved
|
||||
|
||||
|
||||
def run_audio_batch(
|
||||
ffmpeg: str,
|
||||
inputs: list[AudioInput],
|
||||
stream_indexes: dict[Path, int],
|
||||
settings: AudioSettings,
|
||||
) -> list[str]:
|
||||
failures, reserved = [], set()
|
||||
processable = [item for item in inputs if item.streams]
|
||||
progress = ProgressView(len(processable), "Processing audio")
|
||||
fdk_ffmpeg = settings.encoder_ffmpeg or ffmpeg
|
||||
for number, item in enumerate(processable, 1):
|
||||
stream = item.streams[stream_indexes[item.path]]
|
||||
try:
|
||||
action, codec = _action_for(item, stream, settings)
|
||||
if action == "skip":
|
||||
print(f"Skipped {item.path.name}: already matches the requested output.")
|
||||
else:
|
||||
extension = output_extension(settings.container, codec)
|
||||
target = unique_audio_target(item.path, extension, reserved, settings.output_dir)
|
||||
_run_ffmpeg(fdk_ffmpeg if codec == "aac" and settings.encoder == "libfdk_aac" else ffmpeg, item, stream, target, action, settings)
|
||||
print(f"{item.path.name} -> {target.name}")
|
||||
progress.update(number)
|
||||
except (OSError, subprocess.CalledProcessError, RuntimeError) as exc:
|
||||
failures.append(f"{item.path}: {exc}")
|
||||
progress.update(number, "failed")
|
||||
progress.finish(keep=True)
|
||||
return failures
|
||||
|
||||
|
||||
def unique_audio_target(
|
||||
source: Path,
|
||||
extension: str,
|
||||
reserved: set[Path],
|
||||
output_dir: Path | None = None,
|
||||
) -> Path:
|
||||
base = (output_dir or source.parent) / f"{source.stem}{extension}"
|
||||
for index in range(10000):
|
||||
target = base if index == 0 else base.with_name(f"{base.stem}-{index}{base.suffix}")
|
||||
resolved = target.resolve()
|
||||
if not target.exists() and resolved not in reserved:
|
||||
reserved.add(resolved)
|
||||
return target
|
||||
raise RuntimeError(f"Could not create a unique output name for {source.name}")
|
||||
|
||||
|
||||
def _action_for(item: AudioInput, stream: AudioStream, settings: AudioSettings) -> tuple[str, str]:
|
||||
if settings.mode == "remux":
|
||||
extension = output_extension(settings.container, stream.codec)
|
||||
return ("skip", stream.codec) if settings.matching_action == "skip" and same_container(item, extension) else ("remux", stream.codec)
|
||||
assert settings.codec is not None
|
||||
same_codec = stream.codec == settings.codec
|
||||
extension = output_extension(settings.container, settings.codec)
|
||||
if same_codec and settings.matching_action == "skip" and same_container(item, extension):
|
||||
return "skip", settings.codec
|
||||
if same_codec and settings.matching_action == "remux":
|
||||
return "remux", settings.codec
|
||||
return "encode", settings.codec
|
||||
|
||||
|
||||
def _run_ffmpeg(
|
||||
ffmpeg: str,
|
||||
item: AudioInput,
|
||||
stream: AudioStream,
|
||||
target: Path,
|
||||
action: str,
|
||||
settings: AudioSettings,
|
||||
) -> None:
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
command = [ffmpeg, "-hide_banner", "-nostdin", "-i", str(item.path), "-map", f"0:{stream.index}", "-vn", "-map_metadata", "0"]
|
||||
if action == "remux":
|
||||
command.extend(["-c:a", "copy"])
|
||||
else:
|
||||
assert settings.encoder
|
||||
command.extend(["-c:a", settings.encoder])
|
||||
if settings.bitrate:
|
||||
command.extend(["-b:a", settings.bitrate])
|
||||
if settings.quality is not None:
|
||||
command.extend(["-vbr", str(settings.quality)] if settings.encoder == "libfdk_aac" else ["-q:a", str(settings.quality)])
|
||||
if settings.compression is not None:
|
||||
command.extend(["-compression_level", str(settings.compression)])
|
||||
if settings.container == "M4A":
|
||||
command.extend(["-f", "mp4"])
|
||||
command.extend(["-n", str(target)])
|
||||
completed = subprocess.run(command, check=False, capture_output=True, text=True)
|
||||
if completed.returncode:
|
||||
detail = (completed.stderr or completed.stdout).strip()
|
||||
raise RuntimeError(detail[-2000:] or f"FFmpeg exited with {completed.returncode}")
|
||||
|
||||
|
||||
def encoder_for(codec: str, encoders: set[str]) -> str | None:
|
||||
choices = {
|
||||
"aac": "aac",
|
||||
"opus": "libopus",
|
||||
"flac": "flac",
|
||||
"mp3": "libmp3lame",
|
||||
}
|
||||
value = choices[codec]
|
||||
return value if value in encoders else None
|
||||
|
||||
|
||||
def _as_int(value: object) -> int | None:
|
||||
try:
|
||||
return int(str(value))
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
Reference in new issue
Block a user