cmvr-visual/backend/app/adapters/provider/audio_timeline.py

251 lines
9.7 KiB
Python
Raw Normal View History

"""有界采样归一化与多轨混音;仅接受素材编号及经过验证的数值。"""
import math
import re
import uuid
import wave
from app.adapters.media import input_options, run_process
from app.domain.errors import MediaError
from app.domain.execution import CpuResult, enter_phase
MAX_MIX_SEGMENTS = 128
MAX_TOTAL_FRAMES = 360000
def _error(message):
return MediaError("invalid_parameters", message)
def _integer(value, minimum, maximum):
if type(value) is not int or not minimum <= value <= maximum:
raise _error("音频样本或帧数超出允许范围")
return value
def _id(value):
if not isinstance(value, str) or not re.fullmatch(r"[A-Za-z0-9_.-]{1,64}", value):
raise _error("音频只接受素材编号")
def validate(task_type, inputs, parameters):
if not isinstance(inputs, dict) or not isinstance(parameters, dict):
raise _error("音频输入无效")
if task_type == "audio.normalize":
if set(inputs) != {"asset_id"} or parameters:
raise _error("音频归一化仅接受素材编号")
_id(inputs["asset_id"])
return
if (
task_type != "audio.mix"
or set(inputs) != {"segments", "total_frames"}
or set(parameters) - {"ducking"}
):
raise _error("音轨混音字段无效")
if type(parameters.get("ducking", False)) is not bool:
raise _error("旁白压低背景音乐必须为布尔值")
frames = _integer(inputs["total_frames"], 1, MAX_TOTAL_FRAMES)
segments = inputs["segments"]
if not isinstance(segments, list) or not 1 <= len(segments) <= MAX_MIX_SEGMENTS:
raise _error(f"一次混音支持1–{MAX_MIX_SEGMENTS}个片段")
allowed = {
"asset_id",
"source_start_sample",
"source_end_sample",
"offset_sample",
"gain_db",
"fade_in_samples",
"fade_out_samples",
"role",
"segment_id",
}
for segment in segments:
if not isinstance(segment, dict) or set(segment) - allowed:
raise _error("音频片段字段无效")
_id(segment.get("asset_id"))
a = _integer(segment.get("source_start_sample", 0), 0, MAX_TOTAL_FRAMES * 2000)
b = _integer(segment.get("source_end_sample"), 1, MAX_TOTAL_FRAMES * 2000)
offset = _integer(segment.get("offset_sample", 0), 0, frames * 2000)
if b <= a or offset + b - a > frames * 2000:
raise _error("音频区间超出成片")
gain = segment.get("gain_db", 0.0)
if type(gain) not in (int, float) or not math.isfinite(gain) or not -60 <= gain <= 12:
raise _error("音量超出允许范围")
fades = [
_integer(segment.get(key, 0), 0, b - a)
for key in ("fade_in_samples", "fade_out_samples")
]
if sum(fades) > b - a or segment.get("role", "narration") not in {
"narration",
"bgm",
"sfx",
}:
raise _error("音频淡入淡出或图层类型无效")
if "segment_id" in segment:
_id(segment["segment_id"])
def _samples(path):
try:
with wave.open(str(path), "rb") as audio:
if (audio.getframerate(), audio.getnchannels(), audio.getsampwidth()) != (48000, 2, 2):
raise ValueError
return audio.getnframes()
except (wave.Error, EOFError, ValueError):
raise MediaError("invalid_output", "音频归一化结果无效") from None
async def _normalize_file(provider, source, target):
maximum = min(MAX_TOTAL_FRAMES * 2000, (provider.settings.max_output_bytes - 128) // 4)
if maximum < 1:
raise MediaError("output_too_large", "音频输出空间不足")
await run_process(
[
provider.settings.ffmpeg_bin,
"-v",
"error",
"-nostdin",
*input_options(),
"-i",
str(source),
"-vn",
"-t",
f"{(maximum + 1) / 48000:.9f}",
"-ar",
"48000",
"-ac",
"2",
"-c:a",
"pcm_s16le",
"-y",
str(target),
],
timeout=300,
)
count = _samples(target)
if count < 1 or count > maximum or target.stat().st_size > provider.settings.max_output_bytes:
raise MediaError("output_too_large", "音频归一化超出输出大小限制")
return count
async def normalize(provider, inputs, parameters, assets, work):
validate("audio.normalize", inputs, parameters)
await enter_phase("audio_normalize", "cpu_media")
target = work / ("normalized-" + uuid.uuid4().hex + ".wav")
try:
count = await _normalize_file(provider, provider._asset(inputs["asset_id"], assets), target)
result = {
"sample_rate": 48000,
"sample_count": count,
"duration_seconds": count / 48000,
"source_asset_id": inputs["asset_id"],
}
return CpuResult(
[target, provider._json_file(work, "normalized.json", result)],
result,
{"provider": "ffmpeg-cpu", "recipe": "audio-normalize-v2"},
)
except BaseException:
target.unlink(missing_ok=True)
raise
async def mix(provider, inputs, parameters, assets, work):
validate("audio.mix", inputs, parameters)
await enter_phase("audio_mix", "cpu_media")
total = inputs["total_frames"] * 2000
if total * 4 + 128 > provider.settings.max_output_bytes:
raise MediaError("output_too_large", "混音音轨超出输出大小限制")
target = work / ("mixed-" + uuid.uuid4().hex + ".wav")
temporary, normalized, counts = [], {}, {}
script = work / ("mix-" + uuid.uuid4().hex + ".txt")
try:
argv = [provider.settings.ffmpeg_bin, "-v", "error", "-nostdin"]
filters, labels, narration, backgrounds = [], [], [], []
for index, segment in enumerate(inputs["segments"]):
aid = segment["asset_id"]
if aid not in normalized:
path = work / ("mix-source-" + uuid.uuid4().hex + ".wav")
temporary.append(path)
counts[aid] = await _normalize_file(provider, provider._asset(aid, assets), path)
normalized[aid] = path
a, b = segment.get("source_start_sample", 0), segment["source_end_sample"]
if b > counts[aid]:
raise MediaError("invalid_timeline", "混音选用区间超出实际源样本数")
argv += [*input_options(), "-i", str(normalized[aid])]
length = b - a
chain = f"[{index}:a]atrim=start_sample={a}:end_sample={b},asetpts=PTS-STARTPTS,volume={10 ** (segment.get('gain_db', 0) / 20):.12f}"
fi, fo = segment.get("fade_in_samples", 0), segment.get("fade_out_samples", 0)
if fi:
chain += f",afade=t=in:ss=0:ns={fi}"
if fo:
chain += f",afade=t=out:ss={length - fo}:ns={fo}"
chain += f",adelay=delays={segment.get('offset_sample', 0)}S:all=1[s{index}]"
filters.append(chain)
labels.append(f"[s{index}]")
if segment.get("role", "narration") == "narration":
narration.append(f"[s{index}]")
elif segment.get("role") == "bgm":
backgrounds.append(f"[s{index}]")
if parameters.get("ducking") and narration and backgrounds:
others = [label for label in labels if label not in narration + backgrounds]
filters.append(
"".join(narration)
+ f"amix=inputs={len(narration)}:normalize=0,asplit=2[voice][side]"
)
filters.append(
"".join(backgrounds) + f"amix=inputs={len(backgrounds)}:normalize=0[music]"
)
filters.append(
"[music][side]sidechaincompress=threshold=0.03:ratio=6:attack=20:release=250[ducked]"
)
labels = ["[voice]", "[ducked]", *others]
filters.append(
"".join(labels)
+ f"amix=inputs={len(labels)}:normalize=0:dropout_transition=0,alimiter=limit=0.95:level=disabled:latency=1,apad=whole_len={total},atrim=end_sample={total}[mixed]"
)
script.write_text(";\n".join(filters), encoding="utf-8")
# FFmpeg 9已删除filter_complex_script;新版用文件参数语法,旧版保留原选项。
version = (
await run_process([provider.settings.ffmpeg_bin, "-version"], timeout=10)
).decode("utf-8", "replace")
major = re.search(r"ffmpeg version (?:n)?(\d+)", version)
graph_option = (
"-/filter_complex" if major and int(major[1]) >= 7 else "-filter_complex_script"
)
argv += [
graph_option,
str(script),
"-map",
"[mixed]",
"-ar",
"48000",
"-ac",
"2",
"-c:a",
"pcm_s16le",
"-y",
str(target),
]
await run_process(argv, timeout=min(3600, max(300, inputs["total_frames"] / 24 * 5)))
if _samples(target) != total or target.stat().st_size > provider.settings.max_output_bytes:
raise MediaError("invalid_output", "混音音轨样本数或输出大小不正确")
result = {
"sample_rate": 48000,
"sample_count": total,
"total_frames": inputs["total_frames"],
"segments": inputs["segments"],
}
return CpuResult(
[target, provider._json_file(work, "mix.json", result)],
result,
{"provider": "ffmpeg-cpu", "recipe": "audio-mix-v2"},
)
except BaseException:
target.unlink(missing_ok=True)
raise
finally:
script.unlink(missing_ok=True)
for path in temporary:
path.unlink(missing_ok=True)