voice.go 19 KB

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