Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 21 additions & 9 deletions images/chromium-headful/client/src/components/video.vue
Original file line number Diff line number Diff line change
Expand Up @@ -701,10 +701,20 @@

@Watch('stream')
onStreamChanged(stream?: MediaStream) {
if (!this._video || !stream) {
if (!this._video) {
return
}

if (!stream) {
// a stream left on the element still fires canplaythrough and marks
// the closed session playable again
if ('srcObject' in this._video) this._video.srcObject = null
return
}

// swapping srcObject pauses the element without a pause event; starting
// from unplayable lets the new stream's canplaythrough start playback
this.$accessor.video.setPlayable(false)
if ('srcObject' in this._video) {
this._video.srcObject = stream
} else {
Expand Down Expand Up @@ -853,14 +863,7 @@
this.onResize()
})

this._video.addEventListener('canplaythrough', () => {
this.$accessor.video.setPlayable(true)
if (this.autoplay) {
this.$nextTick(() => {
this.$accessor.video.play()
})
}
})
this._video.addEventListener('canplaythrough', () => this.onCanPlayThrough())

this._video.addEventListener('ended', () => {
this.$accessor.video.setPlayable(false)
Expand Down Expand Up @@ -1046,6 +1049,15 @@
}
}

onCanPlayThrough() {
this.$accessor.video.setPlayable(true)
if (this.autoplay) {
this.$nextTick(() => {
this.$accessor.video.play()
})
}
}

pause() {
if (this._video.paused || !this.playable) {
return
Expand Down
10 changes: 9 additions & 1 deletion images/chromium-headful/client/src/neko/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,11 @@ export class NekoClient extends BaseClient implements EventEmitter<NekoEvents> {
connect: () => {
if (this.credentials) this.connect(this.url, this.credentials.password, this.credentials.displayname)
},
// the store reset a drop does, so tracks from the closed attempt don't linger
abort: () => {
this.disconnect()
this.cleanup()
},
onWaiting: (attempt) => {
this.$accessor.setReconnecting(true)
this.postParentMessage({ type: 'KERNEL_RECONNECTING', attempt })
Expand Down Expand Up @@ -165,7 +170,10 @@ export class NekoClient extends BaseClient implements EventEmitter<NekoEvents> {
// A page that comes back may hold a session that died while it was away
// without any event saying so.
private onWake = async () => {
if (document.hidden) return
if (document.hidden) {
this.reconnector.hid()
return
}
if (this.reconnector.active) {
this.reconnector.wake()
return
Expand Down
20 changes: 20 additions & 0 deletions images/chromium-headful/client/src/utils/reconnect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ export interface ReconnectDeps {
hidden(): boolean
probe(): Promise<ProbeResult>
connect(): void
// closes the attempt connect() started without reporting a drop
abort(): void
// an attempt is pending; attempt counts from 1 for each drop
onWaiting(attempt: number): void
onEnded(): void
Expand All @@ -44,6 +46,9 @@ export class Reconnector {
private failures = 0
private connectedAt = -Infinity
private timer?: number
// connect() ran for the current attempt, and the page hid after it did
private dialed = false
private stale = false

constructor(private deps: ReconnectDeps) {}

Expand Down Expand Up @@ -73,8 +78,20 @@ export class Reconnector {
this.phase = 'idle'
}

// the page was hidden; an attempt already dialing may have been suspended
hid() {
if (this.phase === 'connecting' && this.dialed) this.stale = true
}

// the page became visible, was restored, or the network came back
wake() {
// an attempt suspended mid-connect can sit until its timeout; replace it
if (this.phase === 'connecting' && this.stale) {
this.deps.abort()
this.phase = 'waiting'
this.attempt()
return
}
if (this.phase !== 'waiting') return
this.clear()
this.attempt()
Expand Down Expand Up @@ -102,6 +119,8 @@ export class Reconnector {
private async attempt() {
if (this.phase !== 'waiting' || this.deps.hidden()) return
this.phase = 'connecting'
this.dialed = false
this.stale = false
const result = await this.deps.probe()
if (this.phase !== 'connecting') return
if (result === 'ended') {
Expand All @@ -114,6 +133,7 @@ export class Reconnector {
this.phase = 'waiting'
return
}
this.dialed = true
this.deps.connect()
}
}
49 changes: 49 additions & 0 deletions images/chromium-headful/client/tests/reconnect-abort.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { afterEach, expect, test } from 'bun:test'
import { NekoClient } from '../src/neko'

const saved = { document: globalThis.document, window: globalThis.window }

afterEach(() => {
globalThis.document = saved.document
globalThis.window = saved.window
})

test('aborting a reconnect attempt closes it and clears its media', () => {
const calls: string[] = []
const listen = () => {}
globalThis.document = { addEventListener: listen } as unknown as Document
globalThis.window = { addEventListener: listen } as unknown as Window & typeof globalThis
const reset = (name: string) => () => calls.push(`${name} reset`)
const vue = {
$http: { defaults: {} },
$accessor: {
setConnected: (v: boolean) => calls.push(`connected ${v}`),
remote: { reset: reset('remote') },
user: { reset: reset('user') },
video: { reset: reset('video') },
chat: { reset: reset('chat') },
},
}
const client = new NekoClient()
client.initWithURL(vue as never, 'ws://host/ws')

let closed = false
let dropped = false
client['onDisconnected'] = () => (dropped = true)
// like a real socket, closing runs whatever onclose handler is set then
const socket = {
onclose: () => client['onDisconnected'](new Error('websocket closed')),
close() {
closed = true
this.onclose()
},
}
client['_ws'] = socket as unknown as WebSocket

client['reconnector']['deps'].abort()

expect(closed).toBe(true)
expect(client['_ws']).toBeUndefined()
expect(dropped).toBe(false)
expect(calls).toContain('video reset')
})
31 changes: 31 additions & 0 deletions images/chromium-headful/client/tests/reconnect.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ function harness(probe: () => ProbeResult = () => 'ok') {
hidden: () => hidden,
probe: async () => probe(),
connect: () => events.push(`connect@${now}`),
abort: () => events.push(`abort@${now}`),
onWaiting: (attempt) => events.push(`waiting ${attempt}`),
onEnded: () => events.push('ended'),
})
Expand Down Expand Up @@ -188,6 +189,36 @@ describe('reconnector', () => {
expect(h.events.filter((e) => e.startsWith('connect'))).toHaveLength(1)
})

test('a page that hides while an attempt connects replaces it on wake', async () => {
const h = harness()
h.tick(RECONNECT_STABLE_MS)
h.reconnect.dropped()
await h.advance(0)
h.setHidden(true)
h.reconnect.hid()
h.tick(30000)
h.setHidden(false)
h.reconnect.wake()
await h.flush()
expect(h.events).toEqual(['waiting 1', 'connect@10000', 'abort@40000', 'connect@40000'])
expect(h.reconnect.active).toBe(true)
expect(h.pending()).toBe(0)
})

test('a hide before connect() leaves nothing to replace', async () => {
let answer!: (r: ProbeResult) => void
const h = harness()
h.reconnect['deps'].probe = () => new Promise((r) => (answer = r))
h.tick(RECONNECT_STABLE_MS)
h.reconnect.dropped()
await h.advance(0)
h.reconnect.hid()
h.reconnect.wake()
answer('ok')
await h.flush()
expect(h.events).toEqual(['waiting 1', 'connect@10000'])
})

test('a refused page ends the session without connecting', async () => {
const h = harness(() => 'ended')
h.tick(RECONNECT_STABLE_MS)
Expand Down
99 changes: 99 additions & 0 deletions images/chromium-headful/client/tests/video-autoplay.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,105 @@ describe('first load autoplay', () => {
})
})

// The playing and playable state from store/video.ts, with the watcher that
// calls onPlayingChanged when playing changes.
function videoStore(component: Record<string, any>) {
const state = { playing: false, playable: false }
const set = (playing: boolean) => {
if (state.playing === playing) return
state.playing = playing
component.onPlayingChanged(playing)
}
return {
state,
play: () => state.playable && set(true),
pause: () => state.playable && set(false),
setPlayable: (playable: boolean) => {
if (!playable) set(false)
state.playable = playable
},
setMuted: () => {},
reset: () => {
set(false)
state.playable = false
},
}
}

describe('a stream that replaces a closed one', () => {
// An element that, like Chromium, pauses without a pause event when its
// srcObject changes, and fires canplaythrough only while it holds a stream.
function player() {
const video = {
paused: true,
muted: true,
srcObject: null as object | null,
play() {
this.paused = false
return Promise.resolve()
},
pause() {
this.paused = true
},
}
const component = Object.create(videoPrototype(), {
autoplay: { get: () => true },
playable: { get: () => store.state.playable },
})
const store = videoStore(component)
Object.assign(component, {
_video: new Proxy(video, {
set(target, key, value) {
if (key === 'srcObject') target.paused = true
return Reflect.set(target, key, value)
},
}),
isVideoSyncing: false,
videoBlocked: false,
$accessor: { video: store },
$nextTick: (fn: () => void) => fn(),
})
const canPlayThrough = async () => {
if (!video.srcObject) return
component.onCanPlayThrough()
await Promise.resolve()
}
return { component, video, store, canPlayThrough }
}

test('plays after an aborted attempt that had received its stream', async () => {
const { component, video, store, canPlayThrough } = player()
const aborted = {}
component.onStreamChanged(aborted)

// the attempt is aborted: the store resets and its stream goes away
store.reset()
component.onStreamChanged(undefined)
// the closed stream finishes buffering
await canPlayThrough()

component.onStreamChanged({})
await canPlayThrough()

expect(video.paused).toBe(false)
expect(store.state.playing).toBe(true)
})

test('plays a new stream that replaces one already playing', async () => {
const { component, video, store, canPlayThrough } = player()
component.onStreamChanged({})
await canPlayThrough()
expect(video.paused).toBe(false)

component.onStreamChanged({})
expect(video.paused).toBe(true)
await canPlayThrough()

expect(video.paused).toBe(false)
expect(store.state.playing).toBe(true)
})
})

describe('start prompt', () => {
const template = parseComponent(readFileSync(new URL('../src/components/video.vue', import.meta.url), 'utf8'))
.template!.content
Expand Down
Loading