-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathMainPage.xaml.cs
348 lines (296 loc) · 11.8 KB
/
MainPage.xaml.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
using Lumia.Imaging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using VideoEffects;
using Windows.Devices.Enumeration;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Graphics.Display;
using Windows.Media;
using Windows.Media.Capture;
using Windows.Media.MediaProperties;
#if WINDOWS_PHONE_APP
using Windows.Phone.UI.Input;
#endif
using Windows.Storage;
using Windows.Storage.Streams;
using Windows.System.Display;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using ZXing;
using ZXing.Common;
namespace QrCodeDetector
{
public sealed partial class MainPage : Page
{
DisplayRequest m_displayRequest = new DisplayRequest();
MediaCapture m_capture;
ContinuousAutoFocus m_autoFocus;
bool m_initializing;
#if !WINDOWS_PHONE_APP
SystemMediaTransportControls m_mediaControls;
#endif
BarcodeReader m_reader = new BarcodeReader
{
Options = new DecodingOptions
{
PossibleFormats = new BarcodeFormat[] { BarcodeFormat.QR_CODE, BarcodeFormat.CODE_128 },
TryHarder = true
}
};
Stopwatch m_time = new Stopwatch();
volatile bool m_snapRequested;
public MainPage()
{
this.InitializeComponent();
this.NavigationCacheMode = NavigationCacheMode.Required;
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
// Disable app UI rotation
DisplayInformation.AutoRotationPreferences = DisplayOrientations.Landscape;
// Prevent screen timeout
m_displayRequest.RequestActive();
// Handle app going to and coming out of background
#if WINDOWS_PHONE_APP
Application.Current.Resuming += App_Resuming;
Application.Current.Suspending += App_Suspending;
Window.Current.VisibilityChanged += Current_VisibilityChanged;
var ignore = InitializeCaptureAsync();
#else
m_mediaControls = SystemMediaTransportControls.GetForCurrentView();
m_mediaControls.PropertyChanged += m_mediaControls_PropertyChanged;
if (!IsInBackground())
{
var ignore = InitializeCaptureAsync();
}
#endif
}
protected override async void OnNavigatedFrom(NavigationEventArgs e)
{
#if WINDOWS_PHONE_APP
Application.Current.Resuming -= App_Resuming;
Application.Current.Suspending -= App_Suspending;
Window.Current.VisibilityChanged -= Current_VisibilityChanged;
#else
m_mediaControls.PropertyChanged -= m_mediaControls_PropertyChanged;
#endif
DisplayInformation.AutoRotationPreferences = DisplayOrientations.None;
m_displayRequest.RequestRelease();
await DisposeCaptureAsync();
}
#if WINDOWS_PHONE_APP
private void App_Resuming(object sender, object e)
{
// Dispatch call to the UI thread since the event may get fired on some other thread
var ignore = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
{
await InitializeCaptureAsync();
});
}
private void App_Suspending(object sender, Windows.ApplicationModel.SuspendingEventArgs e)
{
// Dispatch call to the UI thread since the event may get fired on some other thread
var ignore = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
{
await DisposeCaptureAsync();
});
}
async void Current_VisibilityChanged(object sender, VisibilityChangedEventArgs e)
{
if (e.Visible)
{
await InitializeCaptureAsync();
}
else
{
await DisposeCaptureAsync();
}
}
#else
void m_mediaControls_PropertyChanged(SystemMediaTransportControls sender, SystemMediaTransportControlsPropertyChangedEventArgs args)
{
if (args.Property != SystemMediaTransportControlsProperty.SoundLevel)
{
return;
}
// Dispatch call to the UI thread since the event may get fired on some other thread
var ignore = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
{
if (!IsInBackground())
{
await InitializeCaptureAsync();
}
else
{
await DisposeCaptureAsync();
}
});
}
private bool IsInBackground()
{
return m_mediaControls.SoundLevel == SoundLevel.Muted;
}
#endif
void capture_Failed(MediaCapture sender, MediaCaptureFailedEventArgs errorEventArgs)
{
// Dispatch call to the UI thread since the event may get fired on some other thread
var ignore = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
{
await DisposeCaptureAsync();
});
}
// Must be called on the UI thread
private async Task InitializeCaptureAsync()
{
if (m_initializing || (m_capture != null))
{
return;
}
m_initializing = true;
try
{
var settings = new MediaCaptureInitializationSettings
{
VideoDeviceId = await GetBackOrDefaulCameraIdAsync(),
StreamingCaptureMode = StreamingCaptureMode.Video
};
var capture = new MediaCapture();
await capture.InitializeAsync(settings);
// Select the capture resolution closest to screen resolution
var formats = capture.VideoDeviceController.GetAvailableMediaStreamProperties(MediaStreamType.VideoPreview);
var format = (VideoEncodingProperties)formats.OrderBy((item) =>
{
var props = (VideoEncodingProperties)item;
return Math.Abs(props.Width - this.ActualWidth) + Math.Abs(props.Height - this.ActualHeight);
}).First();
await capture.VideoDeviceController.SetMediaStreamPropertiesAsync(MediaStreamType.VideoPreview, format);
// Make the preview full screen
var scale = Math.Min(this.ActualWidth / format.Width, this.ActualHeight / format.Height);
Preview.Width = format.Width;
Preview.Height = format.Height;
Preview.RenderTransformOrigin = new Point(.5, .5);
Preview.RenderTransform = new ScaleTransform { ScaleX = scale, ScaleY = scale };
BarcodeOutline.Width = format.Width;
BarcodeOutline.Height = format.Height;
BarcodeOutline.RenderTransformOrigin = new Point(.5, .5);
BarcodeOutline.RenderTransform = new ScaleTransform { ScaleX = scale, ScaleY = scale };
// Enable QR code detection
var definition = new LumiaAnalyzerDefinition(ColorMode.Yuv420Sp, 640, AnalyzeBitmap);
await capture.AddEffectAsync(MediaStreamType.VideoPreview, definition.ActivatableClassId, definition.Properties);
// Start preview
m_time.Restart();
Preview.Source = capture;
await capture.StartPreviewAsync();
capture.Failed += capture_Failed;
m_autoFocus = await ContinuousAutoFocus.StartAsync(capture.VideoDeviceController.FocusControl);
m_capture = capture;
}
catch (Exception e)
{
TextLog.Text = String.Format("Failed to start the camera: {0}", e.Message);
}
m_initializing = false;
}
private void AnalyzeBitmap(Bitmap bitmap, TimeSpan time)
{
if (m_snapRequested)
{
m_snapRequested = false;
IBuffer jpegBuffer = (new JpegRenderer(new BitmapImageSource(bitmap))).RenderAsync().AsTask().Result;
var jpegFile = KnownFolders.PicturesLibrary.CreateFileAsync("QrCodeSnap.jpg", CreationCollisionOption.GenerateUniqueName).AsTask().Result;
FileIO.WriteBufferAsync(jpegFile, jpegBuffer).AsTask().Wait();
}
Log.Events.QrCodeDecodeStart();
Result result = m_reader.Decode(
bitmap.Buffers[0].Buffer.ToArray(),
(int)bitmap.Buffers[0].Pitch, // Should be width here but I haven't found a way to pass both width and stride to ZXing yet
(int)bitmap.Dimensions.Height,
BitmapFormat.Gray8
);
Log.Events.QrCodeDecodeStop(result != null);
var ignore = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
var elapsedTimeInMS = m_time.ElapsedMilliseconds;
m_time.Restart();
if (result == null)
{
TextLog.Text = String.Format("[{0,4}ms] No barcode", elapsedTimeInMS);
if (m_autoFocus != null)
{
m_autoFocus.BarcodeFound = false;
}
BarcodeOutline.Points.Clear();
}
else
{
TextLog.Text = String.Format("[{0,4}ms] {1}", elapsedTimeInMS, result.Text);
if (m_autoFocus != null)
{
m_autoFocus.BarcodeFound = true;
}
BarcodeOutline.Points.Clear();
for (int n = 0; n < result.ResultPoints.Length; n++)
{
BarcodeOutline.Points.Add(new Point(
result.ResultPoints[n].X * (BarcodeOutline.Width / bitmap.Dimensions.Width),
result.ResultPoints[n].Y * (BarcodeOutline.Height / bitmap.Dimensions.Height)
));
}
}
});
}
public static async Task<string> GetBackOrDefaulCameraIdAsync()
{
var devices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);
string deviceId = "";
foreach (var device in devices)
{
if ((device.EnclosureLocation != null) &&
(device.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Back))
{
deviceId = device.Id;
break;
}
}
return deviceId;
}
// Must be called on the UI thread
private async Task DisposeCaptureAsync()
{
Preview.Source = null;
if (m_autoFocus != null)
{
m_autoFocus.Dispose();
m_autoFocus = null;
}
MediaCapture capture;
lock (this)
{
capture = m_capture;
m_capture = null;
}
if (capture != null)
{
capture.Failed -= capture_Failed;
await capture.StopPreviewAsync();
capture.Dispose();
}
}
private void Snap_Click(object sender, RoutedEventArgs e)
{
m_snapRequested = true;
}
}
}