| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516 |
- package com.ruoyi.wvp.service.impl;
- import com.ruoyi.wvp.common.InviteInfo;
- import com.ruoyi.wvp.conf.DynamicTask;
- import com.ruoyi.wvp.conf.UserSetting;
- import com.ruoyi.wvp.gb28181.bean.OpenRTPServerResult;
- import com.ruoyi.wvp.gb28181.bean.SsrcTransaction;
- import com.ruoyi.wvp.gb28181.session.SSRCFactory;
- import com.ruoyi.wvp.gb28181.session.SipInviteSessionManager;
- import com.ruoyi.wvp.media.bean.MediaServer;
- import com.ruoyi.wvp.media.event.hook.Hook;
- import com.ruoyi.wvp.media.event.hook.HookSubscribe;
- import com.ruoyi.wvp.media.event.hook.HookType;
- import com.ruoyi.wvp.media.event.media.MediaArrivalEvent;
- import com.ruoyi.wvp.media.event.media.MediaDepartureEvent;
- import com.ruoyi.wvp.media.service.IMediaServerService;
- import com.ruoyi.wvp.service.IReceiveRtpServerService;
- import com.ruoyi.wvp.service.bean.ErrorCallback;
- import com.ruoyi.wvp.service.bean.InviteErrorCode;
- import com.ruoyi.wvp.service.bean.RTPServerParam;
- import com.ruoyi.wvp.service.bean.SSRCInfo;
- import com.zksy.video.lifecycle.VideoStopReceipts;
- import com.zksy.video.lifecycle.VideoStopReceipts.Allocation;
- import com.zksy.video.lifecycle.VideoStopReceipts.RtpState;
- import com.zksy.video.lifecycle.VideoStopReceipts.Snapshot;
- import lombok.extern.slf4j.Slf4j;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.context.event.EventListener;
- import org.springframework.scheduling.annotation.Async;
- import org.springframework.stereotype.Service;
- import java.util.Objects;
- import java.util.UUID;
- import java.util.function.Predicate;
- @Slf4j
- @Service
- public class RtpServerServiceImpl implements IReceiveRtpServerService {
- @Autowired
- private IMediaServerService mediaServerService;
- @Autowired
- private DynamicTask dynamicTask;
- @Autowired
- private SSRCFactory ssrcFactory;
- @Autowired
- private UserSetting userSetting;
- @Autowired
- private HookSubscribe subscribe;
- @Autowired
- private SipInviteSessionManager sessionManager;
- /**
- * 流到来的处理
- */
- @Async("taskExecutor")
- @EventListener
- public void onApplicationEvent(MediaArrivalEvent event) {
- }
- /**
- * 流离开的处理
- */
- @Async("taskExecutor")
- @EventListener
- public void onApplicationEvent(MediaDepartureEvent event) {
- }
- @Autowired
- private com.zksy.video.lifecycle.VideoLifecycleStore videoLifecycleStore;
- @Autowired
- private VideoStopReceipts stopReceipts;
- // Only callback/timer ownership is local. No field here is stop evidence.
- private final java.util.concurrent.ConcurrentMap<String, ManagedRtp> managedRtp = new java.util.concurrent.ConcurrentHashMap<>();
- private static final class ManagedRtp {
- private final SSRCInfo info;
- private HookSubscribe.Subscription owner;
- private final java.util.concurrent.atomic.AtomicBoolean terminal = new java.util.concurrent.atomic.AtomicBoolean();
- private ManagedRtp(SSRCInfo info) { this.info = info; }
- }
- private String managedKey(MediaServer node, String stream) {
- return Hook.getInstance(HookType.on_media_arrival, "rtp", stream, node.getId()).toString();
- }
- private boolean reserveAllocation(MediaServer node, SSRCInfo info, boolean externalSsrc) {
- if (stopReceipts == null) return false;
- return stopReceipts.update(node.getId(), info.getStream(), snapshot -> {
- if (!snapshot.canReplaceAllocation()) return null;
- if (info.getStream().startsWith("managed_") && snapshot.plays.values().stream().anyMatch(play -> play.cancelled)) return null;
- Allocation allocation = new Allocation(); allocation.token = info.getTimeOutTaskKey();
- allocation.ssrc = info.getSsrc(); allocation.port = info.getPort(); allocation.state = RtpState.INTENT;
- allocation.poolTracked = !externalSsrc; allocation.externalSsrc = externalSsrc;
- snapshot.allocation = allocation;
- VideoStopReceipts.Play play = snapshot.plays.get(info.getStream());
- if (play != null) play.allocationToken = allocation.token;
- return snapshot;
- }) != null;
- }
- private boolean allocationState(MediaServer node, SSRCInfo info, RtpState expected, RtpState next) {
- return allocationState(node, info, expected, next, snapshot -> true);
- }
- private boolean allocationState(MediaServer node, SSRCInfo info, RtpState expected, RtpState next,
- Predicate<Snapshot> actorGuard) {
- if (stopReceipts == null) return false;
- for (int attempt = 0; attempt < 4; attempt++) {
- Snapshot updated = stopReceipts.update(node.getId(), info.getStream(), snapshot -> {
- Allocation allocation = snapshot.allocation;
- if (allocation == null || !allocation.matches(info) || allocation.state != expected || !actorGuard.test(snapshot)) return null;
- if (next == RtpState.CREATING && info.getStream().startsWith("managed_")
- && snapshot.plays.values().stream().anyMatch(play -> play.cancelled)) return null;
- allocation.state = next; allocation.port = info.getPort(); return snapshot;
- });
- if (updated != null) return true;
- Snapshot latest = stopReceipts.read(node.getId(), info.getStream());
- if (latest == null || latest.allocation == null || !latest.allocation.matches(info)
- || latest.allocation.state != expected) return false;
- }
- return false;
- }
- private boolean closeAllocation(MediaServer node, SSRCInfo info) {
- return closeAllocation(node, info, snapshot -> true);
- }
- private boolean closeAllocation(MediaServer node, SSRCInfo info, Predicate<Snapshot> actorGuard) {
- if (stopReceipts == null || info == null || info.getStream() == null || info.getTimeOutTaskKey() == null
- || info.getSsrc() == null || !"rtp".equals(info.getApp())) return false;
- Snapshot retained = stopReceipts.read(node.getId(), info.getStream());
- if ((retained == null || retained.allocation == null) && !info.getStream().startsWith("managed_")) {
- // Pre-upgrade legacy callers retain the original typed allocation. Never replace a newer token,
- // reconstruct a managed/adopted receipt, or treat absence as a positive stop acknowledgement.
- retained = stopReceipts.update(node.getId(), info.getStream(), snapshot -> {
- if (snapshot.allocation != null || !snapshot.plays.isEmpty() || !actorGuard.test(snapshot)
- || (sessionManager != null && sessionManager.isAdoptedAllocation(node.getId(), info))) return null;
- Allocation allocation = new Allocation(); allocation.token = info.getTimeOutTaskKey();
- allocation.ssrc = info.getSsrc(); allocation.port = info.getPort(); allocation.state = RtpState.OPEN;
- snapshot.allocation = allocation; return snapshot;
- });
- }
- if (retained == null || retained.allocation == null || !retained.allocation.matches(info) || !actorGuard.test(retained)) return false;
- if (retained.allocation.terminal()) return true;
- if (retained.allocation.state == RtpState.INTENT) {
- // CAS competes with the creator's INTENT -> CREATING, so this is positive never-created evidence.
- return allocationState(node, info, RtpState.INTENT, RtpState.NEVER_CREATED, actorGuard);
- }
- // A process lost during create/close cannot infer completion or send another name-based command.
- if (!allocationState(node, info, RtpState.OPEN, RtpState.CLOSING, actorGuard)) return false;
- try {
- mediaServerService.closeRTPServer(node, info.getStream(), closed -> {
- // Boolean true is the ZLM adapter's code=0/hit=1 receipt, not a request-send result.
- // Retry only shared state CAS inside allocationState, never the external name-close.
- if (!Boolean.TRUE.equals(closed)) return;
- if (!allocationState(node, info, RtpState.CLOSING, RtpState.CLOSED)) return;
- // A late positive receipt must finish pool cleanup even when the caller already
- // returned and no second stop is ever issued.
- try { releaseClosedSsrc(node, info); }
- catch (RuntimeException ex) { log.warn("[RTP close return] {}/{}: {}", node.getId(), info.getStream(), ex.getMessage()); }
- });
- } catch (RuntimeException ex) {
- log.warn("[RTP close] {}/{} remains pending: {}", node.getId(), info.getStream(), ex.getMessage());
- }
- Snapshot after = stopReceipts.read(node.getId(), info.getStream());
- return after != null && after.allocation != null && after.allocation.matches(info)
- && after.allocation.state == RtpState.CLOSED;
- }
- private boolean cancelled(String stream) {
- // Managed resource creation fails closed without the cancellation persistence seam.
- return videoLifecycleStore == null || videoLifecycleStore.isStreamCancelled(stream);
- }
- private SSRCInfo openManagedRtp(RTPServerParam param, ErrorCallback<OpenRTPServerResult> callback) {
- MediaServer node = param.getMediaServerItem();
- String stream = param.getStreamId();
- if (callback == null || node == null || node.getId() == null || !node.isRtpEnable()
- || !stream.matches("managed_[0-9a-fA-F]{32}") || cancelled(stream)) {
- if (callback != null) callback.run(InviteErrorCode.FAIL.getCode(), "Managed RTP requires a unique stream, multi-port node and live generation", null);
- return null;
- }
- // The stream is a single-use generation identity; use it for the pool request too,
- // so cancellation can fence/recover an acquisition whose reply was lost before RTP registration.
- ManagedRtp entry = new ManagedRtp(new SSRCInfo(0, null, "rtp", stream, stream));
- if (managedRtp.putIfAbsent(managedKey(node, stream), entry) != null) {
- callback.run(InviteErrorCode.FAIL.getCode(), "Managed RTP generation already allocated", null);
- return null;
- }
- try {
- entry.info.setSsrc(ssrcFactory.getPlaySsrc(node.getId(), entry.info.getTimeOutTaskKey()));
- if (!reserveAllocation(node, entry.info, false)) {
- Snapshot current = stopReceipts.read(node.getId(), stream);
- if (current == null || current.allocation == null || !current.allocation.matches(entry.info))
- releaseManagedSsrc(node, entry);
- callback.run(InviteErrorCode.FAIL.getCode(), "Managed RTP allocation is already retained", null);
- return null;
- }
- if (cancelled(stream)) {
- closeManagedRTPServer(node, entry.info);
- return null;
- }
- if (!allocationState(node, entry.info, RtpState.INTENT, RtpState.CREATING)) {
- closeManagedRTPServer(node, entry.info); return null;
- }
- int port = mediaServerService.createRTPServer(node, stream,
- param.isSsrcCheck() ? Long.parseLong(entry.info.getSsrc()) : 0,
- 0, false, param.isDisableAudio(), false, param.getTcpMode());
- entry.info.setPort(port);
- // Only the creator knows create returned. Restart during create remains CREATING.
- if (!allocationState(node, entry.info, RtpState.CREATING, RtpState.OPEN)) {
- // The port was already created above. A failed receipt transition must not leak it:
- // close the exact allocation instead of returning silently.
- closeManagedRTPServer(node, entry.info);
- callback.run(InviteErrorCode.FAIL.getCode(), "Managed RTP receipt not acknowledged", null);
- return null;
- }
- if (port <= 0 || cancelled(stream) || entry.terminal.get()) {
- closeManagedRTPServer(node, entry.info);
- callback.run(InviteErrorCode.FAIL.getCode(), "Managed RTP allocation failed or was cancelled", null);
- return null;
- }
- OpenRTPServerResult result = new OpenRTPServerResult(); result.setSsrcInfo(entry.info);
- Hook hook = Hook.getInstance(HookType.on_media_arrival, "rtp", stream, node.getId());
- entry.owner = subscribe.addOwnedSubscribe(hook, data -> {
- if (data.getMediaServer() == null || !node.getId().equals(data.getMediaServer().getId())
- || !stream.equals(data.getStream()) || !"rtp".equals(data.getApp())
- || data.getMediaInfo() == null || !stream.equals(data.getMediaInfo().getStream())
- || !"rtp".equals(data.getMediaInfo().getApp())
- || (data.getMediaInfo().getMediaServer() != null
- && !node.getId().equals(data.getMediaInfo().getMediaServer().getId()))) return;
- if (!entry.terminal.compareAndSet(false, true)) return;
- try {
- dynamicTask.stop(entry.info.getTimeOutTaskKey());
- if (cancelled(stream)) {
- closeManagedRTPServer(node, entry.info);
- callback.run(InviteErrorCode.FAIL.getCode(), "Managed generation cancelled", result);
- return;
- }
- result.setHookData(data);
- callback.run(InviteErrorCode.SUCCESS.getCode(), InviteErrorCode.SUCCESS.getMsg(), result);
- } finally {
- subscribe.removeOwnedSubscribe(entry.owner);
- }
- });
- if (entry.terminal.get()) subscribe.removeOwnedSubscribe(entry.owner);
- dynamicTask.startDelay(entry.info.getTimeOutTaskKey(), () -> {
- if (!entry.terminal.compareAndSet(false, true)) return;
- try { closeManagedRTPServer(node, entry.info); }
- finally { callback.run(InviteErrorCode.ERROR_FOR_STREAM_TIMEOUT.getCode(), "Managed RTP timed out", result); }
- }, userSetting.getPlayTimeout());
- // Cancellation may have raced creation/registration. Never hand out that resource.
- if (cancelled(stream)) {
- closeManagedRTPServer(node, entry.info);
- callback.run(InviteErrorCode.FAIL.getCode(), "Managed generation cancelled", result);
- return null;
- }
- if (entry.terminal.get()) dynamicTask.stop(entry.info.getTimeOutTaskKey());
- return entry.info;
- } catch (RuntimeException ex) {
- // An ambiguous create/receipt write is not proof that the port never existed.
- closeManagedRTPServer(node, entry.info);
- callback.run(InviteErrorCode.FAIL.getCode(), "Managed RTP allocation uncertain: " + ex.getMessage(), null);
- return null;
- }
- }
- private void releaseManagedSsrc(MediaServer node, ManagedRtp entry) {
- if (entry.info.getSsrc() != null) {
- ssrcFactory.releaseSsrc(node.getId(), entry.info.getSsrc(), entry.info.getTimeOutTaskKey());
- }
- }
- /** A completed port close is not full cleanup until its pool allocation was returned.
- * The Factory receipt is atomic with SADD and remains valid after the SN is reused. */
- private boolean releaseClosedSsrc(MediaServer node, SSRCInfo info) {
- Snapshot snapshot = stopReceipts.read(node.getId(), info.getStream());
- if (snapshot == null || snapshot.allocation == null || !snapshot.allocation.matches(info)
- || !snapshot.allocation.terminal()) return false;
- Allocation allocation = snapshot.allocation;
- if (allocation.externalSsrc || allocation.poolSsrc() == null || allocation.poolReturned) return true;
- String poolSsrc = allocation.poolSsrc(), token = allocation.token;
- if (ssrcFactory.wasReleased(node.getId(), poolSsrc, token)) return true;
- // Return the originally allocated number, never a device-negotiated SSRC.
- boolean released = allocation.poolTracked
- ? ssrcFactory.releaseSsrc(node.getId(), poolSsrc, token)
- : ssrcFactory.releaseObservedLegacySsrc(node.getId(), poolSsrc, token);
- return released || ssrcFactory.wasReleased(node.getId(), poolSsrc, token);
- }
- @Override
- public boolean closeManagedRTPServer(MediaServer node, SSRCInfo info) {
- if (node == null || node.getId() == null || info == null || info.getStream() == null
- || !info.getStream().matches("managed_[0-9a-fA-F]{32}")) return false;
- if (stopReceipts != null) {
- Snapshot pending = stopReceipts.read(node.getId(), info.getStream());
- VideoStopReceipts.Play intent = pending == null ? null : pending.plays.get(info.getStream());
- if (pending != null && pending.allocation == null && intent != null && intent.cancelled
- && !intent.inviteSent && info.getStream().equals(info.getTimeOutTaskKey()))
- return ssrcFactory.cancelAllocation(node.getId(), info.getStream());
- }
- ManagedRtp entry = managedRtp.get(managedKey(node, info.getStream()));
- if (entry != null) {
- entry.terminal.set(true);
- try {
- if (entry.info.getTimeOutTaskKey() != null) dynamicTask.stop(entry.info.getTimeOutTaskKey());
- } catch (RuntimeException ex) {
- log.warn("[Managed timer close] {}: {}", info.getStream(), ex.getMessage());
- } finally { subscribe.removeOwnedSubscribe(entry.owner); }
- }
- boolean closed = closeAllocation(node, info);
- return closed && releaseClosedSsrc(node, info);
- }
- /** Unlike managed UUIDs, legacy names can be allocated again. Keep the allocation token, not a name receipt. */
- private final java.util.Map<String, LegacyRtp> legacyRtp = new java.util.concurrent.ConcurrentHashMap<>();
- private static final class LegacyRtp {
- private final SSRCInfo info;
- private HookSubscribe.Subscription owner;
- private final java.util.concurrent.atomic.AtomicBoolean terminal = new java.util.concurrent.atomic.AtomicBoolean();
- private LegacyRtp(SSRCInfo info) { this.info = info; }
- }
- @Override
- public synchronized boolean closeAdoptedRTPServer(MediaServer node, SSRCInfo info, String callId) {
- if (node == null || node.getId() == null || !node.isRtpEnable() || info == null
- || info.getStream() == null || info.getStream().startsWith("managed_") || !"rtp".equals(info.getApp())
- || info.getSsrc() == null || info.getTimeOutTaskKey() == null || callId == null
- || sessionManager == null || stopReceipts == null || !sessionManager.isAdoptedRtp(node.getId(), callId, info)) return false;
- String key = managedKey(node, info.getStream());
- LegacyRtp entry = legacyRtp.get(key);
- if (entry != null && !entry.info.equals(info)) entry = null; // stale local timer owner is not allocation evidence
- com.ruoyi.wvp.gb28181.bean.SsrcTransaction current = sessionManager.getSsrcTransactionByStream("rtp", info.getStream());
- if (current != null && (!callId.equals(current.getCallId()) || !info.getSsrc().equals(current.getSsrc())
- || !node.getId().equals(current.getMediaServerId()) || !sessionManager.isAdopted(current))) return false;
- Snapshot retained = stopReceipts.read(node.getId(), info.getStream());
- if (retained == null || retained.allocation == null || !retained.allocation.matches(info)
- || !callId.equals(retained.allocation.callId)) return false;
- com.ruoyi.wvp.gb28181.bean.SsrcTransaction expected = retained.plays.values().stream()
- .filter(play -> java.util.Objects.equals(play.allocationToken, info.getTimeOutTaskKey())
- && play.dialog != null && callId.equals(play.dialog.getCallId()))
- .map(play -> play.dialog).findFirst().orElse(null);
- if (expected == null || !sessionManager.isAdopted(expected)
- || (current != null && !SipInviteSessionManager.sameDialog(expected, current))) return false;
- if (entry != null) entry.terminal.set(true);
- try { dynamicTask.stop(info.getTimeOutTaskKey()); }
- catch (RuntimeException ex) { log.warn("[Adopted timer close] {}: {}", info.getStream(), ex.getMessage()); }
- finally { if (entry != null) subscribe.removeOwnedSubscribe(entry.owner); }
- boolean closed = closeAllocation(node, info, snapshot -> originalActor(snapshot, info, expected));
- return closed && releaseClosedSsrc(node, info);
- }
- @Override
- public SSRCInfo openRTPServer(RTPServerParam rtpServerParam, ErrorCallback<OpenRTPServerResult> callback) {
- if (rtpServerParam.getStreamId() != null && rtpServerParam.getStreamId().startsWith("managed_")) {
- return openManagedRtp(rtpServerParam, callback);
- }
- return openLegacyRtp(rtpServerParam, callback);
- }
- private synchronized SSRCInfo openLegacyRtp(RTPServerParam rtpServerParam, ErrorCallback<OpenRTPServerResult> callback) {
- if (callback == null) {
- log.warn("[开启RTP收流] 失败,回调为NULL");
- return null;
- }
- if (rtpServerParam.getMediaServerItem() == null) {
- log.warn("[开启RTP收流] 失败,媒体节点为NULL");
- return null;
- }
- // 获取mediaServer可用的ssrc
- final String timeOutTaskKey = UUID.randomUUID().toString();
- final String ssrc;
- if (rtpServerParam.getPresetSsrc() != null) {
- ssrc = rtpServerParam.getPresetSsrc();
- }else {
- if (rtpServerParam.isPlayback()) {
- ssrc = ssrcFactory.getPlayBackSsrc(rtpServerParam.getMediaServerItem().getId(), timeOutTaskKey);
- }else {
- ssrc = ssrcFactory.getPlaySsrc(rtpServerParam.getMediaServerItem().getId(), timeOutTaskKey);
- }
- }
- final String streamId;
- if (rtpServerParam.getStreamId() == null) {
- streamId = String.format("%08x", Long.parseLong(ssrc)).toUpperCase();
- }else {
- streamId = rtpServerParam.getStreamId();
- }
- if (rtpServerParam.isSsrcCheck() && rtpServerParam.getTcpMode() > 0) {
- // 目前zlm不支持 tcp模式更新ssrc,暂时关闭ssrc校验
- log.warn("[openRTPServer] 平台对接时下级可能自定义ssrc,但是tcp模式zlm收流目前无法更新ssrc,可能收流超时,此时请使用udp收流或者关闭ssrc校验");
- }
- // Register BEFORE create: even an in-flight replacement invalidates the previous close receipt.
- SSRCInfo ssrcInfo = new SSRCInfo(0, ssrc, "rtp", streamId, timeOutTaskKey);
- LegacyRtp entry = new LegacyRtp(ssrcInfo);
- String allocationKey = managedKey(rtpServerParam.getMediaServerItem(), streamId);
- if (!reserveAllocation(rtpServerParam.getMediaServerItem(), ssrcInfo, rtpServerParam.getPresetSsrc() != null)) {
- if (rtpServerParam.getPresetSsrc() == null) ssrcFactory.releaseSsrc(rtpServerParam.getMediaServerItem().getId(), ssrc, timeOutTaskKey);
- callback.run(InviteErrorCode.FAIL.getCode(), "Adopted RTP close is still pending", null);
- return null;
- }
- legacyRtp.put(allocationKey, entry);
- if (!allocationState(rtpServerParam.getMediaServerItem(), ssrcInfo, RtpState.INTENT, RtpState.CREATING)) {
- closeAllocation(rtpServerParam.getMediaServerItem(), ssrcInfo); return null;
- }
- int rtpServerPort;
- if (rtpServerParam.getMediaServerItem().isRtpEnable()) {
- rtpServerPort = mediaServerService.createRTPServer(rtpServerParam.getMediaServerItem(), streamId,
- rtpServerParam.isSsrcCheck() ? Long.parseLong(ssrc) : 0, rtpServerParam.getPort(), rtpServerParam.isOnlyAuto(),
- rtpServerParam.isDisableAudio(), rtpServerParam.isReUsePort(), rtpServerParam.getTcpMode());
- } else {
- rtpServerPort = rtpServerParam.getMediaServerItem().getRtpProxyPort();
- }
- ssrcInfo.setPort(rtpServerPort);
- if (!allocationState(rtpServerParam.getMediaServerItem(), ssrcInfo, RtpState.CREATING, RtpState.OPEN)) {
- // A created port must be closed even when the receipt transition did not commit.
- closeAllocation(rtpServerParam.getMediaServerItem(), ssrcInfo);
- callback.run(InviteErrorCode.FAIL.getCode(), "RTP receipt not acknowledged", null);
- return null;
- }
- if (rtpServerPort == 0) {
- callback.run(InviteErrorCode.ERROR_FOR_RESOURCE_EXHAUSTION.getCode(), "开启RTPServer失败", null);
- // 释放ssrc
- if (rtpServerParam.getPresetSsrc() == null) {
- ssrcFactory.releaseSsrc(rtpServerParam.getMediaServerItem().getId(), ssrc, timeOutTaskKey);
- }
- return null;
- }
- OpenRTPServerResult openRTPServerResult = new OpenRTPServerResult();
- openRTPServerResult.setSsrcInfo(ssrcInfo);
- Hook rtpHook = Hook.getInstance(HookType.on_media_arrival, ssrcInfo.getApp(), streamId, rtpServerParam.getMediaServerItem().getId());
- dynamicTask.startDelay(timeOutTaskKey, () -> {
- if (legacyRtp.get(allocationKey) != entry || !entry.terminal.compareAndSet(false, true)) return;
- // Close through the shared allocation fence; never release an unknown allocation's SSRC early.
- closeRTPServer(rtpServerParam.getMediaServerItem(), ssrcInfo);
- subscribe.removeOwnedSubscribe(entry.owner);
- callback.run(InviteErrorCode.ERROR_FOR_STREAM_TIMEOUT.getCode(), InviteErrorCode.ERROR_FOR_STREAM_TIMEOUT.getMsg(), openRTPServerResult);
- }, userSetting.getPlayTimeout());
- // 开启流到来的监听
- entry.owner = subscribe.addOwnedSubscribe(rtpHook, (hookData) -> {
- if (legacyRtp.get(allocationKey) != entry || !entry.terminal.compareAndSet(false, true)) return;
- dynamicTask.stop(timeOutTaskKey);
- // hook响应
- openRTPServerResult.setHookData(hookData);
- try {
- callback.run(InviteErrorCode.SUCCESS.getCode(), InviteErrorCode.SUCCESS.getMsg(), openRTPServerResult);
- } finally {
- subscribe.removeOwnedSubscribe(entry.owner);
- }
- });
- if (entry.terminal.get()) subscribe.removeOwnedSubscribe(entry.owner);
- return ssrcInfo;
- }
- /** Peer BYE/offline must use the original Invite and dialog, never the name's current allocation. */
- public boolean closeRTPServerForSession(SsrcTransaction original, InviteInfo invite) {
- if (original == null || sessionManager == null || stopReceipts == null
- || !SipInviteSessionManager.sameDialog(original,
- sessionManager.getSsrcTransactionByStream(original.getApp(), original.getStream()))) return false;
- SSRCInfo info = invite == null ? sessionManager.getAdoptedAllocation(original) : invite.getSsrcInfo();
- if (info == null || !Objects.equals(original.getApp(), info.getApp())
- || !Objects.equals(original.getStream(), info.getStream()) || !Objects.equals(original.getSsrc(), info.getSsrc())
- || (invite != null && (!Objects.equals(original.getMediaServerId(), invite.getMediaServerId())
- || !Objects.equals(original.getDeviceId(), invite.getDeviceId()) || !Objects.equals(original.getChannelId(), invite.getChannelId())
- || original.getType() != invite.getType() || !Objects.equals(original.getStream(), invite.getStream())))) return false;
- MediaServer node = mediaServerService.getOne(original.getMediaServerId());
- if (node == null || !Objects.equals(original.getMediaServerId(), node.getId())) return false;
- if (info.getStream().startsWith("managed_")) {
- if (!stopReceipts.retainDialog(original)) return false;
- return closeManagedRTPServer(node, info);
- }
- if (sessionManager.isAdopted(original)) return closeAdoptedRTPServer(node, info, original.getCallId());
- return closeLegacyRtp(node, info, snapshot -> originalActor(snapshot, info, original));
- }
- private boolean originalActor(Snapshot snapshot, SSRCInfo info, SsrcTransaction original) {
- return (snapshot.allocation == null || snapshot.allocation.callId == null
- || Objects.equals(snapshot.allocation.callId, original.getCallId()))
- && snapshot.plays.values().stream().noneMatch(play -> Objects.equals(play.allocationToken, info.getTimeOutTaskKey())
- && play.dialog != null && !SipInviteSessionManager.sameDialog(original, play.dialog));
- }
- @Override
- public void closeRTPServer(MediaServer mediaServer, SSRCInfo ssrcInfo) {
- if (ssrcInfo != null && ssrcInfo.getStream() != null && ssrcInfo.getStream().startsWith("managed_")) {
- closeManagedRTPServer(mediaServer, ssrcInfo);
- return;
- }
- closeLegacyRtp(mediaServer, ssrcInfo, snapshot -> true);
- }
- private boolean closeLegacyRtp(MediaServer mediaServer, SSRCInfo ssrcInfo, Predicate<Snapshot> actorGuard) {
- if (mediaServer == null || mediaServer.getId() == null || ssrcInfo == null || ssrcInfo.getStream() == null) return false;
- if (ssrcInfo.getTimeOutTaskKey() != null) dynamicTask.stop(ssrcInfo.getTimeOutTaskKey());
- LegacyRtp entry = legacyRtp.get(managedKey(mediaServer, ssrcInfo.getStream()));
- if (entry != null && entry.info.equals(ssrcInfo)) {
- entry.terminal.set(true); subscribe.removeOwnedSubscribe(entry.owner);
- }
- boolean closed = closeAllocation(mediaServer, ssrcInfo, actorGuard);
- return closed && releaseClosedSsrc(mediaServer, ssrcInfo);
- }
- }
|