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