Deps: Replace OnceCell with std::sync::OnceLock (#207)

This commit is contained in:
Gnome!
2023-12-02 17:22:00 +00:00
committed by Kyle Simpson
parent 2146846df4
commit 743a1d262e
11 changed files with 59 additions and 58 deletions

View File

@@ -28,7 +28,6 @@ discortp = { default-features = false, features = ["discord", "pnet", "rtp"], op
flume = { optional = true, version = "0.11" } flume = { optional = true, version = "0.11" }
futures = "0.3" futures = "0.3"
nohash-hasher = { optional = true, version = "0.2.0" } nohash-hasher = { optional = true, version = "0.2.0" }
once_cell = { optional = true, version = "1" }
parking_lot = { optional = true, version = "0.12" } parking_lot = { optional = true, version = "0.12" }
pin-project = "1" pin-project = "1"
rand = { optional = true, version = "0.8" } rand = { optional = true, version = "0.8" }
@@ -78,7 +77,6 @@ gateway = [
"dep:async-trait", "dep:async-trait",
"dep:dashmap", "dep:dashmap",
"dep:flume", "dep:flume",
"dep:once_cell",
"dep:parking_lot", "dep:parking_lot",
"dep:tokio", "dep:tokio",
"tokio?/sync", "tokio?/sync",
@@ -96,7 +94,6 @@ driver = [
"dep:discortp", "dep:discortp",
"dep:flume", "dep:flume",
"dep:nohash-hasher", "dep:nohash-hasher",
"dep:once_cell",
"dep:parking_lot", "dep:parking_lot",
"dep:rand", "dep:rand",
"dep:reqwest", "dep:reqwest",

View File

@@ -88,7 +88,7 @@ fn make_src(src: &Vec<u8>, chans: u32, hz: u32) -> (Parsed, DecodeState) {
let adapted: Input = let adapted: Input =
songbird::input::RawAdapter::new(Cursor::new(src.clone()), hz, chans).into(); songbird::input::RawAdapter::new(Cursor::new(src.clone()), hz, chans).into();
let promoted = match adapted { 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."), _ => panic!("Failed to create a guaranteed source."),
}; };
let parsed = match promoted { let parsed = match promoted {

View File

@@ -3,12 +3,12 @@ use crate::driver::{Channels, DecodeMode, SampleRate};
#[cfg(feature = "driver")] #[cfg(feature = "driver")]
use crate::{ use crate::{
driver::{ driver::{
get_default_scheduler,
retry::Retry, retry::Retry,
tasks::disposal::DisposalThread, tasks::disposal::DisposalThread,
CryptoMode, CryptoMode,
MixMode, MixMode,
Scheduler, Scheduler,
DEFAULT_SCHEDULER,
}, },
input::codecs::*, input::codecs::*,
}; };
@@ -173,19 +173,15 @@ pub struct Config {
/// Registry of the inner codecs supported by the driver, adding audiopus-based /// Registry of the inner codecs supported by the driver, adding audiopus-based
/// Opus codec support to all of Symphonia's default codecs. /// Opus codec support to all of Symphonia's default codecs.
/// ///
/// Defaults to [`CODEC_REGISTRY`]. /// Defaults to [`get_codec_registry`].
///
/// [`CODEC_REGISTRY`]: static@CODEC_REGISTRY
pub codec_registry: &'static CodecRegistry, pub codec_registry: &'static CodecRegistry,
#[cfg(feature = "driver")] #[cfg(feature = "driver")]
#[derivative(Debug = "ignore")] #[derivative(Debug = "ignore")]
/// Registry of the muxers and container formats supported by the driver. /// 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. /// and DCA format support.
///
/// [`PROBE`]: static@PROBE
pub format_registry: &'static Probe, pub format_registry: &'static Probe,
#[cfg(feature = "driver")] #[cfg(feature = "driver")]
@@ -203,7 +199,7 @@ pub struct Config {
/// The scheduler is responsible for mapping idle and active [`Driver`] instances /// The scheduler is responsible for mapping idle and active [`Driver`] instances
/// to threads. /// 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 /// [`Driver`]: crate::Driver
pub scheduler: Option<Scheduler>, pub scheduler: Option<Scheduler>,
@@ -249,9 +245,9 @@ impl Default for Config {
#[cfg(feature = "driver")] #[cfg(feature = "driver")]
driver_timeout: Some(Duration::from_secs(10)), driver_timeout: Some(Duration::from_secs(10)),
#[cfg(feature = "driver")] #[cfg(feature = "driver")]
codec_registry: &CODEC_REGISTRY, codec_registry: get_codec_registry(),
#[cfg(feature = "driver")] #[cfg(feature = "driver")]
format_registry: &PROBE, format_registry: get_probe(),
#[cfg(feature = "driver")] #[cfg(feature = "driver")]
disposer: None, disposer: None,
#[cfg(feature = "driver")] #[cfg(feature = "driver")]
@@ -391,7 +387,7 @@ impl Config {
pub fn get_scheduler(&self) -> Scheduler { pub fn get_scheduler(&self) -> Scheduler {
self.scheduler self.scheduler
.as_ref() .as_ref()
.unwrap_or(&*DEFAULT_SCHEDULER) .unwrap_or(get_default_scheduler())
.clone() .clone()
} }

View File

@@ -31,12 +31,12 @@ pub(crate) use crypto::CryptoState;
pub use decode_mode::*; pub use decode_mode::*;
pub use mix_mode::MixMode; pub use mix_mode::MixMode;
pub use scheduler::{ pub use scheduler::{
get_default_scheduler,
Config as SchedulerConfig, Config as SchedulerConfig,
Error as SchedulerError, Error as SchedulerError,
LiveStatBlock, LiveStatBlock,
Mode as SchedulerMode, Mode as SchedulerMode,
Scheduler, Scheduler,
DEFAULT_SCHEDULER,
}; };
#[cfg(test)] #[cfg(test)]
pub use test_config::*; pub use test_config::*;

View File

@@ -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 flume::{Receiver, RecvError, Sender};
use once_cell::sync::Lazy;
use crate::{constants::TIMESTEP_LENGTH, Config as DriverConfig};
use super::tasks::message::{Interconnect, MixerMessage}; use super::tasks::message::{Interconnect, MixerMessage};
use crate::{constants::TIMESTEP_LENGTH, Config as DriverConfig};
mod config; mod config;
mod idle; mod idle;
@@ -34,7 +37,10 @@ const DEFAULT_MIXERS_PER_THREAD: NonZeroUsize = match NonZeroUsize::new(16) {
/// ///
/// [`Config::default`]: crate::Config::default /// [`Config::default`]: crate::Config::default
/// [`ScheduleMode`]: Mode /// [`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 /// A reference to a shared group of threads used for running idle and active
/// audio threads. /// audio threads.

View File

@@ -9,7 +9,7 @@ use crate::{
constants::*, constants::*,
input::{ input::{
cached::Compressed, cached::Compressed,
codecs::{CODEC_REGISTRY, PROBE}, codecs::{get_codec_registry, get_probe},
RawAdapter, RawAdapter,
}, },
test_utils, test_utils,
@@ -103,7 +103,7 @@ impl Mixer {
for _ in 0..num_tracks { for _ in 0..num_tracks {
let input: Input = RawAdapter::new(Cursor::new(floats.clone()), 48_000, 2).into(); let input: Input = RawAdapter::new(Cursor::new(floats.clone()), 48_000, 2).into();
let promoted = match input { 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."), Input::Lazy(_) => panic!("Failed to create a guaranteed source."),
}; };
let (_, ctx) = Track::from(Input::Live(promoted.unwrap(), None)).into_context(); let (_, ctx) = Track::from(Input::Live(promoted.unwrap(), None)).into_context();
@@ -121,7 +121,7 @@ impl Mixer {
let input: Input = RawAdapter::new(Cursor::new(floats.clone()), 48_000, 2).into(); let input: Input = RawAdapter::new(Cursor::new(floats.clone()), 48_000, 2).into();
let promoted = match input { 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."), Input::Lazy(_) => panic!("Failed to create a guaranteed source."),
}; };
let mut track = Track::from(Input::Live(promoted.unwrap(), None)); let mut track = Track::from(Input::Live(promoted.unwrap(), None));
@@ -141,7 +141,7 @@ impl Mixer {
let floats = test_utils::make_sine((i / 5) * STEREO_FRAME_SIZE, true); 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 input: Input = RawAdapter::new(Cursor::new(floats.clone()), 48_000, 2).into();
let promoted = match input { 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."), Input::Lazy(_) => panic!("Failed to create a guaranteed source."),
}; };
let (_, ctx) = Track::from(Input::Live(promoted.unwrap(), None)).into_context(); let (_, ctx) = Track::from(Input::Live(promoted.unwrap(), None)).into_context();
@@ -170,7 +170,7 @@ impl Mixer {
src.raw.load_all(); src.raw.load_all();
let promoted = match src.into() { 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."), Input::Lazy(_) => panic!("Failed to create a guaranteed source."),
}; };
let (_, ctx) = Track::from(Input::Live(promoted.unwrap(), None)).into_context(); let (_, ctx) = Track::from(Input::Live(promoted.unwrap(), None)).into_context();

View File

@@ -2,7 +2,7 @@ use super::{compressed_cost_per_sec, default_config, CodecCacheError, ToAudioByt
use crate::{ use crate::{
constants::*, constants::*,
input::{ input::{
codecs::{dca::*, CODEC_REGISTRY, PROBE}, codecs::{dca::*, get_codec_registry, get_probe},
AudioStream, AudioStream,
Input, Input,
LiveInput, LiveInput,
@@ -52,17 +52,13 @@ use tracing::{debug, trace};
pub struct Config { pub struct Config {
/// Registry of audio codecs supported by the driver. /// 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. /// to all of Symphonia's default codecs.
///
/// [`CODEC_REGISTRY`]: static@CODEC_REGISTRY
pub codec_registry: &'static CodecRegistry, pub codec_registry: &'static CodecRegistry,
/// Registry of the muxers and container formats supported by the driver. /// 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. /// and DCA format support.
///
/// [`PROBE`]: static@PROBE
pub format_registry: &'static Probe, pub format_registry: &'static Probe,
/// Configuration for the inner streamcatcher instance. /// Configuration for the inner streamcatcher instance.
/// ///
@@ -73,8 +69,8 @@ pub struct Config {
impl Default for Config { impl Default for Config {
fn default() -> Self { fn default() -> Self {
Self { Self {
codec_registry: &CODEC_REGISTRY, codec_registry: get_codec_registry(),
format_registry: &PROBE, format_registry: get_probe(),
streamcatcher: ScConfig::default(), streamcatcher: ScConfig::default(),
} }
} }

View File

@@ -4,26 +4,33 @@ pub(crate) mod dca;
mod opus; mod opus;
mod raw; mod raw;
use std::sync::OnceLock;
pub use self::{dca::DcaReader, opus::OpusDecoder, raw::*}; pub use self::{dca::DcaReader, opus::OpusDecoder, raw::*};
use once_cell::sync::Lazy;
use symphonia::{ use symphonia::{
core::{codecs::CodecRegistry, probe::Probe}, core::{codecs::CodecRegistry, probe::Probe},
default::*, default::*,
}; };
/// Default Symphonia [`CodecRegistry`], including the (audiopus-backed) Opus codec. /// Default Symphonia [`CodecRegistry`], including the (audiopus-backed) Opus codec.
pub static CODEC_REGISTRY: Lazy<CodecRegistry> = Lazy::new(|| { pub fn get_codec_registry() -> &'static CodecRegistry {
let mut registry = CodecRegistry::new(); static CODEC_REGISTRY: OnceLock<CodecRegistry> = OnceLock::new();
register_enabled_codecs(&mut registry); CODEC_REGISTRY.get_or_init(|| {
registry.register_all::<OpusDecoder>(); let mut registry = CodecRegistry::new();
registry register_enabled_codecs(&mut registry);
}); registry.register_all::<OpusDecoder>();
registry
})
}
/// Default Symphonia Probe, including DCA format support. /// Default Symphonia Probe, including DCA format support.
pub static PROBE: Lazy<Probe> = Lazy::new(|| { pub fn get_probe() -> &'static Probe {
let mut probe = Probe::default(); static PROBE: OnceLock<Probe> = OnceLock::new();
probe.register_all::<DcaReader>(); PROBE.get_or_init(|| {
probe.register_all::<RawReader>(); let mut probe = Probe::default();
register_enabled_formats(&mut probe); probe.register_all::<DcaReader>();
probe probe.register_all::<RawReader>();
}); register_enabled_formats(&mut probe);
probe
})
}

View File

@@ -160,7 +160,7 @@ mod tests {
// finds the audio on a non-default track via `LiveInput::promote`. // finds the audio on a non-default track via `LiveInput::promote`.
let input = Input::from(File::new(FILE_VID_TARGET)); let input = Input::from(File::new(FILE_VID_TARGET));
input input
.make_playable_async(&CODEC_REGISTRY, &PROBE) .make_playable_async(get_codec_registry(), get_probe())
.await .await
.unwrap(); .unwrap();
} }

View File

@@ -49,8 +49,8 @@
//! [`OpusDecoder`]: codecs::OpusDecoder //! [`OpusDecoder`]: codecs::OpusDecoder
//! [`DcaReader`]: codecs::DcaReader //! [`DcaReader`]: codecs::DcaReader
//! [`RawReader`]: codecs::RawReader //! [`RawReader`]: codecs::RawReader
//! [format]: static@codecs::PROBE //! [format]: codecs::get_probe
//! [codec registries]: static@codecs::CODEC_REGISTRY //! [codec registries]: codecs::get_codec_registry
mod adapters; mod adapters;
mod audiostream; mod audiostream;
@@ -147,7 +147,7 @@ use tokio::runtime::Handle as TokioHandle;
/// // /// //
/// // We can access it on a live track using `TrackHandle::action()`. /// // We can access it on a live track using `TrackHandle::action()`.
/// in_memory_input = in_memory_input /// in_memory_input = in_memory_input
/// .make_playable_async(&CODEC_REGISTRY, &PROBE) /// .make_playable_async(get_codec_registry(), get_probe())
/// .await /// .await
/// .expect("WAV support is included, and this file is good!"); /// .expect("WAV support is included, and this file is good!");
/// ///

View File

@@ -13,7 +13,6 @@ use async_trait::async_trait;
use dashmap::DashMap; use dashmap::DashMap;
#[cfg(feature = "serenity")] #[cfg(feature = "serenity")]
use futures::channel::mpsc::UnboundedSender as Sender; use futures::channel::mpsc::UnboundedSender as Sender;
use once_cell::sync::OnceCell;
use parking_lot::RwLock as PRwLock; use parking_lot::RwLock as PRwLock;
#[cfg(feature = "serenity")] #[cfg(feature = "serenity")]
use serenity::{ use serenity::{
@@ -23,7 +22,7 @@ use serenity::{
voice::VoiceState, voice::VoiceState,
}, },
}; };
use std::sync::Arc; use std::sync::{Arc, OnceLock};
use tokio::sync::Mutex; use tokio::sync::Mutex;
#[cfg(feature = "serenity")] #[cfg(feature = "serenity")]
use tracing::debug; use tracing::debug;
@@ -44,7 +43,7 @@ struct ClientData {
/// [`Call`]: Call /// [`Call`]: Call
#[derive(Debug)] #[derive(Debug)]
pub struct Songbird { pub struct Songbird {
client_data: OnceCell<ClientData>, client_data: OnceLock<ClientData>,
calls: DashMap<GuildId, Arc<Mutex<Call>>>, calls: DashMap<GuildId, Arc<Mutex<Call>>>,
sharder: Sharder, sharder: Sharder,
config: PRwLock<Config>, config: PRwLock<Config>,
@@ -71,7 +70,7 @@ impl Songbird {
#[must_use] #[must_use]
pub fn serenity_from_config(config: Config) -> Arc<Self> { pub fn serenity_from_config(config: Config) -> Arc<Self> {
Arc::new(Self { Arc::new(Self {
client_data: OnceCell::new(), client_data: OnceLock::new(),
calls: DashMap::new(), calls: DashMap::new(),
sharder: Sharder::Serenity(SerenitySharder::default()), sharder: Sharder::Serenity(SerenitySharder::default()),
config: config.initialise_disposer().into(), config: config.initialise_disposer().into(),
@@ -110,7 +109,7 @@ impl Songbird {
U: Into<UserId>, U: Into<UserId>,
{ {
Self { Self {
client_data: OnceCell::with_value(ClientData { client_data: OnceLock::from(ClientData {
shard_count: sender_map.shard_count(), shard_count: sender_map.shard_count(),
user_id: user_id.into(), user_id: user_id.into(),
}), }),