Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

Add NV12 format support and image transform logic

Richie McIlroyd4ff525f3b4b
diff --git a/apps/desktop/src/routes/screenshot-editor/AnnotationLayer.tsx b/apps/desktop/src/routes/screenshot-editor/AnnotationLayer.tsx
index 248b7d273..604a8edf2 100644
--- a/apps/desktop/src/routes/screenshot-editor/AnnotationLayer.tsx
+++ b/apps/desktop/src/routes/screenshot-editor/AnnotationLayer.tsx
@@ -86,9 +86,11 @@ export function AnnotationLayer(props: {
createEffect(() => {
const rect = props.imageRect;
if (rect.width <= 0 || rect.height <= 0) return;
+ const currentlyDrawingId = isDrawing() ? tempAnnotation()?.id : null;
const masksToRemove: string[] = [];
for (const ann of annotations) {
if (ann.type !== "mask") continue;
+ if (ann.id === currentlyDrawingId) continue;
const left = clampValue(
Math.min(ann.x, ann.x + ann.width),
rect.x,
@@ -217,11 +219,11 @@ export function AnnotationLayer(props: {
newAnn.width = 150; // Default width
}
+ setTempAnnotation(newAnn);
+
if (tool === "mask") {
setAnnotations((prev) => [...prev, newAnn]);
}
-
- setTempAnnotation(newAnn);
};
const handleMouseMove = (e: MouseEvent) => {
diff --git a/apps/desktop/src/routes/screenshot-editor/context.tsx b/apps/desktop/src/routes/screenshot-editor/context.tsx
index 0ce9e8564..a4bbb7fe4 100644
--- a/apps/desktop/src/routes/screenshot-editor/context.tsx
+++ b/apps/desktop/src/routes/screenshot-editor/context.tsx
@@ -24,6 +24,57 @@ import {
type XY,
} from "~/utils/tauri";
+const NV12_FORMAT_MAGIC = 0x4e563132;
+
+function convertNv12ToRgba(
+ nv12Data: Uint8ClampedArray,
+ width: number,
+ height: number,
+ yStride: number,
+): Uint8ClampedArray {
+ const rgbaSize = width * height * 4;
+ const rgba = new Uint8ClampedArray(rgbaSize);
+
+ const ySize = yStride * height;
+ const yPlane = nv12Data;
+ const uvPlane = nv12Data.subarray(ySize);
+ const uvStride = width;
+
+ for (let row = 0; row < height; row++) {
+ const yRowOffset = row * yStride;
+ const uvRowOffset = Math.floor(row / 2) * uvStride;
+ const rgbaRowOffset = row * width * 4;
+
+ for (let col = 0; col < width; col++) {
+ const y = yPlane[yRowOffset + col] - 16;
+
+ const uvCol = Math.floor(col / 2) * 2;
+ const u = uvPlane[uvRowOffset + uvCol] - 128;
+ const v = uvPlane[uvRowOffset + uvCol + 1] - 128;
+
+ const c = 298 * y;
+ const d = u;
+ const e = v;
+
+ let r = (c + 409 * e + 128) >> 8;
+ let g = (c - 100 * d - 208 * e + 128) >> 8;
+ let b = (c + 516 * d + 128) >> 8;
+
+ r = r < 0 ? 0 : r > 255 ? 255 : r;
+ g = g < 0 ? 0 : g > 255 ? 255 : g;
+ b = b < 0 ? 0 : b > 255 ? 255 : b;
+
+ const rgbaOffset = rgbaRowOffset + col * 4;
+ rgba[rgbaOffset] = r;
+ rgba[rgbaOffset + 1] = g;
+ rgba[rgbaOffset + 2] = b;
+ rgba[rgbaOffset + 3] = 255;
+ }
+ }
+
+ return rgba;
+}
+
export type ScreenshotProject = ProjectConfiguration;
export type { Annotation, AnnotationType };
@@ -211,41 +262,70 @@ function createScreenshotEditorContext() {
ws.binaryType = "arraybuffer";
ws.onmessage = async (event) => {
const buffer = event.data as ArrayBuffer;
- if (buffer.byteLength < 24) return;
- const metadataOffset = buffer.byteLength - 24;
- const meta = new DataView(buffer, metadataOffset, 24);
- const strideBytes = meta.getUint32(0, true);
- const height = meta.getUint32(4, true);
- const width = meta.getUint32(8, true);
+ let isNv12Format = false;
+ if (buffer.byteLength >= 28) {
+ const formatCheck = new DataView(buffer, buffer.byteLength - 4, 4);
+ isNv12Format = formatCheck.getUint32(0, true) === NV12_FORMAT_MAGIC;
+ }
+
+ let width: number;
+ let height: number;
+ let processedData: Uint8ClampedArray;
- if (!width || !height) return;
+ if (isNv12Format) {
+ if (buffer.byteLength < 28) return;
- hasReceivedWebSocketFrame.value = true;
- setIsRenderReady(true);
+ const metadataOffset = buffer.byteLength - 28;
+ const meta = new DataView(buffer, metadataOffset, 28);
+ const yStride = meta.getUint32(0, true);
+ height = meta.getUint32(4, true);
+ width = meta.getUint32(8, true);
- const expectedRowBytes = width * 4;
- const frameData = new Uint8ClampedArray(
- buffer,
- 0,
- buffer.byteLength - 24,
- );
+ if (!width || !height) return;
- let processedData: Uint8ClampedArray;
- if (strideBytes === expectedRowBytes) {
- processedData = frameData.subarray(0, expectedRowBytes * height);
+ const ySize = yStride * height;
+ const uvSize = width * (height / 2);
+ const totalSize = ySize + uvSize;
+
+ const nv12Data = new Uint8ClampedArray(buffer, 0, totalSize);
+ processedData = convertNv12ToRgba(nv12Data, width, height, yStride);
} else {
- processedData = new Uint8ClampedArray(expectedRowBytes * height);
- for (let row = 0; row < height; row++) {
- const srcStart = row * strideBytes;
- const destStart = row * expectedRowBytes;
- processedData.set(
- frameData.subarray(srcStart, srcStart + expectedRowBytes),
- destStart,
- );
+ if (buffer.byteLength < 24) return;
+
+ const metadataOffset = buffer.byteLength - 24;
+ const meta = new DataView(buffer, metadataOffset, 24);
+ const strideBytes = meta.getUint32(0, true);
+ height = meta.getUint32(4, true);
+ width = meta.getUint32(8, true);
+
+ if (!width || !height) return;
+
+ const expectedRowBytes = width * 4;
+ const frameData = new Uint8ClampedArray(
+ buffer,
+ 0,
+ buffer.byteLength - 24,
+ );
+
+ if (strideBytes === expectedRowBytes) {
+ processedData = frameData.subarray(0, expectedRowBytes * height);
+ } else {
+ processedData = new Uint8ClampedArray(expectedRowBytes * height);
+ for (let row = 0; row < height; row++) {
+ const srcStart = row * strideBytes;
+ const destStart = row * expectedRowBytes;
+ processedData.set(
+ frameData.subarray(srcStart, srcStart + expectedRowBytes),
+ destStart,
+ );
+ }
}
}
+ hasReceivedWebSocketFrame.value = true;
+ setIsRenderReady(true);
+
try {
const imageData = new ImageData(processedData, width, height);
const bitmap = await createImageBitmap(imageData);
@@ -315,6 +395,132 @@ function createScreenshotEditorContext() {
),
);
+ const SCREEN_MAX_PADDING = 0.4;
+
+ const calculateImageTransform = (
+ frameSize: { width: number; height: number },
+ imageSize: { width: number; height: number },
+ padding: number,
+ crop: { position: XY<number>; size: XY<number> } | null,
+ ) => {
+ const cropWidth = crop?.size.x ?? imageSize.width;
+ const cropHeight = crop?.size.y ?? imageSize.height;
+ const croppedAspect = cropWidth / cropHeight;
+ const outputAspect = frameSize.width / frameSize.height;
+
+ const paddingFactor = (padding / 100.0) * SCREEN_MAX_PADDING;
+ const paddingPixels =
+ Math.max(frameSize.width, frameSize.height) * paddingFactor;
+
+ const availableWidth = frameSize.width - 2 * paddingPixels;
+ const availableHeight = frameSize.height - 2 * paddingPixels;
+
+ const isHeightConstrained = croppedAspect <= outputAspect;
+
+ let targetWidth: number;
+ let targetHeight: number;
+ if (isHeightConstrained) {
+ targetHeight = availableHeight;
+ targetWidth = availableHeight * croppedAspect;
+ } else {
+ targetWidth = availableWidth;
+ targetHeight = availableWidth / croppedAspect;
+ }
+
+ const targetOffsetX = (frameSize.width - targetWidth) / 2;
+ const targetOffsetY = (frameSize.height - targetHeight) / 2;
+
+ const offsetX = isHeightConstrained ? targetOffsetX : paddingPixels;
+ const offsetY = isHeightConstrained ? paddingPixels : targetOffsetY;
+
+ return {
+ offset: { x: offsetX, y: offsetY },
+ size: { width: targetWidth, height: targetHeight },
+ };
+ };
+
+ let prevState: {
+ frameSize: { width: number; height: number };
+ imageSize: { width: number; height: number };
+ transform: {
+ offset: { x: number; y: number };
+ size: { width: number; height: number };
+ };
+ } | null = null;
+
+ createEffect(
+ on(
+ () => ({
+ frame: latestFrame(),
+ imageSize: originalImageSize(),
+ padding: project.background.padding,
+ crop: project.background.crop,
+ }),
+ ({ frame, imageSize, padding, crop }) => {
+ if (!frame || !imageSize) return;
+
+ const frameSize = { width: frame.width, height: frame.height };
+
+ const frameSizeChanged =
+ !prevState ||
+ Math.abs(frameSize.width - prevState.frameSize.width) > 1 ||
+ Math.abs(frameSize.height - prevState.frameSize.height) > 1;
+
+ if (!frameSizeChanged) {
+ return;
+ }
+
+ const currentTransform = calculateImageTransform(
+ frameSize,
+ imageSize,
+ padding,
+ crop,
+ );
+
+ const rawAnnotations = unwrap(annotations);
+ const shouldTransform =
+ prevState && rawAnnotations.length > 0 && frameSizeChanged;
+
+ if (shouldTransform && prevState) {
+ const scaleX =
+ currentTransform.size.width / prevState.transform.size.width;
+ const scaleY =
+ currentTransform.size.height / prevState.transform.size.height;
+
+ const oldOffset = prevState.transform.offset;
+ const newOffset = currentTransform.offset;
+
+ const updatedAnnotations = rawAnnotations.map((ann) => {
+ const relX = ann.x - oldOffset.x;
+ const relY = ann.y - oldOffset.y;
+
+ const newX = newOffset.x + relX * scaleX;
+ const newY = newOffset.y + relY * scaleY;
+
+ const newWidth = ann.width * scaleX;
+ const newHeight = ann.height * scaleY;
+
+ return {
+ ...ann,
+ x: newX,
+ y: newY,
+ width: newWidth,
+ height: newHeight,
+ };
+ });
+
+ setAnnotations(reconcile(updatedAnnotations));
+ }
+
+ prevState = {
+ frameSize,
+ imageSize,
+ transform: currentTransform,
+ };
+ },
+ ),
+ );
+
// History Implementation
const [history, setHistory] = createStore<{
past: { project: ScreenshotProject; annotations: Annotation[] }[];
diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.ts
index 40623119e..b14f88498 100644
--- a/apps/desktop/src/utils/tauri.ts
+++ b/apps/desktop/src/utils/tauri.ts
@@ -372,7 +372,6 @@ uploadProgressEvent: "upload-progress-event"
/** user-defined types **/
-export type AllGpusInfo = { gpus: GpuInfoDiag[]; primaryGpuIndex: number | null; isMultiGpuSystem: boolean; hasDiscreteGpu: boolean }
export type Annotation = { id: string; type: AnnotationType; x: number; y: number; width: number; height: number; strokeColor: string; strokeWidth: number; fillColor: string; opacity: number; rotation: number; text: string | null; maskType?: MaskType | null; maskLevel?: number | null }
export type AnnotationType = "arrow" | "circle" | "rectangle" | "text" | "mask"
export type AppTheme = "system" | "light" | "dark"
@@ -441,7 +440,6 @@ quality: number | null;
* Whether to prioritize speed over quality (default: false)
*/
fast: boolean | null }
-export type GpuInfoDiag = { vendor: string; description: string; dedicatedVideoMemoryMb: number; adapterIndex: number; isSoftwareAdapter: boolean; isBasicRenderDriver: boolean; supportsHardwareEncoding: boolean }
export type HapticPattern = "alignment" | "levelChange" | "generic"
export type HapticPerformanceTime = "default" | "now" | "drawCompleted"
export type Hotkey = { code: string; meta: boolean; ctrl: boolean; alt: boolean; shift: boolean }
@@ -454,6 +452,7 @@ export type JsonValue<T> = [T]
export type LogicalBounds = { position: LogicalPosition; size: LogicalSize }
export type LogicalPosition = { x: number; y: number }
export type LogicalSize = { width: number; height: number }
+export type MacOSVersionInfo = { displayName: string }
export type MainWindowRecordingStartBehaviour = "close" | "minimise"
export type MaskKeyframes = { position?: MaskVectorKeyframe[]; size?: MaskVectorKeyframe[]; intensity?: MaskScalarKeyframe[] }
export type MaskKind = "sensitive" | "highlight"
@@ -496,7 +495,6 @@ export type RecordingStatus = "pending" | "recording"
export type RecordingStopped = null
export type RecordingTargetMode = "display" | "window" | "area"
export type RenderFrameEvent = { frame_number: number; fps: number; resolution_base: XY<number> }
-export type RenderingStatus = { isUsingSoftwareRendering: boolean; isUsingBasicRenderDriver: boolean; hardwareEncodingAvailable: boolean; warningMessage: string | null }
export type RequestOpenRecordingPicker = { target_mode: RecordingTargetMode | null }
export type RequestOpenSettings = { page: string }
export type RequestScreenCapturePrewarm = { force?: boolean }
@@ -517,7 +515,7 @@ export type StartRecordingInputs = { capture_target: ScreenCaptureTarget; captur
export type StereoMode = "stereo" | "monoL" | "monoR"
export type StudioRecordingMeta = { segment: SingleSegment } | { inner: MultipleSegments }
export type StudioRecordingStatus = { status: "InProgress" } | { status: "NeedsRemux" } | { status: "Failed"; error: string } | { status: "Complete" }
-export type SystemDiagnostics = { windowsVersion: WindowsVersionInfo | null; gpuInfo: GpuInfoDiag | null; allGpus: AllGpusInfo | null; renderingStatus: RenderingStatus; availableEncoders: string[]; graphicsCaptureSupported: boolean; d3D11VideoProcessorAvailable: boolean }
+export type SystemDiagnostics = { macosVersion: MacOSVersionInfo | null; availableEncoders: string[]; screenCaptureSupported: boolean }
export type TargetUnderCursor = { display_id: DisplayId | null; window: WindowUnderCursor | null }
export type TextSegment = { start: number; end: number; enabled?: boolean; content?: string; center?: XY<number>; size?: XY<number>; fontFamily?: string; fontSize?: number; fontWeight?: number; italic?: boolean; color?: string; fadeDuration?: number }
export type TimelineConfiguration = { segments: TimelineSegment[]; zoomSegments: ZoomSegment[]; sceneSegments?: SceneSegment[]; maskSegments?: MaskSegment[]; textSegments?: TextSegment[] }
@@ -534,7 +532,6 @@ export type VideoUploadInfo = { id: string; link: string; config: S3UploadMeta }
export type WindowExclusion = { bundleIdentifier?: string | null; ownerName?: string | null; windowTitle?: string | null }
export type WindowId = string
export type WindowUnderCursor = { id: WindowId; app_name: string; bounds: LogicalBounds }
-export type WindowsVersionInfo = { major: number; minor: number; build: number; displayName: string; meetsRequirements: boolean; isWindows11: boolean }
export type XY<T> = { x: T; y: T }
export type ZoomMode = "auto" | { manual: { x: number; y: number } }
export type ZoomSegment = { start: number; end: number; amount: number; mode: ZoomMode }