XjVideoClient.java 14 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
package com.glsx.libxj.manager;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.view.SurfaceHolder;

import com.dp.recvvideo.videoclient;
import com.blankj.utilcode.util.LogUtils;
import com.glsx.commonres.util.MmkvUtil;
import com.glsx.libxj.util.MediaCodecUtil;
import com.glsx.libxj.util.TrendIpUtils;

import java.util.ArrayList;


public class XjVideoClient implements videoclient.VideoCallBack {
    private String TAG = XjVideoClient.class.getSimpleName();
    private final static int CONNECT_PORT = 21010;
    public final static int SEND_MSG_PORT = 20110;//命令消息发送端口
    private final static int MSG_PORT = 21020;//初始化连接工具端口
    private static final int MSG_GET_FRAME = 9001;//直播流数据获取Message

    private static final int MSG_TIMER = 123;
    private static final int MSG_SEND_DEVICE_HEARTBEAT = 105;//发送心跳
    private final int FRONT = 0;//前摄
    private final int REAR = 1;//后摄
    private final String HD = "HD";//分辨率:超清
    private final String SMOOTH = "smooth";//分辨率:高清
    @SuppressLint("StaticFieldLeak")
    private static XjVideoClient sIns;
    private Context mContext;

    public static String ip = "";
    public static int uid = 200;
    private boolean isConnect = false;
    private boolean isQ3Preview = false;

    //视频丢帧数据
    private long videoCarch = 0;
    private int carchNum = 0;

    private int m_istatus = 0;
    private int m_ZeroCount = 0;
    private int m_GetCacheCount = 0;
    private int connectType = FRONT;
    public static int currentCameraOrientation;//当前摄像头方向,前摄还是后摄

    private videoclient m_vc;
    private FrameHandler mFrameHandler;
    private MediaCodecUtil codecUtil;
    private boolean isVideoCallBackOK = false;

    /**
     * 摄像头ID    0:前摄   1:后摄
     */
    private int cameraId = 0;//默认前摄

    //心跳状态
    public int heartbeatState;
    public boolean isHeartbeatConnect;
    private IPlayStatusCallBack mPlayStatusCallBack;//播放状态变更CallBack
    private ArrayList<IPlayStatusCallBack> mPlayStatusCallbacks;

//    public static XjVideoClient instance() {
//        if (null == sIns) {
//            sIns = new XjVideoClient();
//        }
//        return sIns;
//    }

    //单例实现及优化
    private static class Holder{
        private static final XjVideoClient INS = new XjVideoClient();
    }

    public static XjVideoClient instance(){
        return Holder.INS;
    }

    private XjVideoClient() {
        mPlayStatusCallbacks = new ArrayList<>();
    }

    public void init(Context context) {
        mContext = context;
        XjDeviceInfoManager.instance().setContext(mContext);
        HandlerThread ht2 = new HandlerThread("Video Client Handler");
        ht2.start();
        mFrameHandler = new FrameHandler(ht2.getLooper());
    }

    //开始心跳
    public void startHeartBeat() {
        XjDeviceInfoManager.instance().resetWifiTokenAndIMEI();
        mFrameHandler.removeMessages(MSG_SEND_DEVICE_HEARTBEAT);
        mFrameHandler.sendEmptyMessage(MSG_SEND_DEVICE_HEARTBEAT);
    }

    /**
     * 设备WiFi已连接,Client端连接设备服务端.
     */
    public void initAfterWifiConnect() {
        initCameraResolution();
        ip = TrendIpUtils.getIp(mContext);
        uid = TrendIpUtils.getUid(mContext);
        m_vc = videoclient.getIns(MSG_PORT);
        videoclient.setMaxFrame(12);
    }

    private void initCameraResolution() {
        if (TextUtils.isEmpty(getRecordFrontResolution())) {
            setRecordFrontResolution(SMOOTH);
        }
        if (TextUtils.isEmpty(getRecordBehindResolution())) {
            setRecordBehindResolution(SMOOTH);
        }
    }

    /**
     * 开启默认摄像头默认分辨率的直播
     */
    public void startDefaultPreview() {
        boolean frontOrRear = FRONT == currentCameraOrientation;
        boolean cameraResolution = frontOrRear ? HD.equalsIgnoreCase(getRecordFrontResolution()) :
                HD.equalsIgnoreCase(getRecordBehindResolution());
        startPreview(frontOrRear, cameraResolution);
    }

    /**
     * 开始前摄高清直播
     */
    public void startFrontHDPreview() {
        startPreview(true, true);
    }

    /**
     * 开启前摄流畅直播
     */
    public void startFrontSmoothPreview() {
        startPreview(true, false);
    }

    /**
     * 开启后摄高清直播
     */
    public void startRearHDPreview() {
        startPreview(false, true);
    }

    /**
     * 开启后摄流畅直播
     */
    public void startRearSmoothPreview() {
        startPreview(false, false);
    }

    /**
     * 停止直播
     */
    public void stopPreview() {
        LogUtils.w(TAG, "XjVideoClient.stopPreview()");
        disconnect();
    }

    /**
     * 开始直播
     *
     * @param frontOrRear 是否前摄,是/否:前摄|后摄
     * @param isHD        是否高清 ,是|否:高清|标清
     */
    public void startPreview(boolean frontOrRear, boolean isHD) {
        LogUtils.w(TAG, "XjVideoClient.startPreview()");
        startHeartBeat();
        videoCarch = 0;
        carchNum = 0;
        m_GetCacheCount = 0;

        int camId = frontOrRear ? 0 : 1;
        cameraId = frontOrRear ? 0 : 1;
        int resolutionId = isHD ? 0 : 1;
        //前摄分高清和超清;后摄只有一种分辨率
        int width = 640;
        int height = 360;
        if (frontOrRear) {//is front
            width = isHD ? 1920 : 960;
            height = isHD ? 1080 : 540;
        }
        m_vc.SetDecSize(camId, resolutionId, width, height);
        isConnect = m_vc.Connect(ip, CONNECT_PORT, cameraId);

        connectType = frontOrRear ? FRONT : REAR;
        mFrameHandler.removeMessages(MSG_TIMER);
        mFrameHandler.sendEmptyMessage(MSG_TIMER);
    }

    @Override
    public void onRecv(int seq, boolean bkey, byte[] data, int len, int m_cameraID) {
        if (mFrameHandler != null) {
            Message message = mFrameHandler.obtainMessage();
            message.what = MSG_GET_FRAME;
            message.arg1 = len;
            message.obj = data;
            message.sendToTarget();
        }
    }

    private class FrameHandler extends Handler {
        FrameHandler(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_TIMER: {
                    onTimer();
                }
                break;
                case MSG_GET_FRAME:
                    int length = msg.arg1;
                    byte[] data = (byte[]) msg.obj;

                    if (codecUtil != null && !codecUtil.isResetCodec()) {
                        codecUtil.onFrame2(data, 0, length);
                    }
                    break;
                case MSG_SEND_DEVICE_HEARTBEAT:
//                    LogUtils.v(TAG, "heartbeatState 1 = " + heartbeatState + " connect_ip = " + ip);
                    heartbeatState = videoclient.DPMsgSendHeartBeat(ip, SEND_MSG_PORT, uid, 2000);
                    LogUtils.v(TAG, "heartbeatState 2 = " + heartbeatState);
                    if (heartbeatState == 0) {
                        isHeartbeatConnect = false;
                    } else if (heartbeatState == 1) {
                        isHeartbeatConnect = true;
                        if (XjDeviceInfoManager.instance().isDeviceInfoNotGet()) {
                            XjDeviceInfoManager.instance().getConfigData();
                        }
                    }
                    this.sendEmptyMessageDelayed(MSG_SEND_DEVICE_HEARTBEAT, 5 * 1000);
                    break;
                default:
                    break;
            }
        }
    }

    public boolean isVideoCallBackOK() {
        return isVideoCallBackOK;
    }

    @SuppressLint("DefaultLocale")
    public void onTimer() {
        if ((++m_GetCacheCount) % 2 == 0) {
            int iStatus = m_vc.getStatus(cameraId);
//            LogUtils.v(TAG, "onTimer()  m_vc.getStatus() = " + iStatus + "  , m_istatus = " + m_istatus);
            if (iStatus != m_istatus) {
                switch (iStatus) {
                    case 0:
                        isQ3Preview = false;
                        onPlayStop();
                        break;
                    case 1:
                        isQ3Preview = true;
                        if (connectType != currentCameraOrientation) {
                            currentCameraOrientation = connectType;
                        }
                        onPlayStart();
                        break;
                    case 2:
                        LogUtils.e(TAG, "预览页面====缓存中");
                        onPlayCaching();
                        break;
                }
                m_istatus = iStatus;
            }
        }

        int cache = m_vc.getCache(cameraId);
//        LogUtils.v(TAG, "预览页面====缓存值=" + cache);
        if (cache == 0) {
            ++m_ZeroCount;
        } else {
            m_ZeroCount = 0;
        }
        if (isConnect && (m_ZeroCount > 6 || m_vc.checkLastShowTime(10, cameraId))) {//10秒都没有去显示一个I帧则断开
            disconnect();
        }

        if (isConnect) {
            m_vc.SendAck(cameraId);
        }
        mFrameHandler.sendEmptyMessageDelayed(MSG_TIMER, 500);
    }

    /**
     * 断开连接
     */
    private void disconnect() {
        videoCarch = 0;
        carchNum = 0;
        m_vc.DisConnect(cameraId);
        isConnect = false;
        isQ3Preview = false;
        //此处需要将轮训任务移除,避免在重复暂停/播放操作之后m_vc.getStatus()一直为0的状态
        mFrameHandler.removeMessages(MSG_TIMER);
        onPlayStop();
        m_istatus = 0;
    }

    /**
     * 播放开始
     */
    private void onPlayStart() {
        LogUtils.e(TAG, "XjVideoClient.onPlayStart()");
        for (IPlayStatusCallBack callback : mPlayStatusCallbacks) {
            callback.onPlayStart();
        }
    }

    private void onPlayStop() {
        LogUtils.e(TAG, "XjVideoClient.onPlayStop()");
        for (IPlayStatusCallBack callback : mPlayStatusCallbacks) {
            callback.onPlayStop();
        }
    }

    private void onPlayCaching() {

    }

    public synchronized void registerPlayStatusCallBack(IPlayStatusCallBack callback) {
        if (callback != null) {
            mPlayStatusCallbacks.add(callback);
        }
    }

    public synchronized void unregisterPlayStatusCallBack(IPlayStatusCallBack callback) {
        if (callback != null) {
            mPlayStatusCallbacks.remove(callback);
        }
    }

    /**
     * 播放状态回调
     */
    public interface IPlayStatusCallBack {
        void onPlayStart();

        void onPlayStop();
    }

    public void wifiConnect() {

    }

    public void wifiDisconnect() {
        disconnect();
        mFrameHandler.removeMessages(MSG_TIMER);
        mFrameHandler.removeMessages(MSG_SEND_DEVICE_HEARTBEAT);

        //重置状态,避免用户不退出App重新连接了另一台小镜记录仪  双录-->切后录-->连接单录
        cameraId = 0;
        connectType = FRONT;
        currentCameraOrientation = connectType;
    }

//    public void setPreviewLayoutParams(int width, int height) {
//        m_vc.SetDisplayArea(0, 0, width, height);
//    }

    /**
     * 开始|停止录像
     */
    public void switchVideoRecord() {
        XjDeviceInfoManager.instance().switchVideoRecord();
    }

    public synchronized void startCoder(SurfaceHolder holder) {
        LogUtils.w(TAG, "startCoder()");
        if (holder != null && holder.getSurface().isValid()) {
            if (codecUtil == null) {
                codecUtil = new MediaCodecUtil(holder);
                codecUtil.startCodec();
            }
        }
        videoclient.setFrontH264CallBack(this);
        videoclient.setBackH264CallBack(this);
        isVideoCallBackOK = true;
    }

    public void stopCoder() {
        LogUtils.i(TAG, "stopCoder()");
        videoclient.setFrontH264CallBack(null);
        videoclient.setBackH264CallBack(null);
        isVideoCallBackOK = false;
        if (codecUtil != null) {
            codecUtil.stopCodec();
            codecUtil = null;
        }
    }

    public boolean isConnect() {
        return isConnect;
    }

    public boolean isPreview() {
        return isQ3Preview;
    }

    /**
     * 切换摄像头
     */
    public void switchCamera() {
        stopPreview();
        boolean curCameraOri = FRONT == currentCameraOrientation;
        boolean setCameraOri = !curCameraOri;
        boolean cameraResolution = setCameraOri ? HD.equalsIgnoreCase(getRecordFrontResolution()) :
                HD.equalsIgnoreCase(getRecordBehindResolution());
        startPreview(setCameraOri, cameraResolution);
    }

    /**
     * 切换分辨率
     */
    public void switchResolution() {
        if (isConnect) {
            m_vc.DisConnect(cameraId);
            isConnect = false;
        }
        boolean curCameraOri = FRONT == currentCameraOrientation;
        boolean cameraResolution = curCameraOri ? HD.equalsIgnoreCase(getRecordFrontResolution()) :
                HD.equalsIgnoreCase(getRecordBehindResolution());
        startPreview(curCameraOri, !cameraResolution);

    }

    public int getCameraId() {
        return cameraId;
    }

    public String getIp() {
        return ip;
    }

    private String getRecordBehindResolution() {
        return MmkvUtil.getStringPref("RecordbehindResolution");
    }

    private String getRecordFrontResolution() {
        return MmkvUtil.getStringPref("RecordfrontResolution");
    }

    private void setRecordBehindResolution(String recordBehindResolution) {
        MmkvUtil.setPref("RecordbehindResolution", recordBehindResolution);
    }

    private void setRecordFrontResolution(String recordFrontResolution) {
        MmkvUtil.setPref("RecordfrontResolution", recordFrontResolution);
    }
}