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