// %BANNER_BEGIN% // --------------------------------------------------------------------- // %COPYRIGHT_BEGIN% // Copyright (c) (2018-2022) Magic Leap, Inc. All Rights Reserved. // Use of this file is governed by the Software License Agreement, located here: https://www.magicleap.com/software-license-agreement-ml2 // Terms and conditions applicable to third-party materials accompanying this distribution may also be found in the top-level NOTICE file appearing herein. // %COPYRIGHT_END% // --------------------------------------------------------------------- // %BANNER_END% namespace UnityEngine.XR.MagicLeap { using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Threading.Tasks; using UnityEngine.XR.MagicLeap.Native; //Disabling WebRTC deprecated warning #pragma warning disable 618 /// /// ALWAYS INHERIT FROM THIS /// public interface IMLRequest { MLResult Start(Params parameters); MLResult TryGetResult(out Result result); } /// /// INHERIT FROM THIS IF YOUR REQUEST SHOULD BE A CLASS /// public abstract class MLRequest : IMLRequest { protected MLRequest() { } public Params Parameters => parameters; protected Params parameters; protected ulong handle = MagicLeapNativeBindings.InvalidHandle; public abstract MLResult Start(Params parameters); public abstract MLResult TryGetResult(out Result result); // if u also need to dispose of managed data, inherit from IDisposable protected abstract void Dispose(bool disposing); ~MLRequest() => this.Dispose(false); } /// /// Magic Leap API return value. /// public partial struct MLResult { /// /// Enables asynchronous native calls to use the same interface as synchronous ones /// public static implicit operator Task(MLResult r) => Task.FromResult(r); /// /// The code of this MLResult. /// Indicates the result status. /// public readonly Code Result; /// /// Holds a list of all the created MLResults mapped to their specific MLResult.Code. /// private static Dictionary existingResults; /// /// The message of this MLResult /// Provides a readable form of the result status. /// private string message; /// /// Initializes a new instance of the struct. /// /// The result code to give this MLResult. /// The message to give this MLResult. private MLResult(Code result, string msg) { this.Result = result; this.message = msg; } /// /// Identifier of Magic Leap API results /// public enum Code : int { /// /// Operation completed successfully. /// Ok = (CodePrefix.MLResultGlobal << 16), /// /// Asynchronous operation has not completed /// Pending, /// /// Operation has timed out. /// Timeout, /// /// Request to lock a shared resource that is already locked. /// Locked, /// /// Operation failed due to an unspecified internal error. /// UnspecifiedFailure, /// /// Operation failed due to an invalid parameter being supplied. /// InvalidParam, /// /// Operation failed because memory failed to be allocated. /// AllocFailed, /// /// Operation failed because a required permission has not been granted. /// PermissionDenied, /// /// Operation failed because it is not currently implemented. /// NotImplemented, /// /// Operation failed because the client count exceeded the number of clients available. /// ClientLimitExceeded, /// /// Operation failed because the requested pose is not available. /// PoseNotFound, /// /// Operation failed because feature isn't supported on current device version. /// IncompatibleSKU, /// /// Operation failed because the Perception System was not started. /// PerceptionSystemNotStarted, /// /// Operation failed because it has been invoked at the wrong time. /// IllegalState, /// /// Operation failed because of missing/incompatible license. /// LicenseError, /// /// Operation failed because the timestamp parameter was outside the expected range. /// InvalidTimestamp, // MLAudioResult /// /// Audio function not implemented. /// AudioNotImplemented = (CodePrefix.MLAudioResult << 16), /// /// Not a valid MLHandle for a sound or input. /// AudioHandleNotFound, /// /// Sample rate not supported. /// AudioInvalidSampleRate, /// /// Bits per sample not supported. /// AudioInvalidBitsPerSample, /// /// Valid bits per sample not supported. /// AudioInvalidValidBits, /// /// Sample format not supported. /// AudioInvalidSampleFormat, /// /// Channel count not supported. /// AudioInvalidChannelCount, /// /// Buffer size too small. /// AudioInvalidBufferSize, /// /// Buffer not ready for read or write. /// AudioBufferNotReady, /// /// Specified file not found. /// AudioFileNotFound, /// /// Specified file has unsupported format. /// AudioFileNotRecognized, /// /// Specified resource is not on the list. /// AudioResourceNotFound, /// /// Data was unloaded or file was closed. /// AudioResourceDiscarded, /// /// Requested operation not possible for given item. /// AudioOperationUnavailable, /// /// Requested operation has not yet been processed. /// AudioInternalOperationNotReady, /// /// Internal configuration problem was detected. /// AudioInternalConfigError, /// /// Operation failed because input service is not available. /// InputServiceNotAvailable = (CodePrefix.MLInputResult << 16), /// /// Operation failed because a required permission has not been granted. /// InputPermissionDenied, /// /// Operation failed because a required device was not found. /// InputDeviceNotFound, /// /// Operation failed because the service was in an illegal state. /// InputIllegalState, /// /// Operation failed because of an internal error. /// InputInternalError, /// /// Operation failed because a required speech feature is disabled in system settings. /// InputSpeechDisabled, // MLMediaPlayerResult /// /// Media errors (example: Codec not supported). /// MediaPlayerServerDied = (CodePrefix.MLMediaPlayerResult << 16), /// /// Runtime errors. /// MediaPlayerNotValidForProgressivePlayback, /// /// Media already connected. /// MediaAlreadyConnected = (CodePrefix.MLMediaResult << 16), /// /// Media not connected. /// MediaNotConnected, /// /// Media had unknown host. /// MediaUnknownHost, /// /// Media cannot connect. /// MediaCannotConnect, /// /// Media IO. /// MediaIO, /// /// Media connection was lost. /// MediaConnectionLost, /// /// Deprecated error. /// MediaLegacy1, /// /// Media was malformed. /// MediaMalformed, /// /// Media was out of range. /// MediaOutOfRange, /// /// Media buffer was too small. /// MediaBufferTooSmall, /// /// Media not supported. /// MediaUnsupported, /// /// Media end of stream. /// MediaEndOfStream, /// /// Media format changed. /// MediaFormatChanged, /// /// Media discontinuity. /// MediaDiscontinuity, /// /// Media output buffers changed. /// MediaOutputBuffersChanged, /// /// Media permission revoked. /// MediaPermissionRevoked, /// /// Media had an unsupported audio format. /// MediaUnsupportedAudioFormat, /// /// Media heartbeat requested to be terminated. /// MediaHeartbeatTerminateRequested, /// /// Unknown Media Codec Resource Request Error. /// MediaUnknownResource, /// /// Invalid Request on Media Codec Resources. /// MediaInvalidResourceRequest, /// /// Only Hardware Media Codec Resources are available. This error code /// is a result of requesting for Software Media Codec Resource that is /// not available. /// MediaOnlyHWResourceAvailable, /// /// Only Software Media Codec Resources are available. This error code /// is a result of requesting for Hardware Media Codec Resource that is /// not available. /// MediaOnlySWResourceAvailable, /// /// No more (Hardware or Software) Media Codec Resources available. /// MediaNoMoreResources, /// /// No more Hardware Media Codec Resources available /// MediaNoMoreHWResources, /// /// No more Software Media Codec Resources available. /// MediaNoMoreSWResources, /// /// Media Codec Resource request made with Invalid Codec parameters. /// This error code could be a result of one of these cases (not limited to) /// 1) Requested video frame width or height is beyond the maximum /// resolution (width or height) supported. /// 2) Requested Framerate/Sample rate/Bitratre/Channel count is not supported. /// MediaInvalidCodecParam, // MLMediaDRMResult /// /// Error code for undefined type. /// MediaDRMUnknown = (CodePrefix.MLMediaDRMResult << 16), /// /// Error code for no DRM license. /// MediaDRMNoLicense, /// /// Error code for DRM license expired. /// MediaDRMLicenseExpired, /// /// Error code for DRM session not expired. /// MediaDRMSessionNotOpened, /// /// Error code for DRM when decrypt unit is not initialized. /// MediaDRMDecryptUnitNotInitialized, /// /// Error code for DRM when failed to decrypt data. /// MediaDRMDecrypt, /// /// Error code for DRM can not handle the operation. /// MediaDRMCannotHandle, /// /// Error code for DRM when data is tampered. /// MediaDRMTamperDetect, /// /// Error Code when an operation on a MLMediaDRM handle is attempted and the device does not have a certificate. /// The app should obtain and install a certificate using the MLMediaDRM provisioning methods then retry the operation. /// MediaDRMNotProvisioned, /// /// Error code for Device License Revoked. /// MediaDRMDeviceRevoked, /// /// Error code if the MLMediaDRM operation fails when the required resources are in use. /// MediaDRMResourceBusy, /// /// Error code for insufficient output protection. /// MediaDRMInsufficientOutputProtection, /// /// Error code for insufficient output protection. /// MediaDRMLastUsedErrorCode = MediaDRMInsufficientOutputProtection, /// /// Range for vendor specific DRM errors. /// MediaDRMVendorMin = (CodePrefix.MLMediaDRMResult << 16) + 500, /// /// Range for vendor specific DRM errors. /// MediaDRMVendorMax = (CodePrefix.MLMediaDRMResult << 16) + 999, // MLMediaGenericResult /// /// Media invalid operation. /// MediaGenericInvalidOperation = (CodePrefix.MLMediaGenericResult << 16), /// /// Media bad type. /// MediaGenericBadType, /// /// Media name not found. /// MediaGenericNameNotFound, /// /// Media handle not found. /// MediaGenericHandleNotFound, /// /// Media NoInit. /// MediaGenericNoInit, /// /// Media already exists. /// MediaGenericAlreadyExists, /// /// Media dead object. /// MediaGenericDeadObject, /// /// Media had a failed transaction. /// MediaGenericFailedTransaction, /// /// Media had a bad index. /// MediaGenericBadIndex, /// /// Media not enough data. /// MediaGenericNotEnoughData, /// /// Media would block. /// MediaGenericWouldBlock, /// /// Media had an unknown transaction. /// MediaGenericUnknownTransaction, /// /// Media FDS not allowed. /// MediaGenericFDSNotAllowed, /// /// Media unexpected null. /// MediaGenericUnexpectedNull, /// /// Media not available. /// MediaGenericNotAvailable, // MLSnapshotResult /// /// Derivatives not calculated for requested coordinate frame. /// SnapshotDerivativesNotCalculated = (CodePrefix.MLSnapshotResult << 16), // MLWebRTCResult /// /// Instance not created. /// WebRTCInstanceNotCreated = (CodePrefix.MLWebRTCResult << 16), /// /// Mismatching handle. /// WebRTCMismatchingHandle, /// /// Invalid frame format. /// WebRTCInvalidFrameFormat, /// /// Invalid frame plane count. /// WebRTCInvalidFramePlaneCount, /// /// Native Frame failed to be sent /// WebRTCSendNativeFrameError, /// /// Data channel is closed. /// WebRTCDataChannelIsClosed, // MLSpatialAnchorResult /// /// The maximum number of anchors for the current space has been reached. /// AnchorsMaxAnchorLimitReached = (CodePrefix.MLAnchorsResult << 16), /// /// The minimum distance between anchors was not met /// AnchorsMinDistanceThresholdExceeded, /// /// The space has not been sufficiently mapped to allow this operation. /// AnchorsInsufficientMapping, /// /// The provided anchor id was not valid. /// AnchorsInvalidId, /// /// The provided expiration suggestion was not valid. /// AnchorsInvalidExpirationTimestamp, /// /// The operation cannot be completed because the device has not yet localized. /// AnchorsNotLocalized, /// /// There was an error communicating with the server. /// AnchorsServerError, /// /// The operation failed because the underlying service is not yet available. /// AnchorsServiceUnavailable, // MLVoiceResult /// /// Operation failed because a required voice intent feature is disabled in system settings. /// VoiceIntentDisabled = (CodePrefix.MLVoiceResult << 16), // MLWebViewResult /// /// Operation failed because zoom limit was reached. /// WebViewZoomLimitReached = (CodePrefix.MLWebViewResult << 16), // MLSpaceResult /// /// There was an error communicating with the server. /// SpacesServerError = (CodePrefix.MLSpaceResult << 16), /// /// The operation failed because the underlying service is not yet available, retry later. /// SpacesServiceUnavailable, /// /// Space is not available. /// UnavailableSpace, /// /// Space is not compatible with the current OS version. /// IncompatibleSpace, /// /// The operation failed because the Space being imported already exists in the device. /// SpaceAlreadyExists, // Facial Expression /// /// Unable to detect the eyes, check MLHeadsetFitStatus. /// HeadsetFitIssue = (CodePrefix.MLFacialExpressionResult << 16), /// /// Operation failed because enable_eye_expression in MLFacialExpressionSettings is disabled. /// EyeExpressionDisabled, /// /// Indicates the component is not connected. /// PowerManagerNotConnect = (CodePrefix.MLPowerManager << 16), /// /// Indicates the component does not currently support transitioning to requested state. /// PowerManagerInvalidStateTransition, /// /// Indicates the component does not currently support transitioning to a different state. /// PowerManagerStateTransitionsDisabled, /// /// Indicates the component does not support the requested power state. /// PowerManagerUnsupportedState, /// /// APIDLLNotFound. /// APIDLLNotFound = int.MaxValue - 0, /// /// APIDLLSymbolsNotFound. /// APISymbolsNotFound = int.MaxValue - 1, } /// /// this.Result code high order 2 byte prefix values used by the CAPI to group results by functionality. This is a ushort to facilitate bit shifting for final result values. /// private enum CodePrefix : ushort { /// /// Code for global MLResults. /// MLResultGlobal = 0x0000, /// /// Code for audio related MLResults. /// MLAudioResult = 0x9e11, /// /// Code for mediaDRM related MLResults. /// MLMediaDRMResult = 0x62ce, /// /// Code for generic media related MLResults. /// MLMediaGenericResult = 0xbf3b, /// /// Code for media player related MLResults. /// MLMediaPlayerResult = 0xc435, /// /// Code for media related MLResults. /// MLMediaResult = 0x4184, /// /// Code for snapshot related MLResults. /// MLSnapshotResult = 0x87b8, /// /// Code for web rtc related MLResults. /// MLWebRTCResult = 0xefc7, /// /// Code for MLAnchors related MLResults. /// MLAnchorsResult = 0x439, /// /// Code for MLVoice related MLResults. /// MLVoiceResult = 0xbe7a, /// /// Code for MLInput related MLResults. /// MLInputResult = 0x21dc, /// /// Code for MLWebView related MLResults. /// MLWebViewResult = 0xebf7, /// /// Code for MLSpace related MLResults. /// MLSpaceResult = 0x10cc, /// /// Code for MLPowerManager related MLResults. /// MLPowerManager = 0x4c8a, /// /// Code for MLFacialExpression related MLResults. /// MLFacialExpressionResult = 0x18cd } /// /// Gets a value indicating whether the result code is MLResult.Code.Ok /// Note that in some cases the result can be different than MLResult.Code.Ok /// and still valid (e.g. MLResult.Code.Pending, MLResult.Code.Ok) /// public bool IsOk { get { return Code.Ok == this.Result; } } /// /// Create a new MLResult or retrieve an already initialized MLResult with the result needed. /// /// The code to use for the created MLResult. /// The message to use for the created MLResult. /// A new or cached MLResult with the provided code and message. public static MLResult Create(Code result, string msg = null) { if (string.IsNullOrEmpty(msg)) { MLResult toReturn; if (existingResults == null) { existingResults = new Dictionary(); } if (existingResults.Count == 0 || !existingResults.TryGetValue(result, out toReturn)) { toReturn = new MLResult(result, msg); existingResults.Add(result, toReturn); } return toReturn; } else { return new MLResult(result, msg); } } /// /// Provides the string value for any MLResult.Code. /// /// The code to convert into a string value. /// The string value of the given MLResult.Code. public static string CodeToString(MLResult.Code resultCode) { string codeString = string.Empty; switch ((CodePrefix)((int)resultCode >> 16)) { case CodePrefix.MLResultGlobal: codeString = MagicLeapNativeBindings.MLGetResultString(resultCode); break; case CodePrefix.MLSnapshotResult: codeString = MagicLeapNativeBindings.MLGetSnapshotResultString(resultCode); break; case CodePrefix.MLAudioResult: codeString = MLAudioOutput.GetResultString(resultCode); break; case CodePrefix.MLMediaDRMResult: case CodePrefix.MLMediaGenericResult: case CodePrefix.MLMediaPlayerResult: case CodePrefix.MLMediaResult: codeString = MLMedia.NativeBindings.GetResultString(resultCode); break; case CodePrefix.MLWebRTCResult: codeString = Marshal.PtrToStringAnsi(MLWebRTC.NativeBindings.MLWebRTCGetResultString(resultCode)); break; case CodePrefix.MLInputResult: codeString = MagicLeapNativeBindings.MLGetInputResultString(resultCode); break; case CodePrefix.MLWebViewResult: // No MLWebViewGetResultString in API codeString = "Web View Result Code - String Not Available"; break; case CodePrefix.MLAnchorsResult: codeString = "MLResult_" + resultCode; break; case CodePrefix.MLPowerManager: codeString = resultCode.ToString(); break; case CodePrefix.MLFacialExpressionResult: codeString = resultCode.ToString(); break; default: // This will catch any unknown/invalid return values. codeString = MagicLeapNativeBindings.MLGetResultString(resultCode); break; } return codeString; } /// /// Indicates whether the result code is Code.Ok /// Note that in some cases the result can be different than MLResult.Code.Ok /// and still be valid (e.g. MLResult.Code.Pending, MLResult.Code.Ok) /// /// The code to determine if it is Ok. /// True if the provided code is equivalent Code.Ok. public static bool IsOK(Code result) { return Code.Ok == result; } /// /// Indicates whether the result code is one of the Pending results. /// /// The code to determine if it is pending. /// True if the provided code is equivalent Code.Pending. public static bool IsPending(Code result) { return (Code.Pending == result); } public static bool DidNativeCallSucceed(Code resultCode, string functionName = "A native function", Predicate successCase = null, bool showError = true) { bool success = successCase?.Invoke(resultCode) ?? IsOK(resultCode); if (!success && showError) MLPluginLog.ErrorFormat($"{functionName} in the Magic Leap API failed. Reason: {CodeToString(resultCode)} "); return success; } /// /// The equality check to be used for comparing two MLResult structs. /// /// The first struct to compare with the second struct. /// The second struct to compare with the first struct. /// True if the two provided structs have the same Result value. public static bool operator ==(MLResult one, MLResult.Code two) { return one.Result == two; } /// /// The inequality check to be used for comparing two MLResult structs. /// /// The first struct to compare with the second struct. /// The second struct to compare with the first struct. /// True if the two provided structs do not have the same Result value. public static bool operator !=(MLResult one, MLResult.Code two) { return !(one.Result == two); } /// /// The equality check to be used for comparing another object to this one. /// /// The object to compare to this one with. /// True if the the provided object is of the MLResult type and has the same Result values. public override bool Equals(object obj) { if (obj is MLResult.Code) { return this.Result == (MLResult.Code)obj; } else { return false; } } /// /// Gets the hash code to use from this.Result. /// /// The hash code returned by the this.Result field. public override int GetHashCode() { return this.Result.GetHashCode(); } /// /// Provides the string value of this.Result or the default message given to this MLResult. /// /// the string value of this.Result or the default message given to this MLResult. public override string ToString() { if (string.IsNullOrEmpty(this.message)) { this.message = CodeToString(this.Result); } return this.message; } } }