UniWebView.Snapshot.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  1. //
  2. // UniWebView.Snapshot.cs
  3. // Created by Wang Wei (@onevcat) on 2025-04-19.
  4. //
  5. // This file is a part of UniWebView Project (https://uniwebview.com)
  6. // By purchasing the asset, you are allowed to use this code in as many as projects
  7. // you want, only if you publish the final products under the name of the same account
  8. // used for the purchase.
  9. //
  10. // This asset and all corresponding files (such as source code) are provided on an
  11. // "as is" basis, without warranty of any kind, express of implied, including but not
  12. // limited to the warranties of merchantability, fitness for a particular purpose, and
  13. // noninfringement. In no event shall the authors or copyright holders be liable for any
  14. // claim, damages or other liability, whether in action of contract, tort or otherwise,
  15. // arising from, out of or in connection with the software or the use of other dealing in the software.
  16. //
  17. using UnityEngine;
  18. using System;
  19. using System.Collections;
  20. using System.Threading.Tasks;
  21. public partial class UniWebView {
  22. private const string SnapshotRenderingLegacyMessage =
  23. "The snapshot rendering APIs are legacy and allocate heavily. " +
  24. "Use StartSnapshotTextureStream instead. See the render-as-texture migration guide.";
  25. private static readonly Rect snapshotFullViewRect = new Rect(-1, -1, -1, -1);
  26. private byte[] snapshotCachedData;
  27. private Coroutine snapshotRefreshCoroutine;
  28. private Action<Texture2D> snapshotStartedAction;
  29. private string snapshotStartedActionIdentifier;
  30. private bool snapshotStartedActionPending;
  31. private UniWebViewSnapshotTextureStream activeSnapshotTextureStream;
  32. private Coroutine snapshotTextureStreamCoroutine;
  33. private long nextSnapshotTextureStreamId;
  34. /// <summary>
  35. /// Capture the content of web view and store it to the cache path on disk with the given file name.
  36. ///
  37. /// When the capturing finishes, `OnCaptureSnapshotFinished` event will be raised, with an error code to indicate
  38. /// whether the operation succeeded and an accessible disk path of the image.
  39. ///
  40. /// The captured image will be stored as a PNG file under the `fileName` in app's cache folder. If a file with the
  41. /// same file name already exists, it will be overridden by the new captured image.
  42. /// </summary>
  43. /// <param name="fileName">
  44. /// The file name to which the captured image is stored to, for example "screenshot.png". If empty, UniWebView will
  45. /// pick a random UUID with "png" file extension as the file name.
  46. /// </param>
  47. public void CaptureSnapshot(string fileName) {
  48. UniWebViewInterface.CaptureSnapshot(listener.Name, fileName);
  49. }
  50. /// <summary>
  51. /// Starts the process of continually rendering the snapshot.
  52. /// </summary>
  53. /// <remarks>
  54. /// <para>
  55. /// This API is legacy and allocation-heavy. For continuous render-as-texture use, prefer
  56. /// <see cref="StartSnapshotTextureStream"/>, which exposes one stream-owned texture
  57. /// updated in place on supported platforms.
  58. /// </para>
  59. /// <para>
  60. /// You take the responsibility of calling this method before you use either <see cref="GetRenderedData(Rect?)"/> or
  61. /// <see cref="CreateRenderedTexture(Rect?)"/> to get the rendered data or texture. It prepares a render buffer for the image
  62. /// data and performs the initial rendering for later use.
  63. /// </para>
  64. /// <para>
  65. /// If this method is not called, the related data or texture methods will not work and will only return <c>null</c>. Once you
  66. /// no longer need the web view to be rendered as a texture, you should call <see cref="StopSnapshotForRendering"/> to clean up
  67. /// the associated resources.
  68. /// </para>
  69. /// </remarks>
  70. /// <param name="rect">The optional rectangle to specify the area for rendering. If <c>null</c>, the entire view is rendered.</param>
  71. /// <param name="onStarted">
  72. /// An optional callback to execute when rendering has started. The callback receives a <see cref="Texture2D"/> parameter
  73. /// representing the rendered texture.
  74. /// </param>
  75. /// <param name="refreshInterval">
  76. /// The interval in seconds between snapshot refreshes. By default (when not set or set to <c>0</c>), it refreshes
  77. /// every frame for the best responsiveness. Use a larger value to reduce CPU/GPU usage, for example <c>1.0f/30</c>
  78. /// for 30 fps or <c>1.0f/10</c> for 10 fps. This is especially useful on Android where snapshot capture runs on
  79. /// the main thread.
  80. /// </param>
  81. [Obsolete(SnapshotRenderingLegacyMessage, false)]
  82. public void StartSnapshotForRendering(
  83. Rect? rect = null, Action<Texture2D> onStarted = null, float refreshInterval = 0
  84. ) {
  85. StopSnapshotRefreshCoroutine();
  86. snapshotCachedData = null;
  87. var identifier = RegisterSnapshotStartedAction(onStarted);
  88. UniWebViewInterface.StartSnapshotForRendering(listener.Name, identifier);
  89. snapshotRefreshCoroutine = StartCoroutine(SnapshotRefreshLoop(rect, refreshInterval));
  90. }
  91. /// <summary>
  92. /// Stops the process of continually rendering the snapshot.
  93. /// </summary>
  94. /// <remarks>
  95. /// <para>
  96. /// This API stops the legacy PNG-backed snapshot rendering path. For continuous render-as-texture use, prefer
  97. /// <see cref="StartSnapshotTextureStream"/>.
  98. /// </para>
  99. /// <para>
  100. /// You should call this method when you no longer need any further data or texture from the
  101. /// <see cref="GetRenderedData(Rect?)"/> or <see cref="CreateRenderedTexture(Rect?)"/> methods. This helps in releasing
  102. /// resources and terminating the rendering process.
  103. /// </para>
  104. /// </remarks>
  105. [Obsolete(SnapshotRenderingLegacyMessage, false)]
  106. public void StopSnapshotForRendering() {
  107. StopSnapshotRefreshCoroutine();
  108. snapshotCachedData = null;
  109. ClearSnapshotStartedAction();
  110. UniWebViewInterface.StopSnapshotForRendering(listener.Name);
  111. }
  112. private IEnumerator SnapshotRefreshLoop(Rect? rect, float interval) {
  113. var r = rect ?? snapshotFullViewRect;
  114. var useEveryFrame = interval <= 0;
  115. var wait = useEveryFrame ? null : new WaitForSeconds(interval);
  116. while (true) {
  117. yield return wait;
  118. var data = UniWebViewInterface.GetRenderedData(
  119. listener.Name, (int)r.x, (int)r.y, (int)r.width, (int)r.height
  120. );
  121. if (data != null) {
  122. snapshotCachedData = data;
  123. TryInvokeSnapshotStartedAction();
  124. }
  125. }
  126. }
  127. private void TryInvokeSnapshotStartedAction() {
  128. if (!snapshotStartedActionPending || snapshotStartedAction == null || snapshotCachedData == null) {
  129. return;
  130. }
  131. var action = snapshotStartedAction;
  132. ClearSnapshotStartedAction();
  133. action(CreateRenderedTextureFromCachedData());
  134. }
  135. private string RegisterSnapshotStartedAction(Action<Texture2D> action) {
  136. ClearSnapshotStartedAction();
  137. if (action == null) {
  138. return null;
  139. }
  140. var identifier = Guid.NewGuid().ToString();
  141. snapshotStartedAction = action;
  142. snapshotStartedActionIdentifier = identifier;
  143. actions.Add(identifier, () => {
  144. if (snapshotStartedActionIdentifier != identifier) {
  145. return;
  146. }
  147. snapshotStartedActionPending = true;
  148. TryInvokeSnapshotStartedAction();
  149. });
  150. return identifier;
  151. }
  152. private void ClearSnapshotStartedAction() {
  153. if (snapshotStartedActionIdentifier != null) {
  154. actions.Remove(snapshotStartedActionIdentifier);
  155. }
  156. snapshotStartedAction = null;
  157. snapshotStartedActionIdentifier = null;
  158. snapshotStartedActionPending = false;
  159. }
  160. private void StopSnapshotRefreshCoroutine() {
  161. if (snapshotRefreshCoroutine != null) {
  162. StopCoroutine(snapshotRefreshCoroutine);
  163. snapshotRefreshCoroutine = null;
  164. }
  165. }
  166. /// <summary>
  167. /// Gets the data of the rendered image for the current web view.
  168. /// </summary>
  169. /// <remarks>
  170. /// <para>
  171. /// This API is legacy and returns PNG bytes from the cached legacy snapshot path. For continuous texture display, prefer
  172. /// <see cref="StartSnapshotTextureStream"/> and use its live texture instead.
  173. /// </para>
  174. /// <para>
  175. /// This method provides you with the raw bytes of the rendered image data in PNG format. To successfully retrieve the
  176. /// current rendered data, you should first call <see cref="StartSnapshotForRendering"/> to initiate the rendering process.
  177. /// If <see cref="StartSnapshotForRendering"/> has not been called, this method will return <c>null</c>.
  178. /// </para>
  179. /// <para>
  180. /// The rendering area specified by the <paramref name="rect"/> parameter is based on the local coordinates of the web view.
  181. /// For example, <c>new Rect(webView.frame.width / 2, webView.frame.height / 2, 100, 100)</c> means setting the origin to the
  182. /// center of the web view and taking a 100x100 square as the snapshot area.
  183. /// </para>
  184. /// <para>
  185. /// Please note that this method supports only software-rendered content. Content rendered by hardware, such as videos
  186. /// and WebGL content, will appear as a black rectangle in the rendered image.
  187. /// </para>
  188. /// </remarks>
  189. /// <param name="rect">
  190. /// The desired rectangle within which the snapshot rendering should occur in the web view. If default value `null` is used,
  191. /// the whole web view frame will be used as the snapshot area.
  192. /// </param>
  193. /// <returns>
  194. /// An array of raw bytes representing the rendered image data in PNG format, or <c>null</c> if the rendering process fails
  195. /// or if the data is not prepared.
  196. /// </returns>
  197. /// <seealso cref="StartSnapshotForRendering"/>
  198. [Obsolete(SnapshotRenderingLegacyMessage, false)]
  199. public byte[] GetRenderedData(Rect? rect = null) {
  200. return GetRenderedDataFromCache(rect);
  201. }
  202. /// <summary>
  203. /// Creates a rendered texture for the current web view.
  204. /// </summary>
  205. /// <remarks>
  206. /// <para>
  207. /// This API is legacy and creates a new standalone texture from PNG data every time it is called. For continuous texture
  208. /// display, prefer <see cref="StartSnapshotTextureStream"/>, assign the stream texture
  209. /// once, and dispose the stream during cleanup.
  210. /// </para>
  211. /// <para>
  212. /// You should destroy the returned texture using the `Destroy` method when you no longer need it to free up resources.
  213. /// </para>
  214. /// <para>
  215. /// This method provides you with a texture of the rendered image for the web view, which you can use in your 3D game world.
  216. /// To obtain the current rendered data, you should call <see cref="StartSnapshotForRendering"/> before using this method.
  217. /// If <see cref="StartSnapshotForRendering"/> has not been called, this method will return <c>null</c>.
  218. /// </para>
  219. /// <para>
  220. /// Please note that this method supports only software-rendered content. Content rendered by hardware, such as videos
  221. /// and WebGL content, will appear as a black rectangle in the rendered image.
  222. /// </para>
  223. /// <para>
  224. /// This method returns a plain <see cref="Texture2D"/> object. The texture is not user interactive and can only be used for
  225. /// display purposes. It is your responsibility to call the `Destroy` method on this texture when you no longer need it.
  226. /// </para>
  227. /// </remarks>
  228. /// <param name="rect">
  229. /// The desired rectangle within which the snapshot rendering should occur in the web view. If default value `null` is used,
  230. /// the whole web view frame will be used as the snapshot area.
  231. /// </param>
  232. /// <returns>
  233. /// A rendered texture of the current web view, or <c>null</c> if the rendering process fails or if the data is not prepared.
  234. /// </returns>
  235. /// <seealso cref="StartSnapshotForRendering"/>
  236. [Obsolete(SnapshotRenderingLegacyMessage, false)]
  237. public Texture2D CreateRenderedTexture(Rect? rect = null) {
  238. return CreateRenderedTextureFromCachedData(rect);
  239. }
  240. private byte[] GetRenderedDataFromCache(Rect? rect = null) {
  241. return snapshotCachedData;
  242. }
  243. private Texture2D CreateRenderedTextureFromCachedData(Rect? rect = null) {
  244. var bytes = GetRenderedDataFromCache(rect);
  245. if (bytes == null) {
  246. return null;
  247. }
  248. Texture2D texture = new Texture2D(2, 2, TextureFormat.RGB24, false);
  249. texture.LoadImage(bytes);
  250. return texture;
  251. }
  252. /// <summary>
  253. /// Starts a live snapshot texture stream for this web view.
  254. /// </summary>
  255. /// <remarks>
  256. /// <para>
  257. /// This is the supported API for continuously showing web view snapshots in Unity. It creates one stream-owned
  258. /// texture and updates it in place. Assign the texture once in <paramref name="onReady"/> and dispose the returned
  259. /// stream when it is no longer needed.
  260. /// </para>
  261. /// <para>
  262. /// If the current platform or graphics backend supports neither the optimized native texture stream nor a CPU
  263. /// readback fallback, the returned stream remains not ready: <see cref="UniWebViewSnapshotTextureStream.Texture"/>
  264. /// is <c>null</c>, <see cref="UniWebViewSnapshotTextureStream.IsReady"/> is <c>false</c>, and
  265. /// <paramref name="onReady"/> is not called. The stream API never falls back to the legacy PNG-backed texture path.
  266. /// </para>
  267. /// <para>
  268. /// On Android, the optimized native texture path requires OpenGL ES 2 or OpenGL ES 3. When Unity runs on another
  269. /// graphics API such as Vulkan, the stream automatically falls back to a CPU readback path that updates the
  270. /// stream-owned texture from the captured frame data. The public behavior is identical, but the per-frame cost is
  271. /// higher than the native texture path, so prefer OpenGL ES when the stream performance matters.
  272. /// </para>
  273. /// </remarks>
  274. /// <param name="rect">The optional rectangle to capture. If <c>null</c>, the entire web view is captured.</param>
  275. /// <param name="refreshInterval">
  276. /// The interval in seconds between snapshot refreshes. Use <c>0</c> to refresh as fast as the internal scheduler
  277. /// safely allows.
  278. /// </param>
  279. /// <param name="onReady">An optional callback invoked once after the first native texture frame is ready.</param>
  280. /// <param name="resolutionScale">
  281. /// The scale applied to the capture resolution, in the <c>(0, 1]</c> range. Use <c>1</c> (the default) to capture
  282. /// at full resolution. Use a smaller value such as <c>0.5f</c> to reduce the capture and upload cost per frame, at
  283. /// the price of a softer image. Values out of the range are clamped. This currently only takes effect on iOS and
  284. /// macOS; Android always captures at full resolution.
  285. /// </param>
  286. /// <returns>The created snapshot texture stream.</returns>
  287. public UniWebViewSnapshotTextureStream StartSnapshotTextureStream(
  288. Rect? rect = null, float refreshInterval = 0, Action<Texture2D> onReady = null, float resolutionScale = 1.0f
  289. ) {
  290. var clampedResolutionScale = ClampSnapshotTextureStreamResolutionScale(resolutionScale);
  291. return StartSnapshotTextureStream(
  292. rect,
  293. refreshInterval,
  294. onReady,
  295. stream => UniWebViewInterface.StartSnapshotTextureStream(
  296. listener.Name,
  297. stream.StreamId,
  298. (int)stream.Rect.x,
  299. (int)stream.Rect.y,
  300. (int)stream.Rect.width,
  301. (int)stream.Rect.height,
  302. clampedResolutionScale
  303. )
  304. );
  305. }
  306. internal static float ClampSnapshotTextureStreamResolutionScale(float resolutionScale) {
  307. if (resolutionScale <= 0) {
  308. return 1.0f;
  309. }
  310. return Mathf.Clamp(resolutionScale, 0.1f, 1.0f);
  311. }
  312. internal UniWebViewSnapshotTextureStream StartSnapshotTextureStreamWithSyntheticFrames(
  313. int width,
  314. int height,
  315. int framePattern,
  316. float refreshInterval = 0,
  317. Action<Texture2D> onReady = null
  318. ) {
  319. var rect = new Rect(0, 0, width, height);
  320. return StartSnapshotTextureStream(
  321. rect,
  322. refreshInterval,
  323. onReady,
  324. stream => UniWebViewInterface.StartSnapshotTextureStreamWithSyntheticFrames(
  325. listener.Name, stream.StreamId, width, height, framePattern
  326. )
  327. );
  328. }
  329. private UniWebViewSnapshotTextureStream StartSnapshotTextureStream(
  330. Rect? rect,
  331. float refreshInterval,
  332. Action<Texture2D> onReady,
  333. Func<UniWebViewSnapshotTextureStream, bool> startNativeStream
  334. ) {
  335. StopActiveSnapshotTextureStream();
  336. var r = rect ?? snapshotFullViewRect;
  337. var stream = new UniWebViewSnapshotTextureStream(
  338. this, listener.Name, ++nextSnapshotTextureStreamId, r, refreshInterval, onReady
  339. );
  340. activeSnapshotTextureStream = stream;
  341. if (startNativeStream(stream)) {
  342. snapshotTextureStreamCoroutine = StartCoroutine(SnapshotTextureStreamLoop(stream));
  343. }
  344. return stream;
  345. }
  346. internal void StopSnapshotTextureStream(UniWebViewSnapshotTextureStream stream) {
  347. if (stream == null) {
  348. return;
  349. }
  350. if (activeSnapshotTextureStream != stream) {
  351. stream.MarkStoppedByOwner();
  352. return;
  353. }
  354. StopSnapshotTextureStreamCoroutine();
  355. UniWebViewInterface.StopSnapshotTextureStream(listener.Name, stream.StreamId);
  356. activeSnapshotTextureStream = null;
  357. stream.MarkStoppedByOwner();
  358. }
  359. private void StopActiveSnapshotTextureStream() {
  360. if (activeSnapshotTextureStream != null) {
  361. activeSnapshotTextureStream.Stop();
  362. }
  363. }
  364. private void StopSnapshotTextureStreamCoroutine() {
  365. if (snapshotTextureStreamCoroutine != null) {
  366. StopCoroutine(snapshotTextureStreamCoroutine);
  367. snapshotTextureStreamCoroutine = null;
  368. }
  369. }
  370. private void CleanupSnapshotResources() {
  371. StopActiveSnapshotTextureStream();
  372. StopSnapshotRefreshCoroutine();
  373. ClearSnapshotStartedAction();
  374. snapshotCachedData = null;
  375. }
  376. private IEnumerator SnapshotTextureStreamLoop(UniWebViewSnapshotTextureStream stream) {
  377. var nextTickTime = 0.0f;
  378. var usesCpuFallback = UniWebViewInterface.SnapshotTextureStreamUsesCpuFallback();
  379. while (activeSnapshotTextureStream == stream && !stream.IsStopped) {
  380. yield return null;
  381. if (ShouldTickSnapshotTextureStream(stream.RefreshInterval, Time.time, ref nextTickTime)) {
  382. UniWebViewInterface.TickSnapshotTextureStream(listener.Name, stream.StreamId);
  383. }
  384. if (usesCpuFallback) {
  385. ConsumeSnapshotTextureStreamCpuFrame(stream);
  386. continue;
  387. }
  388. UniWebViewInterface.PumpSnapshotTextureStream(listener.Name, stream.StreamId);
  389. if (!UniWebViewInterface.IsSnapshotTextureStreamReady(listener.Name, stream.StreamId)) {
  390. continue;
  391. }
  392. ApplySnapshotTextureStreamState(
  393. stream.StreamId,
  394. UniWebViewInterface.GetSnapshotTextureStreamTexturePointer(listener.Name, stream.StreamId),
  395. UniWebViewInterface.GetSnapshotTextureStreamWidth(listener.Name, stream.StreamId),
  396. UniWebViewInterface.GetSnapshotTextureStreamHeight(listener.Name, stream.StreamId),
  397. UniWebViewInterface.GetSnapshotTextureStreamFrameIndex(listener.Name, stream.StreamId)
  398. );
  399. }
  400. }
  401. private void ConsumeSnapshotTextureStreamCpuFrame(UniWebViewSnapshotTextureStream stream) {
  402. var width = UniWebViewInterface.GetSnapshotTextureStreamWidth(listener.Name, stream.StreamId);
  403. var height = UniWebViewInterface.GetSnapshotTextureStreamHeight(listener.Name, stream.StreamId);
  404. if (width <= 0 || height <= 0) {
  405. return;
  406. }
  407. var buffer = stream.PrepareCpuFrameBuffer(width, height);
  408. if (buffer == IntPtr.Zero) {
  409. return;
  410. }
  411. // The frame size is re-validated natively against the buffer capacity, so a concurrent
  412. // resize between the size query and the copy results in a skipped frame, not a tear.
  413. var frameIndex = UniWebViewInterface.ConsumeSnapshotTextureStreamCpuFrame(
  414. listener.Name, stream.StreamId, buffer, width * height * 4
  415. );
  416. if (frameIndex < 0 || activeSnapshotTextureStream != stream) {
  417. return;
  418. }
  419. stream.UpdateTextureWithCpuFrame(width, height, frameIndex);
  420. }
  421. internal static bool ShouldTickSnapshotTextureStream(float refreshInterval, float now, ref float nextTickTime) {
  422. if (refreshInterval <= 0) {
  423. nextTickTime = now;
  424. return true;
  425. }
  426. if (now < nextTickTime) {
  427. return false;
  428. }
  429. nextTickTime = now + refreshInterval;
  430. return true;
  431. }
  432. private void ApplySnapshotTextureStreamState(
  433. long streamId, IntPtr nativeTexturePtr, int width, int height, long frameIndex
  434. ) {
  435. if (activeSnapshotTextureStream == null || activeSnapshotTextureStream.StreamId != streamId) {
  436. return;
  437. }
  438. activeSnapshotTextureStream.UpdateTexture(nativeTexturePtr, width, height, frameIndex);
  439. }
  440. }