Concurrent 25 FPS Video Playback Engine
Hard · Software Engineering Fundamentals · Software Engineer · Technical Screen
Problem Statement
Media replay tools must present recorded frames at a steady wall-clock rate (such as 25 frames per second, or one frame every 40 ms) even when upstream decompression time varies sharply from frame to frame.
Implement a thread-safe VideoPlayer coordinating a background producer thread that pulls frames from a FrameDecoder and a background consumer thread that pushes frames to a DisplaySink on a drift-free monotonic schedule:
from dataclasses import dataclass
from typing import Optional
IDLE = "idle"
PLAYING = "playing"
PAUSED = "paused"
STOPPED = "stopped"
@dataclass
class VideoFrame:
pts_ms: int
data: bytes = b""
class FrameDecoder:
def read_frame(self) -> Optional[VideoFrame]: ...
class DisplaySink:
def render(self, frame: VideoFrame) -> None: ...
class VideoPlayer:
def __init__(
self,
decoder: FrameDecoder,
sink: DisplaySink,
target_fps: int = 25,
max_buffer_size: int = 10,
): ...
@property
def state(self) -> str: ...
def play(self) -> None: ...
def pause(self) -> None: ...
def stop(self) -> None: ...
def join(self, timeout: Optional[float] = None) -> bool: ...
Your engine must uphold five behavioral guarantees:
- Drift-free monotonic scheduling: Deliver one frame every
1.0 / target_fpsseconds (40 msat25 FPS) anchored to a monotonic clock so nonzerorender()durations or OS wake-up jitter never accumulate across successive frames. - Bounded producer-consumer buffer: Store decoded frames in a thread-safe FIFO buffer capped at
max_buffer_sizeitems. Whenever the buffer is full, the decoder thread must sleep until space opens or playback stops. - Race-free lifecycle controls:
- Begin in
"idle"withframes_rendered = 0andunderruns = 0. play()starts worker threads from"idle"or resumes rendering from"paused", transitioningstateto"playing". Callingplay()while already"playing"or after"stopped"must be a safe no-op.pause()transitions"playing"to"paused", halting frame presentation without terminating worker threads or discarding buffered frames.stop()transitions to"stopped", flushes queued frames, wakes any blocked worker threads, and waits for them to exit.join(timeout)waits up totimeoutseconds in total for worker threads to finish and returnsTrueif none remain alive.
- Begin in
- Zero-spin buffer underruns: If a scheduled frame deadline arrives when the buffer is empty (before end-of-stream), increment
self.underruns, sleep without busy-waiting, and advance cleanly to the next monotonic grid slot rather than bursting late frames back-to-back once decoding catches up. - End-of-stream (
None) completion: Whendecoder.read_frame()returnsNone, every already-decoded frame ahead of it must still be rendered on schedule, after whichstatetransitions to"stopped"and both worker threads exit cleanly without deadlocking.
Examples
Example 1
# 5 frames with pts_ms = [0, 40, 80, 120, 160], followed by None (EOS)
player = VideoPlayer(decoder, sink, target_fps=50, max_buffer_size=3)
assert player.state == "idle"
player.play()
player.play() # idempotent while already playing
assert player.join(timeout=1.0) is True
assert rendered_pts == [0, 40, 80, 120, 160]
assert player.frames_rendered == 5
assert player.underruns == 0
assert player.state == "stopped"
Walk-through:
The first play() launches one decoder thread and one render thread; the second play() is ignored. Although max_buffer_size is 3, the decoder blocks whenever 3 frames sit queued and resumes as the renderer pops frames. After all 5 frames are shown in order, the end-of-stream marker transitions state to "stopped" and both threads exit.
Example 2
# 4 frames (pts_ms = [0, 40, 80, 120]) at 25 FPS (40 ms period), max_buffer_size = 2
# Frames 0, 1, 3 decode in < 1 ms; Frame 2 (pts_ms = 80) takes 110 ms to decode.
player = VideoPlayer(stalling_decoder, sink, target_fps=25, max_buffer_size=2)
player.play()
assert player.join(timeout=1.0) is True
assert rendered_pts == [0, 40, 80, 120]
assert player.frames_rendered == 4
assert player.underruns >= 1
assert player.state == "stopped"
Walk-through:
Frame 0 renders at 0 ms and Frame 1 at 40 ms. At the 80 ms deadline, Frame 2 is still decoding (110 ms), so the buffer is empty: underruns increments to 1, and the renderer advances its deadline to 120 ms while sleeping on a condition variable. Frame 2 finishes around 110 ms and renders cleanly on the 120 ms grid mark, followed by Frame 3 at 160 ms (spanning ~160 ms from first to last render rather than rushing Frames 2 and 3 immediately at 110 ms).
Constraints
target_fps > 0andmax_buffer_size > 0(raiseValueErrorotherwise).decoder.read_frame()latency can vary between0 msand80+ msper frame; never hold an internal state lock acrossread_frame()orsink.render(frame).- Busy-waiting (
while ...: pass) is prohibited; blocked threads must consume near-zero CPU. stop()must finish tearing down worker threads within200 ms, whether called during normal playback, while paused, while the buffer is full, or during a slow80 msdecode.
Step-by-step walkthrough
Restate the problem and lock down state transitions
We need to connect two operations with very different timing behaviors: -
decoder.read_frame()takes anywhere from 5 ms to 80 ms per frame and returnsNoneat End-of-Stream (EOS) (when no frames remain). -sink.render(frame)must be called on a steady heartbeat ofperiod = 1.0 / target_fpsseconds (40 msat25 FPS).To make the engine deterministic and easy to test, we pin down every state transition up front: - The player starts in
"idle", moves between"playing"and"paused", and finishes in"stopped"either whenstop()is called or after the last decoded frame has been shown. -play()while already"playing"is a harmless no-op (idempotent, meaning calling it multiple times has the exact same effect as calling it once). -pause()freezes rendering without killing the worker threads or dropping buffered frames; the decoder can still top up the buffer up tomax_buffer_sizeso resuming is instant. -stop()is terminal: it flushes the buffer, wakes every sleeping thread so shutdown finishes well within 200 ms, and waits for both threads to exit.Current state \ Call play() pause() stop() EOS reached ------------------------------------------------------------------------------------------ "idle" -> "playing" (spawn) "idle" -> "stopped" - "playing" "playing" (no-op) -> "paused"-> "stopped" -> "stopped" "paused" -> "playing" (resume) "paused" -> "stopped" stays "paused" "stopped" "stopped" (no-op) "stopped" "stopped" (no-op) -Why single-threaded loops and relative sleeps fail
Two beginner designs look tempting at first glance, and both break down immediately:
- One thread running
decode -> render -> sleep: Whenever a tough keyframe takes 80 ms to decode, the 40 ms deadline is missed by 40 ms — even if the previous ten frames decoded in 5 ms each! Putting a bounded buffer (a fixed-capacity FIFO queue) between a producer thread (decoder) and a consumer thread (renderer) absorbs those spikes: fast 5 ms decodes build up a cushion of up tomax_buffer_sizeframes (10 * 40 ms = 400 msof reserve at 25 FPS) that keeps the screen smooth through temporary 80 ms stalls. - Relative sleeps (
render(frame); time.sleep(0.040)): Every render call takes some time (say 8 ms) and the OS scheduler wakes threads slightly late (say 2 ms). Sleeping a fresh 40 ms after each render stretches every frame interval to8 + 40 + 2 = 50 ms(20 FPS instead of 25 FPS), and the error accumulates forever:
Relative sleep(40 ms) after a 10 ms render (cumulative drift!): Frame: F0 F1 F2 F3 Time (ms): 0 --------> 50 -------> 100 ------> 150 (already 30 ms late by Frame 3!) [10 render + 40 sleep] Absolute grid deadlines (start + k * 40 ms on time.monotonic()): Frame: F0 F1 F2 F3 Time (ms): 0 ------> 40 -----> 80 -----> 120 (zero cumulative drift!) [10 render + 30 sleep]Anchoring a grid
deadline = start + k * periodontime.monotonic()(a stopwatch clock that ticks steadily forward and never jumps backward if the system wall clock is adjusted by NTP) eliminates cumulative drift completely.- One thread running
Coordinate two threads safely with one Condition
All shared state —
self._buffer(acollections.deque),self._state,self._threads, and the counters — is guarded by a singlethreading.Condition(a mutex lock paired with a wait room where threads sleep with 0% CPU until notified).+--------------------------------------+ | Shared under self._cond | Decoder Thread | _state: "idle"|"playing"|... | Render Thread read_frame() -->| _buffer: deque([F0, F1, ..., _EOS]) |--> sink.render() (outside lock) | capacity = max_buffer_size | (outside lock) +--------------------------------------+Every change to
_bufferor_statecallsself._cond.notify_all(), and each thread checks its own wait condition inside awhileloop: - Decoder waits while:_state != "stopped"andlen(_buffer) >= _capacity. - Renderer waits while:_state == "paused", or waiting for the initial frame (not _buffer), or waiting fortime.monotonic()to reachdeadlineviaself._cond.wait(remaining).Three rules guarantee zero deadlocks and sub-200 ms shutdown: 1. Never hold
self._condwhile callingread_frame()orrender(). Those calls can take 80 ms, so holding the lock would stallpause()andstop(), and would deadlock if a callback insiderender()calledplayer.stop(). 2. Always re-check conditions withwhile, neverif. Becausenotify_all()wakes both threads on any state or buffer change, a woken thread must confirm its specific condition is now satisfied. 3. Pass End-of-Stream through the buffer as a sentinel object (_EOS). Putting_EOSbehind the lastVideoFrameguarantees the renderer displays every buffered frame before transitioning to"stopped".Implement state controls: play, pause, stop, and join
Each public control method acquires
self._cond, checks whether the state transition is valid, updatesself._state, and broadcastsnotify_all(). Notice two subtle safety details instop()andjoin(): -stop()setsSTOPPED, clears_buffer, and callsnotify_all()insidewith self._cond:, then callsself.join()outsidewith self._cond:so waking worker threads can acquire the lock to observeSTOPPEDand exit. -join(timeout)tracks a single overallend_timeacross both threads and skipsthreading.current_thread()(preventingRuntimeError: cannot join current threadif aDisplaySinkcallsplayer.stop()from insiderender()).import threading import time from collections import deque from dataclasses import dataclass from typing import Optional IDLE = "idle" PLAYING = "playing" PAUSED = "paused" STOPPED = "stopped" # Unique sentinel object placed in the buffer by the decoder when read_frame() returns None. _EOS = object() @dataclass class VideoFrame: pts_ms: int # presentation timestamp in milliseconds data: bytes = b"" class FrameDecoder: def read_frame(self) -> Optional[VideoFrame]: """Reads the next frame. Returns None on End-of-Stream (EOS).""" raise NotImplementedError class DisplaySink: def render(self, frame: VideoFrame) -> None: """Renders a frame to the screen.""" raise NotImplementedError class VideoPlayer: """Decoder thread -> bounded buffer -> render thread scheduled on a monotonic clock.""" def __init__(self, decoder: FrameDecoder, sink: DisplaySink, target_fps: int = 25, max_buffer_size: int = 10): if target_fps <= 0 or max_buffer_size <= 0: raise ValueError("target_fps and max_buffer_size must be positive") self._decoder = decoder self._sink = sink self._period = 1.0 / target_fps self._capacity = max_buffer_size # _buffer: FIFO deque holding up to _capacity items, e.g. deque([VideoFrame(0), VideoFrame(40), _EOS]) self._buffer = deque() # _cond: single Condition (mutex + wait queue) protecting _buffer, _state, _threads, and counters. self._cond = threading.Condition() self._state = IDLE # _threads: [decoder_thread, renderer_thread], created once on the first play() call. self._threads = [] self.frames_rendered = 0 self.underruns = 0 # render deadlines where _buffer was empty self.late_slots = 0 # whole frame periods skipped after a slow render() call @property def state(self) -> str: with self._cond: return self._state def play(self) -> None: """Starts or resumes playback. No-op while already playing or after stop / EOS.""" with self._cond: # Idempotent when already playing; terminal once stopped. if self._state == PLAYING or self._state == STOPPED: return first_start = self._state == IDLE self._state = PLAYING if first_start: self._threads = [ threading.Thread(target=self._decode_loop, name="decoder", daemon=True), threading.Thread(target=self._render_loop, name="renderer", daemon=True), ] for thread in self._threads: thread.start() # Wake the renderer if it was waiting in PAUSED state. self._cond.notify_all() def pause(self) -> None: """Pauses rendering while keeping worker threads and buffered frames intact.""" with self._cond: if self._state == PLAYING: self._state = PAUSED self._cond.notify_all() def stop(self) -> None: """Stops playback, flushes buffered frames, and waits for worker threads to exit.""" with self._cond: self._state = STOPPED self._buffer.clear() # Wake both threads immediately from full-buffer, paused, or deadline waits. self._cond.notify_all() # Join outside the lock so waking worker threads can acquire self._cond and exit. self.join() def join(self, timeout: Optional[float] = None) -> bool: """Waits up to timeout seconds in total for worker threads to exit; True if all exited.""" with self._cond: threads = list(self._threads) current = threading.current_thread() end_time = None if timeout is None else time.monotonic() + timeout for thread in threads: # Skip current thread in case stop() was called from inside a sink/decoder callback. if thread is current: continue if end_time is None: thread.join() else: remaining = max(0.0, end_time - time.monotonic()) thread.join(remaining) for thread in threads: if thread is not current and thread.is_alive(): return False return TrueImplement the producer: reserving a slot before decoding
The decoder loop enforces
max_buffer_sizewithout holding the lock duringread_frame(). First, it acquiresself._condand waits untillen(self._buffer) < self._capacity. Because this single decoder thread is the only thread that ever appends toself._buffer, that free slot is guaranteed to still be free whenread_frame()finishes 5–80 ms later!When
read_frame()returns, the decoder re-acquiresself._condand checksself._state == STOPPEDa second time. Ifstop()ran whileread_frame()was busy, we must discard the newly decoded frame rather than pushing it into a flushed buffer.def _decode_loop(self) -> None: while True: # Phase 1: Wait until at least one buffer slot is free (or playback stops). with self._cond: while self._state != STOPPED and len(self._buffer) >= self._capacity: self._cond.wait() if self._state == STOPPED: return # Phase 2: Decode outside the lock so an 80 ms read never blocks pause() or stop(). # Because only this single thread appends to _buffer, the reserved slot stays free. frame = self._decoder.read_frame() # Phase 3: Re-check _state (stop() may have run during read_frame), then enqueue. with self._cond: if self._state == STOPPED: return if frame is None: self._buffer.append(_EOS) else: self._buffer.append(frame) self._cond.notify_all() if frame is None: returnImplement the consumer: drift-free deadlines, underruns, and overruns
The render thread tracks
deadline— the targettime.monotonic()timestamp when the next frame should appear: 1. Paused (PAUSED): cleardeadline = Noneand sleep inwait()untilplay()orstop(). 2. Start / resume (deadline is None): wait until_bufferhas at least one item, then setdeadline = time.monotonic(). Starting the clock when frame 0 is actually ready prevents a bogus underrun while frame 0 is still decoding. 3. Timed wait (_sleep_until): computeremaining = deadline - time.monotonic()and sleep withself._cond.wait(remaining). Ifpause()orstop()wakes us early,_sleep_untilreturnsFalseimmediately. 4. Buffer underrun (not self._buffer): incrementself.underrunsand stepdeadline += self._periodonto the next grid point. Instead of spinning CPU or dumping a fast-forward burst when the late frame arrives, the late frame waits cleanly for the next 40 ms beat:Example 2 at 25 FPS (40 ms period) when Frame 2 takes 110 ms to decode: 0 ms -> render Frame 0 40 ms -> render Frame 1 80 ms -> _buffer empty! underruns += 1, advance deadline to 120 ms, sleep via wait() 110 ms -> decoder pushes Frame 2 and calls notify_all(); renderer sees 10 ms left, sleeps 120 ms -> render Frame 2 right on the 40 ms grid (no fast-forward burst!) 160 ms -> render Frame 3- End-of-stream (
_EOS): set_state = STOPPED, clear_buffer, notify, and return. - Render and advance (
_next_deadline): pop the frame, callnotify_all()to free a slot for the decoder, callsink.render(frame)outside the lock, and movedeadline += self._period. If a slowrender()overran by one or more whole periods (for example,deadlinewas1000 ms,render()finished at1105 ms, so1040 msis65 msin the past),_next_deadlineskipsint(65 / 40) = 1whole missed slot to1080 msso playback snaps back onto the grid after at most one late frame.
def _render_loop(self) -> None: # deadline: target time.monotonic() instant for the next frame, or None before schedule starts. deadline = None while True: with self._cond: # Phase 1: If paused, drop the old clock anchor and sleep until play() or stop(). if self._state == PAUSED: deadline = None while self._state == PAUSED: self._cond.wait() if self._state == STOPPED: return # Phase 2: Anchor the schedule when the first frame (or _EOS) arrives, avoiding # a false underrun while the very first frame is still decoding. if deadline is None: while self._state == PLAYING and not self._buffer: self._cond.wait() if self._state != PLAYING: continue deadline = time.monotonic() # Phase 3: Sleep until the target deadline, waking early if paused or stopped. if not self._sleep_until(deadline): continue # Phase 4: Handle empty buffer (underrun) by holding the grid and trying next slot. if not self._buffer: self.underruns += 1 deadline += self._period continue # Phase 5: End-of-stream sentinel reached after all real frames were rendered. if self._buffer[0] is _EOS: self._state = STOPPED self._buffer.clear() self._cond.notify_all() return frame = self._buffer.popleft() # Wake the decoder if it was blocked on a full buffer. self._cond.notify_all() # Phase 6: Render outside the lock so display work never blocks control calls. self._sink.render(frame) with self._cond: self.frames_rendered += 1 if self._state != PLAYING: continue deadline = self._next_deadline(deadline) def _sleep_until(self, deadline: float) -> bool: """Caller holds self._cond. Sleeps until deadline; returns False if state left PLAYING.""" while self._state == PLAYING: remaining = deadline - time.monotonic() # <= 0 means the target instant has arrived (or already passed); render immediately. if remaining <= 0: return True self._cond.wait(remaining) return False def _next_deadline(self, deadline: float) -> float: """Advances to start + k * period, skipping whole missed periods if render() overran.""" deadline += self._period behind = time.monotonic() - deadline if behind >= self._period: skipped = int(behind / self._period) deadline += skipped * self._period with self._cond: self.late_slots += skipped return deadline- End-of-stream (
Complete solution
import threading import time from collections import deque from dataclasses import dataclass from typing import Optional IDLE = "idle" PLAYING = "playing" PAUSED = "paused" STOPPED = "stopped" # Unique sentinel object placed in the buffer by the decoder when read_frame() returns None. _EOS = object() @dataclass class VideoFrame: pts_ms: int # presentation timestamp in milliseconds data: bytes = b"" class FrameDecoder: def read_frame(self) -> Optional[VideoFrame]: """Reads the next frame. Returns None on End-of-Stream (EOS).""" raise NotImplementedError class DisplaySink: def render(self, frame: VideoFrame) -> None: """Renders a frame to the screen.""" raise NotImplementedError class VideoPlayer: """Decoder thread -> bounded buffer -> render thread scheduled on a monotonic clock.""" def __init__(self, decoder: FrameDecoder, sink: DisplaySink, target_fps: int = 25, max_buffer_size: int = 10): if target_fps <= 0 or max_buffer_size <= 0: raise ValueError("target_fps and max_buffer_size must be positive") self._decoder = decoder self._sink = sink self._period = 1.0 / target_fps self._capacity = max_buffer_size # _buffer: FIFO deque holding up to _capacity items, e.g. deque([VideoFrame(0), VideoFrame(40), _EOS]) self._buffer = deque() # _cond: single Condition (mutex + wait queue) protecting _buffer, _state, _threads, and counters. self._cond = threading.Condition() self._state = IDLE # _threads: [decoder_thread, renderer_thread], created once on the first play() call. self._threads = [] self.frames_rendered = 0 self.underruns = 0 # render deadlines where _buffer was empty self.late_slots = 0 # whole frame periods skipped after a slow render() call @property def state(self) -> str: with self._cond: return self._state def play(self) -> None: """Starts or resumes playback. No-op while already playing or after stop / EOS.""" with self._cond: # Idempotent when already playing; terminal once stopped. if self._state == PLAYING or self._state == STOPPED: return first_start = self._state == IDLE self._state = PLAYING if first_start: self._threads = [ threading.Thread(target=self._decode_loop, name="decoder", daemon=True), threading.Thread(target=self._render_loop, name="renderer", daemon=True), ] for thread in self._threads: thread.start() # Wake the renderer if it was waiting in PAUSED state. self._cond.notify_all() def pause(self) -> None: """Pauses rendering while keeping worker threads and buffered frames intact.""" with self._cond: if self._state == PLAYING: self._state = PAUSED self._cond.notify_all() def stop(self) -> None: """Stops playback, flushes buffered frames, and waits for worker threads to exit.""" with self._cond: self._state = STOPPED self._buffer.clear() # Wake both threads immediately from full-buffer, paused, or deadline waits. self._cond.notify_all() # Join outside the lock so waking worker threads can acquire self._cond and exit. self.join() def join(self, timeout: Optional[float] = None) -> bool: """Waits up to timeout seconds in total for worker threads to exit; True if all exited.""" with self._cond: threads = list(self._threads) current = threading.current_thread() end_time = None if timeout is None else time.monotonic() + timeout for thread in threads: # Skip current thread in case stop() was called from inside a sink/decoder callback. if thread is current: continue if end_time is None: thread.join() else: remaining = max(0.0, end_time - time.monotonic()) thread.join(remaining) for thread in threads: if thread is not current and thread.is_alive(): return False return True def _decode_loop(self) -> None: while True: # Phase 1: Wait until at least one buffer slot is free (or playback stops). with self._cond: while self._state != STOPPED and len(self._buffer) >= self._capacity: self._cond.wait() if self._state == STOPPED: return # Phase 2: Decode outside the lock so an 80 ms read never blocks pause() or stop(). # Because only this single thread appends to _buffer, the reserved slot stays free. frame = self._decoder.read_frame() # Phase 3: Re-check _state (stop() may have run during read_frame), then enqueue. with self._cond: if self._state == STOPPED: return if frame is None: self._buffer.append(_EOS) else: self._buffer.append(frame) self._cond.notify_all() if frame is None: return def _render_loop(self) -> None: # deadline: target time.monotonic() instant for the next frame, or None before schedule starts. deadline = None while True: with self._cond: # Phase 1: If paused, drop the old clock anchor and sleep until play() or stop(). if self._state == PAUSED: deadline = None while self._state == PAUSED: self._cond.wait() if self._state == STOPPED: return # Phase 2: Anchor the schedule when the first frame (or _EOS) arrives, avoiding # a false underrun while the very first frame is still decoding. if deadline is None: while self._state == PLAYING and not self._buffer: self._cond.wait() if self._state != PLAYING: continue deadline = time.monotonic() # Phase 3: Sleep until the target deadline, waking early if paused or stopped. if not self._sleep_until(deadline): continue # Phase 4: Handle empty buffer (underrun) by holding the grid and trying next slot. if not self._buffer: self.underruns += 1 deadline += self._period continue # Phase 5: End-of-stream sentinel reached after all real frames were rendered. if self._buffer[0] is _EOS: self._state = STOPPED self._buffer.clear() self._cond.notify_all() return frame = self._buffer.popleft() # Wake the decoder if it was blocked on a full buffer. self._cond.notify_all() # Phase 6: Render outside the lock so display work never blocks control calls. self._sink.render(frame) with self._cond: self.frames_rendered += 1 if self._state != PLAYING: continue deadline = self._next_deadline(deadline) def _sleep_until(self, deadline: float) -> bool: """Caller holds self._cond. Sleeps until deadline; returns False if state left PLAYING.""" while self._state == PLAYING: remaining = deadline - time.monotonic() # <= 0 means the target instant has arrived (or already passed); render immediately. if remaining <= 0: return True self._cond.wait(remaining) return False def _next_deadline(self, deadline: float) -> float: """Advances to start + k * period, skipping whole missed periods if render() overran.""" deadline += self._period behind = time.monotonic() - deadline if behind >= self._period: skipped = int(behind / self._period) deadline += skipped * self._period with self._cond: self.late_slots += skipped return deadline✅ Submit now — all tests should pass.
Intuition & how it works
Think of the player as a movie projector fed by a small tray that holds up to max_buffer_size frames (10 by default). One worker (the producer / decoder thread) unpacks compressed frames at uneven speeds (5 ms to 80 ms) and places them onto the tray, sleeping whenever the tray is full. A second worker (the consumer / render thread) watches a monotonic clock (time.monotonic(), a stopwatch clock that ticks steadily forward and never jumps if the computer's wall-clock time is adjusted) and pulls one frame onto the screen at exact 40 ms marks (0 ms, 40 ms, 80 ms, ...). Both workers coordinate through a single condition variable (threading.Condition, a mutex lock paired with a zero-CPU sleep queue that wakes threads immediately on state or buffer changes).
A naive single-threaded loop (decode -> render -> sleep(0.040)) fails for two separate reasons. First, without a buffer between decoding and rendering, any single 80 ms decode stalls the screen by 40 ms even when surrounding frames decode in 5 ms. Second, sleeping a fixed 40 ms after each render adds every millisecond of render() execution and OS wake-up delay onto all future frames, so a 10 ms render stretches each cycle to 50 ms and drifts 1 full second behind after just 100 frames.
Trace Example 2's 4-frame clip (F0, F1, F2, F3) at 25 FPS (40 ms period) where F0 and F1 are ready quickly, F2 stalls until 110 ms, and F3 finishes right after F2:
1. 0 ms: F0 arrives in _buffer; renderer anchors deadline = 0 ms, pops and renders F0 (which takes 8 ms), then sets deadline = 0 + 40 = 40 ms and sleeps only the remaining 32 ms.
2. 40 ms: Renderer wakes right on schedule, pops and renders F1, and sets deadline = 80 ms.
3. 80 ms: F2 is still decoding, so _buffer is empty (buffer underrun — a deadline arrived with no decoded frame ready); renderer increments underruns = 1, advances deadline = 120 ms, and sleeps via Condition.wait.
4. 110 ms to 200 ms: Decoder pushes F2 at 110 ms (renderer wakes briefly, sees 10 ms still left until 120 ms, and sleeps again), renders F2 cleanly on the 120 ms grid mark, renders F3 at 160 ms, and stops when it sees _EOS (sentinel, a special marker object signaling end-of-stream) at 200 ms.
Complexity
- Time per frame — O(1) scheduling overhead: Aside from the external
decoder.read_frame()andsink.render()calls, each frame performs onedeque.append, onedeque.popleft, a constant number of lock acquisitions, and wake-ups of at most two worker threads, all taking constant time regardless of stream length ormax_buffer_size. - Space — O(max_buffer_size) memory: The
dequeholds at mostmax_buffer_sizeitems because the single decoder thread waits forlen(_buffer) < max_buffer_sizebefore reading a frame, so at mostmax_buffer_sizebuffered frames plus the 1 frame currently insidesink.render()exist in memory at once. - Worker threads — O(1) threads: Exactly two background daemon threads (
decoderandrenderer) are created on the first transition out of"idle"and reused across any number ofpause()/play()cycles. - Shutdown latency — bounded by one in-flight I/O call: Because
stop()clears the buffer and callsnotify_all(), everyCondition.waitwakes immediately, sostop()waits at most for a single already-runningread_frame()(up to 80 ms) orrender()call to return — comfortably within the 200 ms requirement.
Edge cases
- Empty video stream (
read_frame()returnsNoneimmediately): Decoder pushes_EOSinto slot 0; renderer wakes, sees_EOSat the front of_buffer, sets state to"stopped", and exits withframes_rendered == 0andunderruns == 0. - Idempotent and out-of-order control calls: Calling
play()three times in a row spawns only one decoder/renderer pair; callingpause()while"idle"or"paused",stop()beforeplay(),stop()twice, orplay()afterstop()are all safe no-ops. stop()while buffer is full or player is paused: Both threads are parked insideself._cond.wait(), sonotify_all()wakes them immediately and they exit in under a millisecond.stop()during a slow 80 msread_frame(): Whenread_frame()finally returns,_decode_loopre-checksself._state == STOPPEDunder the lock and discards the late frame instead of putting it into the flushed buffer.stop()invoked from inside asink.render()callback:join()compares each worker againstthreading.current_thread()and skips joining itself, avoiding aRuntimeErrorself-join deadlock.max_buffer_size = 1: Works without deadlock — as soon as the renderer pops the single buffered frame (before callingrender()), it callsnotify_all()so the decoder can start decoding the next frame in parallel withrender().- Slow
render()overrunning a whole period:_next_deadlineskips whole elapsed periods (late_slots) so the player does not dump a fast-forward burst of stale frames to catch up.
Common mistakes
- Using relative
time.sleep(1.0 / target_fps)afterrender(): Render duration and OS timer wake-up delay accumulate on every single frame, making playback steadily drift behind real time. - Holding the mutex lock during
read_frame()orrender(): Blockspause()andstop()for up to 80 ms and deadlocks if user sink/decoder code calls back intoplayer.stateorplayer.stop(). - Blocking on
queue.Queue.put()without a wake-up path onstop(): If the buffer is full and the renderer exits first onstop(), a decoder blocked in an untimedqueue.put()never wakes up andjoin()hangs forever. - Checking conditions with
ifinstead ofwhilearoundCondition.wait(): A thread woken bynotify_all()(or a spurious OS wake-up) may find its condition is still false — for instance, the decoder pushing a frame wakes a renderer whose deadline is still 20 ms away. - Busy-waiting (
while not self._buffer: pass) during underruns: Pegs a CPU core at 100% and starves the decoder thread under Python's GIL (Global Interpreter Lock, CPython's mutex allowing only one thread to execute Python bytecode at a time). - Using
time.time()instead oftime.monotonic(): System wall-clock adjustments (NTP syncs, daylight-saving or manual clock edits) can jumptime.time()backward by seconds and freeze playback insidewait(remaining).
Alternative approaches
queue.Queue(maxsize)+threading.Eventwith short polling timeouts: You can pair Python's built-inqueue.Queuewith astop_eventand loop overput(..., timeout=0.02)/get(..., timeout=0.02), which is shorter to write but wakes idle threads 50 times per second and ties shutdown latency to the polling interval.- Scheduling from each frame's
pts_ms(Presentation Timestamp, the exact millisecond offset at which the media container says a frame should be displayed): Settingdeadline = base_time + (frame.pts_ms - first_pts_ms) / 1000.0naturally supports variable-frame-rate (VFR) recordings where sensor frames are not spaced at uniform 40 ms intervals. - Hardware vsync or native real-time threads for sub-2 ms jitter: Monotonic deadlines eliminate cumulative drift, but standard OS
Condition.waitstill has timer slack (the OS scheduler delaying thread wake-ups by 1–10 ms to save power or switch Python's GIL); hitting hard +/- 2 ms bounds under heavy CPU load uses C++/Rust real-time thread priorities and GPU vertical-sync presentation queues.
Follow-up questions
- How would you synchronize video presentation against a hardware audio output stream acting as the reference clock? Because human ears detect tiny audio glitches instantly whereas eyes tolerate a slightly early or late video frame, the audio hardware buffer serves as the master clock:
audio_pts_ms = start_pts_ms + 1000 * (samples_written - samples_buffered_in_driver) / sample_rate. Before showing each video frame, the render loop computesdelta_ms = frame.pts_ms - audio_pts_ms: ifdelta_ms > 0, the video frame is early so the renderer sleepsmin(delta_ms, period)and re-checks the audio clock; ifdelta_ms < -period, the frame is more than one slot behind the audio so the renderer drops it (incrementing a dropped-frame counter) and checks the next buffered frame; otherwise (-period <= delta_ms <= 0), it renders immediately. Re-reading the hardware audio clock on every frame automatically prevents long-term drift between the sound card's crystal oscillator andtime.monotonic(). - When average decode latency exceeds the frame budget continuously, how can the pipeline shed work or recover instead of falling further behind? If decoding averages 50 ms/frame (20 FPS) while playback demands 25 FPS, a 10-frame buffer drains completely in
10 / (25 - 20) = 2seconds, and merely skippingrender()cannot help because decoding itself is the bottleneck. In compressed video, frames come in GOPs (Groups of Pictures starting with an independent I-frame / keyframe, followed by P-frames that future frames depend on and B-frames / non-reference frames that nothing else depends on): first drop non-reference B-frames before decoding them to save CPU without corrupting later frames, and if latency still exceeds a threshold (e.g., 200 ms behind the clock), flush the decoder and jump straight to the next keyframe. For diagnostic telemetry replay where inspecting every single frame matters more than 1x wall-clock speed, offer an automatic fallback to 0.5x playback speed or lower-resolution proxy streams instead of dropping data. - What architectural changes are required to support arbitrary timestamp seeking and smooth backward playback? Build an in-memory keyframe index mapping
pts_ms -> byte_offset, and add a monotonically increasingseek_generationinteger underself._cond: when the user seeks totarget_ms, incrementseek_generation, flush_buffer, wake both threads, have the decoder jump to the latest keyframe at or beforetarget_ms, decode forward silently discarding frames withpts_ms < target_ms, and tag emitted frames withseek_generationso the renderer drops any leftover pre-seek frame. During fast scrub-bar dragging, decode only keyframes for responsive thumbnail previews and perform the exact forward decode once the user releases the mouse. For smooth reverse playback, because inter-frame codecs only decode forward from keyframes, decode an entire GOP (Gframes, typically 15–30 frames) forward into a slice buffer and pop frames in reverse order (G-1down to0) while prefetching the previous GOP in a second buffer, tradingO(G)frame memory for smooth backward 25 FPS rendering.
Follow-up questions
- How would you synchronize video presentation against a hardware audio output stream acting as the reference clock?
- When average decode latency exceeds the frame budget continuously, how can the pipeline shed work or recover instead of falling further behind?
- What architectural changes are required to support arbitrary timestamp seeking and smooth backward playback?
Similar questions
- Thread-Safe Periodic Task Scheduler
- Object-Oriented K-Way Merger for Timestamped Streams
- Lock-Based Concurrency vs. MVCC for Versioned Key-Value Storage
- Buffered 25 FPS Video Playback Over Non-Thread-Safe Calls
- Concurrent Fixed-Frequency Task Scheduler
- Greedy Robot-to-Item Dispatch Across an Obstacle Grid
More Nuro interview questions
- Greedy Robot-to-Item Dispatch Across an Obstacle Grid Medium
- Object-Oriented K-Way Merger for Timestamped Streams Hard
- Vertical Axis Symmetry for Point Multisets Hard Pro
- Lock-Based Concurrency vs. MVCC for Versioned Key-Value Storage Hard Pro
- Deduplicated Run Duration Across Overlapping Intervals Easy Pro
- Buffered 25 FPS Video Playback Over Non-Thread-Safe Calls Hard Pro
- Multi-Tenant Webhook Delivery and Fleet Telemetry Pipeline Hard Pro
- DAG Workflow Scheduler for Weekly Autonomous Driving Simulations Medium Pro
- Multi-Tenant Distributed GPU Training Cluster Hard Pro
- End-to-End Project Deep Dive: Architecture, Ownership, and Debugging Hard Pro