live-streamer/streamer/streamer.go

237 lines
5.3 KiB
Go
Raw Normal View History

2024-10-22 16:39:10 -04:00
package streamer
import (
"bufio"
2024-10-23 03:40:10 -04:00
"context"
2024-10-22 16:39:10 -04:00
"fmt"
"io"
"live-streamer/config"
"log"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
)
type Streamer struct {
2024-10-23 03:40:10 -04:00
videoList []config.InputItem
2024-10-22 16:39:10 -04:00
currentVideoIndex int
cmd *exec.Cmd
logFile *os.File
2024-10-23 03:40:10 -04:00
ctx context.Context
cancel context.CancelFunc
2024-10-22 16:39:10 -04:00
}
2024-10-23 03:40:10 -04:00
func NewStreamer(videoList []config.InputItem) *Streamer {
2024-10-22 16:39:10 -04:00
logDir := "logs"
if err := os.MkdirAll(logDir, 0755); err != nil {
log.Printf("Error creating log directory: %v\n", err)
}
logPath := filepath.Join(logDir, fmt.Sprintf("ffmpeg_%s.log", time.Now().Format("2006-01-02_15-04-05")))
logFile, err := os.OpenFile(logPath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
log.Fatalf("Error opening log file: %v\n", err)
}
return &Streamer{
2024-10-23 03:40:10 -04:00
videoList: videoList,
2024-10-22 16:39:10 -04:00
currentVideoIndex: 0,
cmd: nil,
logFile: logFile,
2024-10-23 03:40:10 -04:00
ctx: nil,
2024-10-22 16:39:10 -04:00
}
}
func (s *Streamer) Add(videoPath string) {
2024-10-23 03:40:10 -04:00
s.videoList = append(s.videoList, config.InputItem{Path: videoPath})
2024-10-22 16:39:10 -04:00
}
func (s *Streamer) Remove(videoPath string) {
2024-10-23 03:40:10 -04:00
for i, item := range s.videoList {
2024-10-22 16:39:10 -04:00
if item.Path == videoPath {
2024-10-23 03:40:10 -04:00
s.videoList = append(s.videoList[:i], s.videoList[i+1:]...)
if s.currentVideoIndex >= len(s.videoList) {
2024-10-22 16:39:10 -04:00
s.currentVideoIndex = 0
}
if s.currentVideoIndex == i {
s.start()
}
break
}
}
}
func (s *Streamer) Prev() {
s.currentVideoIndex--
if s.currentVideoIndex < 0 {
2024-10-23 03:40:10 -04:00
s.currentVideoIndex = len(s.videoList) - 1
2024-10-22 16:39:10 -04:00
}
s.start()
}
func (s *Streamer) Next() {
s.currentVideoIndex++
2024-10-23 03:40:10 -04:00
if s.currentVideoIndex >= len(s.videoList) {
2024-10-22 16:39:10 -04:00
s.currentVideoIndex = 0
}
s.start()
}
func (s *Streamer) Stream() {
for {
2024-10-23 03:40:10 -04:00
if len(s.videoList) == 0 {
2024-10-22 16:39:10 -04:00
time.Sleep(time.Second)
continue
}
2024-10-23 03:40:10 -04:00
if s.currentVideoIndex >= len(s.videoList) {
2024-10-22 16:39:10 -04:00
s.currentVideoIndex = 0
}
s.start()
}
}
func (s *Streamer) buildFFmpegArgs(videoItem config.InputItem) []string {
videoPath := videoItem.Path
args := []string{"-re"}
if videoItem.Start != "" {
args = append(args, "-ss", videoItem.Start)
}
args = append(args, "-i", videoPath)
if videoItem.End != "" {
args = append(args, "-to", videoItem.End)
}
args = append(args,
"-c:v", config.GlobalConfig.Play.VideoCodec,
"-preset", config.GlobalConfig.Play.Preset,
"-crf", fmt.Sprintf("%d", config.GlobalConfig.Play.CRF),
"-maxrate", config.GlobalConfig.Play.MaxRate,
"-bufsize", config.GlobalConfig.Play.BufSize,
"-vf", fmt.Sprintf("scale=%s", config.GlobalConfig.Play.Scale),
"-r", fmt.Sprintf("%d", config.GlobalConfig.Play.FrameRate),
"-c:a", config.GlobalConfig.Play.AudioCodec,
"-b:a", config.GlobalConfig.Play.AudioBitrate,
"-ar", fmt.Sprintf("%d", config.GlobalConfig.Play.AudioSampleRate),
"-f", config.GlobalConfig.Play.OutputFormat,
"-stats", "-loglevel", "info",
)
if config.GlobalConfig.Play.CustomArgs != "" {
customArgs := strings.Fields(config.GlobalConfig.Play.CustomArgs)
args = append(args, customArgs...)
}
args = append(args, fmt.Sprintf("%s/%s", config.GlobalConfig.Output.RTMPServer, config.GlobalConfig.Output.StreamKey))
// log.Println("ffmpeg args: ", args)
return args
}
func (s *Streamer) start() {
2024-10-23 03:40:10 -04:00
s.Stop()
2024-10-22 16:39:10 -04:00
2024-10-23 03:40:10 -04:00
s.ctx, s.cancel = context.WithCancel(context.Background())
currentVideo := s.videoList[s.currentVideoIndex]
2024-10-22 16:39:10 -04:00
videoPath := currentVideo.Path
log.Println("start stream: ", videoPath)
2024-10-23 03:40:10 -04:00
s.cmd = exec.CommandContext(s.ctx, "ffmpeg", s.buildFFmpegArgs(currentVideo)...)
2024-10-22 16:39:10 -04:00
pipe, err := s.cmd.StderrPipe()
if err != nil {
log.Printf("failed to get pipe: %v", err)
return
}
reader := bufio.NewReader(pipe)
writer := bufio.NewWriter(s.logFile)
if err := s.cmd.Start(); err != nil {
log.Printf("starting ffmpeg error: %v\n", err)
return
}
2024-10-23 03:40:10 -04:00
go s.log(reader, writer)
2024-10-22 16:39:10 -04:00
2024-10-23 03:40:10 -04:00
select {
case <-s.ctx.Done():
log.Println("case <-s.ctx.Done")
if s.cmd != nil && s.cmd.Process != nil {
_ = s.cmd.Process.Kill()
2024-10-23 03:44:10 -04:00
s.cmd = nil
2024-10-22 16:39:10 -04:00
}
2024-10-23 03:40:10 -04:00
case err := <-waitCmd(s.cmd):
log.Println("case err := <-waitCmd(s.cmd)")
if err != nil {
log.Printf("ffmpeg exited with error: %v", err)
}
s.Next()
}
2024-10-22 16:39:10 -04:00
}
func (s *Streamer) Stop() {
2024-10-23 03:40:10 -04:00
if s.cancel != nil {
s.cancel()
2024-10-22 16:39:10 -04:00
}
}
func (s *Streamer) GetCurrentVideo() string {
2024-10-23 03:40:10 -04:00
return s.videoList[s.currentVideoIndex].Path
2024-10-22 16:39:10 -04:00
}
func (s *Streamer) GetPlaylist() []config.InputItem {
2024-10-23 03:40:10 -04:00
return s.videoList
2024-10-22 16:39:10 -04:00
}
func (s *Streamer) Close() {
if s.logFile != nil {
s.logFile.Close()
s.logFile = nil
}
}
2024-10-23 03:40:10 -04:00
func waitCmd(cmd *exec.Cmd) <-chan error {
ch := make(chan error, 1)
go func() {
ch <- cmd.Wait()
}()
return ch
}
func (s *Streamer) log(reader *bufio.Reader, writer *bufio.Writer) {
defer func() {
if s.logFile != nil {
if err := s.logFile.Sync(); err != nil {
log.Printf("syncing log file error: %v\n", err)
}
}
}()
buf := make([]byte, 1024)
for {
n, err := reader.Read(buf)
if err != nil {
if err != io.EOF {
log.Printf("reading ffmpeg error: %v\n", err)
}
break
}
if n > 0 {
timestamp := time.Now().Format("2006-01-02 15:04:05")
logLine := fmt.Sprintf("[%s] %s", timestamp, string(buf[:n]))
if s.logFile != nil {
if _, err := writer.WriteString(logLine); err != nil {
log.Printf("writing to log file error: %v\n", err)
}
if err := writer.Flush(); err != nil {
log.Printf("flushing writer error: %v\n", err)
}
}
}
}
}