@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.
Files changed (232) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +79 -2
  3. package/apps/web/dist/assets/index-D5D2HiB1.js +14 -0
  4. package/apps/web/dist/assets/index-DIMuOXSu.css +1 -0
  5. package/apps/web/dist/favicon.svg +1 -0
  6. package/apps/web/dist/index.html +16 -0
  7. package/bin/clipen.js +157 -0
  8. package/clipen +18 -0
  9. package/install +25 -0
  10. package/package.json +52 -4
  11. package/pyproject.toml +28 -0
  12. package/requirements/asr-runtime.txt +13 -0
  13. package/requirements/runtime.txt +20 -0
  14. package/src/clipen/__init__.py +3 -0
  15. package/src/clipen/analysis/__init__.py +89 -0
  16. package/src/clipen/analysis/artifacts.py +416 -0
  17. package/src/clipen/analysis/audio.py +392 -0
  18. package/src/clipen/analysis/evidence.py +102 -0
  19. package/src/clipen/analysis/evidence_service.py +751 -0
  20. package/src/clipen/analysis/image_similarity.py +143 -0
  21. package/src/clipen/analysis/keyframes.py +171 -0
  22. package/src/clipen/analysis/models.py +230 -0
  23. package/src/clipen/analysis/qwen_worker.py +629 -0
  24. package/src/clipen/analysis/resources.py +21 -0
  25. package/src/clipen/analysis/runtime.py +64 -0
  26. package/src/clipen/analysis/service.py +626 -0
  27. package/src/clipen/analysis/setup.py +935 -0
  28. package/src/clipen/analysis/setup_cli.py +117 -0
  29. package/src/clipen/analysis/storage.py +2046 -0
  30. package/src/clipen/analysis/transcription.py +948 -0
  31. package/src/clipen/analysis/visual.py +176 -0
  32. package/src/clipen/annotations/__init__.py +10 -0
  33. package/src/clipen/annotations/models.py +22 -0
  34. package/src/clipen/annotations/storage.py +380 -0
  35. package/src/clipen/annotations/suggestions.py +120 -0
  36. package/src/clipen/asr_release.py +139 -0
  37. package/src/clipen/bootstrap.py +967 -0
  38. package/src/clipen/cli.py +84 -0
  39. package/src/clipen/controller/__init__.py +17 -0
  40. package/src/clipen/controller/app.py +1470 -0
  41. package/src/clipen/controller/server.py +543 -0
  42. package/src/clipen/domain/__init__.py +30 -0
  43. package/src/clipen/domain/errors.py +5 -0
  44. package/src/clipen/domain/media_time.py +117 -0
  45. package/src/clipen/domain/timeline.py +584 -0
  46. package/src/clipen/domain/validation.py +15 -0
  47. package/src/clipen/editing/EDITORIAL_REGRESSIONS.md +38 -0
  48. package/src/clipen/editing/PROGRAM_FORMAT.md +102 -0
  49. package/src/clipen/editing/README.md +115 -0
  50. package/src/clipen/editing/REFACTOR_DESIGN.md +241 -0
  51. package/src/clipen/editing/REFACTOR_HANDOFF.md +73 -0
  52. package/src/clipen/editing/__init__.py +15 -0
  53. package/src/clipen/editing/agent.py +13 -0
  54. package/src/clipen/editing/agent_models.py +134 -0
  55. package/src/clipen/editing/agent_repository.py +757 -0
  56. package/src/clipen/editing/agent_tools.py +532 -0
  57. package/src/clipen/editing/alignment.py +110 -0
  58. package/src/clipen/editing/alignment_setup.py +108 -0
  59. package/src/clipen/editing/alignment_worker.py +22 -0
  60. package/src/clipen/editing/change_report.py +71 -0
  61. package/src/clipen/editing/compiler.py +41 -0
  62. package/src/clipen/editing/component_looks.py +107 -0
  63. package/src/clipen/editing/component_review.py +78 -0
  64. package/src/clipen/editing/coordinator.py +374 -0
  65. package/src/clipen/editing/editorial_review.py +187 -0
  66. package/src/clipen/editing/evidence_jobs.py +295 -0
  67. package/src/clipen/editing/history_changes.py +131 -0
  68. package/src/clipen/editing/music_choices.py +15 -0
  69. package/src/clipen/editing/production_catalog.py +192 -0
  70. package/src/clipen/editing/production_limits.py +59 -0
  71. package/src/clipen/editing/production_media.py +226 -0
  72. package/src/clipen/editing/production_preview.py +180 -0
  73. package/src/clipen/editing/production_progress.py +141 -0
  74. package/src/clipen/editing/production_requirements.py +50 -0
  75. package/src/clipen/editing/production_tools.py +596 -0
  76. package/src/clipen/editing/program_audio.py +118 -0
  77. package/src/clipen/editing/program_direction.py +49 -0
  78. package/src/clipen/editing/program_story.py +53 -0
  79. package/src/clipen/editing/program_subtitles.py +134 -0
  80. package/src/clipen/editing/programme_review.py +73 -0
  81. package/src/clipen/editing/prompt_history.py +47 -0
  82. package/src/clipen/editing/recut.py +127 -0
  83. package/src/clipen/editing/refinement_references.py +188 -0
  84. package/src/clipen/editing/resolve_export.py +616 -0
  85. package/src/clipen/editing/resolve_titles.py +234 -0
  86. package/src/clipen/editing/skill_tools.py +575 -0
  87. package/src/clipen/editing/source_dialogue.py +82 -0
  88. package/src/clipen/editing/speech_coverage.py +30 -0
  89. package/src/clipen/editing/speech_quality.py +6 -0
  90. package/src/clipen/editing/tool_receipts.py +52 -0
  91. package/src/clipen/editing/versions.py +161 -0
  92. package/src/clipen/editing/visual_preview.py +93 -0
  93. package/src/clipen/editing/workbench.py +74 -0
  94. package/src/clipen/filesystem.py +25 -0
  95. package/src/clipen/finishing/README.md +103 -0
  96. package/src/clipen/finishing/__init__.py +1 -0
  97. package/src/clipen/finishing/audio.py +149 -0
  98. package/src/clipen/finishing/catalog.py +181 -0
  99. package/src/clipen/finishing/models.py +14 -0
  100. package/src/clipen/finishing/renderer.py +26 -0
  101. package/src/clipen/mcp_editing/__init__.py +5 -0
  102. package/src/clipen/mcp_editing/__main__.py +40 -0
  103. package/src/clipen/mcp_editing/server.py +353 -0
  104. package/src/clipen/media/__init__.py +50 -0
  105. package/src/clipen/media/discovery.py +266 -0
  106. package/src/clipen/media/models.py +360 -0
  107. package/src/clipen/media/preview.py +147 -0
  108. package/src/clipen/media/probe.py +446 -0
  109. package/src/clipen/media/service.py +317 -0
  110. package/src/clipen/media/storage.py +742 -0
  111. package/src/clipen/music_vocabulary.py +5 -0
  112. package/src/clipen/planning/__init__.py +9 -0
  113. package/src/clipen/planning/models.py +240 -0
  114. package/src/clipen/power.py +23 -0
  115. package/src/clipen/projects/__init__.py +26 -0
  116. package/src/clipen/projects/agent_schema.py +94 -0
  117. package/src/clipen/projects/annotation_schema.py +40 -0
  118. package/src/clipen/projects/deletion.py +269 -0
  119. package/src/clipen/projects/evidence_schema.py +52 -0
  120. package/src/clipen/projects/finishing_schema.py +34 -0
  121. package/src/clipen/projects/models.py +192 -0
  122. package/src/clipen/projects/picker.py +256 -0
  123. package/src/clipen/projects/preview_schema.py +29 -0
  124. package/src/clipen/projects/service.py +175 -0
  125. package/src/clipen/projects/storage.py +1478 -0
  126. package/src/clipen/projects/timeline_schema.py +32 -0
  127. package/src/clipen/projects/validation_schema.py +28 -0
  128. package/src/clipen/provider_registry.py +75 -0
  129. package/src/clipen/providers/__init__.py +43 -0
  130. package/src/clipen/providers/account.py +194 -0
  131. package/src/clipen/providers/claude.py +375 -0
  132. package/src/clipen/providers/claude_editing.py +111 -0
  133. package/src/clipen/providers/codex.py +1036 -0
  134. package/src/clipen/providers/codex_editing.py +91 -0
  135. package/src/clipen/providers/editing_agent.py +565 -0
  136. package/src/clipen/providers/errors.py +51 -0
  137. package/src/clipen/providers/recovery.py +270 -0
  138. package/src/clipen/py.typed +1 -0
  139. package/src/clipen/rendering/__init__.py +12 -0
  140. package/src/clipen/rendering/cover.py +126 -0
  141. package/src/clipen/rendering/custom_components.py +240 -0
  142. package/src/clipen/rendering/custom_render.py +197 -0
  143. package/src/clipen/rendering/fonts/anton-OFL.txt +93 -0
  144. package/src/clipen/rendering/fonts/bebasneue-OFL.txt +93 -0
  145. package/src/clipen/rendering/fonts/caveat-OFL.txt +93 -0
  146. package/src/clipen/rendering/fonts/chenyu-OFL.txt +93 -0
  147. package/src/clipen/rendering/fonts/delagothicone-OFL.txt +93 -0
  148. package/src/clipen/rendering/fonts/hachimarupop-OFL.txt +93 -0
  149. package/src/clipen/rendering/fonts/iansui-OFL.txt +93 -0
  150. package/src/clipen/rendering/fonts/manifest.json +145 -0
  151. package/src/clipen/rendering/fonts/playfairdisplay-OFL.txt +93 -0
  152. package/src/clipen/rendering/fonts/rocknrollone-OFL.txt +93 -0
  153. package/src/clipen/rendering/fonts/yomogi-OFL.txt +94 -0
  154. package/src/clipen/rendering/fonts/yuseimagic-OFL.txt +93 -0
  155. package/src/clipen/rendering/fonts/zenkurenaido-OFL.txt +93 -0
  156. package/src/clipen/rendering/fonts/zenmarugothic-OFL.txt +93 -0
  157. package/src/clipen/rendering/production_effects.py +64 -0
  158. package/src/clipen/rendering/program_components.py +193 -0
  159. package/src/clipen/rendering/program_creator.py +649 -0
  160. package/src/clipen/rendering/program_identities.py +255 -0
  161. package/src/clipen/rendering/program_motion.py +141 -0
  162. package/src/clipen/rendering/program_studio.py +168 -0
  163. package/src/clipen/rendering/program_styles.py +235 -0
  164. package/src/clipen/rendering/program_subtitles.py +52 -0
  165. package/src/clipen/rendering/renderer.py +708 -0
  166. package/src/clipen/rendering/storage.py +243 -0
  167. package/src/clipen/rendering/titles.py +360 -0
  168. package/src/clipen/skills/__init__.py +4 -0
  169. package/src/clipen/skills/builtin/SKILL.md +72 -0
  170. package/src/clipen/skills/builtin/assets/sample-daily-vlog.mp4 +0 -0
  171. package/src/clipen/skills/builtin/assets/sample-event-recap.mp4 +0 -0
  172. package/src/clipen/skills/builtin/assets/sample-food-review.mp4 +0 -0
  173. package/src/clipen/skills/builtin/assets/sample-product-demo.mp4 +0 -0
  174. package/src/clipen/skills/builtin/assets/sample-product-review.mp4 +0 -0
  175. package/src/clipen/skills/builtin/assets/sample-product-unboxing.mp4 +0 -0
  176. package/src/clipen/skills/builtin/assets/sample-shorts-highlight.mp4 +0 -0
  177. package/src/clipen/skills/builtin/assets/sample-travel-highlight.mp4 +0 -0
  178. package/src/clipen/skills/builtin/assets/sample-travel-vlog.mp4 +0 -0
  179. package/src/clipen/skills/builtin/assets/style-cinema.png +0 -0
  180. package/src/clipen/skills/builtin/assets/style-editorial.png +0 -0
  181. package/src/clipen/skills/builtin/assets/style-tpl-daily-vlog.png +0 -0
  182. package/src/clipen/skills/builtin/assets/style-tpl-event-recap.png +0 -0
  183. package/src/clipen/skills/builtin/assets/style-tpl-food-review.png +0 -0
  184. package/src/clipen/skills/builtin/assets/style-tpl-product-demo.png +0 -0
  185. package/src/clipen/skills/builtin/assets/style-tpl-product-review.png +0 -0
  186. package/src/clipen/skills/builtin/assets/style-tpl-product-unboxing.png +0 -0
  187. package/src/clipen/skills/builtin/assets/style-tpl-shorts-highlight.png +0 -0
  188. package/src/clipen/skills/builtin/assets/style-tpl-travel-highlight.png +0 -0
  189. package/src/clipen/skills/builtin/assets/style-tpl-travel-vlog.png +0 -0
  190. package/src/clipen/skills/builtin/assets/style-variety.png +0 -0
  191. package/src/clipen/skills/builtin/components.json +133 -0
  192. package/src/clipen/skills/builtin/font_sources.json +20 -0
  193. package/src/clipen/skills/builtin/font_styles.json +329 -0
  194. package/src/clipen/skills/builtin/manifest.json +32 -0
  195. package/src/clipen/skills/builtin/presets.json +8 -0
  196. package/src/clipen/skills/builtin/references/captions.md +14 -0
  197. package/src/clipen/skills/builtin/references/channel-design.md +37 -0
  198. package/src/clipen/skills/builtin/references/editing.md +30 -0
  199. package/src/clipen/skills/builtin/references/font-chenyu-OFL.txt +93 -0
  200. package/src/clipen/skills/builtin/references/font-iansui-OFL.txt +93 -0
  201. package/src/clipen/skills/builtin/references/graphics.md +59 -0
  202. package/src/clipen/skills/builtin/references/review.md +16 -0
  203. package/src/clipen/skills/builtin/references/sound.md +8 -0
  204. package/src/clipen/skills/builtin/references/story.md +7 -0
  205. package/src/clipen/skills/builtin/skills/travel-program/SKILL.md +27 -0
  206. package/src/clipen/skills/builtin/skills/travel-program/manifest.json +6 -0
  207. package/src/clipen/skills/builtin/template-skills/clipen-daily-vlog/SKILL.md +33 -0
  208. package/src/clipen/skills/builtin/template-skills/clipen-daily-vlog/manifest.json +8 -0
  209. package/src/clipen/skills/builtin/template-skills/clipen-event-recap/SKILL.md +34 -0
  210. package/src/clipen/skills/builtin/template-skills/clipen-event-recap/manifest.json +8 -0
  211. package/src/clipen/skills/builtin/template-skills/clipen-food-review/SKILL.md +33 -0
  212. package/src/clipen/skills/builtin/template-skills/clipen-food-review/manifest.json +8 -0
  213. package/src/clipen/skills/builtin/template-skills/clipen-product-demo/SKILL.md +35 -0
  214. package/src/clipen/skills/builtin/template-skills/clipen-product-demo/manifest.json +8 -0
  215. package/src/clipen/skills/builtin/template-skills/clipen-product-review/SKILL.md +36 -0
  216. package/src/clipen/skills/builtin/template-skills/clipen-product-review/manifest.json +8 -0
  217. package/src/clipen/skills/builtin/template-skills/clipen-product-unboxing/SKILL.md +39 -0
  218. package/src/clipen/skills/builtin/template-skills/clipen-product-unboxing/manifest.json +8 -0
  219. package/src/clipen/skills/builtin/template-skills/clipen-shorts-highlight/SKILL.md +38 -0
  220. package/src/clipen/skills/builtin/template-skills/clipen-shorts-highlight/manifest.json +8 -0
  221. package/src/clipen/skills/builtin/template-skills/clipen-travel-highlight/SKILL.md +34 -0
  222. package/src/clipen/skills/builtin/template-skills/clipen-travel-highlight/manifest.json +8 -0
  223. package/src/clipen/skills/builtin/template-skills/clipen-travel-vlog/SKILL.md +37 -0
  224. package/src/clipen/skills/builtin/template-skills/clipen-travel-vlog/manifest.json +8 -0
  225. package/src/clipen/skills/builtin/templates.json +284 -0
  226. package/src/clipen/skills/builtin/visual_styles.json +1074 -0
  227. package/src/clipen/skills/catalog.py +218 -0
  228. package/src/clipen/skills/library.py +131 -0
  229. package/src/clipen/skills/package.py +231 -0
  230. package/src/clipen/skills/visual_styles.py +44 -0
  231. package/src/clipen/workspace.py +210 -0
  232. package/uninstall +25 -0
@@ -0,0 +1,616 @@
1
+ """Hand the current film to DaVinci Resolve for hands-on editing.
2
+
3
+ The package holds an FCPXML timeline that points at the original footage, the
4
+ on-screen components as transparent PNGs, the captions as SRT, and the music.
5
+ Shots whose look cannot be rebuilt from the original footage (mosaic, speed
6
+ ramps) are rendered to ProRes first so nothing hidden by a mosaic is revealed.
7
+ Everything Resolve cannot take from FCPXML is left as a marker and in 說明.txt.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ from dataclasses import replace
12
+ from datetime import datetime
13
+ from fractions import Fraction
14
+ import json
15
+ import os
16
+ from pathlib import Path
17
+ import re
18
+ import shutil
19
+ import subprocess
20
+ import tempfile
21
+ import threading
22
+ import time
23
+ import xml.etree.ElementTree as ET
24
+
25
+ from clipen.domain import MediaClip, Track, TrackKind
26
+ from clipen.projects import ProjectError
27
+
28
+ # Effects that change which pixels or frames appear, so the shot is rendered as is.
29
+ BURNED = frozenset({'video.mosaic', 'video.speed_ramp'})
30
+ _FRAMING = frozenset({'video.punch_in', 'video.reframe', 'video.slow_push'})
31
+ _UNSAFE_NAME = re.compile(r'[\x00-\x1f/:\\]+')
32
+
33
+
34
+ def seconds(value: Fraction) -> str:
35
+ """An exact FCPXML time value."""
36
+ if value == 0:
37
+ return '0s'
38
+ return f'{value.numerator}s' if value.denominator == 1 else f'{value.numerator}/{value.denominator}s'
39
+
40
+
41
+ def timecode_seconds(timecode: str, rate: Fraction) -> Fraction:
42
+ """Seconds from a file's start timecode, so Resolve and the FCPXML agree on source time."""
43
+ match = re.fullmatch(r'(\d{1,2}):(\d{2}):(\d{2})([:;.])(\d{2,3})', timecode.strip())
44
+ if not match:
45
+ return Fraction(0)
46
+ hours, minutes, secs, separator, frames = match.groups()
47
+ nominal = max(1, round(rate))
48
+ count = ((int(hours) * 60 + int(minutes)) * 60 + int(secs)) * nominal + int(frames)
49
+ if separator in ';.' and rate.denominator == 1001:
50
+ dropped = nominal // 15
51
+ total_minutes = int(hours) * 60 + int(minutes)
52
+ count -= dropped * (total_minutes - total_minutes // 10)
53
+ return count / rate
54
+
55
+
56
+ def probe(path: Path) -> dict:
57
+ """Timecode, rotation and display size, which the project inventory does not keep."""
58
+ completed = subprocess.run(
59
+ ['ffprobe', '-v', 'error', '-print_format', 'json', '-show_entries',
60
+ 'format_tags=timecode:stream=index,codec_type,width,height:stream_tags=timecode,rotate:stream_side_data=rotation',
61
+ str(path)],
62
+ stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=60, check=False)
63
+ if completed.returncode != 0:
64
+ raise ProjectError('resolve_source_unreadable', f'無法讀取素材 {path.name},請確認檔案還在。', status_code=409)
65
+ data = json.loads(completed.stdout or '{}')
66
+ streams = data.get('streams', [])
67
+ timecode = data.get('format', {}).get('tags', {}).get('timecode') or next(
68
+ (s.get('tags', {}).get('timecode') for s in streams if s.get('tags', {}).get('timecode')), None)
69
+ return {'timecode': timecode, 'streams': {s.get('index'): s for s in streams}}
70
+
71
+
72
+ def _rotation(stream: dict) -> int:
73
+ for side in stream.get('side_data_list', []):
74
+ if 'rotation' in side:
75
+ return int(float(side['rotation']))
76
+ return int(float(stream.get('tags', {}).get('rotate', 0) or 0))
77
+
78
+
79
+ def _safe_name(value: str) -> str:
80
+ return _UNSAFE_NAME.sub(' ', value).strip(' .') or 'Clipen'
81
+
82
+
83
+ def _unique(directory: Path, name: str) -> Path:
84
+ candidate, number = directory / name, 2
85
+ while candidate.exists():
86
+ stem, suffix = os.path.splitext(name)
87
+ candidate, number = directory / f'{stem} ({number}){suffix}', number + 1
88
+ return candidate
89
+
90
+
91
+ def _srt_time(value: Fraction) -> str:
92
+ milliseconds = round(value * 1000)
93
+ hours, rest = divmod(milliseconds, 3_600_000)
94
+ minutes, rest = divmod(rest, 60_000)
95
+ secs, milliseconds = divmod(rest, 1000)
96
+ return f'{hours:02d}:{minutes:02d}:{secs:02d},{milliseconds:03d}'
97
+
98
+
99
+ def _lanes(intervals, first: int, step: int) -> list[int]:
100
+ """Give overlapping items their own lane, reusing lanes once an item has ended."""
101
+ ends: list[int] = []
102
+ lanes = []
103
+ for start, end in intervals:
104
+ for index, last in enumerate(ends):
105
+ if last <= start:
106
+ ends[index] = end
107
+ lanes.append(first + index * step)
108
+ break
109
+ else:
110
+ ends.append(end)
111
+ lanes.append(first + (len(ends) - 1) * step)
112
+ return lanes
113
+
114
+
115
+ def _framing(item: MediaClip):
116
+ """Clipen's zoom and crop window as Resolve zoom and position (FCPXML position is % of frame height)."""
117
+ scale, center_x, center_y, push = 1.0, .5, .5, None
118
+ for effect in item.effects:
119
+ p = effect.parameters
120
+ if effect.effect_id == 'video.punch_in':
121
+ scale = min(2.0, max(1.01, float(p.get('scale', 1.08))))
122
+ center_x = min(1.0, max(0.0, float(p.get('center_x', .5))))
123
+ center_y = min(1.0, max(0.0, float(p.get('center_y', .5))))
124
+ elif effect.effect_id == 'video.reframe':
125
+ scale = 1.08
126
+ center_x = min(1.0, max(0.0, float(p.get('x', .5))))
127
+ center_y = min(1.0, max(0.0, float(p.get('y', .5))))
128
+ elif effect.effect_id == 'video.slow_push':
129
+ push = (min(2.0, max(1.0, float(p.get('scale_from', 1.0)))), min(2.0, max(1.0, float(p.get('scale_to', 1.08)))))
130
+ return scale, center_x, center_y, push
131
+
132
+
133
+ class _Builder:
134
+ def __init__(self, timeline, name):
135
+ self.timeline = timeline
136
+ self.fps = Fraction(timeline.frame_rate.numerator, timeline.frame_rate.denominator)
137
+ self.root = ET.Element('fcpxml', version='1.10')
138
+ self.resources = ET.SubElement(self.root, 'resources')
139
+ self.formats: dict[tuple, str] = {}
140
+ self.assets: dict[str, str] = {}
141
+ self.count = 0
142
+ self.sequence_format = self.format(timeline.width, timeline.height, 1 / self.fps, 'Clipen')
143
+ library = ET.SubElement(self.root, 'library')
144
+ event = ET.SubElement(library, 'event', name='Clipen')
145
+ project = ET.SubElement(event, 'project', name=name)
146
+ self.sequence = ET.SubElement(project, 'sequence', format=self.sequence_format,
147
+ duration=seconds(self.time(timeline.duration_frames)),
148
+ tcStart='0s', tcFormat='NDF', audioLayout='stereo', audioRate='48k')
149
+ self.spine = ET.SubElement(self.sequence, 'spine')
150
+ self.parents: list[tuple[int, int, ET.Element, Fraction]] = []
151
+
152
+ def time(self, frames) -> Fraction:
153
+ return Fraction(frames) / self.fps
154
+
155
+ def ident(self) -> str:
156
+ self.count += 1
157
+ return f'r{self.count}'
158
+
159
+ def format(self, width, height, frame_duration: Fraction | None, name=None) -> str:
160
+ key = (width, height, frame_duration)
161
+ if key not in self.formats:
162
+ ident = self.ident()
163
+ attributes = {'id': ident, 'width': str(width), 'height': str(height)}
164
+ if frame_duration is None:
165
+ attributes['name'] = 'FFVideoFormatRateUndefined'
166
+ else:
167
+ attributes['frameDuration'] = seconds(frame_duration)
168
+ if name:
169
+ attributes['name'] = name
170
+ ET.SubElement(self.resources, 'format', attributes)
171
+ self.formats[key] = ident
172
+ return self.formats[key]
173
+
174
+ def asset(self, path: Path, name: str, start: Fraction, duration: Fraction, *, video=None, audio=None) -> str:
175
+ key = str(path)
176
+ if key in self.assets:
177
+ return self.assets[key]
178
+ ident = self.ident()
179
+ attributes = {'id': ident, 'name': name, 'start': seconds(start), 'duration': seconds(duration)}
180
+ if video:
181
+ attributes.update(hasVideo='1', videoSources='1', format=video)
182
+ if audio:
183
+ channels, rate = audio
184
+ attributes.update(hasAudio='1', audioSources='1', audioChannels=str(channels), audioRate=str(rate))
185
+ element = ET.SubElement(self.resources, 'asset', attributes)
186
+ ET.SubElement(element, 'media-rep', kind='original-media', src=path.resolve().as_uri())
187
+ self.assets[key] = ident
188
+ return ident
189
+
190
+ def place(self, element, offset_frames, duration_frames, local_start: Fraction):
191
+ self.spine.append(element)
192
+ self.parents.append((offset_frames, duration_frames, element, local_start))
193
+
194
+ def gap(self, offset_frames, duration_frames):
195
+ element = ET.Element('gap', name='Gap', offset=seconds(self.time(offset_frames)),
196
+ start='0s', duration=seconds(self.time(duration_frames)))
197
+ self.place(element, offset_frames, duration_frames, Fraction(0))
198
+
199
+ def connect(self, tag, attributes, frame):
200
+ """Attach an item at a timeline frame to the storyline clip under it."""
201
+ parent = next((p for p in self.parents if p[0] <= frame < p[0] + p[1]), self.parents[-1])
202
+ offset_frames, _, element, local_start = parent
203
+ attributes = {**attributes, 'offset': seconds(local_start + self.time(frame - offset_frames))}
204
+ return ET.SubElement(element, tag, attributes)
205
+
206
+ def marker(self, element, local_start: Fraction, frames, value, note=''):
207
+ ET.SubElement(element, 'marker', start=seconds(local_start + self.time(frames)),
208
+ duration=seconds(1 / self.fps), value=value, **({'note': note} if note else {}))
209
+
210
+ def write(self, path: Path):
211
+ ET.indent(self.root)
212
+ body = ET.tostring(self.root, encoding='unicode')
213
+ path.write_text('<?xml version="1.0" encoding="UTF-8"?>\n<!DOCTYPE fcpxml>\n\n' + body + '\n', encoding='utf-8')
214
+
215
+
216
+ def _is_caption(track, item, styles) -> bool:
217
+ return track.track_id == 'agent-subtitles' or styles.get(item.style_id, {}).get('kind') == 'program_subtitle'
218
+
219
+
220
+ def export_folder(repository, project_id: str) -> Path:
221
+ """「Clipen 匯出」inside the footage folder: the App Store Resolve reads only folders the user opens,
222
+ so one 'Locate' on the footage folder lets it find the footage and the package together."""
223
+ from clipen.media.discovery import EXPORT_FOLDER
224
+ from clipen.projects import DirectoryRole
225
+ source = next((d for d in repository.projects.get_project(project_id).directories if d.role is DirectoryRole.SOURCE), None)
226
+ if source is None or not Path(source.canonical_path).is_dir():
227
+ raise ProjectError('resolve_source_offline', '找不到毛片資料夾,請確認外接硬碟已連接。', status_code=409)
228
+ folder = Path(source.canonical_path) / EXPORT_FOLDER
229
+ folder.mkdir(exist_ok=True)
230
+ return folder
231
+
232
+
233
+ def export_resolve(repository, project_id: str, run_id: str, destination: Path | None = None, cancel: threading.Event | None = None) -> dict:
234
+ """Write a Resolve package into a new folder (beside the footage unless told otherwise) and describe it."""
235
+ cancel = cancel or threading.Event()
236
+ destination = destination or export_folder(repository, project_id)
237
+ revision = repository.current_revision(project_id, run_id)
238
+ timeline = revision.timeline
239
+ video = next((t for t in timeline.tracks if t.kind is TrackKind.VIDEO and t.items), None)
240
+ if video is None:
241
+ raise ProjectError('resolve_video_required', '這一版還沒有畫面,無法匯出。', status_code=409)
242
+ project_name = repository.projects.get_project(project_id).name
243
+ name = _safe_name(f'{project_name} {datetime.now():%Y-%m-%d %H%M}')
244
+ package = _unique(destination, f'{name} DaVinci Resolve')
245
+ package.mkdir()
246
+ try:
247
+ return _write(repository, project_id, package, name, timeline, video, cancel)
248
+ except Exception:
249
+ shutil.rmtree(package, ignore_errors=True)
250
+ raise
251
+
252
+
253
+ def _write(repository, project_id, package, name, timeline, video, cancel):
254
+ from clipen.finishing.audio import open_asset
255
+ from clipen.media.preview import MediaPreviewRepository
256
+ from clipen.rendering.renderer import FfmpegPreviewRenderer, PreviewRenderError
257
+ from clipen.rendering.titles import TitleCardRenderer, TitleRenderError
258
+ from .production_media import AgentAudioStore, load_text_styles
259
+ media = MediaPreviewRepository(repository.projects)
260
+ styles = load_text_styles(repository.projects, project_id)
261
+ build = _Builder(timeline, name)
262
+ notes: list[str] = []
263
+ probes: dict[Path, dict] = {}
264
+ burned = 0
265
+
266
+ # 1. Shots on the main storyline.
267
+ cursor = 0
268
+ for index, item in enumerate(sorted(video.items, key=lambda i: i.start_frame), 1):
269
+ if cancel.is_set():
270
+ raise ProjectError('cancelled', '已取消匯出。', status_code=409)
271
+ if item.start_frame > cursor:
272
+ build.gap(cursor, item.start_frame - cursor)
273
+ duration = build.time(item.duration_frames)
274
+ clock = f'{int(build.time(item.start_frame) // 60)}:{int(build.time(item.start_frame) % 60):02d}'
275
+ if any(e.effect_id in BURNED for e in item.effects):
276
+ directory = package / '已處理片段'
277
+ directory.mkdir(exist_ok=True)
278
+ output = directory / f'{index:03d} {clock.replace(":", "m")}s.mov'
279
+ kept = tuple(e for e in item.effects if e.effect_id in BURNED | _FRAMING)
280
+ single = replace(timeline, duration_frames=item.duration_frames, markers=(),
281
+ tracks=(Track(video.track_id, TrackKind.VIDEO, (replace(item, start_frame=0, effects=kept),)),))
282
+ try:
283
+ FfmpegPreviewRenderer(media, master=True)._render_media(project_id, single, output, cancel, lambda _: None, preserve_audio_gain=True)
284
+ except PreviewRenderError as error:
285
+ raise ProjectError('resolve_render_failed', f'{clock} 的片段無法輸出({error.code})。', status_code=500) from error
286
+ info = probe(output)
287
+ has_audio = any(s.get('codec_type') == 'audio' for s in info['streams'].values())
288
+ ref = build.asset(output, output.stem, Fraction(0), duration,
289
+ video=build.sequence_format, audio=(2, 48000) if has_audio else None)
290
+ start = Fraction(0)
291
+ burned += 1
292
+ what = '、'.join(label for effect, label in (('video.mosaic', '馬賽克'), ('video.speed_ramp', '變速'))
293
+ if any(e.effect_id == effect for e in item.effects))
294
+ notes.append(f'{clock} 的鏡頭已先輸出成 ProRes(含{what}與構圖),放在「已處理片段」;原始素材不會出現在時間軸上。')
295
+ framing = None
296
+ label = f'{clock} 已處理'
297
+ else:
298
+ path, streams = media.locate(project_id, item.source.span.version_id)
299
+ span = item.source.span
300
+ stream = streams.get(span.stream_index, {})
301
+ if path not in probes:
302
+ probes[path] = probe(path)
303
+ info = probes[path]
304
+ shown = info['streams'].get(span.stream_index, {})
305
+ try:
306
+ rate = Fraction(stream.get('r_frame_rate') or stream.get('avg_frame_rate') or '30')
307
+ except (ValueError, ZeroDivisionError):
308
+ rate = Fraction(0)
309
+ rate = rate or build.fps
310
+ width, height = shown.get('width') or stream.get('width'), shown.get('height') or stream.get('height')
311
+ if _rotation(shown) % 180:
312
+ width, height = height, width
313
+ time_base = Fraction(span.time_base.numerator, span.time_base.denominator)
314
+ stream_start = int(stream.get('start_pts', 0) or 0)
315
+ origin = timecode_seconds(info['timecode'], rate) if info['timecode'] else Fraction(0)
316
+ length = int(stream['duration_ts']) * Fraction(stream['time_base']) if stream.get('duration_ts') and stream.get('time_base') else duration
317
+ audio = next((s for s in streams.values() if s['kind'] == 'audio'), None)
318
+ ref = build.asset(path, path.stem, origin, length,
319
+ video=build.format(width, height, 1 / rate),
320
+ audio=(audio.get('channels', 2), audio.get('sample_rate', 48000)) if audio else None)
321
+ start = origin + (int(span.start_pts) - stream_start) * time_base
322
+ framing = _framing(item)
323
+ label = path.stem
324
+ clip = ET.Element('asset-clip', ref=ref, offset=seconds(build.time(item.start_frame)), name=label,
325
+ start=seconds(start), duration=seconds(duration), tcFormat='NDF', audioRole='dialogue')
326
+ ET.SubElement(clip, 'adjust-conform', type='fit')
327
+ if framing:
328
+ scale, center_x, center_y, push = framing
329
+ shift_x = (scale - 1) * timeline.width * (.5 - center_x) / timeline.height * 100
330
+ shift_y = -(scale - 1) * (.5 - center_y) * 100 + 0.0 # no '-0.0000'
331
+ if scale != 1 or push:
332
+ transform = ET.SubElement(clip, 'adjust-transform', position=f'{shift_x:.4f} {shift_y:.4f}', scale=f'{scale:.4f} {scale:.4f}')
333
+ if push:
334
+ animation = ET.SubElement(ET.SubElement(transform, 'param', name='scale'), 'keyframeAnimation')
335
+ for at, value in ((start, push[0] * scale), (start + duration - 1 / build.fps, push[1] * scale)):
336
+ ET.SubElement(animation, 'keyframe', time=seconds(at), value=f'{value:.4f} {value:.4f}')
337
+ policy = next((e.parameters for e in item.effects if e.effect_id == 'audio.source'), None)
338
+ if policy:
339
+ gain = -96 if policy['mode'] == 'mute' else float(policy['gain_db'])
340
+ ET.SubElement(clip, 'adjust-volume', amount=f'{gain:g}dB')
341
+ build.place(clip, item.start_frame, item.duration_frames, start)
342
+
343
+ # Looks Resolve cannot take from FCPXML stay as markers on the shot.
344
+ if framing is None:
345
+ build.marker(clip, start, 0, 'Clipen 已處理片段', '這段已套用馬賽克或變速並輸出成 ProRes;原始素材不在時間線上。')
346
+ if policy and policy['mode'] == 'dialogue':
347
+ build.marker(clip, start, 0, 'Clipen 對白處理', '高通 85 Hz、低通 11 kHz、輕微壓縮;請在 Fairlight 重做。')
348
+ grade = next((e.parameters for e in item.effects if e.effect_id == 'video.grade'), None)
349
+ if grade:
350
+ build.marker(clip, start, 0, 'Clipen 調色',
351
+ f'對比 {float(grade["contrast"]):.2f}、飽和度 {float(grade["saturation"]):.2f}、亮度 {float(grade["brightness"]):+.2f};請在調色頁重調。')
352
+ notes.append(f'{clock} 的鏡頭有調色,數值記在標記裡。')
353
+ for effect in item.effects:
354
+ p = effect.parameters
355
+ if effect.effect_id == 'video.transition' and p.get('kind') != 'none':
356
+ color = '白' if p['kind'] == 'dip_white' else '黑'
357
+ build.marker(clip, start, 0, f'Clipen 轉場:淡入淡出{color}場', f'共 {p["duration_frames"]} 格,前後兩個鏡頭各一半。')
358
+ notes.append(f'{clock} 有淡入淡出{color}場轉場,請在 Resolve 加上 Dip to Color Dissolve。')
359
+ elif effect.effect_id == 'video.transition_out':
360
+ color = '白' if p.get('kind') == 'dip_white' else '黑'
361
+ build.marker(clip, start, max(0, item.duration_frames - p['duration_frames'] // 2), f'Clipen 轉場:淡出到{color}場', f'共 {p["duration_frames"] // 2} 格。')
362
+ elif effect.effect_id == 'video.fade':
363
+ if p.get('fade_in_frames'):
364
+ build.marker(clip, start, 0, 'Clipen 淡入', f'從黑場淡入 {p["fade_in_frames"]} 格。')
365
+ if p.get('fade_out_frames'):
366
+ build.marker(clip, start, item.duration_frames - p['fade_out_frames'], 'Clipen 淡出', f'淡出到黑場 {p["fade_out_frames"]} 格。')
367
+ if p.get('fade_in_frames') or p.get('fade_out_frames'):
368
+ notes.append(f'{clock} 的鏡頭有淡入或淡出,請在 Resolve 補上。')
369
+ cursor = item.start_frame + item.duration_frames
370
+ if cursor < timeline.duration_frames:
371
+ build.gap(cursor, timeline.duration_frames - cursor)
372
+
373
+ # 2. Components and titles as transparent stills; captions as an editable SRT.
374
+ captions, overlays = [], []
375
+ for track in timeline.tracks:
376
+ if track.kind is not TrackKind.TITLE:
377
+ continue
378
+ for item in track.items:
379
+ (captions if _is_caption(track, item, styles) else overlays).append((track, item))
380
+ rendered, editable = [], 0
381
+ if overlays:
382
+ directory = package / '元件'
383
+ directory.mkdir()
384
+ with tempfile.TemporaryDirectory(dir=package) as temporary:
385
+ images = []
386
+ try:
387
+ # The renderer caps one pass for FFmpeg's sake; stills for Resolve go batch by batch.
388
+ size = TitleCardRenderer._MAX_TITLES
389
+ for first in range(0, len(overlays), size):
390
+ batch = overlays[first:first + size]
391
+ only = replace(timeline, tracks=tuple(Track(f'overlay-{n}', TrackKind.TITLE, (item,)) for n, (_, item) in enumerate(batch)))
392
+ folder = Path(temporary) / str(first)
393
+ folder.mkdir()
394
+ images += TitleCardRenderer(styles).render(only, folder)
395
+ except TitleRenderError as error:
396
+ raise ProjectError('resolve_overlay_failed', f'元件圖片無法產生({error.code})。', status_code=500) from error
397
+ for number, ((_, item), image) in enumerate(zip(overlays, images), 1):
398
+ label = _safe_name(item.text.split('\n', 1)[0])[:40]
399
+ target = directory / f'{number:03d} {label}.png'
400
+ shutil.move(str(image.path), target)
401
+ rendered.append((item, target, label))
402
+ editable = _editable_titles(directory, rendered, styles, timeline)
403
+ still = build.format(timeline.width, timeline.height, None)
404
+ for (item, target, label), lane in zip(rendered, _lanes([(i.start_frame, i.start_frame + i.duration_frames) for i, _, _ in rendered], 1, 1)):
405
+ ref = build.asset(target, target.stem, Fraction(0), Fraction(0), video=still)
406
+ build.connect('video', {'ref': ref, 'lane': str(lane), 'name': label, 'start': '0s',
407
+ 'duration': seconds(build.time(item.duration_frames))}, item.start_frame)
408
+ notes.append(f'畫面元件 {len(rendered)} 個先以透明 PNG 放在影片上層,位置和外觀與 Clipen 相同,彈出動畫不會保留。'
409
+ + (f'其中 {editable} 個可以換成能改字的 DaVinci 標題,做法見上面「想在 Resolve 改元件的字」。' if editable else ''))
410
+ if captions:
411
+ lines = []
412
+ for number, (_, item) in enumerate(sorted(captions, key=lambda pair: pair[1].start_frame), 1):
413
+ lines += [str(number), f'{_srt_time(build.time(item.start_frame))} --> {_srt_time(build.time(item.start_frame + item.duration_frames))}', item.text.strip(), '']
414
+ (package / '字幕.srt').write_text('\n'.join(lines), encoding='utf-8')
415
+
416
+ # 3. Music: the stem Clipen mixed (ducked under speech), plus each source muted for rework.
417
+ layers = [(i, l) for t in timeline.tracks for i in t.items if isinstance(i, MediaClip)
418
+ for e in i.effects if e.effect_id == 'audio.layers' for l in e.parameters['layers']]
419
+ if layers:
420
+ from .program_audio import render_music_stem
421
+ directory = package / '音樂'
422
+ directory.mkdir()
423
+ stem = directory / '配樂(Clipen 混音).wav'
424
+ settings, _ = render_music_stem(media, project_id, timeline, stem, cancel)
425
+ total = build.time(timeline.duration_frames)
426
+ ref = build.asset(stem, stem.stem, Fraction(0), total, audio=(2, 48000))
427
+ build.connect('asset-clip', {'ref': ref, 'lane': '-1', 'name': stem.stem, 'start': '0s',
428
+ 'duration': seconds(total), 'audioRole': 'music'}, 0)
429
+ store = AgentAudioStore(repository.projects, project_id)
430
+ copies: dict[str, tuple[Path, dict]] = {}
431
+ spans = [(clip.start_frame + layer['start_frame'], clip.start_frame + layer['start_frame'] + layer['duration_frames']) for clip, layer in layers]
432
+ for (clip, layer), setting, lane in zip(layers, settings, _lanes(spans, -2, -1)):
433
+ if layer['asset_id'] not in copies:
434
+ fd, asset = open_asset(store.context(layer['asset_id']), layer['asset_id'])
435
+ with os.fdopen(fd, 'rb') as source:
436
+ target = _unique(directory, _safe_name(Path(asset['relative_path']).name))
437
+ with target.open('wb') as copy:
438
+ shutil.copyfileobj(source, copy)
439
+ copies[layer['asset_id']] = (target, asset)
440
+ target, asset = copies[layer['asset_id']]
441
+ length = Fraction(round(asset['duration_seconds'] * 48000), 48000)
442
+ ref = build.asset(target, target.stem, Fraction(0), length, audio=(2, 48000))
443
+ element = build.connect('asset-clip', {'ref': ref, 'lane': str(lane), 'name': f'{target.stem}(原始)', 'enabled': '0',
444
+ 'start': seconds(Fraction(round(layer['source_offset_seconds'] * 48000), 48000)),
445
+ 'duration': seconds(build.time(layer['duration_frames'])), 'audioRole': 'music'},
446
+ clip.start_frame + layer['start_frame'])
447
+ ET.SubElement(element, 'adjust-volume', amount=f'{setting["normalization_db"] + layer["gain_db"]:.2f}dB')
448
+ notes.append('配樂分兩層:「配樂(Clipen 混音)」是 Clipen 混好的成品(講話時自動壓低、含淡入淡出);下方停用的「原始」音軌是各段原始音樂,要重新混音時啟用它們並關掉混音層。')
449
+
450
+ fcpxml = package / f'{name}.fcpxml'
451
+ build.write(fcpxml)
452
+ _guide(package, fcpxml, bool(captions), editable, notes)
453
+ return {'folder': str(package), 'fcpxml': str(fcpxml), 'shots': len(video.items), 'burned': burned,
454
+ 'overlays': len(rendered), 'editable_overlays': editable, 'captions': len(captions),
455
+ 'music_layers': len(layers), 'notes': notes}
456
+
457
+
458
+ def _editable_titles(directory: Path, rendered, styles, timeline) -> int:
459
+ """Record each component's type beside its PNG so a .drt from Resolve can carry it as editable titles."""
460
+ from clipen.rendering import program_creator
461
+ from clipen.rendering.titles import TitleCardRenderer, TitleRenderError
462
+ from .resolve_titles import MANIFEST
463
+ font_path = TitleCardRenderer._font_path()
464
+ manifest = {}
465
+ for item, target, _ in rendered:
466
+ profile = styles.get(item.style_id)
467
+ # A graphic a person resized stays a picture: Resolve's titles would come back at the designed size.
468
+ if not profile or profile.get('kind') != 'program_component' or not program_creator.is_creator(profile) or profile.get('scale', 1) != 1:
469
+ continue
470
+ try:
471
+ plan = program_creator.editable(font_path, timeline, item, profile)
472
+ except TitleRenderError:
473
+ plan = None
474
+ if plan is None:
475
+ continue
476
+ picture = None
477
+ if plan['picture']:
478
+ picture = f'{target.stem}(底圖).png'
479
+ plan['picture'].save(directory / picture, 'PNG', optimize=True)
480
+ manifest[target.name] = {'rows': plan['rows'], 'picture': picture, 'width': timeline.width, 'height': timeline.height}
481
+ if manifest:
482
+ (directory / MANIFEST).write_text(json.dumps(manifest, ensure_ascii=False, indent=1), encoding='utf-8')
483
+ return len(manifest)
484
+
485
+
486
+ RESOLVE_DEFAULT_FOLDER = Path.home() / 'Movies' / 'DaVinci Resolve'
487
+
488
+
489
+ def _timeline_folders(package: Path) -> list[Path]:
490
+ """Where a .drt saved from this package's timeline may land: the package, Resolve's own folder,
491
+ and, for a package in「Clipen 匯出」, that folder and the footage folder around it, since the
492
+ save dialog often opens beside the footage the timeline was relinked to."""
493
+ from clipen.media.discovery import EXPORT_FOLDER
494
+ folders = [package, RESOLVE_DEFAULT_FOLDER]
495
+ if package.parent.name == EXPORT_FOLDER:
496
+ folders += [package.parent, package.parent.parent]
497
+ return folders
498
+
499
+
500
+ def _exported_timeline(package: Path, since: float = 0.) -> Path | None:
501
+ """The newest .drt saved from this package's timeline after since (a time stamp).
502
+
503
+ A .drt counts when its clips point at this package's components, so other films' timelines
504
+ in the same folders are passed over."""
505
+ from .resolve_titles import uses
506
+ # Skip dot files such as the「._」copies macOS leaves beside files on exFAT drives.
507
+ candidates = [p for folder in _timeline_folders(package) for p in folder.glob('*.drt')
508
+ if '(可改字)' not in p.stem and not p.name.startswith('.')]
509
+ candidates = [p for p in candidates if p.stat().st_mtime > since]
510
+ return next((p for p in sorted(candidates, key=lambda p: p.stat().st_mtime, reverse=True) if uses(p, package / '元件')), None)
511
+
512
+
513
+ def timeline_status(package: Path) -> dict:
514
+ """Where Clipen looks for this package's .drt, the newest one it found, and the editable copy.
515
+
516
+ state is waiting (nothing saved yet), found (a .drt is newer than any editable copy) or
517
+ converted (the editable copy covers the newest save)."""
518
+ package = Path(package)
519
+ names = ['這份匯出的資料夾', 'Resolve 預設的資料夾', '「Clipen 匯出」資料夾', '毛片資料夾']
520
+ folders = [{'label': label, 'path': str(folder)} for label, folder in zip(names, _timeline_folders(package))]
521
+ source = _exported_timeline(package)
522
+ copies = sorted((p for p in package.glob('*(可改字).drt') if not p.name.startswith('.')), key=lambda p: p.stat().st_mtime, reverse=True)
523
+ converted = copies[0] if copies else None
524
+ if converted is not None and (source is None or converted.stat().st_mtime >= source.stat().st_mtime):
525
+ state = 'converted'
526
+ else:
527
+ state = 'found' if source is not None else 'waiting'
528
+ return {'state': state, 'folders': folders,
529
+ 'source': str(source) if source else None, 'converted': str(converted) if converted else None}
530
+
531
+
532
+ def convert_timeline(package: Path, source: Path | None = None) -> tuple[Path, int]:
533
+ """Write a copy of the .drt exported from this package's timeline with editable component titles."""
534
+ from .resolve_titles import MANIFEST, convert
535
+ package = Path(package)
536
+ if not (package / '元件' / MANIFEST).is_file():
537
+ raise ProjectError('resolve_titles_missing', '這份匯出沒有可以換成文字的元件。', status_code=409)
538
+ source = source or _exported_timeline(package)
539
+ if source is None:
540
+ raise ProjectError('resolve_timeline_missing', '還找不到這份匯出的 .drt。請先在 DaVinci Resolve 用「檔案 > 匯出 > 時間線…」把時間線存成 .drt。', status_code=409)
541
+ target = _unique(package, f'{source.stem}(可改字).drt')
542
+ temporary = target.with_suffix('.partial')
543
+ try:
544
+ replaced = convert(source, temporary)
545
+ if not replaced:
546
+ raise ProjectError('resolve_titles_unmatched', f'「{source.name}」裡找不到這份匯出的元件。請確認匯出的是從這個資料夾匯入的時間線。', status_code=409)
547
+ temporary.replace(target)
548
+ finally:
549
+ temporary.unlink(missing_ok=True)
550
+ return target, replaced
551
+
552
+
553
+ def watch_timeline(package: Path, since: float, stop: threading.Event | None = None,
554
+ timeout: float = 4 * 3600, interval: float = 2.) -> Path | None:
555
+ """Wait for the person to save this package's timeline as .drt in Resolve, then convert and show it.
556
+
557
+ A save counts once its size holds still for one interval, so a half-written file is never read.
558
+ Gives up after timeout or when stop is set; returns the converted timeline."""
559
+ stop = stop or threading.Event()
560
+ deadline, seen = time.monotonic() + timeout, None
561
+ while not stop.wait(interval) and time.monotonic() < deadline:
562
+ source = _exported_timeline(package, since)
563
+ if source is None:
564
+ continue
565
+ size = source.stat().st_size
566
+ if seen != (source, size):
567
+ seen = (source, size)
568
+ continue
569
+ try:
570
+ target, _ = convert_timeline(package, source)
571
+ except ProjectError:
572
+ return None
573
+ reveal(target)
574
+ return target
575
+ return None
576
+
577
+
578
+ def start_watching(package: Path) -> threading.Thread:
579
+ """Watch for the .drt in the background so the person never has to come back to Clipen for it."""
580
+ since = time.time()
581
+ thread = threading.Thread(target=watch_timeline, args=(Path(package), since), name='resolve-titles', daemon=True)
582
+ thread.start()
583
+ return thread
584
+
585
+
586
+ def reveal(path: Path) -> None:
587
+ """Show the new timeline file in Finder; a missing Finder only skips this courtesy."""
588
+ if os.uname().sysname == 'Darwin':
589
+ subprocess.run(['/usr/bin/open', '-R', str(path)], stdin=subprocess.DEVNULL, capture_output=True, timeout=10, check=False)
590
+
591
+
592
+ def _guide(package: Path, fcpxml: Path, captions: bool, editable: int, notes: list[str]):
593
+ steps = [
594
+ '在 DaVinci Resolve 匯入',
595
+ '',
596
+ f'1. 選「檔案 > 匯入 > 時間線…」(File > Import > Timeline),選擇「{fcpxml.name}」。',
597
+ '2. 匯入視窗保持預設,確認「自動將素材匯入媒體池」有勾選。',
598
+ ]
599
+ if captions:
600
+ steps += ['3. 選「檔案 > 匯入 > 字幕…」(File > Import > Subtitle),選擇「字幕.srt」,再把它拖到時間線最上方的字幕軌。',
601
+ ' 字幕會變成 Resolve 的字幕軌,可以直接改字和時間;外觀請在字幕軌的檢查器設定。']
602
+ steps += ['', '如果 Resolve 顯示「clips were not yet found」,按「Locate」(尋找),選擇毛片資料夾(也就是「Clipen 匯出」所在的資料夾)。',
603
+ 'App Store 版的 Resolve 只能讀取你打開過的資料夾,選一次毛片資料夾,素材和這裡的元件、音樂就都找得到。',
604
+ '', '影片片段直接指向原始素材,前後保留可延長的長度。若搬動了素材,Resolve 會請你重新連結。',
605
+ '這個資料夾裡的元件、音樂和已處理片段也被時間線使用,請保持資料夾完整。']
606
+ if editable:
607
+ steps += ['', '想在 Resolve 改元件的字(需要時再做)', '',
608
+ f'匯入後元件已經和 Clipen 一模一樣,只是以圖片呈現。要改其中的字,再做兩步,{editable} 個元件會一起換成可以改字的標題:',
609
+ '1. 選「檔案 > 匯出 > 時間線…」(File > Export > Timeline),格式選「DaVinci Resolve Timeline Files (*.drt)」,按儲存。',
610
+ ' Clipen 開著的話會自動做好一份名稱有「(可改字)」的 .drt,並在 Finder 打開它;沒出現的話,到 Clipen 的「到 DaVinci Resolve 自己剪」按「把元件換成可改字的標題」。',
611
+ '2. 選「檔案 > 匯入 > 時間線…」,選那份「(可改字)」的 .drt。選取元件後,在右邊「檢查器」改字。',
612
+ ' 改字只會改文字本身;底框、細線這類圖形是固定的圖片,字數差很多時可能要自己調整位置。']
613
+ if notes:
614
+ steps += ['', '需要留意', ''] + [f'・{note}' for note in notes]
615
+ steps += ['', '時間線上的標記(Marker)記下了 Clipen 有、但 Resolve 無法直接帶入的處理,例如調色數值、轉場與淡入淡出。']
616
+ (package / '說明.txt').write_text('\n'.join(steps) + '\n', encoding='utf-8')