voice.go 18 KB

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