useCamera.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. import { defHttp } from '/@/utils/http/axios';
  2. // import { render, h, nextTick } from 'vue';
  3. // import LivePlayer from '@liveqing/liveplayer-v3';
  4. import { useDrag } from '../event/useDrag';
  5. import Player, { I18N } from 'xgplayer';
  6. import HlsPlugin from 'xgplayer-hls';
  7. import FlvPlugin from 'xgplayer-flv';
  8. import 'xgplayer/dist/index.min.css';
  9. import ZH from 'xgplayer/es/lang/zh-cn';
  10. I18N.use(ZH);
  11. export function useCamera() {
  12. const cameraList = (params) => defHttp.get({ url: '/safety/ventanalyCamera/list', params });
  13. const cameraAddrList = (params) => defHttp.post({ url: '/monitor/camera/info', params });
  14. const cameraAddr = (params) => defHttp.get({ url: '/monitor/camera/queryByCameraCode', params });
  15. let webRtcServer = <any[]>[];
  16. const playerList = <any[]>[];
  17. const playerDoms = <(HTMLVideoElement | undefined | null)[]>[];
  18. const videoParentDomList: (HTMLElement | [string, { name: string; addr: string; cameraRate: number; devicekind: string }])[] = [];
  19. async function getCamera(deviceid, parentPlayerDom?, devKind?) {
  20. removeCamera();
  21. if (!parentPlayerDom) {
  22. parentPlayerDom = document.createElement('div');
  23. parentPlayerDom.setAttribute('style', `top:0px; left: 0px; width: 100%; height: 100%; position: fixed; z-index: 999;`);
  24. }
  25. let res;
  26. if (!devKind) {
  27. res = await cameraList({ deviceid });
  28. } else {
  29. res = await cameraList({ sysId: deviceid, devKind });
  30. }
  31. const cameras: [] = res.records || [];
  32. // const cameras: [] = [
  33. // {
  34. // name: '1111',
  35. // devicekind: 'toHKRtsp',
  36. // },
  37. // {
  38. // name: '2222',
  39. // devicekind: 'toHKRtsp',
  40. // },
  41. // // {
  42. // // name: '3333',
  43. // // devicekind: 'toHKRtsp',
  44. // // },
  45. // // {
  46. // // name: '4444',
  47. // // devicekind: 'toHKRtsp',
  48. // // },
  49. // ];
  50. const cameraAddrs: any[] = [],
  51. cameraNames: any[] = [];
  52. if (cameras.length > 0) {
  53. for (let i = 0; i < cameras.length; i++) {
  54. const item = cameras[i];
  55. if (item['devicekind'] === 'toHKRtsp' || item['devicekind'] === 'toHKHLs') {
  56. // 从海康平台接口获取视频流
  57. const videoType = item['devicekind'] === 'toHKRtsp' ? 'rtsp' : '';
  58. try {
  59. const data = await cameraAddr({ cameraCode: item['addr'], videoType });
  60. if (data && data['url']) {
  61. cameraAddrs.push({ name: item['name'], addr: data['url'], cameraRate: item['cameraRate'], devicekind: item['devicekind'] });
  62. }
  63. // // 从海康平台接口获取视频流测试
  64. // cameraAddrs.push({
  65. // name: item['name'],
  66. // addr: 'https://demo.unified-streaming.com/k8s/features/stable/video/tears-of-steel/tears-of-steel.mp4/.m3u8',
  67. // });
  68. } catch (error) {}
  69. } else if (item['devicekind'] == 'toHKR') {
  70. cameraNames.push({ name: item['name'], cameraRate: item['cameraRate'] });
  71. } else {
  72. cameraAddrs.push({ name: item['name'], addr: item['addr'], cameraRate: item['cameraRate'], devicekind: item['devicekind'] });
  73. }
  74. }
  75. }
  76. if (cameraNames.length > 0) {
  77. // 请求接口从装备院拿数据
  78. const cameraNameList = cameraNames.map((item) => item.name);
  79. const addrs: string[] = await cameraAddrList({ cameraNameList: cameraNameList });
  80. for (let i = 0; i < addrs.length; i++) {
  81. cameraAddrs.push({ name: '摄像头' + i, addr: addrs[i] });
  82. }
  83. }
  84. await deviceCameraInit(cameraAddrs, parentPlayerDom);
  85. }
  86. function deviceCameraInit(cameraAddrs, player: HTMLElement) {
  87. const newWebRtcServer = [];
  88. let livePlayerDiv: HTMLElement | null = document.getElementById('LivePlayerBox');
  89. if (livePlayerDiv) {
  90. livePlayerDiv.remove();
  91. livePlayerDiv = null;
  92. }
  93. if (!livePlayerDiv) {
  94. const dom = document.createElement('div');
  95. dom.setAttribute('id', 'LivePlayerBox');
  96. livePlayerDiv = dom;
  97. player.appendChild(livePlayerDiv);
  98. }
  99. return new Promise((resolve) => {
  100. const playCamrea = () => {
  101. if (cameraAddrs.length > 0) {
  102. const promiseList: Promise<any>[] = [];
  103. debugger;
  104. cameraAddrs.forEach(async (cameraUrl: { name: string; addr: string; cameraRate: number; devicekind: string }, index) => {
  105. const promise = new Promise(async (childResolve) => {
  106. let cameraNameDom: null | HTMLElement = null;
  107. console.log('摄像头地址--------->', cameraUrl, cameraUrl.addr.startsWith('rtsp://'), livePlayerDiv);
  108. if (cameraUrl.addr.includes('0.0.0.0')) {
  109. cameraUrl.addr = cameraUrl.addr.replace('0.0.0.0', window.location.hostname);
  110. }
  111. if (cameraUrl.addr && cameraUrl.addr.startsWith('rtsp://')) {
  112. const server = webRtcServer?.shift();
  113. let videoDom: HTMLVideoElement | null = null;
  114. if (server) {
  115. try {
  116. videoDom = server.videoElement as HTMLVideoElement;
  117. videoDom.volume = 0;
  118. const cameraNameDom = videoDom.parentElement?.getElementsByClassName('video-name')[0];
  119. if (cameraNameDom) cameraNameDom.innerText = cameraUrl.name;
  120. playerDoms.unshift(videoDom);
  121. newWebRtcServer.unshift(server);
  122. // videoParentDomList.unshift()
  123. await server.connect(cameraUrl['addr']);
  124. videoDom.play();
  125. childResolve(null);
  126. } catch (error) {
  127. playerDoms.unshift(undefined);
  128. childResolve(null);
  129. }
  130. } else {
  131. videoDom = document.createElement('video');
  132. videoDom.volume = 0;
  133. videoDom.setAttribute('class', 'rtspVideo');
  134. videoDom.setAttribute('muted', 'muted');
  135. videoDom.setAttribute('poster', '/src/assets/images/vent/noSinge.png');
  136. videoDom.autoplay = true;
  137. try {
  138. const server = new window['WebRtcStreamer'](
  139. videoDom,
  140. VUE_APP_URL.webRtcUrl.startsWith('/') ? location.protocol + VUE_APP_URL.webRtcUrl : VUE_APP_URL.webRtcUrl
  141. );
  142. newWebRtcServer.unshift(server);
  143. await server.connect(cameraUrl.addr);
  144. videoDom.play();
  145. playerDoms.unshift(videoDom);
  146. childResolve(null);
  147. } catch (error) {
  148. console.log('WebRtcStreamer 抛出异常!!!!!!');
  149. playerDoms.unshift(null);
  150. childResolve(null);
  151. }
  152. }
  153. if (videoDom) {
  154. const videoParentDom: HTMLElement = document.createElement('div');
  155. videoParentDom.setAttribute('class', 'video-parent');
  156. videoParentDom.appendChild(videoDom);
  157. cameraNameDom = document.createElement('div');
  158. cameraNameDom.setAttribute('class', 'video-name');
  159. cameraNameDom.innerText = cameraUrl.name;
  160. videoParentDom.appendChild(cameraNameDom);
  161. videoParentDom.addEventListener('dblclick', () => {
  162. if (videoDom?.requestFullscreen) {
  163. videoDom.requestFullscreen();
  164. videoDom.play();
  165. }
  166. });
  167. videoParentDomList.push(videoParentDom);
  168. }
  169. } else {
  170. videoParentDomList.push(['player' + index, cameraUrl]);
  171. childResolve(null);
  172. }
  173. });
  174. promiseList.push(promise);
  175. });
  176. Promise.all(promiseList).then(() => {
  177. resolve(null);
  178. });
  179. } else {
  180. resolve(null);
  181. }
  182. };
  183. playCamrea();
  184. }).then(() => {
  185. videoParentDomList.forEach((videoParent) => {
  186. if (typeof videoParent[0] === 'string' && livePlayerDiv) {
  187. const videoParentDom: HTMLElement = document.createElement('div');
  188. videoParentDom.setAttribute('class', 'liveVideo');
  189. livePlayerDiv?.appendChild(videoParentDom);
  190. useDrag(videoParentDom);
  191. const videoDom: HTMLElement = document.createElement('div');
  192. videoDom.setAttribute('id', videoParent[0]);
  193. videoParentDom.appendChild(videoDom);
  194. if (videoParent[1] && videoParent[1].addr) {
  195. const fileExtension = videoParent[1].addr.split('.').pop();
  196. let player;
  197. if (fileExtension === 'flv' || videoParent[1].devicekind == 'flv') {
  198. player = new Player({
  199. lang: 'zh',
  200. id: videoParent[0],
  201. url: videoParent[1].addr,
  202. width: 294,
  203. height: 188,
  204. poster: '/src/assets/images/vent/noSinge.png',
  205. plugins: [FlvPlugin],
  206. fluid: true,
  207. autoplay: true,
  208. isLive: true,
  209. playsinline: true,
  210. screenShot: true,
  211. whitelist: [''],
  212. ignores: ['time', 'progress', 'play', 'i18n', 'volume', 'fullscreen', 'screenShot', 'playbackRate'],
  213. closeVideoClick: true,
  214. customConfig: {
  215. isClickPlayBack: false,
  216. },
  217. controlsList: ['nodownload', 'nofullscreen', 'noremoteplayback'],
  218. defaultPlaybackRate: videoParent[1].cameraRate || 1,
  219. flv: {
  220. retryCount: 3, // 重试 3 次,默认值
  221. retryDelay: 1000, // 每次重试间隔 1 秒,默认值
  222. loadTimeout: 10000, // 请求超时时间为 10 秒,默认值
  223. fetchOptions: {
  224. // 该参数会透传给 fetch,默认值为 undefined
  225. mode: 'cors',
  226. },
  227. targetLatency: 10, // 直播目标延迟,默认 10 秒
  228. maxLatency: 20, // 直播允许的最大延迟,默认 20 秒
  229. disconnectTime: 10, // 直播断流时间,默认 0 秒,(独立使用时等于 maxLatency)
  230. maxJumpDistance: 10,
  231. },
  232. });
  233. playerList.push(player);
  234. }
  235. if (fileExtension === 'm3u8' || videoParent[1].devicekind == 'm3u8') {
  236. let player;
  237. if (document.createElement('video').canPlayType('application/vnd.apple.mpegurl')) {
  238. // 原生支持 hls 播放
  239. player = new Player({
  240. lang: 'zh',
  241. id: videoParent[0],
  242. url: videoParent[1].addr,
  243. width: 294,
  244. height: 188,
  245. isLive: true,
  246. autoplay: true,
  247. autoplayMuted: true,
  248. cors: true,
  249. ignores: ['time', 'progress', 'play', 'i18n', 'volume', 'fullscreen', 'screenShot', 'playbackRate'],
  250. poster: '/src/assets/images/vent/noSinge.png',
  251. defaultPlaybackRate: videoParent[1].cameraRate || 1,
  252. controlsList: ['nodownload', 'nofullscreen', 'noremoteplayback'],
  253. hls: {
  254. retryCount: 10, // 重试 3 次,默认值
  255. retryDelay: 30000, // 每次重试间隔 1 秒,默认值
  256. loadTimeout: 10000, // 请求超时时间为 10 秒,默认值
  257. disconnectTime: 30, //直播断流时间,
  258. fetchOptions: {
  259. // 该参数会透传给 fetch,默认值为 undefined
  260. mode: 'cors',
  261. },
  262. targetLatency: 10, // 直播目标延迟,默认 10 秒
  263. maxLatency: 20, // 直播允许的最大延迟,默认 20 秒
  264. maxJumpDistance: 10,
  265. },
  266. });
  267. } else if (HlsPlugin.isSupported()) {
  268. // 第一步
  269. player = new Player({
  270. lang: 'zh',
  271. id: videoParent[0],
  272. url: videoParent[1].addr,
  273. width: 294,
  274. height: 188,
  275. isLive: true,
  276. autoplay: true,
  277. autoplayMuted: true,
  278. ignores: ['time', 'progress', 'play', 'i18n', 'volume', 'fullscreen', 'screenShot', 'playbackRate'],
  279. plugins: [HlsPlugin], // 第二步
  280. poster: '/src/assets/images/vent/noSinge.png',
  281. defaultPlaybackRate: videoParent[1].cameraRate || 1,
  282. controlsList: ['nodownload', 'nofullscreen', 'noremoteplayback'],
  283. hls: {
  284. retryCount: 10, // 重试 3 次,默认值
  285. retryDelay: 30000, // 每次重试间隔 1 秒,默认值
  286. loadTimeout: 10000, // 请求超时时间为 10 秒,默认值
  287. disconnectTime: 30,
  288. fetchOptions: {
  289. // 该参数会透传给 fetch,默认值为 undefined
  290. mode: 'cors',
  291. },
  292. targetLatency: 10, // 直播目标延迟,默认 10 秒
  293. maxLatency: 20, // 直播允许的最大延迟,默认 20 秒
  294. maxJumpDistance: 10,
  295. },
  296. });
  297. }
  298. playerList.push(player);
  299. }
  300. playerList.push(player);
  301. }
  302. } else {
  303. useDrag(videoParent as HTMLElement);
  304. livePlayerDiv?.appendChild(videoParent as Node);
  305. }
  306. });
  307. const players = livePlayerDiv?.getElementsByClassName('player');
  308. if (players && players.length) {
  309. for (let i = 0; i < players.length; i++) {
  310. try {
  311. const isCanPlayer = !players[i].getAttribute('id')?.startsWith('onPlayer');
  312. const dom = players[i].getElementsByTagName('video')[0];
  313. if (dom && isCanPlayer) {
  314. playerDoms.unshift(dom);
  315. } else {
  316. playerDoms.unshift(null);
  317. }
  318. } catch (error) {
  319. console.log('可以捕获到异常吗?????');
  320. playerDoms.unshift(null);
  321. }
  322. }
  323. }
  324. if (webRtcServer.length > 0) {
  325. for (let i = 0; i < webRtcServer.length; i++) {
  326. webRtcServer[i].videoElement.parentElement.remove();
  327. webRtcServer[i].disconnect();
  328. webRtcServer[i] = undefined;
  329. }
  330. }
  331. webRtcServer.length = 0;
  332. webRtcServer = newWebRtcServer;
  333. });
  334. }
  335. function removeCamera() {
  336. if (webRtcServer.length > 0) {
  337. webRtcServer.forEach((item) => {
  338. item.disconnect();
  339. });
  340. webRtcServer = [];
  341. }
  342. playerDoms.forEach((dom) => {
  343. dom?.remove();
  344. });
  345. playerList.forEach((player) => {
  346. if (player && player.destroy) player.destroy();
  347. player = null;
  348. });
  349. videoParentDomList.length = 0;
  350. playerDoms.length = 0;
  351. playerList.length = 0;
  352. }
  353. return {
  354. getCamera,
  355. webRtcServer,
  356. playerDoms,
  357. deviceCameraInit,
  358. removeCamera,
  359. };
  360. }