A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
Audio: loop the menu theme between the proposed loop points (Refs #2338) (#2420)
Beri23954d6ea195
diff --git a/changelog.d/laneSU-2338.md b/changelog.d/laneSU-2338.mdnew file mode 100644index 000000000..fdedd3140--- /dev/null+++ b/changelog.d/laneSU-2338.md@@ -0,0 +1,6 @@+### Changed+- The start menu's theme plays from the top once, then loops between Afik's proposed loop points, 00:10 to 04:03,+ instead of looping the whole clip (Refs #2338). The loop points are data+ (`unity/Assets/Resources/Music/menu-music.yaml`); the OGG is unchanged. At each seam the next source is scheduled to+ start at the loop start on the same `dspTime` the other ends. Not yet listened to in a web build: in the OGG the cut+ lands on a step of about -45 dBFS (measured with ffmpeg), and #2338 stays open for that check.diff --git a/docs/audio.md b/docs/audio.mdindex f3f302698..245092c72 100644--- a/docs/audio.md+++ b/docs/audio.md@@ -19,6 +19,16 @@ Where the game's sounds live and what plays them (#39).when the menu's fade ends.- The start menu's theme is the file `MenuMusic.File` names. A renamed file is renamed there too. Once a theme iscommitted, `MenuMusicTests.ThePlayerPicksTheThemeInStreamingAssetsMusic` fails while the two differ.+- The theme plays from 0:00 once, then loops between its loop points (#2338): Afik's proposed 00:10 to 04:03, kept as+ data in `unity/Assets/Resources/Music/menu-music.yaml` (`file`, `loop_start_s`, `loop_end_s`), not in the OGG, which+ stays as delivered. Resources, not the music folder: that folder holds OGG files only, and the game reads Resources+ at start with no second download. At each seam, two `AudioSource`s hand over on the audio clock: one ends and the+ other is scheduled to start at the loop start at the same `dspTime`. That is the design; nobody has listened to the+ seam in a web build yet (#2338 stays open for it). Measured in the OGG with ffmpeg, the cut lands on a step of about+ -45 dBFS in a quiet passage. `MenuMusicTests.TheTwoSourcesHandOverAtEachSeamOnTheAudioClock` checks the scheduling+ calls with a fake audio clock, not the sound. A missing or invalid region (no file, another file's name, an end before+ the start or past the clip's end) loops the whole clip, with one plain `MUSIC no loop region` line in the log. `MenuMusicTests.TheThemeLoopsBetweenAfiksLoopPoints` checks the region+ against the committed file.- With no file (or any failed download) the start menu is silent for the rest of the page: no error and no warning,one plain `MUSIC no theme` line in the log. A reload tries again.- Each file needs its rows like any other asset: `ASSETS.yaml` (source, licence, SHA-256), `LICENSING.md` and thediff --git a/unity/Assets/Resources/Music.meta b/unity/Assets/Resources/Music.metanew file mode 100644index 000000000..a9722b954--- /dev/null+++ b/unity/Assets/Resources/Music.meta@@ -0,0 +1,8 @@+fileFormatVersion: 2+guid: 118bedf3ce4fe73708a0fbaf5f91d743+folderAsset: yes+DefaultImporter:+ externalObjects: {}+ userData:+ assetBundleName:+ assetBundleVariant:diff --git a/unity/Assets/Resources/Music/menu-music.yaml b/unity/Assets/Resources/Music/menu-music.yamlnew file mode 100644index 000000000..7076c3a56--- /dev/null+++ b/unity/Assets/Resources/Music/menu-music.yaml@@ -0,0 +1,6 @@+# The start menu theme's loop points (#2338): MenuMusic plays the file from 0:00 once, then loops loop_start_s to+# loop_end_s (seconds from the top of the file). Afik Faerman's proposed loop points for Main_1.3.ogg, as recorded on its+# ASSETS.yaml row: 00:10 to 04:03. The OGG itself is not cut or tagged. A missing or invalid region loops the whole clip.+file: audio/music/Main_1.3.ogg+loop_start_s: 10+loop_end_s: 243diff --git a/unity/Assets/Resources/Music/menu-music.yaml.meta b/unity/Assets/Resources/Music/menu-music.yaml.metanew file mode 100644index 000000000..f9e121ef3--- /dev/null+++ b/unity/Assets/Resources/Music/menu-music.yaml.meta@@ -0,0 +1,7 @@+fileFormatVersion: 2+guid: b5139aef6f364fa72a9891875e58774a+TextScriptImporter:+ externalObjects: {}+ userData:+ assetBundleName:+ assetBundleVariant:diff --git a/unity/Assets/Scripts/UI/MenuMusic.cs b/unity/Assets/Scripts/UI/MenuMusic.csindex 285496705..a9ac2a133 100644--- a/unity/Assets/Scripts/UI/MenuMusic.cs+++ b/unity/Assets/Scripts/UI/MenuMusic.cs@@ -2,6 +2,8 @@using System;using UnityEngine;using UnityEngine.UIElements;+using YamlDotNet.Serialization;+using YamlDotNet.Serialization.NamingConventions;namespace Statecraft.Game.UI{@@ -23,6 +25,11 @@ namespace Statecraft.Game.UI/// committed file against it).</summary>public const string File = "audio/music/Main_1.3.ogg";+ /// <summary>The theme's loop points (#2338), Afik's proposed 00:10 to 04:03 (ASSETS.yaml), as data:+ /// Assets/Resources/Music/menu-music.yaml (`file`, `loop_start_s`, `loop_end_s`). In Resources, not next to the OGG:+ /// the music folder holds OGG files only, and Resources needs no second fetch on the web.</summary>+ public const string LoopResource = "Music/menu-music";+/// <summary>The fade when a game starts (and the dip under the recording), in real time, and the watch's period while/// it loads or plays.</summary>public const int FadeMs = 1000, WatchMs = 50;@@ -36,17 +43,76 @@ namespace Statecraft.Game.UI/// (Recommended)"; SettingsPresenter.SoundLevels' "low").</summary>public const float DefaultVolume = 0.35f;- /// <summary>Where the theme plays. The game's is a looping AudioSource on its own GameObject (SourceOutput).</summary>+ /// <summary>Where the theme plays. The game's is two AudioSources on their own GameObject (SourceOutput).</summary>public interface IOutput : IDisposable{/// <summary>As DeclarationRecording.IOutput.Ready: true once decoded, false while not yet, null when it failed.</summary>bool? Ready(AudioClip clip);- /// <summary>Plays the clip on a loop.</summary>- void Play(AudioClip clip);+ /// <summary>Plays the clip from sample 0 to the loop's End once, then its Start to End again and again+ /// (LoopRegion.SampleAt), the next part scheduled on the same audio-clock time the last one ends.</summary>+ void Play(AudioClip clip, LoopRegion loop);+ /// <summary>Every WatchMs while it plays: time to schedule the next seam.</summary>+ void Watch();void Stop();float Volume { set; }}+ /// <summary>The part of the clip that loops, in samples at Frequency: playback runs from sample 0 to End once, then+ /// from Start to End again and again. The whole clip is (0, samples).</summary>+ public readonly struct LoopRegion : IEquatable<LoopRegion>+ {+ public readonly int Start, End, Frequency;+ public LoopRegion(int start, int end, int frequency) { Start = start; End = end; Frequency = frequency; }++ /// <summary>The clip's sample heard after <paramref name="played"/> samples of playback.</summary>+ public long SampleAt(long played) => played < End ? played : Start + (played - End) % (End - Start);++ /// <summary>How many samples of playback come before seam <paramref name="n"/> (from 0), where End hands over to Start.+ /// Counted in samples, not by adding seconds up, so no rounding drifts over an hour on the menu.</summary>+ public long SeamAt(long n) => End + n * (End - Start);++ public bool Equals(LoopRegion o) => Start == o.Start && End == o.End && Frequency == o.Frequency;+ public override bool Equals(object? o) => o is LoopRegion r && Equals(r);+ public override int GetHashCode() => (Start * 31 + End) * 31 + Frequency;+ public override string ToString() => Start + ".." + End + " @ " + Frequency + " Hz";+ }++ sealed class LoopFile+ {+ public string File { get; set; } = "";+ public double LoopStartS { get; set; } = -1;+ public double LoopEndS { get; set; } = -1;+ }++ /// <summary>The loop region the file gives for a clip of <paramref name="samples"/> at <paramref name="frequency"/>;+ /// no file, a broken one, one for another file, or a region that is empty, reversed or outside the clip is the whole+ /// clip, with <paramref name="why"/> saying which (null when the file's region holds).</summary>+ internal static LoopRegion Loop(string? yaml, int samples, int frequency, out string? why)+ {+ why = null;+ LoopFile? f = null;+ if (string.IsNullOrWhiteSpace(yaml)) why = "no Resources/" + LoopResource + ".yaml";+ else+ {+ try+ {+ f = new DeserializerBuilder().WithNamingConvention(UnderscoredNamingConvention.Instance)+ .WithDuplicateKeyChecking().Build().Deserialize<LoopFile>(yaml);+ }+ catch (YamlDotNet.Core.YamlException e) { why = e.Message; }+ }+ if (why == null && f == null) why = "an empty loop file";+ if (why == null && f!.File != File) why = "the loop file is for '" + f.File + "'";+ if (why != null) return new LoopRegion(0, samples, frequency);+ long start = (long)Math.Round(f!.LoopStartS * frequency), end = (long)Math.Round(f.LoopEndS * frequency);+ if (start < 0 || end <= start || end > samples)+ {+ why = "loop " + f.LoopStartS + " s to " + f.LoopEndS + " s does not fit a clip of " + samples + " samples at " + frequency + " Hz";+ return new LoopRegion(0, samples, frequency);+ }+ return new LoopRegion((int)start, (int)end, frequency);+ }+/// <summary>Idle (not wanted, or waiting for the screen, the first gesture or a volume above 0); Loading (fetching or/// decoding); Playing; Fading (the game has started); Absent (no theme: silent for the rest of the page).</summary>public enum Phase { Idle, Loading, Playing, Fading, Absent }@@ -62,7 +128,7 @@ namespace Statecraft.Game.UIstatic readonly TrickleDown[] Phases = { TrickleDown.TrickleDown, TrickleDown.NoTrickleDown };readonly VisualElement root, listener; readonly bool web; readonly string url;- readonly DeclarationRecording.Fetch fetch; readonly IOutput output; readonly Func<double> now;+ readonly DeclarationRecording.Fetch fetch; readonly IOutput output; readonly Func<double> now; readonly string? loopYaml;readonly EventCallback<PointerDownEvent> onPointerDown; readonly EventCallback<PointerUpEvent> onPointerUp;readonly EventCallback<KeyDownEvent> onKey;readonly IVisualElementScheduledItem timer;@@ -93,9 +159,11 @@ namespace Statecraft.Game.UI/// <param name="fetch">Test seam; null fetches with UnityWebRequestMultimedia as Ogg Vorbis.</param>/// <param name="output">Test seam; null plays through an AudioSource.</param>/// <param name="now">Test seam: the clock, in seconds; null is Time.realtimeSinceStartupAsDouble.</param>+ /// <param name="loop">Test seam: the loop file's text; null reads Resources/Music/menu-music.yaml (LoopResource).</param>public MenuMusic(VisualElement root, bool web, string? url = null, DeclarationRecording.Fetch? fetch = null, IOutput? output = null,- Func<double>? now = null)+ Func<double>? now = null, string? loop = null){+ loopYaml = loop ?? Resources.Load<TextAsset>(LoopResource)?.text;this.root = root; this.web = web;this.url = url ?? Url();this.fetch = fetch ?? DeclarationRecording.WebFetchOgg;@@ -205,7 +273,9 @@ namespace Statecraft.Game.UIdip = Duck?.Invoke() == true ? DipLevel : 1f; // the recording may have started since the fetch did (N1)lastTick = now();Apply();- output.Play(clip!);+ var loop = Loop(loopYaml, clip!.samples, clip.frequency, out var why);+ if (why != null) Debug.Log("MUSIC no loop region for " + File + ": the whole clip loops (" + why + ")");+ output.Play(clip, loop);timer.Resume();}@@ -218,6 +288,7 @@ namespace Statecraft.Game.UIvar t = now();float step = (float)((t - lastTick) * 1000.0 / FadeMs);lastTick = t;+ output.Watch();dip = Duck?.Invoke() == true ? Mathf.Max(DipLevel, dip - step) : Mathf.Min(1f, dip + step);fade = fadingOut ? Mathf.Max(0f, fade - step) : Mathf.Min(1f, fade + step);if (fadingOut && fade <= 1e-4f) { Stop(); return; } // float steps: 20 x 0.05 may leave a hair above 0@@ -261,35 +332,143 @@ namespace Statecraft.Game.UIoutput.Dispose();}- /// <summary>A looping AudioSource on its own GameObject, made at the first Play.</summary>- sealed class SourceOutput : IOutput+ /// <summary>Two AudioSources on their own GameObject, made at the first Play. The whole clip loops on one+ /// (AudioSource.loop). A loop region hands over between the two at each seam on the audio clock: the playing one's+ /// scheduled end and the other's scheduled start (at Start) are the same dspTime (the design; nobody has listened to the+ /// seam in a web build yet, #2338). On the web, Unity's Audio.js turns these into AudioBufferSourceNode start(when,+ /// offset) and stop(when) (Chromium decodes every clip to a buffer). AudioSource.loop cannot do it: it always loops the+ /// whole clip.</summary>+ internal sealed class SourceOutput : IOutput{- GameObject? go; AudioSource? source; float volume = DefaultVolume;+ /// <summary>The first play's lead on the audio clock, so both of the first seam's halves can be scheduled.</summary>+ const double Lead = 0.1;+ readonly Func<double> dsp; readonly Func<ISource> make;+ /// <summary>The sources are AudioSources on our own GameObject: something else may destroy it (Unity's null), and+ /// the next Play then makes both again.</summary>+ readonly bool own;+ GameObject? go; ISource? playing, next; float volume = DefaultVolume;+ LoopRegion loop; bool region; double startDsp, seamDsp; long seam;++ /// <param name="dsp">Test seam: the audio clock, in seconds; null is AudioSettings.dspTime.</param>+ /// <param name="make">Test seam: makes one of the two sources; null adds an AudioSource to the MenuMusic+ /// GameObject. EditMode has no running audio clock, so a test records the scheduling calls instead.</param>+ internal SourceOutput(Func<double>? dsp = null, Func<ISource>? make = null)+ {+ this.dsp = dsp ?? (() => AudioSettings.dspTime);+ this.make = make ?? MakeSource;+ own = make == null;+ }public bool? Ready(AudioClip clip) => DeclarationRecording.SourceOutput.ReadyState(clip);- public void Play(AudioClip clip)+ public void Play(AudioClip clip, LoopRegion loop)+ {+ if (playing == null || (own && go == null)) { playing = make(); next = make(); }+ Stop();+ this.loop = loop;+ region = loop.Start != 0 || loop.End != clip.samples;+ playing!.Clip = next!.Clip = clip;+ playing.Volume = next.Volume = volume;+ playing.Loop = !region;+ playing.TimeSamples = (int)loop.SampleAt(0);+ if (!region) { playing.Play(); return; }+ startDsp = dsp() + Lead;+ playing.PlayScheduled(startDsp);+ seam = 0;+ Schedule();+ }++ ISource MakeSource()+ {+ if (go == null) go = new GameObject("MenuMusic");+ var s = go.AddComponent<AudioSource>();+ s.playOnAwake = false; s.loop = false; s.spatialBlend = 0f;+ return new UnitySource(s);+ }++ /// <summary>Seam number `seam`: the playing source ends and the other starts where the loop goes on, at one time.</summary>+ void Schedule(){- if (go == null)+ seamDsp = startDsp + (double)loop.SeamAt(seam) / loop.Frequency;+ playing!.SetScheduledEndTime(seamDsp);+ next!.TimeSamples = (int)loop.SampleAt(loop.SeamAt(seam));+ next.PlayScheduled(seamDsp);+ }++ /// <summary>Once a seam has passed, the source that took over plays on and the next seam is scheduled, a whole+ /// region (3:53 for the theme) ahead.</summary>+ public void Watch()+ {+ var now = dsp();+ if (!region || now < seamDsp) return;+ (playing, next) = (next, playing);+ seam++;+ if (startDsp + (double)loop.SeamAt(seam) / loop.Frequency <= now + Lead){- go = new GameObject("MenuMusic");- source = go.AddComponent<AudioSource>();- source.playOnAwake = false; source.loop = true; source.spatialBlend = 0f;+ // More than a region late: a hidden tab stalls this watch but not the audio clock, so the source that took+ // over ran past the loop end and stopped. Scheduling the missed seams would restart once per region in a+ // row; instead the loop starts again at its start, as if seam 0 fell just now.+ var at = now + Lead;+ startDsp = at - (double)loop.End / loop.Frequency;+ playing!.TimeSamples = loop.Start;+ playing.PlayScheduled(at);+ seam = 1;}- source!.volume = volume;- source.clip = clip;- source.Play();+ Schedule();}- public void Stop() { if (source != null) { source.Stop(); source.clip = null; } }+ public void Stop()+ {+ region = false;+ if (playing != null) { playing.Stop(); playing.Clip = null; }+ if (next != null) { next.Stop(); next.Clip = null; }+ }- public float Volume { set { volume = value; if (source != null) source.volume = value; } }+ public float Volume+ {+ set+ {+ volume = value;+ if (playing != null) playing.Volume = value;+ if (next != null) next.Volume = value;+ }+ }public void Dispose(){if (go != null) { if (Application.isPlaying) UnityEngine.Object.Destroy(go); else UnityEngine.Object.DestroyImmediate(go); }- go = null; source = null;+ go = null; playing = null; next = null;}}++ /// <summary>The calls SourceOutput makes on one of its two sources: an AudioSource in the game (UnitySource), a+ /// recorder in MenuMusicTests, so the handover at each seam can be checked without an audio clock.</summary>+ internal interface ISource+ {+ AudioClip? Clip { set; }+ float Volume { set; }+ bool Loop { set; }+ int TimeSamples { set; }+ void Play();+ void PlayScheduled(double at);+ void SetScheduledEndTime(double at);+ void Stop();+ }++ /// <summary>Every call skips a destroyed AudioSource (Unity's null): a scene teardown can destroy the MenuMusic+ /// GameObject before GameRoot.OnDisable disposes the music.</summary>+ sealed class UnitySource : ISource+ {+ readonly AudioSource s;+ public UnitySource(AudioSource s) { this.s = s; }+ public AudioClip? Clip { set { if (s != null) s.clip = value; } }+ public float Volume { set { if (s != null) s.volume = value; } }+ public bool Loop { set { if (s != null) s.loop = value; } }+ public int TimeSamples { set { if (s != null) s.timeSamples = value; } }+ public void Play() { if (s != null) s.Play(); }+ public void PlayScheduled(double at) { if (s != null) s.PlayScheduled(at); }+ public void SetScheduledEndTime(double at) { if (s != null) s.SetScheduledEndTime(at); }+ public void Stop() { if (s != null) s.Stop(); }+ }}}diff --git a/unity/Assets/Tests/EditMode/MenuMusicTests.cs b/unity/Assets/Tests/EditMode/MenuMusicTests.csindex a680df474..84d4c0f8a 100644--- a/unity/Assets/Tests/EditMode/MenuMusicTests.cs+++ b/unity/Assets/Tests/EditMode/MenuMusicTests.cs@@ -47,12 +47,16 @@ public class MenuMusicTestssealed class FakeOutput : MenuMusic.IOutput{public readonly List<AudioClip> Played = new List<AudioClip>();+ /// <summary>The loop region of each play.</summary>+ public readonly List<MenuMusic.LoopRegion> Loops = new List<MenuMusic.LoopRegion>();+ public int Watches;public bool IsPlaying { get; private set; }public float Volume { get; set; } = -1f;public bool? Decoded = true;public int Stops;public bool? Ready(AudioClip clip) => Decoded;- public void Play(AudioClip clip) { Played.Add(clip); IsPlaying = true; }+ public void Play(AudioClip clip, MenuMusic.LoopRegion loop) { Played.Add(clip); Loops.Add(loop); IsPlaying = true; }+ public void Watch() => Watches++;public void Stop() { Stops++; IsPlaying = false; }public void Dispose() { }}@@ -66,10 +70,12 @@ public class MenuMusicTestspublic bool Ducked;/// <summary>The fake clock, in milliseconds.</summary>public double Clock;- public Rig(bool web, string? url = null)+ /// <summary>A loop file that fits Answer's 0.1 s clip: samples 441 to 3,969 of 4,410.</summary>+ public const string FittingLoop = Theme + "loop_start_s: 0.01\nloop_end_s: 0.09\n";+ public Rig(bool web, string? url = null, string? loop = FittingLoop){Music = new MenuMusic(Ui.Root, web, url ?? "https://example.invalid/StreamingAssets/" + MenuMusic.File, Fetch.Start, Out,- () => Clock / 1000.0);+ () => Clock / 1000.0, loop);Music.Duck = () => Ducked;}public AudioClip Answer()@@ -498,4 +504,152 @@ public class MenuMusicTestsAssert.AreEqual("חלשה", He["settings.music.low"]);Assert.AreEqual("חזקה", He["settings.music.high"]);}++ /// <summary>The shipped theme's loop region (#2338): Afik's proposed loop points, 00:10 to 04:03 (ASSETS.yaml), read from+ /// Resources/Music/menu-music.yaml: samples 441,000 to 10,716,300 at the file's 44,100 Hz, both inside the clip. The+ /// rate and the length come from the committed OGG itself (its Vorbis header and its last page's granule position).</summary>+ [Test]+ public void TheThemeLoopsBetweenAfiksLoopPoints()+ {+ var ogg = File.ReadAllBytes(Path.Combine(Application.streamingAssetsPath, MenuMusic.File));+ int rate = BitConverter.ToInt32(ogg, 28 + 12); // first page header (28 bytes with one segment), then "\x01vorbis", version, channels+ int last = -1;+ for (int i = ogg.Length - 4; i >= 0 && last < 0; i--)+ if (ogg[i] == 'O' && ogg[i + 1] == 'g' && ogg[i + 2] == 'g' && ogg[i + 3] == 'S') last = i;+ int samples = (int)BitConverter.ToInt64(ogg, last + 6);+ Assert.AreEqual(44100, rate);+ Assert.AreEqual(11037601, samples, "ffprobe's duration_ts for the file (#2338)");+ var yaml = Resources.Load<TextAsset>(MenuMusic.LoopResource)?.text;+ Assert.IsNotNull(yaml, "Assets/Resources/" + MenuMusic.LoopResource + ".yaml is shipped");+ var loop = MenuMusic.Loop(yaml, samples, rate, out var why);+ Assert.IsNull(why);+ Assert.AreEqual(441000, loop.Start, "00:10");+ Assert.AreEqual(10716300, loop.End, "04:03");+ Assert.Less(loop.End, samples, "inside the clip");+ }++ /// <summary>The schedule the output plays (LoopRegion, which SourceOutput's handover follows): the first play starts at+ /// the top (sample 0, not the loop start) and runs to the loop end; from there playback goes on at the loop start, and+ /// again at every later seam, with no sample left out or played twice. MenuMusic hands the output the region and+ /// watches it every tick. (SourceOutput's scheduling calls: TheTwoSourcesHandOverAtEachSeamOnTheAudioClock.)</summary>+ [Test]+ public void ItPlaysFromTheTopThenLoopsTheRegion()+ {+ var loop = new MenuMusic.LoopRegion(441000, 10716300, 44100);+ Assert.AreEqual(0, loop.SampleAt(0), "the first play starts at 0:00");+ Assert.AreEqual(441000, loop.SampleAt(441000), "the intro plays once, straight through");+ Assert.AreEqual(10716299, loop.SampleAt(10716299), "the last sample before the loop end");+ Assert.AreEqual(10716300, loop.SeamAt(0), "the first seam is at 04:03");+ Assert.AreEqual(441000, loop.SampleAt(loop.SeamAt(0)), "at the loop end it continues at the loop start");+ Assert.AreEqual(441001, loop.SampleAt(loop.SeamAt(0) + 1));+ Assert.AreEqual(10716300 + 10275300, loop.SeamAt(1), "the next seam, one region (3:53) later");+ Assert.AreEqual(10716299, loop.SampleAt(loop.SeamAt(1) - 1));+ Assert.AreEqual(441000, loop.SampleAt(loop.SeamAt(1)));+ using var rig = new Rig(web: true);+ rig.Music.Show(true); rig.Click();+ var clip = rig.Answer();+ Assert.AreEqual(new MenuMusic.LoopRegion(441, 3969, 44100), rig.Out.Loops.Single(), "the output gets the region");+ rig.Pass(MenuMusic.WatchMs * 3);+ Assert.AreEqual(3, rig.Out.Watches, "the output is watched every tick, to schedule its next seam");+ UnityEngine.Object.DestroyImmediate(clip);+ }++ /// <summary>One of SourceOutput's two sources: it records every call, with the value, in order, in a shared log.</summary>+ sealed class RecordingSource : MenuMusic.ISource+ {+ readonly string name; readonly List<string> log;+ public RecordingSource(string name, List<string> log) { this.name = name; this.log = log; }+ public AudioClip? Clip { set => log.Add(name + ".Clip " + (value == null ? "null" : value.name)); }+ public float Volume { set => log.Add(name + ".Volume " + value.ToString("0.##", System.Globalization.CultureInfo.InvariantCulture)); }+ public bool Loop { set => log.Add(name + ".Loop " + value); }+ public int TimeSamples { set => log.Add(name + ".TimeSamples " + value); }+ public void Play() => log.Add(name + ".Play");+ public void PlayScheduled(double at) => log.Add(name + ".PlayScheduled " + Ms(at));+ public void SetScheduledEndTime(double at) => log.Add(name + ".SetScheduledEndTime " + Ms(at));+ public void Stop() => log.Add(name + ".Stop");+ /// <summary>The audio clock in whole milliseconds, so seams counted in samples compare exactly.</summary>+ static string Ms(double s) => Math.Round(s * 1000.0).ToString(System.Globalization.CultureInfo.InvariantCulture) + " ms";+ }++ /// <summary>The game's output (SourceOutput) hands over between its two sources on the audio clock (#2338). With a+ /// recorded pair of sources and a fake dspTime: the first source starts at sample 0 and its scheduled end is the first+ /// seam; the second starts at the loop start at that same dspTime. After the seam the roles swap and the next seam is+ /// one region later. A watch stalled past the next seam (a hidden tab) starts the loop again at its start, with the+ /// following seam one region after that. This drives the scheduling calls, not Unity's audio: whether the two halves+ /// meet without a gap or a click in a real browser is the listening check in #2338.</summary>+ [Test]+ public void TheTwoSourcesHandOverAtEachSeamOnTheAudioClock()+ {+ var log = new List<string>();+ double dsp = 10.0;+ var made = 0;+ using var output = new MenuMusic.SourceOutput(() => dsp, () => new RecordingSource(made++ == 0 ? "A" : "B", log));+ // A 10 s clip looping 1 s to 8 s: one region (7 s) is longer than Lead, as the theme's 3:53 is.+ var clip = AudioClip.Create("theme", 441000, 1, 44100, false);+ output.Play(clip, new MenuMusic.LoopRegion(44100, 352800, 44100));+ // Starts at 10 s + Lead (100 ms) = 10,100 ms; the first seam is 8 s of clip later.+ CollectionAssert.AreEqual(new[] {+ "A.Stop", "A.Clip null", "B.Stop", "B.Clip null",+ "B.Clip theme", "A.Clip theme", "B.Volume 0.35", "A.Volume 0.35", "A.Loop False", "A.TimeSamples 0",+ "A.PlayScheduled 10100 ms",+ "A.SetScheduledEndTime 18100 ms", "B.TimeSamples 44100", "B.PlayScheduled 18100 ms",+ }, log, "the first source plays from the top; its end and the second's start at the loop start share the seam's dspTime");+ log.Clear();+ dsp = 18.0; output.Watch();+ CollectionAssert.IsEmpty(log, "nothing to do before the seam");+ dsp = 18.2; output.Watch();+ CollectionAssert.AreEqual(new[] { "B.SetScheduledEndTime 25100 ms", "A.TimeSamples 44100", "A.PlayScheduled 25100 ms" }, log,+ "after the seam the second plays on and the first is scheduled for the next seam, one region (7 s) later");+ log.Clear();+ dsp = 40.0; output.Watch(); // stalled: the seams at 25.1 s and 32.1 s passed unwatched+ CollectionAssert.AreEqual(new[] {+ "A.TimeSamples 44100", "A.PlayScheduled 40100 ms",+ "A.SetScheduledEndTime 47100 ms", "B.TimeSamples 44100", "B.PlayScheduled 47100 ms",+ }, log, "a stalled watch starts the loop again at its start (now + Lead), not once per missed seam");+ log.Clear();+ output.Play(clip, new MenuMusic.LoopRegion(0, 441000, 44100));+ CollectionAssert.AreEqual(new[] {+ "A.Stop", "A.Clip null", "B.Stop", "B.Clip null",+ "B.Clip theme", "A.Clip theme", "B.Volume 0.35", "A.Volume 0.35", "A.Loop True", "A.TimeSamples 0", "A.Play",+ }, log, "the whole clip (no region) loops on one source, with nothing scheduled");+ log.Clear();+ dsp = 60.0; output.Watch();+ CollectionAssert.IsEmpty(log, "and the watch leaves it alone");+ UnityEngine.Object.DestroyImmediate(clip);+ }++ /// <summary>The scene's teardown can destroy the music's GameObject before GameRoot.OnDisable disposes the music (the+ /// order varies). Stop, Volume and Dispose on the game's own output then skip the destroyed AudioSources (Unity's null),+ /// as before #2338, instead of throwing MissingReferenceException.</summary>+ [Test]+ public void ADestroyedMusicObjectStopsAndDisposesQuietly()+ {+ var output = new MenuMusic.SourceOutput();+ var clip = AudioClip.Create("theme", 4410, 1, 44100, false);+ output.Play(clip, new MenuMusic.LoopRegion(0, 4410, 44100));+ var go = UnityEngine.Object.FindObjectsByType<AudioSource>(FindObjectsSortMode.None).First(s => s.clip == clip).gameObject;+ UnityEngine.Object.DestroyImmediate(go);+ Assert.DoesNotThrow(() => { output.Stop(); output.Volume = 0.5f; output.Dispose(); });+ LogAssert.NoUnexpectedReceived();+ UnityEngine.Object.DestroyImmediate(clip);+ }++ const string Theme = "file: " + MenuMusic.File + "\n";++ /// <summary>No loop file, a broken one, one for another file, or a region that is empty, reversed or past the clip's end:+ /// the whole clip loops (as before #2338), with one plain log line, no warning and no error.</summary>+ [Test]+ public void AMissingOrInvalidLoopRegionLoopsTheWholeClip([Values("", "loop_start_s: [", "file: audio/music/Other.ogg\nloop_start_s: 0.01\nloop_end_s: 0.09\n",+ Theme + "loop_start_s: 0.09\nloop_end_s: 0.01\n", Theme + "loop_start_s: 0.05\nloop_end_s: 0.05\n", Theme + "loop_start_s: 0.01\nloop_end_s: 0.2\n",+ Theme + "loop_start_s: -0.01\nloop_end_s: 0.09\n")] string loop)+ {+ using var rig = new Rig(web: true, loop: loop);+ rig.Music.Show(true); rig.Click();+ LogAssert.Expect(LogType.Log, new System.Text.RegularExpressions.Regex("^MUSIC no loop region for " + System.Text.RegularExpressions.Regex.Escape(MenuMusic.File) + ": the whole clip loops \\([\\s\\S]+\\)$"));+ var clip = rig.Answer();+ rig.Pass(MenuMusic.WatchMs * 3);+ LogAssert.NoUnexpectedReceived();+ Assert.AreEqual(new MenuMusic.LoopRegion(0, 4410, 44100), rig.Out.Loops.Single(), "the whole clip");+ UnityEngine.Object.DestroyImmediate(clip);+ }}