voice.go 20 KB

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