Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 50 additions & 5 deletions lib/experimental/media/docs/client-side-media-docs.md
Original file line number Diff line number Diff line change
@@ -1,12 +1,57 @@
# Technical Documentation

## Browser Compatibility

Client-side media processing requires the following browser capabilities:

| Feature | Required | Purpose |
|---------|----------|---------|
| WebAssembly | Yes | Runs the wasm-vips image processing library |
| SharedArrayBuffer | Yes | Enables multi-threaded WASM execution |
| Cross-origin isolation | Yes | Required for SharedArrayBuffer in modern browsers |
| CSP `blob:` workers | Yes | The WASM worker is loaded via a blob URL |

### Browser Support Matrix

| Browser | Minimum Version | Notes |
|---------|-----------------|-------|
| Chrome | 92+ | Full support |
| Firefox | 79+ | Full support except embed previews |
| Safari | 15.2+ | Requires `require-corp` instead of `credentialless` |
| Edge | 92+ | Full support |

### Automatic Fallback

When client-side media processing is unavailable, the system automatically falls back to server-side processing. This fallback is transparent to users and requires no action. A message is logged to the browser console indicating the reason for the fallback.

The fallback occurs when any of the following conditions are detected:
- WebAssembly is not supported in the browser
- SharedArrayBuffer is not available
- Cross-origin isolation is not enabled (missing required headers)
- The site's Content Security Policy (CSP) blocks blob URL workers

## Cross-origin isolation / `SharedArrayBuffer`

WASM-based image optimization requires `SharedArrayBuffer` support, which in turn requires [cross-origin isolation](https://web.dev/articles/cross-origin-isolation-guide). To implement this, the editor uses the following headers:
- `Cross-Origin-Opener-Policy: same-origin`
- `Cross-Origin-Embedder-Policy: credentialless` (or `require-corp` for safari)
WASM-based image optimization requires `SharedArrayBuffer` support, which in turn requires [cross-origin isolation](https://web.dev/articles/cross-origin-isolation-guide).

Once the page is served with these headers, `SharedArrayBuffer` will be available in the browser, and WASM-based image optimization will work as expected. However, all embedded resources (e.g., images, iframes, scripts) must also be served with appropriate CORS headers (or iframe with `iframe-credentialless` for supporting browsers) to ensure cross-origin isolation is maintained. For third party embeds (for example a YouTube video), the plugin uses [iframe `credentialless` attribute](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/IFrame_credentialless) to help with this. For browsers that do not support this attribute, embeds will show an information pane instead of a live preview.

### Troubleshooting

If client-side media processing is not working, check the browser console for messages. Common issues include:

1. **"SharedArrayBuffer is not available"**: The server is not sending the required cross-origin isolation headers.
2. **"Cross-origin isolation is not enabled"**: The headers are present but cross-origin isolation is not active. This can happen if:
- Third-party resources are blocking isolation
- Headers are being stripped by a proxy or CDN
- The page is being served over HTTP instead of HTTPS

3. **"WebAssembly is not supported"**: The browser does not support WebAssembly. This is rare in modern browsers but can occur in older versions or restricted environments.

Once the page is served with these headers, `SharedArrayBuffer` will be available in the browser, and WASM-based image optimization will work as expected. However, all embedded resources (e.g., images, iframes, scripts) must also be served with appropriate CORS headers to ensure cross-origin isolation is maintained. For third party embeds (for example a YouTube video), the plugin uses [iframe `credentialless` attribute](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/IFrame_credentialless) to help with this. For browsers that do not support this attribute, embeds will show an information pane instead of a live preview.
4. **"Content Security Policy (CSP) does not allow blob: workers"**: A security plugin or server configuration is setting a `worker-src` CSP directive that does not include `blob:`. The WASM image processing worker is loaded via a blob URL, which requires CSP to permit it. To resolve this:
- Add `blob:` to the `worker-src` directive in the site's CSP header (e.g., `worker-src 'self' blob:`)
- If using a security plugin (e.g., WP Cerber, Wordfence, or similar), check its CSP settings and add `blob:` to the allowed worker sources
- If the CSP header is set at the server level (e.g., in `.htaccess`, Nginx config, or a CDN), update it there

Check out [this tracking issue](https://github.com/swissspidy/media-experiments/issues/294) for more details and further resources.
Check out [this tracking issue](https://github.com/WordPress/gutenberg/issues/74464) for more details and further resources.

71 changes: 65 additions & 6 deletions packages/block-editor/src/components/provider/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { SlotFillProvider } from '@wordpress/components';
import {
MediaUploadProvider,
store as uploadStore,
detectClientSideMediaSupport,
} from '@wordpress/upload-media';

/**
Expand All @@ -24,6 +25,64 @@ import useMediaUploadSettings from './use-media-upload-settings';

const noop = () => {};

/**
* Flag to track if we've already logged the fallback message.
*/
let hasLoggedFallback = false;

/**
* Cached result of whether client-side media processing should be enabled.
* This is computed once per session for efficiency and stability.
*/
let isClientSideMediaEnabledCache = null;

/**
* Checks if client-side media processing should be enabled.
*
* Returns true only if:
* 1. The experimental media processing flag is enabled
* 2. The browser supports WebAssembly, SharedArrayBuffer, cross-origin isolation, and CSP allows blob workers
*
* The result is cached for the session to ensure stability during React renders.
*
* @return {boolean} Whether client-side media processing should be enabled.
*/
function shouldEnableClientSideMediaProcessing() {
Comment on lines +28 to +50

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just had a thought: should all this live in the upload-media package, or will we need anything that only exists in the block-editor package?

The reason I ask, is that we've also got conditional logic in the editor package for post locking, so I imagine we'll want to use this check over there, too, in place of the experiment check once we stabilise client-side media processing (i.e. what you're doing in #75112).

This might kind of be feedback for that PR, but the overall question is: should we have one place that incorporates all the different kinds of checks (e.g. window.__clientSideMediaProcessing + device capability, etc, etc) and use that function check elsewhere?

So far, it seem this function is such a utility for this. And if so, then maybe upload-media is a good place for it.

What do you think?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So far, it seem this function is such a utility for this. And if so, then maybe upload-media is a good place for it.

That makes sense to me, I'll give that a try here or in a follow up pr.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That makes sense to me, I'll give that a try here or in a follow up pr.

All good. Feel free to land this PR first if it winds up being a bit rabbit-holey.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm going to merge this, then loop back to the final feedback in a follow up

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

See #75605

// Return cached result if available.
if ( isClientSideMediaEnabledCache !== null ) {
return isClientSideMediaEnabledCache;
}

// Check if experimental flag is enabled first.
if ( ! window.__experimentalMediaProcessing ) {
isClientSideMediaEnabledCache = false;
return false;
}

// Safety check in case the import is unavailable.
if ( typeof detectClientSideMediaSupport !== 'function' ) {
isClientSideMediaEnabledCache = false;
return false;
}

const detection = detectClientSideMediaSupport();
if ( ! detection || ! detection.supported ) {
// Only log once per session to avoid console spam.
if ( ! hasLoggedFallback ) {
// eslint-disable-next-line no-console
console.info(
`Client-side media processing unavailable: ${ detection.reason }. Using server-side processing.`
);
hasLoggedFallback = true;
}
isClientSideMediaEnabledCache = false;
return false;
}

isClientSideMediaEnabledCache = true;
return true;
}
Comment thread
adamsilverstein marked this conversation as resolved.
Resolved

/**
* Upload a media file when the file upload button is activated
* or when adding a file to the editor via drag & drop.
Expand Down Expand Up @@ -71,19 +130,19 @@ export const ExperimentalBlockEditorProvider = withRegistryProvider(

const mediaUploadSettings = useMediaUploadSettings( _settings );

const isClientSideMediaEnabled =
shouldEnableClientSideMediaProcessing();

const settings = useMemo( () => {
if (
window.__experimentalMediaProcessing &&
_settings?.mediaUpload
) {
if ( isClientSideMediaEnabled && _settings?.mediaUpload ) {
// Create a new object so that the original props.settings.mediaUpload is not modified.
return {
..._settings,
mediaUpload: mediaUpload.bind( null, registry ),
};
}
return _settings;
}, [ _settings, registry ] );
}, [ _settings, registry, isClientSideMediaEnabled ] );

const { __experimentalUpdateSettings } = unlock(
useDispatch( blockEditorStore )
Expand Down Expand Up @@ -115,7 +174,7 @@ export const ExperimentalBlockEditorProvider = withRegistryProvider(
</SlotFillProvider>
);

if ( window.__experimentalMediaProcessing ) {
if ( isClientSideMediaEnabled ) {
return (
<MediaUploadProvider
settings={ mediaUploadSettings }
Expand Down
100 changes: 100 additions & 0 deletions packages/upload-media/src/feature-detection.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
/**
* Result of client-side media processing support detection.
*/
export interface FeatureDetectionResult {
/**
* Whether client-side media processing is supported.
*/
supported: boolean;
/**
* Reason why client-side media processing is not supported (if applicable).
*/
reason?: string;
}

/**
* Cached result of feature detection.
*/
let cachedResult: FeatureDetectionResult | null = null;

/**
* Detects whether the browser supports client-side media processing.
*
* This checks for:
* 1. WebAssembly support (required for wasm-vips)
* 2. SharedArrayBuffer support (required for WASM threading)
* 3. CSP compatibility for blob URL workers (required for inline worker creation)
*
* @return Feature detection result with supported status and reason if not supported.
*/
export function detectClientSideMediaSupport(): FeatureDetectionResult {
// Return cached result if available.
if ( cachedResult !== null ) {
return cachedResult;
}

// Check WebAssembly support.
if ( typeof WebAssembly === 'undefined' ) {
cachedResult = {
supported: false,
reason: 'WebAssembly is not supported in this browser',
};
return cachedResult;
}
Comment on lines +36 to +43

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess it can't hurt, but I don't think there is any modern browser that doesn't support it. It's been around for 9 years.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Trying to be thorough but yeah, we can probably remove this.


// Check SharedArrayBuffer support (required for WASM threading).
if ( typeof SharedArrayBuffer === 'undefined' ) {
cachedResult = {
supported: false,
reason: 'SharedArrayBuffer is not available. This may be due to missing cross-origin isolation headers.',

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is such a minor thing, but I noticed inconsistent use of . at the end of the reason. This can result in the console log sometimes having a double ..:

Image

};
return cachedResult;
}

// Check that blob URL workers are allowed by CSP.
// Security plugins often set a strict worker-src directive that blocks blob: URLs,
// which would prevent creating the WASM processing worker at runtime.
if ( typeof window !== 'undefined' && typeof Worker !== 'undefined' ) {
try {
const testBlob = new Blob( [ '' ], {
type: 'application/javascript',
} );
const testUrl = URL.createObjectURL( testBlob );
try {
const testWorker = new Worker( testUrl );
testWorker.terminate();
} finally {
URL.revokeObjectURL( testUrl );
}
} catch {
cachedResult = {
supported: false,
reason: "The site's Content Security Policy (CSP) does not allow blob: workers. The worker-src directive must include blob: to enable client-side media processing.",
};
return cachedResult;
}
}

cachedResult = { supported: true };
return cachedResult;
}

/**
* Returns whether client-side media processing is supported.
*
* This is a convenience function that returns just the boolean result.
*
* @return Whether client-side media processing is supported.
*/
export function isClientSideMediaSupported(): boolean {
return detectClientSideMediaSupport().supported;
}

/**
* Clears the cached feature detection result.
*
* This is primarily useful for testing purposes.
*/
export function clearFeatureDetectionCache(): void {
cachedResult = null;
}
6 changes: 6 additions & 0 deletions packages/upload-media/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,11 @@ export { uploadStore as store };

export { default as MediaUploadProvider } from './components/provider';
export { UploadError } from './upload-error';
export {
detectClientSideMediaSupport,
isClientSideMediaSupported,
clearFeatureDetectionCache,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tiny nit: do we need to export clearFeatureDetectionCache? It feels like an internal feature to me, and it's only used in the tests, so I wondered how necessary it is for consumers.

That said, if consumers need to clear the cache, it makes sense to include it, so not a blocker to me.

} from './feature-detection';
Comment thread
adamsilverstein marked this conversation as resolved.
Resolved

export type { ImageFormat } from './store/types';
export type { FeatureDetectionResult } from './feature-detection';
Loading
Loading