File size: 15,605 Bytes
fa291f8 ae559e0 5f865aa fa291f8 2021b5e fa291f8 ae559e0 5f865aa fa291f8 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 | /********** VARIABILI GLOBALI & FUNZIONI PER PLAYER / CANALI **********/
/*********************** Author: Bocaletto Luca ***********************/
let hls; // Istanza globale per Hls.js
const video = document.getElementById("videoPlayer");
const spinner = document.getElementById("spinner");
const channelsContainer = document.getElementById("channelsContainer");
const fileInput = document.getElementById("m3uFile");
const tsInput = document.getElementById("tsFile");
const localM3u8Input = document.getElementById("localM3u8File");
let channels = []; // Array degli elementi canale
let currentSelectedIndex = -1;
// Aggiunge automaticamente il canale demo locale all'avvio
document.addEventListener("DOMContentLoaded", () => {
const demoChannel = document.createElement("div");
demoChannel.className = "channel";
demoChannel.textContent = "Local Demo (TempVideo)";
demoChannel.addEventListener("click", function() {
playChannel("/TempVideo/playlist.m3u8");
currentSelectedIndex = channels.indexOf(demoChannel);
updateSelection();
});
channelsContainer.appendChild(demoChannel);
channels.push(demoChannel);
});
function showSpinner(show = true) {
spinner.style.display = show ? "flex" : "none";
}
function playChannel(streamUrl) {
console.log("Caricamento stream: " + streamUrl);
showSpinner(true);
if (hls) {
hls.destroy();
hls = null;
}
if (Hls.isSupported()) {
hls = new Hls({ enableWorker: true });
hls.loadSource(streamUrl);
hls.attachMedia(video);
hls.once(Hls.Events.MANIFEST_PARSED, () => {
video.play().then(() => {
showSpinner(false);
}).catch(err => {
console.error("Errore nel play:", err);
showSpinner(false);
});
});
hls.on(Hls.Events.ERROR, (event, data) => {
console.error("Errore HLS:", data);
showSpinner(false);
});
} else if (video.canPlayType("application/vnd.apple.mpegurl")) {
video.src = streamUrl;
video.play().then(() => {
showSpinner(false);
}).catch(err => {
console.error("Errore nel play (nativo):", err);
showSpinner(false);
});
} else {
alert("Il tuo browser non supporta lo streaming HLS.");
showSpinner(false);
}
}
function parseChannelList(content) {
const lines = content.split("\n");
channelsContainer.innerHTML = "";
channels = [];
currentSelectedIndex = -1;
let currentTitle = "";
lines.forEach(line => {
line = line.trim();
if (!line) return;
if (line.startsWith("#EXTINF")) {
// Estrae il titolo dal testo dopo la virgola (fallback "Canale IPTV")
const match = line.match(/,(.*)$/);
currentTitle = match ? match[1].trim() : "Canale IPTV";
} else if (line.startsWith("http")) {
const streamUrl = line;
const channelDiv = document.createElement("div");
channelDiv.className = "channel";
channelDiv.textContent = currentTitle;
channelDiv.addEventListener("click", function() {
playChannel(streamUrl);
currentSelectedIndex = channels.indexOf(channelDiv);
updateSelection();
});
channelsContainer.appendChild(channelDiv);
channels.push(channelDiv);
}
});
}
// Event listener per il file input: il file scelto dall'utente viene letto e parsato
fileInput.addEventListener("change", function(event) {
const file = event.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = function(e) {
const content = e.target.result;
parseChannelList(content);
};
reader.readAsText(file);
});
// Event listener per il file input TS: trasforma il file locale in MP4 tramite mux.js e lo riproduce
tsInput.addEventListener("change", function(event) {
const file = event.target.files[0];
if (!file) return;
// Reset player
if (hls) {
hls.destroy();
hls = null;
}
// Crea un transmuxer MP4
const transmuxer = new muxjs.mp4.Transmuxer();
const reader = new FileReader();
reader.onload = function(e) {
const data = new Uint8Array(e.target.result);
// Setup MediaSource
const mime = 'video/mp4; codecs="avc1.42E01E,mp4a.40.2"';
const mediaSource = new MediaSource();
video.src = URL.createObjectURL(mediaSource);
mediaSource.addEventListener('sourceopen', function() {
const sourceBuffer = mediaSource.addSourceBuffer(mime);
// Quando mux.js ha dei dati pronti
transmuxer.on('data', (segment) => {
const data = new Uint8Array(segment.initSegment.byteLength + segment.data.byteLength);
data.set(segment.initSegment, 0);
data.set(segment.data, segment.initSegment.byteLength);
sourceBuffer.appendBuffer(data);
});
// Invia i dati al transmuxer
transmuxer.push(data);
transmuxer.flush();
});
video.play().catch(console.error);
};
reader.readAsArrayBuffer(file);
});
// Event listener per la cartella locale contenente m3u8 e ts
localM3u8Input.addEventListener("change", function(event) {
const files = Array.from(event.target.files);
const m3u8File = files.find(f => f.name.endsWith('.m3u8'));
if (!m3u8File) {
alert("No .m3u8 file found in the selected folder.");
return;
}
// Reset player
if (hls) {
hls.destroy();
hls = null;
}
const reader = new FileReader();
reader.onload = function(e) {
const content = e.target.result;
const lines = content.split('\n');
const tsFilenames = lines
.map(line => line.trim())
.filter(line => line && !line.startsWith('#'));
if (tsFilenames.length === 0) {
alert("No TS segments found in m3u8 file.");
return;
}
playLocalSegments(files, tsFilenames);
};
reader.readAsText(m3u8File);
});
async function playLocalSegments(allFiles, tsFilenames) {
const transmuxer = new muxjs.mp4.Transmuxer();
const mime = 'video/mp4; codecs="avc1.42E01E,mp4a.40.2"';
const mediaSource = new MediaSource();
video.src = URL.createObjectURL(mediaSource);
mediaSource.addEventListener('sourceopen', async function() {
const sourceBuffer = mediaSource.addSourceBuffer(mime);
transmuxer.on('data', (segment) => {
const data = new Uint8Array(segment.initSegment.byteLength + segment.data.byteLength);
data.set(segment.initSegment, 0);
data.set(segment.data, segment.initSegment.byteLength);
// Append buffer safely
if (!sourceBuffer.updating) {
try {
sourceBuffer.appendBuffer(data);
} catch (e) {
console.error("Buffer append error:", e);
}
} else {
// Simple queue mechanism could be added here for robustness
console.warn("Buffer updating, dropping frame for simplicity in demo");
}
});
// Sequentially load and process TS files
for (const filename of tsFilenames) {
const tsFile = allFiles.find(f => f.name === filename);
if (tsFile) {
const arrayBuffer = await tsFile.arrayBuffer();
const data = new Uint8Array(arrayBuffer);
transmuxer.push(data);
transmuxer.flush();
// Small delay to allow buffer to process
await new Promise(r => setTimeout(r, 100));
} else {
console.warn(`File ${filename} not found in selected folder.`);
}
}
// Signal end of stream
if (mediaSource.readyState === 'open') {
mediaSource.endOfStream();
}
});
video.play().catch(console.error);
}
function updateSelection() {
channels.forEach((channel, index) => {
if (index === currentSelectedIndex) {
channel.classList.add("selected");
channel.scrollIntoView({ behavior: "smooth", block: "nearest" });
} else {
channel.classList.remove("selected");
}
});
}
/********** EVENTI DA TASTIERA **********/
document.addEventListener("keydown", function(e) {
// Se l'utente preme "l", simula un click sul file input per ricaricare la lista
if (e.key.toLowerCase() === "l") {
e.preventDefault();
fileInput.click();
return;
}
// Navigazione nella lista dei canali
if (channels.length > 0) {
if (e.key === "ArrowDown") {
e.preventDefault();
currentSelectedIndex = (currentSelectedIndex + 1) % channels.length;
updateSelection();
return;
}
if (e.key === "ArrowUp") {
e.preventDefault();
currentSelectedIndex = (currentSelectedIndex - 1 + channels.length) % channels.length;
updateSelection();
return;
}
if (e.key === "Enter") {
e.preventDefault();
if (currentSelectedIndex >= 0 && currentSelectedIndex < channels.length) {
channels[currentSelectedIndex].click();
}
return;
}
}
// Controlli del player via tastiera
if (e.key === " ") { // Space per pausa/ripresa
e.preventDefault();
video.paused ? video.play() : video.pause();
} else if (e.key === "+" || e.key === "=") { // Volume su
e.preventDefault();
video.volume = Math.min(video.volume + 0.1, 1);
} else if (e.key === "-") { // Volume giù
e.preventDefault();
video.volume = Math.max(video.volume - 0.1, 0);
} else if (e.key.toLowerCase() === "m") { // Toggle mute
e.preventDefault();
video.muted = !video.muted;
} else if (e.key.toLowerCase() === "f") { // Fullscreen toggle
e.preventDefault();
if (!document.fullscreenElement) {
video.requestFullscreen ? video.requestFullscreen() : (video.webkitRequestFullscreen && video.webkitRequestFullscreen());
} else {
document.exitFullscreen ? document.exitFullscreen() : (document.webkitExitFullscreen && document.webkitExitFullscreen());
}
} else if (e.key.toLowerCase() === "p") { // Picture-in-Picture toggle
e.preventDefault();
if (document.pictureInPictureElement) {
document.exitPictureInPicture().catch(err => console.error(err));
} else {
video.requestPictureInPicture ? video.requestPictureInPicture().catch(err => console.error(err)) : null;
}
}
});
/********** SUPPORTO JOYPAD (CONTROLLER/TELECOMANDO) CON DEBOUNCE **********/
const debounceDelay = 250;
// Impostiamo un oggetto per il debounce degli eventi simulati
const debounceTimes = {
ArrowUp: 0,
ArrowDown: 0,
Enter: 0,
" ": 0,
m: 0,
f: 0,
p: 0,
l: 0, // Per il file input
// Volume su e giù li gestiamo con i pulsanti RT e LT
volUp: 0,
volDown: 0
};
function simulateKeyEvent(key) {
const event = new KeyboardEvent("keydown", { key: key, bubbles: true });
document.dispatchEvent(event);
}
function pollGamepad() {
const gamepads = navigator.getGamepads ? navigator.getGamepads() : [];
if (gamepads[0]) {
const gp = gamepads[0];
let now = Date.now();
// D-Pad Up → ArrowUp
if (gp.buttons[12] && gp.buttons[12].pressed) {
if (now - debounceTimes["ArrowUp"] > debounceDelay) {
simulateKeyEvent("ArrowUp");
debounceTimes["ArrowUp"] = now;
}
}
// D-Pad Down → ArrowDown
if (gp.buttons[13] && gp.buttons[13].pressed) {
if (now - debounceTimes["ArrowDown"] > debounceDelay) {
simulateKeyEvent("ArrowDown");
debounceTimes["ArrowDown"] = now;
}
}
// A Button (indice 0) → Enter
if (gp.buttons[0] && gp.buttons[0].pressed) {
if (now - debounceTimes["Enter"] > debounceDelay) {
simulateKeyEvent("Enter");
debounceTimes["Enter"] = now;
}
}
// B Button (indice 1) → Space (pausa/ripresa)
if (gp.buttons[1] && gp.buttons[1].pressed) {
if (now - debounceTimes[" "] > debounceDelay) {
simulateKeyEvent(" ");
debounceTimes[" "] = now;
}
}
// LT (indice 6) → "-" (Volume giù)
if (gp.buttons[6] && gp.buttons[6].pressed) {
if (now - debounceTimes["volDown"] > debounceDelay) {
simulateKeyEvent("-");
debounceTimes["volDown"] = now;
}
}
// RT (indice 7) → "+" (Volume su)
if (gp.buttons[7] && gp.buttons[7].pressed) {
if (now - debounceTimes["volUp"] > debounceDelay) {
simulateKeyEvent("+");
debounceTimes["volUp"] = now;
}
}
// X Button (indice 2) → "m" (Toggle mute)
if (gp.buttons[2] && gp.buttons[2].pressed) {
if (now - debounceTimes["m"] > debounceDelay) {
simulateKeyEvent("m");
debounceTimes["m"] = now;
}
}
// Y Button (indice 3) → "f" (Fullscreen toggle)
if (gp.buttons[3] && gp.buttons[3].pressed) {
if (now - debounceTimes["f"] > debounceDelay) {
simulateKeyEvent("f");
debounceTimes["f"] = now;
}
}
// LB (indice 4) → "l" (Per riaprire il file input)
if (gp.buttons[4] && gp.buttons[4].pressed) {
if (now - debounceTimes["l"] > debounceDelay) {
simulateKeyEvent("l");
debounceTimes["l"] = now;
}
}
// Back Button (indice 8) → "p" (Picture-in-Picture)
if (gp.buttons[8] && gp.buttons[8].pressed) {
if (now - debounceTimes["p"] > debounceDelay) {
simulateKeyEvent("p");
debounceTimes["p"] = now;
}
}
}
requestAnimationFrame(pollGamepad);
}
window.addEventListener("gamepadconnected", function(e) {
console.log("Gamepad collegato:", e.gamepad);
});
if (navigator.getGamepads) {
requestAnimationFrame(pollGamepad);
}
video.addEventListener("playing", () => showSpinner(false));
video.addEventListener("waiting", () => showSpinner(true));
|