// // UniWebView.Snapshot.cs // Created by Wang Wei (@onevcat) on 2025-04-19. // // This file is a part of UniWebView Project (https://uniwebview.com) // By purchasing the asset, you are allowed to use this code in as many as projects // you want, only if you publish the final products under the name of the same account // used for the purchase. // // This asset and all corresponding files (such as source code) are provided on an // "as is" basis, without warranty of any kind, express of implied, including but not // limited to the warranties of merchantability, fitness for a particular purpose, and // noninfringement. In no event shall the authors or copyright holders be liable for any // claim, damages or other liability, whether in action of contract, tort or otherwise, // arising from, out of or in connection with the software or the use of other dealing in the software. // using UnityEngine; using System; using System.Collections; using System.Threading.Tasks; public partial class UniWebView { private const string SnapshotRenderingLegacyMessage = "The snapshot rendering APIs are legacy and allocate heavily. " + "Use StartSnapshotTextureStream instead. See the render-as-texture migration guide."; private static readonly Rect snapshotFullViewRect = new Rect(-1, -1, -1, -1); private byte[] snapshotCachedData; private Coroutine snapshotRefreshCoroutine; private Action snapshotStartedAction; private string snapshotStartedActionIdentifier; private bool snapshotStartedActionPending; private UniWebViewSnapshotTextureStream activeSnapshotTextureStream; private Coroutine snapshotTextureStreamCoroutine; private long nextSnapshotTextureStreamId; /// /// Capture the content of web view and store it to the cache path on disk with the given file name. /// /// When the capturing finishes, `OnCaptureSnapshotFinished` event will be raised, with an error code to indicate /// whether the operation succeeded and an accessible disk path of the image. /// /// The captured image will be stored as a PNG file under the `fileName` in app's cache folder. If a file with the /// same file name already exists, it will be overridden by the new captured image. /// /// /// The file name to which the captured image is stored to, for example "screenshot.png". If empty, UniWebView will /// pick a random UUID with "png" file extension as the file name. /// public void CaptureSnapshot(string fileName) { UniWebViewInterface.CaptureSnapshot(listener.Name, fileName); } /// /// Starts the process of continually rendering the snapshot. /// /// /// /// This API is legacy and allocation-heavy. For continuous render-as-texture use, prefer /// , which exposes one stream-owned texture /// updated in place on supported platforms. /// /// /// You take the responsibility of calling this method before you use either or /// to get the rendered data or texture. It prepares a render buffer for the image /// data and performs the initial rendering for later use. /// /// /// If this method is not called, the related data or texture methods will not work and will only return null. Once you /// no longer need the web view to be rendered as a texture, you should call to clean up /// the associated resources. /// /// /// The optional rectangle to specify the area for rendering. If null, the entire view is rendered. /// /// An optional callback to execute when rendering has started. The callback receives a parameter /// representing the rendered texture. /// /// /// The interval in seconds between snapshot refreshes. By default (when not set or set to 0), it refreshes /// every frame for the best responsiveness. Use a larger value to reduce CPU/GPU usage, for example 1.0f/30 /// for 30 fps or 1.0f/10 for 10 fps. This is especially useful on Android where snapshot capture runs on /// the main thread. /// [Obsolete(SnapshotRenderingLegacyMessage, false)] public void StartSnapshotForRendering( Rect? rect = null, Action onStarted = null, float refreshInterval = 0 ) { StopSnapshotRefreshCoroutine(); snapshotCachedData = null; var identifier = RegisterSnapshotStartedAction(onStarted); UniWebViewInterface.StartSnapshotForRendering(listener.Name, identifier); snapshotRefreshCoroutine = StartCoroutine(SnapshotRefreshLoop(rect, refreshInterval)); } /// /// Stops the process of continually rendering the snapshot. /// /// /// /// This API stops the legacy PNG-backed snapshot rendering path. For continuous render-as-texture use, prefer /// . /// /// /// You should call this method when you no longer need any further data or texture from the /// or methods. This helps in releasing /// resources and terminating the rendering process. /// /// [Obsolete(SnapshotRenderingLegacyMessage, false)] public void StopSnapshotForRendering() { StopSnapshotRefreshCoroutine(); snapshotCachedData = null; ClearSnapshotStartedAction(); UniWebViewInterface.StopSnapshotForRendering(listener.Name); } private IEnumerator SnapshotRefreshLoop(Rect? rect, float interval) { var r = rect ?? snapshotFullViewRect; var useEveryFrame = interval <= 0; var wait = useEveryFrame ? null : new WaitForSeconds(interval); while (true) { yield return wait; var data = UniWebViewInterface.GetRenderedData( listener.Name, (int)r.x, (int)r.y, (int)r.width, (int)r.height ); if (data != null) { snapshotCachedData = data; TryInvokeSnapshotStartedAction(); } } } private void TryInvokeSnapshotStartedAction() { if (!snapshotStartedActionPending || snapshotStartedAction == null || snapshotCachedData == null) { return; } var action = snapshotStartedAction; ClearSnapshotStartedAction(); action(CreateRenderedTextureFromCachedData()); } private string RegisterSnapshotStartedAction(Action action) { ClearSnapshotStartedAction(); if (action == null) { return null; } var identifier = Guid.NewGuid().ToString(); snapshotStartedAction = action; snapshotStartedActionIdentifier = identifier; actions.Add(identifier, () => { if (snapshotStartedActionIdentifier != identifier) { return; } snapshotStartedActionPending = true; TryInvokeSnapshotStartedAction(); }); return identifier; } private void ClearSnapshotStartedAction() { if (snapshotStartedActionIdentifier != null) { actions.Remove(snapshotStartedActionIdentifier); } snapshotStartedAction = null; snapshotStartedActionIdentifier = null; snapshotStartedActionPending = false; } private void StopSnapshotRefreshCoroutine() { if (snapshotRefreshCoroutine != null) { StopCoroutine(snapshotRefreshCoroutine); snapshotRefreshCoroutine = null; } } /// /// Gets the data of the rendered image for the current web view. /// /// /// /// This API is legacy and returns PNG bytes from the cached legacy snapshot path. For continuous texture display, prefer /// and use its live texture instead. /// /// /// This method provides you with the raw bytes of the rendered image data in PNG format. To successfully retrieve the /// current rendered data, you should first call to initiate the rendering process. /// If has not been called, this method will return null. /// /// /// The rendering area specified by the parameter is based on the local coordinates of the web view. /// For example, new Rect(webView.frame.width / 2, webView.frame.height / 2, 100, 100) means setting the origin to the /// center of the web view and taking a 100x100 square as the snapshot area. /// /// /// Please note that this method supports only software-rendered content. Content rendered by hardware, such as videos /// and WebGL content, will appear as a black rectangle in the rendered image. /// /// /// /// The desired rectangle within which the snapshot rendering should occur in the web view. If default value `null` is used, /// the whole web view frame will be used as the snapshot area. /// /// /// An array of raw bytes representing the rendered image data in PNG format, or null if the rendering process fails /// or if the data is not prepared. /// /// [Obsolete(SnapshotRenderingLegacyMessage, false)] public byte[] GetRenderedData(Rect? rect = null) { return GetRenderedDataFromCache(rect); } /// /// Creates a rendered texture for the current web view. /// /// /// /// This API is legacy and creates a new standalone texture from PNG data every time it is called. For continuous texture /// display, prefer , assign the stream texture /// once, and dispose the stream during cleanup. /// /// /// You should destroy the returned texture using the `Destroy` method when you no longer need it to free up resources. /// /// /// This method provides you with a texture of the rendered image for the web view, which you can use in your 3D game world. /// To obtain the current rendered data, you should call before using this method. /// If has not been called, this method will return null. /// /// /// Please note that this method supports only software-rendered content. Content rendered by hardware, such as videos /// and WebGL content, will appear as a black rectangle in the rendered image. /// /// /// This method returns a plain object. The texture is not user interactive and can only be used for /// display purposes. It is your responsibility to call the `Destroy` method on this texture when you no longer need it. /// /// /// /// The desired rectangle within which the snapshot rendering should occur in the web view. If default value `null` is used, /// the whole web view frame will be used as the snapshot area. /// /// /// A rendered texture of the current web view, or null if the rendering process fails or if the data is not prepared. /// /// [Obsolete(SnapshotRenderingLegacyMessage, false)] public Texture2D CreateRenderedTexture(Rect? rect = null) { return CreateRenderedTextureFromCachedData(rect); } private byte[] GetRenderedDataFromCache(Rect? rect = null) { return snapshotCachedData; } private Texture2D CreateRenderedTextureFromCachedData(Rect? rect = null) { var bytes = GetRenderedDataFromCache(rect); if (bytes == null) { return null; } Texture2D texture = new Texture2D(2, 2, TextureFormat.RGB24, false); texture.LoadImage(bytes); return texture; } /// /// Starts a live snapshot texture stream for this web view. /// /// /// /// This is the supported API for continuously showing web view snapshots in Unity. It creates one stream-owned /// texture and updates it in place. Assign the texture once in and dispose the returned /// stream when it is no longer needed. /// /// /// If the current platform or graphics backend supports neither the optimized native texture stream nor a CPU /// readback fallback, the returned stream remains not ready: /// is null, is false, and /// is not called. The stream API never falls back to the legacy PNG-backed texture path. /// /// /// On Android, the optimized native texture path requires OpenGL ES 2 or OpenGL ES 3. When Unity runs on another /// graphics API such as Vulkan, the stream automatically falls back to a CPU readback path that updates the /// stream-owned texture from the captured frame data. The public behavior is identical, but the per-frame cost is /// higher than the native texture path, so prefer OpenGL ES when the stream performance matters. /// /// /// The optional rectangle to capture. If null, the entire web view is captured. /// /// The interval in seconds between snapshot refreshes. Use 0 to refresh as fast as the internal scheduler /// safely allows. /// /// An optional callback invoked once after the first native texture frame is ready. /// /// The scale applied to the capture resolution, in the (0, 1] range. Use 1 (the default) to capture /// at full resolution. Use a smaller value such as 0.5f to reduce the capture and upload cost per frame, at /// the price of a softer image. Values out of the range are clamped. This currently only takes effect on iOS and /// macOS; Android always captures at full resolution. /// /// The created snapshot texture stream. public UniWebViewSnapshotTextureStream StartSnapshotTextureStream( Rect? rect = null, float refreshInterval = 0, Action onReady = null, float resolutionScale = 1.0f ) { var clampedResolutionScale = ClampSnapshotTextureStreamResolutionScale(resolutionScale); return StartSnapshotTextureStream( rect, refreshInterval, onReady, stream => UniWebViewInterface.StartSnapshotTextureStream( listener.Name, stream.StreamId, (int)stream.Rect.x, (int)stream.Rect.y, (int)stream.Rect.width, (int)stream.Rect.height, clampedResolutionScale ) ); } internal static float ClampSnapshotTextureStreamResolutionScale(float resolutionScale) { if (resolutionScale <= 0) { return 1.0f; } return Mathf.Clamp(resolutionScale, 0.1f, 1.0f); } internal UniWebViewSnapshotTextureStream StartSnapshotTextureStreamWithSyntheticFrames( int width, int height, int framePattern, float refreshInterval = 0, Action onReady = null ) { var rect = new Rect(0, 0, width, height); return StartSnapshotTextureStream( rect, refreshInterval, onReady, stream => UniWebViewInterface.StartSnapshotTextureStreamWithSyntheticFrames( listener.Name, stream.StreamId, width, height, framePattern ) ); } private UniWebViewSnapshotTextureStream StartSnapshotTextureStream( Rect? rect, float refreshInterval, Action onReady, Func startNativeStream ) { StopActiveSnapshotTextureStream(); var r = rect ?? snapshotFullViewRect; var stream = new UniWebViewSnapshotTextureStream( this, listener.Name, ++nextSnapshotTextureStreamId, r, refreshInterval, onReady ); activeSnapshotTextureStream = stream; if (startNativeStream(stream)) { snapshotTextureStreamCoroutine = StartCoroutine(SnapshotTextureStreamLoop(stream)); } return stream; } internal void StopSnapshotTextureStream(UniWebViewSnapshotTextureStream stream) { if (stream == null) { return; } if (activeSnapshotTextureStream != stream) { stream.MarkStoppedByOwner(); return; } StopSnapshotTextureStreamCoroutine(); UniWebViewInterface.StopSnapshotTextureStream(listener.Name, stream.StreamId); activeSnapshotTextureStream = null; stream.MarkStoppedByOwner(); } private void StopActiveSnapshotTextureStream() { if (activeSnapshotTextureStream != null) { activeSnapshotTextureStream.Stop(); } } private void StopSnapshotTextureStreamCoroutine() { if (snapshotTextureStreamCoroutine != null) { StopCoroutine(snapshotTextureStreamCoroutine); snapshotTextureStreamCoroutine = null; } } private void CleanupSnapshotResources() { StopActiveSnapshotTextureStream(); StopSnapshotRefreshCoroutine(); ClearSnapshotStartedAction(); snapshotCachedData = null; } private IEnumerator SnapshotTextureStreamLoop(UniWebViewSnapshotTextureStream stream) { var nextTickTime = 0.0f; var usesCpuFallback = UniWebViewInterface.SnapshotTextureStreamUsesCpuFallback(); while (activeSnapshotTextureStream == stream && !stream.IsStopped) { yield return null; if (ShouldTickSnapshotTextureStream(stream.RefreshInterval, Time.time, ref nextTickTime)) { UniWebViewInterface.TickSnapshotTextureStream(listener.Name, stream.StreamId); } if (usesCpuFallback) { ConsumeSnapshotTextureStreamCpuFrame(stream); continue; } UniWebViewInterface.PumpSnapshotTextureStream(listener.Name, stream.StreamId); if (!UniWebViewInterface.IsSnapshotTextureStreamReady(listener.Name, stream.StreamId)) { continue; } ApplySnapshotTextureStreamState( stream.StreamId, UniWebViewInterface.GetSnapshotTextureStreamTexturePointer(listener.Name, stream.StreamId), UniWebViewInterface.GetSnapshotTextureStreamWidth(listener.Name, stream.StreamId), UniWebViewInterface.GetSnapshotTextureStreamHeight(listener.Name, stream.StreamId), UniWebViewInterface.GetSnapshotTextureStreamFrameIndex(listener.Name, stream.StreamId) ); } } private void ConsumeSnapshotTextureStreamCpuFrame(UniWebViewSnapshotTextureStream stream) { var width = UniWebViewInterface.GetSnapshotTextureStreamWidth(listener.Name, stream.StreamId); var height = UniWebViewInterface.GetSnapshotTextureStreamHeight(listener.Name, stream.StreamId); if (width <= 0 || height <= 0) { return; } var buffer = stream.PrepareCpuFrameBuffer(width, height); if (buffer == IntPtr.Zero) { return; } // The frame size is re-validated natively against the buffer capacity, so a concurrent // resize between the size query and the copy results in a skipped frame, not a tear. var frameIndex = UniWebViewInterface.ConsumeSnapshotTextureStreamCpuFrame( listener.Name, stream.StreamId, buffer, width * height * 4 ); if (frameIndex < 0 || activeSnapshotTextureStream != stream) { return; } stream.UpdateTextureWithCpuFrame(width, height, frameIndex); } internal static bool ShouldTickSnapshotTextureStream(float refreshInterval, float now, ref float nextTickTime) { if (refreshInterval <= 0) { nextTickTime = now; return true; } if (now < nextTickTime) { return false; } nextTickTime = now + refreshInterval; return true; } private void ApplySnapshotTextureStreamState( long streamId, IntPtr nativeTexturePtr, int width, int height, long frameIndex ) { if (activeSnapshotTextureStream == null || activeSnapshotTextureStream.StreamId != streamId) { return; } activeSnapshotTextureStream.UpdateTexture(nativeTexturePtr, width, height, frameIndex); } }