Free, open-source screen sharing for private live streams with friends. Watch together in a browser or self-host Piik. 免费开源的私密屏幕共享,支持游戏直播、一起看电影与自部署。
import { z } from "zod";
import { NATIVE_CLIENT_PORT_START, NATIVE_CLIENT_PORT_END } from "./discovery-ports";
import { remoteControlModeSchema, remoteInputPlatformSchema, remoteShortcutKeySchema } from "../remote-control/protocol";
import { iceCandidateSchema, sfuMediaSchema, positiveUint32Schema, qualityResolutionSchema, punchPredictionSchema,
nullableSafeEvidenceNumber, nullableSafeEvidenceInteger } from "../../shared/protocol";
export const NATIVE_CLIENT_PROTOCOL = 10;
export const NATIVE_CLIENT_SUBPROTOCOL = "piik-client-v10";
const decimalIdentifierSchema = z.string().regex(/^[1-9]\d{0,19}$/);
const opaqueIdentifierSchema = z
.string()
.min(8)
.max(256)
.regex(/^[A-Za-z0-9_-]+$/);
// Discovery descriptions may grow; control responses and events stay strict.
export const nativeDiscoveryIdentitySchema = z.object({
protocol: z.number().int().positive().max(Number.MAX_SAFE_INTEGER),
service: z.literal("piik-client"),
port: z
.number()
.int()
.min(NATIVE_CLIENT_PORT_START)
.max(NATIVE_CLIENT_PORT_END),
});
export const nativeHealthSchema = nativeDiscoveryIdentitySchema.extend({
protocol: z.literal(NATIVE_CLIENT_PROTOCOL),
version: z.string().optional(),
revision: z.string().optional(),
packageTarget: z.string().optional(),
qualityPreference: z.boolean().optional(),
activationURL: z.literal("piik://media").optional(),
instanceToken: z
.string()
.length(43)
.regex(/^[A-Za-z0-9_-]+$/),
nativeMedia: z
.object({
maxAudioBitrate: positiveUint32Schema.optional(),
maxVideoResolution: qualityResolutionSchema.optional(),
maxVideoPixels: z.number().int().positive().max(Number.MAX_SAFE_INTEGER).optional(),
maxVideoMacroblocksPerSecond: z.number().int().positive().max(Number.MAX_SAFE_INTEGER).optional(),
maxVideoFramerate: z.number().positive().max(Number.MAX_SAFE_INTEGER).optional(),
maxVideoBitrate: positiveUint32Schema.optional(),
receiverReuse: z.boolean().default(false),
maxRelayChildren: positiveUint32Schema.optional(),
remoteInput: z.boolean().optional(),
remoteStopShortcut: z.boolean().optional(),
remoteCoPlay: z.boolean().optional(),
video: z.boolean().default(false),
processAudio: z.boolean().default(false),
systemAudio: z.boolean().default(false),
processAudioExclusion: z.boolean().default(false),
microphone: z.boolean().default(false),
shareVolume: z.boolean().optional(),
sourceCancellation: z.boolean().optional(),
captureFailureDetails: z.boolean().optional(),
// API availability, not Windows approval or observed border visibility.
captureBorderControl: z.boolean().default(false),
hardwareH264: z.boolean().default(false),
softwareVP8: z.boolean().default(false),
})
.prefault({}),
});
export type NativeHealth = z.infer<typeof nativeHealthSchema>;
// Native receiver lifetime uses the selected backend's physical capability;
// room authority independently limits admitted children until the user opts in.
export function nativeRelayCapacity(capacity: number, health?: Pick<NativeHealth, "nativeMedia">): number {
return Math.min(capacity, health?.nativeMedia.maxRelayChildren ?? 3);
}
export const nativeConnectSchema = nativeDiscoveryIdentitySchema.extend({
protocol: z.literal(NATIVE_CLIENT_PROTOCOL),
connectURL: z.string().url().max(256),
});
const nativeWindowTargetSchema = z
.object({
kind: z.literal("window"),
sourceId: decimalIdentifierSchema,
pid: z.number().int().positive().max(0xffff_ffff),
creationTime: decimalIdentifierSchema,
title: z.string().min(1).max(4096),
})
.strict();
const nativeDisplayTargetSchema = z
.object({
kind: z.literal("display"),
sourceId: decimalIdentifierSchema,
title: z.string().min(1).max(4096),
})
.strict();
const nativePickerTargetSchema = z
.object({
kind: z.literal("picker"),
sourceId: decimalIdentifierSchema,
title: z.string().min(1).max(4096),
})
.strict();
export const nativeCaptureTargetSchema = z.discriminatedUnion("kind", [
nativeWindowTargetSchema,
nativeDisplayTargetSchema,
nativePickerTargetSchema,
]);
export type NativeCaptureTarget = z.infer<typeof nativeCaptureTargetSchema>;
const nativeEncoderSchema = z
.object({
index: z.number().int().nonnegative().max(0xffff_ffff),
name: z.string().min(1).max(512),
identity: z.string().min(1).max(512),
})
.strict();
const nativeAdapterSchema = z
.object({
index: z.number().int().nonnegative().max(0xffff_ffff),
name: z.string().min(1).max(512),
identity: z.string().min(1).max(512),
hardwareH264: z.array(nativeEncoderSchema).max(64),
})
.strict();
export type NativeAdapter = z.infer<typeof nativeAdapterSchema>;
const responseBase = {
version: z.literal(NATIVE_CLIENT_PROTOCOL),
id: opaqueIdentifierSchema,
};
export const remoteStopShortcutSchema = z.object({ key: remoteShortcutKeySchema, available: z.boolean() });
export type RemoteStopShortcut = z.infer<typeof remoteStopShortcutSchema>;
export const remoteStopShortcutResponseSchema = remoteStopShortcutSchema.extend({ ...responseBase, type: z.literal("remote-stop-shortcut") }).strict();
export const punchPreparedResponseSchema = z.object({
...responseBase, type: z.literal("punch-prepared"), prediction: punchPredictionSchema.nullable(),
}).strict();
export const punchCompleteResponseSchema = z.object({
...responseBase, type: z.literal("punch-complete"), connected: z.boolean(),
}).strict();
const nativeVideoCodecSchema = z.enum(["h264", "vp8"]);
export type NativeVideoCodec = z.infer<typeof nativeVideoCodecSchema>;
export const readyResponseSchema = z
.object({ ...responseBase, type: z.literal("ready") })
.strict();
export const pongResponseSchema = z
.object({ ...responseBase, type: z.literal("pong") })
.strict();
export const requestFailedResponseSchema = z
.object({
...responseBase,
type: z.literal("request-failed"),
code: z.enum(["operation-failed", "source-canceled"]),
})
.strict();
export const captureOptionsResponseSchema = z
.object({
...responseBase,
type: z.literal("capture-options"),
adapters: z.array(nativeAdapterSchema).max(64),
})
.strict();
export const sourceListResponseSchema = z
.object({
...responseBase,
type: z.literal("source-list"),
sources: z.array(nativeCaptureTargetSchema).max(1024),
})
.strict();
export const microphoneListResponseSchema = z.object({
...responseBase, type: z.literal("microphone-list"),
devices: z.array(z.object({ id: z.string().min(1).max(512), label: z.string().min(1).max(512) }).strict()).max(64),
}).strict();
export const sourcePreviewResponseSchema = z
.object({
...responseBase,
type: z.literal("source-preview"),
sourceKey: z.string().min(8).max(256),
mime: z.literal("image/bmp"),
data: z.string().max(256 * 1024),
})
.strict();
export const shareStartedResponseSchema = z
.object({
...responseBase,
type: z.literal("share-started"),
shareId: opaqueIdentifierSchema,
audio: z.boolean(),
sourceAudio: z.boolean().optional(),
codec: nativeVideoCodecSchema,
})
.strict();
export const shareUpdatedResponseSchema = z
.object({
...responseBase,
type: z.literal("share-updated"),
shareId: opaqueIdentifierSchema,
})
.strict();
export const shareSourceReplacedResponseSchema = z
.object({
...responseBase,
type: z.literal("share-source-replaced"),
shareId: opaqueIdentifierSchema,
})
.strict();
export const edgeOfferResponseSchema = z
.object({
...responseBase,
type: z.literal("edge-offer"),
shareId: opaqueIdentifierSchema,
connectionId: opaqueIdentifierSchema,
sdp: z
.string()
.min(1)
.max(48 * 1024),
})
.strict();
export const receiveAnswerResponseSchema = z
.object({
...responseBase,
type: z.literal("receive-answer"),
shareId: opaqueIdentifierSchema,
connectionId: opaqueIdentifierSchema,
sdp: z
.string()
.min(1)
.max(48 * 1024),
audio: z.boolean(),
codec: nativeVideoCodecSchema,
reused: z.boolean().optional(),
})
.strict();
export const publicationResponseSchema = z
.object({
...responseBase,
type: z.enum(["publication-offer", "publication-media"]),
shareId: opaqueIdentifierSchema,
publicationGeneration: opaqueIdentifierSchema,
connectionId: opaqueIdentifierSchema,
sdp: z
.string()
.max(48 * 1024)
.optional(),
media: sfuMediaSchema,
})
.strict();
export const nativeAckResponseSchema = z
.object({
...responseBase,
type: z.enum([
"edge-answer-accepted",
"edge-candidate-accepted",
"edge-closed",
"punch-closed",
"receive-candidate-accepted",
"receiver-closed",
"receive-stopped",
"share-stopped",
"share-paused",
"microphone-set",
"share-volume-set",
"remote-control-set",
"publication-answer-accepted",
"publication-candidate-accepted",
"publication-layers-accepted",
"publication-closed",
]),
})
.strict();
const eventBase = {
version: z.literal(NATIVE_CLIENT_PROTOCOL),
shareId: opaqueIdentifierSchema,
};
const remoteControlRequestSchema = z.object({
id: opaqueIdentifierSchema,
peerId: opaqueIdentifierSchema,
state: z.enum(["pending", "active", "suspended"]),
endpointId: z.string().regex(/^[0-9a-f]{32}$/).optional(),
}).strict();
export type RemoteControlRequest = z.infer<typeof remoteControlRequestSchema>;
export const remoteControlStateSchema = z.object({ mode: remoteControlModeSchema, platform: remoteInputPlatformSchema, requests: z.array(remoteControlRequestSchema), coPlay: z.boolean().optional(), gamepad: z.boolean().optional(), simultaneous: z.boolean().optional() });
export type RemoteControlState = z.infer<typeof remoteControlStateSchema>;
export const nativeEventSchema = z.discriminatedUnion("type", [
remoteControlStateSchema.extend({ ...eventBase, type: z.literal("remote-control-state") }).strict(),
z.object({ ...eventBase, type: z.literal("audio-state"), sourceAudio: z.boolean(), microphone: z.boolean(), failed: z.boolean() }).strict(),
z
.object({
...eventBase,
type: z.literal("publication-quality"),
publicationGeneration: opaqueIdentifierSchema,
connectionId: opaqueIdentifierSchema,
sampleTimestampMs: z
.number()
.int()
.nonnegative()
.max(Number.MAX_SAFE_INTEGER),
sampleWindowMs: z.number().int().min(1_000).max(5_000),
rtpStatsId: z.string().min(1).max(256),
trackIdentifier: z.string().min(1).max(256),
codec: nativeVideoCodecSchema,
videoEncodingCount: nullableSafeEvidenceInteger.catch(null),
activeVideoEncodingCount: nullableSafeEvidenceInteger.catch(null),
rid: z.string().max(16),
intervalFramesSent: z
.number()
.int()
.nonnegative()
.max(Number.MAX_SAFE_INTEGER),
framesPerSecond: nullableSafeEvidenceNumber.catch(null),
width: nullableSafeEvidenceInteger.catch(null),
height: nullableSafeEvidenceInteger.catch(null),
bitrateKbps: nullableSafeEvidenceNumber.catch(null),
audioBitrateKbps: nullableSafeEvidenceNumber.catch(null),
availableOutgoingKbps: nullableSafeEvidenceNumber.catch(null),
state: z.enum(["unknown", "healthy", "degraded"]),
reason: z.enum(["none", "bandwidth"]).nullable(),
})
.strict()
.refine(({ state, reason }) =>
state === "unknown"
? reason === null
: state === "healthy"
? reason === "none"
: reason === "bandwidth",
),
z
.object({
...eventBase,
type: z.literal("publication-candidate"),
publicationGeneration: opaqueIdentifierSchema,
connectionId: opaqueIdentifierSchema,
candidate: iceCandidateSchema.nullable(),
})
.strict(),
z
.object({
...eventBase,
type: z.literal("publication-state"),
publicationGeneration: opaqueIdentifierSchema,
connectionId: opaqueIdentifierSchema,
state: z.enum([
"new",
"connecting",
"connected",
"disconnected",
"failed",
"closed",
]),
})
.strict(),
z
.object({
...eventBase,
type: z.literal("capture-state"),
state: z.enum(["starting", "active"]),
})
.strict(),
z
.object({
...eventBase,
type: z.literal("edge-candidate"),
connectionId: opaqueIdentifierSchema,
candidate: iceCandidateSchema.nullable(),
})
.strict(),
z
.object({
...eventBase,
type: z.literal("edge-state"),
connectionId: opaqueIdentifierSchema,
state: z.enum([
"new",
"connecting",
"connected",
"disconnected",
"failed",
"closed",
]),
})
.strict(),
z
.object({
...eventBase,
type: z.literal("edge-path"),
connectionId: opaqueIdentifierSchema,
localType: z.enum(["host", "srflx", "prflx", "relay"]),
remoteType: z.enum(["host", "srflx", "prflx", "relay"]),
natTraversalPath: z.enum(["unknown", "ordinary", "predicted"]),
})
.strict(),
z
.object({
...eventBase,
type: z.literal("edge-quality"),
connectionId: opaqueIdentifierSchema,
sampleTimestampMs: z
.number()
.int()
.nonnegative()
.max(Number.MAX_SAFE_INTEGER),
sampleWindowMs: z.number().int().min(1_000).max(5_000),
rtpStatsId: z.string().min(1).max(256),
trackIdentifier: z.string().min(1).max(256),
state: z.enum(["unknown", "healthy", "degraded"]),
reason: z.enum(["none", "bandwidth"]).nullable(),
intervalFramesEncoded: z
.number()
.int()
.nonnegative()
.max(Number.MAX_SAFE_INTEGER),
framesPerSecond: nullableSafeEvidenceNumber.catch(null),
bitrateKbps: nullableSafeEvidenceNumber.catch(null),
availableOutgoingKbps: nullableSafeEvidenceNumber.catch(null),
width: nullableSafeEvidenceInteger.catch(null),
height: nullableSafeEvidenceInteger.catch(null),
})
.strict()
.superRefine((event, context) => {
if (
(event.state === "unknown" && event.reason !== null) ||
(event.state === "healthy" && event.reason !== "none") ||
(event.state === "degraded" && event.reason !== "bandwidth")
) {
context.addIssue({
code: "custom",
message: "Native edge quality reason does not match its state",
path: ["reason"],
});
}
}),
z
.object({
...eventBase,
type: z.literal("share-ended"),
failed: z.boolean(),
failure: z.object({
stage: z.string().regex(/^[a-z][a-z0-9-]{0,63}$/).optional(),
hresult: z.string().regex(/^0x[0-9a-f]{8}$/).optional(),
exitCode: z.number().int().min(-0x80000000).max(0xffffffff),
}).strict().optional(),
})
.strict().refine(value => value.failed || !value.failure),
]);
export type NativeClientEvent = z.infer<typeof nativeEventSchema>;
export type NativeIceCandidate = z.infer<typeof iceCandidateSchema>;