package com.bytedance.bae.webrtc;

import X.3GY;
import android.media.AudioRecord;
import android.os.Build;
import android.os.Process;
import com.bytedance.bae.base.BaeLogging;
import com.bytedance.bae.base.ThreadUtils;
import com.bytedance.covode.number.Covode;
import com.bytedance.frameworks.apm.trace.MethodCollector;
import java.nio.ByteBuffer;
import java.util.Arrays;

public class WebRtcAudioRecord {
    public static final int DEFAULT_AUDIO_SOURCE;
    public static WebRtcAudioRecordSamplesReadyCallback audioSamplesReadyCallback;
    public static int defaultMediaModeAudioSource;
    public static WebRtcAudioRecordErrorCallback errorCallback;
    public static volatile boolean microphoneMute;
    public String apiResult = "";
    public AudioRecord audioRecord;
    public AudioRecordThread audioThread;
    public ByteBuffer byteBuffer;
    public WebRtcAudioEffects effects;
    public byte[] emptyBytes;
    public final long nativeAudioRecord;

    /* renamed from: com.bytedance.bae.webrtc.WebRtcAudioRecord$1  reason: invalid class name */
    public static /* synthetic */ class AnonymousClass1 {
        static {
            Covode.recordClassIndex(24252);
        }
    }

    public enum AudioRecordStartErrorCode {
        AUDIO_RECORD_START_EXCEPTION,
        AUDIO_RECORD_START_STATE_MISMATCH
    }

    public interface WebRtcAudioRecordErrorCallback {
        static {
            Covode.recordClassIndex(24256);
        }

        void onWebRtcAudioRecordError(String str);

        void onWebRtcAudioRecordInitError(String str);

        void onWebRtcAudioRecordStartError(AudioRecordStartErrorCode audioRecordStartErrorCode, String str);
    }

    public interface WebRtcAudioRecordSamplesReadyCallback {
        static {
            Covode.recordClassIndex(24257);
        }

        void onWebRtcAudioRecordSamplesReady(AudioSamples audioSamples);
    }

    private int channelCountToConfiguration(int i) {
        return i == 1 ? 16 : 12;
    }

    public static void com_bytedance_bae_webrtc_WebRtcAudioRecord_android_media_AudioRecord_release(AudioRecord audioRecord2) {
        3GY.LIZ(100403);
        AudioRecord audioRecord3 = audioRecord2;
        if (!((Boolean) 3GY.LIZ((Object) null, audioRecord3, new Object[0], 100403, "void", false, -917918712, 2).first).booleanValue()) {
            audioRecord3.release();
            3GY.LIZ((Object) null, audioRecord3, new Object[0], 100405, (String) null, false, -917918712, 3);
        }
    }

    public static void com_bytedance_bae_webrtc_WebRtcAudioRecord_android_media_AudioRecord_startRecording(AudioRecord audioRecord2) {
        3GY.LIZ(100400);
        AudioRecord audioRecord3 = audioRecord2;
        if (!((Boolean) 3GY.LIZ((Object) null, audioRecord3, new Object[0], 100400, "void", false, 60056622, 2).first).booleanValue()) {
            audioRecord3.startRecording();
        }
    }

    public static int getDefaultAudioSource() {
        return 0;
    }

    private native void nativeCacheDirectBufferAddress(ByteBuffer byteBuffer2, long j);

    public native void nativeDataIsRecorded(int i, long j);

    public static class AudioSamples {
        public final int audioFormat;
        public final int channelCount;
        public final byte[] data;
        public final int sampleRate;

        static {
            Covode.recordClassIndex(24255);
        }

        public int getAudioFormat() {
            return this.audioFormat;
        }

        public int getChannelCount() {
            return this.channelCount;
        }

        public byte[] getData() {
            return this.data;
        }

        public int getSampleRate() {
            return this.sampleRate;
        }

        public AudioSamples(AudioRecord audioRecord, byte[] bArr) {
            this.audioFormat = audioRecord.getAudioFormat();
            this.channelCount = audioRecord.getChannelCount();
            this.sampleRate = audioRecord.getSampleRate();
            this.data = bArr;
        }

        public /* synthetic */ AudioSamples(AudioRecord audioRecord, byte[] bArr, AnonymousClass1 r3) {
            this(audioRecord, bArr);
        }
    }

    private String getApiResult() {
        return this.apiResult;
    }

    public class AudioRecordThread extends Thread {
        public volatile boolean keepAlive = true;

        static {
            Covode.recordClassIndex(24254);
        }

        public static void com_bytedance_bae_webrtc_WebRtcAudioRecord$AudioRecordThread_android_media_AudioRecord_stop(AudioRecord audioRecord) {
            3GY.LIZ(100401);
            AudioRecord audioRecord2 = audioRecord;
            if (!((Boolean) 3GY.LIZ((Object) null, audioRecord2, new Object[0], 100401, "void", false, 1786926324, 2).first).booleanValue()) {
                audioRecord2.stop();
                3GY.LIZ((Object) null, audioRecord2, new Object[0], 100404, (String) null, false, 1786926324, 3);
            }
        }

        public void stopThread() {
            BaeLogging.i("WebRtcAudioRecord", "stopThread");
            this.keepAlive = false;
        }

        public void run() {
            MethodCollector.i(15125);
            Process.setThreadPriority(-19);
            BaeLogging.i("WebRtcAudioRecord", "AudioRecordThread" + WebRtcAudioUtils.getThreadInfo());
            if (WebRtcAudioRecord.this.audioRecord.getRecordingState() != 3) {
                String str = "AudioRecord.run failed: incorrect state :" + WebRtcAudioRecord.this.audioRecord.getRecordingState();
                BaeLogging.e("WebRtcAudioRecord", str);
                this.keepAlive = false;
                WebRtcAudioRecord.this.reportWebRtcAudioRecordError(str);
            }
            System.nanoTime();
            while (this.keepAlive) {
                int read = WebRtcAudioRecord.this.audioRecord.read(WebRtcAudioRecord.this.byteBuffer, WebRtcAudioRecord.this.byteBuffer.capacity());
                if (read == WebRtcAudioRecord.this.byteBuffer.capacity()) {
                    if (WebRtcAudioRecord.microphoneMute) {
                        WebRtcAudioRecord.this.byteBuffer.clear();
                        WebRtcAudioRecord.this.byteBuffer.put(WebRtcAudioRecord.this.emptyBytes);
                    }
                    if (this.keepAlive) {
                        WebRtcAudioRecord webRtcAudioRecord = WebRtcAudioRecord.this;
                        webRtcAudioRecord.nativeDataIsRecorded(read, webRtcAudioRecord.nativeAudioRecord);
                    }
                    if (WebRtcAudioRecord.audioSamplesReadyCallback != null) {
                        WebRtcAudioRecord.audioSamplesReadyCallback.onWebRtcAudioRecordSamplesReady(new AudioSamples(WebRtcAudioRecord.this.audioRecord, Arrays.copyOf(WebRtcAudioRecord.this.byteBuffer.array(), WebRtcAudioRecord.this.byteBuffer.capacity()), (AnonymousClass1) null));
                    }
                } else {
                    String concat = "AudioRecord.read failed: ".concat(String.valueOf(read));
                    BaeLogging.e("WebRtcAudioRecord", concat);
                    if (read == -3) {
                        this.keepAlive = false;
                        WebRtcAudioRecord.this.reportWebRtcAudioRecordError(concat);
                    }
                }
            }
            try {
                if (WebRtcAudioRecord.this.audioRecord != null) {
                    com_bytedance_bae_webrtc_WebRtcAudioRecord$AudioRecordThread_android_media_AudioRecord_stop(WebRtcAudioRecord.this.audioRecord);
                }
                MethodCollector.o(15125);
            } catch (Exception e) {
                BaeLogging.e("WebRtcAudioRecord", "AudioRecord.stop failed: " + e.getMessage());
                MethodCollector.o(15125);
            }
        }

        public AudioRecordThread(String str) {
            super(str);
        }
    }

    static {
        Covode.recordClassIndex(24251);
        int defaultAudioSource = getDefaultAudioSource();
        DEFAULT_AUDIO_SOURCE = defaultAudioSource;
        defaultMediaModeAudioSource = defaultAudioSource;
    }

    private int getAudioSessionId() {
        AudioRecord audioRecord2 = this.audioRecord;
        if (audioRecord2 == null) {
            return -1;
        }
        return audioRecord2.getAudioSessionId();
    }

    private int getAudioSource() {
        AudioRecord audioRecord2 = this.audioRecord;
        if (audioRecord2 == null) {
            return -1;
        }
        return audioRecord2.getAudioSource();
    }

    private void logMainParametersExtended() {
        if (Build.VERSION.SDK_INT >= 23) {
            BaeLogging.w("WebRtcAudioRecord", "AudioRecord: buffer size in frames: " + this.audioRecord.getBufferSizeInFrames());
        }
    }

    private void releaseAudioResources() {
        BaeLogging.i("WebRtcAudioRecord", "releaseAudioResources");
        AudioRecord audioRecord2 = this.audioRecord;
        if (audioRecord2 != null) {
            com_bytedance_bae_webrtc_WebRtcAudioRecord_android_media_AudioRecord_release(audioRecord2);
            this.audioRecord = null;
        }
    }

    private void logMainParameters() {
        BaeLogging.w("WebRtcAudioRecord", "AudioRecord: session ID: " + this.audioRecord.getAudioSessionId() + ", channels: " + this.audioRecord.getChannelCount() + ", sample rate: " + this.audioRecord.getSampleRate() + ", source:" + this.audioRecord.getAudioSource());
    }

    private boolean stopRecording() {
        boolean z;
        this.apiResult = "StopRecording:";
        BaeLogging.i("WebRtcAudioRecord", "StopRecording:");
        if (this.audioThread != null) {
            z = true;
        } else {
            z = false;
        }
        assertTrue(z);
        this.audioThread.stopThread();
        if (!ThreadUtils.joinUninterruptibly(this.audioThread, 2000)) {
            BaeLogging.e("WebRtcAudioRecord", "Join of AudioRecordJavaThread timed out");
            WebRtcAudioUtils.logAudioState("WebRtcAudioRecord");
            this.apiResult += "Join of AudioRecordJavaThread timed out";
        }
        this.audioThread = null;
        WebRtcAudioEffects webRtcAudioEffects = this.effects;
        if (webRtcAudioEffects != null) {
            webRtcAudioEffects.release();
        }
        releaseAudioResources();
        return true;
    }

    private boolean startRecording() {
        boolean z;
        boolean z2;
        this.apiResult = "StartRecording:";
        BaeLogging.i("WebRtcAudioRecord", "StartRecording:");
        if (this.audioRecord != null) {
            z = true;
        } else {
            z = false;
        }
        assertTrue(z);
        if (this.audioThread == null) {
            z2 = true;
        } else {
            z2 = false;
        }
        assertTrue(z2);
        try {
            com_bytedance_bae_webrtc_WebRtcAudioRecord_android_media_AudioRecord_startRecording(this.audioRecord);
            if (this.audioRecord.getRecordingState() != 3) {
                reportWebRtcAudioRecordStartError(AudioRecordStartErrorCode.AUDIO_RECORD_START_STATE_MISMATCH, "AudioRecord.startRecording failed - incorrect state :" + this.audioRecord.getRecordingState());
                this.apiResult += "AudioRecord.startRecording failed - incorrect state :" + this.audioRecord.getRecordingState();
                WebRtcAudioEffects webRtcAudioEffects = this.effects;
                if (webRtcAudioEffects != null) {
                    webRtcAudioEffects.release();
                }
                releaseAudioResources();
                return false;
            }
            AudioRecordThread audioRecordThread = new AudioRecordThread("BaeRecordJavaThread");
            this.audioThread = audioRecordThread;
            audioRecordThread.start();
            return true;
        } catch (IllegalStateException e) {
            reportWebRtcAudioRecordStartError(AudioRecordStartErrorCode.AUDIO_RECORD_START_EXCEPTION, "AudioRecord.startRecording failed: " + e.getMessage());
            this.apiResult += "AudioRecord.startRecording failed: " + e.getMessage();
            releaseAudioResources();
            return false;
        }
    }

    public static void setOnAudioSamplesReady(WebRtcAudioRecordSamplesReadyCallback webRtcAudioRecordSamplesReadyCallback) {
        audioSamplesReadyCallback = webRtcAudioRecordSamplesReadyCallback;
    }

    public static void assertTrue(boolean z) {
        if (!z) {
            throw new AssertionError("Expected condition to be true");
        }
    }

    public static void setErrorCallback(WebRtcAudioRecordErrorCallback webRtcAudioRecordErrorCallback) {
        BaeLogging.i("WebRtcAudioRecord", "Set error callback");
        errorCallback = webRtcAudioRecordErrorCallback;
    }

    private void reportWebRtcAudioRecordInitError(String str) {
        BaeLogging.e("WebRtcAudioRecord", "Init recording error: ".concat(String.valueOf(str)));
        WebRtcAudioUtils.logAudioState("WebRtcAudioRecord");
        WebRtcAudioRecordErrorCallback webRtcAudioRecordErrorCallback = errorCallback;
        if (webRtcAudioRecordErrorCallback != null) {
            webRtcAudioRecordErrorCallback.onWebRtcAudioRecordInitError(str);
        }
    }

    public static void setMicrophoneMute(boolean z) {
        BaeLogging.w("WebRtcAudioRecord", "setMicrophoneMute(" + z + ")");
        microphoneMute = z;
    }

    public void reportWebRtcAudioRecordError(String str) {
        BaeLogging.e("WebRtcAudioRecord", "Run-time recording error: ".concat(String.valueOf(str)));
        WebRtcAudioUtils.logAudioState("WebRtcAudioRecord");
        WebRtcAudioRecordErrorCallback webRtcAudioRecordErrorCallback = errorCallback;
        if (webRtcAudioRecordErrorCallback != null) {
            webRtcAudioRecordErrorCallback.onWebRtcAudioRecordError(str);
        }
    }

    public WebRtcAudioRecord(long j) {
        BaeLogging.i("WebRtcAudioRecord", "ctor" + WebRtcAudioUtils.getThreadInfo());
        this.nativeAudioRecord = j;
        if (WebRtcAudioEffects.IsAudioEffectSupported()) {
            this.effects = WebRtcAudioEffects.create();
        }
    }

    private boolean enableBuiltInAEC(boolean z) {
        BaeLogging.i("WebRtcAudioRecord", "enableBuiltInAEC(" + z + ')');
        WebRtcAudioEffects webRtcAudioEffects = this.effects;
        if (webRtcAudioEffects != null) {
            return webRtcAudioEffects.setAEC(z);
        }
        BaeLogging.e("WebRtcAudioRecord", "Built-in AEC is not supported on this platform");
        return false;
    }

    private boolean enableBuiltInNS(boolean z) {
        BaeLogging.i("WebRtcAudioRecord", "enableBuiltInNS(" + z + ')');
        WebRtcAudioEffects webRtcAudioEffects = this.effects;
        if (webRtcAudioEffects != null) {
            return webRtcAudioEffects.setNS(z);
        }
        BaeLogging.e("WebRtcAudioRecord", "Built-in NS is not supported on this platform");
        return false;
    }

    private void reportWebRtcAudioRecordStartError(AudioRecordStartErrorCode audioRecordStartErrorCode, String str) {
        BaeLogging.e("WebRtcAudioRecord", "Start recording error: " + audioRecordStartErrorCode + ". " + str);
        WebRtcAudioUtils.logAudioState("WebRtcAudioRecord");
        WebRtcAudioRecordErrorCallback webRtcAudioRecordErrorCallback = errorCallback;
        if (webRtcAudioRecordErrorCallback != null) {
            webRtcAudioRecordErrorCallback.onWebRtcAudioRecordStartError(audioRecordStartErrorCode, str);
        }
    }

    private int initRecording(int i, int i2, boolean z, int i3) {
        AudioRecord audioRecord2;
        Object valueOf;
        WebRtcAudioRecord webRtcAudioRecord = this;
        MethodCollector.i(17862);
        StringBuilder sb = new StringBuilder("InitRecording(sampleRate=");
        int i4 = i;
        sb.append(i4);
        sb.append(", channels=");
        int i5 = i2;
        sb.append(i5);
        sb.append(", forbidVoip=");
        boolean z2 = z;
        sb.append(z2);
        sb.append(", preferredMediaModeSource=");
        int i6 = i3;
        sb.append(i6);
        sb.append("):");
        String sb2 = sb.toString();
        webRtcAudioRecord.apiResult = sb2;
        BaeLogging.w("WebRtcAudioRecord", sb2);
        if (webRtcAudioRecord.audioRecord != null) {
            webRtcAudioRecord.reportWebRtcAudioRecordInitError("InitRecording called twice without StopRecording.");
            MethodCollector.o(17862);
            return -1;
        }
        int i7 = i4 / 100;
        webRtcAudioRecord.byteBuffer = ByteBuffer.allocateDirect(i5 * 2 * i7);
        BaeLogging.i("WebRtcAudioRecord", "byteBuffer.capacity: " + webRtcAudioRecord.byteBuffer.capacity());
        webRtcAudioRecord.emptyBytes = new byte[webRtcAudioRecord.byteBuffer.capacity()];
        webRtcAudioRecord.nativeCacheDirectBufferAddress(webRtcAudioRecord.byteBuffer, webRtcAudioRecord.nativeAudioRecord);
        int channelCountToConfiguration = webRtcAudioRecord.channelCountToConfiguration(i5);
        int minBufferSize = AudioRecord.getMinBufferSize(i4, channelCountToConfiguration, 2);
        if (minBufferSize == -1 || minBufferSize == -2) {
            webRtcAudioRecord.reportWebRtcAudioRecordInitError("AudioRecord.getMinBufferSize failed: ".concat(String.valueOf(minBufferSize)));
            webRtcAudioRecord.apiResult += "AudioRecord.getMinBufferSize failed: " + minBufferSize;
            MethodCollector.o(17862);
            return -1;
        }
        BaeLogging.i("WebRtcAudioRecord", "AudioRecord.getMinBufferSize: ".concat(String.valueOf(minBufferSize)));
        int max = Math.max(minBufferSize * 2, webRtcAudioRecord.byteBuffer.capacity());
        BaeLogging.i("WebRtcAudioRecord", "bufferSizeInBytes: ".concat(String.valueOf(max)));
        try {
            synchronized (webRtcAudioRecord) {
                int i8 = defaultMediaModeAudioSource;
                if (i6 == 1) {
                    i8 = 6;
                }
                if (!z2) {
                    i8 = 7;
                }
                audioRecord2 = new AudioRecord(i8, i4, channelCountToConfiguration, 2, max);
                webRtcAudioRecord.audioRecord = audioRecord2;
            }
            if (audioRecord2.getState() != 1) {
                webRtcAudioRecord.reportWebRtcAudioRecordInitError("Failed to create a new AudioRecord instance");
                webRtcAudioRecord.releaseAudioResources();
                StringBuilder sb3 = new StringBuilder();
                sb3.append(webRtcAudioRecord.apiResult);
                sb3.append("Failed to create a new AudioRecord instance state:");
                AudioRecord audioRecord3 = webRtcAudioRecord.audioRecord;
                if (audioRecord3 == null) {
                    valueOf = "null";
                } else {
                    valueOf = Integer.valueOf(audioRecord3.getState());
                }
                sb3.append(valueOf);
                webRtcAudioRecord.apiResult = sb3.toString();
                MethodCollector.o(17862);
                return -1;
            }
            WebRtcAudioEffects webRtcAudioEffects = webRtcAudioRecord.effects;
            if (webRtcAudioEffects != null) {
                webRtcAudioEffects.enable(webRtcAudioRecord.audioRecord.getAudioSessionId());
            }
            webRtcAudioRecord.logMainParameters();
            webRtcAudioRecord.logMainParametersExtended();
            MethodCollector.o(17862);
            return i7;
        } catch (IllegalArgumentException e) {
            webRtcAudioRecord.reportWebRtcAudioRecordInitError("AudioRecord ctor error: " + e.getMessage());
            webRtcAudioRecord.releaseAudioResources();
            webRtcAudioRecord.apiResult += "AudioRecord ctor error: " + e.getMessage();
            MethodCollector.o(17862);
            return -1;
        } catch (Throwable th) {
            MethodCollector.o(17862);
            throw th;
        }
    }
}
