forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsourceId.ts
More file actions
61 lines (55 loc) · 2.27 KB
/
Copy pathsourceId.ts
File metadata and controls
61 lines (55 loc) · 2.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import { desktopCapturer, screen } from 'electron'
// desktopCapturer.getSources() is pathologically slow on some machines (multiple
// seconds even with thumbnails disabled), and it's the dominant cost of enabling
// Rewind capture. The primary screen's source id is stable for a session, so we
// fetch it once, cache it, and reuse it. The cache is invalidated when the
// display layout changes. A single-flight promise dedupes concurrent callers
// (e.g. the startup prewarm racing the user's first enable).
let cached: string | null = null
let inflight: Promise<string | null> | null = null
async function fetchPrimarySourceId(): Promise<string | null> {
const sources = await desktopCapturer.getSources({
types: ['screen'],
thumbnailSize: { width: 0, height: 0 } // ids only — no screen bitmap
})
// A source's `id` is a sequential screen number, and getSources() makes no
// ordering guarantee — so sources[0] is not necessarily the primary display.
// `display_id` is the documented link to the Screen API; match on it and only
// fall back to the first source when Electron doesn't report one.
const primaryDisplayId = String(screen.getPrimaryDisplay().id)
const primary = sources.find((s) => s.display_id === primaryDisplayId)
return primary?.id ?? sources[0]?.id ?? null
}
/** Cached primary-screen source id; computes it (slowly) once, then reuses it. */
export async function getPrimarySourceId(): Promise<string | null> {
if (cached) return cached
if (!inflight) {
inflight = fetchPrimarySourceId()
.then((id) => {
cached = id
return id
})
.finally(() => {
inflight = null
})
}
return inflight
}
let invalidatorBound = false
/**
* Kick off the slow getSources() once at startup-idle so the cache is warm
* before the user enables capture — turning the multi-second enable hitch into
* an instant cache hit. Also binds display-change listeners that drop the cache.
*/
export function prewarmPrimarySourceId(): void {
if (!invalidatorBound) {
const invalidate = (): void => {
cached = null
}
screen.on('display-added', invalidate)
screen.on('display-removed', invalidate)
screen.on('display-metrics-changed', invalidate)
invalidatorBound = true
}
void getPrimarySourceId()
}