All files / src/consumers MJPEGConsumer.js

97.35% Statements 294/302
86.76% Branches 59/68
100% Functions 7/7
97.35% Lines 294/302

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 3031x 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 14x 14x 14x 14x 14x 110x 110x 35x 35x 14x 14x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 33x 4x 4x 31x 31x 31x 31x 31x 31x 1x 1x 31x             31x 31x 31x 1x 1x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 1x 1x 32x 32x 28x 28x 28x 28x 28x 27x 27x 27x 27x 3x 3x 27x 1x 1x 1x 1x 32x 32x 32x 1x 1x 34x 32x 34x 34x 34x 34x 34x 1x 1x 1x 1x 1x 27x 27x 27x 27x 27x 27x 4x 4x 4x 4x 4x 4x 1x 1x 1x 24x 24x 24x 24x 24x 24x 1031x 1031x 1031x 1031x 1031x 914x 914x 914x 461x 461x 461x 123x 123x 123x 338x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 336x 336x 336x 336x 336x 336x 336x 336x 336x 124x 124x 124x 124x 124x 461x 461x 461x 8x 8x 8x 116x 116x 116x 116x 914x 914x 229x 116x 116x 116x 116x 116x 116x 116x 914x 340x 340x 340x 333x 333x 333x     333x 1x 1x 1x 333x 333x 7x 7x 7x 914x 914x 914x 7x 7x 914x 914x 24x 24x 27x 1x 1x 1x 1x 1x 1x  
// @ts-check
/*
** Copyright (C) 2021 Gabriele De Blasi
**
** This software is provided 'as-is', without any express or implied
** warranty.  In no event will the authors be held liable for any damages
** arising from the use of this software.
**
** Permission is granted to anyone to use this software for any purpose,
** including commercial applications, and to alter it and redistribute it
** freely, subject to the following restrictions:
**
** 1. The origin of this software must not be misrepresented; you must not
**    claim that you wrote the original software. If you use this software
**    in a product, an acknowledgment in the product documentation would be
**    appreciated but is not required.
** 2. Altered source versions must be plainly marked as such, and must not be
**    misrepresented as being the original software.
** 3. This notice may not be removed or altered from any source distribution.
**
** Created on: 2021-11-30T09:30:00+01:00
**     Author: Gabriele De Blasi <gabriele.de.blasi@cern.ch>
**
*/
 
import { EventEmitter } from "node:events";
import http from "node:http";
import { parse } from "content-type";
import VarBuffer from "./VarBuffer.js";
 
/**
 * @typedef {import('http').ClientRequest} Request
 * @typedef {import('http').IncomingMessage} Response
 *
 * @typedef {{ user: string, password: string }} Authentication
 * @typedef {{ src: string, auth?: Authentication, contentLength?: boolean, jpegMagicBytes: boolean,
 *  headerDelimiter: string, boundary?: string, throttle?: number }} MJPEGConsumerOptions
 */
 
const SearchStates = { HEADER_END: 1, CONTENT_END: 2, NEXT_BOUNDARY: 3 };
const CRLFx2 = "\r\n\r\n";
const JPEG_MAGIC_BYTES = Buffer.from("ffd8ff", "hex");
 
/**
 * @param  {function} fun
 */
function frameSkip(fun) {
  const DELTA = 10; // ms
  let deadline = 0;
 
  return function(/** @type {any[]} */ ...args) {
    const now = Date.now();
    if (now + DELTA < deadline) { return; }
    deadline = now + this.throttle;
    fun(...args);
  };
}
 
/**
 * @implements {CamExpress.Consumer}
 * @extends {EventEmitter}
 * @emits :
 *  - 'frame' when a new jpeg frame is received from source
 *  - 'ended' once the stream is stopped at the source
 *  - 'error' when an error occurs
 *  - 'close' once the connection with source is closed
 */
class MJPEGConsumer extends EventEmitter {
 
  /**
   * @param {MJPEGConsumerOptions} options
   */
  constructor(options) {
    super();
    this.src = options?.src ?? "";
    this.user = options?.auth?.user;
    this.pass = options?.auth?.password;
    this.contentLength = options?.contentLength ?? true;
    this.boundary = options?.boundary;
    this.headerDelimiter = options?.headerDelimiter;
    this.jpegMagicBytes = options?.jpegMagicBytes ?? false;
    this._connected = false;
    this._buffer = new VarBuffer();
 
    this._initialThrottle = options?.throttle;
 
    this.updateThrottle(options?.throttle);
 
    /** @type {Request|null} */
    this._req = null;
 
    this._state = SearchStates.HEADER_END;
    this._offset = 0; // search start byte in buffer
    this._contentStart = 0;
    this._frameEnd = 0;
 
    /** @type {Buffer|null} */
    this._delimiter = null;
 
    this.emitError = (err) => {
      if (this._connected) {
        this.emit("error", err);
      }
    };
 
    this.emitFrame = this.throttle ?
      frameSkip(this.emit.bind(this, "frame")) : // limit the frame rate
      this.emit.bind(this, "frame"); // no throttle => direct emit to reduce frame loss
  }
 
  updateThrottle(throttle) {
    if (throttle && throttle < MJPEGConsumer.MIN_THROTTLE_VALUE) {
      throttle = MJPEGConsumer.MIN_THROTTLE_VALUE; // Assert throttle min value
      console.warn(
        `The throttle ${throttle} is too low and` +
        ` was replaced with ${MJPEGConsumer.MIN_THROTTLE_VALUE} ms`
      );
    }
 
    this.throttle = Number(throttle);
  }
 
  connect() {
    if (this._connected) { return; }
 
    this._connected = true;
    this._buffer.reset();
 
    this._delimiter = this.jpegMagicBytes ? JPEG_MAGIC_BYTES :
      Buffer.from(this.headerDelimiter || CRLFx2);
 
    const opts = {
      auth: (this.user && this.pass) ? `${this.user}:${this.pass}` : undefined
    };
 
    const req = this._req = http.get(this.src, opts);
 
    req
    .on("error", this.emitError)
    .once("close", () => {
      req.removeAllListeners();
      // disconnect if the current connection has been terminated by the source
      if (req === this._req) {
        this.disconnect();
      }
    })
    .on("response", (res) => {
      res
      .on("error", this.emitError)
      .once("close", () => res.removeAllListeners());
 
      if ((res.headers["content-type"] ?? "").includes("multipart/x-mixed-replace")) {
        try {
          this.parse(res);
        }
        catch (err) {
          this.emitError(err);
        }
      }
      else {
        this.emitError(new Error("No MJPEG stream detected"));
        this.disconnect();
      }
    })
    .end();
  }
 
  disconnect() {
    if (!this._connected) { return; }
    this._connected = false;
    this._req?.destroy();
 
    this.emit("close");
    this._req = null;
  }
 
  /**
   * @param {Response} res
   */
  parse(res) {
    /** @type {Buffer} */ let boundary;
    try {
      boundary = Buffer.from(this.boundary ??
        parse(res.headers["content-type"] ?? "")?.parameters?.boundary);
    }
    catch (err) {
      // retrieve boundary param by regex
      // (see https://datatracker.ietf.org/doc/html/rfc2046#section-5.1.1)
      const match = (res.headers["content-type"] ?? "")
      .match(/boundary="?([\w\s'()+,\-./:=?]{1,70})"?;?/);
 
      if (!match) { throw err; } // boundary missing or invalid
 
      boundary = Buffer.from(match[1].trimEnd());
    }
 
    // minimum parsable header length
    const minHeaderLen = boundary.length + this._delimiter.length;
 
    res
    .on("data", (chunk) => { // eslint-disable-line complexity, max-statements
      this._buffer.add(chunk);
 
      let index = 0;
 
      while (this._buffer.length > minHeaderLen) {
 
        switch (this._state) {
        case SearchStates.HEADER_END:
          index = this._buffer.buffer().indexOf(this._delimiter, this._offset);
 
          if (index >= 0) {
            this._contentStart = this._offset =
              index + (this.jpegMagicBytes ? 0 : this._delimiter.length);
          }
          else if (this._buffer.length > MJPEGConsumer.MAX_HEADER_LENGTH) {
 
            if (!this.jpegMagicBytes) {
              // fallback solution: search for JPEG magic numbers
              index = this._buffer.buffer().indexOf(JPEG_MAGIC_BYTES);
            }
 
            if (index >= 0) {
              this._contentStart = this._offset = index;
            }
            else { // drop data
              this._buffer.shift(MJPEGConsumer.MAX_HEADER_LENGTH);
              this._offset = 0;
              console.warn(
                `Discarded the first ${MJPEGConsumer.MAX_HEADER_LENGTH} ` +
                "bytes as the maximum header length has been reached.");
              return;
            }
          }
          else {
            // set starting byte for next search considering the worst case:
            // e.g. last 3 bytes equal to '\r\n\r' (with CRLFx2 as delimiter)
            this._offset =
              this._buffer.length - Math.abs(this._delimiter.length - 1);
 
            if (this._offset < 0) { this._offset = 0; }
            return;
          }
 
          // choice between content-Length and boundary
          {
            const match = this.contentLength ?
              this._buffer.slice(0, index).toString("ascii")
              .match(/Content-Length:\s*(\d+)/i) : null;
 
            if (!match) {
              this._state = SearchStates.NEXT_BOUNDARY;
              break;
            }
 
            this._frameEnd = this._contentStart + Number(match[1]);
            this._state = SearchStates.CONTENT_END;
          }
          /* falls through */
        case SearchStates.CONTENT_END:
          if (this._buffer.length < this._frameEnd) { return; }
          this.emitFrame(
            this._buffer.slice(this._contentStart, this._frameEnd));
 
          this._buffer.shift(this._frameEnd);
          this._offset = 0;
          this._state = SearchStates.HEADER_END;
          break;
        case SearchStates.NEXT_BOUNDARY:
          index = this._buffer.buffer().indexOf(boundary, this._offset);
 
          if (index === -1) {
            // same as above
            this._offset = this._buffer.length - (boundary.length - 1);
            if (this._offset < 0) {
              this._offset = 0;
            }
            else if (this._buffer.length > MJPEGConsumer.MAX_CONTENT_LENGTH) {
              this._buffer.shift(this._offset);
              this._offset = 0;
            }
            return;
          }
          this.emitFrame(this._buffer.slice(this._contentStart, index));
 
          this._buffer.shift(index);
          this._offset = boundary.length; // re-start from after the boundary
          /* falls through */
        default:
          this._state = SearchStates.HEADER_END;
          break;
        }
      }
    })
    .on("end", this.emit.bind(this, "ended"));
  }
}
MJPEGConsumer.MAX_HEADER_LENGTH = 2048; // bytes
MJPEGConsumer.MAX_CONTENT_LENGTH = 20971520; // bytes (= 20 MiB)
MJPEGConsumer.MIN_THROTTLE_VALUE = 17; // ms  (~ 60 fps)
 
export default MJPEGConsumer;