.
diff --git a/NOTICE b/NOTICE
new file mode 100644
index 0000000..e77a0d6
--- /dev/null
+++ b/NOTICE
@@ -0,0 +1,54 @@
+StreamWatch
+Copyright (C) 2026 the StreamWatch contributors
+
+StreamWatch is free software: you can redistribute it and/or modify it under
+the terms of the GNU General Public License, version 3 only (GPL-3.0-only), as
+published by the Free Software Foundation. It is distributed in the hope that
+it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
+of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE for the
+complete license text.
+
+Source: https://github.com/troylefevre65/StreamWatch
+
+Related work and attribution
+
+RateCue is the macOS menu bar app that StreamWatch observes and researches.
+The collector's decoder-lifecycle patterns follow RateCue's parser.
+
+Project: https://github.com/troylefevre65/RateCue
+License: GPL-3.0-only
+
+LosslessSwitcher, by Vincent Neo and the LosslessSwitcher contributors,
+established the method of reading Apple Music's format from the macOS unified
+log. The collector's audioCapabilities, ALAC decoder and AudioQueue patterns
+follow the ones LosslessSwitcher uses (Quality/CMPlayerStuff.swift), so that
+StreamWatch can compare that method with RateCue's on the same playback.
+
+Project: https://github.com/vincentneo/LosslessSwitcher
+License: GPL-3.0 (https://github.com/vincentneo/LosslessSwitcher/blob/main/LICENSE)
+Contributors: https://github.com/vincentneo/LosslessSwitcher/graphs/contributors
+
+StreamWatch is a separate project, not a fork or an official release of
+either. It does not include LosslessSwitcher source files, binaries, or
+artwork, and the credit does not attribute StreamWatch's implementation to
+Vincent Neo or the LosslessSwitcher contributors.
+
+Third-party components
+
+StreamWatch bundles no third-party code. The agent installs these Python
+packages, each under its own license, from llm-box/requirements.txt:
+
+ openai Apache-2.0 https://github.com/openai/openai-python
+ ddgs MIT https://github.com/deedy5/ddgs
+ trafilatura Apache-2.0 https://github.com/adbar/trafilatura
+
+The collector and the read-only gate use only the Python standard library.
+A model server and its model weights are chosen and installed by the operator
+and are not part of StreamWatch.
+
+Trademarks
+
+Apple, Apple Music and macOS are trademarks of Apple Inc. GitHub and
+DuckDuckGo are trademarks of their owners. StreamWatch is not affiliated with,
+sponsored by, or endorsed by any of them, or by the LosslessSwitcher project.
+Product names are used only to describe compatibility.
diff --git a/README.md b/README.md
index b24b713..bd23834 100644
--- a/README.md
+++ b/README.md
@@ -1,6 +1,15 @@
# StreamWatch
-StreamWatch is an autonomous local-LLM research agent built to improve [RateCue](https://github.com/troylefevre65/RateCue). It watches Apple Music on a dedicated appliance over long playback sessions. For every track it compares three ways of determining sample rate and bit depth, then researches each disagreement on the appliance, in the RateCue and LosslessSwitcher code, on GitHub and through DuckDuckGo. It writes up what it finds as draft RateCue issues.
+A patient listener for Apple Music: it watches every track, compares what each method says it is, and researches the disagreements.
+
+
+
+
+
+
+
+
+StreamWatch is an autonomous local-LLM research agent built to improve [RateCue](https://github.com/troylefevre65/RateCue), the macOS menu bar app that shows Apple Music's sample rate and bit depth. It watches Apple Music on a dedicated appliance over long playback sessions. For every track it compares three ways of determining sample rate and bit depth, then researches each disagreement on the appliance, in the RateCue and LosslessSwitcher code, on GitHub and through DuckDuckGo. It writes up what it finds as draft RateCue issues.
See the [StreamWatch charter](CHARTER.md) for the authoritative mission, allowed authority, evidence doctrine, prohibited actions and human approval boundary. The agent's own system prompt implements the research subset of that charter; operations and security documentation describe the deployment boundaries.
@@ -39,11 +48,13 @@ For each track start, the `track_formats` view on the Mac puts three answers sid
| Columns | Method | Source |
|---|---|---|
-| `decoder_*` | **RateCue's method.** Music logs `fpfs_StartTrackPlaying` with a per-play lifecycle tag (`<0x…\|I/NDR.01>`), then `fpfs_ReportAudioPlaybackThroughFigLog … [SampleRate 96000] [BitDepth 24]` for the same lifecycle. The collector picks the lifecycle that started nearest the estimated playback start (observed time − player position, ±30 s). `decoder_competing` counts start/render lifecycles within 3 s, including ones that never produced a report. | `lifecycle_events` |
+| `decoder_*` | **RateCue's method.** Music logs `fpfs_StartTrackPlaying` with a per-play lifecycle tag (`<0x…\|I/NDR.01>`) when it starts buffering an item, then `fpfs_ReportAudioPlaybackThroughFigLog … [SampleRate 96000] [BitDepth 24]` for the same lifecycle when the item starts to render. The collector picks the report logged nearest the estimated playback start (observed time − player position), from 3 s before to 8 s after it. Buffering can begin minutes before the boundary, so the lifecycle's start time (`decoder_start_offset_s`, typically −10 to −25 s on a natural track change) does not place the track. A report with a rate and no depth is a lossy rendition. `decoder_competing` counts start/render lifecycles within 3 s of the selected lifecycle's start, including ones that never produced a report. | `lifecycle_events` |
| `ls_*` | **LosslessSwitcher's method.** The nearest Music `audioCapabilities` lines (`asbdSampleRate`, `sdBitDepth`) within ±20 s. | `format_events` |
-| `ratecue_*` | **What RateCue displayed**, read from its `menu-status.json` snapshot at the end of the track: title, publication status, posterior, log-evidence status, detection time. | `ratecue_status` |
+| `ratecue_*` | **What RateCue displayed**, read from the last `menu-status.json` snapshot taken while the track was current: title, publication status, posterior, log-evidence status, detection time. | `ratecue_status` |
+
+A track runs from its estimated start to the next track's. The collector notices a track change up to a poll late, so its own observation time is not the boundary: scoring by it credits the next track's first, still-unknown RateCue snapshot to the track that just ended. An earlier version of the view did that, and reported 194 of 427 plays as `ratecue_unknown` and 6 as `MISMATCH` over two days in which RateCue had never published a wrong lossless depth and had ended 139 of 399 plays without one. Two kinds of row are not plays of their own and are left out: Music showing the previous track with the new position for a moment at a boundary, and one play recorded twice.
-`ratecue_vs_decoder` and `ls_vs_decoder` classify every play as `match`, `MISMATCH`, `ratecue_unknown`/`ls_no_depth`, `no_ratecue`/`ls_none` or `no_decoder`. The agent keeps a running scorecard of these classes. Each `MISMATCH`, each unknown depth that had decoder evidence, and each missing decoder report becomes a research lead. The lead names the playback, the lifecycle, the timing and the code file to examine.
+`ratecue_vs_decoder` and `ls_vs_decoder` classify every play as `match`, `MISMATCH`, `ratecue_unknown`/`ls_no_depth`, `no_ratecue`/`ls_none` or `no_decoder`. For a lossy rendition, displaying no depth is a `match` and displaying one is a `MISMATCH`. The agent keeps a running scorecard of these classes. Each `MISMATCH`, each unknown depth that had decoder evidence, and each missing decoder report becomes a research lead. The lead names the playback, the lifecycle, the timing and the code file to examine.
**The decoder report is Music's own statement, not independent ground truth.** The agent treats it as the reference because it is the most direct evidence available. It is not the bit depth leaving the DAC.
@@ -54,6 +65,15 @@ from already-resolved tracks. When enough history exists, it predicts one and
two track starts ahead and records queue sequence confidence, predicted rate and
depth, the resolved outcome, and the actual format from `track_formats`.
+Music also announces formats itself, and the collector scores those announcements without any track
+identity. About a second into a track Music logs the highest eligible lossless variant of the next queue
+item (`queued`); when it starts buffering the item, typically 11–24 seconds before a natural track change,
+it logs the variant it chose (`prebuffered`). `queue_prediction_metrics` compares each with the item's first
+decoder report, per day and stage: hits, misses, items that played lossy, and how long before the report
+the notice was logged. Over the first two days of this deployment the chosen variant matched for all 321
+items that reported; the queued variant was wrong for 2 of 386. On a database that predates the table, the
+collector scores the lines already in `raw_log` once at startup.
+
The deterministic engine is best-effort measurement only. Music does not expose
an authoritative "Up Next" format API, so the collector cannot claim it knows a
queued rendition in advance. Persistent IDs remain only in the local collector
@@ -143,7 +163,7 @@ The agent's key is locked to `readonly_gate.py` (`command=...,restrict` in `auth
- run read-only SQL against the collector database; SQLite authorization blocks track names, artists, albums, persistent IDs and raw JSON snapshots, including aliases;
- run `log show` for the exact Music-process predicate (with `--last` up to 3 h, or `--start`/`--end` up to 3 h apart; no archives or files);
- run `system_profiler SPAudioDataType -json` (with identity-bearing fields removed), `pmset -g` and `sw_vers`;
-- run these RateCue CLI commands: `menu-status`, `log-format`, `--version` and `first-track-trace export`.
+- run these RateCue CLI commands: `menu-status`, `log-format`, `decoder-status`, `--version` and `first-track-trace export`.
It cannot get a shell, write files, inspect arbitrary preference domains, change RateCue settings, or control Music. Reinstalling with the same public key replaces any older unrestricted entry with the forced read-only command.
@@ -227,3 +247,20 @@ After editing a dedicated-box service: `sudo systemctl restart streamwatch-agent
Run `python3 -m unittest discover -s tests -v` after a change. The tests cover repeated-track detection, report association, competing lifecycle starts, stale device state, SQL privacy authorization, the agent-readable `track_formats` view, log/CLI allowlists, forced-key replacement, redirect checks, external-query redaction and transcript trimming. GitHub Actions runs these tests plus Python and shell syntax validation. Python dependencies are pinned in `llm-box/requirements.txt`.
See [OPERATIONS.md](OPERATIONS.md) for service smoke tests, troubleshooting, upgrades and a 72-hour evidence capture, and [SECURITY.md](SECURITY.md) for trust boundaries and reporting.
+
+## Project guide
+
+- [Charter](CHARTER.md): the mission, what the collector and the agent may and may not do, and the evidence doctrine.
+- [Operations](OPERATIONS.md): installation checks, smoke tests, service commands and troubleshooting.
+- [Security model](SECURITY.md): trust boundaries, private data, and how to report a vulnerability.
+- [Model selection](MODEL-SELECTION.md): choosing and switching an OpenAI-compatible model host.
+- [Contributing](CONTRIBUTING.md) and [code of conduct](CODE_OF_CONDUCT.md): the development workflow and the boundaries a change must keep.
+- [Changelog](CHANGELOG.md): what each version adds and fixes.
+
+## License and credits
+
+Copyright © 2026 the StreamWatch contributors. StreamWatch is free software, licensed under the [GNU General Public License, version 3 only](LICENSE) (`GPL-3.0-only`), and comes with no warranty. Every source file carries an SPDX identifier.
+
+StreamWatch observes [RateCue](https://github.com/troylefevre65/RateCue) and follows its decoder-lifecycle patterns. Its comparison with the log-reading method follows the patterns of [LosslessSwitcher](https://github.com/vincentneo/LosslessSwitcher), by **Vincent Neo and the LosslessSwitcher contributors**. See [NOTICE](NOTICE) for the full attribution and the licenses of the Python packages the agent installs.
+
+StreamWatch is not affiliated with or endorsed by Apple, GitHub, DuckDuckGo or the LosslessSwitcher project. Apple Music is a trademark of Apple Inc.
diff --git a/llm-box/agent.py b/llm-box/agent.py
index 538642e..3750f4e 100755
--- a/llm-box/agent.py
+++ b/llm-box/agent.py
@@ -1,4 +1,5 @@
#!/usr/bin/env python3
+# SPDX-License-Identifier: GPL-3.0-only
"""StreamWatch research agent (runs on the LLM box). Mission: improve RateCue's sample-rate/bit-depth detection.
Each cycle it:
@@ -103,11 +104,14 @@
stream_sample_rate_hz, stream_bit_depth (decoder report, else best other log source),
format_sources, codec_hints,
decoder_rate_hz, decoder_bit_depth, decoder_audio_format, decoder_lifecycle, decoder_start_offset_s,
- decoder_report_delay_s, decoder_competing (lifecycles starting within 3 s of the nearest), decoder_competing_depths
- -- RateCue's method: fpfs report of the lifecycle that started nearest est_start (+/-30 s)
+ decoder_report_delay_s, decoder_competing (lifecycles starting within 3 s of the selected one), decoder_competing_depths
+ -- RateCue's method: the fpfs report logged nearest est_start (3 s before to 8 s after). Music logs it at the
+ -- audible boundary; the lifecycle can start buffering much earlier (decoder_start_offset_s, often -10 to -25).
+ -- decoder_rate_hz set with decoder_bit_depth NULL = Music reported a lossy rendition (no source depth).
ls_rate_hz, ls_bit_depth, ls_codec_hint -- LosslessSwitcher's method: nearest 'audioCapabilities' line (+/-20 s)
ratecue_title, ratecue_rate_hz, ratecue_depth, ratecue_publication, ratecue_posterior24, ratecue_log_status,
- ratecue_depth_ms -- what the RateCue menu app displayed at the end of the track
+ ratecue_depth_ms -- the last RateCue snapshot taken while this track was current
+ -- (between its est_start and the next track's est_start)
ratecue_vs_decoder ('match'|'MISMATCH'|'ratecue_unknown'|'no_ratecue'|'no_decoder'),
ls_vs_decoder ('match'|'MISMATCH'|'ls_no_depth'|'ls_none'|'no_decoder'),
device_sample_rate_hz, device_transport, device_sample_age_s
@@ -125,6 +129,13 @@
sequence_hits, sequence_misses, rate_hits, rate_misses, depth_hits, depth_misses,
mean_sequence_confidence, mean_observed_after_s. No track ID, exact time or per-play row is exposed.
Predictions are best-effort queue-sequence measurements; they never authorize a RateCue or device action.
+- queue_prediction_metrics (VIEW, aggregate only): metric_date, stage ('queued' = highest eligible lossless variant,
+ logged when Music queues an item | 'prebuffered' = the variant Music chose, logged when it starts buffering the
+ item), prediction_count, unresolved_count (item never reported), format_hits, format_misses, rate_misses,
+ depth_misses, played_lossy, lead_under_1s (skips: notice and report arrive together), mean_lead_s, min_lead_s.
+ Music's own advance notice of a queue item's format, scored against that item's first decoder report.
+- queue_predictions: id, ts, lifecycle, stage, sample_rate_hz, bit_depth (the notices themselves; join
+ lifecycle_events on lifecycle for the reports)
- raw_log: id, ts, subsystem, category, message (audio-related unified-log lines from the Music process, 30-day retention)
- collector_health: ts, component, message
diff --git a/llm-box/model_eval_seed.py b/llm-box/model_eval_seed.py
index a1f73d1..50fdc4d 100644
--- a/llm-box/model_eval_seed.py
+++ b/llm-box/model_eval_seed.py
@@ -1,4 +1,5 @@
#!/usr/bin/env python3
+# SPDX-License-Identifier: GPL-3.0-only
"""Clone an archived agent database and seed the fixed model-comparison leads."""
import argparse
import os
diff --git a/llm-box/model_smoke_test.py b/llm-box/model_smoke_test.py
index 969801a..307c600 100644
--- a/llm-box/model_smoke_test.py
+++ b/llm-box/model_smoke_test.py
@@ -1,4 +1,5 @@
#!/usr/bin/env python3
+# SPDX-License-Identifier: GPL-3.0-only
"""Verify an OpenAI-compatible endpoint can run a StreamWatch tool cycle."""
import argparse
import json
diff --git a/llm-box/provision.sh b/llm-box/provision.sh
index c3cc5c9..d11b768 100755
--- a/llm-box/provision.sh
+++ b/llm-box/provision.sh
@@ -1,4 +1,5 @@
#!/usr/bin/env bash
+# SPDX-License-Identifier: GPL-3.0-only
# Provisions the dedicated Linux model host for StreamWatch.
# Run from the llm-box folder: sudo MAC_SSH=@ LAN_CIDR= ./provision.sh
# Re-run after the reboot that follows the NVIDIA driver install. The script is safe to run repeatedly.
diff --git a/llm-box/start-model-host.ps1 b/llm-box/start-model-host.ps1
index 0f9a675..b772b9f 100644
--- a/llm-box/start-model-host.ps1
+++ b/llm-box/start-model-host.ps1
@@ -1,3 +1,4 @@
+# SPDX-License-Identifier: GPL-3.0-only
[CmdletBinding()]
param(
[Parameter(Mandatory)]
diff --git a/mac/authorize-key.sh b/mac/authorize-key.sh
index ccc41d4..b059e15 100755
--- a/mac/authorize-key.sh
+++ b/mac/authorize-key.sh
@@ -1,4 +1,5 @@
#!/bin/bash
+# SPDX-License-Identifier: GPL-3.0-only
# Install an LLM-box public key behind StreamWatch's forced read-only command.
set -euo pipefail
diff --git a/mac/collector.py b/mac/collector.py
index d700108..5b62ed1 100755
--- a/mac/collector.py
+++ b/mac/collector.py
@@ -1,4 +1,5 @@
#!/usr/bin/env python3
+# SPDX-License-Identifier: GPL-3.0-only
"""StreamWatch collector for the macOS streaming appliance.
Continuously records, into one SQLite database:
@@ -112,6 +113,14 @@
CREATE INDEX IF NOT EXISTS prediction_events_anchor
ON prediction_events(anchor_playback_id);
+-- What Music itself logged about a queue item before it played. stage 'queued' is the highest eligible
+-- lossless variant, logged when the item is queued; 'prebuffered' is the variant Music chose, logged when it
+-- starts buffering the item (seconds before a natural track change). Scored against the item's first report.
+CREATE TABLE IF NOT EXISTS queue_predictions(
+ id INTEGER PRIMARY KEY, ts REAL NOT NULL, lifecycle TEXT NOT NULL, stage TEXT NOT NULL,
+ sample_rate_hz REAL, bit_depth INTEGER);
+CREATE INDEX IF NOT EXISTS queue_predictions_lc ON queue_predictions(lifecycle, ts);
+
CREATE TABLE IF NOT EXISTS device_state(
id INTEGER PRIMARY KEY, ts REAL NOT NULL, name TEXT, sample_rate_hz REAL, transport TEXT,
output_channels INTEGER, raw_json TEXT);
@@ -120,25 +129,45 @@
CREATE TABLE IF NOT EXISTS collector_health(ts REAL NOT NULL, component TEXT, message TEXT);
-- One row per observed track start comparing three methods for the same play:
--- decoder_* RateCue's method: the fpfs report whose lifecycle started nearest the estimated playback start
--- (est_start = observed time - player position), within 30 s; decoder_competing > 1 means other
--- lifecycles started within 3 s of the nearest one (RateCue's ambiguity margin).
+-- decoder_* RateCue's method: the fpfs report logged nearest the estimated playback start
+-- (est_start = observed time - player position), from 3 s before to 8 s after it. Music logs the
+-- report at the audible boundary; the lifecycle itself can start buffering minutes earlier, so its
+-- start time does not place the track. A report with a rate but no depth is a lossy rendition.
+-- decoder_competing > 1 means other lifecycles started within 3 s of the selected one's start.
-- ls_* LosslessSwitcher's method: nearest Music 'audioCapabilities' line within 20 s.
--- ratecue_* what the RateCue menu app displayed when the track ended (or now, for the current track).
+-- ratecue_* the last thing the RateCue menu app displayed while this track was current: the latest snapshot
+-- taken between this track's est_start and the next track's est_start. RateCue stamps a snapshot
+-- to the whole second, so both ends are a second early: a snapshot within a second of a boundary
+-- is nearly always the new track's first, and a later one in the same track supersedes it.
+-- A track runs from its est_start to the next one's. The collector sees a track change up to a poll late, so
+-- its own observation time is not the boundary: using it credits the next track's first snapshot to this one.
+-- Two rows are not plays of their own: Music showing the previous track with the new position for a moment
+-- (a start within 3 s of the next one, for a different track), and one play recorded twice. Tracks are told
+-- apart by duration, which is not private; a track skipped within 3 s is dropped by the same rule.
-- stream_* prefers the decoder report, then the best other log source. None of these is independent ground truth.
-- (SQLite cannot reference the outer row in a correlated subquery's ORDER BY, hence the window functions.)
DROP VIEW IF EXISTS track_formats;
CREATE VIEW track_formats AS
-WITH starts AS (
- SELECT p.id, p.ts, p.duration, p.position, p.track_class,
- p.ts - CASE WHEN p.position BETWEEN 0 AND 86400 THEN p.position ELSE 0 END AS est_start,
- min(coalesce(lead(p.ts) OVER (ORDER BY p.ts), 1e12), p.ts + coalesce(p.duration, 600) + 10) AS end_ts
+WITH observed AS (
+ SELECT p.id, p.ts, p.duration, p.position, p.track_class, coalesce(p.duration, -1) AS track,
+ p.ts - CASE WHEN p.position BETWEEN 0 AND 86400 THEN p.position ELSE 0 END AS est_start
FROM playback_events p WHERE p.kind = 'track_start'),
+neighbors AS (
+ SELECT o.*, lead(o.est_start) OVER (ORDER BY o.ts) AS next_est, lead(o.track) OVER (ORDER BY o.ts) AS next_track,
+ lag(o.est_start) OVER (ORDER BY o.ts) AS prev_est, lag(o.track) OVER (ORDER BY o.ts) AS prev_track
+ FROM observed o),
+starts AS (
+ SELECT n.id, n.ts, n.duration, n.position, n.track_class, n.est_start,
+ min(coalesce(lead(n.est_start) OVER (ORDER BY n.ts), 1e12),
+ n.est_start + coalesce(n.duration, 600) + 10) AS end_ts
+ FROM neighbors n
+ WHERE NOT (n.next_est IS NOT NULL AND abs(n.next_est - n.est_start) < 3 AND n.next_track <> n.track)
+ AND NOT (n.prev_est IS NOT NULL AND abs(n.prev_est - n.est_start) < 3 AND n.prev_track = n.track)),
dec AS (
SELECT s.id AS pid, r.lifecycle, r.sample_rate_hz, r.bit_depth, r.audio_format, r.ts AS report_ts,
- r.start_ts, abs(r.start_ts - s.est_start) AS dist
+ r.start_ts, abs(r.ts - s.est_start) AS dist
FROM starts s JOIN lifecycle_events r
- ON r.kind = 'report' AND r.start_ts BETWEEN s.est_start - 30 AND s.est_start + 30),
+ ON r.kind = 'report' AND r.ts BETWEEN s.est_start - 3 AND s.est_start + 8),
dec_rank AS (
SELECT d.*, row_number() OVER (PARTITION BY pid ORDER BY dist, report_ts DESC) AS rn,
min(dist) OVER (PARTITION BY pid) AS mind FROM dec d),
@@ -181,8 +210,11 @@
FROM near GROUP BY pid),
joined AS (
SELECT s.*,
- (SELECT r.id FROM ratecue_status r WHERE r.ts <= s.end_ts - 1 AND r.ts >= s.ts - 3600
- ORDER BY r.ts DESC LIMIT 1) AS rc_id,
+ (SELECT r.id FROM ratecue_status r
+ WHERE r.ts BETWEEN s.est_start - 1 AND s.end_ts + 10
+ AND coalesce(r.snapshot_ts, r.ts) >= s.est_start - 1
+ AND coalesce(r.snapshot_ts, r.ts) < s.end_ts - 1
+ ORDER BY coalesce(r.snapshot_ts, r.ts) DESC, r.id DESC LIMIT 1) AS rc_id,
(SELECT d.id FROM device_state d
WHERE d.ts BETWEEN s.ts - 30 AND s.ts + 5
ORDER BY d.ts DESC LIMIT 1) AS dev_id
@@ -214,12 +246,15 @@
rc.posterior24 AS ratecue_posterior24,
rc.log_evidence_status AS ratecue_log_status,
rc.depth_detection_ms AS ratecue_depth_ms,
- CASE WHEN dr.bit_depth IS NULL THEN 'no_decoder'
+ CASE WHEN dr.pid IS NULL THEN 'no_decoder'
WHEN rc.id IS NULL OR rc.publication_status = 'stale' THEN 'no_ratecue'
+ -- A lossy rendition has no source depth: showing one is a mismatch, showing none is right.
+ WHEN dr.bit_depth IS NULL THEN CASE WHEN rc.display_depth IS NULL THEN 'match' ELSE 'MISMATCH' END
WHEN rc.display_depth IS NULL THEN 'ratecue_unknown'
WHEN rc.display_depth = dr.bit_depth THEN 'match' ELSE 'MISMATCH' END AS ratecue_vs_decoder,
- CASE WHEN dr.bit_depth IS NULL THEN 'no_decoder'
+ CASE WHEN dr.pid IS NULL THEN 'no_decoder'
WHEN l.pid IS NULL THEN 'ls_none'
+ WHEN dr.bit_depth IS NULL THEN CASE WHEN l.bit_depth IS NULL THEN 'match' ELSE 'MISMATCH' END
WHEN l.bit_depth IS NULL THEN 'ls_no_depth'
WHEN l.bit_depth = dr.bit_depth THEN 'match' ELSE 'MISMATCH' END AS ls_vs_decoder,
dv.sample_rate_hz AS device_sample_rate_hz,
@@ -264,6 +299,46 @@
FROM prediction_events p
LEFT JOIN track_formats tf ON tf.playback_id = p.resolved_playback_id
GROUP BY metric_date, p.horizon;
+
+-- Music's own advance notice of a queue item's format, scored against that item's first decoder report.
+-- One prediction per lifecycle and stage (the first). lead_s is how long before the report it was logged:
+-- a 'prebuffered' lead under a second is a skip, where the notice and the report arrive together.
+-- No track identity is involved; a hit is historical evidence, never permission to change audio hardware.
+DROP VIEW IF EXISTS queue_prediction_metrics;
+CREATE VIEW queue_prediction_metrics AS
+WITH first_report AS (
+ SELECT lifecycle, min(ts) AS ts FROM lifecycle_events WHERE kind = 'report' GROUP BY lifecycle),
+actual AS (
+ SELECT f.lifecycle, f.ts, max(e.sample_rate_hz) AS sample_rate_hz, max(e.bit_depth) AS bit_depth
+ FROM first_report f JOIN lifecycle_events e
+ ON e.kind = 'report' AND e.lifecycle = f.lifecycle AND e.ts = f.ts
+ GROUP BY f.lifecycle, f.ts),
+first_prediction AS (
+ SELECT lifecycle, stage, min(ts) AS ts FROM queue_predictions GROUP BY lifecycle, stage),
+scored AS (
+ SELECT q.ts, q.stage, q.sample_rate_hz, q.bit_depth, a.ts AS report_ts,
+ a.sample_rate_hz AS actual_rate_hz, a.bit_depth AS actual_bit_depth
+ FROM first_prediction f
+ JOIN queue_predictions q ON q.lifecycle = f.lifecycle AND q.stage = f.stage AND q.ts = f.ts
+ LEFT JOIN actual a ON a.lifecycle = q.lifecycle AND a.ts >= q.ts AND a.ts - q.ts <= 3600)
+SELECT date(ts, 'unixepoch', 'localtime') AS metric_date,
+ stage,
+ count(*) AS prediction_count,
+ sum(CASE WHEN report_ts IS NULL THEN 1 ELSE 0 END) AS unresolved_count,
+ sum(CASE WHEN report_ts IS NOT NULL AND abs(actual_rate_hz - sample_rate_hz) < 0.5
+ AND actual_bit_depth IS bit_depth THEN 1 ELSE 0 END) AS format_hits,
+ sum(CASE WHEN report_ts IS NOT NULL AND NOT (abs(actual_rate_hz - sample_rate_hz) < 0.5
+ AND actual_bit_depth IS bit_depth) THEN 1 ELSE 0 END) AS format_misses,
+ sum(CASE WHEN report_ts IS NOT NULL AND abs(actual_rate_hz - sample_rate_hz) >= 0.5
+ THEN 1 ELSE 0 END) AS rate_misses,
+ sum(CASE WHEN report_ts IS NOT NULL AND actual_bit_depth IS NOT bit_depth
+ THEN 1 ELSE 0 END) AS depth_misses,
+ sum(CASE WHEN report_ts IS NOT NULL AND actual_bit_depth IS NULL THEN 1 ELSE 0 END) AS played_lossy,
+ sum(CASE WHEN report_ts - ts < 1 THEN 1 ELSE 0 END) AS lead_under_1s,
+ round(avg(CASE WHEN report_ts - ts >= 1 THEN report_ts - ts END), 3) AS mean_lead_s,
+ round(min(CASE WHEN report_ts - ts >= 1 THEN report_ts - ts END), 3) AS min_lead_s
+FROM scored
+GROUP BY metric_date, stage;
"""
# Columns added after the first release; ALTER is skipped when they already exist.
@@ -340,7 +415,9 @@ class FormatParser:
ALAC_BD = re.compile(r"from\s+(\d+)-bit source")
AQ_SR = re.compile(r"sampleRate:\s*([\d.]+)")
LIFECYCLE = re.compile(r"<([^<>]*\|I/[A-Z0-9.]+)>")
- REPORT = re.compile(r"\[SampleRate ([0-9]{5,6})\] \[BitDepth (8|16|20|24|32)\]")
+ REPORT = re.compile(r"\[SampleRate ([0-9]{4,6})\] \[BitDepth ([0-9]{1,2})\]")
+ LOSSLESS_DEPTHS = (16, 20, 24, 32)
+ LOSSLESS_VARIANT = re.compile(r"AudioGroup audio-alac-stereo-([0-9]{5,6})-(16|20|24|32)\]")
REPORT_FORMAT = re.compile(r"\[AudioFormat (\w+)")
REPORT_RENDITION = re.compile(r"\[Rendition ([^\]]+)\]")
AUDIO_GROUP = re.compile(r"AudioGroup audio-([a-z0-9]+)-([a-z0-9]+)-([0-9]{5,6})(?:-(8|16|20|24|32)(?![0-9]))?")
@@ -360,6 +437,9 @@ def _lifecycle(self, ts, message):
del self.starts[key]
kind = "render" if "ordered rendering" in message else "start"
rows.append(("lifecycle_events", dict(lifecycle=lifecycle, kind=kind, raw_message=message[:1000])))
+ prediction = self.queue_prediction(message, lifecycle)
+ if prediction:
+ rows.append(("queue_predictions", prediction))
report = self.REPORT.search(message) if "fpfs_ReportAudioPlaybackThroughFigLog" in message else None
if report and lifecycle:
start = self.starts.get(lifecycle)
@@ -367,7 +447,9 @@ def _lifecycle(self, ts, message):
start = None
fmt = self.REPORT_FORMAT.search(message)
rendition = self.REPORT_RENDITION.search(message)
+ # Music reports a zero depth for a lossy rendition: the rate stands, there is no source depth.
rate, depth = float(report.group(1)), int(report.group(2))
+ depth = depth if depth in self.LOSSLESS_DEPTHS else None
rows.append(("lifecycle_events", dict(
lifecycle=lifecycle, kind="report", start_ts=start, sample_rate_hz=rate, bit_depth=depth,
audio_format=fmt.group(1) if fmt else None, rendition=rendition.group(1) if rendition else None,
@@ -383,6 +465,23 @@ def _lifecycle(self, ts, message):
codec_hint=f"{group.group(1)}-{group.group(2)}", raw_message=message[:2000])))
return rows
+ @classmethod
+ def queue_prediction(cls, message, lifecycle):
+ """The lossless variant Music logged for a queue item before it played, if this line carries one."""
+ if not lifecycle:
+ return None
+ if "fpfsi_logHighestEligibleAlternate" in message:
+ stage = "queued"
+ elif "fpfs_StartTrackPlaying" in message and "playback switches" in message:
+ stage = "prebuffered"
+ else:
+ return None
+ variant = cls.LOSSLESS_VARIANT.search(message)
+ if not variant:
+ return None
+ return dict(lifecycle=lifecycle, stage=stage,
+ sample_rate_hz=float(variant.group(1)), bit_depth=int(variant.group(2)))
+
def feed(self, ts, message):
rows = self._lifecycle(ts, message)
events = []
@@ -597,13 +696,15 @@ def observe_start(self, playback_id, persistent_id, at):
def parse_menu_title(title):
- """RateCue's menu title, e.g. '≈96k / 24', '44.1k / 16', '≈96k / —', '⚠ — / —', 'RateCue'."""
+ """RateCue's menu title: '96 kHz / 24-bit', '≈44.1 kHz / —', '44.1 kHz / lossy', '⚠ — / —', 'RateCue'.
+
+ Before RateCue 0.2 it read '≈96k / 24'. Both are understood, for snapshots without explicit fields."""
rate = depth = None
if title:
- m = re.search(r"([\d.]+)k\b", title)
+ m = re.search(r"([\d.]+)\s?k(?:Hz)?\b", title)
if m:
rate = float(m.group(1)) * 1000.0
- m = re.search(r"/\s*(\d{1,2})\b", title)
+ m = re.search(r"/\s*(\d{1,2})(?:-bit)?\b", title)
if m:
depth = int(m.group(1))
return rate, depth
@@ -618,6 +719,12 @@ def parse_iso(text):
def ratecue_row(snapshot):
rate, depth = parse_menu_title(snapshot.get("menuTitle"))
+ if snapshot.get("certaintyLevel") is not None:
+ # RateCue 0.2 states the displayed format as numbers; a lossy or unknown depth is null.
+ shown = snapshot.get("displayRateHz")
+ rate = float(shown) if isinstance(shown, (int, float)) else None
+ shown = snapshot.get("displayBitDepth")
+ depth = int(shown) if isinstance(shown, (int, float)) else None
return dict(
snapshot_ts=parse_iso(snapshot.get("snapshotAt")), pid=snapshot.get("processIdentifier"),
menu_title=snapshot.get("menuTitle"), display_rate_hz=rate, display_depth=depth,
@@ -649,10 +756,67 @@ def is_track_start(state, name, key, position, last_key, last_position, last_sta
)
+class RestartDebounce:
+ """Music can show the previous track with the next track's position for a moment at a boundary.
+
+ A restart of the same track is therefore recorded only once a second poll still shows that track, with
+ the time and fields of the first poll, so its estimated start is unchanged. A different track is
+ recorded at once."""
+
+ def __init__(self):
+ self.pending = None
+
+ @property
+ def holding(self):
+ return self.pending is not None
+
+ def observe(self, started, same_track, now, fields):
+ """Returns (ts, fields) for a track start to record now, else None."""
+ if not started:
+ self.pending = None
+ return None
+ if not same_track:
+ self.pending = None
+ return now, fields
+ if self.pending is None:
+ self.pending = (now, fields)
+ return None
+ first, self.pending = self.pending, None
+ return first
+
+
+def backfill_queue_predictions(store):
+ """Scores Music's advance notices already kept in raw_log, once, for a database that predates the table."""
+ with store.lock:
+ if store.conn.execute("SELECT 1 FROM queue_predictions LIMIT 1").fetchone():
+ return 0
+ rows = store.conn.execute(
+ "SELECT ts, message FROM raw_log WHERE message LIKE '%fpfs_StartTrackPlaying%' "
+ "OR message LIKE '%fpfsi_logHighestEligibleAlternate%' ORDER BY ts").fetchall()
+ added = 0
+ for ts, message in rows:
+ lifecycle = FormatParser.LIFECYCLE.search(message or "")
+ prediction = FormatParser.queue_prediction(message or "", lifecycle.group(1) if lifecycle else None)
+ if prediction:
+ store.conn.execute(
+ "INSERT INTO queue_predictions(ts, lifecycle, stage, sample_rate_hz, bit_depth) VALUES(?,?,?,?,?)",
+ (ts, prediction["lifecycle"], prediction["stage"], prediction["sample_rate_hz"],
+ prediction["bit_depth"]))
+ added += 1
+ store.conn.commit()
+ return added
+
+
class Collector:
def __init__(self, store):
self.store = store
self.prediction = PredictionModel(store)
+ try:
+ added = backfill_queue_predictions(store)
+ if added:
+ store.health("prediction", f"scored {added} queue notices already in raw_log")
+ except sqlite3.Error as e:
+ store.health("prediction", e)
self.stop = threading.Event()
self.procs = []
@@ -718,6 +882,7 @@ def now_playing():
def nowplaying_loop(self):
last_key, last_position, last_state, last_beat, last_error = None, None, None, 0.0, None
+ restart = RestartDebounce()
while not self.stop.is_set():
try:
info = self.now_playing()
@@ -728,17 +893,24 @@ def nowplaying_loop(self):
fields = {k: info.get(k) for k in ("name", "artist", "album", "persistent_id", "duration",
"position", "track_class")}
position = info.get("position")
- if is_track_start(
+ started = is_track_start(
state, info.get("name"), key, position, last_key, last_position, last_state
- ):
+ )
+ record = restart.observe(started, key == last_key, now, fields)
+ if record:
+ start_ts, start_fields = record
playback_id = self.store.insert(
- "playback_events", ts=now, kind="track_start", state=state, **fields
+ "playback_events", ts=start_ts, kind="track_start", state=state, **start_fields
)
last_key, last_beat = key, now
try:
- self.prediction.observe_start(playback_id, info.get("persistent_id"), now)
+ self.prediction.observe_start(playback_id, start_fields.get("persistent_id"), start_ts)
except Exception as prediction_error:
self.store.health("prediction", prediction_error)
+ elif restart.holding:
+ # Keep the earlier position so the next poll can still tell a restart from a track change.
+ self.stop.wait(NOWPLAYING_INTERVAL)
+ continue
elif state != last_state:
self.store.insert("playback_events", ts=now, kind="state", state=state, **fields)
if state in ("stopped", "not_running"):
diff --git a/mac/install.sh b/mac/install.sh
index f9f029c..70e2f4e 100755
--- a/mac/install.sh
+++ b/mac/install.sh
@@ -1,4 +1,5 @@
#!/bin/bash
+# SPDX-License-Identifier: GPL-3.0-only
# Installs the StreamWatch collector on the macOS appliance.
# Usage: ./install.sh # collector only
# ./install.sh "ssh-ed25519 AAAA... streamwatch-agent" # also authorize the LLM box's key
diff --git a/mac/readonly_gate.py b/mac/readonly_gate.py
index bcea34e..c0458bf 100755
--- a/mac/readonly_gate.py
+++ b/mac/readonly_gate.py
@@ -1,4 +1,5 @@
#!/usr/bin/env python3
+# SPDX-License-Identifier: GPL-3.0-only
"""Forced-command SSH gate for the StreamWatch agent.
The LLM box's SSH key is installed with command="... readonly_gate.py",restrict so it can only
@@ -38,7 +39,7 @@
}
# RateCue CLI subcommands that only return format diagnostics without preferences or device identifiers.
RATECUE_READONLY = [["--version"], ["version"], ["--help"], ["menu-status"], ["log-format"],
- ["first-track-trace", "export"]]
+ ["decoder-status"], ["first-track-trace", "export"]]
LOG_TIME_FORMATS = ("%Y-%m-%d %H:%M:%S%z", "%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M:%S.%f%z", "%Y-%m-%d %H:%M:%S.%f")
SENSITIVE_COLUMNS = {
"name", "artist", "album", "persistent_id", "raw_json",
diff --git a/tests/test_streamwatch.py b/tests/test_streamwatch.py
index 03dbd2e..9a0a5f5 100644
--- a/tests/test_streamwatch.py
+++ b/tests/test_streamwatch.py
@@ -1,3 +1,4 @@
+# SPDX-License-Identifier: GPL-3.0-only
import importlib.util
import json
import pathlib
@@ -202,6 +203,254 @@ def test_view_counts_reportless_competing_start_and_bounds_device_age(self):
store.conn.close()
+class RateCueSnapshotTests(unittest.TestCase):
+ def test_menu_title_is_read_in_both_formats(self):
+ self.assertEqual(collector.parse_menu_title("96 kHz / 24-bit"), (96000.0, 24))
+ self.assertEqual(collector.parse_menu_title("≈44.1 kHz / —"), (44100.0, None))
+ self.assertEqual(collector.parse_menu_title("44.1 kHz / lossy"), (44100.0, None))
+ self.assertEqual(collector.parse_menu_title("⚠ 176.4 kHz / 24-bit"), (176400.0, 24))
+ self.assertEqual(collector.parse_menu_title("⚠ — / —"), (None, None))
+ self.assertEqual(collector.parse_menu_title("RateCue"), (None, None))
+ # Before RateCue 0.2.
+ self.assertEqual(collector.parse_menu_title("≈96k / 24"), (96000.0, 24))
+ self.assertEqual(collector.parse_menu_title("44.1k / 16"), (44100.0, 16))
+ self.assertEqual(collector.parse_menu_title("≈96k / —"), (96000.0, None))
+
+ def test_explicit_display_fields_win_over_the_title(self):
+ row = collector.ratecue_row({
+ "menuTitle": "24-bit", "certainty": "Confirmed by Music's decoder", "certaintyLevel": "decoderConfirmed",
+ "displayRateHz": 96000, "displayBitDepth": 24, "displayLossy": False, "publicationStatus": "published",
+ })
+ self.assertEqual((row["display_rate_hz"], row["display_depth"]), (96000.0, 24))
+ self.assertEqual(row["certainty"], "Confirmed by Music's decoder")
+ lossy = collector.ratecue_row({
+ "menuTitle": "44.1 kHz / lossy", "certaintyLevel": "decoderConfirmed",
+ "displayRateHz": 44100, "displayBitDepth": None, "displayLossy": True,
+ })
+ self.assertEqual((lossy["display_rate_hz"], lossy["display_depth"]), (44100.0, None))
+ # A snapshot from an earlier RateCue has only the title.
+ old = collector.ratecue_row({"menuTitle": "≈44.1k / 16", "publicationStatus": "published"})
+ self.assertEqual((old["display_rate_hz"], old["display_depth"]), (44100.0, 16))
+
+
+class TrackBoundaryTests(unittest.TestCase):
+ """track_formats credits each RateCue snapshot and decoder report to the track that was playing."""
+
+ @staticmethod
+ def start(store, ts, position, duration, track="track"):
+ return store.insert(
+ "playback_events", ts=ts, kind="track_start", state="playing", name=track, artist="a", album="b",
+ persistent_id=track, duration=duration, position=position, track_class="track",
+ )
+
+ @staticmethod
+ def report(store, ts, lifecycle, depth, start_ts=None, rate=44100.0):
+ store.insert(
+ "lifecycle_events", ts=ts, lifecycle=lifecycle, kind="report", start_ts=start_ts,
+ sample_rate_hz=rate, bit_depth=depth, audio_format="qlac", rendition="Lossless", raw_message="report",
+ )
+
+ @staticmethod
+ def snapshot(store, ts, depth, status="published"):
+ store.insert(
+ "ratecue_status", ts=ts + 0.6, snapshot_ts=float(int(ts)), menu_title="title",
+ display_rate_hz=44100.0, display_depth=depth, publication_status=status,
+ )
+
+ @staticmethod
+ def rows(store):
+ cursor = store.conn.execute("SELECT * FROM track_formats ORDER BY started")
+ names = [column[0] for column in cursor.description]
+ return [dict(zip(names, row)) for row in cursor.fetchall()]
+
+ def test_next_tracks_first_snapshot_is_not_credited_to_the_previous_track(self):
+ with tempfile.TemporaryDirectory() as temp:
+ store = collector.Store(str(pathlib.Path(temp) / "streamwatch.db"))
+ # The collector polls every 2 s, so it sees each track 2.6 s after it began.
+ first = self.start(store, 1002.6, 2.6, 240.0, "first")
+ second = self.start(store, 1242.6, 2.6, 200.0, "second")
+ self.report(store, 999.97, "A|I/AAA.01", 16, start_ts=980.0)
+ self.report(store, 1239.97, "B|I/BBB.01", 24, start_ts=1221.0)
+ # RateCue: unknown for a second, then the depth, for each track.
+ self.snapshot(store, 1000.3, None, "priorOnly")
+ self.snapshot(store, 1001.2, 16)
+ self.snapshot(store, 1240.3, None, "priorOnly")
+ self.snapshot(store, 1241.2, 24)
+ rows = {row["playback_id"]: row for row in self.rows(store)}
+ # The second track's first, still-unknown snapshot was taken before the collector saw that track.
+ self.assertEqual(rows[first]["ratecue_depth"], 16)
+ self.assertEqual(rows[first]["ratecue_vs_decoder"], "match")
+ self.assertEqual(rows[second]["ratecue_depth"], 24)
+ self.assertEqual(rows[second]["ratecue_vs_decoder"], "match")
+ # The decoder report is found by its own time, however early the lifecycle began buffering.
+ self.assertEqual(rows[first]["decoder_start_offset_s"], -20.0)
+ self.assertEqual(rows[first]["decoder_report_delay_s"], -0.03)
+ store.conn.close()
+
+ def test_depth_lost_mid_track_is_what_ratecue_displayed_at_the_end(self):
+ with tempfile.TemporaryDirectory() as temp:
+ store = collector.Store(str(pathlib.Path(temp) / "streamwatch.db"))
+ first = self.start(store, 1000.5, 0.5, 240.0, "first")
+ self.start(store, 1240.5, 0.5, 200.0, "second")
+ self.report(store, 1000.0, "A|I/AAA.01", 16)
+ self.snapshot(store, 1001.2, 16)
+ self.snapshot(store, 1100.0, None, "priorOnly")
+ row = next(row for row in self.rows(store) if row["playback_id"] == first)
+ self.assertEqual(row["ratecue_vs_decoder"], "ratecue_unknown")
+ store.conn.close()
+
+ def test_report_without_a_recorded_start_and_lossy_reports_are_scored(self):
+ with tempfile.TemporaryDirectory() as temp:
+ store = collector.Store(str(pathlib.Path(temp) / "streamwatch.db"))
+ lossless = self.start(store, 1000.5, 0.5, 240.0, "lossless")
+ lossy_shown = self.start(store, 1240.5, 0.5, 200.0, "lossy shown as 16")
+ lossy_blank = self.start(store, 1440.5, 0.5, 210.0, "lossy shown blank")
+ silent = self.start(store, 1650.5, 0.5, 180.0, "no report")
+ self.report(store, 1000.0, "A|I/AAA.01", 24) # the poll missed its start line
+ self.report(store, 1240.0, "B|I/BBB.01", None) # Music reported a zero depth
+ self.report(store, 1440.0, "C|I/CCC.01", None)
+ self.snapshot(store, 1001.0, 24)
+ self.snapshot(store, 1241.0, 16)
+ self.snapshot(store, 1441.0, None, "priorOnly")
+ self.snapshot(store, 1651.0, 16)
+ rows = {row["playback_id"]: row for row in self.rows(store)}
+ self.assertEqual(rows[lossless]["ratecue_vs_decoder"], "match")
+ self.assertEqual(rows[lossless]["decoder_bit_depth"], 24)
+ # A lossy rendition has no source depth: displaying one is wrong, displaying none is right.
+ self.assertEqual(rows[lossy_shown]["decoder_rate_hz"], 44100.0)
+ self.assertIsNone(rows[lossy_shown]["decoder_bit_depth"])
+ self.assertEqual(rows[lossy_shown]["ratecue_vs_decoder"], "MISMATCH")
+ self.assertEqual(rows[lossy_blank]["ratecue_vs_decoder"], "match")
+ self.assertEqual(rows[silent]["ratecue_vs_decoder"], "no_decoder")
+ store.conn.close()
+
+ def test_previous_track_shown_with_the_new_position_is_not_a_play_of_its_own(self):
+ with tempfile.TemporaryDirectory() as temp:
+ store = collector.Store(str(pathlib.Path(temp) / "streamwatch.db"))
+ first = self.start(store, 1000.5, 0.5, 278.0, "first")
+ # At the boundary Music showed the first track with the second track's position...
+ ghost = self.start(store, 1279.2, 0.7, 278.0, "first")
+ second = self.start(store, 1283.0, 4.5, 240.0, "second")
+ # ...and after a collector restart the same play was recorded again.
+ again = self.start(store, 1340.0, 61.5, 240.0, "second")
+ third = self.start(store, 1520.5, 2.0, 200.0, "third")
+ ids = [row["playback_id"] for row in self.rows(store)]
+ self.assertEqual(ids, [first, second, third])
+ self.assertNotIn(ghost, ids)
+ self.assertNotIn(again, ids)
+ store.conn.close()
+
+ def test_same_track_restart_is_recorded_only_once_a_second_poll_confirms_it(self):
+ fields = {"persistent_id": "first", "position": 0.7}
+ later = {"persistent_id": "first", "position": 2.7}
+ other = {"persistent_id": "second", "position": 2.9}
+ # Music moved on to another track: only that track is recorded.
+ debounce = collector.RestartDebounce()
+ self.assertIsNone(debounce.observe(True, True, 100.0, fields))
+ self.assertTrue(debounce.holding)
+ self.assertEqual(debounce.observe(True, False, 102.0, other), (102.0, other))
+ self.assertFalse(debounce.holding)
+ # The track really restarted: it is recorded with the time and position of the first poll.
+ debounce = collector.RestartDebounce()
+ self.assertIsNone(debounce.observe(True, True, 100.0, fields))
+ self.assertEqual(debounce.observe(True, True, 102.0, later), (100.0, fields))
+ self.assertFalse(debounce.holding)
+ # A different track is never held back, and a poll without a start clears a pending restart.
+ self.assertEqual(debounce.observe(True, False, 200.0, other), (200.0, other))
+ self.assertIsNone(debounce.observe(True, True, 300.0, fields))
+ self.assertIsNone(debounce.observe(False, True, 302.0, later))
+ self.assertFalse(debounce.holding)
+
+
+class QueuePredictionTests(unittest.TestCase):
+ """Music's own advance notice of a queue item's format, scored against the item's first report."""
+
+ QUEUED = ("<<<< FigStreamPlayer >>>> fpfsi_logHighestEligibleAlternate: [QE Critical][0x7ba4dfe400|P/ZA]: "
+ "<0x7bb5e55c00|I/DSN.01>: Highest peak bitrate Alternate\n")
+ START = ("<<<< FigStreamPlayer >>>> fpfs_StartTrackPlaying: [QE Critical][0x7ba4dfe400|P/ZA]: "
+ "<0x7bb5e55c00|I/DSN.01>: (2171): playback switches; startTime nan desiredRate is 1.000000 "
+ "rate 0.000000 at currentTime 0.000000 track 1 first image 0 Variant []")
+ REPORT = ("<<<< FigStreamPlayer >>>> fpfs_ReportAudioPlaybackThroughFigLog: [QE Critical]"
+ "[0x7ba4dfe400|P/ZA]: <0x7bb5e55c00|I/DSN.01>: [AudioFormat qlac is decodable] [AudioChannels 2] "
+ "[Rendition Lossless] [SampleRate 48000] [BitDepth 24] [Immersive rendering no]")
+
+ def predictions(self, parser, ts, message):
+ return [row for table, row in parser.feed(ts, message) if table == "queue_predictions"]
+
+ def test_parser_records_the_queued_and_the_chosen_variant(self):
+ parser = collector.FormatParser()
+ self.assertEqual(self.predictions(parser, 10.0, self.QUEUED), [dict(
+ lifecycle="0x7bb5e55c00|I/DSN.01", stage="queued", sample_rate_hz=192000.0, bit_depth=24)])
+ self.assertEqual(self.predictions(parser, 200.0, self.START), [dict(
+ lifecycle="0x7bb5e55c00|I/DSN.01", stage="prebuffered", sample_rate_hz=48000.0, bit_depth=24)])
+ self.assertEqual(self.predictions(parser, 218.0, self.REPORT), [])
+ # A lossy variant, a video item and the variant-less second start line predict nothing.
+ self.assertEqual(self.predictions(parser, 1.0, self.START.replace(
+ "audio-alac-stereo-48000-24] [alac]", "audio-stereo-256] [mp4a.40.2]")), [])
+ self.assertEqual(self.predictions(parser, 1.0, self.START.split(" Variant ")[0]), [])
+ self.assertEqual(self.predictions(
+ parser, 1.0, "fpfs_StartTrackPlaying: <0x7bb5e55c00|I/DSN.01> ordered rendering for track 1"), [])
+
+ def test_parser_keeps_a_lossy_report_as_a_rate_without_a_depth(self):
+ parser = collector.FormatParser()
+ rows = parser.feed(5.0, self.REPORT.replace("[BitDepth 24]", "[BitDepth 0]"))
+ report = next(row for table, row in rows if table == "lifecycle_events")
+ self.assertEqual(report["sample_rate_hz"], 48000.0)
+ self.assertIsNone(report["bit_depth"])
+
+ def test_metrics_score_each_stage_against_the_first_report(self):
+ with tempfile.TemporaryDirectory() as temp:
+ path = str(pathlib.Path(temp) / "streamwatch.db")
+ store = collector.Store(path)
+ parser = collector.FormatParser()
+ # The item was queued as 192 kHz, buffered as 48 kHz and played at 48 kHz.
+ lines = [(1000.0, self.QUEUED), (1200.0, self.START), (1218.5, self.REPORT)]
+ # A skipped-to item: the notice and the report arrive together.
+ skipped = "<0x7bb7289c00|I/AFT.01>"
+ lines += [
+ (1300.00, self.START.replace("<0x7bb5e55c00|I/DSN.01>", skipped)),
+ (1300.04, self.REPORT.replace("<0x7bb5e55c00|I/DSN.01>", skipped)),
+ # An item that was buffered but never played.
+ (1400.0, self.START.replace("<0x7bb5e55c00|I/DSN.01>", "<0x7bb9f48e00|I/SPD.01>")),
+ ]
+ for ts, message in lines:
+ for table, row in parser.feed(ts, message):
+ store.insert(table, ts=ts, **row)
+ store.insert("raw_log", ts=ts, subsystem="com.apple.coremedia", category="player", message=message)
+ cursor = store.conn.execute("SELECT * FROM queue_prediction_metrics ORDER BY stage")
+ names = [column[0] for column in cursor.description]
+ metrics = {row[1]: dict(zip(names, row)) for row in cursor.fetchall()}
+ self.assertEqual(metrics["queued"]["prediction_count"], 1)
+ self.assertEqual(metrics["queued"]["format_misses"], 1)
+ self.assertEqual(metrics["queued"]["rate_misses"], 1)
+ self.assertEqual(metrics["prebuffered"]["prediction_count"], 3)
+ self.assertEqual(metrics["prebuffered"]["format_hits"], 2)
+ self.assertEqual(metrics["prebuffered"]["format_misses"], 0)
+ self.assertEqual(metrics["prebuffered"]["unresolved_count"], 1)
+ self.assertEqual(metrics["prebuffered"]["lead_under_1s"], 1)
+ self.assertEqual(metrics["prebuffered"]["mean_lead_s"], 18.5)
+
+ # A database that predates the table is scored once from the lines it already kept.
+ store.conn.execute("DELETE FROM queue_predictions")
+ store.conn.commit()
+ self.assertEqual(collector.backfill_queue_predictions(store), 4)
+ self.assertEqual(collector.backfill_queue_predictions(store), 0)
+ self.assertEqual(store.conn.execute(
+ "SELECT format_hits FROM queue_prediction_metrics WHERE stage='prebuffered'").fetchone()[0], 2)
+ store.conn.close()
+
+ # The aggregate and the notices are readable through the SQL gate; they hold no track identity.
+ with mock.patch.object(gate, "DB_PATH", path):
+ result = gate.run_sql("SELECT stage, format_hits FROM queue_prediction_metrics ORDER BY stage")
+ self.assertTrue(result["ok"], result.get("error"))
+ self.assertEqual([list(row) for row in result["rows"]], [["prebuffered", 2], ["queued", 0]])
+ self.assertTrue(gate.run_sql("SELECT lifecycle, stage FROM queue_predictions LIMIT 1")["ok"])
+
+
class GateTests(unittest.TestCase):
def test_installer_replaces_existing_unrestricted_key(self):
with tempfile.TemporaryDirectory() as temp: