tidal-player-api 1.2.0

Tidal HTTP API client for tidal-player
Documentation
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
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
//! Stream resolution (spec 0003, AC1–AC5): turns a track ID into a
//! [`StreamPlan`] the player can fetch, through
//! `GET /tracks/{id}/playbackinfopostpaywall`.
//!
//! One request per resolve, at the highest quality asked for: Tidal grants
//! less by itself when the track or the account has less, and the granted
//! quality is reported in [`ResolvedStream::quality`]. Nothing is downloaded
//! here; the plan only says where the bytes are.

use std::fmt;
use std::sync::Arc;
use std::time::Duration;

use base64::Engine;
use base64::engine::general_purpose::STANDARD as BASE64;
use quick_xml::XmlVersion;
use quick_xml::events::{BytesStart, Event};
use quick_xml::reader::Reader;
use serde::Deserialize;
use tidal_player_core::AudioQuality;

use crate::SUB_STATUS_NOT_AVAILABLE;
use crate::auth::{AuthError, Authenticator};

/// How long the `playbackinfopostpaywall` request may take before it fails
/// with [`AuthError::Transport`].
pub const RESOLVE_TIMEOUT: Duration = Duration::from_secs(10);

/// An audio codec the player can decode.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Codec {
    /// FLAC, as a raw FLAC file or in (fragmented) MP4.
    Flac,
    /// AAC-LC (`mp4a.40.2`) in MP4.
    AacLc,
}

/// One media segment of a [`StreamPlan::Segmented`] stream.
///
/// Times are in ticks of `timescale` per second, as in the MPD, so they add
/// up exactly; [`Segment::start_time`] and [`Segment::duration_time`] convert.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Segment {
    /// The DASH segment number (`$Number$`).
    pub number: u64,
    /// The segment's URL.
    pub url: String,
    /// Start, in ticks from the start of the track.
    pub start: u64,
    /// Length, in ticks.
    pub duration: u64,
    /// Ticks per second.
    pub timescale: u32,
}

impl Segment {
    /// Start from the start of the track (rounded down to the nanosecond).
    pub fn start_time(&self) -> Duration {
        ticks_to_duration(self.start, self.timescale)
    }

    /// Length (rounded down to the nanosecond).
    pub fn duration_time(&self) -> Duration {
        ticks_to_duration(self.duration, self.timescale)
    }

    /// End from the start of the track (rounded down to the nanosecond).
    pub fn end_time(&self) -> Duration {
        ticks_to_duration(self.start + self.duration, self.timescale)
    }
}

fn ticks_to_duration(ticks: u64, timescale: u32) -> Duration {
    if timescale == 0 {
        return Duration::ZERO;
    }
    let nanos = u128::from(ticks) * 1_000_000_000 / u128::from(timescale);
    Duration::from_nanos(u64::try_from(nanos).unwrap_or(u64::MAX))
}

/// Where a track's bytes are.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum StreamPlan {
    /// One file (BTS manifest), fetched with HTTP `Range` requests.
    Single { url: String, codec: Codec },
    /// MPEG-DASH: the init segment, then `segments` in order, joined.
    Segmented {
        init_url: String,
        segments: Vec<Segment>,
        codec: Codec,
    },
}

impl StreamPlan {
    /// The codec of the stream.
    pub fn codec(&self) -> Codec {
        match self {
            Self::Single { codec, .. } | Self::Segmented { codec, .. } => *codec,
        }
    }
}

/// A resolved track: what Tidal granted, and where to fetch it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolvedStream {
    /// The track ID Tidal answered for.
    pub track_id: u64,
    /// The quality Tidal **granted** (may be lower than asked).
    pub quality: AudioQuality,
    /// Bits per sample, when the response says (lossless grants).
    pub bit_depth: Option<u8>,
    /// Sample rate in Hz, when the response says (lossless grants).
    pub sample_rate: Option<u32>,
    pub plan: StreamPlan,
}

/// What made a stream unplayable.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Unsupported {
    /// An `encryptionType` other than `NONE`, or DASH `ContentProtection`.
    Encrypted,
    /// A `manifestMimeType` other than BTS or DASH.
    Manifest(String),
    /// An `audioMode` other than `STEREO` (Dolby Atmos, Sony 360).
    AudioMode(String),
    /// A codec other than FLAC or AAC-LC (e.g. HE-AAC).
    Codec(String),
    /// An `audioQuality` this player does not know.
    Quality(String),
}

impl fmt::Display for Unsupported {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Encrypted => f.write_str("the stream is encrypted"),
            Self::Manifest(mime) => write!(f, "unknown manifest type {mime:?}"),
            Self::AudioMode(mode) => write!(f, "audio mode {mode} is not supported"),
            Self::Codec(codec) => write!(f, "codec {codec} is not supported"),
            Self::Quality(quality) => write!(f, "unknown audio quality {quality:?}"),
        }
    }
}

/// Why a track could not be resolved.
#[derive(Debug, Clone, PartialEq, thiserror::Error)]
pub enum StreamError {
    /// `401` with `subStatus` `4005`: not playable for this account or
    /// country (or at this quality).
    #[error("the track is not available")]
    NotAvailable,
    /// `500` with `subStatus` `999`: unknown track ID, or not streamable in
    /// the account's country.
    #[error("the track was not found, or cannot be streamed in this country")]
    NotFound,
    /// The response is for a preview, not the full track.
    #[error("the track is only available as a preview")]
    PreviewOnly,
    /// Another `500`.
    #[error("Tidal server error (HTTP {0})")]
    Server(u16),
    /// The stream exists but cannot be played.
    #[error("not playable: {0}")]
    Unsupported(Unsupported),
    /// A `200` whose body or manifest could not be read; says what was
    /// wrong, never quotes the body (its URLs carry tokens).
    #[error("malformed stream response: {0}")]
    Malformed(&'static str),
    /// From the [`Authenticator`], unchanged: transport errors and
    /// timeouts, other statuses (`5xx`, `429`, …), `LoginRequired`.
    #[error(transparent)]
    Auth(#[from] AuthError),
}

/// Resolves tracks to streams through the [`Authenticator`].
#[derive(Debug, Clone)]
pub struct StreamResolver {
    auth: Arc<Authenticator>,
    timeout: Duration,
}

impl StreamResolver {
    /// A resolver whose requests time out after [`RESOLVE_TIMEOUT`].
    pub fn new(auth: Arc<Authenticator>) -> Self {
        Self {
            auth,
            timeout: RESOLVE_TIMEOUT,
        }
    }

    /// Replaces the request timeout.
    pub fn with_timeout(mut self, timeout: Duration) -> Self {
        self.timeout = timeout;
        self
    }

    /// Resolves `track_id`, asking for `max_quality` (AC1, AC5).
    ///
    /// Sends exactly one `playbackinfopostpaywall` request, whatever the
    /// outcome (no client-side quality ladder): Tidal downgrades by itself,
    /// and [`ResolvedStream::quality`] says what it granted. Errors map as
    /// in spec 0003 "Quality"; anything not listed there comes back as
    /// [`StreamError::Auth`], unchanged.
    pub async fn resolve_stream(
        &self,
        track_id: u64,
        max_quality: AudioQuality,
    ) -> Result<ResolvedStream, StreamError> {
        let (_, country) = self.auth.account().await;
        let path = format!("tracks/{track_id}/playbackinfopostpaywall");
        let query = [
            ("audioquality", max_quality.tidal_name()),
            ("playbackmode", "STREAM"),
            ("assetpresentation", "FULL"),
            ("countryCode", country.as_str()),
        ];
        let response = self.auth.get(&path, &query, Some(self.timeout)).await?;
        if response.status().is_success() {
            return parse_playback_info(response.body());
        }
        Err(map_error(response.status().as_u16(), response.sub_status()))
    }
}

/// Tidal's `subStatus` on a `500` for an unknown track ID, or one that
/// cannot be streamed in the account's country.
const SUB_STATUS_NOT_FOUND: u64 = 999;

/// Maps a non-2xx `playbackinfopostpaywall` answer (AC5).
fn map_error(status: u16, sub_status: Option<u64>) -> StreamError {
    match (status, sub_status) {
        (401, Some(SUB_STATUS_NOT_AVAILABLE)) => StreamError::NotAvailable,
        (500, Some(SUB_STATUS_NOT_FOUND)) => StreamError::NotFound,
        (500, _) => StreamError::Server(500),
        (status, _) => StreamError::Auth(AuthError::Http { status, code: None }),
    }
}

const MIME_BTS: &str = "application/vnd.tidal.bts";
const MIME_DASH: &str = "application/dash+xml";

/// The fields of a `playbackinfopostpaywall` body that resolution uses.
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct PlaybackInfo {
    track_id: u64,
    asset_presentation: String,
    audio_mode: String,
    audio_quality: String,
    manifest_mime_type: String,
    manifest: String,
    bit_depth: Option<u8>,
    sample_rate: Option<u32>,
}

/// Parses and validates a `playbackinfopostpaywall` body (AC2–AC4).
///
/// Error messages never quote the body: its URLs carry tokens.
pub fn parse_playback_info(body: &[u8]) -> Result<ResolvedStream, StreamError> {
    let info: PlaybackInfo = serde_json::from_slice(body)
        .map_err(|_| StreamError::Malformed("playback info is not the expected JSON"))?;
    if info.asset_presentation != "FULL" {
        return Err(StreamError::PreviewOnly);
    }
    if info.audio_mode != "STEREO" {
        return Err(StreamError::Unsupported(Unsupported::AudioMode(
            info.audio_mode,
        )));
    }
    let quality = serde_json::from_value(serde_json::Value::String(info.audio_quality.clone()))
        .map_err(|_| StreamError::Unsupported(Unsupported::Quality(info.audio_quality)))?;
    let plan = match info.manifest_mime_type.as_str() {
        MIME_BTS => parse_bts(&decode_manifest(&info.manifest)?)?,
        MIME_DASH => {
            let xml = String::from_utf8(decode_manifest(&info.manifest)?)
                .map_err(|_| StreamError::Malformed("MPD is not UTF-8"))?;
            parse_mpd(&xml)?
        }
        _ => {
            return Err(StreamError::Unsupported(Unsupported::Manifest(
                info.manifest_mime_type,
            )));
        }
    };
    Ok(ResolvedStream {
        track_id: info.track_id,
        quality,
        bit_depth: info.bit_depth,
        sample_rate: info.sample_rate,
        plan,
    })
}

fn decode_manifest(manifest: &str) -> Result<Vec<u8>, StreamError> {
    BASE64
        .decode(manifest)
        .map_err(|_| StreamError::Malformed("manifest is not base64"))
}

/// Maps a manifest's codec string; HE-AAC and anything else is unsupported.
fn codec(codecs: &str) -> Result<Codec, StreamError> {
    match codecs.trim().to_ascii_lowercase().as_str() {
        "flac" => Ok(Codec::Flac),
        "mp4a.40.2" => Ok(Codec::AacLc),
        _ => Err(StreamError::Unsupported(Unsupported::Codec(
            codecs.to_owned(),
        ))),
    }
}

/// A BTS manifest.
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Bts {
    codecs: String,
    encryption_type: String,
    urls: Vec<String>,
}

/// Parses a BTS manifest (AC2): one file, `urls[0]`.
fn parse_bts(manifest: &[u8]) -> Result<StreamPlan, StreamError> {
    let bts: Bts = serde_json::from_slice(manifest)
        .map_err(|_| StreamError::Malformed("BTS manifest is not the expected JSON"))?;
    if bts.encryption_type != "NONE" {
        return Err(StreamError::Unsupported(Unsupported::Encrypted));
    }
    let codec = codec(&bts.codecs)?;
    let url = bts
        .urls
        .into_iter()
        .next()
        .ok_or(StreamError::Malformed("BTS manifest has no URL"))?;
    Ok(StreamPlan::Single { url, codec })
}

/// Upper bound on the segments of one track (about 4 days of 4 s segments),
/// so a hostile `r` cannot exhaust memory.
const MAX_SEGMENTS: u64 = 100_000;

/// One `<S>` entry of a `SegmentTimeline`.
struct TimelineEntry {
    t: Option<u64>,
    d: u64,
    r: u64,
}

/// What the MPD parser collects.
#[derive(Default)]
struct Mpd {
    encrypted: bool,
    representations: usize,
    adaptation_codecs: Option<String>,
    representation_codecs: Option<String>,
    timescale: Option<u32>,
    initialization: Option<String>,
    media: Option<String>,
    start_number: Option<u64>,
    timeline: Vec<TimelineEntry>,
}

/// Parses a DASH MPD (AC3): one audio `Representation` whose
/// `SegmentTemplate` has `initialization`, `media` with `$Number$`,
/// `startNumber`, `timescale` and a `SegmentTimeline`. URLs must be
/// absolute (Tidal's are; `BaseURL` is not supported).
fn parse_mpd(xml: &str) -> Result<StreamPlan, StreamError> {
    let mpd = read_mpd(xml)?;
    if mpd.encrypted {
        return Err(StreamError::Unsupported(Unsupported::Encrypted));
    }
    if mpd.representations != 1 {
        return Err(StreamError::Malformed(
            "MPD must have exactly one Representation",
        ));
    }
    let codecs = mpd
        .representation_codecs
        .or(mpd.adaptation_codecs)
        .ok_or(StreamError::Malformed("MPD has no codecs"))?;
    let codec = codec(&codecs)?;
    let init_url = mpd
        .initialization
        .ok_or(StreamError::Malformed("MPD has no initialization segment"))?;
    let media = mpd
        .media
        .filter(|m| m.contains("$Number$"))
        .ok_or(StreamError::Malformed(
            "MPD has no media template with $Number$",
        ))?;
    let timescale = mpd.timescale.unwrap_or(1);
    if timescale == 0 {
        return Err(StreamError::Malformed("MPD timescale is 0"));
    }
    if mpd.timeline.is_empty() {
        return Err(StreamError::Malformed("MPD has no SegmentTimeline"));
    }
    let total: u64 = mpd
        .timeline
        .iter()
        .map(|s| s.r.saturating_add(1))
        .fold(0, u64::saturating_add);
    if total > MAX_SEGMENTS {
        return Err(StreamError::Malformed("MPD has too many segments"));
    }

    let mut segments = Vec::with_capacity(total as usize);
    let mut time = 0u64;
    let mut number = mpd.start_number.unwrap_or(1);
    for entry in &mpd.timeline {
        if let Some(t) = entry.t {
            time = t;
        }
        for _ in 0..=entry.r {
            segments.push(Segment {
                number,
                url: media.replace("$Number$", &number.to_string()),
                start: time,
                duration: entry.d,
                timescale,
            });
            time = time
                .checked_add(entry.d)
                .ok_or(StreamError::Malformed("MPD timeline overflows"))?;
            number += 1;
        }
    }
    Ok(StreamPlan::Segmented {
        init_url,
        segments,
        codec,
    })
}

/// Collects the parts of the MPD that [`parse_mpd`] uses.
fn read_mpd(xml: &str) -> Result<Mpd, StreamError> {
    const BAD_XML: StreamError = StreamError::Malformed("MPD is not well-formed XML");
    let mut reader = Reader::from_str(xml);
    let mut mpd = Mpd::default();
    loop {
        let element = match reader.read_event().map_err(|_| BAD_XML)? {
            Event::Start(e) | Event::Empty(e) => e,
            Event::Eof => break,
            _ => continue,
        };
        let attrs = attributes(&element)?;
        let get = |name: &str| {
            attrs
                .iter()
                .find(|(k, _)| k == name)
                .map(|(_, v)| v.clone())
        };
        match element.local_name().as_ref() {
            "ContentProtection" => mpd.encrypted = true,
            "AdaptationSet" => mpd.adaptation_codecs = get("codecs"),
            "Representation" => {
                mpd.representations += 1;
                mpd.representation_codecs = get("codecs");
            }
            "SegmentTemplate" => {
                mpd.timescale = get("timescale").map(|v| number(&v)).transpose()?;
                mpd.initialization = get("initialization");
                mpd.media = get("media");
                mpd.start_number = get("startNumber").map(|v| number(&v)).transpose()?;
            }
            "S" => {
                let d = get("d").ok_or(StreamError::Malformed("MPD segment has no duration"))?;
                let d: u64 = number(&d)?;
                if d == 0 {
                    return Err(StreamError::Malformed("MPD segment has no duration"));
                }
                mpd.timeline.push(TimelineEntry {
                    t: get("t").map(|v| number(&v)).transpose()?,
                    d,
                    // A negative `r` (open-ended) does not parse as u64.
                    r: get("r").map(|v| number(&v)).transpose()?.unwrap_or(0),
                });
            }
            _ => {}
        }
    }
    Ok(mpd)
}

/// The element's attributes as `(local name, unescaped value)`.
fn attributes(element: &BytesStart<'_>) -> Result<Vec<(String, String)>, StreamError> {
    const BAD_ATTR: StreamError = StreamError::Malformed("MPD has a malformed attribute");
    element
        .attributes()
        .map(|attr| {
            let attr = attr.map_err(|_| BAD_ATTR)?;
            let key = attr.key.local_name().as_ref().to_owned();
            let value = attr
                .normalized_value(XmlVersion::Implicit1_0)
                .map_err(|_| BAD_ATTR)?
                .into_owned();
            Ok((key, value))
        })
        .collect()
}

fn number<T: std::str::FromStr>(value: &str) -> Result<T, StreamError> {
    value
        .trim()
        .parse()
        .map_err(|_| StreamError::Malformed("MPD has a malformed number"))
}

#[cfg(test)]
mod tests {
    use super::*;
    use base64::Engine;
    use base64::engine::general_purpose::STANDARD;
    use serde_json::Value;

    const HIRES: &str = include_str!("../tests/fixtures/stream/playbackinfo_hires_dash.json");
    const LOSSLESS: &str = include_str!("../tests/fixtures/stream/playbackinfo_lossless_dash.json");
    const HIGH: &str = include_str!("../tests/fixtures/stream/playbackinfo_high_bts.json");
    const BTS_FLAC: &str =
        include_str!("../tests/fixtures/stream/playbackinfo_lossless_bts_flac.json");
    const MPD_HIRES: &str = include_str!("../tests/fixtures/stream/manifest_hires_24_96.mpd");
    const MPD_LOSSLESS: &str = include_str!("../tests/fixtures/stream/manifest_lossless_16_44.mpd");

    /// `fixture` with top-level fields replaced.
    fn edit(fixture: &str, fields: &[(&str, Value)]) -> Vec<u8> {
        let mut info: Value = serde_json::from_str(fixture).unwrap();
        for (key, value) in fields {
            info[*key] = value.clone();
        }
        serde_json::to_vec(&info).unwrap()
    }

    /// The decoded manifest of `fixture`.
    fn manifest(fixture: &str) -> String {
        let info: Value = serde_json::from_str(fixture).unwrap();
        let bytes = STANDARD.decode(info["manifest"].as_str().unwrap()).unwrap();
        String::from_utf8(bytes).unwrap()
    }

    /// `fixture` with its manifest passed through `change`.
    fn edit_manifest(fixture: &str, change: impl Fn(String) -> String) -> Vec<u8> {
        let encoded = STANDARD.encode(change(manifest(fixture)));
        edit(fixture, &[("manifest", Value::String(encoded))])
    }

    /// The `HIGH` fixture with one field of its BTS manifest replaced.
    fn bts_with(field: &str, value: Value) -> Vec<u8> {
        edit_manifest(HIGH, |m| {
            let mut bts: Value = serde_json::from_str(&m).unwrap();
            bts[field] = value.clone();
            bts.to_string()
        })
    }

    fn unsupported(what: Unsupported) -> StreamError {
        StreamError::Unsupported(what)
    }

    #[test]
    fn ac2_bts_manifest() {
        let rows: Vec<(&str, Vec<u8>, Result<StreamPlan, StreamError>)> = vec![
            (
                "FLAC",
                BTS_FLAC.as_bytes().to_vec(),
                Ok(StreamPlan::Single {
                    url: "https://amz-pr-fa.audio.tidal.com/FAKE.flac?token=FAKE".into(),
                    codec: Codec::Flac,
                }),
            ),
            (
                "AAC-LC",
                HIGH.as_bytes().to_vec(),
                Ok(StreamPlan::Single {
                    url: "https://amz-pr-fa.audio.tidal.com/FAKE.mp4?token=FAKE".into(),
                    codec: Codec::AacLc,
                }),
            ),
            (
                "encrypted BTS",
                bts_with("encryptionType", "OLD_AES".into()),
                Err(unsupported(Unsupported::Encrypted)),
            ),
            (
                "encrypted DASH",
                edit_manifest(HIRES, |m| {
                    m.replace(
                        "<Role ",
                        r#"<ContentProtection schemeIdUri="urn:mpeg:dash:mp4protection:2011" value="cenc"/><Role "#,
                    )
                }),
                Err(unsupported(Unsupported::Encrypted)),
            ),
            (
                "unknown manifest type",
                edit(
                    HIGH,
                    &[("manifestMimeType", "application/vnd.tidal.emu".into())],
                ),
                Err(unsupported(Unsupported::Manifest(
                    "application/vnd.tidal.emu".into(),
                ))),
            ),
        ];
        for (name, body, expected) in rows {
            let got = parse_playback_info(&body).map(|r| r.plan);
            assert_eq!(got, expected, "{name}");
        }

        for (name, body) in [
            ("no URL", bts_with("urls", serde_json::json!([]))),
            ("not base64", edit(HIGH, &[("manifest", "%%%".into())])),
            ("not JSON", edit_manifest(HIGH, |_| "nope".into())),
        ] {
            let got = parse_playback_info(&body);
            assert!(
                matches!(got, Err(StreamError::Malformed(_))),
                "{name}: {got:?}"
            );
        }
    }

    fn segments(plan: &StreamPlan) -> (&str, &[Segment], Codec) {
        match plan {
            StreamPlan::Segmented {
                init_url,
                segments,
                codec,
            } => (init_url, segments, *codec),
            other => panic!("not segmented: {other:?}"),
        }
    }

    /// Checks numbering, contiguity and the total of `segments`.
    fn assert_timeline(segments: &[Segment], first_number: u64, total_ticks: u64) {
        let mut next_start = segments.first().map_or(0, |s| s.start);
        for (i, segment) in segments.iter().enumerate() {
            assert_eq!(segment.number, first_number + i as u64, "number of #{i}");
            assert_eq!(segment.start, next_start, "start of #{i}");
            next_start += segment.duration;
        }
        let total: u64 = segments.iter().map(|s| s.duration).sum();
        assert_eq!(total, total_ticks);
    }

    #[test]
    fn ac3_dash_manifest() {
        // The recorded hi-res MPD: 73 × 380928 + 129030 ticks at 96 kHz.
        let plan = parse_mpd(MPD_HIRES).unwrap();
        let (init_url, segs, codec) = segments(&plan);
        assert_eq!(segs.len(), 74);
        assert_eq!(codec, Codec::Flac);
        assert_eq!(
            init_url,
            "https://sp-ad-fa.audio.tidal.com/mediatracks/FAKE/0.mp4?token=FAKE"
        );
        assert_timeline(segs, 1, 27_936_774);
        let url =
            |n| format!("https://sp-ad-fa.audio.tidal.com/mediatracks/FAKE/{n}.mp4?token=FAKE");
        assert_eq!(segs[0].url, url(1));
        assert_eq!(segs[1].url, url(2));
        assert_eq!(segs[73].url, url(74));
        assert_eq!(segs[0].start, 0);
        assert_eq!(segs[0].start_time(), Duration::ZERO);
        assert_eq!(segs[1].start_time(), Duration::from_millis(3968));
        assert_eq!(segs[72].duration, 380_928);
        assert_eq!(segs[73].start, 73 * 380_928);
        assert_eq!(segs[73].duration, 129_030);
        assert!(segs.iter().all(|s| s.timescale == 96_000));
        // = mediaPresentationDuration PT4M51.008S, to the millisecond.
        assert_eq!(segs[73].end_time().as_millis(), 291_008);

        // The recorded 16/44.1 MPD: `&amp;` in the signed URLs is unescaped.
        let plan = parse_mpd(MPD_LOSSLESS).unwrap();
        let (init_url, segs, _) = segments(&plan);
        let query = "Policy=FAKE-POLICY&Signature=FAKE-SIG&Key-Pair-Id=FAKE-KEY";
        assert_eq!(
            init_url,
            format!("https://sp-ad-cf.audio.tidal.com/mediatracks/FAKE/0.mp4?{query}")
        );
        assert_eq!(segs.len(), 57);
        assert_timeline(segs, 1, 56 * 176_128 + 52_930);
        assert_eq!(
            segs[56].url,
            format!("https://sp-ad-cf.audio.tidal.com/mediatracks/FAKE/57.mp4?{query}")
        );
        // = mediaPresentationDuration PT3M44.854S, to the millisecond.
        assert_eq!(segs[56].end_time().as_millis(), 224_854);

        // Hand-written: `t` on the first entry, repeats, startNumber 5.
        let mpd = r#"<MPD><Period><AdaptationSet><Representation codecs="flac">
            <SegmentTemplate timescale="10" initialization="i.mp4" media="s$Number$.m4s" startNumber="5">
              <SegmentTimeline><S t="100" d="20" r="2"/><S d="7"/><S d="3" r="1"/></SegmentTimeline>
            </SegmentTemplate></Representation></AdaptationSet></Period></MPD>"#;
        let plan = parse_mpd(mpd).unwrap();
        let (init_url, segs, _) = segments(&plan);
        assert_eq!(init_url, "i.mp4");
        let got: Vec<(u64, &str, u64, u64)> = segs
            .iter()
            .map(|s| (s.number, s.url.as_str(), s.start, s.duration))
            .collect();
        assert_eq!(
            got,
            [
                (5, "s5.m4s", 100, 20),
                (6, "s6.m4s", 120, 20),
                (7, "s7.m4s", 140, 20),
                (8, "s8.m4s", 160, 7),
                (9, "s9.m4s", 167, 3),
                (10, "s10.m4s", 170, 3),
            ]
        );
        assert_eq!(segs[0].start_time(), Duration::from_secs(10));
    }

    #[test]
    fn ac4_validate_playbackinfo() {
        let errors: Vec<(&str, Vec<u8>, StreamError)> = vec![
            (
                "preview",
                edit(HIRES, &[("assetPresentation", "PREVIEW".into())]),
                StreamError::PreviewOnly,
            ),
            (
                "Dolby Atmos",
                edit(HIRES, &[("audioMode", "DOLBY_ATMOS".into())]),
                unsupported(Unsupported::AudioMode("DOLBY_ATMOS".into())),
            ),
            (
                "HE-AAC (LOW)",
                bts_with("codecs", "mp4a.40.5".into()),
                unsupported(Unsupported::Codec("mp4a.40.5".into())),
            ),
            (
                "HE-AAC v2",
                bts_with("codecs", "mp4a.40.29".into()),
                unsupported(Unsupported::Codec("mp4a.40.29".into())),
            ),
            (
                "HE-AAC in DASH",
                edit_manifest(HIRES, |m| {
                    m.replace(r#"codecs="flac""#, r#"codecs="mp4a.40.5""#)
                }),
                unsupported(Unsupported::Codec("mp4a.40.5".into())),
            ),
            (
                "unknown quality",
                edit(HIRES, &[("audioQuality", "HI_RES".into())]),
                unsupported(Unsupported::Quality("HI_RES".into())),
            ),
        ];
        for (name, body, expected) in errors {
            assert_eq!(parse_playback_info(&body), Err(expected), "{name}");
        }

        let grants = [
            (
                "hi-res",
                HIRES,
                1001,
                AudioQuality::HiResLossless,
                Some(24),
                Some(96_000),
                Codec::Flac,
            ),
            (
                "lossless",
                LOSSLESS,
                1002,
                AudioQuality::Lossless,
                Some(16),
                Some(44_100),
                Codec::Flac,
            ),
            (
                "high",
                HIGH,
                1002,
                AudioQuality::High,
                None,
                None,
                Codec::AacLc,
            ),
        ];
        for (name, body, track_id, quality, bits, rate, codec) in grants {
            let got = parse_playback_info(body.as_bytes());
            let got = got.unwrap_or_else(|e| panic!("{name}: {e:?}"));
            assert_eq!(got.track_id, track_id, "{name}");
            assert_eq!(got.quality, quality, "{name}");
            assert_eq!(got.bit_depth, bits, "{name}");
            assert_eq!(got.sample_rate, rate, "{name}");
            assert_eq!(got.plan.codec(), codec, "{name}");
        }
    }
}