-
Notifications
You must be signed in to change notification settings - Fork 2
/
Sample_Single.cs
1837 lines (1605 loc) · 58.4 KB
/
Sample_Single.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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.Text;
namespace com.samsung.android.sdk.camera.sample.cases
{
using Activity = android.app.Activity;
using AlertDialog = android.app.AlertDialog;
using DialogInterface = android.content.DialogInterface;
using Configuration = android.content.res.Configuration;
using ImageFormat = android.graphics.ImageFormat;
using Matrix = android.graphics.Matrix;
using PixelFormat = android.graphics.PixelFormat;
using Point = android.graphics.Point;
using Rect = android.graphics.Rect;
using RectF = android.graphics.RectF;
using SurfaceTexture = android.graphics.SurfaceTexture;
using CameraAccessException = android.hardware.camera2.CameraAccessException;
using BlackLevelPattern = android.hardware.camera2.@params.BlackLevelPattern;
using Face = android.hardware.camera2.@params.Face;
using MeteringRectangle = android.hardware.camera2.@params.MeteringRectangle;
using StreamConfigurationMap = android.hardware.camera2.@params.StreamConfigurationMap;
using ExifInterface = android.media.ExifInterface;
using Image = android.media.Image;
using ImageReader = android.media.ImageReader;
using MediaScannerConnection = android.media.MediaScannerConnection;
using Uri = android.net.Uri;
using Build = android.os.Build;
using Bundle = android.os.Bundle;
using Environment = android.os.Environment;
using Handler = android.os.Handler;
using HandlerThread = android.os.HandlerThread;
using Looper = android.os.Looper;
using DateFormat = android.text.format.DateFormat;
using Log = android.util.Log;
using Pair = android.util.Pair;
using Range = android.util.Range;
using Rational = android.util.Rational;
using Size = android.util.Size;
using SparseArray = android.util.SparseArray;
using SparseIntArray = android.util.SparseIntArray;
using OrientationEventListener = android.view.OrientationEventListener;
using Surface = android.view.Surface;
using TextureView = android.view.TextureView;
using View = android.view.View;
using WebView = android.webkit.WebView;
using Toast = android.widget.Toast;
using AutoFitTextureView = com.samsung.android.sdk.camera.sample.cases.util.AutoFitTextureView;
using FaceRectView = com.samsung.android.sdk.camera.sample.cases.util.FaceRectView;
using SettingDialog = com.samsung.android.sdk.camera.sample.cases.util.SettingDialog;
using SettingItem = com.samsung.android.sdk.camera.sample.cases.util.SettingItem;
public class Sample_Single : Activity, SettingDialog.OnCameraSettingUpdatedListener
{
private bool InstanceFieldsInitialized = false;
public Sample_Single()
{
if (!InstanceFieldsInitialized)
{
InitializeInstanceFields();
InstanceFieldsInitialized = true;
}
}
private void InitializeInstanceFields()
{
mImageSaver = new ImageSaver(this, this);
}
/// <summary>
/// Tag for the <seealso cref="Log"/>.
/// </summary>
private const string TAG = "Sample_Single";
private SCamera mSCamera;
private SCameraManager mSCameraManager;
private SCameraDevice mSCameraDevice;
private SCameraCaptureSession mSCameraSession;
private SCameraCharacteristics mCharacteristics;
private SCaptureRequest.Builder mPreviewBuilder;
private SCaptureRequest.Builder mCaptureBuilder;
/// <summary>
/// Current Preview Size.
/// </summary>
private Size mPreviewSize;
/// <summary>
/// ID of the current <seealso cref="com.samsung.android.sdk.camera.SCameraDevice"/>.
/// </summary>
private string mCameraId;
/// <summary>
/// Lens facing. Camera with this facing will be opened
/// </summary>
private int mLensFacing;
private IList<int?> mLensFacingList;
/// <summary>
/// Image saving format.
/// </summary>
private int mImageFormat;
private IList<int?> mImageFormatList;
/// <summary>
/// A <seealso cref="com.samsung.android.sdk.camera.sample.cases.util.SettingDialog"/> for camera setting UI.
/// </summary>
private SettingDialog mSettingDialog;
/// <summary>
/// An <seealso cref="com.samsung.android.sdk.camera.sample.cases.util.AutoFitTextureView"/> for camera preview.
/// </summary>
private AutoFitTextureView mTextureView;
/// <summary>
/// A <seealso cref="com.samsung.android.sdk.camera.sample.cases.util.FaceRectView"/> for face detection UI.
/// </summary>
private FaceRectView mFaceRectView;
private ImageReader mJpegReader;
private ImageReader mRawReader;
private ImageSaver mImageSaver;
/// <summary>
/// A camera related listener/callback will be posted in this handler.
/// </summary>
private Handler mBackgroundHandler;
private HandlerThread mBackgroundHandlerThread;
/// <summary>
/// A image saving worker Runnable will be posted to this handler.
/// </summary>
private Handler mImageSavingHandler;
private HandlerThread mImageSavingHandlerThread;
private BlockingQueue<SCaptureResult> mCaptureResultQueue;
/// <summary>
/// An orientation listener for jpeg orientation
/// </summary>
private OrientationEventListener mOrientationListener;
private int mLastOrientation = 0;
private Semaphore mCameraOpenCloseLock = new Semaphore(1);
/// <summary>
/// True if <seealso cref="com.samsung.android.sdk.camera.SCaptureRequest#CONTROL_AF_TRIGGER"/> is triggered.
/// </summary>
private bool isAFTriggered;
/// <summary>
/// True if <seealso cref="com.samsung.android.sdk.camera.SCaptureRequest#CONTROL_AE_PRECAPTURE_TRIGGER"/> is triggered.
/// </summary>
private bool isAETriggered;
/// <summary>
/// Current app state.
/// </summary>
private CAMERA_STATE mState = CAMERA_STATE.IDLE;
/// <summary>
/// Maximum preview width app will use.
/// </summary>
private const int MAX_PREVIEW_WIDTH = 1920;
/// <summary>
/// Maximum preview height app will use.
/// </summary>
private const int MAX_PREVIEW_HEIGHT = 1080;
/// <summary>
/// Conversion from device rotation to DNG orientation
/// </summary>
private static readonly SparseIntArray DNG_ORIENTATION = new SparseIntArray();
static Sample_Single()
{
DNG_ORIENTATION.append(0, ExifInterface.ORIENTATION_NORMAL);
DNG_ORIENTATION.append(90, ExifInterface.ORIENTATION_ROTATE_90);
DNG_ORIENTATION.append(180, ExifInterface.ORIENTATION_ROTATE_180);
DNG_ORIENTATION.append(270, ExifInterface.ORIENTATION_ROTATE_270);
}
public virtual void onCameraSettingUpdated(int key, int value)
{
switch (key)
{
case SettingItem.SETTING_TYPE_REQUEST_KEY:
if (State == CAMERA_STATE.PREVIEW)
{
startPreview();
}
break;
case SettingItem.SETTING_TYPE_CAMERA_FACING:
if (mLensFacing != value)
{
mLensFacing = value;
closeCamera();
State = CAMERA_STATE.IDLE;
openCamera(mLensFacing);
}
break;
case SettingItem.SETTING_TYPE_IMAGE_FORMAT:
if (mImageFormat != value)
{
mImageFormat = value;
}
break;
}
}
private enum CAMERA_STATE
{
IDLE,
PREVIEW,
WAIT_AF,
WAIT_AE,
TAKE_PICTURE,
CLOSING
}
private CAMERA_STATE State
{
set
{
lock (this)
{
mState = value;
}
}
get
{
return mState;
}
}
/// <summary>
/// A <seealso cref="com.samsung.android.sdk.camera.SCameraCaptureSession.CaptureCallback"/> for <seealso cref="com.samsung.android.sdk.camera.SCameraCaptureSession#setRepeatingRequest(com.samsung.android.sdk.camera.SCaptureRequest, com.samsung.android.sdk.camera.SCameraCaptureSession.CaptureCallback, android.os.Handler)"/>
/// </summary>
private SCameraCaptureSession.CaptureCallback mSessionCaptureCallback = new CaptureCallbackAnonymousInnerClassHelper();
private class CaptureCallbackAnonymousInnerClassHelper : SCameraCaptureSession.CaptureCallback
{
public CaptureCallbackAnonymousInnerClassHelper()
{
}
public override void onCaptureCompleted(SCameraCaptureSession session, SCaptureRequest request, STotalCaptureResult result)
{
// Remove comment, if you want to check request/result from console log.
// dumpCaptureResultToLog(result);
// dumpCaptureRequestToLog(request);
// Depends on the current state and capture result, app will take next action.
switch (outerInstance.State)
{
case IDLE:
case TAKE_PICTURE:
case CLOSING:
// do nothing
break;
case PREVIEW:
if (result.get(SCaptureResult.STATISTICS_FACES) != null)
{
outerInstance.processFace(result.get(SCaptureResult.STATISTICS_FACES), result.get(SCaptureResult.SCALER_CROP_REGION));
}
break;
// If AF is triggered and AF_STATE indicates AF process is finished, app will trigger AE pre-capture.
case WAIT_AF:
{
if (outerInstance.isAFTriggered)
{
int afState = result.get(SCaptureResult.CONTROL_AF_STATE);
// Check if AF is finished.
if (SCaptureResult.CONTROL_AF_STATE_FOCUSED_LOCKED == afState || SCaptureResult.CONTROL_AF_STATE_NOT_FOCUSED_LOCKED == afState)
{
// If AE mode is off or device is legacy device then skip AE pre-capture.
if (result.get(SCaptureResult.CONTROL_AE_MODE) != SCaptureResult.CONTROL_AE_MODE_OFF && outerInstance.mCharacteristics.get(SCameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL) != SCameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY)
{
outerInstance.triggerAE();
}
else
{
outerInstance.takePicture();
}
outerInstance.isAFTriggered = false;
}
}
break;
}
// If AE is triggered and AE_STATE indicates AE pre-capture process is finished, app will take a picture.
case WAIT_AE:
{
if (outerInstance.isAETriggered)
{
int? aeState = result.get(SCaptureResult.CONTROL_AE_STATE);
if (null == aeState || SCaptureResult.CONTROL_AE_STATE_CONVERGED == aeState || SCaptureResult.CONTROL_AE_STATE_FLASH_REQUIRED == aeState || SCaptureResult.CONTROL_AE_STATE_LOCKED == aeState)
{ // Legacy device might have null AE_STATE. However, this should not be happened as we skip triggerAE() for legacy device
outerInstance.takePicture();
outerInstance.isAETriggered = false;
}
}
break;
}
}
}
}
/// <summary>
/// A <seealso cref="android.media.ImageReader.OnImageAvailableListener"/> for still capture.
/// </summary>
private ImageReader.OnImageAvailableListener mImageCallback = new OnImageAvailableListenerAnonymousInnerClassHelper();
private class OnImageAvailableListenerAnonymousInnerClassHelper : ImageReader.OnImageAvailableListener
{
public OnImageAvailableListenerAnonymousInnerClassHelper()
{
}
public override void onImageAvailable(ImageReader reader)
{
if (outerInstance.mImageFormat == ImageFormat.JPEG)
{
outerInstance.mImageSaver.save(reader.acquireNextImage(), outerInstance.createFileName() + ".jpg");
}
else
{
outerInstance.mImageSaver.save(reader.acquireNextImage(), outerInstance.createFileName() + ".dng");
}
}
}
protected internal override void onCreate(Bundle savedInstanceState)
{
base.onCreate(savedInstanceState);
ContentView = R.layout.activity_single;
}
public override void onResume()
{
base.onResume();
State = CAMERA_STATE.IDLE;
startBackgroundThread();
// initialize SCamera
mSCamera = new SCamera();
try
{
mSCamera.initialize(this);
}
catch (SsdkUnsupportedException)
{
showAlertDialog("Fail to initialize SCamera.", true);
return;
}
mCaptureResultQueue = new LinkedBlockingQueue<SCaptureResult>();
OrientationListener = true;
createUI();
checkRequiredFeatures();
openCamera(mLensFacing);
}
public override void onPause()
{
State = CAMERA_STATE.CLOSING;
if (mSettingDialog != null)
{
mSettingDialog.dismiss();
mSettingDialog = null;
}
OrientationListener = false;
stopBackgroundThread();
closeCamera();
mSCamera = null;
base.onPause();
}
/// <summary>
/// Prepares an UI, like button, dialog, etc.
/// </summary>
private void createUI()
{
mSettingDialog = new SettingDialog(this);
mSettingDialog.OnCaptureRequestUpdatedListener = this;
findViewById(R.id.picture).OnClickListener = new OnClickListenerAnonymousInnerClassHelper(this);
findViewById(R.id.setting).setOnClickListener(new OnClickListenerAnonymousInnerClassHelper2(this));
findViewById(R.id.info).OnClickListener = new OnClickListenerAnonymousInnerClassHelper3(this);
mTextureView = (AutoFitTextureView) findViewById(R.id.texture);
mFaceRectView = (FaceRectView) findViewById(R.id.face);
// Set SurfaceTextureListener that handle life cycle of TextureView
mTextureView.SurfaceTextureListener = new SurfaceTextureListenerAnonymousInnerClassHelper(this);
}
private class OnClickListenerAnonymousInnerClassHelper : View.OnClickListener
{
private readonly Sample_Single outerInstance;
public OnClickListenerAnonymousInnerClassHelper(Sample_Single outerInstance)
{
this.outerInstance = outerInstance;
}
public override void onClick(View v)
{
// take picture is only works under preview state.
if (outerInstance.State == CAMERA_STATE.PREVIEW)
{
// No AF lock is required for AF modes OFF/EDOF.
if (outerInstance.mPreviewBuilder.get(SCaptureRequest.CONTROL_AF_MODE) != SCaptureRequest.CONTROL_AF_MODE_OFF && outerInstance.mPreviewBuilder.get(SCaptureRequest.CONTROL_AF_MODE) != SCaptureRequest.CONTROL_AF_MODE_EDOF)
{
outerInstance.lockAF();
// No AE pre-capture is required for AE mode OFF or device is LEGACY.
}
else if (outerInstance.mPreviewBuilder.get(SCaptureRequest.CONTROL_AE_MODE) != SCaptureRequest.CONTROL_AE_MODE_OFF && outerInstance.mCharacteristics.get(SCameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL) != SCameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY)
{
outerInstance.triggerAE();
// If AE/AF is skipped, run still capture directly.
}
else
{
outerInstance.takePicture();
}
}
}
}
private class OnClickListenerAnonymousInnerClassHelper2 : View.OnClickListener
{
private readonly Sample_Single outerInstance;
public OnClickListenerAnonymousInnerClassHelper2(Sample_Single outerInstance)
{
this.outerInstance = outerInstance;
}
public override void onClick(View v)
{
if (outerInstance.State == CAMERA_STATE.PREVIEW)
{
outerInstance.mSettingDialog.show();
}
}
}
private class OnClickListenerAnonymousInnerClassHelper3 : View.OnClickListener
{
private readonly Sample_Single outerInstance;
public OnClickListenerAnonymousInnerClassHelper3(Sample_Single outerInstance)
{
this.outerInstance = outerInstance;
}
public override void onClick(View v)
{
outerInstance.showInformationDialog();
}
}
private class SurfaceTextureListenerAnonymousInnerClassHelper : TextureView.SurfaceTextureListener
{
private readonly Sample_Single outerInstance;
public SurfaceTextureListenerAnonymousInnerClassHelper(Sample_Single outerInstance)
{
this.outerInstance = outerInstance;
}
public override void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height)
{
// "onSurfaceTextureAvailable" is called, which means that SCameraCaptureSession is not created.
// We need to configure transform for TextureView and crate SCameraCaptureSession.
outerInstance.configureTransform(width, height);
outerInstance.createPreviewSession();
}
public override void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height)
{
// SurfaceTexture size changed, we need to configure transform for TextureView, again.
outerInstance.configureTransform(width, height);
}
public override bool onSurfaceTextureDestroyed(SurfaceTexture surface)
{
return true;
}
public override void onSurfaceTextureUpdated(SurfaceTexture surface)
{
}
}
/// <summary>
/// Closes a camera and release resources.
/// </summary>
private void closeCamera()
{
lock (this)
{
try
{
mCameraOpenCloseLock.acquire();
if (mSCameraSession != null)
{
mSCameraSession.close();
mSCameraSession = null;
}
if (mSCameraDevice != null)
{
mSCameraDevice.close();
mSCameraDevice = null;
}
if (mJpegReader != null)
{
mJpegReader.close();
mJpegReader = null;
}
if (mRawReader != null)
{
mRawReader.close();
mRawReader = null;
}
mSCameraManager = null;
}
catch (InterruptedException e)
{
Log.e(TAG, "Interrupted while trying to lock camera closing.", e);
}
finally
{
mCameraOpenCloseLock.release();
}
}
}
private void checkRequiredFeatures()
{
try
{
// Find available lens facing value for this device
ISet<int?> lensFacings = new HashSet<int?>();
foreach (string id in mSCamera.SCameraManager.CameraIdList)
{
SCameraCharacteristics cameraCharacteristics = mSCamera.SCameraManager.getCameraCharacteristics(id);
lensFacings.Add(cameraCharacteristics.get(SCameraCharacteristics.LENS_FACING));
}
mLensFacingList = new List<int?>(lensFacings);
mLensFacing = mLensFacingList[mLensFacingList.Count - 1].Value;
}
catch (CameraAccessException e)
{
showAlertDialog("Cannot access the camera.", true);
Log.e(TAG, "Cannot access the camera.", e);
}
}
/// <summary>
/// Opens a <seealso cref="com.samsung.android.sdk.camera.SCameraDevice"/>.
/// </summary>
private void openCamera(int facing)
{
lock (this)
{
try
{
if (!mCameraOpenCloseLock.tryAcquire(3000, TimeUnit.MILLISECONDS))
{
showAlertDialog("Time out waiting to lock camera opening.", true);
}
mSCameraManager = mSCamera.SCameraManager;
mCameraId = null;
// Find camera device that facing to given facing parameter.
foreach (string id in mSCamera.SCameraManager.CameraIdList)
{
SCameraCharacteristics cameraCharacteristics = mSCamera.SCameraManager.getCameraCharacteristics(id);
if (cameraCharacteristics.get(SCameraCharacteristics.LENS_FACING) == facing)
{
mCameraId = id;
break;
}
}
if (mCameraId == null)
{
showAlertDialog("No camera exist with given facing: " + facing, true);
return;
}
// acquires camera characteristics
mCharacteristics = mSCamera.SCameraManager.getCameraCharacteristics(mCameraId);
StreamConfigurationMap streamConfigurationMap = mCharacteristics.get(SCameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
// Acquires supported preview size list that supports SurfaceTexture
mPreviewSize = streamConfigurationMap.getOutputSizes(typeof(SurfaceTexture))[0];
foreach (Size option in streamConfigurationMap.getOutputSizes(typeof(SurfaceTexture)))
{
// Find maximum preview size that is not larger than MAX_PREVIEW_WIDTH/MAX_PREVIEW_HEIGHT
int areaCurrent = Math.Abs((mPreviewSize.Width * mPreviewSize.Height) - (MAX_PREVIEW_WIDTH * MAX_PREVIEW_HEIGHT));
int areaNext = Math.Abs((option.Width * option.Height) - (MAX_PREVIEW_WIDTH * MAX_PREVIEW_HEIGHT));
if (areaCurrent > areaNext)
{
mPreviewSize = option;
}
}
// Acquires supported size for JPEG format
Size[] jpegSizeList = null;
jpegSizeList = streamConfigurationMap.getOutputSizes(ImageFormat.JPEG);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && 0 == jpegSizeList.Length)
{
// If device has 'SCameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_BURST_CAPTURE' getOutputSizes can return zero size list
// for a format value in getOutputFormats.
jpegSizeList = streamConfigurationMap.getHighResolutionOutputSizes(ImageFormat.JPEG);
}
Size jpegSize = jpegSizeList[0];
// Configures an ImageReader
mJpegReader = ImageReader.newInstance(jpegSize.Width, jpegSize.Height, ImageFormat.JPEG, 1);
mJpegReader.setOnImageAvailableListener(mImageCallback, mImageSavingHandler);
if (contains(mCharacteristics.get(SCameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES), SCameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_RAW))
{
Size[] rawSizeList = streamConfigurationMap.getOutputSizes(ImageFormat.RAW_SENSOR);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && 0 == rawSizeList.Length)
{
rawSizeList = streamConfigurationMap.getHighResolutionOutputSizes(ImageFormat.RAW_SENSOR);
}
Size rawSize = rawSizeList[0];
mRawReader = ImageReader.newInstance(rawSize.Width, rawSize.Height, ImageFormat.RAW_SENSOR, 1);
mRawReader.setOnImageAvailableListener(mImageCallback, mImageSavingHandler);
mImageFormatList = Arrays.asList(ImageFormat.JPEG, ImageFormat.RAW_SENSOR);
}
else
{
if (mRawReader != null)
{
mRawReader.close();
mRawReader = null;
}
mImageFormatList = Arrays.asList(ImageFormat.JPEG);
}
mImageFormat = ImageFormat.JPEG;
// Set the aspect ratio to TextureView
int orientation = Resources.Configuration.orientation;
if (orientation == Configuration.ORIENTATION_LANDSCAPE)
{
mTextureView.setAspectRatio(mPreviewSize.Width, mPreviewSize.Height);
mFaceRectView.setAspectRatio(mPreviewSize.Width, mPreviewSize.Height);
}
else
{
mTextureView.setAspectRatio(mPreviewSize.Height, mPreviewSize.Width);
mFaceRectView.setAspectRatio(mPreviewSize.Height, mPreviewSize.Width);
}
// calculate transform matrix for face rect view
configureFaceRectTransform();
// Opening the camera device here
mSCameraManager.openCamera(mCameraId, new StateCallbackAnonymousInnerClassHelper(this), mBackgroundHandler);
}
catch (CameraAccessException e)
{
showAlertDialog("Cannot open the camera.", true);
Log.e(TAG, "Cannot open the camera.", e);
}
catch (InterruptedException e)
{
throw new Exception("Interrupted while trying to lock camera opening.", e);
}
}
}
private class StateCallbackAnonymousInnerClassHelper : SCameraDevice.StateCallback
{
private readonly Sample_Single outerInstance;
public StateCallbackAnonymousInnerClassHelper(Sample_Single outerInstance)
{
this.outerInstance = outerInstance;
}
public virtual void onOpened(SCameraDevice sCameraDevice)
{
outerInstance.mCameraOpenCloseLock.release();
if (outerInstance.State == CAMERA_STATE.CLOSING)
{
return;
}
outerInstance.mSettingDialog.dismiss();
outerInstance.mSCameraDevice = sCameraDevice;
outerInstance.createPreviewSession();
}
public override void onDisconnected(SCameraDevice sCameraDevice)
{
outerInstance.mCameraOpenCloseLock.release();
if (outerInstance.State == CAMERA_STATE.CLOSING)
{
return;
}
outerInstance.showAlertDialog("Camera disconnected.", true);
}
public override void onError(SCameraDevice sCameraDevice, int i)
{
outerInstance.mCameraOpenCloseLock.release();
if (outerInstance.State == CAMERA_STATE.CLOSING)
{
return;
}
outerInstance.showAlertDialog("Error while camera open.", true);
}
}
/// <summary>
/// Create a <seealso cref="com.samsung.android.sdk.camera.SCameraCaptureSession"/> for preview.
/// </summary>
private void createPreviewSession()
{
lock (this)
{
if (null == mSCamera || null == mSCameraDevice || null == mSCameraManager || null == mPreviewSize || !mTextureView.Available)
{
return;
}
try
{
SurfaceTexture texture = mTextureView.SurfaceTexture;
// Set default buffer size to camera preview size.
texture.setDefaultBufferSize(mPreviewSize.Width, mPreviewSize.Height);
Surface surface = new Surface(texture);
// Creates SCaptureRequest.Builder for preview with output target.
mPreviewBuilder = mSCameraDevice.createCaptureRequest(SCameraDevice.TEMPLATE_PREVIEW);
mPreviewBuilder.addTarget(surface);
// Creates SCaptureRequest.Builder for still capture with output target.
mCaptureBuilder = mSCameraDevice.createCaptureRequest(SCameraDevice.TEMPLATE_STILL_CAPTURE);
// Setup SettingDialog. SettingDialog will add setting item depends on camera characteristics.
// and updates builders as setting value changes.
runOnUiThread(() =>
{
mSettingDialog.configure(mCharacteristics, mLensFacing, mLensFacingList, mImageFormat, mImageFormatList, mPreviewBuilder, mCaptureBuilder);
});
// Creates a SCameraCaptureSession here.
IList<Surface> outputSurface = new List<Surface>();
outputSurface.Add(surface);
outputSurface.Add(mJpegReader.Surface);
if (mRawReader != null)
{
outputSurface.Add(mRawReader.Surface);
}
mSCameraDevice.createCaptureSession(outputSurface, new StateCallbackAnonymousInnerClassHelper(this), mBackgroundHandler);
}
catch (CameraAccessException)
{
showAlertDialog("Fail to create camera capture session.", true);
}
}
}
private class StateCallbackAnonymousInnerClassHelper : SCameraCaptureSession.StateCallback
{
private readonly Sample_Single outerInstance;
public StateCallbackAnonymousInnerClassHelper(Sample_Single outerInstance)
{
this.outerInstance = outerInstance;
}
public override void onConfigured(SCameraCaptureSession sCameraCaptureSession)
{
if (outerInstance.State == CAMERA_STATE.CLOSING)
{
return;
}
outerInstance.mSCameraSession = sCameraCaptureSession;
outerInstance.startPreview();
}
public override void onConfigureFailed(SCameraCaptureSession sCameraCaptureSession)
{
if (outerInstance.State == CAMERA_STATE.CLOSING)
{
return;
}
outerInstance.showAlertDialog("Fail to create camera capture session.", true);
outerInstance.State = CAMERA_STATE.IDLE;
}
}
/// <summary>
/// Starts a preview.
/// </summary>
private void startPreview()
{
lock (this)
{
if (mSCameraSession == null)
{
return;
}
try
{
// Starts displaying the preview.
mSCameraSession.setRepeatingRequest(mPreviewBuilder.build(), mSessionCaptureCallback, mBackgroundHandler);
State = CAMERA_STATE.PREVIEW;
}
catch (CameraAccessException)
{
showAlertDialog("Fail to start preview.", true);
}
}
}
/// <summary>
/// Starts AF process by triggering <seealso cref="com.samsung.android.sdk.camera.SCaptureRequest#CONTROL_AF_TRIGGER_START"/>.
/// </summary>
private void lockAF()
{
try
{
State = CAMERA_STATE.WAIT_AF;
isAFTriggered = false;
// Set AF trigger to SCaptureRequest.Builder
mPreviewBuilder.set(SCaptureRequest.CONTROL_AF_TRIGGER, SCaptureRequest.CONTROL_AF_TRIGGER_START);
// App should send AF triggered request for only a single capture.
mSCameraSession.capture(mPreviewBuilder.build(), new CaptureCallbackAnonymousInnerClassHelper2(this), mBackgroundHandler);
mPreviewBuilder.set(SCaptureRequest.CONTROL_AF_TRIGGER, SCaptureRequest.CONTROL_AF_TRIGGER_IDLE);
}
catch (CameraAccessException)
{
showAlertDialog("Fail to trigger AF", true);
}
}
private class CaptureCallbackAnonymousInnerClassHelper2 : SCameraCaptureSession.CaptureCallback
{
private readonly Sample_Single outerInstance;
public CaptureCallbackAnonymousInnerClassHelper2(Sample_Single outerInstance)
{
this.outerInstance = outerInstance;
}
public override void onCaptureCompleted(SCameraCaptureSession session, SCaptureRequest request, STotalCaptureResult result)
{
outerInstance.isAFTriggered = true;
}
}
/// <summary>
/// Unlock AF.
/// </summary>
private void unlockAF()
{
// If we send TRIGGER_CANCEL. Lens move to its default position. This results in bad user experience.
if (mPreviewBuilder.get(SCaptureRequest.CONTROL_AF_MODE) == SCaptureRequest.CONTROL_AF_MODE_AUTO || mPreviewBuilder.get(SCaptureRequest.CONTROL_AF_MODE) == SCaptureRequest.CONTROL_AF_MODE_MACRO)
{
State = CAMERA_STATE.PREVIEW;
return;
}
// Triggers CONTROL_AF_TRIGGER_CANCEL to return to initial AF state.
try
{
mPreviewBuilder.set(SCaptureRequest.CONTROL_AF_TRIGGER, SCaptureRequest.CONTROL_AF_TRIGGER_CANCEL);
mSCameraSession.capture(mPreviewBuilder.build(), new CaptureCallbackAnonymousInnerClassHelper3(this), mBackgroundHandler);
mPreviewBuilder.set(SCaptureRequest.CONTROL_AF_TRIGGER, SCaptureRequest.CONTROL_AF_TRIGGER_IDLE);
}
catch (CameraAccessException)
{
showAlertDialog("Fail to cancel AF", false);
}
}
private class CaptureCallbackAnonymousInnerClassHelper3 : SCameraCaptureSession.CaptureCallback
{
private readonly Sample_Single outerInstance;
public CaptureCallbackAnonymousInnerClassHelper3(Sample_Single outerInstance)
{
this.outerInstance = outerInstance;
}
public override void onCaptureCompleted(SCameraCaptureSession session, SCaptureRequest request, STotalCaptureResult result)
{
if (outerInstance.State == CAMERA_STATE.CLOSING)
{
return;
}
outerInstance.State = CAMERA_STATE.PREVIEW;
}
}
/// <summary>
/// Starts AE pre-capture
/// </summary>
private void triggerAE()
{
try
{
State = CAMERA_STATE.WAIT_AE;
isAETriggered = false;
mPreviewBuilder.set(SCaptureRequest.CONTROL_AE_PRECAPTURE_TRIGGER, SCaptureRequest.CONTROL_AE_PRECAPTURE_TRIGGER_START);
// App should send AE triggered request for only a single capture.
mSCameraSession.capture(mPreviewBuilder.build(), new CaptureCallbackAnonymousInnerClassHelper4(this), mBackgroundHandler);
mPreviewBuilder.set(SCaptureRequest.CONTROL_AE_PRECAPTURE_TRIGGER, SCaptureRequest.CONTROL_AE_PRECAPTURE_TRIGGER_IDLE);
}
catch (CameraAccessException)
{
showAlertDialog("Fail to trigger AE", true);
}
}
private class CaptureCallbackAnonymousInnerClassHelper4 : SCameraCaptureSession.CaptureCallback
{
private readonly Sample_Single outerInstance;
public CaptureCallbackAnonymousInnerClassHelper4(Sample_Single outerInstance)
{
this.outerInstance = outerInstance;
}
public override void onCaptureCompleted(SCameraCaptureSession session, SCaptureRequest request, STotalCaptureResult result)
{
outerInstance.isAETriggered = true;
}
}
/// <summary>
/// Take picture.
/// </summary>
private void takePicture()
{
if (State == CAMERA_STATE.CLOSING)
{
return;
}
try
{
// Sets orientation
mCaptureBuilder.set(SCaptureRequest.JPEG_ORIENTATION, JpegOrientation);
if (mImageFormat == ImageFormat.JPEG)
{
mCaptureBuilder.addTarget(mJpegReader.Surface);
}
else