webrtc中ntp时间戳的计算

2019-08-02  本文已影响0人  hijiang

NTP时间在webrtc中是rtt计算的基础,NTP时间戳是从1900年1月1日经历的秒数,一般用64位表示,高32位表示秒数的整数部分,低32位每位表示微秒部分(以秒为单位的小数)的232=4.294967296*109倍;

来看看webrtc的处理:

const double kMagicNtpFractionalUnit = 4.294967296E+9;(=2^32)
// Retrieve an NTP absolute timestamp.
  NtpTime CurrentNtpTime() const override {
    timeval tv = CurrentTimeVal();//获取到tv结构,包括tv_sec及tv_usec
    double microseconds_in_seconds;
    uint32_t seconds;
    Adjust(tv, &seconds, &microseconds_in_seconds);//计算1900开始的秒数及微秒
    uint32_t fractions = static_cast<uint32_t>(
        microseconds_in_seconds * kMagicNtpFractionalUnit + 0.5);
    return NtpTime(seconds, fractions);
  }
static void Adjust(const timeval& tv,
                     uint32_t* adjusted_s,
                     double* adjusted_us_in_s) {
    *adjusted_s = tv.tv_sec + kNtpJan1970;//NTP时间是从1900年开始,所以需要加上这个70年经过的秒数
    *adjusted_us_in_s = tv.tv_usec / 1e6;//微秒时间的小数表示

    if (*adjusted_us_in_s >= 1) {
      *adjusted_us_in_s -= 1;
      ++*adjusted_s;
    } else if (*adjusted_us_in_s < -1) {
      *adjusted_us_in_s += 1;
      --*adjusted_s;
    }
  }
};

同时,webrtc中sr包及rr中中last_sr是一种压缩过的NTP时间戳,采用32位表示,只保留原来64位的中继32位,高16位表示秒数,低16位表示微秒,单位也一样。
webrtc使用下面这个函数将64位ntp时间戳转为32位的ntp时间戳:

// Helper function for compact ntp representation:
// RFC 3550, Section 4. Time Format.
// Wallclock time is represented using the timestamp format of
// the Network Time Protocol (NTP).
// ...
// In some fields where a more compact representation is
// appropriate, only the middle 32 bits are used; that is, the low 16
// bits of the integer part and the high 16 bits of the fractional part.
inline uint32_t CompactNtp(NtpTime ntp) {
  return (ntp.seconds() << 16) | (ntp.fractions() >> 16);
}

webrtc中,last_sr,使用的是32为NTP,delay使用的是1/2^16秒为单位;

上一篇 下一篇

猜你喜欢

热点阅读