2022-11-18 21:18:12 +00:00
|
|
|
package ffmpeg
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"context"
|
|
|
|
"os"
|
|
|
|
"os/exec"
|
|
|
|
"strconv"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
type FFmpeg struct {
|
2022-11-19 16:37:49 +00:00
|
|
|
Out *bytes.Buffer
|
|
|
|
Cmd *exec.Cmd
|
|
|
|
Started bool
|
|
|
|
Cancel context.CancelFunc
|
|
|
|
Len time.Duration
|
|
|
|
Title string
|
|
|
|
Channel string
|
|
|
|
err chan error
|
2022-11-18 21:18:12 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func NewFFmpeg(uri string, sampleRate int, channels int) (ff *FFmpeg, err error) {
|
|
|
|
ff = new(FFmpeg)
|
|
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
|
|
ff.Cancel = cancel
|
|
|
|
|
|
|
|
ff.Cmd = exec.CommandContext(
|
|
|
|
ctx,
|
|
|
|
"ffmpeg",
|
2022-11-19 16:37:49 +00:00
|
|
|
"-i", uri,
|
2022-11-18 21:18:12 +00:00
|
|
|
"-f", "s16le",
|
|
|
|
"-v", "error",
|
2022-11-19 16:37:49 +00:00
|
|
|
//"-stats",
|
2022-11-18 21:18:12 +00:00
|
|
|
"-ar", strconv.Itoa(sampleRate),
|
|
|
|
"-ac", strconv.Itoa(channels),
|
|
|
|
"-af", "loudnorm=I=-16:LRA=11:TP=-1.5",
|
|
|
|
"pipe:1",
|
|
|
|
)
|
|
|
|
|
|
|
|
ff.Cmd.Stderr = os.Stdin
|
|
|
|
|
2022-11-20 13:28:03 +00:00
|
|
|
ff.Out = bytes.NewBuffer(make([]byte, 4096))
|
2022-11-18 21:18:12 +00:00
|
|
|
ff.Cmd.Stdout = ff.Out
|
|
|
|
|
2022-11-19 16:37:49 +00:00
|
|
|
return
|
|
|
|
}
|
2022-11-18 21:18:12 +00:00
|
|
|
|
2022-11-19 16:37:49 +00:00
|
|
|
func (ff *FFmpeg) Start() error {
|
|
|
|
err := ff.Cmd.Start()
|
2022-11-20 13:28:03 +00:00
|
|
|
|
|
|
|
// We need to wait till the buffer starts filling up..
|
|
|
|
for ff.Out.Len() == 4096 {
|
|
|
|
}
|
|
|
|
|
|
|
|
ff.Started = true
|
2022-11-18 21:18:12 +00:00
|
|
|
go func() {
|
2022-11-19 16:37:49 +00:00
|
|
|
if err != nil {
|
|
|
|
ff.err <- ff.Cmd.Wait()
|
|
|
|
}
|
2022-11-18 21:18:12 +00:00
|
|
|
}()
|
|
|
|
|
2022-11-19 16:37:49 +00:00
|
|
|
return err
|
2022-11-18 21:18:12 +00:00
|
|
|
}
|
|
|
|
|
2022-11-19 16:37:49 +00:00
|
|
|
func (ff FFmpeg) Close() error {
|
2022-11-18 21:18:12 +00:00
|
|
|
ff.Cancel()
|
|
|
|
return nil
|
|
|
|
}
|