All files / src CamService.js

96.42% Statements 620/643
85.34% Branches 99/116
100% Functions 15/15
96.42% Lines 620/643

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 6441x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 9x 9x 9x 9x 1x 1x 1x 1x 1x 1x 1x 1x 1x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 1x 1x 1x 1x 1x 1x 1x 32x 90x 151x 151x 136x 136x 136x 151x 151x 90x 90x 90x 90x 32x 32x 32x 1x 1x 1x 1x 1x 1x 30x 30x 30x 30x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 6x 6x 6x 6x 2x 2x 2x 2x 4x 4x 4x 4x 4x 4x 1x 1x 1x 1x 1x 1x 92x 92x 92x 1x 1x 1x 1x 1x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 3x 2x 2x 1x 1x 1x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 10x       10x 10x 10x 10x 10x 10x 10x 10x 10x 5x 5x 5x 5x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 2x       2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 32x 32x 32x 5x 5x 5x 32x 5x 5x 5x 32x 32x 27x 20x       20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 5x 5x 5x 15x 15x 27x 27x 27x 2x       2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 27x 27x 32x 32x 32x 32x 32x 32x 32x 1x 1x 1x 1x 1x 1x 32x 90x 90x 90x 151x 151x 151x 151x 151x 151x 151x 90x 90x 90x 32x 32x 1x 1x 1x 1x 1x 1x 1x 1x 6x 6x 17x 17x 5x 5x 5x 12x 12x 17x 9x 9x 9x 9x 9x 9x 3x 3x 2x 2x 2x 2x 2x 2x 2x 17x 17x 1x 1x 1x 1x 1x 1x 6x 6x 6x 6x           6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 1x 1x 1x 1x 1x 1x 1x 1x 16x 16x 60x 60x 60x 14x 14x 14x 46x 46x 46x 60x 40x 40x 6x 6x 4x 4x 60x 60x 2x 2x 16x 16x 16x   16x 16x 16x 16x 16x 16x 1x 1x 1x 1x 1x 1x 1x 1x 34x 34x 34x 34x 34x 33x 33x 33x 33x       33x 33x 33x 33x 33x 1x     34x 34x 34x 34x 34x 34x 34x 34x 1x 1x 1x 1x 1x 33x 33x 33x 33x 33x 33x 33x 75x 75x 75x 33x 33x 17x 17x 33x 33x 18x 18x 18x 9x 9x 6x 5x 5x 5x 1x 1x 1x 9x 9x 9x 9x 9x 33x 33x 33x 33x 33x 33x 33x 33x 33x 1x 1x 1x 1x 1x 43x 43x 43x 30x 30x 30x 30x 30x 30x 30x 30x 43x 1x 1x 1x 1x 1x 1x 34x 34x 15x 15x 15x 15x 15x 14x 14x 14x 14x 14x 15x 15x 15x 34x 1x 1x 64x 29x 29x 29x 29x 29x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 1x 1x 1x 1x 1x  
/* eslint-disable max-lines */
// @ts-check
// SPDX-License-Identifier: Zlib
// SPDX-FileCopyrightText: 2024 CERN (home.cern)
 
import { isEmpty, isNil, set } from "@cern/nodash";
import d from "debug";
import cors from "cors";
import ConsumerFactory from "./consumers/ConsumerFactory.js";
import StreamClient from "./StreamClient.js";
import CamSwagger from "./CamSwagger.js";
import PTZService from "./ptz/PTZService.js";
import SShotService from "./screenshots/SShotService.js";
 
const debug = d("cam:service");
 
/**
 * @typedef {import('express').Request} Request
 * @typedef {import('http').OutgoingMessage} HttpResponse
 * @typedef {{ [id: number]: StreamClient }} StreamClients
 *
 * @typedef {import('express').IRouter} expressIRouter
 * @typedef {import('express-ws').WithWebsocketMethod & expressIRouter} IRouter
 * @typedef {import('ws').default} WebSocket
 */
 
/**
 * @swagger
 * definitions:
 *   Config:
 *     description: 'List of cameras divided by group'
 *     type: object
 *     additionalProperties:
 *       type: object
 *       properties:
 *         description:
 *           type: string
 *         cameras:
 *           type: array
 *           items:
 *             type: object
 *             properties:
 *               name: { type: string}
 *               description: { type: string }
 *               ptz: { type: boolean }
 *             required: [ name ]
 *     example:
 *       default:
 *         cameras:
 *           - name: "cam1"
 *             description: "camera 1"
 *           - name: "cam2"
 *             description: "camera 2"
 *         description: "default group"
 */
 
const WS_GOING_AWAY = 1001;
const WS_INTERNAL_ERROR = 1011;
 
function exponentialTimeout(i) {
  const max = 10; // -> max timeout ~1h
  return CamService.CONN_RETRY << ((i < max) ? i : max);
}
 
class CamService {
 
  /**
   * @param {CamExpress.Config} config groups and cameras configuration
   * @param {CamExpress.CamSwagger.Options} [options] filling swagger base config
   * @param {CamExpress.CamSwagger.Info} [extraDoc] merged with dynamic swagger doc
   */
  constructor(config, options, extraDoc) {
    /** @type {number} */
    this._id = 0; // subscription id
    this._camId = 0; // CameraConfig id
    this.hasPTZ = false;
    this.hasSShot = false;
 
    /** @type {PTZService|null} */
    this.ptz = null;
 
    /** @type {CamExpress.InternalGroupConfig} */
    this.groups = this._prepareGroups(config?.groups);
 
    /** @type {CamExpress.Credentials} */
    this.creds = config?.credentials ?? {};
 
    /** @type {CamExpress.CameraList} */
    this.camConfig = {};
 
    /** @type {number} */
    this.unsubscribeTimeout = (config?.unsubscribeTimeout ?? 0) * 1000; // ms
 
    /** @type {CamExpress.CameraMap} */
    this._camMap = {};
 
    /** @type {CamExpress.CamSwagger.Options|undefined} */
    this._swaggerOptions = options;
 
    /** @type {CamExpress.CamSwagger.Info|undefined} */
    this._swaggerExtraDoc = extraDoc;
  }
 
  /**
   *
   * @param {{ [group: string]: CamExpress.GroupConfig }} groups
   * @return {CamExpress.InternalGroupConfig}
   */
  _prepareGroups(groups) {
    Object.values(groups ?? {}).forEach((g) => {
      Object.values(g?.cameras ?? []).forEach((c) => {
        // @ts-ignore
        if (isNil(c.id)) {
          // @ts-ignore
          c.id = this._camId++;
        }
        this.hasPTZ = this.hasPTZ || !!c.ptz;
        this.hasSShot = this.hasSShot || !!c.screenshot;
      });
      // @ts-ignore
      g.cameras = Object.values(g?.cameras ?? []).reduce(
        (r, x) => { r[x["name"]] = x; return r; }, {});
    });
    return /** @type {CamExpress.InternalGroupConfig} */ (/** @type {unknown}*/ (groups));
  }
 
  /**
   * @param {Request} req
   * @return {CamExpress.Camera|undefined}
   */
  getCamera(req) {
    const group = req?.params?.group;
    const camera = req?.params?.camera;
    return this.groups?.[group]?.cameras?.[camera];
  }
 
  /**
   * @param {Request} req
   * @return {CamExpress.CameraConfig}
   */
  getMultiplexedCamera(req) {
    // cameras as array of string => "group/camera"
    /** @type {string[]} */
    const paths = req.query.cameras?.toString().split(",") ?? [];
    const durations = req.query.durations?.toString().split(",") ?? [];
    const cameras = paths?.map((path, index) => {
      const [ group, camera ] = path.split("/");
      const duration = Number(durations?.[index]);
 
      if (isNil(group) || isNil(camera)) {
        throw new Error(
          'Bad query (cameras path should be as "group/camera")'
        );
      }
 
      return { group, camera, duration };
    }) ?? [];
 
    return { name: JSON.stringify(cameras), multiplex: cameras };
  }
 
  /**
   * @param {string|number} camId
   * @param {Buffer|Error} data
   */
  _broadcast(camId, data) {
    Object.values(this._camMap[camId]?.clients ?? {})
    .forEach((c) => c.throttledCB(data));
  }
 
  /**
   * @param {IRouter} router
   */
  register(router) {
    this.release();
 
    this.camConfig = this.getConfig();
 
    /**
     * @swagger
     * /config:
     *   get:
     *     tags: ['config']
     *     summary: list current cameras config
     *     description: list current cameras config
     *     produces:
     *       - application/json
     *     responses:
     *       200:
     *         description: list current cameras config
     *         schema:
     *           $ref: '#/definitions/Config'
     *       500:
     *         description: camera configuration is missing
     */
    router.get("/config", cors(), (req, res) => {
      if (!isEmpty(this.camConfig)) {
        res.status(200).json(this.camConfig);
      }
      else {
        res.status(500).send("Camera configuration missing");
      }
    });
 
    /**
     * @swagger
     * /cameras/{group}/{camera}:
     *   get:
     *     tags: ['cameras']
     *     summary: access the camera frames
     *     description: |
     *       Exposes to clients two routes (streaming via HTTP and WebSocket) and sends the JPEG images
     *       extracted from the MJPEG fragments or fetched through http polling.
     *     parameters:
     *      - in: path
     *        name: group
     *        schema:
     *           type: string
     *        description: name of the group defined in the config
     *        required: true
     *      - in: path
     *        name: camera
     *        schema:
     *           type: string
     *        description: name of the camera defined in the config
     *        required: true
     *      - in: query
     *        name: throttle
     *        schema:
     *           type: int
     *        description: asked throttle for framerate regulation from client
     *        required: false
     *     produces:
     *       - application/json
     *     responses:
     *       200:
     *         description: (GET) open a frame stream via http
     *       101:
     *         description: (WS) open a frame stream via websockets
     *       500:
     *         description: error message
     */
    router.get("/cameras/:group/:camera", (req, res) => {
      if (isEmpty(this.camConfig)) {
        res.status(500).send("No cameras in configuration");
        return;
      }
      const throttle = req.query.throttle; // Throttle from client
      const closeOnErrorArg = (req.query.closeOnError ?? "")
      .toString().toLowerCase();
      const closeOnError =
        !([ "false", "0" ].some((v) => (closeOnErrorArg === v)));
 
      const cam = this.getCamera(req);
 
      if (isNil(cam)) {
        res.status(500).send("Camera not found");
        return;
      }
      this.subscribeHTTP(cam, throttle, res, closeOnError);
    });
 
    /**
     * @swagger
     * /multiplex:
     *   get:
     *     tags: ['config']
     *     summary: rotate between the client query specified cameras stream
     *     description: |
     *       Exposes to clients two routes (streaming via HTTP and WebSocket) and
     *       rotates between the client query specified cameras stream
     *     parameters:
     *      - in: query
     *        name: cameras
     *        schema:
     *          type: array
     *          items: string
     *          example: 'default/cam1, default/cam2'
     *      - in: query
     *        name: durations
     *        schema:
     *          type: array
     *          items: string
     *          example: '2000,4000'
     *     produces:
     *       - application/json
     *     responses:
     *       200:
     *         description: (GET) open a frame stream via http
     *       101:
     *         description: (WS) open a frame stream via websockets
     *       500:
     *         description: error message
     */
    router.get("/multiplex", (req, res) => {
      if (isEmpty(this.camConfig)) {
        res.status(500).send("No cameras in configuration");
        return;
      }
      const closeOnErrorArg = (req.query.closeOnError ?? "")
      .toString().toLowerCase();
      const closeOnError =
        !([ "false", "0" ].some((v) => (closeOnErrorArg === v)));
 
      try {
        // virtual camera config for referencing a temporary consumer
        const virtual = this.getMultiplexedCamera(req);
 
        this.subscribeHTTP(virtual, undefined, res, closeOnError);
      }
      catch (err) {
        res.status(500).send(err.message);
      }
    });
 
    if (this.hasPTZ) {
      this.ptzService = new PTZService(this.groups, this.creds);
      this.ptzService.register(router);
    }
    if (this.hasSShot) {
      this.sshotService = new SShotService(this.groups, this.creds);
      this.sshotService.register(router);
    }
 
    if (router.ws) {
      router.ws("/cameras/:group/:camera", (ws, req) => {
        if (isEmpty(this.camConfig)) {
          ws.close(WS_INTERNAL_ERROR, "No cameras in configuration");
          return;
        }
 
        const throttle = req.query.throttle; // Throttle from client
        const closeOnErrorArg = (req.query.closeOnError ?? "")
        .toString().toLowerCase();
        const closeOnError =
          !([ "false", "0" ].some((v) => (closeOnErrorArg === v)));
 
        const cam = this.getCamera(req);
 
        if (isNil(cam)) {
          ws.close(WS_INTERNAL_ERROR, "Camera not found");
          return;
        }
 
        this.subscribeWS(cam, throttle, ws, closeOnError);
      });
 
      router.ws("/multiplex", (ws, req) => {
        if (isEmpty(this.camConfig)) {
          ws.close(WS_INTERNAL_ERROR, "No cameras in configuration");
          return;
        }
        const closeOnErrorArg = (req.query.closeOnError ?? "")
        .toString().toLowerCase();
        const closeOnError =
          !([ "false", "0" ].some((v) => (closeOnErrorArg === v)));
 
        try {
          // virtual camera config for referencing a temporary consumer
          const virtual = this.getMultiplexedCamera(req);
 
          this.subscribeWS(virtual, undefined, ws, closeOnError);
        }
        catch (err) {
          ws.close(WS_INTERNAL_ERROR, err.message);
        }
      });
    }
 
    const swagger = new CamSwagger(this._swaggerOptions, this._swaggerExtraDoc);
 
    swagger.swag(this);
 
    swagger.register(router);
  }
 
  /**
   * @brief provides configuration to retrieve video streams from cameras
   * @return {CamExpress.ExposedConfig}
   */
  getConfig() {
    return Object.entries(this.groups ?? {}).reduce((ret, [ key, group ]) => {
      ret[key] = {
        description: group?.description ?? "",
        cameras: Object.values(group?.cameras ?? {}).map((camera) => {
          const ret = {
            name: camera.name, description: camera?.description ?? ""
          };
          if (camera.ptz) { ret.ptz = true; }
          if (camera.screenshot) { ret.screenshot = true; }
          if (camera.extra) { Object.assign(ret, camera.extra); }
          return ret;
        })
      };
      return ret;
    }, {});
  }
 
  /**
   * @param {CamExpress.Camera} cam
   * @param {number|undefined} throttle
   * @param {HttpResponse} res
   * @param {boolean} [closeOnError=true]
   */
  subscribeHTTP(cam, throttle, res, closeOnError = true) {
 
    const id = this.subscribe(cam, throttle, (data) => {
 
      if (!data) {
        res.end();
        return;
      }
 
      try {
        if (Buffer.isBuffer(data)) {
          res.write("--frame\r\n");
          res.write("Content-Type: image/jpeg\r\n");
          res.write(`Content-Length: ${data.length}\r\n\r\n`);
          res.write(data);
          res.write("\r\n");
        }
        else if (data instanceof Error) {
          if (closeOnError) { throw data; }
          res.write("--frame\r\n");
          const payload = JSON.stringify({ type: "error", data: data.message });
          res.write("Content-Type: application/json\r\n");
          res.write(`Content-Length: ${payload.length}\r\n\r\n`);
          res.write(payload);
          res.write("\r\n");
        }
      }
      catch (err) {
        res.write("--frame\r\n");
        const payload = JSON.stringify({ type: "error", data: data.message });
        res.write("Content-Type: application/json\r\n");
        res.write(`Content-Length: ${payload.length}\r\n\r\n`);
        res.end(payload);
      }
    });
 
    res
    .on("error", (err) => {
      if (!res.writableEnded) {
        res.write("--frame\r\n");
        res.write("Content-Type: application/json\r\n");
        res.end(JSON.stringify({ type: "error", data: err.message }));
      }
    })
    .once("close", () => {
      res.removeAllListeners();
      this.unsubscribe(cam, id);
    })
    .status(200)
    .set("Cache-Control", "no-store")
    .set("Content-Type", "multipart/x-mixed-replace; boundary=frame")
    .set("Pragma", "no-cache")
    .flushHeaders();
  }
 
  /**
   * @param {CamExpress.Camera} cam
   * @param {number|undefined} throttle
   * @param {WebSocket} ws
   * @param {boolean} [closeOnError=true]
   */
  subscribeWS(cam, throttle, ws, closeOnError = true) {
 
    const id = this.subscribe(cam, throttle, (data) => {
 
      // Check if we want to close the socket
      if (!data) {
        ws.close(WS_GOING_AWAY);
        return;
      }
 
      // Otherwise, we send the datas
      try {
        if (Buffer.isBuffer(data)) {
          ws.send(data);
        }
        else if (data instanceof Error) {
          if (closeOnError) { throw data; }
          ws.send(JSON.stringify({ type: "error", data: data.message }));
        }
      }
      catch (err) {
        ws.close(WS_INTERNAL_ERROR, err.message);
      }
    });
 
    ws.on("error", (err) => {
      ws.close(WS_INTERNAL_ERROR, err.message);
    })
    .once("close", () => {
      ws.removeAllListeners();
      this.unsubscribe(cam, id);
    });
  }
 
  /**
   * @param {CamExpress.Camera} cam
   * @param {number|undefined} throttle
   * @param {(data?: Buffer|Error) => void} cb
   * @return {number}
   */
  subscribe(cam, throttle, cb) {
 
    const clients = this._camMap[cam.id]?.clients || {};
 
    // If first client, init the fetching of camera frames
    if (isEmpty(clients)) {
      set(this._camMap, [ cam.id, "clients" ], clients);
      // try to resume camera stream
      const timeout = this._camMap[cam.id]?.unSubTimeout;
      if (timeout) {
        clearTimeout(timeout);
        this._camMap[cam.id].unSubTimeout = null;
      }
      else {
        // Create, store and add event handling for the camera's consumer
        this.startStream(cam);
      }
    }
    else if (!isNil(this._camMap[cam.id]?.error)) {
      cb(/** @type {Error} */ (this._camMap[cam.id].error)); // eslint-disable-line callback-return
    }
 
    const id = this._id++;
 
    // Instanciate a new client
    clients[id] = new StreamClient({ throttle, cb });
 
    return id;
  }
 
  /**
   * @param {CamExpress.Camera} cam
   */
  startStream(cam) {
 
    // Determine type of stream
    const consumer = ConsumerFactory.createConsumer(cam, this);
 
    // Add events handling
    consumer
    .on("frame", (frame) => {
      set(this._camMap, [ cam.id, "retryAttempt" ], 0);
      set(this._camMap, [ cam.id, "error" ], null);
      this._broadcast(cam.id, frame);
    })
    .on("error", (err) => {
      set(this._camMap, [ cam.id, "error" ], err);
      this._broadcast(cam.id, err);
    })
    .on("close", () => {
      const camera = this._camMap[cam.id];
 
      if (!isEmpty(camera?.clients) && isNil(camera.retryTimer)) {
        // retry connection
        camera.retryTimer = setTimeout(() => {
          if (this._camMap[cam.id]?.consumer === consumer) {
            this._camMap[cam.id].retryTimer = null;
            consumer.connect();
          }
          else {
            consumer.removeAllListeners();
          }
        }, exponentialTimeout(camera.retryAttempt++));
      }
      else {
        consumer.removeAllListeners();
      }
    })
    .connect();
 
    // Store the camera context
    set(this._camMap, [ cam.id, "consumer" ], consumer);
    set(this._camMap, [ cam.id, "retryTimer" ], null);
    set(this._camMap, [ cam.id, "retryAttempt" ], 0);
    set(this._camMap, [ cam.id, "error" ], null);
  }
 
  /**
   * @param {string|number} camId
   */
  stopStream(camId) {
    const camera = this._camMap[camId];
 
    if (camera) {
      camera.consumer?.removeAllListeners();
      camera.consumer?.disconnect();
      camera.consumer = null;
      clearTimeout(camera.retryTimer);
      camera.retryTimer = null;
      camera.retryAttempt = 0;
      camera.error = null;
    }
  }
 
  /**
   * @param {CamExpress.Camera} cam
   * @param {number} id
   */
  unsubscribe(cam, id) {
    const clients = this._camMap[cam.id]?.clients;
    if (isNil(clients)) { return; }
 
    delete clients[id];
 
    if (isEmpty(clients)) {
      this._camMap[cam.id].unSubTimeout = setTimeout(() => {
 
        this.stopStream(cam.id);
 
        set(this._camMap, [ cam.id, "clients" ], {});
        set(this._camMap, [ cam.id, "unSubTimeout" ], null);
      },
      this.unsubscribeTimeout);
    }
  }
 
  release() {
    Object.values(this._camMap ?? {}).forEach((cam, camId) => {
      clearTimeout(cam.unSubTimeout ?? undefined);
      cam.unSubTimeout = null;
      Object.values(cam.clients ?? {}).forEach((c) => c.cb()); // close WS
 
      this.stopStream(camId);
    });
 
    this._camMap = {};
    this.camConfig = {};
    this._id = 0;
    this.ptzService?.release();
    this.sshotService?.release();
 
    debug("CamService released");
  }
 
}
CamService.CONN_RETRY = 3500; // ms
 
export default CamService;