/
Sample_DOF.cs
1514 lines (1282 loc) · 44.3 KB
/
Sample_DOF.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 Bitmap = android.graphics.Bitmap;
using BitmapFactory = android.graphics.BitmapFactory;
using ImageFormat = android.graphics.ImageFormat;
using Matrix = android.graphics.Matrix;
using RectF = android.graphics.RectF;
using SurfaceTexture = android.graphics.SurfaceTexture;
using CameraAccessException = android.hardware.camera2.CameraAccessException;
using StreamConfigurationMap = android.hardware.camera2.@params.StreamConfigurationMap;
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 DateFormat = android.text.format.DateFormat;
using Log = android.util.Log;
using Size = android.util.Size;
using OrientationEventListener = android.view.OrientationEventListener;
using Surface = android.view.Surface;
using TextureView = android.view.TextureView;
using View = android.view.View;
using Button = android.widget.Button;
using ImageView = android.widget.ImageView;
using Toast = android.widget.Toast;
using SCameraDepthOfFieldProcessor = com.samsung.android.sdk.camera.processor.SCameraDepthOfFieldProcessor;
using SCameraProcessorManager = com.samsung.android.sdk.camera.processor.SCameraProcessorManager;
using SCameraProcessorParameter = com.samsung.android.sdk.camera.processor.SCameraProcessorParameter;
using AutoFitTextureView = com.samsung.android.sdk.camera.sample.cases.util.AutoFitTextureView;
public class Sample_DOF : Activity
{
private bool InstanceFieldsInitialized = false;
public Sample_DOF()
{
if (!InstanceFieldsInitialized)
{
InitializeInstanceFields();
InstanceFieldsInitialized = true;
}
}
private void InitializeInstanceFields()
{
mImageSaver = new ImageSaver(this, this);
mSessionCaptureCallback = new DofSessionCaptureCallback(this, this);
mDofCaptureCallback = new DofCaptureCallback(this, this);
}
/// <summary>
/// Tag for the <seealso cref="Log"/>.
/// </summary>
private const string TAG = "Sample_DOF";
private SCamera mSCamera;
private SCameraManager mSCameraManager;
private SCameraDevice mSCameraDevice;
private SCameraCaptureSession mSCameraSession;
private SCaptureRequest.Builder mPreviewBuilder;
private SCaptureRequest.Builder mCaptureBuilder;
/// <summary>
/// ID of the current <seealso cref="com.samsung.android.sdk.camera.SCameraDevice"/>.
/// </summary>
private string mCameraId;
private SCameraCharacteristics mCharacteristics;
/// <summary>
/// Depth of field processor
/// </summary>
private SCameraDepthOfFieldProcessor mProcessor;
/// <summary>
/// An <seealso cref="com.samsung.android.sdk.camera.sample.cases.util.AutoFitTextureView"/> for camera preview.
/// </summary>
private AutoFitTextureView mTextureView;
private ImageReader mImageReader;
private ImageSaver mImageSaver;
/// <summary>
/// Input image list to produce depth of field image
/// </summary>
private IList<Image> mInputImageList = new List<Image>();
private Size mPreviewSize;
/// <summary>
/// A camera related listener/callback will be posted in this handler.
/// </summary>
private Handler mBackgroundHandler;
private HandlerThread mBackgroundHandlerThread;
/// <summary>
/// An orientation listener for jpeg orientation
/// </summary>
private OrientationEventListener mOrientationListener;
private int mLastOrientation = 0;
private Semaphore mCameraOpenCloseLock = new Semaphore(1);
/// <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>
/// Number of input images to produce depth of field image from device
/// </summary>
private int mDeviceDofInputCnt = 0;
private int mReceivedImgCnt = 0;
/// <summary>
/// distance value of infinity focus
/// </summary>
private const float INFINITY_FOCUS_DISTANCE = 0.0f;
private const sbyte IDX_AUTO_FOCUS_IMG = 0;
private const sbyte IDX_INFINITY_FOCUS_IMG = 1;
private enum CAMERA_STATE
{
IDLE,
PREVIEW,
TAKE_DOF_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 class DofSessionCaptureCallback : SCameraCaptureSession.CaptureCallback
{
private readonly Sample_DOF outerInstance;
public DofSessionCaptureCallback(Sample_DOF outerInstance)
{
this.outerInstance = outerInstance;
}
internal CaptureHelper mResultListener = null;
public virtual CaptureHelper ResultListener
{
set
{
mResultListener = value;
}
}
public override void onCaptureCompleted(SCameraCaptureSession session, SCaptureRequest request, STotalCaptureResult result)
{
// Depends on the current state and capture result, app will take next action.
switch (outerInstance.State)
{
case IDLE:
case PREVIEW:
case CLOSING:
// do nothing
break;
case TAKE_DOF_PICTURE:
if (mResultListener != null)
{
mResultListener.checkPresetResult(result);
}
break;
}
}
}
private DofSessionCaptureCallback mSessionCaptureCallback;
/// <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.State == CAMERA_STATE.CLOSING)
{
return;
}
outerInstance.mReceivedImgCnt++;
Image image = reader.acquireNextImage();
outerInstance.mInputImageList.Add(image);
// if we received enough images to produce depth of field image, request process to depth of field processor.
if (outerInstance.mReceivedImgCnt == outerInstance.mDeviceDofInputCnt)
{
outerInstance.mReceivedImgCnt = 0;
outerInstance.mProcessor.requestMultiProcess(outerInstance.mInputImageList);
}
}
}
private Bitmap decodeToBitmap(ByteBuffer jpegData, int sampleSize)
{
sbyte[] jpegDataArray = new sbyte[jpegData.remaining()];
jpegData.get(jpegDataArray);
jpegData.rewind();
BitmapFactory.Options option = new BitmapFactory.Options();
option.inSampleSize = sampleSize;
return BitmapFactory.decodeByteArray(jpegDataArray, 0, jpegDataArray.Length, option);
}
/// <summary>
/// Callback to receive result from depth of field processor.
/// </summary>
private SCameraDepthOfFieldProcessor.EventCallback mProcessorCallback = new EventCallbackAnonymousInnerClassHelper();
private class EventCallbackAnonymousInnerClassHelper : SCameraDepthOfFieldProcessor.EventCallback
{
public EventCallbackAnonymousInnerClassHelper()
{
}
/// <summary>
/// Called as <seealso cref="SCameraDepthOfFieldProcessor#requestMultiProcess"/> is finished.
/// </summary>
/// <param name="result"> a Image object holds result image. </param>
/// <param name="error"> error code when processing </param>
public override void onProcessCompleted(Image result, int error)
{
if (outerInstance.State == CAMERA_STATE.CLOSING)
{
return;
}
// result image is produced, but error occurs when processing depth of field image.
if (error != SCameraDepthOfFieldProcessor.PROCESSING_NO_ERROR)
{
processingDofError(error);
}
// decode result image to bitmap
int sampleSize = 4;
ByteBuffer jpegData = result.Planes[0].Buffer;
Bitmap resultImg = outerInstance.decodeToBitmap(jpegData, sampleSize);
// save result image to file
outerInstance.mImageSaver.save(result, outerInstance.createFileName() + "_dof.jpg");
// decode input images
Bitmap autoFocusImg = outerInstance.decodeToBitmap(outerInstance.mInputImageList[IDX_AUTO_FOCUS_IMG].Planes[0].Buffer, sampleSize);
Bitmap infinityFocusImg = outerInstance.decodeToBitmap(outerInstance.mInputImageList[IDX_INFINITY_FOCUS_IMG].Planes[0].Buffer, sampleSize);
// show result dialog
showResultDialog(autoFocusImg, infinityFocusImg, resultImg);
outerInstance.clearInputImages();
outerInstance.unlockAF();
// done. re-start preview with default parameter
outerInstance.startPreview();
outerInstance.State = CAMERA_STATE.PREVIEW;
}
/// <summary>
/// Called when error occurred.
/// </summary>
public override void onError(int code)
{
if (outerInstance.State == CAMERA_STATE.CLOSING)
{
return;
}
StringBuilder builder = new StringBuilder();
builder.Append("Fail to create result: ");
switch (code)
{
case SCameraDepthOfFieldProcessor.NATIVE_PROCESSOR_MSG_DECODING_FAIL:
{
builder.Append("decoding fail");
break;
}
case SCameraDepthOfFieldProcessor.NATIVE_PROCESSOR_MSG_ENCODING_FAIL:
{
builder.Append("encoding fail");
break;
}
case SCameraDepthOfFieldProcessor.NATIVE_PROCESSOR_MSG_PROCESSING_FAIL:
{
builder.Append("processing fail");
break;
}
case SCameraDepthOfFieldProcessor.NATIVE_PROCESSOR_MSG_UNKNOWN_ERROR:
{
builder.Append("unknown error");
break;
}
}
outerInstance.showAlertDialog(builder.ToString(), false);
outerInstance.clearInputImages();
outerInstance.unlockAF();
outerInstance.State = CAMERA_STATE.PREVIEW;
}
/// <summary>
/// Show error code when processing depth of field </summary>
/// <param name="code"> error code when processing </param>
private void processingDofError(int code)
{
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final StringBuilder builder = new StringBuilder();
StringBuilder builder = new StringBuilder();
switch (code)
{
case SCameraDepthOfFieldProcessor.PROCESSING_ERROR_AF:
{
builder.Append(Resources.getText(R.@string.depth_of_field_error_af));
break;
}
case SCameraDepthOfFieldProcessor.PROCESSING_ERROR_INF:
{
builder.Append(Resources.getText(R.@string.depth_of_field_error_inf));
break;
}
case SCameraDepthOfFieldProcessor.PROCESSING_ERROR_SEGMENTATION:
{
builder.Append(Resources.getText(R.@string.depth_of_field_error_segmentation));
break;
}
}
runOnUiThread(() =>
{
Log.e(TAG, "runOnUiThread - run");
Toast.makeText(outerInstance, builder.ToString(), Toast.LENGTH_SHORT).show();
});
}
}
protected internal override void onCreate(Bundle savedInstanceState)
{
base.onCreate(savedInstanceState);
ContentView = R.layout.activity_dof;
}
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;
}
OrientationListener = true;
if (!checkRequiredFeatures())
{
return;
}
createProcessor();
createUI();
openCamera();
}
public override void onPause()
{
State = CAMERA_STATE.CLOSING;
OrientationListener = false;
stopBackgroundThread();
deinitProcessor();
closeCamera();
base.onPause();
}
private void createProcessor()
{
SCameraProcessorManager processorManager = mSCamera.SCameraProcessorManager;
mProcessor = processorManager.createProcessor(SCameraProcessorManager.PROCESSOR_TYPE_DEPTH_OF_FIELD);
}
private void initProcessor()
{
SCameraProcessorParameter parameter = mProcessor.Parameters;
mDeviceDofInputCnt = parameter.get(SCameraDepthOfFieldProcessor.MULTI_INPUT_COUNT_RANGE).Upper;
parameter.set(SCameraDepthOfFieldProcessor.STILL_INPUT_FORMAT, ImageFormat.JPEG);
parameter.set(SCameraDepthOfFieldProcessor.STILL_OUTPUT_FORMAT, ImageFormat.JPEG);
parameter.set(SCameraDepthOfFieldProcessor.STILL_SIZE, new Size(mImageReader.Width, mImageReader.Height));
mProcessor.Parameters = parameter;
mProcessor.initialize();
mProcessor.setEventCallback(mProcessorCallback, mBackgroundHandler);
}
private void deinitProcessor()
{
if (mProcessor != null)
{
mProcessor.deinitialize();
mProcessor.close();
mProcessor = null;
}
}
private bool checkRequiredFeatures()
{
try
{
mCameraId = null;
foreach (string id in mSCamera.SCameraManager.CameraIdList)
{
SCameraCharacteristics cameraCharacteristics = mSCamera.SCameraManager.getCameraCharacteristics(id);
if (cameraCharacteristics.get(SCameraCharacteristics.LENS_FACING) == SCameraCharacteristics.LENS_FACING_BACK)
{
mCameraId = id;
break;
}
}
if (mCameraId == null)
{
showAlertDialog("No back-facing camera exist.", true);
return false;
}
mCharacteristics = mSCamera.SCameraManager.getCameraCharacteristics(mCameraId);
if (!mCharacteristics.AvailableCaptureRequestKeys.contains(SCaptureRequest.LENS_FOCUS_DISTANCE) || !contains(mCharacteristics.get(SCameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES), SCameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_MANUAL_SENSOR) || !(mCharacteristics.get(SCameraCharacteristics.LENS_INFO_MINIMUM_FOCUS_DISTANCE) > 0.0f))
{
showAlertDialog("Required SCaptureRequest.Key is not supported.", true);
return false;
}
if (!contains(mCharacteristics.get(SCameraCharacteristics.CONTROL_AF_AVAILABLE_MODES), SCameraCharacteristics.CONTROL_AF_MODE_AUTO) || !contains(mCharacteristics.get(SCameraCharacteristics.CONTROL_AF_AVAILABLE_MODES), SCameraCharacteristics.CONTROL_AF_MODE_OFF))
{
showAlertDialog("Required AF mode is not supported.", true);
return false;
}
if (!mSCamera.isFeatureEnabled(SCamera.SCAMERA_PROCESSOR))
{
showAlertDialog("This device does not support SCamera Processor feature.", true);
return false;
}
SCameraProcessorManager processorManager = mSCamera.SCameraProcessorManager;
if (!processorManager.isProcessorAvailable(SCameraProcessorManager.PROCESSOR_TYPE_DEPTH_OF_FIELD))
{
showAlertDialog("This device does not support DOF Processor.", true);
return false;
}
}
catch (CameraAccessException e)
{
showAlertDialog("Cannot access the camera.", true);
Log.e(TAG, "Cannot access the camera.", e);
return false;
}
return true;
}
/// <summary>
/// Prepares an UI, like button, dialog, etc.
/// </summary>
private void createUI()
{
Button button = (Button) findViewById(R.id.picture);
button.OnClickListener = new OnClickListenerAnonymousInnerClassHelper(this);
mTextureView = (AutoFitTextureView) findViewById(R.id.texture);
// Set SurfaceTextureListener that handle life cycle of TextureView
mTextureView.SurfaceTextureListener = new SurfaceTextureListenerAnonymousInnerClassHelper(this);
}
private class OnClickListenerAnonymousInnerClassHelper : View.OnClickListener
{
private readonly Sample_DOF outerInstance;
public OnClickListenerAnonymousInnerClassHelper(Sample_DOF outerInstance)
{
this.outerInstance = outerInstance;
}
public override void onClick(View v)
{
// take picture is only works under preview state.
if (outerInstance.State == CAMERA_STATE.PREVIEW)
{
outerInstance.mBackgroundHandler.post(() =>
{
outerInstance.State = CAMERA_STATE.TAKE_DOF_PICTURE;
outerInstance.takeDofPicture();
});
}
}
}
private class SurfaceTextureListenerAnonymousInnerClassHelper : TextureView.SurfaceTextureListener
{
private readonly Sample_DOF outerInstance;
public SurfaceTextureListenerAnonymousInnerClassHelper(Sample_DOF 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()
{
try
{
mCameraOpenCloseLock.acquire();
if (mSCameraSession != null)
{
mSCameraSession.close();
mSCameraSession = null;
}
if (mSCameraDevice != null)
{
mSCameraDevice.close();
mSCameraDevice = null;
}
if (mImageReader != null)
{
mImageReader.close();
mImageReader = null;
}
mSCameraManager = null;
mSCamera = null;
}
catch (InterruptedException e)
{
Log.e(TAG, "Interrupted while trying to lock camera closing.", e);
}
finally
{
mCameraOpenCloseLock.release();
}
}
/// <summary>
/// Opens a <seealso cref="com.samsung.android.sdk.camera.SCameraDevice"/>.
/// </summary>
private void openCamera()
{
try
{
if (!mCameraOpenCloseLock.tryAcquire(3000, TimeUnit.MILLISECONDS))
{
showAlertDialog("Time out waiting to lock camera opening.", true);
}
mSCameraManager = mSCamera.SCameraManager;
// acquires camera characteristics
SCameraCharacteristics characteristics = mSCameraManager.getCameraCharacteristics(mCameraId);
StreamConfigurationMap streamConfigurationMap = characteristics.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
mImageReader = ImageReader.newInstance(jpegSize.Width, jpegSize.Height, ImageFormat.JPEG, mProcessor.Parameters.get(SCameraDepthOfFieldProcessor.MULTI_INPUT_COUNT_RANGE).Upper);
mImageReader.setOnImageAvailableListener(mImageCallback, mBackgroundHandler);
// Set the aspect ratio to TextureView
int orientation = Resources.Configuration.orientation;
if (orientation == Configuration.ORIENTATION_LANDSCAPE)
{
mTextureView.setAspectRatio(mPreviewSize.Width, mPreviewSize.Height);
}
else
{
mTextureView.setAspectRatio(mPreviewSize.Height, mPreviewSize.Width);
}
// Initialize depth of field processor
initProcessor();
// 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_DOF outerInstance;
public StateCallbackAnonymousInnerClassHelper(Sample_DOF outerInstance)
{
this.outerInstance = outerInstance;
}
public virtual void onOpened(SCameraDevice sCameraDevice)
{
outerInstance.mCameraOpenCloseLock.release();
if (outerInstance.State == CAMERA_STATE.CLOSING)
{
return;
}
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()
{
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);
mCaptureBuilder = mSCameraDevice.createCaptureRequest(SCameraDevice.TEMPLATE_STILL_CAPTURE);
mCaptureBuilder.addTarget(mImageReader.Surface);
// remove af default lens distance
mPreviewBuilder.set(SCaptureRequest.LENS_FOCUS_DISTANCE, null);
mCaptureBuilder.set(SCaptureRequest.LENS_FOCUS_DISTANCE, null);
// set default AF trigger
mPreviewBuilder.set(SCaptureRequest.CONTROL_AF_TRIGGER, SCameraMetadata.CONTROL_AF_TRIGGER_IDLE);
mCaptureBuilder.set(SCaptureRequest.CONTROL_AF_TRIGGER, SCameraMetadata.CONTROL_AF_TRIGGER_IDLE);
// Creates a SCameraCaptureSession here.
IList<Surface> outputSurface = Arrays.asList(surface, mImageReader.Surface);
mSCameraDevice.createCaptureSession(outputSurface, new StateCallbackAnonymousInnerClassHelper(this), mBackgroundHandler);
}
catch (CameraAccessException e)
{
showAlertDialog("Fail to create session. " + e.Message, true);
}
}
private class StateCallbackAnonymousInnerClassHelper : SCameraCaptureSession.StateCallback
{
private readonly Sample_DOF outerInstance;
public StateCallbackAnonymousInnerClassHelper(Sample_DOF outerInstance)
{
this.outerInstance = outerInstance;
}
public override void onConfigured(SCameraCaptureSession sCameraCaptureSession)
{
if (outerInstance.State == CAMERA_STATE.CLOSING)
{
return;
}
outerInstance.mSCameraSession = sCameraCaptureSession;
outerInstance.startPreview();
outerInstance.State = CAMERA_STATE.PREVIEW;
}
public override void onConfigureFailed(SCameraCaptureSession sCameraCaptureSession)
{
if (outerInstance.State == CAMERA_STATE.CLOSING)
{
return;
}
outerInstance.showAlertDialog("Fail to create camera session.", true);
}
}
/// <summary>
/// Starts a preview.
/// </summary>
private void startPreview()
{
try
{
mPreviewBuilder.set(SCaptureRequest.CONTROL_AF_MODE, SCaptureRequest.CONTROL_AF_MODE_AUTO);
mSCameraSession.setRepeatingRequest(mPreviewBuilder.build(), mSessionCaptureCallback, mBackgroundHandler);
}
catch (CameraAccessException e)
{
showAlertDialog("Fail to create preview session. " + e.Message, true);
}
}
/// <summary>
/// Unlock AF.
/// </summary>
private void unlockAF()
{
// 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(), null, mBackgroundHandler);
mPreviewBuilder.set(SCaptureRequest.CONTROL_AF_TRIGGER, SCaptureRequest.CONTROL_AF_TRIGGER_IDLE);
}
catch (CameraAccessException)
{
showAlertDialog("Fail to cancel AF", false);
}
}
private void configureTransform(int viewWidth, int viewHeight)
{
if (null == mTextureView || null == mPreviewSize)
{
return;
}
int rotation = WindowManager.DefaultDisplay.Rotation;
Matrix matrix = new Matrix();
RectF viewRect = new RectF(0, 0, viewWidth, viewHeight);
RectF bufferRect = new RectF(0, 0, mPreviewSize.Height, mPreviewSize.Width);
float centerX = viewRect.centerX();
float centerY = viewRect.centerY();
if (Surface.ROTATION_90 == rotation || Surface.ROTATION_270 == rotation)
{
bufferRect.offset(centerX - bufferRect.centerX(), centerY - bufferRect.centerY());
matrix.setRectToRect(viewRect, bufferRect, Matrix.ScaleToFit.FILL);
float scale = Math.Max((float) viewHeight / mPreviewSize.Height, (float) viewWidth / mPreviewSize.Width);
matrix.postScale(scale, scale, centerX, centerY);
matrix.postRotate(90 * (rotation - 2), centerX, centerY);
}
else
{
matrix.postRotate(90 * rotation, centerX, centerY);
}
mTextureView.Transform = matrix;
mTextureView.SurfaceTexture.setDefaultBufferSize(mPreviewSize.Width, mPreviewSize.Height);
}
/// <summary>
/// Returns required orientation that the jpeg picture needs to be rotated to be displayed upright.
/// </summary>
private int JpegOrientation
{
get
{
int degrees = mLastOrientation;
if (mCharacteristics.get(SCameraCharacteristics.LENS_FACING) == SCameraCharacteristics.LENS_FACING_FRONT)
{
degrees = -degrees;
}
return (mCharacteristics.get(SCameraCharacteristics.SENSOR_ORIENTATION) + degrees + 360) % 360;
}
}
/// <summary>
/// Enable/Disable an orientation listener.
/// </summary>
private bool OrientationListener
{
set
{
if (mOrientationListener == null)
{
mOrientationListener = new OrientationEventListenerAnonymousInnerClassHelper(this);
}
if (value)
{
mOrientationListener.enable();
}
else
{
mOrientationListener.disable();
}
}
}
private class OrientationEventListenerAnonymousInnerClassHelper : OrientationEventListener
{
private readonly Sample_DOF outerInstance;
public OrientationEventListenerAnonymousInnerClassHelper(Sample_DOF outerInstance) : base(outerInstance)
{
this.outerInstance = outerInstance;
}
public override void onOrientationChanged(int orientation)
{
if (orientation == ORIENTATION_UNKNOWN)
{
return;
}
outerInstance.mLastOrientation = (orientation + 45) / 90 * 90;
}
}
private void clearInputImages()
{
foreach (Image i in mInputImageList)
{
i.close();
}
mInputImageList.Clear();
}
/// <summary>
/// Starts back ground thread that callback from camera will posted.
/// </summary>
private void startBackgroundThread()
{
mBackgroundHandlerThread = new HandlerThread("Background Thread");
mBackgroundHandlerThread.start();
mBackgroundHandler = new Handler(mBackgroundHandlerThread.Looper);
}
/// <summary>
/// Stops back ground thread.
/// </summary>
private void stopBackgroundThread()
{
if (mBackgroundHandlerThread != null)
{
mBackgroundHandlerThread.quitSafely();
try
{
mBackgroundHandlerThread.join();
mBackgroundHandlerThread = null;
mBackgroundHandler = null;
}
catch (InterruptedException e)
{
Console.WriteLine(e.ToString());
Console.Write(e.StackTrace);
}
}