Performance of video stream processing in Google Chrome - javascript

I develop web application for mobile browsers which processes video stream from back camera in real time. Based on some calculated feature we may store current frame for followed operations.
The detailed workflow is next:
Input video stream in browser has 4K resolution. We use 3 canvases: two canvases have 4K resolution and the last one has significant lower resolution ( approximately 400x600 ). We get frame from video stream and draw it on 4K canvas. Next we draw this 4K canvas onto smallest one. Then we get array representation of image from this small canvas and perform some calculation with it. Based on that calculation we decide if this frame should be stored or not ( we say that we found "Best frame" ). This best frame we store in original resolution 4K in the second 4K canvas for final processing and continue to process next frames in hope to fine little bit better.
In my work I faced with problem that Google Chrome shows less performance than FireFox on the same device and dramatically worse performance than Safari on the devices with same class.
In order to demonstrate the problem I created test html example. In it I use all of the operations which I consider as critical. There are: drawing frame from video stream onto first 4K canvas, scale this canvas and draw it onto smallest canvas, obtaining of array buffer from smallest canvas for calculation. These three operations are called for each frame therefore their performance is most critical for me.
Repository with example
Deployed example
Measured timers:
Execution time originalCanvas.drawFrame, ms - drawing of videoframe onto 4K canvas
Execution time scaledCanvas.drawFrame, ms - drawing 4K canvas onto small canvas
Execution time scaledCanvas.getBmpData, ms - obtaining byte array from small canvas
All big canvases in testing have resolution 3840x2160, all small ones have resolution 711x400.
Now let's move on to the most important thing... Why we have such big inequality in performance in different browsers and on different devices which have the same class? Unfortunately I can't test example in Chrome and FireFox on iPhones because of prohibition of access to camera there. I consider that manipulation with canvases is a simple operation which shouldn't be so long. And why Safari has extremely amazing performance compare with Chrome or even FireFox?
I hope my topic wasn't very boring. I would be glad to hear everything about my workflow in application or about my conclusions. Thanks a lot!

Related

Canvas performance - long time of clearRect execution

I have problem with canvas performance. At simplest operations I have 3-5 FPS and application is useless. It happens in every browser even when I have one object in canvas. Before last Chrome update application worked better but only on this browser.
On image you can see performance log from Google Chrome which is recorded when I move object by mouse and canvas has 4 objects but it happens with single object too. In step_2.onMouseMove is method which set object position based on pointer coords (very simple calculations)
I use fabric.js library in this project. What could be the reason? How to boost performance of this?­­­­­­­­­­­­­­­­­­­­

WebGL VS Canvas 2D hardware acceleration

These days, I need to draw many images on a canvas. The canvas size is 800x600px, and I have many images of 256x256px(some is smaller) to draw on it, these small images will compose a complete image on the canvas. I have two ways to implement this.
First, if I use canvas 2D context, that is context = canvas.getContext('2d'), then I can just use context.drawimage() method to put every image on the proper location of the canvas.
Another way, I use WebGL to draw these images on the canvas. On this way, for every small image, I need to draw a rectangle. The size of the rectangle is the same as this small image. Besides, the rectangle is on the proper location of the canvas. Then I use the image as texture to fill it.
Then, I compare the performance of these two methods. Both of their fps will reach 60, and the animation(When I click or move by the mouse, canvas will redraw many times) looks very smooth. So I compare their CPU usage. I expect that when I use WebGL, the CPU will use less because GPU will assure many work of drawing. But the result is, the CPU usage looks almost the same. I try to optimize my WebGL code, and I think it's good enough. By google, I found that browser such as Chrome, Firefox will enable Hardware acceleration by default. So I try to close the hardware acceleration. Then the CPU usage of the first method becomes much higher. So, my question is, since canvas 2D use GPU to accelerate, is it necessary for me to use WebGL just for 2D rendering? What is different between canvas 2D GPU acceleration and WebGL? They both use GPU. Maybe there is any other method to lower the CPU usage of the second method? Any answer will be appreciate!
Canvas 2D is still supported more places than WebGL so if you don't need any other functionality then going with Canvas 2D would mean your page will work on those browsers that have canvas but not WebGL (like old android devices). Of course it will be slow on those devices and might fail for other reasons like running out of memory if you have a lot of images.
Theoretically WebGL can be faster because the default for canvas 2d is that the drawingbuffer is preserved whereas for WebGL it's not. That means if you turn anti-aliasing off on WebGL the browser has the option to double buffer. Something it can't do with canvas2d. Another optimization is in WebGL you can turn off alpha which means the browser has the option to turn off blending when compositing your WebGL with the page, again something it doesn't have the option to do with canvas 2d. (there are plans to be able to turn off alpha for canvas 2d but as of 2017/6 it's not widely supported)
But, by option I mean just that. It's up to the browser to decide whether or not to make those optimizations.
Otherwise if you don't pick those optimizations it's possible the 2 will be the same speed. I haven't personally found that to be the case. I've tried to do some drawImage only things with canvas 2d and didn't get a smooth framerate were as I did with WebGL. It made no sense to be but I assumed there was something going on inside the browser I was un-aware off.
I guess that brings up the final difference. WebGL is low-level and well known. There's not much the browser can do to mess it up. Or to put it another way you're 100% in control.
With Canvas2D on the other hand it's up to the browser what to do and which optimizations to make. They might changes on each release. I know for Chrome at one point any canvas under 256x256 was NOT hardware accelerated. Another example would be what the canvas does when drawing an image. In WebGL you make the texture. You decide how complicated your shader is. In Canvas you have no idea what it's doing. Maybe it's using a complicated shader that supports all the various canvas globalCompositeOperation, masking, and other features. Maybe for memory management it splits images into chucks and renders them in pieces. For each browser as well as each version of the same browser what it decides to do is up to that team, where as with WebGL it's pretty much 100% up to you. There's not much they can do in the middle to mess up WebGL.
FYI: Here's an article detailing how to write a WebGL version of the canvas2d drawImage function and it's followed by an article on how to implement the canvas2d matrix stack.

JavaScript canvas game development

Ive been having a really baffling slow down issue with the game I am working on probably because I am unsure how to handle graphics (most likely responsible for the slow down) in javascript without using a third party framework like Phaser/ImapactJS/EaselJS etc)*. The following is the low down on how I am approaching my graphics. I would be very thankful for some tips or methods on how to do this right.
My game is tile based - using tiles designed at 500x500 px because I want them to display decently on high definition devices.
I am using a spritesheet to load all (most of) my tiles before the main loop is run. This image is roughly 4000 x 4000 (keeping it below 4096 because the GPU cant handle texture sizes larger than that).
I then use the drawImage function to cycle through and draw each tile on a part of the canvas using information (w, h, x, y) stored in the tile array. I do this on every cycle of the main loop using my drawMap function.
The map is currently 6x6 tiles in size
A character spritesheet is also loaded and drawn on to the canvas after the map has been drawn. The character displays a different frame of the animation on every cycle of the main loop. There are sets of animations for the character each contained in the same spritesheet.
The character sprite sheet is roughly 4000x3500
The character is roughly 350x250 px
Other objects also use the same sprite sheet. Currently there is only one object.
Possibly helpful questions:
Am I using too many spritesheets or too few?
Should I only draw something if it's coordinates are in bounds of the screen?
How should I go about garbage collection? Do I need to set image objects to null when no longer in use?
Thanks in advance for input. I would just like to know if I am going about it the right way and pick your brains as how to speed it up enough.
*Note that I plan to port the JS game to cocoonJS which provides graphics acceleration for the canvas element on mobile.
** If interested please visit my Patreon page for fun!
You have asked lots of questions here, I'll address the ones I've run into.
I would like to start out by saying very clearly,
Use a profiler
Find out whether each thing you are advised to do, by anybody, is making an improvement. Unless we work on your code, we can only give you theories on how to optimise it.
How should I go about garbage collection? Do I need to set image objects to null when no longer in use?
If you are no longer using an object, setting its reference to null will probably mean it gets garbage collected. Having nulls around is not necessarily good but this is not within the scope of this question.
For high performance applications, you want to avoid too much allocation and therefore too much garbage collection activity. See what your profiler says - the chrome profiler can tell you how much CPU time the garbage collector is taking up. You might be OK at the moment.
I then use the drawImage function to cycle through and draw each tile on a part of the canvas using information (w, h, x, y) stored in the tile array. I do this on every cycle of the main loop using my drawMap function.
This is quite slow - instead consider drawing the current on screen tiles to a background canvas, and then only drawing areas which were previously obscured.
For example, if your player walks to the left, there is going to be a lot of tiles on the left hand side of the screen which have come into view; you will need to draw the background buffer onto the screen, offset to account for the movement, and then draw the missing tiles.
My game is tile based - using tiles designed at 500x500 px because I want them to display decently on high definition devices
If I interpret this right, your tiles are 500x500px in diameter, and you are drawing a small number of these on screen. and then for devices without such a high resolution, the canvas renderer is going to be scaling these down. You really want to be drawing pixels 1:1 on each device.
Would you be able, instead, to have a larger number of smaller tiles on screen - thereby avoiding the extra drawing at the edges? Its likely that the tiles around the edges will sometimes draw only a few pixels of one edge, and the rest of the image will be cropped anyway, so why not break them up further?
Should I only draw something if it's coordinates are in bounds of the screen?
Yes, this is a very common and good optimisation to take. You'll find it makes a big difference.
Am I using too many spritesheets or too few?
I have found that when I have a small number of sprite sheets, the big performance hit is when I frequently switch between them. If during one draw phase, you draw all your characters from character_sheet.png and then draw all the plants from plant_sheet.png you'll be ok. Switching between them can cause lots of trouble and you'll see a slow down. You will know this is happening if your profiler tells you that drawImage is taking a big proportion of your frame.

Paper.js/Canvas performance and simple Raster animations

I am trying to create a tiny Guitar Hero game using Paper.js as an experiment.
Here is a live and testable version of my code (wait for 1 second) -
http://codepen.io/anon/pen/GgggwK
I have an array with delays, e.g intervalArray =[200,300,500,100,200], and I use that array to fire up a function
that pushes a Raster Image into a group.
There are a total of 5 Groups(for 5 guitar chords) which are animated
with view.onFrame so their position.y changes at a specified
dropSpeed.
Hence whatever I push into those Groups is animated(flowing) down the
canvas.
There are also 5 Circles and the images/notes that are flowing down
overlap the circles at some point.
If the user clicks that circle at the right time(when note
overlaps), he gets some points.
I am recycling the images when they reach the end of the canvas, so I will not have too many objects to eat up memory.
The thing is, I was expecting to see a very, very fast performance with this.
I am using Raster Images which are supposed to be very fast to render
in comparison to vectors, I am recycling the images and using few
extra items on the Canvas but still on mobile browsers I am having
some serious performance issues.
Even on my iMac I was expecting to see this run at the full frame rate - 60fps that requestAnimationFrame(this is what view.onFrame uses internally) allows, but sometimes the frame rate variates there as well.
I have tested this on:
Galaxy S3, Stock and Chrome browsers (laggy at some points when animating, the framerate freezes for 5,6 frames every 35 frames).
Google Nexus 5, Stock and Chrome browsers (works somehow better, freezes for 5,7 frames and continues)
iPhone 4 Safari browser (very sluggish)
iMac 2011, 8GB ram, Core2 Duo processor (fairly good framerate, sometimes variates)

Google Chrome hardware acceleration making game run slow

So I have been working on a game in HTML5 canvas and noticed that the games lags and performs much slower when hardware acceleration is turned on in Google Chrome then when it is turned off. You can try for yourself here
From doing some profiling I see that the problem lies in drawImage.
More specifically drawing one canvas onto another. I do a lot of this.
Hardware Acceleration on.
Hardware Acceleration off.
Is there something fundamental I am missing with one canvas to another? Why would the difference be that profound?
If I remember correctly, in-DOM canvases are loaded into GPU memory in Chrome, and off-DOM canvases may not be. So each drawImage from an off-screen canvas to an on-screen canvas results in loading the content of the canvas onto the GPU as a texture, followed by a copy of that memory on-GPU onto the on-screen canvas. The cost of sending a new texture through to the GPU can be quite high. Loading textures is high-throughput, but also high-latency, on most GPUs.
Someone from the Chrome team will have to chime in with a definitive answer, but that fits my experience with canvases in Chrome.

Categories

Resources