Files
takeone-youtube-clone/resources/views/live/broadcast.blade.php
T
ghassanandClaude Opus 4.7 5bf1128196 feat(live): polish — ended-state, chat, viewer actions, Private option
Restores the live streaming controllers / views / model from the
pre-audit WIP that got stashed on 2026-10-21, then applies the Phase 6
polish items:

## /live/new form
Add a Private visibility option that mirrors the upload modal's
wording — "Only you can see this stream. Perfect for testing without
an audience." Validator in LiveStreamController@store now permits
public|unlisted|private (was public|unlisted).

## Watch page ended-state
When the stream status is "ended", the overlay is a solid "Stream
ended" card showing the stream's duration (started_at → ended_at)
and, when a recording was published, a Watch Replay CTA linking to
the saved video. Previously an ended stream showed the generic
"Waiting for the broadcast to start" placeholder forever.

## Channel name link
The uploader's name in the meta row is now a real <a href> to the
channel page.

## Viewer action row
Subscribe + Share buttons below the player, visible to anyone except
the owner. Subscribe for guests uses the Phase 7 ?intended= pattern
so after sign-in they land back on the stream.

## Live chat (DB-backed polling)
New live_chat_messages table (migration 2026_10_21_000003). Viewers
GET /live/{stream}/chat?since=N every 3 seconds; signed-in users POST
to the same path (rate-limited at 60/min). Guests see the panel in
read-only mode with a "Sign in to chat" placeholder.

Private streams reject chat for anyone but the owner (404). Non-live
status rejects chat sends (422). Author name is snapshotted at post
time so a renamed account's old messages keep the name they used.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
2026-10-21 12:41:56 +03:00

447 lines
19 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
@extends('layouts.app')
@section('title', 'Go Live — '.$stream->title)
@section('extra_styles')
<style>
.lv-wrap { max-width: 1100px; margin: 0 auto; padding: 16px; }
/* The preview owns the screen on a phone. Everything else floats on it. */
.lv-stage {
position: relative; background: #000; border-radius: 16px; overflow: hidden;
aspect-ratio: 16 / 9; box-shadow: 0 10px 40px rgba(0,0,0,.45);
}
.lv-stage video { width: 100%; height: 100%; object-fit: cover; display: block; background: #000; }
/* Mirror only the selfie camera — a mirrored rear camera looks broken. */
.lv-stage video.mirrored { transform: scaleX(-1); }
.lv-badge {
position: absolute; top: 12px; left: 12px; display: inline-flex; align-items: center; gap: 7px;
padding: 6px 12px; border-radius: 999px; font-size: 12px; font-weight: 700; letter-spacing: .04em;
background: rgba(0,0,0,.6); color: #fff; backdrop-filter: blur(8px);
}
.lv-badge .dot { width: 8px; height: 8px; border-radius: 50%; background: #6b7280; }
.lv-badge.is-live { background: rgba(239,68,68,.92); }
.lv-badge.is-live .dot { background: #fff; animation: lvPulse 1.4s ease-in-out infinite; }
@keyframes lvPulse { 0%,100% { opacity: 1; transform: scale(1); } 50% { opacity: .35; transform: scale(.75); } }
.lv-stats {
position: absolute; top: 12px; right: 12px; display: flex; flex-direction: column; gap: 4px;
padding: 8px 12px; border-radius: 12px; background: rgba(0,0,0,.55); backdrop-filter: blur(8px);
color: #e5e7eb; font-size: 11px; font-variant-numeric: tabular-nums; text-align: right; min-width: 120px;
}
.lv-stats b { color: #fff; font-weight: 600; }
.lv-stats .warn { color: #fbbf24; }
.lv-stats .bad { color: #f87171; }
.lv-controls {
position: absolute; left: 0; right: 0; bottom: 0; padding: 16px;
display: flex; align-items: center; justify-content: center; gap: 12px;
background: linear-gradient(to top, rgba(0,0,0,.75), transparent);
}
.lv-btn {
width: 52px; height: 52px; border-radius: 50%; border: 1px solid rgba(255,255,255,.25);
background: rgba(255,255,255,.12); color: #fff; font-size: 20px; cursor: pointer;
display: grid; place-items: center; backdrop-filter: blur(8px); transition: transform .12s ease, background .15s ease;
}
.lv-btn:hover { background: rgba(255,255,255,.22); }
.lv-btn:active { transform: scale(.92); }
.lv-btn.off { background: rgba(239,68,68,.85); border-color: transparent; }
.lv-btn:disabled { opacity: .4; cursor: not-allowed; }
.lv-golive {
min-width: 150px; height: 52px; padding: 0 26px; border-radius: 999px; border: 0;
background: #ef4444; color: #fff; font-weight: 700; font-size: 15px; cursor: pointer;
display: inline-flex; align-items: center; gap: 9px; transition: transform .12s ease, background .15s ease;
}
.lv-golive:hover { background: #dc2626; }
.lv-golive:active { transform: scale(.97); }
.lv-golive:disabled { opacity: .55; cursor: not-allowed; }
.lv-golive.is-live { background: #111827; border: 1px solid rgba(255,255,255,.25); }
.lv-meta { margin-top: 18px; display: grid; gap: 14px; grid-template-columns: 1fr; }
@media (min-width: 860px) { .lv-meta { grid-template-columns: 1.4fr 1fr; } }
.lv-card { background: var(--yt-bg-secondary, #181818); border: 1px solid rgba(255,255,255,.08); border-radius: 14px; padding: 16px; }
.lv-card h3 { font-size: 13px; text-transform: uppercase; letter-spacing: .06em; opacity: .6; margin: 0 0 10px; }
.lv-share { display: flex; gap: 8px; }
.lv-share input {
flex: 1; min-width: 0; background: rgba(255,255,255,.06); border: 1px solid rgba(255,255,255,.12);
border-radius: 10px; padding: 10px 12px; color: inherit; font-size: 13px;
}
.lv-note { font-size: 12px; opacity: .6; line-height: 1.6; margin-top: 10px; }
.lv-msg { margin-top: 14px; padding: 12px 14px; border-radius: 12px; font-size: 14px; display: none; }
.lv-msg.err { display: block; background: rgba(239,68,68,.12); border: 1px solid rgba(239,68,68,.35); color: #fca5a5; }
.lv-msg.ok { display: block; background: rgba(34,197,94,.12); border: 1px solid rgba(34,197,94,.35); color: #86efac; }
</style>
@endsection
@section('content')
<div class="lv-wrap">
<div class="lv-stage">
<video id="lvPreview" autoplay playsinline muted></video>
<div class="lv-badge" id="lvBadge"><span class="dot"></span><span id="lvBadgeText">READY</span></div>
<div class="lv-stats" id="lvStats" style="display:none;">
<div><b id="lvRes">—</b> · <b id="lvFps">—</b> fps</div>
<div><b id="lvBitrate">—</b></div>
<div id="lvHealth">—</div>
<div><b id="lvTimer">00:00</b></div>
</div>
<div class="lv-controls">
<button class="lv-btn" id="lvMic" title="Mute microphone"><i class="bi bi-mic-fill"></i></button>
<button class="lv-golive" id="lvGoLive"><i class="bi bi-broadcast"></i><span id="lvGoLiveText">Go Live</span></button>
<button class="lv-btn" id="lvFlip" title="Switch camera"><i class="bi bi-arrow-repeat"></i></button>
</div>
</div>
<div class="lv-msg" id="lvMsg"></div>
<div class="lv-meta">
<div class="lv-card">
<h3>{{ $stream->title }}</h3>
@if ($stream->description)
<p style="margin:0 0 10px;font-size:14px;opacity:.8;">{{ $stream->description }}</p>
@endif
<div class="lv-share">
<input type="text" id="lvWatchUrl" value="{{ $watchUrl }}" readonly onclick="this.select()">
<button class="action-btn" type="button" id="lvCopy"><i class="bi bi-clipboard"></i> <span>Copy</span></button>
</div>
<p class="lv-note">
Anyone with this link can watch while you are live.
{{ $stream->visibility === 'public' ? 'This stream is also listed on the Live page.' : 'This stream is unlisted — only people with the link can find it.' }}
</p>
</div>
<div class="lv-card">
<h3>Quality</h3>
<p class="lv-note" style="margin-top:0;">
Targeting {{ config('live.video_width') }}×{{ config('live.video_height') }} at {{ config('live.video_fps') }} fps.
If your upload speed drops, the picture softens instead of freezing — that is the connection adapting, not a fault.
Wi-Fi or 5G will hold 1080p most reliably.
</p>
</div>
</div>
</div>
@endsection
@section('scripts')
<script>
(function () {
'use strict';
var CFG = {
whipUrl: @json($whipUrl),
tokenUrl: @json(route('live.token', $stream)),
stopUrl: @json(route('live.stop', $stream)),
csrf: @json(csrf_token()),
iceServers: @json($iceServers),
width: {{ (int) config('live.video_width') }},
height: {{ (int) config('live.video_height') }},
fps: {{ (int) config('live.video_fps') }},
maxBitrate: {{ (int) config('live.max_bitrate') }}
};
var el = function (id) { return document.getElementById(id); };
var preview = el('lvPreview'), badge = el('lvBadge'), badgeText = el('lvBadgeText');
var goLive = el('lvGoLive'), goLiveText = el('lvGoLiveText');
var msg = el('lvMsg'), stats = el('lvStats');
var stream = null, pc = null, statsTimer = null, clockTimer = null;
var facing = 'environment', live = false, startedAt = 0;
function say(text, kind) {
msg.textContent = text;
msg.className = 'lv-msg ' + (kind || 'err');
}
function clearSay() { msg.className = 'lv-msg'; msg.textContent = ''; }
/* ---------------- Camera ---------------- */
// Ask for 1080p as an IDEAL, never `exact`: a phone whose camera cannot do
// it should hand back its best effort, not refuse to open at all.
function constraints() {
return {
video: {
width: { ideal: CFG.width },
height: { ideal: CFG.height },
frameRate: { ideal: CFG.fps },
facingMode: { ideal: facing }
},
audio: {
echoCancellation: true,
noiseSuppression: true,
autoGainControl: true
}
};
}
async function openCamera() {
if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
say('This browser cannot open a camera. On iPhone use Safari; on Android use Chrome.');
goLive.disabled = true;
return false;
}
// getUserMedia only exists in a secure context. Saying so plainly beats
// a bare "Permission denied" the user cannot act on.
if (!window.isSecureContext) {
say('The camera needs a secure (HTTPS) connection. Open this page over https.');
goLive.disabled = true;
return false;
}
try {
if (stream) { stream.getTracks().forEach(function (t) { t.stop(); }); }
stream = await navigator.mediaDevices.getUserMedia(constraints());
} catch (e) {
if (e && (e.name === 'NotAllowedError' || e.name === 'SecurityError')) {
say('Camera and microphone access was blocked. Allow it in your browser settings, then reload.');
} else if (e && e.name === 'NotFoundError') {
say('No camera was found on this device.');
} else if (e && e.name === 'NotReadableError') {
say('The camera is already in use by another app. Close it and try again.');
} else {
say('Could not start the camera: ' + (e && e.message ? e.message : e));
}
goLive.disabled = true;
return false;
}
preview.srcObject = stream;
preview.classList.toggle('mirrored', facing === 'user');
goLive.disabled = false;
clearSay();
return true;
}
/* ---------------- Publish (WHIP) ---------------- */
async function startBroadcast() {
goLive.disabled = true;
goLiveText.textContent = 'Starting…';
clearSay();
try {
// The publish credential is minted now, not at page load, so its
// short life starts when the user actually goes live.
var tokenRes = await fetch(CFG.tokenUrl, {
method: 'POST',
headers: { 'X-CSRF-TOKEN': CFG.csrf, 'Accept': 'application/json' },
credentials: 'same-origin'
});
if (!tokenRes.ok) { throw new Error('Could not get permission to publish (' + tokenRes.status + ').'); }
var auth = await tokenRes.json();
pc = new RTCPeerConnection({
iceServers: auth.ice_servers && auth.ice_servers.length ? auth.ice_servers : CFG.iceServers,
bundlePolicy: 'max-bundle'
});
pc.addEventListener('connectionstatechange', function () {
if (pc.connectionState === 'failed' || pc.connectionState === 'disconnected') {
say('The connection to the server dropped. Check your signal and go live again.');
stopBroadcast(true);
}
});
stream.getTracks().forEach(function (track) {
// maintain-resolution keeps 1920x1080 and sheds frame rate when
// the uplink tightens. For a match or a performance, a sharp
// 20fps reads better than a soft, blocky 30.
if (track.kind === 'video') { track.contentHint = 'detail'; }
pc.addTrack(track, stream);
});
var videoSender = pc.getSenders().find(function (s) { return s.track && s.track.kind === 'video'; });
if (videoSender) {
var params = videoSender.getParameters();
params.encodings = params.encodings && params.encodings.length ? params.encodings : [{}];
params.encodings[0].maxBitrate = CFG.maxBitrate;
params.encodings[0].maxFramerate = CFG.fps;
params.degradationPreference = 'maintain-resolution';
try { await videoSender.setParameters(params); } catch (e) { /* older browsers ignore this */ }
}
var offer = await pc.createOffer();
await pc.setLocalDescription(offer);
await iceGatheringComplete(pc);
var res = await fetch(auth.whip_url || CFG.whipUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/sdp',
// Basic auth keeps the credential out of the URL, and so
// out of proxy and access logs.
'Authorization': 'Basic ' + btoa('publisher:' + auth.token)
},
body: pc.localDescription.sdp
});
if (res.status === 401 || res.status === 403) { throw new Error('The server refused the broadcast. Reload the page and try again.'); }
if (!res.ok) { throw new Error('The server rejected the stream (' + res.status + ').'); }
await pc.setRemoteDescription({ type: 'answer', sdp: await res.text() });
live = true;
startedAt = Date.now();
badge.classList.add('is-live');
badgeText.textContent = 'LIVE';
goLive.classList.add('is-live');
goLiveText.textContent = 'End Stream';
goLive.disabled = false;
stats.style.display = 'flex';
say('You are live. Share the link below.', 'ok');
statsTimer = setInterval(sampleStats, 1000);
clockTimer = setInterval(tickClock, 1000);
} catch (e) {
say(e && e.message ? e.message : String(e));
await stopBroadcast(true);
}
}
// Wait for ICE to finish rather than trickling: WHIP is a single
// offer/answer exchange, so the offer must already carry the candidates.
function iceGatheringComplete(pc) {
if (pc.iceGatheringState === 'complete') { return Promise.resolve(); }
return new Promise(function (resolve) {
var done = false;
function finish() { if (!done) { done = true; resolve(); } }
pc.addEventListener('icegatheringstatechange', function () {
if (pc.iceGatheringState === 'complete') { finish(); }
});
// Never hang on a candidate that will not arrive.
setTimeout(finish, 3000);
});
}
async function stopBroadcast(silent) {
clearInterval(statsTimer); statsTimer = null;
clearInterval(clockTimer); clockTimer = null;
if (pc) { try { pc.close(); } catch (e) {} pc = null; }
if (live) {
try {
await fetch(CFG.stopUrl, {
method: 'POST',
headers: { 'X-CSRF-TOKEN': CFG.csrf, 'Accept': 'application/json' },
credentials: 'same-origin'
});
} catch (e) { /* the server also reaps on unpublish */ }
}
live = false;
badge.classList.remove('is-live');
badgeText.textContent = 'READY';
goLive.classList.remove('is-live');
goLiveText.textContent = 'Go Live';
goLive.disabled = false;
stats.style.display = 'none';
if (!silent) { say('Stream ended.', 'ok'); }
}
/* ---------------- Telemetry ---------------- */
var lastBytes = 0, lastAt = 0;
async function sampleStats() {
if (!pc) { return; }
var report = await pc.getStats();
var kbps = null, fps = null, w = null, h = null, lossPct = null;
report.forEach(function (s) {
if (s.type === 'outbound-rtp' && s.kind === 'video') {
var now = s.timestamp;
if (lastAt && s.bytesSent > lastBytes) {
kbps = Math.round(((s.bytesSent - lastBytes) * 8) / ((now - lastAt) / 1000) / 1000);
}
lastBytes = s.bytesSent; lastAt = now;
if (s.framesPerSecond) { fps = Math.round(s.framesPerSecond); }
if (s.frameWidth) { w = s.frameWidth; h = s.frameHeight; }
}
if (s.type === 'remote-inbound-rtp' && s.kind === 'video' && s.packetsLost != null && s.packetsReceived) {
lossPct = (s.packetsLost / (s.packetsLost + s.packetsReceived)) * 100;
}
});
if (w && h) { el('lvRes').textContent = w + '×' + h; }
if (fps !== null) { el('lvFps').textContent = fps; }
if (kbps !== null) { el('lvBitrate').textContent = (kbps / 1000).toFixed(1) + ' Mbps'; }
// Report the connection honestly — a broadcaster who can see the uplink
// struggling can move rather than wonder why the picture went soft.
var health = el('lvHealth');
if (lossPct === null) { health.textContent = 'connection ok'; health.className = ''; }
else if (lossPct < 2) { health.textContent = 'connection good'; health.className = ''; }
else if (lossPct < 8) { health.textContent = 'connection weak'; health.className = 'warn'; }
else { health.textContent = 'connection poor'; health.className = 'bad'; }
}
function tickClock() {
var s = Math.floor((Date.now() - startedAt) / 1000);
var m = Math.floor(s / 60), sec = s % 60;
el('lvTimer').textContent = (m < 10 ? '0' : '') + m + ':' + (sec < 10 ? '0' : '') + sec;
}
/* ---------------- Controls ---------------- */
goLive.addEventListener('click', function () {
if (live) { stopBroadcast(false); } else { startBroadcast(); }
});
el('lvFlip').addEventListener('click', async function () {
facing = (facing === 'environment') ? 'user' : 'environment';
var wasLive = live;
var ok = await openCamera();
if (!ok) { return; }
// Swap the track inside the existing connection so flipping the camera
// mid-broadcast does not drop the stream.
if (wasLive && pc) {
var newTrack = stream.getVideoTracks()[0];
var sender = pc.getSenders().find(function (s) { return s.track && s.track.kind === 'video'; });
if (sender && newTrack) { try { await sender.replaceTrack(newTrack); } catch (e) {} }
}
});
el('lvMic').addEventListener('click', function () {
if (!stream) { return; }
var track = stream.getAudioTracks()[0];
if (!track) { return; }
track.enabled = !track.enabled;
this.classList.toggle('off', !track.enabled);
this.innerHTML = track.enabled ? '<i class="bi bi-mic-fill"></i>' : '<i class="bi bi-mic-mute-fill"></i>';
});
el('lvCopy').addEventListener('click', function () {
var input = el('lvWatchUrl');
input.select();
navigator.clipboard && navigator.clipboard.writeText(input.value);
var span = this.querySelector('span');
var original = span.textContent;
span.textContent = 'Copied';
setTimeout(function () { span.textContent = original; }, 1400);
});
// A broadcaster who closes the tab must not leave a stream stuck live.
window.addEventListener('pagehide', function () {
if (live && navigator.sendBeacon) {
var body = new FormData();
body.append('_token', CFG.csrf);
navigator.sendBeacon(CFG.stopUrl, body);
}
});
openCamera();
})();
</script>
@endsection