-
Notifications
You must be signed in to change notification settings - Fork 1
/
alsa_direct_status_test.rs
229 lines (191 loc) · 6.98 KB
/
alsa_direct_status_test.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
#[macro_use]
extern crate serde_derive;
extern crate docopt;
extern crate alsa;
extern crate alsa_sys;
extern crate time;
extern crate thread_priority;
extern crate libc;
mod realtime_priority;
use std::thread;
use std::time::Duration;
use std::process;
use docopt::Docopt;
use alsa::{Direction, ValueOr};
use alsa::pcm::{PCM, HwParams, Format, Access};
use alsa::direct::pcm::Status;
use alsa::direct::pcm::SyncPtrStatus;
use libc::timespec;
const USAGE: &str = "
alsa-direct-status-test
Usage:
alsa-audio-time [-p -c -D <device> -r <Hz> -s <frames> -o <periods> -f <Hz>]
alsa-audio-time (-h | --help)
Options:
-h --help Show this screen.
-p --playback Playback tstamps
-c --capture Capture tstamps.
-D --device=<device> Select ALSA device [default: hw:0,0].
-s --period-size=<frames> Period size in frames [default: 256].
-o --periods=<count> Periods [default: 4].
-r --sample-rate=<Hz> Recording sample rate [default: 48000].
-f --status-freq=<Hz> Status Frequency [default: 10].
";
const CHANNELS: u32 = 2;
#[derive(Debug, Deserialize)]
struct Args {
flag_playback: bool,
flag_capture: bool,
flag_device: String,
flag_period_size: u32,
flag_periods: u32,
flag_sample_rate: u32,
flag_status_freq: f64,
}
fn main() {
let args: Args = Docopt::new(USAGE)
.and_then(|d| d.deserialize())
.unwrap_or_else(|e| e.exit());
if !args.flag_capture && !args.flag_playback {
eprintln!("{}", USAGE);
eprintln!("Error: please enable capture, playback or both.");
process::exit(1);
}
if args.flag_capture {
eprintln!("Capture from: {}", args.flag_device);
}
if args.flag_playback {
eprintln!("Playback from: {}", args.flag_device);
}
let period_size = args.flag_period_size;
let periods = args.flag_periods;
eprintln!("Period size: {}", period_size);
eprintln!("Periods: {}", periods);
eprintln!("Sample rate: {}", args.flag_sample_rate);
let mut handle_p: Option<PCM> = None;
let mut handle_c: Option<PCM> = None;
let mut pcm_fd_p: Option<i32> = None;
let mut pcm_fd_c: Option<i32> = None;
let mut status_p: Option<Status> = None;
let mut status_c: Option<Status> = None;
let mut buffer_c = vec![0i16; (period_size * periods * CHANNELS) as usize];
let buffer_p = vec![0i16; (period_size * periods * CHANNELS) as usize];
if args.flag_playback {
let mut pcm = PCM::new(&args.flag_device, Direction::Playback, false).unwrap();
set_params(&mut pcm, args.flag_sample_rate, period_size, periods);
{
let hwp = pcm.hw_params_current().unwrap();
let start_threshold = hwp.get_buffer_size().unwrap() - hwp.get_period_size().unwrap();
let swp = pcm.sw_params_current().unwrap();
swp.set_start_threshold(start_threshold).unwrap();
pcm.sw_params(&swp).unwrap();
}
pcm_fd_p = Some(pcm_to_fd(&pcm).unwrap());
if cfg!(target_arch = "x86_64" ) {
status_p = Some(Status::new(&pcm).unwrap());
}
handle_p = Some(pcm);
}
if args.flag_capture {
let mut pcm = PCM::new(&args.flag_device, Direction::Capture, false).unwrap();
set_params(&mut pcm, args.flag_sample_rate, period_size, periods);
pcm_fd_c = Some(pcm_to_fd(&pcm).unwrap());
if cfg!(target_arch = "x86_64" ) {
status_c = Some(Status::new(&pcm).unwrap());
}
handle_c = Some(pcm);
}
let status_freq = args.flag_status_freq;
thread::spawn(move || {
thread::sleep(Duration::from_secs(1));
let sleep_duration = Duration::new(0, (1e9 / status_freq) as u32);
loop {
thread::sleep(sleep_duration);
if let Some(status) = status_c.as_ref() {
print_status(&status);
}
if let Some(pcm_fd) = pcm_fd_c {
print_sync_status(pcm_fd);
}
if let Some(status) = status_p.as_ref() {
print_status(&status);
}
if let Some(pcm_fd) = pcm_fd_p {
print_sync_status(pcm_fd);
}
};
});
realtime_priority::get_realtime_priority();
if let Some(pcm_c) = handle_c.as_ref() {
pcm_c.start().unwrap();
}
loop {
if let Some(pcm_c) = handle_c.as_ref() {
if let Err(e) = pcm_c.wait(None) {
eprintln!("Recovering from Capture wait error");
pcm_c.try_recover(e, false).unwrap();
pcm_c.start().unwrap();
}
let io = pcm_c.io_i16().unwrap();
if let Err(e) = io.readi(&mut buffer_c) {
eprintln!("Recovering from Capture error");
pcm_c.try_recover(e, false).unwrap();
pcm_c.start().unwrap();
}
}
if let Some(pcm_p) = handle_p.as_ref() {
let io = pcm_p.io_i16().unwrap();
if let Err(e) = io.writei(&buffer_p) {
eprintln!("Recovered from Playback error");
pcm_p.try_recover(e, false).unwrap();
}
}
}
}
fn set_params(pcm: &mut PCM, sample_rate: u32, period_size: u32, periods: u32) {
let hwp = HwParams::any(&pcm).unwrap();
hwp.set_channels(2).unwrap();
hwp.set_rate(sample_rate, ValueOr::Nearest).unwrap();
hwp.set_format(Format::s16()).unwrap();
hwp.set_access(Access::RWInterleaved).unwrap();
#[cfg(target_pointer_width = "32")]
hwp.set_period_size(period_size as i32, ValueOr::Nearest).unwrap();
#[cfg(target_pointer_width = "64")]
hwp.set_period_size(period_size as i64, ValueOr::Nearest).unwrap();
hwp.set_periods(periods, ValueOr::Nearest).unwrap();
pcm.hw_params(&hwp).unwrap();
let swp = pcm.sw_params_current().unwrap();
swp.set_tstamp_mode(true).unwrap();
// TODO: also set timestamp type
pcm.sw_params(&swp).unwrap();
}
fn print_sync_status(pcm_fd: i32) {
let status = unsafe {
SyncPtrStatus::sync_ptr(
pcm_fd,
false,
None,
None).unwrap()
};
eprint!("Sync Status: state: {:?} ", status.state());
eprintln!("htstamp: {:<18} ", timespec_f64(status.htstamp()));
}
fn print_status(status: &Status) {
eprint!("Status: state: {:?} ", status.state());
eprint!("htstamp: {:<18} ", timespec_f64(status.htstamp()));
eprintln!("audio_htstamp: {:<18} ", timespec_f64(status.audio_htstamp()));
}
fn timespec_f64(ts: timespec) -> f64 {
ts.tv_sec as f64 + (ts.tv_nsec as f64) / 1e9
}
fn pcm_to_fd(p: &PCM) -> alsa::Result<std::os::unix::io::RawFd> {
use std::mem;
use alsa::PollDescriptors;
use alsa::Error;
let mut fds: [libc::pollfd; 1] = unsafe { mem::zeroed() };
let c = (p as &PollDescriptors).fill(&mut fds)?;
if c != 1 {
return Err(Error::unsupported("snd_pcm_poll_descriptors returned wrong number of fds"))
}
Ok(fds[0].fd)
}