@clipen/clipen-cli 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +79 -2
- package/apps/web/dist/assets/index-D5D2HiB1.js +14 -0
- package/apps/web/dist/assets/index-DIMuOXSu.css +1 -0
- package/apps/web/dist/favicon.svg +1 -0
- package/apps/web/dist/index.html +16 -0
- package/bin/clipen.js +157 -0
- package/clipen +18 -0
- package/install +25 -0
- package/package.json +52 -4
- package/pyproject.toml +28 -0
- package/requirements/asr-runtime.txt +13 -0
- package/requirements/runtime.txt +20 -0
- package/src/clipen/__init__.py +3 -0
- package/src/clipen/analysis/__init__.py +89 -0
- package/src/clipen/analysis/artifacts.py +416 -0
- package/src/clipen/analysis/audio.py +392 -0
- package/src/clipen/analysis/evidence.py +102 -0
- package/src/clipen/analysis/evidence_service.py +751 -0
- package/src/clipen/analysis/image_similarity.py +143 -0
- package/src/clipen/analysis/keyframes.py +171 -0
- package/src/clipen/analysis/models.py +230 -0
- package/src/clipen/analysis/qwen_worker.py +629 -0
- package/src/clipen/analysis/resources.py +21 -0
- package/src/clipen/analysis/runtime.py +64 -0
- package/src/clipen/analysis/service.py +626 -0
- package/src/clipen/analysis/setup.py +935 -0
- package/src/clipen/analysis/setup_cli.py +117 -0
- package/src/clipen/analysis/storage.py +2046 -0
- package/src/clipen/analysis/transcription.py +948 -0
- package/src/clipen/analysis/visual.py +176 -0
- package/src/clipen/annotations/__init__.py +10 -0
- package/src/clipen/annotations/models.py +22 -0
- package/src/clipen/annotations/storage.py +380 -0
- package/src/clipen/annotations/suggestions.py +120 -0
- package/src/clipen/asr_release.py +139 -0
- package/src/clipen/bootstrap.py +967 -0
- package/src/clipen/cli.py +84 -0
- package/src/clipen/controller/__init__.py +17 -0
- package/src/clipen/controller/app.py +1470 -0
- package/src/clipen/controller/server.py +543 -0
- package/src/clipen/domain/__init__.py +30 -0
- package/src/clipen/domain/errors.py +5 -0
- package/src/clipen/domain/media_time.py +117 -0
- package/src/clipen/domain/timeline.py +584 -0
- package/src/clipen/domain/validation.py +15 -0
- package/src/clipen/editing/EDITORIAL_REGRESSIONS.md +38 -0
- package/src/clipen/editing/PROGRAM_FORMAT.md +102 -0
- package/src/clipen/editing/README.md +115 -0
- package/src/clipen/editing/REFACTOR_DESIGN.md +241 -0
- package/src/clipen/editing/REFACTOR_HANDOFF.md +73 -0
- package/src/clipen/editing/__init__.py +15 -0
- package/src/clipen/editing/agent.py +13 -0
- package/src/clipen/editing/agent_models.py +134 -0
- package/src/clipen/editing/agent_repository.py +757 -0
- package/src/clipen/editing/agent_tools.py +532 -0
- package/src/clipen/editing/alignment.py +110 -0
- package/src/clipen/editing/alignment_setup.py +108 -0
- package/src/clipen/editing/alignment_worker.py +22 -0
- package/src/clipen/editing/change_report.py +71 -0
- package/src/clipen/editing/compiler.py +41 -0
- package/src/clipen/editing/component_looks.py +107 -0
- package/src/clipen/editing/component_review.py +78 -0
- package/src/clipen/editing/coordinator.py +374 -0
- package/src/clipen/editing/editorial_review.py +187 -0
- package/src/clipen/editing/evidence_jobs.py +295 -0
- package/src/clipen/editing/history_changes.py +131 -0
- package/src/clipen/editing/music_choices.py +15 -0
- package/src/clipen/editing/production_catalog.py +192 -0
- package/src/clipen/editing/production_limits.py +59 -0
- package/src/clipen/editing/production_media.py +226 -0
- package/src/clipen/editing/production_preview.py +180 -0
- package/src/clipen/editing/production_progress.py +141 -0
- package/src/clipen/editing/production_requirements.py +50 -0
- package/src/clipen/editing/production_tools.py +596 -0
- package/src/clipen/editing/program_audio.py +118 -0
- package/src/clipen/editing/program_direction.py +49 -0
- package/src/clipen/editing/program_story.py +53 -0
- package/src/clipen/editing/program_subtitles.py +134 -0
- package/src/clipen/editing/programme_review.py +73 -0
- package/src/clipen/editing/prompt_history.py +47 -0
- package/src/clipen/editing/recut.py +127 -0
- package/src/clipen/editing/refinement_references.py +188 -0
- package/src/clipen/editing/resolve_export.py +616 -0
- package/src/clipen/editing/resolve_titles.py +234 -0
- package/src/clipen/editing/skill_tools.py +575 -0
- package/src/clipen/editing/source_dialogue.py +82 -0
- package/src/clipen/editing/speech_coverage.py +30 -0
- package/src/clipen/editing/speech_quality.py +6 -0
- package/src/clipen/editing/tool_receipts.py +52 -0
- package/src/clipen/editing/versions.py +161 -0
- package/src/clipen/editing/visual_preview.py +93 -0
- package/src/clipen/editing/workbench.py +74 -0
- package/src/clipen/filesystem.py +25 -0
- package/src/clipen/finishing/README.md +103 -0
- package/src/clipen/finishing/__init__.py +1 -0
- package/src/clipen/finishing/audio.py +149 -0
- package/src/clipen/finishing/catalog.py +181 -0
- package/src/clipen/finishing/models.py +14 -0
- package/src/clipen/finishing/renderer.py +26 -0
- package/src/clipen/mcp_editing/__init__.py +5 -0
- package/src/clipen/mcp_editing/__main__.py +40 -0
- package/src/clipen/mcp_editing/server.py +353 -0
- package/src/clipen/media/__init__.py +50 -0
- package/src/clipen/media/discovery.py +266 -0
- package/src/clipen/media/models.py +360 -0
- package/src/clipen/media/preview.py +147 -0
- package/src/clipen/media/probe.py +446 -0
- package/src/clipen/media/service.py +317 -0
- package/src/clipen/media/storage.py +742 -0
- package/src/clipen/music_vocabulary.py +5 -0
- package/src/clipen/planning/__init__.py +9 -0
- package/src/clipen/planning/models.py +240 -0
- package/src/clipen/power.py +23 -0
- package/src/clipen/projects/__init__.py +26 -0
- package/src/clipen/projects/agent_schema.py +94 -0
- package/src/clipen/projects/annotation_schema.py +40 -0
- package/src/clipen/projects/deletion.py +269 -0
- package/src/clipen/projects/evidence_schema.py +52 -0
- package/src/clipen/projects/finishing_schema.py +34 -0
- package/src/clipen/projects/models.py +192 -0
- package/src/clipen/projects/picker.py +256 -0
- package/src/clipen/projects/preview_schema.py +29 -0
- package/src/clipen/projects/service.py +175 -0
- package/src/clipen/projects/storage.py +1478 -0
- package/src/clipen/projects/timeline_schema.py +32 -0
- package/src/clipen/projects/validation_schema.py +28 -0
- package/src/clipen/provider_registry.py +75 -0
- package/src/clipen/providers/__init__.py +43 -0
- package/src/clipen/providers/account.py +194 -0
- package/src/clipen/providers/claude.py +375 -0
- package/src/clipen/providers/claude_editing.py +111 -0
- package/src/clipen/providers/codex.py +1036 -0
- package/src/clipen/providers/codex_editing.py +91 -0
- package/src/clipen/providers/editing_agent.py +565 -0
- package/src/clipen/providers/errors.py +51 -0
- package/src/clipen/providers/recovery.py +270 -0
- package/src/clipen/py.typed +1 -0
- package/src/clipen/rendering/__init__.py +12 -0
- package/src/clipen/rendering/cover.py +126 -0
- package/src/clipen/rendering/custom_components.py +240 -0
- package/src/clipen/rendering/custom_render.py +197 -0
- package/src/clipen/rendering/fonts/anton-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/bebasneue-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/caveat-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/chenyu-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/delagothicone-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/hachimarupop-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/iansui-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/manifest.json +145 -0
- package/src/clipen/rendering/fonts/playfairdisplay-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/rocknrollone-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/yomogi-OFL.txt +94 -0
- package/src/clipen/rendering/fonts/yuseimagic-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/zenkurenaido-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/zenmarugothic-OFL.txt +93 -0
- package/src/clipen/rendering/production_effects.py +64 -0
- package/src/clipen/rendering/program_components.py +193 -0
- package/src/clipen/rendering/program_creator.py +649 -0
- package/src/clipen/rendering/program_identities.py +255 -0
- package/src/clipen/rendering/program_motion.py +141 -0
- package/src/clipen/rendering/program_studio.py +168 -0
- package/src/clipen/rendering/program_styles.py +235 -0
- package/src/clipen/rendering/program_subtitles.py +52 -0
- package/src/clipen/rendering/renderer.py +708 -0
- package/src/clipen/rendering/storage.py +243 -0
- package/src/clipen/rendering/titles.py +360 -0
- package/src/clipen/skills/__init__.py +4 -0
- package/src/clipen/skills/builtin/SKILL.md +72 -0
- package/src/clipen/skills/builtin/assets/sample-daily-vlog.mp4 +0 -0
- package/src/clipen/skills/builtin/assets/sample-event-recap.mp4 +0 -0
- package/src/clipen/skills/builtin/assets/sample-food-review.mp4 +0 -0
- package/src/clipen/skills/builtin/assets/sample-product-demo.mp4 +0 -0
- package/src/clipen/skills/builtin/assets/sample-product-review.mp4 +0 -0
- package/src/clipen/skills/builtin/assets/sample-product-unboxing.mp4 +0 -0
- package/src/clipen/skills/builtin/assets/sample-shorts-highlight.mp4 +0 -0
- package/src/clipen/skills/builtin/assets/sample-travel-highlight.mp4 +0 -0
- package/src/clipen/skills/builtin/assets/sample-travel-vlog.mp4 +0 -0
- package/src/clipen/skills/builtin/assets/style-cinema.png +0 -0
- package/src/clipen/skills/builtin/assets/style-editorial.png +0 -0
- package/src/clipen/skills/builtin/assets/style-tpl-daily-vlog.png +0 -0
- package/src/clipen/skills/builtin/assets/style-tpl-event-recap.png +0 -0
- package/src/clipen/skills/builtin/assets/style-tpl-food-review.png +0 -0
- package/src/clipen/skills/builtin/assets/style-tpl-product-demo.png +0 -0
- package/src/clipen/skills/builtin/assets/style-tpl-product-review.png +0 -0
- package/src/clipen/skills/builtin/assets/style-tpl-product-unboxing.png +0 -0
- package/src/clipen/skills/builtin/assets/style-tpl-shorts-highlight.png +0 -0
- package/src/clipen/skills/builtin/assets/style-tpl-travel-highlight.png +0 -0
- package/src/clipen/skills/builtin/assets/style-tpl-travel-vlog.png +0 -0
- package/src/clipen/skills/builtin/assets/style-variety.png +0 -0
- package/src/clipen/skills/builtin/components.json +133 -0
- package/src/clipen/skills/builtin/font_sources.json +20 -0
- package/src/clipen/skills/builtin/font_styles.json +329 -0
- package/src/clipen/skills/builtin/manifest.json +32 -0
- package/src/clipen/skills/builtin/presets.json +8 -0
- package/src/clipen/skills/builtin/references/captions.md +14 -0
- package/src/clipen/skills/builtin/references/channel-design.md +37 -0
- package/src/clipen/skills/builtin/references/editing.md +30 -0
- package/src/clipen/skills/builtin/references/font-chenyu-OFL.txt +93 -0
- package/src/clipen/skills/builtin/references/font-iansui-OFL.txt +93 -0
- package/src/clipen/skills/builtin/references/graphics.md +59 -0
- package/src/clipen/skills/builtin/references/review.md +16 -0
- package/src/clipen/skills/builtin/references/sound.md +8 -0
- package/src/clipen/skills/builtin/references/story.md +7 -0
- package/src/clipen/skills/builtin/skills/travel-program/SKILL.md +27 -0
- package/src/clipen/skills/builtin/skills/travel-program/manifest.json +6 -0
- package/src/clipen/skills/builtin/template-skills/clipen-daily-vlog/SKILL.md +33 -0
- package/src/clipen/skills/builtin/template-skills/clipen-daily-vlog/manifest.json +8 -0
- package/src/clipen/skills/builtin/template-skills/clipen-event-recap/SKILL.md +34 -0
- package/src/clipen/skills/builtin/template-skills/clipen-event-recap/manifest.json +8 -0
- package/src/clipen/skills/builtin/template-skills/clipen-food-review/SKILL.md +33 -0
- package/src/clipen/skills/builtin/template-skills/clipen-food-review/manifest.json +8 -0
- package/src/clipen/skills/builtin/template-skills/clipen-product-demo/SKILL.md +35 -0
- package/src/clipen/skills/builtin/template-skills/clipen-product-demo/manifest.json +8 -0
- package/src/clipen/skills/builtin/template-skills/clipen-product-review/SKILL.md +36 -0
- package/src/clipen/skills/builtin/template-skills/clipen-product-review/manifest.json +8 -0
- package/src/clipen/skills/builtin/template-skills/clipen-product-unboxing/SKILL.md +39 -0
- package/src/clipen/skills/builtin/template-skills/clipen-product-unboxing/manifest.json +8 -0
- package/src/clipen/skills/builtin/template-skills/clipen-shorts-highlight/SKILL.md +38 -0
- package/src/clipen/skills/builtin/template-skills/clipen-shorts-highlight/manifest.json +8 -0
- package/src/clipen/skills/builtin/template-skills/clipen-travel-highlight/SKILL.md +34 -0
- package/src/clipen/skills/builtin/template-skills/clipen-travel-highlight/manifest.json +8 -0
- package/src/clipen/skills/builtin/template-skills/clipen-travel-vlog/SKILL.md +37 -0
- package/src/clipen/skills/builtin/template-skills/clipen-travel-vlog/manifest.json +8 -0
- package/src/clipen/skills/builtin/templates.json +284 -0
- package/src/clipen/skills/builtin/visual_styles.json +1074 -0
- package/src/clipen/skills/catalog.py +218 -0
- package/src/clipen/skills/library.py +131 -0
- package/src/clipen/skills/package.py +231 -0
- package/src/clipen/skills/visual_styles.py +44 -0
- package/src/clipen/workspace.py +210 -0
- package/uninstall +25 -0
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
"""Durable state for local rough-cut preview renders."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
import secrets
|
|
7
|
+
import sqlite3
|
|
8
|
+
|
|
9
|
+
from clipen.filesystem import restrict_permissions
|
|
10
|
+
from clipen.projects import ProjectError, ProjectRepository
|
|
11
|
+
from clipen.projects.models import validate_project_id, validate_request_id
|
|
12
|
+
from clipen.projects.storage import utc_now
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class PreviewRenderRepository:
|
|
16
|
+
def __init__(self, projects: ProjectRepository) -> None:
|
|
17
|
+
self.projects = projects
|
|
18
|
+
|
|
19
|
+
def create(
|
|
20
|
+
self, project_id: str, request_id: object, timeline_id: str
|
|
21
|
+
) -> dict[str, object]:
|
|
22
|
+
validate_project_id(project_id)
|
|
23
|
+
request = validate_request_id(request_id)
|
|
24
|
+
now = utc_now()
|
|
25
|
+
try:
|
|
26
|
+
with self.projects.connect(project_id) as database:
|
|
27
|
+
database.execute("BEGIN IMMEDIATE")
|
|
28
|
+
existing = database.execute(
|
|
29
|
+
"SELECT * FROM preview_renders WHERE request_id=?", (request,)
|
|
30
|
+
).fetchone()
|
|
31
|
+
if existing is not None:
|
|
32
|
+
if existing["timeline_id"] != timeline_id:
|
|
33
|
+
database.rollback()
|
|
34
|
+
raise ProjectError(
|
|
35
|
+
"request_conflict",
|
|
36
|
+
"這次初剪輸出與既有操作衝突。",
|
|
37
|
+
status_code=409,
|
|
38
|
+
)
|
|
39
|
+
database.rollback()
|
|
40
|
+
return self._public(existing)
|
|
41
|
+
render_id = "render_" + secrets.token_hex(16)
|
|
42
|
+
database.execute(
|
|
43
|
+
"INSERT INTO preview_renders "
|
|
44
|
+
"(render_id,project_id,timeline_id,request_id,state,progress,created_at) "
|
|
45
|
+
"VALUES(?,?,?,?, 'queued',0,?)",
|
|
46
|
+
(render_id, project_id, timeline_id, request, now),
|
|
47
|
+
)
|
|
48
|
+
database.execute(
|
|
49
|
+
"INSERT INTO current_preview_render(slot,render_id) VALUES(1,?) "
|
|
50
|
+
"ON CONFLICT(slot) DO UPDATE SET render_id=excluded.render_id",
|
|
51
|
+
(render_id,),
|
|
52
|
+
)
|
|
53
|
+
database.commit()
|
|
54
|
+
return self.get(project_id, render_id)
|
|
55
|
+
except ProjectError:
|
|
56
|
+
raise
|
|
57
|
+
except sqlite3.Error as error:
|
|
58
|
+
raise ProjectError(
|
|
59
|
+
"storage_failed",
|
|
60
|
+
"Clipen 無法建立初剪輸出工作。",
|
|
61
|
+
status_code=500,
|
|
62
|
+
) from error
|
|
63
|
+
|
|
64
|
+
def current(self, project_id: str) -> dict[str, object] | None:
|
|
65
|
+
validate_project_id(project_id)
|
|
66
|
+
with self.projects.connect(project_id) as database:
|
|
67
|
+
row = database.execute(
|
|
68
|
+
"SELECT renders.* FROM current_preview_render current "
|
|
69
|
+
"JOIN preview_renders renders ON renders.render_id=current.render_id WHERE current.slot=1"
|
|
70
|
+
).fetchone()
|
|
71
|
+
return None if row is None else self._public(row)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def get(self, project_id: str, render_id: str) -> dict[str, object]:
|
|
75
|
+
validate_project_id(project_id)
|
|
76
|
+
with self.projects.connect(project_id) as database:
|
|
77
|
+
row = database.execute(
|
|
78
|
+
"SELECT * FROM preview_renders WHERE render_id=? AND project_id=?",
|
|
79
|
+
(render_id, project_id),
|
|
80
|
+
).fetchone()
|
|
81
|
+
if row is None:
|
|
82
|
+
raise ProjectError("preview_not_found", "找不到這次初剪輸出。", status_code=404)
|
|
83
|
+
return self._public(row)
|
|
84
|
+
|
|
85
|
+
def media_path(self, project_id: str, render_id: str) -> Path:
|
|
86
|
+
"""The finished film of a render, checked against what was recorded when it succeeded."""
|
|
87
|
+
render = self.get(project_id, render_id)
|
|
88
|
+
if render["state"] != "succeeded":
|
|
89
|
+
raise ProjectError("preview_not_ready", "影片尚未輸出完成。", status_code=409)
|
|
90
|
+
path = self.output_path(project_id, render_id, prepare=False)
|
|
91
|
+
if path.is_symlink() or not path.is_file() or path.stat().st_size != render["size_bytes"]:
|
|
92
|
+
raise ProjectError("preview_missing", "找不到已輸出的影片。", status_code=409)
|
|
93
|
+
return path
|
|
94
|
+
|
|
95
|
+
def finish_unsuccessful(
|
|
96
|
+
self,
|
|
97
|
+
project_id: str,
|
|
98
|
+
render_id: str,
|
|
99
|
+
state: str,
|
|
100
|
+
*,
|
|
101
|
+
error_code: str | None = None,
|
|
102
|
+
) -> dict[str, object]:
|
|
103
|
+
if state not in {"failed", "cancelled"}:
|
|
104
|
+
raise ValueError("unsuccessful preview state is invalid")
|
|
105
|
+
now = utc_now()
|
|
106
|
+
fields = ["state=?", "error_code=?"]
|
|
107
|
+
values: list[object] = [state, error_code]
|
|
108
|
+
fields.append("completed_at=?")
|
|
109
|
+
values.append(now)
|
|
110
|
+
values.extend([render_id, project_id])
|
|
111
|
+
with self.projects.connect(project_id) as database:
|
|
112
|
+
database.execute(
|
|
113
|
+
f"UPDATE preview_renders SET {','.join(fields)} "
|
|
114
|
+
"WHERE render_id=? AND project_id=?",
|
|
115
|
+
values,
|
|
116
|
+
)
|
|
117
|
+
return self.get(project_id, render_id)
|
|
118
|
+
|
|
119
|
+
def mark_running(self, project_id: str, render_id: str) -> dict[str, object]:
|
|
120
|
+
now = utc_now()
|
|
121
|
+
with self.projects.connect(project_id) as database:
|
|
122
|
+
database.execute(
|
|
123
|
+
"UPDATE preview_renders SET state='running',progress=0,"
|
|
124
|
+
"started_at=COALESCE(started_at,?) "
|
|
125
|
+
"WHERE render_id=? AND project_id=? AND state='queued'",
|
|
126
|
+
(now, render_id, project_id),
|
|
127
|
+
)
|
|
128
|
+
return self.get(project_id, render_id)
|
|
129
|
+
|
|
130
|
+
def update_progress(
|
|
131
|
+
self, project_id: str, render_id: str, progress: float
|
|
132
|
+
) -> dict[str, object]:
|
|
133
|
+
normalized = max(0.0, min(1.0, progress))
|
|
134
|
+
with self.projects.connect(project_id) as database:
|
|
135
|
+
database.execute(
|
|
136
|
+
"UPDATE preview_renders SET progress=? "
|
|
137
|
+
"WHERE render_id=? AND project_id=? AND state='running'",
|
|
138
|
+
(normalized, render_id, project_id),
|
|
139
|
+
)
|
|
140
|
+
return self.get(project_id, render_id)
|
|
141
|
+
|
|
142
|
+
def request_cancel(self, project_id: str, render_id: str) -> dict[str, object]:
|
|
143
|
+
with self.projects.connect(project_id) as database:
|
|
144
|
+
database.execute(
|
|
145
|
+
"UPDATE preview_renders SET state='cancelling' "
|
|
146
|
+
"WHERE render_id=? AND project_id=? AND state IN ('queued','running')",
|
|
147
|
+
(render_id, project_id),
|
|
148
|
+
)
|
|
149
|
+
return self.get(project_id, render_id)
|
|
150
|
+
|
|
151
|
+
def complete(
|
|
152
|
+
self,
|
|
153
|
+
project_id: str,
|
|
154
|
+
render_id: str,
|
|
155
|
+
output_relative_path: str,
|
|
156
|
+
output_size_bytes: int,
|
|
157
|
+
) -> dict[str, object]:
|
|
158
|
+
with self.projects.connect(project_id) as database:
|
|
159
|
+
database.execute(
|
|
160
|
+
"UPDATE preview_renders SET state='succeeded',progress=1,error_code=NULL,"
|
|
161
|
+
"output_relative_path=?,output_size_bytes=?,completed_at=? "
|
|
162
|
+
"WHERE render_id=? AND project_id=? AND state='running'",
|
|
163
|
+
(
|
|
164
|
+
output_relative_path,
|
|
165
|
+
output_size_bytes,
|
|
166
|
+
utc_now(),
|
|
167
|
+
render_id,
|
|
168
|
+
project_id,
|
|
169
|
+
),
|
|
170
|
+
)
|
|
171
|
+
return self.get(project_id, render_id)
|
|
172
|
+
|
|
173
|
+
def interrupt_incomplete(self, project_id: str) -> None:
|
|
174
|
+
with self.projects.connect(project_id) as database:
|
|
175
|
+
database.execute(
|
|
176
|
+
"UPDATE preview_renders SET state='interrupted',error_code='controller_restarted',"
|
|
177
|
+
"completed_at=? WHERE state IN ('queued','running','cancelling')",
|
|
178
|
+
(utc_now(),),
|
|
179
|
+
)
|
|
180
|
+
|
|
181
|
+
def interrupt_attempt_renders(self, project_id: str, run_id: str) -> int:
|
|
182
|
+
"""End this run's AI previews still marked in progress.
|
|
183
|
+
|
|
184
|
+
Agent previews render inside the AI's tool process, so they cannot
|
|
185
|
+
outlive an attempt; a row left running (the Mac slept, the process was
|
|
186
|
+
killed) would otherwise block every later preview as busy.
|
|
187
|
+
"""
|
|
188
|
+
with self.projects.connect(project_id) as database:
|
|
189
|
+
cursor = database.execute(
|
|
190
|
+
"UPDATE preview_renders SET state='interrupted',error_code='attempt_ended',completed_at=? "
|
|
191
|
+
"WHERE state IN ('queued','running','cancelling') AND request_id LIKE ? ESCAPE '\\'",
|
|
192
|
+
(utc_now(), 'agent-preview-' + run_id.replace('_', '\\_') + '-%'),
|
|
193
|
+
)
|
|
194
|
+
database.commit()
|
|
195
|
+
return cursor.rowcount
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def output_path(
|
|
199
|
+
self,
|
|
200
|
+
project_id: str,
|
|
201
|
+
render_id: str,
|
|
202
|
+
*,
|
|
203
|
+
staging: bool = False,
|
|
204
|
+
prepare: bool = True,
|
|
205
|
+
) -> Path:
|
|
206
|
+
validate_project_id(project_id)
|
|
207
|
+
root = self.projects.root / project_id
|
|
208
|
+
if root.is_symlink() or not root.is_dir():
|
|
209
|
+
raise ProjectError("project_not_found", "找不到這個作品。", status_code=404)
|
|
210
|
+
directory = root / "previews"
|
|
211
|
+
if prepare:
|
|
212
|
+
directory.mkdir(mode=0o700, exist_ok=True)
|
|
213
|
+
elif not directory.exists():
|
|
214
|
+
name = f".{render_id}.partial.mp4" if staging else f"{render_id}.mp4"
|
|
215
|
+
return directory / name
|
|
216
|
+
if directory.is_symlink() or not directory.is_dir():
|
|
217
|
+
raise ProjectError(
|
|
218
|
+
"storage_corrupt", "Clipen 無法安全建立初剪資料夾。", status_code=500
|
|
219
|
+
)
|
|
220
|
+
if prepare:
|
|
221
|
+
restrict_permissions(directory, 0o700)
|
|
222
|
+
name = f".{render_id}.partial.mp4" if staging else f"{render_id}.mp4"
|
|
223
|
+
return directory / name
|
|
224
|
+
|
|
225
|
+
@staticmethod
|
|
226
|
+
def _public(row) -> dict[str, object]:
|
|
227
|
+
return {
|
|
228
|
+
"render_id": row["render_id"],
|
|
229
|
+
"timeline_id": row["timeline_id"],
|
|
230
|
+
"state": row["state"],
|
|
231
|
+
"progress": row["progress"],
|
|
232
|
+
"error_code": row["error_code"],
|
|
233
|
+
"size_bytes": row["output_size_bytes"],
|
|
234
|
+
"created_at": row["created_at"],
|
|
235
|
+
"started_at": row["started_at"],
|
|
236
|
+
"completed_at": row["completed_at"],
|
|
237
|
+
"playback_url": (
|
|
238
|
+
f"/api/projects/{row['project_id']}/preview/"
|
|
239
|
+
f"{row['render_id']}/media"
|
|
240
|
+
if row["state"] == "succeeded" and row["output_relative_path"]
|
|
241
|
+
else None
|
|
242
|
+
),
|
|
243
|
+
}
|
|
@@ -0,0 +1,360 @@
|
|
|
1
|
+
"""Rasterized title cards and a bounded FFmpeg overlay pass."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
import os
|
|
7
|
+
import re
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
import subprocess
|
|
10
|
+
import tempfile
|
|
11
|
+
import threading
|
|
12
|
+
from typing import Callable, Iterable
|
|
13
|
+
|
|
14
|
+
from clipen.domain import EditTimeline, TextClip, TrackKind
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class TitleRenderError(RuntimeError):
|
|
18
|
+
"""Raised when a trusted timeline cannot be composed locally."""
|
|
19
|
+
|
|
20
|
+
def __init__(self, code: str) -> None:
|
|
21
|
+
super().__init__(code)
|
|
22
|
+
self.code = code
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass(frozen=True, slots=True)
|
|
26
|
+
class RenderedTitle:
|
|
27
|
+
path: Path
|
|
28
|
+
start_seconds: float
|
|
29
|
+
duration_seconds: float
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class TitleCardRenderer:
|
|
33
|
+
"""Turn semantic title styles into transparent, full-canvas PNG overlays."""
|
|
34
|
+
|
|
35
|
+
# Each card becomes one bounded FFmpeg input during the finishing pass.
|
|
36
|
+
# Keep this below the point where full-HD RGBA frames can create avoidable
|
|
37
|
+
# memory pressure on consumer machines.
|
|
38
|
+
_MAX_TITLES = 32
|
|
39
|
+
|
|
40
|
+
def __init__(self,custom_styles=None):
|
|
41
|
+
self.custom_styles=custom_styles or {}
|
|
42
|
+
|
|
43
|
+
def render(self, timeline: EditTimeline, directory: Path) -> tuple[RenderedTitle, ...]:
|
|
44
|
+
items = tuple(
|
|
45
|
+
item
|
|
46
|
+
for track in timeline.tracks
|
|
47
|
+
if track.kind is TrackKind.TITLE
|
|
48
|
+
for item in track.items
|
|
49
|
+
)
|
|
50
|
+
if len(items) > self._MAX_TITLES:
|
|
51
|
+
raise TitleRenderError("preview_title_limit_exceeded")
|
|
52
|
+
if not items:
|
|
53
|
+
return ()
|
|
54
|
+
try:
|
|
55
|
+
from PIL import Image, ImageDraw, ImageFont
|
|
56
|
+
except ImportError as error:
|
|
57
|
+
raise TitleRenderError("preview_title_runtime_missing") from error
|
|
58
|
+
|
|
59
|
+
font_path = self._font_path()
|
|
60
|
+
if font_path is None:
|
|
61
|
+
raise TitleRenderError("preview_title_font_missing")
|
|
62
|
+
frame_rate = timeline.frame_rate.numerator / timeline.frame_rate.denominator
|
|
63
|
+
rendered = []
|
|
64
|
+
for index, item in enumerate(items):
|
|
65
|
+
assert isinstance(item, TextClip)
|
|
66
|
+
image = Image.new("RGBA", (timeline.width, timeline.height), (0, 0, 0, 0))
|
|
67
|
+
draw = ImageDraw.Draw(image)
|
|
68
|
+
self._draw_card(draw, ImageFont, font_path, timeline, item)
|
|
69
|
+
path = directory / f"title-{index:04d}.png"
|
|
70
|
+
image.save(path, "PNG", optimize=True)
|
|
71
|
+
rendered.append(
|
|
72
|
+
RenderedTitle(
|
|
73
|
+
path,
|
|
74
|
+
item.start_frame / frame_rate,
|
|
75
|
+
item.duration_frames / frame_rate,
|
|
76
|
+
)
|
|
77
|
+
)
|
|
78
|
+
return tuple(rendered)
|
|
79
|
+
|
|
80
|
+
@staticmethod
|
|
81
|
+
def _font_path() -> Path | None:
|
|
82
|
+
configured = os.environ.get("CLIPEN_TITLE_FONT")
|
|
83
|
+
candidates = (
|
|
84
|
+
Path(configured).expanduser() if configured else None,
|
|
85
|
+
Path("/System/Library/Fonts/Hiragino Sans GB.ttc"),
|
|
86
|
+
Path("/System/Library/Fonts/STHeiti Light.ttc"),
|
|
87
|
+
Path("/System/Library/Fonts/PingFang.ttc"),
|
|
88
|
+
Path("/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc"),
|
|
89
|
+
Path("/usr/share/fonts/truetype/noto/NotoSansCJK-Regular.ttc"),
|
|
90
|
+
Path("C:/Windows/Fonts/msjh.ttc"),
|
|
91
|
+
)
|
|
92
|
+
return next((path for path in candidates if path is not None and path.is_file()), None)
|
|
93
|
+
|
|
94
|
+
def _draw_card(
|
|
95
|
+
self, draw, image_font, font_path: Path, timeline: EditTimeline, item: TextClip, relative_frame=None
|
|
96
|
+
) -> None:
|
|
97
|
+
width, height = timeline.width, timeline.height
|
|
98
|
+
if self.custom_styles.get(item.style_id,{}).get('kind')=='program_component':
|
|
99
|
+
from .program_components import draw_program_component
|
|
100
|
+
draw_program_component(draw,font_path,timeline,item,self.custom_styles[item.style_id],relative_frame)
|
|
101
|
+
return
|
|
102
|
+
if self.custom_styles.get(item.style_id,{}).get('kind')=='program_subtitle':
|
|
103
|
+
from .program_subtitles import draw_program_subtitle
|
|
104
|
+
draw_program_subtitle(draw,font_path,timeline,item,self.custom_styles[item.style_id],relative_frame)
|
|
105
|
+
return
|
|
106
|
+
if item.style_id in self.custom_styles:
|
|
107
|
+
profile=self.custom_styles[item.style_id]
|
|
108
|
+
size=max(1,round(height*profile['font_size_ratio']))
|
|
109
|
+
font=image_font.truetype(str(font_path),size)
|
|
110
|
+
maximum=round(width*profile['width_ratio'])
|
|
111
|
+
lines=self._wrap(draw,item.text,font,maximum)
|
|
112
|
+
line_height=max(1,round(size*1.5));pad=max(1,round(size*.25))
|
|
113
|
+
x=round(width*profile['x']);y=round(height*profile['y'])
|
|
114
|
+
if y+line_height*len(lines)+pad>height or x+maximum>width:
|
|
115
|
+
raise TitleRenderError('preview_text_overflow')
|
|
116
|
+
for row in lines:
|
|
117
|
+
length=draw.textlength(row,font=font)
|
|
118
|
+
at=x if profile['align']=='left' else x+(maximum-length)/(2 if profile['align']=='center' else 1)
|
|
119
|
+
draw.rounded_rectangle((at-pad,y-pad,at+length+pad,y+line_height),radius=pad,fill=tuple(profile['background_color']))
|
|
120
|
+
draw.text((at,y),row,font=font,fill=tuple(profile['text_color']));y+=line_height
|
|
121
|
+
return
|
|
122
|
+
if item.style_id == "title.chapter":
|
|
123
|
+
size = max(28, round(height * 0.055))
|
|
124
|
+
font = image_font.truetype(str(font_path), size)
|
|
125
|
+
lines = self._wrap(draw, item.text, font, round(width * 0.55))
|
|
126
|
+
box = self._text_box(draw, lines, font, round(size * 0.34))
|
|
127
|
+
x, y = round(width * 0.065), round(height * 0.10)
|
|
128
|
+
pad_x, pad_y = round(size * 0.58), round(size * 0.36)
|
|
129
|
+
draw.rounded_rectangle(
|
|
130
|
+
(x - pad_x, y - pad_y, x + box[0] + pad_x, y + box[1] + pad_y),
|
|
131
|
+
radius=round(size * 0.42),
|
|
132
|
+
fill=(37, 83, 62, 230),
|
|
133
|
+
)
|
|
134
|
+
self._multiline(draw, (x, y), lines, font, (255, 255, 248, 255), size)
|
|
135
|
+
return
|
|
136
|
+
|
|
137
|
+
if item.style_id == "title.caption":
|
|
138
|
+
size = max(26, round(height * 0.043))
|
|
139
|
+
font = image_font.truetype(str(font_path), size)
|
|
140
|
+
lines = self._wrap(draw, item.text, font, round(width * 0.70))
|
|
141
|
+
box = self._text_box(draw, lines, font, round(size * 0.32))
|
|
142
|
+
x = round((width - box[0]) / 2)
|
|
143
|
+
y = round(height * 0.79 - box[1] / 2)
|
|
144
|
+
pad_x, pad_y = round(size * 0.62), round(size * 0.38)
|
|
145
|
+
draw.rounded_rectangle(
|
|
146
|
+
(x - pad_x + 4, y - pad_y + 7, x + box[0] + pad_x + 4, y + box[1] + pad_y + 7),
|
|
147
|
+
radius=round(size * 0.36),
|
|
148
|
+
fill=(0, 0, 0, 75),
|
|
149
|
+
)
|
|
150
|
+
draw.rounded_rectangle(
|
|
151
|
+
(x - pad_x, y - pad_y, x + box[0] + pad_x, y + box[1] + pad_y),
|
|
152
|
+
radius=round(size * 0.36),
|
|
153
|
+
fill=(250, 249, 242, 238),
|
|
154
|
+
)
|
|
155
|
+
self._multiline(draw, (x, y), lines, font, (24, 27, 24, 255), size)
|
|
156
|
+
return
|
|
157
|
+
|
|
158
|
+
size = max(34, round(height * 0.072))
|
|
159
|
+
font = image_font.truetype(str(font_path), size)
|
|
160
|
+
lines = self._wrap(draw, item.text, font, round(width * 0.78))
|
|
161
|
+
box = self._text_box(draw, lines, font, round(size * 0.30))
|
|
162
|
+
x = round((width - box[0]) / 2)
|
|
163
|
+
y = round((height - box[1]) / 2)
|
|
164
|
+
pad_x, pad_y = round(size * 0.66), round(size * 0.44)
|
|
165
|
+
draw.rounded_rectangle(
|
|
166
|
+
(x - pad_x + 5, y - pad_y + 9, x + box[0] + pad_x + 5, y + box[1] + pad_y + 9),
|
|
167
|
+
radius=round(size * 0.34),
|
|
168
|
+
fill=(0, 0, 0, 90),
|
|
169
|
+
)
|
|
170
|
+
draw.rounded_rectangle(
|
|
171
|
+
(x - pad_x, y - pad_y, x + box[0] + pad_x, y + box[1] + pad_y),
|
|
172
|
+
radius=round(size * 0.34),
|
|
173
|
+
fill=(19, 24, 21, 205),
|
|
174
|
+
)
|
|
175
|
+
self._multiline(draw, (x, y), lines, font, (255, 255, 250, 255), size)
|
|
176
|
+
|
|
177
|
+
@staticmethod
|
|
178
|
+
def _wrap(draw, text: str, font, maximum_width: int) -> tuple[str, ...]:
|
|
179
|
+
lines: list[str] = []
|
|
180
|
+
for paragraph in text.splitlines() or (text,):
|
|
181
|
+
current = ""
|
|
182
|
+
for character in paragraph:
|
|
183
|
+
candidate = current + character
|
|
184
|
+
if current and draw.textbbox((0, 0), candidate, font=font)[2] > maximum_width:
|
|
185
|
+
lines.append(current)
|
|
186
|
+
current = character
|
|
187
|
+
else:
|
|
188
|
+
current = candidate
|
|
189
|
+
if current:
|
|
190
|
+
lines.append(current)
|
|
191
|
+
return tuple(lines) or (text,)
|
|
192
|
+
|
|
193
|
+
@staticmethod
|
|
194
|
+
def _text_box(draw, lines: Iterable[str], font, spacing: int) -> tuple[int, int]:
|
|
195
|
+
boxes = [draw.textbbox((0, 0), line, font=font) for line in lines]
|
|
196
|
+
return max(box[2] - box[0] for box in boxes), sum(
|
|
197
|
+
box[3] - box[1] for box in boxes
|
|
198
|
+
) + spacing * (len(boxes) - 1)
|
|
199
|
+
|
|
200
|
+
@staticmethod
|
|
201
|
+
def _multiline(draw, origin, lines: Iterable[str], font, fill, font_size: int) -> None:
|
|
202
|
+
draw.multiline_text(
|
|
203
|
+
origin,
|
|
204
|
+
"\n".join(lines),
|
|
205
|
+
font=font,
|
|
206
|
+
fill=fill,
|
|
207
|
+
spacing=round(font_size * 0.30),
|
|
208
|
+
align="center",
|
|
209
|
+
stroke_width=max(1, round(font_size * 0.018)),
|
|
210
|
+
stroke_fill=(0, 0, 0, 45),
|
|
211
|
+
)
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
class FfmpegTitleCompositor:
|
|
215
|
+
"""Overlay pre-rendered title cards without exposing timeline text to a shell."""
|
|
216
|
+
|
|
217
|
+
def __init__(
|
|
218
|
+
self,
|
|
219
|
+
executable: str = "ffmpeg",
|
|
220
|
+
*,
|
|
221
|
+
popen: Callable[..., subprocess.Popen[str]] = subprocess.Popen,
|
|
222
|
+
) -> None:
|
|
223
|
+
self.executable = executable
|
|
224
|
+
self._popen = popen
|
|
225
|
+
|
|
226
|
+
def compose(
|
|
227
|
+
self,
|
|
228
|
+
source: Path,
|
|
229
|
+
titles: tuple[RenderedTitle, ...],
|
|
230
|
+
output: Path,
|
|
231
|
+
cancel: threading.Event,
|
|
232
|
+
duration_seconds: float,
|
|
233
|
+
progress: Callable[[float], None],
|
|
234
|
+
) -> None:
|
|
235
|
+
command = [self.executable, "-hide_banner", "-loglevel", "error", "-y", "-i", str(source)]
|
|
236
|
+
filters = []
|
|
237
|
+
previous = "[0:v]"
|
|
238
|
+
for index, title in enumerate(titles, start=1):
|
|
239
|
+
command.extend(
|
|
240
|
+
["-loop", "1", "-t", f"{title.duration_seconds:.6f}", "-i", str(title.path)]
|
|
241
|
+
)
|
|
242
|
+
fade = min(0.18, title.duration_seconds / 4)
|
|
243
|
+
fade_out = max(0.0, title.duration_seconds - fade)
|
|
244
|
+
filters.append(
|
|
245
|
+
f"[{index}:v]format=rgba,fade=t=in:st=0:d={fade:.3f}:alpha=1,"
|
|
246
|
+
f"fade=t=out:st={fade_out:.3f}:d={fade:.3f}:alpha=1,"
|
|
247
|
+
f"setpts=PTS+{title.start_seconds:.6f}/TB[title{index}]"
|
|
248
|
+
)
|
|
249
|
+
output_label = f"composed{index}"
|
|
250
|
+
filters.append(
|
|
251
|
+
f"{previous}[title{index}]overlay=0:0:eof_action=pass:shortest=0[{output_label}]"
|
|
252
|
+
)
|
|
253
|
+
previous = f"[{output_label}]"
|
|
254
|
+
command.extend(
|
|
255
|
+
[
|
|
256
|
+
"-filter_complex", ";".join(filters),
|
|
257
|
+
"-map", previous,
|
|
258
|
+
"-map", "0:a?",
|
|
259
|
+
"-c:v", "libx264",
|
|
260
|
+
"-preset", "veryfast",
|
|
261
|
+
"-crf", "21",
|
|
262
|
+
"-pix_fmt", "yuv420p",
|
|
263
|
+
"-c:a", "copy",
|
|
264
|
+
"-movflags", "+faststart",
|
|
265
|
+
"-progress", "pipe:1",
|
|
266
|
+
"-nostats",
|
|
267
|
+
str(output),
|
|
268
|
+
]
|
|
269
|
+
)
|
|
270
|
+
with tempfile.TemporaryFile() as errors:
|
|
271
|
+
try:
|
|
272
|
+
process = self._popen(command, stdout=subprocess.PIPE, stderr=errors, text=True)
|
|
273
|
+
except FileNotFoundError as error:
|
|
274
|
+
raise TitleRenderError("ffmpeg_unavailable") from error
|
|
275
|
+
except OSError as error:
|
|
276
|
+
raise TitleRenderError("ffmpeg_start_failed") from error
|
|
277
|
+
assert process.stdout is not None
|
|
278
|
+
terminated = False
|
|
279
|
+
try:
|
|
280
|
+
for line in process.stdout:
|
|
281
|
+
if cancel.is_set() and not terminated:
|
|
282
|
+
process.terminate()
|
|
283
|
+
terminated = True
|
|
284
|
+
if line.startswith("out_time_ms="):
|
|
285
|
+
value = line.split("=", 1)[1].strip()
|
|
286
|
+
if value.isdigit() and duration_seconds > 0:
|
|
287
|
+
progress(min(0.99, int(value) / 1_000_000 / duration_seconds))
|
|
288
|
+
finally:
|
|
289
|
+
close_stdout = getattr(process.stdout, "close", None)
|
|
290
|
+
if close_stdout is not None:
|
|
291
|
+
close_stdout()
|
|
292
|
+
code = process.wait()
|
|
293
|
+
if cancel.is_set():
|
|
294
|
+
raise TitleRenderError("cancelled")
|
|
295
|
+
if code != 0 or not output.is_file() or output.stat().st_size < 1:
|
|
296
|
+
raise TitleRenderError("ffmpeg_render_failed")
|
|
297
|
+
progress(1.0)
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def compose_dense_titles(executable,source,timeline,directory,output,cancel,custom_styles=None,progress=None,hardware=False):
|
|
301
|
+
"""One event-based RGBA stream avoids opening dozens of full-HD inputs.
|
|
302
|
+
|
|
303
|
+
Reports progress while drawing (first 40%) and while FFmpeg overlays the
|
|
304
|
+
stream (the rest), so a long film never looks stuck at the same number.
|
|
305
|
+
"""
|
|
306
|
+
report=progress or (lambda _value:None)
|
|
307
|
+
from PIL import Image,ImageDraw,ImageFont
|
|
308
|
+
from clipen.finishing.audio import run_process
|
|
309
|
+
items=[i for t in timeline.tracks if t.kind is TrackKind.TITLE for i in t.items]
|
|
310
|
+
if len(items)>(960 if timeline.production_session_id else 96):raise TitleRenderError('preview_title_limit_exceeded')
|
|
311
|
+
font=TitleCardRenderer._font_path()
|
|
312
|
+
if font is None:raise TitleRenderError('preview_title_font_missing')
|
|
313
|
+
renderer=TitleCardRenderer(custom_styles);fps=timeline.frame_rate.numerator/timeline.frame_rate.denominator
|
|
314
|
+
boundaries=sorted({0,timeline.duration_frames,*(i.start_frame for i in items),*(i.start_frame+i.duration_frames for i in items)})
|
|
315
|
+
from .program_subtitles import animation_boundaries
|
|
316
|
+
boundaries=sorted(set(boundaries)|{b for i in items if (custom_styles or {}).get(i.style_id,{}).get('kind')=='program_subtitle' for b in animation_boundaries(i)})
|
|
317
|
+
from .program_components import animation_boundaries as component_boundaries
|
|
318
|
+
boundaries=sorted(set(boundaries)|{b for i in items if (custom_styles or {}).get(i.style_id,{}).get('kind')=='program_component'
|
|
319
|
+
for b in component_boundaries(i,custom_styles[i.style_id],timeline)})
|
|
320
|
+
lines=['ffconcat version 1.0'];events=max(1,len(boundaries)-1)
|
|
321
|
+
for index,(start,end) in enumerate(zip(boundaries,boundaries[1:])):
|
|
322
|
+
if cancel.is_set():raise TitleRenderError('cancelled')
|
|
323
|
+
if index%20==0:report(.4*index/events)
|
|
324
|
+
image=Image.new('RGBA',(timeline.width,timeline.height),(0,0,0,0));draw=ImageDraw.Draw(image)
|
|
325
|
+
for item in items:
|
|
326
|
+
if item.start_frame<=start<item.start_frame+item.duration_frames:renderer._draw_card(draw,ImageFont,font,timeline,item,start-item.start_frame)
|
|
327
|
+
name=f'text-event-{index}.png';image.save(directory/name)
|
|
328
|
+
lines.extend((f"file '{name}'",f'option framerate {timeline.frame_rate.numerator}/{timeline.frame_rate.denominator}',f'duration {(end-start)/fps:.9f}'))
|
|
329
|
+
lines.extend((f"file 'text-event-{len(boundaries)-2}.png'",f'option framerate {timeline.frame_rate.numerator}/{timeline.frame_rate.denominator}'))
|
|
330
|
+
manifest=directory/'text-events.ffconcat';manifest.write_text('\n'.join(lines)+'\n')
|
|
331
|
+
report(.4)
|
|
332
|
+
seconds=timeline.duration_frames/fps;progress_file=directory/'overlay-progress.txt'
|
|
333
|
+
done=threading.Event()
|
|
334
|
+
def watch():
|
|
335
|
+
# FFmpeg rewrites out_time_us in its progress file about twice a second.
|
|
336
|
+
while not done.wait(.5):
|
|
337
|
+
try:text=progress_file.read_text()
|
|
338
|
+
except OSError:continue
|
|
339
|
+
times=[int(v) for v in re.findall(r'out_time_us=(\d+)',text)]
|
|
340
|
+
if times and seconds>0:report(.4+.6*min(1.,times[-1]/1e6/seconds))
|
|
341
|
+
watcher=threading.Thread(target=watch,daemon=True);watcher.start()
|
|
342
|
+
def encode(video):
|
|
343
|
+
run_process([executable,'-v','error','-nostdin','-y','-progress',str(progress_file),'-filter_complex_threads','2','-i',str(source),'-f','concat','-safe','0','-i',str(manifest),
|
|
344
|
+
'-filter_complex','[0:v][1:v]overlay=eof_action=repeat:format=auto,format=yuv420p[v]',
|
|
345
|
+
'-map','[v]','-map','0:a?','-t',str(timeline.duration_frames/fps),'-r',f'{timeline.frame_rate.numerator}/{timeline.frame_rate.denominator}',
|
|
346
|
+
*video,'-c:a','copy','-movflags','+faststart',str(output)],cancel,timeout=max(300,round(timeline.duration_frames/fps*3)))
|
|
347
|
+
software=['-c:v','libx264','-preset','veryfast','-crf','21']
|
|
348
|
+
try:
|
|
349
|
+
if not hardware:
|
|
350
|
+
encode(software)
|
|
351
|
+
else:
|
|
352
|
+
# The Mac's video encoder is about a third faster; any machine that refuses it gets the software path.
|
|
353
|
+
try:
|
|
354
|
+
encode(['-c:v','h264_videotoolbox','-b:v','8000k'])
|
|
355
|
+
except Exception:
|
|
356
|
+
if cancel.is_set():raise
|
|
357
|
+
encode(software)
|
|
358
|
+
finally:
|
|
359
|
+
done.set();watcher.join(timeout=2)
|
|
360
|
+
report(1.)
|