Search code examples
androidandroid-mediaplayerandroid-textureview

same SurfaceTexture for 2 views


Is it possible to use same surfacetexture for 2 views? If so, how? I use mediaplayer to play video and I want to play same video on 2 different views at the same time.

I tried to create SurfaceTexture and then set this surface texture to both views but it doesn't work.

   public int createTextureObject() {
        int[] textures = new int[1];
        GLES20.glGenTextures(1, textures, 0);

        int texId = textures[0];
        GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, texId);

        GLES20.glTexParameterf(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_MIN_FILTER,
                GLES20.GL_NEAREST);
        GLES20.glTexParameterf(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_MAG_FILTER,
                GLES20.GL_LINEAR);
        GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_WRAP_S,
                GLES20.GL_CLAMP_TO_EDGE);
        GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_WRAP_T,
                GLES20.GL_CLAMP_TO_EDGE);

        return texId;
    }

SurfaceTexture st = new SurfaceTexture(createTextureObject());
textureView1.setSurfaceTexture(st);
textureView2.setSurfaceTexture(st); 
mMediaPlayer.setSurface(new Surface(st));

It randomly works on one or another view but not on both at the same time.


Solution

  • I don't believe shared SurfaceTextures are supported by TextureView. I don't know that there's anything that would prevent it from being possible, but the onFrameAvailable() callback can only notify one object.

    (You might be able to jury-rig something where you manually invoke the callback in the second instance from the first, but that seems like asking for trouble.)

    An approach that will work is to create the SurfaceTexture as you are doing now, and send the video frames to it, but provide an onFrameAvailable() listener that renders the video frame to the two TextureViews using OpenGL ES.

    Various examples of this can be found in Grafika, e.g. "continuous capture" receives Camera input on a SurfaceTexture and then renders it twice (once to the display, once to a video encoder).