@twick/media-utils 0.15.0 → 0.15.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -5,10 +5,12 @@ import { Dimensions } from './types';
5
5
  import { downloadFile } from './file-helper';
6
6
  import { extractAudio } from './audio-utils';
7
7
  import { getAudioDuration } from './get-audio-duration';
8
+ import { getDefaultVideoFrameExtractor } from './video-frame-extractor';
8
9
  import { getImageDimensions } from './get-image-dimensions';
9
10
  import { getObjectFitSize } from './dimension-handler';
10
11
  import { getScaledDimensions } from './dimension-handler';
11
12
  import { getThumbnail } from './get-thumbnail';
13
+ import { getThumbnailCached } from './video-frame-extractor';
12
14
  import { getVideoMeta } from './get-video-metadata';
13
15
  import { hasAudio } from './audio-utils';
14
16
  import { limit } from './limit';
@@ -16,6 +18,8 @@ import { loadFile } from './file-helper';
16
18
  import { Position } from './types';
17
19
  import { saveAsFile } from './file-helper';
18
20
  import { stitchAudio } from './audio-utils';
21
+ import { VideoFrameExtractor } from './video-frame-extractor';
22
+ import { VideoFrameExtractorOptions } from './video-frame-extractor';
19
23
  import { VideoMeta } from './types';
20
24
 
21
25
  export { AudioSegment }
@@ -32,6 +36,8 @@ export { extractAudio }
32
36
 
33
37
  export { getAudioDuration }
34
38
 
39
+ export { getDefaultVideoFrameExtractor }
40
+
35
41
  export { getImageDimensions }
36
42
 
37
43
  export { getObjectFitSize }
@@ -40,6 +46,8 @@ export { getScaledDimensions }
40
46
 
41
47
  export { getThumbnail }
42
48
 
49
+ export { getThumbnailCached }
50
+
43
51
  export { getVideoMeta }
44
52
 
45
53
  export { hasAudio }
@@ -54,6 +62,10 @@ export { saveAsFile }
54
62
 
55
63
  export { stitchAudio }
56
64
 
65
+ export { VideoFrameExtractor }
66
+
67
+ export { VideoFrameExtractorOptions }
68
+
57
69
  export { VideoMeta }
58
70
 
59
71
  export { }
package/dist/index.js CHANGED
@@ -86,36 +86,258 @@ const getVideoMeta = (videoSrc) => {
86
86
  return Promise.resolve(videoMetaCache[videoSrc]);
87
87
  }
88
88
  return new Promise((resolve, reject) => {
89
- const video = document.createElement("video");
90
- video.preload = "metadata";
91
89
  const isSafeUrl = /^(https?:|blob:|data:video\/)/i.test(videoSrc);
92
90
  if (!isSafeUrl) {
93
91
  reject(new Error("Unsafe video source URL"));
94
92
  return;
95
93
  }
96
- video.src = videoSrc;
97
- video.onloadedmetadata = () => {
98
- const meta = {
99
- width: video.videoWidth,
100
- height: video.videoHeight,
101
- duration: video.duration
94
+ const tryLoadVideo = (useCors) => {
95
+ const video = document.createElement("video");
96
+ video.preload = "metadata";
97
+ video.crossOrigin = useCors ? "anonymous" : null;
98
+ video.src = videoSrc;
99
+ video.onloadedmetadata = () => {
100
+ const meta = {
101
+ width: video.videoWidth,
102
+ height: video.videoHeight,
103
+ duration: video.duration
104
+ };
105
+ videoMetaCache[videoSrc] = meta;
106
+ resolve(meta);
107
+ };
108
+ video.onerror = () => {
109
+ if (useCors) {
110
+ video.src = "";
111
+ tryLoadVideo(false);
112
+ } else {
113
+ reject(new Error("Failed to load video metadata. This may be due to CORS restrictions or an invalid video URL."));
114
+ }
102
115
  };
103
- videoMetaCache[videoSrc] = meta;
104
- resolve(meta);
105
116
  };
106
- video.onerror = () => reject(new Error("Failed to load video metadata"));
117
+ tryLoadVideo(true);
107
118
  });
108
119
  };
109
120
 
110
121
  const getThumbnail = async (videoUrl, seekTime = 0.1, playbackRate = 1) => {
111
122
  return new Promise((resolve, reject) => {
123
+ const tryLoadThumbnail = (useCors) => {
124
+ const video = document.createElement("video");
125
+ video.crossOrigin = useCors ? "anonymous" : null;
126
+ video.muted = true;
127
+ video.playsInline = true;
128
+ video.autoplay = false;
129
+ video.preload = "auto";
130
+ video.playbackRate = playbackRate;
131
+ video.style.position = "absolute";
132
+ video.style.left = "-9999px";
133
+ video.style.top = "-9999px";
134
+ video.style.width = "1px";
135
+ video.style.height = "1px";
136
+ video.style.opacity = "0";
137
+ video.style.pointerEvents = "none";
138
+ video.style.zIndex = "-1";
139
+ let timeoutId;
140
+ const cleanup = () => {
141
+ if (video.parentNode) video.remove();
142
+ if (timeoutId) clearTimeout(timeoutId);
143
+ };
144
+ const handleError = () => {
145
+ cleanup();
146
+ if (useCors) {
147
+ tryLoadThumbnail(false);
148
+ } else {
149
+ reject(new Error(`Failed to load video: ${video.error?.message || "Unknown error. This may be due to CORS restrictions or an invalid video URL."}`));
150
+ }
151
+ };
152
+ const handleSeeked = () => {
153
+ try {
154
+ video.pause();
155
+ const canvas = document.createElement("canvas");
156
+ const width = video.videoWidth || 640;
157
+ const height = video.videoHeight || 360;
158
+ canvas.width = width;
159
+ canvas.height = height;
160
+ const ctx = canvas.getContext("2d");
161
+ if (!ctx) {
162
+ cleanup();
163
+ reject(new Error("Failed to get canvas context"));
164
+ return;
165
+ }
166
+ ctx.drawImage(video, 0, 0, width, height);
167
+ try {
168
+ const dataUrl = canvas.toDataURL("image/jpeg", 0.8);
169
+ cleanup();
170
+ resolve(dataUrl);
171
+ } catch {
172
+ canvas.toBlob((blob) => {
173
+ if (!blob) {
174
+ cleanup();
175
+ reject(new Error("Failed to create Blob"));
176
+ return;
177
+ }
178
+ const blobUrl = URL.createObjectURL(blob);
179
+ cleanup();
180
+ resolve(blobUrl);
181
+ }, "image/jpeg", 0.8);
182
+ }
183
+ } catch (err) {
184
+ cleanup();
185
+ reject(new Error(`Error creating thumbnail: ${err}`));
186
+ }
187
+ };
188
+ video.addEventListener("error", handleError, { once: true });
189
+ video.addEventListener("seeked", handleSeeked, { once: true });
190
+ video.addEventListener("loadedmetadata", () => {
191
+ const playPromise = video.play();
192
+ if (playPromise !== void 0) {
193
+ playPromise.then(() => {
194
+ video.currentTime = seekTime;
195
+ }).catch(() => {
196
+ video.currentTime = seekTime;
197
+ });
198
+ } else {
199
+ video.currentTime = seekTime;
200
+ }
201
+ }, { once: true });
202
+ timeoutId = window.setTimeout(() => {
203
+ cleanup();
204
+ reject(new Error("Video loading timed out"));
205
+ }, 15e3);
206
+ video.src = videoUrl;
207
+ document.body.appendChild(video);
208
+ };
209
+ tryLoadThumbnail(true);
210
+ });
211
+ };
212
+
213
+ class LRUCache {
214
+ constructor(maxSize = 100) {
215
+ if (maxSize <= 0) {
216
+ throw new Error("maxSize must be greater than 0");
217
+ }
218
+ this.maxSize = maxSize;
219
+ this.cache = /* @__PURE__ */ new Map();
220
+ }
221
+ /**
222
+ * Get a value from the cache.
223
+ * Moves the item to the end (most recently used).
224
+ */
225
+ get(key) {
226
+ const value = this.cache.get(key);
227
+ if (value === void 0) {
228
+ return void 0;
229
+ }
230
+ this.cache.delete(key);
231
+ this.cache.set(key, value);
232
+ return value;
233
+ }
234
+ /**
235
+ * Set a value in the cache.
236
+ * If cache is full, removes the least recently used item.
237
+ */
238
+ set(key, value) {
239
+ if (this.cache.has(key)) {
240
+ this.cache.delete(key);
241
+ } else if (this.cache.size >= this.maxSize) {
242
+ const firstKey = this.cache.keys().next().value;
243
+ if (firstKey !== void 0) {
244
+ this.cache.delete(firstKey);
245
+ }
246
+ }
247
+ this.cache.set(key, value);
248
+ }
249
+ /**
250
+ * Check if a key exists in the cache.
251
+ */
252
+ has(key) {
253
+ return this.cache.has(key);
254
+ }
255
+ /**
256
+ * Delete a key from the cache.
257
+ */
258
+ delete(key) {
259
+ return this.cache.delete(key);
260
+ }
261
+ /**
262
+ * Clear all entries from the cache.
263
+ */
264
+ clear() {
265
+ this.cache.clear();
266
+ }
267
+ /**
268
+ * Get the current size of the cache.
269
+ */
270
+ get size() {
271
+ return this.cache.size;
272
+ }
273
+ }
274
+
275
+ class VideoFrameExtractor {
276
+ constructor(options = {}) {
277
+ this.frameCache = new LRUCache(
278
+ options.maxCacheSize ?? 50
279
+ );
280
+ this.videoElements = /* @__PURE__ */ new Map();
281
+ this.maxVideoElements = options.maxVideoElements ?? 5;
282
+ this.loadTimeout = options.loadTimeout ?? 15e3;
283
+ this.jpegQuality = options.jpegQuality ?? 0.8;
284
+ this.playbackRate = options.playbackRate ?? 1;
285
+ }
286
+ /**
287
+ * Get a frame thumbnail from a video at a specific time.
288
+ * Uses caching and reuses video elements for optimal performance.
289
+ *
290
+ * @param videoUrl - The URL of the video
291
+ * @param seekTime - The time in seconds to extract the frame
292
+ * @returns Promise resolving to a thumbnail image URL (data URL or blob URL)
293
+ */
294
+ async getFrame(videoUrl, seekTime = 0.1) {
295
+ const cacheKey = this.getCacheKey(videoUrl, seekTime);
296
+ const cached = this.frameCache.get(cacheKey);
297
+ if (cached) {
298
+ return cached;
299
+ }
300
+ const videoState = await this.getVideoElement(videoUrl);
301
+ const thumbnail = await this.extractFrame(videoState.video, seekTime);
302
+ this.frameCache.set(cacheKey, thumbnail);
303
+ return thumbnail;
304
+ }
305
+ /**
306
+ * Get or create a video element for the given URL.
307
+ * Reuses existing elements and manages cleanup.
308
+ */
309
+ async getVideoElement(videoUrl) {
310
+ let videoState = this.videoElements.get(videoUrl);
311
+ if (videoState && videoState.isReady) {
312
+ videoState.lastUsed = Date.now();
313
+ return videoState;
314
+ }
315
+ if (videoState && videoState.isLoading && videoState.loadPromise) {
316
+ await videoState.loadPromise;
317
+ if (videoState.isReady) {
318
+ videoState.lastUsed = Date.now();
319
+ return videoState;
320
+ }
321
+ }
322
+ if (this.videoElements.size >= this.maxVideoElements) {
323
+ this.cleanupOldVideoElements();
324
+ }
325
+ videoState = await this.createVideoElement(videoUrl);
326
+ this.videoElements.set(videoUrl, videoState);
327
+ videoState.lastUsed = Date.now();
328
+ return videoState;
329
+ }
330
+ /**
331
+ * Create and initialize a new video element.
332
+ */
333
+ async createVideoElement(videoUrl) {
112
334
  const video = document.createElement("video");
113
335
  video.crossOrigin = "anonymous";
114
336
  video.muted = true;
115
337
  video.playsInline = true;
116
338
  video.autoplay = false;
117
339
  video.preload = "auto";
118
- video.playbackRate = playbackRate;
340
+ video.playbackRate = this.playbackRate;
119
341
  video.style.position = "absolute";
120
342
  video.style.left = "-9999px";
121
343
  video.style.top = "-9999px";
@@ -124,54 +346,127 @@ const getThumbnail = async (videoUrl, seekTime = 0.1, playbackRate = 1) => {
124
346
  video.style.opacity = "0";
125
347
  video.style.pointerEvents = "none";
126
348
  video.style.zIndex = "-1";
127
- let timeoutId;
128
- const cleanup = () => {
129
- if (video.parentNode) video.remove();
130
- if (timeoutId) clearTimeout(timeoutId);
349
+ const state = {
350
+ video,
351
+ isReady: false,
352
+ isLoading: true,
353
+ loadPromise: null,
354
+ lastUsed: Date.now()
131
355
  };
132
- const handleError = () => {
133
- cleanup();
134
- reject(new Error(`Failed to load video: ${video.error?.message || "Unknown error"}`));
135
- };
136
- const handleSeeked = () => {
137
- try {
138
- video.pause();
139
- const canvas = document.createElement("canvas");
140
- const width = video.videoWidth || 640;
141
- const height = video.videoHeight || 360;
142
- canvas.width = width;
143
- canvas.height = height;
144
- const ctx = canvas.getContext("2d");
145
- if (!ctx) {
146
- cleanup();
147
- reject(new Error("Failed to get canvas context"));
356
+ state.loadPromise = new Promise((resolve, reject) => {
357
+ let timeoutId;
358
+ const cleanup = () => {
359
+ if (timeoutId) clearTimeout(timeoutId);
360
+ };
361
+ const handleError = () => {
362
+ cleanup();
363
+ state.isLoading = false;
364
+ reject(new Error(`Failed to load video: ${video.error?.message || "Unknown error"}`));
365
+ };
366
+ const handleLoadedMetadata = () => {
367
+ cleanup();
368
+ state.isReady = true;
369
+ state.isLoading = false;
370
+ resolve();
371
+ };
372
+ video.addEventListener("error", handleError, { once: true });
373
+ video.addEventListener("loadedmetadata", handleLoadedMetadata, { once: true });
374
+ timeoutId = window.setTimeout(() => {
375
+ cleanup();
376
+ state.isLoading = false;
377
+ reject(new Error("Video loading timed out"));
378
+ }, this.loadTimeout);
379
+ video.src = videoUrl;
380
+ document.body.appendChild(video);
381
+ });
382
+ try {
383
+ await state.loadPromise;
384
+ } catch (error) {
385
+ if (video.parentNode) {
386
+ video.remove();
387
+ }
388
+ throw error;
389
+ }
390
+ return state;
391
+ }
392
+ /**
393
+ * Extract a frame from a video at the specified time.
394
+ */
395
+ async extractFrame(video, seekTime) {
396
+ return new Promise((resolve, reject) => {
397
+ video.pause();
398
+ const timeThreshold = 0.1;
399
+ if (Math.abs(video.currentTime - seekTime) < timeThreshold) {
400
+ try {
401
+ const canvas = document.createElement("canvas");
402
+ const width = video.videoWidth || 640;
403
+ const height = video.videoHeight || 360;
404
+ canvas.width = width;
405
+ canvas.height = height;
406
+ const ctx = canvas.getContext("2d");
407
+ if (!ctx) {
408
+ reject(new Error("Failed to get canvas context"));
409
+ return;
410
+ }
411
+ ctx.drawImage(video, 0, 0, width, height);
412
+ try {
413
+ const dataUrl = canvas.toDataURL("image/jpeg", this.jpegQuality);
414
+ resolve(dataUrl);
415
+ } catch {
416
+ canvas.toBlob(
417
+ (blob) => {
418
+ if (!blob) {
419
+ reject(new Error("Failed to create Blob"));
420
+ return;
421
+ }
422
+ const blobUrl = URL.createObjectURL(blob);
423
+ resolve(blobUrl);
424
+ },
425
+ "image/jpeg",
426
+ this.jpegQuality
427
+ );
428
+ }
429
+ return;
430
+ } catch (err) {
431
+ reject(new Error(`Error creating thumbnail: ${err}`));
148
432
  return;
149
433
  }
150
- ctx.drawImage(video, 0, 0, width, height);
434
+ }
435
+ const handleSeeked = () => {
151
436
  try {
152
- const dataUrl = canvas.toDataURL("image/jpeg", 0.8);
153
- cleanup();
154
- resolve(dataUrl);
155
- } catch {
156
- canvas.toBlob((blob) => {
157
- if (!blob) {
158
- cleanup();
159
- reject(new Error("Failed to create Blob"));
160
- return;
161
- }
162
- const blobUrl = URL.createObjectURL(blob);
163
- cleanup();
164
- resolve(blobUrl);
165
- }, "image/jpeg", 0.8);
437
+ const canvas = document.createElement("canvas");
438
+ const width = video.videoWidth || 640;
439
+ const height = video.videoHeight || 360;
440
+ canvas.width = width;
441
+ canvas.height = height;
442
+ const ctx = canvas.getContext("2d");
443
+ if (!ctx) {
444
+ reject(new Error("Failed to get canvas context"));
445
+ return;
446
+ }
447
+ ctx.drawImage(video, 0, 0, width, height);
448
+ try {
449
+ const dataUrl = canvas.toDataURL("image/jpeg", this.jpegQuality);
450
+ resolve(dataUrl);
451
+ } catch {
452
+ canvas.toBlob(
453
+ (blob) => {
454
+ if (!blob) {
455
+ reject(new Error("Failed to create Blob"));
456
+ return;
457
+ }
458
+ const blobUrl = URL.createObjectURL(blob);
459
+ resolve(blobUrl);
460
+ },
461
+ "image/jpeg",
462
+ this.jpegQuality
463
+ );
464
+ }
465
+ } catch (err) {
466
+ reject(new Error(`Error creating thumbnail: ${err}`));
166
467
  }
167
- } catch (err) {
168
- cleanup();
169
- reject(new Error(`Error creating thumbnail: ${err}`));
170
- }
171
- };
172
- video.addEventListener("error", handleError, { once: true });
173
- video.addEventListener("seeked", handleSeeked, { once: true });
174
- video.addEventListener("loadedmetadata", () => {
468
+ };
469
+ video.addEventListener("seeked", handleSeeked, { once: true });
175
470
  const playPromise = video.play();
176
471
  if (playPromise !== void 0) {
177
472
  playPromise.then(() => {
@@ -182,15 +477,80 @@ const getThumbnail = async (videoUrl, seekTime = 0.1, playbackRate = 1) => {
182
477
  } else {
183
478
  video.currentTime = seekTime;
184
479
  }
185
- }, { once: true });
186
- timeoutId = window.setTimeout(() => {
187
- cleanup();
188
- reject(new Error("Video loading timed out"));
189
- }, 15e3);
190
- video.src = videoUrl;
191
- document.body.appendChild(video);
192
- });
193
- };
480
+ });
481
+ }
482
+ /**
483
+ * Generate cache key for a video URL and seek time.
484
+ */
485
+ getCacheKey(videoUrl, seekTime) {
486
+ const roundedTime = Math.round(seekTime * 100) / 100;
487
+ return `${videoUrl}:${roundedTime}`;
488
+ }
489
+ /**
490
+ * Cleanup least recently used video elements.
491
+ */
492
+ cleanupOldVideoElements() {
493
+ if (this.videoElements.size < this.maxVideoElements) {
494
+ return;
495
+ }
496
+ const entries = Array.from(this.videoElements.entries());
497
+ entries.sort((a, b) => a[1].lastUsed - b[1].lastUsed);
498
+ const toRemove = entries.slice(0, entries.length - this.maxVideoElements + 1);
499
+ for (const [url, state] of toRemove) {
500
+ if (state.video.parentNode) {
501
+ state.video.remove();
502
+ }
503
+ this.videoElements.delete(url);
504
+ }
505
+ }
506
+ /**
507
+ * Clear the frame cache.
508
+ */
509
+ clearCache() {
510
+ this.frameCache.clear();
511
+ }
512
+ /**
513
+ * Remove a specific video element and clear its cached frames.
514
+ */
515
+ removeVideo(videoUrl) {
516
+ const state = this.videoElements.get(videoUrl);
517
+ if (state) {
518
+ if (state.video.parentNode) {
519
+ state.video.remove();
520
+ }
521
+ this.videoElements.delete(videoUrl);
522
+ }
523
+ this.frameCache.clear();
524
+ }
525
+ /**
526
+ * Dispose of all video elements and clear caches.
527
+ * Removes all video elements from the DOM and clears both the frame cache
528
+ * and video element cache. Call this when the extractor is no longer needed
529
+ * to prevent memory leaks.
530
+ */
531
+ dispose() {
532
+ for (const state of this.videoElements.values()) {
533
+ if (state.video.parentNode) {
534
+ state.video.remove();
535
+ }
536
+ }
537
+ this.videoElements.clear();
538
+ this.frameCache.clear();
539
+ }
540
+ }
541
+ let defaultExtractor = null;
542
+ function getDefaultVideoFrameExtractor(options) {
543
+ if (!defaultExtractor) {
544
+ defaultExtractor = new VideoFrameExtractor(options);
545
+ }
546
+ return defaultExtractor;
547
+ }
548
+ async function getThumbnailCached(videoUrl, seekTime = 0.1, playbackRate) {
549
+ const extractor = getDefaultVideoFrameExtractor(
550
+ playbackRate !== void 0 ? { playbackRate } : void 0
551
+ );
552
+ return extractor.getFrame(videoUrl, seekTime);
553
+ }
194
554
 
195
555
  const extractAudio = async ({
196
556
  src,
@@ -609,15 +969,18 @@ const detectMediaTypeFromUrl = async (url) => {
609
969
  }
610
970
  };
611
971
 
972
+ exports.VideoFrameExtractor = VideoFrameExtractor;
612
973
  exports.blobUrlToFile = blobUrlToFile;
613
974
  exports.detectMediaTypeFromUrl = detectMediaTypeFromUrl;
614
975
  exports.downloadFile = downloadFile;
615
976
  exports.extractAudio = extractAudio;
616
977
  exports.getAudioDuration = getAudioDuration;
978
+ exports.getDefaultVideoFrameExtractor = getDefaultVideoFrameExtractor;
617
979
  exports.getImageDimensions = getImageDimensions;
618
980
  exports.getObjectFitSize = getObjectFitSize;
619
981
  exports.getScaledDimensions = getScaledDimensions;
620
982
  exports.getThumbnail = getThumbnail;
983
+ exports.getThumbnailCached = getThumbnailCached;
621
984
  exports.getVideoMeta = getVideoMeta;
622
985
  exports.hasAudio = hasAudio;
623
986
  exports.limit = limit;