aboutsummaryrefslogtreecommitdiffstats
path: root/web/crib/app.js
blob: 340f33108913e8b294ef3c252b5d24674b0af007 (plain) (blame)
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
"use strict";
 
const mediaPort = "8890";
const retryDelay = 1000;
const freezeAfter = 5000;
const watchdogEvery = 1000;
 
const video = document.getElementById("video");
const statusLabel = document.getElementById("status-label");
const stateTitle = document.getElementById("state-title");
const stateDetail = document.getElementById("state-detail");
 
const stateCopy = {
  connecting: ["Connecting", "Waiting for the camera stream"],
  offline: ["Camera offline", "Retrying automatically…"],
};
 
const mediaBase = new URL(window.location.href);
mediaBase.port = mediaPort;
mediaBase.pathname = "/crib/";
mediaBase.search = "";
mediaBase.hash = "";
 
let reader = null;
let reconnectTimer = null;
let frameCallback = null;
let lastFrameAt = 0;
let stopped = false;
 
function setState(next) {
  const copy = stateCopy[next];
  document.body.dataset.state = next;
  video.controls = next === "live";
  statusLabel.textContent = next;
  if (copy) {
    [stateTitle.textContent, stateDetail.textContent] = copy;
  }
}
 
function clearVideo() {
  video.pause();
  video.srcObject = null;
}
 
function scheduleReconnect(reason) {
  if (stopped) {
    return;
  }
 
  console.warn(`[cribd] ${reason}`);
  reader?.close();
  reader = null;
  clearVideo();
  setState("offline");
  clearTimeout(reconnectTimer);
  reconnectTimer = window.setTimeout(connect, retryDelay);
}
 
function loadReader() {
  if (window.MediaMTXWebRTCReader !== undefined) {
    return Promise.resolve();
  }
 
  return new Promise((resolve, reject) => {
    const script = document.createElement("script");
    script.src = new URL("reader.js", mediaBase).toString();
    script.onload = () => {
      if (window.MediaMTXWebRTCReader === undefined) {
        reject(new Error("MediaMTX reader did not load"));
        return;
      }
      resolve();
    };
    script.onerror = () => {
      script.remove();
      reject(new Error("MediaMTX reader is unavailable"));
    };
    document.head.append(script);
  });
}
 
async function connect() {
  reconnectTimer = null;
 
  try {
    await loadReader();
    if (stopped) {
      return;
    }
 
    reader = new window.MediaMTXWebRTCReader({
      url: new URL("whep", mediaBase).toString(),
      onError: scheduleReconnect,
      onTrack: (event) => {
        if (stopped || event.streams.length === 0) {
          return;
        }
 
        video.srcObject = event.streams[0];
        lastFrameAt = performance.now();
        video.play().catch(() => undefined);
      },
    });
  } catch (error) {
    scheduleReconnect(error);
  }
}
 
function markFrame() {
  if (video.srcObject === null) {
    return;
  }
  lastFrameAt = performance.now();
  if (document.body.dataset.state !== "live") {
    setState("live");
  }
}
 
if (typeof video.requestVideoFrameCallback === "function") {
  const onFrame = () => {
    markFrame();
    frameCallback = video.requestVideoFrameCallback(onFrame);
  };
  frameCallback = video.requestVideoFrameCallback(onFrame);
} else {
  video.addEventListener("timeupdate", markFrame);
}
 
document.addEventListener("visibilitychange", () => {
  if (!document.hidden) {
    lastFrameAt = performance.now();
  }
});
 
const watchdog = window.setInterval(() => {
  if (
    !document.hidden &&
    video.srcObject !== null &&
    !video.paused &&
    performance.now() - lastFrameAt >= freezeAfter
  ) {
    scheduleReconnect("video stopped producing frames");
  }
}, watchdogEvery);
 
window.addEventListener("beforeunload", () => {
  stopped = true;
  clearTimeout(reconnectTimer);
  clearInterval(watchdog);
  if (
    frameCallback !== null &&
    typeof video.cancelVideoFrameCallback === "function"
  ) {
    video.cancelVideoFrameCallback(frameCallback);
  }
  reader?.close();
});
 
connect();