Skip to content

A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.

TypeScript fluxerfluxerapp
23.6 KB
Raw Blame
// SPDX-License-Identifier: AGPL-3.0-or-later

import {Logger} from '@app/features/platform/utils/AppLogger';
import {getElectronAPI, guessPlatform, isDesktop, type NativePlatform} from '@app/features/ui/utils/NativeUtils';
import type {GpuDeviceInfo, GpuInfo} from '@app/types/electron.d';
import type {VideoCodec} from 'livekit-client';

const logger = new Logger('GpuEncoderCapabilities');

export type HardwareEncodeAnswer = 'hardware' | 'software' | 'unknown';

export interface HardwareEncodeReport {
	av1: HardwareEncodeAnswer;
	h265: HardwareEncodeAnswer;
	h264: HardwareEncodeAnswer;
	vp9: HardwareEncodeAnswer;
	vp8: HardwareEncodeAnswer;
	gpuLabel?: string;
	gpuFamily?: string;
	raw?: GpuInfo;
}

const PCI_VENDOR_NVIDIA = 0x10de;
const PCI_VENDOR_AMD = 0x1002;
const PCI_VENDOR_INTEL = 0x8086;
const PCI_VENDOR_APPLE = 0x106b;

interface GpuFamilyRule {
	family: string;
	caps: Pick<HardwareEncodeReport, 'av1' | 'h265' | 'h264' | 'vp9' | 'vp8'>;
}

const NVIDIA_AV1_FAMILIES: GpuFamilyRule = {
	family: 'nvidia-ada-or-blackwell',
	caps: {av1: 'hardware', h265: 'hardware', h264: 'hardware', vp9: 'software', vp8: 'software'},
};
const NVIDIA_PRE_ADA: GpuFamilyRule = {
	family: 'nvidia-pre-ada',
	caps: {av1: 'software', h265: 'hardware', h264: 'hardware', vp9: 'software', vp8: 'software'},
};
const NVIDIA_PRE_MAXWELL2: GpuFamilyRule = {
	family: 'nvidia-pre-maxwell2',
	caps: {av1: 'software', h265: 'software', h264: 'hardware', vp9: 'software', vp8: 'software'},
};
const AMD_RDNA3_PLUS: GpuFamilyRule = {
	family: 'amd-rdna3-plus',
	caps: {av1: 'hardware', h265: 'hardware', h264: 'hardware', vp9: 'software', vp8: 'software'},
};
const AMD_VCN_NO_AV1: GpuFamilyRule = {
	family: 'amd-vcn-pre-rdna3',
	caps: {av1: 'software', h265: 'hardware', h264: 'hardware', vp9: 'software', vp8: 'software'},
};
const INTEL_AV1_FAMILY: GpuFamilyRule = {
	family: 'intel-arc-or-xe-lpg-plus',
	caps: {av1: 'hardware', h265: 'hardware', h264: 'hardware', vp9: 'hardware', vp8: 'software'},
};
const INTEL_GEN9_PLUS: GpuFamilyRule = {
	family: 'intel-gen9-plus-no-av1',
	caps: {av1: 'software', h265: 'hardware', h264: 'hardware', vp9: 'hardware', vp8: 'software'},
};
const APPLE_SILICON: GpuFamilyRule = {
	family: 'apple-silicon',
	caps: {av1: 'software', h265: 'hardware', h264: 'hardware', vp9: 'software', vp8: 'software'},
};
const APPLE_AV1_ENCODE: GpuFamilyRule = {
	family: 'apple-m4-pro-max-or-newer',
	caps: {av1: 'hardware', h265: 'hardware', h264: 'hardware', vp9: 'software', vp8: 'software'},
};
const INTEL_METEOR_LAKE_IDS = new Set([0x7d40, 0x7d45, 0x7d55, 0x7d60, 0x7dd5]);
const INTEL_LUNAR_LAKE_IDS = new Set([0x6420, 0x64a0, 0x64b0]);
const INTEL_ARROW_LAKE_IDS = new Set([0x7d41, 0x7d51, 0x7d67, 0x7dd1, 0xb640]);

function isIntelDg2(deviceId: number): boolean {
	if (deviceId >= 0x5690 && deviceId <= 0x5697) return true;
	if (deviceId >= 0x56a0 && deviceId <= 0x56a6) return true;
	if (deviceId >= 0x56b0 && deviceId <= 0x56b3) return true;
	if (deviceId >= 0x56ba && deviceId <= 0x56bd) return true;
	if (deviceId >= 0x56c0 && deviceId <= 0x56c2) return true;
	return false;
}

function isIntelBattlemage(deviceId: number): boolean {
	return (deviceId >= 0xe200 && deviceId <= 0xe216) || (deviceId >= 0xe220 && deviceId <= 0xe22f);
}

function isIntelPantherLake(deviceId: number): boolean {
	return deviceId >= 0xb080 && deviceId <= 0xb0bf;
}

function classifyIntelByPciId(deviceId: number): GpuFamilyRule | null {
	if (isIntelDg2(deviceId)) return INTEL_AV1_FAMILY;
	if (isIntelBattlemage(deviceId)) return INTEL_AV1_FAMILY;
	if (isIntelPantherLake(deviceId)) return INTEL_AV1_FAMILY;
	if (INTEL_METEOR_LAKE_IDS.has(deviceId)) return INTEL_AV1_FAMILY;
	if (INTEL_LUNAR_LAKE_IDS.has(deviceId)) return INTEL_AV1_FAMILY;
	if (INTEL_ARROW_LAKE_IDS.has(deviceId)) return INTEL_AV1_FAMILY;
	return null;
}

function classifyNvidiaByPciId(deviceId: number): GpuFamilyRule | null {
	if (deviceId >= 0x2900 && deviceId <= 0x2fff) return NVIDIA_AV1_FAMILIES;
	if (deviceId >= 0x2680 && deviceId <= 0x28ff) return NVIDIA_AV1_FAMILIES;
	if (deviceId >= 0x2330 && deviceId <= 0x2339) return NVIDIA_PRE_ADA;
	if (deviceId >= 0x2200 && deviceId <= 0x25ff) return NVIDIA_PRE_ADA;
	if (deviceId >= 0x1e00 && deviceId <= 0x21ff) return NVIDIA_PRE_ADA;
	if (deviceId >= 0x1d80 && deviceId <= 0x1dff) return NVIDIA_PRE_ADA;
	if (deviceId >= 0x1b80 && deviceId <= 0x1d7f) return NVIDIA_PRE_ADA;
	if (deviceId >= 0x1340 && deviceId <= 0x17ff) return NVIDIA_PRE_ADA;
	return null;
}

function classifyAmdByPciId(deviceId: number): GpuFamilyRule | null {
	if (deviceId >= 0x7550 && deviceId <= 0x755f) return AMD_RDNA3_PLUS;
	if (deviceId >= 0x7440 && deviceId <= 0x74ff) return AMD_RDNA3_PLUS;
	if (deviceId >= 0x73a0 && deviceId <= 0x73ff) return AMD_VCN_NO_AV1;
	if (deviceId >= 0x7310 && deviceId <= 0x734f) return AMD_VCN_NO_AV1;
	if (deviceId >= 0x66a0 && deviceId <= 0x66af) return AMD_VCN_NO_AV1;
	if (deviceId === 0x6860 || deviceId === 0x687f) return AMD_VCN_NO_AV1;
	if (deviceId >= 0x67c0 && deviceId <= 0x67ff) return AMD_VCN_NO_AV1;
	return null;
}

function classifyByPciId(vendorId: number, deviceId: number): GpuFamilyRule | null {
	if (!deviceId) return null;
	if (vendorId === PCI_VENDOR_INTEL) return classifyIntelByPciId(deviceId);
	if (vendorId === PCI_VENDOR_NVIDIA) return classifyNvidiaByPciId(deviceId);
	if (vendorId === PCI_VENDOR_AMD) return classifyAmdByPciId(deviceId);
	return null;
}

function classifyByRenderer(renderer: string, vendorId: number): GpuFamilyRule | null {
	const r = renderer;
	if (vendorId === PCI_VENDOR_NVIDIA || /\bNVIDIA\b/i.test(r)) {
		if (/\bRTX\s*(50|60|70|80|90)\d{2}\b/i.test(r)) return NVIDIA_AV1_FAMILIES;
		if (/\bRTX\s*40\d{2}\b/i.test(r)) return NVIDIA_AV1_FAMILIES;
		if (/\bRTX\s*(20|30)\d{2}\b/i.test(r)) return NVIDIA_PRE_ADA;
		if (/\bGTX\s*(9|10|16)\d{2}\b/i.test(r)) return NVIDIA_PRE_ADA;
		if (/\bGTX\s*[78]\d{2}\b/i.test(r)) return NVIDIA_PRE_MAXWELL2;
		if (/\b(L(?:4|20|30|40[SG]?)|RTX\s*Ada|RTX\s*\d{4}\s*Ada|B(?:100|200))\b/i.test(r)) return NVIDIA_AV1_FAMILIES;
		if (/\b(A100|A40|A30|A10|H100|H200|T4|V100|P100|P40|P4|M\d{2,4})\b/i.test(r)) return NVIDIA_PRE_ADA;
		return NVIDIA_PRE_ADA;
	}
	if (vendorId === PCI_VENDOR_AMD || /\b(AMD|Radeon|ATI)\b/i.test(r)) {
		if (/\bRX\s*9\d{3}\b/i.test(r)) return AMD_RDNA3_PLUS;
		if (/\bRX\s*7\d{3}\b/i.test(r)) return AMD_RDNA3_PLUS;
		if (/\bRadeon\s*(7[4-9]\d|8[0-9]\d|9[0-9]\d)M\b/i.test(r)) return AMD_RDNA3_PLUS;
		if (/\b(navi3[1-9]|navi4\d|gfx11(\d{2})?|gfx12(\d{2})?)\b/i.test(r)) return AMD_RDNA3_PLUS;
		if (/\bRX\s*([56])\d{3}\b/i.test(r)) return AMD_VCN_NO_AV1;
		if (/\bRX\s*(Vega|[45]\d{2}|5\d{2}X)\b/i.test(r)) return AMD_VCN_NO_AV1;
		if (/\b(navi2\d|navi1\d|vega|polaris|gfx10\d{2}|gfx9\d{2})\b/i.test(r)) return AMD_VCN_NO_AV1;
		return AMD_VCN_NO_AV1;
	}
	if (vendorId === PCI_VENDOR_INTEL || /\bIntel\b/i.test(r)) {
		if (/\bArc\b/i.test(r)) return INTEL_AV1_FAMILY;
		if (/\bCore\s*Ultra\b/i.test(r)) return INTEL_AV1_FAMILY;
		if (/\b(MTL|LNL|ARL|PTL|BMG|Xe2|Xe-LPG)\b/.test(r)) return INTEL_AV1_FAMILY;
		if (/\b(UHD|Iris|HD)\s*Graphics\b/i.test(r)) return INTEL_GEN9_PLUS;
		return INTEL_GEN9_PLUS;
	}
	if (vendorId === PCI_VENDOR_APPLE || /\bApple\s*(M\d|GPU)\b/i.test(r)) {
		if (/\bApple\s*M([4-9]|\d{2,})\s*(Pro|Max|Ultra)\b/i.test(r)) return APPLE_AV1_ENCODE;
		return APPLE_SILICON;
	}
	return null;
}

function classifyDevice(vendorId: number, deviceId: number, renderer: string): GpuFamilyRule | null {
	return classifyByPciId(vendorId, deviceId) ?? classifyByRenderer(renderer, vendorId);
}

function pickPrimaryDevice(devices: ReadonlyArray<GpuDeviceInfo>): GpuDeviceInfo | undefined {
	return [...devices].sort((a, b) => {
		const score = (device: GpuDeviceInfo): number => {
			let value = 0;
			if (device.active) value += 1000;
			if (device.headless === false) value += 100;
			if (device.dedicatedVideoMemory)
				value += Math.min(500, Math.floor(device.dedicatedVideoMemory / 1024 / 1024 / 1024));
			if (device.integrated === false) value += 50;
			return value;
		};
		return score(b) - score(a);
	})[0];
}

function buildLabel(info: GpuInfo, device: GpuDeviceInfo | undefined): string | undefined {
	const renderer = info.glRenderer;
	const deviceString = device?.deviceString;
	if (deviceString && device?.vendorName && !new RegExp(`\\b${device.vendorName}\\b`, 'i').test(deviceString)) {
		return `${device.vendorName} ${deviceString}`;
	}
	return renderer || deviceString || device?.vendorName || info.machineModelName;
}

function reportFromGpuInfo(info: GpuInfo): HardwareEncodeReport {
	const device = pickPrimaryDevice(info.devices);
	const renderer = [
		info.glRenderer,
		device?.deviceString,
		info.machineModelName,
		info.machineModelVersion,
		device?.vendorName,
	]
		.filter((value): value is string => typeof value === 'string' && value.length > 0)
		.join(' ');
	const vendorId = device?.vendorId ?? 0;
	const deviceId = device?.deviceId ?? 0;
	const rule = classifyDevice(vendorId, deviceId, renderer);
	if (!rule) {
		logger.info('GPU did not match any known family — leaving hardware-encode answers as unknown', {
			renderer,
			vendorId: vendorId ? `0x${vendorId.toString(16)}` : undefined,
			deviceId: deviceId ? `0x${deviceId.toString(16)}` : undefined,
		});
		return {
			av1: 'unknown',
			h265: 'unknown',
			h264: 'unknown',
			vp9: 'unknown',
			vp8: 'unknown',
			gpuLabel: buildLabel(info, device),
			raw: info,
		};
	}
	logger.info('Classified GPU for hardware-encode capability', {family: rule.family, renderer});
	return {
		...rule.caps,
		gpuLabel: buildLabel(info, device),
		gpuFamily: rule.family,
		raw: info,
	};
}

const H264_PROBE_PROFILE_LEVEL_IDS: ReadonlyArray<string> = ['640028', '640c28', '4d0028', '420028', '42e028'];

const H264_ENCODE_PROBE_CONTENT_TYPES: ReadonlyArray<string> = H264_PROBE_PROFILE_LEVEL_IDS.map(
	(profileLevelId) => `video/H264;level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=${profileLevelId}`,
);

const WEBRTC_ENCODE_PROBE_CONTENT_TYPES: Record<VideoCodec, ReadonlyArray<string>> = {
	av1: ['video/AV1'],
	h265: ['video/H265'],
	h264: H264_ENCODE_PROBE_CONTENT_TYPES,
	vp9: ['video/VP9'],
	vp8: ['video/VP8'],
};

export interface EncodeProbeVideoConfig {
	width: number;
	height: number;
	bitrate: number;
	framerate: number;
}

const ENCODE_PROBE_VIDEO_CONFIG: EncodeProbeVideoConfig = {
	width: 1920,
	height: 1080,
	bitrate: 4_500_000,
	framerate: 30,
};

export interface H264HardwareProfileProbe {
	readonly profiles: ReadonlySet<string>;
	readonly probedWidth: number;
	readonly probedHeight: number;
	readonly probedFrameRate: number;
}

interface WebRtcEncodingInfoResult {
	supported?: boolean;
	powerEfficient?: boolean;
}

interface MediaCapabilitiesLike {
	encodingInfo?: (config: unknown) => Promise<WebRtcEncodingInfoResult | undefined>;
}

interface EncodeProbeAnswer {
	supported: boolean;
	powerEfficient: boolean;
}

function getMediaCapabilities(): MediaCapabilitiesLike | null {
	if (typeof navigator === 'undefined') return null;
	const mediaCapabilities = (navigator as Navigator & {mediaCapabilities?: MediaCapabilitiesLike}).mediaCapabilities;
	if (!mediaCapabilities?.encodingInfo) return null;
	return mediaCapabilities;
}

function resolveEncodeProbeValue(value: number | undefined, fallback: number): number {
	return typeof value === 'number' && Number.isFinite(value) && value > 0 ? Math.round(value) : fallback;
}

function resolveEncodeProbeVideoConfig(config: Partial<EncodeProbeVideoConfig> | undefined): EncodeProbeVideoConfig {
	if (!config) return ENCODE_PROBE_VIDEO_CONFIG;
	return {
		width: resolveEncodeProbeValue(config.width, ENCODE_PROBE_VIDEO_CONFIG.width),
		height: resolveEncodeProbeValue(config.height, ENCODE_PROBE_VIDEO_CONFIG.height),
		bitrate: resolveEncodeProbeValue(config.bitrate, ENCODE_PROBE_VIDEO_CONFIG.bitrate),
		framerate: resolveEncodeProbeValue(config.framerate, ENCODE_PROBE_VIDEO_CONFIG.framerate),
	};
}

function encodeProbeCacheKey(video: EncodeProbeVideoConfig): string {
	return `${video.width}x${video.height}@${video.framerate}/${video.bitrate}`;
}

async function probeContentTypeEncodeEfficiency(
	mediaCapabilities: MediaCapabilitiesLike,
	contentType: string,
	video: EncodeProbeVideoConfig,
): Promise<EncodeProbeAnswer | null> {
	try {
		const info = await mediaCapabilities.encodingInfo?.({type: 'webrtc', video: {contentType, ...video}});
		if (!info) return null;
		return {supported: info.supported === true, powerEfficient: info.powerEfficient === true};
	} catch {
		return null;
	}
}

function probeContentTypesEncodeEfficiency(
	mediaCapabilities: MediaCapabilitiesLike,
	contentTypes: ReadonlyArray<string>,
	video: EncodeProbeVideoConfig,
): Promise<Array<EncodeProbeAnswer | null>> {
	return Promise.all(
		contentTypes.map((contentType) => probeContentTypeEncodeEfficiency(mediaCapabilities, contentType, video)),
	);
}

function collapseEncodeProbeAnswers(answers: ReadonlyArray<EncodeProbeAnswer | null>): HardwareEncodeAnswer {
	let sawSupported = false;
	for (const answer of answers) {
		if (!answer?.supported) continue;
		sawSupported = true;
		if (answer.powerEfficient) return 'hardware';
	}
	return sawSupported ? 'software' : 'unknown';
}

const h264HardwareProfileProbes = new Map<string, H264HardwareProfileProbe>();
const pendingH264HardwareProfileProbes = new Map<string, Promise<H264HardwareProfileProbe | null>>();
let latestH264HardwareProfileProbeKey: string | null = null;

function recordH264HardwareProfileProbe(
	answers: ReadonlyArray<EncodeProbeAnswer | null>,
	video: EncodeProbeVideoConfig,
): H264HardwareProfileProbe | null {
	const profiles = new Set<string>();
	let answered = 0;
	answers.forEach((answer, index) => {
		if (!answer) return;
		answered += 1;
		if (answer.supported && answer.powerEfficient) {
			profiles.add(H264_PROBE_PROFILE_LEVEL_IDS[index].slice(0, 4));
		}
	});
	if (answered === 0) return null;
	const probe: H264HardwareProfileProbe = {
		profiles,
		probedWidth: video.width,
		probedHeight: video.height,
		probedFrameRate: video.framerate,
	};
	const key = encodeProbeCacheKey(video);
	h264HardwareProfileProbes.set(key, probe);
	latestH264HardwareProfileProbeKey = key;
	logger.info('Probed which H.264 profiles this host encodes in hardware', {
		profiles: [...profiles],
		width: video.width,
		height: video.height,
		framerate: video.framerate,
	});
	return probe;
}

export function getH264HardwareProfilesSync(): H264HardwareProfileProbe | null {
	if (latestH264HardwareProfileProbeKey === null) return null;
	return h264HardwareProfileProbes.get(latestH264HardwareProfileProbeKey) ?? null;
}

async function probeH264HardwareProfiles(
	config?: Partial<EncodeProbeVideoConfig>,
): Promise<H264HardwareProfileProbe | null> {
	const video = resolveEncodeProbeVideoConfig(config);
	const key = encodeProbeCacheKey(video);
	const cached = h264HardwareProfileProbes.get(key);
	if (cached) {
		latestH264HardwareProfileProbeKey = key;
		return cached;
	}
	const pending = pendingH264HardwareProfileProbes.get(key);
	if (pending) return pending;
	const mediaCapabilities = getMediaCapabilities();
	if (!mediaCapabilities) return null;
	const promise = probeContentTypesEncodeEfficiency(mediaCapabilities, H264_ENCODE_PROBE_CONTENT_TYPES, video)
		.then((answers) => recordH264HardwareProfileProbe(answers, video))
		.finally(() => {
			pendingH264HardwareProfileProbes.delete(key);
		});
	pendingH264HardwareProfileProbes.set(key, promise);
	return promise;
}

async function probeWebRtcEncodeEfficiency(
	config?: Partial<EncodeProbeVideoConfig>,
): Promise<Record<VideoCodec, HardwareEncodeAnswer> | null> {
	const mediaCapabilities = getMediaCapabilities();
	if (!mediaCapabilities) return null;
	const video = resolveEncodeProbeVideoConfig(config);
	const codecs: ReadonlyArray<VideoCodec> = ['av1', 'h265', 'h264', 'vp9', 'vp8'];
	const answers = await Promise.all(
		codecs.map((codec) =>
			probeContentTypesEncodeEfficiency(mediaCapabilities, WEBRTC_ENCODE_PROBE_CONTENT_TYPES[codec], video),
		),
	);
	const result = {} as Record<VideoCodec, HardwareEncodeAnswer>;
	codecs.forEach((codec, index) => {
		const codecAnswers = answers[index] ?? [];
		if (codec === 'h264') recordH264HardwareProfileProbe(codecAnswers, video);
		result[codec] = collapseEncodeProbeAnswers(codecAnswers);
	});
	return result;
}

function reconcileHardwareEncodeReport(
	report: HardwareEncodeReport,
	efficiency: Record<VideoCodec, HardwareEncodeAnswer> | null,
): HardwareEncodeReport {
	if (!efficiency) return report;
	const adjust = (codec: VideoCodec): HardwareEncodeAnswer =>
		efficiency[codec] === 'unknown' ? report[codec] : efficiency[codec];
	return {
		...report,
		av1: adjust('av1'),
		h265: adjust('h265'),
		h264: adjust('h264'),
		vp9: adjust('vp9'),
		vp8: adjust('vp8'),
	};
}

interface HardwareVideoEncodeProfile {
	codec: VideoCodec;
	profile: string;
	maxWidth: number;
	maxHeight: number;
	maxFrameRate: number | null;
}

interface HardwareVideoEncodeProfileCandidate {
	codec: VideoCodec;
	profile: string;
	codecString: string;
}

interface VideoEncoderSupportLike {
	supported?: boolean;
}

interface VideoEncoderLike {
	isConfigSupported?: (config: unknown) => Promise<VideoEncoderSupportLike | undefined>;
}

const HARDWARE_VIDEO_ENCODE_PROFILE_CANDIDATES: ReadonlyArray<HardwareVideoEncodeProfileCandidate> = [
	{codec: 'h264', profile: 'constrained-baseline', codecString: 'avc1.42e033'},
	{codec: 'h264', profile: 'main', codecString: 'avc1.4d0033'},
	{codec: 'h264', profile: 'high', codecString: 'avc1.640033'},
	{codec: 'vp8', profile: 'any', codecString: 'vp8'},
	{codec: 'vp9', profile: 'profile-0', codecString: 'vp09.00.51.08'},
	{codec: 'h265', profile: 'main', codecString: 'hvc1.1.6.L153.B0'},
	{codec: 'av1', profile: 'main', codecString: 'av01.0.13M.08'},
];

const HARDWARE_VIDEO_ENCODE_PROBE_SIZES: ReadonlyArray<{width: number; height: number}> = [
	{width: 1280, height: 720},
	{width: 1920, height: 1080},
	{width: 2560, height: 1440},
	{width: 3840, height: 2160},
];

const HARDWARE_VIDEO_ENCODE_PROBE_FRAME_RATES: ReadonlyArray<number> = [30, 60, 120];

function getVideoEncoder(): VideoEncoderLike | null {
	const encoder = (globalThis as {VideoEncoder?: VideoEncoderLike}).VideoEncoder;
	return encoder?.isConfigSupported ? encoder : null;
}

async function isHardwareEncodeConfigSupported(
	encoder: VideoEncoderLike,
	codecString: string,
	size: {width: number; height: number},
	framerate?: number,
): Promise<boolean> {
	try {
		const support = await encoder.isConfigSupported?.({
			codec: codecString,
			width: size.width,
			height: size.height,
			...(framerate === undefined ? {} : {framerate}),
			hardwareAcceleration: 'prefer-hardware',
		});
		return support?.supported === true;
	} catch {
		return false;
	}
}

async function probeHardwareVideoEncodeProfile(
	encoder: VideoEncoderLike,
	candidate: HardwareVideoEncodeProfileCandidate,
): Promise<HardwareVideoEncodeProfile | null> {
	let maxSize: {width: number; height: number} | null = null;
	for (const size of HARDWARE_VIDEO_ENCODE_PROBE_SIZES) {
		if (!(await isHardwareEncodeConfigSupported(encoder, candidate.codecString, size))) break;
		maxSize = size;
	}
	if (maxSize === null) return null;
	let maxFrameRate: number | null = null;
	for (const framerate of HARDWARE_VIDEO_ENCODE_PROBE_FRAME_RATES) {
		const supported = await isHardwareEncodeConfigSupported(
			encoder,
			candidate.codecString,
			HARDWARE_VIDEO_ENCODE_PROBE_SIZES[0],
			framerate,
		);
		if (!supported) break;
		maxFrameRate = framerate;
	}
	return {
		codec: candidate.codec,
		profile: candidate.profile,
		maxWidth: maxSize.width,
		maxHeight: maxSize.height,
		maxFrameRate,
	};
}

async function probeHardwareVideoEncodeProfiles(
	encoder: VideoEncoderLike | null,
): Promise<ReadonlyArray<HardwareVideoEncodeProfile> | null> {
	if (!encoder) return null;
	const probed = await Promise.all(
		HARDWARE_VIDEO_ENCODE_PROFILE_CANDIDATES.map((candidate) => probeHardwareVideoEncodeProfile(encoder, candidate)),
	);
	return probed.filter((profile): profile is HardwareVideoEncodeProfile => profile !== null);
}

export function describeHardwareVideoEncodeProfiles(
	profiles: ReadonlyArray<HardwareVideoEncodeProfile> | null,
): string | Array<string> {
	if (profiles === null) return 'unknown: WebCodecs hardware encode probe unavailable';
	if (profiles.length === 0) return 'none: Chromium has no hardware video encoder for any probed profile';
	return profiles.map((profile) => {
		const frameRate = profile.maxFrameRate === null ? 'unknown fps' : `${profile.maxFrameRate} fps`;
		return `${profile.codec} ${profile.profile} up to ${profile.maxWidth}x${profile.maxHeight} at ${frameRate}`;
	});
}

let hardwareVideoEncodeProfiles: ReadonlyArray<HardwareVideoEncodeProfile> | null = null;
let pendingHardwareVideoEncodeProfiles: Promise<ReadonlyArray<HardwareVideoEncodeProfile> | null> | null = null;

export function loadHardwareVideoEncodeProfiles(): Promise<ReadonlyArray<HardwareVideoEncodeProfile> | null> {
	if (hardwareVideoEncodeProfiles) return Promise.resolve(hardwareVideoEncodeProfiles);
	if (pendingHardwareVideoEncodeProfiles) return pendingHardwareVideoEncodeProfiles;
	pendingHardwareVideoEncodeProfiles = probeHardwareVideoEncodeProfiles(getVideoEncoder())
		.then((profiles) => {
			hardwareVideoEncodeProfiles = profiles;
			logger.info('Probed hardware video encode profiles', {profiles: describeHardwareVideoEncodeProfiles(profiles)});
			return profiles;
		})
		.finally(() => {
			pendingHardwareVideoEncodeProfiles = null;
		});
	return pendingHardwareVideoEncodeProfiles;
}

export interface SoftwareVideoEncodeExpectationInput {
	platform: NativePlatform;
	h264HardwareProfileCount: number | null;
	hardwareEncodeProfiles: ReadonlyArray<HardwareVideoEncodeProfile> | null;
}

function isSoftwareVideoEncodeExpected(input: SoftwareVideoEncodeExpectationInput): boolean {
	if (input.platform !== 'linux') return false;
	if ((input.h264HardwareProfileCount ?? 0) > 0) return false;
	if (input.hardwareEncodeProfiles !== null) return input.hardwareEncodeProfiles.length === 0;
	return input.h264HardwareProfileCount === 0;
}

export function isSoftwareVideoEncodeExpectedSync(): boolean {
	return isSoftwareVideoEncodeExpected({
		platform: guessPlatform(),
		h264HardwareProfileCount: getH264HardwareProfilesSync()?.profiles.size ?? null,
		hardwareEncodeProfiles: hardwareVideoEncodeProfiles,
	});
}

let cachedReport: HardwareEncodeReport | null = null;
let pendingPromise: Promise<HardwareEncodeReport | null> | null = null;

function fetchReport(): Promise<HardwareEncodeReport | null> {
	if (!isDesktop()) {
		return Promise.all([probeH264HardwareProfiles(), loadHardwareVideoEncodeProfiles()]).then(() => null);
	}
	const electron = getElectronAPI();
	if (!electron?.getGpuInfo) return loadHardwareVideoEncodeProfiles().then(() => null);
	return Promise.allSettled([
		electron.getGpuInfo(),
		probeWebRtcEncodeEfficiency(),
		loadHardwareVideoEncodeProfiles(),
	]).then(([gpuResult, probeResult]) => {
		if (gpuResult.status !== 'fulfilled') {
			logger.warn('Failed to fetch GPU info from Electron main', {error: gpuResult.reason});
			return null;
		}
		const info = gpuResult.value;
		const baseReport = reportFromGpuInfo(info);
		const efficiency = probeResult.status === 'fulfilled' ? probeResult.value : null;
		const report = reconcileHardwareEncodeReport(baseReport, efficiency);
		logger.info('Reconciled hardware-encode answers against the WebRTC encode probe', {
			probe: efficiency,
			av1: report.av1,
			h265: report.h265,
			h264: report.h264,
			vp9: report.vp9,
			vp8: report.vp8,
		});
		cachedReport = report;
		return report;
	});
}

export function loadGpuEncoderReport(): Promise<HardwareEncodeReport | null> {
	if (cachedReport) return Promise.resolve(cachedReport);
	if (pendingPromise) return pendingPromise;
	pendingPromise = fetchReport().finally(() => {
		pendingPromise = null;
	});
	return pendingPromise;
}

export function getGpuEncoderReportSync(): HardwareEncodeReport | null {
	return cachedReport;
}

if (typeof window !== 'undefined' && isDesktop()) {
	void loadGpuEncoderReport();
}