diff options
| author | Zeyla Hellyer <[email protected]> | 2017-05-22 17:02:00 -0700 |
|---|---|---|
| committer | Zeyla Hellyer <[email protected]> | 2017-05-22 17:02:00 -0700 |
| commit | 9969be60cf320797c37b317da24d9a08fd5eafa5 (patch) | |
| tree | f27bf7a57af95bbc11990b1edcea9cca99276964 /src/voice/streamer.rs | |
| parent | Reasonably derive Debug on items (diff) | |
| download | serenity-9969be60cf320797c37b317da24d9a08fd5eafa5.tar.xz serenity-9969be60cf320797c37b317da24d9a08fd5eafa5.zip | |
Restructure modules
Modules are now separated into a fashion where the library can be used
for most use cases, without needing to compile the rest.
The core of serenity, with no features enabled, contains only the
struct (model) definitions, constants, and prelude. Models do not have
most functions compiled in, as that is separated into the `model`
feature.
The `client` module has been split into 3 modules: `client`, `gateway`,
and `http`.
`http` contains functions to interact with the REST API. `gateway`
contains the Shard to interact with the gateway, requiring `http` for
retrieving the gateway URL. `client` requires both of the other features
and acts as an abstracted interface over both the gateway and REST APIs,
handling the event loop.
The `builder` module has been separated from `utils`, and can now be
optionally compiled in. It and the `http` feature are required by the
`model` feature due to a large number of methods requiring access to
them.
`utils` now contains a number of utilities, such as the Colour struct, the
`MessageBuilder`, and mention parsing functions.
Each of the original `ext` modules are still featured, with `cache` not
requiring any feature to be enabled, `framework` requiring the `client`,
`model`, and `utils`, and `voice` requiring `gateway`.
In total the features and their requirements are:
- `builder`: none
- `cache`: none
- `client`: `gateway`, `http`
- `framework`: `client`, `model`, `utils`
- `gateway`: `http`
- `http`: none
- `model`: `builder`, `http`
- `utils`: none
- `voice`: `gateway`
The default features are `builder`, `cache`, `client`, `framework`,
`gateway`, `model`, `http`, and `utils`.
To help with forwards compatibility, modules have been re-exported from
their original locations.
Diffstat (limited to 'src/voice/streamer.rs')
| -rw-r--r-- | src/voice/streamer.rs | 152 |
1 files changed, 152 insertions, 0 deletions
diff --git a/src/voice/streamer.rs b/src/voice/streamer.rs new file mode 100644 index 0000000..4d3b9a9 --- /dev/null +++ b/src/voice/streamer.rs @@ -0,0 +1,152 @@ +use byteorder::{LittleEndian, ReadBytesExt}; +use serde_json; +use std::ffi::OsStr; +use std::io::{ErrorKind as IoErrorKind, Read, Result as IoResult}; +use std::process::{Child, Command, Stdio}; +use super::{AudioSource, VoiceError}; +use ::internal::prelude::*; + +struct ChildContainer(Child); + +impl Read for ChildContainer { + fn read(&mut self, buffer: &mut [u8]) -> IoResult<usize> { + self.0.stdout.as_mut().unwrap().read(buffer) + } +} + +struct PcmSource<R: Read + Send + 'static>(bool, R); + +impl<R: Read + Send> AudioSource for PcmSource<R> { + fn is_stereo(&mut self) -> bool { + self.0 + } + + fn read_frame(&mut self, buffer: &mut [i16]) -> Option<usize> { + for (i, v) in buffer.iter_mut().enumerate() { + *v = match self.1.read_i16::<LittleEndian>() { + Ok(v) => v, + Err(ref e) => return if e.kind() == IoErrorKind::UnexpectedEof { + Some(i) + } else { + None + }, + } + } + + Some(buffer.len()) + } +} + +/// Opens an audio file through `ffmpeg` and creates an audio source. +pub fn ffmpeg<P: AsRef<OsStr>>(path: P) -> Result<Box<AudioSource>> { + let path = path.as_ref(); + + /// Will fail if the path is not to a file on the fs. Likely a YouTube URI. + let is_stereo = is_stereo(path).unwrap_or(false); + let stereo_val = if is_stereo { + "2" + } else { + "1" + }; + + let args = [ + "-f", + "s16le", + "-ac", + stereo_val, + "-ar", + "48000", + "-acodec", + "pcm_s16le", + "-", + ]; + + let command = Command::new("ffmpeg") + .arg("-i") + .arg(path) + .args(&args) + .stderr(Stdio::null()) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .spawn()?; + + Ok(pcm(is_stereo, ChildContainer(command))) +} + +/// Creates a PCM audio source. +pub fn pcm<R: Read + Send + 'static>(is_stereo: bool, reader: R) + -> Box<AudioSource> { + Box::new(PcmSource(is_stereo, reader)) +} + +/// Creates a streamed audio source with `youtube-dl` and `ffmpeg`. +pub fn ytdl(uri: &str) -> Result<Box<AudioSource>> { + let args = [ + "-f", + "webm[abr>0]/bestaudio/best", + "--no-playlist", + "--print-json", + "--skip-download", + uri, + ]; + + let out = Command::new("youtube-dl") + .args(&args) + .stdin(Stdio::null()) + .output()?; + + if !out.status.success() { + return Err(Error::Voice(VoiceError::YouTubeDLRun(out))); + } + + let value = serde_json::from_reader(&out.stdout[..])?; + let mut obj = match value { + Value::Object(obj) => obj, + other => return Err(Error::Voice(VoiceError::YouTubeDLProcessing(other))), + }; + + let uri = match obj.remove("url") { + 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)))), + }; + + ffmpeg(&uri) +} + +fn is_stereo(path: &OsStr) -> Result<bool> { + let args = [ + "-v", + "quiet", + "-of", + "json", + "-show-streams", + "-i", + ]; + + let out = Command::new("ffprobe") + .args(&args) + .arg(path) + .stdin(Stdio::null()) + .output()?; + + let value: Value = serde_json::from_reader(&out.stdout[..])?; + + let streams = value.as_object() + .and_then(|m| m.get("streams")) + .and_then(|v| v.as_array()) + .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())); + + channels == Some(2) + }); + + Ok(check) +} |