diff --git a/api/stream.go b/api/stream.go index 52754edbc..46f120803 100644 --- a/api/stream.go +++ b/api/stream.go @@ -46,9 +46,11 @@ func (c *StreamController) Stream() { beego.Debug("Streaming file", c.id, ":", c.mf.Path) beego.Debug("Bitrate", c.mf.BitRate, "MaxBitRate", maxBitRate) + contentLength := c.mf.Size if maxBitRate > 0 { - c.Ctx.Output.Header("Content-Length", strconv.Itoa((c.mf.Duration+1)*maxBitRate*1000/8)) + contentLength = strconv.Itoa((c.mf.Duration + 1) * maxBitRate * 1000 / 8) } + c.Ctx.Output.Header("Content-Length", contentLength) c.Ctx.Output.Header("Content-Type", "audio/mpeg") c.Ctx.Output.Header("Expires", "0") c.Ctx.Output.Header("Cache-Control", "must-revalidate") diff --git a/stream/downsampling.go b/stream/downsampling.go index 5eadd0e34..a4f1cbeb7 100644 --- a/stream/downsampling.go +++ b/stream/downsampling.go @@ -9,33 +9,36 @@ import ( "strings" ) +// 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 { - cmdLine, args := createDownsamplingCommand(path, maxBitRate) - - beego.Debug("Executing cmd:", cmdLine, args) - cmd := exec.Command(cmdLine, args...) - cmd.Stderr = os.Stderr - stdout, err := cmd.StdoutPipe() - if err != nil { - beego.Error("Error executing", cmdLine, ":", err) - return err - } - if err = cmd.Start(); err != nil { - beego.Error("Error executing", cmdLine, ":", err) - } else { - _, err = io.Copy(w, stdout) - } - return err + f, err = downsample(path, maxBitRate) } else { - f, err := os.Open(path) - if err != nil { - beego.Error("Error opening file", path, ":", err) - return err - } - _, err = io.Copy(w, f) + 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) {