"""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