voice.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886
  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. }
  194. // WaitUntilConnected waits for the Voice Connection to
  195. // become ready, if it does not become ready it returns an err
  196. func (v *VoiceConnection) waitUntilConnected() error {
  197. v.log(LogInformational, "called")
  198. i := 0
  199. for {
  200. v.RLock()
  201. ready := v.Ready
  202. v.RUnlock()
  203. if ready {
  204. return nil
  205. }
  206. if i > 10 {
  207. return fmt.Errorf("timeout waiting for voice")
  208. }
  209. time.Sleep(1 * time.Second)
  210. i++
  211. }
  212. }
  213. // Open opens a voice connection. This should be called
  214. // after VoiceChannelJoin is used and the data VOICE websocket events
  215. // are captured.
  216. func (v *VoiceConnection) open() (err error) {
  217. v.log(LogInformational, "called")
  218. v.Lock()
  219. defer v.Unlock()
  220. // Don't open a websocket if one is already open
  221. if v.wsConn != nil {
  222. v.log(LogWarning, "refusing to overwrite non-nil websocket")
  223. return
  224. }
  225. // TODO temp? loop to wait for the SessionID
  226. i := 0
  227. for {
  228. if v.sessionID != "" {
  229. break
  230. }
  231. if i > 20 { // only loop for up to 1 second total
  232. return fmt.Errorf("did not receive voice Session ID in time")
  233. }
  234. time.Sleep(50 * time.Millisecond)
  235. i++
  236. }
  237. // Connect to VoiceConnection Websocket
  238. vg := "wss://" + strings.TrimSuffix(v.endpoint, ":80")
  239. v.log(LogInformational, "connecting to voice endpoint %s", vg)
  240. v.wsConn, _, err = websocket.DefaultDialer.Dial(vg, nil)
  241. if err != nil {
  242. v.log(LogWarning, "error connecting to voice endpoint %s, %s", vg, err)
  243. v.log(LogDebug, "voice struct: %#v\n", v)
  244. return
  245. }
  246. type voiceHandshakeData struct {
  247. ServerID string `json:"server_id"`
  248. UserID string `json:"user_id"`
  249. SessionID string `json:"session_id"`
  250. Token string `json:"token"`
  251. }
  252. type voiceHandshakeOp struct {
  253. Op int `json:"op"` // Always 0
  254. Data voiceHandshakeData `json:"d"`
  255. }
  256. data := voiceHandshakeOp{0, voiceHandshakeData{v.GuildID, v.UserID, v.sessionID, v.token}}
  257. err = v.wsConn.WriteJSON(data)
  258. if err != nil {
  259. v.log(LogWarning, "error sending init packet, %s", err)
  260. return
  261. }
  262. v.close = make(chan struct{})
  263. go v.wsListen(v.wsConn, v.close)
  264. // add loop/check for Ready bool here?
  265. // then return false if not ready?
  266. // but then wsListen will also err.
  267. return
  268. }
  269. // wsListen listens on the voice websocket for messages and passes them
  270. // to the voice event handler. This is automatically called by the Open func
  271. func (v *VoiceConnection) wsListen(wsConn *websocket.Conn, close <-chan struct{}) {
  272. v.log(LogInformational, "called")
  273. for {
  274. _, message, err := v.wsConn.ReadMessage()
  275. if err != nil {
  276. // Detect if we have been closed manually. If a Close() has already
  277. // happened, the websocket we are listening on will be different to the
  278. // current session.
  279. v.RLock()
  280. sameConnection := v.wsConn == wsConn
  281. v.RUnlock()
  282. if sameConnection {
  283. v.log(LogError, "voice endpoint %s websocket closed unexpectantly, %s", v.endpoint, err)
  284. // Start reconnect goroutine then exit.
  285. go v.reconnect()
  286. }
  287. return
  288. }
  289. // Pass received message to voice event handler
  290. select {
  291. case <-close:
  292. return
  293. default:
  294. go v.onEvent(message)
  295. }
  296. }
  297. }
  298. // wsEvent handles any voice websocket events. This is only called by the
  299. // wsListen() function.
  300. func (v *VoiceConnection) onEvent(message []byte) {
  301. v.log(LogDebug, "received: %s", string(message))
  302. var e Event
  303. if err := json.Unmarshal(message, &e); err != nil {
  304. v.log(LogError, "unmarshall error, %s", err)
  305. return
  306. }
  307. switch e.Operation {
  308. case 2: // READY
  309. if err := json.Unmarshal(e.RawData, &v.op2); err != nil {
  310. v.log(LogError, "OP2 unmarshall error, %s, %s", err, string(e.RawData))
  311. return
  312. }
  313. // Start the voice websocket heartbeat to keep the connection alive
  314. go v.wsHeartbeat(v.wsConn, v.close, v.op2.HeartbeatInterval)
  315. // TODO monitor a chan/bool to verify this was successful
  316. // Start the UDP connection
  317. err := v.udpOpen()
  318. if err != nil {
  319. v.log(LogError, "error opening udp connection, %s", err)
  320. return
  321. }
  322. // Start the opusSender.
  323. // TODO: Should we allow 48000/960 values to be user defined?
  324. if v.OpusSend == nil {
  325. v.OpusSend = make(chan []byte, 2)
  326. }
  327. go v.opusSender(v.udpConn, v.close, v.OpusSend, 48000, 960)
  328. // Start the opusReceiver
  329. if !v.deaf {
  330. if v.OpusRecv == nil {
  331. v.OpusRecv = make(chan *Packet, 2)
  332. }
  333. go v.opusReceiver(v.udpConn, v.close, v.OpusRecv)
  334. }
  335. return
  336. case 3: // HEARTBEAT response
  337. // add code to use this to track latency?
  338. return
  339. case 4: // udp encryption secret key
  340. v.Lock()
  341. defer v.Unlock()
  342. v.op4 = voiceOP4{}
  343. if err := json.Unmarshal(e.RawData, &v.op4); err != nil {
  344. v.log(LogError, "OP4 unmarshall error, %s, %s", err, string(e.RawData))
  345. return
  346. }
  347. return
  348. case 5:
  349. if len(v.voiceSpeakingUpdateHandlers) == 0 {
  350. return
  351. }
  352. voiceSpeakingUpdate := &VoiceSpeakingUpdate{}
  353. if err := json.Unmarshal(e.RawData, voiceSpeakingUpdate); err != nil {
  354. v.log(LogError, "OP5 unmarshall error, %s, %s", err, string(e.RawData))
  355. return
  356. }
  357. for _, h := range v.voiceSpeakingUpdateHandlers {
  358. h(v, voiceSpeakingUpdate)
  359. }
  360. default:
  361. v.log(LogDebug, "unknown voice operation, %d, %s", e.Operation, string(e.RawData))
  362. }
  363. return
  364. }
  365. type voiceHeartbeatOp struct {
  366. Op int `json:"op"` // Always 3
  367. Data int `json:"d"`
  368. }
  369. // NOTE :: When a guild voice server changes how do we shut this down
  370. // properly, so a new connection can be setup without fuss?
  371. //
  372. // wsHeartbeat sends regular heartbeats to voice Discord so it knows the client
  373. // is still connected. If you do not send these heartbeats Discord will
  374. // disconnect the websocket connection after a few seconds.
  375. func (v *VoiceConnection) wsHeartbeat(wsConn *websocket.Conn, close <-chan struct{}, i time.Duration) {
  376. if close == nil || wsConn == nil {
  377. return
  378. }
  379. var err error
  380. ticker := time.NewTicker(i * time.Millisecond)
  381. defer ticker.Stop()
  382. for {
  383. v.log(LogDebug, "sending heartbeat packet")
  384. v.wsMutex.Lock()
  385. err = wsConn.WriteJSON(voiceHeartbeatOp{3, int(time.Now().Unix())})
  386. v.wsMutex.Unlock()
  387. if err != nil {
  388. v.log(LogError, "error sending heartbeat to voice endpoint %s, %s", v.endpoint, err)
  389. return
  390. }
  391. select {
  392. case <-ticker.C:
  393. // continue loop and send heartbeat
  394. case <-close:
  395. return
  396. }
  397. }
  398. }
  399. // ------------------------------------------------------------------------------------------------
  400. // Code related to the VoiceConnection UDP connection
  401. // ------------------------------------------------------------------------------------------------
  402. type voiceUDPData struct {
  403. Address string `json:"address"` // Public IP of machine running this code
  404. Port uint16 `json:"port"` // UDP Port of machine running this code
  405. Mode string `json:"mode"` // always "xsalsa20_poly1305"
  406. }
  407. type voiceUDPD struct {
  408. Protocol string `json:"protocol"` // Always "udp" ?
  409. Data voiceUDPData `json:"data"`
  410. }
  411. type voiceUDPOp struct {
  412. Op int `json:"op"` // Always 1
  413. Data voiceUDPD `json:"d"`
  414. }
  415. // udpOpen opens a UDP connection to the voice server and completes the
  416. // initial required handshake. This connection is left open in the session
  417. // and can be used to send or receive audio. This should only be called
  418. // from voice.wsEvent OP2
  419. func (v *VoiceConnection) udpOpen() (err error) {
  420. v.Lock()
  421. defer v.Unlock()
  422. if v.wsConn == nil {
  423. return fmt.Errorf("nil voice websocket")
  424. }
  425. if v.udpConn != nil {
  426. return fmt.Errorf("udp connection already open")
  427. }
  428. if v.close == nil {
  429. return fmt.Errorf("nil close channel")
  430. }
  431. if v.endpoint == "" {
  432. return fmt.Errorf("empty endpoint")
  433. }
  434. host := strings.TrimSuffix(v.endpoint, ":80") + ":" + strconv.Itoa(v.op2.Port)
  435. addr, err := net.ResolveUDPAddr("udp", host)
  436. if err != nil {
  437. v.log(LogWarning, "error resolving udp host %s, %s", host, err)
  438. return
  439. }
  440. v.log(LogInformational, "connecting to udp addr %s", addr.String())
  441. v.udpConn, err = net.DialUDP("udp", nil, addr)
  442. if err != nil {
  443. v.log(LogWarning, "error connecting to udp addr %s, %s", addr.String(), err)
  444. return
  445. }
  446. // Create a 70 byte array and put the SSRC code from the Op 2 VoiceConnection event
  447. // into it. Then send that over the UDP connection to Discord
  448. sb := make([]byte, 70)
  449. binary.BigEndian.PutUint32(sb, v.op2.SSRC)
  450. _, err = v.udpConn.Write(sb)
  451. if err != nil {
  452. v.log(LogWarning, "udp write error to %s, %s", addr.String(), err)
  453. return
  454. }
  455. // Create a 70 byte array and listen for the initial handshake response
  456. // from Discord. Once we get it parse the IP and PORT information out
  457. // of the response. This should be our public IP and PORT as Discord
  458. // saw us.
  459. rb := make([]byte, 70)
  460. rlen, _, err := v.udpConn.ReadFromUDP(rb)
  461. if err != nil {
  462. v.log(LogWarning, "udp read error, %s, %s", addr.String(), err)
  463. return
  464. }
  465. if rlen < 70 {
  466. v.log(LogWarning, "received udp packet too small")
  467. return fmt.Errorf("received udp packet too small")
  468. }
  469. // Loop over position 4 through 20 to grab the IP address
  470. // Should never be beyond position 20.
  471. var ip string
  472. for i := 4; i < 20; i++ {
  473. if rb[i] == 0 {
  474. break
  475. }
  476. ip += string(rb[i])
  477. }
  478. // Grab port from position 68 and 69
  479. port := binary.LittleEndian.Uint16(rb[68:70])
  480. // Take the data from above and send it back to Discord to finalize
  481. // the UDP connection handshake.
  482. data := voiceUDPOp{1, voiceUDPD{"udp", voiceUDPData{ip, port, "xsalsa20_poly1305"}}}
  483. v.wsMutex.Lock()
  484. err = v.wsConn.WriteJSON(data)
  485. v.wsMutex.Unlock()
  486. if err != nil {
  487. v.log(LogWarning, "udp write error, %#v, %s", data, err)
  488. return
  489. }
  490. // start udpKeepAlive
  491. go v.udpKeepAlive(v.udpConn, v.close, 5*time.Second)
  492. // TODO: find a way to check that it fired off okay
  493. return
  494. }
  495. // udpKeepAlive sends a udp packet to keep the udp connection open
  496. // This is still a bit of a "proof of concept"
  497. func (v *VoiceConnection) udpKeepAlive(udpConn *net.UDPConn, close <-chan struct{}, i time.Duration) {
  498. if udpConn == nil || close == nil {
  499. return
  500. }
  501. var err error
  502. var sequence uint64
  503. packet := make([]byte, 8)
  504. ticker := time.NewTicker(i)
  505. defer ticker.Stop()
  506. for {
  507. binary.LittleEndian.PutUint64(packet, sequence)
  508. sequence++
  509. _, err = udpConn.Write(packet)
  510. if err != nil {
  511. v.log(LogError, "write error, %s", err)
  512. return
  513. }
  514. select {
  515. case <-ticker.C:
  516. // continue loop and send keepalive
  517. case <-close:
  518. return
  519. }
  520. }
  521. }
  522. // opusSender will listen on the given channel and send any
  523. // pre-encoded opus audio to Discord. Supposedly.
  524. func (v *VoiceConnection) opusSender(udpConn *net.UDPConn, close <-chan struct{}, opus <-chan []byte, rate, size int) {
  525. if udpConn == nil || close == nil {
  526. return
  527. }
  528. // VoiceConnection is now ready to receive audio packets
  529. // TODO: this needs reviewed as I think there must be a better way.
  530. v.Lock()
  531. v.Ready = true
  532. v.Unlock()
  533. defer func() {
  534. v.Lock()
  535. v.Ready = false
  536. v.Unlock()
  537. }()
  538. var sequence uint16
  539. var timestamp uint32
  540. var recvbuf []byte
  541. var ok bool
  542. udpHeader := make([]byte, 12)
  543. var nonce [24]byte
  544. // build the parts that don't change in the udpHeader
  545. udpHeader[0] = 0x80
  546. udpHeader[1] = 0x78
  547. binary.BigEndian.PutUint32(udpHeader[8:], v.op2.SSRC)
  548. // start a send loop that loops until buf chan is closed
  549. ticker := time.NewTicker(time.Millisecond * time.Duration(size/(rate/1000)))
  550. defer ticker.Stop()
  551. for {
  552. // Get data from chan. If chan is closed, return.
  553. select {
  554. case <-close:
  555. return
  556. case recvbuf, ok = <-opus:
  557. if !ok {
  558. return
  559. }
  560. // else, continue loop
  561. }
  562. v.RLock()
  563. speaking := v.speaking
  564. v.RUnlock()
  565. if !speaking {
  566. err := v.Speaking(true)
  567. if err != nil {
  568. v.log(LogError, "error sending speaking packet, %s", err)
  569. }
  570. }
  571. // Add sequence and timestamp to udpPacket
  572. binary.BigEndian.PutUint16(udpHeader[2:], sequence)
  573. binary.BigEndian.PutUint32(udpHeader[4:], timestamp)
  574. // encrypt the opus data
  575. copy(nonce[:], udpHeader)
  576. v.RLock()
  577. sendbuf := secretbox.Seal(udpHeader, recvbuf, &nonce, &v.op4.SecretKey)
  578. v.RUnlock()
  579. // block here until we're exactly at the right time :)
  580. // Then send rtp audio packet to Discord over UDP
  581. select {
  582. case <-close:
  583. return
  584. case <-ticker.C:
  585. // continue
  586. }
  587. _, err := udpConn.Write(sendbuf)
  588. if err != nil {
  589. v.log(LogError, "udp write error, %s", err)
  590. v.log(LogDebug, "voice struct: %#v\n", v)
  591. return
  592. }
  593. if (sequence) == 0xFFFF {
  594. sequence = 0
  595. } else {
  596. sequence++
  597. }
  598. if (timestamp + uint32(size)) >= 0xFFFFFFFF {
  599. timestamp = 0
  600. } else {
  601. timestamp += uint32(size)
  602. }
  603. }
  604. }
  605. // A Packet contains the headers and content of a received voice packet.
  606. type Packet struct {
  607. SSRC uint32
  608. Sequence uint16
  609. Timestamp uint32
  610. Type []byte
  611. Opus []byte
  612. PCM []int16
  613. }
  614. // opusReceiver listens on the UDP socket for incoming packets
  615. // and sends them across the given channel
  616. // NOTE :: This function may change names later.
  617. func (v *VoiceConnection) opusReceiver(udpConn *net.UDPConn, close <-chan struct{}, c chan *Packet) {
  618. if udpConn == nil || close == nil {
  619. return
  620. }
  621. recvbuf := make([]byte, 1024)
  622. var nonce [24]byte
  623. for {
  624. rlen, err := udpConn.Read(recvbuf)
  625. if err != nil {
  626. // Detect if we have been closed manually. If a Close() has already
  627. // happened, the udp connection we are listening on will be different
  628. // to the current session.
  629. v.RLock()
  630. sameConnection := v.udpConn == udpConn
  631. v.RUnlock()
  632. if sameConnection {
  633. v.log(LogError, "udp read error, %s, %s", v.endpoint, err)
  634. v.log(LogDebug, "voice struct: %#v\n", v)
  635. go v.reconnect()
  636. }
  637. return
  638. }
  639. select {
  640. case <-close:
  641. return
  642. default:
  643. // continue loop
  644. }
  645. // For now, skip anything except audio.
  646. if rlen < 12 || (recvbuf[0] != 0x80 && recvbuf[0] != 0x90) {
  647. continue
  648. }
  649. // build a audio packet struct
  650. p := Packet{}
  651. p.Type = recvbuf[0:2]
  652. p.Sequence = binary.BigEndian.Uint16(recvbuf[2:4])
  653. p.Timestamp = binary.BigEndian.Uint32(recvbuf[4:8])
  654. p.SSRC = binary.BigEndian.Uint32(recvbuf[8:12])
  655. // decrypt opus data
  656. copy(nonce[:], recvbuf[0:12])
  657. p.Opus, _ = secretbox.Open(nil, recvbuf[12:rlen], &nonce, &v.op4.SecretKey)
  658. if len(p.Opus) > 8 && recvbuf[0] == 0x90 {
  659. // Extension bit is set, first 8 bytes is the extended header
  660. p.Opus = p.Opus[8:]
  661. }
  662. if c != nil {
  663. select {
  664. case c <- &p:
  665. case <-close:
  666. return
  667. }
  668. }
  669. }
  670. }
  671. // Reconnect will close down a voice connection then immediately try to
  672. // reconnect to that session.
  673. // NOTE : This func is messy and a WIP while I find what works.
  674. // It will be cleaned up once a proven stable option is flushed out.
  675. // aka: this is ugly shit code, please don't judge too harshly.
  676. func (v *VoiceConnection) reconnect() {
  677. v.log(LogInformational, "called")
  678. v.Lock()
  679. if v.reconnecting {
  680. v.log(LogInformational, "already reconnecting to channel %s, exiting", v.ChannelID)
  681. v.Unlock()
  682. return
  683. }
  684. v.reconnecting = true
  685. v.Unlock()
  686. defer func() { v.reconnecting = false }()
  687. // Close any currently open connections
  688. v.Close()
  689. wait := time.Duration(1)
  690. for {
  691. <-time.After(wait * time.Second)
  692. wait *= 2
  693. if wait > 600 {
  694. wait = 600
  695. }
  696. if v.session.DataReady == false || v.session.wsConn == nil {
  697. v.log(LogInformational, "cannot reconnect to channel %s with unready session", v.ChannelID)
  698. continue
  699. }
  700. v.log(LogInformational, "trying to reconnect to channel %s", v.ChannelID)
  701. _, err := v.session.ChannelVoiceJoin(v.GuildID, v.ChannelID, v.mute, v.deaf)
  702. if err == nil {
  703. v.log(LogInformational, "successfully reconnected to channel %s", v.ChannelID)
  704. return
  705. }
  706. v.log(LogInformational, "error reconnecting to channel %s, %s", v.ChannelID, err)
  707. // if the reconnect above didn't work lets just send a disconnect
  708. // packet to reset things.
  709. // Send a OP4 with a nil channel to disconnect
  710. data := voiceChannelJoinOp{4, voiceChannelJoinData{&v.GuildID, nil, true, true}}
  711. v.session.wsMutex.Lock()
  712. err = v.session.wsConn.WriteJSON(data)
  713. v.session.wsMutex.Unlock()
  714. if err != nil {
  715. v.log(LogError, "error sending disconnect packet, %s", err)
  716. }
  717. }
  718. }