翰林优商.apk(点击下载) / MicrophoneServer.java


package com.baidu.speech.audio;

import android.media.AudioRecord;
import android.net.LocalServerSocket;
import android.net.LocalSocket;
import android.text.TextUtils;
import android.util.Log;
import com.baidu.speech.utils.LogUtil;
import com.sigmob.sdk.base.network.b;
import java.io.DataInputStream;
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import kotlin.UByte;

public class MicrophoneServer implements Runnable {
    private static final int PORT = 3277;
    public static final int S_DATA_LENGTH = 1920000;
    public static final int S_LENGTH = 640;
    public static final String TAG = "MicrophoneServer";
    private static HashMap<String, MicrophoneServer> sPorts = new HashMap<>();
    private String SOCKET_ADDRESS = "com.baidu.speech";
    private boolean firstStart = true;
    public Future<Integer> future;
    private int mAudioSource;
    private DataInputStream mIn = null;
    private String mInfile;
    private ArrayList<SocketWrap> mRemoteOutputStreams = new ArrayList<>();
    private final int mServerPort;
    private LocalServerSocket mServerSocket;
    public ExecutorService newSingleThreadExecutor = Executors.newSingleThreadExecutor();
    private final byte[] sData = new byte[S_DATA_LENGTH];
    private final int sLen = 640;
    private long sLimit = 0;

    public static class MicInputStream extends InputStream {
        private static final int DEFAULT_BUFFER_SIZE = 160000;
        private String TAG = MicInputStream.class.getSimpleName();
        private AudioRecord mAudioRecord;

        public MicInputStream(int i, int i2) {
            int i3;
            try {
                this.mAudioRecord = new AudioRecord(i, i2, 16, 2, DEFAULT_BUFFER_SIZE);
                LogUtil.i("audioSource : ", i + "");
                String str = this.TAG;
                LogUtil.i(str, "startRecordingAndCheckStatus recorder status is " + this.mAudioRecord.getState());
                this.mAudioRecord.startRecording();
                byte[] bArr = new byte[32];
                int i4 = 0;
                while (true) {
                    if (i4 >= 10) {
                        i3 = 0;
                        break;
                    }
                    int read = this.mAudioRecord.read(bArr, 0, 32);
                    if (read > 0) {
                        i3 = read + 0;
                        break;
                    }
                    i4++;
                }
                if (i3 <= 0) {
                    this.mAudioRecord.release();
                    new Exception("bad recorder, read(byte[])");
                }
                AudioRecord audioRecord = this.mAudioRecord;
                if ((audioRecord != null && audioRecord.getRecordingState() != 3) || this.mAudioRecord.getState() == 0) {
                    try {
                        this.mAudioRecord.release();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    String str2 = this.TAG;
                    LogUtil.d(str2, "recorder start failed, RecordingState=" + this.mAudioRecord.getRecordingState());
                }
            } catch (Exception e2) {
                e2.printStackTrace();
                AudioRecord audioRecord2 = this.mAudioRecord;
                if ((audioRecord2 != null && audioRecord2.getRecordingState() != 3) || this.mAudioRecord.getState() == 0) {
                    try {
                        this.mAudioRecord.release();
                    } catch (Exception e3) {
                        e3.printStackTrace();
                    }
                    String str3 = this.TAG;
                    LogUtil.d(str3, "recorder start failed, RecordingState=" + this.mAudioRecord.getRecordingState());
                }
            } catch (Throwable th) {
                AudioRecord audioRecord3 = this.mAudioRecord;
                if (!(audioRecord3 == null || audioRecord3.getRecordingState() == 3) || this.mAudioRecord.getState() == 0) {
                    try {
                        this.mAudioRecord.release();
                    } catch (Exception e4) {
                        e4.printStackTrace();
                    }
                    String str4 = this.TAG;
                    LogUtil.d(str4, "recorder start failed, RecordingState=" + this.mAudioRecord.getRecordingState());
                }
                throw th;
            }
        }

        @Override // java.io.Closeable, java.lang.AutoCloseable, java.io.InputStream
        public void close() {
            AudioRecord audioRecord = this.mAudioRecord;
            if (audioRecord != null) {
                audioRecord.release();
            }
        }

        @Override // java.io.InputStream
        public int read() {
            throw new IOException("read not support");
        }

        @Override // java.io.InputStream
        public int read(byte[] bArr, int i, int i2) {
            AudioRecord audioRecord = this.mAudioRecord;
            if (audioRecord != null) {
                int read = audioRecord.read(bArr, i, i2);
                String str = this.TAG;
                LogUtil.v(str, " AudioRecord read: len:" + read + " byteOffset:" + i + " byteCount:" + i2);
                if (read >= 0 && read <= i2) {
                    return read;
                }
                throw new IOException("audio recdoder read error, len = " + read);
            }
            throw new IOException("audio recorder is null");
        }
    }

    public static class SocketWrap extends LocalSocket {
        public byte[] data = new byte[8];
        private long mPosition = -1;
        private final LocalSocket mSocket;

        public SocketWrap(LocalSocket localSocket) {
            this.mSocket = localSocket;
            try {
                localSocket.setSoTimeout(2000);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        private long byteArrayToInt(byte[] bArr) {
            byte[] bArr2 = new byte[8];
            int i = 7;
            int i2 = 0;
            while (i >= 0) {
                if (i2 < bArr.length) {
                    bArr2[i] = bArr[i2];
                } else {
                    bArr2[i] = 0;
                }
                i--;
                i2++;
            }
            return (((long) (bArr2[0] & UByte.MAX_VALUE)) << 56) + (((long) (bArr2[1] & UByte.MAX_VALUE)) << 48) + (((long) (bArr2[2] & UByte.MAX_VALUE)) << 40) + (((long) (bArr2[3] & UByte.MAX_VALUE)) << 32) + (((long) (bArr2[4] & UByte.MAX_VALUE)) << 24) + (((long) (bArr2[5] & UByte.MAX_VALUE)) << 16) + (((long) (bArr2[6] & UByte.MAX_VALUE)) << 8) + ((long) (bArr2[7] & UByte.MAX_VALUE));
        }

        @Override // java.io.Closeable, java.lang.AutoCloseable, android.net.LocalSocket
        public synchronized void close() {
            this.mSocket.close();
        }

        @Override // android.net.LocalSocket
        public OutputStream getOutputStream() {
            return this.mSocket.getOutputStream();
        }

        public long getPosition(long j) {
            long j2 = this.mPosition;
            if (j2 >= 0) {
                return j2;
            }
            try {
                InputStream inputStream = this.mSocket.getInputStream();
                byte[] bArr = this.data;
                inputStream.read(bArr, 0, bArr.length);
                long byteArrayToInt = byteArrayToInt(this.data);
                String str = MicrophoneServer.TAG;
                Log.i(str, "audio mills is " + byteArrayToInt);
                if (byteArrayToInt > 0) {
                    this.mPosition = (Math.min(Math.max(0L, System.currentTimeMillis() - byteArrayToInt), j / 32) / 20) * 20 * 32;
                } else {
                    this.mPosition = 640;
                }
                this.mPosition = ((j - this.mPosition) + 1920000) % 1920000;
            } catch (Exception e) {
                this.mPosition = ((j - 640) + 1920000) % 1920000;
                e.printStackTrace();
            }
            return this.mPosition;
        }

        public void setPosition(long j) {
            this.mPosition = j;
        }

        @Override // android.net.LocalSocket
        public void shutdownOutput() {
            this.mSocket.shutdownOutput();
        }
    }

    private MicrophoneServer(String str, int i) {
        int i2;
        LocalServerSocket localServerSocket;
        this.mInfile = str;
        this.mAudioSource = i;
        String str2 = TAG;
        Log.i(str2, "infile:" + str + "  audioSource:" + i);
        if (TextUtils.isEmpty(str)) {
            i2 = new Random().nextInt(1000);
            localServerSocket = new LocalServerSocket(this.SOCKET_ADDRESS + "_" + i2);
        } else {
            i2 = new Random().nextInt(1000);
            localServerSocket = new LocalServerSocket(this.SOCKET_ADDRESS + "_" + i2);
        }
        this.mServerSocket = localServerSocket;
        this.mServerPort = i2;
        new Thread() {
            /* class com.baidu.speech.audio.MicrophoneServer.AnonymousClass1 */

            public void run() {
                while (true) {
                    try {
                        LocalSocket accept = MicrophoneServer.this.mServerSocket.accept();
                        synchronized (MicrophoneServer.this.mRemoteOutputStreams) {
                            MicrophoneServer.this.mRemoteOutputStreams.add(new SocketWrap(accept));
                            String str = MicrophoneServer.TAG;
                            LogUtil.i(str, "add wrap socket, mRemoteOutputStreams size = " + MicrophoneServer.this.mRemoteOutputStreams.size() + " firstStart = " + MicrophoneServer.this.firstStart);
                            if (MicrophoneServer.this.mRemoteOutputStreams.size() == 1 && MicrophoneServer.this.firstStart) {
                                MicrophoneServer.this.firstStart = false;
                                if (MicrophoneServer.this.mIn != null) {
                                    try {
                                        MicrophoneServer.this.mIn.close();
                                        MicrophoneServer.this.mIn = null;
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                                MicrophoneServer microphoneServer = MicrophoneServer.this;
                                InputStream createInputStream = microphoneServer.createInputStream(microphoneServer.mInfile, MicrophoneServer.this.mAudioSource);
                                MicrophoneServer.this.mIn = new DataInputStream(createInputStream);
                                new Thread(MicrophoneServer.this).start();
                            }
                        }
                    } catch (Exception e2) {
                        String str2 = MicrophoneServer.TAG;
                        LogUtil.d(str2, " mRemoteOutputStreams.size:" + MicrophoneServer.this.mRemoteOutputStreams.size());
                        MicrophoneServer.this.firstStart = true;
                        synchronized (MicrophoneServer.this.mRemoteOutputStreams) {
                            Iterator it = MicrophoneServer.this.mRemoteOutputStreams.iterator();
                            while (it.hasNext()) {
                                LocalSocket localSocket = (LocalSocket) it.next();
                                try {
                                    localSocket.getOutputStream().close();
                                    localSocket.close();
                                } catch (IOException e3) {
                                    e3.printStackTrace();
                                }
                            }
                            MicrophoneServer.this.mRemoteOutputStreams.clear();
                            if (MicrophoneServer.this.mIn != null) {
                                try {
                                    MicrophoneServer.this.mIn.close();
                                    MicrophoneServer.this.mIn = null;
                                } catch (Exception e4) {
                                    e4.printStackTrace();
                                }
                            }
                            try {
                                MicrophoneServer.this.mServerSocket.close();
                            } catch (Exception e5) {
                                e5.printStackTrace();
                            }
                            synchronized (MicrophoneServer.sPorts) {
                                MicrophoneServer.sPorts.remove(MicrophoneServer.this.mInfile);
                                e2.printStackTrace();
                                return;
                            }
                        }
                    }
                }
            }
        }.start();
    }

    public static int create(String str, int i) {
        int i2;
        synchronized (sPorts) {
            if (sPorts.get(str) == null) {
                try {
                    sPorts.put(str, new MicrophoneServer(str, i));
                } catch (Exception e) {
                    e.printStackTrace();
                    return PORT;
                }
            }
            i2 = sPorts.get(str).mServerPort;
        }
        return i2;
    }

    /* access modifiers changed from: private */
    /* access modifiers changed from: public */
    private InputStream createInputStream(String str, int i) {
        if (str == null || str.equals("")) {
            return new MicInputStream(i, 16000);
        }
        if (str.startsWith("#")) {
            Matcher matcher = Pattern.compile("^#(.*)[#.](.*?)\\(").matcher(str);
            if (matcher.find()) {
                return (InputStream) Class.forName(matcher.group(1)).getMethod(matcher.group(2), new Class[0]).invoke(null, new Object[0]);
            }
            throw new IOException("can not create inputStream");
        } else if (str.startsWith("res://")) {
            String replaceFirst = str.replaceFirst("res://", "").replaceFirst("/", "");
            Class<?> cls = getClass();
            return cls.getResourceAsStream("/" + replaceFirst);
        } else if (!str.startsWith("asset://") && !str.startsWith("assets://")) {
            return str.startsWith("tcp://") ? new Socket(b.a, Integer.parseInt(str.replaceFirst("tcp://", "").replaceFirst("/", ""))).getInputStream() : new FileInputStream(str);
        } else {
            String replaceFirst2 = str.replaceFirst("assets://", "").replaceFirst("/", "");
            if (str.startsWith("asset://")) {
                replaceFirst2 = str.replaceFirst("asset://", "").replaceFirst("/", "");
            }
            Class<?> cls2 = getClass();
            return cls2.getResourceAsStream("/assets/" + replaceFirst2);
        }
    }

    /* JADX WARNING: Exception block dominator not found, dom blocks: [] */
    /* JADX WARNING: Missing exception handler attribute for start block: B:108:0x01d0 */
    /* JADX WARNING: Missing exception handler attribute for start block: B:57:0x00ff */
    public void run() {
        while (true) {
            try {
                long j = this.sLimit;
                byte[] bArr = this.sData;
                int length = (int) (j % ((long) bArr.length));
                try {
                    this.mIn.readFully(bArr, length, 640);
                    this.sLimit += 640;
                    final int i = length + 640;
                    synchronized (this.mRemoteOutputStreams) {
                        for (int i2 = 0; i2 < this.mRemoteOutputStreams.size(); i2++) {
                            final SocketWrap socketWrap = this.mRemoteOutputStreams.get(i2);
                            try {
                                final int position = (int) (socketWrap.getPosition(this.sLimit) % ((long) this.sData.length));
                                final OutputStream outputStream = socketWrap.getOutputStream();
                                final int i3 = i - position;
                                Future<Integer> submit = this.newSingleThreadExecutor.submit(new Callable<Integer>() {
                                    /* class com.baidu.speech.audio.MicrophoneServer.AnonymousClass2 */

                                    @Override // java.util.concurrent.Callable
                                    public Integer call() {
                                        if (i3 >= 0) {
                                            outputStream.write(MicrophoneServer.this.sData, position, i3);
                                        } else {
                                            outputStream.write(MicrophoneServer.this.sData, position, MicrophoneServer.this.sData.length - position);
                                            outputStream.write(MicrophoneServer.this.sData, 0, i);
                                        }
                                        socketWrap.setPosition(MicrophoneServer.this.sLimit);
                                        return 0;
                                    }
                                });
                                this.future = submit;
                                submit.get(1000, TimeUnit.MILLISECONDS);
                            } catch (TimeoutException e) {
                                throw e;
                            } catch (Exception e2) {
                                e2.printStackTrace();
                                this.mRemoteOutputStreams.remove(socketWrap);
                                socketWrap.getOutputStream().close();
                                socketWrap.close();
                            }
                        }
                        if (this.mRemoteOutputStreams.size() <= 0) {
                            this.firstStart = true;
                        }
                    }
                } catch (EOFException e3) {
                    e3.printStackTrace();
                    this.firstStart = true;
                }
            } catch (TimeoutException e4) {
                e4.printStackTrace();
                synchronized (sPorts) {
                    this.mServerSocket.close();
                    e4.printStackTrace();
                    sPorts.remove(this.mInfile);
                    synchronized (this.mRemoteOutputStreams) {
                        LogUtil.i(TAG, "finally, mRemoteOutputStreams size = " + this.mRemoteOutputStreams.size() + " firstStart = " + this.firstStart);
                        if (this.firstStart) {
                            Iterator<SocketWrap> it = this.mRemoteOutputStreams.iterator();
                            while (it.hasNext()) {
                                SocketWrap next = it.next();
                                try {
                                    next.getOutputStream().close();
                                    next.close();
                                } catch (IOException e5) {
                                    e5.printStackTrace();
                                }
                            }
                            this.mRemoteOutputStreams.clear();
                            try {
                                DataInputStream dataInputStream = this.mIn;
                                if (dataInputStream != null) {
                                    dataInputStream.close();
                                    this.mIn = null;
                                }
                            } catch (Exception e6) {
                                e6.printStackTrace();
                            }
                        }
                        return;
                    }
                }
            } catch (Exception unknown) {
                try {
                    this.firstStart = true;
                    synchronized (this.mRemoteOutputStreams) {
                        for (int i4 = 0; i4 < this.mRemoteOutputStreams.size(); i4++) {
                            try {
                                OutputStream outputStream2 = this.mRemoteOutputStreams.get(i4).getOutputStream();
                                byte[] bArr2 = TextUtils.isEmpty(this.mInfile) ? new byte[]{0, 0, 0, 0, 0, 0} : new byte[]{1, 0, 0, 0, 0, 0};
                                outputStream2.write(bArr2, 0, bArr2.length);
                            } catch (Exception e7) {
                                e7.printStackTrace();
                            }
                        }
                    }
                    synchronized (this.mRemoteOutputStreams) {
                        LogUtil.i(TAG, "finally, mRemoteOutputStreams size = " + this.mRemoteOutputStreams.size() + " firstStart = " + this.firstStart);
                        if (this.firstStart) {
                            Iterator<SocketWrap> it2 = this.mRemoteOutputStreams.iterator();
                            while (it2.hasNext()) {
                                SocketWrap next2 = it2.next();
                                try {
                                    next2.getOutputStream().close();
                                    next2.close();
                                } catch (IOException e8) {
                                    e8.printStackTrace();
                                }
                            }
                            this.mRemoteOutputStreams.clear();
                            try {
                                DataInputStream dataInputStream2 = this.mIn;
                                if (dataInputStream2 != null) {
                                    dataInputStream2.close();
                                    this.mIn = null;
                                }
                            } catch (Exception e9) {
                                e9.printStackTrace();
                            }
                        }
                    }
                    return;
                } catch (Throwable th) {
                    synchronized (this.mRemoteOutputStreams) {
                        LogUtil.i(TAG, "finally, mRemoteOutputStreams size = " + this.mRemoteOutputStreams.size() + " firstStart = " + this.firstStart);
                        if (this.firstStart) {
                            Iterator<SocketWrap> it3 = this.mRemoteOutputStreams.iterator();
                            while (it3.hasNext()) {
                                SocketWrap next3 = it3.next();
                                try {
                                    next3.getOutputStream().close();
                                    next3.close();
                                } catch (IOException e10) {
                                    e10.printStackTrace();
                                }
                            }
                            this.mRemoteOutputStreams.clear();
                            try {
                                DataInputStream dataInputStream3 = this.mIn;
                                if (dataInputStream3 != null) {
                                    dataInputStream3.close();
                                    this.mIn = null;
                                }
                            } catch (Exception e11) {
                                e11.printStackTrace();
                            }
                        }
                        throw th;
                    }
                }
            }
        }
        synchronized (this.mRemoteOutputStreams) {
            LogUtil.i(TAG, "finally, mRemoteOutputStreams size = " + this.mRemoteOutputStreams.size() + " firstStart = " + this.firstStart);
            if (this.firstStart) {
                Iterator<SocketWrap> it4 = this.mRemoteOutputStreams.iterator();
                while (it4.hasNext()) {
                    SocketWrap next4 = it4.next();
                    try {
                        next4.getOutputStream().close();
                        next4.close();
                    } catch (IOException e12) {
                        e12.printStackTrace();
                    }
                }
                this.mRemoteOutputStreams.clear();
                try {
                    DataInputStream dataInputStream4 = this.mIn;
                    if (dataInputStream4 != null) {
                        dataInputStream4.close();
                        this.mIn = null;
                    }
                } catch (Exception e13) {
                    e13.printStackTrace();
                }
            }
        }
    }
}