scene.service.ts 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457
  1. import { Injectable, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
  2. import { ClientGrpc, Client } from '@nestjs/microservices';
  3. import { grpcClientOptions } from './grpc-scene.options';
  4. import { Inject } from '@nestjs/common';
  5. import { DataChannel, PeerConnection } from 'node-datachannel';
  6. import { BehaviorSubject } from 'rxjs';
  7. // import * as streamBuffers from 'stream-buffers';
  8. import { ActionType } from './actionType';
  9. import { CacheService } from 'src/cache/cache.service';
  10. import { StreamService } from './stream/stream.service';
  11. // import { InjectQueue } from '@nestjs/bull';
  12. // import { Queue } from 'bull';
  13. import { RotateService } from 'src/rotate/rotate.service';
  14. // import { DelayQueue, RxQueue, DebounceQueue } from 'rx-queue';
  15. import { DelayQueue, RxQueue, DebounceQueue } from '../queue/mod';
  16. import { MoveService } from 'src/move/move.service';
  17. import { GetRouterService } from 'src/get-router/get-router.service';
  18. import { ConfigService } from '@nestjs/config';
  19. import { Logger } from 'winston';
  20. import { WINSTON_MODULE_PROVIDER } from 'nest-winston';
  21. // import ShareData from 'src/ShareData';
  22. // interface UserInfo {
  23. // userId: string;
  24. // roomId: string;
  25. // }
  26. const seqExeAsyncFn = (asyncFn) => {
  27. let runPromise = null;
  28. return function seq(...args) {
  29. if (!runPromise) {
  30. runPromise = asyncFn.apply(this, args);
  31. runPromise.then(() => (runPromise = null));
  32. return runPromise;
  33. } else {
  34. return runPromise.then(() => seq.apply(this, args));
  35. }
  36. };
  37. };
  38. @Injectable()
  39. export class SceneService implements OnModuleInit, OnModuleDestroy {
  40. constructor(
  41. private configService: ConfigService,
  42. private cacheService: CacheService,
  43. private streamService: StreamService,
  44. private rotateService: RotateService,
  45. private moveService: MoveService,
  46. private getRouterService: GetRouterService,
  47. @Inject(WINSTON_MODULE_PROVIDER) private readonly logger: Logger,
  48. ) {}
  49. @Client(grpcClientOptions) private readonly client: ClientGrpc;
  50. public _frameInteval: NodeJS.Timeout;
  51. public _frameTimeout: NodeJS.Timeout;
  52. public _rotateTimeout: NodeJS.Timeout;
  53. public _moveTimeout: NodeJS.Timeout;
  54. public _JoyStickingSteamTimeout: NodeJS.Timeout;
  55. public _packFrameTimeout: NodeJS.Timeout;
  56. public startSteaming = new BehaviorSubject<boolean>(false);
  57. public onRotating = new BehaviorSubject<boolean>(false);
  58. public onMoving = new BehaviorSubject<boolean>(false);
  59. public onJoysticking = new BehaviorSubject<boolean>(false);
  60. public frameCnt = new BehaviorSubject<number>(-1);
  61. private rotateframeCnt = -1;
  62. private moveframeCnt = -1;
  63. private joystickFrameCnt = -1;
  64. private rotateFirstIDR = true;
  65. private rotateStopThrottle = false; //防止多次瞬间解触发
  66. private rotateTimeStamp: number;
  67. private channel: DataChannel;
  68. private peer: PeerConnection;
  69. // private logger: Logger = new Logger('SceneService');
  70. private frameCntInterval = 1000;
  71. private user_id: string;
  72. private roomId: string;
  73. private onSteaming = false;
  74. private mockserverTime = Date.now() - 1653000000478;
  75. private lastRenderMedia = '';
  76. private frameCntSubscription: any;
  77. private roQueueSubscription: any;
  78. private moveQueueSubscription: any;
  79. private walkingSub: any;
  80. private _rotateCountFame = -1;
  81. private _rotateStartFame = new BehaviorSubject<number>(-1);
  82. private _rotateCount = -1;
  83. private streamServiceSub: any;
  84. // private roRequestQueue: RxQueue = new DelayQueue(20);
  85. // private roQueue: RxQueue = new DelayQueue(
  86. // Number(this.configService.get('queueConfig.rotate')) || 20,
  87. // );
  88. private moveQueue: RxQueue = new DelayQueue(
  89. Number(this.configService.get('queueConfig.move')) || 20,
  90. );
  91. private requestIFrameQueue: RxQueue = new DebounceQueue(2000);
  92. private requestIFrameQueueSub: any;
  93. private roRequestQueueSub: any;
  94. private rewalking = false;
  95. private firstRender = false;
  96. private lastMovingPointArray: MovingLastUpdateType[] = [];
  97. private latestRotateRequest: any; // 最新Rotate的接收值
  98. private latestWalkingRequest: any; // 最新waking的接收值
  99. private hasJoystickMoveRequest = false; // 最新joystick的接收值
  100. private stopRotated = false;
  101. private moveSliceLastFrame = new BehaviorSubject<MovingLastUpdateType>(null);
  102. private moveSliceLastFrameSub: any;
  103. public lastMoveStreamFrame = new BehaviorSubject<StreamFrameType>({
  104. frame: -1,
  105. clipPath: '',
  106. metaData: '',
  107. });
  108. public testTimer = 0;
  109. private isJoystickHasStream = false;
  110. private hasJoystickFocusRepeat = false;
  111. private startSub: any;
  112. public sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
  113. private globalOptLock = false;
  114. private isStopJointing = false;
  115. onModuleInit(): void {
  116. this.streamServiceSub = this.streamService.onSteaming.subscribe((val) => {
  117. this.onSteaming = val;
  118. });
  119. Number.prototype.padLeft = function (n, str) {
  120. return Array(n - String(this).length + 1).join(str || '0') + this;
  121. };
  122. // this.logger.info('roQueue-period :' + Number(this.roQueue.period));
  123. this.logger.info('moveQueue-period :' + Number(this.moveQueue.period));
  124. }
  125. public isHeaderOrLast(index: number, length: number): boolean {
  126. if (index === 0 || index === length) {
  127. return true;
  128. } else {
  129. return false;
  130. }
  131. }
  132. public getConfig() {
  133. return {
  134. userId: this.user_id,
  135. roomId: this.roomId,
  136. };
  137. }
  138. public startStream(): void {
  139. clearInterval(this._frameInteval);
  140. if (this.frameCnt.value === -1) {
  141. this._frameInteval = setInterval(async () => {
  142. const next = this.frameCnt.value + 1;
  143. this.frameCnt.next(next);
  144. }, 1000);
  145. }
  146. }
  147. public holdSteam(): void {
  148. clearInterval(this._frameInteval);
  149. }
  150. public resumeStream(): void {
  151. this.onMoving.next(false);
  152. this.onRotating.next(false);
  153. this.onJoysticking.next(false);
  154. this.moveframeCnt = -1;
  155. this.rotateframeCnt = -1;
  156. this.globalOptLock = false;
  157. clearInterval(this._frameInteval);
  158. this._frameInteval = setInterval(async () => {
  159. const next = this.frameCnt.getValue() + 1;
  160. this.frameCnt.next(next);
  161. }, 1000);
  162. }
  163. public stopStream(): void {
  164. if (this.frameCntSubscription) {
  165. this.frameCntSubscription.unsubscribe();
  166. this.frameCntSubscription = null;
  167. }
  168. if (this.roQueueSubscription) {
  169. this.roQueueSubscription.unsubscribe();
  170. this.roQueueSubscription = null;
  171. }
  172. if (this.moveQueueSubscription) {
  173. this.moveQueueSubscription.unsubscribe();
  174. this.moveQueueSubscription = null;
  175. }
  176. this.frameCnt.next(-1);
  177. clearInterval(this._frameInteval);
  178. this.rotateframeCnt = -1;
  179. }
  180. setConfig(user_id: string, roomId: string): void {
  181. this.user_id = user_id;
  182. this.roomId = roomId;
  183. }
  184. onModuleDestroy() {
  185. if ('unsubscribe' in this.streamServiceSub) {
  186. this.streamService.onSteaming.unsubscribe();
  187. }
  188. }
  189. init(request: InitRequest) {
  190. try {
  191. this.rotateService.init(
  192. request.app_id,
  193. request.user_id,
  194. request.skin_id,
  195. request.roomId,
  196. request.avatar_id,
  197. );
  198. this.cacheService.getClient();
  199. console.log('rotateService::init');
  200. this.startSub = this.startSteaming.subscribe((flag) => {
  201. if (flag) {
  202. console.log('初始推流::');
  203. this.startStream();
  204. this.handleStream();
  205. }
  206. });
  207. // 加载
  208. } catch (error) {
  209. this.logger.error('error', error);
  210. }
  211. }
  212. async exit() {
  213. this.frameCnt.next(-1);
  214. this.rotateService.deleteUser(this.user_id);
  215. this.hasJoystickFocusRepeat = false;
  216. const userId = this.user_id;
  217. const roomId = this.roomId;
  218. const roomKey =
  219. process.env.NODE_ENV === 'development'
  220. ? `test-room:${roomId}`
  221. : `room:${roomId}`;
  222. this.cacheService.hDel(roomKey, userId);
  223. if (this.startSub) {
  224. this.startSub.unsubscribe();
  225. this.startSub = null;
  226. }
  227. }
  228. async rotate(request: RotateRequest) {
  229. if (this.isHasWalkingJoints()) {
  230. this.globalOptLock = true;
  231. } else {
  232. console.log('开锁rotate或正常rotate');
  233. }
  234. this.latestRotateRequest = request;
  235. // if (
  236. // this.onMoving.getValue() &&
  237. // this.globalOptLock &&
  238. // // this._rotateCount > 5 &&
  239. // !this.rotateStopThrottle
  240. // ) {
  241. // this.handleRotateStop(request);
  242. // // debugger;
  243. // }
  244. this.handleRotate(request);
  245. this._rotateCount += 1;
  246. }
  247. /**
  248. * rotate请求队列
  249. */
  250. async handleRotate(request) {
  251. // try {
  252. const rotateUnlock = this.firstRender && !this.globalOptLock;
  253. console.log('rotateUnlock条件--->' + rotateUnlock, this.globalOptLock);
  254. if (rotateUnlock && this._rotateCount > 2) {
  255. const start = performance.now();
  256. // 当move时处理 _rotateCount是移动端同时触发的问题,rotateStopThrottle是减少重复抖动stop的处理。
  257. this.holdSteam();
  258. const redisMeta: StreamReplyType = await this.rotateService.seqExeRotate(
  259. request,
  260. );
  261. if (redisMeta && 'mediaSrc' in redisMeta) {
  262. if (redisMeta.mediaSrc?.length) {
  263. const src = redisMeta.mediaSrc.split('?')[0];
  264. if (src.length > 0) {
  265. this.lastRenderMedia = src;
  266. const clipPath = this.configService.get('app.prefix') + src;
  267. delete redisMeta.mediaSrc;
  268. const stream: StreamFrameType = {
  269. frame: -1,
  270. clipPath: clipPath,
  271. metaData: JSON.stringify(redisMeta),
  272. serverTime: this.mockserverTime,
  273. DIR: 3,
  274. };
  275. const stop = performance.now();
  276. const inMillSeconds = stop - start;
  277. const rounded = Number(inMillSeconds).toFixed(3);
  278. this.logger.info(
  279. `[timer]-rotate-入队列前: ${rounded}ms -->` +
  280. JSON.stringify(stream),
  281. );
  282. if (!this.stopRotated) {
  283. await this.seqExehandleRotateStream(stream);
  284. }
  285. // this.roQueue.next(stream);
  286. } else {
  287. this.onRotating.next(false);
  288. }
  289. }
  290. }
  291. } else {
  292. return;
  293. }
  294. // } catch (error) {
  295. // this.logger.error('rotate', error.message);
  296. // console.error('error', error);
  297. // }
  298. }
  299. handleStopRotate() {
  300. this.stopRotated = true;
  301. }
  302. resumeRotate() {
  303. this.stopRotated = false;
  304. }
  305. seqExehandleRotateStream = seqExeAsyncFn(this.handleRotateStream);
  306. /**
  307. * rotate 推送seq(不存在队列,直推)
  308. */
  309. async handleRotateStream(stream: StreamFrameType) {
  310. this.rotateTimeStamp = Date.now();
  311. this.holdSteam();
  312. // 在未开始前开始
  313. if (!this.onRotating.value) {
  314. this._rotateStartFame.next(this.frameCnt.value);
  315. console.log('旋转开始记录帧:::--->', this._rotateStartFame.value);
  316. }
  317. this.onRotating.next(true);
  318. stream.frame = this.frameCnt.value + 1;
  319. // 从记录第一帧到最新一帧
  320. this._rotateCountFame = stream.frame - this._rotateStartFame.value;
  321. const IDRflag = this._rotateCountFame % 5 === 0 ? 1 : 3;
  322. stream.DIR = this.rotateFirstIDR ? 1 : IDRflag;
  323. console.log(
  324. '[旋转信息:::info--->]:clipPath: %s, main-frameCnt: %s, stream.frame %s ,_rotateStartFame: %s, _rotateCountFame: %s, IDRflag: %s,time: %s',
  325. stream.clipPath,
  326. // this._rotateStartFame.value,
  327. this.frameCnt.value,
  328. stream.frame,
  329. this._rotateStartFame.value,
  330. this._rotateCountFame,
  331. // this.rotateframeCnt,
  332. IDRflag,
  333. new Date().getTime(),
  334. );
  335. const user = this.moveService.users[this.user_id];
  336. user.isMoving = JSON.parse(stream.metaData)['newUserStates'][0].renderInfo.isMoving
  337. const res = await this.streamService.pushFrameToSteam(stream);
  338. if (res.done) {
  339. this.frameCnt.next(res.frame);
  340. if (this.rotateFirstIDR) {
  341. this.rotateFirstIDR = false;
  342. }
  343. console.log('[旋转信息:::info:::done--->]', res);
  344. clearTimeout(this._rotateTimeout);
  345. this._rotateTimeout = setTimeout(() => {
  346. this.logger.info('rotate end', Date.now());
  347. this.rotateframeCnt = -1;
  348. this._rotateCountFame = -1;
  349. this._rotateCount = 0;
  350. this.latestRotateRequest = null;
  351. this.rotateFirstIDR = true;
  352. this.resumeStream();
  353. }, 200);
  354. } else {
  355. console.error('流地址有误::', res.frame, JSON.stringify(res));
  356. this.logger.error('流地址有误::', res.frame, JSON.stringify(res));
  357. this.resumeStream();
  358. }
  359. }
  360. // /**
  361. // * rotate 推送队列 --backup
  362. // */
  363. // handleRotateStream() {
  364. // if (!this.roQueueSubscription) {
  365. // this.roQueueSubscription = this.roQueue.subscribe(
  366. // async (stream: StreamFrameType) => {
  367. // this.rotateTimeStamp = Date.now();
  368. // if (this.rotateframeCnt === -1) {
  369. // this.rotateframeCnt = this.frameCnt.value;
  370. // }
  371. // this.rotateframeCnt += 1;
  372. // stream.frame = this.rotateframeCnt;
  373. // this._rotateCountFame += 1;
  374. // const IDRflag = this._rotateCountFame % 5 === 0 ? 1 : 3;
  375. // this.logger.info(
  376. // `当前rotate ,mainframeCnt:${this.frameCnt.getValue()}, _rotateCountFame:${this._rotateCountFame
  377. // } IDRflag:${IDRflag}`,
  378. // );
  379. // stream.DIR = this.rotateFirstIDR ? 1 : IDRflag;
  380. // if (this.rotateFirstIDR) {
  381. // this.rotateFirstIDR = false;
  382. // }
  383. // this.logger.info(
  384. // '[media-rotate]: ' +
  385. // ', frame: ' +
  386. // stream.frame +
  387. // ', rotateframeCnt: ' +
  388. // this.rotateframeCnt +
  389. // ', clipPath: ' +
  390. // stream.clipPath,
  391. // // stream.metaData,
  392. // );
  393. // // this.logger.info(
  394. // // `roQueueSubscription:frame:${this.rotateframeCnt} ` +
  395. // // JSON.stringify(stream.metaData),
  396. // // );
  397. // const res = await this.streamService.pushFrameToSteam(stream);
  398. // if (res.done) {
  399. // clearTimeout(this._rotateTimeout);
  400. // this._rotateTimeout = setTimeout(() => {
  401. // this.logger.info('rotate end', Date.now());
  402. // this.frameCnt.next(res.frame);
  403. // this.rotateframeCnt = -1;
  404. // this._rotateCountFame = -1;
  405. // // this.onMoving.next(false);
  406. // // this.onRotating.next(false);
  407. // this.latestRotateRequest = null;
  408. // this.rotateFirstIDR = true;
  409. // this.resumeStream();
  410. // //TODO rotate完后清除request队列
  411. // if (this.roRequestQueueSub) {
  412. // this.roRequestQueueSub.unsubscribe();
  413. // this.roRequestQueueSub = null;
  414. // }
  415. // }, 100);
  416. // } else {
  417. // console.error('流地址有误::', res.frame, JSON.stringify(res));
  418. // this.logger.error('流地址有误::', res.frame, JSON.stringify(res));
  419. // this.resumeStream();
  420. // }
  421. // },
  422. // );
  423. // }
  424. // }
  425. /**
  426. * 旋转中断逻辑
  427. * 1. 行走间
  428. * 1.1 行走间中断只能在每段最后一帧,当前段一定要消费掉,在未消费,globalOptLock锁rotate,消费完 rotate
  429. * 1.2 消费完要处理点位上传,清除当前段往后的都要清掉,回调各种stop function
  430. * 2.joystick间 complementFrame pools 解锁就可以
  431. */
  432. async handleRotateOrWalkingStop(request): Promise<boolean> {
  433. this.rotateStopThrottle = true;
  434. this.isStopJointing = true;
  435. const lastStreamFrame = this.lastMoveStreamFrame.getValue();
  436. this.logger.info(
  437. 'handleRotateOrWalkingStop-frame',
  438. JSON.stringify(lastStreamFrame),
  439. );
  440. const metaData: StreamReplyType = JSON.parse(
  441. lastStreamFrame.metaData,
  442. ) as any as StreamReplyType;
  443. if (!metaData.endBreakPointId) {
  444. }
  445. console.log('stop-4', metaData.traceIds[0]);
  446. console.log('stop-5', request.trace_id);
  447. //判断request是否是新的
  448. if (metaData.traceIds.indexOf(request.trace_id) > -1) {
  449. return Promise.resolve(false);
  450. }
  451. console.log('currentUser-user_id', this.user_id);
  452. const newUserStates: NewUserStatesType = metaData.newUserStates.find(
  453. (item) => item.userId === this.user_id,
  454. );
  455. const trace_id = metaData.traceIds[0];
  456. const userId = newUserStates.userId;
  457. //TODO 临时,可能数据会不对
  458. const breakPointId = metaData.endBreakPointId || metaData.breakPointId;
  459. const cameraAngle = newUserStates.playerState.camera.angle;
  460. const playerAngle = newUserStates.playerState.player.angle;
  461. this.logger.info(
  462. 'stop-data-0' +
  463. 'trace_id: ' +
  464. trace_id +
  465. 'userId:' +
  466. userId +
  467. 'breakPointId :' +
  468. breakPointId +
  469. 'cameraAngle :' +
  470. JSON.stringify(cameraAngle) +
  471. 'playerAngle: ' +
  472. JSON.stringify(playerAngle),
  473. );
  474. //debugger;
  475. console.log('moveService.stop-1:' + breakPointId);
  476. //console.log('20220627test:handleRotateOrWalkingStop-stop');
  477. const redisMeta = await this.moveService.stop(
  478. trace_id,
  479. userId,
  480. breakPointId,
  481. cameraAngle,
  482. playerAngle,
  483. );
  484. this.logger.info('stop-redisMeta-frame', JSON.stringify(redisMeta));
  485. if (redisMeta) {
  486. const src = redisMeta.mediaSrc.split('?')[0];
  487. const mediaSrc = this.configService.get('app.prefix') + src;
  488. const streamData: StreamFrameType = {
  489. frame: this.frameCnt.value + 1,
  490. clipPath: mediaSrc,
  491. metaData: JSON.stringify(redisMeta),
  492. serverTime: this.mockserverTime,
  493. DIR: 1,
  494. };
  495. //推最后一个 STOP Frame
  496. const hasPush = await this.streamService.pushFrameToSteam(streamData);
  497. if (hasPush.done) {
  498. //console.log('20220627test:handleRotateOrWalkingStop-stop:'+streamData.clipPath+'**'+streamData.frame);
  499. this.frameCnt.next(hasPush.frame);
  500. this.isStopJointing = false;
  501. // this.onMoving.next(false);
  502. // this.cleanMoveSteam();
  503. return Promise.resolve(true);
  504. // this.resumeStream();
  505. } else {
  506. console.error(
  507. '暂停STOP::帧有问题',
  508. hasPush.frame,
  509. JSON.stringify(streamData),
  510. );
  511. return Promise.resolve(false);
  512. }
  513. }
  514. }
  515. async getSimplestCameraInfo(appId, userId) {
  516. if (this.moveService.cameraInfos.length > 20) {
  517. const startBreakPointId =
  518. this.moveService.cameraInfos[0].startBreakPointId;
  519. const endBreakPointId =
  520. this.moveService.cameraInfos[this.moveService.cameraInfos.length - 1]
  521. .endBreakPointId;
  522. const path = this.getRouterService.searchRoad2(
  523. startBreakPointId,
  524. endBreakPointId,
  525. );
  526. if (path == null) {
  527. //可以清空cameraInfos
  528. this.moveService.cameraInfos = [];
  529. } else {
  530. await this.moveService.updateCameraInfoForDely(appId, userId, path);
  531. }
  532. }
  533. }
  534. /**
  535. * 行走动作
  536. *
  537. * @param request
  538. */
  539. async walking(request: MoveRequest) {
  540. this.latestWalkingRequest = request;
  541. this.logger.info('walking-trace_id', request.trace_id);
  542. // if (this.isHasWalkingJoints()) {
  543. // console.log('lock-锁-walking', this.latestWalkingRequest);
  544. // this.globalOptLock = true;
  545. // }
  546. // 进入正常walking流程
  547. if (!this.onMoving.getValue()) {
  548. console.log('walking-step-main-1', request.trace_id);
  549. this.latestWalkingRequest = null;
  550. this.handleWalking(request);
  551. } else {
  552. this.globalOptLock = true;
  553. console.log('lock-锁-walking', this.latestWalkingRequest);
  554. }
  555. this.handleWalkingJoints();
  556. }
  557. /**
  558. * 一段walking每个Joints关节点
  559. * @param request
  560. */
  561. handleWalkingJoints() {
  562. // 每个关节点
  563. if (!this.moveSliceLastFrameSub) {
  564. this.moveSliceLastFrameSub = this.moveSliceLastFrame.subscribe(
  565. async (frame: MovingLastUpdateType) => {
  566. //TODO 正在行走时,有新的reqest
  567. if (frame) {
  568. // console.log('unlock-Joints', JSON.stringify(frame));
  569. this.logger.info('Joints', JSON.stringify(frame));
  570. this.resumeRotate();
  571. let isRotateStop = false;
  572. let isWalkingStop = false;
  573. // 在全局锁的情况下
  574. if (this.globalOptLock) {
  575. isRotateStop = !!this.latestRotateRequest && this.onMoving.value;
  576. isWalkingStop =
  577. !!this.latestWalkingRequest && this.onMoving.value;
  578. console.log('g--isRotateStop', isRotateStop);
  579. console.log('g--isWalkingStop', isWalkingStop);
  580. // 这个就是双暂时出现的时候, 强制只执行一次,以isWalkingStop为主
  581. if (isRotateStop && isWalkingStop) {
  582. isRotateStop = false;
  583. }
  584. console.log('g--1-isRotateStop', isRotateStop);
  585. console.log('g--1-isWalkingStop', isWalkingStop);
  586. // 这个旋转暂停
  587. if (isRotateStop) {
  588. const hasStop = await this.handleRotateOrWalkingStop(
  589. this.latestRotateRequest,
  590. );
  591. console.log('旋转-hasStop', hasStop);
  592. this.clearWalkingJoints();
  593. this.cleanMoveSteam();
  594. this.globalOptLock = false;
  595. }
  596. // 这个行走暂停
  597. if (isWalkingStop) {
  598. const hasStop = await this.handleRotateOrWalkingStop(
  599. this.latestWalkingRequest,
  600. );
  601. console.log('walking-hasStop', hasStop);
  602. this.clearWalkingJoints();
  603. this.cleanMoveSteam();
  604. this.globalOptLock = false;
  605. console.log('unlock-walking');
  606. this.handleReWalking(this.latestWalkingRequest);
  607. // console.log('this', this.rewalking);
  608. }
  609. }
  610. }
  611. },
  612. );
  613. }
  614. }
  615. /**
  616. * 清除所有的节点信信息
  617. * @param request
  618. */
  619. clearWalkingJoints() {
  620. this.moveSliceLastFrame.next(null);
  621. this.lastMovingPointArray = [];
  622. }
  623. /**
  624. * 是否有行走关节点
  625. * @returns boolean
  626. */
  627. isHasWalkingJoints(): boolean {
  628. return this.lastMovingPointArray.length > 0;
  629. }
  630. /**
  631. * 行走队列处理器
  632. * @param request MoveRequest
  633. * @returns void
  634. */
  635. async handleWalking(request: MoveRequest): Promise<void> {
  636. try {
  637. // if (!this.onMoving.getValue()) {
  638. console.log('walking-step-main-2', request.trace_id);
  639. const start = performance.now();
  640. this._rotateCount = 0;
  641. const user = this.moveService.users[this.user_id];
  642. console.log('进入1 - searchRoad');
  643. this.logger.info(
  644. 'handleWalking-users' +
  645. JSON.stringify(this.moveService.users) +
  646. ' this.user_id: ' +
  647. this.user_id,
  648. );
  649. this.logger.info(
  650. 'handleWalking-currentUser' +
  651. JSON.stringify(user) +
  652. ' this.user_id: ' +
  653. this.user_id,
  654. );
  655. console.log('path-start' + user.breakPointId);
  656. const path = await this.getRouterService.searchRoad(
  657. user.appId,
  658. user.breakPointId,
  659. request.clicking_action.clicking_point,
  660. );
  661. this.logger.info('walking-path', path);
  662. if (!path) {
  663. console.log('不存在--path', path);
  664. this.cleanMoveSteam();
  665. this.clearWalkingJoints();
  666. this.resumeRotate();
  667. this.resumeStream();
  668. return;
  669. }
  670. // debugger;
  671. const walkingRes = await this.moveService.move(path, request);
  672. if (walkingRes && (!this.onMoving.value || this.rewalking)) {
  673. // 二维数组 做move 序列, move类型
  674. //console.log('move-walkingRes:' + JSON.stringify(walkingRes));
  675. this.handleStopRotate();
  676. if (walkingRes && walkingRes?.length >= 1) {
  677. for (let i = 0; i <= walkingRes.length - 1; i++) {
  678. Array.from(walkingRes[i]).forEach(
  679. (item: StreamReplyType, index: number) => {
  680. //const IDRflag = index % 5 === 0 ? 1 : 3;
  681. const IDRflag = item.isIDR ? 1 : 3;
  682. const dir = this.isHeaderOrLast(
  683. index,
  684. walkingRes[i].length - 1,
  685. );
  686. item.DIR = dir ? 1 : IDRflag;
  687. //将每段最后一个推入lastMovingPointArray
  688. if (index === walkingRes[i].length - 1) {
  689. this.lastMovingPointArray.push({
  690. mediaSrc: item.mediaSrc,
  691. metaData: item,
  692. });
  693. }
  694. },
  695. );
  696. }
  697. }
  698. // walkingRes marker to everybody
  699. const seqs = Array.from(walkingRes).flat() as any as StreamReplyType[];
  700. if (seqs?.length) {
  701. this.logger.info(
  702. 'walking --队列总览:' +
  703. ' 总段数: ' +
  704. walkingRes.length +
  705. ' 镜头帧数:' +
  706. walkingRes[0].length +
  707. ' 行走段数:' +
  708. (walkingRes[0]?.length
  709. ? walkingRes.length - 1
  710. : walkingRes.length) +
  711. ' 队列总帧数:' +
  712. seqs.length,
  713. );
  714. const stop = performance.now();
  715. const inMillSeconds = stop - start;
  716. const rounded = Number(inMillSeconds).toFixed(3);
  717. this.logger.info(`[timer]-move-入队列前:-->${rounded}ms`);
  718. this.handleSeqMoving(seqs);
  719. } else {
  720. console.error('walking-move无数据');
  721. this.cleanMoveSteam();
  722. this.resumeStream();
  723. }
  724. // }
  725. }
  726. // });
  727. // }
  728. } catch (error) {
  729. this.logger.error('walking', error.message);
  730. this.cleanMoveSteam();
  731. this.resumeStream();
  732. }
  733. }
  734. /**
  735. * 改变路线后的walking队列处理(中转)
  736. * @param request MoveRequest
  737. */
  738. handleReWalking(request: MoveRequest) {
  739. // this.latestWalkingRequest = null;
  740. this.rewalking = true;
  741. this.handleWalking(request);
  742. }
  743. /***
  744. * joystick main core
  745. */
  746. async joystick(request: JoystickRequest) {
  747. // TODO hasJoystickMoveRequest中断
  748. this.logger.info(
  749. 'this.hasJoystickMoveRequest',
  750. this.hasJoystickMoveRequest,
  751. );
  752. if (!this.hasJoystickMoveRequest) {
  753. this.handlejoystick(request);
  754. }
  755. }
  756. /**
  757. * joystick 二合一推流
  758. * @param joystickRes StreamMetaType | StreamFrameType;
  759. */
  760. handlePushJoyStickSteamSeq = seqExeAsyncFn(this.handlePushJoyStickSteam);
  761. async handlePushJoyStickSteam(joystickRes: StreamReplyType) {
  762. this.holdSteam();
  763. this.globalOptLock = true;
  764. //console.log('joystickRes有mediaSrc', joystickRes.mediaSrc);
  765. console.log(
  766. 'handlejoystick-angle->相机角度-------------------------:' +
  767. joystickRes['newUserStates'][0].playerState.camera.angle.yaw,
  768. );
  769. let streamData: StreamFrameType | StreamMetaType;
  770. this.joystickFrameCnt = this.frameCnt.getValue() + 1;
  771. const hasMedia = joystickRes?.mediaSrc && joystickRes?.mediaSrc.length > 0;
  772. if (hasMedia) {
  773. console.log('mediaSrc_7:'+joystickRes.mediaSrc);
  774. const src = joystickRes.mediaSrc.split('?')[0];
  775. const mediaSrc = this.configService.get('app.prefix') + src;
  776. // IDR flag设置为I帧
  777. const setDIR = joystickRes.isIDR ? 1 : 3;
  778. streamData = {
  779. frame: this.joystickFrameCnt,
  780. clipPath: mediaSrc,
  781. metaData: JSON.stringify(joystickRes),
  782. serverTime: this.mockserverTime,
  783. DIR: setDIR,
  784. };
  785. console.log(
  786. 'handlejoystick-hasMedia->-------------------------:' +
  787. ' frame: ' +
  788. streamData.frame +
  789. mediaSrc +
  790. ' IDR :' +
  791. setDIR,
  792. );
  793. } else {
  794. streamData = {
  795. frame: this.joystickFrameCnt,
  796. metaData: JSON.stringify(joystickRes),
  797. };
  798. }
  799. const user = this.moveService.users[this.user_id];
  800. user.isMoving = JSON.parse(streamData.metaData)['newUserStates'][0].renderInfo.isMoving;
  801. console.log('handlePushJoyStickSteam:'+user.IDRCount+','+joystickRes.isIDR+','+joystickRes.traceIds);
  802. // 过滤新东西, 推完给回false
  803. this.moveService.sendingFrameForJoystick = true;
  804. const hasPush = hasMedia
  805. ? await this.streamService.pushFrameToSteam(streamData as StreamFrameType)
  806. : await this.streamService.pushMetaDataToSteam(
  807. streamData as StreamMetaType,
  808. );
  809. if (hasPush.done) {
  810. this.isJoystickHasStream = true;
  811. console.log('joystick-hasPush', hasPush);
  812. // if (this.isJoystickHasStream) {
  813. // await this.sleep(20);
  814. // }
  815. // await this.sleep(20);
  816. this.frameCnt.next(hasPush.frame);
  817. this.moveService.sendingFrameForJoystick = false;
  818. const data = joystickRes as StreamReplyType;
  819. console.log('handlejoystick-isIDR:' + data.isIDR);
  820. // if (data?.moveOver && data.moveOver) {
  821. // // moveOver
  822. // console.log('回传updateUser', data);
  823. // // const userId = this.user_id;
  824. // // 回传点暂时有问题,待修复
  825. // //const breakPointId = data.endBreakPointId || data.breakPointId;
  826. // //const lastReply = JSON.stringify(joystickRes);
  827. // //this.moveService.updateUser(userId, breakPointId, lastReply);
  828. // }
  829. /**
  830. * 这个complementFrame 具体说明 pools 是complementFrame这个返回值
  831. * 1. 第一次要在200ms后调用, 如有值(pools) 就要返回主流程执行,但设置hasJoystickFocusRepeat为true
  832. * 2. 第二次或N进入在hasJoystickFocusRepeat为true并绕过200ms timeout,如pools有值返回(2)主流程直到pools为null
  833. * 3. 如pools为空走回 200ms流程 (这时pools应该为空),交权回空流。
  834. */
  835. if (this.hasJoystickFocusRepeat) {
  836. const complementFrame = this.moveService.complementFrame(
  837. this.user_id,
  838. ) as StreamReplyType;
  839. if (complementFrame) {
  840. // 第二次或N次进入时如果有值直接重新进入流主程
  841. this.holdSteam();
  842. this.handlePushJoyStickSteamSeq(complementFrame);
  843. this.globalOptLock = true;
  844. } else {
  845. // 第二次或N次无pool数据再次trigger handleJoystickStop
  846. this.hasJoystickFocusRepeat = false;
  847. this.testTimer = 0;
  848. //this.handleJoystickStop(hasPush);
  849. this.globalOptLock = false;
  850. this.resumeStream();
  851. }
  852. } else {
  853. this.handleJoystickStop(hasPush);
  854. }
  855. } else {
  856. debugger;
  857. console.error('joystick-流地址有误::', joystickRes.mediaSrc);
  858. this.logger.error('joystick-流地址有误::', joystickRes.mediaSrc);
  859. this.resumeStream();
  860. }
  861. }
  862. /**
  863. * Joystick Stop function
  864. */
  865. async handleJoystickStop(hasPush: StreamPushResponse) {
  866. // 最后一帧200ms
  867. clearTimeout(this._JoyStickingSteamTimeout);
  868. this._JoyStickingSteamTimeout = setTimeout(async () => {
  869. const user = this.moveService.users[this.user_id];
  870. await this.getSimplestCameraInfo(user.appId, this.user_id);
  871. const complementFrame = this.moveService.complementFrame(
  872. this.user_id,
  873. ) as StreamReplyType;
  874. // console.log('has-complementFrame', complementFrame);
  875. //console.log('gemer-test-complementFrame', complementFrame);
  876. if (complementFrame) {
  877. this.hasJoystickFocusRepeat = true;
  878. this.globalOptLock = true;
  879. this.testTimer += 1;
  880. console.log('complementFrame-有值');
  881. const start = performance.now();
  882. this.handlePushJoyStickSteamSeq(complementFrame);
  883. const stop = performance.now();
  884. //console.log('handlePushJoyStickSteam', this.testTimer);
  885. const inMillSeconds = stop - start;
  886. const rounded = Number(inMillSeconds).toFixed(3);
  887. console.log(`complementFrame调用时间---->${rounded}`);
  888. } else {
  889. console.log('complementFrame-空1');
  890. this.logger.info('joystick opt done');
  891. this.logger.info('joystick 交权给空流,当前pts', hasPush.frame);
  892. this.hasJoystickFocusRepeat = false;
  893. this.onJoysticking.next(false);
  894. this.resumeStream();
  895. this.joystickFrameCnt = -1;
  896. this.isJoystickHasStream = false;
  897. }
  898. }, 200);
  899. }
  900. /***
  901. * joystick
  902. */
  903. async handlejoystick(request: JoystickRequest) {
  904. try {
  905. //const joystickRes = await this.moveService.joystick(request);
  906. this._rotateCount = 0;
  907. const joystickRes = await this.moveService.seqExeJoystick(request);
  908. this.logger.info(
  909. 'joystick-breakPointId:' +
  910. this.moveService.users[this.user_id].breakPointId,
  911. );
  912. // 有数据 [0]是rotate数据,[1-infinity]是walking数据
  913. //this.logger.info('joystickRes', JSON.stringify(joystickRes));
  914. if (joystickRes) {
  915. this.onJoysticking.next(true);
  916. if (!this.onMoving.getValue()) {
  917. console.log('handlejoystick:data', JSON.stringify(joystickRes));
  918. this.handlePushJoyStickSteamSeq(joystickRes);
  919. }
  920. } else {
  921. console.log('handlejoystick:null');
  922. this.onJoysticking.next(false);
  923. }
  924. } catch (error) {
  925. console.error('joystick错误', error);
  926. this.onJoysticking.next(false);
  927. this.logger.error('joystick', error.message);
  928. }
  929. }
  930. /**
  931. * 主要处理moving的序列动作
  932. * @param seqs StreamReplyType[]
  933. */
  934. handleSeqMoving(seqs: StreamReplyType[]) {
  935. // if (!this.moveQueueSubscription) {
  936. // this.handleMoveSteam();
  937. // }
  938. // this.logger.info('moving-seqs', seqs.length);
  939. this.onMoving.next(true);
  940. this.holdSteam();
  941. // 保证每一段都是序列动作的前面队列是空的
  942. // this.moveQueue.clean();
  943. seqs.forEach((frame: StreamReplyType) => {
  944. const mediaSrc = frame.mediaSrc;
  945. const src = mediaSrc.split('?')[0];
  946. const clipPath = this.configService.get('app.prefix') + src;
  947. const type = frame.mType?.length ? frame.mType.slice() : 'move';
  948. const stream: StreamFrameType = {
  949. frame: -1,
  950. clipPath: clipPath,
  951. metaData: JSON.stringify(frame),
  952. serverTime: this.mockserverTime,
  953. DIR: frame.DIR,
  954. mType: type,
  955. };
  956. // this.moveQueue.next(stream);
  957. this.handleMoveSteam(stream);
  958. });
  959. }
  960. handleMoveSteam = seqExeAsyncFn(this.handleMoveSteamFn);
  961. async handleMoveSteamFn(stream: StreamFrameType) {
  962. try {
  963. if (!this.isStopJointing) {
  964. const metaData: StreamReplyType = JSON.parse(stream.metaData);
  965. this.moveframeCnt = this.frameCnt.value + 1;
  966. const streamData: StreamFrameType = {
  967. frame: this.moveframeCnt,
  968. clipPath: stream.clipPath,
  969. metaData: stream.metaData,
  970. serverTime: this.mockserverTime,
  971. DIR: stream.DIR,
  972. };
  973. this.logger.info(
  974. '[media-move]: ' +
  975. ', moveframeCnt: ' +
  976. this.moveframeCnt +
  977. ', clipPath: ' +
  978. stream.clipPath +
  979. ', mType: ' +
  980. stream.mType +
  981. ', DIR: ' +
  982. stream.DIR,
  983. // stream.metaData,
  984. );
  985. this.logger.info(
  986. '[media-move-lastMovingPointArray]',
  987. this.lastMovingPointArray?.length,
  988. );
  989. const user = this.moveService.users[this.user_id];
  990. user.isMoving = JSON.parse(streamData.metaData)['newUserStates'][0].renderInfo.isMoving;
  991. // 记录lastMoveStreamFrame给打断逻辑使用
  992. this.lastMoveStreamFrame.next(streamData);
  993. // this.lastMoveStreamFrameBk = streamData;
  994. this.holdSteam();
  995. // this.globalOptLock = true;
  996. //console.log('20220627test:handleMoveSteam:' + stream.clipPath)
  997. const frameTimeStart = performance.now();
  998. const res = await this.streamService.pushFrameToSteam(streamData);
  999. const isLastFrameIndex = this.lastMovingPointArray.findIndex(
  1000. (item) => item.mediaSrc === metaData.mediaSrc,
  1001. );
  1002. // this.logger.info('path-update-index', isLastFrameIndex);
  1003. if (res.done) {
  1004. const frameTimeEnd = performance.now();
  1005. const frameAverage = frameTimeEnd - frameTimeStart;
  1006. console.log('walking-frameAverage', frameAverage);
  1007. await this.sleep(40);
  1008. this.frameCnt.next(res.frame);
  1009. //关节点入库
  1010. if (isLastFrameIndex > -1) {
  1011. //this.logger.info('path-update-array', this.lastMovingPointArray);
  1012. const currentMeta = this.lastMovingPointArray[isLastFrameIndex];
  1013. const userId = this.user_id;
  1014. const breakPointId = currentMeta.metaData.endBreakPointId;
  1015. const lastReply = currentMeta.metaData;
  1016. this.moveService.updateUser(userId, breakPointId, lastReply);
  1017. this.lastMovingPointArray.splice(isLastFrameIndex, 1);
  1018. this.moveSliceLastFrame.next(currentMeta);
  1019. }
  1020. clearTimeout(this._moveTimeout);
  1021. this._moveTimeout = setTimeout(() => {
  1022. this.logger.info('move 交权给空流,当前pts', res.frame);
  1023. this.rewalking = false;
  1024. this.frameCnt.next(res.frame);
  1025. this.rotateframeCnt = -1;
  1026. this.onMoving.next(false);
  1027. this.onJoysticking.next(false);
  1028. this.lastMovingPointArray = [];
  1029. this.hasJoystickMoveRequest = false;
  1030. this.cleanMoveSteam();
  1031. this.globalOptLock = false;
  1032. this.resumeStream();
  1033. this.logger.info('move end');
  1034. }, 200);
  1035. } else {
  1036. console.error('流地址有误::', res.frame, JSON.stringify(res));
  1037. this.logger.error(
  1038. `movesteam::当前帧:${res.frame}` + JSON.stringify(res),
  1039. );
  1040. this.resumeStream();
  1041. }
  1042. }
  1043. } catch (error) {
  1044. this.logger.error('handleMoveSteam::error', error);
  1045. }
  1046. }
  1047. cleanMoveSteam() {
  1048. this.moveQueue.clean();
  1049. if (this.moveQueueSubscription) {
  1050. this.moveQueueSubscription.unsubscribe();
  1051. this.moveQueueSubscription = null;
  1052. }
  1053. if (this.walkingSub) {
  1054. this.walkingSub.unsubscribe();
  1055. this.walkingSub = null;
  1056. }
  1057. if (this.moveSliceLastFrameSub) {
  1058. this.lastMoveStreamFrame.next(null);
  1059. this.moveSliceLastFrameSub.unsubscribe();
  1060. this.moveSliceLastFrameSub = null;
  1061. }
  1062. // if (this.clickQueueSub) {
  1063. // this.clickQueueSub.unsubscribe();
  1064. // this.clickQueueSub = null;
  1065. // }
  1066. this.rotateStopThrottle = false;
  1067. }
  1068. async handleDataChanelOpen(
  1069. channel: DataChannel,
  1070. peer: PeerConnection,
  1071. ): Promise<void> {
  1072. this.channel = channel;
  1073. this.peer = peer;
  1074. this.streamService.setChannel(channel);
  1075. this.startSteaming.next(true);
  1076. // this.startStream();
  1077. // this.handleStream();
  1078. //TODO 正式channel打开记录,记录多少人在线
  1079. const userId = this.user_id;
  1080. const roomId = this.roomId;
  1081. const roomKey =
  1082. process.env.NODE_ENV === 'development'
  1083. ? `test-room:${roomId}`
  1084. : `room:${roomId}`;
  1085. this.cacheService.hSet(roomKey, userId, 1);
  1086. // debugger;
  1087. this.channel.onBufferedAmountLow(() => {
  1088. console.error('onBufferedAmountLow-rtt', this.peer.rtt());
  1089. console.error('onBufferedAmountLow', this.channel.bufferedAmount());
  1090. //64k->65536 128k->131072
  1091. this.channel.setBufferedAmountLowThreshold(262144);
  1092. this.logger.error('onBufferedAmountLow', this.channel.bufferedAmount());
  1093. });
  1094. }
  1095. handleDataChanelClose(): void {
  1096. this.stopStream();
  1097. this.startSteaming.next(false);
  1098. this.streamService.closeChannel();
  1099. this.cleanMoveSteam();
  1100. // const exitRequest: ExitRequest = {
  1101. // action_type: 1002,
  1102. // user_id: this.user_id,
  1103. // trace_id: '',
  1104. // };
  1105. this.exit();
  1106. }
  1107. handleMessage(message: string | Buffer) {
  1108. try {
  1109. if (typeof message === 'string') {
  1110. // wasm:特例, requestIframe
  1111. if (message.includes('wasm:')) {
  1112. const parseData = message
  1113. ? String(message).replace('wasm:', '')
  1114. : `{"MstType":1}`;
  1115. const msg: RTCMessageRequest = JSON.parse(parseData);
  1116. this.logger.error('lostIframe-message', JSON.stringify(msg));
  1117. if (Number(msg.MstType) === 0) {
  1118. this.handleIframeRequest();
  1119. }
  1120. } else {
  1121. const msg: RTCMessageRequest = JSON.parse(message);
  1122. // console.log('msg.action_type:' + msg.action_type);
  1123. switch (msg.action_type) {
  1124. case ActionType.walk:
  1125. const walk = msg as any as MoveRequest;
  1126. this.walking(walk);
  1127. break;
  1128. case ActionType.joystick:
  1129. const JoystickRequest = msg as any as JoystickRequest;
  1130. this.joystick(JoystickRequest);
  1131. break;
  1132. case ActionType.breathPoint:
  1133. this.handleBreath(msg);
  1134. break;
  1135. case ActionType.rotate:
  1136. const rotateRequest: RotateRequest = msg;
  1137. this.rotate(rotateRequest);
  1138. break;
  1139. case ActionType.userStatus:
  1140. this.updateUserStatus(msg);
  1141. break;
  1142. case ActionType.status:
  1143. this.updateStatus();
  1144. break;
  1145. default:
  1146. break;
  1147. }
  1148. }
  1149. }
  1150. } catch (error) {
  1151. this.logger.error('handleMessage:rtc--error', error.message);
  1152. }
  1153. }
  1154. async handleIframeRequest() {
  1155. //TODO Iframe 最终传什么?
  1156. this.holdSteam();
  1157. this.requestIFrameQueue.next(this.streamService.lastStreamFrame.getValue());
  1158. if (!this.requestIFrameQueueSub) {
  1159. this.requestIFrameQueueSub = this.requestIFrameQueue.subscribe(
  1160. async (frameData: StreamFrameType) => {
  1161. if (frameData) {
  1162. this.globalOptLock = true;
  1163. const nextFrame = this.frameCnt.getValue() + 1;
  1164. this.logger.warn('lostIframe:' + nextFrame);
  1165. frameData.frame = nextFrame;
  1166. frameData.DIR = 1;
  1167. const res = await this.streamService.pushFrameToSteam(frameData);
  1168. if (res.done) {
  1169. this.logger.error(
  1170. ' frame:' + res.frame + ' 补帧::' + JSON.stringify(frameData),
  1171. );
  1172. this.frameCnt.next(res.frame);
  1173. clearTimeout(this._packFrameTimeout);
  1174. this._packFrameTimeout = setTimeout(() => {
  1175. this.resumeStream();
  1176. this.globalOptLock = false;
  1177. }, 100);
  1178. } else {
  1179. console.error('补帧有误:', JSON.stringify(frameData));
  1180. }
  1181. }
  1182. },
  1183. );
  1184. }
  1185. }
  1186. handleBreath(request) {
  1187. const npsRes = this.moveService.getBreakPoints(request);
  1188. //this.logger.info('npsRes', npsRes.nps);
  1189. this.streamService.pushNormalDataToStream(npsRes);
  1190. }
  1191. updateStatus(): void {
  1192. const reply = {
  1193. data: { action_type: 1009, echo_msg: { echoMsg: Date.now() } },
  1194. track: false,
  1195. };
  1196. this.streamService.pushNormalDataToStream(reply);
  1197. }
  1198. updateUserStatus(request) {
  1199. try {
  1200. const usersData = this.rotateService.getNewUserStateRequest(request);
  1201. if (usersData) {
  1202. usersData.actionType = 1024;
  1203. //this.logger.info(
  1204. // 'joystick:->updateUserStatus' +
  1205. // 'playerPosition:' +
  1206. // JSON.stringify(
  1207. // redisMeta['newUserStates'][0].playerState.player.position,
  1208. // ),
  1209. // );
  1210. this.streamService.pushNormalDataToStream(usersData);
  1211. } else {
  1212. this.logger.error('updateUserStatus::function-empty');
  1213. }
  1214. } catch (error) {
  1215. this.logger.error('updateUserStatus::function', error.message);
  1216. }
  1217. }
  1218. pushFirstRender(clipPath: string, metaData: string): Promise<boolean> {
  1219. return new Promise<boolean>(async (resolve, reject) => {
  1220. try {
  1221. const streamData: StreamFrameType = {
  1222. frame: 1,
  1223. clipPath: clipPath,
  1224. metaData: metaData,
  1225. serverTime: this.mockserverTime,
  1226. DIR: 1,
  1227. };
  1228. const hasPush = await this.streamService.pushFrameToSteam(streamData);
  1229. return resolve(hasPush.done);
  1230. } catch (error) {
  1231. return reject(false);
  1232. }
  1233. });
  1234. }
  1235. handleStream() {
  1236. this.logger.info('this.frameCntSubscription', this.frameCntSubscription);
  1237. let redisData;
  1238. if (!this.frameCntSubscription) {
  1239. this.frameCntSubscription = this.frameCnt.subscribe(async (frame) => {
  1240. try {
  1241. this.logger.info('frame: ' + frame);
  1242. console.log(
  1243. 'networkState:::--->' +
  1244. ' maxMessageSize: ' +
  1245. this.channel.maxMessageSize() +
  1246. ' bytesReceived: ' +
  1247. this.peer.bytesReceived() +
  1248. ' bytesSent: ' +
  1249. this.peer.bytesSent() +
  1250. ' rtt: ' +
  1251. this.peer.rtt() +
  1252. ' state: ' +
  1253. this.peer.state(),
  1254. );
  1255. if (frame === 1) {
  1256. // redisData = await this.rotateService.echo(this.user_id, true);
  1257. const app_id = this.configService.get('app.appId');
  1258. console.log('首页数据', app_id, this.user_id);
  1259. redisData = this.rotateService.getFirstStreamData(
  1260. app_id,
  1261. this.user_id,
  1262. );
  1263. this.logger.warn(
  1264. 'bootstrap:socket::首屏 --->' + JSON.stringify(redisData),
  1265. );
  1266. this.onSteaming = true;
  1267. this.holdSteam();
  1268. if (redisData && 'mediaSrc' in redisData) {
  1269. const mediaSrc: string = redisData.mediaSrc || '';
  1270. if (mediaSrc.length > 0) {
  1271. const src = mediaSrc.split('?')[0];
  1272. const clipPath = this.configService.get('app.prefix') + src;
  1273. delete redisData.mediaSrc;
  1274. this.logger.info(
  1275. `user:${this.user_id}:first render stream` +
  1276. JSON.stringify({ path: clipPath, meta: redisData }),
  1277. );
  1278. const status = await this.pushFirstRender(
  1279. clipPath,
  1280. JSON.stringify(redisData),
  1281. );
  1282. if (status) {
  1283. this.firstRender = true;
  1284. this.frameCnt.next(2);
  1285. this.resumeStream();
  1286. } else {
  1287. this.logger.error('first render problem', status);
  1288. }
  1289. }
  1290. } else {
  1291. this.logger.error(`first render problem:${frame}`);
  1292. }
  1293. }
  1294. if (frame > 1) {
  1295. const isOk =
  1296. !this.onMoving.value &&
  1297. !this.onRotating.value &&
  1298. !this.onJoysticking.value &&
  1299. !this.onSteaming &&
  1300. this.firstRender;
  1301. console.log(
  1302. '空白流条件-->:' +
  1303. isOk +
  1304. ' onMoving: ' +
  1305. this.onMoving.value +
  1306. ' onRotating: ' +
  1307. this.onRotating.value +
  1308. ' onJoysticking: ' +
  1309. this.onJoysticking.value +
  1310. ' onSteaming: ' +
  1311. this.onSteaming +
  1312. ' firstRender: ' +
  1313. this.firstRender,
  1314. );
  1315. }
  1316. if (
  1317. frame > 1 &&
  1318. !this.onMoving.value &&
  1319. !this.onRotating.value &&
  1320. !this.onJoysticking.value &&
  1321. !this.onSteaming &&
  1322. this.firstRender
  1323. ) {
  1324. // debugger
  1325. const redisDataAuto = await this.rotateService.echo(
  1326. this.user_id,
  1327. false,
  1328. );
  1329. if (redisDataAuto) {
  1330. this.logger.info(`空白流::有数据:${frame}`);
  1331. 'mediaSrc' in redisDataAuto && delete redisDataAuto.mediaSrc;
  1332. const streamMeta: StreamMetaType = {
  1333. frame: frame,
  1334. metaData: JSON.stringify(redisDataAuto),
  1335. };
  1336. this.streamService.pushMetaDataToSteam(streamMeta);
  1337. } else {
  1338. this.stopStream();
  1339. this.logger.info('空流无Redis数据');
  1340. }
  1341. }
  1342. } catch (error) {
  1343. if (this.frameCnt.getValue() === 1) {
  1344. this.logger.error('首屏读取有误:', redisData, error.message);
  1345. }
  1346. this.stopStream();
  1347. this.logger.error('handleStream', error.message);
  1348. }
  1349. });
  1350. }
  1351. }
  1352. }