Skip to content

Commit

Permalink
Deps: Replace OnceCell with std::sync::OnceLock (serenity-rs#207)
Browse files Browse the repository at this point in the history
  • Loading branch information
GnomedDev authored and FelixMcFelix committed Jan 6, 2024
1 parent 1b98c30 commit f2bdd91
Show file tree
Hide file tree
Showing 11 changed files with 59 additions and 58 deletions.
3 changes: 0 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ discortp = { default-features = false, features = ["discord", "pnet", "rtp"], op
flume = { optional = true, version = "0.11" }
futures = "0.3"
nohash-hasher = { optional = true, version = "0.2.0" }
once_cell = { optional = true, version = "1" }
parking_lot = { optional = true, version = "0.12" }
pin-project = "1"
rand = { optional = true, version = "0.8" }
Expand Down Expand Up @@ -73,7 +72,6 @@ gateway = [
"dep:async-trait",
"dep:dashmap",
"dep:flume",
"dep:once_cell",
"dep:parking_lot",
"dep:tokio",
"tokio?/sync",
Expand All @@ -88,7 +86,6 @@ driver = [
"dep:reqwest",
"dep:flume",
"dep:nohash-hasher",
"dep:once_cell",
"dep:parking_lot",
"dep:rand",
"dep:ringbuf",
Expand Down
2 changes: 1 addition & 1 deletion benches/base-mixing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ fn make_src(src: &Vec<u8>, chans: u32, hz: u32) -> (Parsed, DecodeState) {
let adapted: Input =
songbird::input::RawAdapter::new(Cursor::new(src.clone()), hz, chans).into();
let promoted = match adapted {
Input::Live(l, _) => l.promote(&CODEC_REGISTRY, &PROBE),
Input::Live(l, _) => l.promote(get_codec_registry(), get_probe()),
_ => panic!("Failed to create a guaranteed source."),
};
let parsed = match promoted {
Expand Down
18 changes: 7 additions & 11 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,12 @@ use crate::driver::DecodeMode;
#[cfg(feature = "driver")]
use crate::{
driver::{
get_default_scheduler,
retry::Retry,
tasks::disposal::DisposalThread,
CryptoMode,
MixMode,
Scheduler,
DEFAULT_SCHEDULER,
},
input::codecs::*,
};
Expand Down Expand Up @@ -161,19 +161,15 @@ pub struct Config {
/// Registry of the inner codecs supported by the driver, adding audiopus-based
/// Opus codec support to all of Symphonia's default codecs.
///
/// Defaults to [`CODEC_REGISTRY`].
///
/// [`CODEC_REGISTRY`]: static@CODEC_REGISTRY
/// Defaults to [`get_codec_registry`].
pub codec_registry: &'static CodecRegistry,

#[cfg(feature = "driver")]
#[derivative(Debug = "ignore")]
/// Registry of the muxers and container formats supported by the driver.
///
/// Defaults to [`PROBE`], which includes all of Symphonia's default format handlers
/// Defaults to [`get_probe`], which includes all of Symphonia's default format handlers
/// and DCA format support.
///
/// [`PROBE`]: static@PROBE
pub format_registry: &'static Probe,

#[cfg(feature = "driver")]
Expand All @@ -191,7 +187,7 @@ pub struct Config {
/// The scheduler is responsible for mapping idle and active [`Driver`] instances
/// to threads.
///
/// If set to None, then songbird will initialise the [`DEFAULT_SCHEDULER`].
/// If set to None, then songbird will use [`get_default_scheduler`].
///
/// [`Driver`]: crate::Driver
pub scheduler: Option<Scheduler>,
Expand Down Expand Up @@ -233,9 +229,9 @@ impl Default for Config {
#[cfg(feature = "driver")]
driver_timeout: Some(Duration::from_secs(10)),
#[cfg(feature = "driver")]
codec_registry: &CODEC_REGISTRY,
codec_registry: get_codec_registry(),
#[cfg(feature = "driver")]
format_registry: &PROBE,
format_registry: get_probe(),
#[cfg(feature = "driver")]
disposer: None,
#[cfg(feature = "driver")]
Expand Down Expand Up @@ -359,7 +355,7 @@ impl Config {
pub fn get_scheduler(&self) -> Scheduler {
self.scheduler
.as_ref()
.unwrap_or(&*DEFAULT_SCHEDULER)
.unwrap_or(get_default_scheduler())
.clone()
}

Expand Down
2 changes: 1 addition & 1 deletion src/driver/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,12 @@ pub(crate) use crypto::CryptoState;
pub use decode_mode::DecodeMode;
pub use mix_mode::MixMode;
pub use scheduler::{
get_default_scheduler,
Config as SchedulerConfig,
Error as SchedulerError,
LiveStatBlock,
Mode as SchedulerMode,
Scheduler,
DEFAULT_SCHEDULER,
};
#[cfg(test)]
pub use test_config::*;
Expand Down
16 changes: 11 additions & 5 deletions src/driver/scheduler/mod.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
use std::{error::Error as StdError, fmt::Display, num::NonZeroUsize, sync::Arc};
use std::{
error::Error as StdError,
fmt::Display,
num::NonZeroUsize,
sync::{Arc, OnceLock},
};

use flume::{Receiver, RecvError, Sender};
use once_cell::sync::Lazy;

use crate::{constants::TIMESTEP_LENGTH, Config as DriverConfig};

use super::tasks::message::{Interconnect, MixerMessage};
use crate::{constants::TIMESTEP_LENGTH, Config as DriverConfig};

mod config;
mod idle;
Expand Down Expand Up @@ -34,7 +37,10 @@ const DEFAULT_MIXERS_PER_THREAD: NonZeroUsize = match NonZeroUsize::new(16) {
///
/// [`Config::default`]: crate::Config::default
/// [`ScheduleMode`]: Mode
pub static DEFAULT_SCHEDULER: Lazy<Scheduler> = Lazy::new(Scheduler::default);
pub fn get_default_scheduler() -> &'static Scheduler {
static DEFAULT_SCHEDULER: OnceLock<Scheduler> = OnceLock::new();
DEFAULT_SCHEDULER.get_or_init(Scheduler::default)
}

/// A reference to a shared group of threads used for running idle and active
/// audio threads.
Expand Down
10 changes: 5 additions & 5 deletions src/driver/test_impls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use crate::{
driver::crypto::KEY_SIZE,
input::{
cached::Compressed,
codecs::{CODEC_REGISTRY, PROBE},
codecs::{get_codec_registry, get_probe},
RawAdapter,
},
test_utils,
Expand Down Expand Up @@ -96,7 +96,7 @@ impl Mixer {
for _ in 0..num_tracks {
let input: Input = RawAdapter::new(Cursor::new(floats.clone()), 48_000, 2).into();
let promoted = match input {
Input::Live(l, _) => l.promote(&CODEC_REGISTRY, &PROBE),
Input::Live(l, _) => l.promote(get_codec_registry(), get_probe()),
Input::Lazy(_) => panic!("Failed to create a guaranteed source."),
};
let (_, ctx) = Track::from(Input::Live(promoted.unwrap(), None)).into_context();
Expand All @@ -113,7 +113,7 @@ impl Mixer {

let input: Input = RawAdapter::new(Cursor::new(floats.clone()), 48_000, 2).into();
let promoted = match input {
Input::Live(l, _) => l.promote(&CODEC_REGISTRY, &PROBE),
Input::Live(l, _) => l.promote(get_codec_registry(), get_probe()),
Input::Lazy(_) => panic!("Failed to create a guaranteed source."),
};
let mut track = Track::from(Input::Live(promoted.unwrap(), None));
Expand All @@ -132,7 +132,7 @@ impl Mixer {
let floats = test_utils::make_sine((i / 5) * STEREO_FRAME_SIZE, true);
let input: Input = RawAdapter::new(Cursor::new(floats.clone()), 48_000, 2).into();
let promoted = match input {
Input::Live(l, _) => l.promote(&CODEC_REGISTRY, &PROBE),
Input::Live(l, _) => l.promote(get_codec_registry(), get_probe()),
Input::Lazy(_) => panic!("Failed to create a guaranteed source."),
};
let (_, ctx) = Track::from(Input::Live(promoted.unwrap(), None)).into_context();
Expand Down Expand Up @@ -160,7 +160,7 @@ impl Mixer {
src.raw.load_all();

let promoted = match src.into() {
Input::Live(l, _) => l.promote(&CODEC_REGISTRY, &PROBE),
Input::Live(l, _) => l.promote(get_codec_registry(), get_probe()),
Input::Lazy(_) => panic!("Failed to create a guaranteed source."),
};
let (_, ctx) = Track::from(Input::Live(promoted.unwrap(), None)).into_context();
Expand Down
14 changes: 5 additions & 9 deletions src/input/adapters/cached/compressed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use super::{compressed_cost_per_sec, default_config, CodecCacheError, ToAudioByt
use crate::{
constants::*,
input::{
codecs::{dca::*, CODEC_REGISTRY, PROBE},
codecs::{dca::*, get_codec_registry, get_probe},
AudioStream,
Input,
LiveInput,
Expand Down Expand Up @@ -53,17 +53,13 @@ use tracing::{debug, trace};
pub struct Config {
/// Registry of audio codecs supported by the driver.
///
/// Defaults to [`CODEC_REGISTRY`], which adds audiopus-based Opus codec support
/// Defaults to [`get_codec_registry`], which adds audiopus-based Opus codec support
/// to all of Symphonia's default codecs.
///
/// [`CODEC_REGISTRY`]: static@CODEC_REGISTRY
pub codec_registry: &'static CodecRegistry,
/// Registry of the muxers and container formats supported by the driver.
///
/// Defaults to [`PROBE`], which includes all of Symphonia's default format handlers
/// Defaults to [`get_probe`], which includes all of Symphonia's default format handlers
/// and DCA format support.
///
/// [`PROBE`]: static@PROBE
pub format_registry: &'static Probe,
/// Configuration for the inner streamcatcher instance.
///
Expand All @@ -74,8 +70,8 @@ pub struct Config {
impl Default for Config {
fn default() -> Self {
Self {
codec_registry: &CODEC_REGISTRY,
format_registry: &PROBE,
codec_registry: get_codec_registry(),
format_registry: get_probe(),
streamcatcher: ScConfig::default(),
}
}
Expand Down
35 changes: 21 additions & 14 deletions src/input/codecs/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,26 +4,33 @@ pub(crate) mod dca;
mod opus;
mod raw;

use std::sync::OnceLock;

pub use self::{dca::DcaReader, opus::OpusDecoder, raw::*};
use once_cell::sync::Lazy;
use symphonia::{
core::{codecs::CodecRegistry, probe::Probe},
default::*,
};

/// Default Symphonia [`CodecRegistry`], including the (audiopus-backed) Opus codec.
pub static CODEC_REGISTRY: Lazy<CodecRegistry> = Lazy::new(|| {
let mut registry = CodecRegistry::new();
register_enabled_codecs(&mut registry);
registry.register_all::<OpusDecoder>();
registry
});
pub fn get_codec_registry() -> &'static CodecRegistry {
static CODEC_REGISTRY: OnceLock<CodecRegistry> = OnceLock::new();
CODEC_REGISTRY.get_or_init(|| {
let mut registry = CodecRegistry::new();
register_enabled_codecs(&mut registry);
registry.register_all::<OpusDecoder>();
registry
})
}

/// Default Symphonia Probe, including DCA format support.
pub static PROBE: Lazy<Probe> = Lazy::new(|| {
let mut probe = Probe::default();
probe.register_all::<DcaReader>();
probe.register_all::<RawReader>();
register_enabled_formats(&mut probe);
probe
});
pub fn get_probe() -> &'static Probe {
static PROBE: OnceLock<Probe> = OnceLock::new();
PROBE.get_or_init(|| {
let mut probe = Probe::default();
probe.register_all::<DcaReader>();
probe.register_all::<RawReader>();
register_enabled_formats(&mut probe);
probe
})
}
2 changes: 1 addition & 1 deletion src/input/live_input.rs
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ mod tests {
// finds the audio on a non-default track via `LiveInput::promote`.
let input = Input::from(File::new(FILE_VID_TARGET));
input
.make_playable_async(&CODEC_REGISTRY, &PROBE)
.make_playable_async(get_codec_registry(), get_probe())
.await
.unwrap();
}
Expand Down
6 changes: 3 additions & 3 deletions src/input/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,8 @@
//! [`OpusDecoder`]: codecs::OpusDecoder
//! [`DcaReader`]: codecs::DcaReader
//! [`RawReader`]: codecs::RawReader
//! [format]: static@codecs::PROBE
//! [codec registries]: static@codecs::CODEC_REGISTRY
//! [format]: codecs::get_probe
//! [codec registries]: codecs::get_codec_registry
mod adapters;
mod audiostream;
Expand Down Expand Up @@ -147,7 +147,7 @@ use tokio::runtime::Handle as TokioHandle;
/// //
/// // We can access it on a live track using `TrackHandle::action()`.
/// in_memory_input = in_memory_input
/// .make_playable_async(&CODEC_REGISTRY, &PROBE)
/// .make_playable_async(get_codec_registry(), get_probe())
/// .await
/// .expect("WAV support is included, and this file is good!");
///
Expand Down
9 changes: 4 additions & 5 deletions src/manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ use async_trait::async_trait;
use dashmap::DashMap;
#[cfg(feature = "serenity")]
use futures::channel::mpsc::UnboundedSender as Sender;
use once_cell::sync::OnceCell;
use parking_lot::RwLock as PRwLock;
#[cfg(feature = "serenity")]
use serenity::{
Expand All @@ -23,7 +22,7 @@ use serenity::{
voice::VoiceState,
},
};
use std::sync::Arc;
use std::sync::{Arc, OnceLock};
use tokio::sync::Mutex;
#[cfg(feature = "serenity")]
use tracing::debug;
Expand All @@ -44,7 +43,7 @@ struct ClientData {
/// [`Call`]: Call
#[derive(Debug)]
pub struct Songbird {
client_data: OnceCell<ClientData>,
client_data: OnceLock<ClientData>,
calls: DashMap<GuildId, Arc<Mutex<Call>>>,
sharder: Sharder,
config: PRwLock<Config>,
Expand All @@ -71,7 +70,7 @@ impl Songbird {
#[must_use]
pub fn serenity_from_config(config: Config) -> Arc<Self> {
Arc::new(Self {
client_data: OnceCell::new(),
client_data: OnceLock::new(),
calls: DashMap::new(),
sharder: Sharder::Serenity(SerenitySharder::default()),
config: config.initialise_disposer().into(),
Expand Down Expand Up @@ -110,7 +109,7 @@ impl Songbird {
U: Into<UserId>,
{
Self {
client_data: OnceCell::with_value(ClientData {
client_data: OnceLock::from(ClientData {
shard_count: sender_map.shard_count(),
user_id: user_id.into(),
}),
Expand Down

0 comments on commit f2bdd91

Please sign in to comment.