voice.go 16 KB

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