""" ============================================================================== AGSoft_Audio_Concatenate_Plus.py ============================================================================== Нода: 🔊🪡AGSoft Audio Concatenate Plus Описание / Description: Склейка до 20 аудиодорожек в один файл с эффектами. Универсальные сокеты audio_N (тип "*") принимают AUDIO-объект, VIDEO-объект (звуковая дорожка), строку пути или тензор волны — как video_N в Video Concatenate Plus. Сокеты добавляются динамически по правилу «подключено+1» (JS-слой). Режимы: concat (встык) и crossfade (плавный переход с настройкой длительности и кривой). Автовыравнивание громкости (loudnorm, EBU R128), fade in/out всего результата, формат source/mp3/wav/flac/ogg/m4a, битрейт, выход AUDIO для цепочек. save_mode: direct = сохранение в output с авто-индексом при коллизии имён; preview = результат только в temp (выдаётся путь + AUDIO-тензор). ВАЖНО: AUDIO/тензор передают уже декодированный PCM, поэтому format=source для такого трека даёт WAV; для сохранения формата файла подавайте путь строкой. --- Concatenates up to 20 audio tracks into one file with effects. Universal audio_N sockets (type "*") accept an AUDIO object, a VIDEO object (audio track), a path string or a waveform tensor - like video_N in Video Concatenate Plus. Sockets are added dynamically by the "connected+1" rule (JS layer). Modes: concat (back-to-back) and crossfade (smooth transition with adjustable duration and curve). Loudness normalization (loudnorm, EBU R128), fade in/out of the whole result, format source/mp3/wav/flac/ogg/m4a, bitrate, AUDIO output for chaining. save_mode: direct = save into output with auto-index on name collision; preview = result only in temp (path + AUDIO tensor are returned). NOTE: AUDIO/tensor deliver already-decoded PCM, so format=source gives WAV for such a track; feed a path string to keep the file format. Возможности / Features: ⚡ Универсальные сокеты audio_N ("*"): AUDIO / VIDEO / путь / тензор волны. Universal audio_N sockets ("*"): AUDIO / VIDEO / path / waveform tensor. ⚡ Динамика «подключено+1» (минимум 1, максимум 20), без виджетов путей. "Connected+1" dynamics (min 1, max 20), no path widgets. ⚡ save_mode direct/preview: output с авто-индексом или только temp + выходы. save_mode direct/preview: output with auto-index or temp-only + outputs. ⚡ Авто-суффикс _001.._999 при коллизии имён: несколько нод не перезаписывают файл. Auto-suffix _001.._999 on name collision: several nodes never overwrite. ⚡ Per-node temp namespace agsoft_audio_concat_: очистка в начале прогона. Per-node temp namespace agsoft_audio_concat_: cleared at run start. ⚡ Режим concat (встык) и crossfade (плавный переход). Concat (back-to-back) and crossfade (smooth transition) modes. ⚡ Длительность и кривая кроссфейда (tri/exp/log/qsin/hsin/dese/desi/nofade). Crossfade duration and curve. ⚡ Нормализация громкости всех треков (loudnorm, EBU R128) перед склейкой. Loudness normalization of all tracks (loudnorm, EBU R128) before joining. ⚡ Fade in / fade out всего результата. Fade in / fade out of the whole result. ⚡ Формат source/mp3/wav/flac/ogg/m4a + битрейт для lossy. Format source/mp3/wav/flac/ogg/m4a + bitrate for lossy. ⚡ Асинхронный пайплайн (async FUNCTION), kill+wait в finally. Async pipeline (async FUNCTION), kill+wait in finally. ⚡ Выход AUDIO для цепочек + метаданные (длительность, таймкод, размер, Гц, каналы). AUDIO output for chaining + metadata (duration, timecode, size, Hz, channels). Автор / Author: AGSoft Дата / Date: 04.12.2026 ============================================================================== """ import os import re import json import wave import asyncio import hashlib import logging import shutil from typing import Dict, Any, Tuple, Optional import torch import numpy as np try: import folder_paths except ImportError: class FolderPathsStub: def get_input_directory(self) -> str: return os.path.abspath(".") def get_output_directory(self) -> str: return os.path.abspath(".") def get_temp_directory(self) -> str: return os.path.abspath(".") folder_paths = FolderPathsStub() try: import imageio_ffmpeg FFMPEG_PATH = imageio_ffmpeg.get_ffmpeg_exe() except Exception: FFMPEG_PATH = "ffmpeg" _ffprobe_same_dir = os.path.join( os.path.dirname(os.path.abspath(FFMPEG_PATH)), "ffprobe.exe" if os.name == "nt" else "ffprobe" ) FFPROBE_PATH = _ffprobe_same_dir if os.path.isfile(_ffprobe_same_dir) else ( shutil.which("ffprobe") or "ffprobe" ) logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) # print("[AGSoft Audio Concatenate Plus] v12.04d loaded (save_mode preview/direct, unique names)") MAX_INPUTS = 20 MODES = ["concat", "crossfade"] CURVES = ["tri", "exp", "log", "qsin", "hsin", "dese", "desi", "nofade"] FORMAT_CHOICES = ["source", "mp3", "wav", "flac", "ogg", "m4a"] FORMAT_CODECS = { ".mp3": "libmp3lame", ".wav": "pcm_s16le", ".flac": "flac", ".ogg": "libvorbis", ".m4a": "aac", } LOSSY_EXTS = {".mp3", ".ogg", ".m4a"} LOUDNORM = "loudnorm=I=-16:TP=-1.5:LRA=11" LOG_PREFIX = "[AGSoft Audio Concat Plus]" def _tip(en: str, ru: str) -> str: """Двуязычный тултип / Bilingual tooltip.""" return en + "\n---\n" + ru def _single(value: Any, default: Any = "") -> Any: """Распаковка значения из списка / Unpack value from list.""" if isinstance(value, (list, tuple)): value = value[0] if value else default return value if value is not None else default def safe_float(value: Any, default: float = 0.0) -> float: """Безопасное преобразование в float / Safe float conversion.""" try: return float(default) if value is None else float(value) except Exception: return float(default) def _roots() -> list: """Разрешённые корни ComfyUI / Allowed ComfyUI roots.""" return [ folder_paths.get_input_directory(), folder_paths.get_output_directory(), folder_paths.get_temp_directory(), ] def _contained(path: str, roots: list) -> bool: """Проверка containment / Containment check.""" rp = os.path.normcase(os.path.realpath(path)) for root in roots: rr = os.path.normcase(os.path.realpath(root)) if rp == rr or rp.startswith(rr + os.sep): return True return False def unique_path(path: str) -> str: """Авто-суффикс при коллизии имён / Auto-suffix on name collision.""" if not os.path.exists(path): return path base, ext = os.path.splitext(path) for i in range(1, 1000): cand = f"{base}_{i:03d}{ext}" if not os.path.exists(cand): return cand return path def node_temp_dir(node_id: str) -> str: """Temp-namespace ноды, очистка в начале прогона / Per-node temp namespace.""" root = os.path.join(folder_paths.get_temp_directory(), f"agsoft_audio_concat_{node_id}") if os.path.isdir(root): shutil.rmtree(root, ignore_errors=True) os.makedirs(root, exist_ok=True) return root def final_destination(output_name: str, output_path: str, save_mode: str, tmp_dir: str, target_ext: str) -> Tuple[str, str]: """Куда писать результат: temp (preview) или output (direct). Where to write the result: temp (preview) or output (direct).""" safe_name = os.path.basename(str(output_name or "audio_concat_plus")) stem, _ = os.path.splitext(safe_name) safe_name = f"{stem or 'audio_concat_plus'}{target_ext}" if save_mode == "preview": return os.path.join(tmp_dir, safe_name), "temp" out_str = "" if output_path is None else str(output_path).strip() target_dir = os.path.abspath(out_str) if out_str else ( folder_paths.get_output_directory() or os.path.abspath(".") ) os.makedirs(target_dir, exist_ok=True) return unique_path(os.path.join(target_dir, safe_name)), "output" def resolve_target_ext(format_choice: str, source_ext: str) -> str: """Определяет расширение выхода / Determines output extension.""" if format_choice == "source": return source_ext if source_ext in FORMAT_CODECS else ".wav" return "." + format_choice def codec_args_for(ext: str, bitrate: str) -> list: """Аргументы кодека для FFmpeg / FFmpeg codec arguments.""" codec = FORMAT_CODECS.get(ext, "pcm_s16le") args = ["-c:a", codec] if ext in LOSSY_EXTS: args += ["-b:a", bitrate] return args async def ffprobe_duration(path: str) -> Optional[float]: """Получает длительность через ffprobe / Gets duration via ffprobe.""" proc = None try: cmd = [FFPROBE_PATH, "-v", "error", "-show_entries", "format=duration", "-of", "json", path] proc = await asyncio.create_subprocess_exec( *cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE ) stdout, _ = await proc.communicate() if proc.returncode != 0: return None data = json.loads(stdout.decode("utf-8", errors="ignore") or "{}") duration = data.get("format", {}).get("duration", None) return float(duration) if duration is not None else None except Exception as e: logger.debug("%s ffprobe_duration failed: %s", LOG_PREFIX, e) return None finally: if proc is not None and proc.returncode is None: proc.kill() await proc.wait() async def parse_audio_info(path: str) -> Dict[str, Any]: """Парсит метаданные аудиофайла / Parses audio file metadata.""" info = {"duration": 0.0, "sample_rate": 0, "channels": 0, "size_mb": 0.0} try: info["size_mb"] = round(os.path.getsize(path) / (1024 * 1024), 3) except Exception: pass dur = await ffprobe_duration(path) if dur and dur > 0: info["duration"] = round(dur, 3) proc = None data = "" try: proc = await asyncio.create_subprocess_exec( FFMPEG_PATH, "-hide_banner", "-i", path, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE ) _, stderr = await proc.communicate() data = stderr.decode("utf-8", errors="ignore") except Exception: return info finally: if proc is not None and proc.returncode is None: proc.kill() await proc.wait() if info["duration"] <= 0: m = re.search(r"Duration:\s*(\d{2}):(\d{2}):(\d{2}(?:\.\d+)?)", data) if m: info["duration"] = round( int(m.group(1)) * 3600 + int(m.group(2)) * 60 + float(m.group(3)), 3 ) audio_line = "" for line in data.splitlines(): if "Audio:" in line: audio_line = line break if audio_line: sm = re.search(r"(\d+)\s*Hz", audio_line) if sm: info["sample_rate"] = int(sm.group(1)) cm = re.search(r"Hz,\s*(mono|stereo|(\d+)\s*channels)", audio_line) if cm: if cm.group(1) == "mono": info["channels"] = 1 elif cm.group(1) == "stereo": info["channels"] = 2 elif cm.group(2): info["channels"] = int(cm.group(2)) return info def audio_to_wav(audio_obj: Dict[str, Any], path: str) -> None: """Сохраняет AUDIO-объект в WAV / Saves AUDIO object to WAV.""" wf = audio_obj.get("waveform") sr = int(audio_obj.get("sample_rate", 44100)) arr = wf.cpu().numpy() if hasattr(wf, "cpu") else np.asarray(wf) if arr.ndim == 3: arr = arr[0] if arr.ndim == 1: arr = arr.reshape(1, -1) arr = np.clip(arr, -1.0, 1.0) pcm = (arr * 32767.0).astype(" Tuple[Optional[str], Optional[str]]: """Универсальный резолвер трека: AUDIO / VIDEO / путь / тензор. Universal track resolver: AUDIO / VIDEO / path / tensor.""" value = _single(value, None) if value is None: return None, None if isinstance(value, str): p = value.strip() if not p: return None, None if not os.path.isabs(p): p = os.path.join(folder_paths.get_input_directory(), p) if not os.path.isfile(p): raise FileNotFoundError(f"{LOG_PREFIX} Track {index}: file not found / файл не найден: {p}") if not _contained(p, _roots()): raise ValueError(f"{LOG_PREFIX} Track {index}: path outside ComfyUI folders / путь вне папок ComfyUI.") return p, os.path.splitext(p)[1].lower() if isinstance(value, dict) and "waveform" in value: out = os.path.join(work_dir, f"track_{index:02d}.wav") audio_to_wav(value, out) return out, ".wav" if hasattr(value, "get_stream_source"): src = value.get_stream_source() if isinstance(src, str) and os.path.isfile(src): if not _contained(src, _roots()): raise ValueError(f"{LOG_PREFIX} Track {index}: path outside ComfyUI folders / путь вне папок.") return src, os.path.splitext(src)[1].lower() if hasattr(src, "read"): out = os.path.join(work_dir, f"track_{index:02d}_src.mp4") with open(out, "wb") as f: if hasattr(src, "seek"): src.seek(0) shutil.copyfileobj(src, f) return out, os.path.splitext(out)[1].lower() if hasattr(value, "get_components"): comp = value.get_components() aud = comp.audio if hasattr(comp, "audio") else None if aud is None: raise ValueError(f"{LOG_PREFIX} Track {index}: no audio track / нет звуковой дорожки.") out = os.path.join(work_dir, f"track_{index:02d}.wav") audio_to_wav(aud, out) return out, ".wav" if hasattr(value, "shape") and getattr(value, "ndim", 0) in (2, 3): out = os.path.join(work_dir, f"track_{index:02d}.wav") audio_to_wav({"waveform": value, "sample_rate": 44100}, out) return out, ".wav" raise ValueError(f"{LOG_PREFIX} Track {index}: unsupported input type / неподдерживаемый тип входа.") async def audio_file_to_comfy_audio(path: str, work_dir: str) -> Dict[str, Any]: """Декодирует файл в объект AUDIO / Decodes file to AUDIO object.""" wav_path = os.path.join(work_dir, "_comfy_audio_out.wav") cmd = [FFMPEG_PATH, "-y", "-hide_banner", "-i", path, "-vn", "-c:a", "pcm_s16le", wav_path] proc = await asyncio.create_subprocess_exec( *cmd, stdout=asyncio.subprocess.DEVNULL, stderr=asyncio.subprocess.PIPE ) try: await proc.communicate() finally: if proc.returncode is None: proc.kill() await proc.wait() try: with wave.open(wav_path, "rb") as w: nchannels = w.getnchannels() sr = w.getframerate() nframes = w.getnframes() raw = w.readframes(nframes) arr = np.frombuffer(raw, dtype=np.int16).astype(np.float32) / 32768.0 arr = arr.reshape(-1, nchannels) arr = arr.T tensor = torch.from_numpy(arr).unsqueeze(0) return {"waveform": tensor, "sample_rate": sr} except Exception as e: logger.warning("%s не удалось создать AUDIO-выход: %s", LOG_PREFIX, e) return {"waveform": torch.zeros(1, 1, 1), "sample_rate": 44100} def build_concat_filter(sources: list, mode: str, crossfade_dur: float, curve: str, loudnorm_on: bool, fade_in: float, fade_out: float, total_dur: float) -> str: """Сборка filter_complex для склейки / Builds filter_complex for concat.""" parts = [] n = len(sources) for i in range(n): chain = f"[{i}:a]aresample=44100:async=1,aformat=sample_fmts=fltp:channel_layouts=stereo" if loudnorm_on: chain += f",{LOUDNORM}" chain += f"[a{i}]" parts.append(chain) if n == 1: parts.append("[a0]anull[a_joined]") elif mode == "crossfade" and crossfade_dur > 0: prev = "a0" for i in range(1, n): out_label = "a_joined" if i == n - 1 else f"xf{i}" parts.append( f"[{prev}][a{i}]acrossfade=d={crossfade_dur:.6f}:c1={curve}:c2={curve}[{out_label}]" ) prev = out_label else: inputs = "".join(f"[a{i}]" for i in range(n)) parts.append(f"{inputs}concat=n={n}:v=0:a=1[a_joined]") fades = [] if fade_in > 0: fades.append(f"afade=t=in:st=0:d={fade_in:.6f}") if fade_out > 0: st = max(0.0, total_dur - fade_out) fades.append(f"afade=t=out:st={st:.6f}:d={fade_out:.6f}") if fades: parts.append(f"[a_joined]{','.join(fades)}[a_final]") else: parts.append("[a_joined]anull[a_final]") return ";".join(parts) async def run_ffmpeg_with_progress(cmd: list, total_duration: float = 0.0, tag: str = LOG_PREFIX) -> Tuple[int, str]: """Запуск FFmpeg с прогрессом / Runs FFmpeg with progress.""" try: proc = await asyncio.create_subprocess_exec( *cmd, stdout=asyncio.subprocess.DEVNULL, stderr=asyncio.subprocess.PIPE ) except FileNotFoundError: raise RuntimeError(f"{tag} FFmpeg не найден: {FFMPEG_PATH}") stderr_chunks = [] last_bucket = -1 time_regex = re.compile(r"time=(\d+):(\d+):(\d+(?:\.\d+)?)") try: async for line in proc.stderr: line_str = line.decode("utf-8", errors="ignore") stderr_chunks.append(line_str) if total_duration > 0: match = time_regex.search(line_str) if match: current = (int(match.group(1)) * 3600 + int(match.group(2)) * 60 + float(match.group(3))) percent = max(0, min(100, int(current / total_duration * 100))) bucket = percent // 5 if bucket > last_bucket: logger.info("%s Progress: %d%%", tag, bucket * 5) last_bucket = bucket await proc.wait() finally: if proc.returncode is None: proc.kill() await proc.wait() return proc.returncode, "".join(stderr_chunks) def format_timecode(seconds: float) -> str: """Форматирует секунды в таймкод / Formats seconds to timecode.""" try: seconds = max(0.0, float(seconds)) except Exception: return "00:00:00.000" ms = int(round((seconds - int(seconds)) * 1000)) total = int(seconds) if ms >= 1000: total += 1 ms = 0 h = total // 3600 m = (total % 3600) // 60 s = total % 60 return f"{h:02d}:{m:02d}:{s:02d}.{ms:03d}" class AGSoftAudioConcatenatePlus: """🔊🪡Склейка аудио с эффектами / Audio concatenation with effects.""" OUTPUT_NODE = True RETURN_TYPES = ("STRING", "AUDIO", "FLOAT", "STRING", "FLOAT", "INT", "INT") RETURN_NAMES = ("audio_path", "audio", "duration_seconds", "duration_timecode", "file_size_mb", "sample_rate", "channels") OUTPUT_TOOLTIPS = ( _tip("Path of the result: output in direct mode, temp in preview mode.", "Путь результата: output в режиме direct, temp в режиме preview."), _tip("AUDIO object for chaining with other nodes.", "Объект AUDIO для цепочек с другими нодами."), _tip("Duration in seconds.", "Длительность в секундах."), _tip("Duration as timecode HH:MM:SS.mmm.", "Длительность в формате таймкода ЧЧ:ММ:СС.ммм."), _tip("File size in megabytes.", "Размер файла в мегабайтах."), _tip("Sample rate in Hz.", "Частота дискретизации в Гц."), _tip("Number of audio channels.", "Количество аудиоканалов."), ) FUNCTION = "concat_audios_plus" CATEGORY = "AGSoft/Audio" WEB_DIRECTORY = "./web" DESCRIPTION = ( "🔊🪡AGSoft Audio Concatenate Plus.\n" "Concatenates up to 20 audio tracks into one file with effects. Universal audio_N sockets " "(type *) accept an AUDIO object, a VIDEO object (audio track), a path string or a waveform " "tensor - like video_N in Video Concatenate Plus. Sockets are added dynamically by the " "connected+1 rule (JS layer). Modes: concat (back-to-back) and crossfade (smooth transition " "with adjustable duration and curve: tri/exp/log/qsin/hsin/dese/desi/nofade). Loudness " "normalization (loudnorm, EBU R128) levels all tracks before joining. Fade in/out of the " "whole result. Output format source/mp3/wav/flac/ogg/m4a and bitrate. AUDIO output for " "chaining. save_mode: direct = save into output with auto-index on name collision; " "preview = result only in temp (path + AUDIO tensor returned). Async pipeline.\n" "NOTE: AUDIO/tensor deliver already-decoded PCM, so format=source gives WAV for such a " "track; feed a path string to keep the file format.\n" "---\n" "🔊🪡AGSoft Audio Concatenate Plus.\n" "Склейка до 20 аудиодорожек в один файл с эффектами. Универсальные сокеты audio_N (тип *) " "принимают AUDIO-объект, VIDEO-объект (звуковая дорожка), строку пути или тензор волны — " "как video_N в Video Concatenate Plus. Сокеты добавляются динамически по правилу " "«подключено+1» (JS-слой). Режимы: concat (встык) и crossfade (плавный переход с " "настраиваемой длительностью и кривой: tri/exp/log/qsin/hsin/dese/desi/nofade). " "Автовыравнивание громкости (loudnorm, EBU R128) приводит все треки к единому уровню перед " "склейкой. Fade in/out всего результата. Формат выхода source/mp3/wav/flac/ogg/m4a и " "битрейт. Выход AUDIO для цепочек. save_mode: direct = сохранение в output с авто-индексом " "при коллизии имён; preview = результат только в temp (выдаётся путь + AUDIO-тензор). " "Асинхронный пайплайн.\n" "ВАЖНО: AUDIO/тензор передают уже декодированный PCM, поэтому format=source для такого " "трека даёт WAV; для сохранения формата файла подавайте путь строкой." ) @classmethod def INPUT_TYPES(cls) -> Dict[str, Dict[str, Any]]: required = { "output_name": ( "STRING", { "default": "audio_concat_plus.mp3", "tooltip": _tip( "Output filename. The extension is set by the chosen format. " "On name collision an auto-index _001.._999 is added (direct mode).", "Имя итогового файла. Расширение задаётся выбранным форматом. " "При коллизии имён добавляется авто-индекс _001.._999 (режим direct)." ) } ), "output_path": ( "STRING", { "default": "", "tooltip": _tip( "Output directory (direct mode). If empty, ComfyUI/output is used.", "Папка сохранения (режим direct). Если пусто, используется ComfyUI/output." ) } ), "save_mode": ( ["direct", "preview"], { "default": "direct", "tooltip": _tip( "direct = save the file into output (unique name on collision). " "preview = write into temp only; the node returns the path and the " "AUDIO tensor without saving into output.", "direct = сохранить файл в output (уникальное имя при коллизии). " "preview = писать только в temp; нода выдаёт путь и AUDIO-тензор " "без сохранения в output." ) } ), "mode": ( MODES, { "default": "concat", "tooltip": _tip( "concat = join tracks back-to-back (no transition).\n" "crossfade = smooth transition between tracks.", "concat = склейка встык (без перехода).\n" "crossfade = плавный переход между треками." ) } ), "crossfade_duration": ( "FLOAT", { "default": 1.0, "min": 0.1, "max": 30.0, "step": 0.1, "tooltip": _tip( "Crossfade duration (seconds) between adjacent tracks. " "Used only in crossfade mode.", "Длительность кроссфейда (в секундах) между соседними треками. " "Только в режиме crossfade." ) } ), "crossfade_curve": ( CURVES, { "default": "tri", "tooltip": _tip( "Crossfade curve. tri = linear, exp = exponential, log = logarithmic, " "qsin/hsin = sine-based, dese/desi = sigmoid, nofade = hard cut.", "Кривая кроссфейда. tri = линейная, exp = экспоненциальная, " "log = логарифмическая, qsin/hsin = синусоидные, dese/desi = сигмоидные, " "nofade = жёсткий рез." ) } ), "loudnorm": ( ["off", "on"], { "default": "off", "tooltip": _tip( "Normalize loudness of all tracks to EBU R128 (I=-16 LUFS) before " "joining, so no track is louder than another.", "Нормализовать громкость всех треков по EBU R128 (I=-16 LUFS) перед " "склейкой, чтобы ни один трек не был громче другого." ) } ), "fade_in": ( "FLOAT", { "default": 0.0, "min": 0.0, "max": 60.0, "step": 0.05, "tooltip": _tip( "Fade-in of the whole result (seconds). 0 = off.", "Нарастание всего результата (в секундах). 0 = выкл." ) } ), "fade_out": ( "FLOAT", { "default": 0.0, "min": 0.0, "max": 60.0, "step": 0.05, "tooltip": _tip( "Fade-out of the whole result (seconds). 0 = off.", "Затухание всего результата (в секундах). 0 = выкл." ) } ), "format": ( FORMAT_CHOICES, { "default": "mp3", "tooltip": _tip( "Output format. source = keep the source format. mp3/wav/flac/ogg/m4a = " "convert. NOTE: AUDIO/tensor inputs are already decoded to PCM, so the " "source format for them is WAV; feed a path string to keep the format.", "Формат выхода. source = сохранить формат источника. " "mp3/wav/flac/ogg/m4a = конвертировать. ВАЖНО: входы AUDIO/тензор уже " "декодированы в PCM, поэтому форматом source для них будет WAV; для " "сохранения формата подавайте путь строкой." ) } ), "bitrate": ( ["96k", "128k", "192k", "256k", "320k"], { "default": "192k", "tooltip": _tip( "Bitrate for lossy formats (mp3/ogg/m4a). Ignored for wav/flac.", "Битрейт для lossy-форматов (mp3/ogg/m4a). Игнорируется для wav/flac." ) } ), } optional = {} for i in range(1, MAX_INPUTS + 1): optional[f"audio_{i}"] = ( "*", { "tooltip": _tip( f"Universal track input #{i}: AUDIO object, VIDEO object (audio track), " "path string or waveform tensor. Empty slots are skipped.", f"Универсальный вход трека #{i}: AUDIO-объект, VIDEO-объект (звуковая " "дорожка), строка пути или тензор волны. Пустые слоты пропускаются." ) } ) return {"required": required, "optional": optional, "hidden": {"unique_id": "UNIQUE_ID"}} @classmethod def IS_CHANGED(cls, **kwargs) -> object: """Кэш: подключённые треки всегда пересчитываются / Cache: linked tracks recompute.""" for key in kwargs: if key.startswith("audio_") and key.replace("audio_", "").isdigit(): return float("nan") h = hashlib.sha256() params = {k: v for k, v in kwargs.items() if not k.startswith("audio_")} h.update(json.dumps(params, sort_keys=True, default=str).encode()) return h.hexdigest() @classmethod def VALIDATE_INPUTS(cls, **kwargs) -> bool: """Проверяет строковые пути, если они пришли значениями / Checks string paths if present.""" for key, value in kwargs.items(): if not (key.startswith("audio_") and key.replace("audio_", "").isdigit()): continue if isinstance(value, str) and value.strip(): p = value.strip() if not os.path.isabs(p): p = os.path.join(folder_paths.get_input_directory(), p) if not os.path.isfile(p): return f"File not found / Файл не найден: {value}" return True @staticmethod def _raise_ffmpeg_error(stderr_text: str) -> None: """Логирует и выбрасывает ошибку FFmpeg / Logs and raises FFmpeg error.""" stderr_text = stderr_text or "" logger.error("%s FFmpeg log:\n%s", LOG_PREFIX, stderr_text[-4000:]) error_msg = "Ошибка FFmpeg" for line in reversed(stderr_text.splitlines()): if line.strip(): error_msg = line.strip() break raise RuntimeError(f"{LOG_PREFIX} FFmpeg не смог склеить аудио. Ошибка: {error_msg}") async def concat_audios_plus( self, output_name: str, output_path: str, save_mode: str, mode: str, crossfade_duration: float, crossfade_curve: str, loudnorm: str, fade_in: float, fade_out: float, format: str, bitrate: str, unique_id=None, **kwargs ) -> Tuple[str, Dict[str, Any], float, str, float, int, int]: """Основной async-метод склейки / Main async concatenation method.""" output_name = _single(output_name, "audio_concat_plus.mp3") output_path = _single(output_path, "") save_mode = _single(save_mode, "direct").strip().lower() mode = _single(mode, "concat").strip().lower() crossfade_curve = _single(crossfade_curve, "tri").strip().lower() loudnorm_on = _single(loudnorm, "off").strip().lower() == "on" format_choice = _single(format, "mp3").strip().lower() bitrate = _single(bitrate, "192k").strip().lower() crossfade_duration = max(0.0, safe_float(crossfade_duration, 1.0)) fade_in = max(0.0, safe_float(fade_in, 0.0)) fade_out = max(0.0, safe_float(fade_out, 0.0)) node_id = str(unique_id or "0") tmp_dir = node_temp_dir(node_id) work_dir = os.path.join(tmp_dir, "work") os.makedirs(work_dir, exist_ok=True) try: sources = [] source_exts = [] for i in range(1, MAX_INPUTS + 1): p, ext = await resolve_audio(kwargs.get(f"audio_{i}"), i, work_dir) if p: sources.append(p) source_exts.append(ext) if len(sources) < 2: raise ValueError( f"{LOG_PREFIX} Нужно подключить как минимум 2 аудиофайла! / " "Connect at least 2 audio sources!" ) first_ext = source_exts[0] if source_exts else ".mp3" target_ext = resolve_target_ext(format_choice, first_ext) final_output_path, kind = final_destination( output_name, output_path, save_mode, tmp_dir, target_ext ) if os.path.isdir(final_output_path): raise ValueError(f"{LOG_PREFIX} Путь назначения — папка: {final_output_path}") final_abs = os.path.normcase(os.path.realpath(final_output_path)) for path in sources: if os.path.normcase(os.path.realpath(path)) == final_abs: raise ValueError(f"{LOG_PREFIX} Итоговый файл не может быть исходным.") durations = [] for p in sources: info = await parse_audio_info(p) d = info["duration"] if d <= 0.05: d = 5.0 logger.warning("%s Длительность не определена, fallback 5.0с: %s", LOG_PREFIX, p) durations.append(d) effective_crossfade = crossfade_duration if mode == "crossfade" and effective_crossfade > 0: min_dur = min(durations) if durations else 0.0 if min_dur > 0 and effective_crossfade >= min_dur: effective_crossfade = max(0.1, min_dur * 0.5) logger.warning("%s Кроссфейд уменьшен до %.2fs (короткий трек)", LOG_PREFIX, effective_crossfade) total_dur = sum(durations) if mode == "crossfade" and effective_crossfade > 0: total_dur -= (len(sources) - 1) * effective_crossfade total_dur = max(0.0, total_dur) filter_complex = build_concat_filter( sources, mode, effective_crossfade, crossfade_curve, loudnorm_on, fade_in, fade_out, total_dur ) input_args = [] for path in sources: input_args.extend(["-i", path]) cmd = [FFMPEG_PATH, "-y", "-hide_banner", *input_args] cmd += ["-filter_complex", filter_complex] cmd += ["-map", "[a_final]"] cmd += codec_args_for(target_ext, bitrate) cmd.append(final_output_path) returncode, stderr = await run_ffmpeg_with_progress(cmd, total_dur, LOG_PREFIX) if returncode != 0: self._raise_ffmpeg_error(stderr) if not os.path.isfile(final_output_path): raise RuntimeError(f"{LOG_PREFIX} Файл не создан: {final_output_path}") out_info = await parse_audio_info(final_output_path) timecode = format_timecode(out_info["duration"]) comfy_audio = await audio_file_to_comfy_audio(final_output_path, work_dir) logger.info( "%s Saved (%s): %s | mode=%s | tracks=%d | crossfade=%.2fs | loudnorm=%s | " "Duration: %s | Size: %s MB", LOG_PREFIX, kind, final_output_path, mode, len(sources), effective_crossfade, loudnorm_on, timecode, out_info["size_mb"] ) return ( final_output_path, comfy_audio, out_info["duration"], timecode, out_info["size_mb"], out_info["sample_rate"], out_info["channels"], ) finally: shutil.rmtree(work_dir, ignore_errors=True) NODE_CLASS_MAPPINGS = { "AGSoftAudioConcatenatePlus": AGSoftAudioConcatenatePlus } NODE_DISPLAY_NAME_MAPPINGS = { "AGSoftAudioConcatenatePlus": "🔊🪡AGSoft Audio Concatenate Plus" }