| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481 |
- //
- // 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<Texture2D> snapshotStartedAction;
- private string snapshotStartedActionIdentifier;
- private bool snapshotStartedActionPending;
- private UniWebViewSnapshotTextureStream activeSnapshotTextureStream;
- private Coroutine snapshotTextureStreamCoroutine;
- private long nextSnapshotTextureStreamId;
- /// <summary>
- /// 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.
- /// </summary>
- /// <param name="fileName">
- /// 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.
- /// </param>
- public void CaptureSnapshot(string fileName) {
- UniWebViewInterface.CaptureSnapshot(listener.Name, fileName);
- }
- /// <summary>
- /// Starts the process of continually rendering the snapshot.
- /// </summary>
- /// <remarks>
- /// <para>
- /// This API is legacy and allocation-heavy. For continuous render-as-texture use, prefer
- /// <see cref="StartSnapshotTextureStream"/>, which exposes one stream-owned texture
- /// updated in place on supported platforms.
- /// </para>
- /// <para>
- /// You take the responsibility of calling this method before you use either <see cref="GetRenderedData(Rect?)"/> or
- /// <see cref="CreateRenderedTexture(Rect?)"/> to get the rendered data or texture. It prepares a render buffer for the image
- /// data and performs the initial rendering for later use.
- /// </para>
- /// <para>
- /// If this method is not called, the related data or texture methods will not work and will only return <c>null</c>. Once you
- /// no longer need the web view to be rendered as a texture, you should call <see cref="StopSnapshotForRendering"/> to clean up
- /// the associated resources.
- /// </para>
- /// </remarks>
- /// <param name="rect">The optional rectangle to specify the area for rendering. If <c>null</c>, the entire view is rendered.</param>
- /// <param name="onStarted">
- /// An optional callback to execute when rendering has started. The callback receives a <see cref="Texture2D"/> parameter
- /// representing the rendered texture.
- /// </param>
- /// <param name="refreshInterval">
- /// The interval in seconds between snapshot refreshes. By default (when not set or set to <c>0</c>), it refreshes
- /// every frame for the best responsiveness. Use a larger value to reduce CPU/GPU usage, for example <c>1.0f/30</c>
- /// for 30 fps or <c>1.0f/10</c> for 10 fps. This is especially useful on Android where snapshot capture runs on
- /// the main thread.
- /// </param>
- [Obsolete(SnapshotRenderingLegacyMessage, false)]
- public void StartSnapshotForRendering(
- Rect? rect = null, Action<Texture2D> onStarted = null, float refreshInterval = 0
- ) {
- StopSnapshotRefreshCoroutine();
- snapshotCachedData = null;
- var identifier = RegisterSnapshotStartedAction(onStarted);
- UniWebViewInterface.StartSnapshotForRendering(listener.Name, identifier);
- snapshotRefreshCoroutine = StartCoroutine(SnapshotRefreshLoop(rect, refreshInterval));
- }
- /// <summary>
- /// Stops the process of continually rendering the snapshot.
- /// </summary>
- /// <remarks>
- /// <para>
- /// This API stops the legacy PNG-backed snapshot rendering path. For continuous render-as-texture use, prefer
- /// <see cref="StartSnapshotTextureStream"/>.
- /// </para>
- /// <para>
- /// You should call this method when you no longer need any further data or texture from the
- /// <see cref="GetRenderedData(Rect?)"/> or <see cref="CreateRenderedTexture(Rect?)"/> methods. This helps in releasing
- /// resources and terminating the rendering process.
- /// </para>
- /// </remarks>
- [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<Texture2D> 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;
- }
- }
- /// <summary>
- /// Gets the data of the rendered image for the current web view.
- /// </summary>
- /// <remarks>
- /// <para>
- /// This API is legacy and returns PNG bytes from the cached legacy snapshot path. For continuous texture display, prefer
- /// <see cref="StartSnapshotTextureStream"/> and use its live texture instead.
- /// </para>
- /// <para>
- /// 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 <see cref="StartSnapshotForRendering"/> to initiate the rendering process.
- /// If <see cref="StartSnapshotForRendering"/> has not been called, this method will return <c>null</c>.
- /// </para>
- /// <para>
- /// The rendering area specified by the <paramref name="rect"/> parameter is based on the local coordinates of the web view.
- /// For example, <c>new Rect(webView.frame.width / 2, webView.frame.height / 2, 100, 100)</c> means setting the origin to the
- /// center of the web view and taking a 100x100 square as the snapshot area.
- /// </para>
- /// <para>
- /// 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.
- /// </para>
- /// </remarks>
- /// <param name="rect">
- /// 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.
- /// </param>
- /// <returns>
- /// An array of raw bytes representing the rendered image data in PNG format, or <c>null</c> if the rendering process fails
- /// or if the data is not prepared.
- /// </returns>
- /// <seealso cref="StartSnapshotForRendering"/>
- [Obsolete(SnapshotRenderingLegacyMessage, false)]
- public byte[] GetRenderedData(Rect? rect = null) {
- return GetRenderedDataFromCache(rect);
- }
- /// <summary>
- /// Creates a rendered texture for the current web view.
- /// </summary>
- /// <remarks>
- /// <para>
- /// This API is legacy and creates a new standalone texture from PNG data every time it is called. For continuous texture
- /// display, prefer <see cref="StartSnapshotTextureStream"/>, assign the stream texture
- /// once, and dispose the stream during cleanup.
- /// </para>
- /// <para>
- /// You should destroy the returned texture using the `Destroy` method when you no longer need it to free up resources.
- /// </para>
- /// <para>
- /// 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 <see cref="StartSnapshotForRendering"/> before using this method.
- /// If <see cref="StartSnapshotForRendering"/> has not been called, this method will return <c>null</c>.
- /// </para>
- /// <para>
- /// 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.
- /// </para>
- /// <para>
- /// This method returns a plain <see cref="Texture2D"/> 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.
- /// </para>
- /// </remarks>
- /// <param name="rect">
- /// 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.
- /// </param>
- /// <returns>
- /// A rendered texture of the current web view, or <c>null</c> if the rendering process fails or if the data is not prepared.
- /// </returns>
- /// <seealso cref="StartSnapshotForRendering"/>
- [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;
- }
- /// <summary>
- /// Starts a live snapshot texture stream for this web view.
- /// </summary>
- /// <remarks>
- /// <para>
- /// 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 <paramref name="onReady"/> and dispose the returned
- /// stream when it is no longer needed.
- /// </para>
- /// <para>
- /// 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: <see cref="UniWebViewSnapshotTextureStream.Texture"/>
- /// is <c>null</c>, <see cref="UniWebViewSnapshotTextureStream.IsReady"/> is <c>false</c>, and
- /// <paramref name="onReady"/> is not called. The stream API never falls back to the legacy PNG-backed texture path.
- /// </para>
- /// <para>
- /// 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.
- /// </para>
- /// </remarks>
- /// <param name="rect">The optional rectangle to capture. If <c>null</c>, the entire web view is captured.</param>
- /// <param name="refreshInterval">
- /// The interval in seconds between snapshot refreshes. Use <c>0</c> to refresh as fast as the internal scheduler
- /// safely allows.
- /// </param>
- /// <param name="onReady">An optional callback invoked once after the first native texture frame is ready.</param>
- /// <param name="resolutionScale">
- /// The scale applied to the capture resolution, in the <c>(0, 1]</c> range. Use <c>1</c> (the default) to capture
- /// at full resolution. Use a smaller value such as <c>0.5f</c> 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.
- /// </param>
- /// <returns>The created snapshot texture stream.</returns>
- public UniWebViewSnapshotTextureStream StartSnapshotTextureStream(
- Rect? rect = null, float refreshInterval = 0, Action<Texture2D> 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<Texture2D> 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<Texture2D> onReady,
- Func<UniWebViewSnapshotTextureStream, bool> 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);
- }
- }
|