KatInterview

Steady-Cadence Frame Player with Bounded Decode Buffer

Data Structure DesignModel answer
HardModel answerData Structure Designconcurrencyproducer-consumerthreading

Last 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

  1. Cadence. Hand frames to the sink every 1 / target_fps seconds using a monotonic clock. Variable render time must not cause cumulative drift.
  2. Bounded buffer. Decoded frames wait in a thread-safe buffer holding at most max_buffer_size entries. The decoder must block when it is full.
  3. State control. Support play, pause, stop. Calling play() while already playing does nothing. State changes must be free of races.
  4. 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.
  5. 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.