AI video models are picky about their input. A clip that plays fine on a phone can still be rejected upstream for its length, its shape or its audio track, or it can produce a broken result. Each failure costs a paid generation and a confused user.

We run every uploaded video through a small Node 22 + FFmpeg service before it reaches the model. This post covers the five checks that removed most of our failed jobs, with the commands we actually use.

1. Lock FFmpeg down before it touches an upload

An uploaded file is untrusted input, and FFmpeg can open network URLs and many exotic formats. The preparation service allows only the demuxers it needs and only local file protocols:

const args = [ '-xerror', '-format_whitelist', 'mov,png_pipe,jpeg_pipe,webp_pipe,bmp_pipe', '-protocol_whitelist', 'file,pipe', // ...the actual job ]; await execFile('ffmpeg', args, { timeout: 120_000, killSignal: 'SIGKILL' }); 

Three details matter here:

  • -format_whitelist stops a renamed file from reaching a demuxer you never meant to expose. MP4 and MOV both use the mov demuxer.
  • -protocol_whitelist file,pipe blocks http, concat and friends inside crafted playlists.
  • Every command has a timeout and a hard kill. A malformed file should fail fast instead of tying up a worker.

We also never return FFmpeg's raw error to the user. It can contain local paths and metadata from the upload, so the service maps every failure to one plain message.

2. Measure duration the way the model does

Our model accepts 4 to 30 seconds. The first version read format.duration and called it done. It wasn't enough.

A video file has several durations: the container's, the picture track's and the audio track's, each with its own start offset. A phone recording often has an audio track that runs a few milliseconds past the picture. Opus audio in MP4 can also start at a positive offset. The model counts the longest track, so a "29.98 second" video can be rejected as over 30.

We compute two numbers with ffprobe -show_streams -show_format:

  • duration: the picture track, which is what the user sees.
  • mediaDuration: the maximum of the container duration and every audio or video stream's duration + start_time.

The picture must be 4 to 30 seconds. The whole file must also be at most 30 seconds. When only a tiny audio tail (50 ms or less) crosses the limit, we trim the audio against the picture timeline and leave the video stream untouched:

ffmpeg -i in.mp4 -map 0:v:0 -map 0:a? -c:v copy \ -c:a aac -b:a 192k -af "atrim=end=29.97" -movflags +faststart out.mp4 

After the fix we hash the video packets of both files (-c:v copy -f hash -hash sha256) to prove the picture did not change. Anything longer than a 50 ms tail goes back to the user with the exact numbers, so they know what to trim.

3. Cut exactly where asked, and aim a little short

Free previews keep 5 seconds, and long uploads keep the 30-second part the user picks. Stream copy (-c copy) cuts on keyframes, so the clip can start a second early or run long. We re-encode instead, so the cut lands on the requested frame:

ffmpeg -ss 12.000 -i in.mov -t 4.950 \ -map 0:v:0 -map 0:a:0? -c:v libx264 -preset veryfast -crf 18 \ -pix_fmt yuv420p -c:a aac -b:a 192k -movflags +faststart out.mp4 

Note -t 4.950 for a 5-second clip. Frame and audio rounding can add a few milliseconds, and video APIs often bill any started second as a whole second. Aiming 50 ms short keeps a 5-second clip billed as 5 seconds. We re-probe the output and reject it if it still came out too long.

4. Center-crop extreme aspect ratios instead of failing

Phone screen recordings are tall, for example 790 × 2140. That is about 2.7:1, and our model rejects anything beyond 2.5:1 in either direction. Instead of an error, we crop the long side, centered, to the limit:

ffmpeg -i in.mp4 -map 0:v:0 -map 0:a:0? \ -vf "crop=w=min(iw\,2*floor(ih*2.5/2)):h=min(ih\,2*floor(iw*2.5/2))" \ -c:v libx264 -preset veryfast -crf 18 -pix_fmt yuv420p -c:a aac out.mp4 

The crop runs after FFmpeg applies rotation metadata, so iw and ih are the upright picture the user sees. The 2*floor(.../2) keeps both sides even, which H.264 with yuv420p requires. Videos already inside the limit are never re-encoded.

5. Find shot changes, including the soft ones

When a clip has several shots, the model needs to know where each shot starts. If it misses a cut, the generated video can drift back to the original person after that cut.

FFmpeg's scene filter finds hard cuts cheaply:

ffmpeg -i in.mp4 -map 0:v:0 -an \ -vf "setpts=PTS-STARTPTS,scale=320:-2,select='gt(scene,0.3)',showinfo" \ -f null - 2>&1 | grep -o 'pts_time:[0-9.]*' 

It misses soft transitions: fades through black, flashes and whip pans in dark footage. For those, we decode the clip into tiny 32 × 18 RGB thumbnails at 30 fps (-f rawvideo -pix_fmt rgb24) and look at two signals in Node:

  • Correlation between neighbouring frames. Each thumbnail is normalized per channel (subtract the mean, divide by the standard deviation), so a brightness change alone does not look like a cut. A correlation below 0.35 between two frames with real contrast counts as a cut.
  • Brightness dips. When brightness falls below 45% of the level on both sides for at most 1.5 seconds, and the pictures before and after the dip differ, the darkest frame counts as a cut.

Soft cuts closer than 0.5 seconds to another cut, or to either end of the clip, are dropped. The pass stays cheap because each 32 × 18 frame is only 1,728 bytes, so a 15-second clip is under 1 MB of raw pixels.

What else runs on every file

  • Photos are decoded completely, not just probed. A truncated JPEG often probes fine, so we also walk the JPEG markers and require a real end-of-image marker.
  • PNG transparency is checked pixel by pixel with alphaextract. A PNG with an alpha channel but no transparent pixels gets the channel removed, and we compare picture hashes before and after. A photo that really is transparent is sent back with a request to fill the background.
  • Jobs are isolated. Each preparation gets its own temporary directory that expires after ten minutes, and a service instance runs at most two preparations at once.

Background

We built this service for Genjutsu AI, a tool that swaps a person or object in a short video with one from a photo. The checks above are model-agnostic, though. If you send user video to any generation API, measuring duration across all tracks and handling extreme aspect ratios before upload will save you paid retries.