-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathSRV1Camera.cs
450 lines (408 loc) · 15.2 KB
/
SRV1Camera.cs
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
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
// AForge Surveyor Robotics Library
// AForge.NET framework
// http://www.aforgenet.com/framework/
//
// Copyright © AForge.NET, 2005-2011
//
namespace AForge.Robotics.Surveyor
{
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using AForge.Video;
/// <summary>
/// Provides access to video stream from Surveyor SRV-1 Blackfin camera.
/// </summary>
///
/// <remarks><para>The class allows to continuously receive video frames from
/// Surveyor SRV-1 Blackfin camera. It creates a background thread and periodically requests
/// new video frames from SRV-1 robot/camera, which are provided to user through <see cref="NewFrame"/>
/// event. The video frame rate can be configured using <see cref="FrameInterval"/>
/// property, which sets time interval between frames.</para>
///
/// <para>In order to get instance of this class, use <see cref="SRV1.GetCamera"/>
/// or <see cref="SVS.GetCamera"/> methods.</para>
///
/// <para>Sample usage:</para>
/// <code>
/// // get SRV-1 camera
/// SRV1Camera camera = srv.GetCamera( );
/// // in the case you work with Surveyor SVS board
/// // the next line can be use
/// // SRV1Camera camera = svs.GetCamera( SVS.Camera.Left );
///
/// // set NewFrame event handler
/// camera.NewFrame += new NewFrameEventHandler( video_NewFrame );
/// // start the video source
/// camera.Start( );
/// // ...
///
/// private void video_NewFrame( object sender, NewFrameEventArgs eventArgs )
/// {
/// // get new frame
/// Bitmap bitmap = eventArgs.Frame;
/// // process the frame
/// }
/// </code>
/// </remarks>
///
public class SRV1Camera : IVideoSource
{
private SRV1 communicator;
// received frames count
private int framesReceived;
// recieved bytes count
private long bytesReceived;
// frame interval in milliseconds
private int frameInterval = 0;
private Thread thread = null;
private ManualResetEvent stopEvent = null;
// buffer size used to download JPEG image
private const int bufferSize = 768 * 1024;
/// <summary>
/// New frame event.
/// </summary>
///
/// <remarks><para>Notifies clients about new available frame from video source.</para>
///
/// <para><note>Since video source may have multiple clients, each client is responsible for
/// making a copy (cloning) of the passed video frame, because the video source disposes its
/// own original copy after notifying of clients.</note></para>
/// </remarks>
///
public event NewFrameEventHandler NewFrame;
/// <summary>
/// Video source error event.
/// </summary>
///
/// <remarks>This event is used to notify clients about any type of errors occurred in
/// video source object, for example internal exceptions.</remarks>
///
public event VideoSourceErrorEventHandler VideoSourceError;
/// <summary>
/// Video playing finished event.
/// </summary>
///
/// <remarks><para>This event is used to notify clients that the video playing has finished.</para>
/// </remarks>
///
public event PlayingFinishedEventHandler PlayingFinished;
/// <summary>
/// Frame interval.
/// </summary>
///
/// <remarks><para>The property sets the interval in milliseconds betwen frames. If the property is
/// set to 100, then the desired frame rate will be 10 frames per second.</para>
///
/// <para>Default value is set to <b>0</b> - get new frames as fast as possible.</para>
/// </remarks>
///
public int FrameInterval
{
get { return frameInterval; }
set { frameInterval = value; }
}
/// <summary>
/// Video source string.
/// </summary>
///
/// <remarks>
/// <para>The property keeps connection string, which was used to connect to SRV-1 Blackfin camera.</para>
/// </remarks>
///
public string Source
{
get { return ( ( communicator != null ) && ( communicator.EndPoint != null ) ) ?
communicator.EndPoint.ToString( ) : "unknown" ; }
}
/// <summary>
/// Received frames count.
/// </summary>
///
/// <remarks>Number of frames the video source provided from the moment of the last
/// access to the property.
/// </remarks>
///
public int FramesReceived
{
get
{
int frames = framesReceived;
framesReceived = 0;
return frames;
}
}
/// <summary>
/// Received bytes count.
/// </summary>
///
/// <remarks>Number of bytes the video source provided from the moment of the last
/// access to the property.
/// </remarks>
///
public long BytesReceived
{
get
{
long bytes = bytesReceived;
bytesReceived = 0;
return bytes;
}
}
/// <summary>
/// State of the video source.
/// </summary>
///
/// <remarks>Current state of video source object - running or not.</remarks>
///
public bool IsRunning
{
get
{
if ( thread != null )
{
// check thread status
if ( thread.Join( 0 ) == false )
return true;
// the thread is not running, free resources
Free( );
}
return false;
}
}
// The class may be instantiate using SVS or SRV1 objects only
internal SRV1Camera( SRV1 communicator )
{
this.communicator = communicator;
}
/// <summary>
/// Start video source.
/// </summary>
///
/// <remarks>Starts video source and return execution to caller. Video source
/// object creates background thread and notifies about new frames with the
/// help of <see cref="NewFrame"/> event.</remarks>
///
/// <exception cref="NotConnectedException">Not connected to SRV-1. Connection to SRV-1
/// was closed using <see cref="SRV1.Disconnect"/> method. New <see cref="SRV1Camera"/>
/// instance must be obtained using <see cref="SRV1.GetCamera"/> or
/// <see cref="SVS.GetCamera"/> methods.
/// </exception>
///
public void Start( )
{
if ( thread == null )
{
if ( ( communicator == null ) || ( communicator.EndPoint == null ) )
{
throw new NotConnectedException( "Not connected to SRV-1." );
}
framesReceived = 0;
bytesReceived = 0;
// create events
stopEvent = new ManualResetEvent( false );
// create and start new thread
thread = new Thread( new ThreadStart( WorkerThread ) );
thread.Name = Source; // mainly for debugging
thread.Start( );
}
}
/// <summary>
/// Signal video source to stop its work.
/// </summary>
///
/// <remarks>Signals video source to stop its background thread, stop to
/// provide new frames and free resources.</remarks>
///
public void SignalToStop( )
{
// stop thread
if ( thread != null )
{
// signal to stop
stopEvent.Set( );
}
}
/// <summary>
/// Wait for video source has stopped.
/// </summary>
///
/// <remarks>Waits for video source stopping after it was signalled to stop using
/// <see cref="SignalToStop"/> method.</remarks>
///
public void WaitForStop( )
{
if ( thread != null )
{
// wait for thread stop
thread.Join( );
Free( );
}
}
/// <summary>
/// Stop video source.
/// </summary>
///
/// <remarks><para>Stops video source aborting its thread.</para>
///
/// <para><note>Since the method aborts background thread, its usage is highly not preferred
/// and should be done only if there are no other options. The correct way of stopping camera
/// is <see cref="SignalToStop">signaling it to stop</see> and then
/// <see cref="WaitForStop">waiting</see> for background thread's completion.</note></para>
/// </remarks>
///
public void Stop( )
{
if ( this.IsRunning )
{
thread.Abort( );
WaitForStop( );
}
}
/// <summary>
/// Free resource.
/// </summary>
///
private void Free( )
{
thread = null;
// release events
stopEvent.Close( );
stopEvent = null;
}
/// <summary>
/// Set video quality.
/// </summary>
///
/// <param name="quality">Video quality to set, [1, 8].</param>
///
/// <remarks><para>The method sets video quality, which is specified in [1, 8] range - 1 is
/// the highest quality level, 8 is the lowest quality level.</para>
///
/// <para><note>Setting higher quality level and <see cref="SetResolution">resolution</see>
/// may increase delays for other requests processed by <see cref="SRV1"/> class. So if
/// robot is used not only for video, but also for controlling servos/motors, and higher
/// response level is required, then do not set very high quality and resolution.
/// </note></para>
/// </remarks>
///
/// <exception cref="ArgumentOutOfRangeException">Invalid quality level was specified.</exception>
///
public void SetQuality( int quality )
{
communicator.SetQuality( quality );
}
/// <summary>
/// Set video resolution.
/// </summary>
///
/// <param name="resolution">Video resolution to set.</param>
///
/// <remarks>
/// <para><note>Setting higher <see cref="SetQuality">quality level</see> and resolution
/// may increase delays for other requests processed by <see cref="SRV1"/> class. So if
/// robot is used not only for video, but also for controlling servos/motors, and higher
/// response level is required, then do not set very high quality and resolution.
/// </note></para>
/// </remarks>
///
public void SetResolution( SRV1.VideoResolution resolution )
{
communicator.SetResolution( resolution );
}
/// <summary>
/// Flip video capture or not (for use with upside-down camera).
/// </summary>
///
/// <param name="isFlipped">Specifies if video should be flipped (<see langword="true"/>),
/// or not (<see langword="false"/>).</param>
///
public void FlipVideo( bool isFlipped )
{
communicator.FlipVideo( isFlipped );
}
/// <summary>
/// Worker thread.
/// </summary>
///
private void WorkerThread( )
{
System.Diagnostics.Stopwatch stopWatch = new System.Diagnostics.Stopwatch( );
// buffer to read stream into
byte[] buffer = new byte[bufferSize];
while ( !stopEvent.WaitOne( 0, false ) )
{
try
{
stopWatch.Reset( );
stopWatch.Start( );
int bytesRead = communicator.SendAndReceive( new byte[] { (byte) 'I' }, buffer );
bytesReceived += bytesRead;
if ( bytesRead > 10 )
{
// check for image reply signature
if (
( buffer[0] == (byte) '#' ) &&
( buffer[1] == (byte) '#' ) &&
( buffer[2] == (byte) 'I' ) &&
( buffer[3] == (byte) 'M' ) &&
( buffer[4] == (byte) 'J' ) )
{
// extract image size
int imageSize = System.BitConverter.ToInt32( buffer, 6 );
if ( !stopEvent.WaitOne( 0, false ) )
{
try
{
// decode image from memory stream
Bitmap bitmap = (Bitmap) Bitmap.FromStream( new MemoryStream( buffer, 10, imageSize ) );
framesReceived++;
// let subscribers know if there are any
if ( NewFrame != null )
{
NewFrame( this, new NewFrameEventArgs( bitmap ) );
}
bitmap.Dispose( );
}
catch
{
}
// wait for a while ?
if ( frameInterval > 0 )
{
// get download duration
stopWatch.Stop( );
// miliseconds to sleep
int msec = frameInterval - (int) stopWatch.ElapsedMilliseconds;
while ( ( msec > 0 ) && ( stopEvent.WaitOne( 0, false ) == false ) )
{
// sleeping ...
Thread.Sleep( ( msec < 100 ) ? msec : 100 );
msec -= 100;
}
}
}
}
}
}
catch
{
if ( VideoSourceError != null )
{
VideoSourceError( this, new VideoSourceErrorEventArgs( "Failed receiving video frame from SRV-1." ) );
}
}
}
stopWatch.Stop( );
if ( PlayingFinished != null )
{
PlayingFinished( this, ReasonToFinishPlaying.StoppedByUser );
}
}
}
}