AVChatVideoUI.java 29.6 KB
Newer Older
konghaorui committed
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
package com.yidianling.avchatkit.ui;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.graphics.Rect;
import android.os.Build;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Chronometer;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.netease.nimlib.sdk.avchat.AVChatManager;
import com.netease.nimlib.sdk.avchat.constant.AVChatType;
import com.netease.nimlib.sdk.avchat.constant.AVChatVideoScalingType;
import com.netease.nimlib.sdk.avchat.model.AVChatData;
import com.netease.nimlib.sdk.avchat.video.AVChatCameraCapturer;
import com.netease.nimlib.sdk.avchat.video.AVChatSurfaceViewRenderer;
import com.netease.nrtc.video.render.IVideoRender;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.yidianling.avchatkit.AVChatKit;
import com.yidianling.im.R;
import com.yidianling.avchatkit.common.imageview.HeadImageView;
import com.yidianling.avchatkit.common.permission.BaseMPermission;
import com.yidianling.avchatkit.common.util.ScreenUtil;
import com.yidianling.avchatkit.common.widgets.ToggleListener;
import com.yidianling.avchatkit.common.widgets.ToggleState;
import com.yidianling.avchatkit.common.widgets.ToggleView;
import com.yidianling.avchatkit.constant.AVChatExitCode;
import com.yidianling.avchatkit.controll.AVChatController;
import com.yidianling.avchatkit.module.AVChatControllerCallback;
import com.yidianling.avchatkit.module.AVSwitchListener;
import com.yidianling.common.tools.ToastUtil;
import com.ydl.ydlcommon.utils.DeviceTool;

import java.util.List;

import io.reactivex.functions.Consumer;

/**
 * 视频界面变化及点击事件
 * Created by winnie on 2017/12/11.
 */

public class AVChatVideoUI implements View.OnClickListener, ToggleListener {

    // constant
    private static final int PEER_CLOSE_CAMERA = 0;
    private static final int LOCAL_CLOSE_CAMERA = 1;
    private static final int AUDIO_TO_VIDEO_WAIT = 2;
    private static final int TOUCH_SLOP = 10;
    private static final String TAG = AVChatVideoUI.class.getSimpleName();

    private final String[] BASIC_PERMISSIONS = new String[]{Manifest.permission.CAMERA,};

    /**
     * surface view
     */
    private LinearLayout largeSizePreviewLayout;
    private FrameLayout smallSizePreviewFrameLayout;
    private LinearLayout smallSizePreviewLayout;
    private ImageView smallSizePreviewCoverImg;//stands for peer or local close camera
    private TextView largeSizePreviewCoverLayout;//stands for peer or local close camera
    private View touchLayout;

    /**
     * video view
     */
    //顶部控制按钮
    private View topRoot;
    private View switchAudio;
    private Chronometer time;
    //中间控制按钮
    private View middleRoot;
    private HeadImageView headImg;
    private TextView nickNameTV;
    private TextView notifyTV;
    private View refuse_receive;
    private TextView refuseTV;
    private TextView receiveTV;
    //底部控制按钮
    private View bottomRoot;
    ToggleView switchCameraToggle;
    ToggleView closeCameraToggle;
    ToggleView muteToggle;
    ImageView recordToggle;
    ImageView hangUpImg;
    //摄像头权限提示显示
    private View permissionRoot;
    //record
    private View recordView;
    private View recordTip;
    private View recordWarning;

    //render
    private AVChatSurfaceViewRenderer smallRender;
    private AVChatSurfaceViewRenderer largeRender;

    // state
    private boolean surfaceInit = false;
    private boolean videoInit = false;
    private boolean shouldEnableToggle = false;
    public boolean canSwitchCamera = false;
    private boolean isInSwitch = false;
    private boolean isPeerVideoOff = false;
    private boolean isLocalVideoOff = false;
    private boolean localPreviewInSmallSize = true;
    private boolean isRecordWarning = false;
    private boolean isInReceiveing = false;

    // data
    private TouchZoneCallback touchZoneCallback;
    private AVChatData avChatData;
    private String account;
    private String displayName;

    private int topRootHeight = 0;
    private int bottomRootHeight = 0;

    private String largeAccount; // 显示在大图像的用户id
    private String smallAccount; // 显示在小图像的用户id

    // move
    private int lastX, lastY;
    private int inX, inY;
    private Rect paddingRect;

    private Context context;
    private View root;
    private AVChatController avChatController;
    private AVSwitchListener avSwitchListener;
    private boolean isReleasedVideo = false;

    // touch zone
    public interface TouchZoneCallback {
        void onTouch();
    }

    public AVChatVideoUI(Context context, View root, AVChatData avChatData, String displayName,
                         AVChatController avChatController, TouchZoneCallback touchZoneCallback,
                         AVSwitchListener avSwitchListener) {
        this.context = context;
        this.root = root;
        this.avChatData = avChatData;
        this.displayName = displayName;
        this.avChatController = avChatController;
        this.touchZoneCallback = touchZoneCallback;
        this.avSwitchListener = avSwitchListener;
        this.smallRender = new AVChatSurfaceViewRenderer(context);
        this.largeRender = new AVChatSurfaceViewRenderer(context);
    }

    /**
     * ********************** surface 初始化 **********************
     */

    private void findSurfaceView() {
        if (surfaceInit) {
            return;
        }
        View surfaceView = root.findViewById(R.id.avchat_surface_layout);
        if (surfaceView != null) {
            touchLayout = surfaceView.findViewById(R.id.touch_zone);
            touchLayout.setOnTouchListener(touchListener);

            smallSizePreviewFrameLayout = surfaceView.findViewById(R.id.small_size_preview_layout);
            smallSizePreviewLayout = surfaceView.findViewById(R.id.small_size_preview);
            smallSizePreviewCoverImg = surfaceView.findViewById(R.id.smallSizePreviewCoverImg);
            smallSizePreviewFrameLayout.setOnTouchListener(smallPreviewTouchListener);

            largeSizePreviewLayout = surfaceView.findViewById(R.id.large_size_preview);
            largeSizePreviewCoverLayout = surfaceView.findViewById(R.id.notificationLayout);

            surfaceInit = true;
        }
    }


    private View.OnTouchListener touchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_UP && touchZoneCallback != null) {
                touchZoneCallback.onTouch();
            }

            return true;
        }
    };

    private View.OnTouchListener smallPreviewTouchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(final View v, MotionEvent event) {
            int x = (int) event.getRawX();
            int y = (int) event.getRawY();

            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    lastX = x;
                    lastY = y;
                    int[] p = new int[2];
                    smallSizePreviewFrameLayout.getLocationOnScreen(p);
                    inX = x - p[0];
                    inY = y - p[1];

                    break;
                case MotionEvent.ACTION_MOVE:
                    final int diff = Math.max(Math.abs(lastX - x), Math.abs(lastY - y));
                    if (diff < TOUCH_SLOP)
                        break;

                    if (paddingRect == null) {
                        paddingRect = new Rect(ScreenUtil.dip2px(10), ScreenUtil.dip2px(20), ScreenUtil.dip2px(10),
                                ScreenUtil.dip2px(70));
                    }

                    int destX, destY;
                    if (x - inX <= paddingRect.left) {
                        destX = paddingRect.left;
                    } else if (x - inX + v.getWidth() >= ScreenUtil.screenWidth - paddingRect.right) {
                        destX = ScreenUtil.screenWidth - v.getWidth() - paddingRect.right;
                    } else {
                        destX = x - inX;
                    }

                    if (y - inY <= paddingRect.top) {
                        destY = paddingRect.top;
                    } else if (y - inY + v.getHeight() >= ScreenUtil.screenHeight - paddingRect.bottom) {
                        destY = ScreenUtil.screenHeight - v.getHeight() - paddingRect.bottom;
                    } else {
                        destY = y - inY;
                    }

                    FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) v.getLayoutParams();
                    params.gravity = Gravity.NO_GRAVITY;
                    params.leftMargin = destX;
                    params.topMargin = destY;
                    v.setLayoutParams(params);

                    break;
                case MotionEvent.ACTION_UP:
                    if (Math.max(Math.abs(lastX - x), Math.abs(lastY - y)) <= 5) {
                        if (largeAccount == null || smallAccount == null) {
                            return true;
                        }
                        String temp;
                        switchRender(smallAccount, largeAccount);
                        temp = largeAccount;
                        largeAccount = smallAccount;
                        smallAccount = temp;
                        switchAndSetLayout();
                    }

                    break;
            }

            return true;
        }
    };

    private IVideoRender remoteRender;
    private IVideoRender localRender;

    // 大小图像显示切换
    private void switchRender(String user1, String user2) {
        String remoteId = TextUtils.equals(user1, AVChatKit.getAccount()) ? user2 : user1;

        if (remoteRender == null && localRender == null) {
            localRender = smallRender;
            remoteRender = largeRender;
        }

        //交换
        IVideoRender render = localRender;
        localRender = remoteRender;
        remoteRender = render;


        //断开SDK视频绘制画布
        AVChatManager.getInstance().setupLocalVideoRender(null, false, 0);
        AVChatManager.getInstance().setupRemoteVideoRender(remoteId, null, false, 0);

        //重新关联上画布
        AVChatManager.getInstance().setupLocalVideoRender(localRender, false, AVChatVideoScalingType.SCALE_ASPECT_BALANCED);
        AVChatManager.getInstance().setupRemoteVideoRender(remoteId, remoteRender, false, AVChatVideoScalingType.SCALE_ASPECT_BALANCED);

    }

    /**
     * ************************** video 初始化 ***********************
     */
    private void findVideoViews() {
        if (videoInit)
            return;
        View videoRoot = root.findViewById(R.id.avchat_video_layout);
        topRoot = videoRoot.findViewById(R.id.avchat_video_top_control);
        switchAudio = topRoot.findViewById(R.id.avchat_video_switch_audio);
        switchAudio.setOnClickListener(this);
        time = topRoot.findViewById(R.id.avchat_video_time);

        middleRoot = videoRoot.findViewById(R.id.avchat_video_middle_control);
        headImg = middleRoot.findViewById(R.id.avchat_video_head);
        nickNameTV = middleRoot.findViewById(R.id.avchat_video_nickname);
        notifyTV = middleRoot.findViewById(R.id.avchat_video_notify);

        refuse_receive = middleRoot.findViewById(R.id.avchat_video_refuse_receive);
        refuseTV = refuse_receive.findViewById(R.id.refuse);
        receiveTV = refuse_receive.findViewById(R.id.receive);
        refuseTV.setOnClickListener(this);
        receiveTV.setOnClickListener(this);

        recordView = videoRoot.findViewById(R.id.avchat_record_layout);
        recordTip = recordView.findViewById(R.id.avchat_record_tip);
        recordWarning = recordView.findViewById(R.id.avchat_record_warning);

        bottomRoot = videoRoot.findViewById(R.id.avchat_video_bottom_control);

        switchCameraToggle = new ToggleView(bottomRoot.findViewById(R.id.avchat_switch_camera), ToggleState.DISABLE, this);
        closeCameraToggle = new ToggleView(bottomRoot.findViewById(R.id.avchat_close_camera), ToggleState.DISABLE, this);
        muteToggle = new ToggleView(bottomRoot.findViewById(R.id.avchat_video_mute), ToggleState.DISABLE, this);
        recordToggle = bottomRoot.findViewById(R.id.avchat_video_record);
        recordToggle.setEnabled(false);
        recordToggle.setOnClickListener(this);
        hangUpImg = bottomRoot.findViewById(R.id.avchat_video_logout);
        hangUpImg.setOnClickListener(this);

        permissionRoot = videoRoot.findViewById(R.id.avchat_video_permission_control);
        videoInit = true;
    }

    public void onResume() {
        surfaceViewFixBefore43(smallSizePreviewLayout, largeSizePreviewLayout);
    }

    public void onDestroy() {
        if (time != null) {
            time.stop();
        }
    }

    /**
     * ********************** 视频流程 **********************
     */

    public void showIncomingCall(AVChatData avChatData) {
        this.avChatData = avChatData;
        this.account = avChatData.getAccount();

        findSurfaceView();
        findVideoViews();

        showProfile();//对方的详细信息
konghaorui committed
359
        showNotify(R.string.im_avchat_video_call_request);
konghaorui committed
360
        setRefuseReceive(true);
konghaorui committed
361
        receiveTV.setText(R.string.im_avchat_pickup);
konghaorui committed
362 363 364 365 366 367 368 369 370 371 372 373
        setTopRoot(false);
        setMiddleRoot(true);
        setBottomRoot(false);
    }

    public void doOutgoingCall(String account) {
        this.account = account;

        findSurfaceView();
        findVideoViews();

        showProfile();//对方的详细信息
konghaorui committed
374
        showNotify(R.string.im_avchat_wait_recieve);
konghaorui committed
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 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631
        setRefuseReceive(false);
        shouldEnableToggle = true;
        enableCameraToggle();   //使用音视频预览时这里可以开启切换摄像头按钮
        setTopRoot(false);
        setMiddleRoot(true);
        setBottomRoot(true);

        avChatController.doCalling(account, AVChatType.VIDEO, new AVChatControllerCallback<AVChatData>() {
            @Override
            public void onSuccess(AVChatData data) {
                avChatData = data;
                avChatController.setAvChatData(data);
                List<String> deniedPermissions = BaseMPermission.getDeniedPermissions((Activity) context, BASIC_PERMISSIONS);
                if (deniedPermissions != null && !deniedPermissions.isEmpty()) {
                    showNoneCameraPermissionView(true);
                    return;
                }
                canSwitchCamera = true;
                initLargeSurfaceView(AVChatKit.getAccount());
            }

            @Override
            public void onFailed(int code, String errorMsg) {
                closeSession();
            }
        });
    }

    public void showVideoInitLayout() {
        findSurfaceView();
        findVideoViews();

        isInSwitch = false;
        enableToggle();
        setTime(true);
        setTopRoot(true);
        setMiddleRoot(false);
        setBottomRoot(true);
        
        showNoneCameraPermissionView(false);
    }

    // 小图像surface view 初始化
    public void initSmallSurfaceView(String account) {
        smallAccount = account;
        smallSizePreviewFrameLayout.setVisibility(View.VISIBLE);

        // 设置画布,加入到自己的布局中,用于呈现视频图像
        AVChatManager.getInstance().setupLocalVideoRender(null, false, AVChatVideoScalingType.SCALE_ASPECT_BALANCED);
        AVChatManager.getInstance().setupLocalVideoRender(smallRender, false, AVChatVideoScalingType.SCALE_ASPECT_BALANCED);
        addIntoSmallSizePreviewLayout(smallRender);

        smallSizePreviewFrameLayout.bringToFront();
        localRender = smallRender;
        localPreviewInSmallSize = true;
    }

    private void addIntoSmallSizePreviewLayout(SurfaceView surfaceView) {
        smallSizePreviewCoverImg.setVisibility(View.GONE);
        if (surfaceView.getParent() != null) {
            ((ViewGroup) surfaceView.getParent()).removeView(surfaceView);
        }
        smallSizePreviewLayout.removeAllViews();
        smallSizePreviewLayout.addView(surfaceView);
        surfaceView.setZOrderMediaOverlay(true);
        smallSizePreviewLayout.setVisibility(View.VISIBLE);
    }


    // 大图像surface view 初始化
    public void initLargeSurfaceView(String account) {
        // 设置画布,加入到自己的布局中,用于呈现视频图像
        // account 要显示视频的用户帐号
        largeAccount = account;
        if (!TextUtils.isEmpty(account)&&account.equals(AVChatKit.getAccount())) {
            AVChatManager.getInstance().setupLocalVideoRender(largeRender, false, AVChatVideoScalingType.SCALE_ASPECT_BALANCED);
        } else {
            AVChatManager.getInstance().setupRemoteVideoRender(account, largeRender, false, AVChatVideoScalingType.SCALE_ASPECT_BALANCED);
        }
        addIntoLargeSizePreviewLayout(largeRender);
        remoteRender = largeRender;
    }

    private void addIntoLargeSizePreviewLayout(SurfaceView surfaceView) {
        if (surfaceView.getParent() != null) {
            ((ViewGroup) surfaceView.getParent()).removeView(surfaceView);
        }
        largeSizePreviewLayout.removeAllViews();
        largeSizePreviewLayout.addView(surfaceView);
        surfaceView.setZOrderMediaOverlay(false);
        largeSizePreviewCoverLayout.setVisibility(View.GONE);
    }

    /**
     * ******************* 音视频切换 *******************
     */

    public void onVideoToAudio() {
        isReleasedVideo = true;
        smallSizePreviewFrameLayout.setVisibility(View.INVISIBLE);
    }

    public void onAudioToVideo() {
        findVideoViews();
        findSurfaceView();

        showNotificationLayout(AUDIO_TO_VIDEO_WAIT);

        isInSwitch = true;
        setTime(true);
        setTopRoot(true);
        setMiddleRoot(false);
        setBottomRoot(true);
        

        showRecordView(avChatController.isRecording(), isRecordWarning);
    }

    public void onAudioToVideoAgree(String largeAccount) {
        showVideoInitLayout();
        account = largeAccount;

        muteToggle.toggle(AVChatManager.getInstance().isLocalAudioMuted() ? ToggleState.ON : ToggleState.OFF);
        closeCameraToggle.toggle(ToggleState.OFF);
        switchCameraToggle.off(false);
        recordToggle.setEnabled(true);
        recordToggle.setSelected(avChatController.isRecording());

        //打开视频
        isReleasedVideo = false;
        smallRender = new AVChatSurfaceViewRenderer(context);
        largeRender = new AVChatSurfaceViewRenderer(context);

        //打开视频
        AVChatManager.getInstance().enableVideo();
        AVChatManager.getInstance().startVideoPreview();

        initSmallSurfaceView(AVChatKit.getAccount());
        // 是否在发送视频 即摄像头是否开启
        if (AVChatManager.getInstance().isLocalVideoMuted()) {
            AVChatManager.getInstance().muteLocalVideo(false);
            localVideoOn();
        }

        initLargeSurfaceView(largeAccount);
        showRecordView(avChatController.isRecording(), isRecordWarning);
    }

    /********************** 界面显示 **********************************/

    // 显示个人信息
    private void showProfile() {
        headImg.loadBuddyAvatar(account);
        nickNameTV.setText(displayName);
    }

    // 显示通知
    private void showNotify(int resId) {
        notifyTV.setText(resId);
        notifyTV.setVisibility(View.VISIBLE);
    }

    private void setRefuseReceive(boolean visible) {
        refuse_receive.setVisibility(visible ? View.VISIBLE : View.GONE);
    }

    private void setTopRoot(boolean visible) {
        topRoot.setVisibility(visible ? View.VISIBLE : View.GONE);
        if (topRootHeight == 0) {
            Rect rect = new Rect();
            topRoot.getGlobalVisibleRect(rect);
            topRootHeight = rect.bottom;
        }
    }

    private void setMiddleRoot(boolean visible) {
        middleRoot.setVisibility(visible ? View.VISIBLE : View.GONE);
    }

    private void setBottomRoot(boolean visible) {
        bottomRoot.setVisibility(visible ? View.VISIBLE : View.GONE);
        if (bottomRootHeight == 0) {
            bottomRootHeight = bottomRoot.getHeight();
        }
    }

    // 底部控制开关可用
    private void enableToggle() {
        if (shouldEnableToggle) {
            if (canSwitchCamera && AVChatCameraCapturer.hasMultipleCameras()) {
                switchCameraToggle.enable();
            }
            closeCameraToggle.enable();
            muteToggle.enable();
            recordToggle.setEnabled(true);
            shouldEnableToggle = false;
        }
    }

    private void setTime(boolean visible) {
        time.setVisibility(visible ? View.VISIBLE : View.GONE);
        if (visible) {
            time.setBase(avChatController.getTimeBase());
            time.start();
        }
    }

    public void showNoneCameraPermissionView(boolean show) {
        permissionRoot.setVisibility(show ? View.VISIBLE : View.GONE);
    }

    private void enableCameraToggle() {
        if (shouldEnableToggle) {
            if (canSwitchCamera && AVChatCameraCapturer.hasMultipleCameras())
                switchCameraToggle.enable();
        }
    }

    // 摄像头切换时,布局显隐
    private void switchAndSetLayout() {
        localPreviewInSmallSize = !localPreviewInSmallSize;
        largeSizePreviewCoverLayout.setVisibility(View.GONE);
        smallSizePreviewCoverImg.setVisibility(View.GONE);
        if (isPeerVideoOff) {
            peerVideoOff();
        }
        if (isLocalVideoOff) {
            localVideoOff();
        }
    }

    /**
     * ******************** 点击事件 **********************
     */

    @Override
    public void toggleOn(View v) {
        onClick(v);
    }

    @Override
    public void toggleOff(View v) {
        onClick(v);
    }

    @Override
    public void toggleDisable(View v) {

    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.refuse) {
            doRefuseCall();
        } else if (i == R.id.receive) {
            if (isInReceiveing || avChatController.isCallEstablish.get()) {
konghaorui committed
632
                ToastUtil.toastShort(context, R.string.im_avchat_in_switch);
konghaorui committed
633 634 635 636 637 638 639 640 641 642 643 644 645 646 647
            } else {
                requestPermission();
            }
        } else if (i == R.id.avchat_video_logout) {
            doHangUp();
        } else if (i == R.id.avchat_video_mute) {
            avChatController.toggleMute();
        } else if (i == R.id.avchat_switch_camera) {
            avChatController.switchCamera();
        } else if (i == R.id.avchat_close_camera) {
            closeCamera();
        } else if (i == R.id.avchat_video_record) {
            doToggleRecord();
        } else if (i == R.id.avchat_video_switch_audio) {
            if (isInSwitch) {
konghaorui committed
648
                ToastUtil.toastShort(context, R.string.im_avchat_in_switch);
konghaorui committed
649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682
            } else {
                avChatController.switchVideoToAudio(avSwitchListener);
            }

        }
    }

    // 拒绝来电
    private void doRefuseCall() {
        avChatController.hangUp(AVChatExitCode.HANGUP);
        closeSession();
    }

    private void requestPermission() {
        new RxPermissions((Activity) this.context)
                .requestEach(Manifest.permission.RECORD_AUDIO,Manifest.permission.CAMERA)
                .subscribe(new Consumer<Permission>() {
                    @Override
                    public void accept(Permission permission) throws Exception {
                        if (permission.granted) {
                            doReceiveCall();
                        } else if (permission.shouldShowRequestPermissionRationale){
                            requestPermission();
                        }else {
                            ToastUtil.toastLong(context,"请开启相机和麦克风权限后重试");
                            DeviceTool.openPersisonSetting((Activity) AVChatVideoUI.this.context);
                            ((Activity) AVChatVideoUI.this.context).finish();
                        }
                    }
                } );
    }

    private void doReceiveCall() {
        isInReceiveing = true;
konghaorui committed
683
        showNotify(R.string.im_avchat_connecting);
konghaorui committed
684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784
        shouldEnableToggle = true;
        avChatController.receive(AVChatType.VIDEO, new AVChatControllerCallback<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                isInReceiveing = false;
                canSwitchCamera = true;
            }

            @Override
            public void onFailed(int code, String errorMsg) {
                isInReceiveing = false;
                closeSession();
            }
        });
    }

    private void doHangUp() {
        releaseVideo();
        avChatController.hangUp(AVChatExitCode.HANGUP);
        closeSession();
    }


    public void releaseVideo() {
        if (isReleasedVideo) {
            return;
        }
        isReleasedVideo = true;
        AVChatManager.getInstance().stopVideoPreview();
        AVChatManager.getInstance().disableVideo();
    }

    /**
     * ********************** 开关摄像头 **********************
     */

    private void closeCamera() {
        if (!AVChatManager.getInstance().isLocalVideoMuted()) {
            // 关闭摄像头
            AVChatManager.getInstance().muteLocalVideo(true);
            localVideoOff();
        } else {
            // 打开摄像头
            AVChatManager.getInstance().muteLocalVideo(false);
            localVideoOn();
        }
    }


    // 对方打开了摄像头
    private void localVideoOn() {
        isLocalVideoOff = false;
        if (localPreviewInSmallSize) {
            smallSizePreviewCoverImg.setVisibility(View.GONE);
        } else {
            largeSizePreviewCoverLayout.setVisibility(View.GONE);
        }
    }

    // 本地关闭了摄像头
    private void localVideoOff() {
        isLocalVideoOff = true;
        if (localPreviewInSmallSize)
            closeSmallSizePreview();
        else
            showNotificationLayout(LOCAL_CLOSE_CAMERA);
    }

    // 对方关闭了摄像头
    public void peerVideoOff() {
        isPeerVideoOff = true;
        if (localPreviewInSmallSize) { //local preview in small size layout, then peer preview should in large size layout
            showNotificationLayout(PEER_CLOSE_CAMERA);
        } else {  // peer preview in small size layout
            closeSmallSizePreview();
        }
    }

    // 对方打开了摄像头
    public void peerVideoOn() {
        isPeerVideoOff = false;
        if (localPreviewInSmallSize) {
            largeSizePreviewCoverLayout.setVisibility(View.GONE);
        } else {
            smallSizePreviewCoverImg.setVisibility(View.GONE);
        }
    }

    // 关闭小窗口
    private void closeSmallSizePreview() {
        smallSizePreviewCoverImg.setVisibility(View.VISIBLE);
    }

    // 界面提示
    private void showNotificationLayout(int closeType) {
        if (largeSizePreviewCoverLayout == null) {
            return;
        }
        TextView textView = largeSizePreviewCoverLayout;
        switch (closeType) {
            case PEER_CLOSE_CAMERA:
konghaorui committed
785
                textView.setText(R.string.im_avchat_peer_close_camera);
konghaorui committed
786 787
                break;
            case LOCAL_CLOSE_CAMERA:
konghaorui committed
788
                textView.setText(R.string.im_avchat_local_close_camera);
konghaorui committed
789 790
                break;
            case AUDIO_TO_VIDEO_WAIT:
konghaorui committed
791
                textView.setText(R.string.im_avchat_audio_to_video_wait);
konghaorui committed
792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867
                break;
            default:
                return;
        }
        largeSizePreviewCoverLayout.setVisibility(View.VISIBLE);
    }


    /**
     * ******************** 录制 ***************************
     */

    private void doToggleRecord() {
        avChatController.toggleRecord(AVChatType.VIDEO.getValue(), account, new AVChatController.RecordCallback() {
            @Override
            public void onRecordUpdate(boolean isRecording) {
                showRecordView(isRecording, isRecordWarning);
            }
        });
    }

    public void showRecordView(boolean show, boolean warning) {
        if (show) {
            recordToggle.setEnabled(true);
            recordToggle.setSelected(true);
            recordView.setVisibility(View.VISIBLE);
            recordTip.setVisibility(View.VISIBLE);
            if (warning) {
                recordWarning.setVisibility(View.VISIBLE);
            } else {
                recordWarning.setVisibility(View.GONE);
            }
        } else {
            recordToggle.setSelected(false);
            recordView.setVisibility(View.INVISIBLE);
            recordTip.setVisibility(View.INVISIBLE);
            recordWarning.setVisibility(View.GONE);
        }
    }

    public void showRecordWarning() {
        isRecordWarning = true;
        showRecordView(avChatController.isRecording(), isRecordWarning);
    }

    public void resetRecordTip() {
        isRecordWarning = false;
        avChatController.setRecording(false);
        showRecordView(false, isRecordWarning);
    }

    private void closeSession() {
        ((Activity) context).finish();
    }

    public AVChatData getAvChatData() {
        return avChatData;
    }

    private void surfaceViewFixBefore43(ViewGroup front, ViewGroup back) {
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            if (back.getChildCount() > 0) {
                View child = back.getChildAt(0);
                back.removeView(child);
                back.addView(child);
            }

            if (front.getChildCount() > 0) {
                View child = front.getChildAt(0);
                front.removeView(child);
                front.addView(child);
            }
        }
    }

}