This repository was archived by the owner on Feb 22, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathFrameDiffDriver.cs
More file actions
235 lines (196 loc) · 8.3 KB
/
Copy pathFrameDiffDriver.cs
File metadata and controls
235 lines (196 loc) · 8.3 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
// <copyright file="FrameDiffDriver.cs" company="Techyian">
// Copyright (c) Ian Auty and contributors. All rights reserved.
// Licensed under the MIT License. Please see LICENSE.txt for License info.
// </copyright>
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Runtime.InteropServices;
using Microsoft.Extensions.Logging;
using MMALSharp.Common;
using MMALSharp.Common.Utility;
namespace MMALSharp.Processors.Motion
{
/// <summary>
/// A frame difference motion detection class which buffers a test frame and a current frame,
/// and invokes an <see cref="IMotionAlgorithm"/> to detect motion.
/// </summary>
public class FrameDiffDriver : FrameAnalyser
{
// Some members are fields rather than properties for parallel processing performance reasons.
// Array-based fields are threadsafe as long as multiple threads access unique array indices.
/// <summary>
/// Fully black pixels are skipped when comparing the test frame to the current frame.
/// </summary>
internal byte[] FrameMask;
/// <summary>
/// This is the image we are comparing against new incoming frames.
/// </summary>
internal byte[] TestFrame;
/// <summary>
/// The number of pixels that differ in each cell between the test frame and current frame.
/// </summary>
internal int[] CellDiff;
private Action _onDetect;
private MotionConfig _motionConfig;
private bool _fullTestFrame;
private Stopwatch _testFrameAge;
/// <summary>
/// When true, the OnDetect Action will be invoked when motion is detected. Using this instead
/// of the capture handler's Enable/DisableMotionDetection allows ongoing motion detection.
/// </summary>
public bool OnDetectEnabled { get; set; }
/// <summary>
/// Tracks the elapsed time since motion was last detected.
/// </summary>
public Stopwatch LastDetectionEvent { get; private set; }
/// <summary>
/// Creates a new instance of <see cref="FrameDiffDriver"/>.
/// </summary>
/// <param name="config">The motion configuration object.</param>
/// <param name="onDetect">A callback when changes are detected.</param>
public FrameDiffDriver(MotionConfig config, Action onDetect)
{
_motionConfig = config;
_onDetect = onDetect;
this.OnDetectEnabled = _onDetect != null;
_testFrameAge = new Stopwatch();
this.LastDetectionEvent = new Stopwatch();
}
// These are used for temporary local performance-testing; uncomment these and four lines in
// the Apply method below, and see the Dispose method at the end of FrameBufferCaptureHandler.
// private Stopwatch frameTimer = new Stopwatch();
// internal long frameCounter;
// internal long totalElapsed;
/// <inheritdoc />
public override void Apply(ImageContext context)
{
base.Apply(context);
if (context.Eos == false)
{
return;
}
// if zero bytes buffered, EOS is the end of a physical input video filestream
if (this.WorkingData.Count == 0)
{
MMALLog.Logger.LogDebug("EOS reached, no working data buffered");
return;
}
if (!_fullTestFrame)
{
MMALLog.Logger.LogDebug("EOS reached for test frame.");
this.PrepareTestFrame();
_fullTestFrame = true;
return;
}
MMALLog.Logger.LogDebug("Have full frame, invoking motion algorithm.");
// frameCounter++;
// frameTimer.Restart();
var detected = _motionConfig.MotionAlgorithm.DetectMotion(this, Metadata);
// frameTimer.Stop();
// totalElapsed += frameTimer.ElapsedMilliseconds;
if (detected)
{
this.LastDetectionEvent.Restart();
if (this.OnDetectEnabled)
{
_onDetect?.Invoke();
}
}
this.TryUpdateTestFrame();
}
/// <summary>
/// Resets the state of the buffers so that a new test frame is
/// stored. Also resets any state in the motion detection algorithm.
/// </summary>
public void ResetAnalyser()
{
this.FullFrame = false;
_fullTestFrame = false;
this.WorkingData = new List<byte>();
this.TestFrame = null;
this.CurrentFrame = null;
_testFrameAge.Reset();
_motionConfig.MotionAlgorithm.ResetAnalyser(this, this.Metadata);
}
/// <inheritdoc />
protected override void ProcessFirstFrame(ImageContext context)
{
base.ProcessFirstFrame(context);
this.PrepareTestFrame();
CellDiff = new int[CellRect.Length];
this.PrepareMask();
// Provide a copy with raw full-frame defaults that the algorithm can safely store and reuse
// if the algorithm is configured to output analysis frames to a capture handler's Apply method.
var fullFrameContextTemplate = new ImageContext
{
Eos = true,
IFrame = true,
Resolution = new Resolution(Metadata.Width, Metadata.Height),
Encoding = context.Encoding,
PixelFormat = context.PixelFormat,
Raw = context.Raw,
Pts = null,
Stride = Metadata.Stride
};
_motionConfig.MotionAlgorithm.FirstFrameCompleted(this, this.Metadata, fullFrameContextTemplate);
}
private void PrepareTestFrame()
{
this.TestFrame = this.WorkingData.ToArray();
if (_motionConfig.TestFrameInterval != TimeSpan.Zero)
{
_testFrameAge.Restart();
}
}
// Periodically replaces the test frame with the current frame, which helps when a scene
// changes over time (such as changing shadows throughout the day).
private void TryUpdateTestFrame()
{
// Exit if the update interval has not elapsed, or if there was recent motion
if (_motionConfig.TestFrameInterval == TimeSpan.Zero
|| _testFrameAge.Elapsed < _motionConfig.TestFrameInterval
|| (_motionConfig.TestFrameRefreshCooldown != TimeSpan.Zero
&& this.LastDetectionEvent.Elapsed < _motionConfig.TestFrameRefreshCooldown))
{
return;
}
MMALLog.Logger.LogDebug($"Updating test frame after {_testFrameAge.ElapsedMilliseconds} ms");
this.PrepareTestFrame();
}
private void PrepareMask()
{
if (string.IsNullOrWhiteSpace(_motionConfig.MotionMaskPathname))
{
return;
}
using (var fs = new FileStream(_motionConfig.MotionMaskPathname, FileMode.Open, FileAccess.Read))
using (var mask = new Bitmap(fs))
{
// Verify it matches our frame dimensions
var maskBpp = Image.GetPixelFormatSize(mask.PixelFormat) / 8;
if (mask.Width != Metadata.Width || mask.Height != Metadata.Height || maskBpp != Metadata.Bpp)
{
throw new Exception("Motion-detection mask must match raw stream width, height, and format (bits per pixel)");
}
// Store the byte array
BitmapData bmpData = null;
try
{
bmpData = mask.LockBits(new Rectangle(0, 0, mask.Width, mask.Height), ImageLockMode.ReadOnly, mask.PixelFormat);
var pNative = bmpData.Scan0;
int size = bmpData.Stride * mask.Height;
FrameMask = new byte[size];
Marshal.Copy(pNative, FrameMask, 0, size);
}
finally
{
mask.UnlockBits(bmpData);
}
}
}
}
}