live-streamer/streamer/streamer.go

345 lines
7.2 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"
2024-10-23 14:35:37 -04:00
"log"
"os"
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"
)
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
}
type streamerState struct {
videoList []config.InputItem
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
func NewStreamer(videoList []config.InputItem) *Streamer {
s := &Streamer{
mailbox: make(chan Message, 100),
state: &streamerState{
videoList: videoList,
},
output: strings.Builder{},
outputQueue: make(chan string, 100),
outputReq: make(chan chan string),
}
GlobalStreamer = s
go s.actorLoop()
go s.handleOutput()
return s
2024-10-22 16:39:10 -04:00
}
func (s *Streamer) actorLoop() {
for msg := range s.mailbox {
if msg.messageType() != CloseMessage.messageType(CloseMessage{}) {
log.Printf("handle %s start\n", msg.messageType())
s.wg.Add(1)
s.handleMessage(msg)
s.wg.Done()
log.Printf("handle %s end\n", msg.messageType())
} 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
s.state.cmd = exec.CommandContext(s.state.ctx, "ffmpeg", buildFFmpegArgs(currentVideo)...)
s.state.waitDone = make(chan any)
2024-10-24 04:21:35 -04:00
2024-10-23 17:06:19 -04:00
s.writeOutput(fmt.Sprintln("start stream: ", videoPath))
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-23 14:35:37 -04:00
log.Printf("failed to get pipe: %v", err)
2024-10-23 10:47:37 -04:00
return
}
reader := bufio.NewReader(pipe)
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 s.log(reader)
go func() {
_ = s.state.cmd.Wait()
s.state.cancel()
s.writeOutput(fmt.Sprintf("stop stream: %s\n", videoPath))
2024-10-23 17:06:19 -04:00
if !s.state.manualControl {
s.mailbox <- NextVideoMessage{}
} else {
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-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
}
s.state.cancel()
2024-10-24 04:21:35 -04:00
if s.state.cmd.Process != nil {
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-23 17:06:19 -04:00
}
func (s *Streamer) handleAdd(path string) {
s.state.videoList = append(s.state.videoList, config.InputItem{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++
if s.state.currentVideoIndex >= len(s.state.videoList) {
s.state.currentVideoIndex = 0
2024-10-22 16:39:10 -04:00
}
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--
if s.state.currentVideoIndex < 0 {
s.state.currentVideoIndex = len(s.state.videoList) - 1
2024-10-22 16:39:10 -04:00
}
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
}
func (s *Streamer) handleGetVideoList(response chan []config.InputItem) {
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() {
s.wg.Wait()
os.Exit(0)
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
func (s *Streamer) GetVideoList() []config.InputItem {
response := make(chan []config.InputItem)
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 <- StopMessage{}
s.mailbox <- CloseMessage{}
}
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
}
func (s *Streamer) log(reader *bufio.Reader) {
select {
case <-s.state.ctx.Done():
return
default:
if !config.GlobalConfig.Log.PlayState {
return
}
buf := make([]byte, 1024)
for {
n, err := reader.Read(buf)
if n > 0 {
s.writeOutput(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
}