electron-cast 0.4.0 → 0.5.0-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (626) hide show
  1. package/CHANGELOG.md +280 -0
  2. package/CONTRIBUTING.md +305 -0
  3. package/README.md +211 -165
  4. package/SECURITY.md +324 -0
  5. package/dist/cjs/client/auth/build-time.js +1 -1
  6. package/dist/cjs/client/auth/cast-auth.d.ts +2 -0
  7. package/dist/cjs/client/auth/cast-auth.js.map +1 -1
  8. package/dist/cjs/dial/dial-registry.d.ts +104 -0
  9. package/dist/cjs/dial/dial-registry.js +301 -0
  10. package/dist/cjs/dial/dial-registry.js.map +1 -0
  11. package/dist/cjs/dial/dial-sink-service.d.ts +108 -0
  12. package/dist/cjs/dial/dial-sink-service.js +314 -0
  13. package/dist/cjs/dial/dial-sink-service.js.map +1 -0
  14. package/dist/cjs/dial/http.d.ts +40 -0
  15. package/dist/cjs/dial/http.js +172 -0
  16. package/dist/cjs/dial/http.js.map +1 -0
  17. package/dist/cjs/dial/index.d.ts +63 -0
  18. package/dist/cjs/dial/index.js +134 -0
  19. package/dist/cjs/dial/index.js.map +1 -0
  20. package/dist/cjs/dial/origins.d.ts +4 -0
  21. package/dist/cjs/dial/origins.js +36 -0
  22. package/dist/cjs/dial/origins.js.map +1 -0
  23. package/dist/cjs/dial/parse.d.ts +101 -0
  24. package/dist/cjs/dial/parse.js +296 -0
  25. package/dist/cjs/dial/parse.js.map +1 -0
  26. package/dist/cjs/dial/route-provider.d.ts +96 -0
  27. package/dist/cjs/dial/route-provider.js +376 -0
  28. package/dist/cjs/dial/route-provider.js.map +1 -0
  29. package/dist/cjs/dial/ssdp-socket.d.ts +34 -0
  30. package/dist/cjs/dial/ssdp-socket.js +72 -0
  31. package/dist/cjs/dial/ssdp-socket.js.map +1 -0
  32. package/dist/cjs/dial/xml.d.ts +13 -0
  33. package/dist/cjs/dial/xml.js +208 -0
  34. package/dist/cjs/dial/xml.js.map +1 -0
  35. package/dist/cjs/discovery/cast-discovery.d.ts +2 -0
  36. package/dist/cjs/discovery/cast-discovery.js.map +1 -1
  37. package/dist/cjs/discovery/device-cache.d.ts +9 -0
  38. package/dist/cjs/discovery/device-cache.js.map +1 -1
  39. package/dist/cjs/discovery/index.d.ts +1 -0
  40. package/dist/cjs/discovery/index.js +1 -0
  41. package/dist/cjs/discovery/index.js.map +1 -1
  42. package/dist/cjs/discovery/ip-policy.d.ts +20 -0
  43. package/dist/cjs/discovery/ip-policy.js +109 -0
  44. package/dist/cjs/discovery/ip-policy.js.map +1 -0
  45. package/dist/cjs/discovery/udp-socket.d.ts +3 -0
  46. package/dist/cjs/discovery/udp-socket.js +3 -0
  47. package/dist/cjs/discovery/udp-socket.js.map +1 -1
  48. package/dist/cjs/electron/access-code.d.ts +221 -0
  49. package/dist/cjs/electron/access-code.js +586 -0
  50. package/dist/cjs/electron/access-code.js.map +1 -0
  51. package/dist/cjs/electron/app-discovery.d.ts +82 -0
  52. package/dist/cjs/electron/app-discovery.js +219 -0
  53. package/dist/cjs/electron/app-discovery.js.map +1 -0
  54. package/dist/cjs/electron/default-presentation.d.ts +38 -0
  55. package/dist/cjs/electron/default-presentation.js +88 -0
  56. package/dist/cjs/electron/default-presentation.js.map +1 -0
  57. package/dist/cjs/electron/main.d.ts +98 -11
  58. package/dist/cjs/electron/main.js +602 -20
  59. package/dist/cjs/electron/main.js.map +1 -1
  60. package/dist/cjs/electron/manager-api.d.ts +200 -18
  61. package/dist/cjs/electron/manager-api.js +199 -4
  62. package/dist/cjs/electron/manager-api.js.map +1 -1
  63. package/dist/cjs/electron/media-controller.d.ts +79 -0
  64. package/dist/cjs/electron/media-controller.js +251 -0
  65. package/dist/cjs/electron/media-controller.js.map +1 -0
  66. package/dist/cjs/electron/network-monitor.d.ts +61 -0
  67. package/dist/cjs/electron/network-monitor.js +124 -0
  68. package/dist/cjs/electron/network-monitor.js.map +1 -0
  69. package/dist/cjs/electron/preload.js.map +1 -1
  70. package/dist/cjs/electron/presentation-handler.d.ts +39 -4
  71. package/dist/cjs/electron/presentation-handler.js +191 -47
  72. package/dist/cjs/electron/presentation-handler.js.map +1 -1
  73. package/dist/cjs/electron/presentation-source.d.ts +76 -0
  74. package/dist/cjs/electron/presentation-source.js +132 -0
  75. package/dist/cjs/electron/presentation-source.js.map +1 -0
  76. package/dist/cjs/electron/session-service.d.ts +198 -24
  77. package/dist/cjs/electron/session-service.js +630 -248
  78. package/dist/cjs/electron/session-service.js.map +1 -1
  79. package/dist/cjs/electron/session-tracker.d.ts +82 -0
  80. package/dist/cjs/electron/session-tracker.js +225 -0
  81. package/dist/cjs/electron/session-tracker.js.map +1 -0
  82. package/dist/cjs/electron/sink-service.d.ts +246 -0
  83. package/dist/cjs/electron/sink-service.js +606 -0
  84. package/dist/cjs/electron/sink-service.js.map +1 -0
  85. package/dist/cjs/electron/wired-display/controller.d.ts +76 -0
  86. package/dist/cjs/electron/wired-display/controller.js +198 -0
  87. package/dist/cjs/electron/wired-display/controller.js.map +1 -0
  88. package/dist/cjs/electron/wired-display/displays.d.ts +44 -0
  89. package/dist/cjs/electron/wired-display/displays.js +98 -0
  90. package/dist/cjs/electron/wired-display/displays.js.map +1 -0
  91. package/dist/cjs/electron/wired-display/electron-windows.d.ts +111 -0
  92. package/dist/cjs/electron/wired-display/electron-windows.js +306 -0
  93. package/dist/cjs/electron/wired-display/electron-windows.js.map +1 -0
  94. package/dist/cjs/electron/wired-display/index.d.ts +90 -0
  95. package/dist/cjs/electron/wired-display/index.js +115 -0
  96. package/dist/cjs/electron/wired-display/index.js.map +1 -0
  97. package/dist/cjs/electron/wired-display/local-presentation.d.ts +98 -0
  98. package/dist/cjs/electron/wired-display/local-presentation.js +234 -0
  99. package/dist/cjs/electron/wired-display/local-presentation.js.map +1 -0
  100. package/dist/cjs/electron/wired-display/provider.d.ts +112 -0
  101. package/dist/cjs/electron/wired-display/provider.js +202 -0
  102. package/dist/cjs/electron/wired-display/provider.js.map +1 -0
  103. package/dist/cjs/index.d.ts +1 -0
  104. package/dist/cjs/index.js +1 -0
  105. package/dist/cjs/index.js.map +1 -1
  106. package/dist/cjs/mirroring/backend.d.ts +76 -0
  107. package/dist/cjs/mirroring/backend.js +21 -0
  108. package/dist/cjs/mirroring/backend.js.map +1 -0
  109. package/dist/cjs/mirroring/electron/agent-protocol.d.ts +158 -0
  110. package/dist/cjs/mirroring/electron/agent-protocol.js +11 -0
  111. package/dist/cjs/mirroring/electron/agent-protocol.js.map +1 -0
  112. package/dist/cjs/mirroring/electron/agent-source.d.ts +20 -0
  113. package/dist/cjs/mirroring/electron/agent-source.js +621 -0
  114. package/dist/cjs/mirroring/electron/agent-source.js.map +1 -0
  115. package/dist/cjs/mirroring/electron/engine-process.d.ts +87 -0
  116. package/dist/cjs/mirroring/electron/engine-process.js +81 -0
  117. package/dist/cjs/mirroring/electron/engine-process.js.map +1 -0
  118. package/dist/cjs/mirroring/electron/host.d.ts +89 -0
  119. package/dist/cjs/mirroring/electron/host.js +321 -0
  120. package/dist/cjs/mirroring/electron/host.js.map +1 -0
  121. package/dist/cjs/mirroring/electron/port-backend.d.ts +107 -0
  122. package/dist/cjs/mirroring/electron/port-backend.js +446 -0
  123. package/dist/cjs/mirroring/electron/port-backend.js.map +1 -0
  124. package/dist/cjs/mirroring/encoding-support.d.ts +66 -0
  125. package/dist/cjs/mirroring/encoding-support.js +89 -0
  126. package/dist/cjs/mirroring/encoding-support.js.map +1 -0
  127. package/dist/cjs/mirroring/engine.d.ts +16 -0
  128. package/dist/cjs/mirroring/engine.js +78 -0
  129. package/dist/cjs/mirroring/engine.js.map +1 -0
  130. package/dist/cjs/mirroring/mirror-settings.d.ts +101 -0
  131. package/dist/cjs/mirroring/mirror-settings.js +140 -0
  132. package/dist/cjs/mirroring/mirror-settings.js.map +1 -0
  133. package/dist/cjs/mirroring/mirroring-activity.d.ts +207 -0
  134. package/dist/cjs/mirroring/mirroring-activity.js +367 -0
  135. package/dist/cjs/mirroring/mirroring-activity.js.map +1 -0
  136. package/dist/cjs/mirroring/mirroring-manager.d.ts +134 -0
  137. package/dist/cjs/mirroring/mirroring-manager.js +286 -0
  138. package/dist/cjs/mirroring/mirroring-manager.js.map +1 -0
  139. package/dist/cjs/mirroring/protocol/answer.d.ts +87 -0
  140. package/dist/cjs/mirroring/protocol/answer.js +233 -0
  141. package/dist/cjs/mirroring/protocol/answer.js.map +1 -0
  142. package/dist/cjs/mirroring/protocol/constants.d.ts +64 -0
  143. package/dist/cjs/mirroring/protocol/constants.js +70 -0
  144. package/dist/cjs/mirroring/protocol/constants.js.map +1 -0
  145. package/dist/cjs/mirroring/protocol/errors.d.ts +25 -0
  146. package/dist/cjs/mirroring/protocol/errors.js +34 -0
  147. package/dist/cjs/mirroring/protocol/errors.js.map +1 -0
  148. package/dist/cjs/mirroring/protocol/frame-id.d.ts +9 -0
  149. package/dist/cjs/mirroring/protocol/frame-id.js +24 -0
  150. package/dist/cjs/mirroring/protocol/frame-id.js.map +1 -0
  151. package/dist/cjs/mirroring/protocol/messenger.d.ts +42 -0
  152. package/dist/cjs/mirroring/protocol/messenger.js +122 -0
  153. package/dist/cjs/mirroring/protocol/messenger.js.map +1 -0
  154. package/dist/cjs/mirroring/protocol/offer.d.ts +109 -0
  155. package/dist/cjs/mirroring/protocol/offer.js +192 -0
  156. package/dist/cjs/mirroring/protocol/offer.js.map +1 -0
  157. package/dist/cjs/mirroring/protocol/recommendations.d.ts +28 -0
  158. package/dist/cjs/mirroring/protocol/recommendations.js +103 -0
  159. package/dist/cjs/mirroring/protocol/recommendations.js.map +1 -0
  160. package/dist/cjs/mirroring/routing.d.ts +60 -0
  161. package/dist/cjs/mirroring/routing.js +147 -0
  162. package/dist/cjs/mirroring/routing.js.map +1 -0
  163. package/dist/cjs/mirroring/rtcp/ntp.d.ts +27 -0
  164. package/dist/cjs/mirroring/rtcp/ntp.js +62 -0
  165. package/dist/cjs/mirroring/rtcp/ntp.js.map +1 -0
  166. package/dist/cjs/mirroring/rtcp/parser.d.ts +50 -0
  167. package/dist/cjs/mirroring/rtcp/parser.js +270 -0
  168. package/dist/cjs/mirroring/rtcp/parser.js.map +1 -0
  169. package/dist/cjs/mirroring/rtcp/sender-report.d.ts +32 -0
  170. package/dist/cjs/mirroring/rtcp/sender-report.js +56 -0
  171. package/dist/cjs/mirroring/rtcp/sender-report.js.map +1 -0
  172. package/dist/cjs/mirroring/rtcp/wire.d.ts +54 -0
  173. package/dist/cjs/mirroring/rtcp/wire.js +73 -0
  174. package/dist/cjs/mirroring/rtcp/wire.js.map +1 -0
  175. package/dist/cjs/mirroring/rtp/frame-crypto.d.ts +11 -0
  176. package/dist/cjs/mirroring/rtp/frame-crypto.js +39 -0
  177. package/dist/cjs/mirroring/rtp/frame-crypto.js.map +1 -0
  178. package/dist/cjs/mirroring/rtp/frame.d.ts +23 -0
  179. package/dist/cjs/mirroring/rtp/frame.js +3 -0
  180. package/dist/cjs/mirroring/rtp/frame.js.map +1 -0
  181. package/dist/cjs/mirroring/rtp/packetizer.d.ts +27 -0
  182. package/dist/cjs/mirroring/rtp/packetizer.js +92 -0
  183. package/dist/cjs/mirroring/rtp/packetizer.js.map +1 -0
  184. package/dist/cjs/mirroring/sender/audio-sender.d.ts +23 -0
  185. package/dist/cjs/mirroring/sender/audio-sender.js +52 -0
  186. package/dist/cjs/mirroring/sender/audio-sender.js.map +1 -0
  187. package/dist/cjs/mirroring/sender/bandwidth-estimator.d.ts +26 -0
  188. package/dist/cjs/mirroring/sender/bandwidth-estimator.js +107 -0
  189. package/dist/cjs/mirroring/sender/bandwidth-estimator.js.map +1 -0
  190. package/dist/cjs/mirroring/sender/capture-size-oracle.d.ts +121 -0
  191. package/dist/cjs/mirroring/sender/capture-size-oracle.js +440 -0
  192. package/dist/cjs/mirroring/sender/capture-size-oracle.js.map +1 -0
  193. package/dist/cjs/mirroring/sender/frame-sender.d.ts +103 -0
  194. package/dist/cjs/mirroring/sender/frame-sender.js +217 -0
  195. package/dist/cjs/mirroring/sender/frame-sender.js.map +1 -0
  196. package/dist/cjs/mirroring/sender/packet-router.d.ts +74 -0
  197. package/dist/cjs/mirroring/sender/packet-router.js +196 -0
  198. package/dist/cjs/mirroring/sender/packet-router.js.map +1 -0
  199. package/dist/cjs/mirroring/sender/sender-session.d.ts +85 -0
  200. package/dist/cjs/mirroring/sender/sender-session.js +240 -0
  201. package/dist/cjs/mirroring/sender/sender-session.js.map +1 -0
  202. package/dist/cjs/mirroring/sender/sender.d.ts +120 -0
  203. package/dist/cjs/mirroring/sender/sender.js +457 -0
  204. package/dist/cjs/mirroring/sender/sender.js.map +1 -0
  205. package/dist/cjs/mirroring/sender/video-encoder-metrics.d.ts +29 -0
  206. package/dist/cjs/mirroring/sender/video-encoder-metrics.js +64 -0
  207. package/dist/cjs/mirroring/sender/video-encoder-metrics.js.map +1 -0
  208. package/dist/cjs/mirroring/sender/video-sender.d.ts +95 -0
  209. package/dist/cjs/mirroring/sender/video-sender.js +183 -0
  210. package/dist/cjs/mirroring/sender/video-sender.js.map +1 -0
  211. package/dist/cjs/mirroring/session-host.d.ts +185 -0
  212. package/dist/cjs/mirroring/session-host.js +630 -0
  213. package/dist/cjs/mirroring/session-host.js.map +1 -0
  214. package/dist/cjs/mirroring/stats/clock-offset-estimator.d.ts +11 -0
  215. package/dist/cjs/mirroring/stats/clock-offset-estimator.js +123 -0
  216. package/dist/cjs/mirroring/stats/clock-offset-estimator.js.map +1 -0
  217. package/dist/cjs/mirroring/stats/openscreen-stats-client.d.ts +12 -0
  218. package/dist/cjs/mirroring/stats/openscreen-stats-client.js +21 -0
  219. package/dist/cjs/mirroring/stats/openscreen-stats-client.js.map +1 -0
  220. package/dist/cjs/mirroring/stats/sorted-map.d.ts +23 -0
  221. package/dist/cjs/mirroring/stats/sorted-map.js +70 -0
  222. package/dist/cjs/mirroring/stats/sorted-map.js.map +1 -0
  223. package/dist/cjs/mirroring/stats/statistics-analyzer.d.ts +50 -0
  224. package/dist/cjs/mirroring/stats/statistics-analyzer.js +339 -0
  225. package/dist/cjs/mirroring/stats/statistics-analyzer.js.map +1 -0
  226. package/dist/cjs/mirroring/stats/statistics-collector.d.ts +29 -0
  227. package/dist/cjs/mirroring/stats/statistics-collector.js +53 -0
  228. package/dist/cjs/mirroring/stats/statistics-collector.js.map +1 -0
  229. package/dist/cjs/mirroring/stats/statistics-common.d.ts +61 -0
  230. package/dist/cjs/mirroring/stats/statistics-common.js +45 -0
  231. package/dist/cjs/mirroring/stats/statistics-common.js.map +1 -0
  232. package/dist/cjs/mirroring/stats/statistics-dispatcher.d.ts +28 -0
  233. package/dist/cjs/mirroring/stats/statistics-dispatcher.js +104 -0
  234. package/dist/cjs/mirroring/stats/statistics-dispatcher.js.map +1 -0
  235. package/dist/cjs/mirroring/stats/statistics.d.ts +84 -0
  236. package/dist/cjs/mirroring/stats/statistics.js +147 -0
  237. package/dist/cjs/mirroring/stats/statistics.js.map +1 -0
  238. package/dist/cjs/mirroring/transport/udp-environment.d.ts +40 -0
  239. package/dist/cjs/mirroring/transport/udp-environment.js +97 -0
  240. package/dist/cjs/mirroring/transport/udp-environment.js.map +1 -0
  241. package/dist/cjs/polyfill/bridge-types.d.ts +11 -0
  242. package/dist/cjs/polyfill/presentation-receiver.d.ts +12 -0
  243. package/dist/cjs/polyfill/presentation-receiver.js +369 -0
  244. package/dist/cjs/polyfill/presentation-receiver.js.map +1 -0
  245. package/dist/cjs/polyfill/presentation-standin.js +157 -15
  246. package/dist/cjs/polyfill/presentation-standin.js.map +1 -1
  247. package/dist/cjs/protocol/framing.d.ts +1 -1
  248. package/dist/cjs/protocol/framing.js +1 -1
  249. package/dist/cjs/protocol/framing.js.map +1 -1
  250. package/dist/cli.d.ts +2 -0
  251. package/dist/cli.js +56 -0
  252. package/dist/cli.js.map +1 -0
  253. package/dist/client/auth/build-time.js +1 -1
  254. package/dist/client/auth/cast-auth.d.ts +2 -0
  255. package/dist/client/auth/cast-auth.js.map +1 -1
  256. package/dist/dial/dial-registry.d.ts +104 -0
  257. package/dist/dial/dial-registry.js +297 -0
  258. package/dist/dial/dial-registry.js.map +1 -0
  259. package/dist/dial/dial-sink-service.d.ts +108 -0
  260. package/dist/dial/dial-sink-service.js +310 -0
  261. package/dist/dial/dial-sink-service.js.map +1 -0
  262. package/dist/dial/http.d.ts +40 -0
  263. package/dist/dial/http.js +165 -0
  264. package/dist/dial/http.js.map +1 -0
  265. package/dist/dial/index.d.ts +63 -0
  266. package/dist/dial/index.js +115 -0
  267. package/dist/dial/index.js.map +1 -0
  268. package/dist/dial/origins.d.ts +4 -0
  269. package/dist/dial/origins.js +32 -0
  270. package/dist/dial/origins.js.map +1 -0
  271. package/dist/dial/parse.d.ts +101 -0
  272. package/dist/dial/parse.js +281 -0
  273. package/dist/dial/parse.js.map +1 -0
  274. package/dist/dial/route-provider.d.ts +96 -0
  275. package/dist/dial/route-provider.js +369 -0
  276. package/dist/dial/route-provider.js.map +1 -0
  277. package/dist/dial/ssdp-socket.d.ts +34 -0
  278. package/dist/dial/ssdp-socket.js +65 -0
  279. package/dist/dial/ssdp-socket.js.map +1 -0
  280. package/dist/dial/xml.d.ts +13 -0
  281. package/dist/dial/xml.js +204 -0
  282. package/dist/dial/xml.js.map +1 -0
  283. package/dist/dial-test/cli-main.d.ts +17 -0
  284. package/dist/dial-test/cli-main.js +130 -0
  285. package/dist/dial-test/cli-main.js.map +1 -0
  286. package/dist/dial-test/report.d.ts +55 -0
  287. package/dist/dial-test/report.js +77 -0
  288. package/dist/dial-test/report.js.map +1 -0
  289. package/dist/dial-test/runner.d.ts +42 -0
  290. package/dist/dial-test/runner.js +566 -0
  291. package/dist/dial-test/runner.js.map +1 -0
  292. package/dist/dial-test/scrub.d.ts +14 -0
  293. package/dist/dial-test/scrub.js +73 -0
  294. package/dist/dial-test/scrub.js.map +1 -0
  295. package/dist/discovery/cast-discovery.d.ts +2 -0
  296. package/dist/discovery/cast-discovery.js.map +1 -1
  297. package/dist/discovery/device-cache.d.ts +9 -0
  298. package/dist/discovery/device-cache.js.map +1 -1
  299. package/dist/discovery/index.d.ts +1 -0
  300. package/dist/discovery/index.js +1 -0
  301. package/dist/discovery/index.js.map +1 -1
  302. package/dist/discovery/ip-policy.d.ts +20 -0
  303. package/dist/discovery/ip-policy.js +103 -0
  304. package/dist/discovery/ip-policy.js.map +1 -0
  305. package/dist/discovery/udp-socket.d.ts +3 -0
  306. package/dist/discovery/udp-socket.js +3 -0
  307. package/dist/discovery/udp-socket.js.map +1 -1
  308. package/dist/electron/access-code.d.ts +221 -0
  309. package/dist/electron/access-code.js +577 -0
  310. package/dist/electron/access-code.js.map +1 -0
  311. package/dist/electron/app-discovery.d.ts +82 -0
  312. package/dist/electron/app-discovery.js +215 -0
  313. package/dist/electron/app-discovery.js.map +1 -0
  314. package/dist/electron/default-presentation.d.ts +38 -0
  315. package/dist/electron/default-presentation.js +83 -0
  316. package/dist/electron/default-presentation.js.map +1 -0
  317. package/dist/electron/main.d.ts +98 -11
  318. package/dist/electron/main.js +597 -21
  319. package/dist/electron/main.js.map +1 -1
  320. package/dist/electron/manager-api.d.ts +200 -18
  321. package/dist/electron/manager-api.js +196 -4
  322. package/dist/electron/manager-api.js.map +1 -1
  323. package/dist/electron/media-controller.d.ts +79 -0
  324. package/dist/electron/media-controller.js +248 -0
  325. package/dist/electron/media-controller.js.map +1 -0
  326. package/dist/electron/network-monitor.d.ts +61 -0
  327. package/dist/electron/network-monitor.js +117 -0
  328. package/dist/electron/network-monitor.js.map +1 -0
  329. package/dist/electron/preload.js.map +1 -1
  330. package/dist/electron/presentation-handler.d.ts +39 -4
  331. package/dist/electron/presentation-handler.js +192 -48
  332. package/dist/electron/presentation-handler.js.map +1 -1
  333. package/dist/electron/presentation-source.d.ts +76 -0
  334. package/dist/electron/presentation-source.js +125 -0
  335. package/dist/electron/presentation-source.js.map +1 -0
  336. package/dist/electron/session-service.d.ts +198 -24
  337. package/dist/electron/session-service.js +629 -248
  338. package/dist/electron/session-service.js.map +1 -1
  339. package/dist/electron/session-tracker.d.ts +82 -0
  340. package/dist/electron/session-tracker.js +219 -0
  341. package/dist/electron/session-tracker.js.map +1 -0
  342. package/dist/electron/sink-service.d.ts +246 -0
  343. package/dist/electron/sink-service.js +602 -0
  344. package/dist/electron/sink-service.js.map +1 -0
  345. package/dist/electron/wired-display/controller.d.ts +76 -0
  346. package/dist/electron/wired-display/controller.js +194 -0
  347. package/dist/electron/wired-display/controller.js.map +1 -0
  348. package/dist/electron/wired-display/displays.d.ts +44 -0
  349. package/dist/electron/wired-display/displays.js +91 -0
  350. package/dist/electron/wired-display/displays.js.map +1 -0
  351. package/dist/electron/wired-display/electron-windows.d.ts +111 -0
  352. package/dist/electron/wired-display/electron-windows.js +301 -0
  353. package/dist/electron/wired-display/electron-windows.js.map +1 -0
  354. package/dist/electron/wired-display/index.d.ts +90 -0
  355. package/dist/electron/wired-display/index.js +99 -0
  356. package/dist/electron/wired-display/index.js.map +1 -0
  357. package/dist/electron/wired-display/local-presentation.d.ts +98 -0
  358. package/dist/electron/wired-display/local-presentation.js +228 -0
  359. package/dist/electron/wired-display/local-presentation.js.map +1 -0
  360. package/dist/electron/wired-display/provider.d.ts +112 -0
  361. package/dist/electron/wired-display/provider.js +197 -0
  362. package/dist/electron/wired-display/provider.js.map +1 -0
  363. package/dist/index.d.ts +1 -0
  364. package/dist/index.js +1 -0
  365. package/dist/index.js.map +1 -1
  366. package/dist/mirroring/backend.d.ts +76 -0
  367. package/dist/mirroring/backend.js +18 -0
  368. package/dist/mirroring/backend.js.map +1 -0
  369. package/dist/mirroring/electron/agent-protocol.d.ts +158 -0
  370. package/dist/mirroring/electron/agent-protocol.js +10 -0
  371. package/dist/mirroring/electron/agent-protocol.js.map +1 -0
  372. package/dist/mirroring/electron/agent-source.d.ts +20 -0
  373. package/dist/mirroring/electron/agent-source.js +618 -0
  374. package/dist/mirroring/electron/agent-source.js.map +1 -0
  375. package/dist/mirroring/electron/engine-process.d.ts +87 -0
  376. package/dist/mirroring/electron/engine-process.js +78 -0
  377. package/dist/mirroring/electron/engine-process.js.map +1 -0
  378. package/dist/mirroring/electron/host.d.ts +89 -0
  379. package/dist/mirroring/electron/host.js +318 -0
  380. package/dist/mirroring/electron/host.js.map +1 -0
  381. package/dist/mirroring/electron/port-backend.d.ts +107 -0
  382. package/dist/mirroring/electron/port-backend.js +441 -0
  383. package/dist/mirroring/electron/port-backend.js.map +1 -0
  384. package/dist/mirroring/encoding-support.d.ts +66 -0
  385. package/dist/mirroring/encoding-support.js +81 -0
  386. package/dist/mirroring/encoding-support.js.map +1 -0
  387. package/dist/mirroring/engine.d.ts +16 -0
  388. package/dist/mirroring/engine.js +75 -0
  389. package/dist/mirroring/engine.js.map +1 -0
  390. package/dist/mirroring/mirror-settings.d.ts +101 -0
  391. package/dist/mirroring/mirror-settings.js +134 -0
  392. package/dist/mirroring/mirror-settings.js.map +1 -0
  393. package/dist/mirroring/mirroring-activity.d.ts +207 -0
  394. package/dist/mirroring/mirroring-activity.js +362 -0
  395. package/dist/mirroring/mirroring-activity.js.map +1 -0
  396. package/dist/mirroring/mirroring-manager.d.ts +134 -0
  397. package/dist/mirroring/mirroring-manager.js +281 -0
  398. package/dist/mirroring/mirroring-manager.js.map +1 -0
  399. package/dist/mirroring/protocol/answer.d.ts +87 -0
  400. package/dist/mirroring/protocol/answer.js +226 -0
  401. package/dist/mirroring/protocol/answer.js.map +1 -0
  402. package/dist/mirroring/protocol/constants.d.ts +64 -0
  403. package/dist/mirroring/protocol/constants.js +66 -0
  404. package/dist/mirroring/protocol/constants.js.map +1 -0
  405. package/dist/mirroring/protocol/errors.d.ts +25 -0
  406. package/dist/mirroring/protocol/errors.js +29 -0
  407. package/dist/mirroring/protocol/errors.js.map +1 -0
  408. package/dist/mirroring/protocol/frame-id.d.ts +9 -0
  409. package/dist/mirroring/protocol/frame-id.js +20 -0
  410. package/dist/mirroring/protocol/frame-id.js.map +1 -0
  411. package/dist/mirroring/protocol/messenger.d.ts +42 -0
  412. package/dist/mirroring/protocol/messenger.js +118 -0
  413. package/dist/mirroring/protocol/messenger.js.map +1 -0
  414. package/dist/mirroring/protocol/offer.d.ts +109 -0
  415. package/dist/mirroring/protocol/offer.js +176 -0
  416. package/dist/mirroring/protocol/offer.js.map +1 -0
  417. package/dist/mirroring/protocol/recommendations.d.ts +28 -0
  418. package/dist/mirroring/protocol/recommendations.js +99 -0
  419. package/dist/mirroring/protocol/recommendations.js.map +1 -0
  420. package/dist/mirroring/routing.d.ts +60 -0
  421. package/dist/mirroring/routing.js +130 -0
  422. package/dist/mirroring/routing.js.map +1 -0
  423. package/dist/mirroring/rtcp/ntp.d.ts +27 -0
  424. package/dist/mirroring/rtcp/ntp.js +57 -0
  425. package/dist/mirroring/rtcp/ntp.js.map +1 -0
  426. package/dist/mirroring/rtcp/parser.d.ts +50 -0
  427. package/dist/mirroring/rtcp/parser.js +265 -0
  428. package/dist/mirroring/rtcp/parser.js.map +1 -0
  429. package/dist/mirroring/rtcp/sender-report.d.ts +32 -0
  430. package/dist/mirroring/rtcp/sender-report.js +51 -0
  431. package/dist/mirroring/rtcp/sender-report.js.map +1 -0
  432. package/dist/mirroring/rtcp/wire.d.ts +54 -0
  433. package/dist/mirroring/rtcp/wire.js +68 -0
  434. package/dist/mirroring/rtcp/wire.js.map +1 -0
  435. package/dist/mirroring/rtp/frame-crypto.d.ts +11 -0
  436. package/dist/mirroring/rtp/frame-crypto.js +35 -0
  437. package/dist/mirroring/rtp/frame-crypto.js.map +1 -0
  438. package/dist/mirroring/rtp/frame.d.ts +23 -0
  439. package/dist/mirroring/rtp/frame.js +2 -0
  440. package/dist/mirroring/rtp/frame.js.map +1 -0
  441. package/dist/mirroring/rtp/packetizer.d.ts +27 -0
  442. package/dist/mirroring/rtp/packetizer.js +88 -0
  443. package/dist/mirroring/rtp/packetizer.js.map +1 -0
  444. package/dist/mirroring/sender/audio-sender.d.ts +23 -0
  445. package/dist/mirroring/sender/audio-sender.js +54 -0
  446. package/dist/mirroring/sender/audio-sender.js.map +1 -0
  447. package/dist/mirroring/sender/bandwidth-estimator.d.ts +26 -0
  448. package/dist/mirroring/sender/bandwidth-estimator.js +103 -0
  449. package/dist/mirroring/sender/bandwidth-estimator.js.map +1 -0
  450. package/dist/mirroring/sender/capture-size-oracle.d.ts +121 -0
  451. package/dist/mirroring/sender/capture-size-oracle.js +433 -0
  452. package/dist/mirroring/sender/capture-size-oracle.js.map +1 -0
  453. package/dist/mirroring/sender/frame-sender.d.ts +103 -0
  454. package/dist/mirroring/sender/frame-sender.js +212 -0
  455. package/dist/mirroring/sender/frame-sender.js.map +1 -0
  456. package/dist/mirroring/sender/packet-router.d.ts +74 -0
  457. package/dist/mirroring/sender/packet-router.js +191 -0
  458. package/dist/mirroring/sender/packet-router.js.map +1 -0
  459. package/dist/mirroring/sender/sender-session.d.ts +85 -0
  460. package/dist/mirroring/sender/sender-session.js +235 -0
  461. package/dist/mirroring/sender/sender-session.js.map +1 -0
  462. package/dist/mirroring/sender/sender.d.ts +120 -0
  463. package/dist/mirroring/sender/sender.js +452 -0
  464. package/dist/mirroring/sender/sender.js.map +1 -0
  465. package/dist/mirroring/sender/video-encoder-metrics.d.ts +29 -0
  466. package/dist/mirroring/sender/video-encoder-metrics.js +58 -0
  467. package/dist/mirroring/sender/video-encoder-metrics.js.map +1 -0
  468. package/dist/mirroring/sender/video-sender.d.ts +95 -0
  469. package/dist/mirroring/sender/video-sender.js +190 -0
  470. package/dist/mirroring/sender/video-sender.js.map +1 -0
  471. package/dist/mirroring/session-host.d.ts +185 -0
  472. package/dist/mirroring/session-host.js +625 -0
  473. package/dist/mirroring/session-host.js.map +1 -0
  474. package/dist/mirroring/stats/clock-offset-estimator.d.ts +11 -0
  475. package/dist/mirroring/stats/clock-offset-estimator.js +120 -0
  476. package/dist/mirroring/stats/clock-offset-estimator.js.map +1 -0
  477. package/dist/mirroring/stats/openscreen-stats-client.d.ts +12 -0
  478. package/dist/mirroring/stats/openscreen-stats-client.js +17 -0
  479. package/dist/mirroring/stats/openscreen-stats-client.js.map +1 -0
  480. package/dist/mirroring/stats/sorted-map.d.ts +23 -0
  481. package/dist/mirroring/stats/sorted-map.js +66 -0
  482. package/dist/mirroring/stats/sorted-map.js.map +1 -0
  483. package/dist/mirroring/stats/statistics-analyzer.d.ts +50 -0
  484. package/dist/mirroring/stats/statistics-analyzer.js +335 -0
  485. package/dist/mirroring/stats/statistics-analyzer.js.map +1 -0
  486. package/dist/mirroring/stats/statistics-collector.d.ts +29 -0
  487. package/dist/mirroring/stats/statistics-collector.js +49 -0
  488. package/dist/mirroring/stats/statistics-collector.js.map +1 -0
  489. package/dist/mirroring/stats/statistics-common.d.ts +61 -0
  490. package/dist/mirroring/stats/statistics-common.js +39 -0
  491. package/dist/mirroring/stats/statistics-common.js.map +1 -0
  492. package/dist/mirroring/stats/statistics-dispatcher.d.ts +28 -0
  493. package/dist/mirroring/stats/statistics-dispatcher.js +100 -0
  494. package/dist/mirroring/stats/statistics-dispatcher.js.map +1 -0
  495. package/dist/mirroring/stats/statistics.d.ts +84 -0
  496. package/dist/mirroring/stats/statistics.js +141 -0
  497. package/dist/mirroring/stats/statistics.js.map +1 -0
  498. package/dist/mirroring/transport/udp-environment.d.ts +40 -0
  499. package/dist/mirroring/transport/udp-environment.js +93 -0
  500. package/dist/mirroring/transport/udp-environment.js.map +1 -0
  501. package/dist/polyfill/bridge-types.d.ts +11 -0
  502. package/dist/polyfill/presentation-receiver.d.ts +12 -0
  503. package/dist/polyfill/presentation-receiver.js +366 -0
  504. package/dist/polyfill/presentation-receiver.js.map +1 -0
  505. package/dist/polyfill/presentation-standin.js +157 -15
  506. package/dist/polyfill/presentation-standin.js.map +1 -1
  507. package/dist/protocol/framing.d.ts +1 -1
  508. package/dist/protocol/framing.js +1 -1
  509. package/dist/protocol/framing.js.map +1 -1
  510. package/docs/API.md +724 -0
  511. package/docs/ARCHITECTURE.md +242 -0
  512. package/docs/CHROMIUM-MAP.md +176 -0
  513. package/docs/DESIGN.md +1189 -0
  514. package/docs/FAQ.md +123 -0
  515. package/docs/GETTING-STARTED.md +248 -0
  516. package/docs/MAIN-API.md +524 -0
  517. package/docs/TROUBLESHOOTING.md +283 -0
  518. package/docs/guides/audio-and-groups.md +75 -0
  519. package/docs/guides/custom-receivers.md +109 -0
  520. package/docs/guides/device-authentication.md +145 -0
  521. package/docs/guides/device-picker.md +176 -0
  522. package/docs/guides/index.md +17 -0
  523. package/docs/guides/low-level-client.md +103 -0
  524. package/docs/guides/restart-rejoin.md +172 -0
  525. package/docs/guides/testing.md +162 -0
  526. package/docs/guides/windows-and-iframes.md +116 -0
  527. package/docs/readme/badges/dependencies.svg +1 -0
  528. package/docs/readme/badges/electron.svg +1 -0
  529. package/docs/readme/badges/license.svg +1 -0
  530. package/docs/readme/badges/node.svg +1 -0
  531. package/docs/readme/board.jpg +0 -0
  532. package/docs/readme/hero-dark.jpg +0 -0
  533. package/docs/readme/hero-light.jpg +0 -0
  534. package/docs/readme/nosignal.jpg +0 -0
  535. package/docs/readme/parity.jpg +0 -0
  536. package/docs/readme/trace.svg +22 -0
  537. package/package.json +21 -5
  538. package/src/cli.ts +57 -0
  539. package/src/client/auth/cast-auth.ts +2 -0
  540. package/src/dial/dial-registry.ts +316 -0
  541. package/src/dial/dial-sink-service.ts +343 -0
  542. package/src/dial/http.ts +200 -0
  543. package/src/dial/index.ts +135 -0
  544. package/src/dial/origins.ts +31 -0
  545. package/src/dial/parse.ts +319 -0
  546. package/src/dial/route-provider.ts +429 -0
  547. package/src/dial/ssdp-socket.ts +79 -0
  548. package/src/dial/xml.ts +180 -0
  549. package/src/dial-test/cli-main.ts +146 -0
  550. package/src/dial-test/report.ts +109 -0
  551. package/src/dial-test/runner.ts +615 -0
  552. package/src/dial-test/scrub.ts +74 -0
  553. package/src/discovery/cast-discovery.ts +2 -0
  554. package/src/discovery/device-cache.ts +5 -0
  555. package/src/discovery/index.ts +1 -0
  556. package/src/discovery/ip-policy.ts +97 -0
  557. package/src/discovery/udp-socket.ts +3 -0
  558. package/src/electron/access-code.ts +681 -0
  559. package/src/electron/app-discovery.ts +244 -0
  560. package/src/electron/default-presentation.ts +104 -0
  561. package/src/electron/main.ts +664 -29
  562. package/src/electron/manager-api.ts +367 -15
  563. package/src/electron/media-controller.ts +313 -0
  564. package/src/electron/network-monitor.ts +140 -0
  565. package/src/electron/preload.ts +1 -1
  566. package/src/electron/presentation-handler.ts +195 -48
  567. package/src/electron/presentation-source.ts +155 -0
  568. package/src/electron/session-service.ts +693 -238
  569. package/src/electron/session-tracker.ts +248 -0
  570. package/src/electron/sink-service.ts +726 -0
  571. package/src/electron/wired-display/controller.ts +212 -0
  572. package/src/electron/wired-display/displays.ts +107 -0
  573. package/src/electron/wired-display/electron-windows.ts +386 -0
  574. package/src/electron/wired-display/index.ts +181 -0
  575. package/src/electron/wired-display/local-presentation.ts +286 -0
  576. package/src/electron/wired-display/provider.ts +276 -0
  577. package/src/index.ts +1 -0
  578. package/src/mirroring/backend.ts +103 -0
  579. package/src/mirroring/electron/agent-protocol.ts +84 -0
  580. package/src/mirroring/electron/agent-source.ts +619 -0
  581. package/src/mirroring/electron/engine-process.ts +131 -0
  582. package/src/mirroring/electron/host.ts +361 -0
  583. package/src/mirroring/electron/port-backend.ts +466 -0
  584. package/src/mirroring/encoding-support.ts +146 -0
  585. package/src/mirroring/engine.ts +91 -0
  586. package/src/mirroring/mirror-settings.ts +174 -0
  587. package/src/mirroring/mirroring-activity.ts +466 -0
  588. package/src/mirroring/mirroring-manager.ts +342 -0
  589. package/src/mirroring/protocol/answer.ts +285 -0
  590. package/src/mirroring/protocol/constants.ts +75 -0
  591. package/src/mirroring/protocol/errors.ts +36 -0
  592. package/src/mirroring/protocol/frame-id.ts +20 -0
  593. package/src/mirroring/protocol/messenger.ts +128 -0
  594. package/src/mirroring/protocol/offer.ts +275 -0
  595. package/src/mirroring/protocol/recommendations.ts +135 -0
  596. package/src/mirroring/routing.ts +160 -0
  597. package/src/mirroring/rtcp/ntp.ts +61 -0
  598. package/src/mirroring/rtcp/parser.ts +292 -0
  599. package/src/mirroring/rtcp/sender-report.ts +88 -0
  600. package/src/mirroring/rtcp/wire.ts +76 -0
  601. package/src/mirroring/rtp/frame-crypto.ts +38 -0
  602. package/src/mirroring/rtp/frame.ts +25 -0
  603. package/src/mirroring/rtp/packetizer.ts +95 -0
  604. package/src/mirroring/sender/audio-sender.ts +59 -0
  605. package/src/mirroring/sender/bandwidth-estimator.ts +111 -0
  606. package/src/mirroring/sender/capture-size-oracle.ts +476 -0
  607. package/src/mirroring/sender/frame-sender.ts +293 -0
  608. package/src/mirroring/sender/packet-router.ts +228 -0
  609. package/src/mirroring/sender/sender-session.ts +306 -0
  610. package/src/mirroring/sender/sender.ts +497 -0
  611. package/src/mirroring/sender/video-encoder-metrics.ts +64 -0
  612. package/src/mirroring/sender/video-sender.ts +243 -0
  613. package/src/mirroring/session-host.ts +725 -0
  614. package/src/mirroring/stats/clock-offset-estimator.ts +139 -0
  615. package/src/mirroring/stats/openscreen-stats-client.ts +19 -0
  616. package/src/mirroring/stats/sorted-map.ts +68 -0
  617. package/src/mirroring/stats/statistics-analyzer.ts +388 -0
  618. package/src/mirroring/stats/statistics-collector.ts +69 -0
  619. package/src/mirroring/stats/statistics-common.ts +112 -0
  620. package/src/mirroring/stats/statistics-dispatcher.ts +133 -0
  621. package/src/mirroring/stats/statistics.ts +170 -0
  622. package/src/mirroring/transport/udp-environment.ts +100 -0
  623. package/src/polyfill/bridge-types.ts +11 -0
  624. package/src/polyfill/presentation-receiver.ts +350 -0
  625. package/src/polyfill/presentation-standin.ts +147 -15
  626. package/src/protocol/framing.ts +1 -1
@@ -1,10 +1,19 @@
1
1
  import type { BridgeEvent, BridgeResult, SessionSnapshot, VolumeSnapshot } from "../polyfill/bridge-types.ts";
2
+ import type { WiredDisplaySink } from "./wired-display/displays.ts";
2
3
  import type { CastDevice } from "../discovery/index.ts";
3
4
  import type { ReceiverApplication, ReceiverStatus, ReceiverVolume } from "../client/index.ts";
4
5
  import { CastTimeoutError } from "../client/index.ts";
5
6
  import {
6
- ObservedMap, createPickerContext, createSinksObservers, type DevicePickerContext, type MediaRoute,
7
+ ObservedMap, combineSources, createPickerContext, createSinksObservers, type DevicePickerContext, type MediaRoute,
7
8
  } from "./manager-api.ts";
9
+ import { CastSinkService, type ChannelParams, type CastSinkOptions } from "./sink-service.ts";
10
+ import type { NetworkMonitor } from "./network-monitor.ts";
11
+ import { CastSessionTracker, type TrackedSession } from "./session-tracker.ts";
12
+ import { CastAppDiscovery, type CastAppSource } from "./app-discovery.ts";
13
+ import { EventEmitter } from "node:events";
14
+ import {
15
+ AccessCodeSinks, type AccessCodeDevice, type AccessCodeOptions, type AccessCodeRememberedSink, type AddSinkResult,
16
+ } from "./access-code.ts";
8
17
 
9
18
  /** Capability bit names in bit order: 1 video_out, 2 video_in, 4 audio_out, 8 audio_in, 32 multizone_group. */
10
19
  export function capabilityNames(bits: number): string[] {
@@ -17,6 +26,8 @@ export function capabilityNames(bits: number): string[] {
17
26
  return names;
18
27
  }
19
28
 
29
+ export { APP_AVAILABILITY_REFRESH_MS } from "./app-discovery.ts";
30
+
20
31
  /** A source of known Cast devices and their change events. */
21
32
  export interface DeviceSource {
22
33
  devices(): CastDevice[];
@@ -26,7 +37,14 @@ export interface DeviceSource {
26
37
 
27
38
  /** The subset of {@link CastClient} used by the session service. */
28
39
  export interface CastClientLike {
40
+ /**
41
+ * The id this client puts in the source of its messages (`CastClient` has it). Mirroring needs it, to address the
42
+ * receiver's replies; a client without it cannot mirror.
43
+ */
44
+ readonly senderId?: string;
29
45
  readonly connected: boolean;
46
+ /** What device authentication found out, once connected (`CastClient.deviceAuth`); absent when the device was not verified. */
47
+ readonly deviceAuth?: { readonly policy: string } | undefined;
30
48
  connect(): Promise<void>;
31
49
  close(): void;
32
50
  send(namespace: string, destinationId: string, payload: string): void;
@@ -34,6 +52,8 @@ export interface CastClientLike {
34
52
  stop(sessionId: string): Promise<ReceiverStatus>;
35
53
  setVolume(volume: { level: number } | { muted: boolean }): Promise<ReceiverStatus>;
36
54
  getStatus(): Promise<ReceiverStatus>;
55
+ /** `GET_APP_AVAILABILITY`; a client without it is taken to have every app. */
56
+ getAppAvailability?(appIds: string[]): Promise<Record<string, boolean>>;
37
57
  connectTransport(transportId: string): void;
38
58
  closeTransport(transportId: string): void;
39
59
  on(event: "message", listener: (msg: ClientMessage) => void): unknown;
@@ -61,6 +81,17 @@ export interface CastRequestInfo {
61
81
  senderId: number;
62
82
  /** The sender's current session for this app, if it has one; the key is absent when it does not. */
63
83
  session?: { sessionId: string; deviceId: string };
84
+ /**
85
+ * Set when the page's request could also be shown on a display (its URLs mix a Cast app URL and a standard presentation
86
+ * source) and displays exist: Chrome's dialog lists both kinds of sink. Answer `{ display: <sink id> }` to pick one.
87
+ */
88
+ displays?: readonly WiredDisplaySink[];
89
+ }
90
+
91
+ /** A display chosen in a picker that also lists displays (see {@link CastRequestInfo.displays}). */
92
+ export interface DisplayChoice {
93
+ /** The id of one of `request.displays`. */
94
+ display: string;
64
95
  }
65
96
 
66
97
  /** The picker's answer: a device to cast to, `null` (cancel) or `"stop"` (stop the sender's current session). */
@@ -69,7 +100,11 @@ export type DeviceChoice = CastDevice | null | "stop";
69
100
  /** Dependencies and callbacks of {@link CastSessionService}. */
70
101
  export interface CastSessionServiceOptions {
71
102
  devices: DeviceSource;
72
- createClient(device: CastDevice): CastClientLike;
103
+ /**
104
+ * Make a client for a device. `params` carries the connect and liveness timeouts Chrome would use for this attempt
105
+ * (10 s; longer after failures only when `sinks.dynamicTimeoutDeltaMs` is set).
106
+ */
107
+ createClient(device: CastDevice, params: ChannelParams): CastClientLike;
73
108
  /**
74
109
  * Ask the user which device to cast to. Resolves a device, `null` (cancel) or
75
110
  * `"stop"` (stop `request.session`, the sender's current session, if it has one).
@@ -77,6 +112,53 @@ export interface CastSessionServiceOptions {
77
112
  selectDevice(devices: CastDevice[], request: CastRequestInfo, picker: DevicePickerContext): Promise<DeviceChoice>;
78
113
  allowOrigin?(origin: string): boolean;
79
114
  emit(senderId: number, event: BridgeEvent): void;
115
+ /** How channels to the devices are opened and retried; the defaults are Chrome's (see {@link CastSinkOptions}). */
116
+ sinks?: CastSinkOptions;
117
+ /**
118
+ * DIAL sinks for the picker (see `requestSink`) and for a page's availability. `source` announces their changes (as
119
+ * `deviceChanged`); `available` lists the sinks that have the app for a page at `origin`; `monitor` makes the sink
120
+ * service find out, until the returned function is called.
121
+ */
122
+ dial?: {
123
+ source: DeviceSource;
124
+ available(appName: string, origin: string): CastDevice[];
125
+ monitor(appName: string, origin: string): (() => void) | null;
126
+ };
127
+ /** Adding a device by address, as Chrome's access code casting adds one; off unless `enabled` (see {@link AccessCodeOptions}). */
128
+ accessCode?: AccessCodeOptions;
129
+ /** Network changes, which the sinks and the devices added by address follow (Chrome: `DiscoveryNetworkMonitor`). */
130
+ networkMonitor?: NetworkMonitor;
131
+ /**
132
+ * True for a session another local activity of this app holds (a mirroring route, or a device it is launching one on),
133
+ * so it is not reported as a non-local route (Chrome: `CastActivityManager` adds a non-local activity only for a
134
+ * session no local activity has).
135
+ */
136
+ ownsSession?(sessionId: string, sinkId: string): boolean;
137
+ /**
138
+ * A session was launched for `senderId` (`CastActivityManager::DoLaunchSession`, where a route from the frame is
139
+ * recorded in `routes_by_frame_`). Not called for a join, which Chrome does not record there.
140
+ */
141
+ onSessionLaunched?(senderId: number): void;
142
+ }
143
+
144
+ /** How long a request that finds no DIAL sink yet waits for the devices' app info (the dialog of Chrome waits for as long as it is open). */
145
+ const DIAL_PROBE_WAIT_MS = 5000;
146
+
147
+ /** Resolves when `done()` is true after a device change, or after `ms`. */
148
+ function waitForDevices(source: DeviceSource, ms: number, done: () => boolean): Promise<void> {
149
+ return new Promise<void>((resolve) => {
150
+ if (done()) return resolve();
151
+ const finish = (): void => {
152
+ clearTimeout(timer);
153
+ source.off("deviceChanged", onChange);
154
+ resolve();
155
+ };
156
+ const onChange = (): void => {
157
+ if (done()) finish();
158
+ };
159
+ const timer = setTimeout(finish, ms);
160
+ source.on("deviceChanged", onChange);
161
+ });
80
162
  }
81
163
 
82
164
  interface SenderRecord {
@@ -92,6 +174,8 @@ interface SessionRecord {
92
174
  origin: string;
93
175
  appId: string;
94
176
  members: Set<number>;
177
+ /** The sender that launched the session (Chrome's `routes_by_frame_` key); unset for a session found running. */
178
+ launchedBy?: number;
95
179
  /**
96
180
  * Senders whose page navigated away (a reload, say) while a member. Like Chrome's Media Router, the session outlives
97
181
  * the page: it stays open on the device so the sender's next page can rejoin it. Parked senders get no events.
@@ -110,15 +194,6 @@ interface PendingRequest {
110
194
  picker?: { close(): void };
111
195
  }
112
196
 
113
- interface ClientEntry {
114
- client: CastClientLike;
115
- device: CastDevice;
116
- /** Connect promise, created once; every openSession awaits it. */
117
- ready: Promise<void>;
118
- /** Number of in-flight openSession calls; cleanupIdle never closes while > 0. */
119
- opening: number;
120
- }
121
-
122
197
  const CAPABILITY_BITS: Record<string, number> = {
123
198
  video_out: 1,
124
199
  video_in: 2,
@@ -170,13 +245,42 @@ function parseInitialize(params: unknown): { appId: string; capabilities: string
170
245
  return { appId, capabilities, autoJoinPolicy };
171
246
  }
172
247
 
173
- function parseRequestSession(params: unknown): { appId: string; capabilities: string[]; timeoutMs: number } | null {
248
+ function parseRequestSession(params: unknown): { appId: string; capabilities: string[]; timeoutMs: number; appAvailability: boolean } | null {
174
249
  if (!isRecord(params)) return null;
175
250
  const { appId, capabilities, timeoutMs } = params;
176
251
  if (typeof appId !== "string" || !isStringArray(capabilities)) return null;
177
252
  const timeout = timeoutMs === undefined ? DEFAULT_TIMEOUT_MS : timeoutMs;
178
253
  if (typeof timeout !== "number" || !Number.isFinite(timeout) || timeout <= 0) return null;
179
- return { appId, capabilities, timeoutMs: timeout };
254
+ return { appId, capabilities, timeoutMs: timeout, appAvailability: params.appAvailability === true };
255
+ }
256
+
257
+ /** `requestSession`'s parameters as a picker request with no DIAL app. */
258
+ function parseRequestSessionParams(params: unknown): RequestParams | null {
259
+ const p = parseRequestSession(params);
260
+ return p === null ? null : { ...p, dialApp: null };
261
+ }
262
+
263
+ /** What a picker request asks for: a Cast app, a DIAL app (`requestSink` only), or both. */
264
+ interface RequestParams {
265
+ appId: string | null;
266
+ dialApp: string | null;
267
+ capabilities: string[];
268
+ timeoutMs: number;
269
+ /** Offer only the sinks that said they have the Cast app (a page's presentation request). */
270
+ appAvailability: boolean;
271
+ }
272
+
273
+ /** `requestSink` parameters: like `requestSession`'s, with the Cast app id optional and a DIAL app name. */
274
+ function parseRequestSink(params: unknown): RequestParams | null {
275
+ if (!isRecord(params)) return null;
276
+ const { appId, dialApp, capabilities, timeoutMs } = params;
277
+ if (appId !== null && typeof appId !== "string") return null;
278
+ if (dialApp !== null && typeof dialApp !== "string") return null;
279
+ if (appId === null && dialApp === null) return null;
280
+ if (!isStringArray(capabilities)) return null;
281
+ const timeout = timeoutMs === undefined ? DEFAULT_TIMEOUT_MS : timeoutMs;
282
+ if (typeof timeout !== "number" || !Number.isFinite(timeout) || timeout <= 0) return null;
283
+ return { appId, dialApp, capabilities, timeoutMs: timeout, appAvailability: params.appAvailability === true };
180
284
  }
181
285
 
182
286
  function parseSessionId(params: unknown): { sessionId: string } | null {
@@ -249,17 +353,121 @@ export class CastSessionService {
249
353
  private readonly sessions = new ObservedMap<string, SessionRecord>((kind, rec) => this.notifySession(kind, rec));
250
354
  private readonly sessionListeners = new Set<() => void>();
251
355
  private readonly sinks;
252
- private readonly clients = new Map<string, ClientEntry>();
356
+ /** The devices with an open channel; the only devices the service offers or casts to. */
357
+ private readonly sinkService: CastSinkService;
358
+ private readonly tracker = new CastSessionTracker();
359
+ private readonly accessCode: AccessCodeSinks;
360
+ private lastRoutesKey = "";
361
+ /** Devices a page's launch is in flight on, with how many: the session it starts is the page's, not a non-local one. */
362
+ private readonly launching = new Map<string, number>();
253
363
  private readonly pendingRequests = new Map<number, PendingRequest>();
254
364
  private readonly deviceListener = (): void => this.onDevicesChanged();
365
+ /** Which sinks have which apps, asked over their open channels (Chrome: CastAppDiscoveryServiceImpl). */
366
+ private readonly appDiscovery: CastAppDiscovery;
367
+ /** The availability observations that follow the DIAL sinks (see `watchDialSinks`). */
368
+ private readonly dialWatchers = new Set<() => void>();
369
+ private readonly onDialSinks = (): void => {
370
+ for (const watcher of [...this.dialWatchers]) watcher();
371
+ };
255
372
  private disposed = false;
373
+ private readonly unobserveNetwork: () => void;
256
374
 
257
375
  constructor(options: CastSessionServiceOptions) {
258
376
  this.options = options;
259
- this.sinks = createSinksObservers(options.devices);
260
- options.devices.on("deviceUp", this.deviceListener);
261
- options.devices.on("deviceDown", this.deviceListener);
262
- options.devices.on("deviceChanged", this.deviceListener);
377
+ this.sinkService = new CastSinkService({
378
+ ...options.sinks,
379
+ source: options.devices,
380
+ ...(options.dial !== undefined ? { dial: options.dial.source } : {}),
381
+ createClient: options.createClient,
382
+ isClientInUse: (client) => [...this.sessions.values()].some((rec) => rec.client === client),
383
+ });
384
+ this.sinks = createSinksObservers(this.sinkService);
385
+ this.appDiscovery = new CastAppDiscovery(this.sinkService);
386
+ this.sinkService.on("deviceUp", this.deviceListener);
387
+ this.sinkService.on("deviceDown", this.deviceListener);
388
+ this.sinkService.on("deviceChanged", this.deviceListener);
389
+ this.sinkService.on("channelOpened", ({ device, client }) => {
390
+ // The tracker goes first so that, when a status ends a session, it no longer lists it by the time this one reports.
391
+ this.tracker.attach(device.id, client);
392
+ this.bindClient(client, device);
393
+ });
394
+ // MediaSinkServiceBase::AddOrUpdateSink tells CastAppDiscoveryServiceImpl at once, not after the 3 s report
395
+ this.sinkService.on("channelOpened", ({ device }) => this.appDiscovery.onSinkAddedOrUpdated(device));
396
+ this.sinkService.on("sinkRemoved", (device) => {
397
+ this.tracker.removeSink(device.id);
398
+ this.appDiscovery.onSinkRemoved(device);
399
+ });
400
+ this.tracker.on("sessionAddedOrUpdated", () => this.onTrackerChanged());
401
+ this.tracker.on("sessionRemoved", () => this.onTrackerChanged());
402
+ this.accessCode = new AccessCodeSinks(
403
+ this.sinkService,
404
+ {
405
+ current: () => this.mediaRoutes().map((r) => ({ id: r.id, sinkId: r.sinkId, isLocal: r.isLocal })),
406
+ observe: (listener) => this.observeSessions(listener),
407
+ },
408
+ options.accessCode,
409
+ );
410
+ // The two observers of Chrome's DiscoveryNetworkMonitor; the sink service asks for the current id first (`Start`).
411
+ const monitor = options.networkMonitor;
412
+ if (monitor !== undefined) this.sinkService.onNetworksChanged(monitor.networkId());
413
+ this.unobserveNetwork = monitor?.observe((networkId) => {
414
+ this.sinkService.onNetworksChanged(networkId);
415
+ this.accessCode.onNetworksChanged(networkId);
416
+ }) ?? (() => {});
417
+ }
418
+
419
+ /** The devices that can be cast to: those with an open, authenticated channel (as Chrome lists sinks). */
420
+ devices(): CastDevice[] {
421
+ return this.sinkService.devices();
422
+ }
423
+
424
+ /** The devices as a {@link DeviceSource}: what `devices()` lists, with the events of that list changing. */
425
+ deviceSource(): DeviceSource {
426
+ return this.sinkService;
427
+ }
428
+
429
+ /**
430
+ * Open channels to the discovered devices that have none now, without Chrome's random delay, and ask the sinks again
431
+ * about the apps being observed, by the refresh rules (`CastMediaRouteProvider::DiscoverSinksNow` ->
432
+ * `CastAppDiscoveryServiceImpl::Refresh`).
433
+ */
434
+ discoverSinksNow(): void {
435
+ this.sinkService.discoverSinksNow();
436
+ this.appDiscovery.refresh();
437
+ }
438
+
439
+ /**
440
+ * The client of the device's open channel, which every activity on the device shares (Chrome: one `CastSocket` per
441
+ * sink, used by `CastMessageHandler` for every session); undefined when the device is not a sink now.
442
+ */
443
+ channelClient(deviceId: string): CastClientLike | undefined {
444
+ return this.sinkService.clientOf(deviceId);
445
+ }
446
+
447
+ /** Resolves when no channel is being opened and none is scheduled to be; for tests. */
448
+ settled(options?: { retries?: boolean }): Promise<void> {
449
+ // no extra wait when nothing is being read: callers of settled() depend on how soon it resolves
450
+ const reading = this.accessCode.ready();
451
+ return reading === undefined ? this.sinkService.settled(options) : reading.then(() => this.sinkService.settled(options));
452
+ }
453
+
454
+ /**
455
+ * Add a device whose address the app knows, as Chrome adds the one an access code resolved to: a channel is opened and
456
+ * the device is listed like any other, remembered for `accessCode.deviceDuration`, then removed. Rejects with
457
+ * `AccessCodeCastDisabledError` unless access code casting is enabled.
458
+ */
459
+ addSinkByAddress(device: AccessCodeDevice): Promise<AddSinkResult> {
460
+ return this.accessCode.addSinkByAddress(device);
461
+ }
462
+
463
+ /** Change `enabled` and `deviceDuration` while running, as Chrome applies its policies. */
464
+ configureAccessCode(settings: { enabled?: boolean; deviceDuration?: number }): Promise<void> {
465
+ return this.accessCode.configure(settings);
466
+ }
467
+
468
+ /** The devices added by address that are remembered now. */
469
+ rememberedSinks(): AccessCodeRememberedSink[] {
470
+ return this.accessCode.remembered();
263
471
  }
264
472
 
265
473
  /** Handle one bridge call; never throws or rejects. */
@@ -274,8 +482,17 @@ export class CastSessionService {
274
482
  return this.handleInitialize(sender, params);
275
483
  case "requestSession":
276
484
  return await this.handleRequestSession(sender, params);
485
+ case "requestSessionOnDevice":
486
+ // main only: the app's own UI chose the device (see the manager's startCasting)
487
+ return await this.handleRequestSession(sender, params, { presetDeviceId: isRecord(params) && typeof params.deviceId === "string" ? params.deviceId : "" });
277
488
  case "joinSession":
278
489
  return this.handleJoinSession(sender, params, true);
490
+ case "requestSink":
491
+ // main only: the presentation handler's request with a `cast-dial:` source
492
+ return await this.handleRequestSession(sender, params, {
493
+ sink: true,
494
+ ...(isRecord(params) && typeof params.deviceId === "string" ? { presetDeviceId: params.deviceId } : {}),
495
+ });
279
496
  case "joinRunningSession":
280
497
  return await this.handleJoinRunningSession(sender, params);
281
498
  case "sendMessage":
@@ -334,24 +551,159 @@ export class CastSessionService {
334
551
  async dispose(): Promise<void> {
335
552
  if (this.disposed) return;
336
553
  this.disposed = true;
554
+ this.unobserveNetwork();
337
555
  this.sinks.dispose();
338
- const d = this.options.devices;
339
- d.off("deviceUp", this.deviceListener);
340
- d.off("deviceDown", this.deviceListener);
341
- d.off("deviceChanged", this.deviceListener);
556
+ this.accessCode.dispose();
342
557
  for (const pending of this.pendingRequests.values()) pending.picker?.close();
343
- const entries = [...this.clients.values()];
344
- this.clients.clear();
345
- for (const entry of entries) entry.client.close();
346
558
  this.sessions.clear();
559
+ this.tracker.dispose();
560
+ this.appDiscovery.dispose();
561
+ this.sinkService.dispose();
347
562
  this.senders.clear();
348
563
  this.pendingRequests.clear();
349
564
  }
350
565
 
566
+ /**
567
+ * What the device said about the app (`GET_APP_AVAILABILITY`), or undefined when it has to be asked: never asked, no
568
+ * answer last time, or "unavailable" longer than `APP_AVAILABILITY_REFRESH_MS` ago. This is
569
+ * CastAppDiscoveryServiceImpl::ShouldRefreshAppAvailability: kAvailable is kept, kUnavailable is asked again after
570
+ * kRefreshThreshold, kUnknown always.
571
+ */
572
+ cachedAppAvailability(device: CastDevice, appId: string): boolean | undefined {
573
+ return this.appDiscovery.cached(device.id, appId);
574
+ }
575
+
576
+ /**
577
+ * Ask the device whether it has the app (`GET_APP_AVAILABILITY`) unless a still-valid answer is cached. An error or
578
+ * no answer is not cached (Chrome's kUnknown): this resolves false, and the next call asks again. Callers that ask on
579
+ * every change (sinks observers) must pace themselves; see createSinksObservers.
580
+ */
581
+ async checkAppAvailability(device: CastDevice, appId: string): Promise<boolean> {
582
+ // Asked over the device's kept-open channel (Chrome: the sink's CastSocket); no channel now is kUnknown. An answer
583
+ // about a channel that was replaced while it was asked is dropped, so it is unknown too.
584
+ await this.appDiscovery.request(device.id, appId);
585
+ return this.appDiscovery.availability(device.id, appId).result === "available";
586
+ }
587
+
588
+ /**
589
+ * A page's `PresentationRequest` availability (`getAvailability()`), as Chrome serves it: a
590
+ * `PresentationMediaSinksObserver` on the source, fed by `CastAppDiscoveryServiceImpl::StartObservingMediaSinks`, so
591
+ * a sink counts once it has said over its open channel that it has the app (`GET_APP_AVAILABILITY`). With `dialApp`
592
+ * (a `cast-dial:` source of the same request) the DIAL sinks that have that app for the page's origin count too, as
593
+ * Blink ORs the sources of a request; the DIAL sink service is asked to find out while the observation lasts.
594
+ * `available` is the first answer: at once from the answers that stand, else once the Cast sinks asked have answered
595
+ * (a sink that says yes answers it at once). `onchange` is called after that only when the answer changes, as
596
+ * `PresentationMediaSinksObserver::OnSinksReceived` skips a repeated one. `close()` stops the observation
597
+ * (`StopObservingMediaSinks`). A disallowed origin is never available.
598
+ */
599
+ observeAppAvailability(
600
+ sender: SenderInfo,
601
+ source: CastAppSource & { dialApp?: string },
602
+ onchange: (available: boolean) => void,
603
+ ): { available: Promise<boolean>; close(): void } {
604
+ const allow = this.options.allowOrigin;
605
+ if (this.disposed || (allow !== undefined && !allow(sender.origin))) return { available: Promise.resolve(false), close: () => {} };
606
+ const dialApp = source.dialApp;
607
+ const dial = dialApp !== undefined ? this.options.dial : undefined;
608
+ const castSource: CastAppSource = { appIds: source.appIds, capabilities: source.capabilities };
609
+ const hasCast = castSource.appIds.length > 0;
610
+ const anyAvailable = (): boolean =>
611
+ (hasCast && this.appDiscovery.availableSinks(castSource).length > 0)
612
+ || (dial !== undefined && dialApp !== undefined && dial.available(dialApp, sender.origin).length > 0);
613
+ let last: boolean | undefined;
614
+ let closed = false;
615
+ let first!: (value: boolean) => void;
616
+ const available = new Promise<boolean>((resolve) => (first = resolve));
617
+ const report = (value: boolean): void => {
618
+ if (closed || value === last) return;
619
+ const answered = last !== undefined;
620
+ last = value;
621
+ if (answered) onchange(value);
622
+ else first(value);
623
+ };
624
+ const stopCast = hasCast ? this.appDiscovery.startObserving(castSource, () => report(anyAvailable())) : () => {};
625
+ let stopDial = (): void => {};
626
+ if (dial !== undefined && dialApp !== undefined) {
627
+ const release = dial.monitor(dialApp, sender.origin) ?? (() => undefined);
628
+ // before the first answer only a yes is final; after it every change counts
629
+ const onDial = (): void => {
630
+ const value = anyAvailable();
631
+ if (last !== undefined || value) report(value);
632
+ };
633
+ const off = this.watchDialSinks(dial.source, onDial);
634
+ stopDial = () => {
635
+ off();
636
+ release();
637
+ };
638
+ if (anyAvailable()) report(true);
639
+ }
640
+ if (last === undefined) {
641
+ const ready = hasCast ? this.appDiscovery.settled(castSource) : Promise.resolve();
642
+ void ready.then(() => {
643
+ if (last === undefined) report(anyAvailable());
644
+ });
645
+ }
646
+ return {
647
+ available,
648
+ close: () => {
649
+ if (closed) return;
650
+ closed = true;
651
+ stopCast();
652
+ stopDial();
653
+ if (last === undefined) first(false);
654
+ },
655
+ };
656
+ }
657
+
658
+ /**
659
+ * One listener on the DIAL sinks for every availability observation: a page may hold many, and a listener each would
660
+ * trip EventEmitter's limit of ten.
661
+ */
662
+ private watchDialSinks(source: DeviceSource, callback: () => void): () => void {
663
+ if (this.dialWatchers.size === 0) source.on("deviceChanged", this.onDialSinks);
664
+ this.dialWatchers.add(callback);
665
+ return () => {
666
+ if (!this.dialWatchers.delete(callback)) return;
667
+ if (this.dialWatchers.size === 0) source.off("deviceChanged", this.onDialSinks);
668
+ };
669
+ }
670
+
671
+ /**
672
+ * The sinks a request for an app is offered, as Chrome's dialog and `StartPresentation` offer the sinks of the
673
+ * source: those that have the app. Observes the source until `close()`, so the picker sees the list change; the
674
+ * first list is waited for when no answer stands yet.
675
+ */
676
+ private async appSinks(source: CastAppSource): Promise<{
677
+ devices(): CastDevice[];
678
+ source: DeviceSource;
679
+ observers: ReturnType<typeof createSinksObservers>;
680
+ close(): void;
681
+ }> {
682
+ const events = new EventEmitter();
683
+ const devices = (): CastDevice[] => this.appDiscovery.availableSinks(source);
684
+ const stop = this.appDiscovery.startObserving(source, () => events.emit("deviceChanged"));
685
+ const sinks: DeviceSource = {
686
+ devices,
687
+ on: (e, l) => events.on(e, l),
688
+ off: (e, l) => events.off(e, l),
689
+ };
690
+ const observers = createSinksObservers(sinks);
691
+ if (devices().length === 0) await this.appDiscovery.settled(source);
692
+ return {
693
+ devices,
694
+ source: sinks,
695
+ observers,
696
+ close: () => {
697
+ observers.dispose();
698
+ stop();
699
+ },
700
+ };
701
+ }
702
+
351
703
  private handleInitialize(sender: SenderInfo, params: unknown): BridgeResult {
352
704
  const p = parseInitialize(params);
353
705
  if (p === null) return bad("invalid_parameter");
354
- const available = this.options.devices.devices().some((d) => deviceMatches(d, p.capabilities));
706
+ const available = this.sinkService.devices().some((d) => deviceMatches(d, p.capabilities));
355
707
  this.senders.set(sender.id, { appId: p.appId, capabilities: p.capabilities, lastAvailable: available });
356
708
  const joined: SessionSnapshot[] = [];
357
709
  for (const rec of this.sessions.values()) {
@@ -368,39 +720,86 @@ export class CastSessionService {
368
720
  return good({ available, sessions: joined });
369
721
  }
370
722
 
371
- private async handleRequestSession(sender: SenderInfo, params: unknown): Promise<BridgeResult> {
372
- const p = parseRequestSession(params);
723
+ /**
724
+ * `requestSession`; with `presetDeviceId` (`requestSessionOnDevice`) the picker is skipped: that device is the choice
725
+ * (and must still be eligible). With `sink` (`requestSink`) the request may name a DIAL app as well as, or instead
726
+ * of, a Cast app, and the picker is offered the DIAL sinks that have it too; a DIAL choice is returned as
727
+ * `{ dialSink }` and nothing is launched here (the presentation handler creates the DIAL route).
728
+ */
729
+ private async handleRequestSession(sender: SenderInfo, params: unknown, opts: { presetDeviceId?: string; sink?: boolean } = {}): Promise<BridgeResult> {
730
+ const presetDeviceId = opts.presetDeviceId;
731
+ const p: RequestParams | null = opts.sink === true ? parseRequestSink(params) : parseRequestSessionParams(params);
373
732
  if (p === null) return bad("invalid_parameter");
733
+ const appId = p.appId;
734
+ const dialApp = p.dialApp;
735
+ const capabilities = p.capabilities;
736
+ const dial = dialApp !== null ? this.options.dial : undefined;
737
+ const dialAvailable = (): CastDevice[] => (dial !== undefined && dialApp !== null ? dial.available(dialApp, sender.origin) : []);
374
738
  if (this.pendingRequests.has(sender.id)) return bad("invalid_parameter");
375
739
  const discard = { value: false };
376
740
  const cancelled = { value: false };
377
741
  const pending: PendingRequest = { discard, cancelled };
378
742
  this.pendingRequests.set(sender.id, pending);
743
+ // Chrome's dialog starts observing the sinks of the source when it opens (StartObservingMediaSinks), and the
744
+ // observer then waits for the answers; so the DIAL monitor starts before the first look, and a request with no sink
745
+ // yet waits a while for the devices' app info instead of failing on a page that never watched availability.
746
+ const stopMonitoring = dial !== undefined && dialApp !== null ? dial.monitor(dialApp, sender.origin) ?? undefined : undefined;
747
+ let appSinks: Awaited<ReturnType<CastSessionService["appSinks"]>> | undefined;
748
+ let combined: ReturnType<typeof createSinksObservers> | undefined;
379
749
  try {
380
- const eligible = this.options.devices.devices().filter((d) => deviceMatches(d, p.capabilities));
381
- if (eligible.length === 0) return bad("receiver_unavailable");
750
+ // A page's presentation request is offered the sinks that have the app; chrome.cast's requestSession is unchanged
751
+ if (p.appAvailability && appId !== null) appSinks = await this.appSinks({ appIds: [appId], capabilities });
752
+ if (cancelled.value || this.disposed) return bad("cancel");
753
+ const castEligible = (): CastDevice[] =>
754
+ appId === null ? [] : (appSinks?.devices() ?? this.sinkService.devices()).filter((d) => deviceMatches(d, capabilities));
755
+ let eligible = [...castEligible(), ...dialAvailable()];
756
+ if (eligible.length === 0 && dial !== undefined && stopMonitoring !== undefined) {
757
+ await waitForDevices(dial.source, Math.min(p.timeoutMs, DIAL_PROBE_WAIT_MS), () => cancelled.value || discard.value || dialAvailable().length > 0);
758
+ if (cancelled.value || this.disposed) return bad("cancel");
759
+ eligible = [...castEligible(), ...dialAvailable()];
760
+ }
761
+ if (eligible.length === 0) {
762
+ // Say why the devices found are not offered, when they failed to open (Chrome shows no sink and logs the error)
763
+ const why = this.sinkService.openErrors();
764
+ return bad("receiver_unavailable", why.length > 0 ? `no device could be reached: ${why.join("; ")}` : undefined);
765
+ }
382
766
  const request: CastRequestInfo = {
383
- appId: p.appId,
384
- capabilities: p.capabilities,
767
+ appId: appId ?? "",
768
+ capabilities,
385
769
  origin: sender.origin,
386
770
  senderId: sender.id,
387
771
  };
388
- const current = this.currentSessionFor(sender.id, p.appId);
772
+ const current = appId === null ? undefined : this.currentSessionFor(sender.id, appId);
389
773
  if (current !== undefined) {
390
774
  request.session = { sessionId: current.app.sessionId, deviceId: current.device.id };
391
775
  }
392
776
  let choice: DeviceChoice;
393
- // The picker gets live device updates until it answers; closing aborts its signal.
394
- const pick = createPickerContext(this.sinks, (d) => deviceMatches(d, p.capabilities));
395
- pending.picker = pick;
396
- try {
397
- choice = await this.options.selectDevice(eligible, request, pick.context);
398
- } catch (err) {
399
- return bad("session_error", describe(err));
400
- } finally {
401
- pick.close();
777
+ if (presetDeviceId !== undefined) {
778
+ choice = eligible.find((d) => d.id === presetDeviceId) ?? null;
779
+ if (choice === null) return bad("receiver_unavailable");
780
+ } else {
781
+ // The picker gets live device updates until it answers; closing aborts its signal. With a DIAL app it watches
782
+ // the DIAL sinks too.
783
+ const castObservers = appSinks?.observers ?? this.sinks;
784
+ if (dial !== undefined) combined = createSinksObservers(combineSources(appSinks?.source ?? this.sinkService, dial.source));
785
+ const pick = createPickerContext(combined ?? castObservers, (d) =>
786
+ d.dial !== undefined ? dialAvailable().some((x) => x.id === d.id) : appId !== null && deviceMatches(d, capabilities));
787
+ pending.picker = pick;
788
+ try {
789
+ choice = await this.options.selectDevice(eligible, request, pick.context);
790
+ } catch (err) {
791
+ return bad("session_error", describe(err));
792
+ } finally {
793
+ pick.close();
794
+ }
402
795
  }
403
796
  if (choice === null) return bad("cancel");
797
+ if (choice !== "stop" && choice.dial !== undefined) {
798
+ // Only a device offered for this request can be chosen.
799
+ if (!eligible.some((d) => d.id === choice.id)) return bad("receiver_unavailable");
800
+ return good({ dialSink: choice });
801
+ }
802
+ if (appId === null) return bad("invalid_parameter");
404
803
  if (choice === "stop") {
405
804
  const rec = request.session !== undefined ? this.sessions.get(request.session.sessionId) : undefined;
406
805
  if (rec === undefined) return bad("cancel");
@@ -409,7 +808,9 @@ export class CastSessionService {
409
808
  const stopped = await this.stopSessionRecord(rec, sender.id, true);
410
809
  return stopped.ok ? bad("cancel") : stopped;
411
810
  }
412
- if (request.session !== undefined && choice.id === request.session.deviceId) {
811
+ // Chrome's CastActivityManager::LaunchSession launches anew even on a sink that has a route (the receiver's status
812
+ // update then removes the old one), so only the page's own picker reuses the sender's session
813
+ if (presetDeviceId === undefined && request.session !== undefined && choice.id === request.session.deviceId) {
413
814
  const rec = this.sessions.get(request.session.sessionId);
414
815
  if (rec !== undefined) return good(this.snapshotOf(rec));
415
816
  }
@@ -422,7 +823,7 @@ export class CastSessionService {
422
823
  }, p.timeoutMs);
423
824
  });
424
825
  try {
425
- const snapshot = await Promise.race([this.openSession(choice, p.appId, sender, discard, cancelled), bound]);
826
+ const snapshot = await Promise.race([this.openSession(choice, appId, sender, discard, cancelled), bound]);
426
827
  return good(snapshot);
427
828
  } catch (err) {
428
829
  if (err instanceof Discarded) return bad("timeout", "timed out");
@@ -432,6 +833,9 @@ export class CastSessionService {
432
833
  if (timer !== undefined) clearTimeout(timer);
433
834
  }
434
835
  } finally {
836
+ combined?.dispose();
837
+ appSinks?.close();
838
+ stopMonitoring?.();
435
839
  this.pendingRequests.delete(sender.id);
436
840
  }
437
841
  }
@@ -482,7 +886,7 @@ export class CastSessionService {
482
886
  private async stopSessionRecord(rec: SessionRecord, caller: number, tellCaller: boolean): Promise<BridgeResult> {
483
887
  rec.stoppingBy = caller;
484
888
  try {
485
- await rec.client.stop(rec.app.sessionId);
889
+ this.tracker.applyStatus(rec.device.id, rec.client, await rec.client.stop(rec.app.sessionId));
486
890
  } catch (err) {
487
891
  rec.stoppingBy = undefined;
488
892
  return bad("session_error", describe(err));
@@ -498,7 +902,6 @@ export class CastSessionService {
498
902
  } else if (tellCaller) {
499
903
  this.emitTo(caller, { type: "sessionEnded", sessionId: rec.app.sessionId, status: "stopped" });
500
904
  }
501
- this.cleanupIdle(rec.device.id, rec.client);
502
905
  return good(undefined);
503
906
  }
504
907
 
@@ -525,7 +928,7 @@ export class CastSessionService {
525
928
  const rec = this.sessions.get(p.sessionId);
526
929
  if (rec === undefined || !rec.members.has(sender.id)) return bad("session_error");
527
930
  try {
528
- await rec.client.setVolume({ level: p.level });
931
+ this.tracker.applyStatus(rec.device.id, rec.client, await rec.client.setVolume({ level: p.level }));
529
932
  } catch (err) {
530
933
  return bad("session_error", describe(err));
531
934
  }
@@ -538,43 +941,20 @@ export class CastSessionService {
538
941
  const rec = this.sessions.get(p.sessionId);
539
942
  if (rec === undefined || !rec.members.has(sender.id)) return bad("session_error");
540
943
  try {
541
- await rec.client.setVolume({ muted: p.muted });
944
+ this.tracker.applyStatus(rec.device.id, rec.client, await rec.client.setVolume({ muted: p.muted }));
542
945
  } catch (err) {
543
946
  return bad("session_error", describe(err));
544
947
  }
545
948
  return good(undefined);
546
949
  }
547
950
 
548
- /** The device's client entry, created and connecting on first use. */
549
- private clientFor(device: CastDevice): ClientEntry {
550
- const existing = this.clients.get(device.id);
551
- if (existing !== undefined) return existing;
552
- const client = this.options.createClient(device);
553
- this.bindClient(client, device);
554
- const entry: ClientEntry = {
555
- client,
556
- device,
557
- ready: client.connect().catch((err: unknown) => {
558
- // Remove the entry and close the client once so the next request starts fresh.
559
- this.dropClient(device.id, client);
560
- throw err;
561
- }),
562
- opening: 0,
563
- };
564
- // A lookup may never await this; openSession still sees the rejection.
565
- entry.ready.catch(() => {});
566
- this.clients.set(device.id, entry);
567
- return entry;
568
- }
569
-
570
951
  /**
571
952
  * Join a session by its id, as Chrome's Media Router does for `reconnect("cast-session_<id>")`. A session this
572
953
  * service already holds is joined without an origin check, like one found on a device. Otherwise the id is looked up
573
- * in the receiver status of
574
- * every known device: Chrome's CastSessionTracker learns the sessions running on all sinks and
575
- * CastActivityManager::AddNonLocalActivity makes them joinable by id (and only by id: auto-join skips them, and no
576
- * origin is checked). `appId`, when given, must be the session's app (CastActivity::CanJoinSession). Unlike Chrome
577
- * the lookup runs when asked instead of tracking every device all the time.
954
+ * in the session tracker, which knows what every device with an open channel runs: Chrome's CastActivityManager adds
955
+ * a non-local activity for each session its CastSessionTracker learns (AddNonLocalActivity) and
956
+ * FindActivityForSessionJoin finds it by id alone; auto-join skips it and no origin is checked. `appId`, when given,
957
+ * must be the session's app (AppActivity::CanJoinSession). Joining makes the route local, as in Chrome.
578
958
  */
579
959
  private async handleJoinRunningSession(sender: SenderInfo, params: unknown): Promise<BridgeResult> {
580
960
  const p = parseSessionId(params);
@@ -585,144 +965,116 @@ export class CastSessionService {
585
965
  if (appId !== undefined && known.appId !== appId) return bad("session_error");
586
966
  return this.handleJoinSession(sender, params, false);
587
967
  }
588
- const found = await this.findRunningSession(p.sessionId);
589
- if (found === undefined) return bad("session_error");
590
- const { entry, app, volume } = found;
968
+ const tracked = this.tracker.sessionById(p.sessionId);
969
+ if (tracked === undefined || this.disposed || (appId !== undefined && tracked.appId !== appId)) return bad("session_error");
970
+ const client = this.sinkService.clientOf(tracked.sinkId);
971
+ const device = this.sinkService.sinkOf(tracked.sinkId);
972
+ if (client === undefined || device === undefined) return bad("session_error");
973
+ client.connectTransport(tracked.app.transportId);
974
+ const rec: SessionRecord = {
975
+ device,
976
+ client,
977
+ app: tracked.app,
978
+ origin: sender.origin,
979
+ appId: tracked.appId,
980
+ members: new Set([sender.id]),
981
+ parked: new Set(),
982
+ lastVolume: tracked.volume,
983
+ lastSnapshot: null,
984
+ };
985
+ rec.lastSnapshot = this.snapshotOf(rec);
986
+ this.sessions.set(tracked.sessionId, rec);
987
+ return good(rec.lastSnapshot);
988
+ }
989
+
990
+ /** Launch the app on the device's open channel and register the session. */
991
+ private async openSession(
992
+ device: CastDevice,
993
+ appId: string,
994
+ sender: SenderInfo,
995
+ discard: { value: boolean },
996
+ cancelled: { value: boolean },
997
+ ): Promise<SessionSnapshot> {
998
+ // A DIAL sink has no Cast port: it is launched by the presentation handler's DIAL route, never as a Cast session.
999
+ if (device.dial !== undefined) throw new MappedError("session_error", "A DIAL device cannot host a Cast session");
1000
+ // Casting needs a channel that is open now; a device that is not a sink (or whose channel dropped) is unavailable.
1001
+ const client = this.sinkService.clientOf(device.id);
1002
+ if (client === undefined) throw new MappedError("receiver_unavailable", "no open channel to the device");
1003
+ if (discard.value) throw new Discarded();
1004
+ if (cancelled.value) throw new MappedError("cancel", "cancelled");
1005
+ this.launching.set(device.id, (this.launching.get(device.id) ?? 0) + 1);
591
1006
  try {
592
- if (this.disposed || (appId !== undefined && app.appId !== appId)) return bad("session_error");
593
- // Another join of the same session finished while this one looked.
594
- if (this.sessions.has(app.sessionId)) return this.handleJoinSession(sender, params, false);
595
- entry.client.connectTransport(app.transportId);
596
- const rec: SessionRecord = {
597
- device: entry.device,
598
- client: entry.client,
599
- app,
600
- origin: sender.origin,
601
- appId: app.appId,
602
- members: new Set([sender.id]),
603
- parked: new Set(),
604
- lastVolume: volume,
605
- lastSnapshot: null,
606
- };
607
- rec.lastSnapshot = this.snapshotOf(rec);
608
- this.sessions.set(app.sessionId, rec);
609
- return good(rec.lastSnapshot);
1007
+ return await this.launchOn(device, client, appId, sender, discard, cancelled);
610
1008
  } finally {
611
- entry.opening -= 1;
612
- if (!this.sessions.has(app.sessionId)) this.cleanupIdle(entry.device.id, entry.client);
1009
+ const left = (this.launching.get(device.id) ?? 1) - 1;
1010
+ if (left > 0) this.launching.set(device.id, left);
1011
+ else this.launching.delete(device.id);
1012
+ // A launch that ended without a session leaves the device's own session listed again
1013
+ if (left === 0) this.onTrackerChanged();
613
1014
  }
614
1015
  }
615
1016
 
616
- /**
617
- * Ask every known device what it runs and resolve with the one running `sessionId`. The winner's `opening` count
618
- * stays raised for the caller to release; a device that cannot be reached or runs something else is let go.
619
- */
620
- private findRunningSession(sessionId: string): Promise<{ entry: ClientEntry; app: ReceiverApplication; volume: ReceiverVolume } | undefined> {
621
- const devices = this.options.devices.devices();
622
- return new Promise((resolve) => {
623
- let pending = devices.length;
624
- let won = false;
625
- if (pending === 0) resolve(undefined);
626
- for (const device of devices) {
627
- const entry = this.clientFor(device);
628
- entry.opening += 1;
629
- void (async () => {
630
- let app: ReceiverApplication | undefined;
631
- let volume: ReceiverVolume | undefined;
632
- try {
633
- await entry.ready;
634
- const status = await entry.client.getStatus();
635
- app = status.applications.find((a) => a.sessionId === sessionId);
636
- volume = status.volume;
637
- } catch {
638
- // unreachable: not this device
639
- }
640
- if (app !== undefined && volume !== undefined && !won) {
641
- won = true;
642
- resolve({ entry, app, volume });
643
- return;
644
- }
645
- entry.opening -= 1;
646
- this.cleanupIdle(device.id, entry.client);
647
- pending -= 1;
648
- if (pending === 0 && !won) resolve(undefined);
649
- })();
650
- }
651
- });
652
- }
653
-
654
- /** Connect (or reuse) the device's client, launch the app and register the session. */
655
- private async openSession(
1017
+ private async launchOn(
656
1018
  device: CastDevice,
1019
+ client: CastClientLike,
657
1020
  appId: string,
658
1021
  sender: SenderInfo,
659
1022
  discard: { value: boolean },
660
1023
  cancelled: { value: boolean },
661
1024
  ): Promise<SessionSnapshot> {
662
- const entry = this.clientFor(device);
663
- const client = entry.client;
664
- entry.opening += 1;
665
- let registered = false;
1025
+ let app: ReceiverApplication;
666
1026
  try {
667
- try {
668
- await entry.ready;
669
- } catch (err) {
670
- if (err instanceof CastTimeoutError) throw new MappedError("timeout", err.message);
671
- throw new MappedError("receiver_unavailable", describe(err));
672
- }
673
- if (discard.value) throw new Discarded();
674
- if (cancelled.value) throw new MappedError("cancel", "cancelled");
675
- let app: ReceiverApplication;
676
- try {
677
- app = await client.launch(appId);
678
- } catch (err) {
679
- if (err instanceof CastTimeoutError) throw new MappedError("timeout", err.message);
680
- throw new MappedError("session_error", describe(err));
681
- }
682
- if (discard.value) {
683
- client.closeTransport(app.transportId);
684
- throw new Discarded();
685
- }
686
- if (cancelled.value) {
687
- client.closeTransport(app.transportId);
688
- throw new MappedError("cancel", "cancelled");
689
- }
690
- client.connectTransport(app.transportId);
691
- let status: ReceiverStatus;
692
- try {
693
- status = await client.getStatus();
694
- } catch (err) {
695
- client.closeTransport(app.transportId);
696
- throw new MappedError("session_error", describe(err));
697
- }
698
- if (discard.value) {
699
- client.closeTransport(app.transportId);
700
- throw new Discarded();
701
- }
702
- if (cancelled.value) {
703
- client.closeTransport(app.transportId);
704
- throw new MappedError("cancel", "cancelled");
705
- }
706
- const rec: SessionRecord = {
707
- device,
708
- client,
709
- app,
710
- origin: sender.origin,
711
- appId,
712
- members: new Set([sender.id]),
713
- parked: new Set(),
714
- lastVolume: status.volume,
715
- lastSnapshot: null,
716
- };
717
- const snapshot = this.snapshotOf(rec);
718
- rec.lastSnapshot = snapshot;
719
- this.sessions.set(app.sessionId, rec);
720
- registered = true;
721
- return snapshot;
722
- } finally {
723
- entry.opening -= 1;
724
- if (!registered) this.cleanupIdle(device.id, client);
1027
+ app = await client.launch(appId);
1028
+ } catch (err) {
1029
+ if (err instanceof CastTimeoutError) throw new MappedError("timeout", err.message);
1030
+ throw new MappedError("session_error", describe(err));
1031
+ }
1032
+ if (discard.value) {
1033
+ client.closeTransport(app.transportId);
1034
+ throw new Discarded();
1035
+ }
1036
+ if (cancelled.value) {
1037
+ client.closeTransport(app.transportId);
1038
+ throw new MappedError("cancel", "cancelled");
1039
+ }
1040
+ client.connectTransport(app.transportId);
1041
+ let status: ReceiverStatus;
1042
+ try {
1043
+ status = await client.getStatus();
1044
+ this.tracker.applyStatus(device.id, client, status);
1045
+ } catch (err) {
1046
+ client.closeTransport(app.transportId);
1047
+ throw new MappedError("session_error", describe(err));
1048
+ }
1049
+ if (discard.value) {
1050
+ client.closeTransport(app.transportId);
1051
+ throw new Discarded();
1052
+ }
1053
+ if (cancelled.value) {
1054
+ client.closeTransport(app.transportId);
1055
+ throw new MappedError("cancel", "cancelled");
1056
+ }
1057
+ const rec: SessionRecord = {
1058
+ device,
1059
+ client,
1060
+ app,
1061
+ origin: sender.origin,
1062
+ appId,
1063
+ launchedBy: sender.id,
1064
+ members: new Set([sender.id]),
1065
+ parked: new Set(),
1066
+ lastVolume: status.volume,
1067
+ lastSnapshot: null,
1068
+ };
1069
+ const snapshot = this.snapshotOf(rec);
1070
+ rec.lastSnapshot = snapshot;
1071
+ this.sessions.set(app.sessionId, rec);
1072
+ try {
1073
+ this.options.onSessionLaunched?.(sender.id);
1074
+ } catch (err) {
1075
+ console.error("electron-cast: onSessionLaunched failed", err);
725
1076
  }
1077
+ return snapshot;
726
1078
  }
727
1079
 
728
1080
  /** Remove a sender from a session; when it was the last one, tear the session down. */
@@ -732,18 +1084,17 @@ export class CastSessionService {
732
1084
  if (rec.members.size === 0 && rec.parked.size === 0) {
733
1085
  rec.client.closeTransport(rec.app.transportId);
734
1086
  this.sessions.delete(rec.app.sessionId);
735
- this.cleanupIdle(rec.device.id, rec.client);
736
1087
  } else {
737
1088
  this.notifySession("updated", rec);
738
1089
  }
739
1090
  }
740
1091
 
741
- /** Subscribe to a freshly created client's events. */
742
- private bindClient(client: CastClientLike, device: CastDevice): void {
1092
+ /** Subscribe to a freshly opened channel's events. */
1093
+ private bindClient(client: CastClientLike, _device: CastDevice): void {
743
1094
  client.on("message", (msg) => this.onClientMessage(client, msg));
744
- client.on("receiverStatus", (status) => this.onClientStatus(client, device, status));
1095
+ client.on("receiverStatus", (status) => this.onClientStatus(client, status));
745
1096
  client.on("transportClosed", (transportId) => this.onTransportClosed(client, transportId));
746
- client.on("close", () => this.onClientClose(client, device.id));
1097
+ client.on("close", () => this.onClientClose(client));
747
1098
  }
748
1099
 
749
1100
  private onClientMessage(client: CastClientLike, msg: ClientMessage): void {
@@ -761,7 +1112,7 @@ export class CastSessionService {
761
1112
  }
762
1113
  }
763
1114
 
764
- private onClientStatus(client: CastClientLike, device: CastDevice, status: ReceiverStatus): void {
1115
+ private onClientStatus(client: CastClientLike, status: ReceiverStatus): void {
765
1116
  for (const rec of [...this.sessions.values()]) {
766
1117
  if (rec.client !== client) continue;
767
1118
  const app = status.applications.find((a) => a.sessionId === rec.app.sessionId);
@@ -784,7 +1135,6 @@ export class CastSessionService {
784
1135
  }
785
1136
  }
786
1137
  }
787
- this.cleanupIdle(device.id, client);
788
1138
  }
789
1139
 
790
1140
  private onTransportClosed(client: CastClientLike, transportId: string): void {
@@ -797,9 +1147,7 @@ export class CastSessionService {
797
1147
  }
798
1148
  }
799
1149
 
800
- private onClientClose(client: CastClientLike, deviceId: string): void {
801
- const entry = this.clients.get(deviceId);
802
- if (entry !== undefined && entry.client === client) this.clients.delete(deviceId);
1150
+ private onClientClose(client: CastClientLike): void {
803
1151
  for (const rec of [...this.sessions.values()]) {
804
1152
  if (rec.client !== client) continue;
805
1153
  this.sessions.delete(rec.app.sessionId);
@@ -812,7 +1160,7 @@ export class CastSessionService {
812
1160
  /** Re-check availability for every initialized sender; emit only on change. */
813
1161
  private onDevicesChanged(): void {
814
1162
  if (this.disposed) return;
815
- const devices = this.options.devices.devices();
1163
+ const devices = this.sinkService.devices();
816
1164
  for (const [id, rec] of this.senders) {
817
1165
  const available = devices.some((d) => deviceMatches(d, rec.capabilities));
818
1166
  if (available !== rec.lastAvailable) {
@@ -822,29 +1170,26 @@ export class CastSessionService {
822
1170
  }
823
1171
  }
824
1172
 
825
- /** Close the client when no session uses it any more and no openSession is in flight. */
826
- private cleanupIdle(deviceId: string, client: CastClientLike): void {
827
- const entry = this.clients.get(deviceId);
828
- if (entry !== undefined && entry.client === client && entry.opening > 0) return;
829
- for (const rec of this.sessions.values()) {
830
- if (rec.client === client) return;
831
- }
832
- this.dropClient(deviceId, client);
833
- }
1173
+ // Main-process API (see manager-api.ts). Control goes through the paths the pages use, so pages see the same events.
834
1174
 
835
- /** Forget a client and close it; a no-op unless it is still the registered entry for the device. */
836
- private dropClient(deviceId: string, client: CastClientLike): void {
837
- const entry = this.clients.get(deviceId);
838
- if (entry === undefined || entry.client !== client) return;
839
- this.clients.delete(deviceId);
840
- client.close();
1175
+ /** The sessions `senderId` launched and that still run (`routes_by_frame_` lookup by frame). */
1176
+ sessionsLaunchedBy(senderId: number): string[] {
1177
+ return [...this.sessions.values()].filter((rec) => rec.launchedBy === senderId).map((rec) => rec.app.sessionId);
841
1178
  }
842
1179
 
843
- // Main-process API (see manager-api.ts). Control goes through the paths the pages use, so pages see the same events.
844
-
845
- /** Every live session, parked ones included. */
1180
+ /**
1181
+ * Every live session, parked ones included, then the sessions the devices run that this service does not hold
1182
+ * (started elsewhere, or let go of here), as Chrome's non-local routes.
1183
+ */
846
1184
  mediaRoutes(): MediaRoute[] {
847
- return [...this.sessions.values()].map((rec) => this.routeOf(rec));
1185
+ const local = [...this.sessions.values()].map((rec) => this.routeOf(rec));
1186
+ return [...local, ...this.nonLocalSessions().map((s) => this.nonLocalRouteOf(s))];
1187
+ }
1188
+
1189
+ /** The tracked sessions no page of this service holds (Chrome: activities with `is_local` false). */
1190
+ private nonLocalSessions(): TrackedSession[] {
1191
+ return this.tracker.sessions().filter((s) => !this.sessions.has(s.sessionId) && !this.launching.has(s.sinkId)
1192
+ && this.options.ownsSession?.(s.sessionId, s.sinkId) !== true);
848
1193
  }
849
1194
 
850
1195
  /** Be told when a session starts, changes (status, volume, pages) or ends; returns the unsubscribe function. */
@@ -853,29 +1198,102 @@ export class CastSessionService {
853
1198
  return () => void this.sessionListeners.delete(listener);
854
1199
  }
855
1200
 
856
- /** Stop a session on the device for every page, as if a member had called stopSession. */
1201
+ /**
1202
+ * Stop a session on the device for every page, as if a member had called stopSession. A session this service does not
1203
+ * hold is stopped on its device as it is (Chrome's TerminateSession works on non-local activities too).
1204
+ */
857
1205
  async terminateSession(sessionId: string): Promise<BridgeResult> {
858
1206
  const rec = this.sessions.get(sessionId);
859
- if (rec === undefined) return bad("session_error", "unknown session");
860
1207
  // No page is the caller, so every member is told sessionEnded.
861
- return this.stopSessionRecord(rec, MAIN_CALLER, false);
1208
+ if (rec !== undefined) return this.stopSessionRecord(rec, MAIN_CALLER, false);
1209
+ const tracked = this.nonLocalSessions().find((s) => s.sessionId === sessionId);
1210
+ if (tracked === undefined) return bad("session_error", "unknown session");
1211
+ // With no open channel the stop cannot be sent: Chrome's `CastMessageHandler::StopSession` finds no socket and
1212
+ // reports a failure, which `HandleStopSessionResponse` turns into this message while the route stays.
1213
+ const client = this.sinkService.clientOf(tracked.sinkId);
1214
+ if (client === undefined) return bad("session_error", "StopSession response is not OK. Failed to terminate route.");
1215
+ try {
1216
+ this.tracker.applyStatus(tracked.sinkId, client, await client.stop(sessionId));
1217
+ } catch (err) {
1218
+ return bad("session_error", describe(err));
1219
+ }
1220
+ return good(undefined);
862
1221
  }
863
1222
 
864
1223
  async setSessionVolume(sessionId: string, volume: { level: number } | { muted: boolean }): Promise<BridgeResult> {
865
1224
  const rec = this.sessions.get(sessionId);
866
- if (rec === undefined) return bad("session_error", "unknown session");
1225
+ const tracked = rec === undefined ? this.nonLocalSessions().find((s) => s.sessionId === sessionId) : undefined;
1226
+ const client = rec?.client ?? (tracked === undefined ? undefined : this.sinkService.clientOf(tracked.sinkId));
1227
+ const sinkId = rec?.device.id ?? tracked?.sinkId;
1228
+ if (client === undefined || sinkId === undefined) return bad("session_error", "unknown session");
867
1229
  try {
868
- await rec.client.setVolume(volume);
1230
+ this.tracker.applyStatus(sinkId, client, await client.setVolume(volume));
869
1231
  } catch (err) {
870
1232
  return bad("session_error", describe(err));
871
1233
  }
872
1234
  return good(undefined);
873
1235
  }
874
1236
 
875
- /** Detach every page from the session and close its transport; the receiver app keeps running. */
1237
+ /**
1238
+ * Every receiver status that describes a session, changed or not, with its volume (the tracker's
1239
+ * `OnSessionAddedOrUpdated`); for the media controller. Returns the unsubscribe function.
1240
+ */
1241
+ observeSessionStatus(listener: (sessionId: string, volume: ReceiverVolume) => void): () => void {
1242
+ const on = (s: TrackedSession): void => listener(s.sessionId, s.volume);
1243
+ this.tracker.on("sessionStatus", on);
1244
+ return () => void this.tracker.off("sessionStatus", on);
1245
+ }
1246
+
1247
+ /**
1248
+ * Every MEDIA_STATUS on a device's channel, credited to the session the device runs and merged with the media saved
1249
+ * before (`CastSessionTracker::HandleMediaStatusMessage`); for the media controller. Returns the unsubscribe function.
1250
+ */
1251
+ observeMediaStatus(listener: (sessionId: string, message: Record<string, unknown>) => void): () => void {
1252
+ const on = (s: TrackedSession, message: Record<string, unknown>): void => listener(s.sessionId, message);
1253
+ this.tracker.on("mediaStatus", on);
1254
+ return () => void this.tracker.off("mediaStatus", on);
1255
+ }
1256
+
1257
+ /**
1258
+ * Send a message to a session's receiver app from main, with no page involved, over the device's channel. A session
1259
+ * this service does not hold is reached too, as Chrome's `CastMessageHandler::SendMediaRequest` reaches a non-local
1260
+ * activity's session: a virtual connection to its transport is opened first (`SendCastMessageToSocket` -> `DoEnsureConnection`).
1261
+ */
1262
+ sendSessionMessage(sessionId: string, namespace: string, message: string): BridgeResult {
1263
+ const rec = this.sessions.get(sessionId);
1264
+ let client = rec?.client;
1265
+ let transportId = rec?.app.transportId;
1266
+ if (rec === undefined) {
1267
+ const tracked = this.nonLocalSessions().find((s) => s.sessionId === sessionId);
1268
+ if (tracked === undefined) return bad("session_error", "unknown session");
1269
+ client = this.sinkService.clientOf(tracked.sinkId);
1270
+ transportId = tracked.transportId;
1271
+ if (client === undefined) return bad("channel_error", "no open channel to the device");
1272
+ }
1273
+ if (client === undefined || transportId === undefined) return bad("session_error", "unknown session");
1274
+ try {
1275
+ if (rec === undefined) client.connectTransport(transportId);
1276
+ client.send(namespace, transportId, message);
1277
+ } catch (err) {
1278
+ return bad("channel_error", describe(err));
1279
+ }
1280
+ return good(undefined);
1281
+ }
1282
+
1283
+ /** The volume the receiver last reported for a session, local or not (Chrome: `receiver.volume` of the CastSession). */
1284
+ sessionVolume(sessionId: string): ReceiverVolume | undefined {
1285
+ return this.sessions.get(sessionId)?.lastVolume ?? this.tracker.sessionById(sessionId)?.volume;
1286
+ }
1287
+
1288
+ /**
1289
+ * Detach every page from the session and close its transport; the receiver app keeps running (and is then listed as a
1290
+ * non-local route). A route no page holds has nothing to detach.
1291
+ */
876
1292
  detachSession(sessionId: string): BridgeResult {
877
1293
  const rec = this.sessions.get(sessionId);
878
- if (rec === undefined) return bad("session_error", "unknown session");
1294
+ if (rec === undefined) {
1295
+ return this.nonLocalSessions().some((s) => s.sessionId === sessionId) ? good(undefined) : bad("session_error", "unknown session");
1296
+ }
879
1297
  for (const member of rec.members) {
880
1298
  this.emitTo(member, { type: "sessionEnded", sessionId, status: "disconnected" });
881
1299
  }
@@ -883,13 +1301,27 @@ export class CastSessionService {
883
1301
  rec.parked.clear();
884
1302
  rec.client.closeTransport(rec.app.transportId);
885
1303
  this.sessions.delete(sessionId);
886
- this.cleanupIdle(rec.device.id, rec.client);
887
1304
  return good(undefined);
888
1305
  }
889
1306
 
890
1307
  /** Tell the route observers something changed (the arguments only fit the ObservedMap callback). */
891
1308
  private notifySession(_kind: "started" | "updated" | "ended", _rec: SessionRecord): void {
892
1309
  if (this.disposed) return;
1310
+ if (_kind === "ended") this.sinkService.releaseUnused();
1311
+ this.lastRoutesKey = JSON.stringify(this.mediaRoutes());
1312
+ this.fireSessionListeners();
1313
+ }
1314
+
1315
+ /** The tracker learned something; route observers hear of it only if the routes they see differ now. */
1316
+ private onTrackerChanged(): void {
1317
+ if (this.disposed) return;
1318
+ const key = JSON.stringify(this.mediaRoutes());
1319
+ if (key === this.lastRoutesKey) return;
1320
+ this.lastRoutesKey = key;
1321
+ this.fireSessionListeners();
1322
+ }
1323
+
1324
+ private fireSessionListeners(): void {
893
1325
  for (const listener of [...this.sessionListeners]) {
894
1326
  try {
895
1327
  listener();
@@ -902,9 +1334,12 @@ export class CastSessionService {
902
1334
  private routeOf(rec: SessionRecord): MediaRoute {
903
1335
  return {
904
1336
  id: rec.app.sessionId,
1337
+ providerId: "cast",
905
1338
  mediaSource: `cast:${rec.appId}`,
906
1339
  sinkId: rec.device.id,
1340
+ sinkName: rec.device.name,
907
1341
  description: rec.app.statusText || rec.app.displayName,
1342
+ isLocal: true,
908
1343
  appId: rec.appId,
909
1344
  displayName: rec.app.displayName,
910
1345
  origin: rec.origin,
@@ -915,6 +1350,26 @@ export class CastSessionService {
915
1350
  };
916
1351
  }
917
1352
 
1353
+ /** Chrome's `AddNonLocalActivity`: the route has no page, and its description is the session's (`GetRouteDescription`). */
1354
+ private nonLocalRouteOf(session: TrackedSession): MediaRoute {
1355
+ return {
1356
+ id: session.sessionId,
1357
+ providerId: "cast",
1358
+ mediaSource: `cast:${session.appId}`,
1359
+ sinkId: session.sinkId,
1360
+ sinkName: this.sinkService.sinkOf(session.sinkId)?.name ?? "",
1361
+ description: session.statusText || session.displayName,
1362
+ isLocal: false,
1363
+ appId: session.appId,
1364
+ displayName: session.displayName,
1365
+ origin: "",
1366
+ volume: { level: session.volume.level ?? null, muted: session.volume.muted ?? null },
1367
+ members: [],
1368
+ parkedSenders: [],
1369
+ parked: false,
1370
+ };
1371
+ }
1372
+
918
1373
  private snapshotOf(rec: SessionRecord): SessionSnapshot {
919
1374
  const app = rec.app;
920
1375
  const volume: VolumeSnapshot = {