Skip to content

Commit

Permalink
Очередь озвучки анонсов, фиксы багов и оптимизация генерации ттсов. (#35
Browse files Browse the repository at this point in the history
)

* Очередь на озвучку оповещений

* Фикс ошибок клиента и оптимизация ттса

* Укоротил сообщения о кодах

* чейнжлог
  • Loading branch information
VigersRay authored Jun 7, 2024
1 parent 5137a7f commit 72affc5
Show file tree
Hide file tree
Showing 21 changed files with 131 additions and 81 deletions.
81 changes: 60 additions & 21 deletions Content.Client/_Sunrise/TTS/TTSSystem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using Robust.Client.Audio;
using Robust.Client.ResourceManagement;
using Robust.Shared.Audio;
using Robust.Shared.Audio.Components;
using Robust.Shared.Audio.Systems;
using Robust.Shared.Configuration;
using Robust.Shared.ContentPack;
Expand All @@ -25,9 +26,8 @@ public sealed class TTSSystem : EntitySystem
private ISawmill _sawmill = default!;
private readonly MemoryContentRoot _contentRoot = new();
private static readonly ResPath Prefix = ResPath.Root / "TTS";
private static readonly AudioResource EmptyAudioResource = new();

private const float TTSVolume = 0f;
private const float TtsVolume = 0f;
private const float AnnounceVolume = 0f;

private float _volume;
Expand All @@ -36,6 +36,9 @@ public sealed class TTSSystem : EntitySystem
private float _volumeAnnounce;
private EntityUid _announcementUid = EntityUid.Invalid;

private Queue<AnnounceTtsEvent> _announceQueue = new();
private (EntityUid Entity, AudioComponent Component)? _currentPlaying;

public override void Initialize()
{
_sawmill = Logger.GetSawmill("tts");
Expand Down Expand Up @@ -83,12 +86,28 @@ private void OnAnnounceTTSPlay(AnnounceTtsEvent ev)
if (_volumeAnnounce == 0)
return;

_announceQueue.Enqueue(ev);
}

private void PlayNextInQueue()
{
if (_announceQueue.Count == 0)
{
return;
}

var ev = _announceQueue.Dequeue();

if (_announcementUid == EntityUid.Invalid)
_announcementUid = Spawn(null);

var finalParams = new AudioParams() {Volume = AnnounceVolume + SharedAudioSystem.GainToVolume(_volumeAnnounce)};
var finalParams = new AudioParams() { Volume = AnnounceVolume + SharedAudioSystem.GainToVolume(_volumeAnnounce) };

PlayTTSBytes(ev.Data, _announcementUid, finalParams, true);
if (ev.AnnouncementSound != null)
{
_currentPlaying = _audio.PlayGlobal(ev.AnnouncementSound, _announcementUid, finalParams.AddVolume(-5f));
}
_currentPlaying = PlayTTSBytes(ev.Data, _announcementUid, finalParams, true);
}

private void OnTtsRadioVolumeChanged(float volume)
Expand All @@ -103,18 +122,24 @@ private void OnPlayTTS(PlayTTSEvent ev)
if (volume == 0)
return;

volume = TTSVolume + SharedAudioSystem.GainToVolume(volume * ev.VolumeModifier);
volume = TtsVolume + SharedAudioSystem.GainToVolume(volume * ev.VolumeModifier);

var audioParams = AudioParams.Default.WithVolume(volume);

PlayTTSBytes(ev.Data, GetEntity(ev.SourceUid), audioParams);
var entity = GetEntity(ev.SourceUid);
PlayTTSBytes(ev.Data, entity, audioParams);
}

private void PlayTTSBytes(byte[] data, EntityUid? sourceUid = null, AudioParams? audioParams = null, bool globally = false)
private (EntityUid Entity, AudioComponent Component)? PlayTTSBytes(byte[] data, EntityUid? sourceUid = null, AudioParams? audioParams = null, bool globally = false)
{
_sawmill.Debug($"Play TTS audio {data.Length} bytes from {sourceUid} entity");
if (data.Length == 0)
return;
return null;

// если sourceUid.Value.Id == 0 то значит эта сущность не прогружена на стороне клиента
if ((sourceUid == null || sourceUid.Value.Id == 0) && !globally)
return null;

_sawmill.Debug($"Play TTS audio {data.Length} bytes from {sourceUid} entity");

var finalParams = audioParams ?? AudioParams.Default;

Expand All @@ -125,27 +150,41 @@ private void PlayTTSBytes(byte[] data, EntityUid? sourceUid = null, AudioParams?
res.Load(_dependencyCollection, Prefix / filePath);
_resourceCache.CacheResource(Prefix / filePath, res);

if (sourceUid != null)
(EntityUid Entity, AudioComponent Component)? playing;

if (globally)
{
_audio.PlayEntity(res.AudioStream, sourceUid.Value, finalParams);
playing = _audio.PlayGlobal(res.AudioStream, finalParams);
}
else
{
_audio.PlayGlobal(res.AudioStream, finalParams);
playing = sourceUid == null ? null : _audio.PlayEntity(res.AudioStream, sourceUid.Value, finalParams);
}

if (globally)
_audio.PlayGlobal(res.AudioStream, finalParams);
else
_contentRoot.RemoveFile(filePath);

_fileIdx++;
return playing;
}

public override void Update(float frameTime)
{
base.Update(frameTime);

if (_currentPlaying.HasValue)
{
if (sourceUid == null)
_audio.PlayGlobal(res.AudioStream, finalParams);
var (entity, component) = _currentPlaying.Value;

if (Deleted(entity))
{
_currentPlaying = null;
}
else
_audio.PlayEntity(res.AudioStream, sourceUid.Value, finalParams);
{
return;
}
}

_contentRoot.RemoveFile(filePath);

_fileIdx++;
PlayNextInQueue();
}
}
17 changes: 7 additions & 10 deletions Content.Server/AlertLevel/AlertLevelSystem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -175,21 +175,18 @@ public void SetLevel(EntityUid station, string level, bool playSound, bool annou
var playDefault = false;
if (playSound)
{
if (detail.Sound != null)
{
var filter = _stationSystem.GetInOwningStation(station);
_audio.PlayGlobal(detail.Sound, filter, true, detail.Sound.Params);
}
else
{
if (detail.Sound == null)
playDefault = true;
}
}

if (announce)
{
_chatSystem.DispatchStationAnnouncement(station, announcementFull, playSound: playDefault,
colorOverride: detail.Color, sender: stationName);
_chatSystem.DispatchStationAnnouncement(station,
announcementFull,
announcementSound: detail.Sound, // Sunrise-edit,
playDefault: playDefault,
colorOverride: detail.Color,
sender: stationName);
}

RaiseLocalEvent(new AlertLevelChangedEvent(station, level));
Expand Down
2 changes: 1 addition & 1 deletion Content.Server/Bed/Cryostorage/CryostorageSystem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,7 @@ public void HandleEnterCryostorage(Entity<CryostorageContainedComponent> ent, Ne
("character", name),
("job", CultureInfo.CurrentCulture.TextInfo.ToTitleCase(jobName))
), Loc.GetString("earlyleave-cryo-sender"),
playSound: false
playDefault: false
);
}

Expand Down
2 changes: 1 addition & 1 deletion Content.Server/Chat/Systems/AnnounceOnSpawnSystem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,6 @@ private void OnInit(EntityUid uid, AnnounceOnSpawnComponent comp, MapInitEvent a
{
var message = Loc.GetString(comp.Message);
var sender = comp.Sender != null ? Loc.GetString(comp.Sender) : "Central Command";
_chat.DispatchGlobalAnnouncement(message, sender, playSound: true, announcementSound: comp.Sound, colorOverride: comp.Color);
_chat.DispatchGlobalAnnouncement(message, sender, playDefault: true, announcementSound: comp.Sound, colorOverride: comp.Color);
}
}
28 changes: 11 additions & 17 deletions Content.Server/Chat/Systems/ChatSystem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,6 @@ public sealed partial class ChatSystem : SharedChatSystem
// public const int WhisperMuffledRange = 5; // how far whisper goes at all, in world units
// Sunrise-TTS-End
public const string DefaultAnnouncementSound = "/Audio/Announcements/announce.ogg"; // Sunrise-edit
public const string NukeAnnouncementSound = "/Audio/Announcements/war.ogg"; // Sunrise-edit

private bool _loocEnabled = true;
private bool _deadLoocEnabled;
Expand Down Expand Up @@ -319,7 +318,7 @@ public void TrySendInGameOOCMessage(
public void DispatchGlobalAnnouncement(
string message,
string sender = "Центральное коммандование", // Sunrise-edit
bool playSound = true,
bool playDefault = true,
SoundSpecifier? announcementSound = null,
bool playTts = true, // Sunrise-edit
Color? colorOverride = null
Expand All @@ -329,20 +328,15 @@ public void DispatchGlobalAnnouncement(
_chatManager.ChatMessageToAll(ChatChannel.Radio, message, wrappedMessage, default, false, true, colorOverride);

// Sunrise-start
if (playSound)
if (playDefault && announcementSound == null)
{
if (sender == Loc.GetString("comms-console-announcement-title-nukie"))
{
announcementSound = new SoundPathSpecifier(NukeAnnouncementSound); // Sunrise-edit
}
announcementSound ??= new SoundPathSpecifier(DefaultAnnouncementSound);
_audio.PlayGlobal(announcementSound?.GetSound() ?? DefaultAnnouncementSound, Filter.Broadcast(), true, announcementSound?.Params ?? AudioParams.Default.WithVolume(-2f));
}

if (playTts)
{
var nukie = sender == Loc.GetString("comms-console-announcement-title-nukie");
var announcementEv = new AnnouncementSpokeEvent(Filter.Broadcast(), message, nukie);
var announcementEv = new AnnouncementSpokeEvent(Filter.Broadcast(), message, announcementSound, nukie);
RaiseLocalEvent(announcementEv);
}
// Sunrise-end
Expand All @@ -364,9 +358,10 @@ public void DispatchStationAnnouncement(
EntityUid source,
string message,
string sender = "Центральное коммандование", // Sunrise-edit
bool playSound = true, // Sunrise-edit
bool playDefault = true, // Sunrise-edit
bool playTts = true,// Sunrise-edit
Color? colorOverride = null)
Color? colorOverride = null,
SoundSpecifier? announcementSound = null)
{
var wrappedMessage = Loc.GetString("chat-manager-sender-announcement-wrap-message", ("sender", sender), ("message", FormattedMessage.EscapeText(message)));
var station = _stationSystem.GetOwningStation(source);
Expand All @@ -384,15 +379,12 @@ public void DispatchStationAnnouncement(
_chatManager.ChatMessageToManyFiltered(filter, ChatChannel.Radio, message, wrappedMessage, source, false, true, colorOverride);

// Sunrise-start
if (playSound)
{
var announcementSound = new SoundPathSpecifier(DefaultAnnouncementSound);
_audio.PlayGlobal(announcementSound?.GetSound() ?? DefaultAnnouncementSound, Filter.Broadcast(), true, announcementSound?.Params ?? AudioParams.Default.WithVolume(-2f));
}
if (playDefault && announcementSound == null)
announcementSound = new SoundPathSpecifier(DefaultAnnouncementSound);

if (playTts)
{
RaiseLocalEvent(new AnnouncementSpokeEvent(filter, message));
RaiseLocalEvent(new AnnouncementSpokeEvent(filter, message, announcementSound));
}
// Sunrise-edit

Expand Down Expand Up @@ -1013,12 +1005,14 @@ public enum ChatTransmitRange : byte
public sealed class AnnouncementSpokeEvent(
Filter source,
string message,
SoundSpecifier? announcementSound,
bool nukie = false)
: EntityEventArgs
{
public readonly Filter Source = source;
public readonly string Message = message;
public readonly bool Nukie = nukie;
public readonly SoundSpecifier? AnnouncementSound = announcementSound;
}

public sealed class RadioSpokeEvent(EntityUid source, string message, EntityUid[] receivers) : EntityEventArgs
Expand Down
2 changes: 1 addition & 1 deletion Content.Server/Communications/CommsHackerSystem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ private void OnDoAfter(EntityUid uid, CommsHackerComponent comp, TerrorDoAfterEv
public void CallInThreat(NinjaHackingThreatPrototype ninjaHackingThreat)
{
_gameTicker.StartGameRule(ninjaHackingThreat.Rule, out _);
_chat.DispatchGlobalAnnouncement(Loc.GetString(ninjaHackingThreat.Announcement), playSound: true, playTts: true, colorOverride: Color.Red);
_chat.DispatchGlobalAnnouncement(Loc.GetString(ninjaHackingThreat.Announcement), playDefault: true, playTts: true, colorOverride: Color.Red);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ private void OnDoAfter(Entity<CriminalRecordsHackerComponent> ent, ref CriminalR
// main damage with this is existing arrest warrants are lost and to anger beepsky
}

_chat.DispatchGlobalAnnouncement(Loc.GetString(ent.Comp.Announcement), playSound: true, colorOverride: Color.Red);
_chat.DispatchGlobalAnnouncement(Loc.GetString(ent.Comp.Announcement), playDefault: true, colorOverride: Color.Red);

// once is enough
RemComp<CriminalRecordsHackerComponent>(ent);
Expand Down
2 changes: 1 addition & 1 deletion Content.Server/Dragon/DragonRiftSystem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ public override void Update(float frameTime)

var msg = Loc.GetString("carp-rift-warning",
("location", FormattedMessage.RemoveMarkup(_navMap.GetNearestBeaconString((uid, xform)))));
_chat.DispatchGlobalAnnouncement(msg, playSound: false, playTts: true, colorOverride: Color.Red);
_chat.DispatchGlobalAnnouncement(msg, playDefault: false, playTts: true, colorOverride: Color.Red);
_audio.PlayGlobal("/Audio/Misc/notice1.ogg", Filter.Broadcast(), true);
_navMap.SetBeaconEnabled(uid, true);
}
Expand Down
2 changes: 1 addition & 1 deletion Content.Server/GameTicking/GameTicker.RoundFlow.cs
Original file line number Diff line number Diff line change
Expand Up @@ -637,7 +637,7 @@ private void AnnounceRound()
var proto = _robustRandom.Pick(options);

if (proto.Message != null)
_chatSystem.DispatchGlobalAnnouncement(Loc.GetString(proto.Message), playSound: true, playTts: false);
_chatSystem.DispatchGlobalAnnouncement(Loc.GetString(proto.Message), playDefault: true, playTts: false);

if (proto.Sound != null)
_audio.PlayGlobal(proto.Sound, Filter.Broadcast(), true);
Expand Down
2 changes: 1 addition & 1 deletion Content.Server/GameTicking/GameTicker.Spawning.cs
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,7 @@ private void SpawnPlayer(ICommonSession player,
("gender", character.Gender), // Russian-LastnameGender
("job", CultureInfo.CurrentCulture.TextInfo.ToTitleCase(jobName))),
Loc.GetString("latejoin-arrival-sender"),
playSound: false);
playDefault: false);
}

if (player.UserId == new Guid("{e887eb93-f503-4b65-95b6-2f282c014192}"))
Expand Down
2 changes: 1 addition & 1 deletion Content.Server/Nuke/NukeSystem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -463,7 +463,7 @@ public void ArmBomb(EntityUid uid, NukeComponent? component = null)
("time", (int) component.RemainingTime),
("location", FormattedMessage.RemoveMarkup(_navMap.GetNearestBeaconString((uid, nukeXform)))));
var sender = Loc.GetString("nuke-component-announcement-sender");
_chatSystem.DispatchStationAnnouncement(stationUid ?? uid, announcement, sender, playSound: false, colorOverride: Color.Red);
_chatSystem.DispatchStationAnnouncement(stationUid ?? uid, announcement, sender, playDefault: false, colorOverride: Color.Red);

_sound.PlayGlobalOnStation(uid, _audio.GetSound(component.ArmSound));
_nukeSongLength = (float) _audio.GetAudioLength(_selectedNukeSong).TotalSeconds;
Expand Down
2 changes: 1 addition & 1 deletion Content.Server/NukeOps/WarDeclaratorSystem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ private void OnActivated(Entity<WarDeclaratorComponent> ent, ref WarDeclaratorAc
if (ev.Status == WarConditionStatus.WarReady)
{
var title = Loc.GetString(ent.Comp.SenderTitle);
_chat.DispatchGlobalAnnouncement(ent.Comp.Message, title, playSound: true, ent.Comp.Sound, colorOverride: ent.Comp.Color);
_chat.DispatchGlobalAnnouncement(ent.Comp.Message, title, playDefault: true, ent.Comp.Sound, colorOverride: ent.Comp.Color);
_adminLogger.Add(LogType.Chat, LogImpact.Low, $"{ToPrettyString(args.Actor):player} has declared war with this text: {ent.Comp.Message}");
}

Expand Down
2 changes: 1 addition & 1 deletion Content.Server/PowerSink/PowerSinkSystem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ private void NotifyStationOfImminentExplosion(EntityUid uid, PowerSinkComponent
_chat.DispatchStationAnnouncement(
station.Value,
Loc.GetString("powersink-immiment-explosion-announcement"),
playSound: true,
playDefault: true,
colorOverride: Color.Yellow
);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -314,7 +314,7 @@ private void OnEmergencyAuthorize(EntityUid uid, EmergencyShuttleConsoleComponen
if (remaining > 0)
_chatSystem.DispatchGlobalAnnouncement(
Loc.GetString("emergency-shuttle-console-auth-left", ("remaining", remaining)),
playSound: false, colorOverride: DangerColor);
playDefault: false, colorOverride: DangerColor);

if (!CheckForLaunch(component))
_audio.PlayGlobal("/Audio/Misc/notice1.ogg", Filter.Broadcast(), recordReplay: true);
Expand Down Expand Up @@ -418,7 +418,7 @@ private void AnnounceLaunch()
_announced = true;
_chatSystem.DispatchGlobalAnnouncement(
Loc.GetString("emergency-shuttle-launch-time", ("consoleAccumulator", $"{_consoleAccumulator:0}")),
playSound: false,
playDefault: false,
colorOverride: DangerColor);

_audio.PlayGlobal("/Audio/Misc/notice1.ogg", Filter.Broadcast(), recordReplay: true);
Expand Down
Loading

0 comments on commit 72affc5

Please sign in to comment.