DeviceList1078.vue 38.1 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 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 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 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 683 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 785 786 787 788 789 790 791 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 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216
<template>
  <el-container class="live-container">
    <el-aside :width="sidebarState ? '280px' : '0px'">
      <div class="sidebar-content">
        <vehicle-list
          ref="vehicleList"
          @tree-loaded="handleTreeLoaded"
          @node-click="nodeClick"
          @node-contextmenu="nodeContextmenu"
        />
      </div>
    </el-aside>

    <div
      v-show="contextMenuVisible"
      :style="{left: contextMenuLeft + 'px', top: contextMenuTop + 'px'}"
      class="custom-context-menu"
      @click.stop
    >
      <div class="menu-item" @click="handleContextCommand('playback')">
        <i class="el-icon-video-play"></i> 一键播放该设备
      </div>
      <div class="menu-item" @click="handleContextCommand('message')">
        <i class="el-icon-chat-dot-round"></i> 文本信息下发
      </div>
      <div class="menu-item" @click="handleContextCommand('intercom')">
        <i :class="(rightClickNode && rightClickNode.data && intercomTarget === rightClickNode.data.id) ? 'el-icon-microphone' : 'el-icon-phone-outline'"></i>
        {{ (rightClickNode && rightClickNode.data && intercomTarget === rightClickNode.data.id) ? '停止语音对讲' : '开启语音对讲' }}
      </div>
    </div>

    <el-container class="right-container">
      <el-header height="40px" class="player-header">
        <i :class="sidebarState ? 'el-icon-s-fold' : 'el-icon-s-unfold'"
           @click="updateSidebarState"
           class="fold-btn"
           title="折叠/展开设备列表"
        />

        <window-num-select v-model="windowNum"></window-num-select>

        <el-button type="danger" size="mini" @click="closeAllVideo">全部关闭</el-button>
        <el-button type="warning" size="mini" @click="closeVideo">关闭选中</el-button>
        <el-button type="primary" size="mini" icon="el-icon-full-screen" @click="toggleFullscreen"></el-button>

        <el-button
          :type="isCarouselRunning ? 'danger' : 'success'"
          size="mini"
          :icon="isCarouselRunning ? 'el-icon-video-pause' : 'el-icon-video-play'"
          @click="openCarouselConfig"
        >
          {{ isCarouselRunning ? '停止轮播' : '轮播设置' }}
        </el-button>

        <div v-if="isCarouselRunning" class="status-tag carousel-status">
          <template v-if="isWithinSchedule">
            <i class="el-icon-loading" style="margin-right:4px"></i>
            <span style="color: #67C23A; font-weight: bold;">轮播中</span>
            <span style="font-size: 10px; color: #909399;">(缓冲:{{channelBuffer.length}})</span>
          </template>
          <template v-else>
            <i class="el-icon-time" style="margin-right:4px"></i>
            <span style="color: #E6A23C;">等待时段</span>
          </template>
        </div>

        <div v-if="intercomTarget" class="status-tag intercom-status">
          <div class="recording-dot"></div>
          <span>正在与 [{{ intercomTargetName }}] 对讲</span>
          <el-button type="text" class="stop-btn" size="mini" @click="stopIntercom">挂断</el-button>
        </div>

        <span class="header-right-info">窗口: {{ windowClickIndex }}</span>
      </el-header>

      <carousel-config
        ref="carouselConfig"
        :device-tree-data="deviceTreeData"
        @save="startCarousel"
      ></carousel-config>

      <el-main ref="videoMain" class="player-main" @click.native="hideContextMenu">
        <player-list-component
          ref="playListComponent"
          @playerClick="handleClick"
          :video-url="videoUrl"
          :videoDataList="videoDataList"
          v-model="windowNum"
          style="width: 100%; height: 100%;"
        ></player-list-component>
      </el-main>
    </el-container>
    <el-dialog
      title="文本信息下发"
      :visible.sync="msgDialogVisible"
      width="400px"
      append-to-body
      :close-on-click-modal="false"
    >
      <div style="margin-bottom: 15px;">
        <span>下发目标:</span>
        <el-tag size="small" v-if="msgTargetNode">{{ msgTargetNode.name }}</el-tag>
      </div>

      <el-input
        type="textarea"
        v-model="msgContent"
        :rows="4"
        placeholder="请输入文本内容..."
        maxlength="50"
        show-word-limit
      ></el-input>

      <span slot="footer" class="dialog-footer">
        <el-button @click="msgDialogVisible = false" size="small">取 消</el-button>
        <el-button type="primary" @click="confirmSendMessage" size="small" :disabled="!msgContent">发 送</el-button>
      </span>
    </el-dialog>
  </el-container>
</template>

<script>
import VehicleList from "./JT1078Components/deviceList/VehicleList.vue";
import CarouselConfig from "./CarouselConfig.vue";
import WindowNumSelect from "./WindowNumSelect.vue";
import PlayerListComponent from './common/PlayerListComponent.vue';
import VideoPlayer from './common/EasyPlayer.vue';
const PCMA_TO_PCM = new Int16Array(256);
for (let i = 0; i < 256; i++) {
  let s = ~i;
  let t = ((s & 0x0f) << 3) + 8;
  let seg = (s & 0x70) >> 4;
  if (seg > 0) t = (t + 0x100) << (seg - 1);
  PCMA_TO_PCM[i] = (s & 0x80) ? -t : t;
}
export default {

  name: "live",
  components: {
    VehicleList,
    CarouselConfig,
    WindowNumSelect,
    PlayerListComponent,
    VideoPlayer
  },
  data() {
    return {
      isFullscreen: false,
      sidebarState: true,
      windowNum: '4',
      windowClickIndex: 1,
      windowClickData: null,

      // 右键菜单相关
      contextMenuVisible: false,
      contextMenuLeft: 0,
      contextMenuTop: 0,
      rightClickNode: null,

      // 播放器与轮播相关
      videoUrl: [],
      videoDataList: [],
      deviceTreeData: [],
      isCarouselRunning: false,
      isWithinSchedule: true,
      carouselConfig: null,
      carouselTimer: null,
      carouselDeviceList: [],
      channelBuffer: [],
      deviceCursor: 0,
      //文本下发相关
      msgDialogVisible: false,
      msgContent: '',
      msgTargetNode: null, // 记录当前要发送给哪辆车
      // 对讲相关
      intercomTarget: null,
      intercomTargetName: '',
      intercomSession: null,

      // 音频处理对象
      audioContext: null,      // 全局音频上下文
      audioStream: null,       // 麦克风流
      audioProcessor: null,    // 录音处理器
      audioInput: null,        // 音频输入源
      nextPlayTime: 0,         // 下一次播放的时间戳(用于平滑播放)

      flvPlayer: null,
      isTalking: false,
      // 重试定时器
      retryTimer: null,
      // 对讲音频播放器
      talkFlvPlayer: null,
      talkAudioElement: null
    };
  },
  mounted() {
    document.addEventListener('fullscreenchange', this.handleFullscreenChange);
    window.addEventListener('beforeunload', this.handleBeforeUnload);
    document.addEventListener('click', this.hideContextMenu);
  },
  beforeDestroy() {
    document.removeEventListener('fullscreenchange', this.handleFullscreenChange);
    window.removeEventListener('beforeunload', this.handleBeforeUnload);
    document.removeEventListener('click', this.hideContextMenu);
    this.stopCarousel();
    this.stopIntercom(); // 确保组件销毁时停止对讲
  },
  // 路由离开守卫
  beforeRouteLeave(to, from, next) {
    if (this.isCarouselRunning) {
      this.$confirm('轮播正在进行中,离开将停止播放,是否确认?', '提示', {
        type: 'warning'
      }).then(() => {
        this.stopCarousel();
        next();
      }).catch(() => next(false));
    } else {
      next();
    }
  },
  methods: {
    // ===========================
    // 1. 界面与基础交互
    // ===========================
    updateSidebarState() {
      this.sidebarState = !this.sidebarState;
      setTimeout(() => {
        const event = new Event('resize');
        window.dispatchEvent(event);
      }, 310);
    },
    handleTreeLoaded(data) {
      this.deviceTreeData = data;
    },
    handleClick(data, index) {
      this.windowClickIndex = index + 1;
      this.windowClickData = data;
    },
    toggleFullscreen() {
      const element = this.$refs.videoMain.$el;
      if (!this.isFullscreen) {
        if (element.requestFullscreen) element.requestFullscreen();
        else if (element.webkitRequestFullscreen) element.webkitRequestFullscreen();
      } else {
        if (document.exitFullscreen) document.exitFullscreen();
        else if (document.webkitExitFullscreen) document.webkitExitFullscreen();
      }
    },
    handleFullscreenChange() {
      this.isFullscreen = !!document.fullscreenElement;
    },

    // ===========================
    // 2. 右键菜单与指令下发
    // ===========================
    nodeContextmenu(event, data, node) {
      if (data.children && data.children.length > 0) {
        this.rightClickNode = node;
        this.contextMenuVisible = true;
        this.contextMenuLeft = event.clientX;
        this.contextMenuTop = event.clientY;
      }
    },
    hideContextMenu() {
      this.contextMenuVisible = false;
    },
    handleContextCommand(command) {
      this.hideContextMenu();
      // 安全检查
      if (!this.rightClickNode || !this.rightClickNode.data) return;
      const nodeData = this.rightClickNode.data;

      if (command === 'playback') {
        this.batchPlayback(nodeData);
      } else if (command === 'message') {
        this.openMessageDialog(nodeData);
      } else if (command === 'intercom') {
        this.toggleIntercom(nodeData);
      }
    },

    // 打开弹窗
    openMessageDialog(data) {
      this.msgTargetNode = data;   // 记录目标车辆
      this.msgContent = '';        // 清空输入框
      this.msgDialogVisible = true; // 显示自定义弹窗
    },

    // 确认发送
    confirmSendMessage() {
      if (!this.msgContent) {
        return this.$message.warning("内容不能为空");
      }
      // 调用之前的发送逻辑
      this.sendTextToDevice(this.msgTargetNode, this.msgContent);
      // 关闭弹窗
      this.msgDialogVisible = false;
    },

    sendTextToDevice(data, content) {
      const params = {
        vehicleNo: data.name,
        sim: data.sim,
        text: content
      };
      this.$axios.post('/api/external/send_text', params).then(res => {
        if (res.data.code === 200) {
          this.$message.success("指令下发成功");
        } else {
          this.$message.error(res.data.msg || "下发失败");
        }
      });
    },

    // 1. 点击对讲按钮入口
    async toggleIntercom(data) {
      // 如果点击的是当前正在对讲的车辆 -> 停止
      if (this.intercomTarget === data.id) {
        this.stopIntercom();
        return;
      }
      // 如果正在和其他车对讲 -> 提示互斥
      if (this.intercomTarget) {
        this.$message.warning(`请先挂断当前与 [${this.intercomTargetName}] 的对讲`);
        return;
      }

      // 权限预检查
      try {
        await navigator.mediaDevices.getUserMedia({ audio: true });
      } catch (err) {
        console.error("麦克风权限错误:", err);
        this.$message.error("无法获取麦克风权限,请检查浏览器设置或HTTPS环境");
        return;
      }

      // 【新增】在用户点击瞬间初始化或恢复音频播放上下文
      if (!this.audioPlayContext) {
        this.audioPlayContext = new (window.AudioContext || window.webkitAudioContext)({ sampleRate: 8000 });
      }
      if (this.audioPlayContext.state === 'suspended') {
        await this.audioPlayContext.resume();
      }
      // 开始流程
      this.startIntercom(data);
    },

    // 2. 请求后端获取网关地址
    startIntercom(data) {
      const loading = this.$loading({
        lock: true,
        text: `正在连接 [${data.name}] ...`,
        background: 'rgba(0, 0, 0, 0.7)'
      });

      this.$axios.get(`/api/jt1078/intercom/url/${data.sim}`)
        .then(res => {
          if (res.data.code === 0 || res.data.code === 200) {
            // 兼容性处理:后端返回的结构可能不同
            let wssUrl = "";
            const responseData = res.data.data;

            if (typeof responseData === 'string') {
              wssUrl = responseData;
            } else if (responseData && responseData.url) {
              wssUrl = responseData.url;
            } else if (responseData && responseData.msg) {
              // 有时候 msg 字段会被误用来放 url
              wssUrl = responseData.msg;
            }

            console.log("获取到网关地址:", wssUrl);

            if (!wssUrl || !wssUrl.startsWith('ws')) {
              loading.close();
              this.$message.error("后端返回的 WebSocket 地址无效");
              return;
            }

            this.initIntercomSession(data, wssUrl, loading);
          } else {
            loading.close();
            this.$message.error(res.data.msg || "获取对讲地址失败");
          }
        })
        .catch(err => {
          loading.close();
          console.error(err);
          this.$message.error("请求超时或网络异常");
        });
    },

    // 3. 初始化 WebSocket (信令交互)
    initIntercomSession(data, url, loadingInstance) {
      try {
        const socket = new WebSocket(url);
        // 【关键】使用默认文本模式发送 JSON,不要设置 binaryType

        socket.onopen = () => {
          this.intercomTarget = data.id;
          this.intercomTargetName = data.name;
          this.intercomSession = socket;
          this.currentIntercomSim = data.sim.toString().padStart(12, '0');
          this.isTalking = true;

          // A. 发送注册包 (必须先发这个,网关才认)
          const registerMsg = { type: 'register', stream_id: this.currentIntercomSim };
          socket.send(JSON.stringify(registerMsg));

          // B. 先启动播放器 (下行 - 收听),等待连接成功后再启动麦克风
          // 使用 nextTick 确保 DOM 元素已经渲染
          this.$nextTick(() => {
            this.playTalkAudioStream(this.currentIntercomSim, loadingInstance);
          });
        };

        socket.onmessage = (event) => {
          // 该网关下行通常不走 WebSocket,这里只打印信令日志
          try {
            const msg = JSON.parse(event.data);
            if(msg.type === 'registered') console.log("网关注册确认成功");
          } catch(e) {}
        };

        socket.onerror = (e) => {
          loadingInstance.close();
          console.error("WS Error", e);
          this.stopIntercom();
          this.$message.error("对讲连接中断");
        };

        socket.onclose = () => {
          if (this.isTalking) {
            console.warn("WebSocket 意外断开");
            this.stopIntercom();
          }
        };

      } catch (e) {
        loadingInstance.close();
        this.$message.error("初始化失败: " + e.message);
      }
    },

    // 4. 采集麦克风 -> 降采样 -> 发送 (上行核心)
    // 启动音频采集 (上行)
    async startAudioCapture(sim) {
      try {
        const stream = await navigator.mediaDevices.getUserMedia({
          audio: {
            channelCount: 1,
            echoCancellation: true,
            noiseSuppression: true,
            autoGainControl: true
          }
        });
        this.audioStream = stream;

        const AudioContext = window.AudioContext || window.webkitAudioContext;
        this.audioContext = new AudioContext();
        // 获取浏览器真实的采样率 (例如 48000 或 44100)
        const sourceSampleRate = this.audioContext.sampleRate;
        console.log("麦克风真实采样率:", sourceSampleRate);

        const source = this.audioContext.createMediaStreamSource(stream);
        const gainNode = this.audioContext.createGain();
        gainNode.gain.value = 2.0; // 音量适度放大(从5.0降低到2.0)

        // 使用 ScriptProcessor(较小的缓冲区以减少延迟)
        this.audioProcessor = this.audioContext.createScriptProcessor(2048, 1, 1);

        this.audioProcessor.onaudioprocess = (e) => {
          if (!this.intercomSession || this.intercomSession.readyState !== WebSocket.OPEN) return;

          // 1. 获取原始数据 (Float32, 48000Hz)
          const inputBuffer = e.inputBuffer.getChannelData(0);

          // 2. 【核心修复】强制降采样到 8000Hz + 转 PCM16
          // 这一步解决了 "声音杂乱" 和 "格式不支持" 的问题
          const pcm16Buffer = this.downsampleBuffer(inputBuffer, sourceSampleRate, 8000);

          // 3. 【核心修复】防止发送空数据
          if (pcm16Buffer.byteLength === 0) {
            return;
          }

          // 4. 转 Base64
          const base64Str = this.arrayBufferToBase64(pcm16Buffer);

          // 5. 【核心修复】防止 Base64 为空
          if (!base64Str) {
            return;
          }

          // 6. 发送数据 (注意 sample_rate 必须是 8000)
          const msg = {
            type: 'audio_data',
            stream_id: sim,
            audio_data: base64Str,
            format: 'pcm16',
            sample_rate: 8000, // 必须告诉网关这是 8k 数据
            channels: 1
          };

          this.intercomSession.send(JSON.stringify(msg));
        };

        source.connect(gainNode);
        gainNode.connect(this.audioProcessor);
        this.audioProcessor.connect(this.audioContext.destination);

      } catch (err) {
        console.error("麦克风启动错误", err);
        this.$message.error("麦克风启动失败");
        this.stopIntercom();
      }
    },

    playTalkAudioStream(sim, loadingInstance) {
      const paddedSim = sim.toString().padStart(12, '0');
      const flvUrl = `ws://127.0.0.1:80/schedule/${paddedSim}_voice.live.flv?callId=41db35390ddad33f83944f44b8b75ded`;

      // 创建隐藏的audio元素用于播放
      if (!this.talkAudioElement) {
        this.talkAudioElement = document.createElement('audio');
        this.talkAudioElement.autoplay = true;
        this.talkAudioElement.controls = false;
        this.talkAudioElement.volume = 1.0;
      }

      // 使用flv.js播放音频流
      if (window.flvjs && window.flvjs.isSupported()) {
        try {
          // 销毁旧的播放器
          if (this.talkFlvPlayer) {
            this.talkFlvPlayer.pause();
            this.talkFlvPlayer.unload();
            this.talkFlvPlayer.detachMediaElement();
            this.talkFlvPlayer.destroy();
            this.talkFlvPlayer = null;
          }

          this.talkFlvPlayer = window.flvjs.createPlayer({
            type: 'flv',
            url: flvUrl,
            isLive: true,
            hasAudio: true,
            hasVideo: false
          }, {
            enableWorker: true,
            enableStashBuffer: true,
            stashInitialSize: 384,
            autoCleanupSourceBuffer: true,
            autoCleanupMaxBackwardDuration: 3,
            autoCleanupMinBackwardDuration: 2,
            fixAudioTimestampGap: true,
            liveBufferLatencyChasing: true,
            liveBufferLatencyChasingOnPaused: false,
            liveBufferLatencyMaxLatency: 3,
            liveBufferLatencyMinRemain: 0.8
          });

          // 监听播放器错误事件
          this.talkFlvPlayer.on(window.flvjs.Events.ERROR, (errorType, errorDetail, errorInfo) => {
            console.error('FLV播放器错误:', errorType, errorDetail, errorInfo);
            if (loadingInstance) {
              loadingInstance.close();
            }
            this.$message.error('连接ZLM音频流失败,对讲已终止');
            // 连接失败,停止对讲
            this.stopIntercom();
          });

          // 监听加载成功事件 - 只有在这里才启动麦克风
          this.talkFlvPlayer.on(window.flvjs.Events.MEDIA_INFO, () => {
            console.log('ZLM音频流连接成功,开始启动麦克风');
            if (loadingInstance) {
              loadingInstance.close();
            }
            // 连接成功后才启动麦克风采集
            this.startAudioCapture(this.currentIntercomSim);
            this.$message.success("对讲通道已建立,可以开始说话");
          });

          this.talkFlvPlayer.attachMediaElement(this.talkAudioElement);
          this.talkFlvPlayer.load();
          this.talkFlvPlayer.play().catch(err => {
            console.error('播放音频失败:', err);
            if (loadingInstance) {
              loadingInstance.close();
            }
            this.$message.error('播放音频失败,对讲已终止');
            // 播放失败,停止对讲
            this.stopIntercom();
          });

          console.log('对讲音频播放器已启动,等待连接ZLM...');
        } catch (e) {
          console.error('创建FLV播放器失败:', e);
          if (loadingInstance) {
            loadingInstance.close();
          }
          this.$message.error('创建音频播放器失败,对讲已终止');
          // 创建失败,停止对讲
          this.stopIntercom();
        }
      } else {
        console.error('浏览器不支持flv.js');
        if (loadingInstance) {
          loadingInstance.close();
        }
        this.$message.error('浏览器不支持FLV播放,对讲已终止');
        // 不支持,停止对讲
        this.stopIntercom();
      }
    },

    // 辅助:彻底销毁播放器
    destroyFlvPlayer() {
      if (this.retryTimer) {
        clearInterval(this.retryTimer);
        clearTimeout(this.retryTimer); // 兼容 setTimeout
        this.retryTimer = null;
      }

      if (this.flvPlayer) {
        try {
          this.flvPlayer.pause();
          this.flvPlayer.unload();
          this.flvPlayer.detachMediaElement();
          this.flvPlayer.destroy();
        } catch (e) {}
        this.flvPlayer = null;
      }
    },

    // 6. 停止对讲
    stopIntercom() {
      console.log("正在停止对讲流程...");

      // A. 通知后端停止
      if (this.currentIntercomSim) {
        this.$axios.post(`/api/jt1078/intercom/stop/${this.currentIntercomSim}`).catch(()=>{});
      }

      this.isTalking = false;

      // B. 停止对讲音频播放器
      if (this.talkFlvPlayer) {
        try {
          this.talkFlvPlayer.pause();
          this.talkFlvPlayer.unload();
          this.talkFlvPlayer.detachMediaElement();
          this.talkFlvPlayer.destroy();
        } catch (e) {
          console.error('销毁对讲播放器失败:', e);
        }
        this.talkFlvPlayer = null;
      }

      if (this.talkAudioElement) {
        try {
          this.talkAudioElement.pause();
          this.talkAudioElement.src = '';
        } catch (e) {}
      }

      // C. 关闭WebSocket连接
      if (this.audioSocket) {
        this.audioSocket.close();
        this.audioSocket = null;
      }
      if (this.audioPlayContext) {
        this.audioPlayContext.close().then(() => {
          console.log("播放器上下文已释放");
        });
        this.audioPlayContext = null;
      }

      // D. 停止上行采集 (喊话)
      if (this.audioStream) {
        this.audioStream.getTracks().forEach(track => track.stop());
        this.audioStream = null;
      }
      if (this.audioProcessor) {
        this.audioProcessor.disconnect();
        this.audioProcessor = null;
      }
      if (this.audioContext) {
        this.audioContext.close();
        this.audioContext = null;
      }

      // E. 关闭与Python的WebSocket信令连接(intercomSession)
      if (this.intercomSession) {
        try {
          this.intercomSession.send(JSON.stringify({ type: 'close_talk' }));
          console.log("已发送关闭信令到Python WebSocket");
        } catch(e){
          console.error("发送关闭信令失败:", e);
        }
        try {
          this.intercomSession.close();
          console.log("Python WebSocket连接已关闭");
        } catch(e) {
          console.error("关闭Python WebSocket失败:", e);
        }
        this.intercomSession = null;
      }

      // F. 重置状态
      this.intercomTarget = null;
      this.intercomTargetName = '';
      this.currentIntercomSim = null;
      this.$message.info("对讲已挂断");
    },

    // 工具:降采样 (Float32 -> Int16)
    downsampleBuffer(buffer, sampleRate, outSampleRate) {
      if (outSampleRate === sampleRate) {
        return this.floatTo16BitPCM(buffer);
      }

      const sampleRateRatio = sampleRate / outSampleRate;
      const newLength = Math.round(buffer.length / sampleRateRatio);

      // 如果计算出的长度无效,返回空 buffer
      if (newLength <= 0) return new ArrayBuffer(0);

      const result = new Int16Array(newLength);
      let offsetResult = 0;
      let offsetBuffer = 0;

      while (offsetResult < newLength) {
        const nextOffsetBuffer = Math.round((offsetResult + 1) * sampleRateRatio);

        let accum = 0, count = 0;
        // 简单的均值算法,防止声音有毛刺
        for (let i = offsetBuffer; i < nextOffsetBuffer && i < buffer.length; i++) {
          accum += buffer[i];
          count++;
        }

        if (count > 0) {
          let s = accum / count;
          // 可以在这里再次放大音量
          // s = s * 2.0;
          s = Math.max(-1, Math.min(1, s));
          result[offsetResult] = s < 0 ? s * 0x8000 : s * 0x7FFF;
        } else {
          result[offsetResult] = 0;
        }

        offsetResult++;
        offsetBuffer = nextOffsetBuffer;
      }
      return result.buffer;
    },

    // 工具: Float32 -> Int16 (保留备用)
    floatTo16BitPCM(input) {
      let output = new Int16Array(input.length);
      for (let i = 0; i < input.length; i++) {
        let s = Math.max(-1, Math.min(1, input[i]));
        output[i] = s < 0 ? s * 0x8000 : s * 0x7FFF;
      }
      return output;
    },

    // 工具:Base64 转换 (必须处理 .buffer)
    arrayBufferToBase64(buffer) {
      let binary = '';
      // 注意:buffer 可能是 ArrayBuffer,需要转 Uint8Array 才能读取
      const bytes = new Uint8Array(buffer);
      const len = bytes.byteLength;

      if (len === 0) return ""; // 此时返回空字符串

      for (let i = 0; i < len; i++) {
        binary += String.fromCharCode(bytes[i]);
      }
      return window.btoa(binary);
    },

    // ===========================
    // 3. 播放逻辑 (单路/批量)
    // ===========================
    nodeClick(data, node) {
      if (this.isCarouselRunning) {
        this.$message.warning("请先停止轮播再手动播放");
        return;
      }
      if (!data.children || data.children.length === 0) {
        this.playSingleChannel(data);
      }
    },

    playSingleChannel(data) {
      let stream = data.code.replace('-', '_');
      let arr = stream.split("_");
      if (arr.length < 3) {
        console.warn("Invalid channel code:", data.code);
        return;
      }
      this.$axios.get(`/api/jt1078/query/send/request/io/${arr[1]}/${arr[2]}`).then(res => {
        if (res.data.code === 0 || res.data.code === 200) {
          const url = (location.protocol === "https:") ? res.data.data.wss_flv : res.data.data.ws_flv;
          const idx = this.windowClickIndex - 1;
          this.$set(this.videoUrl, idx, url);
          this.$set(this.videoDataList, idx, {...data, videoUrl: url});
          const maxWindow = parseInt(this.windowNum) || 4;
          this.windowClickIndex = (this.windowClickIndex % maxWindow) + 1;
        } else {
          this.$message.error(res.data.msg || "获取视频流失败");
        }
      }).catch(err => {
        this.$message.error("请求播放地址异常");
      });
    },

    batchPlayback(nodeData) {
      if (this.isCarouselRunning) return this.$message.warning("轮播中无法操作");
      const channels = nodeData.children;
      if (channels && channels.length > 0) {
        this.videoUrl = [];
        this.videoDataList = [];
        if (channels.length > 16) this.windowNum = '25';
        else if (channels.length > 9) this.windowNum = '16';
        else if (channels.length > 4) this.windowNum = '9';
        else this.windowNum = '4';

        const ids = channels.map(c => {
          const parts = c.code.replaceAll('_', '-').split('-');
          return parts.slice(1).join('-');
        });

        this.$axios.post('/api/jt1078/query/beachSend/request/io', ids).then(res => {
          if (res.data && res.data.data) {
            const list = res.data.data || [];
            list.forEach((item, i) => {
              if (channels[i]) {
                this.$set(this.videoUrl, i, item.ws_flv);
                this.$set(this.videoDataList, i, { ...channels[i], videoUrl: item.ws_flv });
              }
            });
          } else {
            this.$message.warning("批量获取流地址为空");
          }
        }).catch(e => {
          this.$message.error("批量播放失败");
        });
      } else {
        this.$message.warning("该设备下没有通道");
      }
    },

    // ===========================
    // 4. 关闭视频逻辑
    // ===========================
    async checkCarouselPermission(actionName) {
      if (!this.isCarouselRunning) return true;
      try {
        await this.$confirm(`正在轮播,"${actionName}"将停止轮播,是否继续?`, '提示', {type: 'warning'});
        this.stopCarousel();
        return true;
      } catch (e) { return false; }
    },

    async closeAllVideo() {
      if (!(await this.checkCarouselPermission('关闭所有视频'))) return;
      this.closeAllVideoNoConfirm();
    },

    async closeVideo() {
      if (!(await this.checkCarouselPermission('关闭当前窗口'))) return;
      const idx = Number(this.windowClickIndex) - 1;
      if (this.videoUrl && this.videoUrl[idx]) {
        this.$confirm(`确认关闭窗口 [${this.windowClickIndex}] ?`, '提示', {type: 'warning'})
          .then(() => {
            this.$set(this.videoUrl, idx, null);
            this.$set(this.videoDataList, idx, null);
          }).catch(()=>{});
      }
    },

    closeAllVideoNoConfirm() {
      this.videoUrl = new Array(parseInt(this.windowNum)).fill(null);
      this.videoDataList = new Array(parseInt(this.windowNum)).fill(null);
    },

    // ===========================
    // 5. 轮播逻辑
    // ===========================
    openCarouselConfig() {
      if (this.isCarouselRunning) {
        this.$confirm('确定要停止轮播吗?', '提示').then(() => this.stopCarousel());
      } else {
        this.$refs.carouselConfig.open(this.carouselConfig);
      }
    },

    stopCarousel() {
      this.isCarouselRunning = false;
      if (this.carouselTimer) {
        clearTimeout(this.carouselTimer);
        this.carouselTimer = null;
      }
      this.$message.info("轮播已停止");
    },

    async startCarousel(config) {
      this.carouselConfig = config;
      // 1. 筛选目标设备
      let targetNodes = [];
      if (config.sourceType === 'all_online') {
        const collectOnline = (nodes) => {
          nodes.forEach(node => {
            if (node.abnormalStatus === 1) targetNodes.push(node);
            if (node.children && node.children.length > 0) collectOnline(node.children);
          });
        };
        collectOnline(this.deviceTreeData);
      } else {
        targetNodes = config.selectedNodes.filter(n => n.abnormalStatus === 1);
      }

      if (targetNodes.length === 0) {
        this.$message.warning("当前范围内没有在线设备可供轮播");
        return;
      }

      // 2. 初始化状态
      this.carouselDeviceList = targetNodes;
      this.channelBuffer = [];
      this.deviceCursor = 0;
      this.isCarouselRunning = true;
      this.isWithinSchedule = true;

      this.$message.success(`轮播已启动,共 ${targetNodes.length} 台在线设备`);
      await this.executeFirstRound();
    },

    async executeFirstRound() {
      if (this.windowNum !== this.carouselConfig.layout) {
        this.windowNum = this.carouselConfig.layout;
      }
      const batch = await this.fetchNextBatchData();
      if (batch) {
        this.applyVideoBatch(batch);
        this.runCarouselLoop();
      } else {
        this.$message.error("首轮加载失败,尝试重试...");
        this.runCarouselLoop();
      }
    },

    runCarouselLoop() {
      if (!this.isCarouselRunning) return;
      const {runMode, timeRange, interval} = this.carouselConfig;

      // 1. 检查定时
      if (runMode === 'schedule') {
        if (!this.checkTimeRange(timeRange[0], timeRange[1])) {
          this.isWithinSchedule = false;
          if (this.videoUrl.some(v => v)) this.closeAllVideoNoConfirm();
          this.carouselTimer = setTimeout(() => this.runCarouselLoop(), 10000);
          return;
        }
        this.isWithinSchedule = true;
      }

      // 2. 计算时间轴
      const PRELOAD_TIME = 15;
      const intervalSec = Math.max(interval, 30);
      const waitTime = (intervalSec - PRELOAD_TIME) * 1000;

      // 3. 计时循环
      this.carouselTimer = setTimeout(async () => {
        if (!this.isCarouselRunning) return;
        const nextBatch = await this.fetchNextBatchData();

        this.carouselTimer = setTimeout(() => {
          if (!this.isCarouselRunning) return;
          if (nextBatch) this.applyVideoBatch(nextBatch);
          this.runCarouselLoop();
        }, PRELOAD_TIME * 1000);

      }, waitTime);
    },

    applyVideoBatch({urls, infos}) {
      this.videoUrl = new Array(parseInt(this.windowNum)).fill(null);
      setTimeout(() => {
        urls.forEach((url, index) => {
          setTimeout(() => {
            this.$set(this.videoUrl, index, url);
            this.$set(this.videoDataList, index, infos[index]);
          }, index * 100);
        });
      }, 200);
    },

    async fetchNextBatchData() {
      let pageSize = parseInt(this.windowNum) || 4;
      if (isNaN(pageSize)) pageSize = 4;
      let safetyCounter = 0;
      while (this.channelBuffer.length < pageSize && safetyCounter < 100) {
        safetyCounter++;
        if (this.deviceCursor >= this.carouselDeviceList.length) this.deviceCursor = 0;

        const device = this.carouselDeviceList[this.deviceCursor];
        if (device && device.children && device.children.length > 0) {
          const codes = device.children
            .filter(child => !child.disabled)
            .map(child => child.code);
          this.channelBuffer.push(...codes);
        }
        this.deviceCursor++;
      }

      if (this.channelBuffer.length === 0) return null;

      const currentCodes = this.channelBuffer.splice(0, pageSize);
      const streamParams = currentCodes.map(c => c.replaceAll('_', '-').split('-').slice(1).join('-'));

      try {
        const res = await this.$axios.post('/api/jt1078/query/beachSend/request/io', streamParams, {timeout: 20000});
        if (res.data && res.data.data) {
          const resultList = res.data.data;
          const urls = new Array(pageSize).fill('');
          const infos = new Array(pageSize).fill(null);

          resultList.forEach((item, i) => {
            if (i < currentCodes.length) {
              const url = (location.protocol === "https:") ? item.wss_flv : item.ws_flv;
              urls[i] = url;
              infos[i] = {
                code: currentCodes[i],
                name: `通道 ${i + 1}`,
                videoUrl: url
              };
            }
          });
          return {urls, infos};
        }
      } catch (e) {
        console.error("批量请求流地址失败", e);
      }
      return null;
    },

    checkTimeRange(startStr, endStr) {
      if (!startStr || !endStr) return true;
      const now = new Date();
      const current = now.getHours() * 3600 + now.getMinutes() * 60 + now.getSeconds();
      const parse = (str) => {
        const [h, m, s] = str.split(':').map(Number);
        return h * 3600 + m * 60 + s;
      };
      const start = parse(startStr);
      const end = parse(endStr);
      if (end < start) return current >= start || current <= end;
      return current >= start && current <= end;
    },

    handleBeforeUnload(e) {
      if (this.isCarouselRunning) {
        e.preventDefault();
        e.returnValue = '';
      }
      this.stopIntercom();
    },
  }
};
</script>

<style scoped>
.live-container {
  height: 100%;
  width: 100%;
  overflow: hidden;
}

.el-aside {
  background-color: #fff;
  color: #333;
  text-align: center;
  height: 100%;
  overflow: hidden;
  border-right: 1px solid #dcdfe6;
  transition: width 0.3s ease-in-out;
}

.sidebar-content {
  width: 280px;
  height: 100%;
  padding: 10px;
  box-sizing: border-box;
}

.right-container {
  height: 100%;
  display: flex;
  flex-direction: column;
}

/* Header 样式 */
.player-header {
  background-color: #e9eef3;
  color: #333;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  gap: 10px;
  padding: 0 15px;
  border-bottom: 1px solid #dcdfe6;
  box-sizing: border-box;
  overflow: hidden; /* 防止内容过多撑开 */
}

.fold-btn {
  font-size: 20px;
  margin-right: 5px;
  cursor: pointer;
  color: #606266;
}
.fold-btn:hover { color: #409EFF; }

.header-right-info {
  margin-left: auto;
  font-weight: bold;
  font-size: 14px;
  color: #606266;
  white-space: nowrap;
}

.player-main {
  background-color: #000;
  padding: 0 !important;
  margin: 0;
  overflow: hidden;
  flex: 1;
}

/* 右键菜单 */
.custom-context-menu {
  position: fixed;
  background: #fff;
  border: 1px solid #EBEEF5;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);
  z-index: 3000;
  border-radius: 4px;
  padding: 5px 0;
  min-width: 120px;
}
.menu-item {
  padding: 8px 15px;
  font-size: 14px;
  color: #606266;
  cursor: pointer;
}
.menu-item:hover { background: #ecf5ff; color: #409EFF; }

/* 状态标签通用样式 */
.status-tag {
  font-size: 12px;
  display: flex;
  align-items: center;
  background: #fff;
  padding: 2px 10px;
  border-radius: 12px;
  border: 1px solid #dcdfe6;
  white-space: nowrap;
}

/* 轮播状态 */
.carousel-status {
  margin-left: 10px;
}

/* 对讲状态 */
.intercom-status {
  background-color: #fef0f0;
  color: #f56c6c;
  border: 1px solid #fde2e2;
  margin-left: 10px;
  animation: slideIn 0.3s ease;
}

.recording-dot {
  width: 8px;
  height: 8px;
  background-color: #f56c6c;
  border-radius: 50%;
  margin-right: 8px;
  animation: breathe 1s infinite;
}

.stop-btn {
  margin-left: 8px;
  color: #f56c6c;
  font-weight: bold;
  padding: 0;
}

@keyframes breathe {
  0% { opacity: 1; transform: scale(1); }
  50% { opacity: 0.5; transform: scale(1.2); }
  100% { opacity: 1; transform: scale(1); }
}

@keyframes slideIn {
  from { opacity: 0; transform: translateY(-10px); }
  to { opacity: 1; transform: translateY(0); }
}
</style>