streamd: preview quality picker, dashboard polish, C4 wrap keys
All checks were successful
release / build-and-upload (push) Successful in 6m18s
modules-release / build-and-upload (push) Successful in 5m18s

- Preview player can select FHD/HD/SD (or ABR master) from publish links
- Embed dashboard screenshots in README; Linux streamd+agent setup guide
- C4 Widevine wrap license mode + require --wvd; prefer Widevine PSSH
- Channel 4 and My5 modules; streamd auth, variants, schedules, HLS gate
This commit is contained in:
404errordeveloper 2026-10-09 20:57:43 +02:00
parent b3955bd81e
commit 066e018749
113 changed files with 19002 additions and 1541 deletions

View file

@ -219,6 +219,8 @@ type Node struct {
Class string
ResourceID string
Clickable bool
Selected bool
Checked bool
X1, Y1 int
X2, Y2 int
}
@ -260,6 +262,8 @@ func parseNodes(xml string) []Node {
Class: attr("class"),
ResourceID: attr("resource-id"),
Clickable: attr("clickable") == "true",
Selected: attr("selected") == "true",
Checked: attr("checked") == "true",
X1: x1, Y1: y1, X2: x2, Y2: y2,
})
}

View file

@ -89,6 +89,19 @@ type MitmHostList interface {
MitmHosts() []string
}
// ChannelCaptureHints lets a module bias Wait scoring for a specific channel
// (e.g. prefer channel(e4) MPD when capturing E4 while neighbours prefetch).
type ChannelCaptureHints interface {
CaptureHintsFor(channel string) capture.Hints
}
// RequireWVD is implemented by apps that refuse MPD-only captures. When true,
// `drm capture --app …` must pass --wvd; phonecap will not soft-save a session
// without keys.
type RequireWVD interface {
RequireWVD() bool
}
var (
mu sync.RWMutex
registry = map[string]func() (App, error){}

View file

@ -24,6 +24,9 @@ type Hints struct {
// Score ranks candidate manifest URLs. Zero value falls back to
// DefaultScoreCfg, which has no provider hosts.
Score ScoreCfg
// PreferURLContains boosts MPDs whose URL contains any of these substrings
// (e.g. channel(e4) for Channel 4 Live). Used when an app prefetches neighbours.
PreferURLContains []string
}
// RemoteCapPaths are the on-device locations the MITM may persist its capture
@ -59,10 +62,23 @@ func DefaultPassiveHints() Hints {
// score applies the hints' URL scoring, defaulting when unset.
func (h Hints) score(u string) int {
var sc int
if len(h.Score.Deny) == 0 && len(h.Score.Hosts) == 0 {
return DefaultScoreCfg().Score(u)
sc = DefaultScoreCfg().Score(u)
} else {
sc = h.Score.Score(u)
}
return h.Score.Score(u)
if sc <= 0 || len(h.PreferURLContains) == 0 {
return sc
}
low := strings.ToLower(u)
for _, p := range h.PreferURLContains {
p = strings.ToLower(strings.TrimSpace(p))
if p != "" && strings.Contains(low, p) {
return sc + 1000
}
}
return sc
}
// Data is the merged capture payload before key fetch.
@ -70,6 +86,25 @@ type Data map[string]string
func (d Data) Get(k string) string { return d[k] }
// preferSatisfied is true when no PreferURLContains is set, or the chosen MPD
// matches one of the preferred substrings.
func preferSatisfied(cap Data, hints Hints) bool {
if len(hints.PreferURLContains) == 0 {
return true
}
mpd := strings.ToLower(strings.TrimSpace(cap["mpd"]))
if mpd == "" {
return false
}
for _, p := range hints.PreferURLContains {
p = strings.ToLower(strings.TrimSpace(p))
if p != "" && strings.Contains(mpd, p) {
return true
}
}
return false
}
// Wait pulls device JSON + local mirrored log until required fields exist.
func Wait(c *adb.Client, hints Hints, localLog string, localCap string, timeout time.Duration) (Data, error) {
deadline := time.Now().Add(timeout)
@ -104,7 +139,7 @@ func Wait(c *adb.Client, hints Hints, localLog string, localCap string, timeout
enrichFromProxyLog(cap, logText, hints)
if hints.BestEffort {
if hasUseful(cap, hints) {
if hasUseful(cap, hints) && preferSatisfied(cap, hints) {
_ = os.WriteFile(localCap, mustJSON(cap), 0o644)
return cap, nil
}
@ -116,7 +151,7 @@ func Wait(c *adb.Client, hints Hints, localLog string, localCap string, timeout
break
}
}
if !missing {
if !missing && preferSatisfied(cap, hints) {
_ = os.WriteFile(localCap, mustJSON(cap), 0o644)
return cap, nil
}
@ -125,7 +160,7 @@ func Wait(c *adb.Client, hints Hints, localLog string, localCap string, timeout
have := []string{}
keys := hints.Require
if hints.BestEffort {
keys = []string{"mpd", "license_url", "pssh", "auth", "pid"}
keys = []string{"mpd", "license_url", "pssh", "auth", "pid", "license_body"}
}
for _, k := range keys {
if cap[k] != "" {
@ -225,7 +260,8 @@ func enrichFromProxyLog(cap Data, logText string, hints Hints) {
if sc <= 0 {
return
}
if sc > bestScore {
// Prefer higher score; on a tie keep the later URL (last stream played).
if sc > bestScore || (sc == bestScore && sc > 0) {
bestScore = sc
bestMPD = u
}

View file

@ -22,13 +22,16 @@ type Describe struct {
KeyMode string `json:"key_mode"`
ProxyBin string `json:"proxy_bin,omitempty"`
CAHash string `json:"ca_hash,omitempty"`
TransparentMITM bool `json:"transparent_mitm"`
MitmHosts []string `json:"mitm_hosts,omitempty"`
Rewriter string `json:"rewriter,omitempty"`
Channels []Channel `json:"channels"`
Require []string `json:"require,omitempty"`
Score capture.ScoreCfg `json:"score,omitempty"`
HasCatalog bool `json:"has_catalog"`
ValuesPath string `json:"values_path,omitempty"`
ValuesLoaded bool `json:"values_loaded"`
TransparentMITM bool `json:"transparent_mitm"`
MitmHosts []string `json:"mitm_hosts,omitempty"`
Rewriter string `json:"rewriter,omitempty"`
Channels []Channel `json:"channels"`
Require []string `json:"require,omitempty"`
Score capture.ScoreCfg `json:"score,omitempty"`
// ChannelMPDPrefer maps channel id → URL substrings that must win Wait scoring.
ChannelMPDPrefer map[string][]string `json:"channel_mpd_prefer,omitempty"`
HasCatalog bool `json:"has_catalog"`
RequireWVD bool `json:"require_wvd,omitempty"`
ValuesPath string `json:"values_path,omitempty"`
ValuesLoaded bool `json:"values_loaded"`
}

View file

@ -82,6 +82,8 @@ func (r *RemoteApp) MPDRewriter() mpd.Rewriter {
func (r *RemoteApp) UseTransparentMITM() bool { return r.Desc.TransparentMITM }
func (r *RemoteApp) RequireWVD() bool { return r.Desc.RequireWVD }
func (r *RemoteApp) MitmHosts() []string {
out := make([]string, 0, len(r.Desc.MitmHosts))
for _, h := range r.Desc.MitmHosts {
@ -93,6 +95,28 @@ func (r *RemoteApp) MitmHosts() []string {
return out
}
func (r *RemoteApp) CaptureHintsFor(channel string) capture.Hints {
h := r.CaptureHints()
if len(r.Desc.ChannelMPDPrefer) == 0 {
return h
}
id := strings.ToLower(strings.TrimSpace(channel))
if prefs, ok := r.Desc.ChannelMPDPrefer[id]; ok && len(prefs) > 0 {
h.PreferURLContains = append([]string{}, prefs...)
return h
}
// Alias / label fallback: match prefer keys against known channel ids only.
for _, ch := range r.Desc.Channels {
if strings.EqualFold(ch.ID, id) || strings.EqualFold(ch.Label, id) {
if prefs, ok := r.Desc.ChannelMPDPrefer[ch.ID]; ok && len(prefs) > 0 {
h.PreferURLContains = append([]string{}, prefs...)
}
break
}
}
return h
}
func (r *RemoteApp) RewriterName() string {
if r.Desc.Rewriter == "" {
return "none"
@ -126,11 +150,13 @@ func (r *RemoteApp) ValuesPath() string {
// Ensure RemoteApp satisfies the interfaces capture / catalog use.
var (
_ app.App = (*RemoteApp)(nil)
_ app.TransparentMITM = (*RemoteApp)(nil)
_ app.MitmHostList = (*RemoteApp)(nil)
_ app.StreamDefaults = (*RemoteApp)(nil)
_ app.Catalog = (*RemoteApp)(nil)
_ app.App = (*RemoteApp)(nil)
_ app.TransparentMITM = (*RemoteApp)(nil)
_ app.RequireWVD = (*RemoteApp)(nil)
_ app.MitmHostList = (*RemoteApp)(nil)
_ app.ChannelCaptureHints = (*RemoteApp)(nil)
_ app.StreamDefaults = (*RemoteApp)(nil)
_ app.Catalog = (*RemoteApp)(nil)
)
func (r *RemoteApp) VideoSelect() string { return "" }

View file

@ -199,6 +199,9 @@ func Run(opt Options) (res Result, err error) {
proxyBin, caHash := resolveProxy(a, root)
hints := a.CaptureHints()
if chHints, ok := a.(app.ChannelCaptureHints); ok && strings.TrimSpace(opt.Channel) != "" {
hints = chHints.CaptureHintsFor(opt.Channel)
}
useTProxy := false
if tm, ok := a.(app.TransparentMITM); ok && tm.UseTransparentMITM() {
useTProxy = true
@ -253,6 +256,9 @@ func Run(opt Options) (res Result, err error) {
}
localLog := filepath.Join(root, ".cache", "appproxy-"+sanitize(serialTag)+".log")
localCap := filepath.Join(root, ".cache", "appproxy-"+sanitize(serialTag)+"_cap.json")
// Fresh local mirrors each run so grab-all does not reuse a prior channel's MPD.
_ = os.WriteFile(localLog, nil, 0o644)
_ = os.Remove(localCap)
stop := make(chan struct{})
go capture.MirrorLogLoop(c, hints.RemoteLog, localLog, stop)
defer close(stop)
@ -273,13 +279,28 @@ func Run(opt Options) (res Result, err error) {
keyMode = strings.ToLower(strings.TrimSpace(a.KeyMode()))
}
// Brightcove/HLS: proxy often captures license + master URL but not PSSH.
// C4 MPDs list PlayReady before Widevine — replace a PlayReady blob.
// Skip for clear/MPD-only apps (KeyMode none).
if keyMode != "none" && keyMode != "clear" {
if strings.TrimSpace(capData.Get("pssh")) == "" && strings.TrimSpace(capData.Get("mpd")) != "" {
if pssh, err := extractHLSPSSH(capData.Get("mpd")); err == nil && pssh != "" {
capData["pssh"] = pssh
} else if err != nil {
fmt.Fprintf(os.Stderr, "[!] HLS PSSH extract: %v\n", err)
mpdForPSSH := strings.TrimSpace(capData.Get("mpd"))
curPSSH := strings.TrimSpace(capData.Get("pssh"))
needPSSH := curPSSH == "" || isPlayReadyPSSH(curPSSH)
if needPSSH && mpdForPSSH != "" {
if strings.Contains(strings.ToLower(mpdForPSSH), ".mpd") {
if pssh, err := extractWidevinePSSHFromMPD(mpdForPSSH); err == nil && pssh != "" {
if curPSSH != "" && curPSSH != pssh {
fmt.Println("[*] Replaced PlayReady/non-Widevine PSSH with Widevine from MPD")
}
capData["pssh"] = pssh
} else if err != nil && curPSSH == "" {
fmt.Fprintf(os.Stderr, "[!] MPD Widevine PSSH extract: %v\n", err)
}
} else if curPSSH == "" {
if pssh, err := extractHLSPSSH(mpdForPSSH); err == nil && pssh != "" {
capData["pssh"] = pssh
} else if err != nil {
fmt.Fprintf(os.Stderr, "[!] HLS PSSH extract: %v\n", err)
}
}
}
}
@ -296,7 +317,7 @@ func Run(opt Options) (res Result, err error) {
fmt.Println("=========================")
fmt.Println()
fmt.Println("[+] Capture:")
for _, k := range []string{"pid", "mpd", "license_url", "auth", "pssh"} {
for _, k := range []string{"pid", "mpd", "license_url", "auth", "pssh", "license_body"} {
v := capData.Get(k)
if k == "license_url" {
v = first(v, licenseURL)
@ -305,8 +326,12 @@ func Run(opt Options) (res Result, err error) {
continue
}
label := k
if k == "license_url" {
switch k {
case "license_url":
label = "license"
case "license_body":
label = "license_body"
v = trim(v, 80) + fmt.Sprintf(" (%d bytes)", len(capData.Get("license_body")))
}
fmt.Println(" ", label+":", trim(v, 120))
}
@ -318,19 +343,31 @@ func Run(opt Options) (res Result, err error) {
var kerr error
key, kerr = fetchKey(opt, root, capData, licenseURL)
if kerr != nil {
return res, kerr
// Allow MPD-only sessions when no .wvd was passed (grab-all / first pass),
// unless the app requires keys (e.g. c4).
softOK := strings.Contains(kerr.Error(), "requires --wvd")
if softOK {
if rw, ok := a.(app.RequireWVD); ok && rw.RequireWVD() {
return res, kerr
}
fmt.Fprintf(os.Stderr, "[!] %v — saving MPD-only session\n", kerr)
} else {
return res, kerr
}
} else {
fmt.Println("[+] key:", strings.ReplaceAll(key, "\n", " | "))
}
fmt.Println("[+] key:", strings.ReplaceAll(key, "\n", " | "))
}
sess := session.Session{
Channel: opt.Channel,
PSSH: capData.Get("pssh"),
Auth: capData.Get("auth"),
PID: capData.Get("pid"),
Key: key,
MPD: mpdURL,
LicenseURL: licenseURL,
Channel: opt.Channel,
PSSH: capData.Get("pssh"),
Auth: capData.Get("auth"),
PID: capData.Get("pid"),
Key: key,
MPD: mpdURL,
LicenseURL: licenseURL,
LicenseBody: capData.Get("license_body"),
}
path, err := session.Write(root, a.Name(), sess)
if err != nil {
@ -393,6 +430,7 @@ func fetchKey(opt Options, root string, cap capture.Data, licenseURL string) (st
PID: cap.Get("pid"),
LicenseURL: licenseURL,
UserAgent: opt.UserAgent,
WrapJSON: cap.Get("license_body"),
}
mode := strings.ToLower(strings.TrimSpace(opt.KeyMode))
if mode == "" || mode == "auto" {
@ -403,6 +441,11 @@ func fetchKey(opt Options, root string, cap capture.Data, licenseURL string) (st
}
}
}
// RedBee / wrapped JSON: if the phone posted a license body, prefer wrap
// even when the module still says raw (migration safety).
if mode == "raw" && strings.TrimSpace(wopt.WrapJSON) != "" {
mode = "wrap"
}
switch mode {
case "raw":
// Brightcove returns multiple CONTENT keys; NRE needs all of them.
@ -411,6 +454,12 @@ func fetchKey(opt Options, root string, cap capture.Data, licenseURL string) (st
return "", err
}
return strings.Join(keys, "\n"), nil
case "wrap":
keys, err := wvkey.FetchWrapAll(wopt)
if err != nil {
return "", err
}
return strings.Join(keys, "\n"), nil
default:
return wvkey.Fetch(wopt)
}
@ -453,6 +502,62 @@ func extractHLSPSSH(masterURL string) (string, error) {
return "", fmt.Errorf("no Widevine PSSH in HLS master")
}
// PlayReady system id fragment inside a base64 PSSH box.
const playReadyPSSHFrag = "AAAAAmgTweZhAQoarkuZb4IhflQ"
// Widevine system id fragment inside a base64 PSSH box.
const widevinePSSHFrag = "AAAAA7e+LqXnWSs6jyCfc1R0h7Q"
func isPlayReadyPSSH(b64 string) bool {
return strings.Contains(b64, playReadyPSSHFrag) && !strings.Contains(b64, widevinePSSHFrag)
}
func extractWidevinePSSHFromMPD(mpdURL string) (string, error) {
resp, err := http.Get(mpdURL)
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return "", fmt.Errorf("HTTP %d", resp.StatusCode)
}
body, err := io.ReadAll(io.LimitReader(resp.Body, 4<<20))
if err != nil {
return "", err
}
mpd := string(body)
lower := strings.ToLower(mpd)
const (
wvUUID = "edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"
openTag = "<cenc:pssh"
closeTag = "</cenc:pssh>"
)
searchFrom := 0
for {
i := strings.Index(lower[searchFrom:], openTag)
if i < 0 {
break
}
i += searchFrom
j := strings.Index(mpd[i:], ">")
k := strings.Index(lower[i:], closeTag)
if j < 0 || k < 0 || k <= j {
break
}
val := strings.TrimSpace(mpd[i+j+1 : i+k])
windowStart := i - 400
if windowStart < 0 {
windowStart = 0
}
window := lower[windowStart : i+j]
if strings.Contains(window, wvUUID) || strings.Contains(val, widevinePSSHFrag) {
return val, nil
}
searchFrom = i + k + len(closeTag)
}
return "", fmt.Errorf("no Widevine cenc:pssh in MPD")
}
func trim(s string, n int) string {
if len(s) <= n {
return s

View file

@ -22,6 +22,9 @@ type Session struct {
KeyHex string `json:"key_hex,omitempty"`
MPD string `json:"mpd,omitempty"`
LicenseURL string `json:"license_url,omitempty"`
// LicenseBody is the phone's JSON license POST (RedBee wrap). Used to
// re-issue with a local CDM challenge.
LicenseBody string `json:"license_body,omitempty"`
}
// Write creates outputs/<app>/<stamp>/session.json (+ field txt files + latest).
@ -51,11 +54,12 @@ func Write(root, app string, s Session) (string, error) {
return "", err
}
fields := map[string]string{
"pssh": s.PSSH,
"auth": s.Auth,
"pid": s.PID,
"key": s.Key,
"mpd": s.MPD,
"pssh": s.PSSH,
"auth": s.Auth,
"pid": s.PID,
"key": s.Key,
"mpd": s.MPD,
"license_body": s.LicenseBody,
}
for name, val := range fields {
if val == "" {

View file

@ -19,11 +19,13 @@ type Options struct {
PID string
LicenseURL string
UserAgent string
// WrapJSON is a captured phone license POST body (RedBee / wrapped Widevine).
WrapJSON string
}
// Fetch runs wvkey.py --quiet (ModularDrm) and returns the first KID:KEY line.
func Fetch(opt Options) (string, error) {
lines, err := run(opt, false, false)
lines, err := run(opt, "modulardrm", false)
if err != nil {
return "", err
}
@ -35,7 +37,7 @@ func Fetch(opt Options) (string, error) {
// FetchRaw runs wvkey.py --mode raw (Brightcove / octet-stream license).
func FetchRaw(opt Options) (string, error) {
lines, err := run(opt, true, false)
lines, err := run(opt, "raw", false)
if err != nil {
return "", err
}
@ -47,10 +49,15 @@ func FetchRaw(opt Options) (string, error) {
// FetchRawAll returns every CONTENT key from a raw license response.
func FetchRawAll(opt Options) ([]string, error) {
return run(opt, true, true)
return run(opt, "raw", true)
}
func run(opt Options, raw, all bool) ([]string, error) {
// FetchWrapAll re-POSTs a captured JSON license body with a local CDM challenge.
func FetchWrapAll(opt Options) ([]string, error) {
return run(opt, "wrap", true)
}
func run(opt Options, mode string, all bool) ([]string, error) {
py := opt.Python
if py == "" {
py = findPython()
@ -73,12 +80,19 @@ func run(opt Options, raw, all bool) ([]string, error) {
"--wvd", opt.WVD,
"--pssh", opt.PSSH,
"--license-url", opt.LicenseURL,
"--mode", mode,
"--quiet",
}
if raw {
args = append(args, "--mode", "raw")
} else {
args = append(args, "--mode", "modulardrm", "--auth", opt.Auth, "--pid", opt.PID)
switch mode {
case "raw":
// no extra fields
case "wrap":
if strings.TrimSpace(opt.WrapJSON) == "" {
return nil, fmt.Errorf("wvkey wrap mode requires a captured license_body from the phone (playback must start so RedBee gets a token)")
}
args = append(args, "--wrap-json", opt.WrapJSON)
default:
args = append(args, "--auth", opt.Auth, "--pid", opt.PID)
}
if all {
args = append(args, "--all")