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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
package main

import (
	"bufio"
	"context"
	"database/sql"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"log"
	"net/http"
	"net/url"
	"regexp"
	"sort"
	"strconv"
	"strings"
	"sync"
	"time"
)

// ARTE. The film list has one entry per language version (ARTE.DE, ARTE.FR,
// …), each with MP4 files of that version only, but ARTE's own player
// streams one HLS master per programme that carries every audio language
// and subtitle. Its entries share a programme id (e.g. 129974-004-A) in
// their website URL.
//
// We look the master up once per (programme, language), on the first
// request for a video, like thumbnails, and store its text. NewPipe does not
// play the master itself: it plays each quality's URL (playlistUrl with
// "master" replaced by the height) on its own, and ARTE's quality playlists
// are video-only, so each of those URLs must itself be a master, of one
// quality plus all audio and subtitle renditions. We write it from the
// stored text; no request goes to ARTE when a video is played. See
// mediathek(7), "ARTE".

const (
	arteWait        = 2 * time.Second // how long a video request waits for a lookup
	arteWorkers     = 2
	arteQueue       = 100
	arteRefresh     = 24 * time.Hour // re-check a found master after this
	arteRetryNone   = 7 * 24 * time.Hour
	arteRetryError  = time.Hour
	arteMasterMax   = 256 << 10
	arteLookupLimit = 15 * time.Second
)

// reArtePage matches ARTE's video pages: /<lang>/videos/<programme id>/…
var reArtePage = regexp.MustCompile(`^https?://www\.arte\.tv/([a-z]{2})/videos/(\d{6}-\d{3}-[A-Z])/`)

// artePID returns the programme id and page language of an ARTE website URL.
func artePID(website string) (pid, lang string, ok bool) {
	m := reArtePage.FindStringSubmatch(website)
	if m == nil {
		return "", "", false
	}
	return m[2], m[1], true
}

// arteHosts are the only hosts the lookup fetches from.
var arteHosts = map[string]bool{"api.arte.tv": true, "manifest-arte.akamaized.net": true}

// lookupArte asks ARTE's player API for the programme's HLS master in lang
// and fetches it. "" and no error: ARTE has no HLS for it (gone, or not in
// that language).
func lookupArte(ctx context.Context, client *http.Client, pid, lang string) (string, error) {
	cfg, err := arteGet(ctx, client, "https://api.arte.tv/api/player/v2/config/"+lang+"/"+pid)
	if err != nil || cfg == nil {
		return "", err
	}
	master := arteMasterURL(cfg)
	if master == "" {
		return "", nil
	}
	body, err := arteGet(ctx, client, master)
	if err != nil || body == nil {
		return "", err
	}
	return absMaster(string(body), master)
}

// arteMasterURL picks the HLS stream from a player config.
func arteMasterURL(cfg []byte) string {
	var d struct {
		Data struct {
			Attributes struct {
				Streams []struct {
					URL      string `json:"url"`
					Protocol string `json:"protocol"`
				} `json:"streams"`
			} `json:"attributes"`
		} `json:"data"`
	}
	if json.Unmarshal(cfg, &d) != nil {
		return ""
	}
	for _, s := range d.Data.Attributes.Streams {
		if strings.HasPrefix(s.Protocol, "API_HLS") && s.URL != "" {
			return s.URL
		}
	}
	return ""
}

func arteGet(ctx context.Context, client *http.Client, target string) ([]byte, error) {
	u, err := url.Parse(target)
	if err != nil || !arteHosts[u.Host] || u.Scheme != "https" {
		return nil, fmt.Errorf("refusing to fetch %s", target)
	}
	req, err := http.NewRequestWithContext(ctx, "GET", target, nil)
	if err != nil {
		return nil, err
	}
	req.Header.Set("User-Agent", "Mozilla/5.0 (compatible; mediathek; +https://mediathek-newpipe.softwaregardening.org)")
	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	if resp.Request != nil && resp.Request.URL != nil && !arteHosts[resp.Request.URL.Host] {
		return nil, fmt.Errorf("%s redirected to %s", target, resp.Request.URL.Host)
	}
	switch {
	case resp.StatusCode == 404 || resp.StatusCode == 410:
		return nil, nil
	case resp.StatusCode != 200:
		return nil, fmt.Errorf("%s: %s", target, resp.Status)
	}
	return io.ReadAll(io.LimitReader(resp.Body, arteMasterMax))
}

var reURIAttr = regexp.MustCompile(`URI="([^"]*)"`)

// absMaster resolves every URI in a master playlist against its own URL,
// so the text can be served from anywhere, and checks it is one.
func absMaster(body, base string) (string, error) {
	b, err := url.Parse(base)
	if err != nil {
		return "", err
	}
	if !strings.HasPrefix(body, "#EXTM3U") || !strings.Contains(body, "#EXT-X-STREAM-INF") {
		return "", fmt.Errorf("%s: not an HLS master", base)
	}
	abs := func(ref string) string {
		u, err := b.Parse(ref)
		if err != nil {
			return ref
		}
		return u.String()
	}
	var out strings.Builder
	sc := bufio.NewScanner(strings.NewReader(body))
	for sc.Scan() {
		line := strings.TrimSpace(sc.Text())
		switch {
		case line == "":
		case strings.HasPrefix(line, "#"):
			out.WriteString(reURIAttr.ReplaceAllStringFunc(line, func(m string) string {
				return `URI="` + abs(reURIAttr.FindStringSubmatch(m)[1]) + `"`
			}))
			out.WriteByte('\n')
		default:
			out.WriteString(abs(line))
			out.WriteByte('\n')
		}
	}
	return out.String(), sc.Err()
}

// ---------------------------------------------------------------------------
// Reading a stored master.

// hlsVariant is one video quality of a master.
type hlsVariant struct {
	Height int
	Inf    string // the #EXT-X-STREAM-INF line
	URI    string
}

var (
	reResolution = regexp.MustCompile(`RESOLUTION=(\d+)x(\d+)`)
	reCodecs     = regexp.MustCompile(`CODECS="([^"]*)"`)
)

// masterVariants lists a master's H.264 variants, one per height (the
// smaller side, as our quality labels), ascending. HEVC variants are left
// out: not every phone decodes them, and ExoPlayer is only ever given one
// variant (see subMaster).
func masterVariants(master string) []hlsVariant {
	lines := strings.Split(master, "\n")
	byH := map[int]hlsVariant{}
	for i, l := range lines {
		if !strings.HasPrefix(l, "#EXT-X-STREAM-INF:") || i+1 >= len(lines) {
			continue
		}
		if c := reCodecs.FindStringSubmatch(l); c != nil && !strings.Contains(c[1], "avc1") {
			continue
		}
		m := reResolution.FindStringSubmatch(l)
		if m == nil {
			continue
		}
		w, _ := strconv.Atoi(m[1])
		h, _ := strconv.Atoi(m[2])
		h = min(w, h)
		if _, dup := byH[h]; !dup {
			byH[h] = hlsVariant{Height: h, Inf: l, URI: lines[i+1]}
		}
	}
	out := make([]hlsVariant, 0, len(byH))
	for _, v := range byH {
		out = append(out, v)
	}
	sort.Slice(out, func(i, j int) bool { return out[i].Height < out[j].Height })
	return out
}

// dropDuplicateSubs removes subtitle renditions whose file another one
// already lists. ARTE adds its "VO (Forced)" track as a second copy of an
// existing subtitle file (on another host), labelled with the language of
// the original audio instead of the text's: in Studio 54 (132050-000) an
// "en" track that is the French VO-FRA file. The first, correctly labelled
// rendition of a file is kept. Applied when serving, so stored masters are
// fixed too.
func dropDuplicateSubs(master string) string {
	seen := map[string]bool{}
	var b strings.Builder
	for _, l := range strings.SplitAfter(master, "\n") {
		if strings.HasPrefix(l, "#EXT-X-MEDIA:") && strings.Contains(l, "TYPE=SUBTITLES") {
			if m := reURIAttr.FindStringSubmatch(l); m != nil {
				file := m[1][strings.LastIndexByte(m[1], '/')+1:]
				if seen[file] {
					continue
				}
				seen[file] = true
			}
		}
		b.WriteString(l)
	}
	return b.String()
}

// A film list entry is one ARTE *version* of a programme, and its MP4 name
// says which: 132050-000-B_SQ_0_VO-STF_… is the original audio (VO) with
// French subtitles (STF). All versions of a programme in one page language
// share one master, whose DEFAULT audio is the dubbed one, and ExoPlayer
// plays the DEFAULT rendition; so the served master marks the entry's own
// audio (and, where the version is about subtitles, its subtitles) as the
// default instead. Measured on 120 videos: every file's audio code has a
// rendition in its master.
var reArteVersion = regexp.MustCompile(`_[A-Z]Q_\d+_([A-Z]+)(?:-([A-Z]+(?:(?:\[|%5B)[A-Z]+(?:\]|%5D))?))?_`)

// arteVersion reads the version code from a video's files: audio "vo",
// "vf", "vaaud", …, and subtitles "stf", "stma", "ste[ang]", … ("" if
// none). Empty audio if the files are not ARTE's.
func arteVersion(files string) (audio, sub string) {
	fs, _ := decodeFiles(files)
	for _, f := range fs {
		if m := reArteVersion.FindStringSubmatch(f.URL); m != nil {
			sub = strings.NewReplacer("%5B", "[", "%5D", "]").Replace(m[2])
			return strings.ToLower(m[1]), strings.ToLower(sub)
		}
	}
	return "", ""
}

// arteSubTrack is the subtitle characteristic (tv.arte.subtitle.version.X)
// a version's subtitles appear as, if they are worth switching on: they
// translate the audio, or are for the hard of hearing. Same-language
// subtitles of a dubbed version (VF-STF, VA-STA) are the forced ones
// ExoPlayer shows anyway. As seen in the masters of 160 videos:
//
//	VO-STF, VOF-STA, VOA-STF, *-STE[ANG]  translation  vo-fra, vo-all, vo-ang
//	VOF-STMF, VA-STMA, VOA-STMA           hard of hearing  vf-mal, va-mal
func arteSubTrack(audio, sub string) (string, bool) {
	audioLang := map[string]string{"vf": "fra", "vof": "fra", "vfaud": "fra", "va": "all", "voa": "all", "vaaud": "all"}[audio]
	switch {
	case strings.HasPrefix(sub, "stm"):
		switch audioLang {
		case "fra":
			return "vf-mal", true
		case "all":
			return "va-mal", true
		}
		return "", false
	case strings.HasPrefix(sub, "ste[") && strings.HasSuffix(sub, "]"):
		return "vo-" + sub[4:len(sub)-1], true
	case sub == "stf" || sub == "sta":
		code := map[string]string{"stf": "fra", "sta": "all"}[sub]
		if code == audioLang {
			return "", false // dubbed, same-language: forced subtitles
		}
		return "vo-" + code, true
	}
	return "", false
}

var (
	reDefault     = regexp.MustCompile(`\bDEFAULT=(YES|NO)`)
	reAudioChar   = regexp.MustCompile(`tv\.arte\.audio\.version\.([a-z]+)-`)
	reSubChar     = regexp.MustCompile(`tv\.arte\.subtitle\.version\.([a-z]+-[a-z]+)`)
	reForcedYes   = regexp.MustCompile(`\bFORCED=YES`)
	reClearSpeech = regexp.MustCompile(`enhances-speech-intelligibility`)
)

// setDefaults moves DEFAULT=YES to the audio rendition of the given
// version (the plain one, not "clear speech"), and to its subtitle track
// if arteSubTrack says so. Nothing matching: that group is left as it is.
func setDefaults(master, audio, sub string) string {
	if audio == "" {
		return master
	}
	lines := strings.Split(master, "\n")
	pick := func(match func(l string) bool, prefer func(l string) bool) int {
		best := -1
		for i, l := range lines {
			if !match(l) {
				continue
			}
			if best < 0 || (prefer(l) && !prefer(lines[best])) {
				best = i
			}
		}
		return best
	}
	mark := func(isGroup func(l string) bool, chosen int) {
		if chosen < 0 {
			return
		}
		for i, l := range lines {
			if isGroup(l) {
				v := "NO"
				if i == chosen {
					v = "YES"
				}
				lines[i] = reDefault.ReplaceAllString(l, "DEFAULT="+v)
			}
		}
	}
	isAudio := func(l string) bool { return strings.HasPrefix(l, "#EXT-X-MEDIA:") && strings.Contains(l, "TYPE=AUDIO") }
	isSub := func(l string) bool {
		return strings.HasPrefix(l, "#EXT-X-MEDIA:") && strings.Contains(l, "TYPE=SUBTITLES")
	}

	mark(isAudio, pick(func(l string) bool {
		m := reAudioChar.FindStringSubmatch(l)
		return isAudio(l) && m != nil && m[1] == audio
	}, func(l string) bool { return !reClearSpeech.MatchString(l) }))

	if track, on := arteSubTrack(audio, sub); on {
		mark(isSub, pick(func(l string) bool {
			m := reSubChar.FindStringSubmatch(l)
			return isSub(l) && m != nil && m[1] == track && !reForcedYes.MatchString(l)
		}, func(string) bool { return true }))
	}
	return strings.Join(lines, "\n")
}

var (
	reLanguageAttr = regexp.MustCompile(`LANGUAGE="([^"]*)"`)
	reNameAttr     = regexp.MustCompile(`NAME="([^"]*)"`)
)

// labelSubs writes each subtitle rendition's NAME into its LANGUAGE, as
// "<code>-<NAME>" ("de-Deutsch (Für Gehörlose und Schwerhörige)").
// NewPipe's caption menu shows only an ExoPlayer track's language, never
// its label (where NAME goes), and selects a track by that language: with
// three tracks all "de" the menu reads de/de/de and a tap picks any of
// them. The code stays in front because ExoPlayer matches languages on the
// part before the first "-", so forced subtitles still follow the audio
// language. Not valid HLS (LANGUAGE should be a language tag); only
// NewPipe reads these playlists. Values are made unique, since selection
// depends on it. See mediathek(7), ARTE.
func labelSubs(master string) string {
	seen := map[string]bool{}
	lines := strings.Split(master, "\n")
	for i, l := range lines {
		if !strings.HasPrefix(l, "#EXT-X-MEDIA:") || !strings.Contains(l, "TYPE=SUBTITLES") {
			continue
		}
		lang, name := reLanguageAttr.FindStringSubmatch(l), reNameAttr.FindStringSubmatch(l)
		if lang == nil || name == nil || name[1] == "" {
			continue
		}
		v := name[1]
		if lang[1] != "" {
			v = lang[1] + "-" + v
		}
		base := v
		for n := 2; seen[strings.ToLower(v)]; n++ {
			v = fmt.Sprintf("%s %d", base, n)
		}
		seen[strings.ToLower(v)] = true
		lines[i] = strings.Replace(l, lang[0], `LANGUAGE="`+v+`"`, 1)
	}
	return strings.Join(lines, "\n")
}

// subMaster is the master reduced to one video variant, with every audio
// and subtitle rendition kept: what NewPipe plays for one quality.
func subMaster(master string, v hlsVariant) string {
	var b strings.Builder
	for _, l := range strings.Split(master, "\n") {
		switch {
		case l == "#EXTM3U", strings.HasPrefix(l, "#EXT-X-VERSION"), l == "#EXT-X-INDEPENDENT-SEGMENTS",
			strings.HasPrefix(l, "#EXT-X-MEDIA:"):
			b.WriteString(l + "\n")
		}
	}
	b.WriteString(v.Inf + "\n" + v.URI + "\n")
	return b.String()
}

// ---------------------------------------------------------------------------
// The cache and the lookup pool, as for thumbnails (thumbs.go).

type arteState int

const (
	arteUnknown arteState = iota // never looked up, or due for a retry
	arteFound
	arteNone
)

type arteCache struct {
	db     *sql.DB
	client *http.Client
	lookup func(ctx context.Context, pid, lang string) (string, error)
	now    func() time.Time

	mu       sync.Mutex
	inflight map[string]chan struct{} // pid/lang → closed when done
	queue    chan arteJob
}

type arteJob struct {
	pid, lang string
	done      chan struct{}
}

func newArteCache(db *sql.DB) *arteCache {
	a := &arteCache{
		db:       db,
		client:   &http.Client{Timeout: arteLookupLimit},
		now:      time.Now,
		inflight: map[string]chan struct{}{},
		queue:    make(chan arteJob, arteQueue),
	}
	a.lookup = func(ctx context.Context, pid, lang string) (string, error) {
		return lookupArte(ctx, a.client, pid, lang)
	}
	for range arteWorkers {
		go func() {
			for job := range a.queue {
				a.run(job)
			}
		}()
	}
	return a
}

// get returns the stored master and whether it is due for a refresh.
func (a *arteCache) get(ctx context.Context, pid, lang string) (arteState, string, bool, error) {
	var master string
	var checked int64
	var failed bool
	err := a.db.QueryRowContext(ctx, `SELECT master, checked_at, failed FROM arte_hls WHERE pid=? AND lang=?`, pid, lang).
		Scan(&master, &checked, &failed)
	if err == sql.ErrNoRows {
		return arteUnknown, "", false, nil
	}
	if err != nil {
		return arteUnknown, "", false, err
	}
	age := a.now().Sub(time.Unix(checked, 0))
	if master != "" {
		return arteFound, master, age > arteRefresh, nil
	}
	retry := arteRetryNone
	if failed {
		retry = arteRetryError
	}
	if age > retry {
		return arteUnknown, "", false, nil
	}
	return arteNone, "", false, nil
}

// request starts a lookup unless one is running; nil if the queue is full.
func (a *arteCache) request(pid, lang string) chan struct{} {
	key := pid + "/" + lang
	a.mu.Lock()
	defer a.mu.Unlock()
	if ch, ok := a.inflight[key]; ok {
		return ch
	}
	job := arteJob{pid: pid, lang: lang, done: make(chan struct{})}
	select {
	case a.queue <- job:
		a.inflight[key] = job.done
		return job.done
	default:
		return nil
	}
}

func (a *arteCache) run(job arteJob) {
	defer func() {
		a.mu.Lock()
		delete(a.inflight, job.pid+"/"+job.lang)
		a.mu.Unlock()
		close(job.done)
	}()
	ctx, cancel := context.WithTimeout(context.Background(), arteLookupLimit)
	defer cancel()
	master, err := a.lookup(ctx, job.pid, job.lang)
	if err != nil {
		log.Printf("arte %s/%s: %v", job.lang, job.pid, err)
		// A failed refresh keeps the master we have.
		if _, e := a.db.Exec(`INSERT INTO arte_hls (pid, lang, master, checked_at, failed) VALUES (?,?,'',?,1)
			ON CONFLICT (pid, lang) DO UPDATE SET checked_at=excluded.checked_at, failed=(arte_hls.master='')`,
			job.pid, job.lang, a.now().Unix()); e != nil {
			log.Printf("arte %s/%s: store: %v", job.lang, job.pid, e)
		}
		return
	}
	if _, err := a.db.Exec(`INSERT INTO arte_hls (pid, lang, master, checked_at, failed) VALUES (?,?,?,?,0)
		ON CONFLICT (pid, lang) DO UPDATE SET master=excluded.master, checked_at=excluded.checked_at, failed=0`,
		job.pid, job.lang, master, a.now().Unix()); err != nil {
		log.Printf("arte %s/%s: store: %v", job.lang, job.pid, err)
	}
}

// master returns the video's ARTE master if it is known, starting a lookup
// (or a refresh) if not; wait bounds how long to wait for a lookup.
func (s *server) arteMaster(ctx context.Context, r *row, wait time.Duration) string {
	if s.arte == nil || r.PID == "" {
		return ""
	}
	_, lang, ok := artePID(r.Website)
	if !ok {
		return ""
	}
	st, master, stale, err := s.arte.get(ctx, r.PID, lang)
	if err != nil {
		return ""
	}
	switch {
	case st == arteFound && stale:
		s.arte.request(r.PID, lang) // serve what we have, refresh behind it
	case st == arteUnknown && wait > 0:
		if done := s.arte.request(r.PID, lang); done != nil {
			select {
			case <-done:
				st, master, _, _ = s.arte.get(ctx, r.PID, lang)
			case <-time.After(wait):
			case <-ctx.Done():
			}
		}
	case st == arteUnknown:
		s.arte.request(r.PID, lang)
	}
	if st != arteFound {
		return ""
	}
	return master
}

// artePlaylist is the streaming playlist of an ARTE video whose master is
// known: one entry per H.264 height. fileUrl, which NewPipe also offers
// for download, is the MP4 of that height where the film list has one,
// else the /remux stub (see HLS in mediathek(7)).
func (s *server) artePlaylist(r *row, master string) (apiPlaylist, bool) {
	vs := masterVariants(master)
	if len(vs) == 0 {
		return apiPlaylist{}, false
	}
	files, _ := decodeFiles(r.Files)
	pl := apiPlaylist{ID: 1, Type: 1, PlaylistURL: s.base + "/hls/" + r.UUID + "/master.m3u8"}
	for i, v := range vs {
		fu := fmt.Sprintf("%s/remux/%s/%d.mp4", s.base, r.UUID, v.Height)
		for j, f := range files {
			if f.Height == v.Height {
				fu = s.progressive(r, j, f).FileURL
			}
		}
		pl.Files = append(pl.Files, apiFile{
			ID:         i + 1,
			Resolution: labeled{v.Height, label(v.Height)},
			FileURL:    fu,
			FileDLURL:  fu,
			HasAudio:   true,
			HasVideo:   true,
		})
	}
	return pl, true
}

// serveArte answers /hls/<uuid>/<name> from the stored master, if the
// video has one: master.m3u8 as ARTE's, <h>.m3u8 reduced to that height.
func (s *server) serveArte(w http.ResponseWriter, r *http.Request, row *row, name string) bool {
	master := s.arteMaster(r.Context(), row, 0)
	if master == "" {
		return false
	}
	master = dropDuplicateSubs(master)
	audio, sub := arteVersion(row.Files)
	master = labelSubs(setDefaults(master, audio, sub))
	body := master
	if name != "master.m3u8" {
		h, err := strconv.Atoi(strings.TrimSuffix(name, ".m3u8"))
		if err != nil {
			return false
		}
		var found bool
		for _, v := range masterVariants(master) {
			if v.Height == h {
				body, found = subMaster(master, v), true
			}
		}
		if !found {
			return false
		}
	}
	w.Header().Set("Content-Type", "application/vnd.apple.mpegurl")
	w.Header().Set("Cache-Control", "public, max-age=3600")
	io.WriteString(w, body)
	return true
}

// otherVersions lists the other videos of the same ARTE programme: other
// languages, "(mit Untertitel)", "(Audiodeskription)". The redundant
// "pid is not empty" condition lets SQLite use the partial index video_pid,
// whose WHERE clause a query must imply; without it this is a scan of every
// video (see TestOtherVersionsUsesIndex).
func (s *server) otherVersions(ctx context.Context, r *row) []row {
	if r.PID == "" {
		return nil
	}
	g, err := s.liveGen(ctx)
	if err != nil {
		return nil
	}
	rows, err := scanRows(s.db.QueryContext(ctx, `SELECT `+rowCols+` FROM video
		WHERE gen=? AND pid=? AND pid<>'' AND uuid<>? AND published<=? ORDER BY sender, title`, g, r.PID, r.UUID, s.now().Unix()))
	if err != nil {
		return nil
	}
	return rows
}

// pruneArte drops stored masters of programmes no longer in any generation.
func pruneArte(db *sql.DB) (int64, error) {
	res, err := db.Exec(`DELETE FROM arte_hls WHERE pid NOT IN (SELECT pid FROM video WHERE pid<>'')`)
	if err != nil {
		return 0, err
	}
	return res.RowsAffected()
}

// errNoArte is returned by `mediathek arte` for a URL that is not ARTE's.
var errNoArte = errors.New("not an ARTE video page")

// runArte looks masters up by hand: `mediathek arte <website URL>...`.
func runArte(args []string) error {
	if len(args) == 0 {
		return fmt.Errorf("usage: mediathek arte <website URL>...")
	}
	client := &http.Client{Timeout: arteLookupLimit}
	for _, a := range args {
		pid, lang, ok := artePID(a)
		if !ok {
			fmt.Printf("-\t%v\t%s\n", errNoArte, a)
			continue
		}
		t := time.Now()
		m, err := lookupArte(context.Background(), client, pid, lang)
		var hs []string
		for _, v := range masterVariants(m) {
			hs = append(hs, strconv.Itoa(v.Height))
		}
		fmt.Printf("%s\t%s/%s\theights %s, %d renditions\t%v\n", time.Since(t).Round(time.Millisecond), lang, pid,
			strings.Join(hs, ","), strings.Count(m, "#EXT-X-MEDIA:"), err)
	}
	return nil
}