github.com/meowstercatel/discordgo@v0.0.0-20250615204139-29b43d676735/voice.go (about)

     1  // Discordgo - Discord bindings for Go
     2  // Available at https://github.com/bwmarrin/discordgo
     3  
     4  // Copyright 2015-2016 Bruce Marriner <bruce@sqls.net>.  All rights reserved.
     5  // Use of this source code is governed by a BSD-style
     6  // license that can be found in the LICENSE file.
     7  
     8  // This file contains code related to Discord voice suppport
     9  
    10  package discordgo
    11  
    12  import (
    13  	"encoding/binary"
    14  	"encoding/json"
    15  	"fmt"
    16  	"net"
    17  	"strconv"
    18  	"strings"
    19  	"sync"
    20  	"time"
    21  
    22  	"github.com/gorilla/websocket"
    23  	"golang.org/x/crypto/nacl/secretbox"
    24  )
    25  
    26  // ------------------------------------------------------------------------------------------------
    27  // Code related to both VoiceConnection Websocket and UDP connections.
    28  // ------------------------------------------------------------------------------------------------
    29  
    30  // A VoiceConnection struct holds all the data and functions related to a Discord Voice Connection.
    31  type VoiceConnection struct {
    32  	sync.RWMutex
    33  
    34  	Debug        bool // If true, print extra logging -- DEPRECATED
    35  	LogLevel     int
    36  	Ready        bool // If true, voice is ready to send/receive audio
    37  	UserID       string
    38  	GuildID      string
    39  	ChannelID    string
    40  	deaf         bool
    41  	mute         bool
    42  	speaking     bool
    43  	reconnecting bool // If true, voice connection is trying to reconnect
    44  
    45  	OpusSend chan []byte  // Chan for sending opus audio
    46  	OpusRecv chan *Packet // Chan for receiving opus audio
    47  
    48  	wsConn  *websocket.Conn
    49  	wsMutex sync.Mutex
    50  	udpConn *net.UDPConn
    51  	session *Session
    52  
    53  	sessionID string
    54  	token     string
    55  	endpoint  string
    56  
    57  	// Used to send a close signal to goroutines
    58  	close chan struct{}
    59  
    60  	// Used to allow blocking until connected
    61  	connected chan bool
    62  
    63  	// Used to pass the sessionid from onVoiceStateUpdate
    64  	// sessionRecv chan string UNUSED ATM
    65  
    66  	op4 voiceOP4
    67  	op2 voiceOP2
    68  
    69  	voiceSpeakingUpdateHandlers []VoiceSpeakingUpdateHandler
    70  }
    71  
    72  // VoiceSpeakingUpdateHandler type provides a function definition for the
    73  // VoiceSpeakingUpdate event
    74  type VoiceSpeakingUpdateHandler func(vc *VoiceConnection, vs *VoiceSpeakingUpdate)
    75  
    76  // Speaking sends a speaking notification to Discord over the voice websocket.
    77  // This must be sent as true prior to sending audio and should be set to false
    78  // once finished sending audio.
    79  // b : Send true if speaking, false if not.
    80  func (v *VoiceConnection) Speaking(b bool) (err error) {
    81  
    82  	v.log(LogDebug, "called (%t)", b)
    83  
    84  	type voiceSpeakingData struct {
    85  		Speaking bool `json:"speaking"`
    86  		Delay    int  `json:"delay"`
    87  	}
    88  
    89  	type voiceSpeakingOp struct {
    90  		Op   int               `json:"op"` // Always 5
    91  		Data voiceSpeakingData `json:"d"`
    92  	}
    93  
    94  	if v.wsConn == nil {
    95  		return fmt.Errorf("no VoiceConnection websocket")
    96  	}
    97  
    98  	data := voiceSpeakingOp{5, voiceSpeakingData{b, 0}}
    99  	v.wsMutex.Lock()
   100  	err = v.wsConn.WriteJSON(data)
   101  	v.wsMutex.Unlock()
   102  
   103  	v.Lock()
   104  	defer v.Unlock()
   105  	if err != nil {
   106  		v.speaking = false
   107  		v.log(LogError, "Speaking() write json error, %s", err)
   108  		return
   109  	}
   110  
   111  	v.speaking = b
   112  
   113  	return
   114  }
   115  
   116  // ChangeChannel sends Discord a request to change channels within a Guild
   117  // !!! NOTE !!! This function may be removed in favour of just using ChannelVoiceJoin
   118  func (v *VoiceConnection) ChangeChannel(channelID string, mute, deaf bool) (err error) {
   119  
   120  	v.log(LogInformational, "called")
   121  
   122  	data := voiceChannelJoinOp{4, voiceChannelJoinData{&v.GuildID, &channelID, mute, deaf}}
   123  	v.session.wsMutex.Lock()
   124  	err = v.session.wsConn.WriteJSON(data)
   125  	v.session.wsMutex.Unlock()
   126  	if err != nil {
   127  		return
   128  	}
   129  	v.ChannelID = channelID
   130  	v.deaf = deaf
   131  	v.mute = mute
   132  	v.speaking = false
   133  
   134  	return
   135  }
   136  
   137  // Disconnect disconnects from this voice channel and closes the websocket
   138  // and udp connections to Discord.
   139  func (v *VoiceConnection) Disconnect() (err error) {
   140  
   141  	// Send a OP4 with a nil channel to disconnect
   142  	v.Lock()
   143  	if v.sessionID != "" {
   144  		data := voiceChannelJoinOp{4, voiceChannelJoinData{&v.GuildID, nil, true, true}}
   145  		v.session.wsMutex.Lock()
   146  		err = v.session.wsConn.WriteJSON(data)
   147  		v.session.wsMutex.Unlock()
   148  		v.sessionID = ""
   149  	}
   150  	v.Unlock()
   151  
   152  	// Close websocket and udp connections
   153  	v.Close()
   154  
   155  	v.log(LogInformational, "Deleting VoiceConnection %s", v.GuildID)
   156  
   157  	v.session.Lock()
   158  	delete(v.session.VoiceConnections, v.GuildID)
   159  	v.session.Unlock()
   160  
   161  	return
   162  }
   163  
   164  // Close closes the voice ws and udp connections
   165  func (v *VoiceConnection) Close() {
   166  
   167  	v.log(LogInformational, "called")
   168  
   169  	v.Lock()
   170  	defer v.Unlock()
   171  
   172  	v.Ready = false
   173  	v.speaking = false
   174  
   175  	if v.close != nil {
   176  		v.log(LogInformational, "closing v.close")
   177  		close(v.close)
   178  		v.close = nil
   179  	}
   180  
   181  	if v.udpConn != nil {
   182  		v.log(LogInformational, "closing udp")
   183  		err := v.udpConn.Close()
   184  		if err != nil {
   185  			v.log(LogError, "error closing udp connection, %s", err)
   186  		}
   187  		v.udpConn = nil
   188  	}
   189  
   190  	if v.wsConn != nil {
   191  		v.log(LogInformational, "sending close frame")
   192  
   193  		// To cleanly close a connection, a client should send a close
   194  		// frame and wait for the server to close the connection.
   195  		v.wsMutex.Lock()
   196  		err := v.wsConn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
   197  		v.wsMutex.Unlock()
   198  		if err != nil {
   199  			v.log(LogError, "error closing websocket, %s", err)
   200  		}
   201  
   202  		// TODO: Wait for Discord to actually close the connection.
   203  		time.Sleep(1 * time.Second)
   204  
   205  		v.log(LogInformational, "closing websocket")
   206  		err = v.wsConn.Close()
   207  		if err != nil {
   208  			v.log(LogError, "error closing websocket, %s", err)
   209  		}
   210  
   211  		v.wsConn = nil
   212  	}
   213  }
   214  
   215  // AddHandler adds a Handler for VoiceSpeakingUpdate events.
   216  func (v *VoiceConnection) AddHandler(h VoiceSpeakingUpdateHandler) {
   217  	v.Lock()
   218  	defer v.Unlock()
   219  
   220  	v.voiceSpeakingUpdateHandlers = append(v.voiceSpeakingUpdateHandlers, h)
   221  }
   222  
   223  // VoiceSpeakingUpdate is a struct for a VoiceSpeakingUpdate event.
   224  type VoiceSpeakingUpdate struct {
   225  	UserID   string `json:"user_id"`
   226  	SSRC     int    `json:"ssrc"`
   227  	Speaking bool   `json:"speaking"`
   228  }
   229  
   230  // ------------------------------------------------------------------------------------------------
   231  // Unexported Internal Functions Below.
   232  // ------------------------------------------------------------------------------------------------
   233  
   234  // A voiceOP4 stores the data for the voice operation 4 websocket event
   235  // which provides us with the NaCl SecretBox encryption key
   236  type voiceOP4 struct {
   237  	SecretKey [32]byte `json:"secret_key"`
   238  	Mode      string   `json:"mode"`
   239  }
   240  
   241  // A voiceOP2 stores the data for the voice operation 2 websocket event
   242  // which is sort of like the voice READY packet
   243  type voiceOP2 struct {
   244  	SSRC              uint32        `json:"ssrc"`
   245  	Port              int           `json:"port"`
   246  	Modes             []string      `json:"modes"`
   247  	HeartbeatInterval time.Duration `json:"heartbeat_interval"`
   248  	IP                string        `json:"ip"`
   249  }
   250  
   251  // WaitUntilConnected waits for the Voice Connection to
   252  // become ready, if it does not become ready it returns an err
   253  func (v *VoiceConnection) waitUntilConnected() error {
   254  
   255  	v.log(LogInformational, "called")
   256  
   257  	i := 0
   258  	for {
   259  		v.RLock()
   260  		ready := v.Ready
   261  		v.RUnlock()
   262  		if ready {
   263  			return nil
   264  		}
   265  
   266  		if i > 10 {
   267  			return fmt.Errorf("timeout waiting for voice")
   268  		}
   269  
   270  		time.Sleep(1 * time.Second)
   271  		i++
   272  	}
   273  }
   274  
   275  // Open opens a voice connection.  This should be called
   276  // after VoiceChannelJoin is used and the data VOICE websocket events
   277  // are captured.
   278  func (v *VoiceConnection) open() (err error) {
   279  
   280  	v.log(LogInformational, "called")
   281  
   282  	v.Lock()
   283  	defer v.Unlock()
   284  
   285  	// Don't open a websocket if one is already open
   286  	if v.wsConn != nil {
   287  		v.log(LogWarning, "refusing to overwrite non-nil websocket")
   288  		return
   289  	}
   290  
   291  	// TODO temp? loop to wait for the SessionID
   292  	i := 0
   293  	for {
   294  		if v.sessionID != "" {
   295  			break
   296  		}
   297  
   298  		if i > 20 { // only loop for up to 1 second total
   299  			return fmt.Errorf("did not receive voice Session ID in time")
   300  		}
   301  		// Release the lock, so sessionID can be populated upon receiving a VoiceStateUpdate event.
   302  		v.Unlock()
   303  		time.Sleep(50 * time.Millisecond)
   304  		i++
   305  		v.Lock()
   306  	}
   307  
   308  	// Connect to VoiceConnection Websocket
   309  	vg := "wss://" + strings.TrimSuffix(v.endpoint, ":80")
   310  	v.log(LogInformational, "connecting to voice endpoint %s", vg)
   311  	v.wsConn, _, err = v.session.Dialer.Dial(vg, nil)
   312  	if err != nil {
   313  		v.log(LogWarning, "error connecting to voice endpoint %s, %s", vg, err)
   314  		v.log(LogDebug, "voice struct: %#v\n", v)
   315  		return
   316  	}
   317  
   318  	type voiceHandshakeData struct {
   319  		ServerID  string `json:"server_id"`
   320  		UserID    string `json:"user_id"`
   321  		SessionID string `json:"session_id"`
   322  		Token     string `json:"token"`
   323  	}
   324  	type voiceHandshakeOp struct {
   325  		Op   int                `json:"op"` // Always 0
   326  		Data voiceHandshakeData `json:"d"`
   327  	}
   328  	data := voiceHandshakeOp{0, voiceHandshakeData{v.GuildID, v.UserID, v.sessionID, v.token}}
   329  
   330  	v.wsMutex.Lock()
   331  	err = v.wsConn.WriteJSON(data)
   332  	v.wsMutex.Unlock()
   333  	if err != nil {
   334  		v.log(LogWarning, "error sending init packet, %s", err)
   335  		return
   336  	}
   337  
   338  	v.close = make(chan struct{})
   339  	go v.wsListen(v.wsConn, v.close)
   340  
   341  	// add loop/check for Ready bool here?
   342  	// then return false if not ready?
   343  	// but then wsListen will also err.
   344  
   345  	return
   346  }
   347  
   348  // wsListen listens on the voice websocket for messages and passes them
   349  // to the voice event handler.  This is automatically called by the Open func
   350  func (v *VoiceConnection) wsListen(wsConn *websocket.Conn, close <-chan struct{}) {
   351  
   352  	v.log(LogInformational, "called")
   353  
   354  	for {
   355  		_, message, err := v.wsConn.ReadMessage()
   356  		if err != nil {
   357  			// 4014 indicates a manual disconnection by someone in the guild;
   358  			// we shouldn't reconnect.
   359  			if websocket.IsCloseError(err, 4014) {
   360  				v.log(LogInformational, "received 4014 manual disconnection")
   361  
   362  				// Abandon the voice WS connection
   363  				v.Lock()
   364  				v.wsConn = nil
   365  				v.Unlock()
   366  
   367  				// Wait for VOICE_SERVER_UPDATE.
   368  				// When the bot is moved by the user to another voice channel,
   369  				// VOICE_SERVER_UPDATE is received after the code 4014.
   370  				for i := 0; i < 5; i++ { // TODO: temp, wait for VoiceServerUpdate.
   371  					<-time.After(1 * time.Second)
   372  
   373  					v.RLock()
   374  					reconnected := v.wsConn != nil
   375  					v.RUnlock()
   376  					if !reconnected {
   377  						continue
   378  					}
   379  					v.log(LogInformational, "successfully reconnected after 4014 manual disconnection")
   380  					return
   381  				}
   382  
   383  				// When VOICE_SERVER_UPDATE is not received, disconnect as usual.
   384  				v.log(LogInformational, "disconnect due to 4014 manual disconnection")
   385  
   386  				v.session.Lock()
   387  				delete(v.session.VoiceConnections, v.GuildID)
   388  				v.session.Unlock()
   389  
   390  				v.Close()
   391  
   392  				return
   393  			}
   394  
   395  			// Detect if we have been closed manually. If a Close() has already
   396  			// happened, the websocket we are listening on will be different to the
   397  			// current session.
   398  			v.RLock()
   399  			sameConnection := v.wsConn == wsConn
   400  			v.RUnlock()
   401  			if sameConnection {
   402  
   403  				v.log(LogError, "voice endpoint %s websocket closed unexpectantly, %s", v.endpoint, err)
   404  
   405  				// Start reconnect goroutine then exit.
   406  				go v.reconnect()
   407  			}
   408  			return
   409  		}
   410  
   411  		// Pass received message to voice event handler
   412  		select {
   413  		case <-close:
   414  			return
   415  		default:
   416  			go v.onEvent(message)
   417  		}
   418  	}
   419  }
   420  
   421  // wsEvent handles any voice websocket events. This is only called by the
   422  // wsListen() function.
   423  func (v *VoiceConnection) onEvent(message []byte) {
   424  
   425  	v.log(LogDebug, "received: %s", string(message))
   426  
   427  	var e Event
   428  	if err := json.Unmarshal(message, &e); err != nil {
   429  		v.log(LogError, "unmarshall error, %s", err)
   430  		return
   431  	}
   432  
   433  	switch e.Operation {
   434  
   435  	case 2: // READY
   436  
   437  		if err := json.Unmarshal(e.RawData, &v.op2); err != nil {
   438  			v.log(LogError, "OP2 unmarshall error, %s, %s", err, string(e.RawData))
   439  			return
   440  		}
   441  
   442  		// Start the voice websocket heartbeat to keep the connection alive
   443  		go v.wsHeartbeat(v.wsConn, v.close, v.op2.HeartbeatInterval)
   444  		// TODO monitor a chan/bool to verify this was successful
   445  
   446  		// Start the UDP connection
   447  		err := v.udpOpen()
   448  		if err != nil {
   449  			v.log(LogError, "error opening udp connection, %s", err)
   450  			return
   451  		}
   452  
   453  		// Start the opusSender.
   454  		// TODO: Should we allow 48000/960 values to be user defined?
   455  		if v.OpusSend == nil {
   456  			v.OpusSend = make(chan []byte, 2)
   457  		}
   458  		go v.opusSender(v.udpConn, v.close, v.OpusSend, 48000, 960)
   459  
   460  		// Start the opusReceiver
   461  		if !v.deaf {
   462  			if v.OpusRecv == nil {
   463  				v.OpusRecv = make(chan *Packet, 2)
   464  			}
   465  
   466  			go v.opusReceiver(v.udpConn, v.close, v.OpusRecv)
   467  		}
   468  
   469  		return
   470  
   471  	case 3: // HEARTBEAT response
   472  		// add code to use this to track latency?
   473  		return
   474  
   475  	case 4: // udp encryption secret key
   476  		v.Lock()
   477  		defer v.Unlock()
   478  
   479  		v.op4 = voiceOP4{}
   480  		if err := json.Unmarshal(e.RawData, &v.op4); err != nil {
   481  			v.log(LogError, "OP4 unmarshall error, %s, %s", err, string(e.RawData))
   482  			return
   483  		}
   484  		return
   485  
   486  	case 5:
   487  		if len(v.voiceSpeakingUpdateHandlers) == 0 {
   488  			return
   489  		}
   490  
   491  		voiceSpeakingUpdate := &VoiceSpeakingUpdate{}
   492  		if err := json.Unmarshal(e.RawData, voiceSpeakingUpdate); err != nil {
   493  			v.log(LogError, "OP5 unmarshall error, %s, %s", err, string(e.RawData))
   494  			return
   495  		}
   496  
   497  		for _, h := range v.voiceSpeakingUpdateHandlers {
   498  			h(v, voiceSpeakingUpdate)
   499  		}
   500  
   501  	default:
   502  		v.log(LogDebug, "unknown voice operation, %d, %s", e.Operation, string(e.RawData))
   503  	}
   504  
   505  	return
   506  }
   507  
   508  type voiceHeartbeatOp struct {
   509  	Op   int `json:"op"` // Always 3
   510  	Data int `json:"d"`
   511  }
   512  
   513  // NOTE :: When a guild voice server changes how do we shut this down
   514  // properly, so a new connection can be setup without fuss?
   515  //
   516  // wsHeartbeat sends regular heartbeats to voice Discord so it knows the client
   517  // is still connected.  If you do not send these heartbeats Discord will
   518  // disconnect the websocket connection after a few seconds.
   519  func (v *VoiceConnection) wsHeartbeat(wsConn *websocket.Conn, close <-chan struct{}, i time.Duration) {
   520  
   521  	if close == nil || wsConn == nil {
   522  		return
   523  	}
   524  
   525  	var err error
   526  	ticker := time.NewTicker(i * time.Millisecond)
   527  	defer ticker.Stop()
   528  	for {
   529  		v.log(LogDebug, "sending heartbeat packet")
   530  		v.wsMutex.Lock()
   531  		err = wsConn.WriteJSON(voiceHeartbeatOp{3, int(time.Now().Unix())})
   532  		v.wsMutex.Unlock()
   533  		if err != nil {
   534  			v.log(LogError, "error sending heartbeat to voice endpoint %s, %s", v.endpoint, err)
   535  			return
   536  		}
   537  
   538  		select {
   539  		case <-ticker.C:
   540  			// continue loop and send heartbeat
   541  		case <-close:
   542  			return
   543  		}
   544  	}
   545  }
   546  
   547  // ------------------------------------------------------------------------------------------------
   548  // Code related to the VoiceConnection UDP connection
   549  // ------------------------------------------------------------------------------------------------
   550  
   551  type voiceUDPData struct {
   552  	Address string `json:"address"` // Public IP of machine running this code
   553  	Port    uint16 `json:"port"`    // UDP Port of machine running this code
   554  	Mode    string `json:"mode"`    // always "xsalsa20_poly1305"
   555  }
   556  
   557  type voiceUDPD struct {
   558  	Protocol string       `json:"protocol"` // Always "udp" ?
   559  	Data     voiceUDPData `json:"data"`
   560  }
   561  
   562  type voiceUDPOp struct {
   563  	Op   int       `json:"op"` // Always 1
   564  	Data voiceUDPD `json:"d"`
   565  }
   566  
   567  // udpOpen opens a UDP connection to the voice server and completes the
   568  // initial required handshake.  This connection is left open in the session
   569  // and can be used to send or receive audio.  This should only be called
   570  // from voice.wsEvent OP2
   571  func (v *VoiceConnection) udpOpen() (err error) {
   572  
   573  	v.Lock()
   574  	defer v.Unlock()
   575  
   576  	if v.wsConn == nil {
   577  		return fmt.Errorf("nil voice websocket")
   578  	}
   579  
   580  	if v.udpConn != nil {
   581  		return fmt.Errorf("udp connection already open")
   582  	}
   583  
   584  	if v.close == nil {
   585  		return fmt.Errorf("nil close channel")
   586  	}
   587  
   588  	if v.endpoint == "" {
   589  		return fmt.Errorf("empty endpoint")
   590  	}
   591  
   592  	host := v.op2.IP + ":" + strconv.Itoa(v.op2.Port)
   593  	addr, err := net.ResolveUDPAddr("udp", host)
   594  	if err != nil {
   595  		v.log(LogWarning, "error resolving udp host %s, %s", host, err)
   596  		return
   597  	}
   598  
   599  	v.log(LogInformational, "connecting to udp addr %s", addr.String())
   600  	v.udpConn, err = net.DialUDP("udp", nil, addr)
   601  	if err != nil {
   602  		v.log(LogWarning, "error connecting to udp addr %s, %s", addr.String(), err)
   603  		return
   604  	}
   605  
   606  	// Create a 74 byte array to store the packet data
   607  	sb := make([]byte, 74)
   608  	binary.BigEndian.PutUint16(sb, 1)              // Packet type (0x1 is request, 0x2 is response)
   609  	binary.BigEndian.PutUint16(sb[2:], 70)         // Packet length (excluding type and length fields)
   610  	binary.BigEndian.PutUint32(sb[4:], v.op2.SSRC) // The SSRC code from the Op 2 VoiceConnection event
   611  
   612  	// And send that data over the UDP connection to Discord.
   613  	_, err = v.udpConn.Write(sb)
   614  	if err != nil {
   615  		v.log(LogWarning, "udp write error to %s, %s", addr.String(), err)
   616  		return
   617  	}
   618  
   619  	// Create a 74 byte array and listen for the initial handshake response
   620  	// from Discord.  Once we get it parse the IP and PORT information out
   621  	// of the response.  This should be our public IP and PORT as Discord
   622  	// saw us.
   623  	rb := make([]byte, 74)
   624  	rlen, _, err := v.udpConn.ReadFromUDP(rb)
   625  	if err != nil {
   626  		v.log(LogWarning, "udp read error, %s, %s", addr.String(), err)
   627  		return
   628  	}
   629  
   630  	if rlen < 74 {
   631  		v.log(LogWarning, "received udp packet too small")
   632  		return fmt.Errorf("received udp packet too small")
   633  	}
   634  
   635  	// Loop over position 8 through 71 to grab the IP address.
   636  	var ip string
   637  	for i := 8; i < len(rb)-2; i++ {
   638  		if rb[i] == 0 {
   639  			break
   640  		}
   641  		ip += string(rb[i])
   642  	}
   643  
   644  	// Grab port from position 72 and 73
   645  	port := binary.BigEndian.Uint16(rb[len(rb)-2:])
   646  
   647  	// Take the data from above and send it back to Discord to finalize
   648  	// the UDP connection handshake.
   649  	data := voiceUDPOp{1, voiceUDPD{"udp", voiceUDPData{ip, port, "xsalsa20_poly1305"}}}
   650  
   651  	v.wsMutex.Lock()
   652  	err = v.wsConn.WriteJSON(data)
   653  	v.wsMutex.Unlock()
   654  	if err != nil {
   655  		v.log(LogWarning, "udp write error, %#v, %s", data, err)
   656  		return
   657  	}
   658  
   659  	// start udpKeepAlive
   660  	go v.udpKeepAlive(v.udpConn, v.close, 5*time.Second)
   661  	// TODO: find a way to check that it fired off okay
   662  
   663  	return
   664  }
   665  
   666  // udpKeepAlive sends a udp packet to keep the udp connection open
   667  // This is still a bit of a "proof of concept"
   668  func (v *VoiceConnection) udpKeepAlive(udpConn *net.UDPConn, close <-chan struct{}, i time.Duration) {
   669  
   670  	if udpConn == nil || close == nil {
   671  		return
   672  	}
   673  
   674  	var err error
   675  	var sequence uint64
   676  
   677  	packet := make([]byte, 8)
   678  
   679  	ticker := time.NewTicker(i)
   680  	defer ticker.Stop()
   681  	for {
   682  
   683  		binary.LittleEndian.PutUint64(packet, sequence)
   684  		sequence++
   685  
   686  		_, err = udpConn.Write(packet)
   687  		if err != nil {
   688  			v.log(LogError, "write error, %s", err)
   689  			return
   690  		}
   691  
   692  		select {
   693  		case <-ticker.C:
   694  			// continue loop and send keepalive
   695  		case <-close:
   696  			return
   697  		}
   698  	}
   699  }
   700  
   701  // opusSender will listen on the given channel and send any
   702  // pre-encoded opus audio to Discord.  Supposedly.
   703  func (v *VoiceConnection) opusSender(udpConn *net.UDPConn, close <-chan struct{}, opus <-chan []byte, rate, size int) {
   704  
   705  	if udpConn == nil || close == nil {
   706  		return
   707  	}
   708  
   709  	// VoiceConnection is now ready to receive audio packets
   710  	// TODO: this needs reviewed as I think there must be a better way.
   711  	v.Lock()
   712  	v.Ready = true
   713  	v.Unlock()
   714  	defer func() {
   715  		v.Lock()
   716  		v.Ready = false
   717  		v.Unlock()
   718  	}()
   719  
   720  	var sequence uint16
   721  	var timestamp uint32
   722  	var recvbuf []byte
   723  	var ok bool
   724  	udpHeader := make([]byte, 12)
   725  	var nonce [24]byte
   726  
   727  	// build the parts that don't change in the udpHeader
   728  	udpHeader[0] = 0x80
   729  	udpHeader[1] = 0x78
   730  	binary.BigEndian.PutUint32(udpHeader[8:], v.op2.SSRC)
   731  
   732  	// start a send loop that loops until buf chan is closed
   733  	ticker := time.NewTicker(time.Millisecond * time.Duration(size/(rate/1000)))
   734  	defer ticker.Stop()
   735  	for {
   736  
   737  		// Get data from chan.  If chan is closed, return.
   738  		select {
   739  		case <-close:
   740  			return
   741  		case recvbuf, ok = <-opus:
   742  			if !ok {
   743  				return
   744  			}
   745  			// else, continue loop
   746  		}
   747  
   748  		v.RLock()
   749  		speaking := v.speaking
   750  		v.RUnlock()
   751  		if !speaking {
   752  			err := v.Speaking(true)
   753  			if err != nil {
   754  				v.log(LogError, "error sending speaking packet, %s", err)
   755  			}
   756  		}
   757  
   758  		// Add sequence and timestamp to udpPacket
   759  		binary.BigEndian.PutUint16(udpHeader[2:], sequence)
   760  		binary.BigEndian.PutUint32(udpHeader[4:], timestamp)
   761  
   762  		// encrypt the opus data
   763  		copy(nonce[:], udpHeader)
   764  		v.RLock()
   765  		sendbuf := secretbox.Seal(udpHeader, recvbuf, &nonce, &v.op4.SecretKey)
   766  		v.RUnlock()
   767  
   768  		// block here until we're exactly at the right time :)
   769  		// Then send rtp audio packet to Discord over UDP
   770  		select {
   771  		case <-close:
   772  			return
   773  		case <-ticker.C:
   774  			// continue
   775  		}
   776  		_, err := udpConn.Write(sendbuf)
   777  
   778  		if err != nil {
   779  			v.log(LogError, "udp write error, %s", err)
   780  			v.log(LogDebug, "voice struct: %#v\n", v)
   781  			return
   782  		}
   783  
   784  		if (sequence) == 0xFFFF {
   785  			sequence = 0
   786  		} else {
   787  			sequence++
   788  		}
   789  
   790  		if (timestamp + uint32(size)) >= 0xFFFFFFFF {
   791  			timestamp = 0
   792  		} else {
   793  			timestamp += uint32(size)
   794  		}
   795  	}
   796  }
   797  
   798  // A Packet contains the headers and content of a received voice packet.
   799  type Packet struct {
   800  	SSRC      uint32
   801  	Sequence  uint16
   802  	Timestamp uint32
   803  	Type      []byte
   804  	Opus      []byte
   805  	PCM       []int16
   806  }
   807  
   808  // opusReceiver listens on the UDP socket for incoming packets
   809  // and sends them across the given channel
   810  // NOTE :: This function may change names later.
   811  func (v *VoiceConnection) opusReceiver(udpConn *net.UDPConn, close <-chan struct{}, c chan *Packet) {
   812  
   813  	if udpConn == nil || close == nil {
   814  		return
   815  	}
   816  
   817  	recvbuf := make([]byte, 1024)
   818  	var nonce [24]byte
   819  
   820  	for {
   821  		rlen, err := udpConn.Read(recvbuf)
   822  		if err != nil {
   823  			// Detect if we have been closed manually. If a Close() has already
   824  			// happened, the udp connection we are listening on will be different
   825  			// to the current session.
   826  			v.RLock()
   827  			sameConnection := v.udpConn == udpConn
   828  			v.RUnlock()
   829  			if sameConnection {
   830  
   831  				v.log(LogError, "udp read error, %s, %s", v.endpoint, err)
   832  				v.log(LogDebug, "voice struct: %#v\n", v)
   833  
   834  				go v.reconnect()
   835  			}
   836  			return
   837  		}
   838  
   839  		select {
   840  		case <-close:
   841  			return
   842  		default:
   843  			// continue loop
   844  		}
   845  
   846  		// For now, skip anything except audio.
   847  		if rlen < 12 || (recvbuf[0] != 0x80 && recvbuf[0] != 0x90) {
   848  			continue
   849  		}
   850  
   851  		// build a audio packet struct
   852  		p := Packet{}
   853  		p.Type = recvbuf[0:2]
   854  		p.Sequence = binary.BigEndian.Uint16(recvbuf[2:4])
   855  		p.Timestamp = binary.BigEndian.Uint32(recvbuf[4:8])
   856  		p.SSRC = binary.BigEndian.Uint32(recvbuf[8:12])
   857  		// decrypt opus data
   858  		copy(nonce[:], recvbuf[0:12])
   859  
   860  		if opus, ok := secretbox.Open(nil, recvbuf[12:rlen], &nonce, &v.op4.SecretKey); ok {
   861  			p.Opus = opus
   862  		} else {
   863  			continue
   864  		}
   865  
   866  		// extension bit set, and not a RTCP packet
   867  		if ((recvbuf[0] & 0x10) == 0x10) && ((recvbuf[1] & 0x80) == 0) {
   868  			// get extended header length
   869  			extlen := binary.BigEndian.Uint16(p.Opus[2:4])
   870  			// 4 bytes (ext header header) + 4*extlen (ext header data)
   871  			shift := int(4 + 4*extlen)
   872  			if len(p.Opus) > shift {
   873  				p.Opus = p.Opus[shift:]
   874  			}
   875  		}
   876  
   877  		if c != nil {
   878  			select {
   879  			case c <- &p:
   880  			case <-close:
   881  				return
   882  			}
   883  		}
   884  	}
   885  }
   886  
   887  // Reconnect will close down a voice connection then immediately try to
   888  // reconnect to that session.
   889  // NOTE : This func is messy and a WIP while I find what works.
   890  // It will be cleaned up once a proven stable option is flushed out.
   891  // aka: this is ugly shit code, please don't judge too harshly.
   892  func (v *VoiceConnection) reconnect() {
   893  
   894  	v.log(LogInformational, "called")
   895  
   896  	v.Lock()
   897  	if v.reconnecting {
   898  		v.log(LogInformational, "already reconnecting to channel %s, exiting", v.ChannelID)
   899  		v.Unlock()
   900  		return
   901  	}
   902  	v.reconnecting = true
   903  	v.Unlock()
   904  
   905  	defer func() {
   906  		v.Lock()
   907  		v.reconnecting = false
   908  		v.Unlock()
   909  	}()
   910  
   911  	// Close any currently open connections
   912  	v.Close()
   913  
   914  	wait := time.Duration(1)
   915  	for {
   916  
   917  		<-time.After(wait * time.Second)
   918  		wait *= 2
   919  		if wait > 600 {
   920  			wait = 600
   921  		}
   922  
   923  		if v.session.DataReady == false || v.session.wsConn == nil {
   924  			v.log(LogInformational, "cannot reconnect to channel %s with unready session", v.ChannelID)
   925  			continue
   926  		}
   927  
   928  		v.log(LogInformational, "trying to reconnect to channel %s", v.ChannelID)
   929  
   930  		_, err := v.session.ChannelVoiceJoin(v.GuildID, v.ChannelID, v.mute, v.deaf)
   931  		if err == nil {
   932  			v.log(LogInformational, "successfully reconnected to channel %s", v.ChannelID)
   933  			return
   934  		}
   935  
   936  		v.log(LogInformational, "error reconnecting to channel %s, %s", v.ChannelID, err)
   937  
   938  		// if the reconnect above didn't work lets just send a disconnect
   939  		// packet to reset things.
   940  		// Send a OP4 with a nil channel to disconnect
   941  		data := voiceChannelJoinOp{4, voiceChannelJoinData{&v.GuildID, nil, true, true}}
   942  		v.session.wsMutex.Lock()
   943  		err = v.session.wsConn.WriteJSON(data)
   944  		v.session.wsMutex.Unlock()
   945  		if err != nil {
   946  			v.log(LogError, "error sending disconnect packet, %s", err)
   947  		}
   948  
   949  	}
   950  }