Steady-Cadence Frame Player with Bounded Decode Buffer
Data Structure DesignModel answerLast updated
Build a thread-safe player where a decoder thread fills a bounded buffer and a render thread emits frames at a fixed rate on a monotonic clock, with clean pause, stop and underrun handling.
Steady-Cadence Frame Player
A replay tool for recorded driving-simulation footage must show frames at an exact, constant rate (default 25 FPS, one frame every 40 ms), even though the time needed to decode each frame varies between roughly 5 ms and 80 ms.
Implement a thread-safe VideoPlayer in which a background decoder thread feeds a bounded buffer and a separate render thread pulls frames out of that buffer on a fixed schedule.
Interface
from typing import Optional
class VideoFrame:
pts_ms: int # presentation timestamp in milliseconds
data: bytes
class FrameDecoder:
def read_frame(self) -> Optional[VideoFrame]:
"""Return the next frame, or None at end of stream."""
class DisplaySink:
def render(self, frame: VideoFrame) -> None:
"""Show one frame."""
class VideoPlayer:
def __init__(self, decoder: FrameDecoder, sink: DisplaySink,
target_fps: int = 25, max_buffer_size: int = 10): ...
def play(self) -> None: ... # start or resume
def pause(self) -> None: ... # keep threads and buffered frames
def stop(self) -> None: ... # flush buffer, terminate workers
Requirements
- Cadence. Hand frames to the sink every
1 / target_fpsseconds using a monotonic clock. Variable render time must not cause cumulative drift. - Bounded buffer. Decoded frames wait in a thread-safe buffer holding at most
max_buffer_sizeentries. The decoder must block when it is full. - State control. Support
play,pause,stop. Callingplay()while already playing does nothing. State changes must be free of races. - Underruns. If a frame is due and the buffer is empty, record the underrun (count and/or log it) without spinning the CPU, then continue at the next scheduled slot.
- End of stream and teardown. When the decoder reports end of stream, or when
stop()is called, every worker thread must exit without deadlock.
Constraints
- Per-frame decode time: 5 ms to 80 ms.
- No busy-waiting anywhere.
- Under normal buffer conditions, frame timing should stay within about 2 ms of the ideal schedule.
stop()must complete shutdown within 200 ms.
What to deliver
Describe your design, explain why it is correct (timing, bounding, state transitions, shutdown), state the complexity, list edge cases, and give working code.
Hints
Hint 1
Treat it as a bounded producer/consumer pair, and put the deque, the state, and any flags under a single condition variable so every wait can be woken by any relevant change.
Hint 2
Do not sleep a fixed 40 ms after each render. Compute the deadline of frame n as base + n * period from a fixed anchor, so a slow render only shortens the next wait.
Hint 3
Run read_frame() and render() outside the lock, re-check state after every wake-up, and when resuming from pause re-anchor the clock so paused time is not treated as lateness.
Hint 4
For shutdown, have stop() set the state, clear the buffer, and notify_all; the longest remaining blocker is one in-flight decode (at most 80 ms), which fits within 200 ms. Avoid joining the current thread.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a bounded producer/consumer problem where the consumer is driven by absolute deadlines.
- Decoder thread (producer): waits for free space, decodes one frame outside the lock, then appends it. At end of stream it appends a sentinel and exits.
- Render thread (consumer): frame slot
nis due atbase + n * period. It waits until that deadline, takes a frame if one exists, and renders it outside the lock. - One
threading.Conditionprotects the deque, the state enum, and a "re-anchor" flag. All blocking is done withcond.wait(timeout), so there is no polling and no spinning.
States: IDLE -> PLAYING <-> PAUSED -> STOPPED, plus ENDED after end of stream. Threads are created lazily on the first play().
Why it works
No drift. The deadline for slot n depends only on base and n. If a render takes 6 ms too long, the next wait is 6 ms shorter; nothing shifts permanently. Using time.monotonic() avoids wall-clock adjustments. Timing waits use the condition's timeout, which is a blocking wait, not a spin.
Pause and resume. On resume, set base = now and n = 0. Otherwise the elapsed pause looks like a huge backlog and the player would burst through frames.
Late renders. If a render overruns by more than a period, skip the missed slots (count them) instead of rendering back to back.
Bounded buffer. The producer waits while len(buf) >= cap, and it is the only appender, so the buffer, sentinel included, never exceeds capacity. Pausing with a full buffer simply leaves the producer blocked and the frames intact.
Underruns. If the deadline passes and the buffer is empty, increment underruns, log it, advance to the next slot, and wait on the condition until that deadline. A frame arriving late is shown at the next slot, keeping the grid intact rather than rendering off-beat.
Race-free transitions. play, pause, stop change state only while holding the condition, then notify_all. Both workers use while-loops around waits and re-check state, so spurious wake-ups are harmless. play() while PLAYING, STOPPED or ENDED returns immediately.
Clean teardown. stop() sets STOPPED, clears the buffer, and notifies. Every wait loop exits on STOPPED. The worst case is a decoder inside read_frame() for up to 80 ms; because it runs outside the lock and the state is checked afterward, the thread exits well under 200 ms. stop() joins with a shared deadline and skips the current thread, so calling it from inside render cannot self-deadlock.
Complexity
- Time: O(1) amortized per frame (deque push/pop and state checks).
- Space: O(
max_buffer_size) frames plus two threads.
Code
import logging, threading, time
from collections import deque
from enum import Enum, auto
from typing import Optional
log = logging.getLogger(__name__)
class State(Enum):
IDLE = auto(); PLAYING = auto(); PAUSED = auto()
STOPPED = auto(); ENDED = auto()
_EOS = object()
class VideoPlayer:
def __init__(self, decoder, sink, target_fps=25, max_buffer_size=10):
if target_fps <= 0 or max_buffer_size <= 0:
raise ValueError("target_fps and max_buffer_size must be positive")
self._dec, self._sink = decoder, sink
self._period = 1.0 / target_fps
self._cap = max_buffer_size
self._buf = deque()
self._cond = threading.Condition()
self._state = State.IDLE
self._rebase = True
self._threads = []
self.frames_rendered = self.underruns = self.skipped_slots = 0
def play(self):
with self._cond:
if self._state in (State.PLAYING, State.STOPPED, State.ENDED):
return
first = self._state is State.IDLE
self._state = State.PLAYING
self._rebase = True
if first:
self._threads = [
threading.Thread(target=self._decode_loop, daemon=True),
threading.Thread(target=self._render_loop, daemon=True)]
for t in self._threads:
t.start()
self._cond.notify_all()
def pause(self):
with self._cond:
if self._state is State.PLAYING:
self._state = State.PAUSED
self._cond.notify_all()
def stop(self, timeout=0.2):
with self._cond:
if self._state is not State.STOPPED:
self._state = State.STOPPED
self._buf.clear()
self._cond.notify_all()
end = time.monotonic() + timeout
me = threading.current_thread()
for t in self._threads:
if t is not me:
t.join(max(0.0, end - time.monotonic()))
def _decode_loop(self):
while True:
with self._cond:
while len(self._buf) >= self._cap and self._state is not State.STOPPED:
self._cond.wait()
if self._state is State.STOPPED:
return
try:
frame = self._dec.read_frame()
except Exception:
log.exception("decoder failed; treating as EOS")
frame = None
with self._cond:
if self._state is State.STOPPED:
return
self._buf.append(frame if frame is not None else _EOS)
self._cond.notify_all()
if frame is None:
return
def _render_loop(self):
base, n = 0.0, 0
while True:
with self._cond:
while self._state in (State.IDLE, State.PAUSED):
self._cond.wait()
if self._state in (State.STOPPED, State.ENDED):
return
if self._rebase:
base, n, self._rebase = time.monotonic(), 0, False
due = base + n * self._period
while True:
if self._state is not State.PLAYING or self._rebase:
break
remaining = due - time.monotonic()
if remaining <= 0:
break
self._cond.wait(remaining)
if self._state is State.STOPPED:
return
if self._state is not State.PLAYING or self._rebase:
continue # paused or resumed: re-evaluate
if not self._buf:
self.underruns += 1
log.warning("underrun at slot %d", n)
n += 1
continue
item = self._buf.popleft()
self._cond.notify_all() # free space for producer
if item is _EOS:
self._state = State.ENDED
self._cond.notify_all()
return
try:
self._sink.render(item)
self.frames_rendered += 1
except Exception:
log.exception("render failed")
n += 1
# skip slots missed because of a long render
lag = int((time.monotonic() - base) / self._period) - n
if lag > 0:
self.skipped_slots += lag
n += lag
(Underrun handling loops back to the top, where the next deadline wait is a condition wait, so it costs no CPU.)
Edge cases
play()twice, orplay -> pause -> play: resume re-anchors the clock.pause()beforeplay(): no-op.stop()beforeplay(): no threads to join.stop()twice, after EOS, or from insiderender.- Empty stream: first item is the sentinel, so the player goes straight to
ENDED. - Decoder exception: treated as EOS so the consumer is never left waiting forever. Sink exception: logged, playback continues.
- Invalid
target_fpsormax_buffer_size:ValueError.
Common mistakes
sleep(0.04)after each render, which accumulates drift.- Not re-anchoring after pause, causing a catch-up burst.
- Holding the lock during
read_frame()orrender(), which blockspause/stop. - Using
ifinstead ofwhilearound waits. - Using
time.time()instead of a monotonic clock. - Joining the current thread in
stop(). - Forgetting
notify_allafter popping, leaving the producer asleep on a full buffer.
Trade-offs
A single condition is simple and correct; separate not_full/not_empty conditions reduce spurious wake-ups at the cost of more coordination. Python's GIL and OS scheduling make a strict 2 ms jitter best-effort; for hard guarantees use a real-time scheduler, a higher-resolution timer, or a native implementation.