stream-server/srt/stream_ids.go

70 lines
1.9 KiB
Go
Raw Normal View History

2023-09-21 13:36:11 +05:00
package srt
import (
"os"
"io"
"strings"
2023-09-22 12:33:55 +05:00
"stream_server/transcoder"
2023-09-22 12:54:50 +05:00
"time"
"path/filepath"
2023-09-21 13:36:11 +05:00
)
2023-09-22 14:58:33 +05:00
// spawn a transcoder instance and return its stdin pipe
2023-09-21 13:36:11 +05:00
func NewWriter(stream_key string) (io.WriteCloser, error) {
2023-09-22 12:33:55 +05:00
transcoder_in, err := transcoder.NewTranscoder(stream_key)
2023-09-21 13:36:11 +05:00
if err != nil {
return nil, err
}
2023-09-22 12:33:55 +05:00
return transcoder_in, nil
2023-09-21 13:36:11 +05:00
}
2023-09-22 14:58:33 +05:00
// check if the init.mp4 segment has been modified in between a given sleep time
// if it hasn't (stream disconnected for longer) delete it
// else a new stream has started which shouldn't be deleted
2023-09-22 12:54:50 +05:00
func CleanFiles(stream_key string, delay time.Duration) {
time.Sleep(delay * time.Second)
base_dir, _ := os.UserHomeDir()
stream_dir := base_dir + "/live/" + stream_key
fileinfo, file_ok := os.Stat(stream_dir + "/init.mp4")
if file_ok != nil {
return
}
2023-09-22 12:54:50 +05:00
if time.Now().Sub(fileinfo.ModTime()) > delay * time.Second {
leftover_files, _ := filepath.Glob(stream_dir + "/*")
for _, file := range leftover_files {
os.Remove(file)
}
}
}
2023-09-22 14:58:33 +05:00
// stream_id is in reverse order, len is multiple of 4 padded with 0
// get the string, check if corresponding folder exists, then attempt
// to spawn a transcoder instance
2023-09-22 12:54:50 +05:00
func CheckStreamID(stream_id []byte) (io.WriteCloser, string, bool) {
2023-09-21 13:36:11 +05:00
stream_key := make([]byte, 0)
for i := len(stream_id) - 1; i >= 0; i-- {
if stream_id[i] == 0 {
break
}
stream_key = append(stream_key, stream_id[i])
}
stream_key_string := strings.TrimSpace(string(stream_key))
if check_stream_key(stream_key_string) {
writer, err := NewWriter(stream_key_string)
if err != nil {
2023-09-22 12:54:50 +05:00
return nil, stream_key_string, false
2023-09-21 13:36:11 +05:00
}
2023-09-22 12:54:50 +05:00
return writer, stream_key_string, true
2023-09-21 13:36:11 +05:00
}
2023-09-22 12:54:50 +05:00
return nil, stream_key_string, false
2023-09-21 13:36:11 +05:00
}
2023-09-22 14:58:33 +05:00
// checks if folder exists corresponding to the stream_key
2023-09-21 13:36:11 +05:00
func check_stream_key(stream_key string) (bool) {
base_dir, _ := os.UserHomeDir()
if fileinfo, err := os.Stat(base_dir + "/live/" + stream_key); err == nil && fileinfo.IsDir() {
return true
}
return false
}