ARKitCameraSubsystem.cs 35.6 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Unity.Collections;
using UnityEngine.Rendering;
#if MODULE_URP_ENABLED
using UnityEngine.Rendering.Universal;
#endif // MODULE_URP_ENABLED
#if MODULE_LWRP_ENABLED
using UnityEngine.Rendering.LWRP;
#endif // MODULE_LWRP_ENABLED
using UnityEngine.Scripting;
using UnityEngine.XR.ARSubsystems;

namespace UnityEngine.XR.ARKit
{
    /// <summary>
    /// The camera subsystem implementation for ARKit.
    /// </summary>
    [Preserve]
    public sealed class ARKitCameraSubsystem : XRCameraSubsystem
    {
        /// <summary>
        /// The identifying name for the camera-providing implementation.
        /// </summary>
        /// <value>
        /// The identifying name for the camera-providing implementation.
        /// </value>
        const string k_SubsystemId = "ARKit-Camera";

        /// <summary>
        /// The name for the shader for rendering the camera texture.
        /// </summary>
        /// <value>
        /// The name for the shader for rendering the camera texture.
        /// </value>
        const string k_BackgroundShaderName = "Unlit/ARKitBackground";

        /// <summary>
        /// The shader keyword for enabling LWRP rendering.
        /// </summary>
        /// <value>
        /// The shader keyword for enabling LWRP rendering.
        /// </value>
        const string k_BackgroundShaderKeywordLWRP = "ARKIT_BACKGROUND_LWRP";

        /// <summary>
        /// The shader keyword for enabling URP rendering.
        /// </summary>
        /// <value>
        /// The shader keyword for enabling URP rendering.
        /// </value>
        const string k_BackgroundShaderKeywordURP = "ARKIT_BACKGROUND_URP";

        /// <summary>
        /// The list of shader keywords to avoid during compilation.
        /// </summary>
        /// <value>
        /// The list of shader keywords to avoid during compilation.
        /// </value>
        static readonly List<string> k_BackgroundShaderKeywordsToNotCompile = new List<string> {
#if !MODULE_URP_ENABLED
            k_BackgroundShaderKeywordURP,
#endif // !MODULE_URP_ENABLED
#if !MODULE_LWRP_ENABLED
            k_BackgroundShaderKeywordLWRP,
#endif // !MODULE_LWRP_ENABLED
        };

        /// <summary>
        /// Resulting values from setting the camera configuration.
        /// </summary>
        enum CameraConfigurationResult
        {
            /// <summary>
            /// Setting the camera configuration was successful.
            /// </summary>
            Success = 0,

            /// <summary>
            /// Setting camera configuration was not supported by the provider.
            /// </summary>
            Unsupported = 1,

            /// <summary>
            /// The given camera configuration was not valid to be set by the provider.
            /// </summary>
            InvalidCameraConfiguration = 2,

            /// <summary>
            /// The provider session was invalid.
            /// </summary>
            InvalidSession = 3,
        }

        /// <summary>
        /// The name for the background shader.
        /// </summary>
        /// <value>
        /// The name for the background shader.
        /// </value>
        public static string backgroundShaderName => k_BackgroundShaderName;

        /// <summary>
        /// The list of shader keywords to avoid during compilation.
        /// </summary>
        /// <value>
        /// The list of shader keywords to avoid during compilation.
        /// </value>
        internal static List<string> backgroundShaderKeywordsToNotCompile => k_BackgroundShaderKeywordsToNotCompile;

        /// <summary>
        /// Create and register the camera subsystem descriptor to advertise a providing implementation for camera
        /// functionality.
        /// </summary>
        [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]
        static void Register()
        {
#if UNITY_IOS && !UNITY_EDITOR
            XRCameraSubsystemCinfo cameraSubsystemCinfo = new XRCameraSubsystemCinfo
            {
                id = k_SubsystemId,
                implementationType = typeof(ARKitCameraSubsystem),
                supportsAverageBrightness = false,
                supportsAverageColorTemperature = true,
                supportsColorCorrection = false,
                supportsDisplayMatrix = true,
                supportsProjectionMatrix = true,
                supportsTimestamp = true,
                supportsCameraConfigurations = true,
                supportsCameraImage = true,
                supportsAverageIntensityInLumens = true,
                supportsFocusModes = true,
            };

            if (!XRCameraSubsystem.Register(cameraSubsystemCinfo))
            {
                Debug.LogErrorFormat("Cannot register the {0} subsystem", k_SubsystemId);
            }
#endif // UNITY_IOS && !UNITY_EDITOR
        }

        /// <summary>
        /// Create the ARKit camera functionality provider for the camera subsystem.
        /// </summary>
        /// <returns>
        /// The ARKit camera functionality provider for the camera subsystem.
        /// </returns>
        protected override Provider CreateProvider() => new ARKitProvider();

        /// <summary>
        /// Provides the camera functionality for the ARKit implementation.
        /// </summary>
        class ARKitProvider : Provider
        {
            /// <summary>
            /// The shader property name for the luminance component of the camera video frame.
            /// </summary>
            /// <value>
            /// The shader property name for the luminance component of the camera video frame.
            /// </value>
            const string k_TextureYPropertyName = "_textureY";

            /// <summary>
            /// The shader property name for the chrominance components of the camera video frame.
            /// </summary>
            /// <value>
            /// The shader property name for the chrominance components of the camera video frame.
            /// </value>
            const string k_TextureCbCrPropertyName = "_textureCbCr";

            /// <summary>
            /// The shader property name identifier for the luminance component of the camera video frame.
            /// </summary>
            /// <value>
            /// The shader property name identifier for the luminance component of the camera video frame.
            /// </value>
            static readonly int k_TextureYPropertyNameId = Shader.PropertyToID(k_TextureYPropertyName);

            /// <summary>
            /// The shader property name identifier for the chrominance components of the camera video frame.
            /// </summary>
            /// <value>
            /// The shader property name identifier for the chrominance components of the camera video frame.
            /// </value>
            static readonly int k_TextureCbCrPropertyNameId = Shader.PropertyToID(k_TextureCbCrPropertyName);

            /// <summary>
            /// The shader keywords to enable when the Legacy RP is enabled.
            /// </summary>
            /// <value>
            /// The shader keywords to enable when the Legacy RP is enabled.
            /// </value>
            static readonly List<string> k_LegacyRPEnabledMaterialKeywords = null;

            /// <summary>
            /// The shader keywords to disable when the Legacy RP is enabled.
            /// </summary>
            /// <value>
            /// The shader keywords to disable when the Legacy RP is enabled.
            /// </value>
            static readonly List<string> k_LegacyRPDisabledMaterialKeywords = new List<string>() {k_BackgroundShaderKeywordLWRP, k_BackgroundShaderKeywordURP};

#if MODULE_URP_ENABLED
            /// <summary>
            /// The shader keywords to enable when URP is enabled.
            /// </summary>
            /// <value>
            /// The shader keywords to enable when URP is enabled.
            /// </value>
            static readonly List<string> k_URPEnabledMaterialKeywords = new List<string>() {k_BackgroundShaderKeywordURP};

            /// <summary>
            /// The shader keywords to disable when URP is enabled.
            /// </summary>
            /// <value>
            /// The shader keywords to disable when URP is enabled.
            /// </value>
            static readonly List<string> k_URPDisabledMaterialKeywords = new List<string>() {k_BackgroundShaderKeywordLWRP};
#endif // MODULE_URP_ENABLED

#if MODULE_LWRP_ENABLED
            /// <summary>
            /// The shader keywords to enable when LWRP is enabled.
            /// </summary>
            /// <value>
            /// The shader keywords to enable when LWRP is enabled.
            /// </value>
            static readonly List<string> k_LWRPEnabledMaterialKeywords = new List<string>() {k_BackgroundShaderKeywordLWRP};

            /// <summary>
            /// The shader keywords to disable when LWRP is enabled.
            /// </summary>
            /// <value>
            /// The shader keywords to disable when LWRP is enabled.
            /// </value>
            static readonly List<string> k_LWRPDisabledMaterialKeywords = new List<string>() {k_BackgroundShaderKeywordURP};
#endif // MODULE_LWRP_ENABLED

            /// <summary>
            /// Get the material used by <c>XRCameraSubsystem</c> to render the camera texture.
            /// </summary>
            /// <returns>
            /// The material to render the camera texture.
            /// </returns>
            public override Material cameraMaterial => m_CameraMaterial;
            Material m_CameraMaterial;

            /// <summary>
            /// Whether camera permission has been granted.
            /// </summary>
            /// <value>
            /// <c>true</c> if camera permission has been granted for this app. Otherwise, <c>false</c>.
            /// </value>
            public override bool permissionGranted => NativeApi.UnityARKit_Camera_IsCameraPermissionGranted();

            /// <summary>
            /// Constructs the ARKit camera functionality provider.
            /// </summary>
            public ARKitProvider()
            {
                NativeApi.UnityARKit_Camera_Construct(k_TextureYPropertyNameId,
                                                      k_TextureCbCrPropertyNameId);

                string shaderName = ARKitCameraSubsystem.backgroundShaderName;
                if (shaderName == null)
                {
                    Debug.LogError("Cannot create camera background material compatible with the render pipeline");
                }
                else
                {
                    m_CameraMaterial = CreateCameraMaterial(shaderName);
                }
            }

            /// <summary>
            /// Start the camera functionality.
            /// </summary>
            public override void Start() => NativeApi.UnityARKit_Camera_Start();

            /// <summary>
            /// Stop the camera functionality.
            /// </summary>
            public override void Stop() => NativeApi.UnityARKit_Camera_Stop();

            /// <summary>
            /// Destroy any resources required for the camera functionality.
            /// </summary>
            public override void Destroy() => NativeApi.UnityARKit_Camera_Destruct();

            /// <summary>
            /// Get the current camera frame for the subsystem.
            /// </summary>
            /// <param name="cameraParams">The current Unity <c>Camera</c> parameters.</param>
            /// <param name="cameraFrame">The current camera frame returned by the method.</param>
            /// <returns>
            /// <c>true</c> if the method successfully got a frame. Otherwise, <c>false</c>.
            /// </returns>
            public override bool TryGetFrame(XRCameraParams cameraParams, out XRCameraFrame cameraFrame)
            {
                return NativeApi.UnityARKit_Camera_TryGetFrame(cameraParams, out cameraFrame);
            }

            /// <summary>
            /// Set the focus mode for the camera.
            /// </summary>
            /// <param name="cameraFocusMode">The focus mode to set for the camera.</param>
            /// <returns>
            /// <c>true</c> if the method successfully set the focus mode for the camera. Otherwise, <c>false</c>.
            /// </returns>
            public override CameraFocusMode cameraFocusMode
            {
                get => NativeApi.UnityARKit_Camera_GetFocusMode();
                set => NativeApi.UnityARKit_Camera_SetFocusMode(value);
            }

            /// <summary>
            /// Set the light estimation mode.
            /// </summary>
            /// <param name="lightEstimationMode">The light estimation mode to set.</param>
            /// <returns>
            /// <c>true</c> if the method successfully set the light estimation mode. Otherwise, <c>false</c>.
            /// </returns>
            public override bool TrySetLightEstimationMode(LightEstimationMode lightEstimationMode)
            {
                return NativeApi.UnityARKit_Camera_TrySetLightEstimationMode(lightEstimationMode);
            }

            /// <summary>
            /// Get the camera intrinisics information.
            /// </summary>
            /// <param name="cameraIntrinsics">The camera intrinsics information returned from the method.</param>
            /// <returns>
            /// <c>true</c> if the method successfully gets the camera intrinsics information. Otherwise, <c>false</c>.
            /// </returns>
            public override bool TryGetIntrinsics(out XRCameraIntrinsics cameraIntrinsics)
            {
                return NativeApi.UnityARKit_Camera_TryGetIntrinsics(out cameraIntrinsics);
            }

            /// <summary>
            /// Queries the supported camera configurations.
            /// </summary>
            /// <param name="defaultCameraConfiguration">A default value used to fill the returned array before copying
            /// in real values. This ensures future additions to this struct are backwards compatible.</param>
            /// <param name="allocator">The allocation strategy to use for the returned data.</param>
            /// <returns>
            /// The supported camera configurations.
            /// </returns>
            public override NativeArray<XRCameraConfiguration> GetConfigurations(XRCameraConfiguration defaultCameraConfiguration,
                                                                                 Allocator allocator)
            {
                int configurationsCount;
                int configurationSize;
                IntPtr configurations = NativeApi.UnityARKit_Camera_AcquireConfigurations(out configurationsCount,
                                                                                          out configurationSize);

                try
                {
                    unsafe
                    {
                        return NativeCopyUtility.PtrToNativeArrayWithDefault(defaultCameraConfiguration,
                                                                             (void*)configurations,
                                                                             configurationSize, configurationsCount,
                                                                             allocator);
                    }
                }
                finally
                {
                    NativeApi.UnityARKit_Camera_ReleaseConfigurations(configurations);
                }
            }

            /// <summary>
            /// The current camera configuration.
            /// </summary>
            /// <value>
            /// The current camera configuration if it exists. Otherise, <c>null</c>.
            /// </value>
            /// <exception cref="System.ArgumentException">Thrown when setting the current configuration if the given
            /// configuration is not a valid, supported camera configuration.</exception>
            /// <exception cref="System.InvalidOperationException">Thrown when setting the current configuration if the
            /// implementation is unable to set the current camera configuration for various reasons such as:
            /// <list type="bullet">
            /// <item><description>Version of iOS does not support camera configurations</description></item>
            /// <item><description>ARKit session is invalid</description></item>
            /// </list>
            /// </exception>
            public override XRCameraConfiguration? currentConfiguration
            {
                get
                {
                    XRCameraConfiguration cameraConfiguration;
                    if (NativeApi.UnityARKit_Camera_TryGetCurrentConfiguration(out cameraConfiguration))
                    {
                        return cameraConfiguration;
                    }

                    return null;
                }
                set
                {
                    // Assert that the camera configuration is not null.
                    // The XRCameraSubsystem should have already checked this.
                    Debug.Assert(value != null, "Cannot set the current camera configuration to null");

                    switch (NativeApi.UnityARKit_Camera_TrySetCurrentConfiguration((XRCameraConfiguration)value))
                    {
                        case CameraConfigurationResult.Success:
                            break;
                        case CameraConfigurationResult.Unsupported:
                            throw new InvalidOperationException("cannot set camera configuration because ARKit version "
                                                                + "does not support camera configurations");
                        case CameraConfigurationResult.InvalidCameraConfiguration:
                            throw new ArgumentException("camera configuration does not exist in the available "
                                                        + "configurations", "value");
                        case CameraConfigurationResult.InvalidSession:
                            throw new InvalidOperationException("cannot set camera configuration because the ARKit "
                                                                + "session is not valid");
                        default:
                            throw new InvalidOperationException("cannot set camera configuration for ARKit");
                    }
                }
            }

            /// <summary>
            /// Gets the texture descriptors associated with th current camera
            /// frame.
            /// </summary>
            /// <param name="defaultDescriptor">Default descriptor.</param>
            /// <param name="allocator">Allocator.</param>
            /// <returns>The texture descriptors.</returns>
            public unsafe override NativeArray<XRTextureDescriptor> GetTextureDescriptors(
                XRTextureDescriptor defaultDescriptor,
                Allocator allocator)
            {
                int length, elementSize;
                var textureDescriptors = NativeApi.UnityARKit_Camera_AcquireTextureDescriptors(
                    out length, out elementSize);

                try
                {
                    return NativeCopyUtility.PtrToNativeArrayWithDefault(
                        defaultDescriptor,
                        textureDescriptors, elementSize, length, allocator);
                }
                finally
                {
                    NativeApi.UnityARKit_Camera_ReleaseTextureDescriptors(textureDescriptors);
                }
            }

            /// <summary>
            /// Get the enabled and disabled shader keywords for the material.
            /// </summary>
            /// <param name="enabledKeywords">The keywords to enable for the material.</param>
            /// <param name="disabledKeywords">The keywords to disable for the material.</param>
            public override void GetMaterialKeywords(out List<string> enabledKeywords, out List<string> disabledKeywords)
            {
                if (GraphicsSettings.renderPipelineAsset == null)
                {
                    enabledKeywords = k_LegacyRPEnabledMaterialKeywords;
                    disabledKeywords = k_LegacyRPDisabledMaterialKeywords;
                }
#if MODULE_URP_ENABLED
                else if (GraphicsSettings.renderPipelineAsset is UniversalRenderPipelineAsset)
                {
                    enabledKeywords = k_URPEnabledMaterialKeywords;
                    disabledKeywords = k_URPDisabledMaterialKeywords;
                }
#endif // MODULE_URP_ENABLED
#if MODULE_LWRP_ENABLED
                else if (GraphicsSettings.renderPipelineAsset is LightweightRenderPipelineAsset)
                {
                    enabledMaterialKeywords = k_LWRPEnabledMaterialKeywords;
                    disabledKeywords = k_LWRPDisabledMaterialKeywords;
                }
#endif // MODULE_LWRP_ENABLED
                else
                {
                    enabledKeywords = null;
                    disabledKeywords = null;
                }
            }

            /// <summary>
            /// Query for the latest native camera image.
            /// </summary>
            /// <param name="cameraImageCinfo">The metadata required to construct a <see cref="XRCameraImage"/></param>
            /// <returns>
            /// <c>true</c> if the camera image is acquired. Otherwise, <c>false</c>.
            /// </returns>
            public override bool TryAcquireLatestImage(out CameraImageCinfo cameraImageCinfo)
            {
                return NativeApi.UnityARKit_Camera_TryAcquireLatestImage(out cameraImageCinfo);
            }

            /// <summary>
            /// Get the status of an existing asynchronous conversion request.
            /// </summary>
            /// <param name="requestId">The unique identifier associated with a request.</param>
            /// <returns>The state of the request.</returns>
            /// <seealso cref="ConvertAsync(int, XRCameraImageConversionParams)"/>
            public override AsyncCameraImageConversionStatus GetAsyncRequestStatus(int requestId)
            {
                return NativeApi.UnityARKit_Camera_GetAsyncRequestStatus(requestId);
            }

            /// <summary>
            /// Dispose an existing native image identified by <paramref name="nativeHandle"/>.
            /// </summary>
            /// <param name="nativeHandle">A unique identifier for this camera image.</param>
            /// <seealso cref="TryAcquireLatestImage"/>
            public override void DisposeImage(int nativeHandle) => NativeApi.UnityARKit_Camera_DisposeImage(nativeHandle);

            /// <summary>
            /// Dispose an existing async conversion request.
            /// </summary>
            /// <param name="requestId">A unique identifier for the request.</param>
            /// <seealso cref="ConvertAsync(int, XRCameraImageConversionParams)"/>
            public override void DisposeAsyncRequest(int requestId) => NativeApi.UnityARKit_Camera_DisposeAsyncRequest(requestId);

            /// <summary>
            /// Get information about an image plane from a native image handle by index.
            /// </summary>
            /// <param name="nativeHandle">A unique identifier for this camera image.</param>
            /// <param name="planeIndex">The index of the plane to get.</param>
            /// <param name="planeCinfo">The returned camera plane information if successful.</param>
            /// <returns>
            /// <c>true</c> if the image plane was acquired. Otherwise, <c>false</c>.
            /// </returns>
            /// <seealso cref="TryAcquireLatestImage"/>
            public override bool TryGetPlane(
                int nativeHandle,
                int planeIndex,
                out CameraImagePlaneCinfo planeCinfo)
            {
               return NativeApi.UnityARKit_Camera_TryGetPlane(nativeHandle, planeIndex, out planeCinfo);
            }

            /// <summary>
            /// Determine whether a native image handle returned by <see cref="TryAcquireLatestImage"/> is currently
            /// valid. An image may become invalid if it has been disposed.
            /// </summary>
            /// <remarks>
            /// If a handle is valid, <see cref="TryConvert"/> and <see cref="TryGetConvertedDataSize"/> should not fail.
            /// </remarks>
            /// <param name="nativeHandle">A unique identifier for the camera image in question.</param>
            /// <returns><c>true</c>, if it is a valid handle. Otherwise, <c>false</c>.</returns>
            /// <seealso cref="DisposeImage"/>
            public override bool NativeHandleValid(int nativeHandle) => NativeApi.UnityARKit_Camera_HandleValid(nativeHandle);

            /// <summary>
            /// Get the number of bytes required to store an image with the iven dimensions and <c>TextureFormat</c>.
            /// </summary>
            /// <param name="nativeHandle">A unique identifier for the camera image to convert.</param>
            /// <param name="dimensions">The dimensions of the output image.</param>
            /// <param name="format">The <c>TextureFormat</c> for the image.</param>
            /// <param name="size">The number of bytes required to store the converted image.</param>
            /// <returns><c>true</c> if the output <paramref name="size"/> was set.</returns>
            public override bool TryGetConvertedDataSize(
                int nativeHandle,
                Vector2Int dimensions,
                TextureFormat format,
                out int size)
            {
                return NativeApi.UnityARKit_Camera_TryGetConvertedDataSize(nativeHandle, dimensions, format, out size);
            }

            /// <summary>
            /// Convert the image with handle <paramref name="nativeHandle"/> using the provided
            /// <paramref cref="conversionParams"/>.
            /// </summary>
            /// <param name="nativeHandle">A unique identifier for the camera image to convert.</param>
            /// <param name="conversionParams">The parameters to use during the conversion.</param>
            /// <param name="destinationBuffer">A buffer to write the converted image to.</param>
            /// <param name="bufferLength">The number of bytes available in the buffer.</param>
            /// <returns>
            /// <c>true</c> if the image was converted and stored in <paramref name="destinationBuffer"/>.
            /// </returns>
            public override bool TryConvert(
                int nativeHandle,
                XRCameraImageConversionParams conversionParams,
                IntPtr destinationBuffer,
                int bufferLength)
            {
                return NativeApi.UnityARKit_Camera_TryConvert(
                    nativeHandle, conversionParams, destinationBuffer, bufferLength);
            }

            /// <summary>
            /// Create an asynchronous request to convert a camera image, similar to <see cref="TryConvert"/> except
            /// the conversion should happen on a thread other than the calling (main) thread.
            /// </summary>
            /// <param name="nativeHandle">A unique identifier for the camera image to convert.</param>
            /// <param name="conversionParams">The parameters to use during the conversion.</param>
            /// <returns>A unique identifier for this request.</returns>
            public override int ConvertAsync(
                int nativeHandle,
                XRCameraImageConversionParams conversionParams)
            {
                return NativeApi.UnityARKit_Camera_CreateAsyncConversionRequest(nativeHandle, conversionParams);
            }

            /// <summary>
            /// Get a pointer to the image data from a completed asynchronous request. This method should only succeed
            /// if <see cref="GetAsyncRequestStatus"/> returns <see cref="AsyncCameraImageConversionStatus.Ready"/>.
            /// </summary>
            /// <param name="requestId">The unique identifier associated with a request.</param>
            /// <param name="dataPtr">A pointer to the native buffer containing the data.</param>
            /// <param name="dataLength">The number of bytes in <paramref name="dataPtr"/>.</param>
            /// <returns><c>true</c> if <paramref name="dataPtr"/> and <paramref name="dataLength"/> were set and point
            ///  to the image data.</returns>
            public override bool TryGetAsyncRequestData(int requestId, out IntPtr dataPtr, out int dataLength)
            {
                return NativeApi.UnityARKit_Camera_TryGetAsyncRequestData(requestId, out dataPtr, out dataLength);
            }

            /// <summary>
            /// Similar to <see cref="ConvertAsync(int, XRCameraImageConversionParams)"/> but takes a delegate to
            /// invoke when the request is complete, rather than returning a request id.
            /// </summary>
            /// <remarks>
            /// If the first parameter to <paramref name="callback"/> is
            /// <see cref="AsyncCameraImageConversionStatus.Ready"/> then the <c>dataPtr</c> parameter must be valid
            /// for the duration of the invocation. The data may be destroyed immediately upon return. The
            /// <paramref name="context"/> parameter must be passed back to the <paramref name="callback"/>.
            /// </remarks>
            /// <param name="nativeHandle">A unique identifier for the camera image to convert.</param>
            /// <param name="conversionParams">The parameters to use during the conversion.</param>
            /// <param name="callback">A delegate which must be invoked when the request is complete, whether the
            /// conversion was successfully or not.</param>
            /// <param name="context">A native pointer which must be passed back unaltered to
            /// <paramref name="callback"/>.</param>
            public override void ConvertAsync(
                int nativeHandle,
                XRCameraImageConversionParams conversionParams,
                OnImageRequestCompleteDelegate callback,
                IntPtr context)
            {
                NativeApi.UnityARKit_Camera_CreateAsyncConversionRequestWithCallback(
                    nativeHandle, conversionParams, callback, context);
            }

        }

        /// <summary>
        /// Container to wrap the native ARKit camera APIs.
        /// </summary>
        static class NativeApi
        {
            [DllImport("__Internal")]
            public static extern void UnityARKit_Camera_Construct(int textureYPropertyNameId,
                                                                  int textureCbCrPropertyNameId);

            [DllImport("__Internal")]
            public static extern void UnityARKit_Camera_Destruct();

            [DllImport("__Internal")]
            public static extern void UnityARKit_Camera_Start();

            [DllImport("__Internal")]
            public static extern void UnityARKit_Camera_Stop();

            [DllImport("__Internal")]
            public static extern bool UnityARKit_Camera_TryGetFrame(XRCameraParams cameraParams,
                                                                    out XRCameraFrame cameraFrame);

            [DllImport("__Internal")]
            public static extern void UnityARKit_Camera_SetFocusMode(CameraFocusMode cameraFocusMode);

            [DllImport("__Internal")]
            public static extern CameraFocusMode UnityARKit_Camera_GetFocusMode();

            [DllImport("__Internal")]
            public static extern bool UnityARKit_Camera_TrySetLightEstimationMode(LightEstimationMode lightEstimationMode);

            [DllImport("__Internal")]
            public static extern bool UnityARKit_Camera_TryGetIntrinsics(out XRCameraIntrinsics cameraIntrinsics);

            [DllImport("__Internal")]
            public static extern bool UnityARKit_Camera_IsCameraPermissionGranted();

            [DllImport("__Internal")]
            public static extern IntPtr UnityARKit_Camera_AcquireConfigurations(out int configurationsCount,
                                                                                out int configurationSize);

            [DllImport("__Internal")]
            public static extern void UnityARKit_Camera_ReleaseConfigurations(IntPtr configurations);

            [DllImport("__Internal")]
            public static extern bool UnityARKit_Camera_TryGetCurrentConfiguration(out XRCameraConfiguration cameraConfiguration);

            [DllImport("__Internal")]
            public static extern CameraConfigurationResult UnityARKit_Camera_TrySetCurrentConfiguration(XRCameraConfiguration cameraConfiguration);

            [DllImport("__Internal")]
            public static unsafe extern void* UnityARKit_Camera_AcquireTextureDescriptors(
                out int length, out int elementSize);

            [DllImport("__Internal")]
            public static unsafe extern void UnityARKit_Camera_ReleaseTextureDescriptors(
                void* descriptors);

            [DllImport("__Internal")]
            public static extern bool UnityARKit_Camera_TryAcquireLatestImage(out CameraImageCinfo cameraImageCinfo);

            [DllImport("__Internal")]
            public static extern AsyncCameraImageConversionStatus
                UnityARKit_Camera_GetAsyncRequestStatus(int requestId);

            [DllImport("__Internal")]
            public static extern void UnityARKit_Camera_DisposeImage(
                int nativeHandle);

            [DllImport("__Internal")]
            public static extern void UnityARKit_Camera_DisposeAsyncRequest(
                int requestHandle);

            [DllImport("__Internal")]
            public static extern bool UnityARKit_Camera_TryGetPlane(int nativeHandle, int planeIndex,
                                                                    out CameraImagePlaneCinfo planeCinfo);

            [DllImport("__Internal")]
            public static extern bool UnityARKit_Camera_HandleValid(
                int nativeHandle);

            [DllImport("__Internal")]
            public static extern bool UnityARKit_Camera_TryGetConvertedDataSize(
                int nativeHandle, Vector2Int dimensions, TextureFormat format, out int size);

            [DllImport("__Internal")]
            public static extern bool UnityARKit_Camera_TryConvert(
                int nativeHandle, XRCameraImageConversionParams conversionParams,
                IntPtr buffer, int bufferLength);

            [DllImport("__Internal")]
            public static extern int UnityARKit_Camera_CreateAsyncConversionRequest(
                int nativeHandle, XRCameraImageConversionParams conversionParams);

            [DllImport("__Internal")]
            public static extern bool UnityARKit_Camera_TryGetAsyncRequestData(
                int requestHandle, out IntPtr dataPtr, out int dataLength);

            [DllImport("__Internal")]
            public static extern void UnityARKit_Camera_CreateAsyncConversionRequestWithCallback(
                int nativeHandle, XRCameraImageConversionParams conversionParams,
                XRCameraSubsystem.OnImageRequestCompleteDelegate callback, IntPtr context);
        }
    }
}