-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbacklightadapt
executable file
·730 lines (640 loc) · 22.6 KB
/
backlightadapt
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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
#!/usr/bin/env sh
#
# Copyright (c) 2020 Nikita Zlobin <[email protected]>
#
# backlight-adaptive is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# backlight-adaptive is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
startup_args="$*"
progname=backlight-adaptive
backends_all=internal,light,xbacklight
# Default parameters
rate=30
skip=0
onetime=false
log_level=info
log_color=false
max_color=35
maxbright=100
minbright=1
smooth=0
threshold=1
acpi_dev=
backends="${backends_all}"
backend_args=
watch_conf=true
ctl_action=
# first video input for default
for video_dev in /dev/video* ; do break; done
# Helpers
print() { printf '%s\n' "$1"; }
show_help() {
cat << help_end
Usage: $(basename $0) [options] -- [backend options]
Adapt backlight to ambient light using web camera as light sensor.
Commands:
-t, --toggle Stop runing instance or run as new
-1, --onetime Make single adjustment and quit
--calibrate Calibrate backlight to luminance ratio
-p, --pretend Print running parameters without actual run
-h, --help Show this help
Capture options:
-v, --video-dev DEVICE Video device used as sensor, e.g. /dev/video0
-C, --color-max INTEGER Color value for full backlight level (0..255)
-S, --skip INTEGER Frames number to skip at capture start
-r, --rate FLOAT Frame rate (frames per second)
Backlight options:
-M, --bl-max FLOAT Maximum backlight level (%)
-m, --bl-min FLOAT Minimum backlight level (%)
-s, --smooth INT,INT... Light filters description, 0 to disable (see README)
-T, --threshold FLOAT Minimum difference for repeats (%)
Backend options:
-a, --acpi-dev NAME ACPI device to be controlled
-b, --backends STR,STR... Comma-separated list of backlight control backends
-B, --list-backends List available backends
Configuration options:
-w, --watchconf BOOLEAN Auto-restart when configuration file is changed
-u, --update-conf Update configuration with command line options and new options
Log options:
-l, --log STRING Log verbosity. One of: error, warning, info, debug
-c, --color BOOLEAN Colorize output
help_end
}
# args: value
isnum() {
for n in "$@"; do case ${n#[+-]} in
''|*[!0-9.]* | '.' | *.*.*) return 1
esac; done
}
awk_expr() { awk 'BEGIN { printf ("%.17g", '"$1"') }'; }
awk_cmd() { awk "BEGIN { $* }"; }
# args: name, value
set_num() {
if isnum "$2"; then
eval "$1='$2'"
fi
}
# args: name, value
set_bool() {
case "$2" in true | false )
eval "$1='$2'"
esac
}
# args: name, value
set_int_list() {
case "$2" in [0-9,]* )
eval "$1='$2'"
esac
}
# args: start, names
set_enum() {
i="$1"; shift
for name in "$@"; do
eval "$name=$i"
i=$(( i+1 ))
done; unset i name
}
# args: cmdname
cmd_avail() {
type "$1" >/dev/null 2>&1
return $?
}
# args: PID
savepid() {
print "$1" > "$pidfile"
}
# signal handlers: no args, require initialized procpid
quit() {
state=int
kill -- -$procpid
}
restart() {
state=restart
kill -- -$procpid
}
input_max() {
state=input_max
kill -- -$procpid
}
# args: option_name,...
print_options() {
while [ $# -gt 0 ]; do
eval "print $1=\${$1}"
shift
done
}
save_config() {
print_options watch_conf smooth threshold rate log_level log_color max_color maxbright minbright video_dev acpi_dev backends backend_args | sort > "${config_file}"
}
# color helpers
color_init() {
if "$log_color" && ! cmd_avail tput; then
log_color=false
fi
if ! "$log_color"; then
tput() { :; }
fi
set_enum 0 black red green yellow blue pink cyan gray
bold="$(tput bold)"
sgr0="$(tput sgr0)"
}
# args: fgcolor, [bgcolor]
col() {
if isnum "$1"; then
tput setaf "$1"
else
eval "tput setaf \${$1}"
fi
if [ $# -gt 2 ]; then
if isnum "$2"; then
tput setab "$2"
else
eval "tput setab \${$2}"
fi
fi
}
# loging features
msg_init() {
set_enum 0 error warning info debug
eval "log_level_n=\${$log_level}"
}
# args: color, text
msg_color() {
local c="$1"
shift
print "$(col $c)$*$sgr0"
}
# args: text
msg_debug() { [ $log_level_n -ge $debug ] && print "$*${sgr0}" ||:; }
msg_info() { [ $log_level_n -ge $info ] && msg_color blue "$*" ||:; }
msg_warning() { [ $log_level_n -ge $warning ] && msg_color yellow "$*" ||:; }
msg_error() { [ $log_level_n -ge $error ] && msg_color red "$*" ||:; }
fatal() {
msg_error "$@"
exit 1
}
# args: percents
# req: bl_hwmax
percent_to_raw() { awk_expr "$bl_hwmax * $1 / 100"; }
calibrate() {
msg_info "Recalibration..."
frames=$( awk_expr "($rate <= 1 ? 1 : int($rate)) + 1" )
bl_cur=$( bl_get )
input=$( ffmpeg -v quiet -f v4l2 -s 1x1 -i "${video_dev}" -frames $frames -vcodec rawvideo -f rawvideo -vf scale=1:1:flags=area+accurate_rnd,format=gray - | tail -c1 | od -An -w1 -tu1 | tr -d ' ' )
max_color=$( awk_expr "int( $input / $bl_cur * $maxbright )" )
if [ $max_color -gt 255 ]; then
$max_color=255
fi
msg_info "New light maximum: $max_color / 255"
msg_info "New backlight max: $maxbright%"
save_config
}
##### START #####
# Find config file or place to save it
for config_dir in "${XDG_CONFIG_PATH}" "$HOME/.config" '/etc' ; do
{ [ -f "${config_dir}/${progname}" ] || {
[ -d "${config_dir}" ] && \
[ -w "${config_dir}" ]
} } && break ||:
config_dir=
done
# Read existing config or create new
if [ -n "${config_dir}" ]
then
config_file="${config_dir}/${progname}"
if [ -f "${config_file}" ]
then
{ while IFS='=' read name v; do
case $name in
watch_conf ) set_bool watch_conf "$v"; continue;;
acpi_dev ) acpi_dev="$v"; continue;;
video_dev ) video_dev="$v"; continue;;
backend_args) backend_args="$v"; continue;;
backends ) backends="$v"; continue;;
rate ) set_num rate "$v"; continue;;
skip ) set_num skip "$v"; continue;;
fade_frames |\
smooth ) set_int_list smooth "$v"; continue;;
threshold ) set_num threshold "$v"; continue;;
log_level ) log_level="$v"; continue;;
log_color ) set_bool log_color "$v"; continue;;
maxbright ) set_num maxbright "$v"; continue;;
minbright ) set_num minbright "$v"; continue;;
max_color ) set_num max_color "$v"; continue;;
* )
print "Unknown config option '${name}'"
continue;;
esac
done; } < "$HOME/.config/${progname}"
elif touch "${config_file}"; then
save_config
else
unset config_file
fi
fi
# Arguments loading
while [ $# -gt 0 ]; do
case "$1" in
'-r' | '--rate' ) set_num rate "$2"; shift ;;
'-S' | '--skip' ) set_num skip "$2"; shift ;;
'-1' | '--onetime' ) onetime=true ;;
'-l' | '--log' ) log_level="$2"; shift ;;
'-c' | '--color' ) set_bool log_color "$2"; shift ;;
'-M' | '--bl-max' ) set_num maxbright "$2"; shift ;;
'-m' | '--bl-min' ) set_num minbright "$2"; shift ;;
'-C' | '--max-color' ) set_num max_color "$2"; shift ;;
'--calibrate' ) ctl_action=cal ;;
'-s' | '--smooth' ) set_int_list smooth "$2"; shift ;;
'-T' | '--threshold' ) set_int threshold "$2"; shift ;;
'-a' | '--acpi-dev' ) acpi_dev="$2"; shift ;;
'-v' | '--video-dev' ) video_dev="$2"; shift ;;
'-b' | '--backends' ) backends="$2"; shift ;;
'-B' | '--list-backends' ) print "${backends_all}"; exit ;;
'-t' | '--toggle' ) ctl_action=toggle;;
'-w' | '--watchconf' ) set_bool watch_conf "$2"; shift ;;
'-u' | '--update-conf' ) save_config ;;
'-p' | '--pretend' ) ctl_action=pretend ;;
'-h' | '--help' ) show_help; exit ;;
'--' ) backend_args="$*"; break ;;
* ) echo "Invalid option '$1'" ;;
esac
shift
done
color_init
msg_init
msg_info "Config file: ${bold}$(col green)${config_file}"
# Depepdency check
# core depepdencies
msg_info 'Checking dependencies'
for dep in tr ffmpeg awk v4l2-ctl cat tail fuser; do
if ! cmd_avail "$dep"; then
msg_error "${dep} executable required but not found"
abort=1
fi
done
# binary stream printer
for hextool in hexdump od; do
if cmd_avail "$hextool"; then
break
fi
hextool=
done
case "$hextool" in
hexdump )
byteorder_test='hexdump -x'
hexprinter="hexdump -v -e '1/2 \"%u\\n\"'"
;;
od )
byteorder_test='od -x'
hexprinter='od -v -An -w2 -tu2'
;;
* )
abort=1
msg_error 'Either hexdump or od are required'
;;
esac
if [ "$abort" ]; then
exit 1
fi
msg_info "Found hex printer: ${bold}$(col green)${hextool}"
msg_debug "hexprinter: ${hexprinter}"
msg_debug "byteorder_test: ${byteorder_test}"
# Config watch (optional)
if $watch_conf && ! cmd_avail inotifywait; then
watch_conf=false
msg_warning 'Command "inotifywait" is not found. Configuration watch will not work.'
fi
# Choose backlight control tool
msg_info 'Searching usable backend'
if [ ! "${backends}" ]; then
fatal 'Backends are not set'
fi
for backend in $( print "$backends" | tr ',' ' ' ) ; do
msg_info "Checking backend ${bold}$(col green)$backend"
bl_max=${maxbright}
bl_min=${minbright}
case "$backend" in
light )
type ${backend} >/dev/null 2>&1 || continue
bl_get() {
light -G
}
bl_sh='sh'
bl_fmt="light -S %f ${backend_args}\n"
break
;;
xbacklight )
type ${backend} >/dev/null 2>&1 || continue
bl_get() {
xbacklight -get
}
bl_sh='sh'
bl_fmt="xbacklight -set %f ${backend_args}\n"
break
;;
internal )
acpi_dir='/sys/class/backlight'
# ACPI dir exists and is not empty
if ! [ -d "${acpi_dir}" ] ; then
msg_error 'No ACPI support found'
break
fi
# Use first entry if acpi_dev not set
if [ "${acpi_dev}" ] && { [ -d "${acpi_dir}/${acpi_dev}" ] || ! msg_warning "ACPI device ${acpi_dev} not found"; }; then
acpi_dir="${acpi_dir}/${acpi_dev}"
else
for acpi_dir in "${acpi_dir}"/* ; do break; done
if ! { [ -d "${acpi_dir}" ] && [ -f "${acpi_dir}/brightness" ]; }; then
msg_error 'No ACPI backlight devices found'
break
fi
fi
ctl_file="${acpi_dir}/brightness"
if ! [ -w "$ctl_file" ]; then
fatal "Can't write to '$ctl_file'"
fi
# Translate brightness limits to raw backlight range
read bl_hwmax < "${acpi_dir}/max_brightness"
bl_max=$( percent_to_raw "$maxbright" )
bl_min=$( percent_to_raw "$minbright" )
bl_get() {
awk_cmd 'getline v < "'"${ctl_file}"'"; printf "%f", v * 100 / '"${bl_hwmax}"
}
bl_sh="cat > '${ctl_file}'"
bl_fmt='%u\n'
break
;;
esac
backend=
done
if [ ! "${backend}" ]; then
fatal 'No working backends found'
fi
msg_info "Using backend ${bold}$(col green)${backend}"
msg_debug "bl_sh : $bl_sh"
msg_debug "bl_fmt : $bl_fmt"
msg_debug "bl_max : $bl_max"
msg_debug "bl_min : $bl_min"
# onetime tuning
if $onetime; then
msg_info 'One-time mode'
fi
if [ "$smooth" != 0 ] && [ "$bl_min" = 0 ]; then
msg_warning "Minimum backlight can't be zero when fade is enabled. Set to 1 (of max $bl_max)"
bl_min=1
fi
# Setup temporary dir
for path in '/var/run' "${XDG_RUNTIME_DIR}" '/tmp' "$HOME/.cache"; do
# Check base path
[ "${path}" ] && [ -d "${path}" ] && [ -w "${path}" ] || continue
tmpdir="${path}/${progname}"
pidfile="$tmpdir/pid"
break
done
# no place for tmpdir
if [ ! "${tmpdir}" ]; then
fatal "Can't find place for temporary directory"
fi
msg_info "Temporary directory: ${bold}$(col green)${tmpdir}"
# Cancel if pretending
if [ "x$ctl_action" = "xpretend" ]; then
exit
fi
# Create tmpdir if doesn't exist
if [ ! -e "${tmpdir}" ]; then
mkdir -p "${tmpdir}"
elif ! { [ -d "${path}" ] && [ -w "${path}" ]; }; then
fatal "$tmpdir: Not a directory"
elif [ -f "$pidfile" ]; then
# Or check for runing instance
# we are singleton
read pid < "$pidfile"
if [ $((pid)) -ne 0 ] && [ "$(ps -o pid= $pid | grep $pid)" ] ; then
case $ctl_action in
toggle) msg_info "Terminating instance $pid"
kill $pid ;;
cal ) kill -s USR2 $pid ;;
* ) msg_warning 'Found runing instance, exiting.' ;;
esac
exit
fi
fi
if [ "$ctl_action" = cal ]; then
calibrate
fi
savepid "$$"
# Signal handlers setup
trap 'quit' INT TERM QUIT HUP
trap 'restart' USR1
trap 'input_max' USR2
# Processing pipeline
set -m
msg_info "Smoothing duration (frames): $smooth"
msg_debug '=== Processing start ==='
b='stdbuf -oL'
b0='stdbuf -o0'
pix_fmt=$( printf '\x11' | $byteorder_test | awk 'FNR==1 { print substr($2,4,1) ? "gray16le" : "gray16be" }' )
# save original frame size and rate
eval "$( v4l2-ctl --device "${video_dev}" -P -V | awk -vFS=':' '
/[[:space:]]*Width\/Height/ {
split ($2, a, " ")
split (a[1], a, "/")
printf "cam_width=%s; cam_height=%s; ", a[1], a[2]
}
/[[:space:]]*Frames per second/ {
split ($2, a, " ")
print "cam_fps=" a[1]
}'
)"
msg_debug "saving camera settings: width = ${cam_width}, height = ${cam_height}, fps = ${cam_fps}"
ifps=$( awk_cmd 'sprintf ("v4l2-ctl --device '${video_dev}' -p %i\n", '$rate') | getline; print $5' )
ffmpeg_cmd='$b ffmpeg -v $([ $log_level_n -ge $debug ] && printf verbose || printf quiet) \
-f v4l2 -s 1x1 -r "${ifps}" -i "${video_dev}" \
-vf scale=1:1:flags=area+accurate_rnd+print_info,format=${pix_fmt} \
-vcodec rawvideo -f rawvideo -r ${rate} -'
msg_debug "pix_fmt : $pix_fmt"
msg_debug "=== ffmpeg_cmd ============"
msg_debug "${ffmpeg_cmd}"
msg_debug "==========================="
(
eval exec "${ffmpeg_cmd}" </dev/null \
| $b0 tail -c+$(( 2 * skip + 1 )) \
| eval "exec $b $hexprinter" \
| $b awk \
-v bl_fmt="${bl_fmt}" "
function to_log(x) {
return $bl_min + log(x / $bl_min) * d_log_r
}
function from_log(x) {
return $bl_min * r^((x - $bl_min) / d)
}
function bl_limit(v) {
return v > $bl_max ? $bl_max : v < $bl_min ? $bl_min : v
}"'
function filt_init(fa, len, v)
{
for (j in len) {
l = int(len[j])
prec_diff = int( log(l * '$bl_max') / log(2) ) + 1
fa[j]["l"] = l
fa[j]["s"] = v * l
fa[j]["m"] = 2^(PREC - prec_diff)
fa[j]["i"] = 0
fa[j]["t"] = (j == 1) ? 1 : 0
for (i = 0; i < l; i += 1)
fa[j]["a"][i] = v
}
}
function filt_run(fa, v)
{
for (j in fa) {
switch (fa[j]["t"])
{
case 0:
l = fa[j]["l"]
s = fa[j]["s"]
i = fa[j]["i"]
m = fa[j]["m"]
v = int(v * m) / m
s += v - fa[j]["a"][i]
fa[j]["a"][i] = v
v = s / l
i = (i + 1) % l
fa[j]["i"] = i
fa[j]["s"] = s
break
case 1:
i = fa[j]["i"]
l = fa[j]["l"]
fa[j]["a"][i] = v
i = (i + 1) % l
fa[j]["i"] = i
asort (fa[j]["a"], sf)
i = l / 2
v = (i == int(i)) ? (sf[i] + sf[i+1]) / 2 : sf[int(i) + 1]
break
}
}
return v
}'"
function skip_repeat() {
if (onetime)
exit
else
next
}
function check_repeat(new) {
if ( new && b_old && (new > b_old ? new/b_old : b_old/new) < threshold )
skip_repeat()
}
BEGIN {
onetime = system( \"! $onetime\" )
stderr = \"/dev/stderr\"
bl_sh = \"exec ${bl_sh} 2>/dev/null\"
PROCINFO[bl_sh, \"NONFATAL\"]=1
errno_prev = 0
errno_num = 0
threshold = $threshold / 100 + 1
# speedup calculations
imax = 255 ; omax = 65535
bl_fm = imax * ($bl_max - $bl_min)
bl_fd = ($max_color * omax)
# init LPF
split( \"${smooth}\", fade_len, \",\" )
use_fade = 0
for (j in fade_len)
{
if (int( fade_len[j] ) < 2) {
delete fade_len[j]
continue
}
use_fade = 1
}
if (use_fade) {
r = $bl_max / $bl_min
d = $bl_max - $bl_min
d_log_r = d / log(r)
filt_init( filt, fade_len, to_log( $(bl_get) / 100 * ${bl_hwmax} ) )
}
}
# start
{
# map to backlight range
bl = bl_limit( $bl_min + \$1 * bl_fm / bl_fd )
if (use_fade)
bl = bl_limit( from_log( filt_run( filt, to_log(bl) ) ) )
check_repeat( bl )
b_old = bl
}
$(( log_level_n >= debug )) {
"'printf ("brightness: %.02f%% | input light: %u / %u\n", 100 * bl / '$bl_max', $1, omax) > stderr'"
}
# output
{
ERRNO=0
printf (bl_fmt, bl) | bl_sh
if (ERRNO) {
if ( $(( log_level_n >= debug )) )
{
errno_num += (ERRNO == errno_prev)
errno_prev = ERRNO
"'printf (bl_sh": %s%s\r", ERRNO, errno_num > 0 ? sprintf(": %u times", errno_num) : "") > stderr'"
}
close (bl_sh)
} else {
fflush (bl_sh)
}
}"
) & procpid=$!
state=run
if $onetime; then
state=onetime
fi
# setup config change monitor
if $watch_conf && [ -n "$config_file" ]; then {
while :; do
inotifywait -q -e modify "$config_file"
msg_info 'Configuration changed'
kill -s USR1 $$
done
} & monpid=$!; fi
# silence job control noise
set +m
# Waiting
msg_info 'Working...'
wait $procpid
if [ -n "$monpid" ]; then
kill -- -$monpid
fi
while :; do
case $state in
'int' )
msg_info 'Interrupted' ;;
'restart')
msg_info 'Restart...'
savepid 0
eval exec "$0 $startup_args" ;;
'input_max' )
calibrate
state=restart
continue ;;
'run' )
msg_warning 'Processing pipeline terminated on its own' ;;
'onetime' )
msg_info 'Backlight adjustment complete' ;;
esac
# restore original frame size and rate
msg_debug "loading camera settings: width = ${cam_width}, height = ${cam_height}, fps = ${cam_fps}"
msg_debug "$( while fuser "${video_dev}" >/dev/null 2>&1; do sleep 0.1; done; v4l2-ctl --device "${video_dev}" -p "${cam_fps}" -v "width=${cam_width},height=${cam_height}" -P -V )"
savepid 0
break
done