Skip to content

Commit 6c75c84

Browse files
committed
feat: Add camera streaming support with resolution, frame rate
feat: Implement camera list parsing, error handling, and timeout feat: Update UI dialog for camera selection with language support bugfix: Fix camera process cleanup on device disconnect and handle
1 parent 7d9461b commit 6c75c84

12 files changed

Lines changed: 787 additions & 91 deletions

File tree

‎changelog.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
## unreleased
22

3+
- 新增:摄像头投屏支持枚举手机摄像头(含超广角、外接摄像头),按实际能力选择分辨率与帧率,新增画面方向、变焦、手电筒、码率与置顶/全屏/无边框开关,并记住上次选择
4+
- 优化:摄像头启动失败时显示真实原因(相机被占用、权限拒绝等),关闭摄像头窗口或删除设备时结束残留进程
5+
36
## v2.5.0 自动更新上线,软件自己检查并安装新版本
47

58
- 新增:软件启动后自动检查新版本,发现更新时弹窗显示更新说明和安装包大小,可关
Lines changed: 198 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,198 @@
1+
/**
2+
* Camera list parsing and scrcpy camera argument building.
3+
*
4+
* The camera list is printed by the scrcpy server on the device and forwarded
5+
* to the PC on stderr, so callers must pass the combined process output here.
6+
* This module is intentionally dependency-free so it can be unit tested with
7+
* `bun test` without booting Electron.
8+
*/
9+
10+
export type CameraFacing = 'front' | 'back' | 'external' | 'unknown'
11+
12+
export type CameraHighSpeedMode = {
13+
size: string
14+
fps: number[]
15+
}
16+
17+
export type CameraInfo = {
18+
id: string
19+
facing: CameraFacing
20+
activeSize: string
21+
fps: number[]
22+
zoomRange: {min: number; max: number} | null
23+
sizes: string[]
24+
highSpeed: CameraHighSpeedMode[]
25+
}
26+
27+
export type CameraWindowOptions = {
28+
cameraId: string
29+
cameraSize: string
30+
cameraFps: string
31+
orientation: string
32+
zoom: string
33+
torch: boolean
34+
bitRate: string
35+
alwaysOnTop: boolean
36+
fullscreen: boolean
37+
borderless: boolean
38+
}
39+
40+
const parseFacing = (value: string): CameraFacing => {
41+
if (value === 'front' || value === 'back' || value === 'external') {
42+
return value
43+
}
44+
return 'unknown'
45+
}
46+
47+
const parseNumberSet = (value: string): number[] => {
48+
const result: number[] = []
49+
for (const part of value.split(',')) {
50+
const num = Number(part.trim())
51+
if (Number.isFinite(num) && num > 0 && !result.includes(num)) {
52+
result.push(num)
53+
}
54+
}
55+
return result.sort((a, b) => b - a)
56+
}
57+
58+
const parseZoomRange = (value: string): {min: number; max: number} | null => {
59+
const matched = value.match(/^\s*([\d.]+)\s*,\s*([\d.]+)\s*$/)
60+
if (!matched) return null
61+
const min = Number(matched[1])
62+
const max = Number(matched[2])
63+
if (!Number.isFinite(min) || !Number.isFinite(max) || max <= 0) return null
64+
return {min, max}
65+
}
66+
67+
const CAMERA_LINE = /^\s*--camera-id=(\S+)\s*\((.*)\)\s*$/
68+
const SIZE_LINE = /^\s*-\s+(\d+x\d+)(?:\s+\(fps=\{([^}]*)\}\))?/
69+
const HIGH_SPEED_HEADING = /^\s*High speed capture\b/
70+
71+
/**
72+
* Parse the output of `scrcpy --list-cameras` / `--list-camera-sizes`.
73+
*
74+
* Example:
75+
* List of cameras:
76+
* --camera-id=0 (back, 4000x3000, fps={15, 30, 60}, zoom-range=[1, 10])
77+
* - 4000x3000
78+
* - 1920x1080
79+
* High speed capture (--camera-high-speed):
80+
* - 1920x1080 (fps={120, 240})
81+
*
82+
* Unrelated lines (warnings, the trailing `(none)` / `(access denied)`) are
83+
* ignored; an empty array means "no usable camera list".
84+
*/
85+
export const parseCameraList = (output: string): CameraInfo[] => {
86+
const cameras: CameraInfo[] = []
87+
let current: CameraInfo | null = null
88+
let inHighSpeed = false
89+
90+
for (const line of String(output || '').split(/\r?\n/)) {
91+
const cameraMatched = line.match(CAMERA_LINE)
92+
if (cameraMatched) {
93+
const id = cameraMatched[1]
94+
const detail = cameraMatched[2]
95+
const facingMatched = detail.match(/^\s*([a-z]+)\s*,/i)
96+
const sizeMatched = detail.match(/(\d+x\d+)/)
97+
const fpsMatched = detail.match(/fps=\{([^}]*)\}/)
98+
const zoomMatched = detail.match(/zoom-range=\[([^\]]*)\]/)
99+
current = {
100+
id,
101+
facing: parseFacing(facingMatched ? facingMatched[1].toLowerCase() : ''),
102+
activeSize: sizeMatched ? sizeMatched[1] : '',
103+
fps: fpsMatched ? parseNumberSet(fpsMatched[1]) : [],
104+
zoomRange: zoomMatched ? parseZoomRange(zoomMatched[1]) : null,
105+
sizes: [],
106+
highSpeed: [],
107+
}
108+
cameras.push(current)
109+
inHighSpeed = false
110+
continue
111+
}
112+
if (!current) continue
113+
if (HIGH_SPEED_HEADING.test(line)) {
114+
inHighSpeed = true
115+
continue
116+
}
117+
const sizeMatched = line.match(SIZE_LINE)
118+
if (sizeMatched) {
119+
const size = sizeMatched[1]
120+
const fps = sizeMatched[2] ? parseNumberSet(sizeMatched[2]) : []
121+
if (inHighSpeed) {
122+
current.highSpeed.push({size, fps})
123+
} else if (!current.sizes.includes(size)) {
124+
current.sizes.push(size)
125+
}
126+
}
127+
}
128+
129+
return cameras
130+
}
131+
132+
const normalizeSize = (value: string): string => {
133+
const matched = String(value || '').match(/^(\d+)x(\d+)$/)
134+
if (!matched) return ''
135+
const width = Number(matched[1])
136+
const height = Number(matched[2])
137+
if (!width || !height) return ''
138+
return `${width}x${height}`
139+
}
140+
141+
/**
142+
* Build the scrcpy arguments for a camera mirror window.
143+
*
144+
* Camera mode has no touch control, so only video/window options are emitted.
145+
* `--orientation` accepts 0/90/180/270 and flip0/flip90/flip180/flip270; the
146+
* default "0" is omitted because it is scrcpy's default.
147+
*/
148+
export const buildCameraArgs = (option: CameraWindowOptions): string[] => {
149+
const args: string[] = ['--video-source', 'camera']
150+
const cameraId = String(option.cameraId || '').trim()
151+
if (cameraId) {
152+
args.push('--camera-id', cameraId)
153+
}
154+
const cameraSize = normalizeSize(option.cameraSize)
155+
if (cameraSize) {
156+
args.push('--camera-size', cameraSize)
157+
}
158+
const cameraFps = String(option.cameraFps || '').trim()
159+
if (/^\d+$/.test(cameraFps) && Number(cameraFps) > 0) {
160+
args.push('--camera-fps', cameraFps)
161+
}
162+
const orientation = String(option.orientation || '').trim()
163+
if (orientation && orientation !== '0') {
164+
args.push('--orientation', orientation)
165+
}
166+
const zoom = String(option.zoom || '').trim()
167+
if (zoom && Number.isFinite(Number(zoom)) && Number(zoom) !== 1) {
168+
args.push('--camera-zoom', zoom)
169+
}
170+
if (option.torch) {
171+
args.push('--camera-torch')
172+
}
173+
const bitRate = String(option.bitRate || '').trim()
174+
if (bitRate) {
175+
args.push('--video-bit-rate', bitRate)
176+
}
177+
if (option.alwaysOnTop) {
178+
args.push('--always-on-top')
179+
}
180+
if (option.fullscreen) {
181+
args.push('--fullscreen')
182+
}
183+
if (option.borderless) {
184+
args.push('--window-borderless')
185+
}
186+
return args
187+
}
188+
189+
export const cameraOrientationOptions = (): {value: string; labelKey: string}[] => [
190+
{value: '0', labelKey: 'device.cameraOrientationNormal'},
191+
{value: '90', labelKey: 'device.cameraOrientationLeft'},
192+
{value: '270', labelKey: 'device.cameraOrientationRight'},
193+
{value: '180', labelKey: 'device.cameraOrientationUpsideDown'},
194+
{value: 'flip0', labelKey: 'device.cameraOrientationFlip'},
195+
{value: 'flip180', labelKey: 'device.cameraOrientationFlipVertical'},
196+
{value: 'flip90', labelKey: 'device.cameraOrientationFlipLeft'},
197+
{value: 'flip270', labelKey: 'device.cameraOrientationFlipRight'},
198+
]

‎electron/mapi/scrcpy/render.ts‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import {devProResolve, extraResolveBin, extraResolveWithPlatform, isDev, isWin,
22
import adb from '../adb/render'
33
import {Apps} from '../app'
44
import {Log} from '../log'
5+
import {CameraInfo, parseCameraList} from './cameraParse'
56

67
const getBinPath = async (): Promise<string> => {
78
// Dev mode: try pro project scrcpy binary first
@@ -151,6 +152,47 @@ const listApps = async (serial: string): Promise<ScrcpyApp[]> => {
151152
throw new Error(`MirrorAppListEmpty\n${tail}`)
152153
}
153154

155+
// List the cameras declared by the device. The scrcpy server prints the list
156+
// on stderr and exits, so we parse the combined output; a hung server must not
157+
// leave the camera dialog spinning forever, hence the explicit timeout.
158+
const listCameras = async (serial: string, option?: {timeoutMs?: number}): Promise<CameraInfo[]> => {
159+
const timeoutMs = option?.timeoutMs || 12000
160+
let controller: {stop: () => void; result: () => Promise<string>} | null = null
161+
let timer: ReturnType<typeof setTimeout> | null = null
162+
try {
163+
controller = await spawnShell(['--serial', serial, '--list-camera-sizes'])
164+
const timeout = new Promise<string>((_, reject) => {
165+
timer = setTimeout(() => {
166+
try {
167+
controller?.stop()
168+
} catch {}
169+
reject(new Error('CameraListTimeout'))
170+
}, timeoutMs)
171+
})
172+
let output = ''
173+
try {
174+
output = await Promise.race([controller.result(), timeout])
175+
} catch (error) {
176+
const text = String(error)
177+
if (text.includes('CameraListTimeout')) {
178+
throw new Error('CameraListTimeout')
179+
}
180+
// A non-zero exit still prints the camera list (e.g. access denied)
181+
output = text
182+
}
183+
const cameras = parseCameraList(output)
184+
Log.info('Scrcpy.listCameras', {
185+
serial,
186+
count: cameras.length,
187+
})
188+
return cameras
189+
} finally {
190+
if (timer) {
191+
clearTimeout(timer)
192+
}
193+
}
194+
}
195+
154196
const mirror = async (
155197
serial: string,
156198
option: {
@@ -187,5 +229,6 @@ export default {
187229
getBinPath,
188230
spawnShell,
189231
listApps,
232+
listCameras,
190233
mirror,
191234
}

‎package-lock.json‎

Lines changed: 2 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "linkandroid",
3-
"version": "2.5.0",
3+
"version": "2.6.0-beta.1",
44
"main": "dist-electron/main/index.js",
55
"description": "Link android to PC easily",
66
"author": "ModStartLib",

‎src/components.d.ts‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -95,10 +95,9 @@ declare module 'vue' {
9595
ILucideWorkflow: typeof import('~icons/lucide/workflow')['default']
9696
ILucideWrench: typeof import('~icons/lucide/wrench')['default']
9797
ILucideX: typeof import('~icons/lucide/x')['default']
98+
IMdiAlertCircleOutline: typeof import('~icons/mdi/alert-circle-outline')['default']
9899
IMdiAndroid: typeof import('~icons/mdi/android')['default']
99100
IMdiCamera: typeof import('~icons/mdi/camera')['default']
100-
IMdiCameraFront: typeof import('~icons/mdi/camera-front')['default']
101-
IMdiCameraRear: typeof import('~icons/mdi/camera-rear')['default']
102101
IMdiCast: typeof import('~icons/mdi/cast')['default']
103102
IMdiFolderOutline: typeof import('~icons/mdi/folder-outline')['default']
104103
IMdiInbox: typeof import('~icons/mdi/inbox')['default']

‎src/declarations/type.d.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -480,6 +480,20 @@ type DefsMapi = {
480480
},
481481
) => Promise<any>
482482
listApps: (serial: string) => Promise<{id: string; name: string; system: boolean}[]>
483+
listCameras: (
484+
serial: string,
485+
option?: {timeoutMs?: number},
486+
) => Promise<
487+
{
488+
id: string
489+
facing: 'front' | 'back' | 'external' | 'unknown'
490+
activeSize: string
491+
fps: number[]
492+
zoomRange: {min: number; max: number} | null
493+
sizes: string[]
494+
highSpeed: {size: string; fps: number[]}[]
495+
}[]
496+
>
483497
mirror: (
484498
serial: string,
485499
option: {

‎src/lang/en-US.ts‎

Lines changed: 33 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -119,17 +119,48 @@ const messages: Messages = {
119119
'device.batchConnectFailed': 'Batch connect failed',
120120
'device.appManagement': 'App Management',
121121
'device.bitrateUnit': 'BPS',
122-
'device.cameraFps': 'Camera FPS',
122+
'device.cameraAlwaysOnTop': 'Always on top',
123+
'device.cameraBitRate': 'Bitrate',
124+
'device.cameraBorderless': 'Borderless',
125+
'device.cameraFacingBack': 'Back',
126+
'device.cameraFacingExternal': 'External',
127+
'device.cameraFacingFront': 'Front',
128+
'device.cameraFacingUnknown': 'Camera',
129+
'device.cameraFps': 'Frame rate',
123130
'device.cameraFpsAuto': 'Auto',
124131
'device.cameraFront': 'Front',
132+
'device.cameraFullscreen': 'Fullscreen',
133+
'device.cameraListEmpty': 'No usable camera found, falling back to rear/front',
134+
'device.cameraListFailed': 'Failed to read the camera list, falling back to rear/front',
135+
'device.cameraOrientation': 'Orientation',
136+
'device.cameraOrientationFlip': 'Flip horizontally',
137+
'device.cameraOrientationFlipLeft': 'Flip + rotate left 90°',
138+
'device.cameraOrientationFlipRight': 'Flip + rotate right 90°',
139+
'device.cameraOrientationFlipVertical': 'Flip vertically',
140+
'device.cameraOrientationLeft': 'Rotate left 90°',
141+
'device.cameraOrientationNormal': 'Normal',
142+
'device.cameraOrientationRight': 'Rotate right 90°',
143+
'device.cameraOrientationUpsideDown': 'Upside down',
125144
'device.cameraRear': 'Rear',
126-
'device.cameraResolution': 'Camera Resolution',
145+
'device.cameraRefresh': 'Refresh cameras',
146+
'device.cameraResolution': 'Resolution',
127147
'device.cameraResolutionAuto': 'Auto',
128148
'device.cameraScreenshot': 'Camera Screenshot',
129149
'device.cameraScreenshotSaved': 'Camera screenshot saved',
130150
'device.cameraSelect': 'Select Camera',
131151
'device.cameraSettings': 'Camera Settings',
152+
'device.cameraShortcutFlip': 'Flip',
153+
'device.cameraShortcutFullscreen': 'Fullscreen',
154+
'device.cameraShortcutHold': 'In the camera window, hold Alt (Cmd on macOS):',
155+
'device.cameraShortcutRotate': 'Rotate',
156+
'device.cameraShortcutTorch': 'Torch',
157+
'device.cameraShortcutZoom': 'Zoom',
132158
'device.cameraStart': 'Start Camera',
159+
'device.cameraStartFailed': 'Failed to open camera',
160+
'device.cameraTorch': 'Torch',
161+
'device.cameraTorchHint': 'Some cameras do not support the torch',
162+
'device.cameraWindow': 'Window',
163+
'device.cameraZoom': 'Zoom',
133164
'device.closeNetworkPort': 'Close Network Port',
134165
'device.closeNetworkPortSuccess': 'Network port closed successfully',
135166
'device.closingNetworkPort': 'Closing network port',

0 commit comments

Comments
 (0)