diff options
| author | acdenisSK <[email protected]> | 2017-08-24 15:26:49 +0200 |
|---|---|---|
| committer | acdenisSK <[email protected]> | 2017-08-24 16:36:01 +0200 |
| commit | b3a5bc89ad1c09290fb1c15ca3b36fe17c3796f3 (patch) | |
| tree | 315e16f7b252d22b5f832302e722a85c9e6a9b6e /src/voice | |
| parent | Allow FromStr for User to use REST (#147) (diff) | |
| download | serenity-b3a5bc89ad1c09290fb1c15ca3b36fe17c3796f3.tar.xz serenity-b3a5bc89ad1c09290fb1c15ca3b36fe17c3796f3.zip | |
Revamp `RwLock` usage in the lib
Also not quite sure if they goofed rustfmt or something, but its changes it did were a bit bizarre.
Diffstat (limited to 'src/voice')
| -rw-r--r-- | src/voice/connection.rs | 97 | ||||
| -rw-r--r-- | src/voice/error.rs | 18 | ||||
| -rw-r--r-- | src/voice/handler.rs | 2 | ||||
| -rw-r--r-- | src/voice/mod.rs | 3 | ||||
| -rw-r--r-- | src/voice/streamer.rs | 14 |
5 files changed, 58 insertions, 76 deletions
diff --git a/src/voice/connection.rs b/src/voice/connection.rs index 2d1e8f5..7cc8b3a 100644 --- a/src/voice/connection.rs +++ b/src/voice/connection.rs @@ -1,6 +1,11 @@ use byteorder::{BigEndian, LittleEndian, ReadBytesExt, WriteBytesExt}; -use opus::{Application as CodingMode, Channels, Decoder as OpusDecoder, Encoder as OpusEncoder, - packet as opus_packet}; +use opus::{ + packet as opus_packet, + Application as CodingMode, + Channels, + Decoder as OpusDecoder, + Encoder as OpusEncoder, +}; use sodiumoxide::crypto::secretbox::{self, Key, Nonce}; use std::collections::HashMap; use std::io::Write; @@ -11,7 +16,7 @@ use std::thread::{self, Builder as ThreadBuilder, JoinHandle}; use std::time::Duration; use super::audio::{AudioReceiver, AudioSource, HEADER_LEN, SAMPLE_RATE}; use super::connection_info::ConnectionInfo; -use super::{CRYPTO_MODE, VoiceError, payload}; +use super::{payload, VoiceError, CRYPTO_MODE}; use websocket::client::Url as WebsocketUrl; use websocket::sync::client::ClientBuilder; use websocket::sync::stream::{AsTcpStream, TcpStream, TlsStream}; @@ -110,27 +115,27 @@ impl Connection { // Find the position in the bytes that contains the first byte of 0, // indicating the "end of the address". - let index = bytes.iter().skip(4).position(|&x| x == 0).ok_or( - Error::Voice( - VoiceError::FindingByte, - ), - )?; + let index = bytes + .iter() + .skip(4) + .position(|&x| x == 0) + .ok_or(Error::Voice(VoiceError::FindingByte))?; let pos = 4 + index; let addr = String::from_utf8_lossy(&bytes[4..pos]); let port_pos = len - 2; let port = (&bytes[port_pos..]).read_u16::<LittleEndian>()?; - client.send_json( - &payload::build_select_protocol(addr, port), - )?; + client + .send_json(&payload::build_select_protocol(addr, port))?; } let key = encryption_key(&mut client)?; - let _ = client.stream_ref().as_tcp().set_read_timeout( - Some(Duration::from_millis(25)), - ); + let _ = client + .stream_ref() + .as_tcp() + .set_read_timeout(Some(Duration::from_millis(25))); let mutexed_client = Arc::new(Mutex::new(client)); let thread_items = start_threads(mutexed_client.clone(), &udp)?; @@ -178,21 +183,17 @@ impl Connection { let timestamp = handle.read_u32::<BigEndian>()?; let ssrc = handle.read_u32::<BigEndian>()?; - nonce.0[..HEADER_LEN].clone_from_slice( - &packet[..HEADER_LEN], - ); + nonce.0[..HEADER_LEN] + .clone_from_slice(&packet[..HEADER_LEN]); - if let Ok(decrypted) = secretbox::open( - &packet[HEADER_LEN..], - &nonce, - &self.key, - ) { + if let Ok(decrypted) = + secretbox::open(&packet[HEADER_LEN..], &nonce, &self.key) { let channels = opus_packet::get_nb_channels(&decrypted)?; let entry = - self.decoder_map.entry((ssrc, channels)).or_insert_with(|| { - OpusDecoder::new(SAMPLE_RATE, channels).unwrap() - }); + self.decoder_map.entry((ssrc, channels)).or_insert_with( + || OpusDecoder::new(SAMPLE_RATE, channels).unwrap(), + ); let len = entry.decode(&decrypted, &mut buffer, false)?; @@ -200,13 +201,8 @@ impl Connection { let b = if is_stereo { len * 2 } else { len }; - receiver.voice_packet( - ssrc, - seq, - timestamp, - is_stereo, - &buffer[..b], - ); + receiver + .voice_packet(ssrc, seq, timestamp, is_stereo, &buffer[..b]); } }, ReceiverStatus::Websocket(VoiceEvent::Speaking(ev)) => { @@ -227,9 +223,10 @@ impl Connection { // Send the voice websocket keepalive if it's time if self.keepalive_timer.check() { - self.client.lock().unwrap().send_json( - &payload::build_keepalive(), - )?; + self.client + .lock() + .unwrap() + .send_json(&payload::build_keepalive())?; } // Send UDP keepalive if it's time @@ -287,17 +284,14 @@ impl Connection { cursor.write_u32::<BigEndian>(self.ssrc)?; } - nonce.0[..HEADER_LEN].clone_from_slice( - &packet[..HEADER_LEN], - ); + nonce.0[..HEADER_LEN] + .clone_from_slice(&packet[..HEADER_LEN]); let sl_index = packet.len() - 16; let buffer_len = if self.encoder_stereo { 960 * 2 } else { 960 }; - let len = self.encoder.encode( - &buffer[..buffer_len], - &mut packet[HEADER_LEN..sl_index], - )?; + let len = self.encoder + .encode(&buffer[..buffer_len], &mut packet[HEADER_LEN..sl_index])?; let crypted = { let slice = &packet[HEADER_LEN..HEADER_LEN + len]; secretbox::seal(slice, &nonce, &self.key) @@ -359,11 +353,10 @@ impl Connection { self.speaking = speaking; - self.client.lock().unwrap().send_json( - &payload::build_speaking( - speaking, - ), - ) + self.client + .lock() + .unwrap() + .send_json(&payload::build_speaking(speaking)) } } @@ -383,9 +376,8 @@ fn generate_url(endpoint: &mut String) -> Result<WebsocketUrl> { endpoint.truncate(len - 3); } - WebsocketUrl::parse(&format!("wss://{}", endpoint)).or(Err( - Error::Voice(VoiceError::EndpointUrl), - )) + WebsocketUrl::parse(&format!("wss://{}", endpoint)) + .or(Err(Error::Voice(VoiceError::EndpointUrl))) } #[inline] @@ -397,9 +389,8 @@ fn encryption_key(client: &mut Client) -> Result<Key> { return Err(Error::Voice(VoiceError::VoiceModeInvalid)); } - return Key::from_slice(&ready.secret_key).ok_or(Error::Voice( - VoiceError::KeyGen, - )); + return Key::from_slice(&ready.secret_key) + .ok_or(Error::Voice(VoiceError::KeyGen)); }, VoiceEvent::Unknown(op, value) => { debug!( diff --git a/src/voice/error.rs b/src/voice/error.rs index 55be1f6..b756bfb 100644 --- a/src/voice/error.rs +++ b/src/voice/error.rs @@ -7,20 +7,14 @@ use std::process::Output; pub enum VoiceError { /// An indicator that an endpoint URL was invalid. EndpointUrl, - #[doc(hidden)] - ExpectedHandshake, - #[doc(hidden)] - FindingByte, - #[doc(hidden)] - HostnameResolve, - #[doc(hidden)] - KeyGen, + #[doc(hidden)] ExpectedHandshake, + #[doc(hidden)] FindingByte, + #[doc(hidden)] HostnameResolve, + #[doc(hidden)] KeyGen, /// An error occurred while checking if a path is stereo. Streams, - #[doc(hidden)] - VoiceModeInvalid, - #[doc(hidden)] - VoiceModeUnavailable, + #[doc(hidden)] VoiceModeInvalid, + #[doc(hidden)] VoiceModeUnavailable, /// An error occurred while running `youtube-dl`. YouTubeDLRun(Output), /// An error occurred while processing the JSON output from `youtube-dl`. diff --git a/src/voice/handler.rs b/src/voice/handler.rs index 24b3cd9..9c3f691 100644 --- a/src/voice/handler.rs +++ b/src/voice/handler.rs @@ -225,7 +225,7 @@ impl Handler { /// can pass in just a boxed receiver, and do not need to specify `Some`. /// /// Pass `None` to drop the current receiver, if one exists. - pub fn listen<O: Into<Option<Box<AudioReceiver>>>>(&mut self, receiver: O) { +pub fn listen<O: Into<Option<Box<AudioReceiver>>>>(&mut self, receiver: O){ self.send(VoiceStatus::SetReceiver(receiver.into())) } diff --git a/src/voice/mod.rs b/src/voice/mod.rs index 4707ea8..a94c8a0 100644 --- a/src/voice/mod.rs +++ b/src/voice/mod.rs @@ -22,8 +22,7 @@ const CRYPTO_MODE: &'static str = "xsalsa20_poly1305"; pub(crate) enum Status { Connect(ConnectionInfo), - #[allow(dead_code)] - Disconnect, + #[allow(dead_code)] Disconnect, SetReceiver(Option<Box<AudioReceiver>>), SetSender(Option<Box<AudioSource>>), } diff --git a/src/voice/streamer.rs b/src/voice/streamer.rs index 3f40bae..c8400f0 100644 --- a/src/voice/streamer.rs +++ b/src/voice/streamer.rs @@ -101,11 +101,9 @@ pub fn ytdl(uri: &str) -> Result<Box<AudioSource>> { }; let uri = match obj.remove("url") { - Some(v) => { - match v { - Value::String(uri) => uri, - other => return Err(Error::Voice(VoiceError::YouTubeDLUrl(other))), - } + Some(v) => match v { + Value::String(uri) => uri, + other => return Err(Error::Voice(VoiceError::YouTubeDLUrl(other))), }, None => return Err(Error::Voice(VoiceError::YouTubeDLUrl(Value::Object(obj)))), }; @@ -131,9 +129,9 @@ fn is_stereo(path: &OsStr) -> Result<bool> { .ok_or(Error::Voice(VoiceError::Streams))?; let check = streams.iter().any(|stream| { - let channels = stream.as_object().and_then(|m| { - m.get("channels").and_then(|v| v.as_i64()) - }); + let channels = stream + .as_object() + .and_then(|m| m.get("channels").and_then(|v| v.as_i64())); channels == Some(2) }); |