ManagedGbDeepSeamTest.java 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. package com.zksy.video.lifecycle;
  2. import com.alibaba.fastjson2.JSONObject;
  3. import com.ruoyi.wvp.common.*;
  4. import com.ruoyi.wvp.common.InviteInfo;
  5. import com.ruoyi.wvp.conf.*;
  6. import com.ruoyi.wvp.gb28181.SipLayer;
  7. import com.ruoyi.wvp.gb28181.bean.*;
  8. import com.ruoyi.wvp.gb28181.event.SipSubscribe;
  9. import com.ruoyi.wvp.gb28181.service.impl.*;
  10. import com.ruoyi.wvp.gb28181.session.SSRCFactory;
  11. import com.ruoyi.wvp.gb28181.session.SipInviteSessionManager;
  12. import com.ruoyi.wvp.gb28181.transmit.SIPProcessorObserver;
  13. import com.ruoyi.wvp.gb28181.transmit.SIPSender;
  14. import com.ruoyi.wvp.gb28181.transmit.cmd.SIPRequestHeaderProvider;
  15. import com.ruoyi.wvp.gb28181.transmit.cmd.impl.SIPCommander;
  16. import com.ruoyi.wvp.gb28181.transmit.event.response.impl.InviteResponseProcessor;
  17. import com.ruoyi.wvp.mapper.*;
  18. import com.ruoyi.wvp.media.bean.MediaInfo;
  19. import com.ruoyi.wvp.media.bean.MediaServer;
  20. import com.ruoyi.wvp.media.event.hook.HookSubscribe;
  21. import com.ruoyi.wvp.media.event.media.MediaArrivalEvent;
  22. import com.ruoyi.wvp.media.service.impl.MediaServerServiceImpl;
  23. import com.ruoyi.wvp.media.zlm.*;
  24. import com.ruoyi.wvp.service.bean.*;
  25. import com.ruoyi.wvp.service.impl.RtpServerServiceImpl;
  26. import com.ruoyi.wvp.storager.impl.RedisCatchStorageImpl;
  27. import gov.nist.javax.sip.ResponseEventExt;
  28. import gov.nist.javax.sip.message.SIPResponse;
  29. import org.junit.jupiter.api.Test;
  30. import org.springframework.data.redis.core.*;
  31. import org.springframework.test.util.ReflectionTestUtils;
  32. import javax.sip.ResponseEvent;
  33. import javax.sip.SipException;
  34. import javax.sip.SipFactory;
  35. import javax.sip.header.CallIdHeader;
  36. import javax.sip.message.Request;
  37. import java.util.*;
  38. import java.util.concurrent.atomic.AtomicInteger;
  39. import static org.junit.jupiter.api.Assertions.*;
  40. import static org.mockito.ArgumentMatchers.*;
  41. import static org.mockito.Mockito.*;
  42. /** Real Play/RTP/Hook/Invite/Session/Commander/header/media modules; only external I/O and timers are substituted. */
  43. class ManagedGbDeepSeamTest {
  44. private static final String OLD = "managed_11111111111111111111111111111111";
  45. private static final String NEXT = "managed_22222222222222222222222222222222";
  46. @Test void readyWithoutDialogClosesLocalResourcesButRemainsPending() throws Exception {
  47. Fixture f = new Fixture();
  48. assertNotNull(f.start(OLD));
  49. assertFalse(f.play.stopManaged(f.node, f.device, f.channel, OLD));
  50. assertNotNull(f.invites.getInviteInfoByStream(InviteSessionType.PLAY, OLD));
  51. assertTrue(f.hooks.getAll().isEmpty()); assertFalse(f.open.contains(OLD));
  52. assertTrue(f.store.isStreamCancelled(OLD));
  53. assertNull(f.sessions.getSsrcTransactionByStream("rtp", OLD));
  54. assertTrue(f.byes.isEmpty()); assertEquals(Collections.singletonList(OLD), f.closeRequests);
  55. }
  56. @Test void byeFailureFinallyClosesOnlyOldRtpAndRetainsDialogForRetry() throws Exception {
  57. Fixture f = new Fixture(); f.start(OLD); SsrcTransaction dialog = f.dialog(OLD); f.failBye = true;
  58. assertFalse(f.play.stopManaged(f.node, f.device, f.channel, OLD));
  59. assertDialogSnapshot(dialog, f.sessions.getSsrcTransactionByStream("rtp", OLD));
  60. assertFalse(f.sessions.isByeConfirmed(dialog));
  61. assertNotNull(f.invites.getInviteInfoByStream(InviteSessionType.PLAY, OLD));
  62. assertTrue(f.hooks.getAll().isEmpty()); assertFalse(f.open.contains(OLD));
  63. assertEquals(1, f.byeAttempts.get()); assertEquals(Collections.singletonList(OLD), f.closeRequests);
  64. }
  65. @Test void successfulSendWithoutByeResponseIsNotStoppedAndAckAllowsRetryToFinish() throws Exception {
  66. Fixture f = new Fixture(); f.start(OLD); SsrcTransaction dialog = f.dialog(OLD);
  67. assertFalse(f.play.stopManaged(f.node, f.device, f.channel, OLD));
  68. Request bye = f.lastBye(dialog.getCallId()); f.assertBye(bye, dialog);
  69. assertFalse(f.sessions.isByeConfirmed(dialog));
  70. f.byeResponse(bye, 200);
  71. assertTrue(f.sessions.isByeConfirmed(dialog));
  72. assertTrue(f.play.stopManaged(f.node, f.device, f.channel, OLD));
  73. assertNull(f.invites.getInviteInfoByStream(InviteSessionType.PLAY, OLD));
  74. assertNull(f.sessions.getSsrcTransactionByStream("rtp", OLD));
  75. assertNull(f.sessions.getSsrcTransactionByCallId(dialog.getCallId()));
  76. }
  77. @Test void wrongNodeArrivalDoesNotPublishThenCorrectNodeDoes() throws Exception {
  78. Fixture f = new Fixture(); f.start(OLD);
  79. MediaServer wrong = new MediaServer(); wrong.setId("node-b");
  80. f.hooks.onApplicationEvent(f.arrival(OLD, wrong));
  81. assertEquals(0, f.successes.get()); assertEquals(1, f.hooks.getAll().size());
  82. f.hooks.onApplicationEvent(f.arrival(OLD, f.node));
  83. assertEquals(1, f.successes.get()); assertTrue(f.hooks.getAll().isEmpty());
  84. }
  85. @Test void cancelledArrivalAndLateSipCallbacksCannotChangeNewSlot() throws Exception {
  86. Fixture f = new Fixture(); f.start(OLD);
  87. SipSubscribe.Event oldOk = f.inviteOk.get(OLD), oldError = f.inviteError.get(OLD);
  88. assertFalse(f.play.stopManaged(f.node, f.device, f.channel, OLD));
  89. // External reconciliation removes only the old Invite entry, never the cancellation receipt.
  90. f.invites.removeInviteInfo(InviteSessionType.PLAY, f.channel.getId(), OLD);
  91. SSRCInfo next = f.start(NEXT); assertNotNull(next);
  92. f.hooks.onApplicationEvent(f.arrival(OLD, f.node));
  93. SsrcTransaction old = f.dialog(OLD); // actual late INVITE 200 -> ACK -> original-tags BYE
  94. oldOk.response(new SipSubscribe.EventResult<>(f.inviteEvent(OLD, 200)));
  95. oldError.response(new SipSubscribe.EventResult<>(f.inviteEvent(OLD, 500)));
  96. InviteInfo current = f.invites.getInviteInfoByStream(InviteSessionType.PLAY, NEXT);
  97. assertNotNull(current); assertAllocation(next, current.getSsrcInfo());
  98. assertEquals("device", current.getDeviceId()); assertEquals("node-a", current.getMediaServerId());
  99. assertTrue(f.open.contains(NEXT)); assertEquals(1, f.hooks.getAll().size());
  100. assertEquals(NEXT, f.hooks.getAll().get(0).getStream()); assertEquals(0, f.successes.get());
  101. f.assertBye(f.lastBye(old.getCallId()), old);
  102. assertEquals(Collections.singletonList(OLD), f.closeRequests);
  103. }
  104. @Test void cancellationInsideRtpCreationPreventsInviteAndCleansAllocatedPort() throws Exception {
  105. Fixture f = new Fixture(); f.cancelDuringOpen = true;
  106. assertNull(f.start(OLD));
  107. assertFalse(f.open.contains(OLD)); assertTrue(f.inviteOk.isEmpty()); assertTrue(f.hooks.getAll().isEmpty());
  108. assertEquals(Collections.singletonList(OLD), f.closeRequests);
  109. }
  110. @Test void cancelledBeforeStartAndSinglePortNeverCreateResources() throws Exception {
  111. Fixture f = new Fixture(); f.store.markStreamCancelled(OLD);
  112. assertNull(f.start(OLD));
  113. f.node.setRtpEnable(false); assertNull(f.start(NEXT));
  114. assertTrue(f.open.isEmpty()); assertTrue(f.inviteOk.isEmpty()); assertEquals(0, f.openRequests.get());
  115. }
  116. @Test void differentExistingStreamIsNotAdoptedOrStopped() throws Exception {
  117. Fixture f = new Fixture(); SSRCInfo old = f.start(OLD);
  118. assertNull(f.start(NEXT));
  119. assertTrue(f.open.contains(OLD)); assertFalse(f.open.contains(NEXT));
  120. assertAllocation(old, f.invites.getInviteInfoByStream(InviteSessionType.PLAY, OLD).getSsrcInfo());
  121. assertTrue(f.byes.isEmpty()); assertTrue(f.closeRequests.isEmpty());
  122. }
  123. @Test void localCloseFailureCannotBecomeStopSuccessEvenWithBye200() throws Exception {
  124. Fixture f = new Fixture(); f.start(OLD); SsrcTransaction dialog = f.dialog(OLD); f.closeAcknowledged = false;
  125. assertFalse(f.play.stopManaged(f.node, f.device, f.channel, OLD));
  126. f.byeResponse(f.lastBye(dialog.getCallId()), 200);
  127. assertTrue(f.sessions.isByeConfirmed(dialog));
  128. assertFalse(f.play.stopManaged(f.node, f.device, f.channel, OLD));
  129. assertTrue(f.hooks.getAll().isEmpty()); assertTrue(f.open.contains(OLD));
  130. assertEquals(Collections.singletonList(OLD), f.closeRequests);
  131. }
  132. @Test void realCommanderKeepsDialogOnByeTransportFailureAndRemovesOnlyOnAck() throws Exception {
  133. Fixture f = new Fixture(); f.start(OLD); SsrcTransaction tx = f.dialog(OLD); f.failBye = true;
  134. assertFalse(f.play.stopManaged(f.node, f.device, f.channel, OLD));
  135. assertDialogSnapshot(tx, f.sessions.getSsrcTransactionByStream("rtp", OLD));
  136. assertTrue(f.hooks.getAll().isEmpty()); assertFalse(f.open.contains(OLD));
  137. f.failBye = false;
  138. assertFalse(f.play.stopManaged(f.node, f.device, f.channel, OLD));
  139. assertDialogSnapshot(tx, f.sessions.getSsrcTransactionByStream("rtp", OLD));
  140. Request bye = f.lastBye(tx.getCallId()); f.assertBye(bye, tx);
  141. // Exercise Commander's actual callback (not only the observer's restart fallback).
  142. f.byeCallbacks.get(bye).response(new SipSubscribe.EventResult<>(new ResponseEvent(f, null, null, Fixture.reply(bye, 200))));
  143. assertTrue(f.sessions.isByeConfirmed(tx));
  144. assertNull(f.sessions.getSsrcTransactionByStream("rtp", OLD));
  145. assertNull(f.sessions.getSsrcTransactionByCallId(tx.getCallId()));
  146. assertTrue(f.play.stopManaged(f.node, f.device, f.channel, OLD));
  147. assertEquals(2, f.byeAttempts.get()); assertEquals(Collections.singletonList(OLD), f.closeRequests);
  148. }
  149. @Test void lateByeAckCannotDeleteReplacementDialog() throws Exception {
  150. Fixture f = new Fixture(); f.start(OLD); SsrcTransaction old = f.dialog(OLD);
  151. assertFalse(f.play.stopManaged(f.node, f.device, f.channel, OLD));
  152. Request oldBye = f.lastBye(old.getCallId());
  153. SsrcTransaction replacement = f.sessions.getSsrcTransactionByStream("rtp", OLD);
  154. replacement.setCallId("replacement-dialog"); replacement.getSipTransactionInfo().setCallId("replacement-dialog");
  155. replacement.getSipTransactionInfo().setToTag("replacement-to"); f.sessions.put(replacement);
  156. f.byeResponse(oldBye, 200);
  157. assertTrue(f.sessions.isByeConfirmed(old)); assertFalse(f.sessions.isByeConfirmed(replacement));
  158. assertDialogSnapshot(replacement, f.sessions.getSsrcTransactionByStream("rtp", OLD));
  159. assertDialogSnapshot(replacement, f.sessions.getSsrcTransactionByCallId("replacement-dialog"));
  160. assertFalse(f.play.stopManaged(f.node, f.device, f.channel, OLD));
  161. }
  162. @Test void rtpBoundaryAlsoRejectsSharedPortWithoutAllocating() throws Exception {
  163. Fixture f = new Fixture(); f.node.setRtpEnable(false);
  164. RTPServerParam param = new RTPServerParam(); param.setMediaServerItem(f.node); param.setStreamId(OLD);
  165. assertNull(f.rtp.openRTPServer(param, (code, msg, result) -> assertNotEquals(0, code)));
  166. assertTrue(f.open.isEmpty()); assertTrue(f.hooks.getAll().isEmpty()); assertEquals(0, f.openRequests.get());
  167. }
  168. @Test void cancellationDuringMediaReadNeverPublishesReady() throws Exception {
  169. Fixture f = new Fixture(); f.start(OLD);
  170. MediaArrivalEvent event = f.arrival(OLD, f.node);
  171. // An external hook payload schedules cancellation while the real media module reads it.
  172. AtomicInteger reads = new AtomicInteger();
  173. MediaInfo payload = new MediaInfo() {
  174. @Override public String getServerId() { reads.incrementAndGet(); f.store.markStreamCancelled(OLD); return "test"; }
  175. };
  176. payload.setApp("rtp"); payload.setStream(OLD); event.setMediaInfo(payload);
  177. f.hooks.onApplicationEvent(event);
  178. assertTrue(reads.get() > 0); assertTrue(f.store.isStreamCancelled(OLD));
  179. assertEquals(0, f.successes.get()); assertFalse(f.open.contains(OLD)); assertTrue(f.hooks.getAll().isEmpty());
  180. }
  181. @Test void legacyPlayStillReusesItsReadyStreamWithoutManagedAllocation() throws Exception {
  182. Fixture f = new Fixture(); String stream = "device_channel";
  183. SSRCInfo ssrc = new SSRCInfo(30000, "0123450001", "rtp", stream, "legacy-timeout");
  184. StreamInfo live = new StreamInfo(); live.setStream(stream); live.setApp("rtp"); live.setMediaServer(f.node);
  185. InviteInfo existing = InviteInfo.getInviteInfo("device", 7, stream, ssrc, "node-a", "127.0.0.1", 30000,
  186. "UDP", InviteSessionType.PLAY, InviteSessionStatus.ready, false);
  187. existing.setStreamInfo(live); f.invites.updateInviteInfo(existing);
  188. when(f.zlm.getMediaInfo(any(), eq("rtp"), eq("rtsp"), eq(stream))).thenReturn(JSONObject.parseObject("{\"code\":0}"));
  189. AtomicInteger callbacks = new AtomicInteger();
  190. SSRCInfo actual = f.play.play(f.node, "device", "channel", null, (code, msg, info) -> {
  191. assertEquals(0, code); assertNotSame(live, info);
  192. assertEquals("rtp", info.getApp()); assertEquals(stream, info.getStream());
  193. assertEquals("node-a", info.getMediaServer().getId()); callbacks.incrementAndGet();
  194. });
  195. assertAllocation(ssrc, actual);
  196. assertEquals(1, callbacks.get()); assertTrue(f.open.isEmpty()); assertEquals(0, f.openRequests.get());
  197. }
  198. @Test void sameGenerationCanJoinReadyInviteWithoutOpeningAnotherRtp() throws Exception {
  199. Fixture f = new Fixture(); SSRCInfo first = f.start(OLD);
  200. f.hooks.onApplicationEvent(f.arrival(OLD, f.node));
  201. assertAllocation(first, f.start(OLD));
  202. assertEquals(Collections.singleton(OLD), f.open);
  203. assertEquals(1, f.openRequests.get()); assertEquals(2, f.successes.get());
  204. }
  205. @Test void missingInviteAndDialogIsUnknownNotProofOfStop() throws Exception {
  206. Fixture f = new Fixture();
  207. assertFalse(f.play.stopManaged(f.node, f.device, f.channel, OLD));
  208. assertTrue(f.byes.isEmpty()); assertTrue(f.closeRequests.isEmpty());
  209. }
  210. @Test void wrongNodeStopCannotCancelOrCloseOwnedGeneration() throws Exception {
  211. Fixture f = new Fixture(); f.start(OLD);
  212. MediaServer wrong = new MediaServer(); wrong.setId("node-b");
  213. assertFalse(f.play.stopManaged(wrong, f.device, f.channel, OLD));
  214. assertFalse(f.store.isStreamCancelled(OLD)); assertTrue(f.open.contains(OLD));
  215. assertEquals(1, f.hooks.getAll().size()); assertTrue(f.closeRequests.isEmpty());
  216. }
  217. @Test void mismatchedArrivalPayloadCannotConsumeOwnedSubscription() throws Exception {
  218. Fixture f = new Fixture(); f.start(OLD);
  219. MediaArrivalEvent event = f.arrival(OLD, f.node); event.getMediaInfo().setStream(NEXT);
  220. f.hooks.onApplicationEvent(event);
  221. assertEquals(0, f.successes.get()); assertEquals(1, f.hooks.getAll().size());
  222. assertNull(f.invites.getInviteInfoByStream(InviteSessionType.PLAY, NEXT));
  223. f.hooks.onApplicationEvent(f.arrival(OLD, f.node));
  224. assertEquals(1, f.successes.get());
  225. }
  226. static void assertAllocation(SSRCInfo expected, SSRCInfo actual) {
  227. assertNotNull(expected); assertNotNull(actual); assertNotSame(expected, actual);
  228. assertEquals(expected, actual); // Includes port, SSRC, app, stream AND allocation timeout token.
  229. assertNotNull(actual.getTimeOutTaskKey());
  230. }
  231. static void assertDialogSnapshot(SsrcTransaction expected, SsrcTransaction actual) {
  232. assertNotNull(actual); assertNotSame(expected, actual);
  233. assertNotSame(expected.getSipTransactionInfo(), actual.getSipTransactionInfo());
  234. assertEquals(expected.getDeviceId(), actual.getDeviceId()); assertEquals(expected.getChannelId(), actual.getChannelId());
  235. assertEquals(expected.getMediaServerId(), actual.getMediaServerId()); assertEquals(expected.getApp(), actual.getApp());
  236. assertEquals(expected.getStream(), actual.getStream()); assertEquals(expected.getSsrc(), actual.getSsrc());
  237. assertEquals(expected.getType(), actual.getType()); assertEquals(expected.getCallId(), actual.getCallId());
  238. SipTransactionInfo a = expected.getSipTransactionInfo(), b = actual.getSipTransactionInfo();
  239. assertEquals(a.getCallId(), b.getCallId()); assertEquals(a.getFromTag(), b.getFromTag());
  240. assertEquals(a.getToTag(), b.getToTag()); assertEquals(a.getViaBranch(), b.getViaBranch()); assertEquals(a.isAsSender(), b.isAsSender());
  241. }
  242. static class Fixture {
  243. final PlayServiceImpl play = new PlayServiceImpl();
  244. final RtpServerServiceImpl rtp = new RtpServerServiceImpl();
  245. final HookSubscribe hooks = new HookSubscribe();
  246. final InviteStreamServiceImpl invites = new InviteStreamServiceImpl();
  247. final SipInviteSessionManager sessions = new SipInviteSessionManager();
  248. final SIPCommander commander = new SIPCommander();
  249. final SIPProcessorObserver observer = new SIPProcessorObserver();
  250. final InviteResponseProcessor inviteProcessor = new InviteResponseProcessor();
  251. final MediaServerServiceImpl media = new MediaServerServiceImpl();
  252. final DeviceChannelServiceImpl channels = new DeviceChannelServiceImpl();
  253. final DeviceServiceImpl devices = new DeviceServiceImpl();
  254. final DeviceMapper deviceMapper = mock(DeviceMapper.class);
  255. final DeviceChannelMapper channelMapper = mock(DeviceChannelMapper.class);
  256. final MediaServerMapper mediaMapper = mock(MediaServerMapper.class);
  257. final SIPSender sender = mock(SIPSender.class);
  258. final ZLMRESTfulUtils zlm = mock(ZLMRESTfulUtils.class);
  259. final VideoStopReceiptRestartTest.RedisMemory externalRedis = new VideoStopReceiptRestartTest.RedisMemory();
  260. final RedisTemplate<Object, Object> redis = externalRedis.client();
  261. final StringRedisTemplate strings = externalRedis.strings();
  262. final RedisVideoLifecycleStore store = new RedisVideoLifecycleStore(strings);
  263. final VideoStopReceipts receipts = new VideoStopReceipts(redis);
  264. final MediaServer node = new MediaServer();
  265. final Device device = new Device();
  266. final DeviceChannel channel = new DeviceChannel();
  267. final Set<String> open = new HashSet<>();
  268. final Map<String, Request> inviteRequests = new HashMap<>();
  269. final Map<String, SipSubscribe.Event> inviteOk = new HashMap<>(), inviteError = new HashMap<>();
  270. final List<Request> byes = new ArrayList<>(), acks = new ArrayList<>();
  271. final Map<Request, SipSubscribe.Event> byeCallbacks = new IdentityHashMap<>();
  272. final List<String> closeRequests = new ArrayList<>();
  273. final List<Runnable> pendingCloses = new ArrayList<>();
  274. final AtomicInteger successes = new AtomicInteger(), openRequests = new AtomicInteger(), byeAttempts = new AtomicInteger();
  275. boolean cancelDuringOpen, failBye, delayClose, closeAcknowledged = true;
  276. String startingStream;
  277. Fixture() throws Exception {
  278. node.setId("node-a"); node.setType("zlm"); node.setStatus(true); node.setRtpEnable(true);
  279. node.setSdpIp("127.0.0.1"); node.setStreamIp("127.0.0.1");
  280. device.setId(1); device.setDeviceId("device"); device.setStreamMode("UDP");
  281. device.setTransport("UDP"); device.setHostAddress("127.0.0.2:5060");
  282. channel.setId(7); channel.setDeviceId("channel");
  283. UserSetting settings = new UserSetting(); settings.setServerId("test"); settings.setPlayTimeout(30000);
  284. FakeStringRedis ssrcRedis = new FakeStringRedis();
  285. for (int i = 1; i <= 100; i++) ssrcRedis.strings().opsForSet().add(
  286. "CITY_VIDEO_VMP_SSRC_INFO_test_node-a", String.format("20000%04d", i));
  287. SSRCFactory factory = new SSRCFactory(); wire(factory, "redisTemplate", ssrcRedis.strings()); wire(factory, "userSetting", settings);
  288. wire(invites, "redisTemplate", redis); wire(invites, "userSetting", settings);
  289. wire(sessions, "redisTemplate", redis); wire(sessions, "userSetting", settings);
  290. RedisCatchStorageImpl cache = new RedisCatchStorageImpl();
  291. wire(cache, "redisTemplate", redis); wire(cache, "userSetting", settings); cache.updateDevice(device);
  292. redis.opsForHash().put(VideoManagerConstants.MEDIA_SERVER_PREFIX + settings.getServerId(), node.getId(), node);
  293. when(deviceMapper.getDeviceByDeviceId("device")).thenReturn(device);
  294. when(channelMapper.getOneByDeviceIdForSource(1, "channel")).thenReturn(channel);
  295. when(channelMapper.getOneByDeviceId(1, "channel")).thenReturn(channel);
  296. wire(channels, "deviceMapper", deviceMapper); wire(channels, "channelMapper", channelMapper);
  297. wire(devices, "deviceMapper", deviceMapper); wire(devices, "redisCatchStorage", cache);
  298. ZLMServerFactory zlmFactory = new ZLMServerFactory(); wire(zlmFactory, "zlmresTfulUtils", zlm);
  299. ZLMMediaNodeServerService zlmNode = new ZLMMediaNodeServerService();
  300. wire(zlmNode, "zlmServerFactory", zlmFactory); wire(zlmNode, "zlmresTfulUtils", zlm); wire(zlmNode, "userSetting", settings);
  301. wire(media, "nodeServerServiceMap", Map.of("zlm", zlmNode)); wire(media, "redisTemplate", redis);
  302. wire(media, "userSetting", settings); wire(media, "mediaServerMapper", mediaMapper); wire(media, "ssrcFactory", factory);
  303. when(zlm.getRtpInfo(any(), anyString())).thenAnswer(i -> {
  304. JSONObject reply = new JSONObject(); reply.put("code", 0);
  305. reply.put("exist", open.contains((String) i.getArgument(1)));
  306. return reply;
  307. });
  308. when(zlm.openRtpServer(any(), anyMap())).thenAnswer(i -> {
  309. String stream = (String) ((Map<?, ?>) i.getArgument(1)).get("stream_id");
  310. openRequests.incrementAndGet(); open.add(stream); if (cancelDuringOpen) store.markStreamCancelled(stream);
  311. return JSONObject.parseObject("{\"code\":0,\"port\":30000}");
  312. });
  313. doAnswer(i -> {
  314. String stream = (String) ((Map<?, ?>) i.getArgument(1)).get("stream_id"); closeRequests.add(stream);
  315. ZLMRESTfulUtils.RequestCallback callback = i.getArgument(2);
  316. Runnable response = () -> {
  317. boolean hit = closeAcknowledged && open.remove(stream);
  318. callback.run(JSONObject.parseObject(hit ? "{\"code\":0,\"hit\":1}" : "{\"code\":0,\"hit\":0}"));
  319. };
  320. if (delayClose) pendingCloses.add(response); else response.run(); return null;
  321. }).when(zlm).closeRtpServer(any(), anyMap(), any());
  322. when(zlm.getMediaInfo(any(), anyString(), anyString(), anyString())).thenReturn(JSONObject.parseObject("{\"code\":-1}"));
  323. SipConfig config = new SipConfig(); config.setId("34020000002000000001"); config.setDomain("3402000000"); config.setPort(5060);
  324. SipLayer layer = mock(SipLayer.class); when(layer.getLocalIp(any())).thenReturn("127.0.0.1");
  325. SIPRequestHeaderProvider headers = new SIPRequestHeaderProvider();
  326. wire(headers, "sipConfig", config); wire(headers, "sipLayer", layer); wire(headers, "redisCatchStorage", cache);
  327. wire(commander, "headerProvider", headers); wire(commander, "sessionManager", sessions);
  328. wire(commander, "sipSender", sender); wire(commander, "sipLayer", layer); wire(commander, "sipConfig", config);
  329. wire(commander, "userSetting", settings); wire(commander, "videoLifecycleStore", store); wire(commander, "mediaServerService", media);
  330. AtomicInteger calls = new AtomicInteger();
  331. when(sender.getNewCallIdHeader(anyString(), anyString())).thenAnswer(i -> SipFactory.getInstance().createHeaderFactory().createCallIdHeader("call-" + calls.incrementAndGet()));
  332. doAnswer(i -> {
  333. Request request = i.getArgument(1); assertEquals(Request.INVITE, request.getMethod());
  334. inviteRequests.put(startingStream, request); inviteError.put(startingStream, i.getArgument(2));
  335. inviteOk.put(startingStream, i.getArgument(3)); return null;
  336. }).when(sender).transmitRequest(any(), any(), any(), any(), anyLong());
  337. doAnswer(i -> { acks.add(i.getArgument(1)); return null; }).when(sender).transmitRequest(anyString(), any(javax.sip.message.Message.class));
  338. doAnswer(i -> {
  339. Request request = i.getArgument(1); assertEquals(Request.BYE, request.getMethod()); byeAttempts.incrementAndGet();
  340. assertTrue(sessions.hasByeRequest(reply(request, 200)), "The real outgoing BYE must be persisted before transport");
  341. if (failBye) throw new SipException("transport down");
  342. byes.add(request); byeCallbacks.put(request, i.getArgument(3)); return null;
  343. }).when(sender).transmitRequest(any(), any(), any(), any());
  344. wire(observer, "sessionManager", sessions); wire(observer, "sipSubscribe", new SipSubscribe());
  345. wire(inviteProcessor, "sipSender", sender); wire(inviteProcessor, "headerProvider", headers);
  346. wire(inviteProcessor, "sessionManager", sessions); wire(inviteProcessor, "videoLifecycleStore", store);
  347. wire(inviteProcessor, "mediaServerService", media); wire(inviteProcessor, "redisCatchStorage", cache);
  348. wire(inviteProcessor, "deviceChannelService", channels); wire(inviteProcessor, "playService", play);
  349. wire(rtp, "mediaServerService", media); wire(rtp, "dynamicTask", mock(DynamicTask.class)); wire(rtp, "ssrcFactory", factory);
  350. wire(rtp, "userSetting", settings); wire(rtp, "subscribe", hooks); wire(rtp, "videoLifecycleStore", store);
  351. wire(rtp, "sessionManager", sessions); wire(rtp, "stopReceipts", receipts);
  352. wire(play, "cmder", commander); wire(play, "redisCatchStorage", cache); wire(play, "deviceChannelService", channels);
  353. wire(play, "inviteStreamService", invites); wire(play, "sessionManager", sessions); wire(play, "subscribe", hooks);
  354. wire(play, "receiveRtpServerService", rtp); wire(play, "mediaServerService", media);
  355. wire(play, "videoLifecycleStore", store); wire(play, "userSetting", settings); wire(play, "stopReceipts", receipts);
  356. wire(play, "ssrcFactory", factory);
  357. }
  358. SSRCInfo start(String stream) {
  359. startingStream = stream;
  360. return play.playManaged(node, "device", "channel", stream, (code, msg, result) -> { if (code == 0) successes.incrementAndGet(); });
  361. }
  362. SsrcTransaction dialog(String stream) throws Exception {
  363. ResponseEventExt event = inviteEvent(stream, 200);
  364. int before = acks.size(); inviteProcessor.process(event);
  365. assertEquals(before + 1, acks.size()); assertEquals(Request.ACK, acks.get(before).getMethod());
  366. inviteOk.get(stream).response(new SipSubscribe.EventResult<>(event));
  367. SsrcTransaction tx = sessions.getSsrcTransactionByStream("rtp", stream); assertNotNull(tx);
  368. assertEquals(callId(inviteRequests.get(stream)), tx.getCallId());
  369. assertEquals("to-managed", tx.getSipTransactionInfo().getToTag());
  370. assertDialogSnapshot(tx, sessions.getSsrcTransactionByCallId(tx.getCallId())); return tx;
  371. }
  372. ResponseEventExt inviteEvent(String stream, int status) throws Exception {
  373. Request request = inviteRequests.get(stream); assertNotNull(request);
  374. SIPResponse response = reply(request, status);
  375. response.setContent(request.getContent(), SipFactory.getInstance().createHeaderFactory().createContentTypeHeader("application", "sdp"));
  376. // The network metadata is external; the message and all SIP headers are real parsed objects.
  377. ResponseEventExt event = mock(ResponseEventExt.class);
  378. when(event.getResponse()).thenReturn(response); when(event.getRemoteIpAddress()).thenReturn("127.0.0.2");
  379. when(event.getRemotePort()).thenReturn(5060); return event;
  380. }
  381. void byeResponse(Request request, int status) throws Exception { byeResponse(request, reply(request, status)); }
  382. void byeResponse(Request request, SIPResponse response) {
  383. assertEquals(Request.BYE, request.getMethod());
  384. ResponseEvent event = new ResponseEvent(this, null, null, response);
  385. observer.processResponse(event);
  386. // Also exercise the live Commander's callback with the same actual response.
  387. if (byeCallbacks.containsKey(request)) byeCallbacks.get(request).response(new SipSubscribe.EventResult<>(event));
  388. }
  389. Request lastBye(String call) {
  390. return byes.stream().filter(r -> call.equals(callId(r))).reduce((a, b) -> b).orElseThrow();
  391. }
  392. void assertBye(Request request, SsrcTransaction expected) throws Exception {
  393. SIPResponse response = reply(request, 200);
  394. assertEquals(Request.BYE, response.getCSeqHeader().getMethod()); assertTrue(response.getCSeqHeader().getSeqNumber() > 0);
  395. assertEquals(expected.getCallId(), response.getCallIdHeader().getCallId());
  396. assertEquals(expected.getSipTransactionInfo().getFromTag(), response.getFromTag());
  397. assertEquals(expected.getSipTransactionInfo().getToTag(), response.getToTag());
  398. assertEquals(expected.getSipTransactionInfo().getViaBranch(), response.getTopmostViaHeader().getBranch());
  399. assertEquals("channel", ((javax.sip.address.SipURI) request.getRequestURI()).getUser());
  400. assertTrue(sessions.hasByeRequest(response));
  401. }
  402. static String callId(Request request) { return ((CallIdHeader) request.getHeader(CallIdHeader.NAME)).getCallId(); }
  403. static SIPResponse reply(Request request, int status) throws Exception { return VideoStopReceiptRestartTest.reply(request, status); }
  404. MediaArrivalEvent arrival(String stream, MediaServer server) {
  405. MediaArrivalEvent event = new MediaArrivalEvent(this); event.setApp("rtp"); event.setStream(stream); event.setMediaServer(server); event.setSchema("rtsp");
  406. MediaInfo info = new MediaInfo(); info.setApp("rtp"); info.setStream(stream); event.setMediaInfo(info); return event;
  407. }
  408. static void wire(Object bean, String field, Object value) { ReflectionTestUtils.setField(bean, field, value); }
  409. }
  410. }