Skip to content

feat(media): implement video transcoding and HLS chunking pipeline with signed CloudFront cookies - #1977

Open
Alhaandr wants to merge 1 commit into
StellarDevHub:mainfrom
Alhaandr:feature/issue-1844-video-transcoding-hls-signed-cookies
Open

Alhaandr wants to merge 1 commit into
StellarDevHub:mainfrom
Alhaandr:feature/issue-1844-video-transcoding-hls-signed-cookies

Conversation

@Alhaandr

Copy link
Copy Markdown

Summary

This pull request implements an automated video transcoding and HTTP Live Streaming (HLS) chunking pipeline along with AWS CloudFront signed cookies validated against student enrollment records, resolving issue #1844 ([BE-097]).

Raw MP4 video lectures cause excessive buffering for students with fluctuating bandwidth and permit unauthorized downloads that bypass course enrollment paywalls. This solution converts uploaded MP4 videos into adaptive multi-bitrate HLS streams (1080p, 720p, 480p) using FFmpeg, generates standard variant and master playlists (master.m3u8), and restricts access to HLS manifests and segment chunks (.ts) via cryptographic AWS CloudFront signed cookies tied to active student enrollment records.

What changed

  1. Video Transcoding Worker (backend/src/workers/videoTranscodingWorker.ts):
    • Defined adaptive multi-bitrate HLS profiles (1080p @ 5000 kbps, 720p @ 2800 kbps, 480p @ 1200 kbps) with matching video/audio bitrates and resolutions.
    • Implemented transcodeVideoToHls using FFmpeg CLI arguments for HLS chunking (6s target duration, mpegts chunks, vod playlist type) and generated the master.m3u8 adaptive bitrate manifest.
    • Built BullMQ queue processor (createVideoTranscodingProcessor) and integrated startVideoTranscodingWorker / stopVideoTranscodingWorker / enqueueVideoTranscoding.
  2. CloudFront Signed Cookie Service (backend/src/services/cloudfrontCookieService.ts):
    • Implemented RFC 4648 / CloudFront URL-safe base64 conversion.
    • Implemented generateCloudFrontSignedCookies creating minified custom policy statements with expiration and RSA-SHA1 signatures using CloudFront key pairs (CloudFront-Key-Pair-Id, CloudFront-Policy, CloudFront-Signature).
    • Implemented verifyCloudFrontSignedCookies for signature validation, expiry checks, and wildcard resource pattern matching.
    • Included robust cookie header parsing and fallback keypair generation for development and test environments.
  3. Queue Manager & Queue Workers Integration (backend/src/queues/queueManager.ts, backend/src/workers/queueWorkers.ts):
    • Added VIDEO_TRANSCODING: 'video-transcoding' to QUEUE_NAMES and standard tier queue definitions.
    • Registered worker start and stop hooks into the centralized queue manager lifecycle.
  4. Media Routes & Controller (backend/src/controllers/mediaController.ts, backend/src/routes/media.routes.ts):
    • Added POST & GET /media/courses/:courseId/videos/:videoId/session: Validates student enrollment against database records, returning HTTP 403 for unenrolled students, and sets signed CloudFront cookies on response for enrolled students.
    • Added GET /media/courses/:courseId/videos/:videoId/hls/:file: Protects all manifests and .ts video chunks. Verifies CloudFront signed cookies (or authenticated student enrollment); rejects unauthorized/unenrolled requests with HTTP 403 Forbidden.
    • Added POST /media/transcode: Protected route to enqueue video transcoding jobs.
  5. Authentication Middleware (backend/src/middleware/auth.ts):
    • Added optionalAuthenticateToken helper allowing routes (such as video segment streaming) to support either CloudFront cookies or Authorization headers.
  6. Tests:
    • backend/tests/videoTranscodingWorker.test.ts: Unit tests covering HLS profiles, master playlist generation, FFmpeg argument construction, job validation, and BullMQ worker execution.
    • backend/tests/cloudfrontCookies.test.ts: Unit tests for CloudFront base64 encoding, policy generation, signed cookie issuance, expiration, tampering, and signature verification.
    • backend/tests/media.routes.test.ts: Integration tests verifying 401 unauthenticated, 403 for unenrolled users, 200 for enrolled students, and valid HLS chunk serving.

Why

Course video lectures need to adapt dynamically to student connection speeds to prevent buffering while ensuring intellectual property protection and enrollment enforcement. Adaptive HLS streams switch bitrates seamlessly, and CloudFront signed cookies provide scalable edge-level tokenized authentication validated against enrollment records.

Testing performed

  • Ran backend Jest test suites:
    • backend/tests/videoTranscodingWorker.test.ts (passed)
    • backend/tests/cloudfrontCookies.test.ts (passed)
    • backend/tests/media.routes.test.ts (passed)
    • backend/tests/queueWorkers.test.ts (passed)
    • 50 passing tests total across all 4 suites.
  • Ran backend build validation (npm --prefix backend run build):
    • Prisma client generation completed without errors.
    • TypeScript compiler (tsc) finished with zero errors.

Risks considered

  • Key Pair Configuration: In development or CI environments where CLOUDFRONT_PRIVATE_KEY is not present, an in-memory keypair is automatically generated to allow local test execution and development without external dependencies. In production, keys are loaded from environment variables.
  • Worker Resource Consumption: Transcoding concurrency is constrained via the BullMQ queue definition (concurrency: 2) and per-user rate limiting to prevent CPU exhaustion.

Edge cases handled

  • Unenrolled students attempting to create stream sessions receive HTTP 403.
  • Requests to .ts video segments with expired, tampered, or missing cookies receive HTTP 403.
  • Video players accessing segments with signed cookies without Authorization headers succeed seamlessly.
  • Malformed transcoding job payloads fail immediately with BullMQ UnrecoverableError without burning retries.

Closes #1844

@vercel

vercel Bot commented Nov 24, 2026

Copy link
Copy Markdown

@Alhaandr is attempting to deploy a commit to the Ayomide Adeniran's projects Team on Vercel.

A member of the Team first needs to authorize it.

@drips-wave

drips-wave Bot commented Nov 24, 2026

Copy link
Copy Markdown

@Alhaandr Great news! 🎉 Based on an automated assessment of this PR, the linked Wave issue(s) no longer count against your application limits.

You can now already apply to more issues while waiting for a review of this PR. Keep up the great work! 🚀

Learn more about application limits

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BE-097] Video Transcoding & HLS Chunking Pipeline with Signed CloudFront Cookies

1 participant