diff --git a/modules/rds.py b/modules/rds.py
index ee55253..05b6e17 100644
--- a/modules/rds.py
+++ b/modules/rds.py
@@ -2,6 +2,24 @@ from modules import InterModuleCommunication
from . import PlayerModule, log95, Track
import socket
+import uecp.frame
+import uecp.commands
+
+@uecp.commands.UECPCommand.register_type
+class ASCII(uecp.commands.UECPCommand):
+ ELEMENT_CODE = 0x2D
+
+ @classmethod
+ def create_from(cls, data: bytes | list[int]):
+ raise NotImplementedError()
+
+ def __init__(self, data: bytes) -> None:
+ self.data = data
+
+ def encode(self) -> list[int]:
+ return [
+ self.ELEMENT_CODE,
+ 2+len(self.data)] + list(b"95") + list(self.data)
DEBUG = False
@@ -71,7 +89,11 @@ def update_rds(track_name: str):
try:
f = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
f.settimeout(1.0)
- data = f"TEXT={prt}\r\nRTP={rtp}\r\n".encode()
+ uecp_frame = uecp.frame.UECPFrame()
+ uecp_frame.add_command(uecp.commands.RadioTextSetCommand(prt, 4, True))
+ uecp_frame.add_command(ASCII(f"RTP={rtp}\r\n".encode()))
+
+ data = uecp_frame.encode()
f.sendto(data, udp_host)
logger.debug("Sending", str(data))
f.close()
diff --git a/modules/web/index.html b/modules/web/index.html
index 82e7af6..0772f75 100644
--- a/modules/web/index.html
+++ b/modules/web/index.html
@@ -172,7 +172,7 @@
-
RadioPlayer status
+
diff --git a/modules/web/reader.js b/modules/web/reader.js
deleted file mode 100644
index 2a42798..0000000
--- a/modules/web/reader.js
+++ /dev/null
@@ -1,588 +0,0 @@
-'use strict';
-
-/**
- * @callback OnError
- * @param {string} err - error.
- */
-
-/**
- * @callback OnTrack
- * @param {RTCTrackEvent} evt - track event.
- */
-
-/**
- * @callback OnDataChannel
- * @param {RTCDataChannelEvent} evt - data channel event.
- */
-
-/**
- * @typedef Conf
- * @type {object}
- * @property {string} url - absolute URL of the WHEP endpoint.
- * @property {string} user - username.
- * @property {string} pass - password.
- * @property {string} token - token.
- * @property {OnError} onError - called when there's an error.
- * @property {OnTrack} onTrack - called when there's a track available.
- * @property {OnDataChannel} onDataChannel - called when there's a data channel available.
- */
-
-/** WebRTC/WHEP reader. */
-class MediaMTXWebRTCReader {
- /**
- * Create a MediaMTXWebRTCReader.
- * @param {Conf} conf - configuration.
- */
- constructor(conf) {
- this.retryPause = 2000;
- this.conf = conf;
- this.state = 'getting_codecs';
- this.restartTimeout = null;
- this.pc = null;
- this.offerData = null;
- this.sessionUrl = null;
- this.queuedCandidates = [];
- this.#getNonAdvertisedCodecs();
- }
-
- /**
- * Close the reader and all its resources.
- */
- close() {
- this.state = 'closed';
-
- if (this.pc !== null) {
- this.pc.close();
- }
-
- if (this.restartTimeout !== null) {
- clearTimeout(this.restartTimeout);
- }
- }
-
- static #supportsNonAdvertisedCodec(codec, fmtp) {
- return new Promise((resolve) => {
- const pc = new RTCPeerConnection({ iceServers: [] });
- const mediaType = 'audio';
- let payloadType = '';
-
- pc.addTransceiver(mediaType, { direction: 'recvonly' });
- pc.createOffer()
- .then((offer) => {
- if (offer.sdp === undefined) {
- throw new Error('SDP not present');
- }
- if (offer.sdp.includes(` ${codec}`)) { // codec is advertised, there's no need to add it manually
- throw new Error('already present');
- }
-
- const sections = offer.sdp.split(`m=${mediaType}`);
-
- const payloadTypes = sections.slice(1)
- .map((s) => s.split('\r\n')[0].split(' ').slice(3))
- .reduce((prev, cur) => [...prev, ...cur], []);
- payloadType = this.#reservePayloadType(payloadTypes);
-
- const lines = sections[1].split('\r\n');
- lines[0] += ` ${payloadType}`;
- lines.splice(lines.length - 1, 0, `a=rtpmap:${payloadType} ${codec}`);
- if (fmtp !== undefined) {
- lines.splice(lines.length - 1, 0, `a=fmtp:${payloadType} ${fmtp}`);
- }
- sections[1] = lines.join('\r\n');
- offer.sdp = sections.join(`m=${mediaType}`);
- return pc.setLocalDescription(offer);
- })
- .then(() => (
- pc.setRemoteDescription(new RTCSessionDescription({
- type: 'answer',
- sdp: 'v=0\r\n'
- + 'o=- 6539324223450680508 0 IN IP4 0.0.0.0\r\n'
- + 's=-\r\n'
- + 't=0 0\r\n'
- + 'a=fingerprint:sha-256 0D:9F:78:15:42:B5:4B:E6:E2:94:3E:5B:37:78:E1:4B:54:59:A3:36:3A:E5:05:EB:27:EE:8F:D2:2D:41:29:25\r\n'
- + `m=${mediaType} 9 UDP/TLS/RTP/SAVPF ${payloadType}\r\n`
- + 'c=IN IP4 0.0.0.0\r\n'
- + 'a=ice-pwd:7c3bf4770007e7432ee4ea4d697db675\r\n'
- + 'a=ice-ufrag:29e036dc\r\n'
- + 'a=sendonly\r\n'
- + 'a=rtcp-mux\r\n'
- + `a=rtpmap:${payloadType} ${codec}\r\n`
- + ((fmtp !== undefined) ? `a=fmtp:${payloadType} ${fmtp}\r\n` : ''),
- }))
- ))
- .then(() => {
- resolve(true);
- })
- .catch(() => {
- resolve(false);
- })
- .finally(() => {
- pc.close();
- });
- });
- }
-
- static #unquoteCredential(v) {
- return JSON.parse(`"${v}"`);
- }
-
- static #linkToIceServers(links) {
- return (links !== null) ? links.split(', ').map((link) => {
- const m = link.match(/^<(.+?)>; rel="ice-server"(; username="(.*?)"; credential="(.*?)"; credential-type="password")?/i);
- const ret = {
- urls: [m[1]],
- };
-
- if (m[3] !== undefined) {
- ret.username = this.#unquoteCredential(m[3]);
- ret.credential = this.#unquoteCredential(m[4]);
- ret.credentialType = 'password';
- }
-
- return ret;
- }) : [];
- }
-
- static #parseOffer(sdp) {
- const ret = {
- iceUfrag: '',
- icePwd: '',
- medias: [],
- };
-
- for (const line of sdp.split('\r\n')) {
- if (line.startsWith('m=')) {
- ret.medias.push(line.slice('m='.length));
- } else if (ret.iceUfrag === '' && line.startsWith('a=ice-ufrag:')) {
- ret.iceUfrag = line.slice('a=ice-ufrag:'.length);
- } else if (ret.icePwd === '' && line.startsWith('a=ice-pwd:')) {
- ret.icePwd = line.slice('a=ice-pwd:'.length);
- }
- }
-
- return ret;
- }
-
- static #reservePayloadType(payloadTypes) {
- // everything is valid between 30 and 127, except for interval between 64 and 95
- // https://chromium.googlesource.com/external/webrtc/+/refs/heads/master/call/payload_type.h#29
- for (let i = 30; i <= 127; i++) {
- if ((i <= 63 || i >= 96) && !payloadTypes.includes(i.toString())) {
- const pl = i.toString();
- payloadTypes.push(pl);
- return pl;
- }
- }
- throw Error('unable to find a free payload type');
- }
-
- static #enableStereoPcmau(payloadTypes, section) {
- const lines = section.split('\r\n');
-
- let payloadType = this.#reservePayloadType(payloadTypes);
- lines[0] += ` ${payloadType}`;
- lines.splice(lines.length - 1, 0, `a=rtpmap:${payloadType} PCMU/8000/2`);
- lines.splice(lines.length - 1, 0, `a=rtcp-fb:${payloadType} transport-cc`);
-
- payloadType = this.#reservePayloadType(payloadTypes);
- lines[0] += ` ${payloadType}`;
- lines.splice(lines.length - 1, 0, `a=rtpmap:${payloadType} PCMA/8000/2`);
- lines.splice(lines.length - 1, 0, `a=rtcp-fb:${payloadType} transport-cc`);
-
- return lines.join('\r\n');
- }
-
- static #enableMultichannelOpus(payloadTypes, section) {
- const lines = section.split('\r\n');
-
- let payloadType = this.#reservePayloadType(payloadTypes);
- lines[0] += ` ${payloadType}`;
- lines.splice(lines.length - 1, 0, `a=rtpmap:${payloadType} multiopus/48000/3`);
- lines.splice(lines.length - 1, 0, `a=fmtp:${payloadType} channel_mapping=0,2,1;num_streams=2;coupled_streams=1`);
- lines.splice(lines.length - 1, 0, `a=rtcp-fb:${payloadType} transport-cc`);
-
- payloadType = this.#reservePayloadType(payloadTypes);
- lines[0] += ` ${payloadType}`;
- lines.splice(lines.length - 1, 0, `a=rtpmap:${payloadType} multiopus/48000/4`);
- lines.splice(lines.length - 1, 0, `a=fmtp:${payloadType} channel_mapping=0,1,2,3;num_streams=2;coupled_streams=2`);
- lines.splice(lines.length - 1, 0, `a=rtcp-fb:${payloadType} transport-cc`);
-
- payloadType = this.#reservePayloadType(payloadTypes);
- lines[0] += ` ${payloadType}`;
- lines.splice(lines.length - 1, 0, `a=rtpmap:${payloadType} multiopus/48000/5`);
- lines.splice(lines.length - 1, 0, `a=fmtp:${payloadType} channel_mapping=0,4,1,2,3;num_streams=3;coupled_streams=2`);
- lines.splice(lines.length - 1, 0, `a=rtcp-fb:${payloadType} transport-cc`);
-
- payloadType = this.#reservePayloadType(payloadTypes);
- lines[0] += ` ${payloadType}`;
- lines.splice(lines.length - 1, 0, `a=rtpmap:${payloadType} multiopus/48000/6`);
- lines.splice(lines.length - 1, 0, `a=fmtp:${payloadType} channel_mapping=0,4,1,2,3,5;num_streams=4;coupled_streams=2`);
- lines.splice(lines.length - 1, 0, `a=rtcp-fb:${payloadType} transport-cc`);
-
- payloadType = this.#reservePayloadType(payloadTypes);
- lines[0] += ` ${payloadType}`;
- lines.splice(lines.length - 1, 0, `a=rtpmap:${payloadType} multiopus/48000/7`);
- lines.splice(lines.length - 1, 0, `a=fmtp:${payloadType} channel_mapping=0,4,1,2,3,5,6;num_streams=4;coupled_streams=4`);
- lines.splice(lines.length - 1, 0, `a=rtcp-fb:${payloadType} transport-cc`);
-
- payloadType = this.#reservePayloadType(payloadTypes);
- lines[0] += ` ${payloadType}`;
- lines.splice(lines.length - 1, 0, `a=rtpmap:${payloadType} multiopus/48000/8`);
- lines.splice(lines.length - 1, 0, `a=fmtp:${payloadType} channel_mapping=0,6,1,4,5,2,3,7;num_streams=5;coupled_streams=4`);
- lines.splice(lines.length - 1, 0, `a=rtcp-fb:${payloadType} transport-cc`);
-
- return lines.join('\r\n');
- }
-
- static #enableL16(payloadTypes, section) {
- const lines = section.split('\r\n');
-
- let payloadType = this.#reservePayloadType(payloadTypes);
- lines[0] += ` ${payloadType}`;
- lines.splice(lines.length - 1, 0, `a=rtpmap:${payloadType} L16/8000/2`);
- lines.splice(lines.length - 1, 0, `a=rtcp-fb:${payloadType} transport-cc`);
-
- payloadType = this.#reservePayloadType(payloadTypes);
- lines[0] += ` ${payloadType}`;
- lines.splice(lines.length - 1, 0, `a=rtpmap:${payloadType} L16/16000/2`);
- lines.splice(lines.length - 1, 0, `a=rtcp-fb:${payloadType} transport-cc`);
-
- payloadType = this.#reservePayloadType(payloadTypes);
- lines[0] += ` ${payloadType}`;
- lines.splice(lines.length - 1, 0, `a=rtpmap:${payloadType} L16/48000/2`);
- lines.splice(lines.length - 1, 0, `a=rtcp-fb:${payloadType} transport-cc`);
-
- return lines.join('\r\n');
- }
-
- static #enableStereoOpus(section) {
- let opusPayloadFormat = '';
- const lines = section.split('\r\n');
-
- for (let i = 0; i < lines.length; i++) {
- if (lines[i].startsWith('a=rtpmap:') && lines[i].toLowerCase().includes('opus/')) {
- opusPayloadFormat = lines[i].slice('a=rtpmap:'.length).split(' ')[0];
- break;
- }
- }
-
- if (opusPayloadFormat === '') {
- return section;
- }
-
- for (let i = 0; i < lines.length; i++) {
- if (lines[i].startsWith(`a=fmtp:${opusPayloadFormat} `)) {
- if (!lines[i].includes('stereo')) {
- lines[i] += ';stereo=1';
- }
- if (!lines[i].includes('sprop-stereo')) {
- lines[i] += ';sprop-stereo=1';
- }
- }
- }
-
- return lines.join('\r\n');
- }
-
- static #editOffer(sdp, nonAdvertisedCodecs) {
- const sections = sdp.split('m=');
-
- const payloadTypes = sections.slice(1)
- .map((s) => s.split('\r\n')[0].split(' ').slice(3))
- .reduce((prev, cur) => [...prev, ...cur], []);
-
- for (let i = 1; i < sections.length; i++) {
- if (sections[i].startsWith('audio')) {
- sections[i] = this.#enableStereoOpus(sections[i]);
-
- if (nonAdvertisedCodecs.includes('pcma/8000/2')) {
- sections[i] = this.#enableStereoPcmau(payloadTypes, sections[i]);
- }
- if (nonAdvertisedCodecs.includes('multiopus/48000/6')) {
- sections[i] = this.#enableMultichannelOpus(payloadTypes, sections[i]);
- }
- if (nonAdvertisedCodecs.includes('L16/48000/2')) {
- sections[i] = this.#enableL16(payloadTypes, sections[i]);
- }
-
- break;
- }
- }
-
- return sections.join('m=');
- }
-
- static #generateSdpFragment(od, candidates) {
- const candidatesByMedia = {};
- for (const candidate of candidates) {
- const mid = candidate.sdpMLineIndex;
- if (candidatesByMedia[mid] === undefined) {
- candidatesByMedia[mid] = [];
- }
- candidatesByMedia[mid].push(candidate);
- }
-
- let frag = `a=ice-ufrag:${od.iceUfrag}\r\n`
- + `a=ice-pwd:${od.icePwd}\r\n`;
-
- let mid = 0;
-
- for (const media of od.medias) {
- if (candidatesByMedia[mid] !== undefined) {
- frag += `m=${media}\r\n`
- + `a=mid:${mid}\r\n`;
-
- for (const candidate of candidatesByMedia[mid]) {
- frag += `a=${candidate.candidate}\r\n`;
- }
- }
- mid++;
- }
-
- return frag;
- }
-
- #handleError(err) {
- if (this.state === 'running') {
- if (this.pc !== null) {
- this.pc.close();
- this.pc = null;
- }
-
- this.offerData = null;
-
- if (this.sessionUrl !== null) {
- fetch(this.sessionUrl, {
- method: 'DELETE',
- });
- this.sessionUrl = null;
- }
-
- this.queuedCandidates = [];
- this.state = 'restarting';
-
- this.restartTimeout = window.setTimeout(() => {
- this.restartTimeout = null;
- this.state = 'running';
- this.#start();
- }, this.retryPause);
-
- if (this.conf.onError !== undefined) {
- this.conf.onError(`${err}, retrying in some seconds`);
- }
- } else if (this.state === 'getting_codecs') {
- this.state = 'failed';
-
- if (this.conf.onError !== undefined) {
- this.conf.onError(err);
- }
- }
- }
-
- #getNonAdvertisedCodecs() {
- Promise.all([
- ['pcma/8000/2'],
- ['multiopus/48000/6', 'channel_mapping=0,4,1,2,3,5;num_streams=4;coupled_streams=2'],
- ['L16/48000/2'],
- ]
- .map((c) => MediaMTXWebRTCReader.#supportsNonAdvertisedCodec(c[0], c[1]).then((r) => ((r) ? c[0] : false))))
- .then((c) => c.filter((e) => e !== false))
- .then((codecs) => {
- if (this.state !== 'getting_codecs') {
- throw new Error('closed');
- }
-
- this.nonAdvertisedCodecs = codecs;
- this.state = 'running';
- this.#start();
- })
- .catch((err) => {
- this.#handleError(err);
- });
- }
-
- #start() {
- this.#requestICEServers()
- .then((iceServers) => this.#setupPeerConnection(iceServers))
- .then((offer) => this.#sendOffer(offer))
- .then((answer) => this.#setAnswer(answer))
- .catch((err) => {
- this.#handleError(err.toString());
- });
- }
-
- #authHeader() {
- if (this.conf.user !== undefined && this.conf.user !== '') {
- const credentials = btoa(`${this.conf.user}:${this.conf.pass}`);
- return {'Authorization': `Basic ${credentials}`};
- }
- if (this.conf.token !== undefined && this.conf.token !== '') {
- return {'Authorization': `Bearer ${this.conf.token}`};
- }
- return {};
- }
-
- #requestICEServers() {
- return fetch(this.conf.url, {
- method: 'OPTIONS',
- headers: {
- ...this.#authHeader(),
- },
- })
- .then((res) => MediaMTXWebRTCReader.#linkToIceServers(res.headers.get('Link')));
- }
-
- #setupPeerConnection(iceServers) {
- if (this.state !== 'running') {
- throw new Error('closed');
- }
-
- this.pc = new RTCPeerConnection({
- iceServers,
- // https://webrtc.org/getting-started/unified-plan-transition-guide
- sdpSemantics: 'unified-plan',
- });
-
- const direction = 'recvonly';
- // this.pc.addTransceiver('video', { direction });
- this.pc.addTransceiver('audio', { direction });
-
- // using data channels requires creating a data channel locally
- this.pc.createDataChannel('');
-
- this.pc.onicecandidate = (evt) => this.#onLocalCandidate(evt);
- this.pc.onconnectionstatechange = () => this.#onConnectionState();
- this.pc.ontrack = (evt) => this.#onTrack(evt);
- this.pc.ondatachannel = (evt) => this.#onDataChannel(evt);
-
- return this.pc.createOffer()
- .then((offer) => {
- offer.sdp = MediaMTXWebRTCReader.#editOffer(offer.sdp, this.nonAdvertisedCodecs);
- this.offerData = MediaMTXWebRTCReader.#parseOffer(offer.sdp);
-
- return this.pc.setLocalDescription(offer)
- .then(() => offer.sdp);
- });
- }
-
- #sendOffer(offer) {
- if (this.state !== 'running') {
- throw new Error('closed');
- }
-
- return fetch(this.conf.url, {
- method: 'POST',
- headers: {
- ...this.#authHeader(),
- 'Content-Type': 'application/sdp',
- },
- body: offer,
- })
- .then((res) => {
- switch (res.status) {
- case 201:
- break;
- case 404:
- throw new Error('stream not found');
- case 400:
- return res.json().then((e) => { throw new Error(e.error); });
- default:
- throw new Error(`bad status code ${res.status}`);
- }
-
- this.sessionUrl = new URL(res.headers.get('location'), this.conf.url).toString();
-
- return res.text();
- });
- }
-
- #setAnswer(answer) {
- if (this.state !== 'running') {
- throw new Error('closed');
- }
-
- return this.pc.setRemoteDescription(new RTCSessionDescription({
- type: 'answer',
- sdp: answer,
- }))
- .then(() => {
- if (this.state !== 'running') {
- return;
- }
-
- if (this.queuedCandidates.length !== 0) {
- this.#sendLocalCandidates(this.queuedCandidates);
- this.queuedCandidates = [];
- }
- });
- }
-
- #onLocalCandidate(evt) {
- if (this.state !== 'running') {
- return;
- }
-
- if (evt.candidate !== null) {
- if (this.sessionUrl === null) {
- this.queuedCandidates.push(evt.candidate);
- } else {
- this.#sendLocalCandidates([evt.candidate]);
- }
- }
- }
-
- #sendLocalCandidates(candidates) {
- fetch(this.sessionUrl, {
- method: 'PATCH',
- headers: {
- 'Content-Type': 'application/trickle-ice-sdpfrag',
- 'If-Match': '*',
- },
- body: MediaMTXWebRTCReader.#generateSdpFragment(this.offerData, candidates),
- })
- .then((res) => {
- switch (res.status) {
- case 204:
- break;
- case 404:
- throw new Error('stream not found');
- default:
- throw new Error(`bad status code ${res.status}`);
- }
- })
- .catch((err) => {
- this.#handleError(err.toString());
- });
- }
-
- #onConnectionState() {
- if (this.state !== 'running') {
- return;
- }
-
- // "closed" can arrive before "failed" and without
- // the close() method being called at all.
- // It happens when the other peer sends a termination
- // message like a DTLS CloseNotify.
- if (this.pc.connectionState === 'failed'
- || this.pc.connectionState === 'closed'
- ) {
- this.#handleError('peer connection closed');
- }
- }
-
- #onTrack(evt) {
- if (this.conf.onTrack !== undefined) {
- this.conf.onTrack(evt);
- }
- }
-
- #onDataChannel(evt) {
- if (this.conf.onDataChannel !== undefined) {
- this.conf.onDataChannel(evt);
- }
- }
-}
-
-window.MediaMTXWebRTCReader = MediaMTXWebRTCReader;
\ No newline at end of file
diff --git a/modules/web/web.js b/modules/web/web.js
index e31efe0..121b41a 100644
--- a/modules/web/web.js
+++ b/modules/web/web.js
@@ -1,326 +1,387 @@
let ws = null;
let reconnectDelay = 1000;
let playlist = [];
-let Queue = [];
+let queue = [];
let currentTrackPath = "";
let currentTrackIndex = 0;
let selectedPlaylistIndex = null;
let selectedDir = null;
let selectedSubFile = null;
let basePath = "";
-let subbasePath = "";
+let subBasePath = "";
let skipCount = 0;
let skipCountToRender = 0;
let indexDigits = 1;
-let skipped_idx = [];
+let skippedIndices = [];
function toggleSection(id) {
- document.getElementById(id).classList.toggle('collapsed');
+ document.getElementById(id).classList.toggle("collapsed");
}
-function tnet() {
- return window.location.protocol === "file:" || window.location.hostname.includes("tnet")
+function isTnet() {
+ return window.location.protocol === "file:" || window.location.hostname.includes("tnet");
}
+function formatTime(s) {
+ s = Number(s || 0);
+ const h = Math.floor(s / 3600);
+ const m = Math.floor((s % 3600) / 60);
+ const sec = Math.floor(s % 60);
+ const parts = h ? [h, m, sec] : [m, sec];
+ return parts.map(x => String(x).padStart(2, "0")).join(":");
+}
+
+function clearListSelections(...ids) {
+ for (const id of ids) {
+ Array.from(document.getElementById(id).children).forEach(c => c.classList.remove("selected"));
+ }
+}
+
+// ─── Init ─────────────────────────────────────────────────────────────────────
+
function initLayout() {
if (window.innerWidth <= 800) {
- document.getElementById('section-playlist').classList.add('collapsed');
- document.getElementById('section-dirs').classList.add('collapsed');
- document.getElementById('section-subdir').classList.add('collapsed');
+ ["section-playlist", "section-dirs", "section-subdir"].forEach(id =>
+ document.getElementById(id).classList.add("collapsed")
+ );
+ }
+ if (isTnet()) {
+ document.getElementById("whep-url-input").value = "https://webrtc.terminal.tnet/radio/whep";
}
- if(tnet()) document.getElementById("whep-url-input").value = "https://webrtc.terminal.tnet/radio/whep"
}
-function connectWs() {
- const statusText = document.getElementById("server-status");
- statusText.textContent = "connecting...";
+// ─── WebSocket ───────────────────────────────────────────────────────────────
- let url = "/ws";
- if(tnet()) url = "https://radio95.tnet/ws"
- ws = new WebSocket(url);
+function connectWs() {
+ const statusEl = document.getElementById("server-status");
+ statusEl.textContent = "connecting...";
+
+ ws = new WebSocket(isTnet() ? "https://radio95.tnet/ws" : "/ws");
ws.addEventListener("open", () => {
- statusText.textContent = "connected";
+ statusEl.textContent = "connected";
reconnectDelay = 1500;
- ws.send(JSON.stringify({action:"get_toplay"}));
- ws.send(JSON.stringify({action:"skipc"}));
- ws.send(JSON.stringify({action:"skipi"}));
+ ws.send(JSON.stringify({ action: "get_toplay" }));
+ ws.send(JSON.stringify({ action: "skipc" }));
+ ws.send(JSON.stringify({ action: "skipi" }));
});
ws.addEventListener("close", () => {
- statusText.textContent = "disconnected — reconnecting...";
+ statusEl.textContent = "disconnected — reconnecting...";
setTimeout(connectWs, reconnectDelay);
reconnectDelay = Math.min(10000, reconnectDelay + 1500);
});
- ws.addEventListener("error", (e) => {
+ ws.addEventListener("error", e => {
console.error("WS error", e);
- statusText.textContent = "error";
+ statusEl.textContent = "error";
});
- ws.addEventListener("message", (evt) => {
- try { handleMessage(JSON.parse(evt.data)); }
- catch (e) { console.warn("Bad msg", evt.data, e); }
+ ws.addEventListener("message", evt => {
+ handleMessage(JSON.parse(evt.data));
});
}
-function RenderPlaylistQueue() {
- skipCountToRender = skipCount;
- renderQueue()
- renderPlaylist()
+function wsSend(obj) {
+ ws.send(JSON.stringify(obj));
}
+// ─── Message Handling ────────────────────────────────────────────────────────
+
function handleMessage(msg) {
- if(msg.event === "state"){
- const d = msg.data || {};
- if(d.dirs) updateDirs(d.dirs);
- if(d.track) applyProgressState(d.track);
- } else if (msg.event === "rds") {
- const rt = (msg.data?.rt) ?? "";
- document.getElementById("rds-text").textContent = rt ?? "";
- } else if(msg.event === "playlist") {
- playlist = msg.data || [];
- RenderPlaylistQueue()
- } else if(msg.event === "new_track"){
- applyTrackState(msg.data);
- ws.send(JSON.stringify({action:"get_toplay"}));
- ws.send(JSON.stringify({action:"skipc"}));
- ws.send(JSON.stringify({action:"skipi"}));
- } else if(msg.event === "progress") applyProgressState(msg.data);
- else if(msg.event === "toplay") {
- Queue = msg.data.data || [];
- RenderPlaylistQueue();
- } else if(msg.event === "request_dir") applySubdir(msg.data || {})
- else if(msg.event === "skipc") {
- skipCount = msg.data?.data ?? 0;
- document.getElementById("skpn-count").textContent = skipCount;
- RenderPlaylistQueue();
- } else if(msg.event === "skipi") {
- skipped_idx = msg.data?.data ?? skipped_idx;
- RenderPlaylistQueue();
+ switch (msg.event) {
+ case "state": {
+ const d = msg.data || {};
+ if (d.dirs) updateDirs(d.dirs);
+ if (d.track) applyProgressState(d.track);
+ break;
+ }
+ case "rds":
+ document.getElementById("rds-text").textContent = msg.data?.rt ?? "";
+ break;
+ case "playlist":
+ playlist = msg.data || [];
+ renderAll();
+ break;
+ case "new_track":
+ applyTrackState(msg.data);
+ wsSend({ action: "get_toplay" });
+ wsSend({ action: "skipc" });
+ wsSend({ action: "skipi" });
+ break;
+ case "progress":
+ applyProgressState(msg.data);
+ break;
+ case "toplay":
+ queue = msg.data.data || [];
+ renderAll();
+ break;
+ case "request_dir":
+ applySubdir(msg.data || {});
+ break;
+ case "skipc":
+ skipCount = msg.data?.data ?? 0;
+ document.getElementById("skpn-count").textContent = skipCount;
+ renderAll();
+ break;
+ case "skipi":
+ skippedIndices = msg.data?.data ?? skippedIndices;
+ renderAll();
+ break;
}
}
+function renderAll() {
+ skipCountToRender = skipCount;
+ renderQueue();
+ renderPlaylist();
+}
+
+// ─── Track State ─────────────────────────────────────────────────────────────
+
+function trackLabel(track, index) {
+ const prefix = track.official ? "(official) " : "(unofficial) ";
+ return prefix + track.path.replace(basePath, "").slice(1);
+}
+
function applyTrackState(payload) {
const track = payload.track || {};
const next = payload.next_track || {};
currentTrackPath = track.path;
currentTrackIndex = payload.index;
- document.getElementById("now-track").textContent = `${String(currentTrackIndex).padStart(indexDigits,'0')}: ` + (track.official ? "(official) " : "(unofficial) ") + track.path.replace(basePath, "").slice(1);;
- document.getElementById("next-track").textContent = (next.official ? "(official) " : "(unofficial) ") + next.path.replace(basePath, "").slice(1);
- RenderPlaylistQueue();
+ indexDigits = playlist.length.toString().length;
+ document.getElementById("now-track").textContent =
+ `${String(currentTrackIndex).padStart(indexDigits, "0")}: ${trackLabel(track)}`;
+ document.getElementById("next-track").textContent = trackLabel(next);
+ renderAll();
}
function applyProgressState(payload) {
const track = payload.track || {};
- const next_track = payload.next_track || {};
+ const next = payload.next_track || {};
const elapsed = Number(payload.elapsed || 0);
const total = Number(payload.total || payload.real_total || 1) || 1;
- const realtotal = Number(payload.real_total || payload.total || 1) || 1;
- const percent = Math.max(0, Math.min(100, (elapsed/realtotal)*100));
+ const realTotal = Number(payload.real_total || payload.total || 1) || 1;
+ const percent = Math.max(0, Math.min(100, (elapsed / realTotal) * 100));
+
document.getElementById("prog-fill").style.width = percent + "%";
- document.getElementById("time-label").textContent = formatTime(elapsed) + " / " + formatTime(total) + ` (${formatTime(total-elapsed)})`;
+ document.getElementById("time-label").textContent =
+ `${formatTime(elapsed)} / ${formatTime(total)} (${formatTime(total - elapsed)})`;
+
currentTrackIndex = payload.index;
- if(track.path){
+ if (track.path) {
currentTrackPath = track.path;
- document.getElementById("now-track").textContent = `${String(currentTrackIndex).padStart(indexDigits,'0')}: ` + (track.official ? "(official) " : "(unofficial) ") + track.path.replace(basePath, "").slice(1);
- } if(next_track.path) document.getElementById("next-track").textContent = `${next_track.official ? "(official)" : "(unofficial)"} ${next_track.path.replace(basePath, "").slice(1)}`;
+ document.getElementById("now-track").textContent =
+ `${String(currentTrackIndex).padStart(indexDigits, "0")}: ${trackLabel(track)}`;
+ }
+ if (next.path) {
+ document.getElementById("next-track").textContent =
+ `${next.official ? "(official)" : "(unofficial)"} ${next.path.replace(basePath, "").slice(1)}`;
+ }
}
-function applySubdir(payload) {
- if(payload.dir !== selectedDir) return;
- const dirsBox = document.getElementById("subdir-box");
- dirsBox.innerHTML = "Loading...";
- try {
- subbasePath = payload.base || "";
- const files = payload.files || [];
- dirsBox.innerHTML = "";
- files.sort().forEach(f => {
- const node = document.createElement("div");
- node.className = "item";
- node.textContent = f;
- node.addEventListener("click", () => {
- if(node.classList.contains("selected")) { node.classList.remove("selected"); selectedSubFile = null; return; }
- Array.from(dirsBox.children).forEach(c=>c.classList.remove("selected"));
- Array.from(document.getElementById("playlist-ul").children).forEach(c => c.classList.remove("selected"));
- node.classList.add("selected"); selectedSubFile = f;
- });
- dirsBox.appendChild(node);
- });
- } catch(e) { dirsBox.innerHTML = "Error fetching dirs: "+e.message; }
-}
-
-function formatTime(s) {
- s = Number(s || 0);
- const h = Math.floor(s / 3600)
- const m = Math.floor((s % 3600) / 60)
- const sec = Math.floor(s % 60);
-
- if(h != 0) return [h,m,sec].map(x => String(x).padStart(2,'0')).join(":");
- else return [m,sec].map(x => String(x).padStart(2,'0')).join(":");
-}
+// ─── Rendering ───────────────────────────────────────────────────────────────
function renderPlaylist() {
const ul = document.getElementById("playlist-ul");
ul.innerHTML = "";
+ indexDigits = playlist.length.toString().length;
let currentIndex = null;
- indexDigits = playlist.length.toString().length
+
playlist.forEach((t, i) => {
const li = document.createElement("li");
const path = t.path || "
";
- const official = t.official || false;
- const displayPath = (official ? "(official) " : "(unofficial) ") + path.replace(basePath, "").slice(1);
+ const displayPath = (t.official ? "(official) " : "(unofficial) ") + path.replace(basePath, "").slice(1);
li.dataset.path = path;
li.dataset.idx = i;
- li.addEventListener("click", () => { selectPlaylistItem(i, li); });
- if (path === currentTrackPath && i === currentTrackIndex) { li.classList.add("current"); currentIndex = i; }
- else if (i === currentTrackIndex) { li.classList.add("pointer"); currentIndex = i - 1; }
- if(skipCountToRender > 0 && i > currentTrackIndex) {
+ li.addEventListener("click", () => selectPlaylistItem(i, li));
+
+ if (path === currentTrackPath && i === currentTrackIndex) {
+ li.classList.add("current");
+ currentIndex = i;
+ } else if (i === currentTrackIndex) {
+ li.classList.add("pointer");
+ currentIndex = i - 1;
+ }
+
+ if (skipCountToRender > 0 && i > currentTrackIndex) {
li.style.textDecoration = "line-through";
skipCountToRender--;
}
- li.textContent = ` ${String(i).padStart(indexDigits,'0')}: `;
- li.textContent = (i === currentTrackIndex ? "▶ " : " ") + li.textContent + displayPath;
+ if (skippedIndices.includes(i)) {
+ li.style.textDecoration = "line-through";
+ }
+
+ li.textContent = `${i === currentTrackIndex ? "▶ " : " "}${String(i).padStart(indexDigits, "0")}: ${displayPath}`;
ul.appendChild(li);
- if(skipped_idx.includes(i)) li.style.textDecoration = "line-through";
});
- if(currentIndex !== null){
- ul.children[currentIndex]?.scrollIntoView({block:'center', behavior: 'smooth'});
- } updateControls();
+
+ if (currentIndex !== null) {
+ ul.children[currentIndex]?.scrollIntoView({ block: "center", behavior: "smooth" });
+ }
+ updateControls();
}
function renderQueue() {
const ul = document.getElementById("queue-ul");
ul.innerHTML = "";
- Queue.forEach((element, i) => {
+ queue.forEach(path => {
const li = document.createElement("li");
- li.textContent = element.replace(basePath, "").slice(1);
- if(skipCountToRender > 0) {
+ li.textContent = path.replace(basePath, "").slice(1);
+ if (skipCountToRender > 0) {
li.style.textDecoration = "line-through";
skipCountToRender--;
}
ul.appendChild(li);
});
- updateControls()
+ updateControls();
}
-function selectPlaylistItem(i, el){
- if(el.classList.contains("selected")) { el.classList.remove("selected"); selectedPlaylistIndex = null; return; }
- const ul = document.getElementById("playlist-ul");
- Array.from(ul.children).forEach(c => c.classList.remove("selected"));
- Array.from(document.getElementById("dirs-box").children).forEach(c => c.classList.remove("selected"));
- Array.from(document.getElementById("subdir-box").children).forEach(c => c.classList.remove("selected"));
+function updateDirs(payload) {
+ const box = document.getElementById("dirs-box");
+ box.innerHTML = "";
+ basePath = payload.base || "";
+
+ const addItem = (name, onClick) => {
+ const node = document.createElement("div");
+ node.className = "item";
+ node.textContent = name;
+ node.addEventListener("click", () => onClick(node));
+ box.appendChild(node);
+ };
+
+ (payload.dirs || []).sort().forEach(name => {
+ if (!name.startsWith(".")) addItem(name, node => onDirClicked(name, node));
+ });
+
+ (payload.files || []).sort().forEach(name => {
+ if (!name.startsWith(".")) {
+ addItem(name, node => {
+ if (node.classList.contains("selected")) {
+ node.classList.remove("selected");
+ selectedDir = null;
+ selectedSubFile = null;
+ return;
+ }
+ clearListSelections("playlist-ul", "subdir-box");
+ Array.from(box.children).forEach(c => c.classList.remove("selected"));
+ node.classList.add("selected");
+ node.dataset.type = "file";
+ selectedDir = null;
+ selectedSubFile = null;
+ document.getElementById("subdir-box").innerHTML = "";
+ });
+ }
+ });
+}
+
+function onDirClicked(name, node) {
+ if (node.classList.contains("selected")) {
+ node.classList.remove("selected");
+ selectedDir = null;
+ selectedSubFile = null;
+ document.getElementById("subdir-box").innerHTML = "";
+ return;
+ }
+ clearListSelections("dirs-box", "playlist-ul");
+ node.classList.add("selected");
+ selectedDir = name;
+ selectedSubFile = null;
+ wsSend({ action: "request_dir", what: selectedDir });
+}
+
+function applySubdir(payload) {
+ if (payload.dir !== selectedDir) return;
+ const box = document.getElementById("subdir-box");
+ box.innerHTML = "";
+ subBasePath = payload.base || "";
+
+ (payload.files || []).sort().forEach(f => {
+ const node = document.createElement("div");
+ node.className = "item";
+ node.textContent = f;
+ node.addEventListener("click", () => {
+ if (node.classList.contains("selected")) {
+ node.classList.remove("selected");
+ selectedSubFile = null;
+ return;
+ }
+ clearListSelections("subdir-box", "playlist-ul");
+ Array.from(document.getElementById("dirs-box").children).forEach(c => c.classList.remove("selected"));
+
+ // Re-select the parent dir node
+ Array.from(document.getElementById("dirs-box").children).forEach(c => {
+ if (c.textContent === selectedDir) c.classList.add("selected");
+ });
+
+ node.classList.add("selected");
+ selectedSubFile = f;
+ });
+ box.appendChild(node);
+ });
+}
+
+// ─── Playlist Selection ──────────────────────────────────────────────────────
+
+function selectPlaylistItem(i, el) {
+ if (el.classList.contains("selected")) {
+ el.classList.remove("selected");
+ selectedPlaylistIndex = null;
+ updateControls();
+ return;
+ }
+ clearListSelections("playlist-ul", "dirs-box", "subdir-box");
el.classList.add("selected");
selectedPlaylistIndex = i;
- updateControls()
+ updateControls();
}
-async function updateDirs(payload){
- const dirsBox = document.getElementById("dirs-box");
- dirsBox.innerHTML = "Loading...";
- try {
- basePath = payload.base || "";
- const files = payload.files || [];
- const dirs = payload.dirs || [];
- dirsBox.innerHTML = "";
- dirs.sort().forEach(f => {
- if(!f.startsWith(".")) {
- const node = document.createElement("div");
- node.className = "item";
- node.textContent = f;
- node.addEventListener("click", () => onDirClicked(f, node));
- dirsBox.appendChild(node);
- }
- });
- files.sort().forEach(f => {
- if(!f.startsWith(".")) {
- const node = document.createElement("div");
- node.className = "item";
- node.textContent = f;
- node.addEventListener("click", () => {
- if(node.classList.contains("selected")) { node.classList.remove("selected"); selectedDir = null; selectedSubFile = null; return; }
- Array.from(dirsBox.children).forEach(c=>c.classList.remove("selected"));
- Array.from(document.getElementById("playlist-ul").children).forEach(c => c.classList.remove("selected"));
- Array.from(document.getElementById("subdir-box").children).forEach(c => c.classList.remove("selected"));
- node.classList.add("selected");
- selectedDir = null; selectedSubFile = null;
- document.getElementById("subdir-box").innerHTML = "";
- });
- node.dataset.type = "file";
- dirsBox.appendChild(node);
- }
- });
- } catch(e) { dirsBox.innerHTML = "Error fetching dirs: "+e.message; }
-}
-
-function onDirClicked(name, node){
- if(node.classList.contains("selected")) {
- node.classList.remove("selected"); selectedDir = null; selectedSubFile = null;
- document.getElementById("subdir-box").innerHTML = ""; return;
- }
- Array.from(document.getElementById("dirs-box").children).forEach(c => c.classList.remove("selected"));
- Array.from(document.getElementById("playlist-ul").children).forEach(c => c.classList.remove("selected"));
- node.classList.add("selected");
- selectedDir = name; selectedSubFile = null;
- ws.send(JSON.stringify({action:"request_dir", what: selectedDir}))
-}
-
-document.getElementById("skip-btn").addEventListener("click", () => ws.send(JSON.stringify({action:"skip"})));
-document.getElementById("skpn-inc").addEventListener("click", () => ws.send(JSON.stringify({action:"skipc", add: 1})));
-document.getElementById("skpn-dec").addEventListener("click", () => ws.send(JSON.stringify({action:"skipc", remove: -1})));
-document.getElementById("jingle-btn").addEventListener("click", () => ws.send(JSON.stringify({action:"jingle"})));
-document.getElementById("jingle-btn").addEventListener("contextmenu", (e) => {
- e.preventDefault();
- ws.send(JSON.stringify({action:"jingle", top: true}));
-});
-document.getElementById("skipidx-btn").addEventListener("click", () => {
- if (selectedPlaylistIndex == null) return;
- const action = skipped_idx.includes(selectedPlaylistIndex)
- ? { action: "skipi", remove: selectedPlaylistIndex }
- : { action: "skipi", add: selectedPlaylistIndex };
- ws.send(JSON.stringify(action));
-});
-
-document.getElementById("queue-title").addEventListener("click", () => toggleSection("section-queue"));
-document.getElementById("clear-btn").addEventListener("click", (e) => {
- e.stopPropagation();
- ws.send(JSON.stringify({action:"clear_toplay"}));
-});
+// ─── Queue Actions ───────────────────────────────────────────────────────────
function addSelectedFileToQueue(top) {
let fullPath = null;
- let success = false;
+
if (selectedPlaylistIndex != null) {
const selected = playlist[selectedPlaylistIndex];
const path = (selected.official ? "" : "!") + selected.path;
- ws.send(JSON.stringify({ action: "add_to_toplay", songs: [path], top: top }));
- success = true;
- } else if (selectedSubFile && selectedDir) fullPath = subbasePath.replace(/\/$/, '') + '/' + selectedSubFile;
- else {
- const dirEls = document.getElementById("dirs-box").children;
- const selectedItem = Array.from(dirEls).find(el => el.classList.contains("selected"));
- if (selectedItem && selectedItem.dataset.type === "file") fullPath = basePath.replace(/\/$/, '') + '/' + selectedItem.textContent;
+ wsSend({ action: "add_to_toplay", songs: [path], top });
+ // Only clear playlist selection — keep dir/subdir selections intact
+ clearListSelections("playlist-ul");
+ selectedPlaylistIndex = null;
+ updateControls();
+ return true;
}
- if (fullPath) { ws.send(JSON.stringify({ action: "add_to_toplay", songs: [fullPath], top: top })); success = true; }
- Array.from(document.getElementById("playlist-ul").children).forEach(c => c.classList.remove("selected"));
- Array.from(document.getElementById("dirs-box").children).forEach(c => c.classList.remove("selected"));
- Array.from(document.getElementById("subdir-box").children).forEach(c => c.classList.remove("selected"));
- selectedPlaylistIndex = null; selectedSubFile = null;
- return success;
+
+ if (selectedSubFile && selectedDir) {
+ fullPath = subBasePath.replace(/\/$/, "") + "/" + selectedSubFile;
+ } else {
+ const selectedFileEl = Array.from(document.getElementById("dirs-box").children)
+ .find(el => el.classList.contains("selected") && el.dataset.type === "file");
+ if (selectedFileEl) {
+ fullPath = basePath.replace(/\/$/, "") + "/" + selectedFileEl.textContent;
+ }
+ }
+
+ if (fullPath) {
+ wsSend({ action: "add_to_toplay", songs: [fullPath], top });
+ // Dir/subdir selections are intentionally preserved here
+ return true;
+ }
+
+ return false;
}
-document.getElementById("add-to-queue-btn").addEventListener("click", () => addSelectedFileToQueue(false));
-document.getElementById("add-to-queue2-btn").addEventListener("click", () => addSelectedFileToQueue(true));
+// ─── Controls ────────────────────────────────────────────────────────────────
function updateControls() {
- document.getElementById("clear-btn").disabled = Queue.length === 0;
+ document.getElementById("clear-btn").disabled = queue.length === 0;
const btn = document.getElementById("skipidx-btn");
if (selectedPlaylistIndex == null) {
btn.textContent = "⏭+ Skip in playlist";
btn.disabled = true;
btn.classList.remove("activated");
- } else if (skipped_idx.includes(selectedPlaylistIndex)) {
+ } else if (skippedIndices.includes(selectedPlaylistIndex)) {
btn.textContent = "✓ Unskip in playlist";
btn.disabled = false;
btn.classList.add("activated");
@@ -331,114 +392,147 @@ function updateControls() {
}
}
+// ─── Event Listeners ─────────────────────────────────────────────────────────
+
+document.getElementById("skip-btn").addEventListener("click", () => wsSend({ action: "skip" }));
+document.getElementById("skpn-inc").addEventListener("click", () => wsSend({ action: "skipc", add: 1 }));
+document.getElementById("skpn-dec").addEventListener("click", () => wsSend({ action: "skipc", remove: -1 }));
+
+document.getElementById("jingle-btn").addEventListener("click", () => wsSend({ action: "jingle" }));
+document.getElementById("jingle-btn").addEventListener("contextmenu", e => {
+ e.preventDefault();
+ wsSend({ action: "jingle", top: true });
+});
+
+document.getElementById("skipidx-btn").addEventListener("click", () => {
+ if (selectedPlaylistIndex == null) return;
+ const action = skippedIndices.includes(selectedPlaylistIndex)
+ ? { action: "skipi", remove: selectedPlaylistIndex }
+ : { action: "skipi", add: selectedPlaylistIndex };
+ wsSend(action);
+});
+
+document.getElementById("queue-title").addEventListener("click", () => toggleSection("section-queue"));
+document.getElementById("clear-btn").addEventListener("click", e => {
+ e.stopPropagation();
+ wsSend({ action: "clear_toplay" });
+});
+
+document.getElementById("add-to-queue-btn").addEventListener("click", () => addSelectedFileToQueue(false));
+document.getElementById("add-to-queue2-btn").addEventListener("click", () => addSelectedFileToQueue(true));
+
document.addEventListener("keydown", e => {
if (e.target.tagName === "INPUT") return;
if (e.key === "Enter" && addSelectedFileToQueue(e.shiftKey)) e.preventDefault();
- else if (e.key === "s") ws.send(JSON.stringify({action:"skip"}));
- else if (e.key === "n") ws.send(JSON.stringify({action:"skipc", add: 1}));
- else if (e.key === "m") ws.send(JSON.stringify({action:"skipc", remove: -1}));
- else if (e.key.toLowerCase() === "j") ws.send(JSON.stringify({action:"jingle", top: e.shiftKey}));
+ else if (e.key === "s") wsSend({ action: "skip" });
+ else if (e.key === "n") wsSend({ action: "skipc", add: 1 });
+ else if (e.key === "m") wsSend({ action: "skipc", remove: -1 });
+ else if (e.key.toLowerCase() === "j") wsSend({ action: "jingle", top: e.shiftKey });
});
let whepPc = null;
let whepAudio = null;
let whepConnected = false;
-function whepLog(msg, type = 'info') {
- const el = document.getElementById('whep-log');
- const line = document.createElement('div');
- line.className = 'wlog-' + type;
- const ts = new Date().toLocaleTimeString("pl-PL");
- line.textContent = `[${ts}] ${msg}`;
+function whepLog(msg, type = "info") {
+ const el = document.getElementById("whep-log");
+ const line = document.createElement("div");
+ line.className = "wlog-" + type;
+ line.textContent = `[${new Date().toLocaleTimeString("pl-PL")}] ${msg}`;
el.appendChild(line);
el.scrollTop = el.scrollHeight;
- // Keep log short
while (el.children.length > 30) el.removeChild(el.firstChild);
}
function whepSetDot(state) {
- const dot = document.getElementById('whep-dot');
- dot.className = 'whep-status-dot' + (state !== 'idle' ? ' ' + state : '');
- const btn = document.getElementById('whep-btn');
- if (state === 'connected' || state === 'connecting') {
- btn.textContent = '⏹ Disconnect';
- btn.classList.add('activated');
- } else {
- btn.textContent = '▶ Connect';
- btn.classList.remove('activated');
- }
+ document.getElementById("whep-dot").className =
+ "whep-status-dot" + (state !== "idle" ? " " + state : "");
+ const btn = document.getElementById("whep-btn");
+ const active = state === "connected" || state === "connecting";
+ btn.textContent = active ? "⏹ Disconnect" : "▶ Connect";
+ btn.classList.toggle("activated", active);
}
function whepSetVol(v) {
- document.getElementById('whep-vol-out').textContent = (Math.round(v * 1000) / 10).toFixed(1) + '%';
+ document.getElementById("whep-vol-out").textContent =
+ (Math.round(v * 1000) / 10).toFixed(1) + "%";
if (whepAudio) whepAudio.volume = parseFloat(v);
}
function whepToggle() {
- if (whepConnected || whepPc) { whepDisconnect(); return; }
- whepConnect();
+ if (whepConnected || whepPc) whepDisconnect();
+ else whepConnect();
}
function whepDisconnect() {
whepConnected = false;
- if (whepPc) { try { whepPc.close(); } catch(e){} whepPc = null; }
+ if (whepPc) { try { whepPc.close(); } catch (e) {} whepPc = null; }
if (whepAudio) { whepAudio.pause(); whepAudio.srcObject = null; whepAudio = null; }
- whepSetDot('idle');
- whepLog('Disconnected');
+ whepSetDot("idle");
+ whepLog("Disconnected");
}
async function whepConnect() {
- const url = document.getElementById('whep-url-input').value.trim();
+ const url = document.getElementById("whep-url-input").value.trim();
if (!url) return;
- whepSetDot('connecting');
- whepLog('Creating peer connection…');
+ whepSetDot("connecting");
+ whepLog("Creating peer connection…");
try {
whepPc = new RTCPeerConnection();
- whepPc.ontrack = (e) => {
- whepLog('Track received, starting playback', 'ok');
+
+ whepPc.ontrack = e => {
+ whepLog("Track received, starting playback", "ok");
whepAudio = new Audio();
whepAudio.srcObject = e.streams[0];
- whepAudio.volume = parseFloat(document.getElementById('whep-vol').value);
- whepAudio.play().then(() => {
- whepLog('Audio playing', 'ok');
- whepConnected = true;
- whepSetDot('connected');
- }).catch(() => {
- whepLog('Autoplay blocked — click anywhere to resume', 'err');
- document.addEventListener('click', () => whepAudio && whepAudio.play(), { once: true });
- });
+ whepAudio.volume = parseFloat(document.getElementById("whep-vol").value);
+ whepAudio.play()
+ .then(() => {
+ whepLog("Audio playing", "ok");
+ whepConnected = true;
+ whepSetDot("connected");
+ })
+ .catch(() => {
+ whepLog("Autoplay blocked — click anywhere to resume", "err");
+ document.addEventListener("click", () => whepAudio?.play(), { once: true });
+ });
};
+
whepPc.onconnectionstatechange = () => {
- whepLog('State: ' + whepPc.connectionState);
- if (whepPc.connectionState === 'failed' || whepPc.connectionState === 'disconnected') {
- whepLog('Connection lost', 'err');
+ whepLog("State: " + whepPc.connectionState);
+ if (["failed", "disconnected"].includes(whepPc.connectionState)) {
+ whepLog("Connection lost", "err");
whepDisconnect();
- whepSetDot('error');
+ whepSetDot("error");
}
};
- whepPc.oniceconnectionstatechange = () => whepLog('ICE: ' + whepPc.iceConnectionState);
- whepPc.addTransceiver('audio', { direction: 'recvonly' });
+
+ whepPc.oniceconnectionstatechange = () => whepLog("ICE: " + whepPc.iceConnectionState);
+ whepPc.addTransceiver("audio", { direction: "recvonly" });
+
const offer = await whepPc.createOffer();
offer.sdp = offer.sdp
- .replace(/useinbandfec=1/g, 'useinbandfec=1;stereo=1;sprop-stereo=1')
- .replace(/minptime=10/g, 'minptime=10;ptime=10;maxptime=10');
+ .replace(/useinbandfec=1/g, "useinbandfec=1;stereo=1;sprop-stereo=1")
+ .replace(/minptime=10/g, "minptime=10;ptime=10;maxptime=10");
await whepPc.setLocalDescription(offer);
- whepLog('Sending offer to ' + url);
+
+ whepLog("Sending offer to " + url);
const resp = await fetch(url, {
- method: 'POST',
- headers: { 'Content-Type': 'application/sdp', 'Accept': 'application/sdp' },
- body: whepPc.localDescription.sdp
+ method: "POST",
+ headers: { "Content-Type": "application/sdp", Accept: "application/sdp" },
+ body: whepPc.localDescription.sdp,
});
if (!resp.ok) throw new Error(`Server returned ${resp.status} ${resp.statusText}`);
+
const answerSdp = await resp.text();
- whepLog(`Got SDP answer (${answerSdp.length} bytes)`, 'ok');
- await whepPc.setRemoteDescription({ type: 'answer', sdp: answerSdp });
- whepLog('Waiting for ICE + track…');
- } catch(err) {
- whepLog('Error: ' + err.message, 'err');
+ whepLog(`Got SDP answer (${answerSdp.length} bytes)`, "ok");
+ await whepPc.setRemoteDescription({ type: "answer", sdp: answerSdp });
+ whepLog("Waiting for ICE + track…");
+ } catch (err) {
+ whepLog("Error: " + err.message, "err");
whepDisconnect();
- whepSetDot('error');
+ whepSetDot("error");
}
}
+
initLayout();
setTimeout(connectWs, 100);
\ No newline at end of file