home.js 13.6 KB
new Vue({
	el: '#app',
	data(){
		return {
			roomName: '吴波波',
			roomId: 1008611,
			pin: '123456',
			bitrate: 512000,
			iconList: [  
			{sign: '#iconicon-microphone-on',name: '麦克风', status: 1},
			{sign: '#iconicon-volume',name: '声音', status: 1},
			{sign: '#iconicon-camera-on',name: '摄像头', status: 1},
			{sign: '#iconicon-sharescreen',name: '屏幕分享', status: 0},
			{sign: '#iconicon-share',name: '邀请加人', status: 0},
			{sign: '#iconicon-stop',name: '结束', status: 0}
			],  //0-未使用  1-使用中
			server: 'https://janusctest.uccc.cc:24000/janus',
			janus: '',
			opaqueId: "videoroomtest-"+Janus.randomString(12),
			handle: '',
			feeds: []
		}
	},
	created() {
		this.initVideo();
	},
	methods: {
		initVideo() {
			let that = this;
			// //初始化
			Janus.init({debug: "all", callback: function() {
					if(!Janus.isWebrtcSupported()) {
						bootbox.alert("No WebRTC support... ");
						return;
					}
					that._data.janus = new Janus({
						server: that._data.server,
						success: function() {
							that.creatAttach();
						},
						error: function(error) {
							Janus.error(error);
							bootbox.alert(error, function() {
								window.location.reload();
							});
						},
						destroyed: function() {
							window.location.reload();
						}
					})
				}
			})			
		},
		//创建会话
		creatAttach() {
			let that = this;
			var janus = that._data.janus;
			var feeds = that._data.feeds;
			var room = that._data.roomId;
			var pin = that._data.pin;
			var bitrate = that._data.bitrate;
			janus.attach({
				plugin: "janus.plugin.videoroom",
				opaqueId: that._data.opaqueId,
				success: function(pluginHandle) {
					that._data.handle = pluginHandle;
					Janus.log("Plugin attached! (" + that._data.handle.getPlugin() + ", id=" + that._data.handle.getId() + ")");
					that.registerUsername(room, pin);
				},
				error: function(error) {
					Janus.error("  -- Error attaching plugin...", error);
					bootbox.alert("Error attaching plugin... " + error);
				},
				consentDialog: function(on) {
					Janus.debug("Consent dialog should be " + (on ? "on" : "off") + " now");
					if(on) {
					}
				},
				mediaState: function(medium, on) {
					Janus.log("Janus " + (on ? "started" : "stopped") + " receiving our " + medium);
				},
				webrtcState: function(on) {
					Janus.log("Janus says our WebRTC PeerConnection is " + (on ? "up" : "down") + " now");
					if(!on) return;			
					that._data.handle.send({"message": { "request": "configure", "bitrate": bitrate }});	
				},
				onmessage: function(msg, jsep) {
					console.log(msg)
					Janus.debug(" ::: Got a message (publisher) :::");
					Janus.debug(msg);
					var event = msg["videoroom"];
					Janus.debug("Event: " + event);
					if(event != undefined && event != null) {
						if(event === "joined") {
							myid = msg["id"];
							mypvtid = msg["private_id"];
							Janus.log("Successfully joined room " + msg["room"] + " with ID " + myid);
							that.publishOwnFeed(true);
							if(msg["publishers"] !== undefined && msg["publishers"] !== null) {
								var list = msg["publishers"];
								Janus.debug("Got a list of available publishers/feeds:");
								Janus.debug(list);
								for(var f in list) {
									var id = list[f]["id"];
									var display = list[f]["display"];
									var audio = list[f]["audio_codec"];
									var video = list[f]["video_codec"];
									Janus.debug("  >> [" + id + "] " + display + " (audio: " + audio + ", video: " + video + ")");
									that.newRemoteFeed(id, display, audio, video);
								}
							}
						} else if(event === "destroyed") {
							Janus.warn("The room has been destroyed!");
							bootbox.alert("The room has been destroyed", function() {
							   window.location.reload();
							});
						} else if(event === "event") {
						if(msg["publishers"] !== undefined && msg["publishers"] !== null) {
							var list = msg["publishers"];
							Janus.debug("Got a list of available publishers/feeds:");
							Janus.debug(list);
							for(var f in list) {
								var id = list[f]["id"];
								var display = list[f]["display"];
								var audio = list[f]["audio_codec"];
								var video = list[f]["video_codec"];
								Janus.debug("  >> [" + id + "] " + display + " (audio: " + audio + ", video: " + video + ")");
								that.newRemoteFeed(id, display, audio, video);
							}
						} else if(msg["leaving"] !== undefined && msg["leaving"] !== null) {
							var leaving = msg["leaving"];
							Janus.log("Publisher left: " + leaving);
							var remoteFeed = null;
							for(var i=1; i<6; i++) {
								if(feeds[i] != null && feeds[i] != undefined && feeds[i].rfid == leaving) {
									remoteFeed = feeds[i];
									break;
								}
							}
							if(remoteFeed != null) {
								Janus.debug("Feed " + remoteFeed.rfid + " (" + remoteFeed.rfdisplay + ") has left the room, detaching");
								$('#remote'+remoteFeed.rfindex).empty().hide();
								$('#videoremote'+remoteFeed.rfindex).empty();
								feeds[remoteFeed.rfindex] = null;
								remoteFeed.detach();
							}
						} else if(msg["unpublished"] !== undefined && msg["unpublished"] !== null) {
								var unpublished = msg["unpublished"];
								Janus.log("Publisher left: " + unpublished);
								if(unpublished === 'ok') {
									that._data.handle.hangup();
									return;
								}
								var remoteFeed = null;
								for(var i=1; i<6; i++) {
									if(feeds[i] != null && feeds[i] != undefined && feeds[i].rfid == unpublished) {
										remoteFeed = feeds[i];
										break;
								   }
								}
								if(remoteFeed != null) {
									Janus.debug("Feed " + remoteFeed.rfid + " (" + remoteFeed.rfdisplay + ") has left the room, detaching");
									$('#remote'+remoteFeed.rfindex).empty().hide();
									$('#videoremote'+remoteFeed.rfindex).empty();
									feeds[remoteFeed.rfindex] = null;
									remoteFeed.detach();
								}
						} else if(msg["error"] !== undefined && msg["error"] !== null) {
								if(msg["error_code"] === 426) {
								}
						}
					}
						if(jsep !== undefined && jsep !== null) {
							Janus.debug("Handling SDP as well...");
							Janus.debug(jsep);
							that._data.handle.handleRemoteJsep({jsep: jsep});
							var audio = msg["audio_codec"];
							if(mystream && mystream.getAudioTracks() && mystream.getAudioTracks().length > 0 && !audio) {
								toastr.warning("Our audio stream has been rejected, viewers won't hear us");
							}
							var video = msg["video_codec"];
							if(mystream && mystream.getVideoTracks() && mystream.getVideoTracks().length > 0 && !video) {
								toastr.warning("Our video stream has been rejected, viewers won't see us");
							}
						}
					}
				},
				onlocalstream: function(stream) {
					Janus.debug(" ::: Got a local stream :::");
					mystream = stream;
					Janus.debug(stream);
					Janus.attachMediaStream($('#mainVideo_html5_api').get(0), stream);

					var videoTracks = stream.getVideoTracks();
					if(videoTracks === null || videoTracks === undefined || videoTracks.length === 0) {						
					} 
				},
				onremotestream: function(stream) {
				},
				oncleanup: function() {
					Janus.log(" ::: Got a cleanup notification: we are unpublished now :::");
				}	
			})
		},
		registerUsername(room,pin) {
		   var register = { "request": "join", "room": room, "ptype": "publisher", "display": "hhh", "pin": pin };
		   this._data.handle.send({"message": register});
	   },
	   publishOwnFeed(useAudio) {
			var doSimulcast = (this.getQueryStringValue("simulcast") === "yes" || this.getQueryStringValue("simulcast") === "true");
			var doSimulcast2 = (this.getQueryStringValue("simulcast2") === "yes" || this.getQueryStringValue("simulcast2") === "true");
			var canshu = this._data.handle;
			canshu.createOffer({
			media: { audioRecv: false, videoRecv: false, audioSend: useAudio, videoSend: true },
			simulcast: doSimulcast,
			simulcast2: doSimulcast2,
			success: function(jsep) {
				Janus.debug("Got publisher SDP!");
				Janus.debug(jsep);
				var publish = { "request": "configure", "audio": useAudio, "video": true };
				canshu.send({"message": publish, "jsep": jsep});
			},
			error: function(error) {
				Janus.error("WebRTC error:", error);
				if (useAudio) {
					this.publishOwnFeed(false);
				} else {
					bootbox.alert("WebRTC error... " + JSON.stringify(error));
				}
			}
		});
	},
	getQueryStringValue(name) {
		name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
		var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
		results = regex.exec(location.search);
		return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
	},
	newRemoteFeed(id, display, audio, video) {
		var remoteFeed = null;
		let that = this;
		var janus = that._data.janus;
		var feeds = that._data.feeds;
		var room = that._data.roomId;
		var pin = that._data.pin;
		janus.attach(
			{
				plugin: "janus.plugin.videoroom",
				opaqueId: that._data.opaqueId,
				success: function(pluginHandle) {
					remoteFeed = pluginHandle;
					remoteFeed.simulcastStarted = false;
					Janus.log("Plugin attached! (" + remoteFeed.getPlugin() + ", id=" + remoteFeed.getId() + ")");
					Janus.log("  -- This is a subscriber");
					var subscribe = { "request": "join", "room": room, "ptype": "subscriber", "feed": id, "private_id": mypvtid, "pin": pin };
					if(Janus.webRTCAdapter.browserDetails.browser === "safari" &&
							(video === "vp9" || (video === "vp8" && !Janus.safariVp8))) {
						if(video)
							video = video.toUpperCase()
						toastr.warning("Publisher is using " + video + ", but Safari doesn't support it: disabling video");
						subscribe["offer_video"] = false;
					}
					remoteFeed.videoCodec = video;
					remoteFeed.send({"message": subscribe});
				},
				error: function(error) {
					Janus.error("  -- Error attaching plugin...", error);
					bootbox.alert("Error attaching plugin... " + error);
				},
				onmessage: function(msg, jsep) {
					console.log(msg)
					Janus.debug(" ::: Got a message (subscriber) :::");
					Janus.debug(msg);
					var event = msg["videoroom"];
					Janus.debug("Event: " + event);
					if(msg["error"] !== undefined && msg["error"] !== null) {
						bootbox.alert(msg["error"]);
					} else if(event != undefined && event != null) {
						if(event === "attached") {
							for(var i=1;i<6;i++) {
								if(feeds[i] === undefined || feeds[i] === null) {
									feeds[i] = remoteFeed;
									remoteFeed.rfindex = i;
									break;
								}
							}
							remoteFeed.rfid = msg["id"];
							remoteFeed.rfdisplay = msg["display"];
							Janus.log("Successfully attached to feed " + remoteFeed.rfid + " (" + remoteFeed.rfdisplay + ") in room " + msg["room"]);
						} else if(event === "event") {
							var substream = msg["substream"];
							var temporal = msg["temporal"];
							if((substream !== null && substream !== undefined) || (temporal !== null && temporal !== undefined)) {
								if(!remoteFeed.simulcastStarted) {
									remoteFeed.simulcastStarted = true;
									addSimulcastButtons(remoteFeed.rfindex, remoteFeed.videoCodec === "vp8" || remoteFeed.videoCodec === "h264");
								}
								updateSimulcastButtons(remoteFeed.rfindex, substream, temporal);
							}
						} else {
						}
					}
					if(jsep !== undefined && jsep !== null) {
						Janus.debug("Handling SDP as well...");
						Janus.debug(jsep);
						remoteFeed.createAnswer(
							{
								jsep: jsep,
								media: { audioSend: false, videoSend: false },
								success: function(jsep) {
									Janus.debug("Got SDP!");
									Janus.debug(jsep);
									var body = { "request": "start", "room": room };
									remoteFeed.send({"message": body, "jsep": jsep});
								},
								error: function(error) {
									Janus.error("WebRTC error:", error);
									bootbox.alert("WebRTC error... " + JSON.stringify(error));
								}
							});
					}
				},
				webrtcState: function(on) {
					Janus.log("Janus says this WebRTC PeerConnection (feed #" + remoteFeed.rfindex + ") is " + (on ? "up" : "down") + " now");
				},
				onlocalstream: function(stream) {
				},
				onremotestream: function(stream) {
					Janus.debug("Remote feed #" + remoteFeed.rfindex);
					Janus.attachMediaStream($('#sideVideo'+remoteFeed.rfindex + '_html5_api').get(0), stream);
				},
				oncleanup: function() {
					Janus.log(" ::: Got a cleanup notification (remote feed " + id + ") :::");
					remoteFeed.simulcastStarted = false;
				}
			});
	},
	myOption(index) {
		console.log(index);
		if(this.iconList[index].status === 1)  {
			this.iconList[index].status = 0;
			switch(index)
			{
			    case 0:
			    	this.iconList[index].sign = '#iconicon-microphone-off' 
		    		//操控	
			    break;
			    case 1:
			    	this.iconList[index].sign = '#iconicon-volume-off' 
			    break;
			    case 2:
			    	this.iconList[index].sign = '#iconicon-camera-off' 
			    break;
			    case 3:
			    	this.publicNotify('关闭屏幕分享..')
			    break;
			    case 4:
			    	this.publicNotify('关闭屏幕分享..')
				break;
				case 5:
					this.janus.destroy()
					location.href ="./../index.html"
					break;
			}
		}else {
			if (index != 4) {
				this.iconList[index].status = 1;	
			}
			switch(index)
			{
			    case 0:
			    	this.iconList[index].sign = '#iconicon-microphone-on' 
		    		//操控	
			    break;
			    case 1:
			    	this.iconList[index].sign = '#iconicon-volume' 
			    break;
			    case 2:
			    	this.iconList[index].sign = '#iconicon-camera-on'
			    break;
			    case 3:
			    	this.publicNotify('开启屏幕分享..')
			    break;
			    case 4:
			    	this.publicNotify('开启..')
				break;
				case 5:
					this.janus.destroy()
					location.href ="./../index.html"
					break;
			}
		}
	},
	publicNotify(msg) {
		this.$notify({
	      title: 'Tip',
	      message: msg
	    });
	}
	}
})