diff --git a/WebApp/src/class/httphandler.ts b/WebApp/src/class/httphandler.ts index 0c8da6ecb..a9672bbb9 100644 --- a/WebApp/src/class/httphandler.ts +++ b/WebApp/src/class/httphandler.ts @@ -68,24 +68,33 @@ function checkSessionId(req: Request, res: Response, next): void { res.sendStatus(404); return; } - lastRequestedTime[id] = Date.now(); + lastRequestedTime.set(id, Date.now()); next(); } function _deleteConnection(sessionId:string, connectionId:string) { clients.get(sessionId).delete(connectionId); - if (connectionPair.has(connectionId)) { - const pair = connectionPair.get(connectionId); - const otherSessionId = pair[0] == sessionId ? pair[1] : pair[0]; - if (otherSessionId) { - if (clients.has(otherSessionId)) { - clients.get(otherSessionId).delete(connectionId); - const array1 = disconnections.get(otherSessionId); - array1.push(new Disconnection(connectionId, Date.now())); + if(isPrivate) { + if (connectionPair.has(connectionId)) { + const pair = connectionPair.get(connectionId); + const otherSessionId = pair[0] == sessionId ? pair[1] : pair[0]; + if (otherSessionId) { + if (clients.has(otherSessionId)) { + clients.get(otherSessionId).delete(connectionId); + const array1 = disconnections.get(otherSessionId); + array1.push(new Disconnection(connectionId, Date.now())); + } } } + } else { + disconnections.forEach((array, id) => { + if (id == sessionId) + return; + array.push(new Disconnection(connectionId, Date.now())); + }); } + connectionPair.delete(connectionId); offers.get(sessionId).delete(connectionId); answers.get(sessionId).delete(connectionId); @@ -106,30 +115,25 @@ function _deleteSession(sessionId: string) { disconnections.delete(sessionId); } -function _checkDeletedSession(sessionId: string): void { - const connectionIds = Array.from(clients.get(sessionId)); - for (const connectionId of connectionIds) { - const pair = connectionPair.get(connectionId); - if (pair == null) { +function _checkForTimedOutSessions(): void { + for (const sessionId of Array.from(clients.keys())) + { + if(!lastRequestedTime.has(sessionId)) continue; - } - const otherSessionId = sessionId === pair[0] ? pair[1] : pair[0]; - if(!lastRequestedTime.has(otherSessionId)) + if(lastRequestedTime.get(sessionId) > Date.now() - TimeoutRequestedTime) continue; - if(lastRequestedTime[otherSessionId] > Date.now() - TimeoutRequestedTime) - continue; - _deleteSession(otherSessionId); + _deleteSession(sessionId); console.log("deleted"); } } -function _getConnection(sessionId: string): string[] { - _checkDeletedSession(sessionId); +function _getConnection(sessionId: string): string[] { + _checkForTimedOutSessions(); return Array.from(clients.get(sessionId)); } function _getDisconnection(sessionId: string, fromTime: number): Disconnection[] { - _checkDeletedSession(sessionId); + _checkForTimedOutSessions(); let arrayDisconnections: Disconnection[] = []; if (disconnections.size != 0 && disconnections.has(sessionId)) { arrayDisconnections = disconnections.get(sessionId); @@ -331,7 +335,11 @@ function postOffer(req: Request, res: Response): void { return; } - connectionPair.set(connectionId, [sessionId, null]); + if(!connectionPair.has(connectionId)) + { + connectionPair.set(connectionId, [sessionId, null]); + } + keySessionId = sessionId; const map = offers.get(keySessionId); map.set(connectionId, new Offer(req.body.sdp, Date.now(), polite)); diff --git a/WebApp/test/httphandler.test.ts b/WebApp/test/httphandler.test.ts index cd6af811f..8e87ee0db 100644 --- a/WebApp/test/httphandler.test.ts +++ b/WebApp/test/httphandler.test.ts @@ -1,16 +1,21 @@ import { getMockReq, getMockRes } from '@jest-mock/express'; import * as httpHandler from '../src/class/httphandler'; +const RetriesToForceTimeout = 11; // Waits a second each time, timeout is 10 sec for httphandler. + describe('http signaling test in public mode', () => { const sessionId = "abcd1234"; const sessionId2 = "abcd5678"; + const sessionId3 = "abcd9101112"; const connectionId = "12345"; const connectionId2 = "67890"; + const connectionId3 = "9101112"; const testsdp = "test sdp"; const { res, next, mockClear } = getMockRes(); - const req = getMockReq({ header: (): string => sessionId }); - const req2 = getMockReq({ header: (): string => sessionId2 }); + const req = getMockReq({ header: jest.fn(() => sessionId) }); + const req2 = getMockReq({ header: jest.fn(() => sessionId2) }); + const req3 = getMockReq({ header: jest.fn(() => sessionId3) }); beforeAll(() => { httpHandler.reset("public"); @@ -18,129 +23,291 @@ describe('http signaling test in public mode', () => { beforeEach(() => { mockClear(); + httpHandler.checkSessionId(req, res, next); + httpHandler.checkSessionId(req2, res, next); }); test('throw check has session', async () => { httpHandler.checkSessionId(req, res, next); - expect(res.sendStatus).toBeCalledWith(404); - expect(next).not.toBeCalled(); + expect(res.sendStatus).toHaveBeenCalledWith(404); + expect(next).not.toHaveBeenCalled(); }); test('create session', async () => { await httpHandler.createSession(sessionId, res); - expect(res.json).toBeCalledWith({ sessionId: sessionId }); + expect(res.json).toHaveBeenCalledWith({ sessionId: sessionId }); }); test('create session2', async () => { await httpHandler.createSession(sessionId2, res); - expect(res.json).toBeCalledWith({ sessionId: sessionId2 }); + expect(res.json).toHaveBeenCalledWith({ sessionId: sessionId2 }); }); test('create connection from session1', async () => { const body = { connectionId: connectionId }; req.body = body; await httpHandler.createConnection(req, res); - expect(res.json).toBeCalledWith({ connectionId: connectionId, polite: true, datetime: expect.anything(), type: "connect" }); + expect(res.json).toHaveBeenCalledWith({ connectionId: connectionId, polite: true, datetime: expect.anything(), type: "connect" }); }); test('create connection from session2', async () => { const body = { connectionId: connectionId2 }; req2.body = body; await httpHandler.createConnection(req2, res); - expect(res.json).toBeCalledWith({ connectionId: connectionId2, polite: true, datetime: expect.anything(), type: "connect" }); + expect(res.json).toHaveBeenCalledWith({ connectionId: connectionId2, polite: true, datetime: expect.anything(), type: "connect" }); }); test('get connection from session1', async () => { await httpHandler.getConnection(req, res); - expect(res.json).toBeCalledWith({ connections: [{ connectionId: connectionId, datetime: expect.anything(), type: "connect" }] }); + const connect = { connectionId: connectionId, datetime: expect.anything(), type: "connect" }; + expect(res.json).toHaveBeenCalledWith({ connections: expect.arrayContaining([connect]) }); }); test('get all from session1', async () => { await httpHandler.getAll(req, res); - expect(res.json).toBeCalledWith({ messages: [{ connectionId: connectionId, datetime: expect.anything(), type: "connect" }] }); + const connect = { connectionId: connectionId, datetime: expect.anything(), type: "connect" }; + expect(res.json).toHaveBeenCalledWith({ messages: expect.arrayContaining([connect]) }); }); test('post offer from session1', async () => { const body = { connectionId: connectionId, sdp: testsdp, datetime: expect.anything(), type: "offer" }; req.body = body; await httpHandler.postOffer(req, res); - expect(res.sendStatus).toBeCalledWith(200); + expect(res.sendStatus).toHaveBeenCalledWith(200); }); test('get offer from session1', async () => { await httpHandler.getOffer(req, res); - expect(res.json).toBeCalledWith({ offers: [] }); + expect(res.json).toHaveBeenCalledWith({ offers: [] }); }); test('get offer from session2', async () => { await httpHandler.getOffer(req2, res); - expect(res.json).toBeCalledWith({ offers: [{ connectionId: connectionId, sdp: testsdp, polite: false, datetime: expect.anything(), type: "offer" }] }); + expect(res.json).toHaveBeenCalledWith({ offers: [{ connectionId: connectionId, sdp: testsdp, polite: false, datetime: expect.anything(), type: "offer" }] }); }); test('post answer from session2', async () => { const body = { connectionId: connectionId, sdp: testsdp }; req2.body = body; await httpHandler.postAnswer(req2, res); - expect(res.sendStatus).toBeCalledWith(200); + expect(res.sendStatus).toHaveBeenCalledWith(200); }); test('get answer from session1', async () => { await httpHandler.getAnswer(req, res); - expect(res.json).toBeCalledWith({ answers: [{ connectionId: connectionId, sdp: testsdp, datetime: expect.anything(), type: "answer" }] }); + expect(res.json).toHaveBeenCalledWith({ answers: [{ connectionId: connectionId, sdp: testsdp, datetime: expect.anything(), type: "answer" }] }); }); test('get answer from session2', async () => { await httpHandler.getAnswer(req2, res); - expect(res.json).toBeCalledWith({ answers: [] }); + expect(res.json).toHaveBeenCalledWith({ answers: [] }); }); test('post candidate from sesson1', async () => { const body = { connectionId: connectionId, candidate: "testcandidate", sdpMLineIndex: 0, sdpMid: 0 }; req.body = body; await httpHandler.postCandidate(req, res); - expect(res.sendStatus).toBeCalledWith(200); + expect(res.sendStatus).toHaveBeenCalledWith(200); }); test('get candidate from session1', async () => { await httpHandler.getCandidate(req, res); - expect(res.json).toBeCalledWith({ candidates: [] }); + expect(res.json).toHaveBeenCalledWith({ candidates: [] }); }); test('get candidate from session2', async () => { await httpHandler.getCandidate(req2, res); - expect(res.json).toBeCalledWith({ candidates: [{ connectionId: connectionId, candidate: "testcandidate", sdpMLineIndex: 0, sdpMid: 0, type: "candidate", datetime: expect.anything() }] }); + expect(res.json).toHaveBeenCalledWith({ candidates: [{ connectionId: connectionId, candidate: "testcandidate", sdpMLineIndex: 0, sdpMid: 0, type: "candidate", datetime: expect.anything() }] }); }); test('delete connection from session2', async () => { const body = { connectionId: connectionId }; req2.body = body; await httpHandler.deleteConnection(req2, res); - expect(res.json).toBeCalledWith({ connectionId: connectionId }); + expect(res.json).toHaveBeenCalledWith({ connectionId: connectionId }); }); - test('no connection get from session1', async () => { - await httpHandler.getConnection(req, res); - expect(res.json).toBeCalledWith({ connections: [] }); + test('disconnection get from session1', async () => { + await httpHandler.getAll(req, res); + const disconnect = { connectionId: connectionId, datetime: expect.anything(), type: "disconnect" }; + expect(res.json).toHaveBeenCalledWith({ messages: expect.arrayContaining([disconnect]) }); }); test('delete connection from session1', async () => { const body = { connectionId: connectionId }; req.body = body; await httpHandler.deleteConnection(req, res); - expect(res.json).toBeCalledWith({ connectionId: connectionId }); + expect(res.json).toHaveBeenCalledWith({ connectionId: connectionId }); }); test('delete session1', async () => { - const req = getMockReq({ header: (): string => sessionId }); + const req = getMockReq({ header: jest.fn(() => sessionId) }); await httpHandler.deleteSession(req, res); - expect(res.sendStatus).toBeCalledWith(200); + expect(res.sendStatus).toHaveBeenCalledWith(200); }); test('delete session2', async () => { - const req2 = getMockReq({ header: (): string => sessionId2 }); + const req2 = getMockReq({ header: jest.fn(() => sessionId2) }); + await httpHandler.deleteSession(req2, res); + expect(res.sendStatus).toHaveBeenCalledWith(200); + }); + + test('disconnection get when session2 disconnects before session1 answer', async () => { + httpHandler.reset("public"); + + await httpHandler.createSession(sessionId, res); + await httpHandler.createSession(sessionId2, res); + + await httpHandler.getAll(req, res); + expect(res.json).toHaveBeenLastCalledWith({ messages: [] }); + + const connectBody = { connectionId: connectionId }; + req.body = connectBody; + await httpHandler.createConnection(req, res); + + const offerBody = { connectionId: connectionId, sdp: testsdp, datetime: expect.anything(), type: "offer" }; + req.body = offerBody; + await httpHandler.postOffer(req, res); + + const offer = { connectionId: connectionId, sdp: testsdp, datetime: expect.anything(), type: "offer", polite: false }; + await httpHandler.getAll(req, res); + expect(res.json).toHaveBeenLastCalledWith({ messages: expect.not.arrayContaining([offer]) }); + await httpHandler.getAll(req2, res); + expect(res.json).toHaveBeenLastCalledWith({ messages: expect.arrayContaining([offer]) }); + + const deleteBody = { connectionId: connectionId }; + req2.body = deleteBody; + await httpHandler.deleteConnection(req, res); + await httpHandler.deleteSession(req, res); + expect(res.sendStatus).toHaveBeenLastCalledWith(200); + + const answerBody = { connectionId: connectionId, sdp: testsdp }; + req2.body = answerBody; + await httpHandler.postAnswer(req2, res); + + const disconnect = { connectionId: connectionId, type: "disconnect", datetime: expect.anything() }; + await httpHandler.getAll(req2, res); + expect(res.json).toHaveBeenLastCalledWith({ messages: expect.arrayContaining([disconnect]) }); + await httpHandler.deleteSession(req2, res); - expect(res.sendStatus).toBeCalledWith(200); }); + + test('Timed out session2 deleted after session1 resends offer', async () => { + httpHandler.reset("public"); + + await httpHandler.createSession(sessionId, res); + await httpHandler.createSession(sessionId2, res); + + req.url = ""; + req2.url = ""; + await httpHandler.checkSessionId(req, res, next); + await httpHandler.checkSessionId(req2, res, next); + + await httpHandler.getAll(req, res); + expect(res.json).toHaveBeenLastCalledWith({ messages: [] }); + + const connectBody = { connectionId: connectionId }; + req.body = connectBody; + await httpHandler.createConnection(req, res); + + const offerBody = { connectionId: connectionId, sdp: testsdp, datetime: expect.anything(), type: "offer" }; + req.body = offerBody; + await httpHandler.postOffer(req, res); + + const offer = { connectionId: connectionId, sdp: testsdp, datetime: expect.anything(), type: "offer", polite: false }; + await httpHandler.getAll(req, res); + expect(res.json).toHaveBeenLastCalledWith({ messages: expect.not.arrayContaining([offer]) }); + await httpHandler.getAll(req2, res); + expect(res.json).toHaveBeenLastCalledWith({ messages: expect.arrayContaining([offer]) }); + + const answerBody = { connectionId: connectionId, sdp: testsdp }; + req2.body = answerBody; + await httpHandler.postAnswer(req2, res); + + // resend offer after answer to simulate PeerCandidate entering into failed state + req.body = offerBody; + await httpHandler.postOffer(req, res); + + // Wait a second and then checkSession for only session1 to force timeout of session2. + for (let i = 0; i < RetriesToForceTimeout + 1; ++i) + { + await httpHandler.checkSessionId(req, res, next); + await new Promise(resolve => setTimeout(resolve, 1000)); + } + + // Get all for session1 to trigger cleaning up associated session that timed out. + await httpHandler.getAll(req, res); + + // Check that we do have session1 still + await httpHandler.checkSessionId(req, res, next); + expect(res.sendStatus).toHaveBeenLastCalledWith(200); + + // Check that we no longer have session2 + await httpHandler.checkSessionId(req2, res, next); + expect(res.sendStatus).toHaveBeenLastCalledWith(404); + + await httpHandler.deleteSession(req, res); + }, 16000); + +test('Timed out sessions are deleted when other sessions check', async () => { + httpHandler.reset("public"); + + await httpHandler.createSession(sessionId, res); + await httpHandler.createSession(sessionId2, res); + await httpHandler.createSession(sessionId3, res); + + req.url = ""; + req2.url = ""; + req3.url = ""; + await httpHandler.checkSessionId(req, res, next); + await httpHandler.checkSessionId(req2, res, next); + await httpHandler.checkSessionId(req3, res, next); + + await httpHandler.getAll(req, res); + expect(res.json).toHaveBeenLastCalledWith({ messages: [] }); + + const connectBody = { connectionId: connectionId }; + req.body = connectBody; + await httpHandler.createConnection(req, res); + + const offerBody = { connectionId: connectionId, sdp: testsdp, datetime: expect.anything(), type: "offer" }; + req.body = offerBody; + await httpHandler.postOffer(req, res); + + const offer = { connectionId: connectionId, sdp: testsdp, datetime: expect.anything(), type: "offer", polite: false }; + await httpHandler.getAll(req, res); + expect(res.json).toHaveBeenLastCalledWith({ messages: expect.not.arrayContaining([offer]) }); + await httpHandler.getAll(req2, res); + expect(res.json).toHaveBeenLastCalledWith({ messages: expect.arrayContaining([offer]) }); + + const answerBody = { connectionId: connectionId, sdp: testsdp }; + req2.body = answerBody; + await httpHandler.postAnswer(req2, res); + + // Wait a second and then checkSession for only session3 to force timeout of session1 & session2. + for (let i = 0; i < RetriesToForceTimeout + 1; ++i) + { + await httpHandler.checkSessionId(req3, res, next); + await new Promise(resolve => setTimeout(resolve, 1000)); + } + + // Get all for session3 to trigger cleaning up sessions that timed out. + await httpHandler.getAll(req3, res); + + // Check that we do have session3 still + await httpHandler.checkSessionId(req3, res, next); + expect(res.sendStatus).toHaveBeenLastCalledWith(200); + + // Check that we do have session1 still + await httpHandler.checkSessionId(req, res, next); + expect(res.sendStatus).toHaveBeenLastCalledWith(404); + + // Check that we no longer have session2 + await httpHandler.checkSessionId(req2, res, next); + expect(res.sendStatus).toHaveBeenLastCalledWith(404); + + await httpHandler.deleteSession(req3, res); +}, 16000); }); describe('http signaling test in private mode', () => { @@ -150,8 +317,8 @@ describe('http signaling test in private mode', () => { const testsdp = "test sdp"; const { res, next, mockClear } = getMockRes(); - const req = getMockReq({ header: (): string => sessionId }); - const req2 = getMockReq({ header: (): string => sessionId2 }); + const req = getMockReq({ header: jest.fn(() => sessionId) }); + const req2 = getMockReq({ header: jest.fn(() => sessionId2) }); beforeAll(() => { httpHandler.reset("private"); @@ -159,140 +326,185 @@ describe('http signaling test in private mode', () => { beforeEach(() => { mockClear(); + + httpHandler.checkSessionId(req, res, next); + httpHandler.checkSessionId(req2, res, next); }); test('throw check has session', async () => { httpHandler.checkSessionId(req, res, next); - expect(res.sendStatus).toBeCalledWith(404); - expect(next).not.toBeCalled(); + expect(res.sendStatus).toHaveBeenCalledWith(404); + expect(next).not.toHaveBeenCalled(); }); test('create session', async () => { await httpHandler.createSession(sessionId, res); - expect(res.json).toBeCalledWith({ sessionId: sessionId }); + expect(res.json).toHaveBeenCalledWith({ sessionId: sessionId }); }); test('create session2', async () => { await httpHandler.createSession(sessionId2, res); - expect(res.json).toBeCalledWith({ sessionId: sessionId2 }); + expect(res.json).toHaveBeenCalledWith({ sessionId: sessionId2 }); }); test('create connection from session1', async () => { const body = { connectionId: connectionId }; req.body = body; await httpHandler.createConnection(req, res); - expect(res.json).toBeCalledWith({ connectionId: connectionId, polite: false, datetime: expect.anything(), type: "connect" }); + expect(res.json).toHaveBeenCalledWith({ connectionId: connectionId, polite: false, datetime: expect.anything(), type: "connect" }); }); test('create connection from session2', async () => { const body = { connectionId: connectionId }; req2.body = body; await httpHandler.createConnection(req2, res); - expect(res.json).toBeCalledWith({ connectionId: connectionId, polite: true, datetime: expect.anything(), type: "connect" }); + expect(res.json).toHaveBeenCalledWith({ connectionId: connectionId, polite: true, datetime: expect.anything(), type: "connect" }); }); test('response status 400 if connecctionId does not set', async () => { - const req3 = getMockReq({ header: (): string => sessionId }); + const req3 = getMockReq({ header: jest.fn(() => sessionId) }); await httpHandler.createConnection(req3, res); - expect(res.status).toBeCalledWith(400); - expect(res.send).toBeCalledWith({ error: new Error(`connectionId is required`) }); + expect(res.status).toHaveBeenCalledWith(400); + expect(res.send).toHaveBeenCalledWith({ error: new Error(`connectionId is required`) }); }); test('response status 400 if aleady used connection', async () => { const sessionId3 = "session3"; await httpHandler.createSession(sessionId3, res); const body = { connectionId: connectionId }; - const req3 = getMockReq({ header: (): string => sessionId3 }); + const req3 = getMockReq({ header: jest.fn(() => sessionId3) }); req3.body = body; await httpHandler.createConnection(req3, res); - expect(res.status).toBeCalledWith(400); - expect(res.send).toBeCalledWith({ error: new Error(`${connectionId}: This connection id is already used.`) }); + expect(res.status).toHaveBeenCalledWith(400); + expect(res.send).toHaveBeenCalledWith({ error: new Error(`${connectionId}: This connection id is already used.`) }); }); test('not connection get from session1', async () => { await httpHandler.getConnection(req, res); - expect(res.json).toBeCalledWith({ connections: [{ connectionId: connectionId, datetime: expect.anything(), type: "connect" }] }); + expect(res.json).toHaveBeenCalledWith({ connections: [{ connectionId: connectionId, datetime: expect.anything(), type: "connect" }] }); }); test('post offer from session1', async () => { const body = { connectionId: connectionId, sdp: testsdp, datetime: expect.anything(), type: "offer" }; req.body = body; await httpHandler.postOffer(req, res); - expect(res.sendStatus).toBeCalledWith(200); + expect(res.sendStatus).toHaveBeenCalledWith(200); }); test('get offer from session1', async () => { await httpHandler.getOffer(req, res); - expect(res.json).toBeCalledWith({ offers: [] }); + expect(res.json).toHaveBeenCalledWith({ offers: [] }); }); test('get offer from session2', async () => { await httpHandler.getOffer(req2, res); - expect(res.json).toBeCalledWith({ offers: [{ connectionId: connectionId, sdp: testsdp, polite: true, datetime: expect.anything(), type: "offer" }] }); + expect(res.json).toHaveBeenCalledWith({ offers: [{ connectionId: connectionId, sdp: testsdp, polite: true, datetime: expect.anything(), type: "offer" }] }); }); test('post answer from session2', async () => { const body = { connectionId: connectionId, sdp: testsdp }; req2.body = body; await httpHandler.postAnswer(req2, res); - expect(res.sendStatus).toBeCalledWith(200); + expect(res.sendStatus).toHaveBeenCalledWith(200); }); test('get answer from session1', async () => { await httpHandler.getAnswer(req, res); - expect(res.json).toBeCalledWith({ answers: [{ connectionId: connectionId, sdp: testsdp, datetime: expect.anything(), type: "answer" }] }); + expect(res.json).toHaveBeenCalledWith({ answers: [{ connectionId: connectionId, sdp: testsdp, datetime: expect.anything(), type: "answer" }] }); }); test('get answer from session2', async () => { await httpHandler.getAnswer(req2, res); - expect(res.json).toBeCalledWith({ answers: [] }); + expect(res.json).toHaveBeenCalledWith({ answers: [] }); }); test('post candidate from sesson1', async () => { const body = { connectionId: connectionId, candidate: "testcandidate", sdpMLineIndex: 0, sdpMid: 0 }; req.body = body; await httpHandler.postCandidate(req, res); - expect(res.sendStatus).toBeCalledWith(200); + expect(res.sendStatus).toHaveBeenCalledWith(200); }); test('get candidate from session1', async () => { await httpHandler.getCandidate(req, res); - expect(res.json).toBeCalledWith({ candidates: [] }); + expect(res.json).toHaveBeenCalledWith({ candidates: [] }); }); test('get candidate from session2', async () => { await httpHandler.getCandidate(req2, res); - expect(res.json).toBeCalledWith({ candidates: [{ connectionId: connectionId, candidate: "testcandidate", sdpMLineIndex: 0, sdpMid: 0, type: "candidate", datetime: expect.anything() }] }); + expect(res.json).toHaveBeenCalledWith({ candidates: [{ connectionId: connectionId, candidate: "testcandidate", sdpMLineIndex: 0, sdpMid: 0, type: "candidate", datetime: expect.anything() }] }); }); test('delete connection from session2', async () => { const body = { connectionId: connectionId }; req2.body = body; await httpHandler.deleteConnection(req2, res); - expect(res.json).toBeCalledWith({ connectionId: connectionId }); + expect(res.json).toHaveBeenCalledWith({ connectionId: connectionId }); }); test('get connection from session1', async () => { await httpHandler.getConnection(req, res); - expect(res.json).toBeCalledWith({ connections: [] }); + expect(res.json).toHaveBeenCalledWith({ connections: [] }); }); test('delete connection from session1', async () => { const body = { connectionId: connectionId }; req.body = body; await httpHandler.deleteConnection(req, res); - expect(res.json).toBeCalledWith({ connectionId: connectionId }); + expect(res.json).toHaveBeenCalledWith({ connectionId: connectionId }); }); test('delete session1', async () => { - const req = getMockReq({ header: (): string => sessionId }); + const req = getMockReq({ header: jest.fn(() => sessionId) }); await httpHandler.deleteSession(req, res); - expect(res.sendStatus).toBeCalledWith(200); + expect(res.sendStatus).toHaveBeenCalledWith(200); }); test('delete session2', async () => { - const req2 = getMockReq({ header: (): string => sessionId2 }); + const req2 = getMockReq({ header: jest.fn(() => sessionId2) }); + await httpHandler.deleteSession(req2, res); + expect(res.sendStatus).toHaveBeenCalledWith(200); + }); + + test('disconnection get when session2 disconnects before session1 answer', async () => { + httpHandler.reset("private"); + + await httpHandler.createSession(sessionId, res); + await httpHandler.createSession(sessionId2, res); + + await httpHandler.getAll(req, res); + expect(res.json).toHaveBeenLastCalledWith({ messages: [] }); + + const connectBody = { connectionId: connectionId }; + req.body = connectBody; + await httpHandler.createConnection(req, res); + req2.body = connectBody; + await httpHandler.createConnection(req2, res); + + const offerBody = { connectionId: connectionId, sdp: testsdp, datetime: expect.anything(), type: "offer" }; + req.body = offerBody; + await httpHandler.postOffer(req, res); + + const offer = { connectionId: connectionId, sdp: testsdp, datetime: expect.anything(), type: "offer", polite: true }; + await httpHandler.getAll(req, res); + expect(res.json).toHaveBeenLastCalledWith({ messages: expect.not.arrayContaining([offer]) }); + await httpHandler.getAll(req2, res); + expect(res.json).toHaveBeenLastCalledWith({ messages: expect.arrayContaining([offer]) }); + + const deleteBody = { connectionId: connectionId }; + req2.body = deleteBody; + await httpHandler.deleteConnection(req, res); + await httpHandler.deleteSession(req, res); + expect(res.sendStatus).toHaveBeenLastCalledWith(200); + + const answerBody = { connectionId: connectionId, sdp: testsdp }; + req2.body = answerBody; + await httpHandler.postAnswer(req2, res); + + const disconnect = { connectionId: connectionId, type: "disconnect", datetime: expect.anything() }; + await httpHandler.getAll(req2, res); + expect(res.json).toHaveBeenLastCalledWith({ messages: expect.arrayContaining([disconnect]) }); + await httpHandler.deleteSession(req2, res); - expect(res.sendStatus).toBeCalledWith(200); }); }); diff --git a/com.unity.renderstreaming/Editor/WebAppDownloader.cs b/com.unity.renderstreaming/Editor/WebAppDownloader.cs index c520d5506..de2e52889 100644 --- a/com.unity.renderstreaming/Editor/WebAppDownloader.cs +++ b/com.unity.renderstreaming/Editor/WebAppDownloader.cs @@ -82,7 +82,7 @@ public static void DownloadWebApp(string version, string dstPath, System.Action< if (version != LatestKnownVersion) { DownloadWebApp(LatestKnownVersion, dstPath, callback); } else { - Debug.LogError($"Failed downloading web server from:{url}. Error: {e.Error}"); + RenderStreaming.Logger.Log(LogType.Error, $"Failed downloading web server from:{url}. Error: {e.Error}"); } callback?.Invoke(false); return; @@ -90,7 +90,7 @@ public static void DownloadWebApp(string version, string dstPath, System.Action< if (!System.IO.File.Exists(tmpFilePath)) { - Debug.LogError($"Download failed. url:{url}"); + RenderStreaming.Logger.Log(LogType.Error, $"Download failed. url:{url}"); callback?.Invoke(false); return; } @@ -123,7 +123,7 @@ public static void GetPackageVersion(string packageName, System.Action c var packageInfo = req.FindPackage(packageName); if (null == packageInfo) { - Debug.LogError($"Not found package \"{packageName}\""); + RenderStreaming.Logger.Log(LogType.Error, $"Not found package \"{packageName}\""); return; } callback(packageInfo.version); diff --git a/com.unity.renderstreaming/Runtime/Scripts/AudioStreamSender.cs b/com.unity.renderstreaming/Runtime/Scripts/AudioStreamSender.cs index 242a2aae0..7188fc423 100644 --- a/com.unity.renderstreaming/Runtime/Scripts/AudioStreamSender.cs +++ b/com.unity.renderstreaming/Runtime/Scripts/AudioStreamSender.cs @@ -26,7 +26,7 @@ public class AudioStreamSender : StreamSenderBase private int m_sampleRate = 0; /// - /// + /// /// public AudioCodecInfo codec { @@ -34,7 +34,7 @@ public AudioCodecInfo codec } /// - /// + /// /// public uint minBitrate { @@ -42,7 +42,7 @@ public uint minBitrate } /// - /// + /// /// public uint maxBitrate { @@ -50,7 +50,7 @@ public uint maxBitrate } /// - /// + /// /// /// static public IEnumerable GetAvailableCodecs() @@ -61,7 +61,7 @@ static public IEnumerable GetAvailableCodecs() } /// - /// + /// /// /// public void SetBitrate(uint minBitrate, uint maxBitrate) @@ -74,12 +74,12 @@ public void SetBitrate(uint minBitrate, uint maxBitrate) { RTCError error = transceiver.Sender.SetBitrate(m_bitrate.min, m_bitrate.max); if (error.errorType != RTCErrorType.None) - Debug.LogError(error.message); + RenderStreaming.Logger.Log(LogType.Error, error.message); } } /// - /// + /// /// /// public void SetCodec(AudioCodecInfo codec) @@ -151,10 +151,9 @@ protected override void OnDisable() protected virtual void OnAudioFilterRead(float[] data, int channels) { - NativeArray nativeArray = new NativeArray(data, Allocator.Temp); try { - track?.SetData(ref nativeArray, channels, m_sampleRate); + track?.SetData(data, channels, m_sampleRate); } // todo(kazuki):: Should catch only ObjectDisposedException but // AudioStreamTrack also throws NullReferenceException. @@ -162,10 +161,6 @@ protected virtual void OnAudioFilterRead(float[] data, int channels) { track = null; } - finally - { - nativeArray.Dispose(); - } } } } diff --git a/com.unity.renderstreaming/Runtime/Scripts/Broadcast.cs b/com.unity.renderstreaming/Runtime/Scripts/Broadcast.cs index 05b2688d7..2249a6795 100644 --- a/com.unity.renderstreaming/Runtime/Scripts/Broadcast.cs +++ b/com.unity.renderstreaming/Runtime/Scripts/Broadcast.cs @@ -48,7 +48,7 @@ private void Disconnect(string connectionId) { RemoveReceiver(connectionId, receiver); } - foreach (var channel in streams.OfType()) + foreach (var channel in streams.OfType().Where(c => c.ConnectionId == connectionId)) { RemoveChannel(connectionId, channel); } @@ -65,7 +65,7 @@ public void OnOffer(SignalingEventData data) { if (connectionIds.Contains(data.connectionId)) { - Debug.Log($"Already answered this connectionId : {data.connectionId}"); + RenderStreaming.Logger.Log($"Already answered this connectionId : {data.connectionId}"); return; } connectionIds.Add(data.connectionId); diff --git a/com.unity.renderstreaming/Runtime/Scripts/DataChannelBase.cs b/com.unity.renderstreaming/Runtime/Scripts/DataChannelBase.cs index 6d717777a..29e80d5d0 100644 --- a/com.unity.renderstreaming/Runtime/Scripts/DataChannelBase.cs +++ b/com.unity.renderstreaming/Runtime/Scripts/DataChannelBase.cs @@ -1,56 +1,62 @@ +using System; using Unity.WebRTC; using UnityEngine; namespace Unity.RenderStreaming { /// - /// + /// /// public abstract class DataChannelBase : MonoBehaviour, IDataChannel { /// - /// + /// /// [SerializeField] protected bool local = false; /// - /// + /// /// [SerializeField] protected string label; /// - /// + /// /// public bool IsLocal => local; /// - /// + /// /// public string Label => label; /// - /// + /// /// public bool IsConnected => Channel != null && Channel.ReadyState == RTCDataChannelState.Open; /// - /// + /// + /// + public string ConnectionId { get; protected set; } + + /// + /// /// public RTCDataChannel Channel { get; protected set; } /// - /// + /// /// public OnStartedChannelHandler OnStartedChannel { get; set; } /// - /// + /// /// public OnStoppedChannelHandler OnStoppedChannel { get; set; } /// - /// + /// /// /// /// @@ -59,10 +65,12 @@ public virtual void SetChannel(string connectionId, RTCDataChannel channel) Channel = channel; if (Channel == null) { + ConnectionId = String.Empty; OnStoppedChannel?.Invoke(connectionId); return; } + ConnectionId = connectionId; label = Channel.Label; Channel.OnOpen += () => { OnOpen(connectionId); }; Channel.OnClose += () => { OnClose(connectionId); }; @@ -75,7 +83,7 @@ public virtual void SetChannel(string connectionId, RTCDataChannel channel) } /// - /// + /// /// /// public virtual void Send(byte[] msg) @@ -84,7 +92,7 @@ public virtual void Send(byte[] msg) } /// - /// + /// /// /// public virtual void Send(string msg) @@ -93,7 +101,7 @@ public virtual void Send(string msg) } /// - /// + /// /// /// public virtual void SetChannel(SignalingEventData data) @@ -102,7 +110,7 @@ public virtual void SetChannel(SignalingEventData data) } /// - /// + /// /// /// protected virtual void OnMessage(byte[] bytes) @@ -110,7 +118,7 @@ protected virtual void OnMessage(byte[] bytes) } /// - /// + /// /// /// protected virtual void OnOpen(string connectionId) @@ -118,7 +126,7 @@ protected virtual void OnOpen(string connectionId) OnStartedChannel?.Invoke(connectionId); } /// - /// + /// /// /// protected virtual void OnClose(string connectionId) diff --git a/com.unity.renderstreaming/Runtime/Scripts/InputSystem/InputReceiver.cs b/com.unity.renderstreaming/Runtime/Scripts/InputSystem/InputReceiver.cs index f45df4da8..b5c471474 100644 --- a/com.unity.renderstreaming/Runtime/Scripts/InputSystem/InputReceiver.cs +++ b/com.unity.renderstreaming/Runtime/Scripts/InputSystem/InputReceiver.cs @@ -26,7 +26,7 @@ public class InputReceiver : InputChannelReceiverBase public override event Action onDeviceChange; /// - /// + /// /// public InputActionAsset actions { @@ -63,22 +63,22 @@ public InputActionAsset actions } /// - /// + /// /// public bool inputIsActive => m_InputActive; /// - /// + /// /// public InputUser user => m_InputUser; /// - /// + /// /// public ReadOnlyArray devices => m_InputUser.pairedDevices; /// - /// + /// /// public InputActionMap currentActionMap { @@ -92,7 +92,7 @@ public InputActionMap currentActionMap } /// - /// + /// /// public string defaultActionMap { @@ -101,7 +101,7 @@ public string defaultActionMap } /// - /// + /// /// protected virtual void OnEnable() { @@ -115,7 +115,7 @@ protected virtual void OnEnable() } /// - /// + /// /// protected virtual void OnDisable() { @@ -128,7 +128,7 @@ protected virtual void OnDisable() } /// - /// + /// /// public void ActivateInput() { @@ -143,7 +143,7 @@ public void ActivateInput() } /// - /// + /// /// public void DeactivateInput() { @@ -153,7 +153,7 @@ public void DeactivateInput() } /// - /// + /// /// /// public void SwitchCurrentActionMap(string mapNameOrId) @@ -161,14 +161,14 @@ public void SwitchCurrentActionMap(string mapNameOrId) // Must be enabled. if (!m_Enabled) { - Debug.LogError($"Cannot switch to actions '{mapNameOrId}'; input is not enabled", this); + RenderStreaming.Logger.Log(LogType.Error, (object)$"Cannot switch to actions '{mapNameOrId}'; input is not enabled", this); return; } // Must have actions. if (m_Actions == null) { - Debug.LogError($"Cannot switch to actions '{mapNameOrId}'; no actions set on PlayerInput", this); + RenderStreaming.Logger.Log(LogType.Error, (object)$"Cannot switch to actions '{mapNameOrId}'; no actions set on PlayerInput", this); return; } @@ -176,7 +176,7 @@ public void SwitchCurrentActionMap(string mapNameOrId) var actionMap = m_Actions.FindActionMap(mapNameOrId); if (actionMap == null) { - Debug.LogError($"Cannot find action map '{mapNameOrId}' in actions '{m_Actions}'", this); + RenderStreaming.Logger.Log(LogType.Error, (object)$"Cannot find action map '{mapNameOrId}' in actions '{m_Actions}'", this); return; } @@ -184,7 +184,7 @@ public void SwitchCurrentActionMap(string mapNameOrId) } /// - /// + /// /// /// public void PerformPairingWithDevice(InputDevice device) @@ -193,7 +193,7 @@ public void PerformPairingWithDevice(InputDevice device) } /// - /// + /// /// public void PerformPairingWithAllLocalDevices() { @@ -204,7 +204,7 @@ public void PerformPairingWithAllLocalDevices() } /// - /// + /// /// /// public void UnpairDevices(InputDevice device) @@ -236,7 +236,7 @@ public override void SetChannel(string connectionId, RTCDataChannel channel) } /// - /// + /// /// /// Texture Size. /// Region of the texture in world coordinate system. @@ -246,7 +246,7 @@ public void SetInputRange(Vector2Int size, Rect region) } /// - /// + /// /// /// public void SetEnableInputPositionCorrection(bool enabled) @@ -256,7 +256,7 @@ public void SetEnableInputPositionCorrection(bool enabled) /// - /// + /// /// protected virtual void OnDestroy() { @@ -340,15 +340,15 @@ private void InitializeActions() if (!string.IsNullOrEmpty(actionEvent.actionName)) { // We have an action name. Show in message. - Debug.LogError( - $"Cannot find action '{actionEvent.actionName}' with ID '{actionEvent.actionId}' in '{m_Actions}", + RenderStreaming.Logger.Log(LogType.Error, + (object)$"Cannot find action '{actionEvent.actionName}' with ID '{actionEvent.actionId}' in '{m_Actions}", this); } else { // We have no action name. Best we have is ID. - Debug.LogError( - $"Cannot find action with ID '{actionEvent.actionId}' in '{m_Actions}", + RenderStreaming.Logger.Log(LogType.Error, + (object)$"Cannot find action with ID '{actionEvent.actionId}' in '{m_Actions}", this); } } diff --git a/com.unity.renderstreaming/Runtime/Scripts/InputSystem/InputRemoting.cs b/com.unity.renderstreaming/Runtime/Scripts/InputSystem/InputRemoting.cs index 74cd441a7..dceea3a6a 100644 --- a/com.unity.renderstreaming/Runtime/Scripts/InputSystem/InputRemoting.cs +++ b/com.unity.renderstreaming/Runtime/Scripts/InputSystem/InputRemoting.cs @@ -97,7 +97,7 @@ private set static InputRemoting() { #if UNITY_EDITOR - // + // // note: This lines are for avoiding issues when running the editor // on background. When moved the focus from the editor, input events // from another process are ignored. @@ -232,7 +232,7 @@ private void SendAllGeneratedLayouts() { // todo(kazuki):: // layputBuilders property is not published from InputSystem - // + // //foreach (var entry in m_LocalManager.m_Layouts.layoutBuilders) // SendLayout(entry.Key); @@ -514,7 +514,7 @@ public struct Data layout = sender.m_LocalManager.LoadLayout(new InternedString(layoutName)); if (layout == null) { - Debug.Log(string.Format( + RenderStreaming.Logger.Log(string.Format( "Could not find layout '{0}' meant to be sent through remote connection; this should not happen", layoutName)); return null; @@ -522,7 +522,7 @@ public struct Data } catch (Exception exception) { - Debug.Log(string.Format( + RenderStreaming.Logger.Log(string.Format( "Could not load layout '{0}'; not sending to remote listeners (exception: {1})", layoutName, exception)); return null; @@ -621,7 +621,7 @@ public static void Process(InputRemoting Receiver, Message msg) foreach (var entry in devices) if (entry.remoteId == data.deviceId) { - Debug.LogError(string.Format( + RenderStreaming.Logger.Log(LogType.Error, string.Format( "Already received device with id {0} (layout '{1}', description '{3}) from remote {2}", data.deviceId, data.layout, msg.participantId, data.description)); @@ -642,7 +642,7 @@ public static void Process(InputRemoting Receiver, Message msg) } catch (Exception exception) { - Debug.LogError( + RenderStreaming.Logger.Log(LogType.Error, $"Could not create remote device '{data.description}' with layout '{data.layout}' locally (exception: {exception})"); return; } diff --git a/com.unity.renderstreaming/Runtime/Scripts/MicrophoneStreamSender.cs b/com.unity.renderstreaming/Runtime/Scripts/MicrophoneStreamSender.cs index 95e596c04..180476982 100644 --- a/com.unity.renderstreaming/Runtime/Scripts/MicrophoneStreamSender.cs +++ b/com.unity.renderstreaming/Runtime/Scripts/MicrophoneStreamSender.cs @@ -30,7 +30,7 @@ protected override void OnEnable() if (Microphone.devices.Length == 0) { - Debug.LogFormat("Microphone device not found"); + RenderStreaming.Logger.Log("Microphone device not found"); return; } diff --git a/com.unity.renderstreaming/Runtime/Scripts/PeerConnection.cs b/com.unity.renderstreaming/Runtime/Scripts/PeerConnection.cs index fbe622ebb..d88d9f7ed 100644 --- a/com.unity.renderstreaming/Runtime/Scripts/PeerConnection.cs +++ b/com.unity.renderstreaming/Runtime/Scripts/PeerConnection.cs @@ -86,7 +86,7 @@ public PeerConnection(bool polite, RTCConfiguration config, float resendInterval case RTCPeerConnectionState.Connected: OnConnectHandler?.Invoke(); break; - case RTCPeerConnectionState.Disconnected: + case RTCPeerConnectionState.Failed: OnDisconnectHandler?.Invoke(); break; } @@ -165,7 +165,7 @@ public void SendOffer() { if (_processingSetDescription) { - Debug.LogWarning($"{this} already processing other set description"); + RenderStreaming.Logger.Log(LogType.Warning, $"{this} already processing other set description"); return; } @@ -203,7 +203,7 @@ private IEnumerator SendOfferCoroutine() if (opLocalDesc.IsError) { - Debug.LogError($"{this} {opLocalDesc.Error.message}"); + RenderStreaming.Logger.Log(LogType.Error, $"{this} {opLocalDesc.Error.message}"); _processingSetDescription = false; yield break; } @@ -220,7 +220,7 @@ public void SendAnswer() { if (_processingSetDescription) { - Debug.LogWarning($"{this} already processing other set description"); + RenderStreaming.Logger.Log(LogType.Warning, $"{this} already processing other set description"); return; } @@ -239,7 +239,7 @@ private IEnumerator SendAnswerCoroutine() if (opLocalDesc.IsError) { - Debug.LogError($"{this} {opLocalDesc.Error.message}"); + RenderStreaming.Logger.Log(LogType.Error, $"{this} {opLocalDesc.Error.message}"); _processingSetDescription = false; yield break; } @@ -260,7 +260,7 @@ public IEnumerator OnGotDescription(RTCSessionDescription description, Action on if (_ignoreOffer) { - Debug.LogWarning($"{this} glare - ignoreOffer."); + RenderStreaming.Logger.Log(LogType.Warning, $"{this} glare - ignoreOffer."); yield break; } @@ -272,7 +272,7 @@ public IEnumerator OnGotDescription(RTCSessionDescription description, Action on yield return remoteDescOp; if (remoteDescOp.IsError) { - Debug.LogError($"{this} {remoteDescOp.Error.message}"); + RenderStreaming.Logger.Log(LogType.Error, $"{this} {remoteDescOp.Error.message}"); _srdAnswerPending = false; _processingSetDescription = false; yield break; @@ -288,7 +288,7 @@ public bool OnGotIceCandidate(RTCIceCandidate candidate) if (!_peer.AddIceCandidate(candidate)) { if (!_ignoreOffer) - Debug.LogWarning($"{this} this candidate can't accept on state."); + RenderStreaming.Logger.Log(LogType.Warning, $"{this} this candidate can't accept on state."); return false; } diff --git a/com.unity.renderstreaming/Runtime/Scripts/RemoteInput.cs b/com.unity.renderstreaming/Runtime/Scripts/RemoteInput.cs index 3c081e6c2..4db5cc436 100644 --- a/com.unity.renderstreaming/Runtime/Scripts/RemoteInput.cs +++ b/com.unity.renderstreaming/Runtime/Scripts/RemoteInput.cs @@ -222,7 +222,7 @@ public void ProcessInput(byte[] bytes) ChangeEndStateUnusedTouches(touches); } } - + break; case EventType.ButtonClick: var elementId = BitConverter.ToInt16(bytes, 1); @@ -231,7 +231,7 @@ public void ProcessInput(byte[] bytes) case EventType.Gamepad: { GamepadEventType gamepadEventType = (GamepadEventType)bytes[1]; - + switch (gamepadEventType) { case GamepadEventType.ButtonDown: @@ -308,10 +308,10 @@ void ProcessGamepadButtonEvent(GamepadEventType state, GamepadKeyCode buttonInde break; case GamepadKeyCode.Axis1Button: buttonToUpdate = GamepadButton.RightStick; - break; + break; default: - UE.Debug.Log("Unmapped button code: " + buttonIndex); - break; + RenderStreaming.Logger.Log("Unmapped button code: " + buttonIndex); + break; } m_gamepadState = gamepadState.WithButton(buttonToUpdate, GamepadEventType.ButtonDown == state || GamepadEventType.ButtonPressed == state); } diff --git a/com.unity.renderstreaming/Runtime/Scripts/RenderStreaming.cs b/com.unity.renderstreaming/Runtime/Scripts/RenderStreaming.cs index 2584227b7..3e1db6a55 100644 --- a/com.unity.renderstreaming/Runtime/Scripts/RenderStreaming.cs +++ b/com.unity.renderstreaming/Runtime/Scripts/RenderStreaming.cs @@ -20,6 +20,7 @@ public sealed class RenderStreaming : MonoBehaviour [SerializeField, Tooltip("Type of signaling.")] private string signalingType = typeof(HttpSignaling).FullName; + private static ILogger s_logger; [SerializeField, Tooltip("Array to set your own STUN/TURN servers.")] private RTCIceServer[] iceServers = new RTCIceServer[] @@ -42,39 +43,29 @@ public sealed class RenderStreaming : MonoBehaviour private bool m_running; #if UNITY_EDITOR - [InitializeOnLoadMethod] - static void InitializeOnEditor() - { - /// todo(kazuki):: This is workaround. - /// When kicking the Unity Editor with batchmode flag on command line, The Unity Editor crashes - /// caused by not unloading WebRTC native plugin. By this workaround, Some static methods of this - /// package don't work correctly when batchmode. These static methods depend on WebRTC API, - /// therefore the package initialization must be completed just after launching Editor. - /// In the future, we will remove this workaround after improving the initialization of the - /// WebRTC package. - if(!IsYamato) - { - if (Application.isBatchMode) - return; - } - RenderStreamingInternal.DomainUnload(); - RenderStreamingInternal.DomainLoad(); - EditorApplication.quitting += RenderStreamingInternal.DomainUnload; - } - + static bool IsYamato => !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("YAMATO_JOB_ID")); +#endif /// - /// Executed from the auto testing environment or not. + /// Get & set the logger to use when logging debug messages inside the RenderStreaming package. + /// By default will use Debug.unityLogger. /// - static bool IsYamato => !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("YAMATO_JOB_ID")); -#else - [RuntimeInitializeOnLoadMethod] - static void InitializeOnRuntime() + /// Throws if setting a null logger. + public static ILogger Logger { - RenderStreamingInternal.DomainUnload(); - RenderStreamingInternal.DomainLoad(); - Application.quitting += RenderStreamingInternal.DomainUnload; + get + { + if (s_logger == null) + { + return Debug.unityLogger; + } + + return s_logger; + } + set + { + s_logger = value ?? throw new ArgumentNullException(nameof(value)); + } } -#endif static Type GetType(string typeName) { diff --git a/com.unity.renderstreaming/Runtime/Scripts/RenderStreamingInternal.cs b/com.unity.renderstreaming/Runtime/Scripts/RenderStreamingInternal.cs index b4fb998e9..531311ffb 100644 --- a/com.unity.renderstreaming/Runtime/Scripts/RenderStreamingInternal.cs +++ b/com.unity.renderstreaming/Runtime/Scripts/RenderStreamingInternal.cs @@ -101,16 +101,6 @@ internal class RenderStreamingInternal : IDisposable, private bool _runningResendCoroutine; private float _resendInterval = 3.0f; - internal static void DomainLoad() - { - WebRTC.WebRTC.Initialize(); - } - - internal static void DomainUnload() - { - WebRTC.WebRTC.Dispose(); - } - /// /// /// @@ -313,12 +303,27 @@ public void SendAnswer(string connectionId) IEnumerator ResendOfferCoroutine() { + HashSet failedConnections = new HashSet(); while (_runningResendCoroutine) { - foreach (var peer in _mapConnectionIdAndPeer.Where(x => x.Value.waitingAnswer)) + failedConnections.Clear(); + foreach (var peer in _mapConnectionIdAndPeer) { - peer.Value.SendOffer(); + if (peer.Value.peer.ConnectionState == RTCPeerConnectionState.Failed) + { + failedConnections.Add(peer.Key); + } + else if(peer.Value.waitingAnswer) + { + peer.Value.SendOffer(); + } } + + foreach (var connectionId in failedConnections) + { + DestroyConnection(connectionId); + } + yield return 0; } } @@ -340,6 +345,11 @@ void OnCreateConnection(ISignaling signaling, string connectionId, bool polite) } void OnDestroyConnection(ISignaling signaling, string connectionId) + { + DestroyConnection(connectionId); + } + + void DestroyConnection(string connectionId) { DeletePeerConnection(connectionId); onDeletedConnection?.Invoke(connectionId); @@ -356,7 +366,11 @@ PeerConnection CreatePeerConnection(string connectionId, bool polite) _mapConnectionIdAndPeer[connectionId] = peer; peer.OnConnectHandler += () => onConnect?.Invoke(connectionId); - peer.OnDisconnectHandler += () => onDisconnect?.Invoke(connectionId); + peer.OnDisconnectHandler += () => + { + _signaling?.CloseConnection(connectionId); + onDisconnect?.Invoke(connectionId); + }; peer.OnDataChannelHandler += channel => onAddChannel?.Invoke(connectionId, channel);; peer.OnTrackEventHandler += e => onAddTransceiver?.Invoke(connectionId, e.Transceiver); peer.SendOfferHandler += desc => _signaling?.SendOffer(connectionId, desc); @@ -380,7 +394,7 @@ void OnAnswer(ISignaling signaling, DescData e) { if (!_mapConnectionIdAndPeer.TryGetValue(e.connectionId, out var pc)) { - Debug.LogWarning($"connectionId:{e.connectionId}, peerConnection not exist"); + RenderStreaming.Logger.Log(LogType.Warning, $"connectionId:{e.connectionId}, peerConnection not exist"); return; } diff --git a/com.unity.renderstreaming/Runtime/Scripts/Signaling/FurioosSignaling.cs b/com.unity.renderstreaming/Runtime/Scripts/Signaling/FurioosSignaling.cs index ddb682d97..6374798e9 100644 --- a/com.unity.renderstreaming/Runtime/Scripts/Signaling/FurioosSignaling.cs +++ b/com.unity.renderstreaming/Runtime/Scripts/Signaling/FurioosSignaling.cs @@ -144,7 +144,7 @@ private void WSManage() Thread.Sleep((int)(m_timeout * 1000)); } - Debug.Log("Signaling: WS managing thread ended"); + RenderStreaming.Logger.Log("Signaling: WS managing thread ended"); } private void WSCreate() @@ -157,14 +157,14 @@ private void WSCreate() Monitor.Enter(m_webSocket); - Debug.Log($"Signaling: Connecting to Furioos Server"); + RenderStreaming.Logger.Log($"Signaling: Connecting to Furioos Server"); m_webSocket.ConnectAsync(); } private void WSProcessMessage(object sender, MessageEventArgs e) { var content = Encoding.UTF8.GetString(e.RawData); - Debug.Log($"Signaling: Receiving message: {content}"); + RenderStreaming.Logger.Log($"Signaling: Receiving message: {content}"); try { @@ -186,25 +186,25 @@ private void WSProcessMessage(object sender, MessageEventArgs e) { if (msg.status == "SUCCESS") { - Debug.Log("Signaling: Slot signed in."); + RenderStreaming.Logger.Log("Signaling: Slot signed in."); this.WSSend("{\"type\":\"furioos\",\"task\":\"enableStreaming\",\"streamType\":\"RenderStreaming\",\"streamProtocols\":[\"WebRTC\"],\"controlsTypes\":[\"RenderStreaming\"]}"); OnSignedIn?.Invoke(this); } else { - Debug.LogError("Signaling: Sign-in error : " + msg.message); + RenderStreaming.Logger.Log(LogType.Error, "Signaling: Sign-in error : " + msg.message); } } else if (msg.type == "reconnect") { if (msg.status == "SUCCESS") { - Debug.Log("Signaling: Slot reconnected."); + RenderStreaming.Logger.Log("Signaling: Slot reconnected."); } else { - Debug.LogError("Signaling: Reconnect error : " + msg.message); + RenderStreaming.Logger.Log(LogType.Error, "Signaling: Reconnect error : " + msg.message); } } @@ -221,7 +221,7 @@ private void WSProcessMessage(object sender, MessageEventArgs e) } else { - Debug.LogError("Signaling: Received message from unknown peer"); + RenderStreaming.Logger.Log(LogType.Error, "Signaling: Received message from unknown peer"); } } } @@ -239,31 +239,31 @@ private void WSProcessMessage(object sender, MessageEventArgs e) } else { - Debug.LogError("Signaling: Received message from unknown peer"); + RenderStreaming.Logger.Log(LogType.Error, "Signaling: Received message from unknown peer"); } } } catch (Exception ex) { - Debug.LogError("Signaling: Failed to parse message: " + ex); + RenderStreaming.Logger.Log(LogType.Error, "Signaling: Failed to parse message: " + ex); } } private void WSConnected(object sender, EventArgs e) { - Debug.Log("Signaling: WS connected."); + RenderStreaming.Logger.Log("Signaling: WS connected."); this.WSSend("{\"type\" :\"signIn\",\"peerName\" :\"Unity Test App\"}"); } private void WSError(object sender, ErrorEventArgs e) { - Debug.LogError($"Signaling: WS connection error: {e.Message}"); + RenderStreaming.Logger.Log(LogType.Error, $"Signaling: WS connection error: {e.Message}"); } private void WSClosed(object sender, CloseEventArgs e) { - Debug.Log($"Signaling: WS connection closed, code: {e.Code}"); + RenderStreaming.Logger.Log($"Signaling: WS connection closed, code: {e.Code}"); m_wsCloseEvent.Set(); m_webSocket = null; @@ -273,19 +273,19 @@ private void WSSend(object data) { if (m_webSocket == null || m_webSocket.ReadyState != WebSocketState.Open) { - Debug.LogError("Signaling: WS is not connected. Unable to send message"); + RenderStreaming.Logger.Log(LogType.Error, "Signaling: WS is not connected. Unable to send message"); return; } if (data is string s) { - Debug.Log("Signaling: Sending WS data: " + s); + RenderStreaming.Logger.Log("Signaling: Sending WS data: " + s); m_webSocket.Send(s); } else { string str = JsonUtility.ToJson(data); - Debug.Log("Signaling: Sending WS data: " + str); + RenderStreaming.Logger.Log("Signaling: Sending WS data: " + str); m_webSocket.Send(str); } } diff --git a/com.unity.renderstreaming/Runtime/Scripts/Signaling/HttpSignaling.cs b/com.unity.renderstreaming/Runtime/Scripts/Signaling/HttpSignaling.cs index bba7b9bcc..0eac57d35 100644 --- a/com.unity.renderstreaming/Runtime/Scripts/Signaling/HttpSignaling.cs +++ b/com.unity.renderstreaming/Runtime/Scripts/Signaling/HttpSignaling.cs @@ -50,6 +50,7 @@ public void Start() throw new InvalidOperationException("This object is already started."); m_running = true; m_signalingThread = new Thread(HTTPPolling); + m_signalingThread.IsBackground = true; m_signalingThread.Start(); } @@ -59,14 +60,20 @@ public void Stop() if (m_signalingThread != null) { - if (m_signalingThread.ThreadState == ThreadState.WaitSleepJoin) + try { - m_signalingThread.Abort(); + // Note: Allow for twice the configured m_timeout duration when joining to account for the polling sleep + // and the time it takes to send a disconnect to the signaling server. + if (!m_signalingThread.Join((int)(m_timeout * 1000) * 2)) + { + m_signalingThread.Abort(); + } } - else + catch (Exception e) { - m_signalingThread.Join(1000); + RenderStreaming.Logger.Log(LogType.Error, "Signaling: HTTP stopping thread error : " + e); } + m_signalingThread = null; } } @@ -155,12 +162,12 @@ private void HTTPPolling() } catch (Exception e) { - Debug.LogError("Signaling: HTTP polling error : " + e); + RenderStreaming.Logger.Log(LogType.Error, "Signaling: HTTP polling error : " + e); } } HTTPDelete(); - Debug.Log("Signaling: HTTP polling thread ended"); + RenderStreaming.Logger.Log("Signaling: HTTP polling thread ended"); } private static HttpWebResponse HTTPGetResponse(HttpWebRequest request) @@ -175,7 +182,7 @@ private static HttpWebResponse HTTPGetResponse(HttpWebRequest request) } else { - Debug.LogError($"Signaling: {response.ResponseUri} HTTP request failed ({response.StatusCode})"); + RenderStreaming.Logger.Log(LogType.Error, $"Signaling: {response.ResponseUri} HTTP request failed ({response.StatusCode})"); response.Close(); } } @@ -185,7 +192,7 @@ private static HttpWebResponse HTTPGetResponse(HttpWebRequest request) } catch (Exception e) { - Debug.LogError($"Signaling: HTTP request error. url:{request.RequestUri} exception:{e}"); + RenderStreaming.Logger.Log(LogType.Error, $"Signaling: HTTP request error. url:{request.RequestUri} exception:{e}"); } return null; @@ -236,14 +243,14 @@ private bool HTTPCreate() request.KeepAlive = false; request.ContentLength = 0; - Debug.Log($"Signaling: Connecting HTTP {m_url}"); + RenderStreaming.Logger.Log($"Signaling: Connecting HTTP {m_url}"); OpenSessionData resp = HTTPParseJsonResponse(HTTPGetResponse(request)); if (resp != null) { m_sessionId = resp.sessionId; - Debug.Log("Signaling: HTTP connected, sessionId : " + m_sessionId); + RenderStreaming.Logger.Log("Signaling: HTTP connected, sessionId : " + m_sessionId); m_mainThreadContext.Post(d => OnStart?.Invoke(this), null); return true; @@ -262,7 +269,7 @@ private bool HTTPDelete() request.KeepAlive = false; request.Headers.Add("Session-Id", m_sessionId); - Debug.Log($"Signaling: Removing HTTP connection from {m_url}"); + RenderStreaming.Logger.Log($"Signaling: Removing HTTP connection from {m_url}"); return (HTTPParseTextResponse(HTTPGetResponse(request)) != null); } @@ -272,7 +279,7 @@ private bool HTTPPost(string path, object data) string str = JsonUtility.ToJson(data); byte[] bytes = new System.Text.UTF8Encoding().GetBytes(str); - Debug.Log("Signaling: Posting HTTP data: " + str); + RenderStreaming.Logger.Log("Signaling: Posting HTTP data: " + str); HttpWebRequest request = (HttpWebRequest)WebRequest.Create($"{m_url}/{path}"); request.Method = "POST"; @@ -310,7 +317,7 @@ private bool HTTPConnect(string connectionId) if (data == null) return false; - Debug.Log($"Signaling: HTTP create connection, connectionId: {connectionId}, polite:{data.polite}"); + RenderStreaming.Logger.Log($"Signaling: HTTP create connection, connectionId: {connectionId}, polite:{data.polite}"); m_mainThreadContext.Post(d => OnCreateConnection?.Invoke(this, data.connectionId, data.polite), null); return true; } @@ -335,7 +342,7 @@ private bool HTTPDisonnect(string connectionId) if (data == null) return false; - Debug.Log("Signaling: HTTP delete connection, connectionId : " + connectionId); + RenderStreaming.Logger.Log("Signaling: HTTP delete connection, connectionId : " + connectionId); m_mainThreadContext.Post(d => OnDestroyConnection?.Invoke(this, connectionId), null); return true; } diff --git a/com.unity.renderstreaming/Runtime/Scripts/Signaling/WebSocketSignaling.cs b/com.unity.renderstreaming/Runtime/Scripts/Signaling/WebSocketSignaling.cs index 1ec7d522b..39ef8ce1f 100644 --- a/com.unity.renderstreaming/Runtime/Scripts/Signaling/WebSocketSignaling.cs +++ b/com.unity.renderstreaming/Runtime/Scripts/Signaling/WebSocketSignaling.cs @@ -150,7 +150,7 @@ private void WSManage() } } - Debug.Log("Signaling: WS managing thread ended"); + RenderStreaming.Logger.Log("Signaling: WS managing thread ended"); } private void WSCreate() @@ -169,14 +169,14 @@ private void WSCreate() Monitor.Enter(m_webSocket); - Debug.Log($"Signaling: Connecting WS {m_url}"); + RenderStreaming.Logger.Log($"Signaling: Connecting WS {m_url}"); m_webSocket.ConnectAsync(); } private void WSProcessMessage(object sender, MessageEventArgs e) { var content = Encoding.UTF8.GetString(e.RawData); - Debug.Log($"Signaling: Receiving message: {content}"); + RenderStreaming.Logger.Log($"Signaling: Receiving message: {content}"); try { @@ -235,31 +235,31 @@ private void WSProcessMessage(object sender, MessageEventArgs e) else if (routedMessage.type == "error") { msg = JsonUtility.FromJson(content); - Debug.LogError(msg.message); + RenderStreaming.Logger.Log(LogType.Error, msg.message); } } } catch (Exception ex) { - Debug.LogError("Signaling: Failed to parse message: " + ex); + RenderStreaming.Logger.Log(LogType.Error, "Signaling: Failed to parse message: " + ex); } } private void WSConnected(object sender, EventArgs e) { - Debug.Log("Signaling: WS connected."); + RenderStreaming.Logger.Log("Signaling: WS connected."); m_mainThreadContext.Post(d => OnStart?.Invoke(this), null); } private void WSError(object sender, ErrorEventArgs e) { - Debug.LogError($"Signaling: WS connection error: {e.Message}"); + RenderStreaming.Logger.Log(LogType.Error, $"Signaling: WS connection error: {e.Message}"); } private void WSClosed(object sender, CloseEventArgs e) { - Debug.Log($"Signaling: WS connection closed, code: {e.Code}"); + RenderStreaming.Logger.Log($"Signaling: WS connection closed, code: {e.Code}"); m_wsCloseEvent.Set(); m_webSocket = null; @@ -269,19 +269,19 @@ private void WSSend(object data) { if (m_webSocket == null || m_webSocket.ReadyState != WebSocketState.Open) { - Debug.LogError("Signaling: WS is not connected. Unable to send message"); + RenderStreaming.Logger.Log(LogType.Error, "Signaling: WS is not connected. Unable to send message"); return; } if (data is string s) { - Debug.Log("Signaling: Sending WS data: " + s); + RenderStreaming.Logger.Log("Signaling: Sending WS data: " + s); m_webSocket.Send(s); } else { string str = JsonUtility.ToJson(data); - Debug.Log("Signaling: Sending WS data: " + str); + RenderStreaming.Logger.Log("Signaling: Sending WS data: " + str); m_webSocket.Send(str); } } diff --git a/com.unity.renderstreaming/Runtime/Scripts/SignalingHandlerBase.cs b/com.unity.renderstreaming/Runtime/Scripts/SignalingHandlerBase.cs index 0d14473db..37bd778e1 100644 --- a/com.unity.renderstreaming/Runtime/Scripts/SignalingHandlerBase.cs +++ b/com.unity.renderstreaming/Runtime/Scripts/SignalingHandlerBase.cs @@ -196,7 +196,7 @@ public virtual void RemoveSender(string connectionId, IStreamSender sender) /// - /// + /// /// /// /// @@ -354,7 +354,7 @@ public interface IStreamReceiver } /// - /// + /// /// public interface IDataChannel { @@ -373,6 +373,11 @@ public interface IDataChannel /// string Label { get; } + /// + /// + /// + string ConnectionId { get; } + /// /// /// diff --git a/com.unity.renderstreaming/Runtime/Scripts/VideoStreamSender.cs b/com.unity.renderstreaming/Runtime/Scripts/VideoStreamSender.cs index affab23d5..e7de0710a 100644 --- a/com.unity.renderstreaming/Runtime/Scripts/VideoStreamSender.cs +++ b/com.unity.renderstreaming/Runtime/Scripts/VideoStreamSender.cs @@ -86,24 +86,24 @@ public static RTCError SetBitrate(this RTCRtpSender sender, uint? minBitrate, ui } /// - /// + /// /// public enum VideoStreamSource { /// - /// + /// /// Camera = 0, /// - /// + /// /// Screen = 1, /// - /// + /// /// WebCamera = 2, /// - /// + /// /// Texture = 3 } @@ -159,7 +159,7 @@ public class VideoStreamSender : StreamSenderBase private VideoStreamSourceImpl m_sourceImpl = null; /// - /// + /// /// public VideoStreamSource source { @@ -178,7 +178,7 @@ public VideoStreamSource source } /// - /// + /// /// public Camera sourceCamera { @@ -222,7 +222,7 @@ public int sourceDeviceIndex } /// - /// + /// /// public WebCamTexture sourceWebCamTexture { @@ -262,7 +262,7 @@ public uint maxBitrate } /// - /// + /// /// public float scaleResolutionDown { @@ -270,7 +270,7 @@ public float scaleResolutionDown } /// - /// + /// /// public uint width { @@ -282,7 +282,7 @@ public uint width } /// - /// + /// /// public uint height { @@ -294,7 +294,7 @@ public uint height } /// - /// + /// /// public VideoCodecInfo codec { @@ -309,7 +309,7 @@ public bool autoRequestUserAuthorization } /// - /// + /// /// /// public void SetCodec(VideoCodecInfo codec) @@ -332,7 +332,7 @@ public void SetCodec(VideoCodecInfo codec) } /// - /// + /// /// /// public static IEnumerable GetAvailableCodecs() @@ -470,7 +470,7 @@ public override VideoStreamTrack CreateTrack() if (m_renderTexture.graphicsFormat != format) { - Debug.LogWarning( + RenderStreaming.Logger.Log(LogType.Warning, $"This color format:{m_renderTexture.graphicsFormat} not support in unity.webrtc. Change to supported color format:{format}."); m_renderTexture.Release(); m_renderTexture.graphicsFormat = format; diff --git a/com.unity.renderstreaming/Runtime/Scripts/WebBrowserInputChannelReceiver.cs b/com.unity.renderstreaming/Runtime/Scripts/WebBrowserInputChannelReceiver.cs index ef3acc9d4..914d45658 100644 --- a/com.unity.renderstreaming/Runtime/Scripts/WebBrowserInputChannelReceiver.cs +++ b/com.unity.renderstreaming/Runtime/Scripts/WebBrowserInputChannelReceiver.cs @@ -57,6 +57,12 @@ public override void SetChannel(string connectionId, RTCDataChannel channel) onDeviceChange?.Invoke(remoteInput.RemoteKeyboard, InputDeviceChange.Removed); onDeviceChange?.Invoke(remoteInput.RemoteMouse, InputDeviceChange.Removed); onDeviceChange?.Invoke(remoteInput.RemoteTouchscreen, InputDeviceChange.Removed); + + if (Channel != null) + { + Channel.OnMessage -= remoteInput.ProcessInput; + } + remoteInput.Dispose(); remoteInput = null; } diff --git a/com.unity.renderstreaming/Tests/Runtime/MockLogger.cs b/com.unity.renderstreaming/Tests/Runtime/MockLogger.cs new file mode 100644 index 000000000..20246aad3 --- /dev/null +++ b/com.unity.renderstreaming/Tests/Runtime/MockLogger.cs @@ -0,0 +1,93 @@ +using System; +using UnityEngine; +using Object = UnityEngine.Object; + +namespace Unity.RenderStreaming.RuntimeTest +{ + public class MockLogger : ILogger + { + public void LogFormat(LogType logType, Object context, string format, params object[] args) + { + throw new NotImplementedException(); + } + + public void LogException(Exception exception, Object context) + { + throw new NotImplementedException(); + } + + public bool IsLogTypeAllowed(LogType logType) + { + throw new NotImplementedException(); + } + + public void Log(LogType logType, object message) + { + throw new NotImplementedException(); + } + + public void Log(LogType logType, object message, Object context) + { + throw new NotImplementedException(); + } + + public void Log(LogType logType, string tag, object message) + { + throw new NotImplementedException(); + } + + public void Log(LogType logType, string tag, object message, Object context) + { + throw new NotImplementedException(); + } + + public void Log(object message) + { + throw new NotImplementedException(); + } + + public void Log(string tag, object message) + { + throw new NotImplementedException(); + } + + public void Log(string tag, object message, Object context) + { + throw new NotImplementedException(); + } + + public void LogWarning(string tag, object message) + { + throw new NotImplementedException(); + } + + public void LogWarning(string tag, object message, Object context) + { + throw new NotImplementedException(); + } + + public void LogError(string tag, object message) + { + throw new NotImplementedException(); + } + + public void LogError(string tag, object message, Object context) + { + throw new NotImplementedException(); + } + + public void LogFormat(LogType logType, string format, params object[] args) + { + throw new NotImplementedException(); + } + + public void LogException(Exception exception) + { + throw new NotImplementedException(); + } + + public ILogHandler logHandler { get; set; } + public bool logEnabled { get; set; } + public LogType filterLogType { get; set; } + } +} diff --git a/com.unity.renderstreaming/Tests/Runtime/MockLogger.cs.meta b/com.unity.renderstreaming/Tests/Runtime/MockLogger.cs.meta new file mode 100644 index 000000000..47fdf4811 --- /dev/null +++ b/com.unity.renderstreaming/Tests/Runtime/MockLogger.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e2595de35a1ada64f923eed1a5e42aa3 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.unity.renderstreaming/Tests/Runtime/RenderStreamingTest.cs b/com.unity.renderstreaming/Tests/Runtime/RenderStreamingTest.cs index 020f3bdff..fc7ce6bc0 100644 --- a/com.unity.renderstreaming/Tests/Runtime/RenderStreamingTest.cs +++ b/com.unity.renderstreaming/Tests/Runtime/RenderStreamingTest.cs @@ -24,6 +24,8 @@ public void SetUp() public void TearDown() { Object.DestroyImmediate(component.gameObject); + + RenderStreaming.Logger = Debug.unityLogger; } [Test] @@ -71,5 +73,20 @@ public IEnumerator RunAgain() yield return 0; component.Run(signaling:mock, handlers:handlers); } + + [Test] + public void Logger() + { + Assert.NotNull(RenderStreaming.Logger); + Assert.AreEqual(RenderStreaming.Logger, Debug.unityLogger); + + Assert.That(() => RenderStreaming.Logger = null, Throws.ArgumentNullException); + + MockLogger logger = new MockLogger(); + Assert.That(() => RenderStreaming.Logger = logger, Throws.Nothing); + Assert.AreEqual(logger, RenderStreaming.Logger); + + Assert.That(() => RenderStreaming.Logger = Debug.unityLogger, Throws.Nothing); + } } } diff --git a/com.unity.renderstreaming/Tests/Runtime/Signaling/MockSignaling.cs b/com.unity.renderstreaming/Tests/Runtime/Signaling/MockSignaling.cs index f9e1dd7e4..31725dde9 100644 --- a/com.unity.renderstreaming/Tests/Runtime/Signaling/MockSignaling.cs +++ b/com.unity.renderstreaming/Tests/Runtime/Signaling/MockSignaling.cs @@ -23,34 +23,56 @@ interface IMockSignalingManager class MockPublicSignalingManager : IMockSignalingManager { - private List list = new List(); + private Dictionary> signalingToConnectionLookup = new Dictionary>(); + private Dictionary> connectionToSignalingLookup = new Dictionary>(); private const int MillisecondsDelay = 10; public async Task Add(MockSignaling signaling) { await Task.Delay(MillisecondsDelay); - list.Add(signaling); + signalingToConnectionLookup[signaling] = new HashSet(); + signaling.OnStart?.Invoke(signaling); } public async Task Remove(MockSignaling signaling) { await Task.Delay(MillisecondsDelay); - list.Remove(signaling); + + if (signalingToConnectionLookup.ContainsKey(signaling)) + { + foreach (var connectionId in signalingToConnectionLookup[signaling]) + { + foreach (var signalingToDisconnect in connectionToSignalingLookup[connectionId]) + { + signalingToDisconnect.OnDestroyConnection?.Invoke(signaling, connectionId); + } + + connectionToSignalingLookup.Remove(connectionId); + } + + signalingToConnectionLookup.Remove(signaling); + } } public async Task OpenConnection(MockSignaling signaling, string connectionId) { await Task.Delay(MillisecondsDelay); + addToLookups(signaling, connectionId); + signaling.OnCreateConnection?.Invoke(signaling, connectionId, true); } public async Task CloseConnection(MockSignaling signaling, string connectionId) { await Task.Delay(MillisecondsDelay); - foreach (var element in list) + + if (connectionToSignalingLookup.ContainsKey(connectionId)) { - element.OnDestroyConnection?.Invoke(element, connectionId); + foreach (var signalingToDisconnect in connectionToSignalingLookup[connectionId]) + { + signalingToDisconnect.OnDestroyConnection?.Invoke(signalingToDisconnect, connectionId); + } } } @@ -58,7 +80,7 @@ public async Task Offer(MockSignaling owner, DescData data) { await Task.Delay(MillisecondsDelay); data.polite = false; - foreach (var signaling in list.Where(e => e != owner)) + foreach (var signaling in signalingToConnectionLookup.Keys.Where(e => e != owner)) { signaling.OnOffer?.Invoke(signaling, data); } @@ -67,8 +89,9 @@ public async Task Offer(MockSignaling owner, DescData data) public async Task Answer(MockSignaling owner, DescData data) { await Task.Delay(MillisecondsDelay); - foreach (var signaling in list.Where(e => e != owner)) + foreach (var signaling in signalingToConnectionLookup.Keys.Where(e => e != owner)) { + addToLookups(owner, data.connectionId); signaling.OnAnswer?.Invoke(signaling, data); } } @@ -76,11 +99,28 @@ public async Task Answer(MockSignaling owner, DescData data) public async Task Candidate(MockSignaling owner, CandidateData data) { await Task.Delay(MillisecondsDelay); - foreach (var signaling in list.Where(e => e != owner)) + foreach (var signaling in signalingToConnectionLookup.Keys.Where(e => e != owner)) { signaling.OnIceCandidate?.Invoke(signaling, data); } } + + private void addToLookups(MockSignaling signaling, string connectionId) + { + if (!connectionToSignalingLookup.TryGetValue(connectionId, out var signalingSet)) + { + signalingSet = new HashSet(); + connectionToSignalingLookup[connectionId] = signalingSet; + } + signalingSet.Add(signaling); + + if (!signalingToConnectionLookup.TryGetValue(signaling, out var connectionSet)) + { + connectionSet = new HashSet(); + signalingToConnectionLookup[signaling] = connectionSet; + } + connectionSet.Add(connectionId); + } } class MockPrivateSignalingManager : IMockSignalingManager diff --git a/com.unity.renderstreaming/Tests/Runtime/SignalingHandlerTest.cs b/com.unity.renderstreaming/Tests/Runtime/SignalingHandlerTest.cs index 880f32904..aadf4ab46 100644 --- a/com.unity.renderstreaming/Tests/Runtime/SignalingHandlerTest.cs +++ b/com.unity.renderstreaming/Tests/Runtime/SignalingHandlerTest.cs @@ -299,6 +299,152 @@ public IEnumerator SetCodec() container1.Dispose(); container2.Dispose(); } + + //todo:: crash in dispose process on standalone linux + [UnityTest, Timeout(10000)] + [UnityPlatform(exclude = new[] { RuntimePlatform.LinuxPlayer, RuntimePlatform.Android })] + public IEnumerator DataChannelDisconnectWithMultipleConnections() + { + // Ignore signaling log errors due to multiple connections + LogAssert.ignoreFailingMessages = true; + + string connectionId = "12345"; + string connectionId2 = "54321"; + var container1 = TestContainer.Create("test1"); + var container2 = TestContainer.Create("test2"); + var container4 = TestContainer.Create("test4"); + + var channel1 = container1.test.gameObject.AddComponent(); + bool isStartedChannel1 = false; + bool isStoppedChannel1 = false; + channel1.OnStartedChannel += _ => isStartedChannel1 = true; + channel1.OnStoppedChannel += _ => isStoppedChannel1 = true; + container1.test.component.AddComponent(channel1); + + container1.test.component.CreateConnection(connectionId); + yield return new WaitUntil(() => container1.test.component.ExistConnection(connectionId)); + + var channel2 = container2.test.gameObject.AddComponent(); + bool isStartedChannel2 = false; + bool isStoppedChannel2 = false; + channel2.OnStartedChannel += _ => isStartedChannel2 = true; + channel2.OnStoppedChannel += _ => isStoppedChannel2 = true; + + channel2.SetLocal(true); + channel2.SetLabel("test"); + + Assert.That(channel2.IsConnected, Is.False); + Assert.That(channel2.IsLocal, Is.True); + Assert.That(channel2.Label, Is.EqualTo("test")); + + container2.test.component.AddComponent(channel2); + container2.test.component.CreateConnection(connectionId); + yield return new WaitUntil(() => container2.test.component.ExistConnection(connectionId)); + yield return new WaitUntil(() => isStartedChannel1 && isStartedChannel2); + Assert.That(isStartedChannel1, Is.True); + Assert.That(isStartedChannel2, Is.True); + + Assert.That(channel1.IsLocal, Is.False); + Assert.That(channel1.Label, Is.EqualTo("test")); + Assert.That(channel1.IsConnected, Is.True); + Assert.That(channel1.Channel, Is.Not.Null); + Assert.That(channel1.ConnectionId, Is.EqualTo(connectionId)); + + Assert.That(channel2.IsConnected, Is.True); + Assert.That(channel2.Channel, Is.Not.Null); + Assert.That(channel2.ConnectionId, Is.EqualTo(connectionId)); + + var channel3 = container1.test.gameObject.AddComponent(); + bool isStartedChannel3 = false; + bool isStoppedChannel3 = false; + channel3.OnStartedChannel += _ => isStartedChannel3 = true; + channel3.OnStoppedChannel += _ => isStoppedChannel3 = true; + container1.test.component.AddComponent(channel3); + + container1.test.component.CreateConnection(connectionId2); + yield return new WaitUntil(() => container1.test.component.ExistConnection(connectionId2)); + + var channel4 = container4.test.gameObject.AddComponent(); + bool isStartedChannel4 = false; + bool isStoppedChannel4 = false; + channel4.OnStartedChannel += _ => isStartedChannel4 = true; + channel4.OnStoppedChannel += _ => isStoppedChannel4 = true; + + channel4.SetLocal(true); + channel4.SetLabel("test2"); + + Assert.That(channel4.IsConnected, Is.False); + Assert.That(channel4.IsLocal, Is.True); + Assert.That(channel4.Label, Is.EqualTo("test2")); + + container4.test.component.AddComponent(channel4); + container4.test.component.CreateConnection(connectionId2); + yield return new WaitUntil(() => container4.test.component.ExistConnection(connectionId2)); + yield return new WaitUntil(() => isStartedChannel3 && isStartedChannel4); + Assert.That(isStartedChannel3, Is.True); + Assert.That(isStartedChannel4, Is.True); + + Assert.That(channel3.IsLocal, Is.False); + Assert.That(channel3.Label, Is.EqualTo("test2")); + Assert.That(channel3.IsConnected, Is.True); + Assert.That(channel3.Channel, Is.Not.Null); + Assert.That(channel3.ConnectionId, Is.EqualTo(connectionId2)); + + Assert.That(channel4.IsConnected, Is.True); + Assert.That(channel4.Channel, Is.Not.Null); + Assert.That(channel4.ConnectionId, Is.EqualTo(connectionId2)); + + // send message from channel1 to channel2 + string sendMessage = "hello"; + string receivedMessage = null; + channel2.OnReceiveMessage = message => { receivedMessage = message; }; + channel1.Send(sendMessage); + yield return new WaitUntil(() => !string.IsNullOrEmpty(receivedMessage)); + Assert.That(receivedMessage, Is.EqualTo(sendMessage)); + + // send message from channel2 to channel1 + receivedMessage = null; + channel1.OnReceiveMessage = message => { receivedMessage = message; }; + channel2.Send(sendMessage); + yield return new WaitUntil(() => !string.IsNullOrEmpty(receivedMessage)); + Assert.That(receivedMessage, Is.EqualTo(sendMessage)); + + // send message from channel3 to channel4 + receivedMessage = null; + channel4.OnReceiveMessage = message => { receivedMessage = message; }; + channel3.Send(sendMessage); + yield return new WaitUntil(() => !string.IsNullOrEmpty(receivedMessage)); + Assert.That(receivedMessage, Is.EqualTo(sendMessage)); + + // send message from channel4 to channel3 + receivedMessage = null; + channel3.OnReceiveMessage = message => { receivedMessage = message; }; + channel4.Send(sendMessage); + yield return new WaitUntil(() => !string.IsNullOrEmpty(receivedMessage)); + Assert.That(receivedMessage, Is.EqualTo(sendMessage)); + + container1.test.component.DeleteConnection(connectionId); + container2.test.component.DeleteConnection(connectionId); + + yield return new WaitUntil(() => isStoppedChannel1 && isStoppedChannel2); + Assert.That(isStoppedChannel1, Is.True); + Assert.That(isStoppedChannel2, Is.True); + Assert.That(isStoppedChannel3, Is.False); + Assert.That(isStoppedChannel4, Is.False); + + container1.test.component.DeleteConnection(connectionId2); + container4.test.component.DeleteConnection(connectionId2); + + yield return new WaitUntil(() => isStoppedChannel3 && isStoppedChannel4); + Assert.That(isStoppedChannel3, Is.True); + Assert.That(isStoppedChannel4, Is.True); + + container1.Dispose(); + container2.Dispose(); + container4.Dispose(); + + LogAssert.ignoreFailingMessages = false; + } } class SingleConnectionTest diff --git a/com.unity.renderstreaming/Tests/Runtime/SignalingTest.cs b/com.unity.renderstreaming/Tests/Runtime/SignalingTest.cs index f2d750ca4..a1b285e02 100644 --- a/com.unity.renderstreaming/Tests/Runtime/SignalingTest.cs +++ b/com.unity.renderstreaming/Tests/Runtime/SignalingTest.cs @@ -332,5 +332,46 @@ public IEnumerator OnCandidate() signaling2.SendCandidate(connectionId1, m_candidate); yield return new WaitUntil(() => candidateRaised2); } + + [UnityTest, Timeout(10000)] + public IEnumerator OnStop() + { + bool startRaised1 = false; + bool startRaised2 = false; + bool offerRaised = false; + bool answerRaised = false; + bool connectionClosed2 = false; + string connectionId1 = null; + string connectionId2 = null; + + signaling1.OnStart += s => { startRaised1 = true; }; + signaling2.OnStart += s => { startRaised2 = true; }; + signaling1.Start(); + signaling2.Start(); + yield return new WaitUntil(() => startRaised1 && startRaised2); + + signaling1.OnCreateConnection += (s, connectionId, polite) => { + connectionId1 = connectionId; + }; + signaling1.OpenConnection(Guid.NewGuid().ToString()); + signaling2.OnCreateConnection += (s, connectionId, polite) => { + connectionId2 = connectionId; + }; + signaling2.OpenConnection(Guid.NewGuid().ToString()); + yield return new WaitUntil(() => + !string.IsNullOrEmpty(connectionId1) && !string.IsNullOrEmpty(connectionId2)); + + signaling2.OnOffer += (s, e) => { offerRaised = true; }; + signaling1.SendOffer(connectionId1, m_DescOffer); + yield return new WaitUntil(() => offerRaised); + + signaling1.OnAnswer += (s, e) => { answerRaised = true; }; + signaling2.SendAnswer(connectionId1, m_DescAnswer); + yield return new WaitUntil(() => answerRaised); + + signaling2.OnDestroyConnection += (s, e) => { connectionClosed2 = true; }; + signaling1.Stop(); + yield return new WaitUntil(() => connectionClosed2); + } } }