1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316
|
# Copyright (C) 2025 Stephen Fairchild (s-fairchild@users.sourceforge.net)
# This program 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 2 of the License, or
# (at your option) any later version.
#
# This program 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 this program in the file entitled COPYING.
# If not, see <http://www.gnu.org/licenses/>.
import re
import os
import ctypes
import logging
import time
import tempfile
import shlex
import secrets
from functools import wraps
from datetime import datetime
from subprocess import Popen
from binascii import unhexlify
from idjc import FGlobs
from idjc.streamspec import FormatControl
__all__ = ["append", "prepend", "mk_ping", "Backend", "IcecastServer",
"Encoder", "Source", "RandomNoise"]
logging.basicConfig(level=logging.ERROR)
logger = logging.getLogger("testing")
def append(extra_text):
assert extra_text.endswith("\n")
def inner(func):
@wraps(func)
def send(message):
func(f"{message}{extra_text}")
return send
return inner
def prepend(extra_text):
assert extra_text.endswith("\n")
def inner(func):
@wraps(func)
def send(message):
func(f"{extra_text}{message}")
return send
return inner
def mk_ping(send, receive):
start_time = datetime.now()
def ping():
try:
send("ACTN=ping\n")
except BrokenPipeError:
logger.error("ping failed\n")
raise
else:
reply = receive()
if reply != "pong":
logger.critical(f"ping failed: {reply=}\n")
exit(5)
logger.info(f"{datetime.now() - start_time} PING")
return ping
class Backend:
def __init__(self, streams, tmpdirname):
self._streams = streams
self._closer = None
self._tmpdirname = tmpdirname
def __enter__(self):
os.environ["num_encoders"] = str(self._streams)
os.environ["num_streamers"] = str(self._streams)
os.environ["app_name"] = "idjc testing mode"
os.environ["client_id"] = secrets.token_hex(16)
os.environ["ui2be"] = os.path.join(self._tmpdirname, "ui2be")
os.environ["be2ui"] = os.path.join(self._tmpdirname, "be2ui")
backend = ctypes.CDLL(FGlobs.backend)
int_r = ctypes.c_int()
int_w = ctypes.c_int()
if not backend.init_backend(ctypes.byref(int_r), ctypes.byref(int_w)):
logger.critical("call to init_backend failed")
exit(5)
logger.debug(f"file descriptors for read/write are {int_r.value}, {int_w.value}")
try:
reader = os.fdopen(int_r.value, "r")
writer = os.fdopen(int_w.value, "w")
except OSError:
logger.critical("failed to create streams for back-end i/o")
exit(5)
logger.info("awaiting reply")
try:
line = reader.readline()
except IOError as e:
logger.critical(e)
exit(5)
if line != "idjc back-end ready\n":
logger.critical(f"bad reply from back-end: {line}")
exit(5)
logger.debug(f"back-end replied correctly with: {line}")
@append("end\n")
def send(message):
assert re.fullmatch(r"^(mx\n|sc\n)(([^=\n]+?=[^\n]*\n)*?)+(end\n)$",
message)
logger.debug(message.rstrip().replace("\n", "|"))
writer.write(message)
writer.flush()
def closer():
try:
reader.close()
writer.close()
except BrokenPipeError:
pass
self._closer = closer
return prepend("mx\n")(send), prepend("sc\n")(send), \
lambda: reader.readline().rstrip()
def __exit__(self, *_):
if self._closer is not None:
self._closer()
class IcecastServer():
def __init__(self, port):
self._proc = None
self._port = port
self._config_xml = b"""
<icecast>
<limits>
<sources>2</sources>
</limits>
<authentication>
<source-password>changeme</source-password>
<relay-password>changeme</relay-password>
<admin-user>admin</admin-user>
<admin-password>changeme</admin-password>
</authentication>
<directory>
<yp-url-timeout>15</yp-url-timeout>
<yp-url>http://dir.xiph.org/cgi-bin/yp-cgi</yp-url>
</directory>
<hostname>localhost</hostname>
<listen-socket>
<port>%d</port>
</listen-socket>
<fileserve>1</fileserve>
<paths>
<logdir>/tmp</logdir>
<webroot>/usr/share/icecast/web</webroot>
<adminroot>/usr/share/icecast/admin</adminroot>
<alias source="/" destination="/status.xsl"/>
</paths>
<logging>
<accesslog>access.log</accesslog>
<errorlog>error.log</errorlog>
<loglevel>1</loglevel>
</logging>
<http-headers>
<header name="Access-Control-Allow-Origin" value="*" />
</http-headers>
</icecast>""" % port
def __enter__(self):
with tempfile.NamedTemporaryFile(delete=False) as cfg:
cfg.write(self._config_xml)
logger.info(f"start local icecast server on port {self._port}")
def ic_launch(filename):
try:
return Popen(shlex.split(f"{filename} -c {cfg.name}"))
except Exception:
return None
# Account for icecast2 executable name variations across distros.
proc = ic_launch("icecast2") or ic_launch("icecast")
if proc is None:
logger.critical("icecast launch failed")
exit(5)
logger.debug(f"icecast process has pid of {proc.pid}")
time.sleep(3) # Give icecast some time to initialise.
if proc.poll() is not None:
logger.critical(f"icecast exited with code {proc.poll()}")
exit(5)
logger.debug("icecast is running")
self._proc = proc
def __exit__(self, *_):
self._proc.kill()
logger.info("kill signal sent to icecast server")
class Encoder:
def __init__(self, send, receive, random, streams):
self._tabs = [FormatControl(prepend(f"tab_id={i}\n")(send), receive)
for i in range(streams)]
self._random = random
def __enter__(self):
for tab in self._tabs:
if self._random:
tab.select_random()
else:
tab.select_default()
tab.start_encoder_rc()
logger.info("start command issued to encoders")
def __exit__(self, *_):
for tab in self._tabs:
tab.stop_encoder_rc()
tab._clear_selection()
logger.info("stop command issued to encoders")
class Source:
def __init__(self, send, receive, port, streams):
self._send = send
self._receive = receive
def params(i):
return "\n".join((
f"stream_source={i}",
"server_type=Icecast 2",
"host=127.0.0.1",
f"{port=}",
f"mount=/listen{i}",
"login=source",
"password=changeme",
"useragent=",
"dj_name=IMTesting",
"listen_url=www.example.com",
"description=Test Stream",
"genre=Silence or test noise",
"irc=",
"aim=",
"icq=",
"tls=Disabled",
"ca_directory=",
"ca_file=",
"client_cert=",
"make_public=False",
"command=server_connect\n"))
self._param_list = [params(i) for i in range(streams)]
def __enter__(self):
for i, each in enumerate(self._param_list):
self._send(each)
reply = self._receive()
if reply.endswith("failed"):
logger.error(f"server connection failure on tab {i}")
elif reply.endswith("succeeded"):
logger.info(f"connection made on tab {i}")
else:
logger.warn(f"unexpected reply: {reply=}")
def __exit__(self, *_):
for i in range(len(self._param_list)):
self._send(f"stream_source={i}\ncommand=server_disconnect\n")
self._receive()
class RandomNoise:
def __init__(self, send, receive):
self._send = send
self._receive = receive
def __enter__(self):
self._send("command=random_noise_on\n")
self._receive()
def __exit__(self, *_):
self._send("command=random_noise_off\n")
self._receive()
def mk_jack_ports_list(send, receive):
def jack_ports_list(filter_=""):
send(f"ACTN=jackportread\nJFIL={filter_}\nJPRT=\n")
reply = receive()
if not reply.startswith("jackports="):
raise ValueError(f"reply does not start with jackports= \"{reply}\"")
return [str(unhexlify(x.lstrip("@-")), "ascii") for x in reply[10:].split()]
return jack_ports_list
|