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. OP2 *voiceOP2 // exported for dgvoice, may change.
  34. // FrameRate int // This can be used to set the FrameRate of Opus data
  35. // FrameSize int // This can be used to set the FrameSize of Opus data
  36. wsConn *websocket.Conn
  37. UDPConn *net.UDPConn // this will become unexported soon.
  38. session *Session
  39. sessionID string
  40. token string
  41. endpoint string
  42. op4 voiceOP4
  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. v.OP2 = &voiceOP2{}
  233. if err := json.Unmarshal(e.RawData, v.OP2); err != nil {
  234. fmt.Println("voiceWS.onEvent OP2 Unmarshall error: ", err)
  235. printJSON(e.RawData) // TODO: Better error logging
  236. return
  237. }
  238. // Start the voice websocket heartbeat to keep the connection alive
  239. go v.wsHeartbeat(v.wsConn, v.close, v.OP2.HeartbeatInterval)
  240. // TODO monitor a chan/bool to verify this was successful
  241. // Start the UDP connection
  242. err := v.udpOpen()
  243. if err != nil {
  244. fmt.Println("Error opening udp connection: ", err)
  245. return
  246. }
  247. // Start the opusSender.
  248. // TODO: Should we allow 48000/960 values to be user defined?
  249. if v.OpusSend == nil {
  250. v.OpusSend = make(chan []byte, 2)
  251. }
  252. go v.opusSender(v.UDPConn, v.close, v.OpusSend, 48000, 960)
  253. // Start the opusReceiver
  254. if v.OpusRecv == nil {
  255. v.OpusRecv = make(chan *Packet, 2)
  256. }
  257. go v.opusReceiver(v.UDPConn, v.close, v.OpusRecv)
  258. // Send the ready event
  259. v.connected <- true
  260. return
  261. case 3: // HEARTBEAT response
  262. // add code to use this to track latency?
  263. return
  264. case 4: // udp encryption secret key
  265. v.op4 = voiceOP4{}
  266. if err := json.Unmarshal(e.RawData, &v.op4); err != nil {
  267. fmt.Println("voiceWS.onEvent OP4 Unmarshall error: ", err)
  268. printJSON(e.RawData)
  269. return
  270. }
  271. return
  272. case 5:
  273. // SPEAKING TRUE/FALSE NOTIFICATION
  274. /*
  275. {
  276. "user_id": "1238921738912",
  277. "ssrc": 2,
  278. "speaking": false
  279. }
  280. */
  281. default:
  282. fmt.Println("UNKNOWN VOICE OP: ", e.Operation)
  283. printJSON(e.RawData)
  284. }
  285. return
  286. }
  287. type voiceHeartbeatOp struct {
  288. Op int `json:"op"` // Always 3
  289. Data int `json:"d"`
  290. }
  291. // NOTE :: When a guild voice server changes how do we shut this down
  292. // properly, so a new connection can be setup without fuss?
  293. //
  294. // wsHeartbeat sends regular heartbeats to voice Discord so it knows the client
  295. // is still connected. If you do not send these heartbeats Discord will
  296. // disconnect the websocket connection after a few seconds.
  297. func (v *VoiceConnection) wsHeartbeat(wsConn *websocket.Conn, close <-chan struct{}, i time.Duration) {
  298. if close == nil || wsConn == nil {
  299. return
  300. }
  301. var err error
  302. ticker := time.NewTicker(i * time.Millisecond)
  303. for {
  304. err = wsConn.WriteJSON(voiceHeartbeatOp{3, int(time.Now().Unix())})
  305. if err != nil {
  306. fmt.Println("wsHeartbeat send error: ", err)
  307. return
  308. }
  309. select {
  310. case <-ticker.C:
  311. // continue loop and send heartbeat
  312. case <-close:
  313. return
  314. }
  315. }
  316. }
  317. // ------------------------------------------------------------------------------------------------
  318. // Code related to the VoiceConnection UDP connection
  319. // ------------------------------------------------------------------------------------------------
  320. type voiceUDPData struct {
  321. Address string `json:"address"` // Public IP of machine running this code
  322. Port uint16 `json:"port"` // UDP Port of machine running this code
  323. Mode string `json:"mode"` // always "xsalsa20_poly1305"
  324. }
  325. type voiceUDPD struct {
  326. Protocol string `json:"protocol"` // Always "udp" ?
  327. Data voiceUDPData `json:"data"`
  328. }
  329. type voiceUDPOp struct {
  330. Op int `json:"op"` // Always 1
  331. Data voiceUDPD `json:"d"`
  332. }
  333. // udpOpen opens a UDP connection to the voice server and completes the
  334. // initial required handshake. This connection is left open in the session
  335. // and can be used to send or receive audio. This should only be called
  336. // from voice.wsEvent OP2
  337. func (v *VoiceConnection) udpOpen() (err error) {
  338. v.Lock()
  339. defer v.Unlock()
  340. if v.wsConn == nil {
  341. return fmt.Errorf("nil voice websocket")
  342. }
  343. if v.UDPConn != nil {
  344. return fmt.Errorf("udp connection already open")
  345. }
  346. if v.close == nil {
  347. return fmt.Errorf("nil close channel")
  348. }
  349. if v.endpoint == "" {
  350. return fmt.Errorf("empty endpoint")
  351. }
  352. host := fmt.Sprintf("%s:%d", strings.TrimSuffix(v.endpoint, ":80"), v.OP2.Port)
  353. addr, err := net.ResolveUDPAddr("udp", host)
  354. if err != nil {
  355. fmt.Println("udpOpen resolve addr error: ", err)
  356. // TODO better logging
  357. return
  358. }
  359. v.UDPConn, err = net.DialUDP("udp", nil, addr)
  360. if err != nil {
  361. fmt.Println("udpOpen dial udp error: ", err)
  362. // TODO better logging
  363. return
  364. }
  365. // Create a 70 byte array and put the SSRC code from the Op 2 VoiceConnection event
  366. // into it. Then send that over the UDP connection to Discord
  367. sb := make([]byte, 70)
  368. binary.BigEndian.PutUint32(sb, v.OP2.SSRC)
  369. _, err = v.UDPConn.Write(sb)
  370. if err != nil {
  371. fmt.Println("udpOpen udp write error : ", err)
  372. // TODO better logging
  373. return
  374. }
  375. // Create a 70 byte array and listen for the initial handshake response
  376. // from Discord. Once we get it parse the IP and PORT information out
  377. // of the response. This should be our public IP and PORT as Discord
  378. // saw us.
  379. rb := make([]byte, 70)
  380. rlen, _, err := v.UDPConn.ReadFromUDP(rb)
  381. if err != nil {
  382. fmt.Println("udpOpen udp read error : ", err)
  383. // TODO better logging
  384. return
  385. }
  386. if rlen < 70 {
  387. fmt.Println("VoiceConnection RLEN should be 70 but isn't")
  388. }
  389. // Loop over position 4 though 20 to grab the IP address
  390. // Should never be beyond position 20.
  391. var ip string
  392. for i := 4; i < 20; i++ {
  393. if rb[i] == 0 {
  394. break
  395. }
  396. ip += string(rb[i])
  397. }
  398. // Grab port from position 68 and 69
  399. port := binary.LittleEndian.Uint16(rb[68:70])
  400. // Take the data from above and send it back to Discord to finalize
  401. // the UDP connection handshake.
  402. data := voiceUDPOp{1, voiceUDPD{"udp", voiceUDPData{ip, port, "xsalsa20_poly1305"}}}
  403. err = v.wsConn.WriteJSON(data)
  404. if err != nil {
  405. fmt.Println("udpOpen write json error:", err)
  406. return
  407. }
  408. // start udpKeepAlive
  409. go v.udpKeepAlive(v.UDPConn, v.close, 5*time.Second)
  410. // TODO: find a way to check that it fired off okay
  411. return
  412. }
  413. // udpKeepAlive sends a udp packet to keep the udp connection open
  414. // This is still a bit of a "proof of concept"
  415. func (v *VoiceConnection) udpKeepAlive(UDPConn *net.UDPConn, close <-chan struct{}, i time.Duration) {
  416. if UDPConn == nil || close == nil {
  417. return
  418. }
  419. var err error
  420. var sequence uint64
  421. packet := make([]byte, 8)
  422. ticker := time.NewTicker(i)
  423. for {
  424. binary.LittleEndian.PutUint64(packet, sequence)
  425. sequence++
  426. _, err = UDPConn.Write(packet)
  427. if err != nil {
  428. fmt.Println("udpKeepAlive udp write error : ", err)
  429. return
  430. }
  431. select {
  432. case <-ticker.C:
  433. // continue loop and send keepalive
  434. case <-close:
  435. return
  436. }
  437. }
  438. }
  439. // opusSender will listen on the given channel and send any
  440. // pre-encoded opus audio to Discord. Supposedly.
  441. func (v *VoiceConnection) opusSender(UDPConn *net.UDPConn, close <-chan struct{}, opus <-chan []byte, rate, size int) {
  442. if UDPConn == nil || close == nil {
  443. return
  444. }
  445. runtime.LockOSThread()
  446. // VoiceConnection is now ready to receive audio packets
  447. // TODO: this needs reviewed as I think there must be a better way.
  448. v.Ready = true
  449. defer func() { v.Ready = false }()
  450. var sequence uint16
  451. var timestamp uint32
  452. var recvbuf []byte
  453. var ok bool
  454. udpHeader := make([]byte, 12)
  455. var nonce [24]byte
  456. // build the parts that don't change in the udpHeader
  457. udpHeader[0] = 0x80
  458. udpHeader[1] = 0x78
  459. binary.BigEndian.PutUint32(udpHeader[8:], v.OP2.SSRC)
  460. // start a send loop that loops until buf chan is closed
  461. ticker := time.NewTicker(time.Millisecond * time.Duration(size/(rate/1000)))
  462. for {
  463. // Get data from chan. If chan is closed, return.
  464. select {
  465. case <-close:
  466. return
  467. case recvbuf, ok = <-opus:
  468. if !ok {
  469. return
  470. }
  471. // else, continue loop
  472. }
  473. // Add sequence and timestamp to udpPacket
  474. binary.BigEndian.PutUint16(udpHeader[2:], sequence)
  475. binary.BigEndian.PutUint32(udpHeader[4:], timestamp)
  476. // encrypt the opus data
  477. copy(nonce[:], udpHeader)
  478. sendbuf := secretbox.Seal(udpHeader, recvbuf, &nonce, &v.op4.SecretKey)
  479. // block here until we're exactly at the right time :)
  480. // Then send rtp audio packet to Discord over UDP
  481. select {
  482. case <-close:
  483. return
  484. case <-ticker.C:
  485. // continue
  486. }
  487. _, err := UDPConn.Write(sendbuf)
  488. if err != nil {
  489. fmt.Println("error writing to udp connection: ", err)
  490. return
  491. }
  492. if (sequence) == 0xFFFF {
  493. sequence = 0
  494. } else {
  495. sequence++
  496. }
  497. if (timestamp + uint32(size)) >= 0xFFFFFFFF {
  498. timestamp = 0
  499. } else {
  500. timestamp += uint32(size)
  501. }
  502. }
  503. }
  504. // A Packet contains the headers and content of a received voice packet.
  505. type Packet struct {
  506. SSRC uint32
  507. Sequence uint16
  508. Timestamp uint32
  509. Type []byte
  510. Opus []byte
  511. PCM []int16
  512. }
  513. // opusReceiver listens on the UDP socket for incoming packets
  514. // and sends them across the given channel
  515. // NOTE :: This function may change names later.
  516. func (v *VoiceConnection) opusReceiver(UDPConn *net.UDPConn, close <-chan struct{}, c chan *Packet) {
  517. if UDPConn == nil || close == nil {
  518. return
  519. }
  520. p := Packet{}
  521. recvbuf := make([]byte, 1024)
  522. var nonce [24]byte
  523. for {
  524. rlen, err := UDPConn.Read(recvbuf)
  525. if err != nil {
  526. fmt.Println("opusReceiver UDP Read error:", err)
  527. return
  528. }
  529. select {
  530. case <-close:
  531. return
  532. default:
  533. // continue loop
  534. }
  535. // For now, skip anything except audio.
  536. if rlen < 12 || recvbuf[0] != 0x80 {
  537. continue
  538. }
  539. // build a audio packet struct
  540. p.Type = recvbuf[0:2]
  541. p.Sequence = binary.BigEndian.Uint16(recvbuf[2:4])
  542. p.Timestamp = binary.BigEndian.Uint32(recvbuf[4:8])
  543. p.SSRC = binary.BigEndian.Uint32(recvbuf[8:12])
  544. // decrypt opus data
  545. copy(nonce[:], recvbuf[0:12])
  546. p.Opus, _ = secretbox.Open(nil, recvbuf[12:rlen], &nonce, &v.op4.SecretKey)
  547. if c != nil {
  548. c <- &p
  549. }
  550. }
  551. }