legege/node-mjpeg-proxy — pull request #4 by bchabrier (2014-05-03 10:19:32+00:00)
Title: Fixed a concurrency issue

Fixed a bug that when several quick requests were occurring, it sometimes happened that more than one mjpegRequest was created. This can be put in evidence with a page making several calls to the same stream:

<img src="/index1.jpg">
<img src="/index1.jpg">
<img src="/index1.jpg">
<img src="/index1.jpg">
...

while index1.jpg is served by the mjpeg proxy:

app.get('/index1.jpg',
new MjpegProxy('http://admin:admin@192.168.1.109/cgi/mjpg/mjpg.cgi').proxyRequest);

and adding traces each time the mjpegRequest is created.

I noticed this in fact because my own IP camera is not able to serve too many clients (3-4 max in fact), and when displaying several times the same camera images on a page I could get some working correctly, the others being broken.

Looking at the code the selection of whether there is already a client or not is based on the audienceResponses array. This array is populated by _newClient, which is called only once the IP camera has sent an answer (ie mjpegRequest gets a response). If a new request to /index1.jpg is sent before the IP camera had the time to answer, then audienceResponses is not yet populated and we follow the path of the first client again, resulting in the creation of yet another mpjegRequest.

To fix this I have based the detection of the first client on the existence of the mjpegRequest, by making it a member of MjpegProxy. Seems to work better, I can see now a myriad of /index1.jpg on the same page :-)