import Janus from "./webrtc"; import { bus } from "./bus"; import { Message } from "element-ui"; // var serverInfo = "ws://127.0.0.1:8188"; var serverInfo = ""; var libraryVersion = "v1.0.3"; var localstreamAudio = null; var localstreamVideo = null; export function initLibrary(callback) { Janus.init({ debug: "all", callback: function () { callback(Janus.isWebrtcSupported()); }, }); } export function setServerInfo(svrInfo) { serverInfo = svrInfo; } export function getLibraryVersion() { return libraryVersion; } function generateUUID() { var d = new Date().getTime(); var uuid = "xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx".replace(/[xy]/g, function (c) { var r = (d + Math.random() * 16) % 16 | 0; d = Math.floor(d / 16); return (c == "x" ? r : (r & 0x3) | 0x8).toString(16); }); return uuid; } export function PublishVideo() { var libraryHandle = null; var sessionHandle = null; var sessionId = generateUUID(); // 房间 var roomCallback = null; // 视频相关变量 var localVideoRatio = "hires"; var localVideoCodec = "vp9"; var localAudioCodec = "opus"; var selfUserId = null; var selfVideoId = null; var openVideoOptions = null; var localVideoStream = null; console.log(serverInfo, 11111); // 初始化 this.init = function (options) { console.log(options); libraryHandle = new Janus({ server: serverInfo, success: function () { libraryHandle.attach({ plugin: "janus.plugin.videoroom", opaqueId: sessionId, success: function (pluginHandle) { sessionHandle = pluginHandle; Janus.debug("publish: video server load success."); options.success(); }, error: function (err) { Janus.error("publish: video server load fail:" + err); options.error(err); }, consentDialog: onConsentDialog, mediaState: onMediaState, webrtcState: onWebrtcState, onmessage: onMessage, onlocalstream: onLocalStream, onremotestream: onRemoteStream, oncleanup: onCleanup, }); }, error: function (err) { Janus.error("publish: load video library fail:" + err); options.error(err); }, destroyed: function () { Janus.debug("publish: video library is destoryed."); }, }); }; this.setLocalVideoRatio = function (ratio) { if (ratio == "320*240") { localVideoRatio = "lowres"; // localVideoCodec = "vp8"; } else if (ratio == "1280*720") { localVideoRatio = "hires"; // localVideoCodec = "vp9"; } else { localVideoRatio = "stdres"; // localVideoCodec = "vp8"; } }; //创建房间和加入房间 this.openLocalVideo = function (options) { openVideoOptions = options; if (openVideoOptions.type === "camera") { var createRoomMsg = { request: "create", room: Number(openVideoOptions.roomId), description: `${Number(openVideoOptions.roomId)}:${openVideoOptions.videoName}`, publishers: 32, permanent: false, bitrate: 20480000, fir_freq: 10, audiocodec: "pcmu", videocodec: "vp8,h264", opus_fec: true, video_svc: false, record: false, }; localAudioCodec = "pcmu"; localVideoCodec = "H264"; } else { var createRoomMsg = { request: "create", room: Number(openVideoOptions.roomId), description: `${Number(openVideoOptions.roomId)}:${openVideoOptions.videoName}`, publishers: 32, permanent: false, bitrate: 20480000, fir_freq: 10, audiocodec: "opus", videocodec: "vp8,vp9", opus_fec: true, video_svc: false, record: false, }; } sessionHandle.send({ message: createRoomMsg, success: function (msg) { console.log(msg, "createRoom"); if (msg != null && msg != undefined) { if (options.type === "camera") { var joinRoomMsg = { request: "join", room: Number(options.roomId), ptype: "publisher", id: Number(options.roomId), display: `${Number(options.roomId)}:${options.videoName}`, }; sessionHandle.send({ message: joinRoomMsg, success: function (msg) {}, }); } else { var joinRoomMsg = { request: "join", room: Number(options.roomId), ptype: "publisher", id: Number(options.roomId), display: `${Number(options.roomId)}:${options.videoName}`, }; sessionHandle.send({ message: joinRoomMsg, success: function (msg) {}, }); } } }, error: function (err) { console.log(error, "createRoomError"); }, }); }; this.getLocalVideoStream = function () { return localVideoStream; }; this.closeLocalVideo = function () { var unpublishMsg = { request: "unpublish" }; sessionHandle.send({ message: unpublishMsg }); let bindingUserId = Number(localStorage.getItem("bindingUserId")); var destroyRoomMsg = { request: "destroy", room: bindingUserId, permanent: false }; sessionHandle.send({ message: destroyRoomMsg, success: function (msg) { if (msg != null && msg != undefined) { onMessage(msg, null); } }, error: function (err) { if (roomCallback != null) { roomCallback.error(err); roomCallback = null; } }, }); }; // 消息回调 function onConsentDialog(on) { Janus.debug("publish: consent dialog should be " + (on ? "on" : "off")); } function onMediaState(medium, on) { Janus.debug("publish: janus " + (on ? "started" : "stopped") + " receiving our " + medium); } function onWebrtcState(on) { Janus.log("publish: webrtc connection state: " + (on ? "opened" : "closed")); } function onMessage(msg, jsep) { var event = msg["videoroom"]; console.log(msg, 11); Janus.log("publish: on recv notify event: " + msg); Janus.log("publish: Event: " + event); if (event != undefined && event != null) { if (event == "created") { var roomId = msg["room"]; Janus.log("publish: successfully create room: " + roomId); if (roomCallback != null) { roomCallback.success(roomId); roomCallback = null; } sessionDestroy(); } else if (event == "destroyed") { console.log(event, "event"); var roomId = msg["room"]; Janus.warn("publish: room: " + roomId + " is destroyed"); if (roomCallback != null) { roomCallback.success(roomId); roomCallback = null; } sessionDestroy(); } else if (event == "joined") { selfUserId = msg["id"]; selfVideoId = msg["private_id"]; publishers = msg["publishers"]; console.log(selfUserId, 11, selfVideoId, 111); Janus.log("publish: successfully joined room " + msg["room"] + " with id " + selfUserId); if (msg["publishers"] !== undefined && msg["publishers"] !== null) { var publishers = msg["publishers"]; var room = msg["room"]; bus.$emit("pull_video_joined", publishers); publishLocalVideo(); } openVideoOptions.success(selfUserId, selfVideoId); } else if (event == "event") { if (msg["publishers"] !== undefined && msg["publishers"] !== null) { var publishers = msg["publishers"]; var room = msg["room"]; bus.$emit("pull_video_message_new_remote", publishers); } else if (msg["videoroom"] == "event" && msg["leaving"] != undefined) { bus.$emit("remote_HangUp", msg["leaving"]); //当有用户离开时进入这里 } else if (msg["unpublished"] !== undefined && msg["unpublished"] !== null) { var unpublished = msg["unpublished"]; if (typeof unpublished == "string" || unpublished == selfUserId) { Janus.log("publish: unpublisher userId:" + selfUserId + " videoId:" + selfVideoId + " result:" + unpublished); var leaveMsg = { request: "leave" }; sessionHandle.send({ message: leaveMsg }); } else if (typeof undefined == "number") { Janus.log("publish: unpublisher userId:" + selfUserId + " videoId:" + selfVideoId + " unpublished:" + unpublished); } } else if (msg["leaving"] != undefined && msg["leaving"] != null) { var leaving = msg["leaving"]; if (typeof leaving == "string" || leaving == selfUserId) { Janus.log("publish: leaving room:" + openVideoOptions.roomId + " result: " + leaving); sessionDestroy(); } else if (typeof undefined == "number") { Janus.log("publish: leaving room:" + openVideoOptions.roomId + " leaving: " + leaving); } } else if (msg["error"] !== undefined && msg["error"] !== null) { var errMsg = msg["error"]; if (msg["error_code"] == 426) { Janus.error("publish: server not found room :" + currentRoomId); } else { Janus.error("publish: other error: " + errMsg); } if (openVideoOptions != null) { openVideoOptions.error(errMsg); openVideoOptions = null; } if (roomCallback != null) { roomCallback.error(errMsg); roomCallback = null; } sessionDestroy(); } } } if (jsep !== undefined && jsep !== null) { // 检查视频是否被拒绝 Janus.debug("publish: handling sdp as well."); Janus.debug(jsep); sessionHandle.handleRemoteJsep({ jsep: jsep }); var audio = msg["audio_codec"]; if (localVideoStream && localVideoStream.getAudioTracks() && localVideoStream.getAudioTracks().length > 0 && !audio) { Janus.warn("publish: our audio stream has been rejected, viewers won't hear us"); } var video = msg["video_codec"]; if (localVideoStream && localVideoStream.getVideoTracks() && localVideoStream.getVideoTracks().length > 0 && !video) { Janus.warn("publish: our video stream has been rejected, viewers won't see us"); } } } // 禁麦 this.getLocalAudioEnabledTrack = function () { if (localstreamAudio) { localstreamAudio.enabled = false; bus.$emit("local_audio_micphone", false); } else { Message("请先开启会议"); } }; //取消禁麦 this.getLocalAudioTrack = function () { if (localstreamAudio) { localstreamAudio.enabled = true; bus.$emit("local_audio_micphone", true); } else { Message("请先开启会议"); } }; // 关闭摄像头 this.getLocalCameraEnabledTrack = function () { if (localVideoStream) { // 假设你要关闭视频流 localVideoStream.getTracks().forEach((track) => { if (track.kind === "video") { track.enabled = false; // 关闭视频流 } }); bus.$emit("local_video_camera", false); // 更新应用状态或通知其他组件 } else { Message("请先开启会议"); } }; // 打开摄像头 this.getLocalCameraTrack = function () { // 打开本地摄像头 if (localVideoStream) { // 遍历所有轨道,并启用视频轨道 localVideoStream.getTracks().forEach((track) => { if (track.kind === "video") { track.enabled = true; // 启用视频流 } }); bus.$emit("local_video_camera", true); // 更新应用状态或通知其他组件 } else { // 如果本地摄像头流不存在,创建一个新的视频流 navigator.mediaDevices .getUserMedia({ video: true }) .then((stream) => { localVideoStream = stream; // 赋值给本地摄像头流变量 // 遍历所有轨道,并启用视频轨道 localVideoStream.getTracks().forEach((track) => { if (track.kind === "video") { track.enabled = true; // 启用视频流 } }); bus.$emit("local_video_camera", true); // 更新应用状态或通知其他组件 }) .catch((error) => { Message(`获取摄像头失败: ${error.message}`); }); } }; function onLocalStream(stream) { console.log(stream, "localstream"); Janus.debug("publish: got a local video stream"); Janus.debug(stream); console.log(stream.getAudioTracks()[0], 11); localVideoStream = stream; localstreamAudio = stream.getAudioTracks()[0]; // localstreamAudio.enabled = false if (openVideoOptions.videoWnd != undefined && openVideoOptions.videoWnd != null) { Janus.attachMediaStream(openVideoOptions.videoWnd, stream); } } function onRemoteStream(stream) { // 流发送者不会收到此通知 } function onCleanup() { localVideoStream = null; Janus.log("publish: got a cleanup notification: we are unpublished now..."); sessionDestroy(); } function publishLocalVideo() { console.log(openVideoOptions, 11); sessionHandle.createOffer({ media: { audioRecv: false, videoRecv: false, audioSend: openVideoOptions.isAudio, videoSend: openVideoOptions.isVideo, video: localVideoRatio, }, // Publishers are sendonly simulcast: false, simulcast2: false, success: function (jsep) { Janus.debug("publish: got publisher sdp."); Janus.debug(jsep); var publish = { request: "configure", audio: openVideoOptions.isAudio, video: openVideoOptions.isVideo }; publish["audiocodec"] = localAudioCodec; publish["videocodec"] = localVideoCodec; sessionHandle.send({ message: publish, jsep: jsep }); }, error: function (error) { Janus.error("publish: webrtc error:", error); if (openVideoOptions.isAudio) { if (!openVideoOptions.isVideo) { openVideoOptions.error(error); } else { openVideoOptions.isAudio = false; publishLocalVideo(); } } else { // 初始化webrtc错误 openVideoOptions.error(error); } }, }); } // 会话销毁 function sessionDestroy() { var sh = sessionHandle; sessionHandle = null; if (sh != undefined && sh != null) { sh.detach({ success: function () { libraryDestroy(); }, error: function (err) { Janus.log("publish: session destroy fail: " + err); libraryDestroy(); }, }); // openVideoOptions.videoClose(); } else { libraryDestroy(); } } function libraryDestroy() { var lh = libraryHandle; libraryHandle = null; if (lh != undefined && lh != null) { lh.destroy(); } } } export function SubscibeVideo() { var libraryHandle = null; var sessionHandle = null; var sessionId = generateUUID(); // 视频相关变量 var openVideoOptions = null; var remoteVideoStream = null; // 初始化 this.init = function (options) { libraryHandle = new Janus({ server: serverInfo, success: function () { libraryHandle.attach({ plugin: "janus.plugin.videoroom", opaqueId: sessionId, success: function (pluginHandle) { sessionHandle = pluginHandle; Janus.debug("subscibe: video server load success."); options.success(); }, error: function (err) { Janus.error("subscibe: video server load fail:" + err); options.error(err); }, consentDialog: onConsentDialog, mediaState: onMediaState, webrtcState: onWebrtcState, onmessage: onMessage, onlocalstream: onLocalStream, onremotestream: onRemoteStream, oncleanup: onCleanup, }); }, error: function (err) { Janus.error("subscibe: load video library fail:" + err); options.error(err); }, destroyed: function () { Janus.debug("subscibe: video library is destoryed."); }, }); }; // 订阅视频 this.openRemoteVideo = function (options) { console.log(options, "options"); openVideoOptions = options; var subscibeMsg = { request: "join", room: options.roomId, ptype: "subscriber", feed: options.userId, private_id: options.videoId, offer_video: options.isVideo, offer_audio: options.isAudio, }; sessionHandle.send({ message: subscibeMsg }); }; this.getRemoteVideoStream = function () { return remoteVideoStream; }; // 踢出 (this.kickout = function (options) { console.log(options, 22); var kick = { request: "kick", secret: "", room: options.room, id: options.uid, }; sessionHandle.send({ message: kick }); }), (this.closeRemoteVideo = function () { var leaveMsg = { request: "leave" }; sessionHandle.send({ message: leaveMsg }); }); this.destroyRoom = function (callback) { console.log(11123123); let bindingUserId = Number(localStorage.getItem("bindingUserId")); console.log(bindingUserId); var destroyRoomMsg = { request: "destroy", room: bindingUserId, permanent: false }; sessionHandle.send({ message: destroyRoomMsg, success: function (msg) { if (msg != null && msg != undefined) { onMessage(msg, null); } }, error: function (err) { if (roomCallback != null) { roomCallback.error(err); roomCallback = null; } }, }); }; // 消息回调 function onConsentDialog(on) { Janus.debug("subscibe: consent dialog should be " + (on ? "on" : "off")); } function onMediaState(medium, on) { Janus.log("subscibe: janus " + (on ? "started" : "stopped") + " receiving our " + medium); } function onWebrtcState(on) { Janus.log("subscibe: webrtc connection state: " + (on ? "opened" : "closed")); } function onMessage(msg, jsep) { var event = msg["videoroom"]; Janus.log("subscibe: on recv notify event: " + msg); Janus.log("subscibe: Event: " + event); if (msg["error"] !== undefined && msg["error"] !== null) { Janus.error("subscibe: join roomId:" + openVideoOptions.roomId + " fail: " + msg["error"]); openVideoOptions.error("subscibe: remote videoId:" + openVideoOptions.videoId + " not exist."); } else if (event != undefined && event != null) { if (event == "attached") { Janus.log("subscibe: successfully attached to room: " + openVideoOptions.roomId + " feed: " + openVideoOptions.VideoId); } else if (event == "event") { if (msg["leaving"] !== undefined && msg["leaving"] !== null) { // 视频发布者停止发布了 var leaving = msg["leaving"]; Janus.log("subscibe: publisher left: " + leaving + " leaving."); if (leaving == openVideoOptions.videoId) { sessionDestroy(); } } if (msg["left"] != undefined && msg["left"] != null) { Janus.log("subscibe: leave roomId:" + openVideoOptions.roomId); sessionDestroy(); } } else { Janus.log("subscibe: event: " + event + " un handler"); } } if (jsep !== undefined && jsep !== null) { // Janus.log("subscibe: handling SDP..."); Janus.log(jsep); sessionHandle.createAnswer({ jsep: jsep, media: { audioSend: false, videoSend: false }, success: function (jsep) { Janus.debug("subscibe: get SDP!"); Janus.debug(jsep); var body = { request: "start", room: openVideoOptions.roomId }; sessionHandle.send({ message: body, jsep: jsep }); openVideoOptions.success(); }, error: function (err) { Janus.error("subscibe: webrtc error: ", err); openVideoOptions.error(err); }, }); } } function onLocalStream(stream) { // 流订阅者不会收到此通知 } function onRemoteStream(stream) { console.log(stream); Janus.debug("subscibe: got a remote video stream"); Janus.debug(stream); remoteVideoStream = stream; console.log(openVideoOptions.videoWnd, 1111111111111111); if (openVideoOptions.videoWnd != undefined && openVideoOptions.videoWnd != null) { Janus.attachMediaStream(openVideoOptions.videoWnd, stream); } } function onCleanup() { remoteVideoStream = null; Janus.log("subscibe: got a cleanup notification: we cannot view remote video."); sessionDestroy(); } // 会话销毁 function sessionDestroy() { var sh = sessionHandle; sessionHandle = null; if (sh != undefined && sh != null) { sh.detach({ success: function () { libraryDestroy(); }, error: function (err) { Janus.log("subscibe: session destroy fail: " + err); libraryDestroy(); }, }); // openVideoOptions.videoClose(); } else { libraryDestroy(); } } function libraryDestroy() { var lh = libraryHandle; libraryHandle = null; if (lh != undefined && lh != null) { lh.destroy(); } } }