Rtcp.js 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. import Workers from "./Workers.js"
  2. import Heartbeat from "./Heartbeat.js"
  3. import Logger from "./Logger.js"
  4. const logger = new Logger('rtcp')
  5. window.JoyStickDelyTime = null;
  6. export default class Rtcp extends EventEmitter {
  7. constructor(e) {
  8. super();
  9. E(this, "connection", null);
  10. E(this, "inputChannel", null);
  11. E(this, "mediaStream");
  12. E(this, "socket");
  13. E(this, "connected", !1);
  14. E(this, "candidates", []);
  15. E(this, "isAnswered", !1);
  16. E(this, "isFlushing", !1);
  17. E(this, "inputReady", !1);
  18. E(this, "workers");
  19. E(this, "actived", !0);
  20. E(this, "heartbeat");
  21. E(this, "onIcecandidate", e=>{
  22. if (e.candidate != null) {
  23. const t = JSON.stringify(e.candidate);
  24. logger.debug(`Got ice candidate: ${t}`),
  25. this.network.socket.send({
  26. id: "ice_candidate",
  27. data: btoa(t)
  28. })
  29. }
  30. }
  31. );
  32. E(this, "onIcecandidateerror", e=>{
  33. logger.error("onicecandidateerror", e.errorCode, e.errorText, e)
  34. }
  35. );
  36. E(this, "onIceStateChange", e=>{
  37. switch (e.target.iceGatheringState) {
  38. case "gathering":
  39. logger.info("ice gathering");
  40. break;
  41. case "complete":
  42. logger.info("Ice gathering completed")
  43. }
  44. }
  45. );
  46. E(this, "onIceConnectionStateChange", ()=>{
  47. if (!!this.connection)
  48. {
  49. logger.info(`iceConnectionState: ${this.connection.iceConnectionState}`);
  50. switch (this.connection.iceConnectionState) {
  51. case "connected":
  52. {
  53. this.connected = !0;
  54. break
  55. }
  56. case "disconnected":
  57. {
  58. this.connected = !1,
  59. this.emit("rtcDisconnected");
  60. break
  61. }
  62. case "failed":
  63. {
  64. this.emit("rtcDisconnected"),
  65. this.connected = !1;
  66. break
  67. }
  68. }
  69. }
  70. }
  71. );
  72. E(this, "setRemoteDescription", async(e,t)=>{
  73. var a, s, l;
  74. if (!this.connection)
  75. return;
  76. const r = JSON.parse(atob(e))
  77. , n = new RTCSessionDescription(r);
  78. await this.connection.setRemoteDescription(n);
  79. const o = await this.connection.createAnswer();
  80. if (o.sdp = (a = o.sdp) == null ? void 0 : a.replace(/(a=fmtp:111 .*)/g, "$1;stereo=1;sprop-stereo=1"),
  81. ((l = (s = o.sdp) == null ? void 0 : s.match(/a=mid:1/g)) == null ? void 0 : l.length) == 2) {
  82. const u = o.sdp.lastIndexOf("a=mid:1");
  83. o.sdp = o.sdp.slice(0, u) + "a=mid:2" + o.sdp.slice(u + 7)
  84. }
  85. try {
  86. await this.connection.setLocalDescription(o)
  87. } catch (u) {
  88. logger.error("error", u)
  89. }
  90. this.isAnswered = !0,
  91. this.network.rtcp.flushCandidate(),
  92. this.network.socket.send({
  93. id: "answer",
  94. data: btoa(JSON.stringify(o))
  95. }),
  96. t.srcObject = this.mediaStream
  97. }
  98. );
  99. E(this, "flushCandidate", ()=>{
  100. this.isFlushing || !this.isAnswered || (this.isFlushing = !0,
  101. this.candidates.forEach(e=>{
  102. const t = atob(e)
  103. , r = JSON.parse(t);
  104. if (/172\./.test(r.candidate))
  105. return;
  106. const n = new RTCIceCandidate(r);
  107. this.connection && this.connection.addIceCandidate(n).then(()=>{}
  108. , o=>{
  109. logger.info("add candidate failed", o)
  110. }
  111. )
  112. }
  113. ),
  114. this.isFlushing = !1)
  115. }
  116. );
  117. E(this, "input", e=>{
  118. var o = this.inputChannel;
  119. if(!this.actived || !this.inputChannel || this.inputChannel.readyState === "open"){
  120. if(o != null){
  121. //console.log('发送webrtc数据:'+e)
  122. o.send(e)
  123. }
  124. }
  125. }
  126. );
  127. this.network = e,
  128. this.workers = new Workers(this,logger),
  129. this.workers.registerLogger(logger),
  130. this.workers.registerFunction("data", t=>{
  131. this.emit("data", t)
  132. }
  133. ),
  134. this.heartbeat = new Heartbeat({
  135. ping: t=>{
  136. e.room.actionsHandler.echo(t)
  137. }
  138. ,
  139. pong(t, r) {
  140. var n;
  141. r && t > 500 && logger.warn(`high hb value ${t}, traceId:` + r),
  142. (n = e.room.stats) == null || n.assign({
  143. hb: t
  144. })
  145. }
  146. })
  147. }
  148. start() {
  149. this.connection = new RTCPeerConnection;
  150. const e = Date.now();
  151. this.connection.ondatachannel = t=>{
  152. logger.info(`ondatachannel: ${t.channel.label}`);
  153. this.inputChannel = t.channel;
  154. this.inputChannel.onopen = ()=>{
  155. var r;
  156. logger.info("The input channel has opened, id:", (r = this.inputChannel) == null ? void 0 : r.id),
  157. this.inputReady = !0,
  158. this.emit("rtcConnected"),
  159. this.network.room.currentNetworkOptions.reconnect || (logger.infoAndReportMeasurement({
  160. type: "datachannelOpenedAt",
  161. group: "joinRoom"
  162. }),
  163. logger.infoAndReportMeasurement({
  164. type: "datachannelOpenedCost",
  165. group: "joinRoom"
  166. }))
  167. console.log('this.inputChannel',this.inputChannel)
  168. }
  169. ,
  170. this.inputChannel.onclose = ()=>{
  171. var r;
  172. return logger.info("The input channel has closed, id:", (r = this.inputChannel) == null ? void 0 : r.id)
  173. },
  174. this.inputChannel.onmessage = r=>{
  175. this.workers.dataHandle(r.data)
  176. }
  177. }
  178. ,
  179. this.connection.oniceconnectionstatechange = this.onIceConnectionStateChange,
  180. this.connection.onicegatheringstatechange = this.onIceStateChange,
  181. this.connection.onicecandidate = this.onIcecandidate,
  182. this.connection.onicecandidateerror = this.onIcecandidateerror,
  183. this.network.socket.send({
  184. id: "init_webrtc",
  185. data: JSON.stringify({
  186. is_mobile: !0
  187. })
  188. })
  189. }
  190. addCandidate(e) {
  191. e === "" ? this.network.rtcp.flushCandidate() : this.candidates.push(e)
  192. }
  193. disconnect() {
  194. var i, o, s;
  195. this.heartbeat.stop(), logger.info("ready to close datachannel, id", (i = this.inputChannel) == null ? void 0 : i.id), (o = this.inputChannel) == null || o.close(), (s = this.connection) == null || s.close(), this.connection = null, this.inputChannel = null
  196. }
  197. sendStringData(e) {
  198. this.input(e)
  199. }
  200. sendData(e) {
  201. let t = "";
  202. try {
  203. if(e.action_type != 1009 && e.action_type != 1024){
  204. if(e.action_type == 15){
  205. console.log('发送:action_type:'+e.action_type+',trace_id:'+e.trace_id+',joystick_action'+JSON.stringify(e.dir_action)+',playPosition:'+JSON.stringify(window.room.avatars[0].xAvatar.position)+',时间:'+new Date().getTime());
  206. if(window.JoyStickDelyTime == null){
  207. window.JoyStickDelyTime = {
  208. trace_id:e.trace_id,
  209. sendTime:new Date().getTime()
  210. }
  211. }
  212. if(window.JoyStickDelyTime.time_delay){
  213. e.time_delay = window.JoyStickDelyTime.time_delay;
  214. window.JoyStickDelyTime = null;
  215. }
  216. }
  217. else{
  218. console.log('发送:action_type:'+e.action_type+',trace_id:'+e.trace_id+',playPosition:'+JSON.stringify(window.room.avatars[0].xAvatar.position)+',时间:'+new Date().getTime());
  219. }
  220. }
  221. t = JSON.stringify(e)
  222. } catch (r) {
  223. logger.error(r);
  224. return
  225. }
  226. this.input(t)
  227. }
  228. }