hwopus.cpp 13 KB

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