1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
package main

import (
	"net/url"
	"regexp"
	"strconv"
	"strings"
)

// Video height from a CDN URL. Every table here was verified with ffprobe (or
// by reading an upstream HLS master) against real URLs from the film list;
// see mediathek(7), "QUALITY LABELS". The label NewPipe shows is
// min(width,height)+"p", which is what "height" means throughout: it keeps
// vertical and square video from being labelled 1920p.
//
// Rules are tried in order; the first that matches wins. Order matters where
// URLs carry several numbers (NDR's "TV-20231014-1736-5900.hd.mp4": the
// -5900 is an ID, the ".hd" is the quality).

var (
	reZDF       = regexp.MustCompile(`_\d+k_p(\d+)v\d+\.mp4$`)
	reTagesWeb  = regexp.MustCompile(`\.web(s|m|ml|l|xl|xxl)\.h264\.mp4$`)
	reAVC       = regexp.MustCompile(`(?i)[._\-]avc-?(\d{3,4})\.mp4$`)
	reDotNum    = regexp.MustCompile(`(?i)\.(\d{3,4})\.mp4$`)
	reFunkMP4   = regexp.MustCompile(`/(\d{1,2})-[A-Za-z0-9]{20}\.mp4$`)
	reRBBk      = regexp.MustCompile(`_hd(?:1080)?-(\d+)k\.mp4$`)
	reWxH       = regexp.MustCompile(`(?:^|[^0-9])(\d{3,4})x(\d{3,4})(?:[^0-9]|$)`)
	reDotSuffix = regexp.MustCompile(`\.([a-z0-9]+)\.mp4$`)
	reLetter    = regexp.MustCompile(`_([A-Z0-9]{1,2})\.mp4$`)
	reNp        = regexp.MustCompile(`_(\d{3,4})p\.mp4$`)
	reDaserste  = regexp.MustCompile(`/(\d{3,4})-1(?:_\d+)?\.mp4$`)
	reArte      = regexp.MustCompile(`_MP4-(\d+)_`)

	reORFChunk = regexp.MustCompile(`/chunklist_b(\d+)\.m3u8$`)
	reFunk     = regexp.MustCompile(`-video=(\d+)\.m3u8$`)
	reCsmil    = regexp.MustCompile(`/([^/]*)\.mp4\.csmil/index-f(\d+)-v1-a1\.m3u8$`)
)

var zdfCodes = map[string]int{
	"7": 176, "9": 272, "11": 360, "13": 540, "14": 576, "15": 720,
	"20": 272, "34": 576, "35": 576, "36": 720, "37": 1080, "61": 1080,
	"111": 360, "115": 720, "211": 360, "215": 720,
}

// ARD size suffixes (SWR, ard-mcdn.de, avod.ard.de, hbbtv-ondemand) and
// NDR's own set share the ".<code>.mp4" shape and do not overlap.
var dotCodes = map[string]int{
	"s": 180, "sm": 270, "m": 288, "ml": 360, "l": 540, "xl": 720, "xxl": 1080,
	"mn": 270, "hi": 288, "ln": 360, "hq": 540, "hd": 720, "1080": 1080,
}

var tagesCodes = map[string]int{
	"s": 270, "ml": 360, "l": 540, "xl": 720, "xxl": 1080,
	// "m" depends on the host, see height()
}

var brCodes = map[string]int{"A": 270, "E": 360, "C": 540, "X": 720, "HD": 1080}
var srCodes = map[string]int{"K": 270, "M": 288, "N": 360, "L": 540, "P": 720, "H": 1080}

// Funk's progressive files are "<n>-<20 random chars>.mp4" on funk-*dd.
var funkMP4 = map[string]int{"5": 240, "4": 360, "32": 576, "2": 720, "1": 1080, "33": 1440, "34": 2160}

// rbb "…_hd-<kbps>k.mp4" / "…_hd1080-<kbps>k.mp4".
var rbbKbps = map[string]int{
	"256": 270, "512": 288, "900": 360, "1024": 360, "1800": 540,
	"3500": 720, "3584": 720, "6500": 1080,
}

// daserste "<width>-1.mp4": 16:9 widths.
var dasersteWidth = map[string]int{"512": 288, "640": 360, "960": 540, "1280": 720, "1920": 1080}

var arteCodes = map[string]int{"300": 216, "800": 360, "1500": 406, "2200": 720}

// SRF's csmil lists name their renditions qNN.
var srfQ = map[string]int{"q10": 180, "q20": 270, "q30": 360, "q40": 540, "q50": 720, "q60": 1080}

var orfBps = map[string]int{
	"375000": 288, "620000": 360, "1326000": 540,
	"2440000": 576, "4165000": 720, "6100000": 1080,
}

// Funk's Unified Streaming ladder. The video= value wobbles by a few kbps per
// file, so map by range. Read off several upstream manifest.m3u8 masters.
var funkLadder = []struct{ maxKbps, height int }{
	{500, 240}, {1100, 360}, {2000, 576}, {3300, 720}, {5000, 1080}, {8000, 1440}, {1 << 30, 2160},
}

// height returns the video height encoded in a (raw, not rewritten) URL.
func height(raw string) (int, bool) {
	u, err := url.Parse(raw)
	if err != nil {
		return 0, false
	}
	host, path := u.Host, u.Path
	// Most rules only look at the file name; matching them against it
	// rather than the whole path is what keeps the import fast (unanchored
	// regexps over long CDN paths dominated its profile).
	file := path[strings.LastIndexByte(path, '/'):]

	if m := reZDF.FindStringSubmatch(file); m != nil {
		if h, ok := zdfCodes[m[1]]; ok {
			if m[1] == "13" && host == "rodl.zdf.de" {
				return 480, true
			}
			return h, true
		}
	}
	if m := reTagesWeb.FindStringSubmatch(file); m != nil {
		if m[1] == "m" {
			if host == "media.tagesschau.de" {
				return 288, true
			}
			return 360, true
		}
		return tagesCodes[m[1]], true
	}
	if (strings.Contains(file, "avc") || strings.Contains(file, "AVC")) && reAVC.MatchString(file) {
		m := reAVC.FindStringSubmatch(file)
		return atoi(m[1]), true
	}
	if m := wxh(path); m != nil {
		return min(atoi(m[1]), atoi(m[2])), true
	}
	if m := reDotSuffix.FindStringSubmatch(file); m != nil {
		if h, ok := dotCodes[m[1]]; ok {
			return h, true
		}
	}
	if m := reLetter.FindStringSubmatch(file); m != nil {
		switch {
		case host == "cdn-storage.br.de":
			if h, ok := brCodes[m[1]]; ok {
				return h, true
			}
		case host == "mediastorage01.sr-online.de":
			if m[1] == "H" {
				return 576, true
			}
			fallthrough
		case host == "srstorage01-a.akamaihd.net":
			if h, ok := srCodes[m[1]]; ok {
				return h, true
			}
		}
	}
	if m := reNp.FindStringSubmatch(file); m != nil {
		return atoi(m[1]), true
	}
	if m := reDaserste.FindStringSubmatch(file); m != nil {
		if h, ok := dasersteWidth[m[1]]; ok {
			return h, true
		}
	}
	if m := reFunkMP4.FindStringSubmatch(file); m != nil && strings.HasPrefix(host, "funk-") {
		if h, ok := funkMP4[m[1]]; ok {
			return h, true
		}
	}
	if m := reRBBk.FindStringSubmatch(file); m != nil {
		if h, ok := rbbKbps[m[1]]; ok {
			return h, true
		}
	}
	if m := reDotNum.FindStringSubmatch(file); m != nil {
		return atoi(m[1]), true
	}
	if m := reArte.FindStringSubmatch(file); m != nil {
		if h, ok := arteCodes[m[1]]; ok {
			return h, true
		}
	}

	// HLS variants
	if m := reORFChunk.FindStringSubmatch(file); m != nil {
		if h, ok := orfBps[m[1]]; ok {
			return h, true
		}
	}
	if m := reFunk.FindStringSubmatch(file); m != nil {
		kbps := atoi(m[1]) / 1000
		for _, l := range funkLadder {
			if kbps <= l.maxKbps {
				return l.height, true
			}
		}
	}
	if m := reCsmil.FindStringSubmatch(path); m != nil {
		return csmilHeight(host, m[1], atoi(m[2]))
	}
	return 0, false
}

// csmilHeight resolves Akamai's "index-f<N>" (1-based) against the
// comma-separated rendition list in front of ".mp4.csmil", e.g.
// "…_h264_,q40,q10,q20,q30,q50,q60," or "1384283,.sm,.ml,.l,.xl,.xxl,".
// The first element is the shared prefix, the last the shared suffix (often
// empty; ZDF's is "v15"), the ones in between are the renditions.
func csmilHeight(host, list string, n int) (int, bool) {
	parts := strings.Split(list, ",")
	if len(parts) < 3 || n < 1 || n > len(parts)-2 {
		return 0, false
	}
	prefix, item, suffix := parts[0], parts[n], parts[len(parts)-1]
	if h, ok := srfQ[item]; ok {
		return h, true
	}
	if h, err := strconv.Atoi(item); err == nil && h >= 100 && h <= 2160 {
		return h, true // WDR "_AVC-,270,360,…"
	}
	// Otherwise the item completes a regular progressive file name; reuse
	// the MP4 rules on the reconstructed name. BR's HLS host serves the same
	// renditions as its progressive one, whose letter codes we know.
	if host == "brvod-rwrtr.akamaized.net" {
		host = "cdn-storage.br.de"
	}
	return height("https://" + host + "/x/" + prefix + item + suffix + ".mp4")
}

// wxh finds "<W>x<H>" anywhere in the path (daserste, DW, rbb, hr put it in
// directory or file names). Only paths containing a digit-x-digit sequence
// reach the regexp: running it on every URL was half of the import's CPU.
func wxh(path string) []string {
	for i := 1; i+1 < len(path); i++ {
		if path[i] == 'x' && isDigit(path[i-1]) && isDigit(path[i+1]) {
			return reWxH.FindStringSubmatch(path)
		}
	}
	return nil
}

func isDigit(c byte) bool { return c >= '0' && c <= '9' }

func atoi(s string) int {
	n, _ := strconv.Atoi(s)
	return n
}