UniWebViewSnapshotTextureStream.cs 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. //
  2. // UniWebViewSnapshotTextureStream.cs
  3. // Created by Wang Wei (@onevcat) on 2026-05-28.
  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 System;
  18. using System.Runtime.InteropServices;
  19. using UnityEngine;
  20. using Object = UnityEngine.Object;
  21. /// <summary>
  22. /// Represents a live snapshot texture stream owned by a <see cref="UniWebView"/>.
  23. /// </summary>
  24. /// <remarks>
  25. /// The stream owns the texture it exposes. Assign <see cref="Texture"/> once when <see cref="IsReady"/> becomes
  26. /// <c>true</c>, then call <see cref="Dispose"/> when the stream is no longer needed. Do not destroy the texture yourself.
  27. /// </remarks>
  28. public sealed class UniWebViewSnapshotTextureStream : IDisposable {
  29. private readonly UniWebView owner;
  30. private bool stopped;
  31. private bool readyActionInvoked;
  32. private Action<Texture2D> onReady;
  33. private IntPtr cpuFrameBuffer = IntPtr.Zero;
  34. private int cpuFrameBufferSize;
  35. internal UniWebViewSnapshotTextureStream(
  36. UniWebView owner,
  37. string webViewName,
  38. long streamId,
  39. Rect rect,
  40. float refreshInterval,
  41. Action<Texture2D> onReady
  42. ) {
  43. this.owner = owner;
  44. WebViewName = webViewName;
  45. StreamId = streamId;
  46. Rect = rect;
  47. RefreshInterval = refreshInterval;
  48. this.onReady = onReady;
  49. }
  50. /// <summary>
  51. /// The live texture updated in place by this stream. It is <c>null</c> until the first native frame is uploaded.
  52. /// </summary>
  53. public Texture2D Texture { get; private set; }
  54. /// <summary>
  55. /// Whether the stream has received its first usable native texture frame.
  56. /// </summary>
  57. public bool IsReady { get; private set; }
  58. /// <summary>
  59. /// The current stream texture width in pixels.
  60. /// </summary>
  61. public int Width { get; private set; }
  62. /// <summary>
  63. /// The current stream texture height in pixels.
  64. /// </summary>
  65. public int Height { get; private set; }
  66. /// <summary>
  67. /// The local web view rectangle captured by this stream.
  68. /// </summary>
  69. public Rect Rect { get; }
  70. /// <summary>
  71. /// The latest uploaded frame index.
  72. /// </summary>
  73. public long FrameIndex { get; private set; }
  74. internal string WebViewName { get; }
  75. internal long StreamId { get; }
  76. internal float RefreshInterval { get; }
  77. internal bool IsStopped => stopped;
  78. /// <summary>
  79. /// Stops the stream and releases the stream-owned texture.
  80. /// </summary>
  81. public void Stop() {
  82. if (stopped) {
  83. return;
  84. }
  85. owner.StopSnapshotTextureStream(this);
  86. }
  87. /// <summary>
  88. /// Stops the stream and releases the stream-owned texture.
  89. /// </summary>
  90. public void Dispose() {
  91. Stop();
  92. }
  93. internal void MarkStoppedByOwner() {
  94. if (stopped) {
  95. return;
  96. }
  97. stopped = true;
  98. IsReady = false;
  99. Width = 0;
  100. Height = 0;
  101. FrameIndex = 0;
  102. onReady = null;
  103. if (Texture != null) {
  104. DestroyTexture(Texture);
  105. Texture = null;
  106. }
  107. if (cpuFrameBuffer != IntPtr.Zero) {
  108. Marshal.FreeHGlobal(cpuFrameBuffer);
  109. cpuFrameBuffer = IntPtr.Zero;
  110. cpuFrameBufferSize = 0;
  111. }
  112. }
  113. internal void UpdateTexture(IntPtr nativeTexturePtr, int width, int height, long frameIndex) {
  114. if (stopped || nativeTexturePtr == IntPtr.Zero || width <= 0 || height <= 0) {
  115. return;
  116. }
  117. if (Texture == null || Width != width || Height != height) {
  118. if (Texture != null) {
  119. DestroyTexture(Texture);
  120. }
  121. Texture = Texture2D.CreateExternalTexture(
  122. width, height, UniWebViewInterface.GetSnapshotTextureStreamTextureFormat(), false, false, nativeTexturePtr
  123. );
  124. } else {
  125. Texture.UpdateExternalTexture(nativeTexturePtr);
  126. }
  127. Width = width;
  128. Height = height;
  129. FrameIndex = frameIndex;
  130. IsReady = true;
  131. InvokeOnReadyIfNeeded();
  132. }
  133. // Returns a stream-owned unmanaged buffer sized for a width x height RGBA frame. The native
  134. // side copies the latest frame into it, which avoids exposing native-owned pixel memory whose
  135. // lifetime is not controlled by the main thread.
  136. internal IntPtr PrepareCpuFrameBuffer(int width, int height) {
  137. if (stopped || width <= 0 || height <= 0) {
  138. return IntPtr.Zero;
  139. }
  140. var size = width * height * 4;
  141. if (cpuFrameBuffer == IntPtr.Zero) {
  142. cpuFrameBuffer = Marshal.AllocHGlobal(size);
  143. cpuFrameBufferSize = size;
  144. } else if (cpuFrameBufferSize != size) {
  145. cpuFrameBuffer = Marshal.ReAllocHGlobal(cpuFrameBuffer, (IntPtr)size);
  146. cpuFrameBufferSize = size;
  147. }
  148. return cpuFrameBuffer;
  149. }
  150. internal void UpdateTextureWithCpuFrame(int width, int height, long frameIndex) {
  151. if (stopped || cpuFrameBuffer == IntPtr.Zero || width <= 0 || height <= 0) {
  152. return;
  153. }
  154. var size = width * height * 4;
  155. if (cpuFrameBufferSize != size) {
  156. return;
  157. }
  158. if (Texture == null || Width != width || Height != height) {
  159. if (Texture != null) {
  160. DestroyTexture(Texture);
  161. }
  162. Texture = new Texture2D(
  163. width, height, UniWebViewInterface.GetSnapshotTextureStreamTextureFormat(), false, false
  164. );
  165. }
  166. Texture.LoadRawTextureData(cpuFrameBuffer, size);
  167. Texture.Apply(false, false);
  168. Width = width;
  169. Height = height;
  170. FrameIndex = frameIndex;
  171. IsReady = true;
  172. InvokeOnReadyIfNeeded();
  173. }
  174. private void InvokeOnReadyIfNeeded() {
  175. if (readyActionInvoked || onReady == null) {
  176. return;
  177. }
  178. readyActionInvoked = true;
  179. var action = onReady;
  180. onReady = null;
  181. action(Texture);
  182. }
  183. private static void DestroyTexture(Texture2D texture) {
  184. if (Application.isPlaying) {
  185. Object.Destroy(texture);
  186. } else {
  187. Object.DestroyImmediate(texture);
  188. }
  189. }
  190. }