voice.go 22 KB

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