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:

  1. Drift-free monotonic scheduling: Deliver one frame every 1.0 / target_fps seconds (40 ms at 25 FPS) anchored to a monotonic clock so nonzero render() durations or OS wake-up jitter never accumulate across successive frames.
  2. Bounded producer-consumer buffer: Store decoded frames in a thread-safe FIFO buffer capped at max_buffer_size items. Whenever the buffer is full, the decoder thread must sleep until space opens or playback stops.
  3. Race-free lifecycle controls:
    • Begin in "idle" with frames_rendered = 0 and underruns = 0.
    • play() starts worker threads from "idle" or resumes rendering from "paused", transitioning state to "playing". Calling play() 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 to timeout seconds in total for worker threads to finish and returns True if none remain alive.
  4. 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.
  5. End-of-stream (None) completion: When decoder.read_frame() returns None, every already-decoded frame ahead of it must still be rendered on schedule, after which state transitions 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 > 0 and max_buffer_size > 0 (raise ValueError otherwise).
  • decoder.read_frame() latency can vary between 0 ms and 80+ ms per frame; never hold an internal state lock across read_frame() or sink.render(frame).
  • Busy-waiting (while ...: pass) is prohibited; blocked threads must consume near-zero CPU.
  • stop() must finish tearing down worker threads within 200 ms, whether called during normal playback, while paused, while the buffer is full, or during a slow 80 ms decode.

Step-by-step walkthrough

  1. 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 returns None at End-of-Stream (EOS) (when no frames remain). - sink.render(frame) must be called on a steady heartbeat of period = 1.0 / target_fps seconds (40 ms at 25 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 when stop() 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 to max_buffer_size so 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)  -
    
  2. Why single-threaded loops and relative sleeps fail

    Two beginner designs look tempting at first glance, and both break down immediately:

    1. 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 to max_buffer_size frames (10 * 40 ms = 400 ms of reserve at 25 FPS) that keeps the screen smooth through temporary 80 ms stalls.
    2. 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 to 8 + 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 * period on time.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.

  3. Coordinate two threads safely with one Condition

    All shared state — self._buffer (a collections.deque), self._state, self._threads, and the counters — is guarded by a single threading.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 _buffer or _state calls self._cond.notify_all(), and each thread checks its own wait condition inside a while loop: - Decoder waits while: _state != "stopped" and len(_buffer) >= _capacity. - Renderer waits while: _state == "paused", or waiting for the initial frame (not _buffer), or waiting for time.monotonic() to reach deadline via self._cond.wait(remaining).

    Three rules guarantee zero deadlocks and sub-200 ms shutdown: 1. Never hold self._cond while calling read_frame() or render(). Those calls can take 80 ms, so holding the lock would stall pause() and stop(), and would deadlock if a callback inside render() called player.stop(). 2. Always re-check conditions with while, never if. Because notify_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 _EOS behind the last VideoFrame guarantees the renderer displays every buffered frame before transitioning to "stopped".

  4. Implement state controls: play, pause, stop, and join

    Each public control method acquires self._cond, checks whether the state transition is valid, updates self._state, and broadcasts notify_all(). Notice two subtle safety details in stop() and join(): - stop() sets STOPPED, clears _buffer, and calls notify_all() inside with self._cond:, then calls self.join() outside with self._cond: so waking worker threads can acquire the lock to observe STOPPED and exit. - join(timeout) tracks a single overall end_time across both threads and skips threading.current_thread() (preventing RuntimeError: cannot join current thread if a DisplaySink calls player.stop() from inside render()).

    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
    
  5. Implement the producer: reserving a slot before decoding

    The decoder loop enforces max_buffer_size without holding the lock during read_frame(). First, it acquires self._cond and waits until len(self._buffer) < self._capacity. Because this single decoder thread is the only thread that ever appends to self._buffer, that free slot is guaranteed to still be free when read_frame() finishes 5–80 ms later!

    When read_frame() returns, the decoder re-acquires self._cond and checks self._state == STOPPED a second time. If stop() ran while read_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:
                    return
    
  6. Implement the consumer: drift-free deadlines, underruns, and overruns

    The render thread tracks deadline — the target time.monotonic() timestamp when the next frame should appear: 1. Paused (PAUSED): clear deadline = None and sleep in wait() until play() or stop(). 2. Start / resume (deadline is None): wait until _buffer has at least one item, then set deadline = 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): compute remaining = deadline - time.monotonic() and sleep with self._cond.wait(remaining). If pause() or stop() wakes us early, _sleep_until returns False immediately. 4. Buffer underrun (not self._buffer): increment self.underruns and step deadline += self._period onto 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
    
    1. End-of-stream (_EOS): set _state = STOPPED, clear _buffer, notify, and return.
    2. Render and advance (_next_deadline): pop the frame, call notify_all() to free a slot for the decoder, call sink.render(frame) outside the lock, and move deadline += self._period. If a slow render() overran by one or more whole periods (for example, deadline was 1000 ms, render() finished at 1105 ms, so 1040 ms is 65 ms in the past), _next_deadline skips int(65 / 40) = 1 whole missed slot to 1080 ms so 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
    
  7. 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() and sink.render() calls, each frame performs one deque.append, one deque.popleft, a constant number of lock acquisitions, and wake-ups of at most two worker threads, all taking constant time regardless of stream length or max_buffer_size.
  • Space — O(max_buffer_size) memory: The deque holds at most max_buffer_size items because the single decoder thread waits for len(_buffer) < max_buffer_size before reading a frame, so at most max_buffer_size buffered frames plus the 1 frame currently inside sink.render() exist in memory at once.
  • Worker threads — O(1) threads: Exactly two background daemon threads (decoder and renderer) are created on the first transition out of "idle" and reused across any number of pause() / play() cycles.
  • Shutdown latency — bounded by one in-flight I/O call: Because stop() clears the buffer and calls notify_all(), every Condition.wait wakes immediately, so stop() waits at most for a single already-running read_frame() (up to 80 ms) or render() call to return — comfortably within the 200 ms requirement.

Edge cases

  • Empty video stream (read_frame() returns None immediately): Decoder pushes _EOS into slot 0; renderer wakes, sees _EOS at the front of _buffer, sets state to "stopped", and exits with frames_rendered == 0 and underruns == 0.
  • Idempotent and out-of-order control calls: Calling play() three times in a row spawns only one decoder/renderer pair; calling pause() while "idle" or "paused", stop() before play(), stop() twice, or play() after stop() are all safe no-ops.
  • stop() while buffer is full or player is paused: Both threads are parked inside self._cond.wait(), so notify_all() wakes them immediately and they exit in under a millisecond.
  • stop() during a slow 80 ms read_frame(): When read_frame() finally returns, _decode_loop re-checks self._state == STOPPED under the lock and discards the late frame instead of putting it into the flushed buffer.
  • stop() invoked from inside a sink.render() callback: join() compares each worker against threading.current_thread() and skips joining itself, avoiding a RuntimeError self-join deadlock.
  • max_buffer_size = 1: Works without deadlock — as soon as the renderer pops the single buffered frame (before calling render()), it calls notify_all() so the decoder can start decoding the next frame in parallel with render().
  • Slow render() overrunning a whole period: _next_deadline skips 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) after render(): 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() or render(): Blocks pause() and stop() for up to 80 ms and deadlocks if user sink/decoder code calls back into player.state or player.stop().
  • Blocking on queue.Queue.put() without a wake-up path on stop(): If the buffer is full and the renderer exits first on stop(), a decoder blocked in an untimed queue.put() never wakes up and join() hangs forever.
  • Checking conditions with if instead of while around Condition.wait(): A thread woken by notify_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 of time.monotonic(): System wall-clock adjustments (NTP syncs, daylight-saving or manual clock edits) can jump time.time() backward by seconds and freeze playback inside wait(remaining).

Alternative approaches

  • queue.Queue(maxsize) + threading.Event with short polling timeouts: You can pair Python's built-in queue.Queue with a stop_event and loop over put(..., 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): Setting deadline = base_time + (frame.pts_ms - first_pts_ms) / 1000.0 naturally 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.wait still 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 computes delta_ms = frame.pts_ms - audio_pts_ms: if delta_ms > 0, the video frame is early so the renderer sleeps min(delta_ms, period) and re-checks the audio clock; if delta_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 and time.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) = 2 seconds, and merely skipping render() 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 increasing seek_generation integer under self._cond: when the user seeks to target_ms, increment seek_generation, flush _buffer, wake both threads, have the decoder jump to the latest keyframe at or before target_ms, decode forward silently discarding frames with pts_ms < target_ms, and tag emitted frames with seek_generation so 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 (G frames, typically 15–30 frames) forward into a slice buffer and pop frames in reverse order (G-1 down to 0) while prefetching the previous GOP in a second buffer, trading O(G) frame memory for smooth backward 25 FPS rendering.

Follow-up questions

Similar questions

More Nuro interview questions

All 29 Nuro questions →