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