@kriya-ai/harness 0.0.0-stage → 0.2.1

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 (185) hide show
  1. package/README.md +379 -2
  2. package/SAFETY.md +162 -0
  3. package/THIRD_PARTY_NOTICES.md +7911 -0
  4. package/bin/kriya.js +577 -0
  5. package/bundle/cordis.patch.yml +397 -0
  6. package/contract/SOURCE.md +15 -0
  7. package/contract/contract.json +1355 -0
  8. package/package.json +57 -4
  9. package/plugins/anchor/index.js +56 -0
  10. package/plugins/anchor/package.json +13 -0
  11. package/plugins/approvals/index.js +183 -0
  12. package/plugins/approvals/package.json +13 -0
  13. package/plugins/brand/DESIGN.md +112 -0
  14. package/plugins/brand/client.js +826 -0
  15. package/plugins/brand/index.js +15 -0
  16. package/plugins/brand/package.json +25 -0
  17. package/plugins/brand/src/client.js +823 -0
  18. package/plugins/browser/index.js +218 -0
  19. package/plugins/browser/package.json +13 -0
  20. package/plugins/budget/index.js +108 -0
  21. package/plugins/budget/package.json +13 -0
  22. package/plugins/changes/client.js +245 -0
  23. package/plugins/changes/index.js +75 -0
  24. package/plugins/changes/package.json +22 -0
  25. package/plugins/edit/client.js +113 -0
  26. package/plugins/edit/index.js +58 -0
  27. package/plugins/edit/package.json +23 -0
  28. package/plugins/fs-freshness/index.js +28 -0
  29. package/plugins/fs-freshness/package.json +13 -0
  30. package/plugins/graph/client.js +178 -0
  31. package/plugins/graph/index.js +4 -0
  32. package/plugins/graph/package.json +22 -0
  33. package/plugins/kriya-handoff/index.js +194 -0
  34. package/plugins/kriya-handoff/package.json +13 -0
  35. package/plugins/kriya-tools/index.js +189 -0
  36. package/plugins/kriya-tools/package.json +13 -0
  37. package/plugins/loop/index.js +743 -0
  38. package/plugins/loop/package.json +13 -0
  39. package/plugins/mirror/index.js +235 -0
  40. package/plugins/mirror/package.json +13 -0
  41. package/plugins/overview/client.js +276 -0
  42. package/plugins/overview/index.js +95 -0
  43. package/plugins/overview/package.json +22 -0
  44. package/plugins/preview/client.js +337 -0
  45. package/plugins/preview/index.js +4 -0
  46. package/plugins/preview/package.json +22 -0
  47. package/plugins/progress/client.js +290 -0
  48. package/plugins/progress/index.js +100 -0
  49. package/plugins/progress/package.json +22 -0
  50. package/plugins/projects/client.js +249 -0
  51. package/plugins/projects/index.js +30 -0
  52. package/plugins/projects/package.json +24 -0
  53. package/plugins/rea/index.js +256 -0
  54. package/plugins/rea/package.json +10 -0
  55. package/plugins/rea/skill/LICENSE +21 -0
  56. package/plugins/rea/skill/SKILL.md +360 -0
  57. package/plugins/rea/skill/references/android-applications.md +36 -0
  58. package/plugins/rea/skill/references/connection-and-recovery.md +127 -0
  59. package/plugins/rea/skill/references/evidence-workflows.md +71 -0
  60. package/plugins/rea/skill/references/javascript-applications.md +218 -0
  61. package/plugins/rea/skill/references/native-and-artifacts.md +297 -0
  62. package/plugins/rea/skill/references/runtime-observation.md +78 -0
  63. package/plugins/remote/index.js +297 -0
  64. package/plugins/remote/package.json +10 -0
  65. package/plugins/router/index.js +84 -0
  66. package/plugins/router/package.json +13 -0
  67. package/plugins/sessions/client.js +68 -0
  68. package/plugins/sessions/index.js +79 -0
  69. package/plugins/sessions/package.json +20 -0
  70. package/plugins/skills/client.js +504 -0
  71. package/plugins/skills/index.js +166 -0
  72. package/plugins/skills/package.json +23 -0
  73. package/src/api.js +97 -0
  74. package/src/browser.js +286 -0
  75. package/src/changes.js +191 -0
  76. package/src/checkpoints.js +313 -0
  77. package/src/daemon.js +503 -0
  78. package/src/doctor.js +137 -0
  79. package/src/edit/core/anchors.js +102 -0
  80. package/src/edit/core/audio.js +158 -0
  81. package/src/edit/core/faces.js +99 -0
  82. package/src/edit/core/ffmpeg.js +258 -0
  83. package/src/edit/core/handoff.js +220 -0
  84. package/src/edit/core/history.js +90 -0
  85. package/src/edit/core/layout.js +92 -0
  86. package/src/edit/core/mix.js +115 -0
  87. package/src/edit/core/ops.js +602 -0
  88. package/src/edit/core/plan.js +266 -0
  89. package/src/edit/core/project.d.ts +134 -0
  90. package/src/edit/core/project.js +307 -0
  91. package/src/edit/core/reframe.js +125 -0
  92. package/src/edit/core/solver.js +416 -0
  93. package/src/edit/core/time.js +110 -0
  94. package/src/edit/core/tonemap.js +57 -0
  95. package/src/edit/director/ask.js +120 -0
  96. package/src/edit/director/gateway.js +16 -0
  97. package/src/edit/director/revise.js +186 -0
  98. package/src/edit/engine/capabilities.js +33 -0
  99. package/src/edit/engine/captions.js +154 -0
  100. package/src/edit/engine/color.js +269 -0
  101. package/src/edit/engine/confine.js +67 -0
  102. package/src/edit/engine/dna.js +148 -0
  103. package/src/edit/engine/index.js +473 -0
  104. package/src/edit/engine/loudness.js +43 -0
  105. package/src/edit/engine/media.js +57 -0
  106. package/src/edit/engine/motion.js +281 -0
  107. package/src/edit/engine/packs.js +87 -0
  108. package/src/edit/engine/probe.js +101 -0
  109. package/src/edit/engine/receipt.js +123 -0
  110. package/src/edit/engine/tool.js +101 -0
  111. package/src/edit/gates/copy.js +113 -0
  112. package/src/edit/gates/index.js +430 -0
  113. package/src/edit/gates/picture.js +130 -0
  114. package/src/edit/gates/sound.js +58 -0
  115. package/src/edit/gates/speech.js +127 -0
  116. package/src/edit/gates/text.js +196 -0
  117. package/src/edit/gates/text.swift +22 -0
  118. package/src/edit/graph/index.js +139 -0
  119. package/src/edit/graph/journal.js +69 -0
  120. package/src/edit/graph/scheduler.js +79 -0
  121. package/src/edit/host/client.js +58 -0
  122. package/src/edit/host/deliver.js +119 -0
  123. package/src/edit/host/jobs.js +84 -0
  124. package/src/edit/host/main.js +135 -0
  125. package/src/edit/host/paths.js +11 -0
  126. package/src/edit/host/projects.js +415 -0
  127. package/src/edit/host/server.js +391 -0
  128. package/src/edit/host/taste.js +135 -0
  129. package/src/edit/host/tavi.js +417 -0
  130. package/src/edit/host/watch.js +141 -0
  131. package/src/edit/index/db.js +109 -0
  132. package/src/edit/index/index.js +236 -0
  133. package/src/edit/index/layers/faces.js +78 -0
  134. package/src/edit/index/layers/faces.swift +18 -0
  135. package/src/edit/index/layers/meta.js +35 -0
  136. package/src/edit/index/layers/music.js +146 -0
  137. package/src/edit/index/layers/quality.js +120 -0
  138. package/src/edit/index/layers/retakes.js +132 -0
  139. package/src/edit/index/layers/screen.js +99 -0
  140. package/src/edit/index/layers/shots.js +29 -0
  141. package/src/edit/index/layers/sound.js +42 -0
  142. package/src/edit/index/layers/words.js +64 -0
  143. package/src/edit/index/story.js +248 -0
  144. package/src/edit/index/views.js +71 -0
  145. package/src/edit/loop/governor.js +112 -0
  146. package/src/edit/loop/loop.js +69 -0
  147. package/src/edit/loop/make.js +115 -0
  148. package/src/edit/loop/repair.js +97 -0
  149. package/src/edit/loop/replay.js +32 -0
  150. package/src/edit/recipes/multicam.js +461 -0
  151. package/src/edit/recipes/reel.js +202 -0
  152. package/src/edit/recipes/short-from-long.js +237 -0
  153. package/src/edit/recipes/tutorial.js +137 -0
  154. package/src/edit/recipes/youtube.js +155 -0
  155. package/src/edit/runtime/cli.js +126 -0
  156. package/src/edit/runtime/doctor.js +122 -0
  157. package/src/edit/runtime/fetch.js +15 -0
  158. package/src/edit/runtime/licences.js +88 -0
  159. package/src/edit/runtime/manifest.js +73 -0
  160. package/src/edit/runtime/setup.js +252 -0
  161. package/src/failure.js +69 -0
  162. package/src/gateway-proxy.js +213 -0
  163. package/src/intent.js +130 -0
  164. package/src/launch.js +315 -0
  165. package/src/live.js +81 -0
  166. package/src/local-skills.js +284 -0
  167. package/src/login.js +82 -0
  168. package/src/loop.js +428 -0
  169. package/src/modes.js +128 -0
  170. package/src/overview.js +71 -0
  171. package/src/paths.js +30 -0
  172. package/src/profiles.js +92 -0
  173. package/src/projects.js +104 -0
  174. package/src/recon.js +244 -0
  175. package/src/rules.js +139 -0
  176. package/src/runner.bundle.js +21172 -0
  177. package/src/sentinel.js +248 -0
  178. package/src/skill-switches.js +130 -0
  179. package/src/store.js +58 -0
  180. package/src/strict.js +124 -0
  181. package/src/verify.js +659 -0
  182. package/src/world.js +268 -0
  183. package/studio/dist/index.html +14 -0
  184. package/studio/dist/studio.css +163 -0
  185. package/studio/dist/studio.js +1 -0
@@ -0,0 +1,416 @@
1
+ // The solver (EDIT_ENGINE §5): anchors in, exact times out, in the document's order:
2
+ // resolve, sequence, snap, air, J and L, layout, budget. It reports what it couldn't
3
+ // satisfy and never silently drops a request.
4
+
5
+ import { anchorSource, openIndex, wordAfter, wordAt, wordBefore } from "./anchors.js"
6
+ import { safeZoneFor, solveLayout } from "./layout.js"
7
+ import { flicksToFrames, frameAtTimestamp, framesToFlicks, scaleFlicks, snapToFrame } from "./time.js"
8
+
9
+ const ms = (n) => n * 705_600
10
+
11
+ export const DEFAULT_RULES = {
12
+ padIn: ms(120),
13
+ padOut: ms(240),
14
+ zeroTolerance: ms(2),
15
+ airAfter: ms(750),
16
+ maxSplit: null,
17
+ minFrames: 2,
18
+ minShot: 0,
19
+ targetTolerance: 0,
20
+ // null: the strictest safe zone of the project's deliverables (layout.js SAFE_ZONES, ED8)
21
+ safe: null,
22
+ prefer: 80,
23
+ boxWidth: 80,
24
+ boxHeight: 12,
25
+ }
26
+
27
+ const AUDIO_ROLES = ["dialogue", "sfx", "music", "ambience"]
28
+ // Music to be fitted runs to the timeline's end; the plan edits it there on its downbeats (ED9)
29
+ const fitted = (clip) => clip.effects.some((e) => e.type === "fit")
30
+
31
+ const inverse = ({ n, d }) => ({ n: d, d: n })
32
+ const isWordCut = (ref, edge) => ref.word !== undefined && ref.edge === edge && !ref.exact
33
+
34
+ function nearestCrossing(list, t, low, high, tolerance) {
35
+ let from = 0
36
+ let to = list.length
37
+ while (from < to) {
38
+ const middle = (from + to) >> 1
39
+ if (list[middle] < t) from = middle + 1
40
+ else to = middle
41
+ }
42
+ const options = [list[from - 1], list[from]].filter((c) => c !== undefined && Math.abs(c - t) <= tolerance && c >= low && c <= high)
43
+ return options.sort((a, b) => Math.abs(a - t) - Math.abs(b - t))[0] ?? t
44
+ }
45
+
46
+ function snapper(s, asset) {
47
+ const table = asset.facts.vfr ? s.raw.timestamps?.[asset.id] : undefined
48
+ if (table?.length) {
49
+ return {
50
+ down: (t) => table[frameAtTimestamp(table, t)],
51
+ up: (t) => {
52
+ const i = frameAtTimestamp(table, t)
53
+ return table[i] === t ? t : (table[i + 1] ?? table[i])
54
+ },
55
+ }
56
+ }
57
+ const rate = asset.facts.fps ?? s.fps
58
+ return { down: (t) => snapToFrame(t, rate, "floor"), up: (t) => snapToFrame(t, rate, "ceil") }
59
+ }
60
+
61
+ const sourceOf = (s, ref, edge) => (typeof ref === "number" ? ref : (anchorSource(ref, s.index, edge)?.t ?? null))
62
+
63
+ /** Steps 1, 3 and 4 for one clip: where picture and sound really cut. */
64
+ function cutPoints(s, clip, asset) {
65
+ const { rules } = s
66
+ const words = s.index.words.get(asset.id) ?? []
67
+ const duration = asset.facts.duration ?? Number.MAX_SAFE_INTEGER
68
+ const refs = clip.source
69
+ let start = sourceOf(s, refs.in, "start")
70
+ let end = sourceOf(s, refs.out, "end")
71
+ if (start === null || end === null) return null
72
+
73
+ const moved = (word, t) => {
74
+ s.issue("cut_moved_off_word", { clip: clip.id, word: word.id, message: "a cut would have landed inside a word, so it moved to the word's edge" })
75
+ return t
76
+ }
77
+ const inStart = wordAt(words, start)
78
+ if (inStart) start = moved(inStart, inStart.start)
79
+ const inEnd = wordAt(words, end)
80
+ if (inEnd) end = moved(inEnd, inEnd.end)
81
+
82
+ const floor = wordBefore(words, start)?.end ?? 0
83
+ const ceiling = Math.min(wordAfter(words, end)?.start ?? duration, duration)
84
+ const cutIn = Math.max(floor, start - (isWordCut(refs.in, "start") ? rules.padIn : 0))
85
+ let cutOut = Math.min(ceiling, end + (isWordCut(refs.out, "end") ? rules.padOut : 0))
86
+ const spoken = wordBefore(words, end)
87
+ if (spoken && s.airWords.has(spoken.id)) cutOut = Math.max(cutOut, Math.min(ceiling, spoken.end + rules.airAfter))
88
+
89
+ const { down, up } = snapper(s, asset)
90
+ const firstWord = wordAfter(words, cutIn)?.start ?? duration
91
+ const lastWord = wordBefore(words, cutOut)?.end ?? 0
92
+ const noGap = () => s.issue("cut_no_frame_gap", { clip: clip.id, message: "no frame boundary falls in the gap, so the picture keeps the whole word and the sound makes the cut" })
93
+ let pictureIn = down(cutIn)
94
+ if (pictureIn < floor) {
95
+ if (up(cutIn) <= firstWord) pictureIn = up(cutIn)
96
+ else noGap()
97
+ }
98
+ let pictureOut = up(cutOut)
99
+ if (pictureOut > ceiling) {
100
+ if (down(cutOut) >= lastWord) pictureOut = down(cutOut)
101
+ else noGap()
102
+ }
103
+
104
+ const crossings = s.raw.zeroCrossings?.[asset.id] ?? []
105
+ let soundIn = nearestCrossing(crossings, cutIn, floor, firstWord, rules.zeroTolerance)
106
+ let soundOut = nearestCrossing(crossings, cutOut, lastWord, ceiling, rules.zeroTolerance)
107
+
108
+ let lead = clip.audioLead ?? 0
109
+ let lag = clip.audioLag ?? 0
110
+ if (rules.maxSplit !== null && Math.max(lead, lag) > rules.maxSplit) {
111
+ lead = Math.min(lead, rules.maxSplit)
112
+ lag = Math.min(lag, rules.maxSplit)
113
+ s.issue("split_limited", { clip: clip.id, message: "picture and sound can't part by that much; held to the limit" })
114
+ }
115
+ soundIn = Math.max(0, soundIn - lead)
116
+ soundOut = Math.min(duration, soundOut + lag)
117
+ return { pictureIn, pictureOut, soundIn, soundOut }
118
+ }
119
+
120
+ const framesFor = (span, fps) => (span <= 0 ? 0 : flicksToFrames(span - 1, fps) + 1)
121
+
122
+ /** Step 2: lay kept ranges end to end, on the timeline's frames. */
123
+ function layBase(s, clips) {
124
+ let frame = 0
125
+ for (const clip of clips) {
126
+ const asset = s.assets.get(clip.source.asset)
127
+ const cut = cutPoints(s, clip, asset)
128
+ if (cut === null) {
129
+ s.issue("anchor_removed", { clip: clip.id, message: "this clip's words aren't in the transcript any more" })
130
+ continue
131
+ }
132
+ const { pictureIn, pictureOut, soundIn, soundOut } = cut
133
+ const slow = inverse(clip.speed)
134
+ const effects = clip.effects.filter((e) => e.type !== "freeze")
135
+ const piece = (from, to, length, hold) => {
136
+ const frames = framesFor(length, s.fps)
137
+ if (frames === 0) return
138
+ const item = { clip: clip.id, asset: asset.id, in: from, out: to, at: framesToFlicks(frame, s.fps), end: framesToFlicks(frame + frames, s.fps), speed: clip.speed, effects, ...(hold ? { hold } : {}) }
139
+ frame += frames
140
+ s.picture.push(item)
141
+ return item
142
+ }
143
+ const first = frame
144
+ const freeze = clip.effects.find((e) => e.type === "freeze")
145
+ let stop = freeze ? sourceOf(s, freeze.at, "start") : null
146
+ if (freeze && (stop === null || stop < pictureIn || stop >= pictureOut)) {
147
+ s.issue("anchor_removed", { clip: clip.id, anchor: freeze.at, message: "the freeze's point is no longer inside this clip, so there is no hold" })
148
+ stop = null
149
+ }
150
+ const pieces = (stop === null ? [piece(pictureIn, pictureOut, scaleFlicks(pictureOut - pictureIn, slow))] : [piece(pictureIn, stop, scaleFlicks(stop - pictureIn, slow)), piece(stop, stop, freeze.duration, true), piece(stop, pictureOut, scaleFlicks(pictureOut - stop, slow))]).filter(Boolean)
151
+ if (pieces.length === 0) continue
152
+
153
+ if (frame - first < s.rules.minFrames) s.issue("flash_frame", { clip: clip.id, message: `this clip lasts ${frame - first} frame(s), which reads as a flash` })
154
+ if (framesToFlicks(frame - first, s.fps) < s.rules.minShot) s.issue("short_shot", { clip: clip.id, message: "this clip is shorter than the recipe's shortest shot" })
155
+
156
+ if (asset.facts.hasAudio !== false && !s.tracks.get(clip.track).muted) {
157
+ const sound = (from, to, anchor) => {
158
+ const at = anchor.at + scaleFlicks(from - anchor.in, slow)
159
+ const late = Math.max(0, -at)
160
+ s.audio.push({ clip: clip.id, role: "dialogue", asset: asset.id, in: from + late, out: to, at: at + late, end: at + scaleFlicks(to - from, slow), speed: clip.speed, effects })
161
+ }
162
+ sound(soundIn, stop ?? soundOut, pieces[0])
163
+ if (stop !== null) sound(stop, soundOut, pieces.at(-1))
164
+ }
165
+ }
166
+ s.duration = framesToFlicks(frame, s.fps)
167
+ }
168
+
169
+ /** Where a time in an asset sits on the timeline, or null if it was cut. */
170
+ function mapSource(s, place, anchor, spot) {
171
+ const edge = anchor.edge ?? "start"
172
+ const hit = s.picture.find(({ asset, in: from, out, hold }) => !hold && asset === spot.asset && (edge === "start" ? from <= spot.t && spot.t < out : from < spot.t && spot.t <= out))
173
+ if (hit) return hit.at + scaleFlicks(spot.t - hit.in, inverse(hit.speed))
174
+ for (const clip of s.rest) {
175
+ if (clip.source?.asset !== spot.asset || s.tracks.get(clip.track).role === "ambience") continue
176
+ const from = sourceOf(s, clip.source.in, "start")
177
+ const to = sourceOf(s, clip.source.out, "end")
178
+ if (from === null || to === null || spot.t < from || spot.t > to) continue
179
+ const placed = place(clip)
180
+ if (placed) return placed.at + scaleFlicks(spot.t - from, inverse(clip.speed))
181
+ }
182
+ return null
183
+ }
184
+
185
+ function placeRest(s) {
186
+ const placed = new Map()
187
+ const placing = new Set()
188
+ let cycle = false
189
+
190
+ const span = (id) => {
191
+ const pieces = s.picture.filter((p) => p.clip === id)
192
+ if (pieces.length) return { at: pieces[0].at, end: pieces.at(-1).end }
193
+ const clip = s.rest.find((c) => c.id === id)
194
+ return clip ? place(clip) : null
195
+ }
196
+
197
+ const resolve = (ref, edge) => {
198
+ if (typeof ref === "number") return ref
199
+ if (ref.marker !== undefined) {
200
+ const marker = s.sequence.markers.find((m) => m.name === ref.marker || m.id === ref.marker)
201
+ return marker ? resolve(marker.at, edge) : null
202
+ }
203
+ if (ref.clip !== undefined) {
204
+ const other = span(ref.clip)
205
+ return other ? other[ref.edge === "end" ? "end" : "at"] + (ref.offset ?? 0) : null
206
+ }
207
+ const spot = anchorSource(ref, s.index, edge)
208
+ return spot ? mapSource(s, place, ref, spot) : null
209
+ }
210
+
211
+ const lost = (clip, ref) => {
212
+ if (cycle) s.issue("anchor_cycle", { clip: clip.id, message: "clips are anchored to each other in a circle, so neither can be placed" })
213
+ else s.issue("anchor_removed", { clip: clip.id, anchor: ref, message: "what this was anchored to is no longer on the timeline" })
214
+ cycle = false
215
+ }
216
+
217
+ function compute(clip) {
218
+ const role = s.tracks.get(clip.track).role
219
+ let at = resolve(clip.at ?? 0, "start")
220
+ if (at === null) {
221
+ lost(clip, clip.at)
222
+ return null
223
+ }
224
+ if (clip.peak) {
225
+ at -= clip.peak
226
+ if (at < 0) {
227
+ s.issue("peak_before_start", { clip: clip.id, message: "this sound's build-up starts before the timeline, so its peak lands late" })
228
+ at = 0
229
+ }
230
+ }
231
+ if (at >= s.duration) {
232
+ s.issue("past_end", { clip: clip.id, message: "this starts after the timeline ends" })
233
+ return null
234
+ }
235
+
236
+ const from = clip.source ? sourceOf(s, clip.source.in, "start") : 0
237
+ const to = clip.source ? sourceOf(s, clip.source.out, "end") : 0
238
+ const available = clip.source ? scaleFlicks(to - from, inverse(clip.speed)) : null
239
+ let end
240
+ if (clip.until !== undefined) {
241
+ end = resolve(clip.until, "end")
242
+ if (end === null) {
243
+ lost(clip, clip.until)
244
+ end = at + (available ?? 0)
245
+ }
246
+ } else if (clip.duration !== undefined) end = at + clip.duration
247
+ else if (clip.loop || fitted(clip)) end = s.duration
248
+ else if (available !== null) end = at + available
249
+ // A punch-in with no span holds until the next cut
250
+ else end = s.picture.find((p) => p.at <= at && at < p.end)?.end ?? s.duration
251
+
252
+ if (end <= at) {
253
+ s.issue("span_inverted", { clip: clip.id, message: "this ends before it starts" })
254
+ return null
255
+ }
256
+ if (clip.source && !clip.loop && !fitted(clip) && available < end - at) {
257
+ s.issue("source_too_short", { clip: clip.id, message: "the source runs out before the span ends; kept at the length it has" })
258
+ end = at + available
259
+ }
260
+ if (end > s.duration) {
261
+ if (!AUDIO_ROLES.includes(role)) s.issue("past_end", { clip: clip.id, message: "this runs past the end of the timeline, and was cut there" })
262
+ end = s.duration
263
+ }
264
+ if (AUDIO_ROLES.includes(role)) return { at, end, from, to, role }
265
+ const frameAt = snapToFrame(at, s.fps, "nearest")
266
+ return { at: frameAt, end: Math.max(snapToFrame(end, s.fps, "nearest"), frameAt + 1), from, to, role }
267
+ }
268
+
269
+ function place(clip) {
270
+ if (placed.has(clip.id)) return placed.get(clip.id)
271
+ if (placing.has(clip.id)) {
272
+ cycle = true
273
+ return null
274
+ }
275
+ placing.add(clip.id)
276
+ const result = compute(clip)
277
+ placing.delete(clip.id)
278
+ placed.set(clip.id, result)
279
+ return result
280
+ }
281
+
282
+ function caption(clip, effect) {
283
+ const on = []
284
+ const missing = []
285
+ for (const id of effect.words) {
286
+ const word = s.index.word.get(id)
287
+ const at = word ? mapSource(s, place, { edge: "start" }, { asset: word.asset, t: word.start }) : null
288
+ const end = word ? mapSource(s, place, { edge: "end" }, { asset: word.asset, t: word.end }) : null
289
+ if (at === null || end === null) missing.push(id)
290
+ else on.push({ id, text: word.text, at, end })
291
+ }
292
+ if (missing.length) s.issue("anchor_removed", { clip: clip.id, words: missing, message: "these words were cut, so the caption no longer shows them" })
293
+ if (on.length === 0) return
294
+ s.captions.push({
295
+ clip: clip.id,
296
+ at: Math.min(...on.map((w) => w.at)),
297
+ end: Math.max(...on.map((w) => w.end)),
298
+ words: on,
299
+ text: effect.text ?? on.map((w) => w.text).join(" "),
300
+ look: effect.look,
301
+ emphasis: effect.emphasis,
302
+ placement: effect.placement ?? null,
303
+ ...(behind(clip) ? { behind: true } : {}),
304
+ })
305
+ }
306
+
307
+ // Text on a track below the matte track goes behind the speaker (EDIT_ENGINE §3: a stacking rule)
308
+ const matteTrack = [...s.tracks.values()].find((t) => t.role === "matte")
309
+ const behind = (clip) => matteTrack !== undefined && s.tracks.get(clip.track).order < matteTrack.order
310
+
311
+ for (const clip of s.rest) {
312
+ const effect = clip.effects.find((e) => e.type === "caption")
313
+ if (effect) {
314
+ caption(clip, effect)
315
+ continue
316
+ }
317
+ const spot = place(clip)
318
+ if (!spot) continue
319
+ const zoom = clip.effects.find((e) => e.type === "zoom")
320
+ const block = clip.effects.find((e) => e.type === "block")
321
+ const matte = clip.effects.find((e) => e.type === "matte")
322
+ const item = { clip: clip.id, role: spot.role, at: spot.at, end: spot.end }
323
+ if (zoom) s.zooms.push({ ...item, scale: zoom.scale, ease: zoom.ease ?? null, ...(zoom.x === undefined ? {} : { x: zoom.x, y: zoom.y }) })
324
+ else if (matte) s.mattes.push({ ...item, model: matte.model ?? "face-box" })
325
+ else if (AUDIO_ROLES.includes(spot.role)) {
326
+ if (!s.tracks.get(clip.track).muted) s.audio.push({ ...item, asset: clip.source.asset, in: spot.from, out: spot.to, speed: clip.speed, effects: clip.effects, ...(clip.loop ? { loop: true } : {}), ...(clip.peak ? { peak: clip.peak } : {}) })
327
+ } else if (block) s.overlays.push({ ...item, block: { blockId: block.blockId, version: block.version, variables: block.variables }, placement: null, ...(behind(clip) ? { behind: true } : {}) })
328
+ else s.overlays.push({ ...item, asset: clip.source.asset, in: spot.from, out: spot.to, speed: clip.speed, effects: clip.effects })
329
+ }
330
+ }
331
+
332
+ // shortcut: scales face boxes by frame size and ignores any crop path, ED11's reframe recipes must map them through it
333
+ function facesDuring(s, at, end) {
334
+ const { width, height } = s.project.canvas
335
+ const boxes = []
336
+ for (const piece of s.picture) {
337
+ if (piece.end <= at || piece.at >= end) continue
338
+ const facts = s.assets.get(piece.asset).facts
339
+ const scaleX = width / (facts.width ?? width)
340
+ const scaleY = height / (facts.height ?? height)
341
+ const from = piece.in + scaleFlicks(Math.max(0, at - piece.at), piece.speed)
342
+ const to = piece.in + scaleFlicks(Math.min(piece.end, end) - piece.at, piece.speed)
343
+ for (const face of s.raw.faces ?? []) {
344
+ if (face.asset === piece.asset && face.t >= from && face.t <= to) boxes.push({ x: Math.floor(face.box.x * scaleX), y: Math.floor(face.box.y * scaleY), w: Math.ceil(face.box.w * scaleX), h: Math.ceil(face.box.h * scaleY) })
345
+ }
346
+ }
347
+ return boxes
348
+ }
349
+
350
+ /** Step 6: every caption and card gets a place, or a report. */
351
+ function layOut(s) {
352
+ const { rules } = s
353
+ const { width, height } = s.project.canvas
354
+ const safe = rules.safe ?? safeZoneFor(s.project)
355
+ // Narrower than the look's width when the safe zone is (found in ED8: else no row fits)
356
+ const w = Math.min(Math.floor((width * rules.boxWidth) / 100), width - (safe.left ?? 0) - (safe.right ?? 0))
357
+ const h = Math.floor((height * rules.boxHeight) / 100)
358
+ const placeable = [...s.captions, ...s.overlays.filter((o) => o.block)]
359
+ // Text behind the speaker may sit on the face: the matte puts the speaker in front of it
360
+ const items = placeable.map((item) => ({ id: item.clip, at: item.at, end: item.end, w, h, faces: item.behind ? [] : facesDuring(s, item.at, item.end), ...(item.placement ? { fixed: item.placement } : {}) }))
361
+ const { placements, issues } = solveLayout(items, { canvas: { width, height }, safe, prefer: rules.prefer })
362
+ for (const item of placeable) item.placement = placements[item.clip]
363
+ for (const issue of issues) s.issue(issue.code, issue)
364
+ }
365
+
366
+ /** Step 7: the budget. */
367
+ function checkBudget(s) {
368
+ const target = s.project.brief?.targetDuration
369
+ if (target === undefined) return
370
+ const off = s.duration - target
371
+ if (Math.abs(off) <= s.rules.targetTolerance) return
372
+ s.issue(off > 0 ? "over_target" : "under_target", { target, actual: s.duration, message: `the cut ${off > 0 ? "runs over" : "falls short of"} the target duration` })
373
+ }
374
+
375
+ /**
376
+ * @param {object} project
377
+ * @param {object} rawIndex rows from the index: words, shots, beats, faces, timestamps, zeroCrossings
378
+ * @param {Partial<typeof DEFAULT_RULES>} [overrides] a recipe's values
379
+ */
380
+ export function solve(project, rawIndex = {}, overrides = {}) {
381
+ const sequence = project.sequences.find((q) => q.id === project.active)
382
+ const tracks = new Map(sequence.tracks.map((track) => [track.id, track]))
383
+ const isBase = (clip) => tracks.get(clip.track).role === "base"
384
+ const index = openIndex(rawIndex)
385
+ const s = {
386
+ project,
387
+ sequence,
388
+ tracks,
389
+ index,
390
+ raw: rawIndex,
391
+ rules: { ...DEFAULT_RULES, ...overrides },
392
+ assets: new Map(project.assets.map((asset) => [asset.id, asset])),
393
+ fps: project.canvas.fps,
394
+ rest: sequence.clips.filter((clip) => !isBase(clip)),
395
+ picture: [],
396
+ audio: [],
397
+ overlays: [],
398
+ zooms: [],
399
+ captions: [],
400
+ mattes: [],
401
+ issues: [],
402
+ duration: 0,
403
+ issue(code, details) {
404
+ this.issues.push({ ...details, code })
405
+ },
406
+ }
407
+ const sounds = s.rest.filter((clip) => tracks.get(clip.track).role === "sfx" && clip.at?.word !== undefined)
408
+ s.airWords = new Set(s.rules.airAfter > 0 ? sounds.map((clip) => clip.at.word) : [])
409
+
410
+ layBase(s, sequence.clips.filter(isBase))
411
+ placeRest(s)
412
+ layOut(s)
413
+ checkBudget(s)
414
+ const { picture, audio, overlays, zooms, captions, mattes, issues, duration, fps } = s
415
+ return { fps, duration, picture, audio, overlays, zooms, captions, mattes, issues }
416
+ }
@@ -0,0 +1,110 @@
1
+ // Edit Core time (EDIT_ENGINE §2): every time is an integer count of flicks,
2
+ // 1/705,600,000 s, and frame rates are rationals { n, d }. Seconds exist only as
3
+ // the strings the edge functions at the bottom print.
4
+
5
+ export const FLICKS = 705_600_000
6
+
7
+ const BIG = BigInt(FLICKS)
8
+
9
+ export const isFlicks = (value) => Number.isSafeInteger(value)
10
+ export const isRate = (rate) => rate !== null && typeof rate === "object" && Number.isSafeInteger(rate.n) && Number.isSafeInteger(rate.d) && rate.n > 0 && rate.d > 0
11
+
12
+ const whole = (value, name) => {
13
+ if (!Number.isSafeInteger(value)) throw new RangeError(`${name} must be a whole number, got ${value}`)
14
+ return BigInt(value)
15
+ }
16
+ const rateOf = (rate) => {
17
+ if (!isRate(rate)) throw new RangeError("a rate must be a rational { n, d } of positive whole numbers")
18
+ return { n: BigInt(rate.n), d: BigInt(rate.d) }
19
+ }
20
+ const hertz = (hz) => {
21
+ if (!Number.isSafeInteger(hz) || hz <= 0) throw new RangeError("a sample rate must be a positive whole number")
22
+ return BigInt(hz)
23
+ }
24
+ const floorDiv = (a, b) => (a >= 0n ? a / b : -((-a + b - 1n) / b))
25
+ const ceilDiv = (a, b) => -floorDiv(-a, b)
26
+ const safe = (value) => {
27
+ const result = Number(value)
28
+ if (!Number.isSafeInteger(result)) throw new RangeError("time is past what flicks can hold exactly")
29
+ return result
30
+ }
31
+
32
+ /** Flicks in one frame, or null when the rate doesn't divide a flick evenly. */
33
+ export function frameFlicks(rate) {
34
+ const { n, d } = rateOf(rate)
35
+ return (BIG * d) % n === 0n ? Number((BIG * d) / n) : null
36
+ }
37
+
38
+ // Ceiling, so at a rate that doesn't divide a flick a frame's start still belongs to it
39
+ export function framesToFlicks(frame, rate) {
40
+ const { n, d } = rateOf(rate)
41
+ return safe(ceilDiv(whole(frame, "a frame") * BIG * d, n))
42
+ }
43
+
44
+ /** The frame showing at time t. */
45
+ export function flicksToFrames(t, rate) {
46
+ const { n, d } = rateOf(rate)
47
+ return safe(floorDiv(whole(t, "a time") * n, BIG * d))
48
+ }
49
+
50
+ export const samplesToFlicks = (sample, hz) => safe(ceilDiv(whole(sample, "a sample") * BIG, hertz(hz)))
51
+ export const flicksToSamples = (t, hz) => safe(floorDiv(whole(t, "a time") * hertz(hz), BIG))
52
+
53
+ /** @param {"floor" | "ceil" | "nearest"} mode */
54
+ export function snapToFrame(t, rate, mode = "nearest") {
55
+ const below = framesToFlicks(flicksToFrames(t, rate), rate)
56
+ if (below === t || mode === "floor") return below
57
+ const above = framesToFlicks(flicksToFrames(t, rate) + 1, rate)
58
+ if (mode === "ceil") return above
59
+ return t - below < above - t ? below : above
60
+ }
61
+
62
+ /** t × n/d, rounded up so a scaled clip never loses its tail. */
63
+ export function scaleFlicks(t, { n, d }) {
64
+ return safe(ceilDiv(whole(t, "a time") * BigInt(n), BigInt(d)))
65
+ }
66
+
67
+ /** The index of the frame showing at t, from a VFR file's sorted timestamps. */
68
+ export function frameAtTimestamp(table, t) {
69
+ let low = 0
70
+ let high = table.length - 1
71
+ while (low < high) {
72
+ const middle = Math.ceil((low + high) / 2)
73
+ if (table[middle] <= t) low = middle
74
+ else high = middle - 1
75
+ }
76
+ return low
77
+ }
78
+
79
+ // Edge only: an exact decimal string for an FFmpeg argument
80
+ export function secondsArg(t) {
81
+ // Integer division prints -1/6 s as "0.-166666666", which FFmpeg misreads (found in ED11)
82
+ if (t < 0) throw new RangeError(`a time for FFmpeg can't be negative, got ${t}`)
83
+ const nano = (whole(t, "a time") * 2_000_000_000n + BIG) / (2n * BIG)
84
+ return `${nano / 1_000_000_000n}.${String(nano % 1_000_000_000n).padStart(9, "0")}`
85
+ }
86
+
87
+ const gcd = (a, b) => (b === 0 ? a : gcd(b, a % b))
88
+
89
+ // Edge only: FCPXML's rational seconds, such as 1001/24000s
90
+ export function fractionSeconds(t) {
91
+ const divisor = gcd(t, FLICKS)
92
+ if (t === 0) return "0s"
93
+ return divisor === FLICKS ? `${t / FLICKS}s` : `${t / divisor}/${FLICKS / divisor}s`
94
+ }
95
+
96
+ const two = (value) => String(value).padStart(2, "0")
97
+
98
+ /** Non-drop timecode: frames counted at the nominal rate, as CMX 3600 expects. */
99
+ export function timecode(frame, rate) {
100
+ const base = Math.ceil(rate.n / rate.d)
101
+ const seconds = Math.floor(frame / base)
102
+ return [Math.floor(seconds / 3600), Math.floor(seconds / 60) % 60, seconds % 60, frame % base].map(two).join(":")
103
+ }
104
+
105
+ // Edge only: HH:MM:SS,mmm for SRT and VTT
106
+ export function clockTime(t, separator) {
107
+ const total = Math.round(t / 705_600)
108
+ const seconds = Math.floor(total / 1000)
109
+ return `${two(Math.floor(seconds / 3600))}:${two(Math.floor(seconds / 60) % 60)}:${two(seconds % 60)}${separator}${String(total % 1000).padStart(3, "0")}`
110
+ }
@@ -0,0 +1,57 @@
1
+ // HDR to BT.709 as a .cube LUT, computed here so it needs only FFmpeg's `lut3d`:
2
+ // Homebrew's plain ffmpeg has no `zscale` (EF-37). Input is non-linear BT.2020 RGB,
3
+ // output non-linear BT.709 RGB. Pixels are floats; no time passes through here.
4
+
5
+ const PEAK_SDR = 203 // ITU-R BT.2408: the reference white of HDR graphics, in nits
6
+
7
+ const pqToNits = (v) => {
8
+ const [m1, m2, c1, c2, c3] = [0.1593017578125, 78.84375, 0.8359375, 18.8515625, 18.6875]
9
+ const p = v ** (1 / m2)
10
+ return 10_000 * (Math.max(p - c1, 0) / (c2 - c3 * p)) ** (1 / m1)
11
+ }
12
+
13
+ // HLG's inverse OETF, then its system gamma for a 1000-nit display
14
+ const hlgToNits = (v) => {
15
+ const [a, b, c] = [0.17883277, 0.28466892, 0.55991073]
16
+ const scene = v <= 0.5 ? (v * v) / 3 : (Math.exp((v - c) / a) + b) / 12
17
+ return 1000 * scene ** 1.2
18
+ }
19
+
20
+ const toLinear = { smpte2084: pqToNits, "arib-std-b67": hlgToNits }
21
+
22
+ // ITU-R BT.2087: BT.2020 primaries to BT.709, in linear light
23
+ const GAMUT = [
24
+ [1.660491, -0.587641, -0.07285],
25
+ [-0.124551, 1.1329, -0.008349],
26
+ [-0.018151, -0.100579, 1.11873],
27
+ ]
28
+
29
+ // Extended Reinhard, with HDR's 10,000-nit ceiling landing exactly on SDR white.
30
+ // shortcut: GAIN puts reference white near 84% code by eye, EDITOR_WORKFLOWS §6's grade tunes it on real footage
31
+ const GAIN = 2
32
+ const CEILING = (GAIN * 10_000) / PEAK_SDR
33
+ const shoulder = (level) => (level * (1 + level / CEILING ** 2)) / (1 + level)
34
+
35
+ const bt709 = (v) => (v < 0.018 ? 4.5 * v : 1.099 * v ** 0.45 - 0.099)
36
+
37
+ function mapRgb(rgb, linear) {
38
+ const nits = rgb.map(linear)
39
+ const light = GAMUT.map((row) => row[0] * nits[0] + row[1] * nits[1] + row[2] * nits[2])
40
+ const clipped = light.map((v) => Math.max(v, 0) / PEAK_SDR)
41
+ // On brightness, not per channel, so a bright colour keeps its hue
42
+ const level = Math.max(...clipped)
43
+ if (level === 0) return [0, 0, 0]
44
+ const scale = shoulder(level * GAIN) / level
45
+ return clipped.map((v) => bt709(Math.min(v * scale, 1)))
46
+ }
47
+
48
+ /** @param {"smpte2084" | "arib-std-b67"} transfer @param {number} [size] @returns {string} */
49
+ export function toneMapCube(transfer, size = 33) {
50
+ const linear = toLinear[transfer]
51
+ if (!linear) throw new RangeError(`${transfer} isn't an HDR transfer this can map`)
52
+ const lines = [`LUT_3D_SIZE ${size}`]
53
+ const step = (i) => i / (size - 1)
54
+ // .cube order: red changes fastest
55
+ for (let b = 0; b < size; b++) for (let g = 0; g < size; g++) for (let r = 0; r < size; r++) lines.push(mapRgb([step(r), step(g), step(b)], linear).map((v) => v.toFixed(6)).join(" "))
56
+ return `${lines.join("\n")}\n`
57
+ }