capacitor-community-multilens-camerapreview 0.0.4 → 0.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/CapacitorCommunityMultilensCamerapreview.podspec +17 -17
  2. package/README.md +16 -16
  3. package/android/build.gradle +55 -55
  4. package/android/src/main/AndroidManifest.xml +4 -4
  5. package/android/src/main/java/com/ahm/capacitor/camera/preview/CameraActivity.java +1006 -1005
  6. package/android/src/main/java/com/ahm/capacitor/camera/preview/CameraPreview.java +544 -544
  7. package/android/src/main/java/com/ahm/capacitor/camera/preview/CustomSurfaceView.java +23 -23
  8. package/android/src/main/java/com/ahm/capacitor/camera/preview/CustomTextureView.java +29 -29
  9. package/android/src/main/java/com/ahm/capacitor/camera/preview/Preview.java +386 -386
  10. package/android/src/main/java/com/ahm/capacitor/camera/preview/TapGestureDetector.java +24 -24
  11. package/android/src/main/res/layout/bridge_layout_main.xml +15 -15
  12. package/android/src/main/res/layout/camera_activity.xml +68 -68
  13. package/android/src/main/res/values/camera_ids.xml +4 -4
  14. package/android/src/main/res/values/camera_theme.xml +9 -9
  15. package/android/src/main/res/values/colors.xml +3 -3
  16. package/android/src/main/res/values/strings.xml +3 -3
  17. package/android/src/main/res/values/styles.xml +3 -3
  18. package/dist/docs.json +1 -1
  19. package/dist/esm/definitions.d.ts +80 -80
  20. package/dist/esm/definitions.js +1 -1
  21. package/dist/esm/definitions.js.map +1 -1
  22. package/dist/esm/index.d.ts +4 -4
  23. package/dist/esm/index.js +6 -6
  24. package/dist/esm/index.js.map +1 -1
  25. package/dist/esm/web.d.ts +28 -28
  26. package/dist/esm/web.js +155 -155
  27. package/dist/esm/web.js.map +1 -1
  28. package/dist/plugin.cjs.js +149 -149
  29. package/dist/plugin.cjs.js.map +1 -1
  30. package/dist/plugin.js +149 -149
  31. package/dist/plugin.js.map +1 -1
  32. package/ios/Plugin/CameraController.swift +716 -716
  33. package/ios/Plugin/Info.plist +24 -24
  34. package/ios/Plugin/Plugin.h +10 -10
  35. package/ios/Plugin/Plugin.m +18 -18
  36. package/ios/Plugin/Plugin.swift +300 -308
  37. package/package.json +78 -78
@@ -1,1005 +1,1006 @@
1
- package com.ahm.capacitor.camera.preview;
2
-
3
- import android.app.Activity;
4
- import android.app.Fragment;
5
- import android.content.Context;
6
- import android.content.pm.PackageManager;
7
- import android.content.res.Configuration;
8
- import android.graphics.Bitmap;
9
- import android.graphics.Bitmap.CompressFormat;
10
- import android.graphics.BitmapFactory;
11
- import android.graphics.Canvas;
12
- import android.graphics.ImageFormat;
13
- import android.graphics.Matrix;
14
- import android.graphics.Rect;
15
- import android.graphics.YuvImage;
16
- import android.hardware.Camera;
17
- import android.hardware.Camera.PictureCallback;
18
- import android.hardware.Camera.ShutterCallback;
19
- import android.hardware.camera2.CameraManager;
20
- import android.media.AudioManager;
21
- import android.media.CamcorderProfile;
22
- import android.media.MediaRecorder;
23
- import android.os.Bundle;
24
- import android.util.Base64;
25
- import android.util.DisplayMetrics;
26
- import android.util.Log;
27
- import android.view.GestureDetector;
28
- import android.view.Gravity;
29
- import android.view.LayoutInflater;
30
- import android.view.MotionEvent;
31
- import android.view.Surface;
32
- import android.view.Surface;
33
- import android.view.SurfaceHolder;
34
- import android.view.SurfaceView;
35
- import android.view.View;
36
- import android.view.ViewGroup;
37
- import android.view.ViewTreeObserver;
38
- import android.widget.FrameLayout;
39
- import android.widget.RelativeLayout;
40
- import androidx.exifinterface.media.ExifInterface;
41
- import java.io.ByteArrayInputStream;
42
- import java.io.ByteArrayOutputStream;
43
- import java.io.File;
44
- import java.io.FileOutputStream;
45
- import java.io.IOException;
46
- import java.util.Arrays;
47
- import java.util.List;
48
- import java.util.UUID;
49
-
50
- public class CameraActivity extends Fragment {
51
-
52
- public interface CameraPreviewListener {
53
- void onPictureTaken(String originalPicture);
54
- void onPictureTakenError(String message);
55
- void onSnapshotTaken(String originalPicture);
56
- void onSnapshotTakenError(String message);
57
- void onFocusSet(int pointX, int pointY);
58
- void onFocusSetError(String message);
59
- void onBackButton();
60
- void onCameraStarted();
61
- void onStartRecordVideo();
62
- void onStartRecordVideoError(String message);
63
- void onStopRecordVideo(String file);
64
- void onStopRecordVideoError(String error);
65
- }
66
-
67
- private CameraPreviewListener eventListener;
68
- private static final String TAG = "CameraActivity";
69
- public FrameLayout mainLayout;
70
- public FrameLayout frameContainerLayout;
71
-
72
- private Preview mPreview;
73
- private boolean canTakePicture = true;
74
-
75
- private View view;
76
- private Camera.Parameters cameraParameters;
77
- private Camera mCamera;
78
- private int numberOfCameras;
79
- private int cameraCurrentlyLocked;
80
- private int currentQuality;
81
-
82
- private enum RecordingState {
83
- INITIALIZING,
84
- STARTED,
85
- STOPPED
86
- }
87
-
88
- private RecordingState mRecordingState = RecordingState.INITIALIZING;
89
- private MediaRecorder mRecorder = null;
90
- private String recordFilePath;
91
- private float opacity;
92
-
93
- // The first rear facing camera
94
- private int defaultCameraId;
95
- public String defaultCamera;
96
- public boolean tapToTakePicture;
97
- public boolean dragEnabled;
98
- public boolean tapToFocus;
99
- public boolean disableExifHeaderStripping;
100
- public boolean storeToFile;
101
- public boolean toBack;
102
- public boolean enableOpacity = false;
103
- public boolean enableZoom = false;
104
-
105
- public int width;
106
- public int height;
107
- public int x;
108
- public int y;
109
-
110
- public void setEventListener(CameraPreviewListener listener) {
111
- eventListener = listener;
112
- }
113
-
114
- private String appResourcesPackage;
115
-
116
- @Override
117
- public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
118
- appResourcesPackage = getActivity().getPackageName();
119
-
120
- // Inflate the layout for this fragment
121
- view = inflater.inflate(getResources().getIdentifier("camera_activity", "layout", appResourcesPackage), container, false);
122
- createCameraPreview();
123
- return view;
124
- }
125
-
126
- public void setRect(int x, int y, int width, int height) {
127
- this.x = x;
128
- this.y = y;
129
- this.width = width;
130
- this.height = height;
131
- }
132
-
133
- private void createCameraPreview() {
134
- if (mPreview == null) {
135
- setDefaultCameraId();
136
-
137
- //set box position and size
138
- FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(width, height);
139
- layoutParams.setMargins(x, y, 0, 0);
140
- frameContainerLayout =
141
- (FrameLayout) view.findViewById(getResources().getIdentifier("frame_container", "id", appResourcesPackage));
142
- frameContainerLayout.setLayoutParams(layoutParams);
143
-
144
- //video view
145
- mPreview = new Preview(getActivity(), enableOpacity);
146
- mainLayout = (FrameLayout) view.findViewById(getResources().getIdentifier("video_view", "id", appResourcesPackage));
147
- mainLayout.setLayoutParams(
148
- new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT)
149
- );
150
- mainLayout.addView(mPreview);
151
- mainLayout.setEnabled(false);
152
-
153
- if (enableZoom) {
154
- this.setupTouchAndBackButton();
155
- }
156
- }
157
- }
158
-
159
-
160
- private void setupTouchAndBackButton() {
161
- final GestureDetector gestureDetector = new GestureDetector(getActivity().getApplicationContext(), new TapGestureDetector());
162
-
163
- getActivity()
164
- .runOnUiThread(
165
- new Runnable() {
166
- @Override
167
- public void run() {
168
- frameContainerLayout.setClickable(true);
169
- frameContainerLayout.setOnTouchListener(
170
- new View.OnTouchListener() {
171
- private int mLastTouchX;
172
- private int mLastTouchY;
173
- private int mPosX = 0;
174
- private int mPosY = 0;
175
-
176
- @Override
177
- public boolean onTouch(View v, MotionEvent event) {
178
- FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) frameContainerLayout.getLayoutParams();
179
-
180
- boolean isSingleTapTouch = gestureDetector.onTouchEvent(event);
181
- int action = event.getAction();
182
- int eventCount = event.getPointerCount();
183
- Log.d(TAG, "onTouch event, action, count: " + event + ", " + action + ", " + eventCount);
184
- if (eventCount > 1) {
185
- // handle multi-touch events
186
- Camera.Parameters params = mCamera.getParameters();
187
- if (action == MotionEvent.ACTION_POINTER_DOWN) {
188
- mDist = getFingerSpacing(event);
189
- } else if (action == MotionEvent.ACTION_MOVE && params.isZoomSupported()) {
190
- handleZoom(event, params);
191
- }
192
- } else {
193
- if (action != MotionEvent.ACTION_MOVE && isSingleTapTouch) {
194
- if (tapToTakePicture && tapToFocus) {
195
- setFocusArea(
196
- (int) event.getX(0),
197
- (int) event.getY(0),
198
- new Camera.AutoFocusCallback() {
199
- public void onAutoFocus(boolean success, Camera camera) {
200
- if (success) {
201
- takePicture(0, 0, 85);
202
- } else {
203
- Log.d(TAG, "onTouch:" + " setFocusArea() did not suceed");
204
- }
205
- }
206
- }
207
- );
208
- } else if (tapToTakePicture) {
209
- takePicture(0, 0, 85);
210
- } else if (tapToFocus) {
211
- setFocusArea(
212
- (int) event.getX(0),
213
- (int) event.getY(0),
214
- new Camera.AutoFocusCallback() {
215
- public void onAutoFocus(boolean success, Camera camera) {
216
- if (success) {
217
- // A callback to JS might make sense here.
218
- } else {
219
- Log.d(TAG, "onTouch:" + " setFocusArea() did not suceed");
220
- }
221
- }
222
- }
223
- );
224
- }
225
- return true;
226
- } else {
227
- if (dragEnabled) {
228
- int x;
229
- int y;
230
-
231
- switch (event.getAction()) {
232
- case MotionEvent.ACTION_DOWN:
233
- if (mLastTouchX == 0 || mLastTouchY == 0) {
234
- mLastTouchX = (int) event.getRawX() - layoutParams.leftMargin;
235
- mLastTouchY = (int) event.getRawY() - layoutParams.topMargin;
236
- } else {
237
- mLastTouchX = (int) event.getRawX();
238
- mLastTouchY = (int) event.getRawY();
239
- }
240
- break;
241
- case MotionEvent.ACTION_MOVE:
242
- x = (int) event.getRawX();
243
- y = (int) event.getRawY();
244
-
245
- final float dx = x - mLastTouchX;
246
- final float dy = y - mLastTouchY;
247
-
248
- mPosX += dx;
249
- mPosY += dy;
250
-
251
- layoutParams.leftMargin = mPosX;
252
- layoutParams.topMargin = mPosY;
253
-
254
- frameContainerLayout.setLayoutParams(layoutParams);
255
-
256
- // Remember this touch position for the next move event
257
- mLastTouchX = x;
258
- mLastTouchY = y;
259
-
260
- break;
261
- default:
262
- break;
263
- }
264
- }
265
- }
266
- }
267
- return true;
268
- }
269
- }
270
- );
271
- frameContainerLayout.setFocusableInTouchMode(true);
272
- frameContainerLayout.requestFocus();
273
- frameContainerLayout.setOnKeyListener(
274
- new View.OnKeyListener() {
275
- @Override
276
- public boolean onKey(View v, int keyCode, android.view.KeyEvent event) {
277
- if (keyCode == android.view.KeyEvent.KEYCODE_BACK) {
278
- eventListener.onBackButton();
279
- return true;
280
- }
281
- return false;
282
- }
283
- }
284
- );
285
- }
286
-
287
- private float mDist = 0F;
288
-
289
- private void handleZoom(MotionEvent event, Camera.Parameters params) {
290
- if (mCamera != null) {
291
- mCamera.cancelAutoFocus();
292
- int maxZoom = params.getMaxZoom();
293
- int zoom = params.getZoom();
294
- float newDist = getFingerSpacing(event);
295
- if (newDist > mDist) {
296
- //zoom in
297
- if (zoom < maxZoom) zoom++;
298
- } else if (newDist < mDist) {
299
- //zoom out
300
- if (zoom > 0) zoom--;
301
- }
302
- mDist = newDist;
303
- params.setZoom(zoom);
304
- mCamera.setParameters(params);
305
- }
306
- }
307
- }
308
- );
309
- }
310
-
311
- private void setDefaultCameraId() {
312
- // Find the total number of cameras available
313
- numberOfCameras = Camera.getNumberOfCameras();
314
-
315
- int facing = "front".equals(defaultCamera) ? Camera.CameraInfo.CAMERA_FACING_FRONT : Camera.CameraInfo.CAMERA_FACING_BACK;
316
-
317
- // Find the ID of the default camera
318
- Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
319
- for (int i = 0; i < numberOfCameras; i++) {
320
- Camera.getCameraInfo(i, cameraInfo);
321
- if (cameraInfo.facing == facing) {
322
- defaultCameraId = i;
323
- break;
324
- }
325
- }
326
- }
327
-
328
- @Override
329
- public void onResume() {
330
- super.onResume();
331
-
332
- mCamera = Camera.open(defaultCameraId);
333
-
334
- if (cameraParameters != null) {
335
- mCamera.setParameters(cameraParameters);
336
- }
337
-
338
- cameraCurrentlyLocked = defaultCameraId;
339
-
340
- if (mPreview.mPreviewSize == null) {
341
- mPreview.setCamera(mCamera, cameraCurrentlyLocked);
342
- eventListener.onCameraStarted();
343
- } else {
344
- mPreview.switchCamera(mCamera, cameraCurrentlyLocked);
345
- mCamera.startPreview();
346
- }
347
-
348
- Log.d(TAG, "cameraCurrentlyLocked:" + cameraCurrentlyLocked);
349
-
350
- final FrameLayout frameContainerLayout = (FrameLayout) view.findViewById(
351
- getResources().getIdentifier("frame_container", "id", appResourcesPackage)
352
- );
353
-
354
- ViewTreeObserver viewTreeObserver = frameContainerLayout.getViewTreeObserver();
355
-
356
- if (viewTreeObserver.isAlive()) {
357
- viewTreeObserver.addOnGlobalLayoutListener(
358
- new ViewTreeObserver.OnGlobalLayoutListener() {
359
- @Override
360
- public void onGlobalLayout() {
361
- frameContainerLayout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
362
- frameContainerLayout.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
363
- Activity activity = getActivity();
364
- if (isAdded() && activity != null) {
365
- final RelativeLayout frameCamContainerLayout = (RelativeLayout) view.findViewById(
366
- getResources().getIdentifier("frame_camera_cont", "id", appResourcesPackage)
367
- );
368
-
369
- FrameLayout.LayoutParams camViewLayout = new FrameLayout.LayoutParams(
370
- frameContainerLayout.getWidth(),
371
- frameContainerLayout.getHeight()
372
- );
373
- camViewLayout.gravity = Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL;
374
- frameCamContainerLayout.setLayoutParams(camViewLayout);
375
- }
376
- }
377
- }
378
- );
379
- }
380
- }
381
-
382
- @Override
383
- public void onPause() {
384
- super.onPause();
385
-
386
- // Because the Camera object is a shared resource, it's very important to release it when the activity is paused.
387
- if (mCamera != null) {
388
- setDefaultCameraId();
389
- mPreview.setCamera(null, -1);
390
- mCamera.setPreviewCallback(null);
391
- mCamera.release();
392
- mCamera = null;
393
- }
394
- }
395
-
396
- @Override
397
- public void onConfigurationChanged(Configuration newConfig) {
398
- super.onConfigurationChanged(newConfig);
399
-
400
- final FrameLayout frameContainerLayout = (FrameLayout) view.findViewById(
401
- getResources().getIdentifier("frame_container", "id", appResourcesPackage)
402
- );
403
-
404
- final int previousOrientation = frameContainerLayout.getHeight() > frameContainerLayout.getWidth() ? Configuration.ORIENTATION_PORTRAIT : Configuration.ORIENTATION_LANDSCAPE;
405
- // Checks if the orientation of the screen has changed
406
- if (newConfig.orientation != previousOrientation) {
407
-
408
- final RelativeLayout frameCamContainerLayout = (RelativeLayout) view.findViewById(
409
- getResources().getIdentifier("frame_camera_cont", "id", appResourcesPackage)
410
- );
411
-
412
- frameContainerLayout.getLayoutParams().width = frameCamContainerLayout.getHeight();
413
- frameContainerLayout.getLayoutParams().height = frameCamContainerLayout.getWidth();
414
-
415
- frameCamContainerLayout.getLayoutParams().width = frameCamContainerLayout.getHeight();
416
- frameCamContainerLayout.getLayoutParams().height = frameCamContainerLayout.getWidth();
417
-
418
- frameContainerLayout.invalidate();
419
- frameContainerLayout.requestLayout();
420
-
421
- frameCamContainerLayout.forceLayout();
422
-
423
- mPreview.setCameraDisplayOrientation();
424
-
425
- }
426
-
427
- }
428
-
429
-
430
- public Camera getCamera() {
431
- return mCamera;
432
- }
433
-
434
- public void switchCamera() {
435
- // check for availability of multiple cameras
436
- if (numberOfCameras == 1) {
437
- //There is only one camera available
438
- } else {
439
- Log.d(TAG, "numberOfCameras: " + numberOfCameras);
440
-
441
- // OK, we have multiple cameras. Release this camera -> cameraCurrentlyLocked
442
- if (mCamera != null) {
443
- mCamera.stopPreview();
444
- mPreview.setCamera(null, -1);
445
- mCamera.release();
446
- mCamera = null;
447
- }
448
-
449
- Log.d(TAG, "cameraCurrentlyLocked := " + Integer.toString(cameraCurrentlyLocked));
450
- try {
451
- cameraCurrentlyLocked = (cameraCurrentlyLocked + 1) % numberOfCameras;
452
- Log.d(TAG, "cameraCurrentlyLocked new: " + cameraCurrentlyLocked);
453
- } catch (Exception exception) {
454
- Log.d(TAG, exception.getMessage());
455
- }
456
-
457
- // Acquire the next camera and request Preview to reconfigure parameters.
458
- mCamera = Camera.open(cameraCurrentlyLocked);
459
-
460
- if (cameraParameters != null) {
461
- Log.d(TAG, "camera parameter not null");
462
-
463
- // Check for flashMode as well to prevent error on frontward facing camera.
464
- List<String> supportedFlashModesNewCamera = mCamera.getParameters().getSupportedFlashModes();
465
- String currentFlashModePreviousCamera = cameraParameters.getFlashMode();
466
- if (supportedFlashModesNewCamera != null && supportedFlashModesNewCamera.contains(currentFlashModePreviousCamera)) {
467
- Log.d(TAG, "current flash mode supported on new camera. setting params");
468
- /* mCamera.setParameters(cameraParameters);
469
- The line above is disabled because parameters that can actually be changed are different from one device to another. Makes less sense trying to reconfigure them when changing camera device while those settings gan be changed using plugin methods.
470
- */
471
- } else {
472
- Log.d(TAG, "current flash mode NOT supported on new camera");
473
- }
474
- } else {
475
- Log.d(TAG, "camera parameter NULL");
476
- }
477
-
478
- mPreview.switchCamera(mCamera, cameraCurrentlyLocked);
479
-
480
- mCamera.startPreview();
481
- }
482
- }
483
-
484
- public void setCameraParameters(Camera.Parameters params) {
485
- cameraParameters = params;
486
-
487
- if (mCamera != null && cameraParameters != null) {
488
- mCamera.setParameters(cameraParameters);
489
- }
490
- }
491
-
492
- public boolean hasFrontCamera() {
493
- return getActivity().getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FRONT);
494
- }
495
-
496
- public static Bitmap applyMatrix(Bitmap source, Matrix matrix) {
497
- return Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true);
498
- }
499
-
500
- ShutterCallback shutterCallback = new ShutterCallback() {
501
- public void onShutter() {
502
- // do nothing, availabilty of this callback causes default system shutter sound to work
503
- }
504
- };
505
-
506
- private static int exifToDegrees(int exifOrientation) {
507
- if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_90) {
508
- return 90;
509
- } else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_180) {
510
- return 180;
511
- } else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_270) {
512
- return 270;
513
- }
514
- return 0;
515
- }
516
-
517
- private String getTempDirectoryPath() {
518
- File cache = null;
519
-
520
- // Use internal storage
521
- cache = getActivity().getCacheDir();
522
-
523
- // Create the cache directory if it doesn't exist
524
- cache.mkdirs();
525
- return cache.getAbsolutePath();
526
- }
527
-
528
- private String getTempFilePath() {
529
- return getTempDirectoryPath() + "/cpcp_capture_" + UUID.randomUUID().toString().replace("-", "").substring(0, 8) + ".jpg";
530
- }
531
-
532
- PictureCallback jpegPictureCallback = new PictureCallback() {
533
- public void onPictureTaken(byte[] data, Camera arg1) {
534
- Log.d(TAG, "CameraPreview jpegPictureCallback");
535
-
536
- try {
537
- if (!disableExifHeaderStripping) {
538
- Matrix matrix = new Matrix();
539
- if (cameraCurrentlyLocked == Camera.CameraInfo.CAMERA_FACING_FRONT) {
540
- matrix.preScale(1.0f, -1.0f);
541
- }
542
-
543
- ExifInterface exifInterface = new ExifInterface(new ByteArrayInputStream(data));
544
- int rotation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
545
- int rotationInDegrees = exifToDegrees(rotation);
546
-
547
- if (rotation != 0f) {
548
- matrix.preRotate(rotationInDegrees);
549
- }
550
-
551
- // Check if matrix has changed. In that case, apply matrix and override data
552
- if (!matrix.isIdentity()) {
553
- Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
554
- bitmap = applyMatrix(bitmap, matrix);
555
-
556
- ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
557
- bitmap.compress(CompressFormat.JPEG, currentQuality, outputStream);
558
- data = outputStream.toByteArray();
559
- }
560
- }
561
-
562
- if (!storeToFile) {
563
- String encodedImage = Base64.encodeToString(data, Base64.NO_WRAP);
564
-
565
- eventListener.onPictureTaken(encodedImage);
566
- } else {
567
- String path = getTempFilePath();
568
- FileOutputStream out = new FileOutputStream(path);
569
- out.write(data);
570
- out.close();
571
- eventListener.onPictureTaken(path);
572
- }
573
- Log.d(TAG, "CameraPreview pictureTakenHandler called back");
574
- } catch (OutOfMemoryError e) {
575
- // most likely failed to allocate memory for rotateBitmap
576
- Log.d(TAG, "CameraPreview OutOfMemoryError");
577
- // failed to allocate memory
578
- eventListener.onPictureTakenError("Picture too large (memory)");
579
- } catch (IOException e) {
580
- Log.d(TAG, "CameraPreview IOException");
581
- eventListener.onPictureTakenError("IO Error when extracting exif");
582
- } catch (Exception e) {
583
- Log.d(TAG, "CameraPreview onPictureTaken general exception");
584
- } finally {
585
- canTakePicture = true;
586
- mCamera.startPreview();
587
- }
588
- }
589
- };
590
-
591
- private Camera.Size getOptimalPictureSize(
592
- final int width,
593
- final int height,
594
- final Camera.Size previewSize,
595
- final List<Camera.Size> supportedSizes
596
- ) {
597
- /*
598
- get the supportedPictureSize that:
599
- - matches exactly width and height
600
- - has the closest aspect ratio to the preview aspect ratio
601
- - has picture.width and picture.height closest to width and height
602
- - has the highest supported picture width and height up to 2 Megapixel if width == 0 || height == 0
603
- */
604
- Camera.Size size = mCamera.new Size(width, height);
605
-
606
- // convert to landscape if necessary
607
- if (size.width < size.height) {
608
- int temp = size.width;
609
- size.width = size.height;
610
- size.height = temp;
611
- }
612
-
613
- Camera.Size requestedSize = mCamera.new Size(size.width, size.height);
614
-
615
- double previewAspectRatio = (double) previewSize.width / (double) previewSize.height;
616
-
617
- if (previewAspectRatio < 1.0) {
618
- // reset ratio to landscape
619
- previewAspectRatio = 1.0 / previewAspectRatio;
620
- }
621
-
622
- Log.d(TAG, "CameraPreview previewAspectRatio " + previewAspectRatio);
623
-
624
- double aspectTolerance = 0.1;
625
- double bestDifference = Double.MAX_VALUE;
626
-
627
- for (int i = 0; i < supportedSizes.size(); i++) {
628
- Camera.Size supportedSize = supportedSizes.get(i);
629
-
630
- // Perfect match
631
- if (supportedSize.equals(requestedSize)) {
632
- Log.d(TAG, "CameraPreview optimalPictureSize " + supportedSize.width + 'x' + supportedSize.height);
633
- return supportedSize;
634
- }
635
-
636
- double difference = Math.abs(previewAspectRatio - ((double) supportedSize.width / (double) supportedSize.height));
637
-
638
- if (difference < bestDifference - aspectTolerance) {
639
- // better aspectRatio found
640
- if ((width != 0 && height != 0) || (supportedSize.width * supportedSize.height < 2048 * 1024)) {
641
- size.width = supportedSize.width;
642
- size.height = supportedSize.height;
643
- bestDifference = difference;
644
- }
645
- } else if (difference < bestDifference + aspectTolerance) {
646
- // same aspectRatio found (within tolerance)
647
- if (width == 0 || height == 0) {
648
- // set highest supported resolution below 2 Megapixel
649
- if ((size.width < supportedSize.width) && (supportedSize.width * supportedSize.height < 2048 * 1024)) {
650
- size.width = supportedSize.width;
651
- size.height = supportedSize.height;
652
- }
653
- } else {
654
- // check if this pictureSize closer to requested width and height
655
- if (
656
- Math.abs(width * height - supportedSize.width * supportedSize.height) <
657
- Math.abs(width * height - size.width * size.height)
658
- ) {
659
- size.width = supportedSize.width;
660
- size.height = supportedSize.height;
661
- }
662
- }
663
- }
664
- }
665
- Log.d(TAG, "CameraPreview optimalPictureSize " + size.width + 'x' + size.height);
666
- return size;
667
- }
668
-
669
- static byte[] rotateNV21(final byte[] yuv, final int width, final int height, final int rotation) {
670
- if (rotation == 0) return yuv;
671
- if (rotation % 90 != 0 || rotation < 0 || rotation > 270) {
672
- throw new IllegalArgumentException("0 <= rotation < 360, rotation % 90 == 0");
673
- }
674
-
675
- final byte[] output = new byte[yuv.length];
676
- final int frameSize = width * height;
677
- final boolean swap = rotation % 180 != 0;
678
- final boolean xflip = rotation % 270 != 0;
679
- final boolean yflip = rotation >= 180;
680
-
681
- for (int j = 0; j < height; j++) {
682
- for (int i = 0; i < width; i++) {
683
- final int yIn = j * width + i;
684
- final int uIn = frameSize + (j >> 1) * width + (i & ~1);
685
- final int vIn = uIn + 1;
686
-
687
- final int wOut = swap ? height : width;
688
- final int hOut = swap ? width : height;
689
- final int iSwapped = swap ? j : i;
690
- final int jSwapped = swap ? i : j;
691
- final int iOut = xflip ? wOut - iSwapped - 1 : iSwapped;
692
- final int jOut = yflip ? hOut - jSwapped - 1 : jSwapped;
693
-
694
- final int yOut = jOut * wOut + iOut;
695
- final int uOut = frameSize + (jOut >> 1) * wOut + (iOut & ~1);
696
- final int vOut = uOut + 1;
697
-
698
- output[yOut] = (byte) (0xff & yuv[yIn]);
699
- output[uOut] = (byte) (0xff & yuv[uIn]);
700
- output[vOut] = (byte) (0xff & yuv[vIn]);
701
- }
702
- }
703
- return output;
704
- }
705
-
706
- public void setOpacity(final float opacity) {
707
- Log.d(TAG, "set opacity:" + opacity);
708
- this.opacity = opacity;
709
- mPreview.setOpacity(opacity);
710
- }
711
-
712
- public void takeSnapshot(final int quality) {
713
- mCamera.setPreviewCallback(
714
- new Camera.PreviewCallback() {
715
- @Override
716
- public void onPreviewFrame(byte[] bytes, Camera camera) {
717
- try {
718
- Camera.Parameters parameters = camera.getParameters();
719
- Camera.Size size = parameters.getPreviewSize();
720
- int orientation = mPreview.getDisplayOrientation();
721
- if (mPreview.getCameraFacing() == Camera.CameraInfo.CAMERA_FACING_FRONT) {
722
- bytes = rotateNV21(bytes, size.width, size.height, (360 - orientation) % 360);
723
- } else {
724
- bytes = rotateNV21(bytes, size.width, size.height, orientation);
725
- }
726
- // switch width/height when rotating 90/270 deg
727
- Rect rect = orientation == 90 || orientation == 270
728
- ? new Rect(0, 0, size.height, size.width)
729
- : new Rect(0, 0, size.width, size.height);
730
- YuvImage yuvImage = new YuvImage(bytes, parameters.getPreviewFormat(), rect.width(), rect.height(), null);
731
- ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
732
- yuvImage.compressToJpeg(rect, quality, byteArrayOutputStream);
733
- byte[] data = byteArrayOutputStream.toByteArray();
734
- byteArrayOutputStream.close();
735
- eventListener.onSnapshotTaken(Base64.encodeToString(data, Base64.NO_WRAP));
736
- } catch (IOException e) {
737
- Log.d(TAG, "CameraPreview IOException");
738
- eventListener.onSnapshotTakenError("IO Error");
739
- } finally {
740
- mCamera.setPreviewCallback(null);
741
- }
742
- }
743
- }
744
- );
745
- }
746
-
747
- public void takePicture(final int width, final int height, final int quality) {
748
- Log.d(TAG, "CameraPreview takePicture width: " + width + ", height: " + height + ", quality: " + quality);
749
-
750
- if (mPreview != null) {
751
- if (!canTakePicture) {
752
- return;
753
- }
754
-
755
- canTakePicture = false;
756
-
757
- new Thread() {
758
- public void run() {
759
- Camera.Parameters params = mCamera.getParameters();
760
-
761
- Camera.Size size = getOptimalPictureSize(width, height, params.getPreviewSize(), params.getSupportedPictureSizes());
762
- params.setPictureSize(size.width, size.height);
763
- currentQuality = quality;
764
-
765
- if (cameraCurrentlyLocked == Camera.CameraInfo.CAMERA_FACING_FRONT && !storeToFile) {
766
- // The image will be recompressed in the callback
767
- params.setJpegQuality(99);
768
- } else {
769
- params.setJpegQuality(quality);
770
- }
771
-
772
- if (cameraCurrentlyLocked == Camera.CameraInfo.CAMERA_FACING_FRONT && disableExifHeaderStripping) {
773
- Activity activity = getActivity();
774
- int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
775
- int degrees = 0;
776
- switch (rotation) {
777
- case Surface.ROTATION_0:
778
- degrees = 0;
779
- break;
780
- case Surface.ROTATION_90:
781
- degrees = 180;
782
- break;
783
- case Surface.ROTATION_180:
784
- degrees = 270;
785
- break;
786
- case Surface.ROTATION_270:
787
- degrees = 0;
788
- break;
789
- }
790
- int orientation;
791
- Camera.CameraInfo info = new Camera.CameraInfo();
792
- if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
793
- orientation = (info.orientation + degrees) % 360;
794
- if (degrees != 0) {
795
- orientation = (360 - orientation) % 360;
796
- }
797
- } else {
798
- orientation = (info.orientation - degrees + 360) % 360;
799
- }
800
- params.setRotation(orientation);
801
- } else {
802
- params.setRotation(mPreview.getDisplayOrientation());
803
- }
804
-
805
- mCamera.setParameters(params);
806
- mCamera.takePicture(shutterCallback, null, jpegPictureCallback);
807
- }
808
- }
809
- .start();
810
- } else {
811
- canTakePicture = true;
812
- }
813
- }
814
-
815
- public void startRecord(
816
- final String filePath,
817
- final String camera,
818
- final int width,
819
- final int height,
820
- final int quality,
821
- final boolean withFlash,
822
- final int maxDuration,
823
- final String lens
824
- ) {
825
- Log.d(TAG, "CameraPreview startRecord camera: " + camera + " width: " + width + ", height: " + height + ", quality: " + quality + ", lens: " + lens);
826
- Activity activity = getActivity();
827
- muteStream(true, activity);
828
- if (this.mRecordingState == RecordingState.STARTED) {
829
- Log.d(TAG, "Already Recording");
830
- return;
831
- }
832
-
833
- this.recordFilePath = filePath;
834
- int mOrientationHint = calculateOrientationHint();
835
- int videoWidth = 0; //set whatever
836
- int videoHeight = 0; //set whatever
837
-
838
- Camera.Parameters cameraParams = mCamera.getParameters();
839
- if (withFlash) {
840
- cameraParams.setFlashMode(withFlash ? Camera.Parameters.FLASH_MODE_TORCH : Camera.Parameters.FLASH_MODE_OFF);
841
- mCamera.setParameters(cameraParams);
842
- mCamera.startPreview();
843
- }
844
-
845
- mCamera.unlock();
846
- mRecorder = new MediaRecorder();
847
-
848
- try {
849
- mRecorder.setCamera(mCamera);
850
-
851
- CamcorderProfile profile;
852
- if (CamcorderProfile.hasProfile(defaultCameraId, CamcorderProfile.QUALITY_HIGH)) {
853
- profile = CamcorderProfile.get(defaultCameraId, CamcorderProfile.QUALITY_HIGH);
854
- } else {
855
- if (CamcorderProfile.hasProfile(defaultCameraId, CamcorderProfile.QUALITY_480P)) {
856
- profile = CamcorderProfile.get(defaultCameraId, CamcorderProfile.QUALITY_480P);
857
- } else {
858
- if (CamcorderProfile.hasProfile(defaultCameraId, CamcorderProfile.QUALITY_720P)) {
859
- profile = CamcorderProfile.get(defaultCameraId, CamcorderProfile.QUALITY_720P);
860
- } else {
861
- if (CamcorderProfile.hasProfile(defaultCameraId, CamcorderProfile.QUALITY_1080P)) {
862
- profile = CamcorderProfile.get(defaultCameraId, CamcorderProfile.QUALITY_1080P);
863
- } else {
864
- profile = CamcorderProfile.get(defaultCameraId, CamcorderProfile.QUALITY_LOW);
865
- }
866
- }
867
- }
868
- }
869
-
870
- mRecorder.setAudioSource(MediaRecorder.AudioSource.VOICE_RECOGNITION);
871
- mRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
872
- mRecorder.setProfile(profile);
873
- mRecorder.setOutputFile(filePath);
874
- mRecorder.setOrientationHint(mOrientationHint);
875
- mRecorder.setMaxDuration(maxDuration);
876
-
877
- mRecorder.prepare();
878
- Log.d(TAG, "Starting recording");
879
- mRecorder.start();
880
- eventListener.onStartRecordVideo();
881
- } catch (IOException e) {
882
- eventListener.onStartRecordVideoError(e.getMessage());
883
- }
884
- }
885
-
886
- public int calculateOrientationHint() {
887
- DisplayMetrics dm = new DisplayMetrics();
888
- Camera.CameraInfo info = new Camera.CameraInfo();
889
- Camera.getCameraInfo(defaultCameraId, info);
890
- int cameraRotationOffset = info.orientation;
891
- Activity activity = getActivity();
892
-
893
- activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
894
- int currentScreenRotation = activity.getWindowManager().getDefaultDisplay().getRotation();
895
-
896
- int degrees = 0;
897
- switch (currentScreenRotation) {
898
- case Surface.ROTATION_0:
899
- degrees = 0;
900
- break;
901
- case Surface.ROTATION_90:
902
- degrees = 90;
903
- break;
904
- case Surface.ROTATION_180:
905
- degrees = 180;
906
- break;
907
- case Surface.ROTATION_270:
908
- degrees = 270;
909
- break;
910
- }
911
-
912
- int orientation;
913
- if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
914
- orientation = (cameraRotationOffset + degrees) % 360;
915
- if (degrees != 0) {
916
- orientation = (360 - orientation) % 360;
917
- }
918
- } else {
919
- orientation = (cameraRotationOffset - degrees + 360) % 360;
920
- }
921
- Log.w(TAG, "************orientationHint ***********= " + orientation);
922
-
923
- return orientation;
924
- }
925
-
926
- public void stopRecord() {
927
- Log.d(TAG, "stopRecord");
928
-
929
- try {
930
- mRecorder.stop();
931
- mRecorder.reset(); // clear recorder configuration
932
- mRecorder.release(); // release the recorder object
933
- mRecorder = null;
934
- mCamera.lock();
935
- Camera.Parameters cameraParams = mCamera.getParameters();
936
- cameraParams.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
937
- mCamera.setParameters(cameraParams);
938
- mCamera.startPreview();
939
- eventListener.onStopRecordVideo(this.recordFilePath);
940
- } catch (Exception e) {
941
- eventListener.onStopRecordVideoError(e.getMessage());
942
- }
943
- }
944
-
945
- public void muteStream(boolean mute, Activity activity) {
946
- AudioManager audioManager = ((AudioManager) activity.getApplicationContext().getSystemService(Context.AUDIO_SERVICE));
947
- int direction = mute ? audioManager.ADJUST_MUTE : audioManager.ADJUST_UNMUTE;
948
- }
949
-
950
- public void setFocusArea(final int pointX, final int pointY, final Camera.AutoFocusCallback callback) {
951
- if (mCamera != null) {
952
- mCamera.cancelAutoFocus();
953
-
954
- Camera.Parameters parameters = mCamera.getParameters();
955
-
956
- Rect focusRect = calculateTapArea(pointX, pointY, 1f);
957
- parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
958
- parameters.setFocusAreas(Arrays.asList(new Camera.Area(focusRect, 1000)));
959
-
960
- if (parameters.getMaxNumMeteringAreas() > 0) {
961
- Rect meteringRect = calculateTapArea(pointX, pointY, 1.5f);
962
- parameters.setMeteringAreas(Arrays.asList(new Camera.Area(meteringRect, 1000)));
963
- }
964
-
965
- try {
966
- setCameraParameters(parameters);
967
- mCamera.autoFocus(callback);
968
- } catch (Exception e) {
969
- Log.d(TAG, e.getMessage());
970
- callback.onAutoFocus(false, this.mCamera);
971
- }
972
- }
973
- }
974
-
975
- private Rect calculateTapArea(float x, float y, float coefficient) {
976
- if (x < 100) {
977
- x = 100;
978
- }
979
- if (x > width - 100) {
980
- x = width - 100;
981
- }
982
- if (y < 100) {
983
- y = 100;
984
- }
985
- if (y > height - 100) {
986
- y = height - 100;
987
- }
988
- return new Rect(
989
- Math.round((x - 100) * 2000 / width - 1000),
990
- Math.round((y - 100) * 2000 / height - 1000),
991
- Math.round((x + 100) * 2000 / width - 1000),
992
- Math.round((y + 100) * 2000 / height - 1000)
993
- );
994
- }
995
-
996
- /**
997
- * Determine the space between the first two fingers
998
- */
999
- private static float getFingerSpacing(MotionEvent event) {
1000
- // ...
1001
- float x = event.getX(0) - event.getX(1);
1002
- float y = event.getY(0) - event.getY(1);
1003
- return (float) Math.sqrt(x * x + y * y);
1004
- }
1005
- }
1
+ package com.ahm.capacitor.camera.preview;
2
+
3
+ import android.app.Activity;
4
+ import android.app.Fragment;
5
+ import android.content.Context;
6
+ import android.content.pm.PackageManager;
7
+ import android.content.res.Configuration;
8
+ import android.graphics.Bitmap;
9
+ import android.graphics.Bitmap.CompressFormat;
10
+ import android.graphics.BitmapFactory;
11
+ import android.graphics.Canvas;
12
+ import android.graphics.ImageFormat;
13
+ import android.graphics.Matrix;
14
+ import android.graphics.Rect;
15
+ import android.graphics.YuvImage;
16
+ import android.hardware.Camera;
17
+ import android.hardware.Camera.PictureCallback;
18
+ import android.hardware.Camera.ShutterCallback;
19
+ import android.hardware.camera2.CameraManager;
20
+ import android.media.AudioManager;
21
+ import android.media.CamcorderProfile;
22
+ import android.media.MediaRecorder;
23
+ import android.os.Bundle;
24
+ import android.util.Base64;
25
+ import android.util.DisplayMetrics;
26
+ import android.util.Log;
27
+ import android.view.GestureDetector;
28
+ import android.view.Gravity;
29
+ import android.view.LayoutInflater;
30
+ import android.view.MotionEvent;
31
+ import android.view.Surface;
32
+ import android.view.Surface;
33
+ import android.view.SurfaceHolder;
34
+ import android.view.SurfaceView;
35
+ import android.view.View;
36
+ import android.view.ViewGroup;
37
+ import android.view.ViewTreeObserver;
38
+ import android.widget.FrameLayout;
39
+ import android.widget.RelativeLayout;
40
+ import androidx.exifinterface.media.ExifInterface;
41
+ import java.io.ByteArrayInputStream;
42
+ import java.io.ByteArrayOutputStream;
43
+ import java.io.File;
44
+ import java.io.FileOutputStream;
45
+ import java.io.IOException;
46
+ import java.util.Arrays;
47
+ import java.util.List;
48
+ import java.util.UUID;
49
+
50
+ public class CameraActivity extends Fragment {
51
+
52
+ public interface CameraPreviewListener {
53
+ void onPictureTaken(String originalPicture);
54
+ void onPictureTakenError(String message);
55
+ void onSnapshotTaken(String originalPicture);
56
+ void onSnapshotTakenError(String message);
57
+ void onFocusSet(int pointX, int pointY);
58
+ void onFocusSetError(String message);
59
+ void onBackButton();
60
+ void onCameraStarted();
61
+ void onStartRecordVideo();
62
+ void onStartRecordVideoError(String message);
63
+ void onStopRecordVideo(String file);
64
+ void onStopRecordVideoError(String error);
65
+ }
66
+
67
+ private CameraPreviewListener eventListener;
68
+ private static final String TAG = "CameraActivity";
69
+ public FrameLayout mainLayout;
70
+ public FrameLayout frameContainerLayout;
71
+
72
+ private Preview mPreview;
73
+ private boolean canTakePicture = true;
74
+
75
+ private View view;
76
+ private Camera.Parameters cameraParameters;
77
+ private Camera mCamera;
78
+ private int numberOfCameras;
79
+ private int cameraCurrentlyLocked;
80
+ private int currentQuality;
81
+
82
+ private enum RecordingState {
83
+ INITIALIZING,
84
+ STARTED,
85
+ STOPPED
86
+ }
87
+
88
+ private RecordingState mRecordingState = RecordingState.INITIALIZING;
89
+ private MediaRecorder mRecorder = null;
90
+ private String recordFilePath;
91
+ private float opacity;
92
+
93
+ // The first rear facing camera
94
+ private int defaultCameraId;
95
+ public String defaultCamera;
96
+ public boolean tapToTakePicture;
97
+ public boolean dragEnabled;
98
+ public boolean tapToFocus;
99
+ public boolean disableExifHeaderStripping;
100
+ public boolean storeToFile;
101
+ public boolean toBack;
102
+ public boolean enableOpacity = false;
103
+ public boolean enableZoom = false;
104
+
105
+ public int width;
106
+ public int height;
107
+ public int x;
108
+ public int y;
109
+
110
+ public void setEventListener(CameraPreviewListener listener) {
111
+ eventListener = listener;
112
+ }
113
+
114
+ private String appResourcesPackage;
115
+
116
+ @Override
117
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
118
+ appResourcesPackage = getActivity().getPackageName();
119
+
120
+ // Inflate the layout for this fragment
121
+ view = inflater.inflate(getResources().getIdentifier("camera_activity", "layout", appResourcesPackage), container, false);
122
+ createCameraPreview();
123
+ return view;
124
+ }
125
+
126
+ public void setRect(int x, int y, int width, int height) {
127
+ this.x = x;
128
+ this.y = y;
129
+ this.width = width;
130
+ this.height = height;
131
+ }
132
+
133
+ private void createCameraPreview() {
134
+ if (mPreview == null) {
135
+ setDefaultCameraId();
136
+
137
+ //set box position and size
138
+ FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(width, height);
139
+ layoutParams.setMargins(x, y, 0, 0);
140
+ frameContainerLayout =
141
+ (FrameLayout) view.findViewById(getResources().getIdentifier("frame_container", "id", appResourcesPackage));
142
+ frameContainerLayout.setLayoutParams(layoutParams);
143
+
144
+ //video view
145
+ mPreview = new Preview(getActivity(), enableOpacity);
146
+ mainLayout = (FrameLayout) view.findViewById(getResources().getIdentifier("video_view", "id", appResourcesPackage));
147
+ mainLayout.setLayoutParams(
148
+ new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT)
149
+ );
150
+ mainLayout.addView(mPreview);
151
+ mainLayout.setEnabled(false);
152
+
153
+ if (enableZoom) {
154
+ this.setupTouchAndBackButton();
155
+ }
156
+ }
157
+ }
158
+
159
+
160
+ private void setupTouchAndBackButton() {
161
+ final GestureDetector gestureDetector = new GestureDetector(getActivity().getApplicationContext(), new TapGestureDetector());
162
+
163
+ getActivity()
164
+ .runOnUiThread(
165
+ new Runnable() {
166
+ @Override
167
+ public void run() {
168
+ frameContainerLayout.setClickable(true);
169
+ frameContainerLayout.setOnTouchListener(
170
+ new View.OnTouchListener() {
171
+ private int mLastTouchX;
172
+ private int mLastTouchY;
173
+ private int mPosX = 0;
174
+ private int mPosY = 0;
175
+
176
+ @Override
177
+ public boolean onTouch(View v, MotionEvent event) {
178
+ FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) frameContainerLayout.getLayoutParams();
179
+
180
+ boolean isSingleTapTouch = gestureDetector.onTouchEvent(event);
181
+ int action = event.getAction();
182
+ int eventCount = event.getPointerCount();
183
+ Log.d(TAG, "onTouch event, action, count: " + event + ", " + action + ", " + eventCount);
184
+ if (eventCount > 1) {
185
+ // handle multi-touch events
186
+ Camera.Parameters params = mCamera.getParameters();
187
+ if (action == MotionEvent.ACTION_POINTER_DOWN) {
188
+ mDist = getFingerSpacing(event);
189
+ } else if (action == MotionEvent.ACTION_MOVE && params.isZoomSupported()) {
190
+ handleZoom(event, params);
191
+ }
192
+ } else {
193
+ if (action != MotionEvent.ACTION_MOVE && isSingleTapTouch) {
194
+ if (tapToTakePicture && tapToFocus) {
195
+ setFocusArea(
196
+ (int) event.getX(0),
197
+ (int) event.getY(0),
198
+ new Camera.AutoFocusCallback() {
199
+ public void onAutoFocus(boolean success, Camera camera) {
200
+ if (success) {
201
+ takePicture(0, 0, 85);
202
+ } else {
203
+ Log.d(TAG, "onTouch:" + " setFocusArea() did not suceed");
204
+ }
205
+ }
206
+ }
207
+ );
208
+ } else if (tapToTakePicture) {
209
+ takePicture(0, 0, 85);
210
+ } else if (tapToFocus) {
211
+ setFocusArea(
212
+ (int) event.getX(0),
213
+ (int) event.getY(0),
214
+ new Camera.AutoFocusCallback() {
215
+ public void onAutoFocus(boolean success, Camera camera) {
216
+ if (success) {
217
+ // A callback to JS might make sense here.
218
+ } else {
219
+ Log.d(TAG, "onTouch:" + " setFocusArea() did not suceed");
220
+ }
221
+ }
222
+ }
223
+ );
224
+ }
225
+ return true;
226
+ } else {
227
+ if (dragEnabled) {
228
+ int x;
229
+ int y;
230
+
231
+ switch (event.getAction()) {
232
+ case MotionEvent.ACTION_DOWN:
233
+ if (mLastTouchX == 0 || mLastTouchY == 0) {
234
+ mLastTouchX = (int) event.getRawX() - layoutParams.leftMargin;
235
+ mLastTouchY = (int) event.getRawY() - layoutParams.topMargin;
236
+ } else {
237
+ mLastTouchX = (int) event.getRawX();
238
+ mLastTouchY = (int) event.getRawY();
239
+ }
240
+ break;
241
+ case MotionEvent.ACTION_MOVE:
242
+ x = (int) event.getRawX();
243
+ y = (int) event.getRawY();
244
+
245
+ final float dx = x - mLastTouchX;
246
+ final float dy = y - mLastTouchY;
247
+
248
+ mPosX += dx;
249
+ mPosY += dy;
250
+
251
+ layoutParams.leftMargin = mPosX;
252
+ layoutParams.topMargin = mPosY;
253
+
254
+ frameContainerLayout.setLayoutParams(layoutParams);
255
+
256
+ // Remember this touch position for the next move event
257
+ mLastTouchX = x;
258
+ mLastTouchY = y;
259
+
260
+ break;
261
+ default:
262
+ break;
263
+ }
264
+ }
265
+ }
266
+ }
267
+ return true;
268
+ }
269
+ }
270
+ );
271
+ frameContainerLayout.setFocusableInTouchMode(true);
272
+ frameContainerLayout.requestFocus();
273
+ // this was swallowing the back button events
274
+ // frameContainerLayout.setOnKeyListener(
275
+ // new View.OnKeyListener() {
276
+ // @Override
277
+ // public boolean onKey(View v, int keyCode, android.view.KeyEvent event) {
278
+ // if (keyCode == android.view.KeyEvent.KEYCODE_BACK) {
279
+ // eventListener.onBackButton();
280
+ // return true;
281
+ // }
282
+ // return false;
283
+ // }
284
+ // }
285
+ // );
286
+ }
287
+
288
+ private float mDist = 0F;
289
+
290
+ private void handleZoom(MotionEvent event, Camera.Parameters params) {
291
+ if (mCamera != null) {
292
+ mCamera.cancelAutoFocus();
293
+ int maxZoom = params.getMaxZoom();
294
+ int zoom = params.getZoom();
295
+ float newDist = getFingerSpacing(event);
296
+ if (newDist > mDist) {
297
+ //zoom in
298
+ if (zoom < maxZoom) zoom++;
299
+ } else if (newDist < mDist) {
300
+ //zoom out
301
+ if (zoom > 0) zoom--;
302
+ }
303
+ mDist = newDist;
304
+ params.setZoom(zoom);
305
+ mCamera.setParameters(params);
306
+ }
307
+ }
308
+ }
309
+ );
310
+ }
311
+
312
+ private void setDefaultCameraId() {
313
+ // Find the total number of cameras available
314
+ numberOfCameras = Camera.getNumberOfCameras();
315
+
316
+ int facing = "front".equals(defaultCamera) ? Camera.CameraInfo.CAMERA_FACING_FRONT : Camera.CameraInfo.CAMERA_FACING_BACK;
317
+
318
+ // Find the ID of the default camera
319
+ Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
320
+ for (int i = 0; i < numberOfCameras; i++) {
321
+ Camera.getCameraInfo(i, cameraInfo);
322
+ if (cameraInfo.facing == facing) {
323
+ defaultCameraId = i;
324
+ break;
325
+ }
326
+ }
327
+ }
328
+
329
+ @Override
330
+ public void onResume() {
331
+ super.onResume();
332
+
333
+ mCamera = Camera.open(defaultCameraId);
334
+
335
+ if (cameraParameters != null) {
336
+ mCamera.setParameters(cameraParameters);
337
+ }
338
+
339
+ cameraCurrentlyLocked = defaultCameraId;
340
+
341
+ if (mPreview.mPreviewSize == null) {
342
+ mPreview.setCamera(mCamera, cameraCurrentlyLocked);
343
+ eventListener.onCameraStarted();
344
+ } else {
345
+ mPreview.switchCamera(mCamera, cameraCurrentlyLocked);
346
+ mCamera.startPreview();
347
+ }
348
+
349
+ Log.d(TAG, "cameraCurrentlyLocked:" + cameraCurrentlyLocked);
350
+
351
+ final FrameLayout frameContainerLayout = (FrameLayout) view.findViewById(
352
+ getResources().getIdentifier("frame_container", "id", appResourcesPackage)
353
+ );
354
+
355
+ ViewTreeObserver viewTreeObserver = frameContainerLayout.getViewTreeObserver();
356
+
357
+ if (viewTreeObserver.isAlive()) {
358
+ viewTreeObserver.addOnGlobalLayoutListener(
359
+ new ViewTreeObserver.OnGlobalLayoutListener() {
360
+ @Override
361
+ public void onGlobalLayout() {
362
+ frameContainerLayout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
363
+ frameContainerLayout.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
364
+ Activity activity = getActivity();
365
+ if (isAdded() && activity != null) {
366
+ final RelativeLayout frameCamContainerLayout = (RelativeLayout) view.findViewById(
367
+ getResources().getIdentifier("frame_camera_cont", "id", appResourcesPackage)
368
+ );
369
+
370
+ FrameLayout.LayoutParams camViewLayout = new FrameLayout.LayoutParams(
371
+ frameContainerLayout.getWidth(),
372
+ frameContainerLayout.getHeight()
373
+ );
374
+ camViewLayout.gravity = Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL;
375
+ frameCamContainerLayout.setLayoutParams(camViewLayout);
376
+ }
377
+ }
378
+ }
379
+ );
380
+ }
381
+ }
382
+
383
+ @Override
384
+ public void onPause() {
385
+ super.onPause();
386
+
387
+ // Because the Camera object is a shared resource, it's very important to release it when the activity is paused.
388
+ if (mCamera != null) {
389
+ setDefaultCameraId();
390
+ mPreview.setCamera(null, -1);
391
+ mCamera.setPreviewCallback(null);
392
+ mCamera.release();
393
+ mCamera = null;
394
+ }
395
+ }
396
+
397
+ @Override
398
+ public void onConfigurationChanged(Configuration newConfig) {
399
+ super.onConfigurationChanged(newConfig);
400
+
401
+ final FrameLayout frameContainerLayout = (FrameLayout) view.findViewById(
402
+ getResources().getIdentifier("frame_container", "id", appResourcesPackage)
403
+ );
404
+
405
+ final int previousOrientation = frameContainerLayout.getHeight() > frameContainerLayout.getWidth() ? Configuration.ORIENTATION_PORTRAIT : Configuration.ORIENTATION_LANDSCAPE;
406
+ // Checks if the orientation of the screen has changed
407
+ if (newConfig.orientation != previousOrientation) {
408
+
409
+ final RelativeLayout frameCamContainerLayout = (RelativeLayout) view.findViewById(
410
+ getResources().getIdentifier("frame_camera_cont", "id", appResourcesPackage)
411
+ );
412
+
413
+ frameContainerLayout.getLayoutParams().width = frameCamContainerLayout.getHeight();
414
+ frameContainerLayout.getLayoutParams().height = frameCamContainerLayout.getWidth();
415
+
416
+ frameCamContainerLayout.getLayoutParams().width = frameCamContainerLayout.getHeight();
417
+ frameCamContainerLayout.getLayoutParams().height = frameCamContainerLayout.getWidth();
418
+
419
+ frameContainerLayout.invalidate();
420
+ frameContainerLayout.requestLayout();
421
+
422
+ frameCamContainerLayout.forceLayout();
423
+
424
+ mPreview.setCameraDisplayOrientation();
425
+
426
+ }
427
+
428
+ }
429
+
430
+
431
+ public Camera getCamera() {
432
+ return mCamera;
433
+ }
434
+
435
+ public void switchCamera() {
436
+ // check for availability of multiple cameras
437
+ if (numberOfCameras == 1) {
438
+ //There is only one camera available
439
+ } else {
440
+ Log.d(TAG, "numberOfCameras: " + numberOfCameras);
441
+
442
+ // OK, we have multiple cameras. Release this camera -> cameraCurrentlyLocked
443
+ if (mCamera != null) {
444
+ mCamera.stopPreview();
445
+ mPreview.setCamera(null, -1);
446
+ mCamera.release();
447
+ mCamera = null;
448
+ }
449
+
450
+ Log.d(TAG, "cameraCurrentlyLocked := " + Integer.toString(cameraCurrentlyLocked));
451
+ try {
452
+ cameraCurrentlyLocked = (cameraCurrentlyLocked + 1) % numberOfCameras;
453
+ Log.d(TAG, "cameraCurrentlyLocked new: " + cameraCurrentlyLocked);
454
+ } catch (Exception exception) {
455
+ Log.d(TAG, exception.getMessage());
456
+ }
457
+
458
+ // Acquire the next camera and request Preview to reconfigure parameters.
459
+ mCamera = Camera.open(cameraCurrentlyLocked);
460
+
461
+ if (cameraParameters != null) {
462
+ Log.d(TAG, "camera parameter not null");
463
+
464
+ // Check for flashMode as well to prevent error on frontward facing camera.
465
+ List<String> supportedFlashModesNewCamera = mCamera.getParameters().getSupportedFlashModes();
466
+ String currentFlashModePreviousCamera = cameraParameters.getFlashMode();
467
+ if (supportedFlashModesNewCamera != null && supportedFlashModesNewCamera.contains(currentFlashModePreviousCamera)) {
468
+ Log.d(TAG, "current flash mode supported on new camera. setting params");
469
+ /* mCamera.setParameters(cameraParameters);
470
+ The line above is disabled because parameters that can actually be changed are different from one device to another. Makes less sense trying to reconfigure them when changing camera device while those settings gan be changed using plugin methods.
471
+ */
472
+ } else {
473
+ Log.d(TAG, "current flash mode NOT supported on new camera");
474
+ }
475
+ } else {
476
+ Log.d(TAG, "camera parameter NULL");
477
+ }
478
+
479
+ mPreview.switchCamera(mCamera, cameraCurrentlyLocked);
480
+
481
+ mCamera.startPreview();
482
+ }
483
+ }
484
+
485
+ public void setCameraParameters(Camera.Parameters params) {
486
+ cameraParameters = params;
487
+
488
+ if (mCamera != null && cameraParameters != null) {
489
+ mCamera.setParameters(cameraParameters);
490
+ }
491
+ }
492
+
493
+ public boolean hasFrontCamera() {
494
+ return getActivity().getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FRONT);
495
+ }
496
+
497
+ public static Bitmap applyMatrix(Bitmap source, Matrix matrix) {
498
+ return Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true);
499
+ }
500
+
501
+ ShutterCallback shutterCallback = new ShutterCallback() {
502
+ public void onShutter() {
503
+ // do nothing, availabilty of this callback causes default system shutter sound to work
504
+ }
505
+ };
506
+
507
+ private static int exifToDegrees(int exifOrientation) {
508
+ if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_90) {
509
+ return 90;
510
+ } else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_180) {
511
+ return 180;
512
+ } else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_270) {
513
+ return 270;
514
+ }
515
+ return 0;
516
+ }
517
+
518
+ private String getTempDirectoryPath() {
519
+ File cache = null;
520
+
521
+ // Use internal storage
522
+ cache = getActivity().getCacheDir();
523
+
524
+ // Create the cache directory if it doesn't exist
525
+ cache.mkdirs();
526
+ return cache.getAbsolutePath();
527
+ }
528
+
529
+ private String getTempFilePath() {
530
+ return getTempDirectoryPath() + "/cpcp_capture_" + UUID.randomUUID().toString().replace("-", "").substring(0, 8) + ".jpg";
531
+ }
532
+
533
+ PictureCallback jpegPictureCallback = new PictureCallback() {
534
+ public void onPictureTaken(byte[] data, Camera arg1) {
535
+ Log.d(TAG, "CameraPreview jpegPictureCallback");
536
+
537
+ try {
538
+ if (!disableExifHeaderStripping) {
539
+ Matrix matrix = new Matrix();
540
+ if (cameraCurrentlyLocked == Camera.CameraInfo.CAMERA_FACING_FRONT) {
541
+ matrix.preScale(1.0f, -1.0f);
542
+ }
543
+
544
+ ExifInterface exifInterface = new ExifInterface(new ByteArrayInputStream(data));
545
+ int rotation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
546
+ int rotationInDegrees = exifToDegrees(rotation);
547
+
548
+ if (rotation != 0f) {
549
+ matrix.preRotate(rotationInDegrees);
550
+ }
551
+
552
+ // Check if matrix has changed. In that case, apply matrix and override data
553
+ if (!matrix.isIdentity()) {
554
+ Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
555
+ bitmap = applyMatrix(bitmap, matrix);
556
+
557
+ ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
558
+ bitmap.compress(CompressFormat.JPEG, currentQuality, outputStream);
559
+ data = outputStream.toByteArray();
560
+ }
561
+ }
562
+
563
+ if (!storeToFile) {
564
+ String encodedImage = Base64.encodeToString(data, Base64.NO_WRAP);
565
+
566
+ eventListener.onPictureTaken(encodedImage);
567
+ } else {
568
+ String path = getTempFilePath();
569
+ FileOutputStream out = new FileOutputStream(path);
570
+ out.write(data);
571
+ out.close();
572
+ eventListener.onPictureTaken(path);
573
+ }
574
+ Log.d(TAG, "CameraPreview pictureTakenHandler called back");
575
+ } catch (OutOfMemoryError e) {
576
+ // most likely failed to allocate memory for rotateBitmap
577
+ Log.d(TAG, "CameraPreview OutOfMemoryError");
578
+ // failed to allocate memory
579
+ eventListener.onPictureTakenError("Picture too large (memory)");
580
+ } catch (IOException e) {
581
+ Log.d(TAG, "CameraPreview IOException");
582
+ eventListener.onPictureTakenError("IO Error when extracting exif");
583
+ } catch (Exception e) {
584
+ Log.d(TAG, "CameraPreview onPictureTaken general exception");
585
+ } finally {
586
+ canTakePicture = true;
587
+ mCamera.startPreview();
588
+ }
589
+ }
590
+ };
591
+
592
+ private Camera.Size getOptimalPictureSize(
593
+ final int width,
594
+ final int height,
595
+ final Camera.Size previewSize,
596
+ final List<Camera.Size> supportedSizes
597
+ ) {
598
+ /*
599
+ get the supportedPictureSize that:
600
+ - matches exactly width and height
601
+ - has the closest aspect ratio to the preview aspect ratio
602
+ - has picture.width and picture.height closest to width and height
603
+ - has the highest supported picture width and height up to 2 Megapixel if width == 0 || height == 0
604
+ */
605
+ Camera.Size size = mCamera.new Size(width, height);
606
+
607
+ // convert to landscape if necessary
608
+ if (size.width < size.height) {
609
+ int temp = size.width;
610
+ size.width = size.height;
611
+ size.height = temp;
612
+ }
613
+
614
+ Camera.Size requestedSize = mCamera.new Size(size.width, size.height);
615
+
616
+ double previewAspectRatio = (double) previewSize.width / (double) previewSize.height;
617
+
618
+ if (previewAspectRatio < 1.0) {
619
+ // reset ratio to landscape
620
+ previewAspectRatio = 1.0 / previewAspectRatio;
621
+ }
622
+
623
+ Log.d(TAG, "CameraPreview previewAspectRatio " + previewAspectRatio);
624
+
625
+ double aspectTolerance = 0.1;
626
+ double bestDifference = Double.MAX_VALUE;
627
+
628
+ for (int i = 0; i < supportedSizes.size(); i++) {
629
+ Camera.Size supportedSize = supportedSizes.get(i);
630
+
631
+ // Perfect match
632
+ if (supportedSize.equals(requestedSize)) {
633
+ Log.d(TAG, "CameraPreview optimalPictureSize " + supportedSize.width + 'x' + supportedSize.height);
634
+ return supportedSize;
635
+ }
636
+
637
+ double difference = Math.abs(previewAspectRatio - ((double) supportedSize.width / (double) supportedSize.height));
638
+
639
+ if (difference < bestDifference - aspectTolerance) {
640
+ // better aspectRatio found
641
+ if ((width != 0 && height != 0) || (supportedSize.width * supportedSize.height < 2048 * 1024)) {
642
+ size.width = supportedSize.width;
643
+ size.height = supportedSize.height;
644
+ bestDifference = difference;
645
+ }
646
+ } else if (difference < bestDifference + aspectTolerance) {
647
+ // same aspectRatio found (within tolerance)
648
+ if (width == 0 || height == 0) {
649
+ // set highest supported resolution below 2 Megapixel
650
+ if ((size.width < supportedSize.width) && (supportedSize.width * supportedSize.height < 2048 * 1024)) {
651
+ size.width = supportedSize.width;
652
+ size.height = supportedSize.height;
653
+ }
654
+ } else {
655
+ // check if this pictureSize closer to requested width and height
656
+ if (
657
+ Math.abs(width * height - supportedSize.width * supportedSize.height) <
658
+ Math.abs(width * height - size.width * size.height)
659
+ ) {
660
+ size.width = supportedSize.width;
661
+ size.height = supportedSize.height;
662
+ }
663
+ }
664
+ }
665
+ }
666
+ Log.d(TAG, "CameraPreview optimalPictureSize " + size.width + 'x' + size.height);
667
+ return size;
668
+ }
669
+
670
+ static byte[] rotateNV21(final byte[] yuv, final int width, final int height, final int rotation) {
671
+ if (rotation == 0) return yuv;
672
+ if (rotation % 90 != 0 || rotation < 0 || rotation > 270) {
673
+ throw new IllegalArgumentException("0 <= rotation < 360, rotation % 90 == 0");
674
+ }
675
+
676
+ final byte[] output = new byte[yuv.length];
677
+ final int frameSize = width * height;
678
+ final boolean swap = rotation % 180 != 0;
679
+ final boolean xflip = rotation % 270 != 0;
680
+ final boolean yflip = rotation >= 180;
681
+
682
+ for (int j = 0; j < height; j++) {
683
+ for (int i = 0; i < width; i++) {
684
+ final int yIn = j * width + i;
685
+ final int uIn = frameSize + (j >> 1) * width + (i & ~1);
686
+ final int vIn = uIn + 1;
687
+
688
+ final int wOut = swap ? height : width;
689
+ final int hOut = swap ? width : height;
690
+ final int iSwapped = swap ? j : i;
691
+ final int jSwapped = swap ? i : j;
692
+ final int iOut = xflip ? wOut - iSwapped - 1 : iSwapped;
693
+ final int jOut = yflip ? hOut - jSwapped - 1 : jSwapped;
694
+
695
+ final int yOut = jOut * wOut + iOut;
696
+ final int uOut = frameSize + (jOut >> 1) * wOut + (iOut & ~1);
697
+ final int vOut = uOut + 1;
698
+
699
+ output[yOut] = (byte) (0xff & yuv[yIn]);
700
+ output[uOut] = (byte) (0xff & yuv[uIn]);
701
+ output[vOut] = (byte) (0xff & yuv[vIn]);
702
+ }
703
+ }
704
+ return output;
705
+ }
706
+
707
+ public void setOpacity(final float opacity) {
708
+ Log.d(TAG, "set opacity:" + opacity);
709
+ this.opacity = opacity;
710
+ mPreview.setOpacity(opacity);
711
+ }
712
+
713
+ public void takeSnapshot(final int quality) {
714
+ mCamera.setPreviewCallback(
715
+ new Camera.PreviewCallback() {
716
+ @Override
717
+ public void onPreviewFrame(byte[] bytes, Camera camera) {
718
+ try {
719
+ Camera.Parameters parameters = camera.getParameters();
720
+ Camera.Size size = parameters.getPreviewSize();
721
+ int orientation = mPreview.getDisplayOrientation();
722
+ if (mPreview.getCameraFacing() == Camera.CameraInfo.CAMERA_FACING_FRONT) {
723
+ bytes = rotateNV21(bytes, size.width, size.height, (360 - orientation) % 360);
724
+ } else {
725
+ bytes = rotateNV21(bytes, size.width, size.height, orientation);
726
+ }
727
+ // switch width/height when rotating 90/270 deg
728
+ Rect rect = orientation == 90 || orientation == 270
729
+ ? new Rect(0, 0, size.height, size.width)
730
+ : new Rect(0, 0, size.width, size.height);
731
+ YuvImage yuvImage = new YuvImage(bytes, parameters.getPreviewFormat(), rect.width(), rect.height(), null);
732
+ ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
733
+ yuvImage.compressToJpeg(rect, quality, byteArrayOutputStream);
734
+ byte[] data = byteArrayOutputStream.toByteArray();
735
+ byteArrayOutputStream.close();
736
+ eventListener.onSnapshotTaken(Base64.encodeToString(data, Base64.NO_WRAP));
737
+ } catch (IOException e) {
738
+ Log.d(TAG, "CameraPreview IOException");
739
+ eventListener.onSnapshotTakenError("IO Error");
740
+ } finally {
741
+ mCamera.setPreviewCallback(null);
742
+ }
743
+ }
744
+ }
745
+ );
746
+ }
747
+
748
+ public void takePicture(final int width, final int height, final int quality) {
749
+ Log.d(TAG, "CameraPreview takePicture width: " + width + ", height: " + height + ", quality: " + quality);
750
+
751
+ if (mPreview != null) {
752
+ if (!canTakePicture) {
753
+ return;
754
+ }
755
+
756
+ canTakePicture = false;
757
+
758
+ new Thread() {
759
+ public void run() {
760
+ Camera.Parameters params = mCamera.getParameters();
761
+
762
+ Camera.Size size = getOptimalPictureSize(width, height, params.getPreviewSize(), params.getSupportedPictureSizes());
763
+ params.setPictureSize(size.width, size.height);
764
+ currentQuality = quality;
765
+
766
+ if (cameraCurrentlyLocked == Camera.CameraInfo.CAMERA_FACING_FRONT && !storeToFile) {
767
+ // The image will be recompressed in the callback
768
+ params.setJpegQuality(99);
769
+ } else {
770
+ params.setJpegQuality(quality);
771
+ }
772
+
773
+ if (cameraCurrentlyLocked == Camera.CameraInfo.CAMERA_FACING_FRONT && disableExifHeaderStripping) {
774
+ Activity activity = getActivity();
775
+ int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
776
+ int degrees = 0;
777
+ switch (rotation) {
778
+ case Surface.ROTATION_0:
779
+ degrees = 0;
780
+ break;
781
+ case Surface.ROTATION_90:
782
+ degrees = 180;
783
+ break;
784
+ case Surface.ROTATION_180:
785
+ degrees = 270;
786
+ break;
787
+ case Surface.ROTATION_270:
788
+ degrees = 0;
789
+ break;
790
+ }
791
+ int orientation;
792
+ Camera.CameraInfo info = new Camera.CameraInfo();
793
+ if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
794
+ orientation = (info.orientation + degrees) % 360;
795
+ if (degrees != 0) {
796
+ orientation = (360 - orientation) % 360;
797
+ }
798
+ } else {
799
+ orientation = (info.orientation - degrees + 360) % 360;
800
+ }
801
+ params.setRotation(orientation);
802
+ } else {
803
+ params.setRotation(mPreview.getDisplayOrientation());
804
+ }
805
+
806
+ mCamera.setParameters(params);
807
+ mCamera.takePicture(shutterCallback, null, jpegPictureCallback);
808
+ }
809
+ }
810
+ .start();
811
+ } else {
812
+ canTakePicture = true;
813
+ }
814
+ }
815
+
816
+ public void startRecord(
817
+ final String filePath,
818
+ final String camera,
819
+ final int width,
820
+ final int height,
821
+ final int quality,
822
+ final boolean withFlash,
823
+ final int maxDuration,
824
+ final String lens
825
+ ) {
826
+ Log.d(TAG, "CameraPreview startRecord camera: " + camera + " width: " + width + ", height: " + height + ", quality: " + quality + ", lens: " + lens);
827
+ Activity activity = getActivity();
828
+ muteStream(true, activity);
829
+ if (this.mRecordingState == RecordingState.STARTED) {
830
+ Log.d(TAG, "Already Recording");
831
+ return;
832
+ }
833
+
834
+ this.recordFilePath = filePath;
835
+ int mOrientationHint = calculateOrientationHint();
836
+ int videoWidth = 0; //set whatever
837
+ int videoHeight = 0; //set whatever
838
+
839
+ Camera.Parameters cameraParams = mCamera.getParameters();
840
+ if (withFlash) {
841
+ cameraParams.setFlashMode(withFlash ? Camera.Parameters.FLASH_MODE_TORCH : Camera.Parameters.FLASH_MODE_OFF);
842
+ mCamera.setParameters(cameraParams);
843
+ mCamera.startPreview();
844
+ }
845
+
846
+ mCamera.unlock();
847
+ mRecorder = new MediaRecorder();
848
+
849
+ try {
850
+ mRecorder.setCamera(mCamera);
851
+
852
+ CamcorderProfile profile;
853
+ if (CamcorderProfile.hasProfile(defaultCameraId, CamcorderProfile.QUALITY_HIGH)) {
854
+ profile = CamcorderProfile.get(defaultCameraId, CamcorderProfile.QUALITY_HIGH);
855
+ } else {
856
+ if (CamcorderProfile.hasProfile(defaultCameraId, CamcorderProfile.QUALITY_480P)) {
857
+ profile = CamcorderProfile.get(defaultCameraId, CamcorderProfile.QUALITY_480P);
858
+ } else {
859
+ if (CamcorderProfile.hasProfile(defaultCameraId, CamcorderProfile.QUALITY_720P)) {
860
+ profile = CamcorderProfile.get(defaultCameraId, CamcorderProfile.QUALITY_720P);
861
+ } else {
862
+ if (CamcorderProfile.hasProfile(defaultCameraId, CamcorderProfile.QUALITY_1080P)) {
863
+ profile = CamcorderProfile.get(defaultCameraId, CamcorderProfile.QUALITY_1080P);
864
+ } else {
865
+ profile = CamcorderProfile.get(defaultCameraId, CamcorderProfile.QUALITY_LOW);
866
+ }
867
+ }
868
+ }
869
+ }
870
+
871
+ mRecorder.setAudioSource(MediaRecorder.AudioSource.VOICE_RECOGNITION);
872
+ mRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
873
+ mRecorder.setProfile(profile);
874
+ mRecorder.setOutputFile(filePath);
875
+ mRecorder.setOrientationHint(mOrientationHint);
876
+ mRecorder.setMaxDuration(maxDuration);
877
+
878
+ mRecorder.prepare();
879
+ Log.d(TAG, "Starting recording");
880
+ mRecorder.start();
881
+ eventListener.onStartRecordVideo();
882
+ } catch (IOException e) {
883
+ eventListener.onStartRecordVideoError(e.getMessage());
884
+ }
885
+ }
886
+
887
+ public int calculateOrientationHint() {
888
+ DisplayMetrics dm = new DisplayMetrics();
889
+ Camera.CameraInfo info = new Camera.CameraInfo();
890
+ Camera.getCameraInfo(defaultCameraId, info);
891
+ int cameraRotationOffset = info.orientation;
892
+ Activity activity = getActivity();
893
+
894
+ activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
895
+ int currentScreenRotation = activity.getWindowManager().getDefaultDisplay().getRotation();
896
+
897
+ int degrees = 0;
898
+ switch (currentScreenRotation) {
899
+ case Surface.ROTATION_0:
900
+ degrees = 0;
901
+ break;
902
+ case Surface.ROTATION_90:
903
+ degrees = 90;
904
+ break;
905
+ case Surface.ROTATION_180:
906
+ degrees = 180;
907
+ break;
908
+ case Surface.ROTATION_270:
909
+ degrees = 270;
910
+ break;
911
+ }
912
+
913
+ int orientation;
914
+ if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
915
+ orientation = (cameraRotationOffset + degrees) % 360;
916
+ if (degrees != 0) {
917
+ orientation = (360 - orientation) % 360;
918
+ }
919
+ } else {
920
+ orientation = (cameraRotationOffset - degrees + 360) % 360;
921
+ }
922
+ Log.w(TAG, "************orientationHint ***********= " + orientation);
923
+
924
+ return orientation;
925
+ }
926
+
927
+ public void stopRecord() {
928
+ Log.d(TAG, "stopRecord");
929
+
930
+ try {
931
+ mRecorder.stop();
932
+ mRecorder.reset(); // clear recorder configuration
933
+ mRecorder.release(); // release the recorder object
934
+ mRecorder = null;
935
+ mCamera.lock();
936
+ Camera.Parameters cameraParams = mCamera.getParameters();
937
+ cameraParams.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
938
+ mCamera.setParameters(cameraParams);
939
+ mCamera.startPreview();
940
+ eventListener.onStopRecordVideo(this.recordFilePath);
941
+ } catch (Exception e) {
942
+ eventListener.onStopRecordVideoError(e.getMessage());
943
+ }
944
+ }
945
+
946
+ public void muteStream(boolean mute, Activity activity) {
947
+ AudioManager audioManager = ((AudioManager) activity.getApplicationContext().getSystemService(Context.AUDIO_SERVICE));
948
+ int direction = mute ? audioManager.ADJUST_MUTE : audioManager.ADJUST_UNMUTE;
949
+ }
950
+
951
+ public void setFocusArea(final int pointX, final int pointY, final Camera.AutoFocusCallback callback) {
952
+ if (mCamera != null) {
953
+ mCamera.cancelAutoFocus();
954
+
955
+ Camera.Parameters parameters = mCamera.getParameters();
956
+
957
+ Rect focusRect = calculateTapArea(pointX, pointY, 1f);
958
+ parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
959
+ parameters.setFocusAreas(Arrays.asList(new Camera.Area(focusRect, 1000)));
960
+
961
+ if (parameters.getMaxNumMeteringAreas() > 0) {
962
+ Rect meteringRect = calculateTapArea(pointX, pointY, 1.5f);
963
+ parameters.setMeteringAreas(Arrays.asList(new Camera.Area(meteringRect, 1000)));
964
+ }
965
+
966
+ try {
967
+ setCameraParameters(parameters);
968
+ mCamera.autoFocus(callback);
969
+ } catch (Exception e) {
970
+ Log.d(TAG, e.getMessage());
971
+ callback.onAutoFocus(false, this.mCamera);
972
+ }
973
+ }
974
+ }
975
+
976
+ private Rect calculateTapArea(float x, float y, float coefficient) {
977
+ if (x < 100) {
978
+ x = 100;
979
+ }
980
+ if (x > width - 100) {
981
+ x = width - 100;
982
+ }
983
+ if (y < 100) {
984
+ y = 100;
985
+ }
986
+ if (y > height - 100) {
987
+ y = height - 100;
988
+ }
989
+ return new Rect(
990
+ Math.round((x - 100) * 2000 / width - 1000),
991
+ Math.round((y - 100) * 2000 / height - 1000),
992
+ Math.round((x + 100) * 2000 / width - 1000),
993
+ Math.round((y + 100) * 2000 / height - 1000)
994
+ );
995
+ }
996
+
997
+ /**
998
+ * Determine the space between the first two fingers
999
+ */
1000
+ private static float getFingerSpacing(MotionEvent event) {
1001
+ // ...
1002
+ float x = event.getX(0) - event.getX(1);
1003
+ float y = event.getY(0) - event.getY(1);
1004
+ return (float) Math.sqrt(x * x + y * y);
1005
+ }
1006
+ }