voice.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887
  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. "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 defination 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. log.Println("Speaking() write json error:", 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. // !!! NOTE !!! this function may be removed in favour of ChannelVoiceLeave
  109. func (v *VoiceConnection) Disconnect() (err error) {
  110. // Send a OP4 with a nil channel to disconnect
  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. // Close websocket and udp connections
  119. v.Close()
  120. v.log(LogInformational, "Deleting VoiceConnection %s", v.GuildID)
  121. v.session.Lock()
  122. delete(v.session.VoiceConnections, v.GuildID)
  123. v.session.Unlock()
  124. return
  125. }
  126. // Close closes the voice ws and udp connections
  127. func (v *VoiceConnection) Close() {
  128. v.log(LogInformational, "called")
  129. v.Lock()
  130. defer v.Unlock()
  131. v.Ready = false
  132. v.speaking = false
  133. if v.close != nil {
  134. v.log(LogInformational, "closing v.close")
  135. close(v.close)
  136. v.close = nil
  137. }
  138. if v.udpConn != nil {
  139. v.log(LogInformational, "closing udp")
  140. err := v.udpConn.Close()
  141. if err != nil {
  142. log.Println("error closing udp connection: ", err)
  143. }
  144. v.udpConn = nil
  145. }
  146. if v.wsConn != nil {
  147. v.log(LogInformational, "sending close frame")
  148. // To cleanly close a connection, a client should send a close
  149. // frame and wait for the server to close the connection.
  150. v.wsMutex.Lock()
  151. err := v.wsConn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
  152. v.wsMutex.Unlock()
  153. if err != nil {
  154. v.log(LogError, "error closing websocket, %s", err)
  155. }
  156. // TODO: Wait for Discord to actually close the connection.
  157. time.Sleep(1 * time.Second)
  158. v.log(LogInformational, "closing websocket")
  159. err = v.wsConn.Close()
  160. if err != nil {
  161. v.log(LogError, "error closing websocket, %s", err)
  162. }
  163. v.wsConn = nil
  164. }
  165. }
  166. // AddHandler adds a Handler for VoiceSpeakingUpdate events.
  167. func (v *VoiceConnection) AddHandler(h VoiceSpeakingUpdateHandler) {
  168. v.Lock()
  169. defer v.Unlock()
  170. v.voiceSpeakingUpdateHandlers = append(v.voiceSpeakingUpdateHandlers, h)
  171. }
  172. // VoiceSpeakingUpdate is a struct for a VoiceSpeakingUpdate event.
  173. type VoiceSpeakingUpdate struct {
  174. UserID string `json:"user_id"`
  175. SSRC int `json:"ssrc"`
  176. Speaking bool `json:"speaking"`
  177. }
  178. // ------------------------------------------------------------------------------------------------
  179. // Unexported Internal Functions Below.
  180. // ------------------------------------------------------------------------------------------------
  181. // A voiceOP4 stores the data for the voice operation 4 websocket event
  182. // which provides us with the NaCl SecretBox encryption key
  183. type voiceOP4 struct {
  184. SecretKey [32]byte `json:"secret_key"`
  185. Mode string `json:"mode"`
  186. }
  187. // A voiceOP2 stores the data for the voice operation 2 websocket event
  188. // which is sort of like the voice READY packet
  189. type voiceOP2 struct {
  190. SSRC uint32 `json:"ssrc"`
  191. Port int `json:"port"`
  192. Modes []string `json:"modes"`
  193. HeartbeatInterval time.Duration `json:"heartbeat_interval"`
  194. }
  195. // WaitUntilConnected waits for the Voice Connection to
  196. // become ready, if it does not become ready it retuns 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 := fmt.Sprintf("wss://%s", 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. // Detect if we have been closed manually. If a Close() has already
  278. // happened, the websocket we are listening on will be different to the
  279. // current session.
  280. v.RLock()
  281. sameConnection := v.wsConn == wsConn
  282. v.RUnlock()
  283. if sameConnection {
  284. v.log(LogError, "voice endpoint %s websocket closed unexpectantly, %s", v.endpoint, err)
  285. // Start reconnect goroutine then exit.
  286. go v.reconnect()
  287. }
  288. return
  289. }
  290. // Pass received message to voice event handler
  291. select {
  292. case <-close:
  293. return
  294. default:
  295. go v.onEvent(message)
  296. }
  297. }
  298. }
  299. // wsEvent handles any voice websocket events. This is only called by the
  300. // wsListen() function.
  301. func (v *VoiceConnection) onEvent(message []byte) {
  302. v.log(LogDebug, "received: %s", string(message))
  303. var e Event
  304. if err := json.Unmarshal(message, &e); err != nil {
  305. v.log(LogError, "unmarshall error, %s", err)
  306. return
  307. }
  308. switch e.Operation {
  309. case 2: // READY
  310. if err := json.Unmarshal(e.RawData, &v.op2); err != nil {
  311. v.log(LogError, "OP2 unmarshall error, %s, %s", err, string(e.RawData))
  312. return
  313. }
  314. // Start the voice websocket heartbeat to keep the connection alive
  315. go v.wsHeartbeat(v.wsConn, v.close, v.op2.HeartbeatInterval)
  316. // TODO monitor a chan/bool to verify this was successful
  317. // Start the UDP connection
  318. err := v.udpOpen()
  319. if err != nil {
  320. v.log(LogError, "error opening udp connection, %s", err)
  321. return
  322. }
  323. // Start the opusSender.
  324. // TODO: Should we allow 48000/960 values to be user defined?
  325. if v.OpusSend == nil {
  326. v.OpusSend = make(chan []byte, 2)
  327. }
  328. go v.opusSender(v.udpConn, v.close, v.OpusSend, 48000, 960)
  329. // Start the opusReceiver
  330. if !v.deaf {
  331. if v.OpusRecv == nil {
  332. v.OpusRecv = make(chan *Packet, 2)
  333. }
  334. go v.opusReceiver(v.udpConn, v.close, v.OpusRecv)
  335. }
  336. return
  337. case 3: // HEARTBEAT response
  338. // add code to use this to track latency?
  339. return
  340. case 4: // udp encryption secret key
  341. v.Lock()
  342. defer v.Unlock()
  343. v.op4 = voiceOP4{}
  344. if err := json.Unmarshal(e.RawData, &v.op4); err != nil {
  345. v.log(LogError, "OP4 unmarshall error, %s, %s", err, string(e.RawData))
  346. return
  347. }
  348. return
  349. case 5:
  350. if len(v.voiceSpeakingUpdateHandlers) == 0 {
  351. return
  352. }
  353. voiceSpeakingUpdate := &VoiceSpeakingUpdate{}
  354. if err := json.Unmarshal(e.RawData, voiceSpeakingUpdate); err != nil {
  355. v.log(LogError, "OP5 unmarshall error, %s, %s", err, string(e.RawData))
  356. return
  357. }
  358. for _, h := range v.voiceSpeakingUpdateHandlers {
  359. h(v, voiceSpeakingUpdate)
  360. }
  361. default:
  362. v.log(LogDebug, "unknown voice operation, %d, %s", e.Operation, string(e.RawData))
  363. }
  364. return
  365. }
  366. type voiceHeartbeatOp struct {
  367. Op int `json:"op"` // Always 3
  368. Data int `json:"d"`
  369. }
  370. // NOTE :: When a guild voice server changes how do we shut this down
  371. // properly, so a new connection can be setup without fuss?
  372. //
  373. // wsHeartbeat sends regular heartbeats to voice Discord so it knows the client
  374. // is still connected. If you do not send these heartbeats Discord will
  375. // disconnect the websocket connection after a few seconds.
  376. func (v *VoiceConnection) wsHeartbeat(wsConn *websocket.Conn, close <-chan struct{}, i time.Duration) {
  377. if close == nil || wsConn == nil {
  378. return
  379. }
  380. var err error
  381. ticker := time.NewTicker(i * time.Millisecond)
  382. defer ticker.Stop()
  383. for {
  384. v.log(LogDebug, "sending heartbeat packet")
  385. v.wsMutex.Lock()
  386. err = wsConn.WriteJSON(voiceHeartbeatOp{3, int(time.Now().Unix())})
  387. v.wsMutex.Unlock()
  388. if err != nil {
  389. v.log(LogError, "error sending heartbeat to voice endpoint %s, %s", v.endpoint, err)
  390. return
  391. }
  392. select {
  393. case <-ticker.C:
  394. // continue loop and send heartbeat
  395. case <-close:
  396. return
  397. }
  398. }
  399. }
  400. // ------------------------------------------------------------------------------------------------
  401. // Code related to the VoiceConnection UDP connection
  402. // ------------------------------------------------------------------------------------------------
  403. type voiceUDPData struct {
  404. Address string `json:"address"` // Public IP of machine running this code
  405. Port uint16 `json:"port"` // UDP Port of machine running this code
  406. Mode string `json:"mode"` // always "xsalsa20_poly1305"
  407. }
  408. type voiceUDPD struct {
  409. Protocol string `json:"protocol"` // Always "udp" ?
  410. Data voiceUDPData `json:"data"`
  411. }
  412. type voiceUDPOp struct {
  413. Op int `json:"op"` // Always 1
  414. Data voiceUDPD `json:"d"`
  415. }
  416. // udpOpen opens a UDP connection to the voice server and completes the
  417. // initial required handshake. This connection is left open in the session
  418. // and can be used to send or receive audio. This should only be called
  419. // from voice.wsEvent OP2
  420. func (v *VoiceConnection) udpOpen() (err error) {
  421. v.Lock()
  422. defer v.Unlock()
  423. if v.wsConn == nil {
  424. return fmt.Errorf("nil voice websocket")
  425. }
  426. if v.udpConn != nil {
  427. return fmt.Errorf("udp connection already open")
  428. }
  429. if v.close == nil {
  430. return fmt.Errorf("nil close channel")
  431. }
  432. if v.endpoint == "" {
  433. return fmt.Errorf("empty endpoint")
  434. }
  435. host := fmt.Sprintf("%s:%d", strings.TrimSuffix(v.endpoint, ":80"), v.op2.Port)
  436. addr, err := net.ResolveUDPAddr("udp", host)
  437. if err != nil {
  438. v.log(LogWarning, "error resolving udp host %s, %s", host, err)
  439. return
  440. }
  441. v.log(LogInformational, "connecting to udp addr %s", addr.String())
  442. v.udpConn, err = net.DialUDP("udp", nil, addr)
  443. if err != nil {
  444. v.log(LogWarning, "error connecting to udp addr %s, %s", addr.String(), err)
  445. return
  446. }
  447. // Create a 70 byte array and put the SSRC code from the Op 2 VoiceConnection event
  448. // into it. Then send that over the UDP connection to Discord
  449. sb := make([]byte, 70)
  450. binary.BigEndian.PutUint32(sb, v.op2.SSRC)
  451. _, err = v.udpConn.Write(sb)
  452. if err != nil {
  453. v.log(LogWarning, "udp write error to %s, %s", addr.String(), err)
  454. return
  455. }
  456. // Create a 70 byte array and listen for the initial handshake response
  457. // from Discord. Once we get it parse the IP and PORT information out
  458. // of the response. This should be our public IP and PORT as Discord
  459. // saw us.
  460. rb := make([]byte, 70)
  461. rlen, _, err := v.udpConn.ReadFromUDP(rb)
  462. if err != nil {
  463. v.log(LogWarning, "udp read error, %s, %s", addr.String(), err)
  464. return
  465. }
  466. if rlen < 70 {
  467. v.log(LogWarning, "received udp packet too small")
  468. return fmt.Errorf("received udp packet too small")
  469. }
  470. // Loop over position 4 through 20 to grab the IP address
  471. // Should never be beyond position 20.
  472. var ip string
  473. for i := 4; i < 20; i++ {
  474. if rb[i] == 0 {
  475. break
  476. }
  477. ip += string(rb[i])
  478. }
  479. // Grab port from position 68 and 69
  480. port := binary.LittleEndian.Uint16(rb[68:70])
  481. // Take the data from above and send it back to Discord to finalize
  482. // the UDP connection handshake.
  483. data := voiceUDPOp{1, voiceUDPD{"udp", voiceUDPData{ip, port, "xsalsa20_poly1305"}}}
  484. v.wsMutex.Lock()
  485. err = v.wsConn.WriteJSON(data)
  486. v.wsMutex.Unlock()
  487. if err != nil {
  488. v.log(LogWarning, "udp write error, %#v, %s", data, err)
  489. return
  490. }
  491. // start udpKeepAlive
  492. go v.udpKeepAlive(v.udpConn, v.close, 5*time.Second)
  493. // TODO: find a way to check that it fired off okay
  494. return
  495. }
  496. // udpKeepAlive sends a udp packet to keep the udp connection open
  497. // This is still a bit of a "proof of concept"
  498. func (v *VoiceConnection) udpKeepAlive(udpConn *net.UDPConn, close <-chan struct{}, i time.Duration) {
  499. if udpConn == nil || close == nil {
  500. return
  501. }
  502. var err error
  503. var sequence uint64
  504. packet := make([]byte, 8)
  505. ticker := time.NewTicker(i)
  506. defer ticker.Stop()
  507. for {
  508. binary.LittleEndian.PutUint64(packet, sequence)
  509. sequence++
  510. _, err = udpConn.Write(packet)
  511. if err != nil {
  512. v.log(LogError, "write error, %s", err)
  513. return
  514. }
  515. select {
  516. case <-ticker.C:
  517. // continue loop and send keepalive
  518. case <-close:
  519. return
  520. }
  521. }
  522. }
  523. // opusSender will listen on the given channel and send any
  524. // pre-encoded opus audio to Discord. Supposedly.
  525. func (v *VoiceConnection) opusSender(udpConn *net.UDPConn, close <-chan struct{}, opus <-chan []byte, rate, size int) {
  526. if udpConn == nil || close == nil {
  527. return
  528. }
  529. // VoiceConnection is now ready to receive audio packets
  530. // TODO: this needs reviewed as I think there must be a better way.
  531. v.Lock()
  532. v.Ready = true
  533. v.Unlock()
  534. defer func() {
  535. v.Lock()
  536. v.Ready = false
  537. v.Unlock()
  538. }()
  539. var sequence uint16
  540. var timestamp uint32
  541. var recvbuf []byte
  542. var ok bool
  543. udpHeader := make([]byte, 12)
  544. var nonce [24]byte
  545. // build the parts that don't change in the udpHeader
  546. udpHeader[0] = 0x80
  547. udpHeader[1] = 0x78
  548. binary.BigEndian.PutUint32(udpHeader[8:], v.op2.SSRC)
  549. // start a send loop that loops until buf chan is closed
  550. ticker := time.NewTicker(time.Millisecond * time.Duration(size/(rate/1000)))
  551. defer ticker.Stop()
  552. for {
  553. // Get data from chan. If chan is closed, return.
  554. select {
  555. case <-close:
  556. return
  557. case recvbuf, ok = <-opus:
  558. if !ok {
  559. return
  560. }
  561. // else, continue loop
  562. }
  563. v.RLock()
  564. speaking := v.speaking
  565. v.RUnlock()
  566. if !speaking {
  567. err := v.Speaking(true)
  568. if err != nil {
  569. v.log(LogError, "error sending speaking packet, %s", err)
  570. }
  571. }
  572. // Add sequence and timestamp to udpPacket
  573. binary.BigEndian.PutUint16(udpHeader[2:], sequence)
  574. binary.BigEndian.PutUint32(udpHeader[4:], timestamp)
  575. // encrypt the opus data
  576. copy(nonce[:], udpHeader)
  577. v.RLock()
  578. sendbuf := secretbox.Seal(udpHeader, recvbuf, &nonce, &v.op4.SecretKey)
  579. v.RUnlock()
  580. // block here until we're exactly at the right time :)
  581. // Then send rtp audio packet to Discord over UDP
  582. select {
  583. case <-close:
  584. return
  585. case <-ticker.C:
  586. // continue
  587. }
  588. _, err := udpConn.Write(sendbuf)
  589. if err != nil {
  590. v.log(LogError, "udp write error, %s", err)
  591. v.log(LogDebug, "voice struct: %#v\n", v)
  592. return
  593. }
  594. if (sequence) == 0xFFFF {
  595. sequence = 0
  596. } else {
  597. sequence++
  598. }
  599. if (timestamp + uint32(size)) >= 0xFFFFFFFF {
  600. timestamp = 0
  601. } else {
  602. timestamp += uint32(size)
  603. }
  604. }
  605. }
  606. // A Packet contains the headers and content of a received voice packet.
  607. type Packet struct {
  608. SSRC uint32
  609. Sequence uint16
  610. Timestamp uint32
  611. Type []byte
  612. Opus []byte
  613. PCM []int16
  614. }
  615. // opusReceiver listens on the UDP socket for incoming packets
  616. // and sends them across the given channel
  617. // NOTE :: This function may change names later.
  618. func (v *VoiceConnection) opusReceiver(udpConn *net.UDPConn, close <-chan struct{}, c chan *Packet) {
  619. if udpConn == nil || close == nil {
  620. return
  621. }
  622. recvbuf := make([]byte, 1024)
  623. var nonce [24]byte
  624. for {
  625. rlen, err := udpConn.Read(recvbuf)
  626. if err != nil {
  627. // Detect if we have been closed manually. If a Close() has already
  628. // happened, the udp connection we are listening on will be different
  629. // to the current session.
  630. v.RLock()
  631. sameConnection := v.udpConn == udpConn
  632. v.RUnlock()
  633. if sameConnection {
  634. v.log(LogError, "udp read error, %s, %s", v.endpoint, err)
  635. v.log(LogDebug, "voice struct: %#v\n", v)
  636. go v.reconnect()
  637. }
  638. return
  639. }
  640. select {
  641. case <-close:
  642. return
  643. default:
  644. // continue loop
  645. }
  646. // For now, skip anything except audio.
  647. if rlen < 12 || (recvbuf[0] != 0x80 && recvbuf[0] != 0x90) {
  648. continue
  649. }
  650. // build a audio packet struct
  651. p := Packet{}
  652. p.Type = recvbuf[0:2]
  653. p.Sequence = binary.BigEndian.Uint16(recvbuf[2:4])
  654. p.Timestamp = binary.BigEndian.Uint32(recvbuf[4:8])
  655. p.SSRC = binary.BigEndian.Uint32(recvbuf[8:12])
  656. // decrypt opus data
  657. copy(nonce[:], recvbuf[0:12])
  658. p.Opus, _ = secretbox.Open(nil, recvbuf[12:rlen], &nonce, &v.op4.SecretKey)
  659. if len(p.Opus) > 8 && recvbuf[0] == 0x90 {
  660. // Extension bit is set, first 8 bytes is the extended header
  661. p.Opus = p.Opus[8:]
  662. }
  663. if c != nil {
  664. select {
  665. case c <- &p:
  666. case <-close:
  667. return
  668. }
  669. }
  670. }
  671. }
  672. // Reconnect will close down a voice connection then immediately try to
  673. // reconnect to that session.
  674. // NOTE : This func is messy and a WIP while I find what works.
  675. // It will be cleaned up once a proven stable option is flushed out.
  676. // aka: this is ugly shit code, please don't judge too harshly.
  677. func (v *VoiceConnection) reconnect() {
  678. v.log(LogInformational, "called")
  679. v.Lock()
  680. if v.reconnecting {
  681. v.log(LogInformational, "already reconnecting to channel %s, exiting", v.ChannelID)
  682. v.Unlock()
  683. return
  684. }
  685. v.reconnecting = true
  686. v.Unlock()
  687. defer func() { v.reconnecting = false }()
  688. // Close any currently open connections
  689. v.Close()
  690. wait := time.Duration(1)
  691. for {
  692. <-time.After(wait * time.Second)
  693. wait *= 2
  694. if wait > 600 {
  695. wait = 600
  696. }
  697. if v.session.DataReady == false || v.session.wsConn == nil {
  698. v.log(LogInformational, "cannot reconenct to channel %s with unready session", v.ChannelID)
  699. continue
  700. }
  701. v.log(LogInformational, "trying to reconnect to channel %s", v.ChannelID)
  702. _, err := v.session.ChannelVoiceJoin(v.GuildID, v.ChannelID, v.mute, v.deaf)
  703. if err == nil {
  704. v.log(LogInformational, "successfully reconnected to channel %s", v.ChannelID)
  705. return
  706. }
  707. v.log(LogInformational, "error reconnecting to channel %s, %s", v.ChannelID, err)
  708. // if the reconnect above didn't work lets just send a disconnect
  709. // packet to reset things.
  710. // Send a OP4 with a nil channel to disconnect
  711. data := voiceChannelJoinOp{4, voiceChannelJoinData{&v.GuildID, nil, true, true}}
  712. v.session.wsMutex.Lock()
  713. err = v.session.wsConn.WriteJSON(data)
  714. v.session.wsMutex.Unlock()
  715. if err != nil {
  716. v.log(LogError, "error sending disconnect packet, %s", err)
  717. }
  718. }
  719. }