-
Notifications
You must be signed in to change notification settings - Fork 0
/
MainPage.xaml.cs
385 lines (331 loc) · 14.7 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
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
/*
Copyright(c) Microsoft Open Technologies, Inc. All rights reserved.
The MIT License(MIT)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files(the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions :
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
using System;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media.Imaging;
using Windows.Media.Capture;
using Windows.Media.MediaProperties;
using Windows.Storage;
using Windows.Storage.Streams;
using System.Threading.Tasks;
using Windows.Devices.Enumeration;
using System.Linq;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using System.Text;
using Microsoft.WindowsAzure.Storage.Auth;
using Windows.UI.Xaml.Media;
namespace open360cam
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
private int[] indexArray = new int[] {0,1};
private Image[] cameraImageArray = new Image[2];
private MediaCapture[] mediaCaptureArray = new MediaCapture[2];
private bool[] isPreviewingArray = new bool[2];
#region HELPER_FUNCTIONS
enum Action
{
ENABLE,
DISABLE
}
private void WriteLog(string message)
{
status.Text += "\n " + message;
}
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
var grid = (Grid)VisualTreeHelper.GetChild(status, 0);
for (var i = 0; i <= VisualTreeHelper.GetChildrenCount(grid) - 1; i++)
{
object obj = VisualTreeHelper.GetChild(grid, i);
if (!(obj is ScrollViewer)) continue;
((ScrollViewer)obj).ChangeView(0.0f, ((ScrollViewer)obj).ExtentHeight, 1.0f);
break;
}
}
/// <summary>
/// Helper function to enable or disable Initialization buttons
/// </summary>
/// <param name="action">enum Action</param>
private void SetInitButtonVisibility(Action action)
{
if (action == Action.ENABLE)
{
video_init.IsEnabled = true;
}
else
{
video_init.IsEnabled = false;
}
}
/// <summary>
/// Helper function to enable or disable video related buttons (TakePhoto, Start Video Record)
/// </summary>
/// <param name="action">enum Action</param>
private void SetVideoButtonVisibility(Action action)
{
if (action == Action.ENABLE)
{
takePhoto.IsEnabled = true;
takePhoto.Visibility = Visibility.Visible;
}
else
{
takePhoto.IsEnabled = false;
takePhoto.Visibility = Visibility.Collapsed;
}
}
public async Task InitDevices()
{
// Finds all video capture devices
DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);
mediaCaptureArray[0] = new MediaCapture();
var mediaInitSettings = new MediaCaptureInitializationSettings { VideoDeviceId = devices[0].Id };
await mediaCaptureArray[0].InitializeAsync(mediaInitSettings);
var selectedPreviewResolution = mediaCaptureArray[0].VideoDeviceController.GetAvailableMediaStreamProperties(MediaStreamType.VideoPreview).ElementAt(4);
await mediaCaptureArray[0].VideoDeviceController.SetMediaStreamPropertiesAsync(MediaStreamType.VideoPreview, selectedPreviewResolution);
// Set callbacks for failure and recording limit exceeded
WriteLog("Device " + 0 + " successfully initialized!");
mediaCaptureArray[0].Failed += new MediaCaptureFailedEventHandler(mediaCapture_Failed);
mediaCaptureArray[0].RecordLimitationExceeded += new Windows.Media.Capture.RecordLimitationExceededEventHandler(mediaCapture_RecordLimitExceeded);
// Start Preview
previewElement.Source = mediaCaptureArray[0];
await mediaCaptureArray[0].StartPreviewAsync();
isPreviewingArray[0] = true;
///////////////////////////////////////////////////////////////////////////////////
mediaCaptureArray[1] = new MediaCapture();
var mediaInitSettings2 = new MediaCaptureInitializationSettings { VideoDeviceId = devices[1].Id };
await mediaCaptureArray[1].InitializeAsync(mediaInitSettings2);
var selectedPreviewResolution2 = mediaCaptureArray[1].VideoDeviceController.GetAvailableMediaStreamProperties(MediaStreamType.VideoPreview).ElementAt(4);
await mediaCaptureArray[1].VideoDeviceController.SetMediaStreamPropertiesAsync(MediaStreamType.VideoPreview, selectedPreviewResolution2);
// Set callbacks for failure and recording limit exceeded
WriteLog("Device " + 1 + " successfully initialized!");
mediaCaptureArray[1].Failed += new MediaCaptureFailedEventHandler(mediaCapture_Failed);
mediaCaptureArray[1].RecordLimitationExceeded += new Windows.Media.Capture.RecordLimitationExceededEventHandler(mediaCapture_RecordLimitExceeded);
// Start Preview
previewElement2.Source = mediaCaptureArray[1];
await mediaCaptureArray[1].StartPreviewAsync();
isPreviewingArray[1] = true;
}
#endregion
public MainPage()
{
this.InitializeComponent();
cameraImageArray[0] = captureImage;
cameraImageArray[1] = captureImage2;
SetInitButtonVisibility(Action.ENABLE);
SetVideoButtonVisibility(Action.DISABLE);
isPreviewingArray[0] = false;
isPreviewingArray[1] = false;
}
private async void Cleanup()
{
if (mediaCaptureArray[0] != null)
{
if (isPreviewingArray[0])
{
await mediaCaptureArray[0].StopPreviewAsync();
cameraImageArray[0].Source = null;
isPreviewingArray[0] = false;
}
mediaCaptureArray[0].Dispose();
mediaCaptureArray[0] = null;
}
if (mediaCaptureArray[1] != null)
{
if (isPreviewingArray[1])
{
await mediaCaptureArray[1].StopPreviewAsync();
cameraImageArray[1].Source = null;
isPreviewingArray[1] = false;
}
mediaCaptureArray[1].Dispose();
mediaCaptureArray[1] = null;
}
SetInitButtonVisibility(Action.ENABLE);
}
/// <summary>
/// 'Initialize Audio and Video' button action function
/// Dispose existing MediaCapture object and set it up for audio and video
/// Enable or disable appropriate buttons
/// - DISABLE 'Initialize Camera'
/// - ENABLE 'Take Photo'
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private async void initVideo_Click(object sender, RoutedEventArgs e)
{
// Disable all buttons until initialization completes
SetInitButtonVisibility(Action.DISABLE);
SetVideoButtonVisibility(Action.DISABLE);
await App.container.CreateIfNotExistsAsync();
try
{
Cleanup();
WriteLog("Initializing camera to capture audio and video...");
await InitDevices();
WriteLog("Camera preview succeeded!");
// Enable buttons for video and photo capture
SetVideoButtonVisibility(Action.ENABLE);
}
catch (Exception ex)
{
WriteLog("Unable to initialize camera: " + ex.Message);
}
}
private void cleanup_Click(object sender, RoutedEventArgs e)
{
SetInitButtonVisibility(Action.DISABLE);
SetVideoButtonVisibility(Action.DISABLE);
Cleanup();
}
private string buildDateTimeStamp()
{
StringBuilder sb = new StringBuilder();
DateTime currentDate = DateTime.Now;
sb.Append(currentDate.Year.ToString());
if (currentDate.Month.ToString().Length == 1)
{
sb.Append("0" + currentDate.Month.ToString());
}
else
{
sb.Append(currentDate.Month.ToString());
}
if (currentDate.Day.ToString().Length == 1)
{
sb.Append("0" + currentDate.Day.ToString());
}
else
{
sb.Append(currentDate.Day.ToString());
}
if (currentDate.Hour.ToString().Length == 1)
{
sb.Append("0" + currentDate.Hour.ToString());
}
else
{
sb.Append(currentDate.Hour.ToString());
}
if (currentDate.Minute.ToString().Length == 1)
{
sb.Append("0" + currentDate.Minute.ToString());
}
else
{
sb.Append(currentDate.Minute.ToString());
}
if (currentDate.Second.ToString().Length == 1)
{
sb.Append("0" + currentDate.Second.ToString());
}
else
{
sb.Append(currentDate.Second.ToString());
}
sb.Append("-");
sb.Append(currentDate.Millisecond.ToString());
return sb.ToString();
}
/// <summary>
/// 'Take Photo' button click action function
/// Capture image to a file in the default account photos folder
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void takePhoto_Click(object sender, RoutedEventArgs e)
{
try
{
takePhoto.IsEnabled = false;
ImageEncodingProperties imageProperties = ImageEncodingProperties.CreateJpeg();
Parallel.ForEach(indexArray, async (currentIndex) =>
{
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.High, async () =>
{
await mediaCaptureArray[currentIndex].StopPreviewAsync();
cameraImageArray[currentIndex].Source = null;
string PHOTO_FILE_NAME = this.buildDateTimeStamp() + ".jpg";
WriteLog("Device " + currentIndex + " started capturing photo");
StorageFile photoFile = await KnownFolders.PicturesLibrary.CreateFileAsync(
PHOTO_FILE_NAME, CreationCollisionOption.ReplaceExisting);
await mediaCaptureArray[currentIndex].CapturePhotoToStorageFileAsync(imageProperties, photoFile);
WriteLog("Device " + currentIndex + " took photo succesfully: " + photoFile.Path);
IRandomAccessStream photoStream = await photoFile.OpenReadAsync();
BitmapImage bitmap = new BitmapImage();
bitmap.SetSource(photoStream);
cameraImageArray[currentIndex].Source = bitmap;
await mediaCaptureArray[currentIndex].StartPreviewAsync();
WriteLog("Device " + currentIndex + " started upload");
CloudBlockBlob blockBlob = App.container.GetBlockBlobReference(PHOTO_FILE_NAME);
await blockBlob.DeleteIfExistsAsync();
await blockBlob.UploadFromFileAsync(photoFile);
WriteLog("Device " + currentIndex + " finished upload successfully!");
});
});
takePhoto.IsEnabled = true;
}
catch (Exception ex)
{
WriteLog(ex.Message);
Cleanup();
}
finally
{
takePhoto.IsEnabled = true;
}
}
/// <summary>
/// Callback function for any failures in MediaCapture operations
/// </summary>
/// <param name="currentCaptureObject"></param>
/// <param name="currentFailure"></param>
private async void mediaCapture_Failed(MediaCapture currentCaptureObject, MediaCaptureFailedEventArgs currentFailure)
{
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
SetInitButtonVisibility(Action.DISABLE);
SetVideoButtonVisibility(Action.DISABLE);
WriteLog("Check if camera is diconnected. Try re-launching the app");
});
}
/// <summary>
/// Callback function if Recording Limit Exceeded
/// </summary>
/// <param name="currentCaptureObject"></param>
public void mediaCapture_RecordLimitExceeded(Windows.Media.Capture.MediaCapture currentCaptureObject)
{
try
{
//TODO: handle record limit exceeded error
}
catch (Exception ex)
{
WriteLog(ex.Message);
}
}
}
}