diff --git a/audio_tool.py b/audio_tool.py new file mode 100755 index 0000000..e866f39 --- /dev/null +++ b/audio_tool.py @@ -0,0 +1,79 @@ +#!/usr/bin/env python3 +"""Extract, remux, or encode one selected audio stream from media files.""" + +from __future__ import annotations + +import sys + +from tools.audio_batch import collect_audio_inputs, run_audio_batch +from tools.audio_settings import choose_settings, select_stream_indexes +from tools.console import launch_terminal_if_needed, pause_if_interactive +from tools.executables import require_executable +from tools.filesystem import determine_working_dir, input_paths + + +def run(argv: list[str]) -> int: + try: + args = input_paths(argv) + if not args: + print("No inputs selected.") + return 0 + working_dir = determine_working_dir(args) + ffmpeg = require_executable("ffmpeg") + ffprobe = require_executable("ffprobe") + inputs, unreadable = collect_audio_inputs(ffprobe, args) + except RuntimeError as exc: + print(exc) + return 1 + + for path in unreadable: + print(f"Warning: could not probe {path}") + without_audio = [item for item in inputs if not item.streams] + if without_audio: + print(f"Warning: {len(without_audio)} input(s) have no audio stream and will be skipped.") + inputs = [item for item in inputs if item.streams] + if not inputs: + print("No audio streams found.") + return 1 + + print(f"Found {len(inputs)} input(s) with audio.") + print("Audio streams:") + for item in inputs: + details = [] + for stream in item.streams: + channels = f", {stream.channels} channels" if stream.channels else "" + rate = f", {stream.sample_rate} Hz" if stream.sample_rate else "" + bitrate = f", {round(stream.bit_rate / 1000)} kbit/s" if stream.bit_rate else "" + details.append(f"{stream.codec}{channels}{rate}{bitrate}") + print(f" {item.path.name}: {'; '.join(details)}") + try: + stream_indexes = select_stream_indexes(inputs) + settings = choose_settings(ffmpeg, inputs, stream_indexes, working_dir) + except RuntimeError as exc: + print(exc) + return 1 + if settings is None: + print("Nothing changed.") + return 0 + + failures = run_audio_batch(ffmpeg, inputs, stream_indexes, settings) + if failures: + print("\nSome files failed:") + for failure in failures: + print(f" - {failure}") + return 1 + print("\nDone.") + return 0 + + +def main(argv: list[str]) -> int: + if launch_terminal_if_needed(argv): + return 0 + try: + return run(argv) + finally: + pause_if_interactive() + + +if __name__ == "__main__": + raise SystemExit(main(sys.argv)) diff --git a/tools/audio_batch.py b/tools/audio_batch.py new file mode 100644 index 0000000..d72ef9c --- /dev/null +++ b/tools/audio_batch.py @@ -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 diff --git a/tools/audio_settings.py b/tools/audio_settings.py new file mode 100644 index 0000000..40d7d1f --- /dev/null +++ b/tools/audio_settings.py @@ -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 diff --git a/tools/user_config.py b/tools/user_config.py new file mode 100644 index 0000000..e6a3cae --- /dev/null +++ b/tools/user_config.py @@ -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") diff --git a/unit_tests/test_audio_and_metadata_editor.py b/unit_tests/test_audio_and_metadata_editor.py new file mode 100644 index 0000000..e501578 --- /dev/null +++ b/unit_tests/test_audio_and_metadata_editor.py @@ -0,0 +1,73 @@ +from __future__ import annotations + +import unittest +from pathlib import Path +from tempfile import TemporaryDirectory + +from tools.audio_batch import ( + AudioInput, + AudioSettings, + AudioStream, + _action_for, + matching_actions, + same_container, + unique_audio_target, + universal_containers, +) +from tools.audio_settings import parse_bitrate, resolve_output_dir + + +class AudioBatchTests(unittest.TestCase): + def audio_input(self, name: str, container: str, codec: str, *, video: bool = False) -> AudioInput: + return AudioInput(Path(name), container, [AudioStream(0, codec, 2, 48000, 192000)], video) + + def test_m4a_is_available_only_for_supported_audio_codecs(self) -> None: + self.assertEqual(universal_containers({"aac", "opus", "flac"}), ["MKA", "M4A"]) + self.assertEqual(universal_containers({"pcm_s16le"}), ["MKA"]) + + def test_video_mp4_is_not_an_already_audio_only_m4a(self) -> None: + self.assertFalse(same_container(self.audio_input("clip.mp4", "mov,mp4,m4a", "aac", video=True), ".m4a")) + self.assertTrue(same_container(self.audio_input("clip.m4a", "mov,mp4,m4a", "aac"), ".m4a")) + + def test_matching_actions_only_offer_skip_when_it_applies(self) -> None: + matching = self.audio_input("clip.m4a", "mov,mp4,m4a", "aac") + other = self.audio_input("clip.flac", "flac", "flac") + self.assertEqual(matching_actions([matching, other], {matching.path: 0, other.path: 0}, ".m4a", "aac"), ["skip", "remux", "re-encode"]) + self.assertEqual(matching_actions([other], {other.path: 0}, ".m4a", "aac"), ["re-encode"]) + + def test_skip_only_applies_to_matching_audio_only_container(self) -> None: + item = self.audio_input("clip.m4a", "mov,mp4,m4a", "aac") + settings = AudioSettings("encode", "aac", "M4A", "skip", "aac", "192k") + self.assertEqual(_action_for(item, item.streams[0], settings), ("skip", "aac")) + + def test_bitrate_accepts_bare_kilobits(self) -> None: + self.assertEqual(parse_bitrate("192"), "192k") + self.assertEqual(parse_bitrate("192K"), "192k") + with self.assertRaisesRegex(ValueError, "positive number"): + parse_bitrate("fast") + + def test_output_directory_resolution(self) -> None: + working_dir = Path.cwd().resolve() + self.assertIsNone(resolve_output_dir("", working_dir)) + self.assertEqual(resolve_output_dir("exports", working_dir), working_dir / "exports") + self.assertEqual(resolve_output_dir(str(working_dir / "elsewhere"), working_dir), working_dir / "elsewhere") + + with TemporaryDirectory() as temporary: + file_path = Path(temporary) / "not-a-directory" + file_path.touch() + with self.assertRaisesRegex(ValueError, "not a directory"): + resolve_output_dir(str(file_path), working_dir) + + def test_output_names_reserve_same_batch_collisions(self) -> None: + output_dir = Path.cwd() / "exports" + reserved: set[Path] = set() + first = unique_audio_target(Path("one/song.mp4"), ".opus", reserved, output_dir) + second = unique_audio_target(Path("two/song.mkv"), ".opus", reserved, output_dir) + self.assertEqual(first, output_dir / "song.opus") + self.assertEqual(second, output_dir / "song-1.opus") + + + + +if __name__ == "__main__": + unittest.main()