| 6 |
| 7 | #ifndef __VOIPCONTROLLER_H |
| 8 | #define __VOIPCONTROLLER_H |
| 9 |
| 10 | #ifndef _WIN32 |
| 11 | #include <arpa/inet.h> |
| 12 | #include <netinet/in.h> |
| 13 | #endif |
| 14 | #ifdef __APPLE__ |
| 15 | #include <TargetConditionals.h> |
| 16 | #include "os/darwin/AudioUnitIO.h" |
| 17 | #endif |
| 18 | #include <stdint.h> |
| 19 | #include <vector> |
| 20 | #include <string> |
| 21 | #include <unordered_map> |
| 22 | #include <map> |
| 23 | #include <memory> |
| 24 | #include "video/VideoSource.h" |
| 25 | #include "video/VideoRenderer.h" |
| 26 | #include <atomic> |
| 27 | #include "video/ScreamCongestionController.h" |
| 28 | #include "audio/AudioInput.h" |
| 29 | #include "BlockingQueue.h" |
| 30 | #include "audio/AudioOutput.h" |
| 31 | #include "audio/AudioIO.h" |
| 32 | #include "JitterBuffer.h" |
| 33 | #include "OpusDecoder.h" |
| 34 | #include "OpusEncoder.h" |
| 35 | #include "EchoCanceller.h" |
| 36 | #include "CongestionControl.h" |
| 37 | #include "NetworkSocket.h" |
| 38 | #include "Buffers.h" |
| 39 | #include "PacketReassembler.h" |
| 40 | #include "MessageThread.h" |
| 41 | #include "utils.h" |
| 42 |
| 43 | #define LIBTGVOIP_VERSION "2.6" |
| 44 |
| 45 | #ifdef _WIN32 |
| 46 | #undef GetCurrentTime |
| 47 | #undef ERROR_TIMEOUT |
| 48 | #endif |
| 49 |
| 50 | #define TGVOIP_PEER_CAP_GROUP_CALLS 1 |
| 51 | #define TGVOIP_PEER_CAP_VIDEO_CAPTURE 2 |
| 52 | #define TGVOIP_PEER_CAP_VIDEO_DISPLAY 4 |
| 53 |
| 54 | namespace tgvoip{ |
| 55 |
| 56 | enum{ |
| 57 | PROXY_NONE=0, |
| 58 | PROXY_SOCKS5, |
| 59 | //PROXY_HTTP |
| 60 | }; |
| 61 |
| 62 | enum{ |
| 63 | STATE_WAIT_INIT=1, |
| 64 | STATE_WAIT_INIT_ACK, |
| 65 | STATE_ESTABLISHED, |
| 66 | STATE_FAILED, |
| 67 | STATE_RECONNECTING |
| 68 | }; |
| 69 |
| 70 | enum{ |
| 71 | ERROR_UNKNOWN=0, |
| 72 | ERROR_INCOMPATIBLE, |
| 73 | ERROR_TIMEOUT, |
| 74 | ERROR_AUDIO_IO, |
| 75 | ERROR_PROXY |
| 76 | }; |
| 77 |
| 78 | enum{ |
| 79 | NET_TYPE_UNKNOWN=0, |
| 80 | NET_TYPE_GPRS, |
| 81 | NET_TYPE_EDGE, |
| 82 | NET_TYPE_3G, |
| 83 | NET_TYPE_HSPA, |
| 84 | NET_TYPE_LTE, |
| 85 | NET_TYPE_WIFI, |
| 86 | NET_TYPE_ETHERNET, |
| 87 | NET_TYPE_OTHER_HIGH_SPEED, |
| 88 | NET_TYPE_OTHER_LOW_SPEED, |
| 89 | NET_TYPE_DIALUP, |
| 90 | NET_TYPE_OTHER_MOBILE |
| 91 | }; |
| 92 |
| 93 | enum{ |
| 94 | DATA_SAVING_NEVER=0, |
| 95 | DATA_SAVING_MOBILE, |
| 96 | DATA_SAVING_ALWAYS |
| 97 | }; |
| 98 |
| 99 | struct CryptoFunctions{ |
| 100 | void (*rand_bytes)(uint8_t* buffer, size_t length); |
| 101 | void (*sha1)(uint8_t* msg, size_t length, uint8_t* output); |
| 102 | void (*sha256)(uint8_t* msg, size_t length, uint8_t* output); |
| 103 | void (*aes_ige_encrypt)(uint8_t* in, uint8_t* out, size_t length, uint8_t* key, uint8_t* iv); |
| 104 | void (*aes_ige_decrypt)(uint8_t* in, uint8_t* out, size_t length, uint8_t* key, uint8_t* iv); |
| 105 | void (*aes_ctr_encrypt)(uint8_t* inout, size_t length, uint8_t* key, uint8_t* iv, uint8_t* ecount, uint32_t* num); |
| 106 | void (*aes_cbc_encrypt)(uint8_t* in, uint8_t* out, size_t length, uint8_t* key, uint8_t* iv); |
| 107 | void (*aes_cbc_decrypt)(uint8_t* in, uint8_t* out, size_t length, uint8_t* key, uint8_t* iv); |
| 108 | }; |
| 109 |
| 110 | struct CellularCarrierInfo{ |
| 111 | std::string name; |
| 112 | std::string mcc; |
| 113 | std::string mnc; |
| 114 | std::string countryCode; |
| 115 | }; |
| 116 |
| 117 | // API compatibility |
| 118 | struct IPv4Address{ |
| 119 | IPv4Address(std::string addr) : addr(addr){}; |
| 120 | std::string addr; |
| 121 | }; |
| 122 | struct IPv6Address{ |
| 123 | IPv6Address(std::string addr) : addr(addr){}; |
| 124 | std::string addr; |
| 125 | }; |
| 126 |
| 127 | class Endpoint{ |
| 128 | friend class VoIPController; |
| 129 | friend class VoIPGroupController; |
| 130 | public: |
| 131 |
| 132 | enum Type{ |
| 133 | UDP_P2P_INET=1, |
| 134 | UDP_P2P_LAN, |
| 135 | UDP_RELAY, |
| 136 | TCP_RELAY |
| 137 | }; |
| 138 |
| 139 | Endpoint(int64_t id, uint16_t port, const IPv4Address& address, const IPv6Address& v6address, Type type, unsigned char* peerTag); |
| 140 | Endpoint(int64_t id, uint16_t port, const NetworkAddress address, const NetworkAddress v6address, Type type, unsigned char* peerTag); |
| 141 | Endpoint(); |
| 142 | ~Endpoint(); |
| 143 | const NetworkAddress& GetAddress() const; |
| 144 | NetworkAddress& GetAddress(); |
| 145 | bool IsIPv6Only() const; |
| 146 | int64_t CleanID() const; |
| 147 | int64_t id; |
| 148 | uint16_t port; |
| 149 | NetworkAddress address; |
| 150 | NetworkAddress v6address; |
| 151 | Type type; |
| 152 | unsigned char peerTag[16]; |
| 153 |
| 154 | private: |
| 155 | double lastPingTime; |
| 156 | uint32_t lastPingSeq; |
| 157 | HistoricBuffer<double, 6> rtts; |
| 158 | HistoricBuffer<double, 4> selfRtts; |
| 159 | std::map<int64_t, double> udpPingTimes; |
| 160 | double averageRTT; |
| 161 | std::shared_ptr<NetworkSocket> socket; |
| 162 | int udpPongCount; |
| 163 | int totalUdpPings=0; |
| 164 | int totalUdpPingReplies=0; |
| 165 | }; |
| 166 |
| 167 | class AudioDevice{ |
| 168 | public: |
| 169 | std::string id; |
| 170 | std::string displayName; |
| 171 | }; |
| 172 |
| 173 | class AudioOutputDevice : public AudioDevice{ |
| 174 |
| 175 | }; |
| 176 |
| 177 | class AudioInputDevice : public AudioDevice{ |
| 178 |
| 179 | }; |
| 180 |
| 181 | class AudioInputTester{ |
| 182 | public: |
| 183 | AudioInputTester(const std::string deviceID); |
| 184 | ~AudioInputTester(); |
| 185 | TGVOIP_DISALLOW_COPY_AND_ASSIGN(AudioInputTester); |
| 186 | float GetAndResetLevel(); |
| 187 | bool Failed(){ |
| 188 | return io && io->Failed(); |
| 189 | } |
| 190 | private: |
| 191 | void Update(int16_t* samples, size_t count); |
| 192 | audio::AudioIO* io=NULL; |
| 193 | audio::AudioInput* input=NULL; |
| 194 | int16_t maxSample=0; |
| 195 | std::string deviceID; |
| 196 | }; |
| 197 |
| 198 | class PacketSender; |
| 199 | namespace video{ |
| 200 | class VideoPacketSender; |
| 201 | } |
| 202 |
| 203 | class VoIPController{ |
| 204 | friend class VoIPGroupController; |
| 205 | friend class PacketSender; |
| 206 | public: |
| 207 | TGVOIP_DISALLOW_COPY_AND_ASSIGN(VoIPController); |
| 208 | struct Config{ |
| 209 | Config(double initTimeout=30.0, double recvTimeout=20.0, int dataSaving=DATA_SAVING_NEVER, bool enableAEC=false, bool enableNS=false, bool enableAGC=false, bool enableCallUpgrade=false){ |
| 210 | this->initTimeout=initTimeout; |
| 211 | this->recvTimeout=recvTimeout; |
| 212 | this->dataSaving=dataSaving; |
| 213 | this->enableAEC=enableAEC; |
| 214 | this->enableNS=enableNS; |
| 215 | this->enableAGC=enableAGC; |
| 216 | this->enableCallUpgrade=enableCallUpgrade; |
| 217 | } |
| 218 |
| 219 | double initTimeout; |
| 220 | double recvTimeout; |
| 221 | int dataSaving; |
| 222 | #ifndef _WIN32 |
| 223 | std::string logFilePath=""; |
| 224 | std::string statsDumpFilePath=""; |
| 225 | #else |
| 226 | std::wstring logFilePath=L""; |
| 227 | std::wstring statsDumpFilePath=L""; |
| 228 | #endif |
| 229 |
| 230 | bool enableAEC; |
| 231 | bool enableNS; |
| 232 | bool enableAGC; |
| 233 |
| 234 | bool enableCallUpgrade; |
| 235 |
| 236 | bool logPacketStats=false; |
| 237 | bool enableVolumeControl=false; |
| 238 |
| 239 | bool enableVideoSend=false; |
| 240 | bool enableVideoReceive=false; |
| 241 | }; |
| 242 |
| 243 | struct TrafficStats{ |
| 244 | uint64_t bytesSentWifi; |
| 245 | uint64_t bytesRecvdWifi; |
| 246 | uint64_t bytesSentMobile; |
| 247 | uint64_t bytesRecvdMobile; |
| 248 | }; |
| 249 |
| 250 |
| 251 | VoIPController(); |
| 252 | virtual ~VoIPController(); |
| 253 |
| 254 | /** |
| 255 | * Set the initial endpoints (relays) |
| 256 | * @param endpoints Endpoints converted from phone.PhoneConnection TL objects |
| 257 | * @param allowP2p Whether p2p connectivity is allowed |
| 258 | * @param connectionMaxLayer The max_layer field from the phoneCallProtocol object returned by Telegram server. |
| 259 | * DO NOT HARDCODE THIS VALUE, it's extremely important for backwards compatibility. |
| 260 | */ |
| 261 | void SetRemoteEndpoints(std::vector<Endpoint> endpoints, bool allowP2p, int32_t connectionMaxLayer); |
| 262 | /** |
| 263 | * Initialize and start all the internal threads |
| 264 | */ |
| 265 | void Start(); |
| 266 | /** |
| 267 | * Stop any internal threads. Don't call any other methods after this. |
| 268 | */ |
| 269 | void Stop(); |
| 270 | /** |
| 271 | * Initiate connection |
| 272 | */ |
| 273 | void Connect(); |
| 274 | Endpoint& GetRemoteEndpoint(); |
| 275 | /** |
| 276 | * Get the debug info string to be displayed in client UI |
| 277 | */ |
| 278 | virtual std::string GetDebugString(); |
| 279 | /** |
| 280 | * Notify the library of network type change |
| 281 | * @param type The new network type |
| 282 | */ |
| 283 | virtual void SetNetworkType(int type); |
| 284 | /** |
| 285 | * Get the average round-trip time for network packets |
| 286 | * @return |
| 287 | */ |
| 288 | double GetAverageRTT(); |
| 289 | static double GetCurrentTime(); |
| 290 | /** |
| 291 | * Use this field to store any of your context data associated with this call |
| 292 | */ |
| 293 | void* implData; |
| 294 | /** |
| 295 | * |
| 296 | * @param mute |
| 297 | */ |
| 298 | virtual void SetMicMute(bool mute); |
| 299 | /** |
| 300 | * |
| 301 | * @param key |
| 302 | * @param isOutgoing |
| 303 | */ |
| 304 | void SetEncryptionKey(char* key, bool isOutgoing); |
| 305 | /** |
| 306 | * |
| 307 | * @param cfg |
| 308 | */ |
| 309 | void SetConfig(const Config& cfg); |
| 310 | void DebugCtl(int request, int param); |
| 311 | /** |
| 312 | * |
| 313 | * @param stats |
| 314 | */ |
| 315 | void GetStats(TrafficStats* stats); |
| 316 | /** |
| 317 | * |
| 318 | * @return |
| 319 | */ |
| 320 | int64_t GetPreferredRelayID(); |
| 321 | /** |
| 322 | * |
| 323 | * @return |
| 324 | */ |
| 325 | int GetLastError(); |
| 326 | /** |
| 327 | * |
| 328 | */ |
| 329 | static CryptoFunctions crypto; |
| 330 | /** |
| 331 | * |
| 332 | * @return |
| 333 | */ |
| 334 | static const char* GetVersion(); |
| 335 | /** |
| 336 | * |
| 337 | * @return |
| 338 | */ |
| 339 | std::string GetDebugLog(); |
| 340 | /** |
| 341 | * |
| 342 | * @return |
| 343 | */ |
| 344 | static std::vector<AudioInputDevice> EnumerateAudioInputs(); |
| 345 | /** |
| 346 | * |
| 347 | * @return |
| 348 | */ |
| 349 | static std::vector<AudioOutputDevice> EnumerateAudioOutputs(); |
| 350 | /** |
| 351 | * |
| 352 | * @param id |
| 353 | */ |
| 354 | void SetCurrentAudioInput(std::string id); |
| 355 | /** |
| 356 | * |
| 357 | * @param id |
| 358 | */ |
| 359 | void SetCurrentAudioOutput(std::string id); |
| 360 | /** |
| 361 | * |
| 362 | * @return |
| 363 | */ |
| 364 | std::string GetCurrentAudioInputID(); |
| 365 | /** |
| 366 | * |
| 367 | * @return |
| 368 | */ |
| 369 | std::string GetCurrentAudioOutputID(); |
| 370 | /** |
| 371 | * Set the proxy server to route the data through. Call this before connecting. |
| 372 | * @param protocol PROXY_NONE or PROXY_SOCKS5 |
| 373 | * @param address IP address or domain name of the server |
| 374 | * @param port Port of the server |
| 375 | * @param username Username; empty string for anonymous |
| 376 | * @param password Password; empty string if none |
| 377 | */ |
| 378 | void SetProxy(int protocol, std::string address, uint16_t port, std::string username, std::string password); |
| 379 | /** |
| 380 | * Get the number of signal bars to display in the client UI. |
| 381 | * @return the number of signal bars, from 1 to 4 |
| 382 | */ |
| 383 | int GetSignalBarsCount(); |
| 384 | /** |
| 385 | * Enable or disable AGC (automatic gain control) on audio output. Should only be enabled on phones when the earpiece speaker is being used. |
| 386 | * The audio output will be louder with this on. |
| 387 | * AGC with speakerphone or other kinds of loud speakers has detrimental effects on some echo cancellation implementations. |
| 388 | * @param enabled I usually pick argument names to be self-explanatory |
| 389 | */ |
| 390 | void SetAudioOutputGainControlEnabled(bool enabled); |
| 391 | /** |
| 392 | * Get the additional capabilities of the peer client app |
| 393 | * @return corresponding TGVOIP_PEER_CAP_* flags OR'ed together |
| 394 | */ |
| 395 | uint32_t GetPeerCapabilities(); |
| 396 | /** |
| 397 | * Send the peer the key for the group call to prepare this private call to an upgrade to a E2E group call. |
| 398 | * The peer must have the TGVOIP_PEER_CAP_GROUP_CALLS capability. After the peer acknowledges the key, Callbacks::groupCallKeySent will be called. |
| 399 | * @param key newly-generated group call key, must be exactly 265 bytes long |
| 400 | */ |
| 401 | void SendGroupCallKey(unsigned char* key); |
| 402 | /** |
| 403 | * In an incoming call, request the peer to generate a new encryption key, send it to you and upgrade this call to a E2E group call. |
| 404 | */ |
| 405 | void RequestCallUpgrade(); |
| 406 | void SetEchoCancellationStrength(int strength); |
| 407 | int GetConnectionState(); |
| 408 | bool NeedRate(); |
| 409 | /** |
| 410 | * Get the maximum connection layer supported by this libtgvoip version. |
| 411 | * Pass this as <code>max_layer</code> in the phone.phoneConnection TL object when requesting and accepting calls. |
| 412 | */ |
| 413 | static int32_t GetConnectionMaxLayer(){ |
| 414 | return 92; |
| 415 | }; |
| 416 | /** |
| 417 | * Get the persistable state of the library, like proxy capabilities, to save somewhere on the disk. Call this at the end of the call. |
| 418 | * Using this will speed up the connection establishment in some cases. |
| 419 | */ |
| 420 | std::vector<uint8_t> GetPersistentState(); |
| 421 | /** |
| 422 | * Load the persistable state. Call this before starting the call. |
| 423 | */ |
| 424 | void SetPersistentState(std::vector<uint8_t> state); |
| 425 |
| 426 | #if defined(TGVOIP_USE_CALLBACK_AUDIO_IO) |
| 427 | void SetAudioDataCallbacks(std::function<void(int16_t*, size_t)> input, std::function<void(int16_t*, size_t)> output, std::function<void(int16_t*, size_t)> preprocessed); |
| 428 | #endif |
| 429 |
| 430 | void SetVideoCodecSpecificData(const std::vector<Buffer>& data); |
| 431 |
| 432 | struct Callbacks{ |
| 433 | void (*connectionStateChanged)(VoIPController*, int); |
| 434 | void (*signalBarCountChanged)(VoIPController*, int); |
| 435 | void (*groupCallKeySent)(VoIPController*); |
| 436 | void (*groupCallKeyReceived)(VoIPController*, const unsigned char*); |
| 437 | void (*upgradeToGroupCallRequested)(VoIPController*); |
| 438 | }; |
| 439 | void SetCallbacks(Callbacks callbacks); |
| 440 |
| 441 | float GetOutputLevel(){ |
| 442 | return 0.0f; |
| 443 | }; |
| 444 | void SetVideoSource(video::VideoSource* source); |
| 445 | void SetVideoRenderer(video::VideoRenderer* renderer); |
| 446 |
| 447 | void SetInputVolume(float level); |
| 448 | void SetOutputVolume(float level); |
| 449 | #if defined(__APPLE__) && defined(TARGET_OS_OSX) |
| 450 | void SetAudioOutputDuckingEnabled(bool enabled); |
| 451 | #endif |
| 452 |
| 453 | struct PendingOutgoingPacket{ |
| 454 | PendingOutgoingPacket(uint32_t seq, unsigned char type, size_t len, Buffer&& data, int64_t endpoint){ |
| 455 | this->seq=seq; |
| 456 | this->type=type; |
| 457 | this->len=len; |
| 458 | this->data=std::move(data); |
| 459 | this->endpoint=endpoint; |
| 460 | } |
| 461 | PendingOutgoingPacket(PendingOutgoingPacket&& other){ |
| 462 | seq=other.seq; |
| 463 | type=other.type; |
| 464 | len=other.len; |
| 465 | data=std::move(other.data); |
| 466 | endpoint=other.endpoint; |
| 467 | } |
| 468 | PendingOutgoingPacket& operator=(PendingOutgoingPacket&& other){ |
| 469 | if(this!=&other){ |
| 470 | seq=other.seq; |
| 471 | type=other.type; |
| 472 | len=other.len; |
| 473 | data=std::move(other.data); |
| 474 | endpoint=other.endpoint; |
| 475 | } |
| 476 | return *this; |
| 477 | } |
| 478 | TGVOIP_DISALLOW_COPY_AND_ASSIGN(PendingOutgoingPacket); |
| 479 | uint32_t seq; |
| 480 | unsigned char type; |
| 481 | size_t len; |
| 482 | Buffer data; |
| 483 | int64_t endpoint; |
| 484 | }; |
| 485 |
| 486 | struct Stream{ |
| 487 | int32_t userID; |
| 488 | unsigned char id; |
| 489 | unsigned char type; |
| 490 | uint32_t codec; |
| 491 | bool enabled; |
| 492 | bool extraECEnabled; |
| 493 | uint16_t frameDuration; |
| 494 | std::shared_ptr<JitterBuffer> jitterBuffer; |
| 495 | std::shared_ptr<OpusDecoder> decoder; |
| 496 | std::shared_ptr<PacketReassembler> packetReassembler; |
| 497 | std::shared_ptr<CallbackWrapper> callbackWrapper; |
| 498 | std::vector<Buffer> codecSpecificData; |
| 499 | bool csdIsValid=false; |
| 500 | bool paused=false; |
| 501 | int resolution; |
| 502 | unsigned int width=0; |
| 503 | unsigned int height=0; |
| 504 | uint16_t rotation=0; |
| 505 | }; |
| 506 |
| 507 | struct ProtocolInfo{ |
| 508 | uint32_t version; |
| 509 | uint32_t maxVideoResolution; |
| 510 | std::vector<uint32_t> videoDecoders; |
| 511 | bool videoCaptureSupported; |
| 512 | bool videoDisplaySupported; |
| 513 | bool callUpgradeSupported; |
| 514 | }; |
| 515 |
| 516 | private: |
| 517 | struct UnacknowledgedExtraData; |
| 518 |
| 519 | protected: |
| 520 | struct RecentOutgoingPacket{ |
| 521 | uint32_t seq; |
| 522 | uint16_t id; // for group calls only |
| 523 | double sendTime; |
| 524 | double ackTime; |
| 525 | uint8_t type; |
| 526 | uint32_t size; |
| 527 | PacketSender* sender; |
| 528 | bool lost; |
| 529 | }; |
| 530 | struct QueuedPacket{ |
| 531 | Buffer data; |
| 532 | unsigned char type; |
| 533 | HistoricBuffer<uint32_t, 16> seqs; |
| 534 | double firstSentTime; |
| 535 | double lastSentTime; |
| 536 | double retryInterval; |
| 537 | double timeout; |
| 538 | }; |
| 539 | virtual void ProcessIncomingPacket(NetworkPacket& packet, Endpoint& srcEndpoint); |
| 540 | virtual void ProcessExtraData(Buffer& data); |
| 541 | virtual void WritePacketHeader(uint32_t seq, BufferOutputStream* s, unsigned char type, uint32_t length, PacketSender* source); |
| 542 | virtual void SendPacket(unsigned char* data, size_t len, Endpoint& ep, PendingOutgoingPacket& srcPacket); |
| 543 | virtual void SendInit(); |
| 544 | virtual void SendUdpPing(Endpoint& endpoint); |
| 545 | virtual void SendRelayPings(); |
| 546 | virtual void OnAudioOutputReady(); |
| 547 | virtual void SendExtra(Buffer& data, unsigned char type); |
| 548 | void SendStreamFlags(Stream& stream); |
| 549 | void InitializeTimers(); |
| 550 | void ResetEndpointPingStats(); |
| 551 | void SendVideoFrame(const Buffer& frame, uint32_t flags, uint32_t rotation); |
| 552 | void ProcessIncomingVideoFrame(Buffer frame, uint32_t pts, bool keyframe, uint16_t rotation); |
| 553 | std::shared_ptr<Stream> GetStreamByType(int type, bool outgoing); |
| 554 | std::shared_ptr<Stream> GetStreamByID(unsigned char id, bool outgoing); |
| 555 | Endpoint* GetEndpointForPacket(const PendingOutgoingPacket& pkt); |
| 556 | bool SendOrEnqueuePacket(PendingOutgoingPacket pkt, bool enqueue=true, PacketSender* source=NULL); |
| 557 | static std::string NetworkTypeToString(int type); |
| 558 | CellularCarrierInfo GetCarrierInfo(); |
| 559 |
| 560 | private: |
| 561 | struct UnacknowledgedExtraData{ |
| 562 | unsigned char type; |
| 563 | Buffer data; |
| 564 | uint32_t firstContainingSeq; |
| 565 | }; |
| 566 | struct RecentIncomingPacket{ |
| 567 | uint32_t seq; |
| 568 | double recvTime; |
| 569 | }; |
| 570 | enum{ |
| 571 | UDP_UNKNOWN=0, |
| 572 | UDP_PING_PENDING, |
| 573 | UDP_PING_SENT, |
| 574 | UDP_AVAILABLE, |
| 575 | UDP_NOT_AVAILABLE, |
| 576 | UDP_BAD |
| 577 | }; |
| 578 | struct DebugLoggedPacket{ |
| 579 | int32_t seq; |
| 580 | double timestamp; |
| 581 | int32_t length; |
| 582 | }; |
| 583 | struct RawPendingOutgoingPacket{ |
| 584 | TGVOIP_MOVE_ONLY(RawPendingOutgoingPacket); |
| 585 | NetworkPacket packet; |
| 586 | std::shared_ptr<NetworkSocket> socket; |
| 587 | }; |
| 588 |
| 589 | void RunRecvThread(); |
| 590 | void RunSendThread(); |
| 591 | void HandleAudioInput(unsigned char* data, size_t len, unsigned char* secondaryData, size_t secondaryLen); |
| 592 | void UpdateAudioBitrateLimit(); |
| 593 | void SetState(int state); |
| 594 | void UpdateAudioOutputState(); |
| 595 | void InitUDPProxy(); |
| 596 | void UpdateDataSavingState(); |
| 597 | void KDF(unsigned char* msgKey, size_t x, unsigned char* aesKey, unsigned char* aesIv); |
| 598 | void KDF2(unsigned char* msgKey, size_t x, unsigned char* aesKey, unsigned char* aesIv); |
| 599 | void SendPublicEndpointsRequest(); |
| 600 | void SendPublicEndpointsRequest(const Endpoint& relay); |
| 601 | Endpoint& GetEndpointByType(int type); |
| 602 | void SendPacketReliably(unsigned char type, unsigned char* data, size_t len, double retryInterval, double timeout); |
| 603 | uint32_t GenerateOutSeq(); |
| 604 | void ActuallySendPacket(NetworkPacket pkt, Endpoint& ep); |
| 605 | void InitializeAudio(); |
| 606 | void StartAudio(); |
| 607 | void ProcessAcknowledgedOutgoingExtra(UnacknowledgedExtraData& extra); |
| 608 | void AddIPv6Relays(); |
| 609 | void AddTCPRelays(); |
| 610 | void SendUdpPings(); |
| 611 | void EvaluateUdpPingResults(); |
| 612 | void UpdateRTT(); |
| 613 | void UpdateCongestion(); |
| 614 | void UpdateAudioBitrate(); |
| 615 | void UpdateSignalBars(); |
| 616 | void UpdateQueuedPackets(); |
| 617 | void SendNopPacket(); |
| 618 | void TickJitterBufferAndCongestionControl(); |
| 619 | void ResetUdpAvailability(); |
| 620 | std::string GetPacketTypeString(unsigned char type); |
| 621 | void SetupOutgoingVideoStream(); |
| 622 | bool WasOutgoingPacketAcknowledged(uint32_t seq); |
| 623 | RecentOutgoingPacket* GetRecentOutgoingPacket(uint32_t seq); |
| 624 | void NetworkPacketReceived(std::shared_ptr<NetworkPacket> packet); |
| 625 | void TrySendQueuedPackets(); |
| 626 |
| 627 | int state; |
| 628 | std::map<int64_t, Endpoint> endpoints; |
| 629 | int64_t currentEndpoint=0; |
| 630 | int64_t preferredRelay=0; |
| 631 | int64_t peerPreferredRelay=0; |
| 632 | std::atomic<bool> runReceiver; |
| 633 | std::atomic<uint32_t> seq; |
| 634 | uint32_t lastRemoteSeq; |
| 635 | uint32_t lastRemoteAckSeq; |
| 636 | uint32_t lastSentSeq; |
| 637 | std::vector<RecentOutgoingPacket> recentOutgoingPackets; |
| 638 | std::vector<uint32_t> recentIncomingPackets; |
| 639 | HistoricBuffer<uint32_t, 10, double> sendLossCountHistory; |
| 640 | uint32_t audioTimestampIn; |
| 641 | uint32_t audioTimestampOut; |
| 642 | tgvoip::audio::AudioIO* audioIO=NULL; |
| 643 | tgvoip::audio::AudioInput* audioInput=NULL; |
| 644 | tgvoip::audio::AudioOutput* audioOutput=NULL; |
| 645 | OpusEncoder* encoder; |
| 646 | std::vector<PendingOutgoingPacket> sendQueue; |
| 647 | EchoCanceller* echoCanceller; |
| 648 | std::atomic<bool> stopping; |
| 649 | bool audioOutStarted; |
| 650 | Thread* recvThread; |
| 651 | Thread* sendThread; |
| 652 | uint32_t packetsReceived; |
| 653 | uint32_t recvLossCount; |
| 654 | uint32_t prevSendLossCount; |
| 655 | uint32_t firstSentPing; |
| 656 | HistoricBuffer<double, 32> rttHistory; |
| 657 | bool waitingForAcks; |
| 658 | int networkType; |
| 659 | int dontSendPackets; |
| 660 | int lastError; |
| 661 | bool micMuted; |
| 662 | uint32_t maxBitrate; |
| 663 | std::vector<std::shared_ptr<Stream>> outgoingStreams; |
| 664 | std::vector<std::shared_ptr<Stream>> incomingStreams; |
| 665 | unsigned char encryptionKey[256]; |
| 666 | unsigned char keyFingerprint[8]; |
| 667 | unsigned char callID[16]; |
| 668 | double stateChangeTime; |
| 669 | bool waitingForRelayPeerInfo; |
| 670 | bool allowP2p; |
| 671 | bool dataSavingMode; |
| 672 | bool dataSavingRequestedByPeer; |
| 673 | std::string activeNetItfName; |
| 674 | double publicEndpointsReqTime; |
| 675 | std::vector<QueuedPacket> queuedPackets; |
| 676 | double connectionInitTime; |
| 677 | double lastRecvPacketTime; |
| 678 | Config config; |
| 679 | int32_t peerVersion; |
| 680 | CongestionControl* conctl; |
| 681 | TrafficStats stats; |
| 682 | bool receivedInit; |
| 683 | bool receivedInitAck; |
| 684 | bool isOutgoing; |
| 685 | NetworkSocket* udpSocket; |
| 686 | NetworkSocket* realUdpSocket; |
| 687 | FILE* statsDump; |
| 688 | std::string currentAudioInput; |
| 689 | std::string currentAudioOutput; |
| 690 | bool useTCP; |
| 691 | bool useUDP; |
| 692 | bool didAddTcpRelays; |
| 693 | SocketSelectCanceller* selectCanceller; |
| 694 | HistoricBuffer<unsigned char, 4, int> signalBarsHistory; |
| 695 | bool audioStarted=false; |
| 696 |
| 697 | int udpConnectivityState; |
| 698 | double lastUdpPingTime; |
| 699 | int udpPingCount; |
| 700 | int echoCancellationStrength; |
| 701 |
| 702 | int proxyProtocol; |
| 703 | std::string proxyAddress; |
| 704 | uint16_t proxyPort; |
| 705 | std::string proxyUsername; |
| 706 | std::string proxyPassword; |
| 707 | NetworkAddress resolvedProxyAddress=NetworkAddress::Empty(); |
| 708 |
| 709 | uint32_t peerCapabilities; |
| 710 | Callbacks callbacks; |
| 711 | bool didReceiveGroupCallKey; |
| 712 | bool didReceiveGroupCallKeyAck; |
| 713 | bool didSendGroupCallKey; |
| 714 | bool didSendUpgradeRequest; |
| 715 | bool didInvokeUpgradeCallback; |
| 716 |
| 717 | int32_t connectionMaxLayer; |
| 718 | bool useMTProto2; |
| 719 | bool setCurrentEndpointToTCP; |
| 720 |
| 721 | std::vector<UnacknowledgedExtraData> currentExtras; |
| 722 | std::unordered_map<uint8_t, uint64_t> lastReceivedExtrasByType; |
| 723 | bool useIPv6; |
| 724 | bool peerIPv6Available; |
| 725 | NetworkAddress myIPv6=NetworkAddress::Empty(); |
| 726 | bool shittyInternetMode; |
| 727 | int extraEcLevel=0; |
| 728 | std::vector<Buffer> ecAudioPackets; |
| 729 | bool didAddIPv6Relays; |
| 730 | bool didSendIPv6Endpoint; |
| 731 | int publicEndpointsReqCount=0; |
| 732 | bool wasEstablished=false; |
| 733 | bool receivedFirstStreamPacket=false; |
| 734 | std::atomic<unsigned int> unsentStreamPackets; |
| 735 | HistoricBuffer<unsigned int, 5> unsentStreamPacketsHistory; |
| 736 | bool needReInitUdpProxy=true; |
| 737 | bool needRate=false; |
| 738 | std::vector<DebugLoggedPacket> debugLoggedPackets; |
| 739 | BufferPool<1024, 32> outgoingAudioBufferPool; |
| 740 | BlockingQueue<RawPendingOutgoingPacket> rawSendQueue; |
| 741 |
| 742 | uint32_t initTimeoutID=MessageThread::INVALID_ID; |
| 743 | uint32_t udpPingTimeoutID=MessageThread::INVALID_ID; |
| 744 |
| 745 | effects::Volume outputVolume; |
| 746 | effects::Volume inputVolume; |
| 747 |
| 748 | std::vector<uint32_t> peerVideoDecoders; |
| 749 |
| 750 | MessageThread messageThread; |
| 751 |
| 752 | // Locked whenever the endpoints vector is modified (but not endpoints themselves) and whenever iterated outside of messageThread. |
| 753 | // After the call is started, only messageThread is allowed to modify the endpoints vector. |
| 754 | Mutex endpointsMutex; |
| 755 | // Locked while audio i/o is being initialized and deinitialized so as to allow it to fully initialize before deinitialization begins. |
| 756 | Mutex audioIOMutex; |
| 757 |
| 758 | #if defined(TGVOIP_USE_CALLBACK_AUDIO_IO) |
| 759 | std::function<void(int16_t*, size_t)> audioInputDataCallback; |
| 760 | std::function<void(int16_t*, size_t)> audioOutputDataCallback; |
| 761 | std::function<void(int16_t*, size_t)> audioPreprocDataCallback; |
| 762 | ::OpusDecoder* preprocDecoder=nullptr; |
| 763 | int16_t preprocBuffer[4096]; |
| 764 | #endif |
| 765 | #if defined(__APPLE__) && defined(TARGET_OS_OSX) |
| 766 | bool macAudioDuckingEnabled=true; |
| 767 | #endif |
| 768 |
| 769 | video::VideoSource* videoSource=NULL; |
| 770 | video::VideoRenderer* videoRenderer=NULL; |
| 771 | uint32_t lastReceivedVideoFrameNumber=UINT32_MAX; |
| 772 |
| 773 | video::VideoPacketSender* videoPacketSender=NULL; |
| 774 | uint32_t sendLosses=0; |
| 775 | uint32_t unacknowledgedIncomingPacketCount=0; |
| 776 |
| 777 | ProtocolInfo protocolInfo={0}; |
| 778 |
| 779 | /*** debug report problems ***/ |
| 780 | bool wasReconnecting=false; |
| 781 | bool wasExtraEC=false; |
| 782 | bool wasEncoderLaggy=false; |
| 783 | bool wasNetworkHandover=false; |
| 784 |
| 785 | /*** persistable state values ***/ |
| 786 | bool proxySupportsUDP=true; |
| 787 | bool proxySupportsTCP=true; |
| 788 | std::string lastTestedProxyServer=""; |
| 789 |
| 790 | /*** server config values ***/ |
| 791 | uint32_t maxAudioBitrate; |
| 792 | uint32_t maxAudioBitrateEDGE; |
| 793 | uint32_t maxAudioBitrateGPRS; |
| 794 | uint32_t maxAudioBitrateSaving; |
| 795 | uint32_t initAudioBitrate; |
| 796 | uint32_t initAudioBitrateEDGE; |
| 797 | uint32_t initAudioBitrateGPRS; |
| 798 | uint32_t initAudioBitrateSaving; |
| 799 | uint32_t minAudioBitrate; |
| 800 | uint32_t audioBitrateStepIncr; |
| 801 | uint32_t audioBitrateStepDecr; |
| 802 | double relaySwitchThreshold; |
| 803 | double p2pToRelaySwitchThreshold; |
| 804 | double relayToP2pSwitchThreshold; |
| 805 | double reconnectingTimeout; |
| 806 | uint32_t needRateFlags; |
| 807 | double rateMaxAcceptableRTT; |
| 808 | double rateMaxAcceptableSendLoss; |
| 809 | double packetLossToEnableExtraEC; |
| 810 | uint32_t maxUnsentStreamPackets; |
| 811 | uint32_t unackNopThreshold; |
| 812 |
| 813 | public: |
| 814 | #ifdef __APPLE__ |
| 815 | static double machTimebase; |
| 816 | static uint64_t machTimestart; |
| 817 | #endif |
| 818 | #ifdef _WIN32 |
| 819 | static int64_t win32TimeScale; |
| 820 | static bool didInitWin32TimeScale; |
| 821 | #endif |
| 822 | }; |
| 823 |
| 824 | class VoIPGroupController : public VoIPController{ |
| 825 | public: |
| 826 | VoIPGroupController(int32_t timeDifference); |
| 827 | virtual ~VoIPGroupController(); |
| 828 | void SetGroupCallInfo(unsigned char* encryptionKey, unsigned char* reflectorGroupTag, unsigned char* reflectorSelfTag, unsigned char* reflectorSelfSecret, unsigned char* reflectorSelfTagHash, int32_t selfUserID, NetworkAddress reflectorAddress, NetworkAddress reflectorAddressV6, uint16_t reflectorPort); |
| 829 | void AddGroupCallParticipant(int32_t userID, unsigned char* memberTagHash, unsigned char* serializedStreams, size_t streamsLength); |
| 830 | void RemoveGroupCallParticipant(int32_t userID); |
| 831 | float GetParticipantAudioLevel(int32_t userID); |
| 832 | virtual void SetMicMute(bool mute); |
| 833 | void SetParticipantVolume(int32_t userID, float volume); |
| 834 | void SetParticipantStreams(int32_t userID, unsigned char* serializedStreams, size_t length); |
| 835 | static size_t GetInitialStreams(unsigned char* buf, size_t size); |
| 836 |
| 837 | struct Callbacks : public VoIPController::Callbacks{ |
| 838 | void (*updateStreams)(VoIPGroupController*, unsigned char*, size_t); |
| 839 | void (*participantAudioStateChanged)(VoIPGroupController*, int32_t, bool); |
| 840 |
| 841 | }; |
| 842 | void SetCallbacks(Callbacks callbacks); |
| 843 | virtual std::string GetDebugString(); |
| 844 | virtual void SetNetworkType(int type); |
| 845 | protected: |
| 846 | virtual void ProcessIncomingPacket(NetworkPacket& packet, Endpoint& srcEndpoint); |
| 847 | virtual void SendInit(); |
| 848 | virtual void SendUdpPing(Endpoint& endpoint); |
| 849 | virtual void SendRelayPings(); |
| 850 | virtual void SendPacket(unsigned char* data, size_t len, Endpoint& ep, PendingOutgoingPacket& srcPacket); |
| 851 | virtual void WritePacketHeader(uint32_t seq, BufferOutputStream* s, unsigned char type, uint32_t length, PacketSender* sender=NULL); |
| 852 | virtual void OnAudioOutputReady(); |
| 853 | private: |
| 854 | int32_t GetCurrentUnixtime(); |
| 855 | std::vector<std::shared_ptr<Stream>> DeserializeStreams(BufferInputStream& in); |
| 856 | void SendRecentPacketsRequest(); |
| 857 | void SendSpecialReflectorRequest(unsigned char* data, size_t len); |
| 858 | void SerializeAndUpdateOutgoingStreams(); |
| 859 | struct GroupCallParticipant{ |
| 860 | int32_t userID; |
| 861 | unsigned char memberTagHash[32]; |
| 862 | std::vector<std::shared_ptr<Stream>> streams; |
| 863 | AudioLevelMeter* levelMeter; |
| 864 | }; |
| 865 | std::vector<GroupCallParticipant> participants; |
| 866 | unsigned char reflectorSelfTag[16]; |
| 867 | unsigned char reflectorSelfSecret[16]; |
| 868 | unsigned char reflectorSelfTagHash[32]; |
| 869 | int32_t userSelfID; |
| 870 | Endpoint groupReflector; |
| 871 | AudioMixer* audioMixer; |
| 872 | AudioLevelMeter selfLevelMeter; |
| 873 | Callbacks groupCallbacks; |
| 874 | struct PacketIdMapping{ |
| 875 | uint32_t seq; |
| 876 | uint16_t id; |
| 877 | double ackTime; |
| 878 | }; |
| 879 | std::vector<PacketIdMapping> recentSentPackets; |
| 880 | Mutex sentPacketsMutex; |
| 881 | Mutex participantsMutex; |
| 882 | int32_t timeDifference; |
| 883 | }; |
| 884 |
| 885 | }; |
| 886 |
| 887 | #endif |
| 888 |