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