Skip to content

armgit / Piik

Public Imported from GitHub
0

Free, open-source screen sharing for private live streams with friends. Watch together in a browser or self-host Piik. 免费开源的私密屏幕共享,支持游戏直播、一起看电影与自部署。

refactor(browser): fix video codec to VP8

AAAb662ece09995
diff --git a/src/client/media/quality.ts b/src/client/media/quality.ts
index c9e2a30c..3004b2df 100644
--- a/src/client/media/quality.ts
+++ b/src/client/media/quality.ts
@@ -5,7 +5,6 @@ import {
type QualityResolution,
type QualitySettings,
type ScreenAudioQuality,
- type VideoCodecPreference,
} from "../../shared/protocol";
import { displayMediaOptions } from "./audio-capture";
@@ -15,7 +14,6 @@ export type {
QualityResolution,
QualitySettings,
ScreenAudioQuality,
- VideoCodecPreference,
} from "../../shared/protocol";
export type QualityProfile = QualitySettings;
@@ -26,7 +24,6 @@ export const QUALITY_PROFILES = {
maxFramerate: 60,
maxBitrate: 8_000_000,
degradationPreference: "balanced",
- videoCodec: "vp8",
screenAudioQuality: "music",
},
"1080p30": DEFAULT_QUALITY_SETTINGS,
@@ -35,7 +32,6 @@ export const QUALITY_PROFILES = {
maxFramerate: 30,
maxBitrate: 3_000_000,
degradationPreference: "balanced",
- videoCodec: "vp8",
screenAudioQuality: "music",
},
} as const satisfies Record<QualityProfileId, QualitySettings>;
@@ -62,12 +58,6 @@ export const DEGRADATION_PREFERENCE_LABELS = {
"maintain-framerate": "流畅优先",
} as const satisfies Record<DegradationPreference, string>;
-export const VIDEO_CODEC_PREFERENCE_LABELS = {
- automatic: "自动",
- h264: "H.264",
- vp8: "VP8",
-} as const satisfies Record<VideoCodecPreference, string>;
-
export const SCREEN_AUDIO_QUALITY_LABELS = {
saver: "64 kbps 省流",
music: "128 kbps 音乐默认",
@@ -144,8 +134,7 @@ export function videoQualitySettingsEqual(
left.resolution === right.resolution &&
left.maxFramerate === right.maxFramerate &&
left.maxBitrate === right.maxBitrate &&
- left.degradationPreference === right.degradationPreference &&
- (left.videoCodec ?? "vp8") === (right.videoCodec ?? "vp8")
+ left.degradationPreference === right.degradationPreference
);
}
diff --git a/src/client/pages/HostPage.tsx b/src/client/pages/HostPage.tsx
index 47f89fa5..c060a8df 100644
--- a/src/client/pages/HostPage.tsx
+++ b/src/client/pages/HostPage.tsx
@@ -89,8 +89,6 @@ import {
type QualityProfileId,
type QualitySettings,
type ScreenAudioQuality,
- type VideoCodecPreference,
- VIDEO_CODEC_PREFERENCE_LABELS,
} from "../media/quality";
import {
HostSfuRoute,
@@ -125,7 +123,6 @@ import {
shouldPauseLocalPreview,
sourceSwitchNotice,
type HostAction,
- videoCodecLockNotice,
} from "./host-page-notices";
type HostPhase = "idle" | "starting" | "live" | "ended" | "error";
@@ -738,16 +735,6 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
);
}
- function changeVideoCodec(videoCodec: VideoCodecPreference): void {
- if (phase === "starting" || phase === "live") {
- return;
- }
- const next = { ...qualitySettingsRef.current, videoCodec };
- qualitySettingsRef.current = next;
- setQualitySettings(next);
- setAdvancedQuality((current) => ({ ...current, videoCodec }));
- }
-
function changeScreenAudioQuality(
screenAudioQuality: ScreenAudioQuality,
): void {
@@ -763,13 +750,6 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
preserveAdvancedDraft = false,
): Promise<void> {
const previousProfile = qualitySettingsRef.current;
- if (
- phase === "live" &&
- (nextProfile.videoCodec ?? "vp8") !==
- (previousProfile.videoCodec ?? "vp8")
- ) {
- return;
- }
if (phase !== "live") {
commitQuality(nextProfile, preserveAdvancedDraft);
return;
@@ -1953,8 +1933,6 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
: null;
const activeCodeEntryPolicy =
room?.codeEntryPolicy ?? creationProfile.codeEntryPolicy;
- const codecLockNotice = videoCodecLockNotice(phase);
-
return (
<div className="app-shell">
<AppHeader
@@ -2250,8 +2228,6 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
onClick={() =>
void changeQuality({
...QUALITY_PROFILES[id],
- videoCodec:
- qualitySettingsRef.current.videoCodec ?? "vp8",
screenAudioQuality: resolveScreenAudioQuality(
qualitySettingsRef.current.screenAudioQuality,
),
@@ -2364,49 +2340,6 @@ export function HostPage({ onAuthorizationRequired }: HostPageProps = {}) {
))}
</div>
</fieldset>
- <fieldset
- className="control-group quality-priority"
- aria-describedby={
- codecLockNotice ? "video-codec-lock-notice" : undefined
- }
- >
- <legend>视频编码</legend>
- <div className="segmented-control">
- {(
- Object.keys(
- VIDEO_CODEC_PREFERENCE_LABELS,
- ) as VideoCodecPreference[]
- ).map((codec) => (
- <button
- key={codec}
- type="button"
- className={
- (advancedQuality.videoCodec ?? "vp8") === codec
- ? "is-selected"
- : undefined
- }
- aria-pressed={
- (advancedQuality.videoCodec ?? "vp8") === codec
- }
- disabled={
- phase === "starting" ||
- phase === "live" ||
- changingQuality
- }
- onClick={() =>
- changeVideoCodec(codec)
- }
- >
- {VIDEO_CODEC_PREFERENCE_LABELS[codec]}
- </button>
- ))}
- </div>
- {codecLockNotice && (
- <p id="video-codec-lock-notice" className="control-note">
- {codecLockNotice}
- </p>
- )}
- </fieldset>
<fieldset className="control-group quality-priority">
<legend>音频质量</legend>
<div className="segmented-control">
diff --git a/src/client/pages/host-page-notices.ts b/src/client/pages/host-page-notices.ts
index e29255b7..b0fc0c51 100644
--- a/src/client/pages/host-page-notices.ts
+++ b/src/client/pages/host-page-notices.ts
@@ -94,9 +94,3 @@ export function shouldPauseLocalPreview(
): boolean {
return visibilityState !== "visible" || !hasFocus;
}
-
-export function videoCodecLockNotice(phase: string): string | null {
- return phase === "starting" || phase === "live"
- ? "本次分享的视频编码已固定,停止分享后可更改"
- : null;
-}
diff --git a/src/client/sfu/publisher.ts b/src/client/sfu/publisher.ts
index 51599c3e..328d1764 100644
--- a/src/client/sfu/publisher.ts
+++ b/src/client/sfu/publisher.ts
@@ -1101,10 +1101,9 @@ function videoPublishOptions(
profile: QualityProfile,
): TrackPublishOptions {
const highResolution = QUALITY_RESOLUTIONS[profile.resolution];
- const videoCodec = profile.videoCodec ?? "vp8";
return {
backupCodec: false,
- ...(videoCodec === "automatic" ? {} : { videoCodec }),
+ videoCodec: "vp8",
simulcast: true,
screenShareEncoding: {
maxBitrate: profile.maxBitrate,
diff --git a/src/client/webrtc/host-peer.ts b/src/client/webrtc/host-peer.ts
index 0635825d..6ea86b8a 100644
--- a/src/client/webrtc/host-peer.ts
+++ b/src/client/webrtc/host-peer.ts
@@ -21,7 +21,7 @@ import {
collectConnectionMetrics,
createStatsAccumulator,
} from "./stats";
-import { applyVideoCodecPreference } from "./video-codec-preference";
+import { applyVp8Codec } from "./vp8-codec";
const MAX_PENDING_CANDIDATES = 64;
type PeerIceConfig = Pick<RTCConfiguration, "iceServers">;
@@ -100,7 +100,10 @@ export class HostPeer {
direction: "sendonly",
streams: [this.stream],
});
- applyVideoCodecPreference(videoTransceiver, this.desiredProfile.videoCodec);
+ if (!applyVp8Codec(videoTransceiver)) {
+ this.setError(null, "当前浏览器无法使用 VP8 视频编码");
+ return false;
+ }
this.videoSender = videoTransceiver.sender;
this.audioSender = this.connection.addTransceiver(audioTrack ?? "audio", {
direction: "sendonly",
diff --git a/src/client/webrtc/video-codec-preference.ts b/src/client/webrtc/video-codec-preference.ts
deleted file mode 100644
index 0de85004..00000000
--- a/src/client/webrtc/video-codec-preference.ts
+++ /dev/null
@@ -1,43 +0,0 @@
-import type { VideoCodecPreference } from "../../shared/protocol";
-
-function videoCodecs(): RTCRtpCodec[] {
- if (typeof RTCRtpSender === "undefined") {
- return [];
- }
- return RTCRtpSender.getCapabilities?.("video")?.codecs ?? [];
-}
-
-export function applyVideoCodecPreference(
- transceiver: RTCRtpTransceiver,
- preference: VideoCodecPreference | undefined,
-): boolean {
- const resolvedPreference = preference ?? "vp8";
- if (typeof transceiver.setCodecPreferences !== "function") {
- return false;
- }
- if (resolvedPreference === "automatic") {
- try {
- transceiver.setCodecPreferences([]);
- return true;
- } catch {
- return false;
- }
- }
- const codecs = videoCodecs();
- const mimeType = `video/${resolvedPreference}`;
- const preferred = codecs.filter(
- (codec) => codec.mimeType.toLowerCase() === mimeType,
- );
- if (preferred.length === 0) {
- return false;
- }
- try {
- transceiver.setCodecPreferences([
- ...preferred,
- ...codecs.filter((codec) => codec.mimeType.toLowerCase() !== mimeType),
- ]);
- return true;
- } catch {
- return false;
- }
-}
diff --git a/src/client/webrtc/vp8-codec.ts b/src/client/webrtc/vp8-codec.ts
new file mode 100644
index 00000000..6d0956a1
--- /dev/null
+++ b/src/client/webrtc/vp8-codec.ts
@@ -0,0 +1,35 @@
+const REPAIR_CODEC_MIME_TYPES = new Set([
+ "video/rtx",
+ "video/red",
+ "video/ulpfec",
+ "video/flexfec-03",
+]);
+
+export function applyVp8Codec(transceiver: RTCRtpTransceiver): boolean {
+ if (
+ typeof RTCRtpSender === "undefined" ||
+ typeof transceiver.setCodecPreferences !== "function"
+ ) {
+ return false;
+ }
+
+ try {
+ const codecs = RTCRtpSender.getCapabilities?.("video")?.codecs ?? [];
+ const vp8Codecs = codecs.filter(
+ ({ mimeType }) => mimeType.toLowerCase() === "video/vp8",
+ );
+ if (vp8Codecs.length === 0) {
+ return false;
+ }
+
+ transceiver.setCodecPreferences([
+ ...vp8Codecs,
+ ...codecs.filter(({ mimeType }) =>
+ REPAIR_CODEC_MIME_TYPES.has(mimeType.toLowerCase()),
+ ),
+ ]);
+ return true;
+ } catch {
+ return false;
+ }
+}
diff --git a/src/server/signaling.ts b/src/server/signaling.ts
index 3c60b572..733071e8 100644
--- a/src/server/signaling.ts
+++ b/src/server/signaling.ts
@@ -20,7 +20,6 @@ import {
type Role,
type ServerMessage,
type ParticipantPresenceEntry,
- type VideoCodecPreference,
} from "../shared/protocol.js";
import { assertEndpointMediaCopyCapacity } from "../shared/media-copy-accounting.js";
import {
@@ -789,20 +788,6 @@ export class SignalingServer {
);
return;
}
- const currentQuality = this.qualitySettingsByRoom.get(
- authenticated.roomId,
- );
- if (
- currentQuality &&
- videoCodec(currentQuality) !== videoCodec(message.qualitySettings)
- ) {
- this.sendError(
- socket,
- "FORBIDDEN",
- "视频编码只能在开始分享前选择;请停止分享后重新开始",
- );
- return;
- }
this.qualitySettingsByRoom.set(authenticated.roomId, {
...message.qualitySettings,
});
@@ -2086,10 +2071,6 @@ function viewerConnectionKey(roomId: string, peerId: string): string {
return `${roomId}:${peerId}`;
}
-function videoCodec(settings: QualitySettings): VideoCodecPreference {
- return settings.videoCodec ?? DEFAULT_QUALITY_SETTINGS.videoCodec;
-}
-
function authenticationErrorMessage(code: ErrorCode): string {
switch (code) {
case "ROOM_ACCESS_DENIED":
diff --git a/src/shared/protocol.ts b/src/shared/protocol.ts
index 0dac3091..42f7c5e7 100644
--- a/src/shared/protocol.ts
+++ b/src/shared/protocol.ts
@@ -6,7 +6,7 @@ import { isCanonicalVideoCodecEvidence } from "./video-codec-evidence.js";
export const MAX_VIEWERS_PER_ROOM_LIMIT = 20;
export const MAX_PARTICIPANTS_PER_ROOM_LIMIT = MAX_VIEWERS_PER_ROOM_LIMIT + 1;
export const MAX_SIGNAL_BYTES = 64 * 1024;
-export const SIGNALING_PROTOCOL = "screener-v10";
+export const SIGNALING_PROTOCOL = "screener-v11";
export const SIGNAL_CLOSE_CODES = {
sessionReplaced: 4001,
clientReconnect: 4002,
@@ -179,15 +179,6 @@ export type DegradationPreference = z.infer<
typeof degradationPreferenceSchema
>;
-export const videoCodecPreferenceSchema = z.enum([
- "automatic",
- "h264",
- "vp8",
-]);
-export type VideoCodecPreference = z.infer<
- typeof videoCodecPreferenceSchema
->;
-
export const screenAudioQualitySchema = z.enum([
"saver",
"music",
@@ -201,7 +192,6 @@ export const qualitySettingsSchema = z
maxFramerate: z.number().int().min(15).max(60),
maxBitrate: z.number().int().min(2_000_000).max(12_000_000),
degradationPreference: degradationPreferenceSchema,
- videoCodec: videoCodecPreferenceSchema.optional(),
screenAudioQuality: screenAudioQualitySchema.optional(),
})
.strict();
@@ -211,7 +201,6 @@ export const DEFAULT_QUALITY_SETTINGS = {
maxFramerate: 30,
maxBitrate: 5_000_000,
degradationPreference: "balanced",
- videoCodec: "vp8",
screenAudioQuality: "music",
} as const satisfies QualitySettings;
diff --git a/tests/client-state.test.ts b/tests/client-state.test.ts
index 2f5d279f..2f57eeba 100644
--- a/tests/client-state.test.ts
+++ b/tests/client-state.test.ts
@@ -746,7 +746,7 @@ describe("client signaling recovery policy", () => {
Object.defineProperty(authenticated, "data", {
value: JSON.stringify({
type: "authenticated",
- protocol: "screener-v10",
+ protocol: "screener-v11",
role: "viewer",
peerId: "viewer_12345678",
roomExpiresAt: null,
@@ -815,7 +815,7 @@ describe("client signaling recovery policy", () => {
socket.dispatchEvent(new Event("open"));
receive(socket, {
type: "authenticated",
- protocol: "screener-v10",
+ protocol: "screener-v11",
role: "host",
peerId: "host_12345678",
roomExpiresAt: null,
@@ -851,7 +851,7 @@ describe("client signaling recovery policy", () => {
});
receive(sockets[1]!, {
type: "authenticated",
- protocol: "screener-v10",
+ protocol: "screener-v11",
role: "host",
peerId: "host_12345678",
roomExpiresAt: null,
@@ -936,7 +936,7 @@ describe("client signaling recovery policy", () => {
socket.dispatchEvent(new Event("open"));
receive(socket, {
type: "authenticated",
- protocol: "screener-v10",
+ protocol: "screener-v11",
role: "host",
peerId: "host_12345678",
roomExpiresAt: null,
@@ -1061,7 +1061,7 @@ describe("client signaling recovery policy", () => {
sockets[0]!.dispatchEvent(new Event("open"));
receive({
type: "authenticated",
- protocol: "screener-v10",
+ protocol: "screener-v11",
role: "viewer",
peerId: "viewer_12345678",
roomExpiresAt: null,
@@ -1086,7 +1086,6 @@ describe("client signaling recovery policy", () => {
maxFramerate: 30,
maxBitrate: 5_000_000,
degradationPreference: "balanced",
- videoCodec: "automatic",
screenAudioQuality: "music",
},
});
@@ -1189,7 +1188,7 @@ describe("client signaling recovery policy", () => {
JSON.parse(String(sockets[0]!.send.mock.calls[0]![0])),
).toMatchObject({
type: "authenticate",
- protocol: "screener-v10",
+ protocol: "screener-v11",
});
const message = new Event("message");
Object.defineProperty(message, "data", { value: payload });
diff --git a/tests/host-page-notice.test.ts b/tests/host-page-notice.test.ts
index 1bd7650a..33b36cd8 100644
--- a/tests/host-page-notice.test.ts
+++ b/tests/host-page-notice.test.ts
@@ -5,7 +5,6 @@ import {
hostServerErrorNotice,
shouldPauseLocalPreview,
sourceSwitchNotice,
- videoCodecLockNotice,
} from "../src/client/pages/host-page-notices.ts";
describe("host error notices", () => {
@@ -94,16 +93,3 @@ describe("sourceSwitchNotice", () => {
).toBe("分享来源已切换");
});
});
-
-describe("videoCodecLockNotice", () => {
- it("keeps codec selection pre-share only", () => {
- for (const phase of ["starting", "live"]) {
- expect(videoCodecLockNotice(phase)).toBe(
- "本次分享的视频编码已固定,停止分享后可更改",
- );
- }
- for (const phase of ["idle", "ended", "error"]) {
- expect(videoCodecLockNotice(phase)).toBeNull();
- }
- });
-});
diff --git a/tests/host-peer-tracks.test.ts b/tests/host-peer-tracks.test.ts
index 26652c43..d4f3519a 100644
--- a/tests/host-peer-tracks.test.ts
+++ b/tests/host-peer-tracks.test.ts
@@ -79,6 +79,8 @@ class FakePeerConnection {
static activeCount = 0;
static peakActiveCount = 0;
static offersFailing = 0;
+ static omitCodecPreferenceSetter = false;
+ static codecPreferenceCallsFailing = 0;
readonly configurations: RTCConfiguration[] = [];
readonly senders: FakeSender[] = [];
@@ -87,6 +89,7 @@ class FakePeerConnection {
init?: RTCRtpTransceiverInit;
}> = [];
readonly codecPreferenceCalls: RTCRtpCodec[][] = [];
+ createOfferCallCount = 0;
remoteDescriptionCallCount = 0;
deferRemoteDescriptionCall: number | null = null;
private releaseRemoteDescription: (() => void) | null = null;
@@ -128,15 +131,24 @@ class FakePeerConnection {
this.transceiverInputs.push({ trackOrKind, init });
return {
sender,
- setCodecPreferences: (codecs: RTCRtpCodec[]) => {
- this.codecPreferenceCalls.push([...codecs]);
- },
+ ...(FakePeerConnection.omitCodecPreferenceSetter
+ ? {}
+ : {
+ setCodecPreferences: (codecs: RTCRtpCodec[]) => {
+ if (FakePeerConnection.codecPreferenceCallsFailing > 0) {
+ FakePeerConnection.codecPreferenceCallsFailing -= 1;
+ throw new Error("setCodecPreferences failed");
+ }
+ this.codecPreferenceCalls.push([...codecs]);
+ },
+ }),
} as unknown as RTCRtpTransceiver;
}
addEventListener(): void {}
async createOffer(): Promise<RTCSessionDescriptionInit> {
+ this.createOfferCallCount += 1;
if (FakePeerConnection.offersFailing > 0) {
FakePeerConnection.offersFailing -= 1;
throw new Error("createOffer failed");
@@ -349,6 +361,8 @@ beforeEach(() => {
FakePeerConnection.activeCount = 0;
FakePeerConnection.peakActiveCount = 0;
FakePeerConnection.offersFailing = 0;
+ FakePeerConnection.omitCodecPreferenceSetter = false;
+ FakePeerConnection.codecPreferenceCallsFailing = 0;
statsCallbacks.length = 0;
vi.stubGlobal("RTCPeerConnection", FakePeerConnection);
vi.stubGlobal("RTCRtpSender", {
@@ -392,63 +406,93 @@ describe("HostPeer source replacement", () => {
expect(updates.at(-1)?.error).not.toContain("createOffer failed");
});
- it("prefers VP8 before the first offer by default", async () => {
+ it("offers only advertised VP8 and repair codecs", async () => {
+ vi.stubGlobal("RTCRtpSender", {
+ getCapabilities: () => ({
+ codecs: [
+ { mimeType: "video/H264", clockRate: 90_000 },
+ { mimeType: "video/rtx", clockRate: 90_000 },
+ { mimeType: "video/VP9", clockRate: 90_000 },
+ { mimeType: "video/RED", clockRate: 90_000 },
+ { mimeType: "video/VP8", clockRate: 90_000 },
+ { mimeType: "video/ulpfec", clockRate: 90_000 },
+ { mimeType: "video/AV1", clockRate: 90_000 },
+ { mimeType: "video/flexfec-03", clockRate: 90_000 },
+ ],
+ headerExtensions: [],
+ }),
+ });
const peer = createPeer(createStream(createTrack("video", "video"), null));
await expect(peer.start()).resolves.toBe(true);
+ const connection = FakePeerConnection.latest!;
expect(
- FakePeerConnection.latest!.codecPreferenceCalls[0]?.[0]?.mimeType,
- ).toBe("video/VP8");
+ connection.codecPreferenceCalls[0]?.map(({ mimeType }) =>
+ mimeType.toLowerCase(),
+ ),
+ ).toEqual([
+ "video/vp8",
+ "video/rtx",
+ "video/red",
+ "video/ulpfec",
+ "video/flexfec-03",
+ ]);
+ expect(connection.createOfferCallCount).toBe(1);
});
- it("restores browser codec ordering for explicit automatic", async () => {
+ it("fails before creating an offer when codec preferences are unavailable", async () => {
+ FakePeerConnection.omitCodecPreferenceSetter = true;
+ const updates: PeerSnapshot[] = [];
const peer = createPeer(
createStream(createTrack("video", "video"), null),
- () => undefined,
- { iceServers: [] },
- { ...QUALITY_PROFILES["720p30"], videoCodec: "automatic" },
+ (snapshot) => updates.push(snapshot),
);
- await expect(peer.start()).resolves.toBe(true);
+ await expect(peer.start()).resolves.toBe(false);
- expect(FakePeerConnection.latest!.codecPreferenceCalls).toEqual([[]]);
+ expect(FakePeerConnection.latest!.createOfferCallCount).toBe(0);
+ expect(FakePeerConnection.latest!.localDescription).toBeNull();
+ expect(updates.at(-1)?.error).toBe("当前浏览器无法使用 VP8 视频编码");
});
- it.each(["h264", "vp8"] as const)(
- "prefers %s before the first offer while retaining fallback codecs",
- async (videoCodec) => {
- vi.stubGlobal("RTCRtpSender", {
- getCapabilities: () => ({
- codecs: [
- { mimeType: "video/VP8", clockRate: 90_000 },
- { mimeType: "video/rtx", clockRate: 90_000 },
- {
- mimeType: "video/H264",
- clockRate: 90_000,
- sdpFmtpLine: "packetization-mode=1;profile-level-id=42001f",
- },
- { mimeType: "video/rtx", clockRate: 90_000 },
- ],
- headerExtensions: [],
- }),
- });
- const peer = createPeer(
- createStream(createTrack("video", "video"), null),
- () => undefined,
- { iceServers: [] },
- { ...QUALITY_PROFILES["720p30"], videoCodec },
- );
+ it("fails before creating an offer when VP8 is unavailable", async () => {
+ vi.stubGlobal("RTCRtpSender", {
+ getCapabilities: () => ({
+ codecs: [
+ { mimeType: "video/H264", clockRate: 90_000 },
+ { mimeType: "video/rtx", clockRate: 90_000 },
+ ],
+ headerExtensions: [],
+ }),
+ });
+ const updates: PeerSnapshot[] = [];
+ const peer = createPeer(
+ createStream(createTrack("video", "video"), null),
+ (snapshot) => updates.push(snapshot),
+ );
- await expect(peer.start()).resolves.toBe(true);
+ await expect(peer.start()).resolves.toBe(false);
- const preferences = FakePeerConnection.latest!.codecPreferenceCalls[0]!;
- expect(preferences[0]?.mimeType.toLowerCase()).toBe(`video/${videoCodec}`);
- expect(preferences.map(({ mimeType }) => mimeType.toLowerCase())).toEqual(
- expect.arrayContaining(["video/h264", "video/vp8", "video/rtx"]),
- );
- },
- );
+ expect(FakePeerConnection.latest!.createOfferCallCount).toBe(0);
+ expect(FakePeerConnection.latest!.localDescription).toBeNull();
+ expect(updates.at(-1)?.error).toBe("当前浏览器无法使用 VP8 视频编码");
+ });
+
+ it("fails before creating an offer when codec preference setup fails", async () => {
+ FakePeerConnection.codecPreferenceCallsFailing = 1;
+ const updates: PeerSnapshot[] = [];
+ const peer = createPeer(
+ createStream(createTrack("video", "video"), null),
+ (snapshot) => updates.push(snapshot),
+ );
+
+ await expect(peer.start()).resolves.toBe(false);
+
+ expect(FakePeerConnection.latest!.createOfferCallCount).toBe(0);
+ expect(FakePeerConnection.latest!.localDescription).toBeNull();
+ expect(updates.at(-1)?.error).toBe("当前浏览器无法使用 VP8 视频编码");
+ });
it("applies STUN-only ICE configuration at creation and update", () => {
const peer = createPeer(
diff --git a/tests/protocol.test.ts b/tests/protocol.test.ts
index 0d35c64e..6701098e 100644
--- a/tests/protocol.test.ts
+++ b/tests/protocol.test.ts
@@ -32,12 +32,16 @@ const qualitySettings = {
degradationPreference: "maintain-resolution",
} as const;
-const qualitySettingsWithCodec = {
+const qualitySettingsWithAudio = {
...qualitySettings,
- videoCodec: "h264",
screenAudioQuality: "music",
} as const;
+const legacyCodecQualitySettings = {
+ ...qualitySettings,
+ videoCodec: "vp8",
+} as const;
+
const qualityEvidence = {
type: "viewer-quality-evidence",
guard: {
@@ -67,7 +71,7 @@ const qualityEvidence = {
} as const;
describe("client signaling protocol", () => {
- it("keeps executable senders outside the Browser-only v10 checkpoint", () => {
+ it("keeps executable senders outside the Browser-only v11 checkpoint", () => {
const nativeWire = readFileSync(
join(
import.meta.dirname,
@@ -76,7 +80,7 @@ describe("client signaling protocol", () => {
"utf8",
);
- expect(SIGNALING_PROTOCOL).toBe("screener-v10");
+ expect(SIGNALING_PROTOCOL).toBe("screener-v11");
expect(nativeWire).toMatch(/signalingProtocol\s*=\s*"screener-v6"/);
});
@@ -247,13 +251,13 @@ describe("client signaling protocol", () => {
token,
clientId: "host_client_12345678",
shareGeneration: "share_generation_12345678",
- qualitySettings: qualitySettingsWithCodec,
+ qualitySettings: qualitySettingsWithAudio,
}),
),
).toMatchObject({
role: "host",
shareGeneration: "share_generation_12345678",
- qualitySettings: qualitySettingsWithCodec,
+ qualitySettings: qualitySettingsWithAudio,
});
expect(
clientMessageSchema.safeParse({
@@ -588,7 +592,7 @@ describe("client signaling protocol", () => {
});
it("accepts only strict, bounded quality settings", () => {
- expect(DEFAULT_QUALITY_SETTINGS.videoCodec).toBe("vp8");
+ expect(DEFAULT_QUALITY_SETTINGS).not.toHaveProperty("videoCodec");
expect(
clientMessageSchema.safeParse({
type: "set-quality-settings",
@@ -598,7 +602,7 @@ describe("client signaling protocol", () => {
expect(
clientMessageSchema.safeParse({
type: "set-quality-settings",
- qualitySettings: qualitySettingsWithCodec,
+ qualitySettings: qualitySettingsWithAudio,
}).success,
).toBe(true);
expect(
@@ -628,7 +632,7 @@ describe("client signaling protocol", () => {
{ ...qualitySettings, maxBitrate: 12_000_001 },
{ ...qualitySettings, maxBitrate: 5_000_000.5 },
{ ...qualitySettings, degradationPreference: "automatic" },
- { ...qualitySettings, videoCodec: "vp9" },
+ legacyCodecQualitySettings,
{ ...qualitySettings, screenAudioQuality: "lossless" },
{ ...qualitySettings, screenAudioQuality: 960_000 },
{ ...qualitySettings, codec: "video/VP9" },
diff --git a/tests/quality.test.ts b/tests/quality.test.ts
index 9cf66ca1..a451bea4 100644
--- a/tests/quality.test.ts
+++ b/tests/quality.test.ts
@@ -51,13 +51,7 @@ describe("realtime quality controls", () => {
resolution: "1080p",
maxFramerate: 30,
maxBitrate: 5_000_000,
- videoCodec: "vp8",
});
- expect(
- Object.values(QUALITY_PROFILES).every(
- (profile) => profile.videoCodec === "vp8",
- ),
- ).toBe(true);
});
it("offers 854x480 only through advanced resolution settings", () => {
@@ -126,12 +120,6 @@ describe("realtime quality controls", () => {
).toBe(true);
});
- it("keeps codec selection orthogonal to the recommended quality profile", () => {
- const h264 = { ...QUALITY_PROFILES["1080p60"], videoCodec: "h264" } as const;
- expect(matchingQualityProfileId(h264)).toBe("1080p60");
- expect(qualitySettingsEqual(h264, QUALITY_PROFILES["1080p60"])).toBe(false);
- });
-
it("keeps audio selection orthogonal while defaulting old settings to music", () => {
const saver = {
...QUALITY_PROFILES["1080p60"],
diff --git a/tests/server-signal.test.ts b/tests/server-signal.test.ts
index 0f54912a..4da801a9 100644
--- a/tests/server-signal.test.ts
+++ b/tests/server-signal.test.ts
@@ -1677,27 +1677,23 @@ describe("WebSocket signaling", () => {
});
});
- it("binds the new share codec before routing and permits a new choice after stop", async () => {
+ it("binds new-share quality and preserves active-share quality across reconnect", async () => {
const harness = await startHarness({ peerAssistedMedia: true });
- const h264Settings: QualitySettings = {
- resolution: "1080p",
- maxFramerate: 30,
- maxBitrate: 5_000_000,
- degradationPreference: "balanced",
- videoCodec: "h264",
- screenAudioQuality: "music",
+ const initialSettings: QualitySettings = {
+ resolution: "1440p",
+ maxFramerate: 60,
+ maxBitrate: 8_000_000,
+ degradationPreference: "maintain-resolution",
+ screenAudioQuality: "very-high",
};
- const firstGeneration = "h264_share_generation_12345678";
+ const firstGeneration = "first_share_generation_12345678";
const viewer = await openClient(harness.webSocketUrl);
- const viewerAuth = peerAssisted(
- await authenticate(
- viewer,
- harness.room,
- "viewer",
- "codec-viewer-client",
- ),
+ await authenticate(
+ viewer,
+ harness.room,
+ "viewer",
+ "quality-viewer-client",
);
- expect(viewerAuth.qualitySettings.videoCodec).toBe("vp8");
const host = await openClient(harness.webSocketUrl);
const hostAuth = peerAssisted(
@@ -1705,18 +1701,25 @@ describe("WebSocket signaling", () => {
host,
harness.room,
"host",
- "codec-host-client",
+ "quality-host-client",
1,
firstGeneration,
- { qualitySettings: h264Settings },
+ { qualitySettings: initialSettings },
),
);
- expect(hostAuth.qualitySettings).toEqual(h264Settings);
+ expect(hostAuth.qualitySettings).toEqual(initialSettings);
expect(await viewer.inbox.next("quality-settings")).toEqual({
type: "quality-settings",
- qualitySettings: h264Settings,
+ qualitySettings: initialSettings,
});
+ const reconnectSettings: QualitySettings = {
+ resolution: "480p",
+ maxFramerate: 15,
+ maxBitrate: 2_000_000,
+ degradationPreference: "maintain-framerate",
+ screenAudioQuality: "saver",
+ };
const replaced = new Promise<number>((resolve) =>
host.socket.once("close", (code) => resolve(code)),
);
@@ -1726,52 +1729,35 @@ describe("WebSocket signaling", () => {
reconnectedHost,
harness.room,
"host",
- "codec-host-client",
+ "quality-host-client",
1,
firstGeneration,
- {
- qualitySettings: {
- ...h264Settings,
- videoCodec: "vp8",
- },
- },
+ { qualitySettings: reconnectSettings },
),
);
expect(await replaced).toBe(4001);
- expect(reconnectedAuth.qualitySettings).toEqual(h264Settings);
+ expect(reconnectedAuth.qualitySettings).toEqual(initialSettings);
await expect(
viewer.inbox.next("quality-settings", 30),
).rejects.toThrow("Timed out");
- const updatedH264Settings: QualitySettings = {
- ...h264Settings,
+ const updatedSettings: QualitySettings = {
+ ...initialSettings,
resolution: "720p",
+ maxFramerate: 30,
maxBitrate: 3_000_000,
+ degradationPreference: "balanced",
+ screenAudioQuality: "music",
};
reconnectedHost.socket.send(
JSON.stringify({
type: "set-quality-settings",
- qualitySettings: updatedH264Settings,
+ qualitySettings: updatedSettings,
}),
);
expect(await viewer.inbox.next("quality-settings")).toEqual({
type: "quality-settings",
- qualitySettings: updatedH264Settings,
- });
-
- reconnectedHost.socket.send(
- JSON.stringify({
- type: "set-quality-settings",
- qualitySettings: {
- ...updatedH264Settings,
- videoCodec: "vp8",
- },
- }),
- );
- expect(await reconnectedHost.inbox.next("error")).toEqual({
- type: "error",
- code: "FORBIDDEN",
- message: "视频编码只能在开始分享前选择;请停止分享后重新开始",
+ qualitySettings: updatedSettings,
});
const stopped = new Promise<number>((resolve) =>
@@ -1786,28 +1772,24 @@ describe("WebSocket signaling", () => {
expect(await stopped).toBe(1000);
await viewer.inbox.next("sharing-stopped");
- const vp8Settings: QualitySettings = {
- ...updatedH264Settings,
- videoCodec: "vp8",
- };
const nextHost = await openClient(harness.webSocketUrl);
const nextAuth = peerAssisted(
await authenticate(
nextHost,
harness.room,
"host",
- "codec-host-client",
+ "quality-host-client",
1,
- "vp8_share_generation_12345678",
+ "next_share_generation_12345678",
{
- qualitySettings: vp8Settings,
+ qualitySettings: reconnectSettings,
},
),
);
- expect(nextAuth.qualitySettings).toEqual(vp8Settings);
+ expect(nextAuth.qualitySettings).toEqual(reconnectSettings);
expect(await viewer.inbox.next("quality-settings")).toEqual({
type: "quality-settings",
- qualitySettings: vp8Settings,
+ qualitySettings: reconnectSettings,
});
});
@@ -2567,7 +2549,7 @@ describe("WebSocket signaling", () => {
expect(await closeCode).toBe(1009);
});
- it("terminates an invalid protocol before authentication", async () => {
+ it("terminates stale v10 before authentication", async () => {
const harness = await startHarness();
const invalidClient = await openClient(harness.webSocketUrl);
const closed = new Promise<{ code: number; reason: string }>((resolve) =>
@@ -2579,8 +2561,8 @@ describe("WebSocket signaling", () => {
invalidClient.socket.send(
JSON.stringify({
type: "authenticate",
- protocol: "invalid-protocol",
- roomId: "999999999999",
+ protocol: "screener-v10",
+ roomId: harness.room.roomId,
role: "viewer",
clientId: "invalid-client",
}),
diff --git a/tests/sfu-client.test.ts b/tests/sfu-client.test.ts
index 96e39765..e7386ff3 100644
--- a/tests/sfu-client.test.ts
+++ b/tests/sfu-client.test.ts
@@ -698,41 +698,6 @@ describe("SfuPublisher", () => {
});
});
- it.each(["h264", "vp8"] as const)(
- "passes an explicit %s preference to the SFU publisher",
- async (videoCodec) => {
- const publisher = new SfuPublisher();
- await publisher.connect(connection);
-
- await expect(
- publisher.activate(stream(track("video", "video-1")), {
- ...qualityProfile,
- videoCodec,
- }),
- ).resolves.toBe(true);
-
- expect(
- livekit.state.rooms[0].localParticipant.publishTrack.mock.calls[0]?.[1],
- ).toMatchObject({ videoCodec, backupCodec: false });
- },
- );
-
- it("leaves the SFU codec unset only for an explicit automatic preference", async () => {
- const publisher = new SfuPublisher();
- await publisher.connect(connection);
-
- await expect(
- publisher.activate(stream(track("video", "video-1")), {
- ...qualityProfile,
- videoCodec: "automatic",
- }),
- ).resolves.toBe(true);
-
- expect(
- livekit.state.rooms[0].localParticipant.publishTrack.mock.calls[0]?.[1],
- ).not.toHaveProperty("videoCodec");
- });
-
it("fails closed when initial sender configuration is rejected", async () => {
const disconnected = vi.fn();
const publisher = new SfuPublisher({ onDisconnected: disconnected });