-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathliquidsoap.liq
1224 lines (1003 loc) · 40.6 KB
/
liquidsoap.liq
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
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# WARNING! This file is automatically generated by AzuraCast.
# Do not update it directly!
# Custom Configuration (Specified in Station Profile)
### BEGIN: BFF.fm Configuration and Secrets ###
### Secrets should not be checked in to source control. Duh. ###
# General Config
## User Agent: We generate a user agent for HTTP requests using these
user_agent_name = ref("BFF.fm Broadcast System")
user_agent_url = ref("https://bff.fm")
## Fixed MP3 source content
# Our error/info default recordings are stored in the cloud, you can also reference
# local files.
mp3_technical_difficulties = ref("https://.../broadcast-server-test-feed.mp3")
mp3_test_feed = ref("https://.../broadcast-server-test-feed.mp3")
## Azuracast Public API info
azuracast_public_url = ref("https://broadcast.example.com")
azuracast_public_api_key = ref("(PASSWORD)")
## Creek CMS integration
# BFF.fm uses a modified version of Creek as its CMS, through which we authenticate
# our streamers, and also pull canonical track metadata.
creek_app_id = ref("fm.bff.example")
creek_api_base = ref("https://")
creek_public_base = ref("https://")
## Ingestion harbor configuration
# To make re-use and hiding passwords in the checked-in version simpler, set these
# Icecast output variables.
icecast_port = 8005
icecast_password = ref("(PASSWORD)")
## Fixed passwords for studio Icecast stream harbors
# Our studio connections use a single client ID and so have fixed passwords hard-coded
# into this config, rather than authenticating against Creek.
ingest_studio_a_password = ref("(PASSWORD)")
ingest_fallback_password = ref("(PASSWORD)")
ingest_emergency_password = ref("(PASSWORD)")
## Last.FM scrobbling
# We scrobble everything we play when metadata is pulled from Creek.
lastfm_app_id = ref("(PASSWORD)")
lastfm_app_secret = ref("(PASSWORD)")
# You'll need to do an OAuth dance with the app credentials above to get
# a session token for your Last.FM account to scrobble. You can find a node
# utility script to do that here: https://github.com/BFFdotFM/logstash-scrobbler
lastfm_session_token = ref("(PASSWORD)") # @bffdotfm
## Slack logging
# In some world, we'd probably log more actively to a real logging platform,
# but as a community radio station Slack is very, very useful for basic visibility
# and this config throws info like new connections/failed authentication into
# specified slack channels.
# Prefix all Slack logs with this text (useful to distinguish debugging instances from
# your production messages.)
# e.g. :safety_vest:, [DEBUG], etc.
slack_message_prefix = ref(":safety_vest: ")
# We post to Slack using webhooks, so you'll need to create a Slack app for your instance,
# and then create webhooks for the channels you want to post to. Calls to `slack.log` can
# be named, allowing different channels to receive messages (e.g. `alerts`, `stream_auth`,
# and `now_playing`.)
#
# Each assignment only needs to unique path of the webhook, so will look something like
# `ref("J12345678/G1234567890/1234567890abcdef12345678")`
slack_default_channel = ref("(PASSWORD)")
slack_named_channels = ref([
("alerts", slack_default_channel),
("stream_auth", slack_default_channel),
("now_playing", ref("(PASSWORD)"))
])
## TuneIn Air
# As with Last.FM, you'll need to register for the TuneIn Air service to send first-class
# tracking info to TuneIn, and set the various keys here:
tunein_partner_id = ref("(PASSWORD)")
tunein_partner_key = ref("(PASSWORD)")
tunein_station_id = ref("(PASSWORD)")
### END BFF.fm Configuration and Secrets ###
init.daemon.set(false)
init.daemon.pidfile.path.set("/var/azuracast/stations/example/config/liquidsoap.pid")
log.stdout.set(true)
log.file.set(false)
settings.server.log.level.set(4)
settings.server.socket.set(true)
settings.server.socket.permissions.set(0o660)
settings.server.socket.path.set("/var/azuracast/stations/example/config/liquidsoap.sock")
settings.harbor.bind_addrs.set(["0.0.0.0"])
settings.tag.encodings.set(["UTF-8","ISO-8859-1"])
settings.encoder.metadata.export.set(["artist","title","album","song"])
setenv("TZ", "America/Los_Angeles")
autodj_is_loading = ref(true)
ignore(autodj_is_loading)
autodj_ping_attempts = ref(0)
ignore(autodj_ping_attempts)
# Track live-enabled status.
live_enabled = ref(false)
ignore(live_enabled)
# Track live transition for crossfades.
to_live = ref(false)
ignore(to_live)
azuracast_api_url = "http://127.0.0.1:6010/api/internal/1/liquidsoap"
azuracast_api_key = "(PASSWORD)"
def azuracast_api_call(~timeout_ms=2000, url, payload="") =
full_url = "#{azuracast_api_url}/#{url}"
log("API #{url} - Sending POST request to '#{full_url}' with body: #{payload}")
try
response = http.post(full_url,
headers=[
("Content-Type", "application/json"),
("User-Agent", "Liquidsoap AzuraCast"),
("X-Liquidsoap-Api-Key", "#{azuracast_api_key}")
],
timeout_ms=timeout_ms,
data=payload
)
log("API #{url} - Response (#{response.status_code}): #{response}")
"#{response}"
catch err do
log("API #{url} - Error: #{error.kind(err)} - #{error.message(err)}")
"false"
end
end
station_media_dir = "/var/azuracast/stations/example/media"
def azuracast_media_protocol(~rlog=_,~maxtime=_,arg) =
["#{station_media_dir}/#{arg}"]
end
add_protocol(
"media",
azuracast_media_protocol,
doc="Pull files from AzuraCast media directory.",
syntax="media:uri"
)
# Custom Configuration (Specified in Station Profile)
### BEGIN: BFF.fm Settings Overrides ###
# log level 5 for mega debugging
# settings.server.log.level.set(5)
### END: BFF.fm Settings Overrides
### BEGIN: BFF.fm Library Code ###
## After: Azuracast helpers, `add_protocol("media", ...)`
## Time Utilities
# Shorthands for various time formats
let timestamp = ()
# Default to the system timestamp and 'now'
def timestamp.custom(format="%T", datetime="now") =
list.hd(default="", process.read.lines(env=[("TZ", ":America/Los_Angeles"), ("FORMAT", format), ("DT", datetime)], "date -d\"$DT\" +\"$FORMAT\""))
end
# e.g. 20:45:23
def timestamp.hms(datetime="now") =
timestamp.custom("%T", datetime)
end
# e.g. 2022-09-14T03:52:38
def timestamp.iso8609(datetime="now") =
timestamp.custom("%Y-%m-%dT%H:%M:%S", datetime)
end
# e.g. 20220914T035238
def timestamp.ymdhms(datetime="now") =
timestamp.custom("%Y%m%dT%H%M%S", datetime)
end
# e.g. 1663131225
def timestamp.unix(datetime="now") =
timestamp.custom("%s", datetime)
end
# e.g. 9:49pm on 13 September, 2022
def timestamp.friendly(datetime="now") =
timestamp.custom("%-I:%M%P on %-d %B, %Y", datetime)
end
## Hash and Crypto
# Last.FM's API needed some MD5 smushing, so here it is.
let hash = ()
def hash.md5(str) =
md5sum = file.which("md5sum")
log.debug("Path to md5sum: #{md5sum}")
# md5sum returns the form "<HASH> -", so split away just the hash w/ awk:
list.hd(default="", process.read.lines(env=[("STR", str)], "printf %s \"$STR\" | #{md5sum} | awk '{ print $1 }'"))
end
## Curl HTTP functions
# While Azuracast w/ Liquidsoap 2 now has curllib HTTP functions build in (these
# function used to shell out to curl), we still use these wrappers provide some
# sugar around the build-in http.get/post methods, particularly for data wrangling
let curl = ()
let curl.version = ref(list.hd(default="curl/unknown", process.read.lines("curl --version | head -1 | awk '{ print $1 \"/\" $2 }'")))
let curl.userAgent = ref("Liquidsoap/#{liquidsoap.version} (#{!curl.version}) #{!user_agent_name} <#{!user_agent_url}>")
def curl.headers(headers=[]) =
list.add(("User-Agent", !curl.userAgent), headers)
end
# Provide a data object ala
#
# {
# key: "data",
# another: "more"
# }
#
def curl.json(~data={}, ~timeout_ms=2000, ~headers=[], theUrl) =
log("cURL JSON: #{theUrl}")
try
response = http.post(theUrl,
headers=curl.headers(list.add(
("Content-Type", "application/json"),
headers
)),
timeout_ms=timeout_ms,
data=json.stringify(compact=true, data)
)
log("cURL JSON: #{theUrl} - Response (#{response.status_code})")
"#{response}"
catch err do
log("cURL JSON: #{theUrl} - Error: #{error.kind(err)} - #{error.message(err)}")
"Unknown HTTP error"
end
end
# Provide the data object as a list of pairs
#
# [
# ("key", "data"),
# ("another", "more")
# ]
#
def curl.post(~data=[], ~timeout_ms=2000, ~headers=[], theUrl) =
log("cURL POST: #{theUrl}")
def buildDataString(data, arg) =
data ^ fst(arg) ^ "=" ^ url.encode(snd(arg)) ^ "&"
end
formData = list.fold(buildDataString, "", data)
try
response = http.post(theUrl,
headers=curl.headers(list.add(
("Content-Type", "application/x-www-form-urlencoded"),
headers
)),
timeout_ms=timeout_ms,
data=formData
)
log("cURL POST: #{theUrl} - Response (#{response.status_code})")
"#{response}"
catch err do
log("cURL POST: #{theUrl} - Error: #{error.kind(err)} - #{error.message(err)}")
"Unknown HTTP error"
end
end
def curl.fetch(~timeout_ms=2000, ~headers=[], theUrl) =
log("cURL GET: #{theUrl}")
try
response = http.get(theUrl,
headers=curl.headers(list.add(
("Content-Type", "application/x-www-form-urlencoded"),
headers
)),
timeout_ms=timeout_ms
)
"#{response}"
catch err do
log("cURL GET: #{theUrl} - Error: #{error.kind(err)} - #{error.message(err)}")
"Unknown HTTP error"
end
end
## Azuracast Public API Functions
# Functionality that calls the public API for AzuraCast, rather than the internal
# azuracast_api_call version.
#
# You need to provide an API key with `Administer Stations` permission.
let azuracast_public = ()
let azuracast_public.apiBase = azuracast_public_url
let azuracast_public.apiKey = azuracast_public_api_key
# Extract station ID from internal API url above: `/internal/{number}/`
def azuracast_public.stationId() =
let matcher = regexp("/internal/(\\d+)/")
# returns [(index, value)]
snd(list.hd(matcher.exec(azuracast_api_url), default=(0, "0")))
end
def azuracast_public.call(endpoint, payload={}) =
let api_url = "#{!azuracast_public.apiBase}/api/station/#{azuracast_public.stationId()}/#{endpoint}"
log("Azuracast Public: #{api_url}")
ignore(curl.json(
data=payload,
headers=[
("X-Api-Key", !azuracast_public.apiKey)
],
api_url))
end
## BFF.fm API functions
#
# The BFF.fm CMS is a forked version of Creek.fm, along with some of our own
# deployment idiocyncracies, so this wrapper makes calling the API easier
let bff = ()
let bff.appId = creek_app_id
let bff.base = creek_api_base
let bff.publicBase = creek_public_base
def bff.fetch(~cacheBust=false, endpoint)
appendUrl = if (cacheBust == true) then
"&cacheBust=#{timestamp.unix()}"
else
""
end
fullApiCallUrl = "#{!bff.base}/api/#{endpoint}?app_id=#{url.encode(!bff.appId)}#{appendUrl}"
curl.fetch(fullApiCallUrl)
end
def bff.post(~data=[], endpoint)
url = "#{!bff.base}/api/#{endpoint}"
fullData = list.append([
('app_id', !bff.appId)
], data)
curl.post(data=fullData, url)
end
# Create a special "now" endpoint shortlink that will direct users to the most relevant show/broadcast
# destination based on the time of the URL:
#
# e.g. https://bff.fm/now/20200209T115500
def bff.nowUrl() =
"#{creek_public_base}/now/#{timestamp.ymdhms()}"
end
## Slack Functions
# BFF.fm makes heavy use of Slack for all our community organizing and a lot of technical monitoring.
let slack = ()
# These options are documented in the configuration block above
let slack.defaultChannel = slack_default_channel
let slack.channels = slack_named_channels
let slack.messagePrefix = slack_message_prefix
def slack.send(hook, message) =
messageObject = {
text = "[#{timestamp.hms()}] #{!slack.messagePrefix}#{message}",
type = "mrkdwn"
}
log("SLACK: #{message}")
ignore(curl.json(data=messageObject, "https://hooks.slack.com/services/#{hook}"))
end
def slack.log(~channel="", message) =
channelHook = list.assoc(default=slack.defaultChannel, channel, !slack.channels)
slack.send(!channelHook, message)
end
## Last.FM Functions
#
# Last.FM integration can also be provided via an extension for Liquidsoap, but it's
# not shipping in AzuraCast at this time, so we implemented the `track.scrobble` API
# ourselves.
#
# You'll need to create an app at https://www.last.fm/api and then auth your account
# against it to get a Session token and store it all in the config above.
let lastfm = ()
let lastfm.apiBase = ref("https://ws.audioscrobbler.com/2.0/")
let lastfm.appId = lastfm_app_id
let lastfm.appSecret = lastfm_app_secret
let lastfm.sessionToken = lastfm_session_token
def lastfm.scrobble(~artist, ~track, ~album="") =
log.info("Scrobbling: #{track} by #{artist} (Album: #{album})")
# parameters in alphabetical order
params = [
("album", album),
("api_key", !lastfm.appId),
("artist", artist),
("method", "track.scrobble"),
("sk", !lastfm.sessionToken),
("timestamp", timestamp.unix()),
("track", track),
]
def flattenSignatureParam(output, p) =
output ^ fst(p) ^ snd(p)
end
hashableParamString = list.fold(flattenSignatureParam, "", params) ^ !lastfm.appSecret
apiSignature = hash.md5(hashableParamString)
fullParams = list.append(params, [("api_sig", apiSignature)])
ignore(curl.post(data=fullParams, !lastfm.apiBase))
end
# While we now pull our playing data from a richer JSON API, this function handles the common
# Artist - Track string format that might be passed around your automation system.
def lastfm.scrobbleNowPlayingString(nowPlaying) =
parts = list.map(string.trim, string.split(separator="-", nowPlaying))
if (list.length(parts) == 2) then
artist = list.hd(default="", parts)
track = list.nth(default="", parts, 1)
lastfm.scrobble(artist=artist, track=track)
else
log.important("Could not attempt scrobbling #{nowPlaying}, did not split into 2 parts")
end
end
## TuneIn AIR Support
# AzuraCast does have some native support for TuneIn, but since we're pulling richer track
# metadata (see below), we've implemented it directly.
let tunein = ()
let tunein.apiBase = ref("http://air.radiotime.com/Playing.ashx")
let tunein.partnerId = tunein_partner_id
let tunein.partnerKey = tunein_partner_key
let tunein.stationId = tunein_station_id
def tunein.airRequest(params) =
fullParams = list.append([
("partnerId", !tunein.partnerId),
("partnerKey", !tunein.partnerKey),
("id", !tunein.stationId)
], params)
ignore(curl.post(data=fullParams, !tunein.apiBase))
end
def tunein.nowPlaying(~artist, ~track, ~album="") =
log.info("Logging to TuneIn AIR NOW: #{track} by #{artist} (Album: #{album})")
tunein.airRequest([
("artist", artist),
("title", track),
("album", album)
])
end
def tunein.nonMusic(~attribution, ~name) =
log.info("Logging non-music to TuneIn AIR NOW: #{name} attributed to #{attribution}")
tunein.airRequest([
("artist", attribution),
("title", name),
# ("commercial", "true")
])
end
### END: BFF.fm Library Code ###
playlist_silence = playlist(id="playlist_silence",mime_type="audio/x-mpegurl",mode="normal",reload_mode="watch","/var/azuracast/stations/ebbfs/playlists/playlist_silence.m3u")
playlist_silence = cue_cut(id="cue_playlist_silence", playlist_silence)
playlist_silence = drop_metadata(playlist_silence)
# Standard Playlists
radio = random(id="standard_playlists", weights=[5], [playlist_silence])
requests = request.queue(id="requests")
requests = cue_cut(id="cue_requests", requests)
radio = fallback(id="requests_fallback", track_sensitive = true, [requests, radio])
interrupting_queue = request.queue(id="interrupting_requests")
interrupting_queue = cue_cut(id="cue_interrupting_requests", interrupting_queue)
radio = fallback(id="interrupting_fallback", track_sensitive = false, [interrupting_queue, radio])
def add_skip_command(s) =
def skip(_) =
source.skip(s)
"Done!"
end
server.register(namespace="radio", usage="skip", description="Skip the current song.", "skip",skip)
end
add_skip_command(radio)
# Custom Configuration (Specified in Station Profile)
### BEGIN: BFF.fm Hardcoded Sources
## After: `add_skip_command(radio)`
default_error_source = fallback(track_sensitive = false, [single(!mp3_technical_difficulties), single("/usr/local/share/icecast/web/error.mp3")])
### END: BFF.fm Hardcoded Sources
def live_aware_crossfade(old, new) =
if !to_live then
# If going to the live show, play a simple sequence
sequence([fade.out(old.source),fade.in(new.source)])
else
# Otherwise, use the smart transition
cross.simple(old.source, new.source, fade_in=2.00, fade_out=2.00)
end
end
radio = cross(minimum=0., duration=3.00, live_aware_crossfade, radio)
# Allow for Telnet-driven insertion of custom metadata.
radio = server.insert_metadata(id="custom_metadata", radio)
# Apply amplification metadata (if supplied)
radio = amplify(override="liq_amplify", 1., radio)
# Normalization and Compression
radio = normalize(target = 0., window = 0.03, gain_min = -16., gain_max = 0., radio)
radio = compress.exponential(radio, mu = 1.0)
radio = fallback(id="safe_fallback", track_sensitive = false, [radio, single(id="error_jingle", "/usr/local/share/icecast/web/error.mp3")])
# Send metadata changes back to AzuraCast
last_title = ref("")
last_artist = ref("")
def metadata_updated(m) =
def f() =
if (m["title"] != !last_title or m["artist"] != !last_artist) then
last_title := m["title"]
last_artist := m["artist"]
j = json()
if (m["song_id"] != "") then
j.add("song_id", m["song_id"])
j.add("media_id", m["media_id"])
j.add("playlist_id", m["playlist_id"])
else
j.add("artist", m["artist"])
j.add("title", m["title"])
end
_ = azuracast_api_call(
"feedback",
json.stringify(j)
)
end
end
thread.run(f)
end
radio.on_metadata(metadata_updated)
# Handle "Jingle Mode" tracks by replaying the previous metadata.
last_metadata = ref([])
def handle_jingle_mode(m) =
if (m["jingle_mode"] == "true") then
!last_metadata
else
last_metadata := m
m
end
end
radio = metadata.map(update=false, strip=true, handle_jingle_mode, radio)
# Custom Configuration (Specified in Station Profile)
### BEGIN: BFF.fm Ingest Harbors ###
## After: Azuracast autoDJ setup, `radio = metadata.map(...)`
# A Pre-DJ source of radio powered by the Azuracast automation system
# that can be broadcast as fallback when needed.
#
# Since we've had issues with volume matching and falling back when clients
# connections are unreliable, we just broadcast a silent at the present time.
# At some point, we'll properly figure out how to work with Liquidsoap scheduling
# and/or silence detection to fallback gracefully.
radio_without_live = radio
ignore(radio_without_live)
# To bypass Azuracast AutoDJ, reassign 'radio' here:
#
# ignore(radio)
# If running an automation playlist through AzuraCast while enabling AzuraCast
# live streamer mount, assign `radio_without_live`:
#
# radio = fallback(track_sensitive = false, [radio_without_live, default_error_source])
#
# Otherwise, assign a new error MP3:
#
# radio = default_error_source
# Manage Icecast input harbors remote DJs and Studios
let ingest = ()
let ingest.icecastPort = icecast_port
# Ingest precedence stacks all created HTTP harbors (by name) to create the
# cascade by which on-air is determined:
let ingest.precedence = ref([])
# Active harbor connections and associated user:
let ingest.connections = ref([])
# Connection debugging
# If during development/deployment you need to see the current state of the
# active connections list, call this function.
def ingest.debugConnections() =
def listToString(str, item) =
str ^ "#{fst(item)} => #{snd(item)}"
end
connectionsDebug = list.fold(listToString, "", !ingest.connections)
log.debug("Connections: #{connectionsDebug}")
connectionsDebug
end
def ingest.registerSource(sourceName, highPriority=false) =
if (highPriority) then
ingest.precedence := list.add(sourceName, !ingest.precedence)
else
ingest.precedence := list.append(!ingest.precedence, [sourceName])
end
end
# Is a named studio currently connected?
def ingest.isConnected(studio) =
dj = list.assoc(default="", studio, !ingest.connections)
(dj != "")
end
# Who is connected to a named studio?
def ingest.djFor(studio) =
list.assoc(default="", studio, !ingest.connections)
end
def ingest.currentSource() =
# Get the highest precedence source currently connected
def getSource(current, source) =
if (current != "") then
current
else
next = list.assoc(default="", source, !ingest.connections)
if (next != "") then
source
else
""
end
end
end
list.fold(getSource, "", !ingest.precedence)
end
# Who is the current on-air DJ, based on studio precedence?
def ingest.currentDj() =
# Get the DJ for the highest precedence studio that has a DJ
def getDj(current, studio) =
if (current != "") then
current
else
ingest.djFor(studio)
end
end
list.fold(getDj, "", !ingest.precedence)
end
# Global “on connection” handler
def ingest.onDjConnect() =
source_name = ingest.currentSource()
dj_name = ingest.currentDj()
if (dj_name != "") then
_ = azuracast_api_call(
timeout_ms=5000,
"djon",
json.stringify({user = dj_name})
)
slack.log(":rotating_light: ON AIR: #{source_name}/*#{dj_name}*")
end
end
# Global “on disconnect handler
def ingest.onDjDisconnect() =
dj_name = ingest.currentDj()
log.debug("Source disconnected. Current broadcaster was: #{dj_name}")
if (dj_name != "") then
_ = azuracast_api_call(
timeout_ms=5000,
"djoff",
json.stringify({user = dj_name})
)
end
end
# Handle parsing of username:password strings from legacy clients
def ingest.parseCredentials(login) =
if (login.user == "source" or login.user == "") and (string.match(pattern="(:|,)+", login.password)) then
auth_string = string.split(separator="(:|,)", login.password)
{user = list.nth(default="", auth_string, 0),
password = list.nth(default="", auth_string, 2)}
else
{user = login.user, password = login.password}
end
end
# Create a studio source
# — These sources have a single fixed password baked into the configuration.
def ingest.makeStudioSource(studioName, ~mount, ~username="source", ~password, ~dropMetadata=false, ~alertOnDisconnect=false, ~highPriority=false) =
# Register source
ingest.registerSource(studioName, highPriority)
def studioAuth(login) =
auth_info = ingest.parseCredentials(login)
if ((auth_info.user == username) and (auth_info.password == password )) then
ingest.connections := list.add((studioName, username), !ingest.connections)
log.info("Studio connected: #{username}")
true
else
ingest.connections := list.assoc.remove.all(studioName, !ingest.connections)
log.important("Studio authentication failed: #{username}")
false
end
end
# When a studio connects, announce to monitoring destinations
def connected(header) =
log.info("#{studioName} source connected! - #{header}")
slack.log(":zap: #{studioName} source connected (*#{ingest.djFor(studioName)}*)")
# Trigger global connection handler, which will update on-air metadata if
# this studio is top of the precedence stack
ingest.onDjConnect()
end
# When a studio disconnects, announce to monitoring destinations
def disconnected() =
log("#{studioName} disconnected!")
slack.log(":end: #{studioName} disconnected (*#{ingest.djFor(studioName)}*)")
# AlertOnDisconnect sends an extra message to our #alerts channel
if (alertOnDisconnect) then
slack.log(channel="alerts", ":bangbang: #{studioName} streamer disconnected (*#{ingest.djFor(studioName)}*)")
end
ingest.onDjDisconnect()
# Clear studio DJ variables
ingest.connections := list.assoc.remove.all(studioName, !ingest.connections)
# Reset metadata for other remaining connected streams
ingest.onDjConnect()
end
# Create an IceCast harbor for this studio
harbor = audio_to_stereo(input.harbor(mount, port = ingest.icecastPort, auth = studioAuth, icy = true, icy_metadata_charset = "UTF-8", metadata_charset = "UTF-8", on_connect = connected, on_disconnect = disconnected, buffer = 10., max = 15.))
ignore(output.dummy(harbor, fallible=true))
# Experiment: Monitor for connection instability/buffer emptiness
def interruption_notice() =
ignore(slack.log(channel="debug", ":leaves: #{studioName} source may be unstable or buffer empty (*#{ingest.djFor(studioName)}*)"))
end
harbor.on_leave(interruption_notice)
# Experiment with silence detection
def blank_warning() =
ignore(slack.log(channel="debug", ":mute: #{studioName} Silence detected on source (*#{ingest.djFor(studioName)}*)"))
end
ignore(blank.detect(
max_blank = 5.,
track_sensitive = false,
blank_warning,
harbor
))
# return the source
if (dropMetadata == true) then
drop_metadata(harbor)
else
harbor
end
end
# Create an remote DJ source authenticated against AzuraCast's 'streamers' database
def ingest.makeAzuraCastStreamerSource(studioName, ~mount, ~dropMetadata=false, ~highPriority=false) =
# Register source
ingest.registerSource(studioName, highPriority)
# Keep track of who the last DJ was so we can monitor when it changes.
lastDj = ref("")
def azuracastAuth(login) =
auth_info = ingest.parseCredentials(login)
response = azuracast_api_call(
timeout_ms=5000,
"auth",
json.stringify(auth_info)
)
authed = bool_of_string(response)
if (authed) then
lastDj := auth_info.user
log.debug("Set lastDj to: #{!lastDj} (#{auth_info.user})")
else
log.important("Remote DJ authentication failed: #{auth_info.user} authentication returned false")
end
authed
end
def remote_connected(header) =
dj = !lastDj
log.debug("Adding (#{studioName}, #{dj}) pair to active connections")
ingest.connections := list.add((studioName, dj), !ingest.connections)
log.info("#{studioName} connected! DJ: #{dj} - #{header}")
# Announce source connection
slack.log(":zap: #{studioName} source connected (*#{ingest.djFor(studioName)}*)")
# Trigger global connection handler, which will update on-air metadata if
# this source is top of the precedence stack
ingest.onDjConnect()
end
def remote_disconnected() =
log.debug("Remote Disconnected")
dj = ingest.djFor(studioName)
log("Remote DJ source disconnected! Was: #{dj}")
slack.log(":end: #{studioName} disconnected (*#{dj}* :micdrop:)")
ingest.onDjDisconnect()
# Clear studio DJ variables
ingest.connections := list.assoc.remove.all(studioName, !ingest.connections)
# Reset metadata for other remaining connected streams
ingest.onDjConnect()
end
harbor = audio_to_stereo(input.harbor(mount, port = ingest.icecastPort, auth = azuracastAuth, icy = true, icy_metadata_charset = "UTF-8", metadata_charset = "UTF-8", on_connect = remote_connected, on_disconnect = remote_disconnected, buffer = 10., max = 15.))
ignore(output.dummy(harbor, fallible=true))
# return the source
if (dropMetadata == true) then
drop_metadata(harbor)
else
harbor
end
end
# Create an remote DJ source authenticated against Creek's user database
def ingest.makeCreekStreamerSource(
studioName,
~mount,
~dropMetadata=false,
~alertOnDisconnect=false,
~authEndpoint="auth/stream",
~highPriority=false,
~productionEndpoint=true
) =
# Register source
if (productionEndpoint) then
ingest.registerSource(studioName, highPriority)
end
# Count successful connections within 10s period to catch ffmpeg crashes
let successCount = ref(0)
let successRestartThreshold = 10
let successRestartWindow = 10.
def reset_success_count() =
successCount := 0
end
# Keep track of who the last DJ was so we can monitor when it changes.
lastDj = ref("")
def creekAuth(login) =
auth_info = ingest.parseCredentials(login)
log.debug("Authenticating Creek DJ: #{auth_info.user}")
authResponse = bff.post(authEndpoint, data=[
("username", auth_info.user),
("password", auth_info.password)
])
log.debug("Creek DJ auth response: #{authResponse}")
let json.parse (authResult : {
authenticated: bool,
username: string,
display_name: string?,
show: string?,
start_time: string?,
end_time: string?,
reason: string?
}) = authResponse
if (authResult.authenticated) then
djName = "#{authResult.display_name ?? authResult.username}"
showName = "#{authResult.show}"
endTime = "#{authResult.end_time}"
lastDj := "#{djName}/#{showName} (#{authResult.username})"
log.debug("Set lastDj to: #{!lastDj}")
slack.log(channel="stream_auth", ":key: #{studioName} DJ authenticated: *#{djName}*/*#{showName}* (@#{authResult.username})")
slack.log(channel="stream_auth", "<@#{authResult.username}> :clock10: Remember to disconnect before *#{timestamp.friendly(endTime)}* when #{showName} ends!")
else
# Auth failed, get reason and push to Slack:
slack.log(channel="stream_auth", "<@#{authResult.username}> :octagonal_sign: #{studioName} authentication failed: Creek user @#{authResult.username} not authenticated because: *#{authResult.reason}*")
log.important("Creek DJ #{authResult.username} authentication failed: #{authResult.reason}")
end
authResult.authenticated
end
def remote_connected(header) =
dj = !lastDj
# Only record login in connection pool if this is a production endpoint
if (productionEndpoint) then
log.debug("Adding (#{studioName}, #{dj}) pair to active connections")
ingest.connections := list.add((studioName, dj), !ingest.connections)
def listToString(str, item) =
str ^ "#{fst(item)} => #{snd(item)}"
end
connectionsDebug = list.fold(listToString, "", !ingest.connections)
log.debug("Connections After Add: #{connectionsDebug}")
end
# HACK: Count successful connections in a short time window. If a DJ
# repeatedly, successfully reconnects within a short span, it's an indicator
# that the ingest server is crashing at the ffmpeg level. To remedy this, we
# restart the server.
# Clear the count afer successRestartWindow seconds (e.g. 10.)
if (!successCount == 0) then
thread.run(fast=false, delay=successRestartWindow, reset_success_count)
end
successCount := !successCount + 1
# If this is the nth successful connection within the window, presume crashing is occuring,
# and restart the server.
if (!successCount > successRestartThreshold) then
slack.log(":boom: #{dj} was booted from #{studioName} #{successRestartThreshold} times in #{successRestartWindow} seconds.")
slack.log(":boom: Ingest server is likely crashing. Automatic recovery triggered: Restarting Azurcast...")
log.info("#{studioName} ingest crashed! Automatic recovery triggering Azuracast restart...")
azuracast_public.call("backend/restart")
end
log.info("#{studioName} connected! DJ: #{dj} - #{header}")
# Announce source connection
slack.log(":zap: #{studioName} source connected (*#{dj}*)")
# Trigger global connection handler, which will update on-air metadata if
# this source is top of the precedence stack
if (productionEndpoint) then
ingest.onDjConnect()
end
end
def remote_disconnected() =
log.debug("Remote Disconnected")
dj = !lastDj
log("Remote DJ source disconnected! Was: #{dj}")
slack.log(":end: #{studioName} disconnected (*#{dj}* :micdrop:)")
# AlertOnDisconnect sends an extra message to our #alerts channel
if (alertOnDisconnect) then
slack.log(channel="alerts", ":bangbang: #{studioName} streamer disconnected (*#{ingest.djFor(studioName)}*)")
end