This repository has been archived by the owner on Nov 15, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 137
/
Camera.java
2286 lines (1996 loc) · 81.5 KB
/
Camera.java
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 (C) 2007 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.android.camera;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.ContentProviderClient;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Camera.CameraInfo;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.Size;
import android.location.Location;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.media.AudioManager;
import android.media.CameraProfile;
import android.media.ToneGenerator;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Debug;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.MessageQueue;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.provider.Settings;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Display;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.OrientationEventListener;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.MenuItem.OnMenuItemClickListener;
import android.widget.FrameLayout;
import android.widget.ImageView;
import com.android.camera.gallery.IImage;
import com.android.camera.gallery.IImageList;
import com.android.camera.ui.CameraHeadUpDisplay;
import com.android.camera.ui.GLRootView;
import com.android.camera.ui.HeadUpDisplay;
import com.android.camera.ui.ZoomControllerListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
/** The Camera activity which can preview and take pictures. */
public class Camera extends NoSearchActivity implements View.OnClickListener,
ShutterButton.OnShutterButtonListener, SurfaceHolder.Callback,
Switcher.OnSwitchListener {
private static final String TAG = "camera";
private static final int CROP_MSG = 1;
private static final int FIRST_TIME_INIT = 2;
private static final int RESTART_PREVIEW = 3;
private static final int CLEAR_SCREEN_DELAY = 4;
private static final int SET_CAMERA_PARAMETERS_WHEN_IDLE = 5;
// The subset of parameters we need to update in setCameraParameters().
private static final int UPDATE_PARAM_INITIALIZE = 1;
private static final int UPDATE_PARAM_ZOOM = 2;
private static final int UPDATE_PARAM_PREFERENCE = 4;
private static final int UPDATE_PARAM_ALL = -1;
// When setCameraParametersWhenIdle() is called, we accumulate the subsets
// needed to be updated in mUpdateSet.
private int mUpdateSet;
// The brightness settings used when it is set to automatic in the system.
// The reason why it is set to 0.7 is just because 1.0 is too bright.
private static final float DEFAULT_CAMERA_BRIGHTNESS = 0.7f;
private static final int SCREEN_DELAY = 2 * 60 * 1000;
private static final int FOCUS_BEEP_VOLUME = 100;
private static final int ZOOM_STOPPED = 0;
private static final int ZOOM_START = 1;
private static final int ZOOM_STOPPING = 2;
private int mZoomState = ZOOM_STOPPED;
private boolean mSmoothZoomSupported = false;
private int mZoomValue; // The current zoom value.
private int mZoomMax;
private int mTargetZoomValue;
private Parameters mParameters;
private Parameters mInitialParams;
private MyOrientationEventListener mOrientationListener;
// The device orientation in degrees. Default is unknown.
private int mOrientation = OrientationEventListener.ORIENTATION_UNKNOWN;
// The orientation compensation for icons and thumbnails.
private int mOrientationCompensation = 0;
private ComboPreferences mPreferences;
private static final int IDLE = 1;
private static final int SNAPSHOT_IN_PROGRESS = 2;
private static final boolean SWITCH_CAMERA = true;
private static final boolean SWITCH_VIDEO = false;
private int mStatus = IDLE;
private static final String sTempCropFilename = "crop-temp";
private android.hardware.Camera mCameraDevice;
private ContentProviderClient mMediaProviderClient;
private SurfaceView mSurfaceView;
private SurfaceHolder mSurfaceHolder = null;
private ShutterButton mShutterButton;
private FocusRectangle mFocusRectangle;
private ToneGenerator mFocusToneGenerator;
private GestureDetector mGestureDetector;
private Switcher mSwitcher;
private boolean mStartPreviewFail = false;
private GLRootView mGLRootView;
// mPostCaptureAlert, mLastPictureButton, mThumbController
// are non-null only if isImageCaptureIntent() is true.
private ImageView mLastPictureButton;
private ThumbnailController mThumbController;
// mCropValue and mSaveUri are used only if isImageCaptureIntent() is true.
private String mCropValue;
private Uri mSaveUri;
private ImageCapture mImageCapture = null;
private boolean mPreviewing;
private boolean mPausing;
private boolean mFirstTimeInitialized;
private boolean mIsImageCaptureIntent;
private boolean mRecordLocation;
private static final int FOCUS_NOT_STARTED = 0;
private static final int FOCUSING = 1;
private static final int FOCUSING_SNAP_ON_FINISH = 2;
private static final int FOCUS_SUCCESS = 3;
private static final int FOCUS_FAIL = 4;
private int mFocusState = FOCUS_NOT_STARTED;
private ContentResolver mContentResolver;
private boolean mDidRegister = false;
private final ArrayList<MenuItem> mGalleryItems = new ArrayList<MenuItem>();
private LocationManager mLocationManager = null;
private final ShutterCallback mShutterCallback = new ShutterCallback();
private final PostViewPictureCallback mPostViewPictureCallback =
new PostViewPictureCallback();
private final RawPictureCallback mRawPictureCallback =
new RawPictureCallback();
private final AutoFocusCallback mAutoFocusCallback =
new AutoFocusCallback();
private final ZoomListener mZoomListener = new ZoomListener();
// Use the ErrorCallback to capture the crash count
// on the mediaserver
private final ErrorCallback mErrorCallback = new ErrorCallback();
private long mFocusStartTime;
private long mFocusCallbackTime;
private long mCaptureStartTime;
private long mShutterCallbackTime;
private long mPostViewPictureCallbackTime;
private long mRawPictureCallbackTime;
private long mJpegPictureCallbackTime;
private int mPicturesRemaining;
// These latency time are for the CameraLatency test.
public long mAutoFocusTime;
public long mShutterLag;
public long mShutterToPictureDisplayedTime;
public long mPictureDisplayedToJpegCallbackTime;
public long mJpegCallbackFinishTime;
// Add for test
public static boolean mMediaServerDied = false;
// Focus mode. Options are pref_camera_focusmode_entryvalues.
private String mFocusMode;
private String mSceneMode;
private final Handler mHandler = new MainHandler();
private CameraHeadUpDisplay mHeadUpDisplay;
// multiple cameras support
private int mNumberOfCameras;
private int mCameraId;
/**
* This Handler is used to post message back onto the main thread of the
* application
*/
private class MainHandler extends Handler {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case RESTART_PREVIEW: {
restartPreview();
if (mJpegPictureCallbackTime != 0) {
long now = System.currentTimeMillis();
mJpegCallbackFinishTime = now - mJpegPictureCallbackTime;
Log.v(TAG, "mJpegCallbackFinishTime = "
+ mJpegCallbackFinishTime + "ms");
mJpegPictureCallbackTime = 0;
}
break;
}
case CLEAR_SCREEN_DELAY: {
getWindow().clearFlags(
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
break;
}
case FIRST_TIME_INIT: {
initializeFirstTime();
break;
}
case SET_CAMERA_PARAMETERS_WHEN_IDLE: {
setCameraParametersWhenIdle(0);
break;
}
}
}
}
private void resetExposureCompensation() {
String value = mPreferences.getString(CameraSettings.KEY_EXPOSURE,
CameraSettings.EXPOSURE_DEFAULT_VALUE);
if (!CameraSettings.EXPOSURE_DEFAULT_VALUE.equals(value)) {
Editor editor = mPreferences.edit();
editor.putString(CameraSettings.KEY_EXPOSURE, "0");
editor.apply();
if (mHeadUpDisplay != null) {
mHeadUpDisplay.reloadPreferences();
}
}
}
private void keepMediaProviderInstance() {
// We want to keep a reference to MediaProvider in camera's lifecycle.
// TODO: Utilize mMediaProviderClient instance to replace
// ContentResolver calls.
if (mMediaProviderClient == null) {
mMediaProviderClient = getContentResolver()
.acquireContentProviderClient(MediaStore.AUTHORITY);
}
}
// Snapshots can only be taken after this is called. It should be called
// once only. We could have done these things in onCreate() but we want to
// make preview screen appear as soon as possible.
private void initializeFirstTime() {
if (mFirstTimeInitialized) return;
// Create orientation listenter. This should be done first because it
// takes some time to get first orientation.
mOrientationListener = new MyOrientationEventListener(Camera.this);
mOrientationListener.enable();
// Initialize location sevice.
mLocationManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
mRecordLocation = RecordLocationPreference.get(
mPreferences, getContentResolver());
if (mRecordLocation) startReceivingLocationUpdates();
keepMediaProviderInstance();
checkStorage();
// Initialize last picture button.
mContentResolver = getContentResolver();
if (!mIsImageCaptureIntent) {
findViewById(R.id.camera_switch).setOnClickListener(this);
mLastPictureButton =
(ImageView) findViewById(R.id.review_thumbnail);
mLastPictureButton.setOnClickListener(this);
mThumbController = new ThumbnailController(
getResources(), mLastPictureButton, mContentResolver);
mThumbController.loadData(ImageManager.getLastImageThumbPath());
// Update last image thumbnail.
updateThumbnailButton();
}
// Initialize shutter button.
mShutterButton = (ShutterButton) findViewById(R.id.shutter_button);
mShutterButton.setOnShutterButtonListener(this);
mShutterButton.setVisibility(View.VISIBLE);
mFocusRectangle = (FocusRectangle) findViewById(R.id.focus_rectangle);
updateFocusIndicator();
initializeScreenBrightness();
installIntentFilter();
initializeFocusTone();
initializeZoom();
mHeadUpDisplay = new CameraHeadUpDisplay(this);
mHeadUpDisplay.setListener(new MyHeadUpDisplayListener());
initializeHeadUpDisplay();
mFirstTimeInitialized = true;
changeHeadUpDisplayState();
addIdleHandler();
}
private void addIdleHandler() {
MessageQueue queue = Looper.myQueue();
queue.addIdleHandler(new MessageQueue.IdleHandler() {
public boolean queueIdle() {
ImageManager.ensureOSXCompatibleFolder();
return false;
}
});
}
private void updateThumbnailButton() {
// Update last image if URI is invalid and the storage is ready.
if (!mThumbController.isUriValid() && mPicturesRemaining >= 0) {
updateLastImage();
}
mThumbController.updateDisplayIfNeeded();
}
// If the activity is paused and resumed, this method will be called in
// onResume.
private void initializeSecondTime() {
// Start orientation listener as soon as possible because it takes
// some time to get first orientation.
mOrientationListener.enable();
// Start location update if needed.
mRecordLocation = RecordLocationPreference.get(
mPreferences, getContentResolver());
if (mRecordLocation) startReceivingLocationUpdates();
installIntentFilter();
initializeFocusTone();
initializeZoom();
changeHeadUpDisplayState();
keepMediaProviderInstance();
checkStorage();
if (!mIsImageCaptureIntent) {
updateThumbnailButton();
}
}
private void initializeZoom() {
if (!mParameters.isZoomSupported()) return;
mZoomMax = mParameters.getMaxZoom();
mSmoothZoomSupported = mParameters.isSmoothZoomSupported();
mGestureDetector = new GestureDetector(this, new ZoomGestureListener());
mCameraDevice.setZoomChangeListener(mZoomListener);
}
private void onZoomValueChanged(int index) {
if (mSmoothZoomSupported) {
if (mTargetZoomValue != index && mZoomState != ZOOM_STOPPED) {
mTargetZoomValue = index;
if (mZoomState == ZOOM_START) {
mZoomState = ZOOM_STOPPING;
mCameraDevice.stopSmoothZoom();
}
} else if (mZoomState == ZOOM_STOPPED && mZoomValue != index) {
mTargetZoomValue = index;
mCameraDevice.startSmoothZoom(index);
mZoomState = ZOOM_START;
}
} else {
mZoomValue = index;
setCameraParametersWhenIdle(UPDATE_PARAM_ZOOM);
}
}
private float[] getZoomRatios() {
if(!mParameters.isZoomSupported()) return null;
List<Integer> zoomRatios = mParameters.getZoomRatios();
float result[] = new float[zoomRatios.size()];
for (int i = 0, n = result.length; i < n; ++i) {
result[i] = (float) zoomRatios.get(i) / 100f;
}
return result;
}
private class ZoomGestureListener extends
GestureDetector.SimpleOnGestureListener {
@Override
public boolean onDoubleTap(MotionEvent e) {
// Perform zoom only when preview is started and snapshot is not in
// progress.
if (mPausing || !isCameraIdle() || !mPreviewing
|| mZoomState != ZOOM_STOPPED) {
return false;
}
if (mZoomValue < mZoomMax) {
// Zoom in to the maximum.
mZoomValue = mZoomMax;
} else {
mZoomValue = 0;
}
setCameraParametersWhenIdle(UPDATE_PARAM_ZOOM);
mHeadUpDisplay.setZoomIndex(mZoomValue);
return true;
}
}
@Override
public boolean dispatchTouchEvent(MotionEvent m) {
if (!super.dispatchTouchEvent(m) && mGestureDetector != null) {
return mGestureDetector.onTouchEvent(m);
}
return true;
}
LocationListener [] mLocationListeners = new LocationListener[] {
new LocationListener(LocationManager.GPS_PROVIDER),
new LocationListener(LocationManager.NETWORK_PROVIDER)
};
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_MEDIA_MOUNTED)
|| action.equals(Intent.ACTION_MEDIA_UNMOUNTED)
|| action.equals(Intent.ACTION_MEDIA_CHECKING)) {
checkStorage();
} else if (action.equals(Intent.ACTION_MEDIA_SCANNER_FINISHED)) {
checkStorage();
if (!mIsImageCaptureIntent) {
updateThumbnailButton();
}
}
}
};
private class LocationListener
implements android.location.LocationListener {
Location mLastLocation;
boolean mValid = false;
String mProvider;
public LocationListener(String provider) {
mProvider = provider;
mLastLocation = new Location(mProvider);
}
public void onLocationChanged(Location newLocation) {
if (newLocation.getLatitude() == 0.0
&& newLocation.getLongitude() == 0.0) {
// Hack to filter out 0.0,0.0 locations
return;
}
// If GPS is available before start camera, we won't get status
// update so update GPS indicator when we receive data.
if (mRecordLocation
&& LocationManager.GPS_PROVIDER.equals(mProvider)) {
if (mHeadUpDisplay != null) {
mHeadUpDisplay.setGpsHasSignal(true);
}
}
mLastLocation.set(newLocation);
mValid = true;
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
mValid = false;
}
public void onStatusChanged(
String provider, int status, Bundle extras) {
switch(status) {
case LocationProvider.OUT_OF_SERVICE:
case LocationProvider.TEMPORARILY_UNAVAILABLE: {
mValid = false;
if (mRecordLocation &&
LocationManager.GPS_PROVIDER.equals(provider)) {
if (mHeadUpDisplay != null) {
mHeadUpDisplay.setGpsHasSignal(false);
}
}
break;
}
}
}
public Location current() {
return mValid ? mLastLocation : null;
}
}
private final class ShutterCallback
implements android.hardware.Camera.ShutterCallback {
public void onShutter() {
mShutterCallbackTime = System.currentTimeMillis();
mShutterLag = mShutterCallbackTime - mCaptureStartTime;
Log.v(TAG, "mShutterLag = " + mShutterLag + "ms");
clearFocusState();
}
}
private final class PostViewPictureCallback implements PictureCallback {
public void onPictureTaken(
byte [] data, android.hardware.Camera camera) {
mPostViewPictureCallbackTime = System.currentTimeMillis();
Log.v(TAG, "mShutterToPostViewCallbackTime = "
+ (mPostViewPictureCallbackTime - mShutterCallbackTime)
+ "ms");
}
}
private final class RawPictureCallback implements PictureCallback {
public void onPictureTaken(
byte [] rawData, android.hardware.Camera camera) {
mRawPictureCallbackTime = System.currentTimeMillis();
Log.v(TAG, "mShutterToRawCallbackTime = "
+ (mRawPictureCallbackTime - mShutterCallbackTime) + "ms");
}
}
private final class JpegPictureCallback implements PictureCallback {
Location mLocation;
public JpegPictureCallback(Location loc) {
mLocation = loc;
}
public void onPictureTaken(
final byte [] jpegData, final android.hardware.Camera camera) {
if (mPausing) {
return;
}
mJpegPictureCallbackTime = System.currentTimeMillis();
// If postview callback has arrived, the captured image is displayed
// in postview callback. If not, the captured image is displayed in
// raw picture callback.
if (mPostViewPictureCallbackTime != 0) {
mShutterToPictureDisplayedTime =
mPostViewPictureCallbackTime - mShutterCallbackTime;
mPictureDisplayedToJpegCallbackTime =
mJpegPictureCallbackTime - mPostViewPictureCallbackTime;
} else {
mShutterToPictureDisplayedTime =
mRawPictureCallbackTime - mShutterCallbackTime;
mPictureDisplayedToJpegCallbackTime =
mJpegPictureCallbackTime - mRawPictureCallbackTime;
}
Log.v(TAG, "mPictureDisplayedToJpegCallbackTime = "
+ mPictureDisplayedToJpegCallbackTime + "ms");
mHeadUpDisplay.setEnabled(true);
if (!mIsImageCaptureIntent) {
// We want to show the taken picture for a while, so we wait
// for at least 1.2 second before restarting the preview.
long delay = 1200 - mPictureDisplayedToJpegCallbackTime;
if (delay < 0) {
restartPreview();
} else {
mHandler.sendEmptyMessageDelayed(RESTART_PREVIEW, delay);
}
}
mImageCapture.storeImage(jpegData, camera, mLocation);
// Calculate this in advance of each shot so we don't add to shutter
// latency. It's true that someone else could write to the SD card in
// the mean time and fill it, but that could have happened between the
// shutter press and saving the JPEG too.
calculatePicturesRemaining();
if (mPicturesRemaining < 1) {
updateStorageHint(mPicturesRemaining);
}
if (!mHandler.hasMessages(RESTART_PREVIEW)) {
long now = System.currentTimeMillis();
mJpegCallbackFinishTime = now - mJpegPictureCallbackTime;
Log.v(TAG, "mJpegCallbackFinishTime = "
+ mJpegCallbackFinishTime + "ms");
mJpegPictureCallbackTime = 0;
}
}
}
private final class AutoFocusCallback
implements android.hardware.Camera.AutoFocusCallback {
public void onAutoFocus(
boolean focused, android.hardware.Camera camera) {
mFocusCallbackTime = System.currentTimeMillis();
mAutoFocusTime = mFocusCallbackTime - mFocusStartTime;
Log.v(TAG, "mAutoFocusTime = " + mAutoFocusTime + "ms");
if (mFocusState == FOCUSING_SNAP_ON_FINISH) {
// Take the picture no matter focus succeeds or fails. No need
// to play the AF sound if we're about to play the shutter
// sound.
if (focused) {
mFocusState = FOCUS_SUCCESS;
} else {
mFocusState = FOCUS_FAIL;
}
mImageCapture.onSnap();
} else if (mFocusState == FOCUSING) {
// User is half-pressing the focus key. Play the focus tone.
// Do not take the picture now.
ToneGenerator tg = mFocusToneGenerator;
if (tg != null) {
tg.startTone(ToneGenerator.TONE_PROP_BEEP2);
}
if (focused) {
mFocusState = FOCUS_SUCCESS;
} else {
mFocusState = FOCUS_FAIL;
}
} else if (mFocusState == FOCUS_NOT_STARTED) {
// User has released the focus key before focus completes.
// Do nothing.
}
updateFocusIndicator();
}
}
private static final class ErrorCallback
implements android.hardware.Camera.ErrorCallback {
public void onError(int error, android.hardware.Camera camera) {
if (error == android.hardware.Camera.CAMERA_ERROR_SERVER_DIED) {
mMediaServerDied = true;
Log.v(TAG, "media server died");
}
}
}
private final class ZoomListener
implements android.hardware.Camera.OnZoomChangeListener {
public void onZoomChange(
int value, boolean stopped, android.hardware.Camera camera) {
Log.v(TAG, "Zoom changed: value=" + value + ". stopped="+ stopped);
mZoomValue = value;
// Keep mParameters up to date. We do not getParameter again in
// takePicture. If we do not do this, wrong zoom value will be set.
mParameters.setZoom(value);
// We only care if the zoom is stopped. mZooming is set to true when
// we start smooth zoom.
if (stopped && mZoomState != ZOOM_STOPPED) {
if (value != mTargetZoomValue) {
mCameraDevice.startSmoothZoom(mTargetZoomValue);
mZoomState = ZOOM_START;
} else {
mZoomState = ZOOM_STOPPED;
}
}
}
}
private class ImageCapture {
private Uri mLastContentUri;
byte[] mCaptureOnlyData;
// Returns the rotation degree in the jpeg header.
private int storeImage(byte[] data, Location loc) {
try {
long dateTaken = System.currentTimeMillis();
String title = createName(dateTaken);
String filename = title + ".jpg";
int[] degree = new int[1];
mLastContentUri = ImageManager.addImage(
mContentResolver,
title,
dateTaken,
loc, // location from gps/network
ImageManager.CAMERA_IMAGE_BUCKET_NAME, filename,
null, data,
degree);
return degree[0];
} catch (Exception ex) {
Log.e(TAG, "Exception while compressing image.", ex);
return 0;
}
}
public void storeImage(final byte[] data,
android.hardware.Camera camera, Location loc) {
if (!mIsImageCaptureIntent) {
int degree = storeImage(data, loc);
sendBroadcast(new Intent(
"com.android.camera.NEW_PICTURE", mLastContentUri));
setLastPictureThumb(data, degree,
mImageCapture.getLastCaptureUri());
mThumbController.updateDisplayIfNeeded();
} else {
mCaptureOnlyData = data;
showPostCaptureAlert();
}
}
/**
* Initiate the capture of an image.
*/
public void initiate() {
if (mCameraDevice == null) {
return;
}
capture();
}
public Uri getLastCaptureUri() {
return mLastContentUri;
}
public byte[] getLastCaptureData() {
return mCaptureOnlyData;
}
private void capture() {
mCaptureOnlyData = null;
// See android.hardware.Camera.Parameters.setRotation for
// documentation.
int rotation = 0;
if (mOrientation != OrientationEventListener.ORIENTATION_UNKNOWN) {
CameraInfo info = CameraHolder.instance().getCameraInfo()[mCameraId];
if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {
rotation = (info.orientation - mOrientation + 360) % 360;
} else { // back-facing camera
rotation = (info.orientation + mOrientation) % 360;
}
}
mParameters.setRotation(rotation);
// Clear previous GPS location from the parameters.
mParameters.removeGpsData();
// We always encode GpsTimeStamp
mParameters.setGpsTimestamp(System.currentTimeMillis() / 1000);
// Set GPS location.
Location loc = mRecordLocation ? getCurrentLocation() : null;
if (loc != null) {
double lat = loc.getLatitude();
double lon = loc.getLongitude();
boolean hasLatLon = (lat != 0.0d) || (lon != 0.0d);
if (hasLatLon) {
mParameters.setGpsLatitude(lat);
mParameters.setGpsLongitude(lon);
mParameters.setGpsProcessingMethod(loc.getProvider().toUpperCase());
if (loc.hasAltitude()) {
mParameters.setGpsAltitude(loc.getAltitude());
} else {
// for NETWORK_PROVIDER location provider, we may have
// no altitude information, but the driver needs it, so
// we fake one.
mParameters.setGpsAltitude(0);
}
if (loc.getTime() != 0) {
// Location.getTime() is UTC in milliseconds.
// gps-timestamp is UTC in seconds.
long utcTimeSeconds = loc.getTime() / 1000;
mParameters.setGpsTimestamp(utcTimeSeconds);
}
} else {
loc = null;
}
}
mCameraDevice.setParameters(mParameters);
mCameraDevice.takePicture(mShutterCallback, mRawPictureCallback,
mPostViewPictureCallback, new JpegPictureCallback(loc));
mPreviewing = false;
}
public void onSnap() {
// If we are already in the middle of taking a snapshot then ignore.
if (mPausing || mStatus == SNAPSHOT_IN_PROGRESS) {
return;
}
mCaptureStartTime = System.currentTimeMillis();
mPostViewPictureCallbackTime = 0;
mHeadUpDisplay.setEnabled(false);
mStatus = SNAPSHOT_IN_PROGRESS;
mImageCapture.initiate();
}
private void clearLastData() {
mCaptureOnlyData = null;
}
}
private boolean saveDataToFile(String filePath, byte[] data) {
FileOutputStream f = null;
try {
f = new FileOutputStream(filePath);
f.write(data);
} catch (IOException e) {
return false;
} finally {
MenuHelper.closeSilently(f);
}
return true;
}
private void setLastPictureThumb(byte[] data, int degree, Uri uri) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 16;
Bitmap lastPictureThumb =
BitmapFactory.decodeByteArray(data, 0, data.length, options);
lastPictureThumb = Util.rotate(lastPictureThumb, degree);
mThumbController.setData(uri, lastPictureThumb);
}
private String createName(long dateTaken) {
Date date = new Date(dateTaken);
SimpleDateFormat dateFormat = new SimpleDateFormat(
getString(R.string.image_file_name_format));
return dateFormat.format(date);
}
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.camera);
mSurfaceView = (SurfaceView) findViewById(R.id.camera_preview);
mPreferences = new ComboPreferences(this);
CameraSettings.upgradeGlobalPreferences(mPreferences.getGlobal());
mCameraId = CameraSettings.readPreferredCameraId(mPreferences);
mPreferences.setLocalId(this, mCameraId);
CameraSettings.upgradeLocalPreferences(mPreferences.getLocal());
mNumberOfCameras = CameraHolder.instance().getNumberOfCameras();
// we need to reset exposure for the preview
resetExposureCompensation();
/*
* To reduce startup time, we start the preview in another thread.
* We make sure the preview is started at the end of onCreate.
*/
Thread startPreviewThread = new Thread(new Runnable() {
public void run() {
try {
mStartPreviewFail = false;
startPreview();
} catch (CameraHardwareException e) {
// In eng build, we throw the exception so that test tool
// can detect it and report it
if ("eng".equals(Build.TYPE)) {
throw new RuntimeException(e);
}
mStartPreviewFail = true;
}
}
});
startPreviewThread.start();
// don't set mSurfaceHolder here. We have it set ONLY within
// surfaceChanged / surfaceDestroyed, other parts of the code
// assume that when it is set, the surface is also set.
SurfaceHolder holder = mSurfaceView.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
mIsImageCaptureIntent = isImageCaptureIntent();
if (mIsImageCaptureIntent) {
setupCaptureParams();
}
LayoutInflater inflater = getLayoutInflater();
ViewGroup rootView = (ViewGroup) findViewById(R.id.camera);
if (mIsImageCaptureIntent) {
View controlBar = inflater.inflate(
R.layout.attach_camera_control, rootView);
controlBar.findViewById(R.id.btn_cancel).setOnClickListener(this);
controlBar.findViewById(R.id.btn_retake).setOnClickListener(this);
controlBar.findViewById(R.id.btn_done).setOnClickListener(this);
} else {
inflater.inflate(R.layout.camera_control, rootView);
mSwitcher = ((Switcher) findViewById(R.id.camera_switch));
mSwitcher.setOnSwitchListener(this);
mSwitcher.addTouchView(findViewById(R.id.camera_switch_set));
}
// Make sure preview is started.
try {
startPreviewThread.join();
if (mStartPreviewFail) {
showCameraErrorAndFinish();
return;
}
} catch (InterruptedException ex) {
// ignore
}
}
private void changeHeadUpDisplayState() {
// If the camera resumes behind the lock screen, the orientation
// will be portrait. That causes OOM when we try to allocation GPU
// memory for the GLSurfaceView again when the orientation changes. So,
// we delayed initialization of HeadUpDisplay until the orientation
// becomes landscape.
Configuration config = getResources().getConfiguration();
if (config.orientation == Configuration.ORIENTATION_LANDSCAPE
&& !mPausing && mFirstTimeInitialized) {
if (mGLRootView == null) attachHeadUpDisplay();
} else if (mGLRootView != null) {
detachHeadUpDisplay();
}
}
private void overrideHudSettings(final String flashMode,
final String whiteBalance, final String focusMode) {
mHeadUpDisplay.overrideSettings(
CameraSettings.KEY_FLASH_MODE, flashMode,
CameraSettings.KEY_WHITE_BALANCE, whiteBalance,
CameraSettings.KEY_FOCUS_MODE, focusMode);
}
private void updateSceneModeInHud() {
// If scene mode is set, we cannot set flash mode, white balance, and
// focus mode, instead, we read it from driver
if (!Parameters.SCENE_MODE_AUTO.equals(mSceneMode)) {
overrideHudSettings(mParameters.getFlashMode(),
mParameters.getWhiteBalance(), mParameters.getFocusMode());
} else {
overrideHudSettings(null, null, null);
}
}
private void initializeHeadUpDisplay() {
CameraSettings settings = new CameraSettings(this, mInitialParams,
CameraHolder.instance().getCameraInfo());
mHeadUpDisplay.initialize(this,
settings.getPreferenceGroup(R.xml.camera_preferences),
getZoomRatios(), mOrientationCompensation);