scene.service.ts 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081
  1. import { Injectable, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
  2. import { ClientGrpc, Client } from '@nestjs/microservices';
  3. import { grpcClientOptions } from './grpc-scene.options';
  4. import { Logger } from '@nestjs/common';
  5. import { DataChannel } 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. @Injectable()
  20. export class SceneService implements OnModuleInit, OnModuleDestroy {
  21. constructor(
  22. private configService: ConfigService,
  23. private cacheService: CacheService,
  24. private streamService: StreamService,
  25. private rotateService: RotateService,
  26. private moveService: MoveService,
  27. private getRouterService: GetRouterService, // @InjectQueue('rotate') private rotateQueue: Queue, // @InjectQueue('walking') private walkingQueue: Queue,
  28. ) { }
  29. @Client(grpcClientOptions) private readonly client: ClientGrpc;
  30. public _frameInteval: NodeJS.Timeout;
  31. public _frameTimeout: NodeJS.Timeout;
  32. public _rotateTimeout: NodeJS.Timeout;
  33. public _moveTimeout: NodeJS.Timeout;
  34. public _JoyStickingTimeout: NodeJS.Timeout;
  35. public startSteaming = new BehaviorSubject<boolean>(false);
  36. public onRotating = new BehaviorSubject<boolean>(false);
  37. public onMoving = new BehaviorSubject<boolean>(false);
  38. public onJoysticking = new BehaviorSubject<boolean>(false);
  39. public frameCnt = new BehaviorSubject<number>(-1);
  40. private rotateframeCnt = -1;
  41. private moveframeCnt = -1;
  42. private joystickFrameCnt = -1;
  43. private rotateFirstIDR = true;
  44. private sceneGrpcService: SceneGrpcService;
  45. private channel: DataChannel;
  46. private logger: Logger = new Logger('SceneService');
  47. private frameCntInterval = 1000;
  48. private user_id: string;
  49. private roomId: string;
  50. private onSteaming = false;
  51. private mockserverTime = Date.now() - 1653000000478;
  52. private lastRenderMedia = '';
  53. private frameCntSubscription: any;
  54. private roQueueSubscription: any;
  55. private moveQueueSubscription: any;
  56. private walkingSub: any;
  57. private joystickSub: any;
  58. private clickQueueSub: any;
  59. private _rotateCurrentFame = -1;
  60. private _rotateCount = -1;
  61. private streamServiceSub: any;
  62. // private roRequestQueue: RxQueue = new DelayQueue(20);
  63. private roQueue: RxQueue = new DelayQueue(
  64. Number(this.configService.get('queueConfig.rotate')) || 20,
  65. );
  66. private clickQueue: RxQueue = new DebounceQueue(500);
  67. private moveQueue: RxQueue = new DelayQueue(
  68. Number(this.configService.get('queueConfig.move')) || 20,
  69. );
  70. private joystickQueue: RxQueue = new DebounceQueue(500);
  71. private requestIFrameQueue: RxQueue = new DebounceQueue(2000);
  72. private requestIFrameQueueSub: any;
  73. private roRequestQueueSub: any;
  74. private rotateTimeStamp: number;
  75. private rewalking = false;
  76. private firstRender = false;
  77. private latestBreakPointId: number;
  78. private isHoldingStream = false;
  79. private lastMovingPointArray: MovingLastUpdateType[] = [];
  80. private latestWalkingRequest: any; // 最新waking的接收值
  81. private hasJoystickMoveRequest = false; // 最新joystick的接收值
  82. private moveSliceLastFrame = new BehaviorSubject<MovingLastUpdateType>(null);
  83. private moveSliceLastFrameSub: any;
  84. public lastMoveStreamFrame = new BehaviorSubject<StreamFrameType>({
  85. frame: -1,
  86. clipPath: '',
  87. metaData: '',
  88. });
  89. public lastMoveStreamFrameBk: StreamFrameType = {
  90. frame: -1,
  91. clipPath: '',
  92. metaData: '',
  93. };
  94. public users = {};
  95. // initUsers(app_id, userId) {
  96. // const user = {
  97. // appId: null,
  98. // userId: null,
  99. // breakPointId: null,
  100. // roomId: null,
  101. // player: {
  102. // position: { x: -700, y: 0, z: 0 },
  103. // angle: {
  104. // pitch: 0,
  105. // yaw: 0,
  106. // roll: 0,
  107. // },
  108. // },
  109. // camera: {
  110. // position: { x: -1145, y: 0, z: 160 },
  111. // angle: {
  112. // pitch: 0,
  113. // yaw: 0,
  114. // roll: 0,
  115. // },
  116. // },
  117. // rotateInfo: {
  118. // frameIndex: 0,
  119. // horizontal_move: 0,
  120. // mediaSrc: null,
  121. // },
  122. // moveInfo: {},
  123. // // traceIds: [],
  124. // // actionResponses:[]
  125. // };
  126. // user.appId = app_id;
  127. // user.userId = userId;
  128. // user.breakPointId = 100;
  129. // this.users[userId] = user;
  130. // }
  131. onModuleInit(): void {
  132. this.sceneGrpcService =
  133. this.client.getService<SceneGrpcService>('SceneGrpcService');
  134. this.logger.log('init SceneGrpcService');
  135. this.streamServiceSub = this.streamService.onSteaming.subscribe((val) => {
  136. this.onSteaming = val;
  137. });
  138. Number.prototype.padLeft = function (n, str) {
  139. return Array(n - String(this).length + 1).join(str || '0') + this;
  140. };
  141. this.logger.log('roQueue-period :' + Number(this.roQueue.period));
  142. this.logger.log('moveQueue-period :' + Number(this.moveQueue.period));
  143. }
  144. public isHeaderOrLast(index: number, length: number): boolean {
  145. if (index === 0 || index === length) {
  146. return true;
  147. } else {
  148. return false;
  149. }
  150. }
  151. public getConfig() {
  152. return {
  153. userId: this.user_id,
  154. roomId: this.roomId,
  155. };
  156. }
  157. public startStream(): void {
  158. clearInterval(this._frameInteval);
  159. if (this.frameCnt.value === -1) {
  160. this._frameInteval = setInterval(async () => {
  161. const next = this.frameCnt.value + 1;
  162. this.frameCnt.next(next);
  163. }, 1000);
  164. }
  165. }
  166. public holdSteam(): void {
  167. clearInterval(this._frameInteval);
  168. this.isHoldingStream = true;
  169. }
  170. public resumeStream(): void {
  171. this.onMoving.next(false);
  172. this.onRotating.next(false);
  173. this.isHoldingStream = false;
  174. this.moveframeCnt = -1;
  175. this.rotateframeCnt = -1;
  176. clearInterval(this._frameInteval);
  177. this._frameInteval = setInterval(async () => {
  178. const next = this.frameCnt.getValue() + 1;
  179. this.frameCnt.next(next);
  180. }, 1000);
  181. }
  182. public stopStream(): void {
  183. if (this.frameCntSubscription) {
  184. this.frameCntSubscription.unsubscribe();
  185. this.frameCntSubscription = null;
  186. }
  187. if (this.roQueueSubscription) {
  188. this.roQueueSubscription.unsubscribe();
  189. this.roQueueSubscription = null;
  190. }
  191. if (this.moveQueueSubscription) {
  192. this.moveQueueSubscription.unsubscribe();
  193. this.moveQueueSubscription = null;
  194. }
  195. this.frameCnt.next(-1);
  196. clearInterval(this._frameInteval);
  197. this.rotateframeCnt = -1;
  198. }
  199. setConfig(user_id: string, roomId: string): void {
  200. this.user_id = user_id;
  201. this.roomId = roomId;
  202. }
  203. onModuleDestroy() {
  204. if ('unsubscribe' in this.streamServiceSub) {
  205. this.streamService.onSteaming.unsubscribe();
  206. }
  207. }
  208. init(request: InitRequest) {
  209. try {
  210. this.rotateService.init(request.app_id, request.user_id);
  211. // 加载
  212. // let path: string;
  213. // if (process.env.NODE_ENV === 'development') {
  214. // path = join(
  215. // __dirname,
  216. // `../ws/${request.app_id}/points-${request.app_id}.json`,
  217. // );
  218. // console.log('测试服JSON', path);
  219. // }
  220. // if (process.env.NODE_ENV === 'production') {
  221. // path = join(
  222. // `${this.configService.get('app.prefix')}/${request.app_id}/points-${
  223. // request.app_id
  224. // }.json`,
  225. // );
  226. // console.log('正式服JSON', path);
  227. // }
  228. // this.moveService.loadJSON(path);
  229. // this.getRouterService.loadJSON(path);
  230. this.startSteaming.next(true);
  231. this.startStream();
  232. this.handleStream();
  233. // this.moveService.init(request.app_id, request.user_id);
  234. // this.initUsers(request.app_id, request.user_id);
  235. } catch (error) {
  236. this.logger.error('error', error);
  237. }
  238. }
  239. exit() {
  240. this.frameCnt.next(-1);
  241. this.rotateService.deleteUser(this.user_id);
  242. }
  243. async rotate(request: RotateRequest) {
  244. this.handleRotate(request);
  245. this._rotateCount += 1;
  246. //this.logger.log('request', request)
  247. // this.roRequestQueue.next(request);
  248. // if (!this.roRequestQueueSub) {
  249. // this.handleRotate();
  250. // }
  251. }
  252. /**
  253. * rotate请求队列
  254. */
  255. async handleRotate(request) {
  256. // this.roRequestQueueSub = this.roRequestQueue.subscribe(
  257. // async (request: RotateRequest) => {
  258. // try {
  259. if (this.firstRender) {
  260. if (!this.roQueueSubscription) {
  261. this.handleRotateStream();
  262. }
  263. let redisMeta: StreamReplyType;
  264. this.onRotating.next(true);
  265. const start = performance.now();
  266. // 当move时处理 _rotateCount是移动端同时触发的问题
  267. if (this.onMoving.value && this._rotateCount > 5) {
  268. const lastStreamFrame = this.lastMoveStreamFrame.getValue();
  269. const lastMoveStreamFrameBk = this.lastMoveStreamFrameBk;
  270. //TODO对比
  271. this.logger.log('lastStreamFrame', JSON.stringify(lastStreamFrame));
  272. this.logger.log(
  273. 'lastMoveStreamFrameBk',
  274. JSON.stringify(lastMoveStreamFrameBk),
  275. );
  276. const metaData: StreamReplyType = JSON.parse(
  277. lastStreamFrame.metaData,
  278. ) as any as StreamReplyType;
  279. console.log('stop-4', metaData.traceIds[0]);
  280. console.log('stop-5', request.trace_id);
  281. //判断request是否是新的
  282. if (metaData.traceIds.indexOf(request.trace_id) > -1) {
  283. return;
  284. }
  285. const newUserStates: NewUserStatesType = metaData.newUserStates.find(
  286. (item) => item.userId === this.user_id,
  287. );
  288. const trace_id = metaData.traceIds[0];
  289. const userId = newUserStates.userId;
  290. const breakPointId = metaData.endBreakPointId;
  291. const cameraAngle = newUserStates.playerState.camera.angle;
  292. const playerAngle = newUserStates.playerState.player.angle;
  293. this.logger.log(
  294. 'stop-data-0',
  295. trace_id,
  296. userId,
  297. cameraAngle,
  298. cameraAngle,
  299. );
  300. //debugger;
  301. redisMeta = await this.moveService.stop(
  302. trace_id,
  303. userId,
  304. breakPointId,
  305. cameraAngle,
  306. playerAngle,
  307. );
  308. this.logger.log('stop-redisMeta', redisMeta);
  309. this.onMoving.next(false);
  310. this.cleanMoveSteam();
  311. // redisMeta = await this.rotateService.rotate(request);
  312. } else {
  313. // 正常rotate
  314. redisMeta = await this.rotateService.seqExeRotate(request);
  315. }
  316. if (redisMeta && 'mediaSrc' in redisMeta) {
  317. const mediaSrc: string = redisMeta.mediaSrc || '';
  318. if (mediaSrc.length > 0) {
  319. const src = mediaSrc.split('?')[0];
  320. //this.logger.log('进入roQueue1', redisMeta.newUserStates[0].playerState.camera.angle.yaw);
  321. //this.logger.log('进入roQueue2', src);
  322. if (src.length > 0) {
  323. //this.logger.log('不同源');
  324. this.holdSteam();
  325. this.lastRenderMedia = src;
  326. const clipPath = this.configService.get('app.prefix') + src;
  327. //TODO 临时开出
  328. // delete redisMeta.mediaSrc;
  329. const stream: StreamFrameType = {
  330. frame: -1,
  331. clipPath: clipPath,
  332. metaData: JSON.stringify(redisMeta),
  333. serverTime: this.mockserverTime,
  334. DIR: 3,
  335. };
  336. //this.logger.log('rotate', stream, Date.now());
  337. clearTimeout(this._rotateTimeout);
  338. //this.logger.log('进入roQueue3', stream.clipPath);
  339. const stop = performance.now();
  340. const inMillSeconds = stop - start;
  341. const rounded = Number(inMillSeconds).toFixed(3);
  342. this.logger.log(`[timer]-rotate-入队列前: ${rounded}ms`);
  343. this.roQueue.next(stream);
  344. } else {
  345. // this.onRotating.next(false);
  346. }
  347. }
  348. }
  349. }
  350. // } catch (error) {
  351. // this.logger.error('rotate', error.message);
  352. // console.error('error', error);
  353. // }
  354. }
  355. async walking(request: MoveRequest) {
  356. this.latestWalkingRequest = request;
  357. this.logger.log('walking-trace_id', request.trace_id);
  358. // 进入正常walking流程
  359. if (!this.onMoving.getValue()) {
  360. console.log('walking-step-main-1', request.trace_id);
  361. this.latestWalkingRequest = null;
  362. this.handleWalking(request);
  363. }
  364. console.log('moveSliceLastFrameSub', this.moveSliceLastFrameSub);
  365. // 监听每小段最后一帧
  366. if (!this.moveSliceLastFrameSub) {
  367. this.moveSliceLastFrameSub = this.moveSliceLastFrame.subscribe(
  368. async (frame: MovingLastUpdateType) => {
  369. // console.log('walkingStop-'+ this.latestWalkingRequest + ','+ this.onMoving.value);
  370. //TODO 正在行走时,有新的reqest
  371. if (this.latestWalkingRequest && this.onMoving.value) {
  372. this.logger.log('stop-data-1', frame);
  373. this.moveQueue.clean();
  374. // this.moveQueueSubscription.unsubscribe();
  375. // this.moveQueueSubscription = null;
  376. //step1 执行stop方法
  377. const metaData: StreamReplyType = frame.metaData;
  378. const newUserStates: NewUserStatesType =
  379. metaData.newUserStates.find(
  380. (item) => item.userId === this.user_id,
  381. );
  382. const trace_id = metaData.traceIds[0];
  383. const userId = newUserStates.userId;
  384. const breakPointId = metaData.endBreakPointId;
  385. const cameraAngle = newUserStates.playerState.camera.angle;
  386. const playerAngle = newUserStates.playerState.player.angle;
  387. this.logger.log(
  388. 'stop-data-2',
  389. trace_id,
  390. userId,
  391. cameraAngle,
  392. cameraAngle,
  393. );
  394. const redisMeta = await this.moveService.stop(
  395. trace_id,
  396. userId,
  397. breakPointId,
  398. cameraAngle,
  399. playerAngle,
  400. );
  401. this.logger.log('stop-redisMeta', JSON.stringify(redisMeta));
  402. // 2. 中断重新walking
  403. console.log(
  404. 'walking-step-reWalking-1',
  405. request.trace_id + ',' + this.latestWalkingRequest.trace_id,
  406. );
  407. this.handleReWalking(this.latestWalkingRequest);
  408. }
  409. },
  410. );
  411. }
  412. }
  413. /**
  414. * 行走队列处理器
  415. * @param request MoveRequest
  416. * @returns void
  417. */
  418. async handleWalking(request: MoveRequest): Promise<void> {
  419. try {
  420. // if (!this.onMoving.getValue()) {
  421. console.log('walking-step-main-2', request.trace_id);
  422. const start = performance.now();
  423. this._rotateCount = 0;
  424. const user = this.moveService.users[this.user_id];
  425. console.log('进入1 - searchRoad');
  426. console.log('path-start' + user.breakPointId);
  427. const path = await this.getRouterService.searchRoad(
  428. user.appId,
  429. user.breakPointId,
  430. request.clicking_action.clicking_point,
  431. );
  432. this.logger.log('walking-path', path);
  433. if (!path) {
  434. console.log('不存在--path', path);
  435. this.resumeStream();
  436. return;
  437. }
  438. // debugger;
  439. const walkingRes = await this.moveService.move(path, request);
  440. //this.logger.log('walking', walkingRes);
  441. // debugger;
  442. // console.log('walking:'+JSON.stringify(walkingRes))
  443. // console.log('this.onMoving.value:'+this.onMoving.value)
  444. if (walkingRes && (!this.onMoving.value || this.rewalking)) {
  445. //this.logger.log('walkingRes-front', walkingRes);
  446. // shift出前第一个镜头数据
  447. const rotateCamData = walkingRes[0];
  448. this.logger.log('rotateCamData', rotateCamData.length);
  449. if (rotateCamData?.length) {
  450. // 头数组[0] rotate 序列, 头是关键key
  451. walkingRes[0].forEach((item: StreamReplyType, index: number) => {
  452. item.mType = 'rotate';
  453. // item.DIR = index === 0 ? 1 : 3;
  454. const IDRflag = index % 5 === 0 ? 1 : 3;
  455. const dir = this.isHeaderOrLast(index, walkingRes[0].length - 1);
  456. item.DIR = dir ? 1 : IDRflag;
  457. });
  458. } else {
  459. this.logger.log('rotateCamData无数据');
  460. }
  461. // 二维数组 做move 序列, move类型
  462. //console.log('move-walkingRes:' + JSON.stringify(walkingRes));
  463. if (walkingRes && walkingRes?.length >= 1) {
  464. for (let i = 1; i < walkingRes.length; i++) {
  465. Array.from(walkingRes[i]).forEach(
  466. (item: StreamReplyType, index: number) => {
  467. const IDRflag = index % 5 === 0 ? 1 : 3;
  468. const dir = this.isHeaderOrLast(
  469. index,
  470. walkingRes[i].length - 1,
  471. );
  472. item.DIR = dir ? 1 : IDRflag;
  473. //将每段最后一个推入lastMovingPointArray
  474. if (index === walkingRes[i].length - 1) {
  475. this.lastMovingPointArray.push({
  476. mediaSrc: item.mediaSrc,
  477. metaData: item,
  478. });
  479. }
  480. },
  481. );
  482. }
  483. }
  484. // walkingRes marker to everybody
  485. const seqs = Array.from(walkingRes).flat() as any as StreamReplyType[];
  486. if (seqs?.length) {
  487. this.logger.log('walking --总序列--seqs-2:' + seqs.length);
  488. const stop = performance.now();
  489. const inMillSeconds = stop - start;
  490. const rounded = Number(inMillSeconds).toFixed(3);
  491. this.logger.log(`[timer]-move-入队列前:-->${rounded}ms`);
  492. this.handleSeqMoving(seqs);
  493. } else {
  494. console.error('walking-move无数据');
  495. this.cleanMoveSteam();
  496. this.resumeStream();
  497. }
  498. // }
  499. }
  500. // });
  501. // }
  502. } catch (error) {
  503. this.logger.error('walking', error.message);
  504. this.cleanMoveSteam();
  505. this.resumeStream();
  506. }
  507. }
  508. /**
  509. * 改变路线后的walking队列处理(中转)
  510. * @param request MoveRequest
  511. */
  512. handleReWalking(request: MoveRequest) {
  513. this.latestWalkingRequest = null;
  514. this.rewalking = true;
  515. this.handleWalking(request);
  516. }
  517. /***
  518. * joystick main core
  519. */
  520. async joystick(request: JoystickRequest) {
  521. // TODO hasJoystickMoveRequest中断
  522. this.logger.log('this.hasJoystickMoveRequest', this.hasJoystickMoveRequest);
  523. if (!this.hasJoystickMoveRequest) {
  524. this.handlejoystick(request);
  525. }
  526. }
  527. /***
  528. * joystick
  529. */
  530. async handlejoystick(request: JoystickRequest) {
  531. try {
  532. //const joystickRes = await this.moveService.joystick(request);
  533. this._rotateCount = 0;
  534. const joystickRes = await this.moveService.seqExeJoystick(request);
  535. this.logger.log(
  536. 'joystick-breakPointId:' +
  537. this.moveService.users[this.user_id].breakPointId,
  538. );
  539. // 有数据 [0]是rotate数据,[1-infinity]是walking数据
  540. this.logger.log('joystickRes-1', joystickRes);
  541. this.onJoysticking.next(true);
  542. if (Array.isArray(joystickRes)) {
  543. // 处理第一个镜头数据
  544. const rotateCamData = joystickRes[0];
  545. this.logger.log('rotateCamData', rotateCamData.length);
  546. if (rotateCamData?.length) {
  547. // 头数组[0] rotate 序列, 头是关键key
  548. joystickRes[0].forEach((item: StreamReplyType, index: number) => {
  549. const IDRflag = index % 5 === 0 ? 1 : 3;
  550. const dir = this.isHeaderOrLast(index, joystickRes[0].length - 1);
  551. item.DIR = dir ? 1 : IDRflag;
  552. item.mType = 'rotate';
  553. });
  554. } else {
  555. this.logger.log('rotateCamData无数据');
  556. }
  557. // 二维数组 做move 序列, move类型
  558. if (joystickRes?.length >= 1) {
  559. for (let i = 1; i < joystickRes.length; i++) {
  560. this.logger.log('joystickRes-2', joystickRes[i]);
  561. Array.from(joystickRes[i]).forEach(
  562. (item: StreamReplyType, index: number) => {
  563. const IDRflag = index % 5 === 0 ? 1 : 3;
  564. const dir = this.isHeaderOrLast(
  565. index,
  566. joystickRes[i].length - 1,
  567. );
  568. item.DIR = dir ? 1 : IDRflag;
  569. // 将每段最后一个推入lastMovingPointArray
  570. if (index === joystickRes[i].length - 1) {
  571. this.lastMovingPointArray.push({
  572. mediaSrc: item.mediaSrc,
  573. metaData: item,
  574. });
  575. }
  576. //this.logger.log(
  577. // 'joystick:' +
  578. // JSON.stringify(
  579. // joystickRes[i][index]['newUserStates'][0].playerState
  580. // .camera.position,
  581. // ),
  582. // );
  583. },
  584. );
  585. }
  586. }
  587. const seqs = Array.from(joystickRes).flat() as any as StreamReplyType[];
  588. if (seqs?.length > 1) {
  589. this.logger.log('joystick:-seqs', seqs.length);
  590. //TODO joystick中断逻辑
  591. this.hasJoystickMoveRequest = true;
  592. this.handleSeqMoving(seqs);
  593. } else {
  594. console.warn('joystick-move无数据');
  595. }
  596. } else {
  597. this.logger.log('joystick-接收人物数据', this.onMoving.getValue());
  598. if (!this.onMoving.getValue()) {
  599. // 在非行走时接受
  600. this.holdSteam();
  601. if (this.joystickFrameCnt === -1) {
  602. this.joystickFrameCnt = this.frameCnt.getValue();
  603. }
  604. this.joystickFrameCnt += 1;
  605. const stream: StreamMetaType = {
  606. frame: this.joystickFrameCnt,
  607. metaData: JSON.stringify(joystickRes),
  608. };
  609. //this.logger.log('rotate', stream, Date.now());
  610. const res = await this.streamService.pushMetaDataToSteam(stream);
  611. if (res.done) {
  612. this.logger.log('joystick-frame', res.frame);
  613. this.frameCnt.next(res.frame);
  614. clearTimeout(this._JoyStickingTimeout);
  615. this._JoyStickingTimeout = setTimeout(() => {
  616. this.logger.log('joystick opt done');
  617. this.logger.log('joystick 交权给空流,当前pts', res.frame);
  618. // this.frameCnt.next(res.frame);
  619. this.onJoysticking.next(false);
  620. this.resumeStream();
  621. this.joystickFrameCnt = -1;
  622. }, 100);
  623. }
  624. }
  625. }
  626. } catch (error) {
  627. console.error('joystick错误', error);
  628. this.logger.error('joystick', error.message);
  629. }
  630. }
  631. /**
  632. * 主要处理moving的序列动作
  633. * @param seqs StreamReplyType[]
  634. */
  635. handleSeqMoving(seqs: StreamReplyType[]) {
  636. if (!this.moveQueueSubscription) {
  637. this.handleMoveSteam();
  638. }
  639. this.logger.log('moving-seqs', seqs.length);
  640. this.onMoving.next(true);
  641. this.holdSteam();
  642. //TODO Remove
  643. // clearTimeout(this._JoyStickingTimeout);
  644. seqs.forEach((frame: StreamReplyType) => {
  645. const mediaSrc = frame.mediaSrc;
  646. const src = mediaSrc.split('?')[0];
  647. const clipPath = this.configService.get('app.prefix') + src;
  648. const type = frame.mType?.length ? frame.mType.slice() : 'move';
  649. const stream: StreamFrameType = {
  650. frame: -1,
  651. clipPath: clipPath,
  652. metaData: JSON.stringify(frame),
  653. serverTime: this.mockserverTime,
  654. DIR: frame.DIR,
  655. mType: type,
  656. };
  657. this.moveQueue.next(stream);
  658. });
  659. }
  660. cleanMoveSteam() {
  661. if (this.moveQueueSubscription) {
  662. this.moveQueueSubscription.unsubscribe();
  663. this.moveQueueSubscription = null;
  664. }
  665. if (this.walkingSub) {
  666. this.walkingSub.unsubscribe();
  667. this.walkingSub = null;
  668. }
  669. if (this.moveSliceLastFrameSub) {
  670. this.moveSliceLastFrameSub.unsubscribe();
  671. this.moveSliceLastFrameSub = null;
  672. }
  673. // if (this.clickQueueSub) {
  674. // this.clickQueueSub.unsubscribe();
  675. // this.clickQueueSub = null;
  676. // }
  677. }
  678. handleMoveSteam() {
  679. this.moveQueueSubscription = this.moveQueue.subscribe(
  680. async (stream: StreamFrameType) => {
  681. try {
  682. const metaData: StreamReplyType = JSON.parse(stream.metaData);
  683. if (this.moveframeCnt === -1) {
  684. this.moveframeCnt = this.frameCnt.getValue();
  685. }
  686. this.moveframeCnt += 1;
  687. this.latestBreakPointId = metaData.endBreakPointId;
  688. const streamData: StreamFrameType = {
  689. frame: this.moveframeCnt,
  690. clipPath: stream.clipPath,
  691. metaData: stream.metaData,
  692. serverTime: this.mockserverTime,
  693. DIR: stream.DIR,
  694. };
  695. this.logger.log(
  696. '[media-move]: ' +
  697. ', moveframeCnt: ' +
  698. this.moveframeCnt +
  699. ', clipPath: ' +
  700. stream.clipPath +
  701. ', mType: ' +
  702. stream.mType +
  703. ', DIR: ' +
  704. stream.DIR,
  705. // stream.metaData,
  706. );
  707. this.logger.log(
  708. '[media-move-lastMovingPointArray]',
  709. this.lastMovingPointArray?.length,
  710. );
  711. // 记录lastMoveStreamFrame给打断逻辑使用
  712. this.lastMoveStreamFrame.next(streamData);
  713. this.lastMoveStreamFrameBk = streamData;
  714. const res = await this.streamService.pushFrameToSteam(streamData);
  715. const isLastFrameIndex = this.lastMovingPointArray.findIndex(
  716. (item) => item.mediaSrc === metaData.mediaSrc,
  717. );
  718. //this.logger.log('path-update-index', isLastFrameIndex);
  719. //每一段的最后一帧
  720. if (isLastFrameIndex > -1) {
  721. //this.logger.log('path-update-array', this.lastMovingPointArray);
  722. const currentMeta = this.lastMovingPointArray[isLastFrameIndex];
  723. const userId = this.user_id;
  724. const breakPointId = currentMeta.metaData.endBreakPointId;
  725. const lastReply = currentMeta.metaData;
  726. this.moveService.updateUser(userId, breakPointId, lastReply);
  727. //debugger
  728. this.lastMovingPointArray.splice(isLastFrameIndex, 1);
  729. //TODO 队列每一段最后one frame
  730. this.moveSliceLastFrame.next(currentMeta);
  731. }
  732. if (res.done) {
  733. clearTimeout(this._moveTimeout);
  734. this._moveTimeout = setTimeout(() => {
  735. this.logger.log('move 交权给空流,当前pts', res.frame);
  736. this.rewalking = false;
  737. this.frameCnt.next(res.frame);
  738. this.resumeStream();
  739. this.rotateframeCnt = -1;
  740. this.onMoving.next(false);
  741. this.onJoysticking.next(false);
  742. this.cleanMoveSteam();
  743. this.lastMovingPointArray = [];
  744. this.hasJoystickMoveRequest = false;
  745. this.logger.log('move end');
  746. }, 300);
  747. }
  748. } catch (error) {
  749. this.logger.error('handleMoveSteam::error', error);
  750. }
  751. },
  752. );
  753. }
  754. handleDataChanelOpen(channel: DataChannel): void {
  755. this.channel = channel;
  756. this.streamService.setChannel(channel);
  757. }
  758. handleDataChanelClose(): void {
  759. this.stopStream();
  760. this.startSteaming.next(false);
  761. this.streamService.closeChannel();
  762. // const exitRequest: ExitRequest = {
  763. // action_type: 1002,
  764. // user_id: this.user_id,
  765. // trace_id: '',
  766. // };
  767. this.exit();
  768. }
  769. handleMessage(message: string | Buffer) {
  770. try {
  771. if (typeof message === 'string') {
  772. // wasm:特例, requestIframe
  773. if (message.includes('wasm:')) {
  774. const parseData = message
  775. ? String(message).replace('wasm:', '')
  776. : `{"MstType":1}`;
  777. const msg: RTCMessageRequest = JSON.parse(parseData);
  778. this.logger.error('lostIframe-message', JSON.stringify(msg));
  779. if (msg.MstType === 0) {
  780. this.handleIframeRequest();
  781. }
  782. } else {
  783. const msg: RTCMessageRequest = JSON.parse(message);
  784. // console.log('msg.action_type:' + msg.action_type);
  785. switch (msg.action_type) {
  786. case ActionType.walk:
  787. const walk = msg as any as MoveRequest;
  788. this.walking(walk);
  789. break;
  790. case ActionType.joystick:
  791. const JoystickRequest = msg as any as JoystickRequest;
  792. this.joystick(JoystickRequest);
  793. break;
  794. case ActionType.breathPoint:
  795. this.handleBreath(msg);
  796. break;
  797. case ActionType.rotate:
  798. const rotateRequest: RotateRequest = msg;
  799. this.rotate(rotateRequest);
  800. break;
  801. case ActionType.userStatus:
  802. this.updateUserStatus(msg);
  803. break;
  804. case ActionType.status:
  805. this.updateStatus();
  806. break;
  807. default:
  808. break;
  809. }
  810. }
  811. }
  812. } catch (error) {
  813. this.logger.error('handleMessage:rtc--error', error.message);
  814. }
  815. }
  816. async handleIframeRequest() {
  817. //TODO Iframe 最终传什么?
  818. this.requestIFrameQueue.next(this.streamService.lastStreamFrame.getValue());
  819. if (!this.requestIFrameQueueSub) {
  820. this.requestIFrameQueueSub = this.requestIFrameQueue.subscribe(
  821. (frameData: StreamFrameType) => {
  822. const nextFrame = this.frameCnt.getValue() + 1;
  823. this.logger.warn('lostIframe', nextFrame);
  824. frameData.frame = nextFrame;
  825. this.streamService.pushFrameToSteam(frameData);
  826. this.frameCnt.next(nextFrame);
  827. this.resumeStream();
  828. },
  829. );
  830. }
  831. }
  832. handleBreath(request) {
  833. const npsRes = this.moveService.getBreakPoints(request);
  834. //this.logger.log('npsRes', npsRes.nps);
  835. this.streamService.pushNormalDataToStream(npsRes);
  836. }
  837. updateStatus(): void {
  838. const reply = {
  839. data: { action_type: 1009, echo_msg: { echoMsg: Date.now() } },
  840. track: false,
  841. };
  842. this.streamService.pushNormalDataToStream(reply);
  843. }
  844. updateUserStatus(request) {
  845. try {
  846. const usersData = this.rotateService.getNewUserStateRequest(request);
  847. if (usersData) {
  848. usersData.actionType = 1024;
  849. //this.logger.log(
  850. // 'joystick:->updateUserStatus' +
  851. // 'playerPosition:' +
  852. // JSON.stringify(
  853. // redisMeta['newUserStates'][0].playerState.player.position,
  854. // ),
  855. // );
  856. this.streamService.pushNormalDataToStream(usersData);
  857. } else {
  858. this.logger.error('updateUserStatus::function-empty');
  859. }
  860. } catch (error) {
  861. this.logger.error('updateUserStatus::function', error.message);
  862. }
  863. }
  864. /**
  865. * rotate 推送队列
  866. */
  867. handleRotateStream() {
  868. if (!this.roQueueSubscription) {
  869. this.roQueueSubscription = this.roQueue.subscribe(
  870. async (stream: StreamFrameType) => {
  871. this.rotateTimeStamp = Date.now();
  872. if (this.rotateframeCnt === -1) {
  873. this.rotateframeCnt = this.frameCnt.value;
  874. }
  875. this.rotateframeCnt += 1;
  876. stream.frame = this.rotateframeCnt;
  877. this._rotateCurrentFame += 1;
  878. const IDRflag = this._rotateCurrentFame % 5 === 0 ? 1 : 3;
  879. this.logger.log(
  880. `当前rotate ,mainframeCnt:${this.frameCnt.getValue()}, _rotateCurrentFame:${this._rotateCurrentFame
  881. } IDRflag:${IDRflag}`,
  882. );
  883. stream.DIR = this.rotateFirstIDR ? 1 : IDRflag;
  884. if (this.rotateFirstIDR) {
  885. this.rotateFirstIDR = false;
  886. }
  887. this.logger.log(
  888. '[media-rotate]: ' +
  889. ', frame: ' +
  890. stream.frame +
  891. ', rotateframeCnt: ' +
  892. this.rotateframeCnt +
  893. ', clipPath: ' +
  894. stream.clipPath,
  895. // stream.metaData,
  896. );
  897. // this.logger.log(
  898. // `roQueueSubscription:frame:${this.rotateframeCnt} ` +
  899. // JSON.stringify(stream.metaData),
  900. // );
  901. const res = await this.streamService.pushFrameToSteam(stream);
  902. if (res.done) {
  903. clearTimeout(this._rotateTimeout);
  904. this._rotateTimeout = setTimeout(() => {
  905. this.logger.log('rotate end', Date.now());
  906. this.frameCnt.next(res.frame);
  907. this.resumeStream();
  908. this.rotateframeCnt = -1;
  909. this._rotateCurrentFame = -1;
  910. this.onMoving.next(false);
  911. this.onRotating.next(false);
  912. this.rotateFirstIDR = true;
  913. //TODO rotate完后清除request队列
  914. if (this.roRequestQueueSub) {
  915. this.roRequestQueueSub.unsubscribe();
  916. this.roRequestQueueSub = null;
  917. }
  918. }, 300);
  919. }
  920. },
  921. );
  922. }
  923. }
  924. pushFirstRender(clipPath: string, metaData: string): Promise<boolean> {
  925. return new Promise<boolean>(async (resolve, reject) => {
  926. try {
  927. const streamData: StreamFrameType = {
  928. frame: 1,
  929. clipPath: clipPath,
  930. metaData: metaData,
  931. serverTime: this.mockserverTime,
  932. DIR: 1,
  933. };
  934. const hasPush = await this.streamService.pushFrameToSteam(streamData);
  935. return resolve(hasPush.done);
  936. } catch (error) {
  937. return reject(false);
  938. }
  939. });
  940. }
  941. handleStream() {
  942. this.logger.log('this.frameCntSubscription', this.frameCntSubscription);
  943. if (!this.frameCntSubscription) {
  944. this.frameCntSubscription = this.frameCnt.subscribe(async (frame) => {
  945. try {
  946. this.logger.log('frame', frame);
  947. if (frame === 1) {
  948. const redisData = await this.rotateService.echo(this.user_id, true);
  949. this.logger.log('获取-首屏', redisData);
  950. this.onSteaming = true;
  951. this.holdSteam();
  952. if (redisData && 'mediaSrc' in redisData) {
  953. const mediaSrc: string = redisData.mediaSrc || '';
  954. if (mediaSrc.length > 0) {
  955. const src = mediaSrc.split('?')[0];
  956. // 临时本地替换路经
  957. // src = src.replace('/10086/', '');
  958. // const clipPath = join(__dirname, `../ws/${src}`);
  959. const clipPath = this.configService.get('app.prefix') + src;
  960. delete redisData.mediaSrc;
  961. this.logger.log(
  962. `user:${this.user_id}:first render stream` +
  963. JSON.stringify({ path: clipPath, meta: redisData }),
  964. );
  965. const status = await this.pushFirstRender(
  966. clipPath,
  967. JSON.stringify(redisData),
  968. );
  969. if (status) {
  970. this.firstRender = true;
  971. this.frameCnt.next(2);
  972. this.resumeStream();
  973. } else {
  974. this.logger.error('first render problem', status);
  975. }
  976. }
  977. } else {
  978. this.logger.error(`首屏::无数据:${frame}`);
  979. }
  980. }
  981. if (
  982. frame > 1 &&
  983. !this.onMoving.value &&
  984. !this.onRotating.value &&
  985. !this.onJoysticking.value &&
  986. this.firstRender
  987. ) {
  988. const redisDataAuto = await this.rotateService.echo(
  989. this.user_id,
  990. false,
  991. );
  992. if (redisDataAuto) {
  993. this.logger.log(`空白流::有数据:${frame}`);
  994. 'mediaSrc' in redisDataAuto && delete redisDataAuto.mediaSrc;
  995. const streamMeta: StreamMetaType = {
  996. frame: frame,
  997. metaData: JSON.stringify(redisDataAuto),
  998. };
  999. this.streamService.pushMetaDataToSteam(streamMeta);
  1000. } else {
  1001. this.stopStream();
  1002. this.logger.log('空流无Redis数据');
  1003. throw new Error('空流无Redis数据');
  1004. }
  1005. }
  1006. } catch (error) {
  1007. this.stopStream();
  1008. this.logger.error('handleStream', error.message);
  1009. }
  1010. });
  1011. }
  1012. }
  1013. }