feat(export): MediaRecorder fallback when WebCodecs encoders are missing
Summary
Companion to #794. The existing exporter goes through mediabunny, which delegates to the WebCodecs VideoEncoder and AudioEncoder. On browsers where those APIs are not exposed (the same environments that needed the decode fallback in #794), export currently fails with AudioEncoder is not supported by this browser before producing any output.
This adds a parallel fallback path inside SceneExporter so export works in those environments too.
How
- New helpers
isWebCodecsExportSupported()anddetectMediaRecorderSupport()live in a tiny dependency-free module (media-recorder-support.ts) so they can be unit-tested without dragging in the project's WASM glue. exportWithMediaRecorderdrives the existingCanvasRendererat real-time wall-clock, captures the output canvas withHTMLCanvasElement.captureStream(fps), mixes the project audio buffer through aMediaStreamAudioDestinationNode, and records the combinedMediaStreamwithMediaRecorder— producing a WebM blob the same browser can play back natively.SceneExporter.export()checks!isWebCodecsExportSupported()at entry and delegates to the new path. The WebCodecs path is unchanged for capable browsers.
Trade-offs
- Container is WebM (most browsers don't expose an MP4 muxer through MediaRecorder). The user's requested format is honoured best-effort.
- Real-time rendering: a 60-second timeline takes ~60 seconds to export. The WebCodecs path continues to render faster than real-time when available.
- Bitrate: mapped per
ExportQualitypreset (2.5 / 5 / 10 / 20 Mbps for low / medium / high / very_high) intoMediaRecorder.videoBitsPerSecond.
Test plan
- [x] Unit tests cover the four states of WebCodecs / MediaRecorder availability — 5 pass, 0 fail.
- [x] Manual on a browser without
VideoEncoder/AudioEncoder: export now produces a working WebM file with audio. On a capable browser, the existing mediabunny path runs as before.
Notes
- Depends on #794 for the decode side. PR diff against
mainonly contains the export-fallback additions; merging order should be #794 first, this on top.
Summary by CodeRabbit
-
New Features
- Automatic H.264 conversion during import; optional server-side transcode for MP4 export.
- MediaRecorder-based export fallback when native encoders aren’t available.
-
Improvements
- More robust audio/video processing with WebCodecs-aware fallbacks and safer iterator/error handling.
- Better handling of converted file storage, decoding checks, and export progress/status UX.
-
Tests
- Added test suites covering audio fallback, video sinks, and media-recorder support.
@avillagran is attempting to deploy a commit to the OpenCut OSS Team on Vercel.
A member of the Team first needs to authorize it.
Adds graceful fallback media paths: server-side ffmpeg H.264 conversion endpoint and client helper, audio decoding fallback via Web Audio API, video frame extraction via HTMLVideoElement+canvas, MediaRecorder-based export fallback, and integrates these into audio/video managers, media processing, and export UI. WebCodecs Fallback Architecture 🎯 4 (Complex) | ⏱️ ~60 minutes "🐰 I hopped through codecs late at night, ✏️ Tip: You can configure your own custom pre-merge checks in the settings.📝 Walkthrough
Walkthrough
Changes
Layer / File(s)
Summary
ffmpeg-based H.264 video conversion API and client helper
apps/web/src/app/api/convert-video/route.ts, apps/web/src/media/ffmpeg-convert.tsPOST endpoint accepts uploaded video, converts to H.264 MP4 via spawned ffmpeg process with filename sanitization and error handling; client helper uploads to endpoint and constructs File from converted blob.
Audio fallback sink using Web Audio API
apps/web/src/services/audio-cache/fallback-audio-buffer-sink.ts, apps/web/src/services/audio-cache/__tests__/fallback-audio-buffer-sink.test.tsFallbackAudioBufferSink decodes audio via decodeAudioData when WebCodecs AudioDecoder unavailable; supports timestamp-based slicing and handles edge cases like NaN and empty ranges with comprehensive test coverage.
Video fallback sink using HTML5 video element and canvas
apps/web/src/services/video-cache/html-video-element-sink.ts, apps/web/src/services/video-cache/__tests__/html-video-element-sink.test.tsHTMLVideoElementSink frames video via HTML5 video element and canvas rendering when WebCodecs VideoDecoder unavailable; includes FPS clamping, seek error handling, and tests for frame stepping, disposal, and dimension validation.
AudioManager integration with fallback audio sink
apps/web/src/core/managers/audio-manager.ts, apps/web/src/media/audio.tsAudioManager and resolveAudioBufferForAsset probe WebCodecs availability and fall back to FallbackAudioBufferSink when AudioDecoder unavailable; adds error handling around clip iterator consumption and dropped-buffer tracking parameter.
VideoCache service integration with fallback video sink
apps/web/src/services/video-cache/service.tsVideoCache branches on WebCodecs availability to initialize HTMLVideoElementSink as fallback; refactors VideoSinkData to store generic FrameSink with dispose callback for lifecycle consistency.
Media processing pipeline with H.264 conversion
apps/web/src/media/processing.tsIntegrates ffmpeg H.264 conversion: when readVideoFile reports non-decodable video, converts to H.264, re-validates storage and decodeability, updates object URLs, and shows success or warning toast before proceeding with converted file.
MediaRecorder-based export infrastructure
apps/web/src/services/renderer/media-recorder-support.ts, apps/web/src/services/renderer/media-recorder-exporter.ts, apps/web/src/services/renderer/__tests__/media-recorder-exporter.test.tsFeature-detection helpers for MediaRecorder and WebCodecs encoders; exportWithMediaRecorder implements canvas rendering via MediaRecorder, constructs audio capture graph via AudioContext, schedules frames at wall-clock time, and supports cancellation.
Scene exporter routing to MediaRecorder fallback
apps/web/src/services/renderer/scene-exporter.tsSceneExporter.export() detects WebCodecs encoder availability and routes through MediaRecorder-based export as fallback; maps ExportQuality to bitrates, wires progress events, handles cancellation, and normalizes errors.
Export UI: server-side transcode toggle and flow
apps/web/src/components/editor/export-button.tsxExportButton adds a server-transcode checkbox and state; when enabled and needed, uploads output for server-side H.264 conversion, replaces download buffer on success, and shows error toasts/fallback behavior on failure.
Built a sink where decoders took flight,
Canvas frames and ffmpeg's light,
MediaRecorder hums till downloads feel right."🚥 Pre-merge checks | ✅ 3 | ❌ 2
❌ Failed checks (2 warnings)
Check name
Status
Explanation
Resolution
Description check
⚠️ Warning
The description is comprehensive and mostly complete, covering summary, implementation details, trade-offs, testing, and dependencies. However, it does not follow the repository's required template structure.
Add required template sections including checkboxes (for bug vs feature), and address the note that PRs require prior discussion/approval. Clarify approval status or open an issue if following the template requirements.
Docstring Coverage
⚠️ Warning
Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%.
Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name
Status
Explanation
Title check
✅ Passed
The title accurately and concisely describes the primary change: adding a MediaRecorder fallback for export when WebCodecs encoders are unavailable.
Linked Issues check
✅ Passed
Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check
✅ Passed
Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
Comment @coderabbitai help to get the list of available commands and usage tips.
Follow-up commit (6f7dacb4d4cf578df8325942bae6d4446efe6575): added an opt-in server transcode option in the export popover, addressing the practical follow-up that the WebM fallback output doesn't play in QuickTime/Safari. When WebCodecs is missing and the user picked MP4, the popover surfaces a 'Browser compatibility' section with a checkbox to route the produced WebM through the existing /api/convert-video ffmpeg endpoint and download a real H.264 MP4 instead. Off-by-default would be against user intent (they already asked for MP4), so the checkbox defaults to on; opting out keeps the WebM extension/mime so the saved file matches its real container. Failures fall back to the WebM with a toast.