Skip to content

Commit

Permalink
code cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
kamiyaa committed Nov 23, 2022
1 parent a05f449 commit a0a044c
Show file tree
Hide file tree
Showing 35 changed files with 221 additions and 190 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ whenever mocp is playing music, other audio/video apps stop working and vice ver
```
~ $ dizi-server # starts server
~ $ RUST_LOG=debug dizi-server # starts server with debug messages enabled
~ $ dizi # starts server if not already started
~ $ dizi # starts server if not already started, then starts frontend
```

## Configuration
Expand Down
3 changes: 0 additions & 3 deletions config/server.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,6 @@ socket = "~/dizi-server-socket"
# Where to save playlist on exit
playlist = "~/dizi_playlist.m3u"

# not implemented
poll_rate = 200

# supports alsa, jack
audio_system = "alsa"

Expand Down
8 changes: 7 additions & 1 deletion lib/dizi_lib/src/error/error_kind.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,12 @@ pub enum DiziErrorKind {
SendError,
ReceiveError,


#[cfg(feature = "symphonia-backend")]
SymphoniaError(symphonia::core::errors::Error),

CpalBuildStreamError(cpal::BuildStreamError),
CpalPlayStreamError(cpal::PlayStreamError),
CpalPauseStreamError(cpal::PauseStreamError),

NoDevice,
UnrecognizedFormat,
Expand Down Expand Up @@ -111,3 +111,9 @@ impl From<cpal::PlayStreamError> for DiziErrorKind {
Self::CpalPlayStreamError(e)
}
}

impl From<cpal::PauseStreamError> for DiziErrorKind {
fn from(e: cpal::PauseStreamError) -> Self {
Self::CpalPauseStreamError(e)
}
}
10 changes: 10 additions & 0 deletions lib/dizi_lib/src/error/error_type.rs
Original file line number Diff line number Diff line change
Expand Up @@ -158,3 +158,13 @@ impl From<cpal::PlayStreamError> for DiziError {
}
}
}

impl From<cpal::PauseStreamError> for DiziError {
fn from(err: cpal::PauseStreamError) -> Self {
let _cause = err.to_string();
Self {
_kind: DiziErrorKind::from(err),
_cause,
}
}
}
16 changes: 13 additions & 3 deletions lib/dizi_lib/src/player.rs
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,11 @@ impl PlayerState {
Ok(s) => Ok(s),
Err(e) => Err(DiziError::new(
DiziErrorKind::InvalidParameters,
format!("Failed to process query '{}', Reason: '{}'", query, e.to_string()),
format!(
"Failed to process query '{}', Reason: '{}'",
query,
e.to_string()
),
)),
}
}
Expand Down Expand Up @@ -177,10 +181,16 @@ impl PlayerState {
song.file_path().to_string_lossy().to_string(),
);
for (tag, value) in song.music_metadata().standard_tags.iter() {
vars.insert(format!("song.tag.{}", tag.to_lowercase()), value.to_string());
vars.insert(
format!("song.tag.{}", tag.to_lowercase()),
value.to_string(),
);
}
if let Some(total_duration) = song.audio_metadata().total_duration.as_ref() {
vars.insert("song.total_duration".to_string(), total_duration.as_secs().to_string());
vars.insert(
"song.total_duration".to_string(),
total_duration.as_secs().to_string(),
);
}
}
}
Expand Down
61 changes: 46 additions & 15 deletions lib/dizi_lib/src/response/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,31 +10,62 @@ use crate::song::Song;
pub enum ServerBroadcastEvent {
// server is shutting down
ServerQuit,
ServerError { msg: String },
ServerQuery { query: String },
ServerQueryAll { query_items: HashMap<String, String> },
ServerError {
msg: String,
},
ServerQuery {
query: String,
},
ServerQueryAll {
query_items: HashMap<String, String>,
},

// player status updates
PlayerState { state: PlayerState },
PlayerState {
state: PlayerState,
},

PlayerFilePlay { song: Song },
PlayerFilePlay {
song: Song,
},

PlayerPause,
PlayerResume,
PlayerStop,

PlayerRepeat { on: bool },
PlayerShuffle { on: bool },
PlayerNext { on: bool },
PlayerRepeat {
on: bool,
},
PlayerShuffle {
on: bool,
},
PlayerNext {
on: bool,
},

PlayerVolumeUpdate { volume: usize },
PlayerProgressUpdate { elapsed: time::Duration },
PlayerVolumeUpdate {
volume: usize,
},
PlayerProgressUpdate {
elapsed: time::Duration,
},

// playlist
PlaylistOpen { state: PlayerState },
PlaylistPlay { index: usize },
PlaylistAppend { songs: Vec<Song> },
PlaylistRemove { index: usize },
PlaylistSwapMove { index1: usize, index2: usize },
PlaylistOpen {
state: PlayerState,
},
PlaylistPlay {
index: usize,
},
PlaylistAppend {
songs: Vec<Song>,
},
PlaylistRemove {
index: usize,
},
PlaylistSwapMove {
index1: usize,
index2: usize,
},
PlaylistClear,
}
22 changes: 14 additions & 8 deletions lib/dizi_lib/src/song.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::time;
#[cfg(not(feature = "symphonia-backend"))]
use std::fs::File;
#[cfg(not(feature = "symphonia-backend"))]
use std::io::BufReader;
use std::path::{Path, PathBuf};
use std::time;

#[cfg(feature = "rodio-backend")]
use rodio::decoder::Decoder;
Expand Down Expand Up @@ -96,8 +96,7 @@ impl Song {
// Create the media source stream.
let mss = MediaSourceStream::new(Box::new(src), Default::default());

let probed = symphonia::default::get_probe()
.format(&hint, mss, &fmt_opts, &meta_opts)?;
let probed = symphonia::default::get_probe().format(&hint, mss, &fmt_opts, &meta_opts)?;

// Get the instantiated format reader.
let mut format = probed.format;
Expand All @@ -109,7 +108,9 @@ impl Song {
.map(|track| AudioMetadata::from(&track.codec_params))
.unwrap_or_else(|| AudioMetadata::default());

let music_metadata = format.metadata().skip_to_latest()
let music_metadata = format
.metadata()
.skip_to_latest()
.map(|metadata| MusicMetadata::from(metadata))
.unwrap_or_else(|| MusicMetadata::default());

Expand Down Expand Up @@ -207,11 +208,16 @@ pub struct MusicMetadata {
#[cfg(feature = "symphonia-backend")]
impl std::convert::From<&MetadataRevision> for MusicMetadata {
fn from(metadata: &MetadataRevision) -> Self {
let standard_tags: HashMap<String, String> = metadata.tags()
let standard_tags: HashMap<String, String> = metadata
.tags()
.iter()
.filter_map(|tag| tag.std_key.map(|std_key| (format!("{:?}", std_key), tag.value.to_string())))
.filter_map(|tag| {
tag.std_key
.map(|std_key| (format!("{:?}", std_key), tag.value.to_string()))
})
.collect();
let tags: HashMap<String, String> = metadata.tags()
let tags: HashMap<String, String> = metadata
.tags()
.iter()
.filter(|tag| tag.std_key.is_none())
.map(|tag| (tag.key.to_owned(), tag.value.to_string()))
Expand Down
2 changes: 1 addition & 1 deletion src/client/commands/goto.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ fn _playlist_goto_playing(context: &mut AppContext) -> DiziResult {
.playlist()
.iter()
.enumerate()
.find(|(i, song)| song.file_path() == file_path)
.find(|(_, song)| song.file_path() == file_path)
{
set_playlist_index(context, index);
}
Expand Down
6 changes: 3 additions & 3 deletions src/client/config/option/sort_type.rs
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ fn size_sort(file1: &JoshutoDirEntry, file2: &JoshutoDirEntry) -> cmp::Ordering
fn ext_sort(file1: &JoshutoDirEntry, file2: &JoshutoDirEntry) -> cmp::Ordering {
let f1_ext = file1.get_ext();
let f2_ext = file2.get_ext();
alphanumeric_sort::compare_str(&f1_ext, &f2_ext)
alphanumeric_sort::compare_str(f1_ext, f2_ext)
}

fn lexical_sort(
Expand All @@ -151,10 +151,10 @@ fn natural_sort(
let f1_name = f1.file_name();
let f2_name = f2.file_name();
if sort_option.case_sensitive {
alphanumeric_sort::compare_str(&f1_name, &f2_name)
alphanumeric_sort::compare_str(f1_name, f2_name)
} else {
let f1_name = f1_name.to_lowercase();
let f2_name = f2_name.to_lowercase();
alphanumeric_sort::compare_str(&f1_name, &f2_name)
alphanumeric_sort::compare_str(f1_name, f2_name)
}
}
3 changes: 1 addition & 2 deletions src/client/context/app_context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,7 @@ impl AppContext {
}

pub fn flush_stream(&mut self) -> io::Result<()> {
utils::flush(&mut self.stream)?;
Ok(())
utils::flush(&mut self.stream)
}

// event related
Expand Down
2 changes: 0 additions & 2 deletions src/client/util/format.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
use std::time;

pub fn file_size_to_string(file_size: u64) -> String {
const FILE_UNITS: [&str; 6] = ["B", "K", "M", "G", "T", "E"];
const CONV_RATE: f64 = 1024.0;
Expand Down
1 change: 0 additions & 1 deletion src/server/audio/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,3 @@ pub mod request;
pub mod rodio;
#[cfg(feature = "symphonia-backend")]
pub mod symphonia;
pub mod traits;
2 changes: 1 addition & 1 deletion src/server/audio/rodio/player.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,13 @@ use dizi_lib::song::Song;
use crate::audio::device::get_default_host;
use crate::audio::request::PlayerRequest;
use crate::audio::rodio::stream::PlayerStream;
use crate::audio::traits::AudioPlayer;
use crate::config;
use crate::context::PlaylistContext;
use crate::events::ServerEventSender;
use crate::playlist::playlist_directory::PlaylistDirectory;
use crate::playlist::playlist_file::PlaylistFile;
use crate::playlist::traits::{OrderedPlaylist, ShufflePlaylist};
use crate::traits::AudioPlayer;
use crate::util::mimetype::{get_mimetype, is_mimetype_audio, is_mimetype_video};

pub struct RodioPlayer {
Expand Down
10 changes: 4 additions & 6 deletions src/server/audio/symphonia/decode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use symphonia::core::formats::{FormatReader, Packet};
use cpal::traits::{DeviceTrait, StreamTrait};
use cpal::{Stream, StreamConfig};

use dizi_lib::error::{DiziError, DiziErrorKind, DiziResult};
use dizi_lib::error::{DiziError, DiziResult};
use symphonia::core::units::TimeBase;

use crate::audio::request::PlayerRequest;
Expand Down Expand Up @@ -90,7 +90,7 @@ impl PacketDecoder {
SampleBuffer::new(decoded.frames() as u64, spec);
samples.copy_interleaved_ref(decoded);

let sample_data: Vec<T> = samples.samples().iter().map(|s| *s).collect();
let sample_data: Vec<T> = samples.samples().to_vec();
Ok(sample_data)
} else {
Ok(vec![])
Expand Down Expand Up @@ -215,10 +215,8 @@ where
if let Some(stream_tx) = stream_tx.as_ref() {
let _ = stream_tx.send(StreamEvent::Progress(new_duration));
}
{
let mut duration = playback_duration.write().unwrap();
*duration = new_duration.as_secs();
}
let mut duration = playback_duration.write().unwrap();
*duration = new_duration.as_secs();
}
},
err_fn,
Expand Down
27 changes: 12 additions & 15 deletions src/server/audio/symphonia/player.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,12 @@ use log::{debug, log_enabled, Level};
use crate::audio::device::get_default_host;
use crate::audio::request::PlayerRequest;
use crate::audio::symphonia::stream::PlayerStream;
use crate::audio::traits::AudioPlayer;
use crate::config;
use crate::context::PlaylistContext;
use crate::events::ServerEventSender;
use crate::playlist::playlist_directory::PlaylistDirectory;
use crate::playlist::playlist_file::PlaylistFile;
use crate::playlist::traits::{OrderedPlaylist, ShufflePlaylist};
use crate::traits::{AudioPlayer, OrderedPlaylist, ShufflePlaylist};
use crate::util::mimetype::{get_mimetype, is_mimetype_audio, is_mimetype_video};

#[derive(Debug)]
Expand Down Expand Up @@ -51,10 +50,14 @@ impl SymphoniaPlayer {
let server_config = config_t.server_ref();
let player_config = server_config.player_ref();

let mut playlist_context = PlaylistContext::default();
playlist_context.file_playlist =
PlaylistFile::from_file(&PathBuf::from("/"), server_config.playlist_ref())
.unwrap_or_else(|_| PlaylistFile::new(Vec::new()));
let playlist_context = PlaylistContext {
file_playlist: PlaylistFile::from_file(
&PathBuf::from("/"),
server_config.playlist_ref(),
)
.unwrap_or_else(|_| PlaylistFile::new(Vec::new())),
..Default::default()
};

let state = PlayerState {
next: player_config.next,
Expand Down Expand Up @@ -89,7 +92,7 @@ impl SymphoniaPlayer {
song: song.clone(),
volume: self.get_volume() as f32 / 100.0,
})?;
let _resp = self.player_stream_res().recv()??;
self.player_stream_res().recv()??;

self.state.status = PlayerStatus::Playing;
self.state.song = Some(song.clone());
Expand Down Expand Up @@ -125,8 +128,7 @@ impl AudioPlayer for SymphoniaPlayer {
.map(|(i, _)| i);

playlist.set_playlist_index(index);
playlist.set_shuffle(shuffle_enabled);
if playlist.shuffle_enabled() {
if shuffle_enabled {
playlist.shuffle();
}
if let Some(entry) = playlist.current_entry_details() {
Expand All @@ -147,8 +149,7 @@ impl AudioPlayer for SymphoniaPlayer {
// unshuffle the playlist before choosing setting the new index
playlist.unshuffle();
playlist.set_playlist_index(Some(index));
playlist.set_shuffle(shuffle_enabled);
if playlist.shuffle_enabled() {
if shuffle_enabled {
playlist.shuffle();
}
if let Some(entry) = playlist.current_entry_details() {
Expand Down Expand Up @@ -258,10 +259,6 @@ impl AudioPlayer for SymphoniaPlayer {
}
fn set_shuffle(&mut self, shuffle: bool) {
self.state.shuffle = shuffle;
self.playlist_mut().file_playlist_mut().set_shuffle(shuffle);
self.playlist_mut()
.directory_playlist_mut()
.set_shuffle(shuffle);
if self.shuffle_enabled() {
self.playlist_mut().file_playlist_mut().shuffle();
self.playlist_mut().directory_playlist_mut().shuffle();
Expand Down
Loading

0 comments on commit a0a044c

Please sign in to comment.