voice.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  1. // Discordgo - Discord bindings for Go
  2. // Available at https://github.com/bwmarrin/discordgo
  3. // Copyright 2015-2016 Bruce Marriner <bruce@sqls.net>. All rights reserved.
  4. // Use of this source code is governed by a BSD-style
  5. // license that can be found in the LICENSE file.
  6. // This file contains code related to Discord voice suppport
  7. package discordgo
  8. import (
  9. "encoding/binary"
  10. "encoding/json"
  11. "fmt"
  12. "net"
  13. "runtime"
  14. "strings"
  15. "sync"
  16. "time"
  17. "github.com/gorilla/websocket"
  18. )
  19. // ------------------------------------------------------------------------------------------------
  20. // Code related to both Voice Websocket and UDP connections.
  21. // ------------------------------------------------------------------------------------------------
  22. // A Voice struct holds all data and functions related to Discord Voice support.
  23. type Voice struct {
  24. sync.Mutex // future use
  25. Ready bool // If true, voice is ready to send/receive audio
  26. Debug bool // If true, print extra logging
  27. OP2 *voiceOP2 // exported for dgvoice, may change.
  28. OpusSend chan []byte // Chan for sending opus audio
  29. OpusRecv chan *Packet // Chan for receiving opus audio
  30. // FrameRate int // This can be used to set the FrameRate of Opus data
  31. // FrameSize int // This can be used to set the FrameSize of Opus data
  32. wsConn *websocket.Conn
  33. UDPConn *net.UDPConn // this will become unexported soon.
  34. sessionID string
  35. token string
  36. endpoint string
  37. guildID string
  38. channelID string
  39. userID string
  40. }
  41. // ------------------------------------------------------------------------------------------------
  42. // Code related to the Voice websocket connection
  43. // ------------------------------------------------------------------------------------------------
  44. // A voiceOP2 stores the data for the voice operation 2 websocket event
  45. // which is sort of like the voice READY packet
  46. type voiceOP2 struct {
  47. SSRC uint32 `json:"ssrc"`
  48. Port int `json:"port"`
  49. Modes []string `json:"modes"`
  50. HeartbeatInterval time.Duration `json:"heartbeat_interval"`
  51. }
  52. type voiceHandshakeData struct {
  53. ServerID string `json:"server_id"`
  54. UserID string `json:"user_id"`
  55. SessionID string `json:"session_id"`
  56. Token string `json:"token"`
  57. }
  58. type voiceHandshakeOp struct {
  59. Op int `json:"op"` // Always 0
  60. Data voiceHandshakeData `json:"d"`
  61. }
  62. // Open opens a voice connection. This should be called
  63. // after VoiceChannelJoin is used and the data VOICE websocket events
  64. // are captured.
  65. func (v *Voice) Open() (err error) {
  66. // TODO: How do we handle changing channels?
  67. // Don't open a websocket if one is already open
  68. if v.wsConn != nil {
  69. return
  70. }
  71. // Connect to Voice Websocket
  72. vg := fmt.Sprintf("wss://%s", strings.TrimSuffix(v.endpoint, ":80"))
  73. v.wsConn, _, err = websocket.DefaultDialer.Dial(vg, nil)
  74. if err != nil {
  75. fmt.Println("VOICE error opening websocket:", err)
  76. return
  77. }
  78. data := voiceHandshakeOp{0, voiceHandshakeData{v.guildID, v.userID, v.sessionID, v.token}}
  79. err = v.wsConn.WriteJSON(data)
  80. if err != nil {
  81. fmt.Println("VOICE error sending init packet:", err)
  82. return
  83. }
  84. // Start a listening for voice websocket events
  85. // TODO add a check here to make sure Listen worked by monitoring
  86. // a chan or bool?
  87. go v.wsListen()
  88. return
  89. }
  90. // Close closes the voice connection
  91. func (v *Voice) Close() {
  92. if v.UDPConn != nil {
  93. err := v.UDPConn.Close()
  94. if err != nil {
  95. fmt.Println("error closing udp connection: ", err)
  96. }
  97. }
  98. if v.wsConn != nil {
  99. err := v.wsConn.Close()
  100. if err != nil {
  101. fmt.Println("error closing websocket connection: ", err)
  102. }
  103. }
  104. }
  105. // wsListen listens on the voice websocket for messages and passes them
  106. // to the voice event handler. This is automatically called by the Open func
  107. func (v *Voice) wsListen() {
  108. for {
  109. messageType, message, err := v.wsConn.ReadMessage()
  110. if err != nil {
  111. // TODO: Handle this problem better.
  112. // TODO: needs proper logging
  113. fmt.Println("Voice Listen Error:", err)
  114. break
  115. }
  116. // Pass received message to voice event handler
  117. go v.wsEvent(messageType, message)
  118. }
  119. return
  120. }
  121. // wsEvent handles any voice websocket events. This is only called by the
  122. // wsListen() function.
  123. func (v *Voice) wsEvent(messageType int, message []byte) {
  124. if v.Debug {
  125. fmt.Println("wsEvent received: ", messageType)
  126. printJSON(message)
  127. }
  128. var e Event
  129. if err := json.Unmarshal(message, &e); err != nil {
  130. fmt.Println("wsEvent Unmarshall error: ", err)
  131. return
  132. }
  133. switch e.Operation {
  134. case 2: // READY
  135. v.OP2 = &voiceOP2{}
  136. if err := json.Unmarshal(e.RawData, v.OP2); err != nil {
  137. fmt.Println("voiceWS.onEvent OP2 Unmarshall error: ", err)
  138. printJSON(e.RawData) // TODO: Better error logging
  139. return
  140. }
  141. // Start the voice websocket heartbeat to keep the connection alive
  142. go v.wsHeartbeat(v.OP2.HeartbeatInterval)
  143. // TODO monitor a chan/bool to verify this was successful
  144. // Start the UDP connection
  145. err := v.udpOpen()
  146. if err != nil {
  147. fmt.Println("Error opening udp connection: ", err)
  148. return
  149. }
  150. // Start the opusSender.
  151. // TODO: Should we allow 48000/960 values to be user defined?
  152. v.OpusSend = make(chan []byte, 2)
  153. go v.opusSender(v.OpusSend, 48000, 960)
  154. // Start the opusReceiver
  155. v.OpusRecv = make(chan *Packet, 2)
  156. go v.opusReceiver(v.OpusRecv)
  157. return
  158. case 3: // HEARTBEAT response
  159. // add code to use this to track latency?
  160. return
  161. case 4:
  162. // TODO
  163. case 5:
  164. // SPEAKING TRUE/FALSE NOTIFICATION
  165. /*
  166. {
  167. "user_id": "1238921738912",
  168. "ssrc": 2,
  169. "speaking": false
  170. }
  171. */
  172. default:
  173. fmt.Println("UNKNOWN VOICE OP: ", e.Operation)
  174. printJSON(e.RawData)
  175. }
  176. return
  177. }
  178. type voiceHeartbeatOp struct {
  179. Op int `json:"op"` // Always 3
  180. Data int `json:"d"`
  181. }
  182. // wsHeartbeat sends regular heartbeats to voice Discord so it knows the client
  183. // is still connected. If you do not send these heartbeats Discord will
  184. // disconnect the websocket connection after a few seconds.
  185. func (v *Voice) wsHeartbeat(i time.Duration) {
  186. ticker := time.NewTicker(i * time.Millisecond)
  187. for {
  188. err := v.wsConn.WriteJSON(voiceHeartbeatOp{3, int(time.Now().Unix())})
  189. if err != nil {
  190. v.Ready = false
  191. fmt.Println("wsHeartbeat send error: ", err)
  192. return // TODO better logging
  193. }
  194. <-ticker.C
  195. }
  196. }
  197. type voiceSpeakingData struct {
  198. Speaking bool `json:"speaking"`
  199. Delay int `json:"delay"`
  200. }
  201. type voiceSpeakingOp struct {
  202. Op int `json:"op"` // Always 5
  203. Data voiceSpeakingData `json:"d"`
  204. }
  205. // Speaking sends a speaking notification to Discord over the voice websocket.
  206. // This must be sent as true prior to sending audio and should be set to false
  207. // once finished sending audio.
  208. // b : Send true if speaking, false if not.
  209. func (v *Voice) Speaking(b bool) (err error) {
  210. if v.wsConn == nil {
  211. return fmt.Errorf("No Voice websocket.")
  212. }
  213. data := voiceSpeakingOp{5, voiceSpeakingData{b, 0}}
  214. err = v.wsConn.WriteJSON(data)
  215. if err != nil {
  216. fmt.Println("Speaking() write json error:", err)
  217. return
  218. }
  219. return
  220. }
  221. // ------------------------------------------------------------------------------------------------
  222. // Code related to the Voice UDP connection
  223. // ------------------------------------------------------------------------------------------------
  224. type voiceUDPData struct {
  225. Address string `json:"address"` // Public IP of machine running this code
  226. Port uint16 `json:"port"` // UDP Port of machine running this code
  227. Mode string `json:"mode"` // plain or ? (plain or encrypted)
  228. }
  229. type voiceUDPD struct {
  230. Protocol string `json:"protocol"` // Always "udp" ?
  231. Data voiceUDPData `json:"data"`
  232. }
  233. type voiceUDPOp struct {
  234. Op int `json:"op"` // Always 1
  235. Data voiceUDPD `json:"d"`
  236. }
  237. // udpOpen opens a UDP connection to the voice server and completes the
  238. // initial required handshake. This connection is left open in the session
  239. // and can be used to send or receive audio. This should only be called
  240. // from voice.wsEvent OP2
  241. func (v *Voice) udpOpen() (err error) {
  242. host := fmt.Sprintf("%s:%d", strings.TrimSuffix(v.endpoint, ":80"), v.OP2.Port)
  243. addr, err := net.ResolveUDPAddr("udp", host)
  244. if err != nil {
  245. fmt.Println("udpOpen resolve addr error: ", err)
  246. // TODO better logging
  247. return
  248. }
  249. v.UDPConn, err = net.DialUDP("udp", nil, addr)
  250. if err != nil {
  251. fmt.Println("udpOpen dial udp error: ", err)
  252. // TODO better logging
  253. return
  254. }
  255. // Create a 70 byte array and put the SSRC code from the Op 2 Voice event
  256. // into it. Then send that over the UDP connection to Discord
  257. sb := make([]byte, 70)
  258. binary.BigEndian.PutUint32(sb, v.OP2.SSRC)
  259. _, err = v.UDPConn.Write(sb)
  260. if err != nil {
  261. fmt.Println("udpOpen udp write error : ", err)
  262. // TODO better logging
  263. return
  264. }
  265. // Create a 70 byte array and listen for the initial handshake response
  266. // from Discord. Once we get it parse the IP and PORT information out
  267. // of the response. This should be our public IP and PORT as Discord
  268. // saw us.
  269. rb := make([]byte, 70)
  270. rlen, _, err := v.UDPConn.ReadFromUDP(rb)
  271. if err != nil {
  272. fmt.Println("udpOpen udp read error : ", err)
  273. // TODO better logging
  274. return
  275. }
  276. if rlen < 70 {
  277. fmt.Println("Voice RLEN should be 70 but isn't")
  278. }
  279. // Loop over position 4 though 20 to grab the IP address
  280. // Should never be beyond position 20.
  281. var ip string
  282. for i := 4; i < 20; i++ {
  283. if rb[i] == 0 {
  284. break
  285. }
  286. ip += string(rb[i])
  287. }
  288. // Grab port from position 68 and 69
  289. port := binary.LittleEndian.Uint16(rb[68:70])
  290. // Take the data from above and send it back to Discord to finalize
  291. // the UDP connection handshake.
  292. data := voiceUDPOp{1, voiceUDPD{"udp", voiceUDPData{ip, port, "plain"}}}
  293. err = v.wsConn.WriteJSON(data)
  294. if err != nil {
  295. fmt.Println("udpOpen write json error:", err)
  296. return
  297. }
  298. // start udpKeepAlive
  299. go v.udpKeepAlive(5 * time.Second)
  300. // TODO: find a way to check that it fired off okay
  301. return
  302. }
  303. // udpKeepAlive sends a udp packet to keep the udp connection open
  304. // This is still a bit of a "proof of concept"
  305. func (v *Voice) udpKeepAlive(i time.Duration) {
  306. var err error
  307. var sequence uint64
  308. packet := make([]byte, 8)
  309. ticker := time.NewTicker(i)
  310. for {
  311. // TODO: Add a way to break from loop
  312. binary.LittleEndian.PutUint64(packet, sequence)
  313. sequence++
  314. _, err = v.UDPConn.Write(packet)
  315. if err != nil {
  316. fmt.Println("udpKeepAlive udp write error : ", err)
  317. return
  318. }
  319. <-ticker.C
  320. }
  321. }
  322. // opusSender will listen on the given channel and send any
  323. // pre-encoded opus audio to Discord. Supposedly.
  324. func (v *Voice) opusSender(opus <-chan []byte, rate, size int) {
  325. // TODO: Better checking to prevent this from running more than
  326. // one instance at a time.
  327. v.Lock()
  328. if opus == nil {
  329. v.Unlock()
  330. return
  331. }
  332. v.Unlock()
  333. runtime.LockOSThread()
  334. // Voice is now ready to receive audio packets
  335. // TODO: this needs reviewed as I think there must be a better way.
  336. v.Ready = true
  337. defer func() { v.Ready = false }()
  338. var sequence uint16
  339. var timestamp uint32
  340. udpHeader := make([]byte, 12)
  341. // build the parts that don't change in the udpHeader
  342. udpHeader[0] = 0x80
  343. udpHeader[1] = 0x78
  344. binary.BigEndian.PutUint32(udpHeader[8:], v.OP2.SSRC)
  345. // start a send loop that loops until buf chan is closed
  346. ticker := time.NewTicker(time.Millisecond * time.Duration(size/(rate/1000)))
  347. for {
  348. // Add sequence and timestamp to udpPacket
  349. binary.BigEndian.PutUint16(udpHeader[2:], sequence)
  350. binary.BigEndian.PutUint32(udpHeader[4:], timestamp)
  351. // Get data from chan. If chan is closed, return.
  352. recvbuf, ok := <-opus
  353. if !ok {
  354. return
  355. }
  356. // Combine the UDP Header and the opus data
  357. sendbuf := append(udpHeader, recvbuf...)
  358. // block here until we're exactly at the right time :)
  359. // Then send rtp audio packet to Discord over UDP
  360. <-ticker.C
  361. _, err := v.UDPConn.Write(sendbuf)
  362. if err != nil {
  363. fmt.Println("error writing to udp connection: ", err)
  364. }
  365. if (sequence) == 0xFFFF {
  366. sequence = 0
  367. } else {
  368. sequence++
  369. }
  370. if (timestamp + uint32(size)) >= 0xFFFFFFFF {
  371. timestamp = 0
  372. } else {
  373. timestamp += uint32(size)
  374. }
  375. }
  376. }
  377. // A Packet contains the headers and content of a received voice packet.
  378. type Packet struct {
  379. SSRC uint32
  380. Sequence uint16
  381. Timestamp uint32
  382. Type []byte
  383. Opus []byte
  384. PCM []int16
  385. }
  386. // opusReceiver listens on the UDP socket for incoming packets
  387. // and sends them across the given channel
  388. // NOTE :: This function may change names later.
  389. func (v *Voice) opusReceiver(c chan *Packet) {
  390. // TODO: Better checking to prevent this from running more than
  391. // one instance at a time.
  392. v.Lock()
  393. if c == nil {
  394. v.Unlock()
  395. return
  396. }
  397. v.Unlock()
  398. p := Packet{}
  399. recvbuf := make([]byte, 1024)
  400. for {
  401. rlen, err := v.UDPConn.Read(recvbuf)
  402. if err != nil {
  403. fmt.Println("opusReceiver UDP Read error:", err)
  404. return
  405. }
  406. // For now, skip anything except audio.
  407. if rlen < 12 || recvbuf[0] != 0x80 {
  408. continue
  409. }
  410. p.Type = recvbuf[0:2]
  411. p.Sequence = binary.BigEndian.Uint16(recvbuf[2:4])
  412. p.Timestamp = binary.BigEndian.Uint32(recvbuf[4:8])
  413. p.SSRC = binary.BigEndian.Uint32(recvbuf[8:12])
  414. p.Opus = recvbuf[12:rlen]
  415. if c != nil {
  416. c <- &p
  417. }
  418. }
  419. }