aboutsummaryrefslogtreecommitdiff
path: root/src/voice
diff options
context:
space:
mode:
authorZeyla Hellyer <[email protected]>2017-09-18 17:48:52 -0700
committerZeyla Hellyer <[email protected]>2017-09-18 17:48:52 -0700
commitdae2cb77b407044f44a7a2790d93efba3891854e (patch)
treebef263c4490536cf8b56e988e71dd1aa43bc2696 /src/voice
parentFix compiles of a variety of feature combinations (diff)
downloadserenity-dae2cb77b407044f44a7a2790d93efba3891854e.tar.xz
serenity-dae2cb77b407044f44a7a2790d93efba3891854e.zip
Apply rustfmt
Diffstat (limited to 'src/voice')
-rw-r--r--src/voice/connection.rs116
-rw-r--r--src/voice/error.rs18
-rw-r--r--src/voice/mod.rs3
-rw-r--r--src/voice/streamer.rs24
4 files changed, 69 insertions, 92 deletions
diff --git a/src/voice/connection.rs b/src/voice/connection.rs
index 7f2ac23..620f19e 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, AudioType, 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
@@ -257,14 +254,12 @@ impl Connection {
}
match stream.get_type() {
- AudioType::Opus => {
- match stream.read_opus_frame() {
- Some(frame) => {
- opus_frame = frame;
- opus_frame.len()
- },
- None => 0,
- }
+ AudioType::Opus => match stream.read_opus_frame() {
+ Some(frame) => {
+ opus_frame = frame;
+ opus_frame.len()
+ },
+ None => 0,
},
AudioType::Pcm => {
let buffer_len = if is_stereo { 960 * 2 } else { 960 };
@@ -326,23 +321,19 @@ 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 = if opus_frame.is_empty() {
- self.encoder.encode(
- &buffer[..buffer_len],
- &mut packet[HEADER_LEN..sl_index],
- )?
+ self.encoder
+ .encode(&buffer[..buffer_len], &mut packet[HEADER_LEN..sl_index])?
} else {
let len = opus_frame.len();
- packet[HEADER_LEN..HEADER_LEN + len].clone_from_slice(
- opus_frame,
- );
+ packet[HEADER_LEN..HEADER_LEN + len]
+ .clone_from_slice(opus_frame);
len
};
@@ -366,11 +357,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))
}
}
@@ -390,9 +380,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]
@@ -404,9 +393,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 a0bb11a..d402e54 100644
--- a/src/voice/error.rs
+++ b/src/voice/error.rs
@@ -8,20 +8,14 @@ use std;
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/mod.rs b/src/voice/mod.rs
index 6af5926..70f1ae2 100644
--- a/src/voice/mod.rs
+++ b/src/voice/mod.rs
@@ -24,8 +24,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 cf62d27..4702bdb 100644
--- a/src/voice/streamer.rs
+++ b/src/voice/streamer.rs
@@ -65,12 +65,10 @@ impl<R: Read + Send> AudioSource for InputSource<R> {
Some(frame)
},
- Err(ref e) => {
- if e.kind() == IoErrorKind::UnexpectedEof {
- Some(Vec::new())
- } else {
- None
- }
+ Err(ref e) => if e.kind() == IoErrorKind::UnexpectedEof {
+ Some(Vec::new())
+ } else {
+ None
},
}
}
@@ -194,11 +192,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)))),
};
@@ -224,9 +220,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)
});