This repository was archived by the owner on Sep 20, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 183
Expand file tree
/
Copy pathCamera2RawFragment.java
More file actions
1848 lines (1628 loc) · 71.7 KB
/
Camera2RawFragment.java
File metadata and controls
1848 lines (1628 loc) · 71.7 KB
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
/*
* Copyright 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.camera2raw;
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.Fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.graphics.ImageFormat;
import android.graphics.Matrix;
import android.graphics.Point;
import android.graphics.RectF;
import android.graphics.SurfaceTexture;
import android.hardware.SensorManager;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCaptureSession;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraDevice;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.CameraMetadata;
import android.hardware.camera2.CaptureFailure;
import android.hardware.camera2.CaptureRequest;
import android.hardware.camera2.CaptureResult;
import android.hardware.camera2.DngCreator;
import android.hardware.camera2.TotalCaptureResult;
import android.hardware.camera2.params.StreamConfigurationMap;
import android.media.Image;
import android.media.ImageReader;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.os.SystemClock;
import android.support.v13.app.FragmentCompat;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.util.Size;
import android.util.SparseIntArray;
import android.view.LayoutInflater;
import android.view.OrientationEventListener;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* A fragment that demonstrates use of the Camera2 API to capture RAW and JPEG photos.
* <p/>
* In this example, the lifecycle of a single request to take a photo is:
* <ul>
* <li>
* The user presses the "Picture" button, resulting in a call to {@link #takePicture()}.
* </li>
* <li>
* {@link #takePicture()} initiates a pre-capture sequence that triggers the camera's built-in
* auto-focus, auto-exposure, and auto-white-balance algorithms (aka. "3A") to run.
* </li>
* <li>
* When the pre-capture sequence has finished, a {@link CaptureRequest} with a monotonically
* increasing request ID set by calls to {@link CaptureRequest.Builder#setTag(Object)} is sent to
* the camera to begin the JPEG and RAW capture sequence, and an
* {@link ImageSaver.ImageSaverBuilder} is stored for this request in the
* {@link #mJpegResultQueue} and {@link #mRawResultQueue}.
* </li>
* <li>
* As {@link CaptureResult}s and {@link Image}s become available via callbacks in a background
* thread, a {@link ImageSaver.ImageSaverBuilder} is looked up by the request ID in
* {@link #mJpegResultQueue} and {@link #mRawResultQueue} and updated.
* </li>
* <li>
* When all of the necessary results to save an image are available, the an {@link ImageSaver} is
* constructed by the {@link ImageSaver.ImageSaverBuilder} and passed to a separate background
* thread to save to a file.
* </li>
* </ul>
*/
public class Camera2RawFragment extends Fragment
implements View.OnClickListener, FragmentCompat.OnRequestPermissionsResultCallback {
/**
* Conversion from screen rotation to JPEG orientation.
*/
private static final SparseIntArray ORIENTATIONS = new SparseIntArray();
static {
ORIENTATIONS.append(Surface.ROTATION_0, 0);
ORIENTATIONS.append(Surface.ROTATION_90, 90);
ORIENTATIONS.append(Surface.ROTATION_180, 180);
ORIENTATIONS.append(Surface.ROTATION_270, 270);
}
/**
* Request code for camera permissions.
*/
private static final int REQUEST_CAMERA_PERMISSIONS = 1;
/**
* Permissions required to take a picture.
*/
private static final String[] CAMERA_PERMISSIONS = {
Manifest.permission.CAMERA,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
};
/**
* Timeout for the pre-capture sequence.
*/
private static final long PRECAPTURE_TIMEOUT_MS = 1000;
/**
* Tolerance when comparing aspect ratios.
*/
private static final double ASPECT_RATIO_TOLERANCE = 0.005;
/**
* Max preview width that is guaranteed by Camera2 API
*/
private static final int MAX_PREVIEW_WIDTH = 1920;
/**
* Max preview height that is guaranteed by Camera2 API
*/
private static final int MAX_PREVIEW_HEIGHT = 1080;
/**
* Tag for the {@link Log}.
*/
private static final String TAG = "Camera2RawFragment";
/**
* Camera state: Device is closed.
*/
private static final int STATE_CLOSED = 0;
/**
* Camera state: Device is opened, but is not capturing.
*/
private static final int STATE_OPENED = 1;
/**
* Camera state: Showing camera preview.
*/
private static final int STATE_PREVIEW = 2;
/**
* Camera state: Waiting for 3A convergence before capturing a photo.
*/
private static final int STATE_WAITING_FOR_3A_CONVERGENCE = 3;
/**
* An {@link OrientationEventListener} used to determine when device rotation has occurred.
* This is mainly necessary for when the device is rotated by 180 degrees, in which case
* onCreate or onConfigurationChanged is not called as the view dimensions remain the same,
* but the orientation of the has changed, and thus the preview rotation must be updated.
*/
private OrientationEventListener mOrientationListener;
/**
* {@link TextureView.SurfaceTextureListener} handles several lifecycle events of a
* {@link TextureView}.
*/
private final TextureView.SurfaceTextureListener mSurfaceTextureListener
= new TextureView.SurfaceTextureListener() {
@Override
public void onSurfaceTextureAvailable(SurfaceTexture texture, int width, int height) {
configureTransform(width, height);
}
@Override
public void onSurfaceTextureSizeChanged(SurfaceTexture texture, int width, int height) {
configureTransform(width, height);
}
@Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture texture) {
synchronized (mCameraStateLock) {
mPreviewSize = null;
}
return true;
}
@Override
public void onSurfaceTextureUpdated(SurfaceTexture texture) {
}
};
/**
* An {@link AutoFitTextureView} for camera preview.
*/
private AutoFitTextureView mTextureView;
/**
* An additional thread for running tasks that shouldn't block the UI. This is used for all
* callbacks from the {@link CameraDevice} and {@link CameraCaptureSession}s.
*/
private HandlerThread mBackgroundThread;
/**
* A counter for tracking corresponding {@link CaptureRequest}s and {@link CaptureResult}s
* across the {@link CameraCaptureSession} capture callbacks.
*/
private final AtomicInteger mRequestCounter = new AtomicInteger();
/**
* A {@link Semaphore} to prevent the app from exiting before closing the camera.
*/
private final Semaphore mCameraOpenCloseLock = new Semaphore(1);
/**
* A lock protecting camera state.
*/
private final Object mCameraStateLock = new Object();
// *********************************************************************************************
// State protected by mCameraStateLock.
//
// The following state is used across both the UI and background threads. Methods with "Locked"
// in the name expect mCameraStateLock to be held while calling.
/**
* ID of the current {@link CameraDevice}.
*/
private String mCameraId;
/**
* A {@link CameraCaptureSession } for camera preview.
*/
private CameraCaptureSession mCaptureSession;
/**
* A reference to the open {@link CameraDevice}.
*/
private CameraDevice mCameraDevice;
/**
* The {@link Size} of camera preview.
*/
private Size mPreviewSize;
/**
* The {@link CameraCharacteristics} for the currently configured camera device.
*/
private CameraCharacteristics mCharacteristics;
/**
* A {@link Handler} for running tasks in the background.
*/
private Handler mBackgroundHandler;
/**
* A reference counted holder wrapping the {@link ImageReader} that handles JPEG image
* captures. This is used to allow us to clean up the {@link ImageReader} when all background
* tasks using its {@link Image}s have completed.
*/
private RefCountedAutoCloseable<ImageReader> mJpegImageReader;
/**
* A reference counted holder wrapping the {@link ImageReader} that handles RAW image captures.
* This is used to allow us to clean up the {@link ImageReader} when all background tasks using
* its {@link Image}s have completed.
*/
private RefCountedAutoCloseable<ImageReader> mRawImageReader;
/**
* Whether or not the currently configured camera device is fixed-focus.
*/
private boolean mNoAFRun = false;
/**
* Number of pending user requests to capture a photo.
*/
private int mPendingUserCaptures = 0;
/**
* Request ID to {@link ImageSaver.ImageSaverBuilder} mapping for in-progress JPEG captures.
*/
private final TreeMap<Integer, ImageSaver.ImageSaverBuilder> mJpegResultQueue = new TreeMap<>();
/**
* Request ID to {@link ImageSaver.ImageSaverBuilder} mapping for in-progress RAW captures.
*/
private final TreeMap<Integer, ImageSaver.ImageSaverBuilder> mRawResultQueue = new TreeMap<>();
/**
* {@link CaptureRequest.Builder} for the camera preview
*/
private CaptureRequest.Builder mPreviewRequestBuilder;
/**
* The state of the camera device.
*
* @see #mPreCaptureCallback
*/
private int mState = STATE_CLOSED;
/**
* Timer to use with pre-capture sequence to ensure a timely capture if 3A convergence is
* taking too long.
*/
private long mCaptureTimer;
//**********************************************************************************************
/**
* {@link CameraDevice.StateCallback} is called when the currently active {@link CameraDevice}
* changes its state.
*/
private final CameraDevice.StateCallback mStateCallback = new CameraDevice.StateCallback() {
@Override
public void onOpened(CameraDevice cameraDevice) {
// This method is called when the camera is opened. We start camera preview here if
// the TextureView displaying this has been set up.
synchronized (mCameraStateLock) {
mState = STATE_OPENED;
mCameraOpenCloseLock.release();
mCameraDevice = cameraDevice;
// Start the preview session if the TextureView has been set up already.
if (mPreviewSize != null && mTextureView.isAvailable()) {
createCameraPreviewSessionLocked();
}
}
}
@Override
public void onDisconnected(CameraDevice cameraDevice) {
synchronized (mCameraStateLock) {
mState = STATE_CLOSED;
mCameraOpenCloseLock.release();
cameraDevice.close();
mCameraDevice = null;
}
}
@Override
public void onError(CameraDevice cameraDevice, int error) {
Log.e(TAG, "Received camera device error: " + error);
synchronized (mCameraStateLock) {
mState = STATE_CLOSED;
mCameraOpenCloseLock.release();
cameraDevice.close();
mCameraDevice = null;
}
Activity activity = getActivity();
if (null != activity) {
activity.finish();
}
}
};
/**
* This a callback object for the {@link ImageReader}. "onImageAvailable" will be called when a
* JPEG image is ready to be saved.
*/
private final ImageReader.OnImageAvailableListener mOnJpegImageAvailableListener
= new ImageReader.OnImageAvailableListener() {
@Override
public void onImageAvailable(ImageReader reader) {
dequeueAndSaveImage(mJpegResultQueue, mJpegImageReader);
}
};
/**
* This a callback object for the {@link ImageReader}. "onImageAvailable" will be called when a
* RAW image is ready to be saved.
*/
private final ImageReader.OnImageAvailableListener mOnRawImageAvailableListener
= new ImageReader.OnImageAvailableListener() {
@Override
public void onImageAvailable(ImageReader reader) {
dequeueAndSaveImage(mRawResultQueue, mRawImageReader);
}
};
/**
* A {@link CameraCaptureSession.CaptureCallback} that handles events for the preview and
* pre-capture sequence.
*/
private CameraCaptureSession.CaptureCallback mPreCaptureCallback
= new CameraCaptureSession.CaptureCallback() {
private void process(CaptureResult result) {
synchronized (mCameraStateLock) {
switch (mState) {
case STATE_PREVIEW: {
// We have nothing to do when the camera preview is running normally.
break;
}
case STATE_WAITING_FOR_3A_CONVERGENCE: {
boolean readyToCapture = true;
if (!mNoAFRun) {
Integer afState = result.get(CaptureResult.CONTROL_AF_STATE);
if (afState == null) {
break;
}
// If auto-focus has reached locked state, we are ready to capture
readyToCapture =
(afState == CaptureResult.CONTROL_AF_STATE_FOCUSED_LOCKED ||
afState == CaptureResult.CONTROL_AF_STATE_NOT_FOCUSED_LOCKED);
}
// If we are running on an non-legacy device, we should also wait until
// auto-exposure and auto-white-balance have converged as well before
// taking a picture.
if (!isLegacyLocked()) {
Integer aeState = result.get(CaptureResult.CONTROL_AE_STATE);
Integer awbState = result.get(CaptureResult.CONTROL_AWB_STATE);
if (aeState == null || awbState == null) {
break;
}
readyToCapture = readyToCapture &&
aeState == CaptureResult.CONTROL_AE_STATE_CONVERGED &&
awbState == CaptureResult.CONTROL_AWB_STATE_CONVERGED;
}
// If we haven't finished the pre-capture sequence but have hit our maximum
// wait timeout, too bad! Begin capture anyway.
if (!readyToCapture && hitTimeoutLocked()) {
Log.w(TAG, "Timed out waiting for pre-capture sequence to complete.");
readyToCapture = true;
}
if (readyToCapture && mPendingUserCaptures > 0) {
// Capture once for each user tap of the "Picture" button.
while (mPendingUserCaptures > 0) {
captureStillPictureLocked();
mPendingUserCaptures--;
}
// After this, the camera will go back to the normal state of preview.
mState = STATE_PREVIEW;
}
}
}
}
}
@Override
public void onCaptureProgressed(CameraCaptureSession session, CaptureRequest request,
CaptureResult partialResult) {
process(partialResult);
}
@Override
public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request,
TotalCaptureResult result) {
process(result);
}
};
/**
* A {@link CameraCaptureSession.CaptureCallback} that handles the still JPEG and RAW capture
* request.
*/
private final CameraCaptureSession.CaptureCallback mCaptureCallback
= new CameraCaptureSession.CaptureCallback() {
@Override
public void onCaptureStarted(CameraCaptureSession session, CaptureRequest request,
long timestamp, long frameNumber) {
String currentDateTime = generateTimestamp();
File rawFile = new File(Environment.
getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),
"RAW_" + currentDateTime + ".dng");
File jpegFile = new File(Environment.
getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),
"JPEG_" + currentDateTime + ".jpg");
// Look up the ImageSaverBuilder for this request and update it with the file name
// based on the capture start time.
ImageSaver.ImageSaverBuilder jpegBuilder;
ImageSaver.ImageSaverBuilder rawBuilder;
int requestId = (int) request.getTag();
synchronized (mCameraStateLock) {
jpegBuilder = mJpegResultQueue.get(requestId);
rawBuilder = mRawResultQueue.get(requestId);
}
if (jpegBuilder != null) jpegBuilder.setFile(jpegFile);
if (rawBuilder != null) rawBuilder.setFile(rawFile);
}
@Override
public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request,
TotalCaptureResult result) {
int requestId = (int) request.getTag();
ImageSaver.ImageSaverBuilder jpegBuilder;
ImageSaver.ImageSaverBuilder rawBuilder;
StringBuilder sb = new StringBuilder();
// Look up the ImageSaverBuilder for this request and update it with the CaptureResult
synchronized (mCameraStateLock) {
jpegBuilder = mJpegResultQueue.get(requestId);
rawBuilder = mRawResultQueue.get(requestId);
if (jpegBuilder != null) {
jpegBuilder.setResult(result);
sb.append("Saving JPEG as: ");
sb.append(jpegBuilder.getSaveLocation());
}
if (rawBuilder != null) {
rawBuilder.setResult(result);
if (jpegBuilder != null) sb.append(", ");
sb.append("Saving RAW as: ");
sb.append(rawBuilder.getSaveLocation());
}
// If we have all the results necessary, save the image to a file in the background.
handleCompletionLocked(requestId, jpegBuilder, mJpegResultQueue);
handleCompletionLocked(requestId, rawBuilder, mRawResultQueue);
finishedCaptureLocked();
}
showToast(sb.toString());
}
@Override
public void onCaptureFailed(CameraCaptureSession session, CaptureRequest request,
CaptureFailure failure) {
int requestId = (int) request.getTag();
synchronized (mCameraStateLock) {
mJpegResultQueue.remove(requestId);
mRawResultQueue.remove(requestId);
finishedCaptureLocked();
}
showToast("Capture failed!");
}
};
/**
* A {@link Handler} for showing {@link Toast}s on the UI thread.
*/
private final Handler mMessageHandler = new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(Message msg) {
Activity activity = getActivity();
if (activity != null) {
Toast.makeText(activity, (String) msg.obj, Toast.LENGTH_SHORT).show();
}
}
};
public static Camera2RawFragment newInstance() {
return new Camera2RawFragment();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_camera2_basic, container, false);
}
@Override
public void onViewCreated(final View view, Bundle savedInstanceState) {
view.findViewById(R.id.picture).setOnClickListener(this);
view.findViewById(R.id.info).setOnClickListener(this);
mTextureView = (AutoFitTextureView) view.findViewById(R.id.texture);
// Setup a new OrientationEventListener. This is used to handle rotation events like a
// 180 degree rotation that do not normally trigger a call to onCreate to do view re-layout
// or otherwise cause the preview TextureView's size to change.
mOrientationListener = new OrientationEventListener(getActivity(),
SensorManager.SENSOR_DELAY_NORMAL) {
@Override
public void onOrientationChanged(int orientation) {
if (mTextureView != null && mTextureView.isAvailable()) {
configureTransform(mTextureView.getWidth(), mTextureView.getHeight());
}
}
};
}
@Override
public void onResume() {
super.onResume();
startBackgroundThread();
openCamera();
// When the screen is turned off and turned back on, the SurfaceTexture is already
// available, and "onSurfaceTextureAvailable" will not be called. In that case, we should
// configure the preview bounds here (otherwise, we wait until the surface is ready in
// the SurfaceTextureListener).
if (mTextureView.isAvailable()) {
configureTransform(mTextureView.getWidth(), mTextureView.getHeight());
} else {
mTextureView.setSurfaceTextureListener(mSurfaceTextureListener);
}
if (mOrientationListener != null && mOrientationListener.canDetectOrientation()) {
mOrientationListener.enable();
}
}
@Override
public void onPause() {
if (mOrientationListener != null) {
mOrientationListener.disable();
}
closeCamera();
stopBackgroundThread();
super.onPause();
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == REQUEST_CAMERA_PERMISSIONS) {
for (int result : grantResults) {
if (result != PackageManager.PERMISSION_GRANTED) {
showMissingPermissionError();
return;
}
}
} else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.picture: {
takePicture();
break;
}
case R.id.info: {
Activity activity = getActivity();
if (null != activity) {
new AlertDialog.Builder(activity)
.setMessage(R.string.intro_message)
.setPositiveButton(android.R.string.ok, null)
.show();
}
break;
}
}
}
/**
* Sets up state related to camera that is needed before opening a {@link CameraDevice}.
*/
private boolean setUpCameraOutputs() {
Activity activity = getActivity();
CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
if (manager == null) {
ErrorDialog.buildErrorDialog("This device doesn't support Camera2 API.").
show(getFragmentManager(), "dialog");
return false;
}
try {
// Find a CameraDevice that supports RAW captures, and configure state.
for (String cameraId : manager.getCameraIdList()) {
CameraCharacteristics characteristics
= manager.getCameraCharacteristics(cameraId);
// We only use a camera that supports RAW in this sample.
if (!contains(characteristics.get(
CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES),
CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_RAW)) {
continue;
}
StreamConfigurationMap map = characteristics.get(
CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
// For still image captures, we use the largest available size.
Size largestJpeg = Collections.max(
Arrays.asList(map.getOutputSizes(ImageFormat.JPEG)),
new CompareSizesByArea());
Size largestRaw = Collections.max(
Arrays.asList(map.getOutputSizes(ImageFormat.RAW_SENSOR)),
new CompareSizesByArea());
synchronized (mCameraStateLock) {
// Set up ImageReaders for JPEG and RAW outputs. Place these in a reference
// counted wrapper to ensure they are only closed when all background tasks
// using them are finished.
if (mJpegImageReader == null || mJpegImageReader.getAndRetain() == null) {
mJpegImageReader = new RefCountedAutoCloseable<>(
ImageReader.newInstance(largestJpeg.getWidth(),
largestJpeg.getHeight(), ImageFormat.JPEG, /*maxImages*/5));
}
mJpegImageReader.get().setOnImageAvailableListener(
mOnJpegImageAvailableListener, mBackgroundHandler);
if (mRawImageReader == null || mRawImageReader.getAndRetain() == null) {
mRawImageReader = new RefCountedAutoCloseable<>(
ImageReader.newInstance(largestRaw.getWidth(),
largestRaw.getHeight(), ImageFormat.RAW_SENSOR, /*maxImages*/ 5));
}
mRawImageReader.get().setOnImageAvailableListener(
mOnRawImageAvailableListener, mBackgroundHandler);
mCharacteristics = characteristics;
mCameraId = cameraId;
}
return true;
}
} catch (CameraAccessException e) {
e.printStackTrace();
}
// If we found no suitable cameras for capturing RAW, warn the user.
ErrorDialog.buildErrorDialog("This device doesn't support capturing RAW photos").
show(getFragmentManager(), "dialog");
return false;
}
/**
* Opens the camera specified by {@link #mCameraId}.
*/
@SuppressWarnings("MissingPermission")
private void openCamera() {
if (!setUpCameraOutputs()) {
return;
}
if (!hasAllPermissionsGranted()) {
requestCameraPermissions();
return;
}
Activity activity = getActivity();
CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
try {
// Wait for any previously running session to finish.
if (!mCameraOpenCloseLock.tryAcquire(2500, TimeUnit.MILLISECONDS)) {
throw new RuntimeException("Time out waiting to lock camera opening.");
}
String cameraId;
Handler backgroundHandler;
synchronized (mCameraStateLock) {
cameraId = mCameraId;
backgroundHandler = mBackgroundHandler;
}
// Attempt to open the camera. mStateCallback will be called on the background handler's
// thread when this succeeds or fails.
manager.openCamera(cameraId, mStateCallback, backgroundHandler);
} catch (CameraAccessException e) {
e.printStackTrace();
} catch (InterruptedException e) {
throw new RuntimeException("Interrupted while trying to lock camera opening.", e);
}
}
/**
* Requests permissions necessary to use camera and save pictures.
*/
private void requestCameraPermissions() {
if (shouldShowRationale()) {
PermissionConfirmationDialog.newInstance().show(getChildFragmentManager(), "dialog");
} else {
FragmentCompat.requestPermissions(this, CAMERA_PERMISSIONS, REQUEST_CAMERA_PERMISSIONS);
}
}
/**
* Tells whether all the necessary permissions are granted to this app.
*
* @return True if all the required permissions are granted.
*/
private boolean hasAllPermissionsGranted() {
for (String permission : CAMERA_PERMISSIONS) {
if (ActivityCompat.checkSelfPermission(getActivity(), permission)
!= PackageManager.PERMISSION_GRANTED) {
return false;
}
}
return true;
}
/**
* Gets whether you should show UI with rationale for requesting the permissions.
*
* @return True if the UI should be shown.
*/
private boolean shouldShowRationale() {
for (String permission : CAMERA_PERMISSIONS) {
if (FragmentCompat.shouldShowRequestPermissionRationale(this, permission)) {
return true;
}
}
return false;
}
/**
* Shows that this app really needs the permission and finishes the app.
*/
private void showMissingPermissionError() {
Activity activity = getActivity();
if (activity != null) {
Toast.makeText(activity, R.string.request_permission, Toast.LENGTH_SHORT).show();
activity.finish();
}
}
/**
* Closes the current {@link CameraDevice}.
*/
private void closeCamera() {
try {
mCameraOpenCloseLock.acquire();
synchronized (mCameraStateLock) {
// Reset state and clean up resources used by the camera.
// Note: After calling this, the ImageReaders will be closed after any background
// tasks saving Images from these readers have been completed.
mPendingUserCaptures = 0;
mState = STATE_CLOSED;
if (null != mCaptureSession) {
mCaptureSession.close();
mCaptureSession = null;
}
if (null != mCameraDevice) {
mCameraDevice.close();
mCameraDevice = null;
}
if (null != mJpegImageReader) {
mJpegImageReader.close();
mJpegImageReader = null;
}
if (null != mRawImageReader) {
mRawImageReader.close();
mRawImageReader = null;
}
}
} catch (InterruptedException e) {
throw new RuntimeException("Interrupted while trying to lock camera closing.", e);
} finally {
mCameraOpenCloseLock.release();
}
}
/**
* Starts a background thread and its {@link Handler}.
*/
private void startBackgroundThread() {
mBackgroundThread = new HandlerThread("CameraBackground");
mBackgroundThread.start();
synchronized (mCameraStateLock) {
mBackgroundHandler = new Handler(mBackgroundThread.getLooper());
}
}
/**
* Stops the background thread and its {@link Handler}.
*/
private void stopBackgroundThread() {
mBackgroundThread.quitSafely();
try {
mBackgroundThread.join();
mBackgroundThread = null;
synchronized (mCameraStateLock) {
mBackgroundHandler = null;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* Creates a new {@link CameraCaptureSession} for camera preview.
* <p/>
* Call this only with {@link #mCameraStateLock} held.
*/
private void createCameraPreviewSessionLocked() {
try {
SurfaceTexture texture = mTextureView.getSurfaceTexture();
// We configure the size of default buffer to be the size of camera preview we want.
texture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());
// This is the output Surface we need to start preview.
Surface surface = new Surface(texture);
// We set up a CaptureRequest.Builder with the output Surface.
mPreviewRequestBuilder
= mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
mPreviewRequestBuilder.addTarget(surface);
// Here, we create a CameraCaptureSession for camera preview.
mCameraDevice.createCaptureSession(Arrays.asList(surface,
mJpegImageReader.get().getSurface(),
mRawImageReader.get().getSurface()), new CameraCaptureSession.StateCallback() {
@Override
public void onConfigured(CameraCaptureSession cameraCaptureSession) {
synchronized (mCameraStateLock) {
// The camera is already closed
if (null == mCameraDevice) {
return;
}
try {
setup3AControlsLocked(mPreviewRequestBuilder);
// Finally, we start displaying the camera preview.
cameraCaptureSession.setRepeatingRequest(
mPreviewRequestBuilder.build(),
mPreCaptureCallback, mBackgroundHandler);
mState = STATE_PREVIEW;
} catch (CameraAccessException | IllegalStateException e) {
e.printStackTrace();
return;
}
// When the session is ready, we start displaying the preview.
mCaptureSession = cameraCaptureSession;
}
}
@Override
public void onConfigureFailed(CameraCaptureSession cameraCaptureSession) {
showToast("Failed to configure camera.");
}
}, mBackgroundHandler
);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
/**
* Configure the given {@link CaptureRequest.Builder} to use auto-focus, auto-exposure, and
* auto-white-balance controls if available.
* <p/>
* Call this only with {@link #mCameraStateLock} held.
*
* @param builder the builder to configure.
*/
private void setup3AControlsLocked(CaptureRequest.Builder builder) {
// Enable auto-magical 3A run by camera device
builder.set(CaptureRequest.CONTROL_MODE,
CaptureRequest.CONTROL_MODE_AUTO);
Float minFocusDist =
mCharacteristics.get(CameraCharacteristics.LENS_INFO_MINIMUM_FOCUS_DISTANCE);
// If MINIMUM_FOCUS_DISTANCE is 0, lens is fixed-focus and we need to skip the AF run.
mNoAFRun = (minFocusDist == null || minFocusDist == 0);
if (!mNoAFRun) {
// If there is a "continuous picture" mode available, use it, otherwise default to AUTO.
if (contains(mCharacteristics.get(
CameraCharacteristics.CONTROL_AF_AVAILABLE_MODES),
CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE)) {
builder.set(CaptureRequest.CONTROL_AF_MODE,
CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);