use-push.ts 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. import { getRandomString, windowReload } from 'billd-utils';
  2. import { onMounted, onUnmounted, ref, watch } from 'vue';
  3. import { fetchCreateUserLiveRoom } from '@/api/userLiveRoom';
  4. import { loginTip } from '@/hooks/use-login';
  5. import { useTip } from '@/hooks/use-tip';
  6. import { useWebsocket } from '@/hooks/use-websocket';
  7. import { WsMessageIsFileEnum } from '@/interface';
  8. import { useAppStore } from '@/store/app';
  9. import { useNetworkStore } from '@/store/network';
  10. import { useUserStore } from '@/store/user';
  11. import {
  12. WsConnectStatusEnum,
  13. WsMsgTypeEnum,
  14. WsMsrBlobType,
  15. WsRoomNoLiveType,
  16. } from '@/types/websocket';
  17. import { createVideo, generateBase64 } from '@/utils';
  18. import { handlConstraints } from '@/utils/network/webRTC';
  19. export function usePush() {
  20. const appStore = useAppStore();
  21. const userStore = useUserStore();
  22. const networkStore = useNetworkStore();
  23. const roomId = ref('');
  24. const danmuStr = ref('');
  25. const localStream = ref<MediaStream>();
  26. const videoElArr = ref<HTMLVideoElement[]>([]);
  27. const msgIsFile = ref<WsMessageIsFileEnum>(WsMessageIsFileEnum.no);
  28. const {
  29. keepRtcLivingTimer,
  30. roomLiving,
  31. initWs,
  32. handleStartLive,
  33. sendDanmuTxt,
  34. connectStatus,
  35. mySocketId,
  36. canvasVideoStream,
  37. lastCoverImg,
  38. liveUserList,
  39. damuList,
  40. currentMaxFramerate,
  41. currentMaxBitrate,
  42. currentResolutionRatio,
  43. currentAudioContentHint,
  44. currentVideoContentHint,
  45. } = useWebsocket();
  46. onMounted(() => {
  47. if (!loginTip()) return;
  48. });
  49. onUnmounted(() => {
  50. closeWs();
  51. closeRtc();
  52. });
  53. function closeWs() {
  54. networkStore.wsMap.forEach((ws) => {
  55. networkStore.removeWs(ws.roomId);
  56. });
  57. }
  58. function closeRtc() {
  59. networkStore.rtcMap.forEach((rtc) => {
  60. networkStore.removeRtc(rtc.receiver);
  61. });
  62. }
  63. watch(
  64. () => currentResolutionRatio.value,
  65. (newval) => {
  66. console.log('分辨率变了', newval);
  67. networkStore.rtcMap.forEach((rtc) => {
  68. if (canvasVideoStream.value) {
  69. handlConstraints({
  70. frameRate: rtc.maxFramerate,
  71. height: newval,
  72. stream: canvasVideoStream.value,
  73. });
  74. }
  75. });
  76. }
  77. );
  78. watch(
  79. () => currentMaxFramerate.value,
  80. (newval) => {
  81. console.log('帧率变了', newval);
  82. networkStore.rtcMap.forEach((rtc) => {
  83. if (canvasVideoStream.value) {
  84. handlConstraints({
  85. frameRate: newval,
  86. height: rtc.resolutionRatio,
  87. stream: canvasVideoStream.value,
  88. });
  89. }
  90. });
  91. }
  92. );
  93. watch(
  94. () => currentMaxBitrate.value,
  95. (newval) => {
  96. console.log('码率变了', newval);
  97. networkStore.rtcMap.forEach(async (rtc) => {
  98. const res = await rtc.setMaxBitrate(newval);
  99. if (res === 1) {
  100. window.$message.success('切换码率成功!');
  101. } else {
  102. window.$message.success('切换码率失败!');
  103. }
  104. });
  105. }
  106. );
  107. watch(
  108. () => localStream.value,
  109. (stream) => {
  110. console.log('localStream变了');
  111. console.log('音频轨:', stream?.getAudioTracks());
  112. console.log('视频轨:', stream?.getVideoTracks());
  113. videoElArr.value.forEach((dom) => {
  114. dom.remove();
  115. });
  116. stream?.getVideoTracks().forEach((track) => {
  117. console.log('视频轨enabled:', track.id, track.enabled);
  118. const video = createVideo({});
  119. video.setAttribute('track-id', track.id);
  120. video.srcObject = new MediaStream([track]);
  121. videoElArr.value.push(video);
  122. });
  123. stream?.getAudioTracks().forEach((track) => {
  124. console.log('音频轨enabled:', track.id, track.enabled);
  125. const video = createVideo({});
  126. video.setAttribute('track-id', track.id);
  127. video.srcObject = new MediaStream([track]);
  128. videoElArr.value.push(video);
  129. });
  130. },
  131. { deep: true }
  132. );
  133. watch(
  134. () => userStore.userInfo,
  135. async (newVal) => {
  136. if (newVal) {
  137. const res = handleUserHasLiveRoom();
  138. if (!res) {
  139. await useTip({
  140. content: '你还没有直播间,是否立即开通?',
  141. maskClosable: false,
  142. });
  143. await handleCreateUserLiveRoom();
  144. } else {
  145. roomId.value = `${appStore.liveRoomInfo?.id || ''}`;
  146. connectWs();
  147. }
  148. }
  149. },
  150. { immediate: true }
  151. );
  152. function handleUserHasLiveRoom() {
  153. const res = userStore.userInfo?.live_rooms?.[0];
  154. appStore.liveRoomInfo = res;
  155. return res;
  156. }
  157. async function handleCreateUserLiveRoom() {
  158. try {
  159. const res = await fetchCreateUserLiveRoom();
  160. if (res.code === 200) {
  161. window.$message.success('开通直播间成功!');
  162. setTimeout(() => {
  163. windowReload();
  164. }, 500);
  165. }
  166. } catch (error) {
  167. console.log(error);
  168. }
  169. }
  170. function connectWs() {
  171. initWs({
  172. isAnchor: true,
  173. roomId: roomId.value,
  174. currentMaxBitrate: currentMaxBitrate.value,
  175. currentMaxFramerate: currentMaxFramerate.value,
  176. currentResolutionRatio: currentResolutionRatio.value,
  177. });
  178. }
  179. async function startLive({ type, cdn, isdev, msrDelay, msrMaxDelay }) {
  180. if (!loginTip()) return;
  181. const flag = handleUserHasLiveRoom();
  182. if (!flag) {
  183. await useTip({
  184. content: '你还没有直播间,是否立即开通?',
  185. maskClosable: false,
  186. });
  187. await handleCreateUserLiveRoom();
  188. return;
  189. }
  190. if (connectStatus.value !== WsConnectStatusEnum.connect) {
  191. window.$message.warning('websocket未连接');
  192. return;
  193. }
  194. roomLiving.value = true;
  195. const el = appStore.allTrack.find((item) => {
  196. if (item.video === 1) {
  197. return true;
  198. }
  199. });
  200. if (el) {
  201. const res1 = videoElArr.value.find(
  202. (item) => item.getAttribute('track-id') === el.track?.id
  203. );
  204. if (res1) {
  205. // canvas推流的话,不需要再设置预览图了
  206. if (!canvasVideoStream.value) {
  207. lastCoverImg.value = generateBase64(res1);
  208. }
  209. }
  210. }
  211. if (canvasVideoStream.value) {
  212. handlConstraints({
  213. stream: canvasVideoStream.value,
  214. height: currentResolutionRatio.value,
  215. frameRate: currentMaxFramerate.value,
  216. });
  217. }
  218. handleStartLive({ cdn, isdev, type, msrDelay, msrMaxDelay });
  219. }
  220. /** 结束直播 */
  221. function endLive() {
  222. roomLiving.value = false;
  223. localStream.value = undefined;
  224. closeRtc();
  225. clearInterval(keepRtcLivingTimer.value);
  226. }
  227. function sendRoomNoLive() {
  228. const instance = networkStore.wsMap.get(roomId.value);
  229. if (instance) {
  230. instance.send<WsRoomNoLiveType['data']>({
  231. requestId: getRandomString(8),
  232. msgType: WsMsgTypeEnum.roomNoLive,
  233. data: {
  234. live_room_id: appStore.liveRoomInfo?.id!,
  235. },
  236. });
  237. }
  238. }
  239. function sendBlob(data: { blob; blobId: string; delay; max_delay }) {
  240. const instance = networkStore.wsMap.get(roomId.value);
  241. if (instance) {
  242. instance.send<WsMsrBlobType['data']>({
  243. requestId: getRandomString(8),
  244. msgType: WsMsgTypeEnum.msrBlob,
  245. data: {
  246. live_room_id: Number(roomId.value),
  247. blob: data.blob,
  248. blob_id: data.blobId,
  249. delay: data.delay,
  250. max_delay: data.max_delay,
  251. },
  252. });
  253. }
  254. }
  255. function keydownDanmu(event: KeyboardEvent) {
  256. const key = event.key.toLowerCase();
  257. if (key === 'enter') {
  258. event.preventDefault();
  259. sendDanmuTxt(danmuStr.value);
  260. danmuStr.value = '';
  261. }
  262. }
  263. return {
  264. startLive,
  265. endLive,
  266. keydownDanmu,
  267. sendBlob,
  268. sendRoomNoLive,
  269. roomId,
  270. msgIsFile,
  271. mySocketId,
  272. lastCoverImg,
  273. localStream,
  274. canvasVideoStream,
  275. roomLiving,
  276. currentResolutionRatio,
  277. currentMaxBitrate,
  278. currentMaxFramerate,
  279. currentAudioContentHint,
  280. currentVideoContentHint,
  281. danmuStr,
  282. damuList,
  283. liveUserList,
  284. };
  285. }