KatInterview

Build a Frame-Perfect Video Playback Engine

System DesignModel answer
HardModel answerSystem Designconcurrencythreadingproducer-consumer

Last updated

Implement playback logic for a video player that maintains 25fps timing using thread-safe coordination between frame reading and rendering operations.

You're building the playback engine for a video player application. You have access to a Frame data structure and a VideoPlayer class that exposes two methods:

  • Read() — fetches the next frame from the video source, returning either a frame object or a signal indicating no more frames exist
  • Render(frame) — displays the provided frame on screen

Your task is to implement the on_play_click() function that plays the entire video from beginning to end while maintaining a consistent 25 frames per second playback rate.

Critical constraint: Neither Read() nor Render() supports concurrent calls. These methods access shared internal state and cannot be invoked simultaneously, even with themselves.

Your Design Should Address

  1. Thread safety: How do you prevent concurrent access to the unsafe API methods?
  2. Frame buffering: How do you decouple reading from rendering to handle timing variations?
  3. Timing precision: How do you maintain the 40-millisecond interval between frame presentations?
  4. Completeness: How do you handle the first frame, the last frame, and the transition to end-of-video?
  5. Feasibility: Under what conditions can you guarantee the 25fps target, and when must you acknowledge timing violations?

Questions to Consider

Before designing your solution, think through these architectural decisions:

  • How long can Read() and Render() take in the worst case? Can you prefetch frames before playback starts?
  • Does Render() need to execute on a specific thread (e.g., the main UI thread)?
  • What clock and timing mechanisms are available in your environment?
  • How many frames can you buffer simultaneously?
  • What should happen when a frame isn't ready by its scheduled presentation time?
  • How do you handle stop/pause requests or repeated play button clicks during active playback?

Hints

Hint 1

Consider a producer thread that reads frames ahead of time and a consumer thread that renders them on schedule

Hint 2

Use a bounded queue with synchronization primitives (mutex + condition variables) to coordinate between threads

Hint 3

Schedule rendering using absolute timestamps rather than cumulative delays to prevent drift