From 10e5400fd5419480bf904ec26232deca59fa0f30 Mon Sep 17 00:00:00 2001 From: Stein Ivar Berghei Date: Sun, 20 Nov 2022 14:28:03 +0100 Subject: [PATCH] Fix the edgecase where the buffer would empty before ffmpeg was outputting data.. --- ffmpeg/ffmpeg.go | 12 +++++++----- ffmpeg/pcm.go | 8 ++++++++ queue.go | 4 +--- 3 files changed, 16 insertions(+), 8 deletions(-) diff --git a/ffmpeg/ffmpeg.go b/ffmpeg/ffmpeg.go index c5d96f8..78136d1 100644 --- a/ffmpeg/ffmpeg.go +++ b/ffmpeg/ffmpeg.go @@ -18,7 +18,6 @@ type FFmpeg struct { Title string Channel string err chan error - fb chan bool } func NewFFmpeg(uri string, sampleRate int, channels int) (ff *FFmpeg, err error) { @@ -41,17 +40,20 @@ func NewFFmpeg(uri string, sampleRate int, channels int) (ff *FFmpeg, err error) ff.Cmd.Stderr = os.Stdin - // FFmpeg requires a certain buffer size to start writing. This seems to be enough? - // This will grow big enough to fit the whole song. - ff.Out = bytes.NewBuffer(make([]byte, 128*1024)) + ff.Out = bytes.NewBuffer(make([]byte, 4096)) ff.Cmd.Stdout = ff.Out return } func (ff *FFmpeg) Start() error { - ff.Started = true err := ff.Cmd.Start() + + // We need to wait till the buffer starts filling up.. + for ff.Out.Len() == 4096 { + } + + ff.Started = true go func() { if err != nil { ff.err <- ff.Cmd.Wait() diff --git a/ffmpeg/pcm.go b/ffmpeg/pcm.go index bd32d0f..c98faaf 100644 --- a/ffmpeg/pcm.go +++ b/ffmpeg/pcm.go @@ -49,9 +49,17 @@ func NewPCM(uri string, sampleRate int, channels int) (*PCM, error) { } func (d *PCM) Stream(samples [][2]float64) (n int, ok bool) { + if !d.Player.Started { + d.Player.Start() + } tmp := make([]byte, d.c+2) for i := range samples { + if !d.Player.Started { + samples[i] = [2]float64{} + ok = true + break + } dn, err := d.Player.Out.Read(tmp) if dn == len(tmp) { samples[i], _ = d.f.DecodeSigned(tmp) diff --git a/queue.go b/queue.go index cb7c6a1..1f91d6b 100644 --- a/queue.go +++ b/queue.go @@ -132,9 +132,6 @@ func (q *Queue) Preload() { } func (q *Queue) Stream(samples [][2]float64) (n int, ok bool) { - if q.current != nil && !q.current.Value.(*Song).PCM.Player.Started { - q.current.Value.(*Song).PCM.Player.Start() - } // We use the filled variable to track how many samples we've // successfully filled already. We loop until all samples are filled. filled := 0 @@ -160,6 +157,7 @@ func (q *Queue) Stream(samples [][2]float64) (n int, ok bool) { // We update the number of filled samples. filled += n } + return len(samples), true }