Add interactive audio extraction, remuxing and encoding tool

This commit is contained in:
ajp_anton committed 2026-10-06 19:27:46 +00:00
1 parent 9c637a67aa
commit 5842d52784
5 files changed
+894

No files matched your search

+302
View File
@@ -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
+401
View File
@@ -0,0 +1,401 @@
"""Keyboard-driven settings for the audio tool."""
from __future__ import annotations
from dataclasses import dataclass, field
from pathlib import Path
from tools.audio_batch import (
COMMON_AUDIO_CODECS,
POOR_M4A_COMPATIBILITY,
AudioInput,
AudioSettings,
encoder_for,
ffmpeg_encoders,
matching_actions,
native_extension,
output_extension,
same_container,
select_fdk_ffmpeg,
universal_containers,
)
from tools.console import dark_field, draw_screen, inverse, light_red, raw_key_input
from tools.filesystem import complete_path
AAC_ESTIMATES = {1: "~64k", 2: "~80k", 3: "~104k", 4: "~128k", 5: "~176k"}
MP3_ESTIMATES = {
0: "~245k", 1: "~225k", 2: "~190k", 3: "~175k", 4: "~165k",
5: "~130k", 6: "~115k", 7: "~100k", 8: "~85k", 9: "~65k",
}
@dataclass
class AudioDialogState:
mode: str = "encode"
codec: str = "opus"
container: str = "Native"
matching_action: str = "re-encode"
aac_encoder: str = "aac"
fdk_mode: str = "VBR"
mp3_mode: str = "VBR"
bitrates: dict[str, str] = field(
default_factory=lambda: {"aac": "192k", "opus": "128k", "mp3": "192k"}
)
aac_quality: str = "5"
mp3_quality: str = "0"
compression: str = "12"
output_dir: str = ""
confirm: str = "Confirm"
@dataclass(frozen=True)
class Row:
key: str
label: str
options: tuple[str, ...] = ()
editable: bool = False
def select_stream_indexes(inputs: list[AudioInput]) -> dict[Path, int]:
multiple = [item for item in inputs if len(item.streams) > 1]
indexes = {item.path: 0 for item in inputs if item.streams}
if not multiple:
return indexes
layouts = {tuple(stream.layout for stream in item.streams) for item in multiple}
if len(layouts) != 1:
print("Warning: multi-stream inputs have different layouts; using their first audio stream.")
return indexes
streams, selected = multiple[0].streams, 0
with raw_key_input() as read_key:
while True:
options = []
for number, stream in enumerate(streams, 1):
details = ", ".join(
value for value in (
stream.codec,
f"{stream.channels} channels" if stream.channels else "",
f"{stream.sample_rate} Hz" if stream.sample_rate else "",
) if value
)
options.append(f"{number}: {details}")
rendered = " ".join(
inverse(option) if index == selected else option
for index, option in enumerate(options)
)
draw_screen([
"Select the audio stream used by multi-stream inputs",
"Left/Right: navigate Enter: confirm",
"",
rendered,
])
key = read_key()
if key == "left":
selected = max(0, selected - 1)
elif key == "right":
selected = min(len(streams) - 1, selected + 1)
elif key == "enter":
indexes.update({item.path: selected for item in multiple})
return indexes
elif key == "esc":
return indexes
def choose_settings(
ffmpeg: str,
inputs: list[AudioInput],
stream_indexes: dict[Path, int],
working_dir: Path,
) -> AudioSettings | None:
encoders = ffmpeg_encoders(ffmpeg)
codecs = [codec for codec in COMMON_AUDIO_CODECS if codec == "aac" or encoder_for(codec, encoders)]
if not codecs:
raise RuntimeError("FFmpeg has none of the supported audio encoders.")
state = AudioDialogState(codec="opus" if "opus" in codecs else codecs[0])
selected = 0
typing_key = typed = error = ""
with raw_key_input() as read_key:
while True:
rows = _rows(state, inputs, stream_indexes, codecs)
_normalize(state, rows)
rows = _rows(state, inputs, stream_indexes, codecs)
_normalize(state, rows)
selected = min(selected, len(rows) - 1)
draw_screen(
_screen(
state, rows, selected, typing_key, typed, error,
working_dir, inputs, stream_indexes,
)
)
key = read_key()
if typing_key:
if key == "esc":
typing_key = typed = error = ""
elif key == "backspace":
typed = typed[:-1]
elif key == "tab" and typing_key == "output_dir":
typed = complete_path(typed, working_dir)
elif key == "enter":
try:
value = _validate_typed(typing_key, typed, working_dir)
except ValueError as exc:
error = str(exc)
else:
_set_value(state, typing_key, value)
typing_key = typed = error = ""
elif key == "space":
typed += " "
elif len(key) == 1 and key >= " ":
typed += key
continue
row = rows[selected]
if key == "up":
selected = max(0, selected - 1)
elif key == "down":
selected = min(len(rows) - 1, selected + 1)
elif key in {"left", "right"} and row.options:
_move_option(state, row, -1 if key == "left" else 1)
elif key == "enter" and row.editable:
typing_key, typed, error = row.key, _raw_value(state, row.key), ""
elif key == "enter" and row.key == "confirm":
if state.confirm == "Exit":
return None
break
elif key == "enter":
selected = min(len(rows) - 1, selected + 1)
elif key == "esc":
return None
elif row.editable and len(key) == 1 and key >= " ":
typing_key, typed, error = row.key, key, ""
output_dir = resolve_output_dir(state.output_dir, working_dir)
encoder = None if state.mode == "remux" else (
state.aac_encoder if state.codec == "aac" else encoder_for(state.codec, encoders)
)
if encoder == "aac" and encoder not in encoders:
raise RuntimeError("The FFmpeg on PATH does not provide its native AAC encoder.")
encoder_ffmpeg = select_fdk_ffmpeg(ffmpeg) if encoder == "libfdk_aac" else None
bitrate, quality, compression = _encoding_value(state)
return AudioSettings(
state.mode,
None if state.mode == "remux" else state.codec,
state.container,
state.matching_action,
encoder,
bitrate,
quality,
compression,
output_dir,
encoder_ffmpeg,
)
def parse_bitrate(value: str) -> str:
text = value.strip().lower()
if text.endswith("k"):
text = text[:-1]
if not text.isdigit() or int(text) <= 0:
raise ValueError("Bitrate must be a positive number, such as 192 or 192k.")
return f"{int(text)}k"
def resolve_output_dir(value: str, working_dir: Path) -> Path | None:
text = value.strip().strip('"')
if not text:
return None
path = Path(text).expanduser()
path = path if path.is_absolute() else working_dir / path
path = path.resolve()
if path.exists() and not path.is_dir():
raise ValueError("The output path exists but is not a directory.")
return path
def _rows(
state: AudioDialogState,
inputs: list[AudioInput],
stream_indexes: dict[Path, int],
codecs: list[str],
) -> list[Row]:
rows = [Row("mode", "Audio handling", ("encode", "remux"))]
if state.mode == "encode":
rows.append(Row("codec", "Output codec", tuple(codecs)))
if state.codec == "aac":
rows.append(Row("aac_encoder", "AAC encoder", ("aac", "libfdk_aac")))
if state.aac_encoder == "libfdk_aac":
rows.append(Row("fdk_mode", "AAC mode", ("VBR", "CBR")))
elif state.codec == "mp3":
rows.append(Row("mp3_mode", "MP3 mode", ("VBR", "CBR")))
rows.append(Row(_value_key(state), _value_label(state), editable=True))
container_codecs = _source_codecs(inputs, stream_indexes) if state.mode == "remux" else {state.codec}
rows.append(Row("container", "Output container", tuple(["Native", *universal_containers(container_codecs)])))
rows.append(Row("matching_action", "Matching inputs", tuple(_matching_options(state, inputs, stream_indexes))))
rows.append(Row("output_dir", "Output directory", editable=True))
rows.append(Row("confirm", "", ("Confirm", "Exit")))
return rows
def _normalize(state: AudioDialogState, rows: list[Row]) -> None:
for row in rows:
if row.options and _raw_value(state, row.key) not in row.options:
_set_value(state, row.key, row.options[0])
def _matching_options(
state: AudioDialogState,
inputs: list[AudioInput],
stream_indexes: dict[Path, int],
) -> list[str]:
if state.mode == "encode":
return matching_actions(
inputs,
stream_indexes,
output_extension(state.container, state.codec),
state.codec,
)
extension = None if state.container == "Native" else f".{state.container.lower()}"
can_skip = any(
same_container(item, extension or native_extension(item.streams[stream_indexes[item.path]].codec))
for item in inputs
)
return ["skip", "remux"] if can_skip else ["remux"]
def _source_codecs(inputs: list[AudioInput], indexes: dict[Path, int]) -> set[str]:
return {item.streams[indexes[item.path]].codec for item in inputs}
def _value_key(state: AudioDialogState) -> str:
if state.codec == "flac":
return "compression"
if state.codec == "aac" and state.aac_encoder == "libfdk_aac" and state.fdk_mode == "VBR":
return "aac_quality"
if state.codec == "mp3" and state.mp3_mode == "VBR":
return "mp3_quality"
return "bitrate"
def _value_label(state: AudioDialogState) -> str:
return {
"compression": "FLAC compression",
"aac_quality": "AAC quality",
"mp3_quality": "MP3 quality",
"bitrate": "Audio bitrate",
}[_value_key(state)]
def _raw_value(state: AudioDialogState, key: str) -> str:
if key == "bitrate":
return state.bitrates[state.codec]
return str(getattr(state, key))
def _set_value(state: AudioDialogState, key: str, value: str) -> None:
if key == "bitrate":
state.bitrates[state.codec] = value
else:
setattr(state, key, value)
def _move_option(state: AudioDialogState, row: Row, movement: int) -> None:
current = row.options.index(_raw_value(state, row.key))
_set_value(state, row.key, row.options[max(0, min(len(row.options) - 1, current + movement))])
def _validate_typed(key: str, value: str, working_dir: Path) -> str:
if key == "bitrate":
return parse_bitrate(value)
if key == "aac_quality":
return _bounded_integer(value, 1, 5, "AAC quality")
if key == "mp3_quality":
return _bounded_integer(value, 0, 9, "MP3 quality")
if key == "compression":
return _bounded_integer(value, 0, 12, "FLAC compression")
if key == "output_dir":
resolve_output_dir(value, working_dir)
return value.strip().strip('"')
return value
def _bounded_integer(value: str, minimum: int, maximum: int, label: str) -> str:
text = value.strip()
if not text.isdigit() or not minimum <= int(text) <= maximum:
raise ValueError(f"{label} must be from {minimum} through {maximum}.")
return str(int(text))
def _encoding_value(state: AudioDialogState) -> tuple[str | None, int | None, int | None]:
if state.mode == "remux":
return None, None, None
key = _value_key(state)
if key == "bitrate":
return state.bitrates[state.codec], None, None
if key == "compression":
return None, None, int(state.compression)
return None, int(state.aac_quality if key == "aac_quality" else state.mp3_quality), None
def _screen(
state: AudioDialogState,
rows: list[Row],
selected: int,
typing_key: str,
typed: str,
error: str,
working_dir: Path,
inputs: list[AudioInput],
stream_indexes: dict[Path, int],
) -> list[str]:
lines = [
"Audio settings",
f"Working directory: {working_dir}",
"",
"Up/Down: navigate Left/Right: choose Enter: edit/confirm Esc: cancel",
"",
]
for index, row in enumerate(rows):
value = typed if typing_key == row.key else _display_value(state, row.key)
if typing_key == row.key:
value = dark_field(value + " ")
elif index == selected:
value = inverse(value)
lines.append(f"{row.label + ':' if row.label else '':<22}{value}")
warnings = _warnings(state, working_dir, inputs, stream_indexes)
if warnings:
lines.extend(("", *(light_red(warning) for warning in warnings)))
if error:
lines.extend(("", light_red(error)))
return lines
def _display_value(state: AudioDialogState, key: str) -> str:
value = _raw_value(state, key)
if key == "output_dir" and not value:
return "source directories"
if key == "aac_quality":
return f"{value} ({AAC_ESTIMATES[int(value)]} stereo)"
if key == "mp3_quality":
return f"{value} ({MP3_ESTIMATES[int(value)]} stereo)"
return value
def _warnings(
state: AudioDialogState,
working_dir: Path,
inputs: list[AudioInput],
stream_indexes: dict[Path, int],
) -> list[str]:
warnings = []
if state.container == "M4A":
codecs = {state.codec} if state.mode == "encode" else _source_codecs(inputs, stream_indexes)
if codecs & POOR_M4A_COMPATIBILITY:
warnings.append("M4A with this codec has limited player compatibility.")
if state.output_dir and not Path(state.output_dir).is_absolute():
warnings.append(f"Relative output directory: {(working_dir / state.output_dir).resolve()}")
return warnings
+39
View File
@@ -0,0 +1,39 @@
"""Small per-user settings store for optional external tool paths."""
from __future__ import annotations
import json
import os
from pathlib import Path
def config_path() -> Path:
if os.name == "nt":
root = Path(os.environ.get("APPDATA", Path.home() / "AppData" / "Roaming"))
else:
root = Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config"))
return root / "media-batch-tools" / "settings.json"
def load_setting(name: str) -> str | None:
path = config_path()
if not path.is_file():
return None
try:
value = json.loads(path.read_text(encoding="utf-8")).get(name)
except (OSError, json.JSONDecodeError):
return None
return value if isinstance(value, str) and value else None
def save_setting(name: str, value: str) -> None:
path = config_path()
data: dict[str, object] = {}
if path.is_file():
try:
data = json.loads(path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError):
pass
path.parent.mkdir(parents=True, exist_ok=True)
data[name] = value
path.write_text(json.dumps(data, indent=2, sort_keys=True) + "\n", encoding="utf-8")