voice.go 16 KB

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