| 6 |
| 7 | #include "OpusDecoder.h" |
| 8 | #include "audio/Resampler.h" |
| 9 | #include "logging.h" |
| 10 | #include <assert.h> |
| 11 | #include <math.h> |
| 12 | #include <algorithm> |
| 13 | #if defined HAVE_CONFIG_H || defined TGVOIP_USE_INSTALLED_OPUS |
| 14 | #include <opus/opus.h> |
| 15 | #else |
| 16 | #include "opus.h" |
| 17 | #endif |
| 18 |
| 19 | #include "VoIPController.h" |
| 20 |
| 21 | #define PACKET_SIZE (960 * 2) |
| 22 |
| 23 | using namespace tgvoip; |
| 24 |
| 25 | tgvoip::OpusDecoder::OpusDecoder(const std::shared_ptr<MediaStreamItf>& dst, bool isAsync, bool needEC) { |
| 26 | dst->SetCallback(OpusDecoder::Callback, this); |
| 27 | Initialize(isAsync, needEC); |
| 28 | } |
| 29 |
| 30 | tgvoip::OpusDecoder::OpusDecoder(const std::unique_ptr<MediaStreamItf>& dst, bool isAsync, bool needEC) { |
| 31 | dst->SetCallback(OpusDecoder::Callback, this); |
| 32 | Initialize(isAsync, needEC); |
| 33 | } |
| 34 |
| 35 | tgvoip::OpusDecoder::OpusDecoder(MediaStreamItf* dst, bool isAsync, bool needEC) { |
| 36 | dst->SetCallback(OpusDecoder::Callback, this); |
| 37 | Initialize(isAsync, needEC); |
| 38 | } |
| 39 |
| 40 | void tgvoip::OpusDecoder::Initialize(bool isAsync, bool needEC) { |
| 41 | async = isAsync; |
| 42 | if (async) { |
| 43 | decodedQueue = new BlockingQueue<Buffer>(33); |
| 44 | semaphore = new Semaphore(32, 0); |
| 45 | } else { |
| 46 | decodedQueue = NULL; |
| 47 | semaphore = NULL; |
| 48 | } |
| 49 | dec=opus_decoder_create(48000, 1, NULL); |
| 50 | if (needEC) |
| 51 | ecDec = opus_decoder_create(48000, 1, NULL); |
| 52 | else |
| 53 | ecDec = NULL; |
| 54 | // todo buffer = reinterpret_cast<unsigned char*>(aligned_alloc(2, 8192)); |
| 55 | buffer=(unsigned char *) malloc(8192); |
| 56 | lastDecoded = NULL; |
| 57 | outputBufferSize = 0; |
| 58 | echoCanceller = NULL; |
| 59 | frameDuration = 20; |
| 60 | consecutiveLostPackets = 0; |
| 61 | enableDTX = false; |
| 62 | silentPacketCount = 0; |
| 63 | levelMeter = NULL; |
| 64 | nextLen = 0; |
| 65 | running = false; |
| 66 | remainingDataLen = 0; |
| 67 | processedBuffer = NULL; |
| 68 | prevWasEC = false; |
| 69 | prevLastSample = 0; |
| 70 | } |
| 71 |
| 72 | tgvoip::OpusDecoder::~OpusDecoder() { |
| 73 | opus_decoder_destroy(dec); |
| 74 | if (ecDec) |
| 75 | opus_decoder_destroy(ecDec); |
| 76 | free(buffer); |
| 77 | if (decodedQueue) |
| 78 | delete decodedQueue; |
| 79 | if (semaphore) |
| 80 | delete semaphore; |
| 81 | } |
| 82 |
| 83 |
| 84 | void tgvoip::OpusDecoder::SetEchoCanceller(EchoCanceller* canceller) { |
| 85 | echoCanceller = canceller; |
| 86 | } |
| 87 |
| 88 | size_t tgvoip::OpusDecoder::Callback(unsigned char* data, size_t len, void* param) { |
| 89 | return (reinterpret_cast<OpusDecoder*>(param)->HandleCallback(data, len)); |
| 90 | } |
| 91 |
| 92 | size_t tgvoip::OpusDecoder::HandleCallback(unsigned char* data, size_t len) { |
| 93 | if (async) { |
| 94 | if (!running) { |
| 95 | memset(data, 0, len); |
| 96 | return 0; |
| 97 | } |
| 98 | if (outputBufferSize == 0) { |
| 99 | outputBufferSize = len; |
| 100 | int packetsNeeded; |
| 101 | if (len > PACKET_SIZE) |
| 102 | packetsNeeded = len / PACKET_SIZE; |
| 103 | else |
| 104 | packetsNeeded = 1; |
| 105 | packetsNeeded *= 2; |
| 106 | semaphore->Release(packetsNeeded); |
| 107 | } |
| 108 | assert(outputBufferSize == len && "output buffer size is supposed to be the same throughout callbacks"); |
| 109 | if (len == PACKET_SIZE) { |
| 110 | Buffer lastDecoded=decodedQueue->GetBlocking(); |
| 111 | if (lastDecoded.IsEmpty()) |
| 112 | return 0; |
| 113 | memcpy(data, *lastDecoded, PACKET_SIZE); |
| 114 | semaphore->Release(); |
| 115 | if (silentPacketCount > 0) { |
| 116 | silentPacketCount--; |
| 117 | if (levelMeter) |
| 118 | levelMeter->Update(reinterpret_cast<int16_t*>(data), 0); |
| 119 | return 0; |
| 120 | } |
| 121 | if (echoCanceller) { |
| 122 | echoCanceller->SpeakerOutCallback(data, PACKET_SIZE); |
| 123 | } |
| 124 | } else { |
| 125 | LOGE("Opus decoder buffer length != 960 samples"); |
| 126 | abort(); |
| 127 | } |
| 128 | } else { |
| 129 | if (remainingDataLen == 0 && silentPacketCount == 0) { |
| 130 | int duration = DecodeNextFrame(); |
| 131 | remainingDataLen = static_cast<size_t>(duration) / 20 * 960 * 2; |
| 132 | } |
| 133 | if (silentPacketCount > 0 || remainingDataLen == 0 || !processedBuffer){ |
| 134 | if (silentPacketCount > 0) |
| 135 | silentPacketCount--; |
| 136 | memset(data, 0, 960 * 2); |
| 137 | if (levelMeter) |
| 138 | levelMeter->Update(reinterpret_cast<int16_t*>(data), 0); |
| 139 | return 0; |
| 140 | } |
| 141 | memcpy(data, processedBuffer, 960 * 2); |
| 142 | remainingDataLen -= 960 * 2; |
| 143 | if (remainingDataLen > 0) { |
| 144 | memmove(processedBuffer, processedBuffer + 960 * 2, remainingDataLen); |
| 145 | } |
| 146 | } |
| 147 | if (levelMeter) |
| 148 | levelMeter->Update(reinterpret_cast<int16_t*>(data), len / 2); |
| 149 | return len; |
| 150 | } |
| 151 |
| 152 |
| 153 | void tgvoip::OpusDecoder::Start() { |
| 154 | if (!async) |
| 155 | return; |
| 156 | running = true; |
| 157 | thread = new Thread(std::bind(&tgvoip::OpusDecoder::RunThread, this)); |
| 158 | thread->SetName("opus_decoder"); |
| 159 | thread->SetMaxPriority(); |
| 160 | thread->Start(); |
| 161 | } |
| 162 |
| 163 | void tgvoip::OpusDecoder::Stop() { |
| 164 | if (!running || !async) |
| 165 | return; |
| 166 | running = false; |
| 167 | semaphore->Release(); |
| 168 | thread->Join(); |
| 169 | delete thread; |
| 170 | } |
| 171 |
| 172 | void tgvoip::OpusDecoder::RunThread() { |
| 173 | LOGI("decoder: packets per frame %d", packetsPerFrame); |
| 174 | while(running) { |
| 175 | int playbackDuration = DecodeNextFrame(); |
| 176 | for (int i = 0; i < playbackDuration / 20; i++) { |
| 177 | semaphore->Acquire(); |
| 178 | if (!running) { |
| 179 | LOGI("==== decoder exiting ===="); |
| 180 | return; |
| 181 | } |
| 182 | try { |
| 183 | Buffer buf=bufferPool.Get(); |
| 184 | if (remainingDataLen > 0) { |
| 185 | for (effects::AudioEffect*& effect:postProcEffects) { |
| 186 | effect->Process(reinterpret_cast<int16_t*>(processedBuffer+(PACKET_SIZE * i)), 960); |
| 187 | } |
| 188 | buf.CopyFrom(processedBuffer + (PACKET_SIZE * i), 0, PACKET_SIZE); |
| 189 | } else { |
| 190 | //LOGE("Error decoding, result=%d", size); |
| 191 | memset(*buf, 0, PACKET_SIZE); |
| 192 | } |
| 193 | decodedQueue->Put(std::move(buf)); |
| 194 | } catch (const std::bad_alloc&) { |
| 195 | LOGW("decoder: no buffers left!"); |
| 196 | } |
| 197 | } |
| 198 | } |
| 199 | } |
| 200 |
| 201 | int tgvoip::OpusDecoder::DecodeNextFrame() { |
| 202 | int playbackDuration = 0; |
| 203 | bool isEC = false; |
| 204 | size_t len = jitterBuffer->HandleOutput(buffer, 8192, 0, true, playbackDuration, isEC); |
| 205 | bool fec = false; |
| 206 | if (!len) { |
| 207 | fec = true; |
| 208 | len = jitterBuffer->HandleOutput(buffer, 8192, 0, false, playbackDuration, isEC); |
| 209 | //if(len) |
| 210 | // LOGV("Trying FEC..."); |
| 211 | } |
| 212 | int size; |
| 213 | if (len) { |
| 214 | size = opus_decode(isEC ? ecDec : dec, buffer, len, reinterpret_cast<opus_int16*>(decodeBuffer), packetsPerFrame * 960, fec ? 1 : 0); |
| 215 | consecutiveLostPackets = 0; |
| 216 | if (prevWasEC != isEC && size) { |
| 217 | // It turns out the waveforms generated by the PLC feature are also great to help smooth out the |
| 218 | // otherwise audible transition between the frames from different decoders. Those are basically an extrapolation |
| 219 | // of the previous successfully decoded data -- which is exactly what we need here. |
| 220 | size = opus_decode(prevWasEC ? ecDec : dec, NULL, 0, reinterpret_cast<opus_int16*>(nextBuffer), packetsPerFrame * 960, 0); |
| 221 | if (size) { |
| 222 | int16_t* plcSamples = reinterpret_cast<int16_t*>(nextBuffer); |
| 223 | int16_t* samples = reinterpret_cast<int16_t*>(decodeBuffer); |
| 224 | constexpr float coeffs[] = {0.999802f, 0.995062f, 0.984031f, 0.966778f, 0.943413f, 0.914084f, 0.878975f, 0.838309f, 0.792344f, 0.741368f, |
| 225 | 0.685706f, 0.625708f, 0.561754f, 0.494249f, 0.423619f, 0.350311f, 0.274788f, 0.197527f, 0.119018f, 0.039757f}; |
| 226 | for (int i = 0; i < 20; i++) { |
| 227 | samples[i] = static_cast<int16_t>(round(plcSamples[i] * coeffs[i] + samples[i] * (1.f - coeffs[i]))); |
| 228 | } |
| 229 | } |
| 230 | } |
| 231 | prevWasEC = isEC; |
| 232 | prevLastSample = decodeBuffer[size - 1]; |
| 233 | } else { // do packet loss concealment |
| 234 | consecutiveLostPackets++; |
| 235 | if (consecutiveLostPackets > 2 && enableDTX) { |
| 236 | silentPacketCount += packetsPerFrame; |
| 237 | size = packetsPerFrame * 960; |
| 238 | } else { |
| 239 | size = opus_decode(prevWasEC ? ecDec : dec, NULL, 0, reinterpret_cast<opus_int16*>(decodeBuffer), packetsPerFrame * 960, 0); |
| 240 | //LOGV("PLC"); |
| 241 | } |
| 242 | } |
| 243 | if (size < 0) |
| 244 | LOGW("decoder: opus_decode error %d", size); |
| 245 | remainingDataLen = size; |
| 246 | if (playbackDuration == 80) { |
| 247 | processedBuffer = buffer; |
| 248 | audio::Resampler::Rescale60To80(reinterpret_cast<int16_t*>(decodeBuffer), |
| 249 | reinterpret_cast<int16_t*>(processedBuffer)); |
| 250 | } else if (playbackDuration == 40) { |
| 251 | processedBuffer = buffer; |
| 252 | audio::Resampler::Rescale60To40(reinterpret_cast<int16_t*>(decodeBuffer), |
| 253 | reinterpret_cast<int16_t*>(processedBuffer)); |
| 254 | } else { |
| 255 | processedBuffer = decodeBuffer; |
| 256 | } |
| 257 | return playbackDuration; |
| 258 | } |
| 259 |
| 260 |
| 261 | void tgvoip::OpusDecoder::SetFrameDuration(uint32_t duration) { |
| 262 | frameDuration = duration; |
| 263 | packetsPerFrame = frameDuration / 20; |
| 264 | } |
| 265 |
| 266 |
| 267 | void tgvoip::OpusDecoder::SetJitterBuffer(std::shared_ptr<JitterBuffer> jitterBuffer) { |
| 268 | this->jitterBuffer = jitterBuffer; |
| 269 | } |
| 270 |
| 271 | void tgvoip::OpusDecoder::SetDTX(bool enable) { |
| 272 | enableDTX = enable; |
| 273 | } |
| 274 |
| 275 | void tgvoip::OpusDecoder::SetLevelMeter(AudioLevelMeter* levelMeter) { |
| 276 | this->levelMeter = levelMeter; |
| 277 | } |
| 278 |
| 279 | void tgvoip::OpusDecoder::AddAudioEffect(effects::AudioEffect* effect) { |
| 280 | postProcEffects.push_back(effect); |
| 281 | } |
| 282 |
| 283 | void tgvoip::OpusDecoder::RemoveAudioEffect(effects::AudioEffect *effect) { |
| 284 | std::vector<effects::AudioEffect*>::iterator it = std::find(postProcEffects.begin(), postProcEffects.end(), effect); |
| 285 | if (it != postProcEffects.end()) |
| 286 | postProcEffects.erase(it); |
| 287 | } |
| 288 |