Search code examples
javaandroidsurfaceviewandroid-mediacodecsurface

The surface has been released Media Codec


I'm trying to code a encoder/decoder to send a camera through a TCP server and display it with a SurfaceView, when I do decodec.configure I have the "The surface has been released"

This is my code:

SurfaceHolder.Callback callback1 = new SurfaceHolder.Callback() {

    @Override
    public void surfaceCreated(SurfaceHolder surfaceHolder) {
        Log.d(TAG,"inSurfaceCreated");
        hasActiveHolder = true;
    }

    @Override
    public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
        Log.d(TAG,"inSurfaceChanged");
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
        Log.d(TAG,"inSurfaceDestroyed");
        hasActiveHolder = false;
    }
};
FrameLayout frameLayout1=findViewById(R.id.frameLayout);
SurfaceView surfaceView = new SurfaceView(this);
SurfaceHolder holder1 = (surfaceView.getHolder());
holder1.addCallback(callback1);
Surface surfaceAffichage = holder1.getSurface();
frameLayout1.addView(surfaceView);
//while(!hasActiveHolder){ }

MediaFormat mediaFormat = MediaFormat.createVideoFormat(MediaFormat.MIMETYPE_VIDEO_AVC, 640, 640);
mediaFormat.setInteger(MediaFormat.KEY_BIT_RATE, 1000000);
mediaFormat.setInteger(MediaFormat.KEY_FRAME_RATE, 20);
mediaFormat.setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420Flexible);
mediaFormat.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 1);
final MediaCodec decodec = MediaCodec.createDecoderByType("video/avc");
decodec.configure(mediaFormat, surfaceAffichage, null, 0);

If I remove the comment on while loop, I wait forever and the program never gets in the callback surfaceCreated

Can someone help me?


Solution

  • You need to initialize the decoder in the SurfaceHoler.Callback's surfaceCreated body. This callback notifies you when the underlying surface has been created.

    Additionally: while(!hasActiveHolder){ } don't do this. If there is a callback use it to kick off the rest of your logic. If you really need to check if some event has happened periodically, introduce wait times and synchronize variable access.