forked from hypebeast/go-osc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathosc.go
1077 lines (917 loc) · 25.3 KB
/
osc.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Package osc provides a package for sending and receiving OpenSoundControl
// messages. The package is implemented in pure Go.
package osc
import (
"bufio"
"bytes"
"encoding"
"encoding/binary"
"errors"
"fmt"
"net"
"reflect"
"regexp"
"strings"
"time"
)
const (
secondsFrom1900To1970 = 2208988800
bundleTagString = "#bundle"
)
// Packet is the interface for Message and Bundle.
type Packet interface {
encoding.BinaryMarshaler
}
// Message represents a single OSC message. An OSC message consists of an OSC
// address pattern and zero or more arguments.
type Message struct {
Address string
Arguments []interface{}
}
// Verify that Messages implements the Packet interface.
var _ Packet = (*Message)(nil)
// Bundle represents an OSC bundle. It consists of the OSC-string "#bundle"
// followed by an OSC Time Tag, followed by zero or more OSC bundle/message
// elements. The OSC-timetag is a 64-bit fixed point time tag. See
// http://opensoundcontrol.org/spec-1_0 for more information.
type Bundle struct {
Timetag Timetag
Messages []*Message
Bundles []*Bundle
}
// Verify that Bundle implements the Packet interface.
var _ Packet = (*Bundle)(nil)
// Client enables you to send OSC packets. It sends OSC messages and bundles to
// the given IP address and port.
type Client struct {
ip string
port int
laddr *net.UDPAddr
}
// Server represents an OSC server. The server listens on Address and Port for
// incoming OSC packets and bundles.
type Server struct {
Addr string
Dispatcher Dispatcher
ReadTimeout time.Duration
}
// Timetag represents an OSC Time Tag.
// An OSC Time Tag is defined as follows:
// Time tags are represented by a 64 bit fixed point number. The first 32 bits
// specify the number of seconds since midnight on January 1, 1900, and the
// last 32 bits specify fractional parts of a second to a precision of about
// 200 picoseconds. This is the representation used by Internet NTP timestamps.
type Timetag struct {
timeTag uint64 // The acutal time tag
time time.Time
MinValue uint64 // Minimum value of an OSC Time Tag. Is always 1.
}
// Dispatcher is an interface for an OSC message dispatcher. A dispatcher is
// responsible for dispatching received OSC messages.
type Dispatcher interface {
Dispatch(packet Packet)
}
// Handler is an interface for message handlers. Every handler implementation
// for an OSC message must implement this interface.
type Handler interface {
HandleMessage(msg *Message)
}
// HandlerFunc implements the Handler interface. Type definition for an OSC
// handler function.
type HandlerFunc func(msg *Message)
// HandleMessage calls itself with the given OSC Message. Implements the
// Handler interface.
func (f HandlerFunc) HandleMessage(msg *Message) {
f(msg)
}
////
// StandardDispatcher
////
// StandardDispatcher is a dispatcher for OSC packets. It handles the dispatching of
// received OSC packets to Handlers for their given address.
type StandardDispatcher struct {
handlers map[string]Handler
defaultHandler Handler
}
// NewStandardDispatcher returns an StandardDispatcher.
func NewStandardDispatcher() *StandardDispatcher {
return &StandardDispatcher{handlers: make(map[string]Handler)}
}
// AddMsgHandler adds a new message handler for the given OSC address.
func (s *StandardDispatcher) AddMsgHandler(addr string, handler HandlerFunc) error {
if addr == "*" {
s.defaultHandler = handler
return nil
}
for _, chr := range "*?,[]{}# " {
if strings.Contains(addr, fmt.Sprintf("%c", chr)) {
return errors.New("OSC Address string may not contain any characters in \"*?,[]{}#")
}
}
if addressExists(addr, s.handlers) {
return errors.New("OSC address exists already")
}
s.handlers[addr] = handler
return nil
}
// Dispatch dispatches OSC packets. Implements the Dispatcher interface.
func (s *StandardDispatcher) Dispatch(packet Packet) {
switch p := packet.(type) {
default:
return
case *Message:
for addr, handler := range s.handlers {
if p.Match(addr) {
handler.HandleMessage(p)
}
}
if s.defaultHandler != nil {
s.defaultHandler.HandleMessage(p)
}
case *Bundle:
timer := time.NewTimer(p.Timetag.ExpiresIn())
go func() {
<-timer.C
for _, message := range p.Messages {
for address, handler := range s.handlers {
if message.Match(address) {
handler.HandleMessage(message)
}
}
if s.defaultHandler != nil {
s.defaultHandler.HandleMessage(message)
}
}
// Process all bundles
for _, b := range p.Bundles {
s.Dispatch(b)
}
}()
}
}
////
// Message
////
// NewMessage returns a new Message. The address parameter is the OSC address.
func NewMessage(addr string, args ...interface{}) *Message {
return &Message{Address: addr, Arguments: args}
}
// Append appends the given arguments to the arguments list.
func (msg *Message) Append(args ...interface{}) {
msg.Arguments = append(msg.Arguments, args...)
}
// Equals returns true if the given OSC Message `m` is equal to the current OSC
// Message. It checks if the OSC address and the arguments are equal. Returns
// true if the current object and `m` are equal.
func (msg *Message) Equals(m *Message) bool {
return reflect.DeepEqual(msg, m)
}
// Clear clears the OSC address and all arguments.
func (msg *Message) Clear() {
msg.Address = ""
msg.ClearData()
}
// ClearData removes all arguments from the OSC Message.
func (msg *Message) ClearData() {
msg.Arguments = msg.Arguments[len(msg.Arguments):]
}
// Match returns true, if the OSC address pattern of the OSC Message matches the given
// address. The match is case sensitive!
func (msg *Message) Match(addr string) bool {
exp := getRegEx(msg.Address)
if exp.MatchString(addr) {
return true
}
return false
}
// TypeTags returns the type tag string.
func (msg *Message) TypeTags() (string, error) {
if msg == nil {
return "", fmt.Errorf("message is nil")
}
tags := ","
for _, m := range msg.Arguments {
s, err := getTypeTag(m)
if err != nil {
return "", err
}
tags += s
}
return tags, nil
}
// String implements the fmt.Stringer interface.
func (msg *Message) String() string {
if msg == nil {
return ""
}
tags, err := msg.TypeTags()
if err != nil {
return ""
}
formatString := "%s %s"
var args []interface{}
args = append(args, msg.Address)
args = append(args, tags)
for _, arg := range msg.Arguments {
switch arg.(type) {
case bool, int32, int64, float32, float64, string:
formatString += " %v"
args = append(args, arg)
case nil:
formatString += " %s"
args = append(args, "Nil")
case []byte:
formatString += " %s"
args = append(args, "blob")
case Timetag:
formatString += " %d"
timeTag := arg.(Timetag)
args = append(args, timeTag.TimeTag())
}
}
return fmt.Sprintf(formatString, args...)
}
// CountArguments returns the number of arguments.
func (msg *Message) CountArguments() int {
return len(msg.Arguments)
}
// MarshalBinary serializes the OSC message to a byte buffer. The byte buffer
// has the following format:
// 1. OSC Address Pattern
// 2. OSC Type Tag String
// 3. OSC Arguments
func (msg *Message) MarshalBinary() ([]byte, error) {
// We can start with the OSC address and add it to the buffer
data := new(bytes.Buffer)
if _, err := writePaddedString(msg.Address, data); err != nil {
return nil, err
}
// Type tag string starts with ","
typetags := []byte{','}
// Process the type tags and collect all arguments
payload := new(bytes.Buffer)
for _, arg := range msg.Arguments {
// FIXME: Use t instead of arg
switch t := arg.(type) {
default:
return nil, fmt.Errorf("OSC - unsupported type: %T", t)
case bool:
if arg.(bool) == true {
typetags = append(typetags, 'T')
} else {
typetags = append(typetags, 'F')
}
case nil:
typetags = append(typetags, 'N')
case int32:
typetags = append(typetags, 'i')
if err := binary.Write(payload, binary.BigEndian, int32(t)); err != nil {
return nil, err
}
case float32:
typetags = append(typetags, 'f')
if err := binary.Write(payload, binary.BigEndian, float32(t)); err != nil {
return nil, err
}
case string:
typetags = append(typetags, 's')
if _, err := writePaddedString(t, payload); err != nil {
return nil, err
}
case []byte:
typetags = append(typetags, 'b')
if _, err := writeBlob(t, payload); err != nil {
return nil, err
}
case int64:
typetags = append(typetags, 'h')
if err := binary.Write(payload, binary.BigEndian, int64(t)); err != nil {
return nil, err
}
case float64:
typetags = append(typetags, 'd')
if err := binary.Write(payload, binary.BigEndian, float64(t)); err != nil {
return nil, err
}
case Timetag:
typetags = append(typetags, 't')
timeTag := arg.(Timetag)
b, err := timeTag.MarshalBinary()
if err != nil {
return nil, err
}
if _, err = payload.Write(b); err != nil {
return nil, err
}
}
}
// Write the type tag string to the data buffer
if _, err := writePaddedString(string(typetags), data); err != nil {
return nil, err
}
// Write the payload (OSC arguments) to the data buffer
if _, err := data.Write(payload.Bytes()); err != nil {
return nil, err
}
return data.Bytes(), nil
}
////
// Bundle
////
// NewBundle returns an OSC Bundle. Use this function to create a new OSC
// Bundle.
func NewBundle(time time.Time) *Bundle {
return &Bundle{Timetag: *NewTimetag(time)}
}
// Append appends an OSC bundle or OSC message to the bundle.
func (b *Bundle) Append(pck Packet) error {
switch t := pck.(type) {
default:
return fmt.Errorf("unsupported OSC packet type: only Bundle and Message are supported")
case *Bundle:
b.Bundles = append(b.Bundles, t)
case *Message:
b.Messages = append(b.Messages, t)
}
return nil
}
// MarshalBinary serializes the OSC bundle to a byte array with the following
// format:
// 1. Bundle string: '#bundle'
// 2. OSC timetag
// 3. Length of first OSC bundle element
// 4. First bundle element
// 5. Length of n OSC bundle element
// 6. n bundle element
func (b *Bundle) MarshalBinary() ([]byte, error) {
// Add the '#bundle' string
data := new(bytes.Buffer)
if _, err := writePaddedString("#bundle", data); err != nil {
return nil, err
}
// Add the time tag
bd, err := b.Timetag.MarshalBinary()
if err != nil {
return nil, err
}
if _, err = data.Write(bd); err != nil {
return nil, err
}
// Process all OSC Messages
for _, m := range b.Messages {
buf, err := m.MarshalBinary()
if err != nil {
return nil, err
}
// Append the length of the OSC message
if err = binary.Write(data, binary.BigEndian, int32(len(buf))); err != nil {
return nil, err
}
// Append the OSC message
if _, err = data.Write(buf); err != nil {
return nil, err
}
}
// Process all OSC Bundles
for _, b := range b.Bundles {
buf, err := b.MarshalBinary()
if err != nil {
return nil, err
}
// Write the size of the bundle
if err = binary.Write(data, binary.BigEndian, int32(len(buf))); err != nil {
return nil, err
}
// Append the bundle
_, err = data.Write(buf)
if err != nil {
return nil, err
}
}
return data.Bytes(), nil
}
////
// Client
////
// NewClient creates a new OSC client. The Client is used to send OSC
// messages and OSC bundles over an UDP network connection. The `ip` argument
// specifies the IP address and `port` defines the target port where the
// messages and bundles will be send to.
func NewClient(ip string, port int) *Client {
return &Client{ip: ip, port: port, laddr: nil}
}
// IP returns the IP address.
func (c *Client) IP() string { return c.ip }
// SetIP sets a new IP address.
func (c *Client) SetIP(ip string) { c.ip = ip }
// Port returns the port.
func (c *Client) Port() int { return c.port }
// SetPort sets a new port.
func (c *Client) SetPort(port int) { c.port = port }
// SetLocalAddr sets the local address.
func (c *Client) SetLocalAddr(ip string, port int) error {
laddr, err := net.ResolveUDPAddr("udp", fmt.Sprintf("%s:%d", ip, port))
if err != nil {
return err
}
c.laddr = laddr
return nil
}
// Send sends an OSC Bundle or an OSC Message.
func (c *Client) Send(packet Packet) error {
addr, err := net.ResolveUDPAddr("udp", fmt.Sprintf("%s:%d", c.ip, c.port))
if err != nil {
return err
}
conn, err := net.DialUDP("udp", c.laddr, addr)
if err != nil {
return err
}
defer conn.Close()
data, err := packet.MarshalBinary()
if err != nil {
return err
}
if _, err = conn.Write(data); err != nil {
return err
}
return nil
}
////
// Server
////
// ListenAndServe retrieves incoming OSC packets and dispatches the retrieved
// OSC packets.
func (s *Server) ListenAndServe() error {
if s.Dispatcher == nil {
s.Dispatcher = NewStandardDispatcher()
}
ln, err := net.ListenPacket("udp", s.Addr)
if err != nil {
return err
}
defer ln.Close()
return s.Serve(ln)
}
// Serve retrieves incoming OSC packets from the given connection and dispatches
// retrieved OSC packets. If something goes wrong an error is returned.
func (s *Server) Serve(c net.PacketConn) error {
var tempDelay time.Duration
for {
msg, err := s.readFromConnection(c)
if err != nil {
if ne, ok := err.(net.Error); ok && ne.Temporary() {
if tempDelay == 0 {
tempDelay = 5 * time.Millisecond
} else {
tempDelay *= 2
}
if max := 1 * time.Second; tempDelay > max {
tempDelay = max
}
time.Sleep(tempDelay)
continue
}
return err
}
tempDelay = 0
go s.Dispatcher.Dispatch(msg)
}
}
// ReceivePacket listens for incoming OSC packets and returns the packet if one is received.
func (s *Server) ReceivePacket(c net.PacketConn) (Packet, error) {
return s.readFromConnection(c)
}
// readFromConnection retrieves OSC packets.
func (s *Server) readFromConnection(c net.PacketConn) (Packet, error) {
if s.ReadTimeout != 0 {
if err := c.SetReadDeadline(time.Now().Add(s.ReadTimeout)); err != nil {
return nil, err
}
}
data := make([]byte, 65535)
n, _, err := c.ReadFrom(data)
if err != nil {
return nil, err
}
var start int
p, err := readPacket(bufio.NewReader(bytes.NewBuffer(data)), &start, n)
if err != nil {
return nil, err
}
return p, nil
}
// ParsePacket parses the given msg string and returns a Packet
func ParsePacket(msg string) (Packet, error) {
var start int
p, err := readPacket(bufio.NewReader(bytes.NewBufferString(msg)), &start, len(msg))
if err != nil {
return nil, err
}
return p, nil
}
// receivePacket receives an OSC packet from the given reader.
func readPacket(reader *bufio.Reader, start *int, end int) (Packet, error) {
//var buf []byte
buf, err := reader.Peek(1)
if err != nil {
return nil, err
}
// An OSC Message starts with a '/'
if buf[0] == '/' {
packet, err := readMessage(reader, start)
if err != nil {
return nil, err
}
return packet, nil
}
if buf[0] == '#' { // An OSC bundle starts with a '#'
packet, err := readBundle(reader, start, end)
if err != nil {
return nil, err
}
return packet, nil
}
var p Packet
return p, nil
}
// readBundle reads an Bundle from reader.
func readBundle(reader *bufio.Reader, start *int, end int) (*Bundle, error) {
// Read the '#bundle' OSC string
startTag, n, err := readPaddedString(reader)
if err != nil {
return nil, err
}
*start += n
if startTag != bundleTagString {
return nil, fmt.Errorf("Invalid bundle start tag: %s", startTag)
}
// Read the timetag
var timeTag uint64
if err := binary.Read(reader, binary.BigEndian, &timeTag); err != nil {
return nil, err
}
*start += 8
// Create a new bundle
bundle := NewBundle(timetagToTime(timeTag))
// Read until the end of the buffer
for *start < end {
// Read the size of the bundle element
var length int32
if err := binary.Read(reader, binary.BigEndian, &length); err != nil {
return nil, err
}
*start += 4
p, err := readPacket(reader, start, end)
if err != nil {
return nil, err
}
if err = bundle.Append(p); err != nil {
return nil, err
}
}
return bundle, nil
}
// readMessage from `reader`.
func readMessage(reader *bufio.Reader, start *int) (*Message, error) {
// First, read the OSC address
addr, n, err := readPaddedString(reader)
if err != nil {
return nil, err
}
*start += n
// Read all arguments
msg := NewMessage(addr)
if err = readArguments(msg, reader, start); err != nil {
return nil, err
}
return msg, nil
}
// readArguments from `reader` and add them to the OSC message `msg`.
func readArguments(msg *Message, reader *bufio.Reader, start *int) error {
// Read the type tag string
var n int
typetags, n, err := readPaddedString(reader)
if err != nil {
return err
}
*start += n
// If the typetag doesn't start with ',', it's not valid
if typetags[0] != ',' {
return fmt.Errorf("unsupported type tag string %s", typetags)
}
// Remove ',' from the type tag
typetags = typetags[1:]
for _, c := range typetags {
switch c {
default:
return fmt.Errorf("unsupported type tag: %c", c)
case 'i': // int32
var i int32
if err = binary.Read(reader, binary.BigEndian, &i); err != nil {
return err
}
*start += 4
msg.Append(i)
case 'h': // int64
var i int64
if err = binary.Read(reader, binary.BigEndian, &i); err != nil {
return err
}
*start += 8
msg.Append(i)
case 'f': // float32
var f float32
if err = binary.Read(reader, binary.BigEndian, &f); err != nil {
return err
}
*start += 4
msg.Append(f)
case 'd': // float64/double
var d float64
if err = binary.Read(reader, binary.BigEndian, &d); err != nil {
return err
}
*start += 8
msg.Append(d)
case 's': // string
// TODO: fix reading string value
var s string
if s, _, err = readPaddedString(reader); err != nil {
return err
}
*start += len(s) + padBytesNeeded(len(s))
msg.Append(s)
case 'b': // blob
var buf []byte
var n int
if buf, n, err = readBlob(reader); err != nil {
return err
}
*start += n
msg.Append(buf)
case 't': // OSC time tag
var tt uint64
if err = binary.Read(reader, binary.BigEndian, &tt); err != nil {
return nil
}
*start += 8
msg.Append(NewTimetagFromTimetag(tt))
case 'N': // nil
msg.Append(nil)
case 'T': // true
msg.Append(true)
case 'F': // false
msg.Append(false)
}
}
return nil
}
////
// Timetag
////
// NewTimetag returns a new OSC time tag object.
func NewTimetag(timeStamp time.Time) *Timetag {
return &Timetag{
time: timeStamp,
timeTag: timeToTimetag(timeStamp),
MinValue: uint64(1)}
}
// NewTimetagFromTimetag creates a new Timetag from the given `timetag`.
func NewTimetagFromTimetag(timetag uint64) *Timetag {
time := timetagToTime(timetag)
return NewTimetag(time)
}
// Time returns the time.
func (t *Timetag) Time() time.Time {
return t.time
}
// FractionalSecond returns the last 32 bits of the OSC time tag. Specifies the
// fractional part of a second.
func (t *Timetag) FractionalSecond() uint32 {
return uint32(t.timeTag << 32)
}
// SecondsSinceEpoch returns the first 32 bits (the number of seconds since the
// midnight 1900) from the OSC time tag.
func (t *Timetag) SecondsSinceEpoch() uint32 {
return uint32(t.timeTag >> 32)
}
// TimeTag returns the time tag value
func (t *Timetag) TimeTag() uint64 {
return t.timeTag
}
// MarshalBinary converts the OSC time tag to a byte array.
func (t *Timetag) MarshalBinary() ([]byte, error) {
data := new(bytes.Buffer)
if err := binary.Write(data, binary.BigEndian, t.timeTag); err != nil {
return []byte{}, err
}
return data.Bytes(), nil
}
// SetTime sets the value of the OSC time tag.
func (t *Timetag) SetTime(time time.Time) {
t.time = time
t.timeTag = timeToTimetag(time)
}
// ExpiresIn calculates the number of seconds until the current time is the
// same as the value of the time tag. It returns zero if the value of the
// time tag is in the past.
func (t *Timetag) ExpiresIn() time.Duration {
if t.timeTag <= 1 {
return 0
}
tt := timetagToTime(t.timeTag)
seconds := tt.Sub(time.Now())
if seconds <= 0 {
return 0
}
return seconds
}
// timeToTimetag converts the given time to an OSC time tag.
//
// An OSC time tag is defined as follows:
// Time tags are represented by a 64 bit fixed point number. The first 32 bits
// specify the number of seconds since midnight on January 1, 1900, and the
// last 32 bits specify fractional parts of a second to a precision of about
// 200 picoseconds. This is the representation used by Internet NTP timestamps.
//
// The time tag value consisting of 63 zero bits followed by a one in the least
// significant bit is a special case meaning "immediately."
func timeToTimetag(time time.Time) (timetag uint64) {
timetag = uint64((secondsFrom1900To1970 + time.Unix()) << 32)
return (timetag + uint64(uint32(time.Nanosecond())))
}
// timetagToTime converts the given timetag to a time object.
func timetagToTime(timetag uint64) (t time.Time) {
return time.Unix(int64((timetag>>32)-secondsFrom1900To1970), int64(timetag&0xffffffff))
}
////
// De/Encoding functions
////
// readBlob reads an OSC blob from the blob byte array. Padding bytes are
// removed from the reader and not returned.
func readBlob(reader *bufio.Reader) ([]byte, int, error) {
// First, get the length
var blobLen int32
if err := binary.Read(reader, binary.BigEndian, &blobLen); err != nil {
return nil, 0, err
}
n := 4 + int(blobLen)
// Read the data
blob := make([]byte, blobLen)
if _, err := reader.Read(blob); err != nil {
return nil, 0, err
}
// Remove the padding bytes
numPadBytes := padBytesNeeded(int(blobLen))
if numPadBytes > 0 {
n += numPadBytes
dummy := make([]byte, numPadBytes)
if _, err := reader.Read(dummy); err != nil {
return nil, 0, err
}
}
return blob, n, nil
}
// writeBlob writes the data byte array as an OSC blob into buff. If the length
// of data isn't 32-bit aligned, padding bytes will be added.
func writeBlob(data []byte, buf *bytes.Buffer) (int, error) {
// Add the size of the blob
dlen := int32(len(data))
if err := binary.Write(buf, binary.BigEndian, dlen); err != nil {
return 0, err
}
// Write the data
if _, err := buf.Write(data); err != nil {
return 0, nil
}
// Add padding bytes if necessary
numPadBytes := padBytesNeeded(len(data))
if numPadBytes > 0 {
padBytes := make([]byte, numPadBytes)
n, err := buf.Write(padBytes)
if err != nil {
return 0, err
}
numPadBytes = n
}
return 4 + len(data) + numPadBytes, nil
}
// readPaddedString reads a padded string from the given reader. The padding
// bytes are removed from the reader.
func readPaddedString(reader *bufio.Reader) (string, int, error) {
// Read the string from the reader
str, err := reader.ReadString(0)
if err != nil {
return "", 0, err
}
n := len(str)
// Remove the padding bytes (leaving the null delimiter)
padLen := padBytesNeeded(len(str))
if padLen > 0 {
n += padLen
padBytes := make([]byte, padLen)
if _, err = reader.Read(padBytes); err != nil {
return "", 0, err
}
}
// Strip off the string delimiter
return str[:len(str)-1], n, nil
}
// writePaddedString writes a string with padding bytes to the a buffer.
// Returns, the number of written bytes and an error if any.
func writePaddedString(str string, buf *bytes.Buffer) (int, error) {
// Truncate at the first null, just in case there is more than one present
nullIndex := strings.Index(str, "\x00")
if nullIndex > 0 {
str = str[:nullIndex]
}
// Write the string to the buffer
n, err := buf.WriteString(str)
if err != nil {
return 0, err
}
// Always write a null terminator, as we stripped it earlier if it existed
buf.WriteByte(0)
n += 1
// Calculate the padding bytes needed and create a buffer for the padding bytes
numPadBytes := padBytesNeeded(n)
if numPadBytes > 0 {
padBytes := make([]byte, numPadBytes)
// Add the padding bytes to the buffer
n, err := buf.Write(padBytes)
if err != nil {
return 0, err
}
numPadBytes = n
}