Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found
Select Git revision
  • dev-old
  • dev-old-david
  • develop
  • lars-tests
  • master
  • master-old
  • topic/filesystem-fallbacks
  • topic/tank_connection
  • topic/tank_connection_david
  • user/equinox/docker
10 results

Target

Select target project
  • aura/engine
  • hermannschwaerzler/engine
  • sumpfralle/aura-engine
3 results
Select Git revision
  • 122-synchronized-ci
  • feat-use-docker-main-tag
  • fix-aura-sysuser
  • fix-broken-pipe-153
  • fix-docker-release
  • fix-push-latest-with-tag
  • fix-streamchannel-retries
  • gitlab-templates
  • improve-test-coverage-137
  • improve-test-coverage-143
  • main
  • orm-less-scheduling
  • remove-mailer
  • update-changelog-alpha3
  • virtual-timeslots-131
  • 1.0.0-alpha1
  • 1.0.0-alpha2
  • 1.0.0-alpha3
  • 1.0.0-alpha4
  • 1.0.0-alpha5
20 results
Show changes
Showing
with 2609 additions and 0 deletions
if bitrate == 24 then
# if stereo then
ignore(output_filesystem_stereo(%fdkaac(bitrate = 24, channels = 2), filenamepattern, !source))
# else
# ignore(output_filesystem_mono(%fdkaac(bitrate = 24, channels = 1), filenamepattern, mean(!source)))
# end
elsif bitrate == 32 then
# if stereo then
ignore(output_filesystem_stereo(%fdkaac(bitrate = 32, channels = 2), filenamepattern, !source))
# else
# ignore(output_filesystem_mono(%fdkaac(bitrate = 32, channels = 1), filenamepattern, mean(!source)))
# end
elsif bitrate == 48 then
# if stereo then
ignore(output_filesystem_stereo(%fdkaac(bitrate = 48, channels = 2), filenamepattern, !source))
# else
# ignore(output_filesystem_mono(%fdkaac(bitrate = 48, channels = 1), filenamepattern, mean(!source)))
# end
elsif bitrate == 64 then
# if stereo then
ignore(output_filesystem_stereo(%fdkaac(bitrate = 64, channels = 2), filenamepattern, !source))
# else
# ignore(output_filesystem_mono(%fdkaac(bitrate = 64, channels = 1), filenamepattern, mean(!source)))
# end
elsif bitrate == 96 then
# if stereo then
ignore(output_filesystem_stereo(%fdkaac(bitrate = 96, channels = 2), filenamepattern, !source))
# else
# ignore(output_filesystem_mono(%fdkaac(bitrate = 96, channels = 1), filenamepattern, mean(!source)))
# end
elsif bitrate == 128 then
# if stereo then
ignore(output_filesystem_stereo(%fdkaac(bitrate = 128, channels = 2), filenamepattern, !source))
# else
# ignore(output_filesystem_mono(%fdkaac(bitrate = 128, channels = 1), filenamepattern, mean(!source)))
# end
elsif bitrate == 160 then
# if stereo then
ignore(output_filesystem_stereo(%fdkaac(bitrate = 160, channels = 2), filenamepattern, !source))
# else
# ignore(output_filesystem_mono(%fdkaac(bitrate = 160, channels = 1), filenamepattern, mean(!source)))
# end
elsif bitrate == 192 then
# if stereo then
ignore(output_filesystem_stereo(%fdkaac(bitrate = 192, channels = 2), filenamepattern, !source))
# else
# ignore(output_filesystem_mono(%fdkaac(bitrate = 192, channels = 1), filenamepattern, mean(!source)))
# end
elsif bitrate == 224 then
# if stereo then
ignore(output_filesystem_stereo(%fdkaac(bitrate = 224, channels = 2), filenamepattern, !source))
# else
# ignore(output_filesystem_mono(%fdkaac(bitrate = 224, channels = 1), filenamepattern, mean(!source)))
# end
elsif bitrate == 256 then
# if stereo then
ignore(output_filesystem_stereo(%fdkaac(bitrate = 256, channels = 2), filenamepattern, !source))
# else
# ignore(output_filesystem_mono(%fdkaac(bitrate = 256, channels = 1), filenamepattern, mean(!source)))
# end
elsif bitrate == 320 then
# if stereo then
ignore(output_filesystem_stereo(%fdkaac(bitrate = 320, channels = 2), filenamepattern, !source))
# else
# ignore(output_filesystem_mono(%fdkaac(bitrate = 320, channels = 1), filenamepattern, mean(!source)))
# end
end
if bitrate == 24 or bitrate == 32 or bitrate == 48 then
if stereo then
ignore(output_filesystem_stereo(%flac(samplerate=44100, channels = 2, compression = 7, bits_per_sample=8), filenamepattern, !source))
else
ignore(output_filesystem_mono(%flac(samplerate=44100, channels = 1, compression = 7, bits_per_sample=8), filenamepattern, mean(!source)))
end
elsif bitrate == 64 then
if stereo then
ignore(output_filesystem_stereo(%flac(samplerate=44100, channels = 2, compression = 7, bits_per_sample=8), filenamepattern, !source))
else
ignore(output_filesystem_mono(%flac(samplerate=44100, channels = 1, compression = 7, bits_per_sample=8), filenamepattern, mean(!source)))
end
elsif bitrate == 96 then
if stereo then
ignore(output_filesystem_stereo(%flac(samplerate=44100, channels = 2, compression = 7, bits_per_sample=8), filenamepattern, !source))
else
ignore(output_filesystem_mono(%flac(samplerate=44100, channels = 1, compression = 7, bits_per_sample=8), filenamepattern, mean(!source)))
end
elsif bitrate == 128 then
if stereo then
ignore(output_filesystem_stereo(%flac(samplerate=44100, channels = 2, compression = 6, bits_per_sample=16), filenamepattern, !source))
else
ignore(output_filesystem_mono(%flac(samplerate=44100, channels = 1, compression = 6, bits_per_sample=16), filenamepattern, mean(!source)))
end
elsif bitrate == 160 then
if stereo then
ignore(output_filesystem_stereo(%flac(samplerate=44100, channels = 2, compression = 5, bits_per_sample=16), filenamepattern, !source))
else
ignore(output_filesystem_mono(%flac(samplerate=44100, channels = 1, compression = 5, bits_per_sample=16), filenamepattern, mean(!source)))
end
elsif bitrate == 192 then
if stereo then
ignore(output_filesystem_stereo(%flac(samplerate=44100, channels = 2, compression = 4, bits_per_sample=16), filenamepattern, !source))
else
ignore(output_filesystem_mono(%flac(samplerate=44100, channels = 1, compression = 4, bits_per_sample=16), filenamepattern, mean(!source)))
end
elsif bitrate == 224 then
if stereo then
ignore(output_filesystem_stereo(%flac(samplerate=44100, channels = 2, compression = 3, bits_per_sample=32), filenamepattern, !source))
else
ignore(output_filesystem_mono(%flac(samplerate=44100, channels = 1, compression = 3, bits_per_sample=32), filenamepattern, mean(!source)))
end
elsif bitrate == 256 then
if stereo then
ignore(output_filesystem_stereo(%flac(samplerate=44100, channels = 2, compression = 2, bits_per_sample=32), filenamepattern, !source))
else
ignore(output_filesystem_mono(%flac(samplerate=44100, channels = 1, compression = 2, bits_per_sample=32), filenamepattern, mean(!source)))
end
elsif bitrate == 320 then
if stereo then
ignore(output_filesystem_stereo(%flac(samplerate=44100, channels = 2, compression = 1, bits_per_sample=32), filenamepattern, !source))
else
ignore(output_filesystem_mono(%flac(samplerate=44100, channels = 1, compression = 1, bits_per_sample=32), filenamepattern, mean(!source)))
end
end
if bitrate == 24 then
if stereo then
ignore(output_filesystem_stereo(%mp3(bitrate = 24, stereo = true), filenamepattern, !source))
else
ignore(output_filesystem_mono(%mp3(bitrate = 24, stereo = false), filenamepattern, mean(!source)))
end
elsif bitrate == 32 then
if stereo then
ignore(output_filesystem_stereo(%mp3(bitrate = 32, stereo = true), filenamepattern, !source))
else
ignore(output_filesystem_mono(%mp3(bitrate = 32, stereo = false), filenamepattern, mean(!source)))
end
elsif bitrate == 48 then
if stereo then
ignore(output_filesystem_stereo(%mp3(bitrate = 48, stereo = true), filenamepattern, !source))
else
ignore(output_filesystem_mono(%mp3(bitrate = 48, stereo = false), filenamepattern, mean(!source)))
end
elsif bitrate == 64 then
if stereo then
ignore(output_filesystem_stereo(%mp3(bitrate = 64, stereo = true), filenamepattern, !source))
else
ignore(output_filesystem_mono(%mp3(bitrate = 64, stereo = false), filenamepattern, mean(!source)))
end
elsif bitrate == 96 then
if stereo then
ignore(output_filesystem_stereo(%mp3(bitrate = 96, stereo = true), filenamepattern, !source))
else
ignore(output_filesystem_mono(%mp3(bitrate = 96, stereo = false), filenamepattern, mean(!source)))
end
elsif bitrate == 128 then
if stereo then
ignore(output_filesystem_stereo(%mp3(bitrate = 128, stereo = true), filenamepattern, !source))
else
ignore(output_filesystem_mono(%mp3(bitrate = 128, stereo = false), filenamepattern, mean(!source)))
end
elsif bitrate == 160 then
if stereo then
ignore(output_filesystem_stereo(%mp3(bitrate = 160, stereo = true), filenamepattern, !source))
else
ignore(output_filesystem_mono(%mp3(bitrate = 160, stereo = false), filenamepattern, mean(!source)))
end
elsif bitrate == 192 then
if stereo then
ignore(output_filesystem_stereo(%mp3(bitrate = 192, stereo = true), filenamepattern, !source))
else
ignore(output_filesystem_mono(%mp3(bitrate = 192, stereo = false), filenamepattern, mean(!source)))
end
elsif bitrate == 224 then
if stereo then
ignore(output_filesystem_stereo(%mp3(bitrate = 224, stereo = true), filenamepattern, !source))
else
ignore(output_filesystem_mono(%mp3(bitrate = 224, stereo = false), filenamepattern, mean(!source)))
end
elsif bitrate == 256 then
if stereo then
ignore(output_filesystem_stereo(%mp3(bitrate = 256, stereo = true), filenamepattern, !source))
else
ignore(output_filesystem_mono(%mp3(bitrate = 256, stereo = false), filenamepattern, mean(!source)))
end
elsif bitrate == 320 then
if stereo then
ignore(output_filesystem_stereo(%mp3(bitrate = 320, stereo = true), filenamepattern, !source))
else
ignore(output_filesystem_mono(%mp3(bitrate = 320, stereo = false), filenamepattern, mean(!source)))
end
end
if bitrate == 24 or bitrate == 32 or bitrate == 48 then
if stereo then
ignore(output_filesystem_stereo(%vorbis(quality=-0.1, channels = 2), filenamepattern, !source))
else
ignore(output_filesystem_mono(%vorbis(quality=-0.1, channels = 1), filenamepattern, mean(!source)))
end
elsif bitrate == 64 then
if stereo then
ignore(output_filesystem_stereo(%vorbis(quality=0, channels = 2), filenamepattern, !source))
else
ignore(output_filesystem_mono(%vorbis(quality=0, channels = 1), filenamepattern, mean(!source)))
end
elsif bitrate == 96 then
if stereo then
ignore(output_filesystem_stereo(%vorbis(quality=0.2, channels = 2), filenamepattern, !source))
else
ignore(output_filesystem_mono(%vorbis(quality=0.2, channels = 1), filenamepattern, mean(!source)))
end
elsif bitrate == 128 then
if stereo then
ignore(output_filesystem_stereo(%vorbis(quality=0.4, channels = 2), filenamepattern, !source))
else
ignore(output_filesystem_mono(%vorbis(quality=0.4, channels = 1), filenamepattern, mean(!source)))
end
elsif bitrate == 160 then
if stereo then
ignore(output_filesystem_stereo(%vorbis(quality=0.5, channels = 2), filenamepattern, !source))
else
ignore(output_filesystem_mono(%vorbis(quality=0.5, channels = 1), filenamepattern, mean(!source)))
end
elsif bitrate == 192 then
if stereo then
ignore(output_filesystem_stereo(%vorbis(quality=0.6, channels = 2), filenamepattern, !source))
else
ignore(output_filesystem_mono(%vorbis(quality=0.6, channels = 1), filenamepattern, mean(!source)))
end
elsif bitrate == 224 then
if stereo then
ignore(output_filesystem_stereo(%vorbis(quality=0.7, channels = 2), filenamepattern, !source))
else
ignore(output_filesystem_mono(%vorbis(quality=0.7, channels = 1), filenamepattern, mean(!source)))
end
elsif bitrate == 256 then
if stereo then
ignore(output_filesystem_stereo(%vorbis(quality=0.8, channels = 2), filenamepattern, !source))
else
ignore(output_filesystem_mono(%vorbis(quality=0.8, channels = 1), filenamepattern, mean(!source)))
end
elsif bitrate == 320 then
if stereo then
ignore(output_filesystem_stereo(%vorbis(quality=0.9, channels = 2), filenamepattern, !source))
else
ignore(output_filesystem_mono(%vorbis(quality=0.9, channels = 1), filenamepattern, mean(!source)))
end
end
if bitrate == 24 then
if stereo then
ignore(output_filesystem_stereo(%opus(bitrate = 24, channels = 2, signal="music", application="audio", complexity=10, vbr="constrained"), filenamepattern, !source))
else
ignore(output_filesystem_mono(%opus(bitrate = 24, channels = 1, signal="music", application="audio", complexity=10, vbr="constrained"), filenamepattern, mean(!source)))
end
elsif bitrate == 32 then
if stereo then
ignore(output_filesystem_stereo(%opus(bitrate = 32, channels = 2, signal="music", application="audio", complexity=10, vbr="constrained"), filenamepattern, !source))
else
ignore(output_filesystem_mono(%opus(bitrate = 32, channels = 1, signal="music", application="audio", complexity=10, vbr="constrained"), filenamepattern, mean(!source)))
end
elsif bitrate == 48 then
if stereo then
ignore(output_filesystem_stereo(%opus(bitrate = 48, channels = 2, signal="music", application="audio", complexity=10, vbr="constrained"), filenamepattern, !source))
else
ignore(output_filesystem_mono(%opus(bitrate = 48, channels = 1, signal="music", application="audio", complexity=10, vbr="constrained"), filenamepattern, mean(!source)))
end
elsif bitrate == 64 then
if stereo then
ignore(output_filesystem_stereo(%opus(bitrate = 64, channels = 2, signal="music", application="audio", complexity=10, vbr="constrained"), filenamepattern, !source))
else
ignore(output_filesystem_mono(%opus(bitrate = 64, channels = 1, signal="music", application="audio", complexity=10, vbr="constrained"), filenamepattern, mean(!source)))
end
elsif bitrate == 96 then
if stereo then
ignore(output_filesystem_stereo(%opus(bitrate = 96, channels = 2, signal="music", application="audio", complexity=10, vbr="constrained"), filenamepattern, !source))
else
ignore(output_filesystem_mono(%opus(bitrate = 96, channels = 1, signal="music", application="audio", complexity=10, vbr="constrained"), filenamepattern, mean(!source)))
end
elsif bitrate == 128 then
if stereo then
ignore(output_filesystem_stereo(%opus(bitrate = 128, channels = 2, signal="music", application="audio", complexity=10, vbr="constrained"), filenamepattern, !source))
else
ignore(output_filesystem_mono(%opus(bitrate = 128, channels = 1, signal="music", application="audio", complexity=10, vbr="constrained"), filenamepattern, mean(!source)))
end
elsif bitrate == 160 then
if stereo then
ignore(output_filesystem_stereo(%opus(bitrate = 160, channels = 2, signal="music", application="audio", complexity=10, vbr="constrained"), filenamepattern, !source))
else
ignore(output_filesystem_mono(%opus(bitrate = 160, channels = 1, signal="music", application="audio", complexity=10, vbr="constrained"), filenamepattern, mean(!source)))
end
elsif bitrate == 192 then
if stereo then
ignore(output_filesystem_stereo(%opus(bitrate = 192, channels = 2, signal="music", application="audio", complexity=10, vbr="constrained"), filenamepattern, !source))
else
ignore(output_filesystem_mono(%opus(bitrate = 192, channels = 1, signal="music", application="audio", complexity=10, vbr="constrained"), filenamepattern, mean(!source)))
end
elsif bitrate == 224 then
if stereo then
ignore(output_filesystem_stereo(%opus(bitrate = 224, channels = 2, signal="music", application="audio", complexity=10, vbr="constrained"), filenamepattern, !source))
else
ignore(output_filesystem_mono(%opus(bitrate = 224, channels = 1, signal="music", application="audio", complexity=10, vbr="constrained"), filenamepattern, mean(!source)))
end
elsif bitrate == 256 then
if stereo then
ignore(output_filesystem_stereo(%opus(bitrate = 256, channels = 2, signal="music", application="audio", complexity=10, vbr="constrained"), filenamepattern, !source))
else
ignore(output_filesystem_mono(%opus(bitrate = 256, channels = 1, signal="music", application="audio", complexity=10, vbr="constrained"), filenamepattern, mean(!source)))
end
elsif bitrate == 320 then
if stereo then
ignore(output_filesystem_stereo(%opus(bitrate = 320, channels = 2, signal="music", application="audio", complexity=10, vbr="constrained"), filenamepattern, !source))
else
ignore(output_filesystem_mono(%opus(bitrate = 320, channels = 1, signal="music", application="audio", complexity=10, vbr="constrained"), filenamepattern, mean(!source)))
end
end
if bitrate <= 128 then
if stereo then
ignore(output_filesystem_stereo(%wav(stereo=true, channels=2, samplesize=8, header=true, duration=30.), filenamepattern, !source))
else
ignore(output_filesystem_mono(%wav(stereo=false, channels=1, samplesize=8, header=true, duration=30.), filenamepattern, mean(!source)))
end
else
if stereo then
ignore(output_filesystem_stereo(%wav(stereo=true, channels=2, samplesize=16, header=true, duration=30.), filenamepattern, !source))
else
ignore(output_filesystem_mono(%wav(stereo=false, channels=1, samplesize=16, header=true, duration=30.), filenamepattern, mean(!source)))
end
end
\ No newline at end of file
if bitrate == 24 then
if stereo then
ignore(output_icecast_stereo(%aac(bitrate = 24, channels = 2), !source))
else
ignore(output_icecast_mono(%aac(bitrate = 24, channels = 1), mean(!source)))
end
elsif bitrate == 32 then
if stereo then
ignore(output_icecast_stereo(%aac(bitrate = 32, channels = 2), !source))
else
ignore(output_icecast_mono(%aac(bitrate = 32, channels = 1), mean(!source)))
end
elsif bitrate == 48 then
if stereo then
ignore(output_icecast_stereo(%aac(bitrate = 48, channels = 2), !source))
else
ignore(output_icecast_mono(%aac(bitrate = 48, channels = 1), mean(!source)))
end
elsif bitrate == 64 then
if stereo then
ignore(output_icecast_stereo(%aac(bitrate = 64, channels = 2), !source))
else
ignore(output_icecast_mono(%aac(bitrate = 64, channels = 1), mean(!source)))
end
elsif bitrate == 96 then
if stereo then
ignore(output_icecast_stereo(%aac(bitrate = 96, channels = 2), !source))
else
ignore(output_icecast_mono(%aac(bitrate = 96, channels = 1), mean(!source)))
end
elsif bitrate == 128 then
if stereo then
ignore(output_icecast_stereo(%aac(bitrate = 128, channels = 2), !source))
else
ignore(output_icecast_mono(%aac(bitrate = 128, channels = 1), mean(!source)))
end
elsif bitrate == 160 then
if stereo then
ignore(output_icecast_stereo(%aac(bitrate = 160, channels = 2), !source))
else
ignore(output_icecast_mono(%aac(bitrate = 160, channels = 1), mean(!source)))
end
elsif bitrate == 192 then
if stereo then
ignore(output_icecast_stereo(%aac(bitrate = 192, channels = 2), !source))
else
ignore(output_icecast_mono(%aac(bitrate = 192, channels = 1), mean(!source)))
end
elsif bitrate == 224 then
if stereo then
ignore(output_icecast_stereo(%aac(bitrate = 224, channels = 2), !source))
else
ignore(output_icecast_mono(%aac(bitrate = 224, channels = 1), mean(!source)))
end
elsif bitrate == 256 then
if stereo then
ignore(output_icecast_stereo(%aac(bitrate = 256, channels = 2), !source))
else
ignore(output_icecast_mono(%aac(bitrate = 256, channels = 1), mean(!source)))
end
elsif bitrate == 320 then
if stereo then
ignore(output_icecast_stereo(%aac(bitrate = 320, channels = 2), !source))
else
ignore(output_icecast_mono(%aac(bitrate = 320, channels = 1), mean(!source)))
end
end
if not icecast_vorbis_metadata then
source := add(normalize=false, [amplify(0.00001, noise()), !source])
end
if bitrate == 24 or bitrate == 32 or bitrate == 48 then
if stereo then
ignore(output_icecast_stereo(%flac(samplerate=44100, channels = 2, compression = 7, bits_per_sample=8), !source))
else
ignore(output_icecast_mono(%flac(samplerate=44100, channels = 1, compression = 7, bits_per_sample=8), mean(!source)))
end
elsif bitrate == 64 then
if stereo then
ignore(output_icecast_stereo(%flac(samplerate=44100, channels = 2, compression = 7, bits_per_sample=8), !source))
else
ignore(output_icecast_mono(%flac(samplerate=44100, channels = 1, compression = 7, bits_per_sample=8), mean(!source)))
end
elsif bitrate == 96 then
if stereo then
ignore(output_icecast_stereo(%flac(samplerate=44100, channels = 2, compression = 7, bits_per_sample=8), !source))
else
ignore(output_icecast_mono(%flac(samplerate=44100, channels = 1, compression = 7, bits_per_sample=8), mean(!source)))
end
elsif bitrate == 128 then
if stereo then
ignore(output_icecast_stereo(%flac(samplerate=44100, channels = 2, compression = 6, bits_per_sample=16), !source))
else
ignore(output_icecast_mono(%flac(samplerate=44100, channels = 1, compression = 6, bits_per_sample=16), mean(!source)))
end
elsif bitrate == 160 then
if stereo then
ignore(output_icecast_stereo(%flac(samplerate=44100, channels = 2, compression = 5, bits_per_sample=16), !source))
else
ignore(output_icecast_mono(%flac(samplerate=44100, channels = 1, compression = 5, bits_per_sample=16), mean(!source)))
end
elsif bitrate == 192 then
if stereo then
ignore(output_icecast_stereo(%flac(samplerate=44100, channels = 2, compression = 4, bits_per_sample=16), !source))
else
ignore(output_icecast_mono(%flac(samplerate=44100, channels = 1, compression = 4, bits_per_sample=16), mean(!source)))
end
elsif bitrate == 224 then
if stereo then
ignore(output_icecast_stereo(%flac(samplerate=44100, channels = 2, compression = 3, bits_per_sample=32), !source))
else
ignore(output_icecast_mono(%flac(samplerate=44100, channels = 1, compression = 3, bits_per_sample=32), mean(!source)))
end
elsif bitrate == 256 then
if stereo then
ignore(output_icecast_stereo(%flac(samplerate=44100, channels = 2, compression = 2, bits_per_sample=32), !source))
else
ignore(output_icecast_mono(%flac(samplerate=44100, channels = 1, compression = 2, bits_per_sample=32), mean(!source)))
end
elsif bitrate == 320 then
if stereo then
ignore(output_icecast_stereo(%flac(samplerate=44100, channels = 2, compression = 1, bits_per_sample=32), !source))
else
ignore(output_icecast_mono(%flac(samplerate=44100, channels = 1, compression = 1, bits_per_sample=32), mean(!source)))
end
end
if bitrate == 24 then
if stereo then
ignore(output_icecast_stereo(%mp3(bitrate = 24, stereo = true), !source))
else
ignore(output_icecast_mono(%mp3(bitrate = 24, stereo = false), mean(!source)))
end
elsif bitrate == 32 then
if stereo then
ignore(output_icecast_stereo(%mp3(bitrate = 32, stereo = true), !source))
else
ignore(output_icecast_mono(%mp3(bitrate = 32, stereo = false), mean(!source)))
end
elsif bitrate == 48 then
if stereo then
ignore(output_icecast_stereo(%mp3(bitrate = 48, stereo = true), !source))
else
ignore(output_icecast_mono(%mp3(bitrate = 48, stereo = false), mean(!source)))
end
elsif bitrate == 64 then
if stereo then
ignore(output_icecast_stereo(%mp3(bitrate = 64, stereo = true), !source))
else
ignore(output_icecast_mono(%mp3(bitrate = 64, stereo = false), mean(!source)))
end
elsif bitrate == 96 then
if stereo then
ignore(output_icecast_stereo(%mp3(bitrate = 96, stereo = true), !source))
else
ignore(output_icecast_mono(%mp3(bitrate = 96, stereo = false), mean(!source)))
end
elsif bitrate == 128 then
if stereo then
ignore(output_icecast_stereo(%mp3(bitrate = 128, stereo = true), !source))
else
ignore(output_icecast_mono(%mp3(bitrate = 128, stereo = false), mean(!source)))
end
elsif bitrate == 160 then
if stereo then
ignore(output_icecast_stereo(%mp3(bitrate = 160, stereo = true), !source))
else
ignore(output_icecast_mono(%mp3(bitrate = 160, stereo = false), mean(!source)))
end
elsif bitrate == 192 then
if stereo then
ignore(output_icecast_stereo(%mp3(bitrate = 192, stereo = true), !source))
else
ignore(output_icecast_mono(%mp3(bitrate = 192, stereo = false), mean(!source)))
end
elsif bitrate == 224 then
if stereo then
ignore(output_icecast_stereo(%mp3(bitrate = 224, stereo = true), !source))
else
ignore(output_icecast_mono(%mp3(bitrate = 224, stereo = false), mean(!source)))
end
elsif bitrate == 256 then
if stereo then
ignore(output_icecast_stereo(%mp3(bitrate = 256, stereo = true), !source))
else
ignore(output_icecast_mono(%mp3(bitrate = 256, stereo = false), mean(!source)))
end
elsif bitrate == 320 then
if stereo then
ignore(output_icecast_stereo(%mp3(bitrate = 320, stereo = true), !source))
else
ignore(output_icecast_mono(%mp3(bitrate = 320, stereo = false), mean(!source)))
end
end
if not icecast_vorbis_metadata then
source := add(normalize=false, [amplify(0.00001, noise()), !source])
end
if bitrate == 24 or bitrate == 32 or bitrate == 48 then
if stereo then
ignore(output_icecast_stereo(%vorbis(quality=-0.1, channels = 2), !source))
else
ignore(output_icecast_mono(%vorbis(quality=-0.1, channels = 1), mean(!source)))
end
elsif bitrate == 64 then
if stereo then
ignore(output_icecast_stereo(%vorbis(quality=0, channels = 2), !source))
else
ignore(output_icecast_mono(%vorbis(quality=0, channels = 1), mean(!source)))
end
elsif bitrate == 96 then
if stereo then
ignore(output_icecast_stereo(%vorbis(quality=0.2, channels = 2), !source))
else
ignore(output_icecast_mono(%vorbis(quality=0.2, channels = 1), mean(!source)))
end
elsif bitrate == 128 then
if stereo then
ignore(output_icecast_stereo(%vorbis(quality=0.4, channels = 2), !source))
else
ignore(output_icecast_mono(%vorbis(quality=0.4, channels = 1), mean(!source)))
end
elsif bitrate == 160 then
if stereo then
ignore(output_icecast_stereo(%vorbis(quality=0.5, channels = 2), !source))
else
ignore(output_icecast_mono(%vorbis(quality=0.5, channels = 1), mean(!source)))
end
elsif bitrate == 192 then
if stereo then
ignore(output_icecast_stereo(%vorbis(quality=0.6, channels = 2), !source))
else
ignore(output_icecast_mono(%vorbis(quality=0.6, channels = 1), mean(!source)))
end
elsif bitrate == 224 then
if stereo then
ignore(output_icecast_stereo(%vorbis(quality=0.7, channels = 2), !source))
else
ignore(output_icecast_mono(%vorbis(quality=0.7, channels = 1), mean(!source)))
end
elsif bitrate == 256 then
if stereo then
ignore(output_icecast_stereo(%vorbis(quality=0.8, channels = 2), !source))
else
ignore(output_icecast_mono(%vorbis(quality=0.8, channels = 1), mean(!source)))
end
elsif bitrate == 320 then
if stereo then
ignore(output_icecast_stereo(%vorbis(quality=0.9, channels = 2), !source))
else
ignore(output_icecast_mono(%vorbis(quality=0.9, channels = 1), mean(!source)))
end
end
if bitrate == 24 then
if stereo then
ignore(output_icecast_stereo(%opus(bitrate = 24, channels = 2, signal="music", application="audio", complexity=10, vbr="constrained"), !source))
else
ignore(output_icecast_mono(%opus(bitrate = 24, channels = 1, signal="music", application="audio", complexity=10, vbr="constrained"), mean(!source)))
end
elsif bitrate == 32 then
if stereo then
ignore(output_icecast_stereo(%opus(bitrate = 32, channels = 2, signal="music", application="audio", complexity=10, vbr="constrained"), !source))
else
ignore(output_icecast_mono(%opus(bitrate = 32, channels = 1, signal="music", application="audio", complexity=10, vbr="constrained"), mean(!source)))
end
elsif bitrate == 48 then
if stereo then
ignore(output_icecast_stereo(%opus(bitrate = 48, channels = 2, signal="music", application="audio", complexity=10, vbr="constrained"), !source))
else
ignore(output_icecast_mono(%opus(bitrate = 48, channels = 1, signal="music", application="audio", complexity=10, vbr="constrained"), mean(!source)))
end
elsif bitrate == 64 then
if stereo then
ignore(output_icecast_stereo(%opus(bitrate = 64, channels = 2, signal="music", application="audio", complexity=10, vbr="constrained"), !source))
else
ignore(output_icecast_mono(%opus(bitrate = 64, channels = 1, signal="music", application="audio", complexity=10, vbr="constrained"), mean(!source)))
end
elsif bitrate == 96 then
if stereo then
ignore(output_icecast_stereo(%opus(bitrate = 96, channels = 2, signal="music", application="audio", complexity=10, vbr="constrained"), !source))
else
ignore(output_icecast_mono(%opus(bitrate = 96, channels = 1, signal="music", application="audio", complexity=10, vbr="constrained"), mean(!source)))
end
elsif bitrate == 128 then
if stereo then
ignore(output_icecast_stereo(%opus(bitrate = 128, channels = 2, signal="music", application="audio", complexity=10, vbr="constrained"), !source))
else
ignore(output_icecast_mono(%opus(bitrate = 128, channels = 1, signal="music", application="audio", complexity=10, vbr="constrained"), mean(!source)))
end
elsif bitrate == 160 then
if stereo then
ignore(output_icecast_stereo(%opus(bitrate = 160, channels = 2, signal="music", application="audio", complexity=10, vbr="constrained"), !source))
else
ignore(output_icecast_mono(%opus(bitrate = 160, channels = 1, signal="music", application="audio", complexity=10, vbr="constrained"), mean(!source)))
end
elsif bitrate == 192 then
if stereo then
ignore(output_icecast_stereo(%opus(bitrate = 192, channels = 2, signal="music", application="audio", complexity=10, vbr="constrained"), !source))
else
ignore(output_icecast_mono(%opus(bitrate = 192, channels = 1, signal="music", application="audio", complexity=10, vbr="constrained"), mean(!source)))
end
elsif bitrate == 224 then
if stereo then
ignore(output_icecast_stereo(%opus(bitrate = 224, channels = 2, signal="music", application="audio", complexity=10, vbr="constrained"), !source))
else
ignore(output_icecast_mono(%opus(bitrate = 224, channels = 1, signal="music", application="audio", complexity=10, vbr="constrained"), mean(!source)))
end
elsif bitrate == 256 then
if stereo then
ignore(output_icecast_stereo(%opus(bitrate = 256, channels = 2, signal="music", application="audio", complexity=10, vbr="constrained"), !source))
else
ignore(output_icecast_mono(%opus(bitrate = 256, channels = 1, signal="music", application="audio", complexity=10, vbr="constrained"), mean(!source)))
end
elsif bitrate == 320 then
if stereo then
ignore(output_icecast_stereo(%opus(bitrate = 320, channels = 2, signal="music", application="audio", complexity=10, vbr="constrained"), !source))
else
ignore(output_icecast_mono(%opus(bitrate = 320, channels = 1, signal="music", application="audio", complexity=10, vbr="constrained"), mean(!source)))
end
end
#################
# Read INI File #
#################
debug = false
def read_ini(file)
# read ini file
settings_file_content = get_process_lines("cat "^file )
# one entry stored as ["setting_name", "setting"]
settings_map = list.map(string.split(separator="="), settings_file_content)
def filter_pair(setting_pair) =
if debug then
print(" +++ IN FILTER_PAIR +++")
end
# get head of settings_pair
setting_name = list.hd(default="", setting_pair)
if debug then
print(" -- setting_name:")
print(setting_name)
end
# settings in ini are with '"', so read them with high comma
setting_unfiltered = list.nth(default="", setting_pair, 1)
if debug then
print(" -- setting_unfiltered:")
print(setting_unfiltered)
end
# filter high comma out. why the hell comes an array ["1", setting] returned?
# the filter patterns are perl regex
setting = string.extract(pattern='"(.*)"', setting_unfiltered)
if debug then
print(" -- setting ( after string.extract):")
print(setting['1'])
end
filtered_pair = [(setting_name, setting['1'])]
if debug then
print(" -- filter_pair returning: --")
print(filtered_pair)
end
# return filtered_pair
filtered_pair
end
def filter_map(filled_list, next_element) =
# if debug then
# print(" +++ IN FILTER_MAP +++")
# print(" .. length of filled_list: ")
# print(list.length(filled_list))
# print(" .. next_element")
# print(next_element)
# end
# the normal case: settingname and its setting
if list.length(next_element) >= 2 then
if debug then
print(" ===> LENGTH list to insert in settings_list is equal TWO! <===")
print(" -- next_element")
print(next_element)
end
setting_pair = filter_pair(next_element)
# add settings_pair to liquidsoap list
#list.add(setting_pair, filled_list)
list.append(setting_pair, filled_list)
else
if list.length(next_element) >= 1 then
if debug then
print(" ===> LENGTH of list to insert in settings_list is equal ONE! <===")
print(" -- next_element")
print(next_element)
end
#
list.append([(list.hd(default="",next_element), "")], filled_list)
else
if debug then
print(" ===> LENGTH of list to insert in settings_list is greater then two or less than one <===")
print(" -- next_element")
print(next_element)
end
# return the list as is
filled_list
end
end
end
# get install dir
pwd = get_process_lines("pwd") # returns an array
absolute_path = list.hd(default="", pwd) # grabs head of array (pwd only returns one line which is our desired result)
install_dir = '"' ^ path.dirname(path.dirname(absolute_path)) ^ '"' # pre and append " for filter_pair function. otherwise this setting would be lost through regex and fold function below would be imho much more difficult to read
# add installdir to the loaded settings from ini file
#settings_map = list.add(["install_dir", install_dir], settings_map)
# list.fold param description:
# f(a,b,c)
# a) a function which is fold
# b) the list which is to be filled (optional with already containing elements)
# c) from this list every element is taken, function applied and inserted into b
# fold function without pre and appended "
settings = list.fold(filter_map, [("install_dir", install_dir)], settings_map)
#settings = list.fold(filter_map, [], settings_map)
if debug then
print(settings)
end
settings
end
if debug then
ini = read_ini("/etc/aura/engine.ini")
print(ini)
print(list.assoc(default="", "install_dir", ini))
end
#
# engine
#
# Playout Daemon for autoradio project
#
#
# Copyright (C) 2017-2018 Gottfried Gaisbauer <gottfried.gaisbauer@servus.at>
#
# This file is part of engine.
#
# engine is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# any later version.
#
# engine is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with engine. If not, see <http://www.gnu.org/licenses/>.
#
# shutdown server function
#server.register(namespace='server',
# description="shutdown server",
# usage="stop",
# "stop",
# fun(x,y) -> shutdown )
#
# to reduce complexity of lqs => query 'mixer.inputs' over socket and parse it in python
#server.register(namespace="auraengine",
# "enabled_lineins",
# fun (s) -> begin
# log("auraengine.enabled_lineins")
# "0:#{!linein_0_enabled}, 1:#{!linein_1_enabled}, 2:#{!linein_2_enabled}, 3:#{!linein_3_enabled}, 4:#{!linein_4_enabled}"
# end
#)
#server.register(namespace="auraengine",
# "enabled_lineouts",
# fun(s) -> begin
# log("auraengine.enabled_lineouts")
# "0:#{!lineout_0_enabled}, 1:#{!lineout_1_enabled}, 2:#{!lineout_2_enabled}, 3:#{!lineout_3_enabled}, 4:#{!lineout_4_enabled}"
# end
#)
# are outgoing streams connected?
server.register(namespace="auraengine",
description="returns if outgoing streams are connected",
usage="out_streams_connected",
"out_streams_connected",
fun (s) -> begin
log("streams.connection_status")
"0:#{!s0_connected}, 1:#{!s1_connected}, 2:#{!s2_connected}, 3:#{!s3_connected}, 4:#{!s4_connected}"
end
)
# return a state of the inputs/outputs of the soundserver as JSON
server.register(namespace = "auraengine",
description="returns enabled lineouts/lineins, connected outgoing streams, and recorder. Also returns fallbacksettings.",
usage="state",
"state",
fun(s) -> begin
log("auraengine.state")
ret = '{'
ret = ret^'"streams": {'
ret = ret^'"stream_0": {"enabled": #{s0_enable}, "connected": #{!s0_connected}},'
ret = ret^'"stream_1": {"enabled": #{s1_enable}, "connected": #{!s1_connected}},'
ret = ret^'"stream_2": {"enabled": #{s2_enable}, "connected": #{!s2_connected}},'
ret = ret^'"stream_3": {"enabled": #{s3_enable}, "connected": #{!s3_connected}},'
ret = ret^'"stream_4": {"enabled": #{s4_enable}, "connected": #{!s4_connected}}'
ret = ret^'},'
ret = ret^'"recorder": {'
ret = ret^'"recorder_0": {"enabled": #{r0_enable}, "recording": #{!r0_is_recording}},'
ret = ret^'"recorder_1": {"enabled": #{r1_enable}, "recording": #{!r1_is_recording}},'
ret = ret^'"recorder_2": {"enabled": #{r2_enable}, "recording": #{!r2_is_recording}},'
ret = ret^'"recorder_3": {"enabled": #{r3_enable}, "recording": #{!r3_is_recording}},'
ret = ret^'"recorder_4": {"enabled": #{r4_enable}, "recording": #{!r4_is_recording}}'
ret = ret^'},'
ret = ret^'"linein": {'
ret = ret^'"linein_0": {"enabled": #{a0_in != ""}},'
ret = ret^'"linein_1": {"enabled": #{a1_in != ""}},'
ret = ret^'"linein_2": {"enabled": #{a2_in != ""}},'
ret = ret^'"linein_3": {"enabled": #{a3_in != ""}},'
ret = ret^'"linein_4": {"enabled": #{a4_in != ""}}'
ret = ret^'},'
ret = ret^'"lineout": {'
ret = ret^'"lineout_0": {"enabled": #{a0_out != ""}},'
ret = ret^'"lineout_1": {"enabled": #{a1_out != ""}},'
ret = ret^'"lineout_2": {"enabled": #{a2_out != ""}},'
ret = ret^'"lineout_3": {"enabled": #{a3_out != ""}},'
ret = ret^'"lineout_4": {"enabled": #{a4_out != ""}}'
ret = ret^'}'
ret = ret^'}'
ret
# outgoing streams enabled?
#ret = "stream_0_enabled:#{!s0_enable}, stream_1_enabled:#{!s1_enable}, stream_2_enabled:#{!s2_enable}, stream_3_enabled:#{!s3_enable}, stream_4_enabled:#{!s4_enable}, "
# outgoing recorder enabled
#ret = ret^"recorder_0_enabled:#{r0_enable}, recorder_1_enabled:#{r1_enable}, recorder_2_enabled:#{r2_enable}, recorder_3_enabled:#{r3_enable}, recorder_4_enabled:#{r4_enable}, "
#ret = ret^"linein_0_enabled:#{a0_in != ''}, linein_1_enabled:#{a1_in != ''}, linein_2_enabled:#{a2_in != ''}, linein_3_enabled:#{a3_in != ''}, linein_4_enabled:#{a4_in != ''}, "
#ret = ret^"lineout_0_enabled:#{a0_out != ''}, lineout_1_enabled:#{a1_out != ''}, lineout_2_enabled:#{a2_out != ''}, lineout_3_enabled:#{a3_out != ''}, lineout_4_enabled:#{a4_out != ''}, "
#ret = ret^"fallback_max_blank:#{fallback_max_blank}, fallback_min_noise:#{fallback_min_noise}, fallback_threshold:#{fallback_threshold}"
end
)
# enable the seek function for the input from the filesystem
server.register(namespace = source.id(input_filesystem_0),
description="seek to relative position in #{source.id(input_filesystem_0)}",
usage = "seek <duration in seconds>",
"seek",
fun(t) -> begin
log("Seeking #{t} sec")
t = float_of_string(default=0.,t)
ret = source.seek(input_filesystem_0, t)
"Seeked #{ret} seconds."
end
)
server.register(namespace = source.id(input_filesystem_1),
description="seek to relative position in #{source.id(input_filesystem_1)}",
usage = "seek <duration in seconds>",
"seek",
fun(t) -> begin
log("Seeking #{t} sec")
t = float_of_string(default=0.,t)
ret = source.seek(input_filesystem_1, t)
"Seeked #{ret} seconds."
end
)
# server.register(namespace = source.id(input_filesystem_2),
# description="seek to relative position in #{source.id(input_filesystem_2)}",
# usage = "seek <duration in seconds>",
# "seek",
# fun(t) -> begin
# log("Seeking #{t} sec")
# t = float_of_string(default=0.,t)
# ret = source.seek(input_filesystem_2, t)
# "Seeked #{ret} seconds."
# end
# )
# server.register(namespace = source.id(input_filesystem_3),
# description="seek to relative position in #{source.id(input_filesystem_3)}",
# usage = "seek <duration in seconds>",
# "seek",
# fun(t) -> begin
# log("Seeking #{t} sec")
# t = float_of_string(default=0.,t)
# ret = source.seek(input_filesystem_3, t)
# "Seeked #{ret} seconds."
# end
# )
# server.register(namespace = source.id(input_filesystem_4),
# description="seek to relative position in #{source.id(input_filesystem_4)}",
# usage = "seek <duration in seconds>",
# "seek",
# fun(t) -> begin
# log("Seeking #{t} sec")
# t = float_of_string(default=0.,t)
# ret = source.seek(input_filesystem_4, t)
# "Seeked #{ret} seconds."
# end
# )
def fadeTo(source_number) =
if source_number == "" then
print(source_number)
"Usage: mixer.fadeto <source nb> #{source_number}"
else
r = server.execute("mixer.select #{source_number} true")
print(r)
"Donee!"
end
end
# enable fadeTo for the mixer
server.register(namespace = "mixer",
description = "is fading from one mixer input to another",
usage = "fadeto <source number>",
"fadeto",
fadeTo
)
ignore(fade_in_time)
ignore(fade_out_time)
\ No newline at end of file
#
# engine
#
# Playout Daemon for autoradio project
#
#
# Copyright (C) 2017-2018 Gottfried Gaisbauer <gottfried.gaisbauer@servus.at>
#
# This file is part of engine.
#
# engine is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# any later version.
#
# engine is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with engine. If not, see <http://www.gnu.org/licenses/>.
#
# READ INI FILE
%include "readini.liq"
default_config = "../../configuration/engine.ini"
config = list.hd(default=default_config, get_process_lines("ls /etc/aura/engine.ini"))
log("Config file used: #{config}")
ini = read_ini(config)
# TELNET SETTINGS
set("server.telnet", true)
set("server.telnet.bind_addr", "0.0.0.0")
set("server.telnet.port", 1234)
# LOG FILE SETTINGS
log_dir = list.assoc(default="", "logdir", ini)
set("log.file.path", "#{log_dir}/engine-lqs.log")
# SOCKET SETTINGS
set("server.socket", true)
set("server.socket.path", "./<script>.sock")
#set("request.grace_time",2.)
# SOUND CARD SETTINGS
#print(ini)
#a0_in = ini['input_device_0'][0]
a0_in = list.assoc(default="", "input_device_0", ini)
a1_in = list.assoc(default="", "input_device_1", ini)
a2_in = list.assoc(default="", "input_device_2", ini)
a3_in = list.assoc(default="", "input_device_3", ini)
a4_in = list.assoc(default="", "input_device_4", ini)
a0_out = list.assoc(default="", "output_device_0", ini)
a1_out = list.assoc(default="", "output_device_1", ini)
a2_out = list.assoc(default="", "output_device_2", ini)
a3_out = list.assoc(default="", "output_device_3", ini)
a4_out = list.assoc(default="", "output_device_4", ini)
# FALLBACK SETTINGS
fallback_max_blank = float_of_string(list.assoc(default="", "fallback_max_blank", ini))
fallback_min_noise = float_of_string(list.assoc(default="", "fallback_min_noise", ini))
fallback_threshold = float_of_string(list.assoc(default="", "fallback_threshold", ini))
#fallback_max_blank = list.assoc(default="", "fallback_max_blank", ini)
#fallback_min_noise = list.assoc(default="", "fallback_min_noise", ini)
#fallback_threshold = list.assoc(default="", "fallback_threshold", ini)
# FADING SETTINGS
fade_in_time = list.assoc(default="", "fade_in_time", ini) #int_of_string(list.assoc(default="", "fade_in_time", ini))
fade_out_time = list.assoc(default="", "fade_out_time", ini) #int_of_string(list.assoc(default="", "fade_out_time", ini))
# RECORDER SETTINGS
#rec_0_filetype = list.assoc(default="", "rec_0_filetype", ini)
#rec_1_filetype = list.assoc(default="", "rec_1_filetype", ini)
#rec_2_filetype = list.assoc(default="", "rec_2_filetype", ini)
#rec_3_filetype = list.assoc(default="", "rec_3_filetype", ini)
#rec_4_filetype = list.assoc(default="", "rec_4_filetype", ini)
# ALSA / pulse settings
soundsystem = list.assoc(default="", "soundsystem", ini)
use_alsa = soundsystem == "alsa"
use_jack = soundsystem == "jack"
if use_alsa then
frame_duration = float_of_string(list.assoc(default="", "frame_duration", ini))
frame_size = int_of_string(list.assoc(default="", "frame_size", ini))
alsa_buffer = int_of_string(list.assoc(default="", "alsa_buffer", ini))
alsa_buffer_length = int_of_string(list.assoc(default="", "alsa_buffer_length", ini))
alsa_periods = int_of_string(list.assoc(default="", "alsa_periods", ini))
if frame_duration > 0.0 then
print("setting frame.duration to #{frame_duration}s")
set("frame.duration", frame_duration)
end
if frame_size > 0 then
print("setting frame.size to #{frame_size}")
set("frame.audio.size", frame_size)
end
if alsa_buffer > 0 then
print("setting alsa.buffer to #{alsa_buffer}")
set("alsa.alsa_buffer", alsa_buffer)
end
if alsa_buffer > 0 then
print("setting alsa.buffer_length to #{alsa_buffer_length}")
set("alsa.buffer_length", alsa_buffer_length)
end
if alsa_periods > 0 then
print("setting alsa.periods to #{alsa_periods}")
set("alsa.periods", alsa_periods) # assertion error when setting periods other than 0 => alsa default
end
end
# %include "readini.liq"
# ini = read_ini("/etc/aura/engine.ini")
# %include "settings.liq"
# TELNET SETTINGS
# set("server.telnet", true)
# set("server.telnet.bind_addr", "0.0.0.0")
# set("server.telnet.port", 2345)
inst = if argv(1) != "" then string_of(argv(1)) else 'record' end
instance = ref inst
audiobase = if !instance == 'record' then list.assoc(default="", "audiobase", ini) else list.assoc(default="", "altaudiobase", ini) end
rec_filetype = list.assoc(default="", "rec_filetype", ini)
filenamepattern = ref audiobase^"/%Y-%m-%d/%Y-%m-%d-%H-%M.flac"
# Der aktuelle Dateiname für die Aufnahme
recordingfile = ref ""
# wir definieren eine Referenz für die Stop-Funktion, die aber bisher noch nichts tun kann
stop_f = ref (fun () -> ())
# bewahre uns davor, dass zweimal gleichzeitig die gleiche Date aufgenommen wird
is_record_active = ref false
# Stop dump - wir definieren die Funktion, die stop_f ausführt
def stop_dump() =
f = !stop_f
f ()
end
def on_start()
recordingfile := list.hd(default="", get_process_lines("date +#{!filenamepattern}"))
end
# Wav header fixen und ggf. die Aufzeichnung beenden
def on_close(filename)
# es darf wieder aufgenommen werden
is_record_active := false
# if list.assoc(default="", "rec_filetype", ini) == 'wav'
# # Korrekten WAV-Header schreiben
# system("qwavheaderdump -F #{filename}")
# Naechsten Dateinamen vormerken
recordingfile := list.hd(default="", get_process_lines("date +#{!filenamepattern}"))
end
# Der input wie oben definiert
def get_input()
output_source
# input.alsa()
end
def get_output()
input = get_input()
d = int_of_string(list.assoc(default="", "rec_duration", ini))
if rec_filetype == 'flac' then
log("output file type is FLAC")
output.file(
id="recorder",
%flac(samplerate=44100, channels=2, compression=5, bits_per_sample=16),
perm = 0o664,
on_start=on_start,
!filenamepattern,
on_close=on_close,
reopen_when={ if !instance == 'record' then int_of_float(gettimeofday()/60.) mod 30 == 0 else false end },
input
)
else
# record in WAV
log("output file type is WAV")
output.file(
id="recorder",
%wav(stereo=true, channels=2, samplesize=16, header=true),
perm = 0o664,
on_start=on_start,
!filenamepattern,
on_close=on_close,
reopen_when={ if !instance == 'record' then int_of_float(gettimeofday()/60.) mod d == 0 else false end },
input
)
end
end
# Funktion gibt Auskunft welches File aktuell ist und wieviel Prozent bereits aufgenommen werden
def currecording()
curfile = !recordingfile
if curfile != "" then
percent_done = default="", get_process_lines("echo $(($(stat -c%s "^curfile^")/3174777))"))
"#{curfile}, #{percent_done}%"
else
"Nothing is being recorded now"
end
end
#Funktion zum Start der Aufzeichnung
def start_dump() =
log('start dump')
# don't record twice is_record_active
if !is_record_active == false then
is_record_active := true
log('starting to record')
record = get_output()
log('record defined')
# Die Stopfunkton zeigt nun auf die Shutdown-Funktion der aktuellen Source
stop_f := fun () -> begin
log('stop recording')
# Aufnahme sauber beenden
ignore(server.execute('recorder.stop'))
# Source zerstören
source.shutdown(record)
# Variable zurücksetzen
recordingfile := ""
end
else
log("recorder already active")
end
end
# Der Server wird durch 3 Funktionen bereichert
# Der User darf die Aufzeichnung manuell starten
server.register(namespace="record",
description="Start recording.",
usage="start",
"start",
fun (s) -> begin start_dump() "OK" end)
# Der User darf die Aufzeichnung manuell stoppen
server.register(namespace="record",
description="Stop recording.",
usage="stop",
"stop",
fun (s) -> begin stop_dump() "OK" end)
if !instance != 'record' then
# Der User darf einen Dateinamen für die Aufnahme definieren
server.register(namespace="record",
description="Define filename for output.",
usage="setfilename",
"setfilename",
fun (s) -> begin filenamepattern := audiobase^"/"^string_of(s) "OK" end)
end
# Der User kann sich über den Fortschritt der Aufnahme informieren
server.register(namespace="record",
description="Show current file.",
usage="curfile",
"curfile",
fun (s) -> currecording() )
output.dummy(blank(id="serve"))
# define file name pattern
filenamepattern = ref audiobase^"/%Y-%m-%d/%Y-%m-%d-%H-%M.flac"
# Der aktuelle Dateiname für die Aufnahme
recordingfile = ref ""
# bewahre uns davor, dass zweimal gleichzeitig die gleiche Date aufgenommen wird
is_record_active = ref false
#wir definieren eine Referenz für die Stop-Funktion, die aber bisher noch nichts tun kann
stop_f = ref (fun () -> ())
def start_wav_output(recfile, filenamepattern, recorder_number)
duration = int_of_string(list.assoc(default="", "rec_"^recorder_number^"_duration", ini))
channels = int_of_string(list.assoc(default="", "rec_"^recorder_number^"_channels", ini))
samplesize = int_of_string(list.assoc(default="", "rec_"^recorder_number^"_samplesize", ini))
ignore(duration)
ignore(channels)
ignore(samplesize)
# def on_start()
# recfile := list.hd(default="", get_process_lines("date +#{!filenamepattern}"))
# end
# def on_close(filename)
# recordingfile := list.hd(default="", get_process_lines("date +#{!filenamepattern}"))
# end
print(channels)
print(samplesize)
#out_wav = output.file(id="recorder", perm = 0o664, on_start=on_start, on_close=on_close, reopen_when={ int_of_float(gettimeofday()/60.) mod duration == 0 })
#out_wav(%wav(stereo=true, channels=2, samplesize=8, header=true, !filenamepattern, output_source)
#ignore(out_wav)
output.dummy(id="wav_dummy_recording", blank())
# if channels == 2 then
# output.file(id="recorder", %wav(stereo=true, channels=2, samplesize=8, header=true), perm = 0o664, on_start=on_start, on_close=on_close, reopen_when={ int_of_float(gettimeofday()/60.) mod duration == 0 }, !filenamepattern, audio_to_stereo(output_source))
## out_wav(output_source)
# else
# output.file(id="recorder", %wav(stereo=true, channels=1, samplesize=8, header=true), perm = 0o664, on_start=on_start, on_close=on_close, reopen_when={ int_of_float(gettimeofday()/60.) mod duration == 0 }, !filenamepattern, output_source)
# out_wav(output_source)
# end
#if channels == 2 then
# if samplesize < 12 then
# ignore(out_wav(%wav(stereo=true, channels=2, samplesize=8, header=true), !filenamepattern, output_source))
# else
# ignore(out_wav(%wav(stereo=true, channels=2, samplesize=16, header=true), !filenamepattern, output_source))
# end
#else
# if samplesize < 12 then
# ignore(out_wav(%wav(stereo=true, channels=1, samplesize=8, header=true), !filenamepattern, output_source))
# else
# ignore(out_wav(%wav(stereo=true, channels=1, samplesize=16, header=true), !filenamepattern, output_source))
# end
#end
end
def start_flac_output(recorder_number, filenamepattern, duration)
# duration = int_of_string(list.assoc(default="", "rec_"^recorder_number^"_samplerate", ini))
# samplerate = list.assoc(default="", "rec_"^recorder_number^"_samplerate", ini)
channels = int_of_string(list.assoc(default="", "rec_"^recorder_number^"_channels", ini))
# compression = int_of_string(list.assoc(default="", "rec_"^recorder_number^"_compression", ini))
# bits_per_sample = int_of_string(list.assoc(default="", "rec_"^recorder_number^"_bits_per_sample", ini))
#output.file(id="recorder", %flac(samplerate=44100, channels=1, compression=7, bits_per_sample=32), perm = 0o664, on_start=on_start, !filenamepattern, on_close=on_close, reopen_when={ int_of_float(gettimeofday()/60.) mod duration == 0 }, output_source)
recfile = ref ''
def on_start()
recfile := list.hd(default="", get_process_lines("date +#{filenamepattern}"))
end
def on_close(filename)
recfile := list.hd(default="", get_process_lines("date +#{filenamepattern}"))
end
# dumbass liquidsoap cannot handle one output definition for mono and stereo
output_filesystem_mono = output.file(id="recorder", perm = 0o664, on_start=on_start, on_close=on_close, reopen_when={ int_of_float(gettimeofday()/60.) mod duration == 0 })
output_filesystem_stereo = output.file(id="recorder", perm = 0o664, on_start=on_start, on_close=on_close, reopen_when={ int_of_float(gettimeofday()/60.) mod duration == 0 })
ignore(output_filesystem_mono)
ignore(output_filesystem_stereo)
if channels == 2 then
output.dummy(id="flac_dummy_recording_stereo", blank())
# output_stereof(%flac(samplerate=44100, channels=1, compression=1, bits_per_sample=16), !filenamepattern, output_source)
else
output.dummy(id="flac_dummy_recording_mono", blank())
# output_icecast_monof(%flac(samplerate=44100, channels=1, compression=1, bits_per_sample=16), !filenamepattern, output_source)
end
end
def enable_stop_function(record)
# Die Stopfunkton zeigt nun auf die Shutdown-Funktion der aktuellen Source
stop_f := fun () -> begin
log('stop recording')
# Aufnahme sauber beenden
ignore(server.execute('recorder.stop'))
# Source zerstören
source.shutdown(record)
# Variable zurücksetzen
recordingfile := ""
end
end
def set_recorder_output(rec_filetype, recorder_number)
# flac output
if rec_filetype == 'flac' then
log("output file type is FLAC")
record = start_flac_output(recorder_number)
enable_stop_function(record)
# WAV output
else
log("output file type is WAV")
record = start_wav_output(recorder_number)
enable_stop_function(record)
end
end
# shows current file and how many bytes were written so far
def currecording()
curfile = !recordingfile
if curfile != "" then
bytes_written = list.hd(default="", get_process_lines("echo $(($(stat -c%s "^curfile^")))"))
"#{curfile}, #{bytes_written}B"
else
""
end
end
\ No newline at end of file
def get_icecast_mp3_stream(number)
stream_bitrate = int_of_string(list.assoc(default="", "stream_#{number}_bitrate", ini))
stream_mountpoint = list.assoc(default="", "stream_#{number}_mountpoint", ini)
stream_host = list.assoc(default="", "stream_#{number}_host", ini)
stream_port = int_of_string(list.assoc(default="", "stream_#{number}_port", ini))
stream_name = list.assoc(default="", "stream_#{number}_name", ini)
stream_url = list.assoc(default="", "stream_#{number}_url", ini)
stream_genre = list.assoc(default="", "stream_#{number}_genre", ini)
stream_description = list.assoc(default="", "stream_#{number}_description", ini)
stream_user = list.assoc(default="", "stream_#{number}_user", ini)
stream_password = list.assoc(default="", "stream_#{number}_password", ini)
if stream_bitrate == 24 then
icecast_stream = output.icecast(%mp3(bitrate = 24, samplerate = 22050), mount=stream_mountpoint, host=stream_host, port=stream_port, name=stream_name, url=stream_url, genre=stream_genre, description=stream_description, user=stream_user, password=stream_password, icy_metadata="true", fallible=true, buffer(output_source))
clock.assign_new(id="stream_#{number}",
[icecast_stream]
)
icecast_stream
else
icecast_stream = output.icecast(%mp3(samplerate = 44100), mount=stream_mountpoint, host=stream_host, port=stream_port, name=stream_name, url=stream_url, genre=stream_genre, description=stream_description, user=stream_user, password=stream_password, icy_metadata="true", fallible=true, buffer(output_source))
clock.assign_new(id="stream_#{number}",
[icecast_stream]
)
icecast_stream
end
end
def get_icecast_ogg_stream(number)
stream_quality = float_of_string(list.assoc(default="", "stream_#{number}_quality", ini))
stream_mountpoint = list.assoc(default="", "stream_#{number}_mountpoint", ini)
stream_host = list.assoc(default="", "stream_#{number}_host", ini)
stream_port = int_of_string(default="", list.assoc("stream_#{number}_port", ini))
stream_name = list.assoc(default="", "stream_#{number}_name", ini)
stream_url = list.assoc(default="", "stream_#{number}_url", ini)
stream_genre = list.assoc(default="", "stream_#{number}_genre", ini)
stream_description = list.assoc(default="", "stream_#{number}_description", ini)
stream_user = list.assoc(default="", "stream_#{number}_user", ini)
stream_password = list.assoc(default="", "stream_#{number}_password", ini)
if stream_quality >= 0.5 then
icecast_stream = output.icecast(%vorbis(quality = 1.0), mount=stream_mountpoint, host=stream_host, port=stream_port, name=stream_name, url=stream_url, genre=stream_genre, description=stream_description, user=stream_user, password=stream_password, icy_metadata="true", fallible=true, buffer(output_source))
clock.assign_new(id="stream_#{number}",
[icecast_stream]
)
icecast_stream
else
icecast_stream = output.icecast(%vorbis(quality = 0.1), mount=stream_mountpoint, host=stream_host, port=stream_port, name=stream_name, url=stream_url, genre=stream_genre, description=stream_description, user=stream_user, password=stream_password, icy_metadata="true", fallible=true, buffer(output_source))
clock.assign_new(id="stream_#{number}",
[icecast_stream]
)
icecast_stream
end
end
def get_harbour_mp3_stream(number)
stream_bitrate = int_of_string(list.assoc(default="", "stream_#{number}_bitrate", ini))
stream_user = list.assoc(default="", "stream_#{number}_user", ini)
stream_password = list.assoc(default="", "stream_#{number}_password", ini)
stream_port = int_of_string(list.assoc(default="", "stream_#{number}_port", ini))
stream_url = list.assoc(default="", "stream_#{number}_url", ini)
stream_mountpoint = list.assoc(default="", "stream_#{number}_mountpoint", ini)
if stream_bitrate == 24 then
harbourstream = output.harbor(%mp3(bitrate = 24, samplerate = 22050), user=stream_user, password=stream_password, id="stream", port=stream_port, url=stream_url, mount=stream_mountpoint, icy_metadata="true", fallible=true, buffer(output_source))
clock.assign_new(id="stream_#{number}",
[harbourstream]
)
harbourstream
else
harbourstream = output.harbor(%mp3, user=stream_user, password=stream_password, id="stream", port=stream_port, url=stream_url, mount=stream_mountpoint, icy_metadata="true", fallible=true, buffer(output_source))
clock.assign_new(id="stream_#{number}",
[harbourstream]
)
harbourstream
end
end
def get_stream(number)
stream = list.assoc(default="", "stream_#{number}", ini)
stream_type = list.assoc(default="", "stream_#{number}_type", ini)
stream_format = list.assoc(default="", "stream_#{number}_format", ini)
# is stream enabled?
if stream == "y" then
log("activating stream #{number}")
if stream_type == "icecast" then
log("its an icecast stream")
if stream_format == "mp3" then
log("filled with mp3")
get_icecast_mp3_stream(number)
elsif stream_format == "vorbis" then
log("filled with ogg")
get_icecast_ogg_stream(number)
else
output.dummy(id="no_valid_stream_format_DUMMY_ICECAST", blank())
end
elsif stream_type == "harbor" then
log("its an harbor stream")
if stream_format == "mp3" then
get_harbour_mp3_stream(number)
else
output.dummy(id="no_valid_stream_format_DUMMY_HARBOUR", blank())
end
else
output.dummy(id="no_valid_stream_type_DUMMY", blank())
end
else
output.dummy(id="no_stream_enabled_DUMMY", blank())
end
end
def set_streams()
stream_0 = get_stream(0)
#stream_1 = get_stream(1)
#stream_2 = get_stream(2)
#stream_3 = get_stream(3)
#stream_4 = get_stream(4)
end
#
# engine
#
# Playout Daemon for autoradio project
#
#
# Copyright (C) 2017-2018 Gottfried Gaisbauer <gottfried.gaisbauer@servus.at>
#
# This file is part of engine.
#
# engine is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# any later version.
#
# engine is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with engine. If not, see <http://www.gnu.org/licenses/>.
#
import os
import sys
import threading
import json
import queue
import traceback
import urllib
import logging
from mutagen.flac import FLAC
from datetime import datetime, timedelta
from modules.base.utils import SimpleUtil
from modules.database.model import Schedule, Playlist, PlaylistEntry, PlaylistEntryMetaData
from modules.communication.redis.messenger import RedisMessenger
from modules.scheduling.calender_fetcher import CalendarFetcher
class AuraCalendarService(threading.Thread):
"""
The `AuraCalendarService` retrieves all current schedules and related
playlists including audio files from the configured API endpoints and
stores it in the local database.
To perform the API queries it utilizes the CalendarFetcher class.
Attributes:
#FIXME Review attributes not needed.
"""
queue = None
config = None
logger = None
fetched_schedule_data = None
calendar_fetcher = None
stop_event = None
def __init__(self, config):
"""
Initializes the class.
Args:
config (AuraConfig): The configuration
"""
threading.Thread.__init__(self)
self.config = config
self.logger = logging.getLogger("AuraEngine")
self.queue = queue.Queue()
self.stop_event = threading.Event()
self.calendar_fetcher = CalendarFetcher(config)
def get_queue(self):
"""
Retrieves the queue of fetched data.
"""
return self.queue
def run(self):
"""
Fetch calendar data and store it in the database
Returns
Schedule ([]): An arrar of retrieved schedules passed via `self.queue`
"""
result = []
try:
fetched_schedule_data = self.calendar_fetcher.fetch()
self.logger.debug("Schedule data fetched from API: " + str(fetched_schedule_data))
# If nothing is fetched, return
if not fetched_schedule_data:
self.queue.put("fetching_aborted Nothing fetched")
return
# Check if existing schedules have been deleted
local_schedules = Schedule.select_programme(datetime.now())
for local_schedule in local_schedules:
# Filter the local schedule from the fetched ones
existing_schedule = list(filter(lambda new_schedule: \
new_schedule["schedule_id"] == local_schedule.schedule_id, fetched_schedule_data))
if existing_schedule:
self.logger.debug("Schedule (schedule_id: %s) is still existing remotely:" % \
(local_schedule.schedule_id))
else:
self.logger.info("Schedule (schedule_id: %s) has been deleted remotely! [%s]" % \
(local_schedule.schedule_id, str(local_schedule)))
local_schedule.delete(commit=True)
self.logger.info("Deleted local schedule from database (schedule_id: %s)" % local_schedule.schedule_id)
# Process fetched schedules
for schedule in fetched_schedule_data:
# Check schedule for validity
if "start" not in schedule:
self.logger.warning("No 'start' of schedule given. Skipping the schedule: %s " % str(schedule))
continue
if "end" not in schedule:
self.logger.warning("No 'end' of schedule given. Skipping the schedule: %s " % str(schedule))
continue
# Store the schedule
schedule_db = self.store_schedule(schedule)
# Store playlists to play
self.store_playlist(schedule_db, schedule_db.playlist_id, schedule["playlist"])
if schedule_db.schedule_fallback_id:
self.store_playlist(schedule_db, schedule_db.schedule_fallback_id, schedule["schedule_fallback"], 1)
if schedule_db.show_fallback_id:
self.store_playlist(schedule_db, schedule_db.show_fallback_id, schedule["show_fallback"], 2)
if schedule_db.station_fallback_id:
self.store_playlist(schedule_db, schedule_db.station_fallback_id, schedule["station_fallback"], 3)
result.append(schedule_db)
# Release the mutex
self.queue.put(result)
except Exception as e:
# Release the mutex
self.logger.warning("Fetching aborted due to: %s" % str(e))
self.queue.put("fetching_aborted " + str(e))
# terminate the thread
return
def store_schedule(self, schedule):
"""
Stores the given schedule to the database.
Args:
schedule (Schedule): The schedule
"""
schedule_db = Schedule.select_show_on_datetime(schedule["start"])
havetoadd = False
if not schedule_db:
self.logger.debug("no schedule with given schedule id in database => create new")
schedule_db = Schedule()
havetoadd = True
schedule_db.show_id = schedule["show_id"]
schedule_db.schedule_id = schedule["schedule_id"]
schedule_db.schedule_start = schedule["start"]
schedule_db.schedule_end = schedule["end"]
schedule_db.show_name = schedule["show_name"]
schedule_db.show_hosts = schedule["show_hosts"]
schedule_db.is_repetition = schedule["is_repetition"]
schedule_db.funding_category = schedule["show_fundingcategory"]
schedule_db.languages = schedule["show_languages"]
schedule_db.type = schedule["show_type"]
schedule_db.category = schedule["show_categories"]
schedule_db.topic = schedule["show_topics"]
schedule_db.musicfocus = schedule["show_musicfocus"]
# if schedule["playlist_id"] is None:
# # FIXME Manually assigned playlist ID.
# schedule["playlist_id"] = 1
schedule_db.playlist_id = schedule["playlist_id"]
schedule_db.schedule_fallback_id = schedule["schedule_fallback_id"]
schedule_db.show_fallback_id = schedule["show_fallback_id"]
schedule_db.station_fallback_id = schedule["station_fallback_id"]
schedule_db.store(add=havetoadd, commit=True)
return schedule_db
def store_playlist(self, schedule_db, playlist_id, fetched_playlist, fallbackplaylist_type=0):
"""
Stores the Playlist to the database.
"""
playlist_db = Playlist.select_playlist_for_schedule(schedule_db.schedule_start, playlist_id)
havetoadd = False
if not playlist_db:
playlist_db = Playlist()
havetoadd = True
self.logger.debug("Storing playlist %d for schedule (%s)" % (playlist_id, str(schedule_db)))
playlist_db.playlist_id = playlist_id
playlist_db.schedule_start = schedule_db.schedule_start
playlist_db.show_name = schedule_db.show_name
playlist_db.fallback_type = fallbackplaylist_type
if "entries" in fetched_playlist:
playlist_db.entry_count = len(fetched_playlist["entries"])
else:
playlist_db.entry_count = 0
playlist_db.store(havetoadd, commit=True)
if playlist_db.entry_count > 0:
self.store_playlist_entries(schedule_db, playlist_db, fetched_playlist)
return playlist_db
def store_playlist_entries(self, schedule_db, playlist_db, fetched_playlist):
"""
Stores the playlist entries to the database.
"""
entry_num = 0
time_marker = playlist_db.start_unix
for entry in fetched_playlist["entries"]:
entry_db = PlaylistEntry.select_playlistentry_for_playlist(playlist_db.artificial_id, entry_num)
havetoadd = False
if not entry_db:
entry_db = PlaylistEntry()
havetoadd = True
entry_db.entry_start = datetime.fromtimestamp(time_marker)
entry_db.artificial_playlist_id = playlist_db.artificial_id
entry_db.entry_num = entry_num
if "file" in entry and duration in entry["file"]:
# Convert nano-seconds to seconds
duration = int(float(entry["file"]["duration"]) / 1000000000)
# except Exception:
else:
# No duration means it's playing until the end of the schedule
self.logger.debug("Missing duration - setting duration of entry to end-of-schedule")
duration = SimpleUtil.timestamp(schedule_db.schedule_end) - time_marker
entry_db.duration = duration
if "uri" in entry:
# FIXME Refactor mix of uri/filename/file/source
entry_db.uri = entry["uri"]
entry_db.source = entry["uri"]
if "filename" in entry:
entry_db.source = entry["filename"]
entry_db.store(havetoadd, commit=True)
if "file" in entry:
self.store_playlist_entry_metadata(entry_db, entry["file"]["metadata"])
entry_num = entry_num + 1
time_marker += duration
def store_playlist_entry_metadata(self, entry_db, metadata):
"""
Stores the meta-data for a PlaylistEntry.
"""
metadata_db = PlaylistEntryMetaData.select_metadata_for_entry(entry_db.artificial_id)
havetoadd = False
if not metadata_db:
metadata_db = PlaylistEntryMetaData()
havetoadd = True
metadata_db.artificial_entry_id = entry_db.artificial_id
if "artist" not in metadata:
self.logger.warning("Artist not found in metadata for track '%s'. Setting to ''" % entry_db.source)
metadata_db.artist = ""
else:
metadata_db.artist = metadata["artist"]
if "album" in metadata:
metadata_db.album = metadata["album"]
if "artist" not in metadata:
self.logger.warning("Title not found in metadata for track '%s'. Setting to 'n/a'" % entry_db.source)
metadata_db.artist = "n/a"
else:
metadata_db.artist = metadata["artist"]
metadata_db.store(havetoadd, commit=True)
def stop(self):
self.stop_event.set()
import os
import sys
import urllib
import logging
import simplejson
from datetime import datetime, timedelta
#from modules.models.schedule import Schedule
from modules.base.utils import SimpleUtil
class CalendarFetcher:
"""
Fetches the schedules, playlists and playlist entries as JSON
via the API endpoints.
"""
url = dict()
url_parameter = dict()
config = None
logging = None
has_already_fetched = False
fetched_schedule_data = None
# FIXME another crutch because of the missing TANK
used_random_playlist_ids = list()
def __init__(self, config):
"""
Constructor
Args:
config (AuraConfig): Holds the engine configuration
"""
self.config = config
self.logger = logging.getLogger("AuraEngine")
self.__set_url__("api_steering_calendar")
self.__set_url__("api_tank_playlist")
self.__set_url__("api_steering_show")
#
# PUBLIC METHODS
#
def fetch(self):
"""
Retrieve all required data from the API.
"""
# Fetch upcoming schedules from STEERING
try:
self.logger.debug("Fetching schedules from STEERING")
self.fetched_schedule_data = self.__fetch_schedule_data__()
except urllib.error.HTTPError as e:
self.logger.critical("Cannot fetch from " + self.url["api_steering_calendar"] + "! Reason: " + str(e))
self.fetched_schedule_data = None
return None
except (urllib.error.URLError, IOError, ValueError) as e:
self.logger.critical("Cannot connect to " + self.url["api_steering_calendar"] + "! Reason: " + str(e))
self.fetched_schedule_data = None
return None
# Fetch playlist and fallbacks to the schedules from TANK
try:
self.logger.debug("Fetching playlists from TANK")
self.__fetch_schedule_playlists__()
except urllib.error.HTTPError as e:
self.logger.critical("Cannot fetch from " + self.url["api_tank_playlist"] + "! Reason: " + str(e))
self.fetched_schedule_data = None
return None
except (urllib.error.URLError, IOError, ValueError) as e:
self.logger.critical("Cannot connect to " + self.url["api_tank_playlist"] + "! Reason: " + str(e))
self.fetched_schedule_data = None
return None
return_data = []
# Gather returndata
try:
for schedule in self.fetched_schedule_data:
# Skip schedule if no start or end is given
if "start" not in schedule:
self.logger.warning("No start of schedule given. Skipping schedule: " + str(schedule))
schedule = None
if "end" not in schedule:
self.logger.warning("No end of schedule given. Skipping schedule: " + str(schedule))
schedule = None
if "playlist" not in schedule:
self.logger.warning("No playlist for schedule given. Skipping schedule: " + str(schedule))
schedule = None
if schedule:
return_data.append(schedule)
except TypeError as e:
self.logger.error("Nothing fetched...")
self.fetched_schedule_data = None
return None
return return_data
#
# PRIVATE METHODS
#
# FIXME Refactor for more transparent API requests.
def __set_url__(self, type):
"""
Initializes URLs and parameters for API calls.
"""
url = self.config.get(type)
pos = url.find("?")
if pos > 0:
self.url[type] = url[0:pos]
self.url_parameter[type] = url[pos:]
else:
self.url[type] = url
def __fetch_schedule_data__(self):
"""
Fetches schedule data from Steering.
Returns:
([Schedule]): An array of schedules
"""
servicetype = "api_steering_calendar"
schedule = None
# fetch data from steering
url = self.__build_url__(servicetype)
html_response = self.__fetch_data__(servicetype, url)
# use testdata if response fails or is empty
if not html_response or html_response == b"[]":
self.logger.critical("Got no response from Steering!")
# FIXME move hardcoded test-data to separate testing logic.
html_response = self.get_test_schedules()
# convert to dict
schedule = simplejson.loads(html_response)
# check data
if not schedule:
self.logger.warn("Got no schedule via Playout API (Steering)!")
return None
#self.fetched_schedule_data = self.remove_unnecessary_data(schedule)
return self.remove_unnecessary_data(schedule)
def __fetch_schedule_playlists__(self):
"""
Fetches all playlists including fallback playlists for every schedule.
This method used the class member `fetched_schedule_data`` to iterate
over and extend schedule data.
"""
# store fetched entries => do not have to fetch playlist_id more than once
fetched_entries=[]
try:
for schedule in self.fetched_schedule_data:
# Extend schedule with details of show (e.g. slug)
schedule = self.__fetch_show_details__(schedule)
# Retrieve playlist and the fallback playlists for every schedule.
# If a playlist (like station_fallback) is already fetched, it is not fetched again but reused
schedule["playlist"] = self.__fetch_schedule_playlist__(schedule, "playlist_id", fetched_entries)
schedule["schedule_fallback"] = self.__fetch_schedule_playlist__(schedule, "schedule_fallback_id", fetched_entries)
schedule["show_fallback"] = self.__fetch_schedule_playlist__(schedule, "show_fallback_id", fetched_entries)
schedule["station_fallback"] = self.__fetch_schedule_playlist__(schedule, "station_fallback_id", fetched_entries)
except Exception as e:
self.logger.error("Error: "+str(e))
def __fetch_show_details__(self, schedule):
"""
Fetches details of a show from Steering.
Args:
schedule (Schedule): A schedule holding a valid `show_id`
Returns:
(Schedule): The given schedule with additional show fields set.
"""
servicetype = "api_steering_show"
url = self.__build_url__(servicetype, "${ID}", str(schedule["show_id"]))
json_response = self.__fetch_data__(servicetype, url)
show_details = simplejson.loads(json_response)
# Extend "schedules" with details of "show"
schedule["show_slug"] = show_details["slug"]
### ...
### ... Add more properties here, if needed
### ...
return schedule
def __fetch_schedule_playlist__(self, schedule, id_name, fetched_playlists):
"""
Fetches the playlist for a given schedule.
Args:
schedule (Schedule): The schedule to fetch playlists for
id_name (String): The type of playlist to fetch (e.g. normal vs. fallback)
fetched_playlists ([]): Previously fetched playlists to avoid re-fetching
Returns:
([Schedule]): Array of playlists
"""
servicetype = "api_tank_playlist"
# fetch playlists from TANK
if not "show_slug" in schedule:
raise ValueError("Missing 'show_slug' for schedule", schedule)
slug = str(schedule["show_slug"])
url = self.__build_url__(servicetype, "${SLUG}", slug)
json_response = self.__fetch_data__(servicetype, url)
# if a playlist is already fetched, do not fetch it again
for playlist in fetched_playlists:
# FIXME schedule["playlist_id"] is always None, review if playlist["id"] is valid
if playlist["id"] == schedule[id_name]:
self.logger.debug("Playlist #" + str(schedule[id_name]) + " already fetched")
return playlist
if self.config.get("use_test_data"):
# FIXME move hardcoded test-data to separate testing logic.
self.logger.warn("Using test-data for fetch-schedule-playlist")
json_response = self.create_test_data(id_name, schedule)
# convert to list
playlists = simplejson.loads(json_response)
pl = None
if "results" in playlists:
# FIXME Currently we use hardcoded playlist and fallback assignments due to issues in Dashboard/Steering/Tank
self.logger.warn("FIXME Currently we use hardcoded playlist and fallback assignments due to issues in Dashboard/Steering/Tank")
i = 0
for playlist in playlists["results"]:
pl = playlist
# FIXME Always use the first playlist, since the schedule.playlist_id is currently not set via Dashboard:
if i == 0 and id_name == "playlist_id":
schedule["playlist_id"] = playlist["id"]
break
# FIXME Currently it's not possible to set & query the fallback for a timeslot/show/station; therefore hardcode it:
elif i == 1 and id_name == "schedule_fallback_id":
schedule["schedule_fallback_id"] = playlist["id"]
break
elif i == 2 and id_name == "show_fallback_id":
schedule["show_fallback_id"] = playlist["id"]
break
elif i == 3 and id_name == "station_fallback_id":
schedule["station_fallback_id"] = playlist["id"]
break
else:
pl = None
i += 1
if pl:
# Note: playlists without entries are allowed -> will trigger fallbacks
if "entries" in pl:
for entry in pl["entries"]:
if entry["uri"].startswith("file"):
entry["filename"] = self.convert_to_filename(entry["uri"])
fetched_playlists.append(pl)
return pl
def convert_to_filename(self, uri):
"""
Converts a file-system URI to an actual, absolute path to the file.
Args:
uri (String): The URI of the file
Returns:
path (String): Absolute file path
"""
e = self.config.get("audiofolder") + "/" + uri[7:] + ".flac"
if not os.path.isfile(e):
self.logger.warning("File %s does not exist!" % e)
return e
def __fetch_data__(self, type, url):
"""
Fetches JSON data for the given URL.
Args:
url (String): The API endpoint to call
Returns:
(Byte[]): An UTF-8 encoded byte object holding the response
"""
html_response = b''
# Send request to the API and read the data
try:
if type not in self.url_parameter:
if self.url[type] == "":
return False
request = urllib.request.Request(url)
else:
request = urllib.request.Request(url, self.url_parameter[type])
response = urllib.request.urlopen(request)
html_response = response.read()
except (urllib.error.URLError, IOError, ValueError) as e:
self.logger.error("Cannot connect to " + self.url[type] +
" (type: " + type + ")! Reason: " + str(e.reason))
#if not self.has_already_fetched: # first fetch
# self.logger.critical("exiting fetch data thread..")
# sys.exit()
self.has_already_fetched = True
return html_response.decode("utf-8")
def __build_url__(self, type, placeholder=None, value=None):
"""
Builds an API request URL using passed placeholder and value.
"""
url = self.url[type]
if placeholder:
url = url.replace(placeholder, value)
# self.logger.info("built URL: "+url)
return url
def remove_unnecessary_data(self, schedule):
"""
Removes all schedules which are not relevant for
further processing.
"""
count_before = len(schedule)
schedule = self.remove_data_more_than_24h_in_the_future(schedule)
schedule = self.remove_data_in_the_past(schedule)
count_after = len(schedule)
self.logger.info("Removed %d unnecessary schedules from response. Entries left: %d" % ((count_before - count_after), count_after))
return schedule
def remove_data_more_than_24h_in_the_future(self, schedules):
"""
Removes entries 24h in the future and 12 hours in the past.
Note: This might influence resuming (in case of a crash)
single schedules which are longer than 12 hours long.
Think e.g. live broadcasts.
"""
items = []
now = SimpleUtil.timestamp()
now_plus_24hours = now + (12*60*60)
now_minus_12hours = now - (12*60*60)
for s in schedules:
start_time = datetime.strptime(s["start"], "%Y-%m-%dT%H:%M:%S")
start_time = SimpleUtil.timestamp(start_time)
if start_time <= now_plus_24hours and start_time >= now_minus_12hours:
items.append(s)
return items
def remove_data_in_the_past(self, schedules):
"""
Removes all schedules from the past, except the one which is
currently playing.
"""
items = []
now = SimpleUtil.timestamp()
for s in schedules:
start_time = datetime.strptime(s["start"], "%Y-%m-%dT%H:%M:%S")
start_time = SimpleUtil.timestamp(start_time)
end_time = datetime.strptime(s["end"], "%Y-%m-%dT%H:%M:%S")
end_time = SimpleUtil.timestamp(end_time)
# Append all elements in the future
if start_time >= now:
items.append(s)
# Append the one which is playing now
elif start_time < now < end_time:
items.append(s)
return items
#
# TESTING
#
def get_test_schedules(self):
html_response = "{}"
# use testdata if wanted
if self.config.get("use_test_data"):
html_response = '[{"id":1,"schedule_id":1,"automation-id":1,"className":"TestData","memo":"TestData","show_fundingcategory":"TestData","start":"' + (datetime.now() + timedelta(hours=0)).strftime('%Y-%m-%dT%H:00:00') + '","end":"' + (datetime.now() + timedelta(hours=1)).strftime('%Y-%m-%dT%H:00:00') + '","show_id":9,"show_name":"TestData: FROzine","show_hosts":"TestData: Sandra Hochholzer, Martina Schweiger","title":"TestData:title","is_repetition":false,"playlist_id":2,"schedule_fallback_id":12,"show_fallback_id":92,"station_fallback_id":1,"rtr_category":"string","comment":"TestData: Kommentar","show_languages":"TestData: Sprachen","show_type":"TestData: Typ","show_categories":"TestData: Kategorie","show_topics":"TestData: Topic","show_musicfocus":"TestData: Fokus"},' \
'{"id":2,"schedule_id":2,"automation-id":1,"className":"TestData","memo":"TestData","show_fundingcategory":"TestData","start":"' + (datetime.now() + timedelta(hours=1)).strftime('%Y-%m-%dT%H:00:00') + '","end":"' + (datetime.now() + timedelta(hours=2)).strftime('%Y-%m-%dT%H:00:00') + '","show_id":10,"show_name":"TestData: FROMat","show_hosts":"TestData: Sandra Hochholzer, Martina Schweiger","title":"TestData:title","is_repetition":false,"playlist_id":4,"schedule_fallback_id":22,"show_fallback_id":102,"station_fallback_id":1,"rtr_category":"TestData: string","comment":"TestData: Kommentar","show_languages":"TestData: Sprachen","show_type":"TestData: Typ","show_categories":"TestData: Kategorie","show_topics":"TestData: Topic","show_musicfocus":"TestData: Fokus"},' \
'{"id":3,"schedule_id":3,"automation-id":1,"className":"TestData","memo":"TestData","show_fundingcategory":"TestData","start":"' + (datetime.now() + timedelta(hours=2)).strftime('%Y-%m-%dT%H:00:00') + '","end":"' + (datetime.now() + timedelta(hours=3)).strftime('%Y-%m-%dT%H:00:00') + '","show_id":11,"show_name":"TestData: Radio für Senioren","show_hosts":"TestData: Sandra Hochholzer, Martina Schweiger","title":"TestData:title","is_repetition":false,"playlist_id":6,"schedule_fallback_id":32,"show_fallback_id":112,"station_fallback_id":1,"rtr_category":"TestData: string","comment":"TestData: Kommentar","show_languages":"TestData: Sprachen","show_type":"TestData: Typ","show_categories":"TestData: Kategorie","show_topics":"TestData: Topic","show_musicfocus":"TestData: Fokus"}]'
self.logger.critical("Using hardcoded Response!")
return html_response
def create_test_data(self, id_name, schedule):
import random
rand_id = random.randint(1, 10000)
while rand_id in self.used_random_playlist_ids:
rand_id = random.randint(1, 10000)
self.used_random_playlist_ids.append(rand_id)
# FIXME move hardcoded test-data to separate testing logic.
# HARDCODED Testdata
if id_name != "playlist_id":
# FALLBACK TESTDATA
if rand_id % 3 == 0: # playlist fallback
json_response = '{"playlist_id":' + str(
rand_id) + ',"entries":[{"source":"file:///var/audio/fallback/music.flac"},{"source":"file:///var/audio/fallback/NightmaresOnWax/DJ-Kicks/02 - Only Child - Breakneck.flac"}]}'
elif rand_id % 2 == 0: # stream fallback
json_response = '{"playlist_id":' + str(
rand_id) + ',"entries":[{"source":"http://chill.out.airtime.pro:8000/chill_a"}]}'
else: # pool fallback
json_response = '{"playlist_id":' + str(rand_id) + ',"entries":[{"source":"pool:///liedermacherei"}]}'
schedule[id_name] = rand_id
elif schedule[id_name] == 0 or schedule[id_name] is None:
# this happens when playlist id is not filled out in pv
# json_response = '{"playlist_id": 0}'
if rand_id % 4 == 0: # playlist with two files
json_response = '{"playlist_id":' + str(
rand_id) + ',"entries":[{"source":"file:///var/audio/fallback/music.flac"},{"source":"file:///var/audio/fallback/NightmaresOnWax/DJ-Kicks/02 - Only Child - Breakneck.flac"}]}'
elif rand_id % 3 == 0: # playlist with jingle and then linein
json_response = '{"playlist_id":' + str(
rand_id) + ',"entries":[{"source":"file:///var/audio/fallback/music.flac"},{"source":"linein://1"}]}'
elif rand_id % 2 == 0: # playlist with jingle and then http stream
json_response = '{"playlist_id":' + str(
rand_id) + ',"entries":[{"source":"file:///var/audio/fallback/music.flac"},{"source":"http://chill.out.airtime.pro:8000/chill_a"}]}'
else: # pool playlist
json_response = '{"playlist_id":' + str(rand_id) + ',"entries":[{"source":"pool:///hiphop"}]}'
schedule[id_name] = rand_id
elif schedule[id_name] % 4 == 0: # playlist with two files
json_response = '{"playlist_id":' + str(schedule[id_name]) + ',"entries":[{"source":"file:///var/audio/fallback/music.flac"},{"source":"file:///var/audio/fallback/NightmaresOnWax/DJ-Kicks/01 - Type - Slow Process.flac"}]}'
elif schedule[id_name] % 3 == 0: # playlist with jingle and then http stream
json_response = '{"playlist_id":' + str(schedule[id_name]) + ',"entries":[{"source":"file:///var/audio/fallback/music.flac"},{"source":"linein://0"}]}'
elif schedule[id_name] % 2 == 0: # playlist with jingle and then linein
json_response = '{"playlist_id":' + str(schedule[id_name]) + ',"entries":[{"source":"file:///var/audio/fallback/music.flac"},{"source":"http://stream.fro.at:80/fro-128.ogg"}]}'
else: # pool playlist
json_response = '{"playlist_id":' + str(schedule[id_name]) + ',"entries":[{"source":"pool:///chillout"}]}'
self.logger.info("Using 'randomized' playlist: " + json_response + " for " + id_name[:-3] + " for show " + schedule["show_name"] + " starting @ " + schedule["start"])
return json_response
#
# Aura Engine
#
# Playout Daemon for autoradio project
#
#
# Copyright (C) 2020 David Trattnig <david.trattnig@subsquare.at>
#
# This file is part of engine.
#
# engine is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# any later version.
#
# engine is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with engine. If not, see <http://www.gnu.org/licenses/>.
#
# Meta
__version__ = '0.0.1'
__license__ = "GNU General Public License (GPL) Version 3"
__version_info__ = (0, 0, 1)
__author__ = 'David Trattnig <david.trattnig@subsquare.at>'
import os, os.path
import logging
import random
import librosa
from accessify import private, protected
from modules.base.enum import FallbackType
from modules.base.utils import SimpleUtil
from modules.communication.mail import AuraMailer
class FallbackManager:
"""
Handles all types of fallbacks in case there is an outage
for the regular radio programme.
Attributes:
config (AuraConfig): The engine configuration
logger (AuraLogger): The logger
mail (AuraMailer): Mail service
scheduler (AuraScheduler): The scheduler
fallback_history (Dict): Holds a 24h history of played, local tracks to avoid re-play
last_fallback (Integer): Timestamp, when the last local file fallback was played
is_processing (Boolean): Flag to avoid race-conditions, as Liquidsoap sends plenty of requests at once
"""
config = None
logger = None
mailer = None
scheduler = None
fallback_history = {}
last_fallback = 0
is_processing = False
def __init__(self, config, logger, scheduler):
"""
Constructor
Args:
config (AuraConfig): Holds the engine configuration
"""
self.config = config
self.mailer = AuraMailer(self.config)
self.scheduler = scheduler
self.logger = logger
#
# PUBLIC METHODS
#
def get_fallback(self, schedule, type):
"""
Checks if the given schedule is valid and returns a valid fallback
if required.
"""
type = None
playlist_id = schedule.playlist_id
if not schedule.playlist_id:
if not schedule.show_fallback_id:
if not schedule.schedule_fallback_id:
if not schedule.station_fallback_id:
raise Exception
else:
type = FallbackType.STATION
playlist_id = schedule.station_fallback_id
else:
type = FallbackType.TIMESLOT
playlist_id = schedule.schedule_fallback_id
else:
type = FallbackType.SHOW
playlist_id = schedule.show_fallback_id
if type:
self.logger.warn("Detected fallback type '%s' required for schedule %s" % (type, str(schedule)))
return (type, playlist_id)
def validate_playlist(self, playlist_id):
pass
def get_fallback_for(self, fallbackname):
"""
Retrieves a random fallback audio source for any of the types:
- timeslot/schedule
- show
- station
Args:
fallbackname (String): Fallback type
Returns:
(String): Absolute path to the file
"""
file = ""
media_type = "PLAYLIST"
active_schedule, active_playlist = self.scheduler.get_active_playlist()
# Block access to avoid race-conditions
if self.is_processing:
return None
else:
self.is_processing = True
# Get fallback track(s) by fallback-type
if fallbackname == "timeslot":
file = self.get_playlist_items(active_schedule, "schedule_fallback")
elif fallbackname == "show":
file = self.get_playlist_items(active_schedule, "show_fallback")
elif fallbackname == "station":
file = self.get_playlist_items(active_schedule, "station_fallback")
if not file:
media_type = "TRACK"
file = self.get_random_local_track()
if not file:
self.logger.critical("Got no file for station fallback! Playing default test track, to play anything at all.")
file = "../../testing/content/ernie_mayne_sugar.mp3"
media_type = "DEFAULT TRACK"
else:
file = ""
self.logger.critical("Should set next fallback file for " + fallbackname + ", but this fallback is unknown!")
if file:
# Send admin email to notify about the fallback state
if not active_playlist:
active_playlist = "-"
msg = "AURA ENGINE %s FALLBACK DETECTED!\n\n" % fallbackname
msg += "Expected, active Schedule: %s \n" % active_schedule
msg += "Expected, active Playlist: %s \n\n" % active_playlist
msg += "Providing FALLBACK-%s for %s '%s'\n\n" % (media_type, fallbackname, file)
msg += "Please review the schedules or contact your Aura Engine administrator."
self.mailer.send_admin_mail("CRITICAL - Detected fallback for %s" % fallbackname, msg)
self.logger.warn("Providing fallback %s: '%s'. Sent admin email about fallback state" % (media_type, file))
self.is_processing = False
return file
def fallback_has_started(self, artist, title):
"""
Called when a fallback track has actually started playing
"""
self.logger.info("Now playing: fallback track '%s - %s'." % (artist, title))
def get_track_duration(self, file):
"""
Returns the length of the given audio file.
"""
y, sr = librosa.load(file)
duration = librosa.get_duration(y=y, sr=sr)
return duration
#
# PRIVATE METHODS
#
def get_playlist_items(self, schedule, fallback_key):
"""
Retrieves the list of tracks from a playlist defined by `fallback_key`.
"""
playlist_files = ""
if hasattr(schedule, fallback_key):
playlist = getattr(schedule, fallback_key)
if len(playlist) > 0:
playlist = playlist[0]
if playlist and playlist.entries:
for entry in playlist.entries:
playlist_files += entry.source + "\n"
return playlist_files
def get_random_local_track(self):
"""
Retrieves a random audio track from the local station-fallback directory.
Returns:
(String): Absolute path to an audio file
"""
dir = self.config.fallback_music_folder
files = os.listdir(dir)
audio_files = list(filter(lambda f: self.is_audio_file(dir, f), files))
if not dir or not audio_files:
self.logger.error("Folder 'fallback_music_folder = %s' is empty!" % dir)
return None
# If last played fallback is > 24 hours ago, ignore play history
# This should save used memory if the engine runs for a long time
if self.last_fallback < SimpleUtil.timestamp() - (60*60*24):
self.fallback_history = {}
self.logger.info("Cleared fallback history.")
self.last_fallback = SimpleUtil.timestamp()
# Retrieve files which haven't been played yet
history = set(self.fallback_history.keys())
left_audio_files = list( set(audio_files) - (history) )
self.logger.info("Left fallback audio-files: %d/%d" % (len(left_audio_files), len(audio_files)))
# If nothing left, clear history and start with all files again
if not len(left_audio_files):
self.fallback_history = {}
left_audio_files = audio_files
# Select random track from directory
i = random.randint(0, len(left_audio_files)-1)
file = os.path.join(dir, left_audio_files[i])
# Store track in history, to avoid playing it multiple times
if file:
self.fallback_history[left_audio_files[i]] = SimpleUtil.timestamp()
return file
def is_audio_file(self, dir, file):
"""
Checks if the passed file is an audio file i.e. has a file-extension
known for audio files.
Args:
(File): file: the file object.
Returns:
(Boolean): True, if it's an audio file.
"""
audio_extensions = [".wav", ".flac", ".mp3", ".ogg", ".m4a"]
ext = os.path.splitext(file)[1]
abs_path = os.path.join(dir, file)
if os.path.isfile(abs_path):
if any(ext in s for s in audio_extensions):
return True
return False
\ No newline at end of file