From 10ea165c2cde2a7009f7a75ae62425f655c13bfa Mon Sep 17 00:00:00 2001 From: cmcpherson274 Date: Sun, 15 Mar 2026 14:04:59 -0400 Subject: [PATCH] Refactor packet handling with locking mechanism --- apps/proxy/ts_proxy/stream_buffer.py | 39 ++++++++++++++-------------- 1 file changed, 20 insertions(+), 19 deletions(-) diff --git a/apps/proxy/ts_proxy/stream_buffer.py b/apps/proxy/ts_proxy/stream_buffer.py index 42ceb2b7..b61e7794 100644 --- a/apps/proxy/ts_proxy/stream_buffer.py +++ b/apps/proxy/ts_proxy/stream_buffer.py @@ -76,27 +76,28 @@ class StreamBuffer: if not hasattr(self, '_partial_packet'): self._partial_packet = bytearray() - # Combine with any previous partial packet - combined_data = bytearray(self._partial_packet) + bytearray(chunk) - - # Calculate complete packets - complete_packets_size = (len(combined_data) // self.TS_PACKET_SIZE) * self.TS_PACKET_SIZE - - if complete_packets_size == 0: - # Not enough data for a complete packet - self._partial_packet = combined_data - return True - - # Split into complete packets and remainder - complete_packets = combined_data[:complete_packets_size] - self._partial_packet = combined_data[complete_packets_size:] - - # Add completed packets to write buffer - self._write_buffer.extend(complete_packets) - - # Only write to Redis when we have enough data for an optimized chunk + # Lock the full operation to prevent race with reset_buffer_position writes_done = 0 with self.lock: + # Combine with any previous partial packet + combined_data = bytearray(self._partial_packet) + bytearray(chunk) + + # Calculate complete packets + complete_packets_size = (len(combined_data) // self.TS_PACKET_SIZE) * self.TS_PACKET_SIZE + + if complete_packets_size == 0: + # Not enough data for a complete packet + self._partial_packet = combined_data + return True + + # Split into complete packets and remainder + complete_packets = combined_data[:complete_packets_size] + self._partial_packet = combined_data[complete_packets_size:] + + # Add completed packets to write buffer + self._write_buffer.extend(complete_packets) + + # Only write to Redis when we have enough data for an optimized chunk while len(self._write_buffer) >= self.target_chunk_size: # Extract a full chunk chunk_data = self._write_buffer[:self.target_chunk_size]