Moved Stream logic to engine layer
This commit is contained in:
@@ -0,0 +1,56 @@
|
||||
package engine
|
||||
|
||||
import (
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/astaxie/beego"
|
||||
)
|
||||
|
||||
// TODO Encapsulate as a io.Reader
|
||||
func Stream(path string, bitRate int, maxBitRate int, w io.Writer) error {
|
||||
var f io.Reader
|
||||
var err error
|
||||
if maxBitRate > 0 && bitRate > maxBitRate {
|
||||
f, err = downsample(path, maxBitRate)
|
||||
} else {
|
||||
f, err = os.Open(path)
|
||||
}
|
||||
if err != nil {
|
||||
beego.Error("Error opening file", path, ":", err)
|
||||
return err
|
||||
}
|
||||
if _, err = io.Copy(w, f); err != nil {
|
||||
beego.Error("Error copying file", path, ":", err)
|
||||
return err
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func downsample(path string, maxBitRate int) (f io.Reader, err error) {
|
||||
cmdLine, args := createDownsamplingCommand(path, maxBitRate)
|
||||
|
||||
beego.Debug("Executing cmd:", cmdLine, args)
|
||||
cmd := exec.Command(cmdLine, args...)
|
||||
cmd.Stderr = os.Stderr
|
||||
if f, err = cmd.StdoutPipe(); err != nil {
|
||||
return f, err
|
||||
}
|
||||
return f, cmd.Start()
|
||||
}
|
||||
|
||||
func createDownsamplingCommand(path string, maxBitRate int) (string, []string) {
|
||||
cmd := beego.AppConfig.String("downsampleCommand")
|
||||
|
||||
split := strings.Split(cmd, " ")
|
||||
for i, s := range split {
|
||||
s = strings.Replace(s, "%s", path, -1)
|
||||
s = strings.Replace(s, "%b", strconv.Itoa(maxBitRate), -1)
|
||||
split[i] = s
|
||||
}
|
||||
|
||||
return split[0], split[1:len(split)]
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package engine
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
. "github.com/deluan/gosonic/tests"
|
||||
. "github.com/smartystreets/goconvey/convey"
|
||||
)
|
||||
|
||||
func TestDownsampling(t *testing.T) {
|
||||
|
||||
Init(t, false)
|
||||
|
||||
Convey("Subject: createDownsamplingCommand", t, func() {
|
||||
|
||||
Convey("It should create a valid command line", func() {
|
||||
cmd, args := createDownsamplingCommand("/music library/file.mp3", 128)
|
||||
|
||||
So(cmd, ShouldEqual, "ffmpeg")
|
||||
So(args[0], ShouldEqual, "-i")
|
||||
So(args[1], ShouldEqual, "/music library/file.mp3")
|
||||
So(args[2], ShouldEqual, "-b:a")
|
||||
So(args[3], ShouldEqual, "128k")
|
||||
So(args[4], ShouldEqual, "mp3")
|
||||
So(args[5], ShouldEqual, "-")
|
||||
})
|
||||
|
||||
})
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user