@editframe/elements 0.6.0-beta.16 → 0.6.0-beta.17

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.
@@ -0,0 +1,13 @@
1
+ export class EFTimeline extends HTMLElement {
2
+ get durationMs() {
3
+ let duration = 0;
4
+ for (const node of this.childNodes) {
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,103 @@
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
+ await this.trackFragmentIndexLoader.taskComplete;
47
+ await this.initSegmentsLoader.taskComplete;
48
+ await this.seekTask.taskComplete;
49
+ await this.fetchSeekTask.taskComplete;
50
+ await this.videoAssetTask.taskComplete;
51
+ await this.paintTask.taskComplete;
52
+ },
53
+ });
54
+
55
+ paintTask = new Task(this, {
56
+ args: () => [this.videoAssetTask.value, this.desiredSeekTimeMs] as const,
57
+ task: async (
58
+ [videoAsset, seekToMs],
59
+ {
60
+ signal:
61
+ _signal /** Aborting seeks is counter-productive. It is better to drop seeks. */,
62
+ },
63
+ ) => {
64
+ if (!videoAsset) {
65
+ return;
66
+ }
67
+ if (this.#decoderLock) {
68
+ return;
69
+ }
70
+ try {
71
+ this.#decoderLock = true;
72
+ const frame = await videoAsset.seekToTime(seekToMs / 1000);
73
+
74
+ if (!this.canvasElement) {
75
+ return;
76
+ }
77
+ const ctx = this.canvasElement.getContext("2d");
78
+ if (!(frame && ctx)) {
79
+ return;
80
+ }
81
+
82
+ this.canvasElement.width = frame?.codedWidth;
83
+ this.canvasElement.height = frame?.codedHeight;
84
+
85
+ ctx.drawImage(
86
+ frame,
87
+ 0,
88
+ 0,
89
+ this.canvasElement.width,
90
+ this.canvasElement.height,
91
+ );
92
+
93
+ return seekToMs;
94
+ } catch (error) {
95
+ console.trace("Unexpected error while seeking video", error);
96
+ // As a practical matter, we should probably just re-create the VideoAsset if decoding fails.
97
+ // The decoder is probably in an invalid state anyway.
98
+ } finally {
99
+ this.#decoderLock = false;
100
+ }
101
+ },
102
+ });
103
+ }
@@ -0,0 +1,409 @@
1
+ import { EFAudio } from "./EFAudio";
2
+
3
+ import { LitElement, html } from "lit";
4
+ import { customElement, property } from "lit/decorators.js";
5
+ import { EFVideo } from "./EFVideo";
6
+ import { EFTemporal } from "./EFTemporal";
7
+ import { CrossUpdateController } from "./CrossUpdateController";
8
+ import { TWMixin } from "../gui/TWMixin";
9
+ import { Task } from "@lit/task";
10
+ import * as d3 from "d3";
11
+ import { type Ref, createRef, ref } from "lit/directives/ref.js";
12
+ import { EF_INTERACTIVE } from "../EF_INTERACTIVE";
13
+
14
+ @customElement("ef-waveform")
15
+ export class EFWaveform extends EFTemporal(TWMixin(LitElement)) {
16
+ static styles = [];
17
+ svgRef: Ref<SVGElement> = createRef();
18
+ createRenderRoot() {
19
+ return this;
20
+ }
21
+ render() {
22
+ return html` <svg ${ref(this.svgRef)} class="h-full w-full" store></svg> `;
23
+ }
24
+
25
+ @property({
26
+ type: String,
27
+ attribute: "mode",
28
+ })
29
+ mode:
30
+ | "roundBars"
31
+ | "bars"
32
+ | "bricks"
33
+ | "equalizer"
34
+ | "curve"
35
+ | "line"
36
+ | "pixel"
37
+ | "wave" = "bars";
38
+
39
+ @property({ type: String })
40
+ color = "currentColor";
41
+
42
+ connectedCallback() {
43
+ super.connectedCallback();
44
+ if (this.target) {
45
+ new CrossUpdateController(this.target, this);
46
+ }
47
+ }
48
+
49
+ protected drawBars(svg: SVGElement, frequencyData: Uint8Array) {
50
+ const waveWidth = svg.clientWidth * devicePixelRatio;
51
+ const waveHeight = svg.clientHeight;
52
+ const waveLeft = 0;
53
+ const waveRight = waveWidth;
54
+
55
+ const barX = d3
56
+ .scaleBand()
57
+ .paddingInner(0.5)
58
+ .paddingOuter(0.01)
59
+ .domain(d3.range(frequencyData.length).map((n) => String(n)))
60
+ .rangeRound([waveLeft, waveRight]);
61
+
62
+ const height = d3
63
+ .scaleLinear()
64
+ .domain([0, 255])
65
+ .range([0, waveHeight / 2]);
66
+
67
+ const baseline = waveHeight / 2;
68
+
69
+ const bars = d3.select(svg).selectAll("rect").data(frequencyData);
70
+ const minBarHeight = 2;
71
+
72
+ bars
73
+ .enter()
74
+ .append("rect")
75
+ // @ts-ignore Not sure why this doesn't pass typechecks.
76
+ .merge(bars)
77
+ .attr("x", (_, i) => barX(String(i)) || 0)
78
+ .attr("y", (value) => baseline - height(value))
79
+ .attr("width", barX.bandwidth() / 1.2)
80
+ .attr("height", (value) => Math.max(height(value) * 2, minBarHeight));
81
+
82
+ bars.exit().remove();
83
+ }
84
+
85
+ protected drawBricks(svg: SVGElement, frequencyData: Uint8Array) {
86
+ const waveWidth = svg.clientWidth * devicePixelRatio;
87
+ const waveHeight = svg.clientHeight * devicePixelRatio;
88
+ const brickWidth = waveWidth / frequencyData.length;
89
+ const brickHeightFactor = waveHeight / 255 / 2;
90
+ const brickPadding = 2;
91
+ const midHeight = waveHeight / 2;
92
+
93
+ d3.select(svg)
94
+ .selectAll("line.brickBaseLine")
95
+ .data([0])
96
+ .join("line")
97
+ .attr("class", "brickBaseLine")
98
+ .attr("x1", 0)
99
+ .attr("x2", waveWidth)
100
+ .attr("y1", midHeight)
101
+ .attr("y2", midHeight)
102
+ .attr("stroke", "currentColor")
103
+ .attr("stroke-width", 4)
104
+ .attr("stroke-dasharray", "2");
105
+
106
+ d3.select(svg)
107
+ .selectAll("rect.brick")
108
+ .data(frequencyData)
109
+ .join("rect")
110
+ .attr("class", "brick")
111
+ .attr("x", (_d, i) => i * brickWidth)
112
+ .attr("y", (d) => midHeight - d * brickHeightFactor)
113
+ .attr("width", brickWidth - brickPadding)
114
+ .attr("height", (d) => d * brickHeightFactor * 2);
115
+ }
116
+
117
+ protected drawLine(svg: SVGElement, frequencyData: Uint8Array) {
118
+ const waveWidth = svg.clientWidth * devicePixelRatio;
119
+ const waveHeight = svg.clientHeight * devicePixelRatio;
120
+
121
+ const xScale = d3
122
+ .scaleLinear()
123
+ .domain([0, frequencyData.length - 1])
124
+ .range([0, waveWidth]);
125
+
126
+ const yScale = d3.scaleLinear().domain([0, 255]).range([waveHeight, 0]);
127
+
128
+ const lineGenerator = d3
129
+ .line<Uint8Array[number]>()
130
+ .x((_, i) => xScale(i))
131
+ .y((d) => yScale(d));
132
+
133
+ const pathData = lineGenerator(frequencyData);
134
+
135
+ d3.select(svg)
136
+ .selectAll("path.line")
137
+ .data([frequencyData])
138
+ .join("path")
139
+ .attr("class", "line")
140
+ .attr("d", pathData)
141
+ .attr("fill", "none")
142
+ .attr("stroke", "currentColor")
143
+ .attr("stroke-width", 4);
144
+ }
145
+
146
+ protected drawRoundBars(svg: SVGElement, frequencyData: Uint8Array) {
147
+ const waveWidth = svg.clientWidth * devicePixelRatio;
148
+ const waveHeight = svg.clientHeight;
149
+ const waveLeft = 0;
150
+ const waveRight = waveWidth;
151
+
152
+ const barX = d3
153
+ .scaleBand()
154
+ .paddingInner(0.5)
155
+ .paddingOuter(0.01)
156
+ .domain(d3.range(frequencyData.length).map((n) => String(n)))
157
+ .rangeRound([waveLeft, waveRight]);
158
+
159
+ const height = d3
160
+ .scaleLinear()
161
+ .domain([0, 255])
162
+ .range([0, waveHeight / 2]);
163
+
164
+ const baseline = waveHeight / 2;
165
+
166
+ const bars = d3.select(svg).selectAll("rect").data(frequencyData);
167
+ const minBarHeight = 2;
168
+
169
+ bars
170
+ .enter()
171
+ .append("rect")
172
+ // @ts-ignore Not sure why this doesn't pass typechecks.
173
+ .merge(bars)
174
+ .attr("x", (_, i) => barX(String(i)) || 0)
175
+ .attr("y", (value) => baseline - height(value))
176
+ .attr("width", barX.bandwidth() / 1.2)
177
+ .attr("height", (value) => Math.max(height(value) * 2, minBarHeight))
178
+ .attr("rx", barX.bandwidth())
179
+ .attr("ry", barX.bandwidth());
180
+
181
+ bars.exit().remove();
182
+ }
183
+ protected drawEqualizer(svg: SVGElement, frequencyData: Uint8Array) {
184
+ const waveWidth = svg.clientWidth * devicePixelRatio;
185
+ const waveHeight = svg.clientHeight * devicePixelRatio;
186
+ const barWidth = waveWidth / frequencyData.length;
187
+ const barPadding = 1;
188
+ const minHeight = 1;
189
+
190
+ const heightScale = d3
191
+ .scaleLinear()
192
+ .domain([0, 255])
193
+ .range([0, waveHeight / 2]);
194
+
195
+ d3.select(svg)
196
+ .selectAll("line.equalizerBaseLine")
197
+ .data([0])
198
+ .join("line")
199
+ .attr("class", "equalizerBaseLine")
200
+ .attr("x1", 0)
201
+ .attr("x2", waveWidth)
202
+ .attr("y1", waveHeight / 2)
203
+ .attr("y2", waveHeight / 2)
204
+ .attr("stroke-width", 2);
205
+
206
+ d3.select(svg)
207
+ .selectAll("rect.equalizerBar")
208
+ .data(frequencyData)
209
+ .join("rect")
210
+ .attr("class", "equalizerBar")
211
+ .attr("x", (_d, i) => i * barWidth + barPadding / 2)
212
+ .attr(
213
+ "y",
214
+ (d) => waveHeight / 2 - Math.max(heightScale(d) / 2, minHeight),
215
+ )
216
+ .attr("width", barWidth - barPadding)
217
+ .attr("height", (d) => Math.max(heightScale(d), minHeight));
218
+
219
+ d3.select(svg)
220
+ .selectAll("rect.equalizerBar")
221
+ .transition()
222
+ .duration(100)
223
+ .attr(
224
+ "y",
225
+ (d) => waveHeight / 2 - Math.max(heightScale(Number(d)) / 2, minHeight),
226
+ )
227
+ .attr("height", (d) => Math.max(heightScale(Number(d)), minHeight));
228
+ }
229
+
230
+ protected drawCurve(svg: SVGElement, frequencyData: Uint8Array) {
231
+ const waveWidth = svg.clientWidth * devicePixelRatio;
232
+ const waveHeight = svg.clientHeight * devicePixelRatio;
233
+
234
+ const xScale = d3
235
+ .scaleLinear()
236
+ .domain([0, frequencyData.length])
237
+ .range([0, waveWidth]);
238
+
239
+ const yScale = d3.scaleLinear().domain([0, 255]).range([waveHeight, 0]);
240
+
241
+ const curveGenerator = d3
242
+ .line<Uint8Array[number]>()
243
+ .x((_, i) => xScale(i))
244
+ .y((d) => yScale(d))
245
+ .curve(d3.curveNatural);
246
+
247
+ const pathData = curveGenerator(frequencyData);
248
+
249
+ d3.select(svg)
250
+ .selectAll("path.curve")
251
+ .data([frequencyData])
252
+ .join("path")
253
+ .attr("class", "curve")
254
+ .attr("d", pathData)
255
+ .attr("fill", "none")
256
+ .attr("stroke", "currentColor")
257
+ .attr("stroke-width", 4);
258
+ }
259
+
260
+ protected drawPixel(svg: SVGElement, frequencyData: Uint8Array) {
261
+ const waveWidth = svg.clientWidth * devicePixelRatio;
262
+ const waveHeight = svg.clientHeight;
263
+ const baseline = waveHeight / 2;
264
+
265
+ const barX = d3
266
+ .scaleBand()
267
+ .domain(d3.range(frequencyData.length).map(String))
268
+ .rangeRound([0, waveWidth])
269
+ .paddingInner(0.03)
270
+ .paddingOuter(0.02);
271
+
272
+ const height = d3.scaleLinear().domain([0, 255]).range([0, baseline]);
273
+
274
+ const bars = d3.select(svg).selectAll("rect").data(frequencyData);
275
+
276
+ bars
277
+ .enter()
278
+ .append("rect")
279
+ // @ts-ignore Not sure why this doesn't pass typechecks.
280
+ .merge(bars)
281
+ .attr("x", (_, i) => barX(String(i)) || 0)
282
+ .attr("y", (value) => baseline - height(value))
283
+ .attr("width", barX.bandwidth())
284
+ .attr("height", (value) => height(value) * 2);
285
+
286
+ bars.exit().remove();
287
+ }
288
+ protected drawWave(svg: SVGElement, frequencyData: Uint8Array) {
289
+ const waveWidth = svg.clientWidth * devicePixelRatio;
290
+ const waveHeight = svg.clientHeight;
291
+
292
+ const barX = d3
293
+ .scaleBand()
294
+ .domain(d3.range(frequencyData.length).map(String))
295
+ .rangeRound([0, waveWidth])
296
+ .paddingInner(0.03)
297
+ .paddingOuter(0.02);
298
+
299
+ const height = d3
300
+ .scaleLinear()
301
+ .domain([0, 255])
302
+ .range([0, waveHeight / 2]);
303
+
304
+ d3.select(svg)
305
+ .selectAll("line.baseline")
306
+ .data([0])
307
+ .join("line")
308
+ .attr("class", "baseline")
309
+ .attr("x1", (_, i) => barX(String(i)) || 0)
310
+ .attr("x2", waveWidth)
311
+ .attr("y1", waveHeight / 2)
312
+ .attr("y2", waveHeight / 2)
313
+ .attr("stroke", "currentColor")
314
+ .attr("stroke-width", 2);
315
+
316
+ const bars = d3.select(svg).selectAll("rect").data(frequencyData);
317
+
318
+ bars
319
+ .enter()
320
+ .append("rect")
321
+ // @ts-ignore Not sure why this doesn't pass typechecks.
322
+ .merge(bars)
323
+ .attr("x", (_, i) => barX(String(i)) || 0)
324
+ .attr("y", (value) => waveHeight / 2 - height(value))
325
+ .attr("width", barX.bandwidth())
326
+ .attr("height", (value) => height(value) * 2);
327
+
328
+ bars.exit().remove();
329
+ }
330
+
331
+ frameTask = new Task(this, {
332
+ autoRun: EF_INTERACTIVE,
333
+ args: () => [this.target.audioBufferTask.status] as const,
334
+ task: async () => {
335
+ await this.target.audioBufferTask.taskComplete;
336
+ },
337
+ });
338
+
339
+ protected async updated() {
340
+ const svg = this.svgRef.value;
341
+ if (!svg) {
342
+ return;
343
+ }
344
+ if (!this.target.audioBufferTask.value) {
345
+ return;
346
+ }
347
+ if (this.target.ownCurrentTimeMs > 0) {
348
+ const audioContext = new OfflineAudioContext(2, 48000 / 25, 48000);
349
+ const audioBufferSource = audioContext.createBufferSource();
350
+ audioBufferSource.buffer = this.target.audioBufferTask.value.buffer;
351
+ const analyser = audioContext.createAnalyser();
352
+ analyser.fftSize = 256;
353
+ audioBufferSource.connect(analyser);
354
+
355
+ audioBufferSource.start(
356
+ 0,
357
+ Math.max(
358
+ 0,
359
+ (this.target.ownCurrentTimeMs -
360
+ this.target.audioBufferTask.value.startOffsetMs) /
361
+ 1000,
362
+ ),
363
+ 48000 / 1000,
364
+ );
365
+ await audioContext.startRendering();
366
+ const frequencyData = new Uint8Array(analyser.frequencyBinCount);
367
+ analyser.getByteFrequencyData(frequencyData);
368
+ const rect = this.getBoundingClientRect();
369
+
370
+ svg.setAttribute("width", (rect.width * devicePixelRatio).toString());
371
+ svg.setAttribute("height", (rect.height * devicePixelRatio).toString());
372
+
373
+ switch (this.mode) {
374
+ case "bars":
375
+ this.drawBars(svg, frequencyData);
376
+ break;
377
+ case "bricks":
378
+ this.drawBricks(svg, frequencyData);
379
+ break;
380
+ case "curve":
381
+ this.drawCurve(svg, frequencyData);
382
+ break;
383
+ case "line":
384
+ this.drawLine(svg, frequencyData);
385
+ break;
386
+ case "pixel":
387
+ this.drawPixel(svg, frequencyData);
388
+ break;
389
+ case "wave":
390
+ this.drawWave(svg, frequencyData);
391
+ break;
392
+ case "roundBars":
393
+ this.drawRoundBars(svg, frequencyData);
394
+ break;
395
+ case "equalizer":
396
+ this.drawEqualizer(svg, frequencyData);
397
+ break;
398
+ }
399
+ }
400
+ }
401
+
402
+ get target() {
403
+ const target = document.querySelector(this.getAttribute("target") ?? "");
404
+ if (target instanceof EFAudio || target instanceof EFVideo) {
405
+ return target;
406
+ }
407
+ throw new Error("Invalid target, must be an EFAudio element");
408
+ }
409
+ }
@@ -0,0 +1,19 @@
1
+ import { consume } from "@lit/context";
2
+ import type { LitElement } from "lit";
3
+ import { fetchContext } from "../gui/EFWorkbench";
4
+ import { state } from "lit/decorators/state.js";
5
+
6
+ export declare class FetchMixinInterface {
7
+ fetch: typeof fetch;
8
+ }
9
+
10
+ type Constructor<T = {}> = new (...args: any[]) => T;
11
+ export function FetchMixin<T extends Constructor<LitElement>>(superClass: T) {
12
+ class FetchElement extends superClass {
13
+ @consume({ context: fetchContext, subscribe: true })
14
+ @state()
15
+ fetch = fetch.bind(window);
16
+ }
17
+
18
+ return FetchElement as Constructor<FetchMixinInterface> & T;
19
+ }
@@ -0,0 +1,25 @@
1
+ import type { ReactiveController, LitElement } from "lit";
2
+ import type { EFTimegroup } from "./EFTimegroup";
3
+
4
+ export class TimegroupController implements ReactiveController {
5
+ constructor(
6
+ private host: EFTimegroup,
7
+ private child: { currentTimeMs: number; startTimeMs?: number } & LitElement,
8
+ ) {
9
+ this.host.addController(this);
10
+ }
11
+
12
+ remove() {
13
+ this.host.removeController(this);
14
+ }
15
+
16
+ hostDisconnected(): void {
17
+ this.host.removeController(this);
18
+ }
19
+
20
+ hostUpdated(): void {
21
+ this.child.requestUpdate();
22
+ this.child.currentTimeMs =
23
+ this.host.currentTimeMs - (this.child.startTimeMs ?? 0);
24
+ }
25
+ }
@@ -0,0 +1,6 @@
1
+ import { parseTimeToMs } from "./parseTimeToMs";
2
+
3
+ export const durationConverter = {
4
+ fromAttribute: (value: string): number => parseTimeToMs(value),
5
+ toAttribute: (value: number) => `${value}s`,
6
+ };
@@ -0,0 +1,9 @@
1
+ export const parseTimeToMs = (time: string) => {
2
+ if (time.endsWith("ms")) {
3
+ return Number.parseFloat(time);
4
+ }
5
+ if (time.endsWith("s")) {
6
+ return Number.parseFloat(time) * 1000;
7
+ }
8
+ throw new Error("Time must be in milliseconds or seconds (10s, 10000ms)");
9
+ };
@@ -0,0 +1,24 @@
1
+ import { EFTimegroup } from "./EFTimegroup";
2
+
3
+ export const getRootTimeGroup = (element: Element): EFTimegroup | null => {
4
+ let bestCandidate: EFTimegroup | null = null;
5
+
6
+ let currentElement: Element | null = element;
7
+ while (currentElement) {
8
+ if (currentElement instanceof EFTimegroup) {
9
+ bestCandidate = currentElement;
10
+ }
11
+ currentElement = currentElement.parentElement;
12
+ }
13
+
14
+ return bestCandidate;
15
+ };
16
+
17
+ export const getStartTimeMs = (element: Element): number => {
18
+ const nearestTimeGroup = element.closest("ef-timegroup");
19
+ if (!(nearestTimeGroup instanceof EFTimegroup)) {
20
+ return 0;
21
+ }
22
+
23
+ return nearestTimeGroup.startTimeMs;
24
+ };