refactor(core): CORE-09 isolate source operations and settle cancelled switches

This commit is contained in:
Harvey Zhao committed 2026-09-11 02:34:26 +08:00
1 parent 874dac9f22
commit 44f4e083a9
29 files changed
+4512 -255

No files matched your search

+12 -1
View File
@@ -1,5 +1,6 @@
import type { PlayHost } from '../media/hosts'
import type { PlaybackMethods } from '../media/types'
import { captureSource } from '../source/operation'
import { def } from '../utils'
export default function playMix<Media extends Pick<PlaybackMethods, 'play'>>(art: PlayHost<Media>): asserts art is PlayHost<Media> & { play: () => Promise<Awaited<ReturnType<Media['play']>>> } {
@@ -13,12 +14,22 @@ export default function playMix<Media extends Pick<PlaybackMethods, 'play'>>(art
def(art, 'play', {
async value() {
const active = captureSource(art)
const result = await $video.play()
notice.show = i18n.get('Play')
if (!active())
return result
const message = i18n.get('Play')
if (!active())
return result
notice.show = message
if (!active())
return result
art.emit('play')
if (option.mutex) {
for (let index = 0; index < instances.length; index++) {
if (!active())
break
const instance = instances[index]!
if (instance !== art) {
instance.pause()
@@ -1,63 +0,0 @@
import { def, silencePromise } from '../utils'
export default function switchMix(art) {
function switchUrl(url, currentTime) {
return new Promise((resolve, reject) => {
if (url === art.url) {
resolve()
return
}
const { playing, aspectRatio, playbackRate } = art
art.pause()
art.url = url
art.notice.show = ''
const handlers = {}
handlers.error = (error) => {
art.off('video:canplay', handlers.canplay)
art.off('video:loadedmetadata', handlers.metadata)
reject(error)
}
handlers.metadata = () => {
art.currentTime = currentTime
}
handlers.canplay = async () => {
art.off('video:error', handlers.error)
art.playbackRate = playbackRate
art.aspectRatio = aspectRatio
if (playing) {
await silencePromise(art.play())
}
art.notice.show = ''
resolve()
}
art.once('video:error', handlers.error)
art.once('video:loadedmetadata', handlers.metadata)
art.once('video:canplay', handlers.canplay)
})
}
def(art, 'switchQuality', {
value: (url) => {
return switchUrl(url, art.currentTime)
},
})
def(art, 'switchUrl', {
value: (url) => {
return switchUrl(url, 0)
},
})
def(art, 'switch', {
set: art.switchUrl,
})
}
@@ -0,0 +1,10 @@
import type { SwitchHost, SwitchMethods } from '../source/types'
import { switchSource } from '../source/switch'
import { def } from '../utils'
export default function switchMix(art: SwitchHost): asserts art is SwitchHost & SwitchMethods {
const switchUrl = (url: string) => switchSource(art, url, 0)
def(art, 'switchQuality', { value: (url: string) => switchSource(art, url, art.currentTime) })
def(art, 'switchUrl', { value: switchUrl })
def(art, 'switch', { set: switchUrl })
}
-48
View File
@@ -1,48 +0,0 @@
import { getScope } from '../lifecycle/instance'
import { wait } from '../lifecycle/resources'
import { def, getExt } from '../utils'
export default function urlMix(art) {
const {
option,
template: { $video },
} = art
def(art, 'url', {
get() {
return $video.src
},
async set(newUrl) {
if (newUrl) {
const oldUrl = art.url
const typeName = option.type || getExt(newUrl)
const typeCallback = option.customType[typeName]
if (typeName && typeCallback) {
if (!await wait(getScope(art)) || getScope(art).closed)
return
art.loading.show = true
typeCallback.call(art, $video, newUrl, art)
}
else {
URL.revokeObjectURL(oldUrl)
$video.src = newUrl
}
if (oldUrl !== art.url) {
art.option.url = newUrl
if (art.isReady && oldUrl) {
art.once('video:canplay', () => {
art.emit('restart', newUrl)
})
}
}
}
else {
if (!await wait(getScope(art)) || getScope(art).closed)
return
art.loading.show = true
}
},
})
}
+87
View File
@@ -0,0 +1,87 @@
import type { SourceMedia, UrlHost } from '../source/types'
import { isClosing } from '../lifecycle/instance'
import { wait } from '../lifecycle/resources'
import { listenSource } from '../source/listen'
import { failSource, finishAssignment, takeAssignment } from '../source/operation'
import { def, getExt } from '../utils'
export default function urlMix<Media extends SourceMedia, Host extends UrlHost<Media, Host>>(art: Host): void {
const { option, template: { $video } } = art
def(art, 'url', {
get() {
return $video.src
},
async set(newUrl: string) {
if (isClosing(art))
return
const operation = takeAssignment(art)
operation.acceptingEvents = false
try {
if (!newUrl) {
if (await wait(operation.scope) && operation.active())
art.loading.show = true
return
}
const oldUrl = art.url
const typeName = option.type || getExt(newUrl)
const typeCallback = option.customType[typeName]
if (typeName && typeCallback) {
if (!await wait(operation.scope) || !operation.active())
return
art.loading.show = true
}
if (!operation.active())
return
// Proxies can synchronously dispatch readiness from their src setter.
const capture = operation.scope.child()
let ready = false
let failed = false
listenSource(capture, art, 'video:canplay', () => {
ready = !failed
})
listenSource(capture, art, 'video:error', () => {
failed = true
})
try {
operation.acceptingEvents = true
if (typeName && typeCallback) {
const result = typeCallback.call(art, $video, newUrl, art)
// Preserve immediate customType invocation semantics while owning rejections.
void Promise.resolve(result).catch(error => failSource(operation, error))
}
else {
if (oldUrl)
URL.revokeObjectURL(oldUrl)
if (!operation.active())
return
$video.src = newUrl
}
}
finally {
capture.dispose()
}
if (!operation.active())
return
if (oldUrl !== art.url) {
art.option.url = newUrl
if (operation.active() && art.isReady && oldUrl) {
const restart = () => {
if (operation.active())
art.emit('restart', newUrl)
}
if (ready)
restart()
else if (!failed)
listenSource(operation.scope, art, 'video:canplay', restart)
}
}
}
catch (error) {
failSource(operation, error)
}
finally {
finishAssignment(operation)
}
},
})
}
+21
View File
@@ -0,0 +1,21 @@
import type ResourceScope from '../lifecycle/scope'
import type { SourceEvent, SourceEvents, SourceListener } from './types'
export function listenSource(scope: ResourceScope, art: SourceEvents, name: SourceEvent, callback: SourceListener, once = true): SourceListener {
let fired = false
let release: () => void
const guarded: SourceListener = (event) => {
if (scope.closed || fired)
return
if (once) {
fired = true
release()
}
callback(event)
}
art[once ? 'once' : 'on'](name, guarded)
release = scope.add(() => {
art.off(name, guarded)
})
return guarded
}
@@ -0,0 +1,79 @@
import type ResourceScope from '../lifecycle/scope'
import type { UrlTarget } from './types'
import { getScope, isClosing } from '../lifecycle/instance'
export interface SourceOperation {
scope: ResourceScope
assigned: boolean
acceptingEvents: boolean
onAssigned?: () => void
onError?: (error: unknown) => void
active: () => boolean
}
const current = new WeakMap<object, SourceOperation>()
const assignments = new WeakMap<object, SourceOperation>()
export function captureSource(owner: object): () => boolean {
const operation = current.get(owner)
return () => current.get(owner) === operation && (!operation || operation.active())
}
export function beginSource(owner: object): SourceOperation {
const previous = current.get(owner)
const scope = getScope(owner).child()
const operation: SourceOperation = {
scope,
assigned: false,
acceptingEvents: false,
active: () => !isClosing(owner) && !scope.closed && current.get(owner) === operation,
}
current.set(owner, operation)
scope.add(() => {
if (current.get(owner) === operation)
current.delete(owner)
operation.onAssigned = undefined
operation.onError = undefined
})
previous?.scope.dispose()
return operation
}
export function takeAssignment(owner: object): SourceOperation {
const operation = assignments.get(owner)
assignments.delete(owner)
return operation || beginSource(owner)
}
export function finishAssignment(operation: SourceOperation): void {
operation.assigned = true
const callback = operation.onAssigned
operation.onAssigned = undefined
if (operation.active())
callback?.()
}
export function assignUrl(owner: UrlTarget, operation: SourceOperation, url: string): void {
assignments.set(owner, operation)
operation.acceptingEvents = true
try {
owner.url = url
}
finally {
// Also support a host-provided URL setter without a core URL mixin.
if (assignments.get(owner) === operation) {
assignments.delete(owner)
finishAssignment(operation)
}
}
}
export function failSource(operation: SourceOperation, error: unknown): void {
if (!operation.active())
return
if (operation.onError)
operation.onError(error)
else
console.warn('Failed to initialize ArtPlayer source:', error)
operation.scope.dispose()
}
+121
View File
@@ -0,0 +1,121 @@
import type { SourceEvent, SourceListener, SwitchHost } from './types'
import { isClosing } from '../lifecycle/instance'
import { listenSource } from './listen'
import { assignUrl, beginSource } from './operation'
export function switchSource(art: SwitchHost, url: string, currentTime: number): Promise<void> {
return new Promise<void>((resolve, reject) => {
if (isClosing(art) || url === art.url) {
resolve()
return
}
const operation = beginSource(art)
const scope = operation.scope.child()
let settled = false
const settle = (failed = false, error?: unknown) => {
if (settled)
return
settled = true
operation.onError = undefined
operation.onAssigned = undefined
scope.dispose()
if (failed)
reject(error)
else
resolve()
if (failed)
operation.scope.dispose()
}
scope.add(() => {
settle()
})
const active = () => !settled && operation.active()
const fail = (error: unknown) => settle(true, error)
operation.onError = fail
try {
const { playing, aspectRatio, playbackRate } = art
art.pause()
if (!active())
return
const readiness = scope.child()
const handlers = {
'video:error': fail,
'video:loadedmetadata': () => {
if (!active())
return
try {
art.currentTime = currentTime
}
catch (error) {
fail(error)
}
},
'video:canplay': () => {
if (!active())
return
// Detach readiness handlers before awaiting a possibly pending play.
readiness.dispose()
const resume = async () => {
art.playbackRate = playbackRate
if (!active())
return
art.aspectRatio = aspectRatio
if (!active())
return
if (playing) {
// The public play promise still rejects; this internal resume is best effort.
try {
await art.play()
}
catch {}
}
if (!active())
return
art.notice.show = ''
settle()
}
void resume().catch(fail)
},
}
const capture = scope.child()
const queued: [SourceEvent, unknown][] = []
const names = Object.keys(handlers) as SourceEvent[]
for (const name of names) {
listenSource(capture, art, name, (event) => {
if (operation.acceptingEvents)
queued.push([name, event])
}, false)
}
assignUrl(art, operation, url)
if (!active())
return
art.notice.show = ''
if (!active())
return
const activate = () => {
capture.dispose()
if (!url) {
settle()
return
}
const dispatch = {} as Record<SourceEvent, SourceListener>
for (const name of names)
dispatch[name] = listenSource(readiness, art, name, handlers[name])
for (const [name, event] of queued) {
if (!active() || readiness.closed)
break
dispatch[name](event)
}
queued.length = 0
}
if (operation.assigned)
activate()
else
operation.onAssigned = activate
}
catch (error) {
fail(error)
}
})
}
+44
View File
@@ -0,0 +1,44 @@
export type SourceEvent = 'video:error' | 'video:loadedmetadata' | 'video:canplay'
export type SourceListener = (event?: unknown) => void
export interface SourceEvents {
on: (name: SourceEvent, callback: SourceListener) => unknown
once: (name: SourceEvent, callback: SourceListener) => unknown
off: (name: SourceEvent, callback: SourceListener) => unknown
}
export interface SourceMedia {
src: string | null
}
export interface UrlTarget {
url: string | null
}
export interface UrlHost<Media extends SourceMedia, Host> extends UrlTarget, SourceEvents {
template: { $video: Media }
option: {
url: string
type: string
customType: Record<string, ((this: Host, video: Media, url: string, art: Host) => unknown) | undefined>
}
loading: { set show(value: boolean) }
isReady: boolean
emit: (name: 'restart', url: string) => unknown
}
export interface SwitchHost extends UrlTarget, SourceEvents {
currentTime: number
readonly playing: boolean
aspectRatio: string
playbackRate: number
pause: () => unknown
play: () => unknown
notice: { set show(value: string) }
}
export interface SwitchMethods {
switchUrl: (url: string) => Promise<void>
switchQuality: (url: string) => Promise<void>
set switch(url: string)
}