RtpServerServiceImpl.java 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  1. package com.ruoyi.wvp.service.impl;
  2. import com.ruoyi.wvp.common.InviteInfo;
  3. import com.ruoyi.wvp.conf.DynamicTask;
  4. import com.ruoyi.wvp.conf.UserSetting;
  5. import com.ruoyi.wvp.gb28181.bean.OpenRTPServerResult;
  6. import com.ruoyi.wvp.gb28181.bean.SsrcTransaction;
  7. import com.ruoyi.wvp.gb28181.session.SSRCFactory;
  8. import com.ruoyi.wvp.gb28181.session.SipInviteSessionManager;
  9. import com.ruoyi.wvp.media.bean.MediaServer;
  10. import com.ruoyi.wvp.media.event.hook.Hook;
  11. import com.ruoyi.wvp.media.event.hook.HookSubscribe;
  12. import com.ruoyi.wvp.media.event.hook.HookType;
  13. import com.ruoyi.wvp.media.event.media.MediaArrivalEvent;
  14. import com.ruoyi.wvp.media.event.media.MediaDepartureEvent;
  15. import com.ruoyi.wvp.media.service.IMediaServerService;
  16. import com.ruoyi.wvp.service.IReceiveRtpServerService;
  17. import com.ruoyi.wvp.service.bean.ErrorCallback;
  18. import com.ruoyi.wvp.service.bean.InviteErrorCode;
  19. import com.ruoyi.wvp.service.bean.RTPServerParam;
  20. import com.ruoyi.wvp.service.bean.SSRCInfo;
  21. import com.zksy.video.lifecycle.VideoStopReceipts;
  22. import com.zksy.video.lifecycle.VideoStopReceipts.Allocation;
  23. import com.zksy.video.lifecycle.VideoStopReceipts.RtpState;
  24. import com.zksy.video.lifecycle.VideoStopReceipts.Snapshot;
  25. import lombok.extern.slf4j.Slf4j;
  26. import org.springframework.beans.factory.annotation.Autowired;
  27. import org.springframework.context.event.EventListener;
  28. import org.springframework.scheduling.annotation.Async;
  29. import org.springframework.stereotype.Service;
  30. import java.util.Objects;
  31. import java.util.UUID;
  32. import java.util.function.Predicate;
  33. @Slf4j
  34. @Service
  35. public class RtpServerServiceImpl implements IReceiveRtpServerService {
  36. @Autowired
  37. private IMediaServerService mediaServerService;
  38. @Autowired
  39. private DynamicTask dynamicTask;
  40. @Autowired
  41. private SSRCFactory ssrcFactory;
  42. @Autowired
  43. private UserSetting userSetting;
  44. @Autowired
  45. private HookSubscribe subscribe;
  46. @Autowired
  47. private SipInviteSessionManager sessionManager;
  48. /**
  49. * 流到来的处理
  50. */
  51. @Async("taskExecutor")
  52. @EventListener
  53. public void onApplicationEvent(MediaArrivalEvent event) {
  54. }
  55. /**
  56. * 流离开的处理
  57. */
  58. @Async("taskExecutor")
  59. @EventListener
  60. public void onApplicationEvent(MediaDepartureEvent event) {
  61. }
  62. @Autowired
  63. private com.zksy.video.lifecycle.VideoLifecycleStore videoLifecycleStore;
  64. @Autowired
  65. private VideoStopReceipts stopReceipts;
  66. // Only callback/timer ownership is local. No field here is stop evidence.
  67. private final java.util.concurrent.ConcurrentMap<String, ManagedRtp> managedRtp = new java.util.concurrent.ConcurrentHashMap<>();
  68. private static final class ManagedRtp {
  69. private final SSRCInfo info;
  70. private HookSubscribe.Subscription owner;
  71. private final java.util.concurrent.atomic.AtomicBoolean terminal = new java.util.concurrent.atomic.AtomicBoolean();
  72. private ManagedRtp(SSRCInfo info) { this.info = info; }
  73. }
  74. private String managedKey(MediaServer node, String stream) {
  75. return Hook.getInstance(HookType.on_media_arrival, "rtp", stream, node.getId()).toString();
  76. }
  77. private boolean reserveAllocation(MediaServer node, SSRCInfo info, boolean externalSsrc) {
  78. if (stopReceipts == null) return false;
  79. return stopReceipts.update(node.getId(), info.getStream(), snapshot -> {
  80. if (!snapshot.canReplaceAllocation()) return null;
  81. if (info.getStream().startsWith("managed_") && snapshot.plays.values().stream().anyMatch(play -> play.cancelled)) return null;
  82. Allocation allocation = new Allocation(); allocation.token = info.getTimeOutTaskKey();
  83. allocation.ssrc = info.getSsrc(); allocation.port = info.getPort(); allocation.state = RtpState.INTENT;
  84. allocation.poolTracked = !externalSsrc; allocation.externalSsrc = externalSsrc;
  85. snapshot.allocation = allocation;
  86. VideoStopReceipts.Play play = snapshot.plays.get(info.getStream());
  87. if (play != null) play.allocationToken = allocation.token;
  88. return snapshot;
  89. }) != null;
  90. }
  91. private boolean allocationState(MediaServer node, SSRCInfo info, RtpState expected, RtpState next) {
  92. return allocationState(node, info, expected, next, snapshot -> true);
  93. }
  94. private boolean allocationState(MediaServer node, SSRCInfo info, RtpState expected, RtpState next,
  95. Predicate<Snapshot> actorGuard) {
  96. if (stopReceipts == null) return false;
  97. for (int attempt = 0; attempt < 4; attempt++) {
  98. Snapshot updated = stopReceipts.update(node.getId(), info.getStream(), snapshot -> {
  99. Allocation allocation = snapshot.allocation;
  100. if (allocation == null || !allocation.matches(info) || allocation.state != expected || !actorGuard.test(snapshot)) return null;
  101. if (next == RtpState.CREATING && info.getStream().startsWith("managed_")
  102. && snapshot.plays.values().stream().anyMatch(play -> play.cancelled)) return null;
  103. allocation.state = next; allocation.port = info.getPort(); return snapshot;
  104. });
  105. if (updated != null) return true;
  106. Snapshot latest = stopReceipts.read(node.getId(), info.getStream());
  107. if (latest == null || latest.allocation == null || !latest.allocation.matches(info)
  108. || latest.allocation.state != expected) return false;
  109. }
  110. return false;
  111. }
  112. private boolean closeAllocation(MediaServer node, SSRCInfo info) {
  113. return closeAllocation(node, info, snapshot -> true);
  114. }
  115. private boolean closeAllocation(MediaServer node, SSRCInfo info, Predicate<Snapshot> actorGuard) {
  116. if (stopReceipts == null || info == null || info.getStream() == null || info.getTimeOutTaskKey() == null
  117. || info.getSsrc() == null || !"rtp".equals(info.getApp())) return false;
  118. Snapshot retained = stopReceipts.read(node.getId(), info.getStream());
  119. if ((retained == null || retained.allocation == null) && !info.getStream().startsWith("managed_")) {
  120. // Pre-upgrade legacy callers retain the original typed allocation. Never replace a newer token,
  121. // reconstruct a managed/adopted receipt, or treat absence as a positive stop acknowledgement.
  122. retained = stopReceipts.update(node.getId(), info.getStream(), snapshot -> {
  123. if (snapshot.allocation != null || !snapshot.plays.isEmpty() || !actorGuard.test(snapshot)
  124. || (sessionManager != null && sessionManager.isAdoptedAllocation(node.getId(), info))) return null;
  125. Allocation allocation = new Allocation(); allocation.token = info.getTimeOutTaskKey();
  126. allocation.ssrc = info.getSsrc(); allocation.port = info.getPort(); allocation.state = RtpState.OPEN;
  127. snapshot.allocation = allocation; return snapshot;
  128. });
  129. }
  130. if (retained == null || retained.allocation == null || !retained.allocation.matches(info) || !actorGuard.test(retained)) return false;
  131. if (retained.allocation.terminal()) return true;
  132. if (retained.allocation.state == RtpState.INTENT) {
  133. // CAS competes with the creator's INTENT -> CREATING, so this is positive never-created evidence.
  134. return allocationState(node, info, RtpState.INTENT, RtpState.NEVER_CREATED, actorGuard);
  135. }
  136. // A process lost during create/close cannot infer completion or send another name-based command.
  137. if (!allocationState(node, info, RtpState.OPEN, RtpState.CLOSING, actorGuard)) return false;
  138. try {
  139. mediaServerService.closeRTPServer(node, info.getStream(), closed -> {
  140. // Boolean true is the ZLM adapter's code=0/hit=1 receipt, not a request-send result.
  141. // Retry only shared state CAS inside allocationState, never the external name-close.
  142. if (!Boolean.TRUE.equals(closed)) return;
  143. if (!allocationState(node, info, RtpState.CLOSING, RtpState.CLOSED)) return;
  144. // A late positive receipt must finish pool cleanup even when the caller already
  145. // returned and no second stop is ever issued.
  146. try { releaseClosedSsrc(node, info); }
  147. catch (RuntimeException ex) { log.warn("[RTP close return] {}/{}: {}", node.getId(), info.getStream(), ex.getMessage()); }
  148. });
  149. } catch (RuntimeException ex) {
  150. log.warn("[RTP close] {}/{} remains pending: {}", node.getId(), info.getStream(), ex.getMessage());
  151. }
  152. Snapshot after = stopReceipts.read(node.getId(), info.getStream());
  153. return after != null && after.allocation != null && after.allocation.matches(info)
  154. && after.allocation.state == RtpState.CLOSED;
  155. }
  156. private boolean cancelled(String stream) {
  157. // Managed resource creation fails closed without the cancellation persistence seam.
  158. return videoLifecycleStore == null || videoLifecycleStore.isStreamCancelled(stream);
  159. }
  160. private SSRCInfo openManagedRtp(RTPServerParam param, ErrorCallback<OpenRTPServerResult> callback) {
  161. MediaServer node = param.getMediaServerItem();
  162. String stream = param.getStreamId();
  163. if (callback == null || node == null || node.getId() == null || !node.isRtpEnable()
  164. || !stream.matches("managed_[0-9a-fA-F]{32}") || cancelled(stream)) {
  165. if (callback != null) callback.run(InviteErrorCode.FAIL.getCode(), "Managed RTP requires a unique stream, multi-port node and live generation", null);
  166. return null;
  167. }
  168. // The stream is a single-use generation identity; use it for the pool request too,
  169. // so cancellation can fence/recover an acquisition whose reply was lost before RTP registration.
  170. ManagedRtp entry = new ManagedRtp(new SSRCInfo(0, null, "rtp", stream, stream));
  171. if (managedRtp.putIfAbsent(managedKey(node, stream), entry) != null) {
  172. callback.run(InviteErrorCode.FAIL.getCode(), "Managed RTP generation already allocated", null);
  173. return null;
  174. }
  175. try {
  176. entry.info.setSsrc(ssrcFactory.getPlaySsrc(node.getId(), entry.info.getTimeOutTaskKey()));
  177. if (!reserveAllocation(node, entry.info, false)) {
  178. Snapshot current = stopReceipts.read(node.getId(), stream);
  179. if (current == null || current.allocation == null || !current.allocation.matches(entry.info))
  180. releaseManagedSsrc(node, entry);
  181. callback.run(InviteErrorCode.FAIL.getCode(), "Managed RTP allocation is already retained", null);
  182. return null;
  183. }
  184. if (cancelled(stream)) {
  185. closeManagedRTPServer(node, entry.info);
  186. return null;
  187. }
  188. if (!allocationState(node, entry.info, RtpState.INTENT, RtpState.CREATING)) {
  189. closeManagedRTPServer(node, entry.info); return null;
  190. }
  191. int port = mediaServerService.createRTPServer(node, stream,
  192. param.isSsrcCheck() ? Long.parseLong(entry.info.getSsrc()) : 0,
  193. 0, false, param.isDisableAudio(), false, param.getTcpMode());
  194. entry.info.setPort(port);
  195. // Only the creator knows create returned. Restart during create remains CREATING.
  196. if (!allocationState(node, entry.info, RtpState.CREATING, RtpState.OPEN)) {
  197. // The port was already created above. A failed receipt transition must not leak it:
  198. // close the exact allocation instead of returning silently.
  199. closeManagedRTPServer(node, entry.info);
  200. callback.run(InviteErrorCode.FAIL.getCode(), "Managed RTP receipt not acknowledged", null);
  201. return null;
  202. }
  203. if (port <= 0 || cancelled(stream) || entry.terminal.get()) {
  204. closeManagedRTPServer(node, entry.info);
  205. callback.run(InviteErrorCode.FAIL.getCode(), "Managed RTP allocation failed or was cancelled", null);
  206. return null;
  207. }
  208. OpenRTPServerResult result = new OpenRTPServerResult(); result.setSsrcInfo(entry.info);
  209. Hook hook = Hook.getInstance(HookType.on_media_arrival, "rtp", stream, node.getId());
  210. entry.owner = subscribe.addOwnedSubscribe(hook, data -> {
  211. if (data.getMediaServer() == null || !node.getId().equals(data.getMediaServer().getId())
  212. || !stream.equals(data.getStream()) || !"rtp".equals(data.getApp())
  213. || data.getMediaInfo() == null || !stream.equals(data.getMediaInfo().getStream())
  214. || !"rtp".equals(data.getMediaInfo().getApp())
  215. || (data.getMediaInfo().getMediaServer() != null
  216. && !node.getId().equals(data.getMediaInfo().getMediaServer().getId()))) return;
  217. if (!entry.terminal.compareAndSet(false, true)) return;
  218. try {
  219. dynamicTask.stop(entry.info.getTimeOutTaskKey());
  220. if (cancelled(stream)) {
  221. closeManagedRTPServer(node, entry.info);
  222. callback.run(InviteErrorCode.FAIL.getCode(), "Managed generation cancelled", result);
  223. return;
  224. }
  225. result.setHookData(data);
  226. callback.run(InviteErrorCode.SUCCESS.getCode(), InviteErrorCode.SUCCESS.getMsg(), result);
  227. } finally {
  228. subscribe.removeOwnedSubscribe(entry.owner);
  229. }
  230. });
  231. if (entry.terminal.get()) subscribe.removeOwnedSubscribe(entry.owner);
  232. dynamicTask.startDelay(entry.info.getTimeOutTaskKey(), () -> {
  233. if (!entry.terminal.compareAndSet(false, true)) return;
  234. try { closeManagedRTPServer(node, entry.info); }
  235. finally { callback.run(InviteErrorCode.ERROR_FOR_STREAM_TIMEOUT.getCode(), "Managed RTP timed out", result); }
  236. }, userSetting.getPlayTimeout());
  237. // Cancellation may have raced creation/registration. Never hand out that resource.
  238. if (cancelled(stream)) {
  239. closeManagedRTPServer(node, entry.info);
  240. callback.run(InviteErrorCode.FAIL.getCode(), "Managed generation cancelled", result);
  241. return null;
  242. }
  243. if (entry.terminal.get()) dynamicTask.stop(entry.info.getTimeOutTaskKey());
  244. return entry.info;
  245. } catch (RuntimeException ex) {
  246. // An ambiguous create/receipt write is not proof that the port never existed.
  247. closeManagedRTPServer(node, entry.info);
  248. callback.run(InviteErrorCode.FAIL.getCode(), "Managed RTP allocation uncertain: " + ex.getMessage(), null);
  249. return null;
  250. }
  251. }
  252. private void releaseManagedSsrc(MediaServer node, ManagedRtp entry) {
  253. if (entry.info.getSsrc() != null) {
  254. ssrcFactory.releaseSsrc(node.getId(), entry.info.getSsrc(), entry.info.getTimeOutTaskKey());
  255. }
  256. }
  257. /** A completed port close is not full cleanup until its pool allocation was returned.
  258. * The Factory receipt is atomic with SADD and remains valid after the SN is reused. */
  259. private boolean releaseClosedSsrc(MediaServer node, SSRCInfo info) {
  260. Snapshot snapshot = stopReceipts.read(node.getId(), info.getStream());
  261. if (snapshot == null || snapshot.allocation == null || !snapshot.allocation.matches(info)
  262. || !snapshot.allocation.terminal()) return false;
  263. Allocation allocation = snapshot.allocation;
  264. if (allocation.externalSsrc || allocation.poolSsrc() == null || allocation.poolReturned) return true;
  265. String poolSsrc = allocation.poolSsrc(), token = allocation.token;
  266. if (ssrcFactory.wasReleased(node.getId(), poolSsrc, token)) return true;
  267. // Return the originally allocated number, never a device-negotiated SSRC.
  268. boolean released = allocation.poolTracked
  269. ? ssrcFactory.releaseSsrc(node.getId(), poolSsrc, token)
  270. : ssrcFactory.releaseObservedLegacySsrc(node.getId(), poolSsrc, token);
  271. return released || ssrcFactory.wasReleased(node.getId(), poolSsrc, token);
  272. }
  273. @Override
  274. public boolean closeManagedRTPServer(MediaServer node, SSRCInfo info) {
  275. if (node == null || node.getId() == null || info == null || info.getStream() == null
  276. || !info.getStream().matches("managed_[0-9a-fA-F]{32}")) return false;
  277. if (stopReceipts != null) {
  278. Snapshot pending = stopReceipts.read(node.getId(), info.getStream());
  279. VideoStopReceipts.Play intent = pending == null ? null : pending.plays.get(info.getStream());
  280. if (pending != null && pending.allocation == null && intent != null && intent.cancelled
  281. && !intent.inviteSent && info.getStream().equals(info.getTimeOutTaskKey()))
  282. return ssrcFactory.cancelAllocation(node.getId(), info.getStream());
  283. }
  284. ManagedRtp entry = managedRtp.get(managedKey(node, info.getStream()));
  285. if (entry != null) {
  286. entry.terminal.set(true);
  287. try {
  288. if (entry.info.getTimeOutTaskKey() != null) dynamicTask.stop(entry.info.getTimeOutTaskKey());
  289. } catch (RuntimeException ex) {
  290. log.warn("[Managed timer close] {}: {}", info.getStream(), ex.getMessage());
  291. } finally { subscribe.removeOwnedSubscribe(entry.owner); }
  292. }
  293. boolean closed = closeAllocation(node, info);
  294. return closed && releaseClosedSsrc(node, info);
  295. }
  296. /** Unlike managed UUIDs, legacy names can be allocated again. Keep the allocation token, not a name receipt. */
  297. private final java.util.Map<String, LegacyRtp> legacyRtp = new java.util.concurrent.ConcurrentHashMap<>();
  298. private static final class LegacyRtp {
  299. private final SSRCInfo info;
  300. private HookSubscribe.Subscription owner;
  301. private final java.util.concurrent.atomic.AtomicBoolean terminal = new java.util.concurrent.atomic.AtomicBoolean();
  302. private LegacyRtp(SSRCInfo info) { this.info = info; }
  303. }
  304. @Override
  305. public synchronized boolean closeAdoptedRTPServer(MediaServer node, SSRCInfo info, String callId) {
  306. if (node == null || node.getId() == null || !node.isRtpEnable() || info == null
  307. || info.getStream() == null || info.getStream().startsWith("managed_") || !"rtp".equals(info.getApp())
  308. || info.getSsrc() == null || info.getTimeOutTaskKey() == null || callId == null
  309. || sessionManager == null || stopReceipts == null || !sessionManager.isAdoptedRtp(node.getId(), callId, info)) return false;
  310. String key = managedKey(node, info.getStream());
  311. LegacyRtp entry = legacyRtp.get(key);
  312. if (entry != null && !entry.info.equals(info)) entry = null; // stale local timer owner is not allocation evidence
  313. com.ruoyi.wvp.gb28181.bean.SsrcTransaction current = sessionManager.getSsrcTransactionByStream("rtp", info.getStream());
  314. if (current != null && (!callId.equals(current.getCallId()) || !info.getSsrc().equals(current.getSsrc())
  315. || !node.getId().equals(current.getMediaServerId()) || !sessionManager.isAdopted(current))) return false;
  316. Snapshot retained = stopReceipts.read(node.getId(), info.getStream());
  317. if (retained == null || retained.allocation == null || !retained.allocation.matches(info)
  318. || !callId.equals(retained.allocation.callId)) return false;
  319. com.ruoyi.wvp.gb28181.bean.SsrcTransaction expected = retained.plays.values().stream()
  320. .filter(play -> java.util.Objects.equals(play.allocationToken, info.getTimeOutTaskKey())
  321. && play.dialog != null && callId.equals(play.dialog.getCallId()))
  322. .map(play -> play.dialog).findFirst().orElse(null);
  323. if (expected == null || !sessionManager.isAdopted(expected)
  324. || (current != null && !SipInviteSessionManager.sameDialog(expected, current))) return false;
  325. if (entry != null) entry.terminal.set(true);
  326. try { dynamicTask.stop(info.getTimeOutTaskKey()); }
  327. catch (RuntimeException ex) { log.warn("[Adopted timer close] {}: {}", info.getStream(), ex.getMessage()); }
  328. finally { if (entry != null) subscribe.removeOwnedSubscribe(entry.owner); }
  329. boolean closed = closeAllocation(node, info, snapshot -> originalActor(snapshot, info, expected));
  330. return closed && releaseClosedSsrc(node, info);
  331. }
  332. @Override
  333. public SSRCInfo openRTPServer(RTPServerParam rtpServerParam, ErrorCallback<OpenRTPServerResult> callback) {
  334. if (rtpServerParam.getStreamId() != null && rtpServerParam.getStreamId().startsWith("managed_")) {
  335. return openManagedRtp(rtpServerParam, callback);
  336. }
  337. return openLegacyRtp(rtpServerParam, callback);
  338. }
  339. private synchronized SSRCInfo openLegacyRtp(RTPServerParam rtpServerParam, ErrorCallback<OpenRTPServerResult> callback) {
  340. if (callback == null) {
  341. log.warn("[开启RTP收流] 失败,回调为NULL");
  342. return null;
  343. }
  344. if (rtpServerParam.getMediaServerItem() == null) {
  345. log.warn("[开启RTP收流] 失败,媒体节点为NULL");
  346. return null;
  347. }
  348. // 获取mediaServer可用的ssrc
  349. final String timeOutTaskKey = UUID.randomUUID().toString();
  350. final String ssrc;
  351. if (rtpServerParam.getPresetSsrc() != null) {
  352. ssrc = rtpServerParam.getPresetSsrc();
  353. }else {
  354. if (rtpServerParam.isPlayback()) {
  355. ssrc = ssrcFactory.getPlayBackSsrc(rtpServerParam.getMediaServerItem().getId(), timeOutTaskKey);
  356. }else {
  357. ssrc = ssrcFactory.getPlaySsrc(rtpServerParam.getMediaServerItem().getId(), timeOutTaskKey);
  358. }
  359. }
  360. final String streamId;
  361. if (rtpServerParam.getStreamId() == null) {
  362. streamId = String.format("%08x", Long.parseLong(ssrc)).toUpperCase();
  363. }else {
  364. streamId = rtpServerParam.getStreamId();
  365. }
  366. if (rtpServerParam.isSsrcCheck() && rtpServerParam.getTcpMode() > 0) {
  367. // 目前zlm不支持 tcp模式更新ssrc,暂时关闭ssrc校验
  368. log.warn("[openRTPServer] 平台对接时下级可能自定义ssrc,但是tcp模式zlm收流目前无法更新ssrc,可能收流超时,此时请使用udp收流或者关闭ssrc校验");
  369. }
  370. // Register BEFORE create: even an in-flight replacement invalidates the previous close receipt.
  371. SSRCInfo ssrcInfo = new SSRCInfo(0, ssrc, "rtp", streamId, timeOutTaskKey);
  372. LegacyRtp entry = new LegacyRtp(ssrcInfo);
  373. String allocationKey = managedKey(rtpServerParam.getMediaServerItem(), streamId);
  374. if (!reserveAllocation(rtpServerParam.getMediaServerItem(), ssrcInfo, rtpServerParam.getPresetSsrc() != null)) {
  375. if (rtpServerParam.getPresetSsrc() == null) ssrcFactory.releaseSsrc(rtpServerParam.getMediaServerItem().getId(), ssrc, timeOutTaskKey);
  376. callback.run(InviteErrorCode.FAIL.getCode(), "Adopted RTP close is still pending", null);
  377. return null;
  378. }
  379. legacyRtp.put(allocationKey, entry);
  380. if (!allocationState(rtpServerParam.getMediaServerItem(), ssrcInfo, RtpState.INTENT, RtpState.CREATING)) {
  381. closeAllocation(rtpServerParam.getMediaServerItem(), ssrcInfo); return null;
  382. }
  383. int rtpServerPort;
  384. if (rtpServerParam.getMediaServerItem().isRtpEnable()) {
  385. rtpServerPort = mediaServerService.createRTPServer(rtpServerParam.getMediaServerItem(), streamId,
  386. rtpServerParam.isSsrcCheck() ? Long.parseLong(ssrc) : 0, rtpServerParam.getPort(), rtpServerParam.isOnlyAuto(),
  387. rtpServerParam.isDisableAudio(), rtpServerParam.isReUsePort(), rtpServerParam.getTcpMode());
  388. } else {
  389. rtpServerPort = rtpServerParam.getMediaServerItem().getRtpProxyPort();
  390. }
  391. ssrcInfo.setPort(rtpServerPort);
  392. if (!allocationState(rtpServerParam.getMediaServerItem(), ssrcInfo, RtpState.CREATING, RtpState.OPEN)) {
  393. // A created port must be closed even when the receipt transition did not commit.
  394. closeAllocation(rtpServerParam.getMediaServerItem(), ssrcInfo);
  395. callback.run(InviteErrorCode.FAIL.getCode(), "RTP receipt not acknowledged", null);
  396. return null;
  397. }
  398. if (rtpServerPort == 0) {
  399. callback.run(InviteErrorCode.ERROR_FOR_RESOURCE_EXHAUSTION.getCode(), "开启RTPServer失败", null);
  400. // 释放ssrc
  401. if (rtpServerParam.getPresetSsrc() == null) {
  402. ssrcFactory.releaseSsrc(rtpServerParam.getMediaServerItem().getId(), ssrc, timeOutTaskKey);
  403. }
  404. return null;
  405. }
  406. OpenRTPServerResult openRTPServerResult = new OpenRTPServerResult();
  407. openRTPServerResult.setSsrcInfo(ssrcInfo);
  408. Hook rtpHook = Hook.getInstance(HookType.on_media_arrival, ssrcInfo.getApp(), streamId, rtpServerParam.getMediaServerItem().getId());
  409. dynamicTask.startDelay(timeOutTaskKey, () -> {
  410. if (legacyRtp.get(allocationKey) != entry || !entry.terminal.compareAndSet(false, true)) return;
  411. // Close through the shared allocation fence; never release an unknown allocation's SSRC early.
  412. closeRTPServer(rtpServerParam.getMediaServerItem(), ssrcInfo);
  413. subscribe.removeOwnedSubscribe(entry.owner);
  414. callback.run(InviteErrorCode.ERROR_FOR_STREAM_TIMEOUT.getCode(), InviteErrorCode.ERROR_FOR_STREAM_TIMEOUT.getMsg(), openRTPServerResult);
  415. }, userSetting.getPlayTimeout());
  416. // 开启流到来的监听
  417. entry.owner = subscribe.addOwnedSubscribe(rtpHook, (hookData) -> {
  418. if (legacyRtp.get(allocationKey) != entry || !entry.terminal.compareAndSet(false, true)) return;
  419. dynamicTask.stop(timeOutTaskKey);
  420. // hook响应
  421. openRTPServerResult.setHookData(hookData);
  422. try {
  423. callback.run(InviteErrorCode.SUCCESS.getCode(), InviteErrorCode.SUCCESS.getMsg(), openRTPServerResult);
  424. } finally {
  425. subscribe.removeOwnedSubscribe(entry.owner);
  426. }
  427. });
  428. if (entry.terminal.get()) subscribe.removeOwnedSubscribe(entry.owner);
  429. return ssrcInfo;
  430. }
  431. /** Peer BYE/offline must use the original Invite and dialog, never the name's current allocation. */
  432. public boolean closeRTPServerForSession(SsrcTransaction original, InviteInfo invite) {
  433. if (original == null || sessionManager == null || stopReceipts == null
  434. || !SipInviteSessionManager.sameDialog(original,
  435. sessionManager.getSsrcTransactionByStream(original.getApp(), original.getStream()))) return false;
  436. SSRCInfo info = invite == null ? sessionManager.getAdoptedAllocation(original) : invite.getSsrcInfo();
  437. if (info == null || !Objects.equals(original.getApp(), info.getApp())
  438. || !Objects.equals(original.getStream(), info.getStream()) || !Objects.equals(original.getSsrc(), info.getSsrc())
  439. || (invite != null && (!Objects.equals(original.getMediaServerId(), invite.getMediaServerId())
  440. || !Objects.equals(original.getDeviceId(), invite.getDeviceId()) || !Objects.equals(original.getChannelId(), invite.getChannelId())
  441. || original.getType() != invite.getType() || !Objects.equals(original.getStream(), invite.getStream())))) return false;
  442. MediaServer node = mediaServerService.getOne(original.getMediaServerId());
  443. if (node == null || !Objects.equals(original.getMediaServerId(), node.getId())) return false;
  444. if (info.getStream().startsWith("managed_")) {
  445. if (!stopReceipts.retainDialog(original)) return false;
  446. return closeManagedRTPServer(node, info);
  447. }
  448. if (sessionManager.isAdopted(original)) return closeAdoptedRTPServer(node, info, original.getCallId());
  449. return closeLegacyRtp(node, info, snapshot -> originalActor(snapshot, info, original));
  450. }
  451. private boolean originalActor(Snapshot snapshot, SSRCInfo info, SsrcTransaction original) {
  452. return (snapshot.allocation == null || snapshot.allocation.callId == null
  453. || Objects.equals(snapshot.allocation.callId, original.getCallId()))
  454. && snapshot.plays.values().stream().noneMatch(play -> Objects.equals(play.allocationToken, info.getTimeOutTaskKey())
  455. && play.dialog != null && !SipInviteSessionManager.sameDialog(original, play.dialog));
  456. }
  457. @Override
  458. public void closeRTPServer(MediaServer mediaServer, SSRCInfo ssrcInfo) {
  459. if (ssrcInfo != null && ssrcInfo.getStream() != null && ssrcInfo.getStream().startsWith("managed_")) {
  460. closeManagedRTPServer(mediaServer, ssrcInfo);
  461. return;
  462. }
  463. closeLegacyRtp(mediaServer, ssrcInfo, snapshot -> true);
  464. }
  465. private boolean closeLegacyRtp(MediaServer mediaServer, SSRCInfo ssrcInfo, Predicate<Snapshot> actorGuard) {
  466. if (mediaServer == null || mediaServer.getId() == null || ssrcInfo == null || ssrcInfo.getStream() == null) return false;
  467. if (ssrcInfo.getTimeOutTaskKey() != null) dynamicTask.stop(ssrcInfo.getTimeOutTaskKey());
  468. LegacyRtp entry = legacyRtp.get(managedKey(mediaServer, ssrcInfo.getStream()));
  469. if (entry != null && entry.info.equals(ssrcInfo)) {
  470. entry.terminal.set(true); subscribe.removeOwnedSubscribe(entry.owner);
  471. }
  472. boolean closed = closeAllocation(mediaServer, ssrcInfo, actorGuard);
  473. return closed && releaseClosedSsrc(mediaServer, ssrcInfo);
  474. }
  475. }