| 12345678910111213141516171819202122232425262728293031323334353637383940414243 |
- using System;
- namespace DevilLink2.Presentation
- {
- /// <summary>Deterministic voice admission independent of speakers and Unity's isPlaying state.</summary>
- public sealed class AudioVoicePolicy
- {
- public const int Slots = 6, MaxConcurrent = 3;
- private sealed class Voice { public bool Active; public AudioCue Cue; public float Gain; public double Ends; public long Order; }
- private readonly Voice[] voices = new Voice[Slots];
- private long order;
- public AudioVoicePolicy() { for (int i = 0; i < Slots; i++) voices[i] = new Voice(); }
- public int Count { get { int count = 0; foreach (var voice in voices) if (voice.Active) count++; return count; } }
- public float GainSum { get { float sum = 0; foreach (var voice in voices) if (voice.Active) sum += voice.Gain; return sum; } }
- public float GainAt(int slot) => voices[slot].Active ? voices[slot].Gain : 0;
- public void Expire(double now) { foreach (var voice in voices) if (voice.Active && now >= voice.Ends) voice.Active = false; }
- public bool TryStart(AudioCue cue, float gain, double now, double duration, out int slot)
- {
- slot = -1;
- if (gain <= 0 || float.IsNaN(gain) || float.IsInfinity(gain) || double.IsNaN(now) || double.IsInfinity(now) ||
- duration <= 0 || double.IsNaN(duration) || double.IsInfinity(duration)) return false;
- Expire(now);
- for (int i = 0; i < Slots; i++)
- {
- if (!voices[i].Active) continue;
- if (voices[i].Cue == cue) return false; // No chorus of the same still-playing sample.
- if (AudioMixCalibration.IsUi(cue) && AudioMixCalibration.IsUi(voices[i].Cue)) slot = i;
- }
- if (slot < 0 && Count < MaxConcurrent)
- for (int i = 0; i < Slots; i++) if (!voices[i].Active) { slot = i; break; }
- if (slot < 0)
- {
- for (int i = 0; i < Slots; i++) if (voices[i].Active && (slot < 0 ||
- AudioMixCalibration.Priority(voices[i].Cue) < AudioMixCalibration.Priority(voices[slot].Cue) ||
- (AudioMixCalibration.Priority(voices[i].Cue) == AudioMixCalibration.Priority(voices[slot].Cue) && voices[i].Order < voices[slot].Order))) slot = i;
- if (slot < 0 || AudioMixCalibration.Priority(cue) < AudioMixCalibration.Priority(voices[slot].Cue)) { slot = -1; return false; }
- }
- var selected = voices[slot]; selected.Active = true; selected.Cue = cue; selected.Gain = Math.Min(1, gain);
- selected.Ends = now + duration; selected.Order = ++order; return true;
- }
- public void Clear() { foreach (var voice in voices) voice.Active = false; }
- }
- }
|