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