Skip to content

Vigil (Video + AI Moderation)

  1. What: A video platform where every upload is automatically checked for NSFW content before it’s published, with YouTube-style adaptive streaming.
  2. My role: Solo project. I built everything.
  3. Architecture:
    Client (React + Hls.js) ──upload──► Express API
    ▲ │ 1. save temp file
    │ Socket.io │ 2. FFmpeg: extract 1 frame every N sec
    │ (uploading → analyzing │ 3. NSFWJS on each frame (fast, local)
    │ → processing → ready/rejected) │ 4. borderline/flagged → Clarifai (2nd opinion)
    │ │ 5. if safe → upload to Cloudinary
    └───────────────────────────────────┤ 6. Cloudinary creates HLS renditions
    ▼
    MongoDB/Postgres: video metadata, status, owner
    Playback: client loads .m3u8 from Cloudinary → Hls.js switches 480p–1080p
  4. Hard problem: e.g., moderation was too slow when analyzing too many frames → sampled frames; or false positives → tuned thresholds and added the second layer.
  5. Result: Unsafe content never reaches storage/public; users see live progress.
  6. Improve: Move moderation to a job queue with workers, direct-to-Cloudinary signed uploads, Redis adapter for Socket.io, store moderation scores for human review.

Q: How do you get frames from a video?

“I use FFmpeg to extract frames at a fixed interval, for example 1 frame per second or every few seconds, instead of every frame. A 30fps 5-minute video has 9,000 frames, which is way too many to classify. Sampling gives good coverage at a fraction of the cost.”

Terminal window
ffmpeg -i input.mp4 -vf fps=1 frames/frame_%04d.jpg

(Know the exact command or library you used, e.g. fluent-ffmpeg.)

Q: What is NSFWJS? Where does it run?

“NSFWJS is a pre-trained image classification model (MobileNet/Inception based) running on TensorFlow.js. It returns probabilities for 5 classes: Drawing, Hentai, Neutral, Porn, Sexy. I ran it [on the server with @tensorflow/tfjs-node / in the browser before upload]. On the server I load the model once at startup, not per request, because loading is slow.”

If in the browser: a user could bypass client-side checks, so the server must also verify. Know this weakness.

Q: Why two layers? Why not just one?

“NSFWJS is free and fast but less accurate. It’s a small model and gives false positives on things like skin-colored backgrounds. Clarifai is more accurate but costs money per API call and adds network latency. So NSFWJS screens everything first. Clearly safe frames pass, clearly unsafe frames reject. Only uncertain or flagged frames go to Clarifai for a second opinion. That keeps cost low while keeping accuracy high.”

(If you sent everything to both, say so, and explain that the cascade above is how you’d optimize it.)

Q: What thresholds did you use? How do you decide a video is unsafe?

Example: “A frame is unsafe if Porn + Hentai > 0.7 or Sexy > 0.8. The video is rejected if any frame is confidently unsafe, or if more than X% of frames are borderline. The thresholds were tuned by testing on sample videos. There’s a tradeoff: a lower threshold = fewer misses but more false rejections.”

Q: False positives — what happens to a legit video that gets rejected?

“Right now it’s [rejected with a message]. Better: put it in a manual review queue for an admin. That ties in with my RBAC: Admin/Editor roles can review flagged videos and override the decision.”

Q: Moderation of a long video takes time. Does the HTTP request wait?

“The upload request returns immediately once the file is received, with a video ID and status analyzing. The processing continues in the background, and progress is pushed via Socket.io. For production, I’d move processing to a job queue (BullMQ + Redis) so it survives server restarts and can scale with multiple workers.”

Q: What about audio, or text in the video?

“Not covered. My pipeline only checks visual frames. Audio would need speech-to-text + text moderation. Being upfront about this is better than claiming full coverage.”

Q: What is HLS / adaptive bitrate streaming?

“HLS (HTTP Live Streaming) splits the video into small segments (a few seconds each) encoded at multiple qualities. A master playlist (.m3u8) lists the available qualities (renditions) with their bandwidth and resolution, and each rendition has its own playlist of segments. The player downloads segments one by one, measures download speed and buffer level, and switches quality between segments: slow network → 480p, fast → 1080p. That’s why YouTube changes quality without stopping.”

Q: Who does the transcoding? Cloudinary or you?

“Cloudinary. I upload the original, and Cloudinary generates the HLS renditions using a streaming profile (e.g., sp_auto or hd), served via its CDN. I didn’t write the encoding myself. My part was configuring it and the playback.” (Being honest here is important.)

Q: Why do you need Hls.js? Can't `

“Safari supports HLS natively in <video>, but Chrome and Firefox on desktop don’t. Hls.js uses Media Source Extensions: it fetches the playlist and segments with JS and feeds them into the video element. Typical code: if (Hls.isSupported()) { const hls = new Hls(); hls.loadSource(url); hls.attachMedia(video); } else if (video.canPlayType('application/vnd.apple.mpegurl')) video.src = url;”

Q: HLS vs DASH vs just serving an MP4?

“A single MP4 is one quality. Slow users buffer, and you can’t adapt. HLS and DASH both do adaptive streaming. HLS is Apple’s and has the widest support (native on iOS). DASH is an open standard, not native on iOS. I chose HLS for compatibility.”

Q: Why Socket.io and not polling or SSE?

“Status updates are server → client pushes at unpredictable times. Polling wastes requests and adds delay. SSE would actually work too, since it’s one-directional. I chose Socket.io for rooms, automatic reconnection and fallback. Each user joins a room keyed by their userId or videoId, and the server emits status events to that room.”

Q: The user refreshes the page during processing. What happens?

“The socket disconnects and reconnects, but events emitted while disconnected are lost. So the source of truth is the DB: the status is stored on the video record, and on reconnect the client fetches the current status via REST, then listens for further updates.”

Q: How would you scale Socket.io to multiple servers?

“Two issues. (1) The processing server emitting the event may not be the one holding the user’s socket → use the Redis adapter, which broadcasts events across instances via Redis pub/sub. (2) The long-polling fallback needs sticky sessions at the load balancer.”

Q: Write your RBAC middleware.
const jwt = require('jsonwebtoken');
function authenticate(req, res, next) {
const token = req.cookies.token || req.headers.authorization?.split(' ')[1];
if (!token) return res.status(401).json({ error: 'Not authenticated' });
try {
req.user = jwt.verify(token, process.env.JWT_SECRET); // { id, role }
next();
} catch {
return res.status(401).json({ error: 'Invalid or expired token' });
}
}
const authorize = (...roles) => (req, res, next) =>
roles.includes(req.user.role)
? next()
: res.status(403).json({ error: 'Forbidden' });
app.delete('/videos/:id', authenticate, authorize('admin'), deleteVideo);
app.patch('/videos/:id', authenticate, authorize('admin', 'editor'), updateVideo);

Key points: 401 = not logged in, 403 = logged in but not allowed. The role comes from the verified token or DB, never from the request body.

Q: The role is in the JWT. If you demote an admin, they stay admin until expiry. Fix?

“Options: short-lived access tokens (15 min) + refresh tokens, so the role refreshes soon; or look up the role from the DB on sensitive routes; or keep a token version on the user and reject tokens with an old version. The tradeoff is more DB lookups vs a staleness window.”

Q: Where do you store the JWT on the client?

“Ideally in an httpOnly, Secure, SameSite cookie, so JS can’t read it, which protects against XSS stealing it. localStorage is readable by any script on the page. With cookies, you need CSRF protection (SameSite=Lax/Strict helps).” (Say what you actually did, and if it was localStorage, say you’d change it.)

Q: 10,000 uploads per day. What breaks first?

“(1) CPU: FFmpeg + TF.js inference on the API server blocks other requests → separate worker processes via a queue. (2) Clarifai costs scale per frame → the cascade + fewer sampled frames. (3) Uploads going through my server use bandwidth/disk → signed direct uploads to Cloudinary/S3, then moderation pulls from storage (stored as private until approved). (4) Socket.io → Redis adapter.”