voice.go 20 KB

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