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