MJPEGSource.cs
8.22 KB
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
// Camara Vision
//
// Copyright © Andrew Kirillov, 2005-2006
// andrew.kirillov@gmail.com
//
namespace mjpeg
{
using System;
using System.Drawing;
using System.IO;
using System.Text;
using System.Threading;
using System.Net;
using videosource;
/// <summary>
/// MJPEGSource - MJPEG stream support
/// </summary>
public class MJPEGSource : IVideoSource
{
private string source;
private string login = null;
private string password = null;
private object userData = null;
private int framesReceived;
private int bytesReceived;
private bool useSeparateConnectionGroup = true;
private const int bufSize = 512 * 1024; // buffer size
private const int readSize = 1024; // portion size to read
private Thread thread = null;
private ManualResetEvent stopEvent = null;
private ManualResetEvent reloadEvent = null;
// new frame event
public event CameraEventHandler NewFrame;
// SeparateConnectioGroup property
// indicates to open WebRequest in separate connection group
public bool SeparateConnectionGroup
{
get { return useSeparateConnectionGroup; }
set { useSeparateConnectionGroup = value; }
}
// VideoSource property
public string VideoSource
{
get { return source; }
set
{
source = value;
// signal to reload
if (thread != null)
reloadEvent.Set();
}
}
// Login property
public string Login
{
get { return login; }
set { login = value; }
}
// Password property
public string Password
{
get { return password; }
set { password = value; }
}
// FramesReceived property
public int FramesReceived
{
get
{
int frames = framesReceived;
framesReceived = 0;
return frames;
}
}
// BytesReceived property
public int BytesReceived
{
get
{
int bytes = bytesReceived;
bytesReceived = 0;
return bytes;
}
}
// UserData property
public object UserData
{
get { return userData; }
set { userData = value; }
}
// Get state of the video source thread
public bool Running
{
get
{
if (thread != null)
{
if (thread.Join(0) == false)
return true;
// the thread is not running, so free resources
Free();
}
return false;
}
}
// Constructor
public MJPEGSource()
{
}
// Start work
public void Start()
{
if (thread == null)
{
framesReceived = 0;
bytesReceived = 0;
// create events
stopEvent = new ManualResetEvent(false);
reloadEvent = new ManualResetEvent(false);
// create and start new thread
thread = new Thread(new ThreadStart(WorkerThread));
thread.Name = source;
thread.Start();
}
}
// Signal thread to stop work
public void SignalToStop()
{
// stop thread
if (thread != null)
{
// signal to stop
stopEvent.Set();
}
}
// Wait for thread stop
public void WaitForStop()
{
if (thread != null)
{
// wait for thread stop
thread.Join();
Free();
}
}
// Abort thread
public void Stop()
{
if (this.Running)
{
thread.Abort();
WaitForStop();
}
}
// Free resources
private void Free()
{
thread = null;
// release events
stopEvent.Close();
stopEvent = null;
reloadEvent.Close();
reloadEvent = null;
}
// Thread entry point
public void WorkerThread()
{
byte[] buffer = new byte[bufSize]; // buffer to read stream
while (true)
{
// reset reload event
reloadEvent.Reset();
HttpWebRequest req = null;
WebResponse resp = null;
Stream stream = null;
byte[] delimiter = null;
byte[] delimiter2 = null;
byte[] boundary = null;
int boundaryLen, delimiterLen = 0, delimiter2Len = 0;
int read, todo = 0, total = 0, pos = 0, align = 1;
int start = 0, stop = 0;
// align
// 1 = searching for image start
// 2 = searching for image end
try
{
// create request
req = (HttpWebRequest) WebRequest.Create(source);
// set login and password
if ((login != null) && (password != null) && (login != ""))
req.Credentials = new NetworkCredential(login, password);
// set connection group name
if (useSeparateConnectionGroup)
req.ConnectionGroupName = GetHashCode().ToString();
// get response
resp = req.GetResponse();
// check content type
string ct = resp.ContentType;
if (ct.IndexOf("multipart/x-mixed-replace") == -1)
throw new ApplicationException("Invalid URL");
// get boundary
ASCIIEncoding encoding = new ASCIIEncoding();
boundary = encoding.GetBytes(ct.Substring(ct.IndexOf("boundary=", 0) + 9));
boundaryLen = boundary.Length;
// get response stream
stream = resp.GetResponseStream();
// loop
while ((!stopEvent.WaitOne(0, true)) && (!reloadEvent.WaitOne(0, true)))
{
// check total read
if (total > bufSize - readSize)
{
total = pos = todo = 0;
}
// read next portion from stream
if ((read = stream.Read(buffer, total, readSize)) == 0)
throw new ApplicationException();
total += read;
todo += read;
// increment received bytes counter
bytesReceived += read;
// does we know the delimiter ?
if (delimiter == null)
{
// find boundary
pos = ByteArrayUtils.Find(buffer, boundary, pos, todo);
if (pos == -1)
{
// was not found
todo = boundaryLen - 1;
pos = total - todo;
continue;
}
todo = total - pos;
if (todo < 2)
continue;
// check new line delimiter type
if (buffer[pos + boundaryLen] == 10)
{
delimiterLen = 2;
delimiter = new byte[2] {10, 10};
delimiter2Len = 1;
delimiter2 = new byte[1] {10};
}
else
{
delimiterLen = 4;
delimiter = new byte[4] {13, 10, 13, 10};
delimiter2Len = 2;
delimiter2 = new byte[2] {13, 10};
}
pos += boundaryLen + delimiter2Len;
todo = total - pos;
}
// search for image
if (align == 1)
{
start = ByteArrayUtils.Find(buffer, delimiter, pos, todo);
if (start != -1)
{
// found delimiter
start += delimiterLen;
pos = start;
todo = total - pos;
align = 2;
}
else
{
// delimiter not found
todo = delimiterLen - 1;
pos = total - todo;
}
}
// search for image end
while ((align == 2) && (todo >= boundaryLen))
{
stop = ByteArrayUtils.Find(buffer, boundary, pos, todo);
if (stop != -1)
{
pos = stop;
todo = total - pos;
// increment frames counter
framesReceived ++;
// image at stop
if (NewFrame != null)
{
Bitmap bmp = (Bitmap) Bitmap.FromStream(new MemoryStream(buffer, start, stop - start));
// notify client
NewFrame(this, new CameraEventArgs(bmp));
// release the image
bmp.Dispose();
bmp = null;
}
// shift array
pos = stop + boundaryLen;
todo = total - pos;
Array.Copy(buffer, pos, buffer, 0, todo);
total = todo;
pos = 0;
align = 1;
}
else
{
// delimiter not found
todo = boundaryLen - 1;
pos = total - todo;
}
}
}
}
catch (WebException ex)
{
System.Diagnostics.Debug.WriteLine("=============: " + ex.Message);
// wait for a while before the next try
Thread.Sleep(250);
}
catch (ApplicationException ex)
{
System.Diagnostics.Debug.WriteLine("=============: " + ex.Message);
// wait for a while before the next try
Thread.Sleep(250);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("=============: " + ex.Message);
}
finally
{
// abort request
if (req != null)
{
req.Abort();
req = null;
}
// close response stream
if (stream != null)
{
stream.Close();
stream = null;
}
// close response
if (resp != null)
{
resp.Close();
resp = null;
}
}
// need to stop ?
if (stopEvent.WaitOne(0, true))
break;
}
}
}
}