live-streamer/streamer/streamer.go

429 lines
9.6 KiB
Go
Raw Permalink 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-29 05:11:14 -04:00
"errors"
2024-10-22 16:39:10 -04:00
"fmt"
"io"
2024-10-29 05:11:14 -04:00
"live-streamer/model"
"path/filepath"
2024-10-22 16:39:10 -04:00
"os/exec"
"strings"
2024-10-23 04:37:43 -04:00
"sync"
2024-10-22 16:39:10 -04:00
"time"
"go.uber.org/zap"
2024-10-22 16:39:10 -04:00
)
type Streamer struct {
mailbox chan Message
state *streamerState
output strings.Builder
outputQueue chan string
outputReq chan chan string // address output concurrency security issue
wg sync.WaitGroup // wait all handlers(except closehandler) to finish before closure
close chan any // inform actorLoop() to return
closed chan any // inform Close() to return
2024-10-29 05:11:14 -04:00
log *zap.Logger
option *Option
rtmpServer string
streamKey string
}
type Option struct {
FFmpegArgs map[string]any
ShowFFmpegOutput bool
}
type streamerState struct {
2024-10-29 05:11:14 -04:00
videoList []model.VideoItem
2024-10-22 16:39:10 -04:00
currentVideoIndex int
2024-10-24 04:21:35 -04:00
manualControl bool
2024-10-22 16:39:10 -04:00
cmd *exec.Cmd
2024-10-23 03:40:10 -04:00
ctx context.Context
cancel context.CancelFunc
waitDone chan any
2024-10-24 04:21:35 -04:00
}
var GlobalStreamer *Streamer
2024-10-24 04:21:35 -04:00
2024-10-29 05:11:14 -04:00
func NewStreamer(rtmpServer string, streamKey string, videoList []model.VideoItem, log *zap.Logger, option *Option) (*Streamer, error) {
if rtmpServer == "" || streamKey == "" {
return nil, errors.New("lack of args")
}
s := &Streamer{
mailbox: make(chan Message, 100),
state: &streamerState{
videoList: videoList,
},
output: strings.Builder{},
outputQueue: make(chan string, 100),
outputReq: make(chan chan string),
close: make(chan any),
2024-10-29 05:11:14 -04:00
option: option,
log: log,
rtmpServer: rtmpServer,
streamKey: streamKey,
closed: make(chan any),
}
GlobalStreamer = s
go s.actorLoop()
go s.handleOutput()
2024-10-29 05:11:14 -04:00
return s, nil
2024-10-22 16:39:10 -04:00
}
func (s *Streamer) actorLoop() {
for {
select {
case <-s.close:
return
case msg := <-s.mailbox:
if _, ok := msg.(CloseMessage); !ok {
s.wg.Add(1)
s.handleMessage(msg)
s.wg.Done()
} else {
s.handleMessage(msg)
}
}
}
}
2024-10-23 10:47:37 -04:00
func (s *Streamer) handleMessage(msg Message) {
switch m := msg.(type) {
case StartMessage:
s.handleStart()
case StopMessage:
s.handleStop()
case AddVideoMessage:
s.handleAdd(m.Path)
case RemoveVideoMessage:
s.handleRemove(m.Path)
case NextVideoMessage:
s.handleNext()
case PrevVideoMessage:
s.handlePrev()
case GetCurrentVideoMessage:
s.handleGetCurrentVideo(m.Response)
case GetVideoListMessage:
s.handleGetVideoList(m.Response)
case GetVideoListPathMessage:
s.handleGetVideoListPath(m.Response)
case GetCurrentIndexMessage:
s.handleGetCurrentIndex(m.Response)
case CloseMessage:
s.handleClose()
2024-10-23 10:47:37 -04:00
}
}
func (s *Streamer) handleStart() {
if len(s.state.videoList) == 0 {
time.Sleep(time.Second)
s.mailbox <- StartMessage{}
return
}
s.state.ctx, s.state.cancel = context.WithCancel(context.Background())
currentVideo := s.state.videoList[s.state.currentVideoIndex]
2024-10-23 10:47:37 -04:00
videoPath := currentVideo.Path
2024-10-29 05:11:14 -04:00
s.state.cmd = exec.CommandContext(s.state.ctx, "ffmpeg", s.buildFFmpegArgs(currentVideo)...)
s.state.waitDone = make(chan any)
2024-10-24 04:21:35 -04:00
pipe, err := s.state.cmd.StderrPipe() // ffmpeg send all messages to stderr
2024-10-23 10:47:37 -04:00
if err != nil {
2024-10-29 05:11:14 -04:00
s.log.Error("failed to get pipe", zap.Error(err))
2024-10-23 10:47:37 -04:00
return
}
reader := bufio.NewReader(pipe)
2024-10-29 05:11:14 -04:00
s.log.Info("start stream", zap.String("path", videoPath))
s.writeOutput(fmt.Sprintln("start stream: ", videoPath))
if err := s.state.cmd.Start(); err != nil {
2024-10-23 17:06:19 -04:00
s.writeOutput(fmt.Sprintf("starting ffmpeg error: %v\n", err))
2024-10-23 10:47:37 -04:00
return
}
go func() {
2024-10-29 05:11:14 -04:00
s.log.Debug("wait stream end", zap.String("path", videoPath))
_ = s.state.cmd.Wait()
2024-10-29 05:11:14 -04:00
s.log.Debug("process stop", zap.String("path", videoPath))
s.state.cancel()
2024-10-29 05:11:14 -04:00
s.log.Debug("context cancel", zap.String("path", videoPath))
s.writeOutput(fmt.Sprintf("stop stream: %s\n", videoPath))
2024-10-23 17:06:19 -04:00
if !s.state.manualControl {
2024-10-29 05:11:14 -04:00
s.log.Debug("video end", zap.String("path", videoPath))
s.state.currentVideoIndex++
if s.state.currentVideoIndex >= len(s.state.videoList) {
s.state.currentVideoIndex = 0
}
s.mailbox <- StartMessage{}
} else {
2024-10-29 05:11:14 -04:00
s.log.Debug("manually end", zap.String("path", videoPath))
s.state.manualControl = false
2024-10-23 17:06:19 -04:00
}
2024-10-23 10:47:37 -04:00
close(s.state.waitDone)
}()
2024-10-29 05:11:14 -04:00
go s.ffmpegLog(reader)
2024-10-23 10:47:37 -04:00
}
func (s *Streamer) handleStop() {
if s.state.cancel == nil || s.state.cmd == nil {
2024-10-24 04:21:35 -04:00
return
2024-10-22 16:39:10 -04:00
}
videoPath := s.state.videoList[s.state.currentVideoIndex].Path
2024-10-29 05:11:14 -04:00
s.log.Debug("wait context to be cancelled", zap.String("path", videoPath))
s.state.cancel()
2024-10-29 05:11:14 -04:00
s.log.Debug("context has been cancelled", zap.String("path", videoPath))
2024-10-24 04:21:35 -04:00
if s.state.cmd.Process != nil {
2024-10-29 05:11:14 -04:00
s.log.Debug("wait ffmpeg process stop", zap.String("path", videoPath))
2024-10-24 04:21:35 -04:00
select {
case <-s.state.waitDone:
2024-10-24 04:21:35 -04:00
case <-time.After(3 * time.Second):
_ = s.state.cmd.Process.Kill()
2024-10-24 04:21:35 -04:00
}
2024-10-29 05:11:14 -04:00
s.log.Debug("ffmpeg process has stopped", zap.String("path", videoPath))
2024-10-24 04:21:35 -04:00
}
s.state.cancel = nil
s.state.cmd = nil
2024-10-23 17:06:19 -04:00
}
func (s *Streamer) handleAdd(path string) {
2024-10-29 05:11:14 -04:00
s.state.videoList = append(s.state.videoList, model.VideoItem{Path: path})
2024-10-22 16:39:10 -04:00
}
func (s *Streamer) handleRemove(path string) {
var needStop bool
2024-10-24 04:21:35 -04:00
var removeIndex int = -1
for i, item := range s.state.videoList {
if item.Path == path {
2024-10-24 04:21:35 -04:00
removeIndex = i
needStop = (s.state.currentVideoIndex == i)
2024-10-22 16:39:10 -04:00
break
}
}
2024-10-24 04:21:35 -04:00
if removeIndex >= 0 && removeIndex < len(s.state.videoList) {
oldLen := len(s.state.videoList)
s.state.videoList = append(s.state.videoList[:removeIndex], s.state.videoList[removeIndex+1:]...)
if s.state.currentVideoIndex >= oldLen-1 {
s.state.currentVideoIndex = 0
2024-10-24 04:21:35 -04:00
}
}
if needStop {
s.mailbox <- StopMessage{}
s.mailbox <- StartMessage{}
2024-10-24 04:21:35 -04:00
}
2024-10-22 16:39:10 -04:00
}
func (s *Streamer) handleNext() {
if len(s.state.videoList) == 0 {
2024-10-24 04:21:35 -04:00
return
}
s.state.manualControl = true
s.state.currentVideoIndex = (s.state.currentVideoIndex + 1) % len(s.state.videoList)
2024-10-24 04:21:35 -04:00
s.mailbox <- StopMessage{}
s.mailbox <- StartMessage{}
2024-10-22 16:39:10 -04:00
}
func (s *Streamer) handlePrev() {
if len(s.state.videoList) == 0 {
2024-10-24 04:21:35 -04:00
return
}
s.state.manualControl = true
s.state.currentVideoIndex = (s.state.currentVideoIndex - 1 + len(s.state.videoList)) % len(s.state.videoList)
2024-10-24 04:21:35 -04:00
s.mailbox <- StopMessage{}
s.mailbox <- StartMessage{}
2024-10-22 16:39:10 -04:00
}
func (s *Streamer) handleGetCurrentVideo(response chan string) {
if len(s.state.videoList) == 0 {
response <- ""
2024-10-23 10:47:37 -04:00
return
2024-10-22 16:39:10 -04:00
}
response <- s.state.videoList[s.state.currentVideoIndex].Path
2024-10-22 16:39:10 -04:00
}
2024-10-29 05:11:14 -04:00
func (s *Streamer) handleGetVideoList(response chan []model.VideoItem) {
response <- s.state.videoList
}
func (s *Streamer) handleGetVideoListPath(response chan []string) {
var paths []string
for _, item := range s.state.videoList {
paths = append(paths, item.Path)
2024-10-23 17:06:19 -04:00
}
response <- paths
2024-10-23 17:06:19 -04:00
}
func (s *Streamer) handleGetCurrentIndex(response chan int) {
response <- s.state.currentVideoIndex
2024-10-23 17:06:19 -04:00
}
func (s *Streamer) handleClose() {
close(s.close)
s.handleStop()
s.wg.Wait()
close(s.mailbox)
close(s.outputQueue)
close(s.outputReq)
s.output.Reset()
GlobalStreamer = nil
close(s.closed)
2024-10-23 17:06:19 -04:00
}
// Public methods that send messages to the actor
func (s *Streamer) Start() {
s.mailbox <- StartMessage{}
2024-10-23 17:06:19 -04:00
}
func (s *Streamer) Stop() {
s.mailbox <- StopMessage{}
2024-10-23 17:06:19 -04:00
}
func (s *Streamer) Add(path string) {
s.mailbox <- AddVideoMessage{Path: path}
2024-10-23 17:06:19 -04:00
}
func (s *Streamer) Remove(path string) {
s.mailbox <- RemoveVideoMessage{Path: path}
2024-10-23 17:06:19 -04:00
}
func (s *Streamer) Next() {
s.mailbox <- NextVideoMessage{}
}
2024-10-22 16:39:10 -04:00
func (s *Streamer) Prev() {
s.mailbox <- PrevVideoMessage{}
}
2024-10-22 16:39:10 -04:00
func (s *Streamer) GetCurrentVideoPath() string {
response := make(chan string)
s.mailbox <- GetCurrentVideoMessage{Response: response}
return <-response
}
2024-10-22 16:39:10 -04:00
2024-10-29 05:11:14 -04:00
func (s *Streamer) GetVideoList() []model.VideoItem {
response := make(chan []model.VideoItem)
s.mailbox <- GetVideoListMessage{Response: response}
return <-response
}
2024-10-22 16:39:10 -04:00
func (s *Streamer) GetVideoListPath() []string {
response := make(chan []string)
s.mailbox <- GetVideoListPathMessage{Response: response}
return <-response
}
func (s *Streamer) GetCurrentIndex() int {
response := make(chan int)
s.mailbox <- GetCurrentIndexMessage{Response: response}
return <-response
}
2024-10-22 16:39:10 -04:00
func (s *Streamer) Close() {
s.mailbox <- CloseMessage{}
<-s.closed
}
2024-10-22 16:39:10 -04:00
func (s *Streamer) handleOutput() {
for {
select {
case o := <-s.outputQueue:
s.output.WriteString(o)
case c := <-s.outputReq:
c <- s.output.String()
}
}
}
func (s *Streamer) GetOutput() string {
o := make(chan string)
s.outputReq <- o
return <-o
}
func (s *Streamer) writeOutput(str string) {
s.outputQueue <- str
}
2024-10-29 05:11:14 -04:00
func (s *Streamer) ffmpegLog(reader *bufio.Reader) {
select {
case <-s.state.ctx.Done():
return
default:
buf := make([]byte, 1024)
for {
n, err := reader.Read(buf)
if n > 0 {
2024-10-29 05:11:14 -04:00
if s.option.ShowFFmpegOutput {
s.writeOutput(string(buf[:n]))
}
if s.log.Level() == zap.DebugLevel {
fmt.Print(string(buf[:n]))
}
}
if err != nil {
if err != io.EOF {
s.writeOutput(fmt.Sprintf("reading ffmpeg output error: %v\n", err))
}
break
}
}
}
2024-10-22 16:39:10 -04:00
}
2024-10-29 05:11:14 -04:00
func (s *Streamer) buildFFmpegArgs(videoItem model.VideoItem) []string {
videoPath := videoItem.Path
args := []string{"-re"}
if videoItem.Start != "" {
args = append(args, "-ss", videoItem.Start)
}
if videoItem.End != "" {
args = append(args, "-to", videoItem.End)
}
args = append(args,
"-i", videoPath,
)
for k, v := range s.option.FFmpegArgs {
args = append(args, k)
if str, ok := v.(string); ok {
filename := strings.TrimSuffix(filepath.Base(videoPath), filepath.Ext(videoPath))
str = strings.ReplaceAll(str, "{{filepath}}", videoPath)
str = strings.ReplaceAll(str, "{{filename}}", filename)
args = append(args, str)
} else {
args = append(args, fmt.Sprint(v))
}
}
args = append(args, fmt.Sprintf("%s/%s", s.rtmpServer, s.streamKey))
s.log.Debug("build ffmpeg", zap.Strings("args", args))
return args
}