From cd6a64ba9754b12de9125b16c23cedfae86fd8d1 Mon Sep 17 00:00:00 2001 From: Issam Boubcher <99417396+Issaminu@users.noreply.github.com> Date: Mon, 17 Nov 2025 18:12:48 +0100 Subject: [PATCH] Fix FrameBuffer empty segments caused by wrap-around handling --- frame_buffer.go | 37 +++++++++++++++++++++++++++++++++---- 1 file changed, 33 insertions(+), 4 deletions(-) diff --git a/frame_buffer.go b/frame_buffer.go index 9466af8..e42734d 100644 --- a/frame_buffer.go +++ b/frame_buffer.go @@ -28,9 +28,18 @@ func (fb *FrameBuffer) AddFramesToBuffer(startFrame uint32, endFrame uint32, dat } batchStartIndex := (startFrame * FrameSize) % BufferSize - batchEndIndex := (endFrame*FrameSize + FrameSize) % BufferSize // `+FrameSize` because `endFrame*FrameSize` defines where the last frame starts. But what we actually meed os where it ends. i.e. the position of the last byte of the frameBatch + batchEndIndex := (endFrame*FrameSize + FrameSize) % BufferSize // `+FrameSize` because `endFrame*FrameSize` defines where the last frame starts. But what we actually need is where it ends. i.e. the position of the last byte of the frameBatch + + // Fix: Handle wrap-around case for batch size validation + var batchActualSize uint32 + if batchEndIndex >= batchStartIndex { + batchActualSize = batchEndIndex - batchStartIndex + } else { + // Wrapped around: from start to end of buffer + from start of buffer to end index + batchActualSize = (BufferSize - batchStartIndex) + batchEndIndex + } - if batchEndIndex-batchStartIndex != BatchSize { + if batchActualSize != BatchSize { return errors.New("received incorrect batch size") } @@ -42,7 +51,16 @@ func (fb *FrameBuffer) AddFramesToBuffer(startFrame uint32, endFrame uint32, dat return errors.New("framebuffer length is 0") } - copy(fb.buffer[batchStartIndex:batchEndIndex], data[:]) + // Fix: Handle wrap-around case for copying data + if batchEndIndex >= batchStartIndex { + // Normal case: no wrap-around + copy(fb.buffer[batchStartIndex:batchEndIndex], data[:]) + } else { + // Wrap-around case: copy in two parts + firstPartSize := BufferSize - batchStartIndex + copy(fb.buffer[batchStartIndex:], data[:firstPartSize]) + copy(fb.buffer[:batchEndIndex], data[firstPartSize:]) + } fb.head = max(fb.head, batchEndIndex) log.Println("startFramePosition", batchStartIndex) @@ -57,10 +75,21 @@ func (fb *FrameBuffer) GetFrames() []byte { if length == 0 { return nil } + + // Fix: Handle wrap-around case properly if fb.head >= fb.tail { + // Normal case: no wrap-around return fb.buffer[fb.tail%BufferSize : fb.head%BufferSize] + } else { + // Wrap-around case: concatenate two parts + // From tail to end of buffer + from start of buffer to head + part1 := fb.buffer[fb.tail:] + part2 := fb.buffer[:fb.head] + result := make([]byte, len(part1)+len(part2)) + copy(result, part1) + copy(result[len(part1):], part2) + return result } - return fb.buffer[fb.head%BufferSize : fb.tail%BufferSize] } func (fb *FrameBuffer) RemoveSentFramesFromBuffer() {