@mengine/medeo-client 0.1.3 → 1.0.1-alpha.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/dist/document-DgffKwRw.js +1593 -0
- package/dist/index-6e5cbdM3.d.ts +475 -0
- package/dist/index-DRUGsbm2.d.ts +1421 -0
- package/dist/index.d.ts +28 -1813
- package/dist/index.js +133 -1901
- package/dist/schemas.d.ts +2 -0
- package/dist/schemas.js +378 -0
- package/dist/testing.d.ts +46 -0
- package/dist/testing.js +339 -0
- package/package.json +10 -5
|
@@ -0,0 +1,1593 @@
|
|
|
1
|
+
import { Mirror, schema } from "loro-mirror";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import { LoroDoc } from "loro-crdt";
|
|
4
|
+
import { produce } from "immer";
|
|
5
|
+
//#region src/client/base64.ts
|
|
6
|
+
function bytesToBase64(bytes) {
|
|
7
|
+
let binary = "";
|
|
8
|
+
for (const byte of bytes) binary += String.fromCharCode(byte);
|
|
9
|
+
return btoa(binary);
|
|
10
|
+
}
|
|
11
|
+
function base64ToBytes(base64) {
|
|
12
|
+
const binary = atob(base64);
|
|
13
|
+
const bytes = new Uint8Array(binary.length);
|
|
14
|
+
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
|
|
15
|
+
return bytes;
|
|
16
|
+
}
|
|
17
|
+
//#endregion
|
|
18
|
+
//#region src/document/mirror-schema.ts
|
|
19
|
+
/**
|
|
20
|
+
* Declarative `loro-mirror` schema for `VideoDocument` — the canonical structural
|
|
21
|
+
* SSOT and live storage wire (replaces the hand-rolled `@mengine/schema`
|
|
22
|
+
* definition + adapter, see ADR 0008).
|
|
23
|
+
*
|
|
24
|
+
* Mirror gives an in-memory immutable state synced to the Loro doc by declarative
|
|
25
|
+
* diff, so the storage layer no longer hand-writes per-region reconcile or a
|
|
26
|
+
* transaction state machine. The shapes here store only authoritative facts
|
|
27
|
+
* (RFC 02 §6): per-item absolute time, `part_aggregations`, and total duration
|
|
28
|
+
* are projection-derived (cascade-solved at read time), so they are absent here.
|
|
29
|
+
*
|
|
30
|
+
* - tracks live in a single `tracks` `LoroMovableList` keyed by track id
|
|
31
|
+
* (reference/17 §4). Lane is expressed by each track's `parts_kind`, not by
|
|
32
|
+
* which container it lives in; order is the movable-list order itself. There is
|
|
33
|
+
* no `lane` / `lane_order` field, so two peers inserting tracks never collide
|
|
34
|
+
* on an order integer — list moves are conflict-free (RFC 03 §4). The legacy
|
|
35
|
+
* keyed-map (`LoroMapRecord` + an integer `lane_order`) and the prior three
|
|
36
|
+
* named containers are gone; the `main` / `above` / `below` three-pane view is
|
|
37
|
+
* rebuilt by the projection from `parts_kind`.
|
|
38
|
+
* - each track's `items` is a `LoroMovableList` keyed by `part_id`: a part is
|
|
39
|
+
* placed at most once per lane, so `part_id` is the stable placement identity.
|
|
40
|
+
* Reorder diffs to a real Loro `move`, preserving per-item CRDT identity on
|
|
41
|
+
* every lane (main and secondary alike).
|
|
42
|
+
* - `time_position` is the authoritative positioning fact (RFC 02 §4,
|
|
43
|
+
* reference/17 §3), carried as an opaque JSON blob string (a whole tagged-union
|
|
44
|
+
* value, last-writer-wins). The derived `fallback_abs_ms` snapshot sits beside
|
|
45
|
+
* it as its own number field — a separate LWW unit so a projection refresh
|
|
46
|
+
* never clobbers a `time_position` edit.
|
|
47
|
+
* - meta lives in a `meta` LoroMap: the mirror root only accepts container
|
|
48
|
+
* schemas, so meta scalars can't sit at the root as bare values. The domain
|
|
49
|
+
* `VideoDocument` keeps the same `meta` wrapper, so the shapes are isomorphic
|
|
50
|
+
* and the read/seed mapping is a near-identity.
|
|
51
|
+
* - `part_library` values are nested `LoroMap`s: the value is a `LoroMap` with
|
|
52
|
+
* four mutually-exclusive optional part sub-maps (`video_clip` / `speech` /
|
|
53
|
+
* `caption` / `bgm`), each a `LoroMap` whose fields are stored as real Loro
|
|
54
|
+
* sub-keys. This makes each field its own CRDT unit, so two peers editing
|
|
55
|
+
* different fields of the same part (e.g. one volume, one play_out) merge
|
|
56
|
+
* field-by-field instead of one whole-value overwrite. Field `required` mirrors
|
|
57
|
+
* the Smithy `@required` contract (see `video_draft_comp.smithy`). `kind` is not
|
|
58
|
+
* stored (the present sub-key names the kind); `duration_ms` is not stored (it
|
|
59
|
+
* is derived, reference/17 §5). Nested values that the engine does not edit
|
|
60
|
+
* field-by-field — `speed_shift` (a tagged union), `voice`, `caption_ids` — stay
|
|
61
|
+
* as opaque JSON-blob sub-keys via `transform`. The four sub-keys are optional,
|
|
62
|
+
* so the "exactly one part kind" union invariant is not enforced by the schema
|
|
63
|
+
* type; it is rebuilt by `draftToPartUnion` on read and gated by zod on write.
|
|
64
|
+
* - a caption's `style` is the one lazily-created optional child container, so
|
|
65
|
+
* `captionPart` sets `mergeableMapChildContainers: true` — two peers can
|
|
66
|
+
* concurrently first-create the same caption's `style` (one attribute each), and
|
|
67
|
+
* only a mergeable child converges instead of last-writer-wins dropping one. All
|
|
68
|
+
* other nested maps are keyed by a unique id (`part_library`) or created
|
|
69
|
+
* atomically with their parent (`partValue`'s part sub-map), so they never hit
|
|
70
|
+
* that concurrent-first-create fork and stay on plain `setContainer`. See the
|
|
71
|
+
* note on `captionPart` below.
|
|
72
|
+
* - `video_creation_settings` is an opaque JSON blob carried in a string via
|
|
73
|
+
* `transform`: a whole value, last-writer-wins (no field-level concurrent edits).
|
|
74
|
+
*/
|
|
75
|
+
/**
|
|
76
|
+
* JSON-blob transform for an opaque, last-writer-wins value carried in a Loro
|
|
77
|
+
* string. The field must be declared `required: false`: an absent field decodes
|
|
78
|
+
* to `undefined` (mirror never calls `decode`/`encode` for null/undefined),
|
|
79
|
+
* which is how we represent "no value" instead of encoding a `null` sentinel.
|
|
80
|
+
*/
|
|
81
|
+
function jsonTransform() {
|
|
82
|
+
return {
|
|
83
|
+
decode: (value) => JSON.parse(value),
|
|
84
|
+
encode: (value) => JSON.stringify(value),
|
|
85
|
+
isEqual: "encoded-value-equality"
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
const trackItem = schema.LoroMap({
|
|
89
|
+
part_id: schema.String(),
|
|
90
|
+
time_position: schema.String().transform(jsonTransform()),
|
|
91
|
+
fallback_abs_ms: schema.Number({ required: false })
|
|
92
|
+
});
|
|
93
|
+
const track = schema.LoroMap({
|
|
94
|
+
id: schema.String(),
|
|
95
|
+
parts_kind: schema.String({ required: false }),
|
|
96
|
+
is_hidden: schema.Boolean({ required: false }),
|
|
97
|
+
items: schema.LoroMovableList(trackItem, (item) => item.part_id)
|
|
98
|
+
});
|
|
99
|
+
const videoClipPart = schema.LoroMap({
|
|
100
|
+
id: schema.String(),
|
|
101
|
+
play_in: schema.Number(),
|
|
102
|
+
play_out: schema.Number(),
|
|
103
|
+
volume: schema.Number(),
|
|
104
|
+
origin_media_id: schema.String(),
|
|
105
|
+
speed_shift: schema.String({ required: false }).transform(jsonTransform())
|
|
106
|
+
}, { required: false });
|
|
107
|
+
const speechPart = schema.LoroMap({
|
|
108
|
+
id: schema.String(),
|
|
109
|
+
media_duration_ms: schema.Number(),
|
|
110
|
+
audio_script: schema.String(),
|
|
111
|
+
volume: schema.Number(),
|
|
112
|
+
audio_storage_key: schema.String(),
|
|
113
|
+
origin_speech_id: schema.String(),
|
|
114
|
+
voice: schema.String().transform(jsonTransform()),
|
|
115
|
+
caption_ids: schema.String().transform(jsonTransform())
|
|
116
|
+
}, { required: false });
|
|
117
|
+
const captionStyle = schema.LoroMap({
|
|
118
|
+
font_id: schema.String({ required: false }),
|
|
119
|
+
font_size: schema.Number({ required: false }),
|
|
120
|
+
font_color: schema.String({ required: false }),
|
|
121
|
+
font_weight: schema.Number({ required: false }),
|
|
122
|
+
entrance_animation: schema.String({ required: false }),
|
|
123
|
+
entrance_animation_duration_ms: schema.Number({ required: false }),
|
|
124
|
+
stroke_color: schema.String({ required: false }),
|
|
125
|
+
stroke_width: schema.Number({ required: false }),
|
|
126
|
+
position_x: schema.Number({ required: false }),
|
|
127
|
+
position_y: schema.Number({ required: false })
|
|
128
|
+
}, { required: false });
|
|
129
|
+
const captionPart = schema.LoroMap({
|
|
130
|
+
id: schema.String(),
|
|
131
|
+
initial_duration_ms: schema.Number(),
|
|
132
|
+
speech_part_id: schema.String(),
|
|
133
|
+
text: schema.String(),
|
|
134
|
+
start_ms: schema.Number(),
|
|
135
|
+
style: captionStyle
|
|
136
|
+
}, {
|
|
137
|
+
required: false,
|
|
138
|
+
mergeableMapChildContainers: true
|
|
139
|
+
});
|
|
140
|
+
const bgmPart = schema.LoroMap({
|
|
141
|
+
id: schema.String(),
|
|
142
|
+
audio_storage_key: schema.String(),
|
|
143
|
+
volume: schema.Number(),
|
|
144
|
+
origin_media_id: schema.String()
|
|
145
|
+
}, { required: false });
|
|
146
|
+
const partValue = schema.LoroMap({
|
|
147
|
+
video_clip: videoClipPart,
|
|
148
|
+
speech: speechPart,
|
|
149
|
+
caption: captionPart,
|
|
150
|
+
bgm: bgmPart
|
|
151
|
+
});
|
|
152
|
+
const videoDocumentMirrorSchema = schema({
|
|
153
|
+
meta: schema.LoroMap({
|
|
154
|
+
schema_version: schema.String({ required: false }),
|
|
155
|
+
draft_id: schema.String({ required: false }),
|
|
156
|
+
project_id: schema.String({ required: false }),
|
|
157
|
+
owner_id: schema.String({ required: false }),
|
|
158
|
+
thumbnail_storage_key: schema.String({ required: false }),
|
|
159
|
+
chat_session_id: schema.String({ required: false }),
|
|
160
|
+
video_creation_settings: schema.String({ required: false }).transform(jsonTransform()),
|
|
161
|
+
version: schema.Number({ required: false })
|
|
162
|
+
}),
|
|
163
|
+
timeline: schema.LoroMap({ unit_time_ms: schema.Number({ required: false }) }),
|
|
164
|
+
tracks: schema.LoroMovableList(track, (t) => t.id),
|
|
165
|
+
part_library: schema.LoroMapRecord(partValue)
|
|
166
|
+
});
|
|
167
|
+
/** Project a discriminated `PartUnion` into the draft's four-optional shape. */
|
|
168
|
+
function partUnionToDraft(part) {
|
|
169
|
+
if (part.video_clip != null) return { video_clip: omitKind(part.video_clip) };
|
|
170
|
+
if (part.speech != null) return { speech: omitKind(part.speech) };
|
|
171
|
+
if (part.caption != null) return { caption: omitKind(part.caption) };
|
|
172
|
+
return { bgm: omitKind(part.bgm) };
|
|
173
|
+
}
|
|
174
|
+
/**
|
|
175
|
+
* Rebuild a discriminated `PartUnion` from a draft part value: pick the one
|
|
176
|
+
* present sub-key, restore its `kind`, and drop the `$cid`. Returns `undefined`
|
|
177
|
+
* when no part sub-key is present (an empty/placeholder value).
|
|
178
|
+
*/
|
|
179
|
+
function draftToPartUnion(value) {
|
|
180
|
+
if (value == null) return void 0;
|
|
181
|
+
const v = value;
|
|
182
|
+
if (v.video_clip != null) return { video_clip: withKind(v.video_clip, "video_clip") };
|
|
183
|
+
if (v.speech != null) return { speech: withKind(v.speech, "speech") };
|
|
184
|
+
if (v.caption != null) return { caption: withKind(v.caption, "caption") };
|
|
185
|
+
if (v.bgm != null) return { bgm: withKind(v.bgm, "bgm") };
|
|
186
|
+
}
|
|
187
|
+
/** Drop `kind` (not stored) and `$cid` from a part payload for the draft. */
|
|
188
|
+
function omitKind(part) {
|
|
189
|
+
const { kind: _kind, $cid: _cid, ...rest } = part;
|
|
190
|
+
return rest;
|
|
191
|
+
}
|
|
192
|
+
/** Restore `kind` (and drop `$cid`) on a part sub-map read from the draft. */
|
|
193
|
+
function withKind(part, kind) {
|
|
194
|
+
const { $cid: _cid, ...rest } = part;
|
|
195
|
+
return {
|
|
196
|
+
...rest,
|
|
197
|
+
kind
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
/** Entries of a draft record (e.g. `tracks`) with `$cid` stripped. */
|
|
201
|
+
function recordEntries(record) {
|
|
202
|
+
if (record == null) return [];
|
|
203
|
+
const out = [];
|
|
204
|
+
for (const [key, value] of Object.entries(record)) {
|
|
205
|
+
if (key === "$cid") continue;
|
|
206
|
+
out.push([key, value]);
|
|
207
|
+
}
|
|
208
|
+
return out;
|
|
209
|
+
}
|
|
210
|
+
//#endregion
|
|
211
|
+
//#region src/document/types.ts
|
|
212
|
+
const VIDEO_DOCUMENT_SCHEMA_VERSION = "video-document/v0";
|
|
213
|
+
/** The linear speed multiplier of a `speed_shift`, defaulting to 1 (original). */
|
|
214
|
+
function speedOf(speedShift) {
|
|
215
|
+
const speed = speedShift?.config?.linear?.speed;
|
|
216
|
+
return typeof speed === "number" && Number.isFinite(speed) && speed > 0 ? speed : 1;
|
|
217
|
+
}
|
|
218
|
+
/**
|
|
219
|
+
* A video clip's effective timeline duration, derived from authoritative facts
|
|
220
|
+
* (RFC 02, `reference/16` §4, reference/17 §5): the trim window
|
|
221
|
+
* `play_out - play_in` divided by the speed multiplier, rounded to integer ms.
|
|
222
|
+
* `play_in` / `play_out` are optional in the IDL but every write path sets them
|
|
223
|
+
* (defaulting to the whole media), and the legacy-ingest projection backfills the
|
|
224
|
+
* window from a legacy `duration_ms` — so an authoritative clip always carries a
|
|
225
|
+
* trim window and there is no stored `duration_ms` to fall back to. A clip with
|
|
226
|
+
* neither bound yields 0. Speeds the clip up (>1× → shorter) or down (<1×).
|
|
227
|
+
*/
|
|
228
|
+
function effectiveVideoClipDurationMs(clip) {
|
|
229
|
+
const speed = speedOf(clip.speed_shift);
|
|
230
|
+
const sourceMs = (clip.play_out ?? 0) - (clip.play_in ?? 0);
|
|
231
|
+
const effective = Math.round(sourceMs / speed);
|
|
232
|
+
return Number.isFinite(effective) && effective > 0 ? effective : 0;
|
|
233
|
+
}
|
|
234
|
+
//#endregion
|
|
235
|
+
//#region src/timeline-core/types.ts
|
|
236
|
+
/** Total document duration when there is no real content (matches FE bgm fallback). */
|
|
237
|
+
const TIMELINE_SKELETON_DURATION_MS = 2e4;
|
|
238
|
+
/** Empty placeholder clip marker: a video_clip part with no backing media. */
|
|
239
|
+
function isEmptyVideoClip(part) {
|
|
240
|
+
const clip = part?.video_clip;
|
|
241
|
+
if (clip == null) return false;
|
|
242
|
+
return clip.origin_media_id == null || clip.origin_media_id === "";
|
|
243
|
+
}
|
|
244
|
+
/** Clamp a duration to a non-negative integer (NaN/Infinity/negative → 0). */
|
|
245
|
+
function safeDurationMs(value) {
|
|
246
|
+
const n = Number(value);
|
|
247
|
+
if (!Number.isFinite(n) || n <= 0) return 0;
|
|
248
|
+
return Math.round(n);
|
|
249
|
+
}
|
|
250
|
+
function partDurationMs(doc, partId) {
|
|
251
|
+
const part = doc.part_library[partId];
|
|
252
|
+
if (part?.video_clip != null) return safeDurationMs(effectiveVideoClipDurationMs(part.video_clip));
|
|
253
|
+
if (part?.bgm != null) return doc.timeline.duration_ms > 0 ? doc.timeline.duration_ms : TIMELINE_SKELETON_DURATION_MS;
|
|
254
|
+
if (part?.speech != null) return safeDurationMs(part.speech.media_duration_ms);
|
|
255
|
+
if (part?.caption != null) return safeDurationMs(part.caption.initial_duration_ms);
|
|
256
|
+
return 0;
|
|
257
|
+
}
|
|
258
|
+
//#endregion
|
|
259
|
+
//#region src/timeline-core/cascade.ts
|
|
260
|
+
/**
|
|
261
|
+
* Canonical timeline cascade primitives (ADR 0009).
|
|
262
|
+
*
|
|
263
|
+
* Single source of truth for "how an edit's connected regions move": main-track
|
|
264
|
+
* seamless layout, aggregation position sync + reassignment, total-duration
|
|
265
|
+
* recompute, speech-overlap resolution, gap filling. Reconciled per ADR 0009 §4:
|
|
266
|
+
*
|
|
267
|
+
* - product behavior follows the FE current implementation;
|
|
268
|
+
* - all times are integer ms — positions/durations are rounded, never floated;
|
|
269
|
+
* - function decomposition follows agent-harness (the Python-derived structure).
|
|
270
|
+
*
|
|
271
|
+
* Every function mutates the `TimelineDoc` in place (the editor runs them inside
|
|
272
|
+
* one immer `transact`, so in-place edits diff correctly).
|
|
273
|
+
*/
|
|
274
|
+
/**
|
|
275
|
+
* Lay the main track out head-to-tail from 0, rewriting each item's
|
|
276
|
+
* `abs_time_position`. Items whose part is missing from the library are dropped.
|
|
277
|
+
*/
|
|
278
|
+
function arrangeMainTrackSeamlessly(doc) {
|
|
279
|
+
const kept = [];
|
|
280
|
+
let cursor = 0;
|
|
281
|
+
for (const item of doc.main_track) {
|
|
282
|
+
if (doc.part_library[item.part_id] == null) continue;
|
|
283
|
+
item.abs_time_position = cursor;
|
|
284
|
+
cursor += partDurationMs(doc, item.part_id);
|
|
285
|
+
kept.push(item);
|
|
286
|
+
}
|
|
287
|
+
doc.main_track = kept;
|
|
288
|
+
}
|
|
289
|
+
/**
|
|
290
|
+
* Sync attached parts' absolute positions from their host:
|
|
291
|
+
* speech.abs = host_video.abs + relative_time_position
|
|
292
|
+
* caption.abs = speech.abs + caption.start_ms
|
|
293
|
+
*/
|
|
294
|
+
function syncAggregatedClipsTimePosition(doc) {
|
|
295
|
+
const videoByPart = indexByPart(doc.main_track);
|
|
296
|
+
const speechByPart = indexByPart(doc.speech_track);
|
|
297
|
+
for (const aggregation of doc.aggregations) {
|
|
298
|
+
const videoItem = videoByPart.get(aggregation.body_part_id);
|
|
299
|
+
if (videoItem == null) continue;
|
|
300
|
+
for (const attachment of aggregation.attachments) {
|
|
301
|
+
const speechItem = speechByPart.get(attachment.part_id);
|
|
302
|
+
if (speechItem == null) continue;
|
|
303
|
+
speechItem.abs_time_position = videoItem.abs_time_position + attachment.relative_time_position;
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
for (const captionItem of doc.caption_track) {
|
|
307
|
+
const captionPart = doc.part_library[captionItem.part_id]?.caption;
|
|
308
|
+
if (captionPart == null) continue;
|
|
309
|
+
const speechItem = captionPart.speech_part_id == null ? void 0 : speechByPart.get(captionPart.speech_part_id);
|
|
310
|
+
if (speechItem == null) continue;
|
|
311
|
+
captionItem.abs_time_position = speechItem.abs_time_position + safeDurationMs(captionPart.start_ms);
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
/**
|
|
315
|
+
* Reassign each speech to the video clip whose time range contains its start,
|
|
316
|
+
* rebuilding `aggregations`. A speech before the first clip or after the last
|
|
317
|
+
* falls back to the first / last clip respectively (FE: see §4 note — FE falls
|
|
318
|
+
* back to last only; we keep the harness two-sided fallback because a speech
|
|
319
|
+
* dragged before clip 0 belonging to the last clip is clearly wrong, and the FE
|
|
320
|
+
* single-sided rule is an acknowledged rough edge). `relative_time_position` is
|
|
321
|
+
* clamped to a non-negative integer.
|
|
322
|
+
*/
|
|
323
|
+
function reassignSpeechesToVideoClipsByTime(doc) {
|
|
324
|
+
const ranges = doc.main_track.filter((item) => doc.part_library[item.part_id] != null).map((item) => ({
|
|
325
|
+
part_id: item.part_id,
|
|
326
|
+
start: item.abs_time_position,
|
|
327
|
+
end: item.abs_time_position + partDurationMs(doc, item.part_id)
|
|
328
|
+
}));
|
|
329
|
+
if (ranges.length === 0) {
|
|
330
|
+
doc.aggregations = [];
|
|
331
|
+
return;
|
|
332
|
+
}
|
|
333
|
+
const rebuilt = /* @__PURE__ */ new Map();
|
|
334
|
+
for (const speechItem of doc.speech_track) {
|
|
335
|
+
const start = speechItem.abs_time_position;
|
|
336
|
+
const targetRange = ranges.find((r) => r.start <= start && start < r.end) ?? (start < ranges[0].start ? ranges[0] : ranges[ranges.length - 1]);
|
|
337
|
+
const relative = Math.max(0, Math.round(start - targetRange.start));
|
|
338
|
+
const targetId = targetRange.part_id;
|
|
339
|
+
let aggregation = rebuilt.get(targetId);
|
|
340
|
+
if (aggregation == null) {
|
|
341
|
+
aggregation = {
|
|
342
|
+
body_part_id: targetId,
|
|
343
|
+
attachments: []
|
|
344
|
+
};
|
|
345
|
+
rebuilt.set(targetId, aggregation);
|
|
346
|
+
}
|
|
347
|
+
aggregation.attachments.push({
|
|
348
|
+
part_id: speechItem.part_id,
|
|
349
|
+
relative_time_position: relative
|
|
350
|
+
});
|
|
351
|
+
}
|
|
352
|
+
doc.aggregations = ranges.map((r) => rebuilt.get(r.part_id)).filter((a) => a != null);
|
|
353
|
+
}
|
|
354
|
+
/**
|
|
355
|
+
* Recompute `timeline.duration_ms` as the max end (abs + duration) across main,
|
|
356
|
+
* speech, and caption lanes (BGM does not extend the timeline).
|
|
357
|
+
*
|
|
358
|
+
* BGM has no authoritative duration (RFC 02 / `reference/16` §0b): its effective
|
|
359
|
+
* length is always the timeline total, so it is not written back here — the
|
|
360
|
+
* projection derives it from `timeline.duration_ms` on read (`partDurationMs`
|
|
361
|
+
* returns the timeline total for a bgm part). The empty-document 20s skeleton is
|
|
362
|
+
* applied at that read step, not stored.
|
|
363
|
+
*/
|
|
364
|
+
function recalculateTimelineDuration(doc) {
|
|
365
|
+
const max = Math.max(laneEndMs(doc, doc.main_track), laneEndMs(doc, doc.speech_track), laneEndMs(doc, doc.caption_track));
|
|
366
|
+
doc.timeline.duration_ms = max;
|
|
367
|
+
}
|
|
368
|
+
/**
|
|
369
|
+
* Resolve one speech overlap by shifting the overlapping speech's host video
|
|
370
|
+
* (and every clip after it) right. Returns true when one overlap was resolved;
|
|
371
|
+
* callers loop until it returns false. The compared range is the speech merged
|
|
372
|
+
* with its captions: start = min(speech.start, captions.start) (FE behavior),
|
|
373
|
+
* end = max(speech.end, captions.end).
|
|
374
|
+
*/
|
|
375
|
+
function resolveSpeechOverlapByShiftingVideos(doc) {
|
|
376
|
+
const speeches = doc.speech_track;
|
|
377
|
+
for (let i = 1; i < speeches.length; i++) {
|
|
378
|
+
const prev = speechWithCaptionsRange(doc, speeches[i - 1]);
|
|
379
|
+
const curr = speechWithCaptionsRange(doc, speeches[i]);
|
|
380
|
+
if (prev == null || curr == null) continue;
|
|
381
|
+
if (curr.start >= prev.end) continue;
|
|
382
|
+
const overlapMs = Math.round(prev.end - curr.start);
|
|
383
|
+
const hostId = hostVideoOf(doc, speeches[i].part_id);
|
|
384
|
+
if (hostId == null) continue;
|
|
385
|
+
const fromIndex = doc.main_track.findIndex((item) => item.part_id === hostId);
|
|
386
|
+
if (fromIndex < 0) continue;
|
|
387
|
+
for (let idx = fromIndex; idx < doc.main_track.length; idx++) doc.main_track[idx].abs_time_position += overlapMs;
|
|
388
|
+
syncAggregatedClipsTimePosition(doc);
|
|
389
|
+
return true;
|
|
390
|
+
}
|
|
391
|
+
return false;
|
|
392
|
+
}
|
|
393
|
+
/**
|
|
394
|
+
* Resolve speech overlaps for one cascade pass. Mirrors the authoritative FE
|
|
395
|
+
* `ensureNoOverlappingClips`, which is documented to resolve AT MOST ONE overlap
|
|
396
|
+
* per cascade and is invoked exactly once at every FE call site — the supported
|
|
397
|
+
* ops each produce at most one new overlap. It is NOT a fixpoint loop: shifting a
|
|
398
|
+
* host right also moves every speech anchored to it, so two speeches sharing a
|
|
399
|
+
* host can never be separated by shifting. Looping to a "fixed point" there does
|
|
400
|
+
* not converge — it accumulates the same overlap every iteration and pushes the
|
|
401
|
+
* clip arbitrarily far right (e.g. a sped-up clip landing at ~287k ms instead of
|
|
402
|
+
* its seamless slot). A single pass matches FE product behavior and terminates.
|
|
403
|
+
*/
|
|
404
|
+
function resolveAllSpeechOverlaps(doc) {
|
|
405
|
+
resolveSpeechOverlapByShiftingVideos(doc);
|
|
406
|
+
}
|
|
407
|
+
/**
|
|
408
|
+
* Make the main track gapless by adjusting/merging empty placeholder clips or
|
|
409
|
+
* inserting new ones between real clips. Mirrors the harness four-case rule, but
|
|
410
|
+
* the merge of two adjacent empty clips keeps the earlier clip (harness Case 4).
|
|
411
|
+
* Requires `makeEmptyPart` to mint a placeholder part (the editor supplies an
|
|
412
|
+
* id generator).
|
|
413
|
+
*/
|
|
414
|
+
function fillMainTrackTimeGaps(doc, makeEmptyPart) {
|
|
415
|
+
const items = doc.main_track;
|
|
416
|
+
let i = 0;
|
|
417
|
+
while (i < items.length) {
|
|
418
|
+
const current = items[i];
|
|
419
|
+
const currentPart = doc.part_library[current.part_id];
|
|
420
|
+
if (currentPart == null) {
|
|
421
|
+
i += 1;
|
|
422
|
+
continue;
|
|
423
|
+
}
|
|
424
|
+
const currentEnd = current.abs_time_position + partDurationMs(doc, current.part_id);
|
|
425
|
+
if (i + 1 >= items.length) break;
|
|
426
|
+
const next = items[i + 1];
|
|
427
|
+
const nextPart = doc.part_library[next.part_id];
|
|
428
|
+
if (nextPart == null) {
|
|
429
|
+
i += 1;
|
|
430
|
+
continue;
|
|
431
|
+
}
|
|
432
|
+
const gap = next.abs_time_position - currentEnd;
|
|
433
|
+
if (gap > 0) {
|
|
434
|
+
if (isEmptyVideoClip(currentPart)) {
|
|
435
|
+
extendEmptyClip(currentPart.video_clip, gap);
|
|
436
|
+
continue;
|
|
437
|
+
}
|
|
438
|
+
if (isEmptyVideoClip(nextPart)) {
|
|
439
|
+
next.abs_time_position -= gap;
|
|
440
|
+
extendEmptyClip(nextPart.video_clip, gap);
|
|
441
|
+
i += 1;
|
|
442
|
+
continue;
|
|
443
|
+
}
|
|
444
|
+
const { partId } = makeEmptyPart(gap);
|
|
445
|
+
doc.part_library[partId] = { video_clip: {
|
|
446
|
+
id: partId,
|
|
447
|
+
kind: "video_clip",
|
|
448
|
+
play_in: 0,
|
|
449
|
+
play_out: gap,
|
|
450
|
+
volume: 0,
|
|
451
|
+
origin_media_id: ""
|
|
452
|
+
} };
|
|
453
|
+
items.splice(i + 1, 0, {
|
|
454
|
+
part_id: partId,
|
|
455
|
+
time_position: { mode: "sequential" },
|
|
456
|
+
abs_time_position: currentEnd
|
|
457
|
+
});
|
|
458
|
+
i += 1;
|
|
459
|
+
continue;
|
|
460
|
+
}
|
|
461
|
+
if (gap === 0 && isEmptyVideoClip(currentPart) && isEmptyVideoClip(nextPart)) {
|
|
462
|
+
extendEmptyClip(currentPart.video_clip, partDurationMs(doc, next.part_id));
|
|
463
|
+
items.splice(i + 1, 1);
|
|
464
|
+
delete doc.part_library[next.part_id];
|
|
465
|
+
continue;
|
|
466
|
+
}
|
|
467
|
+
i += 1;
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
function indexByPart(items) {
|
|
471
|
+
const map = /* @__PURE__ */ new Map();
|
|
472
|
+
for (const item of items) map.set(item.part_id, item);
|
|
473
|
+
return map;
|
|
474
|
+
}
|
|
475
|
+
function laneEndMs(doc, items) {
|
|
476
|
+
let max = 0;
|
|
477
|
+
for (const item of items) {
|
|
478
|
+
if (doc.part_library[item.part_id] == null) continue;
|
|
479
|
+
const end = item.abs_time_position + partDurationMs(doc, item.part_id);
|
|
480
|
+
if (end > max) max = end;
|
|
481
|
+
}
|
|
482
|
+
return max;
|
|
483
|
+
}
|
|
484
|
+
function extendEmptyClip(clip, byMs) {
|
|
485
|
+
clip.play_out = safeDurationMs(clip.play_out) + byMs;
|
|
486
|
+
}
|
|
487
|
+
/** speech merged with its captions: start = min, end = max. */
|
|
488
|
+
function speechWithCaptionsRange(doc, speechItem) {
|
|
489
|
+
const speech = doc.part_library[speechItem.part_id]?.speech;
|
|
490
|
+
if (speech == null) return null;
|
|
491
|
+
let start = speechItem.abs_time_position;
|
|
492
|
+
let end = speechItem.abs_time_position + safeDurationMs(speech.media_duration_ms);
|
|
493
|
+
for (const captionId of captionIdsOf(speech)) {
|
|
494
|
+
const captionItem = doc.caption_track.find((item) => item.part_id === captionId);
|
|
495
|
+
const captionPart = doc.part_library[captionId]?.caption;
|
|
496
|
+
if (captionItem == null || captionPart == null) continue;
|
|
497
|
+
const cStart = captionItem.abs_time_position;
|
|
498
|
+
const cEnd = captionItem.abs_time_position + safeDurationMs(captionPart.initial_duration_ms);
|
|
499
|
+
if (cStart < start) start = cStart;
|
|
500
|
+
if (cEnd > end) end = cEnd;
|
|
501
|
+
}
|
|
502
|
+
return {
|
|
503
|
+
start,
|
|
504
|
+
end
|
|
505
|
+
};
|
|
506
|
+
}
|
|
507
|
+
function captionIdsOf(speech) {
|
|
508
|
+
return (speech.caption_ids ?? []).filter((id) => id != null);
|
|
509
|
+
}
|
|
510
|
+
function hostVideoOf(doc, speechPartId) {
|
|
511
|
+
for (const aggregation of doc.aggregations) if (aggregation.attachments.some((att) => att.part_id === speechPartId)) return aggregation.body_part_id;
|
|
512
|
+
return null;
|
|
513
|
+
}
|
|
514
|
+
//#endregion
|
|
515
|
+
//#region src/timeline-core/entrypoints.ts
|
|
516
|
+
/**
|
|
517
|
+
* The full solve pipeline: arrange → sync → reassign → resolve-overlap →
|
|
518
|
+
* fill-gaps → recalc. The single cascade the read-side projection runs; ops
|
|
519
|
+
* never call it (they write only facts — RFC 02 §7/§10).
|
|
520
|
+
*/
|
|
521
|
+
function cascadeAfterVideoClipChanges(doc, makeEmptyPart) {
|
|
522
|
+
arrangeMainTrackSeamlessly(doc);
|
|
523
|
+
syncAggregatedClipsTimePosition(doc);
|
|
524
|
+
reassignSpeechesToVideoClipsByTime(doc);
|
|
525
|
+
resolveAllSpeechOverlaps(doc);
|
|
526
|
+
fillMainTrackTimeGaps(doc, makeEmptyPart);
|
|
527
|
+
recalculateTimelineDuration(doc);
|
|
528
|
+
}
|
|
529
|
+
//#endregion
|
|
530
|
+
//#region src/timeline-core/bridge.ts
|
|
531
|
+
/**
|
|
532
|
+
* Solve a `VideoDocument` (authoritative, position-only) into its derived
|
|
533
|
+
* read-view: absolute time per item, `part_aggregations`, and total duration.
|
|
534
|
+
* This is the read side of the single-directional flow — never written back.
|
|
535
|
+
*/
|
|
536
|
+
function solveVideoDocument(document) {
|
|
537
|
+
const doc = videoDocumentToTimelineDoc(document);
|
|
538
|
+
let counter = 0;
|
|
539
|
+
cascadeAfterVideoClipChanges(doc, () => ({ partId: `empty_${counter++}` }));
|
|
540
|
+
const absByPartId = /* @__PURE__ */ new Map();
|
|
541
|
+
for (const item of doc.main_track) absByPartId.set(item.part_id, item.abs_time_position);
|
|
542
|
+
for (const item of doc.speech_track) absByPartId.set(item.part_id, item.abs_time_position);
|
|
543
|
+
for (const item of doc.caption_track) absByPartId.set(item.part_id, item.abs_time_position);
|
|
544
|
+
for (const item of doc.bgm_track) absByPartId.set(item.part_id, item.abs_time_position);
|
|
545
|
+
return {
|
|
546
|
+
absByPartId,
|
|
547
|
+
aggregations: doc.aggregations.map((aggregation) => ({
|
|
548
|
+
body_part_id: aggregation.body_part_id,
|
|
549
|
+
attachments: aggregation.attachments.map((a) => ({
|
|
550
|
+
part_id: a.part_id,
|
|
551
|
+
relative_time_position: a.relative_time_position
|
|
552
|
+
}))
|
|
553
|
+
})),
|
|
554
|
+
durationMs: doc.timeline.duration_ms,
|
|
555
|
+
partLibrary: doc.part_library
|
|
556
|
+
};
|
|
557
|
+
}
|
|
558
|
+
function videoDocumentToTimelineDoc(document) {
|
|
559
|
+
const partLibrary = {};
|
|
560
|
+
for (const [partId, part] of Object.entries(document.part_library ?? {})) partLibrary[partId] = part;
|
|
561
|
+
const laneItems = (track) => (track?.items ?? []).map((item) => ({
|
|
562
|
+
part_id: item.part_id,
|
|
563
|
+
time_position: item.time_position,
|
|
564
|
+
abs_time_position: seedAbs(item.time_position, item.fallback_abs_ms),
|
|
565
|
+
fallback_abs_ms: item.fallback_abs_ms
|
|
566
|
+
}));
|
|
567
|
+
const tracks = document.tracks ?? [];
|
|
568
|
+
let mainItems = [];
|
|
569
|
+
let speechItems = [];
|
|
570
|
+
let bgmItems = [];
|
|
571
|
+
let captionItems = [];
|
|
572
|
+
for (const t of tracks) switch (t.parts_kind) {
|
|
573
|
+
case "video_clip":
|
|
574
|
+
mainItems = mainItems.concat(laneItems(t));
|
|
575
|
+
break;
|
|
576
|
+
case "speech":
|
|
577
|
+
speechItems = speechItems.concat(laneItems(t));
|
|
578
|
+
break;
|
|
579
|
+
case "bgm":
|
|
580
|
+
bgmItems = bgmItems.concat(laneItems(t));
|
|
581
|
+
break;
|
|
582
|
+
case "caption":
|
|
583
|
+
captionItems = captionItems.concat(laneItems(t));
|
|
584
|
+
break;
|
|
585
|
+
}
|
|
586
|
+
return {
|
|
587
|
+
main_track: mainItems,
|
|
588
|
+
speech_track: speechItems,
|
|
589
|
+
caption_track: captionItems,
|
|
590
|
+
bgm_track: bgmItems,
|
|
591
|
+
part_library: partLibrary,
|
|
592
|
+
aggregations: seedAggregations(mainItems, speechItems),
|
|
593
|
+
timeline: {
|
|
594
|
+
duration_ms: 0,
|
|
595
|
+
unit_time_ms: document.timeline?.unit_time_ms ?? 0
|
|
596
|
+
}
|
|
597
|
+
};
|
|
598
|
+
}
|
|
599
|
+
/**
|
|
600
|
+
* Seed an item's solve-variable `abs_time_position` from its `time_position` (and
|
|
601
|
+
* the `fallback_abs_ms` snapshot carried beside it): `absolute` → `offsetMs`;
|
|
602
|
+
* `anchored` → `fallbackAbsMs` (last solved position, also the orphan-recovery
|
|
603
|
+
* anchor when the host is gone); `sequential` → 0 (the cascade lays the main
|
|
604
|
+
* track out head-to-tail). The cascade then resolves anchored items against their
|
|
605
|
+
* host, so this seed only needs to put each item somewhere plausible for the
|
|
606
|
+
* first reassign/overlap pass.
|
|
607
|
+
*/
|
|
608
|
+
function seedAbs(position, fallbackAbsMs) {
|
|
609
|
+
switch (position.mode) {
|
|
610
|
+
case "absolute": return Math.round(position.offsetMs);
|
|
611
|
+
case "anchored": return Math.round(fallbackAbsMs ?? 0);
|
|
612
|
+
case "sequential": return 0;
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
/**
|
|
616
|
+
* Build the cascade `aggregations` parent-map from anchored items: an anchored
|
|
617
|
+
* item's `anchorPartId` is the host's `part_id` (= `body_part_id`), `offsetMs`
|
|
618
|
+
* is `relative_time_position`. Only main-track (video) hosts form aggregations;
|
|
619
|
+
* caption→speech relations are recomputed by the cascade from `caption.start_ms`.
|
|
620
|
+
*/
|
|
621
|
+
function seedAggregations(mainItems, speechItems) {
|
|
622
|
+
const mainPartIds = new Set(mainItems.map((item) => item.part_id));
|
|
623
|
+
const byHost = /* @__PURE__ */ new Map();
|
|
624
|
+
const order = [];
|
|
625
|
+
for (const speech of speechItems) {
|
|
626
|
+
if (speech.time_position.mode !== "anchored") continue;
|
|
627
|
+
const host = speech.time_position.anchorPartId;
|
|
628
|
+
if (!mainPartIds.has(host)) continue;
|
|
629
|
+
let aggregation = byHost.get(host);
|
|
630
|
+
if (aggregation == null) {
|
|
631
|
+
aggregation = {
|
|
632
|
+
body_part_id: host,
|
|
633
|
+
attachments: []
|
|
634
|
+
};
|
|
635
|
+
byHost.set(host, aggregation);
|
|
636
|
+
order.push(host);
|
|
637
|
+
}
|
|
638
|
+
aggregation.attachments.push({
|
|
639
|
+
part_id: speech.part_id,
|
|
640
|
+
relative_time_position: speech.time_position.offsetMs
|
|
641
|
+
});
|
|
642
|
+
}
|
|
643
|
+
return order.map((host) => byHost.get(host));
|
|
644
|
+
}
|
|
645
|
+
/**
|
|
646
|
+
* Lane-stacking rank for the single `tracks` list (reference/17 §4): caption
|
|
647
|
+
* (above) sits before the video_clip main track, which sits before speech / bgm
|
|
648
|
+
* (below). The `tracks` array is kept in this top-to-bottom order so a freshly
|
|
649
|
+
* minted track lands in the right place and the projection's three-pane rebuild
|
|
650
|
+
* stays deterministic.
|
|
651
|
+
*/
|
|
652
|
+
function laneRank(kind) {
|
|
653
|
+
switch (kind) {
|
|
654
|
+
case "caption": return 0;
|
|
655
|
+
case "video_clip": return 1;
|
|
656
|
+
case "speech":
|
|
657
|
+
case "bgm": return 2;
|
|
658
|
+
default: return 3;
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
/**
|
|
662
|
+
* Insert a freshly-minted track into `tracks` at the position that keeps the
|
|
663
|
+
* lane-stacking order (caption → main → speech/bgm). Inserts before the first
|
|
664
|
+
* track whose rank is strictly greater, so same-rank tracks keep insertion order.
|
|
665
|
+
*/
|
|
666
|
+
function insertTrackByLaneOrder(tracks, track) {
|
|
667
|
+
const rank = laneRank(track.parts_kind);
|
|
668
|
+
const at = tracks.findIndex((t) => laneRank(t?.parts_kind) > rank);
|
|
669
|
+
if (at < 0) tracks.push(track);
|
|
670
|
+
else tracks.splice(at, 0, track);
|
|
671
|
+
}
|
|
672
|
+
/**
|
|
673
|
+
* Locate a lane's track row in the single `tracks` list by kind, minting an empty
|
|
674
|
+
* row in lane-stacking order if absent (reference/17 §4: lane = `parts_kind`).
|
|
675
|
+
* Ops use this to write authoritative items onto the right lane. The track id
|
|
676
|
+
* mirrors the seed convention (`<kind>_track`).
|
|
677
|
+
*/
|
|
678
|
+
function ensureLaneTrack(draft, kind) {
|
|
679
|
+
draft.tracks ??= [];
|
|
680
|
+
let track = draft.tracks.find((t) => t?.parts_kind === kind);
|
|
681
|
+
if (track == null) {
|
|
682
|
+
track = {
|
|
683
|
+
id: kind === "video_clip" ? "main_track" : `${kind}_track`,
|
|
684
|
+
parts_kind: kind,
|
|
685
|
+
is_hidden: void 0,
|
|
686
|
+
items: []
|
|
687
|
+
};
|
|
688
|
+
insertTrackByLaneOrder(draft.tracks, track);
|
|
689
|
+
}
|
|
690
|
+
track.items ??= [];
|
|
691
|
+
return track;
|
|
692
|
+
}
|
|
693
|
+
/** Find a secondary lane's track row without minting it. */
|
|
694
|
+
function findLaneTrack(draft, kind) {
|
|
695
|
+
return (draft.tracks ?? []).find((t) => t?.parts_kind === kind);
|
|
696
|
+
}
|
|
697
|
+
//#endregion
|
|
698
|
+
//#region src/document/zod-schema.ts
|
|
699
|
+
const partKindSchema = z.enum([
|
|
700
|
+
"video_clip",
|
|
701
|
+
"speech",
|
|
702
|
+
"caption",
|
|
703
|
+
"bgm"
|
|
704
|
+
]);
|
|
705
|
+
const finiteNumber = z.number().finite();
|
|
706
|
+
const trackItemTimePositionSchema = z.discriminatedUnion("mode", [
|
|
707
|
+
z.object({ mode: z.literal("sequential") }).passthrough(),
|
|
708
|
+
z.object({
|
|
709
|
+
mode: z.literal("anchored"),
|
|
710
|
+
anchorPartId: z.string(),
|
|
711
|
+
offsetMs: finiteNumber
|
|
712
|
+
}).passthrough(),
|
|
713
|
+
z.object({
|
|
714
|
+
mode: z.literal("absolute"),
|
|
715
|
+
offsetMs: finiteNumber
|
|
716
|
+
}).passthrough()
|
|
717
|
+
]);
|
|
718
|
+
const trackItemSchema = z.object({
|
|
719
|
+
part_id: z.string(),
|
|
720
|
+
time_position: trackItemTimePositionSchema,
|
|
721
|
+
fallback_abs_ms: finiteNumber.optional()
|
|
722
|
+
}).passthrough();
|
|
723
|
+
const trackSchema = z.object({
|
|
724
|
+
id: z.string().optional(),
|
|
725
|
+
parts_kind: partKindSchema.optional(),
|
|
726
|
+
is_hidden: z.boolean().optional(),
|
|
727
|
+
items: z.array(trackItemSchema).optional()
|
|
728
|
+
}).passthrough();
|
|
729
|
+
const speedShiftSchema = z.object({
|
|
730
|
+
category: z.string().optional(),
|
|
731
|
+
mode: z.string().optional(),
|
|
732
|
+
config: z.object({ linear: z.object({ speed: finiteNumber.optional() }).passthrough().optional() }).passthrough().optional()
|
|
733
|
+
}).passthrough();
|
|
734
|
+
const videoClipPartSchema = z.object({
|
|
735
|
+
id: z.string().optional(),
|
|
736
|
+
kind: z.literal("video_clip"),
|
|
737
|
+
duration_ms: finiteNumber.optional(),
|
|
738
|
+
play_in: finiteNumber,
|
|
739
|
+
play_out: finiteNumber,
|
|
740
|
+
volume: finiteNumber,
|
|
741
|
+
origin_media_id: z.string(),
|
|
742
|
+
speed_shift: speedShiftSchema.optional()
|
|
743
|
+
}).passthrough();
|
|
744
|
+
const speechPartSchema = z.object({
|
|
745
|
+
id: z.string().optional(),
|
|
746
|
+
kind: z.literal("speech"),
|
|
747
|
+
media_duration_ms: finiteNumber,
|
|
748
|
+
duration_ms: finiteNumber.optional(),
|
|
749
|
+
audio_script: z.string(),
|
|
750
|
+
volume: finiteNumber,
|
|
751
|
+
audio_storage_key: z.string(),
|
|
752
|
+
origin_speech_id: z.string(),
|
|
753
|
+
voice: z.unknown(),
|
|
754
|
+
caption_ids: z.array(z.string())
|
|
755
|
+
}).passthrough();
|
|
756
|
+
const captionPartSchema = z.object({
|
|
757
|
+
id: z.string().optional(),
|
|
758
|
+
kind: z.literal("caption"),
|
|
759
|
+
initial_duration_ms: finiteNumber,
|
|
760
|
+
speech_part_id: z.string(),
|
|
761
|
+
text: z.string(),
|
|
762
|
+
start_ms: finiteNumber,
|
|
763
|
+
style: z.object({
|
|
764
|
+
font_id: z.string().optional(),
|
|
765
|
+
font_size: finiteNumber.optional(),
|
|
766
|
+
font_color: z.string().optional(),
|
|
767
|
+
font_weight: finiteNumber.optional(),
|
|
768
|
+
entrance_animation: z.string().optional(),
|
|
769
|
+
entrance_animation_duration_ms: finiteNumber.optional(),
|
|
770
|
+
stroke_color: z.string().optional(),
|
|
771
|
+
stroke_width: finiteNumber.optional(),
|
|
772
|
+
position_x: finiteNumber.optional(),
|
|
773
|
+
position_y: finiteNumber.optional()
|
|
774
|
+
}).passthrough().optional()
|
|
775
|
+
}).passthrough();
|
|
776
|
+
const bgmPartSchema = z.object({
|
|
777
|
+
id: z.string().optional(),
|
|
778
|
+
kind: z.literal("bgm"),
|
|
779
|
+
audio_storage_key: z.string(),
|
|
780
|
+
volume: finiteNumber,
|
|
781
|
+
origin_media_id: z.string()
|
|
782
|
+
}).passthrough();
|
|
783
|
+
const partUnionSchema = z.union([
|
|
784
|
+
z.object({ video_clip: videoClipPartSchema }).passthrough(),
|
|
785
|
+
z.object({ speech: speechPartSchema }).passthrough(),
|
|
786
|
+
z.object({ caption: captionPartSchema }).passthrough(),
|
|
787
|
+
z.object({ bgm: bgmPartSchema }).passthrough()
|
|
788
|
+
]).refine((part) => {
|
|
789
|
+
const p = part;
|
|
790
|
+
return [
|
|
791
|
+
"video_clip",
|
|
792
|
+
"speech",
|
|
793
|
+
"caption",
|
|
794
|
+
"bgm"
|
|
795
|
+
].filter((k) => p[k] != null).length === 1;
|
|
796
|
+
}, { message: "A part_library value must have exactly one of video_clip / speech / caption / bgm" });
|
|
797
|
+
const videoDocumentMetaSchema = z.object({
|
|
798
|
+
schema_version: z.literal(VIDEO_DOCUMENT_SCHEMA_VERSION),
|
|
799
|
+
draft_id: z.string().optional(),
|
|
800
|
+
project_id: z.string().optional(),
|
|
801
|
+
owner_id: z.string().optional(),
|
|
802
|
+
thumbnail_storage_key: z.string().optional(),
|
|
803
|
+
chat_session_id: z.string().optional(),
|
|
804
|
+
video_creation_settings: z.unknown().optional(),
|
|
805
|
+
version: finiteNumber.optional()
|
|
806
|
+
}).passthrough();
|
|
807
|
+
const videoDocumentSchema = z.object({
|
|
808
|
+
meta: videoDocumentMetaSchema,
|
|
809
|
+
timeline: z.object({ unit_time_ms: finiteNumber.optional() }).passthrough().optional(),
|
|
810
|
+
tracks: z.array(trackSchema).optional(),
|
|
811
|
+
part_library: z.record(z.string(), partUnionSchema).optional()
|
|
812
|
+
}).passthrough().refine((doc) => (doc.tracks ?? []).filter((t) => t.parts_kind === "video_clip").length <= 1, {
|
|
813
|
+
message: "A VideoDocument may have at most one video_clip (main) track",
|
|
814
|
+
path: ["tracks"]
|
|
815
|
+
});
|
|
816
|
+
//#endregion
|
|
817
|
+
//#region src/document/validation.ts
|
|
818
|
+
/**
|
|
819
|
+
* Business-level schema guard for `VideoDocument` (RFC 03 §9). It is the gate
|
|
820
|
+
* that decides whether an arbitrary value is a *legal* `VideoDocument` before it
|
|
821
|
+
* is written into Loro — distinct from two neighbours:
|
|
822
|
+
*
|
|
823
|
+
* - `zod-schema.ts` (`videoDocumentSchema`) checks structure/shape only; this
|
|
824
|
+
* file layers the business rules on top (part-kind match, reference integrity,
|
|
825
|
+
* `position.anchorPartId` targets, value ranges, identity uniqueness).
|
|
826
|
+
* - loro-mirror's own `validateSchema` (run on every `setState`) only checks the
|
|
827
|
+
* storage structure, never these business invariants.
|
|
828
|
+
*
|
|
829
|
+
* Projection (`projection.ts`) calls `assertValidVideoDocument` before solving a
|
|
830
|
+
* document into the legacy `VideoDraft`.
|
|
831
|
+
*/
|
|
832
|
+
var VideoDocumentValidationError = class extends Error {
|
|
833
|
+
issues;
|
|
834
|
+
constructor(issues) {
|
|
835
|
+
super(`Invalid VideoDocument: ${issues.map((issue) => issue.message).join("; ")}`);
|
|
836
|
+
this.issues = issues;
|
|
837
|
+
this.name = "VideoDocumentValidationError";
|
|
838
|
+
}
|
|
839
|
+
};
|
|
840
|
+
/**
|
|
841
|
+
* Assert the document is legal enough to project. Only `error`-severity issues
|
|
842
|
+
* hard-reject; `recoverable` ones (dangling anchor / orphan, RFC 02 §11.1) are
|
|
843
|
+
* left for the projection to heal on read and do NOT throw. Use
|
|
844
|
+
* `validateVideoDocument` directly to inspect recoverable issues too.
|
|
845
|
+
*/
|
|
846
|
+
function assertValidVideoDocument(document) {
|
|
847
|
+
const blocking = validateVideoDocument(document).filter((issue) => (issue.severity ?? "error") === "error");
|
|
848
|
+
if (blocking.length > 0) throw new VideoDocumentValidationError(blocking);
|
|
849
|
+
}
|
|
850
|
+
function validateVideoDocument(document) {
|
|
851
|
+
const parsed = videoDocumentSchema.safeParse(document);
|
|
852
|
+
if (!parsed.success) return parsed.error.issues.map((issue) => ({
|
|
853
|
+
code: "invalid_schema",
|
|
854
|
+
path: zodPath(issue.path),
|
|
855
|
+
message: issue.message
|
|
856
|
+
}));
|
|
857
|
+
const doc = parsed.data;
|
|
858
|
+
const issues = [];
|
|
859
|
+
const partLibrary = doc.part_library ?? {};
|
|
860
|
+
for (const [partId, part] of Object.entries(partLibrary)) {
|
|
861
|
+
if (!partUnionSchema.safeParse(part).success) {
|
|
862
|
+
issues.push({
|
|
863
|
+
code: "unknown_part_kind",
|
|
864
|
+
path: `/part_library/${partId}`,
|
|
865
|
+
message: `Part "${partId}" is not a supported part union`
|
|
866
|
+
});
|
|
867
|
+
continue;
|
|
868
|
+
}
|
|
869
|
+
const wrapperKind = getPartUnionKind(part);
|
|
870
|
+
const innerKind = getPartKind(part);
|
|
871
|
+
if (wrapperKind != null && innerKind != null && wrapperKind !== innerKind) issues.push({
|
|
872
|
+
code: "part_kind_mismatch",
|
|
873
|
+
path: `/part_library/${partId}`,
|
|
874
|
+
message: `Part "${partId}" wrapper kind "${wrapperKind}" does not match inner kind "${innerKind}"`
|
|
875
|
+
});
|
|
876
|
+
validatePartValues(partId, part, issues);
|
|
877
|
+
}
|
|
878
|
+
for (const [idx, track] of (doc.tracks ?? []).entries()) validateTrack(track, `tracks/${idx}`, partLibrary, issues, track.parts_kind === "video_clip");
|
|
879
|
+
validateSpeechCaptionReferences(partLibrary, issues);
|
|
880
|
+
validatePositionReferences(doc, partLibrary, issues);
|
|
881
|
+
return issues;
|
|
882
|
+
}
|
|
883
|
+
/**
|
|
884
|
+
* An `anchored` item whose `anchorPartId` no longer exists in the library is the
|
|
885
|
+
* orphan condition (RFC 02 §4/§11.1) — e.g. a speech whose host video, or a
|
|
886
|
+
* caption whose host speech, was concurrently deleted while this item was being
|
|
887
|
+
* reparented in. This is flagged as a **recoverable** issue, NOT a hard error:
|
|
888
|
+
* the projection heals it on read (the item's `fallback_abs_ms` snapshot seeds
|
|
889
|
+
* its absolute position, then the cascade reassigns it to the nearest available
|
|
890
|
+
* host, or it stays put as an absolute item). Reporting it here keeps the orphan
|
|
891
|
+
* observable without blocking projection — the opposite of a hard reject, which
|
|
892
|
+
* would make an inevitable concurrent-delete outcome un-projectable (§11.1).
|
|
893
|
+
*/
|
|
894
|
+
function validatePositionReferences(doc, partLibrary, issues) {
|
|
895
|
+
const tracks = (doc.tracks ?? []).map((track, idx) => ({
|
|
896
|
+
track,
|
|
897
|
+
path: `tracks/${idx}`
|
|
898
|
+
}));
|
|
899
|
+
for (const { track, path } of tracks) for (const [idx, item] of (track?.items ?? []).entries()) {
|
|
900
|
+
if (item.time_position.mode !== "anchored") continue;
|
|
901
|
+
if (partLibrary[item.time_position.anchorPartId] == null) issues.push({
|
|
902
|
+
code: "invalid_position_anchor",
|
|
903
|
+
path: `/${path}/items/${idx}/time_position/anchorPartId`,
|
|
904
|
+
message: `Track item "${path}/${idx}" anchors to missing part "${item.time_position.anchorPartId}"`,
|
|
905
|
+
severity: "recoverable"
|
|
906
|
+
});
|
|
907
|
+
}
|
|
908
|
+
}
|
|
909
|
+
function validatePartValues(partId, part, issues) {
|
|
910
|
+
const payload = part.video_clip ?? part.speech ?? part.caption ?? part.bgm ?? void 0;
|
|
911
|
+
if (payload == null) return;
|
|
912
|
+
if ("duration_ms" in payload && payload.duration_ms != null && payload.duration_ms < 0) issues.push({
|
|
913
|
+
code: "invalid_part_value",
|
|
914
|
+
path: `/part_library/${partId}/duration_ms`,
|
|
915
|
+
message: `Part "${partId}" has negative duration_ms`
|
|
916
|
+
});
|
|
917
|
+
if ("volume" in payload && payload.volume != null && !Number.isFinite(payload.volume)) issues.push({
|
|
918
|
+
code: "invalid_part_value",
|
|
919
|
+
path: `/part_library/${partId}/volume`,
|
|
920
|
+
message: `Part "${partId}" has non-finite volume`
|
|
921
|
+
});
|
|
922
|
+
if (part.video_clip != null) {
|
|
923
|
+
const { play_in, play_out } = part.video_clip;
|
|
924
|
+
if (play_in != null && play_in < 0) issues.push({
|
|
925
|
+
code: "invalid_part_value",
|
|
926
|
+
path: `/part_library/${partId}/play_in`,
|
|
927
|
+
message: `Video clip "${partId}" has negative play_in`
|
|
928
|
+
});
|
|
929
|
+
if (play_out != null && play_in != null && play_out < play_in) issues.push({
|
|
930
|
+
code: "invalid_part_value",
|
|
931
|
+
path: `/part_library/${partId}/play_out`,
|
|
932
|
+
message: `Video clip "${partId}" has play_out before play_in`
|
|
933
|
+
});
|
|
934
|
+
}
|
|
935
|
+
}
|
|
936
|
+
function validateTrack(track, path, partLibrary, issues, isMainTrack) {
|
|
937
|
+
if (track == null) return;
|
|
938
|
+
const seenPartIds = /* @__PURE__ */ new Set();
|
|
939
|
+
for (const [idx, item] of (track.items ?? []).entries()) {
|
|
940
|
+
const partId = item.part_id;
|
|
941
|
+
if (partId != null && partId !== "") if (seenPartIds.has(partId)) issues.push({
|
|
942
|
+
code: "duplicate_track_item_identity",
|
|
943
|
+
path: `/${path}/items/${idx}/part_id`,
|
|
944
|
+
message: `Track item "${path}/${idx}" reuses part_id "${partId}"`
|
|
945
|
+
});
|
|
946
|
+
else seenPartIds.add(partId);
|
|
947
|
+
if (partId == null || partId === "") {
|
|
948
|
+
issues.push({
|
|
949
|
+
code: "missing_part_reference",
|
|
950
|
+
path: `/${path}/items/${idx}/part_id`,
|
|
951
|
+
message: `Track item "${path}/${idx}" has no part_id`
|
|
952
|
+
});
|
|
953
|
+
continue;
|
|
954
|
+
}
|
|
955
|
+
const part = partLibrary[partId];
|
|
956
|
+
if (part == null) {
|
|
957
|
+
issues.push({
|
|
958
|
+
code: "missing_part_reference",
|
|
959
|
+
path: `/${path}/items/${idx}/part_id`,
|
|
960
|
+
message: `Track item "${path}/${idx}" references missing part "${partId}"`
|
|
961
|
+
});
|
|
962
|
+
continue;
|
|
963
|
+
}
|
|
964
|
+
const partKind = getPartKind(part);
|
|
965
|
+
if (isMainTrack && partKind !== "video_clip") issues.push({
|
|
966
|
+
code: "main_track_non_video_clip",
|
|
967
|
+
path: `/${path}/items/${idx}/part_id`,
|
|
968
|
+
message: `Main track item "${path}/${idx}" references non-video part "${partId}"`
|
|
969
|
+
});
|
|
970
|
+
if (track.parts_kind != null && partKind != null && track.parts_kind !== partKind) issues.push({
|
|
971
|
+
code: "track_kind_mismatch",
|
|
972
|
+
path: `/${path}/items/${idx}/part_id`,
|
|
973
|
+
message: `Track "${path}" expects "${track.parts_kind}" but part "${partId}" is "${partKind}"`
|
|
974
|
+
});
|
|
975
|
+
}
|
|
976
|
+
}
|
|
977
|
+
/**
|
|
978
|
+
* Check speech↔caption references. A reference to a *missing* part (speech's
|
|
979
|
+
* caption_ids → deleted caption, or caption's speech_part_id → deleted speech)
|
|
980
|
+
* is the orphan condition (RFC 02 §11.1): reported as **recoverable** so the
|
|
981
|
+
* projection can heal it on read, not block. A *back-pointer mismatch* (caption
|
|
982
|
+
* exists but does not point back) is data corruption, kept as a hard error.
|
|
983
|
+
*/
|
|
984
|
+
function validateSpeechCaptionReferences(partLibrary, issues) {
|
|
985
|
+
for (const [partId, part] of Object.entries(partLibrary)) {
|
|
986
|
+
if (part.speech != null) for (const captionId of part.speech.caption_ids ?? []) {
|
|
987
|
+
const caption = partLibrary[captionId]?.caption;
|
|
988
|
+
if (caption == null) {
|
|
989
|
+
issues.push({
|
|
990
|
+
code: "invalid_speech_caption_reference",
|
|
991
|
+
path: `/part_library/${partId}/speech/caption_ids`,
|
|
992
|
+
message: `Speech "${partId}" references missing caption "${captionId}"`,
|
|
993
|
+
severity: "recoverable"
|
|
994
|
+
});
|
|
995
|
+
continue;
|
|
996
|
+
}
|
|
997
|
+
if (caption.speech_part_id !== partId) issues.push({
|
|
998
|
+
code: "invalid_speech_caption_reference",
|
|
999
|
+
path: `/part_library/${captionId}/caption/speech_part_id`,
|
|
1000
|
+
message: `Caption "${captionId}" does not point back to speech "${partId}"`
|
|
1001
|
+
});
|
|
1002
|
+
}
|
|
1003
|
+
if (part.caption != null) {
|
|
1004
|
+
const speechId = part.caption.speech_part_id;
|
|
1005
|
+
if (speechId != null && partLibrary[speechId]?.speech == null) issues.push({
|
|
1006
|
+
code: "invalid_speech_caption_reference",
|
|
1007
|
+
path: `/part_library/${partId}/caption/speech_part_id`,
|
|
1008
|
+
message: `Caption "${partId}" references missing speech "${speechId}"`,
|
|
1009
|
+
severity: "recoverable"
|
|
1010
|
+
});
|
|
1011
|
+
}
|
|
1012
|
+
}
|
|
1013
|
+
}
|
|
1014
|
+
function getPartUnionKind(part) {
|
|
1015
|
+
if (part.video_clip != null) return "video_clip";
|
|
1016
|
+
if (part.speech != null) return "speech";
|
|
1017
|
+
if (part.caption != null) return "caption";
|
|
1018
|
+
if (part.bgm != null) return "bgm";
|
|
1019
|
+
}
|
|
1020
|
+
function getPartKind(part) {
|
|
1021
|
+
return part.video_clip?.kind ?? part.speech?.kind ?? part.caption?.kind ?? part.bgm?.kind;
|
|
1022
|
+
}
|
|
1023
|
+
function zodPath(path) {
|
|
1024
|
+
if (path.length === 0) return "/";
|
|
1025
|
+
return `/${path.map(String).join("/")}`;
|
|
1026
|
+
}
|
|
1027
|
+
//#endregion
|
|
1028
|
+
//#region src/document/projection.ts
|
|
1029
|
+
/**
|
|
1030
|
+
* Projection between the authoritative `VideoDocument` and the legacy
|
|
1031
|
+
* `VideoDraft` read-view (RFC 02 §5/§7). Both directions live here:
|
|
1032
|
+
*
|
|
1033
|
+
* - `toVideoDocument` ingests a `VideoDraft`, deriving each item's `position`
|
|
1034
|
+
* from the legacy absolute layout + aggregations; derived values (abs time,
|
|
1035
|
+
* `part_aggregations`, total duration) are dropped.
|
|
1036
|
+
* - `fromVideoDocument` solves a `VideoDocument` back into a `VideoDraft` via the
|
|
1037
|
+
* timeline-core cascade, re-deriving exactly those values.
|
|
1038
|
+
*
|
|
1039
|
+
* Business validation lives in `validation.ts`; `fromVideoDocument` asserts a
|
|
1040
|
+
* valid document before solving.
|
|
1041
|
+
*/
|
|
1042
|
+
/**
|
|
1043
|
+
* Ingest the legacy `VideoDraft` into the authoritative `VideoDocument`,
|
|
1044
|
+
* deriving each item's `time_position` from the legacy absolute layout +
|
|
1045
|
+
* aggregations (RFC 02 §4/§5). Absolute time, `part_aggregations`, and total
|
|
1046
|
+
* duration are dropped — they are re-derived by the projection.
|
|
1047
|
+
*/
|
|
1048
|
+
function toVideoDocument(draft) {
|
|
1049
|
+
const speechHost = buildSpeechHostMap(draft.part_aggregations);
|
|
1050
|
+
const partLibrary = draft.part_library ?? {};
|
|
1051
|
+
const toTrack = (track, isMain) => {
|
|
1052
|
+
if (track == null) return void 0;
|
|
1053
|
+
return {
|
|
1054
|
+
id: track.id,
|
|
1055
|
+
parts_kind: track.parts_kind,
|
|
1056
|
+
is_hidden: track.is_hidden,
|
|
1057
|
+
items: (track.items ?? []).map((item) => deriveItem(item, isMain, speechHost, partLibrary))
|
|
1058
|
+
};
|
|
1059
|
+
};
|
|
1060
|
+
const mainTrack = toTrack(draft.main_track, true);
|
|
1061
|
+
const tracks = [
|
|
1062
|
+
...(draft.above_main_tracks ?? []).map((t) => toTrack(t, false)),
|
|
1063
|
+
...mainTrack == null ? [] : [mainTrack],
|
|
1064
|
+
...(draft.below_main_tracks ?? []).map((t) => toTrack(t, false))
|
|
1065
|
+
];
|
|
1066
|
+
return {
|
|
1067
|
+
meta: {
|
|
1068
|
+
schema_version: VIDEO_DOCUMENT_SCHEMA_VERSION,
|
|
1069
|
+
draft_id: draft.id,
|
|
1070
|
+
project_id: draft.project_id,
|
|
1071
|
+
owner_id: draft.owner_id,
|
|
1072
|
+
thumbnail_storage_key: draft.thumbnail_storage_key,
|
|
1073
|
+
chat_session_id: draft.chat_session_id,
|
|
1074
|
+
video_creation_settings: clone(draft.video_creation_settings),
|
|
1075
|
+
version: draft.version
|
|
1076
|
+
},
|
|
1077
|
+
timeline: draft.timeline == null ? void 0 : { unit_time_ms: draft.timeline.unit_time_ms },
|
|
1078
|
+
tracks,
|
|
1079
|
+
part_library: toAuthoritativePartLibrary(draft.part_library)
|
|
1080
|
+
};
|
|
1081
|
+
}
|
|
1082
|
+
/**
|
|
1083
|
+
* Map the legacy `VideoDraft` part library into the authoritative shape
|
|
1084
|
+
* (reference/17 §5): the authoritative parts store no derived part-level
|
|
1085
|
+
* duration, so the read-view `duration_ms` is dropped from video / speech / bgm.
|
|
1086
|
+
* For a caption the legacy `duration_ms` is the generation-time length, stored
|
|
1087
|
+
* authoritatively as `initial_duration_ms`.
|
|
1088
|
+
*/
|
|
1089
|
+
function toAuthoritativePartLibrary(partLibrary) {
|
|
1090
|
+
if (partLibrary == null) return void 0;
|
|
1091
|
+
const out = {};
|
|
1092
|
+
for (const [partId, part] of Object.entries(partLibrary)) {
|
|
1093
|
+
if (typeof part !== "object" || part == null) continue;
|
|
1094
|
+
if (part.video_clip != null) out[partId] = { video_clip: withTrimWindowFromDuration(part.video_clip) };
|
|
1095
|
+
else if (part.speech != null) {
|
|
1096
|
+
const { duration_ms, rest } = splitDurationMs(part.speech);
|
|
1097
|
+
out[partId] = { speech: {
|
|
1098
|
+
...rest,
|
|
1099
|
+
media_duration_ms: rest.media_duration_ms ?? duration_ms
|
|
1100
|
+
} };
|
|
1101
|
+
} else if (part.caption != null) {
|
|
1102
|
+
const { duration_ms, rest } = splitDurationMs(part.caption);
|
|
1103
|
+
out[partId] = { caption: {
|
|
1104
|
+
...rest,
|
|
1105
|
+
initial_duration_ms: duration_ms
|
|
1106
|
+
} };
|
|
1107
|
+
} else if (part.bgm != null) out[partId] = { bgm: omitDurationMs(part.bgm) };
|
|
1108
|
+
}
|
|
1109
|
+
return out;
|
|
1110
|
+
}
|
|
1111
|
+
/**
|
|
1112
|
+
* Build a speech-host map from a part_aggregations list. Used by
|
|
1113
|
+
* `toVideoDocument` (legacy VideoDraft → VideoDocument) to recover each speech's
|
|
1114
|
+
* host video clip and relative offset. Aggregation items with null ids are
|
|
1115
|
+
* skipped (malformed input tolerance).
|
|
1116
|
+
*/
|
|
1117
|
+
function buildSpeechHostMap(aggregations) {
|
|
1118
|
+
const map = /* @__PURE__ */ new Map();
|
|
1119
|
+
for (const aggregation of aggregations ?? []) {
|
|
1120
|
+
const host = aggregation.body_part_id;
|
|
1121
|
+
if (host == null) continue;
|
|
1122
|
+
for (const attachment of aggregation.attachments ?? []) {
|
|
1123
|
+
if (attachment.part_id == null) continue;
|
|
1124
|
+
map.set(attachment.part_id, {
|
|
1125
|
+
hostPartId: host,
|
|
1126
|
+
offsetMs: Math.round(attachment.relative_time_position ?? 0)
|
|
1127
|
+
});
|
|
1128
|
+
}
|
|
1129
|
+
}
|
|
1130
|
+
return map;
|
|
1131
|
+
}
|
|
1132
|
+
/**
|
|
1133
|
+
* Derive `time_position` (and `fallbackAbsMs` for anchored items) from a legacy
|
|
1134
|
+
* absolute time + pre-built speech-host map + part library. The three-branch
|
|
1135
|
+
* rule (RFC 02 §4/§5, reference/17 §3):
|
|
1136
|
+
*
|
|
1137
|
+
* 1. main-track → `sequential`
|
|
1138
|
+
* 2. speech/attachment (part_id in speechHost) → `anchored(host, offsetMs)`
|
|
1139
|
+
* 3. caption (part has `speech_part_id`) → `anchored(speech, start_ms)`
|
|
1140
|
+
* 4. everything else → `absolute(abs)`
|
|
1141
|
+
*
|
|
1142
|
+
* `partLibrary` values may be `PartUnion | string | undefined` (draft raw
|
|
1143
|
+
* form); only object-typed entries are inspected for `caption`.
|
|
1144
|
+
*/
|
|
1145
|
+
function derivePositionFromAbs(partId, abs, isMain, speechHost, partLibrary) {
|
|
1146
|
+
if (isMain) return { timePosition: { mode: "sequential" } };
|
|
1147
|
+
const host = speechHost.get(partId);
|
|
1148
|
+
if (host != null) return {
|
|
1149
|
+
timePosition: {
|
|
1150
|
+
mode: "anchored",
|
|
1151
|
+
anchorPartId: host.hostPartId,
|
|
1152
|
+
offsetMs: host.offsetMs
|
|
1153
|
+
},
|
|
1154
|
+
fallbackAbsMs: abs
|
|
1155
|
+
};
|
|
1156
|
+
const part = partLibrary[partId];
|
|
1157
|
+
const captionPart = typeof part === "object" && part != null ? part.caption : void 0;
|
|
1158
|
+
const speechId = captionPart?.speech_part_id ?? void 0;
|
|
1159
|
+
if (speechId != null) return {
|
|
1160
|
+
timePosition: {
|
|
1161
|
+
mode: "anchored",
|
|
1162
|
+
anchorPartId: speechId,
|
|
1163
|
+
offsetMs: Math.round(captionPart?.start_ms ?? 0)
|
|
1164
|
+
},
|
|
1165
|
+
fallbackAbsMs: abs
|
|
1166
|
+
};
|
|
1167
|
+
return { timePosition: {
|
|
1168
|
+
mode: "absolute",
|
|
1169
|
+
offsetMs: abs
|
|
1170
|
+
} };
|
|
1171
|
+
}
|
|
1172
|
+
/** Derive one item's authoritative `time_position` from its legacy abs + aggregation. */
|
|
1173
|
+
function deriveItem(item, isMain, speechHost, partLibrary) {
|
|
1174
|
+
const partId = item.part_id ?? "";
|
|
1175
|
+
const { timePosition, fallbackAbsMs } = derivePositionFromAbs(partId, Math.round(item.abs_time_position ?? 0), isMain, speechHost, partLibrary);
|
|
1176
|
+
return fallbackAbsMs == null ? {
|
|
1177
|
+
part_id: partId,
|
|
1178
|
+
time_position: timePosition
|
|
1179
|
+
} : {
|
|
1180
|
+
part_id: partId,
|
|
1181
|
+
time_position: timePosition,
|
|
1182
|
+
fallback_abs_ms: fallbackAbsMs
|
|
1183
|
+
};
|
|
1184
|
+
}
|
|
1185
|
+
/**
|
|
1186
|
+
* Project the authoritative `VideoDocument` back into the legacy `VideoDraft`
|
|
1187
|
+
* read-view, solving each item's absolute position, the `part_aggregations`, and
|
|
1188
|
+
* the total duration via the timeline-core cascade.
|
|
1189
|
+
*/
|
|
1190
|
+
function fromVideoDocument(document) {
|
|
1191
|
+
assertValidVideoDocument(document);
|
|
1192
|
+
const view = solveVideoDocument(document);
|
|
1193
|
+
const tracks = document.tracks ?? [];
|
|
1194
|
+
const mainTrack = tracks.find((t) => t.parts_kind === "video_clip");
|
|
1195
|
+
const aboveTracks = tracks.filter((t) => t.parts_kind === "caption");
|
|
1196
|
+
const belowTracks = tracks.filter((t) => t.parts_kind === "speech" || t.parts_kind === "bgm");
|
|
1197
|
+
return {
|
|
1198
|
+
id: document.meta.draft_id,
|
|
1199
|
+
project_id: document.meta.project_id,
|
|
1200
|
+
owner_id: document.meta.owner_id,
|
|
1201
|
+
thumbnail_storage_key: document.meta.thumbnail_storage_key,
|
|
1202
|
+
timeline: {
|
|
1203
|
+
duration_ms: view.durationMs,
|
|
1204
|
+
unit_time_ms: document.timeline?.unit_time_ms
|
|
1205
|
+
},
|
|
1206
|
+
video_creation_settings: clone(document.meta.video_creation_settings),
|
|
1207
|
+
chat_session_id: document.meta.chat_session_id,
|
|
1208
|
+
main_track: draftTrack(mainTrack, view.absByPartId),
|
|
1209
|
+
above_main_tracks: aboveTracks.map((t) => draftTrack(t, view.absByPartId)),
|
|
1210
|
+
below_main_tracks: belowTracks.map((t) => draftTrack(t, view.absByPartId)),
|
|
1211
|
+
part_aggregations: view.aggregations,
|
|
1212
|
+
part_library: toReadViewPartLibrary(view.partLibrary, view.durationMs),
|
|
1213
|
+
version: document.meta.version
|
|
1214
|
+
};
|
|
1215
|
+
}
|
|
1216
|
+
/**
|
|
1217
|
+
* Map the authoritative part library into the `VideoDraft` read-view shape,
|
|
1218
|
+
* re-injecting the derived effective `duration_ms` downstream expects
|
|
1219
|
+
* (reference/17 §5/§7) — the authoritative parts store no part-level duration:
|
|
1220
|
+
*
|
|
1221
|
+
* - video clip → `(play_out - play_in) / speed` (`effectiveVideoClipDurationMs`)
|
|
1222
|
+
* - speech → its intrinsic `media_duration_ms` (no trim/speed)
|
|
1223
|
+
* - caption → its generation-time `initial_duration_ms`
|
|
1224
|
+
* - bgm → the timeline total (`durationMs`)
|
|
1225
|
+
*
|
|
1226
|
+
* Parts are deep-cloned; the engine extensions (`media_duration_ms`,
|
|
1227
|
+
* `initial_duration_ms`) are kept alongside the injected `duration_ms`.
|
|
1228
|
+
*/
|
|
1229
|
+
function toReadViewPartLibrary(partLibrary, durationMs) {
|
|
1230
|
+
const out = {};
|
|
1231
|
+
for (const [partId, part] of Object.entries(partLibrary)) if (part.video_clip != null) {
|
|
1232
|
+
const clip = clone(part.video_clip);
|
|
1233
|
+
out[partId] = { video_clip: {
|
|
1234
|
+
...clip,
|
|
1235
|
+
duration_ms: effectiveVideoClipDurationMs(clip)
|
|
1236
|
+
} };
|
|
1237
|
+
} else if (part.speech != null) {
|
|
1238
|
+
const speech = clone(part.speech);
|
|
1239
|
+
out[partId] = { speech: {
|
|
1240
|
+
...speech,
|
|
1241
|
+
duration_ms: speech.media_duration_ms
|
|
1242
|
+
} };
|
|
1243
|
+
} else if (part.caption != null) {
|
|
1244
|
+
const caption = clone(part.caption);
|
|
1245
|
+
out[partId] = { caption: {
|
|
1246
|
+
...caption,
|
|
1247
|
+
duration_ms: caption.initial_duration_ms
|
|
1248
|
+
} };
|
|
1249
|
+
} else if (part.bgm != null) out[partId] = { bgm: {
|
|
1250
|
+
...clone(part.bgm),
|
|
1251
|
+
duration_ms: durationMs
|
|
1252
|
+
} };
|
|
1253
|
+
return out;
|
|
1254
|
+
}
|
|
1255
|
+
/** Deep-clone a part payload, dropping the derived read-view `duration_ms`. */
|
|
1256
|
+
function omitDurationMs(part) {
|
|
1257
|
+
const { duration_ms: _drop, ...rest } = clone(part);
|
|
1258
|
+
return rest;
|
|
1259
|
+
}
|
|
1260
|
+
/**
|
|
1261
|
+
* Migrate a legacy video clip into the authoritative trim-window-only shape: the
|
|
1262
|
+
* authoritative part stores no `duration_ms`, so it is dropped — but a legacy
|
|
1263
|
+
* clip with no explicit trim window (`play_in` / `play_out` absent) would then
|
|
1264
|
+
* compute an effective length of 0 and vanish from the layout. When that clip
|
|
1265
|
+
* carried a legacy `duration_ms`, backfill it as the trim window (`play_in` 0,
|
|
1266
|
+
* `play_out = duration_ms`, no speed) so the effective length is preserved, then
|
|
1267
|
+
* drop `duration_ms`. A clip that already has a trim window keeps it verbatim.
|
|
1268
|
+
*/
|
|
1269
|
+
function withTrimWindowFromDuration(clip) {
|
|
1270
|
+
const stripped = omitDurationMs(clip);
|
|
1271
|
+
if (clip.play_in != null || clip.play_out != null) return stripped;
|
|
1272
|
+
const legacyDuration = clip.duration_ms;
|
|
1273
|
+
if (legacyDuration == null || !Number.isFinite(legacyDuration)) return stripped;
|
|
1274
|
+
return {
|
|
1275
|
+
...stripped,
|
|
1276
|
+
play_in: 0,
|
|
1277
|
+
play_out: legacyDuration
|
|
1278
|
+
};
|
|
1279
|
+
}
|
|
1280
|
+
/** Deep-clone a part payload, returning its `duration_ms` separately from the rest. */
|
|
1281
|
+
function splitDurationMs(part) {
|
|
1282
|
+
const { duration_ms, ...rest } = clone(part);
|
|
1283
|
+
return {
|
|
1284
|
+
duration_ms,
|
|
1285
|
+
rest
|
|
1286
|
+
};
|
|
1287
|
+
}
|
|
1288
|
+
function draftTrack(track, absByPartId) {
|
|
1289
|
+
if (track == null) return void 0;
|
|
1290
|
+
return {
|
|
1291
|
+
id: track.id,
|
|
1292
|
+
parts_kind: track.parts_kind,
|
|
1293
|
+
is_hidden: track.is_hidden,
|
|
1294
|
+
items: (track.items ?? []).map((item) => ({
|
|
1295
|
+
part_id: item.part_id,
|
|
1296
|
+
abs_time_position: absByPartId.get(item.part_id) ?? 0
|
|
1297
|
+
}))
|
|
1298
|
+
};
|
|
1299
|
+
}
|
|
1300
|
+
function clone(value) {
|
|
1301
|
+
if (Array.isArray(value)) return value.map((item) => clone(item));
|
|
1302
|
+
if (value != null && typeof value === "object") {
|
|
1303
|
+
const result = {};
|
|
1304
|
+
for (const [key, child] of Object.entries(value)) result[key] = clone(child);
|
|
1305
|
+
return result;
|
|
1306
|
+
}
|
|
1307
|
+
return value;
|
|
1308
|
+
}
|
|
1309
|
+
//#endregion
|
|
1310
|
+
//#region src/document/mirror-read.ts
|
|
1311
|
+
/**
|
|
1312
|
+
* Project the mirror state (`VideoDocumentDraft`) into the authoritative
|
|
1313
|
+
* `VideoDocument`. The storage shape is isomorphic to the domain shape (RFC 03
|
|
1314
|
+
* §4, reference/17 §4: meta map + a single `tracks` list + part_library), so this
|
|
1315
|
+
* is a near-identity — it reads `time_position` / `fallback_abs_ms` JSON blobs
|
|
1316
|
+
* back into structured values and trims empty strings, nothing more.
|
|
1317
|
+
*
|
|
1318
|
+
* It maps only authoritative facts (RFC 02 §6): `part_id` + `time_position`. The
|
|
1319
|
+
* projection-derived `VideoDraft` read-view (absolute time, `part_aggregations`,
|
|
1320
|
+
* total duration) is solved separately by the cascade, not here.
|
|
1321
|
+
*
|
|
1322
|
+
* It reads in-memory mirror state (O(n) over the document), not a Loro
|
|
1323
|
+
* `toJSON()` FFI rebuild — the cost the prior schema adapter paid on every
|
|
1324
|
+
* `snapshot()`.
|
|
1325
|
+
*/
|
|
1326
|
+
function readVideoDocumentFromDraft(draft) {
|
|
1327
|
+
const partLibrary = {};
|
|
1328
|
+
for (const [partId, payload] of recordEntries(draft.part_library)) {
|
|
1329
|
+
const part = draftToPartUnion(payload);
|
|
1330
|
+
if (part != null) partLibrary[partId] = part;
|
|
1331
|
+
}
|
|
1332
|
+
const timeline = draft.timeline;
|
|
1333
|
+
const hasTimeline = timeline?.unit_time_ms != null;
|
|
1334
|
+
const meta = draft.meta;
|
|
1335
|
+
return {
|
|
1336
|
+
meta: {
|
|
1337
|
+
schema_version: VIDEO_DOCUMENT_SCHEMA_VERSION,
|
|
1338
|
+
draft_id: emptyToUndefined(meta?.draft_id),
|
|
1339
|
+
project_id: emptyToUndefined(meta?.project_id),
|
|
1340
|
+
owner_id: emptyToUndefined(meta?.owner_id),
|
|
1341
|
+
thumbnail_storage_key: emptyToUndefined(meta?.thumbnail_storage_key),
|
|
1342
|
+
chat_session_id: emptyToUndefined(meta?.chat_session_id),
|
|
1343
|
+
video_creation_settings: meta?.video_creation_settings ?? void 0,
|
|
1344
|
+
version: meta?.version ?? void 0
|
|
1345
|
+
},
|
|
1346
|
+
timeline: hasTimeline ? { unit_time_ms: timeline.unit_time_ms } : void 0,
|
|
1347
|
+
tracks: rowsToTracks(draft.tracks),
|
|
1348
|
+
part_library: partLibrary
|
|
1349
|
+
};
|
|
1350
|
+
}
|
|
1351
|
+
/** Map a movable-list of track rows (`$cid`-bearing) into domain tracks, dropping empty-id placeholders. */
|
|
1352
|
+
function rowsToTracks(rows) {
|
|
1353
|
+
return (rows ?? []).filter((row) => row.id != null && row.id !== "").map(rowToTrack);
|
|
1354
|
+
}
|
|
1355
|
+
function rowToTrack(row) {
|
|
1356
|
+
return {
|
|
1357
|
+
id: row.id,
|
|
1358
|
+
parts_kind: row.parts_kind ?? void 0,
|
|
1359
|
+
is_hidden: row.is_hidden ?? void 0,
|
|
1360
|
+
items: (row.items ?? []).map((item) => {
|
|
1361
|
+
const result = {
|
|
1362
|
+
part_id: item.part_id ?? "",
|
|
1363
|
+
time_position: item.time_position
|
|
1364
|
+
};
|
|
1365
|
+
if (item.fallback_abs_ms != null) result.fallback_abs_ms = item.fallback_abs_ms;
|
|
1366
|
+
return result;
|
|
1367
|
+
})
|
|
1368
|
+
};
|
|
1369
|
+
}
|
|
1370
|
+
function emptyToUndefined(value) {
|
|
1371
|
+
return value == null || value === "" ? void 0 : value;
|
|
1372
|
+
}
|
|
1373
|
+
//#endregion
|
|
1374
|
+
//#region src/document/mirror-adapter.ts
|
|
1375
|
+
/**
|
|
1376
|
+
* Storage-layer adapter that backs a `VideoDocument` with `loro-mirror` (ADR
|
|
1377
|
+
* 0008). The mirror holds an in-memory immutable state synced to the `LoroDoc`
|
|
1378
|
+
* by declarative diff, replacing the hand-rolled `@mengine/schema` adapter:
|
|
1379
|
+
*
|
|
1380
|
+
* - `snapshot()` projects the mirror's in-memory state to the read model — no
|
|
1381
|
+
* per-call `toJSON()` FFI rebuild.
|
|
1382
|
+
* - `transact(edit, audit)` runs the whole op in one `mirror.setState` callback:
|
|
1383
|
+
* one diff, one `doc.commit` carrying the audit message. The callback edits an
|
|
1384
|
+
* immer draft, so a throw inside it discards the draft and never touches Loro
|
|
1385
|
+
* (natural rollback) — no `guard` / `rollback` / `openTransaction` machinery.
|
|
1386
|
+
* - mirror's `idSelector` (track items keyed by `part_id`) diffs reorders to
|
|
1387
|
+
* real Loro `move` ops on every lane, so per-item CRDT identity survives on
|
|
1388
|
+
* main and secondary tracks alike.
|
|
1389
|
+
*/
|
|
1390
|
+
var MirrorVideoDocumentAdapter = class {
|
|
1391
|
+
doc;
|
|
1392
|
+
mirror;
|
|
1393
|
+
constructor(doc) {
|
|
1394
|
+
this.doc = doc;
|
|
1395
|
+
this.mirror = new Mirror({
|
|
1396
|
+
doc,
|
|
1397
|
+
schema: videoDocumentMirrorSchema
|
|
1398
|
+
});
|
|
1399
|
+
}
|
|
1400
|
+
snapshot() {
|
|
1401
|
+
return readVideoDocumentFromDraft(this.mirror.getState());
|
|
1402
|
+
}
|
|
1403
|
+
/**
|
|
1404
|
+
* True once the doc holds real document content. A fresh mirror over an empty
|
|
1405
|
+
* doc still reports defaulted root maps, so probe the stored `schema_version`
|
|
1406
|
+
* (empty until a snapshot is bootstrapped or synced in).
|
|
1407
|
+
*/
|
|
1408
|
+
hasContent() {
|
|
1409
|
+
return (this.mirror.getState().meta?.schema_version ?? "") !== "";
|
|
1410
|
+
}
|
|
1411
|
+
/**
|
|
1412
|
+
* Apply one op as a single transaction. `edit` mutates the immer draft; mirror
|
|
1413
|
+
* diffs the result and commits once with the audit `message`. A throw in `edit`
|
|
1414
|
+
* discards the draft (Loro untouched). When `edit` produces no change, mirror
|
|
1415
|
+
* skips the commit — matching the prior "empty op leaves no audit" behavior.
|
|
1416
|
+
*/
|
|
1417
|
+
transact(edit, audit) {
|
|
1418
|
+
this.mirror.setState((draft) => {
|
|
1419
|
+
edit(draft);
|
|
1420
|
+
}, {
|
|
1421
|
+
origin: "mengine.semantic_editor",
|
|
1422
|
+
message: JSON.stringify({
|
|
1423
|
+
semantic_op: audit.kind,
|
|
1424
|
+
payload: audit.payload,
|
|
1425
|
+
intent: audit.intent ?? null
|
|
1426
|
+
})
|
|
1427
|
+
});
|
|
1428
|
+
}
|
|
1429
|
+
};
|
|
1430
|
+
/** Build a fresh Loro doc seeded with `document` through the mirror. */
|
|
1431
|
+
function createMirrorVideoDocument(document, options = {}) {
|
|
1432
|
+
assertValidVideoDocument(document);
|
|
1433
|
+
const doc = new LoroDoc();
|
|
1434
|
+
if (options.peerId != null) doc.setPeerId(options.peerId);
|
|
1435
|
+
new Mirror({
|
|
1436
|
+
doc,
|
|
1437
|
+
schema: videoDocumentMirrorSchema
|
|
1438
|
+
}).setState((draft) => {
|
|
1439
|
+
writeVideoDocumentToDraft(draft, document);
|
|
1440
|
+
}, { origin: options.origin ?? "mengine.bootstrap" });
|
|
1441
|
+
return doc;
|
|
1442
|
+
}
|
|
1443
|
+
/** Build a `MirrorVideoDocumentAdapter` over a fresh doc seeded with `document`. */
|
|
1444
|
+
function createMirrorVideoDocumentAdapter(document, options) {
|
|
1445
|
+
return new MirrorVideoDocumentAdapter(createMirrorVideoDocument(document, options));
|
|
1446
|
+
}
|
|
1447
|
+
/** Write a whole `VideoDocument` into a draft (seed a fresh doc / plain-memory state). */
|
|
1448
|
+
function writeVideoDocumentToDraft(draft, document) {
|
|
1449
|
+
draft.meta = {
|
|
1450
|
+
schema_version: document.meta.schema_version,
|
|
1451
|
+
draft_id: document.meta.draft_id ?? void 0,
|
|
1452
|
+
project_id: document.meta.project_id ?? void 0,
|
|
1453
|
+
owner_id: document.meta.owner_id ?? void 0,
|
|
1454
|
+
thumbnail_storage_key: document.meta.thumbnail_storage_key ?? void 0,
|
|
1455
|
+
chat_session_id: document.meta.chat_session_id ?? void 0,
|
|
1456
|
+
video_creation_settings: document.meta.video_creation_settings ?? void 0,
|
|
1457
|
+
version: document.meta.version ?? void 0
|
|
1458
|
+
};
|
|
1459
|
+
draft.timeline = { unit_time_ms: document.timeline?.unit_time_ms ?? void 0 };
|
|
1460
|
+
draft.tracks = (document.tracks ?? []).map(toTrackRow);
|
|
1461
|
+
draft.part_library = {};
|
|
1462
|
+
for (const [partId, part] of Object.entries(document.part_library ?? {})) draft.part_library[partId] = partUnionToDraft(part);
|
|
1463
|
+
}
|
|
1464
|
+
/** Map a domain `Track` to a draft track row (no lane/lane_order — see schema). */
|
|
1465
|
+
function toTrackRow(track) {
|
|
1466
|
+
return {
|
|
1467
|
+
id: track.id ?? "",
|
|
1468
|
+
parts_kind: track.parts_kind ?? void 0,
|
|
1469
|
+
is_hidden: track.is_hidden ?? void 0,
|
|
1470
|
+
items: (track.items ?? []).map((item) => ({
|
|
1471
|
+
part_id: item.part_id,
|
|
1472
|
+
time_position: item.time_position,
|
|
1473
|
+
fallback_abs_ms: item.fallback_abs_ms
|
|
1474
|
+
}))
|
|
1475
|
+
};
|
|
1476
|
+
}
|
|
1477
|
+
//#endregion
|
|
1478
|
+
//#region src/editor/id-gen.ts
|
|
1479
|
+
/**
|
|
1480
|
+
* Part-id generation, aligned with the online ecosystem.
|
|
1481
|
+
*
|
|
1482
|
+
* The authoritative online producers — agent-harness (`@harness/shared`
|
|
1483
|
+
* `genObjId`) and director.v2 (`common/obj_id.py` `gen_obj_id`) — both mint part
|
|
1484
|
+
* ids as `` `${prefix}_${ulid()}` ``, and real captured drafts use exactly that
|
|
1485
|
+
* shape (`clip_…` / `spe_…` / `cap_…` / `bgm_…`, each a 26-char ULID). The engine
|
|
1486
|
+
* previously emitted `vc_<base36 timestamp><6 random>`, a different prefix AND a
|
|
1487
|
+
* different encoding — the sole cross-repo id divergence. This module removes it
|
|
1488
|
+
* by emitting the same `<prefix>_<ULID>` bytes.
|
|
1489
|
+
*
|
|
1490
|
+
* The ULID is generated inline (Crockford Base32, 48-bit time + 80-bit random)
|
|
1491
|
+
* rather than pulling the `ulid` npm package: the randomness class matches the
|
|
1492
|
+
* old generator (both `Math.random`-based) and it keeps `@mengine/medeo-client`
|
|
1493
|
+
* dependency-free for a purely mechanical id string. Part ids only need to be
|
|
1494
|
+
* unique and lexicographically time-sortable, which this satisfies.
|
|
1495
|
+
*/
|
|
1496
|
+
/** Crockford Base32 alphabet (no I, L, O, U), per the ULID spec. */
|
|
1497
|
+
const CROCKFORD = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
|
|
1498
|
+
const TIME_LEN = 10;
|
|
1499
|
+
const RANDOM_LEN = 16;
|
|
1500
|
+
function encodeTime(now) {
|
|
1501
|
+
let out = "";
|
|
1502
|
+
let ms = now;
|
|
1503
|
+
for (let i = TIME_LEN - 1; i >= 0; i--) {
|
|
1504
|
+
const mod = ms % 32;
|
|
1505
|
+
out = CROCKFORD[mod] + out;
|
|
1506
|
+
ms = (ms - mod) / 32;
|
|
1507
|
+
}
|
|
1508
|
+
return out;
|
|
1509
|
+
}
|
|
1510
|
+
function encodeRandom() {
|
|
1511
|
+
let out = "";
|
|
1512
|
+
for (let i = 0; i < RANDOM_LEN; i++) out += CROCKFORD[Math.floor(Math.random() * 32)];
|
|
1513
|
+
return out;
|
|
1514
|
+
}
|
|
1515
|
+
/** A 26-char Crockford Base32 ULID (10-char time + 16-char random). */
|
|
1516
|
+
function ulid() {
|
|
1517
|
+
return encodeTime(Date.now()) + encodeRandom();
|
|
1518
|
+
}
|
|
1519
|
+
function generatePartId(prefix) {
|
|
1520
|
+
return `${prefix}_${ulid()}`;
|
|
1521
|
+
}
|
|
1522
|
+
//#endregion
|
|
1523
|
+
//#region src/document/plain-memory-adapter.ts
|
|
1524
|
+
/**
|
|
1525
|
+
* Pure in-memory `SemanticDocumentAdapter` — no Loro/WASM. Holds a
|
|
1526
|
+
* `VideoDocumentDraft` object and applies each `transact` via immer `produce`,
|
|
1527
|
+
* journaling every audit that actually mutated state (plus any ids minted
|
|
1528
|
+
* during that transact).
|
|
1529
|
+
*
|
|
1530
|
+
* Known benign difference vs `MirrorVideoDocumentAdapter`: the editor's
|
|
1531
|
+
* `setPart` assigns a fresh part object on every call, so a same-value rewrite
|
|
1532
|
+
* produces a new immer state and IS journaled here, while the mirror's deep
|
|
1533
|
+
* diff emits no commit. Terminal `snapshot()` stays equal; replay is idempotent.
|
|
1534
|
+
*/
|
|
1535
|
+
var PlainMemoryAdapter = class {
|
|
1536
|
+
state;
|
|
1537
|
+
_journal = [];
|
|
1538
|
+
baseIdFactory;
|
|
1539
|
+
/** Non-null only while a `transact` edit callback is running. */
|
|
1540
|
+
pendingIds = null;
|
|
1541
|
+
/**
|
|
1542
|
+
* Recording wrapper around the underlying factory. Callers (sandbox editor)
|
|
1543
|
+
* use this so every minted id is appended to the current transact's list.
|
|
1544
|
+
*/
|
|
1545
|
+
idFactory;
|
|
1546
|
+
constructor(document, options) {
|
|
1547
|
+
assertValidVideoDocument(document);
|
|
1548
|
+
const draft = {};
|
|
1549
|
+
writeVideoDocumentToDraft(draft, document);
|
|
1550
|
+
this.state = draft;
|
|
1551
|
+
this.baseIdFactory = options?.idFactory ?? generatePartId;
|
|
1552
|
+
this.idFactory = (prefix) => {
|
|
1553
|
+
const id = this.baseIdFactory(prefix);
|
|
1554
|
+
if (this.pendingIds != null) this.pendingIds.push(id);
|
|
1555
|
+
return id;
|
|
1556
|
+
};
|
|
1557
|
+
}
|
|
1558
|
+
get journal() {
|
|
1559
|
+
return this._journal;
|
|
1560
|
+
}
|
|
1561
|
+
hasContent() {
|
|
1562
|
+
return (this.state.meta?.schema_version ?? "") !== "";
|
|
1563
|
+
}
|
|
1564
|
+
snapshot() {
|
|
1565
|
+
return readVideoDocumentFromDraft(this.state);
|
|
1566
|
+
}
|
|
1567
|
+
/**
|
|
1568
|
+
* Apply one op via immer. A throw in `edit` discards the draft (state and
|
|
1569
|
+
* journal unchanged). When `produce` returns the same reference, there was
|
|
1570
|
+
* no structural change — skip journal, matching mirror "no change, no commit".
|
|
1571
|
+
*/
|
|
1572
|
+
transact(edit, audit) {
|
|
1573
|
+
this.pendingIds = [];
|
|
1574
|
+
try {
|
|
1575
|
+
const next = produce(this.state, edit);
|
|
1576
|
+
if (next !== this.state) {
|
|
1577
|
+
this.state = next;
|
|
1578
|
+
this._journal.push({
|
|
1579
|
+
...audit,
|
|
1580
|
+
generated_ids: this.pendingIds
|
|
1581
|
+
});
|
|
1582
|
+
}
|
|
1583
|
+
} finally {
|
|
1584
|
+
this.pendingIds = null;
|
|
1585
|
+
}
|
|
1586
|
+
}
|
|
1587
|
+
};
|
|
1588
|
+
/** Build a `PlainMemoryAdapter` seeded with `document`. */
|
|
1589
|
+
function createPlainMemoryAdapter(document, options) {
|
|
1590
|
+
return new PlainMemoryAdapter(document, options);
|
|
1591
|
+
}
|
|
1592
|
+
//#endregion
|
|
1593
|
+
export { isEmptyVideoClip as A, bytesToBase64 as B, fillMainTrackTimeGaps as C, resolveSpeechOverlapByShiftingVideos as D, resolveAllSpeechOverlaps as E, speedOf as F, partUnionToDraft as I, recordEntries as L, safeDurationMs as M, VIDEO_DOCUMENT_SCHEMA_VERSION as N, syncAggregatedClipsTimePosition as O, effectiveVideoClipDurationMs as P, videoDocumentMirrorSchema as R, arrangeMainTrackSeamlessly as S, recalculateTimelineDuration as T, videoDocumentSchema as _, createMirrorVideoDocument as a, solveVideoDocument as b, readVideoDocumentFromDraft as c, fromVideoDocument as d, toVideoDocument as f, partUnionSchema as g, validateVideoDocument as h, MirrorVideoDocumentAdapter as i, partDurationMs as j, TIMELINE_SKELETON_DURATION_MS as k, buildSpeechHostMap as l, assertValidVideoDocument as m, createPlainMemoryAdapter as n, createMirrorVideoDocumentAdapter as o, VideoDocumentValidationError as p, generatePartId as r, writeVideoDocumentToDraft as s, PlainMemoryAdapter as t, derivePositionFromAbs as u, ensureLaneTrack as v, reassignSpeechesToVideoClipsByTime as w, cascadeAfterVideoClipChanges as x, findLaneTrack as y, base64ToBytes as z };
|