| 7 | #include "json11.hpp" |
| 8 | #include "logging.h" |
| 9 | #include "threading.h" |
| 10 | #include "Buffers.h" |
| 11 | #include "OpusDecoder.h" |
| 12 | #include "OpusEncoder.h" |
| 13 | #include "PacketSender.h" |
| 14 | #include "PrivateDefines.h" |
| 15 | #include "VoIPController.h" |
| 16 | #include "VoIPServerConfig.h" |
| 17 | #include "video/VideoPacketSender.h" |
| 18 |
| 19 | #ifndef _WIN32 |
| 20 | #include <sys/time.h> |
| 21 | #include <unistd.h> |
| 22 | #endif |
| 23 |
| 24 | #if defined HAVE_CONFIG_H || defined TGVOIP_USE_INSTALLED_OPUS |
| 25 | #include <opus/opus.h> |
| 26 | #else |
| 27 | #include "opus.h" |
| 28 | #endif |
| 29 |
| 30 | #include <algorithm> |
| 31 | #include <cassert> |
| 32 | #include <cerrno> |
| 33 | #include <cinttypes> |
| 34 | #include <cmath> |
| 35 | #include <cstring> |
| 36 | #include <ctime> |
| 37 | #include <cwchar> |
| 38 | #include <limits> |
| 39 | #include <sstream> |
| 40 | #include <stdexcept> |
| 41 |
| 42 | inline int pad4(int x) |
| 43 | { |
| 44 | int r = PAD4(x); |
| 45 | if (r == 4) |
| 46 | return 0; |
| 47 | return r; |
| 48 | } |
| 49 |
| 50 | using namespace tgvoip; |
| 51 |
| 52 | #ifdef __APPLE__ |
| 53 | #include "os/darwin/AudioUnitIO.h" |
| 54 | #include <mach/mach_time.h> |
| 55 | double VoIPController::machTimebase = 0; |
| 56 | std::uint64_t VoIPController::machTimestart = 0; |
| 57 | #endif |
| 58 |
| 59 | #ifdef _WIN32 |
| 60 | std::int64_t VoIPController::win32TimeScale = 0; |
| 61 | bool VoIPController::didInitWin32TimeScale = false; |
| 62 | #endif |
| 63 |
| 64 | #ifdef __ANDROID__ |
| 65 | #include "NetworkSocket.h" |
| 66 | #include "os/android/AudioInputAndroid.h" |
| 67 | #include "os/android/JNIUtilities.h" |
| 68 |
| 69 | extern jclass jniUtilitiesClass; |
| 70 | #endif |
| 71 |
| 72 | #if defined(TGVOIP_USE_CALLBACK_AUDIO_IO) |
| 73 | #include "audio/AudioIOCallback.h" |
| 74 | #endif |
| 75 |
| 76 | #define ENFORCE_MSG_THREAD assert(m_messageThread.IsCurrent()) |
| 77 |
| 78 | extern FILE* tgvoipLogFile; |
| 79 |
| 80 | #pragma mark - Public API |
| 81 |
| 82 | VoIPController::VoIPController() |
| 83 | : m_congestionControl(new CongestionControl()) |
| 84 | , m_udpSocket(NetworkSocket::Create(NetworkProtocol::UDP)) |
| 85 | , m_realUdpSocket(m_udpSocket) |
| 86 | , m_selectCanceller(SocketSelectCanceller::Create()) |
| 87 | , m_rawSendQueue(64) |
| 88 | { |
| 89 | m_unsentStreamPackets.store(0); |
| 90 |
| 91 | ServerConfig* serverConfigInstance = ServerConfig::GetSharedInstance(); |
| 92 | m_maxAudioBitrate = static_cast<std::uint32_t>(serverConfigInstance->GetInt("audio_max_bitrate", 20000)); |
| 93 | m_maxAudioBitrateGPRS = static_cast<std::uint32_t>(serverConfigInstance->GetInt("audio_max_bitrate_gprs", 8000)); |
| 94 | m_maxAudioBitrateEDGE = static_cast<std::uint32_t>(serverConfigInstance->GetInt("audio_max_bitrate_edge", 16000)); |
| 95 | m_maxAudioBitrateSaving = static_cast<std::uint32_t>(serverConfigInstance->GetInt("audio_max_bitrate_saving", 8000)); |
| 96 | m_initAudioBitrate = static_cast<std::uint32_t>(serverConfigInstance->GetInt("audio_init_bitrate", 16000)); |
| 97 | m_initAudioBitrateGPRS = static_cast<std::uint32_t>(serverConfigInstance->GetInt("audio_init_bitrate_gprs", 8000)); |
| 98 | m_initAudioBitrateEDGE = static_cast<std::uint32_t>(serverConfigInstance->GetInt("audio_init_bitrate_edge", 8000)); |
| 99 | m_initAudioBitrateSaving = static_cast<std::uint32_t>(serverConfigInstance->GetInt("audio_init_bitrate_saving", 8000)); |
| 100 | m_audioBitrateStepIncr = static_cast<std::uint32_t>(serverConfigInstance->GetInt("audio_bitrate_step_incr", 1000)); |
| 101 | m_audioBitrateStepDecr = static_cast<std::uint32_t>(serverConfigInstance->GetInt("audio_bitrate_step_decr", 1000)); |
| 102 | m_minAudioBitrate = static_cast<std::uint32_t>(serverConfigInstance->GetInt("audio_min_bitrate", 8000)); |
| 103 | m_needRateFlags = static_cast<std::uint32_t>(serverConfigInstance->GetInt("rate_flags", std::int32_t{~0})); |
| 104 | m_maxUnsentStreamPackets = static_cast<std::uint32_t>(serverConfigInstance->GetInt("max_unsent_stream_packets", 2)); |
| 105 | m_unackNopThreshold = static_cast<std::uint32_t>(serverConfigInstance->GetInt("unack_nop_threshold", 10)); |
| 106 | m_relaySwitchThreshold = serverConfigInstance->GetDouble("relay_switch_threshold", 0.8); |
| 107 | m_p2pToRelaySwitchThreshold = serverConfigInstance->GetDouble("p2p_to_relay_switch_threshold", 0.6); |
| 108 | m_relayToP2pSwitchThreshold = serverConfigInstance->GetDouble("relay_to_p2p_switch_threshold", 0.8); |
| 109 | m_reconnectingTimeout = serverConfigInstance->GetDouble("reconnecting_state_timeout", 2.0); |
| 110 | m_rateMaxAcceptableRTT = serverConfigInstance->GetDouble("rate_min_rtt", 0.6); |
| 111 | m_rateMaxAcceptableSendLoss = serverConfigInstance->GetDouble("rate_min_send_loss", 0.2); |
| 112 | m_packetLossToEnableExtraEC = serverConfigInstance->GetDouble("packet_loss_for_extra_ec", 0.02); |
| 113 |
| 114 |
| 115 | #ifdef __APPLE__ |
| 116 | machTimestart = 0; |
| 117 | #endif |
| 118 |
| 119 | std::shared_ptr<Stream> stream = std::make_shared<Stream>(); |
| 120 | stream->id = 1; |
| 121 | stream->type = StreamType::AUDIO; |
| 122 | stream->codec = CODEC_OPUS; |
| 123 | stream->enabled = true; |
| 124 | stream->frameDuration = 60; |
| 125 | m_outgoingStreams.emplace_back(std::move(stream)); |
| 126 | } |
| 127 |
| 128 | VoIPController::~VoIPController() |
| 129 | { |
| 130 | LOGD("Entered VoIPController::~VoIPController"); |
| 131 | if (!m_stopping) |
| 132 | { |
| 133 | LOGE("!!!!!!!!!!!!!!!!!!!! CALL controller->Stop() BEFORE DELETING THE CONTROLLER OBJECT !!!!!!!!!!!!!!!!!!!!!!!1"); |
| 134 | std::abort(); |
| 135 | } |
| 136 | LOGD("before close socket"); |
| 137 | delete m_udpSocket; |
| 138 | if (m_realUdpSocket != m_udpSocket) |
| 139 | delete m_realUdpSocket; |
| 140 | LOGD("before delete audioIO"); |
| 141 | delete m_audioIO; |
| 142 | m_audioInput = nullptr; |
| 143 | m_audioOutput = nullptr; |
| 144 | for (std::shared_ptr<Stream>& stream : m_incomingStreams) |
| 145 | { |
| 146 | LOGD("before stop decoder"); |
| 147 | if (stream->decoder != nullptr) |
| 148 | stream->decoder->Stop(); |
| 149 | } |
| 150 | LOGD("before delete encoder"); |
| 151 | if (m_encoder != nullptr) |
| 152 | { |
| 153 | m_encoder->Stop(); |
| 154 | delete m_encoder; |
| 155 | } |
| 156 | LOGD("before delete echo canceller"); |
| 157 | if (m_echoCanceller != nullptr) |
| 158 | { |
| 159 | m_echoCanceller->Stop(); |
| 160 | delete m_echoCanceller; |
| 161 | } |
| 162 | delete m_congestionControl; |
| 163 | if (m_statsDump != nullptr) |
| 164 | fclose(m_statsDump); |
| 165 | delete m_selectCanceller; |
| 166 | LOGD("Left VoIPController::~VoIPController"); |
| 167 | if (tgvoipLogFile != nullptr) |
| 168 | { |
| 169 | FILE* log = tgvoipLogFile; |
| 170 | tgvoipLogFile = nullptr; |
| 171 | fclose(log); |
| 172 | } |
| 173 | #if defined(TGVOIP_USE_CALLBACK_AUDIO_IO) |
| 174 | if (m_preprocDecoder) |
| 175 | { |
| 176 | opus_decoder_destroy(m_preprocDecoder); |
| 177 | m_preprocDecoder = nullptr; |
| 178 | } |
| 179 | #endif |
| 180 | } |
| 181 |
| 182 | VoIPController::Config::Config(double initTimeout, double recvTimeout, DataSaving dataSaving, |
| 183 | bool enableAEC, bool enableNS, bool enableAGC, bool enableCallUpgrade) |
| 184 | : initTimeout(initTimeout) |
| 185 | , recvTimeout(recvTimeout) |
| 186 | , dataSaving(dataSaving) |
| 187 | , enableAEC(enableAEC) |
| 188 | , enableNS(enableNS) |
| 189 | , enableAGC(enableAGC) |
| 190 | , enableCallUpgrade(enableCallUpgrade) |
| 191 | { |
| 192 | } |
| 193 |
| 194 | VoIPController::PendingOutgoingPacket::PendingOutgoingPacket(std::uint32_t seq, PktType type, std::size_t len, Buffer&& data, std::int64_t endpoint) |
| 195 | : seq(seq) |
| 196 | , type(type) |
| 197 | , len(len) |
| 198 | , data(std::move(data)) |
| 199 | , endpoint(endpoint) |
| 200 | { |
| 201 | } |
| 202 |
| 203 | VoIPController::PendingOutgoingPacket::PendingOutgoingPacket(PendingOutgoingPacket&& other) noexcept |
| 204 | : seq(other.seq) |
| 205 | , type(other.type) |
| 206 | , len(other.len) |
| 207 | , data(std::move(other.data)) |
| 208 | , endpoint(other.endpoint) |
| 209 | { |
| 210 | } |
| 211 |
| 212 | VoIPController::PendingOutgoingPacket& VoIPController::PendingOutgoingPacket::operator=(PendingOutgoingPacket&& other) noexcept |
| 213 | { |
| 214 | if (this != &other) |
| 215 | { |
| 216 | seq = other.seq; |
| 217 | type = other.type; |
| 218 | len = other.len; |
| 219 | data = std::move(other.data); |
| 220 | endpoint = other.endpoint; |
| 221 | } |
| 222 | return *this; |
| 223 | } |
| 224 |
| 225 | void VoIPController::Stop() |
| 226 | { |
| 227 | LOGD("Entered VoIPController::Stop"); |
| 228 | m_stopping = true; |
| 229 | m_runReceiver = false; |
| 230 | LOGD("before shutdown socket"); |
| 231 | if (m_udpSocket) |
| 232 | m_udpSocket->Close(); |
| 233 | if (m_realUdpSocket != m_udpSocket) |
| 234 | m_realUdpSocket->Close(); |
| 235 | m_selectCanceller->CancelSelect(); |
| 236 | m_rawSendQueue.Put(RawPendingOutgoingPacket{ .packet = NetworkPacket::Empty(), .socket = nullptr }); |
| 237 | LOGD("before join sendThread"); |
| 238 | if (m_sendThread) |
| 239 | { |
| 240 | m_sendThread->Join(); |
| 241 | delete m_sendThread; |
| 242 | } |
| 243 | LOGD("before join recvThread"); |
| 244 | if (m_recvThread) |
| 245 | { |
| 246 | m_recvThread->Join(); |
| 247 | delete m_recvThread; |
| 248 | } |
| 249 | LOGD("before stop messageThread"); |
| 250 | m_messageThread.Stop(); |
| 251 | { |
| 252 | LOGD("Before stop audio I/O"); |
| 253 | MutexGuard m(m_audioIOMutex); |
| 254 | if (m_audioInput) |
| 255 | { |
| 256 | m_audioInput->Stop(); |
| 257 | m_audioInput->SetCallback(nullptr, nullptr); |
| 258 | } |
| 259 | if (m_audioOutput) |
| 260 | { |
| 261 | m_audioOutput->Stop(); |
| 262 | m_audioOutput->SetCallback(nullptr, nullptr); |
| 263 | } |
| 264 | } |
| 265 | if (m_videoPacketSender) |
| 266 | { |
| 267 | LOGD("before delete video packet sender"); |
| 268 | delete m_videoPacketSender; |
| 269 | m_videoPacketSender = nullptr; |
| 270 | } |
| 271 | LOGD("Left VoIPController::Stop [need rate = %d]", m_needRate); |
| 272 | } |
| 273 |
| 274 | bool VoIPController::NeedRate() |
| 275 | { |
| 276 | return m_needRate && ServerConfig::GetSharedInstance()->GetBoolean("bad_call_rating", false); |
| 277 | } |
| 278 |
| 279 | std::int32_t VoIPController::GetConnectionMaxLayer() |
| 280 | { |
| 281 | return 92; |
| 282 | } |
| 283 |
| 284 | void VoIPController::SetRemoteEndpoints(const std::vector<Endpoint>& endpoints, bool allowP2p, std::int32_t connectionMaxLayer) |
| 285 | { |
| 286 | LOGW("Set remote endpoints, allowP2P=%d, connectionMaxLayer=%u", allowP2p ? 1 : 0, connectionMaxLayer); |
| 287 | assert(!m_runReceiver); |
| 288 | m_preferredRelay = 0; |
| 289 |
| 290 | m_endpoints.clear(); |
| 291 | m_didAddTcpRelays = false; |
| 292 | m_useTCP = true; |
| 293 | for (const Endpoint& endpoint : endpoints) |
| 294 | { |
| 295 | if (m_endpoints.find(endpoint.id) != m_endpoints.end()) |
| 296 | LOGE("Endpoint IDs are not unique!"); |
| 297 | m_endpoints[endpoint.id] = endpoint; |
| 298 | if (m_currentEndpoint == 0) |
| 299 | m_currentEndpoint = endpoint.id; |
| 300 | if (endpoint.type == Endpoint::Type::TCP_RELAY) |
| 301 | m_didAddTcpRelays = true; |
| 302 | if (endpoint.type == Endpoint::Type::UDP_RELAY) |
| 303 | m_useTCP = false; |
| 304 | LOGV("Adding endpoint: %s:%d, %s", endpoint.address.ToString().c_str(), endpoint.port, endpoint.type == Endpoint::Type::UDP_RELAY ? "UDP" : "TCP"); |
| 305 | } |
| 306 | m_preferredRelay = m_currentEndpoint; |
| 307 | this->m_allowP2p = allowP2p; |
| 308 | this->m_connectionMaxLayer = connectionMaxLayer; |
| 309 | if (connectionMaxLayer >= 74) |
| 310 | { |
| 311 | m_useMTProto2 = true; |
| 312 | } |
| 313 | AddIPv6Relays(); |
| 314 | } |
| 315 |
| 316 | void VoIPController::Start() |
| 317 | { |
| 318 | LOGW("Starting voip controller"); |
| 319 | m_udpSocket->Open(); |
| 320 | if (m_udpSocket->IsFailed()) |
| 321 | { |
| 322 | SetState(State::FAILED); |
| 323 | return; |
| 324 | } |
| 325 |
| 326 | m_runReceiver = true; |
| 327 | m_recvThread = new Thread(std::bind(&VoIPController::RunRecvThread, this)); |
| 328 | m_recvThread->SetName("VoipRecv"); |
| 329 | m_recvThread->Start(); |
| 330 |
| 331 | m_messageThread.Start(); |
| 332 | } |
| 333 |
| 334 | void VoIPController::Connect() |
| 335 | { |
| 336 | assert(m_state != State::WAIT_INIT_ACK); |
| 337 | m_connectionInitTime = GetCurrentTime(); |
| 338 | if (m_config.initTimeout == 0.0) |
| 339 | { |
| 340 | LOGE("Init timeout is 0 -- did you forget to set config?"); |
| 341 | m_config.initTimeout = 30.0; |
| 342 | } |
| 343 |
| 344 | m_sendThread = new Thread(std::bind(&VoIPController::RunSendThread, this)); |
| 345 | m_sendThread->SetName("VoipSend"); |
| 346 | m_sendThread->Start(); |
| 347 | } |
| 348 |
| 349 | void VoIPController::SetEncryptionKey(char* key, bool isOutgoing) |
| 350 | { |
| 351 | std::memcpy(m_encryptionKey, key, 256); |
| 352 | std::uint8_t sha1[SHA1_LENGTH]; |
| 353 | crypto.sha1(reinterpret_cast<std::uint8_t*>(m_encryptionKey), 256, sha1); |
| 354 | std::memcpy(m_keyFingerprint, sha1 + (SHA1_LENGTH - 8), 8); |
| 355 | std::uint8_t sha256[SHA256_LENGTH]; |
| 356 | crypto.sha256(reinterpret_cast<std::uint8_t*>(m_encryptionKey), 256, sha256); |
| 357 | std::memcpy(m_callID, sha256 + (SHA256_LENGTH - 16), 16); |
| 358 | this->m_isOutgoing = isOutgoing; |
| 359 | } |
| 360 |
| 361 | void VoIPController::SetNetworkType(NetType type) |
| 362 | { |
| 363 | m_networkType = type; |
| 364 | UpdateDataSavingState(); |
| 365 | UpdateAudioBitrateLimit(); |
| 366 | m_myIPv6 = NetworkAddress::Empty(); |
| 367 | std::string itfName = m_udpSocket->GetLocalInterfaceInfo(nullptr, &m_myIPv6); |
| 368 | LOGI("set network type: %s, active interface %s", NetworkTypeToString(type).c_str(), itfName.c_str()); |
| 369 | LOGI("Local IPv6 address: %s", m_myIPv6.ToString().c_str()); |
| 370 | if (IS_MOBILE_NETWORK(m_networkType)) |
| 371 | { |
| 372 | CellularCarrierInfo carrier = GetCarrierInfo(); |
| 373 | if (!carrier.name.empty()) |
| 374 | { |
| 375 | LOGI("Carrier: %s [%s; mcc=%s, mnc=%s]", carrier.name.c_str(), carrier.countryCode.c_str(), carrier.mcc.c_str(), carrier.mnc.c_str()); |
| 376 | } |
| 377 | } |
| 378 | if (itfName != m_activeNetItfName) |
| 379 | { |
| 380 | m_udpSocket->OnActiveInterfaceChanged(); |
| 381 | LOGI("Active network interface changed: %s -> %s", m_activeNetItfName.c_str(), itfName.c_str()); |
| 382 | bool isFirstChange = m_activeNetItfName.length() == 0 && m_state != State::ESTABLISHED && m_state != State::RECONNECTING; |
| 383 | m_activeNetItfName = itfName; |
| 384 | if (isFirstChange) |
| 385 | return; |
| 386 | m_messageThread.Post([this] |
| 387 | { |
| 388 | m_wasNetworkHandover = true; |
| 389 | if (m_currentEndpoint != 0) |
| 390 | { |
| 391 | const Endpoint& _currentEndpoint = m_endpoints.at(m_currentEndpoint); |
| 392 | const Endpoint& _preferredRelay = m_endpoints.at(m_preferredRelay); |
| 393 | if (_currentEndpoint.type != Endpoint::Type::UDP_RELAY) |
| 394 | { |
| 395 | if (_preferredRelay.type == Endpoint::Type::UDP_RELAY) |
| 396 | m_currentEndpoint = m_preferredRelay; |
| 397 | MutexGuard m(m_endpointsMutex); |
| 398 | constexpr std::int64_t lanID = static_cast<std::int64_t>(FOURCC('L', 'A', 'N', '4')) << 32; |
| 399 | m_endpoints.erase(lanID); |
| 400 | for (std::pair<const std::int64_t, Endpoint>& e : m_endpoints) |
| 401 | { |
| 402 | Endpoint& endpoint = e.second; |
| 403 | if (endpoint.type == Endpoint::Type::UDP_RELAY && m_useTCP) |
| 404 | { |
| 405 | m_useTCP = false; |
| 406 | if (_preferredRelay.type == Endpoint::Type::TCP_RELAY) |
| 407 | { |
| 408 | m_preferredRelay = m_currentEndpoint = endpoint.id; |
| 409 | } |
| 410 | } |
| 411 | else if (endpoint.type == Endpoint::Type::TCP_RELAY && endpoint.m_socket) |
| 412 | { |
| 413 | endpoint.m_socket->Close(); |
| 414 | } |
| 415 | endpoint.m_averageRTT = 0; |
| 416 | endpoint.m_rtts.Reset(); |
| 417 | } |
| 418 | } |
| 419 | } |
| 420 | m_lastUdpPingTime = 0; |
| 421 | if (m_proxyProtocol == Proxy::SOCKS5) |
| 422 | InitUDPProxy(); |
| 423 | if (m_allowP2p && m_currentEndpoint) |
| 424 | { |
| 425 | SendPublicEndpointsRequest(); |
| 426 | } |
| 427 | BufferOutputStream s(4); |
| 428 | s.WriteInt32(m_dataSavingMode ? INIT_FLAG_DATA_SAVING_ENABLED : 0); |
| 429 | if (m_peerVersion < 6) |
| 430 | { |
| 431 | SendPacketReliably(PktType::NETWORK_CHANGED, s.GetBuffer(), s.GetLength(), 1, 20); |
| 432 | } |
| 433 | else |
| 434 | { |
| 435 | Buffer buf(std::move(s)); |
| 436 | SendExtra(buf, ExtraType::NETWORK_CHANGED); |
| 437 | } |
| 438 | m_needReInitUdpProxy = true; |
| 439 | m_selectCanceller->CancelSelect(); |
| 440 | m_didSendIPv6Endpoint = false; |
| 441 |
| 442 | AddIPv6Relays(); |
| 443 | ResetUdpAvailability(); |
| 444 | ResetEndpointPingStats(); |
| 445 | }); |
| 446 | } |
| 447 | } |
| 448 |
| 449 | double VoIPController::GetAverageRTT() |
| 450 | { |
| 451 | ENFORCE_MSG_THREAD; |
| 452 |
| 453 | if (m_lastSentSeq >= m_lastRemoteAckSeq) |
| 454 | { |
| 455 | std::uint32_t diff = m_lastSentSeq - m_lastRemoteAckSeq; |
| 456 | if (diff < 32) |
| 457 | { |
| 458 | double res = 0; |
| 459 | int count = 0; |
| 460 | for (const RecentOutgoingPacket& packet : m_recentOutgoingPackets) |
| 461 | { |
| 462 | if (packet.ackTime > 0) |
| 463 | { |
| 464 | res += (packet.ackTime - packet.sendTime); |
| 465 | ++count; |
| 466 | } |
| 467 | } |
| 468 | if (count > 0) |
| 469 | res /= count; |
| 470 | return res; |
| 471 | } |
| 472 | } |
| 473 | return 999; |
| 474 | } |
| 475 |
| 476 | void VoIPController::SetMicMute(bool mute) |
| 477 | { |
| 478 | if (m_micMuted == mute) |
| 479 | return; |
| 480 | m_micMuted = mute; |
| 481 | if (m_audioInput) |
| 482 | { |
| 483 | if (mute) |
| 484 | m_audioInput->Stop(); |
| 485 | else |
| 486 | m_audioInput->Start(); |
| 487 | if (!m_audioInput->IsInitialized()) |
| 488 | { |
| 489 | m_lastError = Error::AUDIO_IO; |
| 490 | SetState(State::FAILED); |
| 491 | return; |
| 492 | } |
| 493 | } |
| 494 | if (m_echoCanceller) |
| 495 | m_echoCanceller->Enable(!mute); |
| 496 | if (m_state == State::ESTABLISHED) |
| 497 | { |
| 498 | m_messageThread.Post([this] |
| 499 | { |
| 500 | for (std::shared_ptr<Stream>& s : m_outgoingStreams) |
| 501 | { |
| 502 | if (s->type != StreamType::AUDIO) |
| 503 | continue; |
| 504 | s->enabled = !m_micMuted; |
| 505 | if (m_peerVersion < 6) |
| 506 | { |
| 507 | std::uint8_t buf[2]; |
| 508 | buf[0] = s->id; |
| 509 | buf[1] = (m_micMuted ? 0 : 1); |
| 510 | SendPacketReliably(PktType::STREAM_STATE, buf, 2, 0.5, 20); |
| 511 | } |
| 512 | else |
| 513 | { |
| 514 | SendStreamFlags(*s); |
| 515 | } |
| 516 | } |
| 517 | }); |
| 518 | } |
| 519 | } |
| 520 |
| 521 | std::string VoIPController::GetDebugString() |
| 522 | { |
| 523 | std::string r = "Remote endpoints: \n"; |
| 524 | char buffer[2048]; |
| 525 | MutexGuard m(m_endpointsMutex); |
| 526 | for (auto& [_, endpoint] : m_endpoints) |
| 527 | { |
| 528 | std::string type; |
| 529 | switch (endpoint.type) |
| 530 | { |
| 531 | case Endpoint::Type::UDP_P2P_INET: |
| 532 | type = "UDP_P2P_INET"; |
| 533 | break; |
| 534 | case Endpoint::Type::UDP_P2P_LAN: |
| 535 | type = "UDP_P2P_LAN"; |
| 536 | break; |
| 537 | case Endpoint::Type::UDP_RELAY: |
| 538 | type = "UDP_RELAY"; |
| 539 | break; |
| 540 | case Endpoint::Type::TCP_RELAY: |
| 541 | type = "TCP_RELAY"; |
| 542 | break; |
| 543 | // default: |
| 544 | // type = "UNKNOWN"; |
| 545 | // break; |
| 546 | } |
| 547 | std::snprintf(buffer, |
| 548 | sizeof(buffer), |
| 549 | "%s:%u %dms %d 0x%" PRIx64 " [%s%s]\n", |
| 550 | endpoint.address.IsEmpty() ? ("[" + endpoint.v6address.ToString() + "]").c_str() : endpoint.address.ToString().c_str(), |
| 551 | endpoint.port, |
| 552 | static_cast<int>(endpoint.m_averageRTT * 1000), |
| 553 | endpoint.m_udpPongCount, |
| 554 | static_cast<std::uint64_t>(endpoint.id), |
| 555 | type.c_str(), |
| 556 | m_currentEndpoint == endpoint.id ? ", IN_USE" : ""); |
| 557 | r += buffer; |
| 558 | } |
| 559 | if (m_shittyInternetMode) |
| 560 | { |
| 561 | std::snprintf(buffer, sizeof(buffer), "ShittyInternetMode: level %d\n", m_extraEcLevel); |
| 562 | r += buffer; |
| 563 | } |
| 564 | double avgLate[3]; |
| 565 | std::shared_ptr<Stream> stream = GetStreamByType(StreamType::AUDIO, false); |
| 566 | std::shared_ptr<JitterBuffer> jitterBuffer; |
| 567 | if (stream != nullptr) |
| 568 | jitterBuffer = stream->jitterBuffer; |
| 569 | if (jitterBuffer != nullptr) |
| 570 | jitterBuffer->GetAverageLateCount(avgLate); |
| 571 | else |
| 572 | std::memset(avgLate, 0, 3 * sizeof(double)); |
| 573 | std::snprintf( |
| 574 | buffer, |
| 575 | sizeof(buffer), |
| 576 | "Jitter buffer: %d/%.2f | %.1f, %.1f, %.1f\n" |
| 577 | "RTT avg/min: %d/%d\n" |
| 578 | "Congestion window: %d/%d bytes\n" |
| 579 | "Key fingerprint: %02hhX%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX%s\n" |
| 580 | "Last sent/ack'd seq: %u/%u\n" |
| 581 | "Last recvd seq: %u\n" |
| 582 | "Send/recv losses: %u/%u (%d%%)\n" |
| 583 | "Audio bitrate: %d kbit\n" |
| 584 | "Outgoing queue: %u\n" |
| 585 | "Frame size out/in: %d/%d\n" |
| 586 | "Bytes sent/recvd: %llu/%llu", |
| 587 | jitterBuffer ? jitterBuffer->GetMinPacketCount() : 0, |
| 588 | jitterBuffer ? jitterBuffer->GetAverageDelay() : 0, |
| 589 | avgLate[0], |
| 590 | avgLate[1], |
| 591 | avgLate[2], |
| 592 | static_cast<int>(m_congestionControl->GetAverageRTT() * 1000), |
| 593 | static_cast<int>(m_congestionControl->GetMinimumRTT() * 1000), |
| 594 | static_cast<int>(m_congestionControl->GetInflightDataSize()), |
| 595 | static_cast<int>(m_congestionControl->GetCongestionWindow()), |
| 596 | m_keyFingerprint[0], |
| 597 | m_keyFingerprint[1], |
| 598 | m_keyFingerprint[2], |
| 599 | m_keyFingerprint[3], |
| 600 | m_keyFingerprint[4], |
| 601 | m_keyFingerprint[5], |
| 602 | m_keyFingerprint[6], |
| 603 | m_keyFingerprint[7], |
| 604 | m_useMTProto2 ? " (MTProto2.0)" : "", |
| 605 | m_lastSentSeq, |
| 606 | m_lastRemoteAckSeq, |
| 607 | m_lastRemoteSeq, |
| 608 | m_sendLosses, |
| 609 | m_recvLossCount, |
| 610 | m_encoder ? m_encoder->GetPacketLoss() : 0, |
| 611 | m_encoder ? (m_encoder->GetBitrate() / 1000) : 0, |
| 612 | m_unsentStreamPackets.load(), |
| 613 | m_outgoingStreams[0]->frameDuration, !m_incomingStreams.empty() ? m_incomingStreams[0]->frameDuration : 0, |
| 614 | static_cast<unsigned long long>(m_stats.bytesSentMobile + m_stats.bytesSentWifi), |
| 615 | static_cast<unsigned long long>(m_stats.bytesRecvdMobile + m_stats.bytesRecvdWifi) |
| 616 | ); |
| 617 | r += buffer; |
| 618 |
| 619 | /*if (m_config.enableVideoSend) |
| 620 | { |
| 621 | std::shared_ptr<Stream> vstm = GetStreamByType(StreamType::VIDEO, true); |
| 622 | if (vstm != nullptr && vstm->enabled && m_videoPacketSender) |
| 623 | { |
| 624 | std::snprintf(buffer, sizeof(buffer), "\nVideo out: %ux%u '%c%c%c%c' %u kbit", vstm->width, vstm->height, PRINT_FOURCC(vstm->codec), m_videoPacketSender->GetBitrate()); |
| 625 | r += buffer; |
| 626 | } |
| 627 | }*/ |
| 628 | if (!m_peerVideoDecoders.empty()) |
| 629 | { |
| 630 | r += "\nPeer codecs: "; |
| 631 | for (std::uint32_t codec : m_peerVideoDecoders) |
| 632 | { |
| 633 | std::snprintf(buffer, sizeof(buffer), "'%c%c%c%c' ", PRINT_FOURCC(codec)); |
| 634 | r += buffer; |
| 635 | } |
| 636 | } |
| 637 | if (m_config.enableVideoReceive) |
| 638 | { |
| 639 | std::shared_ptr<Stream> vstm = GetStreamByType(StreamType::VIDEO, false); |
| 640 | if (vstm != nullptr && vstm->enabled) |
| 641 | { |
| 642 | std::snprintf(buffer, sizeof(buffer), "\nVideo in: %ux%u '%c%c%c%c'", vstm->width, vstm->height, PRINT_FOURCC(vstm->codec)); |
| 643 | r += buffer; |
| 644 | } |
| 645 | } |
| 646 |
| 647 | return r; |
| 648 | } |
| 649 |
| 650 | const char* VoIPController::GetVersion() |
| 651 | { |
| 652 | return LIBTGVOIP_VERSION; |
| 653 | } |
| 654 |
| 655 | std::int64_t VoIPController::GetPreferredRelayID() |
| 656 | { |
| 657 | return m_preferredRelay; |
| 658 | } |
| 659 |
| 660 | Error VoIPController::GetLastError() |
| 661 | { |
| 662 | return m_lastError; |
| 663 | } |
| 664 |
| 665 | void VoIPController::GetStats(TrafficStats* stats) |
| 666 | { |
| 667 | std::memcpy(stats, &this->m_stats, sizeof(TrafficStats)); |
| 668 | } |
| 669 |
| 670 | std::string VoIPController::GetDebugLog() |
| 671 | { |
| 672 | std::map<std::string, json11::Json> network { |
| 673 | {"type", NetworkTypeToString(m_networkType)}}; |
| 674 | if (IS_MOBILE_NETWORK(m_networkType)) |
| 675 | { |
| 676 | CellularCarrierInfo carrier = GetCarrierInfo(); |
| 677 | if (!carrier.name.empty()) |
| 678 | { |
| 679 | network["carrier"] = carrier.name; |
| 680 | network["country"] = carrier.countryCode; |
| 681 | network["mcc"] = carrier.mcc; |
| 682 | network["mnc"] = carrier.mnc; |
| 683 | } |
| 684 | } |
| 685 | else if (m_networkType == NetType::WIFI) |
| 686 | { |
| 687 | #ifdef __ANDROID__ |
| 688 | jni::DoWithJNI([&](JNIEnv* env) { |
| 689 | jmethodID getWifiInfoMethod = env->GetStaticMethodID(jniUtilitiesClass, "getWifiInfo", "()[I"); |
| 690 | jintArray res = static_cast<jintArray>(env->CallStaticObjectMethod(jniUtilitiesClass, getWifiInfoMethod)); |
| 691 | if (res) |
| 692 | { |
| 693 | jint* wifiInfo = env->GetIntArrayElements(res, nullptr); |
| 694 | network["rssi"] = wifiInfo[0]; |
| 695 | network["link_speed"] = wifiInfo[1]; |
| 696 | env->ReleaseIntArrayElements(res, wifiInfo, JNI_ABORT); |
| 697 | } |
| 698 | }); |
| 699 | #endif |
| 700 | } |
| 701 |
| 702 | std::vector<json11::Json> endpointsJson; |
| 703 | for (auto& [_, endpoint] : m_endpoints) |
| 704 | { |
| 705 | std::string type; |
| 706 | std::map<std::string, json11::Json> je |
| 707 | { |
| 708 | { "rtt", static_cast<int>(endpoint.m_averageRTT * 1000) } |
| 709 | }; |
| 710 | std::int64_t id = 0; |
| 711 | if (endpoint.type == Endpoint::Type::UDP_RELAY) |
| 712 | { |
| 713 | je["type"] = endpoint.IsIPv6Only() ? "udp_relay6" : "udp_relay"; |
| 714 | id = endpoint.CleanID(); |
| 715 | if (endpoint.m_totalUdpPings == 0) |
| 716 | je["udp_pings"] = 0.0; |
| 717 | else |
| 718 | je["udp_pings"] = static_cast<double>(endpoint.m_totalUdpPingReplies) / endpoint.m_totalUdpPings; |
| 719 | je["self_rtt"] = static_cast<int>(endpoint.m_selfRtts.Average() * 1000); |
| 720 | } |
| 721 | else if (endpoint.type == Endpoint::Type::TCP_RELAY) |
| 722 | { |
| 723 | je["type"] = endpoint.IsIPv6Only() ? "tcp_relay6" : "tcp_relay"; |
| 724 | id = endpoint.CleanID(); |
| 725 | } |
| 726 | else if (endpoint.type == Endpoint::Type::UDP_P2P_INET) |
| 727 | { |
| 728 | je["type"] = endpoint.IsIPv6Only() ? "p2p_inet6" : "p2p_inet"; |
| 729 | } |
| 730 | else if (endpoint.type == Endpoint::Type::UDP_P2P_LAN) |
| 731 | { |
| 732 | je["type"] = "p2p_lan"; |
| 733 | } |
| 734 | if (m_preferredRelay == endpoint.id && m_wasEstablished) |
| 735 | je["pref"] = true; |
| 736 | if (id) |
| 737 | { |
| 738 | std::ostringstream s; |
| 739 | s << id; |
| 740 | je["id"] = s.str(); |
| 741 | } |
| 742 | endpointsJson.emplace_back(je); |
| 743 | } |
| 744 |
| 745 | std::string p2pType = "none"; |
| 746 | Endpoint& cur = m_endpoints[m_currentEndpoint]; |
| 747 | if (cur.type == Endpoint::Type::UDP_P2P_INET) |
| 748 | p2pType = cur.IsIPv6Only() ? "inet6" : "inet"; |
| 749 | else if (cur.type == Endpoint::Type::UDP_P2P_LAN) |
| 750 | p2pType = "lan"; |
| 751 |
| 752 | std::vector<std::string> problems; |
| 753 | if (m_lastError == Error::TIMEOUT) |
| 754 | problems.emplace_back("timeout"); |
| 755 | if (m_wasReconnecting) |
| 756 | problems.emplace_back("reconnecting"); |
| 757 | if (m_wasExtraEC) |
| 758 | problems.emplace_back("extra_ec"); |
| 759 | if (m_wasEncoderLaggy) |
| 760 | problems.emplace_back("encoder_lag"); |
| 761 | if (!m_wasEstablished) |
| 762 | problems.emplace_back("not_inited"); |
| 763 | if (m_wasNetworkHandover) |
| 764 | problems.emplace_back("network_handover"); |
| 765 |
| 766 | return json11::Json(json11::Json::object |
| 767 | { |
| 768 | { "log_type", "call_stats" }, |
| 769 | { "libtgvoip_version", LIBTGVOIP_VERSION }, |
| 770 | { "network", network }, |
| 771 | { "protocol_version", std::min(m_peerVersion, PROTOCOL_VERSION) }, |
| 772 | { "udp_avail", m_udpConnectivityState == UdpState::AVAILABLE }, |
| 773 | { "tcp_used", m_useTCP }, |
| 774 | { "p2p_type", p2pType }, |
| 775 | { "packet_stats", |
| 776 | json11::Json::object |
| 777 | { |
| 778 | { "out", static_cast<int>(m_seq) }, |
| 779 | { "in", static_cast<int>(m_packetsReceived) }, |
| 780 | { "lost_out", static_cast<int>(m_congestionControl->GetSendLossCount()) }, |
| 781 | { "lost_in", static_cast<int>(m_recvLossCount) } |
| 782 | } |
| 783 | }, |
| 784 | { "endpoints", endpointsJson }, |
| 785 | { "problems", problems } |
| 786 | }).dump(); |
| 787 | } |
| 788 |
| 789 | std::vector<AudioInputDevice> VoIPController::EnumerateAudioInputs() |
| 790 | { |
| 791 | std::vector<AudioInputDevice> devs; |
| 792 | audio::AudioInput::EnumerateDevices(devs); |
| 793 | return devs; |
| 794 | } |
| 795 |
| 796 | std::vector<AudioOutputDevice> VoIPController::EnumerateAudioOutputs() |
| 797 | { |
| 798 | std::vector<AudioOutputDevice> devs; |
| 799 | audio::AudioOutput::EnumerateDevices(devs); |
| 800 | return devs; |
| 801 | } |
| 802 |
| 803 | void VoIPController::SetCurrentAudioInput(std::string id) |
| 804 | { |
| 805 | m_currentAudioInput = std::move(id); |
| 806 | if (m_audioInput != nullptr) |
| 807 | m_audioInput->SetCurrentDevice(m_currentAudioInput); |
| 808 | } |
| 809 |
| 810 | void VoIPController::SetCurrentAudioOutput(std::string id) |
| 811 | { |
| 812 | m_currentAudioOutput = std::move(id); |
| 813 | if (m_audioOutput) |
| 814 | m_audioOutput->SetCurrentDevice(m_currentAudioOutput); |
| 815 | } |
| 816 |
| 817 | std::string VoIPController::GetCurrentAudioInputID() const |
| 818 | { |
| 819 | return m_currentAudioInput; |
| 820 | } |
| 821 |
| 822 | std::string VoIPController::GetCurrentAudioOutputID() const |
| 823 | { |
| 824 | return m_currentAudioOutput; |
| 825 | } |
| 826 |
| 827 | void VoIPController::SetProxy(Proxy protocol, std::string address, std::uint16_t port, std::string username, std::string password) |
| 828 | { |
| 829 | m_proxyProtocol = protocol; |
| 830 | m_proxyAddress = std::move(address); |
| 831 | m_proxyPort = port; |
| 832 | m_proxyUsername = std::move(username); |
| 833 | m_proxyPassword = std::move(password); |
| 834 | } |
| 835 |
| 836 | int VoIPController::GetSignalBarsCount() |
| 837 | { |
| 838 | return m_signalBarsHistory.NonZeroAverage(); |
| 839 | } |
| 840 |
| 841 | void VoIPController::SetCallbacks(VoIPController::Callbacks callbacks) |
| 842 | { |
| 843 | m_callbacks = callbacks; |
| 844 | if (callbacks.connectionStateChanged) |
| 845 | callbacks.connectionStateChanged(this, m_state); |
| 846 | } |
| 847 |
| 848 | float VoIPController::GetOutputLevel() const |
| 849 | { |
| 850 | return 0.0f; |
| 851 | } |
| 852 |
| 853 | void VoIPController::SetAudioOutputGainControlEnabled(bool enabled) |
| 854 | { |
| 855 | LOGD("New output AGC state: %d", enabled); |
| 856 | } |
| 857 |
| 858 | std::uint32_t VoIPController::GetPeerCapabilities() |
| 859 | { |
| 860 | return m_peerCapabilities; |
| 861 | } |
| 862 |
| 863 | void VoIPController::SendGroupCallKey(std::uint8_t* key) |
| 864 | { |
| 865 | Buffer buf(256); |
| 866 | buf.CopyFrom(key, 0, 256); |
| 867 | std::shared_ptr<Buffer> keyPtr = std::make_shared<Buffer>(std::move(buf)); |
| 868 | m_messageThread.Post([this, keyPtr] |
| 869 | { |
| 870 | if (!(m_peerCapabilities & TGVOIP_PEER_CAP_GROUP_CALLS)) |
| 871 | { |
| 872 | LOGE("Tried to send group call key but peer isn't capable of them"); |
| 873 | return; |
| 874 | } |
| 875 | if (m_didSendGroupCallKey) |
| 876 | { |
| 877 | LOGE("Tried to send a group call key repeatedly"); |
| 878 | return; |
| 879 | } |
| 880 | if (!m_isOutgoing) |
| 881 | { |
| 882 | LOGE("You aren't supposed to send group call key in an incoming call, use VoIPController::RequestCallUpgrade() instead"); |
| 883 | return; |
| 884 | } |
| 885 | m_didSendGroupCallKey = true; |
| 886 | SendExtra(*keyPtr, ExtraType::GROUP_CALL_KEY); |
| 887 | }); |
| 888 | } |
| 889 |
| 890 | void VoIPController::RequestCallUpgrade() |
| 891 | { |
| 892 | m_messageThread.Post([this] |
| 893 | { |
| 894 | if (!(m_peerCapabilities & TGVOIP_PEER_CAP_GROUP_CALLS)) |
| 895 | { |
| 896 | LOGE("Tried to send group call key but peer isn't capable of them"); |
| 897 | return; |
| 898 | } |
| 899 | if (m_didSendUpgradeRequest) |
| 900 | { |
| 901 | LOGE("Tried to send upgrade request repeatedly"); |
| 902 | return; |
| 903 | } |
| 904 | if (m_isOutgoing) |
| 905 | { |
| 906 | LOGE("You aren't supposed to send an upgrade request in an outgoing call, generate an encryption key and use VoIPController::SendGroupCallKey instead"); |
| 907 | return; |
| 908 | } |
| 909 | m_didSendUpgradeRequest = true; |
| 910 | Buffer empty(0); |
| 911 | SendExtra(empty, ExtraType::REQUEST_GROUP); |
| 912 | }); |
| 913 | } |
| 914 |
| 915 | void VoIPController::SetEchoCancellationStrength(int strength) |
| 916 | { |
| 917 | m_echoCancellationStrength = strength; |
| 918 | if (m_echoCanceller != nullptr) |
| 919 | m_echoCanceller->SetAECStrength(strength); |
| 920 | } |
| 921 |
| 922 | #if defined(TGVOIP_USE_CALLBACK_AUDIO_IO) |
| 923 | void VoIPController::SetAudioDataCallbacks(std::function<void(std::int16_t*, std::size_t)> input, std::function<void(std::int16_t*, std::size_t)> output, std::function<void(std::int16_t*, std::size_t)> preproc = nullptr) |
| 924 | { |
| 925 | m_audioInputDataCallback = std::move(input); |
| 926 | m_audioOutputDataCallback = std::move(output); |
| 927 | m_audioPreprocDataCallback = std::move(preproc); |
| 928 | m_preprocDecoder = m_preprocDecoder ? m_preprocDecoder : opus_decoder_create(48000, 1, nullptr); |
| 929 | } |
| 930 | #endif |
| 931 |
| 932 | State VoIPController::GetConnectionState() const |
| 933 | { |
| 934 | return m_state; |
| 935 | } |
| 936 |
| 937 | void VoIPController::SetConfig(const Config& cfg) |
| 938 | { |
| 939 | m_config = cfg; |
| 940 | if (tgvoipLogFile) |
| 941 | { |
| 942 | fclose(tgvoipLogFile); |
| 943 | tgvoipLogFile = nullptr; |
| 944 | } |
| 945 | if (!m_config.logFilePath.empty()) |
| 946 | { |
| 947 | #ifndef _WIN32 |
| 948 | tgvoipLogFile = fopen(m_config.logFilePath.c_str(), "a"); |
| 949 | #else |
| 950 | if (_wfopen_s(&tgvoipLogFile, config.logFilePath.c_str(), L"a") != 0) |
| 951 | { |
| 952 | tgvoipLogFile = nullptr; |
| 953 | } |
| 954 | #endif |
| 955 | tgvoip_log_file_write_header(tgvoipLogFile); |
| 956 | } |
| 957 | else |
| 958 | { |
| 959 | tgvoipLogFile = nullptr; |
| 960 | } |
| 961 | if (m_statsDump != nullptr) |
| 962 | { |
| 963 | std::fclose(m_statsDump); |
| 964 | m_statsDump = nullptr; |
| 965 | } |
| 966 | if (!m_config.statsDumpFilePath.empty()) |
| 967 | { |
| 968 | #ifndef _WIN32 |
| 969 | m_statsDump = fopen(m_config.statsDumpFilePath.c_str(), "w"); |
| 970 | #else |
| 971 | if (_wfopen_s(&statsDump, config.statsDumpFilePath.c_str(), L"w") != 0) |
| 972 | { |
| 973 | statsDump = nullptr; |
| 974 | } |
| 975 | #endif |
| 976 | if (m_statsDump != nullptr) |
| 977 | std::fprintf(m_statsDump, "Time\tRTT\tLRSeq\tLSSeq\tLASeq\tLostR\tLostS\tCWnd\tBitrate\tLoss%%\tJitter\tJDelay\tAJDelay\n"); |
| 978 | } |
| 979 | else |
| 980 | { |
| 981 | m_statsDump = nullptr; |
| 982 | } |
| 983 | UpdateDataSavingState(); |
| 984 | UpdateAudioBitrateLimit(); |
| 985 | } |
| 986 |
| 987 | void VoIPController::SetPersistentState(const std::vector<std::uint8_t>& state) |
| 988 | { |
| 989 | using namespace json11; |
| 990 |
| 991 | if (state.empty()) |
| 992 | return; |
| 993 | std::string jsonErr; |
| 994 | std::string json = std::string(state.begin(), state.end()); |
| 995 | Json _obj = Json::parse(json, jsonErr); |
| 996 | if (!jsonErr.empty()) |
| 997 | { |
| 998 | LOGE("Error parsing persistable state: %s", jsonErr.c_str()); |
| 999 | return; |
| 1000 | } |
| 1001 | Json::object obj = _obj.object_items(); |
| 1002 | if (obj.find("proxy") != obj.end()) |
| 1003 | { |
| 1004 | Json::object proxy = obj["proxy"].object_items(); |
| 1005 | m_lastTestedProxyServer = proxy["server"].string_value(); |
| 1006 | m_proxySupportsUDP = proxy["udp"].bool_value(); |
| 1007 | m_proxySupportsTCP = proxy["tcp"].bool_value(); |
| 1008 | } |
| 1009 | } |
| 1010 |
| 1011 | std::vector<std::uint8_t> VoIPController::GetPersistentState() |
| 1012 | { |
| 1013 | using namespace json11; |
| 1014 |
| 1015 | Json::object obj = Json::object { |
| 1016 | {"ver", 1}, |
| 1017 | }; |
| 1018 | if (m_proxyProtocol == Proxy::SOCKS5) |
| 1019 | { |
| 1020 | char pbuf[128]; |
| 1021 | std::snprintf(pbuf, sizeof(pbuf), "%s:%u", m_proxyAddress.c_str(), m_proxyPort); |
| 1022 | obj.insert({"proxy", Json::object {{"server", std::string(pbuf)}, {"udp", m_proxySupportsUDP}, {"tcp", m_proxySupportsTCP}}}); |
| 1023 | } |
| 1024 | std::string _jstr = Json(obj).dump(); |
| 1025 | const char* jstr = _jstr.c_str(); |
| 1026 | return std::vector<std::uint8_t>(jstr, jstr + strlen(jstr)); |
| 1027 | } |
| 1028 |
| 1029 | void VoIPController::SetOutputVolume(float level) |
| 1030 | { |
| 1031 | m_outputVolume.SetLevel(level); |
| 1032 | } |
| 1033 |
| 1034 | void VoIPController::SetInputVolume(float level) |
| 1035 | { |
| 1036 | m_inputVolume.SetLevel(level); |
| 1037 | } |
| 1038 |
| 1039 | #if defined(__APPLE__) && TARGET_OS_OSX |
| 1040 | void VoIPController::SetAudioOutputDuckingEnabled(bool enabled) |
| 1041 | { |
| 1042 | macAudioDuckingEnabled = enabled; |
| 1043 | audio::AudioUnitIO* osxAudio = dynamic_cast<audio::AudioUnitIO*>(audioIO); |
| 1044 | if (osxAudio) |
| 1045 | { |
| 1046 | osxAudio->SetDuckingEnabled(enabled); |
| 1047 | } |
| 1048 | } |
| 1049 | #endif |
| 1050 |
| 1051 | #pragma mark - Internal intialization |
| 1052 |
| 1053 | void VoIPController::InitializeTimers() |
| 1054 | { |
| 1055 | m_initTimeoutID = m_messageThread.Post([this] |
| 1056 | { |
| 1057 | LOGW("Init timeout, disconnecting"); |
| 1058 | m_lastError = Error::TIMEOUT; |
| 1059 | SetState(State::FAILED); |
| 1060 | }, |
| 1061 | m_config.initTimeout); |
| 1062 |
| 1063 | if (!m_config.statsDumpFilePath.empty()) |
| 1064 | { |
| 1065 | m_messageThread.Post([this] |
| 1066 | { |
| 1067 | if (m_statsDump != nullptr && m_incomingStreams.size() == 1) |
| 1068 | { |
| 1069 | std::shared_ptr<JitterBuffer>& jitterBuffer = m_incomingStreams[0]->jitterBuffer; |
| 1070 | std::fprintf(m_statsDump, "%.3f\t%.3f\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%.3f\t%.3f\t%.3f\n", |
| 1071 | GetCurrentTime() - m_connectionInitTime, |
| 1072 | m_endpoints.at(m_currentEndpoint).m_rtts[0], |
| 1073 | m_lastRemoteSeq, |
| 1074 | m_seq.load(), |
| 1075 | m_lastRemoteAckSeq, |
| 1076 | m_recvLossCount, |
| 1077 | m_congestionControl ? m_congestionControl->GetSendLossCount() : 0, |
| 1078 | m_congestionControl ? static_cast<int>(m_congestionControl->GetInflightDataSize()) : 0, |
| 1079 | m_encoder ? m_encoder->GetBitrate() : 0, |
| 1080 | m_encoder ? m_encoder->GetPacketLoss() : 0, |
| 1081 | jitterBuffer ? jitterBuffer->GetLastMeasuredJitter() : 0, |
| 1082 | jitterBuffer ? jitterBuffer->GetLastMeasuredDelay() * 0.06 : 0, |
| 1083 | jitterBuffer ? jitterBuffer->GetAverageDelay() * 0.06 : 0); |
| 1084 | } |
| 1085 | }, |
| 1086 | 0.1, 0.1); |
| 1087 | } |
| 1088 |
| 1089 | m_messageThread.Post(std::bind(&VoIPController::SendRelayPings, this), 0.0, 2.0); |
| 1090 | } |
| 1091 |
| 1092 | void VoIPController::RunSendThread() |
| 1093 | { |
| 1094 | InitializeAudio(); |
| 1095 | InitializeTimers(); |
| 1096 | m_messageThread.Post(std::bind(&VoIPController::SendInit, this)); |
| 1097 |
| 1098 | while (true) |
| 1099 | { |
| 1100 | RawPendingOutgoingPacket pkt = m_rawSendQueue.GetBlocking(); |
| 1101 | if (pkt.packet.IsEmpty()) |
| 1102 | break; |
| 1103 |
| 1104 | if (IS_MOBILE_NETWORK(m_networkType)) |
| 1105 | m_stats.bytesSentMobile += static_cast<std::uint64_t>(pkt.packet.data.Length()); |
| 1106 | else |
| 1107 | m_stats.bytesSentWifi += static_cast<std::uint64_t>(pkt.packet.data.Length()); |
| 1108 | if (pkt.packet.protocol == NetworkProtocol::TCP) |
| 1109 | { |
| 1110 | if (pkt.socket != nullptr && !pkt.socket->IsFailed()) |
| 1111 | { |
| 1112 | pkt.socket->Send(std::move(pkt.packet)); |
| 1113 | } |
| 1114 | } |
| 1115 | else |
| 1116 | { |
| 1117 | m_udpSocket->Send(std::move(pkt.packet)); |
| 1118 | } |
| 1119 | } |
| 1120 |
| 1121 | LOGI("=== send thread exiting ==="); |
| 1122 | } |
| 1123 |
| 1124 | #pragma mark - Miscellaneous |
| 1125 |
| 1126 | void VoIPController::SetState(State state) |
| 1127 | { |
| 1128 | this->m_state = state; |
| 1129 | LOGV("Call state changed to %d", static_cast<int>(state)); |
| 1130 | m_stateChangeTime = GetCurrentTime(); |
| 1131 | m_messageThread.Post([this, state] |
| 1132 | { |
| 1133 | if (m_callbacks.connectionStateChanged) |
| 1134 | m_callbacks.connectionStateChanged(this, state); |
| 1135 | }); |
| 1136 | if (state == State::ESTABLISHED) |
| 1137 | { |
| 1138 | SetMicMute(m_micMuted); |
| 1139 | if (!m_wasEstablished) |
| 1140 | { |
| 1141 | m_wasEstablished = true; |
| 1142 | m_messageThread.Post(std::bind(&VoIPController::UpdateRTT, this), 0.1, 0.5); |
| 1143 | m_messageThread.Post(std::bind(&VoIPController::UpdateAudioBitrate, this), 0.0, 0.3); |
| 1144 | m_messageThread.Post(std::bind(&VoIPController::UpdateCongestion, this), 0.0, 1.0); |
| 1145 | m_messageThread.Post(std::bind(&VoIPController::UpdateSignalBars, this), 1.0, 1.0); |
| 1146 | m_messageThread.Post(std::bind(&VoIPController::TickJitterBufferAndCongestionControl, this), 0.0, 0.1); |
| 1147 | } |
| 1148 | } |
| 1149 | } |
| 1150 |
| 1151 | void VoIPController::SendStreamFlags(Stream& stream) |
| 1152 | { |
| 1153 | ENFORCE_MSG_THREAD; |
| 1154 |
| 1155 | BufferOutputStream s(5); |
| 1156 | s.WriteUInt8(stream.id); |
| 1157 | std::int32_t flags = 0; |
| 1158 | if (stream.enabled) |
| 1159 | flags |= STREAM_FLAG_ENABLED; |
| 1160 | if (stream.extraECEnabled) |
| 1161 | flags |= STREAM_FLAG_EXTRA_EC; |
| 1162 | if (stream.paused) |
| 1163 | flags |= STREAM_FLAG_PAUSED; |
| 1164 | s.WriteInt32(flags); |
| 1165 | LOGV("My stream state: id %u flags %u", stream.id, flags); |
| 1166 | Buffer buf(std::move(s)); |
| 1167 | SendExtra(buf, ExtraType::STREAM_FLAGS); |
| 1168 | } |
| 1169 |
| 1170 | std::shared_ptr<VoIPController::Stream> VoIPController::GetStreamByType(StreamType type, bool outgoing) const |
| 1171 | { |
| 1172 | for (const std::shared_ptr<Stream>& ss : (outgoing ? m_outgoingStreams : m_incomingStreams)) |
| 1173 | if (ss->type == type) |
| 1174 | return ss; |
| 1175 | return std::shared_ptr<Stream>(); |
| 1176 | } |
| 1177 |
| 1178 | std::shared_ptr<VoIPController::Stream> VoIPController::GetStreamByID(std::uint8_t id, bool outgoing) const |
| 1179 | { |
| 1180 | for (const std::shared_ptr<Stream>& ss : (outgoing ? m_outgoingStreams : m_incomingStreams)) |
| 1181 | if (ss->id == id) |
| 1182 | return ss; |
| 1183 | return std::shared_ptr<Stream>(); |
| 1184 | } |
| 1185 |
| 1186 | CellularCarrierInfo VoIPController::GetCarrierInfo() |
| 1187 | { |
| 1188 | #if defined(__APPLE__) && TARGET_OS_IOS |
| 1189 | return DarwinSpecific::GetCarrierInfo(); |
| 1190 | #elif defined(__ANDROID__) |
| 1191 | CellularCarrierInfo carrier; |
| 1192 | jni::DoWithJNI([&carrier](JNIEnv* env) { |
| 1193 | jmethodID getCarrierInfoMethod = env->GetStaticMethodID(jniUtilitiesClass, "getCarrierInfo", "()[Ljava/lang/String;"); |
| 1194 | jobjectArray jinfo = (jobjectArray)env->CallStaticObjectMethod(jniUtilitiesClass, getCarrierInfoMethod); |
| 1195 | if (jinfo && env->GetArrayLength(jinfo) == 4) |
| 1196 | { |
| 1197 | carrier.name = jni::JavaStringToStdString(env, (jstring)env->GetObjectArrayElement(jinfo, 0)); |
| 1198 | carrier.countryCode = jni::JavaStringToStdString(env, (jstring)env->GetObjectArrayElement(jinfo, 1)); |
| 1199 | carrier.mcc = jni::JavaStringToStdString(env, (jstring)env->GetObjectArrayElement(jinfo, 2)); |
| 1200 | carrier.mnc = jni::JavaStringToStdString(env, (jstring)env->GetObjectArrayElement(jinfo, 3)); |
| 1201 | } |
| 1202 | else |
| 1203 | { |
| 1204 | LOGW("Failed to get carrier info"); |
| 1205 | } |
| 1206 | }); |
| 1207 | return carrier; |
| 1208 | #else |
| 1209 | return CellularCarrierInfo(); |
| 1210 | #endif |
| 1211 | } |
| 1212 |
| 1213 | #pragma mark - Audio I/O |
| 1214 |
| 1215 | void VoIPController::HandleAudioInput(std::uint8_t* data, std::size_t len, std::uint8_t* secondaryData, std::size_t secondaryLen) |
| 1216 | { |
| 1217 | if (m_stopping) |
| 1218 | return; |
| 1219 |
| 1220 | // TODO make an AudioPacketSender |
| 1221 |
| 1222 | bool hasSecondaryData = (secondaryLen != 0 && secondaryData != nullptr); |
| 1223 |
| 1224 | Buffer dataBuf = m_outgoingAudioBufferPool.Get(); |
| 1225 | Buffer secondaryDataBuf = hasSecondaryData ? m_outgoingAudioBufferPool.Get() : Buffer(); |
| 1226 | dataBuf.CopyFrom(data, 0, len); |
| 1227 | if (hasSecondaryData) |
| 1228 | { |
| 1229 | secondaryDataBuf.CopyFrom(secondaryData, 0, secondaryLen); |
| 1230 | } |
| 1231 | std::shared_ptr<Buffer> dataBufPtr = std::make_shared<Buffer>(std::move(dataBuf)); |
| 1232 | std::shared_ptr<Buffer> secondaryDataBufPtr = std::make_shared<Buffer>(std::move(secondaryDataBuf)); |
| 1233 | m_messageThread.Post([this, dataBufPtr, secondaryDataBufPtr, len, secondaryLen]() |
| 1234 | { |
| 1235 | m_unsentStreamPacketsHistory.Add(m_unsentStreamPackets); |
| 1236 | if (m_unsentStreamPacketsHistory.Average() >= m_maxUnsentStreamPackets && m_videoPacketSender == nullptr) |
| 1237 | { |
| 1238 | LOGW("Resetting stalled send queue"); |
| 1239 | m_sendQueue.clear(); |
| 1240 | m_unsentStreamPacketsHistory.Reset(); |
| 1241 | m_unsentStreamPackets = 0; |
| 1242 | } |
| 1243 | if (m_waitingForAcks || m_dontSendPackets > 0 || (m_unsentStreamPackets >= m_maxUnsentStreamPackets /*&& endpoints[currentEndpoint].type==Endpoint::Type::TCP_RELAY*/)) |
| 1244 | { |
| 1245 | LOGV("waiting for queue, dropping outgoing audio packet, %d %d %d [%d]", m_unsentStreamPackets.load(), m_waitingForAcks, m_dontSendPackets, m_maxUnsentStreamPackets); |
| 1246 | return; |
| 1247 | } |
| 1248 |
| 1249 | if (!m_receivedInitAck) |
| 1250 | return; |
| 1251 |
| 1252 | BufferOutputStream pkt(1500); |
| 1253 |
| 1254 | bool hasExtraFEC = m_peerVersion >= 7 && (secondaryLen != 0) && m_shittyInternetMode; |
| 1255 | std::uint8_t flags = static_cast<std::uint8_t>((len > 255 || hasExtraFEC) ? STREAM_DATA_FLAG_LEN16 : 0); |
| 1256 | pkt.WriteUInt8(1 | flags); // streamID + flags |
| 1257 | if (len > 255 || hasExtraFEC) |
| 1258 | { |
| 1259 | std::int16_t lenAndFlags = static_cast<std::int16_t>(len); |
| 1260 | if (hasExtraFEC) |
| 1261 | lenAndFlags |= STREAM_DATA_XFLAG_EXTRA_FEC; |
| 1262 | pkt.WriteInt16(lenAndFlags); |
| 1263 | } |
| 1264 | else |
| 1265 | { |
| 1266 | pkt.WriteUInt8(static_cast<std::uint8_t>(len)); |
| 1267 | } |
| 1268 | pkt.WriteUInt32(m_audioTimestampOut); |
| 1269 | pkt.WriteBytes(*dataBufPtr, 0, len); |
| 1270 |
| 1271 | if (hasExtraFEC) |
| 1272 | { |
| 1273 | pkt.WriteUInt8(static_cast<std::uint8_t>(std::min(static_cast<int>(m_ecAudioPackets.size()), m_extraEcLevel))); |
| 1274 | for (auto ecData = m_ecAudioPackets.begin() + std::max(0, static_cast<int>(m_ecAudioPackets.size()) - m_extraEcLevel); |
| 1275 | ecData != m_ecAudioPackets.end(); ++ecData) |
| 1276 | { |
| 1277 | pkt.WriteUInt8(static_cast<std::uint8_t>(ecData->Length())); |
| 1278 | pkt.WriteBytes(*ecData); |
| 1279 | } |
| 1280 | Buffer ecBuf(secondaryLen); |
| 1281 | ecBuf.CopyFrom(**secondaryDataBufPtr, 0, secondaryLen); |
| 1282 | m_ecAudioPackets.emplace_back(std::move(ecBuf)); |
| 1283 | while (m_ecAudioPackets.size() > 4) |
| 1284 | m_ecAudioPackets.pop_front(); |
| 1285 | } |
| 1286 |
| 1287 | ++m_unsentStreamPackets; |
| 1288 | std::size_t pktLength = pkt.GetLength(); |
| 1289 | PendingOutgoingPacket p |
| 1290 | { |
| 1291 | /*.seq=*/ GenerateOutSeq(), |
| 1292 | /*.type=*/ PktType::STREAM_DATA, |
| 1293 | /*.len=*/ pktLength, |
| 1294 | /*.data=*/ Buffer(std::move(pkt)), |
| 1295 | /*.endpoint=*/0, |
| 1296 | }; |
| 1297 |
| 1298 | m_congestionControl->PacketSent(p.seq, p.len); |
| 1299 |
| 1300 | SendOrEnqueuePacket(std::move(p)); |
| 1301 | if (m_peerVersion < 7 && secondaryLen != 0 && m_shittyInternetMode) |
| 1302 | { |
| 1303 | Buffer ecBuf(secondaryLen); |
| 1304 | ecBuf.CopyFrom(*secondaryDataBufPtr, 0, secondaryLen); |
| 1305 | m_ecAudioPackets.emplace_back(std::move(ecBuf)); |
| 1306 | while (m_ecAudioPackets.size() > 4) |
| 1307 | m_ecAudioPackets.pop_front(); |
| 1308 | pkt = BufferOutputStream(1500); |
| 1309 | pkt.WriteUInt8(m_outgoingStreams[0]->id); |
| 1310 | pkt.WriteUInt32(m_audioTimestampOut); |
| 1311 | pkt.WriteUInt8(static_cast<std::uint8_t>(std::min(static_cast<int>(m_ecAudioPackets.size()), m_extraEcLevel))); |
| 1312 | for (auto ecData = m_ecAudioPackets.begin() + std::max(0, static_cast<int>(m_ecAudioPackets.size()) - m_extraEcLevel); |
| 1313 | ecData != m_ecAudioPackets.end(); ++ecData) |
| 1314 | { |
| 1315 | pkt.WriteUInt8(static_cast<std::uint8_t>(ecData->Length())); |
| 1316 | pkt.WriteBytes(*ecData); |
| 1317 | } |
| 1318 |
| 1319 | std::size_t pktLength = pkt.GetLength(); |
| 1320 | PendingOutgoingPacket p |
| 1321 | { |
| 1322 | GenerateOutSeq(), |
| 1323 | PktType::STREAM_EC, |
| 1324 | pktLength, |
| 1325 | Buffer(std::move(pkt)), |
| 1326 | 0 |
| 1327 | }; |
| 1328 | SendOrEnqueuePacket(std::move(p)); |
| 1329 | } |
| 1330 |
| 1331 | m_audioTimestampOut += m_outgoingStreams[0]->frameDuration; |
| 1332 | }); |
| 1333 |
| 1334 | #if defined(TGVOIP_USE_CALLBACK_AUDIO_IO) |
| 1335 | if (m_audioPreprocDataCallback && m_preprocDecoder) |
| 1336 | { |
| 1337 | int size = opus_decode(m_preprocDecoder, data, len, m_preprocBuffer, 4096, 0); |
| 1338 | m_audioPreprocDataCallback(m_preprocBuffer, size); |
| 1339 | } |
| 1340 | #endif |
| 1341 | } |
| 1342 |
| 1343 | void VoIPController::InitializeAudio() |
| 1344 | { |
| 1345 | double t = GetCurrentTime(); |
| 1346 | std::shared_ptr<Stream> outgoingAudioStream = GetStreamByType(StreamType::AUDIO, true); |
| 1347 | LOGI("before create audio io"); |
| 1348 | m_audioIO = audio::AudioIO::Create(m_currentAudioInput, m_currentAudioOutput); |
| 1349 | m_audioInput = m_audioIO->GetInput(); |
| 1350 | m_audioOutput = m_audioIO->GetOutput(); |
| 1351 | #ifdef __ANDROID__ |
| 1352 | audio::AudioInputAndroid* androidInput = dynamic_cast<audio::AudioInputAndroid*>(m_audioInput); |
| 1353 | if (androidInput) |
| 1354 | { |
| 1355 | unsigned int effects = androidInput->GetEnabledEffects(); |
| 1356 | if (!(effects & audio::AudioInputAndroid::EFFECT_AEC)) |
| 1357 | { |
| 1358 | m_config.enableAEC = true; |
| 1359 | LOGI("Forcing software AEC because built-in is not good"); |
| 1360 | } |
| 1361 | if (!(effects & audio::AudioInputAndroid::EFFECT_NS)) |
| 1362 | { |
| 1363 | m_config.enableNS = true; |
| 1364 | LOGI("Forcing software NS because built-in is not good"); |
| 1365 | } |
| 1366 | } |
| 1367 | #elif defined(__APPLE__) && TARGET_OS_OSX |
| 1368 | SetAudioOutputDuckingEnabled(macAudioDuckingEnabled); |
| 1369 | #endif |
| 1370 | LOGI("AEC: %d NS: %d AGC: %d", m_config.enableAEC, m_config.enableNS, m_config.enableAGC); |
| 1371 | m_echoCanceller = new EchoCanceller(m_config.enableAEC, m_config.enableNS, m_config.enableAGC); |
| 1372 | m_encoder = new OpusEncoder(m_audioInput, true); |
| 1373 | m_encoder->SetCallback(std::bind(&VoIPController::HandleAudioInput, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4)); |
| 1374 | m_encoder->SetOutputFrameDuration(outgoingAudioStream->frameDuration); |
| 1375 | m_encoder->SetEchoCanceller(m_echoCanceller); |
| 1376 | m_encoder->SetSecondaryEncoderEnabled(false); |
| 1377 | if (m_config.enableVolumeControl) |
| 1378 | { |
| 1379 | m_encoder->AddAudioEffect(&m_inputVolume); |
| 1380 | } |
| 1381 |
| 1382 | #if defined(TGVOIP_USE_CALLBACK_AUDIO_IO) |
| 1383 | dynamic_cast<audio::AudioInputCallback*>(m_audioInput)->SetDataCallback(m_audioInputDataCallback); |
| 1384 | dynamic_cast<audio::AudioOutputCallback*>(m_audioOutput)->SetDataCallback(m_audioOutputDataCallback); |
| 1385 | #endif |
| 1386 |
| 1387 | if (!m_audioOutput->IsInitialized()) |
| 1388 | { |
| 1389 | LOGE("Error initializing audio playback"); |
| 1390 | m_lastError = Error::AUDIO_IO; |
| 1391 |
| 1392 | SetState(State::FAILED); |
| 1393 | return; |
| 1394 | } |
| 1395 | UpdateAudioBitrateLimit(); |
| 1396 | LOGI("Audio initialization took %f seconds", GetCurrentTime() - t); |
| 1397 | } |
| 1398 |
| 1399 | void VoIPController::StartAudio() |
| 1400 | { |
| 1401 | OnAudioOutputReady(); |
| 1402 |
| 1403 | m_encoder->Start(); |
| 1404 | if (!m_micMuted) |
| 1405 | { |
| 1406 | m_audioInput->Start(); |
| 1407 | if (!m_audioInput->IsInitialized()) |
| 1408 | { |
| 1409 | LOGE("Error initializing audio capture"); |
| 1410 | m_lastError = Error::AUDIO_IO; |
| 1411 |
| 1412 | SetState(State::FAILED); |
| 1413 | return; |
| 1414 | } |
| 1415 | } |
| 1416 | } |
| 1417 |
| 1418 | void VoIPController::OnAudioOutputReady() |
| 1419 | { |
| 1420 | LOGI("Audio I/O ready"); |
| 1421 | std::shared_ptr<Stream>& stream = m_incomingStreams[0]; |
| 1422 | stream->decoder = std::make_shared<OpusDecoder>(m_audioOutput, true, m_peerVersion >= 6); |
| 1423 | stream->decoder->SetEchoCanceller(m_echoCanceller); |
| 1424 | if (m_config.enableVolumeControl) |
| 1425 | { |
| 1426 | stream->decoder->AddAudioEffect(&m_outputVolume); |
| 1427 | } |
| 1428 | stream->decoder->SetJitterBuffer(stream->jitterBuffer); |
| 1429 | stream->decoder->SetFrameDuration(stream->frameDuration); |
| 1430 | stream->decoder->Start(); |
| 1431 | } |
| 1432 |
| 1433 | void VoIPController::UpdateAudioOutputState() |
| 1434 | { |
| 1435 | bool areAnyAudioStreamsEnabled = false; |
| 1436 | for (const std::shared_ptr<Stream>& stream : m_incomingStreams) |
| 1437 | { |
| 1438 | if (stream->type == StreamType::AUDIO && stream->enabled) |
| 1439 | { |
| 1440 | areAnyAudioStreamsEnabled = true; |
| 1441 | break; |
| 1442 | } |
| 1443 | } |
| 1444 |
| 1445 | if (m_audioOutput != nullptr) |
| 1446 | { |
| 1447 | LOGV("New audio output state: %d", areAnyAudioStreamsEnabled); |
| 1448 | if (m_audioOutput->IsPlaying() != areAnyAudioStreamsEnabled) |
| 1449 | { |
| 1450 | if (areAnyAudioStreamsEnabled) |
| 1451 | m_audioOutput->Start(); |
| 1452 | else |
| 1453 | m_audioOutput->Stop(); |
| 1454 | } |
| 1455 | } |
| 1456 | } |
| 1457 |
| 1458 | #pragma mark - Bandwidth management |
| 1459 |
| 1460 | void VoIPController::UpdateAudioBitrateLimit() |
| 1461 | { |
| 1462 | if (m_encoder != nullptr) |
| 1463 | { |
| 1464 | if (m_dataSavingMode || m_dataSavingRequestedByPeer) |
| 1465 | { |
| 1466 | m_maxBitrate = m_maxAudioBitrateSaving; |
| 1467 | m_encoder->SetBitrate(m_initAudioBitrateSaving); |
| 1468 | } |
| 1469 | else if (m_networkType == NetType::GPRS) |
| 1470 | { |
| 1471 | m_maxBitrate = m_maxAudioBitrateGPRS; |
| 1472 | m_encoder->SetBitrate(m_initAudioBitrateGPRS); |
| 1473 | } |
| 1474 | else if (m_networkType == NetType::EDGE) |
| 1475 | { |
| 1476 | m_maxBitrate = m_maxAudioBitrateEDGE; |
| 1477 | m_encoder->SetBitrate(m_initAudioBitrateEDGE); |
| 1478 | } |
| 1479 | else |
| 1480 | { |
| 1481 | m_maxBitrate = m_maxAudioBitrate; |
| 1482 | m_encoder->SetBitrate(m_initAudioBitrate); |
| 1483 | } |
| 1484 | m_encoder->SetVadMode(m_dataSavingMode || m_dataSavingRequestedByPeer); |
| 1485 | if (m_echoCanceller != nullptr) |
| 1486 | m_echoCanceller->SetVoiceDetectionEnabled(m_dataSavingMode || m_dataSavingRequestedByPeer); |
| 1487 | } |
| 1488 | } |
| 1489 |
| 1490 | void VoIPController::UpdateDataSavingState() |
| 1491 | { |
| 1492 | if (m_config.dataSaving == DataSaving::ALWAYS) |
| 1493 | { |
| 1494 | m_dataSavingMode = true; |
| 1495 | } |
| 1496 | else if (m_config.dataSaving == DataSaving::MOBILE) |
| 1497 | { |
| 1498 | m_dataSavingMode = m_networkType == NetType::GPRS || m_networkType == NetType::EDGE || m_networkType == NetType::THREE_G || m_networkType == NetType::HSPA || m_networkType == NetType::LTE || m_networkType == NetType::OTHER_MOBILE; |
| 1499 | } |
| 1500 | else |
| 1501 | { |
| 1502 | m_dataSavingMode = false; |
| 1503 | } |
| 1504 | LOGI("update data saving mode, config %d, enabled %d, reqd by peer %d", static_cast<int>(m_config.dataSaving), m_dataSavingMode, m_dataSavingRequestedByPeer); |
| 1505 | } |
| 1506 |
| 1507 | #pragma mark - Networking & crypto |
| 1508 |
| 1509 | std::uint32_t VoIPController::GenerateOutSeq() |
| 1510 | { |
| 1511 | return m_seq++; |
| 1512 | } |
| 1513 |
| 1514 | void VoIPController::WritePacketHeader(std::uint32_t pseq, BufferOutputStream* s, PktType type, std::uint32_t length, PacketSender* source) |
| 1515 | { |
| 1516 | std::uint32_t acks = 0; |
| 1517 | for (int i = 0; i < 32; ++i) |
| 1518 | { |
| 1519 | if (std::find(m_recentIncomingPackets.begin(), m_recentIncomingPackets.end(), m_lastRemoteSeq - static_cast<std::uint32_t>(i + 1)) != m_recentIncomingPackets.end()) |
| 1520 | { |
| 1521 | acks |= (1 << (31 - i)); |
| 1522 | } |
| 1523 | } |
| 1524 |
| 1525 | if (m_peerVersion >= 8 || (m_peerVersion == 0 && m_connectionMaxLayer >= 92)) |
| 1526 | { |
| 1527 | s->WriteUInt8(static_cast<std::uint8_t>(type)); |
| 1528 | s->WriteUInt32(m_lastRemoteSeq); |
| 1529 | s->WriteUInt32(pseq); |
| 1530 | s->WriteUInt32(acks); |
| 1531 | std::uint8_t flags; |
| 1532 | if (m_currentExtras.empty()) |
| 1533 | { |
| 1534 | flags = 0; |
| 1535 | } |
| 1536 | else |
| 1537 | { |
| 1538 | flags = XPFLAG_HAS_EXTRA; |
| 1539 | } |
| 1540 |
| 1541 | std::shared_ptr<Stream> videoStream = GetStreamByType(StreamType::VIDEO, false); |
| 1542 | if (m_peerVersion >= 9 && videoStream != nullptr && videoStream->enabled) |
| 1543 | flags |= XPFLAG_HAS_RECV_TS; |
| 1544 |
| 1545 | s->WriteUInt8(flags); |
| 1546 |
| 1547 | if (!m_currentExtras.empty()) |
| 1548 | { |
| 1549 | s->WriteUInt8(static_cast<std::uint8_t>(m_currentExtras.size())); |
| 1550 | for (UnacknowledgedExtraData& x : m_currentExtras) |
| 1551 | { |
| 1552 | LOGV("Writing extra into header: type %u, length %d", static_cast<std::uint8_t>(x.type), static_cast<int>(x.data.Length())); |
| 1553 | assert(x.data.Length() <= 254); |
| 1554 | s->WriteUInt8(static_cast<std::uint8_t>(x.data.Length() + 1)); |
| 1555 | s->WriteUInt8(static_cast<std::uint8_t>(x.type)); |
| 1556 | s->WriteBytes(*x.data, x.data.Length()); |
| 1557 | if (x.firstContainingSeq == 0) |
| 1558 | x.firstContainingSeq = pseq; |
| 1559 | } |
| 1560 | } |
| 1561 | if (m_peerVersion >= 9 && videoStream != nullptr && videoStream->enabled) |
| 1562 | { |
| 1563 | s->WriteUInt32(static_cast<std::uint32_t>((m_lastRecvPacketTime - m_connectionInitTime) * 1000)); |
| 1564 | } |
| 1565 | } |
| 1566 | else |
| 1567 | { |
| 1568 | if (m_state == State::WAIT_INIT || m_state == State::WAIT_INIT_ACK) |
| 1569 | { |
| 1570 | s->WriteUInt32(TLID_DECRYPTED_AUDIO_BLOCK); |
| 1571 | std::int64_t randomID; |
| 1572 | crypto.rand_bytes(reinterpret_cast<std::uint8_t*>(&randomID), 8); |
| 1573 | s->WriteInt64(randomID); |
| 1574 | std::uint8_t randBytes[7]; |
| 1575 | crypto.rand_bytes(randBytes, 7); |
| 1576 | s->WriteUInt8(7); |
| 1577 | s->WriteBytes(randBytes, 7); |
| 1578 | std::uint32_t pflags = PFLAG_HAS_RECENT_RECV | PFLAG_HAS_SEQ; |
| 1579 | if (length > 0) |
| 1580 | { |
| 1581 | pflags |= PFLAG_HAS_DATA; |
| 1582 | } |
| 1583 | if (m_state == State::WAIT_INIT || m_state == State::WAIT_INIT_ACK) |
| 1584 | { |
| 1585 | pflags |= PFLAG_HAS_CALL_ID | PFLAG_HAS_PROTO; |
| 1586 | } |
| 1587 | pflags |= (static_cast<std::uint32_t>(type)) << 24; |
| 1588 | s->WriteUInt32(pflags); |
| 1589 |
| 1590 | if (pflags & PFLAG_HAS_CALL_ID) |
| 1591 | { |
| 1592 | s->WriteBytes(m_callID, 16); |
| 1593 | } |
| 1594 | s->WriteUInt32(m_lastRemoteSeq); |
| 1595 | s->WriteUInt32(pseq); |
| 1596 | s->WriteUInt32(acks); |
| 1597 | if (pflags & PFLAG_HAS_PROTO) |
| 1598 | { |
| 1599 | s->WriteInt32(PROTOCOL_NAME); |
| 1600 | } |
| 1601 | if (length > 0) |
| 1602 | { |
| 1603 | if (length <= 253) |
| 1604 | { |
| 1605 | s->WriteUInt8(static_cast<std::uint8_t>(length)); |
| 1606 | } |
| 1607 | else |
| 1608 | { |
| 1609 | s->WriteUInt8(254); |
| 1610 | s->WriteUInt8(static_cast<std::uint8_t>((length >> 0) & 0xFF)); |
| 1611 | s->WriteUInt8(static_cast<std::uint8_t>((length >> 8) & 0xFF)); |
| 1612 | s->WriteUInt8(static_cast<std::uint8_t>((length >> 16) & 0xFF)); |
| 1613 | } |
| 1614 | } |
| 1615 | } |
| 1616 | else |
| 1617 | { |
| 1618 | s->WriteUInt32(TLID_SIMPLE_AUDIO_BLOCK); |
| 1619 | std::int64_t randomID; |
| 1620 | crypto.rand_bytes(reinterpret_cast<std::uint8_t*>(&randomID), 8); |
| 1621 | s->WriteInt64(randomID); |
| 1622 | std::uint8_t randBytes[7]; |
| 1623 | crypto.rand_bytes(randBytes, 7); |
| 1624 | s->WriteUInt8(7); |
| 1625 | s->WriteBytes(randBytes, 7); |
| 1626 | std::uint32_t lenWithHeader = length + 13; |
| 1627 | if (lenWithHeader > 0) |
| 1628 | { |
| 1629 | if (lenWithHeader <= 253) |
| 1630 | { |
| 1631 | s->WriteUInt8(static_cast<std::uint8_t>(lenWithHeader)); |
| 1632 | } |
| 1633 | else |
| 1634 | { |
| 1635 | s->WriteUInt8(std::uint8_t{254}); |
| 1636 | s->WriteUInt8(static_cast<std::uint8_t>((lenWithHeader >> 0) & 0xFF)); |
| 1637 | s->WriteUInt8(static_cast<std::uint8_t>((lenWithHeader >> 8) & 0xFF)); |
| 1638 | s->WriteUInt8(static_cast<std::uint8_t>((lenWithHeader >> 16) & 0xFF)); |
| 1639 | } |
| 1640 | } |
| 1641 | s->WriteUInt8(static_cast<std::uint8_t>(type)); |
| 1642 | s->WriteUInt32(m_lastRemoteSeq); |
| 1643 | s->WriteUInt32(pseq); |
| 1644 | s->WriteUInt32(acks); |
| 1645 | if (m_peerVersion >= 6) |
| 1646 | { |
| 1647 | if (m_currentExtras.empty()) |
| 1648 | { |
| 1649 | s->WriteUInt8(0); |
| 1650 | } |
| 1651 | else |
| 1652 | { |
| 1653 | s->WriteUInt8(XPFLAG_HAS_EXTRA); |
| 1654 | s->WriteUInt8(static_cast<std::uint8_t>(m_currentExtras.size())); |
| 1655 | for (UnacknowledgedExtraData& x : m_currentExtras) |
| 1656 | { |
| 1657 | LOGV("Writing extra into header: type %u, length %d", static_cast<std::uint8_t>(x.type), static_cast<int>(x.data.Length())); |
| 1658 | assert(x.data.Length() <= 254); |
| 1659 | s->WriteUInt8(static_cast<std::uint8_t>(x.data.Length() + 1)); |
| 1660 | s->WriteUInt8(static_cast<std::uint8_t>(x.type)); |
| 1661 | s->WriteBytes(*x.data, x.data.Length()); |
| 1662 | if (x.firstContainingSeq == 0) |
| 1663 | x.firstContainingSeq = pseq; |
| 1664 | } |
| 1665 | } |
| 1666 | } |
| 1667 | } |
| 1668 | } |
| 1669 |
| 1670 | m_unacknowledgedIncomingPacketCount = 0; |
| 1671 | m_recentOutgoingPackets.emplace_back(RecentOutgoingPacket |
| 1672 | { |
| 1673 | pseq, |
| 1674 | 0, |
| 1675 | GetCurrentTime(), |
| 1676 | 0.0, |
| 1677 | type, |
| 1678 | length, |
| 1679 | source, |
| 1680 | false |
| 1681 | }); |
| 1682 | while (m_recentOutgoingPackets.size() > MAX_RECENT_PACKETS) |
| 1683 | { |
| 1684 | m_recentOutgoingPackets.pop_front(); |
| 1685 | } |
| 1686 | m_lastSentSeq = pseq; |
| 1687 | } |
| 1688 |
| 1689 | void VoIPController::SendInit() |
| 1690 | { |
| 1691 | ENFORCE_MSG_THREAD; |
| 1692 |
| 1693 | std::uint32_t initSeq = GenerateOutSeq(); |
| 1694 | for (auto& [_, endpoint] : m_endpoints) |
| 1695 | { |
| 1696 | if (endpoint.type == Endpoint::Type::TCP_RELAY && !m_useTCP) |
| 1697 | continue; |
| 1698 | BufferOutputStream out(1024); |
| 1699 | out.WriteInt32(PROTOCOL_VERSION); |
| 1700 | out.WriteInt32(MIN_PROTOCOL_VERSION); |
| 1701 | std::uint32_t flags = 0; |
| 1702 | if (m_config.enableCallUpgrade) |
| 1703 | flags |= INIT_FLAG_GROUP_CALLS_SUPPORTED; |
| 1704 | if (m_config.enableVideoReceive) |
| 1705 | flags |= INIT_FLAG_VIDEO_RECV_SUPPORTED; |
| 1706 | if (m_config.enableVideoSend) |
| 1707 | flags |= INIT_FLAG_VIDEO_SEND_SUPPORTED; |
| 1708 | if (m_dataSavingMode) |
| 1709 | flags |= INIT_FLAG_DATA_SAVING_ENABLED; |
| 1710 | out.WriteUInt32(flags); |
| 1711 | if (m_connectionMaxLayer < 74) |
| 1712 | { |
| 1713 | out.WriteUInt8(2); // audio codecs count |
| 1714 | out.WriteUInt8(CODEC_OPUS_OLD); |
| 1715 | out.WriteUInt8(0); |
| 1716 | out.WriteUInt8(0); |
| 1717 | out.WriteUInt8(0); |
| 1718 | out.WriteInt32(CODEC_OPUS); |
| 1719 | out.WriteUInt8(0); // video codecs count (decode) |
| 1720 | out.WriteUInt8(0); // video codecs count (encode) |
| 1721 | } |
| 1722 | else |
| 1723 | { |
| 1724 | out.WriteUInt8(std::uint8_t{1}); |
| 1725 | out.WriteInt32(CODEC_OPUS); |
| 1726 | std::vector<std::uint32_t> decoders = m_config.enableVideoReceive ? video::VideoRenderer::GetAvailableDecoders() : std::vector<std::uint32_t>(); |
| 1727 | std::vector<std::uint32_t> encoders = m_config.enableVideoSend ? video::VideoSource::GetAvailableEncoders() : std::vector<std::uint32_t>(); |
| 1728 | out.WriteUInt8(static_cast<std::uint8_t>(decoders.size())); |
| 1729 | for (std::uint32_t id : decoders) |
| 1730 | { |
| 1731 | out.WriteUInt32(id); |
| 1732 | } |
| 1733 | if (m_connectionMaxLayer >= 92) |
| 1734 | out.WriteUInt8(static_cast<std::uint8_t>(video::VideoRenderer::GetMaximumResolution())); |
| 1735 | else |
| 1736 | out.WriteUInt8(std::uint8_t{0}); |
| 1737 | } |
| 1738 | std::size_t outLength = out.GetLength(); |
| 1739 | SendOrEnqueuePacket(PendingOutgoingPacket |
| 1740 | { |
| 1741 | /*.seq=*/ initSeq, |
| 1742 | /*.type=*/ PktType::INIT, |
| 1743 | /*.len=*/ outLength, |
| 1744 | /*.data=*/ Buffer(std::move(out)), |
| 1745 | /*.endpoint=*/endpoint.id |
| 1746 | }); |
| 1747 | } |
| 1748 |
| 1749 | if (m_state == State::WAIT_INIT) |
| 1750 | SetState(State::WAIT_INIT_ACK); |
| 1751 | m_messageThread.Post([this] |
| 1752 | { |
| 1753 | if (m_state == State::WAIT_INIT_ACK) |
| 1754 | { |
| 1755 | SendInit(); |
| 1756 | } |
| 1757 | }, |
| 1758 | 0.5); |
| 1759 | } |
| 1760 |
| 1761 | void VoIPController::InitUDPProxy() |
| 1762 | { |
| 1763 | if (m_realUdpSocket != m_udpSocket) |
| 1764 | { |
| 1765 | m_udpSocket->Close(); |
| 1766 | delete m_udpSocket; |
| 1767 | m_udpSocket = m_realUdpSocket; |
| 1768 | } |
| 1769 | char sbuf[128]; |
| 1770 | std::snprintf(sbuf, sizeof(sbuf), "%s:%u", m_proxyAddress.c_str(), m_proxyPort); |
| 1771 | std::string proxyHostPort(sbuf); |
| 1772 | if (proxyHostPort == m_lastTestedProxyServer && !m_proxySupportsUDP) |
| 1773 | { |
| 1774 | LOGI("Proxy does not support UDP - using UDP directly instead"); |
| 1775 | m_messageThread.Post(std::bind(&VoIPController::ResetUdpAvailability, this)); |
| 1776 | return; |
| 1777 | } |
| 1778 |
| 1779 | NetworkSocket* tcp = NetworkSocket::Create(NetworkProtocol::TCP); |
| 1780 | tcp->Connect(m_resolvedProxyAddress, m_proxyPort); |
| 1781 |
| 1782 | std::list<NetworkSocket*> writeSockets; |
| 1783 | std::list<NetworkSocket*> readSockets; |
| 1784 | std::list<NetworkSocket*> errorSockets; |
| 1785 |
| 1786 | while (!tcp->IsFailed() && !tcp->IsReadyToSend()) |
| 1787 | { |
| 1788 | writeSockets.emplace_back(tcp); |
| 1789 | if (!NetworkSocket::Select(readSockets, writeSockets, errorSockets, m_selectCanceller)) |
| 1790 | { |
| 1791 | LOGW("Select canceled while waiting for proxy control socket to connect"); |
| 1792 | delete tcp; |
| 1793 | return; |
| 1794 | } |
| 1795 | } |
| 1796 | LOGV("UDP proxy control socket ready to send"); |
| 1797 | NetworkSocketSOCKS5Proxy* udpProxy = new NetworkSocketSOCKS5Proxy(tcp, m_realUdpSocket, m_proxyUsername, m_proxyPassword); |
| 1798 | udpProxy->OnReadyToSend(); |
| 1799 | writeSockets.clear(); |
| 1800 | while (!udpProxy->IsFailed() && !tcp->IsFailed() && !udpProxy->IsReadyToSend()) |
| 1801 | { |
| 1802 | readSockets.clear(); |
| 1803 | errorSockets.clear(); |
| 1804 | readSockets.emplace_back(tcp); |
| 1805 | errorSockets.emplace_back(tcp); |
| 1806 | if (!NetworkSocket::Select(readSockets, writeSockets, errorSockets, m_selectCanceller)) |
| 1807 | { |
| 1808 | LOGW("Select canceled while waiting for UDP proxy to initialize"); |
| 1809 | delete udpProxy; |
| 1810 | return; |
| 1811 | } |
| 1812 | if (!readSockets.empty()) |
| 1813 | udpProxy->OnReadyToReceive(); |
| 1814 | } |
| 1815 | LOGV("UDP proxy initialized"); |
| 1816 |
| 1817 | if (udpProxy->IsFailed()) |
| 1818 | { |
| 1819 | udpProxy->Close(); |
| 1820 | delete udpProxy; |
| 1821 | m_proxySupportsUDP = false; |
| 1822 | } |
| 1823 | else |
| 1824 | { |
| 1825 | m_udpSocket = udpProxy; |
| 1826 | } |
| 1827 | m_messageThread.Post(std::bind(&VoIPController::ResetUdpAvailability, this)); |
| 1828 | } |
| 1829 |
| 1830 | void VoIPController::RunRecvThread() |
| 1831 | { |
| 1832 | LOGI("Receive thread starting"); |
| 1833 | if (m_proxyProtocol == Proxy::SOCKS5) |
| 1834 | { |
| 1835 | m_resolvedProxyAddress = NetworkSocket::ResolveDomainName(m_proxyAddress); |
| 1836 | if (m_resolvedProxyAddress.IsEmpty()) |
| 1837 | { |
| 1838 | LOGW("Error resolving proxy address %s", m_proxyAddress.c_str()); |
| 1839 | SetState(State::FAILED); |
| 1840 | return; |
| 1841 | } |
| 1842 | } |
| 1843 | else |
| 1844 | { |
| 1845 | m_udpConnectivityState = UdpState::PING_PENDING; |
| 1846 | m_udpPingTimeoutID = m_messageThread.Post(std::bind(&VoIPController::SendUdpPings, this), 0.0, 0.5); |
| 1847 | } |
| 1848 | while (m_runReceiver) |
| 1849 | { |
| 1850 | if (m_proxyProtocol == Proxy::SOCKS5 && m_needReInitUdpProxy) |
| 1851 | { |
| 1852 | InitUDPProxy(); |
| 1853 | m_needReInitUdpProxy = false; |
| 1854 | } |
| 1855 |
| 1856 | std::list<NetworkSocket*> readSockets; |
| 1857 | std::list<NetworkSocket*> errorSockets; |
| 1858 | std::list<NetworkSocket*> writeSockets; |
| 1859 | readSockets.emplace_back(m_udpSocket); |
| 1860 | errorSockets.emplace_back(m_realUdpSocket); |
| 1861 | if (!m_realUdpSocket->IsReadyToSend()) |
| 1862 | writeSockets.emplace_back(m_realUdpSocket); |
| 1863 |
| 1864 | { |
| 1865 | MutexGuard m(m_endpointsMutex); |
| 1866 | for (const auto& [_, endpoint] : m_endpoints) |
| 1867 | { |
| 1868 | if (endpoint.type == Endpoint::Type::TCP_RELAY) |
| 1869 | { |
| 1870 | if (endpoint.m_socket != nullptr) |
| 1871 | { |
| 1872 | readSockets.emplace_back(endpoint.m_socket.get()); |
| 1873 | errorSockets.emplace_back(endpoint.m_socket.get()); |
| 1874 | if (!endpoint.m_socket->IsReadyToSend()) |
| 1875 | { |
| 1876 | NetworkSocketSOCKS5Proxy* proxy = dynamic_cast<NetworkSocketSOCKS5Proxy*>(endpoint.m_socket.get()); |
| 1877 | if (proxy == nullptr || proxy->NeedSelectForSending()) |
| 1878 | writeSockets.emplace_back(endpoint.m_socket.get()); |
| 1879 | } |
| 1880 | } |
| 1881 | } |
| 1882 | } |
| 1883 | } |
| 1884 |
| 1885 | { |
| 1886 | bool selRes = NetworkSocket::Select(readSockets, writeSockets, errorSockets, m_selectCanceller); |
| 1887 | if (!selRes) |
| 1888 | { |
| 1889 | LOGV("Select canceled"); |
| 1890 | continue; |
| 1891 | } |
| 1892 | } |
| 1893 | if (!m_runReceiver) |
| 1894 | return; |
| 1895 |
| 1896 | if (!errorSockets.empty()) |
| 1897 | { |
| 1898 | if (std::find(errorSockets.begin(), errorSockets.end(), m_realUdpSocket) != errorSockets.end()) |
| 1899 | { |
| 1900 | LOGW("UDP socket failed"); |
| 1901 | SetState(State::FAILED); |
| 1902 | return; |
| 1903 | } |
| 1904 | MutexGuard m(m_endpointsMutex); |
| 1905 | for (NetworkSocket*& socket : errorSockets) |
| 1906 | { |
| 1907 | for (auto& [_, endpoint] : m_endpoints) |
| 1908 | { |
| 1909 | if (endpoint.m_socket != nullptr && endpoint.m_socket.get() == socket) |
| 1910 | { |
| 1911 | endpoint.m_socket->Close(); |
| 1912 | endpoint.m_socket.reset(); |
| 1913 | LOGI("Closing failed TCP socket for %s:%u", endpoint.GetAddress().ToString().c_str(), endpoint.port); |
| 1914 | } |
| 1915 | } |
| 1916 | } |
| 1917 | continue; |
| 1918 | } |
| 1919 |
| 1920 | for (NetworkSocket*& socket : readSockets) |
| 1921 | { |
| 1922 | NetworkPacket packet = socket->Receive(0); |
| 1923 | if (packet.address.IsEmpty()) |
| 1924 | { |
| 1925 | LOGE("Packet has null address. This shouldn't happen."); |
| 1926 | continue; |
| 1927 | } |
| 1928 | if (packet.data.IsEmpty()) |
| 1929 | { |
| 1930 | LOGE("Packet has zero length."); |
| 1931 | continue; |
| 1932 | } |
| 1933 | m_messageThread.Post(bind(&VoIPController::NetworkPacketReceived, this, std::make_shared<NetworkPacket>(std::move(packet)))); |
| 1934 | } |
| 1935 |
| 1936 | if (!writeSockets.empty()) |
| 1937 | { |
| 1938 | m_messageThread.Post(std::bind(&VoIPController::TrySendQueuedPackets, this)); |
| 1939 | } |
| 1940 | } |
| 1941 | LOGI("=== recv thread exiting ==="); |
| 1942 | } |
| 1943 |
| 1944 | void VoIPController::TrySendQueuedPackets() |
| 1945 | { |
| 1946 | ENFORCE_MSG_THREAD; |
| 1947 |
| 1948 | for (auto opkt = m_sendQueue.begin(); opkt != m_sendQueue.end();) |
| 1949 | { |
| 1950 | Endpoint* endpoint = GetEndpointForPacket(*opkt); |
| 1951 | if (endpoint == nullptr) |
| 1952 | { |
| 1953 | opkt = m_sendQueue.erase(opkt); |
| 1954 | LOGE("SendQueue contained packet for nonexistent endpoint"); |
| 1955 | continue; |
| 1956 | } |
| 1957 | bool canSend; |
| 1958 | if (endpoint->type != Endpoint::Type::TCP_RELAY) |
| 1959 | canSend = m_realUdpSocket->IsReadyToSend(); |
| 1960 | else |
| 1961 | canSend = endpoint->m_socket && endpoint->m_socket->IsReadyToSend(); |
| 1962 | if (canSend) |
| 1963 | { |
| 1964 | LOGI("Sending queued packet"); |
| 1965 | SendOrEnqueuePacket(std::move(*opkt), false); |
| 1966 | opkt = m_sendQueue.erase(opkt); |
| 1967 | } |
| 1968 | else |
| 1969 | { |
| 1970 | ++opkt; |
| 1971 | } |
| 1972 | } |
| 1973 | } |
| 1974 |
| 1975 | bool VoIPController::WasOutgoingPacketAcknowledged(std::uint32_t seq) |
| 1976 | { |
| 1977 | RecentOutgoingPacket* pkt = GetRecentOutgoingPacket(seq); |
| 1978 | if (pkt == nullptr) |
| 1979 | return false; |
| 1980 | return pkt->ackTime != 0.0; |
| 1981 | } |
| 1982 |
| 1983 | VoIPController::RecentOutgoingPacket* VoIPController::GetRecentOutgoingPacket(std::uint32_t seq) |
| 1984 | { |
| 1985 | for (RecentOutgoingPacket& opkt : m_recentOutgoingPackets) |
| 1986 | { |
| 1987 | if (opkt.seq == seq) |
| 1988 | { |
| 1989 | return &opkt; |
| 1990 | } |
| 1991 | } |
| 1992 | return nullptr; |
| 1993 | } |
| 1994 |
| 1995 | void VoIPController::NetworkPacketReceived(std::shared_ptr<NetworkPacket> _packet) |
| 1996 | { |
| 1997 | ENFORCE_MSG_THREAD; |
| 1998 |
| 1999 | NetworkPacket& packet = *_packet; |
| 2000 |
| 2001 | std::int64_t srcEndpointID = 0; |
| 2002 |
| 2003 | if (!packet.address.isIPv6) |
| 2004 | { |
| 2005 | for (const auto& [_, endpoint] : m_endpoints) |
| 2006 | { |
| 2007 | if (endpoint.address == packet.address && endpoint.port == packet.port) |
| 2008 | { |
| 2009 | if ((endpoint.type != Endpoint::Type::TCP_RELAY && packet.protocol == NetworkProtocol::UDP) || |
| 2010 | (endpoint.type == Endpoint::Type::TCP_RELAY && packet.protocol == NetworkProtocol::TCP)) |
| 2011 | { |
| 2012 | srcEndpointID = endpoint.id; |
| 2013 | break; |
| 2014 | } |
| 2015 | } |
| 2016 | } |
| 2017 | if (srcEndpointID == 0 && packet.protocol == NetworkProtocol::UDP) |
| 2018 | { |
| 2019 | try |
| 2020 | { |
| 2021 | Endpoint& p2p = GetEndpointByType(Endpoint::Type::UDP_P2P_INET); |
| 2022 | if (p2p.m_rtts[0] == 0.0 && p2p.address.PrefixMatches(24, packet.address)) |
| 2023 | { |
| 2024 | LOGD("Packet source matches p2p endpoint partially: %s:%u", packet.address.ToString().c_str(), packet.port); |
| 2025 | srcEndpointID = p2p.id; |
| 2026 | } |
| 2027 | } |
| 2028 | catch (const std::out_of_range& exception) |
| 2029 | { |
| 2030 | LOGW("No endpoint with type UDP_P2P_INET\nwhat():\n%s", exception.what()); |
| 2031 | } |
| 2032 | } |
| 2033 | } |
| 2034 | else |
| 2035 | { |
| 2036 | for (const auto& [_, endpoint] : m_endpoints) |
| 2037 | { |
| 2038 | if (endpoint.v6address == packet.address && endpoint.port == packet.port && endpoint.IsIPv6Only()) |
| 2039 | { |
| 2040 | if ((endpoint.type != Endpoint::Type::TCP_RELAY && packet.protocol == NetworkProtocol::UDP) || |
| 2041 | (endpoint.type == Endpoint::Type::TCP_RELAY && packet.protocol == NetworkProtocol::TCP)) |
| 2042 | { |
| 2043 | srcEndpointID = endpoint.id; |
| 2044 | break; |
| 2045 | } |
| 2046 | } |
| 2047 | } |
| 2048 | } |
| 2049 |
| 2050 | if (srcEndpointID == 0) |
| 2051 | { |
| 2052 | LOGW("Received a packet from unknown source %s:%u", packet.address.ToString().c_str(), packet.port); |
| 2053 | return; |
| 2054 | } |
| 2055 |
| 2056 | if (IS_MOBILE_NETWORK(m_networkType)) |
| 2057 | m_stats.bytesRecvdMobile += static_cast<std::uint64_t>(packet.data.Length()); |
| 2058 | else |
| 2059 | m_stats.bytesRecvdWifi += static_cast<std::uint64_t>(packet.data.Length()); |
| 2060 |
| 2061 | try |
| 2062 | { |
| 2063 | ProcessIncomingPacket(packet, m_endpoints.at(srcEndpointID)); |
| 2064 | } |
| 2065 | catch (const std::out_of_range& exception) |
| 2066 | { |
| 2067 | LOGW("Error while parsing packet.\nwhat():\n%s", exception.what()); |
| 2068 | } |
| 2069 | } |
| 2070 |
| 2071 | void VoIPController::ProcessRelaySpecialRequest(BufferInputStream& in, Endpoint& srcEndpoint) |
| 2072 | { |
| 2073 | in.Seek(16 + 12); |
| 2074 | std::uint32_t tlid = in.ReadUInt32(); |
| 2075 | switch (tlid) |
| 2076 | { |
| 2077 | case TLID_UDP_REFLECTOR_SELF_INFO: |
| 2078 | { |
| 2079 | if (!(srcEndpoint.type == Endpoint::Type::UDP_RELAY /*&& udpConnectivityState==Udp::PING_SENT*/ && in.Remaining() >= 32)) |
| 2080 | break; |
| 2081 | std::int32_t date = in.ReadInt32(); |
| 2082 | std::int64_t queryID = in.ReadInt64(); |
| 2083 | std::uint8_t myIP[16]; |
| 2084 | in.ReadBytes(myIP, 16); |
| 2085 | std::int16_t myPort = in.ReadInt16(); |
| 2086 | double selfRTT = 0.0; |
| 2087 | ++srcEndpoint.m_udpPongCount; |
| 2088 | ++srcEndpoint.m_totalUdpPingReplies; |
| 2089 |
| 2090 | if (srcEndpoint.m_udpPingTimes.find(queryID) != srcEndpoint.m_udpPingTimes.end()) |
| 2091 | { |
| 2092 | double sendTime = srcEndpoint.m_udpPingTimes[queryID]; |
| 2093 | srcEndpoint.m_udpPingTimes.erase(queryID); |
| 2094 | srcEndpoint.m_selfRtts.Add(selfRTT = GetCurrentTime() - sendTime); |
| 2095 | } |
| 2096 |
| 2097 | LOGV("Received UDP ping reply from %s:%d: date=%d, queryID=%ld, my IP=%s, my port=%d, selfRTT=%f", |
| 2098 | srcEndpoint.address.ToString().c_str(), |
| 2099 | srcEndpoint.port, |
| 2100 | date, |
| 2101 | static_cast<long>(queryID), |
| 2102 | NetworkAddress::IPv4(*reinterpret_cast<std::uint32_t*>(myIP + 12)).ToString().c_str(), |
| 2103 | myPort, |
| 2104 | selfRTT); |
| 2105 |
| 2106 | if (srcEndpoint.IsIPv6Only() && !m_didSendIPv6Endpoint) |
| 2107 | { |
| 2108 | NetworkAddress realAddr = NetworkAddress::IPv6(myIP); |
| 2109 | if (realAddr == m_myIPv6) |
| 2110 | { |
| 2111 | LOGI("Public IPv6 matches local address"); |
| 2112 | m_useIPv6 = true; |
| 2113 | if (m_allowP2p) |
| 2114 | { |
| 2115 | m_didSendIPv6Endpoint = true; |
| 2116 | BufferOutputStream o(18); |
| 2117 | o.WriteBytes(myIP, 16); |
| 2118 | o.WriteUInt16(m_udpSocket->GetLocalPort()); |
| 2119 | Buffer b(std::move(o)); |
| 2120 | SendExtra(b, ExtraType::IPV6_ENDPOINT); |
| 2121 | } |
| 2122 | } |
| 2123 | } |
| 2124 | break; |
| 2125 | } |
| 2126 | case TLID_UDP_REFLECTOR_PEER_INFO: |
| 2127 | { |
| 2128 | if (in.Remaining() < 16) |
| 2129 | break; |
| 2130 | std::uint32_t myAddr = in.ReadUInt32(); |
| 2131 | std::uint16_t myPort = in.ReadUInt16(); |
| 2132 | std::uint32_t peerAddr = in.ReadUInt32(); |
| 2133 | std::uint16_t peerPort = in.ReadUInt16(); |
| 2134 |
| 2135 | constexpr std::int64_t p2pID = static_cast<std::int64_t>(FOURCC('P', '2', 'P', '4')) << 32; |
| 2136 | constexpr std::int64_t lanID = static_cast<std::int64_t>(FOURCC('L', 'A', 'N', '4')) << 32; |
| 2137 |
| 2138 | if (m_currentEndpoint == p2pID || m_currentEndpoint == lanID) |
| 2139 | m_currentEndpoint = m_preferredRelay; |
| 2140 |
| 2141 | if (m_endpoints.find(lanID) != m_endpoints.end()) |
| 2142 | { |
| 2143 | MutexGuard m(m_endpointsMutex); |
| 2144 | m_endpoints.erase(lanID); |
| 2145 | } |
| 2146 |
| 2147 | std::uint8_t peerTag[16]; |
| 2148 | LOGW("Received reflector peer info, my=%s:%u, peer=%s:%u", NetworkAddress::IPv4(myAddr).ToString().c_str(), myPort, NetworkAddress::IPv4(peerAddr).ToString().c_str(), peerPort); |
| 2149 | if (m_waitingForRelayPeerInfo) |
| 2150 | { |
| 2151 | Endpoint p2p(p2pID, peerPort, NetworkAddress::IPv4(peerAddr), NetworkAddress::Empty(), Endpoint::Type::UDP_P2P_INET, peerTag); |
| 2152 | { |
| 2153 | MutexGuard m(m_endpointsMutex); |
| 2154 | m_endpoints[p2pID] = p2p; |
| 2155 | } |
| 2156 | if (myAddr == peerAddr) |
| 2157 | { |
| 2158 | LOGW("Detected LAN"); |
| 2159 | NetworkAddress lanAddr = NetworkAddress::IPv4(0); |
| 2160 | m_udpSocket->GetLocalInterfaceInfo(&lanAddr, nullptr); |
| 2161 |
| 2162 | BufferOutputStream pkt(8); |
| 2163 | pkt.WriteUInt32(lanAddr.addr.ipv4); |
| 2164 | pkt.WriteUInt16(m_udpSocket->GetLocalPort()); |
| 2165 | if (m_peerVersion < 6) |
| 2166 | { |
| 2167 | SendPacketReliably(PktType::LAN_ENDPOINT, pkt.GetBuffer(), pkt.GetLength(), 0.5, 10); |
| 2168 | } |
| 2169 | else |
| 2170 | { |
| 2171 | Buffer buf(std::move(pkt)); |
| 2172 | SendExtra(buf, ExtraType::LAN_ENDPOINT); |
| 2173 | } |
| 2174 | } |
| 2175 | m_waitingForRelayPeerInfo = false; |
| 2176 | } |
| 2177 | break; |
| 2178 | } |
| 2179 | default: |
| 2180 | { |
| 2181 | LOGV("Received relay response with unknown tl id: 0x%08X", tlid); |
| 2182 | break; |
| 2183 | } |
| 2184 | } |
| 2185 | } |
| 2186 |
| 2187 | void VoIPController::ProcessIncomingPacket(NetworkPacket& packet, Endpoint& srcEndpoint) |
| 2188 | { |
| 2189 | ENFORCE_MSG_THREAD; |
| 2190 |
| 2191 | std::uint8_t* buffer = *packet.data; |
| 2192 | std::size_t len = packet.data.Length(); |
| 2193 | BufferInputStream in(packet.data); |
| 2194 | bool hasPeerTag = false; |
| 2195 |
| 2196 | if (m_peerVersion < 9 || srcEndpoint.type == Endpoint::Type::UDP_RELAY || srcEndpoint.type == Endpoint::Type::TCP_RELAY) |
| 2197 | { |
| 2198 | if (std::memcmp(buffer, |
| 2199 | (srcEndpoint.type == Endpoint::Type::UDP_RELAY || srcEndpoint.type == Endpoint::Type::TCP_RELAY) |
| 2200 | ? reinterpret_cast<void*>(srcEndpoint.peerTag) : reinterpret_cast<void*>(m_callID), |
| 2201 | 16) != 0) |
| 2202 | { |
| 2203 | LOGW("Received packet has wrong peerTag"); |
| 2204 | return; |
| 2205 | } |
| 2206 | in.Seek(16); |
| 2207 | hasPeerTag = true; |
| 2208 | } |
| 2209 |
| 2210 | if (in.Remaining() >= 16 && (srcEndpoint.type == Endpoint::Type::UDP_RELAY || srcEndpoint.type == Endpoint::Type::TCP_RELAY) |
| 2211 | && *reinterpret_cast<const std::uint64_t*>(buffer + 16) == std::numeric_limits<std::uint64_t>::max() |
| 2212 | && *reinterpret_cast<const std::uint32_t*>(buffer + 24) == std::numeric_limits<std::uint32_t>::max()) |
| 2213 | { |
| 2214 | // relay special request response |
| 2215 | ProcessRelaySpecialRequest(in, srcEndpoint); |
| 2216 | return; |
| 2217 | } |
| 2218 |
| 2219 | if (in.Remaining() < 40) |
| 2220 | { |
| 2221 | LOGV("Received packet is too small"); |
| 2222 | return; |
| 2223 | } |
| 2224 |
| 2225 | bool retryWith2 = false; |
| 2226 | std::size_t innerLen = 0; |
| 2227 | bool shortFormat = m_peerVersion >= 8 || (m_peerVersion == 0 && m_connectionMaxLayer >= 92); |
| 2228 |
| 2229 | if (!m_useMTProto2) |
| 2230 | { |
| 2231 | std::uint8_t fingerprint[8], msgHash[16]; |
| 2232 | in.ReadBytes(fingerprint, 8); |
| 2233 | in.ReadBytes(msgHash, 16); |
| 2234 | std::uint8_t key[32], iv[32]; |
| 2235 | KDF(msgHash, m_isOutgoing ? 8 : 0, key, iv); |
| 2236 | std::vector<std::uint8_t> aesOut(MSC_STACK_FALLBACK(in.Remaining(), 1500)); |
| 2237 | if (in.Remaining() > aesOut.size()) |
| 2238 | return; |
| 2239 | crypto.aes_ige_decrypt(buffer + in.GetOffset(), aesOut.data(), in.Remaining(), key, iv); |
| 2240 | BufferInputStream _in(aesOut.data(), in.Remaining()); |
| 2241 | std::uint8_t sha[SHA1_LENGTH]; |
| 2242 | std::uint32_t _len = _in.ReadUInt32(); |
| 2243 | if (_len > _in.Remaining()) |
| 2244 | _len = static_cast<std::uint32_t>(_in.Remaining()); |
| 2245 | crypto.sha1(aesOut.data(), static_cast<std::size_t>(_len) + 4, sha); |
| 2246 | if (std::memcmp(msgHash, sha + (SHA1_LENGTH - 16), 16) != 0) |
| 2247 | { |
| 2248 | LOGW("Received packet has wrong hash after decryption"); |
| 2249 | if (m_state == State::WAIT_INIT || m_state == State::WAIT_INIT_ACK) |
| 2250 | retryWith2 = true; |
| 2251 | else |
| 2252 | return; |
| 2253 | } |
| 2254 | else |
| 2255 | { |
| 2256 | std::memcpy(buffer + in.GetOffset(), aesOut.data(), in.Remaining()); |
| 2257 | in.ReadInt32(); |
| 2258 | } |
| 2259 | } |
| 2260 |
| 2261 | if (m_useMTProto2 || retryWith2) |
| 2262 | { |
| 2263 | if (hasPeerTag) |
| 2264 | in.Seek(16); // peer tag |
| 2265 |
| 2266 | std::uint8_t fingerprint[8], msgKey[16]; |
| 2267 | if (!shortFormat) |
| 2268 | { |
| 2269 | in.ReadBytes(fingerprint, 8); |
| 2270 | if (std::memcmp(fingerprint, m_keyFingerprint, 8) != 0) |
| 2271 | { |
| 2272 | LOGW("Received packet has wrong key fingerprint"); |
| 2273 | return; |
| 2274 | } |
| 2275 | } |
| 2276 | in.ReadBytes(msgKey, 16); |
| 2277 |
| 2278 | std::uint8_t decrypted[1500]; |
| 2279 | std::uint8_t aesKey[32], aesIv[32]; |
| 2280 | KDF2(msgKey, m_isOutgoing ? 8 : 0, aesKey, aesIv); |
| 2281 | std::size_t decryptedLen = in.Remaining(); |
| 2282 | if (decryptedLen > sizeof(decrypted)) |
| 2283 | return; |
| 2284 | if (decryptedLen % 16 != 0) |
| 2285 | { |
| 2286 | LOGW("wrong decrypted length"); |
| 2287 | return; |
| 2288 | } |
| 2289 |
| 2290 | crypto.aes_ige_decrypt(*packet.data + in.GetOffset(), decrypted, decryptedLen, aesKey, aesIv); |
| 2291 |
| 2292 | in = BufferInputStream(decrypted, decryptedLen); |
| 2293 | std::size_t sizeSize = shortFormat ? 0 : 4; |
| 2294 |
| 2295 | BufferOutputStream buf(decryptedLen + 32); |
| 2296 | std::size_t x = m_isOutgoing ? 8 : 0; |
| 2297 | buf.WriteBytes(m_encryptionKey + 88 + x, 32); |
| 2298 | buf.WriteBytes(decrypted + sizeSize, decryptedLen - sizeSize); |
| 2299 | std::uint8_t msgKeyLarge[32]; |
| 2300 | crypto.sha256(buf.GetBuffer(), buf.GetLength(), msgKeyLarge); |
| 2301 |
| 2302 | if (std::memcmp(msgKey, msgKeyLarge + 8, 16) != 0) |
| 2303 | { |
| 2304 | LOGW("Received packet has wrong hash"); |
| 2305 | return; |
| 2306 | } |
| 2307 |
| 2308 | innerLen = (shortFormat ? in.ReadUInt16() : in.ReadUInt32()); |
| 2309 | if (innerLen > decryptedLen - sizeSize) |
| 2310 | { |
| 2311 | LOGW("Received packet has wrong inner length (%d with total of %u)", static_cast<int>(innerLen), static_cast<unsigned int>(decryptedLen)); |
| 2312 | return; |
| 2313 | } |
| 2314 | if (decryptedLen - innerLen < (shortFormat ? 16 : 12)) |
| 2315 | { |
| 2316 | LOGW("Received packet has too little padding (%u)", static_cast<unsigned int>(decryptedLen - innerLen)); |
| 2317 | return; |
| 2318 | } |
| 2319 | std::memcpy(buffer, decrypted + (shortFormat ? 2 : 4), innerLen); |
| 2320 | in = BufferInputStream(buffer, innerLen); |
| 2321 | if (retryWith2) |
| 2322 | { |
| 2323 | LOGD("Successfully decrypted packet in MTProto2.0 fallback, upgrading"); |
| 2324 | m_useMTProto2 = true; |
| 2325 | } |
| 2326 | } |
| 2327 |
| 2328 | m_lastRecvPacketTime = GetCurrentTime(); |
| 2329 |
| 2330 | if (m_state == State::RECONNECTING) |
| 2331 | { |
| 2332 | LOGI("Received a valid packet while reconnecting - setting state to established"); |
| 2333 | SetState(State::ESTABLISHED); |
| 2334 | } |
| 2335 |
| 2336 | if (srcEndpoint.type == Endpoint::Type::UDP_P2P_INET && !srcEndpoint.IsIPv6Only()) |
| 2337 | { |
| 2338 | if (srcEndpoint.port != packet.port || srcEndpoint.address != packet.address) |
| 2339 | { |
| 2340 | if (!packet.address.isIPv6) |
| 2341 | { |
| 2342 | LOGI("Incoming packet was decrypted successfully, changing P2P endpoint to %s:%u", packet.address.ToString().c_str(), packet.port); |
| 2343 | srcEndpoint.address = packet.address; |
| 2344 | srcEndpoint.port = packet.port; |
| 2345 | } |
| 2346 | } |
| 2347 | } |
| 2348 |
| 2349 | std::uint32_t ackId, pseq, acks; |
| 2350 | PktType type; |
| 2351 | std::uint8_t pflags; |
| 2352 | std::size_t packetInnerLen = 0; |
| 2353 | if (shortFormat) |
| 2354 | { |
| 2355 | type = static_cast<PktType>(in.ReadUInt8()); |
| 2356 | ackId = in.ReadUInt32(); |
| 2357 | pseq = in.ReadUInt32(); |
| 2358 | acks = in.ReadUInt32(); |
| 2359 | pflags = in.ReadUInt8(); |
| 2360 | packetInnerLen = innerLen - 14; |
| 2361 | } |
| 2362 | else |
| 2363 | { |
| 2364 | std::uint32_t tlid = in.ReadUInt32(); |
| 2365 | switch (tlid) |
| 2366 | { |
| 2367 | case TLID_DECRYPTED_AUDIO_BLOCK: |
| 2368 | { |
| 2369 | in.ReadInt64(); // random id |
| 2370 | std::int32_t randLen = in.ReadTlLength(); |
| 2371 | in.Seek(in.GetOffset() + static_cast<std::size_t>(randLen + pad4(randLen))); |
| 2372 | std::uint32_t flags = in.ReadUInt32(); |
| 2373 | type = static_cast<PktType>((flags >> 24) & 0xFF); |
| 2374 | if (!(flags & PFLAG_HAS_SEQ && flags & PFLAG_HAS_RECENT_RECV)) |
| 2375 | { |
| 2376 | LOGW("Received packet doesn't have PFlag::HAS_SEQ, PFlag::HAS_RECENT_RECV, or both"); |
| 2377 |
| 2378 | return; |
| 2379 | } |
| 2380 | if (flags & PFLAG_HAS_CALL_ID) |
| 2381 | { |
| 2382 | std::uint8_t pktCallID[16]; |
| 2383 | in.ReadBytes(pktCallID, 16); |
| 2384 | if (std::memcmp(pktCallID, m_callID, 16) != 0) |
| 2385 | { |
| 2386 | LOGW("Received packet has wrong call id"); |
| 2387 |
| 2388 | m_lastError = Error::UNKNOWN; |
| 2389 | SetState(State::FAILED); |
| 2390 | return; |
| 2391 | } |
| 2392 | } |
| 2393 | ackId = in.ReadUInt32(); |
| 2394 | pseq = in.ReadUInt32(); |
| 2395 | acks = in.ReadUInt32(); |
| 2396 | if (flags & PFLAG_HAS_PROTO) |
| 2397 | { |
| 2398 | std::uint32_t proto = in.ReadUInt32(); |
| 2399 | if (proto != PROTOCOL_NAME) |
| 2400 | { |
| 2401 | LOGW("Received packet uses wrong protocol"); |
| 2402 |
| 2403 | m_lastError = Error::INCOMPATIBLE; |
| 2404 | SetState(State::FAILED); |
| 2405 | return; |
| 2406 | } |
| 2407 | } |
| 2408 | if (flags & PFLAG_HAS_EXTRA) |
| 2409 | { |
| 2410 | int extraLen = in.ReadTlLength(); |
| 2411 | in.Seek(in.GetOffset() + static_cast<std::size_t>(extraLen + pad4(extraLen))); |
| 2412 | } |
| 2413 | if (flags & PFLAG_HAS_DATA) |
| 2414 | { |
| 2415 | packetInnerLen = static_cast<std::size_t>(in.ReadTlLength()); |
| 2416 | } |
| 2417 | pflags = 0; |
| 2418 | break; |
| 2419 | } |
| 2420 | case TLID_SIMPLE_AUDIO_BLOCK: |
| 2421 | { |
| 2422 | in.ReadInt64(); // random id |
| 2423 | int randLen = in.ReadTlLength(); |
| 2424 | in.Seek(in.GetOffset() + static_cast<std::size_t>(randLen + pad4(randLen))); |
| 2425 | packetInnerLen = static_cast<std::size_t>(in.ReadTlLength()); |
| 2426 | type = static_cast<PktType>(in.ReadUInt8()); |
| 2427 | ackId = in.ReadUInt32(); |
| 2428 | pseq = in.ReadUInt32(); |
| 2429 | acks = in.ReadUInt32(); |
| 2430 | if (m_peerVersion >= 6) |
| 2431 | pflags = in.ReadUInt8(); |
| 2432 | else |
| 2433 | pflags = 0; |
| 2434 | break; |
| 2435 | } |
| 2436 | default: |
| 2437 | { |
| 2438 | LOGW("Received a packet of unknown type %08X", tlid); |
| 2439 | return; |
| 2440 | } |
| 2441 | } |
| 2442 | } |
| 2443 | ++m_packetsReceived; |
| 2444 |
| 2445 | if (seqgt(pseq, m_lastRemoteSeq - MAX_RECENT_PACKETS)) |
| 2446 | { |
| 2447 | if (std::find(m_recentIncomingPackets.begin(), m_recentIncomingPackets.end(), pseq) != m_recentIncomingPackets.end()) |
| 2448 | { |
| 2449 | LOGW("Received duplicated packet for seq %u", pseq); |
| 2450 | return; |
| 2451 | } |
| 2452 | m_recentIncomingPackets.emplace_back(pseq); |
| 2453 | while (m_recentIncomingPackets.size() > MAX_RECENT_PACKETS) |
| 2454 | m_recentIncomingPackets.pop_front(); |
| 2455 | if (seqgt(pseq, m_lastRemoteSeq)) |
| 2456 | m_lastRemoteSeq = pseq; |
| 2457 | } |
| 2458 | else |
| 2459 | { |
| 2460 | LOGW("Packet %u is out of order and too late", pseq); |
| 2461 | return; |
| 2462 | } |
| 2463 |
| 2464 | if (pflags & XPFLAG_HAS_EXTRA) |
| 2465 | { |
| 2466 | std::uint8_t extraCount = in.ReadUInt8(); |
| 2467 | for (int i = 0; i < extraCount; i++) |
| 2468 | { |
| 2469 | std::size_t extraLen = in.ReadUInt8(); |
| 2470 | Buffer xbuffer(extraLen); |
| 2471 | in.ReadBytes(*xbuffer, extraLen); |
| 2472 | ProcessExtraData(xbuffer); |
| 2473 | } |
| 2474 | } |
| 2475 |
| 2476 | std::uint32_t recvTS = 0; |
| 2477 | if (pflags & XPFLAG_HAS_RECV_TS) |
| 2478 | { |
| 2479 | recvTS = in.ReadUInt32(); |
| 2480 | } |
| 2481 |
| 2482 | if (seqgt(ackId, m_lastRemoteAckSeq)) |
| 2483 | { |
| 2484 | if (m_waitingForAcks && m_lastRemoteAckSeq >= m_firstSentPing) |
| 2485 | { |
| 2486 | m_RTTHistory.Reset(); |
| 2487 | m_waitingForAcks = false; |
| 2488 | m_dontSendPackets = 10; |
| 2489 | m_messageThread.Post([this] |
| 2490 | { |
| 2491 | m_dontSendPackets = 0; |
| 2492 | }, |
| 2493 | 1.0); |
| 2494 | LOGI("resuming sending"); |
| 2495 | } |
| 2496 | std::vector<std::uint32_t> peerAcks; |
| 2497 | m_lastRemoteAckSeq = ackId; |
| 2498 | m_congestionControl->PacketAcknowledged(ackId); |
| 2499 | peerAcks.emplace_back(ackId); |
| 2500 | for (unsigned int i = 0; i < 32; ++i) |
| 2501 | { |
| 2502 | if ((acks >> (31 - i)) & 1) |
| 2503 | { |
| 2504 | peerAcks.emplace_back(ackId - (i + 1)); |
| 2505 | } |
| 2506 | } |
| 2507 |
| 2508 | for (RecentOutgoingPacket& opkt : m_recentOutgoingPackets) |
| 2509 | { |
| 2510 | if (opkt.ackTime != 0.0) |
| 2511 | continue; |
| 2512 | if (std::find(peerAcks.begin(), peerAcks.end(), opkt.seq) != peerAcks.end()) |
| 2513 | { |
| 2514 | opkt.ackTime = GetCurrentTime(); |
| 2515 | if (opkt.lost) |
| 2516 | { |
| 2517 | LOGW("acknowledged lost packet %u", opkt.seq); |
| 2518 | --m_sendLosses; |
| 2519 | } |
| 2520 | if (opkt.sender != nullptr && !opkt.lost) |
| 2521 | { // don't report lost packets as acknowledged to PacketSenders |
| 2522 | opkt.sender->PacketAcknowledged(opkt.seq, opkt.sendTime, recvTS / 1000.0, opkt.type, opkt.size); |
| 2523 | } |
| 2524 |
| 2525 | // TODO move this to a PacketSender |
| 2526 | m_congestionControl->PacketAcknowledged(opkt.seq); |
| 2527 | } |
| 2528 | } |
| 2529 |
| 2530 | if (m_peerVersion < 6) |
| 2531 | { |
| 2532 | std::size_t index = 0; |
| 2533 | for (auto it = m_queuedPackets.begin(); it != m_queuedPackets.end();) |
| 2534 | { |
| 2535 | QueuedPacket& qp = *it; |
| 2536 | bool didAck = false; |
| 2537 | for (std::size_t j = 0; j < qp.seqs.Size(); ++j) |
| 2538 | { |
| 2539 | LOGD("queued packet %u, seq %u=%u", static_cast<unsigned>(index), static_cast<unsigned int>(j), qp.seqs[j]); |
| 2540 | if (qp.seqs[j] == 0) |
| 2541 | break; |
| 2542 | int remoteAcksIndex = static_cast<int>(m_lastRemoteAckSeq - qp.seqs[j]); |
| 2543 | if (seqgt(m_lastRemoteAckSeq, qp.seqs[j]) && remoteAcksIndex >= 0 && remoteAcksIndex < 32) |
| 2544 | { |
| 2545 | for (RecentOutgoingPacket& opkt : m_recentOutgoingPackets) |
| 2546 | { |
| 2547 | if (opkt.seq == qp.seqs[j] && opkt.ackTime > 0) |
| 2548 | { |
| 2549 | LOGD("did ack seq %u, removing", qp.seqs[j]); |
| 2550 | didAck = true; |
| 2551 | break; |
| 2552 | } |
| 2553 | } |
| 2554 | if (didAck) |
| 2555 | break; |
| 2556 | } |
| 2557 | } |
| 2558 | if (didAck) |
| 2559 | { |
| 2560 | it = m_queuedPackets.erase(it); |
| 2561 | } |
| 2562 | else |
| 2563 | { |
| 2564 | ++it; |
| 2565 | ++index; |
| 2566 | } |
| 2567 | } |
| 2568 | } |
| 2569 | else |
| 2570 | { |
| 2571 | for (auto x = m_currentExtras.begin(); x != m_currentExtras.end();) |
| 2572 | { |
| 2573 | if (x->firstContainingSeq != 0 && (m_lastRemoteAckSeq == x->firstContainingSeq || seqgt(m_lastRemoteAckSeq, x->firstContainingSeq))) |
| 2574 | { |
| 2575 | LOGV("Peer acknowledged extra type %u length %u", static_cast<std::uint8_t>(x->type), static_cast<unsigned int>(x->data.Length())); |
| 2576 | ProcessAcknowledgedOutgoingExtra(*x); |
| 2577 | x = m_currentExtras.erase(x); |
| 2578 | continue; |
| 2579 | } |
| 2580 | ++x; |
| 2581 | } |
| 2582 | } |
| 2583 | } |
| 2584 |
| 2585 | Endpoint* currentEndpoint = &m_endpoints.at(m_currentEndpoint); |
| 2586 | if ( srcEndpoint.id != m_currentEndpoint |
| 2587 | && (srcEndpoint.type == Endpoint::Type::UDP_RELAY || srcEndpoint.type == Endpoint::Type::TCP_RELAY) |
| 2588 | && ((currentEndpoint->type != Endpoint::Type::UDP_RELAY && currentEndpoint->type != Endpoint::Type::TCP_RELAY) || currentEndpoint->m_averageRTT == 0)) |
| 2589 | { |
| 2590 | if (seqgt(m_lastSentSeq - 32, m_lastRemoteAckSeq)) |
| 2591 | { |
| 2592 | m_currentEndpoint = srcEndpoint.id; |
| 2593 | currentEndpoint = &srcEndpoint; |
| 2594 | LOGI("Peer network address probably changed, switching to relay"); |
| 2595 | if (m_allowP2p) |
| 2596 | SendPublicEndpointsRequest(); |
| 2597 | } |
| 2598 | } |
| 2599 |
| 2600 | if (m_config.logPacketStats) |
| 2601 | { |
| 2602 | DebugLoggedPacket dpkt = |
| 2603 | { |
| 2604 | static_cast<std::int32_t>(pseq), |
| 2605 | GetCurrentTime() - m_connectionInitTime, |
| 2606 | static_cast<std::int32_t>(packet.data.Length()) |
| 2607 | }; |
| 2608 | m_debugLoggedPackets.emplace_back(dpkt); |
| 2609 | if (m_debugLoggedPackets.size() >= 2500) |
| 2610 | { |
| 2611 | m_debugLoggedPackets.erase(m_debugLoggedPackets.begin(), m_debugLoggedPackets.begin() + 500); |
| 2612 | } |
| 2613 | } |
| 2614 |
| 2615 | ++m_unacknowledgedIncomingPacketCount; |
| 2616 | if (m_unacknowledgedIncomingPacketCount > m_unackNopThreshold) |
| 2617 | { |
| 2618 | SendNopPacket(); |
| 2619 | } |
| 2620 |
| 2621 | #ifdef LOG_PACKETS |
| 2622 | LOGV("Received: from=%s:%u, seq=%u, length=%u, type=%s", srcEndpoint.GetAddress().ToString().c_str(), srcEndpoint.port, pseq, (unsigned int)packet.data.Length(), GetPacketTypeString(type).c_str()); |
| 2623 | #endif |
| 2624 |
| 2625 | switch (type) |
| 2626 | { |
| 2627 | case PktType::NOP: |
| 2628 | LOGE("Received packet of NOP type"); |
| 2629 | break; |
| 2630 | case PktType::UPDATE_STREAMS: |
| 2631 | LOGE("Received packet of UPDATE_STREAMS type"); |
| 2632 | break; |
| 2633 | case PktType::SWITCH_TO_P2P: |
| 2634 | LOGE("Received packet of SWITCH_TO_P2P type"); |
| 2635 | break; |
| 2636 | case PktType::SWITCH_PREF_RELAY: |
| 2637 | LOGE("Received packet of SWITCH_PREF_RELAY type"); |
| 2638 | break; |
| 2639 | case PktType::INIT: |
| 2640 | { |
| 2641 | LOGD("Received init"); |
| 2642 | std::int32_t ver = in.ReadInt32(); |
| 2643 | if (!m_receivedInit) |
| 2644 | m_peerVersion = ver; |
| 2645 | LOGI("Peer version is %d", m_peerVersion); |
| 2646 | std::uint32_t minVer = in.ReadUInt32(); |
| 2647 | if (minVer > PROTOCOL_VERSION || m_peerVersion < MIN_PROTOCOL_VERSION) |
| 2648 | { |
| 2649 | m_lastError = Error::INCOMPATIBLE; |
| 2650 |
| 2651 | SetState(State::FAILED); |
| 2652 | return; |
| 2653 | } |
| 2654 | std::uint32_t flags = in.ReadUInt32(); |
| 2655 | if (!m_receivedInit) |
| 2656 | { |
| 2657 | if (flags & INIT_FLAG_DATA_SAVING_ENABLED) |
| 2658 | { |
| 2659 | m_dataSavingRequestedByPeer = true; |
| 2660 | UpdateDataSavingState(); |
| 2661 | UpdateAudioBitrateLimit(); |
| 2662 | } |
| 2663 | if (flags & INIT_FLAG_GROUP_CALLS_SUPPORTED) |
| 2664 | { |
| 2665 | m_peerCapabilities |= TGVOIP_PEER_CAP_GROUP_CALLS; |
| 2666 | } |
| 2667 | if (flags & INIT_FLAG_VIDEO_RECV_SUPPORTED) |
| 2668 | { |
| 2669 | m_peerCapabilities |= TGVOIP_PEER_CAP_VIDEO_DISPLAY; |
| 2670 | } |
| 2671 | if (flags & INIT_FLAG_VIDEO_SEND_SUPPORTED) |
| 2672 | { |
| 2673 | m_peerCapabilities |= TGVOIP_PEER_CAP_VIDEO_CAPTURE; |
| 2674 | } |
| 2675 | } |
| 2676 |
| 2677 | std::uint8_t numSupportedAudioCodecs = in.ReadUInt8(); |
| 2678 | for (int i = 0; i < numSupportedAudioCodecs; ++i) |
| 2679 | { |
| 2680 | if (m_peerVersion < 5) |
| 2681 | in.ReadUInt8(); // ignore for now |
| 2682 | else |
| 2683 | in.ReadInt32(); |
| 2684 | } |
| 2685 | if (!m_receivedInit && ((flags & INIT_FLAG_VIDEO_SEND_SUPPORTED && m_config.enableVideoReceive) || (flags & INIT_FLAG_VIDEO_RECV_SUPPORTED && m_config.enableVideoSend))) |
| 2686 | { |
| 2687 | LOGD("Peer video decoders:"); |
| 2688 | std::uint8_t numSupportedVideoDecoders = in.ReadUInt8(); |
| 2689 | for (int i = 0; i < numSupportedVideoDecoders; ++i) |
| 2690 | { |
| 2691 | std::uint32_t id = in.ReadUInt32(); |
| 2692 | m_peerVideoDecoders.emplace_back(id); |
| 2693 | char* _id = reinterpret_cast<char*>(&id); |
| 2694 | LOGD("%c%c%c%c", _id[3], _id[2], _id[1], _id[0]); |
| 2695 | } |
| 2696 | m_protocolInfo.maxVideoResolution = static_cast<InitVideoRes>(in.ReadUInt8()); |
| 2697 |
| 2698 | SetupOutgoingVideoStream(); |
| 2699 | } |
| 2700 |
| 2701 | BufferOutputStream out(1024); |
| 2702 |
| 2703 | out.WriteInt32(PROTOCOL_VERSION); |
| 2704 | out.WriteInt32(MIN_PROTOCOL_VERSION); |
| 2705 |
| 2706 | out.WriteUInt8(static_cast<std::uint8_t>(m_outgoingStreams.size())); |
| 2707 | for (const std::shared_ptr<Stream>& stream : m_outgoingStreams) |
| 2708 | { |
| 2709 | out.WriteUInt8(stream->id); |
| 2710 | out.WriteUInt8(static_cast<std::uint8_t>(stream->type)); |
| 2711 | if (m_peerVersion < 5) |
| 2712 | out.WriteUInt8(static_cast<std::uint8_t>(stream->codec == CODEC_OPUS ? CODEC_OPUS_OLD : 0)); |
| 2713 | else |
| 2714 | out.WriteUInt32(stream->codec); |
| 2715 | out.WriteUInt16(stream->frameDuration); |
| 2716 | out.WriteUInt8(stream->enabled ? 1 : 0); |
| 2717 | } |
| 2718 | LOGI("Sending init ack"); |
| 2719 | std::size_t outLength = out.GetLength(); |
| 2720 | SendOrEnqueuePacket(PendingOutgoingPacket |
| 2721 | { |
| 2722 | /*.seq=*/ GenerateOutSeq(), |
| 2723 | /*.type=*/ PktType::INIT_ACK, |
| 2724 | /*.len=*/ outLength, |
| 2725 | /*.data=*/ Buffer(std::move(out)), |
| 2726 | /*.endpoint=*/0 |
| 2727 | }); |
| 2728 | if (!m_receivedInit) |
| 2729 | { |
| 2730 | m_receivedInit = true; |
| 2731 | if ((srcEndpoint.type == Endpoint::Type::UDP_RELAY && m_udpConnectivityState != UdpState::BAD && m_udpConnectivityState != UdpState::NOT_AVAILABLE) |
| 2732 | || srcEndpoint.type == Endpoint::Type::TCP_RELAY) |
| 2733 | { |
| 2734 | m_currentEndpoint = srcEndpoint.id; |
| 2735 | if (srcEndpoint.type == Endpoint::Type::UDP_RELAY || (m_useTCP && srcEndpoint.type == Endpoint::Type::TCP_RELAY)) |
| 2736 | m_preferredRelay = srcEndpoint.id; |
| 2737 | } |
| 2738 | } |
| 2739 | if (!m_audioStarted && m_receivedInitAck) |
| 2740 | { |
| 2741 | StartAudio(); |
| 2742 | m_audioStarted = true; |
| 2743 | } |
| 2744 | break; |
| 2745 | } |
| 2746 | case PktType::INIT_ACK: |
| 2747 | { |
| 2748 | LOGD("Received init ack"); |
| 2749 | if (m_receivedInitAck) |
| 2750 | break; |
| 2751 |
| 2752 | m_receivedInitAck = true; |
| 2753 |
| 2754 | m_messageThread.Cancel(m_initTimeoutID); |
| 2755 | m_initTimeoutID = MessageThread::INVALID_ID; |
| 2756 |
| 2757 | if (packetInnerLen > 10) |
| 2758 | { |
| 2759 | m_peerVersion = in.ReadInt32(); |
| 2760 | std::uint32_t minVer = in.ReadUInt32(); |
| 2761 | if (minVer > PROTOCOL_VERSION || m_peerVersion < MIN_PROTOCOL_VERSION) |
| 2762 | { |
| 2763 | m_lastError = Error::INCOMPATIBLE; |
| 2764 |
| 2765 | SetState(State::FAILED); |
| 2766 | return; |
| 2767 | } |
| 2768 | } |
| 2769 | else |
| 2770 | { |
| 2771 | m_peerVersion = 1; |
| 2772 | } |
| 2773 |
| 2774 | LOGI("peer version from init ack %d", m_peerVersion); |
| 2775 |
| 2776 | std::uint8_t streamCount = in.ReadUInt8(); |
| 2777 | if (streamCount == 0) |
| 2778 | return; |
| 2779 |
| 2780 | std::shared_ptr<Stream> incomingAudioStream = nullptr; |
| 2781 | for (int i = 0; i < streamCount; ++i) |
| 2782 | { |
| 2783 | std::shared_ptr<Stream> stream = std::make_shared<Stream>(); |
| 2784 | stream->id = in.ReadUInt8(); |
| 2785 | std::uint8_t type = in.ReadUInt8(); |
| 2786 | if (m_peerVersion < 5) |
| 2787 | { |
| 2788 | std::uint8_t codec = in.ReadUInt8(); |
| 2789 | if (codec == CODEC_OPUS_OLD) |
| 2790 | stream->codec = CODEC_OPUS; |
| 2791 | } |
| 2792 | else |
| 2793 | { |
| 2794 | stream->codec = in.ReadUInt32(); |
| 2795 | } |
| 2796 | in.ReadInt16(); |
| 2797 | stream->frameDuration = 60; |
| 2798 | stream->enabled = in.ReadUInt8() == 1; |
| 2799 | if (type == static_cast<std::uint8_t>(StreamType::VIDEO) && m_peerVersion < 9) |
| 2800 | { |
| 2801 | stream->type = StreamType::VIDEO; |
| 2802 | LOGV("Skipping video stream for old protocol version"); |
| 2803 | continue; |
| 2804 | } |
| 2805 | if (type == static_cast<std::uint8_t>(StreamType::AUDIO)) |
| 2806 | { |
| 2807 | stream->type = StreamType::AUDIO; |
| 2808 | stream->jitterBuffer = std::make_shared<JitterBuffer>(nullptr, stream->frameDuration); |
| 2809 | if (stream->frameDuration > 50) |
| 2810 | stream->jitterBuffer->SetMinPacketCount(static_cast<std::uint32_t>(ServerConfig::GetSharedInstance()->GetInt("jitter_initial_delay_60", 2))); |
| 2811 | else if (stream->frameDuration > 30) |
| 2812 | stream->jitterBuffer->SetMinPacketCount(static_cast<std::uint32_t>(ServerConfig::GetSharedInstance()->GetInt("jitter_initial_delay_40", 4))); |
| 2813 | else |
| 2814 | stream->jitterBuffer->SetMinPacketCount(static_cast<std::uint32_t>(ServerConfig::GetSharedInstance()->GetInt("jitter_initial_delay_20", 6))); |
| 2815 | stream->decoder = nullptr; |
| 2816 | } |
| 2817 | else if (type == static_cast<std::uint8_t>(StreamType::VIDEO)) |
| 2818 | { |
| 2819 | stream->type = StreamType::VIDEO; |
| 2820 | if (!stream->packetReassembler) |
| 2821 | { |
| 2822 | stream->packetReassembler = std::make_shared<PacketReassembler>(); |
| 2823 | stream->packetReassembler->SetCallback(std::bind(&VoIPController::ProcessIncomingVideoFrame, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4)); |
| 2824 | } |
| 2825 | } |
| 2826 | else |
| 2827 | { |
| 2828 | LOGW("Unknown incoming stream type: %u", type); |
| 2829 | continue; |
| 2830 | } |
| 2831 | m_incomingStreams.emplace_back(stream); |
| 2832 | if (stream->type == StreamType::AUDIO && !incomingAudioStream) |
| 2833 | incomingAudioStream = stream; |
| 2834 | } |
| 2835 | if (incomingAudioStream == nullptr) |
| 2836 | return; |
| 2837 |
| 2838 | if (m_peerVersion >= 5 && !m_useMTProto2) |
| 2839 | { |
| 2840 | m_useMTProto2 = true; |
| 2841 | LOGD("MTProto2 wasn't initially enabled for whatever reason but peer supports it; upgrading"); |
| 2842 | } |
| 2843 |
| 2844 | if (!m_audioStarted && m_receivedInit) |
| 2845 | { |
| 2846 | StartAudio(); |
| 2847 | m_audioStarted = true; |
| 2848 | } |
| 2849 | m_messageThread.Post([this] |
| 2850 | { |
| 2851 | if (m_state == State::WAIT_INIT_ACK) |
| 2852 | { |
| 2853 | SetState(State::ESTABLISHED); |
| 2854 | } |
| 2855 | }, |
| 2856 | ServerConfig::GetSharedInstance()->GetDouble("established_delay_if_no_stream_data", 1.5)); |
| 2857 | if (m_allowP2p) |
| 2858 | SendPublicEndpointsRequest(); |
| 2859 | break; |
| 2860 | } |
| 2861 | case PktType::STREAM_DATA: |
| 2862 | case PktType::STREAM_DATA_X2: |
| 2863 | case PktType::STREAM_DATA_X3: |
| 2864 | { |
| 2865 | if (!m_receivedFirstStreamPacket) |
| 2866 | { |
| 2867 | m_receivedFirstStreamPacket = true; |
| 2868 | if (m_state != State::ESTABLISHED && m_receivedInitAck) |
| 2869 | { |
| 2870 | m_messageThread.Post([this]() |
| 2871 | { |
| 2872 | SetState(State::ESTABLISHED); |
| 2873 | }, |
| 2874 | 0.5); |
| 2875 | LOGW("First audio packet - setting state to ESTABLISHED"); |
| 2876 | } |
| 2877 | } |
| 2878 | int count; |
| 2879 | switch (type) |
| 2880 | { |
| 2881 | case PktType::STREAM_DATA: |
| 2882 | count = 1; |
| 2883 | break; |
| 2884 | case PktType::STREAM_DATA_X2: |
| 2885 | count = 2; |
| 2886 | break; |
| 2887 | case PktType::STREAM_DATA_X3: |
| 2888 | count = 3; |
| 2889 | break; |
| 2890 | default: |
| 2891 | assert(false); |
| 2892 | break; |
| 2893 | } |
| 2894 | if (srcEndpoint.type == Endpoint::Type::UDP_RELAY && srcEndpoint.id != m_peerPreferredRelay) |
| 2895 | { |
| 2896 | m_peerPreferredRelay = srcEndpoint.id; |
| 2897 | } |
| 2898 | for (int i = 0; i < count; ++i) |
| 2899 | { |
| 2900 | std::uint8_t streamID = in.ReadUInt8(); |
| 2901 | std::uint8_t flags = streamID & 0xC0; |
| 2902 | streamID &= 0x3F; |
| 2903 | std::uint16_t sdlen = (flags & STREAM_DATA_FLAG_LEN16 ? in.ReadUInt16() : in.ReadUInt8()); |
| 2904 | std::uint32_t pts = in.ReadUInt32(); |
| 2905 | std::uint8_t fragmentCount = 1; |
| 2906 | std::uint8_t fragmentIndex = 0; |
| 2907 | m_audioTimestampIn = pts; |
| 2908 | if (!m_audioOutStarted && m_audioOutput != nullptr) |
| 2909 | { |
| 2910 | MutexGuard m(m_audioIOMutex); |
| 2911 | m_audioOutput->Start(); |
| 2912 | m_audioOutStarted = true; |
| 2913 | } |
| 2914 | bool fragmented = static_cast<bool>(sdlen & STREAM_DATA_XFLAG_FRAGMENTED); |
| 2915 | bool extraFEC = static_cast<bool>(sdlen & STREAM_DATA_XFLAG_EXTRA_FEC); |
| 2916 | bool keyframe = static_cast<bool>(sdlen & STREAM_DATA_XFLAG_KEYFRAME); |
| 2917 | if (fragmented) |
| 2918 | { |
| 2919 | fragmentIndex = in.ReadUInt8(); |
| 2920 | fragmentCount = in.ReadUInt8(); |
| 2921 | } |
| 2922 | sdlen &= 0x7FF; |
| 2923 | if (in.GetOffset() + sdlen > len) |
| 2924 | { |
| 2925 | return; |
| 2926 | } |
| 2927 | std::shared_ptr<Stream> stream; |
| 2928 | for (std::shared_ptr<Stream>& ss : m_incomingStreams) |
| 2929 | { |
| 2930 | if (ss->id == streamID) |
| 2931 | { |
| 2932 | stream = ss; |
| 2933 | break; |
| 2934 | } |
| 2935 | } |
| 2936 |
| 2937 | if (stream == nullptr) |
| 2938 | { |
| 2939 | LOGW("received packet for unknown stream %u", static_cast<unsigned int>(streamID)); |
| 2940 | } |
| 2941 | else |
| 2942 | { |
| 2943 | switch (stream->type) |
| 2944 | { |
| 2945 | case StreamType::AUDIO: |
| 2946 | { |
| 2947 | if (stream->jitterBuffer == nullptr) |
| 2948 | break; |
| 2949 | stream->jitterBuffer->HandleInput(reinterpret_cast<const std::uint8_t*>(buffer + in.GetOffset()), sdlen, pts, false); |
| 2950 | if (extraFEC) |
| 2951 | { |
| 2952 | in.Seek(in.GetOffset() + sdlen); |
| 2953 | std::uint8_t fecCount = in.ReadUInt8(); |
| 2954 | for (unsigned int j = 0; j < fecCount; ++j) |
| 2955 | { |
| 2956 | std::uint8_t dlen = in.ReadUInt8(); |
| 2957 | std::uint8_t data[256]; |
| 2958 | in.ReadBytes(data, dlen); |
| 2959 | stream->jitterBuffer->HandleInput(data, dlen, pts - (fecCount - j) * stream->frameDuration, true); |
| 2960 | } |
| 2961 | } |
| 2962 | } |
| 2963 | case StreamType::VIDEO: |
| 2964 | { |
| 2965 | if (stream->packetReassembler == nullptr) |
| 2966 | break; |
| 2967 | std::uint8_t frameSeq = in.ReadUInt8(); |
| 2968 | Buffer pdata(sdlen); |
| 2969 | std::uint16_t rotation = 0; |
| 2970 | if (fragmentIndex == 0) |
| 2971 | { |
| 2972 | VideoRotation rotationEnum = static_cast<VideoRotation>(in.ReadUInt8() & std::uint8_t{VIDEO_ROTATION_MASK}); |
| 2973 | switch (rotationEnum) |
| 2974 | { |
| 2975 | case VideoRotation::_0: |
| 2976 | rotation = 0; |
| 2977 | break; |
| 2978 | case VideoRotation::_90: |
| 2979 | rotation = 90; |
| 2980 | break; |
| 2981 | case VideoRotation::_180: |
| 2982 | rotation = 180; |
| 2983 | break; |
| 2984 | case VideoRotation::_270: |
| 2985 | rotation = 270; |
| 2986 | break; |
| 2987 | // default: // unreachable on sane CPUs |
| 2988 | // std::abort(); |
| 2989 | } |
| 2990 | } |
| 2991 | pdata.CopyFrom(buffer + in.GetOffset(), 0, sdlen); |
| 2992 | stream->packetReassembler->AddFragment(std::move(pdata), fragmentIndex, fragmentCount, pts, frameSeq, keyframe, rotation); |
| 2993 | } |
| 2994 | } |
| 2995 | } |
| 2996 | if (i < count - 1) |
| 2997 | in.Seek(in.GetOffset() + sdlen); |
| 2998 | } |
| 2999 | break; |
| 3000 | } |
| 3001 | case PktType::PING: |
| 3002 | { |
| 3003 |
| 3004 | if (srcEndpoint.type != Endpoint::Type::UDP_RELAY && srcEndpoint.type != Endpoint::Type::TCP_RELAY && !m_allowP2p) |
| 3005 | { |
| 3006 | LOGW("Received p2p ping but p2p is disabled by manual override"); |
| 3007 | return; |
| 3008 | } |
| 3009 | BufferOutputStream pkt(128); |
| 3010 | pkt.WriteUInt32(pseq); |
| 3011 | std::size_t pktLength = pkt.GetLength(); |
| 3012 | SendOrEnqueuePacket(PendingOutgoingPacket |
| 3013 | { |
| 3014 | /*.seq=*/ GenerateOutSeq(), |
| 3015 | /*.type=*/ PktType::PONG, |
| 3016 | /*.len=*/ pktLength, |
| 3017 | /*.data=*/ Buffer(std::move(pkt)), |
| 3018 | /*.endpoint=*/srcEndpoint.id, |
| 3019 | }); |
| 3020 | break; |
| 3021 | } |
| 3022 | case PktType::PONG: |
| 3023 | { |
| 3024 | if (packetInnerLen < 4) |
| 3025 | break; |
| 3026 | std::uint32_t pingSeq = in.ReadUInt32(); |
| 3027 | #ifdef LOG_PACKETS |
| 3028 | LOGD("Received pong for ping in seq %u", pingSeq); |
| 3029 | #endif |
| 3030 | if (pingSeq == srcEndpoint.m_lastPingSeq) |
| 3031 | { |
| 3032 | srcEndpoint.m_rtts.Add(GetCurrentTime() - srcEndpoint.m_lastPingTime); |
| 3033 | srcEndpoint.m_averageRTT = srcEndpoint.m_rtts.NonZeroAverage(); |
| 3034 | LOGD("Current RTT via %s: %.3f, average: %.3f", packet.address.ToString().c_str(), srcEndpoint.m_rtts[0], srcEndpoint.m_averageRTT); |
| 3035 | if (srcEndpoint.m_averageRTT > m_rateMaxAcceptableRTT) |
| 3036 | m_needRate = true; |
| 3037 | } |
| 3038 | break; |
| 3039 | } |
| 3040 | case PktType::STREAM_STATE: |
| 3041 | { |
| 3042 | std::uint8_t id = in.ReadUInt8(); |
| 3043 | std::uint8_t enabled = in.ReadUInt8(); |
| 3044 | LOGV("Peer stream state: id %u flags %u", id, enabled); |
| 3045 | for (std::shared_ptr<Stream>& stream : m_incomingStreams) |
| 3046 | { |
| 3047 | if (stream->id == id) |
| 3048 | { |
| 3049 | stream->enabled = enabled == 1; |
| 3050 | UpdateAudioOutputState(); |
| 3051 | break; |
| 3052 | } |
| 3053 | } |
| 3054 | break; |
| 3055 | } |
| 3056 | case PktType::LAN_ENDPOINT: |
| 3057 | { |
| 3058 | LOGV("received lan endpoint"); |
| 3059 | std::uint32_t peerAddr = in.ReadUInt32(); |
| 3060 | std::uint16_t peerPort = in.ReadUInt16(); |
| 3061 | constexpr std::int64_t lanID = static_cast<std::int64_t>(FOURCC('L', 'A', 'N', '4')) << 32; |
| 3062 | std::uint8_t peerTag[16]; |
| 3063 | Endpoint lan(lanID, peerPort, NetworkAddress::IPv4(peerAddr), NetworkAddress::Empty(), Endpoint::Type::UDP_P2P_LAN, peerTag); |
| 3064 |
| 3065 | if (m_currentEndpoint == lanID) |
| 3066 | m_currentEndpoint = m_preferredRelay; |
| 3067 |
| 3068 | MutexGuard m(m_endpointsMutex); |
| 3069 | m_endpoints[lanID] = lan; |
| 3070 | break; |
| 3071 | } |
| 3072 | case PktType::NETWORK_CHANGED: |
| 3073 | { |
| 3074 | if (!(currentEndpoint->type != Endpoint::Type::UDP_RELAY && currentEndpoint->type != Endpoint::Type::TCP_RELAY)) |
| 3075 | break; |
| 3076 | m_currentEndpoint = m_preferredRelay; |
| 3077 | if (m_allowP2p) |
| 3078 | SendPublicEndpointsRequest(); |
| 3079 | if (m_peerVersion >= 2) |
| 3080 | { |
| 3081 | std::uint32_t flags = in.ReadUInt32(); |
| 3082 | m_dataSavingRequestedByPeer = (flags & INIT_FLAG_DATA_SAVING_ENABLED) == INIT_FLAG_DATA_SAVING_ENABLED; |
| 3083 | UpdateDataSavingState(); |
| 3084 | UpdateAudioBitrateLimit(); |
| 3085 | ResetEndpointPingStats(); |
| 3086 | } |
| 3087 | break; |
| 3088 | } |
| 3089 | case PktType::STREAM_EC: |
| 3090 | { |
| 3091 | std::uint8_t streamID = in.ReadUInt8(); |
| 3092 | if (m_peerVersion < 7) |
| 3093 | { |
| 3094 | std::uint32_t lastTimestamp = in.ReadUInt32(); |
| 3095 | std::uint8_t count = in.ReadUInt8(); |
| 3096 | for (std::shared_ptr<Stream>& stream : m_incomingStreams) |
| 3097 | { |
| 3098 | if (stream->id == streamID) |
| 3099 | { |
| 3100 | for (unsigned int i = 0; i < count; ++i) |
| 3101 | { |
| 3102 | std::uint8_t dlen = in.ReadUInt8(); |
| 3103 | std::uint8_t data[256]; |
| 3104 | in.ReadBytes(data, dlen); |
| 3105 | if (stream->jitterBuffer != nullptr) |
| 3106 | { |
| 3107 | stream->jitterBuffer->HandleInput(data, dlen, lastTimestamp - (count - i - 1) * stream->frameDuration, true); |
| 3108 | } |
| 3109 | } |
| 3110 | break; |
| 3111 | } |
| 3112 | } |
| 3113 | } |
| 3114 | else |
| 3115 | { |
| 3116 | std::shared_ptr<Stream> stream = GetStreamByID(streamID, false); |
| 3117 | if (stream == nullptr) |
| 3118 | { |
| 3119 | LOGW("Received FEC packet for unknown stream %u", streamID); |
| 3120 | return; |
| 3121 | } |
| 3122 | if (stream->type != StreamType::VIDEO) |
| 3123 | { |
| 3124 | LOGW("Received FEC packet for non-video stream %u", streamID); |
| 3125 | return; |
| 3126 | } |
| 3127 | if (stream->packetReassembler == nullptr) |
| 3128 | return; |
| 3129 |
| 3130 | std::uint8_t fseq = in.ReadUInt8(); |
| 3131 | std::uint8_t fecScheme = in.ReadUInt8(); |
| 3132 | std::uint8_t prevFrameCount = in.ReadUInt8(); |
| 3133 | std::uint16_t fecLen = in.ReadUInt16(); |
| 3134 | if (fecLen > in.Remaining()) |
| 3135 | return; |
| 3136 |
| 3137 | Buffer fecData(fecLen); |
| 3138 | in.ReadBytes(fecData); |
| 3139 |
| 3140 | stream->packetReassembler->AddFEC(std::move(fecData), fseq, prevFrameCount, fecScheme); |
| 3141 | } |
| 3142 | break; |
| 3143 | } |
| 3144 | } |
| 3145 | } |
| 3146 |
| 3147 | void VoIPController::ProcessExtraData(Buffer& data) |
| 3148 | { |
| 3149 | BufferInputStream in(*data, data.Length()); |
| 3150 | ExtraType type = static_cast<ExtraType>(in.ReadUInt8()); |
| 3151 | alignas(8) std::uint8_t fullHash[SHA1_LENGTH]; |
| 3152 | crypto.sha1(*data, data.Length(), fullHash); |
| 3153 | std::uint64_t hash = *reinterpret_cast<std::uint64_t*>(fullHash); |
| 3154 | if (m_lastReceivedExtrasByType[type] == hash) |
| 3155 | { |
| 3156 | return; |
| 3157 | } |
| 3158 | LOGE("ProcessExtraData"); |
| 3159 | m_lastReceivedExtrasByType[type] = hash; |
| 3160 | switch (type) |
| 3161 | { |
| 3162 | case ExtraType::STREAM_FLAGS: |
| 3163 | { |
| 3164 | std::uint8_t id = in.ReadUInt8(); |
| 3165 | std::uint32_t flags = in.ReadUInt32(); |
| 3166 | LOGV("Peer stream state: id %u flags %u", id, flags); |
| 3167 | for (std::shared_ptr<Stream>& s : m_incomingStreams) |
| 3168 | { |
| 3169 | if (s->id == id) |
| 3170 | { |
| 3171 | bool prevEnabled = s->enabled; |
| 3172 | bool prevPaused = s->paused; |
| 3173 | s->enabled = (flags & STREAM_FLAG_ENABLED) == STREAM_FLAG_ENABLED; |
| 3174 | s->paused = (flags & STREAM_FLAG_PAUSED) == STREAM_FLAG_PAUSED; |
| 3175 | if (flags & STREAM_FLAG_EXTRA_EC) |
| 3176 | { |
| 3177 | if (!s->extraECEnabled) |
| 3178 | { |
| 3179 | s->extraECEnabled = true; |
| 3180 | if (s->jitterBuffer) |
| 3181 | s->jitterBuffer->SetMinPacketCount(4); |
| 3182 | } |
| 3183 | } |
| 3184 | else |
| 3185 | { |
| 3186 | if (s->extraECEnabled) |
| 3187 | { |
| 3188 | s->extraECEnabled = false; |
| 3189 | if (s->jitterBuffer) |
| 3190 | s->jitterBuffer->SetMinPacketCount(2); |
| 3191 | } |
| 3192 | } |
| 3193 | if (prevEnabled != s->enabled && s->type == StreamType::VIDEO && m_videoRenderer) |
| 3194 | m_videoRenderer->SetStreamEnabled(s->enabled); |
| 3195 | if (prevPaused != s->paused && s->type == StreamType::VIDEO && m_videoRenderer) |
| 3196 | m_videoRenderer->SetStreamPaused(s->paused); |
| 3197 | UpdateAudioOutputState(); |
| 3198 | break; |
| 3199 | } |
| 3200 | } |
| 3201 | break; |
| 3202 | } |
| 3203 | case ExtraType::STREAM_CSD: |
| 3204 | { |
| 3205 | LOGI("Received codec specific data"); |
| 3206 | std::uint8_t streamID = in.ReadUInt8(); |
| 3207 | for (std::shared_ptr<Stream>& stream : m_incomingStreams) |
| 3208 | { |
| 3209 | if (stream->id == streamID) |
| 3210 | { |
| 3211 | stream->codecSpecificData.clear(); |
| 3212 | stream->csdIsValid = false; |
| 3213 | stream->width = static_cast<unsigned int>(in.ReadUInt16()); |
| 3214 | stream->height = static_cast<unsigned int>(in.ReadUInt16()); |
| 3215 | std::size_t count = in.ReadUInt8(); |
| 3216 | for (std::size_t i = 0; i < count; i++) |
| 3217 | { |
| 3218 | std::size_t len = in.ReadUInt8(); |
| 3219 | Buffer csd(len); |
| 3220 | in.ReadBytes(*csd, len); |
| 3221 | stream->codecSpecificData.emplace_back(std::move(csd)); |
| 3222 | } |
| 3223 | break; |
| 3224 | } |
| 3225 | } |
| 3226 | break; |
| 3227 | } |
| 3228 | case ExtraType::LAN_ENDPOINT: |
| 3229 | { |
| 3230 | if (!m_allowP2p) |
| 3231 | return; |
| 3232 | LOGV("received lan endpoint (extra)"); |
| 3233 | std::uint32_t peerAddr = in.ReadUInt32(); |
| 3234 | std::uint16_t peerPort = in.ReadUInt16(); |
| 3235 | constexpr std::int64_t lanID = static_cast<std::int64_t>(FOURCC('L', 'A', 'N', '4')) << 32; |
| 3236 | if (m_currentEndpoint == lanID) |
| 3237 | m_currentEndpoint = m_preferredRelay; |
| 3238 |
| 3239 | std::uint8_t peerTag[16]; |
| 3240 | Endpoint lan(lanID, peerPort, NetworkAddress::IPv4(peerAddr), NetworkAddress::Empty(), Endpoint::Type::UDP_P2P_LAN, peerTag); |
| 3241 | MutexGuard m(m_endpointsMutex); |
| 3242 | m_endpoints[lanID] = lan; |
| 3243 | break; |
| 3244 | } |
| 3245 | case ExtraType::NETWORK_CHANGED: |
| 3246 | { |
| 3247 | LOGI("Peer network changed"); |
| 3248 | m_wasNetworkHandover = true; |
| 3249 | const Endpoint& _currentEndpoint = m_endpoints.at(m_currentEndpoint); |
| 3250 | if (_currentEndpoint.type != Endpoint::Type::UDP_RELAY && _currentEndpoint.type != Endpoint::Type::TCP_RELAY) |
| 3251 | m_currentEndpoint = m_preferredRelay; |
| 3252 | if (m_allowP2p) |
| 3253 | SendPublicEndpointsRequest(); |
| 3254 | std::uint32_t flags = in.ReadUInt32(); |
| 3255 | m_dataSavingRequestedByPeer = (flags & INIT_FLAG_DATA_SAVING_ENABLED) == INIT_FLAG_DATA_SAVING_ENABLED; |
| 3256 | UpdateDataSavingState(); |
| 3257 | UpdateAudioBitrateLimit(); |
| 3258 | ResetEndpointPingStats(); |
| 3259 | break; |
| 3260 | } |
| 3261 | case ExtraType::GROUP_CALL_KEY: |
| 3262 | { |
| 3263 | if (!m_didReceiveGroupCallKey && !m_didSendGroupCallKey) |
| 3264 | { |
| 3265 | std::uint8_t groupKey[256]; |
| 3266 | in.ReadBytes(groupKey, 256); |
| 3267 | m_messageThread.Post([this, &groupKey] |
| 3268 | { |
| 3269 | if (m_callbacks.groupCallKeyReceived) |
| 3270 | m_callbacks.groupCallKeyReceived(this, groupKey); |
| 3271 | }); |
| 3272 | m_didReceiveGroupCallKey = true; |
| 3273 | } |
| 3274 | break; |
| 3275 | } |
| 3276 | case ExtraType::REQUEST_GROUP: |
| 3277 | { |
| 3278 | if (!m_didInvokeUpgradeCallback) |
| 3279 | { |
| 3280 | m_messageThread.Post([this] |
| 3281 | { |
| 3282 | if (m_callbacks.upgradeToGroupCallRequested) |
| 3283 | m_callbacks.upgradeToGroupCallRequested(this); |
| 3284 | }); |
| 3285 | m_didInvokeUpgradeCallback = true; |
| 3286 | } |
| 3287 | break; |
| 3288 | } |
| 3289 | case ExtraType::IPV6_ENDPOINT: |
| 3290 | { |
| 3291 | if (!m_allowP2p) |
| 3292 | return; |
| 3293 | std::uint8_t _addr[16]; |
| 3294 | in.ReadBytes(_addr, 16); |
| 3295 | NetworkAddress addr = NetworkAddress::IPv6(_addr); |
| 3296 | std::uint16_t port = in.ReadUInt16(); |
| 3297 | m_peerIPv6Available = true; |
| 3298 | LOGV("Received peer IPv6 endpoint [%s]:%u", addr.ToString().c_str(), port); |
| 3299 |
| 3300 | constexpr std::int64_t p2pID = static_cast<std::int64_t>(FOURCC('P', '2', 'P', '6')) << 32; |
| 3301 |
| 3302 | Endpoint ep; |
| 3303 | ep.type = Endpoint::Type::UDP_P2P_INET; |
| 3304 | ep.port = port; |
| 3305 | ep.v6address = addr; |
| 3306 | ep.id = p2pID; |
| 3307 | m_endpoints[p2pID] = ep; |
| 3308 | if (!m_myIPv6.IsEmpty()) |
| 3309 | m_currentEndpoint = p2pID; |
| 3310 | break; |
| 3311 | } |
| 3312 | } |
| 3313 | } |
| 3314 |
| 3315 | void VoIPController::ProcessAcknowledgedOutgoingExtra(UnacknowledgedExtraData& extra) |
| 3316 | { |
| 3317 | if (extra.type == ExtraType::GROUP_CALL_KEY) |
| 3318 | { |
| 3319 | if (!m_didReceiveGroupCallKeyAck) |
| 3320 | { |
| 3321 | m_didReceiveGroupCallKeyAck = true; |
| 3322 | m_messageThread.Post([this] |
| 3323 | { |
| 3324 | if (m_callbacks.groupCallKeySent) |
| 3325 | m_callbacks.groupCallKeySent(this); |
| 3326 | }); |
| 3327 | } |
| 3328 | } |
| 3329 | } |
| 3330 |
| 3331 | Endpoint& VoIPController::GetRemoteEndpoint() |
| 3332 | { |
| 3333 | return m_endpoints.at(m_currentEndpoint); |
| 3334 | } |
| 3335 |
| 3336 | Endpoint* VoIPController::GetEndpointForPacket(const PendingOutgoingPacket& pkt) |
| 3337 | { |
| 3338 | Endpoint* endpoint = nullptr; |
| 3339 | if (pkt.endpoint != 0) |
| 3340 | { |
| 3341 | try |
| 3342 | { |
| 3343 | endpoint = &m_endpoints.at(pkt.endpoint); |
| 3344 | } |
| 3345 | catch (const std::out_of_range& exception) |
| 3346 | { |
| 3347 | LOGW("Unable to send packet via nonexistent endpoint %" PRIu64 "\nwhat():\n%s", pkt.endpoint, exception.what()); |
| 3348 | return nullptr; |
| 3349 | } |
| 3350 | } |
| 3351 | if (endpoint == nullptr) |
| 3352 | endpoint = &m_endpoints.at(m_currentEndpoint); |
| 3353 | return endpoint; |
| 3354 | } |
| 3355 |
| 3356 | bool VoIPController::SendOrEnqueuePacket(PendingOutgoingPacket pkt, bool enqueue, PacketSender* source) |
| 3357 | { |
| 3358 | ENFORCE_MSG_THREAD; |
| 3359 |
| 3360 | Endpoint* endpoint = GetEndpointForPacket(pkt); |
| 3361 | if (endpoint == nullptr) |
| 3362 | { |
| 3363 | std::abort(); |
| 3364 | return false; |
| 3365 | } |
| 3366 |
| 3367 | bool canSend; |
| 3368 | if (endpoint->type != Endpoint::Type::TCP_RELAY) |
| 3369 | { |
| 3370 | canSend = m_realUdpSocket->IsReadyToSend(); |
| 3371 | } |
| 3372 | else |
| 3373 | { |
| 3374 | if (endpoint->m_socket == nullptr) |
| 3375 | { |
| 3376 | LOGV("Connecting to %s:%u", endpoint->GetAddress().ToString().c_str(), endpoint->port); |
| 3377 | if (m_proxyProtocol == Proxy::NONE) |
| 3378 | { |
| 3379 | endpoint->m_socket = std::make_shared<NetworkSocketTCPObfuscated>(NetworkSocket::Create(NetworkProtocol::TCP)); |
| 3380 | endpoint->m_socket->Connect(endpoint->GetAddress(), endpoint->port); |
| 3381 | } |
| 3382 | else if (m_proxyProtocol == Proxy::SOCKS5) |
| 3383 | { |
| 3384 | NetworkSocket* tcp = NetworkSocket::Create(NetworkProtocol::TCP); |
| 3385 | tcp->Connect(m_resolvedProxyAddress, m_proxyPort); |
| 3386 | std::shared_ptr<NetworkSocketSOCKS5Proxy> proxy = std::make_shared<NetworkSocketSOCKS5Proxy>(tcp, nullptr, m_proxyUsername, m_proxyPassword); |
| 3387 | endpoint->m_socket = proxy; |
| 3388 | endpoint->m_socket->Connect(endpoint->GetAddress(), endpoint->port); |
| 3389 | } |
| 3390 | m_selectCanceller->CancelSelect(); |
| 3391 | } |
| 3392 | canSend = endpoint->m_socket && endpoint->m_socket->IsReadyToSend(); |
| 3393 | } |
| 3394 | if (!canSend) |
| 3395 | { |
| 3396 | if (enqueue) |
| 3397 | { |
| 3398 | LOGW("Not ready to send - enqueueing"); |
| 3399 | m_sendQueue.emplace_back(std::move(pkt)); |
| 3400 | } |
| 3401 | return false; |
| 3402 | } |
| 3403 | if ((endpoint->type == Endpoint::Type::TCP_RELAY && m_useTCP) || (endpoint->type != Endpoint::Type::TCP_RELAY && m_useUDP)) |
| 3404 | { |
| 3405 | BufferOutputStream p(1500); |
| 3406 | WritePacketHeader(pkt.seq, &p, pkt.type, static_cast<std::uint32_t>(pkt.len), source); |
| 3407 | p.WriteBytes(pkt.data); |
| 3408 | SendPacket(p.GetBuffer(), p.GetLength(), *endpoint, pkt); |
| 3409 | if (pkt.type == PktType::STREAM_DATA) |
| 3410 | { |
| 3411 | --m_unsentStreamPackets; |
| 3412 | } |
| 3413 | } |
| 3414 | return true; |
| 3415 | } |
| 3416 |
| 3417 | void VoIPController::SendPacket(std::uint8_t* data, std::size_t len, Endpoint& ep, PendingOutgoingPacket& srcPacket) |
| 3418 | { |
| 3419 | if (m_stopping) |
| 3420 | return; |
| 3421 | if (ep.type == Endpoint::Type::TCP_RELAY && !m_useTCP) |
| 3422 | return; |
| 3423 | BufferOutputStream out(len + 128); |
| 3424 | if (ep.type == Endpoint::Type::UDP_RELAY || ep.type == Endpoint::Type::TCP_RELAY) |
| 3425 | out.WriteBytes(ep.peerTag, 16); |
| 3426 | else if (m_peerVersion < 9) |
| 3427 | out.WriteBytes(m_callID, 16); |
| 3428 | if (len > 0) |
| 3429 | { |
| 3430 | if (m_useMTProto2) |
| 3431 | { |
| 3432 | BufferOutputStream inner(len + 128); |
| 3433 | std::size_t sizeSize; |
| 3434 | if (m_peerVersion >= 8 || (!m_peerVersion && m_connectionMaxLayer >= 92)) |
| 3435 | { |
| 3436 | inner.WriteUInt16(static_cast<std::uint16_t>(len)); |
| 3437 | sizeSize = 0; |
| 3438 | } |
| 3439 | else |
| 3440 | { |
| 3441 | inner.WriteUInt32(static_cast<std::uint32_t>(len)); |
| 3442 | out.WriteBytes(m_keyFingerprint, 8); |
| 3443 | sizeSize = 4; |
| 3444 | } |
| 3445 | inner.WriteBytes(data, len); |
| 3446 |
| 3447 | std::size_t padLen = 16 - inner.GetLength() % 16; |
| 3448 | if (padLen < 16) |
| 3449 | padLen += 16; |
| 3450 | std::uint8_t padding[32]; |
| 3451 | crypto.rand_bytes(padding, padLen); |
| 3452 | inner.WriteBytes(padding, padLen); |
| 3453 | assert(inner.GetLength() % 16 == 0); |
| 3454 |
| 3455 | std::uint8_t key[32], iv[32], msgKey[16]; |
| 3456 | BufferOutputStream buf(len + 32); |
| 3457 | std::size_t x = m_isOutgoing ? 0 : 8; |
| 3458 | buf.WriteBytes(m_encryptionKey + 88 + x, 32); |
| 3459 | buf.WriteBytes(inner.GetBuffer() + sizeSize, inner.GetLength() - sizeSize); |
| 3460 | std::uint8_t msgKeyLarge[32]; |
| 3461 | crypto.sha256(buf.GetBuffer(), buf.GetLength(), msgKeyLarge); |
| 3462 | std::memcpy(msgKey, msgKeyLarge + 8, 16); |
| 3463 | KDF2(msgKey, m_isOutgoing ? 0 : 8, key, iv); |
| 3464 | out.WriteBytes(msgKey, 16); |
| 3465 |
| 3466 | std::vector<std::uint8_t> aesOut(MSC_STACK_FALLBACK(inner.GetLength(), 1500)); |
| 3467 | crypto.aes_ige_encrypt(inner.GetBuffer(), aesOut.data(), inner.GetLength(), key, iv); |
| 3468 | out.WriteBytes(aesOut.data(), inner.GetLength()); |
| 3469 | } |
| 3470 | else |
| 3471 | { |
| 3472 | BufferOutputStream inner(len + 128); |
| 3473 | inner.WriteUInt32(static_cast<std::uint32_t>(len)); |
| 3474 | inner.WriteBytes(data, len); |
| 3475 | if (inner.GetLength() % 16 != 0) |
| 3476 | { |
| 3477 | std::size_t padLen = 16 - inner.GetLength() % 16; |
| 3478 | std::uint8_t padding[16]; |
| 3479 | crypto.rand_bytes(padding, padLen); |
| 3480 | inner.WriteBytes(padding, padLen); |
| 3481 | } |
| 3482 | assert(inner.GetLength() % 16 == 0); |
| 3483 | std::uint8_t key[32], iv[32], msgHash[SHA1_LENGTH]; |
| 3484 | crypto.sha1(inner.GetBuffer(), len + 4, msgHash); |
| 3485 | out.WriteBytes(m_keyFingerprint, 8); |
| 3486 | out.WriteBytes((msgHash + (SHA1_LENGTH - 16)), 16); |
| 3487 | KDF(msgHash + (SHA1_LENGTH - 16), m_isOutgoing ? 0 : 8, key, iv); |
| 3488 | std::vector<std::uint8_t> aesOut(MSC_STACK_FALLBACK(inner.GetLength(), 1500)); |
| 3489 | crypto.aes_ige_encrypt(inner.GetBuffer(), aesOut.data(), inner.GetLength(), key, iv); |
| 3490 | out.WriteBytes(aesOut.data(), inner.GetLength()); |
| 3491 | } |
| 3492 | } |
| 3493 | #ifdef LOG_PACKETS |
| 3494 | LOGV("Sending: to=%s:%u, seq=%u, length=%u, type=%s", ep.GetAddress().ToString().c_str(), ep.port, srcPacket.seq, (unsigned int)out.GetLength(), GetPacketTypeString(srcPacket.type).c_str()); |
| 3495 | #endif |
| 3496 |
| 3497 | m_rawSendQueue.Put(RawPendingOutgoingPacket |
| 3498 | { |
| 3499 | NetworkPacket |
| 3500 | { |
| 3501 | Buffer(std::move(out)), |
| 3502 | ep.GetAddress(), |
| 3503 | ep.port, |
| 3504 | ep.type == Endpoint::Type::TCP_RELAY ? NetworkProtocol::TCP : NetworkProtocol::UDP |
| 3505 | }, |
| 3506 | ep.type == Endpoint::Type::TCP_RELAY ? ep.m_socket : nullptr |
| 3507 | }); |
| 3508 | } |
| 3509 |
| 3510 | void VoIPController::ActuallySendPacket(NetworkPacket pkt, Endpoint& ep) |
| 3511 | { |
| 3512 | if (IS_MOBILE_NETWORK(m_networkType)) |
| 3513 | m_stats.bytesSentMobile += static_cast<std::uint64_t>(pkt.data.Length()); |
| 3514 | else |
| 3515 | m_stats.bytesSentWifi += static_cast<std::uint64_t>(pkt.data.Length()); |
| 3516 | if (ep.type == Endpoint::Type::TCP_RELAY) |
| 3517 | { |
| 3518 | if (ep.m_socket != nullptr && !ep.m_socket->IsFailed()) |
| 3519 | { |
| 3520 | ep.m_socket->Send(std::move(pkt)); |
| 3521 | } |
| 3522 | } |
| 3523 | else |
| 3524 | { |
| 3525 | m_udpSocket->Send(std::move(pkt)); |
| 3526 | } |
| 3527 | } |
| 3528 |
| 3529 | std::string VoIPController::NetworkTypeToString(NetType type) |
| 3530 | { |
| 3531 | switch (type) |
| 3532 | { |
| 3533 | case NetType::WIFI: |
| 3534 | return "wifi"; |
| 3535 | case NetType::GPRS: |
| 3536 | return "gprs"; |
| 3537 | case NetType::EDGE: |
| 3538 | return "edge"; |
| 3539 | case NetType::THREE_G: |
| 3540 | return "3g"; |
| 3541 | case NetType::HSPA: |
| 3542 | return "hspa"; |
| 3543 | case NetType::LTE: |
| 3544 | return "lte"; |
| 3545 | case NetType::ETHERNET: |
| 3546 | return "ethernet"; |
| 3547 | case NetType::OTHER_HIGH_SPEED: |
| 3548 | return "other_high_speed"; |
| 3549 | case NetType::OTHER_LOW_SPEED: |
| 3550 | return "other_low_speed"; |
| 3551 | case NetType::DIALUP: |
| 3552 | return "dialup"; |
| 3553 | case NetType::OTHER_MOBILE: |
| 3554 | return "other_mobile"; |
| 3555 | case NetType::UNKNOWN: |
| 3556 | return "unknown"; |
| 3557 | } |
| 3558 | throw std::invalid_argument("NetType " + std::to_string(static_cast<int>(type)) + " is not one of enum values!"); |
| 3559 | } |
| 3560 |
| 3561 | std::string VoIPController::GetPacketTypeString(PktType type) |
| 3562 | { |
| 3563 | switch (type) |
| 3564 | { |
| 3565 | case PktType::INIT: |
| 3566 | return "init"; |
| 3567 | case PktType::INIT_ACK: |
| 3568 | return "init_ack"; |
| 3569 | case PktType::STREAM_STATE: |
| 3570 | return "stream_state"; |
| 3571 | case PktType::STREAM_DATA: |
| 3572 | return "stream_data"; |
| 3573 | case PktType::PING: |
| 3574 | return "ping"; |
| 3575 | case PktType::PONG: |
| 3576 | return "pong"; |
| 3577 | case PktType::LAN_ENDPOINT: |
| 3578 | return "lan_endpoint"; |
| 3579 | case PktType::NETWORK_CHANGED: |
| 3580 | return "network_changed"; |
| 3581 | case PktType::NOP: |
| 3582 | return "nop"; |
| 3583 | case PktType::STREAM_EC: |
| 3584 | return "stream_ec"; |
| 3585 | case PktType::UPDATE_STREAMS: |
| 3586 | return "update_streams"; |
| 3587 | case PktType::STREAM_DATA_X2: |
| 3588 | return "stream_data_x2"; |
| 3589 | case PktType::STREAM_DATA_X3: |
| 3590 | return "stream_data_x3"; |
| 3591 | case PktType::SWITCH_PREF_RELAY: |
| 3592 | return "switch_pref_relay"; |
| 3593 | case PktType::SWITCH_TO_P2P: |
| 3594 | return "switch_to_p2p"; |
| 3595 | } |
| 3596 | return std::string("unknown " + std::to_string(static_cast<std::uint8_t>(type))); |
| 3597 | } |
| 3598 |
| 3599 | void VoIPController::AddIPv6Relays() |
| 3600 | { |
| 3601 | if (!m_myIPv6.IsEmpty() && !m_didAddIPv6Relays) |
| 3602 | { |
| 3603 | std::unordered_map<std::string, std::vector<Endpoint>> endpointsByAddress; |
| 3604 | for (auto& [_, endpoint] : m_endpoints) |
| 3605 | { |
| 3606 | if ((endpoint.type == Endpoint::Type::UDP_RELAY || endpoint.type == Endpoint::Type::TCP_RELAY) |
| 3607 | && !endpoint.v6address.IsEmpty() && !endpoint.address.IsEmpty()) |
| 3608 | { |
| 3609 | endpointsByAddress[endpoint.v6address.ToString()].emplace_back(endpoint); |
| 3610 | } |
| 3611 | } |
| 3612 | MutexGuard m(m_endpointsMutex); |
| 3613 | for (auto& [_, endpoints] : endpointsByAddress) |
| 3614 | { |
| 3615 | for (Endpoint& endpoint : endpoints) |
| 3616 | { |
| 3617 | m_didAddIPv6Relays = true; |
| 3618 | endpoint.address = NetworkAddress::Empty(); |
| 3619 | endpoint.id = endpoint.id ^ (static_cast<std::int64_t>(FOURCC('I', 'P', 'v', '6')) << 32); |
| 3620 | endpoint.m_averageRTT = 0; |
| 3621 | endpoint.m_lastPingSeq = 0; |
| 3622 | endpoint.m_lastPingTime = 0; |
| 3623 | endpoint.m_rtts.Reset(); |
| 3624 | endpoint.m_udpPongCount = 0; |
| 3625 | m_endpoints[endpoint.id] = endpoint; |
| 3626 | LOGD("Adding IPv6-only endpoint [%s]:%u", endpoint.v6address.ToString().c_str(), endpoint.port); |
| 3627 | } |
| 3628 | } |
| 3629 | } |
| 3630 | } |
| 3631 |
| 3632 | void VoIPController::AddTCPRelays() |
| 3633 | { |
| 3634 |
| 3635 | if (!m_didAddTcpRelays) |
| 3636 | { |
| 3637 | bool wasSetCurrentToTCP = m_setCurrentEndpointToTCP; |
| 3638 | LOGV("Adding TCP relays"); |
| 3639 | std::vector<Endpoint> relays; |
| 3640 | for (auto& [_, endpoint] : m_endpoints) |
| 3641 | { |
| 3642 | if (endpoint.type != Endpoint::Type::UDP_RELAY) |
| 3643 | continue; |
| 3644 | if (wasSetCurrentToTCP && !m_useUDP) |
| 3645 | { |
| 3646 | endpoint.m_rtts.Reset(); |
| 3647 | endpoint.m_averageRTT = 0; |
| 3648 | endpoint.m_lastPingSeq = 0; |
| 3649 | } |
| 3650 | Endpoint tcpRelay(endpoint); |
| 3651 | tcpRelay.type = Endpoint::Type::TCP_RELAY; |
| 3652 | tcpRelay.m_averageRTT = 0; |
| 3653 | tcpRelay.m_lastPingSeq = 0; |
| 3654 | tcpRelay.m_lastPingTime = 0; |
| 3655 | tcpRelay.m_rtts.Reset(); |
| 3656 | tcpRelay.m_udpPongCount = 0; |
| 3657 | tcpRelay.id = tcpRelay.id ^ (static_cast<std::int64_t>(FOURCC('T', 'C', 'P', 0)) << 32); |
| 3658 | if (m_setCurrentEndpointToTCP && m_endpoints.at(m_currentEndpoint).type != Endpoint::Type::TCP_RELAY) |
| 3659 | { |
| 3660 | LOGV("Setting current endpoint to TCP"); |
| 3661 | m_setCurrentEndpointToTCP = false; |
| 3662 | m_currentEndpoint = tcpRelay.id; |
| 3663 | m_preferredRelay = tcpRelay.id; |
| 3664 | } |
| 3665 | relays.emplace_back(tcpRelay); |
| 3666 | } |
| 3667 | MutexGuard m(m_endpointsMutex); |
| 3668 | for (Endpoint& e : relays) |
| 3669 | { |
| 3670 | m_endpoints[e.id] = e; |
| 3671 | } |
| 3672 | m_didAddTcpRelays = true; |
| 3673 | } |
| 3674 | } |
| 3675 |
| 3676 | #if defined(__APPLE__) |
| 3677 | static void initMachTimestart() |
| 3678 | { |
| 3679 | mach_timebase_info_data_t tb = {0, 0}; |
| 3680 | mach_timebase_info(&tb); |
| 3681 | VoIPController::machTimebase = tb.numer; |
| 3682 | VoIPController::machTimebase /= tb.denom; |
| 3683 | VoIPController::machTimestart = mach_absolute_time(); |
| 3684 | } |
| 3685 | #endif |
| 3686 |
| 3687 | double VoIPController::GetCurrentTime() |
| 3688 | { |
| 3689 | #if defined(__linux__) |
| 3690 | struct timespec ts; |
| 3691 | clock_gettime(CLOCK_MONOTONIC, &ts); |
| 3692 | return ts.tv_sec + ts.tv_nsec / 1000000000.0; |
| 3693 | #elif defined(__APPLE__) |
| 3694 | static pthread_once_t token = PTHREAD_ONCE_INIT; |
| 3695 | pthread_once(&token, &initMachTimestart); |
| 3696 | return (mach_absolute_time() - machTimestart) * machTimebase / 1000000000.0f; |
| 3697 | #elif defined(_WIN32) |
| 3698 | if (!didInitWin32TimeScale) |
| 3699 | { |
| 3700 | LARGE_INTEGER scale; |
| 3701 | QueryPerformanceFrequency(&scale); |
| 3702 | win32TimeScale = scale.QuadPart; |
| 3703 | didInitWin32TimeScale = true; |
| 3704 | } |
| 3705 | LARGE_INTEGER t; |
| 3706 | QueryPerformanceCounter(&t); |
| 3707 | return (double)t.QuadPart / (double)win32TimeScale; |
| 3708 | #endif |
| 3709 | } |
| 3710 |
| 3711 | void VoIPController::KDF(std::uint8_t* msgKey, std::size_t x, std::uint8_t* aesKey, std::uint8_t* aesIv) |
| 3712 | { |
| 3713 | std::uint8_t sA[SHA1_LENGTH], sB[SHA1_LENGTH], sC[SHA1_LENGTH], sD[SHA1_LENGTH]; |
| 3714 | BufferOutputStream buf(128); |
| 3715 | buf.WriteBytes(msgKey, 16); |
| 3716 | buf.WriteBytes(m_encryptionKey + x, 32); |
| 3717 | crypto.sha1(buf.GetBuffer(), buf.GetLength(), sA); |
| 3718 | buf.Reset(); |
| 3719 | buf.WriteBytes(m_encryptionKey + 32 + x, 16); |
| 3720 | buf.WriteBytes(msgKey, 16); |
| 3721 | buf.WriteBytes(m_encryptionKey + 48 + x, 16); |
| 3722 | crypto.sha1(buf.GetBuffer(), buf.GetLength(), sB); |
| 3723 | buf.Reset(); |
| 3724 | buf.WriteBytes(m_encryptionKey + 64 + x, 32); |
| 3725 | buf.WriteBytes(msgKey, 16); |
| 3726 | crypto.sha1(buf.GetBuffer(), buf.GetLength(), sC); |
| 3727 | buf.Reset(); |
| 3728 | buf.WriteBytes(msgKey, 16); |
| 3729 | buf.WriteBytes(m_encryptionKey + 96 + x, 32); |
| 3730 | crypto.sha1(buf.GetBuffer(), buf.GetLength(), sD); |
| 3731 | buf.Reset(); |
| 3732 | buf.WriteBytes(sA, 8); |
| 3733 | buf.WriteBytes(sB + 8, 12); |
| 3734 | buf.WriteBytes(sC + 4, 12); |
| 3735 | assert(buf.GetLength() == 32); |
| 3736 | std::memcpy(aesKey, buf.GetBuffer(), 32); |
| 3737 | buf.Reset(); |
| 3738 | buf.WriteBytes(sA + 8, 12); |
| 3739 | buf.WriteBytes(sB, 8); |
| 3740 | buf.WriteBytes(sC + 16, 4); |
| 3741 | buf.WriteBytes(sD, 8); |
| 3742 | assert(buf.GetLength() == 32); |
| 3743 | std::memcpy(aesIv, buf.GetBuffer(), 32); |
| 3744 | } |
| 3745 |
| 3746 | void VoIPController::KDF2(std::uint8_t* msgKey, std::size_t x, std::uint8_t* aesKey, std::uint8_t* aesIv) |
| 3747 | { |
| 3748 | std::uint8_t sA[32], sB[32]; |
| 3749 | BufferOutputStream buf(128); |
| 3750 | buf.WriteBytes(msgKey, 16); |
| 3751 | buf.WriteBytes(m_encryptionKey + x, 36); |
| 3752 | crypto.sha256(buf.GetBuffer(), buf.GetLength(), sA); |
| 3753 | buf.Reset(); |
| 3754 | buf.WriteBytes(m_encryptionKey + 40 + x, 36); |
| 3755 | buf.WriteBytes(msgKey, 16); |
| 3756 | crypto.sha256(buf.GetBuffer(), buf.GetLength(), sB); |
| 3757 | buf.Reset(); |
| 3758 | buf.WriteBytes(sA, 8); |
| 3759 | buf.WriteBytes(sB + 8, 16); |
| 3760 | buf.WriteBytes(sA + 24, 8); |
| 3761 | std::memcpy(aesKey, buf.GetBuffer(), 32); |
| 3762 | buf.Reset(); |
| 3763 | buf.WriteBytes(sB, 8); |
| 3764 | buf.WriteBytes(sA + 8, 16); |
| 3765 | buf.WriteBytes(sB + 24, 8); |
| 3766 | std::memcpy(aesIv, buf.GetBuffer(), 32); |
| 3767 | } |
| 3768 |
| 3769 | void VoIPController::SendPublicEndpointsRequest(const Endpoint& relay) |
| 3770 | { |
| 3771 | if (!m_useUDP) |
| 3772 | return; |
| 3773 | LOGD("Sending public endpoints request to %s:%d", relay.address.ToString().c_str(), relay.port); |
| 3774 | m_publicEndpointsReqTime = GetCurrentTime(); |
| 3775 | m_waitingForRelayPeerInfo = true; |
| 3776 | Buffer buf(32); |
| 3777 | std::memcpy(*buf, relay.peerTag, 16); |
| 3778 | std::memset(*buf + 16, 0xFF, 16); |
| 3779 | m_udpSocket->Send(NetworkPacket |
| 3780 | { |
| 3781 | std::move(buf), |
| 3782 | relay.address, |
| 3783 | relay.port, |
| 3784 | NetworkProtocol::UDP |
| 3785 | }); |
| 3786 | } |
| 3787 |
| 3788 | Endpoint& VoIPController::GetEndpointByType(Endpoint::Type type) |
| 3789 | { |
| 3790 | if (type == Endpoint::Type::UDP_RELAY && m_preferredRelay) |
| 3791 | return m_endpoints.at(m_preferredRelay); |
| 3792 | for (auto& [_, endpoint] : m_endpoints) |
| 3793 | if (endpoint.type == type) |
| 3794 | return endpoint; |
| 3795 |
| 3796 | throw std::out_of_range("no endpoint"); |
| 3797 | } |
| 3798 |
| 3799 | void VoIPController::SendPacketReliably(PktType type, std::uint8_t* data, std::size_t len, double retryInterval, double timeout) |
| 3800 | { |
| 3801 | ENFORCE_MSG_THREAD; |
| 3802 |
| 3803 | LOGD("Send reliably, type=%u, len=%u, retry=%.3f, timeout=%.3f", static_cast<std::uint8_t>(type), unsigned(len), retryInterval, timeout); |
| 3804 | QueuedPacket pkt; |
| 3805 | if (data) |
| 3806 | { |
| 3807 | Buffer b(len); |
| 3808 | b.CopyFrom(data, 0, len); |
| 3809 | pkt.data = std::move(b); |
| 3810 | } |
| 3811 | pkt.type = type; |
| 3812 | pkt.retryInterval = retryInterval; |
| 3813 | pkt.timeout = timeout; |
| 3814 | pkt.firstSentTime = 0; |
| 3815 | pkt.lastSentTime = 0; |
| 3816 | m_queuedPackets.emplace_back(std::move(pkt)); |
| 3817 | m_messageThread.Post(std::bind(&VoIPController::UpdateQueuedPackets, this)); |
| 3818 | if (timeout > 0.0) |
| 3819 | { |
| 3820 | m_messageThread.Post(std::bind(&VoIPController::UpdateQueuedPackets, this), timeout); |
| 3821 | } |
| 3822 | } |
| 3823 |
| 3824 | void VoIPController::SendExtra(Buffer& data, ExtraType type) |
| 3825 | { |
| 3826 | ENFORCE_MSG_THREAD; |
| 3827 |
| 3828 | LOGV("Sending extra type %u length %u", static_cast<std::uint8_t>(type), static_cast<unsigned int>(data.Length())); |
| 3829 | for (UnacknowledgedExtraData& extraData : m_currentExtras) |
| 3830 | { |
| 3831 | if (extraData.type == type) |
| 3832 | { |
| 3833 | extraData.firstContainingSeq = 0; |
| 3834 | extraData.data = std::move(data); |
| 3835 | return; |
| 3836 | } |
| 3837 | } |
| 3838 | UnacknowledgedExtraData xd = { type, std::move(data), 0 }; |
| 3839 | m_currentExtras.emplace_back(std::move(xd)); |
| 3840 | } |
| 3841 |
| 3842 | void VoIPController::DebugCtl(int request, int param) |
| 3843 | { |
| 3844 | } |
| 3845 |
| 3846 | void VoIPController::SendUdpPing(Endpoint& endpoint) |
| 3847 | { |
| 3848 | if (endpoint.type != Endpoint::Type::UDP_RELAY) |
| 3849 | return; |
| 3850 | BufferOutputStream p(1024); |
| 3851 | p.WriteBytes(endpoint.peerTag, 16); |
| 3852 | p.WriteInt32(-1); |
| 3853 | p.WriteInt32(-1); |
| 3854 | p.WriteInt32(-1); |
| 3855 | p.WriteInt32(-2); |
| 3856 | std::int64_t id; |
| 3857 | crypto.rand_bytes(reinterpret_cast<std::uint8_t*>(&id), 8); |
| 3858 | p.WriteInt64(id); |
| 3859 | endpoint.m_udpPingTimes[id] = GetCurrentTime(); |
| 3860 | m_udpSocket->Send(NetworkPacket { |
| 3861 | Buffer(std::move(p)), |
| 3862 | endpoint.GetAddress(), |
| 3863 | endpoint.port, |
| 3864 | NetworkProtocol::UDP}); |
| 3865 | endpoint.m_totalUdpPings++; |
| 3866 | LOGV("Sending UDP ping to %s:%d, id %" PRId64, endpoint.GetAddress().ToString().c_str(), endpoint.port, id); |
| 3867 | } |
| 3868 |
| 3869 | void VoIPController::ResetUdpAvailability() |
| 3870 | { |
| 3871 | ENFORCE_MSG_THREAD; |
| 3872 |
| 3873 | LOGI("Resetting UDP availability"); |
| 3874 | if (m_udpPingTimeoutID != MessageThread::INVALID_ID) |
| 3875 | { |
| 3876 | m_messageThread.Cancel(m_udpPingTimeoutID); |
| 3877 | } |
| 3878 | { |
| 3879 | for (std::pair<const std::int64_t, Endpoint>& e : m_endpoints) |
| 3880 | { |
| 3881 | e.second.m_udpPongCount = 0; |
| 3882 | e.second.m_udpPingTimes.clear(); |
| 3883 | } |
| 3884 | } |
| 3885 | m_udpPingCount = 0; |
| 3886 | m_udpConnectivityState = UdpState::PING_PENDING; |
| 3887 | m_udpPingTimeoutID = m_messageThread.Post(std::bind(&VoIPController::SendUdpPings, this), 0.0, 0.5); |
| 3888 | } |
| 3889 |
| 3890 | void VoIPController::ResetEndpointPingStats() |
| 3891 | { |
| 3892 | ENFORCE_MSG_THREAD; |
| 3893 |
| 3894 | for (std::pair<const std::int64_t, Endpoint>& e : m_endpoints) |
| 3895 | { |
| 3896 | e.second.m_averageRTT = 0.0; |
| 3897 | e.second.m_rtts.Reset(); |
| 3898 | } |
| 3899 | } |
| 3900 |
| 3901 | #pragma mark - Video |
| 3902 |
| 3903 | void VoIPController::SetVideoSource(video::VideoSource* source) |
| 3904 | { |
| 3905 | /*std::shared_ptr<Stream> stream = GetStreamByType(StreamType::VIDEO, true); |
| 3906 | if (stream == nullptr) |
| 3907 | { |
| 3908 | LOGE("Can't set video source when there is no outgoing video stream"); |
| 3909 | return; |
| 3910 | } |
| 3911 |
| 3912 | if (source != nullptr) |
| 3913 | { |
| 3914 | if (!stream->enabled) |
| 3915 | { |
| 3916 | stream->enabled = true; |
| 3917 | m_messageThread.Post([this, stream] { SendStreamFlags(*stream); }); |
| 3918 | } |
| 3919 |
| 3920 | if (m_videoPacketSender == nullptr) |
| 3921 | m_videoPacketSender = new video::VideoPacketSender(this, source, stream); |
| 3922 | else |
| 3923 | m_videoPacketSender->SetSource(source); |
| 3924 | } |
| 3925 | else |
| 3926 | { |
| 3927 | if (stream->enabled) |
| 3928 | { |
| 3929 | stream->enabled = false; |
| 3930 | m_messageThread.Post([this, stream] { SendStreamFlags(*stream); }); |
| 3931 | } |
| 3932 | if (m_videoPacketSender != nullptr) |
| 3933 | { |
| 3934 | m_videoPacketSender->SetSource(nullptr); |
| 3935 | } |
| 3936 | }*/ |
| 3937 | } |
| 3938 |
| 3939 | void VoIPController::SetVideoRenderer(video::VideoRenderer* renderer) |
| 3940 | { |
| 3941 | m_videoRenderer = renderer; |
| 3942 | } |
| 3943 |
| 3944 | void VoIPController::SetVideoCodecSpecificData(const std::vector<Buffer>& data) |
| 3945 | { |
| 3946 | m_outgoingStreams[1]->codecSpecificData.clear(); |
| 3947 | for (const Buffer& csd : data) |
| 3948 | { |
| 3949 | m_outgoingStreams[1]->codecSpecificData.emplace_back(Buffer::CopyOf(csd)); |
| 3950 | } |
| 3951 | LOGI("Set outgoing video stream CSD"); |
| 3952 | } |
| 3953 |
| 3954 | void VoIPController::SendVideoFrame(const Buffer& frame, std::uint32_t flags, std::uint32_t rotation) |
| 3955 | { |
| 3956 | std::shared_ptr<Stream> stream = GetStreamByType(StreamType::VIDEO, true); |
| 3957 | if (stream != nullptr) |
| 3958 | { |
| 3959 | } |
| 3960 | } |
| 3961 |
| 3962 | void VoIPController::ProcessIncomingVideoFrame(Buffer frame, std::uint32_t pts, bool keyframe, std::uint16_t rotation) |
| 3963 | { |
| 3964 | if (frame.Length() == 0) |
| 3965 | { |
| 3966 | LOGE("EMPTY FRAME"); |
| 3967 | } |
| 3968 | if (m_videoRenderer != nullptr) |
| 3969 | { |
| 3970 | std::shared_ptr<Stream> stream = GetStreamByType(StreamType::VIDEO, false); |
| 3971 | std::size_t offset = 0; |
| 3972 | if (keyframe) |
| 3973 | { |
| 3974 | BufferInputStream in(frame); |
| 3975 | std::uint16_t width = in.ReadUInt16(); |
| 3976 | std::uint16_t height = in.ReadUInt16(); |
| 3977 | std::uint8_t sizeAndFlag = in.ReadUInt8(); |
| 3978 | int size = sizeAndFlag & 0x0F; |
| 3979 | bool reset = (sizeAndFlag & 0x80) == 0x80; |
| 3980 | if (reset || !stream->csdIsValid || stream->width != width || stream->height != height) |
| 3981 | { |
| 3982 | stream->width = width; |
| 3983 | stream->height = height; |
| 3984 | stream->codecSpecificData.clear(); |
| 3985 | for (int i = 0; i < size; ++i) |
| 3986 | { |
| 3987 | std::size_t len = in.ReadUInt8(); |
| 3988 | Buffer b(len); |
| 3989 | in.ReadBytes(b); |
| 3990 | stream->codecSpecificData.emplace_back(std::move(b)); |
| 3991 | } |
| 3992 | stream->csdIsValid = false; |
| 3993 | } |
| 3994 | else |
| 3995 | { |
| 3996 | for (int i = 0; i < size; i++) |
| 3997 | { |
| 3998 | std::size_t len = in.ReadUInt8(); |
| 3999 | in.Seek(in.GetOffset() + len); |
| 4000 | } |
| 4001 | } |
| 4002 | offset = in.GetOffset(); |
| 4003 | } |
| 4004 | if (!stream->csdIsValid && stream->width && stream->height) |
| 4005 | { |
| 4006 | m_videoRenderer->Reset(stream->codec, stream->width, stream->height, stream->codecSpecificData); |
| 4007 | stream->csdIsValid = true; |
| 4008 | } |
| 4009 | if (m_lastReceivedVideoFrameNumber == UINT32_MAX || m_lastReceivedVideoFrameNumber == pts - 1 || keyframe) |
| 4010 | { |
| 4011 | m_lastReceivedVideoFrameNumber = pts; |
| 4012 | //LOGV("3 before decode %u", (unsigned int)frame.Length()); |
| 4013 | if (stream->rotation != rotation) |
| 4014 | { |
| 4015 | stream->rotation = rotation; |
| 4016 | m_videoRenderer->SetRotation(rotation); |
| 4017 | } |
| 4018 | if (offset == 0) |
| 4019 | { |
| 4020 | m_videoRenderer->DecodeAndDisplay(std::move(frame), pts); |
| 4021 | } |
| 4022 | else |
| 4023 | { |
| 4024 | m_videoRenderer->DecodeAndDisplay(Buffer::CopyOf(frame, offset, frame.Length() - offset), pts); |
| 4025 | } |
| 4026 | } |
| 4027 | else |
| 4028 | { |
| 4029 | LOGW("Skipping non-keyframe after packet loss..."); |
| 4030 | } |
| 4031 | } |
| 4032 | } |
| 4033 |
| 4034 | void VoIPController::SetupOutgoingVideoStream() |
| 4035 | { |
| 4036 | std::vector<std::uint32_t> myEncoders = video::VideoSource::GetAvailableEncoders(); |
| 4037 | std::shared_ptr<Stream> vstm = std::make_shared<Stream>(); |
| 4038 | vstm->id = 2; |
| 4039 | vstm->type = StreamType::VIDEO; |
| 4040 |
| 4041 | if (std::find(myEncoders.begin(), myEncoders.end(), CODEC_HEVC) != myEncoders.end() && |
| 4042 | std::find(m_peerVideoDecoders.begin(), m_peerVideoDecoders.end(), CODEC_HEVC) != m_peerVideoDecoders.end()) |
| 4043 | { |
| 4044 | vstm->codec = CODEC_HEVC; |
| 4045 | } |
| 4046 | else if (std::find(myEncoders.begin(), myEncoders.end(), CODEC_AVC) != myEncoders.end() && |
| 4047 | std::find(m_peerVideoDecoders.begin(), m_peerVideoDecoders.end(), CODEC_AVC) != m_peerVideoDecoders.end()) |
| 4048 | { |
| 4049 | vstm->codec = CODEC_AVC; |
| 4050 | } |
| 4051 | else if (std::find(myEncoders.begin(), myEncoders.end(), CODEC_VP8) != myEncoders.end() && |
| 4052 | std::find(m_peerVideoDecoders.begin(), m_peerVideoDecoders.end(), CODEC_VP8) != m_peerVideoDecoders.end()) |
| 4053 | { |
| 4054 | vstm->codec = CODEC_VP8; |
| 4055 | } |
| 4056 | else |
| 4057 | { |
| 4058 | LOGW("Can't setup outgoing video stream: no codecs in common"); |
| 4059 | return; |
| 4060 | } |
| 4061 |
| 4062 | vstm->enabled = false; |
| 4063 | m_outgoingStreams.emplace_back(vstm); |
| 4064 | } |
| 4065 |
| 4066 | #pragma mark - Timer methods |
| 4067 |
| 4068 | void VoIPController::SendUdpPings() |
| 4069 | { |
| 4070 | LOGW("Send udp pings"); |
| 4071 | ENFORCE_MSG_THREAD; |
| 4072 |
| 4073 | for (std::pair<const std::int64_t, Endpoint>& e : m_endpoints) |
| 4074 | { |
| 4075 | if (e.second.type == Endpoint::Type::UDP_RELAY) |
| 4076 | { |
| 4077 | SendUdpPing(e.second); |
| 4078 | } |
| 4079 | } |
| 4080 | if (m_udpConnectivityState == UdpState::UNKNOWN || m_udpConnectivityState == UdpState::PING_PENDING) |
| 4081 | m_udpConnectivityState = UdpState::PING_SENT; |
| 4082 | m_udpPingCount++; |
| 4083 | if (m_udpPingCount == 4 || m_udpPingCount == 10) |
| 4084 | { |
| 4085 | m_messageThread.CancelSelf(); |
| 4086 | m_udpPingTimeoutID = m_messageThread.Post(std::bind(&VoIPController::EvaluateUdpPingResults, this), 1.0); |
| 4087 | } |
| 4088 | } |
| 4089 |
| 4090 | void VoIPController::EvaluateUdpPingResults() |
| 4091 | { |
| 4092 | double avgPongs = 0; |
| 4093 | int count = 0; |
| 4094 | for (auto& [_, endpoint] : m_endpoints) |
| 4095 | { |
| 4096 | if (endpoint.type == Endpoint::Type::UDP_RELAY) |
| 4097 | { |
| 4098 | if (endpoint.m_udpPongCount > 0) |
| 4099 | { |
| 4100 | avgPongs += endpoint.m_udpPongCount; |
| 4101 | ++count; |
| 4102 | } |
| 4103 | } |
| 4104 | } |
| 4105 | if (count > 0) |
| 4106 | avgPongs /= count; |
| 4107 | else |
| 4108 | avgPongs = 0.0; |
| 4109 | LOGI("UDP ping reply count: %.2f", avgPongs); |
| 4110 | if (avgPongs == 0.0 && m_proxyProtocol == Proxy::SOCKS5 && m_udpSocket != m_realUdpSocket) |
| 4111 | { |
| 4112 | LOGI("Proxy does not let UDP through, closing proxy connection and using UDP directly"); |
| 4113 | NetworkSocket* proxySocket = m_udpSocket; |
| 4114 | proxySocket->Close(); |
| 4115 | m_udpSocket = m_realUdpSocket; |
| 4116 | m_selectCanceller->CancelSelect(); |
| 4117 | delete proxySocket; |
| 4118 | m_proxySupportsUDP = false; |
| 4119 | ResetUdpAvailability(); |
| 4120 | return; |
| 4121 | } |
| 4122 | bool configUseTCP = ServerConfig::GetSharedInstance()->GetBoolean("use_tcp", true); |
| 4123 | if (configUseTCP) |
| 4124 | { |
| 4125 | if (avgPongs == 0.0 || (m_udpConnectivityState == UdpState::BAD && avgPongs < 7.0)) |
| 4126 | { |
| 4127 | if (m_needRateFlags & NEED_RATE_FLAG_UDP_NA) |
| 4128 | m_needRate = true; |
| 4129 | m_udpConnectivityState = UdpState::NOT_AVAILABLE; |
| 4130 | m_useTCP = true; |
| 4131 | m_useUDP = avgPongs > 1.0; |
| 4132 | if (m_endpoints.at(m_currentEndpoint).type != Endpoint::Type::TCP_RELAY) |
| 4133 | m_setCurrentEndpointToTCP = true; |
| 4134 | AddTCPRelays(); |
| 4135 | m_waitingForRelayPeerInfo = false; |
| 4136 | } |
| 4137 | else if (avgPongs < 3.0) |
| 4138 | { |
| 4139 | if (m_needRateFlags & NEED_RATE_FLAG_UDP_BAD) |
| 4140 | m_needRate = true; |
| 4141 | m_udpConnectivityState = UdpState::BAD; |
| 4142 | m_useTCP = true; |
| 4143 | m_setCurrentEndpointToTCP = true; |
| 4144 | AddTCPRelays(); |
| 4145 | m_udpPingTimeoutID = m_messageThread.Post(std::bind(&VoIPController::SendUdpPings, this), 0.5, 0.5); |
| 4146 | } |
| 4147 | else |
| 4148 | { |
| 4149 | m_udpPingTimeoutID = MessageThread::INVALID_ID; |
| 4150 | m_udpConnectivityState = UdpState::AVAILABLE; |
| 4151 | } |
| 4152 | } |
| 4153 | else |
| 4154 | { |
| 4155 | m_udpPingTimeoutID = MessageThread::INVALID_ID; |
| 4156 | m_udpConnectivityState = UdpState::NOT_AVAILABLE; |
| 4157 | } |
| 4158 | } |
| 4159 |
| 4160 | void VoIPController::SendRelayPings() |
| 4161 | { |
| 4162 | ENFORCE_MSG_THREAD; |
| 4163 |
| 4164 | if ((m_state == State::ESTABLISHED || m_state == State::RECONNECTING) && m_endpoints.size() > 1) |
| 4165 | { |
| 4166 | Endpoint* _preferredRelay = &m_endpoints.at(m_preferredRelay); |
| 4167 | Endpoint* _currentEndpoint = &m_endpoints.at(m_currentEndpoint); |
| 4168 | Endpoint* minPingRelay = _preferredRelay; |
| 4169 | double minPing = _preferredRelay->m_averageRTT * (_preferredRelay->type == Endpoint::Type::TCP_RELAY ? 2 : 1); |
| 4170 | if (minPing == 0.0) // force the switch to an available relay, if any |
| 4171 | minPing = std::numeric_limits<double>::max(); |
| 4172 | for (std::pair<const std::int64_t, Endpoint>& _endpoint : m_endpoints) |
| 4173 | { |
| 4174 | Endpoint& endpoint = _endpoint.second; |
| 4175 | if (endpoint.type == Endpoint::Type::TCP_RELAY && !m_useTCP) |
| 4176 | continue; |
| 4177 | if (endpoint.type == Endpoint::Type::UDP_RELAY && !m_useUDP) |
| 4178 | continue; |
| 4179 | if (GetCurrentTime() - endpoint.m_lastPingTime >= 10) |
| 4180 | { |
| 4181 | LOGV("Sending ping to %s", endpoint.GetAddress().ToString().c_str()); |
| 4182 | SendOrEnqueuePacket(PendingOutgoingPacket |
| 4183 | { |
| 4184 | /*.seq=*/ (endpoint.m_lastPingSeq = GenerateOutSeq()), |
| 4185 | /*.type=*/ PktType::PING, |
| 4186 | /*.len=*/ 0, |
| 4187 | /*.data=*/ Buffer(), |
| 4188 | /*.endpoint=*/endpoint.id |
| 4189 | }); |
| 4190 | endpoint.m_lastPingTime = GetCurrentTime(); |
| 4191 | } |
| 4192 | if ((m_useUDP && endpoint.type == Endpoint::Type::UDP_RELAY) || (m_useTCP && endpoint.type == Endpoint::Type::TCP_RELAY)) |
| 4193 | { |
| 4194 | double k = endpoint.type == Endpoint::Type::UDP_RELAY ? 1 : 2; |
| 4195 | if (endpoint.m_averageRTT > 0 && endpoint.m_averageRTT * k < minPing * m_relaySwitchThreshold) |
| 4196 | { |
| 4197 | minPing = endpoint.m_averageRTT * k; |
| 4198 | minPingRelay = &endpoint; |
| 4199 | } |
| 4200 | } |
| 4201 | } |
| 4202 | if (minPingRelay->id != m_preferredRelay) |
| 4203 | { |
| 4204 | m_preferredRelay = minPingRelay->id; |
| 4205 | _preferredRelay = minPingRelay; |
| 4206 | LOGV("set preferred relay to %s", _preferredRelay->address.ToString().c_str()); |
| 4207 | if (_currentEndpoint->type == Endpoint::Type::UDP_RELAY || _currentEndpoint->type == Endpoint::Type::TCP_RELAY) |
| 4208 | { |
| 4209 | m_currentEndpoint = m_preferredRelay; |
| 4210 | _currentEndpoint = _preferredRelay; |
| 4211 | } |
| 4212 | } |
| 4213 | if (_currentEndpoint->type == Endpoint::Type::UDP_RELAY && m_useUDP) |
| 4214 | { |
| 4215 | constexpr std::int64_t p2pID = static_cast<std::int64_t>(FOURCC('P', '2', 'P', '4')) << 32; |
| 4216 | constexpr std::int64_t lanID = static_cast<std::int64_t>(FOURCC('L', 'A', 'N', '4')) << 32; |
| 4217 |
| 4218 | if (m_endpoints.find(p2pID) != m_endpoints.end()) |
| 4219 | { |
| 4220 | Endpoint& p2p = m_endpoints[p2pID]; |
| 4221 | if (m_endpoints.find(lanID) != m_endpoints.end() && m_endpoints[lanID].m_averageRTT > 0 && m_endpoints[lanID].m_averageRTT < minPing * m_relayToP2pSwitchThreshold) |
| 4222 | { |
| 4223 | m_currentEndpoint = lanID; |
| 4224 | LOGI("Switching to p2p (LAN)"); |
| 4225 | } |
| 4226 | else |
| 4227 | { |
| 4228 | if (p2p.m_averageRTT > 0 && p2p.m_averageRTT < minPing * m_relayToP2pSwitchThreshold) |
| 4229 | { |
| 4230 | m_currentEndpoint = p2pID; |
| 4231 | LOGI("Switching to p2p (Inet)"); |
| 4232 | } |
| 4233 | } |
| 4234 | } |
| 4235 | } |
| 4236 | else |
| 4237 | { |
| 4238 | if (minPing > 0 && minPing < _currentEndpoint->m_averageRTT * m_p2pToRelaySwitchThreshold) |
| 4239 | { |
| 4240 | LOGI("Switching to relay"); |
| 4241 | m_currentEndpoint = m_preferredRelay; |
| 4242 | } |
| 4243 | } |
| 4244 | } |
| 4245 | } |
| 4246 |
| 4247 | void VoIPController::UpdateRTT() |
| 4248 | { |
| 4249 | m_RTTHistory.Add(GetAverageRTT()); |
| 4250 | m_waitingForAcks = (m_RTTHistory[0] > 10.0 && m_RTTHistory[8] > 10.0 && (m_networkType == NetType::EDGE || m_networkType == NetType::GPRS)); |
| 4251 | for (const std::shared_ptr<Stream>& stream : m_incomingStreams) |
| 4252 | { |
| 4253 | if (stream->jitterBuffer != nullptr) |
| 4254 | { |
| 4255 | int lostCount = stream->jitterBuffer->GetAndResetLostPacketCount(); |
| 4256 | if (lostCount > 0 || (lostCount < 0 && m_recvLossCount > static_cast<std::uint32_t>(-lostCount))) |
| 4257 | m_recvLossCount += static_cast<std::uint32_t>(lostCount); |
| 4258 | } |
| 4259 | } |
| 4260 | } |
| 4261 |
| 4262 | void VoIPController::UpdateCongestion() |
| 4263 | { |
| 4264 | if (m_congestionControl == nullptr || m_encoder == nullptr) |
| 4265 | return; |
| 4266 |
| 4267 | std::uint32_t sendLossCount = m_congestionControl->GetSendLossCount(); |
| 4268 | m_sendLossCountHistory.Add(sendLossCount - m_prevSendLossCount); |
| 4269 | m_prevSendLossCount = sendLossCount; |
| 4270 | double packetsPerSec = 1000.0 / m_outgoingStreams[0]->frameDuration; |
| 4271 | double avgSendLossCount = m_sendLossCountHistory.Average() / packetsPerSec; |
| 4272 |
| 4273 | if (avgSendLossCount > m_packetLossToEnableExtraEC && m_networkType != NetType::GPRS && m_networkType != NetType::EDGE) |
| 4274 | { |
| 4275 | if (!m_shittyInternetMode) |
| 4276 | { |
| 4277 | // Shitty Internet Mode™. Redundant redundancy you can trust. |
| 4278 | m_shittyInternetMode = true; |
| 4279 | for (std::shared_ptr<Stream>& s : m_outgoingStreams) |
| 4280 | { |
| 4281 | if (s->type == StreamType::AUDIO) |
| 4282 | { |
| 4283 | s->extraECEnabled = true; |
| 4284 | SendStreamFlags(*s); |
| 4285 | break; |
| 4286 | } |
| 4287 | } |
| 4288 | m_encoder->SetSecondaryEncoderEnabled(true); |
| 4289 | LOGW("Enabling extra EC"); |
| 4290 | if (m_needRateFlags & NEED_RATE_FLAG_SHITTY_INTERNET_MODE) |
| 4291 | m_needRate = true; |
| 4292 | m_wasExtraEC = true; |
| 4293 | } |
| 4294 | } |
| 4295 |
| 4296 | if (avgSendLossCount > 0.08) |
| 4297 | m_extraEcLevel = 4; |
| 4298 | else if (avgSendLossCount > 0.05) |
| 4299 | m_extraEcLevel = 3; |
| 4300 | else if (avgSendLossCount > 0.02) |
| 4301 | m_extraEcLevel = 2; |
| 4302 | else |
| 4303 | m_extraEcLevel = 0; |
| 4304 |
| 4305 | m_encoder->SetPacketLoss(static_cast<int>(avgSendLossCount * 100)); |
| 4306 | if (avgSendLossCount > m_rateMaxAcceptableSendLoss) |
| 4307 | m_needRate = true; |
| 4308 |
| 4309 | if ((avgSendLossCount < m_packetLossToEnableExtraEC || m_networkType == NetType::EDGE || m_networkType == NetType::GPRS) && m_shittyInternetMode) |
| 4310 | { |
| 4311 | m_shittyInternetMode = false; |
| 4312 | for (std::shared_ptr<Stream>& s : m_outgoingStreams) |
| 4313 | { |
| 4314 | if (s->type == StreamType::AUDIO) |
| 4315 | { |
| 4316 | s->extraECEnabled = false; |
| 4317 | SendStreamFlags(*s); |
| 4318 | break; |
| 4319 | } |
| 4320 | } |
| 4321 | m_encoder->SetSecondaryEncoderEnabled(false); |
| 4322 | LOGW("Disabling extra EC"); |
| 4323 | } |
| 4324 | if (!m_wasEncoderLaggy && m_encoder->GetComplexity() < 10) |
| 4325 | m_wasEncoderLaggy = true; |
| 4326 | } |
| 4327 |
| 4328 | void VoIPController::UpdateAudioBitrate() |
| 4329 | { |
| 4330 | if (m_congestionControl == nullptr || m_encoder == nullptr) |
| 4331 | return; |
| 4332 |
| 4333 | double time = GetCurrentTime(); |
| 4334 | if ((m_audioInput != nullptr && !m_audioInput->IsInitialized()) || |
| 4335 | (m_audioOutput != nullptr && !m_audioOutput->IsInitialized())) |
| 4336 | { |
| 4337 | LOGE("Audio I/O failed"); |
| 4338 | m_lastError = Error::AUDIO_IO; |
| 4339 | SetState(State::FAILED); |
| 4340 | } |
| 4341 |
| 4342 | tgvoip::ConctlAct act = m_congestionControl->GetBandwidthControlAction(); |
| 4343 | if (m_shittyInternetMode) |
| 4344 | { |
| 4345 | m_encoder->SetBitrate(8000); |
| 4346 | } |
| 4347 | else if (act == tgvoip::ConctlAct::DECREASE) |
| 4348 | { |
| 4349 | std::uint32_t bitrate = m_encoder->GetBitrate(); |
| 4350 | if (bitrate > 8000) |
| 4351 | m_encoder->SetBitrate(bitrate < (m_minAudioBitrate + m_audioBitrateStepDecr) ? m_minAudioBitrate : (bitrate - m_audioBitrateStepDecr)); |
| 4352 | } |
| 4353 | else if (act == tgvoip::ConctlAct::INCREASE) |
| 4354 | { |
| 4355 | std::uint32_t bitrate = m_encoder->GetBitrate(); |
| 4356 | if (bitrate < m_maxBitrate) |
| 4357 | m_encoder->SetBitrate(bitrate + m_audioBitrateStepIncr); |
| 4358 | } |
| 4359 |
| 4360 | if (m_state == State::ESTABLISHED && time - m_lastRecvPacketTime >= m_reconnectingTimeout) |
| 4361 | { |
| 4362 | SetState(State::RECONNECTING); |
| 4363 | if (m_needRateFlags & NEED_RATE_FLAG_RECONNECTING) |
| 4364 | m_needRate = true; |
| 4365 | m_wasReconnecting = true; |
| 4366 | ResetUdpAvailability(); |
| 4367 | } |
| 4368 |
| 4369 | if (m_state == State::ESTABLISHED || m_state == State::RECONNECTING) |
| 4370 | { |
| 4371 | if (time - m_lastRecvPacketTime >= m_config.recvTimeout) |
| 4372 | { |
| 4373 | const Endpoint& _currentEndpoint = m_endpoints.at(m_currentEndpoint); |
| 4374 | if (_currentEndpoint.type != Endpoint::Type::UDP_RELAY && _currentEndpoint.type != Endpoint::Type::TCP_RELAY) |
| 4375 | { |
| 4376 | LOGW("Packet receive timeout, switching to relay"); |
| 4377 | m_currentEndpoint = m_preferredRelay; |
| 4378 | for (auto& [_, endpoint] : m_endpoints) |
| 4379 | { |
| 4380 | if (endpoint.type == Endpoint::Type::UDP_P2P_INET || endpoint.type == Endpoint::Type::UDP_P2P_LAN) |
| 4381 | { |
| 4382 | endpoint.m_averageRTT = 0; |
| 4383 | endpoint.m_rtts.Reset(); |
| 4384 | } |
| 4385 | } |
| 4386 | if (m_allowP2p) |
| 4387 | { |
| 4388 | SendPublicEndpointsRequest(); |
| 4389 | } |
| 4390 | UpdateDataSavingState(); |
| 4391 | UpdateAudioBitrateLimit(); |
| 4392 | BufferOutputStream s(4); |
| 4393 | s.WriteInt32(m_dataSavingMode ? INIT_FLAG_DATA_SAVING_ENABLED : 0); |
| 4394 | if (m_peerVersion < 6) |
| 4395 | { |
| 4396 | SendPacketReliably(PktType::NETWORK_CHANGED, s.GetBuffer(), s.GetLength(), 1, 20); |
| 4397 | } |
| 4398 | else |
| 4399 | { |
| 4400 | Buffer buf(std::move(s)); |
| 4401 | SendExtra(buf, ExtraType::NETWORK_CHANGED); |
| 4402 | } |
| 4403 | m_lastRecvPacketTime = time; |
| 4404 | } |
| 4405 | else |
| 4406 | { |
| 4407 | LOGW("Packet receive timeout, disconnecting"); |
| 4408 | m_lastError = Error::TIMEOUT; |
| 4409 | SetState(State::FAILED); |
| 4410 | } |
| 4411 | } |
| 4412 | } |
| 4413 | } |
| 4414 |
| 4415 | void VoIPController::UpdateSignalBars() |
| 4416 | { |
| 4417 | int prevSignalBarCount = GetSignalBarsCount(); |
| 4418 | double packetsPerSec = 1000.0 / m_outgoingStreams[0]->frameDuration; |
| 4419 | double avgSendLossCount = m_sendLossCountHistory.Average() / packetsPerSec; |
| 4420 |
| 4421 | int signalBarCount = 4; |
| 4422 | if (m_state == State::RECONNECTING || m_waitingForAcks) |
| 4423 | signalBarCount = 1; |
| 4424 | if (m_endpoints.at(m_currentEndpoint).type == Endpoint::Type::TCP_RELAY) |
| 4425 | { |
| 4426 | signalBarCount = std::min(signalBarCount, 3); |
| 4427 | } |
| 4428 | if (avgSendLossCount > 0.1) |
| 4429 | { |
| 4430 | signalBarCount = 1; |
| 4431 | } |
| 4432 | else if (avgSendLossCount > 0.0625) |
| 4433 | { |
| 4434 | signalBarCount = std::min(signalBarCount, 2); |
| 4435 | } |
| 4436 | else if (avgSendLossCount > 0.025) |
| 4437 | { |
| 4438 | signalBarCount = std::min(signalBarCount, 3); |
| 4439 | } |
| 4440 |
| 4441 | for (std::shared_ptr<Stream>& stream : m_incomingStreams) |
| 4442 | { |
| 4443 | if (stream->jitterBuffer != nullptr) |
| 4444 | { |
| 4445 | double avgLateCount[3]; |
| 4446 | stream->jitterBuffer->GetAverageLateCount(avgLateCount); |
| 4447 | if (avgLateCount[2] >= 0.2) |
| 4448 | signalBarCount = 1; |
| 4449 | else if (avgLateCount[2] >= 0.1) |
| 4450 | signalBarCount = std::min(signalBarCount, 2); |
| 4451 | } |
| 4452 | } |
| 4453 |
| 4454 | m_signalBarsHistory.Add(static_cast<unsigned char>(signalBarCount)); |
| 4455 | int _signalBarCount = GetSignalBarsCount(); |
| 4456 | if (_signalBarCount != prevSignalBarCount) |
| 4457 | { |
| 4458 | LOGD("SIGNAL BAR COUNT CHANGED: %d", _signalBarCount); |
| 4459 | if (m_callbacks.signalBarCountChanged) |
| 4460 | m_callbacks.signalBarCountChanged(this, _signalBarCount); |
| 4461 | } |
| 4462 | } |
| 4463 |
| 4464 | void VoIPController::UpdateQueuedPackets() |
| 4465 | { |
| 4466 | std::vector<PendingOutgoingPacket> packetsToSend; |
| 4467 | for (auto qp = m_queuedPackets.begin(); qp != m_queuedPackets.end();) |
| 4468 | { |
| 4469 | if (qp->timeout > 0 && qp->firstSentTime > 0 && GetCurrentTime() - qp->firstSentTime >= qp->timeout) |
| 4470 | { |
| 4471 | LOGD("Removing queued packet because of timeout"); |
| 4472 | qp = m_queuedPackets.erase(qp); |
| 4473 | continue; |
| 4474 | } |
| 4475 | if (GetCurrentTime() - qp->lastSentTime >= qp->retryInterval) |
| 4476 | { |
| 4477 | m_messageThread.Post(std::bind(&VoIPController::UpdateQueuedPackets, this), qp->retryInterval); |
| 4478 | std::uint32_t seq = GenerateOutSeq(); |
| 4479 | qp->seqs.Add(seq); |
| 4480 | qp->lastSentTime = GetCurrentTime(); |
| 4481 | Buffer buf(qp->data.Length()); |
| 4482 | if (qp->firstSentTime == 0) |
| 4483 | qp->firstSentTime = qp->lastSentTime; |
| 4484 | if (qp->data.Length()) |
| 4485 | buf.CopyFrom(qp->data, qp->data.Length()); |
| 4486 | packetsToSend.emplace_back(PendingOutgoingPacket |
| 4487 | { |
| 4488 | /*.seq=*/ seq, |
| 4489 | /*.type=*/ qp->type, |
| 4490 | /*.len=*/ qp->data.Length(), |
| 4491 | /*.data=*/ std::move(buf), |
| 4492 | /*.endpoint=*/0 |
| 4493 | }); |
| 4494 | } |
| 4495 | ++qp; |
| 4496 | } |
| 4497 | for (PendingOutgoingPacket& pkt : packetsToSend) |
| 4498 | { |
| 4499 | SendOrEnqueuePacket(std::move(pkt)); |
| 4500 | } |
| 4501 | } |
| 4502 |
| 4503 | void VoIPController::SendNopPacket() |
| 4504 | { |
| 4505 | if (m_state != State::ESTABLISHED) |
| 4506 | return; |
| 4507 | SendOrEnqueuePacket(PendingOutgoingPacket |
| 4508 | { |
| 4509 | /*.seq=*/ (m_firstSentPing = GenerateOutSeq()), |
| 4510 | /*.type=*/ PktType::NOP, |
| 4511 | /*.len=*/ 0, |
| 4512 | /*.data=*/ Buffer(), |
| 4513 | /*.endpoint=*/0 |
| 4514 | }); |
| 4515 | } |
| 4516 |
| 4517 | void VoIPController::SendPublicEndpointsRequest() |
| 4518 | { |
| 4519 | ENFORCE_MSG_THREAD; |
| 4520 | if (!m_allowP2p) |
| 4521 | return; |
| 4522 | LOGI("Sending public endpoints request"); |
| 4523 | for (std::pair<const std::int64_t, Endpoint>& e : m_endpoints) |
| 4524 | { |
| 4525 | if (e.second.type == Endpoint::Type::UDP_RELAY && !e.second.IsIPv6Only()) |
| 4526 | { |
| 4527 | SendPublicEndpointsRequest(e.second); |
| 4528 | } |
| 4529 | } |
| 4530 | ++m_publicEndpointsReqCount; |
| 4531 | if (m_publicEndpointsReqCount < 10) |
| 4532 | { |
| 4533 | m_messageThread.Post([this] |
| 4534 | { |
| 4535 | if (m_waitingForRelayPeerInfo) |
| 4536 | { |
| 4537 | LOGW("Resending peer relay info request"); |
| 4538 | SendPublicEndpointsRequest(); |
| 4539 | } |
| 4540 | }, |
| 4541 | 5.0); |
| 4542 | } |
| 4543 | else |
| 4544 | { |
| 4545 | m_publicEndpointsReqCount = 0; |
| 4546 | } |
| 4547 | } |
| 4548 |
| 4549 | void VoIPController::TickJitterBufferAndCongestionControl() |
| 4550 | { |
| 4551 | // TODO get rid of this and update states of these things internally and retroactively |
| 4552 | for (std::shared_ptr<Stream>& stream : m_incomingStreams) |
| 4553 | { |
| 4554 | if (stream->jitterBuffer != nullptr) |
| 4555 | { |
| 4556 | stream->jitterBuffer->Tick(); |
| 4557 | } |
| 4558 | } |
| 4559 | if (m_congestionControl != nullptr) |
| 4560 | { |
| 4561 | m_congestionControl->Tick(); |
| 4562 | } |
| 4563 |
| 4564 | double currentTime = GetCurrentTime(); |
| 4565 | double rtt = GetAverageRTT(); |
| 4566 | double packetLossTimeout = std::max(rtt * 2.0, 0.1); |
| 4567 | for (RecentOutgoingPacket& pkt : m_recentOutgoingPackets) |
| 4568 | { |
| 4569 | if (pkt.ackTime != 0.0 || pkt.lost) |
| 4570 | continue; |
| 4571 | if (currentTime - pkt.sendTime > packetLossTimeout) |
| 4572 | { |
| 4573 | pkt.lost = true; |
| 4574 | ++m_sendLosses; |
| 4575 | LOGW("Outgoing packet lost: seq=%u, type=%s, size=%u", pkt.seq, GetPacketTypeString(pkt.type).c_str(), static_cast<unsigned int>(pkt.size)); |
| 4576 | if (pkt.sender) |
| 4577 | { |
| 4578 | pkt.sender->PacketLost(pkt.seq, pkt.type, pkt.size); |
| 4579 | } |
| 4580 | else if (pkt.type == PktType::STREAM_DATA) |
| 4581 | { |
| 4582 | m_congestionControl->PacketLost(pkt.seq); |
| 4583 | } |
| 4584 | } |
| 4585 | } |
| 4586 | } |
| 4587 |