////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.
// All rights reserved.
// Confidential and Proprietary - Qualcomm Technologies, Inc.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @file  camxnodecommontypes.h
/// @brief Declarations of common and wrapped types for Node.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

#ifndef CAMXNODECOMMONTYPES_H
#define CAMXNODECOMMONTYPES_H

#include "camxcommondecltypes.h"
#include "camxhwdefs.h"
#include "camxhwintfdecl.h"
#include "camximagebufferinterface.h"
#include "camxpipelinecommontypes.h"
#include "camxpropertyblob.h"
#include "camxpropertydefs.h"

struct ChiTuningModeParameter;

CAMX_NAMESPACE_BEGIN

/// Forward Declarations

enum class Format;
enum class PoolType;

class  ChiContext;
class  CNodeImpl;
class  DeferredRequestQueue;
class  ImageBuffer;
class  ImageBufferManager;
class  IPipeline;
class  MetadataPool;
class  Session;
class  TuningDataManager;

struct BufferPropertiesInfo;
struct CaptureRequest;
struct ChiFence;
struct OutputPort;
struct PerBatchedFrameInfo;
struct PerNodePortInfo;
struct PipelineDescriptor;
struct LinkNodePortInfo;
struct PerRequestSetupOutputPortInfo;

// NCS Forward Declarations
enum NCSServiceRequestType : UINT;
enum NCSProviderRequestType : UINT;
enum NCSSensorRequestType : UINT;
typedef VOID*   NCSServiceRequestHandle;
typedef VOID*   NCSProviderRequestHandle;
typedef VOID*   NCSSensorRequestHandle;
typedef VOID*   NCSProviderHandle;

static const UINT32 MaxDstPortsPerLink            = 16;
static const UINT32 MaxPublishedCount             = 16;
static const UINT32 MaxPublishedListSize          = 64;
static const UINT32 RequestsCountToPublish        = 8;
static const UINT32 RequestsToPublishItr          = 100;
static const UINT32 MaxRequestBufferDepth         = 64;
static const UINT32 MaxTuningModeSelectors        = 10;
static const UINT32 BufferCountForRealTimeNodes   = 2;
static const UINT32 BufferCountForIFE             = 4;
static const SIZE_T InvalidImageBuffer            = 0xFFFFFFFF;
static const UINT32 MaxTagsPublished              = 64; ///< This will be compared against ChiNodeMaxTagsPublished;
static const UINT32 MaxFenceErrorBufferDepth      = 50;
static const UINT32 MaxRTSessionHandles           = 2;
static const INT32  MaxProcessSequenceIdForTiming = 16;
static const INT32  MinProcessSequenceIdForTiming = -2;
static const UINT64 TimeToPrintSeqIdAverageInMs   = 5000;
static const UINT   InvalidPortIndex              = UINT_MAX;
static const UINT32 FenceMessageVersion2          = 0x08000001;
static const UINT32 MaxNodesConnectedInBypass     = 10;
static const UINT32 StateTransitionThresholdInMs  = 50; ///< Currently set to 50 considering KMD response

CAMX_BEGIN_PACKED

struct ConfigIORequest
{
    VOID*   pDeviceResourceParam;  ///< Untyped pointer to the resource specific structure, structure can be in/out.
} CAMX_PACKED;

CAMX_END_PACKED

/// @brief Enumeration of operation type for per request setup
enum SetupOperationType
{
    BackwardsPass = 0,   ///< Disable links per request dynamically
    ForwardPass   = 1,   ///< Disable output ports of by pass node if no available source ports
};

/// @brief Structure for Output buffer for dependency buffer or delayed buffer
struct DelayedOutputBufferInfo
{
    CSLFence*       phFence;                        ///< Fence associated with the ImageBuffer
                                                    ///  for delayed buffer
    SynxFence       hSynxFence;                     ///< Synx fence corresponding to hFence
    BOOL            isParentInputBuffer;            ///< is the image buffer a parent's input buffer
    ImageBuffer**   ppImageBuffer;                  ///< image buffer pointers
    UINT32          sequenceId;                     ///< Sequence ID that this buffer is associated with
    UINT*           pIsFenceSignalled;              ///< Pointer for fence signalling status
};

/// @brief A property dependency type
struct PropertyDependency
{
    UINT32      count;                              ///< Number of properties in this unit
    PropertyID  properties[MaxProperties];          ///< Property dependencies in this unit
    UINT32      typeIds[MaxProperties];             ///< TypeId dependency in this unit
    UINT64      offsets[MaxProperties];             ///< Offset from current request for dependency
    BOOL        negate[MaxProperties];              ///< Indicate if offsets are negative value
    UINT        pipelineIds[MaxProperties];         ///< Pipeline index for every Property
};

/// @brief A unit of dependency that Node reports back to Pipeline
struct DependencyUnit
{
    union
    {
        struct
        {
            UINT32 hasInputBuffersReadyDependency       :  1;       ///< Node reports buffer dependency
            UINT32 hasPropertyDependency                :  1;       ///< Node reports property dependency
            UINT32 hasFenceDependency                   :  1;       ///< Node reports Chi Fence dependency
            UINT32 isPreemptable                        :  1;       ///< Can dependency be preempted
            UINT32 hasIOBufferAvailabilityDependency    :  1;       ///< Node reports input, output buffers availability as
                                                                    ///  dependency. Until this is set, it is not gauranteed
                                                                    ///  the input, output ImageBuffers are backed with buffers.
                                                                    ///  Nodes have to carefully set this flag when it *really*
                                                                    ///  needs buffers, setting this early even if buffers are
                                                                    ///  not needed on this dependency unit, will cause
                                                                    ///  unnecessary memory consumption.
            UINT32 isInternalDependency                 :  1;       ///< Is dependency internal to base node
            UINT32 reserved                             : 26;       ///< Reserved
        };
        UINT32 dependencyFlagsMask;                                 ///< Flag mask Value
    } dependencyFlags;

    PropertyDependency propertyDependency;                          ///< Set of Property dependency units

    struct
    {
        UINT      fenceCount;                                       ///< Number of fences to wait for
        CSLFence* phFences[MaxDependentFences];                     ///< Fences to wait for
        UINT*     pIsFenceSignaled[MaxDependentFences];             ///< Fence signal status
    } bufferDependency;                                             ///< Buffer dependency unit

    struct
    {
        UINT                chiFenceCount;                           ///< Number of fences to wait for
        ChiFence*           pChiFences[MaxDependentFences];          ///< Fences to wait for
        BOOL*               pIsChiFenceSignaled[MaxDependentFences]; ///< Fence signal status
        PFNCHIFENCECALLBACK pChiFenceCallback;                       ///< Callback when all Chi fence dependencies satisfied
        VOID*               pUserData;                               ///< Client-provided data pointer for Chi callback
    } chiFenceDependency;                                            ///< Buffer dependency unit

    INT32 processSequenceId;            ///< SequenceId to provide back to node when dependency satisfied
};

/// @todo (CAMX-1512) Add static asserts
enum class NodeClass
{
    Default = 0,                             ///< Default node type
    Bypass  = 1,                             ///< Bypass node
    Inplace = 2                              ///< Inplace node
};

/// @brief Enumeration of pass Id
enum BufferNegotiationPassId
{
    BackwardBufferNegotiation       = 0, ///< Backward walk to calculate the resolution range and select the sensor mode. The
                                         ///  format option list will be filtered by the advertised formats.
    ForwardBufferNegotiation        = 1, ///< Forward walk to finalize the resolution and format option list. If the primary
                                         ///  format of the list hits the scaling limitation of IPE node or other downstream
                                         ///  nodes, the renegotiation (i.e., BackwardFinalizeFormatOptions,
                                         ///  ForwardFinalizeBufferFormats, BackwardBufferRenegotiation, and
                                         ///  ForwardFinalizeBufferDimension) will be triggered. Because the primary format hits
                                         ///  the hardware limitation, need to filter the format option list further.
    BackwardFinalizeFormatOptions   = 2, ///< Backward walk to re-finalize the format option list (like the intersection done
                                         ///  in the BackwardBufferNegotiation) only if renego is triggered.
    ForwardFinalizeBufferFormats    = 3, ///< Forward walk to finalize the format (select the new primary format) only if renego
                                         ///  is triggered.
    BackwardBufferRenegotiation     = 4, ///< Backward walk to re-calculate the resolution range and re-select sensor mode (like
                                         ///  what is done in BackwardBufferNegotiation) only if renego is triggered.
    ForwardFinalizeBufferDimension  = 5, ///< Forward walk to re-finalize the resolution (like what is done in
                                         ///  ForwardBufferNegotiation) only if renego is triggered.
    ForwardFinalizeBufferProperties = 6, ///< Forward walk to finalize the property (of sensor, autofocus and other node) and
                                         ///  create image buffer manager.
};

/// @brief node property
struct PerNodeProperty
{
    UINT32 id;                            ///< ID of the property
    VOID*  pValue;                        ///< Pointer to data. Type dependent on ID
};

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// NodePropertyType
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
struct NodePropertyType
{
    // NOWHINE NC008:  Legacy Data structure, used at multiple places
    UINT32          NodePropertyId;     ///< ID of the property
    // NOWHINE NC003a: Legacy Data structure, Prefix (p) is missing for pointer
    CHAR*           NodePropertyValue;  ///< Value of the property
};

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// NodeInfo
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
struct NodeInfo
{
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    /// NodeProperty - Array
    /// Min Length:    0
    /// Max Length:    Unbounded
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // NOWHINE NC003a: Legacy Data structure, Prefix (p) is missing for pointer
    NodePropertyType* NodeProperty;         ///< Node Property struct
    // NOWHINE NC003a: Legacy Data structure, Prefix (p) is missing for pointer
    CHAR*             NodeName;             ///< Node Name
    // NOWHINE NC003a: Legacy Data structure, Prefix (p) is missing for pointer
    CHAR*             NodeInstance;         ///< Node Instance name
    // NOWHINE NC008:  Legacy Data structure, used at multiple places
    UINT32            NodePropertyCount;    ///< Node Property count
    // NOWHINE NC008:  Legacy Data structure, used at multiple places
    UINT32            NodePropertyID;       ///< Node Property Id
    // NOWHINE NC008:  Legacy Data structure, used at multiple places
    UINT32            NodeId;               ///< Node Id
    // NOWHINE NC008:  Legacy Data structure, used at multiple places
    UINT32            NodeInstanceId;       ///< Node Instance Id
};

/// @brief Per node info based on XML
struct PerNodeInfo
{
    NodeInfo*        pNodeInfo;                           ///< Node info coming from XML parser
    CHAR*            pNodeName;                           ///< Node name
    CHAR*            pInstanceName;                       ///< Node instance id
    UINT             nodePropertyCount;                   ///< Node property count
    PerNodeProperty* pNodeProperties;                     ///< Properties associated with the node
    UINT             nodeId;                              ///< Node Id
    UINT             instanceId;                          ///< Instance Id
    NodeClass        nodeClass;                           ///< Node class, bypassable node or default node
    PerNodePortInfo* pPortInfo;                           ///< Port Info associated with the node
    UINT             numTransitionModes;                  ///< Number of transition modes
    UINT             transitionModeIds[MaxNumberOfModes]; ///< Transition Mode Ids applicable for this node
    UINT             preferredMode;                       ///< Preferred transition mode
};

/// @brief Node create input data
struct NodeCreateInputData
{
    BOOL                          isVirtualSensor;          ///< false: real sensor, true: virtual sensor
    const PerNodeInfo*            pNodeInfo;                ///< Node info
    IPipeline*                    pPipeline;                ///< Pipeline Interface pointer
    UINT                          pipelineNodeIndex;        ///< This node instance's index in the pipeline nodes
    CNodeImpl*                    pNodeImplemenation;       ///< reference to Node implementation
};

/// @brief NodeCreateFlags flags
union NodeCreateFlags
{
    struct
    {
        BIT isSinkBuffer                    : 1;  ///< Node with a sink port that outputs a buffer
        BIT isSinkNoBuffer                  : 1;  ///< Node with a sink port that does not output a buffer
        BIT isSourceBuffer                  : 1;  ///< Node who has a input port that is not connected to any other node
        BIT isInPlace                       : 1;  ///< Is this an in place node whose output buffer is the same as input buffer
        BIT willNotifyConfigDone            : 1;  ///< Node needs to notify config done
        BIT isBypassable                    : 1;  ///< Is node a bypassable node
        BIT canDRQPreemptOnStopRecording    : 1;  ///< Can DRQ preempt node on recording stop/pause
        BIT hasFutureDependencies           : 1;  ///< Node has future dependencies, all downstream nodes would set
                                                  ///< hasDelayedNotification automatically
        BIT hasDelayedNotification          : 1;  ///< Node has delayed notification
        BIT isDeferNotifyPipelineCreate     : 1;  ///< Node has defer notification when pipeline creation
        BIT needSynxFence                   : 1;  ///< Node requires synx fence creation
        BIT needHWFence                     : 1;  ///< Node requires HW fence creation
        BIT canBatchInitDependency          : 1;  ///< Node requires batch processing for Sequence 0
        BIT needSerialDestroy               : 1;  ///< Node requires serial destroy
        BIT reserved                        : 18; ///< Reserved
    };

    UINT value;
};

/// @brief Metadata list used/published by the node
struct NodeMetadataList
{
    UINT32   tagCount;                          ///< Number of tags published by the node
    UINT32   partialTagCount;                   ///< Count of partial metadata in the tag array
    UINT32   tagArray[MaxTagsPublished];        ///< Array of tags published by the node
    UINT32   typeIdBitmask[MaxTagsPublished];   ///< Bitmask containing type Ids supported for a tagId
};

/// @brief Node vendor tag information
struct NodeVendorTag
{
    const CHAR* pSectionName;  ///< Vendor tag section
    const CHAR* pTagName;      ///< Vendor tag name
};

/// @brief Node composite fence info
struct BufferGroup
{
    BOOL                                hasCompositeMask;      ///< Flag to indicate if the node has any composite masking
    std::unordered_map<UINT32, UINT32>  portGroupID;           ///< Composite group to which each port is mapped. PortID as key.
    std::unordered_set<UINT32>          inputPortHasSynxFence; ///< Set of input PortIDs for which synx fences will be created
                                                               ///  for synx nodes. If empty, then all ports have synx fences.
};

/// @brief Node create output data
struct NodeCreateOutputData
{
    CNodeImpl*          pNode;                              ///< Created node object pointer
    const CHAR*         pNodeName;                          ///< Name of the node (filled in the by the derived node)
    NodeCreateFlags     createFlags;                        ///< Create flags
    UINT                maxNumCmdBufferManagers;            ///< Max require number of command buffer managers
    UINT                maxOutputPorts;                     ///< Max number of output ports supported
    UINT                maxInputPorts;                      ///< Max number of input ports supported
    BufferGroup         bufferComposite;                    ///< Buffer composite info
};

/// @brief Node capture request data.
struct NodeProcessRequestData
{
    CaptureRequest*      pCaptureRequest;                    ///< Stream configuration pointer
    DependencyUnit       dependencyInfo[MaxDependencies];    ///< List of Dependency info that will be reported back
                                                             ///  to topology. Each element in the list is a set of
                                                             ///  property and buffer dependencies
    UINT                 numDependencyLists;                 ///  Number of entries in the Dependency List
    PerBatchedFrameInfo* pPerBatchedFrameInfo;               ///< Per batched frame info
    INT32                processSequenceId;                  ///< Identifier for the node to track its processing order
    BOOL                 bindIOBuffers;                      ///< Flag indicating whether node requested input, output buffers
                                                             ///  to be available on this sequenceId
    BOOL                 isSequenceIdInternal;               ///< True if processSequenceId belongs to base node
    BOOL                 isEarlyNodeComplete;                ///< Indicates whether the node complete property set earlier
                                                             ///  than request id done.
                                                             ///  @valuesbul
                                                             ///  - 0 -- FALSE
                                                             ///  - 1 -- TRUE @tablebulletend
    VOID*                pDependency;                        ///< Dependency pointer, will be used to find duplicate request
};

/// @brief Output buffer info
struct FenceHandlerBufferInfo
{
    IImageBuffer*   pImageBuffer;                       ///< ImageBuffer for the output buffer
    UINT32          sequenceId;                         ///< Sequence ID that this buffer is associated with
    ChiBufferInfo   bufferInfo;                         ///< CHI buffer (valid only for output buffer on a sink port)
};

/// @brief Passed to CSL when registering fence callback. CSL passes this back in the fence callback. The fence callback
///        simply invokes the Node* and passes it the pNodePrivateData. Nodes fence handler processes the fence signal.
struct FenceCallbackData
{
    CNodeImpl*  pNode;            ///< Node to which the fence (being signaled) belongs to
    VOID*       pNodePrivateData; ///< Node private data - Pointer to "struct PortFenceData"
};

struct ReturnFenceInfo;
/// @brief Node fence handler data - CSL fence callback function passes this data to the Node fence handler that processes
///        the fence signal
struct NodeFenceHandlerData
{
    FenceCallbackData       nodeCSLFenceCallbackData;            ///< Private data passed to CSL when registering
                                                                 ///  node fence callback
    OutputPort*             pOutputPort;                         ///< Output port to which this fence/imagebuffers
                                                                 ///  belong to
    UINT64                  requestId;                           ///< Request Id that this fence is associated with
    CSLFence                hFence;                              ///< CSL fence associated with the port
    SynxFence               hSynxFence;                          ///< Synx fence associated with the port
    UINT                    isFenceSignaled;                     ///< Atomic Load/Store - Has the fence already been
                                                                 ///  signaled
    UINT                    numOutputBuffers;                    ///< Number of output buffers
    FenceHandlerBufferInfo* pOutputBufferInfo;                   ///< Info related to the output buffer on the port
    DelayedOutputBufferInfo delayedOutputBufferData;             ///< Output buffer info for bypassable node
    CSLFenceResult          fenceResult;                         ///< Fence result
    struct
    {
        BIT primaryFence         : 1;  ///< Fence which primary in the composite
        BIT isChiFence           : 1;  ///< boolean to check if the fence is allocated by chi or camx
        BIT isSinkBuffer         : 1;  ///< boolean to check if the buffer is allocated by chi or camx
        BIT reserved             : 29; ///< reserved for future expansion
    };

    CHAR                    identifierString[MaxStringLength256]; ///< Fence Identiifer
    UINT32                  errorCode;                            ///< Fence Error Reason
    ReturnFenceInfo*        pReturnFenceInfo;                     ///< Optional pointer to return fence info
    DMAFence                hDMAFence;                            ///< DMA fence associated with the port
};

/// @brief Port compsite fence info
struct CompositePortFenceInfo
{
    CSLFence                            hCSLFence;             ///< Composite CSL fence handle
    SynxFence                           hSynxFence;            ///< Composite Synx fence handle
    volatile UINT                       aRefCount;             ///< reference count for the fence
    CSLFence*                           phFence;               ///< Pointer to fence to cleanup
    SynxFence*                          pHSynxFence;           ///< Pointer to Synx fence to cleanup
    UINT64                              requestId;             ///< Request Id that this fence is associated with
    std::vector<NodeFenceHandlerData*>  secFenceInfo;          ///< List of data associated with secondary fences
};

/// @brief This structure contains a subset of NodeFenceHandler data to be used in debug logging
struct NodeFenceHandlerDataErrorSubset
{
    CSLFence                hFence;                              ///< Fence associated with the port
    UINT64                  requestId;                           ///< Request Id that this fence is associated with
    UINT                    portId;                              ///< Port Id associated with the failed fence
    UINT32                  errorCode;                           ///< Fence Error Reason
};

/// @brief This structure contains a looping array used to keep track of the 50 most recent fence errors
struct FenceErrorBuffer
{
    NodeFenceHandlerDataErrorSubset fenceErrorData[MaxFenceErrorBufferDepth]; ///< Fence buffers
    UINT                            freeIndex;                                ///< Next free element in the array
};

struct FenceTypeMask
{
    BIT isSynxFence      : 1;  ///< Is synx Fence type
    BIT isHWFence        : 1;  ///< Is HW Fence type
    BIT reserved         : 30; ///< reserved for future expansion
};

/// @brief This structure contains the buffer requirements
struct BufferRequirement
{
    UINT32              minWidth;                                   ///< Min width required to generate the final output buffer
    UINT32              minHeight;                                  ///< Min height required to generate the final output buffer
    UINT32              maxWidth;                                   ///< Max width required to generate the final output buffer
    UINT32              maxHeight;                                  ///< Max height required to generate the final output buffer
    UINT32              optimalWidth;                               ///< Optimal width that the node would want on its input
                                                                    ///  buffer
    UINT32              optimalHeight;                              ///< Optimal height that the node would want on its input
                                                                    ///  buffer
    UINT32              numSupportedFormats;                        ///< The number of supported formats
    Format              supportedFormats[MaxNumSupportedFormats];   ///< Supported formats
    AlignmentInfo       planeAlignment[FormatsMaxPlanes];           ///< Stride and scanline alignment for each plane
    ChiStreamIntentMask streamIntentMask;                           ///< The stream intents associated with this port
    UINT32              physicalCameraId;                           ///< Physical camera id associated with this port
    FenceTypeMask       fenceTypeMask;                              ///< Fence type associated with this port
    BOOL                ignoreOptimal;                              ///< Flag to indicate the Optimal requirement can be ignored
    ChiStreamColorSpace minColorSpace;                              ///< Minimum color space required for this buffer
    UINT32              streamPriority;                             ///< Stream Priority
};

/// @brief This structure contains the buffer requirements of the input ports on a node
struct PortBufferOptions
{
    UINT32            nodeId;               ///< Node Id
    UINT32            instanceId;           ///< Node instance Id
    UINT32            portId;               ///< Port Id
    BufferRequirement bufferRequirement;    ///< Buffer requirement
};

/// @brief Negotiation data for the input ports
struct InputPortNegotiationData
{
    UINT                  inputPortId;       ///< Input portId
    ImageFormat*          pImageFormat;      ///< Image format locked down by the parent's output port
    ChiStreamIntentMask   streamIntentMask;  ///< The stream intents associated with this port.
    FenceTypeMask         fenceTypeMask;     ///< Fence type mask associated with this port.
    UINT                  physicalCameraId;  ///< Physical camera id associated with this port.
};

/// @brief Negotiation data for the output buffer per output port
struct OutputPortNegotiationData
{
    UINT               outputPortIndex;                           ///< Output port index
    BufferRequirement  inputPortRequirement[MaxDstPortsPerLink];  ///< Buffer requirement requested by the input ports
                                                                  ///  connected to the outputPort
    UINT               numInputPortsNotification;                 ///< Number of input ports that have provided their buffer
                                                                  ///  requirements for this outputPort
    BufferRequirement  outputBufferRequirementOptions;            ///< Valid options from which the final buffer properties
                                                                  ///  must be set
    BufferProperties*  pFinalOutputBufferProperties;              ///< Final output buffer properties decided after receiving
                                                                  ///  buffer requirements of all input ports connected to this
                                                                  ///  outputPort
};

/// @brief Structure that contains negotiation data for the node
struct BufferNegotiationData
{
    OutputPortNegotiationData*   pOutputPortNegotiationData;             ///< Array of negotiation data per output port. Filled
                                                                         ///  on the walk-back from sink-to-source
    InputPortNegotiationData*    pInputPortNegotiationData;              ///< Array of negotiation data per input port. Filled
                                                                         ///  on the walk-forward from source-to-sink
    UINT                         numOutputPortsNotified;                 ///< Output ports whose requirements have been obtained
    UINT                         numInputPorts;                          ///< Number of input ports
    PortBufferOptions            inputBufferOptions[MaxPipelineInputs];  ///< Valid options for input port buffer
    UINT                         transitionMode;                         ///< Transition mode used for the buffer negotiation
    BufferNegotiationPassId      bufferNegotiationStatus;                ///< Pass Id during the Buffer & Format negotiation
};

/// @brief Source input port chi fence information
struct NodeSourceInputPortChiFenceCallbackData
{
    CNodeImpl*              pNode;                  ///< Pointer to this Node object
    DeferredRequestQueue*   pDeferredRequestQueue;  ///< Pointer to deferred processing object
    CSLFence*               phFence;                ///< Pointer to the CSL fence
    UINT*                   pIsFenceSignaled;       ///< Fence variable whose signaled status is checked
    UINT64                  requestId;              ///< Request Id that the fence is waiting in
};

/// @brief OutputPort flags
union OutputPortFlags
{
    struct
    {
        BIT isBatchMode                      : 1;  ///< Is batch mode enabled
        BIT isLateBindingDisabled            : 1;  ///< Flag to indicate if the late binding on the image buffer manager of
                                                   ///  the output port has to be disabled.
        BIT disableSelfShrinking             : 1;  ///< Flag to indicate if self shrinking of buffers allocated at this port
                                                   ///  need to be disabled
        BIT isNonSinkHALBufferOutput         : 1;  ///< Flag to indicate that the output port is not a sinkport but still
                                                   ///  outputs a HAL buffer. This will happen in cases if the output port
                                                   ///  is connected to an inplace node that outputs a HAL buffer.
        BIT isSinkBuffer                     : 1;  ///< Is it a sink port with output buffer
        BIT isSinkNoBuffer                   : 1;  ///< Is it a sink port with no output buffer
        BIT isSharedSinkBuffer               : 1;  ///< Is it a sink port with output buffer that also is consumed by other
                                                   ///  nodes
        BIT isEnabled                        : 1;  ///< Is the port enabled
        BIT isSecurePort                     : 1;  ///< Is the port is secure/Non-secure
        BIT isLoopback                       : 1;  ///< Is it a loopback port connected to the same node
        BIT isSinkInplaceBuffer              : 1;  ///< Is it a sink port with output buffer for Inplace node
        BIT noBuffersRequired                : 1;  ///< Buffers not required for this output port
        BIT isDisabledBySelf                 : 1;  ///< TRUE if this node disables this port as opposed if a downstream node
                                                   ///  disables this port. FALSE otherwise
        BIT isDisabledBySelfDontOverwrite    : 1;  ///< TRUE if this node disabled this port and don't overwrite to enable again
        BIT useFallbackBufferManager         : 1;  ///< Indicates if a shared sink link should provide a fallback buffer
                                                   ///  manager for use when a target sink buffer is not available.
        BIT obeyImmediateCount               : 1;  ///< Obey ImmediateCount mentioned in xml for this link's buffer manager
        BIT isAnyChildHWNode                 : 1;  ///< If the child node is a hw node
        BIT isAnyChildSWNode                 : 1;  ///< If the child node is a sw node
        BIT reserved                         : 14; ///< Reserved
    };

    UINT value;
};

CAMX_STATIC_ASSERT(sizeof(OutputPortFlags) == sizeof(OutputPortFlags::value));
/// @brief InputPort flags
union InputPortFlags
{
    struct
    {
        BIT isEnabled           : 1;            ///< Is the port enabled
        BIT isSourceBuffer      : 1;            ///< Is it a source port with a HAL buffer
        BIT isLoopback          : 1;            ///< Is it a loopback port connected to the same node
        BIT isParentInputBuffer : 1;            ///< Is it a parent's input buffer
        BIT isBypssablePort     : 1;            ///< Is this port can be bypassed
        UINT reserved           : 27;           ///< Reserved
    };

    UINT value;
};

/// @brief Stream specific data information
struct StreamData
{
    UINT32                portFPS;              ///< Max FPS of all streams' FPS active at this port
    UINT32                streamIntentBitMask;  ///< Bit mask contianing stream intents for node
};

/// @brief Stream type for a given node
enum StreamProcessType
{
    RealtimeStream, ///< Realtime stream type
    OfflineStream,  ///< Offline stream type
};

/// @brief Basic node processing stages used to OEM configuration
enum OEMCfgNodeStage
{
    InputBufferRequirement = 0,       ///< OEM configuration node stage input buffer requirement
    EPRSequence1,                     ///< OEM configuration node stage EPR sequence1
    InitSequence,                     ///< OEM configuration node stage Init sequence
};

/// @brief Structure to track the number of input ports/references held sharing the same pipeline delay for an output port
struct OutputPortInputDelayRecord
{
    UINT8 delay; ///< The pipeline delay for these inputs
    UINT8 count; ///< The number of connected nodes sharing this pipeline delay
};

/// @brief Output port structure for single output port related information
struct OutputPort
{
    UINT                       portId;                                 ///< Port id (from topology XML file)
    INT32                      deviceIndices[CamxMaxDeviceIndex];      ///< Device indices that may be access buffers owned by
                                                                       ///< this port
    UINT                       deviceCount;                            ///< Number of devices that is in deviceIndices list
    BufferProperties           bufferProperties;                       ///< Buffer properties
    ImageBufferManager*        pImageBufferManagerIntf;                ///< Image buffer manager pointer
    BufferRequirement*         pOutputBufferRequirementOptions;        ///< Buffer negotiation option
    ImageBufferManager*        pFallbackImageBufferManager;            ///< Image buffer manager to allocate buffers for shared
                                                                       ///  sink ports when no sink buffer is available for a
                                                                       ///  request.
    ImageBuffer**              ppImageBuffers;                         ///< Array of Image buffers
                                                                       ///  (numElements == maxImageBuffers)
    NodeFenceHandlerData*      pFenceHandlerData;                      ///< Array of all fence related data -
                                                                       ///  one array element
                                                                       ///  for one image buffer/fence
    UINT                       sinkTargetStreamId;                     ///< If this is a sink port that outputs an HAL buffer,
                                                                       ///  the streamId that this sink port maps to
    UINT64                     enabledInStreamMask;                    ///< List of Stream Ids that enable this output port
                                                                       ///  Bit 0 = 1 if Stream Id 0 enables it
                                                                       ///        = 0 if Stream Id 0 does not enable it
                                                                       ///  Same for other stream Ids. So for e.g. if Stream 0
                                                                       ///  and Stream 2 enables this output port - the mask
                                                                       ///  value would be 5
    UINT                       numInputPortsConnected;                 ///< These are the number of input ports connected to
                                                                       ///  this output port
    UINT                       numInputPortsDisabled;                  ///< Number of input ports that do not use this output
                                                                       ///  although they are connected
    BufferPropertiesInfo*      pBufferProperties;                      ///< Bufferproperties coming from the XML
    UINT                       numBatchedFrames;                       ///< Number of batched frames in this output port
    BOOL                       HALOutputBufferCombined;                ///< Is the HAL output buffer combined for batch mode
    OutputPortFlags            flags;                                  ///< OutputPort flags
    UINT                       portSourceTypeId;                       ///< Port source type id
    UINT                       numSourcePortsMapped;                   ///< Number of source Ports mapped to this output port
                                                                       ///  for bypass
    const UINT*                pMappedSourcePortIds;                   ///< Pointer to the source port Ids mapped to this
                                                                       ///  output ports for bypass
    ChiStreamWrapper*          pChiStreamWrapper;                      ///< ChiStreamWrapper on the port
    UINT                       numInputPortsConnectedinBypass;         ///< These are the number of input ports connected
                                                                       ///  to this output port through bypass
    UINT                       numOfNodesConnected;                    ///< Number of nodes connected to this output port
    CNodeImpl*                 pDstNodes[MaxNumPipelineNodes];         ///< List of nodes connected to this output port
    StreamData                 streamData;                             ///< Stream specific data
    UINT                       numTransitionModes;                     ///< Number of transition modes
    UINT                       transitionModes[MaxNumberOfModes];      ///< Transition mode Ids
    UINT                       internalPortIds[MaxNumberOfModes];      ///< Internal Port Id for each transition mode
    OutputPortNegotiationData* pPortNegotiationData[MaxNumberOfModes]; ///< Pointer to Negotiation Data for each mode
    ///@ todo (CAMX-326) Buffer manager pointers will live here and image buffers for requests will be maintained explicitly
    std::vector<OutputPortInputDelayRecord> inputDelays;
    std::vector<LinkNodePortInfo>           inputPortsConnected;       ///< List of input ports connected to this output port
    BOOL                                    isSynxLinkSource;          ///< If the port is a provider for synx fences
};

/// @brief Input port structure for single input port related information
struct InputPort
{
    UINT                  portId;                                     ///< Port id (from topology XML file)
    CNodeImpl*            pParentNode;                                ///< Parent node for triggering calls like
                                                                      ///  pParentNode::GetImageBuffer(portId, requestId)
                                                                      ///  The above buffer gets programmed as input buffer for
                                                                      ///  the node with this input
    UINT                  parentOutputPortIndex;                      ///< Parent output port to which this input port is
                                                                      ///  connected port.
                                                                      ///  Parent node may have an array of 'n' output ports,
                                                                      ///  parentPortId tells
                                                                      ///  the array element i.e. the parent output port to
                                                                      ///  which this input port is connected
    UINT                  sourceTargetStreamId;                       ///< If this is a source buffer port,
                                                                      ///  the streamId that this source port maps to
    ImageFormat           imageFormat;                                ///< Buffer image format if this input port is a source
                                                                      ///  buffer port
    BufferRequirement*    pInputBufferRequirementOptions;             ///< The requirement filled during the backward
                                                                      ///  negotiation
    ImageBuffer**         ppImageBuffers;                             ///< Container ImageBuffer if this input port is a source
                                                                      ///  buffer port
    InputPortFlags        flags;                                      ///< Flags
    CSLFence*             phFences;                                   ///< Input buffer fences
    SynxFence*            pHSynxFences;                               ///< Synx fences associated with input buffer fences
    UINT*                 pIsFenceSignaled;                           ///< Fence variable whose signaled status is checked
    BOOL                  isInputSynxSourcePort;                      ///< If TRUE, a synx fence will be created for this port
    UINT*                 pInputBufferIndex;                          ///< inputBuffer index for this port
    union FenceSourceFlags                                            ///< CSL Fence association flags with external
                                                                      ///  layer/modules to CAMX
    {
        struct
        {
            BIT isChiAssociatedFence : 1;                             ///< Is this a CHI associated CSL fence?
            BIT reserved             : 31;                            ///< Reserved
        };
        UINT allFlags;
    } *pFenceSourceFlags;
    UINT                      portSourceTypeId;                       ///< Port source type id
    UINT                      parentPortSourceTypeId;                 ///< Parent's Port Source Type ID
    BOOL                      portDisabled;                           ///< Input port disabled if set
    UINT32                    bufferDelta;                            ///< Indicates buffer requirement of current request -
                                                                      ///  bufferDelta
    IImageBufferManager*      pImageBufferManagerIntf;                ///< Image buffer manager pointer
    ChiStreamWrapper*         pChiStreamWrapper;                      ///< ChistreamWrapper Pointer
    UINT                      numTransitionModes;                     ///< Number of modes supported by this port
    UINT                      transitionModes[MaxNumberOfModes];      ///< transition modes supported by this port
    UINT                      internalPortIds[MaxNumberOfModes];      ///< Internal Port Ids
    InputPortNegotiationData* pPortNegotiationData[MaxNumberOfModes]; ///< Pointer to input port negotiation data
                                                                      ///  for each mode
};

/// @brief Per request output port flags
union PerRequestOutputPortFlags
{
    struct
    {
        BIT isOutputHALBuffer  : 1;                     ///< Is the output of this port a HAL buffer
        BIT isBatch            : 1;                     ///< Is the batch mode enabled for this port
        BIT isDelayedBuffer    : 1;                     ///< Is delayed output buffer
        BIT isLoopback         : 1;                     ///< Is loopback port
        BIT noBuffersRequired  : 1;                     ///< Buffers not required for this output port
        BIT isDisabled         : 1;                     ///< Is the port is dynamically disabled during processing
        BIT isPrimaryFence     : 1;                     ///< Is primary fence output port
        BIT isAnyChildHWNode   : 1;                     ///< Is Child Node HW
        BIT isAnyChildSWNode   : 1;                     ///< Is Child Node SW
        BIT isChiFence         : 1;                     ///< If the fence is allocated by chi or camx
        BIT reserved           : 22;                    ///< Reserved
    };

    UINT allFlags;
};

/// @brief Per request input port flags
union PerRequestInputPortFlags
{
    struct
    {
        BIT isInputHALBuffer    : 1;                     ///< Is the input of this port a HAL buffer
        BIT isPendingBuffer     : 1;                     ///< Is the image buffer of this port pending to be resolved
        BIT isParentInputBuffer : 1;                     ///< Is the buffer from parent's input
        BIT reserved            : 29;                    ///< Reserved
    };

    UINT allFlags;
};

/// @brief Per request info for one output port to be sent to the derived nodes that implement request processing
struct PerRequestOutputPortInfo
{
    UINT                        portId;                             ///< PortId from XML
    IImageBuffer**              ppImageBuffer;                      ///< All the output buffers of this port
    PerRequestOutputPortFlags   flags;                              ///< Flags
    UINT                        numOutputBuffers;                   ///< Number of output buffers that will be output
    CSLFence*                   phFence;                            ///< Fence associated with all Imagebuffers in the output
                                                                    ///  port
    DMAFence*                   pHDMAFence;                         /// < DMA fence associated with the buffer for this port
    SynxFence*                  pHSynxFence;                        /// < Synx Fence associated with the buffer for this port
    UINT*                       pIsFenceSignaled;                   ///< Pointer to fence variables signaled status
    DelayedOutputBufferInfo*    pDelayedOutputBufferData;           ///< Pointer to the delayed output buffer
    UINT                        mappedInputPortd;                   ///< Mapped input port identifier to be used by bypass mode
    UINT                        numPerReqInputPortsDisabled;        ///< Number of input ports that are connected but not in
                                                                    ///  use (unused nodes)
};

/// @brief Per request info for one input port to be sent to the derived nodes that implement request processing
struct PerRequestInputPortInfo
{
    UINT                     portId;                    ///< PortId from XML
    UINT                     parentPortSourceTypeId;    ///< Parent Port's Source Type ID from XML
    IImageBuffer*            pImageBuffer;              ///< ImageBuffer associated with the port
    PerRequestInputPortFlags flags;                     ///< Flags
    CSLFence*                phFence;                   ///< Fence associated with the ImageBuffer
    SynxFence*               pHSynxFence;               ///< Synx Fence associated with the buffer
    BOOL                     primaryFence;              ///< Fence which primary in the composite
    BOOL                     createSynxFence;           ///< True if a synx fence needs to be created for this CSL fence
    UINT*                    pIsFenceSignaled;          ///< Pointer to fence variable whose signaled status is checked
    DelayedOutputBufferInfo* pDelayedOutputBufferData;  ///< Pointer to the delayed output buffer
    ChiStreamWrapper*        pParentSinkStream;         ///< Sink stream of the parent
    UINT                     portIndex;                 ///< Index of the port
};

/// @brief Per request info of which ports needs to be setup
struct PerRequestSetupPorts
{
    UINT                            numOutputPorts;    ///< Number of output ports per request
    UINT                            numInputPorts;     ///< Number of input ports per request
    PerRequestSetupOutputPortInfo*  pSetupOutputPorts; ///< Per request setup output ports, points to array size numOutputPorts
    BOOL*                           pSetupInputPorts;  ///< Per request setup input ports,  points to array size numInputPorts
};

/// @brief Per request info of all enabled input/output ports to be sent to the derived nodes that implement request processing
struct PerRequestActivePorts
{
    UINT                      numOutputPorts;          ///< Number of output ports per request
    UINT                      numInputPorts;           ///< Number of input ports per request
    PerRequestOutputPortInfo* pOutputPorts;            ///< Per request output ports - points to array size numOutputPorts
    PerRequestInputPortInfo*  pInputPorts;             ///< Per request input ports  - points to array size numInputPorts
};

/// @brief Per OnSetupRequest output information
struct SetupRequestOutput
{
    std::vector<UINT> inputPortIdsToDisable;  ///< Vector of input port ids to disable
    std::vector<UINT> outputPortIdsToDisable; ///< Vector of output port ids to disable
};

/// @brief Basic node processing stages used to track processing time for a given node
enum class NodeStage
{
    Start,              ///< First time ProcessRequest is called for a given request
    DependenciesMet,    ///< Node's dependencies are met for a given request
    EPReqEnd,           ///< Execute Process Request for the sequence id is done
    End,                ///< Node finish processing for a given request
    MaxNodeStatuses     ///< Maximum node stages
};

/// @brief Execute process request data to be passed to the derived nodes that implement request processing
struct ExecuteProcessRequestData
{
    NodeProcessRequestData* pNodeProcessRequestData;    ///< Request data coming in from Pipeline
    PerRequestActivePorts*  pEnabledPortsInfo;          ///< All enabled ports for the request
    ChiTuningModeParameter* pTuningModeData;            ///< Pointer to tuning mode selector data
};

/// @brief Input port crop info
struct PortCropInfo
{
    CHIRectangle appliedCrop;     ///< Applied crop
    CHIRectangle residualCrop;    ///< Residual crop
    CHIDimension residualFullDim; ///< residual full dim
};

/// @brief AI strength control factor mask for override
enum AIStrengthControlFactor
{
    AIStrengthControlSegGlobalConfidence = 1, ///< Seg global confidence
    AIStrengthControlSWAIStrength,            ///< SW AI control
    AIStrengthControlMax,                     ///< AI strength control max
};

/// @brief Max and Min SW AI strength Values define
enum SWAIStrengthValue
{
    MinAIStrength = 0,   ///< Minmum SW AI Strength value
    MaxAIStrength = 128, ///< Maxmum SW AI Strength value
};

/// @brief Max and Min AI Segment Global Confidence Values define
enum AISegGlobalConfidenceValue
{
    MinAISegGlobalConfidence = 0,   ///< Minmum AI Segmentation global confidence value
    MaxAISegGlobalConfidence = 128, ///< Maxmum AI Segmentation global confidence value
};

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// GetBatchedHALOutputNum
///
/// @brief  Get the number of HAL output buffer for batch mode.
///         If the flag HALOutputBufferCombined is TRUE, the HAL output buffer will be combined into one single buffer.
///         Otherwise, one video output buffer maps to one HAL output buffer, so the output buffer number equal to
///         the numBatchedFrames.
///
/// @param  numBatchedFrames     the number of batched frames for HFR mode.
/// @param  HALOutputBufferCombined     the number of batched frames for HFR mode.
/// @return Number of batched frames
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
CAMX_INLINE UINT GetBatchedHALOutputNum(
    UINT numBatchedFrames,
    BOOL HALOutputBufferCombined)
{
    UINT frames = numBatchedFrames;
    if (TRUE == HALOutputBufferCombined)
    {
        frames = 1;
    }

    return frames;
}

CAMX_NAMESPACE_END

#endif // CAMXNODECOMMONTYPES_H
