voice.go 14 KB

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