1
Fork 0
galene/rtptime/rtptime.go

76 lines
1.9 KiB
Go
Raw Normal View History

2021-04-30 12:57:03 +02:00
// Package rtptime manipulates RTP and NTP time
2020-06-03 20:12:25 +02:00
package rtptime
import (
"math/bits"
"time"
)
2021-04-30 12:57:03 +02:00
// epoch is the origin of NTP time
var epoch = time.Now()
2021-04-30 12:57:03 +02:00
// FromDuration converts a time.Duration into units of 1/hz.
func FromDuration(d time.Duration, hz uint32) int64 {
if d < 0 {
return -FromDuration(d.Abs(), hz)
}
hi, lo := bits.Mul64(uint64(d), uint64(hz))
q, _ := bits.Div64(hi, lo, uint64(time.Second))
return int64(q)
}
2021-04-30 12:57:03 +02:00
// ToDuration converts units of 1/hz into a time.Duration.
func ToDuration(tm int64, hz uint32) time.Duration {
if tm < 0 {
return -ToDuration(-tm, hz)
}
hi, lo := bits.Mul64(uint64(tm), uint64(time.Second))
q, _ := bits.Div64(hi, lo, uint64(hz))
return time.Duration(q)
2020-05-02 18:41:18 +02:00
}
2021-04-30 12:57:03 +02:00
// Now returns the current time in units of 1/hz from an arbitrary origin.
func Now(hz uint32) uint64 {
return uint64(FromDuration(time.Since(epoch), hz))
}
2021-04-30 12:57:03 +02:00
// Microseconds is like Now, but uses microseconds.
func Microseconds() uint64 {
return Now(1000000)
}
2020-05-02 18:41:18 +02:00
2021-04-30 12:57:03 +02:00
// JiffiesPerSec is the number of jiffies in a second. This is the LCM of
// 48000, 96000 and 65536.
2020-06-03 20:18:06 +02:00
const JiffiesPerSec = 24576000
2021-04-30 12:57:03 +02:00
// Jiffies returns the current time in jiffies.
2020-06-03 20:18:06 +02:00
func Jiffies() uint64 {
return Now(JiffiesPerSec)
}
2021-04-30 12:57:03 +02:00
// TimeToJiffies converts a time.Time into jiffies.
2020-06-03 21:48:20 +02:00
func TimeToJiffies(tm time.Time) uint64 {
return uint64(FromDuration(tm.Sub(epoch), JiffiesPerSec))
2020-06-03 21:48:20 +02:00
}
2021-04-30 12:57:03 +02:00
// The origin of NTP time.
2020-05-02 18:41:18 +02:00
var ntpEpoch = time.Date(1900, 1, 1, 0, 0, 0, 0, time.UTC)
2021-04-30 12:57:03 +02:00
// NTPToTime converts an NTP time into a time.Time.
2020-05-02 18:41:18 +02:00
func NTPToTime(ntp uint64) time.Time {
sec := uint32(ntp >> 32)
frac := uint32(ntp & 0xFFFFFFFF)
return ntpEpoch.Add(
2020-12-19 17:38:47 +01:00
time.Duration(sec)*time.Second +
2020-05-02 18:41:18 +02:00
((time.Duration(frac) * time.Second) >> 32),
)
}
2021-04-30 12:57:03 +02:00
// TimeToNTP converts a time.Time into an NTP time.
2020-05-02 18:41:18 +02:00
func TimeToNTP(tm time.Time) uint64 {
d := tm.Sub(ntpEpoch)
sec := uint32(d / time.Second)
frac := uint32(d % time.Second)
2020-12-19 17:38:47 +01:00
return (uint64(sec) << 32) + (uint64(frac)<<32)/uint64(time.Second)
2020-05-02 18:41:18 +02:00
}