当前位置: 首页 > 工具软件 > Kurento > 使用案例 >

Kurento 客户端

岳英锐
2023-12-01
/*
* 该API配合服务器端API模块使用
* hhMedia/svr/nodesvr.js
* */


/*

 */


function TKmsClient(){
    this.config={
        apiUrl :"https://wss.hhdata.cn:20020/hhapi" ,
        wsUrl:"wss://wss.hhdata.cn:20020/hhws" ,
        kurentUrl:"wss://wss.hhdata.cn:8433/kurento",
        defaultPeerOptions:{
            configuration: {
                "iceServers":[
                    {
                        urls:"stun:223.68.161.139:3478"
                    },
                    {
                        urls:["turn:223.68.161.139:3478"],
                        username:"kurento",
                        credential: "kurento"
                    }
                ]
            },
            mediaConstraints:{
               audio: true,
               video: {width: {exact: 1280}, height: {exact: 720}}
            },
            localVideo: null ,
            remoteVideo: null
        }
    };
    this.kmsPeerTypes={
        send:kurentoUtils.WebRtcPeer.WebRtcPeerSendonly,
        rec:kurentoUtils.WebRtcPeer.WebRtcPeerRecvonly,
        sendRec:kurentoUtils.WebRtcPeer.WebRtcPeerSendrecv
    }
    this.events={
        onWsOpen: function (ws) {} ,
        onWsClose: function (ws) {} ,
        onWsMsg: function (ws, msg) {} ,
    };
    this.objs={
        kurentClient:null,
        ws:null
    };
    this.callBack = function( callback , ps){
        if( callback){
            try{
                callback(ps);
            }
            catch (er) {
                console.log(er)
            }
        }
    }
}
TKmsClient.prototype.callApi = function( ac , data , callback){
    var me = this;
    try{
        var aUrl = me.config.apiUrl+"/"+ac+"?tm="+( new Date()).getTime().toString();
        $.ajax({
            url: aUrl ,
            data : data ,
            type:"POST",
            success: function (resData) {
                try{
                    var res = JSON.parse(resData);
                    me.callBack(callback , res);
                }
                catch (erSuccess) {
                    console.log(erSuccess);
                }
            },
            error: function (er0, er1  ) {
                try{
                    var res = JSON.parse(resData);
                    me.callBack(callback , {er0:er0 , er1:er1});
                }
                catch (erSuccess) {
                    console.log(erSuccess);
                }
            }
        })
    }
    catch (er) {
        console.log(er);
    }
};
TKmsClient.prototype.dbQuery = function( appName , key , ps , callback){
    var me = this;
    try{
        var data ={
            app:appName ,
            key: key ,
            ps:JSON.stringify(ps)
        };
        var ac ="queryArray";
        me.callApi(ac , data , callback);
    }
    catch (er) {
        console.log(er);
    }
};
TKmsClient.prototype.dbQueryDict = function( appName , key , ps , callback){
    var me = this;
    try{
        var data ={
            app:appName ,
            key: key ,
            ps:JSON.parse(ps)
        };
        var ac ="queryDict";
        me.callApi(ac , data , callback);
    }
    catch (er) {
        console.log(er);
    }
};
TKmsClient.prototype.openWs = function( onOpen , onClose , onMsg ){
    var me = this;
    try{
        var ws = new WebSocket(me.config.wsUrl);
        ws.onopen = function(){
          //当WebSocket创建成功时,触发onopen事件
           console.log("wss is openned!");
            if( onOpen){
                try{
                    onOpen(ws);
                }
                catch (e1) {
                    console.log(e1);
                }
            }
        };
        ws.onerror = function(){
          try{
                ws.close();
            }
            catch (e1) {
                console.log(e1);
            }
        };
        ws.onclose = function(){
          try{
                if( onClose){
                    try{
                        onClose(ws);
                    }
                    catch (e1) {
                        console.log(e1);
                    }
                }
            }
            catch (e1) {
                console.log(e1);
            }
        };
        ws.onmessage = function(e){
          //当客户端收到服务端发来的消息时,触发onmessage事件,参数e.data包含server传递过来的数据
          console.log(e.data);
            try{
                var msg = JSON.parse(e.data);
                if( msg.id == "s2cSetWsId" ){
                    ws.wsId = msg.body.wsId;
                }
                else  if( onMsg){
                    onMsg(ws,msg);
                }
            }
            catch (err) {
                console.log(err);
            }
        };
        me.objs.ws = ws;
    }
    catch (er) {
        console.log(er);
    }
};
TKmsClient.prototype.wsSendMsg = function( id , body ){
    var me = this;
    try{
        if( me.objs.ws){
            me.objsws.send(JSON.parse({
                id:id,
                body:body
            }));
        }
    }
    catch (er) {
        console.log(er);
    }
};
TKmsClient.prototype.wsSetInfo = function( key, data ){
    var me = this;
    try{
        me.wsSendMsg("setWsInfo",{wsId: me.objs.ws.wsId ,  key:key, data:data});
    }
    catch (er) {
        console.log(er);
    }
};
TKmsClient.prototype.wsGetInfo = function( key, callback ){
    var me = this;
    try{
        me.callApi("getWsInfo",{wsId: me.objs.ws.wsId, key:key}, callback);
    }
    catch (er) {
        console.log(er);
    }
};
TKmsClient.prototype.wsMutilcast = function( groupId , data , callback ){
    var me = this;
    try{
        me.wsSendMsg("wsMutilcast",{groupId:groupId , data:data});
    }
    catch (er) {
        console.log(er);
    }
};
TKmsClient.prototype.wsSetGroup = function( groupId , callback ){
    var me = this;
    try{
        me.wsSendMsg("wsMutilcast",{wsId: me.objs.ws.wsId,  groupId:groupId , data:data});
    }
    catch (er) {
        console.log(er);
    }
};
TKmsClient.prototype.ioSetData = function(  key , data , callback ){
    var me = this;
    try{
        me.callApi('setData',{key:key, data:data}, callback);
    }
    catch (er) {
        console.log(er);
    }
};
TKmsClient.prototype.ioGetData = function( key , callback ){
    var me = this;
    try{
        me.callApi('getData',{key:key, data:data}, callback);
    }
    catch (er) {
        console.log(er);
    }
};
TKmsClient.prototype.kmsGetClient = function( callback){
    var me = this;
    try{
        if (me.objs.kurentClient){
            me.callBack(callback, {res:me.objs.kurentClient, error:null});
        }
        else {
            kurentoClient(me.config.kurentUrl, function (error, client) {
                if (client) {
                    me.objs.kurentClient = client;
                }
                me.callBack(callback, {res:client, error:error});
            });
        }
    }
    catch (er) {
        console.log(er);
    }
};
TKmsClient.prototype.kmsBindPeerAndEndpoint = function ( peer , endpoint,  callback) {
    var me = this;
    try{
        if( endpoint && peer){
            peer.generateOffer(function (errorPeerGenerateOffer, sdpOffer) {
                if( errorPeerGenerateOffer && callback){
                    callback( errorPeerGenerateOffer , null);
                }
                else {
                    endpoint.processOffer(sdpOffer, function (errorSdpOffer, sdpAnswer) {
                        if (errorSdpOffer && callback) {
                            console.log("process sdpOffer error.", errorSdpOffer)
                            callback(errorSdpOffer, null);
                        } else {
                            me.setCandidateEvent(peer , endpoint);
                            peer.processAnswer(sdpAnswer);
                            endpoint.gatherCandidates(function (errorGatherCandidates) {
                                if (errorGatherCandidates && callback) {
                                    console.log('webRtcPoint gatherCandidates error.', errorGatherCandidates)
                                    callback(errorGatherCandidates, null);
                                }
                                else{
                                    peer.endpoint = endpoint;
                                    endpoint.peer = peer;
                                    if( callback) {
                                        callback(null, {endpoint: endpoint, peer: peer});
                                    }
                                }
                            });
                        }
                    });
                }
            });
        }
        else {
            if( callback) {
                callback({ error:"endPoint or peer is null."}, null);
            }
        }
    }
    catch (er) {
        console.log(er,"bindPeerAndEndpoint error.");
    }
};
TKmsClient.prototype.setCandidateEvent = function( peer , endpoint   ){
    var me = this;
    try{
        if( peer && endpoint){
            endpoint.on('OnIceCandidate', function(event) {
                var candidate = event.candidate;
                peer.addIceCandidate(candidate);
                console.log('candidate w->p')
            });
            peer.on('icecandidate', function(candidate){
                var iceCandidate = kurentoClient.register.complexTypes.IceCandidate(candidate);
                endpoint.addIceCandidate(iceCandidate);
                console.log('candidate p->w')

            });
        }
    }
    catch (er) {
        console.log(er,"setCandidateEvent error.");
    }
};

TKmsClient.prototype.kmsFreeEndpoint = function ( endpoint) {
    var me = this;
    try{
        if( endpoint  ){
            endpoint.release(function (err) {
                console.log('free endpoint.')
            });
            endpoint = null;
        }
    }
    catch (er) {
        console.log(er,"freeEndpoint error.");
    }
};
TKmsClient.prototype.kmsFreePeer = function ( peer) {
    var me = this;
    try{
        if( peer  ){
            if( peer.peerConnection){
                peer.peerConnection.close();
            }
            peer.dispose();
            peer = null;
        }
    }
    catch (er) {
        console.log(er,"freePeer error.");
    }
};
TKmsClient.prototype.kmsCreatePeer = function ( localVideo , remoteVideo , sendSource, beforeCreateCallback ,callback) {
    var me = this;
    try{
        var opts= JSON.parse(JSON.stringify(me.config.defaultPeerOptions));

        var localFlag = false;
        if( localVideo && (localVideo!=null)){
            opts.localVideo = localVideo;
            localFlag = true;
        }
        var remoteFlag = false;
        if( remoteVideo && (remoteVideo!=null)){
            opts.remoteVideo = remoteVideo;
            remoteFlag = true;
        }
        if( sendSource=="window" || sendSource=="screen" || sendSource=="desktop"){
            opts.sendSource = sendSource;
        }
        var createFactory = null;
        if( (localFlag)&&(!remoteFlag) ){
            createFactory = kurentoUtils.WebRtcPeer.WebRtcPeerSendonly;
        }
        else  if( (!localFlag)&&(remoteFlag) ){
            createFactory = kurentoUtils.WebRtcPeer.WebRtcPeerRecvonly;
        }
        else  if( (localFlag)&&(remoteFlag) ){
            createFactory = kurentoUtils.WebRtcPeer.WebRtcPeerSendrecv;
        }
        if( beforeCreateCallback){
            try{
                beforeCreateCallback(opts);
            }
            catch (e0) {
                console.log(e0)
            }
        }
        var res ={
            error:null,
            peer:null
        }
        if( createFactory){
            var peer = createFactory(opts , function (err) {
                //opts.video ={ width:1280, height:720};
                var peerId = "peer_"+( new Date()).getTime().toString();
                peer.clientId = peerId;
                peer.peerConnection.addEventListener('iceconnectionstatechange', function(event){
                    if( event){
                        console.log('create peer error.', event);
                    }
                    else {
                        if (peer && peer.peerConnection) {
                            console.log("oniceconnectionstatechange -> " + peer.peerConnection.iceConnectionState);
                            console.log('icegatheringstate -> ' + peer.peerConnection.iceGatheringState);
                        }
                    }
                });
                res.error = err;
                res.peer = peer;
                me.callBack(callback, res);
            })
        }
        else{
            res.error ="createFactory error.";
            me.callBack(callback, res);
        }
    }
    catch (er) {
        console.log(er,"createPeer error.");
    }
};
TKmsClient.prototype.kmsGetAvDevices = function ( callback) {
    var me = this;
    try{
        var res ={};
/*
        navigator.mediaDevices.enumerateDevices(function (devs) {

            for( var i=0;i<devs.length;i++){
                var item = devs[i];
                if( !res[item.kind]){
                    res[item.kind]=[]
                }
                res[item.kind].push(item);
            }
            console.log(res);
            if (callback){
                callback({error: null, devices:res});
            }
        });
*/
        navigator.mediaDevices.enumerateDevices().then(function (devs) {
            for( var i=0;i<devs.length;i++){
                var item = devs[i];
                if( !res[item.kind]){
                    res[item.kind]=[]
                }
                res[item.kind].push(item);
            }
            console.log(res);
            if (callback){
                callback({error: null, devices:res});
            }
        });
    }
    catch (er) {
        console.log(er,"createPeer error.");
    }
};
TKmsClient.prototype.changeCamera = function ( peer, newCameraDeviceId , callback) {
    var me = this;
    try{
        var result={error:null , res: null}
        //var constraints = {video: {deviceId: {exact: newCameraDeviceId}}};
        var constraints = {video: {deviceId: newCameraDeviceId}};
        var sender = null;
        navigator.mediaDevices.getUserMedia(constraints).then(function (stream) {
            try{
                if( stream){
                    let videoTrack = stream.getVideoTracks()[0];
                    peer.localVideo.srcObject = stream;
                    sender = peer.peerConnection.getSenders().find(function (s) {
                        return s.track.kind == videoTrack.kind;
                    });
                    sender.track.stop();
                    sender.replaceTrack(videoTrack);
                    result.res = constraints;
                    if( callback){
                        callback(result);
                    }
                }
                else{
                    if( callback){
                        result.error = "stream is null";
                        callback(result);
                    }
                }
            }
            catch (er) {
                console.log(er);
            }
        });
    }
    catch (er) {
        console.log(er);
    }
}
TKmsClient.prototype.kmsShareScreen = function ( peer , callback) {
    var me = this;
    try{
        if (navigator.mediaDevices.getDisplayMedia) {
            navigator.mediaDevices.getDisplayMedia({video:true}).then(
                function (stream) {
                    let videoTrack = stream.getVideoTracks()[0];
                    peer.localVideo.srcObject = stream;
                    sender = peer.peerConnection.getSenders().find( function (s) {
                        return s.track.kind == videoTrack.kind;
                    });
                    sender.track.stop();
                    sender.replaceTrack(videoTrack);
                    if( callback) {
                        callback( );
                    }
                }
            )
        }
    }
    catch (er) {
        console.log(er);
    }
}
TKmsClient.prototype.kmsCreatePeerEnd = function ( pipe, shareScreenFlag , localVideo , remoteVideo, callback) {
    var me = this;
    try{
        var result={
            error:null,
            peer: null,
            endpoint:null
        };
        var shareOpts = shareScreenFlag?"screen":"webcam";
        me.kmsCreatePeer(localVideo, remoteVideo , shareOpts, null , function (res) {
            if( res.error ){
                result.error = res.error;
                me.callBack(callback,result);
            }
            else{
                result.peer = res.peer;
                pipe.create("WebRtcEndpoint", function ( errEnd , end) {
                    result.endpoint = end;
                    if( errEnd){
                        result.error = errEnd;
                        me.callBack(callback , result);
                    }
                    else{
                        me.kmsBindPeerAndEndpoint(res.peer , end, function () {
                            me.callBack(callback , result);
                        })
                    }
                })
            }
        })
    }
    catch (er) {
        console.log(er);
    }
}
 类似资料: