| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436 |
- package com.zksy.video.lifecycle;
- import com.alibaba.fastjson2.JSONObject;
- import com.ruoyi.wvp.common.*;
- import com.ruoyi.wvp.common.InviteInfo;
- import com.ruoyi.wvp.conf.*;
- import com.ruoyi.wvp.gb28181.SipLayer;
- import com.ruoyi.wvp.gb28181.bean.*;
- import com.ruoyi.wvp.gb28181.event.SipSubscribe;
- import com.ruoyi.wvp.gb28181.service.impl.*;
- import com.ruoyi.wvp.gb28181.session.SSRCFactory;
- import com.ruoyi.wvp.gb28181.session.SipInviteSessionManager;
- import com.ruoyi.wvp.gb28181.transmit.SIPProcessorObserver;
- import com.ruoyi.wvp.gb28181.transmit.SIPSender;
- import com.ruoyi.wvp.gb28181.transmit.cmd.SIPRequestHeaderProvider;
- import com.ruoyi.wvp.gb28181.transmit.cmd.impl.SIPCommander;
- import com.ruoyi.wvp.gb28181.transmit.event.response.impl.InviteResponseProcessor;
- import com.ruoyi.wvp.mapper.*;
- import com.ruoyi.wvp.media.bean.MediaInfo;
- import com.ruoyi.wvp.media.bean.MediaServer;
- import com.ruoyi.wvp.media.event.hook.HookSubscribe;
- import com.ruoyi.wvp.media.event.media.MediaArrivalEvent;
- import com.ruoyi.wvp.media.service.impl.MediaServerServiceImpl;
- import com.ruoyi.wvp.media.zlm.*;
- import com.ruoyi.wvp.service.bean.*;
- import com.ruoyi.wvp.service.impl.RtpServerServiceImpl;
- import com.ruoyi.wvp.storager.impl.RedisCatchStorageImpl;
- import gov.nist.javax.sip.ResponseEventExt;
- import gov.nist.javax.sip.message.SIPResponse;
- import org.junit.jupiter.api.Test;
- import org.springframework.data.redis.core.*;
- import org.springframework.test.util.ReflectionTestUtils;
- import javax.sip.ResponseEvent;
- import javax.sip.SipException;
- import javax.sip.SipFactory;
- import javax.sip.header.CallIdHeader;
- import javax.sip.message.Request;
- import java.util.*;
- import java.util.concurrent.atomic.AtomicInteger;
- import static org.junit.jupiter.api.Assertions.*;
- import static org.mockito.ArgumentMatchers.*;
- import static org.mockito.Mockito.*;
- /** Real Play/RTP/Hook/Invite/Session/Commander/header/media modules; only external I/O and timers are substituted. */
- class ManagedGbDeepSeamTest {
- private static final String OLD = "managed_11111111111111111111111111111111";
- private static final String NEXT = "managed_22222222222222222222222222222222";
- @Test void readyWithoutDialogClosesLocalResourcesButRemainsPending() throws Exception {
- Fixture f = new Fixture();
- assertNotNull(f.start(OLD));
- assertFalse(f.play.stopManaged(f.node, f.device, f.channel, OLD));
- assertNotNull(f.invites.getInviteInfoByStream(InviteSessionType.PLAY, OLD));
- assertTrue(f.hooks.getAll().isEmpty()); assertFalse(f.open.contains(OLD));
- assertTrue(f.store.isStreamCancelled(OLD));
- assertNull(f.sessions.getSsrcTransactionByStream("rtp", OLD));
- assertTrue(f.byes.isEmpty()); assertEquals(Collections.singletonList(OLD), f.closeRequests);
- }
- @Test void byeFailureFinallyClosesOnlyOldRtpAndRetainsDialogForRetry() throws Exception {
- Fixture f = new Fixture(); f.start(OLD); SsrcTransaction dialog = f.dialog(OLD); f.failBye = true;
- assertFalse(f.play.stopManaged(f.node, f.device, f.channel, OLD));
- assertDialogSnapshot(dialog, f.sessions.getSsrcTransactionByStream("rtp", OLD));
- assertFalse(f.sessions.isByeConfirmed(dialog));
- assertNotNull(f.invites.getInviteInfoByStream(InviteSessionType.PLAY, OLD));
- assertTrue(f.hooks.getAll().isEmpty()); assertFalse(f.open.contains(OLD));
- assertEquals(1, f.byeAttempts.get()); assertEquals(Collections.singletonList(OLD), f.closeRequests);
- }
- @Test void successfulSendWithoutByeResponseIsNotStoppedAndAckAllowsRetryToFinish() throws Exception {
- Fixture f = new Fixture(); f.start(OLD); SsrcTransaction dialog = f.dialog(OLD);
- assertFalse(f.play.stopManaged(f.node, f.device, f.channel, OLD));
- Request bye = f.lastBye(dialog.getCallId()); f.assertBye(bye, dialog);
- assertFalse(f.sessions.isByeConfirmed(dialog));
- f.byeResponse(bye, 200);
- assertTrue(f.sessions.isByeConfirmed(dialog));
- assertTrue(f.play.stopManaged(f.node, f.device, f.channel, OLD));
- assertNull(f.invites.getInviteInfoByStream(InviteSessionType.PLAY, OLD));
- assertNull(f.sessions.getSsrcTransactionByStream("rtp", OLD));
- assertNull(f.sessions.getSsrcTransactionByCallId(dialog.getCallId()));
- }
- @Test void wrongNodeArrivalDoesNotPublishThenCorrectNodeDoes() throws Exception {
- Fixture f = new Fixture(); f.start(OLD);
- MediaServer wrong = new MediaServer(); wrong.setId("node-b");
- f.hooks.onApplicationEvent(f.arrival(OLD, wrong));
- assertEquals(0, f.successes.get()); assertEquals(1, f.hooks.getAll().size());
- f.hooks.onApplicationEvent(f.arrival(OLD, f.node));
- assertEquals(1, f.successes.get()); assertTrue(f.hooks.getAll().isEmpty());
- }
- @Test void cancelledArrivalAndLateSipCallbacksCannotChangeNewSlot() throws Exception {
- Fixture f = new Fixture(); f.start(OLD);
- SipSubscribe.Event oldOk = f.inviteOk.get(OLD), oldError = f.inviteError.get(OLD);
- assertFalse(f.play.stopManaged(f.node, f.device, f.channel, OLD));
- // External reconciliation removes only the old Invite entry, never the cancellation receipt.
- f.invites.removeInviteInfo(InviteSessionType.PLAY, f.channel.getId(), OLD);
- SSRCInfo next = f.start(NEXT); assertNotNull(next);
- f.hooks.onApplicationEvent(f.arrival(OLD, f.node));
- SsrcTransaction old = f.dialog(OLD); // actual late INVITE 200 -> ACK -> original-tags BYE
- oldOk.response(new SipSubscribe.EventResult<>(f.inviteEvent(OLD, 200)));
- oldError.response(new SipSubscribe.EventResult<>(f.inviteEvent(OLD, 500)));
- InviteInfo current = f.invites.getInviteInfoByStream(InviteSessionType.PLAY, NEXT);
- assertNotNull(current); assertAllocation(next, current.getSsrcInfo());
- assertEquals("device", current.getDeviceId()); assertEquals("node-a", current.getMediaServerId());
- assertTrue(f.open.contains(NEXT)); assertEquals(1, f.hooks.getAll().size());
- assertEquals(NEXT, f.hooks.getAll().get(0).getStream()); assertEquals(0, f.successes.get());
- f.assertBye(f.lastBye(old.getCallId()), old);
- assertEquals(Collections.singletonList(OLD), f.closeRequests);
- }
- @Test void cancellationInsideRtpCreationPreventsInviteAndCleansAllocatedPort() throws Exception {
- Fixture f = new Fixture(); f.cancelDuringOpen = true;
- assertNull(f.start(OLD));
- assertFalse(f.open.contains(OLD)); assertTrue(f.inviteOk.isEmpty()); assertTrue(f.hooks.getAll().isEmpty());
- assertEquals(Collections.singletonList(OLD), f.closeRequests);
- }
- @Test void cancelledBeforeStartAndSinglePortNeverCreateResources() throws Exception {
- Fixture f = new Fixture(); f.store.markStreamCancelled(OLD);
- assertNull(f.start(OLD));
- f.node.setRtpEnable(false); assertNull(f.start(NEXT));
- assertTrue(f.open.isEmpty()); assertTrue(f.inviteOk.isEmpty()); assertEquals(0, f.openRequests.get());
- }
- @Test void differentExistingStreamIsNotAdoptedOrStopped() throws Exception {
- Fixture f = new Fixture(); SSRCInfo old = f.start(OLD);
- assertNull(f.start(NEXT));
- assertTrue(f.open.contains(OLD)); assertFalse(f.open.contains(NEXT));
- assertAllocation(old, f.invites.getInviteInfoByStream(InviteSessionType.PLAY, OLD).getSsrcInfo());
- assertTrue(f.byes.isEmpty()); assertTrue(f.closeRequests.isEmpty());
- }
- @Test void localCloseFailureCannotBecomeStopSuccessEvenWithBye200() throws Exception {
- Fixture f = new Fixture(); f.start(OLD); SsrcTransaction dialog = f.dialog(OLD); f.closeAcknowledged = false;
- assertFalse(f.play.stopManaged(f.node, f.device, f.channel, OLD));
- f.byeResponse(f.lastBye(dialog.getCallId()), 200);
- assertTrue(f.sessions.isByeConfirmed(dialog));
- assertFalse(f.play.stopManaged(f.node, f.device, f.channel, OLD));
- assertTrue(f.hooks.getAll().isEmpty()); assertTrue(f.open.contains(OLD));
- assertEquals(Collections.singletonList(OLD), f.closeRequests);
- }
- @Test void realCommanderKeepsDialogOnByeTransportFailureAndRemovesOnlyOnAck() throws Exception {
- Fixture f = new Fixture(); f.start(OLD); SsrcTransaction tx = f.dialog(OLD); f.failBye = true;
- assertFalse(f.play.stopManaged(f.node, f.device, f.channel, OLD));
- assertDialogSnapshot(tx, f.sessions.getSsrcTransactionByStream("rtp", OLD));
- assertTrue(f.hooks.getAll().isEmpty()); assertFalse(f.open.contains(OLD));
- f.failBye = false;
- assertFalse(f.play.stopManaged(f.node, f.device, f.channel, OLD));
- assertDialogSnapshot(tx, f.sessions.getSsrcTransactionByStream("rtp", OLD));
- Request bye = f.lastBye(tx.getCallId()); f.assertBye(bye, tx);
- // Exercise Commander's actual callback (not only the observer's restart fallback).
- f.byeCallbacks.get(bye).response(new SipSubscribe.EventResult<>(new ResponseEvent(f, null, null, Fixture.reply(bye, 200))));
- assertTrue(f.sessions.isByeConfirmed(tx));
- assertNull(f.sessions.getSsrcTransactionByStream("rtp", OLD));
- assertNull(f.sessions.getSsrcTransactionByCallId(tx.getCallId()));
- assertTrue(f.play.stopManaged(f.node, f.device, f.channel, OLD));
- assertEquals(2, f.byeAttempts.get()); assertEquals(Collections.singletonList(OLD), f.closeRequests);
- }
- @Test void lateByeAckCannotDeleteReplacementDialog() throws Exception {
- Fixture f = new Fixture(); f.start(OLD); SsrcTransaction old = f.dialog(OLD);
- assertFalse(f.play.stopManaged(f.node, f.device, f.channel, OLD));
- Request oldBye = f.lastBye(old.getCallId());
- SsrcTransaction replacement = f.sessions.getSsrcTransactionByStream("rtp", OLD);
- replacement.setCallId("replacement-dialog"); replacement.getSipTransactionInfo().setCallId("replacement-dialog");
- replacement.getSipTransactionInfo().setToTag("replacement-to"); f.sessions.put(replacement);
- f.byeResponse(oldBye, 200);
- assertTrue(f.sessions.isByeConfirmed(old)); assertFalse(f.sessions.isByeConfirmed(replacement));
- assertDialogSnapshot(replacement, f.sessions.getSsrcTransactionByStream("rtp", OLD));
- assertDialogSnapshot(replacement, f.sessions.getSsrcTransactionByCallId("replacement-dialog"));
- assertFalse(f.play.stopManaged(f.node, f.device, f.channel, OLD));
- }
- @Test void rtpBoundaryAlsoRejectsSharedPortWithoutAllocating() throws Exception {
- Fixture f = new Fixture(); f.node.setRtpEnable(false);
- RTPServerParam param = new RTPServerParam(); param.setMediaServerItem(f.node); param.setStreamId(OLD);
- assertNull(f.rtp.openRTPServer(param, (code, msg, result) -> assertNotEquals(0, code)));
- assertTrue(f.open.isEmpty()); assertTrue(f.hooks.getAll().isEmpty()); assertEquals(0, f.openRequests.get());
- }
- @Test void cancellationDuringMediaReadNeverPublishesReady() throws Exception {
- Fixture f = new Fixture(); f.start(OLD);
- MediaArrivalEvent event = f.arrival(OLD, f.node);
- // An external hook payload schedules cancellation while the real media module reads it.
- AtomicInteger reads = new AtomicInteger();
- MediaInfo payload = new MediaInfo() {
- @Override public String getServerId() { reads.incrementAndGet(); f.store.markStreamCancelled(OLD); return "test"; }
- };
- payload.setApp("rtp"); payload.setStream(OLD); event.setMediaInfo(payload);
- f.hooks.onApplicationEvent(event);
- assertTrue(reads.get() > 0); assertTrue(f.store.isStreamCancelled(OLD));
- assertEquals(0, f.successes.get()); assertFalse(f.open.contains(OLD)); assertTrue(f.hooks.getAll().isEmpty());
- }
- @Test void legacyPlayStillReusesItsReadyStreamWithoutManagedAllocation() throws Exception {
- Fixture f = new Fixture(); String stream = "device_channel";
- SSRCInfo ssrc = new SSRCInfo(30000, "0123450001", "rtp", stream, "legacy-timeout");
- StreamInfo live = new StreamInfo(); live.setStream(stream); live.setApp("rtp"); live.setMediaServer(f.node);
- InviteInfo existing = InviteInfo.getInviteInfo("device", 7, stream, ssrc, "node-a", "127.0.0.1", 30000,
- "UDP", InviteSessionType.PLAY, InviteSessionStatus.ready, false);
- existing.setStreamInfo(live); f.invites.updateInviteInfo(existing);
- when(f.zlm.getMediaInfo(any(), eq("rtp"), eq("rtsp"), eq(stream))).thenReturn(JSONObject.parseObject("{\"code\":0}"));
- AtomicInteger callbacks = new AtomicInteger();
- SSRCInfo actual = f.play.play(f.node, "device", "channel", null, (code, msg, info) -> {
- assertEquals(0, code); assertNotSame(live, info);
- assertEquals("rtp", info.getApp()); assertEquals(stream, info.getStream());
- assertEquals("node-a", info.getMediaServer().getId()); callbacks.incrementAndGet();
- });
- assertAllocation(ssrc, actual);
- assertEquals(1, callbacks.get()); assertTrue(f.open.isEmpty()); assertEquals(0, f.openRequests.get());
- }
- @Test void sameGenerationCanJoinReadyInviteWithoutOpeningAnotherRtp() throws Exception {
- Fixture f = new Fixture(); SSRCInfo first = f.start(OLD);
- f.hooks.onApplicationEvent(f.arrival(OLD, f.node));
- assertAllocation(first, f.start(OLD));
- assertEquals(Collections.singleton(OLD), f.open);
- assertEquals(1, f.openRequests.get()); assertEquals(2, f.successes.get());
- }
- @Test void missingInviteAndDialogIsUnknownNotProofOfStop() throws Exception {
- Fixture f = new Fixture();
- assertFalse(f.play.stopManaged(f.node, f.device, f.channel, OLD));
- assertTrue(f.byes.isEmpty()); assertTrue(f.closeRequests.isEmpty());
- }
- @Test void wrongNodeStopCannotCancelOrCloseOwnedGeneration() throws Exception {
- Fixture f = new Fixture(); f.start(OLD);
- MediaServer wrong = new MediaServer(); wrong.setId("node-b");
- assertFalse(f.play.stopManaged(wrong, f.device, f.channel, OLD));
- assertFalse(f.store.isStreamCancelled(OLD)); assertTrue(f.open.contains(OLD));
- assertEquals(1, f.hooks.getAll().size()); assertTrue(f.closeRequests.isEmpty());
- }
- @Test void mismatchedArrivalPayloadCannotConsumeOwnedSubscription() throws Exception {
- Fixture f = new Fixture(); f.start(OLD);
- MediaArrivalEvent event = f.arrival(OLD, f.node); event.getMediaInfo().setStream(NEXT);
- f.hooks.onApplicationEvent(event);
- assertEquals(0, f.successes.get()); assertEquals(1, f.hooks.getAll().size());
- assertNull(f.invites.getInviteInfoByStream(InviteSessionType.PLAY, NEXT));
- f.hooks.onApplicationEvent(f.arrival(OLD, f.node));
- assertEquals(1, f.successes.get());
- }
- static void assertAllocation(SSRCInfo expected, SSRCInfo actual) {
- assertNotNull(expected); assertNotNull(actual); assertNotSame(expected, actual);
- assertEquals(expected, actual); // Includes port, SSRC, app, stream AND allocation timeout token.
- assertNotNull(actual.getTimeOutTaskKey());
- }
- static void assertDialogSnapshot(SsrcTransaction expected, SsrcTransaction actual) {
- assertNotNull(actual); assertNotSame(expected, actual);
- assertNotSame(expected.getSipTransactionInfo(), actual.getSipTransactionInfo());
- assertEquals(expected.getDeviceId(), actual.getDeviceId()); assertEquals(expected.getChannelId(), actual.getChannelId());
- assertEquals(expected.getMediaServerId(), actual.getMediaServerId()); assertEquals(expected.getApp(), actual.getApp());
- assertEquals(expected.getStream(), actual.getStream()); assertEquals(expected.getSsrc(), actual.getSsrc());
- assertEquals(expected.getType(), actual.getType()); assertEquals(expected.getCallId(), actual.getCallId());
- SipTransactionInfo a = expected.getSipTransactionInfo(), b = actual.getSipTransactionInfo();
- assertEquals(a.getCallId(), b.getCallId()); assertEquals(a.getFromTag(), b.getFromTag());
- assertEquals(a.getToTag(), b.getToTag()); assertEquals(a.getViaBranch(), b.getViaBranch()); assertEquals(a.isAsSender(), b.isAsSender());
- }
- static class Fixture {
- final PlayServiceImpl play = new PlayServiceImpl();
- final RtpServerServiceImpl rtp = new RtpServerServiceImpl();
- final HookSubscribe hooks = new HookSubscribe();
- final InviteStreamServiceImpl invites = new InviteStreamServiceImpl();
- final SipInviteSessionManager sessions = new SipInviteSessionManager();
- final SIPCommander commander = new SIPCommander();
- final SIPProcessorObserver observer = new SIPProcessorObserver();
- final InviteResponseProcessor inviteProcessor = new InviteResponseProcessor();
- final MediaServerServiceImpl media = new MediaServerServiceImpl();
- final DeviceChannelServiceImpl channels = new DeviceChannelServiceImpl();
- final DeviceServiceImpl devices = new DeviceServiceImpl();
- final DeviceMapper deviceMapper = mock(DeviceMapper.class);
- final DeviceChannelMapper channelMapper = mock(DeviceChannelMapper.class);
- final MediaServerMapper mediaMapper = mock(MediaServerMapper.class);
- final SIPSender sender = mock(SIPSender.class);
- final ZLMRESTfulUtils zlm = mock(ZLMRESTfulUtils.class);
- final VideoStopReceiptRestartTest.RedisMemory externalRedis = new VideoStopReceiptRestartTest.RedisMemory();
- final RedisTemplate<Object, Object> redis = externalRedis.client();
- final StringRedisTemplate strings = externalRedis.strings();
- final RedisVideoLifecycleStore store = new RedisVideoLifecycleStore(strings);
- final VideoStopReceipts receipts = new VideoStopReceipts(redis);
- final MediaServer node = new MediaServer();
- final Device device = new Device();
- final DeviceChannel channel = new DeviceChannel();
- final Set<String> open = new HashSet<>();
- final Map<String, Request> inviteRequests = new HashMap<>();
- final Map<String, SipSubscribe.Event> inviteOk = new HashMap<>(), inviteError = new HashMap<>();
- final List<Request> byes = new ArrayList<>(), acks = new ArrayList<>();
- final Map<Request, SipSubscribe.Event> byeCallbacks = new IdentityHashMap<>();
- final List<String> closeRequests = new ArrayList<>();
- final List<Runnable> pendingCloses = new ArrayList<>();
- final AtomicInteger successes = new AtomicInteger(), openRequests = new AtomicInteger(), byeAttempts = new AtomicInteger();
- boolean cancelDuringOpen, failBye, delayClose, closeAcknowledged = true;
- String startingStream;
- Fixture() throws Exception {
- node.setId("node-a"); node.setType("zlm"); node.setStatus(true); node.setRtpEnable(true);
- node.setSdpIp("127.0.0.1"); node.setStreamIp("127.0.0.1");
- device.setId(1); device.setDeviceId("device"); device.setStreamMode("UDP");
- device.setTransport("UDP"); device.setHostAddress("127.0.0.2:5060");
- channel.setId(7); channel.setDeviceId("channel");
- UserSetting settings = new UserSetting(); settings.setServerId("test"); settings.setPlayTimeout(30000);
- FakeStringRedis ssrcRedis = new FakeStringRedis();
- for (int i = 1; i <= 100; i++) ssrcRedis.strings().opsForSet().add(
- "CITY_VIDEO_VMP_SSRC_INFO_test_node-a", String.format("20000%04d", i));
- SSRCFactory factory = new SSRCFactory(); wire(factory, "redisTemplate", ssrcRedis.strings()); wire(factory, "userSetting", settings);
- wire(invites, "redisTemplate", redis); wire(invites, "userSetting", settings);
- wire(sessions, "redisTemplate", redis); wire(sessions, "userSetting", settings);
- RedisCatchStorageImpl cache = new RedisCatchStorageImpl();
- wire(cache, "redisTemplate", redis); wire(cache, "userSetting", settings); cache.updateDevice(device);
- redis.opsForHash().put(VideoManagerConstants.MEDIA_SERVER_PREFIX + settings.getServerId(), node.getId(), node);
- when(deviceMapper.getDeviceByDeviceId("device")).thenReturn(device);
- when(channelMapper.getOneByDeviceIdForSource(1, "channel")).thenReturn(channel);
- when(channelMapper.getOneByDeviceId(1, "channel")).thenReturn(channel);
- wire(channels, "deviceMapper", deviceMapper); wire(channels, "channelMapper", channelMapper);
- wire(devices, "deviceMapper", deviceMapper); wire(devices, "redisCatchStorage", cache);
- ZLMServerFactory zlmFactory = new ZLMServerFactory(); wire(zlmFactory, "zlmresTfulUtils", zlm);
- ZLMMediaNodeServerService zlmNode = new ZLMMediaNodeServerService();
- wire(zlmNode, "zlmServerFactory", zlmFactory); wire(zlmNode, "zlmresTfulUtils", zlm); wire(zlmNode, "userSetting", settings);
- wire(media, "nodeServerServiceMap", Map.of("zlm", zlmNode)); wire(media, "redisTemplate", redis);
- wire(media, "userSetting", settings); wire(media, "mediaServerMapper", mediaMapper); wire(media, "ssrcFactory", factory);
- when(zlm.getRtpInfo(any(), anyString())).thenAnswer(i -> {
- JSONObject reply = new JSONObject(); reply.put("code", 0);
- reply.put("exist", open.contains((String) i.getArgument(1)));
- return reply;
- });
- when(zlm.openRtpServer(any(), anyMap())).thenAnswer(i -> {
- String stream = (String) ((Map<?, ?>) i.getArgument(1)).get("stream_id");
- openRequests.incrementAndGet(); open.add(stream); if (cancelDuringOpen) store.markStreamCancelled(stream);
- return JSONObject.parseObject("{\"code\":0,\"port\":30000}");
- });
- doAnswer(i -> {
- String stream = (String) ((Map<?, ?>) i.getArgument(1)).get("stream_id"); closeRequests.add(stream);
- ZLMRESTfulUtils.RequestCallback callback = i.getArgument(2);
- Runnable response = () -> {
- boolean hit = closeAcknowledged && open.remove(stream);
- callback.run(JSONObject.parseObject(hit ? "{\"code\":0,\"hit\":1}" : "{\"code\":0,\"hit\":0}"));
- };
- if (delayClose) pendingCloses.add(response); else response.run(); return null;
- }).when(zlm).closeRtpServer(any(), anyMap(), any());
- when(zlm.getMediaInfo(any(), anyString(), anyString(), anyString())).thenReturn(JSONObject.parseObject("{\"code\":-1}"));
- SipConfig config = new SipConfig(); config.setId("34020000002000000001"); config.setDomain("3402000000"); config.setPort(5060);
- SipLayer layer = mock(SipLayer.class); when(layer.getLocalIp(any())).thenReturn("127.0.0.1");
- SIPRequestHeaderProvider headers = new SIPRequestHeaderProvider();
- wire(headers, "sipConfig", config); wire(headers, "sipLayer", layer); wire(headers, "redisCatchStorage", cache);
- wire(commander, "headerProvider", headers); wire(commander, "sessionManager", sessions);
- wire(commander, "sipSender", sender); wire(commander, "sipLayer", layer); wire(commander, "sipConfig", config);
- wire(commander, "userSetting", settings); wire(commander, "videoLifecycleStore", store); wire(commander, "mediaServerService", media);
- AtomicInteger calls = new AtomicInteger();
- when(sender.getNewCallIdHeader(anyString(), anyString())).thenAnswer(i -> SipFactory.getInstance().createHeaderFactory().createCallIdHeader("call-" + calls.incrementAndGet()));
- doAnswer(i -> {
- Request request = i.getArgument(1); assertEquals(Request.INVITE, request.getMethod());
- inviteRequests.put(startingStream, request); inviteError.put(startingStream, i.getArgument(2));
- inviteOk.put(startingStream, i.getArgument(3)); return null;
- }).when(sender).transmitRequest(any(), any(), any(), any(), anyLong());
- doAnswer(i -> { acks.add(i.getArgument(1)); return null; }).when(sender).transmitRequest(anyString(), any(javax.sip.message.Message.class));
- doAnswer(i -> {
- Request request = i.getArgument(1); assertEquals(Request.BYE, request.getMethod()); byeAttempts.incrementAndGet();
- assertTrue(sessions.hasByeRequest(reply(request, 200)), "The real outgoing BYE must be persisted before transport");
- if (failBye) throw new SipException("transport down");
- byes.add(request); byeCallbacks.put(request, i.getArgument(3)); return null;
- }).when(sender).transmitRequest(any(), any(), any(), any());
- wire(observer, "sessionManager", sessions); wire(observer, "sipSubscribe", new SipSubscribe());
- wire(inviteProcessor, "sipSender", sender); wire(inviteProcessor, "headerProvider", headers);
- wire(inviteProcessor, "sessionManager", sessions); wire(inviteProcessor, "videoLifecycleStore", store);
- wire(inviteProcessor, "mediaServerService", media); wire(inviteProcessor, "redisCatchStorage", cache);
- wire(inviteProcessor, "deviceChannelService", channels); wire(inviteProcessor, "playService", play);
- wire(rtp, "mediaServerService", media); wire(rtp, "dynamicTask", mock(DynamicTask.class)); wire(rtp, "ssrcFactory", factory);
- wire(rtp, "userSetting", settings); wire(rtp, "subscribe", hooks); wire(rtp, "videoLifecycleStore", store);
- wire(rtp, "sessionManager", sessions); wire(rtp, "stopReceipts", receipts);
- wire(play, "cmder", commander); wire(play, "redisCatchStorage", cache); wire(play, "deviceChannelService", channels);
- wire(play, "inviteStreamService", invites); wire(play, "sessionManager", sessions); wire(play, "subscribe", hooks);
- wire(play, "receiveRtpServerService", rtp); wire(play, "mediaServerService", media);
- wire(play, "videoLifecycleStore", store); wire(play, "userSetting", settings); wire(play, "stopReceipts", receipts);
- wire(play, "ssrcFactory", factory);
- }
- SSRCInfo start(String stream) {
- startingStream = stream;
- return play.playManaged(node, "device", "channel", stream, (code, msg, result) -> { if (code == 0) successes.incrementAndGet(); });
- }
- SsrcTransaction dialog(String stream) throws Exception {
- ResponseEventExt event = inviteEvent(stream, 200);
- int before = acks.size(); inviteProcessor.process(event);
- assertEquals(before + 1, acks.size()); assertEquals(Request.ACK, acks.get(before).getMethod());
- inviteOk.get(stream).response(new SipSubscribe.EventResult<>(event));
- SsrcTransaction tx = sessions.getSsrcTransactionByStream("rtp", stream); assertNotNull(tx);
- assertEquals(callId(inviteRequests.get(stream)), tx.getCallId());
- assertEquals("to-managed", tx.getSipTransactionInfo().getToTag());
- assertDialogSnapshot(tx, sessions.getSsrcTransactionByCallId(tx.getCallId())); return tx;
- }
- ResponseEventExt inviteEvent(String stream, int status) throws Exception {
- Request request = inviteRequests.get(stream); assertNotNull(request);
- SIPResponse response = reply(request, status);
- response.setContent(request.getContent(), SipFactory.getInstance().createHeaderFactory().createContentTypeHeader("application", "sdp"));
- // The network metadata is external; the message and all SIP headers are real parsed objects.
- ResponseEventExt event = mock(ResponseEventExt.class);
- when(event.getResponse()).thenReturn(response); when(event.getRemoteIpAddress()).thenReturn("127.0.0.2");
- when(event.getRemotePort()).thenReturn(5060); return event;
- }
- void byeResponse(Request request, int status) throws Exception { byeResponse(request, reply(request, status)); }
- void byeResponse(Request request, SIPResponse response) {
- assertEquals(Request.BYE, request.getMethod());
- ResponseEvent event = new ResponseEvent(this, null, null, response);
- observer.processResponse(event);
- // Also exercise the live Commander's callback with the same actual response.
- if (byeCallbacks.containsKey(request)) byeCallbacks.get(request).response(new SipSubscribe.EventResult<>(event));
- }
- Request lastBye(String call) {
- return byes.stream().filter(r -> call.equals(callId(r))).reduce((a, b) -> b).orElseThrow();
- }
- void assertBye(Request request, SsrcTransaction expected) throws Exception {
- SIPResponse response = reply(request, 200);
- assertEquals(Request.BYE, response.getCSeqHeader().getMethod()); assertTrue(response.getCSeqHeader().getSeqNumber() > 0);
- assertEquals(expected.getCallId(), response.getCallIdHeader().getCallId());
- assertEquals(expected.getSipTransactionInfo().getFromTag(), response.getFromTag());
- assertEquals(expected.getSipTransactionInfo().getToTag(), response.getToTag());
- assertEquals(expected.getSipTransactionInfo().getViaBranch(), response.getTopmostViaHeader().getBranch());
- assertEquals("channel", ((javax.sip.address.SipURI) request.getRequestURI()).getUser());
- assertTrue(sessions.hasByeRequest(response));
- }
- static String callId(Request request) { return ((CallIdHeader) request.getHeader(CallIdHeader.NAME)).getCallId(); }
- static SIPResponse reply(Request request, int status) throws Exception { return VideoStopReceiptRestartTest.reply(request, status); }
- MediaArrivalEvent arrival(String stream, MediaServer server) {
- MediaArrivalEvent event = new MediaArrivalEvent(this); event.setApp("rtp"); event.setStream(stream); event.setMediaServer(server); event.setSchema("rtsp");
- MediaInfo info = new MediaInfo(); info.setApp("rtp"); info.setStream(stream); event.setMediaInfo(info); return event;
- }
- static void wire(Object bean, String field, Object value) { ReflectionTestUtils.setField(bean, field, value); }
- }
- }
|