@editframe/elements 0.18.8-beta.0 → 0.18.20-beta.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.
Files changed (65) hide show
  1. package/dist/elements/EFMedia/AssetIdMediaEngine.js +4 -1
  2. package/dist/elements/EFMedia/AssetMediaEngine.d.ts +3 -4
  3. package/dist/elements/EFMedia/AssetMediaEngine.js +16 -15
  4. package/dist/elements/EFMedia/BaseMediaEngine.d.ts +30 -11
  5. package/dist/elements/EFMedia/BaseMediaEngine.js +83 -31
  6. package/dist/elements/EFMedia/JitMediaEngine.d.ts +2 -4
  7. package/dist/elements/EFMedia/JitMediaEngine.js +12 -12
  8. package/dist/elements/EFTemporal.d.ts +1 -0
  9. package/dist/elements/EFTemporal.js +8 -4
  10. package/dist/elements/EFTimegroup.js +21 -0
  11. package/dist/elements/EFVideo.d.ts +0 -1
  12. package/dist/elements/EFVideo.js +0 -9
  13. package/dist/elements/TargetController.js +3 -2
  14. package/dist/getRenderInfo.d.ts +2 -2
  15. package/dist/gui/ContextMixin.browsertest.d.ts +5 -0
  16. package/dist/gui/ContextMixin.js +96 -5
  17. package/package.json +2 -2
  18. package/src/elements/EFMedia/AssetIdMediaEngine.ts +10 -1
  19. package/src/elements/EFMedia/AssetMediaEngine.ts +25 -21
  20. package/src/elements/EFMedia/BaseMediaEngine.browsertest.ts +311 -0
  21. package/src/elements/EFMedia/BaseMediaEngine.ts +168 -51
  22. package/src/elements/EFMedia/JitMediaEngine.browsertest.ts +2 -12
  23. package/src/elements/EFMedia/JitMediaEngine.ts +25 -16
  24. package/src/elements/EFTemporal.browsertest.ts +47 -0
  25. package/src/elements/EFTemporal.ts +15 -5
  26. package/src/elements/EFTimegroup.ts +40 -0
  27. package/src/elements/EFVideo.browsertest.ts +127 -281
  28. package/src/elements/EFVideo.ts +9 -9
  29. package/src/elements/TargetController.ts +6 -2
  30. package/src/gui/ContextMixin.browsertest.ts +565 -1
  31. package/src/gui/ContextMixin.ts +138 -5
  32. package/test/__cache__/GET__api_v1_transcode_audio_1_m4s_url_http_3A_2F_2Fweb_3A3000_2Fhead_moov_480p_mp4__32da3954ba60c96ad732020c65a08ebc/metadata.json +3 -8
  33. package/test/__cache__/GET__api_v1_transcode_audio_2_m4s_url_http_3A_2F_2Fweb_3A3000_2Fhead_moov_480p_mp4__b0b2b07efcf607de8ee0f650328c32f7/metadata.json +3 -8
  34. package/test/__cache__/GET__api_v1_transcode_audio_3_m4s_url_http_3A_2F_2Fweb_3A3000_2Fhead_moov_480p_mp4__a75c2252b542e0c152c780e9a8d7b154/metadata.json +3 -8
  35. package/test/__cache__/GET__api_v1_transcode_audio_4_m4s_url_http_3A_2F_2Fweb_3A3000_2Fhead_moov_480p_mp4__a64ff1cfb1b52cae14df4b5dfa1e222b/metadata.json +3 -8
  36. package/test/__cache__/GET__api_v1_transcode_audio_5_m4s_url_http_3A_2F_2Fweb_3A3000_2Fhead_moov_480p_mp4__91e8a522f950809b9f09f4173113b4b0/metadata.json +3 -8
  37. package/test/__cache__/GET__api_v1_transcode_audio_init_m4s_url_http_3A_2F_2Fweb_3A3000_2Fhead_moov_480p_mp4__e66d2c831d951e74ad0aeaa6489795d0/metadata.json +3 -8
  38. package/test/__cache__/GET__api_v1_transcode_high_1_m4s_url_http_3A_2F_2Fweb_3A3000_2Fhead_moov_480p_mp4__26197f6f7c46cacb0a71134131c3f775/data.bin +0 -0
  39. package/test/__cache__/GET__api_v1_transcode_high_1_m4s_url_http_3A_2F_2Fweb_3A3000_2Fhead_moov_480p_mp4__26197f6f7c46cacb0a71134131c3f775/metadata.json +4 -9
  40. package/test/__cache__/GET__api_v1_transcode_high_2_m4s_url_http_3A_2F_2Fweb_3A3000_2Fhead_moov_480p_mp4__4cb6774cd3650ccf59c8f8dc6678c0b9/data.bin +0 -0
  41. package/test/__cache__/GET__api_v1_transcode_high_2_m4s_url_http_3A_2F_2Fweb_3A3000_2Fhead_moov_480p_mp4__4cb6774cd3650ccf59c8f8dc6678c0b9/metadata.json +4 -9
  42. package/test/__cache__/GET__api_v1_transcode_high_3_m4s_url_http_3A_2F_2Fweb_3A3000_2Fhead_moov_480p_mp4__0b3b2b1c8933f7fcf8a9ecaa88d58b41/data.bin +0 -0
  43. package/test/__cache__/GET__api_v1_transcode_high_3_m4s_url_http_3A_2F_2Fweb_3A3000_2Fhead_moov_480p_mp4__0b3b2b1c8933f7fcf8a9ecaa88d58b41/metadata.json +4 -9
  44. package/test/__cache__/GET__api_v1_transcode_high_4_m4s_url_http_3A_2F_2Fweb_3A3000_2Fhead_moov_480p_mp4__a6fb05a22b18d850f7f2950bbcdbdeed/data.bin +0 -0
  45. package/test/__cache__/GET__api_v1_transcode_high_4_m4s_url_http_3A_2F_2Fweb_3A3000_2Fhead_moov_480p_mp4__a6fb05a22b18d850f7f2950bbcdbdeed/metadata.json +4 -9
  46. package/test/__cache__/GET__api_v1_transcode_high_5_m4s_url_http_3A_2F_2Fweb_3A3000_2Fhead_moov_480p_mp4__a50058c7c3602e90879fe3428ed891f4/data.bin +0 -0
  47. package/test/__cache__/GET__api_v1_transcode_high_5_m4s_url_http_3A_2F_2Fweb_3A3000_2Fhead_moov_480p_mp4__a50058c7c3602e90879fe3428ed891f4/metadata.json +4 -9
  48. package/test/__cache__/GET__api_v1_transcode_high_init_m4s_url_http_3A_2F_2Fweb_3A3000_2Fhead_moov_480p_mp4__0798c479b44aaeef850609a430f6e613/data.bin +0 -0
  49. package/test/__cache__/GET__api_v1_transcode_high_init_m4s_url_http_3A_2F_2Fweb_3A3000_2Fhead_moov_480p_mp4__0798c479b44aaeef850609a430f6e613/metadata.json +4 -9
  50. package/test/__cache__/GET__api_v1_transcode_manifest_json_url_http_3A_2F_2Fweb_3A3000_2Fhead_moov_480p_mp4__3be92a0437de726b431ed5af2369158a/metadata.json +2 -4
  51. package/test/recordReplayProxyPlugin.js +46 -31
  52. package/test/setup.ts +16 -0
  53. package/test/useAssetMSW.ts +54 -0
  54. package/test/useMSW.ts +4 -11
  55. package/types.json +1 -1
  56. package/dist/elements/MediaController.d.ts +0 -30
  57. package/src/elements/EFMedia/BaseMediaEngine.test.ts +0 -164
  58. package/src/elements/MediaController.ts +0 -98
  59. package/test/__cache__/GET__api_v1_transcode_audio_1_mp4_url_http_3A_2F_2Fweb_3A3000_2Fhead_moov_480p_mp4_bytes_0__9ed2d25c675aa6bb6ff5b3ae23887c71/data.bin +0 -0
  60. package/test/__cache__/GET__api_v1_transcode_audio_1_mp4_url_http_3A_2F_2Fweb_3A3000_2Fhead_moov_480p_mp4_bytes_0__9ed2d25c675aa6bb6ff5b3ae23887c71/metadata.json +0 -22
  61. package/test/__cache__/GET__api_v1_transcode_audio_2_mp4_url_http_3A_2F_2Fweb_3A3000_2Fhead_moov_480p_mp4_bytes_0__d5a3309a2bf756dd6e304807eb402f56/data.bin +0 -0
  62. package/test/__cache__/GET__api_v1_transcode_audio_2_mp4_url_http_3A_2F_2Fweb_3A3000_2Fhead_moov_480p_mp4_bytes_0__d5a3309a2bf756dd6e304807eb402f56/metadata.json +0 -22
  63. package/test/__cache__/GET__api_v1_transcode_audio_3_mp4_url_http_3A_2F_2Fweb_3A3000_2Fhead_moov_480p_mp4_bytes_0__773254bb671e3466fca8677139fb239e/data.bin +0 -0
  64. package/test/__cache__/GET__api_v1_transcode_audio_3_mp4_url_http_3A_2F_2Fweb_3A3000_2Fhead_moov_480p_mp4_bytes_0__773254bb671e3466fca8677139fb239e/metadata.json +0 -22
  65. /package/dist/elements/EFMedia/{BaseMediaEngine.test.d.ts → BaseMediaEngine.browsertest.d.ts} +0 -0
@@ -24,14 +24,22 @@ function ContextMixin(superClass) {
24
24
  init.headers ||= {};
25
25
  Object.assign(init.headers, { "Content-Type": "application/json" });
26
26
  if (this.signingURL) {
27
- if (!this.#URLTokens[url]) this.#URLTokens[url] = fetch(this.signingURL, {
27
+ const now = Date.now();
28
+ const { cacheKey, signingPayload } = this.#getTokenCacheKey(url);
29
+ const tokenExpiration = this.#URLTokenExpirations[cacheKey] || 0;
30
+ if (!this.#URLTokens[cacheKey] || now >= tokenExpiration) this.#URLTokens[cacheKey] = fetch(this.signingURL, {
28
31
  method: "POST",
29
- body: JSON.stringify({ url })
32
+ body: JSON.stringify(signingPayload)
30
33
  }).then(async (response) => {
31
- if (response.ok) return (await response.json()).token;
34
+ if (response.ok) {
35
+ const tokenData = await response.json();
36
+ const token = tokenData.token;
37
+ this.#URLTokenExpirations[cacheKey] = this.#parseTokenExpiration(token);
38
+ return token;
39
+ }
32
40
  throw new Error(`Failed to sign URL: ${url}. SigningURL: ${this.signingURL} ${response.status} ${response.statusText}`);
33
41
  });
34
- const urlToken = await this.#URLTokens[url];
42
+ const urlToken = await this.#URLTokens[cacheKey];
35
43
  Object.assign(init.headers, { authorization: `Bearer ${urlToken}` });
36
44
  } else init.credentials = "include";
37
45
  return fetch(url, init);
@@ -51,7 +59,76 @@ function ContextMixin(superClass) {
51
59
  set apiHost(value) {
52
60
  this.#apiHost = value;
53
61
  }
62
+ get durationMs() {
63
+ return this.targetTimegroup?.durationMs ?? 0;
64
+ }
65
+ get endTimeMs() {
66
+ return this.targetTimegroup?.endTimeMs ?? 0;
67
+ }
54
68
  #URLTokens = {};
69
+ #URLTokenExpirations = {};
70
+ /**
71
+ * Generate a cache key for URL token based on signing strategy
72
+ *
73
+ * Uses unified prefix + parameter matching approach:
74
+ * - For transcode URLs: signs base "/api/v1/transcode" + params like {url: "source.mp4"}
75
+ * - For regular URLs: signs full URL with empty params {}
76
+ * - All validation uses prefix matching + exhaustive parameter matching
77
+ * - Multiple transcode segments with same source share one token (reduces round-trips)
78
+ */
79
+ #getTokenCacheKey(url) {
80
+ try {
81
+ const urlObj = new URL(url);
82
+ if (urlObj.pathname.includes("/api/v1/transcode/")) {
83
+ const urlParam = urlObj.searchParams.get("url");
84
+ if (urlParam) {
85
+ const basePath = `${urlObj.origin}/api/v1/transcode`;
86
+ const cacheKey = `${basePath}?url=${urlParam}`;
87
+ return {
88
+ cacheKey,
89
+ signingPayload: {
90
+ url: basePath,
91
+ params: { url: urlParam }
92
+ }
93
+ };
94
+ }
95
+ }
96
+ return {
97
+ cacheKey: url,
98
+ signingPayload: { url }
99
+ };
100
+ } catch {
101
+ return {
102
+ cacheKey: url,
103
+ signingPayload: { url }
104
+ };
105
+ }
106
+ }
107
+ /**
108
+ * Parse JWT token to extract safe expiration time (with buffer)
109
+ * @param token JWT token string
110
+ * @returns Safe expiration timestamp in milliseconds (actual expiry minus buffer), or 0 if parsing fails
111
+ */
112
+ #parseTokenExpiration(token) {
113
+ try {
114
+ const parts = token.split(".");
115
+ if (parts.length !== 3) return 0;
116
+ const payload = parts[1];
117
+ if (!payload) return 0;
118
+ const decoded = atob(payload.replace(/-/g, "+").replace(/_/g, "/"));
119
+ const parsed = JSON.parse(decoded);
120
+ const exp = parsed.exp;
121
+ const iat = parsed.iat;
122
+ if (!exp) return 0;
123
+ const lifetimeSeconds = iat ? exp - iat : 3600;
124
+ const tenPercentBufferMs = lifetimeSeconds * .1 * 1e3;
125
+ const fiveMinutesMs = 5 * 60 * 1e3;
126
+ const bufferMs = Math.min(fiveMinutesMs, tenPercentBufferMs);
127
+ return exp * 1e3 - bufferMs;
128
+ } catch {
129
+ return 0;
130
+ }
131
+ }
55
132
  #signingURL;
56
133
  /**
57
134
  * A URL that will be used to generated signed tokens for accessing media files from the
@@ -66,10 +143,20 @@ function ContextMixin(superClass) {
66
143
  #FPS = 30;
67
144
  #MS_PER_FRAME = 1e3 / this.#FPS;
68
145
  #timegroupObserver = new MutationObserver((mutations) => {
146
+ let shouldUpdate = false;
69
147
  for (const mutation of mutations) if (mutation.type === "childList") {
70
148
  const newTimegroup = this.querySelector("ef-timegroup");
71
- if (newTimegroup !== this.targetTimegroup) this.targetTimegroup = newTimegroup;
149
+ if (newTimegroup !== this.targetTimegroup) {
150
+ this.targetTimegroup = newTimegroup;
151
+ shouldUpdate = true;
152
+ }
153
+ } else if (mutation.type === "attributes") {
154
+ if (mutation.attributeName === "duration" || mutation.attributeName === "mode" || mutation.target instanceof Element && (mutation.target.tagName === "EF-TIMEGROUP" || mutation.target.closest("ef-timegroup"))) shouldUpdate = true;
72
155
  }
156
+ if (shouldUpdate) queueMicrotask(() => {
157
+ this.requestUpdate();
158
+ if (this.targetTimegroup) this.targetTimegroup.requestUpdate();
159
+ });
73
160
  });
74
161
  connectedCallback() {
75
162
  super.connectedCallback();
@@ -85,6 +172,8 @@ function ContextMixin(superClass) {
85
172
  super.disconnectedCallback();
86
173
  this.#timegroupObserver.disconnect();
87
174
  this.stopPlayback();
175
+ this.#URLTokens = {};
176
+ this.#URLTokenExpirations = {};
88
177
  }
89
178
  update(changedProperties) {
90
179
  if (changedProperties.has("playing")) if (this.playing) this.startPlayback();
@@ -194,6 +283,8 @@ function ContextMixin(superClass) {
194
283
  })], ContextElement.prototype, "apiHost", null);
195
284
  _decorate([provide({ context: efContext })], ContextElement.prototype, "efContext", void 0);
196
285
  _decorate([provide({ context: targetTimegroupContext }), state()], ContextElement.prototype, "targetTimegroup", void 0);
286
+ _decorate([state()], ContextElement.prototype, "durationMs", null);
287
+ _decorate([state()], ContextElement.prototype, "endTimeMs", null);
197
288
  _decorate([provide({ context: fetchContext })], ContextElement.prototype, "fetch", void 0);
198
289
  _decorate([property({
199
290
  type: String,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@editframe/elements",
3
- "version": "0.18.8-beta.0",
3
+ "version": "0.18.20-beta.0",
4
4
  "description": "",
5
5
  "exports": {
6
6
  ".": {
@@ -27,7 +27,7 @@
27
27
  "license": "UNLICENSED",
28
28
  "dependencies": {
29
29
  "@bramus/style-observer": "^1.3.0",
30
- "@editframe/assets": "0.18.8-beta.0",
30
+ "@editframe/assets": "0.18.20-beta.0",
31
31
  "@lit/context": "^1.1.2",
32
32
  "@lit/task": "^1.0.1",
33
33
  "d3": "^7.9.0",
@@ -27,7 +27,16 @@ export class AssetIdMediaEngine
27
27
  private apiHost: string,
28
28
  ) {
29
29
  // Pass assetId as src to parent constructor for compatibility
30
- super(host, assetId, data);
30
+ super(host, assetId);
31
+ // Initialize data after parent constructor
32
+ this.data = data;
33
+
34
+ // Calculate duration from the data
35
+ const longestFragment = Object.values(this.data).reduce(
36
+ (max, fragment) => Math.max(max, fragment.duration / fragment.timescale),
37
+ 0,
38
+ );
39
+ this.durationMs = longestFragment * 1000;
31
40
  }
32
41
 
33
42
  // Override URL-building methods to use API endpoints instead of file paths
@@ -16,28 +16,32 @@ import {
16
16
  } from "./shared/PrecisionUtils";
17
17
 
18
18
  export class AssetMediaEngine extends BaseMediaEngine implements MediaEngine {
19
+ public src: string;
20
+ protected data: Record<number, TrackFragmentIndex> = {};
21
+ durationMs = 0;
22
+
23
+ constructor(host: EFMedia, src: string) {
24
+ super(host);
25
+ this.src = src;
26
+ }
27
+
19
28
  static async fetch(host: EFMedia, urlGenerator: UrlGenerator, src: string) {
29
+ const engine = new AssetMediaEngine(host, src);
20
30
  const url = urlGenerator.generateTrackFragmentIndexUrl(src);
21
- const response = await host.fetch(url);
22
- const data = (await response.json()) as Record<number, TrackFragmentIndex>;
23
- if (src.startsWith("/")) {
24
- src = src.slice(1);
25
- }
26
- return new AssetMediaEngine(host, src, data);
27
- }
28
- durationMs: number;
31
+ const data = await engine.fetchManifest(url);
32
+ engine.data = data as Record<number, TrackFragmentIndex>;
29
33
 
30
- constructor(
31
- public host: EFMedia,
32
- public src: string,
33
- protected data: Record<number, TrackFragmentIndex>,
34
- ) {
35
- super();
36
- const longestFragment = Object.values(data).reduce(
34
+ // Calculate duration from the data
35
+ const longestFragment = Object.values(engine.data).reduce(
37
36
  (max, fragment) => Math.max(max, fragment.duration / fragment.timescale),
38
37
  0,
39
38
  );
40
- this.durationMs = longestFragment * 1000;
39
+ engine.durationMs = longestFragment * 1000;
40
+
41
+ if (src.startsWith("/")) {
42
+ engine.src = src.slice(1);
43
+ }
44
+ return engine;
41
45
  }
42
46
 
43
47
  get audioTrackIndex() {
@@ -113,15 +117,15 @@ export class AssetMediaEngine extends BaseMediaEngine implements MediaEngine {
113
117
  throw new Error("Init segment not found");
114
118
  }
115
119
 
116
- // Use shared caching mechanism with Range headers - same optimization as JitMediaEngine
120
+ // Use unified fetch method with Range headers
117
121
  const headers = {
118
122
  Range: `bytes=${initSegment.offset}-${initSegment.offset + initSegment.size - 1}`,
119
123
  };
120
124
 
121
- return this.fetchMediaCacheWithHeaders(url, headers, signal);
125
+ return this.fetchMediaWithHeaders(url, headers, signal);
122
126
  }
123
127
 
124
- async fetchMediaSegmentImpl(
128
+ async fetchMediaSegment(
125
129
  segmentId: number,
126
130
  rendition: { trackId: number | undefined; src: string },
127
131
  signal?: AbortSignal,
@@ -138,12 +142,12 @@ export class AssetMediaEngine extends BaseMediaEngine implements MediaEngine {
138
142
  throw new Error("Media segment not found");
139
143
  }
140
144
 
141
- // Use shared caching mechanism with Range headers - same optimization as JitMediaEngine
145
+ // Use unified fetch method with Range headers
142
146
  const headers = {
143
147
  Range: `bytes=${mediaSegment.offset}-${mediaSegment.offset + mediaSegment.size - 1}`,
144
148
  };
145
149
 
146
- return this.fetchMediaCacheWithHeaders(url, headers, signal);
150
+ return this.fetchMediaWithHeaders(url, headers, signal);
147
151
  }
148
152
 
149
153
  /**
@@ -0,0 +1,311 @@
1
+ import { describe, vi } from "vitest";
2
+ import { test as baseTest } from "../../../test/useMSW.js";
3
+
4
+ import type { EFMedia } from "../EFMedia.js";
5
+ import { BaseMediaEngine, mediaCache } from "./BaseMediaEngine.js";
6
+
7
+ const test = baseTest.extend<{}>({});
8
+
9
+ // Test implementation of BaseMediaEngine for testing
10
+ class TestMediaEngine extends BaseMediaEngine {
11
+ fetchMediaSegment = vi.fn();
12
+ public host: EFMedia;
13
+
14
+ constructor(host: EFMedia) {
15
+ super(host);
16
+ this.host = host;
17
+ }
18
+
19
+ get videoRendition() {
20
+ return {
21
+ trackId: 1,
22
+ src: "test-video.mp4",
23
+ segmentDurationMs: 2000,
24
+ };
25
+ }
26
+
27
+ get audioRendition() {
28
+ return {
29
+ trackId: 2,
30
+ src: "test-audio.mp4",
31
+ segmentDurationMs: 1000,
32
+ };
33
+ }
34
+ }
35
+
36
+ describe("BaseMediaEngine deduplication", () => {
37
+ test("should fetch segment successfully", async ({ expect }) => {
38
+ const host = document.createElement("ef-video") as EFMedia;
39
+ const engine = new TestMediaEngine(host);
40
+ engine.fetchMediaSegment.mockResolvedValue(new ArrayBuffer(1024));
41
+
42
+ const rendition = { trackId: 1, src: "test.mp4" };
43
+ const result = await engine.fetchMediaSegment(1, rendition);
44
+
45
+ expect(result).toEqual(new ArrayBuffer(1024));
46
+ expect(engine.fetchMediaSegment).toHaveBeenCalledWith(1, rendition);
47
+ expect(engine.fetchMediaSegment).toHaveBeenCalledTimes(1);
48
+ });
49
+
50
+ test("should deduplicate concurrent requests for same segment", async ({
51
+ expect,
52
+ }) => {
53
+ const host = document.createElement("ef-video") as EFMedia;
54
+ const engine = new TestMediaEngine(host);
55
+ const mockSegmentData = new ArrayBuffer(1024);
56
+ engine.fetchMediaSegment.mockResolvedValue(mockSegmentData);
57
+
58
+ const rendition = { trackId: 1, src: "test.mp4" };
59
+
60
+ // Make two concurrent requests for the same segment
61
+ const [result1, result2] = await Promise.all([
62
+ engine.fetchMediaSegmentWithDeduplication(1, rendition),
63
+ engine.fetchMediaSegmentWithDeduplication(1, rendition),
64
+ ]);
65
+
66
+ // Both should return the same result
67
+ expect(result1).toBe(mockSegmentData);
68
+ expect(result2).toBe(mockSegmentData);
69
+
70
+ // But fetchMediaSegment should only be called once due to deduplication
71
+ expect(engine.fetchMediaSegment).toHaveBeenCalledTimes(1);
72
+ expect(engine.fetchMediaSegment).toHaveBeenCalledWith(1, rendition);
73
+ });
74
+
75
+ test("should handle different segments as separate requests", async ({
76
+ expect,
77
+ }) => {
78
+ const host = document.createElement("ef-video") as EFMedia;
79
+ const engine = new TestMediaEngine(host);
80
+ const mockSegmentData = new ArrayBuffer(1024);
81
+ engine.fetchMediaSegment.mockResolvedValue(mockSegmentData);
82
+
83
+ const rendition = { trackId: 1, src: "test.mp4" };
84
+
85
+ // Make concurrent requests for different segments
86
+ const [result1, result2] = await Promise.all([
87
+ engine.fetchMediaSegmentWithDeduplication(1, rendition),
88
+ engine.fetchMediaSegmentWithDeduplication(2, rendition),
89
+ ]);
90
+
91
+ expect(result1).toBe(mockSegmentData);
92
+ expect(result2).toBe(mockSegmentData);
93
+
94
+ // Should call fetchMediaSegment twice for different segments
95
+ expect(engine.fetchMediaSegment).toHaveBeenCalledTimes(2);
96
+ expect(engine.fetchMediaSegment).toHaveBeenCalledWith(1, rendition);
97
+ expect(engine.fetchMediaSegment).toHaveBeenCalledWith(2, rendition);
98
+ });
99
+
100
+ test("should handle different renditions as separate requests", async ({
101
+ expect,
102
+ }) => {
103
+ const host = document.createElement("ef-video") as EFMedia;
104
+ const engine = new TestMediaEngine(host);
105
+ const mockSegmentData = new ArrayBuffer(1024);
106
+ engine.fetchMediaSegment.mockResolvedValue(mockSegmentData);
107
+
108
+ const rendition1 = { trackId: 1, src: "test1.mp4" };
109
+ const rendition2 = { trackId: 2, src: "test2.mp4" };
110
+
111
+ // Make concurrent requests for same segment but different renditions
112
+ const [result1, result2] = await Promise.all([
113
+ engine.fetchMediaSegmentWithDeduplication(1, rendition1),
114
+ engine.fetchMediaSegmentWithDeduplication(1, rendition2),
115
+ ]);
116
+
117
+ expect(result1).toBe(mockSegmentData);
118
+ expect(result2).toBe(mockSegmentData);
119
+
120
+ // Should call fetchMediaSegment twice for different renditions
121
+ expect(engine.fetchMediaSegment).toHaveBeenCalledTimes(2);
122
+ expect(engine.fetchMediaSegment).toHaveBeenCalledWith(1, rendition1);
123
+ expect(engine.fetchMediaSegment).toHaveBeenCalledWith(1, rendition2);
124
+ });
125
+
126
+ test("should propagate errors correctly", async ({ expect }) => {
127
+ const host = document.createElement("ef-video") as EFMedia;
128
+ const engine = new TestMediaEngine(host);
129
+ const error = new Error("Fetch failed");
130
+ engine.fetchMediaSegment.mockRejectedValue(error);
131
+
132
+ const rendition = { trackId: 1, src: "test.mp4" };
133
+
134
+ await expect(
135
+ engine.fetchMediaSegmentWithDeduplication(1, rendition),
136
+ ).rejects.toThrow("Fetch failed");
137
+ expect(engine.fetchMediaSegment).toHaveBeenCalledWith(1, rendition);
138
+ });
139
+
140
+ test("should retry failed requests after error", async ({ expect }) => {
141
+ const host = document.createElement("ef-video") as EFMedia;
142
+ const engine = new TestMediaEngine(host);
143
+ const rendition = { trackId: 1, src: "test.mp4" };
144
+ const error = new Error("First attempt failed");
145
+ const mockSegmentData = new ArrayBuffer(1024);
146
+
147
+ // First request fails
148
+ engine.fetchMediaSegment.mockRejectedValueOnce(error);
149
+ await expect(
150
+ engine.fetchMediaSegmentWithDeduplication(1, rendition),
151
+ ).rejects.toThrow("First attempt failed");
152
+
153
+ // Second request should succeed (not deduplicated since first failed)
154
+ engine.fetchMediaSegment.mockResolvedValue(mockSegmentData);
155
+ const result = await engine.fetchMediaSegmentWithDeduplication(
156
+ 1,
157
+ rendition,
158
+ );
159
+
160
+ expect(result).toBe(mockSegmentData);
161
+ expect(engine.fetchMediaSegment).toHaveBeenCalledTimes(2);
162
+ });
163
+
164
+ test("should track pending requests correctly", async ({ expect }) => {
165
+ const host = document.createElement("ef-video") as EFMedia;
166
+ const engine = new TestMediaEngine(host);
167
+ const mockSegmentData = new ArrayBuffer(1024);
168
+ engine.fetchMediaSegment.mockResolvedValue(mockSegmentData);
169
+
170
+ const rendition = { trackId: 1, src: "test.mp4" };
171
+
172
+ // Start a request but don't await it
173
+ const promise = engine.fetchMediaSegmentWithDeduplication(1, rendition);
174
+
175
+ // Should detect that segment is being fetched
176
+ expect(engine.isSegmentBeingFetched(1, rendition)).toBe(true);
177
+ expect(engine.getActiveSegmentRequestCount()).toBe(1);
178
+
179
+ // Different segment should not be detected as being fetched
180
+ expect(engine.isSegmentBeingFetched(2, rendition)).toBe(false);
181
+
182
+ await promise.then(() => {
183
+ // After completion, should no longer be detected as being fetched
184
+ expect(engine.isSegmentBeingFetched(1, rendition)).toBe(false);
185
+ expect(engine.getActiveSegmentRequestCount()).toBe(0);
186
+ });
187
+ });
188
+
189
+ test("should cancel all requests correctly", async ({ expect }) => {
190
+ const host = document.createElement("ef-video") as EFMedia;
191
+ const engine = new TestMediaEngine(host);
192
+ const rendition = { trackId: 1, src: "test.mp4" };
193
+
194
+ // Start a request
195
+ engine.fetchMediaSegmentWithDeduplication(1, rendition);
196
+ expect(engine.getActiveSegmentRequestCount()).toBe(1);
197
+
198
+ // Cancel all requests
199
+ engine.cancelAllSegmentRequests();
200
+ expect(engine.getActiveSegmentRequestCount()).toBe(0);
201
+ });
202
+ });
203
+
204
+ describe("BaseMediaEngine caching", () => {
205
+ test("should use shared media cache", async ({ expect }) => {
206
+ // Test that the cache is shared across instances
207
+ expect(mediaCache).toBe(mediaCache);
208
+ });
209
+
210
+ test("should have cache size limit", async ({ expect }) => {
211
+ // Test that the cache has the expected size limit
212
+ expect(mediaCache.maxSize).toBe(100 * 1024 * 1024);
213
+ });
214
+ });
215
+
216
+ describe("BaseMediaEngine abort signal handling", () => {
217
+ test("should handle abort signals independently in BaseMediaEngine", async ({
218
+ expect,
219
+ }) => {
220
+ // Create a test host that actually has a fetch method
221
+ const host = {
222
+ fetch: vi
223
+ .fn()
224
+ .mockImplementation(
225
+ () =>
226
+ new Promise((resolve) =>
227
+ setTimeout(
228
+ () => resolve({ arrayBuffer: () => new ArrayBuffer(1024) }),
229
+ 100,
230
+ ),
231
+ ),
232
+ ),
233
+ } as any;
234
+
235
+ const engine = new TestMediaEngine(host);
236
+
237
+ // Create two abort controllers
238
+ const controller1 = new AbortController();
239
+ const controller2 = new AbortController();
240
+
241
+ // Start two requests with different abort signals to the same URL
242
+ const promise1 = engine.fetchMedia("test-url", controller1.signal);
243
+ const promise2 = engine.fetchMedia("test-url", controller2.signal);
244
+
245
+ // Abort only the first request
246
+ controller1.abort();
247
+
248
+ // First request should fail with AbortError
249
+ await expect(promise1).rejects.toThrow("Aborted");
250
+
251
+ // Second request should still succeed
252
+ const result2 = await promise2;
253
+ expect(result2).toBeInstanceOf(ArrayBuffer);
254
+ expect(result2.byteLength).toBe(1024);
255
+
256
+ // The network request should only be made once due to deduplication
257
+ // This validates our fix: deduplication works but signals are independent
258
+ expect(host.fetch).toHaveBeenCalledTimes(1);
259
+ });
260
+
261
+ test("should handle immediate abort in BaseMediaEngine", async ({
262
+ expect,
263
+ }) => {
264
+ const host = {
265
+ fetch: vi
266
+ .fn()
267
+ .mockResolvedValue({ arrayBuffer: () => new ArrayBuffer(1024) }),
268
+ } as any;
269
+
270
+ const engine = new TestMediaEngine(host);
271
+
272
+ // Create an already aborted signal
273
+ const controller = new AbortController();
274
+ controller.abort();
275
+
276
+ // Request should fail immediately with AbortError
277
+ await expect(
278
+ engine.fetchMedia("test-url", controller.signal),
279
+ ).rejects.toThrow("Aborted");
280
+
281
+ // No network request should be made since abort happens in wrapper method
282
+ expect(host.fetch).not.toHaveBeenCalled();
283
+ });
284
+
285
+ test("should maintain deduplication while respecting individual abort signals", async ({
286
+ expect,
287
+ }) => {
288
+ const host = {
289
+ fetch: vi
290
+ .fn()
291
+ .mockResolvedValue({ arrayBuffer: () => new ArrayBuffer(1024) }),
292
+ } as any;
293
+
294
+ const engine = new TestMediaEngine(host);
295
+
296
+ // Clear any existing cache to ensure clean test
297
+ mediaCache.clear();
298
+
299
+ // Make two requests without signals
300
+ const promise1 = engine.fetchMedia("test-url");
301
+ const promise2 = engine.fetchMedia("test-url");
302
+
303
+ // Both should succeed
304
+ const [result1, result2] = await Promise.all([promise1, promise2]);
305
+ expect(result1).toBeInstanceOf(ArrayBuffer);
306
+ expect(result2).toBeInstanceOf(ArrayBuffer);
307
+
308
+ // Should deduplicate to one network request
309
+ expect(host.fetch).toHaveBeenCalledTimes(1);
310
+ });
311
+ });