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

235 lines
8.8 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""原声选段使用同一个媒体时间原点,不用异步重采样拉伸或补齐语音。"""
import json
from fractions import Fraction
import uuid
import wave
from pathlib import Path
from app.adapters.media import input_options, inspect_video_track, run_process
from app.domain.errors import MediaError
from app.domain.execution import CpuResult, enter_phase
POLICY = "native_av_v1"
async def _timing(provider, source):
raw = await run_process(
[
provider.settings.ffprobe_bin,
"-v",
"error",
*input_options(),
"-show_entries",
"stream=codec_type,start_time,sample_rate,channels:format=start_time",
"-of",
"json",
str(source),
],
timeout=30,
max_output=256 * 1024,
)
try:
info = json.loads(raw)
streams = info["streams"]
audio = next(s for s in streams if s.get("codec_type") == "audio")
video = next(s for s in streams if s.get("codec_type") == "video")
fallback = info.get("format", {}).get("start_time", "0")
origin = Fraction(video.get("start_time", fallback))
onset = Fraction(audio.get("start_time", fallback))
channels = int(audio["channels"])
if channels not in (1, 2) or not -86400 <= origin <= 86400 or not -86400 <= onset <= 86400:
raise ValueError()
return origin, onset, channels
except (ValueError, TypeError, KeyError, StopIteration, ZeroDivisionError):
raise MediaError("missing_native_audio", "原生视频缺少有效原声音轨或时间信息") from None
def _sidecar_info(source):
"""只接受归档的原生立体声 PCM,避免把容器内 AAC 的编码填充当作真实语音。"""
try:
with wave.open(str(source), "rb") as audio:
rate, channels, width, count = (
audio.getframerate(),
audio.getnchannels(),
audio.getsampwidth(),
audio.getnframes(),
)
if (rate, channels, width) != (32000, 2, 2) or count < 1:
raise ValueError()
return dict(
source_sample_rate=rate, source_sample_count=count, source_channels=channels
)
except (OSError, wave.Error, EOFError, ValueError):
raise MediaError(
"invalid_native_audio", "原生音频侧车必须是完整的32kHz立体声PCM WAV"
) from None
async def run_cpu(provider, task, inputs, p, assets, work):
await enter_phase("dialogue_select", "cpu_media")
source = provider._asset(inputs["video_asset_id"], assets)
track = await inspect_video_track(source, provider.settings)
start, count = p["start_frame"], p["duration_frames"]
if abs(track["fps"] - 24) > 0.001 or start + count > track["frames"]:
raise MediaError(
"generation_source_too_short", "原生音视频选段超出24fps源画面,禁止循环补长"
)
sidecar_id = inputs.get("audio_asset_id")
source_info = {}
audio_source = source
if sidecar_id:
from app.adapters.storage import file_thread
audio_source = provider._asset(sidecar_id, assets)
source_info = await file_thread(_sidecar_info, audio_source)
# H3 WAV 与其视频使用共同的逻辑零点;不使用 AAC 编码器的 priming 时间。
origin = onset = Fraction(0)
channels = source_info["source_channels"]
else:
origin, onset, channels = await _timing(provider, source)
beginning = origin + Fraction(start, 24)
ending = beginning + Fraction(count, 24)
offset = max(0, round((onset - beginning) * 48000))
stem = uuid.uuid4().hex
target = work / (
f"native-{stem}.wav" if task == "audio.dialogue.extract" else f"native-{stem}.mp4"
)
# 完整原生尾部可能比视频帧栅格长至多一个音频栅格,提取不能暗中剪掉句尾。
end_trim = f":end={float(ending):.12f}" if start + count < track["frames"] else ""
af = f"aresample=48000,atrim=start={float(beginning):.12f}{end_trim},asetpts=PTS-STARTPTS"
args = [
provider.settings.ffmpeg_bin,
"-v",
"error",
"-nostdin",
"-y",
"-copyts",
*input_options(),
"-i",
str(audio_source),
]
try:
if task == "audio.dialogue.extract":
args += [
"-map",
"0:a:0",
"-vn",
"-af",
af,
"-ar",
"48000",
"-ac",
"2",
"-c:a",
"pcm_s16le",
str(target),
]
else:
if start == 0 and count == track["frames"]:
import shutil
from app.adapters.storage import file_thread
target = work / (f"native-{stem}" + Path(source).suffix)
await file_thread(shutil.copyfile, source, target)
if target.stat().st_size > provider.settings.max_output_bytes:
raise MediaError("output_too_large", "原生音视频超出输出大小限制")
return CpuResult(
[target],
dict(
audio_policy=POLICY,
source_start_frame=0,
source_end_frame=count,
frames=count,
fps=24,
audio=True,
audio_offset_samples=max(0, round((onset - origin) * 48000)),
source_audio_offset_samples=round((onset - origin) * 48000),
source_channels=channels,
),
{
"provider": "ffmpeg-cpu",
"audio_policy": POLICY,
"passthrough": True,
"audio_stretch": False,
},
)
# 延迟只补原本没有采样的静音区间,保留声音相对画面的位置;不改变播放速度。
args += [
"-map",
"0:v:0",
"-map",
"0:a:0",
"-vf",
f"trim=start_frame={start}:end_frame={start + count},setpts=PTS-STARTPTS",
"-af",
af + f",adelay={offset}S:all=1",
"-frames:v",
str(count),
"-c:v",
"libx264",
"-preset",
"fast",
"-crf",
"18",
"-pix_fmt",
"yuv420p",
"-ar",
"48000",
"-ac",
"2",
"-c:a",
"aac",
"-movflags",
"+faststart",
str(target),
]
await run_process(args, timeout=300)
samples = None
if task == "audio.dialogue.extract":
with wave.open(str(target), "rb") as audio:
samples = audio.getnframes()
if samples < 1 or audio.getnchannels() != 2 or audio.getframerate() != 48000:
raise MediaError("missing_native_audio", "选用区间中没有完整可解码的原声")
else:
selected = await inspect_video_track(target, provider.settings)
if selected["frames"] != count or abs(selected["fps"] - 24) > 0.001:
raise MediaError("invalid_output", "原生音视频选段没有保持帧数")
if target.stat().st_size > provider.settings.max_output_bytes:
raise MediaError("output_too_large", "原声音轨超出输出大小限制")
result = dict(
audio_policy=POLICY,
source_start_frame=start,
source_end_frame=start + count,
frames=count,
fps=24,
audio=True,
sample_rate=48000,
channels=2,
source_channels=channels,
audio_offset_samples=offset,
source_audio_offset_samples=round((onset - origin) * 48000),
)
if sidecar_id:
result.update(
source_audio_asset_id=sidecar_id, audio_source="native_sidecar", **source_info
)
else:
result["audio_source"] = "embedded_track"
if samples is not None:
result.update(sample_count=samples, duration_seconds=samples / 48000)
return CpuResult(
[target],
result,
{
"provider": "ffmpeg-cpu",
"audio_policy": POLICY,
"source_asset_id": inputs["video_asset_id"],
"audio_stretch": False,
"source_audio_asset_id": sidecar_id,
},
)
except BaseException:
target.unlink(missing_ok=True)
raise