streamd: optional keys, per-stream proxy, auto deps; agent module.yaml sync; RTE AutoPlay; Telegram release announces
All checks were successful
release / build-and-upload (push) Successful in 6m20s
modules-release / build-and-upload (push) Successful in 4m51s

- streamd: MPD-only start, proxy field, ffmpeg/NRE/mp4decrypt auto-install
- GET/PUT /api/modules for module.yaml sync; agent sync_modules
- RTE Live-tab AutoPlay fixes; modules zip named bbc/rte/tg4.zip
- Telegram notify scripts wired into Forgejo release workflows
This commit is contained in:
404errordeveloper 2026-10-09 00:17:23 +02:00
parent f9c28be3f1
commit ac8701b5a6
36 changed files with 1460 additions and 143 deletions

View file

@ -19,11 +19,13 @@ apps/streamd/
./bin/drm serve --bind 127.0.0.1:8083 --data .cache/streamd --token SECRET
```
Port 8083 by default, to stay clear of anything already on 8080/8081. Media tools
resolve from flags, then env (`NRE_PATH` / `FFMPEG_PATH` / `MP4DECRYPT_PATH`), then
`bin/`, then `PATH` — no machine-specific paths are baked in.
Port 8083 by default, to stay clear of anything already on 8080/8081. On start,
missing media tools are downloaded into `bin/` (ffmpeg, N_m3u8DL-RE, mp4decrypt)
unless you pass `--skip-deps`. Flags / env still win when set.
Open `http://HOST:8083/` and put the token in the header box for mutating actions.
Add a stream with an `.mpd` URL; Widevine keys are optional for clear content.
Optional per-stream SOCKS5/HTTP `proxy` routes origin fetches (geo egress).
## API
@ -35,7 +37,7 @@ Open `http://HOST:8083/` and put the token in the header box for mutating action
| POST | `/api/streams` | create |
| GET/PATCH/DELETE | `/api/streams/:id` | detail / edit / delete |
| POST | `/api/streams/:id/start\|stop\|restart` | desired state |
| POST | `/api/streams/:id/credentials` | `{mpd,key,pssh?,auth?,pid?}`, restarts if enabled |
| POST | `/api/streams/:id/credentials` | `{mpd,key?,pssh?,auth?,pid?}` — key optional; restarts if enabled |
| POST | `/api/streams/:id/claim` | agent lease (`agent_id`, TTL ~3m) |
| POST | `/api/streams/:id/claim/release` | release lease |

View file

@ -10,6 +10,7 @@ import (
"time"
"drmdecryption/apps/streamd/internal/db"
"drmdecryption/apps/streamd/internal/deps"
)
type Supervisor interface {
@ -23,6 +24,7 @@ type Handler struct {
Token string
Supervisor Supervisor
StartedAt time.Time
Deps deps.Status
}
func (h *Handler) Mount(mux *http.ServeMux) {
@ -30,6 +32,8 @@ func (h *Handler) Mount(mux *http.ServeMux) {
mux.HandleFunc("/api/streams", h.streams)
mux.HandleFunc("/api/streams/", h.streamAction)
mux.HandleFunc("/api/apps", h.apps)
mux.HandleFunc("/api/modules", h.modules)
mux.HandleFunc("/api/modules/", h.modules)
}
func (h *Handler) auth(w http.ResponseWriter, r *http.Request) bool {
@ -64,6 +68,7 @@ func (h *Handler) health(w http.ResponseWriter, r *http.Request) {
"service": "streamd",
"uptime_s": time.Since(h.StartedAt).Seconds(),
"started_at": h.StartedAt.UTC().Format(time.RFC3339),
"deps": h.Deps,
})
}
@ -310,8 +315,8 @@ func writeErr(w http.ResponseWriter, code int, msg string) {
writeJSON(w, code, map[string]any{"error": msg})
}
// credentialsChanged is true when the patch touched mpd, key, or headers that
// the live NRE/ffmpeg worker is already using.
// credentialsChanged is true when the patch touched mpd, key, headers, or proxy
// that the live NRE/ffmpeg worker is already using.
func credentialsChanged(before, after db.Stream, in db.PatchStream) bool {
if in.MPD != nil && strings.TrimSpace(before.MPD) != strings.TrimSpace(after.MPD) {
return true
@ -322,5 +327,8 @@ func credentialsChanged(before, after db.Stream, in db.PatchStream) bool {
if in.HeadersJSON != nil && strings.TrimSpace(before.HeadersJSON) != strings.TrimSpace(after.HeadersJSON) {
return true
}
if in.Proxy != nil && strings.TrimSpace(before.Proxy) != strings.TrimSpace(after.Proxy) {
return true
}
return false
}

View file

@ -0,0 +1,157 @@
package api
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"io"
"net/http"
"os"
"path/filepath"
"regexp"
"strings"
"drmdecryption/modhost"
"drmdecryption/repo"
)
// moduleInfo is one modules/<name>/ entry for agent sync.
type moduleInfo struct {
Name string `json:"name"`
HasYAML bool `json:"has_yaml"`
YAMLSHA256 string `json:"yaml_sha256,omitempty"`
}
var moduleNameRe = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$`)
func (h *Handler) modules(w http.ResponseWriter, r *http.Request) {
path := strings.TrimPrefix(r.URL.Path, "/api/modules")
path = strings.Trim(path, "/")
switch {
case path == "" && r.Method == http.MethodGet:
h.listModules(w, r)
case path != "" && !strings.Contains(path, "/") && r.Method == http.MethodGet:
h.getModule(w, r, path)
case path != "" && !strings.Contains(path, "/") && r.Method == http.MethodPut:
h.putModule(w, r, path)
default:
writeErr(w, http.StatusMethodNotAllowed, "method not allowed")
}
}
func (h *Handler) listModules(w http.ResponseWriter, r *http.Request) {
root := repo.Root()
dir := modhost.ModulesDir(root)
ents, err := os.ReadDir(dir)
if err != nil {
if os.IsNotExist(err) {
writeJSON(w, http.StatusOK, map[string]any{"modules": []moduleInfo{}})
return
}
writeErr(w, http.StatusInternalServerError, err.Error())
return
}
out := []moduleInfo{}
for _, e := range ents {
if !e.IsDir() || strings.HasPrefix(e.Name(), ".") {
continue
}
info := moduleYAMLInfo(filepath.Join(dir, e.Name()), e.Name())
out = append(out, info)
}
writeJSON(w, http.StatusOK, map[string]any{"modules": out})
}
func (h *Handler) getModule(w http.ResponseWriter, r *http.Request, name string) {
if !moduleNameRe.MatchString(name) {
writeErr(w, http.StatusBadRequest, "invalid module name")
return
}
info := moduleYAMLInfo(filepath.Join(modhost.ModulesDir(repo.Root()), name), name)
writeJSON(w, http.StatusOK, info)
}
func (h *Handler) putModule(w http.ResponseWriter, r *http.Request, name string) {
if !h.auth(w, r) {
return
}
if !moduleNameRe.MatchString(name) {
writeErr(w, http.StatusBadRequest, "invalid module name")
return
}
body, err := io.ReadAll(io.LimitReader(r.Body, 2<<20))
if err != nil {
writeErr(w, http.StatusBadRequest, err.Error())
return
}
defer r.Body.Close()
yamlBytes, err := extractModuleYAML(r.Header.Get("Content-Type"), body)
if err != nil {
writeErr(w, http.StatusBadRequest, err.Error())
return
}
if len(strings.TrimSpace(string(yamlBytes))) == 0 {
writeErr(w, http.StatusBadRequest, "empty module.yaml")
return
}
modDir := filepath.Join(modhost.ModulesDir(repo.Root()), name)
if err := os.MkdirAll(modDir, 0o755); err != nil {
writeErr(w, http.StatusInternalServerError, err.Error())
return
}
dest := filepath.Join(modDir, "module.yaml")
tmp := dest + ".tmp"
if err := os.WriteFile(tmp, yamlBytes, 0o644); err != nil {
writeErr(w, http.StatusInternalServerError, err.Error())
return
}
if err := os.Rename(tmp, dest); err != nil {
_ = os.Remove(tmp)
writeErr(w, http.StatusInternalServerError, err.Error())
return
}
info := moduleYAMLInfo(modDir, name)
writeJSON(w, http.StatusOK, map[string]any{
"ok": true,
"module": info,
})
}
func moduleYAMLInfo(modDir, name string) moduleInfo {
info := moduleInfo{Name: name}
b, err := os.ReadFile(filepath.Join(modDir, "module.yaml"))
if err != nil {
return info
}
sum := sha256.Sum256(b)
info.HasYAML = true
info.YAMLSHA256 = hex.EncodeToString(sum[:])
return info
}
// extractModuleYAML accepts raw YAML or JSON {"yaml":"..."}.
func extractModuleYAML(contentType string, body []byte) ([]byte, error) {
ct := strings.ToLower(strings.TrimSpace(strings.Split(contentType, ";")[0]))
switch ct {
case "application/json", "text/json":
var wrap struct {
YAML string `json:"yaml"`
}
if err := json.Unmarshal(body, &wrap); err != nil {
return nil, err
}
if strings.TrimSpace(wrap.YAML) == "" {
return nil, errors.New("empty yaml field")
}
return []byte(wrap.YAML), nil
default:
// text/yaml, application/x-yaml, or bare body
return body, nil
}
}

View file

@ -25,6 +25,7 @@ type Stream struct {
MPD string `json:"mpd"`
Key string `json:"key"`
HeadersJSON string `json:"headers_json"`
Proxy string `json:"proxy"` // socks5:// or http:// for origin fetch (NRE)
VideoSelect string `json:"video_select"`
AudioSelect string `json:"audio_select"`
Enabled bool `json:"enabled"`
@ -53,6 +54,7 @@ type CreateStream struct {
MPD string `json:"mpd"`
Key string `json:"key"`
HeadersJSON string `json:"headers_json"`
Proxy string `json:"proxy"`
VideoSelect string `json:"video_select"`
AudioSelect string `json:"audio_select"`
Rewriter string `json:"rewriter"`
@ -66,6 +68,7 @@ type PatchStream struct {
MPD *string `json:"mpd"`
Key *string `json:"key"`
HeadersJSON *string `json:"headers_json"`
Proxy *string `json:"proxy"`
VideoSelect *string `json:"video_select"`
AudioSelect *string `json:"audio_select"`
Rewriter *string `json:"rewriter"`
@ -74,7 +77,7 @@ type PatchStream struct {
type Credentials struct {
MPD string `json:"mpd"`
Key string `json:"key"`
Key string `json:"key"` // optional for clear streams
PSSH string `json:"pssh,omitempty"`
Auth string `json:"auth,omitempty"`
PID string `json:"pid,omitempty"`
@ -114,6 +117,7 @@ CREATE TABLE IF NOT EXISTS streams (
mpd TEXT NOT NULL DEFAULT '',
key_kid_key TEXT NOT NULL DEFAULT '',
headers_json TEXT NOT NULL DEFAULT '{}',
proxy TEXT NOT NULL DEFAULT '',
video_select TEXT NOT NULL DEFAULT '',
audio_select TEXT NOT NULL DEFAULT '',
enabled INTEGER NOT NULL DEFAULT 0,
@ -141,7 +145,12 @@ CREATE TABLE IF NOT EXISTS agent_claims (
expires_at TEXT NOT NULL
);
`)
return err
if err != nil {
return err
}
// Older DBs created before proxy existed.
_, _ = s.DB.Exec(`ALTER TABLE streams ADD COLUMN proxy TEXT NOT NULL DEFAULT ''`)
return nil
}
func now() string {
@ -166,18 +175,19 @@ func slug(name string) string {
return out
}
func (s *Store) ListStreams() ([]Stream, error) {
rows, err := s.DB.Query(`
const streamSelect = `
SELECT s.id, s.name, s.title, s.app, s.channel, s.mpd, s.key_kid_key, s.headers_json,
s.video_select, s.audio_select, s.enabled, s.rewriter, s.created_at, s.updated_at,
COALESCE(s.proxy,''), s.video_select, s.audio_select, s.enabled, s.rewriter, s.created_at, s.updated_at,
COALESCE(r.health,''), COALESCE(r.pid,0), COALESCE(r.play_path,''),
COALESCE(r.uptime_s,0), COALESCE(r.bitrate_mbps,0), COALESCE(r.playlist_age_s,0),
COALESCE(r.last_error,''), COALESCE(r.updated_at,''),
COALESCE(c.agent_id,''), COALESCE(c.expires_at,'')
FROM streams s
LEFT JOIN stream_runtime r ON r.stream_id = s.id
LEFT JOIN agent_claims c ON c.stream_id = s.id
ORDER BY s.name`)
LEFT JOIN agent_claims c ON c.stream_id = s.id`
func (s *Store) ListStreams() ([]Stream, error) {
rows, err := s.DB.Query(streamSelect + ` ORDER BY s.name`)
if err != nil {
return nil, err
}
@ -194,17 +204,7 @@ ORDER BY s.name`)
}
func (s *Store) GetStream(id int64) (Stream, error) {
row := s.DB.QueryRow(`
SELECT s.id, s.name, s.title, s.app, s.channel, s.mpd, s.key_kid_key, s.headers_json,
s.video_select, s.audio_select, s.enabled, s.rewriter, s.created_at, s.updated_at,
COALESCE(r.health,''), COALESCE(r.pid,0), COALESCE(r.play_path,''),
COALESCE(r.uptime_s,0), COALESCE(r.bitrate_mbps,0), COALESCE(r.playlist_age_s,0),
COALESCE(r.last_error,''), COALESCE(r.updated_at,''),
COALESCE(c.agent_id,''), COALESCE(c.expires_at,'')
FROM streams s
LEFT JOIN stream_runtime r ON r.stream_id = s.id
LEFT JOIN agent_claims c ON c.stream_id = s.id
WHERE s.id = ?`, id)
row := s.DB.QueryRow(streamSelect+` WHERE s.id = ?`, id)
return scanStream(row)
}
@ -217,7 +217,7 @@ func scanStream(row rowScanner) (Stream, error) {
var enabled int
err := row.Scan(
&st.ID, &st.Name, &st.Title, &st.App, &st.Channel, &st.MPD, &st.Key, &st.HeadersJSON,
&st.VideoSelect, &st.AudioSelect, &enabled, &st.Rewriter, &st.CreatedAt, &st.UpdatedAt,
&st.Proxy, &st.VideoSelect, &st.AudioSelect, &enabled, &st.Rewriter, &st.CreatedAt, &st.UpdatedAt,
&st.Health, &st.PID, &st.PlayPath, &st.UptimeS, &st.BitrateMbps, &st.PlaylistAgeS,
&st.LastError, &st.RuntimeAt, &st.ClaimedBy, &st.ClaimExp,
)
@ -264,9 +264,9 @@ func (s *Store) CreateStream(in CreateStream) (Stream, error) {
}
ts := now()
res, err := s.DB.Exec(`
INSERT INTO streams(name,title,app,channel,mpd,key_kid_key,headers_json,video_select,audio_select,enabled,rewriter,created_at,updated_at)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)`,
name, in.Title, in.App, in.Channel, in.MPD, in.Key, in.HeadersJSON,
INSERT INTO streams(name,title,app,channel,mpd,key_kid_key,headers_json,proxy,video_select,audio_select,enabled,rewriter,created_at,updated_at)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
name, in.Title, in.App, in.Channel, in.MPD, in.Key, in.HeadersJSON, strings.TrimSpace(in.Proxy),
in.VideoSelect, in.AudioSelect, enabled, in.Rewriter, ts, ts)
if err != nil {
return Stream{}, err
@ -303,6 +303,9 @@ func (s *Store) PatchStream(id int64, in PatchStream) (Stream, error) {
}
cur.HeadersJSON = *in.HeadersJSON
}
if in.Proxy != nil {
cur.Proxy = strings.TrimSpace(*in.Proxy)
}
if in.VideoSelect != nil {
cur.VideoSelect = *in.VideoSelect
}
@ -325,9 +328,9 @@ func (s *Store) PatchStream(id int64, in PatchStream) (Stream, error) {
}
ts := now()
_, err = s.DB.Exec(`
UPDATE streams SET title=?, app=?, channel=?, mpd=?, key_kid_key=?, headers_json=?,
UPDATE streams SET title=?, app=?, channel=?, mpd=?, key_kid_key=?, headers_json=?, proxy=?,
video_select=?, audio_select=?, enabled=?, rewriter=?, updated_at=? WHERE id=?`,
cur.Title, cur.App, cur.Channel, cur.MPD, cur.Key, cur.HeadersJSON,
cur.Title, cur.App, cur.Channel, cur.MPD, cur.Key, cur.HeadersJSON, cur.Proxy,
cur.VideoSelect, cur.AudioSelect, enabled, cur.Rewriter, ts, id)
if err != nil {
return Stream{}, err
@ -362,11 +365,13 @@ ON CONFLICT(stream_id) DO UPDATE SET health=excluded.health, play_path=excluded.
}
func (s *Store) SetCredentials(id int64, cred Credentials) (Stream, error) {
if strings.TrimSpace(cred.MPD) == "" || strings.TrimSpace(cred.Key) == "" {
return Stream{}, fmt.Errorf("mpd and key required")
mpd := strings.TrimSpace(cred.MPD)
key := strings.TrimSpace(cred.Key)
if mpd == "" {
return Stream{}, fmt.Errorf("mpd required")
}
_, err := s.DB.Exec(`UPDATE streams SET mpd=?, key_kid_key=?, updated_at=? WHERE id=?`,
strings.TrimSpace(cred.MPD), strings.TrimSpace(cred.Key), now(), id)
mpd, key, now(), id)
if err != nil {
return Stream{}, err
}

View file

@ -0,0 +1,153 @@
package deps
import (
"archive/tar"
"archive/zip"
"compress/gzip"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"strings"
)
// extractNamed finds a file whose base name matches wantName (case-insensitive
// on Windows) inside archivePath and writes it to destPath.
func extractNamed(archivePath, _ /*binDir*/, wantName, destPath string) error {
lower := strings.ToLower(archivePath)
switch {
case strings.HasSuffix(lower, ".zip"):
return extractZipNamed(archivePath, wantName, destPath)
case strings.HasSuffix(lower, ".tar.gz"), strings.HasSuffix(lower, ".tgz"):
return extractTarGZNamed(archivePath, wantName, destPath)
case strings.HasSuffix(lower, ".tar.xz"):
return extractTarXZNamed(archivePath, wantName, destPath)
default:
return fmt.Errorf("unsupported archive type: %s", archivePath)
}
}
func nameMatch(base, want string) bool {
return strings.EqualFold(filepath.Base(base), want)
}
func extractZipNamed(archivePath, wantName, destPath string) error {
r, err := zip.OpenReader(archivePath)
if err != nil {
return err
}
defer r.Close()
for _, f := range r.File {
if f.FileInfo().IsDir() {
continue
}
if !nameMatch(f.Name, wantName) {
continue
}
rc, err := f.Open()
if err != nil {
return err
}
err = writeFile(destPath, rc)
_ = rc.Close()
return err
}
return fmt.Errorf("%s not found in %s", wantName, filepath.Base(archivePath))
}
func extractTarGZNamed(archivePath, wantName, destPath string) error {
f, err := os.Open(archivePath)
if err != nil {
return err
}
defer f.Close()
gz, err := gzip.NewReader(f)
if err != nil {
return err
}
defer gz.Close()
return readTarNamed(gz, wantName, destPath, filepath.Base(archivePath))
}
// extractTarXZNamed shells out to tar when available (linux/mac; Git Bash on Windows).
func extractTarXZNamed(archivePath, wantName, destPath string) error {
tmp, err := os.MkdirTemp("", "ffmpeg-xz-*")
if err != nil {
return err
}
defer os.RemoveAll(tmp)
tarBin, err := exec.LookPath("tar")
if err != nil {
return fmt.Errorf("tar required to extract .tar.xz (install tar or place %s in bin/): %w", wantName, err)
}
cmd := exec.Command(tarBin, "-xJf", archivePath, "-C", tmp)
if out, err := cmd.CombinedOutput(); err != nil {
return fmt.Errorf("tar extract: %w (%s)", err, strings.TrimSpace(string(out)))
}
var found string
_ = filepath.Walk(tmp, func(path string, info os.FileInfo, err error) error {
if err != nil || info.IsDir() {
return nil
}
if nameMatch(path, wantName) {
found = path
return io.EOF
}
return nil
})
if found == "" {
return fmt.Errorf("%s not found in %s", wantName, filepath.Base(archivePath))
}
in, err := os.Open(found)
if err != nil {
return err
}
defer in.Close()
return writeFile(destPath, in)
}
func readTarNamed(r io.Reader, wantName, destPath, archiveBase string) error {
tr := tar.NewReader(r)
for {
hdr, err := tr.Next()
if err == io.EOF {
break
}
if err != nil {
return err
}
if hdr.Typeflag != tar.TypeReg {
continue
}
if !nameMatch(hdr.Name, wantName) {
continue
}
return writeFile(destPath, tr)
}
return fmt.Errorf("%s not found in %s", wantName, archiveBase)
}
func writeFile(dest string, r io.Reader) error {
if err := os.MkdirAll(filepath.Dir(dest), 0o755); err != nil {
return err
}
tmp := dest + ".partial"
f, err := os.OpenFile(tmp, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o755)
if err != nil {
return err
}
_, copyErr := io.Copy(f, r)
closeErr := f.Close()
if copyErr != nil {
_ = os.Remove(tmp)
return copyErr
}
if closeErr != nil {
_ = os.Remove(tmp)
return closeErr
}
_ = os.Remove(dest)
return os.Rename(tmp, dest)
}

View file

@ -0,0 +1,235 @@
// Package deps ensures media tools (ffmpeg, N_m3u8DL-RE, mp4decrypt) exist
// under bin/ next to the install, downloading static builds when missing.
package deps
import (
"fmt"
"io"
"log"
"net/http"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"time"
"drmdecryption/repo"
)
// Status is the resolved path for each tool after Ensure.
type Status struct {
BinDir string `json:"bin_dir"`
FFmpeg string `json:"ffmpeg"`
NRE string `json:"nre"`
MP4Decrypt string `json:"mp4decrypt"`
Notes []string `json:"notes,omitempty"`
}
// Options controls Ensure.
type Options struct {
// BinDir overrides where binaries are installed. Empty → <repo.Root()>/bin
// or the directory containing the running executable.
BinDir string
// SkipDownload only resolves existing paths (flags/env/bin/PATH).
SkipDownload bool
Log *log.Logger
}
func (o Options) logf(format string, args ...any) {
if o.Log != nil {
o.Log.Printf(format, args...)
} else {
log.Printf(format, args...)
}
}
// Ensure resolves ffmpeg, N_m3u8DL-RE and mp4decrypt, downloading into BinDir
// when missing (unless SkipDownload). Returns paths suitable for the supervisor.
func Ensure(o Options, preferNRE, preferFFmpeg, preferDecrypt string) (Status, error) {
st := Status{}
binDir := o.BinDir
if binDir == "" {
binDir = defaultBinDir()
}
if err := os.MkdirAll(binDir, 0o755); err != nil {
return st, err
}
st.BinDir = binDir
var notes []string
ff, err := resolveOrFetch(o, "ffmpeg", preferFFmpeg, binDir, ffmpegCandidates(binDir), fetchFFmpeg)
if err != nil {
notes = append(notes, "ffmpeg: "+err.Error())
o.logf("[!] deps: ffmpeg: %v", err)
} else {
st.FFmpeg = ff
o.logf("[+] deps: ffmpeg → %s", ff)
}
nre, err := resolveOrFetch(o, "N_m3u8DL-RE", preferNRE, binDir, nreCandidates(binDir), fetchNRE)
if err != nil {
notes = append(notes, "N_m3u8DL-RE: "+err.Error())
o.logf("[!] deps: N_m3u8DL-RE: %v", err)
} else {
st.NRE = nre
o.logf("[+] deps: N_m3u8DL-RE → %s", nre)
}
dec, err := resolveOrFetch(o, "mp4decrypt", preferDecrypt, binDir, decryptCandidates(binDir), fetchMP4Decrypt)
if err != nil {
notes = append(notes, "mp4decrypt: "+err.Error())
o.logf("[!] deps: mp4decrypt: %v", err)
} else {
st.MP4Decrypt = dec
o.logf("[+] deps: mp4decrypt → %s", dec)
}
st.Notes = notes
// Serve can start even if a tool is missing; stream start will fail clearly.
return st, nil
}
func defaultBinDir() string {
root := repo.Root()
if root != "" {
return filepath.Join(root, "bin")
}
exe, err := os.Executable()
if err != nil {
return "bin"
}
if resolved, err := filepath.EvalSymlinks(exe); err == nil {
exe = resolved
}
dir := filepath.Dir(exe)
if strings.EqualFold(filepath.Base(dir), "bin") {
return dir
}
return filepath.Join(dir, "bin")
}
type fetchFunc func(binDir string, logf func(string, ...any)) (string, error)
func resolveOrFetch(o Options, label, prefer, binDir string, candidates []string, fetch fetchFunc) (string, error) {
if p := firstExisting(prefer); p != "" {
return p, nil
}
for _, c := range candidates {
if p := firstExisting(c); p != "" {
return p, nil
}
}
if o.SkipDownload {
return "", fmt.Errorf("%s not found (auto-download disabled)", label)
}
o.logf("[*] deps: %s missing → downloading into %s …", label, binDir)
return fetch(binDir, o.logf)
}
func firstExisting(paths ...string) string {
for _, p := range paths {
p = strings.TrimSpace(p)
if p == "" {
continue
}
if filepath.IsAbs(p) || strings.ContainsAny(p, `/\`) {
if st, err := os.Stat(p); err == nil && !st.IsDir() {
return p
}
continue
}
if abs, err := exec.LookPath(p); err == nil {
return abs
}
}
return ""
}
func ffmpegCandidates(binDir string) []string {
name := "ffmpeg"
if runtime.GOOS == "windows" {
name = "ffmpeg.exe"
}
return []string{
os.Getenv("FFMPEG_PATH"),
os.Getenv("FFMPEG"),
filepath.Join(binDir, name),
name,
}
}
func nreCandidates(binDir string) []string {
names := []string{"N_m3u8DL-RE"}
if runtime.GOOS == "windows" {
names = []string{"N_m3u8DL-RE.exe", "N_m3u8DL-RE"}
}
out := []string{os.Getenv("NRE_PATH"), os.Getenv("N_M3U8DL_RE")}
for _, n := range names {
out = append(out, filepath.Join(binDir, n), n)
}
return out
}
func decryptCandidates(binDir string) []string {
name := "mp4decrypt"
if runtime.GOOS == "windows" {
name = "mp4decrypt.exe"
}
return []string{
os.Getenv("MP4DECRYPT_PATH"),
os.Getenv("MP4DECRYPT"),
filepath.Join(binDir, name),
name,
}
}
func httpGet(url string) (*http.Response, error) {
client := &http.Client{Timeout: 10 * time.Minute}
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return nil, err
}
req.Header.Set("User-Agent", "null-drm-streamd/1.0")
return client.Do(req)
}
func downloadTo(url, dest string, logf func(string, ...any)) error {
logf("[*] deps: GET %s", url)
resp, err := httpGet(url)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("download %s: HTTP %s", url, resp.Status)
}
tmp := dest + ".partial"
f, err := os.Create(tmp)
if err != nil {
return err
}
n, copyErr := io.Copy(f, resp.Body)
closeErr := f.Close()
if copyErr != nil {
_ = os.Remove(tmp)
return copyErr
}
if closeErr != nil {
_ = os.Remove(tmp)
return closeErr
}
if err := os.Rename(tmp, dest); err != nil {
_ = os.Remove(tmp)
return err
}
logf("[+] deps: saved %s (%d bytes)", dest, n)
return nil
}
func chmodX(path string) {
if runtime.GOOS == "windows" {
return
}
_ = os.Chmod(path, 0o755)
}

View file

@ -0,0 +1,64 @@
package deps
import (
"fmt"
"os"
"path/filepath"
"runtime"
)
// BtbN static GPL builds (linked from ffmpeg.org). No official BtbN macOS
// builds — on darwin we leave a clear note to use Homebrew.
func fetchFFmpeg(binDir string, logf func(string, ...any)) (string, error) {
url, archiveName, err := ffmpegURL()
if err != nil {
return "", err
}
archivePath := filepath.Join(binDir, archiveName)
if err := downloadTo(url, archivePath, logf); err != nil {
return "", err
}
defer func() { _ = os.Remove(archivePath) }()
want := "ffmpeg"
if runtime.GOOS == "windows" {
want = "ffmpeg.exe"
}
dest := filepath.Join(binDir, want)
if err := extractNamed(archivePath, binDir, want, dest); err != nil {
return "", err
}
chmodX(dest)
// Best-effort ffprobe alongside ffmpeg.
probeWant := "ffprobe"
if runtime.GOOS == "windows" {
probeWant = "ffprobe.exe"
}
probeDest := filepath.Join(binDir, probeWant)
_ = extractNamed(archivePath, binDir, probeWant, probeDest)
chmodX(probeDest)
return dest, nil
}
func ffmpegURL() (url, archiveName string, err error) {
switch runtime.GOOS + "/" + runtime.GOARCH {
case "windows/amd64":
return "https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/ffmpeg-master-latest-win64-gpl.zip",
"ffmpeg-win64-gpl.zip", nil
case "windows/arm64":
return "https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/ffmpeg-master-latest-winarm64-gpl.zip",
"ffmpeg-winarm64-gpl.zip", nil
case "linux/amd64":
return "https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/ffmpeg-master-latest-linux64-gpl.tar.xz",
"ffmpeg-linux64-gpl.tar.xz", nil
case "linux/arm64":
return "https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/ffmpeg-master-latest-linuxarm64-gpl.tar.xz",
"ffmpeg-linuxarm64-gpl.tar.xz", nil
case "darwin/amd64", "darwin/arm64":
return "", "", fmt.Errorf("no static ffmpeg auto-build for macOS; install with: brew install ffmpeg")
default:
return "", "", fmt.Errorf("unsupported platform %s/%s for ffmpeg auto-download", runtime.GOOS, runtime.GOARCH)
}
}

View file

@ -0,0 +1,50 @@
package deps
import (
"fmt"
"os"
"path/filepath"
"runtime"
)
// Official Bento4 SDK binaries from bento4.com (v1.6.0-641).
// linux/arm64 and windows/arm64 are not published there — clear error.
func fetchMP4Decrypt(binDir string, logf func(string, ...any)) (string, error) {
url, archiveName, err := bento4URL()
if err != nil {
return "", err
}
archivePath := filepath.Join(binDir, archiveName)
if err := downloadTo(url, archivePath, logf); err != nil {
return "", err
}
defer func() { _ = os.Remove(archivePath) }()
want := "mp4decrypt"
if runtime.GOOS == "windows" {
want = "mp4decrypt.exe"
}
dest := filepath.Join(binDir, want)
if err := extractNamed(archivePath, binDir, want, dest); err != nil {
return "", err
}
chmodX(dest)
return dest, nil
}
func bento4URL() (url, archiveName string, err error) {
const base = "https://www.bok.net/Bento4/binaries/"
switch runtime.GOOS + "/" + runtime.GOARCH {
case "windows/amd64":
name := "Bento4-SDK-1-6-0-641.x86_64-microsoft-win32.zip"
return base + name, name, nil
case "linux/amd64":
name := "Bento4-SDK-1-6-0-641.x86_64-unknown-linux.zip"
return base + name, name, nil
case "darwin/amd64", "darwin/arm64":
name := "Bento4-SDK-1-6-0-641.universal-apple-macosx.zip"
return base + name, name, nil
default:
return "", "", fmt.Errorf("no Bento4 binary for %s/%s (place mp4decrypt in bin/ manually)", runtime.GOOS, runtime.GOARCH)
}
}

View file

@ -0,0 +1,71 @@
package deps
import (
"fmt"
"os"
"path/filepath"
"runtime"
)
const nreTag = "v0.6.0-beta"
const nreBase = "https://github.com/nilaoda/N_m3u8DL-RE/releases/download/" + nreTag + "/"
func fetchNRE(binDir string, logf func(string, ...any)) (string, error) {
url, archiveName, binName, err := nreURL()
if err != nil {
return "", err
}
archivePath := filepath.Join(binDir, archiveName)
if err := downloadTo(url, archivePath, logf); err != nil {
return "", err
}
defer func() { _ = os.Remove(archivePath) }()
dest := filepath.Join(binDir, binName)
if err := extractNamed(archivePath, binDir, binName, dest); err != nil {
// Some archives nest the binary or use a slightly different name.
if err2 := extractNamed(archivePath, binDir, "N_m3u8DL-RE", dest); err2 != nil {
if runtime.GOOS == "windows" {
if err3 := extractNamed(archivePath, binDir, "N_m3u8DL-RE.exe", dest); err3 != nil {
return "", err
}
} else {
return "", err
}
}
}
chmodX(dest)
return dest, nil
}
func nreURL() (url, archiveName, binName string, err error) {
binName = "N_m3u8DL-RE"
if runtime.GOOS == "windows" {
binName = "N_m3u8DL-RE.exe"
}
switch runtime.GOOS + "/" + runtime.GOARCH {
case "windows/amd64":
name := "N_m3u8DL-RE_v0.6.0-beta_win-x64_20260629.zip"
return nreBase + name, name, binName, nil
case "windows/arm64":
name := "N_m3u8DL-RE_v0.6.0-beta_win-arm64_20260629.zip"
return nreBase + name, name, binName, nil
case "windows/386":
name := "N_m3u8DL-RE_v0.6.0-beta_win-NT6.0-x86_20260629.zip"
return nreBase + name, name, binName, nil
case "linux/amd64":
name := "N_m3u8DL-RE_v0.6.0-beta_linux-x64_20260629.tar.gz"
return nreBase + name, name, binName, nil
case "linux/arm64":
name := "N_m3u8DL-RE_v0.6.0-beta_linux-arm64_20260629.tar.gz"
return nreBase + name, name, binName, nil
case "darwin/amd64":
name := "N_m3u8DL-RE_v0.6.0-beta_osx-x64_20260629.tar.gz"
return nreBase + name, name, binName, nil
case "darwin/arm64":
name := "N_m3u8DL-RE_v0.6.0-beta_osx-arm64_20260629.tar.gz"
return nreBase + name, name, binName, nil
default:
return "", "", "", fmt.Errorf("unsupported platform %s/%s for N_m3u8DL-RE auto-download", runtime.GOOS, runtime.GOARCH)
}
}

View file

@ -101,13 +101,13 @@ func (m *Media) Start(id int64) error {
if err != nil {
return err
}
if strings.TrimSpace(st.MPD) == "" || strings.TrimSpace(st.Key) == "" {
if strings.TrimSpace(st.MPD) == "" {
_ = m.Store.SetRuntime(id, db.RuntimePatch{
Health: "down",
PlayPath: "/hls/" + st.Name + "/index.m3u8",
LastError: "missing mpd/key - capture required",
LastError: "missing mpd — paste a manifest URL (keys optional for clear streams)",
})
return fmt.Errorf("missing mpd/key")
return fmt.Errorf("missing mpd")
}
mpdURL := strings.TrimSpace(st.MPD)
if !strings.HasPrefix(strings.ToLower(mpdURL), "http://") && !strings.HasPrefix(strings.ToLower(mpdURL), "https://") {
@ -151,9 +151,12 @@ func (m *Media) Start(id int64) error {
}
keysFile := filepath.Join(workDir, "keys.txt")
keysBody := normalizeKeysFile(st.Key)
if err := os.WriteFile(keysFile, []byte(keysBody), 0o644); err != nil {
return err
hasKeys := strings.TrimSpace(st.Key) != ""
if hasKeys {
keysBody := normalizeKeysFile(st.Key)
if err := os.WriteFile(keysFile, []byte(keysBody), 0o644); err != nil {
return err
}
}
saveName := st.Name
@ -167,7 +170,7 @@ func (m *Media) Start(id int64) error {
// The rewriter is named by the stream row or its app module and looked up in
// the mpd registry, so streamd needs no knowledge of any provider.
if rw, needed := mpd.Lookup(cfg.Rewriter); needed && strings.TrimSpace(st.MPD) != "" && !cfg.IsHLS {
srv, err := mpd.StartLocal(st.MPD, st.Key, headers, rw)
srv, err := mpd.StartLocal(st.MPD, st.Key, headers, rw, st.Proxy)
if err != nil {
_ = m.Store.SetRuntime(id, db.RuntimePatch{
Health: "down", PlayPath: "/hls/" + st.Name + "/index.m3u8",
@ -189,12 +192,8 @@ func (m *Media) Start(id int64) error {
liveWait := strconv.Itoa(cfg.LiveWait)
nreArgs := []string{
manifestURL,
// Multi-KID SAMPLE-AES streams rainbow-decrypt with a single --key, so
// always feed every KID:KEY via --key-text-file.
"--key-text-file", keysFile,
"--live-real-time-merge",
"--live-pipe-mux",
"--mp4-real-time-decryption",
"--live-wait-time", liveWait,
"--ffmpeg-binary-path", m.FFmpeg,
"--save-name", saveName,
@ -204,6 +203,19 @@ func (m *Media) Start(id int64) error {
"--log-level", "ERROR",
"-ss", "0",
}
if hasKeys {
// Multi-KID SAMPLE-AES streams rainbow-decrypt with a single --key, so
// always feed every KID:KEY via --key-text-file.
nreArgs = append(nreArgs,
"--key-text-file", keysFile,
"--mp4-real-time-decryption",
)
}
if proxy := strings.TrimSpace(st.Proxy); proxy != "" {
// NRE prefers --custom-proxy over the system proxy when both are set.
nreArgs = append(nreArgs, "--custom-proxy", proxy)
m.logf("stream %s: origin proxy %s", st.Name, proxy)
}
// A synthetic manifest publishes exactly one video + audio pair, and an HLS
// master's variants rarely match a resolution/language filter, so in both
// cases take the best rendition instead of the configured selectors.
@ -212,7 +224,7 @@ func (m *Media) Start(id int64) error {
} else {
nreArgs = append(nreArgs, "-sv", cfg.VideoSelect, "-sa", cfg.AudioSelect)
}
if m.MP4Decrypt != "" {
if hasKeys && m.MP4Decrypt != "" {
nreArgs = append(nreArgs,
"--decryption-engine", "MP4DECRYPT",
"--decryption-binary-path", m.MP4Decrypt,

View file

@ -27,13 +27,13 @@ func (s *Stub) Start(id int64) error {
if err != nil {
return err
}
if st.MPD == "" || st.Key == "" {
if st.MPD == "" {
_, err = s.Store.DB.Exec(`
INSERT INTO stream_runtime(stream_id,health,play_path,last_error,updated_at)
VALUES(?,?,?,?,?)
ON CONFLICT(stream_id) DO UPDATE SET health=excluded.health, last_error=excluded.last_error, updated_at=excluded.updated_at`,
id, "down", "/hls/"+st.Name+"/index.m3u8", "missing mpd/key - capture required", time.Now().UTC().Format(time.RFC3339))
return err
id, "down", "/hls/"+st.Name+"/index.m3u8", "missing mpd", time.Now().UTC().Format(time.RFC3339))
return fmt.Errorf("missing mpd")
}
pid := 10000 + int(id)
s.pids[id] = pid

View file

@ -63,7 +63,7 @@
}
listMsg.textContent = streams.length + " stream(s)";
rowsEl.innerHTML = streams.map((s) => {
const need = !s.mpd || !s.key ? " needs capture" : "";
const need = !s.mpd ? " needs MPD" : "";
return `<tr>
<td><strong>${esc(s.name)}</strong><div class="muted">${esc(s.title || "")}${need}</div></td>
<td>${esc(s.app)} / ${esc(s.channel)}</td>
@ -98,6 +98,25 @@
agentsEl.textContent = "agents: " + list.map((a) => a.agent_id).join(", ");
}
const depsEl = document.getElementById("deps-status");
function renderDeps(d) {
if (!depsEl || !d) return;
const bit = (label, path) => (path ? label + "✓" : label + "✗");
depsEl.textContent = [
bit("ffmpeg", d.ffmpeg),
bit("nre", d.nre),
bit("mp4decrypt", d.mp4decrypt),
].join(" · ");
depsEl.title = [
"bin: " + (d.bin_dir || ""),
"ffmpeg: " + (d.ffmpeg || "(missing)"),
"nre: " + (d.nre || "(missing)"),
"mp4decrypt: " + (d.mp4decrypt || "(missing)"),
...(d.notes || []),
].join("\n");
}
async function refresh() {
try {
const [health, list, agents] = await Promise.all([
@ -106,6 +125,7 @@
api("/api/agents").catch(() => ({ agents: [] })),
]);
uptimeEl.textContent = "up " + Math.floor(health.uptime_s || 0) + "s";
renderDeps(health.deps);
render(list.streams || []);
renderAgents(agents.agents || []);
listMsg.classList.remove("err");
@ -212,6 +232,7 @@
editForm.channel.value = st.channel || "";
editForm.mpd.value = st.mpd || "";
editForm.key.value = st.key || "";
if (editForm.proxy) editForm.proxy.value = st.proxy || "";
editForm.headers_json.value = st.headers_json || "{}";
dlg.showModal();
return;
@ -238,6 +259,7 @@
channel: editForm.channel.value,
mpd: editForm.mpd.value,
key: editForm.key.value,
proxy: editForm.proxy ? editForm.proxy.value : "",
headers_json: editForm.headers_json.value,
};
try {

View file

@ -11,6 +11,7 @@
<h1>streamd</h1>
<div class="header-right">
<span id="uptime" class="muted"></span>
<span id="deps-status" class="muted" title="Media tool paths"></span>
<label class="token-box">token <input id="token" type="password" placeholder="STREAMD_TOKEN" autocomplete="off" /></label>
</div>
</header>
@ -26,8 +27,9 @@
<label>channel
<select name="channel" id="channel-select"></select>
</label>
<label class="span2">mpd <input name="mpd" placeholder="https://…/manifest.mpd (optional until capture)" /></label>
<label class="span2">key <textarea name="key" rows="4" placeholder="KID:KEY (one per line; multi-key streams need every key)" spellcheck="false"></textarea></label>
<label class="span2">mpd <input name="mpd" placeholder="https://…/manifest.mpd (required to start)" /></label>
<label class="span2">key <textarea name="key" rows="3" placeholder="optional — KID:KEY lines (clear streams like BBC need no keys)" spellcheck="false"></textarea></label>
<label class="span2">proxy <input name="proxy" placeholder="optional — socks5://127.0.0.1:1080 or http://127.0.0.1:8080 (origin fetch)" /></label>
<label class="span2">headers JSON <input name="headers_json" value="{}" /></label>
<div class="span2 actions">
<button type="submit">Create</button>
@ -70,7 +72,8 @@
<label>title <input name="title" /></label>
<label>channel <input name="channel" /></label>
<label class="span2">mpd <input name="mpd" /></label>
<label class="span2">key <textarea name="key" rows="4" placeholder="KID:KEY (one per line)" spellcheck="false"></textarea></label>
<label class="span2">key <textarea name="key" rows="3" placeholder="optional — KID:KEY (one per line)" spellcheck="false"></textarea></label>
<label class="span2">proxy <input name="proxy" placeholder="socks5://127.0.0.1:1080" /></label>
<label class="span2">headers JSON <input name="headers_json" /></label>
<div class="span2 actions">
<button type="submit" value="save">Save</button>

View file

@ -17,6 +17,7 @@ import (
"drmdecryption/apps/streamd/internal/api"
"drmdecryption/apps/streamd/internal/db"
"drmdecryption/apps/streamd/internal/deps"
"drmdecryption/apps/streamd/internal/supervisor"
"drmdecryption/apps/streamd/internal/ui"
"drmdecryption/apps/streamd/internal/ws"
@ -54,9 +55,11 @@ serve flags:
--bind listen address (default 0.0.0.0:8083)
--data data dir for sqlite + www + work (default .cache/streamd)
--token shared bearer token for mutating API (or STREAMD_TOKEN)
--nre path to N_m3u8DL-RE (else NRE_PATH, bin/, PATH)
--ffmpeg path to ffmpeg (else FFMPEG_PATH, bin/, PATH)
--mp4decrypt path to mp4decrypt (else MP4DECRYPT_PATH, bin/, PATH)
--nre path to N_m3u8DL-RE (else NRE_PATH, bin/, PATH, auto-download)
--ffmpeg path to ffmpeg (else FFMPEG_PATH, bin/, PATH, auto-download)
--mp4decrypt path to mp4decrypt (else MP4DECRYPT_PATH, bin/, PATH, auto-download)
--bin-dir where to install/look for media tools (default <repo>/bin)
--skip-deps do not auto-download missing ffmpeg / N_m3u8DL-RE / mp4decrypt
`)
}
@ -68,6 +71,8 @@ func serveCmd(args []string) {
nre := fs.String("nre", "", "N_m3u8DL-RE binary")
ffmpeg := fs.String("ffmpeg", "", "ffmpeg binary")
mp4decrypt := fs.String("mp4decrypt", "", "mp4decrypt binary")
binDir := fs.String("bin-dir", "", "directory for media tool binaries (default <repo>/bin)")
skipDeps := fs.Bool("skip-deps", false, "skip auto-download of missing media tools")
_ = fs.Parse(args)
dataDir := *data
@ -91,24 +96,14 @@ func serveCmd(args []string) {
}
defer store.Close()
nrePath := firstExisting(*nre,
os.Getenv("NRE_PATH"),
os.Getenv("N_M3U8DL_RE"),
filepath.Join("bin", "N_m3u8DL-RE.exe"),
"N_m3u8DL-RE",
)
ffPath := firstExisting(*ffmpeg,
os.Getenv("FFMPEG_PATH"),
os.Getenv("FFMPEG"),
filepath.Join("bin", "ffmpeg.exe"),
"ffmpeg",
)
decPath := firstExisting(*mp4decrypt,
os.Getenv("MP4DECRYPT_PATH"),
os.Getenv("MP4DECRYPT"),
filepath.Join("bin", "mp4decrypt.exe"),
"mp4decrypt",
)
depStatus, _ := deps.Ensure(deps.Options{
BinDir: *binDir,
SkipDownload: *skipDeps,
Log: log.Default(),
}, *nre, *ffmpeg, *mp4decrypt)
nrePath := depStatus.NRE
ffPath := depStatus.FFmpeg
decPath := depStatus.MP4Decrypt
sup := supervisor.NewMedia(supervisor.Options{
Store: store,
@ -125,6 +120,7 @@ func serveCmd(args []string) {
Token: tok,
Supervisor: sup,
StartedAt: time.Now(),
Deps: depStatus,
}
hub := ws.NewHub(store, tok, log.Default())
@ -161,7 +157,7 @@ func serveCmd(args []string) {
return
}
for _, st := range list {
if !st.Enabled || strings.TrimSpace(st.MPD) == "" || strings.TrimSpace(st.Key) == "" {
if !st.Enabled || strings.TrimSpace(st.MPD) == "" {
continue
}
mpd := strings.ToLower(strings.TrimSpace(st.MPD))