#!/usr/bin/liquidsoap

# Radio Susan — with track announcements

set("log.file.path", "/var/lib/radio/radio.log")
set("log.level", 3)
set("server.telnet", true)
set("server.telnet.port", 1234)
set("ffmpeg.content_type.parse_metadata", false)

# State file for track metadata exchange
state_file = "/var/lib/radio/track_state.json"

# Track counter
track_count = ref(0)

music = playlist(
  mode="randomize",
  reload=3600,
  reload_mode="watch",
  "/var/lib/radio/playlists/all.m3u"
)
music = drop_video(music)

# Write track metadata to state file on each new track
music = on_track(fun(m) -> begin
  track_count := !track_count + 1
  artist = m["artist"]
  title = m["title"]
  count = !track_count
  # Write JSON state file
  data = '{"artist":"#{artist}","title":"#{title}","count":#{string_of(count)}}'
  ignore(file.write(data=data, state_file))
  log("Track #{string_of(count)}: #{artist} - #{title}")
end, music)

# Jingles
jingles = playlist(
  mode="randomize",
  "/var/lib/radio/jingles"
)
jingles = drop_video(jingles)
jingles = amplify(3.0, jingles)

# Dynamic announcements
def get_announcement() =
  result = list.hd(default="", process.read.lines("/usr/bin/python3 /var/lib/radio/announce_tracks.py --state"))
  if result != "" then
    log("Announcement: #{result}")
    request.create(result)
  else
    # Fallback to a random jingle
    null()
  end
end

announcements = request.dynamic(get_announcement)
announcements = drop_video(announcements)
announcements = amplify(3.0, announcements)

# Rotate: 2 music tracks, then 1 announcement or jingle
radio = rotate(weights=[2, 1], [music, random(weights=[1, 1], [jingles, announcements])])

radio = mksafe(radio)

output.icecast(
  %mp3(bitrate=192),
  host="localhost",
  port=8910,
  password="REDACTED",
  mount="/stream",
  name="Radio Susan",
  description="Personal radio station",
  genre="Eclectic",
  url="https://radio.jihakuz.xyz",
  radio
)
