voice.go 23 KB

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