Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

single callback video event #81

Merged
merged 23 commits into from
Aug 16, 2024
Merged
Show file tree
Hide file tree
Changes from 12 commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions plugin.xml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
<framework src="androidx.camera:camera-camera2:1.1.0" />
<framework src="androidx.camera:camera-lifecycle:1.1.0" />
<framework src="androidx.camera:camera-view:1.1.0" />
<framework src="androidx.camera:camera-video:1.1.0" />

<source-file src="src/android/CameraPreviewFragment.java" target-dir="src/com/spoon/simplecamerapreview" />
<source-file src="src/android/SimpleCameraPreview.java" target-dir="src/com/spoon/simplecamerapreview" />
Expand Down
103 changes: 98 additions & 5 deletions src/android/CameraPreviewFragment.java
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
package com.spoon.simplecamerapreview;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Point;
import android.hardware.camera2.CameraCharacteristics;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
Expand All @@ -29,8 +33,17 @@
import androidx.camera.core.ImageCaptureException;
import androidx.camera.core.Preview;
import androidx.camera.lifecycle.ProcessCameraProvider;
import androidx.camera.video.FileOutputOptions;
import androidx.camera.video.Quality;
import androidx.camera.video.QualitySelector;
import androidx.camera.video.Recorder;
import androidx.camera.video.Recording;
import androidx.camera.video.VideoCapture;
import androidx.camera.video.VideoRecordEvent;
import androidx.camera.view.PreviewView;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import androidx.exifinterface.media.ExifInterface;
import androidx.fragment.app.Fragment;

Expand All @@ -51,6 +64,12 @@ interface CameraCallback {
void onCompleted(Exception err, String nativePath);
}

interface VideoCallback {
void onStart(Boolean recording, String nativePath);
void onStop(Boolean recording, String nativePath);
void onError(String errMessage);
}

interface CameraStartedCallback {
void onCameraStarted(Exception err);
}
Expand All @@ -76,6 +95,9 @@ public class CameraPreviewFragment extends Fragment {
private PreviewView viewFinder;
private Preview preview;
private ImageCapture imageCapture;
private VideoCapture<Recorder> videoCapture;
Recording recording = null;
ProcessCameraProvider cameraProvider = null;
private Camera camera;
private CameraStartedCallback startCameraCallback;
private Location location;
Expand Down Expand Up @@ -120,13 +142,11 @@ public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup c
viewFinder.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT));
containerView.addView(viewFinder);
startCamera();

return containerView;
}

public void startCamera() {
ListenableFuture<ProcessCameraProvider> cameraProviderFuture = ProcessCameraProvider.getInstance(getActivity());
ProcessCameraProvider cameraProvider = null;

try {
cameraProvider = cameraProviderFuture.get();
Expand Down Expand Up @@ -258,6 +278,67 @@ public void hasFlash(HasFlashCallback hasFlashCallback) {
hasFlashCallback.onResult(camera.getCameraInfo().hasFlashUnit());
}

public void startVideoCapture(VideoCallback videoCallback) {
if (ActivityCompat.checkSelfPermission(this.getContext(), Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this.getActivity(), new String[]{Manifest.permission.RECORD_AUDIO}, 200);
}

if (recording != null) {
recording.stop();
recording = null;
return;
}

UUID uuid = UUID.randomUUID();
String filename = uuid.toString() + ".mp4";

File videoFile = new File(
getContext().getFilesDir(),
filename
);

FileOutputOptions outputOptions = new FileOutputOptions.Builder(videoFile).build();

final Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
@Override
public void run() {
stopVideoCapture();
}
}, 30000);

recording = videoCapture.getOutput()
.prepareRecording(this.getContext().getApplicationContext(), outputOptions)
.withAudioEnabled()
.start(ContextCompat.getMainExecutor(this.getContext()), videoRecordEvent -> {
if (videoRecordEvent instanceof VideoRecordEvent.Start) {
videoCallback.onStart(true, null);
} else if (videoRecordEvent instanceof VideoRecordEvent.Finalize) {
VideoRecordEvent.Finalize finalizeEvent = (VideoRecordEvent.Finalize) videoRecordEvent;
handler.removeCallbacksAndMessages(null);
if (finalizeEvent.hasError()) {
int errorCode = finalizeEvent.getError();
Throwable errorCause = finalizeEvent.getCause();
videoCallback.onError(errorCode + " " + errorCause);
} else {
videoCallback.onStop(false, Uri.fromFile(videoFile).toString());
Uri savedUri = finalizeEvent.getOutputResults().getOutputUri();
}
recording = null;
}
});

}

public void stopVideoCapture() {
if (recording != null) {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we have to put this,

Suggested change
if (recording != null) {
if (recording != null && recording == true) {

recording.stop();
recording = null;
}
}



public void takePicture(boolean useFlash, CameraCallback takePictureCallback) {
if (torchActivated) {
useFlash = true;
Expand Down Expand Up @@ -398,18 +479,24 @@ public void setUpCamera(String lens, ProcessCameraProvider cameraProvider) {
targetResolution = CameraPreviewFragment.calculateResolution(getContext(), targetSize);
}

Recorder recorder = new Recorder.Builder()
.setQualitySelector(QualitySelector.from(Quality.LOWEST))
.build();
videoCapture = VideoCapture.withOutput(recorder);


preview = new Preview.Builder().build();
imageCapture = new ImageCapture.Builder()
.setTargetResolution(targetResolution)
.build();

cameraProvider.unbindAll();
try {
camera = cameraProvider.bindToLifecycle(
getActivity(),
cameraSelector,
preview,
imageCapture
imageCapture,
videoCapture
);
} catch (IllegalArgumentException e) {
// Error with result in capturing image with default resolution
Expand All @@ -420,9 +507,15 @@ public void setUpCamera(String lens, ProcessCameraProvider cameraProvider) {
getActivity(),
cameraSelector,
preview,
imageCapture
imageCapture,
videoCapture
);
}
}

@Override
public void onPause() {
super.onPause();
this.stopVideoCapture();
}
}
94 changes: 94 additions & 0 deletions src/android/SimpleCameraPreview.java
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@ public class SimpleCameraPreview extends CordovaPlugin {
private LocationManager locationManager;
private LocationListener mLocationCallback;
private ViewParent webViewParent;
private CallbackContext videoCallbackContext;


private static final int containerViewId = 20;
private static final int DIRECTION_FRONT = 0;
Expand Down Expand Up @@ -72,6 +74,15 @@ public boolean execute(String action, JSONArray args, CallbackContext callbackCo
case "torchSwitch":
return torchSwitch(args.getBoolean(0), callbackContext);

case "initVideoCallback":
return initVideoCallback(callbackContext);

case "startVideoCapture":
return startVideoCapture(callbackContext);

case "stopVideoCapture":
return stopVideoCapture(callbackContext);

case "deviceHasFlash":
return deviceHasFlash(callbackContext);

Expand All @@ -92,6 +103,89 @@ public boolean execute(String action, JSONArray args, CallbackContext callbackCo
}
}

private boolean initVideoCallback(CallbackContext callbackContext) {
this.videoCallbackContext = callbackContext;
PluginResult result = new PluginResult(PluginResult.Status.OK, "video cb initialized");
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
PluginResult result = new PluginResult(PluginResult.Status.OK, "video cb initialized");
PluginResult result = new PluginResult(PluginResult.Status.OK, "video callback initialized");

result.setKeepCallback(true);
this.videoCallbackContext.sendPluginResult(result);
return true;
}

private boolean startVideoCapture(CallbackContext callbackContext) {
if (fragment == null) {
callbackContext.error("Camera is closed");
return true;
}

if (this.videoCallbackContext != null) {
fragment.startVideoCapture(new VideoCallback() {
public void onStart(Boolean recording, String nativePath) {
JSONObject data = new JSONObject();
if (recording) {
try {
data.put("recording", true);
data.put("nativePath", null);
} catch (JSONException e) {
e.printStackTrace();
videoCallbackContext.error("Cannot send recording data");
return;
}

PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, data);
pluginResult.setKeepCallback(true);
videoCallbackContext.sendPluginResult(pluginResult);
}
}

public void onStop(Boolean recording, String nativePath) {
JSONObject data = new JSONObject();
try {
data.put("recording", false);
data.put("nativePath", nativePath);
} catch (JSONException e) {
e.printStackTrace();
videoCallbackContext.error("Cannot send recording data");
return;
}
PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, data);
pluginResult.setKeepCallback(true);
videoCallbackContext.sendPluginResult(pluginResult);
}

@Override
public void onError(String errMessage) {
JSONObject data = new JSONObject();
try {
data.put("error", errMessage);
} catch (JSONException e) {
e.printStackTrace();
return;
}
PluginResult pluginResult = new PluginResult(PluginResult.Status.ERROR, data);
pluginResult.setKeepCallback(true);
videoCallbackContext.sendPluginResult(pluginResult);
}
});
}
callbackContext.success();
return true;
}


private boolean stopVideoCapture(CallbackContext callbackContext) {
if (fragment == null) {
callbackContext.error("Camera is closed");
return true;
}

if (this.videoCallbackContext != null) {
fragment.stopVideoCapture();
}

callbackContext.success();
return true;
}

private boolean setOptions(JSONObject options, CallbackContext callbackContext) {
int targetSize = 0;
try {
Expand Down
36 changes: 36 additions & 0 deletions www/SimpleCameraPreview.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,41 @@ var exec = require("cordova/exec");
var PLUGIN_NAME = "SimpleCameraPreview";
var SimpleCameraPreview = function () {};

SimpleCameraPreview.videoInitialized = false;
SimpleCameraPreview.videoCallback = null;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
SimpleCameraPreview.videoCallback = null;

I think videoInitialized is enough and storing videoCallback as global is not required

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@zfir we can consider it as a refactoring for the next version


SimpleCameraPreview.startVideoCapture = function (onSuccess, onError) {
if (!SimpleCameraPreview.videoCallback) {
console.error("Call setVideoCallback first");
onError("Call setVideoCallback first");
return;
}

if (!SimpleCameraPreview.videoInitialized) {
exec(
(info) => {
SimpleCameraPreview.videoInitialized = true;
this.videoCallback(info);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
this.videoCallback(info);
onSuccess(info);

} ,
(err) => {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
(err) => {
(err) => {

this.videoCallback(null, err);
},
"SimpleCameraPreview",
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
"SimpleCameraPreview",
PLUGIN_NAME,

"initVideoCallback",
[]
);
}
exec(onSuccess, onError, PLUGIN_NAME, "startVideoCapture");
dinitri marked this conversation as resolved.
Show resolved Hide resolved
};

SimpleCameraPreview.stopVideoCapture = function (onSuccess, onError) {
exec(onSuccess, onError, PLUGIN_NAME, "stopVideoCapture");
};

SimpleCameraPreview.setVideoCallback = function (callback) {
this.videoCallback = callback;
}

SimpleCameraPreview.setOptions = function (options, onSuccess, onError) {
exec(onSuccess, onError, PLUGIN_NAME, "setOptions", [options]);
};
Expand Down Expand Up @@ -43,3 +78,4 @@ SimpleCameraPreview.deviceHasUltraWideCamera = function (onSuccess, onError) {
};

module.exports = SimpleCameraPreview;

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change

Loading