/
TiCameraActivity.java
714 lines (620 loc) Β· 19.5 KB
/
TiCameraActivity.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
/**
* Appcelerator Titanium Mobile
* Copyright (c) 2012-2013 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Apache Public License
* Please see the LICENSE included with this distribution for details.
*/
package ti.modules.titanium.media;
import java.io.File;
import java.io.FileOutputStream;
import java.util.List;
import org.appcelerator.kroll.KrollDict;
import org.appcelerator.kroll.KrollFunction;
import org.appcelerator.kroll.KrollObject;
import org.appcelerator.kroll.common.Log;
import org.appcelerator.titanium.TiApplication;
import org.appcelerator.titanium.TiBaseActivity;
import org.appcelerator.titanium.TiBlob;
import org.appcelerator.titanium.TiC;
import org.appcelerator.titanium.io.TiFile;
import org.appcelerator.titanium.io.TiFileFactory;
import org.appcelerator.titanium.proxy.TiViewProxy;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.CameraInfo;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;
import android.hardware.Camera.Size;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.FrameLayout;
@SuppressWarnings("deprecation")
public class TiCameraActivity extends TiBaseActivity implements SurfaceHolder.Callback
{
private static final String TAG = "TiCameraActivity";
private static Camera camera;
private static Size optimalPreviewSize;
private static List<Size> supportedPreviewSizes;
private static int frontCameraId = Integer.MIN_VALUE; // cache
private static int backCameraId = Integer.MIN_VALUE; //cache
private TiViewProxy localOverlayProxy = null;
private SurfaceView preview;
private PreviewLayout previewLayout;
private FrameLayout cameraLayout;
private boolean previewRunning = false;
private int currentRotation;
public static TiViewProxy overlayProxy = null;
public static TiCameraActivity cameraActivity = null;
public static KrollObject callbackContext;
public static KrollFunction successCallback, errorCallback, cancelCallback;
public static boolean saveToPhotoGallery = false;
public static int whichCamera = MediaModule.CAMERA_REAR;
public static int cameraFlashMode = MediaModule.CAMERA_FLASH_OFF;
public static boolean autohide = true;
private static class PreviewLayout extends FrameLayout
{
private double aspectRatio = 1;
private Runnable runAfterMeasure;
public PreviewLayout(Context context)
{
super(context);
}
protected void prepareNewPreview(Runnable runnable)
{
runAfterMeasure = runnable;
this.post(new Runnable()
{
@Override
public void run()
{
PreviewLayout.this.requestLayout();
PreviewLayout.this.invalidate();
}
});
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
int previewWidth = MeasureSpec.getSize(widthMeasureSpec);
int previewHeight = MeasureSpec.getSize(heightMeasureSpec);
// Set the preview size to the most optimal given the target size
optimalPreviewSize = getOptimalPreviewSize(supportedPreviewSizes, previewWidth, previewHeight);
if (optimalPreviewSize != null) {
if (previewWidth > previewHeight) {
aspectRatio = (double) optimalPreviewSize.width / optimalPreviewSize.height;
} else {
aspectRatio = (double) optimalPreviewSize.height / optimalPreviewSize.width;
}
}
if (previewHeight < previewWidth / aspectRatio) {
previewHeight = (int) (previewWidth / aspectRatio + .5);
} else {
previewWidth = (int) (previewHeight * aspectRatio + .5);
}
super.onMeasure(MeasureSpec.makeMeasureSpec(previewWidth,
MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(
previewHeight, MeasureSpec.EXACTLY));
if (runAfterMeasure != null) {
final Runnable run = runAfterMeasure;
runAfterMeasure = null;
this.post(run);
}
}
}
@Override
public void onCreate(Bundle savedInstanceState)
{
setFullscreen(true);
super.onCreate(savedInstanceState);
// checks if device has only front facing camera and sets it
checkWhichCameraAsDefault();
// create camera preview
preview = new SurfaceView(this);
SurfaceHolder previewHolder = preview.getHolder();
previewHolder.addCallback(this);
previewHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
// set preview overlay
localOverlayProxy = overlayProxy;
// set overall layout - will populate in onResume
previewLayout = new PreviewLayout(this);
cameraLayout = new FrameLayout(this);
cameraLayout.setBackgroundColor(Color.BLACK);
cameraLayout.addView(previewLayout, new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT, Gravity.CENTER));
setContentView(cameraLayout);
}
public void surfaceChanged(SurfaceHolder previewHolder, int format, int width, int height)
{
startPreview(previewHolder);
}
public void surfaceCreated(SurfaceHolder previewHolder)
{
try {
camera.setPreviewDisplay(previewHolder);
} catch (Exception e) {
onError(MediaModule.UNKNOWN_ERROR, "Unable to setup preview surface: " + e.getMessage());
cancelCallback = null;
finish();
return;
}
currentRotation = getWindowManager().getDefaultDisplay().getRotation();
}
// make sure to call release() otherwise you will have to force kill the app before
// the built in camera will open
public void surfaceDestroyed(SurfaceHolder previewHolder)
{
stopPreview();
if (camera != null) {
camera.release();
camera = null;
}
}
@Override
protected void onResume()
{
super.onResume();
if (camera == null) {
if (whichCamera == MediaModule.CAMERA_FRONT) {
openCamera(getFrontCameraId());
} else {
openCamera();
}
}
if (camera != null) {
setFlashMode(cameraFlashMode);
}
if (camera == null) {
return; // openCamera will have logged error.
}
try {
//This needs to be called to make sure action bar is gone
if (android.os.Build.VERSION.SDK_INT < 11) {
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.hide();
}
}
} catch(Throwable t) {
//Ignore this
}
cameraActivity = this;
previewLayout.addView(preview, new FrameLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
View overlayView = localOverlayProxy.getOrCreateView().getNativeView();
ViewGroup parent = (ViewGroup) overlayView.getParent();
// Detach from the parent if applicable
if (parent != null) {
parent.removeView(overlayView);
}
cameraLayout.addView(overlayView, new FrameLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
}
public static void setFlashMode(int cameraFlashMode)
{
TiCameraActivity.cameraFlashMode = cameraFlashMode;
if (camera != null) {
try {
Parameters p = camera.getParameters();
if (cameraFlashMode == MediaModule.CAMERA_FLASH_OFF) {
p.setFlashMode(Parameters.FLASH_MODE_OFF);
} else if (cameraFlashMode == MediaModule.CAMERA_FLASH_ON) {
p.setFlashMode(Parameters.FLASH_MODE_ON);
} else if (cameraFlashMode == MediaModule.CAMERA_FLASH_AUTO) {
p.setFlashMode(Parameters.FLASH_MODE_AUTO);
}
camera.setParameters(p);
} catch (Throwable t) {
Log.e(TAG, "Could not set flash mode", t);
}
}
}
@Override
protected void onPause(){
super.onPause();
stopPreview();
previewLayout.removeView(preview);
cameraLayout.removeView(localOverlayProxy.getOrCreateView().getNativeView());
try {
camera.release();
camera = null;
} catch (Throwable t) {
Log.d(TAG, "Camera is not open, unable to release", Log.DEBUG_MODE);
}
cameraActivity = null;
}
private void startPreview(SurfaceHolder previewHolder)
{
if (camera == null) {
return;
}
int rotation = getWindowManager().getDefaultDisplay().getRotation();
if (currentRotation == rotation && previewRunning) {
return;
}
if (previewRunning) {
try {
camera.stopPreview();
} catch (Exception e) {
// ignore: tried to stop a non=existent preview
}
}
//Set the proper display orientation
int cameraId = Integer.MIN_VALUE;
if (whichCamera == MediaModule.CAMERA_FRONT) {
cameraId = TiCameraActivity.getFrontCameraId();
} else {
cameraId = TiCameraActivity.getBackCameraId();
}
CameraInfo info = new Camera.CameraInfo();
Camera.getCameraInfo(cameraId, info);
currentRotation = rotation;
//Clockwise and anticlockwise
int degrees = 0, degrees2 = 0;
//Let Camera display in same orientation as display
switch (currentRotation) {
case Surface.ROTATION_0: degrees = degrees2 = 0; break;
case Surface.ROTATION_180: degrees = degrees2 = 180; break;
case Surface.ROTATION_90: {degrees = 90; degrees2 = 270; } break;
case Surface.ROTATION_270: {degrees = 270; degrees2 = 90;} break;
}
int result, result2;
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
result = (info.orientation + degrees) % 360;
result = (360 - result) % 360; // compensate the mirror
} else { // back-facing
result = (info.orientation - degrees + 360) % 360;
}
//Set up Camera Rotation so jpegCallback has correctly rotated image
Parameters param = camera.getParameters();
if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {
result2 = (info.orientation - degrees2 + 360) % 360;
} else { // back-facing camera
result2 = (info.orientation + degrees2) % 360;
}
camera.setDisplayOrientation(result);
param.setRotation(result2);
// Set appropriate focus mode if supported.
List<String> supportedFocusModes = param.getSupportedFocusModes();
if (supportedFocusModes.contains(MediaModule.FOCUS_MODE_CONTINUOUS_PICTURE)) {
param.setFocusMode(MediaModule.FOCUS_MODE_CONTINUOUS_PICTURE);
} else if (supportedFocusModes.contains(Parameters.FOCUS_MODE_AUTO)) {
param.setFocusMode(Parameters.FOCUS_MODE_AUTO);
} else if (supportedFocusModes.contains(Parameters.FOCUS_MODE_MACRO)) {
param.setFocusMode(Parameters.FOCUS_MODE_MACRO);
}
if (optimalPreviewSize != null) {
param.setPreviewSize(optimalPreviewSize.width, optimalPreviewSize.height);
List<Size> pictSizes = param.getSupportedPictureSizes();
Size pictureSize = getOptimalPictureSize(pictSizes);
if (pictureSize != null) {
param.setPictureSize(pictureSize.width, pictureSize.height);
}
}
camera.setParameters(param);
try {
camera.setPreviewDisplay(previewHolder);
previewRunning = true;
camera.startPreview();
} catch (Exception e) {
onError(MediaModule.UNKNOWN_ERROR, "Unable to setup preview surface: " + e.getMessage());
finish();
return;
}
}
private void stopPreview()
{
if (camera == null || !previewRunning) {
return;
}
camera.stopPreview();
previewRunning = false;
}
@Override
public void finish()
{
// For API 10 and above, the whole activity gets destroyed during an orientation change. We only want to set
// overlayProxy to null when we call finish, i.e. when we hide the camera or take a picture. By doing this, the
// overlay proxy will be available during the recreation of the activity during an orientation change.
overlayProxy = null;
super.finish();
}
/**
* Computes the optimal preview size given the target display size and aspect ratio.
*
* @param supportPreviewSizes
* a list of preview sizes the camera supports
* @param targetSize
* the target display size that will render the preview
* @return the optimal size of the preview
*/
private static Size getOptimalPreviewSize(List<Size> sizes, int w, int h)
{
double targetRatio = 1;
if (w > h) {
targetRatio = (double) w / h;
} else {
targetRatio = (double) h / w;
}
if (sizes == null) {
return null;
}
Size optimalSize = null;
double minAspectDiff = Double.MAX_VALUE;
// Try to find an size match aspect ratio and size
for (Size size : sizes) {
double ratio = (double) size.width / size.height;
if (Math.abs(ratio - targetRatio) < minAspectDiff) {
optimalSize = size;
minAspectDiff = Math.abs(ratio - targetRatio);
}
}
return optimalSize;
}
/**
* Computes the optimal picture size given the preview size.
* This returns the maximum resolution size.
*
* @param sizes
* a list of picture sizes the camera supports
* @return the optimal size of the picture
*/
private static Size getOptimalPictureSize(List<Size> sizes)
{
if (sizes == null) {
return null;
}
Size optimalSize = null;
long resolution = 0;
for (Size size : sizes) {
if (size.width * size.height > resolution) {
optimalSize = size;
resolution = size.width * size.height;
}
}
return optimalSize;
}
private static void onError(int code, String message)
{
if (errorCallback == null) {
Log.e(TAG, message);
return;
}
KrollDict dict = new KrollDict();
dict.putCodeAndMessage(code, message);
dict.put(TiC.PROPERTY_MESSAGE, message);
errorCallback.callAsync(callbackContext, dict);
}
private static File writeToFile(byte[] data, boolean saveToGallery) throws Throwable
{
try
{
File imageFile = null;
if (saveToGallery) {
imageFile = MediaModule.createGalleryImageFile();
} else {
// Save the picture in the internal data directory so it is private to this application.
imageFile = TiFileFactory.createDataFile("tia", ".jpg");
}
FileOutputStream imageOut = new FileOutputStream(imageFile);
imageOut.write(data);
imageOut.close();
if (saveToGallery) {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = Uri.fromFile(imageFile);
mediaScanIntent.setData(contentUri);
Activity activity = TiApplication.getAppCurrentActivity();
activity.sendBroadcast(mediaScanIntent);
}
return imageFile;
} catch (Throwable t) {
throw t;
}
}
static public void takePicture()
{
String focusMode = camera.getParameters().getFocusMode();
if (!(focusMode.equals(Parameters.FOCUS_MODE_EDOF) || focusMode.equals(Parameters.FOCUS_MODE_FIXED) || focusMode
.equals(Parameters.FOCUS_MODE_INFINITY))) {
AutoFocusCallback focusCallback = new AutoFocusCallback()
{
public void onAutoFocus(boolean success, Camera camera)
{
camera.takePicture(shutterCallback, null, jpegCallback);
if (!success) {
Log.w(TAG, "Unable to focus.");
}
camera.cancelAutoFocus();
}
};
camera.autoFocus(focusCallback);
} else {
camera.takePicture(shutterCallback, null, jpegCallback);
}
}
public boolean isPreviewRunning()
{
return this.previewRunning;
}
static public void hide()
{
cameraActivity.setResult(Activity.RESULT_OK);
cameraActivity.finish();
}
static ShutterCallback shutterCallback = new ShutterCallback()
{
// Just the presence of a shutter callback will
// allow the shutter click sound to occur (at least
// on Jelly Bean on a stock Google phone, which
// was remaining silent without this.)
@Override
public void onShutter()
{
// No-op
}
};
static PictureCallback jpegCallback = new PictureCallback()
{
public void onPictureTaken(byte[] data, Camera camera)
{
try {
File imageFile = writeToFile(data, saveToPhotoGallery);
if (successCallback != null) {
TiFile theFile = new TiFile(imageFile, imageFile.toURI().toURL().toExternalForm(), false);
TiBlob theBlob = TiBlob.blobFromFile(theFile);
KrollDict response = MediaModule.createDictForImage(theBlob, theBlob.getMimeType());
successCallback.callAsync(callbackContext, response);
}
} catch (Throwable t) {
if (errorCallback != null) {
KrollDict response = new KrollDict();
response.putCodeAndMessage(MediaModule.UNKNOWN_ERROR, t.getMessage());
errorCallback.callAsync(callbackContext, response);
}
}
if (autohide) {
cameraActivity.finish();
} else {
camera.startPreview();
}
}
};
private void checkWhichCameraAsDefault(){
// This is to check if device has only front facing camera
// TIMOB-15812: Fix for Devices like Nexus 7 (2012) that only
// has front facing camera and no rear camera.
TiCameraActivity.getFrontCameraId();
TiCameraActivity.getBackCameraId();
if (backCameraId == Integer.MIN_VALUE && frontCameraId != Integer.MIN_VALUE) {
TiCameraActivity.whichCamera = MediaModule.CAMERA_FRONT;
} else {
TiCameraActivity.whichCamera = MediaModule.CAMERA_REAR;
}
}
private static int getFrontCameraId()
{
if (frontCameraId == Integer.MIN_VALUE) {
int count = Camera.getNumberOfCameras();
for (int i = 0; i < count; i++) {
CameraInfo info = new CameraInfo();
Camera.getCameraInfo(i, info);
if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {
frontCameraId = i;
break;
}
}
}
return frontCameraId;
}
private static int getBackCameraId()
{
if (backCameraId == Integer.MIN_VALUE) {
int count = Camera.getNumberOfCameras();
for (int i = 0; i < count; i++) {
CameraInfo info = new CameraInfo();
Camera.getCameraInfo(i, info);
if (info.facing == CameraInfo.CAMERA_FACING_BACK) {
backCameraId = i;
break;
}
}
}
return backCameraId;
}
private void openCamera()
{
openCamera(Integer.MIN_VALUE);
}
private void openCamera(int cameraId)
{
if (previewRunning) {
stopPreview();
}
if (camera != null) {
camera.release();
camera = null;
}
if (cameraId == Integer.MIN_VALUE) {
camera = Camera.open();
} else {
camera = Camera.open(cameraId);
}
if (camera == null) {
onError(MediaModule.UNKNOWN_ERROR, "Unable to access the camera.");
finish();
return;
}
supportedPreviewSizes = camera.getParameters()
.getSupportedPreviewSizes();
optimalPreviewSize = null; // Re-calc'd in PreviewLayout.onMeasure.
}
protected void switchCamera(int whichCamera)
{
boolean front = whichCamera == MediaModule.CAMERA_FRONT;
int frontId = Integer.MIN_VALUE; // no-val
if (front) {
frontId = getFrontCameraId();
if (frontId == Integer.MIN_VALUE) {
Log.e(TAG,
"switchCamera cancelled because this device has no front camera.");
return;
}
}
TiCameraActivity.whichCamera = whichCamera;
if (front) {
openCamera(frontId);
} else {
openCamera();
}
if (camera == null) {
return;
}
// Force the onMeasure of PreviewLayout, so aspect ratio, best
// dimensions, etc. can be setup for camera preview. And specify
// a runnable that will be called after the previewLayout
// measures. The runnable will start the camera preview.
// This all guarantees us that the camera preview won't start until
// after the layout has been measured.
previewLayout.prepareNewPreview(new Runnable()
{
@Override
public void run()
{
startPreview(preview.getHolder());
}
});
}
@Override
public void onBackPressed()
{
if (cancelCallback != null) {
KrollDict response = new KrollDict();
response.putCodeAndMessage(-1, "User cancelled the request");
cancelCallback.callAsync(callbackContext, response);
}
super.onBackPressed();
}
@Override
public boolean onKeyDown (int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_MENU) {
//Workaround for http://code.google.com/p/android/issues/detail?id=61394
//Exists atleast till version 19.1 of support library
return true;
}
return super.onKeyDown(keyCode, event);
}
}