2

The reason I'm using an <img> tag for the mjpg stream is that I'm able to size the image with css. However, after letting it run for a while, the browser crashes becuase it's getting out of memory.

I'm currently using URL.revokeObjectURL(mjpgURLwithOutdatedRandomParam) and add a new random param to the URL every few seconds. But unfortunately, the current Chrome still crashes with Out of Memory.

I also tried loading the stream into a canvas, but after a while the browser still gets out of memory:

const canvas = document.getElementById('canvas');
const image = new Image();

image.src = 'http://example.com';

const FRAME_RATE = 30;

image.onload = function() {
  canvas.width = image.width;
  canvas.height = image.height;

  setInterval(function() {
    const context = canvas.getContext('2d');
    context.drawImage(image, 0, 0, canvas.width, canvas.height);
  }, 1000 / FRAME_RATE);
};
<canvas id="canvas"></canvas>

What simple/optimal solution is there?

PS: I don't understand how a browser can support mjpg (within an <img> tag) but not be prepared to handle the memory...

Simon Ferndriger
  • 4,455
  • 6
  • 28
  • 53
  • 1
    Why are you not displaying the mjpeg stream directly using the `` tag? I do that and never noticed out of memory error. – Salman A May 17 '23 at 13:30
  • I tried it, but after 20-30 minutes I got the mentioned error. How long do you run the stream and in which browser? – Simon Ferndriger May 18 '23 at 19:04
  • In Chrome, usually latest version. Never tried keeping the tab in the background, not for that long at least. MJPEG is from an IP cam, running ZoneMinder software. – Salman A May 18 '23 at 19:11

1 Answers1

2

This is because you are continuously drawing on the canvas. You need to clear the resources properly. See Example Below:

const canvas = document.getElementById('canvas');
const image = new Image();

image.src = 'http://example.com';

const FRAME_RATE = 30;

image.onload = function() {
  canvas.width = image.width;
  canvas.height = image.height;

  setInterval(function() {
    const context = canvas.getContext('2d');
    
    // Clear the canvas before drawing each frame
    context.clearRect(0, 0, canvas.width, canvas.height);
    
    // Draw the image onto the canvas
    context.drawImage(image, 0, 0, canvas.width, canvas.height);
  }, 1000 / FRAME_RATE);
};

Hazik Arshad
  • 456
  • 2
  • 8