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