voice.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906
  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. "strconv"
  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 VoiceConnection struct holds all the data and functions related to a Discord Voice Connection.
  24. type VoiceConnection struct {
  25. sync.RWMutex
  26. Debug bool // If true, print extra logging -- DEPRECATED
  27. LogLevel int
  28. Ready bool // If true, voice is ready to send/receive audio
  29. UserID string
  30. GuildID string
  31. ChannelID string
  32. deaf bool
  33. mute bool
  34. speaking bool
  35. reconnecting bool // If true, voice connection is trying to reconnect
  36. OpusSend chan []byte // Chan for sending opus audio
  37. OpusRecv chan *Packet // Chan for receiving opus audio
  38. wsConn *websocket.Conn
  39. wsMutex sync.Mutex
  40. udpConn *net.UDPConn
  41. session *Session
  42. sessionID string
  43. token string
  44. endpoint string
  45. // Used to send a close signal to goroutines
  46. close chan struct{}
  47. // Used to allow blocking until connected
  48. connected chan bool
  49. // Used to pass the sessionid from onVoiceStateUpdate
  50. // sessionRecv chan string UNUSED ATM
  51. op4 voiceOP4
  52. op2 voiceOP2
  53. voiceSpeakingUpdateHandlers []VoiceSpeakingUpdateHandler
  54. }
  55. // VoiceSpeakingUpdateHandler type provides a function definition for the
  56. // VoiceSpeakingUpdate event
  57. type VoiceSpeakingUpdateHandler func(vc *VoiceConnection, vs *VoiceSpeakingUpdate)
  58. // Speaking sends a speaking notification to Discord over the voice websocket.
  59. // This must be sent as true prior to sending audio and should be set to false
  60. // once finished sending audio.
  61. // b : Send true if speaking, false if not.
  62. func (v *VoiceConnection) Speaking(b bool) (err error) {
  63. v.log(LogDebug, "called (%t)", b)
  64. type voiceSpeakingData struct {
  65. Speaking bool `json:"speaking"`
  66. Delay int `json:"delay"`
  67. }
  68. type voiceSpeakingOp struct {
  69. Op int `json:"op"` // Always 5
  70. Data voiceSpeakingData `json:"d"`
  71. }
  72. if v.wsConn == nil {
  73. return fmt.Errorf("no VoiceConnection websocket")
  74. }
  75. data := voiceSpeakingOp{5, voiceSpeakingData{b, 0}}
  76. v.wsMutex.Lock()
  77. err = v.wsConn.WriteJSON(data)
  78. v.wsMutex.Unlock()
  79. v.Lock()
  80. defer v.Unlock()
  81. if err != nil {
  82. v.speaking = false
  83. v.log(LogError, "Speaking() write json error, %s", err)
  84. return
  85. }
  86. v.speaking = b
  87. return
  88. }
  89. // ChangeChannel sends Discord a request to change channels within a Guild
  90. // !!! NOTE !!! This function may be removed in favour of just using ChannelVoiceJoin
  91. func (v *VoiceConnection) ChangeChannel(channelID string, mute, deaf bool) (err error) {
  92. v.log(LogInformational, "called")
  93. data := voiceChannelJoinOp{4, voiceChannelJoinData{&v.GuildID, &channelID, mute, deaf}}
  94. v.wsMutex.Lock()
  95. err = v.session.wsConn.WriteJSON(data)
  96. v.wsMutex.Unlock()
  97. if err != nil {
  98. return
  99. }
  100. v.ChannelID = channelID
  101. v.deaf = deaf
  102. v.mute = mute
  103. v.speaking = false
  104. return
  105. }
  106. // Disconnect disconnects from this voice channel and closes the websocket
  107. // and udp connections to Discord.
  108. func (v *VoiceConnection) Disconnect() (err error) {
  109. // Send a OP4 with a nil channel to disconnect
  110. if v.sessionID != "" {
  111. data := voiceChannelJoinOp{4, voiceChannelJoinData{&v.GuildID, nil, true, true}}
  112. v.session.wsMutex.Lock()
  113. err = v.session.wsConn.WriteJSON(data)
  114. v.session.wsMutex.Unlock()
  115. v.sessionID = ""
  116. }
  117. // Close websocket and udp connections
  118. v.Close()
  119. v.log(LogInformational, "Deleting VoiceConnection %s", v.GuildID)
  120. v.session.Lock()
  121. delete(v.session.VoiceConnections, v.GuildID)
  122. v.session.Unlock()
  123. return
  124. }
  125. // Close closes the voice ws and udp connections
  126. func (v *VoiceConnection) Close() {
  127. v.log(LogInformational, "called")
  128. v.Lock()
  129. defer v.Unlock()
  130. v.Ready = false
  131. v.speaking = false
  132. if v.close != nil {
  133. v.log(LogInformational, "closing v.close")
  134. close(v.close)
  135. v.close = nil
  136. }
  137. if v.udpConn != nil {
  138. v.log(LogInformational, "closing udp")
  139. err := v.udpConn.Close()
  140. if err != nil {
  141. v.log(LogError, "error closing udp connection, %s", err)
  142. }
  143. v.udpConn = nil
  144. }
  145. if v.wsConn != nil {
  146. v.log(LogInformational, "sending close frame")
  147. // To cleanly close a connection, a client should send a close
  148. // frame and wait for the server to close the connection.
  149. v.wsMutex.Lock()
  150. err := v.wsConn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
  151. v.wsMutex.Unlock()
  152. if err != nil {
  153. v.log(LogError, "error closing websocket, %s", err)
  154. }
  155. // TODO: Wait for Discord to actually close the connection.
  156. time.Sleep(1 * time.Second)
  157. v.log(LogInformational, "closing websocket")
  158. err = v.wsConn.Close()
  159. if err != nil {
  160. v.log(LogError, "error closing websocket, %s", err)
  161. }
  162. v.wsConn = nil
  163. }
  164. }
  165. // AddHandler adds a Handler for VoiceSpeakingUpdate events.
  166. func (v *VoiceConnection) AddHandler(h VoiceSpeakingUpdateHandler) {
  167. v.Lock()
  168. defer v.Unlock()
  169. v.voiceSpeakingUpdateHandlers = append(v.voiceSpeakingUpdateHandlers, h)
  170. }
  171. // VoiceSpeakingUpdate is a struct for a VoiceSpeakingUpdate event.
  172. type VoiceSpeakingUpdate struct {
  173. UserID string `json:"user_id"`
  174. SSRC int `json:"ssrc"`
  175. Speaking bool `json:"speaking"`
  176. }
  177. // ------------------------------------------------------------------------------------------------
  178. // Unexported Internal Functions Below.
  179. // ------------------------------------------------------------------------------------------------
  180. // A voiceOP4 stores the data for the voice operation 4 websocket event
  181. // which provides us with the NaCl SecretBox encryption key
  182. type voiceOP4 struct {
  183. SecretKey [32]byte `json:"secret_key"`
  184. Mode string `json:"mode"`
  185. }
  186. // A voiceOP2 stores the data for the voice operation 2 websocket event
  187. // which is sort of like the voice READY packet
  188. type voiceOP2 struct {
  189. SSRC uint32 `json:"ssrc"`
  190. Port int `json:"port"`
  191. Modes []string `json:"modes"`
  192. HeartbeatInterval time.Duration `json:"heartbeat_interval"`
  193. IP string `json:"ip"`
  194. }
  195. // WaitUntilConnected waits for the Voice Connection to
  196. // become ready, if it does not become ready it returns an err
  197. func (v *VoiceConnection) waitUntilConnected() error {
  198. v.log(LogInformational, "called")
  199. i := 0
  200. for {
  201. v.RLock()
  202. ready := v.Ready
  203. v.RUnlock()
  204. if ready {
  205. return nil
  206. }
  207. if i > 10 {
  208. return fmt.Errorf("timeout waiting for voice")
  209. }
  210. time.Sleep(1 * time.Second)
  211. i++
  212. }
  213. }
  214. // Open opens a voice connection. This should be called
  215. // after VoiceChannelJoin is used and the data VOICE websocket events
  216. // are captured.
  217. func (v *VoiceConnection) open() (err error) {
  218. v.log(LogInformational, "called")
  219. v.Lock()
  220. defer v.Unlock()
  221. // Don't open a websocket if one is already open
  222. if v.wsConn != nil {
  223. v.log(LogWarning, "refusing to overwrite non-nil websocket")
  224. return
  225. }
  226. // TODO temp? loop to wait for the SessionID
  227. i := 0
  228. for {
  229. if v.sessionID != "" {
  230. break
  231. }
  232. if i > 20 { // only loop for up to 1 second total
  233. return fmt.Errorf("did not receive voice Session ID in time")
  234. }
  235. time.Sleep(50 * time.Millisecond)
  236. i++
  237. }
  238. // Connect to VoiceConnection Websocket
  239. vg := "wss://" + strings.TrimSuffix(v.endpoint, ":80")
  240. v.log(LogInformational, "connecting to voice endpoint %s", vg)
  241. v.wsConn, _, err = websocket.DefaultDialer.Dial(vg, nil)
  242. if err != nil {
  243. v.log(LogWarning, "error connecting to voice endpoint %s, %s", vg, err)
  244. v.log(LogDebug, "voice struct: %#v\n", v)
  245. return
  246. }
  247. type voiceHandshakeData struct {
  248. ServerID string `json:"server_id"`
  249. UserID string `json:"user_id"`
  250. SessionID string `json:"session_id"`
  251. Token string `json:"token"`
  252. }
  253. type voiceHandshakeOp struct {
  254. Op int `json:"op"` // Always 0
  255. Data voiceHandshakeData `json:"d"`
  256. }
  257. data := voiceHandshakeOp{0, voiceHandshakeData{v.GuildID, v.UserID, v.sessionID, v.token}}
  258. err = v.wsConn.WriteJSON(data)
  259. if err != nil {
  260. v.log(LogWarning, "error sending init packet, %s", err)
  261. return
  262. }
  263. v.close = make(chan struct{})
  264. go v.wsListen(v.wsConn, v.close)
  265. // add loop/check for Ready bool here?
  266. // then return false if not ready?
  267. // but then wsListen will also err.
  268. return
  269. }
  270. // wsListen listens on the voice websocket for messages and passes them
  271. // to the voice event handler. This is automatically called by the Open func
  272. func (v *VoiceConnection) wsListen(wsConn *websocket.Conn, close <-chan struct{}) {
  273. v.log(LogInformational, "called")
  274. for {
  275. _, message, err := v.wsConn.ReadMessage()
  276. if err != nil {
  277. // 4014 indicates a manual disconnection by someone in the guild;
  278. // we shouldn't reconnect.
  279. if websocket.IsCloseError(err, 4014) {
  280. v.log(LogInformational, "received 4014 manual disconnection")
  281. // Abandon the voice WS connection
  282. v.Lock()
  283. v.wsConn = nil
  284. v.Unlock()
  285. v.session.Lock()
  286. delete(v.session.VoiceConnections, v.GuildID)
  287. v.session.Unlock()
  288. v.Close()
  289. return
  290. }
  291. // Detect if we have been closed manually. If a Close() has already
  292. // happened, the websocket we are listening on will be different to the
  293. // current session.
  294. v.RLock()
  295. sameConnection := v.wsConn == wsConn
  296. v.RUnlock()
  297. if sameConnection {
  298. v.log(LogError, "voice endpoint %s websocket closed unexpectantly, %s", v.endpoint, err)
  299. // Start reconnect goroutine then exit.
  300. go v.reconnect()
  301. }
  302. return
  303. }
  304. // Pass received message to voice event handler
  305. select {
  306. case <-close:
  307. return
  308. default:
  309. go v.onEvent(message)
  310. }
  311. }
  312. }
  313. // wsEvent handles any voice websocket events. This is only called by the
  314. // wsListen() function.
  315. func (v *VoiceConnection) onEvent(message []byte) {
  316. v.log(LogDebug, "received: %s", string(message))
  317. var e Event
  318. if err := json.Unmarshal(message, &e); err != nil {
  319. v.log(LogError, "unmarshall error, %s", err)
  320. return
  321. }
  322. switch e.Operation {
  323. case 2: // READY
  324. if err := json.Unmarshal(e.RawData, &v.op2); err != nil {
  325. v.log(LogError, "OP2 unmarshall error, %s, %s", err, string(e.RawData))
  326. return
  327. }
  328. // Start the voice websocket heartbeat to keep the connection alive
  329. go v.wsHeartbeat(v.wsConn, v.close, v.op2.HeartbeatInterval)
  330. // TODO monitor a chan/bool to verify this was successful
  331. // Start the UDP connection
  332. err := v.udpOpen()
  333. if err != nil {
  334. v.log(LogError, "error opening udp connection, %s", err)
  335. return
  336. }
  337. // Start the opusSender.
  338. // TODO: Should we allow 48000/960 values to be user defined?
  339. if v.OpusSend == nil {
  340. v.OpusSend = make(chan []byte, 2)
  341. }
  342. go v.opusSender(v.udpConn, v.close, v.OpusSend, 48000, 960)
  343. // Start the opusReceiver
  344. if !v.deaf {
  345. if v.OpusRecv == nil {
  346. v.OpusRecv = make(chan *Packet, 2)
  347. }
  348. go v.opusReceiver(v.udpConn, v.close, v.OpusRecv)
  349. }
  350. return
  351. case 3: // HEARTBEAT response
  352. // add code to use this to track latency?
  353. return
  354. case 4: // udp encryption secret key
  355. v.Lock()
  356. defer v.Unlock()
  357. v.op4 = voiceOP4{}
  358. if err := json.Unmarshal(e.RawData, &v.op4); err != nil {
  359. v.log(LogError, "OP4 unmarshall error, %s, %s", err, string(e.RawData))
  360. return
  361. }
  362. return
  363. case 5:
  364. if len(v.voiceSpeakingUpdateHandlers) == 0 {
  365. return
  366. }
  367. voiceSpeakingUpdate := &VoiceSpeakingUpdate{}
  368. if err := json.Unmarshal(e.RawData, voiceSpeakingUpdate); err != nil {
  369. v.log(LogError, "OP5 unmarshall error, %s, %s", err, string(e.RawData))
  370. return
  371. }
  372. for _, h := range v.voiceSpeakingUpdateHandlers {
  373. h(v, voiceSpeakingUpdate)
  374. }
  375. default:
  376. v.log(LogDebug, "unknown voice operation, %d, %s", e.Operation, string(e.RawData))
  377. }
  378. return
  379. }
  380. type voiceHeartbeatOp struct {
  381. Op int `json:"op"` // Always 3
  382. Data int `json:"d"`
  383. }
  384. // NOTE :: When a guild voice server changes how do we shut this down
  385. // properly, so a new connection can be setup without fuss?
  386. //
  387. // wsHeartbeat sends regular heartbeats to voice Discord so it knows the client
  388. // is still connected. If you do not send these heartbeats Discord will
  389. // disconnect the websocket connection after a few seconds.
  390. func (v *VoiceConnection) wsHeartbeat(wsConn *websocket.Conn, close <-chan struct{}, i time.Duration) {
  391. if close == nil || wsConn == nil {
  392. return
  393. }
  394. var err error
  395. ticker := time.NewTicker(i * time.Millisecond)
  396. defer ticker.Stop()
  397. for {
  398. v.log(LogDebug, "sending heartbeat packet")
  399. v.wsMutex.Lock()
  400. err = wsConn.WriteJSON(voiceHeartbeatOp{3, int(time.Now().Unix())})
  401. v.wsMutex.Unlock()
  402. if err != nil {
  403. v.log(LogError, "error sending heartbeat to voice endpoint %s, %s", v.endpoint, err)
  404. return
  405. }
  406. select {
  407. case <-ticker.C:
  408. // continue loop and send heartbeat
  409. case <-close:
  410. return
  411. }
  412. }
  413. }
  414. // ------------------------------------------------------------------------------------------------
  415. // Code related to the VoiceConnection UDP connection
  416. // ------------------------------------------------------------------------------------------------
  417. type voiceUDPData struct {
  418. Address string `json:"address"` // Public IP of machine running this code
  419. Port uint16 `json:"port"` // UDP Port of machine running this code
  420. Mode string `json:"mode"` // always "xsalsa20_poly1305"
  421. }
  422. type voiceUDPD struct {
  423. Protocol string `json:"protocol"` // Always "udp" ?
  424. Data voiceUDPData `json:"data"`
  425. }
  426. type voiceUDPOp struct {
  427. Op int `json:"op"` // Always 1
  428. Data voiceUDPD `json:"d"`
  429. }
  430. // udpOpen opens a UDP connection to the voice server and completes the
  431. // initial required handshake. This connection is left open in the session
  432. // and can be used to send or receive audio. This should only be called
  433. // from voice.wsEvent OP2
  434. func (v *VoiceConnection) udpOpen() (err error) {
  435. v.Lock()
  436. defer v.Unlock()
  437. if v.wsConn == nil {
  438. return fmt.Errorf("nil voice websocket")
  439. }
  440. if v.udpConn != nil {
  441. return fmt.Errorf("udp connection already open")
  442. }
  443. if v.close == nil {
  444. return fmt.Errorf("nil close channel")
  445. }
  446. if v.endpoint == "" {
  447. return fmt.Errorf("empty endpoint")
  448. }
  449. host := v.op2.IP + ":" + strconv.Itoa(v.op2.Port)
  450. addr, err := net.ResolveUDPAddr("udp", host)
  451. if err != nil {
  452. v.log(LogWarning, "error resolving udp host %s, %s", host, err)
  453. return
  454. }
  455. v.log(LogInformational, "connecting to udp addr %s", addr.String())
  456. v.udpConn, err = net.DialUDP("udp", nil, addr)
  457. if err != nil {
  458. v.log(LogWarning, "error connecting to udp addr %s, %s", addr.String(), err)
  459. return
  460. }
  461. // Create a 70 byte array and put the SSRC code from the Op 2 VoiceConnection event
  462. // into it. Then send that over the UDP connection to Discord
  463. sb := make([]byte, 70)
  464. binary.BigEndian.PutUint32(sb, v.op2.SSRC)
  465. _, err = v.udpConn.Write(sb)
  466. if err != nil {
  467. v.log(LogWarning, "udp write error to %s, %s", addr.String(), err)
  468. return
  469. }
  470. // Create a 70 byte array and listen for the initial handshake response
  471. // from Discord. Once we get it parse the IP and PORT information out
  472. // of the response. This should be our public IP and PORT as Discord
  473. // saw us.
  474. rb := make([]byte, 70)
  475. rlen, _, err := v.udpConn.ReadFromUDP(rb)
  476. if err != nil {
  477. v.log(LogWarning, "udp read error, %s, %s", addr.String(), err)
  478. return
  479. }
  480. if rlen < 70 {
  481. v.log(LogWarning, "received udp packet too small")
  482. return fmt.Errorf("received udp packet too small")
  483. }
  484. // Loop over position 4 through 20 to grab the IP address
  485. // Should never be beyond position 20.
  486. var ip string
  487. for i := 4; i < 20; i++ {
  488. if rb[i] == 0 {
  489. break
  490. }
  491. ip += string(rb[i])
  492. }
  493. // Grab port from position 68 and 69
  494. port := binary.BigEndian.Uint16(rb[68:70])
  495. // Take the data from above and send it back to Discord to finalize
  496. // the UDP connection handshake.
  497. data := voiceUDPOp{1, voiceUDPD{"udp", voiceUDPData{ip, port, "xsalsa20_poly1305"}}}
  498. v.wsMutex.Lock()
  499. err = v.wsConn.WriteJSON(data)
  500. v.wsMutex.Unlock()
  501. if err != nil {
  502. v.log(LogWarning, "udp write error, %#v, %s", data, err)
  503. return
  504. }
  505. // start udpKeepAlive
  506. go v.udpKeepAlive(v.udpConn, v.close, 5*time.Second)
  507. // TODO: find a way to check that it fired off okay
  508. return
  509. }
  510. // udpKeepAlive sends a udp packet to keep the udp connection open
  511. // This is still a bit of a "proof of concept"
  512. func (v *VoiceConnection) udpKeepAlive(udpConn *net.UDPConn, close <-chan struct{}, i time.Duration) {
  513. if udpConn == nil || close == nil {
  514. return
  515. }
  516. var err error
  517. var sequence uint64
  518. packet := make([]byte, 8)
  519. ticker := time.NewTicker(i)
  520. defer ticker.Stop()
  521. for {
  522. binary.LittleEndian.PutUint64(packet, sequence)
  523. sequence++
  524. _, err = udpConn.Write(packet)
  525. if err != nil {
  526. v.log(LogError, "write error, %s", err)
  527. return
  528. }
  529. select {
  530. case <-ticker.C:
  531. // continue loop and send keepalive
  532. case <-close:
  533. return
  534. }
  535. }
  536. }
  537. // opusSender will listen on the given channel and send any
  538. // pre-encoded opus audio to Discord. Supposedly.
  539. func (v *VoiceConnection) opusSender(udpConn *net.UDPConn, close <-chan struct{}, opus <-chan []byte, rate, size int) {
  540. if udpConn == nil || close == nil {
  541. return
  542. }
  543. // VoiceConnection is now ready to receive audio packets
  544. // TODO: this needs reviewed as I think there must be a better way.
  545. v.Lock()
  546. v.Ready = true
  547. v.Unlock()
  548. defer func() {
  549. v.Lock()
  550. v.Ready = false
  551. v.Unlock()
  552. }()
  553. var sequence uint16
  554. var timestamp uint32
  555. var recvbuf []byte
  556. var ok bool
  557. udpHeader := make([]byte, 12)
  558. var nonce [24]byte
  559. // build the parts that don't change in the udpHeader
  560. udpHeader[0] = 0x80
  561. udpHeader[1] = 0x78
  562. binary.BigEndian.PutUint32(udpHeader[8:], v.op2.SSRC)
  563. // start a send loop that loops until buf chan is closed
  564. ticker := time.NewTicker(time.Millisecond * time.Duration(size/(rate/1000)))
  565. defer ticker.Stop()
  566. for {
  567. // Get data from chan. If chan is closed, return.
  568. select {
  569. case <-close:
  570. return
  571. case recvbuf, ok = <-opus:
  572. if !ok {
  573. return
  574. }
  575. // else, continue loop
  576. }
  577. v.RLock()
  578. speaking := v.speaking
  579. v.RUnlock()
  580. if !speaking {
  581. err := v.Speaking(true)
  582. if err != nil {
  583. v.log(LogError, "error sending speaking packet, %s", err)
  584. }
  585. }
  586. // Add sequence and timestamp to udpPacket
  587. binary.BigEndian.PutUint16(udpHeader[2:], sequence)
  588. binary.BigEndian.PutUint32(udpHeader[4:], timestamp)
  589. // encrypt the opus data
  590. copy(nonce[:], udpHeader)
  591. v.RLock()
  592. sendbuf := secretbox.Seal(udpHeader, recvbuf, &nonce, &v.op4.SecretKey)
  593. v.RUnlock()
  594. // block here until we're exactly at the right time :)
  595. // Then send rtp audio packet to Discord over UDP
  596. select {
  597. case <-close:
  598. return
  599. case <-ticker.C:
  600. // continue
  601. }
  602. _, err := udpConn.Write(sendbuf)
  603. if err != nil {
  604. v.log(LogError, "udp write error, %s", err)
  605. v.log(LogDebug, "voice struct: %#v\n", v)
  606. return
  607. }
  608. if (sequence) == 0xFFFF {
  609. sequence = 0
  610. } else {
  611. sequence++
  612. }
  613. if (timestamp + uint32(size)) >= 0xFFFFFFFF {
  614. timestamp = 0
  615. } else {
  616. timestamp += uint32(size)
  617. }
  618. }
  619. }
  620. // A Packet contains the headers and content of a received voice packet.
  621. type Packet struct {
  622. SSRC uint32
  623. Sequence uint16
  624. Timestamp uint32
  625. Type []byte
  626. Opus []byte
  627. PCM []int16
  628. }
  629. // opusReceiver listens on the UDP socket for incoming packets
  630. // and sends them across the given channel
  631. // NOTE :: This function may change names later.
  632. func (v *VoiceConnection) opusReceiver(udpConn *net.UDPConn, close <-chan struct{}, c chan *Packet) {
  633. if udpConn == nil || close == nil {
  634. return
  635. }
  636. recvbuf := make([]byte, 1024)
  637. var nonce [24]byte
  638. for {
  639. rlen, err := udpConn.Read(recvbuf)
  640. if err != nil {
  641. // Detect if we have been closed manually. If a Close() has already
  642. // happened, the udp connection we are listening on will be different
  643. // to the current session.
  644. v.RLock()
  645. sameConnection := v.udpConn == udpConn
  646. v.RUnlock()
  647. if sameConnection {
  648. v.log(LogError, "udp read error, %s, %s", v.endpoint, err)
  649. v.log(LogDebug, "voice struct: %#v\n", v)
  650. go v.reconnect()
  651. }
  652. return
  653. }
  654. select {
  655. case <-close:
  656. return
  657. default:
  658. // continue loop
  659. }
  660. // For now, skip anything except audio.
  661. if rlen < 12 || (recvbuf[0] != 0x80 && recvbuf[0] != 0x90) {
  662. continue
  663. }
  664. // build a audio packet struct
  665. p := Packet{}
  666. p.Type = recvbuf[0:2]
  667. p.Sequence = binary.BigEndian.Uint16(recvbuf[2:4])
  668. p.Timestamp = binary.BigEndian.Uint32(recvbuf[4:8])
  669. p.SSRC = binary.BigEndian.Uint32(recvbuf[8:12])
  670. // decrypt opus data
  671. copy(nonce[:], recvbuf[0:12])
  672. p.Opus, _ = secretbox.Open(nil, recvbuf[12:rlen], &nonce, &v.op4.SecretKey)
  673. if len(p.Opus) > 8 && recvbuf[0] == 0x90 {
  674. // Extension bit is set, first 8 bytes is the extended header
  675. p.Opus = p.Opus[8:]
  676. }
  677. if c != nil {
  678. select {
  679. case c <- &p:
  680. case <-close:
  681. return
  682. }
  683. }
  684. }
  685. }
  686. // Reconnect will close down a voice connection then immediately try to
  687. // reconnect to that session.
  688. // NOTE : This func is messy and a WIP while I find what works.
  689. // It will be cleaned up once a proven stable option is flushed out.
  690. // aka: this is ugly shit code, please don't judge too harshly.
  691. func (v *VoiceConnection) reconnect() {
  692. v.log(LogInformational, "called")
  693. v.Lock()
  694. if v.reconnecting {
  695. v.log(LogInformational, "already reconnecting to channel %s, exiting", v.ChannelID)
  696. v.Unlock()
  697. return
  698. }
  699. v.reconnecting = true
  700. v.Unlock()
  701. defer func() { v.reconnecting = false }()
  702. // Close any currently open connections
  703. v.Close()
  704. wait := time.Duration(1)
  705. for {
  706. <-time.After(wait * time.Second)
  707. wait *= 2
  708. if wait > 600 {
  709. wait = 600
  710. }
  711. if v.session.DataReady == false || v.session.wsConn == nil {
  712. v.log(LogInformational, "cannot reconnect to channel %s with unready session", v.ChannelID)
  713. continue
  714. }
  715. v.log(LogInformational, "trying to reconnect to channel %s", v.ChannelID)
  716. _, err := v.session.ChannelVoiceJoin(v.GuildID, v.ChannelID, v.mute, v.deaf)
  717. if err == nil {
  718. v.log(LogInformational, "successfully reconnected to channel %s", v.ChannelID)
  719. return
  720. }
  721. v.log(LogInformational, "error reconnecting to channel %s, %s", v.ChannelID, err)
  722. // if the reconnect above didn't work lets just send a disconnect
  723. // packet to reset things.
  724. // Send a OP4 with a nil channel to disconnect
  725. data := voiceChannelJoinOp{4, voiceChannelJoinData{&v.GuildID, nil, true, true}}
  726. v.session.wsMutex.Lock()
  727. err = v.session.wsConn.WriteJSON(data)
  728. v.session.wsMutex.Unlock()
  729. if err != nil {
  730. v.log(LogError, "error sending disconnect packet, %s", err)
  731. }
  732. }
  733. }