voice.go 22 KB

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