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