capacitor-native-video-compressor
v1.1.0
Published
Native video compressor using LightCompressor and AVFoundation
Readme
capacitor-native-video-compressor
A Capacitor plugin to compress videos natively on iOS (using AVFoundation), Android (using LightCompressor), and Web (using FFmpeg.wasm).
Install
npm install capacitor-native-video-compressor
npx cap syncSupported Platforms
- iOS: Uses
AVAssetExportSession(Hardware accelerated). - Android: Uses
LightCompressor(MediaCodec hardware accelerated). - Web: Uses
@ffmpeg/ffmpeg(WebAssembly).
Native Configuration
iOS
Remember to add the following to your Info.plist if you are picking videos from the Photo Library before compressing them:
<key>NSPhotoLibraryUsageDescription</key>
<string>We need access to your photo library to select videos for compression.</string>Android
If you are reading videos from external storage, ensure you have the appropriate permissions in your AndroidManifest.xml:
<uses-permission android:name="android.permission.READ_MEDIA_VIDEO" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" android:maxSdkVersion="32" />Web Configuration (Required)
To use video compression on the Web platform, FFmpeg.wasm requires SharedArrayBuffer to function properly. You must configure your web server/framework to serve these specific HTTP headers:
Cross-Origin-Embedder-Policy: credentialless
Cross-Origin-Opener-Policy: same-originExample: Nuxt 3 / Vite
If you are using Vite or Nuxt, update your configuration to include these headers and avoid optimizing the FFmpeg packages:
// nuxt.config.ts or vite.config.ts
export default defineNuxtConfig({
routeRules: {
'/**': {
headers: {
'Cross-Origin-Embedder-Policy': 'credentialless',
'Cross-Origin-Opener-Policy': 'same-origin',
},
},
},
vite: {
server: {
headers: {
'Cross-Origin-Embedder-Policy': 'credentialless',
'Cross-Origin-Opener-Policy': 'same-origin',
},
},
optimizeDeps: {
exclude: ['@ffmpeg/ffmpeg', '@ffmpeg/util', 'capacitor-native-video-compressor'],
},
},
});Usage
1. Initialization (Web Only)
Before compressing videos on the Web platform, you must initialize the FFmpeg core. This step is safely ignored on Native platforms (iOS/Android), so calling it cross-platform is perfectly fine.
import { NativeVideoCompressor } from 'capacitor-native-video-compressor';
import { Capacitor } from '@capacitor/core';
const initCompressor = async () => {
if (Capacitor.getPlatform() === 'web') {
const result = await NativeVideoCompressor.initialize();
if (!result.success) {
console.error('Failed to load FFmpeg core:', result.message);
}
}
};2. Compression & Progress Subscription
Subscribe to the onProgress event to get updates on the compression process, and then call compressVideo().
import { NativeVideoCompressor } from 'capacitor-native-video-compressor';
// 1. Add progress listener
const listener = await NativeVideoCompressor.addListener('onProgress', (info) => {
// info.status can be: 'started', 'loading_core', 'progress'
if (info.status === 'progress') {
console.log(`Compression Progress: ${info.percent}%`);
}
});
// 2. Start Compression
try {
const result = await NativeVideoCompressor.compressVideo({
sourcePath: '/path/to/original/video.mp4', // Web: blob URL or file path
quality: 'MEDIUM', // 'VERY_HIGH' | 'HIGH' | 'MEDIUM' | 'LOW' | 'VERY_LOW'
});
console.log('Compression successful! Saved at:', result.destPath);
} catch (error) {
console.error('Compression failed:', error);
}
// 3. Remove listener when done
listener.remove();3. Cancelling a Compression
Compressing a long video runs for minutes, so give the user a way out. Pass a
jobId when starting, then cancel with the same id:
import { NativeVideoCompressor, CANCELLED } from 'capacitor-native-video-compressor';
const jobId = crypto.randomUUID();
try {
const result = await NativeVideoCompressor.compressVideo({
sourcePath: '/path/to/video.mp4',
quality: 'HIGH',
jobId,
});
} catch (error) {
if (error.code === CANCELLED) {
// The user asked for this — no error toast, no retry prompt.
return;
}
throw error;
}
// From a Cancel button, anywhere:
await NativeVideoCompressor.cancel({ jobId });Why jobId. Every platform compresses one video at a time, so cancellation
is global by nature. Two independent queues in the same app (say comments and
notes) would otherwise cancel each other's work. cancel() with no jobId
cancels whatever is running, whoever started it — fine when there is only one
caller.
What it costs. The partial output is deleted on every platform. On web,
cancelling terminates the FFmpeg worker, because ffmpeg.exec() runs as
synchronous WASM inside it and never reaches a message poll while encoding —
the AbortSignal exec() accepts only rejects the main-thread promise while
the encode keeps burning CPU behind it. The loaded core is dropped with the
worker, but the core URLs are cached in module scope, so the next compress
re-instantiates without re-downloading the wasm.
cancel() resolves { cancelled: false } when nothing was running, or when a
different job was — it never throws.
Quality Presets
The quality parameter determines the output resolution and compression ratio. Depending on the original aspect ratio, the video will be scaled to match the following heights (or widths, preserving aspect ratio):
| Preset | Target Resolution | Best For |
| ----------- | ----------------- | ----------------------------------------- |
| VERY_HIGH | ~ 1080p | Preserving original high quality |
| HIGH | ~ 720p | Good balance for social media sharing |
| MEDIUM | ~ 540p | Efficient storage and decent quality |
| LOW | ~ 480p | Standard low-bandwidth usage |
| 360P | ~ 360p | Very small files |
| VERY_LOW | ~ 240p | Extreme compression, noticeably pixelated |
Note on Web Platform: On Web, lower qualities also aggressively reduce the Audio Bitrate (down to 48kbps for VERY_LOW) to maximize space savings. On Native, audio maintains steady quality.
Platform Differences for sourcePath
- iOS/Android:
sourcePathmust be a physical device file path (e.g.,file:///var/mobile/...orcontent://...). Do not pass paths obtained from the CapacitorWebView(likehttp://localhost/...). - Web:
sourcePathcan be a Blob URL (e.g.,blob:http://localhost:3000/...), a base64 Data URI, or a direct link to a file if CORS allows.
API
compressVideo(...)
compressVideo(options: CompressOptions) => Promise<CompressResult>| Param | Type |
| ------------- | ----------------------------------------------------------- |
| options | CompressOptions |
Returns: Promise<CompressResult>
cancel(...)
cancel(options?: CancelOptions | undefined) => Promise<CancelResult>Stop the compress that is running now. compressVideo then rejects with
code {@link CANCELLED} and its partial output is deleted.
This is the only way to stop one: the work is synchronous WASM inside a web worker (web) or an AVFoundation / LightCompressor pass on its own thread (native), and none of them watch an AbortSignal.
| Param | Type |
| ------------- | ------------------------------------------------------- |
| options | CancelOptions |
Returns: Promise<CancelResult>
initialize()
initialize() => Promise<{ success: boolean; message?: string; }>Returns: Promise<{ success: boolean; message?: string; }>
addListener('onProgress', ...)
addListener(eventName: 'onProgress', listenerFunc: (info: { status: string; percent?: number; }) => void) => Promise<PluginListenerHandle>| Param | Type |
| ------------------ | --------------------------------------------------------------------- |
| eventName | 'onProgress' |
| listenerFunc | (info: { status: string; percent?: number; }) => void |
Returns: Promise<PluginListenerHandle>
Interfaces
CompressResult
| Prop | Type |
| -------------- | -------------------- |
| success | boolean |
| destPath | string |
CompressOptions
| Prop | Type | Description |
| ---------------- | ------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| sourcePath | string | |
| destPath | string | |
| quality | 'VERY_HIGH' | 'HIGH' | 'MEDIUM' | 'LOW' | 'VERY_LOW' | '360P' | |
| jobId | string | Names this compress so cancel({ jobId }) can target it. Every platform compresses one video at a time, so cancellation is global by nature. Two independent callers in the same app (say a comment queue and a notes queue) therefore need a way to say which job they mean — without one, a cancel from either kills whatever the other is running. |
CancelResult
| Prop | Type | Description |
| --------------- | -------------------- | ------------------------------------------------------------ |
| cancelled | boolean | False when nothing was running, or when a different job was. |
CancelOptions
| Prop | Type | Description |
| ----------- | ------------------- | --------------------------------------------------------------------------------------------------------- |
| jobId | string | Only cancel if this is the job currently running. Omit to cancel whatever is running, whoever started it. |
PluginListenerHandle
| Prop | Type |
| ------------ | ----------------------------------------- |
| remove | () => Promise<void> |
