use-push.ts 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. import { windowReload } from 'billd-utils';
  2. import { onMounted, onUnmounted, ref, watch } from 'vue';
  3. import { useRoute, useRouter } from 'vue-router';
  4. import {
  5. fetchCreateUserLiveRoom,
  6. fetchUserHasLiveRoom,
  7. } from '@/api/userLiveRoom';
  8. import { DanmuMsgTypeEnum, ILiveRoom, IMessage } from '@/interface';
  9. import { WsMsgTypeEnum } from '@/network/webSocket';
  10. import { useAppStore } from '@/store/app';
  11. import { useNetworkStore } from '@/store/network';
  12. import { useUserStore } from '@/store/user';
  13. import { createVideo, generateBase64 } from '@/utils';
  14. import { loginTip } from './use-login';
  15. import { useSrsWs } from './use-srs-ws';
  16. import { useTip } from './use-tip';
  17. export function usePush() {
  18. const route = useRoute();
  19. const router = useRouter();
  20. const appStore = useAppStore();
  21. const userStore = useUserStore();
  22. const networkStore = useNetworkStore();
  23. const roomId = ref('');
  24. const roomName = ref('');
  25. const danmuStr = ref('');
  26. const liveRoomInfo = ref<ILiveRoom>();
  27. const localStream = ref<MediaStream>();
  28. const videoElArr = ref<HTMLVideoElement[]>([]);
  29. const {
  30. roomLiving,
  31. isPull,
  32. initSrsWs,
  33. handleStartLive,
  34. mySocketId,
  35. canvasVideoStream,
  36. lastCoverImg,
  37. liveUserList,
  38. damuList,
  39. currentMaxFramerate,
  40. currentMaxBitrate,
  41. currentResolutionRatio,
  42. } = useSrsWs();
  43. isPull.value = false;
  44. watch(
  45. () => appStore.allTrack,
  46. (newTrack) => {
  47. console.log('appStore.allTrack变了');
  48. const mixedStream = new MediaStream();
  49. newTrack.forEach((item) => {
  50. if (item.track) {
  51. mixedStream.addTrack(item.track);
  52. }
  53. });
  54. console.log('新的allTrack音频轨', mixedStream.getAudioTracks());
  55. console.log('新的allTrack视频轨', mixedStream.getVideoTracks());
  56. console.log('旧的allTrack音频轨', localStream.value?.getAudioTracks());
  57. console.log('旧的allTrack视频轨', localStream.value?.getVideoTracks());
  58. localStream.value = mixedStream;
  59. },
  60. { deep: true }
  61. );
  62. watch(
  63. () => currentResolutionRatio.value,
  64. (newVal) => {
  65. if (canvasVideoStream.value) {
  66. canvasVideoStream.value.getVideoTracks().forEach((track) => {
  67. track.applyConstraints({
  68. frameRate: { max: currentMaxFramerate.value },
  69. height: newVal,
  70. });
  71. });
  72. } else {
  73. appStore.allTrack.forEach((info) => {
  74. info.track?.applyConstraints({
  75. frameRate: { max: currentMaxFramerate.value },
  76. height: newVal,
  77. });
  78. });
  79. }
  80. networkStore.rtcMap.forEach(async (rtc) => {
  81. const res = await rtc.setResolutionRatio(newVal);
  82. if (res === 1) {
  83. window.$message.success('切换分辨率成功!');
  84. } else {
  85. window.$message.success('切换分辨率失败!');
  86. }
  87. });
  88. }
  89. );
  90. watch(
  91. () => currentMaxFramerate.value,
  92. (newVal) => {
  93. if (canvasVideoStream.value) {
  94. canvasVideoStream.value.getVideoTracks().forEach((track) => {
  95. track.applyConstraints({
  96. frameRate: { max: newVal },
  97. height: currentResolutionRatio.value,
  98. });
  99. });
  100. } else {
  101. appStore.allTrack.forEach((info) => {
  102. info.track?.applyConstraints({
  103. frameRate: { max: newVal },
  104. height: currentResolutionRatio.value,
  105. });
  106. });
  107. }
  108. networkStore.rtcMap.forEach(async (rtc) => {
  109. const res = await rtc.setMaxFramerate(newVal);
  110. if (res === 1) {
  111. window.$message.success('切换帧率成功!');
  112. } else {
  113. window.$message.success('切换帧率失败!');
  114. }
  115. });
  116. }
  117. );
  118. watch(
  119. () => currentMaxBitrate.value,
  120. (newVal) => {
  121. networkStore.rtcMap.forEach(async (rtc) => {
  122. const res = await rtc.setMaxBitrate(newVal);
  123. if (res === 1) {
  124. window.$message.success('切换码率成功!');
  125. } else {
  126. window.$message.success('切换码率失败!');
  127. }
  128. });
  129. }
  130. );
  131. watch(
  132. () => localStream.value,
  133. (stream) => {
  134. console.log('localStream变了');
  135. console.log('音频轨:', stream?.getAudioTracks());
  136. console.log('视频轨:', stream?.getVideoTracks());
  137. videoElArr.value.forEach((dom) => {
  138. dom.remove();
  139. });
  140. stream?.getVideoTracks().forEach((track) => {
  141. console.log('视频轨enabled:', track.id, track.enabled);
  142. const video = createVideo({});
  143. video.setAttribute('track-id', track.id);
  144. video.srcObject = new MediaStream([track]);
  145. videoElArr.value.push(video);
  146. });
  147. stream?.getAudioTracks().forEach((track) => {
  148. console.log('音频轨enabled:', track.id, track.enabled);
  149. const video = createVideo({});
  150. video.setAttribute('track-id', track.id);
  151. video.srcObject = new MediaStream([track]);
  152. videoElArr.value.push(video);
  153. });
  154. },
  155. { deep: true }
  156. );
  157. watch(
  158. () => userStore.userInfo,
  159. async (newVal) => {
  160. if (newVal) {
  161. const res = await userHasLiveRoom();
  162. if (!res) {
  163. await useTip('你还没有直播间,是否立即开通?');
  164. await handleCreateUserLiveRoom();
  165. } else {
  166. roomName.value = liveRoomInfo.value?.name || '';
  167. roomId.value = `${liveRoomInfo.value?.id || ''}`;
  168. connectWs();
  169. }
  170. }
  171. },
  172. { immediate: true }
  173. );
  174. onMounted(() => {
  175. roomId.value = route.query.roomId as string;
  176. if (!loginTip()) return;
  177. });
  178. onUnmounted(() => {
  179. closeWs();
  180. closeRtc();
  181. });
  182. function closeWs() {
  183. const instance = networkStore.wsMap.get(roomId.value);
  184. instance?.close();
  185. }
  186. function closeRtc() {
  187. networkStore.rtcMap.forEach((rtc) => {
  188. rtc.close();
  189. networkStore.removeRtc(rtc.roomId);
  190. });
  191. }
  192. async function userHasLiveRoom() {
  193. const res = await fetchUserHasLiveRoom(userStore.userInfo?.id!);
  194. if (res.code === 200 && res.data) {
  195. liveRoomInfo.value = res.data.live_room;
  196. router.push({ query: { ...route.query, roomId: roomId.value } });
  197. return true;
  198. }
  199. return false;
  200. }
  201. async function handleCreateUserLiveRoom() {
  202. try {
  203. const res = await fetchCreateUserLiveRoom();
  204. if (res.code === 200) {
  205. window.$message.success('开通直播间成功!');
  206. setTimeout(() => {
  207. windowReload();
  208. }, 500);
  209. }
  210. } catch (error) {
  211. console.log(error);
  212. }
  213. }
  214. function connectWs() {
  215. initSrsWs({
  216. isAnchor: true,
  217. roomId: roomId.value,
  218. currentMaxBitrate: currentMaxBitrate.value,
  219. currentMaxFramerate: currentMaxFramerate.value,
  220. currentResolutionRatio: currentResolutionRatio.value,
  221. });
  222. }
  223. async function startLive({ type, receiver }) {
  224. console.log('startLive');
  225. if (!loginTip()) return;
  226. const flag = await userHasLiveRoom();
  227. if (!flag) {
  228. await useTip('你还没有直播间,是否立即开通?');
  229. await handleCreateUserLiveRoom();
  230. return;
  231. }
  232. if (!roomNameIsOk()) {
  233. return;
  234. }
  235. roomLiving.value = true;
  236. const el = appStore.allTrack.find((item) => {
  237. if (item.video === 1) {
  238. return true;
  239. }
  240. });
  241. if (el) {
  242. const res1 = videoElArr.value.find(
  243. (item) => item.getAttribute('track-id') === el.track?.id
  244. );
  245. if (res1) {
  246. // canvas推流的话,不需要再设置预览图了
  247. if (!canvasVideoStream.value) {
  248. lastCoverImg.value = generateBase64(res1);
  249. }
  250. }
  251. }
  252. handleStartLive({
  253. coverImg: lastCoverImg.value,
  254. name: roomName.value,
  255. type,
  256. receiver,
  257. });
  258. }
  259. /** 结束直播 */
  260. function endLive() {
  261. roomLiving.value = false;
  262. localStream.value = undefined;
  263. const instance = networkStore.wsMap.get(roomId.value);
  264. if (instance) {
  265. instance.send({
  266. msgType: WsMsgTypeEnum.roomNoLive,
  267. });
  268. }
  269. closeRtc();
  270. }
  271. function roomNameIsOk() {
  272. if (!roomName.value.length) {
  273. window.$message.warning('请输入房间名!');
  274. return false;
  275. }
  276. if (roomName.value.length < 3 || roomName.value.length > 30) {
  277. window.$message.warning('房间名要求3-30个字符!');
  278. return false;
  279. }
  280. return true;
  281. }
  282. function keydownDanmu(event: KeyboardEvent) {
  283. const key = event.key.toLowerCase();
  284. if (key === 'enter') {
  285. event.preventDefault();
  286. sendDanmu();
  287. }
  288. }
  289. function confirmRoomName() {
  290. if (!roomNameIsOk()) return;
  291. }
  292. function sendDanmu() {
  293. if (!danmuStr.value.length) {
  294. window.$message.warning('请输入弹幕内容!');
  295. return;
  296. }
  297. const instance = networkStore.wsMap.get(roomId.value);
  298. if (!instance) {
  299. window.$message.error('还没开播,不能发送弹幕!');
  300. return;
  301. }
  302. instance.send<IMessage['data']>({
  303. msgType: WsMsgTypeEnum.message,
  304. data: {
  305. msg: danmuStr.value,
  306. msgType: DanmuMsgTypeEnum.danmu,
  307. live_room_id: Number(roomId.value),
  308. },
  309. });
  310. damuList.value.push({
  311. socket_id: mySocketId.value,
  312. msgType: DanmuMsgTypeEnum.danmu,
  313. msg: danmuStr.value,
  314. userInfo: userStore.userInfo,
  315. });
  316. danmuStr.value = '';
  317. }
  318. return {
  319. confirmRoomName,
  320. startLive,
  321. endLive,
  322. sendDanmu,
  323. keydownDanmu,
  324. mySocketId,
  325. lastCoverImg,
  326. localStream,
  327. canvasVideoStream,
  328. roomLiving,
  329. currentResolutionRatio,
  330. currentMaxBitrate,
  331. currentMaxFramerate,
  332. danmuStr,
  333. roomName,
  334. damuList,
  335. liveUserList,
  336. liveRoomInfo,
  337. };
  338. }