voice.go 18 KB

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