Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

Clamp AVC level and patch MP4 for iOS

Richie McIlroy40133f29459c
diff --git a/apps/web/__tests__/unit/avc-level-clamp.test.ts b/apps/web/__tests__/unit/avc-level-clamp.test.ts
new file mode 100644
index 000000000..2d485ad16
--- /dev/null
+++ b/apps/web/__tests__/unit/avc-level-clamp.test.ts
@@ -0,0 +1,119 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import {
+ installAvcLevelClamp,
+ pickMobileSafeAvcCodec,
+ rewriteAvcCodecString,
+} from "@/app/(org)/dashboard/caps/components/web-recorder-dialog/avc-level-clamp";
+
+describe("pickMobileSafeAvcCodec", () => {
+ it("returns Level 4.2 for 1080p and below", () => {
+ expect(pickMobileSafeAvcCodec(1920, 1080)).toBe("avc1.64002A");
+ expect(pickMobileSafeAvcCodec(1280, 720)).toBe("avc1.64002A");
+ expect(pickMobileSafeAvcCodec(1920, 1046)).toBe("avc1.64002A");
+ });
+
+ it("returns Level 5.1 for 4K and below", () => {
+ expect(pickMobileSafeAvcCodec(3840, 2160)).toBe("avc1.640033");
+ expect(pickMobileSafeAvcCodec(2560, 1440)).toBe("avc1.640033");
+ });
+
+ it("returns Level 5.2 for sources above 4K", () => {
+ expect(pickMobileSafeAvcCodec(5120, 2880)).toBe("avc1.640034");
+ });
+
+ it("falls back to Level 4.2 when dimensions are missing", () => {
+ expect(pickMobileSafeAvcCodec(undefined, undefined)).toBe("avc1.64002A");
+ expect(pickMobileSafeAvcCodec(0, 0)).toBe("avc1.64002A");
+ });
+});
+
+describe("rewriteAvcCodecString", () => {
+ it("rewrites high-level avc1 strings to a mobile-safe level", () => {
+ expect(rewriteAvcCodecString("avc1.64003D", 1920, 1080)).toBe(
+ "avc1.64002A",
+ );
+ expect(rewriteAvcCodecString("avc1.64003D", 3840, 2160)).toBe(
+ "avc1.640033",
+ );
+ });
+
+ it("preserves non-avc codec strings untouched", () => {
+ expect(rewriteAvcCodecString("vp09.00.10.08", 1920, 1080)).toBe(
+ "vp09.00.10.08",
+ );
+ expect(rewriteAvcCodecString("hvc1.1.6.L120.90", 1920, 1080)).toBe(
+ "hvc1.1.6.L120.90",
+ );
+ });
+});
+
+describe("installAvcLevelClamp", () => {
+ const originalVideoEncoder = (
+ globalThis as { VideoEncoder?: typeof VideoEncoder }
+ ).VideoEncoder;
+
+ afterEach(() => {
+ if (originalVideoEncoder === undefined) {
+ delete (globalThis as { VideoEncoder?: typeof VideoEncoder })
+ .VideoEncoder;
+ } else {
+ (globalThis as { VideoEncoder?: typeof VideoEncoder }).VideoEncoder =
+ originalVideoEncoder;
+ }
+ });
+
+ it("clamps avc1 codec strings passed to VideoEncoder.configure", () => {
+ const configureSpy = vi.fn();
+ class FakeVideoEncoder {
+ configure(config: VideoEncoderConfig) {
+ configureSpy(config);
+ }
+ }
+
+ (globalThis as { VideoEncoder?: unknown }).VideoEncoder = FakeVideoEncoder;
+
+ const restore = installAvcLevelClamp();
+
+ try {
+ const encoder = new FakeVideoEncoder();
+ encoder.configure({
+ codec: "avc1.64003D",
+ width: 1920,
+ height: 1080,
+ } as VideoEncoderConfig);
+
+ expect(configureSpy).toHaveBeenCalledWith(
+ expect.objectContaining({
+ codec: "avc1.64002A",
+ width: 1920,
+ height: 1080,
+ }),
+ );
+ } finally {
+ restore();
+ }
+ });
+
+ it("is a no-op when VideoEncoder is unavailable", () => {
+ delete (globalThis as { VideoEncoder?: typeof VideoEncoder }).VideoEncoder;
+ const restore = installAvcLevelClamp();
+ expect(typeof restore).toBe("function");
+ restore();
+ });
+
+ it("restores the original configure implementation", () => {
+ const configureSpy = vi.fn();
+ class FakeVideoEncoder {
+ configure(config: VideoEncoderConfig) {
+ configureSpy(config);
+ }
+ }
+ (globalThis as { VideoEncoder?: unknown }).VideoEncoder = FakeVideoEncoder;
+
+ const originalConfigure = FakeVideoEncoder.prototype.configure;
+ const restore = installAvcLevelClamp();
+ restore();
+
+ expect(FakeVideoEncoder.prototype.configure).toBe(originalConfigure);
+ });
+});
diff --git a/apps/web/__tests__/unit/mp4-level-patch.test.ts b/apps/web/__tests__/unit/mp4-level-patch.test.ts
new file mode 100644
index 000000000..026f75eeb
--- /dev/null
+++ b/apps/web/__tests__/unit/mp4-level-patch.test.ts
@@ -0,0 +1,217 @@
+import { describe, expect, it, vi } from "vitest";
+import {
+ createLevelPatchedMp4ObjectUrl,
+ isIosSafari,
+ patchMp4AvcLevel,
+ probeAvcLevelFromUrl,
+ readAvcLevelFromMp4Prefix,
+} from "@/app/s/[videoId]/_components/mp4-level-patch";
+
+type BuiltAvcCFixture = {
+ bytes: Uint8Array;
+ avcCLevelOffset: number;
+ spsLevelOffset: number;
+};
+
+function buildAvcCFixture(level: number): BuiltAvcCFixture {
+ const prefix = [0x00, 0x00, 0x00, 0x30];
+ const fourcc = [0x61, 0x76, 0x63, 0x43];
+ const avcCHeader = [0x01, 0x64, 0x00, level, 0xff, 0xe1];
+
+ const sps = [
+ 0x67,
+ 0x64,
+ 0x00,
+ level,
+ 0xac,
+ 0xb2,
+ 0x00,
+ 0x80,
+ 0x11,
+ 0x7f,
+ 0xe0,
+ 0x00,
+ 0x02,
+ ];
+ const spsLen = sps.length;
+ const spsLenBytes = [(spsLen >> 8) & 0xff, spsLen & 0xff];
+
+ const ppsCountAndLen = [0x01];
+ const pps = [0x68, 0xeb, 0xe3, 0xcb, 0x22, 0xc0];
+ const ppsLen = pps.length;
+ const ppsLenBytes = [(ppsLen >> 8) & 0xff, ppsLen & 0xff];
+
+ const flat = [
+ ...prefix,
+ ...fourcc,
+ ...avcCHeader,
+ ...spsLenBytes,
+ ...sps,
+ ...ppsCountAndLen,
+ ...ppsLenBytes,
+ ...pps,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ ];
+
+ const bytes = new Uint8Array(flat);
+ const fourccStart = prefix.length;
+ const payloadStart = fourccStart + fourcc.length;
+ const avcCLevelOffset = payloadStart + 3;
+ const spsStart = payloadStart + avcCHeader.length + spsLenBytes.length;
+ const spsLevelOffset = spsStart + 3;
+
+ return { bytes, avcCLevelOffset, spsLevelOffset };
+}
+
+describe("patchMp4AvcLevel", () => {
+ it("rewrites both avcC level_idc and embedded SPS level_idc when source exceeds ceiling", () => {
+ const { bytes, avcCLevelOffset, spsLevelOffset } = buildAvcCFixture(0x3d);
+ const result = patchMp4AvcLevel(bytes);
+
+ expect(result.patched).toBe(true);
+ expect(result.originalLevel).toBe(0x3d);
+ expect(bytes[avcCLevelOffset]).toBe(0x2a);
+ expect(bytes[spsLevelOffset]).toBe(0x2a);
+ });
+
+ it("is a no-op when the level is already within iOS limits", () => {
+ const { bytes, avcCLevelOffset } = buildAvcCFixture(0x2a);
+ const result = patchMp4AvcLevel(bytes);
+
+ expect(result.patched).toBe(false);
+ expect(result.originalLevel).toBe(0x2a);
+ expect(bytes[avcCLevelOffset]).toBe(0x2a);
+ });
+
+ it("respects custom ceiling and target parameters", () => {
+ const { bytes, avcCLevelOffset, spsLevelOffset } = buildAvcCFixture(0x33);
+ const result = patchMp4AvcLevel(bytes, {
+ maxAllowedLevel: 0x29,
+ targetLevel: 0x28,
+ });
+
+ expect(result.patched).toBe(true);
+ expect(result.originalLevel).toBe(0x33);
+ expect(bytes[avcCLevelOffset]).toBe(0x28);
+ expect(bytes[spsLevelOffset]).toBe(0x28);
+ });
+
+ it("leaves buffers without avcC untouched", () => {
+ const bytes = new Uint8Array([0x00, 0x01, 0x02, 0x03, 0x04, 0x05]);
+ const snapshot = Uint8Array.from(bytes);
+ const result = patchMp4AvcLevel(bytes);
+
+ expect(result.patched).toBe(false);
+ expect(result.originalLevel).toBe(null);
+ expect(bytes).toEqual(snapshot);
+ });
+});
+
+describe("readAvcLevelFromMp4Prefix", () => {
+ it("returns the observed AVCLevelIndication byte", () => {
+ const { bytes } = buildAvcCFixture(0x3d);
+ expect(readAvcLevelFromMp4Prefix(bytes)).toBe(0x3d);
+ });
+
+ it("returns null when avcC is not present in the slice", () => {
+ const bytes = new Uint8Array([0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06]);
+ expect(readAvcLevelFromMp4Prefix(bytes)).toBe(null);
+ });
+});
+
+describe("isIosSafari", () => {
+ it("detects iPhone Safari user agents", () => {
+ expect(
+ isIosSafari(
+ "Mozilla/5.0 (iPhone; CPU iPhone OS 17_2 like Mac OS X) AppleWebKit/605.1.15 Version/17.2 Mobile/15E148 Safari/604.1",
+ ),
+ ).toBe(true);
+ });
+
+ it("returns false for Android Chrome", () => {
+ expect(
+ isIosSafari(
+ "Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 Chrome/120.0.0.0 Mobile Safari/537.36",
+ ),
+ ).toBe(false);
+ });
+
+ it("returns false for desktop Chrome", () => {
+ expect(
+ isIosSafari(
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36",
+ ),
+ ).toBe(false);
+ });
+});
+
+describe("probeAvcLevelFromUrl", () => {
+ it("reads the level from a Range response", async () => {
+ const { bytes } = buildAvcCFixture(0x3d);
+ const fetchImpl = vi.fn(async () => {
+ return new Response(bytes, {
+ status: 206,
+ headers: { "content-range": `bytes 0-${bytes.byteLength - 1}/99999` },
+ });
+ }) as unknown as typeof fetch;
+
+ const level = await probeAvcLevelFromUrl("https://example/video.mp4", {
+ fetchImpl,
+ rangeBytes: bytes.byteLength,
+ });
+
+ expect(level).toBe(0x3d);
+ expect(fetchImpl).toHaveBeenCalledWith(
+ "https://example/video.mp4",
+ expect.objectContaining({
+ headers: { Range: `bytes=0-${bytes.byteLength - 1}` },
+ }),
+ );
+ });
+
+ it("returns null on network failure", async () => {
+ const fetchImpl = vi.fn(async () => {
+ throw new TypeError("network");
+ }) as unknown as typeof fetch;
+
+ const level = await probeAvcLevelFromUrl("https://example/video.mp4", {
+ fetchImpl,
+ });
+ expect(level).toBe(null);
+ });
+});
+
+describe("createLevelPatchedMp4ObjectUrl", () => {
+ const originalCreateObjectURL = URL.createObjectURL;
+
+ it("returns a patched object URL when the level is too high", async () => {
+ const { bytes } = buildAvcCFixture(0x3d);
+ const fetchImpl = vi.fn(async () => {
+ return new Response(bytes.slice(), {
+ status: 200,
+ headers: { "content-type": "video/mp4" },
+ });
+ }) as unknown as typeof fetch;
+
+ URL.createObjectURL = vi.fn(
+ () => "blob:mock",
+ ) as typeof URL.createObjectURL;
+
+ try {
+ const result = await createLevelPatchedMp4ObjectUrl(
+ "https://example/video.mp4",
+ { fetchImpl },
+ );
+
+ expect(result).not.toBeNull();
+ expect(result?.patched).toBe(true);
+ expect(result?.originalLevel).toBe(0x3d);
+ expect(result?.objectUrl).toBe("blob:mock");
+ } finally {
+ URL.createObjectURL = originalCreateObjectURL;
+ }
+ });
+});
diff --git a/apps/web/app/(org)/dashboard/caps/components/web-recorder-dialog/avc-level-clamp.ts b/apps/web/app/(org)/dashboard/caps/components/web-recorder-dialog/avc-level-clamp.ts
new file mode 100644
index 000000000..c0658d801
--- /dev/null
+++ b/apps/web/app/(org)/dashboard/caps/components/web-recorder-dialog/avc-level-clamp.ts
@@ -0,0 +1,104 @@
+const MAX_LEVEL_4_2_WIDTH = 2048;
+const MAX_LEVEL_4_2_HEIGHT = 1088;
+const MAX_LEVEL_5_1_WIDTH = 4096;
+const MAX_LEVEL_5_1_HEIGHT = 2304;
+
+const LEVEL_4_2_CODEC = "avc1.64002A";
+const LEVEL_5_1_CODEC = "avc1.640033";
+const LEVEL_5_2_CODEC = "avc1.640034";
+
+export function pickMobileSafeAvcCodec(
+ width: number | undefined,
+ height: number | undefined,
+): string {
+ const w = typeof width === "number" && width > 0 ? width : 0;
+ const h = typeof height === "number" && height > 0 ? height : 0;
+
+ if (w === 0 || h === 0) {
+ return LEVEL_4_2_CODEC;
+ }
+
+ if (w <= MAX_LEVEL_4_2_WIDTH && h <= MAX_LEVEL_4_2_HEIGHT) {
+ return LEVEL_4_2_CODEC;
+ }
+
+ if (w <= MAX_LEVEL_5_1_WIDTH && h <= MAX_LEVEL_5_1_HEIGHT) {
+ return LEVEL_5_1_CODEC;
+ }
+
+ return LEVEL_5_2_CODEC;
+}
+
+export function rewriteAvcCodecString(
+ codec: string,
+ width: number | undefined,
+ height: number | undefined,
+): string {
+ if (!codec.toLowerCase().startsWith("avc1.")) {
+ return codec;
+ }
+ return pickMobileSafeAvcCodec(width, height);
+}
+
+type AvcClampCleanup = () => void;
+
+export function installAvcLevelClamp(): AvcClampCleanup {
+ if (
+ typeof globalThis === "undefined" ||
+ typeof (globalThis as { VideoEncoder?: typeof VideoEncoder })
+ .VideoEncoder === "undefined"
+ ) {
+ return () => {};
+ }
+
+ const prototype = VideoEncoder.prototype;
+ const descriptor = Object.getOwnPropertyDescriptor(prototype, "configure");
+
+ if (!descriptor || typeof descriptor.value !== "function") {
+ return () => {};
+ }
+
+ const originalConfigure = descriptor.value as (
+ this: VideoEncoder,
+ config: VideoEncoderConfig,
+ ) => void;
+
+ const patched = function patchedConfigure(
+ this: VideoEncoder,
+ config: VideoEncoderConfig,
+ ) {
+ const nextCodec = rewriteAvcCodecString(
+ config.codec,
+ config.width,
+ config.height,
+ );
+
+ if (nextCodec === config.codec) {
+ return originalConfigure.call(this, config);
+ }
+
+ const patchedConfig: VideoEncoderConfig = {
+ ...config,
+ codec: nextCodec,
+ };
+ return originalConfigure.call(this, patchedConfig);
+ };
+
+ try {
+ Object.defineProperty(prototype, "configure", {
+ ...descriptor,
+ value: patched,
+ });
+ } catch {
+ return () => {};
+ }
+
+ let restored = false;
+ return () => {
+ if (restored) return;
+ restored = true;
+ try {
+ Object.defineProperty(prototype, "configure", descriptor);
+ } catch {}
+ };
+}
diff --git a/apps/web/app/(org)/dashboard/caps/components/web-recorder-dialog/recording-conversion.ts b/apps/web/app/(org)/dashboard/caps/components/web-recorder-dialog/recording-conversion.ts
index 49ab67468..93da2fecd 100644
--- a/apps/web/app/(org)/dashboard/caps/components/web-recorder-dialog/recording-conversion.ts
+++ b/apps/web/app/(org)/dashboard/caps/components/web-recorder-dialog/recording-conversion.ts
@@ -1,4 +1,5 @@
import type { UploadStatus } from "../../UploadingContext";
+import { installAvcLevelClamp } from "./avc-level-clamp";
import type { VideoId } from "./web-recorder-types";
const MAX_THUMBNAIL_WIDTH = 1000;
@@ -109,24 +110,31 @@ export const convertToMp4 = async (
const file = new File([blob], "recording.webm", { type: blob.type });
const { convertMedia } = await import("@remotion/webcodecs");
- const result = await convertMedia({
- src: file,
- container: "mp4",
- videoCodec: "h264",
- ...(hasAudio ? { audioCodec: "aac" as const } : {}),
- onProgress: ({ overallProgress }) => {
- if (overallProgress !== null) {
- const percent = Math.min(100, Math.max(0, overallProgress * 100));
- setUploadStatus({
- status: "converting",
- capId: currentVideoId,
- progress: percent,
- });
- }
- },
- });
+ const restoreAvcLevelClamp = installAvcLevelClamp();
- const savedFile = await result.save();
+ let savedFile: Blob;
+ try {
+ const result = await convertMedia({
+ src: file,
+ container: "mp4",
+ videoCodec: "h264",
+ ...(hasAudio ? { audioCodec: "aac" as const } : {}),
+ onProgress: ({ overallProgress }) => {
+ if (overallProgress !== null) {
+ const percent = Math.min(100, Math.max(0, overallProgress * 100));
+ setUploadStatus({
+ status: "converting",
+ capId: currentVideoId,
+ progress: percent,
+ });
+ }
+ },
+ });
+
+ savedFile = await result.save();
+ } finally {
+ restoreAvcLevelClamp();
+ }
if (savedFile.size === 0) {
throw new Error("Conversion produced empty file");
}
diff --git a/apps/web/app/s/[videoId]/_components/CapVideoPlayer.tsx b/apps/web/app/s/[videoId]/_components/CapVideoPlayer.tsx
index 32afbddfc..4988b9d23 100644
--- a/apps/web/app/s/[videoId]/_components/CapVideoPlayer.tsx
+++ b/apps/web/app/s/[videoId]/_components/CapVideoPlayer.tsx
@@ -13,6 +13,12 @@ import { useCallback, useEffect, useRef, useState } from "react";
import { toast } from "sonner";
import { retryVideoProcessing } from "@/actions/video/retry-processing";
import CommentStamp from "./CommentStamp";
+import {
+ AVC_LEVEL_IOS_HARDWARE_CEILING,
+ createLevelPatchedMp4ObjectUrl,
+ isIosSafari,
+ probeAvcLevelFromUrl,
+} from "./mp4-level-patch";
import {
canRetryFailedProcessing,
getUploadFailureMessage,
@@ -143,6 +149,9 @@ export function CapVideoPlayer({
const [playerDuration, setPlayerDuration] = useState(fallbackDuration ?? 0);
const [preferredSource, setPreferredSource] = useState<"mp4" | "raw">("mp4");
const [hasTriedRawFallback, setHasTriedRawFallback] = useState(false);
+ const [iosLevelPatchedUrl, setIosLevelPatchedUrl] = useState<string | null>(
+ null,
+ );
const queryClient = useQueryClient();
useEffect(() => {
@@ -201,6 +210,73 @@ export function CapVideoPlayer({
setHasTriedRawFallback(false);
}, [videoSrc, rawFallbackSrc]);
+ useEffect(() => {
+ const resolvedUrl = resolvedSrc.data?.url;
+ const resolvedType = resolvedSrc.data?.type;
+
+ setIosLevelPatchedUrl((previous) => {
+ if (previous) URL.revokeObjectURL(previous);
+ return null;
+ });
+
+ if (!resolvedUrl || resolvedType !== "mp4") {
+ return;
+ }
+
+ if (
+ typeof window === "undefined" ||
+ !isIosSafari(window.navigator?.userAgent)
+ ) {
+ return;
+ }
+
+ const controller = new AbortController();
+ let cancelled = false;
+ let createdUrl: string | null = null;
+
+ (async () => {
+ const observedLevel = await probeAvcLevelFromUrl(resolvedUrl, {
+ signal: controller.signal,
+ });
+
+ if (cancelled) return;
+ if (observedLevel === null) return;
+ if (observedLevel <= AVC_LEVEL_IOS_HARDWARE_CEILING) return;
+
+ const patched = await createLevelPatchedMp4ObjectUrl(resolvedUrl, {
+ signal: controller.signal,
+ });
+
+ if (cancelled || !patched) {
+ if (patched) URL.revokeObjectURL(patched.objectUrl);
+ return;
+ }
+
+ if (!patched.patched) {
+ URL.revokeObjectURL(patched.objectUrl);
+ return;
+ }
+
+ createdUrl = patched.objectUrl;
+ setIosLevelPatchedUrl(patched.objectUrl);
+ })();
+
+ return () => {
+ cancelled = true;
+ controller.abort();
+ if (createdUrl) URL.revokeObjectURL(createdUrl);
+ };
+ }, [resolvedSrc.data?.url, resolvedSrc.data?.type]);
+
+ useEffect(() => {
+ return () => {
+ setIosLevelPatchedUrl((previous) => {
+ if (previous) URL.revokeObjectURL(previous);
+ return null;
+ });
+ };
+ }, []);
+
// Track video duration for comment markers
useEffect(() => {
setPlayerDuration(fallbackDuration ?? 0);
@@ -571,7 +647,7 @@ export function CapVideoPlayer({
)}
{resolvedSrc.data && (
<MediaPlayerVideo
- src={resolvedSrc.data.url}
+ src={iosLevelPatchedUrl ?? resolvedSrc.data.url}
ref={videoRef}
onLoadedData={() => {
setVideoLoaded(true);
diff --git a/apps/web/app/s/[videoId]/_components/mp4-level-patch.ts b/apps/web/app/s/[videoId]/_components/mp4-level-patch.ts
new file mode 100644
index 000000000..3c56ea802
--- /dev/null
+++ b/apps/web/app/s/[videoId]/_components/mp4-level-patch.ts
@@ -0,0 +1,191 @@
+export const AVC_LEVEL_IOS_HARDWARE_CEILING = 0x34;
+export const AVC_LEVEL_MOBILE_SAFE_TARGET = 0x2a;
+
+const AVCC_FOURCC_A = 0x61;
+const AVCC_FOURCC_V = 0x76;
+const AVCC_FOURCC_C = 0x63;
+const AVCC_FOURCC_UPPER_C = 0x43;
+
+const AVC_PROBE_RANGE_BYTES = 256 * 1024;
+
+export type PatchMp4AvcLevelResult = {
+ patched: boolean;
+ originalLevel: number | null;
+};
+
+export function patchMp4AvcLevel(
+ bytes: Uint8Array,
+ options?: {
+ maxAllowedLevel?: number;
+ targetLevel?: number;
+ },
+): PatchMp4AvcLevelResult {
+ const maxAllowed = options?.maxAllowedLevel ?? AVC_LEVEL_IOS_HARDWARE_CEILING;
+ const target = options?.targetLevel ?? AVC_LEVEL_MOBILE_SAFE_TARGET;
+
+ let patched = false;
+ let firstObservedLevel: number | null = null;
+
+ for (let i = 0; i + 16 < bytes.length; i++) {
+ if (
+ bytes[i] !== AVCC_FOURCC_A ||
+ bytes[i + 1] !== AVCC_FOURCC_V ||
+ bytes[i + 2] !== AVCC_FOURCC_C ||
+ bytes[i + 3] !== AVCC_FOURCC_UPPER_C
+ ) {
+ continue;
+ }
+
+ const payloadStart = i + 4;
+ const levelIndicationOffset = payloadStart + 3;
+
+ if (levelIndicationOffset >= bytes.length) continue;
+
+ if (bytes[payloadStart] !== 0x01) continue;
+
+ const observed = bytes[levelIndicationOffset];
+ if (observed === undefined) continue;
+ if (firstObservedLevel === null) firstObservedLevel = observed;
+
+ if (observed <= maxAllowed) {
+ continue;
+ }
+
+ bytes[levelIndicationOffset] = target;
+ patched = true;
+
+ const numSpsByte = bytes[payloadStart + 5];
+ if (numSpsByte === undefined) continue;
+ const numSps = numSpsByte & 0x1f;
+ let cursor = payloadStart + 6;
+
+ for (let s = 0; s < numSps && cursor + 2 <= bytes.length; s++) {
+ const hiByte = bytes[cursor];
+ const loByte = bytes[cursor + 1];
+ if (hiByte === undefined || loByte === undefined) break;
+ const spsLen = (hiByte << 8) | loByte;
+ cursor += 2;
+ if (spsLen < 4 || cursor + spsLen > bytes.length) break;
+
+ const spsLevelIdc = cursor + 3;
+ const spsLevelByte = bytes[spsLevelIdc];
+ if (spsLevelByte !== undefined && spsLevelByte > maxAllowed) {
+ bytes[spsLevelIdc] = target;
+ }
+
+ cursor += spsLen;
+ }
+ }
+
+ return { patched, originalLevel: firstObservedLevel };
+}
+
+export function readAvcLevelFromMp4Prefix(bytes: Uint8Array): number | null {
+ for (let i = 0; i + 8 < bytes.length; i++) {
+ if (
+ bytes[i] === AVCC_FOURCC_A &&
+ bytes[i + 1] === AVCC_FOURCC_V &&
+ bytes[i + 2] === AVCC_FOURCC_C &&
+ bytes[i + 3] === AVCC_FOURCC_UPPER_C &&
+ bytes[i + 4] === 0x01
+ ) {
+ const levelByte = bytes[i + 4 + 3];
+ return typeof levelByte === "number" ? levelByte : null;
+ }
+ }
+ return null;
+}
+
+export function isIosSafari(userAgent: string | undefined): boolean {
+ if (!userAgent) return false;
+ const ua = userAgent.toLowerCase();
+ const isAppleMobile = /(iphone|ipod|ipad)/.test(ua);
+ if (isAppleMobile) return true;
+
+ if (typeof navigator === "undefined") return false;
+
+ const navWithTouch = navigator as Navigator & { maxTouchPoints?: number };
+ const maxTouch =
+ typeof navWithTouch.maxTouchPoints === "number"
+ ? navWithTouch.maxTouchPoints
+ : 0;
+
+ return (
+ maxTouch > 1 &&
+ /macintosh/.test(ua) &&
+ /safari/.test(ua) &&
+ !/chrome|chromium|edg|opr|firefox/.test(ua)
+ );
+}
+
+export async function probeAvcLevelFromUrl(
+ url: string,
+ options?: {
+ fetchImpl?: typeof fetch;
+ signal?: AbortSignal;
+ rangeBytes?: number;
+ },
+): Promise<number | null> {
+ const fetchImpl = options?.fetchImpl ?? fetch;
+ const rangeEnd = (options?.rangeBytes ?? AVC_PROBE_RANGE_BYTES) - 1;
+
+ try {
+ const response = await fetchImpl(url, {
+ headers: { Range: `bytes=0-${rangeEnd}` },
+ signal: options?.signal,
+ });
+
+ if (!response.ok && response.status !== 206) {
+ return null;
+ }
+
+ const buffer = new Uint8Array(await response.arrayBuffer());
+ return readAvcLevelFromMp4Prefix(buffer);
+ } catch {
+ return null;
+ }
+}
+
+export type PatchedMp4Blob = {
+ objectUrl: string;
+ size: number;
+ patched: boolean;
+ originalLevel: number | null;
+};
+
+export async function createLevelPatchedMp4ObjectUrl(
+ url: string,
+ options?: {
+ fetchImpl?: typeof fetch;
+ signal?: AbortSignal;
+ maxAllowedLevel?: number;
+ targetLevel?: number;
+ },
+): Promise<PatchedMp4Blob | null> {
+ const fetchImpl = options?.fetchImpl ?? fetch;
+
+ try {
+ const response = await fetchImpl(url, { signal: options?.signal });
+ if (!response.ok) return null;
+
+ const arrayBuffer = await response.arrayBuffer();
+ const bytes = new Uint8Array(arrayBuffer);
+ const { patched, originalLevel } = patchMp4AvcLevel(bytes, {
+ maxAllowedLevel: options?.maxAllowedLevel,
+ targetLevel: options?.targetLevel,
+ });
+
+ const blob = new Blob([bytes], {
+ type: response.headers.get("content-type") ?? "video/mp4",
+ });
+
+ return {
+ objectUrl: URL.createObjectURL(blob),
+ size: bytes.byteLength,
+ patched,
+ originalLevel,
+ };
+ } catch {
+ return null;
+ }
+}