-
Notifications
You must be signed in to change notification settings - Fork 1.1k
feat(shared): add WebP image primitives #2854
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,114 @@ | ||
| export interface BrowserWebpEncodeInput { | ||
| pixels: ArrayLike<number>; | ||
| width: number; | ||
| height: number; | ||
| /** Encoder quality from 0 to 100. Defaults to 90. */ | ||
| quality?: number; | ||
| } | ||
|
|
||
| /** | ||
| * Encode RGBA pixels with the WebP encoder provided by the browser. | ||
| * | ||
| * Keep this function self-contained so browser contract tests can execute the | ||
| * production implementation in a page or Worker without a test-only copy. | ||
| */ | ||
| export async function encodeRgbaToWebp({ | ||
| pixels, | ||
| width, | ||
| height, | ||
| quality = 90, | ||
| }: BrowserWebpEncodeInput): Promise<Uint8Array> { | ||
| if ( | ||
| !Number.isSafeInteger(width) || | ||
| !Number.isSafeInteger(height) || | ||
| width <= 0 || | ||
| height <= 0 | ||
| ) { | ||
| throw new Error('WebP image dimensions must be positive safe integers'); | ||
| } | ||
|
|
||
| if (!Number.isFinite(quality) || quality < 0 || quality > 100) { | ||
| throw new Error('WebP quality must be between 0 and 100'); | ||
| } | ||
|
|
||
| const expectedPixelCount = width * height * 4; | ||
| if ( | ||
| !Number.isSafeInteger(expectedPixelCount) || | ||
| pixels.length !== expectedPixelCount | ||
| ) { | ||
| throw new Error( | ||
| `WebP RGBA pixel length must be ${expectedPixelCount}, got ${pixels.length}`, | ||
| ); | ||
| } | ||
|
|
||
| const normalizedQuality = quality / 100; | ||
| let outputBlob: Blob; | ||
|
|
||
| if (typeof OffscreenCanvas !== 'undefined') { | ||
| const canvas = new OffscreenCanvas(width, height); | ||
| const context = canvas.getContext('2d'); | ||
| if (!context) { | ||
| throw new Error('Failed to get an OffscreenCanvas 2d context'); | ||
| } | ||
|
|
||
| const imageData = context.createImageData(width, height); | ||
| imageData.data.set(pixels); | ||
| context.putImageData(imageData, 0, 0); | ||
| outputBlob = await canvas.convertToBlob({ | ||
| type: 'image/webp', | ||
| quality: normalizedQuality, | ||
| }); | ||
| } else if (typeof document !== 'undefined') { | ||
| const canvas = document.createElement('canvas'); | ||
| canvas.width = width; | ||
| canvas.height = height; | ||
| const context = canvas.getContext('2d'); | ||
| if (!context) { | ||
| throw new Error('Failed to get an HTMLCanvasElement 2d context'); | ||
| } | ||
|
|
||
| const imageData = context.createImageData(width, height); | ||
| imageData.data.set(pixels); | ||
| context.putImageData(imageData, 0, 0); | ||
| outputBlob = await new Promise<Blob>((resolve, reject) => { | ||
| canvas.toBlob( | ||
| (blob) => { | ||
| if (blob) { | ||
| resolve(blob); | ||
| } else { | ||
| reject(new Error('HTMLCanvasElement failed to encode WebP')); | ||
| } | ||
| }, | ||
| 'image/webp', | ||
| normalizedQuality, | ||
| ); | ||
| }); | ||
| } else { | ||
| throw new Error( | ||
| 'WebP encoding requires OffscreenCanvas or HTMLCanvasElement', | ||
| ); | ||
| } | ||
|
|
||
| if (outputBlob.type.toLowerCase() !== 'image/webp') { | ||
| throw new Error( | ||
| `Browser WebP encoder returned ${outputBlob.type || 'an unknown MIME type'}`, | ||
| ); | ||
| } | ||
|
|
||
| const output = new Uint8Array(await outputBlob.arrayBuffer()); | ||
| const isWebp = | ||
| output.length >= 12 && | ||
| output[0] === 0x52 && | ||
| output[1] === 0x49 && | ||
| output[2] === 0x46 && | ||
| output[3] === 0x46 && | ||
| output[8] === 0x57 && | ||
| output[9] === 0x45 && | ||
| output[10] === 0x42 && | ||
| output[11] === 0x50; | ||
| if (!isWebp) { | ||
| throw new Error('Browser WebP encoder returned invalid WebP bytes'); | ||
| } | ||
|
|
||
| return output; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,131 @@ | ||
| export type ScreenshotImageFormat = 'png' | 'jpeg' | 'webp'; | ||
|
|
||
| export type ScreenshotImageMimeType = 'image/png' | 'image/jpeg' | 'image/webp'; | ||
|
|
||
| const mimeTypeByFormat: Record<ScreenshotImageFormat, ScreenshotImageMimeType> = | ||
| { | ||
| png: 'image/png', | ||
| jpeg: 'image/jpeg', | ||
| webp: 'image/webp', | ||
| }; | ||
|
|
||
| export function screenshotImageMimeType( | ||
| format: ScreenshotImageFormat, | ||
| ): ScreenshotImageMimeType { | ||
| return mimeTypeByFormat[format]; | ||
| } | ||
|
|
||
| export function screenshotImageExtension( | ||
| format: ScreenshotImageFormat, | ||
| ): ScreenshotImageFormat { | ||
| return format; | ||
| } | ||
|
|
||
| export function screenshotImageFormatFromExtension( | ||
| extension: unknown, | ||
| ): ScreenshotImageFormat | undefined { | ||
| if (typeof extension !== 'string') { | ||
| return undefined; | ||
| } | ||
|
|
||
| switch (extension.toLowerCase()) { | ||
| case 'png': | ||
| return 'png'; | ||
| case 'jpeg': | ||
| case 'jpg': | ||
| return 'jpeg'; | ||
| case 'webp': | ||
| return 'webp'; | ||
| default: | ||
| return undefined; | ||
| } | ||
| } | ||
|
|
||
| export function screenshotImageFormatFromMimeType( | ||
| mimeType: unknown, | ||
| ): ScreenshotImageFormat | undefined { | ||
| if (typeof mimeType !== 'string') { | ||
| return undefined; | ||
| } | ||
|
|
||
| switch (mimeType.toLowerCase()) { | ||
| case 'image/png': | ||
| return 'png'; | ||
| case 'image/jpeg': | ||
| case 'image/jpg': | ||
| return 'jpeg'; | ||
| case 'image/webp': | ||
| return 'webp'; | ||
| default: | ||
| return undefined; | ||
| } | ||
| } | ||
|
|
||
| export function isScreenshotImageMimeType( | ||
| mimeType: unknown, | ||
| ): mimeType is ScreenshotImageMimeType { | ||
| return ( | ||
| mimeType === 'image/png' || | ||
| mimeType === 'image/jpeg' || | ||
| mimeType === 'image/webp' | ||
| ); | ||
| } | ||
|
|
||
| export function inferScreenshotImageFormatFromBase64( | ||
| base64Body: string, | ||
| ): ScreenshotImageFormat | undefined { | ||
| const normalizedBody = base64Body.replace(/\s/g, ''); | ||
| if (normalizedBody.startsWith('iVBORw0KGgo')) { | ||
| return 'png'; | ||
| } | ||
| if (normalizedBody.startsWith('/9j/')) { | ||
| return 'jpeg'; | ||
| } | ||
| if (normalizedBody.startsWith('UklGR')) { | ||
| return 'webp'; | ||
| } | ||
| return undefined; | ||
| } | ||
|
|
||
| export function detectScreenshotImageFormatFromBuffer( | ||
| buffer: Uint8Array, | ||
| ): ScreenshotImageFormat | undefined { | ||
| if ( | ||
| buffer.length >= 8 && | ||
| buffer[0] === 0x89 && | ||
| buffer[1] === 0x50 && | ||
| buffer[2] === 0x4e && | ||
| buffer[3] === 0x47 && | ||
| buffer[4] === 0x0d && | ||
| buffer[5] === 0x0a && | ||
| buffer[6] === 0x1a && | ||
| buffer[7] === 0x0a | ||
| ) { | ||
| return 'png'; | ||
| } | ||
|
|
||
| if ( | ||
| buffer.length >= 3 && | ||
| buffer[0] === 0xff && | ||
| buffer[1] === 0xd8 && | ||
| buffer[2] === 0xff | ||
| ) { | ||
| return 'jpeg'; | ||
| } | ||
|
|
||
| if ( | ||
| buffer.length >= 12 && | ||
| buffer[0] === 0x52 && | ||
| buffer[1] === 0x49 && | ||
| buffer[2] === 0x46 && | ||
| buffer[3] === 0x46 && | ||
| buffer[8] === 0x57 && | ||
| buffer[9] === 0x45 && | ||
| buffer[10] === 0x42 && | ||
| buffer[11] === 0x50 | ||
| ) { | ||
| return 'webp'; | ||
| } | ||
|
|
||
| return undefined; | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
A truncated buffer containing only
RIFF, arbitrary size bytes, andWEBPat offset 8 passes this check because neither the RIFF-declared length nor a complete VP8/VP8L/VP8X image chunk is validated. Consequently the newly exposedisValidWebPImageBuffer,validateScreenshotBuffer, and the WebP fast path incanonicalizeScreenshotBase64accept and pass through corrupt screenshots, deferring failure to Sharp or the model provider. Verify the container length and a complete recognized image chunk, or decode the image before declaring it valid.Useful? React with 👍 / 👎.