Skip to content

Commit

Permalink
fix: logic interruptions caused by video cors errors
Browse files Browse the repository at this point in the history
  • Loading branch information
qq15725 committed Feb 22, 2023
1 parent 3c473d5 commit 2bb1c3f
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 4 deletions.
9 changes: 8 additions & 1 deletion src/clone-video.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,13 @@ export async function cloneVideo<T extends HTMLVideoElement>(
// video to canvas
const ownerDocument = clone.ownerDocument
if (ownerDocument) {
await loadMedia(clone)
let canPlay = true
await loadMedia(clone, {
onError: () => canPlay = false,
})
if (!canPlay) {
return clone
}
clone.currentTime = video.currentTime
await new Promise(resolve => {
clone.addEventListener('seeked', resolve, { once: true })
Expand All @@ -36,6 +42,7 @@ export async function cloneVideo<T extends HTMLVideoElement>(
if (ctx) ctx.drawImage(clone, 0, 0, canvas.width, canvas.height)
} catch (error) {
consoleWarn('Failed to clone video', error)
return clone
}
return cloneCanvas(canvas)
}
Expand Down
8 changes: 5 additions & 3 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -161,13 +161,14 @@ type Media = HTMLVideoElement | HTMLImageElement | SVGImageElement
interface LoadMediaOptions {
ownerDocument?: Document
timeout?: number
onError?: (error: Error) => void
}

export function loadMedia<T extends Media>(media: T, options?: LoadMediaOptions): Promise<T>
export function loadMedia(media: string, options?: LoadMediaOptions): Promise<HTMLImageElement>
export function loadMedia(media: any, options?: LoadMediaOptions): Promise<any> {
return new Promise(resolve => {
const { timeout, ownerDocument } = options ?? {}
const { timeout, ownerDocument, onError: userOnError } = options ?? {}
const node: Media = typeof media === 'string'
? createImage(media, getDocument(ownerDocument))
: media
Expand Down Expand Up @@ -198,10 +199,11 @@ export function loadMedia(media: any, options?: LoadMediaOptions): Promise<any>
const onLoadeddata = onResolve
const onError = (error: any) => {
consoleWarn(
'Video load failed',
'Failed video load',
currentSrc,
error,
)
userOnError?.(error)
onResolve()
}
removeEventListeners = () => {
Expand Down Expand Up @@ -236,7 +238,7 @@ export function loadMedia(media: any, options?: LoadMediaOptions): Promise<any>

const onError = (error: any) => {
consoleWarn(
'Image load failed',
'Failed image load',
node.dataset.originalSrc || currentSrc,
error,
)
Expand Down

0 comments on commit 2bb1c3f

Please sign in to comment.