This repository has been archived by the owner on Jun 29, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
appleMidiServer.go
81 lines (66 loc) · 1.88 KB
/
appleMidiServer.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
package main
import (
"bytes"
"encoding/binary"
"log"
"net"
)
var controlSrv *net.UDPConn
var appleSessions AppleMidiSessions
func StartAppleMidi() {
netAddr, err := net.ResolveUDPAddr("udp", ":5004")
if err != nil {
panic(err)
}
controlSrv, err = net.ListenUDP("udp", netAddr)
if err != nil {
panic(err)
}
appleSessions = make(AppleMidiSessions)
for {
pBuf := make([]byte, 64)
totalBytes, remoteAddr, err := controlSrv.ReadFromUDP(pBuf)
if err != nil {
panic(err)
}
log.Printf("Got %d bytes from %s\n", totalBytes, remoteAddr.String())
dataBuf, command, err := CheckApplePacketValid(pBuf, totalBytes)
if err != nil {
log.Println(err)
continue
}
//command := binary.BigEndian.Uint16(dataBuf.Next(2))
if command == 0x494e { // 'IN'
log.Println("IN packet")
session := HandleInvitation(dataBuf)
appleSessions[string(session.RemoteSSRC)] = session
var payload bytes.Buffer
payload.Write([]byte{0xff, 0xff, 0x4f, 0x4b})
binary.Write(&payload, binary.BigEndian, uint32(2))
payload.Write(session.InitToken)
payload.Write(session.LocalSSRC)
payload.WriteString(session.LocalName)
payload.WriteByte(0x00)
_, err = controlSrv.WriteToUDP(payload.Bytes(), remoteAddr)
// TODO: Start session handler
} else if command == 0x5253 { // 'RS'
log.Println("RS packet")
session, ok := appleSessions[string(dataBuf.Next(4))]
if ok {
session.MidiAck <- binary.BigEndian.Uint16(dataBuf.Next(2))
}
} else if command == 0x4259 { // 'BY'
log.Println("BY packet")
initToken := dataBuf.Next(4)[:]
senderSSRC := string(dataBuf.Next(4))
if bytes.Equal(appleSessions[senderSSRC].InitToken, initToken) {
close(appleSessions[senderSSRC].MidiAck)
delete(appleSessions, senderSSRC)
} else {
log.Println("OI! Someone else tried to disconnect us! Assholes...")
}
} else {
log.Println("?? packet")
}
}
}