Rtcp.js 7.4 KB

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