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 7 #ifndef LIBTGVOIP_JITTERBUFFER_H 8 #define LIBTGVOIP_JITTERBUFFER_H 9 10 #include <stdlib.h> 11 #include <vector> 12 #include <stdio.h> 13 #include "MediaStreamItf.h" 14 #include "BlockingQueue.h" 15 #include "Buffers.h" 16 #include "threading.h" 17 18 #define JITTER_SLOT_COUNT 64 19 #define JITTER_SLOT_SIZE 1024 20 #define JR_OK 1 21 #define JR_MISSING 2 22 #define JR_BUFFERING 3 23 24 25 namespace tgvoip{ 26 class JitterBuffer{ 27 public: 28 JitterBuffer(MediaStreamItf* out, uint32_t step); 29 ~JitterBuffer(); 30 void SetMinPacketCount(uint32_t count); 31 int GetMinPacketCount(); 32 unsigned int GetCurrentDelay(); 33 double GetAverageDelay(); 34 void Reset(); 35 void HandleInput(unsigned char* data, size_t len, uint32_t timestamp, bool isEC); 36 size_t HandleOutput(unsigned char* buffer, size_t len, int offsetInSteps, bool advance, int& playbackScaledDuration, bool& isEC); 37 void Tick(); 38 void GetAverageLateCount(double* out); 39 int GetAndResetLostPacketCount(); 40 double GetLastMeasuredJitter(); 41 double GetLastMeasuredDelay(); 42 43 private: 44 struct jitter_packet_t{ 45 unsigned char* buffer=NULL; 46 size_t size; 47 uint32_t timestamp; 48 bool isEC; 49 double recvTimeDiff; 50 }; 51 static size_t CallbackIn(unsigned char* data, size_t len, void* param); 52 static size_t CallbackOut(unsigned char* data, size_t len, void* param); 53 void PutInternal(jitter_packet_t* pkt, bool overwriteExisting); 54 int GetInternal(jitter_packet_t* pkt, int offset, bool advance); 55 void Advance(); 56 57 BufferPool bufferPool; 58 Mutex mutex; 59 jitter_packet_t slots[JITTER_SLOT_COUNT]; 60 int64_t nextTimestamp=0; 61 uint32_t step; 62 double minDelay=6; 63 uint32_t minMinDelay; 64 uint32_t maxMinDelay; 65 uint32_t maxUsedSlots; 66 uint32_t lastPutTimestamp; 67 uint32_t lossesToReset; 68 double resyncThreshold; 69 unsigned int lostCount=0; 70 unsigned int lostSinceReset=0; 71 unsigned int gotSinceReset=0; 72 bool wasReset=true; 73 bool needBuffering=true; 74 HistoricBuffer<int, 64, double> delayHistory; 75 HistoricBuffer<int, 64, double> lateHistory; 76 bool adjustingDelay=false; 77 unsigned int tickCount=0; 78 unsigned int latePacketCount=0; 79 unsigned int dontIncMinDelay=0; 80 unsigned int dontDecMinDelay=0; 81 int lostPackets=0; 82 double prevRecvTime=0; 83 double expectNextAtTime=0; 84 HistoricBuffer<double, 64> deviationHistory; 85 double lastMeasuredJitter=0; 86 double lastMeasuredDelay=0; 87 int outstandingDelayChange=0; 88 unsigned int dontChangeDelay=0; 89 double avgDelay=0; 90 bool first=true; 91 #ifdef TGVOIP_DUMP_JITTER_STATS 92 FILE* dump; 93 #endif 94 }; 95 } 96 97 #endif //LIBTGVOIP_JITTERBUFFER_H 98