Rename mono to rtptime.

This commit is contained in:
Juliusz Chroboczek
2020-06-03 20:12:25 +02:00
parent e373054f7e
commit 7ae9a9ea69
5 changed files with 23 additions and 22 deletions
+41
View File
@@ -0,0 +1,41 @@
package rtptime
import (
"time"
)
var epoch = time.Now()
func FromDuration(d time.Duration, hz uint32) uint64 {
return uint64(d) * uint64(hz) / uint64(time.Second)
}
func toDuration(tm uint64, hz uint32) time.Duration {
return time.Duration(tm * uint64(time.Second) / uint64(hz))
}
func Now(hz uint32) uint64 {
return FromDuration(time.Since(epoch), hz)
}
func Microseconds() uint64 {
return Now(1000000)
}
var ntpEpoch = time.Date(1900, 1, 1, 0, 0, 0, 0, time.UTC)
func NTPToTime(ntp uint64) time.Time {
sec := uint32(ntp >> 32)
frac := uint32(ntp & 0xFFFFFFFF)
return ntpEpoch.Add(
time.Duration(sec) * time.Second +
((time.Duration(frac) * time.Second) >> 32),
)
}
func TimeToNTP(tm time.Time) uint64 {
d := tm.Sub(ntpEpoch)
sec := uint32(d / time.Second)
frac := uint32(d % time.Second)
return (uint64(sec) << 32) + (uint64(frac) << 32) / uint64(time.Second)
}
+67
View File
@@ -0,0 +1,67 @@
package rtptime
import (
"testing"
"time"
)
func TestDuration(t *testing.T) {
a := FromDuration(time.Second, 48000)
if a != 48000 {
t.Errorf("Expected 48000, got %v", a)
}
b := toDuration(48000, 48000)
if b != time.Second {
t.Errorf("Expected %v, got %v", time.Second, b)
}
}
func differs(a, b, delta uint64) bool {
if a < b {
a, b = b, a
}
return a - b >= delta
}
func TestMono(t *testing.T) {
a := Now(48000)
time.Sleep(4 * time.Millisecond)
b := Now(48000) - a
if differs(b, 4 * 48, 16) {
t.Errorf("Expected %v, got %v", 4 * 48, b)
}
c := Microseconds()
time.Sleep(4 * time.Millisecond)
d := Microseconds() - c
if differs(d, 4000, 1000) {
t.Errorf("Expected %v, got %v", 4000, d)
}
}
func TestNTP(t *testing.T) {
now := time.Now()
ntp := TimeToNTP(now)
now2 := NTPToTime(ntp)
ntp2 := TimeToNTP(now2)
diff1 := now2.Sub(now)
if diff1 < 0 {
diff1 = -diff1
}
if diff1 > time.Nanosecond {
t.Errorf("Expected %v, got %v (diff=%v)",
now, now2, diff1)
}
diff2 := int64(ntp2 - ntp)
if diff2 < 0 {
diff2 = -diff2
}
if diff2 > (1 << 8) {
t.Errorf("Expected %v, got %v (diff=%v)",
ntp, ntp2, float64(diff2) / float64(1<<32))
}
}