system.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821
  1. // SPDX-FileCopyrightText: Copyright 2022 yuzu Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #include <chrono>
  4. #include <span>
  5. #include "audio_core/audio_core.h"
  6. #include "audio_core/common/audio_renderer_parameter.h"
  7. #include "audio_core/common/common.h"
  8. #include "audio_core/common/feature_support.h"
  9. #include "audio_core/common/workbuffer_allocator.h"
  10. #include "audio_core/renderer/adsp/adsp.h"
  11. #include "audio_core/renderer/behavior/info_updater.h"
  12. #include "audio_core/renderer/command/command_buffer.h"
  13. #include "audio_core/renderer/command/command_generator.h"
  14. #include "audio_core/renderer/command/command_list_header.h"
  15. #include "audio_core/renderer/effect/effect_info_base.h"
  16. #include "audio_core/renderer/effect/effect_result_state.h"
  17. #include "audio_core/renderer/memory/memory_pool_info.h"
  18. #include "audio_core/renderer/memory/pool_mapper.h"
  19. #include "audio_core/renderer/mix/mix_info.h"
  20. #include "audio_core/renderer/nodes/edge_matrix.h"
  21. #include "audio_core/renderer/nodes/node_states.h"
  22. #include "audio_core/renderer/sink/sink_info_base.h"
  23. #include "audio_core/renderer/system.h"
  24. #include "audio_core/renderer/upsampler/upsampler_info.h"
  25. #include "audio_core/renderer/voice/voice_channel_resource.h"
  26. #include "audio_core/renderer/voice/voice_info.h"
  27. #include "audio_core/renderer/voice/voice_state.h"
  28. #include "common/alignment.h"
  29. #include "core/core.h"
  30. #include "core/core_timing.h"
  31. #include "core/hle/kernel/k_event.h"
  32. #include "core/hle/kernel/k_transfer_memory.h"
  33. #include "core/memory.h"
  34. namespace AudioCore::AudioRenderer {
  35. u64 System::GetWorkBufferSize(const AudioRendererParameterInternal& params) {
  36. BehaviorInfo behavior;
  37. behavior.SetUserLibRevision(params.revision);
  38. u64 size{0};
  39. size += Common::AlignUp(params.mixes * sizeof(s32), 0x40);
  40. size += params.sub_mixes * MaxEffects * sizeof(s32);
  41. size += (params.sub_mixes + 1) * sizeof(MixInfo);
  42. size += params.voices * (sizeof(VoiceInfo) + sizeof(VoiceChannelResource) + sizeof(VoiceState));
  43. size += Common::AlignUp((params.sub_mixes + 1) * sizeof(MixInfo*), 0x10);
  44. size += Common::AlignUp(params.voices * sizeof(VoiceInfo*), 0x10);
  45. size += Common::AlignUp(((params.sinks + params.sub_mixes) * TargetSampleCount * sizeof(s32) +
  46. params.sample_count * sizeof(s32)) *
  47. (params.mixes + MaxChannels),
  48. 0x40);
  49. if (behavior.IsSplitterSupported()) {
  50. const auto node_size{NodeStates::GetWorkBufferSize(params.sub_mixes + 1)};
  51. const auto edge_size{EdgeMatrix::GetWorkBufferSize(params.sub_mixes + 1)};
  52. size += Common::AlignUp(node_size + edge_size, 0x10);
  53. }
  54. size += SplitterContext::CalcWorkBufferSize(behavior, params);
  55. size += (params.effects + params.voices * MaxWaveBuffers) * sizeof(MemoryPoolInfo);
  56. if (behavior.IsEffectInfoVersion2Supported()) {
  57. size += params.effects * sizeof(EffectResultState);
  58. }
  59. size += 0x50;
  60. size = Common::AlignUp(size, 0x40);
  61. size += (params.sinks + params.sub_mixes) * sizeof(UpsamplerInfo);
  62. size += params.effects * sizeof(EffectInfoBase);
  63. size += Common::AlignUp(params.voices * sizeof(VoiceState), 0x40);
  64. size += params.sinks * sizeof(SinkInfoBase);
  65. if (behavior.IsEffectInfoVersion2Supported()) {
  66. size += params.effects * sizeof(EffectResultState);
  67. }
  68. if (params.perf_frames > 0) {
  69. auto perf_size{PerformanceManager::GetRequiredBufferSizeForPerformanceMetricsPerFrame(
  70. behavior, params)};
  71. size += Common::AlignUp(perf_size * (params.perf_frames + 1) + 0xC0, 0x100);
  72. }
  73. if (behavior.IsVariadicCommandBufferSizeSupported()) {
  74. size += CommandGenerator::CalculateCommandBufferSize(behavior, params) + (0x40 - 1) * 2;
  75. } else {
  76. size += 0x18000 + (0x40 - 1) * 2;
  77. }
  78. size = Common::AlignUp(size, 0x1000);
  79. return size;
  80. }
  81. System::System(Core::System& core_, Kernel::KEvent* adsp_rendered_event_)
  82. : core{core_}, adsp{core.AudioCore().GetADSP()}, adsp_rendered_event{adsp_rendered_event_} {}
  83. Result System::Initialize(const AudioRendererParameterInternal& params,
  84. Kernel::KTransferMemory* transfer_memory, u64 transfer_memory_size,
  85. u32 process_handle_, u64 applet_resource_user_id_, s32 session_id_) {
  86. if (!CheckValidRevision(params.revision)) {
  87. return Service::Audio::ResultInvalidRevision;
  88. }
  89. if (GetWorkBufferSize(params) > transfer_memory_size) {
  90. return Service::Audio::ResultInsufficientBuffer;
  91. }
  92. if (process_handle_ == 0) {
  93. return Service::Audio::ResultInvalidHandle;
  94. }
  95. behavior.SetUserLibRevision(params.revision);
  96. process_handle = process_handle_;
  97. applet_resource_user_id = applet_resource_user_id_;
  98. session_id = session_id_;
  99. sample_rate = params.sample_rate;
  100. sample_count = params.sample_count;
  101. mix_buffer_count = static_cast<s16>(params.mixes);
  102. voice_channels = MaxChannels;
  103. upsampler_count = params.sinks + params.sub_mixes;
  104. memory_pool_count = params.effects + params.voices * MaxWaveBuffers;
  105. render_device = params.rendering_device;
  106. execution_mode = params.execution_mode;
  107. core.ApplicationMemory().ZeroBlock(transfer_memory->GetSourceAddress(), transfer_memory_size);
  108. // Note: We're not actually using the transfer memory because it's a pain to code for.
  109. // Allocate the memory normally instead and hope the game doesn't try to read anything back
  110. workbuffer = std::make_unique<u8[]>(transfer_memory_size);
  111. workbuffer_size = transfer_memory_size;
  112. PoolMapper pool_mapper(process_handle, false);
  113. pool_mapper.InitializeSystemPool(memory_pool_info, workbuffer.get(), workbuffer_size);
  114. WorkbufferAllocator allocator({workbuffer.get(), workbuffer_size}, workbuffer_size);
  115. samples_workbuffer =
  116. allocator.Allocate<s32>((voice_channels + mix_buffer_count) * sample_count, 0x10);
  117. if (samples_workbuffer.empty()) {
  118. return Service::Audio::ResultInsufficientBuffer;
  119. }
  120. auto upsampler_workbuffer{allocator.Allocate<s32>(
  121. (voice_channels + mix_buffer_count) * TargetSampleCount * upsampler_count, 0x10)};
  122. if (upsampler_workbuffer.empty()) {
  123. return Service::Audio::ResultInsufficientBuffer;
  124. }
  125. depop_buffer =
  126. allocator.Allocate<s32>(Common::AlignUp(static_cast<u32>(mix_buffer_count), 0x40), 0x40);
  127. if (depop_buffer.empty()) {
  128. return Service::Audio::ResultInsufficientBuffer;
  129. }
  130. // invalidate samples_workbuffer DSP cache
  131. auto voice_infos{allocator.Allocate<VoiceInfo>(params.voices, 0x10)};
  132. for (auto& voice_info : voice_infos) {
  133. std::construct_at<VoiceInfo>(&voice_info);
  134. }
  135. if (voice_infos.empty()) {
  136. return Service::Audio::ResultInsufficientBuffer;
  137. }
  138. auto sorted_voice_infos{allocator.Allocate<VoiceInfo*>(params.voices, 0x10)};
  139. if (sorted_voice_infos.empty()) {
  140. return Service::Audio::ResultInsufficientBuffer;
  141. }
  142. std::memset(sorted_voice_infos.data(), 0, sorted_voice_infos.size_bytes());
  143. auto voice_channel_resources{allocator.Allocate<VoiceChannelResource>(params.voices, 0x10)};
  144. u32 i{0};
  145. for (auto& voice_channel_resource : voice_channel_resources) {
  146. std::construct_at<VoiceChannelResource>(&voice_channel_resource, i++);
  147. }
  148. if (voice_channel_resources.empty()) {
  149. return Service::Audio::ResultInsufficientBuffer;
  150. }
  151. auto voice_cpu_states{allocator.Allocate<VoiceState>(params.voices, 0x10)};
  152. if (voice_cpu_states.empty()) {
  153. return Service::Audio::ResultInsufficientBuffer;
  154. }
  155. for (auto& voice_state : voice_cpu_states) {
  156. voice_state = {};
  157. }
  158. auto mix_infos{allocator.Allocate<MixInfo>(params.sub_mixes + 1, 0x10)};
  159. if (mix_infos.empty()) {
  160. return Service::Audio::ResultInsufficientBuffer;
  161. }
  162. u32 effect_process_order_count{0};
  163. std::span<s32> effect_process_order_buffer{};
  164. if (params.effects > 0) {
  165. effect_process_order_count = params.effects * (params.sub_mixes + 1);
  166. effect_process_order_buffer = allocator.Allocate<s32>(effect_process_order_count, 0x10);
  167. if (effect_process_order_buffer.empty()) {
  168. return Service::Audio::ResultInsufficientBuffer;
  169. }
  170. }
  171. i = 0;
  172. for (auto& mix_info : mix_infos) {
  173. std::construct_at<MixInfo>(
  174. &mix_info, effect_process_order_buffer.subspan(i * params.effects, params.effects),
  175. params.effects, this->behavior);
  176. i++;
  177. }
  178. auto sorted_mix_infos{allocator.Allocate<MixInfo*>(params.sub_mixes + 1, 0x10)};
  179. if (sorted_mix_infos.empty()) {
  180. return Service::Audio::ResultInsufficientBuffer;
  181. }
  182. std::memset(sorted_mix_infos.data(), 0, sorted_mix_infos.size_bytes());
  183. if (behavior.IsSplitterSupported()) {
  184. u64 node_state_size{NodeStates::GetWorkBufferSize(params.sub_mixes + 1)};
  185. u64 edge_matrix_size{EdgeMatrix::GetWorkBufferSize(params.sub_mixes + 1)};
  186. auto node_states_workbuffer{allocator.Allocate<u8>(node_state_size, 1)};
  187. auto edge_matrix_workbuffer{allocator.Allocate<u8>(edge_matrix_size, 1)};
  188. if (node_states_workbuffer.empty() || edge_matrix_workbuffer.size() == 0) {
  189. return Service::Audio::ResultInsufficientBuffer;
  190. }
  191. mix_context.Initialize(sorted_mix_infos, mix_infos, params.sub_mixes + 1,
  192. effect_process_order_buffer, effect_process_order_count,
  193. node_states_workbuffer, node_state_size, edge_matrix_workbuffer,
  194. edge_matrix_size);
  195. } else {
  196. mix_context.Initialize(sorted_mix_infos, mix_infos, params.sub_mixes + 1,
  197. effect_process_order_buffer, effect_process_order_count, {}, 0, {},
  198. 0);
  199. }
  200. upsampler_manager = allocator.Allocate<UpsamplerManager>(1, 0x10).data();
  201. if (upsampler_manager == nullptr) {
  202. return Service::Audio::ResultInsufficientBuffer;
  203. }
  204. memory_pool_workbuffer = allocator.Allocate<MemoryPoolInfo>(memory_pool_count, 0x10);
  205. for (auto& memory_pool : memory_pool_workbuffer) {
  206. std::construct_at<MemoryPoolInfo>(&memory_pool, MemoryPoolInfo::Location::DSP);
  207. }
  208. if (memory_pool_workbuffer.empty() && memory_pool_count > 0) {
  209. return Service::Audio::ResultInsufficientBuffer;
  210. }
  211. if (!splitter_context.Initialize(behavior, params, allocator)) {
  212. return Service::Audio::ResultInsufficientBuffer;
  213. }
  214. std::span<EffectResultState> effect_result_states_cpu{};
  215. if (behavior.IsEffectInfoVersion2Supported() && params.effects > 0) {
  216. effect_result_states_cpu = allocator.Allocate<EffectResultState>(params.effects, 0x10);
  217. if (effect_result_states_cpu.empty()) {
  218. return Service::Audio::ResultInsufficientBuffer;
  219. }
  220. std::memset(effect_result_states_cpu.data(), 0, effect_result_states_cpu.size_bytes());
  221. }
  222. allocator.Align(0x40);
  223. unk_2B0 = allocator.GetSize() - allocator.GetCurrentOffset();
  224. unk_2A8 = {&workbuffer[allocator.GetCurrentOffset()], unk_2B0};
  225. upsampler_infos = allocator.Allocate<UpsamplerInfo>(upsampler_count, 0x40);
  226. for (auto& upsampler_info : upsampler_infos) {
  227. std::construct_at<UpsamplerInfo>(&upsampler_info);
  228. }
  229. std::construct_at<UpsamplerManager>(upsampler_manager, upsampler_count, upsampler_infos,
  230. upsampler_workbuffer);
  231. if (upsampler_infos.empty()) {
  232. return Service::Audio::ResultInsufficientBuffer;
  233. }
  234. auto effect_infos{allocator.Allocate<EffectInfoBase>(params.effects, 0x40)};
  235. for (auto& effect_info : effect_infos) {
  236. std::construct_at<EffectInfoBase>(&effect_info);
  237. }
  238. if (effect_infos.empty() && params.effects > 0) {
  239. return Service::Audio::ResultInsufficientBuffer;
  240. }
  241. std::span<EffectResultState> effect_result_states_dsp{};
  242. if (behavior.IsEffectInfoVersion2Supported() && params.effects > 0) {
  243. effect_result_states_dsp = allocator.Allocate<EffectResultState>(params.effects, 0x40);
  244. if (effect_result_states_dsp.empty()) {
  245. return Service::Audio::ResultInsufficientBuffer;
  246. }
  247. std::memset(effect_result_states_dsp.data(), 0, effect_result_states_dsp.size_bytes());
  248. }
  249. effect_context.Initialize(effect_infos, params.effects, effect_result_states_cpu,
  250. effect_result_states_dsp, effect_result_states_dsp.size());
  251. auto sinks{allocator.Allocate<SinkInfoBase>(params.sinks, 0x10)};
  252. for (auto& sink : sinks) {
  253. std::construct_at<SinkInfoBase>(&sink);
  254. }
  255. if (sinks.empty()) {
  256. return Service::Audio::ResultInsufficientBuffer;
  257. }
  258. sink_context.Initialize(sinks, params.sinks);
  259. auto voice_dsp_states{allocator.Allocate<VoiceState>(params.voices, 0x40)};
  260. if (voice_dsp_states.empty()) {
  261. return Service::Audio::ResultInsufficientBuffer;
  262. }
  263. for (auto& voice_state : voice_dsp_states) {
  264. voice_state = {};
  265. }
  266. voice_context.Initialize(sorted_voice_infos, voice_infos, voice_channel_resources,
  267. voice_cpu_states, voice_dsp_states, params.voices);
  268. if (params.perf_frames > 0) {
  269. const auto perf_workbuffer_size{
  270. PerformanceManager::GetRequiredBufferSizeForPerformanceMetricsPerFrame(behavior,
  271. params) *
  272. (params.perf_frames + 1) +
  273. 0xC};
  274. performance_workbuffer = allocator.Allocate<u8>(perf_workbuffer_size, 0x40);
  275. if (performance_workbuffer.empty()) {
  276. return Service::Audio::ResultInsufficientBuffer;
  277. }
  278. std::memset(performance_workbuffer.data(), 0, performance_workbuffer.size_bytes());
  279. performance_manager.Initialize(performance_workbuffer, performance_workbuffer.size_bytes(),
  280. params, behavior, memory_pool_info);
  281. }
  282. render_time_limit_percent = 100;
  283. drop_voice = params.voice_drop_enabled && params.execution_mode == ExecutionMode::Auto;
  284. drop_voice_param = 1.0f;
  285. num_voices_dropped = 0;
  286. allocator.Align(0x40);
  287. command_workbuffer_size = allocator.GetRemainingSize();
  288. command_workbuffer = allocator.Allocate<u8>(command_workbuffer_size, 0x40);
  289. if (command_workbuffer.empty()) {
  290. return Service::Audio::ResultInsufficientBuffer;
  291. }
  292. command_buffer_size = 0;
  293. reset_command_buffers = true;
  294. // nn::audio::dsp::FlushDataCache(transferMemory, transferMemorySize);
  295. if (behavior.IsCommandProcessingTimeEstimatorVersion5Supported()) {
  296. command_processing_time_estimator =
  297. std::make_unique<CommandProcessingTimeEstimatorVersion5>(sample_count,
  298. mix_buffer_count);
  299. } else if (behavior.IsCommandProcessingTimeEstimatorVersion4Supported()) {
  300. command_processing_time_estimator =
  301. std::make_unique<CommandProcessingTimeEstimatorVersion4>(sample_count,
  302. mix_buffer_count);
  303. } else if (behavior.IsCommandProcessingTimeEstimatorVersion3Supported()) {
  304. command_processing_time_estimator =
  305. std::make_unique<CommandProcessingTimeEstimatorVersion3>(sample_count,
  306. mix_buffer_count);
  307. } else if (behavior.IsCommandProcessingTimeEstimatorVersion2Supported()) {
  308. command_processing_time_estimator =
  309. std::make_unique<CommandProcessingTimeEstimatorVersion2>(sample_count,
  310. mix_buffer_count);
  311. } else {
  312. command_processing_time_estimator =
  313. std::make_unique<CommandProcessingTimeEstimatorVersion1>(sample_count,
  314. mix_buffer_count);
  315. }
  316. initialized = true;
  317. return ResultSuccess;
  318. }
  319. void System::Finalize() {
  320. if (!initialized) {
  321. return;
  322. }
  323. if (active) {
  324. Stop();
  325. }
  326. applet_resource_user_id = 0;
  327. PoolMapper pool_mapper(process_handle, false);
  328. pool_mapper.Unmap(memory_pool_info);
  329. if (process_handle) {
  330. pool_mapper.ClearUseState(memory_pool_workbuffer, memory_pool_count);
  331. for (auto& memory_pool : memory_pool_workbuffer) {
  332. if (memory_pool.IsMapped()) {
  333. pool_mapper.Unmap(memory_pool);
  334. }
  335. }
  336. // dsp::ProcessCleanup
  337. // close handle
  338. }
  339. initialized = false;
  340. }
  341. void System::Start() {
  342. std::scoped_lock l{lock};
  343. frames_elapsed = 0;
  344. state = State::Started;
  345. active = true;
  346. }
  347. void System::Stop() {
  348. {
  349. std::scoped_lock l{lock};
  350. state = State::Stopped;
  351. active = false;
  352. }
  353. if (execution_mode == ExecutionMode::Auto) {
  354. terminate_event.Wait();
  355. }
  356. }
  357. Result System::Update(std::span<const u8> input, std::span<u8> performance, std::span<u8> output) {
  358. std::scoped_lock l{lock};
  359. const auto start_time{core.CoreTiming().GetClockTicks()};
  360. InfoUpdater info_updater(input, output, process_handle, behavior);
  361. auto result{info_updater.UpdateBehaviorInfo(behavior)};
  362. if (result.IsError()) {
  363. LOG_ERROR(Service_Audio, "Failed to update BehaviorInfo!");
  364. return result;
  365. }
  366. result = info_updater.UpdateMemoryPools(memory_pool_workbuffer, memory_pool_count);
  367. if (result.IsError()) {
  368. LOG_ERROR(Service_Audio, "Failed to update MemoryPools!");
  369. return result;
  370. }
  371. result = info_updater.UpdateVoiceChannelResources(voice_context);
  372. if (result.IsError()) {
  373. LOG_ERROR(Service_Audio, "Failed to update VoiceChannelResources!");
  374. return result;
  375. }
  376. result = info_updater.UpdateVoices(voice_context, memory_pool_workbuffer, memory_pool_count);
  377. if (result.IsError()) {
  378. LOG_ERROR(Service_Audio, "Failed to update Voices!");
  379. return result;
  380. }
  381. result = info_updater.UpdateEffects(effect_context, active, memory_pool_workbuffer,
  382. memory_pool_count);
  383. if (result.IsError()) {
  384. LOG_ERROR(Service_Audio, "Failed to update Effects!");
  385. return result;
  386. }
  387. if (behavior.IsSplitterSupported()) {
  388. result = info_updater.UpdateSplitterInfo(splitter_context);
  389. if (result.IsError()) {
  390. LOG_ERROR(Service_Audio, "Failed to update SplitterInfo!");
  391. return result;
  392. }
  393. }
  394. result =
  395. info_updater.UpdateMixes(mix_context, mix_buffer_count, effect_context, splitter_context);
  396. if (result.IsError()) {
  397. LOG_ERROR(Service_Audio, "Failed to update Mixes!");
  398. return result;
  399. }
  400. result = info_updater.UpdateSinks(sink_context, memory_pool_workbuffer, memory_pool_count);
  401. if (result.IsError()) {
  402. LOG_ERROR(Service_Audio, "Failed to update Sinks!");
  403. return result;
  404. }
  405. PerformanceManager* perf_manager{nullptr};
  406. if (performance_manager.IsInitialized()) {
  407. perf_manager = &performance_manager;
  408. }
  409. result =
  410. info_updater.UpdatePerformanceBuffer(performance, performance.size_bytes(), perf_manager);
  411. if (result.IsError()) {
  412. LOG_ERROR(Service_Audio, "Failed to update PerformanceBuffer!");
  413. return result;
  414. }
  415. result = info_updater.UpdateErrorInfo(behavior);
  416. if (result.IsError()) {
  417. LOG_ERROR(Service_Audio, "Failed to update ErrorInfo!");
  418. return result;
  419. }
  420. if (behavior.IsElapsedFrameCountSupported()) {
  421. result = info_updater.UpdateRendererInfo(frames_elapsed);
  422. if (result.IsError()) {
  423. LOG_ERROR(Service_Audio, "Failed to update RendererInfo!");
  424. return result;
  425. }
  426. }
  427. result = info_updater.CheckConsumedSize();
  428. if (result.IsError()) {
  429. LOG_ERROR(Service_Audio, "Invalid consume size!");
  430. return result;
  431. }
  432. adsp_rendered_event->Clear();
  433. num_times_updated++;
  434. const auto end_time{core.CoreTiming().GetClockTicks()};
  435. ticks_spent_updating += end_time - start_time;
  436. return ResultSuccess;
  437. }
  438. u32 System::GetRenderingTimeLimit() const {
  439. return render_time_limit_percent;
  440. }
  441. void System::SetRenderingTimeLimit(u32 limit) {
  442. render_time_limit_percent = limit;
  443. }
  444. u32 System::GetSessionId() const {
  445. return session_id;
  446. }
  447. u32 System::GetSampleRate() const {
  448. return sample_rate;
  449. }
  450. u32 System::GetSampleCount() const {
  451. return sample_count;
  452. }
  453. u32 System::GetMixBufferCount() const {
  454. return mix_buffer_count;
  455. }
  456. ExecutionMode System::GetExecutionMode() const {
  457. return execution_mode;
  458. }
  459. u32 System::GetRenderingDevice() const {
  460. return render_device;
  461. }
  462. bool System::IsActive() const {
  463. return active;
  464. }
  465. void System::SendCommandToDsp() {
  466. std::scoped_lock l{lock};
  467. if (initialized) {
  468. if (active) {
  469. terminate_event.Reset();
  470. const auto remaining_command_count{adsp.GetRemainCommandCount(session_id)};
  471. u64 command_size{0};
  472. if (remaining_command_count) {
  473. adsp_behind = true;
  474. command_size = command_buffer_size;
  475. } else {
  476. command_size = GenerateCommand(command_workbuffer, command_workbuffer_size);
  477. }
  478. auto translated_addr{
  479. memory_pool_info.Translate(CpuAddr(command_workbuffer.data()), command_size)};
  480. auto time_limit_percent{70.0f};
  481. if (behavior.IsAudioRendererProcessingTimeLimit80PercentSupported()) {
  482. time_limit_percent = 80.0f;
  483. } else if (behavior.IsAudioRendererProcessingTimeLimit75PercentSupported()) {
  484. time_limit_percent = 75.0f;
  485. } else {
  486. // result ignored and 70 is used anyway
  487. behavior.IsAudioRendererProcessingTimeLimit70PercentSupported();
  488. time_limit_percent = 70.0f;
  489. }
  490. ADSP::CommandBuffer command_buffer{
  491. .buffer{translated_addr},
  492. .size{command_size},
  493. .time_limit{
  494. static_cast<u64>((time_limit_percent / 100) * 2'880'000.0 *
  495. (static_cast<f32>(render_time_limit_percent) / 100.0f))},
  496. .remaining_command_count{remaining_command_count},
  497. .reset_buffers{reset_command_buffers},
  498. .applet_resource_user_id{applet_resource_user_id},
  499. .render_time_taken{adsp.GetRenderTimeTaken(session_id)},
  500. };
  501. adsp.SendCommandBuffer(session_id, command_buffer);
  502. reset_command_buffers = false;
  503. command_buffer_size = command_size;
  504. if (remaining_command_count == 0) {
  505. adsp_rendered_event->Signal();
  506. }
  507. } else {
  508. adsp.ClearRemainCount(session_id);
  509. terminate_event.Set();
  510. }
  511. }
  512. }
  513. u64 System::GenerateCommand(std::span<u8> in_command_buffer,
  514. [[maybe_unused]] u64 command_buffer_size_) {
  515. PoolMapper::ClearUseState(memory_pool_workbuffer, memory_pool_count);
  516. const auto start_time{core.CoreTiming().GetClockTicks()};
  517. auto command_list_header{reinterpret_cast<CommandListHeader*>(in_command_buffer.data())};
  518. command_list_header->buffer_count = static_cast<s16>(voice_channels + mix_buffer_count);
  519. command_list_header->sample_count = sample_count;
  520. command_list_header->sample_rate = sample_rate;
  521. command_list_header->samples_buffer = samples_workbuffer;
  522. const auto performance_initialized{performance_manager.IsInitialized()};
  523. if (performance_initialized) {
  524. performance_manager.TapFrame(adsp_behind, num_voices_dropped, render_start_tick);
  525. adsp_behind = false;
  526. num_voices_dropped = 0;
  527. render_start_tick = 0;
  528. }
  529. s8 channel_count{2};
  530. if (execution_mode == ExecutionMode::Auto) {
  531. const auto& sink{core.AudioCore().GetOutputSink()};
  532. channel_count = static_cast<s8>(sink.GetDeviceChannels());
  533. }
  534. AudioRendererSystemContext render_context{
  535. .session_id{session_id},
  536. .channels{channel_count},
  537. .mix_buffer_count{mix_buffer_count},
  538. .behavior{&behavior},
  539. .depop_buffer{depop_buffer},
  540. .upsampler_manager{upsampler_manager},
  541. .memory_pool_info{&memory_pool_info},
  542. };
  543. CommandBuffer command_buffer{
  544. .command_list{in_command_buffer},
  545. .sample_count{sample_count},
  546. .sample_rate{sample_rate},
  547. .size{sizeof(CommandListHeader)},
  548. .count{0},
  549. .estimated_process_time{0},
  550. .memory_pool{&memory_pool_info},
  551. .time_estimator{command_processing_time_estimator.get()},
  552. .behavior{&behavior},
  553. };
  554. PerformanceManager* perf_manager{nullptr};
  555. if (performance_initialized) {
  556. perf_manager = &performance_manager;
  557. }
  558. CommandGenerator command_generator{command_buffer, *command_list_header, render_context,
  559. voice_context, mix_context, effect_context,
  560. sink_context, splitter_context, perf_manager};
  561. voice_context.SortInfo();
  562. const auto start_estimated_time{drop_voice_param *
  563. static_cast<f32>(command_buffer.estimated_process_time)};
  564. command_generator.GenerateVoiceCommands();
  565. command_generator.GenerateSubMixCommands();
  566. command_generator.GenerateFinalMixCommands();
  567. command_generator.GenerateSinkCommands();
  568. if (drop_voice) {
  569. f32 time_limit_percent{70.0f};
  570. if (render_context.behavior->IsAudioRendererProcessingTimeLimit80PercentSupported()) {
  571. time_limit_percent = 80.0f;
  572. } else if (render_context.behavior
  573. ->IsAudioRendererProcessingTimeLimit75PercentSupported()) {
  574. time_limit_percent = 75.0f;
  575. } else {
  576. // result is ignored
  577. render_context.behavior->IsAudioRendererProcessingTimeLimit70PercentSupported();
  578. time_limit_percent = 70.0f;
  579. }
  580. const auto end_estimated_time{drop_voice_param *
  581. static_cast<f32>(command_buffer.estimated_process_time)};
  582. const auto estimated_time{start_estimated_time - end_estimated_time};
  583. const auto time_limit{static_cast<u32>(
  584. estimated_time + (((time_limit_percent / 100.0f) * 2'880'000.0) *
  585. (static_cast<f32>(render_time_limit_percent) / 100.0f)))};
  586. num_voices_dropped =
  587. DropVoices(command_buffer, static_cast<u32>(start_estimated_time), time_limit);
  588. }
  589. command_list_header->buffer_size = command_buffer.size;
  590. command_list_header->command_count = command_buffer.count;
  591. voice_context.UpdateStateByDspShared();
  592. if (render_context.behavior->IsEffectInfoVersion2Supported()) {
  593. effect_context.UpdateStateByDspShared();
  594. }
  595. const auto end_time{core.CoreTiming().GetClockTicks()};
  596. total_ticks_elapsed += end_time - start_time;
  597. num_command_lists_generated++;
  598. render_start_tick = adsp.GetRenderingStartTick(session_id);
  599. frames_elapsed++;
  600. return command_buffer.size;
  601. }
  602. f32 System::GetVoiceDropParameter() const {
  603. return drop_voice_param;
  604. }
  605. void System::SetVoiceDropParameter(f32 voice_drop_) {
  606. drop_voice_param = voice_drop_;
  607. }
  608. u32 System::DropVoices(CommandBuffer& command_buffer, u32 estimated_process_time, u32 time_limit) {
  609. u32 i{0};
  610. auto command_list{command_buffer.command_list.data() + sizeof(CommandListHeader)};
  611. ICommand* cmd{nullptr};
  612. // Find a first valid voice to drop
  613. while (i < command_buffer.count) {
  614. cmd = reinterpret_cast<ICommand*>(command_list);
  615. if (cmd->type == CommandId::Performance ||
  616. cmd->type == CommandId::DataSourcePcmInt16Version1 ||
  617. cmd->type == CommandId::DataSourcePcmInt16Version2 ||
  618. cmd->type == CommandId::DataSourcePcmFloatVersion1 ||
  619. cmd->type == CommandId::DataSourcePcmFloatVersion2 ||
  620. cmd->type == CommandId::DataSourceAdpcmVersion1 ||
  621. cmd->type == CommandId::DataSourceAdpcmVersion2) {
  622. break;
  623. }
  624. command_list += cmd->size;
  625. i++;
  626. }
  627. if (cmd == nullptr || command_buffer.count == 0 || i >= command_buffer.count) {
  628. return 0;
  629. }
  630. auto voices_dropped{0};
  631. while (i < command_buffer.count) {
  632. const auto node_id{cmd->node_id};
  633. const auto node_id_type{cmd->node_id >> 28};
  634. const auto node_id_base{cmd->node_id & 0xFFF};
  635. // If the new estimated process time falls below the limit, we're done dropping.
  636. if (estimated_process_time <= time_limit) {
  637. break;
  638. }
  639. if (node_id_type != 1) {
  640. break;
  641. }
  642. // Don't drop voices marked with the highest priority.
  643. auto& voice_info{voice_context.GetInfo(node_id_base)};
  644. if (voice_info.priority == HighestVoicePriority) {
  645. break;
  646. }
  647. voices_dropped++;
  648. voice_info.voice_dropped = true;
  649. // First iteration should drop the voice, and then iterate through all of the commands tied
  650. // to the voice. We don't need reverb on a voice which we've just removed, for example.
  651. // Depops can't be removed otherwise we'll introduce audio popping, and we don't
  652. // remove perf commands. Lower the estimated time for each command dropped.
  653. while (i < command_buffer.count && cmd->node_id == node_id) {
  654. if (cmd->type == CommandId::DepopPrepare) {
  655. cmd->enabled = true;
  656. } else if (cmd->enabled && cmd->type != CommandId::Performance) {
  657. cmd->enabled = false;
  658. estimated_process_time -= static_cast<u32>(
  659. drop_voice_param * static_cast<f32>(cmd->estimated_process_time));
  660. }
  661. command_list += cmd->size;
  662. cmd = reinterpret_cast<ICommand*>(command_list);
  663. i++;
  664. }
  665. i++;
  666. }
  667. return voices_dropped;
  668. }
  669. } // namespace AudioCore::AudioRenderer