TikTok.apk(点击下载) / InteractEngineImpl.java


package com.ss.avframework.livestreamv2.core.interact;

import X.C62398Oeh;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import com.bytedance.covode.number.Covode;
import com.ss.avframework.livestreamv2.IInputVideoStream;
import com.ss.avframework.livestreamv2.core.Client;
import com.ss.avframework.livestreamv2.core.InteractEngine;
import com.ss.avframework.livestreamv2.core.LiveCore;
import com.ss.avframework.livestreamv2.core.interact.media.MediaEngine;
import com.ss.avframework.livestreamv2.core.interact.model.Config;
import com.ss.avframework.livestreamv2.core.interact.model.InteractConfig;
import com.ss.avframework.livestreamv2.core.interact.model.Region;
import com.ss.avframework.livestreamv2.core.interact.statistic.InteractLogService;
import com.ss.avframework.livestreamv2.core.interact.utils.InteractThreadUtils;
import com.ss.avframework.livestreamv2.filter.IFilterManager;
import com.ss.avframework.livestreamv2.sdkparams.VPassInteractCfg;
import com.ss.avframework.livestreamv2.utils.UrlUtils;
import com.ss.avframework.mixer.VideoMixer;
import com.ss.avframework.opengl.GLThreadManager;
import com.ss.avframework.utils.AVLog;
import com.ss.avframework.utils.LibraryLoader;
import com.ss.avframework.utils.TEBundle;
import com.ss.avframework.utils.ThreadUtils;
import com.ss.bytertc.engine.RTCEngine;
import com.ss.bytertc.engine.livertc.LiveRTCEngine;
import com.ss.bytertc.engine.loader.RTCNativeLibraryLoader;
import com.swift.sandhook.annotation.MethodReflectParams;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class InteractEngineImpl implements InteractEngine, InteractLogService.LogCallback {
    public static AtomicInteger mAtomicInteger = new AtomicInteger(0);
    public static InteractEngineImpl sInteractEngine;
    public String m1stAddClientStack;
    public ArrayList<Client> mClientsList;
    public InteractConfig mConfig;
    public InteractEngineBuilder mEngineBuilder;
    public String mInteractId = "";
    public boolean mIsDispose;
    public LiveCore mLiveCore;
    public LiveCore.Builder.ILogMonitor mLogMonitor;
    public MediaEngine mMediaEngine;
    public JSONObject mMixOnClientParams = null;
    public int mRegionCount;
    public String mRtcAppid = "";
    public LiveRTCEngine mRtcEngine;
    public Map<String, Integer> mRtcMaps;
    public Runnable mTaskAfterPushStream;
    public final Object mTaskFence = new Object();

    /* renamed from: com.ss.avframework.livestreamv2.core.interact.InteractEngineImpl$6  reason: invalid class name */
    public static /* synthetic */ class AnonymousClass6 {
        public static final /* synthetic */ int[] $SwitchMap$com$ss$avframework$livestreamv2$core$LiveCore$FrameType;

        /* JADX WARNING: Can't wrap try/catch for region: R(10:0|1|2|3|4|5|6|7|8|10) */
        /* JADX WARNING: Can't wrap try/catch for region: R(8:0|1|2|3|4|5|6|(3:7|8|10)) */
        /* JADX WARNING: Failed to process nested try/catch */
        /* JADX WARNING: Missing exception handler attribute for start block: B:3:0x0018 */
        /* JADX WARNING: Missing exception handler attribute for start block: B:5:0x0023 */
        /* JADX WARNING: Missing exception handler attribute for start block: B:7:0x002e */
        static {
            Covode.recordClassIndex(117196);
            int[] iArr = new int[LiveCore.FrameType.values().length];
            $SwitchMap$com$ss$avframework$livestreamv2$core$LiveCore$FrameType = iArr;
            iArr[LiveCore.FrameType.DEFAULT_OCCUPY.ordinal()] = 1;
            $SwitchMap$com$ss$avframework$livestreamv2$core$LiveCore$FrameType[LiveCore.FrameType.METADATA.ordinal()] = 2;
            $SwitchMap$com$ss$avframework$livestreamv2$core$LiveCore$FrameType[LiveCore.FrameType.SEI.ordinal()] = 3;
            try {
                $SwitchMap$com$ss$avframework$livestreamv2$core$LiveCore$FrameType[LiveCore.FrameType.METADATA_SEI.ordinal()] = 4;
            } catch (NoSuchFieldError unused) {
            }
        }
    }

    public static class RtcEglContextCheckerInvocationHandler implements InvocationHandler {
        static {
            Covode.recordClassIndex(117197);
        }

        public RtcEglContextCheckerInvocationHandler() {
        }

        private boolean isProxyOfSameInterfaces(Object obj, Class<?> cls) {
            if (!cls.isInstance(obj)) {
                return Proxy.isProxyClass(obj.getClass()) && Arrays.equals(obj.getClass().getInterfaces(), cls.getInterfaces());
            }
            return true;
        }

        @Override // java.lang.reflect.InvocationHandler
        public Object invoke(Object obj, Method method, Object[] objArr) {
            boolean z = false;
            if (objArr == null) {
                objArr = new Object[0];
            }
            if (objArr.length == 0 && method.getName().equals("EglContextDestoryStart")) {
                AVLog.d("InteractEngineImpl", "invoke method: " + method.getName());
                GLThreadManager.lockSharedGLContext();
                return obj;
            } else if (objArr.length == 0 && method.getName().equals("EglContextDestoryEnd")) {
                AVLog.d("InteractEngineImpl", "invoke method: " + method.getName());
                GLThreadManager.unlockSharedGLContext();
                return obj;
            } else if (objArr.length == 0 && method.getName().equals("hashCode")) {
                return Integer.valueOf(hashCode());
            } else {
                if (objArr.length != 1 || !method.getName().equals("equals") || method.getParameterTypes()[0] != Object.class) {
                    return (objArr.length != 0 || !method.getName().equals("toString")) ? obj : toString();
                }
                Object obj2 = objArr[0];
                if (obj2 == null) {
                    return false;
                }
                if (obj == obj2) {
                    return true;
                }
                if (isProxyOfSameInterfaces(obj2, obj.getClass()) && equals(Proxy.getInvocationHandler(obj2))) {
                    z = true;
                }
                return Boolean.valueOf(z);
            }
        }
    }

    static {
        Covode.recordClassIndex(117187);
    }

    public InteractEngineImpl(LiveCore liveCore) {
        this.mLiveCore = liveCore;
        InteractThreadUtils.initThread();
        this.mEngineBuilder = new InteractEngineBuilder(this.mLiveCore);
        this.mLogMonitor = this.mLiveCore.getBuilder().getLogMonitor();
        this.mMediaEngine = new MediaEngine(this.mLiveCore, this.mEngineBuilder);
        setByteRtcSoLoader();
        this.mRtcMaps = new HashMap();
        this.mClientsList = new ArrayList<>();
        setRtcEglContextChecker();
    }

    private void addClients(Client client) {
        if (client != null) {
            client.setInteractEventListener(new Client.InteractEventListener() {
                /* class com.ss.avframework.livestreamv2.core.interact.InteractEngineImpl.AnonymousClass3 */

                static {
                    Covode.recordClassIndex(117193);
                }

                @Override // com.ss.avframework.livestreamv2.core.Client.InteractEventListener
                public void notifyLiveStreamAdjustResolution(Client client, boolean z, int i2, int i3) {
                    LiveCore.Builder builder;
                    LiveCore liveCore = InteractEngineImpl.this.mLiveCore;
                    if (liveCore != null && (builder = liveCore.getBuilder()) != null) {
                        int videoWidth = builder.getVideoWidth();
                        int videoHeight = builder.getVideoHeight();
                        int max = Math.max(videoWidth / 2, i2);
                        int max2 = Math.max(videoHeight / 2, i3);
                        int videoFps = builder.getVideoFps();
                        if (z) {
                            InteractEngineImpl.this.mLiveCore.adaptedVideoResolution(videoWidth, videoHeight, videoFps);
                        } else {
                            InteractEngineImpl.this.mLiveCore.adaptedVideoResolution(max, max2, videoFps);
                        }
                    }
                }

                @Override // com.ss.avframework.livestreamv2.core.Client.InteractEventListener
                public void onInteractInfoReport(Client client, String str, int i2, long j, Object... objArr) {
                    InteractEngineImpl.this.interactInfoReport(client.getRtcEngine().getRtcExtInfo().interactId, client.getConfig().getMixStreamType(), i2, j, str, objArr);
                }

                @Override // com.ss.avframework.livestreamv2.core.Client.InteractEventListener
                public void onInteractStart(Client client) {
                    InteractEngineImpl.this.interactStart();
                }

                @Override // com.ss.avframework.livestreamv2.core.Client.InteractEventListener
                public void onInteractStop(Client client) {
                    InteractEngineImpl.this.interactStop();
                }
            });
            synchronized (this.mClientsList) {
                try {
                    if (this.mClientsList.isEmpty()) {
                        this.m1stAddClientStack = Log.getStackTraceString(new Exception());
                    } else {
                        AVLog.logKibana(6, "InteractEngineImpl", "Created more than 1 clients.\nstack 1: " + this.m1stAddClientStack + "\nstack 2: " + Log.getStackTraceString(new Exception()), null);
                    }
                    this.mClientsList.add(client);
                } finally {
                }
            }
        }
    }

    private void checkInteractCfg() {
        boolean z;
        InteractConfig interactConfig = this.mConfig;
        VPassInteractCfg vPassInteractCfg = this.mEngineBuilder.getVPassInteractCfg();
        if (interactConfig != null && vPassInteractCfg != null) {
            boolean z2 = false;
            if (interactConfig.getCharacter() == Config.Character.ANCHOR) {
                z = true;
                if (interactConfig.getMixStreamType() != Config.MixStreamType.NONE && interactConfig.isNeedCheckClientMixerParams()) {
                    this.mMixOnClientParams = vPassInteractCfg.mixOnClient;
                    checkMixOnClientParams();
                }
            } else {
                z = false;
            }
            interactConfig.setLogReportInterval(5);
            interactConfig.setRoiOn(true);
            interactConfig.setEnableInteractConnectionStatics(false);
            interactConfig.setEnableRemoteUserStatics(vPassInteractCfg.enable_interact_remote_statics);
            LiveCore.Builder builder = this.mEngineBuilder.getLiveCore().getBuilder();
            if (z) {
                Config.MixStreamConfig mixStreamConfig = interactConfig.getMixStreamConfig();
                mixStreamConfig.setVideoSize(builder.getVideoWidth(), builder.getVideoHeight()).setBackgroundColor(interactConfig.getBackgroundColorValue()).setVideoFrameRate(builder.getVideoFps()).setVideoBitrate(builder.getVideoBitrate() / 1000).setVideoCodec(builder.getVideoEncoder() == 2 ? Config.VideoCodec.BYTEVC1 : Config.VideoCodec.H264).setVideoProfile(getVideoProfile(builder.getVideoEncoder(), builder.getVideoProfile())).setVideoGop(builder.getVideoGopSec()).setAudioSampleRate(builder.getAudioSampleHZ()).setAudioChannels(builder.getAudioChannel()).setAudioProfile(builder.getAudioProfile() == 2 ? Config.AudioProfile.HE : Config.AudioProfile.LC).setAudioBitrate(builder.getAudioBitrate() / 1000);
                String str = this.mEngineBuilder.mOriginUrl;
                if (!TextUtils.isEmpty(interactConfig.getMixStreamRtmpUrl())) {
                    str = interactConfig.getMixStreamRtmpUrl();
                }
                String DecodeUrl = UrlUtils.DecodeUrl(str);
                if (!TextUtils.isEmpty(DecodeUrl)) {
                    mixStreamConfig.setStreamUrl(DecodeUrl);
                    mixStreamConfig.setStreamUniqueIdentifier(this.mEngineBuilder.mUUID);
                } else {
                    AVLog.ioe("InteractEngineImpl", "Live stream url is null....");
                }
            } else if (interactConfig.getMixStreamType() != Config.MixStreamType.NONE) {
                AVLog.iow("InteractEngineImpl", "Guest doesn't need mix stream!");
                interactConfig.setMixStreamType(Config.MixStreamType.NONE);
            }
            this.mEngineBuilder.setMixStreamType(interactConfig.getMixStreamType());
            InteractEngineBuilder interactEngineBuilder = this.mEngineBuilder;
            if (builder.getAdmType() == 1) {
                z2 = true;
            }
            interactEngineBuilder.setByteAudioEnabled(z2);
            AVLog.w("InteractEngineImpl", "AdmType: " + builder.getAdmType());
            AVLog.iow("InteractEngineImpl", "AdmType: " + builder.getAdmType());
            interactConfig.setSharedEGLContext14(GLThreadManager.getEGLContext());
            if (interactConfig.getHandler() == null) {
                interactConfig.setHandler(InteractThreadUtils.getWorkThreadHandler());
            }
        }
    }

    private void checkMixOnClientParams() {
        try {
            if (this.mMixOnClientParams != null) {
                AVLog.logKibana(5, "InteractEngineImpl", "mixOnClient Params:" + this.mMixOnClientParams.toString(), null);
                boolean checkVendorClientMixPercentage = checkVendorClientMixPercentage();
                if (this.mConfig.getMixStreamType() != Config.MixStreamType.NONE) {
                    if (!checkVendorClientMixPercentage) {
                        this.mConfig.setMixStreamType(Config.MixStreamType.SERVER_MIX);
                    } else if (this.mEngineBuilder.getVPassInteractCfg().interactUsingRtcClientMix) {
                        this.mConfig.setMixStreamType(Config.MixStreamType.RTC_CLIENT_MIX);
                    } else {
                        this.mConfig.setMixStreamType(Config.MixStreamType.CLIENT_MIX);
                    }
                }
            }
        } catch (Exception unused) {
        }
        int mixType = LiveRTCEngine.getMixType(this.mConfig.getRtcExtInfo());
        if (mixType == 0 || mixType == 1) {
            this.mConfig.setMixStreamType(mixType == 1 ? Config.MixStreamType.CLIENT_MIX : Config.MixStreamType.SERVER_MIX);
        }
    }

    private void dealInteractConfig(InteractConfig interactConfig) {
        if (interactConfig.getRtcABTestConfig() != null) {
            try {
                JSONObject jSONObject = new JSONObject(interactConfig.getRtcExtInfo());
                jSONObject.put("rtc.ab_label", interactConfig.getRtcABTestConfig());
                interactConfig.setRtcExtInfo(jSONObject.toString());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (interactConfig.isAlignTo16() && !this.mLiveCore.getBuilder().isAlignTo16()) {
            interactConfig.setAlignTo16(false);
        }
        this.mLiveCore.setPublishMixBgColor(interactConfig.getBackgroundColorValue());
    }

    private String dealUrl(String str) {
        return !TextUtils.isEmpty(str) ? str.contains("http://") ? str.replace("http", "wss") : str.contains("https://") ? str.replace("https", "wss") : str : str;
    }

    private void destroyLiveRTCEngine() {
        LiveRTCEngine liveRTCEngine = this.mRtcEngine;
        if (liveRTCEngine != null) {
            liveRTCEngine.doDestroy();
            this.mRtcEngine = null;
        }
    }

    private Config.VideoProfile getVideoProfile(int i2, int i3) {
        return i2 == 2 ? Config.VideoProfile.MAIN : i3 != 2 ? i3 != 3 ? Config.VideoProfile.BASELINE : Config.VideoProfile.HIGH : Config.VideoProfile.MAIN;
    }

    public static /* synthetic */ String lambda$dealInteractConfig$1(JSONObject jSONObject, Client.StreamMixer streamMixer, int i2, int i3, List list) {
        String sb = new StringBuilder().append(list.size()).toString();
        try {
            if (!jSONObject.isNull(sb) && jSONObject.optJSONArray(sb).length() == list.size()) {
                JSONArray jSONArray = jSONObject.getJSONArray(sb);
                for (int i4 = 0; i4 < jSONArray.length(); i4++) {
                    JSONObject jSONObject2 = jSONArray.getJSONObject(i4);
                    Region region = (Region) list.get(i4);
                    if (!(region == null || jSONObject2 == null)) {
                        region.size((double) ((float) jSONObject2.getDouble("width")), (double) ((float) jSONObject2.getDouble(C62398Oeh.LJFF)));
                        region.position((double) ((float) jSONObject2.getDouble("x")), (double) ((float) jSONObject2.getDouble("y")));
                    }
                }
                return "";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return streamMixer != null ? streamMixer.mixStream(i2, i3, list) : "";
    }

    private void setByteRtcSoLoader() {
        RTCEngine.setRtcNativeLibraryLoader(new RTCNativeLibraryLoader() {
            /* class com.ss.avframework.livestreamv2.core.interact.InteractEngineImpl.AnonymousClass1 */

            static {
                Covode.recordClassIndex(117191);
            }

            @Override // com.ss.bytertc.engine.loader.RTCNativeLibraryLoader, org.webrtc.NativeLibraryLoader
            public boolean load(String str) {
                try {
                    boolean loadLibrary = LibraryLoader.loadLibrary(str);
                    AVLog.ioi("InteractEngineImpl", "RtcNativeLibraryLoader load(" + str + "): " + loadLibrary);
                    JSONObject jSONObject = new JSONObject();
                    jSONObject.put("loadLibraryPath", str);
                    jSONObject.put("loadResult", loadLibrary);
                    jSONObject.put("LibraryLoaderName", LibraryLoader.class.getSimpleName());
                    InteractEngineImpl.this.onLogReport("live_client_monitor_log", jSONObject);
                    return loadLibrary;
                } catch (Exception e) {
                    e.printStackTrace();
                    AVLog.logToIODevice(6, "InteractEngineImpl", "RtcNativeLibraryLoader load(" + str + ") error", e);
                    return false;
                }
            }
        });
    }

    private void setRtcEglContextChecker() {
        try {
            Class<?> cls = Class.forName("com.ss.video.rtc.engine.RtcEngine");
            Class<?> cls2 = Class.forName("com.ss.video.rtc.engine.utils.RtcEglContextChecker");
            Method method = cls.getMethod("setRtcEglContextChecker", cls2);
            if (method != null) {
                RtcEglContextCheckerInvocationHandler rtcEglContextCheckerInvocationHandler = new RtcEglContextCheckerInvocationHandler();
                method.invoke(null, Proxy.newProxyInstance(InteractEngineImpl.class.getClassLoader(), new Class[]{cls2}, rtcEglContextCheckerInvocationHandler));
            }
        } catch (ClassNotFoundException | NoSuchMethodException unused) {
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void setRtcParameters(InteractConfig interactConfig) {
        try {
            JSONObject jSONObject = new JSONObject();
            jSONObject.put("rtc.aid", interactConfig.getAppId());
            JSONObject jSONObject2 = new JSONObject();
            jSONObject2.put("app_version", interactConfig.getAppVersion());
            jSONObject2.put("app_min_version", interactConfig.getAppMinVersion());
            jSONObject2.put("app_channel", interactConfig.getAppChannel());
            jSONObject.put("rtc.common_extra_info", jSONObject2.toString());
            InteractConfig.UrlDispatcher urlDispatcher = interactConfig.getUrlDispatcher();
            if (urlDispatcher != null) {
                JSONArray jSONArray = new JSONArray();
                String urlDispatch = urlDispatcher.urlDispatch("https://rtc-sg.tiktokv.com/");
                jSONArray.put(urlDispatch);
                JSONObject jSONObject3 = new JSONObject();
                JSONObject jSONObject4 = new JSONObject();
                jSONObject3.put("event_key", "rtc_url_dispatcher");
                JSONObject jSONObject5 = new JSONObject();
                jSONObject5.put("target_url", "https://rtc-sg.tiktokv.com/");
                jSONObject5.put("result_url", urlDispatch);
                jSONObject4.put("config_url", jSONObject5);
                JSONArray jSONArray2 = new JSONArray();
                String urlDispatch2 = urlDispatcher.urlDispatch("https://rtcpc-access-sg.tiktokv.com/");
                String urlDispatch3 = urlDispatcher.urlDispatch("https://rtc-access-sg.tiktokv.com/");
                jSONArray2.put(urlDispatch2);
                jSONArray2.put(urlDispatch3);
                JSONObject jSONObject6 = new JSONObject();
                jSONObject6.put("target_url", "https://rtcpc-access-sg.tiktokv.com/");
                jSONObject6.put("result_url", urlDispatch2);
                jSONObject4.put("access_url_rtcpc", jSONObject6);
                JSONObject jSONObject7 = new JSONObject();
                jSONObject7.put("target_url", "https://rtc-access-sg.tiktokv.com/");
                jSONObject7.put("result_url", urlDispatch3);
                jSONObject4.put("access_url_rtc", jSONObject7);
                String str = dealUrl(urlDispatcher.urlDispatch("https://rtc-logger-va.tiktokv.com/")) + "report";
                JSONObject jSONObject8 = new JSONObject();
                jSONObject8.put("target_url", "https://rtc-logger-va.tiktokv.com/");
                jSONObject8.put("result_url", str);
                jSONObject4.put("log_report_url", jSONObject8);
                if (!TextUtils.isEmpty(jSONArray.toString())) {
                    jSONObject.put("config_hosts", jSONArray);
                }
                if (!TextUtils.isEmpty(jSONArray2.toString())) {
                    jSONObject.put("access_hosts", jSONArray2);
                }
                if (!TextUtils.isEmpty(str)) {
                    jSONObject.put("rtc.log_sdk_websocket_url", str);
                }
                jSONObject3.put("message", jSONObject4.toString());
                onLogReport("live_client_monitor_log", jSONObject3);
            }
            LiveRTCEngine.setParameters(jSONObject.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void startMixStream() {
        AVLog.iod("InteractEngineImpl", "Start RtcMixStream");
        LiveCore liveCore = this.mEngineBuilder.getLiveCore();
        if (liveCore != null) {
            AVLog.iod("InteractEngineImpl", "livecore switch audio mode to MODE_VOICE_COMMUNICATION");
            liveCore.switchAudioMode(7);
            if (this.mEngineBuilder.getMixStreamType() == Config.MixStreamType.SERVER_MIX) {
                liveCore.stop();
            }
        }
    }

    private void startRtcPublish() {
        startMixStream();
    }

    private void stopClientAndDestoryEngine() {
        synchronized (this.mClientsList) {
            try {
                ArrayList<Client> arrayList = this.mClientsList;
                if (arrayList != null && arrayList.size() > 0) {
                    Iterator<Client> it = this.mClientsList.iterator();
                    while (it.hasNext()) {
                        Client next = it.next();
                        if (next != null) {
                            next.stop();
                        }
                    }
                    this.mClientsList.clear();
                }
            } finally {
            }
        }
        LiveRTCEngine liveRTCEngine = this.mRtcEngine;
        if (liveRTCEngine != null) {
            liveRTCEngine.doDestroy();
            this.mRtcEngine = null;
        }
    }

    public synchronized void checkReleaseRtcEngine() {
        ArrayList<Client> arrayList = this.mClientsList;
        if (arrayList != null && arrayList.size() == 0 && InteractThreadUtils.getWorkThreadHandler() != null && !InteractThreadUtils.getWorkThreadHandler().post(new InteractEngineImpl$$Lambda$1(this))) {
            destroyLiveRTCEngine();
            this.mRtcEngine = null;
        }
    }

    public boolean checkVendorClientMixPercentage() {
        int currentTimeMillis = (int) (System.currentTimeMillis() % 100);
        try {
            JSONObject jSONObject = this.mMixOnClientParams;
            return jSONObject != null && !jSONObject.isNull(MethodReflectParams.BYTE) && this.mMixOnClientParams.getJSONObject(MethodReflectParams.BYTE).getInt(this.mConfig.getInteractMode().toString()) > currentTimeMillis;
        } catch (JSONException unused) {
        }
    }

    @Override // com.ss.avframework.livestreamv2.core.InteractEngine
    public Client create(InteractConfig interactConfig) {
        dealInteractConfig(interactConfig);
        this.mConfig = interactConfig;
        checkInteractCfg();
        Client[] clientArr = new Client[1];
        Handler workThreadHandler = InteractThreadUtils.getWorkThreadHandler();
        if (workThreadHandler != null) {
            ThreadUtils.invokeAtFrontUninterruptibly(workThreadHandler, new InteractEngineImpl$$Lambda$0(this, clientArr, interactConfig));
        }
        return clientArr[0];
    }

    public Client createClient(InteractConfig interactConfig) {
        InteractAudioSinkFactory interactAudioSinkFactory;
        String str;
        if (this.mRtcEngine == null) {
            LiveRTCEngine.setEnv(interactConfig.getRtcEnv());
            LiveRTCEngine.setDeviceId(interactConfig.getDeviceId());
            setRtcParameters(interactConfig);
            LiveRTCEngine liveRTCEngine = new LiveRTCEngine(interactConfig.getContext(), interactConfig.getRtcExtInfo(), null, interactConfig.getSharedEGLContext14(), null);
            this.mRtcEngine = liveRTCEngine;
            this.mRtcAppid = liveRTCEngine.getAppId();
        }
        if (this.mRtcEngine != null && !this.mRtcAppid.equalsIgnoreCase(LiveRTCEngine.getAppId(interactConfig.getRtcExtInfo()))) {
            this.mRtcEngine.doDestroy();
            LiveRTCEngine.setDeviceId(interactConfig.getDeviceId());
            LiveRTCEngine liveRTCEngine2 = new LiveRTCEngine(interactConfig.getContext(), interactConfig.getRtcExtInfo(), null, interactConfig.getSharedEGLContext14(), null);
            this.mRtcEngine = liveRTCEngine2;
            this.mRtcAppid = liveRTCEngine2.getAppId();
        }
        InteractAudioClientFactory interactAudioClientFactory = null;
        if (!this.mEngineBuilder.isByteAudioEnabled()) {
            interactAudioClientFactory = this.mMediaEngine.getAudioClientFactory();
            interactAudioSinkFactory = this.mMediaEngine.getInteractAudioSinkFactory();
        } else {
            interactAudioSinkFactory = null;
        }
        ClientImpl clientImpl = new ClientImpl(this.mRtcEngine, interactConfig, this.mMediaEngine.getVideoClientFactory(), this.mMediaEngine.getInteractVideoSinkFactory(), interactAudioClientFactory, interactAudioSinkFactory, this.mMediaEngine, this);
        LiveRTCEngine liveRTCEngine3 = this.mRtcEngine;
        if (!(liveRTCEngine3 == null || liveRTCEngine3.getRtcExtInfo() == null)) {
            String str2 = this.mRtcEngine.getRtcExtInfo().interactId;
            this.mInteractId = str2;
            this.mMediaEngine.setInteractId(str2);
        }
        LiveCore liveCore = this.mLiveCore;
        if (liveCore != null) {
            liveCore.registerInteractListener(new LiveCore.ILiveForInteractListener() {
                /* class com.ss.avframework.livestreamv2.core.interact.InteractEngineImpl.AnonymousClass5 */

                static {
                    Covode.recordClassIndex(117195);
                }

                /* JADX WARNING: Failed to process nested try/catch */
                /* JADX WARNING: Missing exception handler attribute for start block: B:21:0x0061 */
                @Override // com.ss.avframework.livestreamv2.core.LiveCore.ILiveForInteractListener
                public void onInfo(int i2, int i3, int i4) {
                    if (i2 == 2 || i2 == 15) {
                        InteractEngineImpl.this.stopInteractTask();
                    } else if (i2 == 32 && InteractEngineImpl.this.mClientsList != null && !InteractEngineImpl.this.mClientsList.isEmpty()) {
                        synchronized (InteractEngineImpl.this.mClientsList) {
                            JSONObject jSONObject = new JSONObject();
                            jSONObject.put("fps", i3);
                            JSONObject put = new JSONObject().put("PushBase", jSONObject);
                            Iterator<Client> it = InteractEngineImpl.this.mClientsList.iterator();
                            while (it.hasNext()) {
                                Client next = it.next();
                                if (next instanceof ClientImpl) {
                                    next.updateSdkParams(put.toString());
                                }
                            }
                            try {
                            } catch (Throwable th) {
                                throw th;
                            }
                        }
                    }
                }

                @Override // com.ss.avframework.livestreamv2.core.LiveCore.ILiveForInteractListener
                public void updateAuthInfo(JSONObject jSONObject, LiveCore.FrameType frameType) {
                    Client.FrameType frameType2 = Client.FrameType.SEI;
                    int i2 = AnonymousClass6.$SwitchMap$com$ss$avframework$livestreamv2$core$LiveCore$FrameType[frameType.ordinal()];
                    if (i2 == 1) {
                        frameType2 = Client.FrameType.DEFAULT_OCCUPY;
                    } else if (i2 == 2) {
                        frameType2 = Client.FrameType.METADATA;
                    } else if (i2 == 3) {
                        frameType2 = Client.FrameType.SEI;
                    } else if (i2 == 4) {
                        frameType2 = Client.FrameType.METADATA_SEI;
                    }
                    if (InteractEngineImpl.this.mClientsList != null) {
                        Iterator<Client> it = InteractEngineImpl.this.mClientsList.iterator();
                        while (it.hasNext()) {
                            it.next().updateAuthInfo(jSONObject, frameType2);
                        }
                    }
                }

                @Override // com.ss.avframework.livestreamv2.core.LiveCore.ILiveForInteractListener
                public void updateSei(String str, Object obj) {
                    InteractVideoClientFactory videoClientFactory = InteractEngineImpl.this.mMediaEngine.getVideoClientFactory();
                    if (videoClientFactory != null) {
                        videoClientFactory.needSaveSei(str, obj);
                    }
                }
            });
            IFilterManager videoFilterMgr = this.mLiveCore.getVideoFilterMgr();
            if (!(videoFilterMgr == null || (str = this.mInteractId) == null)) {
                videoFilterMgr.setContourInfoIndex(str);
            }
        }
        AVLog.iod("InteractEngineImpl", "Create Interact Client " + clientImpl + " with mix type " + interactConfig.getMixStreamType() + ", AudioClientFactory " + interactAudioSinkFactory + ", AudioSinkFactory " + interactAudioClientFactory);
        return clientImpl;
    }

    public void dealSeiInfo(int i2, String str, int i3, int i4, int i5, long j, ByteBuffer byteBuffer) {
        ByteBuffer byteBuffer2;
        InteractEngineImpl interactEngineImpl;
        if (byteBuffer == null || byteBuffer.isDirect()) {
            byteBuffer2 = byteBuffer;
            interactEngineImpl = this;
        } else {
            byteBuffer2 = ByteBuffer.allocateDirect(byteBuffer.capacity());
            byteBuffer2.position(0);
            byteBuffer2.put(byteBuffer);
            byteBuffer.rewind();
            byteBuffer2.position(0);
            interactEngineImpl = this;
        }
        LiveCore liveCore = interactEngineImpl.mLiveCore;
        if (liveCore != null) {
            liveCore.pushRtcSeiData(i2, str, i3, i4, i5, null, 0, j, byteBuffer2);
        }
    }

    @Override // com.ss.avframework.livestreamv2.core.InteractEngine
    public synchronized void dispose() {
        if (!this.mIsDispose) {
            this.mIsDispose = true;
            if (InteractThreadUtils.getWorkThreadHandler() != null && !InteractThreadUtils.getWorkThreadHandler().post(new InteractEngineImpl$$Lambda$2(this))) {
                stopClientAndDestoryEngine();
                this.mRtcEngine = null;
            }
            MediaEngine mediaEngine = this.mMediaEngine;
            if (mediaEngine != null) {
                mediaEngine.unRegisterFrameAvailableListener();
            }
            InteractThreadUtils.postWorkTask(new Runnable() {
                /* class com.ss.avframework.livestreamv2.core.interact.InteractEngineImpl.AnonymousClass4 */

                static {
                    Covode.recordClassIndex(117194);
                }

                public void run() {
                    if (InteractEngineImpl.this.mMediaEngine != null) {
                        InteractEngineImpl.this.mMediaEngine.stop();
                    }
                }
            });
            InteractThreadUtils.destroyThread();
        }
    }

    public InteractEngineBuilder getBuilder() {
        return this.mEngineBuilder;
    }

    public IInputVideoStream getOriginInputVideoStream() {
        LiveCore liveCore = this.mLiveCore;
        if (liveCore != null) {
            return liveCore.getOriginInputVideoStream();
        }
        return null;
    }

    public void interactInfoReport(String str, Object obj, int i2, long j, String str2, Object... objArr) {
        int i3 = 0;
        int i4 = 3;
        if (i2 != 12) {
            if (i2 == 13 && this.mLiveCore.getBuilder().getSdkSetting().switchParams.getImPerfAlarm() && objArr.length == 3) {
                int parseInt = Integer.parseInt(objArr[0].toString());
                int parseInt2 = Integer.parseInt(objArr[1].toString());
                int parseInt3 = Integer.parseInt(objArr[2].toString());
                TEBundle tEBundle = new TEBundle();
                tEBundle.setInt("width", parseInt);
                tEBundle.setInt(C62398Oeh.LJFF, parseInt2);
                tEBundle.setInt("fps", parseInt3);
                this.mLiveCore.updateSdkParams(tEBundle);
                tEBundle.release();
            }
        } else if (objArr[0].toString().equals(str)) {
            int intValue = ((Integer) objArr[1]).intValue();
            if (intValue == 1 || intValue == 2) {
                i3 = 1;
            } else if (intValue == 3) {
                i3 = 2;
            } else if (intValue == 4) {
                i3 = 3;
            }
            if (this.mLiveCore != null) {
                if (obj == Config.MixStreamType.CLIENT_MIX) {
                    i4 = 2;
                }
                this.mLiveCore.onOuterInfo(101, i4, i3);
            }
        }
    }

    public void interactStart() {
        LiveCore liveCore = this.mLiveCore;
        if (liveCore != null) {
            liveCore.onInteractEvent(1, 0, new Object[0]);
        }
    }

    public void interactStop() {
        IInputVideoStream originInputVideoStream = getOriginInputVideoStream();
        if (originInputVideoStream != null) {
            originInputVideoStream.setMixerDescription(VideoMixer.VideoMixerDescription.FILL().setMode(2));
        }
        LiveCore liveCore = this.mLiveCore;
        if (liveCore != null) {
            liveCore.onInteractEvent(2, 0, new Object[0]);
        }
    }

    public void joinChannel() {
        AVLog.iod("InteractEngineImpl", "joinChannel");
        MediaEngine mediaEngine = this.mMediaEngine;
        if (mediaEngine != null) {
            mediaEngine.registerFrameAvailableListener();
        }
    }

    public final /* synthetic */ void lambda$checkReleaseRtcEngine$2$InteractEngineImpl() {
        destroyLiveRTCEngine();
        this.mRtcEngine = null;
    }

    public final /* synthetic */ void lambda$create$0$InteractEngineImpl(Client[] clientArr, InteractConfig interactConfig) {
        clientArr[0] = createClient(interactConfig);
        addClients(clientArr[0]);
        AVLog.iod("InteractEngineImpl", "Create interact client(" + interactConfig.getCharacter() + "," + this.mEngineBuilder.getMixStreamType() + " mix with textureView " + (interactConfig.getViewType() == Config.ViewType.TEXTURE_VIEW) + ") " + clientArr[0]);
    }

    public final /* synthetic */ void lambda$dispose$3$InteractEngineImpl() {
        stopClientAndDestoryEngine();
        this.mRtcEngine = null;
    }

    public boolean needChangeInteractModeWhenSwitchMode() {
        try {
            JSONObject jSONObject = this.mMixOnClientParams;
            return jSONObject != null && !jSONObject.isNull("checkMixTypeOnSwitchMode") && this.mMixOnClientParams.getBoolean("checkMixTypeOnSwitchMode");
        } catch (Exception unused) {
        }
    }

    @Override // com.ss.avframework.livestreamv2.core.interact.statistic.InteractLogService.LogCallback
    public void onLogReport(final String str, final JSONObject jSONObject) {
        Handler logUppThreadHandler = InteractThreadUtils.getLogUppThreadHandler();
        if (logUppThreadHandler != null) {
            logUppThreadHandler.post(new Runnable() {
                /* class com.ss.avframework.livestreamv2.core.interact.InteractEngineImpl.AnonymousClass2 */

                static {
                    Covode.recordClassIndex(117192);
                }

                public void run() {
                    if (InteractEngineImpl.this.mLogMonitor != null) {
                        InteractEngineImpl.this.mLogMonitor.onLogMonitor(str, jSONObject);
                    }
                }
            });
        }
    }

    public void onRegionChanged(int i2) {
        LiveCore liveCore;
        int i3 = this.mRegionCount;
        if (((i3 <= 1 && i2 > 1) || (i3 > 1 && i2 <= 1)) && (liveCore = this.mLiveCore) != null) {
            liveCore.requestKeyFrame();
        }
        this.mRegionCount = i2;
    }

    public int queryRtcId(String str) {
        synchronized (this.mRtcMaps) {
            try {
                for (Map.Entry<String, Integer> entry : this.mRtcMaps.entrySet()) {
                    if (entry.getKey().equals(str)) {
                        return entry.getValue().intValue();
                    }
                }
                int incrementAndGet = mAtomicInteger.incrementAndGet();
                this.mRtcMaps.put(str, Integer.valueOf(incrementAndGet));
                return incrementAndGet;
            } finally {
            }
        }
    }

    public boolean removeClient(Client client) {
        synchronized (this.mClientsList) {
            try {
                ArrayList<Client> arrayList = this.mClientsList;
                if (arrayList == null || arrayList.isEmpty() || client == null) {
                    return false;
                }
                return this.mClientsList.remove(client);
            } finally {
            }
        }
    }

    public void setMixOnClientParams(JSONObject jSONObject) {
        this.mMixOnClientParams = jSONObject;
    }

    public void setVideoCaptureResolution(int i2, int i3) {
        LiveCore liveCore = this.mEngineBuilder.getLiveCore();
        if (liveCore != null) {
            liveCore.adaptedVideoResolution(i2, i3);
        }
    }

    public void start(Client client) {
        AVLog.iod("InteractEngineImpl", "Start client: ".concat(String.valueOf(client)));
        startRtcPublish();
        MediaEngine mediaEngine = this.mMediaEngine;
        if (mediaEngine != null) {
            mediaEngine.registerFrameAvailableListener();
        }
    }

    public void startInteract(Client client) {
        AVLog.iod("InteractEngineImpl", "startInteract at client: ".concat(String.valueOf(client)));
        startMixStream();
    }

    public void startPushData(Client client) {
    }

    public void stop(Client client, InteractConfig interactConfig, Runnable runnable) {
        List<String> urls;
        AVLog.iod("InteractEngineImpl", "Stop clientFactory at client: ".concat(String.valueOf(client)));
        synchronized (this.mTaskFence) {
            try {
                this.mTaskAfterPushStream = runnable;
            } finally {
            }
        }
        LiveCore liveCore = this.mEngineBuilder.getLiveCore();
        if (liveCore != null) {
            AVLog.iod("InteractEngineImpl", "livecore switch audio mode to MODE_MIC");
            liveCore.switchAudioMode(1);
            if (this.mEngineBuilder.getMixStreamType() == Config.MixStreamType.SERVER_MIX && (urls = liveCore.getUrls()) != null && !urls.isEmpty()) {
                liveCore.setPushStreamAfterServerMix(true);
                liveCore.start(liveCore.getUrls());
            }
        }
    }

    public void stopInteractTask() {
        synchronized (this.mTaskFence) {
            try {
                Runnable runnable = this.mTaskAfterPushStream;
                if (runnable != null) {
                    runnable.run();
                }
                this.mTaskAfterPushStream = null;
            } finally {
            }
        }
    }

    public void switchMixType(Config.MixStreamType mixStreamType) {
        LiveCore liveCore = this.mEngineBuilder.getLiveCore();
        if (liveCore != null && mixStreamType != this.mEngineBuilder.getMixStreamType()) {
            if (mixStreamType == Config.MixStreamType.SERVER_MIX) {
                this.mEngineBuilder.setMixStreamType(Config.MixStreamType.SERVER_MIX);
                liveCore.addSeiField("app_data", null, -1);
                liveCore.addSeiField("canvas", null, -1);
                liveCore.addSeiField("source", null, -1);
                if (!this.mEngineBuilder.getVPassInteractCfg().enablePushStreamSwitchAfterServerMixStream) {
                    liveCore.stop();
                }
            } else if (mixStreamType == Config.MixStreamType.CLIENT_MIX) {
                this.mEngineBuilder.setMixStreamType(Config.MixStreamType.CLIENT_MIX);
                List<String> urls = liveCore.getUrls();
                if (urls != null && !urls.isEmpty()) {
                    liveCore.start(urls);
                }
            } else if (mixStreamType == Config.MixStreamType.RTC_CLIENT_MIX) {
                this.mEngineBuilder.setMixStreamType(Config.MixStreamType.RTC_CLIENT_MIX);
                List<String> urls2 = liveCore.getUrls();
                if (urls2 != null && !urls2.isEmpty()) {
                    liveCore.start(urls2);
                }
            }
        }
    }
}