VoIPController.h 25 KB

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