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.
9 # Copyright 2024 Ian Kelling
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
15 # http://www.apache.org/licenses/LICENSE-2.0
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.
25 # todo: learn to start working in one corner of the screen.
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
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
36 trap 'echo "$0:$LINENO:error: \"$BASH_COMMAND\" exit status: $?, PIPESTATUS: ${PIPESTATUS[*]}" >&2' ERR
40 Usage: ${0##*/} [OPTIONS] [sysops|tech|staff|test]
42 arg is icecast mountpoint suffix, except staff removes suffix.
46 full: full screen even high resolution.
47 tall (default): half screen.
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
53 note: args duplicated in ffp
56 -h|--help Print help and exit.
58 Note: Uses util-linux getopt option parsing: spaces between args and
59 options, short options can be combined, options before args.
64 ##### begin command line parsing ########
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; }
78 temp
=$
(getopt
-l help hdlr
:uw
"$@") || usage
1
116 *) echo "$0: unexpected args: $*" >&2 ; usage
1 ;;
134 echo "error: unexpected \$1: $1" >&2
142 # 2500 gets us around a 4 second delay, up from 1.5s.
143 delay_arg
=,tpad
=start_duration
=2500ms
147 ##### end command line parsing ########
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
155 pass
=$
(sed -n 's/ *<source-password>\([^<]*\).*/\1/p' /p
/c
/icecast.xml
)
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"
167 if [[ $secondary_res ]]; then
168 secondary_x
=${secondary_res%%x*}
169 secondary_y
=${secondary_res##*x}
171 stream_res
=$secondary_res
173 stream_res
=$
(( secondary_x
/ 2 ))x
$secondary_y
175 stream_res
=$
(( secondary_x
/ 2 ))x$
(( secondary_y
/ 2))
179 stream_res
=$primary_res
183 keyframe_interval
=$
((framerate
* 2))
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
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"
196 # be relatively quiet. switch to debug when testing.
201 # tested for decreasing latency: did not help.
203 # tested for warning "Queue input is backward in time". did not help.
206 # note: ordering of inputs also affects zmqsend commands.
208 ## audio input options
213 $thread_queue_size_arg
218 $thread_queue_size_arg
219 # pulse knows this name somewhere
221 # This fixes latency. i haven't tried tuning it, but going too low creates
227 ## video input options
228 -video_size $stream_res
229 $thread_queue_size_arg
231 -framerate $framerate
234 # Video + audio filter. Note: this has only the things we actually need in it.
236 # volume=precision=fixed fixes this error:
237 # The following filters could not choose their formats: Parsed_amerge_4.
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.
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]"
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
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.
265 # video output options
267 -g $keyframe_interval
269 # for 1080p, default 256k is poor quality. 500 is ok. 1500 is a bit better.
274 ## audio output options
277 # afaik, this ensures that the amerge doesn't make 4 channel output if
278 # our output format supported it.
281 -content_type video
/webm
283 icecast
://source:$pass@
$host/fsf
$mount_suffix.webm
286 rm -f /tmp
/iank-ffmpeg-interlude-toggle
288 # system mute. disabled, just using application level mute atm.
290 # pactl set-source-mute @DEFAULT_SOURCE@ true
292 if pkill
-f ^ffmpeg.\
*icecast
://source.\
*/fsf
; then
296 #echo executing: ffmpeg ${opts[@]}
298 #{ sleep 1; ffp &>/dev/null & }
305 ##### begin clipboard history checkup ####
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
316 if (( copyqcount
>= max_rows
)); then
318 for ((i
=max_rows
; i
<copyqcount
; i
++)); do
321 copyq remove
"${rows_arg[@]}"
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
334 msg
="ffs: copyq not gone. aborting. super+y = copyq-restart / clear"
338 dunstify
-u critical
-h string
:x-dunst-stack-tag
:alert
"$msg"
343 ##### end clipboard history checkup ####
345 if [[ $mount_suffix == -sysops ]]; then
346 touch $HOME/.iank-stream-on
349 echo $volume >$HOME/.iank-stream-muted
351 ffmpeg
"${opts[@]}" &
353 # watch the stream and end the stream when we stop watching.
355 ffp
-d "${ffp_args[@]}" ||
:
357 rm -f $HOME/.iank-stream-on
362 ### begin background/development docs ###
364 # zmq vs stdin commands:
366 # * zmq allows targeting a specific filter when there are duplicates.
368 # * if you type stdin command too slow, ffmpeg will die because it stops
369 # doing normal work while it is waiting.
371 # * zmq returns a result to the calling process, rather than printing to
374 # * the only simple zmq tool I found, zmqsend, requires compiling. I
375 # used the latest ffmpeg 7.0.1. Build like so:
377 # p build-dep ffmpeg/aramo
378 # ./configure --enable-libzmq # i already had libzmq3-dev installed
380 # cp tools/zmqsend /a/opt/bin
382 # * ffmpeg debug output was useful in testing zmq commands.
384 # * Important documentation for stdin commands is only found by typing
385 # "c" into the stdin of ffmpeg and reading the output.
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
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
404 # ffprobe -i /tmp/out.wav -show_entries stream=channels -select_streams a:0 -of compact=p=0:nk=1 -v 0
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
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.
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%
424 # how I did perf testing: add -to 00:00:30 to ffmpeg opts to
425 # conveniently exit after measurement. Then run:
427 # ffmpeg "${opts[@]}" &
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=''"
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
447 ### end background/development docs ###