feature/share-libs
rs 98 lines 2.95 KB
Raw
1 use log::{debug, error, info};
2 use record::record_instrument::AudioDevice;
3 use rodio::{
4 cpal::{default_host, traits::HostTrait},
5 Device, DeviceTrait,
6 };
7 use std::{fs::create_dir_all, path::PathBuf};
8
9 pub mod command;
10 pub mod players;
11 pub mod record;
12 pub mod rest;
13 pub mod models;
14
15 #[cfg(debug_assertions)]
16 const HOME_DIR: &str = ".sfai-dev";
17 #[cfg(not(debug_assertions))]
18 const HOME_DIR: &str = ".sfai";
19
20 const AUDIO_DIR: &str = "audio";
21
22 // Get ~/.sfai directory
23 pub fn sfai_home_dir_path() -> Option<PathBuf> {
24 match home::home_dir() {
25 Some(path) => {
26 info!("Home directory: {}", path.to_str().unwrap());
27 let home_dir_path = path.join(HOME_DIR);
28 if home_dir_path.exists() && home_dir_path.is_file() {
29 return Some(home_dir_path);
30 }
31 // CREATE DIRECTORY
32 //create_dir_all(path.join(".smb"))?;
33 let _ = create_dir_all(path.join(HOME_DIR));
34 Some(home_dir_path)
35 }
36 None => {
37 error!("Failed to get home directory. So strange.");
38 None
39 }
40 }
41 }
42
43 // Create audio directory if it doesn't exist
44 pub fn audio_dir_path() -> Option<PathBuf> {
45 if let Some(home_dir_path) = sfai_home_dir_path() {
46 let audio_dir_path = home_dir_path.join(AUDIO_DIR);
47 if audio_dir_path.exists() && audio_dir_path.is_file() {
48 return Some(audio_dir_path);
49 }
50 // CREATE DIRECTORY
51 let _ = create_dir_all(home_dir_path.join(AUDIO_DIR));
52 Some(audio_dir_path)
53 } else {
54 None
55 }
56 }
57
58 // Get the soundcard device or the default device if fallback is true.
59 pub fn get_soundcard(
60 device_type: AudioDevice,
61 fallback_to_default: bool,
62 ) -> Result<Device, anyhow::Error> {
63 let host = default_host();
64 // Get list of all input devices including soundcards, microphones, etc.
65 let devices = match device_type {
66 AudioDevice::Input => host.input_devices()?,
67 AudioDevice::Output => host.output_devices()?,
68 };
69 // Select output device scarlett 2i2
70 let device = match devices.into_iter().find(|x| match x.name() {
71 Ok(n) => {
72 info!("{} name: {}", device_type, n);
73 n.contains("Scarlett 2i2")
74 }
75 Err(e) => {
76 error!("Failed to get device name: {}", e);
77 false
78 }
79 }) {
80 Some(d) => d,
81 None => {
82 if fallback_to_default {
83 let devices = match device_type {
84 AudioDevice::Input => host.default_input_device(),
85 AudioDevice::Output => host.default_output_device(),
86 };
87
88 if let Some(device) = devices {
89 debug!("Fallback to default {}.", device_type);
90 return Ok(device);
91 }
92 }
93 let message = format!("Failed to find {}.", device_type);
94 return Err(anyhow::Error::msg(message));
95 }
96 };
97 Ok(device)
98 }