726 lines
29 KiB
Python
726 lines
29 KiB
Python
"""对白作者合同与 48 kHz 实测音频的纯时序投影。"""
|
|
|
|
from copy import deepcopy
|
|
from typing import Annotated, Literal
|
|
from uuid import NAMESPACE_URL, uuid5
|
|
|
|
from pydantic import Field, model_validator
|
|
|
|
from app.domain.continuity import (
|
|
StoryShotV4,
|
|
StorySpecV4,
|
|
compile_story_timing,
|
|
supports_sample_timing,
|
|
NativeVideoParameters,
|
|
)
|
|
from app.domain.stories import ID, digest, FrameParameters, VideoParameters
|
|
from app.domain.timeline import Strict
|
|
from app.domain.video_generation import H3_V2_PROFILE, constraints, profile_name
|
|
|
|
StableId = Annotated[str, Field(pattern=ID)]
|
|
Name = Annotated[str, Field(min_length=1, max_length=120, pattern=r"^[\w. -]+$")]
|
|
SAMPLES_PER_FRAME = 2000
|
|
|
|
|
|
class DialogueVoice(Strict):
|
|
provider: Literal["kokoro", "voxcpm2"] = "kokoro"
|
|
model: Name = "kokoro-82m"
|
|
voice: str = Field(default="zf_xiaobei", max_length=120, pattern=r"^[\w. -]*$")
|
|
reference_asset_id: StableId | None = None
|
|
reference_text: str = Field(default="", max_length=2000)
|
|
style: str = Field(default="", max_length=500)
|
|
speed: float = Field(default=1, ge=0.5, le=2, allow_inf_nan=False)
|
|
seed: int = Field(default=42, ge=0, le=2**32 - 1)
|
|
revision: int = Field(default=1, ge=1)
|
|
|
|
@model_validator(mode="after")
|
|
def provider_fields(self):
|
|
if self.provider == "kokoro" and not self.voice.strip():
|
|
raise ValueError("Kokoro 需要声音标识")
|
|
if self.provider == "kokoro" and (self.reference_text or self.style):
|
|
raise ValueError("Kokoro 不支持参考文本或风格指令")
|
|
if self.reference_text and not self.reference_asset_id:
|
|
raise ValueError("参考文本需要参考音频")
|
|
return self
|
|
|
|
|
|
class DialogueSpeaker(Strict):
|
|
id: StableId
|
|
entity_id: StableId | None = None
|
|
name: str = Field(min_length=1, max_length=120)
|
|
voice: DialogueVoice = Field(default_factory=DialogueVoice)
|
|
native_voice: str | None = Field(default=None, min_length=1, max_length=500, exclude_if=lambda value: value is None)
|
|
|
|
|
|
class DialogueUtterance(Strict):
|
|
id: StableId
|
|
speaker_id: StableId
|
|
text: str = Field(min_length=1, max_length=2000)
|
|
spoken_text: str | None = Field(default=None, min_length=1, max_length=2000)
|
|
source: Literal["tts", "asset"] = "tts"
|
|
asset_id: StableId | None = None
|
|
source_start_sample: int = Field(default=0, ge=0)
|
|
source_end_sample: int | None = Field(default=None, gt=0)
|
|
gap_after_sample: int = Field(default=9600, ge=0, le=14400000)
|
|
delivery: str = Field(default="", max_length=500)
|
|
locked: bool = False
|
|
|
|
@model_validator(mode="after")
|
|
def valid_source(self):
|
|
if (self.source == "asset") != bool(self.asset_id):
|
|
raise ValueError("录音来源需要唯一素材")
|
|
if (
|
|
self.source_end_sample is not None
|
|
and self.source_end_sample <= self.source_start_sample
|
|
):
|
|
raise ValueError("录音区间无效")
|
|
return self
|
|
|
|
|
|
class DialogueSequence(Strict):
|
|
id: StableId
|
|
scene_id: StableId | None = None
|
|
shot_ids: list[StableId] = Field(min_length=1, max_length=1000)
|
|
utterance_ids: list[StableId] = Field(default_factory=list, max_length=1000)
|
|
timing_mode: Literal["auto", "fixed"] = "auto"
|
|
|
|
|
|
class ShotPerformance(Strict):
|
|
sequence_id: StableId | None = None
|
|
native_utterance_ids: list[StableId] | None = Field(default=None, max_length=1000, exclude_if=lambda value: value is None)
|
|
visible_speaker_ids: list[StableId] = Field(default_factory=list, max_length=2)
|
|
lip_sync: Literal["auto", "required", "off"] = "auto"
|
|
# 零偏移与已有 V5 镜头序列化完全一致,保留其验收签名。
|
|
audio_context_shift_frames: int = Field(
|
|
default=0, ge=-6, le=6, exclude_if=lambda shift: shift == 0
|
|
)
|
|
duration_mode: Literal["auto", "fixed"] = "auto"
|
|
structure_locked: bool = False
|
|
original_audio: Literal["discard", "preserve"] = "discard"
|
|
|
|
|
|
class DialogueSpec(Strict):
|
|
enabled: bool = True
|
|
# 新作者意图显式选择原生有声;未选择的旧 V5 文档保持原序列化摘要。
|
|
generation: Literal["native_av"] | None = Field(default=None, exclude_if=lambda value: value is None)
|
|
language: str | None = Field(default=None, min_length=1, max_length=80, exclude_if=lambda value: value is None)
|
|
speakers: list[DialogueSpeaker] = Field(default_factory=list, max_length=1000)
|
|
utterances: list[DialogueUtterance] = Field(default_factory=list, max_length=1000)
|
|
sequences: list[DialogueSequence] = Field(default_factory=list, max_length=1000)
|
|
|
|
|
|
class NativeAvVideoParameters(FrameParameters):
|
|
profile: Literal["minimax-h3-fl2va-native-av-v1", "minimax-h3-fl2va-native-av-tp2-v1"]
|
|
source_frames: int = Field(default=124, ge=124, le=345)
|
|
num_inference_steps: int = Field(default=50, ge=2, le=100)
|
|
upscale: Literal[False] = False
|
|
|
|
@model_validator(mode="after")
|
|
def native_length(self):
|
|
if (self.source_frames-124)%17 or self.profile == "minimax-h3-fl2va-native-av-tp2-v1" and self.source_frames>158:
|
|
raise ValueError("H3原生音视频帧数不在此配置的支持范围")
|
|
return self
|
|
|
|
|
|
class StoryShotV5(StoryShotV4):
|
|
video_parameters: NativeAvVideoParameters | NativeVideoParameters | VideoParameters = Field(default_factory=VideoParameters)
|
|
performance: ShotPerformance = Field(default_factory=ShotPerformance)
|
|
|
|
|
|
class StorySpecV5(StorySpecV4):
|
|
schema_version: Literal[5] = 5
|
|
shots: list[StoryShotV5] = Field(min_length=1, max_length=1000)
|
|
dialogue: DialogueSpec = Field(default_factory=DialogueSpec)
|
|
|
|
@model_validator(mode="after")
|
|
def check_dialogue(self):
|
|
d = self.dialogue
|
|
speakers = {s.id: s for s in d.speakers}
|
|
people = {e.id for e in self.entities if e.kind == "person"}
|
|
if any(s.entity_id and s.entity_id not in people for s in d.speakers):
|
|
raise ValueError("对白人物引用无效")
|
|
ids = [x.id for x in [*d.speakers, *d.utterances, *d.sequences]]
|
|
occupied = {x.id for x in [*self.shots, *self.entities, *self.scenes]}
|
|
occupied.update(c.id for shot in self.shots for c in shot.cast)
|
|
occupied.update(v.id for entity in self.entities for v in entity.forms + entity.appearances)
|
|
if len(set(ids)) != len(ids) or occupied.intersection(ids):
|
|
raise ValueError("duplicate dialogue id")
|
|
for u in d.utterances:
|
|
if u.speaker_id not in speakers:
|
|
raise ValueError("对白声音引用无效")
|
|
if (
|
|
u.source == "tts"
|
|
and d.generation != "native_av"
|
|
and u.delivery
|
|
and speakers[u.speaker_id].voice.provider == "kokoro"
|
|
):
|
|
raise ValueError("Kokoro 不支持表演指令")
|
|
ordered = [s.id for s in self.shots]
|
|
assigned = {}
|
|
lines = []
|
|
by_id = {s.id: s for s in self.shots}
|
|
for seq in d.sequences:
|
|
if seq.shot_ids[0] not in by_id:
|
|
raise ValueError("对白镜头不存在")
|
|
start = ordered.index(seq.shot_ids[0])
|
|
if seq.shot_ids != ordered[start : start + len(seq.shot_ids)]:
|
|
raise ValueError("对白段落需要依次引用连续镜头")
|
|
for sid in seq.shot_ids:
|
|
if sid in assigned or seq.scene_id and by_id[sid].scene_id != seq.scene_id:
|
|
raise ValueError("对白段落镜头引用冲突")
|
|
assigned[sid] = seq.id
|
|
lines.extend(seq.utterance_ids)
|
|
if sorted(lines) != sorted(u.id for u in d.utterances):
|
|
raise ValueError("每句对白必须且只能属于一个段落")
|
|
for shot in self.shots:
|
|
p = shot.performance
|
|
cast = {c.entity_id for c in shot.cast}
|
|
if p.sequence_id != assigned.get(shot.id):
|
|
raise ValueError("镜头引用的对白段落不一致")
|
|
if p.native_utterance_ids is not None:
|
|
sequence = next((seq for seq in d.sequences if seq.id == p.sequence_id), None)
|
|
if len(set(p.native_utterance_ids)) != len(p.native_utterance_ids) or any(uid not in (sequence.utterance_ids if sequence else []) for uid in p.native_utterance_ids):
|
|
raise ValueError("镜头原生台词必须唯一引用本对白段落")
|
|
if len(set(p.visible_speaker_ids)) != len(p.visible_speaker_ids) or any(
|
|
sid not in speakers or speakers[sid].entity_id not in cast
|
|
for sid in p.visible_speaker_ids
|
|
):
|
|
raise ValueError("画内角色必须出现在镜头演员表中")
|
|
return self
|
|
|
|
|
|
class DialogueSpeakerV6(DialogueSpeaker):
|
|
model_speaker_number: int | None = Field(
|
|
default=None, strict=True, ge=1, le=1000, exclude_if=lambda x: x is None
|
|
)
|
|
face_reference_asset_id: StableId | None = Field(default=None, exclude_if=lambda x: x is None)
|
|
voice_reference_asset_id: StableId | None = Field(default=None, exclude_if=lambda x: x is None)
|
|
|
|
|
|
class DialogueSpecV6(DialogueSpec):
|
|
generation: Literal["native_av"] = "native_av"
|
|
speakers: list[DialogueSpeakerV6] = Field(default_factory=list, max_length=1000)
|
|
|
|
|
|
class ShotPerformanceV6(ShotPerformance):
|
|
dialogue_staging: Literal["two_person_turns"] | None = Field(
|
|
default=None, exclude_if=lambda x: x is None
|
|
)
|
|
first_frame_sha256: str | None = Field(
|
|
default=None, pattern=r"^[0-9a-f]{64}$", exclude_if=lambda x: x is None
|
|
)
|
|
listener_reactions: dict[StableId, Annotated[str, Field(max_length=500)]] = Field(
|
|
default_factory=dict, max_length=1000, exclude_if=lambda x: not x
|
|
)
|
|
|
|
|
|
class StoryShotV6(StoryShotV5):
|
|
performance: ShotPerformanceV6 = Field(default_factory=ShotPerformanceV6)
|
|
|
|
|
|
class StorySpecV6(StorySpecV5):
|
|
schema_version: Literal[6] = 6
|
|
shots: list[StoryShotV6] = Field(min_length=1, max_length=1000)
|
|
dialogue: DialogueSpecV6 = Field(default_factory=DialogueSpecV6)
|
|
|
|
@model_validator(mode="after")
|
|
def check_turn_authoring(self):
|
|
numbers = [
|
|
sp.model_speaker_number
|
|
for sp in self.dialogue.speakers
|
|
if sp.model_speaker_number is not None
|
|
]
|
|
if len(numbers) != len(set(numbers)):
|
|
raise ValueError("角色模型编号必须唯一")
|
|
for shot in self.shots:
|
|
p = shot.performance
|
|
if set(p.listener_reactions).difference(p.native_utterance_ids or []):
|
|
raise ValueError("听者动作必须引用本镜台词")
|
|
return self
|
|
|
|
|
|
def _spec(raw):
|
|
if hasattr(raw, "model_dump"):
|
|
raw = raw.model_dump(mode="json")
|
|
return raw.get("spec", raw)
|
|
|
|
|
|
def has_dialogue(raw):
|
|
spec = _spec(raw)
|
|
return spec.get("schema_version") in (5, 6) and spec.get("dialogue", {}).get("enabled", True)
|
|
|
|
|
|
def has_continuity(raw):
|
|
spec = _spec(raw)
|
|
return supports_sample_timing(spec) and any(
|
|
s.get("continuity", {}).get("transition") == "continue"
|
|
or s.get("continuity", {}).get("endpoint_mode") == "first_last_frame"
|
|
for s in spec.get("shots", [])
|
|
)
|
|
|
|
|
|
def speech_stem_id(shot_id, speaker_id):
|
|
return uuid5(NAMESPACE_URL, f"cmvr:dialogue:stem:{shot_id}:{speaker_id}").hex
|
|
|
|
|
|
def _child_id(parent, role, index):
|
|
return uuid5(NAMESPACE_URL, f"cmvr:dialogue:{role}:{parent}:{index}").hex
|
|
|
|
|
|
def upgrade_dialogue_manifest(manifest):
|
|
from app.domain.editors import validate_manifest
|
|
|
|
m = validate_manifest(manifest)
|
|
if m["source_kind"] != "story":
|
|
raise ValueError("仅故事支持对白")
|
|
if m["schema_version"] in (3, 4) and m["spec"].get("schema_version") in (5, 6):
|
|
return m
|
|
speakers = [
|
|
dict(id=_child_id(e["id"], "speaker", 0), entity_id=e["id"], name=e["name"] or "角色")
|
|
for e in m["spec"]["entities"]
|
|
if e["kind"] == "person"
|
|
]
|
|
by_entity = {s["entity_id"]: s["id"] for s in speakers}
|
|
m["audio"]["segments"] = [
|
|
seg
|
|
for seg in m["audio"]["segments"]
|
|
if seg["text"].strip()
|
|
or "audio:" + seg["id"] in m["bindings"]
|
|
or any(c.get("segment_id") == seg["id"] for c in m["captions"]["cues"])
|
|
]
|
|
sequences = []
|
|
for shot in m["spec"]["shots"]:
|
|
sid = shot["id"]
|
|
seq = _child_id(sid, "sequence", 0)
|
|
sequences.append(dict(id=seq, scene_id=shot["scene_id"], shot_ids=[sid]))
|
|
visible = list(
|
|
dict.fromkeys(
|
|
by_entity[c["entity_id"]] for c in shot["cast"] if c["entity_id"] in by_entity
|
|
)
|
|
)
|
|
shot["performance"] = dict(
|
|
sequence_id=seq, visible_speaker_ids=visible if len(visible) <= 2 else []
|
|
)
|
|
m.update(schema_version=max(3,m["schema_version"]))
|
|
m["spec"].update(schema_version=5, dialogue=dict(generation="native_av", language="Chinese", sequences=sequences, speakers=speakers))
|
|
if m["audio"]["mode"] == "manual_track":
|
|
m["audio"]["mix_mode"] = "manual_mix"
|
|
return validate_manifest(m)
|
|
|
|
|
|
def speech_content_hash(utterance, voice, capabilities):
|
|
u = utterance
|
|
if hasattr(u, "model_dump"):
|
|
u = u.model_dump(mode="json")
|
|
v = DialogueVoice.model_validate(voice).model_dump(mode="json")
|
|
if u.get("source") == "asset":
|
|
aid = u["asset_id"]
|
|
return digest(dict(asset_id=aid, sha=capabilities.get("reference_shas", {}).get(aid)))
|
|
if v["provider"] == "kokoro":
|
|
v.pop("seed", None)
|
|
v.pop("reference_asset_id", None)
|
|
return digest(
|
|
dict(
|
|
text=u.get("spoken_text") or u["text"],
|
|
voice=v,
|
|
delivery=u.get("delivery", ""),
|
|
adapter=capabilities.get("adapter_versions", {}).get(v["provider"]),
|
|
reference_sha=capabilities.get("reference_shas", {}).get(v.get("reference_asset_id")),
|
|
)
|
|
)
|
|
|
|
|
|
def _ceil_div(n, d):
|
|
return -(-n // d)
|
|
|
|
|
|
def _allocate(total, weights, floors):
|
|
"""用累计端点分配整数帧,并保留所有镜头的最小有效区间。"""
|
|
extra = max(0, total - sum(floors))
|
|
weights = [max(0, w - f) for w, f in zip(weights, floors)]
|
|
if not any(weights):
|
|
weights = [1] * len(weights)
|
|
denominator = sum(weights)
|
|
allocated = cursor = 0
|
|
result = []
|
|
for floor, weight in zip(floors, weights):
|
|
cursor += weight
|
|
endpoint = (extra * cursor + denominator // 2) // denominator
|
|
result.append(floor + endpoint - allocated)
|
|
allocated = endpoint
|
|
return result
|
|
|
|
|
|
def _capacity(shot, caps):
|
|
profile = profile_name(shot["video_parameters"])
|
|
max_source = constraints(profile)["num_frames"]["max"]
|
|
if profile != H3_V2_PROFILE:
|
|
max_source = (max_source // 24) * 24
|
|
return min(max_source, 360, caps.get("max_clip_frames", 360))
|
|
|
|
|
|
def _resize_clip(shot, frames):
|
|
shot["edit"]["duration_frames"] = frames
|
|
required = shot["edit"]["start_frame"] + frames
|
|
p = shot["video_parameters"]
|
|
if "source_frames" in p:
|
|
p["source_frames"] = max(
|
|
p["source_frames"], 124 + 17 * _ceil_div(max(0, required - 124), 17)
|
|
)
|
|
else:
|
|
p["source_seconds"] = max(p["source_seconds"], _ceil_div(required, 24))
|
|
|
|
|
|
def _fresh_id(parent, role, index, occupied):
|
|
while True:
|
|
child = _child_id(parent, role, index)
|
|
if child not in occupied:
|
|
occupied.add(child)
|
|
return child
|
|
index += 1
|
|
|
|
|
|
def _plan_sequence(shots, required, seq, manifest, caps, occupied, issue):
|
|
fixed = {}
|
|
weights = []
|
|
floors = []
|
|
for i, shot in enumerate(shots):
|
|
sid = shot["id"]
|
|
p = shot["performance"]
|
|
edit = shot["edit"]
|
|
q = edit["dedup_frames"]
|
|
locked = any(
|
|
manifest["bindings"].get(f"{role}:{sid}", {}).get("locked")
|
|
for role in ("video", "base_video", "selected_video", "synced_video")
|
|
)
|
|
if locked or seq["timing_mode"] == "fixed" or p["duration_mode"] == "fixed":
|
|
fixed[i] = edit["duration_frames"] - q
|
|
else:
|
|
weights.append(edit["duration_frames"] - q)
|
|
floors.append(24 - q)
|
|
remaining = required - sum(fixed.values())
|
|
if not weights and remaining > 0:
|
|
issue("dialogue_duration_conflict", seq["id"], "已锁定时长不足以容纳完整对白")
|
|
return {}
|
|
sizes = iter(_allocate(remaining, weights, floors) if weights else [])
|
|
children = {}
|
|
for i, shot in enumerate(shots):
|
|
sid = shot["id"]
|
|
children[sid] = [shot]
|
|
if i in fixed:
|
|
continue
|
|
frames = next(sizes) + shot["edit"]["dedup_frames"]
|
|
cap = _capacity(shot, caps)
|
|
first_cap = cap - shot["edit"]["start_frame"]
|
|
count = 1 + _ceil_div(max(0, frames - first_cap), max(1, cap))
|
|
if first_cap < 24 or cap < 24 or count > min(caps.get("max_shots", 60), 60):
|
|
issue("dialogue_clip_limit", sid, "镜头超出可生成区间")
|
|
continue
|
|
if count > 1 and (
|
|
shot["performance"]["structure_locked"]
|
|
or shot["continuity"]["transition"] == "continue"
|
|
or shot["continuity"]["endpoint_mode"] == "first_last_frame"
|
|
):
|
|
issue("dialogue_structure_conflict", sid, "需要拆镜,当前结构已锁或包含连续性约束")
|
|
continue
|
|
if count == 1:
|
|
_resize_clip(shot, frames)
|
|
continue
|
|
durations = _allocate(frames, [1] * count, [24] * count)
|
|
overflow = max(0, durations[0] - first_cap)
|
|
durations[0] -= overflow
|
|
for j in range(1, count):
|
|
add = min(overflow, cap - durations[j])
|
|
durations[j] += add
|
|
overflow -= add
|
|
for j, duration in enumerate(durations):
|
|
clip = deepcopy(shot) if j else shot
|
|
if j:
|
|
clip["id"] = _fresh_id(sid, "shot", j, occupied)
|
|
for cast in clip["cast"]:
|
|
cast["id"] = _fresh_id(cast["id"], "cast", j, occupied)
|
|
clip["continuity"]["transition"] = "cut"
|
|
clip["edit"].update(start_frame=0, dedup_frames=0)
|
|
children[sid].append(clip)
|
|
_resize_clip(clip, duration)
|
|
return children
|
|
|
|
|
|
def _project_shot_anchors(m, groups, indexed, issue):
|
|
"""拆镜后用父镜头的贡献帧坐标迁移字幕和音频锚点。"""
|
|
|
|
def intervals(sid):
|
|
cursor = 0
|
|
for shot in groups[sid]:
|
|
frames = indexed[shot["id"]]["contribution_frames"]
|
|
yield shot["id"], cursor, cursor + frames
|
|
cursor += frames
|
|
|
|
cues = []
|
|
cue_ids = {c["id"] for c in m["captions"]["cues"]}
|
|
for cue in m["captions"]["cues"]:
|
|
sid = cue.get("shot_id")
|
|
if cue["anchor"] != "shot" or sid not in groups or len(groups[sid]) == 1:
|
|
cues.append(cue)
|
|
continue
|
|
start, end = cue["start_frame"], cue["end_frame"]
|
|
spans = list(intervals(sid))
|
|
if start < 0 or start >= end or end > spans[-1][2]:
|
|
issue("relative_anchor_conflict", cue["id"], "字幕超出拆镜后的区间")
|
|
cues.append(cue)
|
|
continue
|
|
count = 0
|
|
for child, a, b in spans:
|
|
if max(a, start) < min(b, end):
|
|
cid = _fresh_id(cue["id"], "cue", count, cue_ids) if count else cue["id"]
|
|
cues.append(
|
|
dict(
|
|
cue,
|
|
id=cid,
|
|
shot_id=child,
|
|
start_frame=max(a, start) - a,
|
|
end_frame=min(b, end) - a,
|
|
)
|
|
)
|
|
count += 1
|
|
if len(cues) <= 1000:
|
|
m["captions"]["cues"] = cues
|
|
else:
|
|
issue("caption_limit", "captions", "拆镜后的字幕超过数量上限")
|
|
for item in m["audio"]["layers"] + m["audio"]["segments"]:
|
|
sid = item.get("shot_id")
|
|
if item["anchor"] != "shot" or sid not in groups or len(groups[sid]) == 1:
|
|
continue
|
|
pos = item["offset_sample"]
|
|
for child, a, b in intervals(sid):
|
|
if a * SAMPLES_PER_FRAME <= pos < b * SAMPLES_PER_FRAME:
|
|
item.update(shot_id=child, offset_sample=pos - a * SAMPLES_PER_FRAME)
|
|
break
|
|
else:
|
|
issue("relative_anchor_conflict", item["id"], "音频偏移超出拆镜后的区间")
|
|
|
|
|
|
def prepare_dialogue(manifest, speech_bindings, capabilities):
|
|
from app.domain.editors import editor_issues, validate_manifest
|
|
|
|
m = validate_manifest(manifest)
|
|
if m["schema_version"] not in (3, 4):
|
|
raise ValueError("对白准备要求 V3 编辑清单")
|
|
spec = m["spec"]
|
|
d = spec["dialogue"]
|
|
speakers = {s["id"]: s for s in d["speakers"]}
|
|
lines = {u["id"]: u for u in d["utterances"]}
|
|
by_id = {s["id"]: s for s in spec["shots"]}
|
|
groups = {sid: [s] for sid, s in by_id.items()}
|
|
issues = []
|
|
|
|
def issue(code, uid, message):
|
|
issues.append(dict(code=code, unit_id=uid, message=message))
|
|
|
|
measured = {}
|
|
old_timing = compile_story_timing(spec)
|
|
order = {sid: i for i, sid in enumerate(m["shot_ids"])}
|
|
sequences = sorted(d["sequences"], key=lambda item: order[item["shot_ids"][0]])
|
|
previous_end = -1
|
|
remainder = 0
|
|
planned_count = len(by_id)
|
|
occupied = {
|
|
s["id"]
|
|
for collection in (
|
|
spec["entities"],
|
|
spec["scenes"],
|
|
spec["shots"],
|
|
d["utterances"],
|
|
d["speakers"],
|
|
d["sequences"],
|
|
)
|
|
for s in collection
|
|
}
|
|
occupied.update(c["id"] for shot in spec["shots"] for c in shot["cast"])
|
|
occupied.update(v["id"] for e in spec["entities"] for v in e["forms"] + e["appearances"])
|
|
for seq in sequences if d["enabled"] else []:
|
|
if "sequence_ids" in capabilities and seq["id"] not in capabilities["sequence_ids"]:
|
|
continue
|
|
# 相邻自动段落共用样本原点;保留端点量化余数,防止每段累计漂移。
|
|
if order[seq["shot_ids"][0]] != previous_end or seq["timing_mode"] != "auto":
|
|
remainder = 0
|
|
previous_end = -1
|
|
offset = 9600 + remainder
|
|
if not seq["utterance_ids"]:
|
|
continue
|
|
for pos, uid in enumerate(seq["utterance_ids"]):
|
|
u = lines[uid]
|
|
b = speech_bindings.get("normalized_speech:" + uid) or speech_bindings.get(uid) or {}
|
|
count = b.get("sample_count")
|
|
start = u["source_start_sample"]
|
|
if (
|
|
type(count) is not int
|
|
or count <= 0
|
|
or b.get("sample_rate", 48000) != 48000
|
|
or not b.get("asset_id")
|
|
):
|
|
issue("missing_normalized_speech", uid, "缺少48k实测音频")
|
|
continue
|
|
end = u["source_end_sample"] or count
|
|
if end > count or start >= end:
|
|
issue("invalid_speech_interval", uid, "选用范围超出实测音频")
|
|
continue
|
|
measured[uid] = dict(
|
|
utterance_id=uid,
|
|
sequence_id=seq["id"],
|
|
speaker_id=u["speaker_id"],
|
|
asset_id=b["asset_id"],
|
|
source_start_sample=start,
|
|
source_end_sample=end,
|
|
start_sample=offset,
|
|
end_sample=offset + end - start,
|
|
content_hash=speech_content_hash(
|
|
u, speakers[u["speaker_id"]]["voice"], capabilities
|
|
),
|
|
)
|
|
offset += end - start
|
|
if pos < len(seq["utterance_ids"]) - 1:
|
|
offset += u["gap_after_sample"]
|
|
if all(uid in measured for uid in seq["utterance_ids"]):
|
|
children = _plan_sequence(
|
|
[deepcopy(by_id[sid]) for sid in seq["shot_ids"]],
|
|
_ceil_div(offset + 14400, SAMPLES_PER_FRAME),
|
|
seq,
|
|
m,
|
|
capabilities,
|
|
occupied,
|
|
issue,
|
|
)
|
|
planned_count += sum(len(group) - 1 for group in children.values())
|
|
if planned_count > min(
|
|
60, m["production"]["max_shots"], capabilities.get("max_shots", 60)
|
|
):
|
|
issue("dialogue_budget_exceeded", seq["id"], "拆镜将超过镜头数上限")
|
|
continue
|
|
groups.update(children)
|
|
used_frames = sum(
|
|
shot["edit"]["duration_frames"] - shot["edit"]["dedup_frames"]
|
|
for sid in seq["shot_ids"]
|
|
for shot in groups[sid]
|
|
)
|
|
remainder = offset + 14400 - used_frames * SAMPLES_PER_FRAME
|
|
if -SAMPLES_PER_FRAME < remainder <= 0 and seq["timing_mode"] == "auto":
|
|
previous_end = order[seq["shot_ids"][-1]] + 1
|
|
seq["shot_ids"] = [s["id"] for sid in seq["shot_ids"] for s in groups[sid]]
|
|
spec["shots"] = [shot for group in groups.values() for shot in group]
|
|
spec["render"]["total_frames"] = None
|
|
m["shot_ids"] = [s["id"] for s in spec["shots"]]
|
|
timing = compile_story_timing(spec)
|
|
spec["render"]["total_frames"] = timing["total_frames"]
|
|
if len(spec["shots"]) > min(
|
|
60, m["production"]["max_shots"], capabilities.get("max_shots", 60)
|
|
) or timing["total_frames"] > min(
|
|
7200, m["production"]["max_total_frames"], capabilities.get("max_total_frames", 7200)
|
|
):
|
|
issue("dialogue_budget_exceeded", "production", "准备结果超过镜头或总帧数预算")
|
|
if len(measured) + len(m["audio"]["layers"]) + len(m["audio"]["segments"]) > 128:
|
|
issue("dialogue_mix_limit", "audio", "混音超过128段")
|
|
indexed = {r["shot_id"]: r for r in timing["shots"]}
|
|
_project_shot_anchors(m, groups, indexed, issue)
|
|
performance = {s["id"]: s["performance"] for s in spec["shots"]}
|
|
placements = []
|
|
utterances = []
|
|
for seq in sorted(d["sequences"], key=lambda seq: indexed[seq["shot_ids"][0]]["start_frame"]):
|
|
seq_start = indexed[seq["shot_ids"][0]]["start_frame"] * SAMPLES_PER_FRAME
|
|
for uid in seq["utterance_ids"]:
|
|
if uid not in measured:
|
|
continue
|
|
line = measured[uid]
|
|
line["start_sample"] += seq_start
|
|
line["end_sample"] += seq_start
|
|
line["placement_hash"] = digest(
|
|
{
|
|
k: line[k]
|
|
for k in (
|
|
"utterance_id",
|
|
"sequence_id",
|
|
"start_sample",
|
|
"end_sample",
|
|
"source_start_sample",
|
|
"source_end_sample",
|
|
)
|
|
}
|
|
)
|
|
utterances.append(line)
|
|
for sid in seq["shot_ids"]:
|
|
r = indexed[sid]
|
|
origin = r["start_frame"] * SAMPLES_PER_FRAME
|
|
a = max(origin, line["start_sample"])
|
|
z = min(r["end_frame"] * SAMPLES_PER_FRAME, line["end_sample"])
|
|
if z <= a:
|
|
continue
|
|
source = line["source_start_sample"] + a - line["start_sample"]
|
|
placements.append(
|
|
dict(
|
|
shot_id=sid,
|
|
utterance_id=uid,
|
|
speaker_id=line["speaker_id"],
|
|
start_sample=a,
|
|
end_sample=z,
|
|
shot_start_sample=a - origin,
|
|
shot_end_sample=z - origin,
|
|
source_start_sample=source,
|
|
source_end_sample=source + z - a,
|
|
visible=line["speaker_id"] in performance[sid]["visible_speaker_ids"],
|
|
)
|
|
)
|
|
parents = {s["id"]: parent for parent, group in groups.items() for s in group}
|
|
|
|
def owner(rows, sample):
|
|
return next(
|
|
(
|
|
parents[r["shot_id"]]
|
|
for r in rows
|
|
if r["start_frame"] * SAMPLES_PER_FRAME
|
|
<= sample
|
|
< r["end_frame"] * SAMPLES_PER_FRAME
|
|
),
|
|
None,
|
|
)
|
|
|
|
def absolute_check(uid, start, end):
|
|
if end > timing["total_frames"] * SAMPLES_PER_FRAME or any(
|
|
owner(old_timing["shots"], pos) != owner(timing["shots"], pos)
|
|
for pos in (start, max(start, end - 1))
|
|
):
|
|
issue("absolute_anchor_conflict", uid, "时长调整与绝对时间锚点冲突")
|
|
|
|
for c in m["captions"]["cues"]:
|
|
if c["anchor"] == "absolute":
|
|
absolute_check(
|
|
c["id"], c["start_frame"] * SAMPLES_PER_FRAME, c["end_frame"] * SAMPLES_PER_FRAME
|
|
)
|
|
elif (
|
|
c["anchor"] == "utterance"
|
|
and c["utterance_id"] in measured
|
|
and (c.get("timing_override") or m["captions"]["mode"] == "manual")
|
|
):
|
|
line = measured[c["utterance_id"]]
|
|
if c["end_frame"] > _ceil_div(
|
|
line["end_sample"] - line["start_sample"], SAMPLES_PER_FRAME
|
|
):
|
|
issue("invalid_timeline", c["id"], "字幕超出实测台词时间")
|
|
for layer in m["audio"]["layers"] + m["audio"]["segments"]:
|
|
if layer["anchor"] == "absolute":
|
|
start = layer["offset_sample"]
|
|
end = layer["source_end_sample"]
|
|
absolute_check(
|
|
layer["id"], start, start + (end - layer["source_start_sample"] if end else 1)
|
|
)
|
|
issues.extend(editor_issues(m))
|
|
return dict(
|
|
effective_manifest=m,
|
|
timing=timing,
|
|
utterances=utterances,
|
|
placements=placements,
|
|
provenance=dict(
|
|
shot_children={sid: [s["id"] for s in group] for sid, group in groups.items()}
|
|
),
|
|
issues=issues,
|
|
)
|