aboutsummaryrefslogtreecommitdiff
path: root/sonics/lagdetect.udo
blob: 60cc79dee5763900f41a3e1e8f0220c0d788a91b (plain)
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
#ifndef UDO_LAGDETECT
#define UDO_LAGDETECT ##
/*
	Processing lag detection
	Slim excerpt for Partial Emergence

	This file is part of the SONICS UDO collection by Richard Knight 2022
		License: GPL-2.0-or-later
		http://1bpm.net
*/

#define LAG_DFLT_TTHRESH #0.05#


/*
	Detect when the CPU cannot keep up with proessing: when the realtime clock differs from Csound's clock by a specified threshold time.
	The trigger klagging is output periodically every iautotimethreshold*2 seconds rather than continuously

	klagging, ktimesincelastlag lagdetect [iautotimethreshold=LAG_DFLT_TTHRESH]

	klagging			trigger indicating lag has been detected in this k-cycle
	ktimesincelastlag	time in seconds sine the last lag detected
	iautotimethreshold	if realtime clock and Csound clock differ more than this number of seconds, lag is assumed
*/
opcode lagdetect, kk, j
	iautotimethreshold xin
	iautotimethreshold = (iautotimethreshold == -1) ? $LAG_DFLT_TTHRESH : iautotimethreshold
	kstartrt init rtclock:i()
	kclockrt rtclock
	kstarts init times:i()
	kclocks times    
	klag = abs:k((kclocks - kstarts) - (kclockrt - kstartrt))

	klagging = 0
	; if time difference is above threshold and last adjustment is double threshold, reduce parameters and reset times
	if (klag > iautotimethreshold && kclockrt - kstartrt > iautotimethreshold * 2) then
		kstartrt = kclockrt
		kstarts = kclocks
		klagging = 1		
	endif
	xout klagging, kclocks - kstarts
endop


/*
	Detect when the CPU cannot keep up with proessing: when the realtime clock differs from Csound's clock by a specified threshold time
	The trigger klagging is output periodically every iautotimethreshold*2 seconds rather than continuously

	klagging lagdetect [iautotimethreshold=LAG_DFLT_TTHRESH]

	klagging	trigger indicating lag has been detected in this k-cycle
	iautotimethreshold	if realtime clock and Csound clock differ more than this number of seconds, lag is assumed
*/
opcode lagdetect, k, j
	iautotimethreshold xin
	klagging, ktimesincelag lagdetect iautotimethreshold
	xout klagging
endop

#end