voice.go 19 KB

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