Spaces:
Paused
Paused
Zhen Ye Claude Opus 4.6 commited on
Commit ·
f09ca9c
1
Parent(s): b1974e2
fix: replace gated GSAM2 streaming with adaptive-rate publisher thread
Browse filesThe old streaming approach (60-frame startup buffer + 20-frame safety
threshold + 3x frame duplication) prevented any frames from reaching
the frontend during processing. Replace with a dedicated publisher
thread that measures production rate during a 5s startup window, then
streams at 85% of measured rate with adaptive adjustments and heartbeat
keepalives. Reduce endpoint startup buffer from 30 to 5 frames.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Files changed (3)
- app.py+1-1
- inference.py+124-54
- jobs/streaming.py+1-9
774 unmodified lines775776777778779780781774 unmodified linestry:# Initial Buffer: Wait until we have enough frames or job is doneif not buffered:if q.qsize() < 30:await asyncio.sleep(0.1)continuebuffered = True774 unmodified lines775776777778779780781774 unmodified linestry:# Initial Buffer: Wait until we have enough frames or job is doneif not buffered:if q.qsize() < 5:await asyncio.sleep(0.1)continuebuffered = True
4 unmodified lines56789101809 unmodified lines18201821182218231824182518261827182818291830183118321833183418359 unmodified lines1845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872112 unmodified lines198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201813 unmodified lines2032203320342035203620372 unmodified lines204020412042204320442045204620472048348 unmodified lines2397239823992400240124024 unmodified lines# del os.environ["CUDA_VISIBLE_DEVICES"]import osimport loggingimport timefrom threading import Event, RLock, Thread1809 unmodified linesexcept Exception as e:logging.error("GSAM2 enrichment thread failed for frame %d: %s", frame_idx, e)def _writer_loop():nonlocal render_donenext_idx = 0buf: Dict[int, Tuple] = {}# Streaming constantsSTARTUP_BUFFER = 60SAFETY_THRESHOLD = 20FRAME_DUP = 3# Per-track bbox history (replaces ByteTracker for GSAM2)track_history: Dict[int, List] = {}speed_est = SpeedEstimator(fps=fps) if enable_gpt else None9 unmodified lineswith StreamingVideoWriter(output_video_path, fps, width, height) as writer:# --- Phase 1: Startup buffering ---playback_started = Falsewhile not playback_started:try:idx, frm, fobjs = render_out.get(timeout=1.0)buf[idx] = (frm, fobjs)except Empty:if not any(t.is_alive() for t in r_workers) and render_out.empty():playback_started = Truebreakcontinueahead = sum(1 for k in buf if k >= next_idx)if ahead >= STARTUP_BUFFER or ahead >= total_frames:playback_started = Truelogging.info("Startup buffer filled (%d frames), beginning playback",len(buf),)# --- Phase 2: Write + stream with safety gating ---while next_idx < total_frames:try:while next_idx not in buf:112 unmodified linesif _perf_metrics is not None:_perf_metrics["writer_total_ms"] += (time.perf_counter() - _t_w) * 1000.0# --- Streaming with buffer gating + frame duplication ---if stream_queue or job_id:# Drain any immediately available frames for accurate buffer levelwhile True:try:idx2, frm2, fobjs2 = render_out.get_nowait()buf[idx2] = (frm2, fobjs2)except Empty:breakbuffer_ahead = sum(1 for k in buf if k > next_idx)if buffer_ahead >= SAFETY_THRESHOLD or next_idx >= total_frames - 1:from jobs.streaming import publish_frame as _pubif job_id:for _ in range(FRAME_DUP):_pub(job_id, frm)else:for _ in range(FRAME_DUP):try:stream_queue.put(frm, timeout=0.01)except Exception:passelse:logging.debug("Stream paused: buffer=%d < threshold=%d at frame %d",buffer_ahead, SAFETY_THRESHOLD, next_idx,)next_idx += 1if next_idx % 30 == 0:13 unmodified linescontinuefinally:render_done = True# Shut down enrichment threadif enrich_thread:try:2 unmodified linesexcept Exception:logging.warning("GSAM2 enrichment thread shutdown timed out")writer_thread = Thread(target=_writer_loop, daemon=True)writer_thread.start()# ==================================================================# Phase 1-4: Tracking (single-GPU fallback vs multi-GPU pipeline)# Segments are fed incrementally to render_in as they complete.348 unmodified linesfor t in r_workers:t.join()writer_thread.join()if _perf_metrics is not None:_perf_metrics["end_to_end_ms"] = (time.perf_counter() - _t_e2e) * 1000.04 unmodified lines5678910111809 unmodified lines18211822182318241825182618271828182918301831183218331834183518369 unmodified lines1846184718481849185018511852112 unmodified lines196519661967196819691970197119721973197413 unmodified lines19881989199019911992199319942 unmodified lines199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116348 unmodified lines246524662467246824692470247124724 unmodified lines# del os.environ["CUDA_VISIBLE_DEVICES"]import osimport collectionsimport loggingimport timefrom threading import Event, RLock, Thread1809 unmodified linesexcept Exception as e:logging.error("GSAM2 enrichment thread failed for frame %d: %s", frame_idx, e)# Shared streaming state (publisher ↔ writer)_stream_deque: collections.deque = collections.deque(maxlen=200)_stream_lock = RLock()_stream_writer_done = Event()def _writer_loop():nonlocal render_donenext_idx = 0buf: Dict[int, Tuple] = {}# Per-track bbox history (replaces ByteTracker for GSAM2)track_history: Dict[int, List] = {}speed_est = SpeedEstimator(fps=fps) if enable_gpt else None9 unmodified lineswith StreamingVideoWriter(output_video_path, fps, width, height) as writer:# --- Write + stream (publisher handles pacing) ---while next_idx < total_frames:try:while next_idx not in buf:112 unmodified linesif _perf_metrics is not None:_perf_metrics["writer_total_ms"] += (time.perf_counter() - _t_w) * 1000.0# --- Deposit frame for stream publisher ---if stream_queue or job_id:with _stream_lock:_stream_deque.append(frm)next_idx += 1if next_idx % 30 == 0:13 unmodified linescontinuefinally:render_done = True_stream_writer_done.set()# Shut down enrichment threadif enrich_thread:try:2 unmodified linesexcept Exception:logging.warning("GSAM2 enrichment thread shutdown timed out")def _stream_publisher_thread():"""Adaptive-rate publisher: reads from _stream_deque, publishes at measured pace."""from jobs.streaming import publish_frame as _pubSTARTUP_WAIT = 5.0 # max seconds to accumulate before streamingMIN_FPS = 2.0MAX_FPS = 30.0HEARTBEAT_INTERVAL = 0.5 # re-publish last frame if deque emptyLOW_WATER = 10HIGH_WATER = 50ADJUST_INTERVAL = 1.0last_frame = Nonepublished = 0# --- Phase 1: startup accumulation ---t_start = time.perf_counter()while True:elapsed = time.perf_counter() - t_startif elapsed >= STARTUP_WAIT:breakif _stream_writer_done.is_set():breaktime.sleep(0.1)with _stream_lock:accumulated = len(_stream_deque)elapsed = max(time.perf_counter() - t_start, 0.1)r_prod = accumulated / elapsed if accumulated > 0 else 10.0r_stream = max(MIN_FPS, min(MAX_FPS, 0.85 * r_prod))logging.info("Stream publisher started: R_prod=%.1f fps, R_stream=%.1f fps, ""accumulated=%d frames in %.1fs",r_prod, r_stream, accumulated, elapsed,)# --- Phase 2: adaptive streaming ---last_adjust = time.perf_counter()last_publish_time = 0.0while True:frame_interval = 1.0 / r_stream# Try to pop a frameframe = Nonewith _stream_lock:if _stream_deque:frame = _stream_deque.popleft()if frame is not None:last_frame = frameif job_id:_pub(job_id, frame)elif stream_queue:try:stream_queue.put(frame, timeout=0.01)except Exception:passpublished += 1last_publish_time = time.perf_counter()time.sleep(frame_interval)else:# Deque empty — check terminationif _stream_writer_done.is_set():with _stream_lock:if not _stream_deque:breakcontinue# Heartbeat: re-publish last frame to keep MJPEG alivenow = time.perf_counter()if last_frame is not None and (now - last_publish_time) >= HEARTBEAT_INTERVAL:if job_id:_pub(job_id, last_frame)elif stream_queue:try:stream_queue.put(last_frame, timeout=0.01)except Exception:passlast_publish_time = nowtime.sleep(0.05)# Adaptive rate adjustment (every ~1s)now = time.perf_counter()if now - last_adjust >= ADJUST_INTERVAL:with _stream_lock:level = len(_stream_deque)if level < LOW_WATER:r_stream = max(MIN_FPS, r_stream * 0.9)elif level > HIGH_WATER:r_stream = min(MAX_FPS, r_stream * 1.05)last_adjust = now# Publish final frameif last_frame is not None:if job_id:_pub(job_id, last_frame)elif stream_queue:try:stream_queue.put(last_frame, timeout=0.01)except Exception:passlogging.info("Stream publisher finished: published %d frames", published)writer_thread = Thread(target=_writer_loop, daemon=True)writer_thread.start()_publisher_thread = Noneif stream_queue or job_id:_publisher_thread = Thread(target=_stream_publisher_thread, daemon=True)_publisher_thread.start()# ==================================================================# Phase 1-4: Tracking (single-GPU fallback vs multi-GPU pipeline)# Segments are fed incrementally to render_in as they complete.348 unmodified linesfor t in r_workers:t.join()writer_thread.join()if _publisher_thread is not None:_publisher_thread.join(timeout=15)if _perf_metrics is not None:_perf_metrics["end_to_end_ms"] = (time.perf_counter() - _t_e2e) * 1000.0
26 unmodified lines2728293031323356 unmodified lines9091929394959697989910026 unmodified linesdef create_stream(job_id: str) -> queue.Queue:"""Create a new stream queue for a job. Returns the queue for backward compat."""with _LOCK:q = queue.Queue(maxsize=60)# Create event — will be lazily bound to the correct event loopevent = None # Lazily created in get_stream_event_STREAMS[job_id] = (q, event)56 unmodified lines# Wake the async consumer if waitingif event is not None:event.set()def publish_frame_to_queue(q: queue.Queue, frame: Any) -> None:"""Publish to a specific queue object. Non-blocking drop."""try:q.put_nowait(frame)except queue.Full:pass26 unmodified lines2728293031323356 unmodified lines90919226 unmodified linesdef create_stream(job_id: str) -> queue.Queue:"""Create a new stream queue for a job. Returns the queue for backward compat."""with _LOCK:q = queue.Queue(maxsize=120)# Create event — will be lazily bound to the correct event loopevent = None # Lazily created in get_stream_event_STREAMS[job_id] = (q, event)56 unmodified lines# Wake the async consumer if waitingif event is not None:event.set()
app.py+1-1
inference.py+124-54
jobs/streaming.py+1-9