Skip to content

Commit

Permalink
⚡ Pre-allocate stream buffer with 3MB cap
Browse files Browse the repository at this point in the history
  • Loading branch information
gabe565 committed Jul 23, 2023
1 parent e4496f6 commit bb005de
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 3 deletions.
4 changes: 2 additions & 2 deletions internal/handlers/mix.go
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ func Mix(app core.App) echo.HandlerFunc {
}

// Get current filetype encoder
entry.Encoder, err = fileType.NewEncoder(&entry.Buffer, entry.Format)
entry.Encoder, err = fileType.NewEncoder(entry.Buffer, entry.Format)
if err != nil {
panic(err)
}
Expand Down Expand Up @@ -168,7 +168,7 @@ func Mix(app core.App) echo.HandlerFunc {

// Write buffered stream data to client
c.Response().WriteHeader(http.StatusPartialContent)
if _, err := io.Copy(c.Response(), &entry.Buffer); err != nil {
if _, err := io.Copy(c.Response(), entry.Buffer); err != nil {
if !errors.Is(err, syscall.EPIPE) && !errors.Is(err, syscall.ECONNRESET) {
panic(err)
}
Expand Down
7 changes: 6 additions & 1 deletion internal/stream/stream_cache/entry.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ type Entry struct {
Mix beep.Streamer
Format beep.Format

Buffer bytes.Buffer
Buffer *bytes.Buffer
Encoder encoder.Encoder

Mu sync.Mutex
Expand All @@ -47,6 +47,7 @@ func NewEntry(remoteAddr, preset string) *Entry {
entry := &Entry{
RemoteAddr: remoteAddr,
Preset: preset,
Buffer: bytes.NewBuffer(make([]byte, 0, 3*1024*1024)),
Created: time.Now(),
}
entry.Accessed = entry.Created
Expand All @@ -63,6 +64,10 @@ func (e *Entry) Close() error {

activeStreamMetrics.Dec()

defer func() {
e.Buffer = nil
}()

return errors.Join(
e.Streams.Close(),
e.Encoder.Close(),
Expand Down

0 comments on commit bb005de

Please sign in to comment.