livestream/server/utils.go

124 lines
2.7 KiB
Go
Raw Permalink Normal View History

2023-06-13 00:07:14 +03:00
package main
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
2023-06-13 00:07:14 +03:00
"io/fs"
"os"
2023-06-13 00:07:14 +03:00
"path"
"path/filepath"
"strings"
"github.com/BatteredBunny/rjson"
ffmpeg "github.com/u2takey/ffmpeg-go"
2023-06-13 00:07:14 +03:00
)
func listFilesRecursively(findPath string, hide_hidden bool) (filelist []string, err error) {
err = filepath.Walk(findPath, func(currentPath string, info fs.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() {
if hide_hidden && strings.HasPrefix(path.Base(currentPath), ".") {
return nil
}
filelist = append(filelist, currentPath)
}
return nil
})
return
}
2024-02-24 16:54:27 +02:00
func RecreateDir(dir string) (err error) {
if err = os.RemoveAll(dir); err != nil {
return
}
2024-02-24 16:54:27 +02:00
os.MkdirAll(dir, 0700)
return
}
type StreamInfo struct {
Index int `json:"index"`
CodecName string `json:"codec_name"`
CodecType string `json:"codec_type"`
Disposition StreamInfoDisposition `json:"disposition"`
Tags StreamInfoTags `json:"tags"`
}
type StreamInfoDisposition struct {
HearingImpaired int `json:"hearing_impaired"`
}
type StreamInfoTags struct {
Language string `json:"language"`
}
func SelectPreferredSubtitle(filename string) (*int, error) {
rawMetadata, err := ffmpeg.Probe(filename)
if err != nil {
return nil, err
}
metadata, err := rjson.QueryJson([]byte(rawMetadata), `.streams.[]`)
if err != nil {
return nil, err
}
var streams []StreamInfo
if err = json.Unmarshal(metadata, &streams); err != nil {
return nil, err
}
var numberOfSubStreams int
for _, stream := range streams {
if stream.CodecType == "subtitle" {
numberOfSubStreams += 1
}
}
streamNumberModifier := len(streams) - numberOfSubStreams
var bestSubtitle StreamInfo
var foundSubtitle bool
for _, stream := range streams {
// Skips dvd_subtitle or picture based subtitles as i dont know how to hardcode them
if stream.CodecType != "subtitle" || stream.CodecName == "dvd_subtitle" || stream.Tags.Language != "eng" {
continue
}
if bestSubtitle.Disposition.HearingImpaired == 0 && stream.Disposition.HearingImpaired == 1 {
bestSubtitle = stream
foundSubtitle = true
} else if bestSubtitle.Disposition.HearingImpaired == 1 && stream.Disposition.HearingImpaired == 0 {
// Skips if bestSubtitle is HearingImpaired and current one isnt
continue
} else {
bestSubtitle = stream
foundSubtitle = true
}
}
if foundSubtitle {
actualStreamIndex := bestSubtitle.Index - streamNumberModifier
return &actualStreamIndex, nil
} else {
return nil, nil
}
}
func ToColor(s string) (color string) {
hasher := sha256.New()
hasher.Write([]byte(s))
color = hex.EncodeToString(hasher.Sum(nil))
color = color[0:6]
return
}