distro specific fixes
[distro-setup] / ffs
1 #!/bin/bash
2 # I, Ian Kelling, follow the GNU license recommendations at
3 # https://www.gnu.org/licenses/license-recommendations.en.html. They
4 # recommend that small programs, < 300 lines, be licensed under the
5 # Apache License 2.0. This file contains or is part of one or more small
6 # programs. If a small program grows beyond 300 lines, I plan to change
7 # to a recommended GPL license.
8
9 # Copyright 2024 Ian Kelling
10
11 # Licensed under the Apache License, Version 2.0 (the "License");
12 # you may not use this file except in compliance with the License.
13 # You may obtain a copy of the License at
14
15 # http://www.apache.org/licenses/LICENSE-2.0
16
17 # Unless required by applicable law or agreed to in writing, software
18 # distributed under the License is distributed on an "AS IS" BASIS,
19 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20 # See the License for the specific language governing permissions and
21 # limitations under the License.
22
23 # ffs = ffmpeg stream
24
25 # todo: learn to start working in one corner of the screen.
26
27 # potential improvement: it might be nice that we could have a tall terminal bug only use
28 # the top half for a 1080p stream, this is how:
29 # https://superuser.com/questions/1106674/how-to-add-blank-lines-above-the-bottom-in-terminal
30 #
31
32
33 if ! test "$BASH_VERSION"; then echo "error: shell is not bash" >&2; exit 1; fi
34 shopt -s inherit_errexit 2>/dev/null ||: # ignore fail in bash < 4.4
35 set -eE -o pipefail
36 trap 'echo "$0:$LINENO:error: \"$BASH_COMMAND\" exit status: $?, PIPESTATUS: ${PIPESTATUS[*]}" >&2' ERR
37
38 usage() {
39 cat <<EOF
40 Usage: ${0##*/} [OPTIONS] [sysops|tech|staff|test]
41
42 arg is icecast mountpoint suffix, except staff removes suffix.
43
44 -d debug.
45 -r RESOLUTION_TYPE
46 full: full screen even high resolution.
47 tall (default): half screen.
48 quarter: self evident
49 -l loud/listen. Start unmuted. Usually for testing.
50 -u Undelayed. Removes 5 second video delay, and about 4 second audio delay.
51 -w do not launch watch of stream
52
53 note: args duplicated in ffp
54
55
56 -h|--help Print help and exit.
57
58 Note: Uses util-linux getopt option parsing: spaces between args and
59 options, short options can be combined, options before args.
60 EOF
61 exit $1
62 }
63
64 ##### begin command line parsing ########
65
66 # ensure we can handle args with spaces or empty.
67 ret=0; getopt -T || ret=$?
68 [[ $ret == 4 ]] || { echo "Install util-linux for enhanced getopt" >&2; exit 1; }
69
70 ffp_args=()
71 debug=false
72 delay=true
73 loglevel=fatal
74 watch=true
75 volume=0
76 fullscreen=false
77 tall=true
78 temp=$(getopt -l help hdlr:uw "$@") || usage 1
79 eval set -- "$temp"
80 while true; do
81 case $1 in
82 -d)
83 debug=true
84 loglevel=debug
85 loglevel=info
86 ffp_args+=(-d)
87 ;;
88 -l)
89 volume=1
90 ;;
91 -r)
92 case $2 in
93 tall)
94 fullscreen=false
95 tall=true
96 ;;
97 quarter)
98 fullscreen=false
99 tall=false
100 ;;
101 full)
102 fullscreen=true
103 tall=false
104 ;;
105 esac
106 shift
107 ;;
108 -w)
109 watch=false
110 ;;
111 -u)
112 delay=false
113 ;;
114 -h|--help) usage ;;
115 --) shift; break ;;
116 *) echo "$0: unexpected args: $*" >&2 ; usage 1 ;;
117 esac
118 shift
119 done
120
121 mount_suffix=-sysops
122 if [[ $1 ]]; then
123 case $1 in
124 sysops|tech)
125 mount_suffix=-$1
126 ;;&
127 tech)
128 delay=false
129 ;;
130 staff)
131 mount_suffix=
132 ;;
133 *)
134 echo "error: unexpected \$1: $1" >&2
135 exit 1
136 ;;
137 esac
138 ffp_args+=($1)
139 fi
140
141 if $delay; then
142 # 2500 gets us around a 4 second delay, up from 1.5s.
143 delay_arg=,tpad=start_duration=2500ms
144 fi
145
146
147 ##### end command line parsing ########
148
149 host=live.iankelling.org:8000
150 if ip n show 10.2.0.1 | grep . &>/dev/null && \
151 [[ $(dig +timeout=1 +short @10.2.0.1 -x 10.2.0.2 2>&1 ||:) == kd.b8.nz. ]]; then
152 host=127.0.0.1:8000
153 fi
154
155 pass=$(sed -n 's/ *<source-password>\([^<]*\).*/\1/p' /p/c/icecast.xml)
156
157
158 tmpf=$(mktemp)
159 xrandr >$tmpf
160
161 # example xrandr output: 1280x800+0+0
162 primary_res=$(awk '$2 == "connected" && $3 == "primary" { print $4 }' $tmpf | sed 's/+.*//')
163 tmp=$(awk '$2 == "connected" && $3 != "primary" { print $3 }' $tmpf | sed 's/+/ /g')
164 read -r secondary_res x_offset _ <<<"$tmp"
165
166
167 if [[ $secondary_res ]]; then
168 secondary_x=${secondary_res%%x*}
169 secondary_y=${secondary_res##*x}
170 if $fullscreen; then
171 stream_res=$secondary_res
172 elif $tall; then
173 stream_res=$(( secondary_x / 2 ))x$secondary_y
174 else
175 stream_res=$(( secondary_x / 2 ))x$(( secondary_y / 2))
176 fi
177 else
178 x_offset=0
179 stream_res=$primary_res
180 fi
181
182 framerate=8
183 keyframe_interval=$((framerate * 2))
184
185 # Monitor of default sink.
186 # eg: alsa_output.usb-Audio-gd_Audio-gd-00.analog-stereo
187 pa_sink=$(pactl get-default-sink).monitor
188
189 # this is for ffmpeg warnings. doesnt seem to affect latency.
190 # 160 was too small. at 300, it occasionally complains,
191 # probably only when we are using delayed output
192 thread_queue_size_arg="-thread_queue_size 500"
193
194 opts=(
195 # global options
196 # be relatively quiet. switch to debug when testing.
197 -v $loglevel
198 -hide_banner
199 -nostats
200
201 # tested for decreasing latency: did not help.
202 # -probesize 32
203 # tested for warning "Queue input is backward in time". did not help.
204 #-rtbufsize 500M
205
206 # note: ordering of inputs also affects zmqsend commands.
207
208 ## audio input options
209
210 -f pulse
211 -name ffs
212 # note: duplicated
213 $thread_queue_size_arg
214 -fragment_size 512
215 -i default
216
217 -f pulse
218 $thread_queue_size_arg
219 # pulse knows this name somewhere
220 -name ffsdesktop
221 # This fixes latency. i haven't tried tuning it, but going too low creates
222 # choppy output.
223 -fragment_size 512
224 -i "$pa_sink"
225
226
227 ## video input options
228 -video_size $stream_res
229 $thread_queue_size_arg
230 -f x11grab
231 -framerate $framerate
232 -i :0.0+$x_offset.0
233
234 # Video + audio filter. Note: this has only the things we actually need in it.
235 #
236 # volume=precision=fixed fixes this error:
237 # The following filters could not choose their formats: Parsed_amerge_4.
238 #
239 # Default volume precision is float. Our input is fixed. maybe ffmpeg
240 # thinks the input could change and so can't commit to an output.
241 # The error suggests using aformat, which seems like it would probably
242 # also fix the error.
243 #
244 # man page say zmq url default includes "localhost", but specifying a
245 # localhost url caused an error for me.
246 -filter_complex "[0]azmq,volume=precision=fixed: volume=$volume [vol0];
247 [1]azmq='b=tcp\://127.0.0.1\:5556',volume=precision=fixed: volume=0 [vol1];
248 [vol0][vol1] amerge=inputs=2;
249 [2]zmq='b=tcp\://127.0.0.1\:5557',drawbox=color=0x262626,drawtext=fontsize=90: fontcolor=beige: x=40: y=40: text=''${delay_arg}[out]"
250
251 # An online source says to match a 5 second vid delay, we can do an
252 # audio delay filter: "adelay=5000|5000". However, we already get
253 # a stream delay of about 2 seconds, and having the audio be about
254 # 2 seconds ahead is fine, they do that intentionally in soccer
255 # matches.
256
257 # Based on error message and poking around, it seems ffmpeg is not
258 # smart enough to see that [vol0] and [vol1] are inputs to the amerge
259 # filter, and thus we would not want them as final outputs. So, we
260 # have to identify the amerge output and pass it to -out. This
261 # identifier is called an "output pad" in man ffmpeg-filters, and a
262 # "link label" in man ffmpeg.
263 -map '[out]'
264
265 # video output options
266 -vcodec libvpx
267 -g $keyframe_interval
268 -quality realtime
269 # for 1080p, default 256k is poor quality. 500 is ok. 1500 is a bit better.
270 -b:v 1500k
271 -threads 2
272 -error-resilient 1
273
274 ## audio output options
275 -c:a libvorbis
276 -b:a 128k
277 # afaik, this ensures that the amerge doesn't make 4 channel output if
278 # our output format supported it.
279 -ac 2
280
281 -content_type video/webm
282 -f webm
283 icecast://source:$pass@$host/fsf$mount_suffix.webm
284 )
285
286 rm -f /tmp/iank-ffmpeg-interlude-toggle
287
288 # system mute. disabled, just using application level mute atm.
289 #
290 # pactl set-source-mute @DEFAULT_SOURCE@ true
291
292 if pkill -f ^ffmpeg.\*icecast://source.\*/fsf; then
293 sleep 1
294 fi
295
296 #echo executing: ffmpeg ${opts[@]}
297
298 #{ sleep 1; ffp &>/dev/null & }
299
300 if $debug; then
301 ffmpeg "${opts[@]}"
302 exit 0
303 fi
304
305 ##### begin clipboard history checkup ####
306
307 # Avoid streaming with secrets in our clipboard history. We could just
308 # clear the history, but here I truncate it to a max and then show it,
309 # and then I can press super+y if I want to clear it, or close the
310 # window if I want to keep it.
311 copyqcount=$(copyq count)
312 regex='^[1-9][0-9]*$'
313 if [[ $copyqcount =~ $regex ]]; then
314 # i dont want to think about more than this
315 max_rows=40
316 if (( copyqcount >= max_rows )); then
317 rows_arg=()
318 for ((i=max_rows; i<copyqcount; i++)); do
319 rows_arg+=($i)
320 done
321 copyq remove "${rows_arg[@]}"
322 fi
323 copyq show
324 gone=false
325 for (( i=0; i<40; i++ )); do
326 if i3-msg -t get_tree | jq -e '.. | select(.class? == "copyq" and .instance? == "copyq")' &>/dev/null; then
327 sleep .5
328 else
329 gone=true
330 break
331 fi
332 done
333 if ! $gone; then
334 msg="ffs: copyq not gone. aborting. super+y = copyq-restart / clear"
335 if [[ -t 0 ]]; then
336 echo $msg
337 else
338 dunstify -u critical -h string:x-dunst-stack-tag:alert "$msg"
339 fi
340 exit 1
341 fi
342 fi
343 ##### end clipboard history checkup ####
344
345 if [[ $mount_suffix == -sysops ]]; then
346 touch $HOME/.iank-stream-on
347 fi
348
349 echo $volume >$HOME/.iank-stream-muted
350
351 ffmpeg "${opts[@]}" &
352 if $watch; then
353 # watch the stream and end the stream when we stop watching.
354 sleep 2
355 ffp -d "${ffp_args[@]}" ||:
356 kill %%
357 rm -f $HOME/.iank-stream-on
358 fi
359
360
361
362 ### begin background/development docs ###
363
364 # zmq vs stdin commands:
365 #
366 # * zmq allows targeting a specific filter when there are duplicates.
367 #
368 # * if you type stdin command too slow, ffmpeg will die because it stops
369 # doing normal work while it is waiting.
370 #
371 # * zmq returns a result to the calling process, rather than printing to
372 # stdout.
373 #
374 # * the only simple zmq tool I found, zmqsend, requires compiling. I
375 # used the latest ffmpeg 7.0.1. Build like so:
376 #
377 # p build-dep ffmpeg/aramo
378 # ./configure --enable-libzmq # i already had libzmq3-dev installed
379 # make alltools
380 # cp tools/zmqsend /a/opt/bin
381 #
382 # * ffmpeg debug output was useful in testing zmq commands.
383 #
384 # * Important documentation for stdin commands is only found by typing
385 # "c" into the stdin of ffmpeg and reading the output.
386 #
387 #
388 #
389 # stdin command docs, before I abandoned it for zmq:
390 # mkfifo -m 0600 /tmp/iank-ffmpeg
391 # # ffmpeg sits and waits until we do this. dunno why.
392 # echo >/tmp/iank-ffmpeg &
393 # ffmpeg ... </tmp/iank-ffmpeg |& while read -r line; do : check results; done
394 # # example of working commands:
395 # echo "cdrawbox -1 t 0" >/tmp/iank-ffmpeg
396 # echo "cdrawbox -1 t fill" >/tmp/iank-ffmpeg
397 # echo "cdrawtext -1 reinit text=''" >/tmp/iank-ffmpeg
398 # echo "cvolume -1 volume=1" >/tmp/iank-ffmpeg
399
400
401 # For testing: to show the number of audio channels in a resulting file
402 # https://stackoverflow.com/questions/47905083/how-to-check-number-of-channels-in-my-audio-wav-file-using-ffmpeg-command
403 #
404 # ffprobe -i /tmp/out.wav -show_entries stream=channels -select_streams a:0 -of compact=p=0:nk=1 -v 0
405
406 # for a right/left speaker test:
407 # https://askubuntu.com/questions/148363/which-linux-command-can-i-use-to-test-my-speakers-for-current-talk-radio-output
408 # p install alsa-utils
409 # speaker-test -t wav -c 2 -l 1
410
411 # There are 2 other options for audio, so I wanted to do a little
412 # performance measurement of this method.
413 # 1 is to combine the 2 audio sources in pulse,
414 # https://unix.stackexchange.com/questions/351764/create-combined-source-in-pulseaudio .
415 # 1 is to record mumble and combine in post processing.
416
417 ### benchmark / perf tests: these are pretty inaccurate.
418 # 29 seconds cpu use. video bitrate 1500k, 8 fps, 2x keyframe interval.
419 # * 64k vorbis: 69.7%
420 # * 128k vorbis: 70.1% (used in subsequent tests)
421 # * 1 audio input: 64.3%
422 # * 0 audio inputs: 59.2%
423
424 # how I did perf testing: add -to 00:00:30 to ffmpeg opts to
425 # conveniently exit after measurement. Then run:
426 #
427 # ffmpeg "${opts[@]}" &
428 # pid=$!
429 # sleep 29
430 # ps -p $pid -o %cpu
431 # kill %%
432
433 # filter for only 1 audio input:
434 #-filter_complex "[0]azmq,volume=precision=fixed;[1]zmq='b=tcp\://127.0.0.1\:5557',drawbox=color=0x262626,drawtext=fontsize=90: fontcolor=beige: x=40: y=40: text=''"
435 # filter with 0 audio input:
436 # -filter_complex "[0]zmq='b=tcp\://127.0.0.1\:5557',drawbox=color=0x262626,drawtext=fontsize=90: fontcolor=beige: x=40: y=40: text=''"
437
438
439 # When things weren't working, I did some checking on newer ffmpeg to
440 # see if that helped. It never did. I compiled the latest ffmpeg release
441 # tarball, 7.0.1, and tried the version in debian bullseye by schrooting
442 # before running ffmpeg. Building was just configure; make, but then I
443 # found some flags that were needed. gpl flags r just because I noticed them.
444 # ./configure --enable-libzmq --enable-libpulse --enable-libvorbis --enable-gpl --enable-version3
445 #
446
447 ### end background/development docs ###