abssendtimeextension.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package rtp
  2. import (
  3. "time"
  4. )
  5. const (
  6. absSendTimeExtensionSize = 3
  7. )
  8. // AbsSendTimeExtension is a extension payload format in
  9. // http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time
  10. type AbsSendTimeExtension struct {
  11. Timestamp uint64
  12. }
  13. // Marshal serializes the members to buffer.
  14. func (t AbsSendTimeExtension) Marshal() ([]byte, error) {
  15. return []byte{
  16. byte(t.Timestamp & 0xFF0000 >> 16),
  17. byte(t.Timestamp & 0xFF00 >> 8),
  18. byte(t.Timestamp & 0xFF),
  19. }, nil
  20. }
  21. // Unmarshal parses the passed byte slice and stores the result in the members.
  22. func (t *AbsSendTimeExtension) Unmarshal(rawData []byte) error {
  23. if len(rawData) < absSendTimeExtensionSize {
  24. return errTooSmall
  25. }
  26. t.Timestamp = uint64(rawData[0])<<16 | uint64(rawData[1])<<8 | uint64(rawData[2])
  27. return nil
  28. }
  29. // Estimate absolute send time according to the receive time.
  30. // Note that if the transmission delay is larger than 64 seconds, estimated time will be wrong.
  31. func (t *AbsSendTimeExtension) Estimate(receive time.Time) time.Time {
  32. receiveNTP := toNtpTime(receive)
  33. ntp := receiveNTP&0xFFFFFFC000000000 | (t.Timestamp&0xFFFFFF)<<14
  34. if receiveNTP < ntp {
  35. // Receive time must be always later than send time
  36. ntp -= 0x1000000 << 14
  37. }
  38. return toTime(ntp)
  39. }
  40. // NewAbsSendTimeExtension makes new AbsSendTimeExtension from time.Time.
  41. func NewAbsSendTimeExtension(sendTime time.Time) *AbsSendTimeExtension {
  42. return &AbsSendTimeExtension{
  43. Timestamp: toNtpTime(sendTime) >> 14,
  44. }
  45. }
  46. func toNtpTime(t time.Time) uint64 {
  47. var s uint64
  48. var f uint64
  49. u := uint64(t.UnixNano())
  50. s = u / 1e9
  51. s += 0x83AA7E80 // offset in seconds between unix epoch and ntp epoch
  52. f = u % 1e9
  53. f <<= 32
  54. f /= 1e9
  55. s <<= 32
  56. return s | f
  57. }
  58. func toTime(t uint64) time.Time {
  59. s := t >> 32
  60. f := t & 0xFFFFFFFF
  61. f *= 1e9
  62. f >>= 32
  63. s -= 0x83AA7E80
  64. u := s*1e9 + f
  65. return time.Unix(0, int64(u))
  66. }