promodj/streamer.go

65 lines
1.1 KiB
Go
Raw Normal View History

2021-08-14 09:59:41 +05:00
package main
import (
"errors"
"fmt"
"io"
2022-02-01 10:02:21 +05:00
"log"
2021-08-14 09:59:41 +05:00
"net/http"
"os/exec"
2021-09-18 14:46:07 +05:00
"github.com/djherbis/nio/v3"
2022-02-01 10:02:21 +05:00
"gopkg.in/djherbis/buffer.v1"
2021-08-14 09:59:41 +05:00
)
2023-06-18 14:54:35 +05:00
func stream(url string, w http.ResponseWriter, bitrateKbps uint64) error {
2021-08-14 09:59:41 +05:00
if url == "" {
err := errors.New("empty url")
http.Error(w, err.Error(), http.StatusBadRequest)
return err
}
w.Header().Set("Content-Type", config.ContentType)
w.Header().Set("Accept-Ranges", "none")
w.WriteHeader(http.StatusOK)
2023-06-18 14:54:35 +05:00
return encode(url, w, bitrateKbps)
2021-08-14 09:59:41 +05:00
}
2023-06-18 14:54:35 +05:00
func encode(url string, w io.Writer, bitrateKbps uint64) error {
2021-08-14 09:59:41 +05:00
cmd := exec.Command("ffmpeg",
"-i", url,
"-vn",
"-c:a", config.Codec,
2023-06-18 15:17:20 +05:00
"-b:a", fmt.Sprintf("%dk", bitrateKbps),
2021-08-14 09:59:41 +05:00
"-f", config.Format,
"-ac", "2",
"pipe:1")
out, err := cmd.StdoutPipe()
if err != nil {
return err
}
2022-02-01 10:01:56 +05:00
defer out.Close()
2021-08-14 09:59:41 +05:00
err = cmd.Start()
if err != nil {
return err
}
go func() {
2022-02-01 10:02:21 +05:00
err := cmd.Wait()
if err != nil {
log.Println(err)
}
2021-08-14 09:59:41 +05:00
}()
buf := buffer.New(int64(config.BufferSize) * 1024 * 1024)
_, err = nio.Copy(w, out, buf)
if err != nil {
2022-11-27 14:33:56 +05:00
_ = cmd.Process.Kill()
2021-08-14 09:59:41 +05:00
}
return nil
}