voice.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680
  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. "golang.org/x/crypto/nacl/secretbox"
  19. )
  20. // ------------------------------------------------------------------------------------------------
  21. // Code related to both VoiceConnection Websocket and UDP connections.
  22. // ------------------------------------------------------------------------------------------------
  23. // A VoiceConnectionConnection struct holds all the data and functions related to a Discord Voice Connection.
  24. type VoiceConnection struct {
  25. sync.Mutex
  26. Debug bool // If true, print extra logging
  27. Ready bool // If true, voice is ready to send/receive audio
  28. GuildID string
  29. ChannelID string
  30. UserID string
  31. OpusSend chan []byte // Chan for sending opus audio
  32. OpusRecv chan *Packet // Chan for receiving opus audio
  33. // FrameRate int // This can be used to set the FrameRate of Opus data
  34. // FrameSize int // This can be used to set the FrameSize of Opus data
  35. wsConn *websocket.Conn
  36. udpConn *net.UDPConn
  37. session *Session
  38. sessionID string
  39. token string
  40. endpoint string
  41. op4 voiceOP4
  42. op2 voiceOP2
  43. // Used to send a close signal to goroutines
  44. close chan struct{}
  45. // Used to allow blocking until connected
  46. connected chan bool
  47. // Used to pass the sessionid from onVoiceStateUpdate
  48. sessionRecv chan string
  49. }
  50. // ------------------------------------------------------------------------------------------------
  51. // Code related to the VoiceConnection websocket connection
  52. // ------------------------------------------------------------------------------------------------
  53. // A voiceOP4 stores the data for the voice operation 4 websocket event
  54. // which provides us with the NaCl SecretBox encryption key
  55. type voiceOP4 struct {
  56. SecretKey [32]byte `json:"secret_key"`
  57. Mode string `json:"mode"`
  58. }
  59. // A voiceOP2 stores the data for the voice operation 2 websocket event
  60. // which is sort of like the voice READY packet
  61. type voiceOP2 struct {
  62. SSRC uint32 `json:"ssrc"`
  63. Port int `json:"port"`
  64. Modes []string `json:"modes"`
  65. HeartbeatInterval time.Duration `json:"heartbeat_interval"`
  66. }
  67. type voiceHandshakeData struct {
  68. ServerID string `json:"server_id"`
  69. UserID string `json:"user_id"`
  70. SessionID string `json:"session_id"`
  71. Token string `json:"token"`
  72. }
  73. type voiceHandshakeOp struct {
  74. Op int `json:"op"` // Always 0
  75. Data voiceHandshakeData `json:"d"`
  76. }
  77. // Open opens a voice connection. This should be called
  78. // after VoiceChannelJoin is used and the data VOICE websocket events
  79. // are captured.
  80. func (v *VoiceConnection) Open() (err error) {
  81. v.Lock()
  82. defer v.Unlock()
  83. // Don't open a websocket if one is already open
  84. if v.wsConn != nil {
  85. return
  86. }
  87. // Connect to VoiceConnection Websocket
  88. vg := fmt.Sprintf("wss://%s", strings.TrimSuffix(v.endpoint, ":80"))
  89. v.wsConn, _, err = websocket.DefaultDialer.Dial(vg, nil)
  90. if err != nil {
  91. fmt.Println("VOICE error opening websocket:", err)
  92. return
  93. }
  94. data := voiceHandshakeOp{0, voiceHandshakeData{v.GuildID, v.UserID, v.sessionID, v.token}}
  95. err = v.wsConn.WriteJSON(data)
  96. if err != nil {
  97. fmt.Println("VOICE error sending init packet:", err)
  98. return
  99. }
  100. // Start a listening for voice websocket events
  101. // TODO add a check here to make sure Listen worked by monitoring
  102. // a chan or bool?
  103. v.close = make(chan struct{})
  104. go v.wsListen(v.wsConn, v.close)
  105. return
  106. }
  107. // WaitUntilConnected is a TEMP FUNCTION
  108. // And this is going to be removed or changed entirely.
  109. // I know it looks hacky, but I needed to get it working quickly.
  110. func (v *VoiceConnection) WaitUntilConnected() error {
  111. i := 0
  112. for {
  113. if v.Ready {
  114. return nil
  115. }
  116. if i > 10 {
  117. return fmt.Errorf("Timeout waiting for voice.")
  118. }
  119. time.Sleep(1 * time.Second)
  120. i++
  121. }
  122. return nil
  123. }
  124. type voiceSpeakingData struct {
  125. Speaking bool `json:"speaking"`
  126. Delay int `json:"delay"`
  127. }
  128. type voiceSpeakingOp struct {
  129. Op int `json:"op"` // Always 5
  130. Data voiceSpeakingData `json:"d"`
  131. }
  132. // Speaking sends a speaking notification to Discord over the voice websocket.
  133. // This must be sent as true prior to sending audio and should be set to false
  134. // once finished sending audio.
  135. // b : Send true if speaking, false if not.
  136. func (v *VoiceConnection) Speaking(b bool) (err error) {
  137. if v.wsConn == nil {
  138. return fmt.Errorf("No VoiceConnection websocket.")
  139. }
  140. data := voiceSpeakingOp{5, voiceSpeakingData{b, 0}}
  141. err = v.wsConn.WriteJSON(data)
  142. if err != nil {
  143. fmt.Println("Speaking() write json error:", err)
  144. return
  145. }
  146. return
  147. }
  148. // ChangeChannel sends Discord a request to change channels within a Guild
  149. // !!! NOTE !!! This function may be removed in favour of just using ChannelVoiceJoin
  150. func (v *VoiceConnection) ChangeChannel(channelID string, mute, deaf bool) (err error) {
  151. data := voiceChannelJoinOp{4, voiceChannelJoinData{&v.GuildID, &channelID, mute, deaf}}
  152. err = v.session.wsConn.WriteJSON(data)
  153. return
  154. }
  155. // Disconnect disconnects from this voice channel and closes the websocket
  156. // and udp connections to Discord.
  157. // !!! NOTE !!! this function may be removed in favour of ChannelVoiceLeave
  158. func (v *VoiceConnection) Disconnect() (err error) {
  159. // Send a OP4 with a nil channel to disconnect
  160. if v.sessionID != "" {
  161. data := voiceChannelJoinOp{4, voiceChannelJoinData{&v.GuildID, nil, true, true}}
  162. err = v.session.wsConn.WriteJSON(data)
  163. v.sessionID = ""
  164. }
  165. // Close websocket and udp connections
  166. v.Close()
  167. delete(v.session.VoiceConnections, v.GuildID)
  168. return
  169. }
  170. // Close closes the voice ws and udp connections
  171. func (v *VoiceConnection) Close() {
  172. v.Lock()
  173. defer v.Unlock()
  174. v.Ready = false
  175. if v.close != nil {
  176. close(v.close)
  177. v.close = nil
  178. }
  179. if v.udpConn != nil {
  180. err := v.udpConn.Close()
  181. if err != nil {
  182. fmt.Println("error closing udp connection: ", err)
  183. }
  184. v.udpConn = nil
  185. }
  186. if v.wsConn != nil {
  187. err := v.wsConn.Close()
  188. if err != nil {
  189. fmt.Println("error closing websocket connection: ", err)
  190. }
  191. v.wsConn = nil
  192. }
  193. }
  194. // ------------------------------------------------------------------------------------------------
  195. // Unexported Internal Functions Below.
  196. // ------------------------------------------------------------------------------------------------
  197. // wsListen listens on the voice websocket for messages and passes them
  198. // to the voice event handler. This is automatically called by the Open func
  199. func (v *VoiceConnection) wsListen(wsConn *websocket.Conn, close <-chan struct{}) {
  200. for {
  201. messageType, message, err := v.wsConn.ReadMessage()
  202. if err != nil {
  203. // TODO: add reconnect, matching wsapi.go:listen()
  204. // TODO: Handle this problem better.
  205. // TODO: needs proper logging
  206. fmt.Println("VoiceConnection Listen Error:", err)
  207. return
  208. }
  209. // Pass received message to voice event handler
  210. select {
  211. case <-close:
  212. return
  213. default:
  214. go v.wsEvent(messageType, message)
  215. }
  216. }
  217. }
  218. // wsEvent handles any voice websocket events. This is only called by the
  219. // wsListen() function.
  220. func (v *VoiceConnection) wsEvent(messageType int, message []byte) {
  221. if v.Debug {
  222. fmt.Println("wsEvent received: ", messageType)
  223. printJSON(message)
  224. }
  225. var e Event
  226. if err := json.Unmarshal(message, &e); err != nil {
  227. fmt.Println("wsEvent Unmarshall error: ", err)
  228. return
  229. }
  230. switch e.Operation {
  231. case 2: // READY
  232. if err := json.Unmarshal(e.RawData, &v.op2); err != nil {
  233. fmt.Println("voiceWS.onEvent OP2 Unmarshall error: ", err)
  234. printJSON(e.RawData) // TODO: Better error logging
  235. return
  236. }
  237. // Start the voice websocket heartbeat to keep the connection alive
  238. go v.wsHeartbeat(v.wsConn, v.close, v.op2.HeartbeatInterval)
  239. // TODO monitor a chan/bool to verify this was successful
  240. // Start the UDP connection
  241. err := v.udpOpen()
  242. if err != nil {
  243. fmt.Println("Error opening udp connection: ", err)
  244. return
  245. }
  246. // Start the opusSender.
  247. // TODO: Should we allow 48000/960 values to be user defined?
  248. if v.OpusSend == nil {
  249. v.OpusSend = make(chan []byte, 2)
  250. }
  251. go v.opusSender(v.udpConn, v.close, v.OpusSend, 48000, 960)
  252. // Start the opusReceiver
  253. if v.OpusRecv == nil {
  254. v.OpusRecv = make(chan *Packet, 2)
  255. }
  256. go v.opusReceiver(v.udpConn, v.close, v.OpusRecv)
  257. // Send the ready event
  258. v.connected <- true
  259. return
  260. case 3: // HEARTBEAT response
  261. // add code to use this to track latency?
  262. return
  263. case 4: // udp encryption secret key
  264. v.op4 = voiceOP4{}
  265. if err := json.Unmarshal(e.RawData, &v.op4); err != nil {
  266. fmt.Println("voiceWS.onEvent OP4 Unmarshall error: ", err)
  267. printJSON(e.RawData)
  268. return
  269. }
  270. return
  271. case 5:
  272. // SPEAKING TRUE/FALSE NOTIFICATION
  273. /*
  274. {
  275. "user_id": "1238921738912",
  276. "ssrc": 2,
  277. "speaking": false
  278. }
  279. */
  280. default:
  281. fmt.Println("UNKNOWN VOICE OP: ", e.Operation)
  282. printJSON(e.RawData)
  283. }
  284. return
  285. }
  286. type voiceHeartbeatOp struct {
  287. Op int `json:"op"` // Always 3
  288. Data int `json:"d"`
  289. }
  290. // NOTE :: When a guild voice server changes how do we shut this down
  291. // properly, so a new connection can be setup without fuss?
  292. //
  293. // wsHeartbeat sends regular heartbeats to voice Discord so it knows the client
  294. // is still connected. If you do not send these heartbeats Discord will
  295. // disconnect the websocket connection after a few seconds.
  296. func (v *VoiceConnection) wsHeartbeat(wsConn *websocket.Conn, close <-chan struct{}, i time.Duration) {
  297. if close == nil || wsConn == nil {
  298. return
  299. }
  300. var err error
  301. ticker := time.NewTicker(i * time.Millisecond)
  302. for {
  303. err = wsConn.WriteJSON(voiceHeartbeatOp{3, int(time.Now().Unix())})
  304. if err != nil {
  305. fmt.Println("wsHeartbeat send error: ", err)
  306. return
  307. }
  308. select {
  309. case <-ticker.C:
  310. // continue loop and send heartbeat
  311. case <-close:
  312. return
  313. }
  314. }
  315. }
  316. // ------------------------------------------------------------------------------------------------
  317. // Code related to the VoiceConnection UDP connection
  318. // ------------------------------------------------------------------------------------------------
  319. type voiceUDPData struct {
  320. Address string `json:"address"` // Public IP of machine running this code
  321. Port uint16 `json:"port"` // UDP Port of machine running this code
  322. Mode string `json:"mode"` // always "xsalsa20_poly1305"
  323. }
  324. type voiceUDPD struct {
  325. Protocol string `json:"protocol"` // Always "udp" ?
  326. Data voiceUDPData `json:"data"`
  327. }
  328. type voiceUDPOp struct {
  329. Op int `json:"op"` // Always 1
  330. Data voiceUDPD `json:"d"`
  331. }
  332. // udpOpen opens a UDP connection to the voice server and completes the
  333. // initial required handshake. This connection is left open in the session
  334. // and can be used to send or receive audio. This should only be called
  335. // from voice.wsEvent OP2
  336. func (v *VoiceConnection) udpOpen() (err error) {
  337. v.Lock()
  338. defer v.Unlock()
  339. if v.wsConn == nil {
  340. return fmt.Errorf("nil voice websocket")
  341. }
  342. if v.udpConn != nil {
  343. return fmt.Errorf("udp connection already open")
  344. }
  345. if v.close == nil {
  346. return fmt.Errorf("nil close channel")
  347. }
  348. if v.endpoint == "" {
  349. return fmt.Errorf("empty endpoint")
  350. }
  351. host := fmt.Sprintf("%s:%d", strings.TrimSuffix(v.endpoint, ":80"), v.op2.Port)
  352. addr, err := net.ResolveUDPAddr("udp", host)
  353. if err != nil {
  354. fmt.Println("udpOpen resolve addr error: ", err)
  355. // TODO better logging
  356. return
  357. }
  358. v.udpConn, err = net.DialUDP("udp", nil, addr)
  359. if err != nil {
  360. fmt.Println("udpOpen dial udp error: ", err)
  361. // TODO better logging
  362. return
  363. }
  364. // Create a 70 byte array and put the SSRC code from the Op 2 VoiceConnection event
  365. // into it. Then send that over the UDP connection to Discord
  366. sb := make([]byte, 70)
  367. binary.BigEndian.PutUint32(sb, v.op2.SSRC)
  368. _, err = v.udpConn.Write(sb)
  369. if err != nil {
  370. fmt.Println("udpOpen udp write error : ", err)
  371. // TODO better logging
  372. return
  373. }
  374. // Create a 70 byte array and listen for the initial handshake response
  375. // from Discord. Once we get it parse the IP and PORT information out
  376. // of the response. This should be our public IP and PORT as Discord
  377. // saw us.
  378. rb := make([]byte, 70)
  379. rlen, _, err := v.udpConn.ReadFromUDP(rb)
  380. if err != nil {
  381. fmt.Println("udpOpen udp read error : ", err)
  382. // TODO better logging
  383. return
  384. }
  385. if rlen < 70 {
  386. fmt.Println("VoiceConnection RLEN should be 70 but isn't")
  387. }
  388. // Loop over position 4 though 20 to grab the IP address
  389. // Should never be beyond position 20.
  390. var ip string
  391. for i := 4; i < 20; i++ {
  392. if rb[i] == 0 {
  393. break
  394. }
  395. ip += string(rb[i])
  396. }
  397. // Grab port from position 68 and 69
  398. port := binary.LittleEndian.Uint16(rb[68:70])
  399. // Take the data from above and send it back to Discord to finalize
  400. // the UDP connection handshake.
  401. data := voiceUDPOp{1, voiceUDPD{"udp", voiceUDPData{ip, port, "xsalsa20_poly1305"}}}
  402. err = v.wsConn.WriteJSON(data)
  403. if err != nil {
  404. fmt.Println("udpOpen write json error:", err)
  405. return
  406. }
  407. // start udpKeepAlive
  408. go v.udpKeepAlive(v.udpConn, v.close, 5*time.Second)
  409. // TODO: find a way to check that it fired off okay
  410. return
  411. }
  412. // udpKeepAlive sends a udp packet to keep the udp connection open
  413. // This is still a bit of a "proof of concept"
  414. func (v *VoiceConnection) udpKeepAlive(udpConn *net.UDPConn, close <-chan struct{}, i time.Duration) {
  415. if udpConn == nil || close == nil {
  416. return
  417. }
  418. var err error
  419. var sequence uint64
  420. packet := make([]byte, 8)
  421. ticker := time.NewTicker(i)
  422. for {
  423. binary.LittleEndian.PutUint64(packet, sequence)
  424. sequence++
  425. _, err = udpConn.Write(packet)
  426. if err != nil {
  427. fmt.Println("udpKeepAlive udp write error : ", err)
  428. return
  429. }
  430. select {
  431. case <-ticker.C:
  432. // continue loop and send keepalive
  433. case <-close:
  434. return
  435. }
  436. }
  437. }
  438. // opusSender will listen on the given channel and send any
  439. // pre-encoded opus audio to Discord. Supposedly.
  440. func (v *VoiceConnection) opusSender(udpConn *net.UDPConn, close <-chan struct{}, opus <-chan []byte, rate, size int) {
  441. if udpConn == nil || close == nil {
  442. return
  443. }
  444. runtime.LockOSThread()
  445. // VoiceConnection is now ready to receive audio packets
  446. // TODO: this needs reviewed as I think there must be a better way.
  447. v.Ready = true
  448. defer func() { v.Ready = false }()
  449. var sequence uint16
  450. var timestamp uint32
  451. var recvbuf []byte
  452. var ok bool
  453. udpHeader := make([]byte, 12)
  454. var nonce [24]byte
  455. // build the parts that don't change in the udpHeader
  456. udpHeader[0] = 0x80
  457. udpHeader[1] = 0x78
  458. binary.BigEndian.PutUint32(udpHeader[8:], v.op2.SSRC)
  459. // start a send loop that loops until buf chan is closed
  460. ticker := time.NewTicker(time.Millisecond * time.Duration(size/(rate/1000)))
  461. for {
  462. // Get data from chan. If chan is closed, return.
  463. select {
  464. case <-close:
  465. return
  466. case recvbuf, ok = <-opus:
  467. if !ok {
  468. return
  469. }
  470. // else, continue loop
  471. }
  472. // Add sequence and timestamp to udpPacket
  473. binary.BigEndian.PutUint16(udpHeader[2:], sequence)
  474. binary.BigEndian.PutUint32(udpHeader[4:], timestamp)
  475. // encrypt the opus data
  476. copy(nonce[:], udpHeader)
  477. sendbuf := secretbox.Seal(udpHeader, recvbuf, &nonce, &v.op4.SecretKey)
  478. // block here until we're exactly at the right time :)
  479. // Then send rtp audio packet to Discord over UDP
  480. select {
  481. case <-close:
  482. return
  483. case <-ticker.C:
  484. // continue
  485. }
  486. _, err := udpConn.Write(sendbuf)
  487. if err != nil {
  488. fmt.Println("error writing to udp connection: ", err)
  489. return
  490. }
  491. if (sequence) == 0xFFFF {
  492. sequence = 0
  493. } else {
  494. sequence++
  495. }
  496. if (timestamp + uint32(size)) >= 0xFFFFFFFF {
  497. timestamp = 0
  498. } else {
  499. timestamp += uint32(size)
  500. }
  501. }
  502. }
  503. // A Packet contains the headers and content of a received voice packet.
  504. type Packet struct {
  505. SSRC uint32
  506. Sequence uint16
  507. Timestamp uint32
  508. Type []byte
  509. Opus []byte
  510. PCM []int16
  511. }
  512. // opusReceiver listens on the UDP socket for incoming packets
  513. // and sends them across the given channel
  514. // NOTE :: This function may change names later.
  515. func (v *VoiceConnection) opusReceiver(udpConn *net.UDPConn, close <-chan struct{}, c chan *Packet) {
  516. if udpConn == nil || close == nil {
  517. return
  518. }
  519. p := Packet{}
  520. recvbuf := make([]byte, 1024)
  521. var nonce [24]byte
  522. for {
  523. rlen, err := udpConn.Read(recvbuf)
  524. if err != nil {
  525. fmt.Println("opusReceiver UDP Read error:", err)
  526. return
  527. }
  528. select {
  529. case <-close:
  530. return
  531. default:
  532. // continue loop
  533. }
  534. // For now, skip anything except audio.
  535. if rlen < 12 || recvbuf[0] != 0x80 {
  536. continue
  537. }
  538. // build a audio packet struct
  539. p.Type = recvbuf[0:2]
  540. p.Sequence = binary.BigEndian.Uint16(recvbuf[2:4])
  541. p.Timestamp = binary.BigEndian.Uint32(recvbuf[4:8])
  542. p.SSRC = binary.BigEndian.Uint32(recvbuf[8:12])
  543. // decrypt opus data
  544. copy(nonce[:], recvbuf[0:12])
  545. p.Opus, _ = secretbox.Open(nil, recvbuf[12:rlen], &nonce, &v.op4.SecretKey)
  546. if c != nil {
  547. c <- &p
  548. }
  549. }
  550. }