librealsense icon indicating copy to clipboard operation
librealsense copied to clipboard

Java application crashes at random time using realsense2.dll with JNI.

Open AkhmedAnam opened this issue 8 years ago • 13 comments

  • Before opening a new issue, we wanted to provide you with some useful suggestions (Click "Preview" above for a better view):

  • All users are welcomed to report bugs, ask questions, suggest or request enhancements and generally feel free to open new issue, even if they haven't followed any of the suggestions above :)


Required Info
Camera Model { R200 / F200 / SR300 / ZR300 / D400 }
Firmware Version (Open RealSense Viewer --> Click info)
Operating System & Version {Win (8.1/10) / Linux (Ubuntu 14/16/17) / MacOS
Kernel Version (Linux Only) (e.g. 4.14.13)
Platform PC/Raspberry Pi/ NVIDIA Jetson / etc..
SDK Version { legacy / 2.. }
Language {C/C#/labview/nodejs/opencv/pcl/python/unity }
Segment {Robot/Smartphone/VR/AR/others }

Issue Description

I write a Java application using JNI. In the JNI code I use sdk2 (realsense2.dll). My application works but sometimes (at random time) it crashes. Windows system log report that problem in realsense2.dll. What it may be?

AkhmedAnam avatar Aug 31 '18 13:08 AkhmedAnam

Hi @AkhmedAnam This depends mainly on what you are doing in the JNI layer. We provide debug symbols with our Windows installers that can help you get the call-stack of the crash in any debugger. Please provide more information on the JNI code and your use case.

dorodnic avatar Sep 02 '18 06:09 dorodnic

Hi @dorodnic Where can I get a pdb file for the realsense2.dll? I installed SDK2 with a windows installer and there are not any pdb files in the install directory.

AkhmedAnam avatar Sep 06 '18 09:09 AkhmedAnam

There is a checkbox in the installer to include PDBs (debug symbols)

dorodnic avatar Sep 06 '18 09:09 dorodnic

@dorodnic, thank you very much. I found pdb files. Спасибо;)

AkhmedAnam avatar Sep 06 '18 11:09 AkhmedAnam

I got a dump file for the crushed app but it doesn't clarify the situation. I saw the call stack made up of one call: abort() (librealsense2.dll - line number 77) (see the image) default I will leave below source code of JNI wrapper and the Java class used natives methods. Could you explain me what wrong am I doing? Here my JNI code: `// RealSenseSDK2_JNI_wrapper.cpp: определяет экспортированные функции для приложения DLL. // #include "stdafx.h" #include "rs.hpp" #include"rsutil.h" #include "ru_eleron_oko_scanner_core_api_sdk2_RealSenseGrabberSDK2.h"

typedef unsigned short ushort;

rs2::config* getConfig() { static rs2::config *desiredStreamConfig = new rs2::config(); return desiredStreamConfig; }

rs2::pipeline* getPipeLine() { static rs2::pipeline *pipeline = new rs2::pipeline(); return pipeline; }

std::pair<jclass, jmethodID> getRealsenseImageClass(JNIEnv *env) { static jclass classID = (jclass)env->NewGlobalRef(env->FindClass("ru/eleron/oko/scanner/core/api/sdk2/RealSenseSDK2Image")); static jmethodID constrID = env->GetMethodID(classID, "", "(IIIDI[B)V"); std::pair<jclass, jmethodID> result = std::pair<jclass, jmethodID>(classID, constrID); return result; }

std::pair<jclass, jmethodID> getRealsenseImageChainClass(JNIEnv *env) { static jclass classID = (jclass)env->NewGlobalRef(env->FindClass("ru/eleron/oko/scanner/core/api/sdk2/RealSenseSDK2ImageChain")); static jmethodID constrID = env->GetMethodID( classID, "", "(Lru/eleron/oko/scanner/core/api/sdk2/RealSenseSDK2Image;Lru/eleron/oko/scanner/core/api/sdk2/RealSenseSDK2Image;F)V" ); std::pair<jclass, jmethodID> result = std::pair<jclass, jmethodID>(classID, constrID); return result; }

jmethodID getRealsenseImageChainSetColorImageMethodId(JNIEnv *env, jclass classId) { static jmethodID setColorMethodId = env->GetMethodID(classId, "setColorImage", "(Lru/eleron/oko/scanner/core/api/sdk2/RealSenseSDK2Image;)V"); return setColorMethodId; }

jmethodID getRealsenseImageChainSetDepthImageMethodId(JNIEnv *env, jclass classId) { static jmethodID setColorMethodId = env->GetMethodID(classId, "setDepthImage", "(Lru/eleron/oko/scanner/core/api/sdk2/RealSenseSDK2Image;)V"); return setColorMethodId; }

jmethodID getRealsenseImageChainSetDepthScaleMethodId(JNIEnv *env, jclass classId) { static jmethodID setColorMethodId = env->GetMethodID(classId, "setDepthScale", "(F)V"); return setColorMethodId; }

jclass getJavaStreamTypeClass(JNIEnv *env) { static jclass classID = (jclass)env->NewGlobalRef(env->FindClass("ru/eleron/oko/scanner/core/api/sdk2/RealSenseSDK2StreamType")); return classID; }

jclass getJavaPixelTypeClass(JNIEnv *env) { static jclass classID = (jclass)env->NewGlobalRef(env->FindClass("ru/eleron/oko/scanner/core/api/sdk2/PixelFormatSDK2")); return classID; }

jmethodID getWidthStreamProfileMethodId(JNIEnv *env, jclass& classId) { static jmethodID getWidthID = env->GetMethodID(classId, "getWidthInPixels", "()I"); return getWidthID; }

jmethodID getHeightStreamProfileMethodId(JNIEnv *env, jclass& classId) { static jmethodID getHeightID = env->GetMethodID(classId, "getHeightInPixels", "()I"); return getHeightID; }

jmethodID getStreamTypeStreamProfileMethodId(JNIEnv *env, jclass& classId) { static jmethodID getStreamTypeID = env->GetMethodID(classId, "getRealSenseSDK2StreamType", "()Lru/eleron/oko/scanner/core/api/sdk2/RealSenseSDK2StreamType;"); return getStreamTypeID; }

jmethodID getFpsStreamProfileMethodId(JNIEnv *env, jclass& classId) { static jmethodID getFpsID = env->GetMethodID(classId, "getFps", "()F"); return getFpsID; }

jmethodID getPixelFormatStreamProfileMethodId(JNIEnv *env, jclass& classId) { static jmethodID getPfID = env->GetMethodID(classId, "getPixelFormatSDK2", "()Lru/eleron/oko/scanner/core/api/sdk2/PixelFormatSDK2;"); return getPfID; } jmethodID getIdMethodId(JNIEnv *env, jclass& classId) { static jmethodID getID = env->GetMethodID(classId, "getId", "()I"); return getID; }

std::pair<jclass, jmethodID> getDeviceModelClassAndCnstrId(JNIEnv *env) { static jclass classID = (jclass)env->NewGlobalRef(env->FindClass("ru/eleron/oko/scanner/core/api/DeviceModel")); static jmethodID constrID = env->GetMethodID(classID, "", "()V"); std::pair<jclass, jmethodID> result = std::pair<jclass, jmethodID>(classID, constrID); return result; }

jmethodID getDeviceModelSetNameMethodId(JNIEnv *env, jclass deviceModelClass) { static jmethodID methodId = env->GetMethodID(deviceModelClass, "setName", "(Ljava/lang/String;)V"); return methodId; }

jmethodID getDeviceModelSetSerialMethodId(JNIEnv *env, jclass deviceModelClass) { static jmethodID methodId = env->GetMethodID(deviceModelClass, "setSerial", "(Ljava/lang/String;)V"); return methodId; }

jmethodID getDeviceModelSetFirmwareMethodId(JNIEnv *env, jclass deviceModelClass) { static jmethodID methodId = env->GetMethodID(deviceModelClass, "setFirmware", "(Ljava/lang/String;)V"); return methodId; }

jmethodID getSetNamelDeviceModelMethodId(JNIEnv *env, jclass classId) { static jmethodID setNameMethID = env->GetMethodID(classId, "setName", "(Ljava/lang/String;)V"); return setNameMethID; }

jmethodID getSetSerialDeviceModelMethodId(JNIEnv *env, jclass classId) { static jmethodID setNameMethID = env->GetMethodID(classId, "setSerial", "(Ljava/lang/String;)V"); return setNameMethID; }

jmethodID getSetFirmwareDeviceModelMethodId(JNIEnv *env, jclass classId) { static jmethodID setNameMethID = env->GetMethodID(classId, "setFirmware", "(Ljava/lang/String;)V"); return setNameMethID; }

std::pair<jclass, jmethodID> getDimensionClassAndCnstrId(JNIEnv *env) { static jclass classID = (jclass)env->NewGlobalRef(env->FindClass("java/awt/Dimension")); static jmethodID constrID = env->GetMethodID(classID, "", "(II)V"); std::pair<jclass, jmethodID> result = std::pair<jclass, jmethodID>(classID, constrID); return result; }

jmethodID getDimesionSetSizeMethodId(JNIEnv *env, jclass classId) { static jmethodID resId = env->GetMethodID(classId, "setSize", "(DD)V"); return resId; }

std::pair<jclass, jmethodID> getArrayListClassAndCnstrId(JNIEnv *env) { static jclass classID = (jclass)env->NewGlobalRef(env->FindClass("java/util/ArrayList")); static jmethodID constrID = env->GetMethodID(classID, "", "()V"); std::pair<jclass, jmethodID> result = std::pair<jclass, jmethodID>(classID, constrID); return result; }

jmethodID getArrayListAddMethodId(JNIEnv *env, jclass classId) { static jmethodID arrayListAddID = env->GetMethodID(classId, "add", "(Ljava/lang/Object;)Z"); return arrayListAddID; }

std::pair<jclass, jmethodID> getResolutionFpsCoupleClassAndCnstrId(JNIEnv *env) { static jclass classID = (jclass)env->NewGlobalRef(env->FindClass("ru/eleron/oko/scanner/core/api/sdk2/ResolutionFpsCoupleSDK2")); static jmethodID constrID = env->GetMethodID(classID, "", "(Ljava/awt/Dimension;F)V"); std::pair<jclass, jmethodID> result = std::pair<jclass, jmethodID>(classID, constrID); return result; }

JNIEXPORT void JNICALL Java_ru_eleron_oko_scanner_core_api_sdk2_RealSenseGrabberSDK2__1getDeviceModel (JNIEnv *env, jobject grabberJavaObj, jobject deviceModelJavaObj) { rs2::context context; std::pair<jclass, jmethodID> pair = getDeviceModelClassAndCnstrId(env);

auto activeDevicesList = context.query_devices();
if (activeDevicesList.size() == 0) {
	return;
}
else {
	rs2::device device = activeDevicesList.front();
	const char *nameStr = device.get_info(RS2_CAMERA_INFO_NAME);
	const char *serialNumberStr = device.get_info(RS2_CAMERA_INFO_SERIAL_NUMBER);
	const char *firmwareStr = device.get_info(RS2_CAMERA_INFO_FIRMWARE_VERSION);
	jstring nameStrJ = env->NewStringUTF(nameStr);
	jstring serialNumberStrJ = env->NewStringUTF(serialNumberStr);
	jstring firmwareStrJ = env->NewStringUTF(firmwareStr);

	jmethodID setNameMethID = getSetNamelDeviceModelMethodId(env, pair.first);
	jmethodID setSerialMethID = getSetSerialDeviceModelMethodId(env, pair.first);
	jmethodID setFirmwareMethID = getSetFirmwareDeviceModelMethodId(env, pair.first);

	env->CallVoidMethod(deviceModelJavaObj, setNameMethID, nameStrJ);
	if (env->ExceptionCheck()) {
		return;
	}
	env->CallVoidMethod(deviceModelJavaObj, setSerialMethID, serialNumberStrJ);
	if (env->ExceptionCheck()) {
		return;
	}
	env->CallVoidMethod(deviceModelJavaObj, setFirmwareMethID, firmwareStrJ);
}

}

JNIEXPORT void JNICALL Java_ru_eleron_oko_scanner_core_api_sdk2_RealSenseGrabberSDK2__1getColorCurrentVideoResolution (JNIEnv *env, jobject grabberJavaObj, jobject resultDimensionJavaObj) { auto pipe = getPipeLine(); auto active_pipeline_profile = pipe->get_active_profile(); auto color_stream = active_pipeline_profile.get_stream(RS2_STREAM_COLOR).asrs2::video_stream_profile(); int width = color_stream.width(); int height = color_stream.height(); std::pair<jclass, jmethodID> pair = getDimensionClassAndCnstrId(env); jmethodID setSiziId = getDimesionSetSizeMethodId(env, pair.first); env->CallVoidMethod(resultDimensionJavaObj, setSiziId, (jdouble)width, (jdouble)height); }

JNIEXPORT void JNICALL Java_ru_eleron_oko_scanner_core_api_sdk2_RealSenseGrabberSDK2__1getDepthCurrentVideoResolution (JNIEnv *env, jobject grabberJavaObj, jobject resultDimensionJavaObj) { auto pipe = getPipeLine(); auto active_pipeline_profile = pipe->get_active_profile(); auto depth_stream = active_pipeline_profile.get_stream(RS2_STREAM_DEPTH).asrs2::video_stream_profile(); int width = depth_stream.width(); int height = depth_stream.height(); auto pair = getDimensionClassAndCnstrId(env); jmethodID setSizeId = getDimesionSetSizeMethodId(env, pair.first); env->CallVoidMethod(resultDimensionJavaObj, setSizeId, (jdouble)width, (jdouble)height); }

JNIEXPORT jint JNICALL Java_ru_eleron_oko_scanner_core_api_sdk2_RealSenseGrabberSDK2__1getDeviceCount (JNIEnv *, jobject) { rs2::context context; auto activeDevicesList = context.query_devices(); return activeDevicesList.size(); }

JNIEXPORT jfloat JNICALL Java_ru_eleron_oko_scanner_core_api_sdk2_RealSenseGrabberSDK2__1getCurrentColorFPS (JNIEnv *, jobject) { auto pipe = getPipeLine(); auto active_pipeline_profile = pipe->get_active_profile(); auto color_stream = active_pipeline_profile.get_stream(RS2_STREAM_COLOR).asrs2::video_stream_profile(); int currColorFPS = color_stream.fps(); return (jfloat)currColorFPS; }

JNIEXPORT jfloat JNICALL Java_ru_eleron_oko_scanner_core_api_sdk2_RealSenseGrabberSDK2__1getCurrentDepthFPS (JNIEnv *, jobject) { auto pipe = getPipeLine(); auto active_pipeline_profile = pipe->get_active_profile(); auto depth_stream = active_pipeline_profile.get_stream(RS2_STREAM_DEPTH).asrs2::video_stream_profile(); int currDepthFps = depth_stream.fps(); return (jfloat)currDepthFps; }

JNIEXPORT void JNICALL Java_ru_eleron_oko_scanner_core_api_sdk2_RealSenseGrabberSDK2__1getAvailibaleColorResolutionAndFps (JNIEnv *env, jobject grabberJavaObj, jobject resultArrayListObj) { rs2::context context; auto activeDevicesList = context.query_devices(); rs2::device device = activeDevicesList.front(); std::vector<std::pair<int, std::pair<int, int>>> result;

for (auto&& sensor : device.query_sensors()) {
	auto streamProfiles = sensor.get_stream_profiles();
	for (auto iter = streamProfiles.begin(); iter != streamProfiles.end(); ++iter) {
		auto profile = (*iter).as<rs2::video_stream_profile>();
		auto stream_type = profile.stream_type();
		if (stream_type != rs2_stream::RS2_STREAM_COLOR) {
			continue;
		}
		result.push_back(std::make_pair<int, std::pair<int, int>>(profile.fps(), std::make_pair<int, int>(profile.width(), profile.height())));
	}
}

auto pair = getArrayListClassAndCnstrId(env);
jmethodID arrayListAddID = getArrayListAddMethodId(env, pair.first);
auto dimPair = getDimensionClassAndCnstrId(env);
auto resolutionFpsCouplePair = getResolutionFpsCoupleClassAndCnstrId(env);

for (auto iter = result.begin(); iter != result.end(); ++iter) {
	auto element = *iter;
	int fps = element.first;
	auto dim = element.second;
	int width = dim.first;
	int height = dim.second;
	jobject dimension = env->NewObject(dimPair.first, dimPair.second, width, height);
	if (env->ExceptionCheck()) {
		return;
	}
	jobject resolutionFpsCoupleObj = env->NewObject(resolutionFpsCouplePair.first, resolutionFpsCouplePair.second, dimension, (jfloat)fps);
	env->CallBooleanMethod(resultArrayListObj, arrayListAddID, resolutionFpsCoupleObj);
	if (env->ExceptionCheck()) {
		return;
	}
	env->DeleteLocalRef(dimension);
	env->DeleteLocalRef(resolutionFpsCoupleObj);
}

}

JNIEXPORT void JNICALL Java_ru_eleron_oko_scanner_core_api_sdk2_RealSenseGrabberSDK2__1getAvailibaleDepthResolutionAndFps (JNIEnv *env, jobject grabberJavaObj, jobject resultArrayListObj) { rs2::context context; auto activeDevicesList = context.query_devices(); rs2::device device = activeDevicesList.front(); std::vector<std::pair<int, std::pair<int, int>>> result;

for (auto&& sensor : device.query_sensors()) {
	auto streamProfiles = sensor.get_stream_profiles();
	for (auto iter = streamProfiles.begin(); iter != streamProfiles.end(); ++iter) {
		auto profile = (*iter).as<rs2::video_stream_profile>();
		auto stream_type = profile.stream_type();
		if (stream_type != rs2_stream::RS2_STREAM_DEPTH) {
			continue;
		}
		result.push_back(std::make_pair<int, std::pair<int, int>>(profile.fps(), std::make_pair<int, int>(profile.width(), profile.height())));
	}
}
auto arrayListPair = getArrayListClassAndCnstrId(env);
jmethodID arrayListAddID = getArrayListAddMethodId(env, arrayListPair.first);
auto dimPair = getDimensionClassAndCnstrId(env);
auto resolutionFpsCouplePair = getResolutionFpsCoupleClassAndCnstrId(env);

for (auto iter = result.begin(); iter != result.end(); ++iter) {
	auto element = *iter;
	int fps = element.first;
	auto dim = element.second;
	int width = dim.first;
	int height = dim.second;
	jobject dimension = env->NewObject(dimPair.first, dimPair.second, width, height);
	if (env->ExceptionCheck()) {
		return;
	}
	jobject resolutionFpsCoupleObj = env->NewObject(resolutionFpsCouplePair.first, resolutionFpsCouplePair.second, dimension, (jfloat)fps);
	env->CallBooleanMethod(resultArrayListObj, arrayListAddID, resolutionFpsCoupleObj);
	if (env->ExceptionCheck()) {
		return;
	}
	env->DeleteLocalRef(dimension);
	env->DeleteLocalRef(resolutionFpsCoupleObj);
}

}

JNIEXPORT void JNICALL Java_ru_eleron_oko_scanner_core_api_sdk2_RealSenseGrabberSDK2__1grabImages (JNIEnv *env, jobject grabberJavaObj, jobject resultImageChainObj) { rs2::pipeline *pipeline = getPipeLine(); jfloat depthScale = 0.001F; auto ap = pipeline->get_active_profile(); rs2::frameset frames = pipeline->wait_for_frames(); rs2::depth_frame depthFrame = frames.get_depth_frame(); rs2::video_frame colorFrame = frames.get_color_frame(); jint depthWidth = depthFrame.get_width(); jint depthHeight = depthFrame.get_height(); jint depthStride = depthFrame.get_stride_in_bytes(); jdouble depthTimeStamp = depthFrame.get_timestamp(); jbyte depthDataSrc = (jbyte)depthFrame.get_data(); int depthDataLength = depthStride * depthHeight; jbyteArray javaDepthData = env->NewByteArray(depthDataLength); if (env->ExceptionCheck()) { return; } env->SetByteArrayRegion(javaDepthData, 0, depthDataLength, depthDataSrc); if (env->ExceptionCheck()) { return; } jint colorWidth = colorFrame.get_width(); jint colorHeight = colorFrame.get_height(); jint colorStride = colorFrame.get_stride_in_bytes(); jdouble colorTimeStamp = colorFrame.get_timestamp(); jbyte colorDataSrc = (jbyte)colorFrame.get_data(); int colorDataLength = colorStride * colorHeight; jbyteArray javaColorData = env->NewByteArray(colorDataLength); if (env->ExceptionCheck()) { return; } env->SetByteArrayRegion(javaColorData, 0, colorDataLength, colorDataSrc); if (env->ExceptionCheck()) { return; } auto pair = getRealsenseImageClass(env); jobject colorJavaImage = env->NewObject( pair.first, pair.second, colorWidth, colorHeight, colorStride, colorTimeStamp, rs2_format::RS2_FORMAT_RGB8, javaColorData ); if (env->ExceptionCheck()) { return; } jobject depthJavaImage = env->NewObject( pair.first, pair.second, depthWidth, depthHeight, depthStride, depthTimeStamp, rs2_format::RS2_FORMAT_Z16, javaDepthData ); if (env->ExceptionCheck()) { return; } std::pair<jclass, jmethodID> imageChainPAir = getRealsenseImageChainClass(env); jmethodID setColorImageId = getRealsenseImageChainSetColorImageMethodId(env, imageChainPAir.first); jmethodID setDepthImageId = getRealsenseImageChainSetDepthImageMethodId(env, imageChainPAir.first); jmethodID setDepthScaleMethodID = getRealsenseImageChainSetDepthScaleMethodId(env, imageChainPAir.first); env->CallVoidMethod(resultImageChainObj, setColorImageId, colorJavaImage); if (env->ExceptionCheck()) { return; } env->CallVoidMethod(resultImageChainObj, setDepthImageId, depthJavaImage); if (env->ExceptionCheck()) { return; } env->CallVoidMethod(resultImageChainObj, setDepthScaleMethodID, depthScale); }

JNIEXPORT void JNICALL Java_ru_eleron_oko_scanner_core_api_sdk2_RealSenseGrabberSDK2__1enableStream (JNIEnv * env, jobject grabberInstance, jobject streamProfileSDK2instance) { jclass streamProfileJavaClass = env->GetObjectClass(streamProfileSDK2instance); if (env->ExceptionCheck()) { return; } jclass javaStreamTypeClass = getJavaStreamTypeClass(env); jclass javaPixelFormatClass = getJavaPixelTypeClass(env); jmethodID getWidthID = getWidthStreamProfileMethodId(env, streamProfileJavaClass); jmethodID getHeightID = getHeightStreamProfileMethodId(env, streamProfileJavaClass); jmethodID getStreamTypeID = getStreamTypeStreamProfileMethodId(env, streamProfileJavaClass); jmethodID getFpsID = getFpsStreamProfileMethodId(env, streamProfileJavaClass); jmethodID getPixelFormatID = getPixelFormatStreamProfileMethodId(env, streamProfileJavaClass); jmethodID getStreamTypeID_ID = getIdMethodId(env, javaStreamTypeClass); jmethodID getPixelFormatID_ID = getIdMethodId(env, javaPixelFormatClass); int width = env->CallIntMethod(streamProfileSDK2instance, getWidthID); if (env->ExceptionCheck()) { return; } int height = env->CallIntMethod(streamProfileSDK2instance, getHeightID); if (env->ExceptionCheck()) { return; } float fps = env->CallFloatMethod(streamProfileSDK2instance, getFpsID); if (env->ExceptionCheck()) { return; } jobject javaStreamTypeObj = env->CallObjectMethod(streamProfileSDK2instance, getStreamTypeID); if (env->ExceptionCheck()) { return; } jobject javaPixelTypeObj = env->CallObjectMethod(streamProfileSDK2instance, getPixelFormatID); if (env->ExceptionCheck()) { return; } int pixelTypeID = env->CallIntMethod(javaPixelTypeObj, getPixelFormatID_ID); if (env->ExceptionCheck()) { return; } int streamTypeId = env->CallIntMethod(javaStreamTypeObj, getStreamTypeID_ID); if (env->ExceptionCheck()) { return; } rs2::config *desiredStreamConfig = getConfig(); rs2_stream streamType = static_cast<rs2_stream>(streamTypeId); rs2_format pixelFormat = static_cast<rs2_format>(pixelTypeID); int intFps = static_cast(fps); desiredStreamConfig->enable_stream(streamType, width, height, pixelFormat, intFps); }

JNIEXPORT void JNICALL Java_ru_eleron_oko_scanner_core_api_sdk2_RealSenseGrabberSDK2__1startStreams (JNIEnv *, jobject) { rs2::pipeline *pipeline = getPipeLine(); rs2::config *desiredStreamConfig = getConfig(); pipeline->start(*desiredStreamConfig); }

JNIEXPORT void JNICALL Java_ru_eleron_oko_scanner_core_api_sdk2_RealSenseGrabberSDK2__1stopStreams (JNIEnv *, jobject) { rs2::pipeline *pipeline = getPipeLine(); pipeline->stop(); }

JNIEXPORT jfloat JNICALL Java_ru_eleron_oko_scanner_core_api_sdk2_RealSenseGrabberSDK2__1getDepthScale (JNIEnv *env, jobject) { rs2::context context; rs2::depth_sensor sensor = context.query_all_sensors().front().asrs2::depth_sensor(); return sensor.get_depth_scale(); }

JNIEXPORT jfloatArray JNICALL Java_ru_eleron_oko_scanner_core_api_sdk2_RealSenseGrabberSDK2__1getDepthPixelCorrdinatesFromColor (JNIEnv *env, jobject, jfloatArray colorPixelCoordinates, jfloat averageDepth) { auto length = env->GetArrayLength(colorPixelCoordinates); if (env->ExceptionCheck()) { return colorPixelCoordinates; } float *data = env->GetFloatArrayElements(colorPixelCoordinates, 0); if (env->ExceptionCheck()) { return colorPixelCoordinates; } auto pipelie_profile = getPipeLine()->get_active_profile(); auto color_stream = pipelie_profile.get_stream(rs2_stream::RS2_STREAM_COLOR).asrs2::video_stream_profile(); auto depth_stream = pipelie_profile.get_stream(rs2_stream::RS2_STREAM_DEPTH).asrs2::video_stream_profile(); rs2_intrinsics color_intrinsic = color_stream.get_intrinsics(); rs2_extrinsics color_to_depth_extr = color_stream.get_extrinsics_to(depth_stream); rs2_intrinsics depth_intrinsic = depth_stream.get_intrinsics(); for (int i = 0; i < length; i += 2) { float x = data[i]; float y = data[i + 1]; float color2D[2]{ x, y }; float color3D[3]; rs2_deproject_pixel_to_point(color3D, &color_intrinsic, color2D, averageDepth); float depth3D[3]; rs2_transform_point_to_point(depth3D, &color_to_depth_extr, color3D); float depth2D[2]; rs2_project_point_to_pixel(depth2D, &depth_intrinsic, depth3D); data[i] = depth2D[0]; data[i + 1] = depth2D[1]; } env->ReleaseFloatArrayElements(colorPixelCoordinates, data, JNI_COMMIT); return colorPixelCoordinates; }`

And my Java-code where native methods are defined: `public class RealSenseGrabberSDK2 { private static final Logger logger = LogManager.getLogger(RealSenseGrabberSDK2.class); static { System.loadLibrary("realsense2"); System.loadLibrary("RealSenseSDK2_JNI_wrapper"); }

static class DeviceNotConnectedException extends Exception {
    DeviceNotConnectedException(String msg) {
        super(msg);
    }
}

static class StreamsNotStartedException extends Exception {
    StreamsNotStartedException(String msg) {
        super(msg);
    }
}

static class StreamsNotConfiguredException extends Exception {
    StreamsNotConfiguredException(String msg) {
        super(msg);
    }
}

public synchronized Dimension getColorCurrentVideoResolution()
        throws DeviceNotConnectedException {
    if (devicePresent()) {
        Dimension dimension = new Dimension();
        _getColorCurrentVideoResolution(dimension);
        return dimension;
    } else {
        throw new DeviceNotConnectedException("Ошибка при получении разрешения цветного стрима: камера не обнаружена");
    }
}

public synchronized Dimension getDepthCurrentVideoResolution()
        throws DeviceNotConnectedException {
    if (devicePresent()) {
        Dimension dimension = new Dimension();
        _getDepthCurrentVideoResolution(dimension);
        return dimension;
    } else {
        throw new DeviceNotConnectedException("Ошибка при получении разрешения цветного стрима: камера не обнаружена");
    }
}

public synchronized DeviceModel getDeviceModel()
        throws DeviceNotConnectedException {
    if (devicePresent()) {
        DeviceModel deviceModel = new DeviceModel();
        try {
            _getDeviceModel(deviceModel);
        } catch (Throwable e) {
            String msg = "Ошибка при попытке получить модель камеры.";
            logger.error(msg, e);
        }
        return deviceModel;
    } else {
        throw new DeviceNotConnectedException("Ошибка при получении модели камеры: камера не обнаружена");
    }
}

public synchronized int getDeviceCount() {
    return _getDeviceCount();
}

public synchronized float getCurrentColorFPS()
        throws DeviceNotConnectedException, StreamsNotStartedException {
    String errorMsgPrefix = "Ошибка при получении FPS цветного стрима: ";
    if (!devicePresent()) {
        throw new DeviceNotConnectedException(errorMsgPrefix + "камера не обнаружена");
    } else if (!isConnected) {
        throw new StreamsNotStartedException(errorMsgPrefix + "стрим не начат");
    } else {
        float fps = 0;
        try {
            fps = _getCurrentColorFPS();
        } catch (Throwable e) {
            String msg = "Ошибка при попытке получить текущий FPS для цветного стрима.";
            logger.error(msg, e);
        }
        return fps;
    }
}

public synchronized float getCurrentDepthFPS()
        throws DeviceNotConnectedException, StreamsNotStartedException {
    String errorMsgPrefix = "Ошибка при получении FPS глубинного стрима: ";
    if (!devicePresent()) {
        throw new DeviceNotConnectedException(errorMsgPrefix + "камера не обнаружена");
    } else if (!isConnected) {
        throw new StreamsNotStartedException(errorMsgPrefix + "стрим не начат");
    } else {
        float fps = 0;
        try {
            fps = _getCurrentDepthFPS();
        } catch (Throwable e) {
            String msg = "Ошибка при попытке получить текущий FPS для глубинного стрима.";
            logger.error(msg, e);
        }
        return fps;
    }
}

public synchronized List<ResolutionFpsCoupleSDK2> getAvailibaleColorResolutionAndFps()
        throws DeviceNotConnectedException {
    if (devicePresent()) {
        ArrayList<ResolutionFpsCoupleSDK2> resolutionFpsCoupleSDK2s = new ArrayList<>();
        try {
            _getAvailibaleColorResolutionAndFps(resolutionFpsCoupleSDK2s);
        } catch (Throwable e) {
            String msg = "Ошибка при попытке получить всевозможные разрешения и FPS для цветного стрима.";
            logger.error(msg, e);
        }
        return resolutionFpsCoupleSDK2s;
    } else {
        throw new DeviceNotConnectedException(
                "Ошибка при получении всех возможных разрешений цветного стрима: камера не обнаружена или не стрим не начат"
        );
    }
}

public synchronized List<ResolutionFpsCoupleSDK2> getAvailibaleDepthResolutionAndFps()
        throws DeviceNotConnectedException {
    if (devicePresent()) {
        ArrayList<ResolutionFpsCoupleSDK2> resolutionFpsCoupleSDK2s = new ArrayList<>();
        try {
            _getAvailibaleDepthResolutionAndFps(resolutionFpsCoupleSDK2s);
        } catch (Throwable e) {
            String msg = "Ошибка при попытке получить всевозможные разрешения и FPS для глубинного стрима.";
            logger.error(msg, e);
        }
        return resolutionFpsCoupleSDK2s;
    } else {
        throw new DeviceNotConnectedException(
                "Ошибка при получении всех возможных разрешений глубинного стрима: камера не обнаружена или не стрим не начат"
        );
    }
}

public synchronized RealSenseSDK2ImageChain grabImages()
        throws DeviceNotConnectedException, StreamsNotStartedException {
    String errorMsgPrefix = "Ошибка при получении изображений: ";
    if (!devicePresent()) {
        throw new DeviceNotConnectedException(errorMsgPrefix + "камера не обнаружена");
    } else if (!isConnected) {
        throw new StreamsNotStartedException(errorMsgPrefix + streamsNotStartedMsg);
    } else {
        RealSenseSDK2ImageChain imageChain = new RealSenseSDK2ImageChain();
        try {
            _grabImages(imageChain);
        } catch (Throwable e) {
            String msg = "Ошибка при попытке получить кадры с камеры.";
            logger.error(msg, e);
        }
        return imageChain;
    }
}

public synchronized void enableStream(StreamProfileSDK2 streamProfileSDK2)
        throws DeviceNotConnectedException, IllegalArgumentException {
    String msg = "Ошибка при попытке активировать стрим: камера не обнаружена. Параметры стрима: " + streamProfileSDK2;
    checkPresent(msg);
    final RealSenseSDK2StreamType streamType = streamProfileSDK2.getRealSenseSDK2StreamType();
    final PixelFormatSDK2 pixelFormat = streamProfileSDK2.getPixelFormatSDK2();
    switch (streamType) {
        case RS2_STREAM_COLOR:
            if (pixelFormat != PixelFormatSDK2.RS2_FORMAT_RGB8) {
                throw new IllegalArgumentException("Программа поддерживает только один формат пикселей для цветного стрима: RGB24 (RGB8)");
            }
            break;
        case RS2_STREAM_DEPTH:
            if (pixelFormat != PixelFormatSDK2.RS2_FORMAT_Z16) {
                throw new IllegalArgumentException("Программа поддерживает только один формат пикселей для глубинного стрима: RS2_FORMAT_Z16 (2 байта на пиксель)");
            }
            break;
        default:
            throw new IllegalArgumentException("Программа поддерживает только два типа стримов: цветной и глубинный. Попытка активировать другой тип стрима");
    }
    try {
        _enableStream(streamProfileSDK2);
    } catch (Throwable e) {
        msg = "Ошибка при попытке активировать стримы на камере.";
        logger.error(msg, e);
        return;
    }
    isStreamsConfigured = true;
}

public synchronized void startStreams()
        throws DeviceNotConnectedException, StreamsNotConfiguredException {
    String errorPrefix = "Ошибка при поптыке начать стримы: ";
    checkPresent(errorPrefix);
    checkConfig(errorPrefix);
    try {
        _startStreams();
    } catch (Throwable e) {
        logger.error(errorPrefix, e);
    }
    isConnected = true;
}

public synchronized void stopStreams() {
    if (devicePresent() && isConnected) {
        try {
            _stopStreams();
        } catch (Throwable e) {
            String msg = "Ошибка при попытке остановить стримы на камере.";
            logger.error(msg, e);
        }
        isConnected = false;
    }
}

public synchronized float getDepthScale()
        throws DeviceNotConnectedException, StreamsNotConfiguredException, StreamsNotStartedException {
    String errorPrefix = "Ошибка при попытке получить коэффициент масштабирования для карты высот: ";
    checkPresentConfigAndStarting(errorPrefix);
    float fps = 0;
    try {
        fps = _getDepthScale();
    } catch (Throwable e) {
        String msg = "Ошибка при попытке получить Depth scale.";
        logger.error(msg, e);
    }
    return fps;

}

public synchronized float[] getDepthPixelCorrdinatesFromColor(float[] colorPixelCoordinates, float averageDepth)
        throws DeviceNotConnectedException, StreamsNotConfiguredException, StreamsNotStartedException {
    int length = colorPixelCoordinates.length;
    if (length % 2 != 0) {
        throw new IllegalArgumentException("Нечётная длина массива. В массива должны быть последовательно расположены Х и У координаты точек");
    }
    String errorPrefix = "Ошибка при попытке получить координаты точек на карте высот из координат на цветном изображении: ";
    checkPresentConfigAndStarting(errorPrefix);
    float[] result = new float[colorPixelCoordinates.length];
    try {
        result = _getDepthPixelCorrdinatesFromColor(colorPixelCoordinates, averageDepth);
    } catch (Throwable e) {
        String msg = "Ошибка при попытке преобразовать цветные координаты в глубинные.";
        logger.error(msg, e);
    }
    return result;
}

private void checkPresent(String errorPrefix)
    throws DeviceNotConnectedException{
    if (!devicePresent()) {
        throw new DeviceNotConnectedException(errorPrefix + deviceNotConnectedMsg);
    }
}

private void checkConfig(String msg)
    throws StreamsNotConfiguredException{
    if (!isStreamsConfigured) {
        throw new StreamsNotConfiguredException(msg + streamsNotConfiguredMsg);
    }
}

private void checkStarting(String msg)
    throws StreamsNotStartedException{
    if(!isConnected){
        throw new StreamsNotStartedException(msg + streamsNotStartedMsg);
    }
}

private void checkPresentConfigAndStarting(String msg)
    throws DeviceNotConnectedException, StreamsNotConfiguredException, StreamsNotStartedException{
    checkPresent(msg);
    checkConfig(msg);
    checkStarting(msg);
}
public boolean isConnected() {
    return devicePresent() && isConnected;
}


public boolean isStreamsConfigured() {
    return isStreamsConfigured;
}

private native void _getDeviceModel(DeviceModel deviceModel);

private native void _getColorCurrentVideoResolution(Dimension dimension);

private native void _getDepthCurrentVideoResolution(Dimension dimension);

private native int _getDeviceCount();

private native float _getCurrentColorFPS();

private native float _getCurrentDepthFPS();

private native void _getAvailibaleColorResolutionAndFps(List<ResolutionFpsCoupleSDK2> list);

private native void _getAvailibaleDepthResolutionAndFps(List<ResolutionFpsCoupleSDK2> list);

private native void _grabImages(RealSenseSDK2ImageChain imageChain);

private native void _enableStream(StreamProfileSDK2 streamProfileSDK2);

private native void _startStreams();

private native void _stopStreams();

private native float _getDepthScale();

private native float[] _getDepthPixelCorrdinatesFromColor(float[] colorPixelCoordinates, float averageDepth);

private boolean devicePresent() {
    int deviceCount = 0;
    try {
        deviceCount = _getDeviceCount();
    } catch (Throwable e) {
        String msg = "Ошибка при попытке получить кол-во подключённых камер.";
        logger.error(msg, e);
    }
    return deviceCount != 0;
}

private volatile boolean isConnected = false;
private volatile boolean isStreamsConfigured = false;
private final String deviceNotConnectedMsg = "камера не подключена";
private final String streamsNotConfiguredMsg = "стримы не сконфигурированы. Нужно сперва вызвать метод enableStream()";
private final String streamsNotStartedMsg = "стримы не начаты";

}` The RealSenseGrabberSDK2.grabImages(...) method is invoked in the while loop from another class.

AkhmedAnam avatar Sep 11 '18 05:09 AkhmedAnam

Just checking in to point out that there is a more-or-less working JNI based wrapper at https://github.com/edwinRNDR/librealsense/tree/master/wrappers/java

edwinRNDR avatar Sep 11 '18 09:09 edwinRNDR

Hi @AkhmedAnam Unfortunately, I don't know enough about Java wrapping to comment on your code. Perhaps you could capture the crash-dump (using visual studio or using Windows registry) and upload the resulting dump-file somewhere we can look. Perhaps I'd be able to see something useful in one of the other threads. Also, we could try enabling librealsense logs (to various levels of verbosity) to try and pin-point at what point it breaks.

dorodnic avatar Sep 12 '18 12:09 dorodnic

Hi, @dorodnic.

What should I do to enable librealsense log?

AkhmedAnam avatar Sep 12 '18 12:09 AkhmedAnam

rs2::log_to_console(RS2_SEVERITY_DEBUG); will enable all logs to console. rs2::log_to_file("filename.txt", RS2_SEVERITY_DEBUG); will enable all logs to a specific file.

dorodnic avatar Sep 12 '18 15:09 dorodnic

[Realsense Customer Engineering Team Comment] @AkhmedAnam Did you get chance to collect the logs according to Dorodnic's reply? Please upload the logs so that we can further check. Thanks!

rs2::log_to_console(RS2_SEVERITY_DEBUG); will enable all logs to console. rs2::log_to_file("filename.txt", RS2_SEVERITY_DEBUG); will enable all logs to a specific file.

[Realsense Customer Engineering Team Comment] @AkhmedAnam Is the issue resolved? Or else could you please provide the logs so that we can further check? Thanks!

[Realsense Customer Engineering Team Comment] @AkhmedAnam Could you please update? Thanks!

[Realsense Customer Engineering Team Comment] @AkhmedAnam Could you please update? If still no update we will close this ticket in 5 days. Thanks!