voice.go 19 KB

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