SPB Git

Repository Public

live.ts 11.9 KB 337 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : MacLustr Vision8 * File             : web/src/live.ts9 * Module           : web10 * Repository       : https://git.spboucher.ai/maclustr-vision11 * Project Website  : https://camera.spboucher.ai12 * Created          : 2026-11-3013 * Last Modified    : 2026-11-3014 *15 * Author           : Simon-Pierre Boucher16 * Position         : Professor of Finance17 * Institution      : Université du Québec en Outaouais (UQO)18 * Organization     : SP Boucher19 * Website          : https://spboucher.ai20 * Git              : https://git.spboucher.ai21 *22 * Preferred Contact: admin@spboucher.ai23 * Technical Contact: dev@spboucher.ai24 * Security/Admin   : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License          : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142// Lecteur du direct : MSE sur WebSocket (faible latence, passe par le tunnel HTTPS), repli HLS natif.43// Reconnexion exponentielle avec gigue, état explicite, jamais d'image figée présentée comme du direct.44export type LiveState = 'connecting' | 'live' | 'stalled' | 'offline';45export type Transport = 'auto' | 'mse' | 'hls';46export type LiveStats = { bufferS: number | null; dropped: number | null; frames: number | null; kbps: number | null; width: number; height: number; liveLagS: number | null };47export type LiveInfo = { state: LiveState; transport: 'mse' | 'hls' | null; lastFrameAt: number; codec: string | null; attempt: number };4849const VIDEO_CODECS = ['avc1.640029', 'avc1.64002A', 'avc1.640033', 'hvc1.1.6.L153.B0'];50const AUDIO_CODECS = ['mp4a.40.2', 'mp4a.40.5', 'flac', 'opus'];5152function mseCtor(): typeof MediaSource | null {53  const w = window as any;54  return w.ManagedMediaSource || w.MediaSource || null;55}56export function mseSupported(): boolean {57  return !!mseCtor();58}59export function hevcSupported(): boolean {60  const M = mseCtor();61  if (M) return M.isTypeSupported('video/mp4; codecs="hvc1.1.6.L153.B0"');62  return !!document.createElement('video').canPlayType('video/mp4; codecs="hvc1.1.6.L153.B0"');63}64export function nativeHls(): boolean {65  // HLS natif fiable : Safari / WebKit seulement (Chromium annonce le format sans lire ce flux fMP4 en direct)66  const ua = navigator.userAgent;67  return /AppleWebKit/.test(ua) && !/Chrome|Chromium|Edg\//.test(ua) && !!document.createElement('video').canPlayType('application/vnd.apple.mpegurl');68}6970export class LivePlayer {71  private video: HTMLVideoElement;72  private wsPath: string;73  private hlsPath: string;74  private audio: boolean;75  private preferred: Transport;76  private onInfo: (i: LiveInfo) => void;77  private ws: WebSocket | null = null;78  private ms: MediaSource | null = null;79  private sb: SourceBuffer | null = null;80  private queue: ArrayBuffer[] = [];81  private queued = 0;82  private objectUrl: string | null = null;83  private attempt = 0;84  private retry: number | null = null;85  private watchdog: number | null = null;86  private stopped = true;87  private info: LiveInfo = { state: 'connecting', transport: null, lastFrameAt: 0, codec: null, attempt: 0 };88  private lastTime = -1;89  private bytes: { t: number; n: number }[] = [];90  private onVisibility = () => {91    // onglet masqué : on libère l'abonnement (l'enregistrement serveur n'est pas concerné)92    if (document.hidden) this.teardown();93    else if (!this.stopped) this.connect();94  };9596  constructor(video: HTMLVideoElement, o: { wsPath: string; hlsPath: string; audio: boolean; transport: Transport; onInfo: (i: LiveInfo) => void }) {97    this.video = video;98    this.wsPath = o.wsPath;99    this.hlsPath = o.hlsPath;100    this.audio = o.audio;101    this.preferred = o.transport;102    this.onInfo = o.onInfo;103  }104105  start(): void {106    this.stopped = false;107    document.addEventListener('visibilitychange', this.onVisibility);108    this.watchdog = window.setInterval(() => this.check(), 1000);109    if (!document.hidden) this.connect();110  }111112  stop(): void {113    this.stopped = true;114    document.removeEventListener('visibilitychange', this.onVisibility);115    if (this.watchdog) clearInterval(this.watchdog);116    this.teardown();117  }118119  /** Mesures réelles du lecteur (rien d'estimé côté serveur). */120  stats(): LiveStats {121    const v = this.video;122    let bufferS: number | null = null;123    let liveLagS: number | null = null;124    try {125      if (v.buffered.length) {126        const end = v.buffered.end(v.buffered.length - 1);127        bufferS = Math.max(0, end - v.currentTime);128        liveLagS = bufferS;129      }130      if (this.info.transport === 'hls' && v.seekable.length) liveLagS = Math.max(0, v.seekable.end(v.seekable.length - 1) - v.currentTime);131    } catch {132      /* lecteur en cours de réinitialisation */133    }134    const q = typeof v.getVideoPlaybackQuality === 'function' ? v.getVideoPlaybackQuality() : null;135    const span = this.bytes.length > 1 ? (this.bytes[this.bytes.length - 1].t - this.bytes[0].t) / 1000 : 0;136    const total = this.bytes.reduce((a, b) => a + b.n, 0);137    return { bufferS, dropped: q ? q.droppedVideoFrames : null, frames: q ? q.totalVideoFrames : null, kbps: span > 0.5 ? (total * 8) / span / 1000 : null, width: v.videoWidth, height: v.videoHeight, liveLagS };138  }139140  private set(patch: Partial<LiveInfo>): void {141    const next = { ...this.info, ...patch };142    const changed = next.state !== this.info.state || next.transport !== this.info.transport || next.codec !== this.info.codec || next.attempt !== this.info.attempt || next.lastFrameAt !== this.info.lastFrameAt;143    this.info = next;144    if (changed) this.onInfo(next);145  }146147  private useHls(): boolean {148    if (this.preferred === 'hls') return nativeHls();149    if (this.preferred === 'mse') return false;150    return !mseSupported() && nativeHls();151  }152153  private connect(): void {154    this.teardown();155    if (this.stopped) return;156    this.set({ state: this.info.lastFrameAt ? 'stalled' : 'connecting', attempt: this.attempt });157    if (this.useHls()) return this.connectHls();158    if (!mseSupported()) {159      this.set({ state: 'offline', transport: null });160      return;161    }162    this.connectMse();163  }164165  private connectHls(): void {166    const v = this.video;167    this.set({ transport: 'hls', codec: null });168    v.src = `${this.hlsPath}&_=${Date.now()}`;169    v.onerror = () => this.fail();170    v.play().catch(() => {});171  }172173  private connectMse(): void {174    const M = mseCtor()!;175    const v = this.video;176    const ms = new M();177    this.ms = ms;178    this.set({ transport: 'mse' });179    if ((window as any).ManagedMediaSource && ms instanceof (window as any).ManagedMediaSource) {180      v.disableRemotePlayback = true;181      (v as any).srcObject = ms;182    } else {183      this.objectUrl = URL.createObjectURL(ms);184      v.src = this.objectUrl;185    }186    const proto = location.protocol === 'https:' ? 'wss' : 'ws';187    const ws = new WebSocket(`${proto}://${location.host}${this.wsPath}`);188    ws.binaryType = 'arraybuffer';189    this.ws = ws;190    let opened = false;191    const sendCodecs = () => {192      if (!opened || ms.readyState !== 'open' || this.ws !== ws) return;193      const list = [...VIDEO_CODECS, ...(this.audio ? AUDIO_CODECS : [])].filter((c) => M.isTypeSupported(`video/mp4; codecs="${c}"`));194      ws.send(JSON.stringify({ type: 'mse', value: list.join(',') }));195    };196    ms.addEventListener('sourceopen', sendCodecs, { once: true });197    ws.onopen = () => {198      opened = true;199      sendCodecs();200    };201    ws.onmessage = (ev) => {202      if (this.ws !== ws) return;203      if (typeof ev.data === 'string') {204        let msg: any;205        try {206          msg = JSON.parse(ev.data);207        } catch {208          return;209        }210        if (msg.type === 'mse') {211          try {212            const sb = ms.addSourceBuffer(msg.value);213            sb.mode = 'segments';214            sb.addEventListener('updateend', () => this.flush());215            this.sb = sb;216            this.set({ codec: /codecs="([^"]+)"/.exec(msg.value)?.[1] || null });217          } catch {218            this.fail();219          }220        } else if (msg.type === 'error') {221          this.fail();222        }223        return;224      }225      this.push(ev.data as ArrayBuffer);226    };227    ws.onclose = () => {228      if (this.ws === ws) this.fail();229    };230    ws.onerror = () => {231      if (this.ws === ws) this.fail();232    };233    v.play().catch(() => {});234  }235236  private push(buf: ArrayBuffer): void {237    const now = performance.now();238    this.bytes.push({ t: now, n: buf.byteLength });239    while (this.bytes.length && now - this.bytes[0].t > 4000) this.bytes.shift();240    this.queue.push(buf);241    this.queued += buf.byteLength;242    if (this.queued > 24 * 1024 * 1024) return this.fail(); // lecteur à la traîne : on repart du direct243    this.flush();244  }245246  private flush(): void {247    const sb = this.sb;248    if (!sb || sb.updating || !this.queue.length) return;249    const v = this.video;250    try {251      if (sb.buffered.length) {252        const start = sb.buffered.start(0);253        const end = sb.buffered.end(sb.buffered.length - 1);254        if (end - start > 40) {255          sb.remove(start, end - 20);256          return;257        }258        // rester près du direct259        if (!v.paused && v.currentTime < end - 4) v.currentTime = end - 0.6;260        else if (v.currentTime < start) v.currentTime = start;261      }262      const buf = this.queue.shift()!;263      this.queued -= buf.byteLength;264      sb.appendBuffer(buf);265    } catch {266      this.fail();267    }268  }269270  /** Surveillance : l'image n'est « en direct » que si le temps de lecture avance réellement. */271  private check(): void {272    if (this.stopped || document.hidden) return;273    const v = this.video;274    const now = Date.now();275    const t = v.currentTime;276    if (t !== this.lastTime && v.readyState >= 2) {277      this.lastTime = t;278      this.attempt = 0;279      this.set({ state: 'live', lastFrameAt: now, attempt: 0 });280      return;281    }282    if (v.paused && v.readyState >= 2 && this.info.transport) v.play().catch(() => {});283    const since = now - (this.info.lastFrameAt || now);284    if (this.info.state === 'live' && since > 4000) this.set({ state: 'stalled' });285    if (this.info.lastFrameAt && since > 12000 && !this.retry) this.fail();286  }287288  private fail(): void {289    if (this.stopped) return;290    this.teardown();291    this.attempt++;292    const delay = Math.min(30000, 1000 * 2 ** Math.min(this.attempt - 1, 5)) * (0.7 + Math.random() * 0.6);293    this.set({ state: this.attempt > 1 || !this.info.lastFrameAt ? 'offline' : 'stalled', attempt: this.attempt });294    if (this.retry) clearTimeout(this.retry);295    this.retry = window.setTimeout(() => {296      this.retry = null;297      if (!document.hidden) this.connect();298    }, delay);299  }300301  private teardown(): void {302    if (this.retry) {303      clearTimeout(this.retry);304      this.retry = null;305    }306    const ws = this.ws;307    this.ws = null;308    if (ws) {309      ws.onclose = ws.onerror = ws.onmessage = null;310      try {311        ws.close();312      } catch {313        /* rien */314      }315    }316    this.sb = null;317    this.ms = null;318    this.queue = [];319    this.queued = 0;320    const v = this.video;321    v.onerror = null;322    try {323      v.pause();324      v.removeAttribute('src');325      (v as any).srcObject = null;326      v.load();327    } catch {328      /* rien */329    }330    if (this.objectUrl) {331      URL.revokeObjectURL(this.objectUrl);332      this.objectUrl = null;333    }334    this.lastTime = -1;335  }336}337
Files main
Menu

Theme