voice.go 19 KB

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