package cn.tee3.avd;

import android.media.MediaRecorder;
import android.os.Build;
import android.view.Surface;
import java.io.IOException;
import androidx.annotation.RequiresApi;

public class AVDRecord2Local {

    private MediaRecorder mMediaRecorder;

    private AVDRecord2Local() {
    }

    public static AVDRecord2Local getInstance() {
        return Builder.INSTANCE;
    }

    private static class Builder {
        private static final AVDRecord2Local INSTANCE = new AVDRecord2Local();
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    public void startRecorder(Surface surface, int frameWidth, int frameHeight, int frameRate, String filePath) {
        try {
            if (mMediaRecorder == null){
                mMediaRecorder = new MediaRecorder();
            }

            mMediaRecorder.setInputSurface(surface);
            mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
            mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
            mMediaRecorder.setOutputFile( filePath );
            mMediaRecorder.setVideoSize(frameWidth, frameHeight);
            mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
            mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
            mMediaRecorder.setVideoEncodingBitRate(frameWidth * frameHeight * 4);
            mMediaRecorder.setVideoFrameRate(frameRate);
            mMediaRecorder.prepare();
            mMediaRecorder.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void stopRecord() {
        if (mMediaRecorder != null) {
            mMediaRecorder.stop();
        }
    }

    public void release() {
        if (mMediaRecorder != null) {
            mMediaRecorder.stop();
            mMediaRecorder.release();
        }
    }
}
