Build a Frame-Perfect Video Playback Engine
System DesignModel answerLast 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 existRender(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
- Thread safety: How do you prevent concurrent access to the unsafe API methods?
- Frame buffering: How do you decouple reading from rendering to handle timing variations?
- Timing precision: How do you maintain the 40-millisecond interval between frame presentations?
- Completeness: How do you handle the first frame, the last frame, and the transition to end-of-video?
- 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()andRender()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
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem requires coordinating two concurrent activities—frame acquisition and frame presentation—while respecting strict timing requirements and serialization constraints.
Core Architecture
Two-thread design with bounded buffer:
- Producer thread: Continuously calls
Read()and enqueues frames into a shared buffer - Consumer thread: Dequeues frames and calls
Render()at precise 40ms intervals - Shared buffer: Thread-safe bounded queue that decouples production from consumption
This separation allows reading to run ahead of rendering (within buffer limits), absorbing timing variations in either operation.
Thread Synchronization
Since both APIs are unsafe for concurrent access, we need:
Mutex protection: Each call to Read() or Render() must hold an exclusive lock. The critical insight is that these operations happen on different threads, so the mutex serializes them.
Condition variables for coordination:
not_full: Producer waits on this when buffer is at capacitynot_empty: Consumer waits on this when buffer is emptyshutdown: Signals both threads to terminate cleanly
Producer logic:
while not cancelled:
frame = read_next_frame() # holds lock during Read()
if frame is END_OF_VIDEO:
signal_end_and_exit()
wait_until_buffer_not_full()
enqueue(frame)
signal_not_empty()
Consumer logic:
next_frame_time = current_time()
while not done:
wait_until_buffer_not_empty()
frame = dequeue()
signal_not_full()
sleep_until(next_frame_time)
render_frame(frame) # holds lock during Render()
next_frame_time += 40ms
Timing Strategy
Absolute scheduling: Track the absolute timestamp for each frame rather than sleeping for fixed intervals. This prevents cumulative drift if any individual frame is delayed.
frame_0: t₀
frame_1: t₀ + 40ms
frame_2: t₀ + 80ms
frame_n: t₀ + (n × 40ms)
If frame i renders late, frame i+1 still targets its original absolute time, allowing the system to catch up.
Prefetching: Start reading frames before the first render deadline. This builds up a buffer cushion that absorbs variation in Read() duration.
Feasibility Analysis
The 25fps target is achievable only when:
Necessary condition: max(Read_duration, Render_duration) ≤ 40ms
If either operation takes longer than 40ms, you cannot maintain real-time playback. The buffer helps with variance but not with systematic overruns.
Buffer sizing: If Read takes 30ms and Render takes 35ms, you need enough buffer to cover the period when Read falls behind. A buffer of 5-10 frames typically provides adequate headroom.
Degradation strategy: When a deadline is missed, you have options:
- Drop frames to catch up (visible stutter)
- Render late and accept cumulative delay (audio sync issues)
- Pause and buffer (playback interruption)
Your choice depends on whether you're optimizing for visual smoothness, audio sync, or uninterrupted playback.
Edge Cases and Lifecycle
Initialization: Prefetch several frames before starting the render loop to ensure the first frame displays on time.
Termination: When the producer encounters end-of-video, it must:
- Set an
end_reachedflag - Signal the consumer via condition variable
- Allow the consumer to drain remaining buffered frames
- Clean up both threads after the last frame renders
Cancellation: A separate flag checked by both threads, triggering early exit and resource cleanup.
UI thread affinity: If Render() must run on the UI thread (common in GUI frameworks), the consumer should post render requests to that thread rather than calling directly. This adds scheduling uncertainty.
Complexity
Time: O(n) where n is the number of frames—each frame is read once and rendered once.
Space: O(b) where b is the buffer size, typically a small constant like 10 frames.
Latency: Initial playback starts after prefetching b frames, adding approximately b × Read_duration startup delay.
Common Mistakes
- Relative delays: Using
sleep(40ms)repeatedly accumulates drift over time - Unbounded buffers: Can exhaust memory on slow render paths
- Missing synchronization: Race conditions when checking buffer state or end conditions
- Ignoring thread affinity: Calling UI-bound operations from background threads
- No prefetch: First frame displays late because buffer starts empty
Sample Code Structure
class VideoPlaybackEngine:
def __init__(self, player, buffer_size=10):
self.player = player
self.buffer = deque(maxlen=buffer_size)
self.lock = Lock()
self.not_empty = Condition(self.lock)
self.not_full = Condition(self.lock)
self.cancelled = False
self.end_reached = False
def producer_thread(self):
while not self.cancelled:
frame = self.player.Read()
if frame is END_OF_VIDEO:
with self.lock:
self.end_reached = True
self.not_empty.notify()
break
with self.lock:
while len(self.buffer) >= self.buffer.maxlen:
self.not_full.wait()
self.buffer.append(frame)
self.not_empty.notify()
def consumer_thread(self):
next_time = time.monotonic()
while True:
with self.lock:
while not self.buffer and not self.end_reached:
self.not_empty.wait()
if not self.buffer and self.end_reached:
break
frame = self.buffer.popleft()
self.not_full.notify()
time.sleep_until(next_time)
self.player.Render(frame)
next_time += 0.040 # 40ms in seconds
def on_play_click(self):
self.cancelled = False
producer = Thread(target=self.producer_thread)
consumer = Thread(target=self.consumer_thread)
producer.start()
consumer.start()
return (producer, consumer) # caller manages lifecycle
This design provides the foundation for reliable 25fps playback while respecting the serialization constraints and addressing the key engineering trade-offs.