use-pull.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. import { getRandomString } from 'billd-utils';
  2. import { onUnmounted, ref, watch } from 'vue';
  3. import { useRoute } from 'vue-router';
  4. import { commentAuthTip, loginTip } from '@/hooks/use-login';
  5. import { useFlvPlay, useHlsPlay } from '@/hooks/use-play';
  6. import { useWebsocket } from '@/hooks/use-websocket';
  7. import {
  8. DanmuMsgTypeEnum,
  9. LiveLineEnum,
  10. WsMessageMsgIsFileEnum,
  11. } from '@/interface';
  12. import { useAppStore } from '@/store/app';
  13. import { usePiniaCacheStore } from '@/store/cache';
  14. import { useNetworkStore } from '@/store/network';
  15. import { ILiveRoom, LiveRoomTypeEnum } from '@/types/ILiveRoom';
  16. import { WsMessageType, WsMsgTypeEnum } from '@/types/websocket';
  17. import { createVideo, videoToCanvas } from '@/utils';
  18. export function usePull(roomId: string) {
  19. const route = useRoute();
  20. const networkStore = useNetworkStore();
  21. const cacheStore = usePiniaCacheStore();
  22. const appStore = useAppStore();
  23. const localStream = ref<MediaStream>();
  24. const danmuStr = ref('');
  25. const msgIsFile = ref(WsMessageMsgIsFileEnum.no);
  26. const danmuMsgType = ref<DanmuMsgTypeEnum>(DanmuMsgTypeEnum.danmu);
  27. const autoplayVal = ref(false);
  28. const videoLoading = ref(false);
  29. const isPlaying = ref(false);
  30. const flvurl = ref('');
  31. const hlsurl = ref('');
  32. const videoWrapRef = ref<HTMLDivElement>();
  33. const videoHeight = ref();
  34. const videoElArr = ref<HTMLVideoElement[]>([]);
  35. const remoteVideo = ref<HTMLElement[]>([]);
  36. const {
  37. mySocketId,
  38. initWs,
  39. roomLiving,
  40. anchorInfo,
  41. liveUserList,
  42. damuList,
  43. handleSendGetLiveUser,
  44. } = useWebsocket();
  45. const { flvVideoEl, flvIsPlaying, startFlvPlay, destroyFlv } = useFlvPlay();
  46. const { hlsVideoEl, hlsIsPlaying, startHlsPlay, destroyHls } = useHlsPlay();
  47. const stopDrawingArr = ref<any[]>([]);
  48. onUnmounted(() => {
  49. handleStopDrawing();
  50. });
  51. function handleStopDrawing() {
  52. destroyFlv();
  53. destroyHls();
  54. stopDrawingArr.value.forEach((cb) => cb());
  55. stopDrawingArr.value = [];
  56. remoteVideo.value.forEach((el) => el.remove());
  57. remoteVideo.value = [];
  58. }
  59. watch(hlsVideoEl, () => {
  60. stopDrawingArr.value = [];
  61. stopDrawingArr.value.forEach((cb) => cb());
  62. if (videoWrapRef.value) {
  63. const rect = videoWrapRef.value.getBoundingClientRect();
  64. const { canvas, stopDrawing } = videoToCanvas({
  65. wrapSize: {
  66. width: rect.width,
  67. height: rect.height,
  68. },
  69. videoEl: hlsVideoEl.value!,
  70. videoResize: ({ w, h }) => {
  71. videoHeight.value = `${w}x${h}`;
  72. },
  73. });
  74. stopDrawingArr.value.push(stopDrawing);
  75. remoteVideo.value.push(canvas);
  76. videoLoading.value = false;
  77. }
  78. });
  79. function handleHlsPlay(url: string) {
  80. console.log('handleHlsPlay', url);
  81. handleStopDrawing();
  82. videoLoading.value = true;
  83. appStore.setLiveLine(LiveLineEnum.hls);
  84. startHlsPlay({
  85. hlsurl: url,
  86. });
  87. }
  88. watch(flvVideoEl, () => {
  89. stopDrawingArr.value = [];
  90. stopDrawingArr.value.forEach((cb) => cb());
  91. if (videoWrapRef.value) {
  92. const rect = videoWrapRef.value.getBoundingClientRect();
  93. const { canvas, stopDrawing } = videoToCanvas({
  94. wrapSize: {
  95. width: rect.width,
  96. height: rect.height,
  97. },
  98. videoEl: flvVideoEl.value!,
  99. videoResize: ({ w, h }) => {
  100. videoHeight.value = `${w}x${h}`;
  101. },
  102. });
  103. stopDrawingArr.value.push(stopDrawing);
  104. remoteVideo.value.push(canvas);
  105. videoLoading.value = false;
  106. }
  107. });
  108. function handleFlvPlay() {
  109. console.log('handleFlvPlay');
  110. handleStopDrawing();
  111. videoLoading.value = true;
  112. appStore.setLiveLine(LiveLineEnum.flv);
  113. startFlvPlay({
  114. flvurl: flvurl.value,
  115. });
  116. }
  117. function handlePlay(data: ILiveRoom) {
  118. roomLiving.value = true;
  119. flvurl.value = data.flv_url!;
  120. hlsurl.value = data.hls_url!;
  121. switch (data.type) {
  122. case LiveRoomTypeEnum.srs:
  123. if (appStore.liveLine === LiveLineEnum.flv) {
  124. handleFlvPlay();
  125. } else if (appStore.liveLine === LiveLineEnum.hls) {
  126. handleHlsPlay(data.hls_url!);
  127. }
  128. break;
  129. case LiveRoomTypeEnum.obs:
  130. if (appStore.liveLine === LiveLineEnum.flv) {
  131. handleFlvPlay();
  132. } else if (appStore.liveLine === LiveLineEnum.hls) {
  133. handleHlsPlay(data.hls_url!);
  134. }
  135. break;
  136. case LiveRoomTypeEnum.msr:
  137. if (appStore.liveLine === LiveLineEnum.flv) {
  138. handleFlvPlay();
  139. } else if (appStore.liveLine === LiveLineEnum.hls) {
  140. handleHlsPlay(data.hls_url!);
  141. }
  142. break;
  143. case LiveRoomTypeEnum.system:
  144. if (appStore.liveLine === LiveLineEnum.flv) {
  145. handleFlvPlay();
  146. } else if (appStore.liveLine === LiveLineEnum.hls) {
  147. handleHlsPlay(data.hls_url!);
  148. }
  149. break;
  150. case LiveRoomTypeEnum.pk:
  151. if (appStore.liveLine === LiveLineEnum.flv) {
  152. handleFlvPlay();
  153. } else if (appStore.liveLine === LiveLineEnum.hls) {
  154. handleHlsPlay(data.hls_url!);
  155. }
  156. break;
  157. case LiveRoomTypeEnum.wertc_live:
  158. appStore.setLiveLine(LiveLineEnum.rtc);
  159. break;
  160. }
  161. }
  162. watch(
  163. [() => roomLiving.value, () => appStore.liveRoomInfo],
  164. ([val, liveRoomInfo]) => {
  165. if (val && liveRoomInfo) {
  166. if (
  167. [
  168. LiveRoomTypeEnum.system,
  169. LiveRoomTypeEnum.msr,
  170. LiveRoomTypeEnum.srs,
  171. LiveRoomTypeEnum.obs,
  172. LiveRoomTypeEnum.tencent_css,
  173. LiveRoomTypeEnum.tencent_css_pk,
  174. ].includes(liveRoomInfo.type!)
  175. ) {
  176. handlePlay(liveRoomInfo!);
  177. } else if (LiveRoomTypeEnum.pk === liveRoomInfo.type!) {
  178. if (!route.query.pkKey) {
  179. handlePlay(liveRoomInfo!);
  180. }
  181. }
  182. } else {
  183. closeRtc();
  184. handleStopDrawing();
  185. }
  186. },
  187. {
  188. deep: true,
  189. immediate: true,
  190. }
  191. );
  192. watch(
  193. () => appStore.liveLine,
  194. (newVal) => {
  195. console.log('liveLine变了', newVal);
  196. if (!roomLiving.value) {
  197. return;
  198. }
  199. switch (newVal) {
  200. case LiveLineEnum.flv:
  201. handleFlvPlay();
  202. break;
  203. case LiveLineEnum.hls:
  204. handleHlsPlay(hlsurl.value);
  205. break;
  206. case LiveLineEnum.rtc:
  207. break;
  208. }
  209. }
  210. );
  211. watch(
  212. () => cacheStore.muted,
  213. (newVal) => {
  214. videoElArr.value.forEach((el) => {
  215. el.muted = newVal;
  216. });
  217. if (!newVal) {
  218. cacheStore.setVolume(cacheStore.volume || appStore.normalVolume);
  219. } else {
  220. cacheStore.setVolume(0);
  221. }
  222. }
  223. );
  224. watch(
  225. () => cacheStore.volume,
  226. (newVal) => {
  227. videoElArr.value.forEach((el) => {
  228. el.volume = newVal / 100;
  229. });
  230. if (!newVal) {
  231. cacheStore.setMuted(true);
  232. } else {
  233. cacheStore.setMuted(false);
  234. }
  235. }
  236. );
  237. watch(
  238. () => appStore.play,
  239. (newVal) => {
  240. videoElArr.value.forEach((el) => {
  241. if (newVal) {
  242. el.play();
  243. } else {
  244. el.pause();
  245. }
  246. });
  247. }
  248. );
  249. watch(
  250. () => hlsIsPlaying.value,
  251. (newVal) => {
  252. isPlaying.value = newVal;
  253. }
  254. );
  255. watch(
  256. () => flvIsPlaying.value,
  257. (newVal) => {
  258. isPlaying.value = newVal;
  259. }
  260. );
  261. watch(
  262. () => localStream.value,
  263. (val) => {
  264. if (val) {
  265. console.log('localStream变了');
  266. console.log('音频轨:', val?.getAudioTracks());
  267. console.log('视频轨:', val?.getVideoTracks());
  268. if (appStore.liveRoomInfo?.type === LiveRoomTypeEnum.wertc_live) {
  269. videoElArr.value.forEach((dom) => {
  270. dom.remove();
  271. });
  272. val?.getVideoTracks().forEach((track) => {
  273. console.log('视频轨enabled:', track.id, track.enabled);
  274. const video = createVideo({});
  275. video.setAttribute('track-id', track.id);
  276. video.srcObject = new MediaStream([track]);
  277. remoteVideo.value.push(video);
  278. videoElArr.value.push(video);
  279. });
  280. val?.getAudioTracks().forEach((track) => {
  281. console.log('音频轨enabled:', track.id, track.enabled);
  282. const video = createVideo({});
  283. video.setAttribute('track-id', track.id);
  284. video.srcObject = new MediaStream([track]);
  285. remoteVideo.value.push(video);
  286. videoElArr.value.push(video);
  287. });
  288. videoLoading.value = false;
  289. } else {
  290. videoElArr.value.forEach((dom) => {
  291. dom.remove();
  292. });
  293. val?.getVideoTracks().forEach((track) => {
  294. console.log('视频轨enabled:', track.id, track.enabled);
  295. const video = createVideo({});
  296. video.setAttribute('track-id', track.id);
  297. video.srcObject = new MediaStream([track]);
  298. remoteVideo.value.push(video);
  299. videoElArr.value.push(video);
  300. });
  301. val?.getAudioTracks().forEach((track) => {
  302. console.log('音频轨enabled:', track.id, track.enabled);
  303. const video = createVideo({});
  304. video.setAttribute('track-id', track.id);
  305. video.srcObject = new MediaStream([track]);
  306. remoteVideo.value.push(video);
  307. videoElArr.value.push(video);
  308. });
  309. videoLoading.value = false;
  310. }
  311. } else {
  312. videoElArr.value?.forEach((item) => {
  313. item.remove();
  314. });
  315. }
  316. },
  317. { deep: true }
  318. );
  319. function initPull(autolay = true) {
  320. autoplayVal.value = autolay;
  321. if (autoplayVal.value) {
  322. videoLoading.value = true;
  323. }
  324. initWs({
  325. roomId,
  326. isAnchor: false,
  327. });
  328. }
  329. function closeWs() {
  330. networkStore.wsMap.forEach((ws) => {
  331. networkStore.removeWs(ws.roomId);
  332. });
  333. }
  334. function closeRtc() {
  335. networkStore.rtcMap.forEach((rtc) => {
  336. networkStore.removeRtc(rtc.receiver);
  337. });
  338. }
  339. function keydownDanmu(event: KeyboardEvent) {
  340. const key = event.key.toLowerCase();
  341. if (key === 'enter') {
  342. event.preventDefault();
  343. sendDanmu();
  344. }
  345. }
  346. function sendDanmu() {
  347. if (!loginTip()) {
  348. return;
  349. }
  350. if (!commentAuthTip()) {
  351. return;
  352. }
  353. if (!danmuStr.value.trim().length) {
  354. window.$message.warning('请输入弹幕内容!');
  355. return;
  356. }
  357. const instance = networkStore.wsMap.get(roomId);
  358. if (!instance) return;
  359. const requestId = getRandomString(8);
  360. const messageData: WsMessageType['data'] = {
  361. socket_id: '',
  362. msg: danmuStr.value,
  363. msgType: danmuMsgType.value,
  364. live_room_id: Number(roomId),
  365. msgIsFile: msgIsFile.value,
  366. send_msg_time: +new Date(),
  367. user_agent: navigator.userAgent,
  368. };
  369. instance.send({
  370. requestId,
  371. msgType: WsMsgTypeEnum.message,
  372. data: messageData,
  373. });
  374. danmuStr.value = '';
  375. }
  376. return {
  377. videoWrapRef,
  378. handlePlay,
  379. handleStopDrawing,
  380. initPull,
  381. closeWs,
  382. closeRtc,
  383. keydownDanmu,
  384. sendDanmu,
  385. handleSendGetLiveUser,
  386. danmuMsgType,
  387. isPlaying,
  388. msgIsFile,
  389. mySocketId,
  390. videoHeight,
  391. remoteVideo,
  392. roomLiving,
  393. autoplayVal,
  394. videoLoading,
  395. damuList,
  396. liveUserList,
  397. danmuStr,
  398. anchorInfo,
  399. };
  400. }