Repository navigation
Expand file tree
/
Copy pathapause.exp
More file actions
executable file
·331 lines (271 loc) · 10.7 KB
/
Copy pathapause.exp
File metadata and controls
executable file
·331 lines (271 loc) · 10.7 KB
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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
#!/usr/bin/env expect
# If you're new to https://wiki.tcl-lang.org/page/Expect
#
# - Expect is "only" a Tcl extension and Tcl command.
# An "Expect script" is a somewhat misleading shorthand for "a Tcl
# script that happens to use Expect"
#
# - So, you can't understand this script (or any expect script) without
# some minimum Tcl knowledge. Especially: strings, quoting, lists and
# delayed evaluations.
#
# - Expect resources on the Internet are hit-and-miss. Don Libes' book
# "Exploring Expect" is great: buy the book or check whether your
# employer has an online subscription. That book has a really nice and
# short (single chapter) Tcl introduction too.
# Tcl resources on the Internet are much better than Expect resources.
#
# - The man pages are not good for learning but they are a very useful
# references: run `apt install tcl8*-doc` or equivalent to get Tcl man
# pages, then: `man [3tcl] expect`, `man [3tcl] after`, etc.
#
# - Use the interactive `rlwrap tclsh` to experiment.
#
# log level: 0 = initialization, warnings and errors only, 1 = normal, 2+ = debug
set log_level 1
# Set to 1 only when you're desperate: this randomly interleaves
# aplay's output with output from this script.
log_user 0
# aplay -vv is chatty: no need to wait for very long
set timeout 5
proc log {lvl msg} {
global log_level cmd_shortname
if {$lvl <= $log_level} {
puts "t=[rel_time_ms] ms: $cmd_shortname: $msg"
}
}
# Pop the first element of the list argument.
# Equivalent to "shift" in shell.
proc lshift {args} {
# "upvar" required to escape scope and change argument in place
upvar $args args_up
set first [lindex $args_up 0]
set args_up [lreplace $args_up 0 0]
return $first
}
# Random numbers between min and min+range
proc rand_min_range {min range} {
return [expr $min + int([expr rand() * $range])]
}
set cmd_shortname [lshift argv]
set repeat_count [lshift argv]
set rnd_min [lshift argv]
set rnd_range [lshift argv]
# Should really be 200 ms because of the round-trip between pressing
# "space" and aplay's acknowledgement + other various delays everywhere.
# Keep it that small for now for backwards compatibility.
if {$rnd_min < 20} {
puts "$argv0 ERROR: rnd_min=$rnd_min argument is lower than 20ms"
exit 1
}
# How many times we paused
set pauses_counter 0
# Logging needs this early. Will reset better later.
set start_time_ms [clock milliseconds]
proc rel_time_ms {} {
global start_time_ms
return [expr [clock milliseconds] - $start_time_ms]
}
proc press_space {} {
global last_space_time
log 1 "Pressing SPACE"
send " "
set last_space_time [rel_time_ms]
log 3 "last_space_time set to $last_space_time"
}
proc substract_time_since_last_space {duration} {
global last_space_time
set _delay [expr $duration - ([rel_time_ms] - $last_space_time)]
# Don't return negative values if we already passed the deadline.
# Don't return zero either to avoid interrupting ourselves (just in
# case Tcl thought it would be a good idea)
return [tcl::mathfunc::max 1 $_delay]
}
# aplay's VU-meter uses CRs to write over itself and avoid terminal scrolling.
# But when debugging we want to see everything.
proc cr_to_lf {arg} {
set _lf [regsub "\r" $arg "\n"]
return [string trim $_lf]
}
# Use all remaining arguments as the command to invoke. Example:
#
# arecord $cmd_opts -D $dev -r $rate -c $channel -f $fmt -vv -i $file_name ...
log 0 "$argv0 spawning: $argv"
set device [lindex $argv 2]
set command [lindex $argv 0]
# Determine direction based on the command
if {$command eq "aplay"} {
set direction "p" ; # Playback
} else {
set direction "c" ; # Capture
}
# parse the card number and device
if {![regexp {hw:(\d+),(\d+)} $device match card_number device_id]} {
log 0 "ERROR: Failed to parse hw string: $hw_string"
}
set pcm_status_file "/proc/asound/card${card_number}/pcm${device_id}${direction}/sub0/status"
if {![file exists $pcm_status_file]} {
log 0 "ERROR: PCM status file not found: $pcm_status_file"
exit 1
}
spawn {*}$argv
set start_time_ms [clock milliseconds]; # re-adjust
set last_space_time 0 ; # could not resist that name
# states: active, pause_requested, paused, active_requested
set state active_requested
set in_max_burst false
set volume_always_zero true
# Key Expect matching facts to keep in mind:
#
# 1. Expect never cares about newlines on its own. You must use `\r`
# and/or `\n` _everywhere_ you care about newlines.
#
# 2. When to use \r versus \n versus \r\n (CRLF) in Expect unfortunately
# requires some tty _and_ arecord VU-meter knowledge and is a bit too
# complicated to be summarized here.
#
# 3. When nothing matches, Expect keeps reading and keeps looking
# forward. As soon as something matches, Expect _ignores_ what did
# not match earlier. Except when using ^ which is the "start of
# input" anchor (NOT a "start of line" anchor)
#
# 4. Conversely, whatever is left AFTER a match will always be submitted
# for matching again: exactly like it has not arrived yet (otherwise it
# would be always racy).
expect {
# `man re_syntax` claims that Tcl regular expressions are compliant
# with the basic and extended POSIX ones while adding a 3rd,
# extended flavor. It's not clear which flavor `expect -re` uses
# but it's not the basic one.
# Use {} not "" to avoid quoting issues and backslash proliferation.
# When multiple patterns match, first pattern wins.
-nocase -re {error.*\r|PAUSE.*no[[:blank:]]*hw[[:blank:]]*support.*\r} {
set buffer_with_lf "[cr_to_lf $expect_out(buffer)]"
log 0 "ERROR: $buffer_with_lf"
exit 1
}
# Volume xx% or MAX line
#
# When not backpressured by a sleeping (=bad!) Expect process,
# aplay seems to update its VU-meter about once every 100ms.
-re {#[^\r\n]*\| (..*%|MAX)\r} {
# - $expect_out(0,string) = match
# - $expect_out(buffer) = everything before match + match
set buffer_with_lf "[cr_to_lf $expect_out(buffer)]"
# Always print the audio stream configuration preamble
if [regexp {PCM card} "$buffer_with_lf"] {
log 0 "$buffer_with_lf"
}
if [regexp {\| MAX} "$buffer_with_lf"] {
if { ! $in_max_burst } {
# We unfortunately can't upgrade this to an ERROR
# because of "wontfix" bugs like
# https://github.com/thesofproject/sof-test/pull/931
# https://github.com/thesofproject/linux/issues/5048
log 0 "WARNING: volume MAX! Bug or bad ALSA settings?"
log 0 "$buffer_with_lf"
set in_max_burst true
}
} else {
set in_max_burst false
}
if $volume_always_zero {
# This is not perfect because if Expect becomes very slow
# for some unknown reason, then there could be _multiple_
# volume lines in a single of these buffer iterations and then we
# could miss some non-zeros.
# This is very unlikely though so this is statistically good enough.
if {! [regexp {\| ( |0)0%} "$buffer_with_lf"]} {
set volume_always_zero false
}
}
switch $state {
active {
log 2 "Volume #... | __%:\n[cr_to_lf $expect_out(buffer)]"
exp_continue
}
pause_requested {
log 2 "Volume #... | __% left after requesting pause:\n[cr_to_lf $expect_out(buffer)]"
exp_continue
}
paused {
log 0 "ERROR: found VOLUME while paused!"
log 0 "$buffer_with_lf"
exit 1
}
active_requested {
# First volume line printed since unpaused; stream successfully started!
set state active
set _record_for [rand_min_range $rnd_min $rnd_range]
log 1 "($pauses_counter/$repeat_count) Found volume ### | __%, active for $_record_for ms"
set _delay [substract_time_since_last_space $_record_for]
# wait 50ms for the PCM status to be RUNNING before pausing
# this is to make sure that in the case of an xrun the application
# successfully recovers and restarts the stream.
set max_attempts 50
set attempt 0
while {$attempt < $max_attempts} {
set pcm_status [exec cat $pcm_status_file]
if {[regexp {state:\s*RUNNING} $pcm_status]} {
break
}
incr attempt
after 1
}
if {$attempt >= $max_attempts} {
log 0 "ERROR: timeout waiting for PCM to be in RUNNING state before pause"
log 0 "Current state: $pcm_status"
exit 1
}
after $_delay "press_space; set state pause_requested"
log 3 "last_space_time=$last_space_time; timer in $_delay"
# Debug matched string
log 2 "$buffer_with_lf"
exp_continue
}
default {
log 0 "ERROR: unexpected state=$state! Volume is:\n[cr_to_lf $expect_out(buffer)]"
exit 1
}
}
}
{=== PAUSE ===} {
if {$state != "pause_requested"} {
log 0 "ERROR: received == PAUSE == while in state $state!"
exit 1
}
set state paused
# Re-enable the MAX warning
set in_max_burst false
set _pausing_for [rand_min_range $rnd_min $rnd_range]
log 1 "($pauses_counter/$repeat_count) Found === PAUSE === , pausing for $_pausing_for ms"
set _delay [substract_time_since_last_space $_pausing_for]
after $_delay "press_space; set state active_requested"
log 3 "last_space_time=$last_space_time; timer in $_delay"
incr pauses_counter
if { $pauses_counter <= $repeat_count } {
exp_continue
}
# Normal exit of the "expect" command here
}
# This overlaps with the main volume case above but it's very useful logging when
# forgetting to pass a double -vv and timing out
-re {PCM card[^#]*} {
log 0 "Preamble:\n$expect_out(buffer)"
exp_continue
}
timeout {
log 0 "ERROR: $argv0 timed out. Did you use -vv?"
exit 1
}
eof {
log 0 "ERROR: $argv0: EOF."
log 0 "$expect_out(buffer)"
exit 1
}
}
if $volume_always_zero {
log 0 "WARNING: volume was always 00%!"
}
# TODO: collect exit status with explicit exp_close + exp_wait?
log 0 "SUCCESS: $argv0 $argv"