system.cpp 30 KB

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