OpenCut icon indicating copy to clipboard operation
OpenCut copied to clipboard

feat(media): support browsers without WebCodecs via FFmpeg + HTML5 fallbacks

Open avillagran opened this issue 6 months ago • 5 comments

Summary

OpenCut's video preview and audio playback both rely on mediabunny, which requires the WebCodecs API (VideoDecoder / AudioDecoder). On browsers where WebCodecs is not exposed (e.g. some Linux Chromium builds without proprietary codec support, Firefox in certain configurations), import and playback both throw codec not supported errors and the editor becomes unusable.

This PR makes the editor work on those browsers without changing the WebCodecs fast-path when it is available.

What changed

  • /api/convert-video — server-side route that transcodes incoming videos to H.264 baseline 3.1 + yuv420p via the system ffmpeg binary. processMediaAssets calls it automatically when readVideoFile reports canDecode=false, so the asset persisted to storage is always something the browser can play.
  • HTMLVideoElementSink — a CanvasSink-shaped sink backed by a hidden <video> element and canvas.drawImage. VideoCache.initializeSink selects it only when VideoDecoder is undefined; otherwise it keeps using mediabunny's CanvasSink unchanged.
  • FallbackAudioBufferSink — an AudioBufferSink-shaped sink backed by AudioContext.decodeAudioData, which uses the platform's native audio decoders rather than WebCodecs. AudioManager and the import-time decode path swap to it when audioTrack.canDecode() returns false. runClipIterator is wrapped in a try/catch so a sink failure no longer leaves an unhandled rejection.

Test plan

  • [x] Unit tests (`bun test`) for FPS clamping, frame timing, dispose semantics, WebCodecs/AudioDecoder availability probes, AudioBuffer slicing, and the fallback iterator contract — 19 tests passing.
  • [x] Manual verification on a browser without WebCodecs: import an H.264 AVC mp4, scrub the timeline, play with audio. Video frames render and audio is audible. Confirmed via console:
    • `[VideoCache] WebCodecs unavailable; using HTMLVideoElement fallback for video preview.`
    • `[AudioManager] WebCodecs unavailable; using decodeAudioData fallback for audio clip.`
  • [x] On a WebCodecs-capable browser, behavior is unchanged (no fallback warnings, mediabunny's CanvasSink / AudioBufferSink remain in use).

Notes

  • The fallback sinks duck-type mediabunny's sink interfaces (`canvases(start, end)`, `buffers(start, end)`) so consumers can swap implementations transparently.
  • Server-side ffmpeg conversion currently runs synchronously per upload; future improvement could stream the response or report progress.
  • The fallback path decodes the entire audio file upfront via `decodeAudioData`. For very large clips this trades memory for the ability to play at all on browsers that otherwise can't.

Summary by CodeRabbit

  • New Features

    • On-demand video conversion endpoint producing H.264/MP4 downloads.
    • Client-side video conversion integration for undecodable codecs.
    • HTML-video–based frame-extraction fallback for broader browser support.
  • Enhancements

    • WebCodecs-aware audio decoding with a robust fallback path.
    • Improved media processing flow with safer error handling, resource cleanup, and progress reporting.
  • Tests

    • New unit tests covering audio fallback, video fallback, slicing, and frame extraction behaviors.

Review Change Stack

avillagran avatar May 16 '26 23:05 avillagran

@avillagran is attempting to deploy a commit to the OpenCut OSS Team on Vercel.

A member of the Team first needs to authorize it.

vercel[bot] avatar May 16 '26 23:05 vercel[bot]

📝 Walkthrough

Walkthrough

Adds server-side ffmpeg conversion API and client helper, implements fallback audio/video decoding sinks (with tests) for environments lacking WebCodecs, and integrates these fallbacks into audio manager, media processing, and the video cache service.

Changes

Video Codec Conversion and WebCodecs Fallback Support

Layer / File(s) Summary
Server-side ffmpeg video conversion API
apps/web/src/app/api/convert-video/route.ts
POST endpoint accepts multipart file, writes temp input, runs ffmpeg to convert to H.264/AAC MP4, returns video/mp4 attachment with sanitized filename, and attempts temp-dir cleanup.
Fallback audio decoding sink implementation
apps/web/src/services/audio-cache/fallback-audio-buffer-sink.ts
Adds AudioBufferSinkLike, isWebAudioDecoderAvailable, FallbackAudioBufferSink (decodes via AudioContext), decodeArrayBuffer, and sliceAudioBuffer.
Fallback audio decoding tests
apps/web/src/services/audio-cache/__tests__/fallback-audio-buffer-sink.test.ts
Tests availability detection, sliceAudioBuffer slicing/clamping, and FallbackAudioBufferSink.buffers() semantics and metadata getters.
AudioManager and media/audio integration
apps/web/src/core/managers/audio-manager.ts, apps/web/src/media/audio.ts
Switches sinks to AudioBufferSinkLike, probes canDecode() safely via safeCanDecode, selects WebCodecs or fallback sink, updates getAudioSink/decodeClipBuffer, and adds iterator error handling.
Client-side video conversion wrapper
apps/web/src/media/ffmpeg-convert.ts
convertVideoToH264 POSTs a File to /api/convert-video, surfaces JSON/status errors, and returns a .mp4 File.
Media processing video conversion integration
apps/web/src/media/processing.ts
Imports convertVideoToH264, converts undecodable videos to H.264 MP4, manages temporary URLs and storage checks, re-reads metadata, emits toasts, and pushes processed video assets.
Fallback video decoding sink implementation
apps/web/src/services/video-cache/html-video-element-sink.ts
Adds FrameSink and VideoElementHandle interfaces, createHTMLVideoElementHandle, HTMLVideoElementSink producing canvas frames with FPS clamping, and helpers isWebCodecsAvailable/clampFallbackFps.
Fallback video decoding tests
apps/web/src/services/video-cache/__tests__/html-video-element-sink.test.ts
Tests FPS clamping, WebCodecs detection, async frame iteration/timestamps, seek error handling, disposal, and canvas sizing.
Video cache service fallback integration
apps/web/src/services/video-cache/service.ts
Stores generic FrameSink + dispose() in cache, initializes HTMLVideoElementSink fallback when WebCodecs unavailable, and updates cleanup to call dispose().

Sequence Diagram(s)

sequenceDiagram
  participant User
  participant API as POST /api/convert-video
  participant FFMPEG as ffmpeg
  participant FS as Filesystem

  User->>API: POST video file
  API->>FS: write temp input
  API->>FFMPEG: spawn conversion
  FFMPEG->>FS: write output MP4
  API->>FS: read result
  API->>User: return MP4 blob
  API->>FS: cleanup temps

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

🐰 I hopped through bytes and codecs tight,
Poked ffmpeg to set video right,
When WebCodecs hides, I softly fall back,
With audio buffers and canvas on track,
A joyful hop—now every file takes flight.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The repository's PR template explicitly states 'We are not currently accepting PRs except for critical bugs' and requires issue approval first. The PR description does not acknowledge or address this policy. Address the PR template requirements: either confirm this is a critical bug with prior issue approval, or open an issue for discussion as instructed by the template.
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 clearly and concisely summarizes the main change: adding fallback support for browsers without WebCodecs API using FFmpeg and HTML5 technologies.
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.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • [ ] Create PR with unit tests

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

coderabbitai[bot] avatar May 16 '26 23:05 coderabbitai[bot]

Thanks for the review @coderabbitai. Pushed a force-push that addresses the actionable findings:

  • Temp-file collisions (route.ts): swapped Date.now() for a per-request unique dir via fs.mkdtemp(...). Cleanup uses rm -rf on the directory in finally.
  • Server diagnostics leak (route.ts): catch handler no longer returns error.message; client gets a generic "Video conversion failed." while the full error is still console.error'd server-side.
  • Unused onProgress param (ffmpeg-convert.ts): removed.
  • Post-conversion validation (processing.ts): re-runs the quota check against the converted file's size and fails the import if it no longer fits. If the converted file still reports canDecode === false, we now emit a soft "preview may be limited" toast rather than silently importing — the HTMLVideoElementSink fallback handles preview rendering in that case.
  • NaN guard in FallbackAudioBufferSink.buffers: non-finite startTimestamp is coerced to 0 before clamping. Added a unit test.
  • HTMLVideoElementSink constructor fps clamp: constructor now routes the incoming fps through clampFallbackFps, so direct new HTMLVideoElementSink({ handle, fps: 0 }) callers can no longer divide by zero. Added a unit test.

Skipped:

  • The "don't use console" suggestions. The web app currently uses console.warn / console.error in ~40 places across services (services/storage/service.ts, services/renderer/*, etc.) and there is no shared logger module. Routing only these new warnings through a logger that doesn't exist yet would be inconsistent. Happy to follow up separately if a logger lands.

Tests still green (bun test on the two fallback test files, 21/21).

avillagran avatar May 17 '26 00:05 avillagran

@avillagran — great follow-up, this addresses everything cleanly. A few quick notes on the individual items:

  • mkdtemp + rm -rf — the right call; eliminates the race condition and ensures both files are cleaned up atomically even if the output write fails mid-stream.
  • Generic client error — exactly the right split: operational context server-side, no internal paths/messages leaking to the client.
  • Post-conversion quota + canDecode toast — good defensive layering; the soft toast path is a much better UX than a silent import that later fails in unexpected ways.
  • NaN guard + fps clamp with tests — solid; guarding invariants at the constructor boundary rather than relying on callers is the right approach.
  • Console skip — the rationale holds. Introducing a logger abstraction only for the new code, when the rest of the service layer doesn't have one, would create more inconsistency than it solves. A follow-up that lands a unified logger and migrates all ~40 sites makes sense as a separate concern.

All 21/21 tests green and every actionable finding addressed. I'll go ahead and resolve my open review comments. Would you like me to trigger a fresh review pass on the force-pushed branch?

(╯°□°)╯ ✨🐇

✅ Actions performed

Comments resolved. Approval is disabled; enable reviews.request_changes_workflow to allow explicit top-level @coderabbitai resolve or @coderabbitai approve commands.

coderabbitai[bot] avatar May 17 '26 00:05 coderabbitai[bot]

Addressed the follow-up: Content-Disposition filename is now sanitized (strips control chars / quotes / backslashes / non-ASCII, capped at 200 chars, falls back to "video" if empty) via a small sanitizeContentDispositionName helper.

avillagran avatar May 17 '26 00:05 avillagran