DiscordCoreAPI
A Discord bot library written in C++, with custom asynchronous coroutines.
Loading...
Searching...
No Matches
AudioEncoder.cpp
Go to the documentation of this file.
1/*
2 DiscordCoreAPI, A bot library for Discord, written in C++, and featuring explicit multithreading through the usage of custom, asynchronous C++ CoRoutines.
3
4 Copyright 2021, 2022 Chris M. (RealTimeChris)
5
6 This library is free software; you can redistribute it and/or
7 modify it under the terms of the GNU Lesser General Public
8 License as published by the Free Software Foundation; either
9 version 2.1 of the License, or (at your option) any later version.
10
11 This library is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
15
16 You should have received a copy of the GNU Lesser General Public
17 License along with this library; if not, write to the Free Software
18 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
19 USA
20*/
21/// AudioEncoder.cpp - Source file for the audio encoder class.
22/// Aug 22, 2021
23/// https://discordcoreapi.com
24/// \file AudioEncoder.cpp
25
27#include <opus/opus.h>
28
29namespace DiscordCoreInternal {
30
31 void OpusEncoderWrapper::OpusEncoderDeleter::operator()(OpusEncoder* other) noexcept {
32 if (other) {
33 opus_encoder_destroy(other);
34 other = nullptr;
35 }
36 }
37
38 OpusEncoderWrapper::OpusEncoderWrapper() {
39 int32_t error{};
40 this->ptr.reset(opus_encoder_create(this->sampleRate, this->nChannels, OPUS_APPLICATION_AUDIO, &error));
41 auto result = opus_encoder_ctl(this->ptr.get(), OPUS_SET_SIGNAL(OPUS_SIGNAL_MUSIC));
42 if (result != OPUS_OK) {
43 throw DiscordCoreAPI::DCAException{ "Failed to set the Opus signal type, Reason: " + std::string{ opus_strerror(result) } };
44 }
45 result = opus_encoder_ctl(this->ptr.get(), OPUS_SET_BITRATE(OPUS_BITRATE_MAX));
46 if (result != OPUS_OK) {
47 throw DiscordCoreAPI::DCAException{ "Failed to set the Opus bitrate, Reason: " + std::string{ opus_strerror(result) } };
48 }
49 }
50
51 EncoderReturnData OpusEncoderWrapper::encodeData(std::basic_string_view<std::byte> inputFrame) {
52 if (inputFrame.size() == 0) {
53 return {};
54 }
55 if (this->encodedData.size() == 0) {
56 this->encodedData.resize(this->maxBufferSize);
57 }
58 size_t sampleCount = inputFrame.size() / 2 / 2;
59 int32_t count = opus_encode(this->ptr.get(), reinterpret_cast<const opus_int16*>(inputFrame.data()),
60 static_cast<int32_t>(inputFrame.size() / 2 / 2), reinterpret_cast<uint8_t*>(this->encodedData.data()), this->maxBufferSize);
61 if (count <= 0) {
62 return {};
63 }
64 EncoderReturnData returnData{};
65 returnData.sampleCount = sampleCount;
66 returnData.data = std::basic_string_view<std::byte>{ this->encodedData.data(), this->encodedData.size() };
67 return returnData;
68 }
69}