@editframe/elements 0.5.0-beta.6 → 0.5.0-beta.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/dist/elements/src/EF_FRAMEGEN.mjs +130 -0
  2. package/dist/elements/src/EF_INTERACTIVE.mjs +4 -0
  3. package/dist/elements/{elements → src/elements}/EFAudio.mjs +20 -0
  4. package/dist/elements/{elements → src/elements}/EFCaptions.mjs +3 -0
  5. package/dist/elements/{elements → src/elements}/EFImage.mjs +15 -3
  6. package/dist/elements/{elements → src/elements}/EFMedia.mjs +81 -4
  7. package/dist/elements/{elements → src/elements}/EFTemporal.mjs +29 -1
  8. package/dist/elements/{elements → src/elements}/EFTimegroup.mjs +124 -0
  9. package/dist/elements/{elements → src/elements}/EFVideo.mjs +10 -0
  10. package/dist/elements/{elements → src/elements}/EFWaveform.mjs +41 -24
  11. package/dist/elements/{elements.mjs → src/elements.mjs} +2 -1
  12. package/dist/elements/{gui → src/gui}/EFFilmstrip.mjs +3 -2
  13. package/dist/elements/{gui → src/gui}/EFWorkbench.mjs +51 -63
  14. package/dist/elements/{gui → src/gui}/TWMixin.css.mjs +1 -1
  15. package/dist/style.css +3 -0
  16. package/dist/util/awaitAnimationFrame.mjs +11 -0
  17. package/docker-compose.yaml +17 -0
  18. package/package.json +2 -2
  19. package/src/EF_FRAMEGEN.ts +208 -0
  20. package/src/EF_INTERACTIVE.ts +2 -0
  21. package/src/elements/CrossUpdateController.ts +18 -0
  22. package/src/elements/EFAudio.ts +42 -0
  23. package/src/elements/EFCaptions.ts +202 -0
  24. package/src/elements/EFImage.ts +70 -0
  25. package/src/elements/EFMedia.ts +395 -0
  26. package/src/elements/EFSourceMixin.ts +57 -0
  27. package/src/elements/EFTemporal.ts +246 -0
  28. package/src/elements/EFTimegroup.browsertest.ts +360 -0
  29. package/src/elements/EFTimegroup.ts +394 -0
  30. package/src/elements/EFTimeline.ts +13 -0
  31. package/src/elements/EFVideo.ts +114 -0
  32. package/src/elements/EFWaveform.ts +407 -0
  33. package/src/elements/FetchMixin.ts +18 -0
  34. package/src/elements/TimegroupController.ts +25 -0
  35. package/src/elements/buildLitFixture.ts +13 -0
  36. package/src/elements/durationConverter.ts +6 -0
  37. package/src/elements/parseTimeToMs.ts +10 -0
  38. package/src/elements/util.ts +24 -0
  39. package/src/gui/EFFilmstrip.ts +702 -0
  40. package/src/gui/EFWorkbench.ts +242 -0
  41. package/src/gui/TWMixin.css +3 -0
  42. package/src/gui/TWMixin.ts +27 -0
  43. package/src/util.d.ts +1 -0
  44. package/dist/elements/elements.css.mjs +0 -1
  45. /package/dist/elements/{elements → src/elements}/CrossUpdateController.mjs +0 -0
  46. /package/dist/elements/{elements → src/elements}/EFSourceMixin.mjs +0 -0
  47. /package/dist/elements/{elements → src/elements}/EFTimeline.mjs +0 -0
  48. /package/dist/elements/{elements → src/elements}/FetchMixin.mjs +0 -0
  49. /package/dist/elements/{elements → src/elements}/TimegroupController.mjs +0 -0
  50. /package/dist/elements/{elements → src/elements}/durationConverter.mjs +0 -0
  51. /package/dist/elements/{elements → src/elements}/parseTimeToMs.mjs +0 -0
  52. /package/dist/elements/{elements → src/elements}/util.mjs +0 -0
  53. /package/dist/elements/{gui → src/gui}/TWMixin.mjs +0 -0
@@ -0,0 +1,394 @@
1
+ import { LitElement, html, css, PropertyValueMap } from "lit";
2
+ import { provide } from "@lit/context";
3
+ import { customElement, property } from "lit/decorators.js";
4
+ import {
5
+ EFTemporal,
6
+ isEFTemporal,
7
+ shallowGetTemporalElements,
8
+ timegroupContext,
9
+ } from "./EFTemporal";
10
+ import { TimegroupController } from "./TimegroupController";
11
+ import { EF_INTERACTIVE } from "../EF_INTERACTIVE";
12
+ import { deepGetMediaElements } from "./EFMedia";
13
+ import { Task } from "@lit/task";
14
+
15
+ function audioBufferToFloat32(buffer: AudioBuffer) {
16
+ const numOfChan = buffer.numberOfChannels;
17
+ const length = buffer.length * numOfChan * 4; // 4 bytes per sample for 32-bit float
18
+ const resultBuffer = new ArrayBuffer(length);
19
+ const view = new DataView(resultBuffer);
20
+ const channels = [];
21
+
22
+ for (let i = 0; i < numOfChan; i++) {
23
+ channels.push(buffer.getChannelData(i));
24
+ }
25
+
26
+ let offset = 0;
27
+ for (let i = 0; i < buffer.length; i++) {
28
+ for (let channel = 0; channel < numOfChan; channel++) {
29
+ view.setFloat32(offset, channels[channel][i], true); // true for little-endian
30
+ offset += 4;
31
+ }
32
+ }
33
+
34
+ return new Blob([resultBuffer], { type: "application/octet-stream" });
35
+ }
36
+
37
+ @customElement("ef-timegroup")
38
+ export class EFTimegroup extends EFTemporal(LitElement) {
39
+ static styles = css`
40
+ :host {
41
+ display: block;
42
+ width: 100%;
43
+ height: 100%;
44
+ position: relative;
45
+ top: 0;
46
+ }
47
+ `;
48
+
49
+ @provide({ context: timegroupContext })
50
+ _timeGroupContext = this;
51
+
52
+ #currentTime = 0;
53
+
54
+ @property({
55
+ type: String,
56
+ attribute: "mode",
57
+ })
58
+ mode: "fixed" | "sequence" | "contain" = "sequence";
59
+
60
+ @property({ type: Number })
61
+ set currentTime(time: number) {
62
+ this.#currentTime = Math.max(0, Math.min(time, this.durationMs / 1000));
63
+ try {
64
+ if (this.id) {
65
+ if (this.isConnected) {
66
+ localStorage.setItem(this.storageKey, time.toString());
67
+ }
68
+ }
69
+ } catch (error) {
70
+ console.warn("Failed to save time to localStorage", error);
71
+ }
72
+ }
73
+ get currentTime() {
74
+ return this.#currentTime;
75
+ }
76
+ get currentTimeMs() {
77
+ return this.currentTime * 1000;
78
+ }
79
+ set currentTimeMs(ms: number) {
80
+ this.currentTime = ms / 1000;
81
+ }
82
+
83
+ @property({
84
+ attribute: "crossover",
85
+ converter: {
86
+ fromAttribute: (value: string): number => {
87
+ if (value.endsWith("ms")) {
88
+ return parseFloat(value);
89
+ }
90
+ if (value.endsWith("s")) {
91
+ return parseFloat(value) * 1000;
92
+ } else {
93
+ throw new Error(
94
+ "`crossover` MUST be in milliseconds or seconds (10s, 10000ms)",
95
+ );
96
+ }
97
+ },
98
+ toAttribute: (value: number) => `${value}ms`,
99
+ },
100
+ })
101
+ crossoverMs = 0;
102
+
103
+ render() {
104
+ return html`<slot></slot> `;
105
+ }
106
+
107
+ maybeLoadTimeFromLocalStorage() {
108
+ if (this.id) {
109
+ try {
110
+ return parseFloat(localStorage.getItem(this.storageKey) || "0");
111
+ } catch (error) {
112
+ console.warn("Failed to load time from localStorage", error);
113
+ }
114
+ }
115
+ return 0;
116
+ }
117
+
118
+ connectedCallback() {
119
+ super.connectedCallback();
120
+ if (this.id) {
121
+ this.#currentTime = this.maybeLoadTimeFromLocalStorage();
122
+ }
123
+
124
+ if (this.parentTimegroup) {
125
+ new TimegroupController(this.parentTimegroup, this);
126
+ }
127
+
128
+ if (this.shouldWrapWithWorkbench()) {
129
+ this.wrapWithWorkbench();
130
+ }
131
+ }
132
+
133
+ get storageKey() {
134
+ if (!this.id) {
135
+ throw new Error("Timegroup must have an id to use localStorage.");
136
+ }
137
+ return `ef-timegroup-${this.id}`;
138
+ }
139
+
140
+ get crossoverStartMs() {
141
+ const parentTimeGroup = this.parentTimegroup;
142
+ if (!parentTimeGroup || !this.previousElementSibling) {
143
+ return 0;
144
+ }
145
+
146
+ return parentTimeGroup.crossoverMs;
147
+ }
148
+ get crossoverEndMs() {
149
+ const parentTimeGroup = this.parentTimegroup;
150
+ if (!parentTimeGroup || !this.nextElementSibling) {
151
+ return 0;
152
+ }
153
+
154
+ return parentTimeGroup.crossoverMs;
155
+ }
156
+
157
+ get durationMs() {
158
+ switch (this.mode) {
159
+ case "fixed":
160
+ return super.durationMs || 0;
161
+ case "sequence":
162
+ let duration = 0;
163
+ this.childTemporals.forEach((node) => {
164
+ duration += node.durationMs;
165
+ });
166
+ return duration;
167
+ case "contain":
168
+ let maxDuration = 0;
169
+ this.childTemporals.forEach((node) => {
170
+ if (node.hasOwnDuration) {
171
+ maxDuration = Math.max(maxDuration, node.durationMs);
172
+ }
173
+ });
174
+ return maxDuration;
175
+ default:
176
+ throw new Error(`Invalid time mode: ${this.mode}`);
177
+ }
178
+ }
179
+
180
+ async waitForMediaDurations() {
181
+ return await Promise.all(
182
+ deepGetMediaElements(this).map(
183
+ (media) => media.trackFragmentIndexLoader.taskComplete,
184
+ ),
185
+ );
186
+ }
187
+
188
+ get childTemporals() {
189
+ return shallowGetTemporalElements(this);
190
+ }
191
+
192
+ protected updated(
193
+ changedProperties: PropertyValueMap<any> | Map<PropertyKey, unknown>,
194
+ ): void {
195
+ super.updated(changedProperties);
196
+ if (
197
+ changedProperties.has("currentTime") ||
198
+ changedProperties.has("ownCurrentTimeMs")
199
+ ) {
200
+ console.log("Updating animations to time", this.ownCurrentTimeMs);
201
+ const animations = this.getAnimations({ subtree: true });
202
+ this.style.setProperty(
203
+ "--ef-duration",
204
+ `${this.durationMs + this.crossoverEndMs + this.crossoverStartMs}ms`,
205
+ );
206
+ animations.forEach((animation) => {
207
+ if (animation.playState === "running") {
208
+ animation.pause();
209
+ }
210
+ const effect = animation.effect;
211
+ if (!(effect && effect instanceof KeyframeEffect)) {
212
+ return;
213
+ }
214
+ const target = effect.target;
215
+ // Important to avoid going to the end of the animation
216
+ // or it will reset awkwardly.
217
+ if (isEFTemporal(target)) {
218
+ const timing = effect.getTiming();
219
+ const duration = Number(timing.duration) ?? 0;
220
+ const delay = Number(timing.delay);
221
+ const newTime = Math.floor(
222
+ Math.min(target.ownCurrentTimeMs, duration - 1 + delay),
223
+ );
224
+ if (Number.isNaN(newTime)) {
225
+ return;
226
+ }
227
+ animation.currentTime = newTime;
228
+ } else if (target) {
229
+ const nearestTimegroup = target.closest("ef-timegroup");
230
+ if (!nearestTimegroup) {
231
+ return;
232
+ }
233
+ const timing = effect.getTiming();
234
+ const duration = Number(timing.duration) ?? 0;
235
+ const delay = Number(timing.delay);
236
+ const newTime = Math.floor(
237
+ Math.min(nearestTimegroup.ownCurrentTimeMs, duration - 1 + delay),
238
+ );
239
+
240
+ if (Number.isNaN(newTime)) {
241
+ return;
242
+ }
243
+ animation.currentTime = newTime;
244
+ }
245
+ });
246
+ }
247
+ }
248
+
249
+ shouldWrapWithWorkbench() {
250
+ return (
251
+ EF_INTERACTIVE &&
252
+ this.closest("ef-timegroup") === this &&
253
+ this.closest("ef-workbench") === null
254
+ );
255
+ }
256
+
257
+ wrapWithWorkbench() {
258
+ const workbench = document.createElement("ef-workbench");
259
+ document.body.append(workbench);
260
+ if (!this.hasAttribute("id")) {
261
+ this.setAttribute("id", "root-this");
262
+ }
263
+ this.setAttribute("slot", "canvas");
264
+ workbench.append(this as unknown as Element);
265
+
266
+ const filmstrip = document.createElement("ef-filmstrip");
267
+ filmstrip.setAttribute("slot", "timeline");
268
+ filmstrip.setAttribute("target", `#${this.id}`);
269
+ workbench.append(filmstrip);
270
+ }
271
+
272
+ get hasOwnDuration() {
273
+ return true;
274
+ }
275
+
276
+ get efElements() {
277
+ return Array.from(
278
+ this.querySelectorAll(
279
+ "ef-audio, ef-video, ef-image, ef-captions, ef-waveform",
280
+ ),
281
+ );
282
+ }
283
+
284
+ async renderAudio(fromMs: number, toMs: number) {
285
+ await this.waitForMediaDurations();
286
+
287
+ const durationMs = toMs - fromMs;
288
+ const audioContext = new OfflineAudioContext(
289
+ 2,
290
+ Math.round((48000 * durationMs) / 1000),
291
+ 48000,
292
+ );
293
+
294
+ console.log("RENDERING AUDIO");
295
+ console.log(
296
+ `renderAudio fromMs=${fromMs} toMs=${toMs} durationMs=${durationMs} ctxSize=${audioContext.length}`,
297
+ );
298
+
299
+ await Promise.all(
300
+ deepGetMediaElements(this).map(async (mediaElement) => {
301
+ await mediaElement.trackFragmentIndexLoader.taskComplete;
302
+
303
+ const mediaStartsBeforeEnd = mediaElement.startTimeMs <= toMs;
304
+ const mediaEndsAfterStart = mediaElement.endTimeMs >= fromMs;
305
+ const mediaOverlaps = mediaStartsBeforeEnd && mediaEndsAfterStart;
306
+ if (!mediaOverlaps || mediaElement.defaultAudioTrackId === undefined) {
307
+ console.log("Skipping audio element due to lack of overlap");
308
+ return;
309
+ }
310
+
311
+ const audio = await mediaElement.fetchAudioSpanningTime(fromMs, toMs);
312
+ if (!audio) {
313
+ throw new Error("Failed to fetch audio");
314
+ }
315
+
316
+ const ctxStartMs = Math.max(0, mediaElement.startTimeMs - fromMs);
317
+ const ctxEndMs = Math.min(durationMs, mediaElement.endTimeMs - fromMs);
318
+ const ctxDurationMs = ctxEndMs - ctxStartMs;
319
+
320
+ const offset =
321
+ Math.max(0, fromMs - mediaElement.startTimeMs) - audio.startMs;
322
+
323
+ // console.log("Fetching audio spanning time", audio.startMs, audio.endMs);
324
+ console.log(
325
+ "AUDIO SPAN",
326
+ JSON.stringify({
327
+ fromMs,
328
+ toMs,
329
+ audio: {
330
+ startMs: audio.startMs,
331
+ endMs: audio.endMs,
332
+ },
333
+ elementStart: mediaElement.startTimeMs,
334
+ elementEnd: mediaElement.endTimeMs,
335
+ ctxStart: ctxStartMs,
336
+ ctxEnd: ctxEndMs,
337
+ offset,
338
+ }),
339
+ );
340
+
341
+ const bufferSource = audioContext.createBufferSource();
342
+ bufferSource.buffer = await audioContext.decodeAudioData(
343
+ await audio.blob.arrayBuffer(),
344
+ );
345
+ bufferSource.connect(audioContext.destination);
346
+
347
+ bufferSource.start(
348
+ ctxStartMs / 1000,
349
+ offset / 1000,
350
+ ctxDurationMs / 1000,
351
+ );
352
+ }),
353
+ );
354
+
355
+ return await audioContext.startRendering();
356
+ }
357
+
358
+ async loadMd5Sums() {
359
+ const efElements = this.efElements;
360
+ const loaderTasks: Promise<any>[] = [];
361
+ efElements.forEach((el) => {
362
+ const md5SumLoader = (el as any).md5SumLoader;
363
+ if (md5SumLoader instanceof Task) {
364
+ md5SumLoader.run();
365
+ loaderTasks.push(md5SumLoader.taskComplete);
366
+ }
367
+ });
368
+
369
+ await Promise.all(loaderTasks);
370
+
371
+ efElements.map((el) => {
372
+ if ("productionSrc" in el && el.productionSrc instanceof Function) {
373
+ el.setAttribute("src", el.productionSrc());
374
+ }
375
+ });
376
+ }
377
+
378
+ frameTask = new Task(this, {
379
+ autoRun: EF_INTERACTIVE,
380
+ args: () => [this.ownCurrentTimeMs, this.currentTimeMs] as const,
381
+ task: async ([], { signal }) => {
382
+ let fullyUpdated = await this.updateComplete;
383
+ while (!fullyUpdated) {
384
+ fullyUpdated = await this.updateComplete;
385
+ }
386
+ },
387
+ });
388
+ }
389
+
390
+ declare global {
391
+ interface HTMLElementTagNameMap {
392
+ "ef-timegroup": EFTimegroup & Element;
393
+ }
394
+ }
@@ -0,0 +1,13 @@
1
+ class EFTimeline extends HTMLElement {
2
+ get durationMs() {
3
+ let duration = 0;
4
+ this.childNodes.forEach((node) => {
5
+ if ("durationMs" in node && typeof node.durationMs === "number") {
6
+ duration += node.durationMs;
7
+ }
8
+ });
9
+ return duration;
10
+ }
11
+ }
12
+
13
+ window.customElements.define("ef-timeline", EFTimeline);
@@ -0,0 +1,114 @@
1
+ import { html, css } from "lit";
2
+ import { Task } from "@lit/task";
3
+ import { createRef, ref } from "lit/directives/ref.js";
4
+ import { customElement } from "lit/decorators.js";
5
+
6
+ import { EFMedia } from "./EFMedia";
7
+ import { TWMixin } from "../gui/TWMixin";
8
+
9
+ @customElement("ef-video")
10
+ export class EFVideo extends TWMixin(EFMedia) {
11
+ static styles = [
12
+ css`
13
+ :host {
14
+ display: block;
15
+ }
16
+ `,
17
+ ];
18
+ canvasRef = createRef<HTMLCanvasElement>();
19
+
20
+ render() {
21
+ return html` <canvas
22
+ class="h-full w-full object-fill"
23
+ ${ref(this.canvasRef)}
24
+ ></canvas>`;
25
+ }
26
+
27
+ get canvasElement() {
28
+ return this.canvasRef.value;
29
+ }
30
+
31
+ // The underlying video decoder MUST NOT be used concurrently.
32
+ // If frames are fed in out of order, the decoder may crash.
33
+ #decoderLock = false;
34
+
35
+ frameTask = new Task(this, {
36
+ args: () =>
37
+ [
38
+ this.trackFragmentIndexLoader.status,
39
+ this.initSegmentsLoader.status,
40
+ this.seekTask.status,
41
+ this.fetchSeekTask.status,
42
+ this.videoAssetTask.status,
43
+ this.paintTask.status,
44
+ ] as const,
45
+ task: async () => {
46
+ console.log("EFVideo frameTask", this.ownCurrentTimeMs);
47
+ await this.trackFragmentIndexLoader.taskComplete;
48
+ await this.initSegmentsLoader.taskComplete;
49
+ await this.seekTask.taskComplete;
50
+ await this.fetchSeekTask.taskComplete;
51
+ await this.videoAssetTask.taskComplete;
52
+ await this.paintTask.taskComplete;
53
+ console.log("EFVideo frameTask complete", this.ownCurrentTimeMs);
54
+ this.rootTimegroup?.requestUpdate();
55
+ },
56
+ });
57
+
58
+ paintTask = new Task(this, {
59
+ args: () => [this.videoAssetTask.value, this.desiredSeekTimeMs] as const,
60
+ task: async (
61
+ [videoAsset, seekToMs],
62
+ {
63
+ signal:
64
+ _signal /** Aborting seeks is counter-productive. It is better to drop seeks. */,
65
+ },
66
+ ) => {
67
+ console.log(`EFVideo paintTask decoderLock=${this.#decoderLock}`);
68
+ if (!videoAsset) {
69
+ return;
70
+ }
71
+ if (this.#decoderLock) {
72
+ return;
73
+ }
74
+ try {
75
+ this.#decoderLock = true;
76
+ const frame = await videoAsset.seekToTime(seekToMs / 1000);
77
+ console.log(
78
+ "Painting frame",
79
+ "seekToMs",
80
+ seekToMs,
81
+ "timestamp",
82
+ frame?.timestamp,
83
+ );
84
+
85
+ if (!this.canvasElement) {
86
+ return;
87
+ }
88
+ const ctx = this.canvasElement.getContext("2d");
89
+ if (!(frame && ctx)) {
90
+ return;
91
+ }
92
+
93
+ this.canvasElement.width = frame?.codedWidth;
94
+ this.canvasElement.height = frame?.codedHeight;
95
+
96
+ ctx.drawImage(
97
+ frame,
98
+ 0,
99
+ 0,
100
+ this.canvasElement.width,
101
+ this.canvasElement.height,
102
+ );
103
+
104
+ return seekToMs;
105
+ } catch (error) {
106
+ console.trace("Unexpected error while seeking video", error);
107
+ // As a practical matter, we should probably just re-create the VideoAsset if decoding fails.
108
+ // The decoder is probably in an invalid state anyway.
109
+ } finally {
110
+ this.#decoderLock = false;
111
+ }
112
+ },
113
+ });
114
+ }