hwopus.cpp 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. // Copyright 2018 yuzu emulator team
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include <chrono>
  5. #include <cstring>
  6. #include <memory>
  7. #include <vector>
  8. #include <opus.h>
  9. #include "common/common_funcs.h"
  10. #include "common/logging/log.h"
  11. #include "core/hle/ipc_helpers.h"
  12. #include "core/hle/kernel/hle_ipc.h"
  13. #include "core/hle/service/audio/hwopus.h"
  14. namespace Service::Audio {
  15. namespace {
  16. struct OpusDeleter {
  17. void operator()(void* ptr) const {
  18. operator delete(ptr);
  19. }
  20. };
  21. class IHardwareOpusDecoderManager final : public ServiceFramework<IHardwareOpusDecoderManager> {
  22. public:
  23. IHardwareOpusDecoderManager(std::unique_ptr<OpusDecoder, OpusDeleter> decoder, u32 sample_rate,
  24. u32 channel_count)
  25. : ServiceFramework("IHardwareOpusDecoderManager"), decoder(std::move(decoder)),
  26. sample_rate(sample_rate), channel_count(channel_count) {
  27. // clang-format off
  28. static const FunctionInfo functions[] = {
  29. {0, &IHardwareOpusDecoderManager::DecodeInterleavedOld, "DecodeInterleavedOld"},
  30. {1, nullptr, "SetContext"},
  31. {2, nullptr, "DecodeInterleavedForMultiStreamOld"},
  32. {3, nullptr, "SetContextForMultiStream"},
  33. {4, &IHardwareOpusDecoderManager::DecodeInterleavedWithPerfOld, "DecodeInterleavedWithPerfOld"},
  34. {5, nullptr, "DecodeInterleavedForMultiStreamWithPerfOld"},
  35. {6, &IHardwareOpusDecoderManager::DecodeInterleaved, "DecodeInterleaved"},
  36. {7, nullptr, "DecodeInterleavedForMultiStream"},
  37. };
  38. // clang-format on
  39. RegisterHandlers(functions);
  40. }
  41. private:
  42. /// Describes extra behavior that may be asked of the decoding context.
  43. enum class ExtraBehavior {
  44. /// No extra behavior.
  45. None,
  46. /// Resets the decoder context back to a freshly initialized state.
  47. ResetContext,
  48. };
  49. void DecodeInterleavedOld(Kernel::HLERequestContext& ctx) {
  50. LOG_DEBUG(Audio, "called");
  51. DecodeInterleavedHelper(ctx, nullptr, ExtraBehavior::None);
  52. }
  53. void DecodeInterleavedWithPerfOld(Kernel::HLERequestContext& ctx) {
  54. LOG_DEBUG(Audio, "called");
  55. u64 performance = 0;
  56. DecodeInterleavedHelper(ctx, &performance, ExtraBehavior::None);
  57. }
  58. void DecodeInterleaved(Kernel::HLERequestContext& ctx) {
  59. LOG_DEBUG(Audio, "called");
  60. IPC::RequestParser rp{ctx};
  61. const auto extra_behavior =
  62. rp.Pop<bool>() ? ExtraBehavior::ResetContext : ExtraBehavior::None;
  63. u64 performance = 0;
  64. DecodeInterleavedHelper(ctx, &performance, extra_behavior);
  65. }
  66. void DecodeInterleavedHelper(Kernel::HLERequestContext& ctx, u64* performance,
  67. ExtraBehavior extra_behavior) {
  68. u32 consumed = 0;
  69. u32 sample_count = 0;
  70. std::vector<opus_int16> samples(ctx.GetWriteBufferSize() / sizeof(opus_int16));
  71. if (extra_behavior == ExtraBehavior::ResetContext) {
  72. ResetDecoderContext();
  73. }
  74. if (!Decoder_DecodeInterleaved(consumed, sample_count, ctx.ReadBuffer(), samples,
  75. performance)) {
  76. LOG_ERROR(Audio, "Failed to decode opus data");
  77. IPC::ResponseBuilder rb{ctx, 2};
  78. // TODO(ogniK): Use correct error code
  79. rb.Push(ResultCode(-1));
  80. return;
  81. }
  82. const u32 param_size = performance != nullptr ? 6 : 4;
  83. IPC::ResponseBuilder rb{ctx, param_size};
  84. rb.Push(RESULT_SUCCESS);
  85. rb.Push<u32>(consumed);
  86. rb.Push<u32>(sample_count);
  87. if (performance) {
  88. rb.Push<u64>(*performance);
  89. }
  90. ctx.WriteBuffer(samples.data(), samples.size() * sizeof(s16));
  91. }
  92. bool Decoder_DecodeInterleaved(u32& consumed, u32& sample_count, const std::vector<u8>& input,
  93. std::vector<opus_int16>& output, u64* out_performance_time) {
  94. const auto start_time = std::chrono::high_resolution_clock::now();
  95. const std::size_t raw_output_sz = output.size() * sizeof(opus_int16);
  96. if (sizeof(OpusHeader) > input.size()) {
  97. LOG_ERROR(Audio, "Input is smaller than the header size, header_sz={}, input_sz={}",
  98. sizeof(OpusHeader), input.size());
  99. return false;
  100. }
  101. OpusHeader hdr{};
  102. std::memcpy(&hdr, input.data(), sizeof(OpusHeader));
  103. if (sizeof(OpusHeader) + static_cast<u32>(hdr.sz) > input.size()) {
  104. LOG_ERROR(Audio, "Input does not fit in the opus header size. data_sz={}, input_sz={}",
  105. sizeof(OpusHeader) + static_cast<u32>(hdr.sz), input.size());
  106. return false;
  107. }
  108. const auto frame = input.data() + sizeof(OpusHeader);
  109. const auto decoded_sample_count = opus_packet_get_nb_samples(
  110. frame, static_cast<opus_int32>(input.size() - sizeof(OpusHeader)),
  111. static_cast<opus_int32>(sample_rate));
  112. if (decoded_sample_count * channel_count * sizeof(u16) > raw_output_sz) {
  113. LOG_ERROR(
  114. Audio,
  115. "Decoded data does not fit into the output data, decoded_sz={}, raw_output_sz={}",
  116. decoded_sample_count * channel_count * sizeof(u16), raw_output_sz);
  117. return false;
  118. }
  119. const int frame_size = (static_cast<int>(raw_output_sz / sizeof(s16) / channel_count));
  120. const auto out_sample_count =
  121. opus_decode(decoder.get(), frame, hdr.sz, output.data(), frame_size, 0);
  122. if (out_sample_count < 0) {
  123. LOG_ERROR(Audio,
  124. "Incorrect sample count received from opus_decode, "
  125. "output_sample_count={}, frame_size={}, data_sz_from_hdr={}",
  126. out_sample_count, frame_size, static_cast<u32>(hdr.sz));
  127. return false;
  128. }
  129. const auto end_time = std::chrono::high_resolution_clock::now() - start_time;
  130. sample_count = out_sample_count;
  131. consumed = static_cast<u32>(sizeof(OpusHeader) + hdr.sz);
  132. if (out_performance_time != nullptr) {
  133. *out_performance_time =
  134. std::chrono::duration_cast<std::chrono::milliseconds>(end_time).count();
  135. }
  136. return true;
  137. }
  138. void ResetDecoderContext() {
  139. ASSERT(decoder != nullptr);
  140. opus_decoder_ctl(decoder.get(), OPUS_RESET_STATE);
  141. }
  142. struct OpusHeader {
  143. u32_be sz; // Needs to be BE for some odd reason
  144. INSERT_PADDING_WORDS(1);
  145. };
  146. static_assert(sizeof(OpusHeader) == 0x8, "OpusHeader is an invalid size");
  147. std::unique_ptr<OpusDecoder, OpusDeleter> decoder;
  148. u32 sample_rate;
  149. u32 channel_count;
  150. };
  151. std::size_t WorkerBufferSize(u32 channel_count) {
  152. ASSERT_MSG(channel_count == 1 || channel_count == 2, "Invalid channel count");
  153. return opus_decoder_get_size(static_cast<int>(channel_count));
  154. }
  155. } // Anonymous namespace
  156. void HwOpus::GetWorkBufferSize(Kernel::HLERequestContext& ctx) {
  157. IPC::RequestParser rp{ctx};
  158. const auto sample_rate = rp.Pop<u32>();
  159. const auto channel_count = rp.Pop<u32>();
  160. LOG_DEBUG(Audio, "called with sample_rate={}, channel_count={}", sample_rate, channel_count);
  161. ASSERT_MSG(sample_rate == 48000 || sample_rate == 24000 || sample_rate == 16000 ||
  162. sample_rate == 12000 || sample_rate == 8000,
  163. "Invalid sample rate");
  164. ASSERT_MSG(channel_count == 1 || channel_count == 2, "Invalid channel count");
  165. const u32 worker_buffer_sz = static_cast<u32>(WorkerBufferSize(channel_count));
  166. LOG_DEBUG(Audio, "worker_buffer_sz={}", worker_buffer_sz);
  167. IPC::ResponseBuilder rb{ctx, 3};
  168. rb.Push(RESULT_SUCCESS);
  169. rb.Push<u32>(worker_buffer_sz);
  170. }
  171. void HwOpus::OpenOpusDecoder(Kernel::HLERequestContext& ctx) {
  172. IPC::RequestParser rp{ctx};
  173. const auto sample_rate = rp.Pop<u32>();
  174. const auto channel_count = rp.Pop<u32>();
  175. const auto buffer_sz = rp.Pop<u32>();
  176. LOG_DEBUG(Audio, "called sample_rate={}, channel_count={}, buffer_size={}", sample_rate,
  177. channel_count, buffer_sz);
  178. ASSERT_MSG(sample_rate == 48000 || sample_rate == 24000 || sample_rate == 16000 ||
  179. sample_rate == 12000 || sample_rate == 8000,
  180. "Invalid sample rate");
  181. ASSERT_MSG(channel_count == 1 || channel_count == 2, "Invalid channel count");
  182. const std::size_t worker_sz = WorkerBufferSize(channel_count);
  183. ASSERT_MSG(buffer_sz >= worker_sz, "Worker buffer too large");
  184. std::unique_ptr<OpusDecoder, OpusDeleter> decoder{
  185. static_cast<OpusDecoder*>(operator new(worker_sz))};
  186. if (const int err = opus_decoder_init(decoder.get(), sample_rate, channel_count)) {
  187. LOG_ERROR(Audio, "Failed to init opus decoder with error={}", err);
  188. IPC::ResponseBuilder rb{ctx, 2};
  189. // TODO(ogniK): Use correct error code
  190. rb.Push(ResultCode(-1));
  191. return;
  192. }
  193. IPC::ResponseBuilder rb{ctx, 2, 0, 1};
  194. rb.Push(RESULT_SUCCESS);
  195. rb.PushIpcInterface<IHardwareOpusDecoderManager>(std::move(decoder), sample_rate,
  196. channel_count);
  197. }
  198. HwOpus::HwOpus() : ServiceFramework("hwopus") {
  199. static const FunctionInfo functions[] = {
  200. {0, &HwOpus::OpenOpusDecoder, "OpenOpusDecoder"},
  201. {1, &HwOpus::GetWorkBufferSize, "GetWorkBufferSize"},
  202. {2, nullptr, "OpenOpusDecoderForMultiStream"},
  203. {3, nullptr, "GetWorkBufferSizeForMultiStream"},
  204. };
  205. RegisterHandlers(functions);
  206. }
  207. HwOpus::~HwOpus() = default;
  208. } // namespace Service::Audio