I have a problem in the USB device with camera. And its SDK is special that I can't use webtexture in unity. So I would like to use gles20 to transport camera image to unity. But the callback is in sub thread and it can't render gles20. Texture id is always 0.
- I tried writing glGenTextures in function StartCapture, texture id is not 0 but callback cannot find the texture.
- I search the solution that the sub thread call main thread. Most of them are Activity.runOnUIThread. But the capture crash and stop immediately.
public class CameraTest : MonoBehaviour
{
public class Listener : AndroidJavaProxy
{
// init proxy listener
.........
public void cameraBytes(long timestamp)
{
Debug.LogError("Unity timestamp: " + timestamp);
}
public void SetTextureId(int textureId)
{
this.textureId = textureId;
Texture2D externTex = Texture2D.CreateExternalTexture(640, 480, TextureFormat.RGB565, false, false, (IntPtr)textureId);
tex2D.UpdateExternalTexture(externTex.GetNativeTexturePtr());
}
}
private void Start()
{
// init java camera plugin
.......
}
// trigger button
public void OpenCamera(bool isOpen)
{
plugin.Call("OpenCamera", isOpen);
}
public void StartCapture(bool isCapture)
{
plugin.Call("StartCapture", isCapture);
}
public class Plugin {
private int textureId;
public Plugin(Context context) {
_context = context;
}
public void InitCameraManager(PluginListener listener) {
if (listener != null) _listener = listener;
_dataCallback = new CaptureDataCallback() {
@Override
public void onCaptureData(long timestamp, byte[] bytes) {
Log.d("Data", String.format("timestamp: %d", timestamp));
_listener.cameraBytes(timestamp);
Log.d("Camera", "Bytes length: " + bytes.length);
int[] textures = new int[1];
GLES20.glGenTextures(1, textures, 0);
textureId = textures[0];
Log.d("Camera", "texture id: " + textures[0]);
Bitmap bitmap = Bitmap.createBitmap(640, 480, Bitmap.Config.RGB_565);
if (textureId != 0) {
Log.d("Camera", "texture id: " + textureId);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureId);
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER,
GLES20.GL_LINEAR_MIPMAP_LINEAR);
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER,
GLES20.GL_LINEAR);
GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, bitmap, 0);
bitmap.recycle();
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0);
_listener.SetTextureId(textureId);
} else {
Log.d("Camera", "texture is fail to load");
}
}
};
public void OpenCamera(boolean isOpen) {
// open device camera and set data callback in camera
....
}
public void StartCapture(boolean isCapture) {
// start camera capture data
}