voice.go 20 KB

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