hwopus.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. // SPDX-FileCopyrightText: Copyright 2018 yuzu Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #include <chrono>
  4. #include <cstring>
  5. #include <memory>
  6. #include <vector>
  7. #include <opus.h>
  8. #include <opus_multistream.h>
  9. #include "common/assert.h"
  10. #include "common/logging/log.h"
  11. #include "core/hle/ipc_helpers.h"
  12. #include "core/hle/service/audio/hwopus.h"
  13. namespace Service::Audio {
  14. namespace {
  15. struct OpusDeleter {
  16. void operator()(OpusMSDecoder* ptr) const {
  17. opus_multistream_decoder_destroy(ptr);
  18. }
  19. };
  20. using OpusDecoderPtr = std::unique_ptr<OpusMSDecoder, OpusDeleter>;
  21. struct OpusPacketHeader {
  22. // Packet size in bytes.
  23. u32_be size;
  24. // Indicates the final range of the codec's entropy coder.
  25. u32_be final_range;
  26. };
  27. static_assert(sizeof(OpusPacketHeader) == 0x8, "OpusHeader is an invalid size");
  28. class OpusDecoderState {
  29. public:
  30. /// Describes extra behavior that may be asked of the decoding context.
  31. enum class ExtraBehavior {
  32. /// No extra behavior.
  33. None,
  34. /// Resets the decoder context back to a freshly initialized state.
  35. ResetContext,
  36. };
  37. enum class PerfTime {
  38. Disabled,
  39. Enabled,
  40. };
  41. explicit OpusDecoderState(OpusDecoderPtr decoder_, u32 sample_rate_, u32 channel_count_)
  42. : decoder{std::move(decoder_)}, sample_rate{sample_rate_}, channel_count{channel_count_} {}
  43. // Decodes interleaved Opus packets. Optionally allows reporting time taken to
  44. // perform the decoding, as well as any relevant extra behavior.
  45. void DecodeInterleaved(Kernel::HLERequestContext& ctx, PerfTime perf_time,
  46. ExtraBehavior extra_behavior) {
  47. if (perf_time == PerfTime::Disabled) {
  48. DecodeInterleavedHelper(ctx, nullptr, extra_behavior);
  49. } else {
  50. u64 performance = 0;
  51. DecodeInterleavedHelper(ctx, &performance, extra_behavior);
  52. }
  53. }
  54. private:
  55. void DecodeInterleavedHelper(Kernel::HLERequestContext& ctx, u64* performance,
  56. ExtraBehavior extra_behavior) {
  57. u32 consumed = 0;
  58. u32 sample_count = 0;
  59. std::vector<opus_int16> samples(ctx.GetWriteBufferNumElements<opus_int16>());
  60. if (extra_behavior == ExtraBehavior::ResetContext) {
  61. ResetDecoderContext();
  62. }
  63. if (!DecodeOpusData(consumed, sample_count, ctx.ReadBuffer(), samples, performance)) {
  64. LOG_ERROR(Audio, "Failed to decode opus data");
  65. IPC::ResponseBuilder rb{ctx, 2};
  66. // TODO(ogniK): Use correct error code
  67. rb.Push(ResultUnknown);
  68. return;
  69. }
  70. const u32 param_size = performance != nullptr ? 6 : 4;
  71. IPC::ResponseBuilder rb{ctx, param_size};
  72. rb.Push(ResultSuccess);
  73. rb.Push<u32>(consumed);
  74. rb.Push<u32>(sample_count);
  75. if (performance) {
  76. rb.Push<u64>(*performance);
  77. }
  78. ctx.WriteBuffer(samples);
  79. }
  80. bool DecodeOpusData(u32& consumed, u32& sample_count, const std::vector<u8>& input,
  81. std::vector<opus_int16>& output, u64* out_performance_time) const {
  82. const auto start_time = std::chrono::steady_clock::now();
  83. const std::size_t raw_output_sz = output.size() * sizeof(opus_int16);
  84. if (sizeof(OpusPacketHeader) > input.size()) {
  85. LOG_ERROR(Audio, "Input is smaller than the header size, header_sz={}, input_sz={}",
  86. sizeof(OpusPacketHeader), input.size());
  87. return false;
  88. }
  89. OpusPacketHeader hdr{};
  90. std::memcpy(&hdr, input.data(), sizeof(OpusPacketHeader));
  91. if (sizeof(OpusPacketHeader) + static_cast<u32>(hdr.size) > input.size()) {
  92. LOG_ERROR(Audio, "Input does not fit in the opus header size. data_sz={}, input_sz={}",
  93. sizeof(OpusPacketHeader) + static_cast<u32>(hdr.size), input.size());
  94. return false;
  95. }
  96. const auto frame = input.data() + sizeof(OpusPacketHeader);
  97. const auto decoded_sample_count = opus_packet_get_nb_samples(
  98. frame, static_cast<opus_int32>(input.size() - sizeof(OpusPacketHeader)),
  99. static_cast<opus_int32>(sample_rate));
  100. if (decoded_sample_count * channel_count * sizeof(u16) > raw_output_sz) {
  101. LOG_ERROR(
  102. Audio,
  103. "Decoded data does not fit into the output data, decoded_sz={}, raw_output_sz={}",
  104. decoded_sample_count * channel_count * sizeof(u16), raw_output_sz);
  105. return false;
  106. }
  107. const int frame_size = (static_cast<int>(raw_output_sz / sizeof(s16) / channel_count));
  108. const auto out_sample_count =
  109. opus_multistream_decode(decoder.get(), frame, hdr.size, output.data(), frame_size, 0);
  110. if (out_sample_count < 0) {
  111. LOG_ERROR(Audio,
  112. "Incorrect sample count received from opus_decode, "
  113. "output_sample_count={}, frame_size={}, data_sz_from_hdr={}",
  114. out_sample_count, frame_size, static_cast<u32>(hdr.size));
  115. return false;
  116. }
  117. const auto end_time = std::chrono::steady_clock::now() - start_time;
  118. sample_count = out_sample_count;
  119. consumed = static_cast<u32>(sizeof(OpusPacketHeader) + hdr.size);
  120. if (out_performance_time != nullptr) {
  121. *out_performance_time =
  122. std::chrono::duration_cast<std::chrono::milliseconds>(end_time).count();
  123. }
  124. return true;
  125. }
  126. void ResetDecoderContext() {
  127. ASSERT(decoder != nullptr);
  128. opus_multistream_decoder_ctl(decoder.get(), OPUS_RESET_STATE);
  129. }
  130. OpusDecoderPtr decoder;
  131. u32 sample_rate;
  132. u32 channel_count;
  133. };
  134. class IHardwareOpusDecoderManager final : public ServiceFramework<IHardwareOpusDecoderManager> {
  135. public:
  136. explicit IHardwareOpusDecoderManager(Core::System& system_, OpusDecoderState decoder_state_)
  137. : ServiceFramework{system_, "IHardwareOpusDecoderManager"}, decoder_state{
  138. std::move(decoder_state_)} {
  139. // clang-format off
  140. static const FunctionInfo functions[] = {
  141. {0, &IHardwareOpusDecoderManager::DecodeInterleavedOld, "DecodeInterleavedOld"},
  142. {1, nullptr, "SetContext"},
  143. {2, nullptr, "DecodeInterleavedForMultiStreamOld"},
  144. {3, nullptr, "SetContextForMultiStream"},
  145. {4, &IHardwareOpusDecoderManager::DecodeInterleavedWithPerfOld, "DecodeInterleavedWithPerfOld"},
  146. {5, nullptr, "DecodeInterleavedForMultiStreamWithPerfOld"},
  147. {6, &IHardwareOpusDecoderManager::DecodeInterleaved, "DecodeInterleavedWithPerfAndResetOld"},
  148. {7, nullptr, "DecodeInterleavedForMultiStreamWithPerfAndResetOld"},
  149. {8, &IHardwareOpusDecoderManager::DecodeInterleaved, "DecodeInterleaved"},
  150. {9, nullptr, "DecodeInterleavedForMultiStream"},
  151. };
  152. // clang-format on
  153. RegisterHandlers(functions);
  154. }
  155. private:
  156. void DecodeInterleavedOld(Kernel::HLERequestContext& ctx) {
  157. LOG_DEBUG(Audio, "called");
  158. decoder_state.DecodeInterleaved(ctx, OpusDecoderState::PerfTime::Disabled,
  159. OpusDecoderState::ExtraBehavior::None);
  160. }
  161. void DecodeInterleavedWithPerfOld(Kernel::HLERequestContext& ctx) {
  162. LOG_DEBUG(Audio, "called");
  163. decoder_state.DecodeInterleaved(ctx, OpusDecoderState::PerfTime::Enabled,
  164. OpusDecoderState::ExtraBehavior::None);
  165. }
  166. void DecodeInterleaved(Kernel::HLERequestContext& ctx) {
  167. LOG_DEBUG(Audio, "called");
  168. IPC::RequestParser rp{ctx};
  169. const auto extra_behavior = rp.Pop<bool>() ? OpusDecoderState::ExtraBehavior::ResetContext
  170. : OpusDecoderState::ExtraBehavior::None;
  171. decoder_state.DecodeInterleaved(ctx, OpusDecoderState::PerfTime::Enabled, extra_behavior);
  172. }
  173. OpusDecoderState decoder_state;
  174. };
  175. std::size_t WorkerBufferSize(u32 channel_count) {
  176. ASSERT_MSG(channel_count == 1 || channel_count == 2, "Invalid channel count");
  177. constexpr int num_streams = 1;
  178. const int num_stereo_streams = channel_count == 2 ? 1 : 0;
  179. return opus_multistream_decoder_get_size(num_streams, num_stereo_streams);
  180. }
  181. // Creates the mapping table that maps the input channels to the particular
  182. // output channels. In the stereo case, we map the left and right input channels
  183. // to the left and right output channels respectively.
  184. //
  185. // However, in the monophonic case, we only map the one available channel
  186. // to the sole output channel. We specify 255 for the would-be right channel
  187. // as this is a special value defined by Opus to indicate to the decoder to
  188. // ignore that channel.
  189. std::array<u8, 2> CreateMappingTable(u32 channel_count) {
  190. if (channel_count == 2) {
  191. return {{0, 1}};
  192. }
  193. return {{0, 255}};
  194. }
  195. } // Anonymous namespace
  196. void HwOpus::GetWorkBufferSize(Kernel::HLERequestContext& ctx) {
  197. IPC::RequestParser rp{ctx};
  198. const auto sample_rate = rp.Pop<u32>();
  199. const auto channel_count = rp.Pop<u32>();
  200. LOG_DEBUG(Audio, "called with sample_rate={}, channel_count={}", sample_rate, channel_count);
  201. ASSERT_MSG(sample_rate == 48000 || sample_rate == 24000 || sample_rate == 16000 ||
  202. sample_rate == 12000 || sample_rate == 8000,
  203. "Invalid sample rate");
  204. ASSERT_MSG(channel_count == 1 || channel_count == 2, "Invalid channel count");
  205. const u32 worker_buffer_sz = static_cast<u32>(WorkerBufferSize(channel_count));
  206. LOG_DEBUG(Audio, "worker_buffer_sz={}", worker_buffer_sz);
  207. IPC::ResponseBuilder rb{ctx, 3};
  208. rb.Push(ResultSuccess);
  209. rb.Push<u32>(worker_buffer_sz);
  210. }
  211. void HwOpus::GetWorkBufferSizeEx(Kernel::HLERequestContext& ctx) {
  212. GetWorkBufferSize(ctx);
  213. }
  214. void HwOpus::GetWorkBufferSizeForMultiStreamEx(Kernel::HLERequestContext& ctx) {
  215. OpusMultiStreamParametersEx param;
  216. std::memcpy(&param, ctx.ReadBuffer().data(), ctx.GetReadBufferSize());
  217. const auto sample_rate = param.sample_rate;
  218. const auto channel_count = param.channel_count;
  219. const auto number_streams = param.number_streams;
  220. const auto number_stereo_streams = param.number_stereo_streams;
  221. LOG_DEBUG(
  222. Audio,
  223. "called with sample_rate={}, channel_count={}, number_streams={}, number_stereo_streams={}",
  224. sample_rate, channel_count, number_streams, number_stereo_streams);
  225. ASSERT_MSG(sample_rate == 48000 || sample_rate == 24000 || sample_rate == 16000 ||
  226. sample_rate == 12000 || sample_rate == 8000,
  227. "Invalid sample rate");
  228. const u32 worker_buffer_sz =
  229. static_cast<u32>(opus_multistream_decoder_get_size(number_streams, number_stereo_streams));
  230. IPC::ResponseBuilder rb{ctx, 3};
  231. rb.Push(ResultSuccess);
  232. rb.Push<u32>(worker_buffer_sz);
  233. }
  234. void HwOpus::OpenHardwareOpusDecoder(Kernel::HLERequestContext& ctx) {
  235. IPC::RequestParser rp{ctx};
  236. const auto sample_rate = rp.Pop<u32>();
  237. const auto channel_count = rp.Pop<u32>();
  238. const auto buffer_sz = rp.Pop<u32>();
  239. LOG_DEBUG(Audio, "called sample_rate={}, channel_count={}, buffer_size={}", sample_rate,
  240. channel_count, buffer_sz);
  241. ASSERT_MSG(sample_rate == 48000 || sample_rate == 24000 || sample_rate == 16000 ||
  242. sample_rate == 12000 || sample_rate == 8000,
  243. "Invalid sample rate");
  244. ASSERT_MSG(channel_count == 1 || channel_count == 2, "Invalid channel count");
  245. const std::size_t worker_sz = WorkerBufferSize(channel_count);
  246. ASSERT_MSG(buffer_sz >= worker_sz, "Worker buffer too large");
  247. const int num_stereo_streams = channel_count == 2 ? 1 : 0;
  248. const auto mapping_table = CreateMappingTable(channel_count);
  249. int error = 0;
  250. OpusDecoderPtr decoder{
  251. opus_multistream_decoder_create(sample_rate, static_cast<int>(channel_count), 1,
  252. num_stereo_streams, mapping_table.data(), &error)};
  253. if (error != OPUS_OK || decoder == nullptr) {
  254. LOG_ERROR(Audio, "Failed to create Opus decoder (error={}).", error);
  255. IPC::ResponseBuilder rb{ctx, 2};
  256. // TODO(ogniK): Use correct error code
  257. rb.Push(ResultUnknown);
  258. return;
  259. }
  260. IPC::ResponseBuilder rb{ctx, 2, 0, 1};
  261. rb.Push(ResultSuccess);
  262. rb.PushIpcInterface<IHardwareOpusDecoderManager>(
  263. system, OpusDecoderState{std::move(decoder), sample_rate, channel_count});
  264. }
  265. void HwOpus::OpenHardwareOpusDecoderEx(Kernel::HLERequestContext& ctx) {
  266. IPC::RequestParser rp{ctx};
  267. const auto sample_rate = rp.Pop<u32>();
  268. const auto channel_count = rp.Pop<u32>();
  269. LOG_DEBUG(Audio, "called sample_rate={}, channel_count={}", sample_rate, channel_count);
  270. ASSERT_MSG(sample_rate == 48000 || sample_rate == 24000 || sample_rate == 16000 ||
  271. sample_rate == 12000 || sample_rate == 8000,
  272. "Invalid sample rate");
  273. ASSERT_MSG(channel_count == 1 || channel_count == 2, "Invalid channel count");
  274. const int num_stereo_streams = channel_count == 2 ? 1 : 0;
  275. const auto mapping_table = CreateMappingTable(channel_count);
  276. int error = 0;
  277. OpusDecoderPtr decoder{
  278. opus_multistream_decoder_create(sample_rate, static_cast<int>(channel_count), 1,
  279. num_stereo_streams, mapping_table.data(), &error)};
  280. if (error != OPUS_OK || decoder == nullptr) {
  281. LOG_ERROR(Audio, "Failed to create Opus decoder (error={}).", error);
  282. IPC::ResponseBuilder rb{ctx, 2};
  283. // TODO(ogniK): Use correct error code
  284. rb.Push(ResultUnknown);
  285. return;
  286. }
  287. IPC::ResponseBuilder rb{ctx, 2, 0, 1};
  288. rb.Push(ResultSuccess);
  289. rb.PushIpcInterface<IHardwareOpusDecoderManager>(
  290. system, OpusDecoderState{std::move(decoder), sample_rate, channel_count});
  291. }
  292. HwOpus::HwOpus(Core::System& system_) : ServiceFramework{system_, "hwopus"} {
  293. static const FunctionInfo functions[] = {
  294. {0, &HwOpus::OpenHardwareOpusDecoder, "OpenHardwareOpusDecoder"},
  295. {1, &HwOpus::GetWorkBufferSize, "GetWorkBufferSize"},
  296. {2, nullptr, "OpenOpusDecoderForMultiStream"},
  297. {3, nullptr, "GetWorkBufferSizeForMultiStream"},
  298. {4, &HwOpus::OpenHardwareOpusDecoderEx, "OpenHardwareOpusDecoderEx"},
  299. {5, &HwOpus::GetWorkBufferSizeEx, "GetWorkBufferSizeEx"},
  300. {6, nullptr, "OpenHardwareOpusDecoderForMultiStreamEx"},
  301. {7, &HwOpus::GetWorkBufferSizeForMultiStreamEx, "GetWorkBufferSizeForMultiStreamEx"},
  302. };
  303. RegisterHandlers(functions);
  304. }
  305. HwOpus::~HwOpus() = default;
  306. } // namespace Service::Audio