voice.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  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. Opus chan []byte // Chan for sending opus audio
  29. // FrameRate int // This can be used to set the FrameRate of Opus data
  30. // FrameSize int // This can be used to set the FrameSize of Opus data
  31. wsConn *websocket.Conn
  32. UDPConn *net.UDPConn // this will become unexported soon.
  33. sessionID string
  34. token string
  35. endpoint string
  36. guildID string
  37. channelID string
  38. userID string
  39. }
  40. // ------------------------------------------------------------------------------------------------
  41. // Code related to the Voice websocket connection
  42. // ------------------------------------------------------------------------------------------------
  43. // A voiceOP2 stores the data for the voice operation 2 websocket event
  44. // which is sort of like the voice READY packet
  45. type voiceOP2 struct {
  46. SSRC uint32 `json:"ssrc"`
  47. Port int `json:"port"`
  48. Modes []string `json:"modes"`
  49. HeartbeatInterval time.Duration `json:"heartbeat_interval"`
  50. }
  51. type voiceHandshakeData struct {
  52. ServerID string `json:"server_id"`
  53. UserID string `json:"user_id"`
  54. SessionID string `json:"session_id"`
  55. Token string `json:"token"`
  56. }
  57. type voiceHandshakeOp struct {
  58. Op int `json:"op"` // Always 0
  59. Data voiceHandshakeData `json:"d"`
  60. }
  61. // Open opens a voice connection. This should be called
  62. // after VoiceChannelJoin is used and the data VOICE websocket events
  63. // are captured.
  64. func (v *Voice) Open() (err error) {
  65. // TODO: How do we handle changing channels?
  66. // Don't open a websocket if one is already open
  67. if v.wsConn != nil {
  68. return
  69. }
  70. // Connect to Voice Websocket
  71. vg := fmt.Sprintf("wss://%s", strings.TrimSuffix(v.endpoint, ":80"))
  72. v.wsConn, _, err = websocket.DefaultDialer.Dial(vg, nil)
  73. if err != nil {
  74. fmt.Println("VOICE error opening websocket:", err)
  75. return
  76. }
  77. data := voiceHandshakeOp{0, voiceHandshakeData{v.guildID, v.userID, v.sessionID, v.token}}
  78. err = v.wsConn.WriteJSON(data)
  79. if err != nil {
  80. fmt.Println("VOICE error sending init packet:", err)
  81. return
  82. }
  83. // Start a listening for voice websocket events
  84. // TODO add a check here to make sure Listen worked by monitoring
  85. // a chan or bool?
  86. go v.wsListen()
  87. return
  88. }
  89. // Close closes the voice connection
  90. func (v *Voice) Close() {
  91. if v.UDPConn != nil {
  92. v.UDPConn.Close()
  93. }
  94. if v.wsConn != nil {
  95. v.wsConn.Close()
  96. }
  97. }
  98. // wsListen listens on the voice websocket for messages and passes them
  99. // to the voice event handler. This is automaticly called by the Open func
  100. func (v *Voice) wsListen() {
  101. for {
  102. messageType, message, err := v.wsConn.ReadMessage()
  103. if err != nil {
  104. // TODO: Handle this problem better.
  105. // TODO: needs proper logging
  106. fmt.Println("Voice Listen Error:", err)
  107. break
  108. }
  109. // Pass received message to voice event handler
  110. go v.wsEvent(messageType, message)
  111. }
  112. return
  113. }
  114. // wsEvent handles any voice websocket events. This is only called by the
  115. // wsListen() function.
  116. func (v *Voice) wsEvent(messageType int, message []byte) {
  117. if v.Debug {
  118. fmt.Println("wsEvent received: ", messageType)
  119. printJSON(message)
  120. }
  121. var e Event
  122. if err := json.Unmarshal(message, &e); err != nil {
  123. fmt.Println("wsEvent Unmarshall error: ", err)
  124. return
  125. }
  126. switch e.Operation {
  127. case 2: // READY
  128. v.OP2 = &voiceOP2{}
  129. if err := json.Unmarshal(e.RawData, v.OP2); err != nil {
  130. fmt.Println("voiceWS.onEvent OP2 Unmarshall error: ", err)
  131. printJSON(e.RawData) // TODO: Better error logging
  132. return
  133. }
  134. // Start the voice websocket heartbeat to keep the connection alive
  135. go v.wsHeartbeat(v.OP2.HeartbeatInterval)
  136. // TODO monitor a chan/bool to verify this was successful
  137. // Start the UDP connection
  138. err := v.udpOpen()
  139. if err != nil {
  140. fmt.Println("Error opening udp connection: ", err)
  141. return
  142. }
  143. // Start the opusSender.
  144. // TODO: Should we allow 48000/960 values to be user defined?
  145. v.Opus = make(chan []byte, 2)
  146. go v.opusSender(v.Opus, 48000, 960)
  147. return
  148. case 3: // HEARTBEAT response
  149. // add code to use this to track latency?
  150. return
  151. case 4:
  152. // TODO
  153. case 5:
  154. // SPEAKING TRUE/FALSE NOTIFICATION
  155. /*
  156. {
  157. "user_id": "1238921738912",
  158. "ssrc": 2,
  159. "speaking": false
  160. }
  161. */
  162. default:
  163. fmt.Println("UNKNOWN VOICE OP: ", e.Operation)
  164. printJSON(e.RawData)
  165. }
  166. return
  167. }
  168. type voiceHeartbeatOp struct {
  169. Op int `json:"op"` // Always 3
  170. Data int `json:"d"`
  171. }
  172. // wsHeartbeat sends regular heartbeats to voice Discord so it knows the client
  173. // is still connected. If you do not send these heartbeats Discord will
  174. // disconnect the websocket connection after a few seconds.
  175. func (v *Voice) wsHeartbeat(i time.Duration) {
  176. ticker := time.NewTicker(i * time.Millisecond)
  177. for {
  178. err := v.wsConn.WriteJSON(voiceHeartbeatOp{3, int(time.Now().Unix())})
  179. if err != nil {
  180. v.Ready = false
  181. fmt.Println("wsHeartbeat send error: ", err)
  182. return // TODO better logging
  183. }
  184. <-ticker.C
  185. }
  186. }
  187. type voiceSpeakingData struct {
  188. Speaking bool `json:"speaking"`
  189. Delay int `json:"delay"`
  190. }
  191. type voiceSpeakingOp struct {
  192. Op int `json:"op"` // Always 5
  193. Data voiceSpeakingData `json:"d"`
  194. }
  195. // Speaking sends a speaking notification to Discord over the voice websocket.
  196. // This must be sent as true prior to sending audio and should be set to false
  197. // once finished sending audio.
  198. // b : Send true if speaking, false if not.
  199. func (v *Voice) Speaking(b bool) (err error) {
  200. if v.wsConn == nil {
  201. return fmt.Errorf("No Voice websocket.")
  202. }
  203. data := voiceSpeakingOp{5, voiceSpeakingData{b, 0}}
  204. err = v.wsConn.WriteJSON(data)
  205. if err != nil {
  206. fmt.Println("Speaking() write json error:", err)
  207. return
  208. }
  209. return
  210. }
  211. // ------------------------------------------------------------------------------------------------
  212. // Code related to the Voice UDP connection
  213. // ------------------------------------------------------------------------------------------------
  214. type voiceUDPData struct {
  215. Address string `json:"address"` // Public IP of machine running this code
  216. Port uint16 `json:"port"` // UDP Port of machine running this code
  217. Mode string `json:"mode"` // plain or ? (plain or encrypted)
  218. }
  219. type voiceUDPD struct {
  220. Protocol string `json:"protocol"` // Always "udp" ?
  221. Data voiceUDPData `json:"data"`
  222. }
  223. type voiceUDPOp struct {
  224. Op int `json:"op"` // Always 1
  225. Data voiceUDPD `json:"d"`
  226. }
  227. // udpOpen opens a UDP connection to the voice server and completes the
  228. // initial required handshake. This connection is left open in the session
  229. // and can be used to send or receive audio. This should only be called
  230. // from voice.wsEvent OP2
  231. func (v *Voice) udpOpen() (err error) {
  232. host := fmt.Sprintf("%s:%d", strings.TrimSuffix(v.endpoint, ":80"), v.OP2.Port)
  233. addr, err := net.ResolveUDPAddr("udp", host)
  234. if err != nil {
  235. fmt.Println("udpOpen resolve addr error: ", err)
  236. // TODO better logging
  237. return
  238. }
  239. v.UDPConn, err = net.DialUDP("udp", nil, addr)
  240. if err != nil {
  241. fmt.Println("udpOpen dial udp error: ", err)
  242. // TODO better logging
  243. return
  244. }
  245. // Create a 70 byte array and put the SSRC code from the Op 2 Voice event
  246. // into it. Then send that over the UDP connection to Discord
  247. sb := make([]byte, 70)
  248. binary.BigEndian.PutUint32(sb, v.OP2.SSRC)
  249. _, err = v.UDPConn.Write(sb)
  250. if err != nil {
  251. fmt.Println("udpOpen udp write error : ", err)
  252. // TODO better logging
  253. return
  254. }
  255. // Create a 70 byte array and listen for the initial handshake response
  256. // from Discord. Once we get it parse the IP and PORT information out
  257. // of the response. This should be our public IP and PORT as Discord
  258. // saw us.
  259. rb := make([]byte, 70)
  260. rlen, _, err := v.UDPConn.ReadFromUDP(rb)
  261. if err != nil {
  262. fmt.Println("udpOpen udp read error : ", err)
  263. // TODO better logging
  264. return
  265. }
  266. if rlen < 70 {
  267. fmt.Println("Voice RLEN should be 70 but isn't")
  268. }
  269. // Loop over position 4 though 20 to grab the IP address
  270. // Should never be beyond position 20.
  271. var ip string
  272. for i := 4; i < 20; i++ {
  273. if rb[i] == 0 {
  274. break
  275. }
  276. ip += string(rb[i])
  277. }
  278. // Grab port from postion 68 and 69
  279. port := binary.LittleEndian.Uint16(rb[68:70])
  280. // Take the data from above and send it back to Discord to finalize
  281. // the UDP connection handshake.
  282. data := voiceUDPOp{1, voiceUDPD{"udp", voiceUDPData{ip, port, "plain"}}}
  283. err = v.wsConn.WriteJSON(data)
  284. if err != nil {
  285. fmt.Println("udpOpen write json error:", err)
  286. return
  287. }
  288. // start udpKeepAlive
  289. go v.udpKeepAlive(5 * time.Second)
  290. // TODO: find a way to check that it fired off okay
  291. return
  292. }
  293. // udpKeepAlive sends a udp packet to keep the udp connection open
  294. // This is still a bit of a "proof of concept"
  295. func (v *Voice) udpKeepAlive(i time.Duration) {
  296. var err error
  297. var sequence uint64 = 0
  298. packet := make([]byte, 8)
  299. ticker := time.NewTicker(i)
  300. for {
  301. // TODO: Add a way to break from loop
  302. binary.LittleEndian.PutUint64(packet, sequence)
  303. sequence++
  304. _, err = v.UDPConn.Write(packet)
  305. if err != nil {
  306. fmt.Println("udpKeepAlive udp write error : ", err)
  307. return
  308. }
  309. <-ticker.C
  310. }
  311. }
  312. // opusSender will listen on the given channel and send any
  313. // pre-encoded opus audio to Discord. Supposedly.
  314. func (v *Voice) opusSender(opus <-chan []byte, rate, size int) {
  315. // TODO: Better checking to prevent this from running more than
  316. // one instance at a time.
  317. v.Lock()
  318. if opus == nil {
  319. v.Unlock()
  320. return
  321. }
  322. v.Unlock()
  323. runtime.LockOSThread()
  324. // Voice is now ready to receive audio packets
  325. // TODO: this needs reviewed as I think there must be a better way.
  326. v.Ready = true
  327. var sequence uint16 = 0
  328. var timestamp uint32 = 0
  329. udpHeader := make([]byte, 12)
  330. // build the parts that don't change in the udpHeader
  331. udpHeader[0] = 0x80
  332. udpHeader[1] = 0x78
  333. binary.BigEndian.PutUint32(udpHeader[8:], v.OP2.SSRC)
  334. // start a send loop that loops until buf chan is closed
  335. ticker := time.NewTicker(time.Millisecond * time.Duration(size/(rate/1000)))
  336. for {
  337. // Add sequence and timestamp to udpPacket
  338. binary.BigEndian.PutUint16(udpHeader[2:], sequence)
  339. binary.BigEndian.PutUint32(udpHeader[4:], timestamp)
  340. // Get data from chan. If chan is closed, return.
  341. recvbuf, ok := <-opus
  342. if !ok {
  343. return
  344. }
  345. // Combine the UDP Header and the opus data
  346. sendbuf := append(udpHeader, recvbuf...)
  347. // block here until we're exactly at the right time :)
  348. // Then send rtp audio packet to Discord over UDP
  349. <-ticker.C
  350. v.UDPConn.Write(sendbuf)
  351. if (sequence) == 0xFFFF {
  352. sequence = 0
  353. } else {
  354. sequence += 1
  355. }
  356. if (timestamp + uint32(size)) >= 0xFFFFFFFF {
  357. timestamp = 0
  358. } else {
  359. timestamp += uint32(size)
  360. }
  361. }
  362. }