voice.go 22 KB

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