videoLiveSession.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. /*!
  2. * Live-session helper adapted from city-life-line/src/utils/videoLiveSession.js.
  3. * Copyright (c) 2018 RuoYi — MIT License.
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy of
  5. * this software and associated documentation files (the "Software"), to deal in
  6. * the Software without restriction, including without limitation the rights to
  7. * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
  8. * the Software, and to permit persons to whom the Software is furnished to do so,
  9. * subject to the following conditions:
  10. * The above copyright notice and this permission notice shall be included in all
  11. * copies or substantial portions of the Software.
  12. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
  14. * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
  15. * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
  16. * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  17. * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  18. */
  19. import { selectVideoMedia, VideoRequestError } from './videoApi.js'
  20. /** One visible attempt, owned preparation before media, a bounded retry budget and cleanup observer. */
  21. export function createVideoLiveSession(api, update, timers = globalThis) {
  22. let generation = 0, current = null, cleanupTimer, cleanupChecks = 0, disposed = false
  23. const releases = new Set()
  24. const cleanupMessage = '会话释放未确认,等待服务端回收;可重试清理'
  25. // Retry policy: five automatic attempts after the first normal play, spaced 2/4/8/16/30s.
  26. const retryDelays = [2000, 4000, 8000, 16000, 30000]
  27. const stablePlaybackMs = 30000
  28. const unrecoverable = new Set(['DEVICE_NOT_FOUND', 'VIDEO_UNAVAILABLE', 'SESSION_FORBIDDEN', 'INVALID_RESPONSE', 'NOT_CONFIGURED', 'INVALID_REQUEST', 'UNSUPPORTED_MEDIA'])
  29. let retryBudget = retryDelays.length, retryTimer, retryAttempt = 0, stableTimer
  30. const publish = (patch) => { if (!disposed) update(patch) }
  31. const reportCleanup = () => publish({ cleanupError: releases.size ? cleanupMessage : '' })
  32. const active = (attempt) => !disposed && current === attempt && attempt.version === generation
  33. const clear = (attempt) => {
  34. if (!attempt) return
  35. timers.clearTimeout(attempt.startTimer); timers.clearTimeout(attempt.readyTimer); timers.clearInterval(attempt.heartbeat)
  36. }
  37. const cancelRetry = () => {
  38. timers.clearTimeout(retryTimer); retryTimer = undefined
  39. timers.clearTimeout(stableTimer); stableTimer = undefined
  40. }
  41. function scheduleCleanup() {
  42. if (disposed || cleanupTimer || !releases.size || cleanupChecks >= 40) return
  43. cleanupTimer = timers.setTimeout(async () => {
  44. cleanupTimer = null; cleanupChecks += 1
  45. for (const session of [...releases]) {
  46. try {
  47. const result = await api.status(session)
  48. if (result.sessionId === session.sessionId && ['STOPPED', 'FAILED'].includes(result.status)) {
  49. session.released = true; releases.delete(session)
  50. }
  51. } catch { /* Unknown status is not release evidence. */ }
  52. }
  53. reportCleanup(); scheduleCleanup()
  54. }, 3000)
  55. }
  56. async function release(session) {
  57. if (!session || session.released) return true
  58. if (session.releasing) return session.releasing
  59. releases.add(session)
  60. session.releasing = Promise.resolve().then(async () => {
  61. try {
  62. const result = await api.stop(session)
  63. if (result.sessionId !== session.sessionId || !['STOPPED', 'FAILED'].includes(result.status)) throw new Error('Cleanup not confirmed')
  64. session.released = true; releases.delete(session); return true
  65. } catch {
  66. if (session.released) return true
  67. publish({ cleanupError: cleanupMessage }); scheduleCleanup(); return false
  68. } finally { session.releasing = null }
  69. })
  70. return session.releasing
  71. }
  72. async function stop() {
  73. ++generation
  74. cancelRetry()
  75. const attempt = current; current = null; clear(attempt)
  76. publish({ media: null, phase: 'idle' })
  77. if (attempt?.identity) releases.add(attempt.identity)
  78. cleanupChecks = 0
  79. for (const session of [...releases]) await release(session)
  80. reportCleanup()
  81. return releases.size === 0
  82. }
  83. /** Only a temporary failure with budget left is retried; capability/ownership errors are final. */
  84. function shouldRetry(error) {
  85. if (disposed || !current || releases.size || retryBudget <= 0) return false
  86. // VideoRequestError carries `category`; accepted errors use `code`.
  87. const reason = error?.category || error?.code
  88. return !unrecoverable.has(reason)
  89. } function scheduleRetry(deviceCode, message) {
  90. const attempt = current
  91. // Spend the budget here, before the timer exists, so the last retry cannot schedule another.
  92. retryBudget -= 1
  93. retryAttempt += 1
  94. const delay = retryDelays[retryDelays.length - retryBudget - 1] ?? retryDelays[retryDelays.length - 1]
  95. publish({ phase: 'retrying', error: message, retryAttempt, retryDelayMs: delay, retriesLeft: retryBudget })
  96. retryTimer = timers.setTimeout(() => {
  97. retryTimer = undefined
  98. if (!active(attempt) || releases.size) return
  99. void begin(deviceCode)
  100. }, delay)
  101. }
  102. async function fail(message, media) {
  103. if (!current || (media && current.media !== media)) return
  104. const error = message instanceof Error ? message : Object.assign(new Error(message || '视频播放失败'), {})
  105. const deviceCode = current.deviceCode
  106. publish({ error: error.message || '视频播放失败' })
  107. const attempt = current
  108. const retryable = shouldRetry(error)
  109. const stopping = stop(), version = generation
  110. const released = await stopping
  111. if (disposed || version !== generation) return
  112. if (!retryable || !released) { publish({ phase: 'failed' }); return }
  113. generation = version
  114. current = attempt
  115. attempt.version = version
  116. scheduleRetry(deviceCode, error.message)
  117. }
  118. function ready(media) {
  119. if (!current?.media || current.identity?.released || (media && current.media !== media)) return
  120. timers.clearTimeout(current.readyTimer)
  121. publish({ phase: 'playing' })
  122. // A retry budget is earned only after real, sustained playback.
  123. timers.clearTimeout(stableTimer)
  124. const attempt = current
  125. stableTimer = timers.setTimeout(() => {
  126. if (!active(attempt)) return
  127. retryBudget = retryDelays.length; retryAttempt = 0
  128. }, stablePlaybackMs)
  129. }
  130. async function begin(deviceCode) {
  131. if (disposed) return
  132. if (releases.size) {
  133. publish({ phase: 'failed', error: '上次清理结果尚未确认,暂不能重复建流' }); return
  134. }
  135. const version = generation
  136. const attempt = { version, deviceCode, identity: null, media: null }
  137. current = attempt
  138. publish({ phase: 'starting', media: null, error: '', cleanupError: '' })
  139. attempt.startTimer = timers.setTimeout(() => { if (active(attempt)) void fail('视频建立超时') }, 35000)
  140. try {
  141. const identity = await api.prepare(deviceCode)
  142. if (typeof identity.sessionId !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/.test(identity.sessionId)
  143. || typeof identity.sessionToken !== 'string' || !identity.sessionToken)
  144. throw new VideoRequestError('INVALID_RESPONSE', '媒体启动前未取得完整观看身份')
  145. attempt.identity = { sessionId: identity.sessionId, sessionToken: identity.sessionToken, deviceCode, mode: 'LIVE' }
  146. if (!active(attempt)) { await release(attempt.identity); return }
  147. if (identity.deviceCode !== deviceCode || identity.mode !== 'LIVE' || identity.status !== 'PREPARED')
  148. throw new VideoRequestError('INVALID_RESPONSE', '观看身份与当前设备不匹配')
  149. let data = await api.start(attempt.identity)
  150. while (active(attempt) && data.status === 'STARTING') {
  151. if (data.sessionId !== attempt.identity.sessionId) throw new VideoRequestError('INVALID_RESPONSE', '返回的观看会话不匹配')
  152. await new Promise((resolve) => timers.setTimeout(resolve, 1000))
  153. if (!active(attempt)) break
  154. data = await api.status(attempt.identity)
  155. }
  156. if (!active(attempt)) { await release(attempt.identity); return }
  157. if (data.sessionId !== attempt.identity.sessionId) throw new VideoRequestError('INVALID_RESPONSE', '返回的观看会话不匹配')
  158. if (['STOPPED', 'FAILED'].includes(data.status)) {
  159. attempt.identity.released = true; clear(attempt); current = null
  160. publish({ media: null, phase: 'failed', error: '观看会话未建立或已停止' }); return
  161. }
  162. if (data.mode !== 'LIVE') throw new VideoRequestError('INVALID_RESPONSE', '返回的播放会话与当前设备不匹配')
  163. // 后端 preparedResult 只回 sessionId/status/mode/media;deviceCode 可选,只有在确实回了且不一致时才算不匹配。
  164. if (data.deviceCode !== undefined && data.deviceCode !== deviceCode)
  165. throw new VideoRequestError('INVALID_RESPONSE', '返回的播放会话与当前设备不匹配')
  166. if (data.status !== 'ACTIVE') throw new VideoRequestError('SESSION_PENDING', '媒体尚未就绪,结束本次观看')
  167. attempt.media = selectVideoMedia(data.media)
  168. timers.clearTimeout(attempt.startTimer)
  169. publish({ phase: 'connecting', media: attempt.media })
  170. attempt.readyTimer = timers.setTimeout(() => { if (active(attempt)) void fail('播放器就绪超时') }, 20000)
  171. let beating = false
  172. attempt.heartbeat = timers.setInterval(async () => {
  173. if (beating || !active(attempt)) return
  174. beating = true
  175. try { await api.heartbeat(attempt.identity) }
  176. catch { if (active(attempt)) await fail('播放会话已断开,请重新播放') }
  177. finally { beating = false }
  178. }, 30000)
  179. } catch (error) {
  180. if (active(attempt)) await fail(error)
  181. else if (attempt.identity) await release(attempt.identity)
  182. } finally {
  183. timers.clearTimeout(attempt.startTimer)
  184. reportCleanup()
  185. }
  186. }
  187. async function start(deviceCode) {
  188. const stopping = stop(), version = generation
  189. await stopping
  190. if (disposed || version !== generation) return
  191. // A manual replay starts a fresh budget; automatic retries never call this.
  192. retryBudget = retryDelays.length; retryAttempt = 0
  193. await begin(deviceCode)
  194. }
  195. async function dispose() { await stop(); disposed = true; timers.clearTimeout(cleanupTimer) }
  196. return { start, stop, dispose, ready, fail }
  197. }