This repository has been archived by the owner on Mar 12, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 12
/
CameraService.cs
244 lines (225 loc) · 9.73 KB
/
CameraService.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
using System;
using System.Collections;
using System.Threading;
using System.Threading.Tasks;
using JetBrains.Annotations;
using LabAssistVision;
using Microsoft.MixedReality.Toolkit.Utilities;
using Microsoft.Unity;
using OpenCVForUnity.CoreModule;
using OpenCVForUnity.UnityUtils;
using OpenCVForUnity.UtilsModule;
using UnityEngine;
using UnityEngine.Experimental.Rendering;
using UnityEngine.Rendering;
namespace Microsoft.MixedReality.Toolkit.Extensions
{
[MixedRealityExtensionService(SupportedPlatforms.WindowsStandalone | SupportedPlatforms.WindowsUniversal)]
public class CameraService : BaseExtensionService, ICameraService, IMixedRealityExtensionService
{
#region Member Variables
public event EventHandler<CameraInitializedEventArgs> CameraInitialized;
public event EventHandler<FrameArrivedEventArgs> FrameArrived;
public int FrameWidth => _camera.FrameWidth;
public int FrameHeight => _camera.FrameHeight;
public uint FrameCount = int.MaxValue;
public bool Initialized { get; set; }
public ColorFormat Format => _cameraServiceProfile.format;
CameraFrame ICameraService.CameraFrame => _frame;
private ICamera _camera;
private CameraFrame _frame;
private Shader Yuv2RGBNv12Shader => _cameraServiceProfile.rgbShader;
/// <summary>
/// Contains the YUV2RGB_NV12 Shader required for conversion on the GPU.
/// </summary>
private Material _mediaMaterialRGB;
private Texture2D _luminance;
private Texture2D _chrominance;
private Mat _rgb;
[NotNull] private readonly CameraServiceProfile _cameraServiceProfile;
private LocatableCameraProfile LocatableCameraProfile => _cameraServiceProfile.locatableCameraProfile;
private int _isProcessingFrame;
public bool IsProcessingFrame
{
get { return Interlocked.CompareExchange(ref _isProcessingFrame, 1, 1) == 1; }
set
{
if (value) Interlocked.CompareExchange(ref _isProcessingFrame, 1, 0);
else Interlocked.CompareExchange(ref _isProcessingFrame, 0, 1);
}
}
/// <summary>
/// Introduced for async RGB conversion
/// TODO: Optimize
/// </summary>
private readonly object _sync = new object();
private CameraFrame _currentCameraFrame;
private CameraFrame CurrentCameraFrame
{
get
{
lock (_sync)
return _currentCameraFrame;
}
set
{
lock (_sync)
_currentCameraFrame = value;
}
}
private bool _newFrameAvailable;
public bool NewFrameAvailable
{
get
{
if (!_newFrameAvailable) return false;
_newFrameAvailable = false;
return true;
}
set
{
_newFrameAvailable = value;
}
}
#endregion Member Variables
#region Contructors
public CameraService(string name, uint priority, BaseMixedRealityProfile profile) : base(name, priority, profile)
{
if (profile == null) throw new ArgumentNullException(nameof(profile));
CameraServiceProfile serviceProfile = profile as CameraServiceProfile;
if (serviceProfile == null) throw new ArgumentNullException(nameof(serviceProfile));
_cameraServiceProfile = serviceProfile;
if (Yuv2RGBNv12Shader == null) throw new ArgumentNullException(nameof(Yuv2RGBNv12Shader), "No conversion shader found. Check configuration. Ensure that YUV2RGB_NV12 Shader is always included (Project Settings > Graphics > Always Included Shaders)");
#if ENABLE_WINMD_SUPPORT
_camera = new LocatableCamera(LocatableCameraProfile, Format);
_camera.FrameArrived += OnFrameArrived;
_camera.CameraInitialized += OnCameraInitialized;
#else
_camera = new MonoCamera(Format);
_camera.FrameArrived += OnFrameArrived;
_camera.CameraInitialized += OnCameraInitialized;
#endif
}
#endregion // Constructors
#region Internal Methods
/// <summary>
/// Instantiates required textures and registers RGB conversion if requested.
/// </summary>
private void OnCameraInitialized(object sender, CameraInitializedEventArgs e)
{
if (Format == ColorFormat.RGB)
{
_rgb = new Mat(FrameHeight, FrameWidth, CvType.CV_8UC3);
_mediaMaterialRGB = new Material(Yuv2RGBNv12Shader);
if (_mediaMaterialRGB == null) throw new InvalidOperationException("Media Material shader not found");
// A single-component, 8-bit unsigned-normalized-integer format that supports 8 bits for the red channel.
_luminance = new Texture2D(FrameWidth, FrameHeight, TextureFormat.R8, false);
// A two-component, 16-bit unsigned-normalized-integer format that supports 8 bits for the red channel and 8 bits for the green channel.
_chrominance = new Texture2D(FrameWidth / 2, FrameHeight / 2, TextureFormat.RG16, false);
_mediaMaterialRGB.SetTexture("luminanceChannel", _luminance);
_mediaMaterialRGB.SetTexture("chrominanceChannel", _chrominance);
Camera.onPreRender += OnPreRenderCallback;
}
CameraInitialized?.Invoke(this, e);
Initialized = true;
}
/// <summary>
/// Starts the NV12 to RGB conversion on the GPU.
/// </summary>
/// <param name="camera"></param>
private void OnPreRenderCallback(Camera camera)
{
if (camera != Camera.main) return;
if (CurrentCameraFrame == null) return;
if (FrameCount == CurrentCameraFrame.FrameCount) return;
FrameCount = CurrentCameraFrame.FrameCount;
CoroutineRunner.StartCoroutine(Convert(CurrentCameraFrame));
}
/// <summary>
/// Updates the textures required by the conversion shader and requests the conversion on the GPU.
/// </summary>
/// <param name="frame"></param>
private IEnumerator Convert(CameraFrame frame)
{
Mat nv12 = frame.Mat;
Mat luminance = nv12.submat(0, FrameHeight, 0, FrameWidth);
Mat chrominance = nv12.submat(FrameHeight, nv12.height(), 0, nv12.width());
Utils.fastMatToTexture2D(luminance, _luminance);
Utils.fastMatToTexture2D(chrominance, _chrominance);
var rt = RenderTexture.GetTemporary(FrameWidth, FrameHeight, 0, GraphicsFormat.R8G8B8A8_UNorm);
Graphics.Blit(null, rt, _mediaMaterialRGB);
yield return new WaitForEndOfFrame();
AsyncGPUReadback.Request(rt, 0, TextureFormat.RGB24, OnCompleteReadback);
RenderTexture.ReleaseTemporary(rt);
}
/// <summary>
/// Invoked if the NV12 to RGB conversion is complete and the data is ready to be read to the CPU.
/// </summary>
private void OnCompleteReadback(AsyncGPUReadbackRequest request)
{
if (request.hasError)
{
Debug.LogError("GPU readback error");
return;
}
MatUtils.copyToMat(request.GetData<uint>(), _rgb);
Core.flip(_rgb, _rgb, 0); // image is flipped on x-axis
CameraFrame newFrame = new CameraFrame(_rgb, CurrentCameraFrame.Intrinsic, CurrentCameraFrame.Extrinsic, CurrentCameraFrame.Width, CurrentCameraFrame.Height, CurrentCameraFrame.FrameCount, Format);
FrameArrivedEventArgs args = new FrameArrivedEventArgs(newFrame);
_frame = newFrame;
FrameArrived?.Invoke(this, args);
FPSUtils.VideoTick();
NewFrameAvailable = true;
IsProcessingFrame = false;
}
/// <summary>
/// Depending on color format, the frame is passed on or buffered for conversion.
/// </summary>
private void OnFrameArrived(object sender, FrameArrivedEventArgs e)
{
if (Format == ColorFormat.Grayscale)
{
_frame = e.Frame;
FPSUtils.VideoTick();
FrameArrived?.Invoke(this, e);
}
else
{
if (IsProcessingFrame) return;
IsProcessingFrame = true;
CurrentCameraFrame = e.Frame;
}
}
#endregion // Internal Methods
#region Public Methods
/// <summary>
/// Stops the camera and creates a new <see cref="ICamera">camera</see> with a new profile and format.
/// </summary>
public async void ChangeVideoParameter(LocatableCameraProfile profile, ColorFormat format)
{
await _camera.StopCapture();
_cameraServiceProfile.format = format;
_camera.FrameArrived -= OnFrameArrived;
_camera.CameraInitialized -= OnCameraInitialized;
#if ENABLE_WINMD_SUPPORT
_camera = new LocatableCamera(profile, format);
#else
_camera = new MonoCamera(format);
#endif
_camera.FrameArrived += OnFrameArrived;
_camera.CameraInitialized += OnCameraInitialized;
await _camera.Initialize();
await _camera.StartCapture();
}
public async Task<bool> StartCapture()
{
if (!Initialized) await _camera.Initialize();
return await _camera.StartCapture();
}
public async Task<bool> StopCapture()
{
return await _camera.StopCapture();
}
#endregion // Public Methods
}
}