Skip to content

PRINTFILM: AI short-video marketing and AI short-drama creation platform

Fix Seedance portrait i2v ratio and episode compose codec mismatch.

yia99a7de7b60c
diff --git a/backend/app/api/drama/episodes.py b/backend/app/api/drama/episodes.py
index 769539e..0f9f9c1 100644
--- a/backend/app/api/drama/episodes.py
+++ b/backend/app/api/drama/episodes.py
@@ -17,6 +17,7 @@ from app.models import User
from app.models_drama import DramaEpisode, DramaEpisodeFragment, DramaFragmentAssetRef
from app.schemas_drama import (
DramaActivateVideoVersionRequest,
+ DramaComposeEpisodeRequest,
DramaEpisodeOut,
DramaEpisodeUpdate,
DramaFragmentOut,
@@ -615,6 +616,37 @@ async def generate_status(
}
[email protected]("/episodes/{episode_id}/compose")
+async def compose_episode(
+ episode_id: int,
+ body: DramaComposeEpisodeRequest | None = None,
+ db: AsyncSession = Depends(get_db),
+ user: User = Depends(get_current_user),
+) -> dict:
+ """统一画幅重编码后拼接本集分镜,供浏览器无损失败时回退。"""
+ from app.services.drama.episode_compose import compose_episode_video, load_episode_for_compose
+
+ ep = await get_owned_episode(db, episode_id, user)
+ project = await get_owned_drama_project(db, ep.project_id, user)
+ episode = await load_episode_for_compose(db, episode_id)
+ if episode is None:
+ raise HTTPException(status_code=404, detail="分集不存在")
+ req = body or DramaComposeEpisodeRequest()
+ try:
+ url = await compose_episode_video(
+ db,
+ episode=episode,
+ project=project,
+ fragment_ids=req.fragment_ids,
+ )
+ except RuntimeError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+ except Exception as exc: # noqa: BLE001
+ logger.exception("episode compose failed episode_id=%s", episode_id)
+ raise HTTPException(status_code=500, detail=f"全片合成失败:{exc}") from exc
+ return {"ok": True, "video_url": url, "episode_id": episode_id}
+
+
@router.post("/episodes/{episode_id}/cancel_generate")
async def cancel_generate_episode(
episode_id: int,
diff --git a/backend/app/schemas_drama.py b/backend/app/schemas_drama.py
index 2231ed3..278d6a1 100644
--- a/backend/app/schemas_drama.py
+++ b/backend/app/schemas_drama.py
@@ -249,6 +249,11 @@ class DramaGenerateRequest(BaseModel):
fragment_ids: list[int] | None = None
+class DramaComposeEpisodeRequest(BaseModel):
+ # fragment_ids 仅拼接指定分镜;None 表示本集全部已有视频的分镜
+ fragment_ids: list[int] | None = None
+
+
class DramaPlanFragmentsRequest(BaseModel):
# force 是否覆盖已有视频/手改分镜(单集 AI 重切默认 true)
force: bool = True
diff --git a/backend/app/services/ark.py b/backend/app/services/ark.py
index 026f047..9150233 100644
--- a/backend/app/services/ark.py
+++ b/backend/app/services/ark.py
@@ -20,6 +20,7 @@ from app.config import Settings, get_settings
from app.schemas_routing import ResolvedModelRoute
from app.services.logical_model_router import resolve_logical_model, resolve_logical_model_id
from app.services import storage
+from app.services.drama.seedance_i2v_role import resolve_seedance_i2v_image_role
from app.services.ffmpeg_compose import is_near_silent_audio
from app.services.llm_client import chat_completions
from app.services import seedance_segments as segplan
@@ -634,16 +635,17 @@ class ArkGateway:
if "@duration:" in plain or "00:" in plain or plain.startswith("【"):
text = plain
prompt_as_json = False
+ # 有目标画幅时用 reference_image + ratio(可强制 9:16)。
+ # 纯 first_frame 禁止传 ratio,且实测即使静帧竖屏也可能吐横屏。
+ image_role, target_ratio = resolve_seedance_i2v_image_role(ratio)
content: list[dict[str, Any]] = [
{"type": "text", "text": text},
{
"type": "image_url",
"image_url": {"url": image_ref},
- "role": "first_frame",
+ "role": image_role,
},
]
- # 首帧/首尾帧生视频:ratio 必须省略,输出比例跟随首帧图
- # (传 ratio 会报 InvalidParameter.TaskTypeConstraint)
route = self._resolve_ark_route("video", self.settings.model_video)
video_model = route.upstream_model if route else self.settings.model_video
body: dict[str, Any] = {
@@ -655,13 +657,16 @@ class ArkGateway:
"generate_audio": bool(generate_audio),
"return_last_frame": bool(return_last_frame),
}
+ if target_ratio:
+ body["ratio"] = target_ratio
# Do not send character_consistency — unknown fields have caused BodyFormat failures
logger.info(
- "Seedance i2v create model=%s duration=%s resolution=%s generate_audio=%s "
- "(ratio omitted for first_frame)",
+ "Seedance i2v create model=%s duration=%s resolution=%s ratio=%s role=%s generate_audio=%s",
body["model"],
body["duration"],
resolution,
+ body.get("ratio") or "(omit)",
+ image_role,
body["generate_audio"],
)
@@ -681,16 +686,20 @@ class ArkGateway:
)
if resp.status_code >= 400:
err_text = resp.text or ""
- # 若仍因 ratio 报错(兼容旧调用残留),显式去掉再试
- if "ratio" in err_text.lower() and "ratio" in body:
+ # 仅「误用 first_frame + ratio」时去掉 ratio;有目标画幅时不得回落到 adaptive 横屏
+ if (
+ not target_ratio
+ and "ratio" in err_text.lower()
+ and "ratio" in body
+ ):
body.pop("ratio", None)
resp = await client.post(
self._route_url("/contents/generations/tasks", route),
headers=self._route_headers(route),
json=body,
)
- if resp.status_code >= 400:
- # Last try: drop role(参考图模式,可按需带 adaptive)
+ if resp.status_code >= 400 and not target_ratio:
+ # 无目标画幅时的兼容回退;有竖屏目标时禁止 adaptive,避免再次出横屏
body["content"][1].pop("role", None)
body["ratio"] = "adaptive"
resp = await client.post(
diff --git a/backend/app/services/drama/episode_compose.py b/backend/app/services/drama/episode_compose.py
new file mode 100644
index 0000000..d53cd02
--- /dev/null
+++ b/backend/app/services/drama/episode_compose.py
@@ -0,0 +1,169 @@
+"""漫剧分集成片:统一画幅重编码后拼接(兼容各镜 HEVC 参数不一致)。"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+import tempfile
+from pathlib import Path
+
+from sqlalchemy.ext.asyncio import AsyncSession
+from sqlalchemy.orm import selectinload
+
+from app.models_drama import DramaEpisode, DramaProject
+from app.services import storage as storage_svc
+from app.services.drama.output_settings import resolve_episode_video_output, target_pixel_size
+from app.services.ffmpeg_compose import _run, _scale_pad, _which
+
+logger = logging.getLogger("app.drama.episode_compose")
+
+
+# 将单镜规范到目标分辨率(H.264 + AAC),便于后续 stream copy 拼接
+def _normalize_clip(src: Path, dest: Path, width: int, height: int) -> None:
+ ffmpeg = _which("ffmpeg")
+ vf = _scale_pad(width, height)
+ _run(
+ [
+ ffmpeg,
+ "-y",
+ "-i",
+ str(src),
+ "-vf",
+ vf,
+ "-c:v",
+ "libx264",
+ "-preset",
+ "veryfast",
+ "-crf",
+ "18",
+ "-pix_fmt",
+ "yuv420p",
+ "-c:a",
+ "aac",
+ "-ar",
+ "44100",
+ "-ac",
+ "2",
+ "-movflags",
+ "+faststart",
+ str(dest),
+ ]
+ )
+
+
+# 拼接已规范化的片段(stream copy)
+def _concat_normalized(paths: list[Path], output: Path) -> None:
+ ffmpeg = _which("ffmpeg")
+ with tempfile.TemporaryDirectory(prefix="drama_ep_concat_") as tmp:
+ tmp_path = Path(tmp)
+ concat_list = tmp_path / "concat.txt"
+ concat_list.write_text(
+ "\n".join(f"file '{p.resolve().as_posix()}'" for p in paths),
+ encoding="utf-8",
+ )
+ merged = tmp_path / "merged.mp4"
+ _run(
+ [
+ ffmpeg,
+ "-y",
+ "-f",
+ "concat",
+ "-safe",
+ "0",
+ "-i",
+ str(concat_list),
+ "-c",
+ "copy",
+ "-movflags",
+ "+faststart",
+ str(merged),
+ ]
+ )
+ output.parent.mkdir(parents=True, exist_ok=True)
+ output.write_bytes(merged.read_bytes())
+
+
+# 确保远程/本地视频落到可 ffmpeg 读取的本地路径
+async def _ensure_clip_local(url: str, cache_dir: Path, index: int) -> Path:
+ local = storage_svc.local_path_from_url(url)
+ if local is not None:
+ if not local.exists():
+ await storage_svc.ensure_local_media(url, local)
+ if local.exists() and local.stat().st_size > 0:
+ return local
+ dest = cache_dir / f"src_{index:03d}.mp4"
+ await storage_svc.ensure_local_media(url, dest)
+ if not dest.exists() or dest.stat().st_size <= 0:
+ raise RuntimeError(f"无法下载分镜视频:{url[:120]}")
+ return dest
+
+
+# 按分集设置统一重编码并拼接;返回可下载 URL
+async def compose_episode_video(
+ db: AsyncSession,
+ *,
+ episode: DramaEpisode,
+ project: DramaProject,
+ fragment_ids: list[int] | None = None,
+) -> str:
+ frags = sorted(episode.fragments or [], key=lambda f: f.sort_order)
+ if fragment_ids:
+ allow = {int(x) for x in fragment_ids}
+ frags = [f for f in frags if f.id in allow]
+ clips = [(f.id, (f.video or "").strip()) for f in frags if (f.video or "").strip()]
+ if not clips:
+ raise RuntimeError("本集还没有可拼接的分镜视频")
+
+ ratio, resolution = resolve_episode_video_output(episode.params, project.params)
+ width, height = target_pixel_size(ratio, resolution)
+
+ out_dir = storage_svc.project_dir(project.id)
+ out_path = out_dir / f"episode_{episode.id}_compose.mp4"
+
+ with tempfile.TemporaryDirectory(prefix=f"drama_ep_{episode.id}_") as tmp:
+ tmp_path = Path(tmp)
+ src_dir = tmp_path / "src"
+ norm_dir = tmp_path / "norm"
+ src_dir.mkdir()
+ norm_dir.mkdir()
+
+ local_srcs: list[Path] = []
+ for idx, (_fid, url) in enumerate(clips):
+ local_srcs.append(await _ensure_clip_local(url, src_dir, idx))
+
+ normalized: list[Path] = []
+ for idx, src in enumerate(local_srcs):
+ dest = norm_dir / f"seg_{idx:03d}.mp4"
+ await asyncio.to_thread(_normalize_clip, src, dest, width, height)
+ normalized.append(dest)
+
+ await asyncio.to_thread(_concat_normalized, normalized, out_path)
+
+ published = storage_svc.publish_local(out_path, sync=True)
+ if published and str(published).startswith(("http://", "https://", "/static/")):
+ url = str(published)
+ else:
+ rel = "/static/" + str(out_path.relative_to(storage_svc.STATIC_ROOT)).replace("\\", "/")
+ url = storage_svc.to_public_url(rel)
+ logger.info(
+ "episode compose done episode_id=%s clips=%s size=%sx%s url=%s",
+ episode.id,
+ len(clips),
+ width,
+ height,
+ url[:120],
+ )
+ return url
+
+
+# 加载分集(含 fragments)供合成
+async def load_episode_for_compose(db: AsyncSession, episode_id: int) -> DramaEpisode | None:
+ from sqlalchemy import select
+
+ return (
+ await db.execute(
+ select(DramaEpisode)
+ .where(DramaEpisode.id == episode_id)
+ .options(selectinload(DramaEpisode.fragments))
+ )
+ ).scalar_one_or_none()
diff --git a/backend/app/services/drama/generation.py b/backend/app/services/drama/generation.py
index aef0181..65a6bb2 100644
--- a/backend/app/services/drama/generation.py
+++ b/backend/app/services/drama/generation.py
@@ -1083,6 +1083,18 @@ async def prepare_fragment_video_for_submit(
episode.params if episode else None,
project.params,
)
+ # 分集未落库画幅时写入解析结果,避免 UI 默认 9:16 与 params 长期不一致
+ if episode is not None:
+ ep_params = dict(episode.params or {})
+ changed = False
+ if str(ep_params.get("aspect_ratio") or "").strip() not in {"9:16", "16:9", "1:1"}:
+ ep_params["aspect_ratio"] = ratio
+ changed = True
+ if str(ep_params.get("resolution") or "").strip() not in {"480p", "720p", "1080p"}:
+ ep_params["resolution"] = resolution
+ changed = True
+ if changed:
+ episode.params = ep_params
refs = (
await db.execute(
diff --git a/backend/app/services/drama/seedance_i2v_role.py b/backend/app/services/drama/seedance_i2v_role.py
new file mode 100644
index 0000000..d152620
--- /dev/null
+++ b/backend/app/services/drama/seedance_i2v_role.py
@@ -0,0 +1,11 @@
+"""Seedance i2v 图片角色:有目标画幅时用 reference_image 以便传 ratio。"""
+
+from __future__ import annotations
+
+
+# 解析 i2v 图片 role 与是否附带 ratio
+def resolve_seedance_i2v_image_role(ratio: str | None) -> tuple[str, str | None]:
+ target = (ratio or "").strip() or None
+ if target:
+ return "reference_image", target
+ return "first_frame", None
diff --git a/backend/tests/test_episode_compose_settings.py b/backend/tests/test_episode_compose_settings.py
new file mode 100644
index 0000000..c59b46b
--- /dev/null
+++ b/backend/tests/test_episode_compose_settings.py
@@ -0,0 +1,13 @@
+"""分集合成:目标像素与片段筛选。"""
+
+from app.services.drama.output_settings import target_pixel_size
+
+
+# 竖屏 1080p 目标尺寸
+def test_target_pixel_size_portrait_1080() -> None:
+ assert target_pixel_size("9:16", "1080p") == (1080, 1920)
+
+
+# 横屏 1080p 目标尺寸
+def test_target_pixel_size_landscape_1080() -> None:
+ assert target_pixel_size("16:9", "1080p") == (1920, 1080)
diff --git a/backend/tests/test_seedance_i2v_role.py b/backend/tests/test_seedance_i2v_role.py
new file mode 100644
index 0000000..f1475c3
--- /dev/null
+++ b/backend/tests/test_seedance_i2v_role.py
@@ -0,0 +1,20 @@
+"""Seedance i2v:有目标画幅时用 reference_image + ratio。"""
+
+from app.services.drama.seedance_i2v_role import resolve_seedance_i2v_image_role
+
+
+# 有 ratio 时不得走 first_frame(禁止传 ratio,且可能吐横屏)
+def test_i2v_role_with_target_ratio() -> None:
+ role, sent = resolve_seedance_i2v_image_role("9:16")
+ assert role == "reference_image"
+ assert sent == "9:16"
+
+
+# 无 ratio 时保持 first_frame 兼容
+def test_i2v_role_without_ratio() -> None:
+ role, sent = resolve_seedance_i2v_image_role(None)
+ assert role == "first_frame"
+ assert sent is None
+ role2, sent2 = resolve_seedance_i2v_image_role(" ")
+ assert role2 == "first_frame"
+ assert sent2 is None
diff --git a/docs/releases/2026-08-24.md b/docs/releases/2026-08-24.md
index 0349307..ec4b892 100644
--- a/docs/releases/2026-08-24.md
+++ b/docs/releases/2026-08-24.md
@@ -1,5 +1,35 @@
# 发布记录 · 2026-08-24
+## 2026-08-24 19:08 · 杭州 8.136.41.61 全量
+
+- **操作者**:Agent(按用户反馈全片合成失败)
+- **方式**:`deploy/scripts/deploy_kepu_8136.py` 全量
+- **范围**:frontend / admin / api
+- **变更摘要**:
+ - 浏览器无损拼接遇 HEVC 参数不一致(hvcC)时,自动回退服务端 ffmpeg:统一缩放到分集画幅后 H.264 拼接下载
+ - 新增 `POST /api/drama/episodes/{id}/compose`
+- **验证**:
+ - [x] 脚本 `DONE`;health 200;首页 200
+ - [ ] 业务:分集页再点「全片合成下载」,编码不一致时应自动走「服务端统一重编码拼接」
+- **备注 / 回滚**:
+ - 未改 nginx / 证书 / 中间件容器
+
+## 2026-08-24 18:59 · 杭州 8.136.41.61 全量
+
+- **操作者**:Agent(按用户要求全量发布)
+- **方式**:`deploy/scripts/deploy_kepu_8136.py` 全量(未设 SETUP_NGINX / SETUP_TLS / SETUP_INFRA)
+- **范围**:frontend / admin / api
+- **变更摘要**:
+ - i2v 有目标画幅时改用 `reference_image` + 显式 `ratio`(避免 first_frame 静帧竖屏仍吐横屏)
+ - 生成队列:进行中点详情只看进度,不再挖历史「跳过重复任务」当当前失败
+- **验证**:
+ - [x] 脚本 `DONE`(约 0.9 min);`ai-movie-api` active;health 200;poller running
+ - [x] Host `kepu.printtfilm.com` / `admin.kepu.printtfilm.com` 首页 200(`Last-Modified: Mon, 24 Aug 2026 10:58 GMT`)
+ - [ ] 业务冒烟:片段 18 需再重新生成确认竖屏
+- **备注 / 回滚**:
+ - 未改 nginx / 证书 / Postgres·Redis 容器
+ - 回滚上一包并 `systemctl restart ai-movie-api`
+
## 2026-08-24 18:38 · 杭州 8.136.41.61 全量
- **操作者**:Agent(按用户要求全量发布)
diff --git a/docs/releases/README.md b/docs/releases/README.md
index ada0d39..fe76425 100644
--- a/docs/releases/README.md
+++ b/docs/releases/README.md
@@ -33,6 +33,8 @@
| 日期 | 摘要 | 文件 |
|------|------|------|
+| 2026-08-24 | 全片合成 HEVC 不一致回退服务端拼接;杭州全量 | [2026-08-24.md](./2026-08-24.md) |
+| 2026-08-24 | i2v 强制 ratio + 队列详情不误显旧错;杭州全量 | [2026-08-24.md](./2026-08-24.md) |
| 2026-08-24 | 分镜 i2v 画幅跟首帧导致横屏;杭州全量 | [2026-08-24.md](./2026-08-24.md) |
| 2026-08-24 | 重新生成误跳过修复;杭州全量 | [2026-08-24.md](./2026-08-24.md) |
| 2026-08-21 | 队列错误中文化+任务详情;杭州全量 | [2026-08-21.md](./2026-08-21.md) |
diff --git a/frontend/src/api/drama.ts b/frontend/src/api/drama.ts
index ce58ba1..fc2501b 100644
--- a/frontend/src/api/drama.ts
+++ b/frontend/src/api/drama.ts
@@ -408,6 +408,16 @@ export const dramaApi = {
fragments: Array<{ fragment_id: number; status: string; video?: string; cover?: string }>
}>(`/api/drama/episodes/${episodeId}/generate_status`),
+ /** 服务端统一重编码拼接本集(浏览器无损失败时回退) */
+ composeEpisode: (episodeId: number, fragmentIds?: number[]) =>
+ request<{ ok: boolean; video_url: string; episode_id: number }>(
+ `/api/drama/episodes/${episodeId}/compose`,
+ {
+ method: 'POST',
+ body: JSON.stringify({ fragment_ids: fragmentIds }),
+ },
+ ),
+
cancelEpisodeGenerate: (episodeId: number) =>
request<{ ok: boolean; episode_id: number; fragments: number }>(
`/api/drama/episodes/${episodeId}/cancel_generate`,
diff --git a/frontend/src/components/drama/DramaGenTaskDetail.tsx b/frontend/src/components/drama/DramaGenTaskDetail.tsx
index 656e237..5703fcc 100644
--- a/frontend/src/components/drama/DramaGenTaskDetail.tsx
+++ b/frontend/src/components/drama/DramaGenTaskDetail.tsx
@@ -1,4 +1,4 @@
-/** 生成失败原因:只展示可读错误,不展示队列/平台任务状态 */
+/** 生成队列任务详情:进行中看进度,失败才挖根因 */
import { useEffect, useState } from 'react'
import { Loader2, X } from 'lucide-react'
import { tasksApi, type TaskRunOut } from '../../api/tasks'
@@ -10,6 +10,13 @@ type Props = {
onClose: () => void
}
+const STATUS_LABEL: Record<DramaGenJob['status'], string> = {
+ queued: '排队中',
+ running: '生成中',
+ done: '已完成',
+ failed: '失败',
+}
+
// 拉取该目标相关的多条历史任务(用于挖出被「重试超限」覆盖的根因)
async function listRelatedTasks(job: DramaGenJob): Promise<TaskRunOut[]> {
if (job.kind === 'video' && job.targetId > 0) {
@@ -44,13 +51,30 @@ async function listRelatedTasks(job: DramaGenJob): Promise<TaskRunOut[]> {
return []
}
-// 失败原因抽屉(错误文案为主)
+// 进行中任务的进度说明
+function activeJobHint(job: DramaGenJob): string {
+ if (job.message?.trim()) return job.message.trim()
+ if (job.status === 'queued') return '任务已入队,等待调度器领取。'
+ if (job.kind === 'video') return '正在生成分镜视频,完成后会自动更新封面与成片。'
+ return '正在生成图片,完成后会自动写回资产。'
+}
+
+// 任务详情抽屉(进行中=进度;失败=错误文案)
export function DramaGenTaskDetail({ job, onClose }: Props) {
- const [loading, setLoading] = useState(true)
+ const isFailed = job.status === 'failed'
+ const isActive = job.status === 'queued' || job.status === 'running'
+ const [loading, setLoading] = useState(isFailed)
const [rawError, setRawError] = useState(job.error || '')
const [showRaw, setShowRaw] = useState(false)
useEffect(() => {
+ // 非失败任务不挖历史错误,避免把旧的「跳过重复任务」当成当前失败
+ if (!isFailed) {
+ setRawError('')
+ setLoading(false)
+ return
+ }
+
let cancelled = false
setRawError(job.error || '')
setLoading(true)
@@ -60,13 +84,29 @@ export function DramaGenTaskDetail({ job, onClose }: Props) {
if (cancelled) return
const candidates: Array<string | null | undefined> = [job.error]
for (const task of tasks) {
+ // 优先当前 job 绑定的任务;历史 cancelled「跳过重复」不当作根因抢占
+ if (job.taskId && task.id === job.taskId) {
+ candidates.unshift(task.error_message)
+ continue
+ }
+ if (
+ task.status === 'cancelled' &&
+ /跳过重复任务|分镜已生成完成/.test(String(task.error_message || ''))
+ ) {
+ continue
+ }
candidates.push(task.error_message)
}
let best = pickRootDramaGenError(candidates)
- // list 无 events 时,若仍是包装句再拉几条详情
if (!best || /重试超过|超过上限/.test(best)) {
for (const task of tasks.slice(0, 5)) {
if (!task.id) continue
+ if (
+ task.status === 'cancelled' &&
+ /跳过重复任务|分镜已生成完成/.test(String(task.error_message || ''))
+ ) {
+ continue
+ }
try {
const detail = await tasksApi.get(task.id)
if (cancelled) return
@@ -90,15 +130,16 @@ export function DramaGenTaskDetail({ job, onClose }: Props) {
return () => {
cancelled = true
}
- }, [job])
+ }, [job, isFailed])
- const errView = formatDramaGenError(rawError || job.message)
+ const errView = isFailed ? formatDramaGenError(rawError || job.message) : null
+ const panelTitle = isFailed ? '失败原因' : isActive ? '任务进度' : '任务详情'
return (
- <div className="drama-gen-detail" role="dialog" aria-label="失败原因">
+ <div className="drama-gen-detail" role="dialog" aria-label={panelTitle}>
<header className="drama-gen-detail-head">
<div>
- <strong>失败原因</strong>
+ <strong>{panelTitle}</strong>
<span>{job.title}</span>
</div>
<button type="button" className="drama-gen-fab-icon-btn" onClick={onClose} aria-label="关闭">
@@ -114,26 +155,36 @@ export function DramaGenTaskDetail({ job, onClose }: Props) {
</div>
) : null}
- <section className="drama-gen-detail-card is-error">
- <h4>{errView.title}</h4>
- <p>{errView.message}</p>
- {errView.suggestion ? (
- <p className="drama-gen-detail-tip">
- <strong>建议:</strong>
- {errView.suggestion}
- </p>
- ) : null}
- {rawError ? (
- <button
- type="button"
- className="drama-gen-detail-raw-toggle"
- onClick={() => setShowRaw((v) => !v)}
- >
- {showRaw ? '收起原始错误' : '查看原始错误'}
- </button>
- ) : null}
- {showRaw && rawError ? <pre className="drama-gen-detail-raw">{rawError}</pre> : null}
- </section>
+ {isFailed && errView ? (
+ <section className="drama-gen-detail-card is-error">
+ <h4>{errView.title}</h4>
+ <p>{errView.message}</p>
+ {errView.suggestion ? (
+ <p className="drama-gen-detail-tip">
+ <strong>建议:</strong>
+ {errView.suggestion}
+ </p>
+ ) : null}
+ {rawError ? (
+ <button
+ type="button"
+ className="drama-gen-detail-raw-toggle"
+ onClick={() => setShowRaw((v) => !v)}
+ >
+ {showRaw ? '收起原始错误' : '查看原始错误'}
+ </button>
+ ) : null}
+ {showRaw && rawError ? <pre className="drama-gen-detail-raw">{rawError}</pre> : null}
+ </section>
+ ) : (
+ <section className={`drama-gen-detail-card${isActive ? '' : ' is-done'}`}>
+ <h4>{STATUS_LABEL[job.status]}</h4>
+ <p>{activeJobHint(job)}</p>
+ {job.status === 'done' ? (
+ <p className="drama-gen-detail-tip">成片已写回分镜,可在时间轴预览。</p>
+ ) : null}
+ </section>
+ )}
</div>
</div>
)
diff --git a/frontend/src/lib/composeEpisodeVideoClient.ts b/frontend/src/lib/composeEpisodeVideoClient.ts
index c646717..d490da3 100644
--- a/frontend/src/lib/composeEpisodeVideoClient.ts
+++ b/frontend/src/lib/composeEpisodeVideoClient.ts
@@ -1,7 +1,7 @@
-/** 浏览器内无损拼接本集分镜 MP4(不走服务端 ffmpeg) */
+/** 浏览器内无损拼接本集 MP4;编码不一致时回退服务端统一重编码 */
import type { DramaFragment } from '../api/drama'
-import { resolveDramaMediaUrl } from '../api/drama'
+import { dramaApi, resolveDramaMediaUrl } from '../api/drama'
import { fetchMediaBlob } from './clientDownload'
import { sanitizeMediaBasename } from './canvasNodeMedia'
@@ -12,7 +12,7 @@ export type EpisodeComposeClip = {
}
export type EpisodeComposeProgress = {
- phase: 'download' | 'concat'
+ phase: 'download' | 'concat' | 'server'
done: number
total: number
}
@@ -37,10 +37,29 @@ export function episodeComposeFilename(episodeName: string) {
return `${sanitizeMediaBasename(episodeName || '本集')}_全片.mp4`
}
-/** 拉取各镜并在本地拼成一条 MP4 */
+/** 服务端统一重编码拼接并拉回 Blob */
+async function composeEpisodeVideoServer(
+ episodeId: number,
+ clips: EpisodeComposeClip[],
+ onProgress?: (progress: EpisodeComposeProgress) => void,
+): Promise<Blob> {
+ onProgress?.({ phase: 'server', done: 0, total: clips.length })
+ const result = await dramaApi.composeEpisode(
+ episodeId,
+ clips.map((c) => c.id),
+ )
+ const url = resolveDramaMediaUrl(result.video_url)
+ if (!url) throw new Error('服务端合成未返回可下载地址')
+ const blob = await fetchMediaBlob(url)
+ onProgress?.({ phase: 'server', done: clips.length, total: clips.length })
+ return blob
+}
+
+/** 拉取各镜并在本地拼成一条 MP4;无损失败则自动走服务端 */
export async function composeEpisodeVideoClient(
clips: EpisodeComposeClip[],
onProgress?: (progress: EpisodeComposeProgress) => void,
+ options?: { episodeId?: number },
): Promise<Blob> {
if (clips.length === 0) {
throw new Error('本集还没有可拼接的分镜视频')
@@ -72,6 +91,11 @@ export async function composeEpisodeVideoClient(
}
const compat = mp4Compat(buffers, { names })
if (!compat.ok) {
+ const episodeId = options?.episodeId
+ if (episodeId != null && episodeId > 0) {
+ // Seedance 各镜 HEVC SPS/PPS 常不一致,服务端统一重编码即可
+ return composeEpisodeVideoServer(episodeId, clips, onProgress)
+ }
throw new Error(
`各镜编码不一致,无法在浏览器里无损拼接。请用同一模型、比例和清晰度生成后再试。${
compat.reason ? `(${compat.reason})` : ''
diff --git a/frontend/src/lib/dramaGenError.ts b/frontend/src/lib/dramaGenError.ts
index 91fb6bd..63ddc17 100644
--- a/frontend/src/lib/dramaGenError.ts
+++ b/frontend/src/lib/dramaGenError.ts
@@ -134,6 +134,15 @@ export function formatDramaGenError(raw: string | null | undefined): DramaGenErr
}
}
+ if (/跳过重复任务|分镜已生成完成/.test(text)) {
+ return {
+ title: '旧任务已跳过',
+ message: '调度器发现该分镜已有成片,因此取消了这条重复入队的旧任务。',
+ suggestion:
+ '若你是在「重新生成」,请看队列里是否还有进行中的新任务;没有的话再点一次重新生成。不要把这条旧取消当成当前失败。',
+ }
+ }
+
if (/已取消|任务已中断/.test(text)) {
return {
title: text.includes('取消') ? '已取消' : '任务已中断',
diff --git a/frontend/src/pages/drama/EpisodeEditPage.tsx b/frontend/src/pages/drama/EpisodeEditPage.tsx
index 3d3dad3..bba08a4 100644
--- a/frontend/src/pages/drama/EpisodeEditPage.tsx
+++ b/frontend/src/pages/drama/EpisodeEditPage.tsx
@@ -1390,6 +1390,7 @@ function EpisodeEditInner() {
playingFragmentId={playingFragmentId}
onPlayingFragmentChange={handlePlayingFragmentChange}
aspectRatio={aspectRatio}
+ episodeId={episode?.id}
episodeName={episode?.name || '本集'}
subtitleMode={subtitleMode}
onOpenStoryboard={openEpisodeStoryboard}
diff --git a/frontend/src/pages/drama/EpisodeEditSidePane.tsx b/frontend/src/pages/drama/EpisodeEditSidePane.tsx
index cf1241a..bd9cd6f 100644
--- a/frontend/src/pages/drama/EpisodeEditSidePane.tsx
+++ b/frontend/src/pages/drama/EpisodeEditSidePane.tsx
@@ -19,6 +19,7 @@ type Props = {
playingFragmentId: number | null
onPlayingFragmentChange: (fragmentId: number) => void
aspectRatio: string
+ episodeId?: number
episodeName?: string
subtitleMode: DramaSubtitleMode
onOpenStoryboard: () => void
@@ -35,6 +36,7 @@ function composeProgressLabel(progress: EpisodeComposeProgress | null, busy: boo
if (!busy) return '全片合成下载'
if (!progress) return '全片合成中…'
if (progress.phase === 'download') return `拉取分镜 ${progress.done}/${progress.total}`
+ if (progress.phase === 'server') return '服务端统一重编码拼接…'
return '正在拼接…'
}
@@ -44,6 +46,7 @@ export function EpisodeEditSidePane({
playingFragmentId,
onPlayingFragmentChange,
aspectRatio,
+ episodeId,
episodeName = '本集',
subtitleMode,
onOpenStoryboard,
@@ -80,7 +83,9 @@ export function EpisodeEditSidePane({
setComposeBusy(true)
setComposeProgress({ phase: 'download', done: 0, total: composeClips.length })
try {
- const blob = await composeEpisodeVideoClient(composeClips, setComposeProgress)
+ const blob = await composeEpisodeVideoClient(composeClips, setComposeProgress, {
+ episodeId,
+ })
triggerBlobDownload(blob, episodeComposeFilename(episodeName))
} catch (err) {
setComposeError(err instanceof Error ? err.message : '全片合成失败')