Unnamed: 0
int64
0
0
repo_id
stringlengths
5
186
file_path
stringlengths
15
223
content
stringlengths
1
32.8M
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/storage
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/storage/ata/IOATAStorageDefines.h
/* * Copyright (c) 1998-2007 Apple Inc. All rights reserved. * * @APPLE_LICENSE_HEADER_START@ * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this * file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_LICENSE_HEADER_END@ */ #ifndef _IOKIT_IO_ATA_STORAGE_DEFINES_H_ #define _IOKIT_IO_ATA_STORAGE_DEFINES_H_ #include <stdint.h> #ifdef __cplusplus extern "C" { #endif /* * Important word offsets in device identify data as * defined in ATA-5 standard */ enum { kATAIdentifyConfiguration = 0, kATAIdentifyLogicalCylinderCount = 1, kATAIdentifyLogicalHeadCount = 3, kATAIdentifySectorsPerTrack = 6, kATAIdentifySerialNumber = 10, kATAIdentifyFirmwareRevision = 23, kATAIdentifyModelNumber = 27, kATAIdentifyMultipleSectorCount = 47, kATAIdentifyDriveCapabilities = 49, kATAIdentifyDriveCapabilitiesExtended = 50, kATAIdentifyPIOTiming = 51, kATAIdentifyExtendedInfoSupport = 53, kATAIdentifyCurrentCylinders = 54, kATAIdentifyCurrentHeads = 55, kATAIdentifyCurrentSectors = 56, kATAIdentifyCurrentCapacity = 57, kATAIdentifyCurrentMultipleSectors = 59, kATAIdentifyLBACapacity = 60, kATAIdentifySingleWordDMA = 62, kATAIdentifyMultiWordDMA = 63, kATAIdentifyAdvancedPIOModes = 64, kATAIdentifyMinMultiWordDMATime = 65, kATAIdentifyRecommendedMultiWordDMATime = 66, kATAIdentifyMinPIOTime = 67, kATAIdentifyMinPIOTimeWithIORDY = 68, kATAIdentifyQueueDepth = 75, kATAIdentifyMajorVersion = 80, kATAIdentifyMinorVersion = 81, kATAIdentifyCommandSetSupported = 82, kATAIdentifyCommandSetSupported2 = 83, kATAIdentifyCommandExtension1 = 84, kATAIdentifyCommandExtension2 = 85, kATAIdentifyCommandsEnabled = 86, kATAIdentifyCommandsDefault = 87, kATAIdentifyUltraDMASupported = 88, kATAIdentifyPhysicalLogicalSectorSize = 106, kATAIdentifyWordsPerLogicalSector1 = 117, kATAIdentifyWordsPerLogicalSector2 = 118, kATAIdentifyLogicalSectorAlignment = 209, kATAIdentifyIntegrity = 255 }; /* * Important bits in device identify data * as defined in ATA-5 standard */ enum { // Configuration field (word 0) kFixedDeviceBit = 6, // Fixed disk indicator bit kRemoveableMediaBit = 7, // Removable media indicator bit kNonMagneticDriveBit = 15, // Non-magnetic drive indicator bit kFixedDeviceMask = (1 << kFixedDeviceBit), // Mask for fixed disk indicator kRemoveableMediaMask = (1 << kRemoveableMediaBit), // Mask for removable media indicator kNonMagneticDriveMask = (1 << kNonMagneticDriveBit), // Mask for non-magnetic drive indicator // Capabilities field (word 49) kDMABit = 8, // DMA supported bit kLBABit = 9, // LBA supported bit kIORDYDisableBit = 10, // IORDY can be disabled bit kIORDYBit = 11, // IORDY supported bit kStandbyTimerBit = 13, // Standby timer supported bit kDMASupportedMask = (1 << kDMABit), // Mask for DMA supported kLBASupportedMask = (1 << kLBABit), // Mask for LBA supported kDMADisableMask = (1 << kIORDYDisableBit), // Mask for DMA supported kIORDYSupportedMask = (1 << kIORDYBit), // Mask for IORDY supported kStandbySupportedMask = (1 << kStandbyTimerBit), // Mask for Standby Timer supported // Extensions field (word 53) kCurFieldsValidBit = 0, // Bit to show words 54-58 are valid kExtFieldsValidBit = 1, // Bit to show words 64-70 are valid kCurFieldsValidMask = (1 << kCurFieldsValidBit), // Mask for current fields valid kExtFieldsValidMask = (1 << kExtFieldsValidBit), // Extension word valid // Advanced PIO Transfer Modes field (word 64) kMode3Bit = 0, // Bit to indicate mode 3 is supported kMode3Mask = (1 << kMode3Bit), // Mask for mode 3 support // Integrity of Identify data (word 255) kChecksumValidCookie = 0xA5 // Bits 7:0 if device supports feature }; /* String size constants */ enum { kSizeOfATAModelString = 40, kSizeOfATARevisionString = 8 }; /* ATA Command timeout constants ( in milliseconds ) */ enum { kATATimeout10Seconds = 10000, kATATimeout30Seconds = 30000, kATATimeout45Seconds = 45000, kATATimeout1Minute = 60000, kATADefaultTimeout = kATATimeout30Seconds }; /* Retry constants */ enum { kATAZeroRetries = 0, kATADefaultRetries = 4 }; /* max number of blocks supported in ATA transaction */ enum { kIOATASectorCount8Bit = 8, kIOATASectorCount16Bit = 16 }; enum { kIOATAMaximumBlockCount8Bit = (1 << kIOATASectorCount8Bit), kIOATAMaximumBlockCount16Bit = (1 << kIOATASectorCount16Bit), // For backwards compatibility kIOATAMaxBlocksPerXfer = kIOATAMaximumBlockCount8Bit }; /* Power Management time constants (in seconds) */ enum { kSecondsInAMinute = 60, k5Minutes = 5 * kSecondsInAMinute }; /* Bits for features published in Word 82 of device identify data */ enum { kATASupportsSMARTBit = 0, kATASupportsPowerManagementBit = 3, kATASupportsWriteCacheBit = 5 }; /* Masks for features published in Word 82 of device identify data */ enum { kATASupportsSMARTMask = (1 << kATASupportsSMARTBit), kATASupportsPowerManagementMask = (1 << kATASupportsPowerManagementBit), kATASupportsWriteCacheMask = (1 << kATASupportsWriteCacheBit) }; /* Bits for features published in Word 83 of device identify data */ enum { kATASupportsCompactFlashBit = 2, kATASupportsAdvancedPowerManagementBit = 3, kATASupports48BitAddressingBit = 10, kATASupportsFlushCacheBit = 12, kATASupportsFlushCacheExtendedBit = 13 }; /* Masks for features published in Word 83 of device identify data */ enum { kATASupportsCompactFlashMask = (1 << kATASupportsCompactFlashBit), kATASupportsAdvancedPowerManagementMask = (1 << kATASupportsAdvancedPowerManagementBit), kATASupports48BitAddressingMask = (1 << kATASupports48BitAddressingBit), kATASupportsFlushCacheMask = (1 << kATASupportsFlushCacheBit), kATASupportsFlushCacheExtendedMask = (1 << kATASupportsFlushCacheExtendedBit), // Mask to ensure data is valid kIdentifyWordValidationMask = 0xC000, kIdentifyWordValid = 0x4000 }; /* Bits for features published in Word 84 of device identify data */ enum { kATAForceUnitAccessFeatureBit = 6, }; /* Masks for features published in Word 84 of device identify data */ enum { kATAForceUnitAccessFeatureMask = (1 << kATAForceUnitAccessFeatureBit), }; /* Bits for features published in Word 85 of device identify data */ enum { kATAWriteCacheEnabledBit = 5 }; /* Masks for features published in Word 85 of device identify data */ enum { kATAWriteCacheEnabledMask = (1 << kATAWriteCacheEnabledBit) }; /* Bits for features published in Word 106 of device identify data */ enum { kATAPhysicalLogicalEnabledBit0 = 15, kATAPhysicalLogicalEnabledBit1 = 14, kATAMultipleLogicalSectorsBit = 13, kATAValidLogicalSectorSizeBit = 12 }; /* Masks for features published in Word 106 of device identify data */ enum { kATAPhysicalLogicalEnabledMask = (1 << kATAPhysicalLogicalEnabledBit0) | (1 << kATAPhysicalLogicalEnabledBit1), kATAPhysicalLogicalEnabledValue = (0 << kATAPhysicalLogicalEnabledBit0) | (1 << kATAPhysicalLogicalEnabledBit1), kATAMultipleLogicalSectorsMask = (1 << kATAMultipleLogicalSectorsBit), kATAValidLogicalSectorSizeMask = (1 << kATAValidLogicalSectorSizeBit), kATAPhysicalSectorSizeMask = 0xF, kATALogicalSectorAlignmentMask = 0x3FFF }; // Property table keys #define kIOATASupportedFeaturesKey "ATA Features" /* ATA supported features */ enum { kIOATAFeaturePowerManagement = 0x01, /* OBSOLETE */ kIOATAFeatureWriteCache = 0x02, /* OBSOLETE */ kIOATAFeatureAdvancedPowerManagement = 0x04, kIOATAFeatureCompactFlash = 0x08, kIOATAFeature48BitLBA = 0x10, kIOATAFeatureSMART = 0x20 }; /* ATA Advanced Power Management settings (valid settings range from 1-254), the settings below are the more common settings */ enum { kIOATAMaxPerformance = 0xFE, kIOATADefaultPerformance = 0x80, kIOATAMaxPowerSavings = 0x01 }; /* ATA Transfer Mode bit masks */ enum { kATAEnableUltraDMAModeMask = 0x40, kATAEnableMultiWordDMAModeMask = 0x20, kATAEnablePIOModeMask = 0x08 }; typedef uint32_t ATAOperationType; enum { kATAOperationTypeRead = 0, kATAOperationTypeWrite = 1, kATAOperationTypeFlushCache = 2, kATAOperationTypeSMART = 3, kATAOperationTypeConfiguration = 4, kATAOperationTypePowerManagement = 5, kATAOperationTypeSMS = 6 }; #if defined(KERNEL) typedef struct __ATAIORequest * ATARequestIdentifier; #endif // defined(KERNEL) #ifdef __cplusplus } #endif #endif /* _IOKIT_IO_ATA_STORAGE_DEFINES_H_ */
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/storage
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/storage/ata/ATASMARTLib.h
/* * Copyright (c) 1998-2007 Apple Inc. All rights reserved. * * @APPLE_LICENSE_HEADER_START@ * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this * file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_LICENSE_HEADER_END@ */ #ifndef __ATA_SMART_LIB_H__ #define __ATA_SMART_LIB_H__ /*! @defined kIOPropertySMARTCapableKey @discussion Property to search for in IORegistry to find SMART capable devices without hardcoding the search to a particular device class. */ #define kIOPropertySMARTCapableKey "SMART Capable" #include <IOKit/IOReturn.h> #include <IOKit/IOTypes.h> #if !KERNEL #include <CoreFoundation/CFPlugIn.h> #if COREFOUNDATION_CFPLUGINCOM_SEPARATE #include <CoreFoundation/CFPlugInCOM.h> #endif #include <IOKit/IOCFPlugIn.h> #include <IOKit/storage/ata/IOATAStorageDefines.h> #ifdef __cplusplus extern "C" { #endif /*! @header ATASMARTLib ATASMARTLib implements non-kernel task access to ATA SMART data. */ /* 5E659F92-20D3-11D6-BDB5-0003935A76B2 */ /*! @defined kIOATASMARTLibFactoryID @discussion UUID for the IOATASMARTInterface Factory. */ #define kIOATASMARTLibFactoryID CFUUIDGetConstantUUIDWithBytes(NULL, \ 0x5E, 0x65, 0x9F, 0x92, 0x20, 0xD3, 0x11, 0xD6, \ 0xBD, 0xB5, 0x00, 0x03, 0x93, 0x5A, 0x76, 0xB2) /* 24514B7A-2804-11D6-8A02-003065704866 */ /*! @defined kIOATASMARTUserClientTypeID @discussion Factory ID for creating an ATA SMART user client. */ #define kIOATASMARTUserClientTypeID CFUUIDGetConstantUUIDWithBytes(NULL, \ 0x24, 0x51, 0x4B, 0x7A, 0x28, 0x04, 0x11, 0xD6, \ 0x8A, 0x02, 0x00, 0x30, 0x65, 0x70, 0x48, 0x66) /* 08ABE21C-20D4-11D6-8DF6-0003935A76B2 */ /*! @defined kIOATASMARTInterfaceID @discussion InterfaceID for IOATASMARTInterface. */ #define kIOATASMARTInterfaceID CFUUIDGetConstantUUIDWithBytes(NULL, \ 0x08, 0xAB, 0xE2, 0x1C, 0x20, 0xD4, 0x11, 0xD6, \ 0x8D, 0xF6, 0x00, 0x03, 0x93, 0x5A, 0x76, 0xB2) #endif /* !KERNEL */ // Off-line data collection status byte values ( offset 362 into // device SMART data structure ) See section 8.54.5.8.1 of ATA/ATAPI-6. enum { kATASMARTOffLineCollectionNeverStarted = 0x00, kATASMARTOffLineCollectionNoError = 0x02, kATASMARTOffLineCollectionSuspendedByHost = 0x04, kATASMARTOffLineCollectionAbortedByHost = 0x05, kATASMARTOffLineCollectionFatalError = 0x06, kATASMARTOffLineCollectionMask = 0x7F }; // Self-test execution status values ( offset 363 into // Device SMART data structure ) See section 8.54.5.8.2 of ATA/ATAPI-6. enum { kATASMARTSelfTestStatusNoError = 0x00, kATASMARTSelfTestStatusAbortedByHost = 0x01, kATASMARTSelfTestStatusInterruptedByReset = 0x02, kATASMARTSelfTestStatusFatalError = 0x03, kATASMARTSelfTestStatusPreviousTestUnknownFailure = 0x04, kATASMARTSelfTestStatusPreviousTestElectricalFailure = 0x05, kATASMARTSelfTestStatusPreviousTestServoFailure = 0x06, kATASMARTSelfTestStatusPreviousTestReadFailure = 0x07, kATASMARTSelfTestStatusInProgress = 0x0F }; /* * 512 byte Device SMART data structure - * See section 8.54.5.8 of T13:1410D (ATA/ATAPI-6). */ typedef struct ATASMARTData { UInt8 vendorSpecific1[362]; UInt8 offLineDataCollectionStatus; UInt8 selfTestExecutionStatus; UInt8 secondsToCompleteOffLineActivity[2]; UInt8 vendorSpecific2; UInt8 offLineDataCollectionCapability; UInt8 SMARTCapability[2]; UInt8 errorLoggingCapability; UInt8 vendorSpecific3; UInt8 shortTestPollingInterval; /* expressed in minutes */ UInt8 extendedTestPollingInterval; /* expressed in minutes */ UInt8 reserved[12]; UInt8 vendorSpecific4[125]; UInt8 checksum; } ATASMARTData; /* * 512 byte Device SMART data thresholds structure. Not * strictly part of ATA/ATAPI-6. */ typedef struct ATASMARTDataThresholds { UInt8 vendorSpecific1[362]; UInt8 vendorSpecific2[149]; UInt8 checksum; } ATASMARTDataThresholds; typedef struct ATASMARTLogEntry { UInt8 numberOfSectors; UInt8 reserved; } ATASMARTLogEntry; typedef struct ATASMARTLogDirectory { UInt8 SMARTLoggingVersion[2]; ATASMARTLogEntry entries[255]; } ATASMARTLogDirectory; #if !KERNEL /*! * @interface IOATASMARTInterface * @abstract Self-Monitoring, Analysis, and Reporting * Technology Interface. * @discussion See section 6.14 and section 8.54 of T13:1410D ATA/ATAPI-6 * for details on Self-Monitoring, Analysis, and Reporting Technology * feature set. */ typedef struct IOATASMARTInterface { IUNKNOWN_C_GUTS; UInt16 version; UInt16 revision; /* * MANDATORY API support. If the device claims SMART feature set compliance, it * must implement the following functions. */ /*! @function SMARTEnableDisableOperations @abstract toggle SMART Operations. @discussion See section 8.54.1 and 8.54.3 of ATA/ATAPI-6. @param enable Passing true will ENABLE SMART operations, false will DISABLE SMART operations. @result Returns kIOReturnSuccess if successful, kIOReturnNoDevice if there is no connection to an IOService, kIOReturnExclusiveAccess if it is already opened by another client. */ IOReturn ( *SMARTEnableDisableOperations ) ( void * interface, Boolean enable ); /*! @function SMARTEnableDisableAutosave @abstract toggle SMART Autosave. @discussion See section 8.54.2 of ATA/ATAPI-6. @param enable Passing true will ENABLE SMART Autosave, false will DISABLE SMART Autosave. @result Returns kIOReturnSuccess if successful, kIOReturnNoDevice if there is no connection to an IOService, kIOReturnExclusiveAccess if it is already opened by another client. */ IOReturn ( *SMARTEnableDisableAutosave ) ( void * interface, Boolean enable ); /*! @function SMARTReturnStatus @abstract see if device has detected a threshold exceeded condition. @discussion The caller will poll this function and if exceededCondition is non-zero and we returned kIOReturnSuccess the device threshold exceeded condition. This would prompt the caller to call ATASMARTReadData to get more information. See section 8.54.7 of ATA/ATAPI-6. @param exceededCondition if exceededCondition is non-zero the device threshold exceeded condition. @result Returns kIOReturnSuccess if successful, kIOReturnNoDevice if there is no connection to an IOService, kIOReturnExclusiveAccess if it is already opened by another client. */ IOReturn ( *SMARTReturnStatus ) ( void * interface, Boolean * exceededCondition ); /* * OPTIONAL API support. If the device claims SMART feature set compliance, it * may implement one or more of the following functions. Please consult the * technical manual for the device to see what functions are supported. */ /*! @function SMARTExecuteOffLineImmediate @abstract immediately initiate collection of SMART data. @discussion See section 8.54.4 of ATA/ATAPI-6. @param extendedTest passing true will collect "off-line" extended test, false short test. @result Returns kIOReturnSuccess if successful, kIOReturnNoDevice if there is no connection to an IOService, kIOReturnExclusiveAccess if it is already opened by another client. */ IOReturn ( *SMARTExecuteOffLineImmediate ) ( void * interface, Boolean extendedTest ); /*! @function SMARTReadData @abstract Retrieves 512 byte device SMART data structure. @discussion See section 8.54.5 of ATA/ATAPI-6. Will return an appropiate error if command can not be completed. */ IOReturn ( *SMARTReadData ) ( void * interface, ATASMARTData * data ); /*! @function SMARTValidateReadData @abstract Test the integrity of the device SMART data structure. @discussion The data structure checksum is the two's complement of the sum of the first 511 bytes in the data structure. The sum of all 512 bytes will be zero when the checksum is correct. See section 8.54.5.8.7 of ATA/ATAPI-6. Will return an error if checksum fails. */ IOReturn ( *SMARTValidateReadData ) ( void * interface, const ATASMARTData * data ); /*! @function SMARTReadDataThresholds @abstract Retrieves 512 byte device SMART data thresholds structure. @discussion Retrieves 512 byte device SMART data thresholds structure. This command is not defined as part of ATA/ATAPI-6, but is implemented by a large variety of manufacturers. Will return an appropiate error if command can not be completed. */ IOReturn ( *SMARTReadDataThresholds ) ( void * interface, ATASMARTDataThresholds * dataThresholds ); /*! @function SMARTReadLogDirectory @abstract Reads the 512-byte log directory. @discussion The log directory is a directory of all possible SMART logs available from the drive. */ IOReturn ( *SMARTReadLogDirectory ) ( void * interface, ATASMARTLogDirectory * logData ); /*! @function SMARTReadLogAtAddress @abstract Reads the 512-byte log at the specified logOffset in the log. @discussion Reads the 512-byte log at the specified logOffset in the log. See section 8.54.6.4 of ATA/ATAPI-6. */ IOReturn ( *SMARTReadLogAtAddress ) ( void * interface, UInt32 logOffset, void * buffer, UInt32 size ); /*! @function SMARTWriteLogAtAddress @abstract Writes to the 512-byte log at the specified logOffset in the log. @discussion Writes to the 512-byte log at the specified logOffset in the log. See section 8.54.8.4 of ATA/ATAPI-6. */ IOReturn ( *SMARTWriteLogAtAddress ) ( void * interface, UInt32 logOffset, const void * buffer, UInt32 size ); /*! @function GetATAIdentifyData @abstract Reads the 512-byte data provided by the drive in response to the ATA IDENTIFY DEVICE command. @discussion Reads the 512-byte data provided by the drive in response to the ATA IDENTIFY DEVICE command. See section 8.15 of ATA/ATAPI-6. The data placed in buffer is guaranteed to be in native endian form on return. (i.e. it will be byte swapped on big endian platforms, so the caller need not do anything) @param interface A valid IOATASMARTInterface**. @param buffer A valid buffer. @param inSize The number of bytes to place in the buffer. @param outSize The number of bytes placed in the buffer. Can be NULL if the information is not required by the caller. @return An IOReturn result code. If inSize is greater than 512 or less than 1, kIOReturnBadArgument is returned. */ IOReturn ( *GetATAIdentifyData ) ( void * interface, void * buffer, UInt32 inSize, UInt32 * outSize ); } IOATASMARTInterface; #ifdef __cplusplus } #endif #endif /* !KERNEL */ #endif /* __ATA_SMART_LIB_H__ */
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/storage
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/storage/nvme/NVMeSMARTLibExternal.h
/* * Copyright (c) 1998-2020 Apple Inc. All rights reserved. * * @APPLE_LICENSE_HEADER_START@ * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this * file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_LICENSE_HEADER_END@ */ #ifndef __NVME_SMART_LIB_EXTERNAL_H__ #define __NVME_SMART_LIB_EXTERNAL_H__ /*! @defined kIOPropertySMARTCapableKey @discussion Property to search for in IORegistry to find NVMe SMART capable devices without hardcoding the search to a particular device class. */ #define kIOPropertyNVMeSMARTCapableKey "NVMe SMART Capable" #include <IOKit/IOReturn.h> #include <IOKit/IOTypes.h> #if !KERNEL #include <CoreFoundation/CFPlugIn.h> #if COREFOUNDATION_CFPLUGINCOM_SEPARATE #include <CoreFoundation/CFPlugInCOM.h> #endif #include <IOKit/IOCFPlugIn.h> #ifdef __cplusplus extern "C" { #endif /*! @header NVMeSMARTLib NVMeSMARTLib implements non-kernel task access to NVMe SMART data. */ /* 68413F59-268A-4787-BC48-7F9960235647 */ /*! @defined kIONVMeSMARTLibFactoryID @discussion UUID for the IONVMeSMARTInterface Factory. */ #define kIONVMeSMARTLibFactoryID CFUUIDGetConstantUUIDWithBytes(NULL, \ 0x68, 0x41, 0x3F, 0x59, 0x26, 0x8A, 0x47, 0x87, \ 0xBC, 0x48, 0x7F, 0x99, 0x60, 0x23, 0x56, 0x47) /* AA0FA6F9-C2D6-457F-B10B-59A13253292F */ /*! @defined kIONVMeSMARTUserClientTypeID @discussion Factory ID for creating an NVMe SMART user client. */ #define kIONVMeSMARTUserClientTypeID CFUUIDGetConstantUUIDWithBytes(NULL, \ 0xAA, 0x0F, 0xA6, 0xF9, 0xC2, 0xD6, 0x45, 0x7F, \ 0xB1, 0x0B, 0x59, 0xA1, 0x32, 0x53, 0x29, 0x2F) /* CCD1DB19-FD9A-4DAF-BF95-12454B230AB6 */ /*! @defined kIONVMeSMARTInterfaceID @discussion InterfaceID for IONVMeSMARTInterface. */ #define kIONVMeSMARTInterfaceID CFUUIDGetConstantUUIDWithBytes(NULL, \ 0xCC, 0xD1, 0xDB, 0x19, 0xFD, 0x9A, 0x4D, 0xAF, \ 0xBF, 0x95, 0x12, 0x45, 0x4B, 0x23, 0x0A, 0xB6) #endif /* !KERNEL */ enum { kNVMeIdentifyControllerSerialNumberLen = 20, kNVMeIdentifyControllerModelNumberLen = 40, kNVMeIdentifyControllerFirmwareRevisionLen = 8, kNVMeIdentifyControllerIEEEOUIIDLen = 3, }; #pragma pack(1) typedef struct NVMePowerStateDescriptor { uint16_t MAXIMUM_POWER; uint8_t RESERVED1[2]; uint32_t ENTRY_LATENCY; uint32_t EXIT_LATENCY; uint8_t RELATIVE_READ_THROUGHPUT; uint8_t RELATIVE_READ_LATENCY; uint8_t RELATIVE_WRITE_THROUGHPUT; uint8_t RELATIVE_WRITE_LATENCY; uint8_t RESERVED2[16]; } NVMePowerStateDescriptor; typedef struct NVMeIdentifyControllerStruct { // Controller Capabilites and Features uint16_t PCI_VID; uint16_t PCI_SSVID; uint8_t SERIAL_NUMBER[kNVMeIdentifyControllerSerialNumberLen]; uint8_t MODEL_NUMBER[kNVMeIdentifyControllerModelNumberLen]; uint8_t FW_REVISION[kNVMeIdentifyControllerFirmwareRevisionLen]; uint8_t RECOMMENDED_ARBITRATION_BURST; uint8_t IEEE_OUI_ID[kNVMeIdentifyControllerIEEEOUIIDLen]; uint8_t MIC; uint8_t MAX_DATA_TRANSFER_SIZE; uint16_t CONTROLLER_ID; uint8_t RESERVED1[176]; // Admin Command Set Attributes uint16_t OPTIONAL_ADMIN_COMMAND_SUPPORT; uint8_t ABORT_COMMAND_LIMIT; uint8_t ASYNC_EVENT_REQUEST_LIMIT; uint8_t FW_UPDATES; uint8_t LOG_PAGE_ATTR; uint8_t ERROR_LOG_PAGE_ENTRIES; uint8_t NUM_OF_POWER_STATE_SUPPORT; uint8_t ADMIN_VENDOR_SPECIFIC_COMMAND_CONFIG; uint8_t AUTONOMOUS_POWER_STATE_TRANSITION_ATTR; uint8_t RESERVED2[246]; // NVM Command Set Attributes uint8_t SQ_ENTRY_SIZE; uint8_t CQ_ENTRY_SIZE; uint8_t RESERVED3[2]; uint32_t NUM_OF_NAMESPACES; uint16_t OPTIONAL_NVM_COMMAND_SUPPORT; uint16_t FUSE_OP_SUPPORT; uint8_t FORMAT_NVM_ATTR; uint8_t VOLATILE_WRITE_CACHE; uint16_t ATOMIC_WRITE_UNIT_NORMAL; uint16_t ATOMIC_WRITE_UNIT_POWER_FAIL; uint8_t NVM_VENDOR_SPECIFIC_COMMAND_CONFIG; uint8_t RESERVED4[1]; uint16_t ATOMIC_COMPARE_AND_WRITE_UNIT; uint8_t RESERVED5[2]; uint32_t SGL_SUPPORT; uint8_t RESERVED6[164]; // I/O Command Set Attributes uint8_t RESERVED7[1344]; // Power State Descriptors NVMePowerStateDescriptor POWER_STATE_DESCRIPTORS[32]; uint8_t RESERVED8[1024]; } NVMeIdentifyControllerStruct; typedef struct NVMeLBAFormatDataStruct { uint16_t METADATA_SIZE; uint8_t LBA_DATA_SIZE; uint8_t RELATIVE_PERFORMANCE; } NVMeLBAFormatDataStruct; typedef struct NVMeIdentifyNamespaceStruct { uint64_t NAMESPACE_SIZE; uint64_t NAMESPACE_CAPACITY; uint64_t NAMESPACE_UTILIZATION; uint8_t NAMESPACE_FEATURES; uint8_t NUM_OF_LBA_FORMATS; uint8_t FORMATTED_LBA_SIZE; uint8_t METADATA_CAPS; uint8_t E2E_DATA_PROTECTION_CAPS; uint8_t E2E_DATA_PROTECTION_TYPE_SETTINGS; uint8_t NS_MULTIPATH_IO_AND_NS_SHARING_CAPS; uint8_t RESERVATION_CAPABILITIES; uint8_t RESERVED1[88]; uint64_t IEEE_EXTENDED_UID; NVMeLBAFormatDataStruct LBA_FORMATS[16]; uint8_t RESERVED2[192]; // Vendor Specific Stuff uint8_t NSTYPE; uint8_t VENDOR_SPECIFIC[3711]; } NVMeIdentifyNamespaceStruct; typedef struct NVMeSMARTData { uint8_t CRITICAL_WARNING; uint16_t TEMPERATURE; uint8_t AVAILABLE_SPARE; uint8_t AVAILABLE_SPARE_THRESHOLD; uint8_t PERCENTAGE_USED; uint8_t RESERVED1[26]; uint64_t DATA_UNITS_READ[2]; uint64_t DATA_UNITS_WRITTEN[2]; uint64_t HOST_READ_COMMANDS[2]; uint64_t HOST_WRITE_COMMANDS[2]; uint64_t CONTROLLER_BUSY_TIME[2]; uint64_t POWER_CYCLES[2]; uint64_t POWER_ON_HOURS[2]; uint64_t UNSAFE_SHUTDOWNS[2]; uint64_t MEDIA_ERRORS[2]; uint64_t NUM_ERROR_INFO_LOG_ENTRIES[2]; uint8_t RESERVED2[320]; } NVMeSMARTData; #pragma options align=reset #if !KERNEL typedef struct IONVMeSMARTInterface { IUNKNOWN_C_GUTS; UInt16 version; UInt16 revision; /*! @function SMARTReadData @abstract Retrieves 512 byte device SMART data structure. @discussion See section 5.10.1.2 of NVM Express revision 1.0c. @param data Pointer to a SMART data buffer. @return kIOReturnNoResources If memory allocation failed. @return kIOReturnBadArgument Invalid argument passed. @return kIOReturnOffline Device is offline. @return kIOReturnSuccess Success. */ IOReturn ( *SMARTReadData ) ( void * interface, NVMeSMARTData * data ); /*! @function GetIdentifyData @abstract Retrieves a 4K device or namespace identify data buffer. @discussion See section 5.11 of NVM Express revision 1.0c. @param data Pointer to either an controller or namespace identify strucutre. @param inNamspace Namespace ID or 0 for controller identify data. @return kIOReturnNoResources If memory allocation failed. @return kIOReturnBadArgument Invalid argument passed. @return kIOReturnOffline Device is offline. @return kIOReturnSuccess Success. */ IOReturn ( *GetIdentifyData ) ( void * interface, void * data, uint32_t inNamespace ); UInt64 reserved0; UInt64 reserved1; /*! @function GetLogPage @abstract Retrieves a log page. @discussion See section 5.10 of NVM Express revision 1.0c. @param data Pointer to buffer that will contain log page data. @param inLogPageId Log page ID for this get log page command. @param inNumDWords Number of dwords for log page data, zero based. @return kIOReturnNoResources If memory allocation failed. @return kIOReturnBadArgument Invalid argument passed. @return kIOReturnOffline Device is offline. @return kIOReturnSuccess Success. */ IOReturn ( *GetLogPage ) ( void * interface, void * data, uint32_t inLogPageId, uint32_t inNumDWords ); UInt64 reserved2; UInt64 reserved3; UInt64 reserved4; UInt64 reserved5; UInt64 reserved6; UInt64 reserved7; UInt64 reserved8; UInt64 reserved9; UInt64 reserved10; UInt64 reserved11; UInt64 reserved12; UInt64 reserved13; UInt64 reserved14; UInt64 reserved15; UInt64 reserved16; UInt64 reserved17; UInt64 reserved18; UInt64 reserved19; UInt64 reserved20; UInt64 reserved21; UInt64 reserved22; UInt64 reserved23; } IONVMeSMARTInterface; #ifdef __cplusplus } #endif #endif /* !KERNEL */ #endif /* __NVME_SMART_LIB_EXTERNAL_H__ */
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/graphics/IOFramebufferShared.h
/* * Copyright (c) 1998-2000 Apple Computer, Inc. All rights reserved. * * @APPLE_LICENSE_HEADER_START@ * * The contents of this file constitute Original Code as defined in and * are subject to the Apple Public Source License Version 1.1 (the * "License"). You may not use this file except in compliance with the * License. Please obtain a copy of the License at * http://www.apple.com/publicsource and read it before using this file. * * This Original Code and all software distributed under the License are * distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT. Please see the * License for the specific language governing rights and limitations * under the License. * * @APPLE_LICENSE_HEADER_END@ */ #ifndef _IOKIT_IOFRAMEBUFFERSHARED_H #define _IOKIT_IOFRAMEBUFFERSHARED_H #include <IOKit/hidsystem/IOHIDTypes.h> #include <IOKit/graphics/IOGraphicsTypes.h> #include <libkern/OSAtomic.h> #ifdef __cplusplus extern "C" { #endif /*! @header IOFramebufferShared The IOFramebufferShared.h header contains definitions of objects and types shared between a kernel level IOFrameBuffer service and a non-kernel window server. In Mac OS X this structure is used by the CoreGraphics server and IOGraphics Family, and is not available to other clients. IOFramebuffer subclasses and IOFramebuffer clients within the kernel should also not rely on this structure definition and constants. It is public only for use on Darwin based window servers. Cursor and window server state data is exchanged by kernel and non-kernel tasks through a slice of shared memory containing a StdFBShmem_t structure.<br> For a non-kernel task to get access to this slice of shared memory, a connection to an IOFramebuffer service must be made. A connection is made with the IOServiceOpen() function described in IOKitLib.h. A connection type of kIOFBServerConnectType or kIOFBSharedConnectType (for read-only access) should be specified. An io_connect_t handle is returned by IOServiceOpen(). This handle must be passed to IOFBCreateSharedCursor() to create the slice of shared memory. Then IOConnectMapMemory() may be called with a memory type of kIOFBCursorMemory to map the shared memory into the non-kernel task. */ #ifdef KERNEL // CGS use optional /*! @defined IOFB_ARBITRARY_SIZE_CURSOR @discussion When IOFB_ARBITRARY_SIZE_CURSOR is not defined, the maximum cursor size is assumed to be CURSORWIDTH x CURSORHEIGHT and this header file will define a number of structures for storing cursor images accordingly. A non-kernel task may define IOFB_ARBITRARY_SIZE_CURSOR and use cursors up to the size specified when IOFBCreateSharedCursor() was called. In this case appropriate structures for storing cursor images must be defined elsewhere. In the kernel, IOFB_ARBITRARY_SIZE_CURSOR is always defined. */ #define IOFB_ARBITRARY_SIZE_CURSOR #define IOFB_ARBITRARY_FRAMES_CURSOR 1 #endif #define IOFB_SUPPORTS_XOR_CURSOR #define IOFB_SUPPORTS_HW_SHIELD #define IOFB_SUPPORTS_ARBITRARY_FRAMES_CURSOR // // Cursor and Window Server state data, occupying a slice of shared memory // between the kernel and WindowServer. // /*! @enum CursorParameters @constant kIOFBNumCursorFrames The number of cursor images stored in the StdFBShmem_t structure. @constant kIOFBNumCursorFramesShift Used with waiting cursors. @constant kIOFBMaxCursorDepth The maximum cursor pixel depth. */ enum { #if IOFB_ARBITRARY_FRAMES_CURSOR kIOFBMainCursorIndex = 0, kIOFBWaitCursorIndex = 1, kIOFBNumCursorIndex = 4, #else kIOFBNumCursorFrames = 4, kIOFBNumCursorFramesShift = 2, #endif kIOFBMaxCursorDepth = 32, kIOFBMaxCursorWidth = 256, kIOFBMaxCursorFrames = 32, }; #ifndef IOFB_ARBITRARY_SIZE_CURSOR /*! @defined CURSORWIDTH @discussion The maximum width of the cursor image in pixels. This is only defined if IOFB_ARBITRARY_SIZE_CURSOR is not defined. */ #define CURSORWIDTH 16 /* width in pixels */ /*! @defined CURSORHEIGHT @discussion The maximum height of the cursor image in pixels. This is only defined if IOFB_ARBITRARY_SIZE_CURSOR is not defined. */ #define CURSORHEIGHT 16 /* height in pixels */ /*! @struct bm12Cursor @abstract Cursor image for 1-bit cursor. @discussion This structure stores 16 pixel x 16 pixel cursors to be used with 1-bit color depth. This structure is only defined if IOFB_ARBITRARY_SIZE_CURSOR is not defined. @field image This array contains the cursor images. @field mask This array contains the cursor mask. @field save This array stores the pixel values of the region underneath the cursor in its last drawn position. */ struct bm12Cursor { unsigned int image[4][16]; unsigned int mask[4][16]; unsigned int save[16]; }; /*! @struct bm18Cursor @abstract Cursor image for 8-bit cursor. @discussion This structure stores 16 pixel x 16 pixel cursors to be used with 8-bit color depth. This structure is only defined if IOFB_ARBITRARY_SIZE_CURSOR is not defined. @field image This array contains cursor color values, which are converted to displayed colors through the color table. The array is two dimensional and its first index is the cursor frame and the second index is the cursor pixel. @field mask This array contains the cursor alpha mask. The array is two dimensional with the same indexing as the image. If an alpha mask pixel is 0 and the corresponding image pixel is set to white for the display, then this cursor pixel will invert pixels on the display. @field save This array stores the color values of the region underneath the cursor in its last drawn position. */ struct bm18Cursor { unsigned char image[4][256]; unsigned char mask[4][256]; unsigned char save[256]; }; /*! @struct bm34Cursor @abstract Cursor image for 15-bit cursor. @discussion This structure stores 16 pixel x 16 pixel cursors to be used with 15-bit color depth. This structure is only defined if IOFB_ARBITRARY_SIZE_CURSOR is not defined. @field image This array defines the cursor color values and transparency. The array is two dimensional and its first index is the cursor frame and the second index is the cursor pixel. A value of 0 means the pixel is transparent. Non-zero values are stored with the red, green, blue, and alpha values encoded with the following masks:<BR> red mask = 0xF000<br> blue mask 0x0F00<br> green mask 0x00F0<br> alpha mask = 0x000F<br> Note, only 4 bits are allocated for each color component. @field save This array stores the color values of the region underneath the cursor in its last drawn position. */ struct bm34Cursor { unsigned short image[4][256]; unsigned short save[256]; }; /*! @struct bm38Cursor @abstract Cursor image for 24-bit cursor. @discussion This structure stores 16 pixel x 16 pixel cursors to be used with 24-bit color depth. This structure is only defined if IOFB_ARBITRARY_SIZE_CURSOR is not defined. @field image This array defines the cursor color values and transparency. The array is two dimensional and its first index is the cursor frame and the second index is the cursor pixel. The lower 24 bits of a pixel's value contain the RGB color, while the upper 8 bits contain the alpha value. @field save This array stores the color values of the region underneath the cursor in its last drawn position. */ struct bm38Cursor { unsigned int image[4][256]; unsigned int save[256]; }; #endif /* IOFB_ARBITRARY_SIZE_CURSOR */ enum { kIOFBCursorImageNew = 0x01, kIOFBCursorHWCapable = 0x02 }; enum { kIOFBHardwareCursorActive = 0x01, kIOFBHardwareCursorInVRAM = 0x02 }; /*! @struct StdFBShmem_t @discussion This structure contains cursor and window server state data and occupies a slice of shared memory between the kernel and window server. Several elements of this structure are only used in software cursor mode. Unless otherwise indicated, the coordinates in this structure are given in display space. Display space is the coordinate space that encompasses all the screens. The positions of the screens within display space indicate their location relative to each other as the cursor moves between them. If there is only one screen, the screen coordinates and display space coordinates will be the same. @field cursorSema Semaphore lock for write access to the shared data in this structure. @field frame The current cursor frame index. @field cursorShow The cursor is displayed when cursorShow is 0. @field cursorObscured If this is true, the cursor has been obscured and cursorShow should not be 0. The cursor will be shown again the next time it is moved. @field shieldFlag When this is set to true the cursor will not be displayed in the region specified by shieldRect. @field shielded True if the cursor has been hidden because it entered the shielded region. @field saveRect The region that is saved underneath the cursor in software cursor mode. @field shieldRect The region that the cursor will not be displayed in if shieldFlag is true. @field cursorLoc The location of the cursor hot spot. @field cursorRect The region that the cursor image currently occupies in software cursor mode. @field oldCursorRect The region that the cursor image occupied the last time the cursor was drawn in software cursor mode. @field screenBounds The region that the current screen occupies. @field version Contains kIOFBCurrentShmemVersion so that a user client can ensure it is using the same version of this structure as the kernel. @field structSize Contains the size of this structure. @field vblTime The time of the most recent vertical blanking. @field vblDelta The interval between the two most recent vertical blankings. @field vblCount A running count of vertical blank interrupts. @field reservedC Reserved for future use. @field hardwareCursorCapable True if the hardware is capable of using hardware cursor mode. @field hardwareCursorActive True if currently using the hardware cursor mode. @field reservedB Reserved for future use. @field cursorSize This array contains the cursor sizes indexed by frame. @field hotSpot This array contains the location of the cursor hot spots indexed by frame. The hot spots coordinates are given relative to the top left corner of the cursor image. @field cursor A union of structures that define the cursor images. The structure used depends on the framebuffer's bit depth. These structures are defined above. */ struct StdFBShmem_t { OSSpinLock cursorSema; int frame; char cursorShow; char cursorObscured; char shieldFlag; char shielded; IOGBounds saveRect; IOGBounds shieldRect; IOGPoint cursorLoc; IOGBounds cursorRect; IOGBounds oldCursorRect; IOGBounds screenBounds; int version; int structSize; AbsoluteTime vblTime; AbsoluteTime vblDelta; unsigned long long int vblCount; #if IOFB_ARBITRARY_FRAMES_CURSOR unsigned long long int vblDrift; unsigned long long int vblDeltaMeasured; AbsoluteTime vblDeltaReal; unsigned int reservedC[22]; #else unsigned int reservedC[27]; unsigned char hardwareCursorFlags[kIOFBNumCursorFrames]; #endif unsigned char hardwareCursorCapable; unsigned char hardwareCursorActive; unsigned char hardwareCursorShields; unsigned char reservedB[1]; #if IOFB_ARBITRARY_FRAMES_CURSOR IOGSize cursorSize[kIOFBNumCursorIndex]; IOGPoint hotSpot[kIOFBNumCursorIndex]; #else IOGSize cursorSize[kIOFBNumCursorFrames]; IOGPoint hotSpot[kIOFBNumCursorFrames]; #endif #ifndef IOFB_ARBITRARY_SIZE_CURSOR union { struct bm12Cursor bw; struct bm18Cursor bw8; struct bm34Cursor rgb; struct bm38Cursor rgb24; } cursor; #else /* IOFB_ARBITRARY_SIZE_CURSOR */ unsigned char cursor[0]; #endif /* IOFB_ARBITRARY_SIZE_CURSOR */ }; #ifndef __cplusplus typedef volatile struct StdFBShmem_t StdFBShmem_t; #endif /*! @enum FramebufferConstants @constant kIOFBCurrentShmemVersion The current version of the slice of shared memory that contains the cursor and window server state data in the StdFBShmem_t structure. @constant kIOFBCursorMemory The memory type for IOConnectMapMemory() to get a slice of shared memory that contains the StdFBShmem_t structure. */ enum { // version for IOFBCreateSharedCursor kIOFBShmemVersionMask = 0x000000ff, kIOFBTenPtOneShmemVersion = 2, kIOFBTenPtTwoShmemVersion = 3, kIOFBCurrentShmemVersion = 2, // number of frames in animating cursor (if > kIOFBTenPtTwoShmemVersion) kIOFBShmemCursorNumFramesMask = 0x00ff0000, kIOFBShmemCursorNumFramesShift = 16, // memory types for IOConnectMapMemory. kIOFBCursorMemory = 100 }; /*! @defined IOFRAMEBUFFER_CONFORMSTO @discussion The class name of the framebuffer service. */ #define IOFRAMEBUFFER_CONFORMSTO "IOFramebuffer" #ifdef __cplusplus } #endif #endif /* ! _IOKIT_IOFRAMEBUFFERSHARED_H */
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/graphics/IOGraphicsInterface.h
/* * Copyright (c) 1999-2000 Apple Computer, Inc. All rights reserved. * * @APPLE_LICENSE_HEADER_START@ * * The contents of this file constitute Original Code as defined in and * are subject to the Apple Public Source License Version 1.1 (the * "License"). You may not use this file except in compliance with the * License. Please obtain a copy of the License at * http://www.apple.com/publicsource and read it before using this file. * * This Original Code and all software distributed under the License are * distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT. Please see the * License for the specific language governing rights and limitations * under the License. * * @APPLE_LICENSE_HEADER_END@ */ #ifndef _IOKIT_IOGRAPHICSINTERFACE_H #define _IOKIT_IOGRAPHICSINTERFACE_H #ifdef KERNEL #define NO_CFPLUGIN 1 #endif #ifndef NO_CFPLUGIN #include <IOKit/IOCFPlugIn.h> #endif /* ! NO_CFPLUGIN */ #define IOGA_COMPAT 1 #include <IOKit/graphics/IOGraphicsInterfaceTypes.h> // <rdar://problem/23764215> IOGraphics: IOGraphicsInterface.h: "C" linkage not enforced. #ifdef __cplusplus extern "C" { #endif #define kIOGraphicsAcceleratorTypeID \ (CFUUIDGetConstantUUIDWithBytes(NULL, \ 0xAC, 0xCF, 0x00, 0x00, \ 0x00, 0x00, \ 0x00, 0x00, \ 0x00, 0x00, \ 0x00, 0x0a, 0x27, 0x89, 0x90, 0x4e)) // IOGraphicsAcceleratorType objects must implement the // IOGraphicsAcceleratorInterface #define kIOGraphicsAcceleratorInterfaceID \ (CFUUIDGetConstantUUIDWithBytes(NULL, \ 0x67, 0x66, 0xE9, 0x4A, \ 0x00, 0x00, \ 0x00, 0x00, \ 0x00, 0x00, \ 0x00, 0x0a, 0x27, 0x89, 0x90, 0x4e)) /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ typedef IOReturn (*IOBlitAccumulatePtr)(void *thisPointer, SInt32 a, SInt32 b, SInt32 c, SInt32 d, SInt32 e, SInt32 f ); #ifdef IOGA_COMPAT typedef IOReturn (*IOBlitProcPtr)(void *thisPointer, IOOptionBits options, IOBlitType type, IOBlitSourceDestType sourceDestType, IOBlitOperation * operation, void * source, void * destination, IOBlitCompletionToken * completionToken ); #endif typedef IOReturn (*IOBlitterPtr)(void *thisPointer, IOOptionBits options, IOBlitType type, IOBlitSourceType sourceType, IOBlitOperation * operation, void * source ); /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #ifndef NO_CFPLUGIN typedef struct IOGraphicsAcceleratorInterfaceStruct { IUNKNOWN_C_GUTS; IOCFPLUGINBASE; IOReturn (*Reset) (void *thisPointer, IOOptionBits options); IOReturn (*CopyCapabilities) (void *thisPointer, FourCharCode select, CFTypeRef * capabilities); #ifdef IOGA_COMPAT IOReturn (*GetBlitProc) (void *thisPointer, IOOptionBits options, IOBlitType type, IOBlitSourceDestType sourceDestType, IOBlitProcPtr * blitProc ); #else void * __gaInterfaceReserved0; #endif IOReturn (*Flush) (void *thisPointer, IOOptionBits options); #ifdef IOGA_COMPAT IOReturn (*WaitForCompletion) (void *thisPointer, IOOptionBits options, IOBlitCompletionToken completionToken); #else void * __gaInterfaceReserved1; #endif IOReturn (*Synchronize) (void *thisPointer, UInt32 options, UInt32 x, UInt32 y, UInt32 w, UInt32 h ); IOReturn (*GetBeamPosition) (void *thisPointer, IOOptionBits options, SInt32 * position); IOReturn (*AllocateSurface) (void *thisPointer, IOOptionBits options, IOBlitSurface * surface, void * cgsSurfaceID ); IOReturn (*FreeSurface) (void *thisPointer, IOOptionBits options, IOBlitSurface * surface); IOReturn (*LockSurface) (void *thisPointer, IOOptionBits options, IOBlitSurface * surface, vm_address_t * address ); IOReturn (*UnlockSurface) (void *thisPointer, IOOptionBits options, IOBlitSurface * surface, IOOptionBits * swapFlags); IOReturn (*SwapSurface) (void *thisPointer, IOOptionBits options, IOBlitSurface * surface, IOOptionBits * swapFlags); IOReturn (*SetDestination) (void *thisPointer, IOOptionBits options, IOBlitSurface * surface ); IOReturn (*GetBlitter) (void *thisPointer, IOOptionBits options, IOBlitType type, IOBlitSourceType sourceType, IOBlitterPtr * blitter ); IOReturn (*WaitComplete) (void *thisPointer, IOOptionBits options); void * __gaInterfaceReserved[ 24 ]; } IOGraphicsAcceleratorInterface; #endif /* ! NO_CFPLUGIN */ /* Helper function for plugin use */ IOReturn IOAccelFindAccelerator( io_service_t framebuffer, io_service_t * pAccelerator, UInt32 * pFramebufferIndex ); #ifdef __cplusplus } #endif /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #endif /* !_IOKIT_IOGRAPHICSINTERFACE_H */
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/graphics/IOAccelSurfaceConnect.h
/* * Copyright (c) 2000 Apple Computer, Inc. All rights reserved. * * @APPLE_LICENSE_HEADER_START@ * * The contents of this file constitute Original Code as defined in and * are subject to the Apple Public Source License Version 1.1 (the * "License"). You may not use this file except in compliance with the * License. Please obtain a copy of the License at * http://www.apple.com/publicsource and read it before using this file. * * This Original Code and all software distributed under the License are * distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT. Please see the * License for the specific language governing rights and limitations * under the License. * * @APPLE_LICENSE_HEADER_END@ */ #ifndef _IOACCEL_SURFACE_CONNECT_H #define _IOACCEL_SURFACE_CONNECT_H #include <IOKit/graphics/IOAccelTypes.h> #include <IOKit/graphics/IOAccelClientConnect.h> /* ** Surface visible region in device coordinates. ** ** num_rects: The number of rectangles in the rect array. If num_rects ** is zero the bounds rectangle is used for the visible rectangle. ** If num_rects is zero the surface must be completely contained ** by the device. ** ** bounds: The unclipped surface rectangle in device coords. Extends ** beyond the device bounds if the surface is not totally on ** the device. ** ** rect[]: An array of visible rectangles in device coords. If num_rects ** is non-zero only the region described by these rectangles is ** copied to the frame buffer during a flush operation. */ typedef struct { UInt32 num_rects; IOAccelBounds bounds; IOAccelBounds rect[0]; } IOAccelDeviceRegion; /* ** Determine the size of a region. */ #define IOACCEL_SIZEOF_DEVICE_REGION(_rgn_) (sizeof(IOAccelDeviceRegion) + (_rgn_)->num_rects * sizeof(IOAccelBounds)) /* ** Surface client public memory types. Private memory types start with ** kIOAccelNumSurfaceMemoryTypes. */ enum eIOAccelSurfaceMemoryTypes { kIOAccelNumSurfaceMemoryTypes }; /* ** Surface client public methods. Private methods start with ** kIOAccelNumSurfaceMethods. */ enum eIOAccelSurfaceMethods { kIOAccelSurfaceReadLockOptions, kIOAccelSurfaceReadUnlockOptions, kIOAccelSurfaceGetState, kIOAccelSurfaceWriteLockOptions, kIOAccelSurfaceWriteUnlockOptions, kIOAccelSurfaceRead, kIOAccelSurfaceSetShapeBacking, kIOAccelSurfaceSetIDMode, kIOAccelSurfaceSetScale, kIOAccelSurfaceSetShape, kIOAccelSurfaceFlush, kIOAccelSurfaceQueryLock, kIOAccelSurfaceReadLock, kIOAccelSurfaceReadUnlock, kIOAccelSurfaceWriteLock, kIOAccelSurfaceWriteUnlock, kIOAccelSurfaceControl, kIOAccelSurfaceSetShapeBackingAndLength, kIOAccelNumSurfaceMethods }; /* ** Option bits for IOAccelCreateSurface and the kIOAccelSurfaceSetIDMode method. ** The color depth field can take any value of the _CGSDepth enumeration. */ typedef enum { kIOAccelSurfaceModeColorDepth1555 = 0x00000003, kIOAccelSurfaceModeColorDepth8888 = 0x00000004, // kIOAccelSurfaceModeColorDepthRGB565 = 0x00000005, kIOAccelSurfaceModeColorDepthYUV = 0x00000006, kIOAccelSurfaceModeColorDepthYUV9 = 0x00000007, kIOAccelSurfaceModeColorDepthYUV12 = 0x00000008, kIOAccelSurfaceModeColorDepthYUV2 = 0x00000009, kIOAccelSurfaceModeColorDepthBGRA32 = 0x0000000A, // kIOAccelSurfaceModeColorDepthRGBA64 = 0x0000000B, // kIOAccelSurfaceModeColorDepthRGBAFloat64 = 0x0000000C, // kIOAccelSurfaceModeColorDepthRGBAFloat128 = 0x0000000D, // kIOAccelSurfaceModeColorDepthYUV420 = 0x0000000E, kIOAccelSurfaceModeColorDepth2101010 = 0x0000000F, kIOAccelSurfaceModeColorDepthBits = 0x0000000F, kIOAccelSurfaceModeStereoBit = 0x00000010, kIOAccelSurfaceModeWindowedBit = 0x00000020, #ifndef _OPEN_SOURCE_ kIOAccelSurfaceModeSurface2 = 0x00004000, #endif /* _OPEN_SOURCE_ */ kIOAccelSurfaceModeBeamSync = 0x00008000 } eIOAccelSurfaceModeBits; /* ** Options bits for IOAccelSetSurfaceShape and the kIOAccelSurfaceSetShape method. */ typedef enum { kIOAccelSurfaceShapeNone = 0x00000000, kIOAccelSurfaceShapeNonBlockingBit = 0x00000001, kIOAccelSurfaceShapeNonSimpleBit = 0x00000002, kIOAccelSurfaceShapeIdentityScaleBit = 0x00000004, kIOAccelSurfaceShapeFrameSyncBit = 0x00000008, kIOAccelSurfaceShapeBeamSyncBit = 0x00000010, kIOAccelSurfaceShapeStaleBackingBit = 0x00000020, kIOAccelSurfaceShapeAssemblyBit = 0x00000040, kIOAccelSurfaceShapeWaitEnabledBit = 0x00000080, /* wrong name, use kIOAccelSurfaceShapeNonBlockingBit */ kIOAccelSurfaceShapeBlockingBit = kIOAccelSurfaceShapeNonBlockingBit } eIOAccelSurfaceShapeBits; /* ** Return bits for the kIOAccelSurfaceGetState method. */ typedef enum { kIOAccelSurfaceStateNone = 0x00000000, kIOAccelSurfaceStateIdleBit = 0x00000001 } eIOAccelSurfaceStateBits; /* ** Option bits for the kIOAccelSurfaceSetScale method. */ typedef enum { kIOAccelSurfaceBeamSyncSwaps = 0x00000001, kIOAccelSurfaceFixedSource = 0x00000002, kIOAccelSurfaceFiltering = 0x000000f0, kIOAccelSurfaceFilterDefault = 0x00000000, kIOAccelSurfaceFilterNone = 0x00000010, kIOAccelSurfaceFilterLinear = 0x00000020 } eIOAccelSurfaceScaleBits; /* ** Option bits for the kIOAccelSurfaceLock methods. */ typedef enum { kIOAccelSurfaceLockInBacking = 0, kIOAccelSurfaceLockInAccel = 1, kIOAccelSurfaceLockInDontCare = 2, kIOAccelSurfaceLockInMask = 0x00000003 } eIOAccelSurfaceLockBits; #endif /* _IOACCEL_SURFACE_CONNECT_H */
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/graphics/IOGraphicsEngine.h
/* * Copyright (c) 1998-2000 Apple Computer, Inc. All rights reserved. * * @APPLE_LICENSE_HEADER_START@ * * The contents of this file constitute Original Code as defined in and * are subject to the Apple Public Source License Version 1.1 (the * "License"). You may not use this file except in compliance with the * License. Please obtain a copy of the License at * http://www.apple.com/publicsource and read it before using this file. * * This Original Code and all software distributed under the License are * distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT. Please see the * License for the specific language governing rights and limitations * under the License. * * @APPLE_LICENSE_HEADER_END@ */ /* * Copyright (c) 1998 Apple Computer, Inc. All rights reserved. * * HISTORY * * 10 Mar 99 sdouglas created. */ struct IOGraphicsEngineContext { OSSpinLock contextLock; IOOptionBits state; void * owner; UInt32 version; IOByteCount structSize; UInt32 reserved[ 8 ]; }; #ifndef __cplusplus typedef volatile struct IOGraphicsEngineContext IOGraphicsEngineContext; #endif enum { // memory type for IOMapMemory kIOGraphicsEngineContext = 100 }; enum { // version kIOGraphicsEngineContextVersion = 1 };
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/graphics/IOAccelTypes.h
/* * Copyright (c) 2000 Apple Computer, Inc. All rights reserved. * * @APPLE_LICENSE_HEADER_START@ * * The contents of this file constitute Original Code as defined in and * are subject to the Apple Public Source License Version 1.1 (the * "License"). You may not use this file except in compliance with the * License. Please obtain a copy of the License at * http://www.apple.com/publicsource and read it before using this file. * * This Original Code and all software distributed under the License are * distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT. Please see the * License for the specific language governing rights and limitations * under the License. * * @APPLE_LICENSE_HEADER_END@ */ #ifndef _IOACCEL_TYPES_H #define _IOACCEL_TYPES_H #include <IOKit/IOTypes.h> #include <IOKit/IOKitKeys.h> #define IOACCEL_TYPES_REV 12 #if !defined(OSTYPES_K64_REV) && !defined(MAC_OS_X_VERSION_10_6) #define IOACCELTYPES_10_5 1 #endif /* Integer rectangle in device coordinates */ typedef struct { SInt16 x; SInt16 y; SInt16 w; SInt16 h; } IOAccelBounds; typedef struct { SInt16 w; SInt16 h; } IOAccelSize; /* Surface information */ enum { kIOAccelVolatileSurface = 0x00000001 }; typedef struct { #if IOACCELTYPES_10_5 vm_address_t address[4]; #else mach_vm_address_t address[4]; #endif /* IOACCELTYPES_10_5 */ UInt32 rowBytes; UInt32 width; UInt32 height; UInt32 pixelFormat; IOOptionBits flags; IOFixed colorTemperature[4]; UInt32 typeDependent[4]; } IOAccelSurfaceInformation; typedef struct { #if IOACCELTYPES_10_5 long x, y, w, h; void *client_addr; unsigned long client_row_bytes; #else SInt32 x, y, w, h; mach_vm_address_t client_addr; UInt32 client_row_bytes; #endif /* IOACCELTYPES_10_5 */ } IOAccelSurfaceReadData; typedef struct { IOAccelBounds buffer; IOAccelSize source; UInt32 reserved[8]; } IOAccelSurfaceScaling; typedef SInt32 IOAccelID; enum { kIOAccelPrivateID = 0x00000001 }; #endif /* _IOACCEL_TYPES_H */
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/graphics/IOGraphicsLib.h
/* * Copyright (c) 1999-2000 Apple Computer, Inc. All rights reserved. * * @APPLE_LICENSE_HEADER_START@ * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this * file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_LICENSE_HEADER_END@ */ #ifndef _IOKIT_IOGRAPHICSLIB_H #define _IOKIT_IOGRAPHICSLIB_H #ifdef __cplusplus extern "C" { #endif #include <IOKit/IOKitLib.h> #include <IOKit/graphics/IOFramebufferShared.h> #include <IOKit/graphics/IOGraphicsInterface.h> /*! @header IOGraphicsLib IOGraphicsLib implements non-kernel task access to IOGraphics family object types - IOFramebuffer and IOAccelerator. These functions implement a graphics family specific API.<br> A connection to a graphics IOService must be made before these functions are called. A connection is made with the IOServiceOpen() function described in IOKitLib.h. An io_connect_t handle is returned by IOServiceOpen(), which must be passed to the IOGraphicsLib functions. The appropriate connection type from IOGraphicsTypes.h must be specified in the call to IOServiceOpen(). All of the IOFramebuffer functions can only be called from a kIOFBServerConnectType connection. Except as specified below, functions whose names begin with IOFB are IOFramebuffer functions. Functions whose names begin with IOPS are IOAccelerator functions and must be called from connections of type kIOFBEngineControllerConnectType or kIOFBEngineConnectType.<br> The functions in IOGraphicsLib use a number of special types. The display mode is the screen's resolution and refresh rate. The known display modes are referred to by an index of type IODisplayModeID. The display depth is the number of significant color bits used in representing each pixel. Depths are also referred to by an index value that is 0 for 8 bits, 1 for 15 bits, and 2 for 24 bits. A combination of display mode and depth may have a number of supported pixel formats. The pixel aperture is an index of supported pixel formats for a display mode and depth. This index is of type IOPixelAperture. All of these graphics specific types are defined in IOGraphicsTypes.h. */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ extern kern_return_t IOFramebufferOpen( io_service_t service, task_port_t owningTask, unsigned int type, io_connect_t * connect ); /*! @enum IODisplayDictionaryOptions @constant kIODisplayMatchingInfo Include only the keys necessary to match two displays with IODisplayMatchDictionaries(). @constant kIODisplayOnlyPreferredName The kDisplayProductName property includes only the localized names returned by CFBundleCopyPreferredLocalizationsFromArray(). @constant kIODisplayNoProductName The kDisplayProductName property is not included in the returned dictionary. */ enum { kIODisplayMatchingInfo = 0x00000100, kIODisplayOnlyPreferredName = 0x00000200, kIODisplayNoProductName = 0x00000400 }; /*! @function IODisplayCreateInfoDictionary @abstract Create a CFDictionary with information about display hardware. @discussion The CFDictionary created by this function contains information about the display hardware associated with a framebuffer. The keys for the dictionary are listed in IOGraphicsTypes.h. @param framebuffer The IOService handle for an IOFramebuffer service. @param options Use IODisplayDictionaryOptions to specify which keys to include. @result The returned CFDictionary that should be released by the caller with CFRelease(). */ CFDictionaryRef IODisplayCreateInfoDictionary( io_service_t framebuffer, IOOptionBits options ); /*! @defined IOCreateDisplayInfoDictionary @discussion IOCreateDisplayInfoDictionary() was renamed IODisplayCreateInfoDictionary(). IOCreateDisplayInfoDictionary() is now a macro for IODisplayCreateInfoDictionary() for compatibility with older code. */ #define IOCreateDisplayInfoDictionary(f,o) \ IODisplayCreateInfoDictionary(f,o) /*! @function IODisplayMatchDictionaries @abstract Match two display information dictionaries to see if they are for the same display. @discussion By comparing two CFDictionaries returned from IODisplayCreateInfoDictionary(), this function determines if the displays are the same. The information compared is what is returned by calling IODisplayCreateInfoDictionary() with an option of kIODisplayMatchingInfo. This includes information such as the vendor, product, and serial number. @param matching1 A CFDictionary returned from IODisplayCreateInfoDictionary(). @param matching2 Another CFDictionary returned from IODisplayCreateInfoDictionary(). @param options No options are currently defined. @result Returns FALSE if the two displays are not equivalent or TRUE if they are. */ SInt32 IODisplayMatchDictionaries( CFDictionaryRef matching1, CFDictionaryRef matching2, IOOptionBits options ); /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ io_service_t IODisplayForFramebuffer( io_service_t framebuffer, IOOptionBits options ); IOReturn IODisplaySetParameters( io_service_t service, IOOptionBits options, CFDictionaryRef params ); IOReturn IODisplaySetFloatParameter( io_service_t service, IOOptionBits options, CFStringRef parameterName, float value ); IOReturn IODisplaySetIntegerParameter( io_service_t service, IOOptionBits options, CFStringRef parameterName, SInt32 value ); IOReturn IODisplayCopyParameters( io_service_t service, IOOptionBits options, CFDictionaryRef * params ); IOReturn IODisplayCopyFloatParameters( io_service_t service, IOOptionBits options, CFDictionaryRef * params ); IOReturn IODisplayGetFloatParameter( io_service_t service, IOOptionBits options, CFStringRef parameterName, float * value ); IOReturn IODisplayGetIntegerRangeParameter( io_service_t service, IOOptionBits options, CFStringRef parameterName, SInt32 * value, SInt32 * min, SInt32 * max ); IOReturn IODisplayCommitParameters( io_service_t service, IOOptionBits options ); /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #ifdef __cplusplus } #endif #endif /* ! _IOKIT_IOGRAPHICSLIB_H */
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/graphics/IOAccelClientConnect.h
/* * Copyright (c) 2000 Apple Computer, Inc. All rights reserved. * * @APPLE_LICENSE_HEADER_START@ * * The contents of this file constitute Original Code as defined in and * are subject to the Apple Public Source License Version 1.1 (the * "License"). You may not use this file except in compliance with the * License. Please obtain a copy of the License at * http://www.apple.com/publicsource and read it before using this file. * * This Original Code and all software distributed under the License are * distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT. Please see the * License for the specific language governing rights and limitations * under the License. * * @APPLE_LICENSE_HEADER_END@ */ #ifndef _IOACCEL_CLIENT_CONNECT_H #define _IOACCEL_CLIENT_CONNECT_H /* ** The IOAccelerator service name */ #define kIOAcceleratorClassName "IOAccelerator" /* ** IOAccelerator public client types. Private client types start with ** kIOAccelNumClientTypes. */ enum eIOAcceleratorClientTypes { kIOAccelSurfaceClientType, kIOAccelNumClientTypes, #ifndef _OPEN_SOURCE_ kIOAccelSurface2ClientType = 0x20 #endif /* _OPEN_SOURCE_ */ }; #endif /* _IOACCEL_CLIENT_CONNECT_H */
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/graphics/IOGraphicsTypes.h
/* * Copyright (c) 1998-2000 Apple Computer, Inc. All rights reserved. * * @APPLE_LICENSE_HEADER_START@ * * The contents of this file constitute Original Code as defined in and * are subject to the Apple Public Source License Version 1.1 (the * "License"). You may not use this file except in compliance with the * License. Please obtain a copy of the License at * http://www.apple.com/publicsource and read it before using this file. * * This Original Code and all software distributed under the License are * distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT. Please see the * License for the specific language governing rights and limitations * under the License. * * @APPLE_LICENSE_HEADER_END@ */ #ifndef _IOKIT_IOGRAPHICSTYPES_H #define _IOKIT_IOGRAPHICSTYPES_H #include <IOKit/IOTypes.h> #include <IOKit/IOKitKeys.h> #ifdef __cplusplus extern "C" { #endif #define IOGRAPHICSTYPES_REV 76 typedef SInt32 IOIndex; typedef UInt32 IOSelect; typedef UInt32 IOFixed1616; typedef UInt32 IODisplayVendorID; typedef UInt32 IODisplayProductID; typedef SInt32 IODisplayModeID; enum { // This is the ID given to a programmable timing used at boot time kIODisplayModeIDBootProgrammable = (IODisplayModeID)0xFFFFFFFB, // Lowest (unsigned) DisplayModeID reserved by Apple kIODisplayModeIDReservedBase = (IODisplayModeID)0x80000000 }; enum { kIOMaxPixelBits = 64 }; typedef char IOPixelEncoding[ kIOMaxPixelBits ]; // Common Apple pixel formats #define IO1BitIndexedPixels "P" #define IO2BitIndexedPixels "PP" #define IO4BitIndexedPixels "PPPP" #define IO8BitIndexedPixels "PPPPPPPP" #define IO16BitDirectPixels "-RRRRRGGGGGBBBBB" #define IO32BitDirectPixels "--------RRRRRRRRGGGGGGGGBBBBBBBB" #define kIO30BitDirectPixels "--RRRRRRRRRRGGGGGGGGGGBBBBBBBBBB" #define kIO64BitDirectPixels "-16R16G16B16" #define kIO16BitFloatPixels "-16FR16FG16FB16" #define kIO32BitFloatPixels "-32FR32FG32FB32" // other possible pixel formats #define IOYUV422Pixels "Y4U2V2" #define IO8BitOverlayPixels "O8" // page flipping #define IOPagedPixels "Page1" #define IO_SampleTypeAlpha 'A' #define IO_SampleTypeSkip '-' // Info about a pixel format enum { kIOCLUTPixels = 0, kIOFixedCLUTPixels = 1, kIORGBDirectPixels = 2, kIOMonoDirectPixels = 3, kIOMonoInverseDirectPixels = 4, kIORGBSignedDirectPixels = 5, kIORGBSignedFloatingPointPixels = 6 }; /*! * @struct IOPixelInformation * @abstract A structure defining the format of a framebuffer. * @discussion This structure is used by IOFramebuffer to define the format of the pixels. * @field bytesPerRow The number of bytes per row. * @field bytesPerPlane Not used. * @field bitsPerPixel The number of bits per pixel, including unused bits and alpha. * @field pixelType One of kIOCLUTPixels (indexed pixels with changeable CLUT), kIORGBDirectPixels (direct pixels). * @field componentCount One for indexed pixels, three for direct pixel formats. * @field bitsPerComponent Number of bits per component in each pixel. * @field componentMasks Mask of the bits valid for each component of the pixel - in R, G, B order for direct pixels. * @field pixelFormat String description of the pixel format - IO32BitDirectPixels, IO16BitDirectPixels etc. * @field flags None defined - set to zero. * @field activeWidth Number of pixels visible per row. * @field activeHeight Number of visible pixel rows. * @field reserved Set to zero. */ struct IOPixelInformation { UInt32 bytesPerRow; UInt32 bytesPerPlane; UInt32 bitsPerPixel; UInt32 pixelType; UInt32 componentCount; UInt32 bitsPerComponent; UInt32 componentMasks[ 8 * 2 ]; IOPixelEncoding pixelFormat; UInt32 flags; UInt32 activeWidth; UInt32 activeHeight; UInt32 reserved[ 2 ]; }; typedef struct IOPixelInformation IOPixelInformation; // ID for industry standard display timings typedef UInt32 IOAppleTimingID; /*! * @struct IODisplayModeInformation * @abstract A structure defining the format of a framebuffer. * @discussion This structure is used by IOFramebuffer to define the format of the pixels. * @field nominalWidth Number of pixels visible per row. * @field nominalHeight Number of visible pixel rows. * @field refreshRate Refresh rate in fixed point 16.16. * @field maxDepthIndex Highest depth index available in this display mode. * @field flags Flags for the mode, including: <br> * kDisplayModeInterlacedFlag mode is interlaced. <br> * kDisplayModeSimulscanFlag mode is available on multiple display connections. <br> * kDisplayModeNotPresetFlag mode is not a factory preset for the display (geometry may need correction). <br> * kDisplayModeStretchedFlag mode is stretched/distorted to match the display aspect ratio. <br> * @field imageWidth Physical width of active image if known, in millimeters, otherwise zero. <br> * @field imageHeight Physical height of active image if known, in millimeters, otherwise zero. <br> * @field reserved Set to zero. */ struct IODisplayModeInformation { UInt32 nominalWidth; UInt32 nominalHeight; IOFixed1616 refreshRate; IOIndex maxDepthIndex; UInt32 flags; UInt16 imageWidth; UInt16 imageHeight; UInt32 reserved[ 3 ]; }; typedef struct IODisplayModeInformation IODisplayModeInformation; // flags enum { kDisplayModeSafetyFlags = 0x00000007, kDisplayModeAlwaysShowFlag = 0x00000008, kDisplayModeNeverShowFlag = 0x00000080, kDisplayModeNotResizeFlag = 0x00000010, kDisplayModeRequiresPanFlag = 0x00000020, kDisplayModeInterlacedFlag = 0x00000040, kDisplayModeSimulscanFlag = 0x00000100, kDisplayModeBuiltInFlag = 0x00000400, kDisplayModeNotPresetFlag = 0x00000200, kDisplayModeStretchedFlag = 0x00000800, kDisplayModeNotGraphicsQualityFlag = 0x00001000, kDisplayModeValidateAgainstDisplay = 0x00002000, kDisplayModeTelevisionFlag = 0x00100000, kDisplayModeValidForMirroringFlag = 0x00200000, kDisplayModeAcceleratorBackedFlag = 0x00400000, kDisplayModeValidForHiResFlag = 0x00800000, kDisplayModeValidForAirPlayFlag = 0x01000000, kDisplayModeNativeFlag = 0x02000000 }; enum { kDisplayModeValidFlag = 0x00000001, kDisplayModeSafeFlag = 0x00000002, kDisplayModeDefaultFlag = 0x00000004 }; #ifndef KERNEL // Framebuffer info - obsolete struct IOFramebufferInformation { IOPhysicalAddress baseAddress; UInt32 activeWidth; UInt32 activeHeight; IOByteCount bytesPerRow; IOByteCount bytesPerPlane; UInt32 bitsPerPixel; UInt32 pixelType; UInt32 flags; UInt32 reserved[ 4 ]; }; typedef struct IOFramebufferInformation IOFramebufferInformation; #endif // flags enum { kFramebufferSupportsCopybackCache = 0x00010000, kFramebufferSupportsWritethruCache = 0x00020000, kFramebufferSupportsGammaCorrection = 0x00040000, kFramebufferDisableAltivecAccess = 0x00080000 }; // Aperture is an index into supported pixel formats for a mode & depth typedef IOIndex IOPixelAperture; enum { kIOFBSystemAperture = 0 }; //// CLUTs // IOFBSetGamma Sync Types #define kIOFBSetGammaSyncNotSpecified -1 #define kIOFBSetGammaSyncNoSync 0 #define kIOFBSetGammaSyncVerticalBlankSync 1 typedef UInt16 IOColorComponent; /*! * @struct IOColorEntry * @abstract A structure defining one entry of a color lookup table. * @discussion This structure is used by IOFramebuffer to define an entry of a color lookup table. * @field index Number of pixels visible per row. * @field red Value of red component 0-65535. * @field green Value of green component 0-65535. * @field blue Value of blue component 0-65535. */ struct IOColorEntry { UInt16 index; IOColorComponent red; IOColorComponent green; IOColorComponent blue; }; typedef struct IOColorEntry IOColorEntry; // options (masks) enum { kSetCLUTByValue = 0x00000001, // else at index kSetCLUTImmediately = 0x00000002, // else at VBL kSetCLUTWithLuminance = 0x00000004 // else RGB }; //// Controller attributes enum { kIOPowerStateAttribute = 'pwrs', kIOPowerAttribute = 'powr', kIODriverPowerAttribute = 'dpow', kIOHardwareCursorAttribute = 'crsr', kIOMirrorAttribute = 'mirr', kIOMirrorDefaultAttribute = 'mrdf', kIOCapturedAttribute = 'capd', kIOCursorControlAttribute = 'crsc', kIOSystemPowerAttribute = 'spwr', kIOWindowServerActiveAttribute = 'wsrv', kIOVRAMSaveAttribute = 'vrsv', kIODeferCLUTSetAttribute = 'vclt', kIOClamshellStateAttribute = 'clam', kIOFBDisplayPortTrainingAttribute = 'dpta', kIOFBDisplayState = 'dstt', kIOFBVariableRefreshRate = 'vrr?', kIOFBLimitHDCPAttribute = 'hdcp', kIOFBLimitHDCPStateAttribute = 'sHDC', kIOFBStop = 'stop', kIOFBRedGammaScaleAttribute = 'gslr', // as of IOGRAPHICSTYPES_REV 54 kIOFBGreenGammaScaleAttribute = 'gslg', // as of IOGRAPHICSTYPES_REV 54 kIOFBBlueGammaScaleAttribute = 'gslb', // as of IOGRAPHICSTYPES_REV 54 kIOFBHDRMetaDataAttribute = 'hdrm', // as of IOGRAPHICSTYPES_REV 64 kIOBuiltinPanelPowerAttribute = 'pnlp', // as of IOGRAPHICSTYPES_REV 71 }; enum { kIOFBHDCPLimit_AllowAll = 0, kIOFBHDCPLimit_NoHDCP1x = 1 << 0, kIOFBHDCPLimit_NoHDCP20Type0 = 1 << 1, kIOFBHDCPLimit_NoHDCP20Type1 = 1 << 2, // Default case }; // <rdar://problem/34574357> kIOFBHDRMetaDataAttribute struct IOFBHDRMetaDataV1 { uint16_t displayPrimary_X0; // X coordinate of red primary uint16_t displayPrimary_Y0; // Y coordinate of red primary uint16_t displayPrimary_X1; // X coordinate of green primary uint16_t displayPrimary_Y1; // Y coordinate of green primary uint16_t displayPrimary_X2; // X coordinate of blue primary uint16_t displayPrimary_Y2; // Y coordinate of blue primary uint16_t displayPrimary_X; // X coordinate of white primary uint16_t displayPrimary_Y; // Y coordinate of white primary uint16_t desiredLuminance_Max; // Desired max display luminance uint16_t desiredLuminance_Min; // Desired min display luminance uint16_t desiredLightLevel_Avg; // Desired max frame-average light level uint16_t desiredLightLevel_Max; // Desired max light level uint64_t __reservedA[5]; // Reserved - set to zero }; typedef struct IOFBHDRMetaDataV1 IOFBHDRMetaDataV1; typedef union { IOFBHDRMetaDataV1 v1; } IOFBHDRMetaData; // <rdar://problem/29184178> IOGraphics: Implement display state attribute for deteriming display state post wake // kIOFBDisplayState enum { kIOFBDisplayState_AlreadyActive = (1 << 0), kIOFBDisplayState_RestoredProfile = (1 << 1), kIOFBDisplayState_PipelineBlack = (1 << 2), kIOFBDisplayState_Mask = (kIOFBDisplayState_AlreadyActive | kIOFBDisplayState_RestoredProfile | kIOFBDisplayState_PipelineBlack) }; // values for kIOWindowServerActiveAttribute enum { // States kIOWSAA_Unaccelerated = 0, // CPU rendering/access only, no GPU access kIOWSAA_Accelerated = 1, // GPU rendering/access only, no CPU mappings kIOWSAA_From_Accelerated = 2, // Transitioning from GPU to CPU kIOWSAA_To_Accelerated = 3, // Transitioning from CPU to GPU kIOWSAA_Sleep = 4, kIOWSAA_Hibernate = kIOWSAA_Sleep, kIOWSAA_DriverOpen = 5, // Reserved kIOWSAA_StateMask = 0xF, // Bits kIOWSAA_Transactional = 0x10, // If this bit is present, transition is to/from transactional operation model. // These attributes are internal kIOWSAA_DeferStart = 0x100, kIOWSAA_DeferEnd = 0x200, kIOWSAA_NonConsoleDevice = 0x400, // If present, associated FB is non-console. See ERS for further details. kIOWSAA_Reserved = 0xF0000000 }; // IOFBNS prefix is IOFramebuffer notifyServer enum { kIOFBNS_Rendezvous = 0x87654321, // Note sign-bit is 1 here. kIOFBNS_MessageMask = 0x0000000f, kIOFBNS_Sleep = 0x00, kIOFBNS_Wake = 0x01, kIOFBNS_Doze = 0x02, #ifndef _OPEN_SOURCE_ // <rdar://problem/39199290> IOGraphics: Add 10 second timeout to IODW DIM // policy. // Enum of Bitfields for Windows server notification msgh_id, which is a // integer_t signed type. kIOFBNS_Dim = 0x03, kIOFBNS_UnDim = 0x04, #endif // !_OPEN_SOURCE_ // For Wake messages this field contains the current kIOFBDisplayState as // returned by attribute 'kIOFBDisplayState' kIOFBNS_DisplayStateMask = 0x00000f00, kIOFBNS_DisplayStateShift = 8, // Message Generation Count, top-bit i.e. sign-bit is always 0 for normal // messages, see kIOFBNS_Rendezvous is the only exception and it doesn't // encode a generation count. kIOFBNS_GenerationMask = 0x7fff0000, kIOFBNS_GenerationShift = 16, }; // values for kIOMirrorAttribute enum { kIOMirrorIsPrimary = 0x80000000, kIOMirrorHWClipped = 0x40000000, kIOMirrorIsMirrored = 0x20000000 }; // values for kIOMirrorDefaultAttribute enum { kIOMirrorDefault = 0x00000001, kIOMirrorForced = 0x00000002 }; //// Display mode timing information struct IODetailedTimingInformationV1 { // from EDID defn UInt32 pixelClock; // Hertz UInt32 horizontalActive; // pixels UInt32 horizontalBlanking; // pixels UInt32 horizontalBorder; // pixels UInt32 horizontalSyncOffset; // pixels UInt32 horizontalSyncWidth; // pixels UInt32 verticalActive; // lines UInt32 verticalBlanking; // lines UInt32 verticalBorder; // lines UInt32 verticalSyncOffset; // lines UInt32 verticalSyncWidth; // lines }; typedef struct IODetailedTimingInformationV1 IODetailedTimingInformationV1; /*! * @struct IODetailedTimingInformationV2 * @abstract A structure defining the detailed timing information of a display mode. * @discussion This structure is used by IOFramebuffer to define detailed timing information for a display mode. The VESA EDID document has more information. * @field __reservedA Set to zero. * @field horizontalScaledInset If the mode is scaled, sets the number of active pixels to remove the left and right edges in order to display an underscanned image. * @field verticalScaledInset If the mode is scaled, sets the number of active lines to remove the top and bottom edges in order to display an underscanned image. * @field scalerFlags If the mode is scaled, * kIOScaleStretchToFit may be set to allow stretching. * kIOScaleRotateFlags is mask which may have the value given by kIOScaleRotate90, kIOScaleRotate180, kIOScaleRotate270 to display a rotated framebuffer. * @field horizontalScaled If the mode is scaled, sets the size of the image before scaling or rotation. * @field verticalScaled If the mode is scaled, sets the size of the image before scaling or rotation. * @field signalConfig * kIOAnalogSetupExpected set if display expects a blank-to-black setup or pedestal. See VESA signal standards. <br> * kIOInterlacedCEATiming set for a CEA style interlaced timing:<br> * Field 1 vertical blanking = half specified vertical blanking lines. <br> * Field 2 vertical blanking = (half vertical blanking lines) + 1 line. <br> * Field 1 vertical offset = half specified vertical sync offset. <br> * Field 2 vertical offset = (half specified vertical sync offset) + 0.5 lines. <br> * @field signalLevels One of:<br> * kIOAnalogSignalLevel_0700_0300 0.700 - 0.300 V p-p.<br> * kIOAnalogSignalLevel_0714_0286 0.714 - 0.286 V p-p.<br> * kIOAnalogSignalLevel_1000_0400 1.000 - 0.400 V p-p.<br> * kIOAnalogSignalLevel_0700_0000 0.700 - 0.000 V p-p.<br> * @field pixelClock Pixel clock frequency in Hz. * @field minPixelClock Minimum pixel clock frequency in Hz, with error. * @field maxPixelClock Maximum pixel clock frequency in Hz, with error. * @field horizontalActive Pixel clocks per line. * @field horizontalBlanking Blanking clocks per line. * @field horizontalSyncOffset First clock of horizontal sync. * @field horizontalSyncPulseWidth Width of horizontal sync. * @field verticalActive Number of lines per frame. * @field verticalBlanking Blanking lines per frame. * @field verticalSyncOffset First line of vertical sync. * @field verticalSyncPulseWidth Height of vertical sync. * @field horizontalBorderLeft Number of pixels in left horizontal border. * @field horizontalBorderRight Number of pixels in right horizontal border. * @field verticalBorderTop Number of lines in top vertical border. * @field verticalBorderBottom Number of lines in bottom vertical border. * @field horizontalSyncConfig kIOSyncPositivePolarity for positive polarity horizontal sync (0 for negative). * @field horizontalSyncLevel Zero. * @field verticalSyncConfig kIOSyncPositivePolarity for positive polarity vertical sync (0 for negative). * @field verticalSyncLevel Zero. * @field numLinks number of links to be used by a dual link timing, if zero, assume one link. * @field verticalBlankingExtension maximum number of blanking extension lines that is available. (0 for none). * @field pixelEncoding 2017 Timing Features - ERS 2-58 (6.3.1) * @field bitsPerColorComponent 2017 Timing Features - ERS 2-58 (6.3.1) * @field colorimetry 2017 Timing Features - ERS 2-58 (6.3.1) * @field dynamicRange 2017 Timing Features - ERS 2-58 (6.3.1) * @field dscCompressedBitsPerPixel 2018 Timing Features - ERS 2-63 (6.3.1) * @field dscSliceHeight 2018 Timing Features - ERS 2-63 (6.3.1) * @field dscSliceWidth 2018 Timing Features - ERS 2-63 (6.3.1) * @field verticalBlankingMaxStretchPerFrame Max stretch time used for VRR refresh rate ramps * @field verticalBlankingMaxShrinkPerFrame Max shrink time used for VRR refresh rate ramps * @field __reservedB Reserved set to zero. */ struct IODetailedTimingInformationV2 { UInt32 __reservedA[3]; // Init to 0 UInt32 horizontalScaledInset; // pixels UInt32 verticalScaledInset; // lines UInt32 scalerFlags; UInt32 horizontalScaled; UInt32 verticalScaled; UInt32 signalConfig; UInt32 signalLevels; UInt64 pixelClock; // Hz UInt64 minPixelClock; // Hz - With error what is slowest actual clock UInt64 maxPixelClock; // Hz - With error what is fasted actual clock UInt32 horizontalActive; // pixels UInt32 horizontalBlanking; // pixels UInt32 horizontalSyncOffset; // pixels UInt32 horizontalSyncPulseWidth; // pixels UInt32 verticalActive; // lines UInt32 verticalBlanking; // lines UInt32 verticalSyncOffset; // lines UInt32 verticalSyncPulseWidth; // lines UInt32 horizontalBorderLeft; // pixels UInt32 horizontalBorderRight; // pixels UInt32 verticalBorderTop; // lines UInt32 verticalBorderBottom; // lines UInt32 horizontalSyncConfig; UInt32 horizontalSyncLevel; // Future use (init to 0) UInt32 verticalSyncConfig; UInt32 verticalSyncLevel; // Future use (init to 0) UInt32 numLinks; UInt32 verticalBlankingExtension; // lines (AdaptiveSync: 0 for non-AdaptiveSync support) UInt16 pixelEncoding; UInt16 bitsPerColorComponent; UInt16 colorimetry; UInt16 dynamicRange; UInt16 dscCompressedBitsPerPixel; UInt16 dscSliceHeight; UInt16 dscSliceWidth; UInt16 verticalBlankingMaxStretchPerFrame; UInt16 verticalBlankingMaxShrinkPerFrame; UInt16 __reservedB[3]; // Init to 0 }; typedef struct IODetailedTimingInformationV2 IODetailedTimingInformationV2; typedef struct IODetailedTimingInformationV2 IODetailedTimingInformation; struct IOTimingInformation { IOAppleTimingID appleTimingID; // kIOTimingIDXXX const UInt32 flags; union { IODetailedTimingInformationV1 v1; IODetailedTimingInformationV2 v2; } detailedInfo; }; typedef struct IOTimingInformation IOTimingInformation; enum { // IOTimingInformation flags kIODetailedTimingValid = 0x80000000, kIOScalingInfoValid = 0x40000000 }; enum { // scalerFlags kIOScaleStretchToFit = 0x00000001, kIOScaleRotateFlags = 0x000000f0, kIOScaleSwapAxes = 0x00000010, kIOScaleInvertX = 0x00000020, kIOScaleInvertY = 0x00000040, kIOScaleRotate0 = 0x00000000, kIOScaleRotate90 = kIOScaleSwapAxes | kIOScaleInvertX, kIOScaleRotate180 = kIOScaleInvertX | kIOScaleInvertY, kIOScaleRotate270 = kIOScaleSwapAxes | kIOScaleInvertY }; enum { kIOPixelEncodingNotSupported = 0x0000, kIOPixelEncodingRGB444 = 0x0001, kIOPixelEncodingYCbCr444 = 0x0002, kIOPixelEncodingYCbCr422 = 0x0004, kIOPixelEncodingYCbCr420 = 0x0008 }; enum { kIOBitsPerColorComponentNotSupported = 0x0000, kIOBitsPerColorComponent6 = 0x0001, kIOBitsPerColorComponent8 = 0x0002, kIOBitsPerColorComponent10 = 0x0004, kIOBitsPerColorComponent12 = 0x0008, kIOBitsPerColorComponent16 = 0x0010 }; enum { kIOColorimetryNotSupported = 0x0000, kIOColorimetryNativeRGB = 0x0001, kIOColorimetrysRGB = 0x0002, kIOColorimetryDCIP3 = 0x0004, kIOColorimetryAdobeRGB = 0x0008, kIOColorimetryxvYCC = 0x0010, kIOColorimetryWGRGB = 0x0020, kIOColorimetryBT601 = 0x0040, kIOColorimetryBT709 = 0x0080, kIOColorimetryBT2020 = 0x0100, kIOColorimetryBT2100 = 0x0200 }; enum { // dynamicRange - should be in sync with "supportedDynamicRangeModes" enum below kIODynamicRangeNotSupported = 0x0000, kIODynamicRangeSDR = 0x0001, kIODynamicRangeHDR10 = 0x0002, kIODynamicRangeDolbyNormalMode = 0x0004, kIODynamicRangeDolbyTunnelMode = 0x0008, kIODynamicRangeTraditionalGammaHDR = 0x0010, kIODynamicRangeTraditionalGammaSDR = 0x0020, // as of IOGRAPHICSTYPES_REV 72 }; #pragma pack(push, 4) struct IOFBDisplayModeDescription { IODisplayModeInformation info; IOTimingInformation timingInfo; }; typedef struct IOFBDisplayModeDescription IOFBDisplayModeDescription; #pragma pack(pop) /*! * @struct IODisplayTimingRangeV1 * @abstract A structure defining the limits and attributes of a display or framebuffer. * @discussion This structure is used to define the limits for modes programmed as detailed timings by the OS. The VESA EDID is useful background information for many of these fields. A data property with this structure under the key kIOFBTimingRangeKey in a framebuffer will allow the OS to program detailed timings that fall within its range. * @field __reservedA Set to zero. * @field version Set to zero. * @field __reservedB Set to zero. * @field minPixelClock minimum pixel clock frequency in range, in Hz. * @field minPixelClock maximum pixel clock frequency in range, in Hz. * @field maxPixelError largest variation between specified and actual pixel clock frequency, in Hz. * @field supportedSyncFlags mask of supported sync attributes. The following are defined:<br> * kIORangeSupportsSeparateSyncs - digital separate syncs.<br> * kIORangeSupportsSyncOnGreen - sync on green.<br> * kIORangeSupportsCompositeSync - composite sync.<br> * kIORangeSupportsVSyncSerration - vertical sync has serration and equalization pulses.<br> * kIORangeSupportsVRR - variable refresh rate. <br> * @field supportedSignalLevels mask of possible signal levels. The following are defined:<br> * kIORangeSupportsSignal_0700_0300 0.700 - 0.300 V p-p.<br> * kIORangeSupportsSignal_0714_0286 0.714 - 0.286 V p-p.<br> * kIORangeSupportsSignal_1000_0400 1.000 - 0.400 V p-p.<br> * kIORangeSupportsSignal_0700_0000 0.700 - 0.000 V p-p.<br> * @field supportedSignalConfigs mask of possible signal configurations. The following are defined:<br> * kIORangeSupportsInterlacedCEATiming Supports CEA style interlaced timing:<br> * Field 1 vertical blanking = specified vertical blanking lines. <br> * Field 2 vertical blanking = vertical blanking lines + 1 line. <br> * Field 1 vertical offset = specified vertical sync offset. <br> * Field 2 vertical offset = specified vertical sync offset + 0.5 lines. <br> * kIORangeSupportsInterlacedCEATimingWithConfirm Supports CEA style interlaced timing, but require a confirm. * @field minFrameRate minimum frame rate (vertical refresh frequency) in range, in Hz. * @field maxFrameRate maximum frame rate (vertical refresh frequency) in range, in Hz. * @field minLineRate minimum line rate (horizontal refresh frequency) in range, in Hz. * @field maxLineRate maximum line rate (horizontal refresh frequency) in range, in Hz. * @field maxHorizontalTotal maximum clocks in horizontal line (active + blanking). * @field maxVerticalTotal maximum lines in vertical frame (active + blanking). * @field __reservedD Set to zero. * @field charSizeHorizontalActive horizontalActive must be a multiple of charSizeHorizontalActive. * @field charSizeHorizontalBlanking horizontalBlanking must be a multiple of charSizeHorizontalBlanking. * @field charSizeHorizontalSyncOffset horizontalSyncOffset must be a multiple of charSizeHorizontalSyncOffset. * @field charSizeHorizontalSyncPulse horizontalSyncPulse must be a multiple of charSizeHorizontalSyncPulse. * @field charSizeVerticalActive verticalActive must be a multiple of charSizeVerticalActive. * @field charSizeVerticalBlanking verticalBlanking must be a multiple of charSizeVerticalBlanking. * @field charSizeVerticalSyncOffset verticalSyncOffset must be a multiple of charSizeVerticalSyncOffset. * @field charSizeVerticalSyncPulse verticalSyncPulse must be a multiple of charSizeVerticalSyncPulse. * @field charSizeHorizontalBorderLeft horizontalBorderLeft must be a multiple of charSizeHorizontalBorderLeft. * @field charSizeHorizontalBorderRight horizontalBorderRight must be a multiple of charSizeHorizontalBorderRight. * @field charSizeVerticalBorderTop verticalBorderTop must be a multiple of charSizeVerticalBorderTop. * @field charSizeVerticalBorderBottom verticalBorderBottom must be a multiple of charSizeVerticalBorderBottom. * @field charSizeHorizontalTotal (horizontalActive + horizontalBlanking) must be a multiple of charSizeHorizontalTotal. * @field charSizeVerticalTotal (verticalActive + verticalBlanking) must be a multiple of charSizeVerticalTotal. * @field __reservedE Set to zero. * @field minHorizontalActiveClocks minimum value of horizontalActive. * @field maxHorizontalActiveClocks maximum value of horizontalActive. * @field minHorizontalBlankingClocks minimum value of horizontalBlanking. * @field maxHorizontalBlankingClocks maximum value of horizontalBlanking. * @field minHorizontalSyncOffsetClocks minimum value of horizontalSyncOffset. * @field maxHorizontalSyncOffsetClocks maximum value of horizontalSyncOffset. * @field minHorizontalPulseWidthClocks minimum value of horizontalPulseWidth. * @field maxHorizontalPulseWidthClocks maximum value of horizontalPulseWidth. * @field minVerticalActiveClocks minimum value of verticalActive. * @field maxVerticalActiveClocks maximum value of verticalActive. * @field minVerticalBlankingClocks minimum value of verticalBlanking. * @field maxVerticalBlankingClocks maximum value of verticalBlanking. * @field minVerticalSyncOffsetClocks minimum value of verticalSyncOffset. * @field maxVerticalSyncOffsetClocks maximum value of verticalSyncOffset. * @field minVerticalPulseWidthClocks minimum value of verticalPulseWidth. * @field maxVerticalPulseWidthClocks maximum value of verticalPulseWidth. * @field minHorizontalBorderLeft minimum value of horizontalBorderLeft. * @field maxHorizontalBorderLeft maximum value of horizontalBorderLeft. * @field minHorizontalBorderRight minimum value of horizontalBorderRight. * @field maxHorizontalBorderRight maximum value of horizontalBorderRight. * @field minVerticalBorderTop minimum value of verticalBorderTop. * @field maxVerticalBorderTop maximum value of verticalBorderTop. * @field minVerticalBorderBottom minimum value of verticalBorderBottom. * @field maxVerticalBorderBottom maximum value of verticalBorderBottom. * @field maxNumLinks number of links supported, if zero, 1 link is assumed. * @field minLink0PixelClock minimum pixel clock for link 0 (kHz). * @field maxLink0PixelClock maximum pixel clock for link 0 (kHz). * @field minLink1PixelClock minimum pixel clock for link 1 (kHz). * @field maxLink1PixelClock maximum pixel clock for link 1 (kHz). * @field supportedPixelEncoding 2017 Timing Features - ERS 2-58 (6.3.1) * @field supportedBitsPerColorComponent 2017 Timing Features - ERS 2-58 (6.3.1) * @field supportedColorimetry 2017 Timing Features - ERS 2-58 (6.3.1) * @field supportedDynamicRange 2017 Timing Features - ERS 2-58 (6.3.1) * @field __reservedF Set to zero. */ struct IODisplayTimingRangeV1 { UInt32 __reservedA[2]; // Init to 0 UInt32 version; // Init to 0 UInt32 __reservedB[5]; // Init to 0 UInt64 minPixelClock; // Min dot clock in Hz UInt64 maxPixelClock; // Max dot clock in Hz UInt32 maxPixelError; // Max dot clock error UInt32 supportedSyncFlags; UInt32 supportedSignalLevels; UInt32 supportedSignalConfigs; UInt32 minFrameRate; // Hz UInt32 maxFrameRate; // Hz UInt32 minLineRate; // Hz UInt32 maxLineRate; // Hz UInt32 maxHorizontalTotal; // Clocks - Maximum total (active + blanking) UInt32 maxVerticalTotal; // Clocks - Maximum total (active + blanking) UInt32 __reservedD[2]; // Init to 0 UInt8 charSizeHorizontalActive; UInt8 charSizeHorizontalBlanking; UInt8 charSizeHorizontalSyncOffset; UInt8 charSizeHorizontalSyncPulse; UInt8 charSizeVerticalActive; UInt8 charSizeVerticalBlanking; UInt8 charSizeVerticalSyncOffset; UInt8 charSizeVerticalSyncPulse; UInt8 charSizeHorizontalBorderLeft; UInt8 charSizeHorizontalBorderRight; UInt8 charSizeVerticalBorderTop; UInt8 charSizeVerticalBorderBottom; UInt8 charSizeHorizontalTotal; // Character size for active + blanking UInt8 charSizeVerticalTotal; // Character size for active + blanking UInt16 __reservedE; // Reserved (Init to 0) UInt32 minHorizontalActiveClocks; UInt32 maxHorizontalActiveClocks; UInt32 minHorizontalBlankingClocks; UInt32 maxHorizontalBlankingClocks; UInt32 minHorizontalSyncOffsetClocks; UInt32 maxHorizontalSyncOffsetClocks; UInt32 minHorizontalPulseWidthClocks; UInt32 maxHorizontalPulseWidthClocks; UInt32 minVerticalActiveClocks; UInt32 maxVerticalActiveClocks; UInt32 minVerticalBlankingClocks; UInt32 maxVerticalBlankingClocks; UInt32 minVerticalSyncOffsetClocks; UInt32 maxVerticalSyncOffsetClocks; UInt32 minVerticalPulseWidthClocks; UInt32 maxVerticalPulseWidthClocks; UInt32 minHorizontalBorderLeft; UInt32 maxHorizontalBorderLeft; UInt32 minHorizontalBorderRight; UInt32 maxHorizontalBorderRight; UInt32 minVerticalBorderTop; UInt32 maxVerticalBorderTop; UInt32 minVerticalBorderBottom; UInt32 maxVerticalBorderBottom; UInt32 maxNumLinks; // number of links, if zero, assume link 1 UInt32 minLink0PixelClock; // min pixel clock for link 0 (kHz) UInt32 maxLink0PixelClock; // max pixel clock for link 0 (kHz) UInt32 minLink1PixelClock; // min pixel clock for link 1 (kHz) UInt32 maxLink1PixelClock; // max pixel clock for link 1 (kHz) UInt16 supportedPixelEncoding; UInt16 supportedBitsPerColorComponent; UInt16 supportedColorimetryModes; UInt16 supportedDynamicRangeModes; UInt32 __reservedF[1]; // Init to 0 }; typedef struct IODisplayTimingRangeV1 IODisplayTimingRangeV1; /*! * @struct IODisplayTimingRangeV2 * @abstract A structure defining the limits and attributes of DSC capabilities in a framebuffer. * @discussion This structure is used to define the limits for DSC enabled modes programmed as detailed timings by the OS. The VESA DSC spec is useful background information for many of these fields. * @field maxBandwidth Maximum permitted bandwidth of the given topology in bits per second. * @field dscMinSliceHeight Minimum slice Height, in units of line. * @field dscMaxSliceHeight Maximum slice Height, in units of line. * @field dscMinSliceWidth Minimum slice width, in units of line. * @field dscMaxSliceWidth Maximum slice width, in units of line. * @field dscMinSlicePerLine Minimum slice per Line. * @field dscMaxSlicePerLine Maximum slice per Line. * @field dscMinBPC Minimum Bits per component, in units of bits. * @field dscMaxBPC Maximum Bits per component, in units of bits. * @field dscMinBPP Minimum target bits/pixel, in bpp. * @field dscMaxBPP Maximum target bits/pixel, in bpp. * @field dscVBR VBR mode, 0:disabled 1:enabled. * @field dscBlockPredEnable DSC BP is user or not, 0: not used, 1: used. * @field __reservedF Set to zero. */ struct IODisplayTimingRangeV2 { UInt32 __reservedA[2]; // Init to 0 UInt32 version; // Init to 0 UInt32 __reservedB[5]; // Init to 0 UInt64 minPixelClock; // Min dot clock in Hz UInt64 maxPixelClock; // Max dot clock in Hz UInt32 maxPixelError; // Max dot clock error UInt32 supportedSyncFlags; UInt32 supportedSignalLevels; UInt32 supportedSignalConfigs; UInt32 minFrameRate; // Hz UInt32 maxFrameRate; // Hz UInt32 minLineRate; // Hz UInt32 maxLineRate; // Hz UInt32 maxHorizontalTotal; // Clocks - Maximum total (active + blanking) UInt32 maxVerticalTotal; // Clocks - Maximum total (active + blanking) UInt32 __reservedD[2]; // Init to 0 UInt8 charSizeHorizontalActive; UInt8 charSizeHorizontalBlanking; UInt8 charSizeHorizontalSyncOffset; UInt8 charSizeHorizontalSyncPulse; UInt8 charSizeVerticalActive; UInt8 charSizeVerticalBlanking; UInt8 charSizeVerticalSyncOffset; UInt8 charSizeVerticalSyncPulse; UInt8 charSizeHorizontalBorderLeft; UInt8 charSizeHorizontalBorderRight; UInt8 charSizeVerticalBorderTop; UInt8 charSizeVerticalBorderBottom; UInt8 charSizeHorizontalTotal; // Character size for active + blanking UInt8 charSizeVerticalTotal; // Character size for active + blanking UInt16 __reservedE; // Reserved (Init to 0) UInt32 minHorizontalActiveClocks; UInt32 maxHorizontalActiveClocks; UInt32 minHorizontalBlankingClocks; UInt32 maxHorizontalBlankingClocks; UInt32 minHorizontalSyncOffsetClocks; UInt32 maxHorizontalSyncOffsetClocks; UInt32 minHorizontalPulseWidthClocks; UInt32 maxHorizontalPulseWidthClocks; UInt32 minVerticalActiveClocks; UInt32 maxVerticalActiveClocks; UInt32 minVerticalBlankingClocks; UInt32 maxVerticalBlankingClocks; UInt32 minVerticalSyncOffsetClocks; UInt32 maxVerticalSyncOffsetClocks; UInt32 minVerticalPulseWidthClocks; UInt32 maxVerticalPulseWidthClocks; UInt32 minHorizontalBorderLeft; UInt32 maxHorizontalBorderLeft; UInt32 minHorizontalBorderRight; UInt32 maxHorizontalBorderRight; UInt32 minVerticalBorderTop; UInt32 maxVerticalBorderTop; UInt32 minVerticalBorderBottom; UInt32 maxVerticalBorderBottom; UInt32 maxNumLinks; // number of links, if zero, assume link 1 UInt32 minLink0PixelClock; // min pixel clock for link 0 (kHz) UInt32 maxLink0PixelClock; // max pixel clock for link 0 (kHz) UInt32 minLink1PixelClock; // min pixel clock for link 1 (kHz) UInt32 maxLink1PixelClock; // max pixel clock for link 1 (kHz) UInt16 supportedPixelEncoding; UInt16 supportedBitsPerColorComponent; UInt16 supportedColorimetryModes; UInt16 supportedDynamicRangeModes; UInt32 __reservedF[1]; // Init to 0 UInt64 maxBandwidth; UInt32 dscMinSliceHeight; UInt32 dscMaxSliceHeight; UInt32 dscMinSliceWidth; UInt32 dscMaxSliceWidth; UInt32 dscMinSlicePerLine; UInt32 dscMaxSlicePerLine; UInt16 dscMinBPC; UInt16 dscMaxBPC; UInt16 dscMinBPP; UInt16 dscMaxBPP; UInt8 dscVBR; UInt8 dscBlockPredEnable; UInt32 __reservedC[6]; }; typedef struct IODisplayTimingRangeV2 IODisplayTimingRangeV2; typedef struct IODisplayTimingRangeV2 IODisplayTimingRange; enum { // IOTimingRange version kIOTimingRangeV2 = 0x00000002, kIOTimingRangeV1 = 0x00000000 }; enum { // supportedPixelEncoding kIORangePixelEncodingNotSupported = 0x0000, kIORangePixelEncodingRGB444 = 0x0001, kIORangePixelEncodingYCbCr444 = 0x0002, kIORangePixelEncodingYCbCr422 = 0x0004, kIORangePixelEncodingYCbCr420 = 0x0008, }; enum { // supportedBitsPerColorComponent kIORangeBitsPerColorComponentNotSupported = 0x0000, kIORangeBitsPerColorComponent6 = 0x0001, kIORangeBitsPerColorComponent8 = 0x0002, kIORangeBitsPerColorComponent10 = 0x0004, kIORangeBitsPerColorComponent12 = 0x0008, kIORangeBitsPerColorComponent16 = 0x0010, }; enum { // supportedColorimetry kIORangeColorimetryNotSupported = 0x0000, kIORangeColorimetryNativeRGB = 0x0001, kIORangeColorimetrysRGB = 0x0002, kIORangeColorimetryDCIP3 = 0x0004, kIORangeColorimetryAdobeRGB = 0x0008, kIORangeColorimetryxvYCC = 0x0010, kIORangeColorimetryWGRGB = 0x0020, kIORangeColorimetryBT601 = 0x0040, kIORangeColorimetryBT709 = 0x0080, kIORangeColorimetryBT2020 = 0x0100, kIORangeColorimetryBT2100 = 0x0200, }; enum { // supportedDynamicRangeModes - should be in sync with "dynamicRange" enum above kIORangeDynamicRangeNotSupported = 0x0000, kIORangeDynamicRangeSDR = 0x0001, kIORangeDynamicRangeHDR10 = 0x0002, kIORangeDynamicRangeDolbyNormalMode = 0x0004, kIORangeDynamicRangeDolbyTunnelMode = 0x0008, kIORangeDynamicRangeTraditionalGammaHDR = 0x0010, kIORangeDynamicRangeTraditionalGammaSDR = 0x0020, // as of IOGRAPHICSTYPES_REV 72 }; enum { // supportedSignalLevels kIORangeSupportsSignal_0700_0300 = 0x00000001, kIORangeSupportsSignal_0714_0286 = 0x00000002, kIORangeSupportsSignal_1000_0400 = 0x00000004, kIORangeSupportsSignal_0700_0000 = 0x00000008 }; enum { // supportedSyncFlags kIORangeSupportsSeparateSyncs = 0x00000001, kIORangeSupportsSyncOnGreen = 0x00000002, kIORangeSupportsCompositeSync = 0x00000004, kIORangeSupportsVSyncSerration = 0x00000008, kIORangeSupportsVRR = 0x00000010 // since IOGRAPHICSTYPES_REV 76 }; enum { // supportedSignalConfigs kIORangeSupportsInterlacedCEATiming = 0x00000004, kIORangeSupportsInterlacedCEATimingWithConfirm = 0x00000008, kIORangeSupportsMultiAlignedTiming = 0x00000040 // since IOGRAPHICSTYPES_REV 75 }; enum { // signalConfig kIODigitalSignal = 0x00000001, kIOAnalogSetupExpected = 0x00000002, kIOInterlacedCEATiming = 0x00000004, kIONTSCTiming = 0x00000008, kIOPALTiming = 0x00000010, kIODSCBlockPredEnable = 0x00000020, kIOMultiAlignedTiming = 0x00000040, // since IOGRAPHICSTYPES_REV 73 }; enum { // signalLevels for analog kIOAnalogSignalLevel_0700_0300 = 0, kIOAnalogSignalLevel_0714_0286 = 1, kIOAnalogSignalLevel_1000_0400 = 2, kIOAnalogSignalLevel_0700_0000 = 3 }; enum { // horizontalSyncConfig and verticalSyncConfig kIOSyncPositivePolarity = 0x00000001 }; /*! * @struct IODisplayScalerInformation * @abstract A structure defining the scaling capabilities of a framebuffer. * @discussion This structure is used to define the limits for modes programmed as detailed timings by the OS. A data property with this structure under the key kIOFBScalerInfoKey in a framebuffer will allow the OS to program detailed timings that are scaled to a displays native resolution. * @field __reservedA Set to zero. * @field version Set to zero. * @field __reservedB Set to zero. * @field scalerFeatures Mask of scaling features. The following are defined:<br> * kIOScaleStretchOnly If set the framebuffer can only provide stretched scaling with non-square pixels, without borders.<br> * kIOScaleCanUpSamplePixels If set framebuffer can scale up from a smaller number of source pixels to a larger native timing (eg. 640x480 pixels on a 1600x1200 timing).<br> * kIOScaleCanDownSamplePixels If set framebuffer can scale down from a larger number of source pixels to a smaller native timing (eg. 1600x1200 pixels on a 640x480 timing).<br> * kIOScaleCanScaleInterlaced If set framebuffer can scale an interlaced detailed timing.<br> * kIOScaleCanSupportInset If set framebuffer can support scaled modes with non-zero horizontalScaledInset, verticalScaledInset fields.<br> * kIOScaleCanRotate If set framebuffer can support some of the flags in the kIOScaleRotateFlags mask.<br> * kIOScaleCanBorderInsetOnly If set framebuffer can support scaled modes with non-zero horizontalScaledInset, verticalScaledInset fields, but requires the active pixels to be equal in size to the inset area, ie. can do insets with a border versus scaling an image.<br> * @field maxHorizontalPixels Maximum number of horizontal source pixels (horizontalScaled).<br> * @field maxVerticalPixels Maximum number of vertical source pixels (verticalScaled).<br> * @field __reservedC Set to zero. */ struct IODisplayScalerInformation { UInt32 __reservedA[1]; // Init to 0 UInt32 version; // Init to 0 UInt32 __reservedB[2]; // Init to 0 IOOptionBits scalerFeatures; UInt32 maxHorizontalPixels; UInt32 maxVerticalPixels; UInt32 __reservedC[5]; // Init to 0 }; typedef struct IODisplayScalerInformation IODisplayScalerInformation; enum { /* scalerFeatures */ kIOScaleStretchOnly = 0x00000001, kIOScaleCanUpSamplePixels = 0x00000002, kIOScaleCanDownSamplePixels = 0x00000004, kIOScaleCanScaleInterlaced = 0x00000008, kIOScaleCanSupportInset = 0x00000010, kIOScaleCanRotate = 0x00000020, kIOScaleCanBorderInsetOnly = 0x00000040 }; //// Connections enum { kOrConnections = 0xffffffe, kAndConnections = 0xffffffd }; enum { kConnectionFlags = 'flgs', kConnectionSyncEnable = 'sync', kConnectionSyncFlags = 'sycf', kConnectionSupportsAppleSense = 'asns', kConnectionSupportsLLDDCSense = 'lddc', kConnectionSupportsHLDDCSense = 'hddc', kConnectionEnable = 'enab', kConnectionCheckEnable = 'cena', kConnectionProbe = 'prob', kConnectionIgnore = '\0igr', kConnectionChanged = 'chng', kConnectionPower = 'powr', kConnectionPostWake = 'pwak', kConnectionDisplayParameterCount = 'pcnt', kConnectionDisplayParameters = 'parm', kConnectionOverscan = 'oscn', kConnectionVideoBest = 'vbst', kConnectionRedGammaScale = 'rgsc', kConnectionGreenGammaScale = 'ggsc', kConnectionBlueGammaScale = 'bgsc', kConnectionGammaScale = 'gsc ', kConnectionFlushParameters = 'flus', kConnectionVBLMultiplier = 'vblm', kConnectionHandleDisplayPortEvent = 'dpir', kConnectionPanelTimingDisable = 'pnlt', kConnectionColorMode = 'cyuv', kConnectionColorModesSupported = 'colr', kConnectionColorDepthsSupported = ' bpc', kConnectionControllerDepthsSupported = '\0grd', kConnectionControllerColorDepth = '\0dpd', kConnectionControllerDitherControl = '\0gdc', kConnectionDisplayFlags = 'dflg', kConnectionEnableAudio = 'aud ', kConnectionAudioStreaming = 'auds', kConnectionStartOfFrameTime = 'soft', // as of IOGRAPHICSTYPES_REV 65 }; // kConnectionFlags values enum { kIOConnectionBuiltIn = 0x00000800, kIOConnectionStereoSync = 0x00008000 }; // kConnectionSyncControl values enum { kIOHSyncDisable = 0x00000001, kIOVSyncDisable = 0x00000002, kIOCSyncDisable = 0x00000004, kIONoSeparateSyncControl = 0x00000040, kIOTriStateSyncs = 0x00000080, kIOSyncOnBlue = 0x00000008, kIOSyncOnGreen = 0x00000010, kIOSyncOnRed = 0x00000020 }; // kConnectionHandleDisplayPortEvent values enum { kIODPEventStart = 1, kIODPEventIdle = 2, kIODPEventForceRetrain = 3, kIODPEventRemoteControlCommandPending = 256, kIODPEventAutomatedTestRequest = 257, kIODPEventContentProtection = 258, kIODPEventMCCS = 259, kIODPEventSinkSpecific = 260 }; #define kIODisplayAttributesKey "IODisplayAttributes" #define kIODisplaySupportsUnderscanKey "IODisplaySupportsUnderscan" #define kIODisplaySupportsBasicAudioKey "IODisplaySupportsBasicAudio" #define kIODisplaySupportsYCbCr444Key "IODisplaySupportsYCbCr444" #define kIODisplaySupportsYCbCr422Key "IODisplaySupportsYCbCr422" #define kIODisplaySelectedColorModeKey "cmod" enum { kIODisplayColorMode = kConnectionColorMode, }; #if 0 enum { // kConnectionColorMode attribute kIODisplayColorModeReserved = 0x00000000, kIODisplayColorModeRGB = 0x00000001, kIODisplayColorModeYCbCr422 = 0x00000010, kIODisplayColorModeYCbCr444 = 0x00000100, kIODisplayColorModeRGBLimited = 0x00001000, kIODisplayColorModeAuto = 0x10000000, }; #endif enum { // kConnectionColorDepthsSupported attribute kIODisplayRGBColorComponentBitsUnknown = 0x00000000, kIODisplayRGBColorComponentBits6 = 0x00000001, kIODisplayRGBColorComponentBits8 = 0x00000002, kIODisplayRGBColorComponentBits10 = 0x00000004, kIODisplayRGBColorComponentBits12 = 0x00000008, kIODisplayRGBColorComponentBits14 = 0x00000010, kIODisplayRGBColorComponentBits16 = 0x00000020, kIODisplayYCbCr444ColorComponentBitsUnknown = 0x00000000, kIODisplayYCbCr444ColorComponentBits6 = 0x00000100, kIODisplayYCbCr444ColorComponentBits8 = 0x00000200, kIODisplayYCbCr444ColorComponentBits10 = 0x00000400, kIODisplayYCbCr444ColorComponentBits12 = 0x00000800, kIODisplayYCbCr444ColorComponentBits14 = 0x00001000, kIODisplayYCbCr444ColorComponentBits16 = 0x00002000, kIODisplayYCbCr422ColorComponentBitsUnknown = 0x00000000, kIODisplayYCbCr422ColorComponentBits6 = 0x00010000, kIODisplayYCbCr422ColorComponentBits8 = 0x00020000, kIODisplayYCbCr422ColorComponentBits10 = 0x00040000, kIODisplayYCbCr422ColorComponentBits12 = 0x00080000, kIODisplayYCbCr422ColorComponentBits14 = 0x00100000, kIODisplayYCbCr422ColorComponentBits16 = 0x00200000, }; enum { // kConnectionDitherControl attribute kIODisplayDitherDisable = 0x00000000, kIODisplayDitherSpatial = 0x00000001, kIODisplayDitherTemporal = 0x00000002, kIODisplayDitherFrameRateControl = 0x00000004, kIODisplayDitherDefault = 0x00000080, kIODisplayDitherAll = 0x000000FF, kIODisplayDitherRGBShift = 0, kIODisplayDitherYCbCr444Shift = 8, kIODisplayDitherYCbCr422Shift = 16, }; enum { // kConnectionDisplayFlags attribute kIODisplayNeedsCEAUnderscan = 0x00000001, }; enum { kIODisplayPowerStateOff = 0, kIODisplayPowerStateMinUsable = 1, kIODisplayPowerStateOn = 2, }; #define IO_DISPLAY_CAN_FILL 0x00000040 #define IO_DISPLAY_CAN_BLIT 0x00000020 #define IO_24BPP_TRANSFER_TABLE_SIZE 256 #define IO_15BPP_TRANSFER_TABLE_SIZE 256 #define IO_8BPP_TRANSFER_TABLE_SIZE 256 #define IO_12BPP_TRANSFER_TABLE_SIZE 256 #define IO_2BPP_TRANSFER_TABLE_SIZE 256 #define STDFB_BM256_TO_BM38_MAP_SIZE 256 #define STDFB_BM38_TO_BM256_MAP_SIZE 256 #define STDFB_BM38_TO_256_WITH_LOGICAL_SIZE \ (STDFB_BM38_TO_BM256_MAP_SIZE + (256/sizeof(int))) #define STDFB_4BPS_TO_5BPS_MAP_SIZE 16 #define STDFB_5BPS_TO_4BPS_MAP_SIZE 32 enum { // connection types for IOServiceOpen kIOFBServerConnectType = 0, kIOFBSharedConnectType = 1, kIOGDiagnoseGTraceType = 11452, // On Display Wrangler kIOGDiagnoseConnectType = 38744, #ifndef _OPEN_SOURCE_ kIODisplayAssertionConnectType = 61074, #endif // !_OPEN_SOURCE_ }; enum { // options for IOServiceRequestProbe() kIOFBUserRequestProbe = 0x00000001 }; struct IOGPoint { SInt16 x; SInt16 y; }; typedef struct IOGPoint IOGPoint; struct IOGSize { SInt16 width; SInt16 height; }; typedef struct IOGSize IOGSize; struct IOGBounds { SInt16 minx; SInt16 maxx; SInt16 miny; SInt16 maxy; }; typedef struct IOGBounds IOGBounds; #ifndef kIODescriptionKey #if !defined(__Point__) && !defined(BINTREE_H) && !defined(__MACTYPES__) #define __Point__ typedef IOGPoint Point; #endif #if !defined(__Bounds__) && !defined(BINTREE_H) && !defined(__MACTYPES__) #define __Bounds__ typedef IOGBounds Bounds; #endif #endif /* !kIODescriptionKey */ // cursor description enum { kTransparentEncoding = 0, kInvertingEncoding }; enum { kTransparentEncodingShift = (kTransparentEncoding << 1), kTransparentEncodedPixel = (0x01 << kTransparentEncodingShift), kInvertingEncodingShift = (kInvertingEncoding << 1), kInvertingEncodedPixel = (0x01 << kInvertingEncodingShift) }; enum { kHardwareCursorDescriptorMajorVersion = 0x0001, kHardwareCursorDescriptorMinorVersion = 0x0000 }; /*! * @struct IOHardwareCursorDescriptor * @abstract A structure defining the format of a hardware cursor. * @discussion This structure is used by IOFramebuffer to define the format of a hardware cursor. * @field majorVersion Set to kHardwareCursorDescriptorMajorVersion. * @field minorVersion Set to kHardwareCursorDescriptorMinorVersion. * @field height Maximum size of the cursor. * @field width Maximum size of the cursor. * @field bitDepth Number bits per pixel, or a QD/QT pixel type, for example kIO8IndexedPixelFormat, kIO32ARGBPixelFormat. * @field maskBitDepth Unused. * @field numColors Number of colors for indexed pixel types. * @field colorEncodings An array pointer specifying the pixel values corresponding to the indices into the color table, for indexed pixel types. * @field flags None defined, set to zero. * @field supportedSpecialEncodings Mask of supported special pixel values, eg. kTransparentEncodedPixel, kInvertingEncodedPixel. * @field specialEncodings Array of pixel values for each supported special encoding. */ struct IOHardwareCursorDescriptor { UInt16 majorVersion; UInt16 minorVersion; UInt32 height; UInt32 width; UInt32 bitDepth; // bits per pixel, or a QD/QT pixel type UInt32 maskBitDepth; // unused UInt32 numColors; // number of colors in the colorMap. ie. UInt32 * colorEncodings; UInt32 flags; UInt32 supportedSpecialEncodings; UInt32 specialEncodings[16]; }; typedef struct IOHardwareCursorDescriptor IOHardwareCursorDescriptor; enum { kHardwareCursorInfoMajorVersion = 0x0001, kHardwareCursorInfoMinorVersion = 0x0000 }; /*! * @struct IOHardwareCursorInfo * @abstract A structure defining the converted data of a hardware cursor. * @discussion This structure is used by IOFramebuffer to return the data of a hardware cursor by convertCursorImage() after conversion based on the IOHardwareCursorDescriptor passed to that routine. * @field majorVersion Set to kHardwareCursorInfoMajorVersion. * @field minorVersion Set to kHardwareCursorInfoMinorVersion. * @field cursorHeight The actual size of the cursor is returned. * @field cursorWidth The actual size of the cursor is returned. * @field colorMap Pointer to array of IOColorEntry structures, with the number of elements set by the numColors field of the IOHardwareCursorDescriptor. Zero should be passed for direct pixel formats. * @field hardwareCursorData Buffer to receive the converted cursor data. * @field cursorHotSpotX Cursor's hotspot. * @field cursorHotSpotY Cursor's hotspot. * @field reserved Reserved, set to zero. */ struct IOHardwareCursorInfo { UInt16 majorVersion; UInt16 minorVersion; UInt32 cursorHeight; UInt32 cursorWidth; // nil or big enough for hardware's max colors IOColorEntry * colorMap; UInt8 * hardwareCursorData; UInt16 cursorHotSpotX; UInt16 cursorHotSpotY; UInt32 reserved[5]; }; typedef struct IOHardwareCursorInfo IOHardwareCursorInfo; // interrupt types enum { kIOFBVBLInterruptType = 'vbl ', kIOFBHBLInterruptType = 'hbl ', kIOFBFrameInterruptType = 'fram', // Demand to check configuration (Hardware unchanged) kIOFBConnectInterruptType = 'dci ', // Demand to rebuild (Hardware has reinitialized on dependent change) kIOFBChangedInterruptType = 'chng', // Demand to remove framebuffer (Hardware not available on dependent change -- but must not buserror) kIOFBOfflineInterruptType = 'remv', // Notice that hardware is available (after being removed) kIOFBOnlineInterruptType = 'add ', // DisplayPort short pulse kIOFBDisplayPortInterruptType = 'dpir', // DisplayPort link event kIOFBDisplayPortLinkChangeInterruptType = 'dplk', // MCCS kIOFBMCCSInterruptType = 'mccs', // early vram notification kIOFBWakeInterruptType = 'vwak', }; // IOAppleTimingID's enum { kIOTimingIDInvalid = 0, /* Not a standard timing */ kIOTimingIDApple_FixedRateLCD = 42, /* Lump all fixed-rate LCDs into one category.*/ kIOTimingIDApple_512x384_60hz = 130, /* 512x384 (60 Hz) Rubik timing. */ kIOTimingIDApple_560x384_60hz = 135, /* 560x384 (60 Hz) Rubik-560 timing. */ kIOTimingIDApple_640x480_67hz = 140, /* 640x480 (67 Hz) HR timing. */ kIOTimingIDApple_640x400_67hz = 145, /* 640x400 (67 Hz) HR-400 timing. */ kIOTimingIDVESA_640x480_60hz = 150, /* 640x480 (60 Hz) VGA timing. */ kIOTimingIDVESA_640x480_72hz = 152, /* 640x480 (72 Hz) VGA timing. */ kIOTimingIDVESA_640x480_75hz = 154, /* 640x480 (75 Hz) VGA timing. */ kIOTimingIDVESA_640x480_85hz = 158, /* 640x480 (85 Hz) VGA timing. */ kIOTimingIDGTF_640x480_120hz = 159, /* 640x480 (120 Hz) VESA Generalized Timing Formula */ kIOTimingIDApple_640x870_75hz = 160, /* 640x870 (75 Hz) FPD timing.*/ kIOTimingIDApple_640x818_75hz = 165, /* 640x818 (75 Hz) FPD-818 timing.*/ kIOTimingIDApple_832x624_75hz = 170, /* 832x624 (75 Hz) GoldFish timing.*/ kIOTimingIDVESA_800x600_56hz = 180, /* 800x600 (56 Hz) SVGA timing. */ kIOTimingIDVESA_800x600_60hz = 182, /* 800x600 (60 Hz) SVGA timing. */ kIOTimingIDVESA_800x600_72hz = 184, /* 800x600 (72 Hz) SVGA timing. */ kIOTimingIDVESA_800x600_75hz = 186, /* 800x600 (75 Hz) SVGA timing. */ kIOTimingIDVESA_800x600_85hz = 188, /* 800x600 (85 Hz) SVGA timing. */ kIOTimingIDVESA_1024x768_60hz = 190, /* 1024x768 (60 Hz) VESA 1K-60Hz timing. */ kIOTimingIDVESA_1024x768_70hz = 200, /* 1024x768 (70 Hz) VESA 1K-70Hz timing. */ kIOTimingIDVESA_1024x768_75hz = 204, /* 1024x768 (75 Hz) VESA 1K-75Hz timing (very similar to kIOTimingIDApple_1024x768_75hz). */ kIOTimingIDVESA_1024x768_85hz = 208, /* 1024x768 (85 Hz) VESA timing. */ kIOTimingIDApple_1024x768_75hz = 210, /* 1024x768 (75 Hz) Apple 19" RGB. */ kIOTimingIDVESA_1152x864_75hz = 215, /* 1152x864 (75 Hz) VESA timing. */ kIOTimingIDApple_1152x870_75hz = 220, /* 1152x870 (75 Hz) Apple 21" RGB. */ kIOTimingIDAppleNTSC_ST = 230, /* 512x384 (60 Hz, interlaced, non-convolved). */ kIOTimingIDAppleNTSC_FF = 232, /* 640x480 (60 Hz, interlaced, non-convolved). */ kIOTimingIDAppleNTSC_STconv = 234, /* 512x384 (60 Hz, interlaced, convolved). */ kIOTimingIDAppleNTSC_FFconv = 236, /* 640x480 (60 Hz, interlaced, convolved). */ kIOTimingIDApplePAL_ST = 238, /* 640x480 (50 Hz, interlaced, non-convolved). */ kIOTimingIDApplePAL_FF = 240, /* 768x576 (50 Hz, interlaced, non-convolved). */ kIOTimingIDApplePAL_STconv = 242, /* 640x480 (50 Hz, interlaced, convolved). */ kIOTimingIDApplePAL_FFconv = 244, /* 768x576 (50 Hz, interlaced, convolved). */ kIOTimingIDVESA_1280x960_75hz = 250, /* 1280x960 (75 Hz) */ kIOTimingIDVESA_1280x960_60hz = 252, /* 1280x960 (60 Hz) */ kIOTimingIDVESA_1280x960_85hz = 254, /* 1280x960 (85 Hz) */ kIOTimingIDVESA_1280x1024_60hz = 260, /* 1280x1024 (60 Hz) */ kIOTimingIDVESA_1280x1024_75hz = 262, /* 1280x1024 (75 Hz) */ kIOTimingIDVESA_1280x1024_85hz = 268, /* 1280x1024 (85 Hz) */ kIOTimingIDVESA_1600x1200_60hz = 280, /* 1600x1200 (60 Hz) VESA timing. */ kIOTimingIDVESA_1600x1200_65hz = 282, /* 1600x1200 (65 Hz) VESA timing. */ kIOTimingIDVESA_1600x1200_70hz = 284, /* 1600x1200 (70 Hz) VESA timing. */ kIOTimingIDVESA_1600x1200_75hz = 286, /* 1600x1200 (75 Hz) VESA timing (pixel clock is 189.2 Mhz dot clock). */ kIOTimingIDVESA_1600x1200_80hz = 288, /* 1600x1200 (80 Hz) VESA timing (pixel clock is 216>? Mhz dot clock) - proposed only. */ kIOTimingIDVESA_1600x1200_85hz = 289, /* 1600x1200 (85 Hz) VESA timing (pixel clock is 229.5 Mhz dot clock). */ kIOTimingIDVESA_1792x1344_60hz = 296, /* 1792x1344 (60 Hz) VESA timing (204.75 Mhz dot clock). */ kIOTimingIDVESA_1792x1344_75hz = 298, /* 1792x1344 (75 Hz) VESA timing (261.75 Mhz dot clock). */ kIOTimingIDVESA_1856x1392_60hz = 300, /* 1856x1392 (60 Hz) VESA timing (218.25 Mhz dot clock). */ kIOTimingIDVESA_1856x1392_75hz = 302, /* 1856x1392 (75 Hz) VESA timing (288 Mhz dot clock). */ kIOTimingIDVESA_1920x1440_60hz = 304, /* 1920x1440 (60 Hz) VESA timing (234 Mhz dot clock). */ kIOTimingIDVESA_1920x1440_75hz = 306, /* 1920x1440 (75 Hz) VESA timing (297 Mhz dot clock). */ kIOTimingIDSMPTE240M_60hz = 400, /* 60Hz V, 33.75KHz H, interlaced timing, 16:9 aspect, typical resolution of 1920x1035. */ kIOTimingIDFilmRate_48hz = 410, /* 48Hz V, 25.20KHz H, non-interlaced timing, typical resolution of 640x480. */ kIOTimingIDSony_1600x1024_76hz = 500, /* 1600x1024 (76 Hz) Sony timing (pixel clock is 170.447 Mhz dot clock). */ kIOTimingIDSony_1920x1080_60hz = 510, /* 1920x1080 (60 Hz) Sony timing (pixel clock is 159.84 Mhz dot clock). */ kIOTimingIDSony_1920x1080_72hz = 520, /* 1920x1080 (72 Hz) Sony timing (pixel clock is 216.023 Mhz dot clock). */ kIOTimingIDSony_1920x1200_76hz = 540, /* 1900x1200 (76 Hz) Sony timing (pixel clock is 243.20 Mhz dot clock). */ kIOTimingIDApple_0x0_0hz_Offline = 550, /* Indicates that this timing will take the display off-line and remove it from the system. */ kIOTimingIDVESA_848x480_60hz = 570, /* 848x480 (60 Hz) VESA timing. */ kIOTimingIDVESA_1360x768_60hz = 590 /* 1360x768 (60 Hz) VESA timing. */ }; // framebuffer property keys #define kIOFramebufferInfoKey "IOFramebufferInformation" #define kIOFBWidthKey "IOFBWidth" #define kIOFBHeightKey "IOFBHeight" #define kIOFBRefreshRateKey "IOFBRefreshRate" #define kIOFBFlagsKey "IOFBFlags" #define kIOFBBytesPerRowKey "IOFBBytesPerRow" #define kIOFBBytesPerPlaneKey "IOFBBytesPerPlane" #define kIOFBBitsPerPixelKey "IOFBBitsPerPixel" #define kIOFBComponentCountKey "IOFBComponentCount" #define kIOFBBitsPerComponentKey "IOFBBitsPerComponent" #define kIOFBDetailedTimingsKey "IOFBDetailedTimings" #define kIOFBTimingRangeKey "IOFBTimingRange" #define kIOFBScalerInfoKey "IOFBScalerInfo" #define kIOFBCursorInfoKey "IOFBCursorInfo" #define kIOFBHDMIDongleROMKey "IOFBHDMIDongleROM" #define kIOFBHostAccessFlagsKey "IOFBHostAccessFlags" #define kIOFBMemorySizeKey "IOFBMemorySize" #define kIOFBNeedsRefreshKey "IOFBNeedsRefresh" #define kIOFBProbeOptionsKey "IOFBProbeOptions" #define kIOFBGammaWidthKey "IOFBGammaWidth" #define kIOFBGammaCountKey "IOFBGammaCount" #define kIOFBCLUTDeferKey "IOFBCLUTDefer" #define kIOFBDisplayPortConfigurationDataKey "dpcd-registers" // exists on the hibernate progress display device #ifndef kIOHibernatePreviewActiveKey #define kIOHibernatePreviewActiveKey "IOHibernatePreviewActive" // values for kIOHibernatePreviewActiveKey set by driver enum { kIOHibernatePreviewActive = 0x00000001, kIOHibernatePreviewUpdates = 0x00000002 }; #endif #define kIOHibernateEFIGfxStatusKey "IOHibernateEFIGfxStatus" // CFNumber/CFData #define kIOFBAVSignalTypeKey "av-signal-type" enum { kIOFBAVSignalTypeUnknown = 0x00000000, kIOFBAVSignalTypeVGA = 0x00000001, kIOFBAVSignalTypeDVI = 0x00000002, kIOFBAVSignalTypeHDMI = 0x00000008, kIOFBAVSignalTypeDP = 0x00000010, }; // kIOFBDisplayPortTrainingAttribute data struct IOFBDPLinkConfig { uint16_t version; // 8 bit high (major); 8 bit low (minor) uint8_t bitRate; // same encoding as the spec uint8_t __reservedA[1]; // reserved set to zero uint16_t t1Time; // minimum duration of the t1 pattern (microseconds) uint16_t t2Time; // minimum duration of the t2 pattern uint16_t t3Time; // minimum duration of the t3 pattern uint8_t idlePatterns; // minimum number of idle patterns uint8_t laneCount; // number of lanes in the link uint8_t voltage; uint8_t preEmphasis; uint8_t downspread; uint8_t scrambler; uint8_t maxBitRate; // same encoding as the bitRate field uint8_t maxLaneCount; // an integer uint8_t maxDownspread; // 0 = Off. 1 = 0.5 uint8_t __reservedB[9]; // reserved set to zero - fix align and provide 8 bytes of padding. }; typedef struct IOFBDPLinkConfig IOFBDPLinkConfig; enum { kIOFBBitRateRBR = 0x06, // 1.62 Gbps per lane kIOFBBitRateHBR = 0x0A, // 2.70 Gbps per lane kIOFBBitRateHBR2 = 0x14, // 5.40 Gbps per lane }; enum { kIOFBLinkVoltageLevel0 = 0x00, kIOFBLinkVoltageLevel1 = 0x01, kIOFBLinkVoltageLevel2 = 0x02, kIOFBLinkVoltageLevel3 = 0x03 }; enum { kIOFBLinkPreEmphasisLevel0 = 0x00, kIOFBLinkPreEmphasisLevel1 = 0x01, kIOFBLinkPreEmphasisLevel2 = 0x02, kIOFBLinkPreEmphasisLevel3 = 0x03 }; enum { kIOFBLinkDownspreadNone = 0x0, kIOFBLinkDownspreadMax = 0x1 }; enum { kIOFBLinkScramblerNormal = 0x0, // for external displays kIOFBLinkScramblerAlternate = 0x1 // used for eDP }; // diagnostic keys #define kIOFBConfigKey "IOFBConfig" #define kIOFBModesKey "IOFBModes" #define kIOFBModeIDKey "ID" #define kIOFBModeDMKey "DM" #define kIOFBModeTMKey "TM" #define kIOFBModeAIDKey "AID" #define kIOFBModeDFKey "DF" #define kIOFBModePIKey "PI" // display property keys #define kIODisplayEDIDKey "IODisplayEDID" #define kIODisplayEDIDOriginalKey "IODisplayEDIDOriginal" #define kIODisplayLocationKey "IODisplayLocation" // CFString #define kIODisplayConnectFlagsKey "IODisplayConnectFlags" // CFNumber #define kIODisplayHasBacklightKey "IODisplayHasBacklight" // CFBoolean #define kIODisplayIsDigitalKey "IODisplayIsDigital" // CFBoolean #define kDisplayBundleKey "DisplayBundle" #define kAppleDisplayTypeKey "AppleDisplayType" #define kAppleSenseKey "AppleSense" #define kIODisplayMCCSVersionKey "IODisplayMCCSVersion" #define kIODisplayTechnologyTypeKey "IODisplayTechnologyType" #define kIODisplayUsageTimeKey "IODisplayUsageTime" #define kIODisplayFirmwareLevelKey "IODisplayFirmwareLevel" enum { kDisplayVendorIDUnknown = 'unkn', kDisplayProductIDGeneric = 0x717 }; #define kDisplayVendorID "DisplayVendorID" // CFNumber #define kDisplayProductID "DisplayProductID" // CFNumber #define kDisplaySerialNumber "DisplaySerialNumber" // CFNumber #define kDisplaySerialString "DisplaySerialString" // CFString #define kDisplayWeekOfManufacture "DisplayWeekManufacture" // CFNumber #define kDisplayYearOfManufacture "DisplayYearManufacture" // CFNumber // CFDictionary of language-locale keys, name values // eg. "en"="Color LCD", "en-GB"="Colour LCD" #define kDisplayProductName "DisplayProductName" // all CFNumber or CFArray of CFNumber (floats) #define kDisplayWhitePointX "DisplayWhitePointX" #define kDisplayWhitePointY "DisplayWhitePointY" #define kDisplayRedPointX "DisplayRedPointX" #define kDisplayRedPointY "DisplayRedPointY" #define kDisplayGreenPointX "DisplayGreenPointX" #define kDisplayGreenPointY "DisplayGreenPointY" #define kDisplayBluePointX "DisplayBluePointX" #define kDisplayBluePointY "DisplayBluePointY" #define kDisplayWhiteGamma "DisplayWhiteGamma" #define kDisplayRedGamma "DisplayRedGamma" #define kDisplayGreenGamma "DisplayGreenGamma" #define kDisplayBlueGamma "DisplayBlueGamma" // Display gamma #define kDisplayGammaChannels "DisplayGammaChannels" // CFNumber 1 or 3 channel count #define kDisplayGammaEntryCount "DisplayGammaEntryCount" // CFNumber 1-based count of entries per channel #define kDisplayGammaEntrySize "DisplayGammaEntrySize" // CFNumber size in bytes of each table entry #define kDisplayGammaTable "DisplayGammaTable" // CFData // CFBoolean #define kDisplayBrightnessAffectsGamma "DisplayBrightnessAffectsGamma" #define kDisplayViewAngleAffectsGamma "DisplayViewAngleAffectsGamma" // CFData #define kDisplayCSProfile "DisplayCSProfile" // CFNumber #define kDisplayHorizontalImageSize "DisplayHorizontalImageSize" #define kDisplayVerticalImageSize "DisplayVerticalImageSize" // Pixel description // CFBoolean #define kDisplayFixedPixelFormat "DisplayFixedPixelFormat" enum { kDisplaySubPixelLayoutUndefined = 0x00000000, kDisplaySubPixelLayoutRGB = 0x00000001, kDisplaySubPixelLayoutBGR = 0x00000002, kDisplaySubPixelLayoutQuadGBL = 0x00000003, kDisplaySubPixelLayoutQuadGBR = 0x00000004, kDisplaySubPixelConfigurationUndefined = 0x00000000, kDisplaySubPixelConfigurationDelta = 0x00000001, kDisplaySubPixelConfigurationStripe = 0x00000002, kDisplaySubPixelConfigurationStripeOffset = 0x00000003, kDisplaySubPixelConfigurationQuad = 0x00000004, kDisplaySubPixelShapeUndefined = 0x00000000, kDisplaySubPixelShapeRound = 0x00000001, kDisplaySubPixelShapeSquare = 0x00000002, kDisplaySubPixelShapeRectangular = 0x00000003, kDisplaySubPixelShapeOval = 0x00000004, kDisplaySubPixelShapeElliptical = 0x00000005 }; // CFNumbers #define kDisplaySubPixelLayout "DisplaySubPixelLayout" #define kDisplaySubPixelConfiguration "DisplaySubPixelConfiguration" #define kDisplaySubPixelShape "DisplaySubPixelShape" #define kIODisplayOverrideMatchingKey "IODisplayOverrideMatching" // Display parameters #define kIODisplayParametersKey "IODisplayParameters" #define kIODisplayGUIDKey "IODisplayGUID" #define kIODisplayValueKey "value" #define kIODisplayMinValueKey "min" #define kIODisplayMaxValueKey "max" #define kIODisplayBrightnessProbeKey "brightness-probe" #define kIODisplayLinearBrightnessProbeKey "linear-brightness-probe" #define kIODisplayBrightnessKey "brightness" #define kIODisplayLinearBrightnessKey "linear-brightness" #define kIODisplayUsableLinearBrightnessKey "usable-linear-brightness" #define kIODisplayBrightnessFadeKey "brightness-fade" #define kIODisplayContrastKey "contrast" #define kIODisplayHorizontalPositionKey "horizontal-position" #define kIODisplayHorizontalSizeKey "horizontal-size" #define kIODisplayVerticalPositionKey "vertical-position" #define kIODisplayVerticalSizeKey "vertical-size" #define kIODisplayTrapezoidKey "trapezoid" #define kIODisplayPincushionKey "pincushion" #define kIODisplayParallelogramKey "parallelogram" #define kIODisplayRotationKey "rotation" #define kIODisplayTheatreModeKey "theatre-mode" #define kIODisplayTheatreModeWindowKey "theatre-mode-window" #define kIODisplayOverscanKey "oscn" #define kIODisplayVideoBestKey "vbst" #define kIODisplaySpeakerVolumeKey "speaker-volume" #define kIODisplaySpeakerSelectKey "speaker-select" #define kIODisplayMicrophoneVolumeKey "microphone-volume" #define kIODisplayAmbientLightSensorKey "ambient-light-sensor" #define kIODisplayAudioMuteAndScreenBlankKey "audio-mute-and-screen-blank" #define kIODisplayAudioTrebleKey "audio-treble" #define kIODisplayAudioBassKey "audio-bass" #define kIODisplayAudioBalanceLRKey "audio-balance-LR" #define kIODisplayAudioProcessorModeKey "audio-processor-mode" #define kIODisplayPowerModeKey "power-mode" #define kIODisplayManufacturerSpecificKey "manufacturer-specific" #define kIODisplayPowerStateKey "dsyp" #define kIODisplayControllerIDKey "IODisplayControllerID" #define kIODisplayCapabilityStringKey "IODisplayCapabilityString" #define kIODisplayRedGammaScaleKey "rgsc" #define kIODisplayGreenGammaScaleKey "ggsc" #define kIODisplayBlueGammaScaleKey "bgsc" #define kIODisplayGammaScaleKey "gsc " #define kIODisplayParametersCommitKey "commit" #define kIODisplayParametersDefaultKey "defaults" #define kIODisplayParametersFlushKey "flush" #ifdef __cplusplus } #endif #endif /* ! _IOKIT_IOGRAPHICSTYPES_H */
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/graphics/IOGraphicsInterfaceTypes.h
/* * Copyright (c) 1999-2000 Apple Computer, Inc. All rights reserved. * * @APPLE_LICENSE_HEADER_START@ * * The contents of this file constitute Original Code as defined in and * are subject to the Apple Public Source License Version 1.1 (the * "License"). You may not use this file except in compliance with the * License. Please obtain a copy of the License at * http://www.apple.com/publicsource and read it before using this file. * * This Original Code and all software distributed under the License are * distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT. Please see the * License for the specific language governing rights and limitations * under the License. * * @APPLE_LICENSE_HEADER_END@ */ #ifndef _IOKIT_IOGRAPHICSINTERFACETYPES_H #define _IOKIT_IOGRAPHICSINTERFACETYPES_H #include <IOKit/graphics/IOAccelSurfaceConnect.h> #define IO_FOUR_CHAR_CODE(x) (x) typedef UInt32 IOFourCharCode; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #define kCurrentGraphicsInterfaceVersion 1 #define kCurrentGraphicsInterfaceRevision 2 #ifdef IOGA_COMPAT typedef SInt32 IOBlitCompletionToken; #endif typedef UInt32 IOBlitType; enum { kIOBlitTypeVerbMask = 0x000000ff, kIOBlitTypeRects = 0, kIOBlitTypeCopyRects, kIOBlitTypeLines, kIOBlitTypeScanlines, kIOBlitTypeCopyRegion, kIOBlitTypeMoveCursor, kIOBlitTypeShowCursor, kIOBlitTypeHideCursor, kIOBlitTypeMonoExpand = 0x00000100, kIOBlitTypeColorSpaceConvert = 0x00000200, kIOBlitTypeScale = 0x00000400, kIOBlitTypeSourceKeyColorModeMask = 0x00003000, kIOBlitTypeDestKeyColorModeMask = 0x0000c000, kIOBlitTypeSourceKeyColorEqual = 0x00001000, kIOBlitTypeSourceKeyColorNotEqual = 0x00002000, kIOBlitTypeDestKeyColorEqual = 0x00004000, kIOBlitTypeDestKeyColorNotEqual = 0x00008000, kIOBlitTypeOperationMask = 0x0fff0000, kIOBlitTypeOperationShift = 16, kIOBlitTypeOperationTypeMask = 0x0f000000, kIOBlitTypeOperationType0 = 0x00000000, kIOBlitCopyOperation = 0x00000000 | kIOBlitTypeOperationType0, kIOBlitOrOperation = 0x00010000 | kIOBlitTypeOperationType0, kIOBlitXorOperation = 0x00020000 | kIOBlitTypeOperationType0, kIOBlitBlendOperation = 0x00030000 | kIOBlitTypeOperationType0, kIOBlitHighlightOperation = 0x00040000 | kIOBlitTypeOperationType0 }; typedef UInt32 IOBlitSourceType; enum { kIOBlitSourceDefault = 0x00000000, kIOBlitSourceFramebuffer = 0x00001000, kIOBlitSourceMemory = 0x00002000, kIOBlitSourceOOLMemory = 0x00003000, kIOBlitSourcePattern = 0x00004000, kIOBlitSourceOOLPattern = 0x00005000, kIOBlitSourceSolid = 0x00006000, kIOBlitSourceCGSSurface = 0x00007000, kIOBlitSourceIsSame = 0x80000000 }; #ifdef IOGA_COMPAT typedef IOBlitSourceType IOBlitSourceDestType; enum { kIOBlitDestFramebuffer = 0x00000001 }; #endif typedef struct IOBlitOperationStruct { UInt32 color0; UInt32 color1; SInt32 offsetX; SInt32 offsetY; UInt32 sourceKeyColor; UInt32 destKeyColor; UInt32 specific[16]; } IOBlitOperation; typedef struct IOBlitRectangleStruct { SInt32 x; SInt32 y; SInt32 width; SInt32 height; } IOBlitRectangle; typedef struct IOBlitRectanglesStruct { IOBlitOperation operation; IOItemCount count; IOBlitRectangle rects[1]; } IOBlitRectangles; typedef struct IOBlitCopyRectangleStruct { SInt32 sourceX; SInt32 sourceY; SInt32 x; SInt32 y; SInt32 width; SInt32 height; } IOBlitCopyRectangle; typedef struct IOBlitCopyRectanglesStruct { IOBlitOperation operation; IOItemCount count; IOBlitCopyRectangle rects[1]; } IOBlitCopyRectangles; typedef struct IOBlitCopyRegionStruct { IOBlitOperation operation; SInt32 deltaX; SInt32 deltaY; IOAccelDeviceRegion * region; } IOBlitCopyRegion; typedef struct IOBlitVertexStruct { SInt32 x; SInt32 y; } IOBlitVertex; typedef struct IOBlitVerticesStruct { IOBlitOperation operation; IOItemCount count; IOBlitVertex vertices[2]; } IOBlitVertices; typedef struct IOBlitScanlinesStruct { IOBlitOperation operation; IOItemCount count; SInt32 y; SInt32 height; SInt32 x[2]; } IOBlitScanlines; typedef struct IOBlitCursorStruct { IOBlitOperation operation; IOBlitRectangle rect; } IOBlitCursor; typedef struct _IOBlitMemory * IOBlitMemoryRef; /* Quickdraw.h pixel formats*/ enum { kIO1MonochromePixelFormat = 0x00000001, /* 1 bit indexed*/ kIO2IndexedPixelFormat = 0x00000002, /* 2 bit indexed*/ kIO4IndexedPixelFormat = 0x00000004, /* 4 bit indexed*/ kIO8IndexedPixelFormat = 0x00000008, /* 8 bit indexed*/ kIO16BE555PixelFormat = 0x00000010, /* 16 bit BE rgb 555 (Mac)*/ kIO24RGBPixelFormat = 0x00000018, /* 24 bit rgb */ kIO32ARGBPixelFormat = 0x00000020, /* 32 bit argb (Mac)*/ kIO1IndexedGrayPixelFormat = 0x00000021, /* 1 bit indexed gray*/ kIO2IndexedGrayPixelFormat = 0x00000022, /* 2 bit indexed gray*/ kIO4IndexedGrayPixelFormat = 0x00000024, /* 4 bit indexed gray*/ kIO8IndexedGrayPixelFormat = 0x00000028 /* 8 bit indexed gray*/ }; enum { kIO16LE555PixelFormat = IO_FOUR_CHAR_CODE('L555'), /* 16 bit LE rgb 555 (PC)*/ kIO16LE5551PixelFormat = IO_FOUR_CHAR_CODE('5551'), /* 16 bit LE rgb 5551*/ kIO16BE565PixelFormat = IO_FOUR_CHAR_CODE('B565'), /* 16 bit BE rgb 565*/ kIO16LE565PixelFormat = IO_FOUR_CHAR_CODE('L565'), /* 16 bit LE rgb 565*/ kIO24BGRPixelFormat = IO_FOUR_CHAR_CODE('24BG'), /* 24 bit bgr */ kIO32BGRAPixelFormat = IO_FOUR_CHAR_CODE('BGRA'), /* 32 bit bgra (Matrox)*/ kIO32ABGRPixelFormat = IO_FOUR_CHAR_CODE('ABGR'), /* 32 bit abgr */ kIO32RGBAPixelFormat = IO_FOUR_CHAR_CODE('RGBA'), /* 32 bit rgba */ kIOYUVSPixelFormat = IO_FOUR_CHAR_CODE('yuvs'), /* YUV 4:2:2 byte ordering 16-unsigned = 'YUY2'*/ kIOYUVUPixelFormat = IO_FOUR_CHAR_CODE('yuvu'), /* YUV 4:2:2 byte ordering 16-signed*/ kIOYVU9PixelFormat = IO_FOUR_CHAR_CODE('YVU9'), /* YVU9 Planar 9*/ kIOYUV411PixelFormat = IO_FOUR_CHAR_CODE('Y411'), /* YUV 4:1:1 Interleaved 16*/ kIOYVYU422PixelFormat = IO_FOUR_CHAR_CODE('YVYU'), /* YVYU 4:2:2 byte ordering 16*/ kIOUYVY422PixelFormat = IO_FOUR_CHAR_CODE('UYVY'), /* UYVY 4:2:2 byte ordering 16*/ kIOYUV211PixelFormat = IO_FOUR_CHAR_CODE('Y211'), /* YUV 2:1:1 Packed 8*/ kIO2vuyPixelFormat = IO_FOUR_CHAR_CODE('2vuy') /* UYVY 4:2:2 byte ordering 16*/ }; /* Non Quickdraw.h pixel formats*/ enum { kIO16LE4444PixelFormat = IO_FOUR_CHAR_CODE('L444'), /* 16 bit LE argb 4444*/ kIO16BE4444PixelFormat = IO_FOUR_CHAR_CODE('B444'), /* 16 bit BE argb 4444*/ kIO64BGRAPixelFormat = IO_FOUR_CHAR_CODE('B16I'), /* 64 bit bgra */ kIO64RGBAFloatPixelFormat = IO_FOUR_CHAR_CODE('B16F'), /* 64 bit rgba */ kIO128RGBAFloatPixelFormat = IO_FOUR_CHAR_CODE('B32F') /* 128 bit rgba float */ }; enum { kIOBlitMemoryRequiresHostFlush = 0x00000001 }; typedef struct IOBlitSurfaceStruct { union { UInt8 * bytes; IOBlitMemoryRef ref; } memory; IOFourCharCode pixelFormat; IOBlitRectangle size; UInt32 rowBytes; UInt32 byteOffset; UInt32 * palette; IOOptionBits accessFlags; IOBlitMemoryRef interfaceRef; UInt32 more[14]; } IOBlitSurface; typedef IOBlitSurface IOBlitMemory; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ enum { // options for Synchronize kIOBlitSynchronizeWaitBeamExit = 0x00000001, kIOBlitSynchronizeFlushHostWrites = 0x00000002 }; enum { // options for WaitComplete & Flush kIOBlitWaitContext = 0x00000000, kIOBlitWaitAll2D = 0x00000001, kIOBlitWaitGlobal = 0x00000001, kIOBlitWaitAll = 0x00000002, kIOBlitWaitCheck = 0x00000080, kIOBlitFlushWithSwap = 0x00010000 }; enum { // options for AllocateSurface kIOBlitHasCGSSurface = 0x00000001, kIOBlitFixedSource = 0x00000002, kIOBlitBeamSyncSwaps = 0x00000004, kIOBlitReferenceSource = 0x00000008 }; enum { // options for UnlockSurface kIOBlitUnlockWithSwap = 0x80000000 }; enum { // options for SetDestination kIOBlitFramebufferDestination = 0x00000000, kIOBlitSurfaceDestination = 0x00000001 }; enum { // options for blit procs kIOBlitBeamSync = 0x00000001, kIOBlitBeamSyncAlways = 0x00000002, kIOBlitBeamSyncSpin = 0x00000004, kIOBlitAllOptions = 0xffffffff }; enum { // capabilities kIOBlitColorSpaceTypes = IO_FOUR_CHAR_CODE('cspc') }; // keys for IOAccelFindAccelerator() #define kIOAccelTypesKey "IOAccelTypes" #define kIOAccelIndexKey "IOAccelIndex" #define kIOAccelRevisionKey "IOAccelRevision" /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #endif /* !_IOKIT_IOGRAPHICSINTERFACETYPES_H */
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/hidsystem/IOHIDServiceClient.h
/* * Copyright (c) 2016 Apple Computer, Inc. All rights reserved. * * @APPLE_LICENSE_HEADER_START@ * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this * file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_LICENSE_HEADER_END@ */ #ifndef IOHIDServiceClient_h #define IOHIDServiceClient_h #include <CoreFoundation/CoreFoundation.h> __BEGIN_DECLS CF_ASSUME_NONNULL_BEGIN CF_IMPLICIT_BRIDGING_ENABLED /*! @header IOHIDServiceClient IOHIDServiceClient serves as a client to the HID event system services. Users are able to copy/set specific properties (defined in <code>IOKit/hid/IOHIDProperties.h</code>), and gather more information about the services available in the HID event system. */ typedef struct CF_BRIDGED_TYPE(id) __IOHIDServiceClient * IOHIDServiceClientRef; /*! * @function IOHIDServiceClientSetProperty * * @abstract Sets a property on the HID service. * * @param service the HID service to set the property on. * * @param key the property key to set. A list of keys can be found in <code>HIDProperties.h</code>. * * @param property the value to set the property. * * @result Returns true on success. */ Boolean IOHIDServiceClientSetProperty(IOHIDServiceClientRef service, CFStringRef key, CFTypeRef property); /*! * @function IOHIDServiceClientCopyProperty * * @abstract Copies a property from the HID service. * * @param service the HID service to copy the property from. * * @param key the property key to copy. A list of keys can be found in <code>HIDProperties.h</code>. * * @result Returns a CFTypeRef of the property to be copied on success, otherwise NULL. * Caller is responsible for calling CFRelease on the property. */ CFTypeRef _Nullable IOHIDServiceClientCopyProperty(IOHIDServiceClientRef service, CFStringRef key); /*! * @function IOHIDServiceClientGetTypeID * * @result Returns the CFTypeID of the <code>IOHIDServiceClient</code> class. */ CFTypeID IOHIDServiceClientGetTypeID(void); /*! * @function IOHIDServiceClientGetRegistryID * * @param service the HID service to get the registry ID for. * * @result Returns a CFTypeRef containing the registry ID for the service. */ CFTypeRef IOHIDServiceClientGetRegistryID(IOHIDServiceClientRef service); /*! * @function IOHIDServiceClientConformsTo * * @abstract Determines if a HID service conforms to a specific usage page and usage. * * @param usagePage A usage page defined in <code>IOHIDUsageTables.h</code>. * * @param usage A usage defined in <code>IOHIDUsageTables.h</code>. * * @result Returns true if the service conforms to the provided usage page and usage. */ boolean_t IOHIDServiceClientConformsTo(IOHIDServiceClientRef service, uint32_t usagePage, uint32_t usage); CF_IMPLICIT_BRIDGING_DISABLED CF_ASSUME_NONNULL_END __END_DECLS #endif /* IOHIDServiceClient_h */
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/hidsystem/IOLLEvent.h
/* * @APPLE_LICENSE_HEADER_START@ * * Copyright (c) 1999-2009 Apple Computer, Inc. All Rights Reserved. * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this * file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_LICENSE_HEADER_END@ */ /****************************************************************************** event.h (PostScript side version) CONFIDENTIAL Copyright (c) 1988 NeXT, Inc. as an unpublished work. All Rights Reserved. Created Leo 01Mar88 Modified: 04May88 Leo Final event types and record 22Aug88 Leo Change short -> int for window, add reserved 26May90 Ted Added NX_UNDIMMASK to correct triggering of UndoAutoDim 12Dec91 Mike Brought into sync with dpsclient/event.h, and fixed the #ifndef interlock with dpsclient/event.h that was broken during the Great Header Revision. The PostScript version of this file differs from the Window Kit version in that the coordinates here are ints instead of floats. ******************************************************************************/ #ifndef _DEV_EVENT_H #define _DEV_EVENT_H #include <libkern/OSTypes.h> #include <IOKit/hidsystem/IOHIDTypes.h> #include <mach/mach_types.h> #ifdef EVENT_H /* Interlock with dpsclient/event.h */ #if !defined(_NXSIZE_) /* Work around patch for old event.h in Phase 3 projs*/ #define _NXSIZE_ 1 /* NXCoord, NXPoint, NXSize decl seen */ #define _NXSize_ NXSize #endif /* _NXSIZE_ */ #else /* EVENT_H */ /* Haven't seen dpsclient/event.h, so define away */ #define EVENT_H #ifdef KERNEL #else /* KERNEL */ #if !defined(_NXSIZE_) /* Work around patch for old event.h in Phase 3 projs*/ #define _NXSIZE_ 1 /* NXCoord, NXPoint, NXSize decl seen */ typedef float NXCoord; typedef struct _NXPoint { /* point */ NXCoord x, y; } NXPoint; typedef struct _NXSize { /* size */ NXCoord width, height; } NXSize; #define _NXSize_ NXSize /* Correct usage in event_status_driver.h */ #endif /* _NXSIZE_ */ #endif /* KERNEL */ /* Event types */ #define NX_NULLEVENT 0 /* internal use */ /* mouse events */ #define NX_LMOUSEDOWN 1 /* left mouse-down event */ #define NX_LMOUSEUP 2 /* left mouse-up event */ #define NX_RMOUSEDOWN 3 /* right mouse-down event */ #define NX_RMOUSEUP 4 /* right mouse-up event */ #define NX_MOUSEMOVED 5 /* mouse-moved event */ #define NX_LMOUSEDRAGGED 6 /* left mouse-dragged event */ #define NX_RMOUSEDRAGGED 7 /* right mouse-dragged event */ #define NX_MOUSEENTERED 8 /* mouse-entered event */ #define NX_MOUSEEXITED 9 /* mouse-exited event */ /* other mouse events * * event.data.mouse.buttonNumber should contain the * button number (2-31) changing state. */ #define NX_OMOUSEDOWN 25 /* other mouse-down event */ #define NX_OMOUSEUP 26 /* other mouse-up event */ #define NX_OMOUSEDRAGGED 27 /* other mouse-dragged event */ /* keyboard events */ #define NX_KEYDOWN 10 /* key-down event */ #define NX_KEYUP 11 /* key-up event */ #define NX_FLAGSCHANGED 12 /* flags-changed event */ /* composite events */ #define NX_KITDEFINED 13 /* application-kit-defined event */ #define NX_SYSDEFINED 14 /* system-defined event */ #define NX_APPDEFINED 15 /* application-defined event */ /* There are additional DPS client defined events past this point. */ /* Scroll wheel events */ #define NX_SCROLLWHEELMOVED 22 /* Zoom events */ #define NX_ZOOM 28 /* tablet events */ #define NX_TABLETPOINTER 23 /* for non-mousing transducers */ #define NX_TABLETPROXIMITY 24 /* for non-mousing transducers */ /* event range */ #define NX_FIRSTEVENT 0 #define NX_LASTEVENT 28 #define NX_NUMPROCS (NX_LASTEVENT-NX_FIRSTEVENT+1) /* Event masks */ #define NX_NULLEVENTMASK (1 << NX_NULLEVENT) /* NULL event */ #define NX_LMOUSEDOWNMASK (1 << NX_LMOUSEDOWN) /* left mouse-down */ #define NX_LMOUSEUPMASK (1 << NX_LMOUSEUP) /* left mouse-up */ #define NX_RMOUSEDOWNMASK (1 << NX_RMOUSEDOWN) /* right mouse-down */ #define NX_RMOUSEUPMASK (1 << NX_RMOUSEUP) /* right mouse-up */ #define NX_OMOUSEDOWNMASK (1 << NX_OMOUSEDOWN) /* other mouse-down */ #define NX_OMOUSEUPMASK (1 << NX_OMOUSEUP) /* other mouse-up */ #define NX_MOUSEMOVEDMASK (1 << NX_MOUSEMOVED) /* mouse-moved */ #define NX_LMOUSEDRAGGEDMASK (1 << NX_LMOUSEDRAGGED) /* left-dragged */ #define NX_RMOUSEDRAGGEDMASK (1 << NX_RMOUSEDRAGGED) /* right-dragged */ #define NX_OMOUSEDRAGGEDMASK (1 << NX_OMOUSEDRAGGED) /* other-dragged */ #define NX_MOUSEENTEREDMASK (1 << NX_MOUSEENTERED) /* mouse-entered */ #define NX_MOUSEEXITEDMASK (1 << NX_MOUSEEXITED) /* mouse-exited */ #define NX_KEYDOWNMASK (1 << NX_KEYDOWN) /* key-down */ #define NX_KEYUPMASK (1 << NX_KEYUP) /* key-up */ #define NX_FLAGSCHANGEDMASK (1 << NX_FLAGSCHANGED) /* flags-changed */ #define NX_KITDEFINEDMASK (1 << NX_KITDEFINED) /* kit-defined */ #define NX_SYSDEFINEDMASK (1 << NX_SYSDEFINED) /* system-defined */ #define NX_APPDEFINEDMASK (1 << NX_APPDEFINED) /* app-defined */ #define NX_SCROLLWHEELMOVEDMASK (1 << NX_SCROLLWHEELMOVED) /* scroll wheel moved */ #define NX_ZOOMMASK (1 << NX_ZOOM) /* Zoom */ #define NX_TABLETPOINTERMASK (1 << NX_TABLETPOINTER) /* tablet pointer moved */ #define NX_TABLETPROXIMITYMASK (1 << NX_TABLETPROXIMITY) /* tablet pointer proximity */ #define EventCodeMask(type) (1 << (type)) #define NX_ALLEVENTS -1 /* Check for all events */ /* sub types for mouse and move events */ #define NX_SUBTYPE_DEFAULT 0 #define NX_SUBTYPE_TABLET_POINT 1 #define NX_SUBTYPE_TABLET_PROXIMITY 2 #define NX_SUBTYPE_MOUSE_TOUCH 3 /* sub types for system defined events */ #define NX_SUBTYPE_POWER_KEY 1 #define NX_SUBTYPE_AUX_MOUSE_BUTTONS 7 /* * NX_SUBTYPE_AUX_CONTROL_BUTTONS usage * * The incoming NXEvent for other mouse button down/up has event.type * NX_SYSDEFINED and event.data.compound.subtype NX_SUBTYPE_AUX_MOUSE_BUTTONS. * Within the event.data.compound.misc.L[0] contains bits for all the buttons * that have changed state, and event.data.compound.misc.L[1] contains the * current button state as a bitmask, with 1 representing down, and 0 * representing up. Bit 0 is the left button, bit one is the right button, * bit 2 is the center button and so forth. */ #define NX_SUBTYPE_AUX_CONTROL_BUTTONS 8 #define NX_SUBTYPE_EJECT_KEY 10 #define NX_SUBTYPE_SLEEP_EVENT 11 #define NX_SUBTYPE_RESTART_EVENT 12 #define NX_SUBTYPE_SHUTDOWN_EVENT 13 #define NX_SUBTYPE_MENU 16 #define NX_SUBTYPE_ACCESSIBILITY 17 #define NX_SUBTYPE_STICKYKEYS_ON 100 #define NX_SUBTYPE_STICKYKEYS_OFF 101 #define NX_SUBTYPE_STICKYKEYS_SHIFT 102 #define NX_SUBTYPE_STICKYKEYS_CONTROL 103 #define NX_SUBTYPE_STICKYKEYS_ALTERNATE 104 #define NX_SUBTYPE_STICKYKEYS_COMMAND 105 #define NX_SUBTYPE_STICKYKEYS_RELEASE 106 #define NX_SUBTYPE_STICKYKEYS_TOGGLEMOUSEDRIVING 107 // New stickykeys key events // These were created to send an event describing the // different state of the modifiers #define NX_SUBTYPE_STICKYKEYS_SHIFT_DOWN 110 #define NX_SUBTYPE_STICKYKEYS_CONTROL_DOWN 111 #define NX_SUBTYPE_STICKYKEYS_ALTERNATE_DOWN 112 #define NX_SUBTYPE_STICKYKEYS_COMMAND_DOWN 113 #define NX_SUBTYPE_STICKYKEYS_FN_DOWN 114 #define NX_SUBTYPE_STICKYKEYS_SHIFT_LOCK 120 #define NX_SUBTYPE_STICKYKEYS_CONTROL_LOCK 121 #define NX_SUBTYPE_STICKYKEYS_ALTERNATE_LOCK 122 #define NX_SUBTYPE_STICKYKEYS_COMMAND_LOCK 123 #define NX_SUBTYPE_STICKYKEYS_FN_LOCK 124 #define NX_SUBTYPE_STICKYKEYS_SHIFT_UP 130 #define NX_SUBTYPE_STICKYKEYS_CONTROL_UP 131 #define NX_SUBTYPE_STICKYKEYS_ALTERNATE_UP 132 #define NX_SUBTYPE_STICKYKEYS_COMMAND_UP 133 #define NX_SUBTYPE_STICKYKEYS_FN_UP 134 // SlowKeys #define NX_SUBTYPE_SLOWKEYS_START 200 #define NX_SUBTYPE_SLOWKEYS_ABORT 201 #define NX_SUBTYPE_SLOWKEYS_END 202 // HID Parameter Property Modified #define NX_SUBTYPE_HIDPARAMETER_MODIFIED 210 /* Masks for the bits in event.flags */ /* device-independent */ #define NX_ALPHASHIFTMASK 0x00010000 #define NX_SHIFTMASK 0x00020000 #define NX_CONTROLMASK 0x00040000 #define NX_ALTERNATEMASK 0x00080000 #define NX_COMMANDMASK 0x00100000 #define NX_NUMERICPADMASK 0x00200000 #define NX_HELPMASK 0x00400000 #define NX_SECONDARYFNMASK 0x00800000 #define NX_ALPHASHIFT_STATELESS_MASK 0x01000000 /* device-dependent (really?) */ #define NX_DEVICELCTLKEYMASK 0x00000001 #define NX_DEVICELSHIFTKEYMASK 0x00000002 #define NX_DEVICERSHIFTKEYMASK 0x00000004 #define NX_DEVICELCMDKEYMASK 0x00000008 #define NX_DEVICERCMDKEYMASK 0x00000010 #define NX_DEVICELALTKEYMASK 0x00000020 #define NX_DEVICERALTKEYMASK 0x00000040 #define NX_DEVICE_ALPHASHIFT_STATELESS_MASK 0x00000080 #define NX_DEVICERCTLKEYMASK 0x00002000 /* * Additional reserved bits in event.flags */ #define NX_STYLUSPROXIMITYMASK 0x00000080 /* deprecated */ #define NX_NONCOALSESCEDMASK 0x00000100 /* click state values * If you have the following events in close succession, the click * field has the indicated value: * * Event Click Value Comments * mouse-down 1 Not part of any click yet * mouse-up 1 Aha! A click! * mouse-down 2 Doing a double-click * mouse-up 2 It's finished * mouse-down 3 A triple * mouse-up 3 */ /* Values for the character set in event.data.key.charSet */ #define NX_ASCIISET 0 #define NX_SYMBOLSET 1 #define NX_DINGBATSSET 2 /* tablet button masks * Mask bits for the tablet barrel buttons placed in tablet.buttons. * The buttons field uses adopts the following convention: * * Bit Comments * 0 Left Mouse Button ( kHIDUsage_Button_1 ) * 1 Right Mouse Button ( kHIDUsage_Button_2 ) * 2 Middle Mouse Button ( kHIDUsage_Button_3 ) * 3 4th Mouse Button ( kHIDUsage_Button_4 ) * ... * 15 15th Mouse Button * * For your convenience, the following mask bits have been defined * for tablet specific application: */ #define NX_TABLET_BUTTON_PENTIPMASK 0x0001 #define NX_TABLET_BUTTON_PENLOWERSIDEMASK 0x0002 #define NX_TABLET_BUTTON_PENUPPERSIDEMASK 0x0004 /* tablet capability masks * Mask bits for the tablet capabilities field. Use these * masks with the capabilities field of a proximity event to * determine what fields in a Tablet Event are valid for this * device. */ #define NX_TABLET_CAPABILITY_DEVICEIDMASK 0x0001 #define NX_TABLET_CAPABILITY_ABSXMASK 0x0002 #define NX_TABLET_CAPABILITY_ABSYMASK 0x0004 #define NX_TABLET_CAPABILITY_VENDOR1MASK 0x0008 #define NX_TABLET_CAPABILITY_VENDOR2MASK 0x0010 #define NX_TABLET_CAPABILITY_VENDOR3MASK 0x0020 #define NX_TABLET_CAPABILITY_BUTTONSMASK 0x0040 #define NX_TABLET_CAPABILITY_TILTXMASK 0x0080 #define NX_TABLET_CAPABILITY_TILTYMASK 0x0100 #define NX_TABLET_CAPABILITY_ABSZMASK 0x0200 #define NX_TABLET_CAPABILITY_PRESSUREMASK 0x0400 #define NX_TABLET_CAPABILITY_TANGENTIALPRESSUREMASK 0x0800 #define NX_TABLET_CAPABILITY_ORIENTINFOMASK 0x1000 #define NX_TABLET_CAPABILITY_ROTATIONMASK 0x2000 /* proximity pointer types * Value that describes the type of pointing device placed in * proximity.pointerType. */ #define NX_TABLET_POINTER_UNKNOWN 0 #define NX_TABLET_POINTER_PEN 1 #define NX_TABLET_POINTER_CURSOR 2 #define NX_TABLET_POINTER_ERASER 3 /* TabletPointData type: defines the tablet data for points included * in mouse events created by a tablet driver. */ typedef struct _NXTabletPointData { SInt32 x; /* absolute x coordinate in tablet space at full tablet resolution */ SInt32 y; /* absolute y coordinate in tablet space at full tablet resolution */ SInt32 z; /* absolute z coordinate in tablet space at full tablet resolution */ UInt16 buttons; /* one bit per button - bit 0 is first button - 1 = closed */ UInt16 pressure; /* scaled pressure value; MAX=(2^16)-1, MIN=0 */ struct { /* tilt range is -((2^15)-1) to (2^15)-1 (-32767 to 32767) */ SInt16 x; /* scaled tilt x value */ SInt16 y; /* scaled tilt y value */ } tilt; UInt16 rotation; /* Fixed-point representation of device rotation in a 10.6 format */ SInt16 tangentialPressure; /* tangential pressure on the device; same range as tilt */ UInt16 deviceID; /* system-assigned unique device ID */ SInt16 vendor1; /* vendor-defined signed 16-bit integer */ SInt16 vendor2; /* vendor-defined signed 16-bit integer */ SInt16 vendor3; /* vendor-defined signed 16-bit integer */ } NXTabletPointData, *NXTabletPointDataPtr; /* TabletProximityData type: defines the tablet data for proximity * events included in mouse events created by a tablet driver. */ typedef struct _NXTabletProximityData { UInt16 vendorID; /* vendor-defined ID - typically the USB vendor ID */ UInt16 tabletID; /* vendor-defined tablet ID - typically the USB product ID */ UInt16 pointerID; /* vendor-defined ID of the specific pointing device */ UInt16 deviceID; /* system-assigned unique device ID */ UInt16 systemTabletID; /* system-assigned unique tablet ID */ UInt16 vendorPointerType; /* vendor-defined pointer type */ UInt32 pointerSerialNumber; /* vendor-defined serial number */ UInt64 uniqueID __attribute__ ((packed)); /* vendor-defined unique ID */ UInt32 capabilityMask; /* capabilities mask of the device */ UInt8 pointerType; /* type of pointing device */ UInt8 enterProximity; /* non-zero = entering; zero = leaving */ SInt16 reserved1; } NXTabletProximityData, *NXTabletProximityDataPtr; /* EventData type: defines the data field of an event */ typedef union { struct { /* For mouse-down and mouse-up events */ UInt8 subx; /* sub-pixel position for x */ UInt8 suby; /* sub-pixel position for y */ SInt16 eventNum; /* unique identifier for this button */ SInt32 click; /* click state of this event */ UInt8 pressure; /* pressure value: 0=none, 255=full */ UInt8 buttonNumber;/* button generating other button event (0-31) */ UInt8 subType; UInt8 reserved2; SInt32 reserved3; union { NXTabletPointData point; /* tablet point data */ NXTabletProximityData proximity; /* tablet proximity data */ } tablet; } mouse; struct { SInt32 dx; SInt32 dy; UInt8 subx; UInt8 suby; UInt8 subType; UInt8 reserved1; SInt32 reserved2; union { NXTabletPointData point; /* tablet point data */ NXTabletProximityData proximity; /* tablet proximity data */ } tablet; } mouseMove; struct { /* For key-down and key-up events */ UInt16 origCharSet; /* unmodified character set code */ SInt16 repeat; /* for key-down: nonzero if really a repeat */ UInt16 charSet; /* character set code */ UInt16 charCode; /* character code in that set */ UInt16 keyCode; /* device-dependent key number */ UInt16 origCharCode; /* unmodified character code */ SInt32 reserved1; UInt32 keyboardType; SInt32 reserved2; SInt32 reserved3; SInt32 reserved4; SInt32 reserved5[4]; } key; struct { /* For mouse-entered and mouse-exited events */ SInt16 reserved; SInt16 eventNum; /* unique identifier from mouse down event */ SInt32 trackingNum; /* unique identifier from settrackingrect */ SInt32 userData; /* uninterpreted integer from settrackingrect */ SInt32 reserved1; SInt32 reserved2; SInt32 reserved3; SInt32 reserved4; SInt32 reserved5; SInt32 reserved6[4]; } tracking; struct { SInt16 deltaAxis1; SInt16 deltaAxis2; SInt16 deltaAxis3; SInt16 reserved1; SInt32 fixedDeltaAxis1; SInt32 fixedDeltaAxis2; SInt32 fixedDeltaAxis3; SInt32 pointDeltaAxis1; SInt32 pointDeltaAxis2; SInt32 pointDeltaAxis3; SInt32 reserved8[4]; } scrollWheel, zoom; struct { /* For window-changed, sys-defined, and app-defined events */ SInt16 reserved; SInt16 subType; /* event subtype for compound events */ union { float F[11]; /* for use in compound events */ SInt32 L[11]; /* for use in compound events */ SInt16 S[22]; /* for use in compound events */ char C[44]; /* for use in compound events */ } misc; } compound; struct { SInt32 x; /* absolute x coordinate in tablet space at full tablet resolution */ SInt32 y; /* absolute y coordinate in tablet space at full tablet resolution */ SInt32 z; /* absolute z coordinate in tablet space at full tablet resolution */ UInt16 buttons; /* one bit per button - bit 0 is first button - 1 = closed */ UInt16 pressure; /* scaled pressure value; MAX=(2^16)-1, MIN=0 */ struct { /* tilt range is -((2^15)-1) to (2^15)-1 (-32767 to 32767) */ SInt16 x; /* scaled tilt x value */ SInt16 y; /* scaled tilt y value */ } tilt; UInt16 rotation; /* Fixed-point representation of device rotation in a 10.6 format */ SInt16 tangentialPressure; /* tangential pressure on the device; same range as tilt */ UInt16 deviceID; /* system-assigned unique device ID */ SInt16 vendor1; /* vendor-defined signed 16-bit integer */ SInt16 vendor2; /* vendor-defined signed 16-bit integer */ SInt16 vendor3; /* vendor-defined signed 16-bit integer */ SInt32 reserved[4]; } tablet; struct { UInt16 vendorID; /* vendor-defined ID - typically the USB vendor ID */ UInt16 tabletID; /* vendor-defined tablet ID - typically the USB product ID */ UInt16 pointerID; /* vendor-defined ID of the specific pointing device */ UInt16 deviceID; /* system-assigned unique device ID */ UInt16 systemTabletID; /* system-assigned unique tablet ID */ UInt16 vendorPointerType; /* vendor-defined pointer type */ UInt32 pointerSerialNumber; /* vendor-defined serial number */ UInt64 uniqueID __attribute__ ((packed)); /* vendor-defined unique ID */ UInt32 capabilityMask; /* capabilities mask of the device */ UInt8 pointerType; /* type of pointing device */ UInt8 enterProximity; /* non-zero = entering; zero = leaving */ SInt16 reserved1; SInt32 reserved2[4]; } proximity; } NXEventData; /* The current version number of the NXEventData structure. */ #define kNXEventDataVersion 2 /* Finally! The event record! */ #ifndef __ppc__ typedef struct _NXEvent { SInt32 type; /* An event type from above */ struct { SInt32 x, y; /* Base coordinates in window, */ } location; /* from bottom left */ UInt64 time __attribute__ ((packed)); /* time since launch */ SInt32 flags; /* key state flags */ UInt32 window; /* window number of assigned window */ UInt64 service_id __attribute__ ((packed)); /* service id */ SInt32 ext_pid; /* external pid */ NXEventData data; /* type-dependent data */ } NXEvent, *NXEventPtr; #else typedef struct _NXEvent { SInt32 type; /* An event type from above */ struct { SInt32 x, y; /* Base coordinates in window, */ } location; /* from bottom left */ UInt64 time __attribute__ ((packed)); /* time since launch */ SInt32 flags; /* key state flags */ UInt32 window; /* window number of assigned window */ NXEventData data; /* type-dependent data */ UInt64 service_id __attribute__ ((packed)); /* service id */ SInt32 ext_pid; /* external pid */ } NXEvent, *NXEventPtr; #endif /* The current version number of the NXEvent structure. */ #define kNXEventVersion 2 /* How to pick window(s) for event (for PostEvent) */ #define NX_NOWINDOW -1 #define NX_BYTYPE 0 #define NX_BROADCAST 1 #define NX_TOPWINDOW 2 #define NX_FIRSTWINDOW 3 #define NX_MOUSEWINDOW 4 #define NX_NEXTWINDOW 5 #define NX_LASTLEFT 6 #define NX_LASTRIGHT 7 #define NX_LASTKEY 8 #define NX_EXPLICIT 9 #define NX_TRANSMIT 10 #define NX_BYPSCONTEXT 11 #endif /* EVENT_H */ /* End of defs common with dpsclient/event.h */ /* Mask of events that cause the screen to wake up */ #define NX_WAKEMASK ( NX_KEYDOWNMASK | NX_FLAGSCHANGEDMASK | \ NX_LMOUSEDOWNMASK | NX_LMOUSEUPMASK | \ NX_RMOUSEDOWNMASK | NX_RMOUSEUPMASK | \ NX_OMOUSEDOWNMASK | NX_OMOUSEUPMASK \ ) /* Mask of events that cause screen to undim */ #define NX_UNDIMMASK ( NX_WAKEMASK | NX_KEYUPMASK | NX_SCROLLWHEELMOVEDMASK | \ NX_LMOUSEDRAGGEDMASK | NX_RMOUSEDRAGGEDMASK | NX_OMOUSEDRAGGEDMASK | \ NX_MOUSEMOVEDMASK | NX_MOUSEENTEREDMASK | NX_MOUSEEXITEDMASK | \ NX_TABLETPOINTERMASK | NX_TABLETPROXIMITYMASK \ ) #define NX_EVENT_EXTENSION_LOCATION_INVALID 0x1 #define NX_EVENT_EXTENSION_LOCATION_TYPE_FLOAT 0x2 #define NX_EVENT_EXTENSION_LOCATION_DEVICE_SCALED 0x4 #define NX_EVENT_EXTENSION_MOUSE_DELTA_TYPE_FLOAT 0x8 #define NX_EVENT_EXTENSION_AUDIT_TOKEN 0x10 typedef struct _NXEventExtension { UInt32 flags; audit_token_t audit; } NXEventExtension; typedef struct _NXEventExt { NXEvent payload; NXEventExtension extension; } NXEventExt; #endif /* !_DEV_EVENT_H */
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/hidsystem/IOHIDTypes.h
/* * @APPLE_LICENSE_HEADER_START@ * * Copyright (c) 1999-2003 Apple Computer, Inc. All Rights Reserved. * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this * file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_LICENSE_HEADER_END@ */ /****************************************************************************** ev_types.h Data types for the events status driver. This file contains public API. mpaque 11Oct91 Copyright 1991 NeXT Computer, Inc. Copyright 1997-2011 Apple, Inc. Modified: ******************************************************************************/ #ifndef _DEV_EV_TYPES_H #define _DEV_EV_TYPES_H #include <mach/boolean.h> #include <libkern/OSAtomic.h> #include <IOKit/graphics/IOGraphicsTypes.h> // This should be removed, but is being used by others // <rdar://problem/8917741> IOHIDFamily-355 causes projects to fail to build with 'ev_lock_data_t' does not name a type #include <IOKit/IOSharedLock.h> /* Shared memory versions */ #define EVENT_SYSTEM_VERSION 2 /* Maximum length of SetMouseScaling arrays */ #define NX_MAXMOUSESCALINGS 20 typedef struct evsioKeymapping /* Match old struct names in kernel */ { int size; char *mapping; } NXKeyMapping; typedef struct evsioMouseScaling /* Match old struct names in kernel */ { int numScaleLevels; short scaleThresholds[NX_MAXMOUSESCALINGS]; short scaleFactors[NX_MAXMOUSESCALINGS]; } NXMouseScaling; typedef enum { NX_OneButton, NX_LeftButton, NX_RightButton } NXMouseButton; // IOFixedPoint32 is a 24.8 format typedef struct __IOFixedPoint32 { int32_t x; int32_t y; } IOFixedPoint32; /* * NXEventSystemInfo() information structures. These are designed to * allow for expansion. * * The current implementation of NXEventSystemInfo() uses an ioctl call. * THIS WILL CHANGE. */ /* * Generic query max size and typedefs. * * The maximum size is selected to support anticipated future extensions * of request flavors. Certain flavors planned for future releases may * require roughtly 800 ints to represent. We allow a little extra, in * case further growth is needed. */ typedef int *NXEventSystemInfoType; #define NX_EVS_INFO_MAX (1024) /* Max array size */ typedef int NXEventSystemInfoData[NX_EVS_INFO_MAX]; /* Event System Devices query */ #define NX_EVS_DEVICE_MAX 16 /* Interface types */ #define NX_EVS_DEVICE_INTERFACE_OTHER 0 #define NX_EVS_DEVICE_INTERFACE_NeXT 1 // NeXT custom, in older sys #define NX_EVS_DEVICE_INTERFACE_ADB 2 // NeXT/fruit keybds/mice #define NX_EVS_DEVICE_INTERFACE_ACE 3 // For x86 PC keyboards #define NX_EVS_DEVICE_INTERFACE_SERIAL_ACE 4 // For PC serial mice #define NX_EVS_DEVICE_INTERFACE_BUS_ACE 5 // For PC bus mice #define NX_EVS_DEVICE_INTERFACE_HIL 6 // For HIL hp keyboard #define NX_EVS_DEVICE_INTERFACE_TYPE5 7 // For Sun Type5 keyboard /* * Note! if any new interface types are added above, the following * definition of the number of interfaces supported must reflect this. * This is used in the libkeymap project (storemap.c module) which needs * to be cognizant of the number of new devices coming online * via support for heterogeneous architecture platforms. * e.g., PCs, HP's HIL, Sun's Type5 keyboard,... */ #define NUM_SUPPORTED_INTERFACES (NX_EVS_DEVICE_INTERFACE_TYPE5 + 1) // Other, NeXT, ADB, ACE,... /* Device types */ #define NX_EVS_DEVICE_TYPE_OTHER 0 #define NX_EVS_DEVICE_TYPE_KEYBOARD 1 #define NX_EVS_DEVICE_TYPE_MOUSE 2 // Relative position devices #define NX_EVS_DEVICE_TYPE_TABLET 3 // Absolute position devices typedef struct { int interface; /* NeXT, ADB, other */ int interface_addr; /* Device address on the interface */ int dev_type; /* Keyboard, mouse, tablet, other */ int id; /* manufacturer's device handler ID */ } NXEventSystemDevice; typedef struct { NXEventSystemDevice dev[NX_EVS_DEVICE_MAX]; } NXEventSystemDeviceList; #define __OLD_NX_EVS_DEVICE_INFO 1 #define NX_EVS_DEVICE_INFO "Evs_EventDeviceInfo" #define NX_EVS_DEVICE_INFO_COUNT \ (sizeof (NXEventSystemDeviceList) / sizeof (int)) /* * Types used in evScreen protocol compliant operations. */ typedef enum {EVNOP, EVHIDE, EVSHOW, EVMOVE, EVLEVEL} EvCmd; /* Cursor state */ #define EV_SCREEN_MIN_BRIGHTNESS 0 #define EV_SCREEN_MAX_BRIGHTNESS 64 /* Scale should lie between MIN_BRIGHTNESS and MAX_BRIGHTNESS */ #define EV_SCALE_BRIGHTNESS( scale, datum ) \ ((((UInt32)(datum))*((UInt32)scale)) >> 6) /* * Definition of a tick, as a time in milliseconds. This controls how * often the event system periodic jobs are run. All actual tick times * are derived from the nanosecond timer. These values are typically used * as part of computing mouse velocity for acceleration purposes. */ #define EV_TICK_TIME 16 /* 16 milliseconds */ #define EV_TICKS_PER_SEC (1000/EV_TICK_TIME) /* ~ 62 Hz */ /* Mouse Button bits, as passed from an EventSrc to the Event Driver */ #define EV_RB (0x01) #define EV_LB (0x04) #define EV_MOUSEBUTTONMASK (EV_LB | EV_RB) /* Tablet Pressure Constants, as passed from an EventSrc to the Event Driver */ #define EV_MINPRESSURE 0 #define EV_MAXPRESSURE 255 /* Cursor size in pixels */ #define EV_CURSOR_WIDTH 16 #define EV_CURSOR_HEIGHT 16 #define kAppleOnboardGUID 0x0610000000000000ULL #endif /* !_DEV_EV_TYPES_H */
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/hidsystem/ev_keymap.h
/* * @APPLE_LICENSE_HEADER_START@ * * Copyright (c) 1999-2003 Apple Computer, Inc. All Rights Reserved. * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this * file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_LICENSE_HEADER_END@ */ /* Copyright (c) 1992 NeXT Computer, Inc. All rights reserved. * * ev_keymap.h * Defines the structure used for parsing keymappings. These structures * and definitions are used by event sources in the kernel and by * applications and utilities which manipulate keymaps. * * HISTORY * 02-Jun-1992 Mike Paquette at NeXT * Created. */ #ifndef _DEV_EV_KEYMAP_H #define _DEV_EV_KEYMAP_H #define NX_NUMKEYCODES 256 /* Highest key code is 0xff. ADB used to use 0x80 for keydown state, but who the heck uses adb anymore. */ #define NX_NUMSEQUENCES 128 /* Maximum possible number of sequences */ #define NX_NUMMODIFIERS 16 /* Maximum number of modifier bits */ #define NX_BYTE_CODES 0 /* If first short 0, all are bytes (else shorts) */ #define NX_WHICHMODMASK 0x0f /* bits out of keyBits for bucky bits */ #define NX_MODMASK 0x10 /* Bit out of keyBits indicates modifier bit */ #define NX_CHARGENMASK 0x20 /* bit out of keyBits for char gen */ #define NX_SPECIALKEYMASK 0x40 /* bit out of keyBits for specialty key */ #define NX_KEYSTATEMASK 0x80 /* OBSOLETE - DO NOT USE IN NEW DESIGNS */ /* * Special keys currently known to and understood by the system. * If new specialty keys are invented, extend this list as appropriate. * The presence of these keys in a particular implementation is not * guaranteed. */ #define NX_NOSPECIALKEY 0xFFFF #define NX_KEYTYPE_SOUND_UP 0 #define NX_KEYTYPE_SOUND_DOWN 1 #define NX_KEYTYPE_BRIGHTNESS_UP 2 #define NX_KEYTYPE_BRIGHTNESS_DOWN 3 #define NX_KEYTYPE_CAPS_LOCK 4 #define NX_KEYTYPE_HELP 5 #define NX_POWER_KEY 6 #define NX_KEYTYPE_MUTE 7 #define NX_UP_ARROW_KEY 8 #define NX_DOWN_ARROW_KEY 9 #define NX_KEYTYPE_NUM_LOCK 10 #define NX_KEYTYPE_CONTRAST_UP 11 #define NX_KEYTYPE_CONTRAST_DOWN 12 #define NX_KEYTYPE_LAUNCH_PANEL 13 #define NX_KEYTYPE_EJECT 14 #define NX_KEYTYPE_VIDMIRROR 15 #define NX_KEYTYPE_PLAY 16 #define NX_KEYTYPE_NEXT 17 #define NX_KEYTYPE_PREVIOUS 18 #define NX_KEYTYPE_FAST 19 #define NX_KEYTYPE_REWIND 20 #define NX_KEYTYPE_ILLUMINATION_UP 21 #define NX_KEYTYPE_ILLUMINATION_DOWN 22 #define NX_KEYTYPE_ILLUMINATION_TOGGLE 23 #define NX_NUMSPECIALKEYS 24 /* Maximum number of special keys */ #define NX_NUM_SCANNED_SPECIALKEYS 24 /* First 24 special keys are */ /* actively scanned in kernel */ #define NX_KEYTYPE_MENU 25 /* Mask of special keys that are posted as events */ #define NX_SPECIALKEY_POST_MASK \ ((1 << NX_KEYTYPE_SOUND_UP) | (1 << NX_KEYTYPE_SOUND_DOWN) | \ (1 << NX_POWER_KEY) | (1 << NX_KEYTYPE_MUTE) | \ (1 << NX_KEYTYPE_BRIGHTNESS_UP) | (1 << NX_KEYTYPE_BRIGHTNESS_DOWN) | \ (1 << NX_KEYTYPE_CONTRAST_UP) | (1 << NX_KEYTYPE_CONTRAST_UP) | \ (1 << NX_KEYTYPE_LAUNCH_PANEL) | (1 << NX_KEYTYPE_EJECT) | \ (1 << NX_KEYTYPE_VIDMIRROR) | (1 << NX_KEYTYPE_PLAY) | \ (1 << NX_KEYTYPE_NEXT) | (1 << NX_KEYTYPE_PREVIOUS) | \ (1 << NX_KEYTYPE_FAST) | (1 << NX_KEYTYPE_REWIND) | \ (1 << NX_KEYTYPE_ILLUMINATION_UP) | \ (1 << NX_KEYTYPE_ILLUMINATION_DOWN) | \ (1 << NX_KEYTYPE_ILLUMINATION_TOGGLE) | 0) /* Modifier key indices into modDefs[] */ #define NX_MODIFIERKEY_ALPHALOCK 0 #define NX_MODIFIERKEY_SHIFT 1 #define NX_MODIFIERKEY_CONTROL 2 #define NX_MODIFIERKEY_ALTERNATE 3 #define NX_MODIFIERKEY_COMMAND 4 #define NX_MODIFIERKEY_NUMERICPAD 5 #define NX_MODIFIERKEY_HELP 6 #define NX_MODIFIERKEY_SECONDARYFN 7 #define NX_MODIFIERKEY_NUMLOCK 8 /* support for right hand modifier */ #define NX_MODIFIERKEY_RSHIFT 9 #define NX_MODIFIERKEY_RCONTROL 10 #define NX_MODIFIERKEY_RALTERNATE 11 #define NX_MODIFIERKEY_RCOMMAND 12 #define NX_MODIFIERKEY_ALPHALOCK_STATELESS 13 #define NX_MODIFIERKEY_LAST_KEY 13 typedef struct _NXParsedKeyMapping_ { /* If nonzero, all numbers are shorts; if zero, all numbers are bytes*/ short shorts; /* * For each keycode, low order bit says if the key * generates characters. * High order bit says if the key is assigned to a modifier bit. * The second to low order bit gives the current state of the key. */ char keyBits[NX_NUMKEYCODES]; /* Bit number of highest numbered modifier bit */ int maxMod; /* Pointers to where the list of keys for each modifiers bit begins, * or NULL. */ unsigned char *modDefs[NX_NUMMODIFIERS]; /* Key code of highest key deinfed to generate characters */ int numDefs; /* Pointer into the keyMapping where this key's definitions begin */ unsigned char *keyDefs[NX_NUMKEYCODES]; /* number of sequence definitions */ int numSeqs; /* pointers to sequences */ unsigned char *seqDefs[NX_NUMSEQUENCES]; /* Special key definitions */ int numSpecialKeys; /* Special key values, or 0xFFFF if none */ unsigned short specialKeys[NX_NUMSPECIALKEYS]; /* Pointer to the original keymapping string */ const unsigned char *mapping; /* Length of the original string */ int mappingLen; } NXParsedKeyMapping; #endif /* !_DEV_EV_KEYMAP_H */
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/hidsystem/IOHIDShared.h
/* * @APPLE_LICENSE_HEADER_START@ * * Copyright (c) 1999-2011 Apple Computer, Inc. All Rights Reserved. * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this * file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_LICENSE_HEADER_END@ */ #ifndef _DEV_EVIO_H #define _DEV_EVIO_H #include <sys/cdefs.h> __BEGIN_DECLS #if KERNEL #include <IOKit/system.h> #else /* !KERNEL */ #include <mach/message.h> #include <IOKit/IOKitLib.h> #endif /* KERNEL */ #include <IOKit/IOReturn.h> #include <IOKit/graphics/IOGraphicsTypes.h> #include <IOKit/hidsystem/IOHIDTypes.h> #include <IOKit/hidsystem/IOLLEvent.h> /* * Identify this driver as one that uses the new driverkit and messaging API */ #ifndef _NeXT_MACH_EVENT_DRIVER_ #define _NeXT_MACH_EVENT_DRIVER_ (1) #endif /* _NeXT_MACH_EVENT_DRIVER_ */ /* Pressure Constants */ #define MINPRESSURE EV_MINPRESSURE #define MAXPRESSURE EV_MAXPRESSURE #define LLEQSIZE 240 /* Entries in low-level event queue */ typedef struct _NXEQElStruct { int next; /* Slot of lleq for next event */ OSSpinLock sema; /* Is high-level code reading this event now? */ NXEvent event; /* The event itself */ } NXEQElement; /****************************************************************************** SHARED MEMORY OVERVIEW PERSPECTIVE The ev driver and PostScript share at least one page of wired memory. This memory contains the low-level event queue which ev deposits events into and PostScript reads events from. Also, this memory contains other important data such as wait cursor state and some general cursor state. This memory is critical for speed. That is, we avoid having to make system calls for common operations. SHARED MEMORY REGIONS There are currently three "regions" or "zones" delineated within this shared memory. The first zone is the EvOffsets structure. This structure contains two offsets from the beginning of shared memory. The first offset is to the second zone, EvGlobals. The second offset is to the third zone, private shmem for drivers. INITIALIZATION OF SHARED MEMORY When the WindowServer starts up, it finds all screens that will be active. It then opens the ev driver and calls the EVIOSSCR ioctl repeatedly for each screen in use. This lets the ev driver set up the evScreen array and fill in each element. This ioctl also returns to PostScript a running total shared memory size with which to allocate. PostScript then allocates a region of memory this size and calls evmmap to "map in" this shared region. Evmmap initializes and fills in the EvOffsets and EvGlobals. Next the WindowServer calls each screen in turn to register itself with the ev driver in the same sequence as presented to EVIOSSCR. Each screen driver calls ev_register_screen() which among other things allocates a part of the private shmem (of the third shared memory zone) for the driver. DEBUGGING NOTES You can easily display and set this shared memory from kgdb, but usually cannot do so from within PostScript. Gdb (or some weird interaction between gdb and the os) chokes on this shmem. So if you read or write this area of memory, copy-on-write will occur and you'll get a completely new page for PostScript. This will render the shared memory scheme useless and you will have to restart PostScript. It was my understanding that before, we were able to "read" this area from PS, but not write to it (the idea behind copy-on-WRITE). However, this seems to be broken in 2.0. We think this is a kernel bug. ******************************************************************************/ typedef volatile struct _evOffsets { int evGlobalsOffset; /* Offset to EvGlobals structure */ int evShmemOffset; /* Offset to private shmem regions */ } EvOffsets; /****************************************************************************** EvGlobals This structures defines the portion of the events driver data structure that is exported to the PostScript server. It contains the event queue which is in memory shared between the driver and the PostScript server. All the variables necessary to read and process events from the queue are contained here. ******************************************************************************/ typedef volatile struct _evGlobals { OSSpinLock cursorSema; /* set to disable periodic code */ int eNum; /* Unique id for mouse events */ int buttons; /* State of the mouse buttons 1==down, 0==up */ int eventFlags; /* The current value of event.flags */ int VertRetraceClock; /* The current value of event.time */ IOGPoint cursorLoc; /* The current location of the cursor, in desktop coordinates */ int frame; /* current cursor frame */ IOGBounds workBounds; /* bounding box of all screens */ IOGBounds mouseRect; /* Rect for mouse-exited events */ int version; /* for run time checks */ int structSize; /* for run time checks */ int lastFrame; /* The current location of the cursor, 24.8 bit fixed point format */ IOFixedPoint32 screenCursorFixed; /* in Screen coordinates */ IOFixedPoint32 desktopCursorFixed;/* in Desktop coordinates */ unsigned int reservedA[27]; unsigned reserved:25; unsigned updateCursorPositionFromFixed:1; /* if this is set, IOHIDSystem will take any cursor position updates from desktopCursorFixed instead of cursorLoc */ unsigned logCursorUpdates:1; /* log cursor updates */ unsigned wantPressure:1; /* pressure in current mouseRect? */ unsigned wantPrecision:1; /* precise coordinates in current mouseRect? */ unsigned dontWantCoalesce:1; /* coalesce within the current mouseRect? */ unsigned dontCoalesce:1; /* actual flag which determines coalescing */ unsigned mouseRectValid:1; /* If nonzero, post a mouse-exited whenever mouse outside mouseRect. */ int movedMask; /* This contains an event mask for the three events MOUSEMOVED, LMOUSEDRAGGED, and RMOUSEDRAGGED. It says whether driver should generate those events. */ OSSpinLock waitCursorSema; /* protects wait cursor fields */ int AALastEventSent; /* timestamp for wait cursor */ int AALastEventConsumed; /* timestamp for wait cursor */ int waitCursorUp; /* Is wait cursor up? */ char ctxtTimedOut; /* Has wait cursor timer expired? */ char waitCursorEnabled; /* Play wait cursor game (per ctxt)? */ char globalWaitCursorEnabled; /* Play wait cursor game (global)? */ int waitThreshold; /* time before wait cursor appears */ int LLEHead; /* The next event to be read */ int LLETail; /* Where the next event will go */ int LLELast; /* The last event entered */ NXEQElement lleq[LLEQSIZE]; /* The event queue itself */ } EvGlobals; /* These evio structs are used in various calls supported by the ev driver. */ struct evioLLEvent { int setCursor; int type; IOGPoint location; NXEventData data; int setFlags; int flags; }; typedef struct evioLLEvent _NXLLEvent; #ifdef mach3xxx /* * On a keypress of a VOL UP or VOL DOWN key, we send a message to the * sound server to notify it of the volume change. The message includes * a flag to indicate which key was pressed, and the machine independant * flag bits to indicate which modifier keys were pressed. */ struct evioSpecialKeyMsg { msg_header_t Head; msg_type_t keyType; int key; // special key number, from bsd/dev/ev_keymap.h msg_type_t directionType; int direction; // NX_KEYDOWN, NX_KEYUP from event.h msg_type_t flagsType; int flags; // device independant flags from event.h msg_type_t levelType; int level; // EV_AUDIO_MIN_VOLUME to EV_AUDIO_MAX_VOLUME }; #else struct evioSpecialKeyMsg { mach_msg_header_t Head; int key; // special key number, from bsd/dev/ev_keymap.h int direction; // NX_KEYDOWN, NX_KEYUP from event.h int flags; // device independant flags from event.h int level; // EV_AUDIO_MIN_VOLUME to EV_AUDIO_MAX_VOLUME }; #endif #define EV_SPECIAL_KEY_MSG_ID (('S'<<24) | ('k'<<16) | ('e'<<8) | ('y')) typedef struct evioSpecialKeyMsg *evioSpecialKeyMsg_t; /* * Volume ranges */ #define EV_AUDIO_MIN_VOLUME 0 #define EV_AUDIO_MAX_VOLUME 64 #define kIOHIDSystemClass "IOHIDSystem" #define kIOHIKeyboardClass "IOHIKeyboard" #define kIOHIPointingClass "IOHIPointing" #define IOHIDSYSTEM_CONFORMSTO kIOHIDSystemClass enum { kIOHIDEventNotification = 0, }; #define kIOHIDCurrentShmemVersion 4 #define kIOHIDLastCompatibleShmemVersion 3 enum { kIOHIDServerConnectType = 0, kIOHIDParamConnectType = 1, kIOHIDEventSystemConnectType = 3, }; enum { kIOHIDGlobalMemory = 0 }; enum { kIOHIDEventQueueTypeKernel = 0, kIOHIDEventQueueTypeUser = 1 }; #ifdef KERNEL typedef UInt16 (*MasterVolumeUpdate)(void); typedef bool (*MasterMuteUpdate)(void); typedef struct { MasterVolumeUpdate incrementMasterVolume; MasterVolumeUpdate decrementMasterVolume; MasterMuteUpdate toggleMasterMute; } MasterAudioFunctions; extern MasterAudioFunctions *masterAudioFunctions; #endif #ifndef KERNEL #ifndef _IOKIT_IOHIDLIB_H #include <IOKit/hidsystem/IOHIDLib.h> #endif #endif /* !KERNEL */ enum { /*! @defined kIOHIDOpenedByEventSystem @abstract option passed to open for IOHIDInterface if opened by IOHIDEventDriver */ kIOHIDOpenedByEventSystem = 0x10000, /*! @defined kIOHIDOpenedByFastPathClient @abstract option passed to open for IOHIDEventService if opened by fast path client */ kIOHIDOpenedByFastPathClient = 0x20000 }; // iokit_vendor_specific_msg(1) unused /*! @defined kIOHIDMessageRelayServiceInterfaceActive @abstract message from IOHIDDevice to indicate that the IOHIDRelayService's USB interface is active. */ #define kIOHIDMessageRelayServiceInterfaceActive iokit_vendor_specific_msg(2) __END_DECLS #endif /* !_DEV_EVIO_H */
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/hidsystem/IOHIDLib.h
/* * Copyright (c) 1999-2009 Apple Computer, Inc. All rights reserved. * * @APPLE_LICENSE_HEADER_START@ * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this * file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_LICENSE_HEADER_END@ */ /* * Copyright (c) 1999 Apple Computer, Inc. All rights reserved. * * HISTORY * */ #ifndef _IOKIT_IOHIDLIB_H #define _IOKIT_IOHIDLIB_H #include <IOKit/hidsystem/IOHIDShared.h> #include <sys/cdefs.h> __BEGIN_DECLS /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ extern kern_return_t IOHIDCreateSharedMemory( io_connect_t connect, unsigned int version ); extern kern_return_t IOHIDSetEventsEnable( io_connect_t connect, boolean_t enable ); extern kern_return_t IOHIDSetCursorEnable( io_connect_t connect, boolean_t enable ) __attribute__((availability(macos,deprecated=11.0))); enum { // Options for IOHIDPostEvent() kIOHIDSetGlobalEventFlags = 0x00000001, kIOHIDSetCursorPosition = 0x00000002, kIOHIDSetRelativeCursorPosition = 0x00000004, kIOHIDPostHIDManagerEvent = 0x00000008 }; #define HIDPostEventDeprecatedMsg "Use CGSEventTap for posting HID events, IOHIDUserDevice for simulating HID device, IOPMAssertionDeclareUserActivity for reporting user activity" extern kern_return_t IOHIDPostEvent( io_connect_t connect, UInt32 eventType, IOGPoint location, const NXEventData * eventData, UInt32 eventDataVersion, IOOptionBits eventFlags, IOOptionBits options ) __attribute__((availability(macos,deprecated=11.0,message=HIDPostEventDeprecatedMsg))); extern kern_return_t IOHIDSetMouseLocation( io_connect_t connect, int x, int y) __attribute__((availability(macos,deprecated=11.0))); extern kern_return_t IOHIDGetButtonEventNum( io_connect_t connect, NXMouseButton button, int * eventNum ) __deprecated; extern kern_return_t IOHIDGetScrollAcceleration( io_connect_t handle, double * acceleration ) __attribute__((availability(macos,introduced=10.0,deprecated=10.12))); extern kern_return_t IOHIDSetScrollAcceleration( io_connect_t handle, double acceleration ) __attribute__((availability(macos,introduced=10.0,deprecated=10.12))); extern kern_return_t IOHIDGetMouseAcceleration( io_connect_t handle, double * acceleration) __attribute__((availability(macos,introduced=10.0,deprecated=10.12))); extern kern_return_t IOHIDSetMouseAcceleration( io_connect_t handle, double acceleration ) __attribute__((availability(macos,introduced=10.0,deprecated=10.12))); extern kern_return_t IOHIDGetMouseButtonMode( io_connect_t handle, int * mode ) __attribute__((availability(macos,deprecated=11.0))); extern kern_return_t IOHIDSetMouseButtonMode( io_connect_t handle, int mode ) __attribute__((availability(macos,introduced=10.0,deprecated=10.12))); extern kern_return_t IOHIDGetAccelerationWithKey( io_connect_t handle, CFStringRef key, double * acceleration ) __attribute__((availability(macos,introduced=10.0,deprecated=10.12))); extern kern_return_t IOHIDSetAccelerationWithKey( io_connect_t handle, CFStringRef key, double acceleration ) __attribute__((availability(macos,introduced=10.0,deprecated=10.12))); extern kern_return_t IOHIDGetParameter( io_connect_t handle, CFStringRef key, IOByteCount maxSize, void * bytes, IOByteCount * actualSize ) __attribute__((availability(macos,introduced=10.0,deprecated=10.12))); extern kern_return_t IOHIDSetParameter( io_connect_t handle, CFStringRef key, const void * bytes, IOByteCount size ) __attribute__((availability(macos,introduced=10.0,deprecated=10.12))); extern kern_return_t IOHIDCopyCFTypeParameter( io_connect_t handle, CFStringRef key, CFTypeRef * parameter ); extern kern_return_t IOHIDSetCFTypeParameter( io_connect_t handle, CFStringRef key, CFTypeRef parameter ); // selectors are found in IOHIDParameter.h extern kern_return_t IOHIDGetStateForSelector( io_connect_t handle, int selector, UInt32 *state ); extern kern_return_t IOHIDSetStateForSelector( io_connect_t handle, int selector, UInt32 state ); extern kern_return_t IOHIDGetModifierLockState( io_connect_t handle, int selector, bool *state ); extern kern_return_t IOHIDSetModifierLockState( io_connect_t handle, int selector, bool state ); // Used by Window Server only extern kern_return_t IOHIDRegisterVirtualDisplay( io_connect_t handle, UInt32 *display_token ) __attribute__((availability(macos,introduced=10.0,deprecated=11.0))); extern kern_return_t IOHIDUnregisterVirtualDisplay( io_connect_t handle, UInt32 display_token ) __attribute__((availability(macos,introduced=10.0,deprecated=11.0))); extern kern_return_t IOHIDSetVirtualDisplayBounds( io_connect_t handle, UInt32 display_token, const IOGBounds * bounds ) __attribute__((availability(macos,introduced=10.0,deprecated=11.0))); extern kern_return_t IOHIDGetActivityState( io_connect_t handle, bool *hidActivityIdle ) __attribute__((availability(macos,deprecated=11.0))); /* * @typedef IOHIDRequestType * * @abstract * Request type passed in to IOHIDCheckAccess/IOHIDRequestAccess. * * @field kIOHIDRequestTypePostEvent * Request to post event through IOHIDPostEvent API. Access must be granted * by the user to use this API. If you do not request access through the * IOHIDRequestAccess call, the request will be made on the process's behalf * in the IOHIDPostEvent call. * * @field kIOHIDRequestTypeListenEvent * Request to listen to event through IOHIDManager/IOHIDDevice API. Access must * be granted by the user to use this API. If you do not request access through * the IOHIDRequestAccess call, the request will be made on the process's behalf * in IOHIDManagerOpen/IOHIDDeviceOpen calls. * */ typedef enum { kIOHIDRequestTypePostEvent, kIOHIDRequestTypeListenEvent } IOHIDRequestType; /* * @typedef IOHIDAccessType * * @abstract * Enumerator of access types returned from IOHIDCheckAccess. */ typedef enum { kIOHIDAccessTypeGranted, kIOHIDAccessTypeDenied, kIOHIDAccessTypeUnknown } IOHIDAccessType; /*! * @function IOHIDCheckAccess * * @abstract * Checks if the process has access to a specific IOHIDRequestType. A process * may request access by calling the IOHIDRequestAccess function. * * @param requestType * The request type defined in the IOHIDRequestType enumerator. * * @result * Returns an access type defined in the IOHIDAccessType enumerator. */ IOHIDAccessType IOHIDCheckAccess(IOHIDRequestType requestType) __OSX_AVAILABLE(10.15) __IOS_AVAILABLE(13.0) __TVOS_AVAILABLE(13.0) __WATCHOS_AVAILABLE(6.0); /*! * @function IOHIDRequestAccess * * @abstract * Requests access from the user for a specific IOHIDRequestType. * * @discussion * Processes that wish to post events through the IOHIDPostEvent API, or receive * reports through the IOHIDManager/IOHIDDevice API must be granted access first * by the user. If you do not call this API, it will be called on your behalf * when the API are used. * * @param requestType * The request type defined in the IOHIDRequestType enumerator. * * @result * Returns true if access was granted. */ bool IOHIDRequestAccess(IOHIDRequestType requestType) __OSX_AVAILABLE(10.15) __IOS_AVAILABLE(13.0) __TVOS_AVAILABLE(13.0) __WATCHOS_AVAILABLE(6.0); /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ __END_DECLS #endif /* ! _IOKIT_IOHIDLIB_H */
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/hidsystem/IOHIDParameter.h
/* * @APPLE_LICENSE_HEADER_START@ * * Copyright (c) 1999-2003 Apple Computer, Inc. All Rights Reserved. * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this * file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_LICENSE_HEADER_END@ */ /* Copyright (c) 1992 NeXT Computer, Inc. All rights reserved. * * evsio.h - Get/Set parameter calls for Event Status Driver. * * CAUTION: Developers should stick to the API exported in * <drivers/event_status_driver.h> to guarantee * binary compatability of their applications in future * releases. * * HISTORY * 22 May 1992 Mike Paquette at NeXT * Created. */ #ifndef _DEV_EVSIO_H #define _DEV_EVSIO_H /* Public type definitions. */ #include <IOKit/hidsystem/IOHIDTypes.h> #include <IOKit/hidsystem/IOLLEvent.h> #include <IOKit/hid/IOHIDProperties.h> /* * Identify this driver as one that uses the new driverkit and messaging API */ #ifndef _NeXT_MACH_EVENT_DRIVER_ #define _NeXT_MACH_EVENT_DRIVER_ (1) #endif /* !_NeXT_MACH_EVENT_DRIVER_ */ /* * */ #define kIOHIDKindKey "HIDKind" #define kIOHIDInterfaceIDKey "HIDInterfaceID" #define kIOHIDSubinterfaceIDKey "HIDSubinterfaceID" #define kIOHIDOriginalSubinterfaceIDKey "HIDOriginalSubinterfaceID" #define kIOHIDParametersKey "HIDParameters" #define kIOHIDVirtualHIDevice "HIDVirtualDevice" #define kIOHIDKeyRepeatKey "HIDKeyRepeat" #define kIOHIDInitialKeyRepeatKey "HIDInitialKeyRepeat" #define kIOHIDKeyMappingKey "HIDKeyMapping" #define kIOHIDResetKeyboardKey "HIDResetKeyboard" #define kIOHIDKeyboardModifierMappingPairsKey "HIDKeyboardModifierMappingPairs" #define kIOHIDKeyboardModifierMappingSrcKey "HIDKeyboardModifierMappingSrc" #define kIOHIDKeyboardModifierMappingDstKey "HIDKeyboardModifierMappingDst" #define kIOHIDKeyboardCapsLockDoesLockKey "HIDKeyboardCapsLockDoesLock" #define kIOHIDKeyboardSupportsF12EjectKey "HIDKeyboardSupportsF12Eject" #define kIOHIDKeyboardSupportedModifiersKey "HIDKeyboardSupportedModifiers" #define kIOHIDKeyboardGlobalModifiersKey "HIDKeyboardGlobalModifiers" //read only property that specify usage of clobal modifiers // Bit[0] - Report modifiers to the service by setting kIOHIDKeyboardGlobalModifiersKey with global modifiers // Bit[1] - Update/translate events from service taking global modifiers state in consideration #define kIOHIDServiceGlobalModifiersUsageKey "HIDServiceGlobalModifiersUsage" #define kIOHIDPointerResolutionKey "HIDPointerResolution" #define kIOHIDResetPointerKey "HIDResetPointer" #define kIOHIDPointerConvertAbsoluteKey "HIDPointerConvertAbsolute" #define kIOHIDPointerContactToMoveKey "HIDPointerContactToMove" #define kIOHIDPointerPressureToClickKey "HIDPointerPressureToClick" #define kIOHIDPointerButtonCountKey "HIDPointerButtonCount" #define kIOHIDPointerAccelerationSettingsKey "HIDPointerAccelerationSettings" #define kIOHIDPointerAccelerationTableKey "HIDPointerAccelerationTable" // velocity for pointer acceleration #define kIOHIDPointerAccelerationMultiplierKey "HIDPointerAccelerationMultiplier" #define kIOHIDScrollResetKey "HIDScrollReset" #define kIOHIDScrollResolutionKey "HIDScrollResolution" #define kIOHIDScrollReportRateKey "HIDScrollReportRate" #define kIOHIDScrollAccelerationTableKey "HIDScrollAccelerationTable" #define kIOHIDScrollResolutionXKey "HIDScrollResolutionX" #define kIOHIDScrollResolutionYKey "HIDScrollResolutionY" #define kIOHIDScrollResolutionZKey "HIDScrollResolutionZ" #define kIOHIDScrollAccelerationTableXKey "HIDScrollAccelerationTableX" #define kIOHIDScrollAccelerationTableYKey "HIDScrollAccelerationTableY" #define kIOHIDScrollAccelerationTableZKey "HIDScrollAccelerationTableZ" #define kIOHIDScrollMouseButtonKey "HIDScrollMouseButton" #define kIOHIDScrollZoomModifierMaskKey "HIDScrollZoomModifierMask" #define kIOHIDTrackpadScrollAccelerationKey "HIDTrackpadScrollAcceleration" #define kIOHIDTrackpadAccelerationType "HIDTrackpadAcceleration" #define kIOHIDClickTimeKey "HIDClickTime" #define kIOHIDClickSpaceKey "HIDClickSpace" #define kIOHIDWaitCursorFrameIntervalKey "HIDWaitCursorFrameInterval" #define kIOHIDAutoDimThresholdKey "HIDAutoDimThreshold" #define kIOHIDAutoDimStateKey "HIDAutoDimState" #define kIOHIDAutoDimTimeKey "HIDAutoDimTime" #define kIOHIDIdleTimeKey "HIDIdleTime" #define kIOHIDBrightnessKey "HIDBrightness" #define kIOHIDAutoDimBrightnessKey "HIDAutoDimBrightness" #define kIOHIDFKeyModeKey "HIDFKeyMode" // if kIOHIDStickyKeysDisabledKey is 1, then all sticky keys functionality // is completely turned off. Multiple shifts will have no effect. #define kIOHIDStickyKeysDisabledKey "HIDStickyKeysDisabled" // if kIOHIDStickyKeysOnKey is 1 then a depressed modifier will stay down // until a non-modifer key is pressed (or sticky keys is turned off) #define kIOHIDStickyKeysOnKey "HIDStickyKeysOn" // if kIOHIDStickyKeysShiftTogglesKey is 1, then a sequence of five // shift keys in sequence will toggle sticky keys on or off #define kIOHIDStickyKeysShiftTogglesKey "HIDStickyKeysShiftToggles" // // #define kIOHIDResetStickyKeyNotification "HIDResetStickyKeyNotification" // if kIOHIDMouseKeysOptionTogglesKey is 1, then a sequence of five // option keys in sequence will toggle mouse keys on or off #define kIOHIDMouseKeysOptionTogglesKey "HIDMouseKeysOptionToggles" // kIOHIDSlowKeysDelayKey represents the delay used for slow keys. // if kIOHIDSlowKeysDelayKey is 0, then slow keys off #define kIOHIDSlowKeysDelayKey "HIDSlowKeysDelay" #define kIOHIDF12EjectDelayKey "HIDF12EjectDelay" #define kIOHIDMouseKeysOnKey "HIDMouseKeysOn" #define kIOHIDUseKeyswitchKey "HIDUseKeyswitch" #define kIOHIDDisallowRemappingOfPrimaryClickKey "HIDDisallowRemappingOfPrimaryClick" #define kIOHIDMouseKeysEnablesVirtualNumPadKey "HIDMouseKeysEnablesVirtualNumPad" #define kIOHIDResetLEDsKey "HIDResetLEDs" // Parametric Acceleration Keys #define kHIDAccelParametricCurvesKey "HIDAccelCurves" #define kHIDPointerReportRateKey "HIDPointerReportRate" #define kHIDTrackingAccelParametricCurvesKey "HIDTrackingAccelCurves" #define kHIDScrollAccelParametricCurvesKey "HIDScrollAccelCurves" #define kHIDAccelParametricCurvesDebugKey "HIDAccelCurvesDebug" #define kHIDScrollAccelParametricCurvesDebugKey "HIDScrollAccelCurvesDebug" #define kHIDAccelGainLinearKey "HIDAccelGainLinear" #define kHIDAccelGainParabolicKey "HIDAccelGainParabolic" #define kHIDAccelGainCubicKey "HIDAccelGainCubic" #define kHIDAccelGainQuarticKey "HIDAccelGainQuartic" #define kHIDAccelTangentSpeedLinearKey "HIDAccelTangentSpeedLinear" #define kHIDAccelTangentSpeedParabolicRootKey "HIDAccelTangentSpeedParabolicRoot" #define kHIDAccelTangentSpeedCubicRootKey "HIDAccelTangentSpeedCubicRoot" #define kHIDAccelTangentSpeedQuarticRootKey "HIDAccelTangentSpeedQuarticRoot" #define kHIDAccelIndexKey "HIDAccelIndex" // Scroll Count Keys #define kIOHIDScrollCountMaxTimeDeltaBetweenKey "HIDScrollCountMaxTimeDeltaBetween" #define kIOHIDScrollCountMaxTimeDeltaToSustainKey "HIDScrollCountMaxTimeDeltaToSustain" #define kIOHIDScrollCountMinDeltaToStartKey "HIDScrollCountMinDeltaToStart" #define kIOHIDScrollCountMinDeltaToSustainKey "HIDScrollCountMinDeltaToSustain" #define kIOHIDScrollCountIgnoreMomentumScrollsKey "HIDScrollCountIgnoreMomentumScrolls" #define kIOHIDScrollCountMouseCanResetKey "HIDScrollCountMouseCanReset" #define kIOHIDScrollCountMaxKey "HIDScrollCountMax" #define kIOHIDScrollCountAccelerationFactorKey "HIDScrollCountAccelerationFactor" #define kIOHIDScrollCountZeroKey "HIDScrollCountZero" #define kIOHIDScrollCountBootDefaultKey "HIDScrollCountBootDefault" #define kIOHIDScrollCountResetKey "HIDScrollCountReset" // HIDSystem Property Key // Mark user activity state on HID System #define kIOHIDActivityUserIdleKey "IOHIDActivityUserIdle" // the following values are used in kIOHIDPointerButtonMode typedef enum { kIOHIDButtonMode_BothLeftClicks = 0, kIOHIDButtonMode_ReverseLeftRightClicks = 1, kIOHIDButtonMode_EnableRightClick = 2 } IOHIDButtonModes; #ifdef _undef #define EVS_PREFIX "Evs_" /* All EVS calls start with this string */ /* WaitCursor-related ioctls */ #define EVSIOSWT "Evs_SetWaitThreshold" #define EVSIOSWT_SIZE EVS_PACKED_TIME_SIZE #define EVSIOSWS "Evs_SetWaitSustain" #define EVSIOSWS_SIZE EVS_PACKED_TIME_SIZE #define EVSIOSWFI "Evs_SetWaitFrameInterval" #define EVSIOSWFI_SIZE EVS_PACKED_TIME_SIZE #define EVSIOCWINFO "Evs_CurrentWaitCursorInfo" #define EVSIOCWINFO_THRESH 0 #define EVSIOCWINFO_SUSTAIN (EVSIOCWINFO_THRESH + EVS_PACKED_TIME_SIZE) #define EVSIOCWINFO_FINTERVAL (EVSIOCWINFO_SUSTAIN + EVS_PACKED_TIME_SIZE) #define EVSIOCWINFO_SIZE (EVSIOCWINFO_FINTERVAL + EVS_PACKED_TIME_SIZE) #endif #define EVS_PACKED_TIME_SIZE (sizeof(UInt64) / sizeof( unsigned int)) /* Device control ioctls. Levels specified may be in the range 0 - 64. */ #define EVSIOSB kIOHIDBrightnessKey #define EVSIOSB_SIZE 1 #define EVSIOSADB kIOHIDAutoDimBrightnessKey #define EVSIOSADB_SIZE 1 #ifdef _undef #define EVSIOSA "Evs_SetAttenuation" #define EVIOSA_SIZE 1 #define EVSIO_DCTLINFO "Evs_DeviceControlInfo" typedef enum { EVSIO_DCTLINFO_BRIGHT, EVSIO_DCTLINFO_ATTEN, EVSIO_DCTLINFO_AUTODIMBRIGHT } evsio_DCTLINFOIndices; #define EVSIO_DCTLINFO_SIZE (EVSIO_DCTLINFO_AUTODIMBRIGHT + 1) #endif /* * Device status request */ #define EVSIOINFO NX_EVS_DEVICE_INFO /* Keyboard-related ioctls - implemented within Event Sources */ #define EVSIOSKR kIOHIDKeyRepeatKey #define EVSIOSKR_SIZE EVS_PACKED_TIME_SIZE #define EVSIOSIKR kIOHIDInitialKeyRepeatKey #define EVSIOSIKR_SIZE EVS_PACKED_TIME_SIZE #define EVSIORKBD kIOHIDResetKeyboardKey #define EVSIORKBD_SIZE 1 #define EVSIOCKR_SIZE EVS_PACKED_TIME_SIZE #define EVSIOCKML kIOHIDKeyMappingKey #define EVSIOCKML_SIZE 1 /* The following two tokens are for use with the get/set character routines. */ #define EVSIOSKM kIOHIDKeyMappingKey #define EVSIOSKM_SIZE 4096 #define EVSIOCKM kIOHIDKeyMappingKey #define EVSIOCKM_SIZE 4096 /* Mouse-related ioctls - implemented within Event Sources */ #define EVSIOSMS kIOHIDPointerAccelerationKey #define EVSIOSMS_SIZE (1) #define EVSIOCMS kIOHIDPointerAccelerationKey #define EVSIOCMS_SIZE (1) #ifdef _undef #define EVSIOSMH "Evs_SetMouseHandedness" #define EVSIOSMH_SIZE 1 // value from NXMouseButton enum #define EVSIOCMH "Evs_CurrentMouseHandedness" #define EVSIOCMH_SIZE 1 #endif /* Generic pointer device controls, implemented by the Event Driver. */ #define EVSIOSCT kIOHIDClickTimeKey #define EVSIOSCT_SIZE EVS_PACKED_TIME_SIZE #define EVSIOSCS kIOHIDClickSpaceKey typedef enum { EVSIOSCS_X, EVSIOSCS_Y } evsioEVSIOSCSIndices; #define EVSIOSCS_SIZE (EVSIOSCS_Y + 1) #define EVSIOSADT kIOHIDAutoDimThresholdKey #define EVSIOSADT_SIZE EVS_PACKED_TIME_SIZE #define EVSIOSADS kIOHIDAutoDimStateKey #define EVSIOSADS_SIZE 1 #define EVSIORMS kIOHIDResetPointerKey #define EVSIORMS_SIZE 1 #define EVSIOCCT kIOHIDClickTimeKey #define EVSIOCCT_SIZE EVS_PACKED_TIME_SIZE #define EVSIOCADT kIOHIDAutoDimThresholdKey #define EVSIOCADT_SIZE EVS_PACKED_TIME_SIZE #define EVSIOGDADT kIOHIDAutoDimTimeKey #define EVSIOGDADT_SIZE EVS_PACKED_TIME_SIZE #define EVSIOIDLE kIOHIDIdleTimeKey #define EVSIOIDLE_SIZE EVS_PACKED_TIME_SIZE #define EVSIOCCS kIOHIDClickSpaceKey typedef enum { EVSIOCCS_X, EVSIOCCS_Y } evsioEVSIOCCSIndices; #define EVSIOCCS_SIZE (EVSIOCCS_Y + 1) #define EVSIOCADS kIOHIDAutoDimStateKey #define EVSIOCADS_SIZE 1 enum { // Selectors for IOHIDGetModifierLockState and IOHIDSetModifierLockState kIOHIDCapsLockState = 0x00000001, kIOHIDNumLockState = 0x00000002, kIOHIDActivityUserIdle = 0x00000003, // We no longer report display state through HIDSystem. This will not return the current state. kIOHIDActivityDisplayOn = 0x00000004, }; #endif /* !_DEV_EVSIO_H */
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/hidsystem/IOHIDEventSystemClient.h
/* * Copyright (c) 2016 Apple Computer, Inc. All rights reserved. * * @APPLE_LICENSE_HEADER_START@ * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this * file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_LICENSE_HEADER_END@ */ #ifndef IOHIDEventSystemClient_h #define IOHIDEventSystemClient_h #include <CoreFoundation/CoreFoundation.h> __BEGIN_DECLS CF_ASSUME_NONNULL_BEGIN CF_IMPLICIT_BRIDGING_ENABLED /*! @header IOHIDEventSystemClient IOHIDEventSystemClient serves as a client that can be used for reading/writing specific properties of the HID event system, as well as getting services of the HID event system. A list of accessible properties can be found in <code>IOKit/hid/IOHIDProperties.h</code>. @seealso IOKit/hidsystem/IOHIDServiceClient.h */ typedef struct CF_BRIDGED_TYPE(id) __IOHIDEventSystemClient * IOHIDEventSystemClientRef; /*! * @function IOHIDEventSystemClientCreateSimpleClient * * @abstract Creates a client of the HID event system that has to ability to read/write certain * properties. * * @discussion Certain properties have the ability to be set/read by clients, see * <code>IOHIDProperties.h</code> for a list of these properties. * * @param allocator a custom allocator reference to be used for allocation of the result. * * @result Returns a <code>IOHIDEventSystemClientRef</code> on success. * Caller should CFRelease the client when they are finished with it, or keep a * reference to the client if multiple properties need to be set/read. */ IOHIDEventSystemClientRef IOHIDEventSystemClientCreateSimpleClient(CFAllocatorRef _Nullable allocator); /*! * @function IOHIDEventSystemClientSetProperty * * @abstract Sets a property on the HID event system. * * @param client the HID client that created via <code>IOHIDEventSystemClientCreateSimpleClient()</code>. * * @param key the property key to set. A list of keys can be found in <code>HIDProperties.h</code>. * * @param property the value to set the property. * * @result Returns true on success. */ Boolean IOHIDEventSystemClientSetProperty(IOHIDEventSystemClientRef client, CFStringRef key, CFTypeRef property); /*! * @function IOHIDEventSystemClientCopyProperty * * @abstract Copies a property from the HID event system. * * @param client the HID client created via <code>IOHIDEventSystemClientCreateSimpleClient()</code>. * * @param key the property key to copy. A list of keys can be found in <code>HIDProperties.h</code>. * * @result Returns a CFTypeRef of the property to be copied on success, otherwise NULL. * Caller is responsible for calling CFRelease on the property. */ CFTypeRef _Nullable IOHIDEventSystemClientCopyProperty(IOHIDEventSystemClientRef client, CFStringRef key); /*! * @function IOHIDEventSystemClientGetTypeID * * @result Returns the CFTypeID of the <code>IOHIDEventSystemClient</code> class. */ CFTypeID IOHIDEventSystemClientGetTypeID(void); /*! * @function IOHIDEventSystemClientCopyServices * * @abstract Copies all services available to the client. * * @discussion Useful for seeing services that are available. Clients can further probe * the services with the APIs available in <code>IOHIDServiceClient.h</code>. * * @param client the HID client that created via <code>IOHIDEventSystemClientCreateSimpleClient()</code>. * * @result On success, returns a CFArrayRef of <code>IOHIDServiceClientRefs</code> that are * available to the client. Caller is responsible for releasing the array. */ CFArrayRef _Nullable IOHIDEventSystemClientCopyServices(IOHIDEventSystemClientRef client); CF_IMPLICIT_BRIDGING_DISABLED CF_ASSUME_NONNULL_END __END_DECLS #endif /* IOHIDEventSystemClient_h */
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/hidsystem/IOHIDUserDevice.h
/* * * @APPLE_LICENSE_HEADER_START@ * * Copyright (c) 2019 Apple Computer, Inc. All Rights Reserved. * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this * file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_LICENSE_HEADER_END@ */ #ifndef _IOKIT_HID_IOHIDUSERDEVICE_H #define _IOKIT_HID_IOHIDUSERDEVICE_H #include <CoreFoundation/CoreFoundation.h> #include <IOKit/IOKitLib.h> #include <IOKit/hid/IOHIDKeys.h> __BEGIN_DECLS CF_ASSUME_NONNULL_BEGIN CF_IMPLICIT_BRIDGING_ENABLED typedef struct CF_BRIDGED_TYPE(id) __IOHIDUserDevice * IOHIDUserDeviceRef; /*! * @typedef IOHIDUserDeviceSetReportBlock * * @abstract * The type block used for IOHIDUserDevice set report calls. * * @param type * The report type. * * @param reportID * The report ID. * * @param report * The report bytes. * * @param reportLength * The length of the report being passed in. */ typedef IOReturn (^IOHIDUserDeviceSetReportBlock)(IOHIDReportType type, uint32_t reportID, const uint8_t *report, CFIndex reportLength); /*! * @typedef IOHIDUserDeviceGetReportBlock * * @abstract * The type block used for IOHIDUserDevice get report calls. * * @param type * The report type. * * @param reportID * The report ID. * * @param report * A buffer to be filled in by the implementor with the report. * * @param reportLength * The length of the report buffer being passed in. The implementor of this * block may update the reportLength variable to reflect the actual length of * the returned report. */ typedef IOReturn (^IOHIDUserDeviceGetReportBlock)(IOHIDReportType type, uint32_t reportID, uint8_t *report, CFIndex *reportLength); /*! * @enum IOHIDUserDeviceOptions * * @abstract * Enumerator of IOHIDUserDeviceOptions to be passed in to * IOHIDUserDeviceCreateWithOptions. * * @field IOHIDUserDeviceOptionsCreateOnActivate * Specifies that the kernel HID device should not be created until the call * to IOHIDUserDeviceActivate. This may be useful for preventing dropped get/set * report calls to the user device. */ typedef CF_ENUM(IOOptionBits, IOHIDUserDeviceOptions) { IOHIDUserDeviceOptionsCreateOnActivate = 1 << 0, }; /*! * @function IOHIDUserDeviceGetTypeID * * @abstract * Returns the type identifier of all IOHIDUserDevice instances. */ CF_EXPORT CFTypeID IOHIDUserDeviceGetTypeID(void); /*! * @function IOHIDUserDeviceCreateWithProperties * * @abstract * Creates a virtual IOHIDDevice in the kernel. * * @discussion * The IOHIDUserDeviceRef represents a virtual IOHIDDevice. In order to create * the device, the entitlement "com.apple.developer.hid.virtual.device" is * required to validate the source of the device. * * @param allocator * Allocator to be used during creation. * * @param properties * Dictionary containing device properties indexed by keys defined in * IOHIDKeys.h. At the bare minimum, the kIOHIDReportDescriptorKey key must be * provided, where the value represents a CFData representation of the device's * report descriptor. * * @param options * Options to be used when creating the device. * * @result * Returns a IOHIDUserDeviceRef on success. */ CF_EXPORT IOHIDUserDeviceRef _Nullable IOHIDUserDeviceCreateWithProperties( CFAllocatorRef _Nullable allocator, CFDictionaryRef properties, IOOptionBits options) __OSX_AVAILABLE(10.15) __IOS_AVAILABLE(13.0) __TVOS_AVAILABLE(13.0) __WATCHOS_AVAILABLE(6.0); /*! * @function IOHIDUserDeviceRegisterGetReportBlock * * @abstract * Registers a block to receive get report requests. * * @discussion * The call to IOHIDUserDeviceRegisterGetReportBlock should be made before the * device is activated. The device must be activated in order to receive * get report requests. * * @param device * Reference to a IOHIDUserDeviceRef * * @param block * The block to be invoked for get report calls. */ CF_EXPORT void IOHIDUserDeviceRegisterGetReportBlock(IOHIDUserDeviceRef device, IOHIDUserDeviceGetReportBlock block) __OSX_AVAILABLE(10.15) __IOS_AVAILABLE(13.0) __TVOS_AVAILABLE(13.0) __WATCHOS_AVAILABLE(6.0); /*! * @function IOHIDUserDeviceRegisterSetReportBlock * * @abstract * Registers a block to receive set report requests. * * @discussion * The call to IOHIDUserDeviceRegisterSetReportBlock should be made before the * device is activated. The device must be activated in order to receive set * report requests. * * @param device * Reference to a IOHIDUserDeviceRef * * @param block * The block to be invoked for set report calls. */ CF_EXPORT void IOHIDUserDeviceRegisterSetReportBlock(IOHIDUserDeviceRef device, IOHIDUserDeviceSetReportBlock block) __OSX_AVAILABLE(10.15) __IOS_AVAILABLE(13.0) __TVOS_AVAILABLE(13.0) __WATCHOS_AVAILABLE(6.0); /*! * @function IOHIDUserDeviceSetDispatchQueue * * @abstract * Sets the dispatch queue to be associated with the IOHIDUserDevice. * This is necessary in order to receive asynchronous events from the kernel. * * @discussion * A call to IOHIDUserDeviceSetDispatchQueue should only be made once. * * After a dispatch queue is set, the IOHIDUserDevice must make a call to * activate via IOHIDUserDeviceActivate and cancel via IOHIDUserDeviceCancel. * All calls to "Register" functions should be done before activation and not * after cancellation. * * @param device * Reference to an IOHIDUserDevice * * @param queue * The dispatch queue to which the event handler block will be submitted. */ CF_EXPORT void IOHIDUserDeviceSetDispatchQueue(IOHIDUserDeviceRef device, dispatch_queue_t queue) __OSX_AVAILABLE(10.15) __IOS_AVAILABLE(13.0) __TVOS_AVAILABLE(13.0) __WATCHOS_AVAILABLE(6.0); /*! * @function IOHIDUserDeviceSetCancelHandler * * @abstract * Sets a cancellation handler for the dispatch queue associated with * IOHIDUserDeviceScheduleWithDispatchQueue. * * @discussion * The cancellation handler (if specified) will be submitted to the device's * dispatch queue in response to a call to to IOHIDUserDeviceCancel * after all the events have been handled. * * The IOHIDUserDeviceRef should only be released after the device has been * cancelled, and the cancel handler has been called. This is to ensure all * asynchronous objects are released. For example: * * dispatch_block_t cancelHandler = dispatch_block_create(0, ^{ * CFRelease(device); * }); * IOHIDUserDeviceSetCancelHandler(device, cancelHandler); * IOHIDUserDeviceActivate(device); * IOHIDUserDeviceCancel(device); * * @param device * Reference to an IOHIDUserDevice. * * @param handler * The cancellation handler block to be associated with the dispatch queue. */ CF_EXPORT void IOHIDUserDeviceSetCancelHandler(IOHIDUserDeviceRef device, dispatch_block_t handler) __OSX_AVAILABLE(10.15) __IOS_AVAILABLE(13.0) __TVOS_AVAILABLE(13.0) __WATCHOS_AVAILABLE(6.0); /*! * @function IOHIDUserDeviceActivate * * @abstract * Activates the IOHIDUserDevice object. * * @discussion * An IOHIDUserDevice object associated with a dispatch queue is created * in an inactive state. The object must be activated in order to * receive asynchronous events from the kernel. * * A dispatch queue must be set via IOHIDUserDeviceSetDispatchQueue before * activation. * * An activated device must be cancelled via IOHIDUserDeviceCancel. All calls * to "Register" functions should be done before activation and not after * cancellation. * * Calling IOHIDUserDeviceActivate on an active IOHIDUserDevice has no effect. * * @param device * Reference to an IOHIDUserDevice. */ CF_EXPORT void IOHIDUserDeviceActivate(IOHIDUserDeviceRef device) __OSX_AVAILABLE(10.15) __IOS_AVAILABLE(13.0) __TVOS_AVAILABLE(13.0) __WATCHOS_AVAILABLE(6.0); /*! * @function IOHIDUserDeviceCancel * * @abstract * Cancels the IOHIDUserDevice preventing any further invocation of its event * handler block. * * @discussion * Cancelling prevents any further invocation of the event handler block for * the specified dispatch queue, but does not interrupt an event handler block * that is already in progress. * * Explicit cancellation of the IOHIDUserDevice is required, no implicit * cancellation takes place. * * Calling IOHIDUserDeviceCancel on an already cancelled queue has no effect. * * The IOHIDUserDeviceRef should only be released after the device has been * cancelled, and the cancel handler has been called. This is to ensure all * asynchronous objects are released. For example: * * dispatch_block_t cancelHandler = dispatch_block_create(0, ^{ * CFRelease(device); * }); * IOHIDUserDeviceSetCancelHandler(device, cancelHandler); * IOHIDUserDeviceActivate(device); * IOHIDUserDeviceCancel(device); * * @param device * Reference to an IOHIDUserDevice */ CF_EXPORT void IOHIDUserDeviceCancel(IOHIDUserDeviceRef device) __OSX_AVAILABLE(10.15) __IOS_AVAILABLE(13.0) __TVOS_AVAILABLE(13.0) __WATCHOS_AVAILABLE(6.0); /*! * @function IOHIDUserDeviceCopyProperty * * @abstract * Obtains a property from the device. * * @param key * The property key. * * @result * Returns the property on success. */ CF_EXPORT CFTypeRef _Nullable IOHIDUserDeviceCopyProperty(IOHIDUserDeviceRef device, CFStringRef key) __OSX_AVAILABLE(10.15) __IOS_AVAILABLE(13.0) __TVOS_AVAILABLE(13.0) __WATCHOS_AVAILABLE(6.0); /*! * @function IOHIDUserDeviceSetProperty * * @abstract * Sets a property on the device. * * @param key * The property key. * * @param value * The value of the property. * * @result * Returns true on success. */ CF_EXPORT Boolean IOHIDUserDeviceSetProperty(IOHIDUserDeviceRef device, CFStringRef key, CFTypeRef property) __OSX_AVAILABLE(10.15) __IOS_AVAILABLE(13.0) __TVOS_AVAILABLE(13.0) __WATCHOS_AVAILABLE(6.0); /*! * @function IOHIDUserDeviceHandleReportWithTimeStamp * * @abstract * Dispatches a report on behalf of the device. * * @param device * Reference to a IOHIDUserDeviceRef. * * @param timestamp * mach_absolute_time() based timestamp. * * @param report * Buffer containing a HID report. * * @param reportLength * The report buffer length. * * @result * Returns kIOReturnSuccess on success. */ CF_EXPORT IOReturn IOHIDUserDeviceHandleReportWithTimeStamp(IOHIDUserDeviceRef device, uint64_t timestamp, const uint8_t *report, CFIndex reportLength) __OSX_AVAILABLE(10.15) __IOS_AVAILABLE(13.0) __TVOS_AVAILABLE(13.0) __WATCHOS_AVAILABLE(6.0); CF_IMPLICIT_BRIDGING_DISABLED CF_ASSUME_NONNULL_END __END_DECLS #endif /* _IOKIT_HID_IOHIDUSERDEVICE_H */
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/hid/IOHIDDeviceKeys.h
/* * * @APPLE_LICENSE_HEADER_START@ * * Copyright (c) 2019 Apple Computer, Inc. All Rights Reserved. * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this * file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_LICENSE_HEADER_END@ */ #ifndef IOHIDDeviceKeys_h #define IOHIDDeviceKeys_h /*! * @define kIOHIDTransportKey * * @abstract * Number property that describes the transport of the device. */ #define kIOHIDTransportKey "Transport" /*! * @define kIOHIDVendorIDKey * * @abstract * Number property that describes the vendor ID of the device. */ #define kIOHIDVendorIDKey "VendorID" /*! * @define kIOHIDProductIDKey * * @abstract * Number property that describes the product ID of the device. */ #define kIOHIDProductIDKey "ProductID" /*! * @define kIOHIDVersionNumberKey * * @abstract * Number property that describes the version number of the device. */ #define kIOHIDVersionNumberKey "VersionNumber" /*! * @define kIOHIDManufacturerKey * * @abstract * String property that describes the manufacturer of the device. */ #define kIOHIDManufacturerKey "Manufacturer" /*! * @define kIOHIDProductKey * * @abstract * String property that describes the product of the device. */ #define kIOHIDProductKey "Product" /*! * @define kIOHIDSerialNumberKey * * @abstract * String property that describes the serial number of the device. */ #define kIOHIDSerialNumberKey "SerialNumber" /*! * @define kIOHIDCountryCodeKey * * @abstract * Number property that describes the country code of the device. */ #define kIOHIDCountryCodeKey "CountryCode" /*! * @define kIOHIDLocationIDKey * * @abstract * Number property that describes the location ID of the device. */ #define kIOHIDLocationIDKey "LocationID" /*! * @define kIOHIDDeviceUsagePairsKey * * @abstract * Array property that describes the top level usages of the device. The array * will have dictionaries of usage pages/usages of each top level collection * that exists on the device. */ #define kIOHIDDeviceUsagePairsKey "DeviceUsagePairs" /*! * @define kIOHIDDeviceUsageKey * * @abstract * Number property used in the device usage pairs array above. Describes a * usage of the device. */ #define kIOHIDDeviceUsageKey "DeviceUsage" /*! * @define kIOHIDDeviceUsagePageKey * * @abstract * Number property used in the device usage pairs array above. Describes a * usage page of the device. */ #define kIOHIDDeviceUsagePageKey "DeviceUsagePage" /*! * @define kIOHIDPrimaryUsageKey * * @abstract * Number property that describes the primary usage page of the device. */ #define kIOHIDPrimaryUsageKey "PrimaryUsage" /*! * @define kIOHIDPrimaryUsagePageKey * * @abstract * Number property that describes the primary usage of the device. */ #define kIOHIDPrimaryUsagePageKey "PrimaryUsagePage" /*! * @define kIOHIDMaxInputReportSizeKey * * @abstract * Number property that describes the max input report size of the device. This * is derived from the report descriptor data provided in the * kIOHIDReportDescriptorKey key. */ #define kIOHIDMaxInputReportSizeKey "MaxInputReportSize" /*! * @define kIOHIDMaxOutputReportSizeKey * * @abstract * Number property that describes the max output report size of the device. This * is derived from the report descriptor data provided in the * kIOHIDReportDescriptorKey key. */ #define kIOHIDMaxOutputReportSizeKey "MaxOutputReportSize" /*! * @define kIOHIDMaxFeatureReportSizeKey * * @abstract * Number property that describes the max feature report size of the device. * This is derived from the report descriptor data provided in the * kIOHIDReportDescriptorKey key. */ #define kIOHIDMaxFeatureReportSizeKey "MaxFeatureReportSize" /*! * @define kIOHIDReportIntervalKey * * @abstract * Number property set on the device from a client that describes the interval in us * at which the client wishes to receive reports. It is up to the device to * determine how to handle this key, if it chooses to do so. */ #define kIOHIDReportIntervalKey "ReportInterval" /*! * @define kIOHIDBatchIntervalKey * * @abstract * Number property set on the device from a client that describes the interval * at which the client wishes to receive batched reports. It is up to the device * to determine how to handle this key, if it chooses to do so. */ #define kIOHIDBatchIntervalKey "BatchInterval" /*! * @define kIOHIDRequestTimeoutKey * * @abstract * Number property that describes the request timeout in us for get/setReport calls. * It is up to the device to determine how to handle this key, if it chooses to * do so. */ #define kIOHIDRequestTimeoutKey "RequestTimeout" /*! * @define kIOHIDReportDescriptorKey * * @abstract * Data property that describes the report descriptor of the device. */ #define kIOHIDReportDescriptorKey "ReportDescriptor" /*! * @define kIOHIDBuiltInKey * * @abstract * Number property that describes if the device is built in. */ #define kIOHIDBuiltInKey "Built-In" /*! * @define kIOHIDPhysicalDeviceUniqueIDKey * * @abstract * String property that describes a unique identifier of the device. */ #define kIOHIDPhysicalDeviceUniqueIDKey "PhysicalDeviceUniqueID" #endif /* IOHIDDeviceKeys_h */
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/hid/IOHIDDevicePlugIn.h
/* * Copyright (c) 1999-2008 Apple Computer, Inc. All Rights Reserved. * * @APPLE_LICENSE_HEADER_START@ * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this * file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_LICENSE_HEADER_END@ */ #ifndef _IOKIT_HID_IOHIDDEVICEPLUGIN_H #define _IOKIT_HID_IOHIDDEVICEPLUGIN_H #include <sys/cdefs.h> #include <CoreFoundation/CoreFoundation.h> #if COREFOUNDATION_CFPLUGINCOM_SEPARATE #include <CoreFoundation/CFPlugInCOM.h> #endif #include <IOKit/IOTypes.h> #include <IOKit/IOReturn.h> #include <IOKit/IOCFPlugIn.h> #include <IOKit/hid/IOHIDBase.h> #include <IOKit/hid/IOHIDKeys.h> #include <IOKit/hid/IOHIDLibObsolete.h> __BEGIN_DECLS /*! @header IOHIDDevicePlugIn This documentation describes the details of the programming interface for accessing Human Interface Devices and interfaces from code running in user space. It is intended that user mode HID drivers properly inplement all interfaces described here in order to be visible via the HID Manager. <p> This documentation assumes that you have a basic understanding of the material contained in <a href="http://developer.apple.com/documentation/DeviceDrivers/Conceptual/AccessingHardware/index.html"><i>Accessing Hardware From Applications</i></a> For definitions of I/O Kit terms used in this documentation, such as matching dictionary, family, and driver, see the overview of I/O Kit terms and concepts in the "Device Access and the I/O Kit" chapter of <i>Accessing Hardware From Applications</i>. This documentation also assumes you have read <a href="http://developer.apple.com/documentation/DeviceDrivers/HumanInterfaceDeviceForceFeedback-date.html"><i>Human Interface Device & Force Feedback</i></a>. Please review documentation before using this reference. <p> All of the information described in this document is contained in the header file <font face="Courier New,Courier,Monaco">IOHIDLib.h</font> found at <font face="Courier New,Courier,Monaco">/System/Library/Frameworks/IOKit.framework/Headers/hid/IOHIDDevicePlugIn.h</font>. */ /* 13AA9C44-6F1B-11D4-907C-0005028F18D5 */ /*! @defined kIOHIDDeviceFactoryID @discussion This UUID constant is used internally by the system, and should not have to be used by any driver code to access the device interfaces. */ #define kIOHIDDeviceFactoryID CFUUIDGetConstantUUIDWithBytes(NULL, \ 0x13, 0xAA, 0x9C, 0x44, 0x6F, 0x1B, 0x11, 0xD4, \ 0x90, 0x7C, 0x00, 0x05, 0x02, 0x8F, 0x18, 0xD5) /* 7DDEECA8-A7B4-11DA-8A0E-0014519758EF */ /*! @defined kIOHIDDeviceTypeID @discussion This UUID constant is used to obtain a device interface corresponding to an io_service_t corresponding to an IOHIDDevice in the kernel. Once you have obtained the IOCFPlugInInterface for the service, you must use the QueryInterface function to obtain the device interface for the user client itself. Example: <pre> @textblock io_service_t hidDeviceRef; // obtained earlier IOCFPlugInInterface **iodev; // fetching this now SInt32 score; // not used IOReturn err; err = IOCreatePlugInInterfaceForService(hidDeviceRef, kIOHIDDeviceTypeID, kIOCFPlugInInterfaceID, &iodev, &score); @/textblock </pre> */ #define kIOHIDDeviceTypeID CFUUIDGetConstantUUIDWithBytes(NULL, \ 0x7d, 0xde, 0xec, 0xa8, 0xa7, 0xb4, 0x11, 0xda, \ 0x8a, 0x0e, 0x00, 0x14, 0x51, 0x97, 0x58, 0xef) /* 474BDC8E-9F4A-11DA-B366-000D936D06D2 */ /*! @defined kIOHIDDeviceDeviceInterfaceID @discussion This UUID constant is used to obtain a device interface corresponding to an IOHIDDevice service in the kernel. The type of this device interface is IOHIDDeviceDeviceInterface. This device interface is obtained after the IOCFPlugInInterface for the service itself has been obtained. <b>Note:</b> Please note that subsequent calls to QueryInterface with the UUID kIOHIDDeviceDeviceInterfaceID, will return a retained instance of an existing IOHIDDeviceDeviceInterface. Example: <pre> @textblock IOCFPluginInterface ** iodev; // obtained earlier IOHIDDeviceDeviceInterface ** dev; // fetching this now IOReturn err; err = (*iodev)->QueryInterface(iodev, CFUUIDGetUUIDBytes(kIOHIDDeviceDeviceInterfaceID), (LPVoid)&dev); @/textblock </pre> */ #define kIOHIDDeviceDeviceInterfaceID CFUUIDGetConstantUUIDWithBytes(NULL, \ 0x47, 0x4b, 0xdc, 0x8e, 0x9f, 0x4a, 0x11, 0xda, \ 0xb3, 0x66, 0x00, 0x0d, 0x93, 0x6d, 0x06, 0xd2 ) /* B473256C-6A72-4E04-B694-C4001D202020 */ /*! @defined kIOHIDDeviceDeviceInterfaceID2 @discussion This UUID constant is used to obtain a device interface corresponding to an IOHIDDevice service in the kernel, but only for timestamped report callbacks. The type of this device interface is IOHIDDeviceTimeStampedDeviceInterface. This device interface is obtained after the IOCFPlugInInterface for the service itself has been obtained. <b>Note:</b> Please note that subsequent calls to QueryInterface with the UUID kIOHIDDeviceDeviceInterfaceID2, will return a retained instance of an existing IOHIDDeviceTimeStampedDeviceInterface. Example: <pre> @textblock IOCFPluginInterface **iodev; // obtained earlier IOHIDDeviceTimeStampedDeviceInterface **devTime;// fetching this now IOReturn err; err = (*iodev)->QueryInterface(iodev, CFUUIDGetUUIDBytes(kIOHIDDeviceDeviceInterfaceID2), (LPVoid)&devTime); @/textblock </pre> */ #define kIOHIDDeviceDeviceInterfaceID2 CFUUIDGetConstantUUIDWithBytes(NULL, \ 0xB4, 0x73, 0x25, 0x6C, 0x6A, 0x72, 0x4E, 0x04, \ 0xB6, 0x94, 0xC4, 0x00, 0x1D, 0x20, 0x20, 0x20) /* 2EC78BDB-9F4E-11DA-B65C-000D936D06D2 */ /*! @defined kIOHIDDeviceQueueInterfaceID @discussion This UUID constant is used to obtain a queue interface corresponding to an IOHIDDevice service in the kernel. The type of this queue interface is IOHIDDeviceQueueInterface. This device interface is obtained after the device interface for the service itself has been obtained. <b>Note:</b> Please note that subsequent calls to QueryInterface with the UUID kIOHIDDeviceQueueInterfaceID, will return a retained instance of a new IOHIDDeviceQueueInterface. Example: <pre> @textblock IOCFPluginInterface ** iodev; // obtained earlier IOHIDDeviceQueueInterface ** intf; // fetching this now IOReturn err; err = (*iodev)->QueryInterface(iodev, CFUUIDGetUUIDBytes(kIOHIDDeviceQueueInterfaceID), (LPVoid)&intf); @/textblock </pre> */ #define kIOHIDDeviceQueueInterfaceID CFUUIDGetConstantUUIDWithBytes(NULL, \ 0x2e, 0xc7, 0x8b, 0xdb, 0x9f, 0x4e, 0x11, 0xda, \ 0xb6, 0x5c, 0x00, 0x0d, 0x93, 0x6d, 0x06, 0xd2) /* 1F2E78FA-9FFA-11DA-90B4-000D936D06D2 */ /*! @defined kIOHIDDeviceTransactionInterfaceID @discussion This UUID constant is used to obtain a transaction interface corresponding to an IOHIDDevice service in the kernel. The type of this queue interface is IOHIDDeviceTransactionInterface. This device interface is obtained after the device interface for the service itself has been obtained. <b>Note:</b> Please note that subsequent calls to QueryInterface with the UUID kIOHIDDeviceTransactionInterfaceID, will return a retained instance of a new IOHIDDeviceTransactionInterface. Example: <pre> @textblock IOCFPluginInterface ** iodev; // obtained earlier IOHIDDeviceTransactionInterface ** intf; // fetching this now IOReturn err; err = (*iodev)->QueryInterface(iodev, CFUUIDGetUUIDBytes(kIOHIDDeviceTransactionInterfaceID), (LPVoid)&intf); @/textblock </pre> */ #define kIOHIDDeviceTransactionInterfaceID CFUUIDGetConstantUUIDWithBytes(NULL, \ 0x1f, 0x2e, 0x78, 0xfa, 0x9f, 0xfa, 0x11, 0xda, \ 0x90, 0xb4, 0x00, 0x0d, 0x93, 0x6d, 0x06, 0xd2) #define IOHID_DEVICE_DEVICE_FUNCS_V1 \ IOReturn (*open)(void * self, IOOptionBits options); \ IOReturn (*close)(void * self, IOOptionBits options); \ IOReturn (*getProperty)(void * self, CFStringRef key, CFTypeRef * pProperty); \ IOReturn (*setProperty)(void * self, CFStringRef key, CFTypeRef property); \ IOReturn (*getAsyncEventSource)(void * self, CFTypeRef * pSource); \ IOReturn (*copyMatchingElements)(void * self, CFDictionaryRef matchingDict, CFArrayRef * pElements, IOOptionBits options); \ IOReturn (*setValue)(void * self, IOHIDElementRef element, IOHIDValueRef value, uint32_t timeout, IOHIDValueCallback callback, void * context, IOOptionBits options); \ IOReturn (*getValue)(void * self, IOHIDElementRef element, IOHIDValueRef * pValue, uint32_t timeout, IOHIDValueCallback callback, void * context, IOOptionBits options); \ IOReturn (*setInputReportCallback)(void * self, uint8_t * report, CFIndex reportLength, IOHIDReportCallback callback, void * context, IOOptionBits options); \ IOReturn (*setReport)(void * self, IOHIDReportType reportType, uint32_t reportID, const uint8_t * report, CFIndex reportLength, uint32_t timeout, IOHIDReportCallback callback, void * context, IOOptionBits options); \ IOReturn (*getReport)(void * self, IOHIDReportType reportType, uint32_t reportID, uint8_t * report, CFIndex * pReportLength, uint32_t timeout, IOHIDReportCallback callback, void * context, IOOptionBits options) /*! @interface IOHIDDeviceDeviceInterface @abstract The object you use to access HID devices from user space, returned by version 1.5 of the IOHIDFamily. @discussion The functions listed here will work with any version of the IOHIDDeviceDeviceInterface. <b>Note:</b> Please note that methods declared in this interface follow the copy/get/set conventions. */ typedef struct IOHIDDeviceDeviceInterface { IUNKNOWN_C_GUTS; #ifdef IOHID_DEVICE_DEVICE_FUNCS_V1 // { IOHID_DEVICE_DEVICE_FUNCS_V1; #else // } { /*! @function open @abstract Opens the IOHIDDevice. @discussion Before the client can issue commands that change the state of the device, it must have succeeded in opening the device. This establishes a link between the client's task and the actual device. To establish an exclusive link use the kIOHIDOptionsTypeSeizeDevice option. @param self Pointer to the IOHIDDeviceDeviceInterface. @param options Option bits to be passed down to the user client. @result Returns kIOReturnSuccess if successful, some other mach error if the connection is no longer valid. */ IOReturn (*open)(void * self, IOOptionBits options); /*! @function close @abstract Closes the task's connection to the IOHIDDevice. @discussion Releases the client's access to the IOHIDDevice. @param self Pointer to the IOHIDDeviceDeviceInterface. @param options Option bits to be passed down to the user client. @result Returns kIOReturnSuccess if successful, kIOReturnNoDevice if there is no connection to an IOService. */ IOReturn (*close)(void * self, IOOptionBits options); /*! @function getProperty @abstract Obtains a property related to the IOHIDDevice. @discussion Property keys are prefixed by kIOHIDDevice and declared in IOHIDKeys.h. @param self Pointer to the IOHIDDeviceDeviceInterface. @param key CFStringRef key @param pProperty Pointer to a CFTypeRef property. @result Returns kIOReturnSuccess if successful. */ IOReturn (*getProperty)(void * self, CFStringRef key, CFTypeRef * pProperty); /*! @function setProperty @abstract Sets a property related to the IOHIDDevice. @discussion Property keys are prefixed by kIOHIDDevice and declared in IOHIDKeys.h. @param self Pointer to the IOHIDDeviceDeviceInterface. @param key CFStringRef key @param property CFTypeRef property. @result Returns kIOReturnSuccess if successful. */ IOReturn (*setProperty)(void * self, CFStringRef key, CFTypeRef property); /*! @function getAsyncEventSource @abstract Obtains the event source for this IOHIDDeviceDeviceInterface instance. @discussion The returned event source can be of type CFRunLoopSourceRef or CFRunLoopTimerRef. @param self Pointer to the IOHIDDeviceDeviceInterface. @param pSource Pointer to a CFType to return the run loop event source. @result Returns kIOReturnSuccess if successful or a kern_return_t if unsuccessful. */ IOReturn (*getAsyncEventSource)(void * self, CFTypeRef * pSource); /*! @function copyMatchingElements @abstract Obtains a CFArrayRef containing the IOHIDDeviceDeviceInterface elements that match the passed matching dictionary. @discussion Objects contained in the returned array are of type IOHIDElementRef. Please see IOHIDElement.h for additional API information. Elemenet properties are prefixed by kIOHIDElement and declared in IOHIDKeys.h. @param self Pointer to the IOHIDDeviceDeviceInterface. @param matchingDict CFDictionaryRef containing the element properties to match on. @param pElements CFArrayRef containing matched elements. @param options Reserved for future use. Ignored in current implementation. Set to zero. @result Returns kIOReturnSuccess if successful or a kern_return_t if unsuccessful. */ IOReturn (*copyMatchingElements)(void * self, CFDictionaryRef matchingDict, CFArrayRef * pElements, IOOptionBits options); /*! @function setValue @abstract Sets the value for an element. @discussion If setting multiple element values, please consider using an IOHIDDeviceTransactionInterface with the kIOHIDTransactionDirectionTypeOutput direction. <br> <b>Note:</b> In order to make use of asynchronous behavior, the event source obtained using getAsyncEventSource must be added to a run loop. @param self Pointer to the IOHIDDeviceDeviceInterface. @param element IOHIDElementRef referencing the element of interest. @param value IOHIDValueRef containing element value to be set. @param timeout Time in milliseconds to wait before aborting request. @param callback Callback of type IOHIDValueCallback to be used after report data has been sent to the device. If null, this method will behave synchronously. @param context Pointer to data to be passed to the callback. @param options Reserved for future use. Ignored in current implementation. Set to zero. @result Returns kIOReturnSuccess if successful or a kern_return_t if unsuccessful. */ IOReturn (*setValue)(void * self, IOHIDElementRef element, IOHIDValueRef value, uint32_t timeout, IOHIDValueCallback callback, void * context, IOOptionBits options); /*! @function getValue @abstract Obtains the current value for an element. @discussion If an element of type kIOHIDElementTypeFeature is passed, this method will issue a request to the IOHIDDevice. Otherwise, this will return the last value reported by the IOHIDDevice. If requesting multiple feature element values, please consider using an IOHIDDeviceTransactionInterface with the kIOHIDTransactionDirectionTypeInput direction. <br> <b>Note:</b> In order to make use of asynchronous behavior, the event source obtained using getAsyncEventSource must be added to a run loop. @param self Pointer to the IOHIDDeviceDeviceInterface. @param element IOHIDElementRef referencing the element of interest. @param pValue Pointer to a IOHIDValueRef to return the element value. @param timeout Time in milliseconds to wait before aborting request. @param callback Callback of type IOHIDReportCallback to be used when element value has been received from the device. If null, this method will behave synchronously. @param context Pointer to data to be passed to the callback. @param options Reserved for future use. Ignored in current implementation. Set to zero. @result Returns kIOReturnSuccess if successful or a kern_return_t if unsuccessful. */ IOReturn (*getValue)(void * self, IOHIDElementRef element, IOHIDValueRef * pValue, uint32_t timeout, IOHIDValueCallback callback, void * context, IOOptionBits options); /*! @function setInputReportCallback @abstract Sets the input report callback to be used when data is received from the Input pipe. @discussion In order to function properly, the event source obtained using getAsyncEventSource must be added to a run loop. @param self Pointer to the IOHIDDeviceDeviceInterface. @param report Pointer to a pre-allocated buffer to be filled and passed back via the callback. @param reportLength Length of the report buffer. @param callback Callback of type IOHIDReportCallback to be used when report data has been receieved by the IOHIDDevice. @param context Pointer to data to be passed to the callback. @param options Reserved for future use. Ignored in current implementation. Set to zero. @result Returns kIOReturnSuccess if successful or a kern_return_t if unsuccessful. */ IOReturn (*setInputReportCallback)(void * self, uint8_t * report, CFIndex reportLength, IOHIDReportCallback callback, void * context, IOOptionBits options); /*! @function setReport @abstract Sends a report of type kIOHIDReportTypeOutput or kIOHIDReportTypeFeature to the IOHIDDevice. @discussion This method is useful if specific knowledge of the unparsed report is known to the caller. Otherwise, using an IOHIDDeviceTransactionInterface with the kIOHIDTransactionDirectionTypeOutput direction is recommended. <br> <b>Note:</b> In order to make use of asynchronous behavior, the event source obtained using getAsyncEventSource must be added to a run loop. @param self Pointer to the IOHIDDeviceDeviceInterface. @param reportType The report type. @param reportID The report id. @param report Pointer to a buffer containing the report data to be sent. @param reportLength Length of the report buffer. @param timeout Timeout in milliseconds for issuing the setReport. @param callback Callback of type IOHIDReportCallback to be used after report data has been sent to the device. If null, this method will behave synchronously. @param context Pointer to data to be passed to the callback. @param options Reserved for future use. Ignored in current implementation. Set to zero. @result Returns kIOReturnSuccess if successful or a kern_return_t if unsuccessful. */ IOReturn (*setReport)(void * self, IOHIDReportType reportType, uint32_t reportID, const uint8_t * report, CFIndex reportLength, uint32_t timeout, IOHIDReportCallback callback, void * context, IOOptionBits options); /*! @function getReport @abstract Obtains a report of type kIOHIDReportTypeInput or kIOHIDReportTypeFeature from the IOHIDDevice. @discussion This method is useful if specific knowledge of the unparsed report is known to the caller. Otherwise, using an IOHIDDeviceTransactionInterface with the kIOHIDTransactionDirectionTypeInput direction is recommended. <br> <b>Note:</b> In order to make use of asynchronous behavior, the event source obtained using getAsyncEventSource must be added to a run loop. @param self Pointer to the IOHIDDeviceDeviceInterface. @param reportType The report type. @param reportID The report id. @param report Pointer to a pre-allocated buffer to be filled. @param pReportLength Length of the report buffer. When finished, this will contain the actual length of the report. @param timeout Timeout in milliseconds for issuing the getReport. @param callback Callback of type IOHIDReportCallback to be used when report data has been received from the device. If null, this method will behave synchronously. @param context Pointer to data to be passed to the callback. @param options Reserved for future use. Ignored in current implementation. Set to zero. @result Returns kIOReturnSuccess if successful or a kern_return_t if unsuccessful. */ IOReturn (*getReport)(void * self, IOHIDReportType reportType, uint32_t reportID, uint8_t * report, CFIndex * pReportLength, uint32_t timeout, IOHIDReportCallback callback, void * context, IOOptionBits options); #endif // } } IOHIDDeviceDeviceInterface; #define IOHID_DEVICE_DEVICE_FUNCS_V2 \ IOReturn (*setInputReportWithTimeStampCallback)(void * self, uint8_t * report, CFIndex reportLength, IOHIDReportWithTimeStampCallback callback, void * context, IOOptionBits options) /*! @interface IOHIDDeviceTimeStampedDeviceInterface @abstract The object you use to access HID devices from user space, returned by version 2.1 of the IOHIDFamily. @discussion The functions listed here include all of the functions from the IOHIDDeviceDeviceInterface. <b>Note:</b> Please note that methods declared in this interface follow the copy/get/set conventions. */ typedef struct IOHIDDeviceTimeStampedDeviceInterface { IUNKNOWN_C_GUTS; IOHID_DEVICE_DEVICE_FUNCS_V1; #ifdef IOHID_DEVICE_DEVICE_FUNCS_V2 // { IOHID_DEVICE_DEVICE_FUNCS_V2; #else // } { /*! @function setInputReportWithTimeStampCallback @abstract Sets the input report callback to be used when data is received from the Input pipe. @discussion In order to function properly, the event source obtained using getAsyncEventSource must be added to a run loop. @param self Pointer to the IOHIDDeviceDeviceInterface. @param report Pointer to a pre-allocated buffer to be filled and passed back via the callback. @param reportLength Length of the report buffer. @param callback Callback of type IOHIDReportWithTimeStampCallback to be used when report data has been receieved by the IOHIDDevice. @param context Pointer to data to be passed to the callback. @param options Reserved for future use. Ignored in current implementation. Set to zero. @result Returns kIOReturnSuccess if successful or a kern_return_t if unsuccessful. */ IOReturn (*setInputReportWithTimeStampCallback)(void * self, uint8_t * report, CFIndex reportLength, IOHIDReportWithTimeStampCallback callback, void * context, IOOptionBits options); #endif // } } IOHIDDeviceTimeStampedDeviceInterface; /*! @interface IOHIDDeviceQueueInterface @abstract The object you use to access a HID queue from user space, returned by version 1.5 of the IOHIDFamily. @discussion The functions listed here will work with any version of the IOHIDDeviceQueueInterface. This behavior is useful when you need to keep track of all values of an input element, rather than just the most recent one. <br> <b>Note:</b>Absolute element values (based on a fixed origin) will only be placed on a queue if there is a change in value. */ typedef struct IOHIDDeviceQueueInterface { IUNKNOWN_C_GUTS; /*! @function getAsyncEventSource @abstract Obtains the event source for this IOHIDDeviceQueueInterface instance. @discussion The returned event source can be of type CFRunLoopSourceRef or CFRunLoopTimerRef. @param self Pointer to the IOHIDDeviceQueueInterface. @param pSource Pointer to a CFType to return the run loop event source. @result Returns kIOReturnSuccess if successful or a kern_return_t if unsuccessful. */ IOReturn (*getAsyncEventSource)(void * self, CFTypeRef * pSource); /*! @function setDepth @abstract Sets the depth for this IOHIDDeviceQueueInterface instance. @discussion Regardless of element value size, queue will guarantee n=depth elements will be serviced. @param self Pointer to the IOHIDDeviceTransactionInterface. @param depth The maximum number of elements in the queue before the oldest elements in the queue begin to be lost. @param options Reserved for future use. Ignored in current implementation. Set to zero. @result Returns kIOReturnSuccess if successful or a kern_return_t if unsuccessful. */ IOReturn (*setDepth)(void *self, uint32_t depth, IOOptionBits options); /*! @function getDepth @abstract Obtains the queue depth for this IOHIDDeviceQueueInterface instance. @param self Pointer to the IOHIDDeviceQueueInterface. @param pDepth Pointer to a uint32_t to obtain the number of elements that can be serviced by the queue. @result Returns kIOReturnSuccess if successful or a kern_return_t if unsuccessful. */ IOReturn (*getDepth)(void *self, uint32_t * pDepth); /*! @function addElement @abstract Adds an element to this IOHIDDeviceQueueInterface instance. @param self Pointer to the IOHIDDeviceQueueInterface. @param element IOHIDElementRef referencing the element to be added to the queue. @param options Reserved for future use. Ignored in current implementation. Set to zero. @result Returns kIOReturnSuccess if successful or a kern_return_t if unsuccessful. */ IOReturn (*addElement)(void * self, IOHIDElementRef element, IOOptionBits options); /*! @function removeElement @abstract Removes an element from this IOHIDDeviceQueueInterface instance. @param self Pointer to the IOHIDDeviceQueueInterface. @param element IOHIDElementRef referencing the element to be removed from the queue. @param options Reserved for future use. Ignored in current implementation. Set to zero. @result Returns kIOReturnSuccess if successful or a kern_return_t if unsuccessful. */ IOReturn (*removeElement)(void * self, IOHIDElementRef element, IOOptionBits options); /*! @function containsElement @abstract Determines whether an element has been added to this IOHIDDeviceQueueInterface instance. @param self Pointer to the IOHIDDeviceQueueInterface. @param element IOHIDElementRef referencing the element to be be found in the queue. @param pValue Pointer to a Boolean to return whether or not the element was found in the queue. @param options Reserved for future use. Ignored in current implementation. Set to zero. @result Returns kIOReturnSuccess if successful or a kern_return_t if unsuccessful. */ IOReturn (*containsElement)(void * self, IOHIDElementRef element, Boolean * pValue, IOOptionBits options); /*! @function start @abstract Starts element value delivery to the queue. @param self Pointer to the IOHIDDeviceQueueInterface. @param options Reserved for future use. Ignored in current implementation. Set to zero. @result Returns kIOReturnSuccess if successful or a kern_return_t if unsuccessful. */ IOReturn (*start)(void * self, IOOptionBits options); /*! @function stop @abstract Stops element value delivery to the queue. @param self Pointer to the IOHIDDeviceQueueInterface. @param options Reserved for future use. Ignored in current implementation. Set to zero. @result Returns kIOReturnSuccess if successful or a kern_return_t if unsuccessful. */ IOReturn (*stop)(void * self, IOOptionBits options); /*! @function setValueAvailableCallback @abstract Sets callback to be used when the queue transitions to non-empty. @discussion In order to make use of asynchronous behavior, the event source obtained using getAsyncEventSource must be added to a run loop. @param self Pointer to the IOHIDDeviceQueueInterface. @param callback Callback of type IOHIDCallback to be used when data is placed on the queue. @param context Pointer to data to be passed to the callback. @result Returns kIOReturnSuccess if successful or a kern_return_t if unsuccessful. */ IOReturn (*setValueAvailableCallback)(void * self, IOHIDCallback callback, void * context); /*! @function copyNextValue @abstract Dequeues a retained copy of an element value from the head of an IOHIDDeviceQueueInterface. @discussion Because the value is a retained copy, it is up to the caller to release the value using CFRelease. Use with setValueCallback to avoid polling the queue for data. @param self Pointer to the IOHIDDeviceQueueInterface. @param pValue Pointer to a IOHIDValueRef to return the value at the head of the queue. @param timeout Timeout in milliseconds before aborting an attempt to dequeue a value from the head of a queue. @param options Reserved for future use. Ignored in current implementation. Set to zero. @result Returns kIOReturnSuccess if successful, kIOReturnUnderrun if data is unavailble, or a kern_return_t if unsuccessful. */ IOReturn (*copyNextValue)(void * self, IOHIDValueRef * pValue, uint32_t timeout, IOOptionBits options); } IOHIDDeviceQueueInterface; /*! @interface IOHIDDeviceTransactionInterface @abstract The object you use to access a HID transaction from user space, returned by version 1.5 of the IOHIDFamily. @discussion The functions listed here will work with any version of the IOHIDDeviceTransactionInterface. This functionality is useful when either setting or getting the values for multiple parsed elements. */ typedef struct IOHIDDeviceTransactionInterface { IUNKNOWN_C_GUTS; /*! @function getAsyncEventSource @abstract Obtains the event source for this IOHIDDeviceTransactionInterface instance. @discussion The returned event source can be of type CFRunLoopSourceRef or CFRunLoopTimerRef. @param self Pointer to the IOHIDDeviceTransactionInterface. @param pSource Pointer to a CFType to return the run loop event source. @result Returns kIOReturnSuccess if successful or a kern_return_t if unsuccessful. */ IOReturn (*getAsyncEventSource)(void * self, CFTypeRef * pSource); /*! @function setDirection @abstract Sets the direction for this IOHIDDeviceTransactionInterface instance. @discussion Direction constants are declared in IOHIDTransactionDirectionType. Changing directions is useful when dealing with elements of type kIOHIDElementTypeFeature as you use the transaction to both set and get element values. @param self Pointer to the IOHIDDeviceTransactionInterface. @param direction Transaction direction of type IOHIDTransactionDirectionType. @param options Reserved for future use. Ignored in current implementation. Set to zero. @result Returns kIOReturnSuccess if successful or a kern_return_t if unsuccessful. */ IOReturn (*setDirection)(void * self, IOHIDTransactionDirectionType direction, IOOptionBits options); /*! @function getDirection @abstract Obtains the direction for this IOHIDDeviceTransactionInterface instance. @discussion Direction constants are declared in IOHIDTransactionDirectionType. @param self Pointer to the IOHIDDeviceTransactionInterface. @param pDirection Pointer to a IOHIDTransactionDirectionType to obtain transaction direction. @result Returns kIOReturnSuccess if successful or a kern_return_t if unsuccessful. */ IOReturn (*getDirection)(void * self, IOHIDTransactionDirectionType * pDirection); /*! @function addElement @abstract Adds an element to this IOHIDDeviceTransactionInterface instance. @param self Pointer to the IOHIDDeviceTransactionInterface. @param element IOHIDElementRef referencing the element to be added to the transaction. @param options Reserved for future use. Ignored in current implementation. Set to zero. @result Returns kIOReturnSuccess if successful or a kern_return_t if unsuccessful. */ IOReturn (*addElement)(void * self, IOHIDElementRef element, IOOptionBits options); /*! @function removeElement @abstract Removes an element from this IOHIDDeviceTransactionInterface instance. @param self Pointer to the IOHIDDeviceTransactionInterface. @param element IOHIDElementRef referencing the element to be removed from the transaction. @param options Reserved for future use. Ignored in current implementation. Set to zero. @result Returns kIOReturnSuccess if successful or a kern_return_t if unsuccessful. */ IOReturn (*removeElement)(void * self, IOHIDElementRef element, IOOptionBits options); /*! @function containsElement @abstract Checks whether an element has been added to this IOHIDDeviceTransactionInterface instance. @param self Pointer to the IOHIDDeviceTransactionInterface. @param element IOHIDElementRef referencing the element to be be found in the transaction. @param pValue Pointer to a Boolean to return whether or not the element was found in the transaction. @param options Reserved for future use. Ignored in current implementation. Set to zero. @result Returns kIOReturnSuccess if successful or a kern_return_t if unsuccessful. */ IOReturn (*containsElement)(void * self, IOHIDElementRef element, Boolean * pValue, IOOptionBits options); /*! @function setValue @abstract Sets the transaction value for an element in this IOHIDDeviceTransactionInterface instance. @discussion This method is intended for use with transaction of direction kIOHIDTransactionDirectionTypeOutput. Use the kIOHIDTransactionOptionDefaultOutputValue option to set the default element value. @param self Pointer to the IOHIDDeviceTransactionInterface. @param element IOHIDElementRef referencing the element of interest. @param value IOHIDValueRef referencing element value to be used in the transaction. @param options See IOHIDTransactionOption. @result Returns kIOReturnSuccess if successful or a kern_return_t if unsuccessful. */ IOReturn (*setValue)(void * self, IOHIDElementRef element, IOHIDValueRef value, IOOptionBits options); /*! @function getValue @abstract Obtains the transaction value for an element in this IOHIDDeviceTransactionInterface instance. @discussion Use the kIOHIDTransactionOptionDefaultOutputValue option to get the default element value. @param self Pointer to the IOHIDDeviceTransactionInterface. @param element IOHIDElementRef referencing the element of interest. @param pValue Pointer to an IOHIDValueRef to return the element value of the transaction. @param options See IOHIDTransactionOption. @result Returns kIOReturnSuccess if successful or a kern_return_t if unsuccessful. */ IOReturn (*getValue)(void * self, IOHIDElementRef element, IOHIDValueRef *pValue, IOOptionBits options); /*! @function commit @abstract Commits element transaction to an IOHIDDevice in this IOHIDDeviceTransactionInterface instance. @discussion In regards to kIOHIDTransactionDirectionTypeOutput direction, default element values will be used if element values are not set. If neither are set, that element will be omitted from the commit. After a transaction is committed, transaction element values will be cleared and default values preserved. <br> <b>Note:</b> It is possible for elements from different reports to be present in a given transaction causing a commit to transcend multiple reports. Keep this in mind when setting a timeout. @param self Pointer to the IOHIDDeviceTransactionInterface. @param timeout Timeout in milliseconds for issuing the transaction. @param callback Callback of type IOHIDCallback to be used when transaction has been completed. If null, this method will behave synchronously. @param context Pointer to data to be passed to the callback. @param options Reserved for future use. Ignored in current implementation. Set to zero. @result Returns kIOReturnSuccess if successful or a kern_return_t if unsuccessful. */ IOReturn (*commit)(void * self, uint32_t timeout, IOHIDCallback callback, void * context, IOOptionBits options); /*! @function clear @abstract Clears element transaction values for an IOHIDDeviceTransactionInterface. @discussion In regards to kIOHIDTransactionDirectionTypeOutput direction, default element values will be preserved. @param self Pointer to the IOHIDDeviceTransactionInterface. @param options Reserved for future use. Ignored in current implementation. Set to zero. @result Returns kIOReturnSuccess if successful or a kern_return_t if unsuccessful. */ IOReturn (*clear)(void * self, IOOptionBits options); } IOHIDDeviceTransactionInterface; __END_DECLS #endif /* _IOKIT_HID_IOHIDDEVICEPLUGIN_H */
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/hid/IOHIDDevice.h
/* * Copyright (c) 1999-2008 Apple Computer, Inc. All Rights Reserved. * * @APPLE_LICENSE_HEADER_START@ * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this * file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_LICENSE_HEADER_END@ */ #ifndef _IOKIT_HID_IOHIDDEVICE_USER_H #define _IOKIT_HID_IOHIDDEVICE_USER_H #include <CoreFoundation/CoreFoundation.h> #include <IOKit/hid/IOHIDBase.h> /*! @header IOHIDDevice IOHIDDevice defines a Human Interface Device (HID) object, which interacts with an IOHIDDevicePlugIn object that typically maps to an object in the kernel. IOHIDDevice is used to communicate with a single HID device in order to obtain or set device properties, element values, and reports. IOHIDDevice is also a CFType object and as such conforms to all the conventions expected such object. <p> All of the information described in this document is contained in the header file <font face="Courier New,Courier,Monaco">IOHIDDevice.h</font> found at <font face="Courier New,Courier,Monaco">/System/Library/Frameworks/IOKit.framework/Headers/hid/IOHIDDevice.h</font>. */ __BEGIN_DECLS CF_ASSUME_NONNULL_BEGIN CF_IMPLICIT_BRIDGING_ENABLED /*! @function IOHIDDeviceGetTypeID @abstract Returns the type identifier of all IOHIDDevice instances. */ CF_EXPORT CFTypeID IOHIDDeviceGetTypeID(void) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDDeviceCreate @abstract Creates an element from an io_service_t. @discussion The io_service_t passed in this method must reference an object in the kernel of type IOHIDDevice. @param allocator Allocator to be used during creation. @param service Reference to service object in the kernel. @result Returns a new IOHIDDeviceRef. */ CF_EXPORT IOHIDDeviceRef _Nullable IOHIDDeviceCreate( CFAllocatorRef _Nullable allocator, io_service_t service) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDDeviceGetService @abstract Returns the io_service_t for an IOHIDDevice, if it has one. @discussion If the IOHIDDevice references an object in the kernel, this is used to get the io_service_t for that object. @param device Reference to an IOHIDDevice. @result Returns the io_service_t if the IOHIDDevice has one, or MACH_PORT_NULL if it does not. */ CF_EXPORT io_service_t IOHIDDeviceGetService( IOHIDDeviceRef device) AVAILABLE_MAC_OS_X_VERSION_10_6_AND_LATER; /*! @function IOHIDDeviceOpen @abstract Opens a HID device for communication. @discussion Before the client can issue commands that change the state of the device, it must have succeeded in opening the device. This establishes a link between the client's task and the actual device. To establish an exclusive link use the kIOHIDOptionsTypeSeizeDevice option. @param device Reference to an IOHIDDevice. @param options Option bits to be sent down to the device. @result Returns kIOReturnSuccess if successful. */ CF_EXPORT IOReturn IOHIDDeviceOpen( IOHIDDeviceRef device, IOOptionBits options) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDDeviceClose @abstract Closes communication with a HID device. @discussion This closes a link between the client's task and the actual device. @param device Reference to an IOHIDDevice. @param options Option bits to be sent down to the device. @result Returns kIOReturnSuccess if successful. */ CF_EXPORT IOReturn IOHIDDeviceClose( IOHIDDeviceRef device, IOOptionBits options) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDDeviceConformsTo @abstract Convenience function that scans the Application Collection elements to see if it conforms to the provided usagePage and usage. @discussion Examples of Application Collection usages pairs are: <br> usagePage = kHIDPage_GenericDesktop <br> usage = kHIDUsage_GD_Mouse <br> <b>or</b> <br> usagePage = kHIDPage_GenericDesktop <br> usage = kHIDUsage_GD_Keyboard @param device Reference to an IOHIDDevice. @param usagePage Device usage page @param usage Device usage @result Returns TRUE if device conforms to provided usage. */ CF_EXPORT Boolean IOHIDDeviceConformsTo( IOHIDDeviceRef device, uint32_t usagePage, uint32_t usage) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDDeviceGetProperty @abstract Obtains a property from an IOHIDDevice. @discussion Property keys are prefixed by kIOHIDDevice and declared in <IOKit/hid/IOHIDKeys.h>. @param device Reference to an IOHIDDevice. @param key CFStringRef containing key to be used when querying the device. @result Returns CFTypeRef containing the property. */ CF_EXPORT CFTypeRef _Nullable IOHIDDeviceGetProperty( IOHIDDeviceRef device, CFStringRef key) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDDeviceSetProperty @abstract Sets a property for an IOHIDDevice. @discussion Property keys are prefixed by kIOHIDDevice and declared in <IOKit/hid/IOHIDKeys.h>. @param device Reference to an IOHIDDevice. @param key CFStringRef containing key to be used when modifiying the device property. @param property CFTypeRef containg the property to be set. @result Returns TRUE if successful. */ CF_EXPORT Boolean IOHIDDeviceSetProperty( IOHIDDeviceRef device, CFStringRef key, CFTypeRef property) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDDeviceCopyMatchingElements @abstract Obtains HID elements that match the criteria contained in the matching dictionary. @discussion Matching keys are prefixed by kIOHIDElement and declared in <IOKit/hid/IOHIDKeys.h>. Passing a NULL dictionary will result in all device elements being returned. @param device Reference to an IOHIDDevice. @param matching CFDictionaryRef containg element matching criteria. @param options Reserved for future use. @result Returns CFArrayRef containing multiple IOHIDElement object. */ CF_EXPORT CFArrayRef _Nullable IOHIDDeviceCopyMatchingElements( IOHIDDeviceRef device, CFDictionaryRef _Nullable matching, IOOptionBits options) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDDeviceScheduleWithRunLoop @abstract Schedules HID device with run loop. @discussion Formally associates device with client's run loop. Scheduling this device with the run loop is necessary before making use of any asynchronous APIs. @param device Reference to an IOHIDDevice. @param runLoop RunLoop to be used when scheduling any asynchronous activity. @param runLoopMode Run loop mode to be used when scheduling any asynchronous activity. */ CF_EXPORT void IOHIDDeviceScheduleWithRunLoop( IOHIDDeviceRef device, CFRunLoopRef runLoop, CFStringRef runLoopMode) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDDeviceUnscheduleFromRunLoop @abstract Unschedules HID device with run loop. @discussion Formally disassociates device with client's run loop. @param device Reference to an IOHIDDevice. @param runLoop RunLoop to be used when unscheduling any asynchronous activity. @param runLoopMode Run loop mode to be used when unscheduling any asynchronous activity. */ CF_EXPORT void IOHIDDeviceUnscheduleFromRunLoop( IOHIDDeviceRef device, CFRunLoopRef runLoop, CFStringRef runLoopMode) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! * @function IOHIDDeviceSetDispatchQueue * * @abstract * Sets the dispatch queue to be associated with the IOHIDDevice. * This is necessary in order to receive asynchronous events from the kernel. * * @discussion * An IOHIDDevice should not be associated with both a runloop and * dispatch queue. A call to IOHIDDeviceSetDispatchQueue should only be made once. * * After a dispatch queue is set, the IOHIDDevice must make a call to activate * via IOHIDDeviceActivate and cancel via IOHIDDeviceCancel. All calls to "Register" * functions should be done before activation and not after cancellation. * * @param device * Reference to an IOHIDDevice * * @param queue * The dispatch queue to which the event handler block will be submitted. */ CF_EXPORT void IOHIDDeviceSetDispatchQueue( IOHIDDeviceRef device, dispatch_queue_t queue) __OSX_AVAILABLE(10.15) __IOS_AVAILABLE(13.0) __TVOS_AVAILABLE(13.0) __WATCHOS_AVAILABLE(6.0); /*! * @function IOHIDDeviceSetCancelHandler * * @abstract * Sets a cancellation handler for the dispatch queue associated with * IOHIDDeviceSetDispatchQueue. * * @discussion * The cancellation handler (if specified) will be will be submitted to the * device's dispatch queue in response to a call to IOHIDDeviceCancel after * all the events have been handled. * * IOHIDDeviceSetCancelHandler should not be used when scheduling with * a run loop. * * The IOHIDDeviceRef should only be released after the device has been * cancelled, and the cancel handler has been called. This is to ensure all * asynchronous objects are released. For example: * * dispatch_block_t cancelHandler = dispatch_block_create(0, ^{ * CFRelease(device); * }); * IOHIDDeviceSetCancelHandler(device, cancelHandler); * IOHIDDeviceActivate(device); * IOHIDDeviceCancel(device); * * @param device * Reference to an IOHIDDevice. * * @param handler * The cancellation handler block to be associated with the dispatch queue. */ CF_EXPORT void IOHIDDeviceSetCancelHandler( IOHIDDeviceRef device, dispatch_block_t handler) __OSX_AVAILABLE(10.15) __IOS_AVAILABLE(13.0) __TVOS_AVAILABLE(13.0) __WATCHOS_AVAILABLE(6.0); /*! * @function IOHIDDeviceActivate * * @abstract * Activates the IOHIDDevice object. * * @discussion * An IOHIDDevice object associated with a dispatch queue is created * in an inactive state. The object must be activated in order to * receive asynchronous events from the kernel. * * A dispatch queue must be set via IOHIDDeviceSetDispatchQueue before * activation. * * An activated device must be cancelled via IOHIDDeviceCancel. All calls * to "Register" functions should be done before activation * and not after cancellation. * * Calling IOHIDDeviceActivate on an active IOHIDDevice has no effect. * * @param device * Reference to an IOHIDDevice */ CF_EXPORT void IOHIDDeviceActivate( IOHIDDeviceRef device) __OSX_AVAILABLE(10.15) __IOS_AVAILABLE(13.0) __TVOS_AVAILABLE(13.0) __WATCHOS_AVAILABLE(6.0); /*! * @function IOHIDDeviceCancel * * @abstract * Cancels the IOHIDDevice preventing any further invocation * of its event handler block. * * @discussion * Cancelling prevents any further invocation of the event handler block for * the specified dispatch queue, but does not interrupt an event handler * block that is already in progress. * * Explicit cancellation of the IOHIDDevice is required, no implicit * cancellation takes place. * * Calling IOHIDDeviceCancel on an already cancelled queue has no effect. * * The IOHIDDeviceRef should only be released after the device has been * cancelled, and the cancel handler has been called. This is to ensure all * asynchronous objects are released. For example: * * dispatch_block_t cancelHandler = dispatch_block_create(0, ^{ * CFRelease(device); * }); * IOHIDDeviceSetCancelHandler(device, cancelHandler); * IOHIDDeviceActivate(device); * IOHIDDeviceCancel(device); * * @param device * Reference to an IOHIDDevice */ CF_EXPORT void IOHIDDeviceCancel( IOHIDDeviceRef device) __OSX_AVAILABLE(10.15) __IOS_AVAILABLE(13.0) __TVOS_AVAILABLE(13.0) __WATCHOS_AVAILABLE(6.0); /*! @function IOHIDDeviceRegisterRemovalCallback @abstract Registers a callback to be used when a IOHIDDevice is removed. @discussion In most cases this occurs when a device is unplugged. If a dispatch queue is set, this call must occur before activation. @param device Reference to an IOHIDDevice. @param callback Pointer to a callback method of type IOHIDCallback. @param context Pointer to data to be passed to the callback. */ CF_EXPORT void IOHIDDeviceRegisterRemovalCallback( IOHIDDeviceRef device, IOHIDCallback _Nullable callback, void * _Nullable context) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDDeviceRegisterInputValueCallback @abstract Registers a callback to be used when an input value is issued by the device. @discussion An input element refers to any element of type kIOHIDElementTypeInput and is usually issued by interrupt driven reports. If more specific element values are desired, you can specify matching criteria via IOHIDDeviceSetInputValueMatching and IOHIDDeviceSetInputValueMatchingMultiple. If a dispatch queue is set, this call must occur before activation. @param device Reference to an IOHIDDevice. @param callback Pointer to a callback method of type IOHIDValueCallback. @param context Pointer to data to be passed to the callback. */ CF_EXPORT void IOHIDDeviceRegisterInputValueCallback( IOHIDDeviceRef device, IOHIDValueCallback _Nullable callback, void * _Nullable context) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDDeviceRegisterInputReportCallback @abstract Registers a callback to be used when an input report is issued by the device. @discussion An input report is an interrupt driver report issued by the device. If a dispatch queue is set, this call must occur before activation. @param device Reference to an IOHIDDevice. @param report Pointer to preallocated buffer in which to copy inbound report data. @param reportLength Length of preallocated buffer. @param callback Pointer to a callback method of type IOHIDReportCallback. @param context Pointer to data to be passed to the callback. */ CF_EXPORT void IOHIDDeviceRegisterInputReportCallback( IOHIDDeviceRef device, uint8_t * report, CFIndex reportLength, IOHIDReportCallback _Nullable callback, void * _Nullable context) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDDeviceRegisterInputReportWithTimeStampCallback @abstract Registers a timestamped callback to be used when an input report is issued by the device. @discussion An input report is an interrupt driver report issued by the device. If a dispatch queue is set, this call must occur before activation. @param device Reference to an IOHIDDevice. @param report Pointer to preallocated buffer in which to copy inbound report data. @param reportLength Length of preallocated buffer. @param callback Pointer to a callback method of type IOHIDReportWithTimeStampCallback. @param context Pointer to data to be passed to the callback. */ CF_EXPORT void IOHIDDeviceRegisterInputReportWithTimeStampCallback( IOHIDDeviceRef device, uint8_t * report, CFIndex reportLength, IOHIDReportWithTimeStampCallback _Nullable callback, void * _Nullable context) AVAILABLE_MAC_OS_X_VERSION_10_10_AND_LATER; /*! @function IOHIDDeviceSetInputValueMatching @abstract Sets matching criteria for input values received via IOHIDDeviceRegisterInputValueCallback. @discussion Matching keys are prefixed by kIOHIDElement and declared in <IOKit/hid/IOHIDKeys.h>. Passing a NULL dictionary will result in all devices being enumerated. Any subsequent calls will cause the hid manager to release previously matched input elements and restart the matching process using the revised criteria. If interested in multiple, specific device elements, please defer to using IOHIDDeviceSetInputValueMatchingMultiple. If a dispatch queue is set, this call must occur before activation. @param device Reference to an IOHIDDevice. @param matching CFDictionaryRef containg device matching criteria. */ CF_EXPORT void IOHIDDeviceSetInputValueMatching( IOHIDDeviceRef device, CFDictionaryRef _Nullable matching) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDDeviceSetInputValueMatchingMultiple @abstract Sets multiple matching criteria for input values received via IOHIDDeviceRegisterInputValueCallback. @discussion Matching keys are prefixed by kIOHIDElement and declared in <IOKit/hid/IOHIDKeys.h>. This method is useful if interested in multiple, specific elements. If a dispatch queue is set, this call must occur before activation. @param device Reference to an IOHIDDevice. @param multiple CFArrayRef containing multiple CFDictionaryRef objects containg input element matching criteria. */ CF_EXPORT void IOHIDDeviceSetInputValueMatchingMultiple( IOHIDDeviceRef device, CFArrayRef _Nullable multiple) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDDeviceSetValue @abstract Sets a value for an element. @discussion This method behaves synchronously and will block until the report has been issued to the device. It is only relevent for either output or feature type elements. If setting values for multiple elements you may want to consider using IOHIDDeviceSetValueMultiple or IOHIDTransaction. @param device Reference to an IOHIDDevice. @param element IOHIDElementRef whose value is to be modified. @param value IOHIDValueRef containing value to be set. @result Returns kIOReturnSuccess if successful. */ CF_EXPORT IOReturn IOHIDDeviceSetValue( IOHIDDeviceRef device, IOHIDElementRef element, IOHIDValueRef value) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDDeviceSetValueMultiple @abstract Sets multiple values for multiple elements. @discussion This method behaves synchronously and will block until the report has been issued to the device. It is only relevent for either output or feature type elements. @param device Reference to an IOHIDDevice. @param multiple CFDictionaryRef where key is IOHIDElementRef and value is IOHIDValueRef. @result Returns kIOReturnSuccess if successful. */ CF_EXPORT IOReturn IOHIDDeviceSetValueMultiple( IOHIDDeviceRef device, CFDictionaryRef multiple) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDDeviceSetValueWithCallback @abstract Sets a value for an element and returns status via a completion callback. @discussion This method behaves asynchronously and will invoke the callback once the report has been issued to the device. It is only relevent for either output or feature type elements. If setting values for multiple elements you may want to consider using IOHIDDeviceSetValueWithCallback or IOHIDTransaction. @param device Reference to an IOHIDDevice. @param element IOHIDElementRef whose value is to be modified. @param value IOHIDValueRef containing value to be set. @param timeout CFTimeInterval containing the timeout. @param callback Pointer to a callback method of type IOHIDValueCallback. @param context Pointer to data to be passed to the callback. @result Returns kIOReturnSuccess if successful. */ CF_EXPORT IOReturn IOHIDDeviceSetValueWithCallback( IOHIDDeviceRef device, IOHIDElementRef element, IOHIDValueRef value, CFTimeInterval timeout, IOHIDValueCallback _Nullable callback, void * _Nullable context) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDDeviceSetValueMultipleWithCallback @abstract Sets multiple values for multiple elements and returns status via a completion callback. @discussion This method behaves asynchronously and will invoke the callback once the report has been issued to the device. It is only relevent for either output or feature type elements. @param device Reference to an IOHIDDevice. @param multiple CFDictionaryRef where key is IOHIDElementRef and value is IOHIDValueRef. @param timeout CFTimeInterval containing the timeout. @param callback Pointer to a callback method of type IOHIDValueMultipleCallback. @param context Pointer to data to be passed to the callback. @result Returns kIOReturnSuccess if successful. */ CF_EXPORT IOReturn IOHIDDeviceSetValueMultipleWithCallback( IOHIDDeviceRef device, CFDictionaryRef multiple, CFTimeInterval timeout, IOHIDValueMultipleCallback _Nullable callback, void * _Nullable context) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDDeviceGetValue @abstract Gets a value for an element. @discussion This method behaves synchronously and return back immediately for input type element. If requesting a value for a feature element, this will block until the report has been issued to the device. If obtaining values for multiple elements you may want to consider using IOHIDDeviceCopyValueMultiple or IOHIDTransaction. @param device Reference to an IOHIDDevice. @param element IOHIDElementRef whose value is to be obtained. @param pValue Pointer to IOHIDValueRef to be obtained. @result Returns kIOReturnSuccess if successful. */ CF_EXPORT IOReturn IOHIDDeviceGetValue( IOHIDDeviceRef device, IOHIDElementRef element, IOHIDValueRef _Nonnull * _Nonnull pValue) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; typedef CF_ENUM(uint32_t, IOHIDDeviceGetValueOptions) { kIOHIDDeviceGetValueWithUpdate = 0x00020000, // force value update (get report will be send to the device) kIOHIDDeviceGetValueWithoutUpdate = 0x00040000 // get last value }; /*! @function IOHIDDeviceGetValueWithOptions @abstract Gets a value for an element. @discussion This method behaves synchronously and return back immediately for input type element. If requesting a value for a feature element, this will block until the report has been issued to the device. If obtaining values for multiple elements you may want to consider using IOHIDDeviceCopyValueMultiple or IOHIDTransaction. @param device Reference to an IOHIDDevice. @param element IOHIDElementRef whose value is to be obtained. @param pValue Pointer to IOHIDValueRef to be obtained. @param options (see IOHIDDeviceGetValueOptions). @result Returns kIOReturnSuccess if successful. */ IOReturn IOHIDDeviceGetValueWithOptions ( IOHIDDeviceRef device, IOHIDElementRef element, IOHIDValueRef _Nonnull * _Nonnull pValue, uint32_t options) AVAILABLE_MAC_OS_X_VERSION_10_13_AND_LATER; /*! @function IOHIDDeviceCopyValueMultiple @abstract Copies a values for multiple elements. @discussion This method behaves synchronously and return back immediately for input type element. If requesting a value for a feature element, this will block until the report has been issued to the device. @param device Reference to an IOHIDDevice. @param elements CFArrayRef containing multiple IOHIDElementRefs whose values are to be obtained. @param pMultiple Pointer to CFDictionaryRef where the keys are the provided elements and the values are the requested values. @result Returns kIOReturnSuccess if successful. */ CF_EXPORT IOReturn IOHIDDeviceCopyValueMultiple( IOHIDDeviceRef device, CFArrayRef elements, CFDictionaryRef _Nullable * _Nullable pMultiple) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDDeviceGetValueWithCallback @abstract Gets a value for an element and returns status via a completion callback. @discussion This method behaves asynchronusly and is only relevent for either output or feature type elements. If obtaining values for multiple elements you may want to consider using IOHIDDeviceCopyValueMultipleWithCallback or IOHIDTransaction. @param device Reference to an IOHIDDevice. @param element IOHIDElementRef whose value is to be obtained. @param pValue Pointer to IOHIDValueRef to be passedback. @param timeout CFTimeInterval containing the timeout. @param callback Pointer to a callback method of type IOHIDValueCallback. @param context Pointer to data to be passed to the callback. @result Returns kIOReturnSuccess if successful. */ CF_EXPORT IOReturn IOHIDDeviceGetValueWithCallback( IOHIDDeviceRef device, IOHIDElementRef element, IOHIDValueRef _Nonnull * _Nonnull pValue, CFTimeInterval timeout, IOHIDValueCallback _Nullable callback, void * _Nullable context) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDDeviceCopyValueMultipleWithCallback @abstract Copies a values for multiple elements and returns status via a completion callback. @discussion This method behaves asynchronusly and is only relevent for either output or feature type elements. @param device Reference to an IOHIDDevice. @param elements CFArrayRef containing multiple IOHIDElementRefs whose values are to be obtained. @param pMultiple Pointer to CFDictionaryRef where the keys are the provided elements and the values are the requested values. @param timeout CFTimeInterval containing the timeout. @param callback Pointer to a callback method of type IOHIDValueMultipleCallback. @param context Pointer to data to be passed to the callback. @result Returns kIOReturnSuccess if successful. */ CF_EXPORT IOReturn IOHIDDeviceCopyValueMultipleWithCallback( IOHIDDeviceRef device, CFArrayRef elements, CFDictionaryRef _Nullable * _Nullable pMultiple, CFTimeInterval timeout, IOHIDValueMultipleCallback _Nullable callback, void * _Nullable context) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDDeviceSetReport @abstract Sends a report to the device. @discussion This method behaves synchronously and will block until the report has been issued to the device. It is only relevent for either output or feature type reports. @param device Reference to an IOHIDDevice. @param reportType Type of report being sent. @param reportID ID of the report being sent. If the device supports multiple reports, this should also be set in the first byte of the report. @param report The report bytes to be sent to the device. @param reportLength The length of the report to be sent to the device. @result Returns kIOReturnSuccess if successful. */ CF_EXPORT IOReturn IOHIDDeviceSetReport( IOHIDDeviceRef device, IOHIDReportType reportType, CFIndex reportID, const uint8_t * report, CFIndex reportLength) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDDeviceSetReportWithCallback @abstract Sends a report to the device. @discussion This method behaves asynchronously and will block until the report has been issued to the device. It is only relevent for either output or feature type reports. @param device Reference to an IOHIDDevice. @param reportType Type of report being sent. @param reportID ID of the report being sent. If the device supports multiple reports, this should also be set in the first byte of the report. @param report The report bytes to be sent to the device. @param reportLength The length of the report to be sent to the device. @param timeout CFTimeInterval containing the timeout. @param callback Pointer to a callback method of type IOHIDReportCallback. @param context Pointer to data to be passed to the callback. @result Returns kIOReturnSuccess if successful. */ CF_EXPORT IOReturn IOHIDDeviceSetReportWithCallback( IOHIDDeviceRef device, IOHIDReportType reportType, CFIndex reportID, const uint8_t * report, CFIndex reportLength, CFTimeInterval timeout, IOHIDReportCallback _Nullable callback, void * _Nullable context) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDDeviceGetReport @abstract Obtains a report from the device. @discussion This method behaves synchronously and will block until the report has been received from the device. This is only intended for feature reports because of sporadic devicesupport for polling input reports. Please defer to using IOHIDDeviceRegisterInputReportCallback for obtaining input reports. @param device Reference to an IOHIDDevice. @param reportType Type of report being requested. @param reportID ID of the report being requested. @param report Pointer to preallocated buffer in which to copy inbound report data. @param pReportLength Pointer to length of preallocated buffer. This value will be modified to refect the length of the returned report. @result Returns kIOReturnSuccess if successful. */ CF_EXPORT IOReturn IOHIDDeviceGetReport( IOHIDDeviceRef device, IOHIDReportType reportType, CFIndex reportID, uint8_t * report, CFIndex * pReportLength) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDDeviceGetReportWithCallback @abstract Obtains a report from the device. @discussion This method behaves asynchronously and will block until the report has been received from the device. This is only intended for feature reports because of sporadic devicesupport for polling input reports. Please defer to using IOHIDDeviceRegisterInputReportCallback for obtaining input reports. @param device Reference to an IOHIDDevice. @param reportType Type of report being requested. @param reportID ID of the report being requested. @param report Pointer to preallocated buffer in which to copy inbound report data. @param pReportLength Pointer to length of preallocated buffer. @param pReportLength Pointer to length of preallocated buffer. This value will be modified to refect the length of the returned report. @param callback Pointer to a callback method of type IOHIDReportCallback. @param context Pointer to data to be passed to the callback. @result Returns kIOReturnSuccess if successful. */ CF_EXPORT IOReturn IOHIDDeviceGetReportWithCallback( IOHIDDeviceRef device, IOHIDReportType reportType, CFIndex reportID, uint8_t * report, CFIndex * pReportLength, CFTimeInterval timeout, IOHIDReportCallback callback, void * context) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; CF_IMPLICIT_BRIDGING_DISABLED CF_ASSUME_NONNULL_END __END_DECLS #endif /* _IOKIT_HID_IOHIDDEVICE_USER_H */
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/hid/IOHIDQueue.h
/* * Copyright (c) 1999-2008 Apple Computer, Inc. All Rights Reserved. * * @APPLE_LICENSE_HEADER_START@ * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this * file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_LICENSE_HEADER_END@ */ #ifndef _IOKIT_HID_IOHIDQUEUE_USER_H #define _IOKIT_HID_IOHIDQUEUE_USER_H #include <CoreFoundation/CoreFoundation.h> #include <IOKit/hid/IOHIDBase.h> /*! @header IOHIDQueue IOHIDQueue defines an object used to queue values from input parsed items (IOHIDElement) contained within a Human Interface Device (HID) object. This object is useful when you need to keep track of all values of an input element, rather than just the most recent one. IOHIDQueue is a CFType object and as such conforms to all the conventions expected such object. <p> IOHIDQueue should be considered optional and is only useful for working with complex input elements. These elements include those whose length are greater than sizeof(CFIndex) or elements that are duplicate items. Whenever possible please defer to using IOHIDManagerRegisterInputValueCallback or IOHIDDeviceRegisterInputValueCallback. <p> <b>Note:</b>Absolute element values (based on a fixed origin) will only be placed on a queue if there is a change in value. <p> This documentation assumes that you have a basic understanding of the material contained in <a href="http://developer.apple.com/documentation/DeviceDrivers/Conceptual/AccessingHardware/index.html"><i>Accessing Hardware From Applications</i></a> For definitions of I/O Kit terms used in this documentation, such as matching dictionary, family, and driver, see the overview of I/O Kit terms and concepts in the "Device Access and the I/O Kit" chapter of <i>Accessing Hardware From Applications</i>. This documentation also assumes you have read <a href="http://developer.apple.com/documentation/DeviceDrivers/HumanInterfaceDeviceForceFeedback-date.html"><i>Human Interface Device & Force Feedback</i></a>. Please review documentation before using this reference. <p> All of the information described in this document is contained in the header file <font face="Courier New,Courier,Monaco">IOHIDQueue.h</font> found at <font face="Courier New,Courier,Monaco">/System/Library/Frameworks/IOKit.framework/Headers/hid/IOHIDQueue.h</font>. */ __BEGIN_DECLS CF_ASSUME_NONNULL_BEGIN CF_IMPLICIT_BRIDGING_ENABLED /*! @typedef IOHIDQueueRef This is the type of a reference to the IOHIDQueue. */ typedef struct CF_BRIDGED_TYPE(id) __IOHIDQueue * IOHIDQueueRef; /*! @function IOHIDQueueGetTypeID @abstract Returns the type identifier of all IOHIDQueue instances. */ CF_EXPORT CFTypeID IOHIDQueueGetTypeID(void) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDQueueCreate @abstract Creates an IOHIDQueue object for the specified device. @discussion Take care in specifying an appropriate depth to prevent dropping events. @param allocator Allocator to be used during creation. @param device IOHIDDevice object @param depth The number of values that can be handled by the queue. @param options Reserved for future use. @result Returns a new IOHIDQueueRef. */ CF_EXPORT IOHIDQueueRef _Nullable IOHIDQueueCreate( CFAllocatorRef _Nullable allocator, IOHIDDeviceRef device, CFIndex depth, IOOptionBits options) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDQueueGetDevice @abstract Obtain the device associated with the queue. @param queue IOHIDQueue to be queried. @result Returns the a reference to the device. */ CF_EXPORT IOHIDDeviceRef IOHIDQueueGetDevice( IOHIDQueueRef queue) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDQueueGetDepth @abstract Obtain the depth of the queue. @param queue IOHIDQueue to be queried. @result Returns the queue depth. */ CF_EXPORT CFIndex IOHIDQueueGetDepth( IOHIDQueueRef queue) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDQueueSetDepth @abstract Sets the depth of the queue. @discussion Set the appropriate depth value based on the number of elements contained in a queue. @param queue IOHIDQueue object to be modified. @param depth The new queue depth. */ CF_EXPORT void IOHIDQueueSetDepth( IOHIDQueueRef queue, CFIndex depth) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDQueueAddElement @abstract Adds an element to the queue @param queue IOHIDQueue object to be modified. @param element Element to be added to the queue. */ CF_EXPORT void IOHIDQueueAddElement( IOHIDQueueRef queue, IOHIDElementRef element) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDQueueRemoveElement @abstract Removes an element from the queue @param queue IOHIDQueue object to be modified. @param element Element to be removed from the queue. */ CF_EXPORT void IOHIDQueueRemoveElement( IOHIDQueueRef queue, IOHIDElementRef element) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDQueueContainsElement @abstract Queries the queue to determine if elemement has been added. @param queue IOHIDQueue object to be queried. @param element Element to be queried. @result Returns true or false depending if element is present. */ CF_EXPORT Boolean IOHIDQueueContainsElement( IOHIDQueueRef queue, IOHIDElementRef element) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDQueueStart @abstract Starts element value delivery to the queue. @discussion When a dispatch queue is assocaited with the IOHIDQueue via IOHIDQueueSetDispatchQueue, the queue does not need to be explicity started, this will be done during activation when IOHIDQueueActivate is called. @param queue IOHIDQueue object to be started. */ CF_EXPORT void IOHIDQueueStart( IOHIDQueueRef queue) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDQueueStop @abstract Stops element value delivery to the queue. @discussion When a dispatch queue is assocaited with the IOHIDQueue via IOHIDQueueSetDispatchQueue, the queue does not need to be explicity stopped, this will be done during cancellation when IOHIDQueueCancel is called. @param queue IOHIDQueue object to be stopped. */ CF_EXPORT void IOHIDQueueStop( IOHIDQueueRef queue) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDQueueScheduleWithRunLoop @abstract Schedules queue with run loop. @discussion Formally associates queue with client's run loop. Scheduling this queue with the run loop is necessary before making use of any asynchronous APIs. @param queue IOHIDQueue object to be modified. @param runLoop RunLoop to be used when scheduling any asynchronous activity. @param runLoopMode Run loop mode to be used when scheduling any asynchronous activity. */ CF_EXPORT void IOHIDQueueScheduleWithRunLoop( IOHIDQueueRef queue, CFRunLoopRef runLoop, CFStringRef runLoopMode) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDQueueUnscheduleFromRunLoop @abstract Unschedules queue with run loop. @discussion Formally disassociates queue with client's run loop. @param queue IOHIDQueue object to be modified. @param runLoop RunLoop to be used when scheduling any asynchronous activity. @param runLoopMode Run loop mode to be used when scheduling any asynchronous activity. */ CF_EXPORT void IOHIDQueueUnscheduleFromRunLoop( IOHIDQueueRef queue, CFRunLoopRef runLoop, CFStringRef runLoopMode) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! * @function IOHIDQueueSetDispatchQueue * * @abstract * Sets the dispatch queue to be associated with the IOHIDQueue. * This is necessary in order to receive asynchronous events from the kernel. * * @discussion * An IOHIDQueue should not be associated with both a runloop and * dispatch queue. A call to IOHIDQueueSetDispatchQueue should only be made once. * * After a dispatch queue is set, the IOHIDQueue must make a call to activate * via IOHIDQueueActivate and cancel via IOHIDQueueCancel. All calls to "Register" * functions should be done before activation and not after cancellation. * * @param queue * Reference to an IOHIDQueue * * @param dispatchQueue * The dispatch queue to which the event handler block will be submitted. */ CF_EXPORT void IOHIDQueueSetDispatchQueue( IOHIDQueueRef queue, dispatch_queue_t dispatchQueue) __OSX_AVAILABLE(10.15) __IOS_AVAILABLE(13.0) __TVOS_AVAILABLE(13.0) __WATCHOS_AVAILABLE(6.0); /*! * @function IOHIDQueueSetCancelHandler * * @abstract * Sets a cancellation handler for the dispatch queue associated with * IOHIDQueueSetDispatchQueue. * * @discussion * The cancellation handler (if specified) will be will be submitted to the * queue's dispatch queue in response to a call to IOHIDQueueCancel after all * the events have been handled. * * IOHIDQueueSetCancelHandler should not be used when scheduling with * a run loop. * * The IOHIDQueueRef should only be released after the queue has been * cancelled, and the cancel handler has been called. This is to ensure all * asynchronous objects are released. For example: * * dispatch_block_t cancelHandler = dispatch_block_create(0, ^{ * CFRelease(queue); * }); * IOHIDQueueSetCancelHandler(queue, cancelHandler); * IOHIDQueueActivate(queue); * IOHIDQueueCancel(queue); * * @param queue * Reference to an IOHIDQueue. * * @param handler * The cancellation handler block to be associated with the dispatch queue. */ CF_EXPORT void IOHIDQueueSetCancelHandler( IOHIDQueueRef queue, dispatch_block_t handler) __OSX_AVAILABLE(10.15) __IOS_AVAILABLE(13.0) __TVOS_AVAILABLE(13.0) __WATCHOS_AVAILABLE(6.0); /*! * @function IOHIDQueueActivate * * @abstract * Activates the IOHIDQueue object. * * @discussion * An IOHIDQueue object associated with a dispatch queue is created * in an inactive state. The object must be activated in order to * receive asynchronous events from the kernel. * * A dispatch queue must be set via IOHIDQueueSetDispatchQueue before * activation. * * An activated queue must be cancelled via IOHIDQueueCancel. All calls * to "Register" functions should be done before activation * and not after cancellation. * * Calling IOHIDQueueActivate on an active IOHIDQueue has no effect. * * @param queue * Reference to an IOHIDQueue */ CF_EXPORT void IOHIDQueueActivate( IOHIDQueueRef queue) __OSX_AVAILABLE(10.15) __IOS_AVAILABLE(13.0) __TVOS_AVAILABLE(13.0) __WATCHOS_AVAILABLE(6.0); /*! * @function IOHIDQueueCancel * * @abstract * Cancels the IOHIDQueue preventing any further invocation * of its event handler block. * * @discussion * Cancelling prevents any further invocation of the event handler block for * the specified dispatch queue, but does not interrupt an event handler * block that is already in progress. * * Explicit cancellation of the IOHIDQueue is required, no implicit * cancellation takes place. * * Calling IOHIDQueueCancel on an already cancelled queue has no effect. * * The IOHIDQueueRef should only be released after the queue has been * cancelled, and the cancel handler has been called. This is to ensure all * asynchronous objects are released. For example: * * dispatch_block_t cancelHandler = dispatch_block_create(0, ^{ * CFRelease(queue); * }); * IOHIDQueueSetCancelHandler(queue, cancelHandler); * IOHIDQueueActivate(queue); * IOHIDQueueCancel(queue); * * @param queue * Reference to an IOHIDQueue */ CF_EXPORT void IOHIDQueueCancel( IOHIDQueueRef queue) __OSX_AVAILABLE(10.15) __IOS_AVAILABLE(13.0) __TVOS_AVAILABLE(13.0) __WATCHOS_AVAILABLE(6.0); /*! @function IOHIDQueueRegisterValueAvailableCallback @abstract Sets callback to be used when the queue transitions to non-empty. @discussion In order to make use of asynchronous behavior, the queue needs to be scheduled with the run loop or dispatch queue. If a dispatch queue is set, this call must occur before activation. @param queue IOHIDQueue object to be modified. @param callback Callback of type IOHIDCallback to be used when data is placed on the queue. @param context Pointer to data to be passed to the callback. */ CF_EXPORT void IOHIDQueueRegisterValueAvailableCallback( IOHIDQueueRef queue, IOHIDCallback callback, void * _Nullable context) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDQueueCopyNextValue @abstract Dequeues a retained copy of an element value from the head of an IOHIDQueue. @discussion Because the value is a retained copy, it is up to the caller to release the value using CFRelease. Use with setValueCallback to avoid polling the queue for data. @param queue IOHIDQueue object to be queried. @result Returns valid IOHIDValueRef if data is available. */ CF_EXPORT IOHIDValueRef _Nullable IOHIDQueueCopyNextValue( IOHIDQueueRef queue) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDQueueCopyNextValueWithTimeout @abstract Dequeues a retained copy of an element value from the head of an IOHIDQueue. This method will block until either a value is available or it times out. @discussion Because the value is a retained copy, it is up to the caller to release the value using CFRelease. Use with setValueCallback to avoid polling the queue for data. @param queue IOHIDQueue object to be queried. @param timeout Timeout before aborting an attempt to dequeue a value from the head of a queue. @result Returns valid IOHIDValueRef if data is available. */ CF_EXPORT IOHIDValueRef _Nullable IOHIDQueueCopyNextValueWithTimeout( IOHIDQueueRef queue, CFTimeInterval timeout) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; CF_IMPLICIT_BRIDGING_DISABLED CF_ASSUME_NONNULL_END __END_DECLS #endif /* _IOKIT_HID_IOHIDQUEUE_USER_H */
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/hid/IOHIDKeys.h
/* * * @APPLE_LICENSE_HEADER_START@ * * Copyright (c) 1999-2020 Apple Computer, Inc. All Rights Reserved. * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this * file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_LICENSE_HEADER_END@ */ #ifndef _IOKIT_HID_IOHIDKEYS_H_ #define _IOKIT_HID_IOHIDKEYS_H_ #include <sys/cdefs.h> #include <IOKit/hidsystem/IOHIDParameter.h> #include <IOKit/IOReturn.h> #include <IOKit/IOMessage.h> #include <IOKit/hid/IOHIDProperties.h> #include <IOKit/hid/IOHIDDeviceTypes.h> #include <IOKit/hid/IOHIDDeviceKeys.h> __BEGIN_DECLS /* The following keys are used to search the IORegistry for HID related services */ /* This is used to find HID Devices in the IORegistry */ #define kIOHIDDeviceKey "IOHIDDevice" /*! @defined HID Device Property Keys @abstract Keys that represent properties of a paticular device. @discussion Keys that represent properties of a paticular device. Can be added to your matching dictionary when refining searches for HID devices. <br><br> <b>Please note:</b><br> kIOHIDPrimaryUsageKey and kIOHIDPrimaryUsagePageKey are no longer rich enough to describe a device's capabilities. Take, for example, a device that describes both a keyboard and a mouse in the same descriptor. The previous behavior was to only describe the keyboard behavior with the primary usage and usage page. Needless to say, this would sometimes cause a program interested in mice to skip this device when matching. <br> Thus we have added 3 additional keys: <ul> <li>kIOHIDDeviceUsageKey</li> <li>kIOHIDDeviceUsagePageKey</li> <li>kIOHIDDeviceUsagePairsKey</li> </ul> kIOHIDDeviceUsagePairsKey is used to represent an array of dictionaries containing key/value pairs referenced by kIOHIDDeviceUsageKey and kIOHIDDeviceUsagePageKey. These usage pairs describe all application type collections (behaviors) defined by the device. <br><br> An application intersted in only matching on one criteria would only add the kIOHIDDeviceUsageKey and kIOHIDDeviceUsagePageKey keys to the matching dictionary. If it is interested in a device that has multiple behaviors, the application would instead add an array or dictionaries referenced by kIOHIDDeviceUsagePairsKey to his matching dictionary. */ #define kIOHIDVendorIDSourceKey "VendorIDSource" #define kIOHIDStandardTypeKey "StandardType" #define kIOHIDSampleIntervalKey "SampleInterval" #define kIOHIDResetKey "Reset" #define kIOHIDKeyboardLanguageKey "KeyboardLanguage" #define kIOHIDAltHandlerIdKey "alt_handler_id" #define kIOHIDDisplayIntegratedKey "DisplayIntegrated" #define kIOHIDProductIDMaskKey "ProductIDMask" #define kIOHIDProductIDArrayKey "ProductIDArray" #define kIOHIDPowerOnDelayNSKey "HIDPowerOnDelayNS" #define kIOHIDCategoryKey "Category" #define kIOHIDMaxResponseLatencyKey "MaxResponseLatency" #define kIOHIDUniqueIDKey "UniqueID" #define kIOHIDModelNumberKey "ModelNumber" #define kIOHIDTransportUSBValue "USB" #define kIOHIDTransportBluetoothValue "Bluetooth" #define kIOHIDTransportBluetoothLowEnergyValue "BluetoothLowEnergy" #define kIOHIDTransportAIDBValue "AID" #define kIOHIDTransportI2CValue "I2C" #define kIOHIDTransportSPIValue "SPI" #define kIOHIDTransportSerialValue "Serial" #define kIOHIDTransportIAPValue "iAP" #define kIOHIDTransportAirPlayValue "AirPlay" #define kIOHIDTransportSPUValue "SPU" #define kIOHIDTransportBTAACPValue "BT-AACP" #define kIOHIDCategoryAutomotiveValue "Automotive" /*! @define kIOHIDElementKey @abstract Keys that represents an element property. @discussion Property for a HID Device or element dictionary. Elements can be heirarchical, so they can contain other elements. */ #define kIOHIDElementKey "Elements" /*! @defined HID Element Dictionary Keys @abstract Keys that represent properties of a particular elements. @discussion These keys can also be added to a matching dictionary when searching for elements via copyMatchingElements. */ #define kIOHIDElementCookieKey "ElementCookie" #define kIOHIDElementTypeKey "Type" #define kIOHIDElementCollectionTypeKey "CollectionType" #define kIOHIDElementUsageKey "Usage" #define kIOHIDElementUsagePageKey "UsagePage" #define kIOHIDElementMinKey "Min" #define kIOHIDElementMaxKey "Max" #define kIOHIDElementScaledMinKey "ScaledMin" #define kIOHIDElementScaledMaxKey "ScaledMax" #define kIOHIDElementSizeKey "Size" #define kIOHIDElementReportSizeKey "ReportSize" #define kIOHIDElementReportCountKey "ReportCount" #define kIOHIDElementReportIDKey "ReportID" #define kIOHIDElementIsArrayKey "IsArray" #define kIOHIDElementIsRelativeKey "IsRelative" #define kIOHIDElementIsWrappingKey "IsWrapping" #define kIOHIDElementIsNonLinearKey "IsNonLinear" #define kIOHIDElementHasPreferredStateKey "HasPreferredState" #define kIOHIDElementHasNullStateKey "HasNullState" #define kIOHIDElementFlagsKey "Flags" #define kIOHIDElementUnitKey "Unit" #define kIOHIDElementUnitExponentKey "UnitExponent" #define kIOHIDElementNameKey "Name" #define kIOHIDElementValueLocationKey "ValueLocation" #define kIOHIDElementDuplicateIndexKey "DuplicateIndex" #define kIOHIDElementParentCollectionKey "ParentCollection" #define kIOHIDElementVariableSizeKey "VariableSize" #ifndef __ppc__ #define kIOHIDElementVendorSpecificKey "VendorSpecific" #else #define kIOHIDElementVendorSpecificKey "VendorSpecifc" #endif /*! @defined HID Element Match Keys @abstract Keys used for matching particular elements. @discussion These keys should only be used with a matching dictionary when searching for elements via copyMatchingElements. */ #define kIOHIDElementCookieMinKey "ElementCookieMin" #define kIOHIDElementCookieMaxKey "ElementCookieMax" #define kIOHIDElementUsageMinKey "UsageMin" #define kIOHIDElementUsageMaxKey "UsageMax" /*! @defined kIOHIDElementCalibrationMinKey @abstract The minimum bounds for a calibrated value. */ #define kIOHIDElementCalibrationMinKey "CalibrationMin" /*! @defined kIOHIDElementCalibrationMaxKey @abstract The maximum bounds for a calibrated value. */ #define kIOHIDElementCalibrationMaxKey "CalibrationMax" /*! @defined kIOHIDElementCalibrationSaturationMinKey @abstract The mininum tolerance to be used when calibrating a logical element value. @discussion The saturation property is used to allow for slight differences in the minimum and maximum value returned by an element. */ #define kIOHIDElementCalibrationSaturationMinKey "CalibrationSaturationMin" /*! @defined kIOHIDElementCalibrationSaturationMaxKey @abstract The maximum tolerance to be used when calibrating a logical element value. @discussion The saturation property is used to allow for slight differences in the minimum and maximum value returned by an element. */ #define kIOHIDElementCalibrationSaturationMaxKey "CalibrationSaturationMax" /*! @defined kIOHIDElementCalibrationDeadZoneMinKey @abstract The minimum bounds near the midpoint of a logical value in which the value is ignored. @discussion The dead zone property is used to allow for slight differences in the idle value returned by an element. */ #define kIOHIDElementCalibrationDeadZoneMinKey "CalibrationDeadZoneMin" /*! @defined kIOHIDElementCalibrationDeadZoneMinKey @abstract The maximum bounds near the midpoint of a logical value in which the value is ignored. @discussion The dead zone property is used to allow for slight differences in the idle value returned by an element. */ #define kIOHIDElementCalibrationDeadZoneMaxKey "CalibrationDeadZoneMax" /*! @defined kIOHIDElementCalibrationGranularityKey @abstract The scale or level of detail returned in a calibrated element value. @discussion Values are rounded off such that if granularity=0.1, values after calibration are 0, 0.1, 0.2, 0.3, etc. */ #define kIOHIDElementCalibrationGranularityKey "CalibrationGranularity" /*! @defined kIOHIDKeyboardSupportsEscKey @abstract Describe if keyboard device supports esc key. @discussion Keyboard devices having full HID keyboard descriptor can specify if esc key is actually supported or not. For new macs with TouchBar this is ideal scenario where keyboard descriptor by defaultspecifies presence of esc key but through given property client can check if key is present or not */ #define kIOHIDKeyboardSupportsEscKey "HIDKeyboardSupportsEscKey" /*! @typedef IOHIDOptionsType @abstract Options for opening a device via IOHIDLib. @constant kIOHIDOptionsTypeNone Default option. @constant kIOHIDOptionsTypeSeizeDevice Used to open exclusive communication with the device. This will prevent the system and other clients from receiving events from the device. */ enum { kIOHIDOptionsTypeNone = 0x00, kIOHIDOptionsTypeSeizeDevice = 0x01 }; typedef uint32_t IOHIDOptionsType; /*! @typedef IOHIDQueueOptionsType @abstract Options for creating a queue via IOHIDLib. @constant kIOHIDQueueOptionsTypeNone Default option. @constant kIOHIDQueueOptionsTypeEnqueueAll Force the IOHIDQueue to enqueue all events, relative or absolute, regardless of change. */ enum { kIOHIDQueueOptionsTypeNone = 0x00, kIOHIDQueueOptionsTypeEnqueueAll = 0x01 }; typedef uint32_t IOHIDQueueOptionsType; /*! @typedef IOHIDStandardType @abstract Type to define what industrial standard the device is referencing. @constant kIOHIDStandardTypeANSI ANSI. @constant kIOHIDStandardTypeISO ISO. @constant kIOHIDStandardTypeJIS JIS. @constant kIOHIDStandardTypeUnspecified. */ enum { kIOHIDStandardTypeANSI = 0x0, kIOHIDStandardTypeISO = 0x1, kIOHIDStandardTypeJIS = 0x2, kIOHIDStandardTypeUnspecified = 0xFFFFFFFF, }; typedef uint32_t IOHIDStandardType; #define kIOHIDDigitizerGestureCharacterStateKey "DigitizerCharacterGestureState" /* * kIOHIDSystemButtonPressedDuringDarkBoot - Used to message that a wake button was pressed during dark boot */ #define kIOHIDSystemButtonPressedDuringDarkBoot iokit_family_msg(sub_iokit_hidsystem, 7) /*! @defined IOHIDKeyboard Keys @abstract Keys that represent parameters of keyboards. @discussion Legacy IOHIDKeyboard keys, formerly in IOHIDPrivateKeys. See IOHIDServiceKeys.h for the new keys. */ #define kIOHIDKeyboardCapsLockDelay "CapsLockDelay" #define kIOHIDKeyboardEjectDelay "EjectDelay" /*! @defined kFnFunctionUsageMapKey @abstract top row key remapping for consumer usages @discussion string of comma separated uint64_t value representing (usagePage<<32) | usage pairs */ #define kFnFunctionUsageMapKey "FnFunctionUsageMap" /*! @defined kFnKeyboardUsageMapKey @abstract top row key reampping for consumer usages @discussion string of comma separated uint64_t value representing (usagePage<<32) | usage pairs */ #define kFnKeyboardUsageMapKey "FnKeyboardUsageMap" #define kNumLockKeyboardUsageMapKey "NumLockKeyboardUsageMap" #define kKeyboardUsageMapKey "KeyboardUsageMap" /*! @defined kIOHIDDeviceOpenedByEventSystemKey @abstract Property set when corresponding event service object opened by HID event system @discussion boolean value */ #define kIOHIDDeviceOpenedByEventSystemKey "DeviceOpenedByEventSystem" /*! * @define kIOHIDDeviceSuspendKey * * @abstract * Boolean property set on a user space IOHIDDeviceRef to suspend report delivery * to registered callbacks. * * @discussion * When set to true, the callbacks registered via the following API will not be invoked: * IOHIDDeviceRegisterInputReportCallback * IOHIDDeviceRegisterInputReportWithTimeStampCallback * IOHIDDeviceRegisterInputValueCallback * To resume report delivery, this property should be set to false. */ #define kIOHIDDeviceSuspendKey "IOHIDDeviceSuspend" /*! * @define kIOHIDMaxReportBufferCountKey * @abstract Number property published for an IOHIDDevice that contains the * report buffer count. * @discussion IOHIDLibUserClient connections to an IOHIDDevice created * using IOKit/hid/IOHIDDevice.h/IOHIDDeviceCreate have a report * buffer, where reports can be enqueued and dispatched in quick succession. * A report buffer count can be published to help determine the * correct queue size that will be able to handle incoming report * rates. The queue size is determined by report buffer count * multiplied by the report buffer's entry size, this total size is * limited to 131072 bytes. This property can be set in the * IOHIDDevice's IOKit property table, or on the individual * IOHIDLibUserClient connection using IOHIDDeviceSetProperty. * (See kIOHIDReportBufferEntrySizeKey). */ #define kIOHIDMaxReportBufferCountKey "MaxReportBufferCount" /*! * @define kIOHIDReportBufferEntrySizeKey * @abstract Number property published on an IOHIDDevice that contains * the report buffer's entry size. * @discussion This key describes the entry size of the reports (in bytes) * in the report buffer between an IOHIDLibUserClient and its * associated IOHIDDevice. The queue size is determined by the * report buffer's report count multiplied by the entry size. The * buffer entry size is currently limited to 8167 bytes, exceeding * this value will result in a minimum queue size. This property * can be set in the IOHIDDevice's IOKit property table, or on the individual * IOHIDLibUserClient connection using IOHIDDeviceSetProperty. * (See kIOHIDMaxReportBufferCountKey). */ #define kIOHIDReportBufferEntrySizeKey "ReportBufferEntrySize" /*! @defined kIOHIDSensorPropertyReportIntervalKey @abstract Property to get or set the Report Interval in us of supported sensor devices @discussion Corresponds to kHIDUsage_Snsr_Property_ReportInterval in a sensor device's descriptor. */ #define kIOHIDSensorPropertyReportIntervalKey kIOHIDReportIntervalKey /*! @defined kIOHIDSensorPropertySampleIntervalKey @abstract Property to get or set the Sample Interval in us of supported sensor devices @discussion Corresponds to kHIDUsage_Snsr_Property_SamplingRate in a sensor device's descriptor. */ #define kIOHIDSensorPropertySampleIntervalKey kIOHIDSampleIntervalKey /*! @defined kIOHIDSensorPropertyBatchIntervalKey @abstract Property to get or set the Batch Interval / Report Latency in us of supported sensor devices @discussion Corresponds to kHIDUsage_Snsr_Property_ReportLatency in a sensor device's descriptor. */ #define kIOHIDSensorPropertyBatchIntervalKey kIOHIDBatchIntervalKey /*! @defined kIOHIDSensorPropertyReportLatencyKey @abstract Alias of kIOHIDSensorPropertyBatchIntervalKey */ #define kIOHIDSensorPropertyReportLatencyKey kIOHIDSensorPropertyBatchIntervalKey /*! @defined kIOHIDSensorPropertyMaxFIFOEventsKey @abstract Property to get or set the maximum FIFO event queue size of supported sensor devices @discussion Corresponds to kHIDUsage_Snsr_Property_MaxFIFOEvents in a sensor device's descriptor. */ #define kIOHIDSensorPropertyMaxFIFOEventsKey "MaxFIFOEvents" /*! @defined kIOHIDDigitizerSurfaceSwitchKey @abstract Property to turn on / of surface digitizer contact reporting @discussion To allow for better power management, a host may wish to indicate what it would like a touchpad digitizer to not report surface digitizer contacts by clearing this flag. By default, upon cold‐boot/power cycle, touchpads that support reporting surface contacts shall do so by default. */ #define kIOHIDDigitizerSurfaceSwitchKey "DigitizerSurfaceSwitch" /*! @defined kIOHIDPointerAccelerationSupportKey @abstract Property to turn enable/disable acceleration of relative pointer events @discussion A boolean value to enable devices that report movement precisely but using relative positions, if false the events from the device will not have acceleration applied to the event value calculation. If the key is not set then the device will have acceleration applied to it's events by default. */ #define kIOHIDPointerAccelerationSupportKey "HIDSupportsPointerAcceleration" /*! @defined kIOHIDScrollAccelerationSupportKey @abstract Property to turn enable/disable acceleration of scroll events @discussion A boolean value to enable devices that report scroll precisely but using relative positions, if false the events from the device will not have acceleration applied to the event value calculation. If the key is not set then the device will have acceleration applied to it's events by default. */ #define kIOHIDScrollAccelerationSupportKey "HIDSupportsScrollAcceleration" __END_DECLS #endif /* !_IOKIT_HID_IOHIDKEYS_H_ */
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/hid/IOHIDValue.h
/* * Copyright (c) 1999-2008 Apple Computer, Inc. All Rights Reserved. * * @APPLE_LICENSE_HEADER_START@ * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this * file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_LICENSE_HEADER_END@ */ #ifndef _IOKIT_HID_IOHIDELEMENTEVENT_H #define _IOKIT_HID_IOHIDELEMENTEVENT_H #include <CoreFoundation/CoreFoundation.h> #include <IOKit/hid/IOHIDBase.h> #include <IOKit/hid/IOHIDKeys.h> /*! @header IOHIDValue IOHIDValue defines a value at a given time from an parsed item (IOHIDElement) contained within a Human Interface Device (HID) object. It is used to obtain either integer or data element values along with scaled values based on physical or calibrated settings. IOHIDValue is a CFType object and as such conforms to all the conventions expected such object. <p> This documentation assumes that you have a basic understanding of the material contained in <a href="http://developer.apple.com/documentation/DeviceDrivers/Conceptual/AccessingHardware/index.html"><i>Accessing Hardware From Applications</i></a> For definitions of I/O Kit terms used in this documentation, such as matching dictionary, family, and driver, see the overview of I/O Kit terms and concepts in the "Device Access and the I/O Kit" chapter of <i>Accessing Hardware From Applications</i>. This documentation also assumes you have read <a href="http://developer.apple.com/documentation/DeviceDrivers/HumanInterfaceDeviceForceFeedback-date.html"><i>Human Interface Device & Force Feedback</i></a>. Please review documentation before using this reference. <p> All of the information described in this document is contained in the header file <font face="Courier New,Courier,Monaco">IOHIDValue.h</font> found at <font face="Courier New,Courier,Monaco">/System/Library/Frameworks/IOKit.framework/Headers/hid/IOHIDValue.h</font>. */ __BEGIN_DECLS CF_ASSUME_NONNULL_BEGIN CF_IMPLICIT_BRIDGING_ENABLED /*! @function IOHIDValueGetTypeID @abstract Returns the type identifier of all IOHIDValue instances. */ CF_EXPORT CFTypeID IOHIDValueGetTypeID(void) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDValueCreateWithIntegerValue @abstract Creates a new element value using an integer value. @discussion IOHIDValueGetTimeStamp should represent OS AbsoluteTime, not CFAbsoluteTime. To obtain the OS AbsoluteTime, please reference the APIs declared in <mach/mach_time.h> @param allocator The CFAllocator which should be used to allocate memory for the value. This parameter may be NULL in which case the current default CFAllocator is used. If this reference is not a valid CFAllocator, the behavior is undefined. @param element IOHIDElementRef associated with this value. @param timeStamp OS absolute time timestamp for this value. @param value Integer value to be copied to this object. @result Returns a reference to a new IOHIDValueRef. */ CF_EXPORT IOHIDValueRef IOHIDValueCreateWithIntegerValue(CFAllocatorRef _Nullable allocator, IOHIDElementRef element, uint64_t timeStamp, CFIndex value) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDValueCreateWithBytes @abstract Creates a new element value using byte data. @discussion IOHIDValueGetTimeStamp should represent OS AbsoluteTime, not CFAbsoluteTime. To obtain the OS AbsoluteTime, please reference the APIs declared in <mach/mach_time.h> @param allocator The CFAllocator which should be used to allocate memory for the value. This parameter may be NULL in which case the current default CFAllocator is used. If this reference is not a valid CFAllocator, the behavior is undefined. @param element IOHIDElementRef associated with this value. @param timeStamp OS absolute time timestamp for this value. @param bytes Pointer to a buffer of uint8_t to be copied to this object. @param length Number of bytes in the passed buffer. @result Returns a reference to a new IOHIDValueRef. */ CF_EXPORT IOHIDValueRef _Nullable IOHIDValueCreateWithBytes(CFAllocatorRef _Nullable allocator, IOHIDElementRef element, uint64_t timeStamp, const uint8_t * bytes, CFIndex length) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDValueCreateWithBytesNoCopy @abstract Creates a new element value using byte data without performing a copy. @discussion The timestamp value passed should represent OS AbsoluteTime, not CFAbsoluteTime. To obtain the OS AbsoluteTime, please reference the APIs declared in <mach/mach_time.h> @param allocator The CFAllocator which should be used to allocate memory for the value. This parameter may be NULL in which case the current default CFAllocator is used. If this reference is not a valid CFAllocator, the behavior is undefined. @param element IOHIDElementRef associated with this value. @param timeStamp OS absolute time timestamp for this value. @param bytes Pointer to a buffer of uint8_t to be referenced by this object. @param length Number of bytes in the passed buffer. @result Returns a reference to a new IOHIDValueRef. */ CF_EXPORT IOHIDValueRef _Nullable IOHIDValueCreateWithBytesNoCopy(CFAllocatorRef _Nullable allocator, IOHIDElementRef element, uint64_t timeStamp, const uint8_t * bytes, CFIndex length) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDValueGetElement @abstract Returns the element value associated with this IOHIDValueRef. @param value The value to be queried. If this parameter is not a valid IOHIDValueRef, the behavior is undefined. @result Returns a IOHIDElementRef referenced by this value. */ CF_EXPORT IOHIDElementRef IOHIDValueGetElement(IOHIDValueRef value) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDValueGetTimeStamp @abstract Returns the timestamp value contained in this IOHIDValueRef. @discussion The timestamp value returned represents OS AbsoluteTime, not CFAbsoluteTime. @param value The value to be queried. If this parameter is not a valid IOHIDValueRef, the behavior is undefined. @result Returns a uint64_t representing the timestamp of this value. */ CF_EXPORT uint64_t IOHIDValueGetTimeStamp(IOHIDValueRef value) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDValueGetLength @abstract Returns the size, in bytes, of the value contained in this IOHIDValueRef. @param value The value to be queried. If this parameter is not a valid IOHIDValueRef, the behavior is undefined. @result Returns length of the value. */ CF_EXPORT CFIndex IOHIDValueGetLength(IOHIDValueRef value) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDValueGetBytePtr @abstract Returns a byte pointer to the value contained in this IOHIDValueRef. @param value The value to be queried. If this parameter is not a valid IOHIDValueRef, the behavior is undefined. @result Returns a pointer to the value. */ CF_EXPORT const uint8_t * IOHIDValueGetBytePtr(IOHIDValueRef value) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDValueGetIntegerValue @abstract Returns an integer representaion of the value contained in this IOHIDValueRef. @discussion The value is based on the logical element value contained in the report returned by the device. @param value The value to be queried. If this parameter is not a valid IOHIDValueRef, the behavior is undefined. @result Returns an integer representation of the value. */ CF_EXPORT CFIndex IOHIDValueGetIntegerValue(IOHIDValueRef value) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDValueGetScaledValue @abstract Returns an scaled representaion of the value contained in this IOHIDValueRef based on the scale type. @discussion The scaled value is based on the range described by the scale type's min and max, such that: <br> scaledValue = ((value - min) * (scaledMax - scaledMin) / (max - min)) + scaledMin <br> <b>Note:</b> <br> There are currently two types of scaling that can be applied: <ul> <li><b>kIOHIDValueScaleTypePhysical</b>: Scales element value using the physical bounds of the device such that <b>scaledMin = physicalMin</b> and <b>scaledMax = physicalMax</b>. <li><b>kIOHIDValueScaleTypeCalibrated</b>: Scales element value such that <b>scaledMin = -1</b> and <b>scaledMax = 1</b>. This value will also take into account the calibration properties associated with this element. </ul> @param value The value to be queried. If this parameter is not a valid IOHIDValueRef, the behavior is undefined. @param type The type of scaling to be performed. @result Returns an scaled floating point representation of the value. */ CF_EXPORT double_t IOHIDValueGetScaledValue(IOHIDValueRef value, IOHIDValueScaleType type) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; CF_IMPLICIT_BRIDGING_DISABLED CF_ASSUME_NONNULL_END __END_DECLS #endif /* _IOKIT_HID_IOHIDELEMENTEVENT_H */
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/hid/IOHIDLib.h
/* * Copyright (c) 1999-2008 Apple Computer, Inc. All Rights Reserved. * * @APPLE_LICENSE_HEADER_START@ * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this * file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_LICENSE_HEADER_END@ */ #ifndef _IOKIT_HID_IOHIDLIB_H_ #define _IOKIT_HID_IOHIDLIB_H_ #include <CoreFoundation/CoreFoundation.h> #include <IOKit/IOTypes.h> #include <IOKit/IOReturn.h> #include <IOKit/hid/IOHIDBase.h> #include <IOKit/hid/IOHIDDevice.h> #include <IOKit/hid/IOHIDElement.h> #include <IOKit/hid/IOHIDKeys.h> #include <IOKit/hid/IOHIDLibObsolete.h> #include <IOKit/hid/IOHIDManager.h> #include <IOKit/hid/IOHIDQueue.h> #include <IOKit/hid/IOHIDUsageTables.h> #include <IOKit/hid/IOHIDValue.h> #include <IOKit/hid/IOHIDTransaction.h> #endif /* _IOKIT_HID_IOHIDLIB_H_ */
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/hid/IOHIDProperties.h
/* * Copyright (c) 2016 Apple Computer, Inc. All rights reserved. * * @APPLE_LICENSE_HEADER_START@ * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this * file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_LICENSE_HEADER_END@ */ #ifndef IOHIDProperties_h #define IOHIDProperties_h #include <IOKit/hid/IOHIDEventServiceKeys.h> /*! * @define kIOHIDMouseAccelerationType * * @abstract CFNumber that contains the mouse acceleration value. */ #define kIOHIDMouseAccelerationType "HIDMouseAcceleration" /*! * @define kIOHIDPointerButtonMode * * @abstract CFNumber containing the current pointer button mode. * See IOHIDButtonModes enumerator for possible modes. */ #define kIOHIDPointerButtonMode "HIDPointerButtonMode" #define kIOHIDPointerButtonModeKey kIOHIDPointerButtonMode /*! * @define kIOHIDUserUsageMapKey * * @abstract CFArray of dictionaries that contain user defined key mappings. */ #define kIOHIDUserKeyUsageMapKey "UserKeyMapping" /*! * @define kIOHIDKeyboardCapsLockDelayOverride * * @abstract CFNumber containing the delay (in ms) before the caps lock key is activated. */ #define kIOHIDKeyboardCapsLockDelayOverride "CapsLockDelayOverride" #define kIOHIDKeyboardCapsLockDelayOverrideKey kIOHIDKeyboardCapsLockDelayOverride /*! * @define kIOHIDServiceEjectDelayKey * * @abstract CFNumber containing the delay (in ms) before the eject key is activated. */ #define kIOHIDServiceEjectDelayKey "EjectDelay" /*! * @define kIOHIDServiceLockKeyDelayKey * * @abstract CFNumber containing the delay (in ms) before the lock key is activated. */ #define kIOHIDServiceLockKeyDelayKey "LockKeyDelay" /*! * @define kIOHIDServiceInitialKeyRepeatDelayKey * * @abstract CFNumber containing the delay (in ns) before the initial key repeat. * If value is 0, there are no repeats. */ #define kIOHIDServiceInitialKeyRepeatDelayKey "HIDInitialKeyRepeat" /*! * @define kIOHIDServiceKeyRepeatDelayKey * * @abstract CFNumber containing the delay (in ns) for subsequent key repeats. * If value is 0, there are no repeats (including initial). */ #define kIOHIDServiceKeyRepeatDelayKey "HIDKeyRepeat" /*! * @define kIOHIDIdleTimeMicrosecondsKey * * @abstract CFNumber containing the HID idle time in microseconds. */ #define kIOHIDIdleTimeMicrosecondsKey "HIDIdleTimeMicroseconds" /*! * @define kIOHIDServiceCapsLockStateKey * * @abstract CFBoolean for setting/getting the caps lock state of the * service. The caps lock LED will be updated to reflect the state. */ #define kIOHIDServiceCapsLockStateKey "HIDCapsLockState" #endif /* IOHIDProperties_h */
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/hid/IOHIDManager.h
/* * Copyright (c) 1999-2008 Apple Computer, Inc. All Rights Reserved. * * @APPLE_LICENSE_HEADER_START@ * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this * file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_LICENSE_HEADER_END@ */ #ifndef _IOKIT_HID_IOHIDMANAGER_H_ #define _IOKIT_HID_IOHIDMANAGER_H_ #include <IOKit/IOTypes.h> #include <IOKit/IOReturn.h> #include <IOKit/hid/IOHIDLib.h> #include <CoreFoundation/CoreFoundation.h> /*! @header IOHIDManager IOHIDManager defines an Human Interface Device (HID) managment object. It provides global interaction with managed HID devices such as discovery/removal and receiving input events. IOHIDManager is also a CFType object and as such conforms to all the conventions expected such object. <p> This documentation assumes that you have a basic understanding of the material contained in <a href="http://developer.apple.com/documentation/DeviceDrivers/Conceptual/AccessingHardware/index.html"><i>Accessing Hardware From Applications</i></a> For definitions of I/O Kit terms used in this documentation, such as matching dictionary, family, and driver, see the overview of I/O Kit terms and concepts n the "Device Access and the I/O Kit" chapter of <i>Accessing Hardware From Applications</i>. This documentation also assumes you have read <a href="http://developer.apple.com/documentation/DeviceDrivers/HumanInterfaceDeviceForceFeedback-date.html"><i>Human Interface Device & Force Feedback</i></a>. Please review documentation before using this reference. <p> All of the information described in this document is contained in the header file <font face="Courier New,Courier,Monaco">IOHIDManager.h</font> found at <font face="Courier New,Courier,Monaco">/System/Library/Frameworks/IOKit.framework/Headers/hid/IOHIDManager.h</font>. */ __BEGIN_DECLS CF_ASSUME_NONNULL_BEGIN CF_IMPLICIT_BRIDGING_ENABLED /*! @enum IOHIDManagerOptions @abstract Various options that can be supplied to IOHIDManager functions. @const kIOHIDManagerOptionNone For those times when supplying 0 just isn't explicit enough. @const kIOHIDManagerOptionUsePersistentProperties This constant can be supplied to @link IOHIDManagerCreate @/link to create and/or use a persistent properties store. @const kIOHIDManagerOptionDoNotLoadProperties This constant can be supplied to @link IOHIDManagerCreate when you wish to overwrite the persistent properties store without loading it first. @const kIOHIDManagerOptionDoNotSaveProperties This constant can be supplied to @link IOHIDManagerCreate @/link when you want to use the persistent property store but do not want to add to it. @const kIOHIDManagerOptionIndependentDevices Devices maintained by the manager will act independently from calls to the manager. This allows for devices to be scheduled on separate queues, and their lifetime can persist after the manager is gone. The following calls will not be propagated to the devices: IOHIDManagerOpen, IOHIDManagerClose, IOHIDManagerScheduleWithRunLoop, IOHIDManagerUnscheduleFromRunLoop, IOHIDManagerSetDispatchQueue, IOHIDManagerSetCancelHandler, IOHIDManagerActivate, IOHIDManagerCancel, IOHIDManagerRegisterInputReportCallback, IOHIDManagerRegisterInputReportWithTimeStampCallback, IOHIDManagerRegisterInputValueCallback, IOHIDManagerSetInputValueMatching, IOHIDManagerSetInputValueMatchingMultiple, This also means that the manager will not be able to receive input reports or input values, since the devices may or may not be scheduled. */ typedef CF_OPTIONS(uint32_t, IOHIDManagerOptions) { kIOHIDManagerOptionNone = 0x0, kIOHIDManagerOptionUsePersistentProperties = 0x1, kIOHIDManagerOptionDoNotLoadProperties = 0x2, kIOHIDManagerOptionDoNotSaveProperties = 0x4, kIOHIDManagerOptionIndependentDevices = 0x8, }; /*! @typedef IOHIDManagerRef @abstract This is the type of a reference to the IOHIDManager. */ typedef struct CF_BRIDGED_TYPE(id) __IOHIDManager * IOHIDManagerRef; /*! @function IOHIDManagerGetTypeID @abstract Returns the type identifier of all IOHIDManager instances. */ CF_EXPORT CFTypeID IOHIDManagerGetTypeID(void) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDManagerCreate @abstract Creates an IOHIDManager object. @discussion The IOHIDManager object is meant as a global management system for communicating with HID devices. @param allocator Allocator to be used during creation. @param options Supply @link kIOHIDManagerOptionUsePersistentProperties @/link to load properties from the default persistent property store. Otherwise supply @link kIOHIDManagerOptionNone @/link (or 0). @result Returns a new IOHIDManagerRef. */ CF_EXPORT IOHIDManagerRef IOHIDManagerCreate( CFAllocatorRef _Nullable allocator, IOOptionBits options) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDManagerOpen @abstract Opens the IOHIDManager. @discussion This will open both current and future devices that are enumerated. To establish an exclusive link use the kIOHIDOptionsTypeSeizeDevice option. @param manager Reference to an IOHIDManager. @param options Option bits to be sent down to the manager and device. @result Returns kIOReturnSuccess if successful. */ CF_EXPORT IOReturn IOHIDManagerOpen( IOHIDManagerRef manager, IOOptionBits options) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDManagerClose @abstract Closes the IOHIDManager. @discussion This will also close all devices that are currently enumerated. @param manager Reference to an IOHIDManager. @param options Option bits to be sent down to the manager and device. @result Returns kIOReturnSuccess if successful. */ CF_EXPORT IOReturn IOHIDManagerClose( IOHIDManagerRef manager, IOOptionBits options) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDManagerGetProperty @abstract Obtains a property of an IOHIDManager. @discussion Property keys are prefixed by kIOHIDDevice and declared in <IOKit/hid/IOHIDKeys.h>. @param manager Reference to an IOHIDManager. @param key CFStringRef containing key to be used when querying the manager. @result Returns CFTypeRef containing the property. */ CF_EXPORT CFTypeRef _Nullable IOHIDManagerGetProperty( IOHIDManagerRef manager, CFStringRef key) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDManagerSetProperty @abstract Sets a property for an IOHIDManager. @discussion Property keys are prefixed by kIOHIDDevice and kIOHIDManager and declared in <IOKit/hid/IOHIDKeys.h>. This method will propagate any relevent properties to current and future devices that are enumerated. @param manager Reference to an IOHIDManager. @param key CFStringRef containing key to be used when modifiying the device property. @param value CFTypeRef containing the property value to be set. @result Returns TRUE if successful. */ CF_EXPORT Boolean IOHIDManagerSetProperty( IOHIDManagerRef manager, CFStringRef key, CFTypeRef value) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDManagerScheduleWithRunLoop @abstract Schedules HID manager with run loop. @discussion Formally associates manager with client's run loop. Scheduling this device with the run loop is necessary before making use of any asynchronous APIs. This will propagate to current and future devices that are enumerated. @param manager Reference to an IOHIDManager. @param runLoop RunLoop to be used when scheduling any asynchronous activity. @param runLoopMode Run loop mode to be used when scheduling any asynchronous activity. */ CF_EXPORT void IOHIDManagerScheduleWithRunLoop( IOHIDManagerRef manager, CFRunLoopRef runLoop, CFStringRef runLoopMode) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDManagerUnscheduleFromRunLoop @abstract Unschedules HID manager with run loop. @discussion Formally disassociates device with client's run loop. This will propagate to current devices that are enumerated. @param manager Reference to an IOHIDManager. @param runLoop RunLoop to be used when unscheduling any asynchronous activity. @param runLoopMode Run loop mode to be used when unscheduling any asynchronous activity. */ CF_EXPORT void IOHIDManagerUnscheduleFromRunLoop( IOHIDManagerRef manager, CFRunLoopRef runLoop, CFStringRef runLoopMode) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! * @function IOHIDManagerSetDispatchQueue * * @abstract * Sets the dispatch queue to be associated with the IOHIDManager. * This is necessary in order to receive asynchronous events from the kernel. * * @discussion * An IOHIDManager should not be associated with both a runloop and * dispatch queue. A call to IOHIDManagerSetDispatchQueue should only be made once. * * After a dispatch queue is set, the IOHIDManager must make a call to activate * via IOHIDManagerActivate and cancel via IOHIDManagerCancel. All calls to "Register" * functions should be done before activation and not after cancellation. * * @param manager * Reference to an IOHIDManager * * @param queue * The dispatch queue to which the event handler block will be submitted. */ CF_EXPORT void IOHIDManagerSetDispatchQueue( IOHIDManagerRef manager, dispatch_queue_t queue) __OSX_AVAILABLE(10.15) __IOS_AVAILABLE(13.0) __TVOS_AVAILABLE(13.0) __WATCHOS_AVAILABLE(6.0); /*! * @function IOHIDManagerSetCancelHandler * * @abstract * Sets a cancellation handler for the dispatch queue associated with * IOHIDManagerSetDispatchQueue. * * @discussion * The cancellation handler (if specified) will be will be submitted to the * manager's dispatch queue in response to a call to IOHIDManagerCancel after * all the events have been handled. * * IOHIDManagerSetCancelHandler should not be used when scheduling with * a run loop. * * The IOHIDManagerRef should only be released after the manager has been * cancelled, and the cancel handler has been called. This is to ensure all * asynchronous objects are released. For example: * * dispatch_block_t cancelHandler = dispatch_block_create(0, ^{ * CFRelease(manager); * }); * IOHIDManagerSetCancelHandler(manager, cancelHandler); * IOHIDManagerActivate(manager); * IOHIDManageCancel(manager); * * @param manager * Reference to an IOHIDManager. * * @param handler * The cancellation handler block to be associated with the dispatch queue. */ CF_EXPORT void IOHIDManagerSetCancelHandler( IOHIDManagerRef manager, dispatch_block_t handler) __OSX_AVAILABLE(10.15) __IOS_AVAILABLE(13.0) __TVOS_AVAILABLE(13.0) __WATCHOS_AVAILABLE(6.0); /*! * @function IOHIDManagerActivate * * @abstract * Activates the IOHIDManager object. * * @discussion * An IOHIDManager object associated with a dispatch queue is created * in an inactive state. The object must be activated in order to * receive asynchronous events from the kernel. * * A dispatch queue must be set via IOHIDManagerSetDispatchQueue before * activation. * * An activated manager must be cancelled via IOHIDManagerCancel. All calls * to "Register" functions should be done before activation * and not after cancellation. * * Calling IOHIDManagerActivate on an active IOHIDManager has no effect. * * @param manager * Reference to an IOHIDManager */ CF_EXPORT void IOHIDManagerActivate( IOHIDManagerRef manager) __OSX_AVAILABLE(10.15) __IOS_AVAILABLE(13.0) __TVOS_AVAILABLE(13.0) __WATCHOS_AVAILABLE(6.0); /*! * @function IOHIDManagerCancel * * @abstract * Cancels the IOHIDManager preventing any further invocation * of its event handler block. * * @discussion * Cancelling prevents any further invocation of the event handler block for * the specified dispatch queue, but does not interrupt an event handler * block that is already in progress. * * Explicit cancellation of the IOHIDManager is required, no implicit * cancellation takes place. * * Calling IOHIDManagerCancel on an already cancelled queue has no effect. * * The IOHIDManagerRef should only be released after the manager has been * cancelled, and the cancel handler has been called. This is to ensure all * asynchronous objects are released. For example: * * dispatch_block_t cancelHandler = dispatch_block_create(0, ^{ * CFRelease(manager); * }); * IOHIDManagerSetCancelHandler(manager, cancelHandler); * IOHIDManagerActivate(manager); * IOHIDManageCancel(manager); * * @param manager * Reference to an IOHIDManager */ CF_EXPORT void IOHIDManagerCancel( IOHIDManagerRef manager) __OSX_AVAILABLE(10.15) __IOS_AVAILABLE(13.0) __TVOS_AVAILABLE(13.0) __WATCHOS_AVAILABLE(6.0); /*! @function IOHIDManagerSetDeviceMatching @abstract Sets matching criteria for device enumeration. @discussion Matching keys are prefixed by kIOHIDDevice and declared in <IOKit/hid/IOHIDKeys.h>. Passing a NULL dictionary will result in all devices being enumerated. Any subsequent calls will cause the hid manager to release previously enumerated devices and restart the enuerate process using the revised criteria. If interested in multiple, specific device classes, please defer to using IOHIDManagerSetDeviceMatchingMultiple. If a dispatch queue is set, this call must occur before activation. @param manager Reference to an IOHIDManager. @param matching CFDictionaryRef containg device matching criteria. */ CF_EXPORT void IOHIDManagerSetDeviceMatching( IOHIDManagerRef manager, CFDictionaryRef _Nullable matching) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDManagerSetDeviceMatchingMultiple @abstract Sets multiple matching criteria for device enumeration. @discussion Matching keys are prefixed by kIOHIDDevice and declared in <IOKit/hid/IOHIDKeys.h>. This method is useful if interested in multiple, specific device classes. If a dispatch queue is set, this call must occur before activation. @param manager Reference to an IOHIDManager. @param multiple CFArrayRef containing multiple CFDictionaryRef objects containg device matching criteria. */ CF_EXPORT void IOHIDManagerSetDeviceMatchingMultiple( IOHIDManagerRef manager, CFArrayRef _Nullable multiple) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDManagerCopyDevices @abstract Obtains currently enumerated devices. @param manager Reference to an IOHIDManager. @result CFSetRef containing IOHIDDeviceRefs. */ CF_EXPORT CFSetRef _Nullable IOHIDManagerCopyDevices( IOHIDManagerRef manager) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDManagerRegisterDeviceMatchingCallback @abstract Registers a callback to be used a device is enumerated. @discussion Only device matching the set criteria will be enumerated. If a dispatch queue is set, this call must occur before activation. Devices provided in the callback will be scheduled with the same runloop/dispatch queue as the IOHIDManagerRef, and should not be rescheduled. @param manager Reference to an IOHIDManagerRef. @param callback Pointer to a callback method of type IOHIDDeviceCallback. @param context Pointer to data to be passed to the callback. */ CF_EXPORT void IOHIDManagerRegisterDeviceMatchingCallback( IOHIDManagerRef manager, IOHIDDeviceCallback _Nullable callback, void * _Nullable context) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDManagerRegisterDeviceRemovalCallback @abstract Registers a callback to be used when any enumerated device is removed. @discussion In most cases this occurs when a device is unplugged. If a dispatch queue is set, this call must occur before activation. @param manager Reference to an IOHIDManagerRef. @param callback Pointer to a callback method of type IOHIDDeviceCallback. @param context Pointer to data to be passed to the callback. */ CF_EXPORT void IOHIDManagerRegisterDeviceRemovalCallback( IOHIDManagerRef manager, IOHIDDeviceCallback _Nullable callback, void * _Nullable context) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDManagerRegisterInputReportCallback @abstract Registers a callback to be used when an input report is issued by any enumerated device. @discussion An input report is an interrupt driver report issued by a device. If a dispatch queue is set, this call must occur before activation. @param manager Reference to an IOHIDManagerRef. @param callback Pointer to a callback method of type IOHIDReportCallback. @param context Pointer to data to be passed to the callback. */ CF_EXPORT void IOHIDManagerRegisterInputReportCallback( IOHIDManagerRef manager, IOHIDReportCallback _Nullable callback, void * _Nullable context) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDManagerRegisterInputReportWithTimeStampCallback @abstract Registers a callback to be used when an input report is issued by any enumerated device. @discussion An input report is an interrupt driver report issued by a device. If a dispatch queue is set, this call must occur before activation. @param manager Reference to an IOHIDManagerRef. @param callback Pointer to a callback method of type IOHIDReportWithTimeStampCallback. @param context Pointer to data to be passed to the callback. */ void IOHIDManagerRegisterInputReportWithTimeStampCallback( IOHIDManagerRef manager, IOHIDReportWithTimeStampCallback callback, void * _Nullable context) __OSX_AVAILABLE(10.15) __IOS_AVAILABLE(13.0) __TVOS_AVAILABLE(13.0) __WATCHOS_AVAILABLE(6.0); /*! @function IOHIDManagerRegisterInputValueCallback @abstract Registers a callback to be used when an input value is issued by any enumerated device. @discussion An input element refers to any element of type kIOHIDElementTypeInput and is usually issued by interrupt driven reports. If a dispatch queue is set, this call must occur before activation. @param manager Reference to an IOHIDManagerRef. @param callback Pointer to a callback method of type IOHIDValueCallback. @param context Pointer to data to be passed to the callback. */ CF_EXPORT void IOHIDManagerRegisterInputValueCallback( IOHIDManagerRef manager, IOHIDValueCallback _Nullable callback, void * _Nullable context) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDManagerSetInputValueMatching @abstract Sets matching criteria for input values received via IOHIDManagerRegisterInputValueCallback. @discussion Matching keys are prefixed by kIOHIDElement and declared in <IOKit/hid/IOHIDKeys.h>. Passing a NULL dictionary will result in all devices being enumerated. Any subsequent calls will cause the hid manager to release previously matched input elements and restart the matching process using the revised criteria. If interested in multiple, specific device elements, please defer to using IOHIDManagerSetInputValueMatchingMultiple. If a dispatch queue is set, this call must occur before activation. @param manager Reference to an IOHIDManager. @param matching CFDictionaryRef containg device matching criteria. */ CF_EXPORT void IOHIDManagerSetInputValueMatching( IOHIDManagerRef manager, CFDictionaryRef _Nullable matching) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDManagerSetInputValueMatchingMultiple @abstract Sets multiple matching criteria for input values received via IOHIDManagerRegisterInputValueCallback. @discussion Matching keys are prefixed by kIOHIDElement and declared in <IOKit/hid/IOHIDKeys.h>. This method is useful if interested in multiple, specific elements. If a dispatch queue is set, this call must occur before activation. @param manager Reference to an IOHIDManager. @param multiple CFArrayRef containing multiple CFDictionaryRef objects containing input element matching criteria. */ CF_EXPORT void IOHIDManagerSetInputValueMatchingMultiple( IOHIDManagerRef manager, CFArrayRef _Nullable multiple) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @abstract Used to write out the current properties to a specific domain. @discussion Using this function will cause the persistent properties to be saved out replacing any properties that already existed in the specified domain. All arguments must be non-NULL except options. @param manager Reference to an IOHIDManager. @param applicationID Reference to a CFPreferences applicationID. @param userName Reference to a CFPreferences userName. @param hostName Reference to a CFPreferences hostName. @param options Reserved for future use. */ CF_EXPORT void IOHIDManagerSaveToPropertyDomain(IOHIDManagerRef manager, CFStringRef applicationID, CFStringRef userName, CFStringRef hostName, IOOptionBits options) AVAILABLE_MAC_OS_X_VERSION_10_6_AND_LATER; CF_IMPLICIT_BRIDGING_DISABLED CF_ASSUME_NONNULL_END __END_DECLS #endif /* _IOKIT_HID_IOHIDMANAGER_H_ */
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/hid/IOHIDDeviceTypes.h
/* * * @APPLE_LICENSE_HEADER_START@ * * Copyright (c) 2019 Apple Computer, Inc. All Rights Reserved. * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this * file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_LICENSE_HEADER_END@ */ #ifndef IOHIDDeviceTypes_h #define IOHIDDeviceTypes_h #include <TargetConditionals.h> #if TARGET_OS_DRIVERKIT #include <DriverKit/IOTypes.h> #include <DriverKit/IOReturn.h> #else #include <IOKit/IOReturn.h> #include <IOKit/IOTypes.h> #endif // TARGET_OS_DRIVERKIT /*! * @typedef IOHIDReportType * * @abstract * Describes different type of HID reports. */ enum IOHIDReportType { kIOHIDReportTypeInput = 0, kIOHIDReportTypeOutput, kIOHIDReportTypeFeature, kIOHIDReportTypeCount }; typedef enum IOHIDReportType IOHIDReportType; /*! * @typedef IOHIDElementCommitDirection * * @abstract * Commit direction passed in to the commit() function of an IOHIDElement. * * @field kIOHIDElementCommitDirectionIn * Passing in kIOHIDElementCommitDirectionIn will issue a getReport call to the * device, and the element will be updated with the value retrieved by the * device. The value can be accessed via the getValue() or getDataValue() * functions. * * @field kIOHIDElementCommitDirectionOut * Passing in kIOHIDElementCommitDirectionOut will issue a setReport call to the * device. Before issuing this call, the desired value should be set on the * element with the setValue() or setDataValue() functions. */ typedef enum { kIOHIDElementCommitDirectionIn, kIOHIDElementCommitDirectionOut } IOHIDElementCommitDirection; /*! * @typedef IOHIDElementCookie * * @abstract * Abstract data type used as a unique identifier for an element. */ #if TARGET_OS_DRIVERKIT || defined(__LP64__) typedef uint32_t IOHIDElementCookie; #else typedef void * IOHIDElementCookie; #endif /*! * @typedef IOHIDElementType * * @abstract * Describes different types of HID elements. * * @discussion * Used by the IOHIDFamily to identify the type of element processed. * Represented by the key kIOHIDElementTypeKey in the dictionary describing the * element. * * @field kIOHIDElementTypeInput_Misc * Misc input data field or varying size. * * @field kIOHIDElementTypeInput_Button * One bit input data field. * * @field kIOHIDElementTypeInput_Axis * Input data field used to represent an axis. * * @field kIOHIDElementTypeInput_ScanCodes * Input data field used to represent a scan code or usage selector. * * @field kIOHIDElementTypeInput_NULL * Input data field used to represent the end of an input report when receiving * input elements. * * @field kIOHIDElementTypeOutput * Used to represent an output data field in a report. * * @field kIOHIDElementTypeFeature * Describes input and output elements not intended for consumption by the end * user. * * @field kIOHIDElementTypeCollection * Element used to identify a relationship between two or more elements. */ enum IOHIDElementType { kIOHIDElementTypeInput_Misc = 1, kIOHIDElementTypeInput_Button = 2, kIOHIDElementTypeInput_Axis = 3, kIOHIDElementTypeInput_ScanCodes = 4, kIOHIDElementTypeInput_NULL = 5, kIOHIDElementTypeOutput = 129, kIOHIDElementTypeFeature = 257, kIOHIDElementTypeCollection = 513 }; typedef enum IOHIDElementType IOHIDElementType; enum { kIOHIDElementFlagsConstantMask = 0x0001, kIOHIDElementFlagsVariableMask = 0x0002, kIOHIDElementFlagsRelativeMask = 0x0004, kIOHIDElementFlagsWrapMask = 0x0008, kIOHIDElementFlagsNonLinearMask = 0x0010, kIOHIDElementFlagsNoPreferredMask = 0x0020, kIOHIDElementFlagsNullStateMask = 0x0040, kIOHIDElementFlagsVolativeMask = 0x0080, kIOHIDElementFlagsBufferedByteMask = 0x0100 }; typedef uint32_t IOHIDElementFlags; /*! * @typedef IOHIDElementCollectionType * * @abstract * Describes different types of HID collections. * * @discussion * Collections identify a relationship between two or more elements. * * @field kIOHIDElementCollectionTypePhysical * Used for a set of data items that represent data points collected at one * geometric point. * * @field kIOHIDElementCollectionTypeApplication * Identifies item groups serving different purposes in a single device. * * @field kIOHIDElementCollectionTypeLogical * Used when a set of data items form a composite data structure. * * @field kIOHIDElementCollectionTypeReport * Wraps all the fields in a report. * * @field kIOHIDElementCollectionTypeNamedArray * Contains an array of selector usages. * * @field kIOHIDElementCollectionTypeUsageSwitch * Modifies the meaning of the usage it contains. * * @field kIOHIDElementCollectionTypeUsageModifier * Modifies the meaning of the usage attached to the encompassing collection. */ enum IOHIDElementCollectionType{ kIOHIDElementCollectionTypePhysical = 0x00, kIOHIDElementCollectionTypeApplication, kIOHIDElementCollectionTypeLogical, kIOHIDElementCollectionTypeReport, kIOHIDElementCollectionTypeNamedArray, kIOHIDElementCollectionTypeUsageSwitch, kIOHIDElementCollectionTypeUsageModifier }; typedef enum IOHIDElementCollectionType IOHIDElementCollectionType; /*! * @typedef IOHIDValueScaleType * * @abstract * Describes different types of scaling that can be performed on element values. * * @field kIOHIDValueScaleTypeCalibrated * Type for value that is scaled with respect to the calibration properties. * * @field kIOHIDValueScaleTypePhysical * Type for value that is scaled with respect to the physical min and physical * max of the element. * * @field kIOHIDValueScaleTypeExponent * Type for value that is scaled with respect to the element's unit exponent. */ enum { kIOHIDValueScaleTypeCalibrated, kIOHIDValueScaleTypePhysical, kIOHIDValueScaleTypeExponent }; typedef uint32_t IOHIDValueScaleType; /*! * @typedef IOHIDValueOptions * * @abstract * Describes options for gathering element values. * * @field kIOHIDValueOptionsFlagRelativeSimple * Compares against previous value * * @field kIOHIDValueOptionsUpdateElementValues * Generates a get report before reading the element value when getting an element. * Generates a set report with the passed value, even if it did not change, to the device when setting a value. */ enum { kIOHIDValueOptionsFlagRelativeSimple = (1<<0), kIOHIDValueOptionsFlagPrevious = (1<<1), kIOHIDValueOptionsUpdateElementValues = (1<<2) }; typedef uint32_t IOHIDValueOptions; /*! * @typedef IOHIDCompletionAction * * @abstract Function called when set/get report completes * * @param target * The target specified in the IOHIDCompletion struct. * * @param parameter * The parameter specified in the IOHIDCompletion struct. * * @param status * Completion status */ typedef void (*IOHIDCompletionAction)(void *target, void *parameter, IOReturn status, uint32_t bufferSizeRemaining); /*! * @typedef IOHIDCompletion * * @abstract * Struct spefifying action to perform when set/get report completes. * * @var target * The target to pass to the action function. * * @var action * The function to call. * * @var parameter * The parameter to pass to the action function. */ typedef struct IOHIDCompletion { void *target; IOHIDCompletionAction action; void *parameter; } IOHIDCompletion; /*! * @abstract * Option bits for IOHIDDevice::handleReport, IOHIDDevice::getReport, and * IOHIDDevice::setReport * * @field kIOHIDReportOptionNotInterrupt * Tells method that the report passed was not interrupt driven. */ enum { kIOHIDReportOptionNotInterrupt = 0x100, kIOHIDReportOptionVariableSize = 0x200 }; /*! * @typedef HIDReportCommandType * * @abstract * Type of the report command for DriverKit driver */ typedef enum { kIOHIDReportCommandSetReport, kIOHIDReportCommandGetReport } HIDReportCommandType; #endif /* IOHIDDeviceTypes_h */
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/hid/IOHIDEventServiceTypes.h
/* * * @APPLE_LICENSE_HEADER_START@ * * Copyright (c) 2019 Apple Computer, Inc. All Rights Reserved. * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this * file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_LICENSE_HEADER_END@ */ #ifndef IOHIDEventServiceTypes_h #define IOHIDEventServiceTypes_h /*! * @typedef IOHIDKeyboardEventOptions * * @abstract * Keyboard event options passed in to dispatchKeyboardEvent function in * IOHIDEventService. * * @field kIOHIDKeyboardEventOptionsNoKeyRepeat * Default behavior for keyboard events is to repeat keys if the key has been * held down for a certain amount of time defined in system preferences. Pass * in this option to not apply key repeat logic to this event. */ typedef enum { kIOHIDKeyboardEventOptionsNoKeyRepeat = (1 << 8), } IOHIDKeyboardEventOptions; /*! * @typedef IOHIDPointerEventOptions * * @abstract * Pointer event options passed in to dispatch(Relative/Absolute)PointerEvent * function in IOHIDEventService. * * @field kIOHIDPointerEventOptionsNoAcceleration * Pointer events are subject to an acceleration algorithm. Pass in this option * if you do not wish to have acceleration logic applied to the pointer event. */ typedef enum { kIOHIDPointerEventOptionsNoAcceleration = (1 << 8), } IOHIDPointerEventOptions; /*! * @typedef IOHIDScrollEventOptions * * @abstract * Scroll event options passed in to dispatchScrollEvent function in * IOHIDEventService. * * @field kIOHIDScrollEventOptionsNoAcceleration * Scroll events are subject to an acceleration algorithm. Pass in this option * if you do not wish to have acceleration logic applied to the scroll event. */ typedef enum { kIOHIDScrollEventOptionsNoAcceleration = (1 << 8), } IOHIDScrollEventOptions; #endif /* IOHIDEventServiceTypes_h */
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/hid/IOHIDEventServiceKeys.h
/* * * @APPLE_LICENSE_HEADER_START@ * * Copyright (c) 2019 Apple Computer, Inc. All Rights Reserved. * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this * file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_LICENSE_HEADER_END@ */ #ifndef IOHIDEventServiceKeys_h #define IOHIDEventServiceKeys_h /*! * @define kIOHIDPointerAccelerationKey * * @abstract * Number property that contains the pointer acceleration value. */ #define kIOHIDPointerAccelerationKey "HIDPointerAcceleration" /*! * @define kIOHIDPointerAccelerationTypeKey * * @abstract * String property containing the type of acceleration for pointer. * Supported types are: * <code>kIOHIDPointerAccelerationKey</code> * <code>kIOHIDMouseScrollAccelerationKey</code> * <code>kIOHIDTrackpadAccelerationType</code> */ #define kIOHIDPointerAccelerationTypeKey "HIDPointerAccelerationType" /*! * @define kIOHIDMouseScrollAccelerationKey * * @abstract * Number property that contains the mouse scroll acceleration value. */ #define kIOHIDMouseScrollAccelerationKey "HIDMouseScrollAcceleration" /*! * @define kIOHIDMouseAccelerationTypeKey * * @abstract * Number property that contains the mouse acceleration value. */ #define kIOHIDMouseAccelerationTypeKey "HIDMouseAcceleration" /*! * @define kIOHIDScrollAccelerationKey * * @abstract * Number property that contains the scroll acceleration value. */ #define kIOHIDScrollAccelerationKey "HIDScrollAcceleration" /*! * @define kIOHIDScrollAccelerationTypeKey * * @abstract * Number property containing the type of acceleration for scroll. * Supported types are: * <code>kIOHIDMouseScrollAccelerationKey</code> * <code>kIOHIDTrackpadScrollAccelerationKey</code> */ #define kIOHIDScrollAccelerationTypeKey "HIDScrollAccelerationType" /*! * @define kIOHIDDigitizerTipThresholdKey * * @abstract * Number property that describes the threshold percentage for when the tip * pressure of a digitizer stylus should change from hovering to dragging. * * @discussion * If a digitizer stylus supports the kHIDUsage_Dig_TipPressure (0x30) usage, * the service may optionally publish this key to describe the value at which * the pressure should change the pointer behavior from hovering to dragging. * The value is a percentage from 0 to 100, where 100 percent is equal to the * logical max that the stylus dispatches. If no value is provided, the default * value of 75 will be used. */ #define kIOHIDDigitizerTipThresholdKey "DigitizerTipThreshold" /*! * @define kIOHIDSurfaceDimensionsKey * * @abstract * Dictionary property published on a service that describes the surface * dimensions for services that publish absolute X/Y values, such as digitizer * and pointer devices. The dictionary will contain the kIOHIDWidthKey and * kIOHIDHeightKey keys described below. Value is in millimeter represented * as IOFixed. */ #define kIOHIDSurfaceDimensionsKey "SurfaceDimensions" /*! * @define kIOHIDWidthKey * * @abstract * Number property used in the surface dimensions dictionary described above. * Default value represents the physical max - physical min of the absolute * X value. */ #define kIOHIDWidthKey "Width" /*! * @define kIOHIDHeightKey * * @abstract * Number property used in the surface dimensions dictionary described above. * Default value represents the physical max - physical min of the absolute * Y value. */ #define kIOHIDHeightKey "Height" /*! * @define kIOHIDEventDriverHandlesReport * * @abstract * Boolean property used to let handleReport in an IOUserHIDEventDriver get the * report before any other processing is done in IOUserHIDEventService. * If this property is enabled the IOUserHIDEventService subclass should update * the elements with IOHIDInterface::processReport to update the IOHIDElements as * IOUserHIDEventService will not do this like when this property is not set. */ #define kIOHIDEventDriverHandlesReport "IOHIDEventDriverHandlesReport" #endif /* IOHIDDeviceTypes_h */
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/hid/IOHIDElement.h
/* * Copyright (c) 1999-2008 Apple Computer, Inc. All Rights Reserved. * * @APPLE_LICENSE_HEADER_START@ * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this * file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_LICENSE_HEADER_END@ */ #ifndef _IOKIT_HID_IOHIDELEMENT_USER_H #define _IOKIT_HID_IOHIDELEMENT_USER_H #include <CoreFoundation/CoreFoundation.h> #include <IOKit/hid/IOHIDKeys.h> #include <IOKit/hid/IOHIDBase.h> /*! @header IOHIDElement IOHIDElement defines a parsed item contained within a Human Interface Device (HID) object. It is used to obtain properties of the parsed. It can also be used to set properties such as calibration settings. IOHIDElement is a CFType object and as such conforms to all the conventions expected such object. <p> This documentation assumes that you have a basic understanding of the material contained in <a href="http://developer.apple.com/documentation/DeviceDrivers/Conceptual/AccessingHardware/index.html"><i>Accessing Hardware From Applications</i></a> For definitions of I/O Kit terms used in this documentation, such as matching dictionary, family, and driver, see the overview of I/O Kit terms and concepts in the "Device Access and the I/O Kit" chapter of <i>Accessing Hardware From Applications</i>. This documentation also assumes you have read <a href="http://developer.apple.com/documentation/DeviceDrivers/HumanInterfaceDeviceForceFeedback-date.html"><i>Human Interface Device & Force Feedback</i></a>. Please review documentation before using this reference. <p> All of the information described in this document is contained in the header file <font face="Courier New,Courier,Monaco">IOHIDElement.h</font> found at <font face="Courier New,Courier,Monaco">/System/Library/Frameworks/IOKit.framework/Headers/hid/IOHIDElement.h</font>. */ __BEGIN_DECLS CF_ASSUME_NONNULL_BEGIN CF_IMPLICIT_BRIDGING_ENABLED /*! @function IOHIDElementGetTypeID @abstract Returns the type identifier of all IOHIDElement instances. */ CF_EXPORT CFTypeID IOHIDElementGetTypeID(void) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDElementCreateWithDictionary @abstract Creates an element from a dictionary. @discussion The dictionary should contain keys defined in IOHIDKeys.h and start with kIOHIDElement. This call is meant be used by a IOHIDDeviceDeviceInterface object. @param allocator Allocator to be used during creation. @param dictionary dictionary containing values in which to create element. @result Returns a new IOHIDElementRef. */ CF_EXPORT IOHIDElementRef IOHIDElementCreateWithDictionary(CFAllocatorRef _Nullable allocator, CFDictionaryRef dictionary) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDElementGetDevice @abstract Obtain the device associated with the element. @param element IOHIDElement to be queried. @result Returns the a reference to the device. */ CF_EXPORT IOHIDDeviceRef IOHIDElementGetDevice(IOHIDElementRef element) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDElementGetParent @abstract Returns the parent for the element. @discussion The parent element can be an element of type kIOHIDElementTypeCollection. @param element The element to be queried. If this parameter is not a valid IOHIDElementRef, the behavior is undefined. @result Returns an IOHIDElementRef referencing the parent element. */ CF_EXPORT IOHIDElementRef _Nullable IOHIDElementGetParent(IOHIDElementRef element) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDElementGetChildren @abstract Returns the children for the element. @discussion An element of type kIOHIDElementTypeCollection usually contains children. @param element The element to be queried. If this parameter is not a valid IOHIDElementRef, the behavior is undefined. @result Returns an CFArrayRef containing element objects of type IOHIDElementRef. */ CF_EXPORT CFArrayRef _Nullable IOHIDElementGetChildren(IOHIDElementRef element) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDElementAttach @abstract Establish a relationship between one or more elements. @discussion This is useful for grouping HID elements with related functionality. @param element The element to be modified. If this parameter is not a valid IOHIDElementRef, the behavior is undefined. @param toAttach The element to be attached. If this parameter is not a valid IOHIDElementRef, the behavior is undefined. */ CF_EXPORT void IOHIDElementAttach(IOHIDElementRef element, IOHIDElementRef toAttach) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDElementDetach @abstract Remove a relationship between one or more elements. @discussion This is useful for grouping HID elements with related functionality. @param element The element to be modified. If this parameter is not a valid IOHIDElementRef, the behavior is undefined. @param toDetach The element to be detached. If this parameter is not a valid IOHIDElementRef, the behavior is undefined. */ CF_EXPORT void IOHIDElementDetach(IOHIDElementRef element, IOHIDElementRef toDetach) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDElementCopyAttached @abstract Obtain attached elements. @discussion Attached elements are those that have been grouped via IOHIDElementAttach. @param element The element to be modified. If this parameter is not a valid IOHIDElementRef, the behavior is undefined. @result Returns a copy of the current attached elements. */ CF_EXPORT CFArrayRef _Nullable IOHIDElementCopyAttached(IOHIDElementRef element) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDElementGetCookie @abstract Retrieves the cookie for the element. @discussion The IOHIDElementCookie represent a unique identifier for an element within a device. @param element The element to be queried. If this parameter is not a valid IOHIDElementRef, the behavior is undefined. @result Returns the IOHIDElementCookie for the element. */ CF_EXPORT IOHIDElementCookie IOHIDElementGetCookie(IOHIDElementRef element) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDElementGetType @abstract Retrieves the type for the element. @param element The element to be queried. If this parameter is not a valid IOHIDElementRef, the behavior is undefined. @result Returns the IOHIDElementType for the element. */ CF_EXPORT IOHIDElementType IOHIDElementGetType(IOHIDElementRef element) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDElementGetCollectionType @abstract Retrieves the collection type for the element. @discussion The value returned by this method only makes sense if the element type is kIOHIDElementTypeCollection. @param element The element to be queried. If this parameter is not a valid IOHIDElementRef, the behavior is undefined. @result Returns the IOHIDElementCollectionType for the element. */ CF_EXPORT IOHIDElementCollectionType IOHIDElementGetCollectionType(IOHIDElementRef element) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDElementGetUsagePage @abstract Retrieves the usage page for an element. @param element The element to be queried. If this parameter is not a valid IOHIDElementRef, the behavior is undefined. @result Returns the usage page for the element. */ CF_EXPORT uint32_t IOHIDElementGetUsagePage(IOHIDElementRef element) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDElementGetUsage @abstract Retrieves the usage for an element. @param element The element to be queried. If this parameter is not a valid IOHIDElementRef, the behavior is undefined. @result Returns the usage for the element. */ CF_EXPORT uint32_t IOHIDElementGetUsage(IOHIDElementRef element) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDElementIsVirtual @abstract Returns the virtual property for the element. @discussion Indicates whether the element is a virtual element. @param element The element to be queried. If this parameter is not a valid IOHIDElementRef, the behavior is undefined. @result Returns the TRUE if virtual or FALSE if not. */ CF_EXPORT Boolean IOHIDElementIsVirtual(IOHIDElementRef element) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDElementIsRelative @abstract Returns the relative property for the element. @discussion Indicates whether the data is relative (indicating the change in value from the last report) or absolute (based on a fixed origin). @param element The element to be queried. If this parameter is not a valid IOHIDElementRef, the behavior is undefined. @result Returns TRUE if relative or FALSE if absolute. */ CF_EXPORT Boolean IOHIDElementIsRelative(IOHIDElementRef element) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDElementIsWrapping @abstract Returns the wrap property for the element. @discussion Wrap indicates whether the data "rolls over" when reaching either the extreme high or low value. @param element The element to be queried. If this parameter is not a valid IOHIDElementRef, the behavior is undefined. @result Returns TRUE if wrapping or FALSE if non-wrapping. */ CF_EXPORT Boolean IOHIDElementIsWrapping(IOHIDElementRef element) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDElementIsArray @abstract Returns the array property for the element. @discussion Indicates whether the element represents variable or array data values. Variable values represent data from a physical control. An array returns an index in each field that corresponds to the pressed button (like keyboard scan codes). <br> <b>Note:</b> The HID Manager will represent most elements as "variable" including the possible usages of an array. Array indices will remain as "array" elements with a usage of 0xffffffff. @param element The element to be queried. If this parameter is not a valid IOHIDElementRef, the behavior is undefined. @result Returns TRUE if array or FALSE if variable. */ CF_EXPORT Boolean IOHIDElementIsArray(IOHIDElementRef element) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDElementIsNonLinear @abstract Returns the linear property for the element. @discussion Indicates whether the value for the element has been processed in some way, and no longer represents a linear relationship between what is measured and the value that is reported. @param element The element to be queried. If this parameter is not a valid IOHIDElementRef, the behavior is undefined. @result Returns TRUE if non linear or FALSE if linear. */ CF_EXPORT Boolean IOHIDElementIsNonLinear(IOHIDElementRef element) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDElementHasPreferredState @abstract Returns the preferred state property for the element. @discussion Indicates whether the element has a preferred state to which it will return when the user is not physically interacting with the control. @param element The element to be queried. If this parameter is not a valid IOHIDElementRef, the behavior is undefined. @result Returns TRUE if preferred state or FALSE if no preferred state. */ CF_EXPORT Boolean IOHIDElementHasPreferredState(IOHIDElementRef element) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDElementHasNullState @abstract Returns the null state property for the element. @discussion Indicates whether the element has a state in which it is not sending meaningful data. @param element The element to be queried. If this parameter is not a valid IOHIDElementRef, the behavior is undefined. @result Returns TRUE if null state or FALSE if no null state. */ CF_EXPORT Boolean IOHIDElementHasNullState(IOHIDElementRef element) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDElementGetName @abstract Returns the name for the element. @param element The element to be queried. If this parameter is not a valid IOHIDElementRef, the behavior is undefined. @result Returns CFStringRef containing the element name. */ CF_EXPORT CFStringRef IOHIDElementGetName(IOHIDElementRef element) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDElementGetReportID @abstract Returns the report ID for the element. @discussion The report ID represents what report this particular element belongs to. @param element The element to be queried. If this parameter is not a valid IOHIDElementRef, the behavior is undefined. @result Returns the report ID. */ CF_EXPORT uint32_t IOHIDElementGetReportID(IOHIDElementRef element) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDElementGetReportSize @abstract Returns the report size in bits for the element. @discussion If the element is an array type the total number of bit in the element is equal to IOHIDElementGetReportSize(element) * IOHIDElementGetReportCount(element). Otherwise this size is the total number of bits in the element. @param element The element to be queried. If this parameter is not a valid IOHIDElementRef, the behavior is undefined. @result Returns the report size. */ CF_EXPORT uint32_t IOHIDElementGetReportSize(IOHIDElementRef element) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDElementGetReportCount @abstract Returns the report count for the element. @discussion If the IOHIDElementGetReportCount(element) is greater than one and the element does not represent an array then the element represents a repeated set of usages, the size of each usage in the element is IOHIDElementGetReportSize(element) / IOHIDElementGetReportCount(element). @param element The element to be queried. If this parameter is not a valid IOHIDElementRef, the behavior is undefined. @result Returns the report count. */ CF_EXPORT uint32_t IOHIDElementGetReportCount(IOHIDElementRef element) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDElementGetUnit @abstract Returns the unit property for the element. @discussion The unit property is described in more detail in Section 6.2.2.7 of the "Device Class Definition for Human Interface Devices(HID)" Specification, Version 1.11. @param element The element to be queried. If this parameter is not a valid IOHIDElementRef, the behavior is undefined. @result Returns the unit. */ CF_EXPORT uint32_t IOHIDElementGetUnit(IOHIDElementRef element) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDElementGetUnitExponent @abstract Returns the unit exponenet in base 10 for the element. @discussion The unit exponent property is described in more detail in Section 6.2.2.7 of the "Device Class Definition for Human Interface Devices(HID)" Specification, Version 1.11. @param element The element to be queried. If this parameter is not a valid IOHIDElementRef, the behavior is undefined. @result Returns the unit exponent. */ CF_EXPORT uint32_t IOHIDElementGetUnitExponent(IOHIDElementRef element) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDElementGetLogicalMin @abstract Returns the minimum value possible for the element. @discussion This corresponds to the logical minimun, which indicates the lower bounds of a variable element. @param element The element to be queried. If this parameter is not a valid IOHIDElementRef, the behavior is undefined. @result Returns the logical minimum. */ CF_EXPORT CFIndex IOHIDElementGetLogicalMin(IOHIDElementRef element) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDElementGetLogicalMax @abstract Returns the maximum value possible for the element. @discussion This corresponds to the logical maximum, which indicates the upper bounds of a variable element. @param element The element to be queried. If this parameter is not a valid IOHIDElementRef, the behavior is undefined. @result Returns the logical maximum. */ CF_EXPORT CFIndex IOHIDElementGetLogicalMax(IOHIDElementRef element) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDElementGetPhysicalMin @abstract Returns the scaled minimum value possible for the element. @discussion Minimum value for the physical extent of a variable element. This represents the value for the logical minimum with units applied to it. @param element The element to be queried. If this parameter is not a valid IOHIDElementRef, the behavior is undefined. @result Returns the physical minimum. */ CF_EXPORT CFIndex IOHIDElementGetPhysicalMin(IOHIDElementRef element) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDElementGetPhysicalMax @abstract Returns the scaled maximum value possible for the element. @discussion Maximum value for the physical extent of a variable element. This represents the value for the logical maximum with units applied to it. @param element The element to be queried. If this parameter is not a valid IOHIDElementRef, the behavior is undefined. @result Returns the physical maximum. */ CF_EXPORT CFIndex IOHIDElementGetPhysicalMax(IOHIDElementRef element) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDElementGetProperty @abstract Returns the an element property. @discussion Property keys are prefixed by kIOHIDElement and declared in IOHIDKeys.h. @param element The element to be queried. If this parameter is not a valid IOHIDElementRef, the behavior is undefined. @param key The key to be used when querying the element. @result Returns the property. */ CF_EXPORT CFTypeRef _Nullable IOHIDElementGetProperty(IOHIDElementRef element, CFStringRef key) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDElementSetProperty @abstract Sets an element property. @discussion This method can be used to set arbitrary element properties, such as application specific references. @param element The element to be queried. If this parameter is not a valid IOHIDElementRef, the behavior is undefined. @param key The key to be used when querying the element. @result Returns TRUE if successful. */ CF_EXPORT Boolean IOHIDElementSetProperty(IOHIDElementRef element, CFStringRef key, CFTypeRef property) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; CF_IMPLICIT_BRIDGING_DISABLED CF_ASSUME_NONNULL_END __END_DECLS #endif /* _IOKIT_HID_IOHIDELEMENT_USER_H */
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/hid/IOHIDTransaction.h
/* * Copyright (c) 1999-2008 Apple Computer, Inc. All Rights Reserved. * * @APPLE_LICENSE_HEADER_START@ * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this * file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_LICENSE_HEADER_END@ */ #ifndef _IOKIT_HID_IOHIDTRANSACTION_USER_H #define _IOKIT_HID_IOHIDTRANSACTION_USER_H #include <CoreFoundation/CoreFoundation.h> #include <IOKit/hid/IOHIDBase.h> /*! @header IOHIDTransaction IOHIDTransaction defines an object used to manipulate multiple parsed items (IOHIDElement) contained within a Human Interface Device (HID) object. It is used to minimize device communication when interacting with feature and output type elements that are grouped by their report IDs. IOHIDTransaction is a CFType object and as such conforms to all the conventions expected such object. <p> This documentation assumes that you have a basic understanding of the material contained in <a href="http://developer.apple.com/documentation/DeviceDrivers/Conceptual/AccessingHardware/index.html"><i>Accessing Hardware From Applications</i></a> For definitions of I/O Kit terms used in this documentation, such as matching dictionary, family, and driver, see the overview of I/O Kit terms and concepts in the "Device Access and the I/O Kit" chapter of <i>Accessing Hardware From Applications</i>. This documentation also assumes you have read <a href="http://developer.apple.com/documentation/DeviceDrivers/HumanInterfaceDeviceForceFeedback-date.html"><i>Human Interface Device & Force Feedback</i></a>. Please review documentation before using this reference. <p> All of the information described in this document is contained in the header file <font face="Courier New,Courier,Monaco">IOHIDTransaction.h</font> found at <font face="Courier New,Courier,Monaco">/System/Library/Frameworks/IOKit.framework/Headers/hid/IOHIDTransaction.h</font>. */ __BEGIN_DECLS CF_ASSUME_NONNULL_BEGIN CF_IMPLICIT_BRIDGING_ENABLED /*! @enum IOHIDTransactionOptions @abstract Various options that can be supplied to IOHIDTransaction functions. @const kIOHIDTransactionOptionsNone For those times when supplying 0 just isn't explicit enough. @const kIOHIDTransactionOptionsWeakDevice specifies the transaction to not retain the IOHIDDeviceRef being passed in. The expectation is that transaction will only exist during the lifetime of the IOHIDDeviceRef object. */ typedef CF_OPTIONS(uint32_t, IOHIDTransactionOptions) { kIOHIDTransactionOptionsNone = 0x0, kIOHIDTransactionOptionsWeakDevice = 0x1, }; /*! @typedef IOHIDTransactionRef This is the type of a reference to the IOHIDTransaction. */ typedef struct CF_BRIDGED_TYPE(id) __IOHIDTransaction * IOHIDTransactionRef; /*! @function IOHIDTransactionGetTypeID @abstract Returns the type identifier of all IOHIDTransaction instances. */ CF_EXPORT CFTypeID IOHIDTransactionGetTypeID(void) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDTransactionCreate @abstract Creates an IOHIDTransaction object for the specified device. @discussion IOHIDTransaction objects can be used to either send or receive multiple element values. As such the direction used should represent they type of objects added to the transaction. @param allocator Allocator to be used during creation. @param device IOHIDDevice object @param direction The direction, either in or out, for the transaction. @param options Reserved for future use. @result Returns a new IOHIDTransactionRef. */ CF_EXPORT IOHIDTransactionRef _Nullable IOHIDTransactionCreate( CFAllocatorRef _Nullable allocator, IOHIDDeviceRef device, IOHIDTransactionDirectionType direction, IOOptionBits options) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDTransactionGetDevice @abstract Obtain the device associated with the transaction. @param transaction IOHIDTransaction to be queried. @result Returns the a reference to the device. */ CF_EXPORT IOHIDDeviceRef IOHIDTransactionGetDevice( IOHIDTransactionRef transaction) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDTransactionGetDirection @abstract Obtain the direction of the transaction. @param transaction IOHIDTransaction to be queried. @result Returns the transaction direction. */ CF_EXPORT IOHIDTransactionDirectionType IOHIDTransactionGetDirection( IOHIDTransactionRef transaction) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDTransactionSetDirection @abstract Sets the direction of the transaction @disussion This method is useful for manipulating bi-direction (feature) elements such that you can set or get element values without creating an additional transaction object. @param transaction IOHIDTransaction object to be modified. @param direction The new transaction direction. */ CF_EXPORT void IOHIDTransactionSetDirection( IOHIDTransactionRef transaction, IOHIDTransactionDirectionType direction) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDTransactionAddElement @abstract Adds an element to the transaction @disussion To minimize device traffic it is important to add elements that share a common report type and report id. @param transaction IOHIDTransaction object to be modified. @param element Element to be added to the transaction. */ CF_EXPORT void IOHIDTransactionAddElement( IOHIDTransactionRef transaction, IOHIDElementRef element) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDTransactionRemoveElement @abstract Removes an element to the transaction @param transaction IOHIDTransaction object to be modified. @param element Element to be removed to the transaction. */ CF_EXPORT void IOHIDTransactionRemoveElement( IOHIDTransactionRef transaction, IOHIDElementRef element) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDTransactionContainsElement @abstract Queries the transaction to determine if elemement has been added. @param transaction IOHIDTransaction object to be queried. @param element Element to be queried. @result Returns true or false depending if element is present. */ CF_EXPORT Boolean IOHIDTransactionContainsElement( IOHIDTransactionRef transaction, IOHIDElementRef element) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDTransactionScheduleWithRunLoop @abstract Schedules transaction with run loop. @discussion Formally associates transaction with client's run loop. Scheduling this transaction with the run loop is necessary before making use of any asynchronous APIs. @param transaction IOHIDTransaction object to be modified. @param runLoop RunLoop to be used when scheduling any asynchronous activity. @param runLoopMode Run loop mode to be used when scheduling any asynchronous activity. */ CF_EXPORT void IOHIDTransactionScheduleWithRunLoop( IOHIDTransactionRef transaction, CFRunLoopRef runLoop, CFStringRef runLoopMode) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDTransactionUnscheduleFromRunLoop @abstract Unschedules transaction with run loop. @discussion Formally disassociates transaction with client's run loop. @param transaction IOHIDTransaction object to be modified. @param runLoop RunLoop to be used when scheduling any asynchronous activity. @param runLoopMode Run loop mode to be used when scheduling any asynchronous activity. */ CF_EXPORT void IOHIDTransactionUnscheduleFromRunLoop( IOHIDTransactionRef transaction, CFRunLoopRef runLoop, CFStringRef runLoopMode) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDTransactionSetValue @abstract Sets the value for a transaction element. @discussion The value set is pended until the transaction is committed and is only used if the transaction direction is kIOHIDTransactionDirectionTypeOutput. Use the kIOHIDTransactionOptionDefaultOutputValue option to set the default element value. @param transaction IOHIDTransaction object to be modified. @param element Element to be modified after a commit. @param value Value to be set for the given element. @param options See IOHIDTransactionOption. */ CF_EXPORT void IOHIDTransactionSetValue( IOHIDTransactionRef transaction, IOHIDElementRef element, IOHIDValueRef value, IOOptionBits options) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDTransactionGetValue @abstract Obtains the value for a transaction element. @discussion If the transaction direction is kIOHIDTransactionDirectionTypeInput the value represents what was obtained from the device from the transaction. Otherwise, if the transaction direction is kIOHIDTransactionDirectionTypeOutput the value represents the pending value to be sent to the device. Use the kIOHIDTransactionOptionDefaultOutputValue option to get the default element value. @param transaction IOHIDTransaction object to be queried. @param element Element to be queried. @param options See IOHIDTransactionOption. @result Returns IOHIDValueRef for the given element. */ CF_EXPORT IOHIDValueRef _Nullable IOHIDTransactionGetValue( IOHIDTransactionRef transaction, IOHIDElementRef element, IOOptionBits options) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDTransactionCommit @abstract Synchronously commits element transaction to the device. @discussion In regards to kIOHIDTransactionDirectionTypeOutput direction, default element values will be used if element values are not set. If neither are set, that element will be omitted from the commit. After a transaction is committed, transaction element values will be cleared and default values preserved. @param transaction IOHIDTransaction object to be modified. @result Returns kIOReturnSuccess if successful or a kern_return_t if unsuccessful. */ CF_EXPORT IOReturn IOHIDTransactionCommit( IOHIDTransactionRef transaction) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDTransactionCommitWithCallback @abstract Commits element transaction to the device. @discussion In regards to kIOHIDTransactionDirectionTypeOutput direction, default element values will be used if element values are not set. If neither are set, that element will be omitted from the commit. After a transaction is committed, transaction element values will be cleared and default values preserved. <br> <b>Note:</b> It is possible for elements from different reports to be present in a given transaction causing a commit to transcend multiple reports. Keep this in mind when setting a appropriate timeout. @param transaction IOHIDTransaction object to be modified. @param timeout Timeout for issuing the transaction. @param callback Callback of type IOHIDCallback to be used when transaction has been completed. If null, this method will behave synchronously. @param context Pointer to data to be passed to the callback. @result Returns kIOReturnSuccess if successful or a kern_return_t if unsuccessful. */ CF_EXPORT IOReturn IOHIDTransactionCommitWithCallback( IOHIDTransactionRef transaction, CFTimeInterval timeout, IOHIDCallback _Nullable callback, void * _Nullable context) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; /*! @function IOHIDTransactionClear @abstract Clears element transaction values. @discussion In regards to kIOHIDTransactionDirectionTypeOutput direction, default element values will be preserved. @param transaction IOHIDTransaction object to be modified. */ CF_EXPORT void IOHIDTransactionClear( IOHIDTransactionRef transaction) AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER; CF_IMPLICIT_BRIDGING_DISABLED CF_ASSUME_NONNULL_END __END_DECLS #endif /* _IOKIT_HID_IOHIDTRANSACTION_USER_H */
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/hid/IOHIDLibObsolete.h
/* * * @APPLE_LICENSE_HEADER_START@ * * Copyright (c) 1999-2003 Apple Computer, Inc. All Rights Reserved. * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this * file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_LICENSE_HEADER_END@ */ #ifndef _IOKIT_HID_IOHIDLIBOBSOLETE_H_ #define _IOKIT_HID_IOHIDLIBOBSOLETE_H_ #include <sys/cdefs.h> __BEGIN_DECLS #include <CoreFoundation/CoreFoundation.h> #if COREFOUNDATION_CFPLUGINCOM_SEPARATE #include <CoreFoundation/CFPlugInCOM.h> #endif #include <IOKit/IOTypes.h> #include <IOKit/IOReturn.h> #include <IOKit/hid/IOHIDKeys.h> struct IOHIDEventStruct { IOHIDElementType type; IOHIDElementCookie elementCookie; int32_t value; AbsoluteTime timestamp; uint32_t longValueSize; void * longValue; }; typedef struct IOHIDEventStruct IOHIDEventStruct; /* FA12FA38-6F1A-11D4-BA0C-0005028F18D5 */ #define kIOHIDDeviceUserClientTypeID CFUUIDGetConstantUUIDWithBytes(NULL, \ 0xFA, 0x12, 0xFA, 0x38, 0x6F, 0x1A, 0x11, 0xD4, \ 0xBA, 0x0C, 0x00, 0x05, 0x02, 0x8F, 0x18, 0xD5) /* 78BD420C-6F14-11D4-9474-0005028F18D5 */ /*! @defined kIOHIDDeviceInterfaceID @discussion Interface ID for the IOHIDDeviceInterface. Corresponds to an available HID device. */ #define kIOHIDDeviceInterfaceID CFUUIDGetConstantUUIDWithBytes(NULL, \ 0x78, 0xBD, 0x42, 0x0C, 0x6F, 0x14, 0x11, 0xD4, \ 0x94, 0x74, 0x00, 0x05, 0x02, 0x8F, 0x18, 0xD5) /* 7D0B510E-16D5-11D7-9E9B-000393992E38 */ /*! @defined kIOHIDDeviceInterfaceID121 @discussion Interface ID for the IOHIDDeviceInterface121. Corresponds to an available HID device that includes methods from IOHIDDeviceInterface. This interface is available on IOHIDLib 1.2.1 and Mac OS X 10.2.3 or later.*/ #define kIOHIDDeviceInterfaceID121 CFUUIDGetConstantUUIDWithBytes(NULL, \ 0x7d, 0xb, 0x51, 0xe, 0x16, 0xd5, 0x11, 0xd7, \ 0x9e, 0x9b, 0x0, 0x3, 0x93, 0x99, 0x2e, 0x38) /* B70ABF31-16D5-11D7-AB35-000393992E38 */ /*! @defined kIOHIDDeviceInterfaceID122 @discussion Interface ID for the IOHIDDeviceInterface122. Corresponds to an available HID device that includes methods from IOHIDDeviceInterface and IOHIDDeviceInterface121. This interface is available on IOHIDLib 1.2.2 and Mac OS X 10.3 or later.*/ #define kIOHIDDeviceInterfaceID122 CFUUIDGetConstantUUIDWithBytes(NULL, \ 0xb7, 0xa, 0xbf, 0x31, 0x16, 0xd5, 0x11, 0xd7, \ 0xab, 0x35, 0x0, 0x3, 0x93, 0x99, 0x2e, 0x38) /* 8138629E-6F14-11D4-970E-0005028F18D5 */ /*! @defined kIOHIDQueueInterfaceID @discussion Interface ID for the kIOHIDQueueInterfaceID. Corresponds to a queue for a specific HID device. */ #define kIOHIDQueueInterfaceID CFUUIDGetConstantUUIDWithBytes(NULL, \ 0x81, 0x38, 0x62, 0x9E, 0x6F, 0x14, 0x11, 0xD4, \ 0x97, 0x0E, 0x00, 0x05, 0x02, 0x8F, 0x18, 0xD5) /* 80CDCC00-755D-11D4-8E0F-0005028F18D5 */ /*! @defined kIOHIDOutputTransactionInterfaceID @discussion Interface ID for the kIOHIDOutputTransactionInterfaceID. Corresponds to an output transaction for one or more report IDs on a specific device. */ #define kIOHIDOutputTransactionInterfaceID CFUUIDGetConstantUUIDWithBytes(NULL,\ 0x80, 0xCD, 0xCC, 0x00, 0x75, 0x5D, 0x11, 0xD4, \ 0x80, 0xEF, 0x00, 0x05, 0x02, 0x8F, 0x18, 0xD5) /*! @typedef IOHIDCallbackFunction @discussion Type and arguments of callout C function that is used when a completion routine is called, see IOHIDLib.h:setRemovalCallback(). @param target void * pointer to your data, often a pointer to an object. @param result Completion result of desired operation. @param refcon void * pointer to more data. @param sender Interface instance sending the completion routine. */ typedef void (*IOHIDCallbackFunction)(void * target, IOReturn result, void * refcon, void * sender); /*! @typedef IOHIDElementCallbackFunction @discussion Type and arguments of callout C function that is used when a completion routine is called, see IOHIDLib.h:setElementValue(). @param target void * pointer to your data, often a pointer to an object. @param result Completion result of desired operation. @param refcon void * pointer to more data. @param sender Interface instance sending the completion routine. @param elementCookie Element within interface instance sending completion. */ typedef void (*IOHIDElementCallbackFunction) (void * target, IOReturn result, void * refcon, void * sender, IOHIDElementCookie elementCookie); /*! @typedef IOHIDReportCallbackFunction @discussion Type and arguments of callout C function that is used when a completion routine is called, see IOHIDLib.h:setReport(). @param target void * pointer to your data, often a pointer to an object. @param result Completion result of desired operation. @param refcon void * pointer to more data. @param sender Interface instance sending the completion routine. @param bufferSize Size of the buffer received upon completion. */ typedef void (*IOHIDReportCallbackFunction) (void * target, IOReturn result, void * refcon, void * sender, uint32_t bufferSize); /* Forward declarations of the queue and output transaction interfaces */ struct IOHIDQueueInterface; struct IOHIDOutputTransactionInterface; typedef struct IOHIDQueueInterface IOHIDQueueInterface; typedef struct IOHIDOutputTransactionInterface IOHIDOutputTransactionInterface; // // IOHIDDeviceInterface Functions available in version 1.0 (10.0) and higher of Mac OS X // #define IOHIDDEVICEINTERFACE_FUNCS_100 \ IOReturn (*createAsyncEventSource)(void * self, CFRunLoopSourceRef * source); \ CFRunLoopSourceRef (*getAsyncEventSource)(void * self); \ IOReturn (*createAsyncPort)(void * self, mach_port_t * port); \ mach_port_t (*getAsyncPort)(void * self); \ IOReturn (*open)(void * self, IOOptionBits flags); \ IOReturn (*close)(void * self); \ IOReturn (*setRemovalCallback)(void * self, IOHIDCallbackFunction removalCallback, \ void * removalTarget, void * removalRefcon); \ IOReturn (*getElementValue)(void * self, IOHIDElementCookie elementCookie, \ IOHIDEventStruct * valueEvent); \ IOReturn (*setElementValue)(void * self, IOHIDElementCookie elementCookie, \ IOHIDEventStruct * valueEvent, uint32_t timeoutMS, \ IOHIDElementCallbackFunction callback, \ void * callbackTarget, void * callbackRefcon); \ IOReturn (*queryElementValue)(void * self, IOHIDElementCookie elementCookie, \ IOHIDEventStruct * valueEvent, uint32_t timeoutMS, \ IOHIDElementCallbackFunction callback, \ void * callbackTarget, void * callbackRefcon); \ IOReturn (*startAllQueues)(void * self); \ IOReturn (*stopAllQueues)(void * self); \ IOHIDQueueInterface ** (*allocQueue) (void *self); \ IOHIDOutputTransactionInterface ** (*allocOutputTransaction) (void *self) // // IOHIDDeviceInterface Functions available in version 1.2.1 (10.2.3) and higher of Mac OS X // #define IOHIDDEVICEINTERFACE_FUNCS_121 \ IOReturn (*setReport)(void * self, IOHIDReportType reportType, uint32_t reportID, \ void * reportBuffer, uint32_t reportBufferSize, \ uint32_t timeoutMS, IOHIDReportCallbackFunction callback, \ void * callbackTarget, void * callbackRefcon); \ IOReturn (*getReport)(void * self, IOHIDReportType reportType, \ uint32_t reportID, void * reportBuffer, \ uint32_t * reportBufferSize, uint32_t timeoutMS, \ IOHIDReportCallbackFunction callback, \ void * callbackTarget, void * callbackRefcon) // // IOHIDDeviceInterface Functions available in version 1.2.2 (10.3) and higher of Mac OS X // #define IOHIDDEVICEINTERFACE_FUNCS_122 \ IOReturn (*copyMatchingElements)(void * self, CFDictionaryRef matchingDict, \ CFArrayRef * elements); \ IOReturn (*setInterruptReportHandlerCallback)(void * self, void * reportBuffer, \ uint32_t reportBufferSize, \ IOHIDReportCallbackFunction callback, \ void * callbackTarget, void * callbackRefcon) typedef struct IOHIDDeviceInterface { IUNKNOWN_C_GUTS; IOHIDDEVICEINTERFACE_FUNCS_100; IOHIDDEVICEINTERFACE_FUNCS_121; } IOHIDDeviceInterface; typedef struct IOHIDDeviceInterface121 { IUNKNOWN_C_GUTS; IOHIDDEVICEINTERFACE_FUNCS_100; IOHIDDEVICEINTERFACE_FUNCS_121; } IOHIDDeviceInterface121; typedef struct IOHIDDeviceInterface122 { IUNKNOWN_C_GUTS; IOHIDDEVICEINTERFACE_FUNCS_100; IOHIDDEVICEINTERFACE_FUNCS_121; IOHIDDEVICEINTERFACE_FUNCS_122; } IOHIDDeviceInterface122; // // IOHIDQueueInterface Functions available in version 1.0 (10.0) and higher of Mac OS X // #define IOHIDQUEUEINTERFACE_FUNCS_100 \ IOReturn (*createAsyncEventSource)(void * self, CFRunLoopSourceRef * source); \ CFRunLoopSourceRef (*getAsyncEventSource)(void * self); \ IOReturn (*createAsyncPort)(void * self, mach_port_t * port); \ mach_port_t (*getAsyncPort)(void * self); \ IOReturn (*create)(void * self, uint32_t flags, uint32_t depth); \ IOReturn (*dispose)(void * self); \ IOReturn (*addElement)(void * self, IOHIDElementCookie elementCookie, uint32_t flags);\ IOReturn (*removeElement)(void * self, IOHIDElementCookie elementCookie); \ Boolean (*hasElement)(void * self, IOHIDElementCookie elementCookie); \ IOReturn (*start)(void * self); \ IOReturn (*stop)(void * self); \ IOReturn (*getNextEvent)(void * self, IOHIDEventStruct * event, \ AbsoluteTime maxTime, uint32_t timeoutMS); \ IOReturn (*setEventCallout)(void * self, IOHIDCallbackFunction callback, \ void * callbackTarget, void * callbackRefcon); \ IOReturn (*getEventCallout)(void * self, IOHIDCallbackFunction * outCallback, \ void ** outCallbackTarget, void ** outCallbackRefcon) struct IOHIDQueueInterface { IUNKNOWN_C_GUTS; IOHIDQUEUEINTERFACE_FUNCS_100; }; // // IOHIDOutputTransactionInterface Functions available in version 1.2 (10.2) and higher of Mac OS X // #define IOHIDOUTPUTTRANSACTIONINTERFACE_FUNCS_120 \ IOReturn (*createAsyncEventSource)(void * self, CFRunLoopSourceRef * source); \ CFRunLoopSourceRef (*getAsyncEventSource)(void * self); \ IOReturn (*createAsyncPort)(void * self, mach_port_t * port); \ mach_port_t (*getAsyncPort)(void * self); \ IOReturn (*create)(void * self); \ IOReturn (*dispose)(void * self); \ IOReturn (*addElement)(void * self, IOHIDElementCookie elementCookie); \ IOReturn (*removeElement)(void * self, IOHIDElementCookie elementCookie); \ Boolean (*hasElement)(void * self, IOHIDElementCookie elementCookie); \ IOReturn (*setElementDefault)(void *self, IOHIDElementCookie elementCookie, \ IOHIDEventStruct * valueEvent); \ IOReturn (*getElementDefault)(void * self, IOHIDElementCookie elementCookie, \ IOHIDEventStruct * outValueEvent); \ IOReturn (*setElementValue)(void * self, IOHIDElementCookie elementCookie, \ IOHIDEventStruct * valueEvent); \ IOReturn (*getElementValue)(void * self, IOHIDElementCookie elementCookie, \ IOHIDEventStruct * outValueEvent); \ IOReturn (*commit)(void * self, uint32_t timeoutMS, IOHIDCallbackFunction callback, \ void * callbackTarget, void * callbackRefcon); \ IOReturn (*clear)(void * self) struct IOHIDOutputTransactionInterface { IUNKNOWN_C_GUTS; IOHIDOUTPUTTRANSACTIONINTERFACE_FUNCS_120; }; // // BEGIN READABLE STRUCTURE DEFINITIONS // // This portion of uncompiled code provides a more reader friendly representation of // the CFPlugin methods defined above. #if 0 /*! @class IOHIDDeviceInterface @discussion CFPlugin object subclass which provides the primary interface to HID devices. */ typedef struct IOHIDDeviceInterface { IUNKNOWN_C_GUTS; /*! @function createAsyncEventSource @abstract Creates async eventsource. @discussion This method will create an async mach port, if one has not already been created. @param source Reference to CFRunLoopSourceRef that is created. @result Returns an IOReturn code. */ IOReturn (*createAsyncEventSource)(void * self, CFRunLoopSourceRef * source); /*! @function getAsyncEventSource @abstract Gets the created async event source. @result Returns a CFRunLoopSourceRef. */ CFRunLoopSourceRef (*getAsyncEventSource)(void * self); /*! @function createAsyncPort @abstract Creates an async port. @discussion The port must be created before any callbacks can be used. @param port Reference to mach port that is created. @result Returns an IOReturn code. */ IOReturn (*createAsyncPort)(void * self, mach_port_t * port); /*! @function getAsyncPort @abstract Gets the current async port. @result Returns a mach_port_t. */ mach_port_t (*getAsyncPort)(void * self); /*! @function open @abstract Opens the device. @param flags Flags to be passed down to the user client. @result Returns an IOReturn code. */ IOReturn (*open)(void * self, uint32_t flags); /*! @function close @abstract Closes the device. @result Returns an IOReturn code. */ IOReturn (*close)(void * self); /*! @function setRemovalCallback @abstract Sets callback to be used when device is removed. @param removalCallback Called when the device is removed. @param removalTarget Passed to the callback. @param removalRefcon Passed to the callback. @result Returns an IOReturn code. */ IOReturn (*setRemovalCallback)(void * self, IOHIDCallbackFunction removalCallback, void * removalTarget, void * removalRefcon); /*! @function getElementValue @abstract Obtains the most recent value of an element. @discussion This call is most useful for interrupt driven elements, such as input type elements. Since feature type element values need to be polled from the device, it is recommended to use the queryElementValue method to obtain the current value. The timestamp field in the event details the last time the element value was altered. @param elementCookie The element of interest. @param valueEvent The event that will be filled. If a long value is present, it is up to the caller to deallocate it. @result Returns an IOReturn code. */ IOReturn (*getElementValue)(void * self, IOHIDElementCookie elementCookie, IOHIDEventStruct * valueEvent); /*! @function setElementValue @abstract Sets an element value on the device. @discussion This call is most useful for feature type elements. It is recommended to use IOOutputTransaction for output type elements. @param elementCookie The element of interest. @param valueEvent The event that will be filled. If a long value is present, it will be copied. @param timeoutMS UNSUPPORTED. @param callback UNSUPPORTED. @param callbackTarget UNSUPPORTED. @param callbackRefcon UNSUPPORTED. @result Returns an IOReturn code. */ IOReturn (*setElementValue)(void * self, IOHIDElementCookie elementCookie, IOHIDEventStruct * valueEvent, uint32_t timeoutMS, IOHIDElementCallbackFunction callback, void * callbackTarget, void * callbackRefcon); /*! @function queryElementValue @abstract Obtains the current value of an element. @discussion This call is most useful for feature type elements. This method will poll the device for the current element value. @param elementCookie The element of interest. @param valueEvent The event that will be filled. If a long value is present, it is up to the caller to deallocate it. @param timeoutMS UNSUPPORTED. @param callback UNSUPPORTED. @param callbackTarget UNSUPPORTED. @param callbackRefcon UNSUPPORTED. @result Returns an IOReturn code. */ IOReturn (*queryElementValue)(void * self, IOHIDElementCookie elementCookie, IOHIDEventStruct * valueEvent, uint32_t timeoutMS, IOHIDElementCallbackFunction callback, void * callbackTarget, void * callbackRefcon); /*! @function startAllQueues @abstract Starts data delivery on all queues for this device. @result Returns an IOReturn code. */ IOReturn (*startAllQueues)(void * self); /*! @function stopAllQueues @abstract Stops data delivery on all queues for this device. @result Returns an IOReturn code. */ IOReturn (*stopAllQueues)(void * self); /*! @function allocQueue @abstract Wrapper to return instances of the IOHIDQueueInterface. @result Returns the created IOHIDQueueInterface. */ IOHIDQueueInterface ** (*allocQueue) (void *self); /*! @function allocOutputTransaction @abstract Wrapper to return instances of the IOHIDOutputTransactionInterface. @result Returns the created IOHIDOutputTransactionInterface. */ IOHIDOutputTransactionInterface ** (*allocOutputTransaction) (void *self); } IOHIDDeviceInterface; /*! @class IOHIDDeviceInterface121 @discussion CFPlugin object subclass which provides the primary interface to HID devices. This class is a subclass of IOHIDDeviceInterface. */ typedef struct IOHIDDeviceInterface121 { IUNKNOWN_C_GUTS; IOHIDDEVICEINTERFACE_FUNCS_100; /*! @function setReport @abstract Sends a report to the device. @param reportType The report type. @param reportID The report id. @param reportBuffer Pointer to a preallocated buffer. @param reportBufferSize Size of the reportBuffer in bytes. @param timeoutMS @param callback If null, this method will behave synchronously. @param callbackTarget The callback target passed to the callback. @param callbackRefcon The callback refcon passed to the callback. @result Returns an IOReturn code. */ IOReturn (*setReport) (void * self, IOHIDReportType reportType, uint32_t reportID, void * reportBuffer, uint32_t reportBufferSize, uint32_t timeoutMS, IOHIDReportCallbackFunction callback, void * callbackTarget, void * callbackRefcon); /*! @function getReport @abstract Obtains a report from the device. @param reportType The report type. @param reportID The report ID. @param reportBuffer Pointer to a preallocated buffer. @param reportBufferSize Size of the reportBuffer in bytes. When finished, will contain the actual size of the report. @param timeoutMS @param callback If null, this method will behave synchronously. @param callbackTarget The callback target passed to the callback. @param callbackRefcon The callback refcon passed to the callback. @result Returns an IOReturn code. */ IOReturn (*getReport) (void * self, IOHIDReportType reportType, uint32_t reportID, void * reportBuffer, uint32_t * reportBufferSize, uint32_t timeoutMS, IOHIDReportCallbackFunction callback, void * callbackTarget, void * callbackRefcon); }IOHIDDeviceInterface121; /*! @class IOHIDDeviceInterface122 @discussion CFPlugin object subclass which provides the primary interface to HID devices. This class is a subclass of IOHIDDeviceInterface121. */ typedef struct IOHIDDeviceInterface122 { IUNKNOWN_C_GUTS; IOHIDDEVICEINTERFACE_FUNCS_100; IOHIDDEVICEINTERFACE_FUNCS_121; /*! @function copyMatchingElements @abstract Obtains specific elements defined by the device. @discussion Using keys defined in IOHIDKeys.h for elements, create a matching dictonary containing items that you wish to search for. A null array indicates that no elements matching that criteria were found. Each item in the array is a reference to the same dictionary item that represents each element in the I/O Registry. It is up to the caller to release the returned array of elements. @param matchingDict Dictionary containg key/value pairs to match on. Pass a null value to match on all elements. @param elements Pointer to a CFArrayRef that will be returned by this method. It is up to the caller to release it when finished. @result Returns an IOReturn code. */ IOReturn (*copyMatchingElements)(void * self, CFDictionaryRef matchingDict, CFArrayRef * elements); /*! @function setInterruptReportHandlerCallback @abstract Sets the report handler callout to be called when the data is received from the Interrupt-In pipe. @discussion In order for this to work correctly, you must call createAsyncPort and createAsyncEventSource. @param reportBuffer Pointer to a preallocated buffer. @param reportBufferSize Size of the reportBuffer in bytes. @param callback If non-NULL, is a callback to be called when data is received from the device. @param callbackTarget The callback target passed to the callback @param callbackRefcon The callback refcon passed to the callback. @result Returns an IOReturn code. */ IOReturn (*setInterruptReportHandlerCallback)( void * self, void * reportBuffer, uint32_t reportBufferSize, IOHIDReportCallbackFunction callback, void * callbackTarget, void * callbackRefcon); }IOHIDDeviceInterface122; /*! @class IOHIDQueueInterface @discussion CFPlugin object subclass which provides an interface for input queues from HID devices. Created by an IOHIDDeviceInterface object. */ typedef struct IOHIDQueueInterface { IUNKNOWN_C_GUTS; /*! @function createAsyncEventSource @abstract Creates an async event source. @discussion This will be used with setEventCallout. @param source The newly created event source. @result Returns an IOReturn code. */ IOReturn (*createAsyncEventSource)(void * self, CFRunLoopSourceRef * source); /*! @function getAsyncEventSource @abstract Obtains the current event source. @result Returns a CFRunLoopSourceRef. */ CFRunLoopSourceRef (*getAsyncEventSource)(void * self); /*! @function createAsyncPort @abstract Creates an async port. @discussion This will be used with createAsyncEventSource. @param port The newly created async port. @result Returns an IOReturn code. */ IOReturn (*createAsyncPort)(void * self, mach_port_t * port); /*! @function getAsyncPort @abstract Obtains the current async port. @result Returns a mach_port_t. */ mach_port_t (*getAsyncPort)(void * self); /*! @function create @abstract Creates the current queue. @param flags Pass kIOHIDQueueOptionsTypeEnqueueAll option to force the IOHIDQueue to enqueue all events, relative or absolute, regardless of change. @param depth The maximum number of elements in the queue before the oldest elements in the queue begin to be lost. @result Returns an IOReturn code. */ IOReturn (*create)(void * self, uint32_t flags, uint32_t depth); /*! @function dispose @abstract Disposes of the current queue. @result Returns an IOReturn code. */ IOReturn (*dispose)(void * self); /*! @function addElement @abstract Adds an element to the queue. @discussion If the element has already been added to queue, an error will be returned. @param elementCookie The element of interest. @param flags @result Returns an IOReturn code. */ IOReturn (*addElement)(void * self, IOHIDElementCookie elementCookie, uint32_t flags); /*! @function removeElement @abstract Removes an element from the queue. @discussion If the element has not been added to queue, an error will be returned. @param elementCookie The element of interest. @result Returns an IOReturn code. */ IOReturn (*removeElement)(void * self, IOHIDElementCookie elementCookie); /*! @function hasElement @abstract Checks whether an element has been added to the queue. @discussion Will return true if present, otherwise will return false. @param elementCookie The element of interest. @result Returns a Boolean value. */ Boolean (*hasElement)(void * self, IOHIDElementCookie elementCookie); /*! @function start @abstract Starts event delivery to the queue. @result Returns an IOReturn code. */ IOReturn (*start)(void * self); /*! @function stop @abstract Stops event delivery to the queue. @result Returns an IOReturn code. */ IOReturn (*stop)(void * self); /*! @function getNextEvent @abstract Reads next event from the queue. @param event The event that will be filled. If a long value is present, it is up to the caller to deallocate it. @param maxTime UNSUPPORTED. If non-zero, limits read events to those that occurred on or before maxTime. @param timeoutMS UNSUPPORTED. The timeout in milliseconds, a zero timeout will cause this call to be non-blocking (returning queue empty) if there is a NULL callback, and blocking forever until the queue is non-empty if there is a valid callback. @result Returns an IOReturn code. */ IOReturn (*getNextEvent)(void * self, IOHIDEventStruct * event, AbsoluteTime maxTime, uint32_t timeoutMS); /*! @function setEventCallout @abstract Sets the event callout to be called when the queue transitions to non-empty. @discussion In order for this to work correctly, you must call createAsyncPort and createAsyncEventSource. @param callback if non-NULL is a callback to be called when data is inserted to the queue @param callbackTarget The callback target passed to the callback @param callbackRefcon The callback refcon passed to the callback. @result Returns an IOReturn code. */ IOReturn (*setEventCallout)(void * self, IOHIDCallbackFunction callback, void * callbackTarget, void * callbackRefcon); /*! @function getEventCallout @abstract Gets the event callout. @discussion This callback will be called the queue transitions to non-empty. @param outCallback if non-NULL is a callback to be called when data is inserted to the queue @param outCallbackTarget The callback target passed to the callback @param outCallbackRefcon The callback refcon passed to the callback @result Returns an IOReturn code. */ IOReturn (*getEventCallout)(void * self, IOHIDCallbackFunction * outCallback, void ** outCallbackTarget, void ** outCallbackRefcon); } IOHIDQueueInterface; /*! @class IOHIDOutputTransactionInterface @discussion CFPlugin object subclass which privides interface for output transactions to HID devices. Created by a IOHIDDeviceInterface object. */ typedef struct IOHIDOutputTransactionInterface { IUNKNOWN_C_GUTS; /*! @function createAsyncEventSource @abstract Creates an async event source. @discussion This will be used with setEventCallout. @param source The newly created event source @result Returns an IOReturn code. */ IOReturn (*createAsyncEventSource)(void * self, CFRunLoopSourceRef * source); /*! @function getAsyncEventSource @abstract Obtains the current event source. @result Returns a CFRunLoopSourceRef. */ CFRunLoopSourceRef (*getAsyncEventSource)(void * self); /*! @function createAsyncPort @abstract Creates an async port. @discussion This will be used with createAsyncEventSource. @param port The newly created async port. @result Returns an IOReturn code. */ IOReturn (*createAsyncPort)(void * self, mach_port_t * port); /*! @function getAsyncPort @abstract Obtains the current async port. @result Returns a mach_port_t. */ mach_port_t (*getAsyncPort)(void * self); /*! @function create @abstract Creates the current transaction. @discussion This method will free any memory that has been allocated for this transaction. @result Returns an IOReturn code. */ IOReturn (*create)(void * self); /*! @function dispose @abstract Disposes of the current transaction. @discussion The transaction will have to be recreated, in order to perform any operations on the transaction. @result Returns an IOReturn code. */ IOReturn (*dispose)(void * self); /*! @function addElement @abstract Adds an element to the transaction. @discussion If the element has already been added to transaction, an error will be returned. @param elementCookie The element of interest. @result Returns an IOReturn code. */ IOReturn (*addElement) (void * self, IOHIDElementCookie elementCookie); /*! @function removeElement @abstract Removes an element from the transaction. @discussion If the element has not been added to transaction, an error will be returned. @param elementCookie The element of interest. @result Returns an IOReturn code. */ IOReturn (*removeElement) (void * self, IOHIDElementCookie elementCookie); /*! @function hasElement @abstract Checks whether an element has been added to the transaction. @discussion Will return true if present, otherwise will return false. @param elementCookie The element of interest. @result Returns a Boolean value. */ Boolean (*hasElement) (void * self, IOHIDElementCookie elementCookie); /*! @function setElementDefault @abstract Sets the default value of an element in a transaction. @discussion An error will be returned if the element has not been added to the transaction. @param elementCookie The element of interest. @param valueEvent The event that will be filled. If a long value is present, it will be copied. @result Returns an IOReturn code. */ IOReturn (*setElementDefault)(void * self, IOHIDElementCookie elementCookie, IOHIDEventStruct * valueEvent); /*! @function getElementDefault @abstract Obtains the default value of an element in a transaction. @discussion An error will be returned if the element has not been added to the transaction. @param elementCookie The element of interest. @param outValueEvent The event that will be filled. If a long value is present, it is up to the caller to deallocate it. @result Returns an IOReturn code. */ IOReturn (*getElementDefault)(void * self, IOHIDElementCookie elementCookie, IOHIDEventStruct * outValueEvent); /*! @function setElementValue @abstract Sets the value of an element in a transaction. @discussion An error will be returned if the element has not been added to the transaction. @param elementCookie The element of interest. @param valueEvent The event that will be filled. If a long value is present, it will be copied. @result Returns an IOReturn code. */ IOReturn (*setElementValue)(void * self, IOHIDElementCookie elementCookie, IOHIDEventStruct * valueEvent); /*! @function getElementValue @abstract Obtains the value of an element in a transaction. @discussion An error will be returned if the element has not been added to the transaction. @param elementCookie The element of interest. @param outValueEvent The event that will be filled. If a long value is present, it is up to the caller to deallocate it. @result Returns an IOReturn code. */ IOReturn (*getElementValue)(void * self, IOHIDElementCookie elementCookie, IOHIDEventStruct * outValueEvent); /*! @function commit @abstract Commits the transaction. @discussion Transaction element values, if set, will be sent to the device. Otherwise, the default element value will be used. If neither are set, that element will be omitted from the commit. After a transaction is committed, transaction element values will be cleared. Default values will be preserved. @param timeoutMS UNSUPPORTED @param callback UNSUPPORTED @param callbackTarget UNSUPPORTED @param callbackRefcon UNSUPPORTED @result Returns an IOReturn code. */ IOReturn (*commit)(void * self, uint32_t timeoutMS, IOHIDCallbackFunction callback, void * callbackTarget, void * callbackRefcon); /*! @function clear @abstract Clears the transaction. @discussion Transaction element values will cleared. Default values will be preserved. @result Returns an IOReturn code. */ IOReturn (*clear)(void * self); } IOHIDOutputTransactionInterface; #endif __END_DECLS #endif /* !_IOKIT_HID_IOHIDLIBOBSOLETE_H_ */
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/hid/IOHIDBase.h
/* * Copyright (c) 1999-2008 Apple Computer, Inc. All Rights Reserved. * * @APPLE_LICENSE_HEADER_START@ * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this * file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_LICENSE_HEADER_END@ */ #ifndef _IOKIT_HID_IOHIDBASE_H_ #define _IOKIT_HID_IOHIDBASE_H_ #include <IOKit/hid/IOHIDKeys.h> #include <IOKit/IOTypes.h> /* IOOptionBits */ #include <stdint.h> /* uint32_t */ __BEGIN_DECLS CF_ASSUME_NONNULL_BEGIN CF_IMPLICIT_BRIDGING_ENABLED /*! @typedef IOHIDDeviceRef This is the type of a reference to the IOHIDDevice. */ typedef struct CF_BRIDGED_TYPE(id) __IOHIDDevice * IOHIDDeviceRef; /*! @typedef IOHIDElementRef This is the type of a reference to the IOHIDElement. */ typedef struct CF_BRIDGED_TYPE(id) __IOHIDElement * IOHIDElementRef; /*! @typedef IOHIDValueRef This is the type of a reference to the IOHIDValue. */ typedef struct CF_BRIDGED_TYPE(id) __IOHIDValue * IOHIDValueRef; /*! @typedef IOHIDTransactionDirectionType @abstract Direction for an IOHIDDeviceTransactionInterface. @constant kIOHIDTransactionDirectionTypeInput Transaction direction used for requesting element values from a device. @constant kIOHIDTransactionDirectionTypeOutput Transaction direction used for dispatching element values to a device. */ typedef CF_ENUM(uint32_t, IOHIDTransactionDirectionType) { kIOHIDTransactionDirectionTypeInput, kIOHIDTransactionDirectionTypeOutput }; /*! @enum IOHIDTransactionOption @abstract Options to be used in conjuntion with an IOHIDDeviceTransactionInterface. @constant kIOHIDTransactionOptionDefaultOutputValue Option to set the default element value to be used with an IOHIDDeviceTransactionInterface of direction kIOHIDTransactionDirectionTypeOutput. */ static const IOOptionBits kIOHIDTransactionOptionDefaultOutputValue = 0x0001; /*! @typedef IOHIDCallback @discussion Type and arguments of callout C function that is used when a completion routine is called. @param context void * pointer to your data, often a pointer to an object. @param result Completion result of desired operation. @param refcon void * pointer to more data. @param sender Interface instance sending the completion routine. */ typedef void (*IOHIDCallback)( void * _Nullable context, IOReturn result, void * _Nullable sender); /*! @typedef IOHIDReportCallback @discussion Type and arguments of callout C function that is used when a HID report completion routine is called. @param context void * pointer to your data, often a pointer to an object. @param result Completion result of desired operation. @param sender Interface instance sending the completion routine. @param type The type of the report that was completed. @param reportID The ID of the report that was completed. @param report Pointer to the buffer containing the contents of the report. @param reportLength Size of the buffer received upon completion. */ typedef void (*IOHIDReportCallback) ( void * _Nullable context, IOReturn result, void * _Nullable sender, IOHIDReportType type, uint32_t reportID, uint8_t * report, CFIndex reportLength); /*! @typedef IOHIDReportCallback @discussion Type and arguments of callout C function that is used when a HID report completion routine is called. @param context void * pointer to your data, often a pointer to an object. @param result Completion result of desired operation. @param sender Interface instance sending the completion routine. @param type The type of the report that was completed. @param reportID The ID of the report that was completed. @param report Pointer to the buffer containing the contents of the report. @param reportLength Size of the buffer received upon completion. @param timeStamp The time at which the report arrived. */ typedef void (*IOHIDReportWithTimeStampCallback) ( void * _Nullable context, IOReturn result, void * _Nullable sender, IOHIDReportType type, uint32_t reportID, uint8_t * report, CFIndex reportLength, uint64_t timeStamp); /*! @typedef IOHIDValueCallback @discussion Type and arguments of callout C function that is used when an element value completion routine is called. @param context void * pointer to more data. @param result Completion result of desired operation. @param sender Interface instance sending the completion routine. @param value IOHIDValueRef containing the returned element value. */ typedef void (*IOHIDValueCallback) ( void * _Nullable context, IOReturn result, void * _Nullable sender, IOHIDValueRef value); /*! @typedef IOHIDValueMultipleCallback @discussion Type and arguments of callout C function that is used when an element value completion routine is called. @param context void * pointer to more data. @param result Completion result of desired operation. @param sender Interface instance sending the completion routine. @param multiple CFDictionaryRef containing the returned element key value pairs. */ typedef void (*IOHIDValueMultipleCallback) ( void * _Nullable context, IOReturn result, void * _Nullable sender, CFDictionaryRef multiple); /*! @typedef IOHIDDeviceCallback @discussion Type and arguments of callout C function that is used when a device routine is called. @param context void * pointer to more data. @param result Completion result of desired operation. @param device IOHIDDeviceRef containing the sending device. */ typedef void (*IOHIDDeviceCallback) ( void * _Nullable context, IOReturn result, void * _Nullable sender, IOHIDDeviceRef device); CF_IMPLICIT_BRIDGING_DISABLED CF_ASSUME_NONNULL_END __END_DECLS #endif /* _IOKIT_HID_IOHIDBASE_H_ */
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/kext/KextManager.h
/* * Copyright (c) 2000-2008, 2012 Apple Inc. All rights reserved. * * @APPLE_OSREFERENCE_LICENSE_HEADER_START@ * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. The rights granted to you under the License * may not be used to create, or enable the creation or redistribution of, * unlawful or unlicensed copies of an Apple operating system, or to * circumvent, violate, or enable the circumvention or violation of, any * terms of an Apple operating system software license agreement. * * Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_OSREFERENCE_LICENSE_HEADER_END@ */ #ifndef __KEXTMANAGER_H__ #define __KEXTMANAGER_H__ #include <CoreFoundation/CoreFoundation.h> #include <libkern/OSReturn.h> #include <sys/cdefs.h> __BEGIN_DECLS /*! * @header KextManager.h * * @abstract * The KextManager API provides a simple interface for applications * to load kernel extensions (kexts) via RPC to kextd, and to look up the * URLs for kexts by bundle identifier. */ /*! * @function KextManagerCreateURLForBundleIdentifier * @abstract Create a URL locating a kext with a given bundle identifier. * * @param allocator * The allocator to use to allocate memory for the new object. * Pass <code>NULL</code> or <code>kCFAllocatorDefault</code> * to use the current default allocator. * @param kextIdentifier * The bundle identifier to look up. * * @result * A CFURLRef locating a kext with the requested bundle identifier. * Returns <code>NULL</code> if the kext cannot be found, or on error. * * @discussion * Kexts are looked up first by whether they are loaded, second by version. * Specifically, if <code>kextIdentifier</code> identifies a kext * that is currently loaded, * the returned URL will locate that kext if it's still present on disk. * If the requested kext is not loaded, * or if its bundle is not at the location it was originally loaded from, * the returned URL will locate the latest version of the desired kext, * if one can be found within the system extensions folder. * If no version of the kext can be found, <code>NULL</code> is returned. */ CFURLRef KextManagerCreateURLForBundleIdentifier( CFAllocatorRef allocator, CFStringRef kextIdentifier) AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER; /*! * @function KextManagerLoadKextWithIdentifier * @abstract * Request the kext loading system to load a kext with a given bundle identifier. * * @param kextIdentifier * The bundle identifier of the kext to look up and load. * @param dependencyKextAndFolderURLs * An array of additional URLs, of individual kexts and * of folders that may contain kexts. * * @result * <code>kOSReturnSuccess</code> if the kext is successfully loaded * (or is already loaded), otherwise returns on error. * * @discussion * <code>kextIdentifier</code> is looked up in the system extensions * folder and among any kexts from <code>dependencyKextAndFolderURLs</code>. * Any non-kext URLs in <code>dependencyKextAndFolderURLs</code> * are scanned at the top level for kexts and plugins of kexts. * * Either the calling process must have an effective user id of 0 (superuser), * or the kext being loaded and all its dependencies must reside in * /System and have an OSBundleAllowUserLoad property of <code>true</code>. */ OSReturn KextManagerLoadKextWithIdentifier( CFStringRef kextIdentifier, CFArrayRef dependencyKextAndFolderURLs) AVAILABLE_MAC_OS_X_VERSION_10_6_AND_LATER; /*! * @function KextManagerLoadKextWithURL * @abstract * Request the kext loading system to load a kext with a given URL. * * @param kextURL * The URL of the kext to load. * @param dependencyKextAndFolderURLs * An array of additional URLs, of individual kexts and * of folders that may contain kexts. * * @result * <code>kOSReturnSuccess</code> if the kext is successfully loaded * (or is already loaded), otherwise returns on error. * * @discussion * Any non-kext URLs in <code>dependencyKextAndFolderURLs</code> * are scanned at the top level for kexts and plugins of kexts. * * Either the calling process must have an effective user id of 0 (superuser), * or the kext being loaded and all its dependencies must reside in * /System and have an OSBundleAllowUserLoad property of <code>true</code>. */ OSReturn KextManagerLoadKextWithURL( CFURLRef kextURL, CFArrayRef dependencyKextAndFolderURLs) AVAILABLE_MAC_OS_X_VERSION_10_6_AND_LATER; /*! * @function KextManagerUnloadKextWithIdentifier * @abstract * Request the kernel to unload a kext with a given bundle identifier. * * @param kextIdentifier * The bundle identifier of the kext to unload. * * @result * <code>kOSReturnSuccess</code> if the kext is * found and successfully unloaded, * otherwise returns on error. * See <code>/usr/include/libkern/OSKextLib.h</code> * for error codes. * * @discussion * The calling process must have an effective user id of 0 (superuser). */ OSReturn KextManagerUnloadKextWithIdentifier( CFStringRef kextIdentifier) AVAILABLE_MAC_OS_X_VERSION_10_7_AND_LATER; /*! * @function KextManagerCopyLoadedKextInfo * @abstract Returns information about loaded kexts in a dictionary. * * @param kextIdentifiers An array of kext identifiers to read from the kernel. * Pass <code>NULL</code> to read info for all loaded kexts. * @param infoKeys An array of info keys to read from the kernel. * Pass <code>NULL</code> to read all information. * @result * A dictionary, keyed by bundle identifier, * of dictionaries containing information about loaded kexts. * * @discussion * The information keys returned by this function are listed below. * Some are taken directly from the kext's information property list, * and some are generated at run time. * Never assume a given key will be present for a kext. * * <ul> * <li><code>CFBundleIdentifier</code> - CFString</li> * <li><code>CFBundleVersion</code> - CFString (note: version strings may be canonicalized * but their numeric values will be the same; "1.2.0" may become "1.2", for example)</li> * <li><code>OSBundleCompatibleVersion</code> - CFString</li> * <li><code>OSBundleIsInterface</code> - CFBoolean</li> * <li><code>OSKernelResource</code> - CFBoolean</li> * <li><code>OSBundleCPUType</code> - CFNumber</li> * <li><code>OSBundleCPUSubtype</code> - CFNumber</li> * <li><code>OSBundlePath</code> - CFString (this is merely a hint stored in the kernel; * the kext is not guaranteed to be at this path)</li> * <li><code>OSBundleExecutablePath</code> - CFString * (the absolute path to the executable within the kext bundle; a hint as above)</li> * <li><code>OSBundleUUID</code> - CFData (the UUID of the kext executable, if it has one)</li> * <li><code>OSBundleStarted</code> - CFBoolean (true if the kext is running)</li> * <li><code>OSBundlePrelinked</code> - CFBoolean (true if the kext is loaded from a prelinked kernel)</li> * <li><code>OSBundleLoadTag</code> - CFNumber (the "Index" given by kextstat)</li> * <li><code>OSBundleLoadAddress</code> - CFNumber</li> * <li><code>OSBundleLoadSize</code> - CFNumber</li> * <li><code>OSBundleWiredSize</code> - CFNumber</li> * <li><code>OSBundleDependencies</code> - CFArray of load tags identifying immediate link dependencies</li> * <li><code>OSBundleRetainCount</code> - CFNumber (the OSObject retain count of the kext itself)</li> * <li><code>OSBundleClasses</code> - CFArray of CFDictionary containing info on C++ classes * defined by the kext:</li> * <ul> * <li><code>OSMetaClassName</code> - CFString</li> * <li><code>OSMetaClassSuperclassName</code> - CFString, absent for root classes</li> * <li><code>OSMetaClassTrackingCount</code> - CFNumber giving the instance count * of the class itself, <i>plus</i> 1 for each direct subclass with any instances</li> * </ul> * </ul> */ CFDictionaryRef KextManagerCopyLoadedKextInfo( CFArrayRef kextIdentifiers, CFArrayRef infoKeys) AVAILABLE_MAC_OS_X_VERSION_10_7_AND_LATER; __END_DECLS #endif /* __KEXTMANAGER_H__ */
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/video/IOVideoDeviceLib.h
/* File: IOVideoDeviceLib.h Contains: IOCFPlugin library for using IOVideoDevice objects. The IOVideoDevice plugin provides a convenient set of functions for accessing and manipulating IOVideoDevice objects from user programs. Copyright: © 2006-2012 by Apple Inc., all rights reserved. */ #if !defined(__IOKIT_IOVIDEODEVICELIB_H) #define __IOKIT_IOVIDEODEVICELIB_H #include <CoreFoundation/CoreFoundation.h> #include <IOKit/IOKitLib.h> #include <IOKit/IOCFPlugIn.h> #include <IOKit/stream/IOStreamLib.h> #include <IOKit/stream/IOStreamShared.h> #include <IOKit/video/IOVideoDeviceShared.h> #include <IOKit/video/IOVideoTypes.h> __BEGIN_DECLS #pragma mark IOVideo UUIDs /*! @defined kIOVideoDeviceLibTypeID @discussion This is the UUID of the plug-in type (5339633C-F903-4212-9C90-9B18AF01862D). */ #define kIOVideoDeviceLibTypeID CFUUIDGetConstantUUIDWithBytes(kCFAllocatorDefault, 0x53, 0x39, 0x63, 0x3C, 0xF9, 0x03, 0x42, 0x12, 0x9C, 0x90, 0x9B, 0x18, 0xAF, 0x01, 0x86, 0x2D) /*! @defined kIOVideoDeviceInterfaceID_v1 @discussion This is the UUID of version 1 of the plug-in interface (080E3-5106-4D16-B70C-B3216F13CDB9A). */ #define kIOVideoDeviceInterfaceID_v1 CFUUIDGetConstantUUIDWithBytes(kCFAllocatorDefault, 0x0D, 0xE0, 0x80, 0xE3, 0x51, 0x06, 0x4D, 0x16, 0xB7, 0x0C, 0xB3, 0x21, 0x6F, 0x13, 0xCD, 0xB9) #define kIOVideoDeviceInterfaceID kIOVideoDeviceInterfaceID_v1 typedef struct IOVideoDeviceInterface_v1_t IOVideoDeviceInterface_v1_t; /*! @typedef IOVideoDeviceRef */ typedef IOVideoDeviceInterface_v1_t** IOVideoDeviceRef; /*! @typedef IOVideoDeviceOutputCallback */ typedef void (*IOVideoDeviceOutputCallback)( IOVideoDeviceRef stream, void* context); /*! @typedef IOVideoDeviceNotificationCallback */ typedef void (*IOVideoDeviceNotificationCallback)( IOVideoDeviceRef device, void* context, void* message); /*! @interface IOVideoDeviceInterface @abstract Interface for accessing kernel-space video drivers from user space. */ typedef struct IOVideoDeviceInterface_v1_t { IUNKNOWN_C_GUTS; UInt32 Version; UInt32 Revision; /*! @functiongroup Opening and closing VideoDevices */ /*! @function Open @abstract Open an IOVideoDevice from user space. @discussion The Open function opens the device. @param device The IOVideoDeviceRef to the device returned by QueryInterface. @param options Open options. Currently unused. @result If the device could not be opened an error will be returned. */ IOReturn (*Open)(IOVideoDeviceRef device, IOOptionBits options); /*! @function Close @abstract Closes an IOVideoDevice. @discussion Calling Close frees all streams belonging to the device and frees all user resources used by the device. @param device The IOVideoDeviceRef of the device to close. @result Returns kIOReturnSuccess if the device was successfully closed. */ IOReturn (*Close)(IOVideoDeviceRef device); /*! @function GetNotificationPort @abstract Get the notification port for device state changes sent to user space. @param device The IOVideoDeviceRef of the stream to operate on. @result A CFMachPortRef of the output notification port. */ CFMachPortRef (*GetNotificationPort)(IOVideoDeviceRef device); /*! @function SetNotificationCallback @abstract Set the callback function to be called when certain device state changes happen. @param device The IOVideoDeviceRef of the device to operate on. Pass NULL to remove the callback. @result Returns kIOReturnSuccess if the callback was successfully set or removed. */ IOReturn (*SetNotificationCallback)( IOVideoDeviceRef device, IOVideoDeviceNotificationCallback callback, void* context); /*! @function SetControlValue @param device @param controlID @param newValue @result Returns kIOReturnSuccess if the call was successfully. */ IOReturn (*SetControlValue)( IOVideoDeviceRef device, UInt32 controlID, UInt32 value, UInt32* newValue); /*! @function SetStreamFormat @param device @param streamID @param streamFormat @result Returns kIOReturnSuccess if the call was successfully. */ IOReturn (*SetStreamFormat)( IOVideoDeviceRef device, UInt32 streamID, IOVideoStreamDescription* streamFormat); /*! @function GetRunLoopSource @abstract Gets a CFRunLoopSource for the CFMachPort used for notifications from the kernel that data is ready. @param device The IOVideoDeviceRef of the stream to operate on. @result The CFRunLoopSourceRef for the run loop source, or NULL if there was an error creating the source. */ CFRunLoopSourceRef (*GetRunLoopSource)(IOVideoDeviceRef device); /*! @function AddToRunLoop @abstract Add the CFRunLoopSource for the notification port to a run loop. @param device The IOVideoDeviceRef of the device to operate on. @param runLoop The run loop to which to add the notification source. @result Returns kIOReturnSuccess if the source was successfully added to the run loop. */ IOReturn (*AddToRunLoop)( IOVideoDeviceRef device, CFRunLoopRef runLoop); /*! @function RemoveFromRunLoop @abstract Remove the CFRunLoopSource for the notification port from a run loop. @param device The IOVideoDeviceRef of the device to operate on. @param runLoop The run loop from which to remove the notification source. @result Returns kIOReturnSuccess if the source was successfully removed from the run loop. */ IOReturn (*RemoveFromRunLoop)( IOVideoDeviceRef device, CFRunLoopRef runLoop); /*! @function CreateStreamInterface @param device The IOVideoDeviceRef of the device to operate on. @param streamDictionary @param streamIndex @param isInput @result Returns kIOReturnSuccess if the stream was successfully created. */ IOReturn (*CreateStreamInterface)( IOVideoDeviceRef device, CFDictionaryRef streamDictionary, UInt32 streamIndex, bool isInput, IOStreamRef* streamRef); /*! @function ReleaseStreamInterface @param device The IOVideoDeviceRef of the device to operate on. @param isInput @param streamRef @result Returns kIOReturnSuccess if the stream was successfully released. */ IOReturn (*ReleaseStreamInterface)( IOVideoDeviceRef device, bool isInput, IOStreamRef* streamRef); } IOVideoDeviceInterface; __END_DECLS #endif
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/video/IOVideoStreamFormatDictionary.h
/* File: IOVideoStreamFormat.h Contains: Copyright: © 2006-2012 by Apple Inc., all rights reserved. */ #if !defined(__IOVideoStreamFormat_h__) #define __IOVideoStreamFormat_h__ // System Includes #include <IOKit/video/IOVideoTypes.h> class OSDictionary; class IOVideoStreamFormatDictionary { public: static OSDictionary* create(UInt32 codecType, UInt32 codecFlags, UInt32 width, UInt32 height); static OSDictionary* createWithDescription(const IOVideoStreamDescription& format); // Attributes public: static UInt32 getCodecType(const OSDictionary* dictionary); static void setCodecType(OSDictionary* dictionary, UInt32 codecType); static UInt32 getCodecFlags(const OSDictionary* dictionary); static void setCodecFlags(OSDictionary* dictionary, UInt32 codecFlags); static UInt32 getWidth(const OSDictionary* dictionary); static void setWidth(OSDictionary* dictionary, UInt32 width); static UInt32 getHeight(const OSDictionary* dictionary); static void setHeight(OSDictionary* dictionary, UInt32 height); static void getDescription(const OSDictionary* dictionary, IOVideoStreamDescription& format); static void printDescription(const IOVideoStreamDescription& format); static void printDictionary(const OSDictionary* dictionary); static bool isSameSampleFormat(const IOVideoStreamDescription& format1, const IOVideoStreamDescription& format2); }; #endif
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/video/IOVideoDevice.h
/* File: IOVideoDevice.h Contains: Copyright: © 2006-2013 by Apple Inc., all rights reserved. */ #if !defined(__IOKIT_IOVIDEODEVICE_H) #define __IOKIT_IOVIDEODEVICE_H #include <IOKit/IOService.h> #include <IOKit/video/IOVideoTypes.h> #include <IOKit/stream/IOStreamShared.h> class IOVideoStream; /*! @class IOVideoDevice @abstract A class representing a video device. @discussion The IOVideoDevice class defines a mechanism for accessing the IOVideoStreams that a device presents. Although it is expected that the client of an IOVideoDevice will be in user space, this is not required. */ class IOVideoDevice : public IOService { // Construction/Destruction OSDeclareDefaultStructors(IOVideoDevice); public: virtual bool init(OSDictionary* properties); virtual void free(void); /*! @function newUserClient @abstract See the documentation for the IOService method newUserClient. */ virtual IOReturn newUserClient(task_t owningTask, void* securityID, UInt32 type, OSDictionary* properties, IOUserClient** handler); /*! @function getStreamCount @result Returns the number of streams of the device. */ virtual int getStreamCount(void); /*! @function getStream @param streamIndex The index for which the underlying stream is desired. @result Returns the number of streams of the device. */ virtual IOVideoStream* getStream(UInt32 streamIndex); /*! @function startStream @abstract Start sending data on a stream. @result Returns kIOReturnSuccess if the stream was successfully started. @discussion This must be implemented by a subclass. */ virtual IOReturn startStream(IOVideoStream* stream); /*! @function stopStream @abstract Stop sending data on a stream. @result Returns kIOReturnSuccess if the stream was successfully started. @discussion This must be implemented by a subclass. */ virtual IOReturn stopStream(IOVideoStream* stream); /*! @function suspendStream @abstract Temporarily suspend data flow on the stream. @result Returns kIOReturnSuccess if the stream was successfully suspended. @discussion This must be implemented by a subclass. */ virtual IOReturn suspendStream(IOVideoStream* stream); /*! @function setStreamMode @abstract Sets the mode of the stream, either input or output. @discussion This must be implemented by a subclass. */ virtual IOReturn setStreamMode(IOVideoStream* stream, IOStreamMode mode); virtual IOReturn openStream(UInt32 streamIndex); virtual IOReturn closeStream(UInt32 streamIndex); virtual IOReturn startStream(UInt32 streamIndex); virtual IOReturn stopStream(UInt32 streamIndex); virtual IOReturn suspendStream(UInt32 streamIndex); virtual IOReturn releaseStreams(void); virtual void inputCallback(UInt32 token); virtual void inputSyncCallback(UInt32 token); virtual IOReturn registerNotificationPort(mach_port_t port, UInt32 type, UInt32 clientData); virtual void sendSingleNotification(UInt32 notificationID, UInt32 objectID, UInt32 notificationArgument1, UInt32 notificationArgument2, UInt64 notificationArgument3, UInt64 notificationArgument4); virtual void sendMultiNotification(UInt32 numberNotifications, const IOVideoDeviceNotification* notifications); virtual IOReturn setStreamFormat(UInt32 streamID, const IOVideoStreamDescription* newStreamFormat); // Control methods virtual IOReturn setControlValue(UInt32 controlID, UInt32 value, UInt32* newValue); protected: virtual IOReturn addStream(IOVideoStream* stream); virtual IOReturn removeStream(UInt32 streamIndex); OSArray* mStreams; IOVideoDeviceNotificationMessage* mNotificationMessage; UInt32 mMaxNumberNotifications; UInt32 mOutstandingConfigChangeRequests; // Future Expansion public: OSMetaClassDeclareReservedUnused(IOVideoDevice, 0); OSMetaClassDeclareReservedUnused(IOVideoDevice, 1); OSMetaClassDeclareReservedUnused(IOVideoDevice, 2); OSMetaClassDeclareReservedUnused(IOVideoDevice, 3); OSMetaClassDeclareReservedUnused(IOVideoDevice, 4); OSMetaClassDeclareReservedUnused(IOVideoDevice, 5); OSMetaClassDeclareReservedUnused(IOVideoDevice, 6); OSMetaClassDeclareReservedUnused(IOVideoDevice, 7); OSMetaClassDeclareReservedUnused(IOVideoDevice, 8); OSMetaClassDeclareReservedUnused(IOVideoDevice, 9); OSMetaClassDeclareReservedUnused(IOVideoDevice, 10); OSMetaClassDeclareReservedUnused(IOVideoDevice, 11); OSMetaClassDeclareReservedUnused(IOVideoDevice, 12); OSMetaClassDeclareReservedUnused(IOVideoDevice, 13); OSMetaClassDeclareReservedUnused(IOVideoDevice, 14); OSMetaClassDeclareReservedUnused(IOVideoDevice, 15); OSMetaClassDeclareReservedUnused(IOVideoDevice, 16); OSMetaClassDeclareReservedUnused(IOVideoDevice, 17); OSMetaClassDeclareReservedUnused(IOVideoDevice, 18); OSMetaClassDeclareReservedUnused(IOVideoDevice, 19); OSMetaClassDeclareReservedUnused(IOVideoDevice, 20); OSMetaClassDeclareReservedUnused(IOVideoDevice, 21); OSMetaClassDeclareReservedUnused(IOVideoDevice, 22); OSMetaClassDeclareReservedUnused(IOVideoDevice, 23); OSMetaClassDeclareReservedUnused(IOVideoDevice, 24); OSMetaClassDeclareReservedUnused(IOVideoDevice, 25); OSMetaClassDeclareReservedUnused(IOVideoDevice, 26); OSMetaClassDeclareReservedUnused(IOVideoDevice, 27); OSMetaClassDeclareReservedUnused(IOVideoDevice, 28); OSMetaClassDeclareReservedUnused(IOVideoDevice, 29); OSMetaClassDeclareReservedUnused(IOVideoDevice, 30); OSMetaClassDeclareReservedUnused(IOVideoDevice, 31); protected: struct ExpansionData {}; ExpansionData *mReserved; }; #endif
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/video/IOVideoStreamDictionary.h
/* File: IOVideoStreamDictionary.h Contains: Copyright: © 2006-2012 by Apple Inc., all rights reserved. */ #if !defined(__IOVideoStreamDictionary_h__) #define __IOVideoStreamDictionary_h__ // System Includes #include <IOKit/video/IOVideoTypes.h> class OSArray; class OSDictionary; class IOVideoStreamDictionary { // Construction/Destruction public: static OSDictionary* create(UInt32 streamID, UInt32 startingDeviceChannelNumber, const OSDictionary* currentFormat, OSArray* availableFormats = NULL); // Attributes public: static UInt32 getStreamID(const OSDictionary* dictionary); static void setStreamID(OSDictionary* dictionary, UInt32 streamID); static UInt32 getStartingDeviceChannelNumber(const OSDictionary* dictionary); static void setStartingDeviceChannelNumber(OSDictionary* dictionary, UInt32 startingDeviceChannelNumber); static IOOptionBits getBufferMappingOptions(const OSDictionary* dictionary); static void setBufferMappingOptions(OSDictionary* dictionary, IOOptionBits bufferMappingOptions); static bool getCurrentFormat(const OSDictionary* dictionary, IOVideoStreamDescription& format); static void setCurrentFormat(OSDictionary* dictionary, const IOVideoStreamDescription& format); static OSDictionary* copyCurrentFormatDictionary(const OSDictionary* dictionary); static void setCurrentFormatDictionary(OSDictionary* dictionary, const OSDictionary* format); static OSArray* copyAvailableFormats(const OSDictionary* dictionary); static void setAvailableFormats(OSDictionary* dictionary, OSArray* availableFormats); static void printDictionary(const OSDictionary* dictionary); }; #endif
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/video/IOVideoDeviceUserClient.h
/* File: IOVideoDeviceUserClient.h Contains: Copyright: © 2006-2012 by Apple Inc., all rights reserved. */ #if !defined(__IOKIT_IOVIDEODEVICEUSERCLIENT_H) #define __IOKIT_IOVIDEODEVICEUSERCLIENT_H /*! @enum User client methods @constant kIOVideoDeviceMethodOpen @constant kIOVideoDeviceMethodClose @constant kIOVideoDeviceMethodGetMode @constant kIOVideoDeviceMethodSetControlValue @constant kIOVideoDeviceMethodOpenStream @constant kIOVideoDeviceMethodCloseStream @constant kIOVideoDeviceMethodSetStreamFormat @constant kIOVideoDeviceMethodStartStream @constant kIOVideoDeviceMethodStopStream @constant kIOVideoDeviceMethodSuspendStream @abstract Client method numbers used with IOConnectMethod...() functions. */ enum { kIOVideoDeviceMethodOpen = 0, kIOVideoDeviceMethodClose, kIOVideoDeviceMethodGetMode, kIOVideoDeviceMethodSetMode, kIOVideoDeviceMethodSetControlValue, kIOVideoDeviceMethodOpenStream, kIOVideoDeviceMethodCloseStream, kIOVideoDeviceMethodSetStreamFormat, kIOVideoDeviceMethodStartStream, kIOVideoDeviceMethodStopStream, kIOVideoDeviceMethodSuspendStream, kIOVideoDeviceMethodCount }; #ifdef KERNEL #ifdef __cplusplus #include <IOKit/IOUserClient.h> #include <IOKit/stream/IOStreamShared.h> #include <IOKit/video/IOVideoTypes.h> class IOVideoDevice; class IOVideoDeviceUserClient : public IOUserClient { // Construction/Destruction OSDeclareDefaultStructors(IOVideoDeviceUserClient) // Static versions of external methods private: static IOReturn sOpen(IOVideoDeviceUserClient* target, void* reference, IOExternalMethodArguments* arguments); static IOReturn sClose(IOVideoDeviceUserClient* target, void* reference, IOExternalMethodArguments* arguments); static IOReturn sGetMode(IOVideoDeviceUserClient* target, void* reference, IOExternalMethodArguments* arguments); static IOReturn sSetMode(IOVideoDeviceUserClient* target, void* reference, IOExternalMethodArguments* arguments); static IOReturn sSetControlValue(IOVideoDeviceUserClient* target, void* reference, IOExternalMethodArguments* arguments); static IOReturn sOpenStream(IOVideoDeviceUserClient* target, void* reference, IOExternalMethodArguments* arguments); static IOReturn sCloseStream(IOVideoDeviceUserClient* target, void* reference, IOExternalMethodArguments* arguments); static IOReturn sSetStreamFormat(IOVideoDeviceUserClient* target, void* reference, IOExternalMethodArguments* arguments); static IOReturn sStartStream(IOVideoDeviceUserClient* target, void* reference, IOExternalMethodArguments* arguments); static IOReturn sStopStream(IOVideoDeviceUserClient* target, void* reference, IOExternalMethodArguments* arguments); static IOReturn sSuspendStream(IOVideoDeviceUserClient* target, void* reference, IOExternalMethodArguments* arguments); protected: const IOExternalMethodDispatch* mExternalMethods; IOVideoDevice* mDevice; task_t mTask; // IOUserClient overriden methods public: virtual bool initWithTask(task_t owningTask, void* securityToken, UInt32 type); virtual bool initWithTask(task_t owningTask, void* securityToken, UInt32 type, OSDictionary* properties); virtual IOReturn clientClose(void); virtual IOReturn clientDied(void); virtual IOService* getService(void); virtual IOReturn registerNotificationPort(mach_port_t port, UInt32 portType, UInt32 refCon); virtual IOReturn connectClient(IOUserClient* client); virtual IOReturn externalMethod(uint32_t selector, IOExternalMethodArguments* arguments, IOExternalMethodDispatch* dispatch, OSObject* target, void* reference); // IOService overriden methods virtual bool start(IOService* provider); // external methods public: virtual IOReturn open(IOOptionBits options); virtual IOReturn close(void); virtual IOReturn getMode(UInt32 streamIndex, IOStreamMode* mode); virtual IOReturn setMode(UInt32 streamIndex, IOStreamMode mode); virtual IOReturn setControlValue(UInt32 controlID, UInt32 value, UInt32* newValue); virtual IOReturn setStreamFormat(UInt32 streamID, const IOVideoStreamDescription* newStreamFormat); virtual IOReturn openStream(UInt32 streamIndex); virtual IOReturn closeStream(UInt32 streamIndex); virtual IOReturn startStream(UInt32 streamIndex); virtual IOReturn stopStream(UInt32 streamIndex); virtual IOReturn suspendStream(UInt32 streamIndex); }; #endif /* __cplusplus */ #endif /* KERNEL */ #endif
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/video/IOVideoDeviceShared.h
/* File: IOVideoDeviceShared.h Contains: Copyright: © 2006-2012 by Apple Inc., all rights reserved. */ #if !defined(__IOKIT_IOVIDEODEVICESHARED_H) #define __IOKIT_IOVIDEODEVICESHARED_H #include <sys/cdefs.h> #include <IOKit/IOTypes.h> /*! @header IOVideoDeviceShared.h IOVideoDevice definitions shared between kernel and user space. */ __BEGIN_DECLS /*! @enum Mach port types @constant kIOVideoDevicePortTypeNotification @constant kIOVideoDevicePortTypeOutput @constant kIOVideoDevicePortTypeInput @abstract Port types used with IOConnectSetNotificationPort(). */ enum { kIOVideoDevicePortTypeNotification, kIOVideoDevicePortTypeOutput, kIOVideoDevicePortTypeInput }; __END_DECLS #endif /* ! __IOKIT_IOVIDEODEVICESHARED_H */
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/video/IOVideoTypes.h
/* File: IOVideoTypes.h Contains: Copyright: © 2006-2014 by Apple Inc., all rights reserved. */ #if !defined(__IOVideoTypes_h__) #define __IOVideoTypes_h__ // System Includes #include <IOKit/IOTypes.h> #include <mach/message.h> #if defined(__cplusplus) extern "C" { #endif /*! @struct IOVideoDeviceNotification @abstract This structure contains an individual notification from the driver. @field mObjectID The ID of the object to which the notification pertains. @field mNotificationID A UInt32 that identifies the kind of the notification. @field mNotificationArgument1 A UInt32 whose usage depends on the the specific kind of notification. @field mNotificationArgument2 A UInt32 whose usage depends on the the specific kind of notification. @field mNotificationArgument3 A UInt64 whose usage depends on the the specific kind of notification. @field mNotificationArgument4 A UInt64 whose usage depends on the the specific kind of notification. */ struct IOVideoDeviceNotification { UInt32 mObjectID; UInt32 mNotificationID; UInt32 mNotificationArgument1; UInt32 mNotificationArgument2; UInt64 mNotificationArgument3; UInt64 mNotificationArgument4; }; typedef struct IOVideoDeviceNotification IOVideoDeviceNotification; /*! @struct IOVideoDeviceNotificationMessage @abstract This structure describes a notification from the driver. Note that the message can contain multiple notifications. @field mMessageHeader The mach message header. @field mClientData The client data that was registered with the mach port. @field mNumberNotifications The number of IOVideoDeviceNotifications in the mNotifications array. @field mNotifications A variable length array of IOVideoDeviceNotification structures that carry the actual notification data. The number of elements in this array is denoted by mNumberNotifications, but can also be inferred from the message size in the mach message header. */ struct IOVideoDeviceNotificationMessage { mach_msg_header_t mMessageHeader; UInt32 mClientData; UInt32 mNumberNotifications; IOVideoDeviceNotification mNotifications[1]; }; typedef struct IOVideoDeviceNotificationMessage IOVideoDeviceNotificationMessage; #define CalculateIOVideoDeviceNotificationMessageSize(numberNotifications) (sizeof(IOVideoDeviceNotificationMessage) + (((numberNotifications) - 1) * sizeof(IOVideoDeviceNotification))) #pragma mark Notification IDs /*! @enum Notification IDs @discussion @abstract The four char codes used to identify the kind of the notification. @discussion All device-level notifications will have an object ID of 0. @constant kIOVideoDeviceNotificationID_ControlValueChanged Indicates that the value of the control with the given ID has changed. The first argument is the new value. @constant kIOVideoDeviceNotificationID_ControlRangeChanged Indicates that the range of the control with the given ID has changed. */ enum { kIOVideoDeviceNotificationID_ControlValueChanged = 'cval', kIOVideoDeviceNotificationID_ControlRangeChanged = 'crng' }; struct IOVideoStreamDescription { UInt32 mVideoCodecType; UInt32 mVideoCodecFlags; UInt32 mWidth; UInt32 mHeight; UInt32 mReserved1; UInt32 mReserved2; }; typedef struct IOVideoStreamDescription IOVideoStreamDescription; //================================================================================================== #pragma mark Control Constants /*! @enum Control Constants @discussion @abstract Various constants related to controls. @constant kIOVideoControlScopeGlobal The scope for controls that apply to the device as a whole. @constant kIOVideoControlScopeInput The scope for controls that apply to the input section of the device. @constant kIOVideoControlScopeOutput The scope for controls that apply to the output section of the device. @constant kIOVideoControlScopePlayThrough The scope for controls that apply to the play through section of the device. @constant kIOVideoControlElementMaster The element value for controls that apply to the master element or to the entire scope. Note that other elements are numbered consecutively starting from 1. */ enum { kIOVideoControlScopeGlobal = 'glob', kIOVideoControlScopeInput = 'inpt', kIOVideoControlScopeOutput = 'outp', kIOVideoControlScopePlayThrough = 'ptru', kIOVideoControlElementMaster = 0 }; /*! @enum Control Base Class IDs @discussion @abstract The class IDs that identify the various control base classes. @constant kIOVideoControlBaseClassIDBoolean The class ID that identifies the boolean control class which is a subclass of the base control class. Boolean controls manipulate on/off switches in the hardware. @constant kIOVideoControlBaseClassIDSelector The class ID that identifies the selector control class which is a subclass of the base control class. Selector controls manipulate controls that have multiple, but discreet values. @constant kIOVideoControlBaseClassIDFeature The class ID that identifies the feature control class which is a subclass of the base control class. Feature controls manipulate various features that might be present on a device, such as hue, saturation, zoom, etc. */ enum { kIOVideoControlBaseClassIDBoolean = 'togl', kIOVideoControlBaseClassIDSelector = 'slct', kIOVideoControlBaseClassIDFeature = 'ftct' }; /*! @enum IOVideoBooleanControl Subclass IDs @discussion @abstract The four char codes that identify the various standard subclasses of IOVideoBooleanControl. @constant kIOVideoBooleanControlClassIDJack A IOVideoBooleanControl where a true value means something is plugged into that element. @constant kIOVideoBooleanControlClassIDDirection A IOVideoBooleanControl where a true value means the element is operating in input mode, and false means the element is operating in output mode. This control is only needed for devices which can do input and output, but not at the same time. */ enum { kIOVideoBooleanControlClassIDJack = 'jack', kIOVideoBooleanControlClassIDDirection = 'dire' }; /*! @enum IOVideoSelectorControl Subclass IDs @discussion @abstract The four char codes that identify the various standard subclasses of IOVideoSelectorControl. @constant kIOVideoSelectorControlClassIDDataSource A IOVideoSelectorControl that identifies where the data for the element is coming from. @constant kIOVideoSelectorControlClassIDDataDestination A IOVideoSelectorControl that identifies where the data for the element is going. */ enum { kIOVideoSelectorControlClassIDDataSource = 'dsrc', kIOVideoSelectorControlClassIDDataDestination = 'dest' }; /*! @enum IOVideoFeatureControl Subclass IDs @discussion @abstract The four char codes that identify the various standard subclasses of IOVideoFeatureControl. @constant kIOVideoFeatureControlClassIDBlackLevel A IOVideoFeatureControl that controls the black level offset. The units for the control's absolute value are percetage (%). @constant kIOVideoFeatureControlClassIDWhiteLevel A IOVideoFeatureControl that controls the white level offset. The units for the control's absolute value are percentage (%). @constant kIOVideoFeatureControlClassIDHue A IOVideoFeatureControl that controls the hue offset. Positive values mean counterclockwise, negative values means clockwise on a vector scope. The units for the control's absolute value are degrees (°). @constant kIOVideoFeatureControlClassIDSaturation A IOVideoFeatureControl that controls color intensity. For example, at high saturation levels, red appears to be red; at low saturation, red appears as pink. The unit for the control's absolute value is a percentage (%). @constant kIOVideoFeatureControlClassIDContrast A IOVideoFeatureControl that controls a the distance bewtween the whitest whites and blackest blacks. The units for the control's absolute value are percentage (%). @constant kIOVideoFeatureControlClassIDSharpness A IOVideoFeatureControl that controls the sharpness of the picture. The units for the control's absolute value are undefined. @constant kIOVideoFeatureControlClassIDBrightness A IOVideoFeatureControl that controls the intensity of the video level. The units for the control's absolute value are percetage (%). @constant kIOVideoFeatureControlClassIDGain A IOVideoFeatureControl that controls the amplification of the signal. The units for the control's absolute value are decibels (dB). @constant kIOVideoFeatureControlClassIDIris A IOVideoFeatureControl that controls a mechanical lens iris. The units for the control's absolute value are an F number (F). @constant kIOVideoFeatureControlClassIDShutter A IOVideoFeatureControl that controls the integration time of the incoming light. The units for the control's absolute value are seconds (s). @constant kIOVideoFeatureControlClassIDExposure A IOVideoFeatureControl that controls a the total amount of light accumulated. The units for the control's absolute value are exposure value (EV). @constant kIOVideoFeatureControlClassIDWhiteBalanceU A IOVideoFeatureControl that controls the adjustment of the white color of the picture. The units for the control's absolute value are kelvin (K). @constant kIOVideoFeatureControlClassIDWhiteBalanceV A IOVideoFeatureControl that controls a adjustment of the white color of the picture. The units for the control's absolute value are kelvin (K). @constant kIOVideoFeatureControlClassIDGamma A IOVideoFeatureControl that defines the function between incoming light level and output picture level. The units for the control's absolute value are undefined. @constant kIOVideoFeatureControlClassIDTemperature A IOVideoFeatureControl that controls the temperature inside of the device and/or controlling temperature. The units for the control's absolute value are undefined. @constant kIOVideoFeatureControlClassIDZoom A IOVideoFeatureControl that controls the zoom. The units for the control's absolute value are power where 1 is the wide end. @constant kIOVideoFeatureControlClassIDFocus A IOVideoFeatureControl that controls a focus mechanism. The units for the control's absolute value are meters (m). @constant kIOVideoFeatureControlClassIDPan A IOVideoFeatureControl that controls a panning mechanism. Positive values mean clockwise, negative values means counterclockwise. The units for the control's absolute value are degrees (°). @constant kIOVideoFeatureControlClassIDTilt A IOVideoFeatureControl that controls a tilt mechanism. Positive values mean upwards, negative values means downwards. The units for the control's absolute value are degrees (°). @constant kIOVideoFeatureControlClassIDOpticalFilter A IOVideoFeatureControl that controls changing the optical filter of camera lens function. The units for the control's absolute value are are undefined. @constant kIOVideoFeatureControlClassIDBacklightCompensation A IOVideoFeatureControl that controls the amount of backlight compensation to apply. A low number indicates the least amount of backlight compensation. The units for the control's absolute value are are undefined. @constant kIOVideoFeatureControlClassIDPowerLineFrequency A IOVideoFeatureControl to specify the power line frequency to properly implement anti-flicker processing. The units for the contorl's absolute value are hertz (Hz). */ enum { kIOVideoFeatureControlClassIDBlackLevel = 'bklv', kIOVideoFeatureControlClassIDWhiteLevel = 'whlv', kIOVideoFeatureControlClassIDHue = 'hue ', kIOVideoFeatureControlClassIDSaturation = 'satu', kIOVideoFeatureControlClassIDContrast = 'ctst', kIOVideoFeatureControlClassIDSharpness = 'shrp', kIOVideoFeatureControlClassIDBrightness = 'brit', kIOVideoFeatureControlClassIDGain = 'gain', kIOVideoFeatureControlClassIDIris = 'iris', kIOVideoFeatureControlClassIDShutter = 'shtr', kIOVideoFeatureControlClassIDExposure = 'xpsr', kIOVideoFeatureControlClassIDWhiteBalanceU = 'whbu', kIOVideoFeatureControlClassIDWhiteBalanceV = 'whbv', kIOVideoFeatureControlClassIDGamma = 'gmma', kIOVideoFeatureControlClassIDTemperature = 'temp', kIOVideoFeatureControlClassIDZoom = 'zoom', kIOVideoFeatureControlClassIDFocus = 'fcus', kIOVideoFeatureControlClassIDPan = 'pan ', kIOVideoFeatureControlClassIDTilt = 'tilt', kIOVideoFeatureControlClassIDOpticalFilter = 'opft', kIOVideoFeatureControlClassIDBacklightCompensation = 'bklt', kIOVideoFeatureControlClassIDPowerLineFrequency = 'pwfq' }; //================================================================================================== #pragma mark IORegistry Keys // IOVideo Class Names #define kIOVideoDevice_ClassName "IOVideoDevice" // IOVideoDevice IORegistry Keys #pragma mark IOVideoDevice IORegistry Keys #define kIOVideoDeviceKey_DeviceName "device name" #define kIOVideoDeviceKey_DeviceManufacturer "device manufacturer" #define kIOVideoDeviceKey_DeviceUID "device UID" #define kIOVideoDeviceKey_IOEngineIsRunning "is running" #define kIOVideoDeviceKey_InputLatency "input latency" #define kIOVideoDeviceKey_OutputLatency "output latency" #define kIOVideoDeviceKey_InputStreamList "input streams" #define kIOVideoDeviceKey_OutputStreamList "output streams" #define kIOVideoDeviceKey_ControlList "controls" // IOVideoDevice Stream Dictionary Keys #pragma mark IOVideoDevice Stream Dictionary Keys #define kIOVideoStreamKey_StreamID "stream ID" #define kIOVideoStreamKey_StartingDeviceChannelNumber "starting channel" #define kIOVideoStreamKey_BufferMappingOptions "buffer mapping options" #define kIOVideoStreamKey_CurrentFormat "current format" #define kIOVideoStreamKey_AvailableFormats "available formats" // IOVideoDevice Control Dictionary Keys #pragma mark IOVideoDevice Control Dictionary Keys #define kIOVideoControlKey_ControlID "control ID" #define kIOVideoControlKey_BaseClass "base class" #define kIOVideoControlKey_Class "class" #define kIOVideoControlKey_Scope "scope" #define kIOVideoControlKey_Element "element" #define kIOVideoControlKey_IsReadOnly "read only" #define kIOVideoControlKey_Variant "variant" #define kIOVideoControlKey_Name "name" #define kIOVideoControlKey_Value "value" // IOVideoDevice Selector Control Dictionary Keys #pragma mark IOVideoDevice Selector Control Dictionary Keys #define kIOVideoSelectorControlKey_SelectorMap "selectors" // IOVideoDevice Selector Control Selector Map Item Dictionary Keys #pragma mark IOVideoDevice Selector Control Selector Map Item Dictionary Keys #define kIOVideoSelectorControlSelectorMapItemKey_Value "value" #define kIOVideoSelectorControlSelectorMapItemKey_Name "name" #define kIOVideoSelectorControlSelectorMapItemKey_Kind "kind" // Stream Format Dictionary Keys #pragma mark Stream Format Dictionary Keys #define kIOVideoStreamFormatKey_CodecType "codec type" #define kIOVideoStreamFormatKey_CodecFlags "codec flags" #define kIOVideoStreamFormatKey_Width "width" #define kIOVideoStreamFormatKey_Height "height" //================================================================================================== #if defined(__cplusplus) } #endif #endif
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/video/IOVideoStream.h
/* File: IOVideoStream.h Contains: Copyright: © 2006-2012 by Apple Inc., all rights reserved. */ #ifndef __IOKIT_IOVIDEOSTREAM_H #define __IOKIT_IOVIDEOSTREAM_H #include <IOKit/stream/IOStream.h> class IOVideoDevice; /*! @class IOVideoStream @abstract A class representing a stream of video data buffers passed from kernel to user space and back again. @discussion The IOVideoStream class defines a mechanism for moving buffers of data from kernel space to user space or vice-versa. The policy for which direction the data flows and the nature of the data is left up the the implementer of the driver which uses IOStream. Although it is expected that the client of an IOVideoStream will be in user space, this is not required. References to "output" mean "from the IOVideoStream to the user client", and "input" means "from the user client to the IOVideoStream." */ class IOVideoStream : public IOStream { // Construction/Destruction OSDeclareDefaultStructors(IOVideoStream); protected: IOStreamMode mStreamMode; public: /*! @function withBuffers @param buffers An array of IOStreamBuffer objects which will be the buffers for this stream. @param mode The initial mode of the video stream, either output, input, or input/output. @param queueLength The nuber of queue entries to reserve in the input and output queue. Zero means to make the queues big enough to accommodate all the buffers at once. @param properties A dictionary of properties which will be set on the video stream. */ static IOVideoStream* withBuffers(OSArray* buffers, IOStreamMode mode = kIOStreamModeOutput, IOItemCount queueLength = 0, OSDictionary* properties = 0); /*! @function initWithBuffers @param buffers An array of IOStreamBuffer objects which will be the buffers for this stream. @param mode The initial mode of the video stream, either output, input, or input/output. @param queueLength The nuber of queue entries to reserve in the input and output queue. Zero means to make the queues big enough to accommodate all the buffers at once. @param properties A dictionary of properties which will be set on the video stream. */ virtual bool initWithBuffers(OSArray* buffers, IOStreamMode mode = kIOStreamModeOutput, IOItemCount queueLength = 0, OSDictionary* properties = 0); virtual IOVideoDevice* getDevice(void); // Returns provider cast to an IOVideoDevice /*! @function getStreamMode @abstract Returns the mode of the stream, either input or output. @result The mode of the stream, either kIOStreamModeInput (from user space to kernel space) or the default kIOStreamModeOutput (from kernel space to user space). */ virtual IOStreamMode getStreamMode(void); /*! @function setStreamMode @abstract Sets the mode of the stream, either input or output. */ virtual IOReturn setStreamMode(IOStreamMode mode); /*! @function startStream @abstract Start sending data on a stream. @result Returns kIOReturnSuccess if the stream was successfully started. */ virtual IOReturn startStream(void); /*! @function stopStream @abstract Stop sending data on a stream. @result Returns kIOReturnSuccess if the stream was successfully started. */ virtual IOReturn stopStream(void); /*! @function suspendStream @abstract Temporarily suspend data flow on the stream. @result Returns kIOReturnSuccess if the stream was successfully suspended. */ virtual IOReturn suspendStream(void); // Future Expansion public: OSMetaClassDeclareReservedUnused(IOVideoStream, 0); OSMetaClassDeclareReservedUnused(IOVideoStream, 1); OSMetaClassDeclareReservedUnused(IOVideoStream, 2); OSMetaClassDeclareReservedUnused(IOVideoStream, 3); OSMetaClassDeclareReservedUnused(IOVideoStream, 4); OSMetaClassDeclareReservedUnused(IOVideoStream, 5); OSMetaClassDeclareReservedUnused(IOVideoStream, 6); OSMetaClassDeclareReservedUnused(IOVideoStream, 7); OSMetaClassDeclareReservedUnused(IOVideoStream, 8); OSMetaClassDeclareReservedUnused(IOVideoStream, 9); OSMetaClassDeclareReservedUnused(IOVideoStream, 10); OSMetaClassDeclareReservedUnused(IOVideoStream, 11); OSMetaClassDeclareReservedUnused(IOVideoStream, 12); OSMetaClassDeclareReservedUnused(IOVideoStream, 13); OSMetaClassDeclareReservedUnused(IOVideoStream, 14); OSMetaClassDeclareReservedUnused(IOVideoStream, 15); OSMetaClassDeclareReservedUnused(IOVideoStream, 16); OSMetaClassDeclareReservedUnused(IOVideoStream, 17); OSMetaClassDeclareReservedUnused(IOVideoStream, 18); OSMetaClassDeclareReservedUnused(IOVideoStream, 19); OSMetaClassDeclareReservedUnused(IOVideoStream, 20); OSMetaClassDeclareReservedUnused(IOVideoStream, 21); OSMetaClassDeclareReservedUnused(IOVideoStream, 22); OSMetaClassDeclareReservedUnused(IOVideoStream, 23); OSMetaClassDeclareReservedUnused(IOVideoStream, 24); OSMetaClassDeclareReservedUnused(IOVideoStream, 25); OSMetaClassDeclareReservedUnused(IOVideoStream, 26); OSMetaClassDeclareReservedUnused(IOVideoStream, 27); OSMetaClassDeclareReservedUnused(IOVideoStream, 28); OSMetaClassDeclareReservedUnused(IOVideoStream, 29); OSMetaClassDeclareReservedUnused(IOVideoStream, 30); OSMetaClassDeclareReservedUnused(IOVideoStream, 31); protected: struct ExpansionData {}; ExpansionData *mReserved; }; #endif
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/video/IOVideoControlDictionary.h
/* File: IOVideoControlDictionary.h Contains: Copyright: © 2006-2012 by Apple Inc., all rights reserved. */ #if !defined(__IOVideoControlDictionary_h__) #define __IOVideoControlDictionary_h__ // System Includes #include <IOKit/video/IOVideoTypes.h> class OSArray; class OSDictionary; class OSString; class IOVideoControlDictionary { // Construction/Destruction public: static OSDictionary* create(UInt32 controlID, UInt32 baseClass, UInt32 derivedClass, UInt32 scope, UInt32 element, bool isReadOnly = false, UInt32 variant = 0, OSString* name = NULL); static OSDictionary* createBooleanControl(UInt32 controlID, UInt32 baseClass, UInt32 derivedClass, UInt32 scope, UInt32 element, bool value, bool isReadOnly = false, UInt32 variant = 0, OSString* name = NULL); static OSDictionary* createSelectorControl(UInt32 controlID, UInt32 baseClass, UInt32 derivedClass, UInt32 scope, UInt32 element, UInt32 value, OSArray* selectorMap, bool isReadOnly = false, UInt32 variant = 0, OSString* name = NULL); // General Attributes public: static OSDictionary* getControlByID(OSArray* controlList, UInt32 controlID); static UInt32 getControlID(const OSDictionary* dictionary); static void setControlID(OSDictionary* dictionary, UInt32 controlID); static UInt32 getBaseClass(const OSDictionary* dictionary); static void setBaseClass(OSDictionary* dictionary, UInt32 baseClass); static UInt32 getClass(const OSDictionary* dictionary); static void setClass(OSDictionary* dictionary, UInt32 derivedClass); static UInt32 getScope(const OSDictionary* dictionary); static void setScope(OSDictionary* dictionary, UInt32 scope); static UInt32 getElement(const OSDictionary* dictionary); static void setElement(OSDictionary* dictionary, UInt32 element); static bool isReadOnly(const OSDictionary* dictionary); static void setIsReadOnly(OSDictionary* dictionary, bool isReadOnly); static UInt32 getVariant(const OSDictionary* dictionary); static void setVariant(OSDictionary* dictionary, UInt32 variant); static OSString* copyName(const OSDictionary* dictionary); static void setName(OSDictionary* dictionary, const OSString* name); // Boolean Control Attributes public: static bool getBooleanControlValue(const OSDictionary* dictionary); static void setBooleanControlValue(OSDictionary* dictionary, bool value); // Selector Control Attributes public: static UInt32 getSelectorControlValue(const OSDictionary* dictionary); static void setSelectorControlValue(OSDictionary* dictionary, UInt32 value); static OSArray* copySelectorControlSelectorMap(const OSDictionary* dictionary); static void setSelectorControlSelectorMap(OSDictionary* dictionary, const OSArray* selectorMap); // Selector Control Selector Map Item Support public: static OSDictionary* createSelectorControlSelectorMapItem(UInt32 value, const OSString* name); static OSDictionary* createSelectorControlSelectorMapItem(UInt32 value, const OSString* name, UInt32 kind); }; #endif
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/video/IOVideoDeviceClientInit.h
/* File: IOVideoDeviceClientInit.h Contains: This class is used to add an IOProviderMergeProperties dictionary entry to a provider's property list, thus providing a tie between hardware and a CFBundle at hardware load time. This property usually contains the user client class name and the CFPlugInTypes UUID's but it can contain other properties. Copyright: © 2006-2012 by Apple Inc., all rights reserved. */ #ifndef __IOVIDEODEVICECLIENTINIT_H #define __IOVIDEODEVICECLIENTINIT_H #include <IOKit/IOService.h> class IOVideoDeviceUserClientInit : public IOService { OSDeclareDefaultStructors(IOVideoDeviceUserClientInit); public: virtual bool start(IOService* provider) ; virtual bool MergeDictionaryIntoProvider(IOService* provider, OSDictionary* mergeDicttionary); virtual bool MergeDictionaryIntoDictionary(OSDictionary* sourceDictionary, OSDictionary* targetDictionary); }; #endif
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/audio/IOAudioTypes.h
/* * Copyright (c) 1998-2013 Apple Computer, Inc. All rights reserved. * * @APPLE_LICENSE_HEADER_START@ * * The contents of this file constitute Original Code as defined in and * are subject to the Apple Public Source License Version 1.1 (the * "License"). You may not use this file except in compliance with the * License. Please obtain a copy of the License at * http://www.apple.com/publicsource and read it before using this file. * * This Original Code and all software distributed under the License are * distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT. Please see the * License for the specific language governing rights and limitations * under the License. * * @APPLE_LICENSE_HEADER_END@ */ #ifndef _IOKIT_IOAUDIOTYPES_H #define _IOKIT_IOAUDIOTYPES_H #include <libkern/OSTypes.h> #include <mach/message.h> /*! * @enum IOAudioEngineMemory * @abstract Used to identify the type of memory requested by a client process to be mapped into its process space * @discussion This is the parameter to the type field of IOMapMemory when called on an IOAudioEngine. This is * only intended for use by the Audio Device API library. * @constant kIOAudioSampleBuffer This requests the IOAudioEngine's sample buffer * @constant kIOAudioStatusBuffer This requests the IOAudioEngine's status buffer. It's type is IOAudioEngineStatus. * @constant kIOAudioMixBuffer This requests the IOAudioEngine's mix buffer */ typedef enum _IOAudioEngineMemory { kIOAudioStatusBuffer = 0, kIOAudioSampleBuffer = 1, kIOAudioMixBuffer = 2, kIOAudioBytesInInputBuffer = 3, kIOAudioBytesInOutputBuffer = 4 } IOAudioEngineMemory; /*! * @enum IOAudioEngineCalls * @abstract The set of constants passed to IOAudioEngineUserClient::getExternalMethodForIndex() when making calls * from the IOAudioFamily user client code. */ typedef enum _IOAudioEngineCalls { kIOAudioEngineCallRegisterClientBuffer = 0, kIOAudioEngineCallUnregisterClientBuffer = 1, kIOAudioEngineCallGetConnectionID = 2, kIOAudioEngineCallStart = 3, kIOAudioEngineCallStop = 4, kIOAudioEngineCallGetNearestStartTime = 5 } IOAudioEngineCalls; /*! @defined kIOAudioEngineNumCalls The number of elements in the IOAudioEngineCalls enum. */ #define kIOAudioEngineNumCalls 6 typedef enum _IOAudioEngineTraps { kIOAudioEngineTrapPerformClientIO = 0 } IOAudioEngineTraps; typedef enum _IOAudioEngineNotifications { kIOAudioEngineAllNotifications = 0, kIOAudioEngineStreamFormatChangeNotification = 1, kIOAudioEngineChangeNotification = 2, kIOAudioEngineStartedNotification = 3, kIOAudioEngineStoppedNotification = 4, kIOAudioEnginePausedNotification = 5, kIOAudioEngineResumedNotification = 6 } IOAudioEngineNotifications; /*! * @enum IOAudioEngineState * @abstract Represents the state of an IOAudioEngine * @constant kIOAudioEngineRunning The IOAudioEngine is currently running - it is transferring data to or * from the device. * @constant kIOAudioEngineStopped The IOAudioEngine is currently stopped - no activity is occurring. */ typedef enum _IOAudioEngineState { kIOAudioEngineStopped = 0, kIOAudioEngineRunning = 1, kIOAudioEnginePaused = 2, kIOAudioEngineResumed = 3 } IOAudioEngineState; /*! * @typedef IOAudioEngineStatus * @abstract Shared-memory structure giving audio engine status * @discussion * @field fVersion Indicates version of this structure * @field fCurrentLoopCount Number of times around the ring buffer since the audio engine started * @field fLastLoopTime Timestamp of the last time the ring buffer wrapped * @field fEraseHeadSampleFrame Location of the erase head in sample frames - erased up to but not * including the given sample frame */ typedef struct _IOAudioEngineStatus { UInt32 fVersion; volatile UInt32 fCurrentLoopCount; volatile AbsoluteTime fLastLoopTime; volatile UInt32 fEraseHeadSampleFrame; } IOAudioEngineStatus; #define kIOAudioEngineCurrentStatusStructVersion 2 typedef struct _IOAudioStreamFormat { UInt32 fNumChannels; UInt32 fSampleFormat; UInt32 fNumericRepresentation; UInt8 fBitDepth; UInt8 fBitWidth; UInt8 fAlignment; UInt8 fByteOrder; UInt8 fIsMixable; UInt32 fDriverTag; } IOAudioStreamFormat; #define kFormatExtensionInvalidVersion 0 #define kFormatExtensionCurrentVersion 1 typedef struct _IOAudioStreamFormatExtension { UInt32 fVersion; UInt32 fFlags; UInt32 fFramesPerPacket; UInt32 fBytesPerPacket; } IOAudioStreamFormatExtension; typedef struct _IOAudioBufferDataDescriptor { UInt32 fActualDataByteSize; UInt32 fActualNumSampleFrames; UInt32 fTotalDataByteSize; UInt32 fNominalDataByteSize; UInt8 fData[1]; } IOAudioBufferDataDescriptor; #define kStreamDataDescriptorInvalidVersion 0 #define kStreamDataDescriptorCurrentVersion 1 typedef struct _IOAudioStreamDataDescriptor { UInt32 fVersion; UInt32 fNumberOfStreams; UInt32 fStreamLength[1]; // Array with fNumberOfStreams number of entries } IOAudioStreamDataDescriptor; typedef struct _IOAudioSampleIntervalDescriptor { UInt32 sampleIntervalHi; UInt32 sampleIntervalLo; } IOAudioSampleIntervalDescriptor; /*! @struct SMPTETime @abstract A structure for holding a SMPTE time. @field fSubframes The number of subframes in the full message. @field fSubframeDivisor The number of subframes per frame (typically 80). @field fCounter The total number of messages received. @field fType The kind of SMPTE time using the SMPTE time type constants. @field fFlags A set of flags that indicate the SMPTE state. @field fHours The number of hourse in the full message. @field fMinutes The number of minutes in the full message. @field fSeconds The number of seconds in the full message. @field fFrames The number of frames in the full message. */ typedef struct _IOAudioSMPTETime { SInt16 fSubframes; SInt16 fSubframeDivisor; UInt32 fCounter; UInt32 fType; UInt32 fFlags; SInt16 fHours; SInt16 fMinutes; SInt16 fSeconds; SInt16 fFrames; } IOAudioSMPTETime; // constants describing SMPTE types (taken from the MTC spec), <rdar://11955717> enum { kIOAudioSMPTETimeType24 = 0, kIOAudioSMPTETimeType25 = 1, kIOAudioSMPTETimeType30Drop = 2, kIOAudioSMPTETimeType30 = 3, kIOAudioSMPTETimeType2997 = 4, kIOAudioSMPTETimeType2997Drop = 5, kIOAudioSMPTETimeType60 = 6, kIOAudioSMPTETimeType5994 = 7, kIOAudioSMPTETimeType60Drop = 8, kIOAudioSMPTETimeType5994Drop = 9, kIOAudioSMPTETimeType50 = 10, kIOAudioSMPTETimeType2398 = 11 }; // flags describing a SMPTE time stamp enum { kIOAudioSMPTETimeValid = (1L << 0), // the full time is valid kIOAudioSMPTETimeRunning = (1L << 1) // time is running }; // A struct for encapsulating the parts of a time stamp. The flags // say which fields are valid. typedef struct _IOAudioTimeStamp { UInt64 fSampleTime; // the absolute sample time, was a Float64 UInt64 fHostTime; // the host's root timebase's time UInt64 fRateScalar; // the system rate scalar, was a Float64 UInt64 fWordClockTime; // the word clock time IOAudioSMPTETime fSMPTETime; // the SMPTE time UInt32 fFlags; // the flags indicate which fields are valid UInt32 fReserved; // reserved, pads the structure out to force 8 byte alignment } IOAudioTimeStamp; // flags for the AudioTimeStamp sturcture enum { kIOAudioTimeStampSampleTimeValid = (1L << 0), kIOAudioTimeStampHostTimeValid = (1L << 1), kIOAudioTimeStampRateScalarValid = (1L << 2), kIOAudioTimeStampWordClockTimeValid = (1L << 3), kIOAudioTimeStampSMPTETimeValid = (1L << 4) }; // Some commonly used combinations of timestamp flags enum { kIOAudioTimeStampSampleHostTimeValid = (kIOAudioTimeStampSampleTimeValid | kIOAudioTimeStampHostTimeValid) }; /*! * @enum IOAudioStreamDirection * @abstract Represents the direction of an IOAudioStream * @constant kIOAudioStreamDirectionOutput Output buffer * @constant kIOAudioStreamDirectionInput Input buffer */ typedef enum _IOAudioStreamDirection { kIOAudioStreamDirectionOutput = 0, kIOAudioStreamDirectionInput = 1 } IOAudioStreamDirection; enum { kIOAudioDeviceCanBeDefaultNothing = 0, kIOAudioDeviceCanBeDefaultInput = (1L << 0), kIOAudioDeviceCanBeDefaultOutput = (1L << 1), kIOAudioDeviceCanBeSystemOutput = (1L << 2) }; /*! * @defined kIOAudioEngineDefaultMixBufferSampleSize */ #define kIOAudioEngineDefaultMixBufferSampleSize sizeof(float) /* The following are for use only by the IOKit.framework audio family code */ /*! * @enum IOAudioControlCalls * @abstract The set of constants passed to IOAudioControlUserClient::getExternalMethodForIndex() when making calls * from the IOAudioFamily user client code. * @constant kIOAudioControlCallSetValue Used to set the value of an IOAudioControl. * @constant kIOAudioControlCallGetValue Used to get the value of an IOAudioControl. */ typedef enum _IOAudioControlCalls { kIOAudioControlCallSetValue = 0, kIOAudioControlCallGetValue = 1 } IOAudioControlCalls; /*! @defined kIOAudioControlNumCalls The number of elements in the IOAudioControlCalls enum. */ #define kIOAudioControlNumCalls 2 /*! * @enum IOAudioControlNotifications * @abstract The set of constants passed in the type field of IOAudioControlUserClient::registerNotificaitonPort(). * @constant kIOAudioControlValueChangeNotification Used to request value change notifications. * @constant kIOAudioControlRangeChangeNotification Used to request range change notifications. */ typedef enum _IOAudioControlNotifications { kIOAudioControlValueChangeNotification = 0, kIOAudioControlRangeChangeNotification = 1 } IOAudioControlNotifications; /*! * @struct IOAudioNotificationMessage * @abstract Used in the mach message for IOAudio notifications. * @field messageHeader Standard mach message header * @field ref The param passed to registerNotificationPort() in refCon. */ typedef struct _IOAudioNotificationMessage { mach_msg_header_t messageHeader; UInt32 type; UInt32 ref; void * sender; } IOAudioNotificationMessage; typedef struct _IOAudioSampleRate { UInt32 whole; UInt32 fraction; } IOAudioSampleRate; #define kNoIdleAudioPowerDown 0xffffffffffffffffULL enum { kIOAudioPortTypeOutput = 'outp', kIOAudioPortTypeInput = 'inpt', kIOAudioPortTypeMixer = 'mixr', kIOAudioPortTypePassThru = 'pass', kIOAudioPortTypeProcessing = 'proc' }; enum { kIOAudioOutputPortSubTypeInternalSpeaker = 'ispk', kIOAudioOutputPortSubTypeExternalSpeaker = 'espk', kIOAudioOutputPortSubTypeHeadphones = 'hdpn', kIOAudioOutputPortSubTypeLine = 'line', kIOAudioOutputPortSubTypeSPDIF = 'spdf', kIOAudioInputPortSubTypeInternalMicrophone = 'imic', kIOAudioInputPortSubTypeExternalMicrophone = 'emic', kIOAudioInputPortSubTypeCD = 'cd ', kIOAudioInputPortSubTypeLine = 'line', kIOAudioInputPortSubTypeSPDIF = 'spdf' }; enum { kIOAudioControlTypeLevel = 'levl', kIOAudioControlTypeToggle = 'togl', kIOAudioControlTypeJack = 'jack', kIOAudioControlTypeSelector = 'slct' }; // <rdar://8325563> Added kIOAudioToggleControlSubTypePhantomPower, kIOAudioToggleControlSubTypePhaseInvert & // kIOAudioSelectorControlSubTypeChannelHighPassFilter enum { kIOAudioLevelControlSubTypeVolume = 'vlme', kIOAudioLevelControlSubTypeLFEVolume = 'subv', kIOAudioLevelControlSubTypePRAMVolume = 'pram', kIOAudioToggleControlSubTypeMute = 'mute', kIOAudioToggleControlSubTypeSolo = 'solo', kIOAudioToggleControlSubTypeLFEMute = 'subm', kIOAudioToggleControlSubTypeiSubAttach = 'atch', kIOAudioToggleControlSubTypePhantomPower = 'phan', kIOAudioToggleControlSubTypePhaseInvert = 'phsi', kIOAudioSelectorControlSubTypeOutput = 'outp', kIOAudioSelectorControlSubTypeInput = 'inpt', kIOAudioSelectorControlSubTypeClockSource = 'clck', kIOAudioSelectorControlSubTypeDestination = 'dest', kIOAudioSelectorControlSubTypeChannelNominalLineLevel = 'nlev', kIOAudioSelectorControlSubTypeChannelLevelPlus4dBu = '4dbu', kIOAudioSelectorControlSubTypeChannelLevelMinus10dBV = '10db', kIOAudioSelectorControlSubTypeChannelLevelMinus20dBV = '20db', kIOAudioSelectorControlSubTypeChannelLevelMicLevel = 'micl', kIOAudioSelectorControlSubTypeChannelLevelInstrumentLevel = 'istl', kIOAudioSelectorControlSubTypeChannelHighPassFilter = 'hipf' }; enum { kIOAudioControlUsageOutput = 'outp', kIOAudioControlUsageInput = 'inpt', kIOAudioControlUsagePassThru = 'pass', kIOAudioControlUsageCoreAudioProperty = 'prop' }; enum { kIOAudioControlChannelNumberInactive = -1, kIOAudioControlChannelIDAll = 0, kIOAudioControlChannelIDDefaultLeft = 1, kIOAudioControlChannelIDDefaultRight = 2, kIOAudioControlChannelIDDefaultCenter = 3, kIOAudioControlChannelIDDefaultLeftRear = 4, kIOAudioControlChannelIDDefaultRightRear = 5, kIOAudioControlChannelIDDefaultSub = 6, kIOAudioControlChannelIDDefaultFrontLeftCenter = 7, kIOAudioControlChannelIDDefaultFrontRightCenter = 8, kIOAudioControlChannelIDDefaultRearCenter = 9, kIOAudioControlChannelIDDefaultSurroundLeft = 10, kIOAudioControlChannelIDDefaultSurroundRight = 11 }; enum { kIOAudioSelectorControlSelectionValueNone = 'none', // Output-specific selection IDs kIOAudioSelectorControlSelectionValueInternalSpeaker = 'ispk', kIOAudioSelectorControlSelectionValueExternalSpeaker = 'espk', kIOAudioSelectorControlSelectionValueHeadphones = 'hdpn', // Input-specific selection IDs kIOAudioSelectorControlSelectionValueInternalMicrophone = 'imic', kIOAudioSelectorControlSelectionValueExternalMicrophone = 'emic', kIOAudioSelectorControlSelectionValueCD = 'cd ', // Common selection IDs kIOAudioSelectorControlSelectionValueLine = 'line', kIOAudioSelectorControlSelectionValueSPDIF = 'spdf' }; enum { kIOAudioStreamSampleFormatLinearPCM = 'lpcm', kIOAudioStreamSampleFormatIEEEFloat = 'ieee', kIOAudioStreamSampleFormatALaw = 'alaw', kIOAudioStreamSampleFormatMuLaw = 'ulaw', kIOAudioStreamSampleFormatMPEG = 'mpeg', kIOAudioStreamSampleFormatAC3 = 'ac-3', kIOAudioStreamSampleFormat1937AC3 = 'cac3', kIOAudioStreamSampleFormat1937MPEG1 = 'mpg1', kIOAudioStreamSampleFormat1937MPEG2 = 'mpg2', kIOAudioStreamSampleFormatTimeCode = 'time' // a stream of IOAudioTimeStamp structures that capture any incoming time code information }; enum { kIOAudioStreamNumericRepresentationSignedInt = 'sint', kIOAudioStreamNumericRepresentationUnsignedInt = 'uint', kIOAudioStreamNumericRepresentationIEEE754Float = 'flot' }; enum { kIOAudioClockSelectorTypeInternal = 'int ', kIOAudioClockSelectorTypeExternal = 'ext ', kIOAudioClockSelectorTypeAESEBU = 'asbu', kIOAudioClockSelectorTypeTOSLink = 'tosl', kIOAudioClockSelectorTypeSPDIF = 'spdf', kIOAudioClockSelectorTypeADATOptical = 'adto', kIOAudioClockSelectorTypeADAT9Pin = 'adt9', kIOAudioClockSelectorTypeSMPTE = 'smpt', kIOAudioClockSelectorTypeVideo = 'vdeo', kIOAudioClockSelectorTypeControl = 'cnrl', kIOAudioClockSelectorTypeOther = 'othr', }; enum { kIOAudioStreamAlignmentLowByte = 0, kIOAudioStreamAlignmentHighByte = 1 }; enum { kIOAudioStreamByteOrderBigEndian = 0, kIOAudioStreamByteOrderLittleEndian = 1 }; enum { kIOAudioLevelControlNegativeInfinity = 0xffffffff }; enum { #ifndef __OPEN_SOURCE__ kIOAudioBuiltInSystemClockDomain = 0x737973, #endif kIOAudioNewClockDomain = 0xffffffff }; // Device connection types #ifndef __OPEN_SOURCE__ // <rdar://7130813> Added kIOAudioDeviceTransportTypeDisplayPort #endif enum { kIOAudioDeviceTransportTypeBuiltIn = 'bltn', kIOAudioDeviceTransportTypePCI = 'pci ', kIOAudioDeviceTransportTypeUSB = 'usb ', kIOAudioDeviceTransportTypeFireWire = '1394', kIOAudioDeviceTransportTypeNetwork = 'ntwk', kIOAudioDeviceTransportTypeWireless = 'wrls', kIOAudioDeviceTransportTypeOther = 'othr', kIOAudioDeviceTransportTypeBluetooth = 'blue', kIOAudioDeviceTransportTypeVirtual = 'virt', kIOAudioDeviceTransportTypeDisplayPort = 'dprt', kIOAudioDeviceTransportTypeHdmi = 'hdmi', kIOAudioDeviceTransportTypeAVB = 'eavb', //<rdar://10874672> kIOAudioDeviceTransportTypeThunderbolt = 'thun' //<rdar://10874672> }; // types that go nowhere enum { OUTPUT_NULL = 0x0100, INPUT_NULL = 0x0101 }; // Input terminal types enum { INPUT_UNDEFINED = 0x0200, INPUT_MICROPHONE = 0x0201, INPUT_DESKTOP_MICROPHONE = 0x0202, INPUT_PERSONAL_MICROPHONE = 0x0203, INPUT_OMNIDIRECTIONAL_MICROPHONE = 0x0204, INPUT_MICROPHONE_ARRAY = 0x0205, INPUT_PROCESSING_MICROPHONE_ARRAY = 0x0206, INPUT_MODEM_AUDIO = 0x207 }; // Output terminal types enum { OUTPUT_UNDEFINED = 0x0300, OUTPUT_SPEAKER = 0x0301, OUTPUT_HEADPHONES = 0x0302, OUTPUT_HEAD_MOUNTED_DISPLAY_AUDIO = 0x0303, OUTPUT_DESKTOP_SPEAKER = 0x0304, OUTPUT_ROOM_SPEAKER = 0x0305, OUTPUT_COMMUNICATION_SPEAKER = 0x0306, OUTPUT_LOW_FREQUENCY_EFFECTS_SPEAKER = 0x0307 }; // Bi-directional terminal types enum { BIDIRECTIONAL_UNDEFINED = 0x0400, BIDIRECTIONAL_HANDSET = 0x0401, BIDIRECTIONAL_HEADSET = 0x0402, BIDIRECTIONAL_SPEAKERPHONE_NO_ECHO_REDX = 0x0403, BIDIRECTIONAL_ECHO_SUPPRESSING_SPEAKERPHONE = 0x0404, BIDIRECTIONAL_ECHO_CANCELING_SPEAKERPHONE = 0x0405 }; // Telephony terminal types enum { TELEPHONY_UNDEFINED = 0x0500, TELEPHONY_PHONE_LINE = 0x0501, TELEPHONY_TELEPHONE = 0x0502, TELEPHONY_DOWN_LINE_PHONE = 0x0503 }; // External terminal types enum { EXTERNAL_UNDEFINED = 0x0600, EXTERNAL_ANALOG_CONNECTOR = 0x0601, EXTERNAL_DIGITAL_AUDIO_INTERFACE = 0x0602, EXTERNAL_LINE_CONNECTOR = 0x0603, EXTERNAL_LEGACY_AUDIO_CONNECTOR = 0x0604, EXTERNAL_SPDIF_INTERFACE = 0x0605, EXTERNAL_1394_DA_STREAM = 0x0606, EXTERNAL_1394_DV_STREAM_SOUNDTRACK = 0x0607, EXTERNAL_ADAT = 0x0608, EXTERNAL_TDIF = 0x0609, EXTERNAL_MADI = 0x060A }; // Embedded terminal types enum { EMBEDDED_UNDEFINED = 0x0700, EMBEDDED_LEVEL_CALIBRATION_NOISE_SOURCE = 0x0701, EMBEDDED_EQUALIZATION_NOISE = 0x0702, EMBEDDED_CD_PLAYER = 0x0703, EMBEDDED_DAT = 0x0704, EMBEDDED_DCC = 0x0705, EMBEDDED_MINIDISK = 0x0706, EMBEDDED_ANALOG_TAPE = 0x0707, EMBEDDED_PHONOGRAPH = 0x0708, EMBEDDED_VCR_AUDIO = 0x0709, EMBEDDED_VIDEO_DISC_AUDIO = 0x070A, EMBEDDED_DVD_AUDIO = 0x070B, EMBEDDED_TV_TUNER_AUDIO = 0x070C, EMBEDDED_SATELLITE_RECEIVER_AUDIO = 0x070D, EMBEDDED_CABLE_TUNER_AUDIO = 0x070E, EMBEDDED_DSS_AUDIO = 0x070F, EMBEDDED_RADIO_RECEIVER = 0x0710, EMBEDDED_RADIO_TRANSMITTER = 0x0711, EMBEDDED_MULTITRACK_RECORDER = 0x0712, EMBEDDED_SYNTHESIZER = 0x0713 }; // Processing terminal types enum { PROCESSOR_UNDEFINED = 0x0800, PROCESSOR_GENERAL = 0x0801 }; // Channel spatial position types #ifndef __OPEN_SOURCE__ // <rdar://6868206> NOTE: the following are derived from CoreAudioTypes.h #endif #define kIOAudioChannelLabel_Discrete_field_ba 16 enum { kIOAudioChannelLabel_Unknown = 0xFFFFFFFF, // unknown or unspecified other use kIOAudioChannelLabel_Unused = 0, // channel is present, but has no intended use or destination kIOAudioChannelLabel_UseCoordinates = 100, // channel is described by the mCoordinates fields. kIOAudioChannelLabel_Left = 1, kIOAudioChannelLabel_Right = 2, kIOAudioChannelLabel_Center = 3, kIOAudioChannelLabel_LFEScreen = 4, kIOAudioChannelLabel_LeftSurround = 5, // WAVE: "Back Left" kIOAudioChannelLabel_RightSurround = 6, // WAVE: "Back Right" kIOAudioChannelLabel_LeftCenter = 7, kIOAudioChannelLabel_RightCenter = 8, kIOAudioChannelLabel_CenterSurround = 9, // WAVE: "Back Center" or plain "Rear Surround" kIOAudioChannelLabel_LeftSurroundDirect = 10, // WAVE: "Side Left" kIOAudioChannelLabel_RightSurroundDirect = 11, // WAVE: "Side Right" kIOAudioChannelLabel_TopCenterSurround = 12, kIOAudioChannelLabel_VerticalHeightLeft = 13, // WAVE: "Top Front Left" kIOAudioChannelLabel_VerticalHeightCenter = 14, // WAVE: "Top Front Center" kIOAudioChannelLabel_VerticalHeightRight = 15, // WAVE: "Top Front Right" kIOAudioChannelLabel_TopBackLeft = 16, kIOAudioChannelLabel_TopBackCenter = 17, kIOAudioChannelLabel_TopBackRight = 18, kIOAudioChannelLabel_RearSurroundLeft = 33, kIOAudioChannelLabel_RearSurroundRight = 34, kIOAudioChannelLabel_LeftWide = 35, kIOAudioChannelLabel_RightWide = 36, kIOAudioChannelLabel_LFE2 = 37, kIOAudioChannelLabel_LeftTotal = 38, // matrix encoded 4 channels kIOAudioChannelLabel_RightTotal = 39, // matrix encoded 4 channels kIOAudioChannelLabel_HearingImpaired = 40, kIOAudioChannelLabel_Narration = 41, kIOAudioChannelLabel_Mono = 42, kIOAudioChannelLabel_DialogCentricMix = 43, kIOAudioChannelLabel_CenterSurroundDirect = 44, // back center, non diffuse kIOAudioChannelLabel_Haptic = 45, kIOAudioChannelLabel_LeftTopFront = kIOAudioChannelLabel_VerticalHeightLeft, kIOAudioChannelLabel_CenterTopFront = kIOAudioChannelLabel_VerticalHeightCenter, kIOAudioChannelLabel_RightTopFront = kIOAudioChannelLabel_VerticalHeightRight, kIOAudioChannelLabel_LeftTopMiddle = 49, kIOAudioChannelLabel_CenterTopMiddle = kIOAudioChannelLabel_TopCenterSurround, kIOAudioChannelLabel_RightTopMiddle = 51, kIOAudioChannelLabel_LeftTopRear = 52, kIOAudioChannelLabel_CenterTopRear = 53, kIOAudioChannelLabel_RightTopRear = 54, // first order ambisonic channels kIOAudioChannelLabel_Ambisonic_W = 200, kIOAudioChannelLabel_Ambisonic_X = 201, kIOAudioChannelLabel_Ambisonic_Y = 202, kIOAudioChannelLabel_Ambisonic_Z = 203, // Mid/Side Recording kIOAudioChannelLabel_MS_Mid = 204, kIOAudioChannelLabel_MS_Side = 205, // X-Y Recording kIOAudioChannelLabel_XY_X = 206, kIOAudioChannelLabel_XY_Y = 207, // other kIOAudioChannelLabel_HeadphonesLeft = 301, kIOAudioChannelLabel_HeadphonesRight = 302, kIOAudioChannelLabel_ClickTrack = 304, kIOAudioChannelLabel_ForeignLanguage = 305, // generic discrete channel kIOAudioChannelLabel_Discrete = 400, // numbered discrete channel kIOAudioChannelLabel_Discrete_0 = ( 1 << kIOAudioChannelLabel_Discrete_field_ba ) | 0, kIOAudioChannelLabel_Discrete_1 = ( 1 << kIOAudioChannelLabel_Discrete_field_ba ) | 1, kIOAudioChannelLabel_Discrete_2 = ( 1 << kIOAudioChannelLabel_Discrete_field_ba ) | 2, kIOAudioChannelLabel_Discrete_3 = ( 1 << kIOAudioChannelLabel_Discrete_field_ba ) | 3, kIOAudioChannelLabel_Discrete_4 = ( 1 << kIOAudioChannelLabel_Discrete_field_ba ) | 4, kIOAudioChannelLabel_Discrete_5 = ( 1 << kIOAudioChannelLabel_Discrete_field_ba ) | 5, kIOAudioChannelLabel_Discrete_6 = ( 1 << kIOAudioChannelLabel_Discrete_field_ba ) | 6, kIOAudioChannelLabel_Discrete_7 = ( 1 << kIOAudioChannelLabel_Discrete_field_ba ) | 7, kIOAudioChannelLabel_Discrete_8 = ( 1 << kIOAudioChannelLabel_Discrete_field_ba ) | 8, kIOAudioChannelLabel_Discrete_9 = ( 1 << kIOAudioChannelLabel_Discrete_field_ba ) | 9, kIOAudioChannelLabel_Discrete_10 = ( 1 << kIOAudioChannelLabel_Discrete_field_ba ) | 10, kIOAudioChannelLabel_Discrete_11 = ( 1 << kIOAudioChannelLabel_Discrete_field_ba ) | 11, kIOAudioChannelLabel_Discrete_12 = ( 1 << kIOAudioChannelLabel_Discrete_field_ba ) | 12, kIOAudioChannelLabel_Discrete_13 = ( 1 << kIOAudioChannelLabel_Discrete_field_ba ) | 13, kIOAudioChannelLabel_Discrete_14 = ( 1 << kIOAudioChannelLabel_Discrete_field_ba ) | 14, kIOAudioChannelLabel_Discrete_15 = ( 1 << kIOAudioChannelLabel_Discrete_field_ba ) | 15, kIOAudioChannelLabel_Discrete_65535 = ( 1 << kIOAudioChannelLabel_Discrete_field_ba ) | 65535 }; #endif /* _IOKIT_IOAUDIOTYPES_H */
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/audio/IOAudioDefines.h
/* * Copyright (c) 1998-2013 Apple Computer, Inc. All rights reserved. * * @APPLE_LICENSE_HEADER_START@ * * The contents of this file constitute Original Code as defined in and * are subject to the Apple Public Source License Version 1.1 (the * "License"). You may not use this file except in compliance with the * License. Please obtain a copy of the License at * http://www.apple.com/publicsource and read it before using this file. * * This Original Code and all software distributed under the License are * distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT. Please see the * License for the specific language governing rights and limitations * under the License. * * @APPLE_LICENSE_HEADER_END@ */ #ifndef _IOAUDIODEFINES_H #define _IOAUDIODEFINES_H #define kIOAudioDeviceClassName "IOAudioDevice" #define kIOAudioEngineClassName "IOAudioEngine" #define kIOAudioStreamClassName "IOAudioStream" #define kIOAudioPortClassName "IOAudioPort" #define kIOAudioControlClassName "IOAudioControl" /*! * @defined kIOAudioSampleRateKey * @abstract The key in the IORegistry for the IOAudioEngine sample rate attribute * @discussion This value is represented as an integer in samples per second. */ #define kIOAudioSampleRateKey "IOAudioSampleRate" #define kIOAudioSampleRateWholeNumberKey "IOAudioSampleRateWholeNumber" #define kIOAudioSampleRateFractionKey "IOAudioSampleRateFraction" /****** * * IOAudioDevice defines * *****/ /*! * @defined kIOAudioDeviceNameKey * @abstract The key in the IORegistry for the IOAudioDevice name attribute. */ #define kIOAudioDeviceNameKey "IOAudioDeviceName" #define kIOAudioDeviceShortNameKey "IOAudioDeviceShortName" /*! * @defined kIOAudioDeviceManufacturerNameKey * @abstract The key in the IORegistry for the IOAudioDevice manufacturer name attribute. */ #define kIOAudioDeviceManufacturerNameKey "IOAudioDeviceManufacturerName" #define kIOAudioDeviceLocalizedBundleKey "IOAudioDeviceLocalizedBundle" #define kIOAudioDeviceTransportTypeKey "IOAudioDeviceTransportType" #define kIOAudioDeviceConfigurationAppKey "IOAudioDeviceConfigurationApplication" #define kIOAudioDeviceCanBeDefaults "IOAudioDeviceCanBeDefaults" #define kIOAudioDeviceModelIDKey "IOAudioDeviceModelID" /*! * @defined kIOAudioDeviceIconName * @abstract The key in the IORegistry for the IOAudioDevice icon name attribute. */ #define kIOAudioDeviceIconNameKey "IOAudioDeviceIconName" #define kIOAudioDeviceIconTypeKey "IOAudioDeviceIconType" #define kIOAudioDeviceIconSubDirKey "IOAudioDeviceIconSubDir" /***** * * IOAudioEngine defines * *****/ /*! * @defined kIOAudioEngineStateKey * @abstract The key in the IORegistry for the IOAudioEngine state atrribute * @discussion The value for this key may be one of: "Running", "Stopped" or "Paused". Currently the "Paused" * state is unimplemented. */ #define kIOAudioEngineStateKey "IOAudioEngineState" /*! * @defined kIOAudioEngineOutputSampleLatencyKey * @abstract The key in the IORegistry for the IOAudioEngine output sample latency key * @discussion */ #define kIOAudioEngineOutputSampleLatencyKey "IOAudioEngineOutputSampleLatency" /*! * @defined kIOAudioStreamSampleLatencyKey * @abstract The key in the IORegistry for the IOAudioStream output sample latency key * @discussion Tells the HAL how much latency is on a particular stream. If two streams * on the same engine have different latencies (e.g. one is analog, one is digital), then * set this property on both streams to inform the HAL of the latency differences. Alternately, * you can set the engine latency, and just include the latency additional to that for the particular * stream. The HAL will add the engine and stream latency numbers together to get the total latency. */ #define kIOAudioStreamSampleLatencyKey "IOAudioStreamSampleLatency" #define kIOAudioEngineInputSampleLatencyKey "IOAudioEngineInputSampleLatency" #define kIOAudioEngineSampleOffsetKey "IOAudioEngineSampleOffset" #define kIOAudioEngineInputSampleOffsetKey "IOAudioEngineInputSampleOffset" #define kIOAudioEngineNumSampleFramesPerBufferKey "IOAudioEngineNumSampleFramesPerBuffer" #define kIOAudioEngineCoreAudioPlugInKey "IOAudioEngineCoreAudioPlugIn" #define kIOAudioEngineNumActiveUserClientsKey "IOAudioEngineNumActiveUserClients" #define kIOAudioEngineUserClientActiveKey "IOAudioEngineUserClientActive" #define kIOAudioEngineGlobalUniqueIDKey "IOAudioEngineGlobalUniqueID" #define kIOAudioEngineDescriptionKey "IOAudioEngineDescription" #define kIOAudioEngineClockIsStableKey "IOAudioEngineClockIsStable" #define kIOAudioEngineClockDomainKey "IOAudioEngineClockDomain" #define kIOAudioEngineIsHiddenKey "IOAudioEngineIsHidden" #define kIOAudioEngineOutputAutoRouteKey "NoAutoRoute" /*! * @defined kIOAudioEngineUseHiResSampleInterval * @abstract The key in the IORegistry to tell the HAL to use "Hi Resolution" sampleInterval values in performClientIO * @discussion The HAL has always passed two 32 bit values to the performClientIO trap. sampleIntervalHi is the upper * 32 bits and sampleIntervalLo the lower 32 bits of an AbsoluteTime representing the time between two consecutive audio * samples on this Engine's running clock. This time is always very small, meaning that the upper 32 bits are always 0 * but the value is also rounded, meaning that there could be error in the amount of time, especially at higher sample rates * where the value is pretty small (e.g. at a nominal rate of 768kHz, sampleInterval is 1302.0833 nanoseconds which will come * into performClientIO as (0, 1302) thus losing some precision * when kIOAudioEngineUseHiResSampleInterval is set, the HAL will send the sampleInterval as a 32.32 Fixed Point number. * sampleIntervalHi will contain the integer part of the sampleInterval (1302) abd sampleIntervalLo will contain the fractional * part encoded as a standard binary fixed point decimal */ #define kIOAudioEngineUseHiResSampleIntervalKey "IOAudioEngineUseHiResSampleInterval" /*! * @defined kIOAudioEngineFullChannelNamesKey * @abstract The key in the IORegistry for the IOAudioEngine's dictionary of fully constructed names for each channel keyed by the device channel * @discussion */ #define kIOAudioEngineFullChannelNamesKey "IOAudioEngineChannelNames" /*! * @defined kIOAudioEngineFullChannelCategoryNamesKey * @abstract The key in the IORegistry for the IOAudioEngine's dictionary of category names for each channel keyed by the device channel * @discussion */ #define kIOAudioEngineFullChannelCategoryNamesKey "IOAudioEngineChannelCategoryNames" /*! * @defined kIOAudioEngineFullChannelNamesKey * @abstract The key in the IORegistry for the IOAudioEngine's dictionary of number names for each channel keyed by the device channel * @discussion */ #define kIOAudioEngineFullChannelNumberNamesKey "IOAudioEngineChannelNumberNames" #define kIOAudioEngineFullChannelNameKeyInputFormat "InputChannel%u" #define kIOAudioEngineFullChannelNameKeyOutputFormat "OutputChannel%u" #define kIOAudioEngineFlavorKey "IOAudioEngineFlavor" #define kIOAudioEngineAlwaysLoadCoreAudioPlugInKey "IOAudioEngineAlwaysLoadCoreAudioPlugIn" /*! * @defined kIOAudioEngineInputChannelLayoutKey * @abstract The key in the IORegistry for the IOAudioEngine's dictionary describes an array of OSNumber data that describe the spatial position of each channel. See IOAudioTypes.h. * @discussion */ #ifndef __OPEN_SOURCE__ // <rdar://6868206> #endif #define kIOAudioEngineInputChannelLayoutKey "IOAudioEngineInputChannelLayout" /*! * @defined kIOAudioEngineOutputChannelLayoutKey * @abstract The key in the IORegistry for the IOAudioEngine's dictionary describes an array of OSNumber data that describe the spatial position of each channel. See IOAudioTypes.h. * @discussion */ #ifndef __OPEN_SOURCE__ // <rdar://6868206> #endif #define kIOAudioEngineOutputChannelLayoutKey "IOAudioEngineOutputChannelLayout" /*! * @defined kIOAudioEngineDisableClockBoundsCheck * @abstract The key in the IORegistry for the IOAudioEngine's dictionary implemented as an OSBoolean that is used to disable the bounds checking on timestamps being passed to the HAL. * @discussion By using this key and setting the value to true the driver is asserting that it guarantees that all zero timestamps passed to the HAL increment appropriately at the correct period. This key is used to disable the HAL test that the timestamp is within 1ms of the current time, so that a driver may pass a timestamp that is more than 1ms in the future. This may be useful when a timestamp is based on a large DMA read/write which encompasses the wrap point but occurs many samples before the end of that point. */ #define kIOAudioEngineDisableClockBoundsCheck "IOAudioEngineDisableClockBoundsCheck" /***** * * IOAudioStream defines * *****/ #define kIOAudioStreamIDKey "IOAudioStreamID" #define kIOAudioStreamDescriptionKey "IOAudioStreamDescription" #define kIOAudioStreamNumClientsKey "IOAudioStreamNumClients" /*! * @defined kIOAudioStreamDirectionKey * @abstract The key in the IORegistry for the IOAudioStream direction attribute. * @discussion The value for this key may be either "Output" or "Input". */ #define kIOAudioStreamDirectionKey "IOAudioStreamDirection" #define kIOAudioStreamStartingChannelIDKey "IOAudioStreamStartingChannelID" #define kIOAudioStreamStartingChannelNumberKey "IOAudioStreamStartingChannelNumber" #define kIOAudioStreamAvailableKey "IOAudioStreamAvailable" #define kIOAudioStreamFormatKey "IOAudioStreamFormat" #define kIOAudioStreamAvailableFormatsKey "IOAudioStreamAvailableFormats" #define kIOAudioStreamNumChannelsKey "IOAudioStreamNumChannels" #define kIOAudioStreamSampleFormatKey "IOAudioStreamSampleFormat" #define kIOAudioStreamNumericRepresentationKey "IOAudioStreamNumericRepresentation" #define kIOAudioStreamFormatFlagsKey "IOAudioStreamFormatFlags" #define kIOAudioStreamFramesPerPacketKey "IOAudioStreamFramesPerPacket" #define kIOAudioStreamBytesPerPacketKey "IOAudioStreamBytesPerPacket" #define kIOAudioStreamBitDepthKey "IOAudioStreamBitDepth" #define kIOAudioStreamBitWidthKey "IOAudioStreamBitWidth" #define kIOAudioStreamAlignmentKey "IOAudioStreamAlignment" #define kIOAudioStreamByteOrderKey "IOAudioStreamByteOrder" #define kIOAudioStreamIsMixableKey "IOAudioStreamIsMixable" #define kIOAudioStreamMinimumSampleRateKey "IOAudioStreamMinimumSampleRate" #define kIOAudioStreamMaximumSampleRateKey "IOAudioStreamMaximumSampleRate" #define kIOAudioStreamDriverTagKey "IOAudioStreamDriverTag" #define kIOAudioStreamTerminalTypeKey "IOAudioStreamTerminalType" /***** * * IOAudioPort defines * *****/ /*! * @defined kIOAudioPortTypeKey * @abstract The key in the IORegistry for the IOAudioPort type attribute. * @discussion This is a driver-defined text attribute that may contain any type. * Common types are defined as: "Speaker", "Headphones", "Microphone", "CD", "Line", "Digital", "Mixer", "PassThru". */ #define kIOAudioPortTypeKey "IOAudioPortType" /*! * @defined kIOAudioPortSubTypeKey * @abstract The key in the IORegistry for the IOAudioPort subtype attribute. * @discussion The IOAudioPort subtype is a driver-defined text attribute designed to complement the type * attribute. */ #define kIOAudioPortSubTypeKey "IOAudioPortSubType" /*! * @defined kIOAudioPortNameKey * @abstract The key in the IORegistry for the IOAudioPort name attribute. */ #define kIOAudioPortNameKey "IOAudioPortName" /***** * * IOAudioControl defines * *****/ /*! * @defined kIOAudioControlTypeKey * @abstract The key in the IORegistry for the IOAudioCntrol type attribute. * @discussion The value of this text attribute may be defined by the driver, however system-defined * types recognized by the upper-level software are "Level", "Mute", "Selector". */ #define kIOAudioControlTypeKey "IOAudioControlType" #define kIOAudioControlSubTypeKey "IOAudioControlSubType" #define kIOAudioControlUsageKey "IOAudioControlUsage" #define kIOAudioControlIDKey "IOAudioControlID" /*! * @defined kIOAudioControlChannelIDKey * @abstract The key in the IORegistry for the IOAudioControl channel ID attribute * @discussion The value for this key is an integer which may be driver defined. Default values for * common channel types are provided in the following defines. */ #define kIOAudioControlChannelIDKey "IOAudioControlChannelID" #define kIOAudioControlChannelNumberKey "IOAudioControlChannelNumber" #define kIOAudioControlCoreAudioPropertyIDKey "IOAudioControlCoreAudioPropertyID" /*! * @defined kIOAudioControlChannelNameKey * @abstract The key in the IORegistry for the IOAudioControl name attribute. * @discussion This name should be a human-readable name for the channel(s) represented by the port. * *** NOTE *** We really need to make all of the human-readable attributes that have potential to * be used in a GUI localizable. There will need to be localized strings in the kext bundle matching * the text. */ #define kIOAudioControlChannelNameKey "IOAudioControlChannelName" /*! * @defined kIOAudioControlChannelNameAll * @abstract The value for the kIOAudioControlChannelNameKey in the IORegistry representing * the channel name for all channels. */ #define kIOAudioControlChannelNameAll "All Channels" /*! * @defined kIOAudioControlChannelNameLeft * @abstract The value for the kIOAudioControlChannelNameKey in the IORegistry representing * the channel name for the left channel. */ #define kIOAudioControlChannelNameLeft "Left" /*! * @defined kIOAudioControlChannelNameRight * @abstract The value for the kIOAudioControlChannelNameKey in the IORegistry representing * the channel name for the right channel. */ #define kIOAudioControlChannelNameRight "Right" /*! * @defined kIOAudioControlChannelNameCenter * @abstract The value for the kIOAudioControlChannelNameKey in the IORegistry representing * the channel name for the center channel. */ #define kIOAudioControlChannelNameCenter "Center" /*! * @defined kIOAudioControlChannelNameLeftRear * @abstract The value for the kIOAudioControlChannelNameKey in the IORegistry representing * the channel name for the left rear channel. */ #define kIOAudioControlChannelNameLeftRear "LeftRear" /*! * @defined kIOAudioControlChannelNameRightRear * @abstract The value for the kIOAudioControlChannelNameKey in the IORegistry representing * the channel name for the right rear channel. */ #define kIOAudioControlChannelNameRightRear "RightRear" /*! * @defined kIOAudioControlChannelNameSub * @abstract The value for the kIOAudioControlChannelNameKey in the IORegistry representing * the channel name for the sub/LFE channel. */ #define kIOAudioControlChannelNameSub "Sub" /*! * @defined kIOAudioControlChannelNameFrontLeftCenter * @abstract The value for the kIOAudioControlChannelNameKey in the IORegistry representing * the channel name for the FrontLeftCenter channel. */ #define kIOAudioControlChannelNameFrontLeftCenter "FrontLeftCenter" /*! * @defined kIOAudioControlChannelNameFrontRightCenter * @abstract The value for the kIOAudioControlChannelNameKey in the IORegistry representing * the channel name for the FrontRightCenter channel. */ #define kIOAudioControlChannelNameFrontRightCenter "FrontRightCenter" /*! * @defined kIOAudioControlChannelNameRearCenter * @abstract The value for the kIOAudioControlChannelNameKey in the IORegistry representing * the channel name for the RearCenter channel. */ #define kIOAudioControlChannelNameRearCenter "RearCenter" /*! * @defined kIOAudioControlChannelNameSurroundLeft * @abstract The value for the kIOAudioControlChannelNameKey in the IORegistry representing * the channel name for the SurroundLeft channel. */ #define kIOAudioControlChannelNameSurroundLeft "SurroundLeft" /*! * @defined kIOAudioControlChannelNameSurroundRight * @abstract The value for the kIOAudioControlChannelNameKey in the IORegistry representing * the channel name for the SurroundRight channel. */ #define kIOAudioControlChannelNameSurroundRight "SurroundRight" /*! * @defined kIOAudioControlValueKey * @abstract The key in the IORegistry for the IOAudioControl value attribute. * @discussion The value returned by this key is a 32-bit integer representing the current value of the IOAudioControl. */ #define kIOAudioControlValueKey "IOAudioControlValue" /*! * @defined kIOAudioControlValueIsReadOnlyKey * @abstract The key in the IORegistry for the IOAudioControl value-is-read-only attribute. * @discussion The value returned by this key is a 32-bit integer but the value doesn't have any direct meaning. * Instead, the presence of this key indicates that the value for the control is read-only */ #define kIOAudioControlValueIsReadOnlyKey "IOAudioControlValueIsReadOnly" /*! * @defined kIOAudioLevelControlMinValueKey * @abstract The key in the IORegistry for the IOAudioControl minimum value attribute. * @discussion The value returned by this key is a 32-bit integer representing the minimum value for the IOAudioControl. * This is currently only valid for Level controls or other driver-defined controls that have a minimum and maximum * value. */ #define kIOAudioLevelControlMinValueKey "IOAudioLevelControlMinValue" /*! * @defined kIOAudioLevelControlMaxValueKey * @abstract The key in the IORegistry for the IOAudioControl maximum value attribute. * @discussion The value returned by this key is a 32-bit integer representing the maximum value for the IOAudioControl. * This is currently only valid for Level controls or other driver-defined controls that have a minimum and maximum * value. */ #define kIOAudioLevelControlMaxValueKey "IOAudioLevelControlMaxValue" /*! * @defined kIOAudioLevelControlMinDBKey * @abstract The key in the IORgistry for the IOAudioControl minimum db value attribute. * @discussion The value returned by this key is a fixed point value in 16.16 format represented as a 32-bit * integer. It represents the minimum value in db for the IOAudioControl. This value matches the minimum * value attribute. This is currently valid for Level controls or other driver-defined controls that have a * minimum and maximum db value. */ #define kIOAudioLevelControlMinDBKey "IOAudioLevelControlMinDB" /*! * @defined kIOAudioLevelControlMaxDBKey * @abstract The key in the IORgistry for the IOAudioControl maximum db value attribute. * @discussion The value returned by this key is a fixed point value in 16.16 format represented as a 32-bit * integer. It represents the maximum value in db for the IOAudioControl. This value matches the maximum * value attribute. This is currently valid for Level controls or other driver-defined controls that have a * minimum and maximum db value. */ #define kIOAudioLevelControlMaxDBKey "IOAudioLevelControlMaxDB" #define kIOAudioLevelControlRangesKey "IOAudioLevelControlRanges" #define kIOAudioLevelControlUseLinearScale "IOAudioLevelControlUseLinearScale" #define kIOAudioSelectorControlAvailableSelectionsKey "IOAudioSelectorControlAvailableSelections" #define kIOAudioSelectorControlSelectionValueKey "IOAudioSelectorControlSelectionValue" #define kIOAudioSelectorControlSelectionDescriptionKey "IOAudioSelectorControlSelectionDescriptionKey" #define kIOAudioSelectorControlTransportValueKey "IOAudioSelectorControlTransportValue" // <rdar://8202424> #define kIOAudioSelectorControlClockSourceKey "IOAudioSelectorControlClockSourceKey" #endif /* _IOAUDIODEFINES_H */
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/audio/IOAudioLib.h
/* * Copyright (c) 2000 Apple Computer, Inc. All rights reserved. * * @APPLE_LICENSE_HEADER_START@ * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this * file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_LICENSE_HEADER_END@ */ /* * Copyright (c) 1998-2000 Apple Computer, Inc. All rights reserved. */ /*! * @header IOAudioLib * C interface to IOAudio functions */ #ifndef _IOAUDIOLIB_H #define _IOAUDIOLIB_H #if TARGET_OS_OSX #include <IOKit/audio/IOAudioTypes.h> #endif #if 0 #ifdef __cplusplus extern "C" { #endif /*! * @function IOAudioIsOutput * @abstract Determines if the audio stream is an output stream * @param service * @param out * @result kern_return_t */ kern_return_t IOAudioIsOutput(io_service_t service, int *out); /*! * @function IOAudioFlush * @abstract Indicate the position at which the audio stream can be stopped. * @param connect the audio stream * @param end the position * @result kern_return_t */ kern_return_t IOAudioFlush(io_connect_t connect, IOAudioStreamPosition *end); /*! * @function IOAudioSetErase * @abstract Set autoerase flag, returns old value * @param connect the audio stream * @param erase true to turn off, false otherwise * @param oldVal previous value * @result kern_return_t */ kern_return_t IOAudioSetErase(io_connect_t connect, int erase, int *oldVal); #ifdef __cplusplus } #endif #endif /* 0 */ #endif /* ! _IOAUDIOLIB_H */
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/serial/IOSerialKeys.h
/* * Copyright (c) 2000 Apple Computer, Inc. All rights reserved. * * @APPLE_LICENSE_HEADER_START@ * * The contents of this file constitute Original Code as defined in and * are subject to the Apple Public Source License Version 1.1 (the * "License"). You may not use this file except in compliance with the * License. Please obtain a copy of the License at * http://www.apple.com/publicsource and read it before using this file. * * This Original Code and all software distributed under the License are * distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT. Please see the * License for the specific language governing rights and limitations * under the License. * * @APPLE_LICENSE_HEADER_END@ */ /* * IOSerialKeys.h * * 2000-10-21 gvdl Initial real change to IOKit serial family. * */ /* Sample Matching dictionary { IOProviderClass = kIOSerialBSDServiceValue; kIOSerialBSDTypeKey = kIOSerialBSDAllTypes | kIOSerialBSDModemType | kIOSerialBSDRS232Type; kIOTTYDeviceKey = <Raw Unique Device Name>; kIOTTYBaseNameKey = <Raw Unique Device Name>; kIOTTYSuffixKey = <Raw Unique Device Name>; kIOCalloutDeviceKey = <Callout Device Name>; kIODialinDeviceKey = <Dialin Device Name>; } Note only the IOProviderClass is mandatory. The other keys allow the searcher to reduce the size of the set of matching devices. */ /* Service Matching That is the 'IOProviderClass' */ #define kIOSerialBSDServiceValue "IOSerialBSDClient" /* Matching keys */ #define kIOSerialBSDTypeKey "IOSerialBSDClientType" /* Currently possible kIOSerialBSDTypeKey values. */ #define kIOSerialBSDAllTypes "IOSerialStream" #define kIOSerialBSDModemType "IOSerialStream" #define kIOSerialBSDRS232Type "IOSerialStream" // Properties that resolve to a /dev device node to open for // a particular service #define kIOTTYDeviceKey "IOTTYDevice" #define kIOTTYBaseNameKey "IOTTYBaseName" #define kIOTTYSuffixKey "IOTTYSuffix" #define kIOCalloutDeviceKey "IOCalloutDevice" #define kIODialinDeviceKey "IODialinDevice" // Property 'ioctl' wait for the tty device to go idle. #define kIOTTYWaitForIdleKey "IOTTYWaitForIdle" #if KERNEL #if !defined(KERNEL_PRIVATE) extern const OSSymbol *gIOSerialBSDServiceValue __deprecated_msg("Use DriverKit"); extern const OSSymbol *gIOSerialBSDTypeKey __deprecated_msg("Use DriverKit"); extern const OSSymbol *gIOSerialBSDAllTypes __deprecated_msg("Use DriverKit"); extern const OSSymbol *gIOSerialBSDModemType __deprecated_msg("Use DriverKit"); extern const OSSymbol *gIOSerialBSDRS232Type __deprecated_msg("Use DriverKit"); extern const OSSymbol *gIOTTYDeviceKey __deprecated_msg("Use DriverKit"); extern const OSSymbol *gIOTTYBaseNameKey __deprecated_msg("Use DriverKit"); extern const OSSymbol *gIOTTYSuffixKey __deprecated_msg("Use DriverKit"); extern const OSSymbol *gIOCalloutDeviceKey __deprecated_msg("Use DriverKit"); extern const OSSymbol *gIODialinDeviceKey __deprecated_msg("Use DriverKit"); #else extern const OSSymbol *gIOSerialBSDServiceValue; extern const OSSymbol *gIOSerialBSDTypeKey; extern const OSSymbol *gIOSerialBSDAllTypes; extern const OSSymbol *gIOSerialBSDModemType; extern const OSSymbol *gIOSerialBSDRS232Type; extern const OSSymbol *gIOTTYDeviceKey; extern const OSSymbol *gIOTTYBaseNameKey; extern const OSSymbol *gIOTTYSuffixKey; extern const OSSymbol *gIOCalloutDeviceKey; extern const OSSymbol *gIODialinDeviceKey; #endif #endif /* KERNEL */
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/serial/ioss.h
/* * Copyright (c) 2000 Apple Computer, Inc. All rights reserved. * * @APPLE_LICENSE_HEADER_START@ * * The contents of this file constitute Original Code as defined in and * are subject to the Apple Public Source License Version 1.1 (the * "License"). You may not use this file except in compliance with the * License. Please obtain a copy of the License at * http://www.apple.com/publicsource and read it before using this file. * * This Original Code and all software distributed under the License are * distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT. Please see the * License for the specific language governing rights and limitations * under the License. * * @APPLE_LICENSE_HEADER_END@ */ /* Copyright (c) 1997 Apple Computer, Inc. All Rights Reserved */ /* ioctl's for all Apple IOSerialStream based streaming serial ports */ #ifndef _SYS_IOSS_H #define _SYS_IOSS_H #ifndef _POSIX_SOURCE #include <sys/termios.h> #include <sys/ttycom.h> /* * External clock baud rates, for use with cfsetospeed */ #define _MAKE_EXT(x) (((x) << 1) | 1) #define BEXT1 _MAKE_EXT(1) #define BEXT2 _MAKE_EXT(2) #define BEXT4 _MAKE_EXT(4) #define BEXT8 _MAKE_EXT(8) #define BEXT16 _MAKE_EXT(16) #define BEXT32 _MAKE_EXT(32) #define BEXT64 _MAKE_EXT(64) #define BEXT128 _MAKE_EXT(128) #define BEXT256 _MAKE_EXT(256) // ul - unsigned long for x86_64 // us - unsigned long for i386 // speed and shspeed correspondingly typedef __uint64_t user_ul_t; typedef __uint64_t user_speed_t; typedef __uint32_t user_us_t; typedef __uint32_t user_shspeed_t; /* * Sets the receive latency (in microseconds) with the default * value of 0 meaning a 256 / 3 character delay latency. */ #define IOSSDATALAT _IOW('T', 0, unsigned long) #define IOSSDATALAT_32 _IOW('T', 0, user_us_t) #define IOSSDATALAT_64 _IOW('T', 0, user_ul_t) /* * Controls the pre-emptible status of IOSS based serial dial in devices * (i.e. /dev/tty.* devices). If true an open tty.* device is pre-emptible by * a dial out call. Once a dial in call is established then setting pre-empt * to false will halt any further call outs on the cu device. */ #define IOSSPREEMPT _IOW('T', 1, int) /* * Sets the input speed and output speed to a non-traditional baud rate */ #define IOSSIOSPEED _IOW('T', 2, speed_t) #define IOSSIOSPEED_32 _IOW('T', 2, user_shspeed_t) #define IOSSIOSPEED_64 _IOW('T', 2, user_speed_t) #endif /*_POSIX_SOURCE */ /* * END OF PROTECTED INCLUDE. */ #endif /* !_SYS_IOSS_H */
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/firewire/IOFireWireLibIsoch.h
/* * Copyright (c) 1998-2002 Apple Computer, Inc. All rights reserved. * * @APPLE_LICENSE_HEADER_START@ * * The contents of this file constitute Original Code as defined in and * are subject to the Apple Public Source License Version 1.1 (the * "License"). You may not use this file except in compliance with the * License. Please obtain a copy of the License at * http://www.apple.com/publicsource and read it before using this file. * * This Original Code and all software distributed under the License are * distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT. Please see the * License for the specific language governing rights and limitations * under the License. * * @APPLE_LICENSE_HEADER_END@ */ /* * IOFireWireLibIsoch.h * IOFireWireFamily * * Created on Mon Mar 19 2001. * Copyright (c) 2001-2002 Apple Computer, Inc. All rights reserved. * */ #ifndef __IOFireWireLibIsoch_H__ #define __IOFireWireLibIsoch_H__ #include <CoreFoundation/CoreFoundation.h> #include <IOKit/IOCFPlugIn.h> #include <IOKit/firewire/IOFireWireFamilyCommon.h> #include <IOKit/firewire/IOFireWireLib.h> // // local isoch port // // uuid string: 541971C6-CE72-11D7-809D-000393C0B9D8 #define kIOFireWireLocalIsochPortInterfaceID_v5 CFUUIDGetConstantUUIDWithBytes( kCFAllocatorDefault \ , 0x54, 0x19, 0x71, 0xC6, 0xCE, 0x72, 0x11, 0xD7\ , 0x80, 0x9D, 0x00, 0x03, 0x93, 0xC0, 0xB9, 0xD8 ) // uuid string: FECAA2F6-4E84-11D7-B6FD-0003938BEB0A #define kIOFireWireLocalIsochPortInterfaceID_v4 CFUUIDGetConstantUUIDWithBytes( kCFAllocatorDefault \ ,0xFE, 0xCA, 0xA2, 0xF6, 0x4E, 0x84, 0x11, 0xD7\ ,0xB6, 0xFD, 0x00, 0x03, 0x93, 0x8B, 0xEB, 0x0A ) // uuid string: A0AD095E-6D2F-11D6-AC82-0003933F84F0 #define kIOFireWireLocalIsochPortInterfaceID_v3 CFUUIDGetConstantUUIDWithBytes(kCFAllocatorDefault,\ 0xA0, 0xAD, 0x09, 0x5E, 0x6D, 0x2F, 0x11, 0xD6,\ 0xAC, 0x82, 0x00, 0x03, 0x93, 0x3F, 0x84, 0xF0 ) // Availability: Mac OS X "Jaguar" and later // uuid string: 73C76D09-6D2F-11D6-AF7F-0003933F84F0 #define kIOFireWireLocalIsochPortInterfaceID_v2 CFUUIDGetConstantUUIDWithBytes(kCFAllocatorDefault,\ 0x73, 0xC7, 0x6D, 0x09, 0x6D, 0x2F, 0x11, 0xD6,\ 0xAF, 0x7F, 0x00, 0x03, 0x93, 0x3F, 0x84, 0xF0 ) // uuid string: 0F5E33C8-1350-11D5-9BE7-003065AF75CC #define kIOFireWireLocalIsochPortInterfaceID CFUUIDGetConstantUUIDWithBytes(kCFAllocatorDefault,\ 0x0F, 0x5E, 0x33, 0xC8, 0x13, 0x50, 0x11, 0xD5,\ 0x9B, 0xE7, 0x00, 0x30, 0x65, 0xAF, 0x75, 0xCC) // // remote isoch port // // uuid string: AAFDBDB0-489F-11D5-BC9B-003065423456 #define kIOFireWireRemoteIsochPortInterfaceID CFUUIDGetConstantUUIDWithBytes(kCFAllocatorDefault,\ 0xAA, 0xFD, 0xBD, 0xB0, 0x48, 0x9F, 0x11, 0xD5,\ 0xBC, 0x9B, 0x00, 0x30, 0x65, 0x42, 0x34, 0x56) // // isoch channel // // uuid string: 2EC1E404-1350-11D5-89B5-003065AF75CC #define kIOFireWireIsochChannelInterfaceID CFUUIDGetConstantUUIDWithBytes(kCFAllocatorDefault,\ 0x2E, 0xC1, 0xE4, 0x04, 0x13, 0x50, 0x11, 0xD5,\ 0x89, 0xB5, 0x00, 0x30, 0x65, 0xAF, 0x75, 0xCC) // // DCL command pool // // uuid string: 4A4B1710-1350-11D5-9B12-003065AF75CC #define kIOFireWireDCLCommandPoolInterfaceID CFUUIDGetConstantUUIDWithBytes(kCFAllocatorDefault,\ 0x4A, 0x4B, 0x17, 0x10, 0x13, 0x50, 0x11, 0xD5,\ 0x9B, 0x12, 0x00, 0x30, 0x65, 0xAF, 0x75, 0xCC) // // NuDCL pool // // uuid string: D3837670-4463-11D7-B79A-0003938BEB0A #define kIOFireWireNuDCLPoolInterfaceID CFUUIDGetConstantUUIDWithBytes( kCFAllocatorDefault,\ 0xD3, 0x83, 0x76, 0x70, 0x44, 0x63, 0x11, 0xD7,\ 0xB7, 0x9A, 0x00, 0x03, 0x93, 0x8B, 0xEB, 0x0A) // uuid string: 6D1FDE59-50CE-4ED4-880A-9D13A4624038 #define kIOFireWireAsyncStreamListenerInterfaceID CFUUIDGetConstantUUIDWithBytes(kCFAllocatorDefault,\ 0x6D, 0x1F, 0xDE, 0x59, 0x50, 0xCE, 0x4E, 0xD4,\ 0x88, 0x0A, 0x90, 0x13, 0xA4, 0x62, 0x40, 0x38) typedef void (*IOFireWireIsochChannelForceStopHandler)( IOFireWireLibIsochChannelRef interface, UInt32 stopCondition); typedef IOReturn (*IOFireWireLibIsochPortCallback)( IOFireWireLibIsochPortRef interface) ; typedef IOReturn (*IOFireWireLibIsochPortAllocateCallback)( IOFireWireLibIsochPortRef interface, IOFWSpeed maxSpeed, UInt32 channel) ; typedef IOReturn (*IOFireWireLibIsochPortGetSupportedCallback)( IOFireWireLibIsochPortRef interface, IOFWSpeed* outMaxSpeed, UInt64* outChanSupported) ; typedef IOReturn (*IOFireWireLibIsochPortFinalizeCallback)( void* refcon ) ; // ============================================================ // // IOFireWireIsochPort // // ============================================================ /*! @parseOnly */ #define IOFIREWIRELIBISOCHPORT_C_GUTS \ /*! @function GetSupported \ @abstract The method is called to determine which FireWire isochronous \ channels and speed this port supports. \ @discussion This method is called by the channel object to which a port \ has been added. Subclasses of IOFireWireIsochPortInterface override \ this method to support specific hardware. Do not call this method \ directly. \ @param self The isoch port interface to use. \ @param maxSpeed A pointer to an IOFWSpeed which should be filled with \ the maximum speed this port can talk or listen. \ @param chanSupported A pointer to a UInt64 which should be filled with \ a bitmask representing the FireWire bus isochonous channels on \ which the port can talk or listen. Set '1' for supported, '0' for \ unsupported. \ @result Return kIOReturnSuccess on success, other return any other \ IOReturn error code.*/ \ IOReturn (*GetSupported) ( IOFireWireLibIsochPortRef self, IOFWSpeed* maxSpeed, UInt64* chanSupported ) ; \ /*! @function AllocatePort \ @abstract The method is called when the port should configure its \ associated hardware to prepare to send or receive isochronous data \ on the channel number and at the speed specified. \ @discussion This method is called by the channel object to which a port \ has been added. Subclasses of IOFireWireIsochPortInterface override \ this method to support specific hardware. Do not call this method \ directly. \ @param self The isoch port interface to use. \ @param speed Channel speed \ @param chan Channel number (0-63) \ @result Return kIOReturnSuccess on success, other return any other \ IOReturn error code.*/ \ IOReturn (*AllocatePort) ( IOFireWireLibIsochPortRef self, IOFWSpeed speed, UInt32 chan ) ; \ /*! @function ReleasePort \ @abstract The method is called to release the hardware after the \ channel has been stopped. \ @discussion This method is called by the channel object to which a port \ has been added. Subclasses of IOFireWireIsochPortInterface override \ this method to support specific hardware. Do not call this method \ directly. \ @param self The isoch port interface to use. \ @result Return kIOReturnSuccess on success, other return any other IOReturn error code.*/ \ IOReturn (*ReleasePort) ( IOFireWireLibIsochPortRef self ) ; \ /*! @function Start \ @abstract The method is called when the port is to begin talking or listening. \ @discussion This method is called by the channel object to which a port \ has been added. Subclasses of IOFireWireIsochPortInterface override \ this method to support specific hardware. Do not call this method \ directly. \ @param self The isoch port interface to use. \ @result Return kIOReturnSuccess on success, other return any other IOReturn error code.*/ \ IOReturn (*Start) ( IOFireWireLibIsochPortRef self ) ; \ /*! @function Stop \ @abstract The method is called when the port is to stop talking or listening. \ @discussion This method is called by the channel object to which a port \ has been added. Subclasses of IOFireWireIsochPortInterface override \ this method to support specific hardware. Do not call this method \ directly. \ @param self The isoch port interface to use. \ @result Return kIOReturnSuccess on success, other return any \ other IOReturn error code.*/ \ IOReturn (*Stop) ( IOFireWireLibIsochPortRef self ) ; \ /*! @function SetRefCon \ @abstract Set reference value associated with this port. \ @discussion Retrieve the reference value with GetRefCon() \ @param self The isoch port interface to use. \ @param inRefCon The new reference value.*/ \ void (*SetRefCon) ( IOFireWireLibIsochPortRef self, void* inRefCon) ; \ /*! @function GetRefCon \ @abstract Get reference value associated with this port. \ @discussion Set the reference value with SetRefCon() \ @param self The isoch port interface to use. \ @result The port refcon value.*/ \ void* (*GetRefCon) ( IOFireWireLibIsochPortRef self) /*! @class @abstract FireWire user client isochronous port interface @discussion Isochronous ports represent talkers or listeners on a FireWire isochronous channel. This is a base class containing all isochronous port functionality not specific to any type of port. Ports are added to channel interfaces (IOFireWireIsochChannelInterface) which coordinate the start and stop of isochronous traffic on a FireWire bus isochronous channel. */ typedef struct IOFireWireIsochPortInterface_t { IUNKNOWN_C_GUTS ; /*! Interface revision. */ UInt32 revision; /*! Interface version. */ UInt32 version; IOFIREWIRELIBISOCHPORT_C_GUTS ; } IOFireWireIsochPortInterface ; /*! @class Description forthcoming */ typedef struct IOFireWireRemoteIsochPortInterface_t { IUNKNOWN_C_GUTS ; /*! Interface revision. */ UInt32 revision; /*! Interface version. */ UInt32 version; IOFIREWIRELIBISOCHPORT_C_GUTS ; /*! Description forthcoming */ IOFireWireLibIsochPortGetSupportedCallback (*SetGetSupportedHandler) ( IOFireWireLibRemoteIsochPortRef self, IOFireWireLibIsochPortGetSupportedCallback inHandler) ; /*! Description forthcoming */ IOFireWireLibIsochPortAllocateCallback (*SetAllocatePortHandler) ( IOFireWireLibRemoteIsochPortRef self, IOFireWireLibIsochPortAllocateCallback inHandler) ; /*! Description forthcoming */ IOFireWireLibIsochPortCallback (*SetReleasePortHandler)( IOFireWireLibRemoteIsochPortRef self, IOFireWireLibIsochPortCallback inHandler) ; /*! Description forthcoming */ IOFireWireLibIsochPortCallback (*SetStartHandler)( IOFireWireLibRemoteIsochPortRef self, IOFireWireLibIsochPortCallback inHandler) ; /*! Description forthcoming */ IOFireWireLibIsochPortCallback (*SetStopHandler)( IOFireWireLibRemoteIsochPortRef self, IOFireWireLibIsochPortCallback inHandler) ; } IOFireWireRemoteIsochPortInterface ; /*! @class @abstract FireWire user client local isochronous port object. @discussion Represents a FireWire isochronous talker or listener within the local machine. Isochronous transfer is controlled by an associated DCL (Data Stream Control Language) program, which is similar to a hardware DMA program but is hardware agnostic. DCL programs can be written using the IOFireWireDCLCommandPoolInterface object. This interface contains all methods of IOFireWireIsochPortInterface and IOFireWireLocalIsochPortInterface. This interface will contain all v2 methods of IOFireWireLocalIsochPortInterface when instantiated as v2 or newer. Transfer buffers for the local isoch port must all come from a single allocation made with vm_allocate() or mmap(..., MAP_ANON ). Calling vm_deallocate() on the buffers before deallocating a local isoch port object may result in a deadlock. Note: Calling Release() on the local isoch port may not immediately release the isoch port; so it may not be safe to call vm_deallocate() on your transfer buffers. To guarantee the port has been release, run the isochronous runloop until the port is finalized (it has processed any pending callbacks). The finalize callback will be called when the port is finalized. Set the finalize callback using SetFinalizeCallback(). */ typedef struct IOFireWireLocalIsochPortInterface_t { IUNKNOWN_C_GUTS ; /*! Interface revision */ UInt32 revision; /*! Interface revision */ UInt32 version; IOFIREWIRELIBISOCHPORT_C_GUTS ; /*! @function ModifyJumpDCL @abstract Change the jump target label of a jump DCL. @discussion Use this function to change the flow of a DCL program. Works whether the DCL program is currently running or not. @param self The local isoch port interface to use. @param inJump The jump DCL to modify. @param inLabel The label to jump to. @result kIOReturnSuccess on success. Will return an error if 'inJump' does not point to a valid jump DCL or 'inLabel' does not point to a valid label DCL.*/ IOReturn (*ModifyJumpDCL)( IOFireWireLibLocalIsochPortRef self, DCLJump* inJump, DCLLabel* inLabel) ; // --- utility functions ---------- /*! @function PrintDCLProgram @abstract Display the contents of a DCL program. @param self The local isoch port interface to use. @param inProgram A pointer to the first DCL of the program to display. @param inLength The length (in DCLs) of the program.*/ void (*PrintDCLProgram)( IOFireWireLibLocalIsochPortRef self, const DCLCommand* inProgram, UInt32 inLength) ; // // --- v2 // /*! @function ModifyTransferPacketDCLSize @abstract Modify the transfer size of a transfer packet DCL (send or receive) @discussion Allows you to modify transfer packet DCLs after they have been compiled and while the DCL program is still running. The transfer size can be set to any size less than or equal to the size set when the DCL program was compiled (including 0). Availability: IOFireWireLocalIsochPortInterface_v2 and newer. @param self The local isoch port interface to use. @param inDCL A pointer to the DCL to modify. @param size The new size of data to be transferred. @result Returns kIOReturnSuccess on success. Will return an error if 'size' is too large for this program.*/ IOReturn (*ModifyTransferPacketDCLSize)( IOFireWireLibLocalIsochPortRef self, DCLTransferPacket* inDCL, IOByteCount size ) ; // // --- v3 // /*! @function ModifyTransferPacketDCLBuffer @abstract NOT IMPLEMENTED. Modify the transfer size of a transfer packet DCL (send or receive) @discussion NOT IMPLEMENTED. Allows you to modify transfer packet DCLs after they have been compiled and while the DCL program is still running. The buffer can be set to be any location within the range of buffers specified when the DCL program was compiled (including 0). Availability: IOFireWireLocalIsochPortInterface_v3 and newer. @param self The local isoch port interface to use. @param inDCL A pointer to the DCL to modify. @param buffer The new buffer to or from data will be transferred. @result Returns kIOReturnSuccess on success. Will return an error if the range specified by [buffer, buffer+size] is not in the range of memory locked down for this program.*/ IOReturn (*ModifyTransferPacketDCLBuffer)( IOFireWireLibLocalIsochPortRef self, DCLTransferPacket* inDCL, void* buffer ) ; /*! @function ModifyTransferPacketDCL @abstract Modify the transfer size of a transfer packet DCL (send or receive) @discussion Allows you to modify transfer packet DCLs after they have been compiled and while the DCL program is still running. The transfer size can be set to any size less than or equal to the size set when the DCL program was compiled (including 0). Availability: IOFireWireLocalIsochPortInterface_v3 and newer. @param self The local isoch port interface to use. @param inDCL A pointer to the DCL to modify. @param buffer The new buffer to or from data will be transferred. @param size The new size of data to be transferred. @result Returns kIOReturnSuccess on success. Will return an error if 'size' is too large or 'inDCL' does not point to a valid transfer packet DCL, or the range specified by [buffer, buffer+size] is not in the range of memory locked down for this program.*/ IOReturn (*ModifyTransferPacketDCL)( IOFireWireLibLocalIsochPortRef self, DCLTransferPacket* inDCL, void* buffer, IOByteCount size ) ; // // v4 // /*! @function SetFinalizeCallback @abstract Set the finalize callback for a local isoch port @discussion When Stop() is called on a LocalIsochPortInterface, there may or may not be isoch callbacks still pending for this isoch port. The port must be allowed to handle any pending callbacks, so the isoch runloop should not be stopped until a port has handled all pending callbacks. The finalize callback is called after the final callback has been made on the isoch runloop. After this callback is sent, it is safe to stop the isoch runloop. You should not access the isoch port after the finalize callback has been made; it may be released immediately after this callback is sent. Availability: IOFireWireLocalIsochPortInterface_v4 and newer. @param self The local isoch port interface to use. @param finalizeCallback The finalize callback. @result Returns true if this isoch port has no more pending callbacks and does not need any more runloop time.*/ IOReturn (*SetFinalizeCallback)( IOFireWireLibLocalIsochPortRef self, IOFireWireLibIsochPortFinalizeCallback finalizeCallback ) ; // // v5 // IOReturn (*SetResourceUsageFlags)( IOFireWireLibLocalIsochPortRef self, IOFWIsochResourceFlags flags ) ; IOReturn (*Notify)( IOFireWireLibLocalIsochPortRef self, IOFWDCLNotificationType notificationType, void ** inDCLList, UInt32 numDCLs ) ; } IOFireWireLocalIsochPortInterface ; // ============================================================ // // IOFireWireIsochChannelInterface // // ============================================================ /*! @class @abstract FireWire user client isochronous channel object. @discussion IOFireWireIsochChannelInterface is an abstract representataion of a FireWire bus isochronous channel. This interface coordinates starting and stopping traffic on a FireWire bus isochronous channel and can optionally communicate with the IRM to automatically allocate bandwidth and channel numbers. When using automatic IRM allocation, the channel interface reallocates its bandwidth and channel reservation after each bus reset. Isochronous port interfaces representing FireWire isochronous talkers and listeners must be added to the channel using SetTalker() and AddListener() */ typedef struct IOFireWireIsochChannelInterface_t { IUNKNOWN_C_GUTS ; /*! Interface revision. */ UInt32 revision; /*! Interface version. */ UInt32 version; /*! @function SetTalker @abstract Set the talker port for this channel. @param self The isoch channel interface to use. @param talker The new talker. @result Returns an IOReturn error code. */ IOReturn (*SetTalker) ( IOFireWireLibIsochChannelRef self, IOFireWireLibIsochPortRef talker ) ; /*! @function AddListener @abstract Modify the transfer size of a transfer packet DCL (send or receive) @discussion Allows you to modify transfer packet DCLs after they have been compiled and while the DCL program is still running. The transfer size can be set to any size less than or equal to the size set when the DCL program was compiled (including 0). Availability: IOFireWireLocalIsochPortInterface_v3 and newer. @param self The isoch channel interface to use. @param listener The listener to add. @result Returns an IOReturn error code. */ IOReturn (*AddListener) ( IOFireWireLibIsochChannelRef self, IOFireWireLibIsochPortRef listener ) ; /*! @function AllocateChannel @abstract Prepare all hardware to begin sending or receiving isochronous data. @discussion Calling this function will result in all listener and talker ports on this isochronous channel having their AllocatePort method called. @param self The isoch channel interface to use. @result Returns an IOReturn error code. */ IOReturn (*AllocateChannel) ( IOFireWireLibIsochChannelRef self ) ; /*! @function ReleaseChannel @abstract Release all hardware after stopping the isochronous channel. @discussion Calling this function will result in all listener and talker ports on this isochronous channel having their ReleasePort method called. @param self The isoch channel interface to use. @result Returns an IOReturn error code. */ IOReturn (*ReleaseChannel) ( IOFireWireLibIsochChannelRef self ) ; /*! @function Start @abstract Start the channel. @discussion Calling this function will result in all listener and talker ports on this isochronous channel having their Start method called. @param self The isoch channel interface to use. @result Returns an IOReturn error code. */ IOReturn (*Start) ( IOFireWireLibIsochChannelRef self ) ; /*! @function Stop @abstract Stop the channel. @discussion Calling this function will result in all listener and talker ports on this isochronous channel having their Stop method called. @param self The isoch channel interface to use. @result Returns an IOReturn error code. */ IOReturn (*Stop) ( IOFireWireLibIsochChannelRef self ) ; // --- notification /*! @function SetChannelForceStopHandler @abstract Set the channel force stop handler. @discussion The specified callback is called when the channel is stopped and cannot be restarted automatically. @param self The isoch channel interface to use. @param stopProc The handler to set. @result Returns the previously set handler or NULL is no handler was set.*/ IOFireWireIsochChannelForceStopHandler (*SetChannelForceStopHandler) ( IOFireWireLibIsochChannelRef self, IOFireWireIsochChannelForceStopHandler stopProc) ; /*! @function SetRefCon @abstract Set reference value associated with this channel. @discussion Retrieve the reference value with GetRefCon() @param self The isoch channel interface to use. @param stopProcRefCon The new reference value.*/ void (*SetRefCon) ( IOFireWireLibIsochChannelRef self, void* stopProcRefCon) ; /*! @function GetRefCon @abstract Set reference value associated with this channel. @discussion Retrieve the reference value with SetRefCon() @param self The isoch channel interface to use.*/ void* (*GetRefCon) ( IOFireWireLibIsochChannelRef self) ; /*! Description forthcoming */ Boolean (*NotificationIsOn) ( IOFireWireLibIsochChannelRef self) ; /*! Description forthcoming */ Boolean (*TurnOnNotification) ( IOFireWireLibIsochChannelRef self) ; /*! Description forthcoming */ void (*TurnOffNotification) ( IOFireWireLibIsochChannelRef self) ; /*! Description forthcoming */ void (*ClientCommandIsComplete) ( IOFireWireLibIsochChannelRef self, FWClientCommandID commandID, IOReturn status) ; } IOFireWireIsochChannelInterface ; // ============================================================ // // IOFireWireDCLCommandPoolInterface // // ============================================================ /*! @class IOFireWireDCLCommandPoolInterface Description forthcoming. */ typedef struct IOFireWireDCLCommandPoolInterface_t { IUNKNOWN_C_GUTS ; /*! Interface revision. */ UInt32 revision; /*! Interface version. */ UInt32 version; /*! Description forthcoming */ DCLCommand* (*Allocate) ( IOFireWireLibDCLCommandPoolRef self, IOByteCount inSize ) ; /*! Description forthcoming */ IOReturn (*AllocateWithOpcode) ( IOFireWireLibDCLCommandPoolRef self, DCLCommand* inDCL, DCLCommand** outDCL, UInt32 opcode, ... ) ; /*! Description forthcoming */ DCLCommand* (*AllocateTransferPacketDCL) ( IOFireWireLibDCLCommandPoolRef self, DCLCommand* inDCL, UInt32 inOpcode, void* inBuffer, IOByteCount inSize) ; /*! Description forthcoming */ DCLCommand* (*AllocateTransferBufferDCL) ( IOFireWireLibDCLCommandPoolRef self, DCLCommand* inDCL, UInt32 inOpcode, void* inBuffer, IOByteCount inSize, IOByteCount inPacketSize, UInt32 inBufferOffset) ; /*! Description forthcoming */ DCLCommand* (*AllocateSendPacketStartDCL) ( IOFireWireLibDCLCommandPoolRef self, DCLCommand* inDCL, void* inBuffer, IOByteCount inSize) ; // AllocateSendPacketWithHeaderStartDCL has been deprecated! If you need this functionality, you should be using NuDCL! /*! Description forthcoming */ DCLCommand* (*AllocateSendPacketWithHeaderStartDCL)( IOFireWireLibDCLCommandPoolRef self, DCLCommand* inDCL, void* inBuffer, IOByteCount inSize) ; /*! Description forthcoming */ DCLCommand* (*AllocateSendBufferDCL) ( IOFireWireLibDCLCommandPoolRef self, DCLCommand* inDCL, void* inBuffer, IOByteCount inSize, IOByteCount inPacketSize, UInt32 inBufferOffset) ; /*! Description forthcoming */ DCLCommand* (*AllocateSendPacketDCL) ( IOFireWireLibDCLCommandPoolRef self, DCLCommand* inDCL, void* inBuffer, IOByteCount inSize) ; /*! Description forthcoming */ DCLCommand* (*AllocateReceivePacketStartDCL)( IOFireWireLibDCLCommandPoolRef self, DCLCommand* inDCL, void* inBuffer, IOByteCount inSize) ; /*! Description forthcoming */ DCLCommand* (*AllocateReceivePacketDCL) ( IOFireWireLibDCLCommandPoolRef self, DCLCommand* inDCL, void* inBuffer, IOByteCount inSize) ; /*! Description forthcoming */ DCLCommand* (*AllocateReceiveBufferDCL) ( IOFireWireLibDCLCommandPoolRef self, DCLCommand* inDCL, void* inBuffer, IOByteCount inSize, IOByteCount inPacketSize, UInt32 inBufferOffset) ; /*! Description forthcoming */ DCLCommand* (*AllocateCallProcDCL) ( IOFireWireLibDCLCommandPoolRef self, DCLCommand* inDCL, DCLCallCommandProc* inProc, DCLCallProcDataType inProcData) ; /*! Description forthcoming */ DCLCommand* (*AllocateLabelDCL) ( IOFireWireLibDCLCommandPoolRef self, DCLCommand* inDCL) ; /*! Description forthcoming */ DCLCommand* (*AllocateJumpDCL) ( IOFireWireLibDCLCommandPoolRef self, DCLCommand* inDCL, DCLLabel* pInJumpDCLLabel) ; /*! Description forthcoming */ DCLCommand* (*AllocateSetTagSyncBitsDCL) ( IOFireWireLibDCLCommandPoolRef self, DCLCommand* inDCL, UInt16 inTagBits, UInt16 inSyncBits) ; /*! Description forthcoming */ DCLCommand* (*AllocateUpdateDCLListDCL) ( IOFireWireLibDCLCommandPoolRef self, DCLCommand* inDCL, DCLCommand** inDCLCommandList, UInt32 inNumCommands) ; /*! Description forthcoming */ DCLCommand* (*AllocatePtrTimeStampDCL) ( IOFireWireLibDCLCommandPoolRef self, DCLCommand* inDCL, UInt32* inTimeStampPtr) ; /*! Description forthcoming */ void (*Free) ( IOFireWireLibDCLCommandPoolRef self, DCLCommand* inDCL ) ; /*! Description forthcoming */ IOByteCount (*GetSize) ( IOFireWireLibDCLCommandPoolRef self ) ; /*! Description forthcoming */ Boolean (*SetSize) ( IOFireWireLibDCLCommandPoolRef self, IOByteCount inSize ) ; /*! Description forthcoming */ IOByteCount (*GetBytesRemaining) ( IOFireWireLibDCLCommandPoolRef self ) ; } IOFireWireDCLCommandPoolInterface ; /*! @class IOFireWireNuDCLPoolInterface @discussion Use this interface to build NuDCL-based DCL programs. */ typedef struct IOFireWireNuDCLPoolInterface_t { IUNKNOWN_C_GUTS ; /*! Interface version */ UInt32 revision; /*! Interface version */ UInt32 version; // Command pool management: /*! @function GetProgram @abstract Finds the first DCL in the pool not preceeded by any other DCL. @discussion Returns a backwards-compatible DCL program pointer. This can be passed to IOFireWireLibDeviceRef::CreateLocalIsochPort. @param self The NuDCL pool to use. @result A DCLCommand pointer.*/ DCLCommand* (*GetProgram)( IOFireWireLibNuDCLPoolRef self ) ; /*! @function GetDCLs @abstract Returns the pool's DCL program as a CFArray of NuDCLRef's. @param self The NuDCL pool to use. @result A CFArrayRef.*/ CFArrayRef (*GetDCLs)( IOFireWireLibNuDCLPoolRef self ) ; /*! Description forthcoming */ void (*PrintProgram)( IOFireWireLibNuDCLPoolRef self ) ; /*! Description forthcoming */ void (*PrintDCL)( NuDCLRef dcl ) ; // Allocating transmit NuDCLs: /*! @function SetCurrentTagAndSync @abstract Set current tag and sync bits @discussion Sets the DCL pool's current tag and sync bits. All send DCLs allocated after calling this function will transmit the specified tag and sync values. These fields can also be set on each DCL using SetDCLTagBits() and SetDCLSyncBits(). @param self The NuDCL pool to use. @param tag Tag field value for subsequently allocated send DCLs @param sync Sync field value for subsequently allocated send DCLs */ void (*SetCurrentTagAndSync)( IOFireWireLibNuDCLPoolRef self, UInt8 tag, UInt8 sync ) ; /*! @function AllocateSendPacket @abstract Allocate a SendPacket NuDCL and append it to the program. @discussion The SendPacket DCL sends an isochronous packet on the bus. One DCL runs per bus cycle. The isochronous header is automatically generated, but can be overriden. An update must be run to regenerate the isochronous header. The sync and tag fields of allocated DCLs default to 0, unless If SetCurrentTagAndSync has been called. Send DCLs can be modified using other functions of IOFireWireLibNuDCLPool. @param self The NuDCL pool to use. @param saveBag The allocated DCL can be added to a CFBag for easily setting DCL update lists. Pass a CFMutableSetRef to add the allocated DCL to a CFBag; pass NULL to ignore. SaveBag is unmodified on failure. @param numBuffers The number of virtual ranges in 'buffers'. @param buffers An array of virtual memory ranges containing the packet contents. The array is copied into the DCL. @result Returns an NuDCLSendPacketRef on success or 0 on failure. */ NuDCLSendPacketRef (*AllocateSendPacket)( IOFireWireLibNuDCLPoolRef self, CFMutableSetRef saveBag, UInt32 numBuffers, IOVirtualRange* buffers ) ; /*! @function AllocateSendPacket_v @abstract Allocate a SendPacket NuDCL and append it to the program. @discussion Same as AllocateSendPacket but ranges are passed as a NULL-terminated vector of IOVirtualRange's @param self The NuDCL pool to use. @param saveBag The allocated DCL can be added to a CFBag for easily setting DCL update lists. Pass a CFMutableSetRef to add the allocated DCL to a CFBag; pass NULL to ignore. SaveBag is unmodified on failure. @param firstRange The first buffer to be transmitted. Follow with additional ranges; terminate with NULL. @result Returns an NuDCLSendPacketRef on success or 0 on failure. */ NuDCLSendPacketRef (*AllocateSendPacket_v)( IOFireWireLibNuDCLPoolRef self, CFMutableSetRef saveBag, IOVirtualRange* firstRange, ... ) ; /*! @function AllocateSkipCycle @abstract Allocate a SkipCycle NuDCL and append it to the program. @discussion The SkipCycle DCL causes the DCL program to "sends" an empty cycle. @param self The NuDCL pool to use. @result Returns an NuDCLSkipCycleRef on success or 0 on failure. */ NuDCLSkipCycleRef (*AllocateSkipCycle)( IOFireWireLibNuDCLPoolRef self ) ; // Allocating receive NuDCLs: /*! @function AllocateReceivePacket @abstract Allocate a ReceivePacket NuDCL and append it to the program @discussion The ReceivePacket DCL receives an isochronous packet from the bus. One DCL runs per bus cycle. If receiving isochronous headers, an update must be run before the isochronous header is valid. Receive DCLs can be modified using other functions of IOFireWireLibNuDCLPool. @param self The NuDCL pool to use. @param headerBytes Number of bytes of isochronous header to receive with the data. Valid values are 0, 4, and 8. @param saveBag The allocated DCL can be added to a CFBag for easily setting DCL update lists. Pass a CFMutableSetRef to add the allocated DCL to a CFBag; pass NULL to ignore. SaveBag is unmodified on failure. @param numBuffers The number of virtual ranges in 'buffers'. @param buffers An array of virtual memory ranges containing the packet contents. The array is copied into the DCL. @result Returns an NuDCLReceivePacketRef on success or 0 on failure. */ NuDCLReceivePacketRef (*AllocateReceivePacket)( IOFireWireLibNuDCLPoolRef self, CFMutableSetRef saveBag, UInt8 headerBytes, UInt32 numBuffers, IOVirtualRange* buffers ) ; /*! @function AllocateReceivePacket_v @abstract Allocate a ReceivePacket NuDCL and append it to the program @discussion Same as AllocateReceivePacket but ranges are passed as a NULL-terminated vector of IOVirtualRange's @param self The NuDCL pool to use. @param saveBag The allocated DCL can be added to a CFBag for easily setting DCL update lists. Pass a CFMutableSetRef to add the allocated DCL to a CFBag; pass NULL to ignore. SaveBag is unmodified on failure. @param headerBytes Number of bytes of isochronous header to receive with the data. Valid values are 0, 4, and 8. @param firstRange The first buffer to be transmitted. Follow with additional ranges; terminate with NULL. @result Returns an NuDCLReceivePacketRef on success or 0 on failure. */ NuDCLReceivePacketRef (*AllocateReceivePacket_v)( IOFireWireLibNuDCLPoolRef self, CFMutableSetRef saveBag, UInt8 headerBytes, IOVirtualRange* firstRange, ... ) ; // NuDCL configuration /*! @function FindDCLNextDCL @abstract Get the next pointer for a NuDCL @discussion Applies: Any NuDCLRef @param dcl The dcl whose next pointer will be returned @result Returns the DCL immediately following this DCL in program order (ignoring branches) or 0 for none.*/ NuDCLRef (*FindDCLNextDCL)( IOFireWireLibNuDCLPoolRef self, NuDCLRef dcl ) ; /*! @function SetDCLBranch @abstract Set the branch pointer for a NuDCL @discussion Program execution will jump to the DCL pointed to by 'branchDCL', after the DCL is executed. If set to 0, execution will stop after this DCL. This change will apply immediately to a non-running DCL program. To apply the change to a running program use IOFireWireLocalIsochPortInterface::Notify() Applies: Any NuDCLRef. @result Returns an IOReturn error code.*/ IOReturn (*SetDCLBranch)( NuDCLRef dcl, NuDCLRef branchDCL ) ; /*! @function GetDCLBranch @abstract Get the branch pointer for a NuDCL @discussion Applies: Any NuDCLRef. @param dcl The dcl whose branch pointer will be returned. @result Returns the branch pointer of 'dcl' or 0 for none is set.*/ NuDCLRef (*GetDCLBranch)( NuDCLRef dcl ) ; /*! @function SetDCLTimeStampPtr @abstract Set the time stamp pointer for a NuDCL @discussion Setting a the time stamp pointer for a NuDCL causes a time stamp to be recorded when a DCL executes. This DCL must be updated after it has executed for the timestamp to be valid. This change will apply immediately to a non-running DCL program. To apply the change to a running program use IOFireWireLocalIsochPortInterface::Notify() Applies: Any NuDCLRef. @param dcl The DCL for which time stamp pointer will be set @param timeStampPtr A pointer to a quadlet which will hold the timestamp after 'dcl' is updated. @result Returns an IOReturn error code.*/ IOReturn (*SetDCLTimeStampPtr)( NuDCLRef dcl, UInt32* timeStampPtr ) ; /*! @function GetDCLTimeStampPtr @abstract Get the time stamp pointer for a NuDCL. @discussion Applies: Any NuDCLRef. @param dcl The DCL whose timestamp pointer will be returned. @result Returns a UInt32 time stamp pointer.*/ UInt32* (*GetDCLTimeStampPtr)( NuDCLRef dcl ) ; /*! @function SetDCLStatusPtr @abstract Set the status pointer for a NuDCL @discussion Setting a the status pointer for a NuDCL causes the packet transmit/receive hardware status to be recorded when the DCL executes. This DCL must be updated after it has executed for the status to be valid. This change will apply immediately to a non-running DCL program. To apply the change to a running program use IOFireWireLocalIsochPortInterface::Notify() Status values are as follows: (from the OHCI spec, section 3.1.1) <dfn><table bgcolor="#EBEBEB"> <tr> <td><b>5'h00</b></td> <td>No event status. </td> </tr> <tr> <td><b>5'h02</b></td> <td>evt_long_packet (receive)</td> <td>The received data length was greater than the buffer's data_length. </td> </tr> <tr> <td><b>5'h05</b></td> <td>evt_overrun (receive)</td> <td>A receive FIFO overflowed during the reception of an isochronous packet. </td> </tr> <tr> <td><b>5'h06</b></td> <td>evt_descriptor_read (receive/transmit)</td> <td>An unrecoverable error occurred while the Host Controller was reading a descriptor block. </td> </tr> <tr> <td><b>5'h07</b></td> <td>evt_data_read (transmit)</td> <td>An error occurred while the Host Controller was attempting to read from host memory in the data stage of descriptor processing. </td> </tr> <tr> <td><b>5'h08</b></td> <td>evt_data_write (receive/transmit)</td> <td>An error occurred while the Host Controller was attempting to write to host memory either in the data stage of descriptor processing (AR, IR), or when processing a single 16-bit host memory write (IT). </td> </tr> <tr> <td><b>5'h0A</b></td> <td>evt_timeout (transmit)</td> <td>Indicates that the asynchronous transmit response packet expired and was not transmitted, or that an IT DMA context experienced a skip processing overflow (See section9.3.4). </td> </tr> <tr> <td><b>5'h0B</b></td> <td>evt_tcode_err (transmit)</td> <td>A bad tCode is associated with this packet. The packet was flushed. </td> </tr> <tr> <td><b>5'h0E</b></td> <td>evt_unknown (receive/transmit)</td> <td>An error condition has occurred that cannot be represented by any other event codes defined herein. </td> </tr> <tr> <td><b>5'h11</b></td> <td>ack_complete (receive/transmit)</td> <td>No event occurred. (Success)</td> </tr> <tr> <td><b>5'h1D</b></td> <td>ack_data_error (receive)</td> <td>A data field CRC or data_length error.</td> </tr> </table> </dfn> Applies: Any NuDCLRef. @param dcl The DCL for which status pointer will be set @param statusPtr A pointer to a quadlet which will hold the status after 'dcl' is updated. @result Returns an IOReturn error code.*/ IOReturn (*SetDCLStatusPtr)( NuDCLRef dcl, UInt32* statusPtr ) ; /*! @function GetDCLStatusPtr @abstract Get the status pointer for a NuDCL. @discussion Applies: Any NuDCLRef. @param dcl The DCL whose status pointer will be returned. @result Returns a UInt32 status pointer.*/ UInt32* (*GetDCLStatusPtr)( NuDCLRef dcl ) ; /*! @function AppendDCLRanges @abstract Add a memory range to the scatter gather list of a NuDCL @discussion This change will apply immediately to a non-running DCL program. To apply the change to a running program use IOFireWireLocalIsochPortInterface::Notify() Applies: NuDCLSendPacketRef, NuDCLReceivePacketRef @param dcl The DCL to modify @param range A IOVirtualRange to add to this DCL buffer list. Do not pass NULL. @result Returns an IOReturn error code.*/ IOReturn (*AppendDCLRanges) ( NuDCLRef dcl, UInt32 numRanges, IOVirtualRange* range ) ; /*! @function SetDCLRanges @abstract Set the scatter gather list for a NuDCL @discussion Set the list of data buffers for a DCL. Setting too many ranges may result in a memory region with too many discontinous physical segments for the hardware to send or receive in a single packet. This will result in an error when the program is compiled. This change will apply immediately to a non-running DCL program. To apply the change to a running program use IOFireWireLocalIsochPortInterface::Notify() Applies: NuDCLSendPacketRef, NuDCLReceivePacketRef @param dcl The DCL to modify @param numRanges number of ranges in 'ranges'. @param ranges An array of virtual ranges @result Returns an IOReturn error code.*/ IOReturn (*SetDCLRanges) ( NuDCLRef dcl, UInt32 numRanges, IOVirtualRange* ranges ) ; IOReturn (*SetDCLRanges_v) ( NuDCLRef dcl, IOVirtualRange* firstRange, ... ) ; /*! @function GetDCLRanges @abstract Get the scatter-gather list for a NuDCL @discussion Applies: NuDCLSendPacketRef, NuDCLReceivePacketRef @param dcl The DCL to query @param maxRanges Description forthcoming. @param outRanges Description forthcoming. @result Returns the previously set handler or NULL is no handler was set.*/ UInt32 (*GetDCLRanges) ( NuDCLRef dcl, UInt32 maxRanges, IOVirtualRange* outRanges ) ; /*! @function CountDCLRanges @abstract Returns number of buffers for a NuDCL @discussion Applies: NuDCLSendPacketRef, NuDCLReceivePacket @param dcl The DCL to query @result Returns number of ranges in DCLs scatter-gather list*/ UInt32 (*CountDCLRanges) ( NuDCLRef dcl ) ; /*! @function GetDCLSpan @abstract Returns a virtual range spanning lowest referenced buffer address to highest @discussion Applies: NuDCLSendPacketRef, NuDCLReceivePacket @param dcl The DCL to query @result Returns an IOVirtualRange.*/ IOReturn (*GetDCLSpan) ( NuDCLRef dcl, IOVirtualRange* spanRange ) ; /*! @function GetDCLSize @abstract Returns number of bytes to be transferred by a NuDCL @discussion Applies: NuDCLSendPacketRef, NuDCLReceivePacket @param dcl The DCL to query @result Returns an IOByteCount.*/ IOByteCount (*GetDCLSize) ( NuDCLRef dcl ) ; /*! @function SetDCLCallback @abstract Set the callback for a NuDCL @discussion A callback can be called each time a NuDCL is run. Use SetDCLCallback() to set the callback for a NuDCL. If the update option is also set, the callback will be called after the update has run. This change will apply immediately to a non-running DCL program. To apply the change to a running program use IOFireWireLocalIsochPortInterface::Notify() Applies: Any NuDCLRef @param dcl The DCL to modify @param callback The callback function. @result Returns an IOReturn error code.*/ IOReturn (*SetDCLCallback) ( NuDCLRef dcl, NuDCLCallback callback ) ; /*! @function GetDCLCallback @abstract Get callback for a NuDCL @discussion Returns the callback function for a DCL Applies: Any NuDCLRef @param dcl The DCL to query @result Returns the DCLs callback function or NULL if none is set.*/ NuDCLCallback (*GetDCLCallback)( NuDCLRef dcl ) ; /*! @function SetDCLUserHeaderPtr @abstract Set a user specified header for a send NuDCL @discussion Allows the client to create a custom header for a transmitted isochronous packet. The header is masked with 'mask', and the FireWire system software fills in the masked out bits. This change will apply immediately to a non-running DCL program. An update must be run on the DCL for changes to take effect in a running program. Applies: NuDCLSendPacketRef @param dcl The DCL to modify @param headerPtr A pointer to a two-quadlet header. See section 9.6 of the the OHCI specification. @param mask A pointer to a two-quadlet mask. The quadlets in headerPtr are masked with 'mask' and the masked-out bits are replaced by the FireWire system software. @result Returns an IOReturn error code.*/ IOReturn (*SetDCLUserHeaderPtr)( NuDCLRef dcl, UInt32 * headerPtr, UInt32 * mask ) ; /*! Description forthcoming */ UInt32 * (*GetDCLUserHeaderPtr)( NuDCLRef dcl ) ; /*! Description forthcoming */ UInt32 * (*GetUserHeaderMaskPtr)( NuDCLRef dcl ) ; /*! Description forthcoming */ void (*SetDCLRefcon)( NuDCLRef dcl, void* refcon ) ; /*! Description forthcoming */ void* (*GetDCLRefcon)( NuDCLRef dcl ) ; /*! Description forthcoming */ IOReturn (*AppendDCLUpdateList)( NuDCLRef dcl, NuDCLRef updateDCL ) ; // consumes a reference on dclList.. /*! Description forthcoming */ IOReturn (*SetDCLUpdateList)( NuDCLRef dcl, CFSetRef dclList ) ; /*! Description forthcoming */ CFSetRef (*CopyDCLUpdateList)( NuDCLRef dcl ) ; /*! Description forthcoming */ IOReturn (*RemoveDCLUpdateList)( NuDCLRef dcl ) ; /*! Description forthcoming */ IOReturn (*SetDCLWaitControl)( NuDCLRef dcl, Boolean wait ) ; /*! Description forthcoming */ void (*SetDCLFlags)( NuDCLRef dcl, UInt32 flags ) ; /*! Description forthcoming */ UInt32 (*GetDCLFlags)( NuDCLRef dcl ) ; /*! Description forthcoming */ IOReturn (*SetDCLSkipBranch)( NuDCLRef dcl, NuDCLRef skipCycleDCL ) ; /*! Description forthcoming */ NuDCLRef (*GetDCLSkipBranch)( NuDCLRef dcl ) ; /*! Description forthcoming */ IOReturn (*SetDCLSkipCallback)( NuDCLRef dcl, NuDCLCallback callback ) ; /*! Description forthcoming */ NuDCLCallback (*GetDCLSkipCallback)( NuDCLRef dcl ) ; /*! Description forthcoming */ IOReturn (*SetDCLSkipRefcon)( NuDCLRef dcl, void * refcon ) ; /*! Description forthcoming */ void * (*GetDCLSkipRefcon)( NuDCLRef dcl ) ; /*! Description forthcoming */ IOReturn (*SetDCLSyncBits)( NuDCLRef dcl, UInt8 syncBits ) ; /*! Description forthcoming */ UInt8 (*GetDCLSyncBits)( NuDCLRef dcl ) ; /*! Description forthcoming */ IOReturn (*SetDCLTagBits)( NuDCLRef dcl, UInt8 tagBits ) ; /*! Description forthcoming */ UInt8 (*GetDCLTagBits)( NuDCLRef dcl ) ; } IOFireWireNuDCLPoolInterface ; #pragma mark - #pragma mark ASYNCSTREAM LISTENER INTERFACE // ============================================================ // IOFWAsyncStreamListener Interface // ============================================================ /*! @class @discussion Represents and provides management functions for a asyn stream listener object. */ typedef struct IOFWAsyncStreamListenerInterface_t { IUNKNOWN_C_GUTS ; /*! Interface version. */ UInt16 version; /*! Interface revision. */ UInt16 revision; /*! @function SetListenerHandler @abstract Set the callback that should be called to handle incoming async stream packets @param self The async stream interface to use. @param inReceiver The callback to set. @result Returns the callback that was previously set or nil for none.*/ const IOFWAsyncStreamListenerHandler (*SetListenerHandler)( IOFWAsyncStreamListenerInterfaceRef self, IOFWAsyncStreamListenerHandler inReceiver) ; /*! @function SetSkippedPacketHandler @abstract Set the callback that should be called when incoming packets are dropped by the address space. @param self The address space interface to use. @param inHandler The callback to set. @result Returns the callback that was previously set or nil for none.*/ const IOFWAsyncStreamListenerSkippedPacketHandler (*SetSkippedPacketHandler)( IOFWAsyncStreamListenerInterfaceRef self, IOFWAsyncStreamListenerSkippedPacketHandler inHandler) ; /*! @function NotificationIsOn @abstract Is notification on? @param self The async stream interface to use. @result Returns true if packet notifications for this channel are active */ Boolean (*NotificationIsOn)(IOFWAsyncStreamListenerInterfaceRef self) ; /*! @function TurnOnNotification @abstract Try to turn on packet notifications for this channel. @param self The async stream interface to use. @result Returns true upon success */ Boolean (*TurnOnNotification)(IOFWAsyncStreamListenerInterfaceRef self) ; /*! @function TurnOffNotification @abstract Force packet notification off. @param self The async stream interface to use. */ void (*TurnOffNotification)(IOFWAsyncStreamListenerInterfaceRef self) ; /*! @function ClientCommandIsComplete @abstract Notify the async stream object that a packet notification handler has completed. @discussion Packet notifications are received one at a time, in order. This function must be called after a packet handler has completed its work. @param self The async stream interface to use. @param commandID The ID of the packet notification being completed. This is the same ID that was passed when a packet notification handler is called. @param status The completion status of the packet handler */ void (*ClientCommandIsComplete)(IOFWAsyncStreamListenerInterfaceRef self, FWClientCommandID commandID, IOReturn status) ; // --- accessors ---------- /*! @function GetRefCon @abstract Returns the user refCon value for this async stream interface. @param self The async stream interface to use. @result returns the callback object.*/ void* (*GetRefCon)(IOFWAsyncStreamListenerInterfaceRef self) ; /*! @function SetFlags @abstract set flags for the listener. @param self The async stream interface to use. @param flags indicate performance metrics. @result none. */ void (*SetFlags)( IOFWAsyncStreamListenerInterfaceRef self, UInt32 flags ); /*! @function GetFlags @abstract get the flags of listener. @param self The async stream interface to use. @result flags. */ UInt32 (*GetFlags)(IOFWAsyncStreamListenerInterfaceRef self); /*! @function GetOverrunCounter @abstract get overrun counter from the DCL program. @param self The async stream interface to use. @result returns the counter value. */ UInt32 (*GetOverrunCounter)(IOFWAsyncStreamListenerInterfaceRef self); } IOFWAsyncStreamListenerInterface ; #endif //__IOFireWireLibIsoch_H__
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/firewire/IOFireWireLib.h
/* * Copyright (c) 1998-2000 Apple Computer, Inc. All rights reserved. * * @APPLE_LICENSE_HEADER_START@ * * The contents of this file constitute Original Code as defined in and * are subject to the Apple Public Source License Version 1.1 (the * "License"). You may not use this file except in compliance with the * License. Please obtain a copy of the License at * http://www.apple.com/publicsource and read it before using this file. * * This Original Code and all software distributed under the License are * distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT. Please see the * License for the specific language governing rights and limitations * under the License. * * @APPLE_LICENSE_HEADER_END@ */ /* * IOFireWireLib.h * IOFireWireLib * * Created on Thu Apr 27 2000. * Copyright (c) 2000-2002 Apple Computer, Inc. All rights reserved. * */ /*! @header IOFireWireLib.h IOFireWireLib is the software used by user space software to communicate with FireWire devices and control the FireWire bus. IOFireWireLib is the lowest-level FireWire interface available in user space. To communicate with a device on the FireWire bus, an instance of IOFireWireDeviceInterface (a struct which is defined below) is created. The methods of IOFireWireDeviceInterface allow you to communicate with the device and create instances of other interfaces which provide extended functionality (for example, creation of unit directories on the local machine). References to interfaces should be kept using the interface reference typedefs defined herein. For example, you should use IOFireWireLibDeviceRef to refer to instances of IOFireWireDeviceInterface, IOFireWireLibCommandRef to refer to instances of IOFireWireCommandInterface, and so on. To obtain an IOFireWireDeviceInterface for a device on the FireWire bus, use the function IOCreatePlugInInterfaceForService() defined in IOKit/IOCFPlugIn.h. (Note the "i" in "PlugIn" is always upper-case.) Quick usage reference:<br> <ul> <li>'service' is a reference to the IOKit registry entry of the kernel object (usually of type IOFireWireDevice) representing the device of interest. This reference can be obtained using the functions defined in IOKit/IOKitLib.h.</li> <li>'plugInType' should be CFUUIDGetUUIDBytes(kIOCFPlugInInterfaceID)</li> <li>'interfaceType' should be CFUUIDGetUUIDBytes(kIOFireWireLibTypeID) when using IOFireWireLib</li> </ul> The interface returned by IOCreatePlugInInterfaceForService() should be deallocated using IODestroyPlugInInterface(). Do not call Release() on it. */ /* $Log: not supported by cvs2svn $ Revision 1.77 2009/10/29 22:28:28 calderon <rdar://7308574> IOFireWireLib.h and IOFireWireLibIsoch.h headerdoc markup patch Revision 1.76 2008/12/12 04:43:57 collin user space compare swap command fixes Revision 1.75 2008/09/12 23:44:05 calderon <rdar://5971979/> PseudoAddressSpace skips/mangles packets <rdar://5708169/> FireWire synchronous commands' headerdoc missing callback info Revision 1.74 2007/11/09 01:39:04 arulchan fix for rdar://5555060 Revision 1.73 2007/10/16 16:50:21 ayanowit Removed existing "work-in-progress" support for buffer-fill isoch. Revision 1.72 2007/06/21 04:08:45 collin *** empty log message *** Revision 1.71 2007/05/12 01:10:45 arulchan Asyncstream transmit command interface Revision 1.70 2007/05/03 01:21:29 arulchan Asyncstream transmit APIs Revision 1.69 2007/04/28 02:54:23 collin *** empty log message *** Revision 1.68 2007/04/28 01:42:35 collin *** empty log message *** Revision 1.67 2007/04/11 03:37:41 collin *** empty log message *** Revision 1.66 2007/04/05 22:32:09 collin *** empty log message *** Revision 1.65 2007/03/23 01:47:17 collin *** empty log message *** Revision 1.64 2007/03/22 00:30:00 collin *** empty log message *** Revision 1.63 2007/03/14 02:29:35 collin *** empty log message *** Revision 1.62 2007/03/06 06:30:05 collin *** empty log message *** Revision 1.61 2007/03/06 04:50:21 collin *** empty log message *** Revision 1.60 2007/03/03 05:52:20 collin *** empty log message *** Revision 1.59 2007/03/03 04:47:15 collin *** empty log message *** Revision 1.58 2007/02/16 19:09:15 arulchan *** empty log message *** Revision 1.57 2007/02/16 17:41:00 ayanowit More Leopard changes. Revision 1.56 2007/02/15 22:02:38 ayanowit More fixes for new IRMAllocation stuff. Revision 1.55 2007/02/14 22:43:34 collin *** empty log message *** Revision 1.54 2007/02/10 02:40:58 collin *** empty log message *** Revision 1.53 2007/02/09 20:36:46 ayanowit More Leopard IRMAllocation changes. Revision 1.52 2007/01/17 23:22:40 collin *** empty log message *** Revision 1.51 2007/01/17 03:46:27 collin *** empty log message *** Revision 1.50 2007/01/11 04:34:18 collin *** empty log message *** Revision 1.49 2007/01/04 04:07:25 collin *** empty log message *** Revision 1.48 2006/12/22 05:15:13 collin *** empty log message *** Revision 1.47 2006/12/22 03:50:40 collin *** empty log message *** Revision 1.46 2006/12/06 00:01:10 arulchan Isoch Channel 31 Generic Receiver Revision 1.45 2006/10/26 00:39:16 calderon Changed headerdoc to specify release() need on GetConfigDirectory Revision 1.44 2006/09/28 23:50:05 collin *** empty log message *** Revision 1.43 2006/09/28 22:47:06 ayanowit Another tweak to new APIs. Revision 1.42 2006/09/28 22:31:31 arulchan New Feature rdar::3413505 Revision 1.41 2006/09/27 22:42:12 ayanowit Merged in Leopard changes for new IRMAllocation API. Revision 1.40 2006/09/22 06:45:19 collin *** empty log message *** Revision 1.39 2004/06/10 20:57:37 niels *** empty log message *** Revision 1.38 2004/05/04 22:52:20 niels *** empty log message *** Revision 1.37 2004/04/19 21:51:49 niels Revision 1.36 2004/03/25 00:00:24 niels fix panic allocating large physical address spaces Revision 1.35 2004/02/27 21:02:20 calderon Changed headerdoc abstract of function "GetSpeedBetweenNodes" from "Get maximum transfer speed to device to which this interface is attached." to "Get the maximum transfer speed between nodes 'srcNodeID' and 'destNodeID'." Revision 1.34 2003/11/20 19:14:08 niels Revision 1.33 2003/11/07 21:24:28 niels Revision 1.32 2003/11/07 21:01:19 niels Revision 1.31 2003/09/10 23:01:48 collin Revision 1.30 2003/09/06 01:37:24 collin Revision 1.29 2003/08/25 08:39:17 niels Revision 1.28 2003/08/08 21:03:47 gecko1 Merge max-rec clipping code into TOT Revision 1.27 2003/07/21 06:53:10 niels merge isoch to TOT Revision 1.26.14.2 2003/07/18 00:17:47 niels Revision 1.26.14.1 2003/07/01 20:54:23 niels isoch merge Revision 1.26 2002/11/06 23:44:21 wgulland Update header doc for CreateLocalIsochPort Revision 1.25 2002/09/25 00:27:33 niels flip your world upside-down Revision 1.24 2002/09/12 22:41:55 niels add GetIRMNodeID() to user client */ #ifndef __IOFireWireLib_H__ #define __IOFireWireLib_H__ #ifndef KERNEL #include <CoreFoundation/CoreFoundation.h> #include <IOKit/IOCFPlugIn.h> #include <IOKit/firewire/IOFireWireFamilyCommon.h> // ============================================================ // plugin loading // ============================================================ #pragma mark IOFIREWIRELIB TYPE UUID // uuid string: CDCFCA94-F197-11D4-87E6-000502072F80 #define kIOFireWireLibTypeID CFUUIDGetConstantUUIDWithBytes(kCFAllocatorDefault,\ 0xCD, 0xCF, 0xCA, 0x94, 0xF1, 0x97, 0x11, 0xD4,\ 0x87, 0xE6, 0x00, 0x05, 0x02, 0x07, 0x2F, 0x80) #pragma mark - #pragma mark DEVICE/UNIT/NUB INTERFACE UUIDs // ============================================================ // device/unit/nub interfaces (newest first) // ============================================================ // // version 9 // 10.5 Leopard // // kIOFireWireDeviceInterface_v9 // uuid: EE0A94D7-29B4-4D76-A857-57CA477C73B1 #define kIOFireWireDeviceInterfaceID_v9 CFUUIDGetConstantUUIDWithBytes( kCFAllocatorDefault,\ 0xEE, 0x0A, 0x94, 0xD7, 0x29, 0xB4, 0x4D, 0x76, \ 0xA8, 0x57, 0x57, 0xCA, 0x47, 0x7C, 0x73, 0xB1 ) // // version 8 // // kIOFireWireDeviceInterface_v8 // uuid: 22A258BB-A859-11D8-AA56-000A95992A78 #define kIOFireWireDeviceInterfaceID_v8 CFUUIDGetConstantUUIDWithBytes( kCFAllocatorDefault,\ 0x22, 0xA2, 0x58, 0xBB, 0xA8, 0x59, 0x11, 0xD8, \ 0xAA, 0x56, 0x00, 0x0A, 0x95, 0x99, 0x2A, 0x78 ) // // version 7 // // kIOFireWireDeviceInterface_v7 // uuid: 188517DE-10B4-11D8-B5CC-000393CFACEA #define kIOFireWireDeviceInterfaceID_v7 CFUUIDGetConstantUUIDWithBytes( kCFAllocatorDefault,\ 0x18, 0x85, 0x17, 0xDE, 0x10, 0xB4, 0x11, 0xD8,\ 0xB5, 0xCC, 0x00, 0x03, 0x93, 0xCF, 0xAC, 0xEA ) // // version 6 (obsolete) // // kIOFireWireDeviceInterface_v6 // uuid: C2AB2F11-45E2-11D7-815C-000393470256 #define kIOFireWireDeviceInterfaceID_v6 CFUUIDGetConstantUUIDWithBytes( kCFAllocatorDefault,\ 0xC2, 0xAB, 0x2F, 0x11, 0x45, 0xE2, 0x11, 0xD7,\ 0x81, 0x5C, 0x00, 0x03, 0x93, 0x47, 0x02, 0x56 ) // // version 5 interfaces (obsolete) // // // kIOFireWireNubInterface_v5 // uuid string: D4900C5A-C69E-11D6-AEA5-0003938BEB0A #define kIOFireWireNubInterfaceID_v5 CFUUIDGetConstantUUIDWithBytes( kCFAllocatorDefault,\ 0xD4, 0x90, 0x0C, 0x5A, 0xC6, 0x9E, 0x11, 0xD6,\ 0xAE, 0xA5, 0x00, 0x03, 0x93, 0x8B, 0xEB, 0x0A ) // kIOFireWireUnitInterfaceID_v5 // uuid string: 121D7347-C69F-11D6-9B31-0003938BEB0A #define kIOFireWireUnitInterfaceID_v5 CFUUIDGetConstantUUIDWithBytes( kCFAllocatorDefault,\ 0x12, 0x1D, 0x73, 0x47, 0xC6, 0x9F, 0x11, 0xD6,\ 0x9B, 0x31, 0x00, 0x03, 0x93, 0x8B, 0xEB, 0x0A ) // kIOFireWireDeviceInterfaceID_v5 // uuid string: 127A12F6-C69F-11D6-9D11-0003938BEB0A #define kIOFireWireDeviceInterfaceID_v5 CFUUIDGetConstantUUIDWithBytes( kCFAllocatorDefault,\ 0x12, 0x7A, 0x12, 0xF6, 0xC6, 0x9F, 0x11, 0xD6,\ 0x9D, 0x11, 0x00, 0x03, 0x93, 0x8B, 0xEB, 0x0A ) // // version 4 interfaces (obsolete) // // availability: // Mac OS X 10.2 "Jaguar" and later // // kIOFireWireNubInterface_v4 // uuid string: 939151B8-6945-11D6-BEC7-0003933F84F0 #define kIOFireWireNubInterfaceID_v4 CFUUIDGetConstantUUIDWithBytes( kCFAllocatorDefault,\ 0x93, 0x91, 0x51, 0xB8, 0x69, 0x45, 0x11, 0xD6,\ 0xBE, 0xC7, 0x00, 0x03, 0x93, 0x3F, 0x84, 0xF0 ) // kIOFireWireUnitInterface_v4 // uuid string: D1A395C9-6945-11D6-9B32-0003933F84F0 #define kIOFireWireUnitInterfaceID_v4 CFUUIDGetConstantUUIDWithBytes( kCFAllocatorDefault,\ 0xD1, 0xA3, 0x95, 0xC9, 0x69, 0x45, 0x11, 0xD6,\ 0x9B, 0x32, 0x00, 0x03, 0x93, 0x3F, 0x84, 0xF0 ) // kIOFireWireDeviceInterface_v4 // uuid string: F4B3748B-6945-11D6-8299-0003933F84F0 #define kIOFireWireDeviceInterfaceID_v4 CFUUIDGetConstantUUIDWithBytes( kCFAllocatorDefault,\ 0xF4, 0xB3, 0x74, 0x8B, 0x69, 0x45, 0x11, 0xD6,\ 0x82, 0x99, 0x00, 0x03, 0x93, 0x3F, 0x84, 0xF0 ) // // version 3 interfaces (obsolete) // // availability: // Mac OS X 10.2 "Jaguar" and later // // kIOFireWireNubInterfaceID_v3 // uuid string: F70FE149-E393-11D5-958A-0003933F84F0 #define kIOFireWireNubInterfaceID_v3 CFUUIDGetConstantUUIDWithBytes( kCFAllocatorDefault,\ 0xF7, 0x0F, 0xE1, 0x49, 0xE3, 0x93, 0x11, 0xD5,\ 0x95, 0x8A, 0x00, 0x03, 0x93, 0x3F, 0x84, 0xF0 ) // kIOFireWireUnitInterfaceID_v3 // uuid string: FE7A02EB-E393-11D5-8A61-0003933F84F0 #define kIOFireWireUnitInterfaceID_v3 CFUUIDGetConstantUUIDWithBytes( kCFAllocatorDefault,\ 0xFE, 0x7A, 0x02, 0xEB, 0xE3, 0x93, 0x11, 0xD5,\ 0x8A, 0x61, 0x00, 0x03, 0x93, 0x3F, 0x84, 0xF0 ) // kIOFireWireDeviceInterfaceID_v3 // uuid string: 00EB71A0-E394-11D5-829A-0003933F84F0 #define kIOFireWireDeviceInterfaceID_v3 CFUUIDGetConstantUUIDWithBytes(kCFAllocatorDefault,\ 0x00, 0xEB, 0x71, 0xA0, 0xE3, 0x94, 0x11, 0xD5,\ 0x82, 0x9A, 0x00, 0x03, 0x93, 0x3F, 0x84, 0xF0 ) // // version 2 interfaces (obsolete) // // availability: // Mac OS X 10.1 and later // // kIOFireWireNubInterfaceID // uuid string: 2575E4C4-B6C1-11D5-8F73-003065AF75CC #define kIOFireWireNubInterfaceID CFUUIDGetConstantUUIDWithBytes( kCFAllocatorDefault,\ 0x25, 0x75, 0xE4, 0xC4, 0xB6, 0xC1, 0x11, 0xD5,\ 0x8F, 0x73, 0x00, 0x30, 0x65, 0xAF, 0x75, 0xCC ) // kIOFireWireUnitInterfaceID // uuid string: A02CC5D4-B6C1-11D5-AEA8-003065AF75CC #define kIOFireWireUnitInterfaceID CFUUIDGetConstantUUIDWithBytes( kCFAllocatorDefault,\ 0xA0, 0x2C, 0xC5, 0xD4, 0xB6, 0xC1, 0x11, 0xD5,\ 0xAE, 0xA8, 0x00, 0x30, 0x65, 0xAF, 0x75, 0xCC ) // kIOFireWireDeviceInterfaceID_v2 // uuid string: B3993EB8-56E2-11D5-8BD0-003065423456 #define kIOFireWireDeviceInterfaceID_v2 CFUUIDGetConstantUUIDWithBytes(kCFAllocatorDefault,\ 0xB3, 0x99, 0x3E, 0xB8, 0x56, 0xE2, 0x11, 0xD5,\ 0x8B, 0xD0, 0x00, 0x30, 0x65, 0x42, 0x34, 0x56) // // version 1 interfaces (obsolete) // // availablity: // Mac OS X 10.0.0 and later // // kIOFireWireDeviceInterfaceID // (obsolete: do not use. may be removed in the future.) // uuid string: E3DF4460-F197-11D4-8AC8-000502072F80 #define kIOFireWireDeviceInterfaceID CFUUIDGetConstantUUIDWithBytes(kCFAllocatorDefault,\ 0xE3, 0xDF, 0x44, 0x60, 0xF1, 0x97, 0x11, 0xD4,\ 0x8A, 0xC8, 0x00, 0x05, 0x02, 0x07, 0x2F, 0x80) #pragma mark - #pragma mark COMMAND OBJECT UUIDs // ============================================================ // command objects // ============================================================ // version 3 interfaces: // // availability: // Mac OS X "Leopard" and later // // uuid string : 18B932AA-697A-4C7E-8F22-80EE746773A9 #define kIOFireWireAsyncStreamCommandInterfaceID CFUUIDGetConstantUUIDWithBytes(kCFAllocatorDefault, \ 0x18, 0xB9, 0x32, 0xAA, 0x69, 0x7A, 0x4C, 0x7E, \ 0x8F, 0x22, 0x80, 0xEE, 0x74, 0x67, 0x73, 0xA9 ) // uuid string : F3FF3AC6-FE88-47A0-ACB7-509009808128 #define kIOFireWirePHYCommandInterfaceID CFUUIDGetConstantUUIDWithBytes(kCFAllocatorDefault,\ 0xF3, 0xFF, 0x3A, 0xC6, 0xFE, 0x88, 0x47, 0xA0, \ 0xAC, 0xB7, 0x50, 0x90, 0x09, 0x80, 0x81, 0x28 ) // uuid string : FAF5529D-9F99-42CB-B0E8-67860807F551 #define kIOFireWireVectorCommandInterfaceID CFUUIDGetConstantUUIDWithBytes(kCFAllocatorDefault,\ 0xFA, 0xF5, 0x52, 0x9D, 0x9F, 0x99, 0x42, 0xCB,\ 0xB0, 0xE8, 0x67, 0x86, 0x08, 0x07, 0xF5, 51) // uuid: 12DE8E37-0BE4-4094-882F-FD0B932A3174 #define kIOFireWireIRMAllocationInterfaceID CFUUIDGetConstantUUIDWithBytes( kCFAllocatorDefault,\ 0x12, 0xDE, 0x8E, 0x37, 0x0B, 0xE4, 0x40, 0x94, \ 0x88, 0x2F, 0xFD, 0x0B, 0x93, 0x2A, 0x31, 0x74 ) // uuid string: 577B1AFE-1A48-4137-8993-71077820E0CD #define kIOFireWireCommandInterfaceID_v3 CFUUIDGetConstantUUIDWithBytes(kCFAllocatorDefault,\ 0x57, 0x7B, 0x1A, 0xFE, 0x1A, 0x48, 0x41, 0x37,\ 0x89, 0x93, 0x71, 0x07, 0x78, 0x20, 0xE0, CD ) // uuid string: 30FB7D2A-FF2E-4236-871B-2A473B0B7B3B #define kIOFireWireReadCommandInterfaceID_v3 CFUUIDGetConstantUUIDWithBytes(kCFAllocatorDefault,\ 0x30, 0xFB, 0x7D, 0x2A, 0xFF, 0x2E, 0x42, 0x36,\ 0x87, 0x1B, 0x2A, 0x47, 0x3B, 0x0B, 0x7B, 0x3B ) // uuid string: EF55343D-40A4-4007-BF99-DF1413251309 #define kIOFireWireWriteCommandInterfaceID_v3 CFUUIDGetConstantUUIDWithBytes(kCFAllocatorDefault,\ 0xEF, 0x55, 0x34, 0x3D, 0x40, 0xA4, 0x40, 0x07,\ 0xBF, 0x99, 0xDF, 0x14, 0x13, 0x25, 0x13, 0x09 ) // uuid string: 037F5D98-F5F9-4FBF-9267-4B9BFE9642D6 #define kIOFireWireCompareSwapCommandInterfaceID_v3 CFUUIDGetConstantUUIDWithBytes(kCFAllocatorDefault,\ 0x03, 0x7F, 0x5D, 0x98, 0xF5, 0xF9, 0x4F, 0xBF,\ 0x92, 0x67, 0x4B, 0x9B, 0xFE, 0x96, 0x42, 0xD6 ) // // version 2 interfaces: // // availability: // Mac OS X "Jaguar" and later // // kIOFireWireCompareSwapCommandInterfaceID_v2 // uuid string: 6100FEC9-6946-11D6-8A49-0003933F84F0 #define kIOFireWireCompareSwapCommandInterfaceID_v2 CFUUIDGetConstantUUIDWithBytes(kCFAllocatorDefault,\ 0x61, 0x00, 0xFE, 0xC9, 0x69, 0x46, 0x11, 0xD6,\ 0x8A, 0x49, 0x00, 0x03, 0x93, 0x3F, 0x84, 0xF0 ) // // version 1 interfaces (obsolete) // // uuid string: F8B6993A-F197-11D4-A3F1-000502072F80 #define kIOFireWireCommandInterfaceID CFUUIDGetConstantUUIDWithBytes(kCFAllocatorDefault,\ 0xF8, 0xB6, 0x99, 0x3A, 0xF1, 0x97, 0x11, 0xD4,\ 0xA3, 0xF1, 0x00, 0x05, 0x02, 0x07, 0x2F, 0x80) // uuid string: AB26F124-76E9-11D5-86D5-003065423456 #define kIOFireWireReadCommandInterfaceID_v2 CFUUIDGetConstantUUIDWithBytes(kCFAllocatorDefault,\ 0xAB, 0x26, 0xF1, 0x24, 0x76, 0xE9, 0x11, 0xD5,\ 0x86, 0xD5, 0x00, 0x30, 0x65, 0x42, 0x34, 0x56) // uuid string: 1023605C-76EA-11D5-B82A-003065423456 #define kIOFireWireWriteCommandInterfaceID_v2 CFUUIDGetConstantUUIDWithBytes(kCFAllocatorDefault,\ 0x10, 0x23, 0x60, 0x5C, 0x76, 0xEA, 0x11, 0xD5,\ 0xB8, 0x2A, 0x00, 0x30, 0x65, 0x42, 0x34, 0x56) // uuid string: 70C10E38-F64A-11D4-AFE7-0050E4D93B36 #define kIOFireWireCompareSwapCommandInterfaceID CFUUIDGetConstantUUIDWithBytes(kCFAllocatorDefault,\ 0x70, 0xC1, 0x0E, 0x38, 0xF6, 0x4A, 0x11, 0xD4,\ 0xAF, 0xE7, 0x00, 0x50, 0xE4, 0xD9, 0x3B, 0x36) // obsolete: do not use. may be removed in the future. // uuid string: 3D72672A-F64A-11D4-9683-0050E4D93B36 #define kIOFireWireReadQuadletCommandInterfaceID CFUUIDGetConstantUUIDWithBytes(kCFAllocatorDefault,\ 0x3D, 0x72, 0x67, 0x2A, 0xF6, 0x4A, 0x11, 0xD4,\ 0x96, 0x83, 0x00, 0x50, 0xE4, 0xD9, 0x3B, 0x36) // obsolete: do not use. may be removed in the future. // uuid string: 5C9423CE-F64A-11D4-AB7B-0050E4D93B36 #define kIOFireWireWriteQuadletCommandInterfaceID CFUUIDGetConstantUUIDWithBytes(kCFAllocatorDefault,\ 0x5C, 0x94, 0x23, 0xCE, 0xF6, 0x4A, 0x11, 0xD4,\ 0xAB, 0x7B, 0x00, 0x50, 0xE4, 0xD9, 0x3B, 0x3) // obsolete: do not use. may be removed in the future. // uuid string: 6E32F9D4-F63A-11D4-A194-003065423456 #define kIOFireWireReadCommandInterfaceID CFUUIDGetConstantUUIDWithBytes(kCFAllocatorDefault,\ 0x6E, 0x32, 0xF9, 0xD4, 0xF6, 0x3A, 0x11, 0xD4,\ 0xA1, 0x94, 0x00, 0x30, 0x65, 0x42, 0x34, 0x56) // obsolete: do not use. may be removed in the future. // uuid string: 4EDDED10-F64A-11D4-B7A5-0050E4D93B36 #define kIOFireWireWriteCommandInterfaceID CFUUIDGetConstantUUIDWithBytes(kCFAllocatorDefault,\ 0x4E, 0xDD, 0xED, 0x10, 0xF6, 0x4A, 0x11, 0xD4,\ 0xB7, 0xA5, 0x00, 0x50, 0xE4, 0xD9, 0x3B, 0x36) #pragma mark - #pragma mark ADDRESS SPACE UUIDs // ============================================================ // address spaces // ============================================================ // uuid string: 0D32AC50-F198-11D4-8DB5-000502072F80 #define kIOFireWirePseudoAddressSpaceInterfaceID CFUUIDGetConstantUUIDWithBytes(kCFAllocatorDefault,\ 0x0D, 0x32, 0xAC, 0x50, 0xF1, 0x98, 0x11, 0xD4,\ 0x8D, 0xB5, 0x00, 0x05, 0x02, 0x07, 0x2F, 0x80) // uuid string: 489110F6-F198-11D4-8BEB-000502072F80 #define kIOFireWirePhysicalAddressSpaceInterfaceID CFUUIDGetConstantUUIDWithBytes(kCFAllocatorDefault,\ 0x48, 0x91, 0x10, 0xF6, 0xF1, 0x98, 0x11, 0xD4,\ 0x8B, 0xEB, 0x00, 0x05, 0x02, 0x07, 0x2F, 0x80) // uuid string: 763F18CA-5E84-4612-A2BD-10011730E131 #define kIOFireWirePHYPacketListenerInterfaceID CFUUIDGetConstantUUIDWithBytes(kCFAllocatorDefault,\ 0x76, 0x3F, 0x18, 0xCA, 0x5E, 0x84, 0x46, 0x12,\ 0xA2, 0xBD, 0x10, 0x01, 0x17, 0x30, 0xE1, 0x31) #pragma mark - #pragma mark CONFIG ROM UUIDs // ============================================================ // config ROM // ============================================================ // uuid string: 69CA4D74-F198-11D4-B325-000502072F80 #define kIOFireWireLocalUnitDirectoryInterfaceID CFUUIDGetConstantUUIDWithBytes(kCFAllocatorDefault,\ 0x69, 0xCA, 0x4D, 0x74, 0xF1, 0x98, 0x11, 0xD4,\ 0xB3, 0x25, 0x00, 0x05, 0x02, 0x07, 0x2F, 0x80) // uuid string: 7D43B506-F198-11D4-AA10-000502072F80 #define kIOFireWireConfigDirectoryInterfaceID CFUUIDGetConstantUUIDWithBytes(kCFAllocatorDefault,\ 0x7D, 0x43, 0xB5, 0x06, 0xF1, 0x98, 0x11, 0xD4,\ 0xAA, 0x10, 0x00, 0x05, 0x02, 0x07, 0x2F, 0x80) #pragma mark - #pragma mark INTERFACE TYPES // ============================================================ // IOFireWireLib interface types // ============================================================ typedef struct IOFireWireDeviceInterface_t** IOFireWireLibDeviceRef ; typedef IOFireWireLibDeviceRef IOFireWireLibUnitRef ; typedef IOFireWireLibDeviceRef IOFireWireLibNubRef ; typedef struct IOFireWirePseudoAddressSpaceInterface_t** IOFireWireLibPseudoAddressSpaceRef ; typedef struct IOFireWirePhysicalAddressSpaceInterface_t** IOFireWireLibPhysicalAddressSpaceRef ; typedef struct IOFireWireLocalUnitDirectoryInterface_t** IOFireWireLibLocalUnitDirectoryRef ; typedef struct IOFireWireConfigDirectoryInterface_t** IOFireWireLibConfigDirectoryRef ; typedef struct IOFireWireCommandInterface_t** IOFireWireLibCommandRef ; typedef struct IOFireWireReadCommandInterface_t** IOFireWireLibReadCommandRef ; typedef struct IOFireWireReadQuadletCommandInterface_t** IOFireWireLibReadQuadletCommandRef ; typedef struct IOFireWireWriteCommandInterface_t** IOFireWireLibWriteCommandRef ; typedef struct IOFireWireWriteQuadletCommandInterface_t** IOFireWireLibWriteQuadletCommandRef ; typedef struct IOFireWireCompareSwapCommandInterface_t** IOFireWireLibCompareSwapCommandRef ; typedef struct IOFireWireLibVectorCommandInterface_t** IOFireWireLibVectorCommandRef; typedef struct IOFireWirePHYCommandInterface_t** IOFireWireLibPHYCommandRef; typedef struct IOFireWireAsyncStreamCommandInterface_t** IOFireWireLibAsyncStreamCommandRef; typedef struct IOFireWireCompareSwapCommandInterface_v3_t** IOFireWireLibCompareSwapCommandV3Ref ; typedef struct IOFireWireLibIRMAllocationInterface_t** IOFireWireLibIRMAllocationRef ; // --- isoch interfaces ---------- typedef struct IOFireWireIsochChannelInterface_t** IOFireWireLibIsochChannelRef ; typedef struct IOFireWireIsochPortInterface_t** IOFireWireLibIsochPortRef ; typedef struct IOFireWireRemoteIsochPortInterface_t** IOFireWireLibRemoteIsochPortRef ; typedef struct IOFireWireLocalIsochPortInterface_t** IOFireWireLibLocalIsochPortRef ; typedef struct IOFireWireDCLCommandPoolInterface_t** IOFireWireLibDCLCommandPoolRef ; typedef struct IOFireWireNuDCLPoolInterface_t** IOFireWireLibNuDCLPoolRef ; typedef struct IOFWAsyncStreamListenerInterface_t** IOFWAsyncStreamListenerInterfaceRef; typedef struct IOFireWireLibPHYPacketListenerInterface_t** IOFireWireLibPHYPacketListenerRef; #pragma mark - #pragma mark CALLBACK TYPES // ============================================================ // IOFireWireLib callback types // ============================================================ /*! @typedef IOFireWirePseudoAddressSpaceReadHandler @abstract This callback is called to handle read requests to pseudo address spaces. This function should fill in the specified area in the pseudo address space backing store and call ClientCommandIsComplete with the specified command ID @param addressSpace The address space to which the request is being made @param commandID An FWClientCommandID which should be passed to ClientCommandIsComplete when the buffer has been filled in @param packetLen number of bytes requested @param packetOffset number of bytes from beginning of address space backing store @param srcNodeID nodeID of the requester @param destAddressHi high 16 bits of destination address on this computer @param destAddressLo low 32 bits of destination address on this computer @param refCon user specified reference number passed in when the address space was created */ typedef UInt32 (*IOFireWirePseudoAddressSpaceReadHandler)( IOFireWireLibPseudoAddressSpaceRef addressSpace, FWClientCommandID commandID, UInt32 packetLen, UInt32 packetOffset, UInt16 srcNodeID, // nodeID of requester UInt32 destAddressHi, // destination on this node UInt32 destAddressLo, void * refCon) ; /*! @typedef IOFireWirePseudoAddressSpaceSkippedPacketHandler @abstract Callback called when incoming packets have been dropped from the internal queue @param addressSpace The address space which dropped the packet(s) @param commandID An FWClientCommandID to be passed to ClientCommandIsComplete() @param skippedPacketCount The number of skipped packets */ typedef void (*IOFireWirePseudoAddressSpaceSkippedPacketHandler)( IOFireWireLibPseudoAddressSpaceRef addressSpace, FWClientCommandID commandID, UInt32 skippedPacketCount) ; /*! @typedef IOFireWirePseudoAddressSpaceWriteHandler @abstract Callback called to handle write requests to a pseudo address space. @param addressSpace The address space to which the write is being made @param commandID An FWClientCommandID to be passed to ClientCommandIsComplete() @param packetLen Length in bytes of incoming packet @param packet Pointer to the received data @param srcNodeID Node ID of the sender @param destAddressHi high 16 bits of destination address on this computer @param destAddressLo low 32 bits of destination address on this computer @param refCon user specified reference number passed in when the address space was created */ typedef UInt32 (*IOFireWirePseudoAddressSpaceWriteHandler)( IOFireWireLibPseudoAddressSpaceRef addressSpace, FWClientCommandID commandID, UInt32 packetLen, void* packet, UInt16 srcNodeID, // nodeID of sender UInt32 destAddressHi, // destination on this node UInt32 destAddressLo, void * refCon) ; /*! @typedef IOFireWireBusResetHandler @abstract Called when a bus reset has occured, but before FireWire has completed configuring the bus. @param interface A reference to the device on which the callback was installed @param commandID An FWClientCommandID to be passed to ClientCommandIsComplete() */ typedef void (*IOFireWireBusResetHandler)( IOFireWireLibDeviceRef interface, FWClientCommandID commandID ); // parameters may change /*! @typedef IOFireWireBusResetDoneHandler @abstract Called when a bus reset has occured and FireWire has completed configuring the bus. @param interface A reference to the device on which the callback was installed @param commandID An FWClientCommandID to be passed to ClientCommandIsComplete() */ typedef void (*IOFireWireBusResetDoneHandler)( IOFireWireLibDeviceRef interface, FWClientCommandID commandID ) ; // parameters may change /*! @typedef IOFireWireLibCommandCallback @abstract Callback called when an asynchronous command has completed executing @param refCon A user specified reference value set before command object was submitted */ typedef void (*IOFireWireLibCommandCallback)( void* refCon, IOReturn completionStatus) ; /*! @typedef IOFireWireLibPHYPacketCallback @abstract Callback called to handle incoming PHY packets @param listener The listener which received the callback @param commandID An FWClientCommandID to be passed to ClientCommandIsComplete() @param data1 first quad of received PHY packet @param data2 second quad of received PHY packet @param refCon user specified reference value specified on the listener */ typedef void (*IOFireWireLibPHYPacketCallback)( IOFireWireLibPHYPacketListenerRef listener, FWClientCommandID commandID, UInt32 data1, UInt32 data2, void * refCon ); /*! @typedef IOFireWireLibPHYPacketSkippedCallback @abstract Callback called when incoming packets have been dropped from the internal queue @param listener The listener which dropped the packets @param commandID An FWClientCommandID to be passed to ClientCommandIsComplete() @param skippedPacketCount The number of skipped packets @param refCon user specified reference value specified on the listener */ typedef void (*IOFireWireLibPHYPacketSkippedCallback)( IOFireWireLibPHYPacketListenerRef listener, FWClientCommandID commandID, UInt32 skippedPacketCount, void * refCon ); /*! @typedef IOFireWireLibIRMAllocationLostNotificationProc @abstract Callback called when an IOFireWireLibIRMAllocationRef fails to reclaim IRM resources after a bus-reset */ typedef void (*IOFireWireLibIRMAllocationLostNotificationProc)(IOFireWireLibIRMAllocationRef irmAllocation, void *refCon); /*! @typedef IOFWAsyncStreamListenerHandler @abstract Callback called to handle Async Stream packets. @param listener The listener which received the callback @param commandID An FWClientCommandID to be passed to ClientCommandIsComplete() @param packet Pointer to the received data @param refCon user specified reference number passed in when async stream interface is created */ typedef UInt32 (*IOFWAsyncStreamListenerHandler)( IOFWAsyncStreamListenerInterfaceRef listener, FWClientCommandID commandID, UInt32 size, void* packet, void* refCon) ; /*! @typedef IOFWAsyncStreamListenerSkippedPacketHandler @abstract Callback called when incoming packets have been dropped from the internal queue @param listener The listener which dropped the packets @param commandID An FWClientCommandID to be passed to ClientCommandIsComplete() @param skippedPacketCount The number of skipped packets */ typedef void (*IOFWAsyncStreamListenerSkippedPacketHandler)( IOFWAsyncStreamListenerInterfaceRef listener, FWClientCommandID commandID, UInt32 skippedPacketCount) ; #pragma mark - #pragma mark DEVICE INTERFACE // ============================================================ // IOFireWireDeviceInterface // ============================================================ /*! @class @abstract IOFireWireDeviceInterface is your primary gateway to the functionality contained in IOFireWireLib. @discussion You can use IOFireWireDeviceInterface to:<br> <ul> <li>perform synchronous read, write and lock operations</li> <li>perform other miscellanous bus operations, such as reset the FireWire bus. </li> <li>create FireWire command objects and interfaces used to perform synchronous/asynchronous read, write and lock operations. These include:</li> <ul type="square"> <li>IOFireWireReadCommandInterface <li>IOFireWireReadQuadletCommandInterface <li>IOFireWireWriteCommandInterface <li>IOFireWireWriteQuadletCommandInterface <li>IOFireWireCompareSwapCommandInterface </ul> <li>create interfaces which provide a other extended services. These include:</li> <ul type="square"> <li>IOFireWirePseudoAddressSpaceInterface -- pseudo address space services</li> <li>IOFireWirePhysicalAddressSpaceInterface -- physical address space services</li> <li>IOFireWireLocalUnitDirectoryInterface -- manage local unit directories in the mac</li> <li>IOFireWireConfigDirectoryInterface -- access and browse remote device config directories</li> </ul> <li>create interfaces which provide isochronous services (see IOFireWireLibIsoch.h). These include:</li> <ul type="square"> <li>IOFireWireIsochChannelInterface -- create/manage talker and listener isoch channels</li> <li>IOFireWireLocalIsochPortInterface -- create local isoch ports</li> <li>IOFireWireRemoteIsochPortInterface -- create remote isoch ports</li> <li>IOFireWireDCLCommandPoolInterface -- create a DCL command pool allocator.</li> </ul> </ul> */ typedef struct IOFireWireDeviceInterface_t { IUNKNOWN_C_GUTS ; /*! Interface version */ UInt32 version; /*! Interface revision */ UInt32 revision; // version/revision // --- maintenance methods ------------- /*! @function InterfaceIsInited @abstract Determine whether interface has been properly inited. @param self The device interface to use. @result Returns true if interface is inited and false if is it not. */ Boolean (*InterfaceIsInited)(IOFireWireLibDeviceRef self) ; /*! @function GetDevice @abstract Get the IOKit service to which this interface is connected. @param self The device interface to use. @result Returns an io_object_t corresponding to the device the interface is using */ io_object_t (*GetDevice)(IOFireWireLibDeviceRef self) ; /*! @function Open @abstract Open the connected device for exclusive access. When you have the device open using this method, all accesses by other clients of this device will be denied until Close() is called. @param self The device interface to use. @result An IOReturn error code */ IOReturn (*Open)(IOFireWireLibDeviceRef self) ; /*! @function OpenWithSessionRef @abstract An open function which allows this interface to have access to the device when already opened. The service which has already opened the device must be able to provide an IOFireWireSessionRef. @param self The device interface to use @param sessionRef The sessionRef returned from the client who has the device open @result An IOReturn error code */ IOReturn (*OpenWithSessionRef)(IOFireWireLibDeviceRef self, IOFireWireSessionRef sessionRef) ; /*! @function Close @abstract Release exclusive access to the device @param self The device interface to use */ void (*Close)(IOFireWireLibDeviceRef self) ; // --- notification -------------------- /*! @function NotificationIsOn @abstract Determine whether callback notifications for this interface are currently active @param self The device interface to use @result A Boolean value where true indicates notifications are active */ const Boolean (*NotificationIsOn)(IOFireWireLibDeviceRef self) ; /*! @function AddCallbackDispatcherToRunLoop @abstract Installs the proper run loop event source to allow callbacks to function. This method must be called before callback notifications for this interface or any interfaces created using this interface can function. @param self The device interface to use. @param inRunLoop The run loop on which to install the event source */ const IOReturn (*AddCallbackDispatcherToRunLoop)(IOFireWireLibDeviceRef self, CFRunLoopRef inRunLoop) ; /*! @function RemoveCallbackDispatcherFromRunLoop @abstract Reverses the effects of AddCallbackDispatcherToRunLoop(). This method removes the run loop event source that was added to the specified run loop preventing any future callbacks from being called @param self The device interface to use. */ const void (*RemoveCallbackDispatcherFromRunLoop)(IOFireWireLibDeviceRef self) ; /*! @function TurnOnNotification @abstract Activates any callbacks specified for this device interface. Only works after AddCallbackDispatcherToRunLoop has been called. See also AddIsochCallbackDispatcherToRunLoop(). @param self The device interface to use. @result A Boolean value. Returns true on success. */ const Boolean (*TurnOnNotification)(IOFireWireLibDeviceRef self) ; /*! @function TurnOffNotification @abstract Deactivates and callbacks specified for this device interface. Reverses the effects of TurnOnNotification() @param self The device interface to use. */ void (*TurnOffNotification)(IOFireWireLibDeviceRef self) ; /*! @function SetBusResetHandler @abstract Sets the callback that should be called when a bus reset occurs. Note that this callback can be called multiple times before the bus reset done handler is called. (f.ex., multiple bus resets might occur before bus reconfiguration has completed.) @param self The device interface to use. @param handler Function pointer to the handler to install @result Returns an IOFireWireBusResetHandler function pointer to the previously installed bus reset handler. Returns 0 if none was set. */ const IOFireWireBusResetHandler (*SetBusResetHandler)(IOFireWireLibDeviceRef self, IOFireWireBusResetHandler handler) ; /*! @function SetBusResetDoneHandler @abstract Sets the callback that should be called after a bus reset has occurred and reconfiguration of the bus has been completed. This function will only be called once per bus reset. @param self The device interface to use. @param handler Function pointer to the handler to install @result Returns on IOFireWireBusResetDoneHandler function pointer to the previously installed bus reset handler. Returns 0 if none was set. */ const IOFireWireBusResetDoneHandler (*SetBusResetDoneHandler)(IOFireWireLibDeviceRef self, IOFireWireBusResetDoneHandler handler) ; /*! @function ClientCommandIsComplete @abstract This function must be called from callback routines once they have completed processing a callback. This function only applies to callbacks which take an IOFireWireLibDeviceRef (i.e. bus reset), parameter. @param commandID The command ID passed to the callback function when it was called @param status An IOReturn value indicating the completion status of the callback function */ void (*ClientCommandIsComplete)(IOFireWireLibDeviceRef self, FWClientCommandID commandID, IOReturn status) ; // --- read/write/lock operations ------- /*! @function Read @abstract Perform synchronous block read @param self The device interface to use. @param device The service (representing an attached FireWire device) to read. For 48-bit, device relative addressing, pass the service used to create the device interface. This can be obtained by calling GetDevice(). For 64-bit absolute addressing, pass 0. Other values are unsupported. @param addr Command target address @param buf A pointer to a buffer where the results will be stored @param size Number of bytes to read @param failOnReset Pass true if the command should only be executed during the FireWire bus generation specified in generation. Pass false to ignore the generation parameter. The generation can be obtained by calling GetBusGeneration(). Must be 'true' when using 64-bit addressing. @param generation The FireWire bus generation during which the command should be executed. Ignored if failOnReset is false. Must be a valid generation number when using 64-bit absolute addressing. @result An IOReturn error code */ IOReturn (*Read)(IOFireWireLibDeviceRef self, io_object_t device, const FWAddress* addr, void* buf, UInt32* size, Boolean failOnReset, UInt32 generation) ; /*! @function ReadQuadlet @abstract Perform synchronous quadlet read @param self The device interface to use. @param device The service (representing an attached FireWire device) to read. For 48-bit, device relative addressing, pass the service used to create the device interface. This can be obtained by calling GetDevice(). For 64-bit absolute addressing, pass 0. Other values are unsupported. @param addr Command target address @param val A pointer to where to data should be stored @param failOnReset Pass true if the command should only be executed during the FireWire bus generation specified in generation. Pass false to ignore the generation parameter. The generation can be obtained by calling GetBusGeneration() @param generation The FireWire bus generation during which the command should be executed. Ignored if failOnReset is false. Must be a valid generation number when using 64-bit absolute addressing. @result An IOReturn error code */ IOReturn (*ReadQuadlet)( IOFireWireLibDeviceRef self, io_object_t device, const FWAddress* addr, UInt32* val, Boolean failOnReset, UInt32 generation) ; /*! @function Write @abstract Perform synchronous block write @param self The device interface to use. @param device The service (representing an attached FireWire device) to which to write. For 48-bit, device relative addressing, pass the service used to create the device interface. This can be obtained by calling GetDevice(). For 64-bit absolute addressing, pass 0. Other values are unsupported. @param addr Command target address @param buf A pointer to a buffer where the results will be stored @param size Number of bytes to read @param failOnReset Pass true if the command should only be executed during the FireWire bus generation specified in 'generation'. Pass false to ignore the generation parameter. The generation can be obtained by calling GetBusGeneration(). Must be 'true' when using 64-bit addressing. @param generation The FireWire bus generation during which the command should be executed. Ignored if failOnReset is false. Must be a valid generation number when using 64-bit absolute addressing. @result An IOReturn error code */ IOReturn (*Write)( IOFireWireLibDeviceRef self, io_object_t device, const FWAddress* addr, const void* buf, UInt32* size, Boolean failOnReset, UInt32 generation) ; /*! @function WriteQuadlet @abstract Perform synchronous quadlet write @param self The device interface to use. @param device The service (representing an attached FireWire device) to which to write. For 48-bit, device relative addressing, pass the service used to create the device interface. This can be obtained by calling GetDevice(). For 64-bit absolute addressing, pass 0. Other values are unsupported. @param addr Command target address @param val The value to write @param failOnReset Pass true if the command should only be executed during the FireWire bus generation specified in 'generation'. Pass false to ignore the generation parameter. The generation can be obtained by calling GetBusGeneration(). Must be 'true' when using 64-bit addressing. @param generation The FireWire bus generation during which the command should be executed. Ignored if failOnReset is false. Must be a valid generation number when using 64-bit absolute addressing. @result An IOReturn error code */ IOReturn (*WriteQuadlet)(IOFireWireLibDeviceRef self, io_object_t device, const FWAddress* addr, const UInt32 val, Boolean failOnReset, UInt32 generation) ; /*! @function CompareSwap @abstract Perform synchronous lock operation @param self The device interface to use. @param device The service (representing an attached FireWire device) to which to write. For 48-bit, device relative addressing, pass the service used to create the device interface. This can be obtained by calling GetDevice(). For 64-bit absolute addressing, pass 0. Other values are unsupported. @param addr Command target address @param cmpVal The check/compare value @param newVal Value to set @param failOnReset Pass true if the command should only be executed during the FireWire bus generation specified in 'generation'. Pass false to ignore the generation parameter. The generation can be obtained by calling GetBusGeneration(). Must be 'true' when using 64-bit addressing. @param generation The FireWire bus generation during which the command should be executed. Ignored if failOnReset is false. Must be a valid generation number when using 64-bit absolute addressing. @result An IOReturn error code */ IOReturn (*CompareSwap)(IOFireWireLibDeviceRef self, io_object_t device, const FWAddress* addr, UInt32 cmpVal, UInt32 newVal, Boolean failOnReset, UInt32 generation) ; // --- FireWire command object methods --------- /*! @function CreateReadCommand @abstract Create a block read command object. @param self The device interface to use. @param device The service (representing an attached FireWire device) to which to write. For 48-bit, device relative addressing, pass the service used to create the device interface. This can be obtained by calling GetDevice(). For 64-bit absolute addressing, pass 0. Other values are unsupported. Setting the callback value to nil defaults to synchronous execution. @param addr Command target address @param buf A pointer to a buffer where the results will be stored @param size Number of bytes to read @param callback Command completion callback. Setting the callback value to nil defaults to synchronous execution. @param failOnReset Pass true if the command should only be executed during the FireWire bus generation specified in 'generation'. Pass false to ignore the generation parameter. The generation can be obtained by calling GetBusGeneration(). Must be 'true' when using 64-bit addressing. @param generation The FireWire bus generation during which the command should be executed. Ignored if failOnReset is false. Must be a valid generation number when using 64-bit absolute addressing. @result An IOFireWireLibCommandRef interface. See IOFireWireLibCommandRef. */ IOFireWireLibCommandRef (*CreateReadCommand)( IOFireWireLibDeviceRef self, io_object_t device, const FWAddress * addr, void* buf, UInt32 size, IOFireWireLibCommandCallback callback, Boolean failOnReset, UInt32 generation, void* inRefCon, REFIID iid) ; /*! @function CreateReadQuadletCommand @abstract Create a quadlet read command object. @param self The device interface to use. @param device The service (representing an attached FireWire device) to which to write. For 48-bit, device relative addressing, pass the service used to create the device interface. This can be obtained by calling GetDevice(). For 64-bit absolute addressing, pass 0. Other values are unsupported. Setting the callback value to nil defaults to synchronous execution. @param addr Command target address @param quads An array of quadlets where results should be stored @param numQuads Number of quadlets to read @param callback Command completion callback. Setting the callback value to nil defaults to synchronous execution. @param failOnReset Pass true if the command should only be executed during the FireWire bus generation specified in 'generation'. Pass false to ignore the generation parameter. The generation can be obtained by calling GetBusGeneration(). Must be 'true' when using 64-bit addressing. @param generation The FireWire bus generation during which the command should be executed. Ignored if failOnReset is false. Must be a valid generation number when using 64-bit absolute addressing. @result An IOFireWireLibCommandRef interface. See IOFireWireLibCommandRef.*/ IOFireWireLibCommandRef (*CreateReadQuadletCommand)( IOFireWireLibDeviceRef self, io_object_t device, const FWAddress * addr, UInt32 quads[], UInt32 numQuads, IOFireWireLibCommandCallback callback, Boolean failOnReset, UInt32 generation, void* inRefCon, REFIID iid) ; /*! @function CreateWriteCommand @abstract Create a block write command object. @param self The device interface to use. @param device The service (representing an attached FireWire device) to which to write. For 48-bit, device relative addressing, pass the service used to create the device interface. This can be obtained by calling GetDevice(). For 64-bit absolute addressing, pass 0. Other values are unsupported. Setting the callback value to nil defaults to synchronous execution. @param addr Command target address @param buf A pointer to the buffer containing the data to be written @param size Number of bytes to write @param callback Command completion callback. Setting the callback value to nil defaults to synchronous execution. @param failOnReset Pass true if the command should only be executed during the FireWire bus generation specified in 'generation'. Pass false to ignore the generation parameter. The generation can be obtained by calling GetBusGeneration(). Must be 'true' when using 64-bit addressing. @param generation The FireWire bus generation during which the command should be executed. Ignored if failOnReset is false. Must be a valid generation number when using 64-bit absolute addressing. @result An IOFireWireLibCommandRef interface. See IOFireWireLibCommandRef.*/ IOFireWireLibCommandRef (*CreateWriteCommand)( IOFireWireLibDeviceRef self, io_object_t device, const FWAddress * addr, void* buf, UInt32 size, IOFireWireLibCommandCallback callback, Boolean failOnReset, UInt32 generation, void* inRefCon, REFIID iid) ; /*! @function CreateWriteQuadletCommand @abstract Create a quadlet write command object. @param self The device interface to use. @param device The service (representing an attached FireWire device) to which to write. For 48-bit, device relative addressing, pass the service used to create the device interface. This can be obtained by calling GetDevice(). For 64-bit absolute addressing, pass 0. Other values are unsupported. Setting the callback value to nil defaults to synchronous execution. @param addr Command target address @param quads An array of quadlets containing quadlets to be written @param numQuads Number of quadlets to write @param callback Command completion callback. Setting the callback value to nil defaults to synchronous execution. @param failOnReset Pass true if the command should only be executed during the FireWire bus generation specified in 'generation'. Pass false to ignore the generation parameter. The generation can be obtained by calling GetBusGeneration(). Must be 'true' when using 64-bit addressing. @param generation The FireWire bus generation during which the command should be executed. Ignored if failOnReset is false. Must be a valid generation number when using 64-bit absolute addressing. @result An IOFireWireLibCommandRef interface. See IOFireWireLibCommandRef. */ IOFireWireLibCommandRef (*CreateWriteQuadletCommand)(IOFireWireLibDeviceRef self, io_object_t device, const FWAddress * addr, UInt32 quads[], UInt32 numQuads, IOFireWireLibCommandCallback callback, Boolean failOnReset, UInt32 generation, void* inRefCon, REFIID iid) ; /*! @function CreateCompareSwapCommand @abstract Create a quadlet compare/swap command object. @param self The device interface to use. @param device The service (representing an attached FireWire device) to which to write. For 48-bit, device relative addressing, pass the service used to create the device interface. This can be obtained by calling GetDevice(). For 64-bit absolute addressing, pass 0. Other values are unsupported. Setting the callback value to nil defaults to synchronous execution. @param addr Command target address @param cmpVal 32-bit value expected at target address @param newVal 32-bit value to be set at target address @param callback Command completion callback. Setting the callback value to nil defaults to synchronous execution. @param failOnReset Pass true if the command should only be executed during the FireWire bus generation specified in 'generation'. Pass false to ignore the generation parameter. The generation can be obtained by calling GetBusGeneration(). Must be 'true' when using 64-bit addressing. @param generation The FireWire bus generation during which the command should be executed. Ignored if failOnReset is false. Must be a valid generation number when using 64-bit absolute addressing. @result An IOFireWireLibCommandRef interface. See IOFireWireLibCommandRef. */ IOFireWireLibCommandRef (*CreateCompareSwapCommand)( IOFireWireLibDeviceRef self, io_object_t device, const FWAddress * addr, UInt32 cmpVal, UInt32 newVal, IOFireWireLibCommandCallback callback, Boolean failOnReset, UInt32 generation, void* inRefCon, REFIID iid) ; // --- other methods --------------------------- /*! @function BusReset @abstract Cause a bus reset @param self The device interface to use. */ IOReturn (*BusReset)( IOFireWireLibDeviceRef self) ; /*! @function GetCycleTime @abstract Get bus cycle time. @param self The device interface to use. @param outCycleTime A pointer to a UInt32 to hold the result @result An IOReturn error code. */ IOReturn (*GetCycleTime)( IOFireWireLibDeviceRef self, UInt32* outCycleTime) ; /*! @function GetGenerationAndNodeID @abstract (Obsolete) Get bus generation and remote device node ID. @discussion Obsolete -- Please use GetBusGeneration() and/or GetRemoteNodeID() in interface v4. @param self The device interface to use. @param outGeneration A pointer to a UInt32 to hold the generation result @param outNodeID A pointer to a UInt16 to hold the remote device node ID @result An IOReturn error code. */ IOReturn (*GetGenerationAndNodeID)( IOFireWireLibDeviceRef self, UInt32* outGeneration, UInt16* outNodeID) ; /*! @function GetLocalNodeID @abstract (Obsolete) Get local node ID. @discussion Obsolete -- Please use GetBusGeneration() and GetLocalNodeIDWithGeneration() in interface v4. @param self The device interface to use. @param outLocalNodeID A pointer to a UInt16 to hold the local device node ID @result An IOReturn error code. */ IOReturn (*GetLocalNodeID)( IOFireWireLibDeviceRef self, UInt16* outLocalNodeID) ; /*! @function GetResetTime @abstract Get time since last bus reset. @param self The device interface to use. @param outResetTime A pointer to an AbsolutTime to hold the result. @result An IOReturn error code. */ IOReturn (*GetResetTime)( IOFireWireLibDeviceRef self, AbsoluteTime* outResetTime) ; // --- unit directory support ------------------ /*! @function CreateLocalUnitDirectory @abstract Creates a local unit directory object and returns an interface to it. An instance of a unit directory object corresponds to an instance of a unit directory in the local machine's configuration ROM. @param self The device interface to use. @param iid An ID number, of type CFUUIDBytes (see CFUUID.h), identifying the type of interface to be returned for the created unit directory object. @result An IOFireWireLibLocalUnitDirectoryRef. Returns 0 upon failure */ IOFireWireLibLocalUnitDirectoryRef (*CreateLocalUnitDirectory)( IOFireWireLibDeviceRef self, REFIID iid) ; // --- config directory support ---------------- /*! @function GetConfigDirectory @abstract Creates a config directory object and returns an interface to it. The created config directory object represents the config directory in the remote device or unit to which the creating device interface is attached. @param self The device interface to use. @param iid An ID number, of type CFUUIDBytes (see CFUUID.h), identifying the type of interface to be returned for the created config directory object. @result An IOFireWireLibConfigDirectoryRef which should be released using Release(). Returns 0 upon failure. */ IOFireWireLibConfigDirectoryRef (*GetConfigDirectory)( IOFireWireLibDeviceRef self, REFIID iid) ; /*! @function CreateConfigDirectoryWithIOObject @abstract This function can be used to create a config directory object and a corresponding interface from an opaque IOObject reference. Some configuration directory interface methods may return an io_object_t instead of an IOFireWireLibConfigDirectoryRef. Use this function to obtain an IOFireWireLibConfigDirectoryRef from an io_object_t. @param self The device interface to use. @param iid An ID number, of type CFUUIDBytes (see CFUUID.h), identifying the type of interface to be returned for the created config directory object. @result An IOFireWireLibConfigDirectoryRef. Returns 0 upon failure */ IOFireWireLibConfigDirectoryRef (*CreateConfigDirectoryWithIOObject)( IOFireWireLibDeviceRef self, io_object_t inObject, REFIID iid) ; // --- address space support ------------------- /*! @function CreatePseudoAddressSpace @abstract Creates a pseudo address space object and returns an interface to it. This will create a pseudo address space (software-backed) on the local machine. @param self The device interface to use. @param inSize The size in bytes of this address space. @param inRefCon A user specified reference value. This will be passed to all callback functions. @param inQueueBufferSize The size of the queue which receives packets from the bus before they are handed to the client and/or put in the backing store. A larger queue can help eliminate dropped packets when receiving large bursts of data. When a packet is received which can not fit into the queue, the packet dropped callback will be called. @param inBackingStore An optional block of allocated memory representing the contents of the address space. This memory block must be of size inSize. @param inFlags A UInt32 with bits set corresponding to the flags that should be set for this address space. <ul> <li>kFWAddressSpaceNoFlags -- All flags off</li> <li>kFWAddressSpaceNoWriteAccess -- Write access to this address space will be disallowed. Setting this flag also disables compare/swap transactions on this address space.</li> <li>kFWAddressSpaceNoReadAccess -- Read access access to this address space will be disallowed. Setting this flag also disables compare/swap transactions on this address space.</li> <li>kFWAddressSpaceAutoWriteReply -- Writes will be made automatically, directly modifying the contents of the backing store. The user process will not be notified of writes.</li> <li>kFWAddressSpaceAutoReadReply -- Reads to this address space will be answered automagically using the contents of the backing store. The user process will not be notified of reads.</li> <li>kFWAddressSpaceAutoCopyOnWrite -- Writes to this address space will be made directly to the backing store at the same time the user process is notified of a write.</li> </ul> @param iid An ID number, of type CFUUIDBytes (see CFUUID.h), identifying the type of interface to be returned for the created pseudo address space object. @result An IOFireWireLibPseudoAddressSpaceRef. Returns 0 upon failure */ IOFireWireLibPseudoAddressSpaceRef (*CreatePseudoAddressSpace)( IOFireWireLibDeviceRef self, UInt32 inSize, void* inRefCon, UInt32 inQueueBufferSize, void* inBackingStore, UInt32 inFlags, REFIID iid) ; /*! @function CreatePhysicalAddressSpace @abstract Creates a physical address space object and returns an interface to it. This will create a physical address space on the local machine. @param self The device interface to use. @param inSize The size in bytes of this address space. @param inBackingStore An block of allocated memory representing the contents of the address space. @param inFlags A UInt32 with bits set corresponding to the flags that should be set for this address space. For future use -- always pass 0. @param iid An ID number, of type CFUUIDBytes (see CFUUID.h), identifying the type of interface to be returned for the created physical address space object. @result An IOFireWireLibPhysicalAddressSpaceRef. Returns 0 upon failure */ IOFireWireLibPhysicalAddressSpaceRef (*CreatePhysicalAddressSpace)( IOFireWireLibDeviceRef self, UInt32 inSize, void* inBackingStore, UInt32 inFlags, REFIID iid) ; // --- debugging ------------------------------- /*! Description forthcoming */ IOReturn (*FireBugMsg)( IOFireWireLibDeviceRef self, const char* msg) ; // // NOTE: the following methods available only in interface v2 and later // // --- eye-sock-run-U.S. ----------------------- /*! @function AddIsochCallbackDispatcherToRunLoop @abstract This function adds an event source for the isochronous callback dispatcher to the specified CFRunLoop. Isochronous related callbacks will not function before this function is called. This functions is similar to AddCallbackDispatcherToRunLoop. The passed CFRunLoop can be different from that passed to AddCallbackDispatcherToRunLoop. @param self The device interface to use. @param inRunLoop A CFRunLoopRef for the run loop to which the event loop source should be added @result An IOReturn error code. */ IOReturn (*AddIsochCallbackDispatcherToRunLoop)( IOFireWireLibDeviceRef self, CFRunLoopRef inRunLoop) ; /*! @function CreateRemoteIsochPort @abstract Creates a remote isochronous port object and returns an interface to it. A remote isochronous port object is an abstract entity used to represent a remote talker or listener device on an isochronous channel. @param self The device interface to use. @param inTalking Pass true if this port represents an isochronous talker. Pass false if this port represents an isochronous listener. @param iid An ID number, of type CFUUIDBytes (see CFUUID.h), identifying the type of interface to be returned for the created remote isochronous port object. @result An IOFireWireLibRemoteIsochPortRef. Returns 0 upon failure */ IOFireWireLibRemoteIsochPortRef (*CreateRemoteIsochPort)( IOFireWireLibDeviceRef self, Boolean inTalking, REFIID iid) ; /*! @function CreateLocalIsochPort @abstract Creates a local isochronous port object and returns an interface to it. A local isochronous port object is an abstract entity used to represent a talking or listening endpoint in the local machine. @param self The device interface to use. @param inTalking Pass true if this port represents an isochronous talker. Pass false if this port represents an isochronous listener. @param inDCLProgram A pointer to the first DCL command struct of the DCL program to be compiled and used to send or receive data on this port. @param inStartEvent Start event: 0 or kFWDCLCycleEvent or kFWDCLSyBitsEvent @param inStartState Start state bits. For kFWDCLCycleEvent specifies the cycle to start the DMA on. For kFWDCLSyBitsEvent specifies the packet sync field value for the first packet to receive. @param inStartMask Start mask bits. For kFWDCLCycleEvent specifies a mask for the start cycle: the DMA will start when currentCycle & inStartMask == inStartEvent & inStartMask. For kFWDCLSyBitsEvent specifies a mask for the sync field: the DMA will start when packet sync == inStartEvent & inStartMask. @param inDCLProgramRanges This is an optional optimization parameter which can be used to decrease the time the local port object spends determining which set of virtual ranges the passed DCL program occupies. Pass a pointer to an array of IOVirtualRange structs or nil to ignore this parameter. @param inDCLProgramRangeCount The number of virtual ranges passed to inDCLProgramRanges. Pass 0 for none. @param inBufferRanges This is an optional optimization parameter which can be used to decrease the time the local port object spends determining which set of virtual ranges the data buffers referenced by the passed DCL program occupy. Pass a pointer to an array of IOVirtualRange structs or nil to ignore this parameter. @param inBufferRangeCount The number of virtual ranges passed to inBufferRanges. Pass 0 for none. @param iid An ID number, of type CFUUIDBytes (see CFUUID.h), identifying the type of interface to be returned for the created object. @result An IOFireWireLibLocalIsochPortRef. Returns 0 upon failure */ IOFireWireLibLocalIsochPortRef (*CreateLocalIsochPort)( IOFireWireLibDeviceRef self, Boolean inTalking, DCLCommand* inDCLProgram, UInt32 inStartEvent, UInt32 inStartState, UInt32 inStartMask, IOVirtualRange inDCLProgramRanges[], // optional optimization parameters UInt32 inDCLProgramRangeCount, IOVirtualRange inBufferRanges[], UInt32 inBufferRangeCount, REFIID iid) ; /*! @function CreateIsochChannel @abstract Creates an isochronous channel object and returns an interface to it. An isochronous channel object is an abstract entity used to represent a FireWire isochronous channel. @param self The device interface to use. @param doIrm Controls whether the channel automatically performs IRM operations. Pass true if the channel should allocate its channel and bandwidth with the IRM. Pass false to ignore the IRM. @param packetSize Size of payload in bytes of packets being sent or received with this channel, excluding headers. This is automatically translated into a bandwidth allocation appropriate for the speed passed in prefSpeed. @param prefSpeed The preferred bus speed of this channel. @param iid An ID number, of type CFUUIDBytes (see CFUUID.h), identifying the type of interface to be returned for the created object. @result An IOFireWireLibIsochChannelRef. Returns 0 upon failure */ IOFireWireLibIsochChannelRef (*CreateIsochChannel)( IOFireWireLibDeviceRef self, Boolean doIrm, UInt32 packetSize, IOFWSpeed prefSpeed, REFIID iid ) ; /*! @function CreateDCLCommandPool @abstract Creates a command pool object and returns an interface to it. The command pool can be used to build DCL programs. @param self The device interface to use. @param size Starting size of command pool @param iid An ID number, of type CFUUIDBytes (see CFUUID.h), identifying the type of interface to be returned for the created object. @result An IOFireWireLibDCLCommandPoolRef. Returns 0 upon failure */ IOFireWireLibDCLCommandPoolRef (*CreateDCLCommandPool)( IOFireWireLibDeviceRef self, IOByteCount size, REFIID iid ) ; // --- refcons --------------------------------- /*! @function GetRefCon @abstract Get user reference value set on this interface @param self The device interface to use. @result Returns the user's reference value set on this interface. */ void* (*GetRefCon)( IOFireWireLibDeviceRef self) ; /*! @function SetRefCon @abstract Set user reference value on this interface @param self The device interface to use. @param refCon The reference value to set. */ void (*SetRefCon)( IOFireWireLibDeviceRef self, const void* refCon) ; // --- debugging ------------------------------- // do not use this function /*! @function @description Do not use this function. */ CFTypeRef (*GetDebugProperty)( IOFireWireLibDeviceRef self, void* interface, CFStringRef inPropertyName, CFTypeID* outPropertyType) ; /*! @function PrintDCLProgram @abstract Walk a DCL program linked list and print its contents @param self The device interface to use. @param inProgram A pointer to the first DCL of the program to print @param inLength Number of DCLs expected in the program. PrintDCLProgram() will report an error if this number does not match the number of DCLs found in the program. */ void (*PrintDCLProgram)( IOFireWireLibDeviceRef self, const DCLCommand* inProgram, UInt32 inLength) ; // // NOTE: the following methods available only in interface v3 and later // // --- v3 functions ---------- /*! @function CreateInitialUnitsPseudoAddressSpace @abstract Creates a pseudo address space in initial units space. @discussion Creates a pseudo address space object in initial units space and returns an interface to it. This will create a pseudo address space (software-backed) on the local machine. Availablilty: IOFireWireDeviceInterface_v3, and newer @param self The device interface to use. @param inAddressLo The lower 32 bits of the base address of the address space to be created. The address is always in initial units space. @param inSize The size in bytes of this address space. @param inRefCon A user specified reference value. This will be passed to all callback functions. @param inQueueBufferSize The size of the queue which receives packets from the bus before they are handed to the client and/or put in the backing store. A larger queue can help eliminate dropped packets when receiving large bursts of data. When a packet is received which can not fit into the queue, the packet dropped callback will be called. @param inBackingStore An optional block of allocated memory representing the contents of the address space. This memory block must be of size inSize. @param inFlags A UInt32 with bits set corresponding to the flags that should be set for this address space. <ul> <li>kFWAddressSpaceNoFlags -- All flags off</li> <li>kFWAddressSpaceNoWriteAccess -- Write access to this address space will be disallowed. Setting this flag also disables compare/swap transactions on this address space.</li> <li>kFWAddressSpaceNoReadAccess -- Read access access to this address space will be disallowed. Setting this flag also disables compare/swap transactions on this address space.</li> <li>kFWAddressSpaceAutoWriteReply -- Writes will be made automatically, directly modifying the contents of the backing store. The user process will not be notified of writes.</li> <li>kFWAddressSpaceAutoReadReply -- Reads to this address space will be answered automagically using the contents of the backing store. The user process will not be notified of reads.</li> <li>kFWAddressSpaceAutoCopyOnWrite -- Writes to this address space will be made directly to the backing store at the same time the user process is notified of a write. Clients will only be notified of a write if kFWAddressSpaceAutoWriteReply is not set.</li> <li>kFWAddressSpaceShareIfExists -- Allows creation of this address space even if another client already has an address space at the requested address. All clients will be notified of writes to covered addresses.</li> <li>kFWAddressSpaceExclusive -- Ensures that the allocation of this address space will fail if any portion of this address range is already allocated. If the allocation is successful this flag ensures that any future allocations overlapping this range will fail even if allocted with kFWAddressSpaceShareIfExists.</li> </ul> @param iid An ID number, of type CFUUIDBytes (see CFUUID.h), identifying the type of interface to be returned for the created pseudo address space object. @result An IOFireWireLibPseudoAddressSpaceRef. Returns 0 upon failure */ IOFireWireLibPseudoAddressSpaceRef (*CreateInitialUnitsPseudoAddressSpace)( IOFireWireLibDeviceRef self, UInt32 inAddressLo, UInt32 inSize, void* inRefCon, UInt32 inQueueBufferSize, void* inBackingStore, UInt32 inFlags, REFIID iid) ; /*! @function AddCallbackDispatcherToRunLoopForMode @abstract Add a run loop event source to allow IOFireWireLib callbacks to function. @discussion Installs the proper run loop event source to allow callbacks to function. This method must be called before callback notifications for this interface or any interfaces created using this interface can function. With this function, you can additionally specify for which run loop modes this source should be added. Availability: IOFireWireDeviceInterface_v3, and newer @param self The device interface to use. @param inRunLoop The run loop on which to install the event source @param inRunLoopMode The run loop mode(s) for which to install the event source @result An IOReturn error code. */ IOReturn (*AddCallbackDispatcherToRunLoopForMode)( IOFireWireLibDeviceRef self, CFRunLoopRef inRunLoop, CFStringRef inRunLoopMode ) ; /*! @function AddIsochCallbackDispatcherToRunLoop @abstract Add a run loop event source to allow IOFireWireLib isoch callbacks to function. @discussion This function adds an event source for the isochronous callback dispatcher to the specified CFRunLoop. Isochronous related callbacks will not be called unless this function has been called. This function is similar to AddCallbackDispatcherToRunLoop. The passed CFRunLoop can be different from that passed to AddCallbackDispatcherToRunLoop. Availability: IOFireWireDeviceInterface_v3, and newer @param self The device interface to use. @param inRunLoop A CFRunLoopRef for the run loop to which the event loop source should be added @param inRunLoopMode The run loop mode(s) for which to install the event source @result An IOReturn error code. */ IOReturn (*AddIsochCallbackDispatcherToRunLoopForMode)( IOFireWireLibDeviceRef self, CFRunLoopRef inRunLoop, CFStringRef inRunLoopMode ) ; /*! @function RemoveIsochCallbackDispatcherFromRunLoop @abstract Removes an IOFireWireLib-added run loop event source. @discussion Reverses the effects of AddIsochCallbackDispatcherToRunLoop(). This method removes the run loop event source that was added to the specified run loop preventing any future callbacks from being called. Availability: IOFireWireDeviceInterface_v3, and newer @param self The device interface to use. */ void (*RemoveIsochCallbackDispatcherFromRunLoop)( IOFireWireLibDeviceRef self) ; /*! @function Seize @abstract Seize control of device/unit @discussion Allows a user space client to seize control of an in-kernel service even if that service has been Opened() by another client or in-kernel driver. This function should be used with care. Admin rights are required to use this function. Calling this method makes it appear to all other drivers that the device has been unplugged. Open() should be called after this method has been invoked. When access is complete, Close() and then IOServiceRequestProbe() should be called to restore normal operation. Calling IOServiceRequestProbe() makes it appear that the device has been "re-plugged." @param self The device interface to use. @param inFlags Reserved for future use. Set to NULL. Description forthcoming? */ IOReturn (*Seize)( IOFireWireLibDeviceRef self, IOOptionBits inFlags, ... ) ; /*! @function FireLog // DEPRECATED @abstract Logs string to in-kernel debug buffer @param self The device interface to use. */ IOReturn (*FireLog)( IOFireWireLibDeviceRef self, const char* format, ... ) ; /*! @function GetBusCycleTime @abstract Get bus and cycle time. @param self The device interface to use. @param outBusTime A pointer to a UInt32 to hold the bus time @param outCycleTime A pointer to a UInt32 to hold the cycle time @result An IOReturn error code. */ IOReturn (*GetBusCycleTime)( IOFireWireLibDeviceRef self, UInt32* outBusTime, UInt32* outCycleTime) ; // // v4 // /*! @function CreateCompareSwapCommand64 @abstract Create a quadlet compare/swap command object and initialize it with 64-bit values. @param self The device interface to use. @param device The service (representing an attached FireWire device) to which to write. For 48-bit, device relative addressing, pass the service used to create the device interface. This can be obtained by calling GetDevice(). For 64-bit absolute addressing, pass 0. Other values are unsupported. Setting the callback value to nil defaults to synchronous execution. @param addr Command target address @param cmpVal 64-bit value expected at target address @param newVal 64-bit value to be set at target address @param callback Command completion callback. @param failOnReset Pass true if the command should only be executed during the FireWire bus generation specified in 'generation'. Pass false to ignore the generation parameter. The generation can be obtained by calling GetBusGeneration() @param generation The FireWire bus generation during which the command should be executed. Ignored if failOnReset is false. @result An IOFireWireLibCommandRef interface. See IOFireWireLibCommandRef. */ IOFireWireLibCommandRef (*CreateCompareSwapCommand64)( IOFireWireLibDeviceRef self, io_object_t device, const FWAddress* addr, UInt64 cmpVal, UInt64 newVal, IOFireWireLibCommandCallback callback, Boolean failOnReset, UInt32 generation, void* inRefCon, REFIID iid) ; /*! @function CompareSwap64 @abstract Perform synchronous lock operation @param self The device interface to use. @param device The service (representing an attached FireWire device) to which to write. For 48-bit, device relative addressing, pass the service used to create the device interface. This can be obtained by calling GetDevice(). For 64-bit absolute addressing, pass 0. Other values are unsupported. If the quadlets stored at 'oldVal' match those passed to 'expectedVal', the lock operation was successful. @param addr Command target address @param expectedVal Pointer to quadlets expected at target. @param newVal Pointer to quadlets to atomically set at target if compare is successful. @param oldVal Pointer to quadlets to hold value found at target address after transaction if completed. @param size Size in bytes of compare swap transaction to perform. Value values are 4 and 8. @param failOnReset Pass true if the command should only be executed during the FireWire bus generation specified in 'generation'. Pass false to ignore the generation parameter. The generation can be obtained by calling GetBusGeneration() @param generation The FireWire bus generation during which the command should be executed. Ignored if failOnReset is false. @result An IOReturn error code */ IOReturn (*CompareSwap64)( IOFireWireLibDeviceRef self, io_object_t device, const FWAddress* addr, UInt32* expectedVal, UInt32* newVal, UInt32* oldVal, IOByteCount size, Boolean failOnReset, UInt32 generation) ; /*! @function GetBusGeneration @abstract Get bus generation number. @discussion The bus generation number stays constant between bus resets and can be used in combination with a FireWire node ID to uniquely identify nodes on the bus. Pass the generation number to functions that take or return FireWire node IDs. Availability: IOFireWireDeviceInterface_v4 and newer @param self The device interface to use. @param outGeneration A pointer to a UInt32 to hold the bus generation number @result Returns kIOReturnSuccess if a valid bus generation has been returned in 'outGeneration'.*/ IOReturn (*GetBusGeneration)( IOFireWireLibDeviceRef self, UInt32* outGeneration ) ; /*! @function GetLocalNodeIDWithGeneration @abstract Get node ID of local machine. @discussion Use this function instead of GetLocalNodeID(). Availability: IOFireWireDeviceInterface_v4 and newer @param self The device interface to use. @param checkGeneration A bus generation number obtained from GetBusGeneration() @param outLocalNodeID A pointer to a UInt16 to hold the node ID of the local machine. @result Returns kIOReturnSuccess if a valid nodeID has been returned in 'outLocalNodeID'. Returns kIOFireWireBusReset if 'checkGeneration' does not match the current bus generation number.*/ IOReturn (*GetLocalNodeIDWithGeneration)( IOFireWireLibDeviceRef self, UInt32 checkGeneration, UInt16* outLocalNodeID ) ; /*! @function GetRemoteNodeID @abstract Get node ID of device to which this interface is attached. @discussion Availability: IOFireWireDeviceInterface_v4 and newer @param self The device interface to use. @param checkGeneration A bus generation number obtained from GetBusGeneration() @param outRemoteNodeID A pointer to a UInt16 to hold the node ID of the remote device. @result Returns kIOReturnSuccess if a valid nodeID has been returned in 'outRemoteNodeID'. Returns kIOFireWireBusReset if 'checkGeneration' does not match the current bus generation number.*/ IOReturn (*GetRemoteNodeID)( IOFireWireLibDeviceRef self, UInt32 checkGeneration, UInt16* outRemoteNodeID ) ; /*! @function GetSpeedToNode @abstract Get maximum transfer speed to device to which this interface is attached. @discussion Availability: IOFireWireDeviceInterface_v4 and newer @param self The device interface to use. @param checkGeneration A bus generation number obtained from GetBusGeneration() @param outSpeed A pointer to an IOFWSpeed to hold the maximum speed to the remote device. @result Returns kIOReturnSuccess if a valid speed has been returned in 'outSpeed'. Returns kIOFireWireBusReset if 'checkGeneration' does not match the current bus generation number.*/ IOReturn (*GetSpeedToNode)( IOFireWireLibDeviceRef self, UInt32 checkGeneration, IOFWSpeed* outSpeed) ; /*! @function GetSpeedBetweenNodes @abstract Get the maximum transfer speed between nodes 'srcNodeID' and 'destNodeID'. @discussion Availability: IOFireWireDeviceInterface_v4 and newer @param self The device interface to use. @param checkGeneration A bus generation number obtained from GetBusGeneration() @param srcNodeID A FireWire node ID. @param destNodeID A FireWire node ID. @param outSpeed A pointer to an IOFWSpeed to hold the maximum transfer speed between node 'srcNodeID' and 'destNodeID'. @result Returns kIOReturnSuccess if a valid speed has been returned in 'outSpeed'. Returns kIOFireWireBusReset if 'checkGeneration' does not match the current bus generation number.*/ IOReturn (*GetSpeedBetweenNodes)( IOFireWireLibDeviceRef self, UInt32 checkGeneration, UInt16 srcNodeID, UInt16 destNodeID, IOFWSpeed* outSpeed) ; // // v5 // /*! Description forthcoming */ IOReturn (*GetIRMNodeID)( IOFireWireLibDeviceRef self, UInt32 checkGeneration, UInt16* outIRMNodeID ) ; // // v6 // /*! Description forthcoming */ IOReturn (*ClipMaxRec2K)( IOFireWireLibDeviceRef self, Boolean clipMaxRec ) ; /*! Description forthcoming */ IOFireWireLibNuDCLPoolRef (*CreateNuDCLPool)( IOFireWireLibDeviceRef self, UInt32 capacity, REFIID iid ) ; // // v7 // /*! Description forthcoming */ IOFireWireSessionRef (*GetSessionRef)( IOFireWireLibDeviceRef self ) ; // // v8 // /*! @function CreateLocalIsochPortWithOptions @abstract Create a local isoch port @discussion Same as CreateLocalIsochPort(), above, but allows additional options to be passed. Availability: IOFireWireDeviceInterface_v8 and newer @param options Currently supported options are 'kFWIsochPortUseSeparateKernelThread'. If this option is used, a separate kernel thread will be created to handle interrupt processing for this port only. Pass 'kFWIsochPortDefaultOptions' for no options. @result Returns kIOReturnSuccess if a valid speed has been returned in 'outSpeed'. Returns kIOFireWireBusReset if 'checkGeneration' does not match the current bus generation number.*/ IOFireWireLibLocalIsochPortRef (*CreateLocalIsochPortWithOptions)( IOFireWireLibDeviceRef self, Boolean inTalking, DCLCommand * dclProgram, UInt32 startEvent, UInt32 startState, UInt32 startMask, IOVirtualRange dclProgramRanges[], // optional optimization parameters UInt32 dclProgramRangeCount, IOVirtualRange bufferRanges[], UInt32 bufferRangeCount, IOFWIsochPortOptions options, REFIID iid) ; // // v9 // /*! @function CreateVectorCommand @abstract Create a vector command object. @param self The device interface to use. @param callback Command completion callback. Setting the callback value to nil defaults to synchronous execution. @param inRefCon Reference constant for 3rd party use. @result An IOFireWireLibVectorCommandRef interface*/ IOFireWireLibVectorCommandRef (*CreateVectorCommand)( IOFireWireLibDeviceRef self, IOFireWireLibCommandCallback callback, void* inRefCon, REFIID iid) ; /*! @function AllocateIRMBandwidthInGeneration @abstract Attempt to allocate some isochronous bandwidth from the IRM @discussion Attempts to allocates some isochronous bandwidth from the IRM, if the generation matches the current generation. Availability: IOFireWireDeviceInterface_v9 and newer @param bandwidthUnits The number of bandwidth units to allocate @param generation The bus generation that this allocation attempt is to take place in. @result Returns kIOReturnSuccess if bandwidth allocation was successful. Returns kIOFireWireBusReset if 'generation' does not match the current bus generation number. Returns kIOReturnError for any other error (such as the allocation failed) */ IOReturn (*AllocateIRMBandwidthInGeneration)(IOFireWireLibDeviceRef self, UInt32 bandwidthUnits, UInt32 generation) ; /*! @function ReleaseIRMBandwidthInGeneration @abstract Attempt to release some isochronous bandwidth from the IRM @discussion Attempts to release some isochronous bandwidth from the IRM, if the generation matches the current generation. Availability: IOFireWireDeviceInterface_v9 and newer @param bandwidthUnits The number of bandwidth units to release @param generation The bus generation that this release attempt is to take place in. @result Returns kIOReturnSuccess if bandwidth release was successful. Returns kIOFireWireBusReset if 'generation' does not match the current bus generation number. Returns kIOReturnError for any other error (such as the allocation failed) */ IOReturn (*ReleaseIRMBandwidthInGeneration)(IOFireWireLibDeviceRef self, UInt32 bandwidthUnits, UInt32 generation) ; /*! @function AllocateIRMChannelInGeneration @abstract Attempt to allocate an isochronous channel from the IRM @discussion Attempts to allocates an isochronous channel from the IRM, if the generation matches the current generation. Availability: IOFireWireDeviceInterface_v9 and newer @param isochChannel The isochronous channel to allocate @param generation The bus generation that this allocation attempt is to take place in. @result Returns kIOReturnSuccess if channel allocation was successful. Returns kIOFireWireBusReset if 'generation' does not match the current bus generation number. Returns kIOReturnError for any other error (such as the allocation failed) */ IOReturn (*AllocateIRMChannelInGeneration)(IOFireWireLibDeviceRef self, UInt8 isochChannel, UInt32 generation) ; /*! @function ReleaseIRMChannelInGeneration @abstract Attempt to release an isochronous channel from the IRM @discussion Attempts to release an isochronous channel from the IRM, if the generation matches the current generation. Availability: IOFireWireDeviceInterface_v9 and newer @param isochChannel The isochronous channel to release @param generation The bus generation that this release attempt is to take place in. @result Returns kIOReturnSuccess if channel relase was successful. Returns kIOFireWireBusReset if 'generation' does not match the current bus generation number. Returns kIOReturnError for any other error (such as the allocation failed) */ IOReturn (*ReleaseIRMChannelInGeneration)(IOFireWireLibDeviceRef self, UInt8 isochChannel, UInt32 generation) ; /*! @function CreateIRMAllocation @abstract Attempt to create an IRM allocation that persists accross bus-resets. @discussion Create an IOFireWireIRMAllocation object, which can be used to allocate IRM resources, and will reallocate automatically after bus-resets (if possible). Availability: IOFireWireDeviceInterface_v9 and newer @param releaseIRMResourcesOnFree Specify whether or not the IRM resources shall be released when the IOFireWireLibIRMAllocation is destroyed. Can be overrided later. @param callback The handler to notify clients of failure to reclaim IRM resources after bus-reset. @param pLostNotificationProcRefCon The refCon passed with the callback. @result Returns a pointer to the newly created IRM allocation object, if successful, NULL otherwise. */ IOFireWireLibIRMAllocationRef (*CreateIRMAllocation)( IOFireWireLibDeviceRef self, Boolean releaseIRMResourcesOnFree, IOFireWireLibIRMAllocationLostNotificationProc callback, void *pLostNotificationProcRefCon, REFIID iid) ; /*! @function CreateAsyncStreamListener @abstract Creates a async stream listener object and returns an interface to it. @param self The device interface to use. @param channel The channel to allocate. @param inRefCon A user specified reference value. This will be passed to all callback functions. @param inQueueBufferSize The size of the queue which receives packets from the bus before they are handed to the client. A larger queue can help eliminate dropped packets when receiving large bursts of data. When a packet is received which can not fit into the queue, the packet dropped callback will be called. @param iid An ID number, of type CFUUIDBytes (see CFUUID.h), identifying the type of interface to be returned for the created ayns stream listener object. @result An IOFWAsyncStreamListenerInterfaceRef. Returns 0 upon failure */ IOFWAsyncStreamListenerInterfaceRef (*CreateAsyncStreamListener)( IOFireWireLibDeviceRef self, UInt32 channel, IOFWAsyncStreamListenerHandler callback, void* inRefCon, UInt32 inQueueBufferSize, REFIID iid) ; /*! @function GetIsochAsyncPort @abstract Returns the notification port used for async and isoch callbacks @discussion If necessary GetIsochAsyncPort will allocate the port. Availability: IOFireWireDeviceInterface_v9 and newer @param self The device interface to use. @result Returns the mach_port used for notifications */ mach_port_t (*GetIsochAsyncPort)( IOFireWireLibDeviceRef self ); /*! @function CreatePHYCommand @abstract Create a command object for sending a PHY packet @param self The device interface to use. @param data1 phy packet quadlet 1 @param data2 phy packet quadlet 1 @param callback completion callback @param failOnReset Pass true if the command should only be executed during the FireWire bus generation specified in 'generation'. Pass false to ignore the generation parameter. The generation can be obtained by calling GetBusGeneration() @param generation The FireWire bus generation during which the command should be executed. Ignored if failOnReset is false. @param iid An ID number, of type CFUUIDBytes (see CFUUID.h), identifying the type of interface to be returned for the created phy command object. @result An IOReturn error code */ IOFireWireLibCommandRef (*CreatePHYCommand)( IOFireWireLibDeviceRef self, UInt32 data1, UInt32 data2, IOFireWireLibCommandCallback callback, Boolean failOnReset, UInt32 generation, void* inRefCon, REFIID iid ); /*! @function CreatePHYPacketListener @abstract Create a listener object for receiving PHY packets @param self The device interface to use. @param queueCount The maximum queue size to use to buffer phy packets between kernel and user space @param iid An ID number, of type CFUUIDBytes (see CFUUID.h), identifying the type of interface to be returned for the created phy packet listener object. @result An IOReturn error code */ IOFireWireLibPHYPacketListenerRef (*CreatePHYPacketListener)( IOFireWireLibDeviceRef self, UInt32 queueCount, REFIID iid ); /*! @function CreateAsyncStreamCommand @abstract Create a command object for sending Async Stream packets @param self The device interface to use. @param channel The channel number to use. @param buf A pointer to the buffer containing the data to be written @param size Number of bytes to write @param callback Command completion callback. @param failOnReset Pass true if the command should only be executed during the FireWire bus generation specified in 'generation'. Pass false to ignore the generation parameter. The generation can be obtained by calling GetBusGeneration(). Must be 'true' when using 64-bit addressing. @param inRefCon A user specified reference value. This will be passed to all callback functions. @param iid An ID number, of type CFUUIDBytes (see CFUUID.h), identifying the type of interface to be returned for the created phy packet listener object. @result An IOReturn error code */ IOFireWireLibCommandRef (*CreateAsyncStreamCommand)(IOFireWireLibDeviceRef self, UInt32 channel, UInt32 sync, UInt32 tag, void* buf, UInt32 size, IOFireWireLibCommandCallback callback, Boolean failOnReset, UInt32 generation, void* inRefCon, REFIID iid); /*! @function GetCycleTimeAndUpTime @abstract Get bus cycle time and cpu uptime. @param self The device interface to use. @param outCycleTime A pointer to a UInt32 to hold the result @param outUpTime A pointer to a UInt64 to hold the result @result An IOReturn error code. */ IOReturn (*GetCycleTimeAndUpTime)( IOFireWireLibDeviceRef self, UInt32* outCycleTime, UInt64* outUpTime) ; } IOFireWireDeviceInterface, IOFireWireUnitInterface, IOFireWireNubInterface ; #endif // ifdef KERNEL #pragma mark - #pragma mark PSEUDO ADDRESS SPACE // ============================================================ // IOFireWirePseudoAddressSpaceInterface // ============================================================ // creation flags /*! FireWire address space creation flags */ typedef enum { kFWAddressSpaceNoFlags = 0, kFWAddressSpaceNoWriteAccess = (1 << 0) , kFWAddressSpaceNoReadAccess = (1 << 1) , kFWAddressSpaceAutoWriteReply = (1 << 2) , kFWAddressSpaceAutoReadReply = (1 << 3) , kFWAddressSpaceAutoCopyOnWrite = (1 << 4) , kFWAddressSpaceShareIfExists = (1 << 5) , kFWAddressSpaceExclusive = (1 << 6) } FWAddressSpaceFlags ; #ifndef KERNEL /*! @class @discussion Represents and provides management functions for a pseudo address space (software-backed) in the local machine. Pseudo address space objects can be created using IOFireWireDeviceInterface.*/ typedef struct IOFireWirePseudoAddressSpaceInterface_t { IUNKNOWN_C_GUTS ; /*! Interface version */ UInt32 version; /*! Interface revision */ UInt32 revision; /*! @function SetWriteHandler @abstract Set the callback that should be called to handle write accesses to the corresponding address space @param self The address space interface to use. @param inWriter The callback to set. @result Returns the callback that was previously set or nil for none.*/ const IOFireWirePseudoAddressSpaceWriteHandler (*SetWriteHandler)( IOFireWireLibPseudoAddressSpaceRef self, IOFireWirePseudoAddressSpaceWriteHandler inWriter) ; /*! @function SetReadHandler @abstract Set the callback that should be called to handle read accesses to the corresponding address space @param self The address space interface to use. @param inReader The callback to set. @result Returns the callback that was previously set or nil for none.*/ const IOFireWirePseudoAddressSpaceReadHandler (*SetReadHandler)( IOFireWireLibPseudoAddressSpaceRef self, IOFireWirePseudoAddressSpaceReadHandler inReader) ; /*! @function SetSkippedPacketHandler @abstract Set the callback that should be called when incoming packets are dropped by the address space. @param self The address space interface to use. @param inHandler The callback to set. @result Returns the callback that was previously set or nil for none.*/ const IOFireWirePseudoAddressSpaceSkippedPacketHandler (*SetSkippedPacketHandler)( IOFireWireLibPseudoAddressSpaceRef self, IOFireWirePseudoAddressSpaceSkippedPacketHandler inHandler) ; /*! @function NotificationIsOn @abstract Is notification on? @param self The address space interface to use. @result Returns true if packet notifications for this address space are active */ Boolean (*NotificationIsOn)(IOFireWireLibPseudoAddressSpaceRef self) ; /*! @function TurnOnNotification @abstract Try to turn on packet notifications for this address space. @param self The address space interface to use. @result Returns true upon success */ Boolean (*TurnOnNotification)(IOFireWireLibPseudoAddressSpaceRef self) ; /*! @function TurnOffNotification @abstract Force packet notification off. @param self The pseudo address interface to use. */ void (*TurnOffNotification)(IOFireWireLibPseudoAddressSpaceRef self) ; /*! @function ClientCommandIsComplete @abstract Notify the address space that a packet notification handler has completed. @discussion Packet notifications are received one at a time, in order. This function must be called after a packet handler has completed its work. @param self The address space interface to use. @param commandID The ID of the packet notification being completed. This is the same ID that was passed when a packet notification handler is called. @param status The completion status of the packet handler */ void (*ClientCommandIsComplete)(IOFireWireLibPseudoAddressSpaceRef self, FWClientCommandID commandID, IOReturn status) ; // --- accessors ---------- /*! @function GetFWAddress @abstract Get the FireWire address of this address space @param self The pseudo address interface to use. */ void (*GetFWAddress)(IOFireWireLibPseudoAddressSpaceRef self, FWAddress* outAddr) ; /*! @function GetBuffer @abstract Get a pointer to the backing store for this address space @param self The address space interface to use. @result A pointer to the backing store of this pseudo address space. Returns nil if none. */ void* (*GetBuffer)(IOFireWireLibPseudoAddressSpaceRef self) ; /*! @function GetBufferSize @abstract Get the size in bytes of this address space. @param self The address space interface to use. @result Size of the pseudo address space in bytes. Returns 0 for none.*/ const UInt32 (*GetBufferSize)(IOFireWireLibPseudoAddressSpaceRef self) ; /*! @function GetRefCon @abstract Returns the user refCon value for this address space. @param self The address space interface to use. @result Size of the pseudo address space in bytes. Returns 0 for none.*/ void* (*GetRefCon)(IOFireWireLibPseudoAddressSpaceRef self) ; } IOFireWirePseudoAddressSpaceInterface ; #pragma mark - #pragma mark IRM ALLOCATION // ============================================================ // IOFireWireLibIRMAllocationInterface // ============================================================ /*! @class Description forthcoming */ typedef struct IOFireWireLibIRMAllocationInterface_t { IUNKNOWN_C_GUTS ; UInt32 version, revision ; /*! @function setReleaseIRMResourcesOnFree @abstract Set a new value for releaseIRMResourcesOnFree @param self The IRMAllocation interface to use. @param doRelease The new value for releaseIRMResourcesOnFree. */ const void (*setReleaseIRMResourcesOnFree)( IOFireWireLibIRMAllocationRef self, Boolean doRelease) ; /*! @function allocateIsochResources @abstract Use this interface to allocate isochronous resources @param self The IRMAllocation interface to use. @param isochChannel The isoch channel to allocate. @param bandwidthUnits The bandwidth units to allocate. @result Returns true if allocation success */ IOReturn (*allocateIsochResources)(IOFireWireLibIRMAllocationRef self, UInt8 isochChannel, UInt32 bandwidthUnits); /*! @function deallocateIsochResources @abstract Deallocate previously allocated resources @param self The IRMAllocation interface to use. @result Returns true if deallocation success */ IOReturn (*deallocateIsochResources)(IOFireWireLibIRMAllocationRef self); /*! @function areIsochResourcesAllocated @abstract Poll to see if IRM resources are still allocated @param self The IRMAllocation interface to use. @param pAllocatedIsochChannel If allocated, the channel @param pAllocatedBandwidthUnits If allocated, the amount of bandwidth @result Returns true if currently allocated, false otherwise */ Boolean (*areIsochResourcesAllocated)(IOFireWireLibIRMAllocationRef self, UInt8 *pAllocatedIsochChannel, UInt32 *pAllocatedBandwidthUnits); /*! @function NotificationIsOn @abstract Is notification on? @param self The IRMAllocation interface to use. @result Returns true if notifications for this IRMAllocation are enabled */ Boolean (*NotificationIsOn)(IOFireWireLibIRMAllocationRef self) ; /*! @function TurnOnNotification @abstract Try to turn on notifications @param self The IRMAllocation interface to use. @result Returns true upon success */ Boolean (*TurnOnNotification)(IOFireWireLibIRMAllocationRef self) ; /*! @function TurnOffNotification @abstract Force notification off. @param self The IRMAllocation interface to use. */ void (*TurnOffNotification)(IOFireWireLibIRMAllocationRef self) ; /*! @function SetRefCon @abstract Set a new refcon @param self The IRMAllocation interface to use. @param refCon The new refcon value. */ void (*SetRefCon)(IOFireWireLibIRMAllocationRef self, void* refCon) ; /*! @function GetRefCon @abstract Get the current refcon @param self The IRMAllocation interface to use. @result Returns the current refcon value */ void* (*GetRefCon)(IOFireWireLibIRMAllocationRef self) ; }IOFireWireLibIRMAllocationInterface; #pragma mark - #pragma mark LOCAL UNIT DIRECTORY INTERFACE // ============================================================ // // IOFireWireLocalUnitDirectoryInterface // // ============================================================ /*! @class @discussion Allows creation and management of unit directories in the config ROM of the local machine. After the unit directory has been built, Publish() should be called to cause it to appear in the config ROM. Unpublish() has the reverse effect as Publish(). This interface can be created using IOFireWireDeviceInterface::CreateLocalUnitDirectory. */ typedef struct IOFireWireLocalUnitDirectoryInterface_t { IUNKNOWN_C_GUTS ; /*! Interface version */ UInt32 version; /*! Interface revision */ UInt32 revision ; // --- adding to ROM ------------------- /*! @function AddEntry_Ptr @abstract Append a data leaf @discussion Appends a leaf data node to a unit directory @param self The local unit directory interface to use. @param key The config ROM key for the data to be added. @param inBuffer A pointer to the data to be placed in the added leaf. @param inLen Length of the data being added. @param inDesc Reserved; set to NULL. */ IOReturn (*AddEntry_Ptr)(IOFireWireLibLocalUnitDirectoryRef self, int key, void* inBuffer, size_t inLen, CFStringRef inDesc) ; /*! @function AddEntry_UInt32 @abstract Append an immediate leaf @discussion Appends an immediate leaf to a unit directory. Note that only the lower 3 bytes of the passed in value can appear in the unit directory. @param self The local unit directory interface to use. @param key The config ROM key for the data to be added. @param value The value to be added. @param inDesc Reserved; set to NULL. */ IOReturn (*AddEntry_UInt32)(IOFireWireLibLocalUnitDirectoryRef self, int key, UInt32 value, CFStringRef inDesc) ; /*! @function AddEntry_FWAddress @abstract Append an offset leaf @discussion Appends an offset leaf to a unit directory. The address passed in value should be an address in initial unit space of the local config ROM. @param self The local unit directory interface to use. @param key The config ROM key for the data to be added. @param value A pointer to a FireWire address. @param inDesc Reserved; set to NULL. */ IOReturn (*AddEntry_FWAddress)(IOFireWireLibLocalUnitDirectoryRef self, int key, const FWAddress* value, CFStringRef inDesc) ; // Use this function to cause your unit directory to appear in the Mac's config ROM. /*! @function Publish @abstract Causes a constructed or updated unit directory to appear in the local machine's config ROM. Note that this call will cause a bus reset, after which the unit directory will be visible to devices on the bus. @param self The local unit directory interface to use. */ IOReturn (*Publish)(IOFireWireLibLocalUnitDirectoryRef self) ; /*! @function Unpublish @abstract Has the opposite effect from Publish(). This call removes a unit directory from the local machine's config ROM. Note that this call will cause a bus reset, after which the unit directory will no longer appear to devices on the bus. @param self The local unit directory interface to use. */ IOReturn (*Unpublish)(IOFireWireLibLocalUnitDirectoryRef self) ; } IOFireWireLocalUnitDirectoryInterface ; #pragma mark - #pragma mark PHYSICAL ADDRESS SPACE INTERFACE // ============================================================ // // IOFireWireLibPhysicalAddressSpaceInterface // // ============================================================ /*! @class @abstract IOFireWireLib physical address space object. ( interface name: IOFireWirePhysicalAddressSpaceInterface ) @discussion Represents and provides management functions for a physical address space (hardware-backed) in the local machine.<br> Physical address space objects can be created using IOFireWireDeviceInterface.*/ typedef struct IOFireWirePhysicalAddressSpaceInterface_t { IUNKNOWN_C_GUTS ; /*! Interface version. */ UInt32 version; /*! Interface revision. */ UInt32 revision ; /*! @function GetPhysicalSegments @abstract Returns the list of physical memory ranges this address space occupies on the local machine. @param self The address space interface to use. @param ioSegmentCount Pass in a pointer to the number of list entries in outSegments and outAddress. Upon completion, this will contain the actual number of segments returned in outSegments and outAddress @param outSegments A pointer to an array to hold the function results. Upon completion, this will contain the lengths of the physical segments this address space occupies on the local machine @param outAddresses A pointer to an array to hold the function results. Upon completion, this will contain the addresses of the physical segments this address space occupies on the local machine. If NULL, ioSegmentCount will contain the number of physical segments in the address space.*/ void (*GetPhysicalSegments)( IOFireWireLibPhysicalAddressSpaceRef self, UInt32* ioSegmentCount, IOByteCount outSegments[], IOPhysicalAddress outAddresses[]) ; /*! @function GetPhysicalSegment @abstract Returns the physical segment containing the address at a specified offset from the beginning of this address space @param self The address space interface to use. @param offset Offset from beginning of address space @param length Pointer to a value which upon completion will contain the length of the segment returned by the function. @result The address of the physical segment containing the address at the specified offset of the address space */ IOPhysicalAddress (*GetPhysicalSegment)( IOFireWireLibPhysicalAddressSpaceRef self, IOByteCount offset, IOByteCount* length) ; /*! @function GetPhysicalAddress @abstract Returns the physical address of the beginning of this address space @param self The address space interface to use. @result The physical address of the start of this address space */ IOPhysicalAddress (*GetPhysicalAddress)( IOFireWireLibPhysicalAddressSpaceRef self) ; // --- accessors ---------- /*! @function GetFWAddress @abstract Get the FireWire address of this address space @param self The address space interface to use. */ void (*GetFWAddress)( IOFireWireLibPhysicalAddressSpaceRef self, FWAddress* outAddr) ; /*! @function GetBuffer @abstract Get a pointer to the backing store for this address space @param self The address space interface to use. @result A pointer to the backing store of this address space.*/ void* (*GetBuffer)( IOFireWireLibPhysicalAddressSpaceRef self) ; /*! @function GetBufferSize @abstract Get the size in bytes of this address space. @param self The address space interface to use. @result Size of the pseudo address space in bytes. */ const UInt32 (*GetBufferSize)( IOFireWireLibPhysicalAddressSpaceRef self) ; } IOFireWirePhysicalAddressSpaceInterface ; #endif // ifndef KERNEL #pragma mark - #pragma mark COMMAND OBJECT INTERFACES // ================================================================= // command objects // ================================================================= #define kFireWireCommandUserFlagsMask (0x0000FFFF) // 8 quadlets #define kFWUserCommandSubmitWithCopyMaxBufferBytes 32 // // Flags to be set on IOFireWireLib command objects // Passed to SetFlags() // /*! @enum IOFireWireLib Command Flags @abstract Flags for IOFireWireLib command objects @discussion Pass these flags to the object's SetFlags callback. */ enum { kFWCommandNoFlags = 0, kFWCommandInterfaceForceNoCopy = (1 << 0), kFWCommandInterfaceForceCopyAlways = (1 << 1), kFWCommandInterfaceSyncExecute = (1 << 2), kFWCommandInterfaceAbsolute = (1 << 3), kFWVectorCommandInterfaceOrdered = (1 << 4), kFWCommandInterfaceForceBlockRequest = (1 << 5) } ; /*! @enum IOFireWireLib failOnReset Flags @abstract Flags for IOFireWireLib commands @discussion Pass these flags in the failOnReset of various commands. */ enum { kFWDontFailOnReset = false, kFWFailOnReset = true } ; /*! @enum IOFireWireLib Additional Command Flags @abstract Flags for IOFireWireLib commands @discussion Pass these flags to the object's SetFlags callback. */ enum { kFireWireCommandUseCopy = (1 << 16), kFireWireCommandAbsolute = (1 << 17) } ; #ifndef KERNEL // // IOFIREWIRELIBCOMMAND_C_GUTS // Macro used to insert generic superclass function definitions into all subclass of // IOFireWireCommand. Comments for functions contained in this macro follow below: // /*! @parseOnly */ #define IOFIREWIRELIBCOMMAND_C_GUTS \ /*! @function GetStatus \ @abstract Return command completion status. \ @discussion Availability: (for interfaces obtained with ID) \ <table border="0" rules="all"> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireReadCommandInterfaceID</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireReadCommandInterfaceID_v2</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireWriteCommandInterfaceID</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireWriteCommandInterfaceID_v2</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireReadQuadletCommandInterfaceID</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireWriteQuadletCommandInterfaceID</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireCompareSwapCommandInterfaceID</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireAsyncStreamCommandInterfaceID</code></td> \ <td>YES</td> \ </tr> \ </table> \ \ @param self The command object interface of interest \ @result An IOReturn error code indicating the completion error (if any) returned the last \ time this command object was executed */ \ IOReturn (*GetStatus)(IOFireWireLibCommandRef self) ; \ /*! @function GetTransferredBytes \ @abstract Return number of bytes transferred by this command object when it last completed \ execution. \ @discussion Availability: (for interfaces obtained with ID) \ <table border="0" rules="all"> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireReadCommandInterfaceID</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireReadCommandInterfaceID_v2</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireWriteCommandInterfaceID</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireWriteCommandInterfaceID_v2</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireReadQuadletCommandInterfaceID</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireWriteQuadletCommandInterfaceID</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireCompareSwapCommandInterfaceID</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireAsyncStreamCommandInterfaceID</code></td> \ <td>YES</td> \ </tr> \ </table> \ @param self The command object interface of interest \ @result A UInt32 containing the bytes transferred value */ \ UInt32 (*GetTransferredBytes)(IOFireWireLibCommandRef self) ; \ /*! @function GetTargetAddress \ @abstract Get command target address. \ @discussion Availability: (for interfaces obtained with ID) \ <table border="0" rules="all"> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireReadCommandInterfaceID</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireReadCommandInterfaceID_v2</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireWriteCommandInterfaceID</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireWriteCommandInterfaceID_v2</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireReadQuadletCommandInterfaceID</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireWriteQuadletCommandInterfaceID</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireCompareSwapCommandInterfaceID</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireAsyncStreamCommandInterfaceID</code></td> \ <td>NO</td> \ </tr> \ </table> \ @param self The command object interface of interest \ @param outAddr A pointer to an FWAddress to contain the function result. */ \ void (*GetTargetAddress)(IOFireWireLibCommandRef self, FWAddress* outAddr) ; \ /*! @function SetTarget \ @abstract Set command target address \ @discussion Availability: (for interfaces obtained with ID) \ <table border="0" rules="all"> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireReadCommandInterfaceID</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireReadCommandInterfaceID_v2</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireWriteCommandInterfaceID</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireWriteCommandInterfaceID_v2</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireReadQuadletCommandInterfaceID</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireWriteQuadletCommandInterfaceID</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireCompareSwapCommandInterfaceID</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireAsyncStreamCommandInterfaceID</code></td> \ <td>NO</td> \ </tr> \ </table> \ @param self The command object interface of interest \ @param addr A pointer to an FWAddress. */ \ void (*SetTarget)(IOFireWireLibCommandRef self, const FWAddress* addr) ; \ /*! @function SetGeneration \ @abstract Set FireWire bus generation for which the command object shall be valid. \ If the failOnReset attribute has been set, the command will only be considered for \ execution during the bus generation specified by this function. \ @discussion Availability: (for interfaces obtained with ID) \ <table border="0" rules="all"> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireReadCommandInterfaceID</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireReadCommandInterfaceID_v2</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireWriteCommandInterfaceID</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireWriteCommandInterfaceID_v2</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireReadQuadletCommandInterfaceID</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireWriteQuadletCommandInterfaceID</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireCompareSwapCommandInterfaceID</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireAsyncStreamCommandInterfaceID</code></td> \ <td>YES</td> \ </tr> \ </table> \ @param self The command object interface of interest \ @param generation A bus generation. The current bus generation can be obtained \ from IOFireWireDeviceInterface::GetBusGeneration(). */ \ void (*SetGeneration)(IOFireWireLibCommandRef self, UInt32 generation) ; \ /*! @function SetCallback \ @abstract Set the completion handler to be called once the command completes \ asynchronous execution . \ @discussion Availability: (for interfaces obtained with ID) \ <table border="0" rules="all"> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireReadCommandInterfaceID</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireReadCommandInterfaceID_v2</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireWriteCommandInterfaceID</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireWriteCommandInterfaceID_v2</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireReadQuadletCommandInterfaceID</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireWriteQuadletCommandInterfaceID</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireCompareSwapCommandInterfaceID</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireAsyncStreamCommandInterfaceID</code></td> \ <td>YES</td> \ </tr> \ </table> \ @param self The command object interface of interest \ @param inCallback A callback handler. Passing nil forces the command object to \ execute synchronously. */ \ void (*SetCallback)(IOFireWireLibCommandRef self, IOFireWireLibCommandCallback inCallback) ; \ /*! @function SetRefCon \ @abstract Set the user refCon value. This is the user defined value that will be passed \ in the refCon argument to the completion function. \ @discussion Availability: (for interfaces obtained with ID) \ <table border="0" rules="all"> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireReadCommandInterfaceID</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireReadCommandInterfaceID_v2</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireWriteCommandInterfaceID</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireWriteCommandInterfaceID_v2</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireReadQuadletCommandInterfaceID</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireWriteQuadletCommandInterfaceID</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireCompareSwapCommandInterfaceID</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireAsyncStreamCommandInterfaceID</code></td> \ <td>YES</td> \ </tr> \ </table> */ \ void (*SetRefCon)(IOFireWireLibCommandRef self, void* refCon) ; \ /*! @function IsExecuting \ @abstract Is this command object currently executing? \ @discussion Availability: (for interfaces obtained with ID) \ <table border="0" rules="all"> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireReadCommandInterfaceID</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireReadCommandInterfaceID_v2</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireWriteCommandInterfaceID</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireWriteCommandInterfaceID_v2</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireReadQuadletCommandInterfaceID</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireWriteQuadletCommandInterfaceID</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireCompareSwapCommandInterfaceID</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireAsyncStreamCommandInterfaceID</code></td> \ <td>YES</td> \ </tr> \ </table> \ @param self The command object interface of interest \ @result Returns true if the command object is executing. */ \ const Boolean (*IsExecuting)(IOFireWireLibCommandRef self) ; \ /*! Description forthcoming */ \ IOReturn (*Submit)(IOFireWireLibCommandRef self) ; \ /*! @function Submit \ @abstract Submit this command object to FireWire for execution. \ @discussion Availability: (for interfaces obtained with ID) \ <table border="0" rules="all"> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireReadCommandInterfaceID</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireReadCommandInterfaceID_v2</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireWriteCommandInterfaceID</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireWriteCommandInterfaceID_v2</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireReadQuadletCommandInterfaceID</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireWriteQuadletCommandInterfaceID</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireCompareSwapCommandInterfaceID</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireAsyncStreamCommandInterfaceID</code></td> \ <td>YES</td> \ </tr> \ </table> \ @param self The command object interface of interest \ @result An IOReturn result code indicating whether or not the command was successfully \ submitted */ \ /*! @function SubmitWithRefconAndCallback \ @abstract Set the command refCon value and callback handler, and submit the command \ to FireWire for execution. \ @discussion Availability: (for interfaces obtained with ID) \ <table border="0" rules="all"> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireReadCommandInterfaceID</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireReadCommandInterfaceID_v2</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireWriteCommandInterfaceID</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireWriteCommandInterfaceID_v2</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireReadQuadletCommandInterfaceID</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireWriteQuadletCommandInterfaceID</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireCompareSwapCommandInterfaceID</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireAsyncStreamCommandInterfaceID</code></td> \ <td>YES</td> \ </tr> \ </table> \ @param self The command object interface of interest \ @result An IOReturn result code indicating whether or not the command was successfully \ submitted */ \ IOReturn (*SubmitWithRefconAndCallback)(IOFireWireLibCommandRef self, void* refCon, IOFireWireLibCommandCallback inCallback) ;\ /*! @function Cancel \ @abstract Cancel command execution \ @discussion Availability: (for interfaces obtained with ID) \ <table border="0" rules="all"> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireReadCommandInterfaceID</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireReadCommandInterfaceID_v2</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireWriteCommandInterfaceID</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireWriteCommandInterfaceID_v2</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireReadQuadletCommandInterfaceID</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireWriteQuadletCommandInterfaceID</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireCompareSwapCommandInterfaceID</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireAsyncStreamCommandInterfaceID</code></td> \ <td>YES</td> \ </tr> \ </table> \ @param self The command object interface of interest \ @result An IOReturn result code */ \ IOReturn (*Cancel)(IOFireWireLibCommandRef self, IOReturn reason) /*! @parseOnly */ #define IOFIREWIRELIBCOMMAND_C_GUTS_v2 \ /*! @function SetBuffer \ @abstract Set the buffer where read data should be stored. \ @discussion Availability: (for interfaces obtained with ID) \ <table border="0" rules="all"> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireReadCommandInterfaceID</code></td> \ <td>NO</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireReadCommandInterfaceID_v2</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireWriteCommandInterfaceID</code></td> \ <td>NO</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireWriteCommandInterfaceID_v2</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireReadQuadletCommandInterfaceID</code></td> \ <td>NO</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireWriteQuadletCommandInterfaceID</code></td> \ <td>NO</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireCompareSwapCommandInterfaceID</code></td> \ <td>NO</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireAsyncStreamCommandInterfaceID</code></td> \ <td>YES</td> \ </tr> \ </table> \ @param self The command object interface of interest \ @param size Size in bytes of the receive buffer. \ @param buf A pointer to the receive buffer. */ \ void (*SetBuffer)(IOFireWireLibCommandRef self, UInt32 size, void* buf) ; \ /*! @function GetBuffer \ @abstract Set the command refCon value and callback handler, and submit the command \ to FireWire for execution. \ @discussion Availability: (for interfaces obtained with ID) \ <table border="0" rules="all"> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireReadCommandInterfaceID</code></td> \ <td>NO</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireReadCommandInterfaceID_v2</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireWriteCommandInterfaceID</code></td> \ <td>NO</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireWriteCommandInterfaceID_v2</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireReadQuadletCommandInterfaceID</code></td> \ <td>NO</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireWriteQuadletCommandInterfaceID</code></td> \ <td>NO</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireCompareSwapCommandInterfaceID</code></td> \ <td>NO</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireAsyncStreamCommandInterfaceID</code></td> \ <td>YES</td> \ </tr> \ </table> \ @param self The command object interface of interest */ \ void (*GetBuffer)(IOFireWireLibCommandRef self, UInt32* outSize, void** outBuf) ; \ /*! @function SetMaxPacket \ @abstract Set the maximum size in bytes of packets transferred by this command. \ @discussion Availability: (for interfaces obtained with ID) \ <table border="0" rules="all"> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireReadCommandInterfaceID</code></td> \ <td>NO</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireReadCommandInterfaceID_v2</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireWriteCommandInterfaceID</code></td> \ <td>NO</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireWriteCommandInterfaceID_v2</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireReadQuadletCommandInterfaceID</code></td> \ <td>NO</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireWriteQuadletCommandInterfaceID</code></td> \ <td>NO</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireCompareSwapCommandInterfaceID</code></td> \ <td>NO</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireAsyncStreamCommandInterfaceID</code></td> \ <td>YES</td> \ </tr> \ </table> \ @param self The command object interface of interest \ @param maxPacketSize Size in bytes of largest packet that should be transferred \ by this command. \ @result An IOReturn result code indicating whether or not the command was successfully \ submitted */ \ IOReturn (*SetMaxPacket)(IOFireWireLibCommandRef self, IOByteCount maxPacketSize) ; \ /*! @function SetFlags \ @abstract Set flags governing this command's execution. \ @discussion Availability: (for interfaces obtained with ID) \ <table border="0" rules="all"> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireReadCommandInterfaceID</code></td> \ <td>NO</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireReadCommandInterfaceID_v2</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireWriteCommandInterfaceID</code></td> \ <td>NO</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireWriteCommandInterfaceID_v2</code></td> \ <td>YES</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireReadQuadletCommandInterfaceID</code></td> \ <td>NO</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireWriteQuadletCommandInterfaceID</code></td> \ <td>NO</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireCompareSwapCommandInterfaceID</code></td> \ <td>NO</td> \ </tr> \ <tr> \ <td width="20%"></td> \ <td><code>kIOFireWireAsyncStreamCommandInterfaceID</code></td> \ <td>YES</td> \ </tr> \ </table> \ @param self The command object interface of interest \ @param inFlags A UInt32 with bits set corresponding to the flags that should be set \ for this command object. The following values may be used:<br> \ <ul> \ <li>kFWCommandNoFlags -- all flags off</li> \ <li>kFWCommandInterfaceForceNoCopy -- data sent by this command should always be \ received/sent directly from the buffer set with SetBuffer(). Whatever data \ is in the buffer when the command is submitted will be used.</li> \ <li>kFWCommandInterfaceForceCopyAlways -- data will always be copied out of the \ command object data buffer when SetBuffer() is called, up to a maximum \ allowed size (kFWUserCommandSubmitWithCopyMaxBufferBytes). This can result \ in faster data transfer. Changes made to the data buffer contents after \ calling SetBuffer() will be ignored; SetBuffer() should be called whenever \ the data buffer contents change.</li> \ <li>kFWCommandInterfaceSyncExecute -- Setting this flag causes the command object \ to execute synchronously. The calling context will block until the command \ object has completed execution or an error occurs. Using synchronous execution \ can avoid kernel transitions associated with asynchronous completion and often \ remove the need for a state machine.</li> \ <li>kFWCommandInterfaceForceBlockRequest -- Setting this flag causes read and write \ transactions to use block request packets even if the payload is 4 bytes. If this \ flag is not set 4 byte transactions will occur using quadlet transactions.</li> \ </ul>*/ \ void (*SetFlags)(IOFireWireLibCommandRef self, UInt32 inFlags) /*! @parseOnly */ #define IOFIREWIRELIBCOMMAND_C_GUTS_v3 \ /*! @function SetTimeoutDuration \ @abstract Sets the duration of the timeout for this command. \ @param self A reference to the command \ @param duration A timeout value in microseconds \ @result void */ \ void (*SetTimeoutDuration)(IOFireWireLibCommandRef self, UInt32 duration ); \ /*! @function SetMaxRetryCount \ @abstract Sets the maximum number of retries for this command. \ @param self A reference to the command \ @param count The number of retires \ @result void */ \ void (*SetMaxRetryCount)(IOFireWireLibCommandRef self, UInt32 count ); \ /*! @function GetAckCode \ @abstract Gets the most recently received ack code for this transaction. \ @param self A reference to the command \ @result The FireWire ack code. */ \ UInt32 (*GetAckCode)( IOFireWireLibCommandRef self ); \ /*! @function GetResponseCode \ @abstract Gets the most recently received response code for this transaction. \ @param self A reference to the command \ @result The FireWire response code. */ \ UInt32 (*GetResponseCode)( IOFireWireLibCommandRef self ); \ /*! @function SetMaxPacketSpeed \ @abstract Gets the most recently received ack code for this transaction. \ @param self A reference to the command \ @param speed the desired maximum packet speed \ @result void */ \ void (*SetMaxPacketSpeed)( IOFireWireLibCommandRef self, IOFWSpeed speed ); \ /*! @function GetRefCon \ @abstract Gets the refcon associated with this command \ @param self A reference to the command \ @result void */ \ void * (*GetRefCon)( IOFireWireLibCommandRef self ) /*! @class @abstract IOFireWireLib command object. @discussion Represents an object that is configured and submitted to issue synchronous and asynchronous bus commands. This is a superclass containing all command object functionality not specific to any kind of bus transaction. Note that data may not always be transferred to or from the data buffer for command objects at the time the command is submitted. In some cases the transfer may happen as soon as SetBuffer() (below, v2 interfaces and newer) is called. You can use the SetFlags() call (below, v2 interfaces and newer) to control this behavior. */ typedef struct IOFireWireCommandInterface_t { IUNKNOWN_C_GUTS ; /*! Interface version */ UInt32 version; /*! Interface revision */ UInt32 revision; /* IMPORTANT: Do not add HeaderDoc markup to the following symbols; they contain HeaderDoc markup, and that would be bad. */ IOFIREWIRELIBCOMMAND_C_GUTS ; // version 2 interfaces: (appear in IOFireWireReadCommandInterface_v2 and IOFireWireWriteCommandInterface_v2) IOFIREWIRELIBCOMMAND_C_GUTS_v2 ; IOFIREWIRELIBCOMMAND_C_GUTS_v3 ; } IOFireWireCommandInterface ; /*! @class @abstract IOFireWireLib block read command object. @discussion Represents an object that is configured and submitted to issue synchronous and asynchronous block read commands. This interface contains all methods of IOFireWireCommandInterface. This interface will contain all v2 methods of IOFireWireCommandInterface when instantiated as v2 or newer. */ typedef struct IOFireWireReadCommandInterface_t { IUNKNOWN_C_GUTS ; /*! Interface version. */ UInt32 version; /*! Interface revision. */ UInt32 revision; IOFIREWIRELIBCOMMAND_C_GUTS ; // following functions // available only in IOFireWireReadCommandInterface interface v2 and newer IOFIREWIRELIBCOMMAND_C_GUTS_v2 ; IOFIREWIRELIBCOMMAND_C_GUTS_v3 ; } IOFireWireReadCommandInterface ; /*! @class @abstract IOFireWireLib block read command object. @discussion Represents an object that is configured and submitted to issue synchronous and asynchronous block read commands. This interface contains all methods of IOFireWireCommandInterface. This interface will contain all v2 methods of IOFireWireCommandInterface when instantiated as v2 or newer. */ typedef struct IOFireWireWriteCommandInterface_t { IUNKNOWN_C_GUTS ; /*! Interface version. */ UInt32 version; /*! Interface revision. */ UInt32 revision; IOFIREWIRELIBCOMMAND_C_GUTS ; // following functions // available only in IOFireWireWriteCommandInterface_v2 and newer IOFIREWIRELIBCOMMAND_C_GUTS_v2 ; IOFIREWIRELIBCOMMAND_C_GUTS_v3 ; } IOFireWireWriteCommandInterface ; /*! @class Description forthcoming */ typedef struct IOFireWireCompareSwapCommandInterface_t { IUNKNOWN_C_GUTS ; /*! Interface version. */ UInt32 version; /*! Interface revision. */ UInt32 revision; IOFIREWIRELIBCOMMAND_C_GUTS ; /*! @function SetValues @abstract Set values for 32-bit compare swap operation. Calling this function will make the command object perform 32-bit compare swap transactions on the bus. To perform 64-bit compare swap operations, use the SetValues64() call, below. @discussion Available in v2 and newer. @param self The command object interface of interest @param cmpVal The value expected at the address targeted by this command object @param newVal The value to be written at the address targeted by this command object */ void (*SetValues)(IOFireWireLibCompareSwapCommandRef self, UInt32 cmpVal, UInt32 newVal) ; // --- v2 --- /*! @function SetValues64 @abstract Set values for 64-bit compare swap operation. Calling this function will make the command object perform 64-bit compare swap transactions on the bus. To perform 32-bit compare swap operations, use the SetValues() call, above. @discussion Available in v2 and newer. @param self The command object interface of interest @param cmpVal The value expected at the address targeted by this command object @param newVal The value to be written at the address targeted by this command object */ void (*SetValues64)(IOFireWireLibCompareSwapCommandRef self, UInt64 cmpVal, UInt64 newVal) ; /*! @function DidLock @abstract Was the last lock operation successful? @discussion Available in v2 and newer. @param self The command object interface of interest @result Returns true if the last lock operation performed by this command object was successful, false otherwise. */ Boolean (*DidLock)(IOFireWireLibCompareSwapCommandRef self) ; /*! @function Locked @abstract Get the 32-bit value returned on the last compare swap operation. @discussion Available in v2 and newer. @param self The command object interface of interest @param oldValue A pointer to contain the value returned by the target of this command on the last compare swap operation @result Returns kIOReturnBadArgument if the last compare swap operation performed was 64-bit. */ IOReturn (*Locked)(IOFireWireLibCompareSwapCommandRef self, UInt32* oldValue) ; /*! @function Locked64 @abstract Get the 64-bit value returned on the last compare swap operation. @discussion Available in v2 and newer. @param self The command object interface of interest @param oldValue A pointer to contain the value returned by the target of this command on the last compare swap operation @result Returns kIOReturnBadArgument if the last compare swap performed was 32-bit. */ IOReturn (*Locked64)(IOFireWireLibCompareSwapCommandRef self, UInt64* oldValue) ; /*! @function SetFlags @abstract Set flags governing this command's execution. @discussion Available in v2 and newer. Same as SetFlags() above. @param self The command object interface of interest. @param inFlags A UInt32 with bits set corresponding to the flags that should be set. */ void (*SetFlags)(IOFireWireLibCompareSwapCommandRef self, UInt32 inFlags) ; } IOFireWireCompareSwapCommandInterface ; /*! @class Description forthcoming */ typedef struct IOFireWireCompareSwapCommandInterface_v3_t { IUNKNOWN_C_GUTS ; /*! Interface version. */ UInt32 version; /*! Interface version. */ UInt32 revision; IOFIREWIRELIBCOMMAND_C_GUTS; IOFIREWIRELIBCOMMAND_C_GUTS_v2; IOFIREWIRELIBCOMMAND_C_GUTS_v3; /*! @function SetValues @abstract Set values for 32-bit compare swap operation. Calling this function will make the command object perform 32-bit compare swap transactions on the bus. To perform 64-bit compare swap operations, use the SetValues64() call, below. @discussion Available in v2 and newer. @param self The command object interface of interest @param cmpVal The value expected at the address targeted by this command object @param newVal The value to be written at the address targeted by this command object */ void (*SetValues)(IOFireWireLibCompareSwapCommandV3Ref self, UInt32 cmpVal, UInt32 newVal) ; // --- v2 --- /*! @function SetValues64 @abstract Set values for 64-bit compare swap operation. Calling this function will make the command object perform 64-bit compare swap transactions on the bus. To perform 32-bit compare swap operations, use the SetValues() call, above. @discussion Available in v2 and newer. @param self The command object interface of interest @param cmpVal The value expected at the address targeted by this command object @param newVal The value to be written at the address targeted by this command object */ void (*SetValues64)(IOFireWireLibCompareSwapCommandV3Ref self, UInt64 cmpVal, UInt64 newVal) ; /*! @function DidLock @abstract Was the last lock operation successful? @discussion Available in v2 and newer. @param self The command object interface of interest @result Returns true if the last lock operation performed by this command object was successful, false otherwise. */ Boolean (*DidLock)(IOFireWireLibCompareSwapCommandV3Ref self) ; /*! @function Locked @abstract Get the 32-bit value returned on the last compare swap operation. @discussion Available in v2 and newer. @param self The command object interface of interest @param oldValue A pointer to contain the value returned by the target of this command on the last compare swap operation @result Returns kIOReturnBadArgument if the last compare swap operation performed was 64-bit. */ IOReturn (*Locked)(IOFireWireLibCompareSwapCommandV3Ref self, UInt32* oldValue) ; /*! @function Locked64 @abstract Get the 64-bit value returned on the last compare swap operation. @discussion Available in v2 and newer. @param self The command object interface of interest @param oldValue A pointer to contain the value returned by the target of this command on the last compare swap operation @result Returns kIOReturnBadArgument if the last compare swap performed was 32-bit. */ IOReturn (*Locked64)(IOFireWireLibCompareSwapCommandV3Ref self, UInt64* oldValue) ; } IOFireWireCompareSwapCommandInterface_v3 ; /*! @class Description forthcoming */ typedef struct IOFireWirePHYCommandInterface_t { IUNKNOWN_C_GUTS ; /*! Interface version. */ UInt32 version; /*! Interface revision. */ UInt32 revision; IOFIREWIRELIBCOMMAND_C_GUTS; IOFIREWIRELIBCOMMAND_C_GUTS_v2; IOFIREWIRELIBCOMMAND_C_GUTS_v3; /*! @function SetDataQuads @abstract Set the 2 quadlets of data to be sent in a PHY packet. @discussion Available in v1 and newer. @param self The command object interface of interest @param data1 The value of the first quad of the phy packet @param data2 The value of the second quad of the phy packet */ void (*SetDataQuads)( IOFireWireLibPHYCommandRef self, UInt32 data1, UInt32 data2 ); } IOFireWirePHYCommandInterface; /*! @class Description forthcoming */ typedef struct IOFireWireAsyncStreamCommandInterface_t { IUNKNOWN_C_GUTS ; /*! Interface version. */ UInt32 version; /*! Interface revision. */ UInt32 revision; IOFIREWIRELIBCOMMAND_C_GUTS; IOFIREWIRELIBCOMMAND_C_GUTS_v2; IOFIREWIRELIBCOMMAND_C_GUTS_v3; /*! @function SetChannel @abstract Set the new channel to transmit the AsyncStream command. @discussion Available in v1 and newer. @param self The command object interface of interest @param channel The channel for AsyncStream command transmit.*/ void (*SetChannel)( IOFireWireLibAsyncStreamCommandRef self, UInt32 channel ); /*! @function SetSyncBits @abstract Set the sync bits for the AsynStream packets. @discussion Available in v1 and newer. @param self The command object interface of interest @param sync The value for sync bits in the AsyncStream packet */ void (*SetSyncBits)( IOFireWireLibAsyncStreamCommandRef self, UInt16 sync ); /*! @function SetTagBits @abstract Set the tag bits for the AsynStream packets. @discussion Available in v1 and newer. @param self The command object interface of interest @param tag The value for tag bits in the AsyncStream packet */ void (*SetTagBits)( IOFireWireLibAsyncStreamCommandRef self, UInt16 tag ); } IOFireWireAsyncStreamCommandInterface; /*! @class @abstract IOFireWireReadQuadletCommandInterface -- IOFireWireLib quadlet read command object. @discussion Obsolete; do not use. Use IOFireWireReadCommandInterface v2 or newer and its function SetMaxPacket() */ typedef struct IOFireWireReadQuadletCommandInterface_t { IUNKNOWN_C_GUTS ; /*! Interface version. */ UInt32 version; /*! Interface revision. */ UInt32 revision; IOFIREWIRELIBCOMMAND_C_GUTS ; /*! @function SetQuads @abstract Set destination for read data @param self The command object interface of interest @param inQuads An array of quadlets @param inNumQuads Number of quadlet in 'inQuads' */ void (*SetQuads)(IOFireWireLibReadQuadletCommandRef self, UInt32 inQuads[], UInt32 inNumQuads) ; } IOFireWireReadQuadletCommandInterface ; /*! @class @abstract IOFireWireLib quadlet read command object. @discussion Obsolete; do not use. Use IOFireWireWriteCommandInterface v2 or newer and its function SetMaxPacket() */ typedef struct IOFireWireWriteQuadletCommandInterface_t { IUNKNOWN_C_GUTS ; /*! Interface version. */ UInt32 version; /*! Interface revision. */ UInt32 revision; IOFIREWIRELIBCOMMAND_C_GUTS ; /*! IOFireWireLibWriteQuadletCommandRef */ void (*SetQuads)(IOFireWireLibWriteQuadletCommandRef self, UInt32 inQuads[], UInt32 inNumQuads) ; } IOFireWireWriteQuadletCommandInterface ; #pragma mark - #pragma mark CONFIG DIRECTORY INTERFACE // ============================================================ // IOFireWireConfigDirectoryInterface // ============================================================ /*! @class @abstract IOFireWireLib device config ROM browsing interface @discussion Represents an interface to the config ROM of a remote device. You can use the methods of this interface to browser the ROM and obtain key values. You can also create additional IOFireWireConfigDirectoryInterface's to represent subdirectories within the ROM.*/ typedef struct IOFireWireConfigDirectoryInterface_t { IUNKNOWN_C_GUTS ; /*! Interface version. */ UInt32 version; /*! Interface revision. */ UInt32 revision ; /*! @function Update @abstract Causes the ROM data to be updated through the specified byte offset. This function should not be called in normal usage. @param self The config directory interface of interest @param inOffset Offset in bytes indicating length of ROM to be updated. @result An IOReturn result code */ IOReturn (*Update) ( IOFireWireLibConfigDirectoryRef self, UInt32 inOffset) ; /*! Description forthcoming */ IOReturn (*GetKeyType) ( IOFireWireLibConfigDirectoryRef self, int inKey, IOConfigKeyType* outType); /*! Description forthcoming */ IOReturn (*GetKeyValue_UInt32) ( IOFireWireLibConfigDirectoryRef self, int inKey, UInt32* outValue, CFStringRef* outText); /*! Description forthcoming */ IOReturn (*GetKeyValue_Data) ( IOFireWireLibConfigDirectoryRef self, int inKey, CFDataRef* outValue, CFStringRef* outText); /*! Description forthcoming */ IOReturn (*GetKeyValue_ConfigDirectory) ( IOFireWireLibConfigDirectoryRef self, int inKey, IOFireWireLibConfigDirectoryRef* outValue, REFIID iid, CFStringRef* outText); /*! Description forthcoming */ IOReturn (*GetKeyOffset_FWAddress) ( IOFireWireLibConfigDirectoryRef self, int inKey, FWAddress* outValue, CFStringRef* text); /*! Description forthcoming */ IOReturn (*GetIndexType) ( IOFireWireLibConfigDirectoryRef self, int inIndex, IOConfigKeyType* type); /*! Description forthcoming */ IOReturn (*GetIndexKey) ( IOFireWireLibConfigDirectoryRef self, int inIndex, int * key); /*! Description forthcoming */ IOReturn (*GetIndexValue_UInt32) ( IOFireWireLibConfigDirectoryRef self, int inIndex, UInt32 * value); /*! Description forthcoming */ IOReturn (*GetIndexValue_Data) ( IOFireWireLibConfigDirectoryRef self, int inIndex, CFDataRef * value); /*! Description forthcoming */ IOReturn (*GetIndexValue_String) ( IOFireWireLibConfigDirectoryRef self, int inIndex, CFStringRef* outValue); /*! Description forthcoming */ IOReturn (*GetIndexValue_ConfigDirectory) ( IOFireWireLibConfigDirectoryRef self, int inIndex, IOFireWireLibConfigDirectoryRef* outValue, REFIID iid); /*! Description forthcoming */ IOReturn (*GetIndexOffset_FWAddress) ( IOFireWireLibConfigDirectoryRef self, int inIndex, FWAddress* outValue); /*! Description forthcoming */ IOReturn (*GetIndexOffset_UInt32) ( IOFireWireLibConfigDirectoryRef self, int inIndex, UInt32* outValue); /*! Description forthcoming */ IOReturn (*GetIndexEntry) ( IOFireWireLibConfigDirectoryRef self, int inIndex, UInt32* outValue); /*! Description forthcoming */ IOReturn (*GetSubdirectories) ( IOFireWireLibConfigDirectoryRef self, io_iterator_t* outIterator); /*! Description forthcoming */ IOReturn (*GetKeySubdirectories) ( IOFireWireLibConfigDirectoryRef self, int inKey, io_iterator_t* outIterator); /*! Description forthcoming */ IOReturn (*GetType) ( IOFireWireLibConfigDirectoryRef self, int* outType) ; /*! Description forthcoming */ IOReturn (*GetNumEntries) ( IOFireWireLibConfigDirectoryRef self, int* outNumEntries) ; } IOFireWireConfigDirectoryInterface ; /*! Description forthcoming */ CF_INLINE IOVirtualRange IOVirtualRangeMake( IOVirtualAddress address, IOByteCount length ) { IOVirtualRange range ; range.address = address ; range.length = length ; return range ; } #pragma mark - #pragma mark VECTOR COMMAND INTERFACE // ============================================================ // IOFireWireVectorCommandInterface // ============================================================ /*! @class @abstract IOFireWireLib command object for grouping commands execution. @discussion Read and Write commands can be attached in order to the vector command. When the vector command is submitted all the commands are sent to the kernel for execution. When all the commands in a vector command are complete the vector command's completion is called. The advantage over submitting and completeing each command simultaneously is that only one kernel transition will be used for submission and one for completion, regardless of the number of commands in the vector.*/ typedef struct IOFireWireLibVectorCommandInterface_t { IUNKNOWN_C_GUTS ; /*! Interface version. */ UInt32 version; /*! Interface revision. */ UInt32 revision; /*! @function Submit @abstract Submit this command object to FireWire for execution. @param self A reference to the vector command object @result An IOReturn result code */ IOReturn (*Submit)(IOFireWireLibVectorCommandRef self); /*! @function Submit @abstract Submit this command object to FireWire for execution. @discussion A convienence method to set the callback and refcon and then submit. @param self A reference to the vector command object @param refCon A reference constant for 3rd party use. This is the same refcon set with SetRefCon and retreived with GetRefCon. @param inCallback A callback function to be called upon command completion. @result An IOReturn result code */ IOReturn (*SubmitWithRefconAndCallback)(IOFireWireLibVectorCommandRef self, void* refCon, IOFireWireLibCommandCallback inCallback); /*! @function IsExecuting @abstract Checks if the vector command is currently executing. @param self A reference to the vector command object @result True if the command is executing, false otherwise */ Boolean (*IsExecuting)(IOFireWireLibVectorCommandRef self); /*! @function SetCallback @abstract Set the callback routine for this command. @param self A reference to the vector command object @param inCallback A callback function to be called upon command completion. @result void */ void (*SetCallback)(IOFireWireLibVectorCommandRef self, IOFireWireLibCommandCallback inCallback); /*! @function SetRefCon @abstract Set the reference constant for this command. @param self A reference to the vector command object @param refCon A reference constant for 3rd party use. @result void */ void (*SetRefCon)(IOFireWireLibVectorCommandRef self, void* refCon); /*! @function GetRefCon @abstract Get the reference constant for this command. @param self A reference to the vector command object @result The reference contant set in SetRefCon */ void * (*GetRefCon)(IOFireWireLibVectorCommandRef self); /*! @function SetFlags @abstract Set flags governing this command's execution. @param self A reference to the vector command object @param inFlags A UInt32 with bits set corresponding to the flags that should be set for this command object. The following values may be used:<br> <ul> <li>kFWCommandNoFlags -- all flags off</li> <li>kFWCommandInterfaceSyncExecute -- Setting this flag causes the command object to execute synchronously. The calling context will block until the command object has completed execution or an error occurs. Using synchronous execution can avoid kernel transitions associated with asynchronous completion and often remove the need for a state machine.</li> <li>kFWVectorCommandInterfaceOrdered - Normally all commands in a vector are executed simultaneously. Setting this flag will dispatch a command only after the prior command has completed. </ul> @result void */ void (*SetFlags)(IOFireWireLibVectorCommandRef self, UInt32 inFlags); /*! @function GetFlags @abstract Get the flags currently set for this command. @param self A reference to the vector command object @result The flags set in SetFlags */ UInt32 (*GetFlags)(IOFireWireLibVectorCommandRef self); /*! @function EnsureCapacity @abstract Sets the number of commands this vector can hold. @discussion The vector can grow dynamically, but for performance reasons developers may want the storage preallocated for a certain number of commmands @param self A reference to the vector command object @param capacity The number of commands this vector command should expect to hold @result An IOReturn result code */ IOReturn (*EnsureCapacity)(IOFireWireLibVectorCommandRef self, UInt32 capacity); /*! @function AddCommand @abstract Adds a command to the vector command. @param self A reference to the vector command object @param command A reference to the command to add @result An IOReturn result code */ void (*AddCommand)(IOFireWireLibVectorCommandRef self, IOFireWireLibCommandRef command); /*! @function RemoveCommand @abstract Removes a command to the vector command. @param self A reference to the vector command object @param command A reference to the command to be removed @result An IOReturn result code */ void (*RemoveCommand)(IOFireWireLibVectorCommandRef self, IOFireWireLibCommandRef command); /*! @function InsertCommandAtIndex @abstract Inserts a command at a given index. Commands at and after this index will be moved to their next sequential index. @param self A reference to the vector command object @param command A reference to the command to be inserted @param index The index to insert the command at. */ void (*InsertCommandAtIndex)(IOFireWireLibVectorCommandRef self, IOFireWireLibCommandRef command, UInt32 index); /*! @function GetCommandAtIndex @abstract Returns the command at a given index. @discussion Returns kIOReturnBadArgument if the index is out of bounds. @param self A reference to the vector command object @param index The index to return a command from @result The IOFireWireLibCommandRef at the specified index on return */ IOFireWireLibCommandRef (*GetCommandAtIndex)(IOFireWireLibVectorCommandRef self, UInt32 index); /*! @function GetIndexOfCommand @abstract Returns the index of the specified command. @discussion Returns kIOReturnNotFound if the command does not exist in this vector. @param self A reference to the vector command object @param command The command in question @result The index of the specified command */ UInt32 (*GetIndexOfCommand)(IOFireWireLibVectorCommandRef self, IOFireWireLibCommandRef command); /*! @function RemoveCommandAtIndex @abstract Removes the command at a give index. Commands at and afte this index will be moved to their previous sequential index. @discussion Returns kIOReturnBadArgument if the index is out of bounds. @param self A reference to the vector command object @param index Will be set to the index of the specified command. */ void (*RemoveCommandAtIndex)(IOFireWireLibVectorCommandRef self, UInt32 index); /*! @function RemoveAllCommands @abstract Removes all commands from the vector. @param self A reference to the vector command object */ void (*RemoveAllCommands)(IOFireWireLibVectorCommandRef self); /*! @function GetCommandCount @abstract Returns the number of commands currently in this vector. @param self A reference to the vector command object @result UInt32 The number of commands in this vector */ UInt32 (*GetCommandCount)(IOFireWireLibVectorCommandRef self); } IOFireWireLibVectorCommandInterface; #pragma mark - #pragma mark PHY PACKET LISTENER INTERFACE // ============================================================ // IOFireWireLibPHYPacketListenerInterface Interface // ============================================================ /*! @class @discussion Represents and provides management functions for a phy packet listener object. */ typedef struct IOFireWireLibPHYPacketListenerInterface_t { IUNKNOWN_C_GUTS ; /*! Interface version. */ UInt16 version; /*! Interface revision. */ UInt16 revision; /*! @function SetListenerCallback @abstract Set the callback that should be called to handle incoming phy packets @param self The PHY packet listener object. @param inCallback The callback to set. */ void (*SetListenerCallback)( IOFireWireLibPHYPacketListenerRef self, IOFireWireLibPHYPacketCallback inCallback ); /*! @function SetSkippedPacketCallback @abstract Set the callback that should be called when incoming phy packets are dropped by the listener space. @param self The PHY packet listener object. @param inCallback The callback to set. */ void (*SetSkippedPacketCallback)( IOFireWireLibPHYPacketListenerRef self, IOFireWireLibPHYPacketSkippedCallback inCallback ); /*! @function NotificationIsOn @abstract Is notification on? @param self The PHY packet listener object. @result Returns true if packet notifications for this listener are active */ Boolean (*NotificationIsOn)( IOFireWireLibPHYPacketListenerRef self ); /*! @function TurnOnNotification @abstract Try to turn on packet notifications for this listener. @param self The PHY packet listener object. @result Returns kIOReturnSuccess if successful */ IOReturn (*TurnOnNotification)( IOFireWireLibPHYPacketListenerRef self ); /*! @function TurnOffNotification @abstract Turn packet notification off. @param self The PHY packet listener object. */ void (*TurnOffNotification)( IOFireWireLibPHYPacketListenerRef self ); /*! @function ClientCommandIsComplete @abstract Notify the PHY packet listener object that a packet notification handler has completed. @discussion Packet notifications are received one at a time, in order. This function must be called after a packet handler has completed its work. @param self The PHY packet listener object. @param commandID The ID of the packet notification being completed. This is the same ID that was passed when a packet notification handler is called. */ void (*ClientCommandIsComplete)(IOFireWireLibPHYPacketListenerRef self, FWClientCommandID commandID ); // --- accessors ---------- /*! @function SetRefCon @abstract Sets the user refCon value for this interface. @param self The PHY packet listener object. @param refcon the refcon */ void (*SetRefCon)( IOFireWireLibPHYPacketListenerRef self, void * refcon ); /*! @function GetRefCon @abstract Returns the user refCon value for thisinterface. @param self The PHY packet listener object. @result returns the refcon */ void* (*GetRefCon)( IOFireWireLibPHYPacketListenerRef self ); /*! @function SetFlags @abstract set flags for the listener. @param self The PHY packet listener object. @param flags No current flags are defined. */ void (*SetFlags)( IOFireWireLibPHYPacketListenerRef self, UInt32 flags ); /*! @function GetFlags @abstract get the flags of listener. @param self The PHY packet listener object. @result flags No current flags are defined. */ UInt32 (*GetFlags)( IOFireWireLibPHYPacketListenerRef self ); } IOFireWireLibPHYPacketListenerInterface; #endif // ifndef KERNEL #endif //__IOFireWireLib_H__
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/pwr_mgt/IOPM.h
/* * Copyright (c) 1998-2005 Apple Computer, Inc. All rights reserved. * * @APPLE_OSREFERENCE_LICENSE_HEADER_START@ * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. The rights granted to you under the License * may not be used to create, or enable the creation or redistribution of, * unlawful or unlicensed copies of an Apple operating system, or to * circumvent, violate, or enable the circumvention or violation of, any * terms of an Apple operating system software license agreement. * * Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_OSREFERENCE_LICENSE_HEADER_END@ */ #ifndef _IOKIT_IOPM_H #define _IOKIT_IOPM_H #include <IOKit/IOTypes.h> #include <IOKit/IOMessage.h> #include <IOKit/IOReturn.h> /*! @header IOPM.h * @abstract Defines power management constants and keys used by both in-kernel and user space power management. * @discussion IOPM.h defines a range of power management constants used in several in-kernel and user space APIs. Most significantly, the IOPMPowerFlags used to specify the fields of an IOPMPowerState struct are defined here. * * Most of the constants defined in IOPM.h are deprecated or for Apple internal use only, and are not elaborated on in headerdoc. */ enum { kIOPMMaxPowerStates = 10, IOPMMaxPowerStates = kIOPMMaxPowerStates }; /*! @enum IOPMPowerFlags * @abstract Bits are used in defining capabilityFlags, inputPowerRequirements, and outputPowerCharacter in the IOPMPowerState structure. * @discussion These bits may be bitwise-OR'd together in the IOPMPowerState capabilityFlags field, the outputPowerCharacter field, and/or the inputPowerRequirement field. * * The comments clearly mark whether each flag should be used in the capabilityFlags field, outputPowerCharacter field, and inputPowerRequirement field, or all three. * * The value of capabilityFlags, inputPowerRequirement or outputPowerCharacter may be 0. Most drivers implement their 'OFF' state, used when asleep, by defininf each of the 3 fields as 0. * * The bits listed below are only the most common bits used to define a device's power states. Your device's IO family may require that your device specify other input or output power flags to interact properly. Consult family-specific documentation to determine if your IOPower plane parents or children require other power flags; they probably don't. * * @constant kIOPMPowerOn Indicates the device is on, requires power, and provides power. Useful as a: Capability, InputPowerRequirement, OutputPowerCharacter * * @constant kIOPMDeviceUsable Indicates the device is usable in this state. Useful only as a Capability * * @constant kIOPMLowPower * Indicates device is in a low power state. May be bitwis-OR'd together * with kIOPMDeviceUsable flag, to indicate the device is still usable. * * A device with a capability of kIOPMLowPower may: * Require either 0 or kIOPMPowerOn from its power parent * Offer either kIOPMLowPower, kIOPMPowerOn, or 0 (no power at all) * to its power plane children. * * Useful only as a Capability, although USB drivers should consult USB family documentation for other valid circumstances to use the kIOPMLowPower bit. * * @constant kIOPMPreventIdleSleep * In the capability field of a power state, disallows idle system sleep while the device is in that state. * * For example, displays and disks set this capability for their ON power state; since the system may not idle sleep while the display (and thus keyboard or mouse) or the disk is active. * * Useful only as a Capability. * * @constant kIOPMSleepCapability * Used only by certain IOKit Families (USB). Not defined or used by generic Power Management. Read your family documentation to see if you should define a powerstate using these capabilities. * * @constant kIOPMRestartCapability * Used only by certain IOKit Families (USB). Not defined or used by generic Power Management. Read your family documentation to see if you should define a powerstate using these capabilities. * * @constant kIOPMSleep * Used only by certain IOKit Families (USB). Not defined or used by generic Power Management. Read your family documentation to see if you should define a powerstate using these capabilities. * * @constant kIOPMRestart * Used only by certain IOKit Families (USB). Not defined or used by generic Power Management. Read your family documentation to see if you should define a powerstate using these capabilities. * * @constant kIOPMInitialDeviceState * Indicates the initial power state for the device. If <code>initialPowerStateForDomainState()</code> returns a power state with this flag set in the capability field, then the initial power change is performed without calling the driver's <code>setPowerState()</code>. * * @constant kIOPMRootDomainState * An indication that the power flags represent the state of the root power * domain. This bit must not be set in the IOPMPowerState structure. * Power Management may pass this bit to initialPowerStateForDomainState() * to map from a global system state to the desired device state. */ typedef unsigned long IOPMPowerFlags; enum { kIOPMPowerOn = 0x00000002, kIOPMDeviceUsable = 0x00008000, kIOPMLowPower = 0x00010000, kIOPMPreventIdleSleep = 0x00000040, kIOPMSleepCapability = 0x00000004, kIOPMRestartCapability = 0x00000080, kIOPMSleep = 0x00000001, kIOPMRestart = 0x00000080, kIOPMInitialDeviceState = 0x00000100, kIOPMRootDomainState = 0x00000200 }; /* * Private IOPMPowerFlags * * For Apple use only * Not for use with non-Apple drivers * Their behavior is undefined */ enum { kIOPMClockNormal = 0x0004, kIOPMClockRunning = 0x0008, kIOPMPreventSystemSleep = 0x0010, kIOPMDoze = 0x0400, kIOPMChildClamp = 0x0080, kIOPMChildClamp2 = 0x0200, kIOPMNotPowerManaged = 0x0800 }; /* * Deprecated IOPMPowerFlags * Their behavior is undefined when used in IOPMPowerState * Capability, InputPowerRequirement, or OutputPowerCharacter fields. */ enum { kIOPMMaxPerformance = 0x4000, kIOPMPassThrough = 0x0100, kIOPMAuxPowerOn = 0x0020, kIOPMNotAttainable = 0x0001, kIOPMContextRetained = 0x2000, kIOPMConfigRetained = 0x1000, kIOPMStaticPowerValid = 0x0800, kIOPMSoftSleep = 0x0400, kIOPMCapabilitiesMask = kIOPMPowerOn | kIOPMDeviceUsable | kIOPMMaxPerformance | kIOPMContextRetained | kIOPMConfigRetained | kIOPMSleepCapability | kIOPMRestartCapability }; /* * Support for old names of IOPMPowerFlag constants */ enum { IOPMNotAttainable = kIOPMNotAttainable, IOPMPowerOn = kIOPMPowerOn, IOPMClockNormal = kIOPMClockNormal, IOPMClockRunning = kIOPMClockRunning, IOPMAuxPowerOn = kIOPMAuxPowerOn, IOPMDeviceUsable = kIOPMDeviceUsable, IOPMMaxPerformance = kIOPMMaxPerformance, IOPMContextRetained = kIOPMContextRetained, IOPMConfigRetained = kIOPMConfigRetained, IOPMNotPowerManaged = kIOPMNotPowerManaged, IOPMSoftSleep = kIOPMSoftSleep }; enum { kIOPMNextHigherState = 1, kIOPMHighestState = 2, kIOPMNextLowerState = 3, kIOPMLowestState = 4 }; enum { IOPMNextHigherState = kIOPMNextHigherState, IOPMHighestState = kIOPMHighestState, IOPMNextLowerState = kIOPMNextLowerState, IOPMLowestState = kIOPMLowestState }; // Internal commands used by power managment command queue enum { kIOPMBroadcastAggressiveness = 1, kIOPMUnidleDevice }; // Power consumption unknown value enum { kIOPMUnknown = 0xFFFF }; /******************************************************************************* * * Root Domain property keys of interest * ******************************************************************************/ /* AppleClamshellState * reflects the state of the clamshell (lid) on a portable. * It has a boolean value. * true == clamshell is closed * false == clamshell is open * not present == no clamshell on this hardware */ #define kAppleClamshellStateKey "AppleClamshellState" /* AppleClamshellCausesSleep * reflects the clamshell close behavior on a portable. * It has a boolean value. * true == system will sleep when clamshell is closed * false == system will not sleep on clamshell close * (typically external display mode) * not present == no clamshell on this hardware */ #define kAppleClamshellCausesSleepKey "AppleClamshellCausesSleep" /* kIOPMSleepWakeUUIDKey * Key refers to a CFStringRef that will uniquely identify * a sleep/wake cycle for logging & tracking. * The key becomes valid at the beginning of a sleep cycle - before we * initiate any sleep/wake notifications. * The key becomes invalid at the completion of a system wakeup. The * property will not be present in the IOPMrootDomain's registry entry * when it is invalid. * * See IOPMrootDomain notification kIOPMMessageSleepWakeUUIDChange */ #define kIOPMSleepWakeUUIDKey "SleepWakeUUID" /* kIOPMBootSessionUUIDKey * Key refers to a CFStringRef that will uniquely identify * a boot cycle. * The key becomes valid at boot time and remains valid * till shutdown. The property value will remain same across * sleep/wake/hibernate cycle. */ #define kIOPMBootSessionUUIDKey "BootSessionUUID" /* kIOPMDeepSleepEnabledKey * Indicates the Deep Sleep enable state. * It has a boolean value. * true == Deep Sleep is enabled * false == Deep Sleep is disabled * not present == Deep Sleep is not supported on this hardware */ #define kIOPMDeepSleepEnabledKey "Standby Enabled" /* kIOPMDeepSleepDelayKey * Key refers to a CFNumberRef that represents the delay in seconds before * entering Deep Sleep state when on battery power and when remaining * battery capacity is below a particular threshold (e.g., 50%.) The * property is not present if Deep Sleep is unsupported. */ #define kIOPMDeepSleepDelayKey "Standby Delay" /* kIOPMDeepSleepDelayHighKey * Key refers to a CFNumberRef that represents the delay in seconds before * entering Deep Sleep state. This is used instead of the value specified by * kIOPMDeepSleepDelayKey if the remaining battery capacity is above a * particular threshold (e.g. 50%) or on AC power. The property is not * present if Deep Sleep is unsupported. */ #define kIOPMDeepSleepDelayHighKey "High Standby Delay" /* kIOPMLowBatteryThresholdKey * Key refers to a CFNumberRef that represents the threshold used to choose * between the normal deep sleep delay and the high deep sleep delay (as a * percentage of total battery capacity remaining.) The property is not * present if Deep Sleep is unsupported. */ #define kIOPMStandbyBatteryThresholdKey "Standby Battery Threshold" /* kIOPMDestroyFVKeyOnStandbyKey * Specifies if FileVault key can be stored when going to standby mode * It has a boolean value, * true == Destroy FV key when going to standby mode * false == Retain FV key when going to standby mode * not present == Retain FV key when going to standby mode */ #define kIOPMDestroyFVKeyOnStandbyKey "DestroyFVKeyOnStandby" /******************************************************************************* * * Properties that can control power management behavior * ******************************************************************************/ /* kIOPMResetPowerStateOnWakeKey * If an IOService publishes this key with the value of kOSBooleanTrue, * then PM will disregard the influence from changePowerStateToPriv() or * any activity tickles that occurred before system sleep when resolving * the initial device power state on wake. Influences from power children * and changePowerStateTo() are not eliminated. At the earliest opportunity * upon system wake, PM will query the driver for a new power state to be * installed as the initial changePowerStateToPriv() influence, by calling * initialPowerStateForDomainState() with both kIOPMRootDomainState and * kIOPMPowerOn flags set. The default implementation will always return * the lowest power state. Drivers can override this default behavior to * immediately raise the power state when there are work blocked on the * power change, and cannot afford to wait until the next activity tickle. * This property should be statically added to a driver's plist or set at * runtime before calling PMinit(). */ #define kIOPMResetPowerStateOnWakeKey "IOPMResetPowerStateOnWake" /******************************************************************************* * * Driver PM Assertions * ******************************************************************************/ /* Driver Assertion bitfield description * Driver PM assertions are defined by these bits. */ enum { /*! kIOPMDriverAssertionCPUBit * When set, PM kernel will prefer to leave the CPU and core hardware * running in "Dark Wake" state, instead of sleeping. */ kIOPMDriverAssertionCPUBit = 0x01, /*! kIOPMDriverAssertionPreventSystemIdleSleepBit * When set, the system should not idle sleep. This does not prevent * demand sleep. */ kIOPMDriverAssertionPreventSystemIdleSleepBit = 0x02, /*! kIOPMDriverAssertionUSBExternalDeviceBit * When set, driver is informing PM that an external USB device is attached. */ kIOPMDriverAssertionUSBExternalDeviceBit = 0x04, /*! kIOPMDriverAssertionBluetoothHIDDevicePairedBit * When set, driver is informing PM that a Bluetooth HID device is paired. */ kIOPMDriverAssertionBluetoothHIDDevicePairedBit = 0x08, /*! kIOPMDriverAssertionExternalMediaMountedBit * When set, driver is informing PM that an external media is mounted. */ kIOPMDriverAssertionExternalMediaMountedBit = 0x10, /*! kIOPMDriverAssertionReservedBit5 * Reserved for Thunderbolt. */ kIOPMDriverAssertionReservedBit5 = 0x20, /*! kIOPMDriverAssertionPreventDisplaySleepBit * When set, the display should remain powered on while the system's awake. */ kIOPMDriverAssertionPreventDisplaySleepBit = 0x40, /*! kIOPMDriverAssertionReservedBit7 * Reserved for storage family. */ kIOPMDriverAssertionReservedBit7 = 0x80, /*! kIOPMDriverAssertionMagicPacketWakeEnabledBit * When set, driver is informing PM that magic packet wake is enabled. */ kIOPMDriverAssertionMagicPacketWakeEnabledBit = 0x100, /*! kIOPMDriverAssertionNetworkKeepAliveActiveBit * When set, driver is informing PM that it is holding the network * interface up to do TCPKeepAlive */ kIOPMDriverAssertionNetworkKeepAliveActiveBit = 0x200 }; /* kIOPMAssertionsDriverKey * This kIOPMrootDomain key refers to a CFNumberRef property, containing * a bitfield describing the aggregate PM assertion levels. * Example: A value of 0 indicates that no driver has asserted anything. * Or, a value of <link>kIOPMDriverAssertionCPUBit</link> * indicates that a driver (or drivers) have asserted a need for CPU and video. */ #define kIOPMAssertionsDriverKey "DriverPMAssertions" /* kIOPMAssertionsDriverKey * This kIOPMrootDomain key refers to a CFNumberRef property, containing * a bitfield describing the aggregate PM assertion levels. * Example: A value of 0 indicates that no driver has asserted anything. * Or, a value of <link>kIOPMDriverAssertionCPUBit</link> * indicates that a driver (or drivers) have asserted a need for CPU and video. */ #define kIOPMAssertionsDriverDetailedKey "DriverPMAssertionsDetailed" /******************************************************************************* * * Kernel Driver assertion detailed dictionary keys * * Keys decode the Array & dictionary data structure under IOPMrootDomain property * kIOPMAssertionsDriverKey. * */ #define kIOPMDriverAssertionIDKey "ID" #define kIOPMDriverAssertionCreatedTimeKey "CreatedTime" #define kIOPMDriverAssertionModifiedTimeKey "ModifiedTime" #define kIOPMDriverAssertionOwnerStringKey "Owner" #define kIOPMDriverAssertionOwnerServiceKey "ServicePtr" #define kIOPMDriverAssertionRegistryEntryIDKey "RegistryEntryID" #define kIOPMDriverAssertionLevelKey "Level" #define kIOPMDriverAssertionAssertedKey "Assertions" /******************************************************************************* * * Root Domain general interest messages * * Available by registering for interest type 'gIOGeneralInterest' * on IOPMrootDomain. * ******************************************************************************/ /* kIOPMMessageClamshellStateChange * Delivered as a general interest notification on the IOPMrootDomain * IOPMrootDomain sends this message when state of either AppleClamshellState * or AppleClamshellCausesSleep changes. If this clamshell change results in * a sleep, the sleep will initiate soon AFTER delivery of this message. * The state of both variables is encoded in a bitfield argument sent with * the message. Check bits 0 and 1 using kClamshellStateBit & kClamshellSleepBit */ enum { kClamshellStateBit = (1 << 0), kClamshellSleepBit = (1 << 1) }; #define kIOPMMessageClamshellStateChange \ iokit_family_msg(sub_iokit_powermanagement, 0x100) /* kIOPMMessageFeatureChange * Delivered when the set of supported features ("Supported Features" dictionary * under IOPMrootDomain registry) changes in some way. Typically addition or * removal of a supported feature. * RootDomain passes no argument with this message. */ #define kIOPMMessageFeatureChange \ iokit_family_msg(sub_iokit_powermanagement, 0x110) /* kIOPMMessageInflowDisableCancelled * The battery has drained completely to its "Fully Discharged" state. * If a user process has disabled battery inflow for battery * calibration, we forcibly re-enable Inflow at this point. * If inflow HAS been forcibly re-enabled, bit 0 * (kInflowForciblyEnabledBit) will be set. */ enum { kInflowForciblyEnabledBit = (1 << 0) }; /* kIOPMMessageInternalBatteryFullyDischarged * The battery has drained completely to its "Fully Discharged" state. */ #define kIOPMMessageInternalBatteryFullyDischarged \ iokit_family_msg(sub_iokit_powermanagement, 0x120) /* kIOPMMessageSystemPowerEventOccurred * Some major system thermal property has changed, and interested clients may * modify their behavior. */ #define kIOPMMessageSystemPowerEventOccurred \ iokit_family_msg(sub_iokit_powermanagement, 0x130) /* kIOPMMessageSleepWakeUUIDChange * Either a new SleepWakeUUID has been specified at the beginning of a sleep, * or we're removing the existing property upon completion of a wakeup. */ #define kIOPMMessageSleepWakeUUIDChange \ iokit_family_msg(sub_iokit_powermanagement, 0x140) /* kIOPMMessageSleepWakeUUIDSet * Argument accompanying the kIOPMMessageSleepWakeUUIDChange notification when * a new UUID has been specified. */ #define kIOPMMessageSleepWakeUUIDSet ((void *)1) /* kIOPMMessageSleepWakeUUIDCleared * Argument accompanying the kIOPMMessageSleepWakeUUIDChange notification when * the current UUID has been removed. */ #define kIOPMMessageSleepWakeUUIDCleared ((void *)NULL) /*! kIOPMMessageDriverAssertionsChanged * Sent when kernel PM driver assertions have changed. */ #define kIOPMMessageDriverAssertionsChanged \ iokit_family_msg(sub_iokit_powermanagement, 0x150) /*! kIOPMMessageDarkWakeThermalEmergency * Sent when machine becomes unsustainably warm in DarkWake. * Kernel PM might choose to put the machine back to sleep right after. */ #define kIOPMMessageDarkWakeThermalEmergency \ iokit_family_msg(sub_iokit_powermanagement, 0x160) /******************************************************************************* * * Power commands issued to root domain * Use with IOPMrootDomain::receivePowerNotification() * * These commands are issued from system drivers only: * ApplePMU, AppleSMU, IOGraphics, AppleACPIFamily * * TODO: deprecate kIOPMAllowSleep and kIOPMPreventSleep ******************************************************************************/ enum { kIOPMSleepNow = (1 << 0),// put machine to sleep now kIOPMAllowSleep = (1 << 1),// allow idle sleep kIOPMPreventSleep = (1 << 2),// do not allow idle sleep kIOPMPowerButton = (1 << 3),// power button was pressed kIOPMClamshellClosed = (1 << 4),// clamshell was closed kIOPMPowerEmergency = (1 << 5),// battery dangerously low kIOPMDisableClamshell = (1 << 6),// do not sleep on clamshell closure kIOPMEnableClamshell = (1 << 7),// sleep on clamshell closure kIOPMProcessorSpeedChange = (1 << 8),// change the processor speed kIOPMOverTemp = (1 << 9),// system dangerously hot kIOPMClamshellOpened = (1 << 10),// clamshell was opened kIOPMDWOverTemp = (1 << 11),// DarkWake thermal limits exceeded. kIOPMPowerButtonUp = (1 << 12),// Power button up kIOPMProModeEngaged = (1 << 13),// Fans entered 'ProMode' kIOPMProModeDisengaged = (1 << 14) // Fans exited 'ProMode' }; /******************************************************************************* * * Power Management Return Codes * ******************************************************************************/ enum { kIOPMNoErr = 0, // Returned by driver's setPowerState(), powerStateWillChangeTo(), // powerStateDidChangeTo(), or acknowledgeSetPowerState() to // implicitly acknowledge power change upon function return. kIOPMAckImplied = 0, // Deprecated kIOPMWillAckLater = 1, // Returned by requestPowerDomainState() to indicate // unrecognized specification parameter. kIOPMBadSpecification = 4, // Returned by requestPowerDomainState() to indicate // no power state matches search specification. kIOPMNoSuchState = 5, // Deprecated kIOPMCannotRaisePower = 6, // Deprecated kIOPMParameterError = 7, // Returned when power management state is accessed // before driver has called PMinit(). kIOPMNotYetInitialized = 8, // And the old constants; deprecated IOPMNoErr = kIOPMNoErr, IOPMAckImplied = kIOPMAckImplied, IOPMWillAckLater = kIOPMWillAckLater, IOPMBadSpecification = kIOPMBadSpecification, IOPMNoSuchState = kIOPMNoSuchState, IOPMCannotRaisePower = kIOPMCannotRaisePower, IOPMParameterError = kIOPMParameterError, IOPMNotYetInitialized = kIOPMNotYetInitialized }; // IOPMPowerSource class descriptive strings // Power Source state is published as properties to the IORegistry under these // keys. #define kIOPMPSExternalConnectedKey "ExternalConnected" #define kIOPMPSExternalChargeCapableKey "ExternalChargeCapable" #define kIOPMPSBatteryInstalledKey "BatteryInstalled" #define kIOPMPSIsChargingKey "IsCharging" #define kIOPMFullyChargedKey "FullyCharged" #define kIOPMPSAtWarnLevelKey "AtWarnLevel" #define kIOPMPSAtCriticalLevelKey "AtCriticalLevel" #define kIOPMPSCurrentCapacityKey "CurrentCapacity" #define kIOPMPSMaxCapacityKey "MaxCapacity" #define kIOPMPSDesignCapacityKey "DesignCapacity" #define kIOPMPSTimeRemainingKey "TimeRemaining" #define kIOPMPSAmperageKey "Amperage" #define kIOPMPSVoltageKey "Voltage" #define kIOPMPSCycleCountKey "CycleCount" #define kIOPMPSMaxErrKey "MaxErr" #define kIOPMPSAdapterInfoKey "AdapterInfo" #define kIOPMPSLocationKey "Location" #define kIOPMPSErrorConditionKey "ErrorCondition" #define kIOPMPSManufacturerKey "Manufacturer" #define kIOPMPSManufactureDateKey "ManufactureDate" #define kIOPMPSModelKey "Model" #define kIOPMPSSerialKey "Serial" #define kIOPMDeviceNameKey "DeviceName" #define kIOPMPSLegacyBatteryInfoKey "LegacyBatteryInfo" #define kIOPMPSBatteryHealthKey "BatteryHealth" #define kIOPMPSHealthConfidenceKey "HealthConfidence" #define kIOPMPSCapacityEstimatedKey "CapacityEstimated" #define kIOPMPSBatteryChargeStatusKey "ChargeStatus" #define kIOPMPSBatteryTemperatureKey "Temperature" #define kIOPMPSAdapterDetailsKey "AdapterDetails" #define kIOPMPSChargerConfigurationKey "ChargerConfiguration" // kIOPMPSBatteryChargeStatusKey may have one of the following values, or may have // no value. If kIOPMBatteryChargeStatusKey has a NULL value (or no value) associated with it // then charge is proceeding normally. If one of these battery charge status reasons is listed, // then the charge may have been interrupted. #define kIOPMBatteryChargeStatusTooHot "HighTemperature" #define kIOPMBatteryChargeStatusTooCold "LowTemperature" #define kIOPMBatteryChargeStatusTooHotOrCold "HighOrLowTemperature" #define kIOPMBatteryChargeStatusGradient "BatteryTemperatureGradient" // Definitions for battery location, in case of multiple batteries. // A location of 0 is unspecified // Location is undefined for single battery systems enum { kIOPMPSLocationLeft = 1001, kIOPMPSLocationRight = 1002 }; // Battery quality health types, specified by BatteryHealth and HealthConfidence // properties in an IOPMPowerSource battery kext. enum { kIOPMUndefinedValue = 0, kIOPMPoorValue = 1, kIOPMFairValue = 2, kIOPMGoodValue = 3 }; // Keys for kIOPMPSAdapterDetailsKey dictionary #define kIOPMPSAdapterDetailsIDKey "AdapterID" #define kIOPMPSAdapterDetailsWattsKey "Watts" #define kIOPMPSAdapterDetailsRevisionKey "AdapterRevision" #define kIOPMPSAdapterDetailsSerialNumberKey "SerialNumber" #define kIOPMPSAdapterDetailsFamilyKey "FamilyCode" #define kIOPMPSAdapterDetailsAmperageKey "Current" #define kIOPMPSAdapterDetailsDescriptionKey "Description" #define kIOPMPSAdapterDetailsPMUConfigurationKey "PMUConfiguration" #define kIOPMPSAdapterDetailsVoltage "Voltage" #define kIOPMPSAdapterDetailsSourceIDKey "Source" #define kIOPMPSAdapterDetailsErrorFlagsKey "ErrorFlags" #define kIOPMPSAdapterDetailsSharedSourceKey "SharedSource" #define kIOPMPSAdapterDetailsCloakedKey "CloakedSource" // values for kIOPSPowerAdapterFamilyKey enum { kIOPSFamilyCodeDisconnected = 0, kIOPSFamilyCodeUnsupported = kIOReturnUnsupported, kIOPSFamilyCodeFirewire = iokit_family_err(sub_iokit_firewire, 0), kIOPSFamilyCodeUSBHost = iokit_family_err(sub_iokit_usb, 0), kIOPSFamilyCodeUSBHostSuspended = iokit_family_err(sub_iokit_usb, 1), kIOPSFamilyCodeUSBDevice = iokit_family_err(sub_iokit_usb, 2), kIOPSFamilyCodeUSBAdapter = iokit_family_err(sub_iokit_usb, 3), kIOPSFamilyCodeUSBChargingPortDedicated = iokit_family_err(sub_iokit_usb, 4), kIOPSFamilyCodeUSBChargingPortDownstream = iokit_family_err(sub_iokit_usb, 5), kIOPSFamilyCodeUSBChargingPort = iokit_family_err(sub_iokit_usb, 6), kIOPSFamilyCodeUSBUnknown = iokit_family_err(sub_iokit_usb, 7), kIOPSFamilyCodeUSBCBrick = iokit_family_err(sub_iokit_usb, 8), kIOPSFamilyCodeUSBCTypeC = iokit_family_err(sub_iokit_usb, 9), kIOPSFamilyCodeUSBCPD = iokit_family_err(sub_iokit_usb, 10), kIOPSFamilyCodeAC = iokit_family_err(sub_iokit_pmu, 0), kIOPSFamilyCodeExternal = iokit_family_err(sub_iokit_pmu, 1), kIOPSFamilyCodeExternal2 = iokit_family_err(sub_iokit_pmu, 2), kIOPSFamilyCodeExternal3 = iokit_family_err(sub_iokit_pmu, 3), kIOPSFamilyCodeExternal4 = iokit_family_err(sub_iokit_pmu, 4), kIOPSFamilyCodeExternal5 = iokit_family_err(sub_iokit_pmu, 5), kIOPSFamilyCodeExternal6 = iokit_family_err(sub_iokit_pmu, 6), kIOPSFamilyCodeExternal7 = iokit_family_err(sub_iokit_pmu, 7), }; // values for kIOPMPSAdapterDetailsErrorFlagsKey enum { kIOPSAdapterErrorFlagNoErrors = 0, kIOPSAdapterErrorFlagInsufficientAvailablePower = (1 << 1), kIOPSAdapterErrorFlagForeignObjectDetected = (1 << 2), kIOPSAdapterErrorFlagDeviceNeedsToBeRepositioned = (1 << 3), }; // Battery's time remaining estimate is invalid this long (seconds) after a wake #define kIOPMPSInvalidWakeSecondsKey "BatteryInvalidWakeSeconds" // Battery must wait this long (seconds) after being completely charged before // the battery is settled. #define kIOPMPSPostChargeWaitSecondsKey "PostChargeWaitSeconds" // Battery must wait this long (seconds) after being completely discharged // before the battery is settled. #define kIOPMPSPostDishargeWaitSecondsKey "PostDischargeWaitSeconds" /* CPU Power Management status keys * Pass as arguments to IOPMrootDomain::systemPowerEventOccurred * Or as arguments to IOPMSystemPowerEventOccurred() * Or to decode the dictionary obtained from IOPMCopyCPUPowerStatus() * These keys reflect restrictions placed on the CPU by the system * to bring the CPU's power consumption within allowable thermal and * power constraints. */ /* kIOPMGraphicsPowerLimitsKey * The key representing the dictionary of graphics power limits. * The dictionary contains the other kIOPMCPUPower keys & their associated * values (e.g. Speed limit, Processor Count, and Schedule limits). */ #define kIOPMGraphicsPowerLimitsKey "Graphics_Power_Limits" /* kIOPMGraphicsPowerLimitPerformanceKey * The key representing the percent of overall performance made available * by the graphics chip as a percentage (integer 0 - 100). */ #define kIOPMGraphicsPowerLimitPerformanceKey "Graphics_Power_Performance" /* kIOPMCPUPowerLimitsKey * The key representing the dictionary of CPU Power Limits. * The dictionary contains the other kIOPMCPUPower keys & their associated * values (e.g. Speed limit, Processor Count, and Schedule limits). */ #define kIOPMCPUPowerLimitsKey "CPU_Power_Limits" /* kIOPMCPUPowerLimitProcessorSpeedKey defines the speed & voltage limits placed * on the CPU. * Represented as a percentage (0-100) of maximum CPU speed. */ #define kIOPMCPUPowerLimitProcessorSpeedKey "CPU_Speed_Limit" /* kIOPMCPUPowerLimitProcessorCountKey reflects how many, if any, CPUs have been * taken offline. Represented as an integer number of CPUs (0 - Max CPUs). */ #define kIOPMCPUPowerLimitProcessorCountKey "CPU_Available_CPUs" /* kIOPMCPUPowerLimitSchedulerTimeKey represents the percentage (0-100) of CPU time * available. 100% at normal operation. The OS may limit this time for a percentage * less than 100%. */ #define kIOPMCPUPowerLimitSchedulerTimeKey "CPU_Scheduler_Limit" /* Thermal Level Warning Key * Indicates the thermal constraints placed on the system. This value may * cause clients to action to consume fewer system resources. * The value associated with this warning is defined by the platform. */ #define kIOPMThermalLevelWarningKey "Thermal_Level_Warning" /* Thermal Warning Level values * kIOPMThermalLevelNormal - under normal operating conditions * kIOPMThermalLevelDanger - thermal pressure may cause system slowdown * kIOPMThermalLevelCritical - thermal conditions may cause imminent shutdown * * The platform may define additional thermal levels if necessary. * Platform specific values are defined from 100 and above */ enum { kIOPMThermalLevelNormal = 0, kIOPMThermalLevelDanger = 5, kIOPMThermalLevelCritical = 10, kIOPMThermalLevelWarning = 100, kIOPMThermalLevelTrap = 110, kIOPMThermalLevelUnknown = 255, }; #define kIOPMThermalWarningLevelNormal kIOPMThermalLevelNormal #define kIOPMThermalWarningLevelDanger kIOPMThermalLevelWarning #define kIOPMThermalWarningLevelCrisis kIOPMThermalLevelCritical // PM Settings Controller setting types // Settings types used primarily with: // IOPMrootDomain::registerPMSettingController // The values are identical to the similarly named keys for use in user space // PM settings work. Those keys are defined in IOPMLibPrivate.h. #define kIOPMSettingWakeOnRingKey "Wake On Modem Ring" #define kIOPMSettingRestartOnPowerLossKey "Automatic Restart On Power Loss" #define kIOPMSettingWakeOnACChangeKey "Wake On AC Change" #define kIOPMSettingSleepOnPowerButtonKey "Sleep On Power Button" #define kIOPMSettingWakeOnClamshellKey "Wake On Clamshell Open" #define kIOPMSettingReduceBrightnessKey "ReduceBrightness" #define kIOPMSettingDisplaySleepUsesDimKey "Display Sleep Uses Dim" #define kIOPMSettingTimeZoneOffsetKey "TimeZoneOffsetSeconds" #define kIOPMSettingMobileMotionModuleKey "MobileMotionModule" #define kIOPMSettingGraphicsSwitchKey "GPUSwitch" #define kIOPMSettingProModeControl "ProModeControl" #define kIOPMSettingProModeDefer "ProModeDefer" // Setting controlling drivers can register to receive scheduled wake data // Either in "CF seconds" type, or structured calendar data in a formatted // IOPMCalendarStruct defined below. #define kIOPMSettingAutoWakeSecondsKey "wake" #define kIOPMSettingAutoWakeCalendarKey "WakeByCalendarDate" #define kIOPMSettingAutoPowerSecondsKey "poweron" #define kIOPMSettingAutoPowerCalendarKey "PowerByCalendarDate" // Debug seconds auto wake // Used by sleep cycling debug tools #define kIOPMSettingDebugWakeRelativeKey "WakeRelativeToSleep" #define kIOPMSettingDebugPowerRelativeKey "PowerRelativeToShutdown" // Maintenance wake calendar. #define kIOPMSettingMaintenanceWakeCalendarKey "MaintenanceWakeCalendarDate" struct IOPMCalendarStruct { UInt32 year; UInt8 month; UInt8 day; UInt8 hour; UInt8 minute; UInt8 second; UInt8 selector; }; typedef struct IOPMCalendarStruct IOPMCalendarStruct; // SetAggressiveness types enum { kPMGeneralAggressiveness = 0, kPMMinutesToDim, kPMMinutesToSpinDown, kPMMinutesToSleep, kPMEthernetWakeOnLANSettings, kPMSetProcessorSpeed, kPMPowerSource, kPMMotionSensor, kPMLastAggressivenessType }; #define kMaxType (kPMLastAggressivenessType-1) // SetAggressiveness values for the kPMPowerSource aggressiveness type enum { kIOPMInternalPower = 1, kIOPMExternalPower }; #define kIOREMSleepEnabledKey "REMSleepEnabled" // Strings for deciphering the dictionary returned from IOPMCopyBatteryInfo #define kIOBatteryInfoKey "IOBatteryInfo" #define kIOBatteryCurrentChargeKey "Current" #define kIOBatteryCapacityKey "Capacity" #define kIOBatteryFlagsKey "Flags" #define kIOBatteryVoltageKey "Voltage" #define kIOBatteryAmperageKey "Amperage" #define kIOBatteryCycleCountKey "Cycle Count" enum { kIOBatteryInstalled = (1 << 2), kIOBatteryCharge = (1 << 1), kIOBatteryChargerConnect = (1 << 0) }; // Private power management message indicating battery data has changed // Indicates new data resides in the IORegistry #define kIOPMMessageBatteryStatusHasChanged iokit_family_msg(sub_iokit_pmu, 0x100) // Apple private Legacy messages for re-routing AutoWake and AutoPower messages to the PMU // through newer user space IOPMSchedulePowerEvent API #define kIOPMUMessageLegacyAutoWake iokit_family_msg(sub_iokit_pmu, 0x200) #define kIOPMUMessageLegacyAutoPower iokit_family_msg(sub_iokit_pmu, 0x210) // For use with IOPMPowerSource bFlags #define IOPM_POWER_SOURCE_REV 2 enum { kIOPMACInstalled = kIOBatteryChargerConnect, kIOPMBatteryCharging = kIOBatteryCharge, kIOPMBatteryInstalled = kIOBatteryInstalled, kIOPMUPSInstalled = (1 << 3), kIOPMBatteryAtWarn = (1 << 4), kIOPMBatteryDepleted = (1 << 5), kIOPMACnoChargeCapability = (1 << 6), // AC adapter cannot charge battery kIOPMRawLowBattery = (1 << 7), // used only by Platform Expert kIOPMForceLowSpeed = (1 << 8), // set by Platfm Expert, chk'd by Pwr Plugin kIOPMClosedClamshell = (1 << 9), // set by PMU - reflects state of the clamshell kIOPMClamshellStateOnWake = (1 << 10) // used only by Platform Expert }; // ********************************************** // Internal power management data structures // ********************************************** struct IOPowerStateChangeNotification { void * powerRef; unsigned long returnValue; unsigned long stateNumber; IOPMPowerFlags stateFlags; }; typedef struct IOPowerStateChangeNotification IOPowerStateChangeNotification; typedef IOPowerStateChangeNotification sleepWakeNote; /*! @struct IOPMSystemCapabilityChangeParameters * @abstract A structure describing a system capability change. * @discussion A system capability change is a system level transition from a set * of system capabilities to a new set of system capabilities. Power management * sends a <code>kIOMessageSystemCapabilityChange</code> message and provides * this structure as the message data (by reference) to * <code>gIOPriorityPowerStateInterest</code> clients when system capability * changes. * @field notifyRef An identifier for this message notification. Clients with pending * I/O can signal completion by calling <code>allowPowerChange()</code> with this * value as the argument. Clients that are able to process the notification * synchronously should ignore this field. * @field maxWaitForReply A return value to the caller indicating the maximum time in * microseconds to wait for the <code>allowPowerChange()</code> call. The default * value is zero, which indicates the client processing has finished, and power * management should not wait for an <code>allowPowerChange()</code> call. * @field changeFlags Flags will be set to indicate whether the notification precedes * the capability change (<code>kIOPMSystemCapabilityWillChange</code>), or after * the capability change has occurred (<code>kIOPMSystemCapabilityDidChange</code>). * @field __reserved1 Set to zero. * @field fromCapabilities The system capabilities at the start of the transition. * @field toCapabilities The system capabilities at the end of the transition. * @field __reserved2 Set to zero. */ struct IOPMSystemCapabilityChangeParameters { uint32_t notifyRef; uint32_t maxWaitForReply; uint32_t changeFlags; uint32_t __reserved1; uint32_t fromCapabilities; uint32_t toCapabilities; uint32_t __reserved2[4]; }; /*! @enum IOPMSystemCapabilityChangeFlags * @constant kIOPMSystemCapabilityWillChange Indicates the system capability will change. * @constant kIOPMSystemCapabilityDidChange Indicates the system capability has changed. */ enum { kIOPMSystemCapabilityWillChange = 0x01, kIOPMSystemCapabilityDidChange = 0x02 }; enum { kIOPMSystemCapabilityCPU = 0x01, kIOPMSystemCapabilityGraphics = 0x02, kIOPMSystemCapabilityAudio = 0x04, kIOPMSystemCapabilityNetwork = 0x08 }; #endif /* ! _IOKIT_IOPM_H */
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/pwr_mgt/IOPMLibDefs.h
/* * Copyright (c) 1998-2000 Apple Computer, Inc. All rights reserved. * * @APPLE_OSREFERENCE_LICENSE_HEADER_START@ * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. The rights granted to you under the License * may not be used to create, or enable the creation or redistribution of, * unlawful or unlicensed copies of an Apple operating system, or to * circumvent, violate, or enable the circumvention or violation of, any * terms of an Apple operating system software license agreement. * * Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_OSREFERENCE_LICENSE_HEADER_END@ */ #define kPMSetAggressiveness 0 #define kPMGetAggressiveness 1 #define kPMSleepSystem 2 #define kPMAllowPowerChange 3 #define kPMCancelPowerChange 4 #define kPMShutdownSystem 5 #define kPMRestartSystem 6 #define kPMSleepSystemOptions 7 #define kPMSetMaintenanceWakeCalendar 8 #define kPMSetUserAssertionLevels 9 #define kPMActivityTickle 10 #define kPMGetSystemSleepType 11 #define kPMSetClamshellSleepState 12 #define kPMSleepWakeWatchdogEnable 13 #define kPMSleepWakeDebugTrig 14 #define kPMSetDisplayPowerOn 15 #define kPMSetDisplayState 16 #define kNumPMMethods 17
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/pwr_mgt/IOPMLib.h
/* * Copyright (c) 1998-2005 Apple Computer, Inc. All rights reserved. * * @APPLE_LICENSE_HEADER_START@ * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this * file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_LICENSE_HEADER_END@ */ #include <CoreFoundation/CFArray.h> #include <IOKit/IOKitLib.h> #include <IOKit/pwr_mgt/IOPMLibDefs.h> #include <IOKit/pwr_mgt/IOPMKeys.h> #include <Availability.h> #ifndef _IOKIT_PWRMGT_IOPMLIB_ #define _IOKIT_PWRMGT_IOPMLIB_ #ifdef __cplusplus extern "C" { #endif /*! @header IOPMLib.h IOPMLib provides access to common power management facilities, like initiating system sleep, getting current idle timer values, registering for sleep/wake notifications, and preventing system sleep. */ /*! @function IOPMFindPowerManagement @abstract Finds the Root Power Domain IOService. @param master_device_port Just pass in MACH_PORT_NULL for master device port. @result Returns a io_connect_t handle on the root domain. Must be released with IOServiceClose() when done. */ io_connect_t IOPMFindPowerManagement( mach_port_t master_device_port ) AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER; /*! @function IOPMSetAggressiveness @abstract Sets one of the aggressiveness factors in IOKit Power Management. @param fb Representation of the Root Power Domain from IOPMFindPowerManagement. @param type Specifies which aggressiveness factor is being set. @param aggressiveness New value of the aggressiveness factor. @result Returns kIOReturnSuccess or an error condition if request failed. */ IOReturn IOPMSetAggressiveness (io_connect_t fb, unsigned long type, unsigned long aggressiveness ) AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER; /*! @function IOPMGetAggressiveness @abstract Retrieves the current value of one of the aggressiveness factors in IOKit Power Management. @param fb Representation of the Root Power Domain from IOPMFindPowerManagement. @param type Specifies which aggressiveness factor is being retrieved. @param aggressiveness Points to where to store the retrieved value of the aggressiveness factor. @result Returns kIOReturnSuccess or an error condition if request failed. */ IOReturn IOPMGetAggressiveness ( io_connect_t fb, unsigned long type, unsigned long * aggressiveness ) AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER; /*! @function IOPMSleepEnabled @abstract Tells whether the system supports full sleep, or just doze @result Returns true if the system supports sleep, false if some hardware prevents full sleep. */ boolean_t IOPMSleepEnabled ( void ) AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER; /*! @function IOPMSleepSystem @abstract Request that the system initiate sleep. @discussion For security purposes, caller must be root or the console user. @param fb Port used to communicate to the kernel, from IOPMFindPowerManagement. @result Returns kIOReturnSuccess or an error condition if request failed. */ IOReturn IOPMSleepSystem ( io_connect_t fb ) AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER; /*! @function IOPMCopyBatteryInfo @abstract Request battery data from the system. @discussion This API is supported, but not recommended. Developers should prefer to use the IOPowerSources API. IOPowerSources provides more battery data, and notifications when battery state changes) @param masterPort The master port obtained from IOMasterPort(). Just pass MACH_PORT_NULL. @param info A CFArray of CFDictionaries containing raw battery data. Use these keys, defined in IOPM.h to read from the dictionary: <pre> <code>@link kIOBatteryInfoKey @/link</code> <code>@link kIOBatteryCurrentChargeKey @/link</code> <code>@link kIOBatteryCapacityKey @/link</code> <code>@link kIOBatteryFlagsKey @/link</code> <code>@link kIOBatteryVoltageKey @/link</code> <code>@link kIOBatteryAmperageKey @/link</code> <code>@link kIOBatteryCycleCountKey @/link</code> </pre> @result Returns kIOReturnSuccess or an error condition if request failed. */ IOReturn IOPMCopyBatteryInfo( mach_port_t masterPort, CFArrayRef * info ) AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER; /*! @functiongroup Notifications */ /*! @function IORegisterApp @abstract DEPRECATED - An obsolete method for interacting with driver power state changes. @discussion This function is obsolete and deprecated. To receive notifications of driver power state changes, Please use IOServiceAddInterestNotification with interest type gIOGeneralInterest instead. */ io_connect_t IORegisterApp( void * refcon, io_service_t theDriver, IONotificationPortRef * thePortRef, IOServiceInterestCallback callback, io_object_t * notifier ) __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_0, __MAC_10_9, __IPHONE_NA, __IPHONE_NA); /*! @function IORegisterForSystemPower @abstract Connects the caller to the Root Power Domain IOService for the purpose of receiving sleep & wake notifications for the system. Does not provide system shutdown and restart notifications. @discussion Provides sleep/wake notifications to applications. Requires that applications acknowledge some, but not all notifications. Register for sleep/wake notifications will deliver these messages over the sleep/wake lifecycle: <ul> <li>kIOMessageSystemWillSleep is delivered at the point the system is initiating a non-abortable sleep. Callers MUST acknowledge this event by calling @link IOAllowPowerChange @/link. If a caller does not acknowledge the sleep notification, the sleep will continue anyway after a 30 second timeout (resulting in bad user experience). Delivered before any hardware is powered off. <li>kIOMessageSystemWillPowerOn is delivered at early wakeup time, before most hardware has been powered on. Be aware that any attempts to access disk, network, the display, etc. may result in errors or blocking your process until those resources become available. Caller must NOT acknowledge kIOMessageSystemWillPowerOn; the caller must simply return from its handler. <li>kIOMessageSystemHasPoweredOn is delivered at wakeup completion time, after all device drivers and hardware have handled the wakeup event. Expect this event 1-5 or more seconds after initiating system wakeup. Caller must NOT acknowledge kIOMessageSystemHasPoweredOn; the caller must simply return from its handler. <li>kIOMessageCanSystemSleep indicates the system is pondering an idle sleep, but gives apps the chance to veto that sleep attempt. Caller must acknowledge kIOMessageCanSystemSleep by calling @link IOAllowPowerChange @/link or @link IOCancelPowerChange @/link. Calling IOAllowPowerChange will not veto the sleep; any app that calls IOCancelPowerChange will veto the idle sleep. A kIOMessageCanSystemSleep notification will be followed up to 30 seconds later by a kIOMessageSystemWillSleep message. or a kIOMessageSystemWillNotSleep message. <li>kIOMessageSystemWillNotSleep is delivered when some app client has vetoed an idle sleep request. kIOMessageSystemWillNotSleep may follow a kIOMessageCanSystemSleep notification, but will not otherwise be sent. Caller must NOT acknowledge kIOMessageSystemWillNotSleep; the caller must simply return from its handler. </ul> To deregister for sleep/wake notifications, the caller must make two calls, in this order: <ol><li> Call IODeregisterForSystemPower with the 'notifier' argument returned here. <li> Then call IONotificationPortDestroy passing the 'thePortRef' argument returned here. </ol> @param refcon Caller may provide data to receive as an argument to 'callback' on power state changes. @param thePortRef On return, thePortRef is a pointer to an IONotificationPortRef, which will deliver the power notifications. The port is allocated by this function and must be later released by the caller (after calling <code>@link IODeregisterForSystemPower @/link</code>). The caller should also enable IONotificationPortRef by calling <code>@link IONotificationPortGetRunLoopSource @/link</code>, or <code>@link IONotificationPortGetMachPort @/link</code>, or <code>@link IONotificationPortSetDispatchQueue @/link</code>. @param callback A c-function which is called during the notification. @param notifier On success, returns a pointer to a unique notifier which caller must keep and pass to a subsequent call to IODeregisterForSystemPower. @result Returns a io_connect_t session for the IOPMrootDomain or IO_OBJECT_NULL if request failed. Caller must close return value via IOServiceClose() after calling IODeregisterForSystemPower on the notifier argument. */ io_connect_t IORegisterForSystemPower ( void * refcon, IONotificationPortRef * thePortRef, IOServiceInterestCallback callback, io_object_t * notifier ) AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER; /*! @function IODeregisterApp @abstract Disconnects the caller from an IOService after receiving power state change notifications from the IOService. (Caller must also release IORegisterApp's return io_connect_t and returned IONotificationPortRef for complete clean-up). @param notifier An object from IORegisterApp. @result Returns kIOReturnSuccess or an error condition if request failed. */ IOReturn IODeregisterApp ( io_object_t * notifier ) AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER; /*! @function IODeregisterForSystemPower @abstract Disconnects the caller from the Root Power Domain IOService after receiving system power state change notifications. (Caller must also destroy the IONotificationPortRef returned from IORegisterForSystemPower.) @param notifier The object returned from IORegisterForSystemPower. @result Returns kIOReturnSuccess or an error condition if request failed. */ IOReturn IODeregisterForSystemPower ( io_object_t * notifier ) AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER; /*! @function IOAllowPowerChange @abstract The caller acknowledges notification of a power state change on a device it has registered for notifications for via IORegisterForSystemPower or IORegisterApp. @discussion Must be used when handling kIOMessageCanSystemSleep and kIOMessageSystemWillSleep messages from IOPMrootDomain system power. The caller should not call IOAllowPowerChange in response to any messages except for these two. @param kernelPort Port used to communicate to the kernel, from IORegisterApp or IORegisterForSystemPower. @param notificationID A copy of the notification ID which came as part of the power state change notification being acknowledged. @result Returns kIOReturnSuccess or an error condition if request failed. */ IOReturn IOAllowPowerChange ( io_connect_t kernelPort, intptr_t notificationID ) AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER; /*! @function IOCancelPowerChange @abstract The caller denies an idle system sleep power state change. @discussion Should only called in response to kIOMessageCanSystemSleep messages from IOPMrootDomain. IOCancelPowerChange has no meaning for responding to kIOMessageSystemWillSleep (which is non-abortable) or any other messages. When an app responds to a kIOMessageCanSystemSleep message by calling IOCancelPowerChange, the app vetoes the idle sleep request. The system will stay awake. The idle timer will elapse again after a period of inactivity, and the system will send out the same kIOMessageCanSystemSleep message, and interested applications will respond gain. @param kernelPort Port used to communicate to the kernel, from IORegisterApp or IORegisterForSystemPower. @param notificationID A copy of the notification ID which came as part of the power state change notification being acknowledged. @result Returns kIOReturnSuccess or an error condition if request failed. */ IOReturn IOCancelPowerChange ( io_connect_t kernelPort, intptr_t notificationID ) AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER; /*! @functiongroup ScheduledEvents */ /*! @function IOPMSchedulePowerEvent @abstract Schedule the machine to wake from sleep, power on, go to sleep, or shutdown. @discussion This event will be added to the system's queue of power events and stored persistently on disk. The sleep and shutdown events present a graphical warning and allow a console user to cancel the event. Must be called as root. @param time_to_wake Date and time that the system will power on/off. @param my_id A CFStringRef identifying the calling app by CFBundleIdentifier. May be NULL. @param type The type of power on you desire, either wake from sleep or power on. Choose from: <ul> <li>CFSTR(<code>kIOPMAutoWake</code>) == wake machine, <li>CFSTR(<code>kIOPMAutoPowerOn</code>) == power on machine, <li>CFSTR(<code>kIOPMAutoWakeOrPowerOn</code>) == wake or power on, <li>CFSTR(<code>kIOPMAutoSleep</code>) == sleep machine, <li>CFSTR(<code>kIOPMAutoShutdown</code>) == power off machine, <li>CFSTR(<code>kIOPMAutoRestart</code>) == restart the machine. </ul> @result kIOReturnSuccess on success, otherwise on failure */ IOReturn IOPMSchedulePowerEvent(CFDateRef time_to_wake, CFStringRef my_id, CFStringRef type); /*! @function IOPMCancelScheduledPowerEvent @abstract Cancel a previously scheduled power event. @discussion Arguments mirror those to IOPMSchedulePowerEvent. All arguments must match the original arguments from when the power on was scheduled. Must be called as root. @param time_to_wake Cancel entry with this date and time. @param my_id Cancel entry with this name. @param type Type to cancel @result kIOReturnSuccess on success, otherwise on failure */ IOReturn IOPMCancelScheduledPowerEvent(CFDateRef time_to_wake, CFStringRef my_id, CFStringRef type); /*! @function IOPMCopyScheduledPowerEvents @abstract List all scheduled system power events @discussion Returns a CFArray of CFDictionaries of power events. Each CFDictionary contains keys for CFSTR(kIOPMPowerEventTimeKey), CFSTR(kIOPMPowerEventAppNameKey), and CFSTR(kIOPMPowerEventTypeKey). @result A CFArray of CFDictionaries of power events. The CFArray must be released by the caller. NULL if there are no scheduled events. */ CFArrayRef IOPMCopyScheduledPowerEvents(void); #pragma mark IOKit Power Assertions /*! * * @functiongroup IOPMAssertions * */ /*! * @define kIOPMAssertPreventUserIdleSystemSleep * * @abstract Prevents the system from sleeping automatically due to a lack of user activity. * * @discussion When asserted and set to level <code>@link kIOPMAssertionLevelOn@/link</code>, * will prevent the system from sleeping due to a period of idle user activity. * Create this assertion with * <code>@link IOPMAssertionCreateWithName @/link</code> * or <code>@link IOPMAssertionCreateWithDescription @/link</code> * * The display may dim and idle sleep while <code>kIOPMAssertPreventUserIdleSystemSleep</code> is * enabled, but the system may not idle sleep. The system may still sleep for lid close, * Apple menu, low battery, or other sleep reasons. * * This assertion has no effect if the system is in Dark Wake. * */ #define kIOPMAssertPreventUserIdleSystemSleep CFSTR("PreventUserIdleSystemSleep") /*! * @define kIOPMAssertPreventUserIdleDisplaySleep * * @abstract Prevents the display from dimming automatically. * * @discussion Create this assertion with * <code>@link IOPMAssertionCreateWithName @/link</code> * or <code>@link IOPMAssertionCreateWithDescription @/link</code>. * * When asserted and set to level <code>@link kIOPMAssertionLevelOn@/link</code>, * will prevent the display from turning off due to a period of idle user activity. * Note that the display may still sleep for other reasons, like a user closing a * portable's lid or the machine sleeping. If the display is already off, this * assertion does not light up the display. If display needs to be turned on, then * consider calling function <code>@link IOPMAssertionDeclareUserActivity@/link</code>. * * While the display is prevented from dimming, the system cannot go into idle sleep. * * This assertion has no effect if the system is in Dark Wake. */ #define kIOPMAssertPreventUserIdleDisplaySleep CFSTR("PreventUserIdleDisplaySleep") /*! * @define kIOPMAssertPreventDiskIdle * * @abstract Prevent attached disks from idling into lower power states. * * @discussion When asserted and set to level <code>@link kIOPMAssertionLevelOn@/link</code>, * will prevent attached disks and optical media from idling into lower power states. * Create this assertion with * <code>@link IOPMAssertionCreateWithName @/link</code> * or <code>@link IOPMAssertionCreateWithDescription @/link</code>. * * Apps who rely on real-time access to disks should create this assertion to avoid * latencies caused by disks changing power states. For example, audio and video performance * or recording apps may benefit from this assertion. Most Apps should not take this assertion; * preventing disk idle consumes battery life, and most apps don't require the low latency * disk access that this provides. * * This assertion doesn't increase a disk's power state (it just prevents that device from idling). * After creating this assertion, the caller should perform disk I/O on the necessary drives to * ensure that they're in a usable power state. * * The system may still sleep while this assertion is active. * Callers should also take <code>@link kIOPMAssertPreventUserIdleSystemSleep@/link</code> * if necessary, to prevent idle system sleep. */ #define kIOPMAssertPreventDiskIdle CFSTR("PreventDiskIdle") /*! * @define kIOPMAssertNetworkClientActive * * @abstract Keeps the system awake while OS X serves active network clients. * * @discussion When asserted and set to level <code>@link kIOPMAssertionLevelOn@/link</code>, * will keep the computer awake. Create this assertion with * <code>@link IOPMAssertionCreateWithName @/link</code> * or <code>@link IOPMAssertionCreateWithDescription @/link</code>. * * Instead of taking this assertion, most callers should instead use: * <code>@link IOPMDeclareNetworkClientActivity @/link</code> * it takes the assertion, but with a built-in timeout. * * This assertion keeps the system awake in dark or full wake, * as long as the system is on AC power. On battery, this assertion can * prevent system from going into idle sleep. * IOKit power assertions are suggestions and OS X may not honor them under * battery, thermal, or user circumstances. * * This assertion provides CPU, disk, and network connectivity. * If the network is no longer available, this assertion may stop working * and allow the system to go to sleep. * * Callers should take this assertion when they have remote clients connected and active. * Please <code>@link IOPMAssertionRelease @/link></code> this assertion if remote clients become * inactive, idle, or disconnected. * If your process already manages user timeouts and tracks activity, * you can take this assertion directly with * <code>@link IOPMAssertionCreateWithProperties @/link</code>. * * IOKit can manage remote client idleness for you if you call * <code>@link IOPMDeclareNetworkClientActivity @/link</code> upon every remote access, * * This assertion is a suggestion; Mac OS X may need to sleep the system even if * this assertion is active. */ #define kIOPMAssertNetworkClientActive CFSTR("NetworkClientActive") /*! @/defineblock IOPMAssertionDictionary Keys*/ /*! * @typedef IOPMAssertionID * * @abstract Type for AssertionID arguments to <code>@link IOPMAssertionCreateWithProperties@/link</code> * and <code>@link IOPMAssertionRelease@/link</code> */ typedef uint32_t IOPMAssertionID; /*! * @enum kIOPMNullAssertionID * * @abstract This value represents a non-initialized assertion ID * * @constant kIOPMNullAssertionID * This value represents a non-initialized assertion ID. * */ enum { kIOPMNullAssertionID = 0 }; /*! * @typedef IOPMAssertionLevel * * @abstract Type for AssertionLevel argument to IOPMAssertionCreate * * @discussion Possible values for <code>IOPMAssertionLevel</code> are * <code>@link kIOPMAssertionLevelOff@/link</code> * and <code>@link kIOPMAssertionLevelOn@/link</code> */ typedef uint32_t IOPMAssertionLevel; /*! * @enum Assertion Levels */ enum { /*! * @constant kIOPMAssertionLevelOff * @abstract Level for a disabled assertion, passed as an argument to IOPMAssertionCreate. */ kIOPMAssertionLevelOff = 0, /*! * @constant kIOPMAssertionLevelOn * @abstract Level for an enabled assertion, passed as an argument to IOPMAssertionCreate. */ kIOPMAssertionLevelOn = 255 }; typedef enum { kIOPMUserActiveLocal, /* User is local on the system */ kIOPMUserActiveRemote /* Remote User connected to the system */ } IOPMUserActiveType; /*! @function IOPMAssertionCreateWithDescription * * @abstract The preferred API to create a power assertion. * * @description Creates an IOPMAssertion. This is the preferred API to call to create an assertion. * It allows the caller to specify the Name, Details, and HumanReadableReason at creation time. * There are other keys that can further describe an assertion, but most developers don't need * to use them. Use <code>@link IOPMAssertionSetProperty @/link</code> or * <code>@link IOPMAssertionCreateWithProperties @/link</code> if you need to specify properties * that aren't available here. * * @param AssertionType An assertion type constant. * Caller must specify this argument. * * @param Name A CFString value to correspond to key <code>@link kIOPMAssertionNameKey@/link</code>. * Caller must specify this argument. * * @param Details A CFString value to correspond to key <code>@link kIOPMAssertionDetailsKey@/link</code>. * Caller may pass NULL, but it helps power users and administrators identify the * reasons for this assertion. * * @param HumanReadableReason * A CFString value to correspond to key <code>@link kIOPMAssertionHumanReadableReasonKey@/link</code>. * Caller may pass NULL, but if it's specified OS X may display it to users * to describe the active assertions on their system. * * @param LocalizationBundlePath * A CFString value to correspond to key <code>@link kIOPMAssertionLocalizationBundlePathKey@/link</code>. * This bundle path should include a localization for the string <code>HumanReadableReason</code> * Caller may pass NULL, but this argument is required if caller specifies <code>HumanReadableReason</code> * * @param Timeout Specifies a timeout for this assertion. Pass 0 for no timeout. * * @param TimeoutAction Specifies a timeout action. Caller my pass NULL. If a timeout is specified but a TimeoutAction is not, * the default timeout action is <code>kIOPMAssertionTimeoutActionTurnOff</code> * * @param AssertionID (Output) On successful return, contains a unique reference to a PM assertion. * * @result kIOReturnSuccess, or another IOKit return code on error. */ IOReturn IOPMAssertionCreateWithDescription( CFStringRef AssertionType, CFStringRef Name, CFStringRef Details, CFStringRef HumanReadableReason, CFStringRef LocalizationBundlePath, CFTimeInterval Timeout, CFStringRef TimeoutAction, IOPMAssertionID *AssertionID) __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_4_3); /*! * @function IOPMAssertionCreateWithProperties * * @abstract Creates an IOPMAssertion with more flexibility than <code>@link IOPMAssertionCreateWithDescription @/link</code>. * @param AssertionProperties Dictionary providing the properties of the assertion that need to be created. * @param AssertionID (Output) On successful return, contains a unique reference to a PM assertion. * * @discussion * Create a new PM assertion - the caller must specify the type of assertion, initial level, and its * properties as @link IOPMAssertionDictionaryKeys@/link keys in the <code>AssertionProperties</code> dictionary. * The following keys are recommend and/or required to be specified in the AssertionProperties * dictionary argument. * <ul> * <li> REQUIRED: <code>kIOPMAssertionTypeKey</code> define the assertion type. * * <li> REQUIRED: <code>kIOPMAssertionNameKey</code> Caller must describe the name for the activity that * requires the change in behavior provided by the assertion. * * <li> OPTIONAL: <code>kIOPMAssertionLevelKey</code> define an inital value. If not set, assertion is * turned on after creation. * * <li> OPTIONAL: <code>kIOPMAssertionDetailsKey</code> Caller may describe context-specific data about the * assertion. * * <li> OPTIONAL: <code>kIOPMAssertionHumanReadableReasonKey</code> Caller may describe the reason for creating the assertion * in a localizable CFString. This should be a human readable phrase that describes the actions the * calling process is taking while the assertion is held, like "Downloading TV episodes", or "Compiling Projects" * * <li> OPTIONAL: <code>kIOPMAssertionLocalizationBundlePathKey</code> Caller may provide its bundle's path, where OS X * can localize for GUI display the CFString specified by <code>@link kIOPMAssertionHumanReadableReasonKey@/link</code>. * * <li> OPTIONAL: <code>kIOPMAssertionPlugInIDKey</code> if the caller is a plugin with a different identity than the process * it's loaded in. * * <li> OPTIONAL: <code>kIOPMAssertionFrameworkIDKey</code> if the caller is a framework acting on behalf of a process. * * <li> OPTIONAL: <code>kIOPMAssertionTimeoutKey</code> The caller may specify a timeout. * </ul> */ IOReturn IOPMAssertionCreateWithProperties( CFDictionaryRef AssertionProperties, IOPMAssertionID *AssertionID) __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_3_2); /*! * @function IOPMAssertionDeclareUserActivity * * @abstract Declares that the user is active on the system. * * @discussion This causes the display to power on and postpone display sleep, * up to the user's display sleep Energy Saver settings. * * If you need to hold the display awake for a longer period and you know * how long you'd like to hold it, consider taking assertion * <code>@link kIOPMAssertPreventUserIdleDisplaySleep @/link</code> using * <code>@link IOPMAssertionCreateWithDescription @/link</code> API instead. * * No special privileges are necessary to make this call - any process may * call this API. Caller must specify an AssertionName - NULL is not * a valid input. * * @param AssertionName A string that describes the name of the caller and the activity being * handled by this assertion (e.g. "Mail Compacting Mailboxes"). Name may be no longer * than 128 characters. * * @param userType This parameter specifies if the active user is located locally in front of the * system or connected to the system over the network. Various components of the system * are maintained at different power levels depending on user location. * * @param AssertionID On Success, unique id will be returned in this parameter. Caller * may call this function again with the unique id retured previously to report continous * user activity. The unique id returned by this function may change on each call depending * on how frequently this function call is repeated and the current display sleep timer value. * If you make this call more than once, track the returned value for * assertionID, and pass it in as an argument on each call. * * @result Returns kIOReturnSuccess on success, any other return indicates * PM could not successfully activate the specified assertion. */ IOReturn IOPMAssertionDeclareUserActivity( CFStringRef AssertionName, IOPMUserActiveType userType, IOPMAssertionID *AssertionID) AVAILABLE_MAC_OS_X_VERSION_10_7_AND_LATER; /* This API is introduced in 10.7.3 */ /*! * @function IOPMDeclareNetworkClientActivity * * @abstract A convenience function for handling remote network clients; this is a wrapper for * holding <code>@link kIOPMAssertNetworkClientActive @/link </code> * * @discussion Call this whenever you detect activity from your remote network clients. * This call generates an IPC call, and may block. * * On the first invocation, this will populate parameter * <code>AssertionID</code> with a new assertion ID. * You should pass in this returned assertion ID on every access. * * When system is on AC power, every call to <code>IOPMDeclareNetworkClientActivity</code> * prevents system from idle sleeping and from demand sleeping for the duration of * system sleep timer. When system is on Battery power, every call to * <code>IOPMDeclareNetworkClientActivity</code> prevents system from idle sleeping for the * duration of system sleep timer. * * Assertion created by this interface is valid only for the duration of system sleep timer * from the last call. IOKit will disable <code>AssertionID</code> after that duration. * * If you detect that your remote client is no longer active, please immediately call * <code>@link IOPMAssertionRelease@/link</code. Do not wait for the timeout. * * If your process can detect when remote clients are active and idle, you can skip * this API and directly create <code>@link kIOPMAssertNetworkClientActive @/link</code> yourself. * * If your remote clients require access to the framebuffer or the GPU, then this * isn't the appropriate call for you. Please see * <code>@link IOPMAssertionDeclareUserActivity @/link</code> and pass in argument * <code>@link kIOPMUserActiveRemote @/link</code>. * * @param AssertionName A string that describes the name of the caller and the activity being * handled by this assertion (e.g. "Serving a podcast"). The name must be less than * 128 characters. * * * @param AssertionID On Success, unique id will be returned in this parameter. Caller * may call this function again with the unique id retured previously to report additional * user activity. The unique id returned by this function may change on each call depending * on how frequently this function call is repeated and the current system sleep timer value. * If you make this call more than once, track the returned value for * assertionID, and pass it in as an argument on each call. * * @result Returns kIOReturnSuccess on success, any other return indicates * PM could not successfully activate the specified assertion. */ IOReturn IOPMDeclareNetworkClientActivity( CFStringRef AssertionName, IOPMAssertionID *AssertionID) __OSX_AVAILABLE_STARTING(__MAC_10_9, __IPHONE_NA); /*! * @function IOPMAssertionRetain * * @abstract Increments the assertion's retain count. * @discussion Increments the retain count according to CoreFoundation style retain/release semantics. * Retain count can be inspected in the assertion's info dictionary at * key <code>@link kIOPMAssertionRetainCountKey@/link</code> * @param theAssertion The assertion ID to retain. */ void IOPMAssertionRetain(IOPMAssertionID theAssertion) __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_3_2); /*! * @function IOPMAssertionRelease * * @abstract Decrements the assertion's retain count. * * @discussion If the retain count becomes zero, then this also frees and deactivates * the assertion referred to by <code>assertionID</code> * * Calls to <code>@link IOPMAssertionCreate@/link</code> and <code>@link IOPMAssertionRetain@/link</code> * must each be paired with calls to IOPMAssertionRelease. * * @param AssertionID The assertion_id, returned from IOPMAssertionCreate, to cancel. * * @result Returns kIOReturnSuccess on success. */ IOReturn IOPMAssertionRelease(IOPMAssertionID AssertionID) __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_3_2); /*! * @function IOPMAssertionCopyProperties * @abstract Copies details about an <code>IOPMAssertion</code>. * @discussion Returns a dictionary describing an IOPMAssertion's specifications and current state. * @param theAssertion The assertion ID to copy info about. * @result A dictionary describing the assertion with keys specified in See @link IOPMAssertionDictionaryKeys@/link. * It's the caller's responsibility to release this dictionary. */ CFDictionaryRef IOPMAssertionCopyProperties(IOPMAssertionID theAssertion) __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_3_2); /*! * @function IOPMAssertionSetProperty * @abstract Sets a property in the assertion. * @discussion Only the process that created an assertion may change its properties. * @param theAssertion The <code>@link IOPMAssertionID@/link</code> of the assertion to modify. * @param theProperty The CFString key, from <code>@link IOPMAssertionDictionaryKeys@/link</code> to modify. * @param theValue The property to set. The value must match the CF type expected for the specified key. * @result Returns <code>@link kIOReturnNotPriviliged@/link</code> if the caller doesn't * have permission to modify this assertion. * Returns <code>@link kIOReturnNotFound@/link</code> if PM can't locate this assertion. * Returns <code>@link kIOReturnError@/link</code> upon an unidentified error. * Returns <code>@link kIOReturnSuccess@/link</code> otherwise. */ IOReturn IOPMAssertionSetProperty(IOPMAssertionID theAssertion, CFStringRef theProperty, CFTypeRef theValue) __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_3_2); /*! * @function IOPMCopyAssertionsByProcess * * @abstract Returns a dictionary listing all assertions, grouped by their owning process. * * @discussion Notes: One process may have multiple assertions. Several processes may * have asserted the same assertion to different levels. * * @param AssertionsByPID On success, this returns a dictionary of assertions per process. * At the top level, keys to the CFDictionary are pids stored as CFNumbers (kCFNumberIntType). * The value associated with each CFNumber pid is a CFArray of active assertions. * Each entry in the CFArray is an assertion represented as a CFDictionary. See the keys * kIOPMAssertionTypeKey and kIOPMAssertionLevelKey. * Caller must CFRelease() this dictionary when done. * * @result Returns kIOReturnSuccess on success. */ IOReturn IOPMCopyAssertionsByProcess(CFDictionaryRef *AssertionsByPID) __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_3_2); /*! * @function IOPMCopyAssertionsStatus * * @abstract Returns a list of available assertions and their system-wide levels. * * @discussion The system-wide level is the maximum of all individual assertions' levels. * * @param AssertionsStatus On success, this returns a CFDictionary of all assertions currently available. * The keys in the dictionary are the assertion types, and the value of each is a CFNumber that * represents the aggregate level for that assertion. Caller must CFRelease() this dictionary when done. * * @result Returns kIOReturnSuccess on success. */ IOReturn IOPMCopyAssertionsStatus(CFDictionaryRef *AssertionsStatus) __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_3_2); /*! * @function IOPMAssertionCreate * * @abstract This is a deprecated call to create a power assertion. * * @deprecated IOPMAssertionCreate is deprecated in favor of <code>@link IOPMAssertionCreateWithProperties@/link</code>. * Please use that version of this API instead. * * @discussion No special privileges necessary to make this call - any process may * activate a power assertion. * * @param AssertionType The CFString assertion type to request from the PM system. * @param AssertionLevel Pass kIOPMAssertionLevelOn or kIOPMAssertionLevelOff. * @param AssertionID On success, a unique id will be returned in this parameter. * * @result Returns kIOReturnSuccess on success, any other return indicates * PM could not successfully activate the specified assertion. */ IOReturn IOPMAssertionCreate(CFStringRef AssertionType, IOPMAssertionLevel AssertionLevel, IOPMAssertionID *AssertionID) __OSX_AVAILABLE_BUT_DEPRECATED (__MAC_10_5,__MAC_10_6,__IPHONE_2_0, __IPHONE_2_1); /*! * @function IOPMAssertionCreateWithName * * @abstract The simplest API to create a power assertion. * * @discussion No special privileges are necessary to make this call - any process may * activate a power assertion. Caller must specify an AssertionName - NULL is not * a valid input. * * @param AssertionType The CFString assertion type to request from the PM system. * @param AssertionLevel Pass kIOPMAssertionLevelOn or kIOPMAssertionLevelOff. * @param AssertionName A string that describes the name of the caller and the activity being * handled by this assertion (e.g. "Mail Compacting Mailboxes"). Name may be no longer * than 128 characters. * * @param AssertionID On success, a unique id will be returned in this parameter. * * @result Returns kIOReturnSuccess on success, any other return indicates * PM could not successfully activate the specified assertion. */ IOReturn IOPMAssertionCreateWithName( CFStringRef AssertionType, IOPMAssertionLevel AssertionLevel, CFStringRef AssertionName, IOPMAssertionID *AssertionID) AVAILABLE_MAC_OS_X_VERSION_10_6_AND_LATER; /*! * @define kIOPMAssertionTimeoutKey * @abstract kIOPMAssertionTimeoutKey specifies an outer bound, in seconds, that this assertion should be asserted. * * @discussion If your application hangs, or is unable to complete its assertion task in a reasonable amount of time, * specifying a timeout allows PM to disable your assertion so the system can resume normal activity. * Once a timeout with the <code>@link kIOPMAssertionTimeoutActionTurnOff@/link</code> assertion fires, the level * will be set to <code>@link kIOPMAssertionTimeoutActionTurnOff@/link</code>. The assertion may be re-armed by calling * <code>@link IOPMAssertionSetProperty@/link</code> and setting a new value for for * <code>kIOPMAssertionTimeoutKey</code>. * * This key may be specified in the dictionary passed to <code>@link IOPMAssertionCreateWithProperties@/link</code>. * * This key may be present in the dictionary returned from <code>@link IOPMAssertionCopyProperties@/link</code>. */ #define kIOPMAssertionTimeoutKey CFSTR("TimeoutSeconds") /*! * @define kIOPMAssertionTimeoutActionKey * * @abstract Specifies the action to take upon timeout expiration. * * @discussion Specifying the timeout action only has meaning if you also specify an <code>@link kIOPMAssertionTimeoutKey@/link</code> * If the caller does not specify a timeout action, the default action is <code>@link kIOPMAssertionTimeoutActionTurnOff@/link</code> * * This key may be specified in the dictionary passed to <code>@link IOPMAssertionCreateWithProperties@/link</code>. * * This key may be present in the dictionary returned from <code>@link IOPMAssertionCopyProperties@/link</code>. */ #define kIOPMAssertionTimeoutActionKey CFSTR("TimeoutAction") /*! * @define kIOPMAssertionTimeoutActionLog * * @abstract A potential value for <code>@link kIOPMAssertionTimeoutActionKey@/link</code> * * @discussion When this timeout action is specified, PM will log the timeout event * but will not turn off or affect the setting of the assertion in any way. * */ #define kIOPMAssertionTimeoutActionLog CFSTR("TimeoutActionLog") /*! * @define kIOPMAssertionTimeoutActionTurnOff * * @discussion When a timeout expires with this action, Power Management will log the timeout event, * and will set the assertion's level to <code>@link kIOPMAssertionLevelOff@/link</code>. */ #define kIOPMAssertionTimeoutActionTurnOff CFSTR("TimeoutActionTurnOff") /*! * @define kIOPMAssertionTimeoutActionRelease * * @discussion When a timeout expires with this action, Power Management will log the timeout event, * and will release the assertion. */ #define kIOPMAssertionTimeoutActionRelease CFSTR("TimeoutActionRelease") /*! * @define kIOPMAssertionRetainCountKey * * @discussion kIOPMAssertionRetainCountKey reflects the CoreFoundation-style retain count on this assertion. * Creating or retaining an assertion increments its retain count. * Release an assertion decrements its retain count. * When the retain count decrements to zero, the OS will destroy the object. * * This key can be found in the dictionary returned from <code>@link IOPMAssertionCopyProperties@/link</code>. */ #define kIOPMAssertionRetainCountKey CFSTR("RetainCount") /*! * @define kIOPMAssertionNameKey * * @abstract The CFDictionary key for assertion name. Setting this key is required when you're creating an assertion. * * @discussion <code>kIOPMAssertionNameKey</code> describes the the activity the assertion is protecting. The creator should * specify a CFString value for this key in the dictionary passed to <code>@link IOPMAssertionCreateWithProperties@/link</code> * * The assertion name is separate from the assertion type's behavior - specify a CFString * like "Checking mail" or "Compiling" that describes the task that this assertion protects. * * The CFString you associate with this key does not have to be localizable (OS X will not attempt to localize it.) * * Describe your assertion as thoroughly as possible. See these other keys that can you can also set to add explanation * to an assertion: * <ul> * <li> OPTIONAL <code>@link kIOPMAssertionDetailsKey@/link</code> * <li> OPTIONAL <code>@link kIOPMAssertionHumanReadableReasonKey @/link</code> * <li> OPTIONAL <code>@link kIOPMAssertionLocalizationBundlePathKey@/link</code> * </ul> */ #define kIOPMAssertionNameKey CFSTR("AssertName") /*! * @define kIOPMAssertionDetailsKey * * @abstract You may provide extra, contextual information about an assertion for admins and for debugging * in this key. Setting this key in an assertion dictionary is optional. * * @discussion Please name your assertion something unique with <code>@link kIOPMAssertionNameKey@/link</code> first. * If you have more data to describe this assertion, put it here as a CFString. * * ' EXAMPLE: OS X creates an assertion named <code>com.apple.powermanagement.tty</code> to prevent sleep for * remote-logged in users. To identify the cause for these assertions, OS X sets <code>kIOPMAssertionDetailsKey</code> * to the CFString device path of the active remote session(s), e.g. "/dev/ttys000 /dev/ttys004" * * The CFString you associate with this key does not have to be localizable (OS X will not attempt to localize it.) * * Describe your assertion as thoroughly as possible. See these other keys that can you can set to add explanation * to an assertion: * <ul> * <li>REQUIRED <code>@link kIOPMAssertionNameKey@/link</code> * <li>OPTIONAL <code>@link kIOPMAssertionHumanReadableReasonKey @/link</code> * <li>OPTIONAL <code>@link kIOPMAssertionLocalizationBundlePathKey@/link</code> * </ul> */ #define kIOPMAssertionDetailsKey CFSTR("Details") /*! * @define kIOPMAssertionHumanReadableReasonKey * * @abstract Optional key that provides a localizable string for OS X to display PM Assertions in the GUI. * * @discussion The caller should specify this string in <code>@link IOPMAssertionCreateWithProperties@/link</code>. * If present, OS X may display this string, localized to the user's language, to explain changes in system * behavior caused by the assertion. * * If set, the caller must also specify a bundle path for the key * <code>@link kIOPMAssertionLocalizationBundlePathKey@/link</code> * The bundle at that path should contain localization info for the specified string. * * This key may be specified in the dictionary passed to <code>@link IOPMAssertionCreateWithProperties@/link</code>. * * This key may be present in the dictionary returned from <code>@link IOPMAssertionCopyProperties@/link</code>. * * Describe your assertion as thoroughly as possible. See these other keys that can you can set to add explanation * to an assertion: * <ul> * <li>REQUIRED <code>@link kIOPMAssertionNameKey@/link</code> * <li>OPTIONAL <code>@link kIOPMAssertionDetailsKey @/link</code> * </ul> */ #define kIOPMAssertionHumanReadableReasonKey CFSTR("HumanReadableReason") /*! * @define kIOPMAssertionLocalizationBundlePathKey * * @abstract Refers to a CFURL, as a CFString, identifying the path to the caller's * bundle, which contains localization info. * * @discussion The bundle must contain localizations for * <code>@link kIOPMAssertionHumanReadableReasonKey@/link</code> * * This key may be specified in the dictionary passed to <code>@link IOPMAssertionCreateWithProperties@/link</code>. * * This key may be present in the dictionary returned from <code>@link IOPMAssertionCopyProperties@/link</code>. */ #define kIOPMAssertionLocalizationBundlePathKey CFSTR("BundlePath") /*! * @define kIOPMAssertionFrameworkIDKey * * @abstract Specify if the assertion creator is a framework. * * @discussion If the code that creates the assertion resides in a framework or library, the caller * should specify a CFBundleIdentifier, as a CFString, identifying that bundle here. * This info helps developers and administrators determine the source of an assertion. * * This key may be specified in the dictionary passed to <code>@link IOPMAssertionCreateWithProperties@/link</code>. * * This key may be present in the dictionary returned from <code>@link IOPMAssertionCopyProperties@/link</code>. */ #define kIOPMAssertionFrameworkIDKey CFSTR("FrameworkBundleID") /*! * @define kIOPMAssertionPlugInIDKey * * @abstract Specify if the assertion creator is a plugin. * * @discussion If the code that creates the assertion resides in a plugin, the caller * should specify a CFBundleIdentifier, as a CFString, identifying the plugin's bundle here. * This info helps developers and administrators determine the source of an assertion. * * This key may be specified in the dictionary passed to <code>@link IOPMAssertionCreateWithProperties@/link</code>. * * This key may be present in the dictionary returned from <code>@link IOPMAssertionCopyProperties@/link</code>. */ #define kIOPMAssertionPlugInIDKey CFSTR("PlugInBundleID") /*! * @define kIOPMAssertionTypeKey * * @abstract The CFDictionary key for assertion type in an assertion info dictionary. * * @discussion The value for this key will be a CFStringRef, with the value of the assertion * type specified at creation time. * Note that OS X may substitute a support assertion type string if the caller * specifies a deprecated assertion type; in that case the value for this key could * differ from the caller-provided assertion type. */ #define kIOPMAssertionTypeKey CFSTR("AssertType") /*! * @define kIOPMAssertionLevelKey * * @abstract The CFDictionary key for assertion level in an assertion info dictionary. * * @discussion The value for this key will be a CFNumber, kCFNumberIntType with value * <code>kIOPMAssertionLevelOff</code> or <code>kIOPMAssertionLevelOn</code>. * The level reflects the assertion's level set at creation, or adjusted via * <code>@link IOPMAssertionSetProperty@/link</code> */ #define kIOPMAssertionLevelKey CFSTR("AssertLevel") /*! * @define kIOPMAssertionTypePreventUserIdleSystemSleep * @abstract This assertion type is identical to <code>@link kIOPMAssertPreventUserIdleSystemSleep @/link</code> * Please use that instead. */ #define kIOPMAssertionTypePreventUserIdleSystemSleep kIOPMAssertPreventUserIdleSystemSleep /*! * @define kIOPMAssertionTypePreventUserIdleDisplaySleep * @abstract This assertion type is identical to <code>@link kIOPMAssertPreventUserIdleDisplaySleep @/link</code> * Please use that instead. */ #define kIOPMAssertionTypePreventUserIdleDisplaySleep kIOPMAssertPreventUserIdleDisplaySleep /*! * @define kIOPMAssertionTypePreventSystemSleep * @deprecated Deprecated in 10.9. This assertion is not supported in any OS X releases. * @abstract This assertion is deprecated. Do not use it. * @discussion Please consider using either assertion type for system activities: * <ul> * <li><code>@link kIOPMAssertRemoteAccess @/link</code></li> * <li><code>@link kIOPMAssertPreventUserIdleSystemSleep @/link</code></li> * </ul> */ #define kIOPMAssertionTypePreventSystemSleep CFSTR("PreventSystemSleep") /*! * @define kIOPMAssertionTypeNoIdleSleep * @deprecated Deprecated in 10.7. * @abstract Please use assertion type <code>@link kIOPMAssertPreventUserIdleSystemSleep@/link</code> instead. */ #define kIOPMAssertionTypeNoIdleSleep CFSTR("NoIdleSleepAssertion") /*! * @define kIOPMAssertionTypeNoDisplaySleep * @deprecated Deprecated in 10.7. * @abstract Please use assertion type <code>@link kIOPMAssertPreventUserIdleDisplaySleep@/link</code> instead. */ #define kIOPMAssertionTypeNoDisplaySleep CFSTR("NoDisplaySleepAssertion") #pragma mark IOSystemLoadAdvisory /*! * @functiongroup IOSystemLoadAdvisory */ /*! @define kIOSystemLoadAdvisoryNotifyName @abstract The notification by this name fires when system "SystemLoadAdvisory" status changes. @discussion Pass this string as an argument to register via notify(3). You can query SystemLoadAdvisory state via notify_get_state() when this notification fires - this is more efficient than calling IOGetSystemLoadAdvisory(), and returns an identical combined SystemLoadAdvisory value. */ #define kIOSystemLoadAdvisoryNotifyName "com.apple.system.powermanagement.SystemLoadAdvisory" /*! @typedef IOSystemLoadAdvisoryLevel @abstract Return type for IOGetSystemLoadAdvisory @discussion Value is one of kIOSystemLoadAdvisoryLevelGreat, kIOSystemLoadAdvisoryLevelOK, or kIOSystemLoadAdvisoryLevelBad. */ typedef int IOSystemLoadAdvisoryLevel; enum { kIOSystemLoadAdvisoryLevelBad = 1, kIOSystemLoadAdvisoryLevelOK = 2, kIOSystemLoadAdvisoryLevelGreat = 3 }; /*! @define kIOSystemLoadAdvisoryUserLevelKey @abstract Key for dictionary returned by IOCopySystemLoadAdvisoryDetailed @discussion Indicates user activity constraints on the current SystemLoadAdvisory level. */ #define kIOSystemLoadAdvisoryUserLevelKey CFSTR("UserLevel") /*! @define kIOSystemLoadAdvisoryBatteryLevelKey @abstract Key for dictionary returned by IOCopySystemLoadAdvisoryDetailed @discussion Indicates battery constraints on the current SystemLoadAdvisory level. */ #define kIOSystemLoadAdvisoryBatteryLevelKey CFSTR("BatteryLevel") /*! @define kIOSystemLoadAdvisoryThermalLevelKey @abstract Key for dictionary returned by IOCopySystemLoadAdvisoryDetailed @discussion Indicates thermal constraints on the current SystemLoadAdvisory level. */ #define kIOSystemLoadAdvisoryThermalLevelKey CFSTR("ThermalLevel") /*! @define kIOSystemLoadAdvisoryCombinedLevelKey @abstract Key for dictionary returned by IOCopySystemLoadAdvisoryDetailed @discussion Provides a combined level based on UserLevel, BatteryLevel, and ThermalLevels; the combined level is the minimum of these levels. In the future, this combined level may represent new levels as well. The combined level is identical to the value returned by IOGetSystemLoadAdvisory(). */ #define kIOSystemLoadAdvisoryCombinedLevelKey CFSTR("CombinedLevel") /*! @function IOGetSystemLoadAdvisory @abstract Returns a hint about whether now would be a good time to perform time-insensitive work. @discussion Based on user and system load, IOGetSystemLoadAdvisory determines "better" and "worse" times to run optional or time-insensitive CPU or disk work. Applications may use this result to avoid degrading the user experience. If it is a "Bad" or "OK" time to perform work, applications should slow down and perform work less aggressively. There is no guarantee that the system will ever be in "Great" condition to perform work - all essential work must still be performed even in "Bad", or "OK" times. Completely optional work, such as updating caches, may be postponed indefinitely. Note: You may more efficiently read the SystemLoadAdvisory level using notify_get_state() instead of IOGetSystemLoadAdvisory. The results are identical. notify_get_state() requires that you pass the token argument received by registering for SystemLoadAdvisory notifications. @return IOSystemLoadAdvisoryLevel - one of: <ul> <li>kIOSystemLoadAdvisoryLevelGreat - A Good time to perform time-insensitive work. <li>kIOSystemLoadAdvisoryLevelOK - An OK time to perform time-insensitive work. <li>kIOSystemLoadAdvisoryLevelBad - A Bad time to perform time-insensitive work. </ul> */ IOSystemLoadAdvisoryLevel IOGetSystemLoadAdvisory( void ); /*! @function IOCopySystemLoadAdvisoryDetailed @abstract Indicates how user activity, battery level, and thermal level each contribute to the overall "SystemLoadAdvisory" level. In the future, this combined level may represent new levels as well. @discussion See dictionary keys defined above. @return Returns a CFDictionaryRef, or NULL on error. Caller must release the returned dictionary. */ CFDictionaryRef IOCopySystemLoadAdvisoryDetailed(void); /*! * @functiongroup CPU Power & Thermal */ /*! * @define kIOPMCPUPowerNotificationKey * @abstract Key to register for BSD style notifications on CPU power or thermal change. */ #define kIOPMCPUPowerNotificationKey "com.apple.system.power.CPU" /*! * @define kIOPMThermalWarningNotificationKey * @abstract Key to register for BSD style notifications on system thermal warnings. */ #define kIOPMThermalWarningNotificationKey "com.apple.system.power.thermal_warning" /*! * @function IOPMCopyCPUPowerStatus * @abstract Copy status of all current CPU power levels. * @discussion The returned dictionary may define some of these keys, * as defined in IOPM.h: * <ul> * <li>kIOPMCPUPowerLimitProcessorSpeedKey * <li>kIOPMCPUPowerLimitProcessorCountKey * <li>kIOPMCPUPowerLimitSchedulerTimeKey * </ul> * @param cpuPowerStatus Upon success, a pointer to a dictionary defining CPU power; * otherwise NULL. Pointer will be populated with a newly created dictionary * upon successful return. Caller must release dictionary. * @result kIOReturnSuccess, or other error report. Returns kIOReturnNotFound if * CPU PowerStatus has not been published. */ IOReturn IOPMCopyCPUPowerStatus(CFDictionaryRef *cpuPowerStatus); /*! * @function IOPMGetThermalWarningLevel * @abstract Get thermal warning level of the system. * @result An integer pointer declaring the power warning level of the system. * The value of the integer is one of (defined in IOPM.h): * <ul> * <li>kIOPMThermalWarningLevelNormal * <li>kIOPMThermalWarningLevelDanger * <li>kIOPMThermalWarningLevelCrisis * </ul> * Upon success the thermal level value will be found at the * pointer argument. * @result kIOReturnSuccess, or other error report. Returns kIOReturnNotFound if * thermal warning level has not been published. */ IOReturn IOPMGetThermalWarningLevel(uint32_t *thermalLevel); #ifdef __cplusplus } #endif #endif
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/pwr_mgt/IOPMKeys.h
/* * Copyright (c) 2006 Apple Computer, Inc. All rights reserved. * * @APPLE_LICENSE_HEADER_START@ * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this * file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_LICENSE_HEADER_END@ */ /*! @header IOPMKeys.h IOPMKeys.h defines C strings for use accessing power management data. Note that all of these C strings must be converted to CFStrings before use. You can wrap them with the CFSTR() macro, or create a CFStringRef (that you must later CFRelease()) using CFStringCreateWithCString() */ #ifndef _IOPMKEYS_H_ #define _IOPMKEYS_H_ /* * Types of power event * These are potential arguments to IOPMSchedulePowerEvent(). * These are all potential values of the kIOPMPowerEventTypeKey in the CFDictionaries * returned by IOPMCopyScheduledPowerEvents(). */ /*! @define kIOPMAutoWake @abstract Value for scheduled wake from sleep. */ #define kIOPMAutoWake "wake" /*! @define kIOPMAutoPowerOn @abstract Value for scheduled power on from off state. */ #define kIOPMAutoPowerOn "poweron" /*! @define kIOPMAutoWakeOrPowerOn @abstract Value for scheduled wake from sleep, or power on. The system will either wake OR power on, whichever is necessary. */ #define kIOPMAutoWakeOrPowerOn "wakepoweron" /*! @define kIOPMAutoSleep @abstract Value for scheduled sleep. */ #define kIOPMAutoSleep "sleep" /*! @define kIOPMAutoShutdown @abstract Value for scheduled shutdown. */ #define kIOPMAutoShutdown "shutdown" /*! @define kIOPMAutoRestart @abstract Value for scheduled restart. */ #define kIOPMAutoRestart "restart" /* * Keys for evaluating the CFDictionaries returned by IOPMCopyScheduledPowerEvents() */ /*! @define kIOPMPowerEventTimeKey @abstract Key for the time of the scheduled power event. Value is a CFDateRef. */ #define kIOPMPowerEventTimeKey "time" /*! @define kIOPMPowerEventAppNameKey @abstract Key for the CFBundleIdentifier of the app that scheduled the power event. Value is a CFStringRef. */ #define kIOPMPowerEventAppNameKey "scheduledby" /*! @define kIOPMPowerEventAppPIDKey @abstract Key for the PID the App that scheduled the power event. Value is a CFNumber integer. */ #define kIOPMPowerEventAppPIDKey "appPID" /*! @define kIOPMPowerEventTypeKey @abstract Key for the type of power event. Value is a CFStringRef, with the c-string value of one of the "kIOPMAuto" strings. */ #define kIOPMPowerEventTypeKey "eventtype" #endif
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/i2c/IOI2CInterface.h
/* * Copyright (c) 1998-2000 Apple Computer, Inc. All rights reserved. * * @APPLE_LICENSE_HEADER_START@ * * The contents of this file constitute Original Code as defined in and * are subject to the Apple Public Source License Version 1.1 (the * "License"). You may not use this file except in compliance with the * License. Please obtain a copy of the License at * http://www.apple.com/publicsource and read it before using this file. * * This Original Code and all software distributed under the License are * distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT. Please see the * License for the specific language governing rights and limitations * under the License. * * @APPLE_LICENSE_HEADER_END@ */ #ifndef _IOKIT_IOI2CINTERFACE_H #define _IOKIT_IOI2CINTERFACE_H #include <IOKit/IOTypes.h> /* IOOptionBits */ #include <stdint.h> /* uint32_t */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ typedef struct IOI2CRequest IOI2CRequest; typedef struct IOI2CBuffer IOI2CBuffer; typedef void (*IOI2CRequestCompletion) (IOI2CRequest * request); // IOI2CRequest.sendTransactionType, IOI2CRequest.replyTransactionType enum { kIOI2CNoTransactionType = 0, kIOI2CSimpleTransactionType = 1, kIOI2CDDCciReplyTransactionType = 2, kIOI2CCombinedTransactionType = 3, kIOI2CDisplayPortNativeTransactionType = 4 }; // IOI2CRequest.commFlags enum { kIOI2CUseSubAddressCommFlag = 0x00000002 }; /*! * @struct IOI2CRequest * @abstract A structure defining an I2C bus transaction. * @discussion This structure is used to request an I2C transaction consisting of a send (write) to and reply (read) from a device, either of which is optional, to be carried out atomically on an I2C bus. * @field __reservedA Set to zero. * @field result The result of the transaction. Common errors are kIOReturnNoDevice if there is no device responding at the given address, kIOReturnUnsupportedMode if the type of transaction is unsupported on the requested bus. * @field completion A completion routine to be executed when the request completes. If NULL is passed, the request is synchronous, otherwise it may execute asynchronously. * @field commFlags Flags that modify the I2C transaction type. The following flags are defined:<br> * kIOI2CUseSubAddressCommFlag Transaction includes a subaddress.<br> * @field minReplyDelay Minimum delay as absolute time between send and reply transactions. * @field sendAddress I2C address to write. * @field sendSubAddress I2C subaddress to write. * @field __reservedB Set to zero. * @field sendTransactionType The following types of transaction are defined for the send part of the request:<br> * kIOI2CNoTransactionType No send transaction to perform. <br> * kIOI2CSimpleTransactionType Simple I2C message. <br> * kIOI2CCombinedTransactionType Combined format I2C R/~W transaction. <br> * @field sendBuffer Pointer to the send buffer. * @field sendBytes Number of bytes to send. Set to actual bytes sent on completion of the request. * @field replyAddress I2C Address from which to read. * @field replySubAddress I2C Address from which to read. * @field __reservedC Set to zero. * @field replyTransactionType The following types of transaction are defined for the reply part of the request:<br> * kIOI2CNoTransactionType No reply transaction to perform. <br> * kIOI2CSimpleTransactionType Simple I2C message. <br> * kIOI2CDDCciReplyTransactionType DDC/ci message (with embedded length). See VESA DDC/ci specification. <br> * kIOI2CCombinedTransactionType Combined format I2C R/~W transaction. <br> * @field replyBuffer Pointer to the reply buffer. * @field replyBytes Max bytes to reply (size of replyBuffer). Set to actual bytes received on completion of the request. * @field __reservedD Set to zero. */ #pragma pack(push, 4) struct IOI2CRequest { IOOptionBits sendTransactionType; IOOptionBits replyTransactionType; uint32_t sendAddress; uint32_t replyAddress; uint8_t sendSubAddress; uint8_t replySubAddress; uint8_t __reservedA[2]; uint64_t minReplyDelay; IOReturn result; IOOptionBits commFlags; #if defined(__LP64__) uint32_t __padA; #else vm_address_t sendBuffer; #endif uint32_t sendBytes; uint32_t __reservedB[2]; #if defined(__LP64__) uint32_t __padB; #else vm_address_t replyBuffer; #endif uint32_t replyBytes; IOI2CRequestCompletion completion; #if !defined(__LP64__) uint32_t __padC[5]; #else vm_address_t sendBuffer; vm_address_t replyBuffer; #endif uint32_t __reservedC[10]; }; #pragma pack(pop) /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #define kIOI2CInterfaceClassName "IOI2CInterface" #define kIOI2CInterfaceIDKey "IOI2CInterfaceID" #define kIOI2CBusTypeKey "IOI2CBusType" #define kIOI2CTransactionTypesKey "IOI2CTransactionTypes" #define kIOI2CSupportedCommFlagsKey "IOI2CSupportedCommFlags" #define kIOFBI2CInterfaceInfoKey "IOFBI2CInterfaceInfo" #define kIOFBI2CInterfaceIDsKey "IOFBI2CInterfaceIDs" // kIOI2CBusTypeKey values enum { kIOI2CBusTypeI2C = 1, kIOI2CBusTypeDisplayPort = 2 }; /*! * @struct IOI2CBusTiming * @abstract A structure defining low level timing for an I2C bus. * @discussion This structure is used to specify timeouts and pulse widths for an I2C bus implementation. * @field bitTimeout Maximum time a slave can delay (by pulling the clock line low) a single bit response. * @field byteTimeout Maximum time a slave can delay (by pulling the clock line low) the first bit of a byte response. * @field acknowledgeTimeout Maximum time to wait for a slave to respond with an ACK after writing a byte. * @field startTimeout Maximum time to wait for a slave to respond after a start signal. * @field riseFallTime Time to wait after any change in output signal. * @field __reservedA Set to zero. */ struct IOI2CBusTiming { AbsoluteTime bitTimeout; AbsoluteTime byteTimeout; AbsoluteTime acknowledgeTimeout; AbsoluteTime startTimeout; AbsoluteTime holdTime; AbsoluteTime riseFallTime; UInt32 __reservedA[8]; }; typedef struct IOI2CBusTiming IOI2CBusTiming; #ifndef KERNEL /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ // options for IOFBCopyI2CInterfaceForBus() enum { kIOI2CBusNumberMask = 0x000000ff }; /*! @function IOFBGetI2CInterfaceCount @abstract Returns a count of I2C interfaces available associated with an IOFramebuffer instance. @discussion Returns a count of I2C interfaces available associated with an IOFramebuffer instance. @param framebuffer The io_service_t of an IOFramebuffer instance. CoreGraphics will provide this for a CGDisplay with the CGDisplayIOServicePort() call. @param count Interface count is returned. @result An IOReturn code. */ IOReturn IOFBGetI2CInterfaceCount( io_service_t framebuffer, IOItemCount * count ); /*! @function IOFBCopyI2CInterfaceForBus @abstract Returns an instance of an I2C bus interface, associated with an IOFramebuffer instance / bus index pair. @discussion Some graphics devices will allow access to an I2C bus routed through a display connector in order to control external devices on that bus. This function returns an instance of an I2C bus interface, associated with an IOFramebuffer instance / bus index pair. The number of I2C buses is available from the IOFBGetI2CInterfaceCount() call. The interface may be used with the IOI2CInterfaceOpen/Close/SendRequest() calls to carry out I2C transactions on that bus. Not all graphics devices support this functionality. @param bus The zero based index of the bus on the requested framebuffer. @param interface The interface instance is returned. The caller should release this instance with IOObjectRelease(). @result An IOReturn code. */ IOReturn IOFBCopyI2CInterfaceForBus( io_service_t framebuffer, IOOptionBits bus, io_service_t * interface ); typedef struct IOI2CConnect * IOI2CConnectRef; /* struct IOI2CConnect is opaque */ IOReturn IOI2CCopyInterfaceForID( CFTypeRef identifier, io_service_t * interface ); /*! @function IOI2CInterfaceOpen @abstract Opens an instance of an I2C bus interface, allowing I2C requests to be made. @discussion An instance of an I2C bus interface, obtained by IOFBCopyI2CInterfaceForBus, is opened with this function allowing I2C requests to be made. @param interface An I2C bus interface (see IOFBCopyI2CInterfaceForBus). The interface may be released after this call is made. @param options Pass kNilOptions. @param connect The opaque IOI2CConnectRef is returned, for use with IOI2CSendRequest() and IOI2CInterfaceClose(). @result An IOReturn code. */ IOReturn IOI2CInterfaceOpen( io_service_t interface, IOOptionBits options, IOI2CConnectRef * connect ); /*! @function IOI2CInterfaceClose @abstract Closes an IOI2CConnectRef. @discussion Frees the resources associated with an IOI2CConnectRef. @param connect The opaque IOI2CConnectRef returned by IOI2CInterfaceOpen(). @param options Pass kNilOptions. @result An IOReturn code. */ IOReturn IOI2CInterfaceClose( IOI2CConnectRef connect, IOOptionBits options ); /*! @function IOI2CSendRequest @abstract Carries out the I2C transaction specified by an IOI2CRequest structure. @discussion Frees the resources associated with an IOI2CConnectRef. @param connect The opaque IOI2CConnectRef returned by IOI2CInterfaceOpen(). @param options Pass kNilOptions. @param request Pass a pointer to a IOI2CRequest structure describing the request. If an asynchronous request (with a non-NULL completion routine) the request structure must be valid for the life of the request. @result An IOReturn code reflecting only the result of starting the transaction. If the result of IOI2CSendRequest() is kIOReturnSuccess, the I2C transaction result is returned in the result field of the request structure. */ IOReturn IOI2CSendRequest( IOI2CConnectRef connect, IOOptionBits options, IOI2CRequest * request ); #else /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /*! @class IOI2CInterface @abstract The base class for an I2C bus interface. @discussion The IOI2CInterface base class defines an I2C bus interface. Not useful for developers. */ class IOI2CInterface : public IOService { OSDeclareDefaultStructors(IOI2CInterface) protected: UInt64 fID; public: IOReturn newUserClient( task_t owningTask, void * security_id, UInt32 type, IOUserClient ** handler ) APPLE_KEXT_OVERRIDE; bool registerI2C( UInt64 id ); virtual IOReturn startIO( IOI2CRequest * request ) = 0; }; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #endif /* KERNEL */ #endif /* ! _IOKIT_IOI2CINTERFACE_H */
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/ps/IOPowerSources.h
/* * Copyright (c) 2002 Apple Computer, Inc. All rights reserved. * * @APPLE_LICENSE_HEADER_START@ * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this * file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_LICENSE_HEADER_END@ */ /* * HISTORY * */ #ifndef _IOKIT_IOPOWERSOURCES_H #define _IOKIT_IOPOWERSOURCES_H #include <sys/cdefs.h> #include <CoreFoundation/CoreFoundation.h> /* CFTimeInterval, CFArrayRef, CFDictionaryRef, CFRunLoopSourceRef */ __BEGIN_DECLS /*! * @header IOPowerSources.h * * @discussion IOPowerSources provides uniform access to the state of power sources attached to the system. * You can receive a change notification when any power source data changes. * "Power sources" currently include batteries and UPS devices. * * The header follows CF semantics in that it is the caller's responsibility to * CFRelease() anything returned by a "Copy" function, and the caller should not * CFRelease() anything returned by a "Get" function. */ /*! * @functiongroup Low Power Warnings */ /*! @constant kIOPSNotifyLowBattery * * @abstract Notify(3) key. IOKit posts kIOPSNotifyLowBattery notifications when the * system is drawing from limited battery power, and the battery time * remaining drops into a warnable level. * * See also kIOPSNotifyPowerSource, and kIOPSNotifyTimeRemaining */ #define kIOPSNotifyLowBattery "com.apple.system.powersources.lowbattery" /*! * @enum IOPSLowBatteryWarningLevel * * @discussion Possible return values from <code>@link IOPSGetBatteryWarningLevel@/link</code> */ typedef enum { /*! @constant kIOPSLowBatteryWarningNone * * @abstract The system is not in a low battery situation, or is on drawing from an external power source. * * @discussion The system displays no low power warnings; neither should application clients of this * API. */ kIOPSLowBatteryWarningNone = 1, /*! @constant kIOPSLowBatteryWarningEarly * * @abstract The battery can provide no more than 20 minutes of runtime. * * @discussion OS X makes no guarantees that the system shall remain in Early Warning for 20 minutes. * Batteries are frequently calibrated differently and may provide runtime * for more, or less, than the estimated 20 minutes. * OS X alerts the user by changing the color of BatteryMonitor to red. * Warning the user is optional for full screen apps. */ kIOPSLowBatteryWarningEarly = 2, /*! @constant kIOPSLowBatteryWarningFinal * * @abstract The battery can provide no more than 10 minutes of runtime. * * @discussion OS X makes no guarantees that the system shall remain in Final Warning for 10 minutes. * Batteries are frequently calibrated differently and may provide runtime * for more, or less, than the estimated 10 minutes. */ kIOPSLowBatteryWarningFinal = 3 } IOPSLowBatteryWarningLevel; /*! @function IOPSGetBatteryWarningLevel * * @abstract Indicates whether the system is at a low battery warning level. * * @discussion If your app runs in full screen mode and occludes OS X's battery monitor's low * battery warnings, you should alert the user at least when the system * is in kIOPSLowBatteryWarnFinal. */ IOPSLowBatteryWarningLevel IOPSGetBatteryWarningLevel(void); /*! * @functiongroup Quick Power Source Info */ /*! * @define kIOPSNotifyTimeRemaining * C-string key for a notification of changes to any power source's time remaining estimate. * IOKit also posts this notification when the active power source changes between AC, Battery, and UPS. * * If you only need to detect when the power source changes between AC, Battery, or UPS, please use * <code>@link kIOPSNotifyPowerSource @/link</code>; your code will run less often and conserve battery life. * * See API <code>@link IOPSGetTimeRemainingEstimate @/link</code> to determine whether the active power source is * limited or unlimited; and to determine the estimated time remaining until empty. * * Use notify(3) API to register for notifications. */ #define kIOPSNotifyTimeRemaining "com.apple.system.powersources.timeremaining" #define kIOPSTimeRemainingNotificationKey kIOPSNotifyTimeRemaining /*! * @define kIOPSNotifyPowerSource * @abstract C-string key for a notification of changes to the active power source. * @discussion Use this notification to discover when the active power source changes from AC power (unlimited/wall power), * to Battery Power or UPS Power (limited power). IOKit will not deliver this notification when a battery's * time remaining changes, only when the active power source changes. This makes it a more efficient * choice for clients only interested in differentiating AC vs Battery. * * See API <code>@link IOPSGetTimeRemainingEstimate @/link</code> to determine whether the active power source is * limited or unlimited. * * Example: IOKit posts kIOPSNotifyPowerSource upon connecting or disconnecting AC power to a laptop. * IOKit posts kIOPSNotifyPowerSource upon a UPS losing AC Power; as the system switches to a limited * UPS battery power source. * * Use notify(3) API to register for notifications. * */ #define kIOPSNotifyPowerSource "com.apple.system.powersources.source" /*! * @define kIOPSNotifyAttach * @abstract C-string key for a notification when a power source is attached or detached. * @discussion Example: IOKit posts kIOPSNotifyAttach upon detection of internal battery. * IOKit posts kIOPSNotifyAttach when a user attaches or detaches an external UPS. * * Note that IOKit doesn't deliver kIOPSNotifyAttach upon plugging or unplugging AC Power to a laptop; see * <code>@link kIOPSNotifyPowerSource@/link</code> for changes to the active power source. * * IOKit may take many seconds to discover a built-in battery at boot time. If your user process runs * at early boot, use kIOPSNotifyAttach to detect an IOPowerSource's appearance. * Use notify(3) API to register for notifications. */ #define kIOPSNotifyAttach "com.apple.system.powersources.attach" /*! * @define kIOPSNotifyAnyPowerSource * @abstract C-string key for a notification that of changes to any attribute of any IOPowerSource. * @discussion Use notify(3) API to register for notifications. * IOKit posts this notification more frequently than the other notifications, and thus uses more * energy to run your code. To conserve CPU cycles and battery life, please consider another notification * that also fits your needs. Please consider these instead: * <code>@link kIOPSNotifyPowerSource @/link</code>, * <code>@link kIOPSNotifyTimeRemaining @/link</code> * */ #define kIOPSNotifyAnyPowerSource "com.apple.system.powersources" /*! * @constant kIOPSTimeRemainingUnknown * Possible return value from <code>@link IOPSGetTimeRemainingEstimate@/link</code> * Indicates the system is connected to a limited power source, but the system is still * calculating a time remaining estimate. Check for a valid estimate again when IOKit posts the * notification <code>@link kIOPSPowerSourcesNotificationKey@/link</code>. */ #define kIOPSTimeRemainingUnknown ((CFTimeInterval)-1.0) /*! * @constant kIOPSTimeRemainingUnlimited * Possible return value from <code>@link IOPSGetTimeRemainingEstimate@/link</code> * Indicates the system is connected to an external power source, without a time limit. */ #define kIOPSTimeRemainingUnlimited ((CFTimeInterval)-2.0) /*! * @constant kIOPMUPSPowerKey * Possible return value from <code>@link IOPSGetProvidingPowerSourceType@/link</code> * Indicates that the system is connected to an external power source, that identifies itself as * as an UPS. */ #define kIOPMUPSPowerKey "UPS Power" /*! * @constant kIOPMBatteryPowerKey * Possible return value from <code>@link IOPSGetProvidingPowerSourceType@/link</code> * Indicates that the system is connected to internal battery power source. */ #define kIOPMBatteryPowerKey "Battery Power" /*! * @constant kIOPMACPowerKey * Possible return value from <code>@link IOPSGetProvidingPowerSourceType@/link</code> * Indicates that the system is connected to an external unlimited power source. */ #define kIOPMACPowerKey "AC Power" /*! * @function IOPSGetTimeRemainingEstimate * * @abstract Returns the estimated minutes remaining until all power sources * (battery and/or UPS's) are empty, or returns <code>@link kIOPSTimeRemainingUnlimited@/link </code> * if attached to an unlimited power source. * * @discussion * If attached to an "Unlimited" power source, like AC power or any external source, the * return value is <code>@link kIOPSTimeRemainingUnlimited@/link </code> * * If the system is on "Limited" power, like a battery or UPS, * but is still calculating the time remaining, which may * take several seconds after each system power event * (e.g. waking from sleep, or unplugging AC Power), the return value is * <code>@link kIOPSTimeRemainingUnknown@/link </code> * * Otherwise, if the system is on "Limited" power and the system has an accurate time * remaining estimate, the system returns a CFTimeInterval estimate of the time * remaining until the system is out of battery power. * * If you require more detailed battery information, use * <code>@link IOPSCopyPowerSourcesInfo @/link></code> * and <code>@link IOPSGetPowerSourceDescription @/link></code>. * * @result * Returns <code>@link kIOPSTimeRemainingUnknown@/link</code> if the * OS cannot determine the time remaining. * * Returns <code>@link kIOPSTimeRemainingUnlimited@/link</code> if the * system has an unlimited power source. * * Otherwise returns a positive number of type CFTimeInterval, indicating the time * remaining in seconds until all power sources are depleted. */ CFTimeInterval IOPSGetTimeRemainingEstimate(void); /*! * @functiongroup Power Source Descriptions */ typedef void (*IOPowerSourceCallbackType)(void *context); /*! @function IOPSCopyPowerSourcesInfo * * @abstract Returns a blob of Power Source information in an opaque CFTypeRef. * * @discussion Clients should not directly access data in the returned CFTypeRef - * they should use the accessor functions IOPSCopyPowerSourcesList and * IOPSGetPowerSourceDescription, instead. * * @result NULL if errors were encountered, a CFTypeRef otherwise. * Caller must CFRelease() the return value when done accessing it. */ CFTypeRef IOPSCopyPowerSourcesInfo(void); /*! @function IOPSCopyPowerSourcesList * * @abstract Returns a CFArray of Power Source handles, each of type CFTypeRef. * * @discussion The caller shouldn't directly access the CFTypeRefs, but should use * IOPSGetPowerSourceDescription on each member of the CFArrayRef. * * @param blob Takes the CFTypeRef returned by IOPSCopyPowerSourcesInfo() * * @result Returns NULL if errors were encountered, otherwise a CFArray of CFTypeRefs. * Caller must CFRelease() the returned CFArrayRef. */ CFArrayRef IOPSCopyPowerSourcesList(CFTypeRef blob); /*! @function IOPSGetPowerSourceDescription * * @abstract Returns a CFDictionary with readable information about the specific power source. * * @discussion See the C-strings defined in IOPSKeys.h for specific keys into the dictionary. * Don't expect all keys to be present in any dictionary. Some power sources, for example, * may not support the "Time Remaining To Empty" key and it will not be present in their dictionaries. * * @param blob The CFTypeRef returned by IOPSCopyPowerSourcesInfo() * * @param ps One of the CFTypeRefs in the CFArray returned by IOPSCopyPowerSourcesList() * * @result Returns NULL if an error was encountered, otherwise a CFDictionary. Caller should * NOT release the returned CFDictionary - it will be released as part of the CFTypeRef returned by * IOPSCopyPowerSourcesInfo(). */ CFDictionaryRef IOPSGetPowerSourceDescription(CFTypeRef blob, CFTypeRef ps); /*! @function IOPSGetProvidingPowerSourceType * * @abstract Indicates the power source the computer is currently drawing from. * * @discussion Determines which power source is providing power. * * @param snapshot The CFTypeRef returned by IOPSCopyPowerSourcesInfo() * * @result One of: CFSTR(kIOPMACPowerKey), CFSTR(kIOPMBatteryPowerKey), CFSTR(kIOPMUPSPowerKey) */ CFStringRef IOPSGetProvidingPowerSourceType(CFTypeRef snapshot); /*! @function IOPSNotificationCreateRunLoopSource * * @abstract Returns a CFRunLoopSourceRef that notifies the caller when power source * information changes. * * @discussion Returns a CFRunLoopSourceRef for scheduling with your CFRunLoop. * If your project does not use a CFRunLoop, you can alternatively * receive notifications via mach port, dispatch, or signal, via <code>notify.h</code> * using the name <code>@link kIOPSTimeRemainingNotificationKey @/link</code>. * * IOKit delivers this notification when percent remaining or time remaining changes. * Thus it fires fairly frequently while discharging or charging the battery; * please consider using: * <code>@link IOPSCreateLimitedPowerNotification @/link</code> if you only require * notifications when the power source type changes from limited to unlimited. * * @param callback A function to be called whenever any power source is added, removed, or changes. * * @param context Any user-defined pointer, passed to the IOPowerSource callback. * * @result Returns NULL if an error was encountered, otherwise a CFRunLoopSource. Caller must * release the CFRunLoopSource. */ CFRunLoopSourceRef IOPSNotificationCreateRunLoopSource(IOPowerSourceCallbackType callback, void *context); /*! @function IOPSCreateLimitedPowerNotification * * @abstract Returns a CFRunLoopSourceRef that notifies the caller when power source * changes from an unlimited power source (like attached to wall, car, or airplane power), to a limited * power source (like a battery or UPS). * * @discussion Returns a CFRunLoopSourceRef for scheduling with your CFRunLoop. * If your project does not use a CFRunLoop, you can alternatively * receive this notification via <code>notify.h</code> * using the name <code>@link kIOPSNotifyPowerSource @/link</code> * * @param callback A function to be called whenever the power source changes from AC to DC.. * * @param context Any user-defined pointer, passed to the IOPowerSource callback. * * @result Returns NULL if an error was encountered, otherwise a CFRunLoopSource. Caller must * release the CFRunLoopSource. */ CFRunLoopSourceRef IOPSCreateLimitedPowerNotification(IOPowerSourceCallbackType callback, void *context) __OSX_AVAILABLE_STARTING(__MAC_10_9, __IPHONE_7_0); /*! @function IOPSCopyExternalPowerAdapterDetails * * @abstract Returns a CFDictionary that describes the attached (AC) external * power adapter (if any external power adapter is attached. * * @discussion Use the kIOPSPowerAdapter... keys described in IOPSKeys.h * to interpret the returned CFDictionary. * * @result Returns a CFDictionary on success. Caller must release the returned * dictionary. If no adapter is attached, or if there's an error, returns NULL. */ CFDictionaryRef IOPSCopyExternalPowerAdapterDetails(void); __END_DECLS #endif /* _IOKIT_IOPOWERSOURCES_H */
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/ps/IOUPSPlugIn.h
/* * * @APPLE_LICENSE_HEADER_START@ * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this * file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_LICENSE_HEADER_END@ */ /*! @header IOUPSPlugIn.h IOUPSPlugIn.h is the header that defines the software used by ioupsd in user-space to communicate with UPS devices. <p> <b>NOTE:</b> Kernel extensions should have the following key/value pair in their personality in order to be recognized by ioupsd: <pre> <key>UPSDevice</key> <true/> </pre> </p> <p> To communicate with a UPS device, an instance of IOUPSPlugInInterface (a struct which is defined below) is created. The methods of IOUPSPlugInInterface allow ioupsd to communicate with the device. </p> <p> To obtain an IOUPSPlugInInterface for a UPS device, use the function IOCreatePlugInInterfaceForService() defined in IOKit/IOCFPlugIn.h. (Note the "i" in "PlugIn" is always upper-case.) Quick usage reference:<br> <ul> <li>'service' is a reference to the IOKit registry entry of the kernel object (usually of type IOHIDDevice) representing the device of interest. This reference can be obtained using the functions defined in IOKit/IOKitLib.h.</li> <li>'plugInType' should be CFUUIDGetUUIDBytes(kIOCFPlugInInterfaceID)</li> <li>'interfaceType' should be CFUUIDGetUUIDBytes(kIOUPSPlugInTypeID) when using IOUPSPlugIn</li> </ul> The interface returned by IOCreatePlugInInterfaceForService() should be deallocated using IODestroyPlugInInterface(). Do not call Release() on it. </p> */ #ifndef _IOKIT_PM_IOUPSPLUGIN_H #define _IOKIT_PM_IOUPSPLUGIN_H #include <CoreFoundation/CoreFoundation.h> #include <IOKit/IOCFPlugIn.h> /* 40A57A4E-26A0-11D8-9295-000A958A2C78 */ /*! @define kIOUPSPlugInTypeID @discussion Type ID for the IOUPSPlugInInterface. Corresponds to an available UPS device. */ #define kIOUPSPlugInTypeID CFUUIDGetConstantUUIDWithBytes(NULL, \ 0x40, 0xa5, 0x7a, 0x4e, 0x26, 0xa0, 0x11, 0xd8, \ 0x92, 0x95, 0x00, 0x0a, 0x95, 0x8a, 0x2c, 0x78) /* 63F8BFC4-26A0-11D8-88B4-000A958A2C78 */ /*! @define kIOUPSPlugInInterfaceID @discussion Interface ID for the IOUPSPlugInInterface. Corresponds to an available UPS device. */ #define kIOUPSPlugInInterfaceID CFUUIDGetConstantUUIDWithBytes(NULL, \ 0x63, 0xf8, 0xbf, 0xc4, 0x26, 0xa0, 0x11, 0xd8, \ 0x88, 0xb4, 0x0, 0xa, 0x95, 0x8a, 0x2c, 0x78) /* E60E0799-9AA6-49DF-B55B-A5C94BA07A4A */ /*! @define kIOUPSPlugInInterfaceID_v140 @discussion Interface ID for the IOUPSPlugInInterface. Corresponds to an available UPS device. */ #define kIOUPSPlugInInterfaceID_v140 CFUUIDGetConstantUUIDWithBytes(NULL, \ 0xe6, 0xe, 0x7, 0x99, 0x9a, 0xa6, 0x49, 0xdf, \ 0xb5, 0x5b, 0xa5, 0xc9, 0x4b, 0xa0, 0x7a, 0x4a) /*! @typedef IOUPSEventCallbackFunction @discussion Type and arguments of callout C function that is used when a completion routine is called. This function pointer is set via setEventCallback and is called when an event is available from the UPS. @param target void * pointer to your data, often a pointer to an object. @param result Completion result of desired operation. @param refcon void * pointer to more data. @param sender Interface instance sending the completion routine. @param event CFDictionaryRef containing event data. */ typedef void (*IOUPSEventCallbackFunction) (void * target, IOReturn result, void * refcon, void * sender, CFDictionaryRef event); #define IOUPSPLUGINBASE \ IOReturn (*getProperties)( void * thisPointer, \ CFDictionaryRef * properties); \ IOReturn (*getCapabilities)(void * thisPointer, \ CFSetRef * capabilities); \ IOReturn (*getEvent)( void * thisPointer, \ CFDictionaryRef * event); \ IOReturn (*setEventCallback)(void * thisPointer, \ IOUPSEventCallbackFunction callback, \ void * callbackTarget, \ void * callbackRefcon); \ IOReturn (*sendCommand)( void * thisPointer, \ CFDictionaryRef command) #define IOUPSPLUGIN_V140 \ IOReturn (*createAsyncEventSource)(void * thisPointer, \ CFTypeRef * source) typedef struct IOUPSPlugInInterface { IUNKNOWN_C_GUTS; IOUPSPLUGINBASE; } IOUPSPlugInInterface; typedef struct IOUPSPlugInInterface_v140 { IUNKNOWN_C_GUTS; IOUPSPLUGINBASE; IOUPSPLUGIN_V140; } IOUPSPlugInInterface_v140; // // BEGIN READABLE STRUCTURE DEFINITIONS // // This portion of uncompiled code provides a more reader friendly representation of // the CFPlugin methods defined above. #if 0 /*! @interface IOUPSPlugInInterface @discussion Represents and provides management functions for a UPS device. */ typedef struct IOUPSPlugInInterface { IUNKNOWN_C_GUTS; /*! @function getProperties @abstract Used to obtain the properties of the UPS device such as the name and transport. @discussion Property keys are defined in IOPSKeys.h. This is not an allocation method. Thus the caller does not release the CFDictionary that is returned. @param thisPointer The UPS Interface to use. @param properties Pointer to a CFDictionaryRef that contains the properties. @result An IOReturn error code. */ IOReturn (*getProperties)( void * thisPointer, CFDictionaryRef * properties); /*! @function getCapabilities @abstract Used to obtain the capabilities of the UPS device. @discussion Keys are defined in IOPSKeys.h and begin with kIOPS. This is not an allocation method. Thus the caller does not release the CFSet that is returned. @param thisPointer The UPS Interface to use. @param capabilities Pointer to a CFSetRef that contains the capabilities. @result An IOReturn error code. */ IOReturn (*getCapabilities)(void * thisPointer, CFSetRef * capabilities); /*! @function getEvent @abstract Used to poll the current state of the UPS. @discussion Keys are defined in IOPSKeys.h and begin with kIOPS. This is not an allocation method. Thus the caller does not release the CFDictionary that is returned. @param thisPointer The UPS Interface to use. @param event Pointer to a CFDictionaryRef that contains the current event state. @result An IOReturn error code. */ IOReturn (*getEvent)( void * thisPointer, CFDictionaryRef * event); /*! @function setEventCallback @abstract Set the callback that should be called to handle an event from the UPS. @discussion The proivided callback method should be called whenever there is a change of state in the UPS. This should be used in conjunction with createAsyncEventSource. @param thisPointer The UPS Interface to use. @param callback A callback handler of type IOUPSEventCallbackFunction. @param callbackTarget The address to be targeted by this callback. @param callbackRefcon A user specified reference value. This will be passed to all callback functions. @result An IOReturn error code. */ IOReturn (*setEventCallback)(void * thisPointer, IOUPSEventCallbackFunction callback, void * callbackTarget, void * callbackRefcon); /*! @function sendCommand @abstract Send a command to the UPS. @discussion Command keys are defined in IOPSKeys.h and begin with kIOPSCommand. An error should be returned if your device does not know how to respond to a command. @param thisPointer The UPS Interface to use. @param command CFDictionaryRef that contains the command. @result An IOReturn error code. */ IOReturn (*sendCommand)( void * thisPointer, CFDictionaryRef command); /*! @function createAsyncEventSource @abstract Used to create an async run loop event source of the plugin. @discussion This is an allocation method. Thus the caller must release the object that is returned. @param thisPointer The UPS Interface to use. @param source Pointer to a CFTypeRef. It is expected that this point to either a CFRunLoopSourceRef, a CFRunLoopTimerRef or a CFArray containing the aforementioned types. @result An IOReturn error code. */ IOReturn (*createAsyncEventSource)( void * thisPointer, CFTypeRef * source); } IOUPSPlugInInterface; #endif // END READABLE STRUCTURE DEFINITIONS #endif /* !_IOKIT_PM_IOUPSPLUGIN_H */
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/ps/IOPSKeys.h
/* * Copyright (c) 2002-2010 Apple Computer, Inc. All rights reserved. * * @APPLE_LICENSE_HEADER_START@ * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this * file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_LICENSE_HEADER_END@ */ /*! * @header IOPSKeys.h * * @discussion * IOPSKeys.h defines C strings for use accessing power source data in IOPowerSource * CFDictionaries, as returned by <code>@link //apple_ref/c/func/IOPSGetPowerSourceDescription IOPSGetPowerSourceDescription @/link</code> * Note that all of these C strings must be converted to CFStrings before use. You can wrap * them with the CFSTR() macro, or create a CFStringRef (that you must later CFRelease()) using CFStringCreateWithCString(). */ #ifndef _IOPSKEYS_H_ #define _IOPSKEYS_H_ /*! * @group IOPSPowerAdapter Keys * * @discussion * Use these kIOPSPowerAdapter keys to decipher the dictionary returned * by @link //apple_ref/c/func/IOPSCopyExternalPowerAdapterDetails IOPSCopyExternalPowerAdapterDetails @/link */ /*! * @define kIOPSPowerAdapterIDKey * * @abstract This key refers to the attached external AC power adapter's ID. * The value associated with this key is a CFNumberRef kCFNumberIntType integer. * * @discussion This key may be present in the dictionary returned from * @link //apple_ref/c/func/IOPSCopyExternalPowerAdapterDetails IOPSCopyExternalPowerAdapterDetails @/link * This key might not be defined in the adapter details dictionary. */ #define kIOPSPowerAdapterIDKey "AdapterID" /*! * @define kIOPSPowerAdapterWattsKey * * @abstract This key refers to the wattage of the external AC power adapter attached to a portable. * The value associated with this key is a CFNumberRef kCFNumberIntType integer value, in units of watts. * * @discussion This key may be present in the dictionary returned from * @link //apple_ref/c/func/IOPSCopyExternalPowerAdapterDetails IOPSCopyExternalPowerAdapterDetails @/link * This key might not be defined in the adapter details dictionary. */ #define kIOPSPowerAdapterWattsKey "Watts" /*! * @define kIOPSPowerAdapterRevisionKey * * @abstract The power adapter's revision. * The value associated with this key is a CFNumberRef kCFNumberIntType integer value * * @discussion This key may be present in the dictionary returned from * @link //apple_ref/c/func/IOPSCopyExternalPowerAdapterDetails IOPSCopyExternalPowerAdapterDetails @/link * This key might not be defined in the adapter details dictionary. */ #define kIOPSPowerAdapterRevisionKey "AdapterRevision" /*! * @define kIOPSPowerAdapterSerialNumberKey * * @abstract The power adapter's serial number. * The value associated with this key is a CFNumberRef kCFNumberIntType integer value * * @discussion This key may be present in the dictionary returned from * @link //apple_ref/c/func/IOPSCopyExternalPowerAdapterDetails IOPSCopyExternalPowerAdapterDetails @/link * This key might not be defined in the adapter details dictionary. */ #define kIOPSPowerAdapterSerialNumberKey "SerialNumber" /*! * @define kIOPSPowerAdapterFamilyKey * * @abstract The power adapter's family code. * The value associated with this key is a CFNumberRef kCFNumberIntType integer value * * @discussion This key may be present in the dictionary returned from * @link //apple_ref/c/func/IOPSCopyExternalPowerAdapterDetails IOPSCopyExternalPowerAdapterDetails @/link * This key might not be defined in the adapter details dictionary. */ #define kIOPSPowerAdapterFamilyKey "FamilyCode" /*! * @define kIOPSPowerAdapterCurrentKey * * @abstract This key refers to the current of the external AC power adapter attached to a portable. * The value associated with this key is a CFNumberRef kCFNumberIntType integer value, in units of mAmps. * * @discussion This key may be present in the dictionary returned from * @link //apple_ref/c/func/IOPSCopyExternalPowerAdapterDetails IOPSCopyExternalPowerAdapterDetails @/link * This key might not be defined in the adapter details dictionary. */ #define kIOPSPowerAdapterCurrentKey "Current" /*! * @define kIOPSPowerAdapterSourceKey * * @abstract This key refers to the source of the power. * The value associated with this key is a CFNumberRef kCFNumberIntType integer value. * * @discussion This key may be present in the dictionary returned from * @link //apple_ref/c/func/IOPSCopyExternalPowerAdapterDetails IOPSCopyExternalPowerAdapterDetails @/link * This key might not be defined in the adapter details dictionary. */ #define kIOPSPowerAdapterSourceKey "Source" /*! * @group Internal Keys * */ /*! * @define kIOPSUPSManagementClaimed * * @abstract Claims UPS management for a third-party driver. * @discussion kIOPSUPSManagementClaimed is obsolete. Do not use. * @deprecated Unsupported in OS X 10.5 and later. */ #define kIOPSUPSManagementClaimed "/IOKit/UPSPowerManagementClaimed" /*! * @define kIOPSLowWarnLevelKey * @abstract Specifies the battery capacity percentage at which device is considered to be low on power. * Typically used to show initial warning to the user. * * Holds a CFNumber, with possible values between 0-100. */ #define kIOPSLowWarnLevelKey "Low Warn Level" /*! * @define kIOPSDeadWarnLevelKey * @abstract Specifies the battery capacity percentage at which device is considered to be very low on power and * soon will not be functional. Typically used to show final warning to the user. * * Holds a CFNumber, with possible values between 0-100. * */ #define kIOPSDeadWarnLevelKey "Shutdown Level" /*! * @define kIOPSDynamicStorePath * * @abstract This is only used for internal bookkeeping, and should be ignored. */ #define kIOPSDynamicStorePath "/IOKit/PowerSources" /*! * @group Power Source Commands (UPS) * */ /*! * @define kIOPSCommandDelayedRemovePowerKey * * @abstract Command to give a UPS when it should remove power from its AC plugs in a specified amount of time * @discussion * <ul> * <li>The matching argument should be a CFNumber of kCFNumberIntType specifying when the UPS should * <li>remove power from its AC power ports. * </ul> */ #define kIOPSCommandDelayedRemovePowerKey "Delayed Remove Power" /*! * @define kIOPSCommandEnableAudibleAlarmKey * * @abstract Command to give a UPS when it should either enable or disable the audible alarm. * @discussion * <ul> * <li>The matching argument should be a CFBooleanRef where kCFBooleanTrue enables the alarm and * <li>kCFBooleanFalse diables the alarm * </ul> */ #define kIOPSCommandEnableAudibleAlarmKey "Enable Audible Alarm" /*! * @define kIOPSCommandStartupDelayKey * * @abstract Tell UPS how long it should wait for * @discussion * <ul> * <li>The matching argument should be a CFNumber of kCFNumberIntType specifying when the UPS should * <li>remove power from its AC power ports. * </ul> */ #define kIOPSCommandStartupDelayKey "Startup Delay" /*! * @define kIOPSCommandSetCurrentLimitKey * * @abstract Tell the UPS the max current it can draw from an attached power source * @discussion * <ul> * <li>The matching argument should be a CFNumber of kCFNumberIntType specifying the UPS' new current * <li>limit in mA. */ #define kIOPSCommandSetCurrentLimitKey "Set Current Limit" /*! * @define kIOPSCommandSetRequiredVoltageKey * * @abstract Tell the UPS the minimum voltage it needs to provide. * @discussion * <ul> * <li>The matching argument should be a CFNumber of kCFNumberIntType specifying the required voltage * <li>from a UPS in mV. */ #define kIOPSCommandSetRequiredVoltageKey "Set Required Voltage" /*! * @define kIOPSCommandSendCurrentStateOfCharge * * @abstract Tell the UPS the device's current state of charge * @discussion * <ul> * <li>The matching argument should be a CFNumber of kCFNumberIntType specifying the device's * <li>state of charge as a percentage. */ #define kIOPSCommandSendCurrentStateOfCharge "Send Current State of Charge" /*! * @define kIOPSCommandSendCurrentTemperature * * @abstract Tell the UPS the device's current temperature * @discussion * <ul> * <li>The matching argument should be a CFNumber of kCFNumberIntType specifying the device's * <li>temperature in degrees deciKelvin. */ #define kIOPSCommandSendCurrentTemperature "Send Current Temperature" /*! * @group Power Source data keys * */ /* These keys specify the values in a dictionary of PowerSource details. * Use these keys in conjunction with the dictionary returned by * <code>@link //apple_ref/c/func/IOPSGetPowerSourceDescription IOPSGetPowerSourceDescription @/link</code> * * Clients of <code>@link //apple_ref/c/func/IOPSCreatePowerSource IOPSCreatePowerSource @/link</code> * must specify these keys in their power source dictionaries. * Each key is labelled with one of these labels that indicate what information is REQUIRED. to * represent a power source in OS X. * * <ul> * <li> For power source creators: Providing this key is REQUIRED. * <li> For power source creators: Providing this key is RECOMMENDED. * <li> For power source creators: Providing this key is OPTIONAL. * <li> This key is DEPRECATED, do not provide it. * </ul> * */ /*! * @define kIOPSPowerSourceIDKey * * @abstract CFNumber key uniquely identifying the power source. * * @discussion * <ul> * <li> Callers should not set this key; OS X power management will publish this key for all power sources * <li> Type CFNumber, kCFNumberIntType, uniquely identifying the power source * </ul> */ #define kIOPSPowerSourceIDKey "Power Source ID" /*! * @define kIOPSPowerSourceStateKey * * @abstract CFDictionary key for the current source of power. * * @discussion * <ul> * <li> Apple-defined power sources will publish this key. * <li> For power source creators: Providing this key is REQUIRED. * <li> <code>@link kIOPSBatteryPowerValue @/link</code> indicates power source is drawing internal power; * <code>@link kIOPSACPowerValue@/link</code> indicates power source is connected to an external power source. * <li> Type CFString, value is <code>@link kIOPSACPowerValue@/link</code>, <code>@link kIOPSBatteryPowerValue@/link</code>, or <code>@link kIOPSOffLineValue@/link</code>. * </ul> */ #define kIOPSPowerSourceStateKey "Power Source State" /*! * @define kIOPSCurrentCapacityKey * @abstract CFDictionary key for the current power source's capacity. * * @discussion * <ul> * <li> Apple-defined power sources will publish this key in units of percent. * <li> The power source's software may specify the units for this key. * The units must be consistent for all capacities reported by this power source. * The power source will usually define this number in units of percent, or mAh. * <li> Clients may derive a percentage of power source battery remaining by dividing "Current Capacity" by "Max Capacity" * <li> For power source creators: Providing this key is REQUIRED. * <li> Type CFNumber kCFNumberIntType (signed integer) * </ul> */ #define kIOPSCurrentCapacityKey "Current Capacity" /*! * @define kIOPSMaxCapacityKey * @abstract CFDictionary key for the current power source's maximum or "Full Charge Capacity" * @discussion * <ul> * <li> Apple-defined power sources will publish this key in units of percent. The value is usually 100%. * <li> The power source's software may specify the units for this key. The units must be consistent for all capacities reported by this power source. * <li> For power source creators: Providing this key is REQUIRED. * <li> Type CFNumber kCFNumberIntType (signed integer) * </ul> */ #define kIOPSMaxCapacityKey "Max Capacity" /*! * @define kIOPSDesignCapacityKey * @abstract CFDictionary key for the current power source's design capacity * @discussion * <ul> * <li> Apple-defined power sources might not publish this key. * <li> The power source's software may specify the units for this key. The units must be consistent for all capacities reported by this power source. * <li> For power source creators: Providing this key is RECOMMENDED. * <li> Type CFNumber kCFNumberIntType (signed integer) * </ul> */ #define kIOPSDesignCapacityKey "DesignCapacity" /*! * @define kIOPSNominalCapacityKey * @abstract CFDictionary key for the current power source's normalized full, or "nominal", charge capacity * @discussion * <ul> * <li> Apple-defined power sources might not publish this key. * <li> The power source's software may specify the units for this key. The units must be consistent for all capacities reported by this power source. * <li> For power source creators: Providing this key is RECOMMENDED. * <li> Type CFNumber kCFNumberIntType (signed integer) * </ul> */ #define kIOPSNominalCapacityKey "Nominal Capacity" /*! * @define kIOPSTimeToEmptyKey * @abstract CFDictionary key for the current power source's time remaining until empty. * @discussion * Only valid if the power source is running off its own power. That's when the * <code>@link kIOPSPowerSourceStateKey @/link</code> has value <code>@link kIOPSBatteryPowerValue @/link</code> * and the value of <code>@link kIOPSIsChargingKey @/link</code> is kCFBooleanFalse. * <ul> * <li> Apple-defined power sources will publish this key. * <li> For power source creators: Providing this key is RECOMMENDED. * <li> Type CFNumber kCFNumberIntType (signed integer), units are minutes * <li> A value of -1 indicates "Still Calculating the Time", otherwise estimated minutes left on the battery. * </ul> */ #define kIOPSTimeToEmptyKey "Time to Empty" /*! * @define kIOPSTimeToFullChargeKey * @abstract CFDictionary key for the current power source's time remaining until empty. * @discussion * Only valid if the value of <code>@link kIOPSIsChargingKey @/link</code> is kCFBooleanTrue. * <ul> * <li> Apple-defined power sources will publish this key. * <li> For power source creators: Providing this key is RECOMMENDED. * <li> Type CFNumber kCFNumberIntType (signed integer), units are minutes * <li>A value of -1 indicates "Still Calculating the Time", otherwise estimated minutes until fully charged. * </ul> */ #define kIOPSTimeToFullChargeKey "Time to Full Charge" /*! * @define kIOPSIsChargingKey * @abstract CFDictionary key for the current power source's charging state * @discussion * <ul> * <li> Apple-defined power sources will publish this key. * <li> For power source creators: Providing this key is REQUIRED. * <li> Type CFBoolean - kCFBooleanTrue or kCFBooleanFalse * </ul> */ #define kIOPSIsChargingKey "Is Charging" /*! * @define kIOPSInternalFailureKey * @abstract CFDictionary key for whether the current power source has experienced a failure * @discussion * <ul> * <li> Apple-defined power sources might not publish this key. * <li> For power source creators: Providing this key is RECOMMENDED. * <li> Type CFBoolean - kCFBooleanTrue or kCFBooleanFalse * </ul> */ #define kIOPSInternalFailureKey "Internal Failure" /*! * @define kIOPSIsPresentKey * @abstract CFDictionary key for the current power source's presence. * @discussion * <ul> * <li> Apple-defined power sources will publish this key. * <li> For instance, a portable with the capacity for two batteries but * with only one present would show two power source dictionaries, * but kIOPSIsPresentKey would have the value kCFBooleanFalse in one of them. * <li> For power source creators: Providing this key is REQUIRED. * <li> Type CFBoolean - kCFBooleanTrue or kCFBooleanFalse * </ul> */ #define kIOPSIsPresentKey "Is Present" /*! * @define kIOPSVoltageKey * @abstract CFDictionary key for the current power source's electrical voltage. * @discussion * <ul> * <li> Apple-defined power sources will publish this key. * <li> For power source creators: Providing this key is RECOMMENDED. * <li> Type CFNumber kCFNumberIntType (signed integer) - units are mV * </ul> */ #define kIOPSVoltageKey "Voltage" /*! * @define kIOPSCurrentKey * @abstract CFDictionary key for the current power source's electrical current. * @discussion * <ul> * <li> Apple-defined power sources will publish this key. * <li> For power source creators: Providing this key is RECOMMENDED. * <li> Type CFNumber kCFNumberIntType (signed integer) - units are mA * </ul> */ #define kIOPSCurrentKey "Current" /*! * @define kIOPSTemperatureKey * @abstract CFDictionary key for the current power source's temperature. * @discussion * <ul> * <li> Apple-defined power sources will publish this key. * <li> For power source creators: Providing this key is RECOMMENDED. * <li> Type CFNumber kCFNumberIntType (signed integer) - units are C * </ul> */ #define kIOPSTemperatureKey "Temperature" /*! * @define kIOPSNameKey * @abstract CFDictionary key for the current power source's name. * @discussion * <ul> * <li> Apple-defined power sources will publish this key. * <li> For power source creators: Providing this key is REQUIRED. * <li> Type CFStringRef * </ul> */ #define kIOPSNameKey "Name" /*! * @define kIOPSTypeKey * @abstract CFDictionary key for the type of the power source * @discussion * <ul> * <li> Apple-defined power sources will publish this key. * <li> For power source creators: Providing this key is REQUIRED. * <li> Type CFStringRef. Valid transport types are kIOPSUPSType or kIOPSInternalBatteryType. * </ul> */ #define kIOPSTypeKey "Type" /*! * @define kIOPSTransportTypeKey * @abstract CFDictionary key for the current power source's data transport type (e.g. the means that the power source conveys power source data to the OS X machine). * @discussion * <ul> * <li> Apple-defined power sources will publish this key. * <li> A value of <code>@link kIOPSInternalType @/link</code> describes an internal power source. * <li> <code>@link kIOPSUSBTransportType @/link</code>, <code>@link kIOPSNetworkTransportType @/link</code>, and <code>@link kIOPSSerialTransportType @/link</code> usually describe UPS's. * <li> For power source creators: Providing this key is REQUIRED. * <li> Type CFStringRef. Valid transport types are kIOPSSerialTransportType, * kIOPSUSBTransportType, kIOPSNetworkTransportType, kIOPSInternalType * </ul> */ #define kIOPSTransportTypeKey "Transport Type" /*! * @define kIOPSVendorIDKey * @abstract CFDictionary key for the current power source's vendor ID. * @discussion * <ul> * <li> Apple-defined power sources will publish this key. * <li> For power source creators: Providing this key is RECOMMENDED. * <li> Type CFNumberRef * </ul> */ #define kIOPSVendorIDKey "Vendor ID" /*! * @define kIOPSProductIDKey * @abstract CFDictionary key for the current power source's product ID. * @discussion * <ul> * <li> Apple-defined power sources will publish this key. * <li> For power source creators: Providing this key is RECOMMENDED. * <li> Type CFNumberRef * </ul> */ #define kIOPSProductIDKey "Product ID" /*! * @define kIOPSVendorDataKey * @abstract CFDictionary key for arbitrary vendor data. * @discussion * <ul> * <li> Apple-defined power sources are not required to publish this key. * <li> For power source creators: Providing this key is OPTIONAL. * <li>CFDictionary; contents determined by the power source software. OS X will not look at this data. * </ul> */ #define kIOPSVendorDataKey "Vendor Specific Data" /*! * @define kIOPSBatteryHealthKey * @abstract CFDictionary key for the current power source's "health" estimate. * @discussion * <ul> * <li> Apple-defined battery power sources will publish this key. * <li> Use value <code>@link kIOPSGoodValue @/link</code> to describe a well-performing power source, * <li> Use <code>@link kIOPSFairValue @/link</code> to describe a functional power source with limited capacity * <li> And use <code>@link kIOPSPoorValue @/link</code> to describe a power source that's not capable of Providing power. * <li> For power source creators: Providing this key is OPTIONAL. * <li> Type CFStringRef * </ul> */ #define kIOPSBatteryHealthKey "BatteryHealth" /*! * @define kIOPSBatteryHealthConditionKey * @abstract kIOPSBatteryHealthConditionKey broadly describes the battery's health. * @discussion * <ul> * <li> Apple-defined power sources will publish this key. * <li> Value is one of the "Battery Health Condition Values" strings described in this file. * <li> For power source creators: Providing this key is OPTIONAL - these keys have values only used by Apple power sources. * <li> Type CFStringRef * </ul> */ #define kIOPSBatteryHealthConditionKey "BatteryHealthCondition" /*! * @define kIOPSBatteryFailureModesKey * @abstract Enumerates a battery's failures and error conditions. * @discussion * Various battery failures will be listed here. A battery may suffer from more than one * type of failure simultaneously, so this key has a CFArray value. * * If BatteryFailureModesKey is not defined (or is set to an empty dictionary), * then the battery has no detectable failures. * * Each entry in the array should be a short descriptive string describing the error. * <li> Apple-defined power sources will publish this key if any battery errors exist. * <li> For power source creators: Providing this key is RECOMMENDED. * <li> Type CFArrayRef * </ul> */ #define kIOPSBatteryFailureModesKey "BatteryFailureModes" /*! * @define kIOPSHealthConfidenceKey * @abstract CFDictionary key for our confidence in the accuracy of our * power source's "health" estimate. * @deprecated In OS X 10.6 and later. * @discussion * <ul> * <li> Apple-defined power sources will no longer publish this key. * <li> Power source creators should not publish this key. * <li> For power source creators: This key is DEPRECATED, do not implement it. * <li> Type CFStringRef * </ul> */ #define kIOPSHealthConfidenceKey "HealthConfidence" /*! * @define kIOPSMaxErrKey * @abstract CFDictionary key for the current power source's percentage error in capacity reporting. * @discussion * In internal batteries, this refers to the battery pack's estimated percentage error. * <ul> * <li> Apple-defined battery power sources will publish this key, but only if it's defined for the battery. * <li> For power source creators: Providing this key is OPTIONAL. * <li> Type CFNumberRef kCFNumberIntType, non-negative integer * </ul> */ #define kIOPSMaxErrKey "MaxErr" /*! * @define kIOPSIsChargedKey * @abstract CFDictionary key indicates whether the battery is charged. * @discussion * A battery must be plugged in to an external power source in order to be fully charged. * Note that a battery may validly be plugged in, not charging, and <100% charge. * e.g. A battery with capacity >= 95% and not charging, is defined as charged. * <ul> * <li> Apple-defined power sources will publish this key. * <li> For power source creators: Providing this key is REQUIRED. * <li> Type CFBoolean - kCFBooleanTrue or kCFBooleanFalse * </ul> */ #define kIOPSIsChargedKey "Is Charged" /*! * @define kIOPSIsFinishingChargeKey * @abstract CFDictionary key indicates whether the battery is finishing off its charge. * @discussion * When this is true, the system UI should indicate that the battery is "Finishing Charge." * Some batteries may continue charging after they report 100% capacity. * <ul> * <li> Apple-defined battery power sources will publish this key. * <li> For power source creators: Providing this key is RECOMMENDED. * <li> Type CFBoolean - kCFBooleanTrue or kCFBooleanFalse * </ul> */ #define kIOPSIsFinishingChargeKey "Is Finishing Charge" /*! * @define kIOPSHardwareSerialNumberKey * @abstract A unique serial number that identifies the power source. * @discussion For Apple-manufactured batteries, this is an alphanumeric string generated * during the battery manufacturing process. * <ul> * <li> Apple-defined power sources will publish this key if the hardware provides the serial number. * <li> For power source creators: Providing this key is RECOMMENDED. * <li> Type CFStringRef * </ul> */ #define kIOPSHardwareSerialNumberKey "Hardware Serial Number" /* * @group Transport types * @abstract Possible values for <code>@link kIOPSTransportTypeKey @/link</code> */ /*! * @define kIOPSSerialTransportType * @abstract Value for key <code>@link kIOPSTransportTypeKey @/link</code>. * @discussion Indicates the power source is a UPS attached over a serial connection. */ #define kIOPSSerialTransportType "Serial" /*! * @define kIOPSUSBTransportType * @abstract Value for key <code>@link kIOPSTransportTypeKey @/link</code>. * @discussion Indicates the power source is a UPS attached over a USB connection. */ #define kIOPSUSBTransportType "USB" /*! * @define kIOPSNetworkTransportType * @abstract Value for key <code>@link kIOPSTransportTypeKey @/link</code>. * @discussion Indicates the power source is a UPS attached over a network connection (and it may be managing several computers). */ #define kIOPSNetworkTransportType "Ethernet" /*! * @define kIOPSInternalType * @abstract Value for key <code>@link kIOPSTransportTypeKey @/link</code>. Indicates the power source is an internal battery. */ #define kIOPSInternalType "Internal" /* * @group PowerSource Types * @discussion * A string that broadly describes the type of power source. One of these strings must be passed * as an argument to IOPSCreatePowerSource() when defining a new system power source. */ /*! * @define kIOPSInternalBatteryType * * @abstract Represents a battery residing inside a Mac. */ #define kIOPSInternalBatteryType "InternalBattery" /*! * @define kIOPSUPSType * * @abstract Represents an external attached UPS. */ #define kIOPSUPSType "UPS" /* * PS state */ /*! * @define kIOPSOffLineValue * @abstract Value for key kIOPSPowerSourceStateKey. Power source is off-line or no longer connected. */ #define kIOPSOffLineValue "Off Line" /*! * @define kIOPSACPowerValue * @abstract Value for key kIOPSPowerSourceStateKey. Power source is connected to external or AC power, and is not draining the internal battery. */ #define kIOPSACPowerValue "AC Power" /*! * @define kIOPSBatteryPowerValue * @abstract Value for key kIOPSPowerSourceStateKey. Power source is currently using the internal battery. */ #define kIOPSBatteryPowerValue "Battery Power" /*! * @group Battery Health values */ /*! * @define kIOPSPoorValue * @abstract Value for key <code>@link kIOPSBatteryHealthKey @/link</code>. */ #define kIOPSPoorValue "Poor" /*! * @define kIOPSFairValue * @abstract Value for key <code>@link kIOPSBatteryHealthKey @/link</code>. */ #define kIOPSFairValue "Fair" /*! * @define kIOPSGoodValue * @abstract Value for key <code>@link kIOPSBatteryHealthKey @/link</code>. */ #define kIOPSGoodValue "Good" /* * @group Battery Health Condition values */ /*! * @define kIOPSCheckBatteryValue * * @abstract Value for key <code>@link kIOPSBatteryHealthConditionKey @/link</code> * * @discussion This value indicates that the battery should be checked out by a licensed Mac repair service. */ #define kIOPSCheckBatteryValue "Check Battery" /*! * @define kIOPSPermanentFailureValue * * @abstract Value for key <code>@link kIOPSBatteryHealthConditionKey @/link</code> * * @discussion Indicates the battery needs replacement. */ #define kIOPSPermanentFailureValue "Permanent Battery Failure" /*! * @group Battery Failure Mode values */ /*! * @define kIOPSFailureExternalInput * * @abstract Value for key <code>@link kIOPSBatteryFailureModesKey@/link</code> */ #define kIOPSFailureExternalInput "Externally Indicated Failure" /*! * @define kIOPSFailureSafetyOverVoltage * * @abstract Potential value for key <code>@link kIOPSBatteryFailureModesKey@/link</code> */ #define kIOPSFailureSafetyOverVoltage "Safety Over-Voltage" /*! * @define kIOPSFailureChargeOverTemp * * @abstract Potential value for key <code>@link kIOPSBatteryFailureModesKey@/link</code> */ #define kIOPSFailureChargeOverTemp "Charge Over-Temperature" /*! * @define kIOPSFailureDischargeOverTemp * * @abstract Potential value for key <code>@link kIOPSBatteryFailureModesKey@/link</code> */ #define kIOPSFailureDischargeOverTemp "Discharge Over-Temperature" /*! * @define kIOPSFailureCellImbalance * * @abstract Potential value for key <code>@link kIOPSBatteryFailureModesKey@/link</code> */ #define kIOPSFailureCellImbalance "Cell Imbalance" /*! * @define kIOPSFailureChargeFET * * @abstract Potential value for key <code>@link kIOPSBatteryFailureModesKey@/link</code> */ #define kIOPSFailureChargeFET "Charge FET" /*! * @define kIOPSFailureDischargeFET * * @abstract Potential value for key <code>@link kIOPSBatteryFailureModesKey@/link</code> */ #define kIOPSFailureDischargeFET "Discharge FET" /*! * @define kIOPSFailureDataFlushFault * * @abstract Potential value for key <code>@link kIOPSBatteryFailureModesKey@/link</code> */ #define kIOPSFailureDataFlushFault "Data Flush Fault" /*! * @define kIOPSFailurePermanentAFEComms * * @abstract Potential value for key <code>@link kIOPSBatteryFailureModesKey@/link</code> */ #define kIOPSFailurePermanentAFEComms "Permanent AFE Comms" /*! * @define kIOPSFailurePeriodicAFEComms * * @abstract Potential value for key <code>@link kIOPSBatteryFailureModesKey@/link</code> */ #define kIOPSFailurePeriodicAFEComms "Periodic AFE Comms" /*! * @define kIOPSFailureChargeOverCurrent * * @abstract Potential value for key <code>@link kIOPSBatteryFailureModesKey@/link</code> */ #define kIOPSFailureChargeOverCurrent "Charge Over-Current" /*! * @define kIOPSFailureDischargeOverCurrent * * @abstract Potential value for key <code>@link kIOPSBatteryFailureModesKey@/link</code> */ #define kIOPSFailureDischargeOverCurrent "Discharge Over-Current" /*! * @define kIOPSFailureOpenThermistor * * @abstract Potential value for key <code>@link kIOPSBatteryFailureModesKey@/link</code> */ #define kIOPSFailureOpenThermistor "Open Thermistor" /*! * @define kIOPSFailureFuseBlown * * @abstract Potential value for key <code>@link kIOPSBatteryFailureModesKey@/link</code> */ #define kIOPSFailureFuseBlown "Fuse Blown" #endif
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/scsi/SCSICmds_INQUIRY_Definitions.h
/* * Copyright (c) 1998-2018 Apple Inc. All rights reserved. * * @APPLE_LICENSE_HEADER_START@ * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this * file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_LICENSE_HEADER_END@ */ #ifndef _IOKIT_SCSI_CMDS_INQUIRY_H_ #define _IOKIT_SCSI_CMDS_INQUIRY_H_ //----------------------------------------------------------------------------- // Includes //----------------------------------------------------------------------------- #if KERNEL #include <IOKit/IOTypes.h> #else #include <CoreFoundation/CoreFoundation.h> #endif /*! @header SCSI Inquiry Definitions @discussion This file contains all definitions for the data returned from the INQUIRY (0x12) command. */ /*! * @enum Payload sizes * @discussion * Definitions for sizes related to the INQUIRY data. * @constant kINQUIRY_StandardDataHeaderSize * INQUIRY data header size. * @constant kINQUIRY_MaximumDataSize * Maximum size for INQUIRY data. */ enum { kINQUIRY_StandardDataHeaderSize = 5, kINQUIRY_MaximumDataSize = 255 }; /*! @enum INQUIRY field sizes @discussion Sizes for some of the inquiry data fields. @constant kINQUIRY_VENDOR_IDENTIFICATION_Length Size of VENDOR_IDENTIFICATION field. @constant kINQUIRY_PRODUCT_IDENTIFICATION_Length Size of PRODUCT_IDENTIFICATION field. @constant kINQUIRY_PRODUCT_REVISION_LEVEL_Length Size of PRODUCT_REVISION_LEVEL field. */ enum { kINQUIRY_VENDOR_IDENTIFICATION_Length = 8, kINQUIRY_PRODUCT_IDENTIFICATION_Length = 16, kINQUIRY_PRODUCT_REVISION_LEVEL_Length = 4 }; /*! @struct SCSICmd_INQUIRY_StandardData @discussion This structure defines the format of the required standard data that is returned for the INQUIRY command. This is the data that is required to be returned from all devices. */ typedef struct SCSICmd_INQUIRY_StandardData { UInt8 PERIPHERAL_DEVICE_TYPE; // 7-5 = Qualifier. 4-0 = Device type. UInt8 RMB; // 7 = removable UInt8 VERSION; // 7/6 = ISO/IEC, 5-3 = ECMA, 2-0 = ANSI. UInt8 RESPONSE_DATA_FORMAT; // 7 = AERC, 6 = Obsolete, 5 = NormACA, 4 = HiSup 3-0 = Response data format. (SPC-3 obsoletes AERC) // If ANSI Version = 0, this is ATAPI and bits 7-4 = ATAPI version. UInt8 ADDITIONAL_LENGTH; // Number of additional bytes available in inquiry data UInt8 SCCSReserved; // SCC-2 device flag and reserved fields (SPC-3 adds PROTECT 3PC TPGS, and ACC) UInt8 flags1; // First byte of support flags (See SPC-3 section 6.4.2) UInt8 flags2; // Second byte of support flags (Byte 7) (See SPC-3 section 6.4.2) char VENDOR_IDENTIFICATION[kINQUIRY_VENDOR_IDENTIFICATION_Length]; char PRODUCT_IDENTIFICATION[kINQUIRY_PRODUCT_IDENTIFICATION_Length]; char PRODUCT_REVISION_LEVEL[kINQUIRY_PRODUCT_REVISION_LEVEL_Length]; } SCSICmd_INQUIRY_StandardData; typedef SCSICmd_INQUIRY_StandardData * SCSICmd_INQUIRY_StandardDataPtr; /*! @struct SCSICmd_INQUIRY_StandardDataAll @discussion This structure defines the all of the fields that can be returned in repsonse to the INQUIRy request for the standard data. There is no requirement as to how much of the additional data must be returned by a device. */ typedef struct SCSICmd_INQUIRY_StandardDataAll { UInt8 PERIPHERAL_DEVICE_TYPE; // 7-5 = Qualifier. 4-0 = Device type. UInt8 RMB; // 7 = removable UInt8 VERSION; // 7/6 = ISO/IEC, 5-3 = ECMA, 2-0 = ANSI. UInt8 RESPONSE_DATA_FORMAT; // 7 = AERC, 6 = Obsolete, 5 = NormACA, 4 = HiSup 3-0 = Response data format. // If ANSI Version = 0, this is ATAPI and bits 7-4 = ATAPI version. UInt8 ADDITIONAL_LENGTH; // Number of additional bytes available in inquiry data UInt8 SCCSReserved; // SCC-2 device flag and reserved fields UInt8 flags1; // First byte of support flags (Byte 6) UInt8 flags2; // Second byte of support flags (Byte 7) char VENDOR_IDENTIFICATION[kINQUIRY_VENDOR_IDENTIFICATION_Length]; char PRODUCT_IDENTIFICATION[kINQUIRY_PRODUCT_IDENTIFICATION_Length]; char PRODUCT_REVISION_LEVEL[kINQUIRY_PRODUCT_REVISION_LEVEL_Length]; // Following is the optional data that may be returned by a device. UInt8 VendorSpecific1[20]; UInt8 flags3; // Third byte of support flags, mainly SPI-3 (Byte 56) UInt8 Reserved1; UInt16 VERSION_DESCRIPTOR[8]; UInt8 Reserved2[22]; UInt8 VendorSpecific2[160]; } SCSICmd_INQUIRY_StandardDataAll; /*! @enum Peripheral Qualifier @discussion Inquiry Peripheral Qualifier definitions @constant kINQUIRY_PERIPHERAL_QUALIFIER_Connected Peripheral Device is connected. @constant kINQUIRY_PERIPHERAL_QUALIFIER_SupportedButNotConnected Peripheral Device is supported, but not connected. @constant kINQUIRY_PERIPHERAL_QUALIFIER_NotSupported Peripheral Device is not supported. @constant kINQUIRY_PERIPHERAL_QUALIFIER_Mask Mask to use for PERIPHERAL_DEVICE_TYPE field. */ enum { kINQUIRY_PERIPHERAL_QUALIFIER_Connected = 0x00, kINQUIRY_PERIPHERAL_QUALIFIER_SupportedButNotConnected = 0x20, kINQUIRY_PERIPHERAL_QUALIFIER_NotSupported = 0x60, kINQUIRY_PERIPHERAL_QUALIFIER_Mask = 0xE0 }; /*! @enum Peripheral Device types @discussion Inquiry Peripheral Device type definitions @constant kINQUIRY_PERIPHERAL_TYPE_DirectAccessSBCDevice SBC Device. @constant kINQUIRY_PERIPHERAL_TYPE_SequentialAccessSSCDevice Sequential Access (Tape) SSC Device. @constant kINQUIRY_PERIPHERAL_TYPE_PrinterSSCDevice SSC Device. @constant kINQUIRY_PERIPHERAL_TYPE_ProcessorSPCDevice SPC Device. @constant kINQUIRY_PERIPHERAL_TYPE_WriteOnceSBCDevice SBC Device. @constant kINQUIRY_PERIPHERAL_TYPE_CDROM_MMCDevice MMC Device. @constant kINQUIRY_PERIPHERAL_TYPE_ScannerSCSI2Device SCSI2 Device. @constant kINQUIRY_PERIPHERAL_TYPE_OpticalMemorySBCDevice SBC Device. @constant kINQUIRY_PERIPHERAL_TYPE_MediumChangerSMCDevice SMC Device. @constant kINQUIRY_PERIPHERAL_TYPE_CommunicationsSSCDevice Comms SSC Device. @constant kINQUIRY_PERIPHERAL_TYPE_StorageArrayControllerSCC2Device SCC2 Device. @constant kINQUIRY_PERIPHERAL_TYPE_EnclosureServicesSESDevice SES Device. @constant kINQUIRY_PERIPHERAL_TYPE_SimplifiedDirectAccessRBCDevice RBC Device. @constant kINQUIRY_PERIPHERAL_TYPE_OpticalCardReaderOCRWDevice OCRW Device. @constant kINQUIRY_PERIPHERAL_TYPE_ObjectBasedStorageDevice OSD device. @constant kINQUIRY_PERIPHERAL_TYPE_AutomationDriveInterface Automation Drive Interface device. @constant kINQUIRY_PERIPHERAL_TYPE_WellKnownLogicalUnit Well known logical unit. @constant kINQUIRY_PERIPHERAL_TYPE_UnknownOrNoDeviceType Unknown or no device. @constant kINQUIRY_PERIPHERAL_TYPE_Mask Mask to use for PERIPHERAL_DEVICE_TYPE field. */ enum { kINQUIRY_PERIPHERAL_TYPE_DirectAccessSBCDevice = 0x00, kINQUIRY_PERIPHERAL_TYPE_SequentialAccessSSCDevice = 0x01, kINQUIRY_PERIPHERAL_TYPE_PrinterSSCDevice = 0x02, kINQUIRY_PERIPHERAL_TYPE_ProcessorSPCDevice = 0x03, kINQUIRY_PERIPHERAL_TYPE_WriteOnceSBCDevice = 0x04, kINQUIRY_PERIPHERAL_TYPE_CDROM_MMCDevice = 0x05, kINQUIRY_PERIPHERAL_TYPE_ScannerSCSI2Device = 0x06, kINQUIRY_PERIPHERAL_TYPE_OpticalMemorySBCDevice = 0x07, kINQUIRY_PERIPHERAL_TYPE_MediumChangerSMCDevice = 0x08, kINQUIRY_PERIPHERAL_TYPE_CommunicationsSSCDevice = 0x09, /* 0x0A - 0x0B ASC IT8 Graphic Arts Prepress Devices */ kINQUIRY_PERIPHERAL_TYPE_StorageArrayControllerSCC2Device = 0x0C, kINQUIRY_PERIPHERAL_TYPE_EnclosureServicesSESDevice = 0x0D, kINQUIRY_PERIPHERAL_TYPE_SimplifiedDirectAccessRBCDevice = 0x0E, kINQUIRY_PERIPHERAL_TYPE_OpticalCardReaderOCRWDevice = 0x0F, /* 0x10 - 0x1E Reserved Device Types */ kINQUIRY_PERIPHERAL_TYPE_ObjectBasedStorageDevice = 0x11, kINQUIRY_PERIPHERAL_TYPE_AutomationDriveInterface = 0x12, kINQUIRY_PERIPHERAL_TYPE_WellKnownLogicalUnit = 0x1E, kINQUIRY_PERIPHERAL_TYPE_UnknownOrNoDeviceType = 0x1F, kINQUIRY_PERIPHERAL_TYPE_Mask = 0x1F }; /*! @enum Removable Bit field definitions @discussion Inquiry Removable Bit field definitions @constant kINQUIRY_PERIPHERAL_RMB_MediumFixed Medium type is fixed disk. @constant kINQUIRY_PERIPHERAL_RMB_MediumRemovable Medium type is removable disk. @constant kINQUIRY_PERIPHERAL_RMB_BitMask Mask to use for RMB field. */ enum { kINQUIRY_PERIPHERAL_RMB_MediumFixed = 0x00, kINQUIRY_PERIPHERAL_RMB_MediumRemovable = 0x80, kINQUIRY_PERIPHERAL_RMB_BitMask = 0x80 }; /*! @enum Version field definitions @discussion Definitions for bits/masks in the INQUIRY Version field. @constant kINQUIRY_ISO_IEC_VERSION_Mask Mask for valid bits for ISO/IEC Version. @constant kINQUIRY_ECMA_VERSION_Mask Mask for valid bits for ECMA Version. @constant kINQUIRY_ANSI_VERSION_NoClaimedConformance No ANSI conformance claimed by the device server. @constant kINQUIRY_ANSI_VERSION_SCSI_1_Compliant SCSI-1 conformance claimed by the device server. @constant kINQUIRY_ANSI_VERSION_SCSI_2_Compliant SCSI-2 conformance claimed by the device server. @constant kINQUIRY_ANSI_VERSION_SCSI_SPC_Compliant SPC conformance claimed by the device server. @constant kINQUIRY_ANSI_VERSION_SCSI_SPC_2_Compliant SPC-2 conformance claimed by the device server. @constant kINQUIRY_ANSI_VERSION_SCSI_SPC_3_Compliant SPC-3 conformance claimed by the device server. @constant kINQUIRY_ANSI_VERSION_Mask Mask for valid bits for ANSI Version. */ enum { kINQUIRY_ISO_IEC_VERSION_Mask = 0xC0, kINQUIRY_ECMA_VERSION_Mask = 0x38, kINQUIRY_ANSI_VERSION_NoClaimedConformance = 0x00, kINQUIRY_ANSI_VERSION_SCSI_1_Compliant = 0x01, kINQUIRY_ANSI_VERSION_SCSI_2_Compliant = 0x02, kINQUIRY_ANSI_VERSION_SCSI_SPC_Compliant = 0x03, kINQUIRY_ANSI_VERSION_SCSI_SPC_2_Compliant = 0x04, kINQUIRY_ANSI_VERSION_SCSI_SPC_3_Compliant = 0x05, kINQUIRY_ANSI_VERSION_Mask = 0x07 }; /*! @enum Response Data Format field definitions @discussion Definitions for bits/masks in the INQUIRY RESPONSE_DATA_FORMAT field. @constant kINQUIRY_Byte3_HISUP_Bit HISUP bit definition. @constant kINQUIRY_Byte3_NORMACA_Bit NORMACA bit definition. @constant kINQUIRY_Byte3_AERC_Bit AERC bit definition. @constant kINQUIRY_RESPONSE_DATA_FORMAT_Mask Mask for valid bits for RESPONSE_DATA_FORMAT. @constant kINQUIRY_Byte3_HISUP_Mask Mask to use to test the HISUP bit. @constant kINQUIRY_Byte3_NORMACA_Mask Mask to use to test the NORMACA bit. @constant kINQUIRY_Byte3_AERC_Mask Mask to use to test the AERC bit. */ enum { // Bit definitions // Bits 0-3: RESPONSE DATA FORMAT kINQUIRY_Byte3_HISUP_Bit = 4, kINQUIRY_Byte3_NORMACA_Bit = 5, // Bit 6 is Obsolete kINQUIRY_Byte3_AERC_Bit = 7, // Masks kINQUIRY_RESPONSE_DATA_FORMAT_Mask = 0x0F, // Bits 0-3 kINQUIRY_Byte3_HISUP_Mask = (1 << kINQUIRY_Byte3_HISUP_Bit), kINQUIRY_Byte3_NORMACA_Mask = (1 << kINQUIRY_Byte3_NORMACA_Bit), // Bit 6 is Obsolete kINQUIRY_Byte3_AERC_Mask = (1 << kINQUIRY_Byte3_AERC_Bit) }; /*! @enum SCCS field definitions @discussion Definitions for bits/masks in the INQUIRY SCCSReserved field. @constant kINQUIRY_Byte5_SCCS_Bit SCCS bit definition. @constant kINQUIRY_Byte5_ACC_Bit ACC bit definition. @constant kINQUIRY_Byte5_ExplicitTPGS_Bit Explicit TPGS bit definition. @constant kINQUIRY_Byte5_ImplicitTPGS_Bit Implicit TPGS bit definition. @constant kINQUIRY_Byte5_3PC_Bit 3PC bit definition. @constant kINQUIRY_Byte5_PROTECT_Bit PROTECT bit definition. @constant kINQUIRY_Byte5_SCCS_Mask Mask to use to test the SCCS bit. @constant kINQUIRY_Byte5_ACC_Mask Mask to use to test the ACC bit. @constant kINQUIRY_Byte5_ExplicitTPGS_Mask Mask to use for the Explicit TPGS bits. @constant kINQUIRY_Byte5_ImplicitTPGS_Mask Mask to use for the Implicit TPGS bits. @constant kINQUIRY_Byte5_3PC_Mask Mask to use to test the 3PC bit. @constant kINQUIRY_Byte5_PROTECT_Mask Mask to use to test the PROTECT bit. */ enum { // Bit definitions kINQUIRY_Byte5_SCCS_Bit = 7, kINQUIRY_Byte5_ACC_Bit = 6, kINQUIRY_Byte5_ExplicitTPGS_Bit = 5, kINQUIRY_Byte5_ImplicitTPGS_Bit = 4, kINQUIRY_Byte5_3PC_Bit = 3, // Bits 1-2: Reserved kINQUIRY_Byte5_PROTECT_Bit = 0, // Masks kINQUIRY_Byte5_SCCS_Mask = (1 << kINQUIRY_Byte5_SCCS_Bit), kINQUIRY_Byte5_ACC_Mask = (1 << kINQUIRY_Byte5_ACC_Bit), kINQUIRY_Byte5_ExplicitTPGS_Mask = (1 << kINQUIRY_Byte5_ExplicitTPGS_Bit), kINQUIRY_Byte5_ImplicitTPGS_Mask = (1 << kINQUIRY_Byte5_ImplicitTPGS_Bit), kINQUIRY_Byte5_3PC_Mask = (1 << kINQUIRY_Byte5_3PC_Bit), // Bits 1-2: Reserved kINQUIRY_Byte5_PROTECT_Mask = (1 << kINQUIRY_Byte5_PROTECT_Bit) }; /*! @enum flags1 field definitions @discussion Definitions for bits/masks in the INQUIRY flags1 field. @constant kINQUIRY_Byte6_ADDR16_Bit ADDR16 bit definition. @constant kINQUIRY_Byte6_MCHNGR_Bit MCHNGR bit definition. @constant kINQUIRY_Byte6_MULTIP_Bit MULTIP bit definition. @constant kINQUIRY_Byte6_VS_Bit VS bit definition. @constant kINQUIRY_Byte6_ENCSERV_Bit ENCSERV bit definition. @constant kINQUIRY_Byte6_BQUE_Bit BQUE bit definition. @constant kINQUIRY_Byte6_ADDR16_Mask Mask to use to test the ADDR16 bit. @constant kINQUIRY_Byte6_MCHNGR_Mask Mask to use to test the MCHNGR bit. @constant kINQUIRY_Byte6_MULTIP_Mask Mask to use to test the MULTIP bit. @constant kINQUIRY_Byte6_VS_Mask Mask to use to test the VS bit. @constant kINQUIRY_Byte6_ENCSERV_Mask Mask to use to test the ENCSERV bit. @constant kINQUIRY_Byte6_BQUE_Mask Mask to use to test the BQUE bit. */ enum { // Byte offset kINQUIRY_Byte6_Offset = 6, // Bit definitions kINQUIRY_Byte6_ADDR16_Bit = 0, // SPI Specific // Bit 1 is Obsolete // Bit 2 is Obsolete kINQUIRY_Byte6_MCHNGR_Bit = 3, kINQUIRY_Byte6_MULTIP_Bit = 4, kINQUIRY_Byte6_VS_Bit = 5, kINQUIRY_Byte6_ENCSERV_Bit = 6, kINQUIRY_Byte6_BQUE_Bit = 7, // Masks kINQUIRY_Byte6_ADDR16_Mask = (1 << kINQUIRY_Byte6_ADDR16_Bit), // SPI Specific // Bit 1 is Obsolete // Bit 2 is Obsolete kINQUIRY_Byte6_MCHNGR_Mask = (1 << kINQUIRY_Byte6_MCHNGR_Bit), kINQUIRY_Byte6_MULTIP_Mask = (1 << kINQUIRY_Byte6_MULTIP_Bit), kINQUIRY_Byte6_VS_Mask = (1 << kINQUIRY_Byte6_VS_Bit), kINQUIRY_Byte6_ENCSERV_Mask = (1 << kINQUIRY_Byte6_ENCSERV_Bit), kINQUIRY_Byte6_BQUE_Mask = (1 << kINQUIRY_Byte6_BQUE_Bit) }; /*! @enum flags2 field definitions @discussion Definitions for bits/masks in the INQUIRY flags2 field. @constant kINQUIRY_Byte7_VS_Bit VS bit definition. @constant kINQUIRY_Byte7_CMDQUE_Bit CMDQUE bit definition. @constant kINQUIRY_Byte7_TRANDIS_Bit TRANDIS bit definition. @constant kINQUIRY_Byte7_LINKED_Bit LINKED bit definition. @constant kINQUIRY_Byte7_SYNC_Bit SYNC bit definition. @constant kINQUIRY_Byte7_WBUS16_Bit WBUS16 bit definition. @constant kINQUIRY_Byte7_RELADR_Bit RELADR bit definition. @constant kINQUIRY_Byte7_VS_Mask Mask to use to test the VS bit. @constant kINQUIRY_Byte7_CMDQUE_Mask Mask to use to test the CMDQUE bit. @constant kINQUIRY_Byte7_TRANDIS_Mask Mask to use to test the TRANDIS bit. @constant kINQUIRY_Byte7_LINKED_Mask Mask to use to test the LINKED bit. @constant kINQUIRY_Byte7_SYNC_Mask Mask to use to test the SYNC bit. @constant kINQUIRY_Byte7_WBUS16_Mask Mask to use to test the WBUS16 bit. @constant kINQUIRY_Byte7_RELADR_Mask Mask to use to test the RELADR bit. */ enum { // Byte offset kINQUIRY_Byte7_Offset = 7, // Bit definitions kINQUIRY_Byte7_VS_Bit = 0, kINQUIRY_Byte7_CMDQUE_Bit = 1, kINQUIRY_Byte7_TRANDIS_Bit = 2, // SPI Specific kINQUIRY_Byte7_LINKED_Bit = 3, kINQUIRY_Byte7_SYNC_Bit = 4, // SPI Specific kINQUIRY_Byte7_WBUS16_Bit = 5, // SPI Specific // Bit 6 is Obsolete kINQUIRY_Byte7_RELADR_Bit = 7, // Masks kINQUIRY_Byte7_VS_Mask = (1 << kINQUIRY_Byte7_VS_Bit), kINQUIRY_Byte7_CMDQUE_Mask = (1 << kINQUIRY_Byte7_CMDQUE_Bit), kINQUIRY_Byte7_TRANDIS_Mask = (1 << kINQUIRY_Byte7_TRANDIS_Bit),// SPI Specific kINQUIRY_Byte7_LINKED_Mask = (1 << kINQUIRY_Byte7_LINKED_Bit), kINQUIRY_Byte7_SYNC_Mask = (1 << kINQUIRY_Byte7_SYNC_Bit), // SPI Specific kINQUIRY_Byte7_WBUS16_Mask = (1 << kINQUIRY_Byte7_WBUS16_Bit), // SPI Specific // Bit 6 is Obsolete kINQUIRY_Byte7_RELADR_Mask = (1 << kINQUIRY_Byte7_RELADR_Bit) }; /*! @enum Byte 56 features field definitions @discussion Definitions for bits/masks in the INQUIRY Byte 56 field. Inquiry Byte 56 features (for devices that report an ANSI VERSION of kINQUIRY_ANSI_VERSION_SCSI_SPC_Compliant or later). These are SPI-3 Specific. @constant kINQUIRY_Byte56_IUS_Bit IUS bit definition. @constant kINQUIRY_Byte56_QAS_Bit QAS bit definition. @constant kINQUIRY_Byte56_IUS_Mask Mask to use to test the IUS bit. @constant kINQUIRY_Byte56_QAS_Mask Mask to use to test the QAS bit. @constant kINQUIRY_Byte56_CLOCKING_Mask Mask to use to test CLOCKING bits. @constant kINQUIRY_Byte56_CLOCKING_ONLY_ST Single-transition clocking only. @constant kINQUIRY_Byte56_CLOCKING_ONLY_DT Double-transition clocking only. @constant kINQUIRY_Byte56_CLOCKING_ST_AND_DT Single-transition and double-transition clocking. */ enum { // Byte offset kINQUIRY_Byte56_Offset = 56, // Bit definitions kINQUIRY_Byte56_IUS_Bit = 0, kINQUIRY_Byte56_QAS_Bit = 1, // Bits 2 and 3 are the CLOCKING bits // All other bits are reserved kINQUIRY_Byte56_IUS_Mask = (1 << kINQUIRY_Byte56_IUS_Bit), kINQUIRY_Byte56_QAS_Mask = (1 << kINQUIRY_Byte56_QAS_Bit), kINQUIRY_Byte56_CLOCKING_Mask = 0x0C, // Definitions for the CLOCKING bits kINQUIRY_Byte56_CLOCKING_ONLY_ST = 0x00, kINQUIRY_Byte56_CLOCKING_ONLY_DT = 0x04, // kINQUIRY_Byte56_CLOCKING_RESERVED = 0x08, kINQUIRY_Byte56_CLOCKING_ST_AND_DT = 0x0C }; /*! @define kINQUIRY_VERSION_DESCRIPTOR_MaxCount Maximum number of INQUIRY version descriptors supported. */ #define kINQUIRY_VERSION_DESCRIPTOR_MaxCount 8 /*! @enum kINQUIRY_VERSION_DESCRIPTOR_SAT SAT specification version descriptor. */ enum { kINQUIRY_VERSION_DESCRIPTOR_SAT = 0x1EA0 }; /*! @enum kINQUIRY_VERSION_DESCRIPTOR_NVME NVMe specification version descriptor. */ enum { kINQUIRY_VERSION_DESCRIPTOR_NVME = 0x8080 }; /* IORegistry property names for information derived from the Inquiry data. The Peripheral Device Type is the only property that the generic Logical Unit Drivers will use to match. These properties are listed in order of matching priority. First is the Peripheral Device Type. Second is the Vendor Identification. Third is the Product Identification. Last is the Product Revision Level. To match a particular product, you would specify the Peripheral Device Type, Vendor Identification, and Product Identification. To restrict the match to a particular firmware revision, you would add the Product Revision Level. To not match on a particular product, but on a particular vendor's products, you would only include the Peripheral Device Type and the Vendor Identification. */ /*! @define kIOPropertySCSIPeripheralDeviceType SCSI Peripheral Device Type as reported in the INQUIRY data. */ #define kIOPropertySCSIPeripheralDeviceType "Peripheral Device Type" /*! @define kIOPropertySCSIPeripheralDeviceTypeSize Size of the kIOPropertySCSIPeripheralDeviceType key. */ #define kIOPropertySCSIPeripheralDeviceTypeSize 8 /*! @define kIOPropertyTPGSInfo TPGS Info as reported in the INQUIRY data. */ #define kIOPropertyTPGSInfo "TPGS Information" /*! @define kIOPropertyHiSup Hierarchical LUN Support as reported in the INQUIRY data. */ #define kIOPropertyHiSup "Hierarchical LUN Support" /*! @define kIOPropertyTPGSInfoSize Size of the kIOPropertyTPGSInfo key. */ #define kIOPropertyTPGSInfoSize 8 /* These properties are listed in order of matching priority */ /*! @define kIOPropertySCSIVendorIdentification Vendor ID as reported in the INQUIRY data. Additional space characters (0x20) are truncated. */ #define kIOPropertySCSIVendorIdentification "Vendor Identification" /*! @define kIOPropertySCSIProductIdentification Product ID as reported in the INQUIRY data. Additional space characters (0x20) are truncated. */ #define kIOPropertySCSIProductIdentification "Product Identification" /*! @define kIOPropertySCSIProductRevisionLevel Product Revision Level as reported in the INQUIRY data. */ #define kIOPropertySCSIProductRevisionLevel "Product Revision Level" #ifndef __OPEN_SOURCE__ /*! @enum INQUIRY Page Codes @discussion INQUIRY Page Codes to be used when EVPD is set in the INQUIRY command. @constant kINQUIRY_Page00_PageCode Page Code 00h. @constant kINQUIRY_Page80_PageCode Page Code 80h. @constant kINQUIRY_Page83_PageCode Page Code 83h. @constant kINQUIRY_Page89_PageCode Page Code 89h. @constant kINQUIRY_PageB0_PageCode Page Code B0h. @constant kINQUIRY_PageB1_PageCode Page Code B1h. @constant kINQUIRY_PageB2_PageCode Page Code B2h. @constant kINQUIRY_PageC0_PageCode Page Code C0h. @constant kINQUIRY_PageC1_PageCode Page Code C1h. */ enum { kINQUIRY_Page00_PageCode = 0x00, kINQUIRY_Page80_PageCode = 0x80, kINQUIRY_Page83_PageCode = 0x83, kINQUIRY_Page89_PageCode = 0x89, kINQUIRY_PageB0_PageCode = 0xB0, kINQUIRY_PageB1_PageCode = 0xB1, kINQUIRY_PageB2_PageCode = 0xB2, kINQUIRY_PageC0_PageCode = 0xC0, kINQUIRY_PageC1_PageCode = 0xC1 }; #else /*! @enum INQUIRY Page Codes @discussion INQUIRY Page Codes to be used when EVPD is set in the INQUIRY command. @constant kINQUIRY_Page00_PageCode Page Code 00h. @constant kINQUIRY_Page80_PageCode Page Code 80h. @constant kINQUIRY_Page83_PageCode Page Code 83h. @constant kINQUIRY_Page89_PageCode Page Code 89h. @constant kINQUIRY_PageB0_PageCode Page Code B0h. @constant kINQUIRY_PageB1_PageCode Page Code B1h. @constant kINQUIRY_PageB2_PageCode Page Code B2h. */ enum { kINQUIRY_Page00_PageCode = 0x00, kINQUIRY_Page80_PageCode = 0x80, kINQUIRY_Page83_PageCode = 0x83, kINQUIRY_Page89_PageCode = 0x89, kINQUIRY_PageB0_PageCode = 0xB0, kINQUIRY_PageB1_PageCode = 0xB1, kINQUIRY_PageB2_PageCode = 0xB2, }; #endif /* __OPEN_SOURCE__ */ /*! @struct SCSICmd_INQUIRY_Page00_Header @discussion INQUIRY Page 00h Header. */ typedef struct SCSICmd_INQUIRY_Page00_Header { UInt8 PERIPHERAL_DEVICE_TYPE; // 7-5 = Qualifier. 4-0 = Device type. UInt8 PAGE_CODE; // Must be equal to 00h UInt8 RESERVED; // reserved field UInt8 PAGE_LENGTH; // n-3 bytes } SCSICmd_INQUIRY_Page00_Header; /*! @struct SCSICmd_INQUIRY_Page00_Header_SPC_16 @discussion INQUIRY Page 00h Header. */ typedef struct SCSICmd_INQUIRY_Page00_Header_SPC_16 { UInt8 PERIPHERAL_DEVICE_TYPE; // 7-5 = Qualifier. 4-0 = Device type. UInt8 PAGE_CODE; // Must be equal to 00h UInt16 PAGE_LENGTH; // n-3 bytes } SCSICmd_INQUIRY_Page00_Header_SPC_16; /*! @struct SCSICmd_INQUIRY_Page80_Header @discussion INQUIRY Page 80h Header. */ typedef struct SCSICmd_INQUIRY_Page80_Header { UInt8 PERIPHERAL_DEVICE_TYPE; // 7-5 = Qualifier. 4-0 = Device type. UInt8 PAGE_CODE; // Must be equal to 80h UInt8 RESERVED; // reserved field UInt8 PAGE_LENGTH; // n-3 bytes UInt8 PRODUCT_SERIAL_NUMBER; // 4-n } SCSICmd_INQUIRY_Page80_Header; /*! @struct SCSICmd_INQUIRY_Page80_Header_SPC_16 @discussion INQUIRY Page 80h Header with 16 bytes INQUIRY Command. */ typedef struct SCSICmd_INQUIRY_Page80_Header_SPC_16 { UInt8 PERIPHERAL_DEVICE_TYPE; // 7-5 = Qualifier. 4-0 = Device type. UInt8 PAGE_CODE; // Must be equal to 80h UInt16 PAGE_LENGTH; // n-3 bytes UInt8 PRODUCT_SERIAL_NUMBER; // 4-n } SCSICmd_INQUIRY_Page80_Header_SPC_16; /*! @define kIOPropertySCSIINQUIRYUnitSerialNumber Key that describes the INQUIRY Unit Serial Number in the IORegistry. */ #define kIOPropertySCSIINQUIRYUnitSerialNumber "INQUIRY Unit Serial Number" /*! @struct SCSICmd_INQUIRY_Page83_Header @discussion INQUIRY Page 83h Header. */ typedef struct SCSICmd_INQUIRY_Page83_Header { UInt8 PERIPHERAL_DEVICE_TYPE; // 7-5 = Qualifier. 4-0 = Device type. UInt8 PAGE_CODE; // Must be equal to 83h UInt8 RESERVED; // reserved field UInt8 PAGE_LENGTH; // n-3 bytes } SCSICmd_INQUIRY_Page83_Header; /*! @struct SCSICmd_INQUIRY_Page83_Header_SPC_16 @discussion INQUIRY Page 83h Header used with the 16 byte INQUIRY command. */ typedef struct SCSICmd_INQUIRY_Page83_Header_SPC_16 { UInt8 PERIPHERAL_DEVICE_TYPE; // 7-5 = Qualifier. 4-0 = Device type. UInt8 PAGE_CODE; // Must be equal to 83h UInt16 PAGE_LENGTH; // n-3 bytes } SCSICmd_INQUIRY_Page83_Header_SPC_16; /*! @struct SCSICmd_INQUIRY_Page83_Identification_Descriptor @discussion INQUIRY Page 83h Identification Descriptor. */ typedef struct SCSICmd_INQUIRY_Page83_Identification_Descriptor { UInt8 CODE_SET; // 7-4 = Protocol Identifier. 3-0 = Code Set UInt8 IDENTIFIER_TYPE; // 7 = PIV 5-4 = ASSOCIATION 3-0 = Identifier UInt8 RESERVED; UInt8 IDENTIFIER_LENGTH; UInt8 IDENTIFIER; } SCSICmd_INQUIRY_Page83_Identification_Descriptor; /*! @enum INQUIRY Page 83h Code Set @discussion Definitions for the Code Set field. @constant kINQUIRY_Page83_CodeSetBinaryData The identifier contains binary data. @constant kINQUIRY_Page83_CodeSetASCIIData The identifier contains ASCII data. @constant kINQUIRY_Page83_CodeSetUTF8Data The identifier contains UTF-8 data. */ enum { kINQUIRY_Page83_CodeSetReserved = 0x0, kINQUIRY_Page83_CodeSetBinaryData = 0x1, kINQUIRY_Page83_CodeSetASCIIData = 0x2, kINQUIRY_Page83_CodeSetUTF8Data = 0x3, // 0x4 - 0xF reserved kINQUIRY_Page83_CodeSetMask = 0xF }; /*! @enum INQUIRY Page 83h Association @discussion Definitions for the Association field. @constant kINQUIRY_Page83_AssociationLogicalUnit Association of the identifier is with the logical unit. @constant kINQUIRY_Page83_AssociationDevice Association of the identifier is with the device (same as logical unit in SPC-2). @constant kINQUIRY_Page83_AssociationTargetPort Association of the identifier is with the target port. @constant kINQUIRY_Page83_AssociationTargetDevice Association of the identifier is with the target device (i.e. all ports). @constant kINQUIRY_Page83_AssociationMask Mask to use to determine association. */ enum { // SPC-3 - Association is changed to be specific to // Logical Units kINQUIRY_Page83_AssociationLogicalUnit = 0x00, // Backwards compatibility for SPC-2 kINQUIRY_Page83_AssociationDevice = kINQUIRY_Page83_AssociationLogicalUnit, // Association is related to a Target Port kINQUIRY_Page83_AssociationTargetPort = 0x10, // SPC-3 - Added as specific association to // a Target device. kINQUIRY_Page83_AssociationTargetDevice = 0x20, kINQUIRY_Page83_AssociationMask = 0x30, kINQUIRY_Page83_AssociationShift = 4 }; /*! @enum INQUIRY Page 83h Identifier Type @discussion Definitions for the Identifier Type field. @constant kINQUIRY_Page83_IdentifierTypeVendorSpecific Vendor Specific Identifier Type. @constant kINQUIRY_Page83_IdentifierTypeVendorID Vendor Specific Identifier Type. @constant kINQUIRY_Page83_IdentifierTypeIEEE_EUI64 EUI-64 Identifier Type. @constant kINQUIRY_Page83_IdentifierTypeNAAIdentifier NAA Identifier Type. @constant kINQUIRY_Page83_IdentifierTypeRelativePortIdentifier Relative Target Port Identifier Type. @constant kINQUIRY_Page83_IdentifierTypeTargetPortGroup Target Port Group Identifier Type. @constant kINQUIRY_Page83_IdentifierTypeLogicalUnitGroup Logical Unit Group Identifier Type. @constant kINQUIRY_Page83_IdentifierTypeMD5LogicalUnitIdentifier MD5 Logical Unit Identifier Type. @constant kINQUIRY_Page83_IdentifierTypeSCSINameString SCSI Name String Identifier Type. @constant kINQUIRY_Page83_IdentifierTypeMask Mask to use to determine association. @constant kINQUIRY_Page83_ProtocolIdentifierValidBit PIV Bit definition. @constant kINQUIRY_Page83_ProtocolIdentifierValidMask Mask to use to determine if PIV is set. */ enum { kINQUIRY_Page83_IdentifierTypeVendorSpecific = 0, kINQUIRY_Page83_IdentifierTypeVendorID = 1, kINQUIRY_Page83_IdentifierTypeIEEE_EUI64 = 2, kINQUIRY_Page83_IdentifierTypeNAAIdentifier = 3, kINQUIRY_Page83_IdentifierTypeRelativePortIdentifier = 4, kINQUIRY_Page83_IdentifierTypeTargetPortGroup = 5, kINQUIRY_Page83_IdentifierTypeLogicalUnitGroup = 6, kINQUIRY_Page83_IdentifierTypeMD5LogicalUnitIdentifier = 7, kINQUIRY_Page83_IdentifierTypeSCSINameString = 8, // 0x9 - 0xF Reserved kINQUIRY_Page83_IdentifierTypeMask = 0xF, kINQUIRY_Page83_ProtocolIdentifierValidBit = 7, kINQUIRY_Page83_ProtocolIdentifierValidMask = (1 << kINQUIRY_Page83_ProtocolIdentifierValidBit) }; // Backwards compatibility #define kINQUIRY_Page83_IdentifierTypeFCNameIdentifier kINQUIRY_Page83_IdentifierTypeNAAIdentifier #define kINQUIRY_Page83_IdentifierTypeUndefined kINQUIRY_Page83_IdentifierTypeVendorSpecific /*! @enum Protocol Identifier values @discussion Definitions for the protocol identifier values. @constant kSCSIProtocolIdentifier_FibreChannel FibreChannel Protocol Identifier. @constant kSCSIProtocolIdentifier_ParallelSCSI Parallel SCSI Protocol Identifier. @constant kSCSIProtocolIdentifier_SSA SSA Protocol Identifier. @constant kSCSIProtocolIdentifier_FireWire FireWire (IEEE-1394) Protocol Identifier. @constant kSCSIProtocolIdentifier_RDMA RDMA Protocol Identifier. @constant kSCSIProtocolIdentifier_iSCSI iSCSI Protocol Identifier. @constant kSCSIProtocolIdentifier_SAS SAS Protocol Identifier. @constant kSCSIProtocolIdentifier_ADT ADT Protocol Identifier. @constant kSCSIProtocolIdentifier_ATAPI ATAPI Protocol Identifier. @constant kSCSIProtocolIdentifier_None No Protocol Identifier. */ enum { kSCSIProtocolIdentifier_FibreChannel = 0, kSCSIProtocolIdentifier_ParallelSCSI = 1, kSCSIProtocolIdentifier_SSA = 2, kSCSIProtocolIdentifier_FireWire = 3, kSCSIProtocolIdentifier_RDMA = 4, kSCSIProtocolIdentifier_iSCSI = 5, kSCSIProtocolIdentifier_SAS = 6, kSCSIProtocolIdentifier_ADT = 7, kSCSIProtocolIdentifier_ATAPI = 8, // 0x9-0xE Reserved kSCSIProtocolIdentifier_None = 0xF }; /*! @define kIOPropertySCSIINQUIRYDeviceIdentification Device Identification key. */ #define kIOPropertySCSIINQUIRYDeviceIdentification "INQUIRY Device Identification" /*! @define kIOPropertySCSIINQUIRYDeviceIdCodeSet Code Set type key. */ #define kIOPropertySCSIINQUIRYDeviceIdCodeSet "Code Set" /*! @define kIOPropertySCSIINQUIRYDeviceIdType Identifier Type key. */ #define kIOPropertySCSIINQUIRYDeviceIdType "Identifier Type" /*! @define kIOPropertySCSIINQUIRYDeviceIdAssociation Association key. */ #define kIOPropertySCSIINQUIRYDeviceIdAssociation "Association" /*! @define kIOPropertySCSIINQUIRYDeviceIdentifier Identifier key (data or string). */ #define kIOPropertySCSIINQUIRYDeviceIdentifier "Identifier" /*! @struct SCSICmd_INQUIRY_Page83_RelativeTargetPort_Identifier @discussion INQUIRY Page 83h Relative Target Port Identifier. */ typedef struct SCSICmd_INQUIRY_Page83_RelativeTargetPort_Identifier { UInt16 OBSOLETE; UInt16 RELATIVE_TARGET_PORT_IDENTIFIER; } SCSICmd_INQUIRY_Page83_RelativeTargetPort_Identifier; /*! @struct SCSICmd_INQUIRY_Page83_TargetPortGroup_Identifier @discussion INQUIRY Page 83h Target Port Group Identifier. */ typedef struct SCSICmd_INQUIRY_Page83_TargetPortGroup_Identifier { UInt16 RESERVED; UInt16 TARGET_PORT_GROUP; } SCSICmd_INQUIRY_Page83_TargetPortGroup_Identifier; /*! @struct SCSICmd_INQUIRY_Page83_LogicalUnitGroup_Identifier @discussion INQUIRY Page 83h Logical Unit Group Identifier. */ typedef struct SCSICmd_INQUIRY_Page83_LogicalUnitGroup_Identifier { UInt16 RESERVED; UInt16 LOGICAL_UNIT_GROUP; } SCSICmd_INQUIRY_Page83_LogicalUnitGroup_Identifier; /*! @struct SCSICmd_INQUIRY_Page89_Data @discussion INQUIRY Page 89h data as defined in the SAT 1.0 specification. This section contains all structures and definitions used by the INQUIRY command in response to a request for page 89h - ATA information VPD Page. */ typedef struct SCSICmd_INQUIRY_Page89_Data { UInt8 PERIPHERAL_DEVICE_TYPE; // 7-5 = Qualifier. 4-0 = Device type. UInt8 PAGE_CODE; // Must be equal to 89h UInt16 PAGE_LENGTH; // Must be equal to 238h UInt32 Reserved; UInt8 SAT_VENDOR_IDENTIFICATION[kINQUIRY_VENDOR_IDENTIFICATION_Length]; UInt8 SAT_PRODUCT_IDENTIFICATION[kINQUIRY_PRODUCT_IDENTIFICATION_Length]; UInt8 SAT_PRODUCT_REVISION_LEVEL[kINQUIRY_PRODUCT_REVISION_LEVEL_Length]; UInt8 ATA_DEVICE_SIGNATURE[20]; UInt8 COMMAND_CODE; UInt8 Reserved2[3]; UInt8 IDENTIFY_DATA[512]; } SCSICmd_INQUIRY_Page89_Data; #pragma pack(push, 1) /*! @struct SCSICmd_INQUIRY_PageB0_Data @discussion INQUIRY Page B0h data as defined in the SBC specification. This section contains all structures and definitions used by the INQUIRY command in response to a request for page B0h - Block Limits VPD Page. */ typedef struct SCSICmd_INQUIRY_PageB0_Data { UInt8 PERIPHERAL_DEVICE_TYPE; // 7-5 = Qualifier. 4-0 = Device type. UInt8 PAGE_CODE; // Must be equal to B0h UInt16 PAGE_LENGTH; // Must be equal to 3Ch UInt8 WSNZ; // 0 = WSNZ, 7-1 = Reserved. UInt8 MAXIMUM_COMPARE_AND_WRITE_LENGTH; UInt16 OPTIMAL_TRANSFER_LENGTH_GRANULARITY; UInt32 MAXIMUM_TRANSFER_LENGTH; UInt32 OPTIMAL_TRANSFER_LENGTH; UInt32 MAXIMUM_PREFETCH_LENGTH; UInt32 MAXIMUM_UNMAP_LBA_COUNT; UInt32 MAXIMUM_UNMAP_BLOCK_DESCRIPTOR_COUNT; UInt32 OPTIMAL_UNMAP_GRANULARITY; UInt32 UNMAP_GRANULARITY_ALIGNMENT; UInt64 MAXIMUM_WRITE_SAME_LENGTH; UInt32 MAXIMUM_ATOMIC_TRANSFER_LENGTH; UInt32 ATOMIC_ALIGNMENT; UInt32 ATOMIC_TRANSFER_LENGTH_GRANULARITY; UInt32 MAXIMUM_ATOMIC_TRANSFER_LENGTH_WITH_ATOMIC_BOUNDARY; UInt32 MAXIMUM_ATOMIC_BOUNDARY_SIZE; } SCSICmd_INQUIRY_PageB0_Data; #pragma pack(pop) /*! @struct SCSICmd_INQUIRY_PageB1_Data @discussion INQUIRY Page B1h data as defined in the SBC specification. This section contains all structures and definitions used by the INQUIRY command in response to a request for page B1h - Block Device Characteristics VPD Page. */ typedef struct SCSICmd_INQUIRY_PageB1_Data { UInt8 PERIPHERAL_DEVICE_TYPE; // 7-5 = Qualifier. 4-0 = Device type. UInt8 PAGE_CODE; // Must be equal to B1h UInt8 Reserved; UInt8 PAGE_LENGTH; // Must be equal to 3Ch UInt16 MEDIUM_ROTATION_RATE; UInt8 Reserved2[58]; } SCSICmd_INQUIRY_PageB1_Data; enum { kINQUIRY_PageB1_Page_Length = 0x3C }; #pragma pack(push, 1) /*! @struct SCSICmd_INQUIRY_PageB2_Data @discussion INQUIRY Page B2h data as defined in the SBC specification. This section contains all structures and definitions used by the INQUIRY command in response to a request for page B2h - Logical Block Provisioning VPD Page. */ typedef struct SCSICmd_INQUIRY_PageB2_Data { UInt8 PERIPHERAL_DEVICE_TYPE; // 7-5 = Qualifier. 4-0 = Device type. UInt8 PAGE_CODE; // Must be equal to B2h. UInt16 PAGE_LENGTH; // Must be n-3. UInt8 THRESHOLD_EXPONENT; UInt8 LBP_FLAGS; // 7 = LBPU, 6 = LBPWS, 5 = LBPWS10, // 4-2 = LBPRZ, 1 = ANC_SUP, 0 = DP. UInt8 MINIMUM_PERCENTAGE; // 7-3 = MINIMUM PERCENTAGE, // 2-0 = PROVISIONING TYPE. UInt8 THRESHOLD_PERCENTAGE; } SCSICmd_INQUIRY_PageB2_Data; typedef struct SCSICmd_INQUIRY_PageB2_Provisioning_Group_Descriptor { UInt8 DESIGNATION_DESCRIPTOR[20]; UInt8 RESERVED[18]; } SCSICmd_INQUIRY_PageB2_Provisioning_Group_Descriptor; #pragma pack(pop) #ifndef __OPEN_SOURCE__ #pragma pack(push, 1) enum { kC0DataMaxStringLen = 32 }; enum { kINQUIRY_PageC0_Features_HasSEP_LUN = ( 1 << 3 ) }; typedef struct SCSICmd_INQUIRY_PageCx_Header { UInt8 PERIPHERAL_DEVICE_TYPE; // 7-5 = Qualifier. 4-0 = Device type. UInt8 PAGE_CODE; // Must be equal to C0h or C1h UInt8 RESERVED; UInt8 PAGE_LENGTH; } SCSICmd_INQUIRY_PAGECx_Header; /*! @struct SCSICmd_INQUIRY_PageC0_Data @discussion INQUIRY Page C0h data as defined in Apple Target Disk Mode specification. This is a vendor specific data structure. This section contains all structures and definitions used by the INQUIRY command in response to a request for page C0h. */ typedef struct SCSICmd_INQUIRY_PageC0_Data { SCSICmd_INQUIRY_PAGECx_Header fHeader; UInt8 fTdmPageVersion; UInt8 fTdmProtocolVersion; UInt8 fReserved1; UInt8 fReserved2; UInt8 fMacModelId[kC0DataMaxStringLen]; UInt8 fSerialNumber[kC0DataMaxStringLen]; UInt32 fMaxReadSize; UInt32 fMaxWriteSize; UInt32 fNativeBlockSize; UInt32 fPreferredIOSize; UInt64 fFeatures; UInt64 fWorkArounds; UInt16 fEncryptionType; UInt8 fReserved3[2]; UInt64 fInstalledRAMSize; } SCSICmd_INQUIRY_PageC0_Data; /*! @struct SCSICmd_INQUIRY_PageC1_Data @discussion INQUIRY Page C1h data as defined in Apple Target Disk Mode specification. This is a vendor specific data structure. This section contains all structures and definitions used by the INQUIRY command in response to a request for page C1h. */ typedef struct SCSICmd_INQUIRY_PageC1_Data { SCSICmd_INQUIRY_PAGECx_Header fHeader; UInt8 fTdmPowerRequirementsPageVersion; UInt8 fReserved1; UInt16 fReserved2; UInt32 fPowerRequired; } SCSICmd_INQUIRY_PageC1_Data; #pragma pack(pop) #endif /* __OPEN_SOURCE__ */ /*! @define kIOPropertySATVendorIdentification Vendor Identification of the SATL. */ #define kIOPropertySATVendorIdentification "SAT Vendor Identification" /*! @define kIOPropertySATProductIdentification Product Identification of the SATL. */ #define kIOPropertySATProductIdentification "SAT Product Identification" /*! @define kIOPropertySATProductRevisonLevel Product Revision Level of the SATL. */ #define kIOPropertySATProductRevisonLevel "SAT Product Revision Level" #endif /* _IOKIT_SCSI_CMDS_INQUIRY_H_ */
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/scsi/IOSCSIMultimediaCommandsDevice.h
/* * Copyright (c) 1998-2009 Apple Inc. All rights reserved. * * @APPLE_LICENSE_HEADER_START@ * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this * file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_LICENSE_HEADER_END@ */ #ifndef _IOKIT_IO_SCSI_MULTIMEDIA_COMMANDS_DEVICE_H_ #define _IOKIT_IO_SCSI_MULTIMEDIA_COMMANDS_DEVICE_H_ #if KERNEL #include <IOKit/IOTypes.h> #else #include <CoreFoundation/CoreFoundation.h> #endif #include <IOKit/storage/IOStorageDeviceCharacteristics.h> // Build includes #include <TargetConditionals.h> //----------------------------------------------------------------------------- // Constants //----------------------------------------------------------------------------- // Message constants #define kIOMessageTrayStateChange 0x69000035 #define kIOMessageTrayStateHasChanged kIOMessageTrayStateChange // DEPRECATED, use kIOMessageTrayStateChange instead // Message values for kIOMessageTrayStateChange enum { kMessageTrayStateChangeRequestAccepted = 0, kMessageTrayStateChangeRequestRejected = 1 }; #define kIOMessageMediaAccessChange 0x69000036 // Message values for kIOMessageMediaAccessChange enum { kMessageDeterminingMediaPresence = 0, kMessageFoundMedia = 1, kMessageMediaTypeDetermined = 2 }; // IOKit property keys and constants #define kIOPropertySupportedCDFeatures kIOPropertySupportedCDFeaturesKey #define kIOPropertySupportedDVDFeatures kIOPropertySupportedDVDFeaturesKey #define kIOPropertySupportedBDFeatures kIOPropertySupportedBDFeaturesKey #define kIOPropertyLowPowerPolling "Low Power Polling" typedef UInt32 CDFeatures; enum { kCDFeaturesAnalogAudioBit = 0, // Analog Audio playback kCDFeaturesReadStructuresBit = 1, // CD-ROM kCDFeaturesWriteOnceBit = 2, // CD-R kCDFeaturesReWriteableBit = 3, // CD-R/W kCDFeaturesCDDAStreamAccurateBit = 4, // CD-DA stream accurate kCDFeaturesPacketWriteBit = 5, // Packet Writing kCDFeaturesTAOWriteBit = 6, // CD Track At Once kCDFeaturesSAOWriteBit = 7, // CD Mastering - Session At Once kCDFeaturesRawWriteBit = 8, // CD Mastering - Raw kCDFeaturesTestWriteBit = 9, // CD Mastering/TAO - Test Write kCDFeaturesBUFWriteBit = 10 // CD Mastering/TAO - Buffer Underrun Free }; enum { kCDFeaturesAnalogAudioMask = (1 << kCDFeaturesAnalogAudioBit), kCDFeaturesReadStructuresMask = (1 << kCDFeaturesReadStructuresBit), kCDFeaturesWriteOnceMask = (1 << kCDFeaturesWriteOnceBit), kCDFeaturesReWriteableMask = (1 << kCDFeaturesReWriteableBit), kCDFeaturesCDDAStreamAccurateMask = (1 << kCDFeaturesCDDAStreamAccurateBit), kCDFeaturesPacketWriteMask = (1 << kCDFeaturesPacketWriteBit), kCDFeaturesTAOWriteMask = (1 << kCDFeaturesTAOWriteBit), kCDFeaturesSAOWriteMask = (1 << kCDFeaturesSAOWriteBit), kCDFeaturesRawWriteMask = (1 << kCDFeaturesRawWriteBit), kCDFeaturesTestWriteMask = (1 << kCDFeaturesTestWriteBit), kCDFeaturesBUFWriteMask = (1 << kCDFeaturesBUFWriteBit) }; typedef UInt32 DVDFeatures; enum { kDVDFeaturesCSSBit = 0, // DVD-CSS kDVDFeaturesReadStructuresBit = 1, // DVD-ROM kDVDFeaturesWriteOnceBit = 2, // DVD-R kDVDFeaturesRandomWriteableBit = 3, // DVD-RAM kDVDFeaturesReWriteableBit = 4, // DVD-RW kDVDFeaturesTestWriteBit = 5, // DVD-R Write - Test Write kDVDFeaturesBUFWriteBit = 6, // DVD-R Write - Buffer Underrun Free kDVDFeaturesPlusRBit = 7, // DVD+R kDVDFeaturesPlusRWBit = 8, // DVD+RW (implies backgound format support) kDVDFeaturesHDReadBit = 9, // HD DVD-ROM kDVDFeaturesHDRBit = 10, // HD DVD-R kDVDFeaturesHDRAMBit = 11, // HD DVD-RAM kDVDFeaturesHDRWBit = 12 // HD DVD-RW }; enum { kDVDFeaturesCSSMask = (1 << kDVDFeaturesCSSBit), kDVDFeaturesReadStructuresMask = (1 << kDVDFeaturesReadStructuresBit), kDVDFeaturesWriteOnceMask = (1 << kDVDFeaturesWriteOnceBit), kDVDFeaturesRandomWriteableMask = (1 << kDVDFeaturesRandomWriteableBit), kDVDFeaturesReWriteableMask = (1 << kDVDFeaturesReWriteableBit), kDVDFeaturesTestWriteMask = (1 << kDVDFeaturesTestWriteBit), kDVDFeaturesBUFWriteMask = (1 << kDVDFeaturesBUFWriteBit), kDVDFeaturesPlusRMask = (1 << kDVDFeaturesPlusRBit), kDVDFeaturesPlusRWMask = (1 << kDVDFeaturesPlusRWBit), kDVDFeaturesHDReadMask = (1 << kDVDFeaturesHDReadBit), kDVDFeaturesHDRMask = (1 << kDVDFeaturesHDRBit), kDVDFeaturesHDRAMMask = (1 << kDVDFeaturesHDRAMBit), kDVDFeaturesHDRWMask = (1 << kDVDFeaturesHDRWBit) }; typedef UInt32 BDFeatures; enum { kBDFeaturesReadBit = 0, // BD-ROM kBDFeaturesWriteBit = 1 // BD-R / BD-RE }; enum { kBDFeaturesReadMask = (1 << kBDFeaturesReadBit), kBDFeaturesWriteMask = (1 << kBDFeaturesWriteBit) }; enum { kDiscStatusEmpty = 0, kDiscStatusIncomplete = 1, kDiscStatusComplete = 2, kDiscStatusOther = 3, kDiscStatusMask = 0x03, kDiscStatusErasableMask = 0x10 }; #if defined(KERNEL) && defined(__cplusplus) // MMC power states as defined in T10:1228D SCSI Multimedia Commands - 2 (MMC-2) // Revision 11a, August 30, 1999, page 312 (Annex F). enum { kMMCPowerStateSystemSleep = 0, kMMCPowerStateSleep = 1, kMMCPowerStateStandby = 2, kMMCPowerStateIdle = 3, kMMCPowerStateActive = 4, kMMCNumPowerStates = 5 }; enum { kMediaStateUnlocked = 0, kMediaStateLocked = 1 }; //----------------------------------------------------------------------------- // Includes //----------------------------------------------------------------------------- // General IOKit headers #include <IOKit/IOLib.h> #include <IOKit/IOMemoryDescriptor.h> // Generic IOKit storage related headers #include <IOKit/storage/IOStorage.h> #include <IOKit/storage/IOCDTypes.h> #include <IOKit/storage/IODVDTypes.h> // SCSI Architecture Model Family includes #include <IOKit/scsi/IOSCSIPrimaryCommandsDevice.h> // Forward definitions for internal use only classes class SCSIMultimediaCommands; class SCSIBlockCommands; //----------------------------------------------------------------------------- // Class Declaration //----------------------------------------------------------------------------- class __exported IOSCSIMultimediaCommandsDevice : public IOSCSIPrimaryCommandsDevice { OSDeclareAbstractStructors ( IOSCSIMultimediaCommandsDevice ) private: static void AsyncReadWriteComplete ( SCSITaskIdentifier completedTask ); protected: // Reserve space for future expansion. struct IOSCSIMultimediaCommandsDeviceExpansionData { IONotifier * fPowerDownNotifier; bool fDeviceSupportsPowerOff; BDFeatures fSupportedBDFeatures; bool fDeviceSupportsAsyncNotification; bool fDeviceSupportsFastSpindown; UInt8 fCDLoadingMechanism; bool fDoNotLockMedia; }; IOSCSIMultimediaCommandsDeviceExpansionData * fIOSCSIMultimediaCommandsDeviceReserved; #define fPowerDownNotifier fIOSCSIMultimediaCommandsDeviceReserved->fPowerDownNotifier #define fDeviceSupportsPowerOff fIOSCSIMultimediaCommandsDeviceReserved->fDeviceSupportsPowerOff #define fSupportedBDFeatures fIOSCSIMultimediaCommandsDeviceReserved->fSupportedBDFeatures #define fDeviceSupportsAsyncNotification fIOSCSIMultimediaCommandsDeviceReserved->fDeviceSupportsAsyncNotification #define fDeviceSupportsFastSpindown fIOSCSIMultimediaCommandsDeviceReserved->fDeviceSupportsFastSpindown #define fCDLoadingMechanism fIOSCSIMultimediaCommandsDeviceReserved->fCDLoadingMechanism #define fDoNotLockMedia fIOSCSIMultimediaCommandsDeviceReserved->fDoNotLockMedia CDFeatures fSupportedCDFeatures; DVDFeatures fSupportedDVDFeatures; UInt16 fCurrentDiscSpeed; bool fMediaChanged; bool fMediaPresent; // The byte count of each physical block on the media. UInt32 fMediaBlockSize; // The total number of blocks of fMediaBlockSize on the media. UInt32 fMediaBlockCount; // Flags used to indicate device feature bool fMediaIsRemovable; bool fMediaIsWriteProtected; UInt32 fMediaType; thread_call_t fPollingThread; bool fDeviceSupportsLowPowerPolling; bool fLowPowerPollingEnabled; UInt32 fPollingMode; enum { kPollingMode_Suspended = 0, kPollingMode_NewMedia = 1, kPollingMode_MediaRemoval = 2 }; virtual IOReturn setProperties ( OSObject * properties ) APPLE_KEXT_OVERRIDE; virtual void CreateStorageServiceNub ( void ); virtual bool DetermineDeviceCharacteristics ( void ); virtual IOReturn DetermineIfMediaIsRemovable ( void ); virtual IOReturn DetermineDeviceFeatures ( void ); virtual void DetermineMediaType ( void ); virtual bool CheckForDVDMediaType ( void ); virtual bool CheckForCDMediaType ( void ); virtual void PollForMedia ( void ); virtual void EnablePolling ( void ); virtual void DisablePolling ( void ); virtual void CheckWriteProtection ( void ); virtual bool ClearNotReadyStatus ( void ) APPLE_KEXT_OVERRIDE; virtual IOReturn GetDeviceConfiguration ( void ); virtual IOReturn GetDeviceConfigurationSize ( UInt32 * size ); virtual IOReturn ParseFeatureList ( UInt32 numProfiles, UInt8 * firstFeaturePtr ); virtual IOReturn GetMechanicalCapabilities ( void ); virtual IOReturn GetMechanicalCapabilitiesSize ( UInt32 * size ); virtual IOReturn ParseMechanicalCapabilities ( UInt8 * mechanicalCapabilitiesPtr ); virtual IOReturn CheckForLowPowerPollingSupport ( void ); virtual IOReturn GetCurrentPowerStateOfDrive ( UInt32 * powerState ); virtual IOReturn IssueRead ( IOMemoryDescriptor * buffer, UInt64 startBlock, UInt64 blockCount ); virtual IOReturn IssueRead ( IOMemoryDescriptor * buffer, void * clientData, UInt64 startBlock, UInt64 blockCount ); virtual IOReturn IssueWrite ( IOMemoryDescriptor * buffer, UInt64 startBlock, UInt64 blockCount ); virtual IOReturn IssueWrite ( IOMemoryDescriptor * buffer, void * clientData, UInt64 startBlock, UInt64 blockCount ); virtual void SetMediaCharacteristics ( UInt32 blockSize, UInt32 blockCount ); virtual void ResetMediaCharacteristics ( void ); UInt8 ConvertBCDToHex ( UInt8 binaryCodedDigit ); // ------ User Client Support ------ virtual IOReturn HandleSetUserClientExclusivityState ( IOService * userClient, bool state ) APPLE_KEXT_OVERRIDE; // ----- Power Management Support ------ // We override this method to set our power states and register ourselves // as a power policy maker. virtual void InitializePowerManagement ( IOService * provider ) APPLE_KEXT_OVERRIDE; // We override this method so that when we register for power management, // we go to our active power state (which the drive is definitely in // at startup time). virtual UInt32 GetInitialPowerState ( void ) APPLE_KEXT_OVERRIDE; // We override this method in order to provide the number of transitions // from Fully active to Sleep state so that the idle timer can be adjusted // to the appropriate time period based on the disk spindown time set in // the Energy Saver prefs panel. virtual UInt32 GetNumberOfPowerStateTransitions ( void ) APPLE_KEXT_OVERRIDE; // The TicklePowerManager method is called to tell the power manager that the // device needs to be in a certain power state to handle requests. virtual void TicklePowerManager ( void ) APPLE_KEXT_OVERRIDE; // The HandlePowerChange method is the state machine for power management. // It is guaranteed to be on its own thread of execution (different from // the power manager thread AND the workloop thread. This routine can // send sync or async calls to the drive without worrying about threading // issues. virtual void HandlePowerChange ( void ) APPLE_KEXT_OVERRIDE; // The HandleCheckPowerState (void) method is on the serialized side of the command // gate and can change member variables safely without multi-threading issues. // It's main purpose is to call the superclass' HandleCheckPowerState ( UInt32 maxPowerState ) // with the max power state the class registered with. virtual void HandleCheckPowerState ( void ) APPLE_KEXT_OVERRIDE; // The CheckMediaPresence method is called to see if the media which we // anticipated being there is still there. virtual bool CheckMediaPresence ( void ); virtual bool InitializeDeviceSupport ( void ) APPLE_KEXT_OVERRIDE; virtual void StartDeviceSupport ( void ) APPLE_KEXT_OVERRIDE; virtual void SuspendDeviceSupport ( void ) APPLE_KEXT_OVERRIDE; virtual void ResumeDeviceSupport ( void ) APPLE_KEXT_OVERRIDE; virtual void StopDeviceSupport ( void ) APPLE_KEXT_OVERRIDE; virtual void TerminateDeviceSupport ( void ) APPLE_KEXT_OVERRIDE; virtual void free ( void ) APPLE_KEXT_OVERRIDE; virtual IOReturn VerifyDeviceState ( void ) APPLE_KEXT_OVERRIDE; public: virtual IOReturn setAggressiveness ( unsigned long type, unsigned long minutes ) APPLE_KEXT_OVERRIDE; virtual IOReturn SyncReadWrite ( IOMemoryDescriptor * buffer, UInt64 startBlock, UInt64 blockCount ); virtual IOReturn AsyncReadWrite ( IOMemoryDescriptor * buffer, UInt64 block, UInt64 nblks, void * clientData ); virtual IOReturn EjectTheMedia ( void ); virtual IOReturn GetTrayState ( UInt8 * trayState ); virtual IOReturn SetTrayState ( UInt8 trayState ); virtual IOReturn FormatMedia ( UInt64 byteCapacity ); virtual UInt32 GetFormatCapacities ( UInt64 * capacities, UInt32 capacitiesMaxCount ) const; virtual IOReturn LockUnlockMedia ( bool doLock ); virtual IOReturn SynchronizeCache ( void ); virtual IOReturn ReportBlockSize ( UInt64 * blockSize ); virtual IOReturn ReportEjectability ( bool * isEjectable ); virtual IOReturn ReportLockability ( bool * isLockable ); virtual IOReturn ReportPollRequirements ( bool * pollIsRequired, bool * pollIsExpensive ); virtual IOReturn ReportMaxReadTransfer ( UInt64 blockSize, UInt64 * max ); virtual IOReturn ReportMaxValidBlock ( UInt64 * maxBlock ); virtual IOReturn ReportMaxWriteTransfer ( UInt64 blockSize, UInt64 * max ); virtual IOReturn ReportMediaState ( bool * mediaPresent, bool * changed ); virtual IOReturn ReportRemovability ( bool * isRemovable ); virtual IOReturn ReportWriteProtection ( bool * isWriteProtected ); static void sPollForMedia ( void * pdtDriver, void * refCon ); /* CD Specific */ virtual IOReturn SetMediaAccessSpeed ( UInt16 kilobytesPerSecond ); virtual IOReturn GetMediaAccessSpeed ( UInt16 * kilobytesPerSecond ); virtual IOReturn AsyncReadCD ( IOMemoryDescriptor * buffer, UInt32 block, UInt32 nblks, CDSectorArea sectorArea, CDSectorType sectorType, void * clientData ); virtual IOReturn ReadISRC ( UInt8 track, CDISRC isrc ); virtual IOReturn ReadMCN ( CDMCN mcn); virtual IOReturn ReadTOC ( IOMemoryDescriptor * buffer ); /* DVD Specific */ virtual UInt32 GetMediaType ( void ); virtual IOReturn ReportKey ( IOMemoryDescriptor * buffer, const DVDKeyClass keyClass, const UInt32 lba, const UInt8 agid, const DVDKeyFormat keyFormat ) __attribute__ ((deprecated)); virtual IOReturn SendKey ( IOMemoryDescriptor * buffer, const DVDKeyClass keyClass, const UInt8 agid, const DVDKeyFormat keyFormat ); virtual IOReturn ReadDVDStructure ( IOMemoryDescriptor * buffer, const UInt32 length, const UInt8 structureFormat, const UInt32 logicalBlockAddress, const UInt8 layer, const UInt8 agid ); // The block size decoding for Read CD and Read CD MSF as defined in table 255 bool GetBlockSize ( UInt32 * requestedByteCount, SCSICmdField3Bit EXPECTED_SECTOR_TYPE, SCSICmdField1Bit SYNC, SCSICmdField2Bit HEADER_CODES, SCSICmdField1Bit USER_DATA, SCSICmdField1Bit EDC_ECC, SCSICmdField2Bit ERROR_FIELD, SCSICmdField3Bit SUBCHANNEL_SELECTION_BITS ); SCSICmdField4Byte ConvertMSFToLBA ( SCSICmdField3Byte MSF ); // The GET CONFIGURATION command as defined in section 6.1.4 virtual bool GET_CONFIGURATION ( SCSITaskIdentifier request, IOMemoryDescriptor * dataBuffer, SCSICmdField2Bit RT, SCSICmdField2Byte STARTING_FEATURE_NUMBER, SCSICmdField2Byte ALLOCATION_LENGTH, SCSICmdField1Byte CONTROL ); // The GET EVENT/STATUS NOTIFICATION command as defined in section 6.1.5 virtual bool GET_EVENT_STATUS_NOTIFICATION ( SCSITaskIdentifier request, IOMemoryDescriptor * dataBuffer, SCSICmdField1Bit IMMED, SCSICmdField1Byte NOTIFICATION_CLASS_REQUEST, SCSICmdField2Byte ALLOCATION_LENGTH, SCSICmdField1Byte CONTROL ); // The GET PERFORMANCE command as defined in section 6.1.6 virtual bool GET_PERFORMANCE ( SCSITaskIdentifier request, IOMemoryDescriptor * dataBuffer, SCSICmdField2Bit TOLERANCE, SCSICmdField1Bit WRITE, SCSICmdField2Bit EXCEPT, SCSICmdField4Byte STARTING_LBA, SCSICmdField2Byte MAXIMUM_NUMBER_OF_DESCRIPTORS, SCSICmdField1Byte CONTROL ); // The LOAD/UNLOAD MEDIUM command as defined in section 6.1.7 virtual bool LOAD_UNLOAD_MEDIUM ( SCSITaskIdentifier request, SCSICmdField1Bit IMMED, SCSICmdField1Bit LO_UNLO, SCSICmdField1Bit START, SCSICmdField1Byte SLOT, SCSICmdField1Byte CONTROL ); // The MECHANISM STATUS command as defined in section 6.1.8 virtual bool MECHANISM_STATUS ( SCSITaskIdentifier request, IOMemoryDescriptor * dataBuffer, SCSICmdField2Byte ALLOCATION_LENGTH, SCSICmdField1Byte CONTROL ); virtual bool READ_10 ( SCSITaskIdentifier request, IOMemoryDescriptor *dataBuffer, UInt32 blockSize, SCSICmdField1Bit DPO, SCSICmdField1Bit FUA, SCSICmdField1Bit RELADR, SCSICmdField4Byte LOGICAL_BLOCK_ADDRESS, SCSICmdField2Byte TRANSFER_LENGTH, SCSICmdField1Byte CONTROL ); // The READ CD command as defined in section 6.1.15 virtual bool READ_CD ( SCSITaskIdentifier request, IOMemoryDescriptor * dataBuffer, SCSICmdField3Bit EXPECTED_SECTOR_TYPE, SCSICmdField1Bit RELADR, SCSICmdField4Byte STARTING_LOGICAL_BLOCK_ADDRESS, SCSICmdField3Byte TRANSFER_LENGTH, SCSICmdField1Bit SYNC, SCSICmdField2Bit HEADER_CODES, SCSICmdField1Bit USER_DATA, SCSICmdField1Bit EDC_ECC, SCSICmdField2Bit ERROR_FIELD, SCSICmdField3Bit SUBCHANNEL_SELECTION_BITS, SCSICmdField1Byte CONTROL ); // The READ CD MSF command as defined in section 6.1.16 virtual bool READ_CD_MSF ( SCSITaskIdentifier request, IOMemoryDescriptor * dataBuffer, SCSICmdField3Bit EXPECTED_SECTOR_TYPE, SCSICmdField3Byte STARTING_MSF, SCSICmdField3Byte ENDING_MSF, SCSICmdField1Bit SYNC, SCSICmdField2Bit HEADER_CODES, SCSICmdField1Bit USER_DATA, SCSICmdField1Bit EDC_ECC, SCSICmdField2Bit ERROR_FIELD, SCSICmdField3Bit SUBCHANNEL_SELECTION_BITS, SCSICmdField1Byte CONTROL ); // The READ CAPACITY command as defined in section 6.1.17 virtual bool READ_CAPACITY ( SCSITaskIdentifier request, IOMemoryDescriptor * dataBuffer, SCSICmdField1Bit RELADR, SCSICmdField4Byte LOGICAL_BLOCK_ADDRESS, SCSICmdField1Bit PMI, SCSICmdField1Byte CONTROL ); // The READ DISC INFORMATION command as defined in section 6.1.18 virtual bool READ_DISC_INFORMATION ( SCSITaskIdentifier request, IOMemoryDescriptor * dataBuffer, SCSICmdField2Byte ALLOCATION_LENGTH, SCSICmdField1Byte CONTROL ); // The READ DVD STRUCTURE command as defined in section 6.1.19 virtual bool READ_DVD_STRUCTURE ( SCSITaskIdentifier request, IOMemoryDescriptor * dataBuffer, SCSICmdField4Byte ADDRESS, SCSICmdField1Byte LAYER_NUMBER, SCSICmdField1Byte FORMAT, SCSICmdField2Byte ALLOCATION_LENGTH, SCSICmdField2Bit AGID, SCSICmdField1Byte CONTROL ); // The READ FORMAT CAPACITIES command as defined in section 6.1.20 virtual bool READ_FORMAT_CAPACITIES ( SCSITaskIdentifier request, IOMemoryDescriptor * dataBuffer, SCSICmdField2Byte ALLOCATION_LENGTH, SCSICmdField1Byte CONTROL ); // The READ SUB-CHANNEL command as defined in section 6.1.23 virtual bool READ_SUB_CHANNEL ( SCSITaskIdentifier request, IOMemoryDescriptor * dataBuffer, SCSICmdField1Bit MSF, SCSICmdField1Bit SUBQ, SCSICmdField1Byte SUB_CHANNEL_PARAMETER_LIST, SCSICmdField1Byte TRACK_NUMBER, SCSICmdField2Byte ALLOCATION_LENGTH, SCSICmdField1Byte CONTROL ); // The READ TOC/PMA/ATIP command as defined in section 6.1.24/25 virtual bool READ_TOC_PMA_ATIP ( SCSITaskIdentifier request, IOMemoryDescriptor * dataBuffer, SCSICmdField1Bit MSF, SCSICmdField4Bit FORMAT, SCSICmdField1Byte TRACK_SESSION_NUMBER, SCSICmdField2Byte ALLOCATION_LENGTH, SCSICmdField1Byte CONTROL ); // The READ TRACK INFORMATION command as defined in section 6.1.26 virtual bool READ_TRACK_INFORMATION ( SCSITaskIdentifier request, IOMemoryDescriptor * dataBuffer, SCSICmdField2Bit ADDRESS_NUMBER_TYPE, SCSICmdField4Byte LOGICAL_BLOCK_ADDRESS_TRACK_SESSION_NUMBER, SCSICmdField2Byte ALLOCATION_LENGTH, SCSICmdField1Byte CONTROL ); /*********************** LEGACY COMMAND SUPPORT ***********************/ // The SET CD SPEED command as defined in section 6.1.36 virtual bool SET_CD_SPEED ( SCSITaskIdentifier request, SCSICmdField2Byte LOGICAL_UNIT_READ_SPEED, SCSICmdField2Byte LOGICAL_UNIT_WRITE_SPEED, SCSICmdField1Byte CONTROL ); /*********************** END LEGACY COMMAND SUPPORT ***********************/ // The SET READ AHEAD command as defined in section 6.1.37 virtual bool SET_READ_AHEAD ( SCSITaskIdentifier request, SCSICmdField4Byte TRIGGER_LOGICAL_BLOCK_ADDRESS, SCSICmdField4Byte READ_AHEAD_LOGICAL_BLOCK_ADDRESS, SCSICmdField1Byte CONTROL ); // The SET STREAMING command as defined in section 6.1.38 virtual bool SET_STREAMING ( SCSITaskIdentifier request, IOMemoryDescriptor * dataBuffer, SCSICmdField2Byte PARAMETER_LIST_LENGTH, SCSICmdField1Byte CONTROL ); virtual bool START_STOP_UNIT ( SCSITaskIdentifier request, SCSICmdField1Bit IMMED, SCSICmdField4Bit POWER_CONDITIONS, SCSICmdField1Bit LOEJ, SCSICmdField1Bit START, SCSICmdField1Byte CONTROL ); // The SYNCHRONIZE CACHE command as defined in section 6.1.40 virtual bool SYNCHRONIZE_CACHE ( SCSITaskIdentifier request, SCSICmdField1Bit IMMED, SCSICmdField1Bit RELADR, SCSICmdField4Byte LOGICAL_BLOCK_ADDRESS, SCSICmdField2Byte NUMBER_OF_BLOCKS, SCSICmdField1Byte CONTROL ); // The WRITE (10) command as defined in section 6.1.41 virtual bool WRITE_10 ( SCSITaskIdentifier request, IOMemoryDescriptor * dataBuffer, UInt32 blockSize, SCSICmdField1Bit DPO, SCSICmdField1Bit FUA, SCSICmdField1Bit RELADR, SCSICmdField4Byte LOGICAL_BLOCK_ADDRESS, SCSICmdField2Byte TRANSFER_LENGTH, SCSICmdField1Byte CONTROL ); // The WRITE AND VERIFY (10) command as defined in section 6.1.42 virtual bool WRITE_AND_VERIFY_10 ( SCSITaskIdentifier request, IOMemoryDescriptor * dataBuffer, UInt32 blockSize, SCSICmdField1Bit DPO, SCSICmdField1Bit BYT_CHK, SCSICmdField1Bit RELADR, SCSICmdField4Byte LOGICAL_BLOCK_ADDRESS, SCSICmdField4Byte TRANSFER_LENGTH, SCSICmdField1Byte CONTROL ); /* Added with 10.1.3 */ OSMetaClassDeclareReservedUsed ( IOSCSIMultimediaCommandsDevice, 1 ); virtual IOReturn ReadTOC ( IOMemoryDescriptor * buffer, CDTOCFormat format, UInt8 msf, UInt32 trackSessionNumber, UInt16 * actualByteCount ); /* Added with 10.1.3 */ OSMetaClassDeclareReservedUsed ( IOSCSIMultimediaCommandsDevice, 2 ); virtual IOReturn ReadDiscInfo ( IOMemoryDescriptor * buffer, UInt16 * actualByteCount ); /* Added with 10.1.3 */ OSMetaClassDeclareReservedUsed ( IOSCSIMultimediaCommandsDevice, 3 ); virtual IOReturn ReadTrackInfo ( IOMemoryDescriptor * buffer, UInt32 address, CDTrackInfoAddressType addressType, UInt16 * actualByteCount ); /* Added with 10.2 */ OSMetaClassDeclareReservedUsed ( IOSCSIMultimediaCommandsDevice, 4 ); virtual IOReturn PowerDownHandler ( void * refCon, UInt32 messageType, IOService * provider, void * messageArgument, vm_size_t argSize ); /* Added with 10.3.3 */ OSMetaClassDeclareReservedUsed ( IOSCSIMultimediaCommandsDevice, 5 ); protected: virtual void AsyncReadWriteCompletion ( SCSITaskIdentifier completedTask ); public: /* Added with 10.5 */ OSMetaClassDeclareReservedUsed ( IOSCSIMultimediaCommandsDevice, 6 ); virtual IOReturn ReadDiscStructure ( IOMemoryDescriptor * buffer, const UInt32 length, const UInt8 structureFormat, const UInt32 logicalBlockAddress, const UInt8 layer, const UInt8 agid, const UInt8 mediaType ); bool CheckForBDMediaType ( void ); bool READ_DISC_STRUCTURE ( SCSITaskIdentifier request, IOMemoryDescriptor * dataBuffer, SCSICmdField4Bit MEDIA_TYPE, SCSICmdField4Byte ADDRESS, SCSICmdField1Byte LAYER_NUMBER, SCSICmdField1Byte FORMAT, SCSICmdField2Byte ALLOCATION_LENGTH, SCSICmdField2Bit AGID, SCSICmdField1Byte CONTROL ); OSMetaClassDeclareReservedUsed ( IOSCSIMultimediaCommandsDevice, 7 ); virtual IOReturn ReserveTrack ( UInt8 reservationType, UInt8 reservationFormat, UInt64 ReservationParameter ); bool RESERVE_TRACK_V2 ( SCSITaskIdentifier request, SCSICmdField1Bit RMZ, SCSICmdField1Bit ARSV, SCSICmdField7Byte RESERVATION_PARAMETER, SCSICmdField1Byte CONTROL ); bool REPORT_KEY_V2 ( SCSITaskIdentifier request, IOMemoryDescriptor * dataBuffer, SCSICmdField4Byte LOGICAL_BLOCK_ADDRESS, SCSICmdField1Byte KEY_CLASS, SCSICmdField2Byte ALLOCATION_LENGTH, SCSICmdField2Bit AGID, SCSICmdField6Bit KEY_FORMAT, SCSICmdField1Byte CONTROL ) __attribute__ ((deprecated)); bool REPORT_KEY_V3 ( SCSITaskIdentifier request, IOMemoryDescriptor * dataBuffer, SCSICmdField4Byte LOGICAL_BLOCK_ADDRESS, SCSICmdField1Byte KEY_CLASS, SCSICmdField2Byte ALLOCATION_LENGTH, SCSICmdField1Byte BLOCK_COUNT, SCSICmdField2Bit AGID, SCSICmdField6Bit KEY_FORMAT, SCSICmdField1Byte CONTROL ); bool SEND_KEY_V2 ( SCSITaskIdentifier request, IOMemoryDescriptor * dataBuffer, SCSICmdField1Byte KEY_CLASS, SCSICmdField2Byte PARAMETER_LIST_LENGTH, SCSICmdField2Bit AGID, SCSICmdField6Bit KEY_FORMAT, SCSICmdField1Byte CONTROL ); protected: void SetPollingMode ( UInt32 newPollingMode ); public: /* 10.6.0 */ IOReturn RequestIdle ( void ); /* 10.12.0 */ virtual IOReturn ReportKey ( IOMemoryDescriptor * buffer, const DVDKeyClass keyClass, const UInt32 lba, const UInt8 blockCount, const UInt8 agid, const DVDKeyFormat keyFormat ); private: // Space reserved for future expansion. OSMetaClassDeclareReservedUnused ( IOSCSIMultimediaCommandsDevice, 9 ); OSMetaClassDeclareReservedUnused ( IOSCSIMultimediaCommandsDevice, 10 ); OSMetaClassDeclareReservedUnused ( IOSCSIMultimediaCommandsDevice, 11 ); OSMetaClassDeclareReservedUnused ( IOSCSIMultimediaCommandsDevice, 12 ); OSMetaClassDeclareReservedUnused ( IOSCSIMultimediaCommandsDevice, 13 ); OSMetaClassDeclareReservedUnused ( IOSCSIMultimediaCommandsDevice, 14 ); OSMetaClassDeclareReservedUnused ( IOSCSIMultimediaCommandsDevice, 15 ); OSMetaClassDeclareReservedUnused ( IOSCSIMultimediaCommandsDevice, 16 ); }; #endif /* defined(KERNEL) && defined(__cplusplus) */ #endif /* _IOKIT_IO_SCSI_MULTIMEDIA_COMMANDS_DEVICE_H_ */
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/scsi/SCSICmds_REPORT_LUNS_Definitions.h
/* * Copyright (c) 2004-2009 Apple Inc. All rights reserved. * * @APPLE_LICENSE_HEADER_START@ * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this * file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_LICENSE_HEADER_END@ */ #ifndef _IOKIT_SCSI_CMDS_REPORT_LUNS_DEFINITIONS_H_ #define _IOKIT_SCSI_CMDS_REPORT_LUNS_DEFINITIONS_H_ #if KERNEL #include <IOKit/IOTypes.h> #else #include <CoreFoundation/CoreFoundation.h> #endif /*! @header SCSI Request Sense Definitions @discussion This file contains all definitions for the data returned from the REPORT_LUNS (0xA0) command. */ /*! @struct SCSICmd_REPORT_LUNS_LUN_ENTRY @discussion This structure represents a single LUN entry in a LUN list returned via the REPORT_LUNS command. */ typedef struct SCSICmd_REPORT_LUNS_LUN_ENTRY { UInt16 FIRST_LEVEL_ADDRESSING; UInt16 SECOND_LEVEL_ADDRESSING; UInt16 THIRD_LEVEL_ADDRESSING; UInt16 FOURTH_LEVEL_ADDRESSING; } SCSICmd_REPORT_LUNS_LUN_ENTRY; /*! @constant kREPORT_LUNS_HeaderSize @discussion Size of the REPORT_LUNS header as defined in the SPC-3 specification. */ #define kREPORT_LUNS_HeaderSize 8 /*! @enum REPORT_LUNS addressing methods. @discussion REPORT_LUNS addressing methods described in SAM-2 documents. @constant kREPORT_LUNS_ADDRESS_METHOD_PERIPHERAL_DEVICE Peripheral Device Addressing Method. @constant kREPORT_LUNS_ADDRESS_DEVICE_TYPE_SPECIFIC Device Type Specific Addressing Method. @constant kREPORT_LUNS_ADDRESS_METHOD_LOGICAL_UNIT Logical Unit Specific Addressing Method. @constant kREPORT_LUNS_ADDRESS_METHOD_OFFSET Offset to the address method data. */ enum { kREPORT_LUNS_ADDRESS_METHOD_PERIPHERAL_DEVICE = 0, kREPORT_LUNS_ADDRESS_METHOD_FLAT_SPACE = 1, kREPORT_LUNS_ADDRESS_DEVICE_TYPE_SPECIFIC = kREPORT_LUNS_ADDRESS_METHOD_FLAT_SPACE, kREPORT_LUNS_ADDRESS_METHOD_LOGICAL_UNIT = 2, // Reserved [3] kREPORT_LUNS_ADDRESS_METHOD_OFFSET = 14 }; /*! @struct REPORT_LUNS_LOGICAL_UNIT_ADDRESSING @discussion This structure represents a LUN Addressing scheme. */ typedef struct REPORT_LUNS_LOGICAL_UNIT_ADDRESSING { #ifdef __LITTLE_ENDIAN__ UInt16 LUN : 5; UInt16 BUS_NUMBER : 3; UInt16 TARGET : 6; UInt16 reserved2 : 1; UInt16 reserved : 1; #else /* !__LITTLE_ENDIAN__ */ UInt16 reserved : 1; UInt16 reserved2 : 1; UInt16 TARGET : 6; UInt16 BUS_NUMBER : 3; UInt16 LUN : 5; #endif /* !__LITTLE_ENDIAN__ */ } REPORT_LUNS_LOGICAL_UNIT_ADDRESSING; /*! @struct REPORT_LUNS_PERIPHERAL_DEVICE_ADDRESSING @discussion This structure represents a Peripheral Device Addressing scheme. */ typedef struct REPORT_LUNS_PERIPHERAL_DEVICE_ADDRESSING { #ifdef __LITTLE_ENDIAN__ UInt16 TARGET_LUN : 8; UInt16 BUS_IDENTIFIER : 6; UInt16 reserved2 : 1; UInt16 reserved : 1; #else /* !__LITTLE_ENDIAN__ */ UInt16 reserved : 1; UInt16 reserved2 : 1; UInt16 BUS_IDENTIFIER : 6; UInt16 TARGET_LUN : 8; #endif /* !__LITTLE_ENDIAN__ */ } REPORT_LUNS_PERIPHERAL_DEVICE_ADDRESSING; /*! @struct SCSICmd_REPORT_LUNS_Header @discussion This structure defines the format of the data that is returned for the REPORT_LUNS command. */ typedef struct SCSICmd_REPORT_LUNS_Header { UInt32 LUN_LIST_LENGTH; // LUN list length in bytes. UInt32 RESERVED; SCSICmd_REPORT_LUNS_LUN_ENTRY LUN[1]; // Variable length list. Must have at least LUN 0 if } SCSICmd_REPORT_LUNS_Header; // Target supports REPORT_LUNS command. #endif /* _IOKIT_SCSI_CMDS_REPORT_LUNS_DEFINITIONS_H_ */
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/scsi/SCSITask.h
/* * Copyright (c) 1998-2009 Apple Inc. All rights reserved. * * @APPLE_LICENSE_HEADER_START@ * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this * file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_LICENSE_HEADER_END@ */ #ifndef _IOKIT_SCSI_TASK_H_ #define _IOKIT_SCSI_TASK_H_ #include <TargetConditionals.h> #if TARGET_OS_DRIVERKIT typedef uint8_t UInt8; typedef uint64_t UInt64; #else #if KERNEL #include <IOKit/IOTypes.h> #else #include <CoreFoundation/CoreFoundation.h> #endif #endif /*! @header SCSITask SCSITask typedefs and constants used inside the kernel and user space. Note that the SCSITaskIdentifier is an opaque object and that directly casting the SCSITaskIdentifier to any other type is discouraged. The SCSITask implementation changes when necessary to accomodate architectural changes, performance improvements, and bug fixes. Device and protocol layer drivers that need to access information contained in a SCSITask should use the appropriate accessor methods in IOSCSIPrimaryCommandsDevice.h or IOSCSIProtocolServices.h */ /*! @typedef SCSIDeviceIdentifier @abstract 64-bit number to represent a SCSI Device. @discussion If the identifier can either be that of an initiator or a target, SCSIDeviceIdentifier should be used. */ typedef UInt64 SCSIDeviceIdentifier; /*! @typedef SCSITargetIdentifier @abstract 64-bit number to represent a SCSI Target Device. @discussion If the identifier is for a target only and not an initiator, then SCSITargetIdentifier should be used. */ typedef SCSIDeviceIdentifier SCSITargetIdentifier; /*! @typedef SCSIInitiatorIdentifier @abstract 64-bit number to represent a SCSI Initiator Device. @discussion If the identifier is for an initiator only and not a target, then SCSIInitiatorIdentifier should be used. */ typedef SCSIDeviceIdentifier SCSIInitiatorIdentifier; /*! @typedef SCSILogicalUnitBytes[8] @abstract 8-Byte array to represent LUN information @discussion The SCSI Primary Commands specification treats the 64-bits of LUN information as 4 2-byte structures. Use of the 64-bit SCSILogicalUnitNumber is now deprecated. Since it was not defined on Mac OS X how the 64-bits were encoded for hierarchical units and all usage was simply as a 64-bit number, changing the encoding scheme now would result in non-binary compatible code. New APIs have been added to retrieve the LUN bytes from the SCSITask and set them in the SCSITask. */ typedef UInt8 SCSILogicalUnitBytes[8]; typedef UInt64 SCSILogicalUnitNumber; // DEPRECATED /*! @typedef SCSITaggedTaskIdentifier @abstract 64-bit number to represent a unique task identifier. @discussion The Tagged Task Identifier is used when a Task has a Task Attribute other than SIMPLE. The SCSI Application Layer client that controls the Logical Unit for which a Task is intended is required to guarantee that the Task Tag Identifier is unique. Zero cannot be used a a Tag value as this is used to when a Tagged Task Identifier value is needed for a Task with a SIMPLE attribute. */ typedef UInt64 SCSITaggedTaskIdentifier; /*! @enum Untagged Task Identifier @discussion The Untagged Task Identifier is used to indicate no unique tag is associated with the Task. @constant kSCSIUntaggedTaskIdentifier This value means the task is untagged. */ enum { kSCSIUntaggedTaskIdentifier = 0 }; /*! @typedef SCSITaskAttribute @abstract Attributes for task delivery. @discussion The Task Attribute defines how this task should be managed when determing order for queueing and submission to the appropriate device server. The Task Attribute is set by the SCSI Application Layer and cannot be modified by the SCSI Protocol Layer. @constant kSCSITask_SIMPLE The task has a simple attribute. @constant kSCSITask_ORDERED The task has an ordered attribute. @constant kSCSITask_HEAD_OF_QUEUE The task has a head-of-queue attribute. @constant kSCSITask_ACA The task has an auto-contingent-allegiance attribute. */ typedef enum SCSITaskAttribute { kSCSITask_SIMPLE = 0, kSCSITask_ORDERED = 1, kSCSITask_HEAD_OF_QUEUE = 2, kSCSITask_ACA = 3 } SCSITaskAttribute; /*! @typedef SCSITaskState @abstract Attributes for task state. @discussion The Task State represents the current state of the task. The state is set to NEW_TASK when the task is created. The SCSI Protocol Layer will then adjust the state as the task is queued and during execution. The SCSI Application Layer can examine the state to monitor the progress of a task. The Task State can only be modified by the SCSI Protocol Layer. The SCSI Application Layer can only read the state. @constant kSCSITaskState_NEW_TASK The task state is new task. @constant kSCSITaskState_ENABLED The task is enabled and queued. @constant kSCSITaskState_BLOCKED The task is blocked. @constant kSCSITaskState_DORMANT The task is dormant. @constant kSCSITaskState_ENDED The task is complete. */ typedef enum SCSITaskState { kSCSITaskState_NEW_TASK = 0, kSCSITaskState_ENABLED = 1, kSCSITaskState_BLOCKED = 2, kSCSITaskState_DORMANT = 3, kSCSITaskState_ENDED = 4 } SCSITaskState; /*! @typedef SCSIServiceResponse @abstract Attributes for task service response. @discussion The Service Response represents the execution status of a service request made to a Protocol Services Driver. The Service Response can only be modified by the SCSI Protocol Layer. The SCSI Application Layer can only read the state. */ typedef enum SCSIServiceResponse { /*! @constant kSCSIServiceResponse_Request_In_Process Not defined in SAM specification, but is a service response used for asynchronous commands that are not yet completed. */ kSCSIServiceResponse_Request_In_Process = 0, /*! @constant kSCSIServiceResponse_SERVICE_DELIVERY_OR_TARGET_FAILURE The service request failed because of a delivery or target failure. */ kSCSIServiceResponse_SERVICE_DELIVERY_OR_TARGET_FAILURE = 1, /*! @constant kSCSIServiceResponse_TASK_COMPLETE The task completed. */ kSCSIServiceResponse_TASK_COMPLETE = 2, /*! @constant kSCSIServiceResponse_LINK_COMMAND_COMPLETE The linked command completed. */ kSCSIServiceResponse_LINK_COMMAND_COMPLETE = 3, /*! @constant kSCSIServiceResponse_FUNCTION_COMPLETE The task management function completed. */ kSCSIServiceResponse_FUNCTION_COMPLETE = 4, /*! @constant kSCSIServiceResponse_FUNCTION_REJECTED The task management function was rejected. */ kSCSIServiceResponse_FUNCTION_REJECTED = 5 } SCSIServiceResponse; /*! @typedef SCSITaskStatus @abstract Attributes for task status. @discussion The Task Status represents the completion status of the task which provides the SCSI Application Layer with additional information about how to procede in handling a completed task. The SCSI Architecture Model specification only defines task status values for when a task completes with a service response of either TASK_COMPLETED or LINK_COMMAND_COMPLETE. Since additional information will aid in error recovery when a task fails to be completed by a device due to a service response of kSCSIServiceResponse_SERVICE_DELIVERY_OR_TARGET_FAILURE, additional values have been defined that can be returned by the SCSI Protocol Layer to inform the SCSI Application Layer of the cause of the delivery failure. The Task Status can only be modified by the SCSI Protocol Layer. The SCSI Application Layer can only read the status */ typedef enum SCSITaskStatus { /*! @constant kSCSITaskStatus_GOOD The task completed with a status of GOOD. */ kSCSITaskStatus_GOOD = 0x00, /*! @constant kSCSITaskStatus_CHECK_CONDITION The task completed with a status of CHECK_CONDITION. Additional information about the condition should be available in the sense data. */ kSCSITaskStatus_CHECK_CONDITION = 0x02, /*! @constant kSCSITaskStatus_CONDITION_MET The task completed with a status of CONDITION_MET. */ kSCSITaskStatus_CONDITION_MET = 0x04, /*! @constant kSCSITaskStatus_BUSY The task completed with a status of BUSY. The device server might need time to process a request and a delay may be required. */ kSCSITaskStatus_BUSY = 0x08, /*! @constant kSCSITaskStatus_INTERMEDIATE The task completed with a status of INTERMEDIATE. */ kSCSITaskStatus_INTERMEDIATE = 0x10, /*! @constant kSCSITaskStatus_INTERMEDIATE_CONDITION_MET The task completed with a status of INTERMEDIATE_CONDITION_MET. */ kSCSITaskStatus_INTERMEDIATE_CONDITION_MET = 0x14, /*! @constant kSCSITaskStatus_RESERVATION_CONFLICT The task completed with a status of RESERVATION_CONFLICT. */ kSCSITaskStatus_RESERVATION_CONFLICT = 0x18, /*! @constant kSCSITaskStatus_TASK_SET_FULL The task completed with a status of TASK_SET_FULL. The device server may need to complete a task before the initiator sends another. */ kSCSITaskStatus_TASK_SET_FULL = 0x28, /*! @constant kSCSITaskStatus_ACA_ACTIVE The task completed with a status of ACA_ACTIVE. The device server may need the initiator to clear the Auto-Contingent Allegiance condition before it will respond to new commands. */ kSCSITaskStatus_ACA_ACTIVE = 0x30, /*! @constant kSCSITaskStatus_TaskTimeoutOccurred If a task is aborted by the SCSI Protocol Layer due to it exceeding the timeout value specified by the task, the task status shall be set to kSCSITaskStatus_TaskTimeoutOccurred. */ kSCSITaskStatus_TaskTimeoutOccurred = 0x01, /*! @constant kSCSITaskStatus_ProtocolTimeoutOccurred If a task is aborted by the SCSI Protocol Layer due to it exceeding a timeout value specified by the support for the protocol or a related specification, the task status shall be set to kSCSITaskStatus_ProtocolTimeoutOccurred. */ kSCSITaskStatus_ProtocolTimeoutOccurred = 0x02, /*! @constant kSCSITaskStatus_DeviceNotResponding If a task is unable to be delivered due to a failure of the device not accepting the task or the device acknowledging the attempt to send it the device the task status shall be set to kSCSITaskStatus_DeviceNotResponding. This will allow the SCSI Application driver to perform the necessary steps to try to recover the device. This shall only be reported after the SCSI Protocol Layer driver has attempted all protocol specific attempts to recover the device. */ kSCSITaskStatus_DeviceNotResponding = 0x03, /*! @constant kSCSITaskStatus_DeviceNotPresent If the task is unable to be delivered because the device has been detached, the task status shall be set to kSCSITaskStatus_DeviceNotPresent. This will allow the SCSI Application Layer to halt the sending of tasks to the device and, if supported, perform any device failover or system cleanup. */ kSCSITaskStatus_DeviceNotPresent = 0x04, /*! @constant kSCSITaskStatus_DeliveryFailure If the task is unable to be delivered to the device due to a failure in the SCSI Protocol Layer, such as a bus reset or communications error, but the device is is known to be functioning properly, the task status shall be set to kSCSITaskStatus_DeliveryFailure. This can also be reported if the task could not be delivered due to a protocol error that has since been corrected. */ kSCSITaskStatus_DeliveryFailure = 0x05, /*! @constant kSCSITaskStatus_No_Status This status is not defined by the SCSI specifications, but is here to provide a status that can be returned in cases where there is not status available from the device or protocol, for example, when the service response is neither TASK_COMPLETED nor LINK_COMMAND_COMPLETE or when the service response is SERVICE_DELIVERY_OR_TARGET_FAILURE and the reason for failure could not be determined. */ kSCSITaskStatus_No_Status = 0xFF } SCSITaskStatus; /*! @enum Command Descriptor Block Size @discussion Command Descriptor Block Size constants. */ enum { /*! @constant kSCSICDBSize_Maximum This is the largest size a Command Descriptor Block can be as specified in SPC-2. */ kSCSICDBSize_Maximum = 16, /*! @constant kSCSICDBSize_6Byte Use this for a 6-byte CDB. */ kSCSICDBSize_6Byte = 6, /*! @constant kSCSICDBSize_10Byte Use this for a 10-byte CDB. */ kSCSICDBSize_10Byte = 10, /*! @constant kSCSICDBSize_12Byte Use this for a 12-byte CDB. */ kSCSICDBSize_12Byte = 12, /*! @constant kSCSICDBSize_16Byte Use this for a 16-byte CDB. */ kSCSICDBSize_16Byte = 16 }; typedef UInt8 SCSICommandDescriptorBlock[kSCSICDBSize_Maximum]; /*! @enum Data Transfer Direction @discussion DataTransferDirection constants. */ enum { /*! @constant kSCSIDataTransfer_NoDataTransfer Use this for tasks that transfer no data. */ kSCSIDataTransfer_NoDataTransfer = 0x00, /*! @constant kSCSIDataTransfer_FromInitiatorToTarget Use this for tasks that transfer data from the initiator to the target. */ kSCSIDataTransfer_FromInitiatorToTarget = 0x01, /*! @constant kSCSIDataTransfer_FromTargetToInitiator Use this for tasks that transfer data from the target to the initiator. */ kSCSIDataTransfer_FromTargetToInitiator = 0x02 }; /* Libkern includes */ #if defined(KERNEL) && defined(__cplusplus) #if TARGET_OS_DRIVERKIT #include <DriverKit/OSObject.h> #else #include <libkern/c++/OSObject.h> #endif /*! @enum SCSITaskMode @discussion The SCSI Task mode is used by the SCSI Protocol Layer to indicate what mode the task is executing. */ typedef enum SCSITaskMode { kSCSITaskMode_CommandExecution = 1, kSCSITaskMode_Autosense = 2 } SCSITaskMode; /*! @typedef SCSITaskIdentifier @discussion This is an opaque object that represents a task. This is used so that drivers for both the SCSI Protocol Layer and the SCSI Application Layer cannot modify the SCSITask object directly but must instead use the inherited methods to do so. This allows the implementation of SCSITask to change without directly impacting device and protocol layer drivers. In addition, it prevents changing of properties that are not allowed to be changed by a given layer. */ typedef OSObject * SCSITaskIdentifier; /*! @typedef SCSITaskCompletion @discussion This is the typedef for completion routines that work with SCSITaskIdentifiers. */ typedef void ( *SCSITaskCompletion )( SCSITaskIdentifier completedTask ); #endif /* defined(KERNEL) && defined(__cplusplus) */ #endif /* _IOKIT_SCSI_TASK_H_ */
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/scsi/SCSITaskLib.h
/* * Copyright (c) 2001-2009 Apple Inc. All rights reserved. * * @APPLE_LICENSE_HEADER_START@ * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this * file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_LICENSE_HEADER_END@ */ #ifndef __SCSI_TASK_LIB_H__ #define __SCSI_TASK_LIB_H__ #include <IOKit/scsi/SCSITask.h> #include <IOKit/scsi/SCSICommandDefinitions.h> #include <IOKit/scsi/SCSICmds_INQUIRY_Definitions.h> #include <IOKit/scsi/SCSICmds_REQUEST_SENSE_Defs.h> #if !KERNEL #include <CoreFoundation/CFPlugIn.h> #if COREFOUNDATION_CFPLUGINCOM_SEPARATE #include <CoreFoundation/CFPlugInCOM.h> #endif #include <IOKit/IOReturn.h> #include <IOKit/IOTypes.h> #include <IOKit/IOCFPlugIn.h> #ifdef __cplusplus extern "C" { #endif /*! @header SCSITaskLib SCSITaskLib implements non-kernel task access to specific IOKit object types, namely any SCSI Peripheral Device for which there isn't an in-kernel driver and for authoring devices such as CD-R/W and DVD-R/W drives. */ // 7D66678E-08A2-11D5-A1B8-0030657D052A /*! @defined kIOSCSITaskDeviceUserClientTypeID @discussion Factory ID for creating an SCSITask Device User Client. */ #define kIOSCSITaskDeviceUserClientTypeID CFUUIDGetConstantUUIDWithBytes(NULL, \ 0x7D, 0x66, 0x67, 0x8E, 0x08, 0xA2, 0x11, 0xD5, \ 0xA1, 0xB8, 0x00, 0x30, 0x65, 0x7D, 0x05, 0x2A) // 97ABCF2C-23CC-11D5-A0E8-003065704866 /*! @defined kIOMMCDeviceUserClientTypeID @discussion Factory ID for creating an MMC Device User Client. */ #define kIOMMCDeviceUserClientTypeID \ CFUUIDGetConstantUUIDWithBytes(NULL, \ 0x97, 0xAB, 0xCF, 0x2C, 0x23, 0xCC, 0x11, 0xD5, \ 0xA0, 0xE8, 0x00, 0x30, 0x65, 0x70, 0x48, 0x66) // 63326D72-08A2-11D5-865F-0030657D052A /*! @defined kIOSCSITaskLibFactoryID @discussion UUID for the SCSITaskLib Factory. */ #define kIOSCSITaskLibFactoryID CFUUIDGetConstantUUIDWithBytes(NULL, \ 0x63, 0x32, 0x6D, 0x72, 0x08, 0xA2, 0x11, 0xD5, \ 0x86, 0x5F, 0x00, 0x30, 0x65, 0x7D, 0x05, 0x2A) //0B85B63C-462E-11D5-A9D6-003065704866 /*! @defined kIOSCSITaskInterfaceID @discussion InterfaceID for SCSITaskInterface. */ #define kIOSCSITaskInterfaceID CFUUIDGetConstantUUIDWithBytes(NULL, \ 0x0B, 0x85, 0xB6, 0x3C, 0x46, 0x2E, 0x11, 0xD5, \ 0xA9, 0xD6, 0x00, 0x30, 0x65, 0x70, 0x48, 0x66) // 1BBC4132-08A5-11D5-90ED-0030657D052A /*! @defined kIOSCSITaskDeviceInterfaceID @discussion InterfaceID for SCSITaskDeviceInterface. */ #define kIOSCSITaskDeviceInterfaceID \ CFUUIDGetConstantUUIDWithBytes(NULL, \ 0x1B, 0xBC, 0x41, 0x32, 0x08, 0xA5, 0x11, 0xD5, \ 0x90, 0xED, 0x00, 0x30, 0x65, 0x7D, 0x05, 0x2A) // 1F651106-23CC-11D5-BBDB-003065704866 /*! @defined kIOMMCDeviceInterfaceID @discussion InterfaceID for MMCDeviceInterface. */ #define kIOMMCDeviceInterfaceID \ CFUUIDGetConstantUUIDWithBytes(NULL, \ 0x1F, 0x65, 0x11, 0x06, 0x23, 0xCC, 0x11, 0xD5, \ 0xBB, 0xDB, 0x00, 0x30, 0x65, 0x70, 0x48, 0x66) // The following UUID constants are deprecated because of possible name-space collisions // Eventually this switch will be set to 0 and then removed entirely. #define OLD_UUIDS 1 #if OLD_UUIDS #define kSCSITaskDeviceInterfaceID kIOSCSITaskDeviceInterfaceID #define kMMCDeviceInterfaceID kIOMMCDeviceInterfaceID #define kSCSITaskInterfaceID kIOSCSITaskInterfaceID #define kSCSITaskDeviceUserClientTypeID kIOSCSITaskDeviceUserClientTypeID #define kMMCDeviceUserClientTypeID kIOMMCDeviceUserClientTypeID #define kSCSITaskLibFactoryID kIOSCSITaskLibFactoryID #endif /* OLD_UUIDS */ #endif /* !KERNEL */ /*! @defined kIOPropertySCSITaskUserClientInstanceGUID @discussion IORegistry property for the SCSITaskUserClient GUID. This GUID helps uniquely identify and track SCSITask enabled devices */ #define kIOPropertySCSITaskUserClientInstanceGUID "SCSITaskUserClient GUID" /*! @defined kIOPropertySCSITaskDeviceCategory @discussion IORegistry property for the SCSITaskUserClient. This category identifies which type of device and interface to the device is used in conjunction with the SCSITaskUserClient. */ #define kIOPropertySCSITaskDeviceCategory "SCSITaskDeviceCategory" /*! @defined kIOPropertySCSITaskUserClientDevice @discussion IORegistry property for the SCSI Task User Client. This property identifies an SCSITask enabled device. */ #define kIOPropertySCSITaskUserClientDevice "SCSITaskUserClientDevice" /*! @defined kIOPropertySCSITaskAuthoringDevice @discussion IORegistry property for the SCSI Task User Client. This property identifies an SCSITask enabled device capable of authoring. */ #define kIOPropertySCSITaskAuthoringDevice "SCSITaskAuthoringDevice" /*! @enum MMCDeviceTrayState @abstract Used to identify the state of an MMCDevice's tray (if applicable). @discussion Used to identify the state of an MMCDevice's tray (if applicable). @constant kMMCDeviceTrayClosed This value means the tray is closed. @constant kMMCDeviceTrayOpen This value means the tray is open. */ enum { kMMCDeviceTrayClosed = 0, kMMCDeviceTrayOpen = 1, kMMCDeviceTrayMask = 0x1 }; #if defined(__LP64__) typedef IOAddressRange SCSITaskSGElement; #else typedef IOVirtualRange SCSITaskSGElement; #endif #if !KERNEL /*! @typedef SCSITaskCallbackFunction @abstract Asynchronous callback routine definition. @discussion Asynchronous callback routine definition. Any function which is used as a callback routine for SCSITasks must conform to this function definition. @param serviceResponse An SCSIServiceResponse returned by the protocol transport. @param taskStatus An SCSITaskStatus to indicate the task's status @param bytesTransferred A total byte count of bytes transferred. @param refCon The refCon passed when the task was executed. */ typedef void ( *SCSITaskCallbackFunction ) ( SCSIServiceResponse serviceResponse, SCSITaskStatus taskStatus, UInt64 bytesTransferred, void * refCon ); /*! @class SCSITaskInterface @abstract Basic interface for a SCSITask. @discussion After rendezvous with a SCSITask Device in the IORegistry you can create an instance of this interface using the CreateSCSITask method in the SCSITaskDeviceInterface. Once you have this interface, or one of its subclasses, you can manipulate SCSITasks to send to the device. */ typedef struct SCSITaskInterface { IUNKNOWN_C_GUTS; /*! Interface version */ UInt16 version; /*! Interface revision */ UInt16 revision; /*! @function IsTaskActive @abstract Method to find out if the task is active or not. @discussion Method to find out if the task is active or not. The task is considered "active" if the SCSITaskState is not kSCSITaskState_NEW nor kSCSITaskState_ENDED. @param task Pointer to an instance of an SCSITaskInterface. @result Returns 0 if the task is not active, non-zero if it is active. */ Boolean ( *IsTaskActive ) ( void * task ); /*! @function SetTaskAttribute @abstract Method to set the task's attribute. @discussion This method can be used to set the SCSITask's SCSITaskAttribute field. Valid values are defined in SCSITask.h @param task Pointer to an instance of an SCSITaskInterface. @param inAttribute The new attribute value to be stored in the SCSITask. @result Returns kIOReturnSuccess or kIOReturnError. */ IOReturn ( *SetTaskAttribute ) ( void * task, SCSITaskAttribute inAttribute ); /*! @function GetTaskAttribute @abstract Method to get the task's attribute. @discussion This method can be used to get the SCSITasks' SCSITaskAttribute field. Valid values are defined in SCSITask.h @param task Pointer to an instance of an SCSITaskInterface. @param outAttribute Pointer to the attribute value stored in the SCSITask. @result Returns kIOReturnSuccess or kIOReturnError. */ IOReturn ( *GetTaskAttribute ) ( void * task, SCSITaskAttribute * outAttribute ); /*! @function SetCommandDescriptorBlock @abstract Method to set the task's SCSICommandDescriptorBlock. @discussion This method can be used to set the SCSITasks' SCSICommandDescriptorBlock. @param task Pointer to an instance of an SCSITaskInterface. @param inCDB Pointer to an array of values to be stored in the SCSITask's SCSICommandDescriptorBlock. @param inSize The size of the array inCDB. Valid values are 6, 10, 12, and 16 which have enums defined in SCSITask.h. @result Returns kIOReturnSuccess or kIOReturnError. */ IOReturn ( *SetCommandDescriptorBlock ) ( void * task, UInt8 * inCDB, UInt8 inSize ); /*! @function GetCommandDescriptorBlockSize @abstract Method to get the task's SCSICommandDescriptorBlock size. @discussion This method can be used to get the size of the SCSITask's SCSICommandDescriptorBlock. @param task Pointer to an instance of an SCSITaskInterface. @result UInt8 which is the size of the SCSICommandDescriptorBlock. Valid values are 6, 10, 12, and 16 which have enums defined in SCSITask.h */ UInt8 ( *GetCommandDescriptorBlockSize ) ( void * task ); /*! @function GetCommandDescriptorBlock @abstract Method to get the task's SCSICommandDescriptorBlock. @discussion This method can be used to get the SCSITasks' SCSICommandDescriptorBlock. @param task Pointer to an instance of an SCSITaskInterface. @param outCDB Pointer to an array the size of the SCSICommandDescriptorBlock in question. Clients should call GetCommandDescriptorBlockSize first to find out how large an array should be passed in. @result Returns kIOReturnSucces or kIOReturnError. */ IOReturn ( *GetCommandDescriptorBlock ) ( void * task, UInt8 * outCDB ); /*! @function SetScatterGatherEntries @abstract Method to set the task's scatter-gather list entries. @discussion This method can be used to set the SCSITask's scatter-gather list entries. Scatter-gather lists are represented as an array of SCSITaskSGElements. The SCSITaskSGElement structure has two elements, the address of the buffer and the length of the buffer. @param task Pointer to an instance of an SCSITaskInterface. @param inScatterGatherList Pointer to an array of SCSITaskSGElements. @param inScatterGatherEntries The size of the inScatterGatherList array. @param inTransferCount The TOTAL amount of data to transfer. The length of all the entries in the scatter-gather list should at least add up to the amount in inTransferCount. @param inTransferDirection The transfer direction as defined in SCSITask.h. Valid values are kSCSIDataTransfer_NoDataTransfer, kSCSIDataTransfer_FromTargetToInitiator, and kSCSIDataTransfer_FromInitiatorToTarget. @result Returns kIOReturnSucces or kIOReturnError. */ IOReturn ( *SetScatterGatherEntries ) ( void * task, SCSITaskSGElement * inScatterGatherList, UInt8 inScatterGatherEntries, UInt64 inTransferCount, UInt8 inTransferDirection ); /*! @function SetTimeoutDuration @abstract Method to set the timeout duration for the SCSITask. @discussion This method can be used to set the timeout duration for the SCSITask. The timeout duration is counted in milliseconds. A value of zero is equivalent to "Wait Forever", but on some buses, this isn't possible, so ULONG_MAX is used. @param task Pointer to an instance of an SCSITaskInterface. @param inTimeoutDurationMS UInt32 representing the timeout in milliseconds. @result Returns kIOReturnSucces or kIOReturnError. */ IOReturn ( *SetTimeoutDuration ) ( void * task, UInt32 inTimeoutDurationMS ); /*! @function GetTimeoutDuration @abstract Method to get the timeout duration for the SCSITask. @discussion This method can be used to get the timeout duration for the SCSITask. The timeout duration is counted in milliseconds. @param task Pointer to an instance of an SCSITaskInterface. @result Returns a value between zero and ULONG_MAX. */ UInt32 ( *GetTimeoutDuration ) ( void * task ); /*! @function SetTaskCompletionCallback @abstract Method to set the asynchronous completion routine for the SCSITask. @discussion This method can be used to set the asynchronous completion routine for the SCSITask. @param task Pointer to an instance of an SCSITaskInterface. @param callback SCSITaskCallbackFunction to be called upon completion of the SCSITask. @param refCon A value to be returned to the caller upon completion of the routine. This field is not used by the SCSITaskInterface. @result Returns kIOReturnSuccess, kIOReturnError, or kIOReturnNotPermitted if the client has not called AddCallbackDispatcherToRunLoop on the SCSITaskDeviceInterface. */ IOReturn ( *SetTaskCompletionCallback ) ( void * task, SCSITaskCallbackFunction callback, void * refCon ); /*! @function ExecuteTaskAsync @abstract Method to execute the SCSITask asynchronously. @discussion This method can be used to execute the SCSITask asynchronously. @param task Pointer to an instance of an SCSITaskInterface. @result Returns a valid IOReturn code such as kIOReturnSuccess, kIOReturnError, kIOReturnVMError, kIOReturnCannotWire, etc. It will return kIOReturnNotPermitted if the client has not called AddCallbackDispatcherToRunLoop on the SCSITaskDeviceInterface. NOTE: IOReturn is defined as kern_return_t and as such, you may get errors back that do not fall under the IOKit subsystem error domain (sys_iokit) defined in IOReturn.h. */ IOReturn ( *ExecuteTaskAsync ) ( void * task ); /*! @function ExecuteTaskSync @abstract Method to execute the SCSITask synchronously. @discussion This method can be used to execute the SCSITask synchronously. @param task Pointer to an instance of an SCSITaskInterface. @param senseDataBuffer Pointer to a buffer for REQUEST_SENSE data. May be NULL if caller does not wish to have sense data returned. If caller has previously called SetAutoSenseDataBuffer(), this parameter is ignored. @param outStatus Pointer to an SCSITaskStatus. May be NULL if caller does not wish to have task status returned. @param realizedTransferCount Pointer to an UInt64 which reflects how much data was actually transferred. May be NULL if caller does not wish to know how many bytes were transferred. @result Returns a valid IOReturn code such as kIOReturnSuccess, kIOReturnError, kIOReturnVMError, kIOReturnCannotWire, etc. NOTE: IOReturn is defined as kern_return_t and as such, you may get errors back that do not fall under the IOKit subsystem error domain (sys_iokit) defined in IOReturn.h. */ IOReturn ( *ExecuteTaskSync ) ( void * task, SCSI_Sense_Data * senseDataBuffer, SCSITaskStatus * outStatus, UInt64 * realizedTransferCount ); /*! @function AbortTask @abstract Method to abort the SCSITask. @discussion This method can be used to abort an SCSITask which is already in progress. @param task Pointer to an instance of an SCSITaskInterface. @result Returns kIOReturnSuccess, kIOReturnUnsupported or kIOReturnError. */ IOReturn ( *AbortTask ) ( void * task ); /*! @function GetSCSIServiceResponse @abstract Method to get the SCSIServiceResponse from the SCSITask. @discussion This method can be used to get the SCSIServiceResponse from the SCSITask. @param task Pointer to an instance of an SCSITaskInterface. @param outServiceResponse Pointer to an SCSIServiceResponse. @result Returns kIOReturnSuccess or kIOReturnError. */ IOReturn ( *GetSCSIServiceResponse ) ( void * task, SCSIServiceResponse * outServiceResponse ); /*! @function GetTaskState @abstract Method to get the SCSITaskState from the SCSITask. @discussion This method can be used to get the SCSITaskState from the SCSITask. @param task Pointer to an instance of an SCSITaskInterface. @param outState Pointer to an SCSITaskState. @result Returns kIOReturnSuccess or kIOReturnError. */ IOReturn ( *GetTaskState ) ( void * task, SCSITaskState * outState ); /*! @function GetTaskStatus @abstract Method to get the SCSITaskStatus from the SCSITask. @discussion This method can be used to get the SCSITaskStatus from the SCSITask. @param task Pointer to an instance of an SCSITaskInterface. @param outStatus Pointer to an SCSITaskStatus. @result Returns kIOReturnSuccess or kIOReturnError. */ IOReturn ( *GetTaskStatus ) ( void * task, SCSITaskStatus * outStatus ); /*! @function GetRealizedDataTransferCount @abstract Method to get the actual transfer count in bytes from the SCSITask. @discussion This method can be used to get the actual transfer count in bytes from the SCSITask. @param task Pointer to an instance of an SCSITaskInterface. @result Returns a UInt64 value of bytes transferred. */ UInt64 ( *GetRealizedDataTransferCount ) ( void * task ); /*! @function GetAutoSenseData @abstract Method to get the auto-sense data from the SCSITask. @discussion This method can be used to get the auto-sense data from the SCSITask. @param task Pointer to an instance of an SCSITaskInterface. @param senseDataBuffer Pointer to a buffer the size of the SCSI_Sense_Data structure. If caller has previously called SetAutoSenseDataBuffer(), this routine will return an error. @result Returns kIOReturnSuccess if sense data is valid, otherwise kIOReturnError. */ IOReturn ( *GetAutoSenseData ) ( void * task, SCSI_Sense_Data * senseDataBuffer ); /* Added in 10.2 */ /*! @function SetAutoSenseDataBuffer @abstract Method to set the auto-sense data for the SCSITask. @discussion This method can be used to set the auto-sense data buffer for the SCSITask. @param task Pointer to an instance of an SCSITaskInterface. @param senseDataBuffer Pointer to a buffer. May be be NULL if the caller wants to restrict the size to be less than the normal 18 bytes of sense data. @param senseDataLength Amount of sense data to retrieve. Zero is not a valid value. @result Returns kIOReturnSuccess if sense data buffer was set, otherwise kIOReturnError. */ IOReturn ( *SetAutoSenseDataBuffer ) ( void * task, SCSI_Sense_Data * senseDataBuffer, UInt8 senseDataLength ); /* Added in 10.6 */ /*! @function ResetForNewTask @abstract Method to reset the SCSITask to defaults. @discussion This method can be used to reset the SCSITask to defaults. @param task Pointer to an instance of an SCSITaskInterface. @result Returns kIOReturnSuccess if reset was successful, otherwise kIOReturnError. */ IOReturn ( *ResetForNewTask ) ( void * task ); } SCSITaskInterface; /*! @class SCSITaskDeviceInterface @abstract Basic interface for a SCSITask Device. @discussion After rendezvous with a SCSITask Device in the IORegistry you can create an instance of this interface as a proxy to the IOService. Once you have this interface, or one of its subclasses, you can create SCSITasks to send to the device. Use the CreateSCSITask method to create new SCSITask instances for this device. */ typedef struct SCSITaskDeviceInterface { IUNKNOWN_C_GUTS; /*! Interface version */ UInt16 version; /*! Interface revision */ UInt16 revision; /*! @function IsExclusiveAccessAvailable @abstract Method to find out if the device can be opened exclusively by the caller. @discussion Method to find out if the device can be opened exclusively by the caller. @param self Pointer to an instance of an SCSITaskDeviceInterface. @result Returns false if the device has been opened for exclusive access, otherwise true. */ Boolean ( *IsExclusiveAccessAvailable ) ( void * self ); /*! @function AddCallbackDispatcherToRunLoop @abstract Convenience method to add asynchronous callback mechanisms to the CFRunLoop of choice. @discussion Once a SCSITaskDeviceInterface is opened, the client may make synchronous or asynchronous requests to the device. This method creates and initializes a mach_port_t for receiving asynchronous callback notifications via the CFRunLoop mechanism. @param self Pointer to a SCSITaskDeviceInterface instance. @param cfRunLoopRef The CFRunLoop to which asynchronous callback notifications should be attached. @result Returns kIOReturnSuccess if successful, kIOReturnNoDevice if there is no connection to an IOService, or kIOReturnNoMemory if a mach port could not be allocated and initialized properly. */ IOReturn ( *AddCallbackDispatcherToRunLoop ) ( void * self, CFRunLoopRef cfRunLoopRef ); /*! @function RemoveCallbackDispatcherFromRunLoop @abstract Convenience method to remove asynchronous callback mechanisms from the CFRunLoop. @discussion Once a SCSITaskDeviceInterface is opened, the client may make synchronous or asynchronous requests to the device. This method removes the asynchronous notifications delivered via the CFRunLoop. This should be called only after calling AddCallbackDispatcherToRunLoop. @param self Pointer to a SCSITaskDeviceInterface instance. */ void ( *RemoveCallbackDispatcherFromRunLoop ) ( void * self ); /*! @function ObtainExclusiveAccess @abstract Method to obtain exclusive access to the device so that SCSITasks can be sent to it. @discussion Once a SCSITaskDeviceInterface is opened, the client may request exclusive access to the device. Once the client has successfully gained exclusive access, it becomes the Logical Unit Driver and all in-kernel Logical Unit Drivers are quiesced. @param self Pointer to a SCSITaskDeviceInterface instance. @result Returns kIOReturnSuccess if exclusive access was granted, else if media is still mounted it returns kIOReturnBusy. If another client already has exclusive access, kIOReturnExclusiveAccess is returned. */ IOReturn ( *ObtainExclusiveAccess ) ( void * self ); /*! @function ReleaseExclusiveAccess @abstract Method to release exclusive access to the device so that other clients can send commands to it. @discussion Once a SCSITaskDeviceInterface is opened, the client may request exclusive access to the device. Once the client has successfully gained exclusive access, it becomes the Logical Unit Driver and all in-kernel Logical Unit Drivers (if any are matched on the device) are quiesced. This method releases this access and unquiesces the in-kernel drivers (if any). @param self Pointer to a SCSITaskDeviceInterface instance. @result Returns kIOReturnSuccess if exclusive access was released, else some appropriate error. */ IOReturn ( *ReleaseExclusiveAccess ) ( void * self ); /*! @function CreateSCSITask @abstract Method to create SCSITasks. @discussion Once a SCSITaskDeviceInterface is opened, the client may request exclusive access to the device. Once the client has successfully gained exclusive access, it becomes the Logical Unit Driver. It then can use this method to allocate SCSITasks to be sent to the device. @param self Pointer to a SCSITaskDeviceInterface instance. @result Returns a handle to an instance of a SCSITaskInterface or NULL if one could not be allocated. */ SCSITaskInterface ** ( *CreateSCSITask )( void * self ); } SCSITaskDeviceInterface; /*! @class MMCDeviceInterface @abstract Basic interface for an MMC-2 Compliant Device. @discussion After rendezvous with a MMC-2 Compliant Device in the IORegistry you can create an instance of this interface as a proxy to the IOService. Once you have this interface, or one of its subclasses, you can issue some select MMC-2 calls to the device without getting exclusive access first. */ typedef struct MMCDeviceInterface { IUNKNOWN_C_GUTS; /*! Interface version */ UInt16 version; /*! Interface revision */ UInt16 revision; /*! @function Inquiry @abstract Issues an INQUIRY command to the device as defined in SPC-2. @discussion Once an MMCDeviceInterface is opened, the client may send this command to get inquiry data from the drive. @param self Pointer to an MMCDeviceInterface for one IOService. @param inquiryBuffer A pointer to a buffer the size of the SCSICmd_INQUIRY_StandardData struct found in SCSICmds_INQUIRY_Definitions.h. @param inqBufferSize The amount of INQUIRY data to ask the device for (some devices return less INQUIRY data than the size of SCSICmd_INQUIRY_StandardData and will need to be reset if more than that amount is specified). This value must be less than the size of SCSICmd_INQUIRY_StandardData. @param taskStatus Pointer to a SCSITaskStatus to get the status of the SCSITask which was executed. Valid SCSITaskStatus values are defined in SCSITask.h @param senseDataBuffer Pointer to a buffer the size of the SCSI_Sense_Data struct found in SCSICmds_REQUEST_SENSE_Defs.h. The sense data is only valid if the SCSITaskStatus is kSCSITaskStatus_CHECK_CONDITION. @result Returns kIOReturnSuccess if successful, kIOReturnNoDevice if there is no connection to an IOService, kIOReturnNoMemory if a SCSITask couldn't be created, or kIOReturnExclusiveAccess if the device is already opened for exclusive access by another client. */ IOReturn ( *Inquiry )( void * self, SCSICmd_INQUIRY_StandardData * inquiryBuffer, UInt32 inqBufferSize, SCSITaskStatus * taskStatus, SCSI_Sense_Data * senseDataBuffer ); /*! @function TestUnitReady @abstract Issues a TEST_UNIT_READY command to the device as defined in SPC-2. @discussion Once an MMCDeviceInterface is opened, the client may send this command to test if the drive is ready. @param self Pointer to an MMCDeviceInterface for one IOService. @param taskStatus Pointer to a SCSITaskStatus to get the status of the SCSITask which was executed. Valid SCSITaskStatus values are defined in SCSITask.h @param senseDataBuffer Pointer to a buffer the size of the SCSI_Sense_Data struct found in SCSICmds_REQUEST_SENSE_Defs.h. The sense data is only valid if the SCSITaskStatus is kSCSITaskStatus_CHECK_CONDITION. @result Returns kIOReturnSuccess if successful, kIOReturnNoDevice if there is no connection to an IOService, kIOReturnNoMemory if a SCSITask couldn't be created, or kIOReturnExclusiveAccess if the device is already opened for exclusive access by another client. */ IOReturn ( *TestUnitReady )( void * self, SCSITaskStatus * taskStatus, SCSI_Sense_Data * senseDataBuffer ); /* This version of GetPerformance is OBSOLETED by Mt. Fuji 5. Please use the newly * introduced API at the end of this struct */ /*! @function GetPerformance @abstract Issues a GET_PERFORMANCE command to the device as defined in MMC-2. @discussion Once an MMCDeviceInterface is opened, the client may send this command to get performance information from the device. @param self Pointer to an MMCDeviceInterface for one IOService. @param TOLERANCE The TOLERANCE field as described for the GET_PERFORMANCE command in MMC-2. @param WRITE The WRITE bit as described in MMC-2 for the GET_PERFORMANCE command. @param EXCEPT The EXCEPT field as described in MMC-2 for the GET_PERFORMANCE command. @param STARTING_LBA The STARTING_LBA field as described in MMC-2 for the GET_PERFORMANCE command. @param MAXIMUM_NUMBER_OF_DESCRIPTORS The MAXIMUM_NUMBER_OF_DESCRIPTORS field as described in MMC-2 for the GET_PERFORMANCE command. @param buffer Pointer to the buffer where the mode sense data should be placed. @param bufferSize Size of the buffer. @param taskStatus Pointer to a SCSITaskStatus to get the status of the SCSITask which was executed. Valid SCSITaskStatus values are defined in SCSITask.h @param senseDataBuffer Pointer to a buffer the size of the SCSI_Sense_Data struct found in SCSICmds_REQUEST_SENSE_Defs.h. The sense data is only valid if the SCSITaskStatus is kSCSITaskStatus_CHECK_CONDITION. @result Returns kIOReturnSuccess if successful, kIOReturnNoDevice if there is no connection to an IOService, kIOReturnNoMemory if a SCSITask couldn't be created, or kIOReturnExclusiveAccess if the device is already opened for exclusive access by another client. */ IOReturn ( *GetPerformance )( void * self, SCSICmdField2Bit TOLERANCE, SCSICmdField1Bit WRITE, SCSICmdField2Bit EXCEPT, SCSICmdField4Byte STARTING_LBA, SCSICmdField2Byte MAXIMUM_NUMBER_OF_DESCRIPTORS, void * buffer, SCSICmdField2Byte bufferSize, SCSITaskStatus * taskStatus, SCSI_Sense_Data * senseDataBuffer ); /*! @function GetConfiguration @abstract Issues a GET_CONFIGURATION command to the device as defined in MMC-2. @discussion Once an MMCDeviceInterface is opened, the client may send this command to get configuration information from the device. @param self Pointer to an MMCDeviceInterface for one IOService. @param RT The RT field as described for the GET_CONFIGURATION command in MMC-2. @param STARTING_FEATURE_NUMBER The STARTING_FEATURE_NUMBER field as described in MMC-2 for the GET_CONFIGURATION command. @param buffer Pointer to the buffer where the mode sense data should be placed. @param bufferSize Size of the buffer. @param taskStatus Pointer to a SCSITaskStatus to get the status of the SCSITask which was executed. Valid SCSITaskStatus values are defined in SCSITask.h @param senseDataBuffer Pointer to a buffer the size of the SCSI_Sense_Data struct found in SCSICmds_REQUEST_SENSE_Defs.h. The sense data is only valid if the SCSITaskStatus is kSCSITaskStatus_CHECK_CONDITION. @result Returns kIOReturnSuccess if successful, kIOReturnNoDevice if there is no connection to an IOService, kIOReturnNoMemory if a SCSITask couldn't be created, or kIOReturnExclusiveAccess if the device is already opened for exclusive access by another client. */ IOReturn ( *GetConfiguration )( void * self, SCSICmdField1Byte RT, SCSICmdField2Byte STARTING_FEATURE_NUMBER, void * buffer, SCSICmdField2Byte bufferSize, SCSITaskStatus * taskStatus, SCSI_Sense_Data * senseDataBuffer ); /*! @function ModeSense10 @abstract Issues a MODE_SENSE_10 command to the device as defined in SPC-2. @discussion Once an MMCDeviceInterface is opened, the client may send this command to get mode page information from the device. @param self Pointer to an MMCDeviceInterface for one IOService. @param LLBAA The LLBAA bit as defined in SPC-2 for the MODE_SENSE_10 command. @param DBD The DBD bit as defined in SPC-2 for the MODE_SENSE_10 command. @param PC The PC bits as defined in SPC-2 for the MODE_SENSE_10 command. @param PAGE_CODE The PAGE_CODE bits as defined in SPC-2 for the MODE_SENSE_10 command. @param buffer Pointer to the buffer where the mode sense data should be placed. @param bufferSize Size of the buffer. @param taskStatus Pointer to a SCSITaskStatus to get the status of the SCSITask which was executed. Valid SCSITaskStatus values are defined in SCSITask.h @param senseDataBuffer Pointer to a buffer the size of the SCSI_Sense_Data struct found in SCSICmds_REQUEST_SENSE_Defs.h. The sense data is only valid if the SCSITaskStatus is kSCSITaskStatus_CHECK_CONDITION. @result Returns kIOReturnSuccess if successful, kIOReturnNoDevice if there is no connection to an IOService, kIOReturnNoMemory if a SCSITask couldn't be created, or kIOReturnExclusiveAccess if the device is already opened for exclusive access by another client. */ IOReturn ( *ModeSense10 )( void * self, SCSICmdField1Bit LLBAA, SCSICmdField1Bit DBD, SCSICmdField2Bit PC, SCSICmdField6Bit PAGE_CODE, void * buffer, SCSICmdField2Byte bufferSize, SCSITaskStatus * taskStatus, SCSI_Sense_Data * senseDataBuffer ); /*! @function SetWriteParametersModePage @abstract Issues a MODE_SELECT command to the device as defined in SPC-2 with the Write Parameters Mode Page Code as defined in MMC-2. @discussion Once an MMCDeviceInterface is opened, the client may send this command to set the default values returned in a READ_DISC_INFORMATION call. @param buffer Pointer to buffer (including mode parameter header). @param taskStatus Pointer to a SCSITaskStatus to get the status of the SCSITask which was executed. Valid SCSITaskStatus values are defined in SCSITask.h @param senseDataBuffer Pointer to a buffer the size of the SCSI_Sense_Data struct found in SCSICmds_REQUEST_SENSE_Defs.h. The sense data is only valid if the SCSITaskStatus is kSCSITaskStatus_CHECK_CONDITION. @result Returns kIOReturnSuccess if successful, kIOReturnNoDevice if there is no connection to an IOService, kIOReturnNoMemory if a SCSITask couldn't be created, or kIOReturnExclusiveAccess if the device is already opened for exclusive access by another client. */ IOReturn ( *SetWriteParametersModePage )( void * self, void * buffer, SCSICmdField1Byte bufferSize, SCSITaskStatus * taskStatus, SCSI_Sense_Data * senseDataBuffer ); /*! @function GetTrayState @abstract Issues a GET_EVENT_STATUS_NOTIFICATION command to the device as defined in MMC-2. @discussion Once an MMCDeviceInterface is opened, the client may send this command to find out if the device's medium tray is open. @param self Pointer to an MMCDeviceInterface for one IOService. @param trayState Pointer to a UInt8 which will hold the tray state on completion of the routine. The tray state can be one of two values, kMMCDeviceTrayClosed or kMMCDeviceTrayOpen. @result Returns kIOReturnSuccess if successful, kIOReturnNoDevice if there is no connection to an IOService, or kIOReturnExclusiveAccess if the device is already opened for exclusive access by another client. */ IOReturn ( *GetTrayState )( void * self, UInt8 * trayState ); /*! @function SetTrayState @abstract Issues a START_STOP_UNIT command to the device as defined in SBC-3. @discussion Once an MMCDeviceInterface is opened and all volumes associated with that device's media have been unmounted, the client may send this command to eject the tray. @param self Pointer to an MMCDeviceInterface for one IOService. @param trayState A UInt8 describing which tray state is desired. The tray state can be one of two values, kMMCDeviceTrayClosed or kMMCDeviceTrayOpen. @result Returns kIOReturnSuccess if successful, kIOReturnNoDevice if there is no connection to an IOService, kIOReturnNotPermitted if media is inserted, or kIOReturnExclusiveAccess if the device is already opened for exclusive access by another client. */ IOReturn ( *SetTrayState )( void * self, UInt8 trayState ); /*! @function ReadTableOfContents @abstract Issues a READ_TOC_PMA_ATIP command to the device as defined in MMC-2/SFF-8020i. @discussion Once an MMCDeviceInterface is opened the client may send this command to read the table of contents from the media. @param self Pointer to an MMCDeviceInterface for one IOService. @param MSF The MSF bit as defined in MMC-2/SFF-8020i. @param FORMAT The FORMAT field as defined in MMC-2/SFF-8020i. @param TRACK_SESSION_NUMBER The TRACK_SESSION_NUMBER field as defined in MMC-2/SFF-8020i. @param buffer Pointer to the buffer to be used for this function. @param bufferSize The size of the data transfer requested. @param taskStatus Pointer to a SCSITaskStatus to get the status of the SCSITask which was executed. Valid SCSITaskStatus values are defined in SCSITask.h @param senseDataBuffer Pointer to a buffer the size of the SCSI_Sense_Data struct found in SCSICmds_REQUEST_SENSE_Defs.h. The sense data is only valid if the SCSITaskStatus is kSCSITaskStatus_CHECK_CONDITION. @result Returns kIOReturnSuccess if successful, kIOReturnNoDevice if there is no connection to an IOService, kIOReturnNoMemory if a SCSITask couldn't be created, or kIOReturnExclusiveAccess if the device is already opened for exclusive access by another client. */ IOReturn ( *ReadTableOfContents )( void * self, SCSICmdField1Bit MSF, SCSICmdField4Bit FORMAT, SCSICmdField1Byte TRACK_SESSION_NUMBER, void * buffer, SCSICmdField2Byte bufferSize, SCSITaskStatus * taskStatus, SCSI_Sense_Data * senseDataBuffer ); /*! @function ReadDiscInformation @abstract Issues a READ_DISC_INFORMATION command to the device as defined in MMC-2. @discussion Once an MMCDeviceInterface is opened the client may send this command to read information about the disc (CD-R/RW, (un)finalized, etc.. @param self Pointer to an MMCDeviceInterface for one IOService. @param buffer Pointer to the buffer to be used for this function. @param bufferSize The size of the data transfer requested. @param taskStatus Pointer to a SCSITaskStatus to get the status of the SCSITask which was executed. Valid SCSITaskStatus values are defined in SCSITask.h @param senseDataBuffer Pointer to a buffer the size of the SCSI_Sense_Data struct found in SCSICmds_REQUEST_SENSE_Defs.h. The sense data is only valid if the SCSITaskStatus is kSCSITaskStatus_CHECK_CONDITION. @result Returns kIOReturnSuccess if successful, kIOReturnNoDevice if there is no connection to an IOService, kIOReturnNoMemory if a SCSITask couldn't be created, or kIOReturnExclusiveAccess if the device is already opened for exclusive access by another client. */ IOReturn ( *ReadDiscInformation ) ( void * self, void * buffer, SCSICmdField2Byte bufferSize, SCSITaskStatus * taskStatus, SCSI_Sense_Data * senseDataBuffer ); /*! @function ReadTrackInformation @abstract Issues a READ_TRACK_INFORMATION command to the device as defined in MMC-2. @discussion Once an MMCDeviceInterface is opened the client may send this command to read information about selected tracks on the disc. @param self Pointer to an MMCDeviceInterface for one IOService. @param ADDRESS_NUMBER_TYPE The ADDRESS/NUMBER_TYPE field as defined in MMC-2. @param LOGICAL_BLOCK_ADDRESS_TRACK_SESSION_NUMBER The LOGICAL_BLOCK_ADDRESS/SESSION_NUMBER field as defined in MMC-2. @param buffer Pointer to the buffer to be used for this function. @param bufferSize The size of the data transfer requested. @param taskStatus Pointer to a SCSITaskStatus to get the status of the SCSITask which was executed. Valid SCSITaskStatus values are defined in SCSITask.h @param senseDataBuffer Pointer to a buffer the size of the SCSI_Sense_Data struct found in SCSICmds_REQUEST_SENSE_Defs.h. The sense data is only valid if the SCSITaskStatus is kSCSITaskStatus_CHECK_CONDITION. @result Returns kIOReturnSuccess if successful, kIOReturnNoDevice if there is no connection to an IOService, kIOReturnNoMemory if a SCSITask couldn't be created, or kIOReturnExclusiveAccess if the device is already opened for exclusive access by another client. */ IOReturn ( *ReadTrackInformation ) ( void * self, SCSICmdField2Bit ADDRESS_NUMBER_TYPE, SCSICmdField4Byte LOGICAL_BLOCK_ADDRESS_TRACK_SESSION_NUMBER, void * buffer, SCSICmdField2Byte bufferSize, SCSITaskStatus * taskStatus, SCSI_Sense_Data * senseDataBuffer ); /*! @function ReadDVDStructure @abstract Issues a READ_DVD_STRUCTURE command to the device as defined in MMC-2. @discussion Once an MMCDeviceInterface is opened the client may send this command to read information about DVD specific structures on the disc. @param self Pointer to an MMCDeviceInterface for one IOService. @param ADDRESS The ADDRESS field as defined in MMC-2. @param LAYER_NUMBER The LAYER_NUMBER field as defined in MMC-2. @param FORMAT The FORMAT field as defined in MMC-2. @param buffer Pointer to the buffer to be used for this function. @param bufferSize The size of the data transfer requested. @param taskStatus Pointer to a SCSITaskStatus to get the status of the SCSITask which was executed. Valid SCSITaskStatus values are defined in SCSITask.h @param senseDataBuffer Pointer to a buffer the size of the SCSI_Sense_Data struct found in SCSICmds_REQUEST_SENSE_Defs.h. The sense data is only valid if the SCSITaskStatus is kSCSITaskStatus_CHECK_CONDITION. @result Returns kIOReturnSuccess if successful, kIOReturnNoDevice if there is no connection to an IOService, kIOReturnNoMemory if a SCSITask couldn't be created, or kIOReturnExclusiveAccess if the device is already opened for exclusive access by another client. */ IOReturn ( *ReadDVDStructure ) ( void * self, SCSICmdField4Byte ADDRESS, SCSICmdField1Byte LAYER_NUMBER, SCSICmdField1Byte FORMAT, void * buffer, SCSICmdField2Byte bufferSize, SCSITaskStatus * taskStatus, SCSI_Sense_Data * senseDataBuffer ); /*! @function GetSCSITaskDeviceInterface @abstract Gets a handle to the SCSITaskDeviceInterface without closing the user client connection which was initiated by IOCreateCFPlugInForService. @discussion Once an MMCDeviceInterface is opened the client may use this function to get a handle to the interface used to create and send SCSITasks directly to the device. @param self Pointer to an MMCDeviceInterface for one IOService. @result Returns a handle to a SCSITaskDeviceInterface if successful, otherwise NULL. */ SCSITaskDeviceInterface ** ( *GetSCSITaskDeviceInterface )( void * self ); /* Added in Mac OS X 10.2 */ /*! @function GetPerformanceV2 @abstract Issues a GET_PERFORMANCE command to the device as defined in Mt. Fuji 5. @discussion Once an MMCDeviceInterface is opened, the client may send this command to get performance information from the device. @param self Pointer to an MMCDeviceInterface for one IOService. @param DATA_TYPE The DATA_TYPE field as described for the GET_PERFORMANCE command in Mt. Fuji 5. @param STARTING_LBA The STARTING_LBA field as described in Mt. Fuji 5 for the GET_PERFORMANCE command. @param MAXIMUM_NUMBER_OF_DESCRIPTORS The MAXIMUM_NUMBER_OF_DESCRIPTORS field as described in Mt. Fuji 5 for the GET_PERFORMANCE command. @param TYPE The TYPE field as described for the GET_PERFORMANCE command in Mt. Fuji 5. @param buffer Pointer to the buffer where the mode sense data should be placed. @param bufferSize Size of the buffer. @param taskStatus Pointer to a SCSITaskStatus to get the status of the SCSITask which was executed. Valid SCSITaskStatus values are defined in SCSITask.h @param senseDataBuffer Pointer to a buffer the size of the SCSI_Sense_Data struct found in SCSICmds_REQUEST_SENSE_Defs.h. The sense data is only valid if the SCSITaskStatus is kSCSITaskStatus_CHECK_CONDITION. @result Returns kIOReturnSuccess if successful, kIOReturnNoDevice if there is no connection to an IOService, kIOReturnNoMemory if a SCSITask couldn't be created, or kIOReturnExclusiveAccess if the device is already opened for exclusive access by another client. */ IOReturn ( *GetPerformanceV2 )( void * self, SCSICmdField5Bit DATA_TYPE, SCSICmdField4Byte STARTING_LBA, SCSICmdField2Byte MAXIMUM_NUMBER_OF_DESCRIPTORS, SCSICmdField1Byte TYPE, void * buffer, SCSICmdField2Byte bufferSize, SCSITaskStatus * taskStatus, SCSI_Sense_Data * senseDataBuffer ); /* Added in Mac OS X 10.3 */ /*! @function SetCDSpeed @abstract Issues a SET_CD_SPEED command to the device as defined in MMC-2. @discussion Once an MMCDeviceInterface is opened the client may send this command to change the read and/or write CD speed of the drive. @param self Pointer to an MMCDeviceInterface for one IOService. @param LOGICAL_UNIT_READ_SPEED The LOGICAL_UNIT_READ_SPEED field as defined in MMC-2. @param LOGICAL_UNIT_WRITE_SPEED The LOGICAL_UNIT_WRITE_SPEED field as defined in MMC-2. @param taskStatus Pointer to a SCSITaskStatus to get the status of the SCSITask which was executed. Valid SCSITaskStatus values are defined in SCSITask.h @param senseDataBuffer Pointer to a buffer the size of the SCSI_Sense_Data struct found in SCSICmds_REQUEST_SENSE_Defs.h. The sense data is only valid if the SCSITaskStatus is kSCSITaskStatus_CHECK_CONDITION. @result Returns kIOReturnSuccess if successful, kIOReturnNoDevice if there is no connection to an IOService, kIOReturnNoMemory if a SCSITask couldn't be created, or kIOReturnExclusiveAccess if the device is already opened for exclusive access by another client. */ IOReturn ( *SetCDSpeed ) ( void * self, SCSICmdField2Byte LOGICAL_UNIT_READ_SPEED, SCSICmdField2Byte LOGICAL_UNIT_WRITE_SPEED, SCSITaskStatus * taskStatus, SCSI_Sense_Data * senseDataBuffer ); /* Added in Mac OS X 10.3 */ /*! @function ReadFormatCapacities @abstract Issues a READ_FORMAT_CAPACITIES command to the device as defined in MMC-2. @discussion Once an MMCDeviceInterface is opened the client may send this command to get format capacity information from the media. @param self Pointer to an MMCDeviceInterface for one IOService. @param buffer Pointer to the buffer where the mode sense data should be placed. @param bufferSize Size of the buffer. @param taskStatus Pointer to a SCSITaskStatus to get the status of the SCSITask which was executed. Valid SCSITaskStatus values are defined in SCSITask.h @param senseDataBuffer Pointer to a buffer the size of the SCSI_Sense_Data struct found in SCSICmds_REQUEST_SENSE_Defs.h. The sense data is only valid if the SCSITaskStatus is kSCSITaskStatus_CHECK_CONDITION. @result Returns kIOReturnSuccess if successful, kIOReturnNoDevice if there is no connection to an IOService, kIOReturnNoMemory if a SCSITask couldn't be created, or kIOReturnExclusiveAccess if the device is already opened for exclusive access by another client. */ IOReturn ( *ReadFormatCapacities ) ( void * self, void * buffer, SCSICmdField2Byte bufferSize, SCSITaskStatus * taskStatus, SCSI_Sense_Data * senseDataBuffer ); /*! @function ReadDiscStructure @abstract Issues a READ_DISC_STRUCTURE command to the device as defined in MMC-5. @discussion Once an MMCDeviceInterface is opened the client may send this command to read information about Disc specific structures on the disc. @param self Pointer to an MMCDeviceInterface for one IOService. @param MEDIA_TYPE The MEDIA_TYPE field as defined in MMC-5. @param ADDRESS The ADDRESS field as defined in MMC-5. @param LAYER_NUMBER The LAYER_NUMBER field as defined in MMC-5. @param FORMAT The FORMAT field as defined in MMC-5. @param buffer Pointer to the buffer to be used for this function. @param bufferSize The size of the data transfer requested. @param taskStatus Pointer to a SCSITaskStatus to get the status of the SCSITask which was executed. Valid SCSITaskStatus values are defined in SCSITask.h @param senseDataBuffer Pointer to a buffer the size of the SCSI_Sense_Data struct found in SCSICmds_REQUEST_SENSE_Defs.h. The sense data is only valid if the SCSITaskStatus is kSCSITaskStatus_CHECK_CONDITION. @result Returns kIOReturnSuccess if successful, kIOReturnNoDevice if there is no connection to an IOService, kIOReturnNoMemory if a SCSITask couldn't be created, or kIOReturnExclusiveAccess if the device is already opened for exclusive access by another client. */ IOReturn ( *ReadDiscStructure ) ( void * self, SCSICmdField4Bit MEDIA_TYPE, SCSICmdField4Byte ADDRESS, SCSICmdField1Byte LAYER_NUMBER, SCSICmdField1Byte FORMAT, void * buffer, SCSICmdField2Byte bufferSize, SCSITaskStatus * taskStatus, SCSI_Sense_Data * senseDataBuffer ); /*! @function ReadDiscInformationV2 @abstract Issues a READ_DISC_INFORMATION command to the device as defined in MMC-5. @discussion Once an MMCDeviceInterface is opened the client may send this command to read information about the disc (CD-R/RW, (un)finalized, etc.. @param self Pointer to an MMCDeviceInterface for one IOService. @param DATA_TYPE The DATA_TYPE field as defined in MMC-5. @param buffer Pointer to the buffer to be used for this function. @param bufferSize The size of the data transfer requested. @param taskStatus Pointer to a SCSITaskStatus to get the status of the SCSITask which was executed. Valid SCSITaskStatus values are defined in SCSITask.h @param senseDataBuffer Pointer to a buffer the size of the SCSI_Sense_Data struct found in SCSICmds_REQUEST_SENSE_Defs.h. The sense data is only valid if the SCSITaskStatus is kSCSITaskStatus_CHECK_CONDITION. @result Returns kIOReturnSuccess if successful, kIOReturnNoDevice if there is no connection to an IOService, kIOReturnNoMemory if a SCSITask couldn't be created, or kIOReturnExclusiveAccess if the device is already opened for exclusive access by another client. */ IOReturn ( *ReadDiscInformationV2 ) ( void * self, SCSICmdField3Bit DATA_TYPE, void * buffer, SCSICmdField2Byte bufferSize, SCSITaskStatus * taskStatus, SCSI_Sense_Data * senseDataBuffer ); /*! @function ReadTrackInformationV2 @abstract Issues a READ_TRACK_INFORMATION command to the device as defined in Mt. Fuji 5. @discussion Once an MMCDeviceInterface is opened the client may send this command to read information about selected tracks on the disc. @param self Pointer to an MMCDeviceInterface for one IOService. @param OPEN The OPEN field as defined in Mt. Fuji 5. @param ADDRESS_NUMBER_TYPE The ADDRESS/NUMBER_TYPE field as defined in Mt. Fuji 5. @param LOGICAL_BLOCK_ADDRESS_TRACK_SESSION_NUMBER The LOGICAL_BLOCK_ADDRESS/SESSION_NUMBER field as defined in Mt. Fuji 5. @param buffer Pointer to the buffer to be used for this function. @param bufferSize The size of the data transfer requested. @param taskStatus Pointer to a SCSITaskStatus to get the status of the SCSITask which was executed. Valid SCSITaskStatus values are defined in SCSITask.h @param senseDataBuffer Pointer to a buffer the size of the SCSI_Sense_Data struct found in SCSICmds_REQUEST_SENSE_Defs.h. The sense data is only valid if the SCSITaskStatus is kSCSITaskStatus_CHECK_CONDITION. @result Returns kIOReturnSuccess if successful, kIOReturnNoDevice if there is no connection to an IOService, kIOReturnNoMemory if a SCSITask couldn't be created, or kIOReturnExclusiveAccess if the device is already opened for exclusive access by another client. */ IOReturn ( *ReadTrackInformationV2 ) ( void * self, SCSICmdField1Bit OPEN, SCSICmdField2Bit ADDRESS_NUMBER_TYPE, SCSICmdField4Byte LOGICAL_BLOCK_ADDRESS_TRACK_SESSION_NUMBER, void * buffer, SCSICmdField2Byte bufferSize, SCSITaskStatus * taskStatus, SCSI_Sense_Data * senseDataBuffer ); /* Added in 10.6 */ /*! @function SetStreaming @abstract Issues a SET_STREAMING command to the device as defined in MMC-5. @discussion Once an MMCDeviceInterface is opened the client may send this command to change streaming attributes. Clients should check for the Real-time Streaming Feature (107h) before using this command. @param self Pointer to an MMCDeviceInterface for one IOService. @param TYPE The TYPE field as defined in MMC-5. @param buffer Pointer to the buffer to be used for this function. @param bufferSize The size of the data transfer requested. @param taskStatus Pointer to a SCSITaskStatus to get the status of the SCSITask which was executed. Valid SCSITaskStatus values are defined in SCSITask.h @param senseDataBuffer Pointer to a buffer the size of the SCSI_Sense_Data struct found in SCSICmds_REQUEST_SENSE_Defs.h. The sense data is only valid if the SCSITaskStatus is kSCSITaskStatus_CHECK_CONDITION. @result Returns kIOReturnSuccess if successful, kIOReturnNoDevice if there is no connection to an IOService, kIOReturnNoMemory if a SCSITask couldn't be created, or kIOReturnExclusiveAccess if the device is already opened for exclusive access by another client. */ IOReturn ( *SetStreaming ) ( void * self, SCSICmdField1Byte TYPE, void * buffer, SCSICmdField2Byte bufferSize, SCSITaskStatus * taskStatus, SCSI_Sense_Data * senseDataBuffer ); } MMCDeviceInterface; #endif #if !KERNEL #ifdef __cplusplus } #endif #endif /* !KERNEL */ #endif /* __SCSI_TASK_LIB_H__ */
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/scsi/SCSICommandDefinitions.h
/* * Copyright (c) 2001-2009 Apple Inc. All rights reserved. * * @APPLE_LICENSE_HEADER_START@ * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this * file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_LICENSE_HEADER_END@ */ #ifndef _IOKIT_SCSI_COMMAND_DEFINITIONS_H_ #define _IOKIT_SCSI_COMMAND_DEFINITIONS_H_ #if KERNEL #include <IOKit/IOTypes.h> #else #include <CoreFoundation/CoreFoundation.h> #endif /*! @header SCSICommandDefinitions @discussion This file contains all the definitions for types and constants that are used by the command set classes for building CDBs. The field type definitions are used for the parameters passed to a method that builds and sends any SCSI defined command to clearly identify the type of value expected for a parameter. The command methods will then use the appropriate mask to verify that the value passed into a parameter is of the specified type. Currently only types and masks are defined for 8 bytes and smaller fields. If a command is defined that uses a larger field, these should be expanded to include those sizes. */ #pragma mark Field Type Definitions /* These are the type definitions used for the parameters of methods that * build and send Command Descriptor Blocks. */ /* 1 Byte or smaller fields. */ /*! @typedef SCSICmdField1Bit */ typedef UInt8 SCSICmdField1Bit; /*! @typedef SCSICmdField2Bit */ typedef UInt8 SCSICmdField2Bit; /*! @typedef SCSICmdField3Bit */ typedef UInt8 SCSICmdField3Bit; /*! @typedef SCSICmdField4Bit */ typedef UInt8 SCSICmdField4Bit; /*! @typedef SCSICmdField5Bit */ typedef UInt8 SCSICmdField5Bit; /*! @typedef SCSICmdField6Bit */ typedef UInt8 SCSICmdField6Bit; /*! @typedef SCSICmdField7Bit */ typedef UInt8 SCSICmdField7Bit; /*! @typedef SCSICmdField1Byte */ typedef UInt8 SCSICmdField1Byte; /* 2 Bytes or smaller fields. */ /*! @typedef SCSICmdField9Bit */ typedef UInt16 SCSICmdField9Bit; /*! @typedef SCSICmdField10Bit */ typedef UInt16 SCSICmdField10Bit; /*! @typedef SCSICmdField11Bit */ typedef UInt16 SCSICmdField11Bit; /*! @typedef SCSICmdField12Bit */ typedef UInt16 SCSICmdField12Bit; /*! @typedef SCSICmdField13Bit */ typedef UInt16 SCSICmdField13Bit; /*! @typedef SCSICmdField14Bit */ typedef UInt16 SCSICmdField14Bit; /*! @typedef SCSICmdField15Bit */ typedef UInt16 SCSICmdField15Bit; /*! @typedef SCSICmdField2Byte */ typedef UInt16 SCSICmdField2Byte; /* 3 Bytes or smaller fields. */ /*! @typedef SCSICmdField17Bit */ typedef UInt32 SCSICmdField17Bit; /*! @typedef SCSICmdField18Bit */ typedef UInt32 SCSICmdField18Bit; /*! @typedef SCSICmdField19Bit */ typedef UInt32 SCSICmdField19Bit; /*! @typedef SCSICmdField20Bit */ typedef UInt32 SCSICmdField20Bit; /*! @typedef SCSICmdField21Bit */ typedef UInt32 SCSICmdField21Bit; /*! @typedef SCSICmdField22Bit */ typedef UInt32 SCSICmdField22Bit; /*! @typedef SCSICmdField23Bit */ typedef UInt32 SCSICmdField23Bit; /*! @typedef SCSICmdField3Byte */ typedef UInt32 SCSICmdField3Byte; /* 4 Bytes or smaller fields. */ /*! @typedef SCSICmdField25Bit */ typedef UInt32 SCSICmdField25Bit; /*! @typedef SCSICmdField26Bit */ typedef UInt32 SCSICmdField26Bit; /*! @typedef SCSICmdField27Bit */ typedef UInt32 SCSICmdField27Bit; /*! @typedef SCSICmdField28Bit */ typedef UInt32 SCSICmdField28Bit; /*! @typedef SCSICmdField29Bit */ typedef UInt32 SCSICmdField29Bit; /*! @typedef SCSICmdField30Bit */ typedef UInt32 SCSICmdField30Bit; /*! @typedef SCSICmdField31Bit */ typedef UInt32 SCSICmdField31Bit; /*! @typedef SCSICmdField4Byte */ typedef UInt32 SCSICmdField4Byte; /* 5 Bytes or smaller fields. */ /*! @typedef SCSICmdField33Bit */ typedef UInt64 SCSICmdField33Bit; /*! @typedef SCSICmdField34Bit */ typedef UInt64 SCSICmdField34Bit; /*! @typedef SCSICmdField35Bit */ typedef UInt64 SCSICmdField35Bit; /*! @typedef SCSICmdField36Bit */ typedef UInt64 SCSICmdField36Bit; /*! @typedef SCSICmdField37Bit */ typedef UInt64 SCSICmdField37Bit; /*! @typedef SCSICmdField38Bit */ typedef UInt64 SCSICmdField38Bit; /*! @typedef SCSICmdField39Bit */ typedef UInt64 SCSICmdField39Bit; /*! @typedef SCSICmdField5Byte */ typedef UInt64 SCSICmdField5Byte; /* 6 Bytes or smaller fields. */ /*! @typedef SCSICmdField41Bit */ typedef UInt64 SCSICmdField41Bit; /*! @typedef SCSICmdField42Bit */ typedef UInt64 SCSICmdField42Bit; /*! @typedef SCSICmdField43Bit */ typedef UInt64 SCSICmdField43Bit; /*! @typedef SCSICmdField44Bit */ typedef UInt64 SCSICmdField44Bit; /*! @typedef SCSICmdField45Bit */ typedef UInt64 SCSICmdField45Bit; /*! @typedef SCSICmdField46Bit */ typedef UInt64 SCSICmdField46Bit; /*! @typedef SCSICmdField47Bit */ typedef UInt64 SCSICmdField47Bit; /*! @typedef SCSICmdField6Byte */ typedef UInt64 SCSICmdField6Byte; /* 7 Bytes or smaller fields. */ /*! @typedef SCSICmdField49Bit */ typedef UInt64 SCSICmdField49Bit; /*! @typedef SCSICmdField50Bit */ typedef UInt64 SCSICmdField50Bit; /*! @typedef SCSICmdField51Bit */ typedef UInt64 SCSICmdField51Bit; /*! @typedef SCSICmdField52Bit */ typedef UInt64 SCSICmdField52Bit; /*! @typedef SCSICmdField53Bit */ typedef UInt64 SCSICmdField53Bit; /*! @typedef SCSICmdField54Bit */ typedef UInt64 SCSICmdField54Bit; /*! @typedef SCSICmdField55Bit */ typedef UInt64 SCSICmdField55Bit; /*! @typedef SCSICmdField7Byte */ typedef UInt64 SCSICmdField7Byte; /* 8 Bytes or smaller fields. */ /*! @typedef SCSICmdField57Bit */ typedef UInt64 SCSICmdField57Bit; /*! @typedef SCSICmdField58Bit */ typedef UInt64 SCSICmdField58Bit; /*! @typedef SCSICmdField59Bit */ typedef UInt64 SCSICmdField59Bit; /*! @typedef SCSICmdField60Bit */ typedef UInt64 SCSICmdField60Bit; /*! @typedef SCSICmdField61Bit */ typedef UInt64 SCSICmdField61Bit; /*! @typedef SCSICmdField62Bit */ typedef UInt64 SCSICmdField62Bit; /*! @typedef SCSICmdField63Bit */ typedef UInt64 SCSICmdField63Bit; /*! @typedef SCSICmdField8Byte */ typedef UInt64 SCSICmdField8Byte; #pragma mark Field Mask Definitions /* These are masks that are used to verify that the values passed into the * parameters for the fields are not larger than the field size. * * NB: These have changed from enums to #define since enums greater than * 32 bits in size are not well-defined in C99. */ /* 1 Byte or smaller fields. */ /*! @constant kSCSICmdFieldMask1Bit */ #define kSCSICmdFieldMask1Bit 0x01 /*! @constant kSCSICmdFieldMask2Bit */ #define kSCSICmdFieldMask2Bit 0x03 /*! @constant kSCSICmdFieldMask3Bit */ #define kSCSICmdFieldMask3Bit 0x07 /*! @constant kSCSICmdFieldMask4Bit */ #define kSCSICmdFieldMask4Bit 0x0F /*! @constant kSCSICmdFieldMask5Bit */ #define kSCSICmdFieldMask5Bit 0x1F /*! @constant kSCSICmdFieldMask6Bit */ #define kSCSICmdFieldMask6Bit 0x3F /*! @constant kSCSICmdFieldMask7Bit */ #define kSCSICmdFieldMask7Bit 0x7F #define kSCSICmdFieldMask1Byte 0xFF /* 2 Bytes or smaller fields. */ /*! @constant kSCSICmdFieldMask9Bit */ #define kSCSICmdFieldMask9Bit 0x01FF /*! @constant kSCSICmdFieldMask10Bit */ #define kSCSICmdFieldMask10Bit 0x03FF /*! @constant kSCSICmdFieldMask11Bit */ #define kSCSICmdFieldMask11Bit 0x07FF /*! @constant kSCSICmdFieldMask12Bit */ #define kSCSICmdFieldMask12Bit 0x0FFF /*! @constant kSCSICmdFieldMask13Bit */ #define kSCSICmdFieldMask13Bit 0x1FFF /*! @constant kSCSICmdFieldMask14Bit */ #define kSCSICmdFieldMask14Bit 0x3FFF /*! @constant kSCSICmdFieldMask15Bit */ #define kSCSICmdFieldMask15Bit 0x7FFF /*! @constant kSCSICmdFieldMask2Byte */ #define kSCSICmdFieldMask2Byte 0xFFFF /* 3 Bytes or smaller fields. */ /*! @constant kSCSICmdFieldMask17Bit */ #define kSCSICmdFieldMask17Bit 0x01FFFF /*! @constant kSCSICmdFieldMask18Bit */ #define kSCSICmdFieldMask18Bit 0x03FFFF /*! @constant kSCSICmdFieldMask19Bit */ #define kSCSICmdFieldMask19Bit 0x07FFFF /*! @constant kSCSICmdFieldMask20Bit */ #define kSCSICmdFieldMask20Bit 0x0FFFFF /*! @constant kSCSICmdFieldMask21Bit */ #define kSCSICmdFieldMask21Bit 0x1FFFFF /*! @constant kSCSICmdFieldMask22Bit */ #define kSCSICmdFieldMask22Bit 0x3FFFFF /*! @constant kSCSICmdFieldMask23Bit */ #define kSCSICmdFieldMask23Bit 0x7FFFFF /*! @constant kSCSICmdFieldMask3Byte */ #define kSCSICmdFieldMask3Byte 0xFFFFFF /* 4 Bytes or smaller fields. */ /*! @constant kSCSICmdFieldMask25Bit */ #define kSCSICmdFieldMask25Bit 0x01FFFFFFUL /*! @constant kSCSICmdFieldMask26Bit */ #define kSCSICmdFieldMask26Bit 0x03FFFFFFUL /*! @constant kSCSICmdFieldMask27Bit */ #define kSCSICmdFieldMask27Bit 0x07FFFFFFUL /*! @constant kSCSICmdFieldMask28Bit */ #define kSCSICmdFieldMask28Bit 0x0FFFFFFFUL /*! @constant kSCSICmdFieldMask29Bit */ #define kSCSICmdFieldMask29Bit 0x1FFFFFFFUL /*! @constant kSCSICmdFieldMask30Bit */ #define kSCSICmdFieldMask30Bit 0x3FFFFFFFUL /*! @constant kSCSICmdFieldMask31Bit */ #define kSCSICmdFieldMask31Bit 0x7FFFFFFFUL /*! @constant kSCSICmdFieldMask4Byte */ #define kSCSICmdFieldMask4Byte 0xFFFFFFFFUL /* 5 Bytes or smaller fields. */ /*! @constant kSCSICmdFieldMask33Bit */ #define kSCSICmdFieldMask33Bit 0x01FFFFFFFFULL /*! @constant kSCSICmdFieldMask34Bit */ #define kSCSICmdFieldMask34Bit 0x03FFFFFFFFULL /*! @constant kSCSICmdFieldMask35Bit */ #define kSCSICmdFieldMask35Bit 0x07FFFFFFFFULL /*! @constant kSCSICmdFieldMask36Bit */ #define kSCSICmdFieldMask36Bit 0x0FFFFFFFFFULL /*! @constant kSCSICmdFieldMask37Bit */ #define kSCSICmdFieldMask37Bit 0x1FFFFFFFFFULL /*! @constant kSCSICmdFieldMask38Bit */ #define kSCSICmdFieldMask38Bit 0x3FFFFFFFFFULL /*! @constant kSCSICmdFieldMask39Bit */ #define kSCSICmdFieldMask39Bit 0x7FFFFFFFFFULL /*! @constant kSCSICmdFieldMask5Byte */ #define kSCSICmdFieldMask5Byte 0xFFFFFFFFFFULL /* 6 Bytes or smaller fields. */ /*! @constant kSCSICmdFieldMask41Bit */ #define kSCSICmdFieldMask41Bit 0x01FFFFFFFFFFULL /*! @constant kSCSICmdFieldMask42Bit */ #define kSCSICmdFieldMask42Bit 0x03FFFFFFFFFFULL /*! @constant kSCSICmdFieldMask43Bit */ #define kSCSICmdFieldMask43Bit 0x07FFFFFFFFFFULL /*! @constant kSCSICmdFieldMask44Bit */ #define kSCSICmdFieldMask44Bit 0x0FFFFFFFFFFFULL /*! @constant kSCSICmdFieldMask45Bit */ #define kSCSICmdFieldMask45Bit 0x1FFFFFFFFFFFULL /*! @constant kSCSICmdFieldMask46Bit */ #define kSCSICmdFieldMask46Bit 0x3FFFFFFFFFFFULL /*! @constant kSCSICmdFieldMask47Bit */ #define kSCSICmdFieldMask47Bit 0x7FFFFFFFFFFFULL /*! @constant kSCSICmdFieldMask6Byte */ #define kSCSICmdFieldMask6Byte 0xFFFFFFFFFFFFULL /* 7 Bytes or smaller fields. */ /*! @constant kSCSICmdFieldMask49Bit */ #define kSCSICmdFieldMask49Bit 0x01FFFFFFFFFFFFULL /*! @constant kSCSICmdFieldMask50Bit */ #define kSCSICmdFieldMask50Bit 0x03FFFFFFFFFFFFULL /*! @constant kSCSICmdFieldMask51Bit */ #define kSCSICmdFieldMask51Bit 0x07FFFFFFFFFFFFULL /*! @constant kSCSICmdFieldMask52Bit */ #define kSCSICmdFieldMask52Bit 0x0FFFFFFFFFFFFFULL /*! @constant kSCSICmdFieldMask53Bit */ #define kSCSICmdFieldMask53Bit 0x1FFFFFFFFFFFFFULL /*! @constant kSCSICmdFieldMask54Bit */ #define kSCSICmdFieldMask54Bit 0x3FFFFFFFFFFFFFULL /*! @constant kSCSICmdFieldMask55Bit */ #define kSCSICmdFieldMask55Bit 0x7FFFFFFFFFFFFFULL /*! @constant kSCSICmdFieldMask7Byte */ #define kSCSICmdFieldMask7Byte 0xFFFFFFFFFFFFFFULL /* 8 Bytes or smaller fields. */ /*! @constant kSCSICmdFieldMask57Bit */ #define kSCSICmdFieldMask57Bit 0x01FFFFFFFFFFFFFFULL /*! @constant kSCSICmdFieldMask58Bit */ #define kSCSICmdFieldMask58Bit 0x03FFFFFFFFFFFFFFULL /*! @constant kSCSICmdFieldMask59Bit */ #define kSCSICmdFieldMask59Bit 0x07FFFFFFFFFFFFFFULL /*! @constant kSCSICmdFieldMask60Bit */ #define kSCSICmdFieldMask60Bit 0x0FFFFFFFFFFFFFFFULL /*! @constant kSCSICmdFieldMask61Bit */ #define kSCSICmdFieldMask61Bit 0x1FFFFFFFFFFFFFFFULL /*! @constant kSCSICmdFieldMask62Bit */ #define kSCSICmdFieldMask62Bit 0x3FFFFFFFFFFFFFFFULL /*! @constant kSCSICmdFieldMask63Bit */ #define kSCSICmdFieldMask63Bit 0x7FFFFFFFFFFFFFFFULL /*! @constant kSCSICmdFieldMask8Byte */ #define kSCSICmdFieldMask8Byte 0xFFFFFFFFFFFFFFFFULL #endif /* _IOKIT_SCSI_COMMAND_DEFINITIONS_H_ */
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/scsi/SCSICmds_REQUEST_SENSE_Defs.h
/* * Copyright (c) 1998-2009 Apple Inc. All rights reserved. * * @APPLE_LICENSE_HEADER_START@ * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this * file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_LICENSE_HEADER_END@ */ #ifndef _IOKIT_SCSI_CMDS_REQUEST_SENSE_H_ #define _IOKIT_SCSI_CMDS_REQUEST_SENSE_H_ #include <TargetConditionals.h> #if TARGET_OS_DRIVERKIT typedef uint8_t UInt8; #else #if KERNEL #include <IOKit/IOTypes.h> #else #include <CoreFoundation/CoreFoundation.h> #endif #endif /*! @header SCSI Request Sense Definitions @discussion This file contains all definitions for the data returned from the REQUEST SENSE (0x03) command and from auto sense on protocols that support it. */ /*! @enum kSenseDefaultSize @discussion The default size for SCSI Request Sense data. */ enum { kSenseDefaultSize = 18 }; /*! @struct SCSI_Sense_Data @discussion The basic SCSI Request Sense data structure. */ typedef struct SCSI_Sense_Data { UInt8 VALID_RESPONSE_CODE; // 7 = Valid. 6-0 = Response Code. UInt8 SEGMENT_NUMBER; // Segment number UInt8 SENSE_KEY; // 7 = FILEMARK, 6 = EOM, 5 = ILI, 3-0 = SENSE KEY. UInt8 INFORMATION_1; // INFORMATION. UInt8 INFORMATION_2; // INFORMATION. UInt8 INFORMATION_3; // INFORMATION. UInt8 INFORMATION_4; // INFORMATION. UInt8 ADDITIONAL_SENSE_LENGTH; // Number of additional bytes available in sense data UInt8 COMMAND_SPECIFIC_INFORMATION_1; // Command Specific Information UInt8 COMMAND_SPECIFIC_INFORMATION_2; // Command Specific Information UInt8 COMMAND_SPECIFIC_INFORMATION_3; // Command Specific Information UInt8 COMMAND_SPECIFIC_INFORMATION_4; // Command Specific Information UInt8 ADDITIONAL_SENSE_CODE; // Additional Sense Code UInt8 ADDITIONAL_SENSE_CODE_QUALIFIER; // Additional Sense Code Qualifier UInt8 FIELD_REPLACEABLE_UNIT_CODE; // Field Replaceable Unit Code UInt8 SKSV_SENSE_KEY_SPECIFIC_MSB; // 7 = Sense Key Specific Valid bit, 6-0 Sense Key Specific MSB UInt8 SENSE_KEY_SPECIFIC_MID; // Sense Key Specific Middle UInt8 SENSE_KEY_SPECIFIC_LSB; // Sense Key Specific LSB } SCSI_Sense_Data; /*! @enum Sense Valid @discussion Masks to use to determine if sense data is valid or not. @constant kSENSE_DATA_VALID Sense data is valid. @constant kSENSE_NOT_DATA_VALID Sense data is not valid. @constant kSENSE_DATA_VALID_Mask Validity mask to use when checking the VALID_RESPONSE_CODE field. */ enum { kSENSE_DATA_VALID = 0x80, kSENSE_NOT_DATA_VALID = 0x00, kSENSE_DATA_VALID_Mask = 0x80 }; /*! @enum Sense Response Codes @discussion Masks and values to determine the Response Code. @constant kSENSE_RESPONSE_CODE_Current_Errors Response code indicating current errors are reported. @constant kSENSE_RESPONSE_CODE_Deferred_Errors Response code indicating deferred errors are reported. @constant kSENSE_RESPONSE_CODE_Mask Mask to use when checking the VALID_RESPONSE_CODE field. */ enum { kSENSE_RESPONSE_CODE_Current_Errors = 0x70, kSENSE_RESPONSE_CODE_Deferred_Errors = 0x71, kSENSE_RESPONSE_CODE_Mask = 0x7F }; /*! @enum FILEMARK bit field definitions @discussion Masks and values to determine the FileMark bit field. @constant kSENSE_FILEMARK_Set Filemark bit is set. @constant kSENSE_FILEMARK_Not_Set Filemark bit is not set. @constant kSENSE_FILEMARK_Mask Mask to use when checking the SENSE_KEY field for the FILEMARK bit. */ enum { kSENSE_FILEMARK_Set = 0x80, kSENSE_FILEMARK_Not_Set = 0x00, kSENSE_FILEMARK_Mask = 0x80 }; /*! @enum EOM bit field definitions @discussion Masks and values to determine the End Of Medium bit field. @constant kSENSE_EOM_Set End Of Medium bit is set. @constant kSENSE_EOM_Not_Set End Of Medium bit is not set. @constant kSENSE_EOM_Mask Mask to use when checking the SENSE_KEY field for the EOM bit. */ enum { kSENSE_EOM_Set = 0x40, kSENSE_EOM_Not_Set = 0x00, kSENSE_EOM_Mask = 0x40 }; /*! @enum ILI bit field definitions @discussion Masks and values to determine the Incorrect Length Indicator bit field. @constant kSENSE_ILI_Set Incorrect Length Indicator bit is set. @constant kSENSE_ILI_Not_Set Incorrect Length Indicator bit is not set. @constant kSENSE_ILI_Mask Mask to use when checking the SENSE_KEY field for the ILI bit. */ enum { kSENSE_ILI_Set = 0x20, kSENSE_ILI_Not_Set = 0x00, kSENSE_ILI_Mask = 0x20 }; /*! @enum Sense Key definitions @discussion Masks and values to determine the SENSE_KEY. @constant kSENSE_KEY_NO_SENSE No sense data is present. @constant kSENSE_KEY_RECOVERED_ERROR A recovered error has occurred. @constant kSENSE_KEY_NOT_READY Device server is not ready. @constant kSENSE_KEY_MEDIUM_ERROR Device server detected a medium error. @constant kSENSE_KEY_HARDWARE_ERROR Device server detected a hardware error. @constant kSENSE_KEY_ILLEGAL_REQUEST Device server detected an illegal request. @constant kSENSE_KEY_UNIT_ATTENTION Device server indicates a unit attention condition. @constant kSENSE_KEY_DATA_PROTECT Device server indicates a data protect condition. @constant kSENSE_KEY_BLANK_CHECK Device server indicates a blank check condition. @constant kSENSE_KEY_VENDOR_SPECIFIC Device server indicates a vendor specific condition. @constant kSENSE_KEY_COPY_ABORTED Device server indicates a copy aborted condition. @constant kSENSE_KEY_ABORTED_COMMAND Device server indicates an aborted command condition. @constant kSENSE_KEY_VOLUME_OVERFLOW Device server indicates a volume overflow condition. @constant kSENSE_KEY_MISCOMPARE Device server indicates a miscompare condition. @constant kSENSE_KEY_Mask Mask to use when checking the SENSE_KEY field for the SENSE_KEY value. */ enum { kSENSE_KEY_NO_SENSE = 0x00, kSENSE_KEY_RECOVERED_ERROR = 0x01, kSENSE_KEY_NOT_READY = 0x02, kSENSE_KEY_MEDIUM_ERROR = 0x03, kSENSE_KEY_HARDWARE_ERROR = 0x04, kSENSE_KEY_ILLEGAL_REQUEST = 0x05, kSENSE_KEY_UNIT_ATTENTION = 0x06, kSENSE_KEY_DATA_PROTECT = 0x07, kSENSE_KEY_BLANK_CHECK = 0x08, kSENSE_KEY_VENDOR_SPECIFIC = 0x09, kSENSE_KEY_COPY_ABORTED = 0x0A, kSENSE_KEY_ABORTED_COMMAND = 0x0B, /* SENSE KEY 0x0C is obsoleted */ kSENSE_KEY_VOLUME_OVERFLOW = 0x0D, kSENSE_KEY_MISCOMPARE = 0x0E, /* SENSE KEY 0x0F is reserved */ kSENSE_KEY_Mask = 0x0F }; #endif /* _IOKIT_SCSI_CMDS_REQUEST_SENSE_H_ */
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/scsi/SCSICommandOperationCodes.h
/* * Copyright (c) 2001-2009 Apple Inc. All rights reserved. * * @APPLE_LICENSE_HEADER_START@ * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this * file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_LICENSE_HEADER_END@ */ #ifndef _SCSI_COMMAND_OPERATION_CODES_H_ #define _SCSI_COMMAND_OPERATION_CODES_H_ #pragma mark About this file /* This file contains the operation code definitions for all commands defined * by the SCSI specifications. The commands are listed in three formats: * 1) All commands are listed in alphabetical order. This list is the live * enumeration for all of the command constants. * 2) The commands are listed in ascending numerical order. * 3) The commands are grouped by Peripheral Device Type. * * In the command listings by Peripheral Device Type, there will be a comment * following each command. This comment indentifies the section of the related * specification where the commands is defined and the requirement type of the * command, Mandatory or Optional. * If a specification redefines an optional command from SPC as mandatory, * the command will be relisted in the Peripheral Device Type command list with * the mandatory tag next to it. * All commands that are listed in SPC as Device Type Specifc will be relisted * as a comment in all specifications lists that support that command with the * appropriate Mandatory or Optional tag for that specification. * * The section number and the requirement type of the command are based on the * version of the specification listed in the header comment for the Peripheral * Device Type. This data is provided for informational purposes only. The * specification document and version that the device adheres to as indicated * by the data returned in response to the INQUIRY command should be used as * the authorative source for supported and required behavior of the device. * * The SPC set is listed before all other Peripheral Device Type commands as * this is the base document from which all of the other documents are derived. * * The Peripheral Device Types and associated command sets as defined by SPC-2, * section 7.4.1 are as follows: * Peripheral Device Type Associated Command Specification * ------------------------------------ ----------------------------------- * 0x00 Direct Access Device SBC - SCSI-3 Block Commands * 0x01 Sequential Access Device SSC - SCSI-3 Stream Commands * 0x02 Printer Device SSC - SCSI-3 Stream Commands * 0x03 Processor Device SPC - SCSI Primary Commands-2 * 0x04 Write Once Device SBC - SCSI-3 Block Commands * 0x05 CD-ROM Device MMC - SCSI Multimedia Commands-2 * 0x06 Scanner Device SGC - SCSI-3 Graphics Commands * 0x07 Optical Memory Device SBC - SCSI-3 Block Commands * 0x08 Medium Changer Device SMC - SCSI-3 Medium Changer Cmds * 0x09 Communications Device SSC - SCSI-3 Stream Commands * 0x0A - 0x0B Graphic Arts Prepress Dev ASC IT8 * 0x0C Storage Array Controller Device SCC-2 - SCSI Controller Commands-2 * 0x0D Enclosure Services SES - SCSI-3 Enclosure Services * 0x0E Simplified Direct Access Device RBC - SCSI Reduced Block Commands * 0x0F Optical Card Reader/Writer Device OCRW - SCSI Specification for * Optical Card Reader/Writer * 0x10 Reserved No command specification * 0x11 Object-Based Storage Device OSD - SCSI Object Based Storage * Device Commands * 0x12 - 0x14 Reserved No command specification * 0x15 Multimedia Media Access Engine RMC - Reduced Multimedia Commands * 0x16 - 0x1E Reserved No command specification * 0x1F Unknown or No Device No command specification */ #pragma mark - #pragma mark Command Definitions by Name /* All SCSI Commands listed in alphabetical order. These are the live * definitions of the commands. All other command lists are informative. */ enum { kSCSICmd_ACCESS_CONTROL_IN = 0x86, kSCSICmd_ACCESS_CONTROL_OUT = 0x87, kSCSICmd_BLANK = 0xA1, kSCSICmd_CHANGE_DEFINITION = 0x40, kSCSICmd_CLOSE_TRACK_SESSION = 0x5B, kSCSICmd_COMPARE = 0x39, kSCSICmd_COPY = 0x18, kSCSICmd_COPY_AND_VERIFY = 0x3A, kSCSICmd_ERASE_10 = 0x2C, kSCSICmd_ERASE_12 = 0xAC, kSCSICmd_EXTENDED_COPY = 0x83, kSCSICmd_FORMAT_UNIT = 0x04, kSCSICmd_GET_CONFIGURATION = 0x46, kSCSICmd_GET_EVENT_STATUS_NOTIFICATION = 0x4A, kSCSICmd_GET_PERFORMANCE = 0xAC, kSCSICmd_INQUIRY = 0x12, kSCSICmd_LOAD_UNLOAD_MEDIUM = 0xA6, kSCSICmd_LOCK_UNLOCK_CACHE = 0x36, kSCSICmd_LOCK_UNLOCK_CACHE_16 = 0x92, kSCSICmd_LOG_SELECT = 0x4C, kSCSICmd_LOG_SENSE = 0x4D, kSCSICmd_MAINTENANCE_IN = 0xA3, kSCSICmd_MAINTENANCE_OUT = 0xA4, kSCSICmd_MECHANISM_STATUS = 0xBD, kSCSICmd_MEDIUM_SCAN = 0x38, kSCSICmd_MODE_SELECT_6 = 0x15, kSCSICmd_MODE_SELECT_10 = 0x55, kSCSICmd_MODE_SENSE_6 = 0x1A, kSCSICmd_MODE_SENSE_10 = 0x5A, kSCSICmd_MOVE_MEDIUM_ATTACHED = 0xA7, kSCSICmd_PAUSE_RESUME = 0x4B, kSCSICmd_PERSISTENT_RESERVE_IN = 0x5E, kSCSICmd_PERSISTENT_RESERVE_OUT = 0x5F, kSCSICmd_PLAY_AUDIO_10 = 0x45, kSCSICmd_PLAY_AUDIO_12 = 0xA5, kSCSICmd_PLAY_AUDIO_MSF = 0x47, kSCSICmd_PLAY_AUDIO_TRACK_INDEX = 0x48, kSCSICmd_PLAY_CD = 0xBC, kSCSICmd_PLAY_RELATIVE_10 = 0x49, kSCSICmd_PLAY_RELATIVE_12 = 0xA9, kSCSICmd_PREFETCH = 0x34, kSCSICmd_PREFETCH_16 = 0x90, kSCSICmd_PREVENT_ALLOW_MEDIUM_REMOVAL = 0x1E, kSCSICmd_READ_6 = 0x08, kSCSICmd_READ_10 = 0x28, kSCSICmd_READ_12 = 0xA8, kSCSICmd_READ_16 = 0x88, kSCSICmd_READ_ATTRIBUTE = 0x8C, kSCSICmd_READ_BUFFER = 0x3C, kSCSICmd_READ_BUFFER_CAPACITY = 0x5C, kSCSICmd_READ_CAPACITY = 0x25, kSCSICmd_READ_CD = 0xBE, kSCSICmd_READ_CD_MSF = 0xB9, kSCSICmd_READ_DEFECT_DATA_10 = 0x37, kSCSICmd_READ_DEFECT_DATA_12 = 0xB7, kSCSICmd_READ_DISC_INFORMATION = 0x51, kSCSICmd_READ_DVD_STRUCTURE = 0xAD, kSCSICmd_READ_DISC_STRUCTURE = 0xAD, kSCSICmd_READ_ELEMENT_STATUS_ATTACHED = 0xB4, kSCSICmd_READ_FORMAT_CAPACITIES = 0x23, kSCSICmd_READ_GENERATION = 0x29, kSCSICmd_READ_HEADER = 0x44, kSCSICmd_READ_LONG = 0x3E, kSCSICmd_READ_MASTER_CUE = 0x59, kSCSICmd_READ_SUB_CHANNEL = 0x42, kSCSICmd_READ_TOC_PMA_ATIP = 0x43, kSCSICmd_READ_TRACK_INFORMATION = 0x52, kSCSICmd_READ_UPDATED_BLOCK_10 = 0x2D, kSCSICmd_REASSIGN_BLOCKS = 0x07, kSCSICmd_REBUILD = 0x81, kSCSICmd_RECEIVE = 0x08, kSCSICmd_RECEIVE_COPY_RESULTS = 0x84, kSCSICmd_RECEIVE_DIAGNOSTICS_RESULTS = 0x1C, kSCSICmd_REDUNDANCY_GROUP_IN = 0xBA, kSCSICmd_REDUNDANCY_GROUP_OUT = 0xBB, kSCSICmd_REGENERATE = 0x82, kSCSICmd_RELEASE_6 = 0x17, kSCSICmd_RELEASE_10 = 0x57, kSCSICmd_REPAIR_TRACK = 0x58, kSCSICmd_REPORT_DEVICE_IDENTIFIER = 0xA3, kSCSICmd_REPORT_KEY = 0xA4, kSCSICmd_REPORT_LUNS = 0xA0, kSCSICmd_REQUEST_SENSE = 0x03, kSCSICmd_RESERVE_6 = 0x16, kSCSICmd_RESERVE_10 = 0x56, kSCSICmd_RESERVE_TRACK = 0x53, kSCSICmd_REZERO_UNIT = 0x01, kSCSICmd_SCAN_MMC = 0xBA, kSCSICmd_SEARCH_DATA_EQUAL_10 = 0x31, kSCSICmd_SEARCH_DATA_EQUAL_12 = 0xB1, kSCSICmd_SEARCH_DATA_HIGH_10 = 0x30, kSCSICmd_SEARCH_DATA_HIGH_12 = 0xB0, kSCSICmd_SEARCH_DATA_LOW_10 = 0x32, kSCSICmd_SEARCH_DATA_LOW_12 = 0xB2, kSCSICmd_SEEK_6 = 0x0B, kSCSICmd_SEEK_10 = 0x2B, kSCSICmd_SEND = 0x0A, kSCSICmd_SEND_CUE_SHEET = 0x5D, kSCSICmd_SEND_DIAGNOSTICS = 0x1D, kSCSICmd_SEND_DVD_STRUCTURE = 0xBF, kSCSICmd_SEND_EVENT = 0xA2, kSCSICmd_SEND_KEY = 0xA3, kSCSICmd_SEND_OPC_INFORMATION = 0x54, kSCSICmd_SERVICE_ACTION_IN = 0x9E, kSCSICmd_SERVICE_ACTION_OUT = 0x9F, kSCSICmd_SET_CD_SPEED = 0xBB, kSCSICmd_SET_DEVICE_IDENTIFIER = 0xA4, kSCSICmd_SET_LIMITS_10 = 0x33, kSCSICmd_SET_LIMITS_12 = 0xB3, kSCSICmd_SET_READ_AHEAD = 0xA7, kSCSICmd_SET_STREAMING = 0xB6, kSCSICmd_SPARE_IN = 0xBC, kSCSICmd_SPARE_OUT = 0xBD, kSCSICmd_START_STOP_UNIT = 0x1B, kSCSICmd_STOP_PLAY_SCAN = 0x4E, kSCSICmd_SYNCHRONIZE_CACHE = 0x35, kSCSICmd_SYNCHRONIZE_CACHE_16 = 0x91, kSCSICmd_TEST_UNIT_READY = 0x00, kSCSICmd_UPDATE_BLOCK = 0x3D, kSCSICmd_UNMAP = 0x42, kSCSICmd_VERIFY_10 = 0x2F, kSCSICmd_VERIFY_12 = 0xAF, kSCSICmd_VERIFY_16 = 0x8F, kSCSICmd_VOLUME_SET_IN = 0xBE, kSCSICmd_VOLUME_SET_OUT = 0xBF, kSCSICmd_WRITE_6 = 0x0A, kSCSICmd_WRITE_10 = 0x2A, kSCSICmd_WRITE_12 = 0xAA, kSCSICmd_WRITE_16 = 0x8A, kSCSICmd_WRITE_AND_VERIFY_10 = 0x2E, kSCSICmd_WRITE_AND_VERIFY_12 = 0xAE, kSCSICmd_WRITE_AND_VERIFY_16 = 0x8E, kSCSICmd_WRITE_ATTRIBUTE = 0x8D, kSCSICmd_WRITE_BUFFER = 0x3B, kSCSICmd_WRITE_LONG = 0x3F, kSCSICmd_WRITE_SAME = 0x41, kSCSICmd_WRITE_SAME_16 = 0x93, kSCSICmd_XDREAD = 0x52, kSCSICmd_XDWRITE = 0x50, kSCSICmd_XDWRITE_EXTENDED = 0x80, kSCSICmd_XDWRITEREAD_10 = 0x53, kSCSICmd_XPWRITE = 0x51, kSCSICmdVariableLengthCDB = 0x7F }; /* Service Action Definitions for the Variable Length CDB (7Fh) command */ enum { kSCSIServiceAction_READ_32 = 0x0009, kSCSIServiceAction_VERIFY_32 = 0x000A, kSCSIServiceAction_WRITE_32 = 0x000B, kSCSIServiceAction_WRITE_AND_VERIFY_32 = 0x000C, kSCSIServiceAction_WRITE_SAME_32 = 0x000D, kSCSIServiceAction_XDREAD_32 = 0x0003, kSCSIServiceAction_XDWRITE_32 = 0x0004, kSCSIServiceAction_XDWRITEREAD_32 = 0x0007, kSCSIServiceAction_XPWRITE_32 = 0x0006 }; /* Service Action Definitions for the MAINTENANCE IN (A3h) command */ enum { kSCSIServiceAction_REPORT_ALIASES = 0x0B, kSCSIServiceAction_REPORT_DEVICE_IDENTIFIER = 0x05, kSCSIServiceAction_REPORT_PRIORITY = 0x0E, kSCSIServiceAction_REPORT_PROVISIONING_INITIALIZATION_PATTERN = 0x1D, kSCSIServiceAction_REPORT_SUPPORTED_OPERATION_CODES = 0x0C, kSCSIServiceAction_REPORT_SUPPORTED_TASK_MANAGEMENT_FUNCTIONS = 0x0D, kSCSIServiceAction_REPORT_TARGET_PORT_GROUPS = 0x0A }; /* Service Action Definitions for the MAINTENANCE OUT (A4h) command */ enum { kSCSIServiceAction_CHANGE_ALIASES = 0x0B, kSCSIServiceAction_SET_DEVICE_IDENTIFIER = 0x06, kSCSIServiceAction_SET_PRIORITY = 0x0E, kSCSIServiceAction_SET_TARGET_PORT_GROUPS = 0x0A }; /* Service Action Definitions for the SERVICE ACTION IN (9Eh) command */ enum { kSCSIServiceAction_GET_LBA_STATUS = 0x12, kSCSIServiceAction_READ_CAPACITY_16 = 0x10, kSCSIServiceAction_READ_LONG_16 = 0x11, }; /* Service Action Definitions for the SERVICE ACTION OUT (9Fh) command */ enum { kSCSIServiceAction_WRITE_LONG_16 = 0x11 }; #pragma mark - #pragma mark Command Definitions by Number #if 0 enum { }; #endif #pragma mark - #pragma mark All Types SPC Commands /* Commands defined by the T10:1236-D SCSI Primary Commands-2 (SPC-2) * command specification. The definitions and section numbers are based on * section 7 of the revision 18, 21 May 2000 version of the specification. * * These commands are defined for all devices. */ enum { kSPCCmd_CHANGE_DEFINITION = 0x40, /* Obsolete */ kSPCCmd_COMPARE = 0x39, /* Sec. 7.2: Optional */ kSPCCmd_COPY = 0x18, /* Sec. 7.3: Optional */ kSPCCmd_COPY_AND_VERIFY = 0x3A, /* Sec. 7.4: Optional */ kSPCCmd_EXTENDED_COPY = 0x83, /* Sec. 7.5: Optional */ kSPCCmd_INQUIRY = 0x12, /* Sec. 7.6: Mandatory */ kSPCCmd_LOG_SELECT = 0x4C, /* Sec. 7.7: Optional */ kSPCCmd_LOG_SENSE = 0x4D, /* Sec. 7.8: Optional */ kSPCCmd_MODE_SELECT_6 = 0x15, /* Sec. 7.9: Device Type * Specific */ kSPCCmd_MODE_SELECT_10 = 0x55, /* Sec. 7.10: Device Type * Specific */ kSPCCmd_MODE_SENSE_6 = 0x1A, /* Sec. 7.11: Device Type * Specific */ kSPCCmd_MODE_SENSE_10 = 0x5A, /* Sec. 7.12: Device Type * Specific */ kSPCCmd_MOVE_MEDIUM_ATTACHED = 0xA7, /* Defined in SMC */ kSPCCmd_PERSISTENT_RESERVE_IN = 0x5E, /* Sec. 7.13: Device Type * Specific */ kSPCCmd_PERSISTENT_RESERVE_OUT = 0x5F, /* Sec. 7.14: Device Type * Specific */ kSPCCmd_PREVENT_ALLOW_MEDIUM_REMOVAL = 0x1E, /* Sec. 7.15: Device Type * Specific */ kSPCCmd_READ_BUFFER = 0x3C, /* Sec. 7.16: Optional */ kSPCCmd_READ_ELEMENT_STATUS_ATTACHED = 0xB4, /* Defined in SMC */ kSPCCmd_RECEIVE_COPY_RESULTS = 0x84, /* Sec. 7.17: Optional */ kSPCCmd_RECEIVE_DIAGNOSTICS_RESULTS = 0x1C, /* Sec. 7.18: Optional */ kSPCCmd_RELEASE_10 = 0x57, /* Sec. 7.19: Device Type * Specific */ kSPCCmd_RELEASE_6 = 0x17, /* Sec. 7.20: Device Type * Specific */ kSPCCmd_REPORT_DEVICE_IDENTIFIER = 0xA3, /* Sec. 7.21: Optional */ kSPCCmd_REPORT_LUNS = 0xA0, /* Sec. 7.22: Mandatory for * LUN Supporting devices*/ kSPCCmd_REQUEST_SENSE = 0x03, /* Sec. 7.23: Device Type * Specific */ kSPCCmd_RESERVE_10 = 0x56, /* Sec. 7.24: Device Type * Specific */ kSPCCmd_RESERVE_6 = 0x16, /* Sec. 7.25: Device Type * Specific */ kSPCCmd_SEND_DIAGNOSTICS = 0x1D, /* Sec. 7.26: Optional */ kSPCCmd_SET_DEVICE_IDENTIFIER = 0xA4, /* Sec. 7.27: Optional */ kSPCCmd_TEST_UNIT_READY = 0x00, /* Sec. 7.28: Mandatory */ kSPCCmd_WRITE_BUFFER = 0x3B /* Sec. 7.29: Optional */ }; #pragma mark - #pragma mark 0x00 SBC Direct Access Commands /* Commands defined by the T10:990-D SCSI-3 Block Commands (SBC) command * specification. The definitions and section numbers are based on section 6.1 * of the revision 8c, 13 November 1997 version of the specification. */ enum { kSBCCmd_CHANGE_DEFINITION = 0x40, /* Obsolete */ kSBCCmd_COMPARE = 0x39, /* SPC: Optional */ kSBCCmd_COPY = 0x18, /* SPC: Optional */ kSBCCmd_COPY_AND_VERIFY = 0x3A, /* SPC: Optional*/ kSBCCmd_FORMAT_UNIT = 0x04, /* Sec. 6.1.1: Mandatory */ kSBCCmd_INQUIRY = 0x12, /* SPC: Mandatory */ kSBCCmd_LOCK_UNLOCK_CACHE = 0x36, /* Sec. 6.1.2: Optional */ kSBCCmd_LOG_SELECT = 0x4C, /* SPC: Optional */ kSBCCmd_LOG_SENSE = 0x4D, /* SPC: Optional */ kSBCCmd_MODE_SELECT_6 = 0x15, /* SPC: Optional */ kSBCCmd_MODE_SELECT_10 = 0x55, /* SPC: Optional */ kSBCCmd_MODE_SENSE_6 = 0x1A, /* SPC: Optional */ kSBCCmd_MODE_SENSE_10 = 0x5A, /* SPC: Optional */ kSBCCmd_MOVE_MEDIUM_ATTACHED = 0xA7, /* SMC: Optional */ kSBCCmd_PERSISTENT_RESERVE_IN = 0x5E, /* SPC: Optional */ kSBCCmd_PERSISTENT_RESERVE_OUT = 0x5F, /* SPC: Optional */ kSBCCmd_PREFETCH = 0x34, /* Sec. 6.1.3: Optional */ kSBCCmd_PREVENT_ALLOW_MEDIUM_REMOVAL = 0x1E, /* SPC: Optional */ kSBCCmd_READ_6 = 0x08, /* Sec. 6.1.4: Mandatory */ kSBCCmd_READ_10 = 0x28, /* Sec. 6.1.5: Mandatory */ kSBCCmd_READ_12 = 0xA8, /* Sec. 6.2.4: Optional */ kSBCCmd_READ_BUFFER = 0x3C, /* SPC: Optional */ kSBCCmd_READ_CAPACITY = 0x25, /* Sec. 6.1.6: Mandatory */ kSBCCmd_READ_DEFECT_DATA_10 = 0x37, /* Sec. 6.1.7: Optional */ kSBCCmd_READ_DEFECT_DATA_12 = 0xB7, /* Sec. 6.2.5: Optional */ kSBCCmd_READ_ELEMENT_STATUS_ATTACHED = 0xB4, /* SMC: Optional */ kSBCCmd_READ_GENERATION = 0x29, /* Sec. 6.2.6: Optional */ kSBCCmd_READ_LONG = 0x3E, /* Sec. 6.1.8: Optional */ kSBCCmd_READ_UPDATED_BLOCK_10 = 0x2D, /* Sec. 6.2.7: Optional */ kSBCCmd_REASSIGN_BLOCKS = 0x07, /* Sec. 6.1.9: Optional */ kSBCCmd_REBUILD = 0x81, /* Sec. 6.1.10: Optional */ kSBCCmd_RECEIVE_DIAGNOSTICS_RESULTS = 0x1C, /* SPC: Optional */ kSBCCmd_REGENERATE = 0x82, /* Sec. 6.1.11: Optional */ kSBCCmd_RELEASE_6 = 0x17, /* SPC: Optional */ kSBCCmd_RELEASE_10 = 0x57, /* SPC: Mandatory */ kSBCCmd_REPORT_LUNS = 0xA0, /* SPC: Optional */ kSBCCmd_REQUEST_SENSE = 0x03, /* SPC: Mandatory */ kSBCCmd_RESERVE_6 = 0x16, /* SPC: Optional */ kSBCCmd_RESERVE_10 = 0x56, /* SPC: Mandatory */ kSBCCmd_REZERO_UNIT = 0x01, /* Obsolete */ kSBCCmd_SEARCH_DATA_EQUAL_10 = 0x31, /* Obsolete */ kSBCCmd_SEARCH_DATA_HIGH_10 = 0x30, /* Obsolete */ kSBCCmd_SEARCH_DATA_LOW_10 = 0x32, /* Obsolete */ kSBCCmd_SEEK_6 = 0x0B, /* Obsolete */ kSBCCmd_SEEK_10 = 0x2B, /* Sec. 6.1.12: Optional */ kSBCCmd_SEND_DIAGNOSTICS = 0x1D, /* SPC: Mandatory */ kSBCCmd_SET_LIMITS_10 = 0x33, /* Sec. 6.1.13: Optional */ kSBCCmd_SET_LIMITS_12 = 0xB3, /* Sec. 6.2.8: Optional */ kSBCCmd_START_STOP_UNIT = 0x1B, /* Sec. 6.1.14: Optional */ kSBCCmd_SYNCHRONIZE_CACHE = 0x35, /* Sec. 6.1.15: Optional */ kSBCCmd_TEST_UNIT_READY = 0x00, /* SPC: Mandatory */ kSBCCmd_UPDATE_BLOCK = 0x3D, /* Sec. 6.2.9: Optional */ kSBCCmd_VERIFY_10 = 0x2F, /* Sec. 6.1.16: Optional */ kSBCCmd_WRITE_6 = 0x0A, /* Sec. 6.1.17: Optional */ kSBCCmd_WRITE_10 = 0x2A, /* Sec. 6.1.18: Optional */ kSBCCmd_WRITE_12 = 0xAA, /* Sec. 6.2.13: Optional */ kSBCCmd_WRITE_AND_VERIFY_10 = 0x2E, /* Sec. 6.1.19: Optional */ kSBCCmd_WRITE_AND_VERIFY_12 = 0xAE, /* Sec. 6.2.15: Optional */ kSBCCmd_WRITE_BUFFER = 0x3B, /* SPC: Optional */ kSBCCmd_WRITE_LONG = 0x3F, /* Sec. 6.1.20: Optional */ kSBCCmd_WRITE_SAME = 0x41, /* Sec. 6.1.21: Optional */ kSBCCmd_XDREAD = 0x52, /* Sec. 6.1.22: Optional */ kSBCCmd_XDWRITE = 0x50, /* Sec. 6.1.23: Optional */ kSBCCmd_XDWRITE_EXTENDED = 0x80, /* Sec. 6.1.24: Optional */ kSBCCmd_XPWRITE = 0x51 /* Sec. 6.1.25: Optional */ }; #pragma mark - #pragma mark 0x01 SSC Sequential Access Commands /* Commands defined by the T10:997-D SCSI-3 Stream Commands (SSC) command * specification. The definitions and section numbers are based on section 5 * of the revision 22, January 1, 2000 version of the specification. */ enum { kSSCSeqCmd_CHANGE_DEFINITION = 0x40, /* Obsolete */ kSSCSeqCmd_COMPARE = 0x39, /* SPC: Optional */ kSSCSeqCmd_COPY = 0x18, /* SPC: Optional */ kSSCSeqCmd_COPY_AND_VERIFY = 0x3A, /* SPC: Optional */ kSSCSeqCmd_ERASE = 0x19, /* Sec. 5.3.1: Mandatory */ kSSCSeqCmd_FORMAT_MEDIUM = 0x04, /* Sec. 5.3.2: Optional */ kSSCSeqCmd_INQUIRY = 0x12, /* SPC: Mandatory */ kSSCSeqCmd_LOAD_UNLOAD = 0x1B, /* Sec. 5.3.3: Optional */ kSSCSeqCmd_LOCATE = 0x2B, /* Sec. 5.3.4: Optional */ kSSCSeqCmd_LOG_SELECT = 0x4C, /* SPC: Optional */ kSSCSeqCmd_LOG_SENSE = 0x4D, /* SPC: Optional */ kSSCSeqCmd_MODE_SELECT_6 = 0x15, /* SPC: Mandatory */ kSSCSeqCmd_MODE_SELECT_10 = 0x55, /* SPC: Optional */ kSSCSeqCmd_MODE_SENSE_6 = 0x1A, /* SPC: Mandatory */ kSSCSeqCmd_MODE_SENSE_10 = 0x5A, /* SPC: Optional */ kSSCSeqCmd_MOVE_MEDIUM = 0xA5, /* SMC: Optional */ kSSCSeqCmd_MOVE_MEDIUM_ATTACHED = 0xA7, /* SMC: Optional */ kSSCSeqCmd_PERSISTENT_RESERVE_IN = 0x5E, /* SPC: Optional */ kSSCSeqCmd_PERSISTENT_RESERVE_OUT = 0x5F, /* SPC: Optional */ kSSCSeqCmd_PREVENT_ALLOW_MEDIUM_REMOVAL = 0x1E, /* SPC: Optional */ kSSCSeqCmd_READ_6 = 0x08, /* Sec. 5.3.5: Mandatory */ kSSCSeqCmd_READ_BLOCK_LIMITS = 0x05, /* Sec. 5.3.6: Mandatory */ kSSCSeqCmd_READ_BUFFER = 0x3C, /* SPC: Optional */ kSSCSeqCmd_READ_ELEMENT_STATUS = 0xB8, /* SMC: Optional */ kSSCSeqCmd_READ_ELEMENT_STATUS_ATTACHED = 0xB4, /* SMC: Optional */ kSSCSeqCmd_READ_POSITION = 0x34, /* Sec. 5.3.7: Mandatory */ kSSCSeqCmd_READ_REVERSE = 0x0F, /* Sec. 5.3.8: Optional */ kSSCSeqCmd_RECEIVE_DIAGNOSTICS_RESULTS = 0x1C, /* SPC: Optional */ kSSCSeqCmd_RECOVER_BUFFERED_DATA = 0x14, /* Sec. 5.3.9: Optional */ kSSCSeqCmd_RELEASE_6 = 0x17, /* SPC: Mandatory */ kSSCSeqCmd_RELEASE_10 = 0x57, /* SPC: Mandatory */ kSSCSeqCmd_REPORT_DENSITY_SUPPORT = 0x44, /* Sec. 5.3.10: Mandatory*/ kSSCSeqCmd_REPORT_LUNS = 0xA0, /* SPC: Mandatory */ kSSCSeqCmd_REQUEST_SENSE = 0x03, /* SPC: Mandatory */ kSSCSeqCmd_RESERVE_6 = 0x16, /* SPC: Mandatory */ kSSCSeqCmd_RESERVE_10 = 0x56, /* SPC: Mandatory */ kSSCSeqCmd_REWIND = 0x01, /* Sec. 5.3.11: Mandatory*/ kSSCSeqCmd_SEND_DIAGNOSTICS = 0x1D, /* SPC: Mandatory */ kSSCSeqCmd_SPACE = 0x11, /* Sec. 5.3.12: Mandatory*/ kSSCSeqCmd_TEST_UNIT_READY = 0x00, /* SPC: Mandatory */ kSSCSeqCmd_VERIFY_6 = 0x13, /* Sec. 5.3.13: Optional */ kSSCSeqCmd_WRITE_6 = 0x0A, /* Sec. 5.3.14: Mandatory*/ kSSCSeqCmd_WRITE_BUFFER = 0x3B, /* SPC: Optional */ kSSCSeqCmd_WRITE_FILEMARKS = 0x10 /* Sec. 5.3.15: Mandatory*/ }; #pragma mark - #pragma mark 0x02 SSC Printer Commands /* Commands defined by the T10:997-D SCSI-3 Stream Commands (SSC) command * specification. The definitions and section numbers are based on section 6 * of the revision 22, January 1, 2000 version of the specification. */ enum { kSSCPrinterCmd_CHANGE_DEFINITION = 0x40, /* Obsolete */ kSSCPrinterCmd_COMPARE = 0x39, /* SPC: Optional */ kSSCPrinterCmd_COPY = 0x18, /* SPC: Optional */ kSSCPrinterCmd_COPY_AND_VERIFY = 0x3A, /* SPC: Optional */ kSSCPrinterCmd_FORMAT = 0x04, /* Sec. 6.2.1: Optional */ kSSCPrinterCmd_INQUIRY = 0x12, /* SPC: Mandatory */ kSSCPrinterCmd_LOG_SELECT = 0x4C, /* SPC: Optional */ kSSCPrinterCmd_LOG_SENSE = 0x4D, /* SPC: Optional */ kSSCPrinterCmd_MODE_SELECT_6 = 0x15, /* SPC: Mandatory */ kSSCPrinterCmd_MODE_SELECT_10 = 0x55, /* SPC: Optional */ kSSCPrinterCmd_MODE_SENSE_6 = 0x1A, /* SPC: Mandatory */ kSSCPrinterCmd_MODE_SENSE_10 = 0x5A, /* SPC: Optional */ kSSCPrinterCmd_PERSISTENT_RESERVE_IN = 0x5E, /* SPC: Optional */ kSSCPrinterCmd_PERSISTENT_RESERVE_OUT = 0x5F, /* SPC: Optional */ kSSCPrinterCmd_PRINT = 0x0A, /* Sec. 6.2.2: Mandatory */ kSSCPrinterCmd_READ_BUFFER = 0x3C, /* SPC: Optional */ kSSCPrinterCmd_RECEIVE_DIAGNOSTICS_RESULTS = 0x1C, /* SPC: Optional */ kSSCPrinterCmd_RECOVER_BUFFERED_DATA = 0x14, /* Sec. 6.2.3: Optional */ kSSCPrinterCmd_RELEASE_6 = 0x17, /* SPC: Mandatory */ kSSCPrinterCmd_RELEASE_10 = 0x57, /* SPC: Mandatory */ kSSCPrinterCmd_REPORT_LUNS = 0xA0, /* SPC: Mandatory */ kSSCPrinterCmd_REQUEST_SENSE = 0x03, /* SPC: Mandatory */ kSSCPrinterCmd_RESERVE_6 = 0x16, /* SPC: Mandatory */ kSSCPrinterCmd_RESERVE_10 = 0x56, /* SPC: Mandatory */ kSSCPrinterCmd_SEND_DIAGNOSTICS = 0x1D, /* SPC: Mandatory */ kSSCPrinterCmd_SLEW_AND_PRINT = 0x0B, /* Sec. 6.2.4: Optional */ kSSCPrinterCmd_STOP_PRINT = 0x1B, /* Sec. 6.2.5: Optional */ kSSCPrinterCmd_SYNCHRONIZE_BUFFER = 0x10, /* Sec. 6.2.6: Optional */ kSSCPrinterCmd_TEST_UNIT_READY = 0x00, /* SPC: Mandatory */ kSSCPrinterCmd_WRITE_BUFFER = 0x3B /* SPC: Optional */ }; #pragma mark - #pragma mark 0x03 SPC Processor Commands /* Commands defined by the T10:1236-D SCSI Primary Commands-2 (SPC-2) * command specification. The definitions and section numbers are based on * section 9 of the revision 18, 21 May 2000 version of the specification. */ enum { kSPCProcCmd_CHANGE_DEFINITION = 0x40, /* Obsolete */ kSPCProcCmd_COMPARE = 0x39, /* Sec. 7.2: Optional */ kSPCProcCmd_COPY = 0x18, /* Sec. 7.3: Optional */ kSPCProcCmd_COPY_AND_VERIFY = 0x3A, /* Sec. 7.4: Optional */ kSPCProcCmd_EXTENDED_COPY = 0x83, /* Sec. 7.5: Optional */ kSPCProcCmd_INQUIRY = 0x12, /* Sec. 7.6: Mandatory */ kSPCProcCmd_LOG_SELECT = 0x4C, /* Sec. 7.7: Optional */ kSPCProcCmd_LOG_SENSE = 0x4D, /* Sec. 7.8: Optional */ kSPCProcCmd_PERSISTENT_RESERVE_IN = 0x5E, /* Sec. 7.13: Optional */ kSPCProcCmd_PERSISTENT_RESERVE_OUT = 0x5F, /* Sec. 7.14: Optional */ kSPCProcCmd_READ_BUFFER = 0x3C, /* Sec. 7.16: Optional */ kSPCProcCmd_RECEIVE = 0x08, /* Sec. 9.2: Optional */ kSPCProcCmd_RECEIVE_COPY_RESULTS = 0x84, /* Sec. 7.17: Optional */ kSPCProcCmd_RECEIVE_DIAGNOSTICS_RESULTS = 0x1C, /* Sec. 7.18: Optional */ kSPCProcCmd_RELEASE_10 = 0x57, /* Sec. 7.19: Optional */ kSPCProcCmd_RELEASE_6 = 0x17, /* Sec. 7.20: Optional */ kSPCProcCmd_REPORT_LUNS = 0xA0, /* Sec. 7.22: Optional */ kSPCProcCmd_REQUEST_SENSE = 0x03, /* Sec. 7.23: Mandatory */ kSPCProcCmd_RESERVE_10 = 0x56, /* Sec. 7.24: Optional */ kSPCProcCmd_RESERVE_6 = 0x16, /* Sec. 7.25: Optional */ kSPCProcCmd_SEND = 0x0A, /* Sec. 9.3: Optional */ kSPCProcCmd_SEND_DIAGNOSTICS = 0x1D, /* Sec. 7.26: Mandatory */ kSPCProcCmd_TEST_UNIT_READY = 0x00, /* Sec. 7.27: Mandatory */ kSPCProcCmd_WRITE_BUFFER = 0x3B /* Sec. 7.29: Optional */ }; #pragma mark - #pragma mark 0x04 SBC Write Once Commands /* Commands defined by the T10:990-D SCSI-3 Block Commands (SBC) command * specification. The definitions and section numbers are based on section 6.3 * of the revision 8c, 13 November 1997 version of the specification. */ enum { kSBCWOCmd_CHANGE_DEFINITION = 0x40, /* SPC: Optional */ kSBCWOCmd_COMPARE = 0x39, /* SPC: Optional */ kSBCWOCmd_COPY = 0x18, /* SPC: Optional */ kSBCWOCmd_COPY_AND_VERIFY = 0x3A, /* SPC: Optional*/ kSBCWOCmd_INQUIRY = 0x12, /* SPC: Mandatory */ kSBCWOCmd_LOCK_UNLOCK_CACHE = 0x36, /* Sec. 6.1.2: Optional */ kSBCWOCmd_LOG_SELECT = 0x4C, /* SPC: Optional */ kSBCWOCmd_LOG_SENSE = 0x4D, /* SPC: Optional */ kSBCWOCmd_MEDIUM_SCAN = 0x38, /* Sec. 6.2.3: Optional */ kSBCWOCmd_MODE_SELECT_6 = 0x15, /* SPC: Optional */ kSBCWOCmd_MODE_SELECT_10 = 0x55, /* SPC: Optional */ kSBCWOCmd_MODE_SENSE_6 = 0x1A, /* SPC: Optional */ kSBCWOCmd_MODE_SENSE_10 = 0x5A, /* SPC: Optional */ kSBCWOCmd_MOVE_MEDIUM = 0xA5, /* SMC: Optional */ kSBCWOCmd_PERSISTENT_RESERVE_IN = 0x5E, /* SPC: Optional */ kSBCWOCmd_PERSISTENT_RESERVE_OUT = 0x5F, /* SPC: Optional */ kSBCWOCmd_PREFETCH = 0x34, /* Sec. 6.1.3: Optional */ kSBCWOCmd_PREVENT_ALLOW_MEDIUM_REMOVAL = 0x1E, /* SPC: Optional */ kSBCWOCmd_READ_6 = 0x08, /* Sec. 6.1.4: Optional */ kSBCWOCmd_READ_10 = 0x28, /* Sec. 6.1.5: Mandatory */ kSBCWOCmd_READ_12 = 0xA8, /* Sec. 6.2.4: Optional */ kSBCWOCmd_READ_BUFFER = 0x3C, /* SPC: Optional */ kSBCWOCmd_READ_CAPACITY = 0x25, /* Sec. 6.1.6: Mandatory */ kSBCWOCmd_READ_ELEMENT_STATUS = 0xB8, /* SMC: Optional */ kSBCWOCmd_READ_LONG = 0x3E, /* Sec. 6.1.8: Optional */ kSBCWOCmd_REASSIGN_BLOCKS = 0x07, /* Sec. 6.1.9: Optional */ kSBCWOCmd_RECEIVE_DIAGNOSTICS_RESULTS = 0x1C, /* SPC: Optional */ kSBCWOCmd_RELEASE_6 = 0x17, /* SPC: Optional */ kSBCWOCmd_RELEASE_10 = 0x57, /* SPC: Mandatory */ kSBCWOCmd_REQUEST_SENSE = 0x03, /* SPC: Mandatory */ kSBCWOCmd_RESERVE_6 = 0x16, /* SPC: Optional */ kSBCWOCmd_RESERVE_10 = 0x56, /* SPC: Mandatory */ kSBCWOCmd_REZERO_UNIT = 0x01, /* Obsolete */ kSBCWOCmd_SEARCH_DATA_EQUAL_10 = 0x31, /* Obsolete */ kSBCWOCmd_SEARCH_DATA_EQUAL_12 = 0xB1, /* Obsolete */ kSBCWOCmd_SEARCH_DATA_HIGH_10 = 0x30, /* Obsolete */ kSBCWOCmd_SEARCH_DATA_HIGH_12 = 0xB0, /* Obsolete */ kSBCWOCmd_SEARCH_DATA_LOW_10 = 0x32, /* Obsolete */ kSBCWOCmd_SEARCH_DATA_LOW_12 = 0xB2, /* Obsolete */ kSBCWOCmd_SEEK_6 = 0x0B, /* Obsolete */ kSBCWOCmd_SEEK_10 = 0x2B, /* Sec. 6.1.12: Optional */ kSBCWOCmd_SEND_DIAGNOSTICS = 0x1D, /* SPC: Mandatory */ kSBCWOCmd_SET_LIMITS_10 = 0x33, /* Sec. 6.1.13: Optional */ kSBCWOCmd_SET_LIMITS_12 = 0xB3, /* Sec. 6.2.8: Optional */ kSBCWOCmd_START_STOP_UNIT = 0x1B, /* Sec. 6.1.14: Optional */ kSBCWOCmd_SYNCHRONIZE_CACHE = 0x35, /* Sec. 6.1.15: Optional */ kSBCWOCmd_TEST_UNIT_READY = 0x00, /* SPC: Mandatory */ kSBCWOCmd_VERIFY_10 = 0x2F, /* Sec. 6.2.10: Optional */ kSBCWOCmd_VERIFY_12 = 0xAF, /* Sec. 6.2.11: Optional */ kSBCWOCmd_WRITE_6 = 0x0A, /* Sec. 6.1.17: Optional */ kSBCWOCmd_WRITE_10 = 0x2A, /* Sec. 6.2.10: Mandatory*/ kSBCWOCmd_WRITE_12 = 0xAA, /* Sec. 6.2.13: Optional */ kSBCWOCmd_WRITE_AND_VERIFY_10 = 0x2E, /* Sec. 6.2.14: Optional */ kSBCWOCmd_WRITE_AND_VERIFY_12 = 0xAE, /* Sec. 6.2.15: Optional */ kSBCWOCmd_WRITE_BUFFER = 0x3B, /* SPC: Optional */ kSBCWOCmd_WRITE_LONG = 0x3F /* Sec. 6.1.20: Optional */ }; #pragma mark - #pragma mark 0x05 MMC CD-ROM Commands /* Commands defined by the T10:1363-D SCSI Multimedia Commands-3 (MMC-3) * specification. The definitions and section numbers are based on section 6.1 * of the revision 01, March 03, 2000 version of the specification. * * NOTE: The comments following each command may not be accurate. These are * not from the MMC-3 specification, but have been derived from the SCSI-2 and * original MMC specifications. Unlike the other SCSI command specifications, * MMC-2 and MMC-3 do not provide a command requirement type and therefore does * not relist the SPC commands with these requirements as they apply to MMC * devices. The MMC-2 and MMC-3 specifications also refer back to the SBC * specification which seems invalid since MMC devices do not represent a * Peripheral Device Type defined by SBC. It is assumed that the SBC * references refer to the Peripheral Device Type 0x00 - Direct Access Commands * definitions from that specification. */ enum { kMMCCmd_BLANK = 0xA1, /* Sec. 6.1.1: */ kMMCCmd_CHANGE_DEFINITION = 0x40, /* Obsolete */ kMMCCmd_CLOSE_TRACK_SESSION = 0x5B, /* Sec. 6.1.2: */ kMMCCmd_COMPARE = 0x39, /* SPC: Optional */ kMMCCmd_COPY = 0x18, /* SPC: Optional */ kMMCCmd_COPY_AND_VERIFY = 0x3A, /* SPC: Optional */ kMMCCmd_ERASE = 0x2C, /* SBC: */ kMMCCmd_FORMAT_UNIT = 0x04, /* Sec. 6.1.3: */ kMMCCmd_GET_CONFIGURATION = 0x46, /* Sec. 6.1.4: */ kMMCCmd_GET_EVENT_STATUS_NOTIFICATION = 0x4A, /* Sec. 6.1.5: */ kMMCCmd_GET_PERFORMANCE = 0xAC, /* Sec. 6.1.6: */ kMMCCmd_INQUIRY = 0x12, /* SPC: Mandatory */ kMMCCmd_LOAD_UNLOAD_MEDIUM = 0xA6, /* Sec. 6.1.7: */ kMMCCmd_LOG_SELECT = 0x4C, /* SPC: Optional */ kMMCCmd_LOG_SENSE = 0x4D, /* SPC: Optional */ kMMCCmd_MECHANISM_STATUS = 0xBD, /* Sec. 6.1.8: */ kMMCCmd_MODE_SELECT_6 = 0x15, /* SPC: Mandatory */ kMMCCmd_MODE_SELECT_10 = 0x55, /* SPC: Mandatory */ kMMCCmd_MODE_SENSE_6 = 0x1A, /* SPC: Mandatory */ kMMCCmd_MODE_SENSE_10 = 0x5A, /* SPC: Mandatory */ kMMCCmd_PAUSE_RESUME = 0x4B, /* Sec. 6.1.9: */ kMMCCmd_PLAY_AUDIO_10 = 0x45, /* Sec. 6.1.10: */ kMMCCmd_PLAY_AUDIO_12 = 0xA5, /* Sec. 6.1.11: */ kMMCCmd_PLAY_AUDIO_MSF = 0x47, /* Sec. 6.1.12: */ kMMCCmd_PLAY_AUDIO_TRACK_INDEX = 0x48, /* Obsolete */ kMMCCmd_PLAY_CD = 0xBC, /* Sec. 6.1.13: */ kMMCCmd_PLAY_RELATIVE_10 = 0x49, /* Obsolete */ kMMCCmd_PLAY_RELATIVE_12 = 0xA9, /* Obsolete */ kMMCCmd_PREFETCH = 0x34, /* Optional */ kMMCCmd_PREVENT_ALLOW_MEDIUM_REMOVAL = 0x1E, /* Optional */ kMMCCmd_READ_6 = 0x08, /* Optional */ kMMCCmd_READ_10 = 0x28, /* Mandatory */ kMMCCmd_READ_12 = 0xA8, /* Optional */ kMMCCmd_READ_BUFFER = 0x3C, /* Optional */ kMMCCmd_READ_BUFFER_CAPACITY = 0x5C, /* Sec. 6.1.15: */ kMMCCmd_READ_CD = 0xBE, /* Sec. 6.1.16: */ kMMCCmd_READ_CD_MSF = 0xB9, /* Sec. 6.1.17: */ kMMCCmd_READ_CAPACITY = 0x25, /* Sec. 6.1.18: */ kMMCCmd_READ_DISC_INFORMATION = 0x51, /* Sec. 6.1.19: */ kMMCCmd_READ_DVD_STRUCTURE = 0xAD, /* Sec. 6.1.20: */ kMMCCmd_READ_DISC_STRUCTURE = 0xAD, /* Sec. 6.1.20: */ kMMCCmd_READ_FORMAT_CAPACITIES = 0x23, /* Sec. 6.1.21: */ kMMCCmd_READ_HEADER = 0x44, /* Sec. 6.1.22: */ kMMCCmd_READ_LONG = 0x3E, /* Optional */ kMMCCmd_READ_MASTER_CUE = 0x59, /* Sec. 6.1.23: */ kMMCCmd_READ_SUB_CHANNEL = 0x42, /* Sec. 6.1.24: */ kMMCCmd_READ_TOC_PMA_ATIP = 0x43, /* Sec. 6.1.25: */ kMMCCmd_READ_TRACK_INFORMATION = 0x52, /* Sec. 6.1.27: */ kMMCCmd_RECEIVE_DIAGNOSTICS_RESULTS = 0x1C, /* Optional */ kMMCCmd_RELEASE_6 = 0x17, /* Mandatory */ kMMCCmd_RELEASE_10 = 0x57, /* Optional */ kMMCCmd_REPAIR_TRACK = 0x58, /* Sec. 6.1.28: */ kMMCCmd_REPORT_KEY = 0xA4, /* Sec. 6.1.29: */ kMMCCmd_REQUEST_SENSE = 0x03, /* Mandatory */ kMMCCmd_RESERVE_6 = 0x16, /* Mandatory */ kMMCCmd_RESERVE_10 = 0x56, /* Optional */ kMMCCmd_RESERVE_TRACK = 0x53, /* Sec. 6.1.30: */ kMMCCmd_SCAN_MMC = 0xBA, /* Sec. 6.1.31: */ kMMCCmd_SEARCH_DATA_EQUAL_10 = 0x31, /* Obsolete */ kMMCCmd_SEARCH_DATA_EQUAL_12 = 0xB1, /* Obsolete */ kMMCCmd_SEARCH_DATA_HIGH_10 = 0x30, /* Obsolete */ kMMCCmd_SEARCH_DATA_HIGH_12 = 0xB0, /* Obsolete */ kMMCCmd_SEARCH_DATA_LOW_10 = 0x32, /* Obsolete */ kMMCCmd_SEARCH_DATA_LOW_12 = 0xB2, /* Obsolete */ kMMCCmd_SEEK_6 = 0x0B, /* Obsolete */ kMMCCmd_SEEK_10 = 0x2B, /* SBC: */ kMMCCmd_SEND_CUE_SHEET = 0x5D, /* Sec. 6.1.32: */ kMMCCmd_SEND_DIAGNOSTICS = 0x1D, /* Mandatory */ kMMCCmd_SEND_DVD_STRUCTURE = 0xBF, /* Sec. 6.1.33: */ kMMCCmd_SEND_EVENT = 0xA2, /* Sec. 6.1.34: */ kMMCCmd_SEND_KEY = 0xA3, /* Sec. 6.1.35: */ kMMCCmd_SEND_OPC_INFORMATION = 0x54, /* Sec. 6.1.36: */ kMMCCmd_SET_CD_SPEED = 0xBB, /* Sec. 6.1.37: */ kMMCCmd_SET_LIMITS_10 = 0x33, /* Optional */ kMMCCmd_SET_LIMITS_12 = 0xB3, /* Optional */ kMMCCmd_SET_READ_AHEAD = 0xA7, /* Sec. 6.1.38: */ kMMCCmd_SET_STREAMING = 0xB6, /* Sec. 6.1.39: */ kMMCCmd_START_STOP_UNIT = 0x1B, /* Optional */ kMMCCmd_STOP_PLAY_SCAN = 0x4E, /* Sec. 6.1.40: */ kMMCCmd_SYNCHRONIZE_CACHE = 0x35, /* Sec. 6.1.41: */ kMMCCmd_TEST_UNIT_READY = 0x00, /* Mandatory */ kMMCCmd_VERIFY_10 = 0x2F, /* Optional */ kMMCCmd_VERIFY_12 = 0xAF, /* Optional */ kMMCCmd_WRITE_10 = 0x2A, /* Sec. 6.1.42: */ kMMCCmd_WRITE_12 = 0xAA, /* Sec. 6.1.43: */ kMMCCmd_WRITE_AND_VERIFY_10 = 0x2E, /* Sec. 6.1.44: */ kMMCCmd_WRITE_BUFFER = 0x3B /* Optional */ }; #pragma mark - #pragma mark 0x06 SGC Scanner Commands /* Commands defined by the T10:998-D SCSI-3 Graphics Commands (SGC) * specification. The definitions and section numbers are based on section 6 * of the revision 0, April 1995 version of the specification. */ enum { kSGCCmd_CHANGE_DEFINITION = 0x40, /* SPC: Optional */ kSGCCmd_COMPARE = 0x39, /* SPC: Optional */ kSGCCmd_COPY = 0x18, /* SPC: Optional */ kSGCCmd_COPY_AND_VERIFY = 0x3A, /* SPC: Optional */ kSGCCmd_GET_DATA_BUFFER_STATUS = 0x34, /* Sec. 6.1.1: Optional */ kSGCCmd_GET_WINDOW = 0x25, /* Sec. 6.1.2: Optional */ kSGCCmd_INQUIRY = 0x12, /* SPC: Mandatory */ kSGCCmd_LOG_SELECT = 0x4C, /* SPC: Optional */ kSGCCmd_LOG_SENSE = 0x4D, /* SPC: Optional */ kSGCCmd_MODE_SELECT_6 = 0x15, /* SPC: Optional */ kSGCCmd_MODE_SELECT_10 = 0x55, /* SPC: Optional */ kSGCCmd_MODE_SENSE_6 = 0x1A, /* SPC: Optional */ kSGCCmd_MODE_SENSE_10 = 0x5A, /* SPC: Optional */ kSGCCmd_OBJECT_POSITION = 0x31, /* Sec. 6.1.3: Optional */ kSGCCmd_PORT_STATUS = 0x11, /* SPC (??): Mandatory * for dual port devices */ kSGCCmd_READ = 0x28, /* Sec. 6.1.4: Mandatory */ kSGCCmd_READ_BUFFER = 0x3C, /* SPC: Optional */ kSGCCmd_RECEIVE_DIAGNOSTICS_RESULTS = 0x1C, /* SPC: Optional */ kSGCCmd_RELEASE_6 = 0x17, /* SPC: Mandatory */ kSGCCmd_REQUEST_SENSE = 0x03, /* SPC: Mandatory */ kSGCCmd_RESERVE_6 = 0x16, /* SPC: Mandatory */ kSGCCmd_SCAN = 0x1B, /* Sec. 6.1.5: Optional */ kSGCCmd_SEND = 0x1B, /* Sec. 6.1.6: Optional */ kSGCCmd_SEND_DIAGNOSTICS = 0x1D, /* SPC: Mandatory */ kSGCCmd_SET_WINDOW = 0x24, /* Sec. 6.1.7: Mandatory */ kSGCCmd_TEST_UNIT_READY = 0x00, /* SPC: Mandatory */ kSGCCmd_WRITE_BUFFER = 0x3B /* SPC: Optional */ }; #pragma mark - #pragma mark 0x07 SBC Optical Media Commands /* Commands defined by the T10:990-D SCSI-3 Block Commands (SBC) * (revision 8c, 13 November 1998) command specification. */ #pragma mark - #pragma mark 0x08 SMC Medium Changer Commands /* Commands defined by the T10:1228-D SCSI-3 Medium Changer Commands-2 (SMC-2) * (revision 0, March 16, 2000) command specification. */ enum { /* Commands For Independent Medium Changers */ kSMCCmd_EXCHANGE_MEDIUM = 0xA6, /* Optional */ kSMCCmd_INITIALIZE_ELEMENT_STATUS = 0x07, /* Optional */ kSMCCmd_MODE_SELECT_6 = 0x15, /* Optional */ kSMCCmd_MODE_SELECT_10 = 0x55, /* Optional */ kSMCCmd_MODE_SENSE_6 = 0x1A, /* Optional */ kSMCCmd_MODE_SENSE_10 = 0x5A, /* Optional */ kSMCCmd_MOVE_MEDIUM = 0xA5, /* Mandatory */ kSMCCmd_PERSISTENT_RESERVE_IN = 0x5E, /* Optional */ kSMCCmd_PERSISTENT_RESERVE_OUT = 0x5F, /* Optional */ kSMCCmd_POSITION_TO_ELEMENT = 0x2B, /* Optional */ kSMCCmd_READ_ELEMENT_STATUS = 0xB8, /* Mandatory */ kSMCCmd_RELEASE_ELEMENT_6 = 0x16, /* Optional */ kSMCCmd_RELEASE_ELEMENT_10 = 0x56, /* Optional */ kSMCCmd_REQUEST_VOLUME_ELEMENT_ADDRESS = 0xB5, /* Optional */ kSMCCmd_REQUEST_SENSE = 0x03, /* Mandatory */ kSMCCmd_RESERVE_ELEMENT_6 = 0x16, /* Optional */ kSMCCmd_RESERVE_ELEMENT_10 = 0x56 /* Optional */ }; #pragma mark - #pragma mark 0x09 SSC Communications Commands /* Commands defined by the T10:997-D SCSI-3 Stream Commands (SSC) * (revision 22, January 1, 2000) command specification. */ #pragma mark - #pragma mark 0x0A ASC IT8 Prepress Commands #pragma mark 0x0B ASC IT8 Prepress Commands /* Commands defined by the ASC IT8 <title goes here> specification * (revision xx, month day, year) command specification. */ #if 0 enum { }; #endif #pragma mark - #pragma mark 0x0C SCC Array Controller Commands /* Commands defined by the ANSI NCITS.318-199x SCSI Controller * Commands (SCC-2) ratified command specification. */ enum { kSCCCmd_MAINTENANCE_IN = 0xA3, /* Mandatory */ kSCCCmd_MAINTENANCE_OUT = 0xA4, /* Optional */ kSCCCmd_MODE_SELECT_6 = 0x15, /* Optional */ kSCCCmd_MODE_SELECT_10 = 0x55, /* Optional */ kSCCCmd_MODE_SENSE_6 = 0x1A, /* Optional */ kSCCCmd_MODE_SENSE_10 = 0x5A, /* Optional */ kSCCCmd_PERSISTENT_RESERVE_IN = 0x5E, /* Optional */ kSCCCmd_PERSISTENT_RESERVE_OUT = 0x5F, /* Optional */ kSCCCmd_PORT_STATUS = 0x1F, /* Optional */ kSCCCmd_REDUNDANCY_GROUP_IN = 0xBA, /* Mandatory */ kSCCCmd_REDUNDANCY_GROUP_OUT = 0xBB, /* Optional */ kSCCCmd_RELEASE_6 = 0x17, /* Optional */ kSCCCmd_RELEASE_10 = 0x57, /* Optional */ kSCCCmd_REPORT_LUNS = 0xA0, /* Mandatory */ kSCCCmd_REQUEST_SENSE = 0x03, /* Mandatory */ kSCCCmd_RESERVE_6 = 0x16, /* Optional */ kSCCCmd_RESERVE_10 = 0x56, /* Optional*/ kSCCCmd_SEND_DIAGNOSTICS = 0x1D, /* Optional */ kSCCCmd_SPARE_IN = 0xBC, /* Mandatory */ kSCCCmd_SPARE_OUT = 0xBD /* Optional */ }; #pragma mark - #pragma mark 0x0D SES Enclosure Services Commands /* Commands defined by the T10:1212-D SCSI-3 Enclosure Services (SES) * (revision 8b, February 11, 1998) command specification. */ enum { kSESCmd_MODE_SELECT_6 = 0x15, /* Optional */ kSESCmd_MODE_SELECT_10 = 0x55, /* Optional */ kSESCmd_MODE_SENSE_6 = 0x1A, /* Optional */ kSESCmd_MODE_SENSE_10 = 0x5A, /* Optional */ kSESCmd_PERSISTENT_RESERVE_IN = 0x5E, /* Optional */ kSESCmd_PERSISTENT_RESERVE_OUT = 0x5F, /* Optional */ kSESCmd_RECEIVE_DIAGNOSTICS_RESULTS = 0x17, /* Mandatory */ kSESCmd_RELEASE_6 = 0x17, /* Optional */ kSESCmd_RELEASE_10 = 0x57, /* Optional */ kSESCmd_REQUEST_SENSE = 0x03, /* Mandatory */ kSESCmd_RESERVE_6 = 0x16, /* Optional */ kSESCmd_RESERVE_10 = 0x56, /* Optional */ kSESCmd_SEND_DIAGNOSTICS = 0x1D /* Mandatory */ }; #pragma mark - #pragma mark 0x0E RBC Reduced Block Commands /* Commands defined by the T10:1240-D Reduced Block Commands (RBC) * (revision 10a, August 18, 1999) command specification. */ enum { kRBCCmd_FORMAT_UNIT = 0x04, /* Optional */ kRBCCmd_READ_10 = 0x28, /* Mandatory */ kRBCCmd_READ_CAPACITY = 0x25, /* Mandatory */ kRBCCmd_START_STOP_UNIT = 0x1B, /* Mandatory */ kRBCCmd_SYNCHRONIZE_CACHE = 0x35, /* Optional */ kRBCCmd_VERIFY_10 = 0x2F, /* Mandatory */ kRBCCmd_WRITE_10 = 0x2A, /* Mandatory */ kRBCCmd_WRITE_BUFFER = 0x3B /* Mandatory for fixed media * Optional for removable */ }; #pragma mark - #pragma mark 0x0F OCRW Optical Card Commands /* Commands defined by the ISO/IEC 14776-381 SCSI Specification for * Optical Card Reader/Writer (OCRW) ratified command specification. */ #if 0 enum { }; #endif #pragma mark - #pragma mark 0x11 OSD Object-based Storage Commands /* Commands defined by the T10:1355-D Object-based Storage Commands (OSD) * (revision 1, 18 May 2000) command specification. */ #if 0 enum { }; #endif #pragma mark - #pragma mark 0x15 RMC Simplified Multimedia Commands /* Commands defined by the T10:1364-D Reduced Multimedia Commands (RMC) * (revision 1, November 11, 1999) command specification. */ #if 0 enum { }; #endif #endif /* _SCSI_COMMAND_OPERATION_CODES_H_ */
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/scsi/SCSICmds_READ_CAPACITY_Definitions.h
/* * Copyright (c) 1998-2009 Apple Inc. All rights reserved. * * @APPLE_LICENSE_HEADER_START@ * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this * file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_LICENSE_HEADER_END@ */ #ifndef _IOKIT_SCSI_CMDS_READ_CAPACITY_H_ #define _IOKIT_SCSI_CMDS_READ_CAPACITY_H_ #if KERNEL #include <IOKit/IOTypes.h> #else #include <CoreFoundation/CoreFoundation.h> #endif /*! @header SCSI Request Sense Definitions @discussion This file contains all definitions for the data returned from the READ CAPACITY 10 (0x25) and READ CAPACITY 16 (0x9E) commands. */ /*! @enum READ CAPACITY Payload Sizes @discussion Sizes of the payload for the READ CAPACITY 10 and READ CAPACITY 16 commands. @constant kREPORT_CAPACITY_DataSize Data size for a READ_CAPACITY command. @constant kREPORT_CAPACITY_16_DataSize Data size for a READ_CAPACITY_16 command. */ enum { kREPORT_CAPACITY_DataSize = 8, kREPORT_CAPACITY_16_DataSize = 32 }; /*! @constant kREPORT_CAPACITY_MaximumLBA @discussion Maximum LBA supported via READ CAPACITY 10 command. */ #define kREPORT_CAPACITY_MaximumLBA 0xFFFFFFFFUL /*! @constant kREPORT_CAPACITY_16_MaximumLBA @discussion Maximum LBA supported via READ CAPACITY 16 command. */ #define kREPORT_CAPACITY_16_MaximumLBA 0xFFFFFFFFFFFFFFFFULL /*! @struct SCSI_Capacity_Data @discussion Capacity return structure for READ CAPACITY 10 command. */ typedef struct SCSI_Capacity_Data { UInt32 RETURNED_LOGICAL_BLOCK_ADDRESS; UInt32 BLOCK_LENGTH_IN_BYTES; } SCSI_Capacity_Data; /*! @struct SCSI_Capacity_Data_Long @discussion Capacity return structure for READ CAPACITY 16 command. */ typedef struct SCSI_Capacity_Data_Long { UInt64 RETURNED_LOGICAL_BLOCK_ADDRESS; UInt32 BLOCK_LENGTH_IN_BYTES; UInt8 RTO_EN_PROT_EN; UInt8 Reserved[19]; } SCSI_Capacity_Data_Long; /*! @enum RTO_EN definitions @discussion Values for the REFERENCE TAG OWN (RTO_EN) bit in the READ CAPACITY Long Data structure. @constant kREAD_CAPACITY_RTO_Enabled Reference Tag Own enabled. @constant kREAD_CAPACITY_RTO_Disabled Reference Tag Own disabled. @constant kREAD_CAPACITY_RTO_Mask Mask to use when checking the RTO_EN_PROT_EN field. */ enum { kREAD_CAPACITY_RTO_Enabled = 0x02, kREAD_CAPACITY_RTO_Disabled = 0x00, kREAD_CAPACITY_RTO_Mask = 0x02 }; /*! @enum PROTECTION INFORMATION definitions @discussion Values for the PROTECTION INFORMATION (PROT_EN) bit in the READ CAPACITY Long Data structure. @constant kREAD_CAPACITY_PROT_Enabled Protection Information enabled. @constant kREAD_CAPACITY_PROT_Disabled Protection Information disabled. @constant kREAD_CAPACITY_PROT_Mask Mask to use when checking the RTO_EN_PROT_EN field. */ enum { kREAD_CAPACITY_PROT_Enabled = 0x01, kREAD_CAPACITY_PROT_Disabled = 0x00, kREAD_CAPACITY_PROT_Mask = 0x01 }; #endif /* _IOKIT_SCSI_CMDS_READ_CAPACITY_H_ */
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/scsi/SCSICmds_MODE_Definitions.h
/* * Copyright (c) 1998-2009 Apple Inc. All rights reserved. * * @APPLE_LICENSE_HEADER_START@ * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this * file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_LICENSE_HEADER_END@ */ #ifndef _IOKIT_SCSI_CMDS_MODE_DEFINITIONS_H_ #define _IOKIT_SCSI_CMDS_MODE_DEFINITIONS_H_ //----------------------------------------------------------------------------- // Includes //----------------------------------------------------------------------------- #if KERNEL #include <IOKit/IOTypes.h> #else #include <CoreFoundation/CoreFoundation.h> #endif /*! @header SCSI Request Sense Definitions @discussion This file contains all definitions for the data returned from the MODE_SENSE_6 and MODE_SENSE_10 commands. */ #pragma pack(1) /*! @struct SPCModeParameterHeader6 @discussion Mode Parameter Header for the MODE_SENSE_6 command. */ typedef struct SPCModeParameterHeader6 { UInt8 MODE_DATA_LENGTH; UInt8 MEDIUM_TYPE; UInt8 DEVICE_SPECIFIC_PARAMETER; UInt8 BLOCK_DESCRIPTOR_LENGTH; } SPCModeParameterHeader6; /*! @struct SPCModeParameterHeader10 @discussion Mode Parameter Header for the MODE_SENSE_10 command. */ typedef struct SPCModeParameterHeader10 { UInt16 MODE_DATA_LENGTH; UInt8 MEDIUM_TYPE; UInt8 DEVICE_SPECIFIC_PARAMETER; UInt8 LONGLBA; UInt8 RESERVED; UInt16 BLOCK_DESCRIPTOR_LENGTH; } SPCModeParameterHeader10; /*! @enum Long LBA Bitfield definitions @discussion Long LBA Bitfield definitions for Mode Parameter Header for MODE_SENSE_10 command. @constant kModeSenseParameterHeader10_LongLBABit Bit to indicate Long LBA block descriptors follow. @constant kModeSenseParameterHeader10_LongLBAMask Mask to test for kModeSenseParameterHeader10_LongLBABit. */ enum { kModeSenseParameterHeader10_LongLBABit = 0, kModeSenseParameterHeader10_LongLBAMask = (1 << kModeSenseParameterHeader10_LongLBABit), }; /*! @enum Device Specific Parameter Bitfield definitions @discussion SBC definitions for Device Specific Parameter in the Mode Sense Header Block. @constant kModeSenseSBCDeviceSpecific_DPOFUABit Bit to indicate DPO and FUA bits are accepted by the device server. @constant kModeSenseSBCDeviceSpecific_WriteProtectBit Bit to indicate medium is write protected. @constant kModeSenseSBCDeviceSpecific_DPOFUAMask Mask to test for kModeSenseSBCDeviceSpecific_DPOFUABit. @constant kModeSenseSBCDeviceSpecific_WriteProtectMask Mask to test for kModeSenseSBCDeviceSpecific_WriteProtectBit. */ enum { kModeSenseSBCDeviceSpecific_DPOFUABit = 4, kModeSenseSBCDeviceSpecific_WriteProtectBit = 7, kModeSenseSBCDeviceSpecific_DPOFUAMask = (1 << kModeSenseSBCDeviceSpecific_DPOFUABit), kModeSenseSBCDeviceSpecific_WriteProtectMask = (1 << kModeSenseSBCDeviceSpecific_WriteProtectBit) }; /*! @struct ModeParameterBlockDescriptor @discussion General mode parameter block descriptor. */ typedef struct ModeParameterBlockDescriptor { UInt8 DENSITY_CODE; UInt8 NUMBER_OF_BLOCKS[3]; UInt8 RESERVED; UInt8 BLOCK_LENGTH[3]; } ModeParameterBlockDescriptor; /*! @struct DASDModeParameterBlockDescriptor @discussion Direct Access Storage Device mode parameter block descriptor. */ typedef struct DASDModeParameterBlockDescriptor { UInt32 NUMBER_OF_BLOCKS; UInt8 DENSITY_CODE; UInt8 BLOCK_LENGTH[3]; } DASDModeParameterBlockDescriptor; /*! @struct LongLBAModeParameterBlockDescriptor @discussion Long LBA mode parameter block descriptor. */ typedef struct LongLBAModeParameterBlockDescriptor { UInt64 NUMBER_OF_BLOCKS; UInt8 DENSITY_CODE; UInt8 RESERVED[3]; UInt32 BLOCK_LENGTH; } LongLBAModeParameterBlockDescriptor; /*! @struct ModePageFormatHeader @discussion Mode Page format header. */ typedef struct ModePageFormatHeader { UInt8 PS_PAGE_CODE; UInt8 PAGE_LENGTH; } ModePageFormatHeader; /*! @enum Mode Page Format bit definitions @discussion Mode Page Format bit definitions. @constant kModePageFormat_PS_Bit Bit to indicate Parameters Saveable. @constant kModePageFormat_PAGE_CODE_Mask Mask to obtain the PAGE_CODE from the PS_PAGE_CODE field. @constant kModePageFormat_PS_Mask Mask to test for kModePageFormat_PS_Bit. */ enum { kModePageFormat_PS_Bit = 7, kModePageFormat_PAGE_CODE_Mask = 0x3F, kModePageFormat_PS_Mask = (1 << kModePageFormat_PS_Bit) }; #if 0 #pragma mark - #pragma mark SPC Mode Pages #pragma mark - #endif /*! @enum SPC Mode Pages @discussion SPC Mode Page definitions. @constant kSPCModePagePowerConditionCode Power Conditions Mode Page value. @constant kSPCModePageAllPagesCode All Mode Pages value. */ enum { kSPCModePagePowerConditionCode = 0x1A, kSPCModePageAllPagesCode = 0x3F }; /*! @struct SPCModePagePowerCondition @discussion Power Conditions Mode Page (PAGE CODE 0x1A) format. */ typedef struct SPCModePagePowerCondition { ModePageFormatHeader header; UInt8 RESERVED; UInt8 IDLE_STANDBY; UInt32 IDLE_CONDITION_TIMER; UInt32 STANDBY_CONDITION_TIMER; } SPCModePagePowerCondition; #if 0 #pragma mark - #pragma mark 0x00 SBC Direct Access Mode Pages #pragma mark - #endif /*! @enum SBC Mode Pages @discussion SBC Mode Page definitions. @constant kSBCModePageFormatDeviceCode Format Device Mode Page value. @constant kSBCModePageRigidDiskGeometryCode Rigid Disk Geometry Page value. @constant kSBCModePageFlexibleDiskCode Flexible Disk Page value. @constant kSBCModePageCachingCode Caching Page value. */ enum { kSBCModePageFormatDeviceCode = 0x03, kSBCModePageRigidDiskGeometryCode = 0x04, kSBCModePageFlexibleDiskCode = 0x05, kSBCModePageCachingCode = 0x08 }; /*! @struct SBCModePageFormatDevice @discussion Format Device Mode Page (PAGE CODE 0x03) format. */ typedef struct SBCModePageFormatDevice { ModePageFormatHeader header; UInt16 TRACKS_PER_ZONE; UInt16 ALTERNATE_SECTORS_PER_ZONE; UInt16 ALTERNATE_TRACKS_PER_ZONE; UInt16 ALTERNATE_TRACKS_PER_LOGICAL_UNIT; UInt16 SECTORS_PER_TRACK; UInt16 DATA_BYTES_PER_PHYSICAL_SECTOR; UInt16 INTERLEAVE; UInt16 TRACK_SKEW_FACTOR; UInt16 CYLINDER_SKEW_FACTOR; UInt8 SSEC_HSEC_RMB_SURF; UInt8 RESERVED[3]; } SBCModePageFormatDevice; /*! @struct SBCModePageRigidDiskGeometry @discussion Rigid Disk Geometry Mode Page (PAGE CODE 0x04) format. */ typedef struct SBCModePageRigidDiskGeometry { ModePageFormatHeader header; UInt8 NUMBER_OF_CYLINDERS[3]; UInt8 NUMBER_OF_HEADS; UInt8 STARTING_CYLINDER_WRITE_PRECOMPENSATION[3]; UInt8 STARTING_CYLINDER_REDUCED_WRITE_CURRENT[3]; UInt16 DEVICE_STEP_RATE; UInt8 LANDING_ZONE_CYLINDER[3]; UInt8 RPL; UInt8 ROTATIONAL_OFFSET; UInt8 RESERVED; UInt16 MEDIUM_ROTATION_RATE; UInt8 RESERVED1[2]; } SBCModePageRigidDiskGeometry; /*! @enum Rigid Disk Geometry bitfields @discussion Bit field masks for Rigid Disk Geometry structure fields. @constant kSBCModePageRigidDiskGeometry_RPL_Mask Mask for use with the RPL field. */ enum { kSBCModePageRigidDiskGeometry_RPL_Mask = 0x03 }; /*! @struct SBCModePageFlexibleDisk @discussion Flexible Disk Mode Page (PAGE CODE 0x05) format. */ typedef struct SBCModePageFlexibleDisk { ModePageFormatHeader header; UInt16 TRANSFER_RATE; UInt8 NUMBER_OF_HEADS; UInt8 SECTORS_PER_TRACK; UInt16 DATA_BYTES_PER_SECTOR; UInt16 NUMBER_OF_CYLINDERS; UInt16 STARTING_CYLINDER_WRITE_PRECOMPENSATION; UInt16 STARTING_CYLINDER_REDUCED_WRITE_CURRENT; UInt16 DEVICE_STEP_RATE; UInt8 DEVICE_STEP_PULSE_WIDTH; UInt16 HEAD_SETTLE_DELAY; UInt8 MOTOR_ON_DELAY; UInt8 MOTOR_OFF_DELAY; UInt8 TRDY_SSN_MO; UInt8 SPC; UInt8 WRITE_COMPENSATION; UInt8 HEAD_LOAD_DELAY; UInt8 HEAD_UNLOAD_DELAY; UInt8 PIN_34_PIN_2; UInt8 PIN_4_PIN_1; UInt16 MEDIUM_ROTATION_RATE; UInt8 RESERVED[2]; } SBCModePageFlexibleDisk; /*! @enum TRDY_SSN_MO bitfields @discussion Bit field definitions and masks for Flexible Disk TRDY_SSN_MO field. @constant kSBCModePageFlexibleDisk_MO_Bit MO Bit definition. @constant kSBCModePageFlexibleDisk_SSN_Bit SSN Bit definition. @constant kSBCModePageFlexibleDisk_TRDY_Bit TRDY Bit definition. @constant kSBCModePageFlexibleDisk_MO_Mask Mask for use with TRDY_SSN_MO field. @constant kSBCModePageFlexibleDisk_SSN_Mask Mask for use with TRDY_SSN_MO field. @constant kSBCModePageFlexibleDisk_TRDY_Mask Mask for use with TRDY_SSN_MO field. */ enum { // Bits 0:4 Reserved kSBCModePageFlexibleDisk_MO_Bit = 5, kSBCModePageFlexibleDisk_SSN_Bit = 6, kSBCModePageFlexibleDisk_TRDY_Bit = 7, kSBCModePageFlexibleDisk_MO_Mask = (1 << kSBCModePageFlexibleDisk_MO_Bit), kSBCModePageFlexibleDisk_SSN_Mask = (1 << kSBCModePageFlexibleDisk_SSN_Bit), kSBCModePageFlexibleDisk_TRDY_Mask = (1 << kSBCModePageFlexibleDisk_TRDY_Bit) }; /*! @enum SPC bitfields @discussion Bit field definitions and masks for Flexible Disk SPC field. @constant kSBCModePageFlexibleDisk_SPC_Mask Mask for use with SPC field. */ enum { kSBCModePageFlexibleDisk_SPC_Mask = 0x0F }; /*! @enum PIN_34_PIN_2 bitfields @discussion Bit field definitions and masks for Flexible Disk PIN_34_PIN_2 field. @constant kSBCModePageFlexibleDisk_PIN_2_Mask Mask for use with PIN_34_PIN_2 field. @constant kSBCModePageFlexibleDisk_PIN_34_Mask Mask for use with PIN_34_PIN_2 field. */ enum { kSBCModePageFlexibleDisk_PIN_2_Mask = 0x0F, kSBCModePageFlexibleDisk_PIN_34_Mask = 0xF0 }; /*! @enum PIN_4_PIN_1 bitfields @discussion Bit field definitions and masks for Flexible Disk PIN_4_PIN_1 field. @constant kSBCModePageFlexibleDisk_PIN_1_Mask Mask for use with PIN_4_PIN_1 field. @constant kSBCModePageFlexibleDisk_PIN_4_Mask Mask for use with PIN_4_PIN_1 field. */ enum { kSBCModePageFlexibleDisk_PIN_1_Mask = 0x0F, kSBCModePageFlexibleDisk_PIN_4_Mask = 0xF0 }; /*! @struct SBCModePageCaching @discussion Caching Mode Page (PAGE CODE 0x08) format. */ typedef struct SBCModePageCaching { ModePageFormatHeader header; UInt8 flags; UInt8 DEMAND_READ_WRITE_RETENTION_PRIORITY; UInt16 DISABLE_PREFETCH_TRANSFER_LENGTH; UInt16 MINIMUM_PREFETCH; UInt16 MAXIMUM_PREFETCH; UInt16 MAXIMUM_PREFETCH_CEILING; UInt8 flags2; UInt8 NUMBER_OF_CACHE_SEGMENTS; UInt16 CACHE_SEGMENT_SIZE; UInt8 RESERVED; UInt8 NON_CACHE_SEGMENT_SIZE[3]; } SBCModePageCaching; /*! @enum Caching flags bitfields @discussion Bit field definitions and masks for Caching flags field. @constant kSBCModePageCaching_RCD_Bit RCD Bit definition. @constant kSBCModePageCaching_MF_Bit MF Bit definition. @constant kSBCModePageCaching_WCE_Bit WCE Bit definition. @constant kSBCModePageCaching_SIZE_Bit SIZE Bit definition. @constant kSBCModePageCaching_DISC_Bit DISC Bit definition. @constant kSBCModePageCaching_CAP_Bit CAP Bit definition. @constant kSBCModePageCaching_ABPF_Bit ABPF Bit definition. @constant kSBCModePageCaching_IC_Bit IC Bit definition. @constant kSBCModePageCaching_RCD_Mask Mask for use with flags field. @constant kSBCModePageCaching_MF_Mask Mask for use with flags field. @constant kSBCModePageCaching_WCE_Mask Mask for use with flags field. @constant kSBCModePageCaching_SIZE_Mask Mask for use with flags field. @constant kSBCModePageCaching_DISC_Mask Mask for use with flags field. @constant kSBCModePageCaching_CAP_Mask Mask for use with flags field. @constant kSBCModePageCaching_ABPF_Mask Mask for use with flags field. @constant kSBCModePageCaching_IC_Mask Mask for use with flags field. */ enum { kSBCModePageCaching_RCD_Bit = 0, kSBCModePageCaching_MF_Bit = 1, kSBCModePageCaching_WCE_Bit = 2, kSBCModePageCaching_SIZE_Bit = 3, kSBCModePageCaching_DISC_Bit = 4, kSBCModePageCaching_CAP_Bit = 5, kSBCModePageCaching_ABPF_Bit = 6, kSBCModePageCaching_IC_Bit = 7, kSBCModePageCaching_RCD_Mask = (1 << kSBCModePageCaching_RCD_Bit), kSBCModePageCaching_MF_Mask = (1 << kSBCModePageCaching_MF_Bit), kSBCModePageCaching_WCE_Mask = (1 << kSBCModePageCaching_WCE_Bit), kSBCModePageCaching_SIZE_Mask = (1 << kSBCModePageCaching_SIZE_Bit), kSBCModePageCaching_DISC_Mask = (1 << kSBCModePageCaching_DISC_Bit), kSBCModePageCaching_CAP_Mask = (1 << kSBCModePageCaching_CAP_Bit), kSBCModePageCaching_ABPF_Mask = (1 << kSBCModePageCaching_ABPF_Bit), kSBCModePageCaching_IC_Mask = (1 << kSBCModePageCaching_IC_Bit) }; /*! @enum Demand Read/Write Retention masks @discussion Demand Read/Write Retention masks. @constant kSBCModePageCaching_DEMAND_WRITE_Mask Mask for the DEMAND_READ_WRITE_RETENTION_PRIORITY field. @constant kSBCModePageCaching_DEMAND_READ_Mask Mask for the DEMAND_READ_WRITE_RETENTION_PRIORITY field. */ enum { kSBCModePageCaching_DEMAND_WRITE_Mask = 0x00FF, kSBCModePageCaching_DEMAND_READ_Mask = 0xFF00 }; /*! @enum Caching flags2 bitfields @discussion Bit field definitions and masks for Caching flags2 field. @constant kSBCModePageCaching_VS1_Bit VS1 Bit definition. @constant kSBCModePageCaching_VS2_Bit VS2 Bit definition. @constant kSBCModePageCaching_DRA_Bit DRA Bit definition. @constant kSBCModePageCaching_LBCSS_Bit LBCSS Bit definition. @constant kSBCModePageCaching_FSW_Bit FSW Bit definition. @constant kSBCModePageCaching_VS1_Mask Mask for use with flags2 field. @constant kSBCModePageCaching_VS2_Mask Mask for use with flags2 field. @constant kSBCModePageCaching_DRA_Mask Mask for use with flags2 field. @constant kSBCModePageCaching_LBCSS_Mask Mask for use with flags2 field. @constant kSBCModePageCaching_FSW_Mask Mask for use with flags2 field. */ enum { // Bits 0:2 Reserved kSBCModePageCaching_VS1_Bit = 3, kSBCModePageCaching_VS2_Bit = 4, kSBCModePageCaching_DRA_Bit = 5, kSBCModePageCaching_LBCSS_Bit = 6, kSBCModePageCaching_FSW_Bit = 7, kSBCModePageCaching_VS1_Mask = (1 << kSBCModePageCaching_VS1_Bit), kSBCModePageCaching_VS2_Mask = (1 << kSBCModePageCaching_VS2_Bit), kSBCModePageCaching_DRA_Mask = (1 << kSBCModePageCaching_DRA_Bit), kSBCModePageCaching_LBCSS_Mask = (1 << kSBCModePageCaching_LBCSS_Bit), kSBCModePageCaching_FSW_Mask = (1 << kSBCModePageCaching_FSW_Bit) }; #pragma options align=reset #endif /* _IOKIT_SCSI_CMDS_MODE_DEFINITIONS_H_ */
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/usb/AppleUSBDefinitions.h
/* * Copyright (c) 1998-2019 Apple Inc. All rights reserved. * * @APPLE_OSREFERENCE_LICENSE_HEADER_START@ * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. The rights granted to you under the License * may not be used to create, or enable the creation or redistribution of, * unlawful or unlicensed copies of an Apple operating system, or to * circumvent, violate, or enable the circumvention or violation of, any * terms of an Apple operating system software license agreement. * * Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_OSREFERENCE_LICENSE_HEADER_END@ */ #ifndef AppleUSBCommon_AppleUSBDefinitions_h #define AppleUSBCommon_AppleUSBDefinitions_h #include <TargetConditionals.h> #if TARGET_OS_DRIVERKIT #include <stdint.h> #include <stddef.h> #include <sys/_types/_uuid_t.h> #include <DriverKit/IOTypes.h> #include <DriverKit/IOLib.h> #else #include <IOKit/IOTypes.h> #include <libkern/OSByteOrder.h> #endif #ifndef IOUSBBit #define IOUSBBit(bit) ((uint32_t)(1) << bit) #endif #ifndef IOUSBBitRange #define IOUSBBitRange(start, end) (~(((uint32_t)(1) << start) - 1) & (((uint32_t)(1) << end) | (((uint32_t)(1) << end) - 1))) #endif #ifndef IOUSBBitRange64 #define IOUSBBitRange64(start, end) (~(((uint64_t)(1) << start) - 1) & (((uint64_t)(1) << end) | (((uint64_t)(1) << end) - 1))) #endif #ifndef IOUSBBitRangePhase #define IOUSBBitRangePhase(start, end) (start) #endif #ifndef USBToHost16 #define USBToHost16 OSSwapLittleToHostInt16 #endif #ifndef HostToUSB16 #define HostToUSB16 OSSwapHostToLittleInt16 #endif #ifndef USBToHost32 #define USBToHost32 OSSwapLittleToHostInt32 #endif #ifndef HostToUSB32 #define HostToUSB32 OSSwapHostToLittleInt32 #endif #ifndef USBToHost64 #define USBToHost64 OSSwapLittleToHostInt64 #endif #ifndef HostToUSB64 #define HostToUSB64 OSSwapHostToLittleInt64 #endif #define kIOUSB30Bitrate5Gbps ( 5 * 1000 * 1000 * 1000ULL) #define kIOUSB30Bitrate10Gbps (10 * 1000 * 1000 * 1000ULL) #define kIOUSB32Bitrate20Gbps (20 * 1000 * 1000 * 1000ULL) /*! * @enum kIOUSBAppleVendorID * @discussion Apple's vendor ID, assigned by the USB-IF */ enum { kIOUSBAppleVendorID = 0x05AC }; #pragma mark Descriptor definitions /*! * @enum tIOUSBDescriptorType * @brief Descriptor types defined by USB 2.0 Table 9-5 and USB 3.0 Table 9-6 */ enum tIOUSBDescriptorType { kIOUSBDescriptorTypeDevice = 1, kIOUSBDescriptorTypeConfiguration = 2, kIOUSBDescriptorTypeString = 3, kIOUSBDescriptorTypeInterface = 4, kIOUSBDescriptorTypeEndpoint = 5, kIOUSBDescriptorTypeDeviceQualifier = 6, kIOUSBDescriptorTypeOtherSpeedConfiguration = 7, kIOUSBDescriptorTypeInterfacePower = 8, kIOUSBDescriptorTypeOTG = 9, kIOUSBDescriptorTypeDebug = 10, kIOUSBDescriptorTypeInterfaceAssociation = 11, kIOUSBDescriptorTypeBOS = 15, kIOUSBDescriptorTypeDeviceCapability = 16, kIOUSBDecriptorTypeHID = 33, kIOUSBDecriptorTypeReport = 34, kIOUSBDescriptorTypePhysical = 35, kIOUSBDescriptorTypeHub = 41, kIOUSBDescriptorTypeSuperSpeedHub = 42, kIOUSBDescriptorTypeSuperSpeedUSBEndpointCompanion = 48, kIOUSBDescriptorTypeSuperSpeedPlusIsochronousEndpointCompanion = 49 }; typedef enum tIOUSBDescriptorType tIOUSBDescriptorType; /*! * @enum tIOUSBDescriptorSize * @brief Size in bytes for descriptor structures */ enum tIOUSBDescriptorSize { kIOUSBDescriptorHeaderSize = 2, kIOUSBDescriptorSizeDevice = 18, kIOUSBDescriptorSizeConfiguration = 9, kIOUSBDescriptorSizeInterface = 9, kIOUSBDescriptorSizeEndpoint = 7, kIOUSBDescriptorSizeStringMinimum = kIOUSBDescriptorHeaderSize, kIOUSBDescriptorSizeStringMaximum = 255, kIOUSBDescriptorSizeDeviceQualifier = 10, kIOUSBDescriptorSizeInterfaceAssociation = 8, kIOUSBDescriptorSizeBOS = 5, kIOUSBDescriptorSizeDeviceCapability = 3, kIOUSBDescriptorSizeUSB20ExtensionCapability = 7, kIOUSBDescriptorSizeSuperSpeedUSBDeviceCapability = 10, kIOUSBDescriptorSizeContainerIDCapability = 20, kIOUSBDescriptorSizeHubMinimum = 9, kIOUSBDescriptorSizeHubMaximum = 21, kIOUSBDescriptorSizeSuperSpeedHub = 12, kIOUSBDescriptorSizeSuperSpeedUSBEndpointCompanion = 6, kIOUSBDescriptorSizeSuperSpeedPlusIsochronousEndpointCompanion = 8, kIOUSBDescriptorSizeBillboardDeviceMinimum = 44, kIOUSBDescriptorSizeBillboardDeviceMaximum = 256, kIOUSBDescriptorSizePlatformECIDCapability = 28, kIOUSBDescriptorSizePlatformCapability = 20 }; typedef enum tIOUSBDescriptorSize tIOUSBDescriptorSize; /*! * @struct IOUSBDescriptorHeader * @brief Base descriptor defined by USB 2.0 9.5 * @discussion IOUSBDescriptorDefinitions declares structs to represent a variety of USB standard * descriptors. */ struct IOUSBDescriptorHeader { uint8_t bLength; uint8_t bDescriptorType; } __attribute__((packed)); typedef struct IOUSBDescriptorHeader IOUSBDescriptorHeader; /*! * @brief Base descriptor defined by USB 2.0 9.5 * @discussion Used to represent generic descriptor definitions */ typedef IOUSBDescriptorHeader IOUSBDescriptor; /*! * @typedef IOUSBDeviceDescriptor * @discussion Descriptor for a USB Device. * See the USB Specification at <a href="http://www.usb.org" target="_blank">http://www.usb.org</a>. */ struct IOUSBDeviceDescriptor { uint8_t bLength; uint8_t bDescriptorType; uint16_t bcdUSB; uint8_t bDeviceClass; uint8_t bDeviceSubClass; uint8_t bDeviceProtocol; uint8_t bMaxPacketSize0; uint16_t idVendor; uint16_t idProduct; uint16_t bcdDevice; uint8_t iManufacturer; uint8_t iProduct; uint8_t iSerialNumber; uint8_t bNumConfigurations; } __attribute__((packed)); typedef struct IOUSBDeviceDescriptor IOUSBDeviceDescriptor; /*! * @typedef IOUSBDeviceQualifierDescriptor * @discussion USB Device Qualifier Descriptor. * See the USB Specification at <a href="http://www.usb.org" target="_blank">http://www.usb.org</a>. * USB 2.0 9.6.2: Device Qualifier */ struct IOUSBDeviceQualifierDescriptor { uint8_t bLength; uint8_t bDescriptorType; uint16_t bcdUSB; uint8_t bDeviceClass; uint8_t bDeviceSubClass; uint8_t bDeviceProtocol; uint8_t bMaxPacketSize0; uint8_t bNumConfigurations; uint8_t bReserved; } __attribute__((packed)); typedef struct IOUSBDeviceQualifierDescriptor IOUSBDeviceQualifierDescriptor; /*! * @typedef IOUSBConfigurationDescHeader * @discussion Header of a IOUSBConfigurationDescriptor. Used to get the total length of the descriptor. * USB 2.0 9.6.3: Configuration */ struct IOUSBConfigurationDescHeader { uint8_t bLength; uint8_t bDescriptorType; uint16_t wTotalLength; } __attribute__((packed)); typedef struct IOUSBConfigurationDescHeader IOUSBConfigurationDescHeader; /*! * @typedef IOUSBConfigurationDescriptor * @discussion Standard USB Configuration Descriptor. It is variable length, so this only specifies * the known fields. We use the wTotalLength field to read the whole descriptor. * See the USB Specification at <a href="http://www.usb.org" target="_blank">http://www.usb.org</a>. * USB 2.0 9.6.3: Configuration */ struct IOUSBConfigurationDescriptor { uint8_t bLength; uint8_t bDescriptorType; uint16_t wTotalLength; uint8_t bNumInterfaces; uint8_t bConfigurationValue; uint8_t iConfiguration; uint8_t bmAttributes; uint8_t MaxPower; } __attribute__((packed)); typedef struct IOUSBConfigurationDescriptor IOUSBConfigurationDescriptor; enum { kIOUSBConfigurationDescriptorAttributeRemoteWakeCapable = IOUSBBit(5), kIOUSBConfigurationDescriptorAttributeSelfPowered = IOUSBBit(6) }; /*! * @typedef IOUSBInterfaceDescriptor * @discussion Descriptor for a USB Interface. See the USB Specification at * <a href="http://www.usb.org" target="_blank">http://www.usb.org</a>. * USB 2.0 9.6.5: Interface */ struct IOUSBInterfaceDescriptor { uint8_t bLength; uint8_t bDescriptorType; uint8_t bInterfaceNumber; uint8_t bAlternateSetting; uint8_t bNumEndpoints; uint8_t bInterfaceClass; uint8_t bInterfaceSubClass; uint8_t bInterfaceProtocol; uint8_t iInterface; } __attribute__((packed)); typedef struct IOUSBInterfaceDescriptor IOUSBInterfaceDescriptor; /*! * @typedef IOUSBEndpointDescriptor * @discussion Descriptor for a USB Endpoint. See the USB Specification at * <a href="http://www.usb.org" target="_blank">http://www.usb.org</a>. * USB 2.0 9.6.6: Endpoint */ struct IOUSBEndpointDescriptor { uint8_t bLength; uint8_t bDescriptorType; uint8_t bEndpointAddress; uint8_t bmAttributes; uint16_t wMaxPacketSize; uint8_t bInterval; } __attribute__((packed)); typedef struct IOUSBEndpointDescriptor IOUSBEndpointDescriptor; enum { kIOUSBEndpointDescriptorNumber = IOUSBBitRange(0, 3), kIOUSBEndpointDescriptorNumberPhase = IOUSBBitRangePhase(0, 3), kIOUSBEndpointDescriptorEndpointAddressReserved = IOUSBBitRange(4, 6), kIOUSBEndpointDescriptorDirection = IOUSBBit(7), kIOUSBEndpointDescriptorDirectionPhase = IOUSBBitRangePhase(7, 7), kIOUSBEndpointDescriptorDirectionOut = 0, kIOUSBEndpointDescriptorDirectionIn = IOUSBBit(7), kIOUSBEndpointDescriptorTransferType = IOUSBBitRange(0, 1), kIOUSBEndpointDescriptorTransferTypePhase = IOUSBBitRangePhase(0, 1), kIOUSBEndpointDescriptorTransferTypeControl = (0 << IOUSBBitRangePhase(0, 1)), kIOUSBEndpointDescriptorTransferTypeIsochronous = (1 << IOUSBBitRangePhase(0, 1)), kIOUSBEndpointDescriptorTransferTypeBulk = (2 << IOUSBBitRangePhase(0, 1)), kIOUSBEndpointDescriptorTransferTypeInterrupt = (3 << IOUSBBitRangePhase(0, 1)), kIOUSBEndpointDescriptorSynchronizationType = IOUSBBitRange(2, 3), kIOUSBEndpointDescriptorSynchronizationTypePhase = IOUSBBitRangePhase(2, 3), kIOUSBEndpointDescriptorSynchronizationTypeNone = (0 << IOUSBBitRangePhase(2, 3)), kIOUSBEndpointDescriptorSynchronizationTypeAsynchronous = (1 << IOUSBBitRangePhase(2, 3)), kIOUSBEndpointDescriptorSynchronizationTypeAdaptive = (2 << IOUSBBitRangePhase(2, 3)), kIOUSBEndpointDescriptorSynchronizationTypeSynchronous = (3 << IOUSBBitRangePhase(2, 3)), kIOUSBEndpointDescriptorUsageType = IOUSBBitRange(4, 5), kIOUSBEndpointDescriptorUsageTypePhase = IOUSBBitRangePhase(4, 5), kIOUSBEndpointDescriptorUsageTypeInterruptPeriodic = (0 << IOUSBBitRangePhase(4, 5)), kIOUSBEndpointDescriptorUsageTypeInterruptNotification = (1 << IOUSBBitRangePhase(4, 5)), kIOUSBEndpointDescriptorUsageTypeInterruptReserved1 = (2 << IOUSBBitRangePhase(4, 5)), kIOUSBEndpointDescriptorUsageTypeInterruptReserved2 = (3 << IOUSBBitRangePhase(4, 5)), kIOUSBEndpointDescriptorUsageTypeIsocData = (0 << IOUSBBitRangePhase(4, 5)), kIOUSBEndpointDescriptorUsageTypeIsocFeedback = (1 << IOUSBBitRangePhase(4, 5)), kIOUSBEndpointDescriptorUsageTypeIsocImplicit = (2 << IOUSBBitRangePhase(4, 5)), kIOUSBEndpointDescriptorUsageTypeIsocReserved = (3 << IOUSBBitRangePhase(4, 5)), kIOUSBEndpointDescriptorPacketSize = IOUSBBitRange(0, 10), kIOUSBEndpointDescriptorPacketSizePhase = IOUSBBitRangePhase(0, 10), kIOUSBEndpointDescriptorPacketSizeMult = IOUSBBitRange(11, 12), kIOUSBEndpointDescriptorPacketSizeMultPhase = IOUSBBitRangePhase(11, 12), kIOUSBEndpointDescriptorReserved = IOUSBBitRange(13, 15), kIOUSBEndpointDescriptorReservedPhase = IOUSBBitRangePhase(13, 15) }; /*! * @enum tIOUSBEndpointDirection * @brief IO Direction of an endpoint * @constant kIOUSBEndpointDirectionOut endpoint direction is host-to-device * @constant kIOUSBEndpointDirectionIn endpoint direction is device-to-host * @constant kIOUSBEndpointDirectionUnknown the direction is unknown */ enum tIOUSBEndpointDirection { kIOUSBEndpointDirectionOut = (kIOUSBEndpointDescriptorDirectionOut >> kIOUSBEndpointDescriptorDirectionPhase), kIOUSBEndpointDirectionIn = (kIOUSBEndpointDescriptorDirectionIn >> kIOUSBEndpointDescriptorDirectionPhase), kIOUSBEndpointDirectionUnknown = 2 }; typedef enum tIOUSBEndpointDirection tIOUSBEndpointDirection; /*! * @enum tIOUSBEndpointType * @brief Describes the type of endpoint * @constant kIOUSBEndpointTypeControl endpoint is a control endpoint * @constant kIOUSBEndpointTypeIsochronous endpoint is an isochronous endpoint * @constant kIOUSBEndpointTypeBulk is a bulk endpoint * @constant kIOUSBEndpointTypeInterrupt is an interrupt endpoint */ enum tIOUSBEndpointType { kIOUSBEndpointTypeControl = (kIOUSBEndpointDescriptorTransferTypeControl >> kIOUSBEndpointDescriptorTransferTypePhase), kIOUSBEndpointTypeIsochronous = (kIOUSBEndpointDescriptorTransferTypeIsochronous >> kIOUSBEndpointDescriptorTransferTypePhase), kIOUSBEndpointTypeBulk = (kIOUSBEndpointDescriptorTransferTypeBulk >> kIOUSBEndpointDescriptorTransferTypePhase), kIOUSBEndpointTypeInterrupt = (kIOUSBEndpointDescriptorTransferTypeInterrupt >> kIOUSBEndpointDescriptorTransferTypePhase) }; typedef enum tIOUSBEndpointType tIOUSBEndpointType; enum tIOUSBEndpointSynchronizationType { kIOUSBEndpointSynchronizationTypeNone = (kIOUSBEndpointDescriptorSynchronizationTypeNone >> kIOUSBEndpointDescriptorSynchronizationTypePhase), kIOUSBEndpointSynchronizationTypeAsynchronous = (kIOUSBEndpointDescriptorSynchronizationTypeAsynchronous >> kIOUSBEndpointDescriptorSynchronizationTypePhase), kIOUSBEndpointSynchronizationTypeAdaptive = (kIOUSBEndpointDescriptorSynchronizationTypeAdaptive >> kIOUSBEndpointDescriptorSynchronizationTypePhase), kIOUSBEndpointSynchronizationTypeSynchronous = (kIOUSBEndpointDescriptorSynchronizationTypeSynchronous >> kIOUSBEndpointDescriptorSynchronizationTypePhase) }; typedef enum tIOUSBEndpointSynchronizationType tIOUSBEndpointSynchronizationType; enum tIOUSBEndpointUsageType { kIOUSBEndpointUsageTypeIsocData = (kIOUSBEndpointDescriptorUsageTypeIsocData >> kIOUSBEndpointDescriptorUsageTypePhase), kIOUSBEndpointUsageTypeIsocFeedback = (kIOUSBEndpointDescriptorUsageTypeIsocFeedback >> kIOUSBEndpointDescriptorUsageTypePhase), kIOUSBEndpointUsageTypeIsocImplicit = (kIOUSBEndpointDescriptorUsageTypeIsocImplicit >> kIOUSBEndpointDescriptorUsageTypePhase) }; typedef enum tIOUSBEndpointUsageType tIOUSBEndpointUsageType; /*! * @enum tIOUSBLanguageID * @brief USB Language Identifiers 1.0 */ enum tIOUSBLanguageID { kIOUSBLanguageIDEnglishUS = 0x0409 }; typedef enum tIOUSBLanguageID tIOUSBLanguageID; /*! * @typedef IOUSBStringDescriptor * @discussion Descriptor for a USB Strings. See the USB Specification at * <a href="http://www.usb.org" target="_blank">http://www.usb.org</a>. * USB 2.0 9.6.7: String */ struct IOUSBStringDescriptor { uint8_t bLength; uint8_t bDescriptorType; uint8_t bString[1]; } __attribute__((packed)); typedef struct IOUSBStringDescriptor IOUSBStringDescriptor; enum tIOUSBDeviceCapabilityType { // USB 3.0 Table 9-13 kIOUSBDeviceCapabilityTypeWireless = 1, kIOUSBDeviceCapabilityTypeUSB20Extension = 2, kIOUSBDeviceCapabilityTypeSuperSpeed = 3, kIOUSBDeviceCapabilityTypeContainerID = 4, // USB 3.1 Table 9-14 kIOUSBDeviceCapabilityTypePlatform = 5, kIOUSBDeviceCapabilityTypePowerDelivery = 6, kIOUSBDeviceCapabilityTypeBatteryInfo = 7, kIOUSBDeviceCapabilityTypePdConsumerPort = 8, kIOUSBDeviceCapabilityTypePdProviderPort = 9, kIOUSBDeviceCapabilityTypeSuperSpeedPlus = 10, kIOUSBDeviceCapabilityTypePrecisionMeasurement = 11, kIOUSBDeviceCapabilityTypeWirelessExt = 12, kIOUSBDeviceCapabilityTypeBillboard = 13, kIOUSBDeviceCapabilityTypeBillboardAltMode = 15 }; typedef enum tIOUSBDeviceCapabilityType tIOUSBDeviceCapabilityType; /*! * @typedef IOUSBBOSDescriptor * @discussion USB BOS descriptor. See the USB Specification at * <a href="http://www.usb.org" target="_blank">http://www.usb.org</a>. * USB 3.0 9.6.2: Binary Device Object Store (BOS) */ struct IOUSBBOSDescriptor { uint8_t bLength; uint8_t bDescriptorType; uint16_t wTotalLength; uint8_t bNumDeviceCaps; } __attribute__((packed)); typedef struct IOUSBBOSDescriptor IOUSBBOSDescriptor; /*! * @typedef IOUSBDeviceCapabilityDescriptorHeader * @discussion Device Capability descriptor. See the USB Specification at * <a href="http://www.usb.org" target="_blank">http://www.usb.org</a>. * USB 3.0 9.6.2: Binary Device Object Store (BOS) */ struct IOUSBDeviceCapabilityDescriptorHeader { uint8_t bLength; uint8_t bDescriptorType; uint8_t bDevCapabilityType; } __attribute__((packed)); typedef struct IOUSBDeviceCapabilityDescriptorHeader IOUSBDeviceCapabilityDescriptorHeader; /*! * @typedef IOUSBDeviceCapabilityUSB2Extension * @discussion Device Capability USB 2.0 Extension. * USB 3.0 9.6.2.1: USB 2.0 Extension */ struct IOUSBDeviceCapabilityUSB2Extension { uint8_t bLength; uint8_t bDescriptorType; uint8_t bDevCapabilityType; uint32_t bmAttributes; } __attribute__((packed)); typedef struct IOUSBDeviceCapabilityUSB2Extension IOUSBDeviceCapabilityUSB2Extension; enum { kIOUSBUSB20ExtensionCapabilityLPM = IOUSBBit(1), // From USB 2.0 ECN Errata for Link Power Management. kIOUSBUSB20ExtensionCapabilityBESLSupport = IOUSBBit(2), kIOUSBUSB20ExtensionCapabilityBESLValid = IOUSBBit(3), kIOUSBUSB20ExtensionCapabilityBESLDValid = IOUSBBit(4), kIOUSBUSB20ExtensionCapabilityBESL = IOUSBBitRange(8, 11), kIOUSBUSB20ExtensionCapabilityBESLPhase = IOUSBBitRangePhase(8, 11), kIOUSBUSB20ExtensionCapabilityBESLD = IOUSBBitRange(12, 15), kIOUSBUSB20ExtensionCapabilityBESLDPhase = IOUSBBitRangePhase(12, 15) }; /*! * @typedef IOUSBDeviceCapabilitySuperSpeedUSB * @discussion Device Capability SuperSpeed USB. USB 3.0 9.6.2.2: SuperSpeed USB Device Capability */ struct IOUSBDeviceCapabilitySuperSpeedUSB { uint8_t bLength; uint8_t bDescriptorType; uint8_t bDevCapabilityType; uint8_t bmAttributes; uint16_t wSpeedsSupported; uint8_t bFunctionalitySupport; uint8_t bU1DevExitLat; uint16_t wU2DevExitLat; } __attribute__((packed)); typedef struct IOUSBDeviceCapabilitySuperSpeedUSB IOUSBDeviceCapabilitySuperSpeedUSB; enum { kIOUSBSuperSpeedDeviceCapabilityLTM = IOUSBBit(1), kIOUSBSuperSpeedDeviceCapabilityLowSpeed = IOUSBBit(0), kIOUSBSuperSpeedDeviceCapabilityFullSpeed = IOUSBBit(1), kIOUSBSuperSpeedDeviceCapabilityHighSpeed = IOUSBBit(2), kIOUSBSuperSpeedDeviceCapability5Gb = IOUSBBit(3), kIOUSBSuperSpeedDeviceCapabilitySupportLowSpeed = 0, kIOUSBSuperSpeedDeviceCapabilitySupportFullSpeed = 1, kIOUSBSuperSpeedDeviceCapabilitySupportHighSpeed = 2, kIOUSBSuperSpeedDeviceCapabilitySupport5Gb = 3, kIOUSBSuperSpeedDeviceCapabilityU1DevExitLatMax = 0xa, kIOUSBSuperSpeedDeviceCapabilityU2DevExitLatMax = 0x7ff }; /*! * @typedef IOUSBDeviceCapabilitySuperSpeedPlusUSB * @discussion Device Capability SuperSpeedPlus USB. * USB 3.1 9.6.2.5: SuperSpeedPlus USB Device Capability */ struct IOUSBDeviceCapabilitySuperSpeedPlusUSB { uint8_t bLength; uint8_t bDescriptorType; uint8_t bDevCapabilityType; uint8_t bReserved; uint32_t bmAttributes; uint16_t wFunctionalitySupport; uint16_t wReserved; uint32_t bmSublinkSpeedAttr[]; } __attribute__((packed)); typedef struct IOUSBDeviceCapabilitySuperSpeedPlusUSB IOUSBDeviceCapabilitySuperSpeedPlusUSB; enum { //bmAttributes kIOUSBSuperSpeedPlusDeviceCapabilitySublinkSpeedAttrCount = IOUSBBitRange(0, 4), kIOUSBSuperSpeedPlusDeviceCapabilitySublinkSpeedAttrCountPhase = IOUSBBitRangePhase(0, 4), kIOUSBSuperSpeedPlusDeviceCapabilitySublinkSpeedIdCount = IOUSBBitRange(5, 8), kIOUSBSuperSpeedPlusDeviceCapabilitySublinkSpeedIdCountPhase = IOUSBBitRangePhase(5, 8), //wFunctionalitySupport kIOUSBSuperSpeedPlusDeviceCapabilitySublinkMinSpeedId = IOUSBBitRange(0, 3), kIOUSBSuperSpeedPlusDeviceCapabilitySublinkMinSpeedIdPhase = IOUSBBitRangePhase(0, 3), kIOUSBSuperSpeedPlusDeviceCapabilityReserved = IOUSBBitRange(4, 7), kIOUSBSuperSpeedPlusDeviceCapabilityReservedPhase = IOUSBBitRangePhase(4, 7), kIOUSBSuperSpeedPlusDeviceCapabilityMinRxLaneCount = IOUSBBitRange(8, 11), kIOUSBSuperSpeedPlusDeviceCapabilityMinRxLaneCountPhase = IOUSBBitRangePhase(8, 11), kIOUSBSuperSpeedPlusDeviceCapabilityMinTxLaneCount = IOUSBBitRange(12, 15), kIOUSBSuperSpeedPlusDeviceCapabilityMinTxLaneCountPhase = IOUSBBitRangePhase(12, 15), //bmSublinkSpeedAttr kIOUSBSuperSpeedPlusDeviceCapabilitySublinkSpeedId = IOUSBBitRange(0, 3), kIOUSBSuperSpeedPlusDeviceCapabilitySublinkSpeedIdPhase = IOUSBBitRangePhase(0, 3), kIOUSBSuperSpeedPlusDeviceCapabilitySublinkLSE = IOUSBBitRange(4, 5), kIOUSBSuperSpeedPlusDeviceCapabilitySublinkLSEPhase = IOUSBBitRangePhase(4, 5), kIOUSBSuperSpeedPlusDeviceCapabilitySublinkLSEBits = (0 << kIOUSBSuperSpeedPlusDeviceCapabilitySublinkLSEPhase), kIOUSBSuperSpeedPlusDeviceCapabilitySublinkLSEKbits = (1 << kIOUSBSuperSpeedPlusDeviceCapabilitySublinkLSEPhase), kIOUSBSuperSpeedPlusDeviceCapabilitySublinkLSEMbits = (2 << kIOUSBSuperSpeedPlusDeviceCapabilitySublinkLSEPhase), kIOUSBSuperSpeedPlusDeviceCapabilitySublinkLSEGbits = (3 << kIOUSBSuperSpeedPlusDeviceCapabilitySublinkLSEPhase), kIOUSBSuperSpeedPlusDeviceCapabilitySublinkType = IOUSBBitRange(6, 7), kIOUSBSuperSpeedPlusDeviceCapabilitySublinkTypePhase = IOUSBBitRangePhase(6, 7), kIOUSBSuperSpeedPlusDeviceCapabilitySublinkSymmetry = IOUSBBit(6), kIOUSBSuperSpeedPlusDeviceCapabilitySublinkSymmetryPhase = IOUSBBitRangePhase(6, 6), kIOUSBSuperSpeedPlusDeviceCapabilitySublinkSymmetric = (0 << kIOUSBSuperSpeedPlusDeviceCapabilitySublinkSymmetryPhase), kIOUSBSuperSpeedPlusDeviceCapabilitySublinkAsymmetric = (1 << kIOUSBSuperSpeedPlusDeviceCapabilitySublinkSymmetryPhase), kIOUSBSuperSpeedPlusDeviceCapabilitySublinkDirection = IOUSBBit(7), kIOUSBSuperSpeedPlusDeviceCapabilitySublinkDirectionPhase = IOUSBBitRangePhase(7, 7), kIOUSBSuperSpeedPlusDeviceCapabilitySublinkDirectionRx = (0 << kIOUSBSuperSpeedPlusDeviceCapabilitySublinkDirectionPhase), kIOUSBSuperSpeedPlusDeviceCapabilitySublinkDirectionTx = (1 << kIOUSBSuperSpeedPlusDeviceCapabilitySublinkDirectionPhase), kIOUSBSuperSpeedPlusDeviceCapabilitySublinkReserved = IOUSBBitRange(8, 13), kIOUSBSuperSpeedPlusDeviceCapabilitySublinkReservedPhase = IOUSBBitRangePhase(8, 13), kIOUSBSuperSpeedPlusDeviceCapabilitySublinkProtocol = IOUSBBitRange(14, 15), kIOUSBSuperSpeedPlusDeviceCapabilitySublinkProtocolPhase = IOUSBBitRangePhase(14, 15), kIOUSBSuperSpeedPlusDeviceCapabilitySublinkSpeedMantissa = IOUSBBitRange(16, 31), kIOUSBSuperSpeedPlusDeviceCapabilitySublinkSpeedMantissaPhase = IOUSBBitRangePhase(16, 31), }; /*! * @typedef IOUSBDeviceCapabilityContainerID * @discussion Device Capability Container ID. * USB 3.0 9.6.2.3: Container ID */ struct IOUSBDeviceCapabilityContainerID { uint8_t bLength; uint8_t bDescriptorType; uint8_t bDevCapabilityType; uint8_t bReservedID; uint8_t containerID[16]; } __attribute__((packed)); typedef struct IOUSBDeviceCapabilityContainerID IOUSBDeviceCapabilityContainerID; /*! * @typedef IOUSBPlatformCapabilityDescriptor * @discussion Device Capability Platform Descriptor. * USB 3.1 9.6.2.4: Platform Descriptor */ struct IOUSBPlatformCapabilityDescriptor { uint8_t bLength; uint8_t bDescriptorType; uint8_t bDevCapabilityType; uint8_t bReserved; uuid_t PlatformCapabilityUUID; } __attribute__((packed)); typedef struct IOUSBPlatformCapabilityDescriptor IOUSBPlatformCapabilityDescriptor; /*! * @typedef IOUSBDeviceCapabilityBillboardAltConfig * @discussion Device Capability Billboard Alternate Setting Info. * USB Billboard 3.1.6.2: Billboard Capability Descriptor V1.2 */ struct IOUSBDeviceCapabilityBillboardAltConfigCompatibility { uint16_t wSVID; uint32_t dwAlternateMode; uint8_t iAlternateModeString; } __attribute__((packed)); typedef struct IOUSBDeviceCapabilityBillboardAltConfigCompatibility IOUSBDeviceCapabilityBillboardAltConfigCompatibility; /*! * @typedef IOUSBDeviceCapabilityBillboardAltConfig * @discussion Device Capability Billboard Alternate Setting Info. * USB Billboard 3.1.6.2: Billboard Capability Descriptor V1.1 and 1.21+ */ struct IOUSBDeviceCapabilityBillboardAltConfig { uint16_t wSVID; uint8_t bAltenateMode; uint8_t iAlternateModeString; } __attribute__((packed)); typedef struct IOUSBDeviceCapabilityBillboardAltConfig IOUSBDeviceCapabilityBillboardAltConfig; /*! * @typedef IOUSBDeviceCapabilityBillboard * @discussion Device Capability Billboard. * USB Billboard 3.1.6.2: Billboard Capability Descriptor */ struct IOUSBDeviceCapabilityBillboard { uint8_t bLength; uint8_t bDescriptorType; uint8_t bDevCapabilityType; uint8_t iAdditionalInfoURL; uint8_t bNumberOfAlternateModes; uint8_t bPreferredAlternateMode; uint16_t vCONNPower; uint8_t bmConfigured[32]; uint16_t bcdVersion; uint8_t bAdditionalFailureInfo; uint8_t bReserved; IOUSBDeviceCapabilityBillboardAltConfig pAltConfigurations[]; } __attribute__((packed)); typedef struct IOUSBDeviceCapabilityBillboard IOUSBDeviceCapabilityBillboard; /*! * @typedef IOUSBDeviceCapabilityBillboardAltMode * @discussion Device Capability Billboard Alternate mode. * USB Billboard 3.1.6.3: Billboard Capability Descriptor V1.21 */ struct IOUSBDeviceCapabilityBillboardAltMode { uint8_t bLength; uint8_t bDescriptorType; uint8_t bDevCapabilityType; uint8_t bIndex; uint16_t dwAlternateModeVdo; } __attribute__((packed)); typedef struct IOUSBDeviceCapabilityBillboardAltMode IOUSBDeviceCapabilityBillboardAltMode; /*! * @typedef IOUSBInterfaceAssociationDescriptor * @discussion USB Inerface Association Descriptor. ECN to the USB 2.0 Spec. * See the USB Specification at <a href="http://www.usb.org" target="_blank">http://www.usb.org</a>. * USB 3.0 9.6.4: Interface Association */ struct IOUSBInterfaceAssociationDescriptor { uint8_t bLength; uint8_t bDescriptorType; uint8_t bFirstInterface; uint8_t bInterfaceCount; uint8_t bFunctionClass; uint8_t bFunctionSubClass; uint8_t bFunctionProtocol; uint8_t iFunction; } __attribute__((packed)); typedef struct IOUSBInterfaceAssociationDescriptor IOUSBInterfaceAssociationDescriptor; /*! * @typedef IOUSBSuperSpeedEndpointCompanionDescriptor * @discussion Descriptor for a SuperSpeed USB Endpoint Companion. * See the USB Specification at <a href="http://www.usb.org"TARGET="_blank">http://www.usb.org</a>. * USB 3.1 9.6.7: SuperSpeed Endpoint Companion */ struct IOUSBSuperSpeedEndpointCompanionDescriptor { uint8_t bLength; uint8_t bDescriptorType; uint8_t bMaxBurst; uint8_t bmAttributes; uint16_t wBytesPerInterval; } __attribute__((packed)); typedef struct IOUSBSuperSpeedEndpointCompanionDescriptor IOUSBSuperSpeedEndpointCompanionDescriptor; enum { kIOUSBSuperSpeedEndpointCompanionDescriptorMaxBurst = IOUSBBitRange(0, 4), kIOUSBSuperSpeedEndpointCompanionDescriptorMaxBurstPhase = IOUSBBitRangePhase(0, 4), kIOUSBSuperSpeedEndpointCompanionDescriptorBulkMaxStreams = IOUSBBitRange(0, 4), kIOUSBSuperSpeedEndpointCompanionDescriptorBulkMaxStreamsPhase = IOUSBBitRangePhase(0, 4), kIOUSBSuperSpeedEndpointCompanionDescriptorBulkReserved = IOUSBBitRange(5, 7), kIOUSBSuperSpeedEndpointCompanionDescriptorBulkReservedPhase = IOUSBBitRangePhase(5, 7), kIOUSBSuperSpeedEndpointCompanionDescriptorIsocMult = IOUSBBitRange(0, 1), kIOUSBSuperSpeedEndpointCompanionDescriptorIsocMultPhase = IOUSBBitRangePhase(0, 1), kIOUSBSuperSpeedEndpointCompanionDescriptorIsocReserved = IOUSBBitRange(2, 6), kIOUSBSuperSpeedEndpointCompanionDescriptorIsocReservedPhase = IOUSBBitRangePhase(2, 6), kIOUSBSuperSpeedEndpointCompanionDescriptorSSPIsocCompanion = IOUSBBit(7) }; /*! * @typedef IOUSBSuperSpeedPlusIsochronousEndpointCompanionDescriptor * @discussion Descriptor for a SuperSpeedPlus Isochronout USB Endpoint Companion. * See the USB Specification at <a href="http://www.usb.org"TARGET="_blank">http://www.usb.org</a>. * USB 3.1 9.6.8: SuperSpeedPlus Isochronous Endpoint Companion */ struct IOUSBSuperSpeedPlusIsochronousEndpointCompanionDescriptor { uint8_t bLength; uint8_t bDescriptorType; uint16_t wReserved; uint32_t dwBytesPerInterval; } __attribute__((packed)); typedef struct IOUSBSuperSpeedPlusIsochronousEndpointCompanionDescriptor IOUSBSuperSpeedPlusIsochronousEndpointCompanionDescriptor; /*! * @typedef IOUSB20HubDescriptor * @discussion Descriptor for a USB hub. * See the USB Specification at <a href="http://www.usb.org"TARGET="_blank">http://www.usb.org</a>. * USB 2.0 11.23.2.1: Hub Descriptor */ struct IOUSB20HubDescriptor { uint8_t bLength; uint8_t bDescriptorType; uint8_t bNumberPorts; uint16_t wHubCharacteristics; uint8_t bPowerOnToPowerGood; uint8_t bHubControllerCurrent; uint8_t deviceRemovable[2]; // Technically variable size uint8_t reserved[2]; // Unused } __attribute__((packed)); typedef struct IOUSB20HubDescriptor IOUSB20HubDescriptor; /*! * @typedef IOUSBSuperSpeedHubDescriptor * @discussion Descriptor for a Super Speed USB hub. * See the USB Specification at <a href="http://www.usb.org"TARGET="_blank">http://www.usb.org</a>. * USB 3.0 10.13.2.1: SuperSpeed Hub Descriptor */ struct IOUSBSuperSpeedHubDescriptor { uint8_t bLength; uint8_t bDescriptorType; uint8_t bNumberPorts; uint16_t wHubCharacteristics; uint8_t bPowerOnToPowerGood; uint8_t bHubControllerCurrent; uint8_t bHubDecodeLatency; uint16_t wHubDelay; uint16_t deviceRemovable; } __attribute__((packed)); typedef struct IOUSBSuperSpeedHubDescriptor IOUSBSuperSpeedHubDescriptor; enum { kIOUSBSuperSpeedHubCharacteristicsPowerSwitchingMask = IOUSBBitRange(0, 1), kIOUSBSuperSpeedHubCharacteristicsPowerSwitchingGanged = (0 << IOUSBBitRangePhase(0, 1)), kIOUSBSuperSpeedHubCharacteristicsPowerSwitchingIndividual = (1 << IOUSBBitRangePhase(0, 1)), kIOUSBSuperSpeedHubCharacteristicsCompoundDevice = IOUSBBit(2), kIOUSBSuperSpeedHubCharacteristicsOverCurrentMask = IOUSBBitRange(3, 4), kIOUSBSuperSpeedHubCharacteristicsOverCurrentGlobal = (0 << IOUSBBitRangePhase(3, 4)), kIOUSBSuperSpeedHubCharacteristicsOverCurrentIndividual = (1 << IOUSBBitRangePhase(3, 4)), kIOUSBSuperSpeedHubCharacteristicsReserved = IOUSBBitRange(5, 15), kIOUSBSuperSpeedHubDecodeLatencyMax = 10, kIOUSBSuperSpeedHubDelayMax = 400 }; /*! * @typedef UASPipeDescriptor * @discussion Structure used to specify the Mass Storage Specific UAS pipe usage descriptor */ struct UASPipeDescriptor { uint8_t bLength; uint8_t bDescriptorType; uint8_t bPipeID; uint8_t bReserved; } __attribute__((packed)); typedef struct UASPipeDescriptor UASPipeDescriptor; /*! * @typedef IOUSBHIDDescriptor * @discussion USB HID Descriptor. See the USB HID Specification at * <a href="http://www.usb.org" target="_blank">http://www.usb.org</a>. */ struct IOUSBHIDDescriptor { uint8_t descLen; uint8_t descType; uint16_t descVersNum; uint8_t hidCountryCode; uint8_t hidNumDescriptors; uint8_t hidDescriptorType; uint8_t hidDescriptorLengthLo; uint8_t hidDescriptorLengthHi; } __attribute__((packed)); typedef struct IOUSBHIDDescriptor IOUSBHIDDescriptor; /*! * @typedef IOUSBHIDReportDesc * @discussion USB HID Report Descriptor header. See the USB HID Specification at * <a href="http://www.usb.org" target="_blank">http://www.usb.org</a>. */ struct IOUSBHIDReportDesc { uint8_t hidDescriptorType; uint8_t hidDescriptorLengthLo; uint8_t hidDescriptorLengthHi; } __attribute__((packed)); typedef struct IOUSBHIDReportDesc IOUSBHIDReportDesc; /*! * @typedef IOUSBDFUDescriptor * @discussion USB Device Firmware Update Descriptor. See the USB Device Firmware Update * Specification at <a href="http://www.usb.org" target="_blank">http://www.usb.org</a>. */ struct IOUSBDFUDescriptor { uint8_t bLength; uint8_t bDescriptorType; uint8_t bmAttributes; uint16_t wDetachTimeout; uint16_t wTransferSize; } __attribute__((packed)); typedef struct IOUSBDFUDescriptor IOUSBDFUDescriptor; #pragma mark Device requests /*! * @typedef IOUSBDeviceRequest * @discussion Standard device request. * See the USB Specification at <a href="http://www.usb.org"TARGET="_blank">http://www.usb.org</a>. * USB 2.0 9.3: USB Device Requests */ struct IOUSBDeviceRequest { uint8_t bmRequestType; uint8_t bRequest; uint16_t wValue; uint16_t wIndex; uint16_t wLength; } __attribute__((packed)); typedef struct IOUSBDeviceRequest IOUSBDeviceRequest; /*! * @typedef IOUSBDeviceRequestSetSELData * @discussion See the USB Specification at <a href="http://www.usb.org"TARGET="_blank">http://www.usb.org</a>. * USB 3.0 9.4.12: Set SEL Standard Device Request */ struct IOUSBDeviceRequestSetSELData { uint8_t u1Sel; // Time in μs for U1 System Exit Latency uint8_t u1Pel; // Time in μs for U1 Device to Host Exit Latency uint16_t u2Sel; // Time in μs for U2 System Exit Latency uint16_t u2Pel; // Time in μs for U2 Device to Host Exit Latency } __attribute__((packed)); typedef struct IOUSBDeviceRequestSetSELData IOUSBDeviceRequestSetSELData; /*! * @enum tIOUSBDeviceRequestDirectionValue * @brief Values of 'direction' field of a device request * @constant kIOUSBDeviceRequestDirectionValueOut the device request data phase direction is host-to-device * @constant kIOUSBDeviceRequestDirectionValueIn the device request data phase direction is device-to-host */ enum tIOUSBDeviceRequestDirectionValue { kIOUSBDeviceRequestDirectionValueOut = 0, kIOUSBDeviceRequestDirectionValueIn = 1 }; typedef enum tIOUSBDeviceRequestDirectionValue tIOUSBDeviceRequestDirectionValue; /*! * @enum tIOUSBDeviceRequestType * @brief Values of 'type' field of a device request * @constant kIOUSBDeviceRequestTypeValueStandard the device request is a standard device request * @constant kIOUSBDeviceRequestTypeValueClass the device request is a class specified device request * @constant kIOUSBDeviceRequestTypeValueVendor the device request is a vendor specified device request */ enum tIOUSBDeviceRequestTypeValue { kIOUSBDeviceRequestTypeValueStandard = 0, kIOUSBDeviceRequestTypeValueClass = 1, kIOUSBDeviceRequestTypeValueVendor = 2 }; typedef enum tIOUSBDeviceRequestTypeValue tIOUSBDeviceRequestTypeValue; /*! * @enum tIOUSBDeviceRequestRecipientValue * @brief Values of 'recipient' field of a device request * @constant kIOUSBDeviceRequestRecipientValueDevice the device request's recipient is a device * @constant kIOUSBDeviceRequestRecipientValueInterface the device request's recipient is an interface * @constant kIOUSBDeviceRequestRecipientValueEndpoint the device request's recipient is an endpoint * @constant kIOUSBDeviceRequestRecipientValueOther the device request's recipient is an other type */ enum tIOUSBDeviceRequestRecipientValue { kIOUSBDeviceRequestRecipientValueDevice = 0, kIOUSBDeviceRequestRecipientValueInterface = 1, kIOUSBDeviceRequestRecipientValueEndpoint = 2, kIOUSBDeviceRequestRecipientValueOther = 3 }; typedef enum tIOUSBDeviceRequestRecipientValue tIOUSBDeviceRequestRecipientValue; enum tIOUSBDeviceRequest { kIOUSBDeviceRequestSize = 8, kIOUSBDeviceRequestDirectionMask = IOUSBBit(7), kIOUSBDeviceRequestDirectionPhase = IOUSBBitRangePhase(7, 7), kIOUSBDeviceRequestDirectionOut = (kIOUSBDeviceRequestDirectionValueOut << kIOUSBDeviceRequestDirectionPhase), kIOUSBDeviceRequestDirectionIn = (kIOUSBDeviceRequestDirectionValueIn << kIOUSBDeviceRequestDirectionPhase), kIOUSBDeviceRequestTypeMask = IOUSBBitRange(5, 6), kIOUSBDeviceRequestTypePhase = IOUSBBitRangePhase(5, 6), kIOUSBDeviceRequestTypeStandard = (kIOUSBDeviceRequestTypeValueStandard << kIOUSBDeviceRequestTypePhase), kIOUSBDeviceRequestTypeClass = (kIOUSBDeviceRequestTypeValueClass << kIOUSBDeviceRequestTypePhase), kIOUSBDeviceRequestTypeVendor = (kIOUSBDeviceRequestTypeValueVendor << kIOUSBDeviceRequestTypePhase), kIOUSBDeviceRequestRecipientMask = IOUSBBitRange(0, 4), kIOUSBDeviceRequestRecipientPhase = IOUSBBitRangePhase(0, 4), kIOUSBDeviceRequestRecipientDevice = (kIOUSBDeviceRequestRecipientValueDevice << kIOUSBDeviceRequestRecipientPhase), kIOUSBDeviceRequestRecipientInterface = (kIOUSBDeviceRequestRecipientValueInterface << kIOUSBDeviceRequestRecipientPhase), kIOUSBDeviceRequestRecipientEndpoint = (kIOUSBDeviceRequestRecipientValueEndpoint << kIOUSBDeviceRequestRecipientPhase), kIOUSBDeviceRequestRecipientOther = (kIOUSBDeviceRequestRecipientValueOther << kIOUSBDeviceRequestRecipientPhase), }; // USB 2.0 9.4: Standard Device Requests // USB 3.0 9.4: Standard Device Requests enum { kIOUSBDeviceRequestGetStatus = 0, kIOUSBDeviceRequestClearFeature = 1, kIOUSBDeviceRequestGetState = 2, kIOUSBDeviceRequestSetFeature = 3, kIOUSBDeviceRequestSetAddress = 5, kIOUSBDeviceRequestGetDescriptor = 6, kIOUSBDeviceRequestSetDescriptor = 7, kIOUSBDeviceRequestGetConfiguration = 8, kIOUSBDeviceRequestSetConfiguration = 9, kIOUSBDeviceRequestGetInterface = 10, kIOUSBDeviceRequestSetInterface = 11, kIOUSBDeviceRequestSynchFrame = 12, kIOUSBDeviceRequestSetSel = 48, kIOUSBDeviceRequestSetIsochronousDelay = 49 }; // USB 2.0 9.4.5: Get Status // USB 3.0 9.4.5: Get Status enum { kIOUSBDeviceStatusSelfPowered = IOUSBBit(0), kIOUSBDeviceStatusRemoteWakeEnable = IOUSBBit(1), kIOUSBDeviceStatusU1Enable = IOUSBBit(2), kIOUSBDeviceStatusU2Enable = IOUSBBit(3), kIOUSBDeviceStatusLTMEnable = IOUSBBit(4), kIOUSBInterfaceStatusRemoteWakeCapable = IOUSBBit(0), kIOUSBInterfaceStatusRemoteWakeEnable = IOUSBBit(1), IOUSBEndpointStatusHalt = IOUSBBit(0) }; // USB 2.0 Table 9-6: Standard Feature Selectors // USB 3.0 Table 9-7: Standard Feature Selectors enum { kIOUSBDeviceFeatureSelectorRemoteWakeup = 1, kIOUSBDeviceFeatureSelectorTestMode = 2, kIOUSBDeviceFeatureSelectorU1Enable = 48, kIOUSBDeviceFeatureSelectorU2Enable = 49, kIOUSBDeviceFeatureSelectorLTMEnable = 50, kIOUSBInterfaceFeatureSelectorSuspend = 0, IOUSBEndpointFeatureSelectorStall = 0, }; // USB 3.0 Table 9-8: Suspend Options enum { kIOUSBInterfaceSuspendLowPower = IOUSBBit(0), kIOUSBInterfaceSuspendRemoteWakeEnable = IOUSBBit(1) }; // USB 3.0 Table 10-16: Hub Parameters enum { kIOUSBHubPort2PortExitLatencyNs = 1000, kIOUSBHubDelayNs = 400 }; // USB 3.0 Table 8-33: Timing Parameters enum { kIOUSBPingResponseTimeNs = 400 }; #pragma mark Power Constants enum tIOUSBBusVoltage { kIOUSBBusVoltageDefault = 5 }; enum tIOUSB20BusCurrent { kIOUSB20BusCurrentMinimum = 100, kIOUSB20BusCurrentDefault = 500, kIOUSB20BusCurrentMaxPowerUnits = 2 }; enum tIOUSB30BusCurrent { kIOUSB30BusCurrentMinimum = 150, kIOUSB30BusCurrentDefault = 900, kIOUSB30BusCurrentMaxPowerUnits = 8 }; #pragma mark USB 2.0 constants // USB 2.0 4.1.1 enum tIOUSBTopology { kIOUSBTopologyHost = 1, kIOUSBTopologyRootPort = 2, kIOUSBTopology1Hub = 3, kIOUSBTopology2Hub = 4, kIOUSBTopology3Hub = 5, kIOUSBTopology4Hub = 6, kIOUSBTopology5Hub = 7, kIOUSBTopologyTierLimit = kIOUSBTopology5Hub }; #pragma mark USB 3.0 constants // USB 3.0 Table 6-21 enum tIOUSB30ResetTimeout { kIOUSB30ResetMinimumTimeout = 80, kIOUSB30ResetTypicalTimeout = 100, kIOUSB30ResetMaximumTimeout = 120, kIOUSB30ResetMaximumWithMarginTimeout = 150 }; // USB 3.0 Table 7-12 enum tIOUSB30LinkStateTimeout { kIOUSB30LinkStateSSInactiveQuietTimeout = 12, kIOUSB30LinkStateRxDetectQuietTimeout = 12, kIOUSB30LinkStatePollingLFPSTimeout = 360, kIOUSB30LinkStatePollingActiveTimeout = 12, kIOUSB30LinkStatePollingConfigurationTimeout = 12, kIOUSB30LinkStatePollingIdleTimeout = 2, kIOUSB30LinkStateU0RecoveryTimeout = 1, kIOUSB30LinkStateU0LTimeout = 0, // 10 microseconds kIOUSB30LinkStateU1NoLFPSResponseTimeout = 2, kIOUSB30LinkStateU1PingTimeout = 300, kIOUSB30LinkStateU2NoLFPSResponseTimeout = 2, kIOUSB30LinKStateU2RxDetectDelay = 100, kIOUSB30LinkStateU3NoLFPSResponseTimeout = 10, kIOUSB30LinkStateU3WakeupRetryDelay = 100, kIOUSB30LinkStateU3RxDetectDelay = 100, kIOUSB30LinkStateRecoveryActiveTimeout = 12, kIOUSB30LinkStateRecoveryConfigurationTimeout = 6, kIOUSB30LinkStateRecoveryIdleTimeout = 2, kIOUSB30LinkStateLoopbackExitTimeout = 2, kIOUSB30LinkStateHotResetActiveTimeout = 12, kIOUSB30LinkStateHotResetExitTimeout = 2, // USB 3.0 7.5.4 kIOUSB30LinkStatePollingDeadline = (kIOUSB30LinkStatePollingLFPSTimeout + 1 + kIOUSB30LinkStatePollingActiveTimeout + kIOUSB30LinkStatePollingConfigurationTimeout + kIOUSB30LinkStatePollingIdleTimeout), // USB 3.0 7.5.9 and 7.5.10 kIOUSB30LinkStateSSResumeDeadline = (kIOUSB30LinkStateU3WakeupRetryDelay /* accomodation for retimer */ + kIOUSB30LinkStateU3NoLFPSResponseTimeout + kIOUSB30LinkStateRecoveryActiveTimeout + kIOUSB30LinkStateRecoveryConfigurationTimeout + kIOUSB30LinkStateRecoveryIdleTimeout), // USB 3.0 7.5.10 kIOUSB30LinkStateRecoveryDeadline = (kIOUSB30LinkStateRecoveryActiveTimeout + kIOUSB30LinkStateRecoveryConfigurationTimeout + kIOUSB30LinkStateRecoveryIdleTimeout + 1 /* margin */), // USB 3.0 7.5.12 kIOUSB30LinkStateHotResetDeadline = kIOUSB30LinkStateHotResetActiveTimeout + kIOUSB30LinkStateHotResetExitTimeout + 1 /* margin */, }; // USB 3.1 Table 8-18 enum tIOUSB30DeviceNotificationType { kIOUSB30DeviceNotificationTypeFunctionWake = 1, kIOUSB30DeviceNotificationTypeLatencyTolerance = 2, kIOUSB30DeviceNotificationTypeBusIntervalAdjustment = 3, kIOUSB30DeviceNotificationTypeHostRoleRequest = 4, kIOUSB30DeviceNotificationTypeSublinkSpeed = 5 }; // USB 3.1 Table 8-36 enum tIOUSB30TimingParameters { kIOUSB30TimingParameterBELTDefaultNs = 1 * 1000 * 1000, kIOUSB30TimingParameterBELTMinNs = 125 * 1000 }; // USB 3.1 Table 10-12 Port Status Type Codes enum tIOUSB30HubPortStatusCode { kIOUSB30HubPortStatusCodeStandard = 0, kIOUSB30HubPortStatusCodePD = 1, kIOUSB30HubPortStatusCodeExt = 2, kIOUSB30HubPortStatusCodeCount = 3 }; // USB 3.2 E.1.2 enum { kIOUSB30RetimerDepthLimit = 4 }; /*! * @typedef IOUSB30HubPortStatusExt * @discussion See the USB Specification at <a href="http://www.usb.org"TARGET="_blank">http://www.usb.org</a>. * USB 3.1 10.16.2.6 Get Port Status */ struct IOUSB30HubPortStatusExt { uint16_t wPortStatus; uint16_t wPortChange; uint32_t dwExtPortStatus; } __attribute__((packed)); // USB 3.1 Table 10-11. Note, offsets are specific to dwExtPortStatus enum tIOUSB30HubExtStatus { kIOUSB30HubExtStatusRxSublinkSpeedID = IOUSBBitRange(0, 3), kIOUSB30HubExtStatusRxSublinkSpeedIDPhase = IOUSBBitRangePhase(0, 3), kIOUSB30HubExtStatusTxSublinkSpeedID = IOUSBBitRange(4, 7), kIOUSB30HubExtStatusTxSublinkSpeedIDPhase = IOUSBBitRangePhase(4, 7), kIOUSB30HubExtStatusRxLaneCount = IOUSBBitRange(8, 11), kIOUSB30HubExtStatusRxLaneCountPhase = IOUSBBitRangePhase(8, 11), kIOUSB30HubExtStatusTxLaneCount = IOUSBBitRange(12, 15), kIOUSB30HubExtStatusTxLaneCountPhase = IOUSBBitRangePhase(12, 15) }; #endif /* AppleUSBCommon_AppleUSBDefinitions_h */
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/usb/USBSpec.h
/* * Copyright � 1998-2012 Apple Inc. All rights reserved. * * @APPLE_LICENSE_HEADER_START@ * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this * file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_LICENSE_HEADER_END@ */ /* * Constants that both OS9 and OSX want to define, and whose values are * specified by the USB Standard. * Put in a seperate file so they can be included if the OS9 include file isn't already * included. */ #ifndef _USBSPEC_H #define _USBSPEC_H #include <IOKit/usb/AppleUSBDefinitions.h> #include <IOKit/usb/IOUSBHostFamilyDefinitions.h> #if defined(__has_include) #if __has_include(<IOKit/usb/IOUSBHostFamily.h>) #include <IOKit/usb/IOUSBHostFamily.h> #endif #if __has_include(<IOKit/usb/StandardUSB.h>) #include <IOKit/usb/StandardUSB.h> #ifdef __cplusplus using namespace StandardUSB; #endif #endif #endif #ifdef __cplusplus extern "C" { #endif #if TARGET_OS_OSX || TARGET_OS_MACCATALYST /* Nothing to define */ #else /* @enum Feature constants @discussion Used with SET_FEATURE requests */ enum { kUSBFunctionSuspendLowPower = kIOUSBInterfaceSuspendLowPower, kUSBFunctionSuspendEnableRemoteWake = kIOUSBInterfaceSuspendRemoteWakeEnable }; /*! @enum Device Status @discussion Specified bits returned by a get status request */ enum { kUSBDeviceStatusSelfPowered = kIOUSBDeviceStatusSelfPowered, kUSBDeviceStatusRemoteWake = kIOUSBDeviceStatusRemoteWakeEnable, kUSBDeviceStatusU1Enable = kIOUSBDeviceStatusU1Enable, kUSBDeviceStatusU2Enable = kIOUSBDeviceStatusU2Enable, kUSBDeviceStatusLTMEnable = kIOUSBDeviceStatusLTMEnable, kUSBInterfaceStatusFunctionRemoteWakeCapable = kIOUSBInterfaceStatusRemoteWakeCapable, kUSBInterfaceStatusFunctionRemoteWake = kIOUSBInterfaceStatusRemoteWakeEnable, kUSBPipeStatusHalt = IOUSBEndpointStatusHalt }; #endif /*! @header USBSpec.h @abstract Constants and definitions of parameters that are used in communcating with USB devices and interfaces. @discussion */ /*! @enum Endpoint type @discussion Used in IOUSBFindEndpointRequest's type field */ enum { kUSBControl = kIOUSBEndpointTypeControl, kUSBIsoc = kIOUSBEndpointTypeIsochronous, kUSBBulk = kIOUSBEndpointTypeBulk, kUSBInterrupt = kIOUSBEndpointTypeInterrupt, kUSBAnyType = 0xFF }; /*! @enum Endpoint direction @discussion Used in IOUSBFindEndpointRequest's direction field */ enum { kUSBOut = kIOUSBEndpointDirectionOut, kUSBIn = kIOUSBEndpointDirectionIn, kUSBNone = kIOUSBEndpointDirectionUnknown, kUSBAnyDirn = 3 }; /*! @enum Device Request Type @discussion This type is encoded in the bmRequestType field of a Device Request. It specifies the type of request: standard, class or vendor specific. */ enum { kUSBStandard = kIOUSBDeviceRequestTypeValueStandard, kUSBClass = kIOUSBDeviceRequestTypeValueClass, kUSBVendor = kIOUSBDeviceRequestTypeValueVendor }; /*! @enum Device Request Recipient @discussion This recipient is encoded in the bmRequestType field of a Device Request. It specifies the type of recipient for a request: the device, the interface, or an endpoint. */ enum { kUSBDevice = kIOUSBDeviceRequestRecipientValueDevice, kUSBInterface = kIOUSBDeviceRequestRecipientValueInterface, kUSBEndpoint = kIOUSBDeviceRequestRecipientValueEndpoint, kUSBOther = kIOUSBDeviceRequestRecipientValueOther }; /*! @enum Device Request @discussion Specifies values for the bRequest field of a Device Request. */ enum { kUSBRqGetStatus = kIOUSBDeviceRequestGetStatus, kUSBRqClearFeature = kIOUSBDeviceRequestClearFeature, kUSBRqGetState = kIOUSBDeviceRequestGetState, kUSBRqSetFeature = kIOUSBDeviceRequestSetFeature, kUSBRqReserved2 = 4, kUSBRqSetAddress = kIOUSBDeviceRequestSetAddress, kUSBRqGetDescriptor = kIOUSBDeviceRequestGetDescriptor, kUSBRqSetDescriptor = kIOUSBDeviceRequestSetDescriptor, kUSBRqGetConfig = kIOUSBDeviceRequestGetConfiguration, kUSBRqSetConfig = kIOUSBDeviceRequestSetConfiguration, kUSBRqGetInterface = kIOUSBDeviceRequestGetInterface, kUSBRqSetInterface = kIOUSBDeviceRequestSetInterface, kUSBRqSyncFrame = kIOUSBDeviceRequestSynchFrame, kUSBSetSel = kIOUSBDeviceRequestSetSel, kUSBSetIsochDelay = kIOUSBDeviceRequestSetIsochronousDelay }; /*! @enum USB Descriptors @discussion Specifies values for diffent descriptor types. */ enum { kUSBAnyDesc = 0, // Wildcard for searches kUSBDeviceDesc = kIOUSBDescriptorTypeDevice, kUSBConfDesc = kIOUSBDescriptorTypeConfiguration, kUSBStringDesc = kIOUSBDescriptorTypeString, kUSBInterfaceDesc = kIOUSBDescriptorTypeInterface, kUSBEndpointDesc = kIOUSBDescriptorTypeEndpoint, kUSBDeviceQualifierDesc = kIOUSBDescriptorTypeDeviceQualifier, kUSBOtherSpeedConfDesc = kIOUSBDescriptorTypeOtherSpeedConfiguration, kUSBInterfacePowerDesc = kIOUSBDescriptorTypeInterfacePower, kUSBOnTheGoDesc = kIOUSBDescriptorTypeOTG, kUSDebugDesc = kIOUSBDescriptorTypeDebug, kUSBInterfaceAssociationDesc = kIOUSBDescriptorTypeInterfaceAssociation, kUSBBOSDescriptor = kIOUSBDescriptorTypeBOS, kUSBDeviceCapability = kIOUSBDescriptorTypeDeviceCapability, kUSBSuperSpeedEndpointCompanion = kIOUSBDescriptorTypeSuperSpeedUSBEndpointCompanion, kUSB3HUBDesc = kIOUSBDescriptorTypeSuperSpeedHub, kUSBHIDDesc = kIOUSBDecriptorTypeHID, kUSBReportDesc = kIOUSBDecriptorTypeReport, kUSBPhysicalDesc = 0x23, kUSBHUBDesc = kIOUSBDescriptorTypeHub, }; /*! @enum Device Capability Types @discussion Used with decoding the Device Capability descriptor */ enum { kUSBDeviceCapabilityWirelessUSB = kIOUSBDeviceCapabilityTypeWireless, kUSBDeviceCapabilityUSB20Extension = kIOUSBDeviceCapabilityTypeUSB20Extension, kUSBDeviceCapabilitySuperSpeedUSB = kIOUSBDeviceCapabilityTypeSuperSpeed, kUSBDeviceCapabilityContainerID = kIOUSBDeviceCapabilityTypeContainerID, kUSBDeviceCapabilityBillboard = kIOUSBDeviceCapabilityTypeBillboard, kUSBDeviceCapabilityBillboardAltMode = kIOUSBDeviceCapabilityTypeBillboardAltMode }; /*! @enum Feature Selectors @discussion Used with SET/CLEAR_FEATURE requests. */ enum { kUSBFeatureEndpointStall = IOUSBEndpointFeatureSelectorStall, // Endpoint kUSBFeatureDeviceRemoteWakeup = kIOUSBDeviceFeatureSelectorRemoteWakeup, // Device kUSBFeatureTestMode = kIOUSBDeviceFeatureSelectorTestMode, // Device kUSBFeatureFunctionSuspend = kIOUSBInterfaceFeatureSelectorSuspend, // Interface kUSBFeatureU1Enable = kIOUSBDeviceFeatureSelectorU1Enable, // Device kUSBFeatureU2Enable = kIOUSBDeviceFeatureSelectorU2Enable, // Device kUSBFeatureLTMEnable = kIOUSBDeviceFeatureSelectorLTMEnable // Device }; /*! @enum Miscellaneous bits and masks */ enum { kUSBFunctionRemoteWakeCapableBit = IOUSBBit(0), // GET_STATUS kUSBFunctionRemoteWakeupBit = IOUSBBit(1), // GET_STATUS kUSBLowPowerSuspendStateBit = IOUSBBit(0), // SET_FEATURE(FUNCTION_SUSPEND) kUSBFunctionRemoteWakeEnableBit = IOUSBBit(1) // SET_FEATURE(FUNCTION_SUSPEND) }; /*! @enum USB Power constants @discussion Constants relating to USB Power. */ enum { kUSB100mAAvailable = 50, kUSB500mAAvailable = 250, kUSB100mA = 50, kUSBAtrBusPowered = 0x80, kUSBAtrSelfPowered = 0x40, kUSBAtrRemoteWakeup = 0x20, kUSB2MaxPowerPerPort = kIOUSB20BusCurrentDefault, kUSB150mAAvailable = 75, kUSB900mAAvailable = 450, kUSB150mA = 75, kUSB3MaxPowerPerPort = kIOUSB30BusCurrentDefault }; /*! @enum USB Release constants @discussion Constants relating to USB releases as found in the bcdUSB field of the Device Descriptor. */ enum { kUSBRel10 = 0x0100, kUSBRel11 = 0x0110, kUSBRel20 = 0x0200, kUSBRel30 = 0x0300 }; /*! @enum HID requests @discussion Constants for HID requests. */ enum { kHIDRqGetReport = 1, kHIDRqGetIdle = 2, kHIDRqGetProtocol = 3, kHIDRqSetReport = 9, kHIDRqSetIdle = 10, kHIDRqSetProtocol = 11 }; /*! @enum HID report types @discussion Constants for the three kinds of HID reports. */ enum { kHIDRtInputReport = 1, kHIDRtOutputReport = 2, kHIDRtFeatureReport = 3 }; /*! @enum HID Protocol @discussion Used in the SET_PROTOCOL device request */ enum { kHIDBootProtocolValue = 0, kHIDReportProtocolValue = 1 }; enum { kUSBCapsLockKey = 0x39, kUSBNumLockKey = 0x53, kUSBScrollLockKey = 0x47 }; /*! @enum Device Class Codes @discussion Constants for USB Device classes (bDeviceClass). */ enum { kUSBCompositeClass = 0, kUSBCommClass = 2, // Deprecated kUSBCommunicationClass = 2, kUSBHubClass = 9, kUSBDataClass = 10, kUSBPersonalHealthcareClass = 15, kUSBBillBoardClass = 17, kUSBDiagnosticClass = 220, kUSBWirelessControllerClass = 224, kUSBMiscellaneousClass = 239, kUSBApplicationSpecificClass = 254, kUSBVendorSpecificClass = 255 }; /*! @enum Interface Class @discussion Constants for Interface classes (bInterfaceClass). */ enum { kUSBAudioClass = 1, // Deprecated kUSBAudioInterfaceClass = 1, kUSBCommunicationControlInterfaceClass = 2, kUSBCommunicationDataInterfaceClass = 10, kUSBHIDClass = 3, kUSBHIDInterfaceClass = 3, kUSBPhysicalInterfaceClass = 5, kUSBImageInterfaceClass = 6, kUSBPrintingClass = 7, // Deprecated kUSBPrintingInterfaceClass = 7, kUSBMassStorageClass = 8, // Deprecated kUSBMassStorageInterfaceClass = 8, kUSBChipSmartCardInterfaceClass = 11, kUSBContentSecurityInterfaceClass = 13, kUSBVideoInterfaceClass = 14, kUSBPersonalHealthcareInterfaceClass = 15, kUSBDiagnosticDeviceInterfaceClass = 220, kUSBWirelessControllerInterfaceClass = 224, kUSBApplicationSpecificInterfaceClass = 254, kUSBVendorSpecificInterfaceClass = 255 }; // Obsolete enum { kUSBDisplayClass = 4 // Obsolete }; /*! @enum Interface SubClass @discussion Constants for USB Interface SubClasses (bInterfaceSubClass). */ enum { kUSBCompositeSubClass = 0, kUSBHubSubClass = 0, // For the kUSBAudioInterfaceClass // kUSBAudioControlSubClass = 0x01, kUSBAudioStreamingSubClass = 0x02, kUSBMIDIStreamingSubClass = 0x03, // For the kUSBApplicationSpecificInterfaceClass // kUSBDFUSubClass = 0x01, kUSBIrDABridgeSubClass = 0x02, kUSBTestMeasurementSubClass = 0x03, // For the kUSBMassStorageInterfaceClass // kUSBMassStorageRBCSubClass = 0x01, kUSBMassStorageATAPISubClass = 0x02, kUSBMassStorageQIC157SubClass = 0x03, kUSBMassStorageUFISubClass = 0x04, kUSBMassStorageSFF8070iSubClass = 0x05, kUSBMassStorageSCSISubClass = 0x06, // For the kUSBHIDInterfaceClass // kUSBHIDBootInterfaceSubClass = 0x01, // For the kUSBCommunicationDataInterfaceClass // kUSBCommDirectLineSubClass = 0x01, kUSBCommAbstractSubClass = 0x02, kUSBCommTelephoneSubClass = 0x03, kUSBCommMultiChannelSubClass = 0x04, kUSBCommCAPISubClass = 0x05, kUSBCommEthernetNetworkingSubClass = 0x06, kUSBATMNetworkingSubClass = 0x07, // For the kUSBDiagnosticDeviceInterfaceClass // kUSBReprogrammableDiagnosticSubClass = 0x01, // For the kUSBWirelessControllerInterfaceClass // kUSBRFControllerSubClass = 0x01, // For the kUSBMiscellaneousClass // kUSBCommonClassSubClass = 0x02, // For the kUSBVideoInterfaceClass // kUSBVideoControlSubClass = 0x01, kUSBVideoStreamingSubClass = 0x02, kUSBVideoInterfaceCollectionSubClass = 0x03 }; enum USBClassSpecificDesc { kUSBClassSpecificDescriptor = 0x24 }; /*! @enum Interface Protocol @discussion Reported in the bInterfaceProtocol field of the Interface Descriptor. */ enum { // For kUSBHubClass kHubSuperSpeedProtocol = 3, // For kUSBHIDInterfaceClass // kHIDNoInterfaceProtocol = 0, kHIDKeyboardInterfaceProtocol = 1, kHIDMouseInterfaceProtocol = 2, kUSBVendorSpecificProtocol = 0xff, // For kUSBDiagnosticDeviceInterfaceClass // kUSB2ComplianceDeviceProtocol = 0x01, // For kUSBWirelessControllerInterfaceClass // kUSBBluetoothProgrammingInterfaceProtocol = 0x01, // For kUSBMiscellaneousClass // KUSBInterfaceAssociationDescriptorProtocol = 0x01, // For Mass Storage // kMSCProtocolControlBulkInterrupt = 0x00, kMSCProtocolControlBulk = 0x01, kMSCProtocolBulkOnly = 0x50, kMSCProtocolUSBAttachedSCSI = 0x62 }; /*! @enum DFU Class Attributes @discussion */ enum { kUSBDFUAttributesMask = 0x07, kUSBDFUCanDownloadBit = 0, kUSBDFUCanUploadBit = 1, kUSBDFUManifestationTolerantBit = 2 }; /*! @enum Printer Class Requests @discussion The bRequest parameter for Printing Class Sepcific Requests */ enum { kUSPrintingClassGetDeviceID = 0, kUSPrintingClassGePortStatus = 1, kUSPrintingClassSoftReset = 2 }; /*! @enum Endpoint Descriptor bits @discussion Bit definitions for endpoint descriptor fields */ enum { kUSBbEndpointAddressMask = 0x0f, kUSBbEndpointDirectionBit = kIOUSBEndpointDescriptorDirectionPhase, kUSBbEndpointDirectionMask = kIOUSBEndpointDescriptorDirection, kUSBEndpointDirectionOut = kIOUSBEndpointDescriptorDirectionOut, kUSBEndpointDirectionIn = kIOUSBEndpointDescriptorDirectionIn, kUSBEndpointbmAttributesTransferTypeMask = kIOUSBEndpointDescriptorTransferType, kUSBEndpointbmAttributesSynchronizationTypeMask = kIOUSBEndpointDescriptorSynchronizationType, kUSBEndpointbmAttributesSynchronizationTypeShift = 2, kUSBEndpointbmAttributesUsageTypeMask = kIOUSBEndpointDescriptorUsageType, kUSBEndpointbmAttributesUsageTypeShift = 4, kUSBPeriodicInterruptUsageType = 0, kUSBNotificationInterruptUsageType = 1, kUSBNoSynchronizationIsocSyncType = 0, kUSBAsynchronousIsocSyncType = 1, kUSBAdaptiveIsocSyncType = 2, kUSBSynchronousIsocSyncType = 3, kUSBDataIsocUsageType = 0, kUSBFeedbackIsocUsageType = 1, kUSBImplicitFeedbackDataIsocUsageType = 2 }; /*! @enum USB Device Capability Type constants @discussion Bit definitions and constants for different values of USB Device Capability types */ enum { kUSB20ExtensionLPMSupported = 1, // Bit 1 of bmAttributes of USB 2.0 Extension Device Capability kUSBSuperSpeedLTMCapable = 1, // Bit 1 of bmAttributes of SuperSpeed USB Device Capability kUSBSuperSpeedSupportsLS = 0, // Value of wSpeedSupported indicating that the device supports low speed kUSBSuperSpeedSupportsFS = 1, // Value of wSpeedSupported indicating that the device supports full speed kUSBSuperSpeedSupportsHS = 2, // Value of wSpeedSupported indicating that the device supports high speed kUSBSuperSpeedSupportsSS = 3, // Value of wSpeedSupported indicating that the device supports 5 Gbps }; /*! @enum USB Device Billboard Capability Vconn Power constants @discussion Power needed by the adapter for full functionality */ enum { kUSBBillboardVConn1Watt = 0, kUSBBillboardVConn1P5Watt = 1, kUSBBillboardVConn2Watt = 2, kUSBBillboardVConn3Watt = 3, kUSBBillboardVConn4Watt = 4, kUSBBillboardVConn5Watt = 5, kUSBBillboardVConn6Watt = 6, kUSBBillboardVConnReserved = 7 }; /*! @defineblock USB Billboard Capability Descriptor Constant @define kUSBBillboardVConnNoPowerReq bit position for No Power Required, VConn b2:0 are ignored when this bit is set */ #define kUSBBillboardVConnNoPowerReq 15 /*! @/defineblock */ /*! @enum USB Device Billboard Capability bmConfigured constants @ A bit pair signifying the state of Alternate Modes */ enum { kUSBBillboardUnspecifiedError = 0, kUSBBillboardConfigNotAttempted = 1, kUSBBillboardConfigUnsuccessful = 2, kUSBBillboardAltModeConfigSuccess = 3 }; /*! @enum USB Device Billboard Capability AdditionalFailureInfo constants @ A bit field signifying additional failure information */ enum { kUSBBillboardAdditinalInfoNoPower = 1, kUSBBillboardAdditinalInfoNoUSBPD = 2 }; /*! @defineblock USB Descriptor and IORegistry constants @discussion Various constants used to describe the fields in the various USB Device Descriptors and IORegistry names used for some of those fields @define kUSBDeviceClass The field in the USB Device Descriptor corresponding to the device class @define kUSBDeviceSubClass The field in the USB Device Descriptor corresponding to the device sub class @define kUSBDeviceProtocol The field in the USB Device Descriptor corresponding to the device protocol @define kUSBDeviceMaxPacketSize The field in the USB Device Descriptor corresponding to the maximum packet size for endpoint 0 @define kUSBVendorID The field in the USB Device Descriptor corresponding to the device USB Vendor ID @define kUSBVendorName Deprecated. Use kUSBVendorID @define kUSBProductID The field in the USB Device Descriptor corresponding to the device USB Product ID @define kUSBProductName Deprecated. Use kUSBProductID @define kUSBDeviceReleaseNumber The field in the USB Device Descriptor corresponding to the device release version @define kUSBManufacturerStringIndex The field in the USB Device Descriptor corresponding to the index for the manufacturer's string @define kUSBProductStringIndex The field in the USB Device Descriptor corresponding to the index for the product name's string @define kUSBSerialNumberStringIndex The field in the USB Device Descriptor corresponding to the index for the serial number's string @define kUSBDeviceNumConfigs The field in the USB Configuration Descriptor corresponding to the number of configurations @define kUSBInterfaceNumber The field in the USB Configuration Descriptor corresponding to the number of configurations @define kUSBAlternateSetting The field in the USB Configuration Descriptor corresponding to the number of configurations @define kUSBNumEndpoints The field in the USB Configuration Descriptor corresponding to the number of configurations @define kUSBInterfaceClass The field in the USB Interface Descriptor corresponding to the interface class @define kUSBInterfaceSubClass The field in the USB Interface Descriptor corresponding to the interface sub class @define kUSBInterfaceProtocol The field in the USB Interface Descriptor corresponding to the interface protocol @define kUSBInterfaceStringIndex The field in the USB Interface Descriptor corresponding to the index for the interface name's string @define kUSBConfigurationValue The field in the USB Interface Descriptor corresponding to the configuration @define kUSBProductString IORegistry key for the device's USB Product string @define kUSBVendorString IORegistry key for the device's USB manufacturer string @define kUSBSerialNumberString IORegistry key for the device's USB serial number string @define kUSB1284DeviceID IORegistry key for the 1284 Device ID of a printer */ #define kUSBDeviceClass kUSBHostMatchingPropertyDeviceClass #define kUSBDeviceSubClass kUSBHostMatchingPropertyDeviceSubClass #define kUSBDeviceProtocol kUSBHostMatchingPropertyDeviceProtocol #define kUSBDeviceMaxPacketSize kUSBHostDevicePropertyMaxPacketSize #define kUSBVendorID kUSBHostMatchingPropertyVendorID #define kUSBVendorName kUSBVendorID // bad name - keep for backward compatibility #define kUSBProductID kUSBHostMatchingPropertyProductID #define kUSBProductName kUSBProductID // bad name - keep for backward compatibility #define kUSBDeviceReleaseNumber kUSBHostMatchingPropertyDeviceReleaseNumber #define kUSBManufacturerStringIndex kUSBHostDevicePropertyManufacturerStringIndex #define kUSBProductStringIndex kUSBHostDevicePropertyProductStringIndex #define kUSBSerialNumberStringIndex kUSBHostDevicePropertySerialNumberStringIndex #define kUSBDeviceNumConfigs kUSBHostDevicePropertyNumConfigs #define kUSBInterfaceNumber kUSBHostMatchingPropertyInterfaceNumber #define kUSBAlternateSetting kUSBHostInterfacePropertyAlternateSetting #define kUSBNumEndpoints kUSBHostInterfacePropertyNumEndpoints #define kUSBInterfaceClass kUSBHostMatchingPropertyInterfaceClass #define kUSBInterfaceSubClass kUSBHostMatchingPropertyInterfaceSubClass #define kUSBInterfaceProtocol kUSBHostMatchingPropertyInterfaceProtocol #define kUSBInterfaceStringIndex kUSBHostInterfacePropertyStringIndex #define kUSBConfigurationValue kUSBHostMatchingPropertyConfigurationValue #define kUSBInterfaceString kUSBHostInterfacePropertyString #define kUSB1284DeviceID "1284 Device ID" #define kUSBCompatibilityMatch "USBCompatibilityMatch" #define kUSBStandardVersion kUSBHostDevicePropertyStandardVersion #define kUSBSpecReleaseNumber kUSBStandardVersion #define kUSBDeviceContainerID kUSBContainerID #define kUSBContainerID kUSBHostDevicePropertyContainerID #if TARGET_OS_OSX || TARGET_OS_MACCATALYST #if MAC_OS_X_VERSION_MIN_REQUIRED <= MAC_OS_X_VERSION_10_14 #define kUSBProductString "USB Product Name" #define kUSBVendorString "USB Vendor Name" #define kUSBSerialNumberString "USB Serial Number" #else #define kUSBProductString kUSBHostDevicePropertyProductString #define kUSBVendorString kUSBHostDevicePropertyVendorString #define kUSBSerialNumberString kUSBHostDevicePropertySerialNumberString #endif /* MAC_OS_X_VERSION_MIN_REQUIRED <= MAC_OS_X_VERSION_10_14 */ #else #define kUSBProductString kUSBHostDevicePropertyProductString #define kUSBVendorString kUSBHostDevicePropertyVendorString #define kUSBSerialNumberString kUSBHostDevicePropertySerialNumberString #endif /*! @enum Apple USB Vendor ID @discussion Apple's vendor ID, assigned by the USB-IF */ enum { kAppleVendorID = kIOUSBAppleVendorID }; #ifdef __cplusplus } #endif #endif
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/usb/IOUSBHostFamilyDefinitions.h
/* * Copyright (c) 1998-2016 Apple Inc. All rights reserved. * * @APPLE_OSREFERENCE_LICENSE_HEADER_START@ * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. The rights granted to you under the License * may not be used to create, or enable the creation or redistribution of, * unlawful or unlicensed copies of an Apple operating system, or to * circumvent, violate, or enable the circumvention or violation of, any * terms of an Apple operating system software license agreement. * * Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_OSREFERENCE_LICENSE_HEADER_END@ */ /*! @header IOUSBHostFamilyDefinitions.h @brief Definitions used for the IOUSBHostFamily !*/ #ifndef IOUSBHostFamily_IOUSBHostFamilyDefinitions_h #define IOUSBHostFamily_IOUSBHostFamilyDefinitions_h #include <TargetConditionals.h> #if TARGET_OS_DRIVERKIT #include <stdint.h> #include <stddef.h> #include <sys/_types/_uuid_t.h> #include <DriverKit/IOTypes.h> #include <DriverKit/IOLib.h> #else #include <IOKit/IOTypes.h> #include <libkern/OSByteOrder.h> #endif #define IOUSBHostFamilyBit(bit) ((uint32_t)(1) << bit) #define IOUSBHostFamilyBitRange(start, end) (~(((uint32_t)(1) << start) - 1) & (((uint32_t)(1) << end) | (((uint32_t)(1) << end) - 1))) #define IOUSBHostFamilyBitRange64(start, end) (~(((uint64_t)(1) << start) - 1) & (((uint64_t)(1) << end) | (((uint64_t)(1) << end) - 1))) #define IOUSBHostFamilyBitRangePhase(start, end) (start) #define iokit_usb_codemask IOUSBHostFamilyBitRange(0, 11) #define iokit_usbhost_group (1 << IOUSBHostFamilyBitRangePhase(12, 13)) #define iokit_usblegacy_group (0 << IOUSBHostFamilyBitRangePhase(12, 13)) #define iokit_usbhost_err(message) ((IOReturn)(iokit_family_err(sub_iokit_usb, iokit_usbhost_group | (message & iokit_usb_codemask)))) #define iokit_usbhost_msg(message) ((uint32_t)(iokit_family_msg(sub_iokit_usb, iokit_usbhost_group | (message & iokit_usb_codemask)))) #define iokit_usblegacy_err_msg(message) ((uint32_t)(sys_iokit | sub_iokit_usb | message)) /*! @definedblock IOUSBHostFamily message codes @discussion Messages passed between USB services using the <code>IOService::message</code> API. */ #define kUSBHostMessageConfigurationSet iokit_usbhost_msg(0x00) // 0xe0005000 IOUSBHostDevice -> clients upon a setConfiguration call. #define kUSBHostMessageRenegotiateCurrent iokit_usbhost_msg(0x01) // 0xe0005001 Request clients to renegotiate bus current allocations #define kUSBHostMessageControllerException iokit_usbhost_msg(0x02) // 0xe0005002 A fatal problem has occurred with an AppleUSBUserHCI controller #define kUSBHostReturnPipeStalled iokit_usbhost_err(0x0) // 0xe0005000 Pipe has issued a STALL handshake. Use clearStall to clear this condition. #define kUSBHostReturnNoPower iokit_usbhost_err(0x1) // 0xe0005001 A setConfiguration call was not able to succeed because all configurations require more power than is available. /*! * @enum tIOUSBHostConnectionSpeed * @brief Connection speeds reported in kUSBHostMatchingPropertySpeed * @discussion This enumeration matches the default speed ID mappings defined in XHCI 1.0 Table 147. * @constant kIOUSBHostConnectionSpeedNone No device is connected * @constant kIOUSBHostConnectionSpeedFull A full-speed (12 Mb/s) device is connected * @constant kIOUSBHostConnectionSpeedLow A low-speed (1.5 Mb/s) device is connected * @constant kIOUSBHostConnectionSpeedHigh A high-speed (480 Mb/s) device is connected) * @constant kIOUSBHostConnectionSpeedSuper A superspeed (5 Gb/s) device is connected) * @constant kIOUSBHostConnectionSpeedSuperPlus A superspeed (10 Gb/s) device is connected) * @constant kIOUSBHostConnectionSpeedSuperPlusBy2 A superspeed (20 Gb/s) device is connected) */ enum tIOUSBHostConnectionSpeed { kIOUSBHostConnectionSpeedNone = 0, kIOUSBHostConnectionSpeedFull = 1, kIOUSBHostConnectionSpeedLow = 2, kIOUSBHostConnectionSpeedHigh = 3, kIOUSBHostConnectionSpeedSuper = 4, kIOUSBHostConnectionSpeedSuperPlus = 5, kIOUSBHostConnectionSpeedSuperPlusBy2 = 6, kIOUSBHostConnectionSpeedCount = 7 }; /*! * @brief Port types returned by IOUSBHostDevice::getPortStatus and kUSBHostPortPropertyStatus * * @constant kIOUSBHostPortTypeStandard A general-purpose USB port. * @constant kIOUSBHostPortTypeCaptive The attached device cannot be physically disconnected from the port. * @constant kIOUSBHostPortTypeInternal The attached device cannot be physically disconnected from the host machine. * @constant kIOUSBHostPortTypeAccessory The attached device may require authentication before function drivers can access it. * @constant kIOUSBHostPortTypeCount The number of entries in this enum. */ enum tIOUSBHostPortType { kIOUSBHostPortTypeStandard = 0, kIOUSBHostPortTypeCaptive, kIOUSBHostPortTypeInternal, kIOUSBHostPortTypeAccessory, kIOUSBHostPortTypeExpressCard, kIOUSBHostPortTypeCount }; /*! * @brief Values returned by IOUSBHostDevice::getPortStatus and kUSBHostPortPropertyStatus * * @constant kIOUSBHostPortStatusPortTypeMask The mask for bits representing the port type. * @constant kIOUSBHostPortStatusPortTypeStandard A general-purpose USB port. * @constant kIOUSBHostPortStatusPortTypeCaptive The attached device cannot be physically disconnected from the port. * @constant kIOUSBHostPortStatusPortTypeInternal The attached device cannot be physically disconnected from the host machine. * @constant kIOUSBHostPortStatusPortTypeAccessory The attached device may require authentication before function drivers can access it. * @constant kIOUSBHostPortStatusConnectedSpeedMask The mask for bits representing the connection state. * @constant kIOUSBHostPortStatusConnectedSpeedNone The port does not have a connected device. * @constant kIOUSBHostPortStatusConnectedSpeedFull The port has a full-speed device connected. * @constant kIOUSBHostPortStatusConnectedSpeedLow The port has a low-speed device connected. * @constant kIOUSBHostPortStatusConnectedSpeedHigh The port has a high-speed device connected. * @constant kIOUSBHostPortStatusConnectedSpeedSuper The port has a superspeed device connected. * @constant kIOUSBHostPortStatusResetting The port is currently resetting the link. * @constant kIOUSBHostPortStatusEnabled The port is enabled and packets are permitted to reach the device. Not valid unless kIOUSBHostPortStatusConnectedSpeedMask is nonzero. * @constant kIOUSBHostPortStatusSuspended The port is suspended. Not valid unless kIOUSBHostPortStatusConnectedSpeedMask is nonzero. * @constant kIOUSBHostPortStatusOvercurrent The port is in the overcurrent condition. * @constant kIOUSBHostPortStatusTestMode The port is in test mode. */ enum tIOUSBHostPortStatus { kIOUSBHostPortStatusPortTypeMask = IOUSBHostFamilyBitRange(0, 3), kIOUSBHostPortStatusPortTypePhase = IOUSBHostFamilyBitRangePhase(0, 3), kIOUSBHostPortStatusPortTypeStandard = (kIOUSBHostPortTypeStandard << IOUSBHostFamilyBitRangePhase(0, 3)), kIOUSBHostPortStatusPortTypeCaptive = (kIOUSBHostPortTypeCaptive << IOUSBHostFamilyBitRangePhase(0, 3)), kIOUSBHostPortStatusPortTypeInternal = (kIOUSBHostPortTypeInternal << IOUSBHostFamilyBitRangePhase(0, 3)), kIOUSBHostPortStatusPortTypeAccessory = (kIOUSBHostPortTypeAccessory << IOUSBHostFamilyBitRangePhase(0, 3)), kIOUSBHostPortStatusPortTypeReserved = IOUSBHostFamilyBitRange(4, 7), kIOUSBHostPortStatusConnectedSpeedMask = IOUSBHostFamilyBitRange(8, 10), kIOUSBHostPortStatusConnectedSpeedPhase = IOUSBHostFamilyBitRangePhase(8, 10), kIOUSBHostPortStatusConnectedSpeedNone = (kIOUSBHostConnectionSpeedNone << IOUSBHostFamilyBitRangePhase(8, 10)), kIOUSBHostPortStatusConnectedSpeedFull = (kIOUSBHostConnectionSpeedFull << IOUSBHostFamilyBitRangePhase(8, 10)), kIOUSBHostPortStatusConnectedSpeedLow = (kIOUSBHostConnectionSpeedLow << IOUSBHostFamilyBitRangePhase(8, 10)), kIOUSBHostPortStatusConnectedSpeedHigh = (kIOUSBHostConnectionSpeedHigh << IOUSBHostFamilyBitRangePhase(8, 10)), kIOUSBHostPortStatusConnectedSpeedSuper = (kIOUSBHostConnectionSpeedSuper << IOUSBHostFamilyBitRangePhase(8, 10)), kIOUSBHostPortStatusConnectedSpeedSuperPlus = (kIOUSBHostConnectionSpeedSuperPlus << IOUSBHostFamilyBitRangePhase(8, 10)), kIOUSBHostPortStatusConnectedSpeedSuperPlusBy2 = (kIOUSBHostConnectionSpeedSuperPlusBy2 << IOUSBHostFamilyBitRangePhase(8, 10)), kIOUSBHostPortStatusResetting = IOUSBHostFamilyBit(11), kIOUSBHostPortStatusEnabled = IOUSBHostFamilyBit(12), kIOUSBHostPortStatusSuspended = IOUSBHostFamilyBit(13), kIOUSBHostPortStatusOvercurrent = IOUSBHostFamilyBit(14), kIOUSBHostPortStatusTestMode = IOUSBHostFamilyBit(15) }; #pragma mark Entitlements #define kIOUSBTransportDextEntitlement "com.apple.developer.driverkit.transport.usb" #define kIOUSBHostVMEntitlement "com.apple.vm.device-access" #define kIOUSBHostControllerInterfaceEntitlement "com.apple.developer.usb.host-controller-interface" #pragma mark Registry property names #define kUSBHostMatchingPropertySpeed "USBSpeed" #define kUSBHostMatchingPropertyPortType "USBPortType" #define kUSBHostMatchingPropertyVendorID "idVendor" #define kUSBHostMatchingPropertyProductID "idProduct" #define kUSBHostMatchingPropertyProductIDMask "idProductMask" #define kUSBHostMatchingPropertyProductIDArray "idProductArray" #define kUSBHostMatchingPropertyDeviceClass "bDeviceClass" #define kUSBHostMatchingPropertyDeviceSubClass "bDeviceSubClass" #define kUSBHostMatchingPropertyDeviceProtocol "bDeviceProtocol" #define kUSBHostMatchingPropertyDeviceReleaseNumber "bcdDevice" #define kUSBHostMatchingPropertyConfigurationValue "bConfigurationValue" #define kUSBHostMatchingPropertyInterfaceClass "bInterfaceClass" #define kUSBHostMatchingPropertyInterfaceSubClass "bInterfaceSubClass" #define kUSBHostMatchingPropertyInterfaceProtocol "bInterfaceProtocol" #define kUSBHostMatchingPropertyInterfaceNumber "bInterfaceNumber" #define kUSBHostPropertyLocationID "locationID" #define kUSBHostPropertyDebugOptions "kUSBDebugOptions" #define kUSBHostPropertyWakePowerSupply "kUSBWakePowerSupply" #define kUSBHostPropertySleepPowerSupply "kUSBSleepPowerSupply" #define kUSBHostPropertyWakePortCurrentLimit "kUSBWakePortCurrentLimit" #define kUSBHostPropertySleepPortCurrentLimit "kUSBSleepPortCurrentLimit" #define kUSBHostPropertyFailedRemoteWake "kUSBFailedRemoteWake" #define kUSBHostPropertyBusCurrentPoolID "UsbBusCurrentPoolID" #define kUSBHostPropertySmcBusCurrentPoolID "UsbSmcBusCurrentPoolID" #define kUSBHostPropertyForcePower "UsbForcePower" #define kUSBHostPropertyForceLinkSpeed "UsbLinkSpeed" #define kUSBHostPropertyForceHardwareException "UsbHardwareException" #define kUSBHostPropertyAllowSoftRetry "UsbAllowSoftRetry" #define kUSBHostUserClientPropertyOwningTaskName "UsbUserClientOwningTaskName" #define kUSBHostUserClientPropertyEntitlementRequired "UsbUserClientEntitlementRequired" #define kUSBHostUserClientPropertyEnableReset "UsbUserClientEnableReset" #define kUSBHostUserClientPropertyEnableDataToggleReset "UsbUserClientEnableDataToggleReset" #define kUSBHostDevicePropertyVendorString "kUSBVendorString" #define kUSBHostDevicePropertySerialNumberString "kUSBSerialNumberString" #define kUSBHostDevicePropertyContainerID "kUSBContainerID" #define kUSBHostDevicePropertyFailedRequestedPower "kUSBFailedRequestedPower" #define kUSBHostDevicePropertyResumeRecoveryTime "kUSBResumeRecoveryTime" #define kUSBHostDevicePropertyPreferredConfiguration "kUSBPreferredConfiguration" #define kUSBHostDevicePropertyPreferredRecoveryConfiguration "kUSBPreferredRecoveryConfiguration" #define kUSBHostDevicePropertyCurrentConfiguration "kUSBCurrentConfiguration" #define kUSBHostDevicePropertyRemoteWakeOverride "kUSBRemoteWakeOverride" #define kUSBHostDevicePropertyConfigurationDescriptorOverride "kUSBConfigurationDescriptorOverride" #define kUSBHostDevicePropertyDeviceDescriptorOverride "kUSBDeviceDescriptorOverride" #define kUSBHostDevicePropertyConfigurationCurrentOverride "kUSBConfigurationCurrentOverride" #define kUSBHostDevicePropertyResetDurationOverride "kUSBResetDurationOverride" #define kUSBHostDevicePropertyDesiredChargingCurrent "kUSBDesiredChargingCurrent" #define kUSBHostDevicePropertyDescriptorOverride "kUSBDescriptorOverride" #define kUSBHostDescriptorOverrideVendorStringIndex "UsbDescriptorOverrideVendorStringIndex" #define kUSBHostDescriptorOverrideProductStringIndex "UsbDescriptorOverrideProductStringIndex" #define kUSBHostDescriptorOverrideSerialNumberStringIndex "UsbDescriptorOverrideSerialNumberStringIndex" #define kUSBHostDevicePropertyDeviceECID "kUSBDeviceECID" #define kUSBHostDevicePropertyEnableLPM "kUSBHostDeviceEnableLPM" #define kUSBHostDevicePropertyDisablePortLPM "kUSBHostDeviceDisablePortLPM" // Disable port initiated LPM for this device #define kUSBHostDevicePropertyStreamsSupported "UsbStreamsSupported" // Default kOSBooleanTrue. OSBoolean indicating if streaming endpoints are supported #define kUSBHostBillboardDevicePropertyNumberOfAlternateModes "bNumberOfAlternateModes" #define kUSBHostBillboardDevicePropertyPreferredAlternateMode "bPreferredAlternateMode" #define kUSBHostBillboardDevicePropertyVCONNPower "VCONNPower" #define kUSBHostBillboardDevicePropertyConfigured "bmConfigured" #define kUSBHostBillboardDevicePropertyAdditionalFailureInfo "bAdditonalFailureInfo" #define kUSBHostBillboardDevicePropertyBcdVersion "BcdVersion" #define kUSBHostBillboardDevicePropertySVID "wSVID" #define kUSBHostBillboardDevicePropertyAlternateMode "bAlternateMode" #define kUSBHostBillboardDevicePropertyAlternateModeStringIndex "iAlternateModeString" #define kUSBHostBillboardDevicePropertyAlternateModeString "AlternateModeString" #define kUSBHostBillboardDevicePropertyAddtionalInfoURLIndex "iAddtionalInfoURL" #define kUSBHostBillboardDevicePropertyAddtionalInfoURL "AddtionalInfoURL" #define kUSBHostBillboardDevicePropertydwAlternateModeVdo "dwAlternateModeVdo" #define kUSBHostInterfacePropertyAlternateSetting "bAlternateSetting" #define kUSBHostPortPropertyStatus "port-status" #define kUSBHostPortPropertyOvercurrent "UsbHostPortOvercurrent" #define kUSBHostPortPropertyPortNumber "port" #define kUSBHostPortPropertyRemovable "removable" #define kUSBHostPortPropertyTestMode "kUSBTestMode" #define kUSBHostPortPropertyUsb3ComplianceMode "kUSBHostPortPropertyUsb3ComplianceMode" #define kUSBHostPortPropertySimulateInterrupt "kUSBSimulateInterrupt" #define kUSBHostPortPropertyBusCurrentAllocation "kUSBBusCurrentAllocation" #define kUSBHostPortPropertyBusCurrentSleepAllocation "kUSBBusCurrentSleepAllocation" #define kUSBHostPortPropertyConnectable "UsbConnectable" #define kUSBHostPortPropertyConnectorType "UsbConnector" #define kUSBHostPortPropertyMux "UsbMux" #define kUSBHostPortPropertyCompanionIndex "kUSBCompanionIndex" #define kUSBHostPortPropertyDisconnectInterval "kUSBDisconnectInterval" #define kUSBHostPortPropertyUsbCPortNumber "UsbCPortNumber" #define kUSBHostPortPropertyCompanionPortNumber "UsbCompanionPortNumber" // OSData key to set/get the port number of the companion port #define kUSBHostPortPropertyPowerSource "UsbPowerSource" #define kUSBHostPortPropertyUSB3Mode "Usb3Mode" #define kUSBHostPortPropertyExternalDeviceResetController "kUSBHostPortExternalDeviceResetController" #define kUSBHostPortPropertyExternalDevicePowerController "kUSBHostPortExternalDevicePowerController" #define kUSBHostPortPropertyCardReader "kUSBHostPortPropertyCardReader" #define kUSBHostPortPropertyCardReaderValidateDescriptors "kUSBHostPortPropertyCardReaderValidateDescriptors" #define kUSBHostHubPropertyPowerSupply "kUSBHubPowerSupply" // OSNumber mA available for downstream ports, 0 for bus-powered #define kUSBHostHubPropertyIdlePolicy "kUSBHubIdlePolicy" // OSNumber ms to be used as device idle policy #define kUSBHostHubPropertyStartupDelay "kUSBHubStartupDelay" // OSNumber ms delay before creating downstream ports #define kUSBHostHubPropertyPortSequenceDelay "kUSBHubPortSequenceDelay" // OSNumber ms delay between port creation #define kUSBHostHubPropertyHubPowerSupplyType "kUSBHubPowerSupplyType" // OSNumber for tPowerSupply hub is, 2 for bus-powered, 1 for self #define kUSBHostHubPropertyGlobalSuspendSupported "UsbHubGlobalSuspendSupported" // OSBoolean false to attempt selective suspend (legacy behavior) #define kUSBHostControllerPropertyIsochronousRequiresContiguous "kUSBIsochronousRequiresContiguous" #define kUSBHostControllerPropertySleepSupported "kUSBSleepSupported" #define kUSBHostControllerPropertyRTD3Supported "UsbRTD3Supported" #define kUSBHostControllerPropertyMuxEnabled "kUSBMuxEnabled" #define kUSBHostControllerPropertyCompanion "kUSBCompanion" // OSBoolean false to disable all companion controllers #define kUSBHostControllerPropertyLowSpeedCompanion "kUSBLowSpeedCompanion" // OSBoolean false to disable low-speed companion controller #define kUSBHostControllerPropertyFullSpeedCompanion "kUSBFullSpeedCompanion" // OSBoolean false to disable full-speed companion controller #define kUSBHostControllerPropertyHighSpeedCompanion "kUSBHighSpeedCompanion" // OSBoolean false to disable high-speed companion controller #define kUSBHostControllerPropertySuperSpeedCompanion "kUSBSuperSpeedCompanion" // OSBoolean false to disable superspeed companion controller #define kUSBHostControllerPropertyRevision "Revision" // OSData Major/minor revision number of controller #define kUSBHostControllerPropertyCompanionControllerName "UsbCompanionControllerName" // OSString key to set/get the name of the service, i.e. companion controller dictionary. #define kUSBHostControllerPropertyDisableUSB3LPM "kUSBHostControllerDisableUSB3LPM" // OSBoolean true to disable USB3 LPM on a given controller #define kUSBHostControllerPropertyDisableUSB2LPM "kUSBHostControllerDisableUSB2LPM" // OSBoolean true to disable USB2 LPM on a given controller #define kUSBHostControllerPropertyDisableWakeSources "UsbHostControllerDisableWakeSources" // OSBoolean true to disable connect/disconnect/overcurrent wake sources #define kUSBHostControllerPropertyPersistFullSpeedIsochronous "UsbHostControllerPersistFullSpeedIsochronous" // OSBoolean true to reduce commands related to full-speed isochronous endpoints #define kUSBHostControllerPropertyDeferRegisterService "UsbHostControllerDeferRegisterService" // OSBoolean true to defer registerService call by base class during start #define kUSBHostControllerPropertyStreamPolicy "UsbHostControllerStreamPolicy" // OSNumber containing tUSBStreamPolicy #define kUSBHostControllerPropertyTierLimit "UsbHostControllerTierLimit" // OSNumber containing the number of tiers supported by this controller (See USB 2.0 § 4.1.1) #define kIOUSBHostDeviceClassName "IOUSBHostDevice" #define kIOUSBHostInterfaceClassName "IOUSBHostInterface" // for IOUSBLib compatibility #define kUSBHostDevicePropertyAddress "kUSBAddress" #define kUSBHostDevicePropertyManufacturerStringIndex "iManufacturer" #define kUSBHostDevicePropertySerialNumberStringIndex "iSerialNumber" #define kUSBHostDevicePropertyProductStringIndex "iProduct" #define kUSBHostDevicePropertyProductString "kUSBProductString" #define kUSBHostDevicePropertyNumConfigs "bNumConfigurations" #define kUSBHostDevicePropertyMaxPacketSize "bMaxPacketSize0" #define kUSBHostDevicePropertyStandardVersion "bcdUSB" #define kUSBHostInterfacePropertyStringIndex "iInterface" #define kUSBHostInterfacePropertyString "kUSBString" #define kUSBHostInterfacePropertyNumEndpoints "bNumEndpoints" // Legacy power properties #define kAppleMaxPortCurrent "AAPL,current-available" #define kAppleCurrentExtra "AAPL,current-extra" #define kAppleMaxPortCurrentInSleep "AAPL,max-port-current-in-sleep" #define kAppleCurrentExtraInSleep "AAPL,current-extra-in-sleep" #define kAppleExternalConnectorBitmap "AAPL,ExternalConnectorBitmap" #endif /* IOUSBHostFamily_IOUSBHostFamilyDefinitions_h */
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/avc/IOFireWireAVCLib.h
/* * Copyright (c) 1998-2001 Apple Computer, Inc. All rights reserved. * * @APPLE_LICENSE_HEADER_START@ * * The contents of this file constitute Original Code as defined in and * are subject to the Apple Public Source License Version 1.1 (the * "License"). You may not use this file except in compliance with the * License. Please obtain a copy of the License at * http://www.apple.com/publicsource and read it before using this file. * * This Original Code and all software distributed under the License are * distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT. Please see the * License for the specific language governing rights and limitations * under the License. * * @APPLE_LICENSE_HEADER_END@ */ #ifndef _IOKIT_IOFIREWIREAVCLIB_H_ #define _IOKIT_IOFIREWIREAVCLIB_H_ #include <IOKit/IOCFPlugIn.h> #include <IOKit/firewire/IOFireWireFamilyCommon.h> #include <IOKit/avc/IOFireWireAVCConsts.h> // Unit type UUID /* 6AAF2EF7-D476-11D5-B57C-0003934B81A0 */ #define kIOFireWireAVCLibUnitTypeID CFUUIDGetConstantUUIDWithBytes(NULL, \ 0x6A, 0xAF, 0x2E, 0xF7, 0xD4, 0x76, 0x11, 0xD5, 0xB5, 0x7C, 0x00, 0x03, 0x93, 0x4B, 0x81, 0xA0) // Unit Factory UUID /* 3F4057BC-D479-11D5-9F05-0003934B81A0 */ #define kIOFireWireAVCLibUnitFactoryID CFUUIDGetConstantUUIDWithBytes(NULL, \ 0x3F, 0x40, 0x57, 0xBC, 0xD4, 0x79, 0x11, 0xD5, 0x9F, 0x05, 0x00, 0x03, 0x93, 0x4B, 0x81, 0xA0) // IOFireWireAVCUnitInterface UUID /* FC65C030-D498-11D5-878D-0003934B81A0 */ #define kIOFireWireAVCLibUnitInterfaceID CFUUIDGetConstantUUIDWithBytes(NULL, \ 0xFC, 0x65, 0xC0, 0x30, 0xD4, 0x98, 0x11, 0xD5, 0x87, 0x8D, 0x00, 0x03, 0x93, 0x4B, 0x81, 0xA0) // kIOFireWireAVCLibUnitInterfaceID_v2 UUID - No Throttling of AVC Commands /* 85B5E954-0AEF-11D8-8D19-000393914ABA */ #define kIOFireWireAVCLibUnitInterfaceID_v2 CFUUIDGetConstantUUIDWithBytes(NULL, \ 0x85, 0xB5, 0xE9, 0x54, 0x0A, 0xEF, 0x11, 0xD8, 0x8D, 0x19, 0x00, 0x03, 0x93, 0x91, 0x4A, 0xBA) // Protocol type UUID /* B54BC8F8-D53B-11D5-A1A1-0003934B81A0 */ #define kIOFireWireAVCLibProtocolTypeID CFUUIDGetConstantUUIDWithBytes(NULL, \ 0xB5, 0x4B, 0xC8, 0xF8, 0xD5, 0x3B, 0x11, 0xD5, 0xA1, 0xA1, 0x00, 0x03, 0x93, 0x4B, 0x81, 0xA0) // Protocol Factory UUID /* 8E9AD5AC-D55E-11D5-B7D2-0003934B81A0 */ #define kIOFireWireAVCLibProtocolFactoryID CFUUIDGetConstantUUIDWithBytes(NULL, \ 0x8E, 0x9A, 0xD5, 0xAC, 0xD5, 0x5E, 0x11, 0xD5, 0xB7, 0xD2, 0x00, 0x03, 0x93, 0x4B, 0x81, 0xA0) // IOFireWireAVCProtocolInterface UUID /* CC85D421-D55E-11D5-8A10-0003934B81A0 */ #define kIOFireWireAVCLibProtocolInterfaceID CFUUIDGetConstantUUIDWithBytes(NULL, \ 0xCC, 0x85, 0xD4, 0x21, 0xD5, 0x5E, 0x11, 0xD5, 0x8A, 0x10, 0x00, 0x03, 0x93, 0x4B, 0x81, 0xA0) // IOFireWireAVCLibConsumerInterfaceID /* 7FB7A454-226F-11D6-B889-000A277E7234 */ #define kIOFireWireAVCLibConsumerInterfaceID CFUUIDGetConstantUUIDWithBytes(NULL, \ 0x7F, 0xB7, 0xA4, 0x54, 0x22, 0x6F, 0x11, 0xD6, 0xB8, 0x89, 0x00, 0x0A, 0x27, 0x7E, 0x72, 0x34) typedef void (*IOFWAVCMessageCallback)( void * refCon, UInt32 type, void * arg ); /*! @typedef IOFWAVCRequestCallback @abstract This Callback has been deprecated. Use installAVCCommandHandler instead. */ typedef IOReturn (*IOFWAVCRequestCallback)( void *refCon, UInt32 generation, UInt16 srcNodeID, const UInt8 * command, UInt32 cmdLen, UInt8 * response, UInt32 *responseLen); /*! @typedef IOFWAVCPCRCallback @abstract Callback called after a successful lock transaction to a CMP plug. @param refcon refcon supplied when a client is registered @param generation Bus generation command was received in @param nodeID is the node originating the request @param plug is the plug number @param oldVal is the value the plug used to contain @param newVal is the quad written into the plug */ typedef void (*IOFWAVCPCRCallback)(void *refcon, UInt32 generation, UInt16 nodeID, UInt32 plug, UInt32 oldVal, UInt32 newVal); /*! @typedef IOFWAVCCommandHandlerCallback @abstract Callback called when a incoming AVC command matching a registered command handler is received. @param refCon The refcon supplied when a client is registered @param generation The FireWire bus generation value at the time the command was received @param srcNodeID The node ID of the device who sent us this command @param speed The speed the AVC command packet @param command A pointer to the command bytes @param cmdLen The length of the AVC command bytes buffer in bytes @result The callback handler should return success if it will send the AVC response, or an error if it doesn't want to handle the command */ typedef IOReturn (*IOFWAVCCommandHandlerCallback)( void *refCon, UInt32 generation, UInt16 srcNodeID, IOFWSpeed speed, const UInt8 * command, UInt32 cmdLen); /*! @typedef IOFWAVCSubunitPlugHandlerCallback @abstract Callback called when a incoming AVC command matching a registered command handler is received. @param refCon The refcon supplied when a client is registered @param subunitTypeAndID The subunit type and id of this plug @param plugType The type of plug receiving the message @param plugNum The number of the plug receiving the message @param plugMessage The plug message @param messageParams The parameters associated with the plug message @result The return value is only pertinent for the kIOFWAVCSubunitPlugMsgSignalFormatModified message. Return an error if not accepting the sig format change. */ typedef IOReturn (*IOFWAVCSubunitPlugHandlerCallback)(void *refCon, UInt32 subunitTypeAndID, IOFWAVCPlugTypes plugType, UInt32 plugNum, IOFWAVCSubunitPlugMessages plugMessage, UInt32 messageParams); typedef struct _IOFireWireAVCLibProtocolInterface IOFireWireAVCLibProtocolInterface; typedef struct _IOFireWireAVCLibAsynchronousCommand { IOFWAVCAsyncCommandState cmdState; void *pRefCon; UInt8 *pCommandBuf; UInt32 cmdLen; UInt8 *pInterimResponseBuf; UInt32 interimResponseLen; UInt8 *pFinalResponseBuf; UInt32 finalResponseLen; }IOFireWireAVCLibAsynchronousCommand; typedef void (*IOFireWireAVCLibAsynchronousCommandCallback)(void *pRefCon, IOFireWireAVCLibAsynchronousCommand *pCommandObject); /*! @class IOFireWireAVCLibUnitInterface @abstract Initial interface discovered for all AVC Unit drivers. @discussion The IOFireWireAVCLibUnitInterface is the initial interface discovered by most drivers. It supplies the methods that control the operation of the AVC unit as a whole. Finally, the Unit can supply a reference to the IOFireWireUnit. This can be useful if a driver wishes to access the standard FireWire APIs. */ typedef struct { IUNKNOWN_C_GUTS; UInt16 version; UInt16 revision; /*! @function open @abstract Exclusively opens a connection to the in-kernel device. @discussion Exclusively opens a connection to the in-kernel device. As long as the in-kernel device object is open, no other drivers will be able to open a connection to the device. When open, the device on the bus may disappear, but the in-kernel object representing it will stay instantiated and can begin communicating with the device again if it ever reappears. @param self Pointer to IOFireWireAVCLibUnitInterface. @result Returns kIOReturnSuccess on success. */ IOReturn (*open)( void * self ); /*! @function openWithSessionRef @abstract Opens a connection to a device that is not already open. @discussion Sometimes it is desirable to open multiple user clients on a device. In the case of FireWire sometimes we wish to have both the FireWire User Client and the AVC User Client open at the same time. The technique to arbitrate this is as follows:<br>First open normally the device furthest from the root in the I/O Registry.<br>Second, get its sessionRef with the getSessionRef call.<br>Third, open the device further up the chain by calling this method and passing the sessionRef returned from the call in step 2. @param sessionRef SessionRef returned from getSessionRef call. @param self Pointer to IOFireWireAVCLibUnitInterface. @result Returns kIOReturnSuccess on success. */ IOReturn (*openWithSessionRef)( void * self, IOFireWireSessionRef sessionRef ); /*! @function getSessionRef @abstract Get the session reference. @discussion Gets the sessionRef to be used with openWithSessionRef. @param self Pointer to IOFireWireAVCLibUnitInterface. @result Returns a sessionRef on success. */ IOFireWireSessionRef (*getSessionRef)(void * self); /*! @function close @abstract Closes an exclusive access to the device. @discussion Closes an exclusive access to the device. When a device is closed it may be unloaded by the kernel. If it is unloaded and then later reappears it will be represented by a different object. You won't be able to use this user client on the new object. The new object will have to be looked up in the I/O Registry and a new user client will have to be opened on it. @param self Pointer to IOFireWireAVCLibUnitInterface. */ void (*close)( void * self ); /*! @function addCallbackDispatcherToRunLoop @abstract Adds a dispatcher for kernel callbacks to the specified runloop. @discussion The user space portions of the AVC API communicate with the in-kernel services by messaging the kernel. Similarly, the kernel messages the user space services in response. These responses need to be picked up by a piece of code. This call adds that code to the specified run loop. Most drivers will call this method on the run loop that was created when your task was created. To avoid deadlock you must avoid sleeping (or spin waiting) the run loop to wait for AVC response. If you do this the dispatcher will never get to run and you will wait forever. @param self Pointer to IOFireWireAVCLibUnitInterface. @param cfRunLoopRef Reference to a run loop. @result Returns kIOReturnSuccess on success. */ IOReturn (*addCallbackDispatcherToRunLoop)( void *self, CFRunLoopRef cfRunLoopRef ); /*! @function removeCallbackDispatcherFromRunLoop @abstract Removes a dispatcher for kernel callbacks to the specified run loop. @discussion Undoes the work of addCallbackDispatcherToRunLoop. @param self Pointer to IOFireWireAVCLibUnitInterface. */ void (*removeCallbackDispatcherFromRunLoop)( void * self ); /*! @function setMessageCallback @abstract Sets callback for user space message routine. @discussion In FireWire and AVC, bus status messages are delivered via IOKit's message routine. This routine is emulated in user space for AVC and FireWire messages via this callback. You should register here for bus reset and reconnect messages. @param self Pointer to IOFireWireAVCLibUnitInterface. @param refCon RefCon to be returned as first argument of completion routine. @param callback Address of completion routine. */ void (*setMessageCallback)( void *self, void * refCon, IOFWAVCMessageCallback callback); /*! @function AVCCommand @abstract Sends an AVC command to the device and returns the response. @discussion This function will block until the device returns a response or the kernel driver times out. @param self Pointer to IOFireWireAVCLibUnitInterface. @param command Pointer to command to send. @param cmdLen Length (in bytes) of command. @param response Pointer to place to store the response sent by the device. @param responseLen Pointer to place to store the length of the response. */ IOReturn (*AVCCommand)( void * self, const UInt8 * command, UInt32 cmdLen, UInt8 * response, UInt32 *responseLen); /*! @function AVCCommandInGeneration @abstract Sends an AVC command to the device and returns the response. @discussion Sends an AVC command to the device and returns the response. The command must complete in the specified bus generation. This function is only available if the interface version is > 1 (MacOSX 10.2.0 or later?). This function will block until the device returns a response or the kernel driver times out. @param self Pointer to IOFireWireAVCLibUnitInterface. @param busGeneration FireWire bus generation that the command is valid in. @param command Pointer to command to send. @param cmdLen Length (in bytes) of command. @param response Pointer to place to store the response sent by the device. @param responseLen Pointer to place to store the length of the response. */ IOReturn (*AVCCommandInGeneration)( void * self, UInt32 busGeneration, const UInt8 * command, UInt32 cmdLen, UInt8 * response, UInt32 *responseLen); /*! @function getAncestorInterface @abstract Creates a plug-in object for an ancestor (in the I/O Registry) of the AVC unit and returns an interface to it. @discussion This function is only available if the interface version is > 1 (MacOSX 10.2.0 or later?). @param self Pointer to IOFireWireAVCLibUnitInterface. @param object_class Class name of ancestor of the device to get an interface for. @param pluginType An ID number, of type CFUUIDBytes (see CFUUID.h), identifying the type of plug-in service to be returned for the ancestor. @param iid An ID number, of type CFUUIDBytes (see CFUUID.h), identifying the type of interface to be returned for the created plug-in object. @result Returns a COM-style interface pointer. Returns 0 upon failure. */ void * (*getAncestorInterface)( void * self, char * object_class, REFIID pluginType, REFIID iid) ; /*! @function getProtocolInterface @abstract Creates a plug-in object for a protocol driver for the FireWire bus the AVC unit is connected to and returns an interface to it. @discussion This function is only available if the interface version is > 1 (MacOSX 10.2.0 or later?). @param self Pointer to IOFireWireAVCLibUnitInterface. @param pluginType An ID number, of type CFUUIDBytes (see CFUUID.h), identifying the type of plug-in service to be returned for the created protocol object. @param iid An ID number, of type CFUUIDBytes (see CFUUID.h), identifying the type of interface to be returned for the created protocol device object. @result Returns a COM-style interface pointer. Returns 0 upon failure. */ void * (*getProtocolInterface)( void * self, REFIID pluginType, REFIID iid) ; /* */ IOReturn (*getAsyncConnectionPlugCounts) ( void *self, UInt8 * inputPlugCount, UInt8 * outputPlugCount ); /* */ IUnknownVTbl ** (*createConsumerPlug)( void *self, UInt8 plugNumber, REFIID iid ); /*! @function updateAVCCommandTimeout @abstract Updates an AVCCommand's timeout back to 10 seconds. @discussion AVCCommands will time out after 10 seconds unless this function is called (from another thread) to update the command's timeout back to 10 seconds. This function is only available if the interface version is > 2. */ IOReturn (*updateAVCCommandTimeout)(void * self); /*! @function makeP2PInputConnection @abstract Increments the point-to-point connection count of a unit input plug. @discussion This function is only available if the interface version is > 3. */ IOReturn (*makeP2PInputConnection)(void * self, UInt32 inputPlug, UInt32 chan); /*! @function breakP2PInputConnection @abstract Decrements the point-to-point connection count of a unit input plug. @discussion This function is only available if the interface version is > 3. */ IOReturn (*breakP2PInputConnection)(void * self, UInt32 inputPlug); /*! @function makeP2POutputConnection @abstract Increments the point-to-point connection count of a unit output plug. @discussion This function is only available if the interface version is > 3. */ IOReturn (*makeP2POutputConnection)(void * self, UInt32 outputPlug, UInt32 chan, IOFWSpeed speed); /*! @function breakP2POutputConnection @abstract Decrements the point-to-point connection count of a unit output plug. @discussion This function is only available if the interface version is > 3. */ IOReturn (*breakP2POutputConnection)(void * self, UInt32 outputPlug); /*! @function createAVCAsynchronousCommand */ IOReturn (*createAVCAsynchronousCommand)(void * self, const UInt8 * command, UInt32 cmdLen, IOFireWireAVCLibAsynchronousCommandCallback completionCallback, void *pRefCon, IOFireWireAVCLibAsynchronousCommand **ppCommandObject); /*! @function AVCAsynchronousCommandSubmit */ IOReturn (*AVCAsynchronousCommandSubmit)(void * self, IOFireWireAVCLibAsynchronousCommand *pCommandObject); /*! @function AVCAsynchronousCommandReinit */ IOReturn (*AVCAsynchronousCommandReinit)(void * self, IOFireWireAVCLibAsynchronousCommand *pCommandObject); /*! @function AVCAsynchronousCommandCancel */ IOReturn (*AVCAsynchronousCommandCancel)(void * self, IOFireWireAVCLibAsynchronousCommand *pCommandObject); /*! @function AVCAsynchronousCommandRelease */ IOReturn (*AVCAsynchronousCommandRelease)(void * self, IOFireWireAVCLibAsynchronousCommand *pCommandObject); /*! @function AVCAsynchronousCommandReinitWithCommandBytes */ IOReturn (*AVCAsynchronousCommandReinitWithCommandBytes)(void * self, IOFireWireAVCLibAsynchronousCommand *pCommandObject, const UInt8 * command, UInt32 cmdLen); } IOFireWireAVCLibUnitInterface; /*! @class IOFireWireAVCLibProtocolInterface @abstract Initial interface discovered for all AVC protocol drivers. @discussion The IOFireWireAVCLibProtocolInterface is used to set up local plug control registers and to receive AVC requests. */ typedef struct _IOFireWireAVCLibProtocolInterface { IUNKNOWN_C_GUTS; UInt16 version; UInt16 revision; /*! @function addCallbackDispatcherToRunLoop @abstract Adds a dispatcher for kernel callbacks to the specified run loop. @discussion The user space portions of the AVC API communicate with the in-kernel services by messaging the kernel. Similarly, the kernel messages the user space services in response. These responses need to be picked up by a piece of code. This call adds that code to the specified run loop. Most drivers will call this method on the run loop that was created when your task was created. To avoid deadlock you must avoid sleeping (or spin waiting) the run loop to wait for AVC response. If you do this the dispatcher will never get to run and you will wait forever. @param self Pointer to IOFireWireAVCLibProtocolInterface. @param cfRunLoopRef Reference to a run loop. @result Returns kIOReturnSuccess on success. */ IOReturn (*addCallbackDispatcherToRunLoop)( void *self, CFRunLoopRef cfRunLoopRef ); /*! @function removeCallbackDispatcherFromRunLoop @abstract Removes a dispatcher for kernel callbacks to the specified run loop. @discussion Undoes the work of addCallbackDispatcherToRunLoop. @param self Pointer to IOFireWireAVCLibProtocolInterface. */ void (*removeCallbackDispatcherFromRunLoop)( void * self ); /*! @function setMessageCallback @abstract Sets callback for user space message routine. @discussion In FireWire and AVC, bus status messages are delivered via IOKit's message routine. This routine is emulated in user space for AVC and FireWire messages via this callback. You should register here for bus reset and reconnect messages. @param self Pointer to IOFireWireAVCLibProtocolInterface. @param refCon RefCon to be returned as first argument of completion routine. @param callback Address of completion routine. */ void (*setMessageCallback)( void *self, void * refCon, IOFWAVCMessageCallback callback); /*! @function setAVCRequestCallback @abstract This function has been deprecated. Use installAVCCommandHandler instead. */ IOReturn (*setAVCRequestCallback)( void *self, UInt32 subUnitType, UInt32 subUnitID, void *refCon, IOFWAVCRequestCallback callback); /*! @function allocateInputPlug @abstract Allocates an input plug. @param self Pointer to IOFireWireAVCLibProtocolInterface. @param refcon Arbitrary value passed back as first argument of callback. @param func Callback function when a successful lock transaction to the plug has been performed. @param plug Set to the plug number if a plug is successfully allocated. */ IOReturn (*allocateInputPlug)( void *self, void *refcon, IOFWAVCPCRCallback func, UInt32 *plug); /*! @function freeInputPlug @abstract Deallocates an input plug. @param self Pointer to IOFireWireAVCLibProtocolInterface. @param plug Value returned by allocateInputPlug. */ void (*freeInputPlug)( void *self, UInt32 plug); /*! @function readInputPlug @abstract Returns the current value of an input plug. @param self Pointer to IOFireWireAVCLibProtocolInterface. @param plug Value returned by allocateInputPlug. */ UInt32 (*readInputPlug)( void *self, UInt32 plug); /*! @function updateInputPlug @abstract Updates the value of an input plug (simulating a lock transaction). @param self Pointer to IOFireWireAVCLibProtocolInterface. @param plug Value returned by allocateInputPlug. @param oldVal Value returned by readInputPlug. @param newVal New value to store in plug if its current value is oldVal. */ IOReturn (*updateInputPlug)( void *self, UInt32 plug, UInt32 oldVal, UInt32 newVal); /*! @function allocateOutputPlug @abstract Allocates an output plug. @param self Pointer to IOFireWireAVCLibProtocolInterface. @param refcon Arbitrary value passed back as first argument of callback. @param func Callback function when a successful lock transaction to the plug has been performed. @param plug Set to the plug number if a plug is successfully allocated. */ IOReturn (*allocateOutputPlug)( void *self, void *refcon, IOFWAVCPCRCallback func, UInt32 *plug); /*! @function freeOutputPlug @abstract Deallocates an output plug. @param self Pointer to IOFireWireAVCLibProtocolInterface. @param plug Value returned by allocateOutputPlug. */ void (*freeOutputPlug)( void *self, UInt32 plug); /*! @function readOutputPlug @abstract Returns the current value of an output plug. @param self Pointer to IOFireWireAVCLibProtocolInterface. @param plug Value returned by allocateOutputPlug. */ UInt32 (*readOutputPlug)( void *self, UInt32 plug); /*! @function updateOutputPlug @abstract Updates the value of an output plug (simulating a lock transaction). @param self Pointer to IOFireWireAVCLibProtocolInterface. @param plug Value returned by allocateOutputPlug. @param oldVal Value returned by readOutputPlug. @param newVal New value to store in plug if its current value is oldVal. */ IOReturn (*updateOutputPlug)( void *self, UInt32 plug, UInt32 oldVal, UInt32 newVal); /*! @function readOutputMasterPlug @abstract Returns the current value of the output master plug. @param self Pointer to IOFireWireAVCLibProtocolInterface. */ UInt32 (*readOutputMasterPlug)( void *self); /*! @function updateOutputMasterPlug @abstract Updates the value of the master output plug (simulating a lock transaction). @param self Pointer to IOFireWireAVCLibProtocolInterface. @param oldVal Value returned by readOutputMasterPlug. @param newVal New value to store in plug if its current value is oldVal. */ IOReturn (*updateOutputMasterPlug)( void *self, UInt32 oldVal, UInt32 newVal); /*! @function readInputMasterPlug @abstract Returns the current value of the input master plug. @param self Pointer to IOFireWireAVCLibProtocolInterface. */ UInt32 (*readInputMasterPlug)( void *self); /*! @function updateInputMasterPlug @abstract Updates the value of the master input plug (simulating a lock transaction). @param self Pointer to IOFireWireAVCLibProtocolInterface. @param oldVal Value returned by readInputMasterPlug. @param newVal New value to store in plug if its current value is oldVal. */ IOReturn (*updateInputMasterPlug)( void *self, UInt32 oldVal, UInt32 newVal); /*! @function publishAVCUnitDirectory @abstract Publishes an AVC unit directory in the config ROM. @param self Pointer to IOFireWireAVCLibProtocolInterface. */ IOReturn (*publishAVCUnitDirectory)(void *self); /*! @function installAVCCommandHandler @abstract Installs a command handler for handling specific incoming AVC commands. @param self Pointer to IOFireWireAVCLibProtocolInterface. @param subUnitTypeAndID The subunit type and ID for this command handler. @param opCode The opcode for this command handler. @param refCon Arbitrary value passed back as first argument of callback. @param callback A pointer to the callback function */ IOReturn (*installAVCCommandHandler)(void *self, UInt32 subUnitTypeAndID, UInt32 opCode, void *refCon, IOFWAVCCommandHandlerCallback callback); /*! @function sendAVCResponse @abstract Sends an AVC response packet. @param self Pointer to IOFireWireAVCLibProtocolInterface. @param generation The Firewire bus generation that this response should be sent in. @param nodeID The node ID of the device we are sending this response to. @param response A pointer to the response bytes. @param responseLen The number of response bytes. */ IOReturn (*sendAVCResponse)(void *self, UInt32 generation, UInt16 nodeID, const char *response, UInt32 responseLen); /*! @function addSubunit @abstract Installs a virtual AVC subunit. @param self Pointer to IOFireWireAVCLibProtocolInterface. @param subunitType The type of subunit to create. @param numSourcePlugs The number of source plugs for this subunit. @param numDestPlugs The number of destination plugs for this subunit. @param refCon Arbitrary value passed back as first argument of callback. @param callback A pointer to the callback to receive plug management messages. @param pSubunitTypeAndID A pointer to a byte to hold the returned subunit address for the new subunit. */ IOReturn (*addSubunit)(void *self, UInt32 subunitType, UInt32 numSourcePlugs, UInt32 numDestPlugs, void *refCon, IOFWAVCSubunitPlugHandlerCallback callback, UInt32 *pSubunitTypeAndID); /*! @function setSubunitPlugSignalFormat @abstract Sets the signal format of the specifed plug. @param self Pointer to IOFireWireAVCLibProtocolInterface. @param subunitTypeAndID The subunit type and ID of the plug. @param plugType The plug type. @param plugNum The plug number. @param signalFormat The 32-bit signal format value. */ IOReturn (*setSubunitPlugSignalFormat)(void *self, UInt32 subunitTypeAndID, IOFWAVCPlugTypes plugType, UInt32 plugNum, UInt32 signalFormat); /*! @function getSubunitPlugSignalFormat @abstract Gets the signal format of the specifed plug. @param self Pointer to IOFireWireAVCLibProtocolInterface. @param subunitTypeAndID The subunit type and ID of the plug. @param plugType The plug type. @param plugNum The plug number. @param pSignalFormat A pointer to the location to return the signal format value. */ IOReturn (*getSubunitPlugSignalFormat)(void *self, UInt32 subunitTypeAndID, IOFWAVCPlugTypes plugType, UInt32 plugNum, UInt32 *pSignalFormat); /*! @function connectTargetPlugs @abstract Establishes an internal AVC plug connection between subunit/unit plugs. @param self Pointer to IOFireWireAVCLibProtocolInterface. @param sourceSubunitTypeAndID The subunit type and ID for the source plug @param sourcePlugType The source plug type. @param pSourcePlugNum A pointer to the source plug num. Will return the actual source plug num here. @param destSubunitTypeAndID The subunit type and ID for the destination plug. @param destPlugType The dest plug type. @param pDestPlugNum A pointer to the dest plug num. Will return the actual dest plug num here. @param lockConnection A flag to specify if this connection should be locked. @param permConnection A flag to specify if this connection is permanent. */ IOReturn (*connectTargetPlugs)(void *self, UInt32 sourceSubunitTypeAndID, IOFWAVCPlugTypes sourcePlugType, UInt32 *pSourcePlugNum, UInt32 destSubunitTypeAndID, IOFWAVCPlugTypes destPlugType, UInt32 *pDestPlugNum, bool lockConnection, bool permConnection); /*! @function disconnectTargetPlugs @abstract Breaks an internal AVC plug connection between subunit/unit plugs. @param self Pointer to IOFireWireAVCLibProtocolInterface. @param sourceSubunitTypeAndID The subunit type and ID for the source plug. @param sourcePlugType The source plug type. @param sourcePlugNum The source plug num. @param destSubunitTypeAndID The subunit type and ID for the destination plug. @param destPlugType The dest plug type. @param destPlugNum The dest plug num. */ IOReturn (*disconnectTargetPlugs)(void *self, UInt32 sourceSubunitTypeAndID, IOFWAVCPlugTypes sourcePlugType, UInt32 sourcePlugNum, UInt32 destSubunitTypeAndID, IOFWAVCPlugTypes destPlugType, UInt32 destPlugNum); /*! @function getTargetPlugConnection @abstract Gets the connection details for a specific plug. @param self Pointer to IOFireWireAVCLibProtocolInterface. @param subunitTypeAndID The subunit type and ID of the plug. @param plugType The plug type. @param plugNum The plug number. @param pConnectedSubunitTypeAndID The subunit type and ID of the connected plug. @param pConnectedPlugType The type of the connected plug. @param pConnectedPlugNum The number of the connected plug. @param pLockConnection A pointer for returning the lock status of the connection. @param pPermConnection A pointer for returning the perm status of the connection. */ IOReturn (*getTargetPlugConnection)(void *self, UInt32 subunitTypeAndID, IOFWAVCPlugTypes plugType, UInt32 plugNum, UInt32 *pConnectedSubunitTypeAndID, IOFWAVCPlugTypes *pConnectedPlugType, UInt32 *pConnectedPlugNum, bool *pLockConnection, bool *pPermConnection); } IOFireWireAVCLibProtocolInterface; typedef void (*IOFireWireAVCPortStateHandler)( void * refcon, UInt32 state ); typedef void (*IOFireWireAVCFrameStatusHandler)( void * refcon, UInt32 mode, UInt32 count ); /*! @class IOFireWireAVCLibConsumerInterface @abstract Interface for an asynchronous connection consumer. @discussion Used to receive data from an asynchronous connection producer. */ typedef struct { IUNKNOWN_C_GUTS; UInt16 version; UInt16 revision; void (*setSubunit)( void * self, UInt8 subunit ); void (*setRemotePlug)( void * self, UInt8 plugNumber ); IOReturn (*connectToRemotePlug)( void * self ); IOReturn (*disconnectFromRemotePlug)( void * self ); void (*setFrameStatusHandler)( void * self, void * refcon, IOFireWireAVCFrameStatusHandler handler ); void (*frameProcessed)( void * self, UInt32 mode ); void (*setMaxPayloadSize)( void * self, UInt32 size ); IOReturn (*setSegmentSize)( void * self, UInt32 size ); UInt32 (*getSegmentSize)( void * self ); char * (*getSegmentBuffer)( void * self ); void (*setPortStateHandler)( void * self, void * refcon, IOFireWireAVCPortStateHandler handler ); void (*setPortFlags)( void * self, UInt32 flags ); void (*clearPortFlags)( void * self, UInt32 flags ); UInt32 (*getPortFlags)( void * self ); } IOFireWireAVCLibConsumerInterface; #endif
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/avc/IOFireWireAVCConsts.h
/* * Copyright (c) 1998-2001 Apple Computer, Inc. All rights reserved. * * @APPLE_LICENSE_HEADER_START@ * * The contents of this file constitute Original Code as defined in and * are subject to the Apple Public Source License Version 1.1 (the * "License"). You may not use this file except in compliance with the * License. Please obtain a copy of the License at * http://www.apple.com/publicsource and read it before using this file. * * This Original Code and all software distributed under the License are * distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT. Please see the * License for the specific language governing rights and limitations * under the License. * * @APPLE_LICENSE_HEADER_END@ */ #ifndef _IOKIT_IOFIREWIREAVCCONSTS_H #define _IOKIT_IOFIREWIREAVCCONSTS_H // Fields of AVC frame typedef enum { kAVCCommandResponse = 0, kAVCAddress = 1, kAVCOpcode = 2, kAVCOperand0 = 3, kAVCOperand1 = 4, kAVCOperand2 = 5, kAVCOperand3 = 6, kAVCOperand4 = 7, kAVCOperand5 = 8, kAVCOperand6 = 9, kAVCOperand7 = 10, kAVCOperand8 = 11 } IOAVCFrameFields; // Command/Response values typedef enum { kAVCControlCommand = 0x00, kAVCStatusInquiryCommand = 0x01, kAVCSpecificInquiryCommand = 0x02, kAVCNotifyCommand = 0x03, kAVCGeneralInquiryCommand = 0x04, kAVCNotImplementedStatus = 0x08, kAVCAcceptedStatus = 0x09, kAVCRejectedStatus = 0x0a, kAVCInTransitionStatus = 0x0b, kAVCImplementedStatus = 0x0c, kAVCChangedStatus = 0x0d, kAVCInterimStatus = 0x0f } IOAVCCommandResponse; // Opcodes typedef enum { // Unit commands kAVCPlugInfoOpcode = 0x02, kAVCOutputPlugSignalFormatOpcode = 0x18, kAVCInputPlugSignalFormatOpcode = 0x19, kAVCUnitInfoOpcode = 0x30, kAVCSubunitInfoOpcode = 0x31, kAVCConnectionsOpcode = 0x22, kAVCConnectOpcode = 0x24, kAVCDisconnectOpcode = 0x25, kAVCPowerOpcode = 0xB2, kAVCSignalSourceOpcode = 0x1A, // Vendor dependent commands kAVCVendorDependentOpcode = 0x00, // Subunit commands kAVCOutputSignalModeOpcode = 0x78, kAVCInputSignalModeOpcode = 0x79, kAVCSignalModeSD525_60 = 0x00, kAVCSignalModeSDL525_60 = 0x04, kAVCSignalModeHD1125_60 = 0x08, kAVCSignalModeSD625_50 = 0x80, kAVCSignalModeSDL625_50 = 0x84, kAVCSignalModeHD1250_50 = 0x88, kAVCSignalModeDVCPro525_60 = 0x78, kAVCSignalModeDVCPro625_50 = 0xf8, kAVCSignalModeDummyOperand = 0xff, kAVCSignalModeMask_50 = 0x80, kAVCSignalModeMask_STYPE = 0x7c, kAVCSignalModeMask_SDL = 0x04, kAVCSignalModeMask_DVCPro25 = 0x78 } IOAVCOpcodes; // Unit/Subunit types typedef enum { kAVCVideoMonitor = 0x00, kAVCAudio = 0x01, kAVCPrinter = 0x02, kAVCDiskRecorder = 0x03, kAVCTapeRecorder = 0x04, kAVCTuner = 0x05, kAVCVideoCamera = 0x07, kAVCCameraStorage = 0x0b, kAVCVendorUnique = 0x1c, kAVCNumSubUnitTypes = 0x20 } IOAVCUnitTypes; #define kAVCAllOpcodes 0xFF #define kAVCAllSubunitsAndUnit 0xEE #define kAVCMaxNumPlugs 31 #define kAVCAnyAvailableIsochPlug 0x7F #define kAVCAnyAvailableExternalPlug 0xFF #define kAVCAnyAvailableSubunitPlug 0xFF #define kAVCMultiplePlugs 0xFD #define kAVCInvalidPlug 0xFE #define IOAVCAddress(type, id) (((type) << 3) | (id)) #define kAVCUnitAddress 0xff #define IOAVCType(address) ((address) >> 3) #define IOAVCId(address) ((address) & 0x7) // Macros for Plug Control Register field manipulation // Master control registers #define kIOFWPCRDataRate FWBitRange(0,1) #define kIOFWPCRDataRatePhase FWBitRangePhase(0,1) #define kIOFWPCRExtension FWBitRange(8,15) #define kIOFWPCRExtensionPhase FWBitRangePhase(8,15) #define kIOFWPCRNumPlugs FWBitRange(27,31) #define kIOFWPCRNumPlugsPhase FWBitRangePhase(27,31) // master output register #define kIOFWPCRBroadcastBase FWBitRange(2,7) #define kIOFWPCRBroadcastBasePhase FWBitRangePhase(2,7) // plug registers #define kIOFWPCROnline FWBitRange(0,0) #define kIOFWPCROnlinePhase FWBitRangePhase(0,0) #define kIOFWPCRBroadcast FWBitRange(1,1) #define kIOFWPCRBroadcastPhase FWBitRangePhase(1,1) #define kIOFWPCRP2PCount FWBitRange(2,7) #define kIOFWPCRP2PCountPhase FWBitRangePhase(2,7) #define kIOFWPCRChannel FWBitRange(10,15) #define kIOFWPCRChannelPhase FWBitRangePhase(10,15) // Extra fields for output plug registers #define kIOFWPCROutputDataRate FWBitRange(16,17) #define kIOFWPCROutputDataRatePhase FWBitRangePhase(16,17) #define kIOFWPCROutputOverhead FWBitRange(18,21) #define kIOFWPCROutputOverheadPhase FWBitRangePhase(18,21) #define kIOFWPCROutputPayload FWBitRange(22,31) #define kIOFWPCROutputPayloadPhase FWBitRangePhase(22,31) // async plug numbers enum { kFWAVCAsyncPlug0 = 0xa0, kFWAVCAsyncPlug1 = 0xa1, kFWAVCAsyncPlug2 = 0xa2, kFWAVCAsyncPlug3 = 0xa3, kFWAVCAsyncPlug4 = 0xa4, kFWAVCAsyncPlug5 = 0xa5, kFWAVCAsyncPlug6 = 0xa6, kFWAVCAsyncPlug7 = 0xa7, kFWAVCAsyncPlug8 = 0xa8, kFWAVCAsyncPlug9 = 0xa9, kFWAVCAsyncPlug10 = 0xa1, kFWAVCAsyncPlug11 = 0xab, kFWAVCAsyncPlug12 = 0xac, kFWAVCAsyncPlug13 = 0xad, kFWAVCAsyncPlug14 = 0xae, kFWAVCAsyncPlug15 = 0xaf, kFWAVCAsyncPlug16 = 0xb0, kFWAVCAsyncPlug17 = 0xb1, kFWAVCAsyncPlug18 = 0xb2, kFWAVCAsyncPlug19 = 0xb3, kFWAVCAsyncPlug20 = 0xb4, kFWAVCAsyncPlug21 = 0xb5, kFWAVCAsyncPlug22 = 0xb6, kFWAVCAsyncPlug23 = 0xb7, kFWAVCAsyncPlug24 = 0xb8, kFWAVCAsyncPlug25 = 0xb9, kFWAVCAsyncPlug26 = 0xba, kFWAVCAsyncPlug27 = 0xbb, kFWAVCAsyncPlug28 = 0xbc, kFWAVCAsyncPlug29 = 0xbd, kFWAVCAsyncPlug30 = 0xbe, kFWAVCAsyncPlugAny = 0xbf }; enum { kFWAVCStateBusSuspended = 0, kFWAVCStateBusResumed = 1, kFWAVCStatePlugReconnected = 2, kFWAVCStatePlugDisconnected = 3, kFWAVCStateDeviceRemoved = 4 }; enum { kFWAVCConsumerMode_MORE = 1, kFWAVCConsumerMode_LAST = 4, kFWAVCConsumerMode_LESS = 5, kFWAVCConsumerMode_JUNK = 6, kFWAVCConsumerMode_LOST = 7 }; enum { kFWAVCProducerMode_SEND = 5, kFWAVCProducerMode_TOSS = 7 }; typedef enum { IOFWAVCPlugSubunitSourceType, IOFWAVCPlugSubunitDestType, IOFWAVCPlugIsochInputType, IOFWAVCPlugIsochOutputType, IOFWAVCPlugAsynchInputType, IOFWAVCPlugAsynchOutputType, IOFWAVCPlugExternalInputType, IOFWAVCPlugExternalOutputType } IOFWAVCPlugTypes; typedef enum { kIOFWAVCSubunitPlugMsgConnected, kIOFWAVCSubunitPlugMsgDisconnected, kIOFWAVCSubunitPlugMsgConnectedPlugModified, kIOFWAVCSubunitPlugMsgSignalFormatModified } IOFWAVCSubunitPlugMessages; // Some plug signal formats #define kAVCPlugSignalFormatNTSCDV 0x80000000 #define kAVCPlugSignalFormatPalDV 0x80800000 #define kAVCPlugSignalFormatMPEGTS 0xA0000000 // Possible states of an AVCAsynchronousCommand typedef enum { kAVCAsyncCommandStatePendingRequest, kAVCAsyncCommandStateRequestSent, kAVCAsyncCommandStateRequestFailed, kAVCAsyncCommandStateWaitingForResponse, kAVCAsyncCommandStateReceivedInterimResponse, kAVCAsyncCommandStateReceivedFinalResponse, kAVCAsyncCommandStateTimeOutBeforeResponse, kAVCAsyncCommandStateBusReset, kAVCAsyncCommandStateOutOfMemory, kAVCAsyncCommandStateCanceled } IOFWAVCAsyncCommandState; #endif // _IOKIT_IOFIREWIREAVCCONSTS_H
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/ndrvsupport/IOMacOSTypes.h
/* * Copyright (c) 1998-2000 Apple Computer, Inc. All rights reserved. * * @APPLE_LICENSE_HEADER_START@ * * The contents of this file constitute Original Code as defined in and * are subject to the Apple Public Source License Version 1.1 (the * "License"). You may not use this file except in compliance with the * License. Please obtain a copy of the License at * http://www.apple.com/publicsource and read it before using this file. * * This Original Code and all software distributed under the License are * distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT. Please see the * License for the specific language governing rights and limitations * under the License. * * @APPLE_LICENSE_HEADER_END@ */ /* * Copyright (c) 1997 Apple Computer, Inc. * * * HISTORY * * sdouglas 22 Oct 97 - first checked in. * sdouglas 21 July 98 - start IOKit */ /* File: Types.h Contains: Basic Macintosh data types. Version: Technology: PowerSurge 1.0.2. Package: Universal Interfaces 2.1.2 on ETO #20 Copyright: � 1984-1995 by Apple Computer, Inc. All rights reserved. Bugs?: If you find a problem with this file, use the Apple Bug Reporter stack. Include the file and version information (from above) in the problem description and send to: Internet: [email protected] AppleLink: APPLE.BUGS */ #ifndef _IOKIT_IOMACOSTYPES_H #define _IOKIT_IOMACOSTYPES_H #ifndef __MACTYPES__ #include <IOKit/IOTypes.h> #ifdef __cplusplus extern "C" { #endif #ifndef __LP64__ #pragma options align=mac68k #endif #ifndef NULL #if !defined(__cplusplus) && (defined(__SC__) || defined(THINK_C)) #define NULL ((void *) 0) #else #define NULL 0 #endif #endif enum { noErr = 0 }; typedef unsigned char Byte; typedef signed char SignedByte; typedef UInt16 UniChar; typedef char *Ptr; typedef Ptr *Handle; typedef UInt32 Fixed; typedef Fixed *FixedPtr; typedef UInt32 Fract; typedef Fract *FractPtr; /* enum { false, true }; #if !__option(bool) #ifndef true #define true 1 #endif #ifndef false #define false 0 #endif #endif typedef unsigned char Boolean; */ typedef short OSErr; typedef unsigned int FourCharCode; typedef FourCharCode OSType; typedef FourCharCode ResType; typedef OSType *OSTypePtr; typedef ResType *ResTypePtr; struct Rect { short top; short left; short bottom; short right; }; typedef struct Rect Rect; typedef Rect *RectPtr; // Quickdraw.i /* kVariableLengthArray is used in array bounds to specify a variable length array. It is ususally used in variable length structs when the last field is an array of any size. Before ANSI C, we used zero as the bounds of variable length array, but that is illegal in ANSI C. Example: struct FooList { short listLength; Foo elements[kVariableLengthArray]; }; */ enum { kVariableLengthArray = 1 }; /* Numeric version part of 'vers' resource */ struct NumVersion { UInt8 majorRev; /*1st part of version number in BCD*/ UInt8 minorAndBugRev; /*2nd & 3rd part of version number share a byte*/ UInt8 stage; /*stage code: dev, alpha, beta, final*/ UInt8 nonRelRev; /*revision level of non-released version*/ }; typedef struct NumVersion NumVersion; typedef struct OpaqueRef *KernelID; typedef UInt8 *BytePtr; typedef IOByteCount ByteCount; typedef IOItemCount ItemCount; typedef void *LogicalAddress; #if !defined(__LP64__) typedef void *PhysicalAddress; #endif typedef UInt32 PBVersion; typedef SInt32 Duration; #define kInvalidID 0 enum { kNilOptions = 0 }; typedef unsigned char Str31[32]; /* From: File: DriverFamilyMatching.i <18> Copyright: � 1995-1996 by Apple Computer, Inc., all rights reserved. */ //############################################## // Well known properties in the Name Registry //############################################## #define kPropertyName "name" #define kPropertyCompatible "compatible" #define kPropertyDriverPtr "driver-ptr" #define kPropertyDriverDesc "driver-description" #define kPropertyReg "reg" #define kPropertyAAPLAddress "AAPL,address" #define kPropertyMatching "matching" //######################################################### // Descriptor for Drivers and NDRVs //######################################################### /* Driver Typing Information Used to Match Drivers With Devices */ struct DriverType { Str31 nameInfoStr; /* Driver Name/Info String*/ NumVersion version; /* Driver Version Number*/ }; typedef struct DriverType DriverType; typedef DriverType * DriverTypePtr; /* OS Runtime Information Used to Setup and Maintain a Driver's Runtime Environment */ typedef IOOptionBits RuntimeOptions; enum { kDriverIsLoadedUponDiscovery = 0x00000001, /* auto-load driver when discovered*/ kDriverIsOpenedUponLoad = 0x00000002, /* auto-open driver when loaded*/ kDriverIsUnderExpertControl = 0x00000004, /* I/O expert handles loads/opens*/ kDriverIsConcurrent = 0x00000008, /* supports concurrent requests*/ kDriverQueuesIOPB = 0x00000010, /* device manager doesn't queue IOPB*/ kDriverIsLoadedAtBoot = 0x00000020, /* Driver is loaded at the boot time */ kDriverIsForVirtualDevice = 0x00000040, /* Driver is for a virtual Device */ kDriverSupportDMSuspendAndResume = 0x00000080 /* Driver supports Device Manager Suspend and Resume command */ }; struct DriverOSRuntime { RuntimeOptions driverRuntime; /* Options for OS Runtime*/ Str31 driverName; /* Driver's name to the OS*/ UInt32 driverDescReserved[8]; /* Reserved area*/ }; typedef struct DriverOSRuntime DriverOSRuntime; typedef DriverOSRuntime * DriverOSRuntimePtr; /* OS Service Information Used To Declare What APIs a Driver Supports */ typedef UInt32 ServiceCount; struct DriverServiceInfo { OSType serviceCategory; /* Service Category Name*/ OSType serviceType; /* Type within Category*/ NumVersion serviceVersion; /* Version of service*/ }; typedef struct DriverServiceInfo DriverServiceInfo; typedef DriverServiceInfo * DriverServiceInfoPtr; struct DriverOSService { ServiceCount nServices; /* Number of Services Supported*/ DriverServiceInfo service[1]; /* The List of Services (at least one)*/ }; typedef struct DriverOSService DriverOSService; typedef DriverOSService * DriverOSServicePtr; /* Categories */ enum { kServiceCategoryDisplay = 'disp', /* Display Manager*/ kServiceCategoryOpenTransport = 'otan', /* Open Transport*/ kServiceCategoryBlockStorage = 'blok', /* Block Storage*/ kServiceCategoryNdrvDriver = 'ndrv', /* Generic Native Driver*/ kServiceCategoryScsiSIM = 'scsi', /* SCSI */ kServiceCategoryFileManager = 'file', /* File Manager */ kServiceCategoryIDE = 'ide-', /* ide */ kServiceCategoryADB = 'adb-', /* adb */ kServiceCategoryPCI = 'pci-', /* pci bus */ /* Nu Bus */ kServiceCategoryDFM = 'dfm-', /* DFM */ kServiceCategoryMotherBoard = 'mrbd', /* mother Board */ kServiceCategoryKeyboard = 'kybd', /* Keyboard */ kServiceCategoryPointing = 'poit', /* Pointing */ kServiceCategoryRTC = 'rtc-', /* RTC */ kServiceCategoryNVRAM = 'nram', /* NVRAM */ kServiceCategorySound = 'sond', /* Sound (1/3/96 MCS) */ kServiceCategoryPowerMgt = 'pgmt', /* Power Management */ kServiceCategoryGeneric = 'genr' /* Generic Service Category to receive general Events */ }; /* Ndrv ServiceCategory Types */ enum { kNdrvTypeIsGeneric = 'genr', /* generic*/ kNdrvTypeIsVideo = 'vido', /* video*/ kNdrvTypeIsBlockStorage = 'blok', /* block storage*/ kNdrvTypeIsNetworking = 'netw', /* networking*/ kNdrvTypeIsSerial = 'serl', /* serial*/ kNdrvTypeIsParallel = 'parl', /* parallel */ kNdrvTypeIsSound = 'sond', /* sound*/ kNdrvTypeIsBusBridge = 'brdg' }; typedef UInt32 DriverDescVersion; /* The Driver Description */ enum { kInitialDriverDescriptor = 0, kVersionOneDriverDescriptor = 1 }; enum { kTheDescriptionSignature = 'mtej', kDriverDescriptionSignature = 'pdes' }; struct DriverDescription { OSType driverDescSignature; /* Signature field of this structure*/ DriverDescVersion driverDescVersion; /* Version of this data structure*/ DriverType driverType; /* Type of Driver*/ DriverOSRuntime driverOSRuntimeInfo; /* OS Runtime Requirements of Driver*/ DriverOSService driverServices; /* Apple Service API Membership*/ }; typedef struct DriverDescription DriverDescription; typedef DriverDescription * DriverDescriptionPtr; #ifndef __LP64__ #pragma options align=reset #endif #ifdef __cplusplus } #endif #endif /* __MACTYPES__ */ #ifndef __QUICKDRAW__ #ifdef __cplusplus extern "C" { #endif #ifndef __LP64__ #pragma options align=mac68k #endif struct RGBColor { unsigned short red; /*magnitude of red component*/ unsigned short green; /*magnitude of green component*/ unsigned short blue; /*magnitude of blue component*/ }; typedef struct RGBColor RGBColor; typedef RGBColor *RGBColorPtr; typedef RGBColorPtr *RGBColorHdl; struct ColorSpec { short value; /*index or other value*/ RGBColor rgb; /*true color*/ }; typedef struct ColorSpec ColorSpec; typedef ColorSpec *ColorSpecPtr; struct GammaTbl { short gVersion; /*gamma version number*/ short gType; /*gamma data type*/ short gFormulaSize; /*Formula data size*/ short gChanCnt; /*number of channels of data*/ short gDataCnt; /*number of values/channel*/ short gDataWidth; /*bits/corrected value (data packed to next larger byte size)*/ short gFormulaData[1]; /*data for formulas followed by gamma values*/ }; typedef struct GammaTbl GammaTbl; typedef GammaTbl *GammaTblPtr; struct RegEntryID { void * opaque[4]; }; typedef struct RegEntryID RegEntryID; typedef RegEntryID * RegEntryIDPtr; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ struct IONDRVControlParameters { UInt8 __reservedA[0x1a]; UInt16 code; void * params; UInt8 __reservedB[0x12]; }; enum { kIONDRVOpenCommand = 128 + 0, kIONDRVCloseCommand = 128 + 1, kIONDRVReadCommand = 128 + 2, kIONDRVWriteCommand = 128 + 3, kIONDRVControlCommand = 128 + 4, kIONDRVStatusCommand = 128 + 5, kIONDRVKillIOCommand = 128 + 6, kIONDRVInitializeCommand = 128 + 7, /* init driver and device*/ kIONDRVFinalizeCommand = 128 + 8, /* shutdown driver and device*/ kIONDRVReplaceCommand = 128 + 9, /* replace an old driver*/ kIONDRVSupersededCommand = 128 + 10 /* prepare to be replaced by a new driver*/ }; enum { kIONDRVSynchronousIOCommandKind = 0x00000001, kIONDRVAsynchronousIOCommandKind = 0x00000002, kIONDRVImmediateIOCommandKind = 0x00000004 }; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #ifndef __LP64__ #pragma options align=reset #endif #ifdef __cplusplus } #endif #endif /* __QUICKDRAW__ */ #endif /* _IOKIT_IOMACOSTYPES_H */
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Headers/ndrvsupport/IOMacOSVideo.h
/* * Copyright (c) 1998-2000 Apple Computer, Inc. All rights reserved. * * @APPLE_LICENSE_HEADER_START@ * * The contents of this file constitute Original Code as defined in and * are subject to the Apple Public Source License Version 1.1 (the * "License"). You may not use this file except in compliance with the * License. Please obtain a copy of the License at * http://www.apple.com/publicsource and read it before using this file. * * This Original Code and all software distributed under the License are * distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT. Please see the * License for the specific language governing rights and limitations * under the License. * * @APPLE_LICENSE_HEADER_END@ */ /* File: Video.h Contains: Video Driver Interfaces. Copyright: (c) 1986-2000 by Apple Computer, Inc., all rights reserved Bugs?: For bug reports, consult the following page on the World Wide Web: http://developer.apple.com/bugreporter/ */ #ifndef __IOMACOSVIDEO__ #define __IOMACOSVIDEO__ #define PRAGMA_STRUCT_ALIGN 1 #define FOUR_CHAR_CODE(x) (x) #include <IOKit/ndrvsupport/IOMacOSTypes.h> #ifdef __cplusplus extern "C" { #endif #ifndef __LP64__ #pragma options align=mac68k #endif enum { mBaseOffset = 1, /*Id of mBaseOffset.*/ mRowBytes = 2, /*Video sResource parameter Id's */ mBounds = 3, /*Video sResource parameter Id's */ mVersion = 4, /*Video sResource parameter Id's */ mHRes = 5, /*Video sResource parameter Id's */ mVRes = 6, /*Video sResource parameter Id's */ mPixelType = 7, /*Video sResource parameter Id's */ mPixelSize = 8, /*Video sResource parameter Id's */ mCmpCount = 9, /*Video sResource parameter Id's */ mCmpSize = 10, /*Video sResource parameter Id's */ mPlaneBytes = 11, /*Video sResource parameter Id's */ mVertRefRate = 14, /*Video sResource parameter Id's */ mVidParams = 1, /*Video parameter block id.*/ mTable = 2, /*Offset to the table.*/ mPageCnt = 3, /*Number of pages*/ mDevType = 4, /*Device Type*/ oneBitMode = 128, /*Id of OneBitMode Parameter list.*/ twoBitMode = 129, /*Id of TwoBitMode Parameter list.*/ fourBitMode = 130, /*Id of FourBitMode Parameter list.*/ eightBitMode = 131 /*Id of EightBitMode Parameter list.*/ }; enum { sixteenBitMode = 132, /*Id of SixteenBitMode Parameter list.*/ thirtyTwoBitMode = 133, /*Id of ThirtyTwoBitMode Parameter list.*/ firstVidMode = 128, /*The new, better way to do the above. */ secondVidMode = 129, /* QuickDraw only supports six video */ thirdVidMode = 130, /* at this time. */ fourthVidMode = 131, fifthVidMode = 132, sixthVidMode = 133, spGammaDir = 64, spVidNamesDir = 65 }; typedef UInt32 AVIDType; typedef AVIDType DisplayIDType; typedef IODisplayModeID DisplayModeID; typedef UInt16 DepthMode; typedef UInt32 VideoDeviceType; typedef UInt32 GammaTableID; /* csTimingFormat values in VDTimingInfo */ /* look in the declaration rom for timing info */ enum { kDeclROMtables = FOUR_CHAR_CODE('decl'), kDetailedTimingFormat = FOUR_CHAR_CODE('arba') /* Timing is a detailed timing*/ }; /* Size of a block of EDID (Extended Display Identification Data) */ enum { kDDCBlockSize = 128 }; /* ddcBlockType constants*/ enum { kDDCBlockTypeEDID = 0 /* EDID block type. */ }; /* ddcFlags constants*/ enum { kDDCForceReadBit = 0, /* Force a new read of the EDID. */ kDDCForceReadMask = (1 << kDDCForceReadBit) /* Mask for kddcForceReadBit. */ }; /* Timing mode constants for Display Manager MultiMode support Corresponding .h equates are in Video.h .a equates are in Video.a .r equates are in DepVideoEqu.r The second enum is the old names (for compatibility). The first enum is the new names. */ enum { timingInvalid = 0, /* Unknown timing... force user to confirm. */ timingInvalid_SM_T24 = 8, /* Work around bug in SM Thunder24 card.*/ timingApple_FixedRateLCD = 42, /* Lump all fixed-rate LCDs into one category.*/ timingApple_512x384_60hz = 130, /* 512x384 (60 Hz) Rubik timing. */ timingApple_560x384_60hz = 135, /* 560x384 (60 Hz) Rubik-560 timing. */ timingApple_640x480_67hz = 140, /* 640x480 (67 Hz) HR timing. */ timingApple_640x400_67hz = 145, /* 640x400 (67 Hz) HR-400 timing. */ timingVESA_640x480_60hz = 150, /* 640x480 (60 Hz) VGA timing. */ timingVESA_640x480_72hz = 152, /* 640x480 (72 Hz) VGA timing. */ timingVESA_640x480_75hz = 154, /* 640x480 (75 Hz) VGA timing. */ timingVESA_640x480_85hz = 158, /* 640x480 (85 Hz) VGA timing. */ timingGTF_640x480_120hz = 159, /* 640x480 (120 Hz) VESA Generalized Timing Formula */ timingApple_640x870_75hz = 160, /* 640x870 (75 Hz) FPD timing.*/ timingApple_640x818_75hz = 165, /* 640x818 (75 Hz) FPD-818 timing.*/ timingApple_832x624_75hz = 170, /* 832x624 (75 Hz) GoldFish timing.*/ timingVESA_800x600_56hz = 180, /* 800x600 (56 Hz) SVGA timing. */ timingVESA_800x600_60hz = 182, /* 800x600 (60 Hz) SVGA timing. */ timingVESA_800x600_72hz = 184, /* 800x600 (72 Hz) SVGA timing. */ timingVESA_800x600_75hz = 186, /* 800x600 (75 Hz) SVGA timing. */ timingVESA_800x600_85hz = 188, /* 800x600 (85 Hz) SVGA timing. */ timingVESA_1024x768_60hz = 190, /* 1024x768 (60 Hz) VESA 1K-60Hz timing. */ timingVESA_1024x768_70hz = 200, /* 1024x768 (70 Hz) VESA 1K-70Hz timing. */ timingVESA_1024x768_75hz = 204, /* 1024x768 (75 Hz) VESA 1K-75Hz timing (very similar to timingApple_1024x768_75hz). */ timingVESA_1024x768_85hz = 208, /* 1024x768 (85 Hz) VESA timing. */ timingApple_1024x768_75hz = 210, /* 1024x768 (75 Hz) Apple 19" RGB. */ timingApple_1152x870_75hz = 220, /* 1152x870 (75 Hz) Apple 21" RGB. */ timingAppleNTSC_ST = 230, /* 512x384 (60 Hz, interlaced, non-convolved). */ timingAppleNTSC_FF = 232, /* 640x480 (60 Hz, interlaced, non-convolved). */ timingAppleNTSC_STconv = 234, /* 512x384 (60 Hz, interlaced, convolved). */ timingAppleNTSC_FFconv = 236, /* 640x480 (60 Hz, interlaced, convolved). */ timingApplePAL_ST = 238, /* 640x480 (50 Hz, interlaced, non-convolved). */ timingApplePAL_FF = 240, /* 768x576 (50 Hz, interlaced, non-convolved). */ timingApplePAL_STconv = 242, /* 640x480 (50 Hz, interlaced, convolved). */ timingApplePAL_FFconv = 244, /* 768x576 (50 Hz, interlaced, convolved). */ timingVESA_1280x960_75hz = 250, /* 1280x960 (75 Hz) */ timingVESA_1280x960_60hz = 252, /* 1280x960 (60 Hz) */ timingVESA_1280x960_85hz = 254, /* 1280x960 (85 Hz) */ timingVESA_1280x1024_60hz = 260, /* 1280x1024 (60 Hz) */ timingVESA_1280x1024_75hz = 262, /* 1280x1024 (75 Hz) */ timingVESA_1280x1024_85hz = 268, /* 1280x1024 (85 Hz) */ timingVESA_1600x1200_60hz = 280, /* 1600x1200 (60 Hz) VESA timing. */ timingVESA_1600x1200_65hz = 282, /* 1600x1200 (65 Hz) VESA timing. */ timingVESA_1600x1200_70hz = 284, /* 1600x1200 (70 Hz) VESA timing. */ timingVESA_1600x1200_75hz = 286, /* 1600x1200 (75 Hz) VESA timing (pixel clock is 189.2 Mhz dot clock). */ timingVESA_1600x1200_80hz = 288, /* 1600x1200 (80 Hz) VESA timing (pixel clock is 216>? Mhz dot clock) - proposed only. */ timingVESA_1600x1200_85hz = 289, /* 1600x1200 (85 Hz) VESA timing (pixel clock is 229.5 Mhz dot clock). */ timingVESA_1792x1344_60hz = 296, /* 1792x1344 (60 Hz) VESA timing (204.75 Mhz dot clock). */ timingVESA_1792x1344_75hz = 298, /* 1792x1344 (75 Hz) VESA timing (261.75 Mhz dot clock). */ timingVESA_1856x1392_60hz = 300, /* 1856x1392 (60 Hz) VESA timing (218.25 Mhz dot clock). */ timingVESA_1856x1392_75hz = 302, /* 1856x1392 (75 Hz) VESA timing (288 Mhz dot clock). */ timingVESA_1920x1440_60hz = 304, /* 1920x1440 (60 Hz) VESA timing (234 Mhz dot clock). */ timingVESA_1920x1440_75hz = 306, /* 1920x1440 (75 Hz) VESA timing (297 Mhz dot clock). */ timingSMPTE240M_60hz = 400, /* 60Hz V, 33.75KHz H, interlaced timing, 16:9 aspect, typical resolution of 1920x1035. */ timingFilmRate_48hz = 410, /* 48Hz V, 25.20KHz H, non-interlaced timing, typical resolution of 640x480. */ timingSony_1600x1024_76hz = 500, /* 1600x1024 (76 Hz) Sony timing (pixel clock is 170.447 Mhz dot clock). */ timingSony_1920x1080_60hz = 510, /* 1920x1080 (60 Hz) Sony timing (pixel clock is 159.84 Mhz dot clock). */ timingSony_1920x1080_72hz = 520, /* 1920x1080 (72 Hz) Sony timing (pixel clock is 216.023 Mhz dot clock). */ timingSony_1920x1200_76hz = 540, /* 1900x1200 (76 Hz) Sony timing (pixel clock is 243.20 Mhz dot clock). */ timingApple_0x0_0hz_Offline = 550 /* Indicates that this timing will take the display off-line and remove it from the system. */ }; /* Deprecated timing names.*/ enum { timingApple12 = timingApple_512x384_60hz, timingApple12x = timingApple_560x384_60hz, timingApple13 = timingApple_640x480_67hz, timingApple13x = timingApple_640x400_67hz, timingAppleVGA = timingVESA_640x480_60hz, timingApple15 = timingApple_640x870_75hz, timingApple15x = timingApple_640x818_75hz, timingApple16 = timingApple_832x624_75hz, timingAppleSVGA = timingVESA_800x600_56hz, timingApple1Ka = timingVESA_1024x768_60hz, timingApple1Kb = timingVESA_1024x768_70hz, timingApple19 = timingApple_1024x768_75hz, timingApple21 = timingApple_1152x870_75hz, timingSony_1900x1200_74hz = 530, /* 1900x1200 (74 Hz) Sony timing (pixel clock is 236.25 Mhz dot clock). */ timingSony_1900x1200_76hz = timingSony_1920x1200_76hz /* 1900x1200 (76 Hz) Sony timing (pixel clock is 245.48 Mhz dot clock). */ }; /* csConnectFlags values in VDDisplayConnectInfo */ enum { kAllModesValid = 0, /* All modes not trimmed by primary init are good close enough to try */ kAllModesSafe = 1, /* All modes not trimmed by primary init are know to be safe */ kReportsTagging = 2, /* Can detect tagged displays (to identify smart monitors) */ kHasDirectConnection = 3, /* True implies that driver can talk directly to device (e.g. serial data link via sense lines) */ kIsMonoDev = 4, /* Says whether there's an RGB (0) or Monochrome (1) connection. */ kUncertainConnection = 5, /* There may not be a display (no sense lines?). */ kTaggingInfoNonStandard = 6, /* Set when csConnectTaggedType/csConnectTaggedData are non-standard (i.e., not the Apple CRT sense codes). */ kReportsDDCConnection = 7, /* Card can do ddc (set kHasDirectConnect && kHasDDCConnect if you actually found a ddc display). */ kHasDDCConnection = 8, /* Card has ddc connect now. */ kConnectionInactive = 9, /* Set when the connection is NOT currently active (generally used in a multiconnection environment). */ kDependentConnection = 10, /* Set when some ascpect of THIS connection depends on another (will generally be set in a kModeSimulscan environment). */ kBuiltInConnection = 11, /* Set when connection is KNOWN to be built-in (this is not the same as kHasDirectConnection). */ kOverrideConnection = 12, /* Set when the reported connection is not the true one, but is one that has been forced through a SetConnection call */ kFastCheckForDDC = 13, /* Set when all 3 are true: 1) sense codes indicate DDC display could be attached 2) attempted fast check 3) DDC failed */ kReportsHotPlugging = 14, /* Detects and reports hot pluggging on connector (via VSL also implies DDC will be up to date w/o force read) */ kStereoSyncConnection = 15 /* Connection supports stereo sync signalling */ }; /* csDisplayType values in VDDisplayConnectInfo */ enum { kUnknownConnect = 1, /* Not sure how we'll use this, but seems like a good idea. */ kPanelConnect = 2, /* For use with fixed-in-place LCD panels. */ kPanelTFTConnect = 2, /* Alias for kPanelConnect */ kFixedModeCRTConnect = 3, /* For use with fixed-mode (i.e., very limited range) displays. */ kMultiModeCRT1Connect = 4, /* 320x200 maybe, 12" maybe, 13" (default), 16" certain, 19" maybe, 21" maybe */ kMultiModeCRT2Connect = 5, /* 320x200 maybe, 12" maybe, 13" certain, 16" (default), 19" certain, 21" maybe */ kMultiModeCRT3Connect = 6, /* 320x200 maybe, 12" maybe, 13" certain, 16" certain, 19" default, 21" certain */ kMultiModeCRT4Connect = 7, /* Expansion to large multi mode (not yet used) */ kModelessConnect = 8, /* Expansion to modeless model (not yet used) */ kFullPageConnect = 9, /* 640x818 (to get 8bpp in 512K case) and 640x870 (these two only) */ kVGAConnect = 10, /* 640x480 VGA default -- question everything else */ kNTSCConnect = 11, /* NTSC ST (default), FF, STconv, FFconv */ kPALConnect = 12, /* PAL ST (default), FF, STconv, FFconv */ kHRConnect = 13, /* Straight-6 connect -- 640x480 and 640x400 (to get 8bpp in 256K case) (these two only) */ kPanelFSTNConnect = 14, /* For use with fixed-in-place LCD FSTN (aka "Supertwist") panels */ kMonoTwoPageConnect = 15, /* 1152x870 Apple color two-page display */ kColorTwoPageConnect = 16, /* 1152x870 Apple B&W two-page display */ kColor16Connect = 17, /* 832x624 Apple B&W two-page display */ kColor19Connect = 18, /* 1024x768 Apple B&W two-page display */ kGenericCRT = 19, /* Indicates nothing except that connection is CRT in nature. */ kGenericLCD = 20, /* Indicates nothing except that connection is LCD in nature. */ kDDCConnect = 21, /* DDC connection, always set kHasDDCConnection */ kNoConnect = 22 /* No display is connected - load sensing or similar level of hardware detection is assumed (used by resident drivers that support hot plugging when nothing is currently connected) */ }; /* csTimingFlags values in VDTimingInfoRec */ enum { kModeValid = 0, /* Says that this mode should NOT be trimmed. */ kModeSafe = 1, /* This mode does not need confirmation */ kModeDefault = 2, /* This is the default mode for this type of connection */ kModeShowNow = 3, /* This mode should always be shown (even though it may require a confirm) */ kModeNotResize = 4, /* This mode should not be used to resize the display (eg. mode selects a different connector on card) */ kModeRequiresPan = 5, /* This mode has more pixels than are actually displayed */ kModeInterlaced = 6, /* This mode is interlaced (single pixel lines look bad). */ kModeShowNever = 7, /* This mode should not be shown in the user interface. */ kModeSimulscan = 8, /* Indicates that more than one display connection can be driven from a single framebuffer controller. */ kModeNotPreset = 9, /* Indicates that the timing is not a factory preset for the current display (geometry may need correction) */ kModeBuiltIn = 10, /* Indicates that the display mode is for the built-in connect only (on multiconnect devices like the PB 3400) Only the driver is quieried */ kModeStretched = 11, /* Indicates that the display mode will be stretched/distorted to match the display aspect ratio */ kModeNotGraphicsQuality = 12, /* Indicates that the display mode is not the highest quality (eg. stretching artifacts). Intended as a hint */ kModeValidateAgainstDisplay = 13 /* Indicates that this mode should be validated against the display EDID */ }; /* csDepthFlags in VDVideoParametersInfoRec */ enum { kDepthDependent = 0, /* Says that this depth mode may cause dependent changes in other framebuffers (and . */ kDepthDependentMask = (1 << kDepthDependent) /* mask for kDepthDependent */ }; /* csResolutionFlags bit flags for VDResolutionInfoRec */ enum { kResolutionHasMultipleDepthSizes = 0 /* Says that this mode has different csHorizontalPixels, csVerticalLines at different depths (usually slightly larger at lower depths) */ }; enum { /* Power Mode constants for VDPowerStateRec.powerState. Note the numeric order does not match the power state order */ kAVPowerOff = 0, /* Power fully off*/ kAVPowerStandby = 1, kAVPowerSuspend = 2, kAVPowerOn = 3, kHardwareSleep = 128, kHardwareWake = 129, kHardwareWakeFromSuspend = 130, kHardwareWakeToDoze = 131, kHardwareWakeToDozeFromSuspend = 132, kHardwarePark = 133, kHardwareDrive = 134 }; /* Reduced perf level, for GetPowerState, SetPowerState*/ enum { kPowerStateReducedPowerMask = 0x00000300, kPowerStateFullPower = 0x00000000, kPowerStateReducedPower1 = 0x00000100, kPowerStateReducedPower2 = 0x00000200, kPowerStateReducedPower3 = 0x00000300 }; enum { /* Power Mode masks and bits for VDPowerStateRec.powerFlags. */ kPowerStateNeedsRefresh = 0, /* When leaving this power mode, a display will need refreshing */ kPowerStateSleepAwareBit = 1, /* if gestaltPCCardDockingSelectorFix, Docking mgr checks this bit before checking kPowerStateSleepAllowedBit */ kPowerStateSleepForbiddenBit = 2, /* if kPowerStateSleepAwareBit, Docking mgr checks this bit before sleeping */ kPowerStateSleepCanPowerOffBit = 3, /* supports power down sleep (ie PCI power off)*/ kPowerStateSleepNoDPMSBit = 4, /* Bug #2425210. Do not use DPMS with this display.*/ kPowerStateSleepWaketoDozeBit = 5, /* Supports Wake to Doze */ kPowerStateSleepWakeNeedsProbeBit = 6, /* Does not sense connection changes on wake */ kPowerStateNeedsRefreshMask = (1 << kPowerStateNeedsRefresh), kPowerStateSleepAwareMask = (1 << kPowerStateSleepAwareBit), kPowerStateSleepForbiddenMask = (1 << kPowerStateSleepForbiddenBit), kPowerStateSleepCanPowerOffMask = (1 << kPowerStateSleepCanPowerOffBit), kPowerStateSleepNoDPMSMask = (1 << kPowerStateSleepNoDPMSBit), kPowerStateSleepWaketoDozeMask = (1 << kPowerStateSleepWaketoDozeBit), kPowerStateSleepWakeNeedsProbeMask = (1 << kPowerStateSleepWakeNeedsProbeBit), kPowerStateSupportsReducedPower1Bit = 10, kPowerStateSupportsReducedPower2Bit = 11, kPowerStateSupportsReducedPower3Bit = 12, kPowerStateSupportsReducedPower1BitMask = (1 << 10), kPowerStateSupportsReducedPower2BitMask = (1 << 11), kPowerStateSupportsReducedPower3BitMask = (1 << 12) }; enum { /* Control Codes */ cscReset = 0, cscKillIO = 1, cscSetMode = 2, cscSetEntries = 3, cscSetGamma = 4, cscGrayPage = 5, cscGrayScreen = 5, cscSetGray = 6, cscSetInterrupt = 7, cscDirectSetEntries = 8, cscSetDefaultMode = 9, cscSwitchMode = 10, /* Takes a VDSwitchInfoPtr */ cscSetSync = 11, /* Takes a VDSyncInfoPtr */ cscSavePreferredConfiguration = 16, /* Takes a VDSwitchInfoPtr */ cscSetHardwareCursor = 22, /* Takes a VDSetHardwareCursorPtr */ cscDrawHardwareCursor = 23, /* Takes a VDDrawHardwareCursorPtr */ cscSetConvolution = 24, /* Takes a VDConvolutionInfoPtr */ cscSetPowerState = 25, /* Takes a VDPowerStatePtr */ cscPrivateControlCall = 26, /* Takes a VDPrivateSelectorDataRec*/ cscSetMultiConnect = 28, /* From a GDI point of view, this call should be implemented completely in the HAL and not at all in the core.*/ cscSetClutBehavior = 29, /* Takes a VDClutBehavior */ cscSetDetailedTiming = 31, /* Takes a VDDetailedTimingPtr */ cscDoCommunication = 33, /* Takes a VDCommunicationPtr */ cscProbeConnection = 34, /* Takes nil pointer */ /* (may generate a kFBConnectInterruptServiceType service interrupt) */ cscSetScaler = 36, /* Takes a VDScalerPtr */ cscSetMirror = 37, /* Takes a VDMirrorPtr*/ cscSetFeatureConfiguration = 38, /* Takes a VDConfigurationPtr*/ cscUnusedCall = 127 /* This call used to expand the scrn resource. Its imbedded data contains more control info */ }; enum { /* Status Codes */ cscGetMode = 2, cscGetEntries = 3, cscGetPageCnt = 4, cscGetPages = 4, /* This is what C&D 2 calls it. */ cscGetPageBase = 5, cscGetBaseAddr = 5, /* This is what C&D 2 calls it. */ cscGetGray = 6, cscGetInterrupt = 7, cscGetGamma = 8, cscGetDefaultMode = 9, cscGetCurMode = 10, /* Takes a VDSwitchInfoPtr */ cscGetSync = 11, /* Takes a VDSyncInfoPtr */ cscGetConnection = 12, /* Return information about the connection to the display */ cscGetModeTiming = 13, /* Return timing info for a mode */ cscGetModeBaseAddress = 14, /* Return base address information about a particular mode */ cscGetScanProc = 15, /* QuickTime scan chasing routine */ cscGetPreferredConfiguration = 16, /* Takes a VDSwitchInfoPtr */ cscGetNextResolution = 17, /* Takes a VDResolutionInfoPtr */ cscGetVideoParameters = 18, /* Takes a VDVideoParametersInfoPtr */ cscGetGammaInfoList = 20, /* Takes a VDGetGammaListPtr */ cscRetrieveGammaTable = 21, /* Takes a VDRetrieveGammaPtr */ cscSupportsHardwareCursor = 22, /* Takes a VDSupportsHardwareCursorPtr */ cscGetHardwareCursorDrawState = 23, /* Takes a VDHardwareCursorDrawStatePtr */ cscGetConvolution = 24, /* Takes a VDConvolutionInfoPtr */ cscGetPowerState = 25, /* Takes a VDPowerStatePtr */ cscPrivateStatusCall = 26, /* Takes a VDPrivateSelectorDataRec*/ cscGetDDCBlock = 27, /* Takes a VDDDCBlockRec */ cscGetMultiConnect = 28, /* From a GDI point of view, this call should be implemented completely in the HAL and not at all in the core.*/ cscGetClutBehavior = 29, /* Takes a VDClutBehavior */ cscGetTimingRanges = 30, /* Takes a VDDisplayTimingRangePtr */ cscGetDetailedTiming = 31, /* Takes a VDDetailedTimingPtr */ cscGetCommunicationInfo = 32, /* Takes a VDCommunicationInfoPtr */ cscGetScalerInfo = 35, /* Takes a VDScalerInfoPtr */ cscGetScaler = 36, /* Takes a VDScalerPtr */ cscGetMirror = 37, /* Takes a VDMirrorPtr*/ cscGetFeatureConfiguration = 38, /* Takes a VDConfigurationPtr*/ cscGetFeatureList = 39 }; /* Bit definitions for the Get/Set Sync call*/ enum { kDisableHorizontalSyncBit = 0, kDisableVerticalSyncBit = 1, kDisableCompositeSyncBit = 2, kEnableSyncOnBlue = 3, kEnableSyncOnGreen = 4, kEnableSyncOnRed = 5, kNoSeparateSyncControlBit = 6, kTriStateSyncBit = 7, kHorizontalSyncMask = 0x01, kVerticalSyncMask = 0x02, kCompositeSyncMask = 0x04, kDPMSSyncMask = 0x07, kTriStateSyncMask = 0x80, kSyncOnBlueMask = 0x08, kSyncOnGreenMask = 0x10, kSyncOnRedMask = 0x20, kSyncOnMask = 0x38 }; enum { /* Power Mode constants for translating DPMS modes to Get/SetSync calls. */ kDPMSSyncOn = 0, kDPMSSyncStandby = 1, kDPMSSyncSuspend = 2, kDPMSSyncOff = 7 }; /* Bit definitions for the Get/Set Convolution call*/ enum { kConvolved = 0, kLiveVideoPassThru = 1, kConvolvedMask = 0x01, kLiveVideoPassThruMask = 0x02 }; struct VPBlock { UInt32 vpBaseOffset; /*Offset to page zero of video RAM (From minorBaseOS).*/ #if __LP64__ UInt32 vpRowBytes; /*Width of each row of video memory.*/ #else SInt16 vpRowBytes; /*Width of each row of video memory.*/ #endif Rect vpBounds; /*BoundsRect for the video display (gives dimensions).*/ SInt16 vpVersion; /*PixelMap version number.*/ SInt16 vpPackType; UInt32 vpPackSize; UInt32 vpHRes; /*Horizontal resolution of the device (pixels per inch).*/ UInt32 vpVRes; /*Vertical resolution of the device (pixels per inch).*/ SInt16 vpPixelType; /*Defines the pixel type.*/ SInt16 vpPixelSize; /*Number of bits in pixel.*/ SInt16 vpCmpCount; /*Number of components in pixel.*/ SInt16 vpCmpSize; /*Number of bits per component*/ UInt32 vpPlaneBytes; /*Offset from one plane to the next.*/ }; typedef struct VPBlock VPBlock; typedef VPBlock * VPBlockPtr; struct VDEntryRecord { Ptr csTable; /* pointer to color table entry=value, r,g,b:INTEGER*/ }; typedef struct VDEntryRecord VDEntryRecord; typedef VDEntryRecord * VDEntRecPtr; /* Parm block for SetGray control call */ struct VDGrayRecord { Boolean csMode; /*Same as GDDevType value (0=color, 1=mono)*/ SInt8 filler; }; typedef struct VDGrayRecord VDGrayRecord; typedef VDGrayRecord * VDGrayPtr; /* Parm block for SetInterrupt call */ struct VDFlagRecord { SInt8 csMode; SInt8 filler; }; typedef struct VDFlagRecord VDFlagRecord; typedef VDFlagRecord * VDFlagRecPtr; /* Parm block for SetEntries control call */ struct VDSetEntryRecord { ColorSpec * csTable; /*Pointer to an array of color specs*/ SInt16 csStart; /*Which spec in array to start with, or -1*/ SInt16 csCount; /*Number of color spec entries to set*/ }; typedef struct VDSetEntryRecord VDSetEntryRecord; typedef VDSetEntryRecord * VDSetEntryPtr; /* Parm block for SetGamma control call */ struct VDGammaRecord { Ptr csGTable; /*pointer to gamma table*/ }; typedef struct VDGammaRecord VDGammaRecord; typedef VDGammaRecord * VDGamRecPtr; struct VDSwitchInfoRec { DepthMode csMode; /* mode depth*/ DisplayModeID csData; /* functional sResource of mode*/ UInt16 csPage; /* page to switch in*/ Ptr csBaseAddr; /* base address of page (return value)*/ uintptr_t csReserved; /* Reserved (set to 0) */ }; typedef struct VDSwitchInfoRec VDSwitchInfoRec; typedef VDSwitchInfoRec * VDSwitchInfoPtr; struct VDTimingInfoRec { DisplayModeID csTimingMode; /* timing mode (a la InitGDevice) */ uintptr_t csTimingReserved; /* reserved */ UInt32 csTimingFormat; /* what format is the timing info */ UInt32 csTimingData; /* data supplied by driver */ UInt32 csTimingFlags; /* mode within device */ }; typedef struct VDTimingInfoRec VDTimingInfoRec; typedef VDTimingInfoRec * VDTimingInfoPtr; struct VDDisplayConnectInfoRec { UInt16 csDisplayType; /* Type of display connected */ UInt8 csConnectTaggedType; /* type of tagging */ UInt8 csConnectTaggedData; /* tagging data */ UInt32 csConnectFlags; /* tell us about the connection */ uintptr_t csDisplayComponent; /* if the card has a direct connection to the display, it returns the display component here (FUTURE) */ uintptr_t csConnectReserved; /* reserved */ }; typedef struct VDDisplayConnectInfoRec VDDisplayConnectInfoRec; typedef VDDisplayConnectInfoRec * VDDisplayConnectInfoPtr; struct VDMultiConnectInfoRec { UInt32 csDisplayCountOrNumber; /* For GetMultiConnect, returns count n of 1..n connections; otherwise, indicates the ith connection.*/ VDDisplayConnectInfoRec csConnectInfo; /* Standard VDDisplayConnectionInfo for connection i.*/ }; typedef struct VDMultiConnectInfoRec VDMultiConnectInfoRec; typedef VDMultiConnectInfoRec * VDMultiConnectInfoPtr; /* RawSenseCode This abstract data type is not exactly abstract. Rather, it is merely enumerated constants for the possible raw sense code values when 'standard' sense code hardware is implemented. For 'standard' sense code hardware, the raw sense is obtained as follows: o Instruct the frame buffer controller NOT to actively drive any of the monitor sense lines o Read the state of the monitor sense lines 2, 1, and 0. (2 is the MSB, 0 the LSB) IMPORTANT Note: When the 'kTaggingInfoNonStandard' bit of 'csConnectFlags' is FALSE, then these constants are valid 'csConnectTaggedType' values in 'VDDisplayConnectInfo' */ typedef UInt8 RawSenseCode; enum { kRSCZero = 0, kRSCOne = 1, kRSCTwo = 2, kRSCThree = 3, kRSCFour = 4, kRSCFive = 5, kRSCSix = 6, kRSCSeven = 7 }; /* ExtendedSenseCode This abstract data type is not exactly abstract. Rather, it is merely enumerated constants for the values which are possible when the extended sense algorithm is applied to hardware which implements 'standard' sense code hardware. For 'standard' sense code hardware, the extended sense code algorithm is as follows: (Note: as described here, sense line 'A' corresponds to '2', 'B' to '1', and 'C' to '0') o Drive sense line 'A' low and read the values of 'B' and 'C'. o Drive sense line 'B' low and read the values of 'A' and 'C'. o Drive sense line 'C' low and read the values of 'A' and 'B'. In this way, a six-bit number of the form BC/AC/AB is generated. IMPORTANT Note: When the 'kTaggingInfoNonStandard' bit of 'csConnectFlags' is FALSE, then these constants are valid 'csConnectTaggedData' values in 'VDDisplayConnectInfo' */ typedef UInt8 ExtendedSenseCode; enum { kESCZero21Inch = 0x00, /* 21" RGB */ kESCOnePortraitMono = 0x14, /* Portrait Monochrome */ kESCTwo12Inch = 0x21, /* 12" RGB */ kESCThree21InchRadius = 0x31, /* 21" RGB (Radius) */ kESCThree21InchMonoRadius = 0x34, /* 21" Monochrome (Radius) */ kESCThree21InchMono = 0x35, /* 21" Monochrome */ kESCFourNTSC = 0x0A, /* NTSC */ kESCFivePortrait = 0x1E, /* Portrait RGB */ kESCSixMSB1 = 0x03, /* MultiScan Band-1 (12" thru 1Six") */ kESCSixMSB2 = 0x0B, /* MultiScan Band-2 (13" thru 19") */ kESCSixMSB3 = 0x23, /* MultiScan Band-3 (13" thru 21") */ kESCSixStandard = 0x2B, /* 13"/14" RGB or 12" Monochrome */ kESCSevenPAL = 0x00, /* PAL */ kESCSevenNTSC = 0x14, /* NTSC */ kESCSevenVGA = 0x17, /* VGA */ kESCSeven16Inch = 0x2D, /* 16" RGB (GoldFish) */ kESCSevenPALAlternate = 0x30, /* PAL (Alternate) */ kESCSeven19Inch = 0x3A, /* Third-Party 19" */ kESCSevenDDC = 0x3E, /* DDC display */ kESCSevenNoDisplay = 0x3F /* No display connected */ }; /* DepthMode This abstract data type is used to to reference RELATIVE pixel depths. Its definition is largely derived from its past usage, analogous to 'xxxVidMode' Bits per pixel DOES NOT directly map to 'DepthMode' For example, on some graphics hardware, 'kDepthMode1' may represent 1 BPP, whereas on other hardware, 'kDepthMode1' may represent 8BPP. DepthMode IS considered to be ordinal, i.e., operations such as <, >, ==, etc. behave as expected. The values of the constants which comprise the set are such that 'kDepthMode4 < kDepthMode6' behaves as expected. */ enum { kDepthMode1 = 128, kDepthMode2 = 129, kDepthMode3 = 130, kDepthMode4 = 131, kDepthMode5 = 132, kDepthMode6 = 133 }; enum { kFirstDepthMode = 128, /* These constants are obsolete, and just included */ kSecondDepthMode = 129, /* for clients that have converted to the above */ kThirdDepthMode = 130, /* kDepthModeXXX constants. */ kFourthDepthMode = 131, kFifthDepthMode = 132, kSixthDepthMode = 133 }; struct VDPageInfo { DepthMode csMode; /* mode within device*/ DisplayModeID csData; /* data supplied by driver*/ SInt16 csPage; /* page to switch in*/ Ptr csBaseAddr; /* base address of page*/ }; typedef struct VDPageInfo VDPageInfo; typedef VDPageInfo * VDPgInfoPtr; struct VDSizeInfo { SInt16 csHSize; /* desired/returned h size*/ SInt16 csHPos; /* desired/returned h position*/ SInt16 csVSize; /* desired/returned v size*/ SInt16 csVPos; /* desired/returned v position*/ }; typedef struct VDSizeInfo VDSizeInfo; typedef VDSizeInfo * VDSzInfoPtr; struct VDSettings { SInt16 csParamCnt; /* number of params*/ SInt16 csBrightMax; /* max brightness*/ SInt16 csBrightDef; /* default brightness*/ SInt16 csBrightVal; /* current brightness*/ SInt16 csCntrstMax; /* max contrast*/ SInt16 csCntrstDef; /* default contrast*/ SInt16 csCntrstVal; /* current contrast*/ SInt16 csTintMax; /* max tint*/ SInt16 csTintDef; /* default tint*/ SInt16 csTintVal; /* current tint*/ SInt16 csHueMax; /* max hue*/ SInt16 csHueDef; /* default hue*/ SInt16 csHueVal; /* current hue*/ SInt16 csHorizDef; /* default horizontal*/ SInt16 csHorizVal; /* current horizontal*/ SInt16 csHorizMax; /* max horizontal*/ SInt16 csVertDef; /* default vertical*/ SInt16 csVertVal; /* current vertical*/ SInt16 csVertMax; /* max vertical*/ }; typedef struct VDSettings VDSettings; typedef VDSettings * VDSettingsPtr; struct VDDefMode { UInt8 csID; SInt8 filler; }; typedef struct VDDefMode VDDefMode; typedef VDDefMode * VDDefModePtr; struct VDSyncInfoRec { UInt8 csMode; UInt8 csFlags; }; typedef struct VDSyncInfoRec VDSyncInfoRec; typedef VDSyncInfoRec * VDSyncInfoPtr; /* All displayModeID values from 0x80000000 to 0xFFFFFFFF and 0x00 are reserved for Apple Computer. */ /* Constants for the cscGetNextResolution call */ enum { kDisplayModeIDCurrent = 0x00, /* Reference the Current DisplayModeID */ kDisplayModeIDInvalid = (IODisplayModeID)0xFFFFFFFF, /* A bogus DisplayModeID in all cases */ kDisplayModeIDFindFirstResolution = (IODisplayModeID)0xFFFFFFFE, /* Used in cscGetNextResolution to reset iterator */ kDisplayModeIDNoMoreResolutions = (IODisplayModeID)0xFFFFFFFD, /* Used in cscGetNextResolution to indicate End Of List */ kDisplayModeIDFindFirstProgrammable = (IODisplayModeID)0xFFFFFFFC, /* Used in cscGetNextResolution to find unused programmable timing */ kDisplayModeIDBootProgrammable = (IODisplayModeID)0xFFFFFFFB, /* This is the ID given at boot time by the OF driver to a programmable timing */ kDisplayModeIDReservedBase = (IODisplayModeID)0x80000000 /* Lowest (unsigned) DisplayModeID reserved by Apple */ }; /* Constants for the GetGammaInfoList call */ enum { kGammaTableIDFindFirst = (GammaTableID)0xFFFFFFFE, /* Get the first gamma table ID */ kGammaTableIDNoMoreTables = (GammaTableID)0xFFFFFFFD, /* Used to indicate end of list */ kGammaTableIDSpecific = 0x00 /* Return the info for the given table id */ }; /* Constants for GetMultiConnect call*/ enum { kGetConnectionCount = 0xFFFFFFFF, /* Used to get the number of possible connections in a "multi-headed" framebuffer environment.*/ kActivateConnection = (0 << kConnectionInactive), /* Used for activating a connection (csConnectFlags value).*/ kDeactivateConnection = (1 << kConnectionInactive) /* Used for deactivating a connection (csConnectFlags value.)*/ }; /* VDCommunicationRec.csBusID values*/ enum { kVideoDefaultBus = 0 }; /* VDCommunicationInfoRec.csBusType values*/ enum { kVideoBusTypeInvalid = 0, kVideoBusTypeI2C = 1, kVideoBusTypeDisplayPort = 2 }; /* VDCommunicationRec.csSendType and VDCommunicationRec.csReplyType values*/ enum { kVideoNoTransactionType = 0, /* No transaction*/ kVideoNoTransactionTypeMask = (1 << kVideoNoTransactionType), kVideoSimpleI2CType = 1, /* Simple I2C message*/ kVideoSimpleI2CTypeMask = (1 << kVideoSimpleI2CType), kVideoDDCciReplyType = 2, /* DDC/ci message (with imbedded length)*/ kVideoDDCciReplyTypeMask = (1 << kVideoDDCciReplyType), kVideoCombinedI2CType = 3, /* Combined format I2C R/~W transaction*/ kVideoCombinedI2CTypeMask = (1 << kVideoCombinedI2CType), kVideoDisplayPortNativeType = 4, /* DisplayPort Native */ kVideoDisplayPortNativeTypeMask = (1 << kVideoDisplayPortNativeType) }; // VDCommunicationRec.csCommFlags and VDCommunicationInfoRec.csSupportedCommFlags enum { kVideoReplyMicroSecDelayBit = 0, /* If bit set, the driver should delay csMinReplyDelay micro seconds between send and receive*/ kVideoReplyMicroSecDelayMask = (1 << kVideoReplyMicroSecDelayBit), kVideoUsageAddrSubAddrBit = 1, /* If bit set, the driver understands to use the lower 16 bits of the address field as two 8 bit values (address/subaddress) for the I2C transaction*/ kVideoUsageAddrSubAddrMask = (1 << kVideoUsageAddrSubAddrBit) }; struct VDResolutionInfoRec { DisplayModeID csPreviousDisplayModeID; /* ID of the previous resolution in a chain */ DisplayModeID csDisplayModeID; /* ID of the next resolution */ UInt32 csHorizontalPixels; /* # of pixels in a horizontal line at the max depth */ UInt32 csVerticalLines; /* # of lines in a screen at the max depth */ Fixed csRefreshRate; /* Vertical Refresh Rate in Hz */ DepthMode csMaxDepthMode; /* 0x80-based number representing max bit depth */ UInt32 csResolutionFlags; /* Reserved - flag bits */ uintptr_t csReserved; /* Reserved */ }; typedef struct VDResolutionInfoRec VDResolutionInfoRec; typedef VDResolutionInfoRec * VDResolutionInfoPtr; struct VDVideoParametersInfoRec { DisplayModeID csDisplayModeID; /* the ID of the resolution we want info on */ DepthMode csDepthMode; /* The bit depth we want the info on (0x80 based) */ VPBlockPtr csVPBlockPtr; /* Pointer to a video parameter block */ UInt32 csPageCount; /* Number of pages supported by the resolution */ VideoDeviceType csDeviceType; /* Device Type: Direct, Fixed or CLUT; */ UInt32 csDepthFlags; /* Flags */ }; typedef struct VDVideoParametersInfoRec VDVideoParametersInfoRec; typedef VDVideoParametersInfoRec * VDVideoParametersInfoPtr; struct VDGammaInfoRec { GammaTableID csLastGammaID; /* the ID of the previous gamma table */ GammaTableID csNextGammaID; /* the ID of the next gamma table */ Ptr csGammaPtr; /* Ptr to a gamma table data */ uintptr_t csReserved; /* Reserved */ }; typedef struct VDGammaInfoRec VDGammaInfoRec; typedef VDGammaInfoRec * VDGammaInfoPtr; struct VDGetGammaListRec { GammaTableID csPreviousGammaTableID; /* ID of the previous gamma table */ GammaTableID csGammaTableID; /* ID of the gamma table following csPreviousDisplayModeID */ UInt32 csGammaTableSize; /* Size of the gamma table in bytes */ char * csGammaTableName; /* Gamma table name (c-string) */ }; typedef struct VDGetGammaListRec VDGetGammaListRec; typedef VDGetGammaListRec * VDGetGammaListPtr; struct VDRetrieveGammaRec { GammaTableID csGammaTableID; /* ID of gamma table to retrieve */ GammaTbl * csGammaTablePtr; /* Location to copy desired gamma to */ }; typedef struct VDRetrieveGammaRec VDRetrieveGammaRec; typedef VDRetrieveGammaRec * VDRetrieveGammaPtr; struct VDSetHardwareCursorRec { void * csCursorRef; /* reference to cursor data */ UInt32 csReserved1; /* reserved for future use */ UInt32 csReserved2; /* should be ignored */ }; typedef struct VDSetHardwareCursorRec VDSetHardwareCursorRec; typedef VDSetHardwareCursorRec * VDSetHardwareCursorPtr; struct VDDrawHardwareCursorRec { SInt32 csCursorX; /* x coordinate */ SInt32 csCursorY; /* y coordinate */ UInt32 csCursorVisible; /* true if cursor is must be visible */ UInt32 csReserved1; /* reserved for future use */ UInt32 csReserved2; /* should be ignored */ }; typedef struct VDDrawHardwareCursorRec VDDrawHardwareCursorRec; typedef VDDrawHardwareCursorRec * VDDrawHardwareCursorPtr; struct VDSupportsHardwareCursorRec { UInt32 csSupportsHardwareCursor; /* true if hardware cursor is supported */ UInt32 csReserved1; /* reserved for future use */ UInt32 csReserved2; /* must be zero */ }; typedef struct VDSupportsHardwareCursorRec VDSupportsHardwareCursorRec; typedef VDSupportsHardwareCursorRec * VDSupportsHardwareCursorPtr; struct VDHardwareCursorDrawStateRec { SInt32 csCursorX; /* x coordinate */ SInt32 csCursorY; /* y coordinate */ UInt32 csCursorVisible; /* true if cursor is visible */ UInt32 csCursorSet; /* true if cursor successfully set by last set control call */ UInt32 csReserved1; /* reserved for future use */ UInt32 csReserved2; /* must be zero */ }; typedef struct VDHardwareCursorDrawStateRec VDHardwareCursorDrawStateRec; typedef VDHardwareCursorDrawStateRec * VDHardwareCursorDrawStatePtr; struct VDConvolutionInfoRec { DisplayModeID csDisplayModeID; /* the ID of the resolution we want info on */ DepthMode csDepthMode; /* The bit depth we want the info on (0x80 based) */ UInt32 csPage; UInt32 csFlags; UInt32 csReserved; }; typedef struct VDConvolutionInfoRec VDConvolutionInfoRec; typedef VDConvolutionInfoRec * VDConvolutionInfoPtr; struct VDPowerStateRec { UInt32 powerState; UInt32 powerFlags; uintptr_t powerReserved1; uintptr_t powerReserved2; }; typedef struct VDPowerStateRec VDPowerStateRec; typedef VDPowerStateRec * VDPowerStatePtr; /* Private Data to video drivers. In versions of MacOS with multiple address spaces (System 8), the OS must know the extent of parameters in order to move them between the caller and driver. The old private-selector model for video drivers does not have this information so: For post-7.x Systems private calls should be implemented using the cscPrivateCall */ struct VDPrivateSelectorDataRec { LogicalAddress privateParameters; /* Caller's parameters*/ ByteCount privateParametersSize; /* Size of data sent from caller to driver*/ LogicalAddress privateResults; /* Caller's return area. Can be nil, or same as privateParameters.*/ ByteCount privateResultsSize; /* Size of data driver returns to caller. Can be nil, or same as privateParametersSize.*/ }; typedef struct VDPrivateSelectorDataRec VDPrivateSelectorDataRec; struct VDPrivateSelectorRec { UInt32 reserved; /* Reserved (set to 0). */ VDPrivateSelectorDataRec data[1]; }; typedef struct VDPrivateSelectorRec VDPrivateSelectorRec; struct VDDDCBlockRec { UInt32 ddcBlockNumber; /* Input -- DDC EDID (Extended Display Identification Data) number (1-based) */ ResType ddcBlockType; /* Input -- DDC block type (EDID/VDIF) */ UInt32 ddcFlags; /* Input -- DDC Flags*/ UInt32 ddcReserved; /* Reserved */ Byte ddcBlockData[128]; /* Output -- DDC EDID/VDIF data (kDDCBlockSize) */ }; typedef struct VDDDCBlockRec VDDDCBlockRec; typedef VDDDCBlockRec * VDDDCBlockPtr; enum { /* timingSyncConfiguration*/ kSyncInterlaceMask = (1 << 7), kSyncAnalogCompositeMask = 0, kSyncAnalogCompositeSerrateMask = (1 << 2), kSyncAnalogCompositeRGBSyncMask = (1 << 1), kSyncAnalogBipolarMask = (1 << 3), kSyncAnalogBipolarSerrateMask = (1 << 2), kSyncAnalogBipolarSRGBSyncMask = (1 << 1), kSyncDigitalCompositeMask = (1 << 4), kSyncDigitalCompositeSerrateMask = (1 << 2), kSyncDigitalCompositeMatchHSyncMask = (1 << 2), kSyncDigitalSeperateMask = (1 << 4) + (1 << 3), kSyncDigitalVSyncPositiveMask = (1 << 2), kSyncDigitalHSyncPositiveMask = (1 << 1) }; struct VDDisplayTimingRangeRec { UInt32 csRangeSize; /* Init to sizeof(VDDisplayTimingRangeRec) */ UInt32 csRangeType; /* Init to 0 */ UInt32 csRangeVersion; /* Init to 0 */ UInt32 csRangeReserved; /* Init to 0 */ UInt32 csRangeBlockIndex; /* Requested block (first index is 0)*/ UInt32 csRangeGroup; /* set to 0 */ UInt32 csRangeBlockCount; /* # blocks */ UInt32 csRangeFlags; /* dependent video */ UInt64 csMinPixelClock; /* Min dot clock in Hz */ UInt64 csMaxPixelClock; /* Max dot clock in Hz */ UInt32 csMaxPixelError; /* Max dot clock error */ UInt32 csTimingRangeSyncFlags; UInt32 csTimingRangeSignalLevels; UInt32 csTimingRangeSupportedSignalConfigs; UInt32 csMinFrameRate; /* Hz */ UInt32 csMaxFrameRate; /* Hz */ UInt32 csMinLineRate; /* Hz */ UInt32 csMaxLineRate; /* Hz */ UInt32 csMaxHorizontalTotal; /* Clocks - Maximum total (active + blanking) */ UInt32 csMaxVerticalTotal; /* Clocks - Maximum total (active + blanking) */ UInt32 csMaxTotalReserved1; /* Reserved */ UInt32 csMaxTotalReserved2; /* Reserved */ /* Some cards require that some timing elements*/ /* be multiples of a "character size" (often 8*/ /* clocks). The "xxxxCharSize" fields document*/ /* those requirements.*/ UInt8 csCharSizeHorizontalActive; /* Character size */ UInt8 csCharSizeHorizontalBlanking; /* Character size */ UInt8 csCharSizeHorizontalSyncOffset; /* Character size */ UInt8 csCharSizeHorizontalSyncPulse; /* Character size */ UInt8 csCharSizeVerticalActive; /* Character size */ UInt8 csCharSizeVerticalBlanking; /* Character size */ UInt8 csCharSizeVerticalSyncOffset; /* Character size */ UInt8 csCharSizeVerticalSyncPulse; /* Character size */ UInt8 csCharSizeHorizontalBorderLeft; /* Character size */ UInt8 csCharSizeHorizontalBorderRight; /* Character size */ UInt8 csCharSizeVerticalBorderTop; /* Character size */ UInt8 csCharSizeVerticalBorderBottom; /* Character size */ UInt8 csCharSizeHorizontalTotal; /* Character size for active + blanking */ UInt8 csCharSizeVerticalTotal; /* Character size for active + blanking */ UInt16 csCharSizeReserved1; /* Reserved (Init to 0) */ UInt32 csMinHorizontalActiveClocks; UInt32 csMaxHorizontalActiveClocks; UInt32 csMinHorizontalBlankingClocks; UInt32 csMaxHorizontalBlankingClocks; UInt32 csMinHorizontalSyncOffsetClocks; UInt32 csMaxHorizontalSyncOffsetClocks; UInt32 csMinHorizontalPulseWidthClocks; UInt32 csMaxHorizontalPulseWidthClocks; UInt32 csMinVerticalActiveClocks; UInt32 csMaxVerticalActiveClocks; UInt32 csMinVerticalBlankingClocks; UInt32 csMaxVerticalBlankingClocks; UInt32 csMinVerticalSyncOffsetClocks; UInt32 csMaxVerticalSyncOffsetClocks; UInt32 csMinVerticalPulseWidthClocks; UInt32 csMaxVerticalPulseWidthClocks; UInt32 csMinHorizontalBorderLeft; UInt32 csMaxHorizontalBorderLeft; UInt32 csMinHorizontalBorderRight; UInt32 csMaxHorizontalBorderRight; UInt32 csMinVerticalBorderTop; UInt32 csMaxVerticalBorderTop; UInt32 csMinVerticalBorderBottom; UInt32 csMaxVerticalBorderBottom; UInt32 csMaxNumLinks; /* number of links, if zero, assume link 1 */ UInt32 csMinLink0PixelClock; /* min pixel clock for link 0 (kHz) */ UInt32 csMaxLink0PixelClock; /* max pixel clock for link 0 (kHz) */ UInt32 csMinLink1PixelClock; /* min pixel clock for link 1 (kHz) */ UInt32 csMaxLink1PixelClock; /* max pixel clock for link 1 (kHz) */ UInt32 csReserved6; /* Reserved (Init to 0)*/ UInt32 csReserved7; /* Reserved (Init to 0)*/ UInt32 csReserved8; /* Reserved (Init to 0)*/ }; typedef struct VDDisplayTimingRangeRec VDDisplayTimingRangeRec; typedef VDDisplayTimingRangeRec * VDDisplayTimingRangePtr; enum { /* csDisplayModeState*/ kDMSModeReady = 0, /* Display Mode ID is configured and ready*/ kDMSModeNotReady = 1, /* Display Mode ID is is being programmed*/ kDMSModeFree = 2 /* Display Mode ID is not associated with a timing*/ }; /* Video driver Errors -10930 to -10959 */ enum { kTimingChangeRestrictedErr = -10930, kVideoI2CReplyPendingErr = -10931, kVideoI2CTransactionErr = -10932, kVideoI2CBusyErr = -10933, kVideoI2CTransactionTypeErr = -10934, kVideoBufferSizeErr = -10935, kVideoCannotMirrorErr = -10936 }; enum { /* csTimingRangeSignalLevels*/ kRangeSupportsSignal_0700_0300_Bit = 0, kRangeSupportsSignal_0714_0286_Bit = 1, kRangeSupportsSignal_1000_0400_Bit = 2, kRangeSupportsSignal_0700_0000_Bit = 3, kRangeSupportsSignal_0700_0300_Mask = (1 << kRangeSupportsSignal_0700_0300_Bit), kRangeSupportsSignal_0714_0286_Mask = (1 << kRangeSupportsSignal_0714_0286_Bit), kRangeSupportsSignal_1000_0400_Mask = (1 << kRangeSupportsSignal_1000_0400_Bit), kRangeSupportsSignal_0700_0000_Mask = (1 << kRangeSupportsSignal_0700_0000_Bit) }; enum { /* csSignalConfig*/ kDigitalSignalBit = 0, /* Do not set. Mac OS does not currently support arbitrary digital timings*/ kAnalogSetupExpectedBit = 1, /* Analog displays - display expects a blank-to-black setup or pedestal. See VESA signal standards.*/ kInterlacedCEA861SyncModeBit = 2, kDigitalSignalMask = (1 << kDigitalSignalBit), kAnalogSetupExpectedMask = (1 << kAnalogSetupExpectedBit), kInterlacedCEA861SyncModeMask = (1 << kInterlacedCEA861SyncModeBit) }; enum { /* csSignalLevels for analog*/ kAnalogSignalLevel_0700_0300 = 0, kAnalogSignalLevel_0714_0286 = 1, kAnalogSignalLevel_1000_0400 = 2, kAnalogSignalLevel_0700_0000 = 3 }; enum { /* csTimingRangeSyncFlags*/ kRangeSupportsSeperateSyncsBit = 0, kRangeSupportsSyncOnGreenBit = 1, kRangeSupportsCompositeSyncBit = 2, kRangeSupportsVSyncSerrationBit = 3, kRangeSupportsSeperateSyncsMask = (1 << kRangeSupportsSeperateSyncsBit), kRangeSupportsSyncOnGreenMask = (1 << kRangeSupportsSyncOnGreenBit), kRangeSupportsCompositeSyncMask = (1 << kRangeSupportsCompositeSyncBit), kRangeSupportsVSyncSerrationMask = (1 << kRangeSupportsVSyncSerrationBit) }; enum { /* csHorizontalSyncConfig and csVerticalSyncConfig*/ kSyncPositivePolarityBit = 0, /* Digital separate sync polarity for analog interfaces (0 => negative polarity)*/ kSyncPositivePolarityMask = (1 << kSyncPositivePolarityBit) }; /* For timings with kDetailedTimingFormat.*/ struct VDDetailedTimingRec { UInt32 csTimingSize; /* Init to sizeof(VDDetailedTimingRec)*/ UInt32 csTimingType; /* Init to 0*/ UInt32 csTimingVersion; /* Init to 0*/ UInt32 csTimingReserved; /* Init to 0*/ DisplayModeID csDisplayModeID; /* Init to 0*/ UInt32 csDisplayModeSeed; /* */ UInt32 csDisplayModeState; /* Display Mode state*/ UInt32 csDisplayModeAlias; /* Mode to use when programmed.*/ UInt32 csSignalConfig; UInt32 csSignalLevels; UInt64 csPixelClock; /* Hz*/ UInt64 csMinPixelClock; /* Hz - With error what is slowest actual clock */ UInt64 csMaxPixelClock; /* Hz - With error what is fasted actual clock */ UInt32 csHorizontalActive; /* Pixels*/ UInt32 csHorizontalBlanking; /* Pixels*/ UInt32 csHorizontalSyncOffset; /* Pixels*/ UInt32 csHorizontalSyncPulseWidth; /* Pixels*/ UInt32 csVerticalActive; /* Lines*/ UInt32 csVerticalBlanking; /* Lines*/ UInt32 csVerticalSyncOffset; /* Lines*/ UInt32 csVerticalSyncPulseWidth; /* Lines*/ UInt32 csHorizontalBorderLeft; /* Pixels*/ UInt32 csHorizontalBorderRight; /* Pixels*/ UInt32 csVerticalBorderTop; /* Lines*/ UInt32 csVerticalBorderBottom; /* Lines*/ UInt32 csHorizontalSyncConfig; UInt32 csHorizontalSyncLevel; /* Future use (init to 0)*/ UInt32 csVerticalSyncConfig; UInt32 csVerticalSyncLevel; /* Future use (init to 0)*/ UInt32 csNumLinks; /* number of links, if 0 = assume link - 0 */ UInt32 csReserved2; /* Init to 0*/ UInt32 csReserved3; /* Init to 0*/ UInt32 csReserved4; /* Init to 0*/ UInt32 csReserved5; /* Init to 0*/ UInt32 csReserved6; /* Init to 0*/ UInt32 csReserved7; /* Init to 0*/ UInt32 csReserved8; /* Init to 0*/ }; typedef struct VDDetailedTimingRec VDDetailedTimingRec; typedef VDDetailedTimingRec * VDDetailedTimingPtr; /* csScalerFeatures */ enum { kScaleStretchOnlyMask = (1<<0), /* True means the driver cannot add borders to avoid non-square pixels */ kScaleCanUpSamplePixelsMask = (1<<1), /* True means timings with more active clocks than pixels (ie 640x480 pixels on a 1600x1200 timing) */ kScaleCanDownSamplePixelsMask = (1<<2), /* True means timings with fewer active clocks than pixels (ie 1600x1200 pixels on a 640x480 timing) */ kScaleCanScaleInterlacedMask = (1<<3), /* True means can scale an interlaced timing */ kScaleCanSupportInsetMask = (1<<4), /* True means can scale a timing with insets */ kScaleCanRotateMask = (1<<5), /* True means can rotate image */ kScaleCanBorderInsetOnlyMask = (1<<6) /* True means can scale a timing with insets */ }; /* csScalerFlags */ enum { kScaleStretchToFitMask = 0x00000001, /* True means the driver should avoid borders and allow non-square pixels */ kScaleRotateFlagsMask = 0x000000f0, kScaleSwapAxesMask = 0x00000010, kScaleInvertXMask = 0x00000020, kScaleInvertYMask = 0x00000040, kScaleRotate0Mask = 0x00000000, kScaleRotate90Mask = kScaleSwapAxesMask | kScaleInvertXMask, kScaleRotate180Mask = kScaleInvertXMask | kScaleInvertYMask, kScaleRotate270Mask = kScaleSwapAxesMask | kScaleInvertYMask }; typedef UInt32 VDClutBehavior; typedef VDClutBehavior * VDClutBehaviorPtr; enum { kSetClutAtSetEntries = 0, /* SetEntries behavior is to update clut during SetEntries call*/ kSetClutAtVBL = 1 /* SetEntries behavior is to upate clut at next vbl*/ }; struct VDCommunicationRec { SInt32 csBusID; /* kVideoDefaultBus for single headed cards.*/ UInt32 csCommFlags; /* Always zero*/ UInt32 csMinReplyDelay; /* Minimum delay between send and reply transactions (units depend on csCommFlags)*/ UInt32 csReserved2; /* Always zero*/ UInt32 csSendAddress; /* Usually I2C address (eg 0x6E)*/ UInt32 csSendType; /* See kVideoSimpleI2CType etc.*/ LogicalAddress csSendBuffer; /* Pointer to the send buffer*/ ByteCount csSendSize; /* Number of bytes to send*/ UInt32 csReplyAddress; /* Address from which to read (eg 0x6F for kVideoDDCciReplyType I2C address)*/ UInt32 csReplyType; /* See kVideoDDCciReplyType etc.*/ LogicalAddress csReplyBuffer; /* Pointer to the reply buffer*/ ByteCount csReplySize; /* Max bytes to reply (size of csReplyBuffer)*/ UInt32 csReserved3; UInt32 csReserved4; UInt32 csReserved5; /* Always zero*/ UInt32 csReserved6; /* Always zero*/ }; typedef struct VDCommunicationRec VDCommunicationRec; typedef VDCommunicationRec * VDCommunicationPtr; struct VDCommunicationInfoRec { SInt32 csBusID; /* kVideoDefaultBus for single headed cards. */ UInt32 csBusType; /* See kVideoBusI2C etc.*/ SInt32 csMinBus; /* Minimum bus (usually kVideoDefaultBus). Used to probe additional busses*/ SInt32 csMaxBus; /* Max bus (usually kVideoDefaultBus). Used to probe additional busses*/ UInt32 csSupportedTypes; /* Bit field for first 32 supported transaction types. Eg. 0x07 => support for kVideoNoTransactionType, kVideoSimpleI2CType and kVideoDDCciReplyType.*/ UInt32 csSupportedCommFlags; /* Return the flags csCommFlags understood by this driver. */ UInt32 csReserved2; /* Always zero*/ UInt32 csReserved3; /* Always zero*/ UInt32 csReserved4; /* Always zero*/ UInt32 csReserved5; /* Always zero*/ UInt32 csReserved6; /* Always zero*/ UInt32 csReserved7; /* Always zero*/ }; typedef struct VDCommunicationInfoRec VDCommunicationInfoRec; typedef VDCommunicationInfoRec * VDCommunicationInfoPtr; struct VDScalerRec { UInt32 csScalerSize; /* Init to sizeof(VDScalerRec) */ UInt32 csScalerVersion; /* Init to 0 */ UInt32 csReserved1; /* Init to 0 */ UInt32 csReserved2; /* Init to 0 */ DisplayModeID csDisplayModeID; /* Display Mode ID modified by this call. */ UInt32 csDisplayModeSeed; /* */ UInt32 csDisplayModeState; /* Display Mode state */ UInt32 csReserved3; /* Init to 0 */ UInt32 csScalerFlags; /* Init to 0 */ UInt32 csHorizontalPixels; /* Graphics system addressable pixels */ UInt32 csVerticalPixels; /* Graphics system addressable lines */ UInt32 csHorizontalInset; /* Border pixels for underscan */ UInt32 csVerticalInset; /* Border lines for underscan */ UInt32 csReserved6; /* Init to 0 */ UInt32 csReserved7; /* Init to 0 */ UInt32 csReserved8; /* Init to 0 */ }; typedef struct VDScalerRec VDScalerRec; typedef VDScalerRec *VDScalerPtr; struct VDScalerInfoRec { UInt32 csScalerInfoSize; /* Init to sizeof(VDScalerInfoRec) */ UInt32 csScalerInfoVersion; /* Init to 0 */ UInt32 csReserved1; /* Init to 0 */ UInt32 csReserved2; /* Init to 0 */ UInt32 csScalerFeatures; /* Feature flags */ UInt32 csMaxHorizontalPixels; /* limit to horizontal scaled pixels */ UInt32 csMaxVerticalPixels; /* limit to vertical scaled pixels */ UInt32 csReserved3; /* Init to 0 */ UInt32 csReserved4; /* Init to 0 */ UInt32 csReserved5; /* Init to 0 */ UInt32 csReserved6; /* Init to 0 */ UInt32 csReserved7; /* Init to 0 */ }; typedef struct VDScalerInfoRec VDScalerInfoRec; typedef VDScalerInfoRec *VDScalerInfoPtr; enum { /* csMirrorFeatures*/ kMirrorSameDepthOnlyMirrorMask = (1 << 0), /* Commonly true - Mirroring can only be done if the displays are the same bitdepth*/ kMirrorSameSizeOnlyMirrorMask = (1 << 1), /* Commonly false - Mirroring can only be done if the displays are the same size*/ kMirrorSameTimingOnlyMirrorMask = (1 << 2), /* Sometimes true - Mirroring can only be done if the displays are the same timing*/ kMirrorCommonGammaMask = (1 << 3) /* Sometimes true - Only one gamma correction LUT.*/ }; enum { /* csMirrorSupportedFlags and csMirrorFlags*/ kMirrorCanMirrorMask = (1 << 0), /* Set means we can HW mirrored right now (uses csMirrorEntryID)*/ kMirrorAreMirroredMask = (1 << 1), /* Set means we are HW mirrored right now (uses csMirrorEntryID)*/ kMirrorUnclippedMirrorMask = (1 << 2), /* Set means mirrored displays are not clipped to their intersection*/ kMirrorHAlignCenterMirrorMask = (1 << 3), /* Set means mirrored displays can/should be centered horizontally*/ kMirrorVAlignCenterMirrorMask = (1 << 4), /* Set means mirrored displays can/should be centered vertically*/ kMirrorCanChangePixelFormatMask = (1 << 5), /* Set means mirrored the device should change the pixel format of mirrored displays to allow mirroring.*/ kMirrorCanChangeTimingMask = (1 << 6), /* Set means mirrored the device should change the timing of mirrored displays to allow mirroring.*/ kMirrorClippedMirrorMask = (1 << 7) /* Set means mirrored displays are clipped to their intersection (driver handles blacking and base address adjustment)*/ }; struct VDMirrorRec { UInt32 csMirrorSize; /* Init to sizeof(VDMirrorRec)*/ UInt32 csMirrorVersion; /* Init to 0*/ RegEntryID csMirrorRequestID; /* Input RegEntryID to check for mirroring support and state*/ RegEntryID csMirrorResultID; /* Output RegEntryID of the next mirrored device*/ UInt32 csMirrorFeatures; /* Output summary features of the driver*/ UInt32 csMirrorSupportedFlags; /* Output configuration options supported by the driver*/ UInt32 csMirrorFlags; /* Output configuration options active now*/ UInt32 csReserved1; /* Init to 0*/ UInt32 csReserved2; /* Init to 0*/ UInt32 csReserved3; /* Init to 0*/ UInt32 csReserved4; /* Init to 0*/ UInt32 csReserved5; /* Init to 0*/ }; typedef struct VDMirrorRec VDMirrorRec; typedef VDMirrorRec * VDMirrorPtr; struct VDConfigurationRec { UInt32 csConfigFeature; /* input what feature to config - always input*/ UInt32 csConfigSupport; /* output support value - always output*/ uintptr_t csConfigValue; /* input/output feature value - input on Control(), output on Status()*/ uintptr_t csReserved1; uintptr_t csReserved2; }; typedef struct VDConfigurationRec VDConfigurationRec; typedef VDConfigurationRec * VDConfigurationPtr; enum { kDVIPowerSwitchFeature = (1 << 0), /* Used for csConfigFeature*/ kDVIPowerSwitchSupportMask = (1 << 0), /* Read-only*/ kDVIPowerSwitchActiveMask = (1 << 0), /* Read/write for csConfigValue*/ }; struct VDConfigurationFeatureListRec { OSType * csConfigFeatureList; ItemCount csNumConfigFeatures; uintptr_t csReserved1; uintptr_t csReserved2; }; typedef struct VDConfigurationFeatureListRec VDConfigurationFeatureListRec; typedef VDConfigurationFeatureListRec * VDConfigurationFeatureListRecPtr; #ifndef __LP64__ #pragma options align=reset #endif #ifdef __cplusplus } #endif #endif /* __IOMACOSVIDEO__ */
0
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework
repos/simulations/libs/system-sdk/macos12/System/Library/Frameworks/IOKit.framework/Modules/module.modulemap
framework module IOKit [extern_c] { header "IOReturn.h" header "IOMapTypes.h" header "IOTypes.h" header "IOKitKeys.h" header "OSMessageNotification.h" header "IOKitLib.h" header "IOBSD.h" header "IODataQueueClient.h" header "IOCFBundle.h" header "IODataQueueShared.h" header "IOSharedLock.h" header "IOCFPlugIn.h" header "IOCFSerialize.h" header "IOCFURLAccess.h" header "IOKitServer.h" header "IOCFUnserialize.h" header "IOMessage.h" header "IORPC.h" header "IOUserServer.h" export * explicit module audio { header "audio/IOAudioDefines.h" header "audio/IOAudioLib.h" header "audio/IOAudioTypes.h" export * } explicit module avc { header "avc/IOFireWireAVCConsts.h" header "avc/IOFireWireAVCLib.h" export * } explicit module firewire { header "firewire/IOFireWireLib.h" header "firewire/IOFireWireFamilyCommon.h" header "firewire/IOFireWireLibIsoch.h" export * module deprecated { requires unavailable header "firewire/IOFWIsoch.h" } } explicit module graphics { header "graphics/IOAccelClientConnect.h" header "graphics/IOGraphicsInterface.h" header "graphics/IOAccelSurfaceConnect.h" header "graphics/IOGraphicsInterfaceTypes.h" header "graphics/IOAccelTypes.h" header "graphics/IOGraphicsLib.h" header "graphics/IOFramebufferShared.h" header "graphics/IOGraphicsTypes.h" header "graphics/IOGraphicsEngine.h" export * } explicit module hid { header "hid/IOHIDBase.h" header "hid/IOHIDKeys.h" header "hid/IOHIDQueue.h" header "hid/IOHIDDevice.h" header "hid/IOHIDLib.h" header "hid/IOHIDTransaction.h" header "hid/IOHIDDevicePlugIn.h" header "hid/IOHIDLibObsolete.h" header "hid/IOHIDUsageTables.h" header "hid/IOHIDElement.h" header "hid/IOHIDManager.h" header "hid/IOHIDValue.h" header "hid/IOHIDDeviceKeys.h" header "hid/IOHIDDeviceTypes.h" header "hid/IOHIDEventServiceKeys.h" header "hid/IOHIDEventServiceTypes.h" header "hid/IOHIDProperties.h" export * } explicit module hidsystem { header "hidsystem/IOHIDLib.h" header "hidsystem/IOHIDTypes.h" header "hidsystem/event_status_driver.h" header "hidsystem/IOHIDParameter.h" header "hidsystem/IOLLEvent.h" header "hidsystem/IOHIDShared.h" header "hidsystem/ev_keymap.h" header "hidsystem/IOHIDEventSystemClient.h" header "hidsystem/IOHIDServiceClient.h" header "hidsystem/IOHIDUserDevice.h" export * } explicit module i2c { header "i2c/IOI2CInterface.h" export * } explicit module kext { header "kext/KextManager.h" export * } /* DPG: this module redefines bits from ApplicationServices.QD, which creates a conflict. explicit module ndrvsupport { header "ndrvsupport/IOMacOSTypes.h" header "ndrvsupport/IOMacOSVideo.h" export * } */ explicit module network { header "network/IOEthernetController.h" header "network/IONetworkData.h" header "network/IONetworkStack.h" header "network/IOEthernetInterface.h" header "network/IONetworkInterface.h" header "network/IONetworkStats.h" header "network/IOEthernetStats.h" header "network/IONetworkLib.h" header "network/IONetworkUserClient.h" header "network/IONetworkController.h" header "network/IONetworkMedium.h" export * } explicit module ps { header "ps/IOPSKeys.h" header "ps/IOPowerSources.h" header "ps/IOUPSPlugIn.h" export * } explicit module pwr_mgt { header "pwr_mgt/IOPM.h" header "pwr_mgt/IOPMKeys.h" header "pwr_mgt/IOPMLib.h" header "pwr_mgt/IOPMLibDefs.h" export * } explicit module sbp2 { header "sbp2/IOFireWireSBP2Lib.h" export * } explicit module scsi { header "scsi/IOSCSIMultimediaCommandsDevice.h" header "scsi/SCSICmds_REQUEST_SENSE_Defs.h" header "scsi/SCSICmds_INQUIRY_Definitions.h" header "scsi/SCSICommandDefinitions.h" header "scsi/SCSICmds_MODE_Definitions.h" header "scsi/SCSICommandOperationCodes.h" header "scsi/SCSICmds_READ_CAPACITY_Definitions.h" header "scsi/SCSITask.h" header "scsi/SCSICmds_REPORT_LUNS_Definitions.h" header "scsi/SCSITaskLib.h" export * } explicit module serial { header "serial/IOSerialKeys.h" header "serial/ioss.h" export * } explicit module storage { header "storage/IOAppleLabelScheme.h" header "storage/IODVDMediaBSDClient.h" header "storage/IOApplePartitionScheme.h" header "storage/IODVDTypes.h" header "storage/IOBDBlockStorageDevice.h" header "storage/IOFDiskPartitionScheme.h" header "storage/IOBDMedia.h" header "storage/IOFilterScheme.h" header "storage/IOBDMediaBSDClient.h" header "storage/IOFireWireStorageCharacteristics.h" header "storage/IOBDTypes.h" header "storage/IOGUIDPartitionScheme.h" header "storage/IOBlockStorageDevice.h" header "storage/IOMedia.h" header "storage/IOBlockStorageDriver.h" header "storage/IOMediaBSDClient.h" header "storage/IOCDBlockStorageDevice.h" header "storage/IOPartitionScheme.h" header "storage/IOCDMedia.h" header "storage/IOStorage.h" header "storage/IOCDMediaBSDClient.h" header "storage/IOStorageCardCharacteristics.h" header "storage/IOCDPartitionScheme.h" header "storage/IOStorageDeviceCharacteristics.h" header "storage/IOCDTypes.h" header "storage/IOStorageControllerCharacteristics.h" header "storage/IOStorageProtocolCharacteristics.h" header "storage/IODVDBlockStorageDevice.h" header "storage/IODVDMedia.h" export * explicit module ata { header "storage/ata/ATASMARTLib.h" header "storage/ata/IOATAStorageDefines.h" export * } } explicit module stream { header "stream/IOStreamLib.h" header "stream/IOStreamShared.h" export * } explicit module usb { umbrella "Headers/usb" export * module * { export * } } explicit module video { // rdar://problem/19486850 requires cplusplus, unavailable header "video/IOVideoControlDictionary.h" header "video/IOVideoDeviceUserClient.h" header "video/IOVideoDevice.h" header "video/IOVideoStream.h" header "video/IOVideoDeviceClientInit.h" header "video/IOVideoStreamDictionary.h" header "video/IOVideoDeviceLib.h" header "video/IOVideoStreamFormatDictionary.h" header "video/IOVideoDeviceShared.h" header "video/IOVideoTypes.h" export * } }
0
repos/simulations/libs
repos/simulations/libs/zstbi/README.md
# zstbi v0.10.0 - stb image bindings ## Features * Supports Zig memory allocators * Supports decoding most popular formats * Supports HDR images * Supports 8-bits and 16-bits per channel * Supports image resizing * Supports image writing (.png, .jpg) ## Getting started Copy `zstbi` to a subdirectory of your project and add the following to your `build.zig.zon` .dependencies: ```zig .zstbi = .{ .path = "libs/zstbi" }, ``` Then in your `build.zig` add: ```zig pub fn build(b: *std.Build) void { const exe = b.addExecutable(.{ ... }); const zstbi = b.dependency("zstbi", .{}); exe.root_module.addImport("zstbi", zstbi.module("root")); exe.linkLibrary(zstbi.artifact("zstbi")); } ``` Now in your code you may import and use `zstbi`. Init the lib. `zstbi.init()` is cheap and you may call it whenever you need to change memory allocator. Must be called from the main thread. ```zig const zstbi = @import("zstbi"); zstbi.init(allocator); defer zstbi.deinit(); ``` ```zig pub const Image = struct { data: []u8, width: u32, height: u32, num_components: u32, bytes_per_component: u32, bytes_per_row: u32, is_hdr: bool, ... ``` ```zig pub fn loadFromFile(pathname: [:0]const u8, forced_num_components: u32) !Image pub fn loadFromMemory(data: []const u8, forced_num_components: u32) !Image pub fn createEmpty(width: u32, height: u32, num_components: u32, args: struct { bytes_per_component: u32 = 0, bytes_per_row: u32 = 0, }) !Image pub fn info(pathname: [:0]const u8) struct { is_supported: bool, width: u32, height: u32, num_components: u32, } pub fn resize(image: *const Image, new_width: u32, new_height: u32) Image pub fn writeToFile( image: *const Image, filename: [:0]const u8, image_format: ImageWriteFormat, ) ImageWriteError!void pub fn writeToFn( image: *const Image, write_fn: *const fn (ctx: ?*anyopaque, data: ?*anyopaque, size: c_int) callconv(.C) void, context: ?*anyopaque, image_format: ImageWriteFormat, ) ImageWriteError!void ``` ```zig var image = try zstbi.Image.loadFromFile("data/image.png", forced_num_components); defer image.deinit(); const new_resized_image = image.resize(1024, 1024); ``` Misc functions: ```zig pub fn isHdr(filename: [:0]const u8) bool pub fn is16bit(filename: [:0]const u8) bool pub fn setFlipVerticallyOnLoad(should_flip: bool) void ```
0
repos/simulations/libs
repos/simulations/libs/zstbi/build.zig.zon
.{ .name = "zstbi", .version = "0.10.0", .paths = .{ "build.zig", "build.zig.zon", "libs", "src", "README.md", }, }
0
repos/simulations/libs
repos/simulations/libs/zstbi/build.zig
const std = @import("std"); pub fn build(b: *std.Build) void { const optimize = b.standardOptimizeOption(.{}); const target = b.standardTargetOptions(.{}); _ = b.addModule("root", .{ .root_source_file = b.path("src/zstbi.zig"), }); const zstbi_lib = b.addStaticLibrary(.{ .name = "zstbi", .target = target, .optimize = optimize, }); zstbi_lib.addIncludePath(b.path("libs/stbi")); if (optimize == .Debug) { // TODO: Workaround for Zig bug. zstbi_lib.addCSourceFile(.{ .file = b.path("src/zstbi.c"), .flags = &.{ "-std=c99", "-fno-sanitize=undefined", "-g", "-O0", }, }); } else { zstbi_lib.addCSourceFile(.{ .file = b.path("src/zstbi.c"), .flags = &.{ "-std=c99", "-fno-sanitize=undefined", }, }); } zstbi_lib.linkLibC(); b.installArtifact(zstbi_lib); const test_step = b.step("test", "Run zstbi tests"); const tests = b.addTest(.{ .name = "zstbi-tests", .root_source_file = b.path("src/zstbi.zig"), .target = target, .optimize = optimize, }); tests.linkLibrary(zstbi_lib); b.installArtifact(tests); test_step.dependOn(&b.addRunArtifact(tests).step); }
0
repos/simulations/libs/zstbi
repos/simulations/libs/zstbi/src/zstbi.c
#include <stdlib.h> void* (*zstbiMallocPtr)(size_t size) = NULL; void* (*zstbiReallocPtr)(void* ptr, size_t size) = NULL; void (*zstbiFreePtr)(void* ptr) = NULL; #define STBI_MALLOC(size) zstbiMallocPtr(size) #define STBI_REALLOC(ptr, size) zstbiReallocPtr(ptr, size) #define STBI_FREE(ptr) zstbiFreePtr(ptr) #define STB_IMAGE_IMPLEMENTATION #include "stb_image.h" void* (*zstbirMallocPtr)(size_t size, void* context) = NULL; void (*zstbirFreePtr)(void* ptr, void* context) = NULL; #define STBIR_MALLOC(size, context) zstbirMallocPtr(size, context) #define STBIR_FREE(ptr, context) zstbirFreePtr(ptr, context) #define STB_IMAGE_RESIZE_IMPLEMENTATION #include "stb_image_resize.h" void* (*zstbiwMallocPtr)(size_t size) = NULL; void* (*zstbiwReallocPtr)(void* ptr, size_t size) = NULL; void (*zstbiwFreePtr)(void* ptr) = NULL; #define STBIW_MALLOC(size) zstbiwMallocPtr(size) #define STBIW_REALLOC(ptr, size) zstbiwReallocPtr(ptr, size) #define STBIW_FREE(ptr) zstbiwFreePtr(ptr) #define STB_IMAGE_WRITE_IMPLEMENTATION #include "stb_image_write.h"
0
repos/simulations/libs/zstbi
repos/simulations/libs/zstbi/src/zstbi.zig
const std = @import("std"); const testing = std.testing; const assert = std.debug.assert; pub fn init(allocator: std.mem.Allocator) void { assert(mem_allocator == null); mem_allocator = allocator; mem_allocations = std.AutoHashMap(usize, usize).init(allocator); // stb image zstbiMallocPtr = zstbiMalloc; zstbiReallocPtr = zstbiRealloc; zstbiFreePtr = zstbiFree; // stb image resize zstbirMallocPtr = zstbirMalloc; zstbirFreePtr = zstbirFree; // stb image write zstbiwMallocPtr = zstbiMalloc; zstbiwReallocPtr = zstbiRealloc; zstbiwFreePtr = zstbiFree; } pub fn deinit() void { assert(mem_allocator != null); assert(mem_allocations.?.count() == 0); setFlipVerticallyOnLoad(false); setFlipVerticallyOnWrite(false); mem_allocations.?.deinit(); mem_allocations = null; mem_allocator = null; } pub const JpgWriteSettings = struct { quality: u32, }; pub const ImageWriteFormat = union(enum) { png, jpg: JpgWriteSettings, }; pub const ImageWriteError = error{ CouldNotWriteImage, }; pub const Image = struct { data: []u8, width: u32, height: u32, num_components: u32, bytes_per_component: u32, bytes_per_row: u32, is_hdr: bool, pub fn info(pathname: [:0]const u8) struct { is_supported: bool, width: u32, height: u32, num_components: u32, } { assert(mem_allocator != null); var w: c_int = 0; var h: c_int = 0; var c: c_int = 0; const is_supported = stbi_info(pathname, &w, &h, &c); return .{ .is_supported = if (is_supported == 1) true else false, .width = @as(u32, @intCast(w)), .height = @as(u32, @intCast(h)), .num_components = @as(u32, @intCast(c)), }; } pub fn loadFromFile(pathname: [:0]const u8, forced_num_components: u32) !Image { assert(mem_allocator != null); var width: u32 = 0; var height: u32 = 0; var num_components: u32 = 0; var bytes_per_component: u32 = 0; var bytes_per_row: u32 = 0; var is_hdr = false; const data = if (isHdr(pathname)) data: { var x: c_int = undefined; var y: c_int = undefined; var ch: c_int = undefined; const ptr = stbi_loadf( pathname, &x, &y, &ch, @as(c_int, @intCast(forced_num_components)), ); if (ptr == null) return error.ImageInitFailed; num_components = if (forced_num_components == 0) @as(u32, @intCast(ch)) else forced_num_components; width = @as(u32, @intCast(x)); height = @as(u32, @intCast(y)); bytes_per_component = 2; bytes_per_row = width * num_components * bytes_per_component; is_hdr = true; // Convert each component from f32 to f16. var ptr_f16 = @as([*]f16, @ptrCast(ptr.?)); const num = width * height * num_components; var i: u32 = 0; while (i < num) : (i += 1) { ptr_f16[i] = @as(f16, @floatCast(ptr.?[i])); } break :data @as([*]u8, @ptrCast(ptr_f16))[0 .. height * bytes_per_row]; } else data: { var x: c_int = undefined; var y: c_int = undefined; var ch: c_int = undefined; const is_16bit = is16bit(pathname); const ptr = if (is_16bit) @as(?[*]u8, @ptrCast(stbi_load_16( pathname, &x, &y, &ch, @as(c_int, @intCast(forced_num_components)), ))) else stbi_load( pathname, &x, &y, &ch, @as(c_int, @intCast(forced_num_components)), ); if (ptr == null) return error.ImageInitFailed; num_components = if (forced_num_components == 0) @as(u32, @intCast(ch)) else forced_num_components; width = @as(u32, @intCast(x)); height = @as(u32, @intCast(y)); bytes_per_component = if (is_16bit) 2 else 1; bytes_per_row = width * num_components * bytes_per_component; is_hdr = false; break :data @as([*]u8, @ptrCast(ptr))[0 .. height * bytes_per_row]; }; return Image{ .data = data, .width = width, .height = height, .num_components = num_components, .bytes_per_component = bytes_per_component, .bytes_per_row = bytes_per_row, .is_hdr = is_hdr, }; } pub fn loadFromMemory(data: []const u8, forced_num_components: u32) !Image { assert(mem_allocator != null); var width: u32 = 0; var height: u32 = 0; var num_components: u32 = 0; var bytes_per_component: u32 = 0; var bytes_per_row: u32 = 0; var is_hdr = false; const image_data = if (isHdrFromMem(data)) data: { var x: c_int = undefined; var y: c_int = undefined; var ch: c_int = undefined; const ptr = stbi_loadf_from_memory( data.ptr, @as(c_int, @intCast(data.len)), &x, &y, &ch, @as(c_int, @intCast(forced_num_components)), ); if (ptr == null) return error.ImageInitFailed; num_components = if (forced_num_components == 0) @as(u32, @intCast(ch)) else forced_num_components; width = @as(u32, @intCast(x)); height = @as(u32, @intCast(y)); bytes_per_component = 2; bytes_per_row = width * num_components * bytes_per_component; is_hdr = true; // Convert each component from f32 to f16. var ptr_f16 = @as([*]f16, @ptrCast(ptr.?)); const num = width * height * num_components; var i: u32 = 0; while (i < num) : (i += 1) { ptr_f16[i] = @as(f16, @floatCast(ptr.?[i])); } break :data @as([*]u8, @ptrCast(ptr_f16))[0 .. height * bytes_per_row]; } else data: { var x: c_int = undefined; var y: c_int = undefined; var ch: c_int = undefined; const ptr = stbi_load_from_memory( data.ptr, @as(c_int, @intCast(data.len)), &x, &y, &ch, @as(c_int, @intCast(forced_num_components)), ); if (ptr == null) return error.ImageInitFailed; num_components = if (forced_num_components == 0) @as(u32, @intCast(ch)) else forced_num_components; width = @as(u32, @intCast(x)); height = @as(u32, @intCast(y)); bytes_per_component = 1; bytes_per_row = width * num_components * bytes_per_component; break :data @as([*]u8, @ptrCast(ptr))[0 .. height * bytes_per_row]; }; return Image{ .data = image_data, .width = width, .height = height, .num_components = num_components, .bytes_per_component = bytes_per_component, .bytes_per_row = bytes_per_row, .is_hdr = is_hdr, }; } pub fn createEmpty(width: u32, height: u32, num_components: u32, args: struct { bytes_per_component: u32 = 0, bytes_per_row: u32 = 0, }) !Image { assert(mem_allocator != null); const bytes_per_component = if (args.bytes_per_component == 0) 1 else args.bytes_per_component; const bytes_per_row = if (args.bytes_per_row == 0) width * num_components * bytes_per_component else args.bytes_per_row; const size = height * bytes_per_row; const data = @as([*]u8, @ptrCast(zstbiMalloc(size))); @memset(data[0..size], 0); return Image{ .data = data[0..size], .width = width, .height = height, .num_components = num_components, .bytes_per_component = bytes_per_component, .bytes_per_row = bytes_per_row, .is_hdr = false, }; } pub fn resize(image: *const Image, new_width: u32, new_height: u32) Image { assert(mem_allocator != null); // TODO: Add support for HDR images const new_bytes_per_row = new_width * image.num_components * image.bytes_per_component; const new_size = new_height * new_bytes_per_row; const new_data = @as([*]u8, @ptrCast(zstbiMalloc(new_size))); stbir_resize_uint8( image.data.ptr, @as(c_int, @intCast(image.width)), @as(c_int, @intCast(image.height)), 0, new_data, @as(c_int, @intCast(new_width)), @as(c_int, @intCast(new_height)), 0, @as(c_int, @intCast(image.num_components)), ); return .{ .data = new_data[0..new_size], .width = new_width, .height = new_height, .num_components = image.num_components, .bytes_per_component = image.bytes_per_component, .bytes_per_row = new_bytes_per_row, .is_hdr = image.is_hdr, }; } pub fn writeToFile( image: Image, filename: [:0]const u8, image_format: ImageWriteFormat, ) ImageWriteError!void { assert(mem_allocator != null); const w = @as(c_int, @intCast(image.width)); const h = @as(c_int, @intCast(image.height)); const comp = @as(c_int, @intCast(image.num_components)); const result = switch (image_format) { .png => stbi_write_png(filename.ptr, w, h, comp, image.data.ptr, 0), .jpg => |settings| stbi_write_jpg( filename.ptr, w, h, comp, image.data.ptr, @as(c_int, @intCast(settings.quality)), ), }; // if the result is 0 then it means an error occured (per stb image write docs) if (result == 0) { return ImageWriteError.CouldNotWriteImage; } } pub fn writeToFn( image: Image, write_fn: *const fn (ctx: ?*anyopaque, data: ?*anyopaque, size: c_int) callconv(.C) void, context: ?*anyopaque, image_format: ImageWriteFormat, ) ImageWriteError!void { assert(mem_allocator != null); const w = @as(c_int, @intCast(image.width)); const h = @as(c_int, @intCast(image.height)); const comp = @as(c_int, @intCast(image.num_components)); const result = switch (image_format) { .png => stbi_write_png_to_func(write_fn, context, w, h, comp, image.data.ptr, 0), .jpg => |settings| stbi_write_jpg_to_func( write_fn, context, w, h, comp, image.data.ptr, @as(c_int, @intCast(settings.quality)), ), }; // if the result is 0 then it means an error occured (per stb image write docs) if (result == 0) { return ImageWriteError.CouldNotWriteImage; } } pub fn deinit(image: *Image) void { stbi_image_free(image.data.ptr); image.* = undefined; } }; /// `pub fn setHdrToLdrScale(scale: f32) void` pub const setHdrToLdrScale = stbi_hdr_to_ldr_scale; /// `pub fn setHdrToLdrGamma(gamma: f32) void` pub const setHdrToLdrGamma = stbi_hdr_to_ldr_gamma; /// `pub fn setLdrToHdrScale(scale: f32) void` pub const setLdrToHdrScale = stbi_ldr_to_hdr_scale; /// `pub fn setLdrToHdrGamma(gamma: f32) void` pub const setLdrToHdrGamma = stbi_ldr_to_hdr_gamma; pub fn isHdr(filename: [:0]const u8) bool { return stbi_is_hdr(filename) != 0; } pub fn isHdrFromMem(buffer: []const u8) bool { return stbi_is_hdr_from_memory(buffer.ptr, @as(c_int, @intCast(buffer.len))) != 0; } pub fn is16bit(filename: [:0]const u8) bool { return stbi_is_16_bit(filename) != 0; } pub fn setFlipVerticallyOnLoad(should_flip: bool) void { stbi_set_flip_vertically_on_load(if (should_flip) 1 else 0); } pub fn setFlipVerticallyOnWrite(should_flip: bool) void { stbi_flip_vertically_on_write(if (should_flip) 1 else 0); } var mem_allocator: ?std.mem.Allocator = null; var mem_allocations: ?std.AutoHashMap(usize, usize) = null; var mem_mutex: std.Thread.Mutex = .{}; const mem_alignment = 16; extern var zstbiMallocPtr: ?*const fn (size: usize) callconv(.C) ?*anyopaque; extern var zstbiwMallocPtr: ?*const fn (size: usize) callconv(.C) ?*anyopaque; fn zstbiMalloc(size: usize) callconv(.C) ?*anyopaque { mem_mutex.lock(); defer mem_mutex.unlock(); const mem = mem_allocator.?.alignedAlloc( u8, mem_alignment, size, ) catch @panic("zstbi: out of memory"); mem_allocations.?.put(@intFromPtr(mem.ptr), size) catch @panic("zstbi: out of memory"); return mem.ptr; } extern var zstbiReallocPtr: ?*const fn (ptr: ?*anyopaque, size: usize) callconv(.C) ?*anyopaque; extern var zstbiwReallocPtr: ?*const fn (ptr: ?*anyopaque, size: usize) callconv(.C) ?*anyopaque; fn zstbiRealloc(ptr: ?*anyopaque, size: usize) callconv(.C) ?*anyopaque { mem_mutex.lock(); defer mem_mutex.unlock(); const old_size = if (ptr != null) mem_allocations.?.get(@intFromPtr(ptr.?)).? else 0; const old_mem = if (old_size > 0) @as([*]align(mem_alignment) u8, @ptrCast(@alignCast(ptr)))[0..old_size] else @as([*]align(mem_alignment) u8, undefined)[0..0]; const new_mem = mem_allocator.?.realloc(old_mem, size) catch @panic("zstbi: out of memory"); if (ptr != null) { const removed = mem_allocations.?.remove(@intFromPtr(ptr.?)); std.debug.assert(removed); } mem_allocations.?.put(@intFromPtr(new_mem.ptr), size) catch @panic("zstbi: out of memory"); return new_mem.ptr; } extern var zstbiFreePtr: ?*const fn (maybe_ptr: ?*anyopaque) callconv(.C) void; extern var zstbiwFreePtr: ?*const fn (maybe_ptr: ?*anyopaque) callconv(.C) void; fn zstbiFree(maybe_ptr: ?*anyopaque) callconv(.C) void { if (maybe_ptr) |ptr| { mem_mutex.lock(); defer mem_mutex.unlock(); const size = mem_allocations.?.fetchRemove(@intFromPtr(ptr)).?.value; const mem = @as([*]align(mem_alignment) u8, @ptrCast(@alignCast(ptr)))[0..size]; mem_allocator.?.free(mem); } } extern var zstbirMallocPtr: ?*const fn (size: usize, maybe_context: ?*anyopaque) callconv(.C) ?*anyopaque; fn zstbirMalloc(size: usize, _: ?*anyopaque) callconv(.C) ?*anyopaque { return zstbiMalloc(size); } extern var zstbirFreePtr: ?*const fn (maybe_ptr: ?*anyopaque, maybe_context: ?*anyopaque) callconv(.C) void; fn zstbirFree(maybe_ptr: ?*anyopaque, _: ?*anyopaque) callconv(.C) void { zstbiFree(maybe_ptr); } extern fn stbi_info(filename: [*:0]const u8, x: *c_int, y: *c_int, comp: *c_int) c_int; extern fn stbi_load( filename: [*:0]const u8, x: *c_int, y: *c_int, channels_in_file: *c_int, desired_channels: c_int, ) ?[*]u8; extern fn stbi_load_16( filename: [*:0]const u8, x: *c_int, y: *c_int, channels_in_file: *c_int, desired_channels: c_int, ) ?[*]u16; extern fn stbi_loadf( filename: [*:0]const u8, x: *c_int, y: *c_int, channels_in_file: *c_int, desired_channels: c_int, ) ?[*]f32; pub extern fn stbi_load_from_memory( buffer: [*]const u8, len: c_int, x: *c_int, y: *c_int, channels_in_file: *c_int, desired_channels: c_int, ) ?[*]u8; pub extern fn stbi_loadf_from_memory( buffer: [*]const u8, len: c_int, x: *c_int, y: *c_int, channels_in_file: *c_int, desired_channels: c_int, ) ?[*]f32; extern fn stbi_image_free(image_data: ?[*]u8) void; extern fn stbi_hdr_to_ldr_scale(scale: f32) void; extern fn stbi_hdr_to_ldr_gamma(gamma: f32) void; extern fn stbi_ldr_to_hdr_scale(scale: f32) void; extern fn stbi_ldr_to_hdr_gamma(gamma: f32) void; extern fn stbi_is_16_bit(filename: [*:0]const u8) c_int; extern fn stbi_is_hdr(filename: [*:0]const u8) c_int; extern fn stbi_is_hdr_from_memory(buffer: [*]const u8, len: c_int) c_int; extern fn stbi_set_flip_vertically_on_load(flag_true_if_should_flip: c_int) void; extern fn stbi_flip_vertically_on_write(flag: c_int) void; // flag is non-zero to flip data vertically extern fn stbir_resize_uint8( input_pixels: [*]const u8, input_w: c_int, input_h: c_int, input_stride_in_bytes: c_int, output_pixels: [*]u8, output_w: c_int, output_h: c_int, output_stride_in_bytes: c_int, num_channels: c_int, ) void; extern fn stbi_write_jpg( filename: [*:0]const u8, w: c_int, h: c_int, comp: c_int, data: [*]const u8, quality: c_int, ) c_int; extern fn stbi_write_png( filename: [*:0]const u8, w: c_int, h: c_int, comp: c_int, data: [*]const u8, stride_in_bytes: c_int, ) c_int; extern fn stbi_write_png_to_func( func: *const fn (?*anyopaque, ?*anyopaque, c_int) callconv(.C) void, context: ?*anyopaque, w: c_int, h: c_int, comp: c_int, data: [*]const u8, stride_in_bytes: c_int, ) c_int; extern fn stbi_write_jpg_to_func( func: *const fn (?*anyopaque, ?*anyopaque, c_int) callconv(.C) void, context: ?*anyopaque, x: c_int, y: c_int, comp: c_int, data: [*]const u8, quality: c_int, ) c_int; test "zstbi basic" { init(testing.allocator); defer deinit(); var im1 = try Image.createEmpty(8, 6, 4, .{}); defer im1.deinit(); try testing.expect(im1.width == 8); try testing.expect(im1.height == 6); try testing.expect(im1.num_components == 4); } test "zstbi resize" { init(testing.allocator); defer deinit(); var im1 = try Image.createEmpty(32, 32, 4, .{}); defer im1.deinit(); var im2 = im1.resize(8, 6); defer im2.deinit(); try testing.expect(im2.width == 8); try testing.expect(im2.height == 6); try testing.expect(im2.num_components == 4); } test "zstbi write and load file" { init(testing.allocator); defer deinit(); const pth = try std.fs.selfExeDirPathAlloc(testing.allocator); defer testing.allocator.free(pth); try std.posix.chdir(pth); var img = try Image.createEmpty(8, 6, 4, .{}); defer img.deinit(); try img.writeToFile("test_img.png", ImageWriteFormat.png); try img.writeToFile("test_img.jpg", .{ .jpg = .{ .quality = 80 } }); var img_png = try Image.loadFromFile("test_img.png", 0); defer img_png.deinit(); try testing.expect(img_png.width == img.width); try testing.expect(img_png.height == img.height); try testing.expect(img_png.num_components == img.num_components); var img_jpg = try Image.loadFromFile("test_img.jpg", 0); defer img_jpg.deinit(); try testing.expect(img_jpg.width == img.width); try testing.expect(img_jpg.height == img.height); try testing.expect(img_jpg.num_components == 3); // RGB JPEG try std.fs.cwd().deleteFile("test_img.png"); try std.fs.cwd().deleteFile("test_img.jpg"); }
0
repos/simulations/libs/zstbi/libs
repos/simulations/libs/zstbi/libs/stbi/stb_image_resize.h
/* stb_image_resize - v0.97 - public domain image resizing by Jorge L Rodriguez (@VinoBS) - 2014 http://github.com/nothings/stb Written with emphasis on usability, portability, and efficiency. (No SIMD or threads, so it be easily outperformed by libs that use those.) Only scaling and translation is supported, no rotations or shears. Easy API downsamples w/Mitchell filter, upsamples w/cubic interpolation. COMPILING & LINKING In one C/C++ file that #includes this file, do this: #define STB_IMAGE_RESIZE_IMPLEMENTATION before the #include. That will create the implementation in that file. QUICKSTART stbir_resize_uint8( input_pixels , in_w , in_h , 0, output_pixels, out_w, out_h, 0, num_channels) stbir_resize_float(...) stbir_resize_uint8_srgb( input_pixels , in_w , in_h , 0, output_pixels, out_w, out_h, 0, num_channels , alpha_chan , 0) stbir_resize_uint8_srgb_edgemode( input_pixels , in_w , in_h , 0, output_pixels, out_w, out_h, 0, num_channels , alpha_chan , 0, STBIR_EDGE_CLAMP) // WRAP/REFLECT/ZERO FULL API See the "header file" section of the source for API documentation. ADDITIONAL DOCUMENTATION SRGB & FLOATING POINT REPRESENTATION The sRGB functions presume IEEE floating point. If you do not have IEEE floating point, define STBIR_NON_IEEE_FLOAT. This will use a slower implementation. MEMORY ALLOCATION The resize functions here perform a single memory allocation using malloc. To control the memory allocation, before the #include that triggers the implementation, do: #define STBIR_MALLOC(size,context) ... #define STBIR_FREE(ptr,context) ... Each resize function makes exactly one call to malloc/free, so to use temp memory, store the temp memory in the context and return that. ASSERT Define STBIR_ASSERT(boolval) to override assert() and not use assert.h OPTIMIZATION Define STBIR_SATURATE_INT to compute clamp values in-range using integer operations instead of float operations. This may be faster on some platforms. DEFAULT FILTERS For functions which don't provide explicit control over what filters to use, you can change the compile-time defaults with #define STBIR_DEFAULT_FILTER_UPSAMPLE STBIR_FILTER_something #define STBIR_DEFAULT_FILTER_DOWNSAMPLE STBIR_FILTER_something See stbir_filter in the header-file section for the list of filters. NEW FILTERS A number of 1D filter kernels are used. For a list of supported filters see the stbir_filter enum. To add a new filter, write a filter function and add it to stbir__filter_info_table. PROGRESS For interactive use with slow resize operations, you can install a progress-report callback: #define STBIR_PROGRESS_REPORT(val) some_func(val) The parameter val is a float which goes from 0 to 1 as progress is made. For example: static void my_progress_report(float progress); #define STBIR_PROGRESS_REPORT(val) my_progress_report(val) #define STB_IMAGE_RESIZE_IMPLEMENTATION #include "stb_image_resize.h" static void my_progress_report(float progress) { printf("Progress: %f%%\n", progress*100); } MAX CHANNELS If your image has more than 64 channels, define STBIR_MAX_CHANNELS to the max you'll have. ALPHA CHANNEL Most of the resizing functions provide the ability to control how the alpha channel of an image is processed. The important things to know about this: 1. The best mathematically-behaved version of alpha to use is called "premultiplied alpha", in which the other color channels have had the alpha value multiplied in. If you use premultiplied alpha, linear filtering (such as image resampling done by this library, or performed in texture units on GPUs) does the "right thing". While premultiplied alpha is standard in the movie CGI industry, it is still uncommon in the videogame/real-time world. If you linearly filter non-premultiplied alpha, strange effects occur. (For example, the 50/50 average of 99% transparent bright green and 1% transparent black produces 50% transparent dark green when non-premultiplied, whereas premultiplied it produces 50% transparent near-black. The former introduces green energy that doesn't exist in the source image.) 2. Artists should not edit premultiplied-alpha images; artists want non-premultiplied alpha images. Thus, art tools generally output non-premultiplied alpha images. 3. You will get best results in most cases by converting images to premultiplied alpha before processing them mathematically. 4. If you pass the flag STBIR_FLAG_ALPHA_PREMULTIPLIED, the resizer does not do anything special for the alpha channel; it is resampled identically to other channels. This produces the correct results for premultiplied-alpha images, but produces less-than-ideal results for non-premultiplied-alpha images. 5. If you do not pass the flag STBIR_FLAG_ALPHA_PREMULTIPLIED, then the resizer weights the contribution of input pixels based on their alpha values, or, equivalently, it multiplies the alpha value into the color channels, resamples, then divides by the resultant alpha value. Input pixels which have alpha=0 do not contribute at all to output pixels unless _all_ of the input pixels affecting that output pixel have alpha=0, in which case the result for that pixel is the same as it would be without STBIR_FLAG_ALPHA_PREMULTIPLIED. However, this is only true for input images in integer formats. For input images in float format, input pixels with alpha=0 have no effect, and output pixels which have alpha=0 will be 0 in all channels. (For float images, you can manually achieve the same result by adding a tiny epsilon value to the alpha channel of every image, and then subtracting or clamping it at the end.) 6. You can suppress the behavior described in #5 and make all-0-alpha pixels have 0 in all channels by #defining STBIR_NO_ALPHA_EPSILON. 7. You can separately control whether the alpha channel is interpreted as linear or affected by the colorspace. By default it is linear; you almost never want to apply the colorspace. (For example, graphics hardware does not apply sRGB conversion to the alpha channel.) CONTRIBUTORS Jorge L Rodriguez: Implementation Sean Barrett: API design, optimizations Aras Pranckevicius: bugfix Nathan Reed: warning fixes REVISIONS 0.97 (2020-02-02) fixed warning 0.96 (2019-03-04) fixed warnings 0.95 (2017-07-23) fixed warnings 0.94 (2017-03-18) fixed warnings 0.93 (2017-03-03) fixed bug with certain combinations of heights 0.92 (2017-01-02) fix integer overflow on large (>2GB) images 0.91 (2016-04-02) fix warnings; fix handling of subpixel regions 0.90 (2014-09-17) first released version LICENSE See end of file for license information. TODO Don't decode all of the image data when only processing a partial tile Don't use full-width decode buffers when only processing a partial tile When processing wide images, break processing into tiles so data fits in L1 cache Installable filters? Resize that respects alpha test coverage (Reference code: FloatImage::alphaTestCoverage and FloatImage::scaleAlphaToCoverage: https://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvimage/FloatImage.cpp ) */ #ifndef STBIR_INCLUDE_STB_IMAGE_RESIZE_H #define STBIR_INCLUDE_STB_IMAGE_RESIZE_H #ifdef _MSC_VER typedef unsigned char stbir_uint8; typedef unsigned short stbir_uint16; typedef unsigned int stbir_uint32; #else #include <stdint.h> typedef uint8_t stbir_uint8; typedef uint16_t stbir_uint16; typedef uint32_t stbir_uint32; #endif #ifndef STBIRDEF #ifdef STB_IMAGE_RESIZE_STATIC #define STBIRDEF static #else #ifdef __cplusplus #define STBIRDEF extern "C" #else #define STBIRDEF extern #endif #endif #endif ////////////////////////////////////////////////////////////////////////////// // // Easy-to-use API: // // * "input pixels" points to an array of image data with 'num_channels' channels (e.g. RGB=3, RGBA=4) // * input_w is input image width (x-axis), input_h is input image height (y-axis) // * stride is the offset between successive rows of image data in memory, in bytes. you can // specify 0 to mean packed continuously in memory // * alpha channel is treated identically to other channels. // * colorspace is linear or sRGB as specified by function name // * returned result is 1 for success or 0 in case of an error. // #define STBIR_ASSERT() to trigger an assert on parameter validation errors. // * Memory required grows approximately linearly with input and output size, but with // discontinuities at input_w == output_w and input_h == output_h. // * These functions use a "default" resampling filter defined at compile time. To change the filter, // you can change the compile-time defaults by #defining STBIR_DEFAULT_FILTER_UPSAMPLE // and STBIR_DEFAULT_FILTER_DOWNSAMPLE, or you can use the medium-complexity API. STBIRDEF int stbir_resize_uint8( const unsigned char *input_pixels , int input_w , int input_h , int input_stride_in_bytes, unsigned char *output_pixels, int output_w, int output_h, int output_stride_in_bytes, int num_channels); STBIRDEF int stbir_resize_float( const float *input_pixels , int input_w , int input_h , int input_stride_in_bytes, float *output_pixels, int output_w, int output_h, int output_stride_in_bytes, int num_channels); // The following functions interpret image data as gamma-corrected sRGB. // Specify STBIR_ALPHA_CHANNEL_NONE if you have no alpha channel, // or otherwise provide the index of the alpha channel. Flags value // of 0 will probably do the right thing if you're not sure what // the flags mean. #define STBIR_ALPHA_CHANNEL_NONE -1 // Set this flag if your texture has premultiplied alpha. Otherwise, stbir will // use alpha-weighted resampling (effectively premultiplying, resampling, // then unpremultiplying). #define STBIR_FLAG_ALPHA_PREMULTIPLIED (1 << 0) // The specified alpha channel should be handled as gamma-corrected value even // when doing sRGB operations. #define STBIR_FLAG_ALPHA_USES_COLORSPACE (1 << 1) STBIRDEF int stbir_resize_uint8_srgb(const unsigned char *input_pixels , int input_w , int input_h , int input_stride_in_bytes, unsigned char *output_pixels, int output_w, int output_h, int output_stride_in_bytes, int num_channels, int alpha_channel, int flags); typedef enum { STBIR_EDGE_CLAMP = 1, STBIR_EDGE_REFLECT = 2, STBIR_EDGE_WRAP = 3, STBIR_EDGE_ZERO = 4, } stbir_edge; // This function adds the ability to specify how requests to sample off the edge of the image are handled. STBIRDEF int stbir_resize_uint8_srgb_edgemode(const unsigned char *input_pixels , int input_w , int input_h , int input_stride_in_bytes, unsigned char *output_pixels, int output_w, int output_h, int output_stride_in_bytes, int num_channels, int alpha_channel, int flags, stbir_edge edge_wrap_mode); ////////////////////////////////////////////////////////////////////////////// // // Medium-complexity API // // This extends the easy-to-use API as follows: // // * Alpha-channel can be processed separately // * If alpha_channel is not STBIR_ALPHA_CHANNEL_NONE // * Alpha channel will not be gamma corrected (unless flags&STBIR_FLAG_GAMMA_CORRECT) // * Filters will be weighted by alpha channel (unless flags&STBIR_FLAG_ALPHA_PREMULTIPLIED) // * Filter can be selected explicitly // * uint16 image type // * sRGB colorspace available for all types // * context parameter for passing to STBIR_MALLOC typedef enum { STBIR_FILTER_DEFAULT = 0, // use same filter type that easy-to-use API chooses STBIR_FILTER_BOX = 1, // A trapezoid w/1-pixel wide ramps, same result as box for integer scale ratios STBIR_FILTER_TRIANGLE = 2, // On upsampling, produces same results as bilinear texture filtering STBIR_FILTER_CUBICBSPLINE = 3, // The cubic b-spline (aka Mitchell-Netrevalli with B=1,C=0), gaussian-esque STBIR_FILTER_CATMULLROM = 4, // An interpolating cubic spline STBIR_FILTER_MITCHELL = 5, // Mitchell-Netrevalli filter with B=1/3, C=1/3 } stbir_filter; typedef enum { STBIR_COLORSPACE_LINEAR, STBIR_COLORSPACE_SRGB, STBIR_MAX_COLORSPACES, } stbir_colorspace; // The following functions are all identical except for the type of the image data STBIRDEF int stbir_resize_uint8_generic( const unsigned char *input_pixels , int input_w , int input_h , int input_stride_in_bytes, unsigned char *output_pixels, int output_w, int output_h, int output_stride_in_bytes, int num_channels, int alpha_channel, int flags, stbir_edge edge_wrap_mode, stbir_filter filter, stbir_colorspace space, void *alloc_context); STBIRDEF int stbir_resize_uint16_generic(const stbir_uint16 *input_pixels , int input_w , int input_h , int input_stride_in_bytes, stbir_uint16 *output_pixels , int output_w, int output_h, int output_stride_in_bytes, int num_channels, int alpha_channel, int flags, stbir_edge edge_wrap_mode, stbir_filter filter, stbir_colorspace space, void *alloc_context); STBIRDEF int stbir_resize_float_generic( const float *input_pixels , int input_w , int input_h , int input_stride_in_bytes, float *output_pixels , int output_w, int output_h, int output_stride_in_bytes, int num_channels, int alpha_channel, int flags, stbir_edge edge_wrap_mode, stbir_filter filter, stbir_colorspace space, void *alloc_context); ////////////////////////////////////////////////////////////////////////////// // // Full-complexity API // // This extends the medium API as follows: // // * uint32 image type // * not typesafe // * separate filter types for each axis // * separate edge modes for each axis // * can specify scale explicitly for subpixel correctness // * can specify image source tile using texture coordinates typedef enum { STBIR_TYPE_UINT8 , STBIR_TYPE_UINT16, STBIR_TYPE_UINT32, STBIR_TYPE_FLOAT , STBIR_MAX_TYPES } stbir_datatype; STBIRDEF int stbir_resize( const void *input_pixels , int input_w , int input_h , int input_stride_in_bytes, void *output_pixels, int output_w, int output_h, int output_stride_in_bytes, stbir_datatype datatype, int num_channels, int alpha_channel, int flags, stbir_edge edge_mode_horizontal, stbir_edge edge_mode_vertical, stbir_filter filter_horizontal, stbir_filter filter_vertical, stbir_colorspace space, void *alloc_context); STBIRDEF int stbir_resize_subpixel(const void *input_pixels , int input_w , int input_h , int input_stride_in_bytes, void *output_pixels, int output_w, int output_h, int output_stride_in_bytes, stbir_datatype datatype, int num_channels, int alpha_channel, int flags, stbir_edge edge_mode_horizontal, stbir_edge edge_mode_vertical, stbir_filter filter_horizontal, stbir_filter filter_vertical, stbir_colorspace space, void *alloc_context, float x_scale, float y_scale, float x_offset, float y_offset); STBIRDEF int stbir_resize_region( const void *input_pixels , int input_w , int input_h , int input_stride_in_bytes, void *output_pixels, int output_w, int output_h, int output_stride_in_bytes, stbir_datatype datatype, int num_channels, int alpha_channel, int flags, stbir_edge edge_mode_horizontal, stbir_edge edge_mode_vertical, stbir_filter filter_horizontal, stbir_filter filter_vertical, stbir_colorspace space, void *alloc_context, float s0, float t0, float s1, float t1); // (s0, t0) & (s1, t1) are the top-left and bottom right corner (uv addressing style: [0, 1]x[0, 1]) of a region of the input image to use. // // //// end header file ///////////////////////////////////////////////////// #endif // STBIR_INCLUDE_STB_IMAGE_RESIZE_H #ifdef STB_IMAGE_RESIZE_IMPLEMENTATION #ifndef STBIR_ASSERT #include <assert.h> #define STBIR_ASSERT(x) assert(x) #endif // For memset #include <string.h> #include <math.h> #ifndef STBIR_MALLOC #include <stdlib.h> // use comma operator to evaluate c, to avoid "unused parameter" warnings #define STBIR_MALLOC(size,c) ((void)(c), malloc(size)) #define STBIR_FREE(ptr,c) ((void)(c), free(ptr)) #endif #ifndef _MSC_VER #ifdef __cplusplus #define stbir__inline inline #else #define stbir__inline #endif #else #define stbir__inline __forceinline #endif // should produce compiler error if size is wrong typedef unsigned char stbir__validate_uint32[sizeof(stbir_uint32) == 4 ? 1 : -1]; #ifdef _MSC_VER #define STBIR__NOTUSED(v) (void)(v) #else #define STBIR__NOTUSED(v) (void)sizeof(v) #endif #define STBIR__ARRAY_SIZE(a) (sizeof((a))/sizeof((a)[0])) #ifndef STBIR_DEFAULT_FILTER_UPSAMPLE #define STBIR_DEFAULT_FILTER_UPSAMPLE STBIR_FILTER_CATMULLROM #endif #ifndef STBIR_DEFAULT_FILTER_DOWNSAMPLE #define STBIR_DEFAULT_FILTER_DOWNSAMPLE STBIR_FILTER_MITCHELL #endif #ifndef STBIR_PROGRESS_REPORT #define STBIR_PROGRESS_REPORT(float_0_to_1) #endif #ifndef STBIR_MAX_CHANNELS #define STBIR_MAX_CHANNELS 64 #endif #if STBIR_MAX_CHANNELS > 65536 #error "Too many channels; STBIR_MAX_CHANNELS must be no more than 65536." // because we store the indices in 16-bit variables #endif // This value is added to alpha just before premultiplication to avoid // zeroing out color values. It is equivalent to 2^-80. If you don't want // that behavior (it may interfere if you have floating point images with // very small alpha values) then you can define STBIR_NO_ALPHA_EPSILON to // disable it. #ifndef STBIR_ALPHA_EPSILON #define STBIR_ALPHA_EPSILON ((float)1 / (1 << 20) / (1 << 20) / (1 << 20) / (1 << 20)) #endif #ifdef _MSC_VER #define STBIR__UNUSED_PARAM(v) (void)(v) #else #define STBIR__UNUSED_PARAM(v) (void)sizeof(v) #endif // must match stbir_datatype static unsigned char stbir__type_size[] = { 1, // STBIR_TYPE_UINT8 2, // STBIR_TYPE_UINT16 4, // STBIR_TYPE_UINT32 4, // STBIR_TYPE_FLOAT }; // Kernel function centered at 0 typedef float (stbir__kernel_fn)(float x, float scale); typedef float (stbir__support_fn)(float scale); typedef struct { stbir__kernel_fn* kernel; stbir__support_fn* support; } stbir__filter_info; // When upsampling, the contributors are which source pixels contribute. // When downsampling, the contributors are which destination pixels are contributed to. typedef struct { int n0; // First contributing pixel int n1; // Last contributing pixel } stbir__contributors; typedef struct { const void* input_data; int input_w; int input_h; int input_stride_bytes; void* output_data; int output_w; int output_h; int output_stride_bytes; float s0, t0, s1, t1; float horizontal_shift; // Units: output pixels float vertical_shift; // Units: output pixels float horizontal_scale; float vertical_scale; int channels; int alpha_channel; stbir_uint32 flags; stbir_datatype type; stbir_filter horizontal_filter; stbir_filter vertical_filter; stbir_edge edge_horizontal; stbir_edge edge_vertical; stbir_colorspace colorspace; stbir__contributors* horizontal_contributors; float* horizontal_coefficients; stbir__contributors* vertical_contributors; float* vertical_coefficients; int decode_buffer_pixels; float* decode_buffer; float* horizontal_buffer; // cache these because ceil/floor are inexplicably showing up in profile int horizontal_coefficient_width; int vertical_coefficient_width; int horizontal_filter_pixel_width; int vertical_filter_pixel_width; int horizontal_filter_pixel_margin; int vertical_filter_pixel_margin; int horizontal_num_contributors; int vertical_num_contributors; int ring_buffer_length_bytes; // The length of an individual entry in the ring buffer. The total number of ring buffers is stbir__get_filter_pixel_width(filter) int ring_buffer_num_entries; // Total number of entries in the ring buffer. int ring_buffer_first_scanline; int ring_buffer_last_scanline; int ring_buffer_begin_index; // first_scanline is at this index in the ring buffer float* ring_buffer; float* encode_buffer; // A temporary buffer to store floats so we don't lose precision while we do multiply-adds. int horizontal_contributors_size; int horizontal_coefficients_size; int vertical_contributors_size; int vertical_coefficients_size; int decode_buffer_size; int horizontal_buffer_size; int ring_buffer_size; int encode_buffer_size; } stbir__info; static const float stbir__max_uint8_as_float = 255.0f; static const float stbir__max_uint16_as_float = 65535.0f; static const double stbir__max_uint32_as_float = 4294967295.0; static stbir__inline int stbir__min(int a, int b) { return a < b ? a : b; } static stbir__inline float stbir__saturate(float x) { if (x < 0) return 0; if (x > 1) return 1; return x; } #ifdef STBIR_SATURATE_INT static stbir__inline stbir_uint8 stbir__saturate8(int x) { if ((unsigned int) x <= 255) return x; if (x < 0) return 0; return 255; } static stbir__inline stbir_uint16 stbir__saturate16(int x) { if ((unsigned int) x <= 65535) return x; if (x < 0) return 0; return 65535; } #endif static float stbir__srgb_uchar_to_linear_float[256] = { 0.000000f, 0.000304f, 0.000607f, 0.000911f, 0.001214f, 0.001518f, 0.001821f, 0.002125f, 0.002428f, 0.002732f, 0.003035f, 0.003347f, 0.003677f, 0.004025f, 0.004391f, 0.004777f, 0.005182f, 0.005605f, 0.006049f, 0.006512f, 0.006995f, 0.007499f, 0.008023f, 0.008568f, 0.009134f, 0.009721f, 0.010330f, 0.010960f, 0.011612f, 0.012286f, 0.012983f, 0.013702f, 0.014444f, 0.015209f, 0.015996f, 0.016807f, 0.017642f, 0.018500f, 0.019382f, 0.020289f, 0.021219f, 0.022174f, 0.023153f, 0.024158f, 0.025187f, 0.026241f, 0.027321f, 0.028426f, 0.029557f, 0.030713f, 0.031896f, 0.033105f, 0.034340f, 0.035601f, 0.036889f, 0.038204f, 0.039546f, 0.040915f, 0.042311f, 0.043735f, 0.045186f, 0.046665f, 0.048172f, 0.049707f, 0.051269f, 0.052861f, 0.054480f, 0.056128f, 0.057805f, 0.059511f, 0.061246f, 0.063010f, 0.064803f, 0.066626f, 0.068478f, 0.070360f, 0.072272f, 0.074214f, 0.076185f, 0.078187f, 0.080220f, 0.082283f, 0.084376f, 0.086500f, 0.088656f, 0.090842f, 0.093059f, 0.095307f, 0.097587f, 0.099899f, 0.102242f, 0.104616f, 0.107023f, 0.109462f, 0.111932f, 0.114435f, 0.116971f, 0.119538f, 0.122139f, 0.124772f, 0.127438f, 0.130136f, 0.132868f, 0.135633f, 0.138432f, 0.141263f, 0.144128f, 0.147027f, 0.149960f, 0.152926f, 0.155926f, 0.158961f, 0.162029f, 0.165132f, 0.168269f, 0.171441f, 0.174647f, 0.177888f, 0.181164f, 0.184475f, 0.187821f, 0.191202f, 0.194618f, 0.198069f, 0.201556f, 0.205079f, 0.208637f, 0.212231f, 0.215861f, 0.219526f, 0.223228f, 0.226966f, 0.230740f, 0.234551f, 0.238398f, 0.242281f, 0.246201f, 0.250158f, 0.254152f, 0.258183f, 0.262251f, 0.266356f, 0.270498f, 0.274677f, 0.278894f, 0.283149f, 0.287441f, 0.291771f, 0.296138f, 0.300544f, 0.304987f, 0.309469f, 0.313989f, 0.318547f, 0.323143f, 0.327778f, 0.332452f, 0.337164f, 0.341914f, 0.346704f, 0.351533f, 0.356400f, 0.361307f, 0.366253f, 0.371238f, 0.376262f, 0.381326f, 0.386430f, 0.391573f, 0.396755f, 0.401978f, 0.407240f, 0.412543f, 0.417885f, 0.423268f, 0.428691f, 0.434154f, 0.439657f, 0.445201f, 0.450786f, 0.456411f, 0.462077f, 0.467784f, 0.473532f, 0.479320f, 0.485150f, 0.491021f, 0.496933f, 0.502887f, 0.508881f, 0.514918f, 0.520996f, 0.527115f, 0.533276f, 0.539480f, 0.545725f, 0.552011f, 0.558340f, 0.564712f, 0.571125f, 0.577581f, 0.584078f, 0.590619f, 0.597202f, 0.603827f, 0.610496f, 0.617207f, 0.623960f, 0.630757f, 0.637597f, 0.644480f, 0.651406f, 0.658375f, 0.665387f, 0.672443f, 0.679543f, 0.686685f, 0.693872f, 0.701102f, 0.708376f, 0.715694f, 0.723055f, 0.730461f, 0.737911f, 0.745404f, 0.752942f, 0.760525f, 0.768151f, 0.775822f, 0.783538f, 0.791298f, 0.799103f, 0.806952f, 0.814847f, 0.822786f, 0.830770f, 0.838799f, 0.846873f, 0.854993f, 0.863157f, 0.871367f, 0.879622f, 0.887923f, 0.896269f, 0.904661f, 0.913099f, 0.921582f, 0.930111f, 0.938686f, 0.947307f, 0.955974f, 0.964686f, 0.973445f, 0.982251f, 0.991102f, 1.0f }; static float stbir__srgb_to_linear(float f) { if (f <= 0.04045f) return f / 12.92f; else return (float)pow((f + 0.055f) / 1.055f, 2.4f); } static float stbir__linear_to_srgb(float f) { if (f <= 0.0031308f) return f * 12.92f; else return 1.055f * (float)pow(f, 1 / 2.4f) - 0.055f; } #ifndef STBIR_NON_IEEE_FLOAT // From https://gist.github.com/rygorous/2203834 typedef union { stbir_uint32 u; float f; } stbir__FP32; static const stbir_uint32 fp32_to_srgb8_tab4[104] = { 0x0073000d, 0x007a000d, 0x0080000d, 0x0087000d, 0x008d000d, 0x0094000d, 0x009a000d, 0x00a1000d, 0x00a7001a, 0x00b4001a, 0x00c1001a, 0x00ce001a, 0x00da001a, 0x00e7001a, 0x00f4001a, 0x0101001a, 0x010e0033, 0x01280033, 0x01410033, 0x015b0033, 0x01750033, 0x018f0033, 0x01a80033, 0x01c20033, 0x01dc0067, 0x020f0067, 0x02430067, 0x02760067, 0x02aa0067, 0x02dd0067, 0x03110067, 0x03440067, 0x037800ce, 0x03df00ce, 0x044600ce, 0x04ad00ce, 0x051400ce, 0x057b00c5, 0x05dd00bc, 0x063b00b5, 0x06970158, 0x07420142, 0x07e30130, 0x087b0120, 0x090b0112, 0x09940106, 0x0a1700fc, 0x0a9500f2, 0x0b0f01cb, 0x0bf401ae, 0x0ccb0195, 0x0d950180, 0x0e56016e, 0x0f0d015e, 0x0fbc0150, 0x10630143, 0x11070264, 0x1238023e, 0x1357021d, 0x14660201, 0x156601e9, 0x165a01d3, 0x174401c0, 0x182401af, 0x18fe0331, 0x1a9602fe, 0x1c1502d2, 0x1d7e02ad, 0x1ed4028d, 0x201a0270, 0x21520256, 0x227d0240, 0x239f0443, 0x25c003fe, 0x27bf03c4, 0x29a10392, 0x2b6a0367, 0x2d1d0341, 0x2ebe031f, 0x304d0300, 0x31d105b0, 0x34a80555, 0x37520507, 0x39d504c5, 0x3c37048b, 0x3e7c0458, 0x40a8042a, 0x42bd0401, 0x44c20798, 0x488e071e, 0x4c1c06b6, 0x4f76065d, 0x52a50610, 0x55ac05cc, 0x5892058f, 0x5b590559, 0x5e0c0a23, 0x631c0980, 0x67db08f6, 0x6c55087f, 0x70940818, 0x74a007bd, 0x787d076c, 0x7c330723, }; static stbir_uint8 stbir__linear_to_srgb_uchar(float in) { static const stbir__FP32 almostone = { 0x3f7fffff }; // 1-eps static const stbir__FP32 minval = { (127-13) << 23 }; stbir_uint32 tab,bias,scale,t; stbir__FP32 f; // Clamp to [2^(-13), 1-eps]; these two values map to 0 and 1, respectively. // The tests are carefully written so that NaNs map to 0, same as in the reference // implementation. if (!(in > minval.f)) // written this way to catch NaNs in = minval.f; if (in > almostone.f) in = almostone.f; // Do the table lookup and unpack bias, scale f.f = in; tab = fp32_to_srgb8_tab4[(f.u - minval.u) >> 20]; bias = (tab >> 16) << 9; scale = tab & 0xffff; // Grab next-highest mantissa bits and perform linear interpolation t = (f.u >> 12) & 0xff; return (unsigned char) ((bias + scale*t) >> 16); } #else // sRGB transition values, scaled by 1<<28 static int stbir__srgb_offset_to_linear_scaled[256] = { 0, 40738, 122216, 203693, 285170, 366648, 448125, 529603, 611080, 692557, 774035, 855852, 942009, 1033024, 1128971, 1229926, 1335959, 1447142, 1563542, 1685229, 1812268, 1944725, 2082664, 2226148, 2375238, 2529996, 2690481, 2856753, 3028870, 3206888, 3390865, 3580856, 3776916, 3979100, 4187460, 4402049, 4622919, 4850123, 5083710, 5323731, 5570236, 5823273, 6082892, 6349140, 6622065, 6901714, 7188133, 7481369, 7781466, 8088471, 8402427, 8723380, 9051372, 9386448, 9728650, 10078021, 10434603, 10798439, 11169569, 11548036, 11933879, 12327139, 12727857, 13136073, 13551826, 13975156, 14406100, 14844697, 15290987, 15745007, 16206795, 16676389, 17153826, 17639142, 18132374, 18633560, 19142734, 19659934, 20185196, 20718552, 21260042, 21809696, 22367554, 22933648, 23508010, 24090680, 24681686, 25281066, 25888850, 26505076, 27129772, 27762974, 28404716, 29055026, 29713942, 30381490, 31057708, 31742624, 32436272, 33138682, 33849884, 34569912, 35298800, 36036568, 36783260, 37538896, 38303512, 39077136, 39859796, 40651528, 41452360, 42262316, 43081432, 43909732, 44747252, 45594016, 46450052, 47315392, 48190064, 49074096, 49967516, 50870356, 51782636, 52704392, 53635648, 54576432, 55526772, 56486700, 57456236, 58435408, 59424248, 60422780, 61431036, 62449032, 63476804, 64514376, 65561776, 66619028, 67686160, 68763192, 69850160, 70947088, 72053992, 73170912, 74297864, 75434880, 76581976, 77739184, 78906536, 80084040, 81271736, 82469648, 83677792, 84896192, 86124888, 87363888, 88613232, 89872928, 91143016, 92423512, 93714432, 95015816, 96327688, 97650056, 98982952, 100326408, 101680440, 103045072, 104420320, 105806224, 107202800, 108610064, 110028048, 111456776, 112896264, 114346544, 115807632, 117279552, 118762328, 120255976, 121760536, 123276016, 124802440, 126339832, 127888216, 129447616, 131018048, 132599544, 134192112, 135795792, 137410592, 139036528, 140673648, 142321952, 143981456, 145652208, 147334208, 149027488, 150732064, 152447968, 154175200, 155913792, 157663776, 159425168, 161197984, 162982240, 164777968, 166585184, 168403904, 170234160, 172075968, 173929344, 175794320, 177670896, 179559120, 181458992, 183370528, 185293776, 187228736, 189175424, 191133888, 193104112, 195086128, 197079968, 199085648, 201103184, 203132592, 205173888, 207227120, 209292272, 211369392, 213458480, 215559568, 217672656, 219797792, 221934976, 224084240, 226245600, 228419056, 230604656, 232802400, 235012320, 237234432, 239468736, 241715280, 243974080, 246245120, 248528464, 250824112, 253132064, 255452368, 257785040, 260130080, 262487520, 264857376, 267239664, }; static stbir_uint8 stbir__linear_to_srgb_uchar(float f) { int x = (int) (f * (1 << 28)); // has headroom so you don't need to clamp int v = 0; int i; // Refine the guess with a short binary search. i = v + 128; if (x >= stbir__srgb_offset_to_linear_scaled[i]) v = i; i = v + 64; if (x >= stbir__srgb_offset_to_linear_scaled[i]) v = i; i = v + 32; if (x >= stbir__srgb_offset_to_linear_scaled[i]) v = i; i = v + 16; if (x >= stbir__srgb_offset_to_linear_scaled[i]) v = i; i = v + 8; if (x >= stbir__srgb_offset_to_linear_scaled[i]) v = i; i = v + 4; if (x >= stbir__srgb_offset_to_linear_scaled[i]) v = i; i = v + 2; if (x >= stbir__srgb_offset_to_linear_scaled[i]) v = i; i = v + 1; if (x >= stbir__srgb_offset_to_linear_scaled[i]) v = i; return (stbir_uint8) v; } #endif static float stbir__filter_trapezoid(float x, float scale) { float halfscale = scale / 2; float t = 0.5f + halfscale; STBIR_ASSERT(scale <= 1); x = (float)fabs(x); if (x >= t) return 0; else { float r = 0.5f - halfscale; if (x <= r) return 1; else return (t - x) / scale; } } static float stbir__support_trapezoid(float scale) { STBIR_ASSERT(scale <= 1); return 0.5f + scale / 2; } static float stbir__filter_triangle(float x, float s) { STBIR__UNUSED_PARAM(s); x = (float)fabs(x); if (x <= 1.0f) return 1 - x; else return 0; } static float stbir__filter_cubic(float x, float s) { STBIR__UNUSED_PARAM(s); x = (float)fabs(x); if (x < 1.0f) return (4 + x*x*(3*x - 6))/6; else if (x < 2.0f) return (8 + x*(-12 + x*(6 - x)))/6; return (0.0f); } static float stbir__filter_catmullrom(float x, float s) { STBIR__UNUSED_PARAM(s); x = (float)fabs(x); if (x < 1.0f) return 1 - x*x*(2.5f - 1.5f*x); else if (x < 2.0f) return 2 - x*(4 + x*(0.5f*x - 2.5f)); return (0.0f); } static float stbir__filter_mitchell(float x, float s) { STBIR__UNUSED_PARAM(s); x = (float)fabs(x); if (x < 1.0f) return (16 + x*x*(21 * x - 36))/18; else if (x < 2.0f) return (32 + x*(-60 + x*(36 - 7*x)))/18; return (0.0f); } static float stbir__support_zero(float s) { STBIR__UNUSED_PARAM(s); return 0; } static float stbir__support_one(float s) { STBIR__UNUSED_PARAM(s); return 1; } static float stbir__support_two(float s) { STBIR__UNUSED_PARAM(s); return 2; } static stbir__filter_info stbir__filter_info_table[] = { { NULL, stbir__support_zero }, { stbir__filter_trapezoid, stbir__support_trapezoid }, { stbir__filter_triangle, stbir__support_one }, { stbir__filter_cubic, stbir__support_two }, { stbir__filter_catmullrom, stbir__support_two }, { stbir__filter_mitchell, stbir__support_two }, }; stbir__inline static int stbir__use_upsampling(float ratio) { return ratio > 1; } stbir__inline static int stbir__use_width_upsampling(stbir__info* stbir_info) { return stbir__use_upsampling(stbir_info->horizontal_scale); } stbir__inline static int stbir__use_height_upsampling(stbir__info* stbir_info) { return stbir__use_upsampling(stbir_info->vertical_scale); } // This is the maximum number of input samples that can affect an output sample // with the given filter static int stbir__get_filter_pixel_width(stbir_filter filter, float scale) { STBIR_ASSERT(filter != 0); STBIR_ASSERT(filter < STBIR__ARRAY_SIZE(stbir__filter_info_table)); if (stbir__use_upsampling(scale)) return (int)ceil(stbir__filter_info_table[filter].support(1/scale) * 2); else return (int)ceil(stbir__filter_info_table[filter].support(scale) * 2 / scale); } // This is how much to expand buffers to account for filters seeking outside // the image boundaries. static int stbir__get_filter_pixel_margin(stbir_filter filter, float scale) { return stbir__get_filter_pixel_width(filter, scale) / 2; } static int stbir__get_coefficient_width(stbir_filter filter, float scale) { if (stbir__use_upsampling(scale)) return (int)ceil(stbir__filter_info_table[filter].support(1 / scale) * 2); else return (int)ceil(stbir__filter_info_table[filter].support(scale) * 2); } static int stbir__get_contributors(float scale, stbir_filter filter, int input_size, int output_size) { if (stbir__use_upsampling(scale)) return output_size; else return (input_size + stbir__get_filter_pixel_margin(filter, scale) * 2); } static int stbir__get_total_horizontal_coefficients(stbir__info* info) { return info->horizontal_num_contributors * stbir__get_coefficient_width (info->horizontal_filter, info->horizontal_scale); } static int stbir__get_total_vertical_coefficients(stbir__info* info) { return info->vertical_num_contributors * stbir__get_coefficient_width (info->vertical_filter, info->vertical_scale); } static stbir__contributors* stbir__get_contributor(stbir__contributors* contributors, int n) { return &contributors[n]; } // For perf reasons this code is duplicated in stbir__resample_horizontal_upsample/downsample, // if you change it here change it there too. static float* stbir__get_coefficient(float* coefficients, stbir_filter filter, float scale, int n, int c) { int width = stbir__get_coefficient_width(filter, scale); return &coefficients[width*n + c]; } static int stbir__edge_wrap_slow(stbir_edge edge, int n, int max) { switch (edge) { case STBIR_EDGE_ZERO: return 0; // we'll decode the wrong pixel here, and then overwrite with 0s later case STBIR_EDGE_CLAMP: if (n < 0) return 0; if (n >= max) return max - 1; return n; // NOTREACHED case STBIR_EDGE_REFLECT: { if (n < 0) { if (n < max) return -n; else return max - 1; } if (n >= max) { int max2 = max * 2; if (n >= max2) return 0; else return max2 - n - 1; } return n; // NOTREACHED } case STBIR_EDGE_WRAP: if (n >= 0) return (n % max); else { int m = (-n) % max; if (m != 0) m = max - m; return (m); } // NOTREACHED default: STBIR_ASSERT(!"Unimplemented edge type"); return 0; } } stbir__inline static int stbir__edge_wrap(stbir_edge edge, int n, int max) { // avoid per-pixel switch if (n >= 0 && n < max) return n; return stbir__edge_wrap_slow(edge, n, max); } // What input pixels contribute to this output pixel? static void stbir__calculate_sample_range_upsample(int n, float out_filter_radius, float scale_ratio, float out_shift, int* in_first_pixel, int* in_last_pixel, float* in_center_of_out) { float out_pixel_center = (float)n + 0.5f; float out_pixel_influence_lowerbound = out_pixel_center - out_filter_radius; float out_pixel_influence_upperbound = out_pixel_center + out_filter_radius; float in_pixel_influence_lowerbound = (out_pixel_influence_lowerbound + out_shift) / scale_ratio; float in_pixel_influence_upperbound = (out_pixel_influence_upperbound + out_shift) / scale_ratio; *in_center_of_out = (out_pixel_center + out_shift) / scale_ratio; *in_first_pixel = (int)(floor(in_pixel_influence_lowerbound + 0.5)); *in_last_pixel = (int)(floor(in_pixel_influence_upperbound - 0.5)); } // What output pixels does this input pixel contribute to? static void stbir__calculate_sample_range_downsample(int n, float in_pixels_radius, float scale_ratio, float out_shift, int* out_first_pixel, int* out_last_pixel, float* out_center_of_in) { float in_pixel_center = (float)n + 0.5f; float in_pixel_influence_lowerbound = in_pixel_center - in_pixels_radius; float in_pixel_influence_upperbound = in_pixel_center + in_pixels_radius; float out_pixel_influence_lowerbound = in_pixel_influence_lowerbound * scale_ratio - out_shift; float out_pixel_influence_upperbound = in_pixel_influence_upperbound * scale_ratio - out_shift; *out_center_of_in = in_pixel_center * scale_ratio - out_shift; *out_first_pixel = (int)(floor(out_pixel_influence_lowerbound + 0.5)); *out_last_pixel = (int)(floor(out_pixel_influence_upperbound - 0.5)); } static void stbir__calculate_coefficients_upsample(stbir_filter filter, float scale, int in_first_pixel, int in_last_pixel, float in_center_of_out, stbir__contributors* contributor, float* coefficient_group) { int i; float total_filter = 0; float filter_scale; STBIR_ASSERT(in_last_pixel - in_first_pixel <= (int)ceil(stbir__filter_info_table[filter].support(1/scale) * 2)); // Taken directly from stbir__get_coefficient_width() which we can't call because we don't know if we're horizontal or vertical. contributor->n0 = in_first_pixel; contributor->n1 = in_last_pixel; STBIR_ASSERT(contributor->n1 >= contributor->n0); for (i = 0; i <= in_last_pixel - in_first_pixel; i++) { float in_pixel_center = (float)(i + in_first_pixel) + 0.5f; coefficient_group[i] = stbir__filter_info_table[filter].kernel(in_center_of_out - in_pixel_center, 1 / scale); // If the coefficient is zero, skip it. (Don't do the <0 check here, we want the influence of those outside pixels.) if (i == 0 && !coefficient_group[i]) { contributor->n0 = ++in_first_pixel; i--; continue; } total_filter += coefficient_group[i]; } // NOTE(fg): Not actually true in general, nor is there any reason to expect it should be. // It would be true in exact math but is at best approximately true in floating-point math, // and it would not make sense to try and put actual bounds on this here because it depends // on the image aspect ratio which can get pretty extreme. //STBIR_ASSERT(stbir__filter_info_table[filter].kernel((float)(in_last_pixel + 1) + 0.5f - in_center_of_out, 1/scale) == 0); STBIR_ASSERT(total_filter > 0.9); STBIR_ASSERT(total_filter < 1.1f); // Make sure it's not way off. // Make sure the sum of all coefficients is 1. filter_scale = 1 / total_filter; for (i = 0; i <= in_last_pixel - in_first_pixel; i++) coefficient_group[i] *= filter_scale; for (i = in_last_pixel - in_first_pixel; i >= 0; i--) { if (coefficient_group[i]) break; // This line has no weight. We can skip it. contributor->n1 = contributor->n0 + i - 1; } } static void stbir__calculate_coefficients_downsample(stbir_filter filter, float scale_ratio, int out_first_pixel, int out_last_pixel, float out_center_of_in, stbir__contributors* contributor, float* coefficient_group) { int i; STBIR_ASSERT(out_last_pixel - out_first_pixel <= (int)ceil(stbir__filter_info_table[filter].support(scale_ratio) * 2)); // Taken directly from stbir__get_coefficient_width() which we can't call because we don't know if we're horizontal or vertical. contributor->n0 = out_first_pixel; contributor->n1 = out_last_pixel; STBIR_ASSERT(contributor->n1 >= contributor->n0); for (i = 0; i <= out_last_pixel - out_first_pixel; i++) { float out_pixel_center = (float)(i + out_first_pixel) + 0.5f; float x = out_pixel_center - out_center_of_in; coefficient_group[i] = stbir__filter_info_table[filter].kernel(x, scale_ratio) * scale_ratio; } // NOTE(fg): Not actually true in general, nor is there any reason to expect it should be. // It would be true in exact math but is at best approximately true in floating-point math, // and it would not make sense to try and put actual bounds on this here because it depends // on the image aspect ratio which can get pretty extreme. //STBIR_ASSERT(stbir__filter_info_table[filter].kernel((float)(out_last_pixel + 1) + 0.5f - out_center_of_in, scale_ratio) == 0); for (i = out_last_pixel - out_first_pixel; i >= 0; i--) { if (coefficient_group[i]) break; // This line has no weight. We can skip it. contributor->n1 = contributor->n0 + i - 1; } } static void stbir__normalize_downsample_coefficients(stbir__contributors* contributors, float* coefficients, stbir_filter filter, float scale_ratio, int input_size, int output_size) { int num_contributors = stbir__get_contributors(scale_ratio, filter, input_size, output_size); int num_coefficients = stbir__get_coefficient_width(filter, scale_ratio); int i, j; int skip; for (i = 0; i < output_size; i++) { float scale; float total = 0; for (j = 0; j < num_contributors; j++) { if (i >= contributors[j].n0 && i <= contributors[j].n1) { float coefficient = *stbir__get_coefficient(coefficients, filter, scale_ratio, j, i - contributors[j].n0); total += coefficient; } else if (i < contributors[j].n0) break; } STBIR_ASSERT(total > 0.9f); STBIR_ASSERT(total < 1.1f); scale = 1 / total; for (j = 0; j < num_contributors; j++) { if (i >= contributors[j].n0 && i <= contributors[j].n1) *stbir__get_coefficient(coefficients, filter, scale_ratio, j, i - contributors[j].n0) *= scale; else if (i < contributors[j].n0) break; } } // Optimize: Skip zero coefficients and contributions outside of image bounds. // Do this after normalizing because normalization depends on the n0/n1 values. for (j = 0; j < num_contributors; j++) { int range, max, width; skip = 0; while (*stbir__get_coefficient(coefficients, filter, scale_ratio, j, skip) == 0) skip++; contributors[j].n0 += skip; while (contributors[j].n0 < 0) { contributors[j].n0++; skip++; } range = contributors[j].n1 - contributors[j].n0 + 1; max = stbir__min(num_coefficients, range); width = stbir__get_coefficient_width(filter, scale_ratio); for (i = 0; i < max; i++) { if (i + skip >= width) break; *stbir__get_coefficient(coefficients, filter, scale_ratio, j, i) = *stbir__get_coefficient(coefficients, filter, scale_ratio, j, i + skip); } continue; } // Using min to avoid writing into invalid pixels. for (i = 0; i < num_contributors; i++) contributors[i].n1 = stbir__min(contributors[i].n1, output_size - 1); } // Each scan line uses the same kernel values so we should calculate the kernel // values once and then we can use them for every scan line. static void stbir__calculate_filters(stbir__contributors* contributors, float* coefficients, stbir_filter filter, float scale_ratio, float shift, int input_size, int output_size) { int n; int total_contributors = stbir__get_contributors(scale_ratio, filter, input_size, output_size); if (stbir__use_upsampling(scale_ratio)) { float out_pixels_radius = stbir__filter_info_table[filter].support(1 / scale_ratio) * scale_ratio; // Looping through out pixels for (n = 0; n < total_contributors; n++) { float in_center_of_out; // Center of the current out pixel in the in pixel space int in_first_pixel, in_last_pixel; stbir__calculate_sample_range_upsample(n, out_pixels_radius, scale_ratio, shift, &in_first_pixel, &in_last_pixel, &in_center_of_out); stbir__calculate_coefficients_upsample(filter, scale_ratio, in_first_pixel, in_last_pixel, in_center_of_out, stbir__get_contributor(contributors, n), stbir__get_coefficient(coefficients, filter, scale_ratio, n, 0)); } } else { float in_pixels_radius = stbir__filter_info_table[filter].support(scale_ratio) / scale_ratio; // Looping through in pixels for (n = 0; n < total_contributors; n++) { float out_center_of_in; // Center of the current out pixel in the in pixel space int out_first_pixel, out_last_pixel; int n_adjusted = n - stbir__get_filter_pixel_margin(filter, scale_ratio); stbir__calculate_sample_range_downsample(n_adjusted, in_pixels_radius, scale_ratio, shift, &out_first_pixel, &out_last_pixel, &out_center_of_in); stbir__calculate_coefficients_downsample(filter, scale_ratio, out_first_pixel, out_last_pixel, out_center_of_in, stbir__get_contributor(contributors, n), stbir__get_coefficient(coefficients, filter, scale_ratio, n, 0)); } stbir__normalize_downsample_coefficients(contributors, coefficients, filter, scale_ratio, input_size, output_size); } } static float* stbir__get_decode_buffer(stbir__info* stbir_info) { // The 0 index of the decode buffer starts after the margin. This makes // it okay to use negative indexes on the decode buffer. return &stbir_info->decode_buffer[stbir_info->horizontal_filter_pixel_margin * stbir_info->channels]; } #define STBIR__DECODE(type, colorspace) ((int)(type) * (STBIR_MAX_COLORSPACES) + (int)(colorspace)) static void stbir__decode_scanline(stbir__info* stbir_info, int n) { int c; int channels = stbir_info->channels; int alpha_channel = stbir_info->alpha_channel; int type = stbir_info->type; int colorspace = stbir_info->colorspace; int input_w = stbir_info->input_w; size_t input_stride_bytes = stbir_info->input_stride_bytes; float* decode_buffer = stbir__get_decode_buffer(stbir_info); stbir_edge edge_horizontal = stbir_info->edge_horizontal; stbir_edge edge_vertical = stbir_info->edge_vertical; size_t in_buffer_row_offset = stbir__edge_wrap(edge_vertical, n, stbir_info->input_h) * input_stride_bytes; const void* input_data = (char *) stbir_info->input_data + in_buffer_row_offset; int max_x = input_w + stbir_info->horizontal_filter_pixel_margin; int decode = STBIR__DECODE(type, colorspace); int x = -stbir_info->horizontal_filter_pixel_margin; // special handling for STBIR_EDGE_ZERO because it needs to return an item that doesn't appear in the input, // and we want to avoid paying overhead on every pixel if not STBIR_EDGE_ZERO if (edge_vertical == STBIR_EDGE_ZERO && (n < 0 || n >= stbir_info->input_h)) { for (; x < max_x; x++) for (c = 0; c < channels; c++) decode_buffer[x*channels + c] = 0; return; } switch (decode) { case STBIR__DECODE(STBIR_TYPE_UINT8, STBIR_COLORSPACE_LINEAR): for (; x < max_x; x++) { int decode_pixel_index = x * channels; int input_pixel_index = stbir__edge_wrap(edge_horizontal, x, input_w) * channels; for (c = 0; c < channels; c++) decode_buffer[decode_pixel_index + c] = ((float)((const unsigned char*)input_data)[input_pixel_index + c]) / stbir__max_uint8_as_float; } break; case STBIR__DECODE(STBIR_TYPE_UINT8, STBIR_COLORSPACE_SRGB): for (; x < max_x; x++) { int decode_pixel_index = x * channels; int input_pixel_index = stbir__edge_wrap(edge_horizontal, x, input_w) * channels; for (c = 0; c < channels; c++) decode_buffer[decode_pixel_index + c] = stbir__srgb_uchar_to_linear_float[((const unsigned char*)input_data)[input_pixel_index + c]]; if (!(stbir_info->flags&STBIR_FLAG_ALPHA_USES_COLORSPACE)) decode_buffer[decode_pixel_index + alpha_channel] = ((float)((const unsigned char*)input_data)[input_pixel_index + alpha_channel]) / stbir__max_uint8_as_float; } break; case STBIR__DECODE(STBIR_TYPE_UINT16, STBIR_COLORSPACE_LINEAR): for (; x < max_x; x++) { int decode_pixel_index = x * channels; int input_pixel_index = stbir__edge_wrap(edge_horizontal, x, input_w) * channels; for (c = 0; c < channels; c++) decode_buffer[decode_pixel_index + c] = ((float)((const unsigned short*)input_data)[input_pixel_index + c]) / stbir__max_uint16_as_float; } break; case STBIR__DECODE(STBIR_TYPE_UINT16, STBIR_COLORSPACE_SRGB): for (; x < max_x; x++) { int decode_pixel_index = x * channels; int input_pixel_index = stbir__edge_wrap(edge_horizontal, x, input_w) * channels; for (c = 0; c < channels; c++) decode_buffer[decode_pixel_index + c] = stbir__srgb_to_linear(((float)((const unsigned short*)input_data)[input_pixel_index + c]) / stbir__max_uint16_as_float); if (!(stbir_info->flags&STBIR_FLAG_ALPHA_USES_COLORSPACE)) decode_buffer[decode_pixel_index + alpha_channel] = ((float)((const unsigned short*)input_data)[input_pixel_index + alpha_channel]) / stbir__max_uint16_as_float; } break; case STBIR__DECODE(STBIR_TYPE_UINT32, STBIR_COLORSPACE_LINEAR): for (; x < max_x; x++) { int decode_pixel_index = x * channels; int input_pixel_index = stbir__edge_wrap(edge_horizontal, x, input_w) * channels; for (c = 0; c < channels; c++) decode_buffer[decode_pixel_index + c] = (float)(((double)((const unsigned int*)input_data)[input_pixel_index + c]) / stbir__max_uint32_as_float); } break; case STBIR__DECODE(STBIR_TYPE_UINT32, STBIR_COLORSPACE_SRGB): for (; x < max_x; x++) { int decode_pixel_index = x * channels; int input_pixel_index = stbir__edge_wrap(edge_horizontal, x, input_w) * channels; for (c = 0; c < channels; c++) decode_buffer[decode_pixel_index + c] = stbir__srgb_to_linear((float)(((double)((const unsigned int*)input_data)[input_pixel_index + c]) / stbir__max_uint32_as_float)); if (!(stbir_info->flags&STBIR_FLAG_ALPHA_USES_COLORSPACE)) decode_buffer[decode_pixel_index + alpha_channel] = (float)(((double)((const unsigned int*)input_data)[input_pixel_index + alpha_channel]) / stbir__max_uint32_as_float); } break; case STBIR__DECODE(STBIR_TYPE_FLOAT, STBIR_COLORSPACE_LINEAR): for (; x < max_x; x++) { int decode_pixel_index = x * channels; int input_pixel_index = stbir__edge_wrap(edge_horizontal, x, input_w) * channels; for (c = 0; c < channels; c++) decode_buffer[decode_pixel_index + c] = ((const float*)input_data)[input_pixel_index + c]; } break; case STBIR__DECODE(STBIR_TYPE_FLOAT, STBIR_COLORSPACE_SRGB): for (; x < max_x; x++) { int decode_pixel_index = x * channels; int input_pixel_index = stbir__edge_wrap(edge_horizontal, x, input_w) * channels; for (c = 0; c < channels; c++) decode_buffer[decode_pixel_index + c] = stbir__srgb_to_linear(((const float*)input_data)[input_pixel_index + c]); if (!(stbir_info->flags&STBIR_FLAG_ALPHA_USES_COLORSPACE)) decode_buffer[decode_pixel_index + alpha_channel] = ((const float*)input_data)[input_pixel_index + alpha_channel]; } break; default: STBIR_ASSERT(!"Unknown type/colorspace/channels combination."); break; } if (!(stbir_info->flags & STBIR_FLAG_ALPHA_PREMULTIPLIED)) { for (x = -stbir_info->horizontal_filter_pixel_margin; x < max_x; x++) { int decode_pixel_index = x * channels; // If the alpha value is 0 it will clobber the color values. Make sure it's not. float alpha = decode_buffer[decode_pixel_index + alpha_channel]; #ifndef STBIR_NO_ALPHA_EPSILON if (stbir_info->type != STBIR_TYPE_FLOAT) { alpha += STBIR_ALPHA_EPSILON; decode_buffer[decode_pixel_index + alpha_channel] = alpha; } #endif for (c = 0; c < channels; c++) { if (c == alpha_channel) continue; decode_buffer[decode_pixel_index + c] *= alpha; } } } if (edge_horizontal == STBIR_EDGE_ZERO) { for (x = -stbir_info->horizontal_filter_pixel_margin; x < 0; x++) { for (c = 0; c < channels; c++) decode_buffer[x*channels + c] = 0; } for (x = input_w; x < max_x; x++) { for (c = 0; c < channels; c++) decode_buffer[x*channels + c] = 0; } } } static float* stbir__get_ring_buffer_entry(float* ring_buffer, int index, int ring_buffer_length) { return &ring_buffer[index * ring_buffer_length]; } static float* stbir__add_empty_ring_buffer_entry(stbir__info* stbir_info, int n) { int ring_buffer_index; float* ring_buffer; stbir_info->ring_buffer_last_scanline = n; if (stbir_info->ring_buffer_begin_index < 0) { ring_buffer_index = stbir_info->ring_buffer_begin_index = 0; stbir_info->ring_buffer_first_scanline = n; } else { ring_buffer_index = (stbir_info->ring_buffer_begin_index + (stbir_info->ring_buffer_last_scanline - stbir_info->ring_buffer_first_scanline)) % stbir_info->ring_buffer_num_entries; STBIR_ASSERT(ring_buffer_index != stbir_info->ring_buffer_begin_index); } ring_buffer = stbir__get_ring_buffer_entry(stbir_info->ring_buffer, ring_buffer_index, stbir_info->ring_buffer_length_bytes / sizeof(float)); memset(ring_buffer, 0, stbir_info->ring_buffer_length_bytes); return ring_buffer; } static void stbir__resample_horizontal_upsample(stbir__info* stbir_info, float* output_buffer) { int x, k; int output_w = stbir_info->output_w; int channels = stbir_info->channels; float* decode_buffer = stbir__get_decode_buffer(stbir_info); stbir__contributors* horizontal_contributors = stbir_info->horizontal_contributors; float* horizontal_coefficients = stbir_info->horizontal_coefficients; int coefficient_width = stbir_info->horizontal_coefficient_width; for (x = 0; x < output_w; x++) { int n0 = horizontal_contributors[x].n0; int n1 = horizontal_contributors[x].n1; int out_pixel_index = x * channels; int coefficient_group = coefficient_width * x; int coefficient_counter = 0; STBIR_ASSERT(n1 >= n0); STBIR_ASSERT(n0 >= -stbir_info->horizontal_filter_pixel_margin); STBIR_ASSERT(n1 >= -stbir_info->horizontal_filter_pixel_margin); STBIR_ASSERT(n0 < stbir_info->input_w + stbir_info->horizontal_filter_pixel_margin); STBIR_ASSERT(n1 < stbir_info->input_w + stbir_info->horizontal_filter_pixel_margin); switch (channels) { case 1: for (k = n0; k <= n1; k++) { int in_pixel_index = k * 1; float coefficient = horizontal_coefficients[coefficient_group + coefficient_counter++]; STBIR_ASSERT(coefficient != 0); output_buffer[out_pixel_index + 0] += decode_buffer[in_pixel_index + 0] * coefficient; } break; case 2: for (k = n0; k <= n1; k++) { int in_pixel_index = k * 2; float coefficient = horizontal_coefficients[coefficient_group + coefficient_counter++]; STBIR_ASSERT(coefficient != 0); output_buffer[out_pixel_index + 0] += decode_buffer[in_pixel_index + 0] * coefficient; output_buffer[out_pixel_index + 1] += decode_buffer[in_pixel_index + 1] * coefficient; } break; case 3: for (k = n0; k <= n1; k++) { int in_pixel_index = k * 3; float coefficient = horizontal_coefficients[coefficient_group + coefficient_counter++]; STBIR_ASSERT(coefficient != 0); output_buffer[out_pixel_index + 0] += decode_buffer[in_pixel_index + 0] * coefficient; output_buffer[out_pixel_index + 1] += decode_buffer[in_pixel_index + 1] * coefficient; output_buffer[out_pixel_index + 2] += decode_buffer[in_pixel_index + 2] * coefficient; } break; case 4: for (k = n0; k <= n1; k++) { int in_pixel_index = k * 4; float coefficient = horizontal_coefficients[coefficient_group + coefficient_counter++]; STBIR_ASSERT(coefficient != 0); output_buffer[out_pixel_index + 0] += decode_buffer[in_pixel_index + 0] * coefficient; output_buffer[out_pixel_index + 1] += decode_buffer[in_pixel_index + 1] * coefficient; output_buffer[out_pixel_index + 2] += decode_buffer[in_pixel_index + 2] * coefficient; output_buffer[out_pixel_index + 3] += decode_buffer[in_pixel_index + 3] * coefficient; } break; default: for (k = n0; k <= n1; k++) { int in_pixel_index = k * channels; float coefficient = horizontal_coefficients[coefficient_group + coefficient_counter++]; int c; STBIR_ASSERT(coefficient != 0); for (c = 0; c < channels; c++) output_buffer[out_pixel_index + c] += decode_buffer[in_pixel_index + c] * coefficient; } break; } } } static void stbir__resample_horizontal_downsample(stbir__info* stbir_info, float* output_buffer) { int x, k; int input_w = stbir_info->input_w; int channels = stbir_info->channels; float* decode_buffer = stbir__get_decode_buffer(stbir_info); stbir__contributors* horizontal_contributors = stbir_info->horizontal_contributors; float* horizontal_coefficients = stbir_info->horizontal_coefficients; int coefficient_width = stbir_info->horizontal_coefficient_width; int filter_pixel_margin = stbir_info->horizontal_filter_pixel_margin; int max_x = input_w + filter_pixel_margin * 2; STBIR_ASSERT(!stbir__use_width_upsampling(stbir_info)); switch (channels) { case 1: for (x = 0; x < max_x; x++) { int n0 = horizontal_contributors[x].n0; int n1 = horizontal_contributors[x].n1; int in_x = x - filter_pixel_margin; int in_pixel_index = in_x * 1; int max_n = n1; int coefficient_group = coefficient_width * x; for (k = n0; k <= max_n; k++) { int out_pixel_index = k * 1; float coefficient = horizontal_coefficients[coefficient_group + k - n0]; output_buffer[out_pixel_index + 0] += decode_buffer[in_pixel_index + 0] * coefficient; } } break; case 2: for (x = 0; x < max_x; x++) { int n0 = horizontal_contributors[x].n0; int n1 = horizontal_contributors[x].n1; int in_x = x - filter_pixel_margin; int in_pixel_index = in_x * 2; int max_n = n1; int coefficient_group = coefficient_width * x; for (k = n0; k <= max_n; k++) { int out_pixel_index = k * 2; float coefficient = horizontal_coefficients[coefficient_group + k - n0]; output_buffer[out_pixel_index + 0] += decode_buffer[in_pixel_index + 0] * coefficient; output_buffer[out_pixel_index + 1] += decode_buffer[in_pixel_index + 1] * coefficient; } } break; case 3: for (x = 0; x < max_x; x++) { int n0 = horizontal_contributors[x].n0; int n1 = horizontal_contributors[x].n1; int in_x = x - filter_pixel_margin; int in_pixel_index = in_x * 3; int max_n = n1; int coefficient_group = coefficient_width * x; for (k = n0; k <= max_n; k++) { int out_pixel_index = k * 3; float coefficient = horizontal_coefficients[coefficient_group + k - n0]; output_buffer[out_pixel_index + 0] += decode_buffer[in_pixel_index + 0] * coefficient; output_buffer[out_pixel_index + 1] += decode_buffer[in_pixel_index + 1] * coefficient; output_buffer[out_pixel_index + 2] += decode_buffer[in_pixel_index + 2] * coefficient; } } break; case 4: for (x = 0; x < max_x; x++) { int n0 = horizontal_contributors[x].n0; int n1 = horizontal_contributors[x].n1; int in_x = x - filter_pixel_margin; int in_pixel_index = in_x * 4; int max_n = n1; int coefficient_group = coefficient_width * x; for (k = n0; k <= max_n; k++) { int out_pixel_index = k * 4; float coefficient = horizontal_coefficients[coefficient_group + k - n0]; output_buffer[out_pixel_index + 0] += decode_buffer[in_pixel_index + 0] * coefficient; output_buffer[out_pixel_index + 1] += decode_buffer[in_pixel_index + 1] * coefficient; output_buffer[out_pixel_index + 2] += decode_buffer[in_pixel_index + 2] * coefficient; output_buffer[out_pixel_index + 3] += decode_buffer[in_pixel_index + 3] * coefficient; } } break; default: for (x = 0; x < max_x; x++) { int n0 = horizontal_contributors[x].n0; int n1 = horizontal_contributors[x].n1; int in_x = x - filter_pixel_margin; int in_pixel_index = in_x * channels; int max_n = n1; int coefficient_group = coefficient_width * x; for (k = n0; k <= max_n; k++) { int c; int out_pixel_index = k * channels; float coefficient = horizontal_coefficients[coefficient_group + k - n0]; for (c = 0; c < channels; c++) output_buffer[out_pixel_index + c] += decode_buffer[in_pixel_index + c] * coefficient; } } break; } } static void stbir__decode_and_resample_upsample(stbir__info* stbir_info, int n) { // Decode the nth scanline from the source image into the decode buffer. stbir__decode_scanline(stbir_info, n); // Now resample it into the ring buffer. if (stbir__use_width_upsampling(stbir_info)) stbir__resample_horizontal_upsample(stbir_info, stbir__add_empty_ring_buffer_entry(stbir_info, n)); else stbir__resample_horizontal_downsample(stbir_info, stbir__add_empty_ring_buffer_entry(stbir_info, n)); // Now it's sitting in the ring buffer ready to be used as source for the vertical sampling. } static void stbir__decode_and_resample_downsample(stbir__info* stbir_info, int n) { // Decode the nth scanline from the source image into the decode buffer. stbir__decode_scanline(stbir_info, n); memset(stbir_info->horizontal_buffer, 0, stbir_info->output_w * stbir_info->channels * sizeof(float)); // Now resample it into the horizontal buffer. if (stbir__use_width_upsampling(stbir_info)) stbir__resample_horizontal_upsample(stbir_info, stbir_info->horizontal_buffer); else stbir__resample_horizontal_downsample(stbir_info, stbir_info->horizontal_buffer); // Now it's sitting in the horizontal buffer ready to be distributed into the ring buffers. } // Get the specified scan line from the ring buffer. static float* stbir__get_ring_buffer_scanline(int get_scanline, float* ring_buffer, int begin_index, int first_scanline, int ring_buffer_num_entries, int ring_buffer_length) { int ring_buffer_index = (begin_index + (get_scanline - first_scanline)) % ring_buffer_num_entries; return stbir__get_ring_buffer_entry(ring_buffer, ring_buffer_index, ring_buffer_length); } static void stbir__encode_scanline(stbir__info* stbir_info, int num_pixels, void *output_buffer, float *encode_buffer, int channels, int alpha_channel, int decode) { int x; int n; int num_nonalpha; stbir_uint16 nonalpha[STBIR_MAX_CHANNELS]; if (!(stbir_info->flags&STBIR_FLAG_ALPHA_PREMULTIPLIED)) { for (x=0; x < num_pixels; ++x) { int pixel_index = x*channels; float alpha = encode_buffer[pixel_index + alpha_channel]; float reciprocal_alpha = alpha ? 1.0f / alpha : 0; // unrolling this produced a 1% slowdown upscaling a large RGBA linear-space image on my machine - stb for (n = 0; n < channels; n++) if (n != alpha_channel) encode_buffer[pixel_index + n] *= reciprocal_alpha; // We added in a small epsilon to prevent the color channel from being deleted with zero alpha. // Because we only add it for integer types, it will automatically be discarded on integer // conversion, so we don't need to subtract it back out (which would be problematic for // numeric precision reasons). } } // build a table of all channels that need colorspace correction, so // we don't perform colorspace correction on channels that don't need it. for (x = 0, num_nonalpha = 0; x < channels; ++x) { if (x != alpha_channel || (stbir_info->flags & STBIR_FLAG_ALPHA_USES_COLORSPACE)) { nonalpha[num_nonalpha++] = (stbir_uint16)x; } } #define STBIR__ROUND_INT(f) ((int) ((f)+0.5)) #define STBIR__ROUND_UINT(f) ((stbir_uint32) ((f)+0.5)) #ifdef STBIR__SATURATE_INT #define STBIR__ENCODE_LINEAR8(f) stbir__saturate8 (STBIR__ROUND_INT((f) * stbir__max_uint8_as_float )) #define STBIR__ENCODE_LINEAR16(f) stbir__saturate16(STBIR__ROUND_INT((f) * stbir__max_uint16_as_float)) #else #define STBIR__ENCODE_LINEAR8(f) (unsigned char ) STBIR__ROUND_INT(stbir__saturate(f) * stbir__max_uint8_as_float ) #define STBIR__ENCODE_LINEAR16(f) (unsigned short) STBIR__ROUND_INT(stbir__saturate(f) * stbir__max_uint16_as_float) #endif switch (decode) { case STBIR__DECODE(STBIR_TYPE_UINT8, STBIR_COLORSPACE_LINEAR): for (x=0; x < num_pixels; ++x) { int pixel_index = x*channels; for (n = 0; n < channels; n++) { int index = pixel_index + n; ((unsigned char*)output_buffer)[index] = STBIR__ENCODE_LINEAR8(encode_buffer[index]); } } break; case STBIR__DECODE(STBIR_TYPE_UINT8, STBIR_COLORSPACE_SRGB): for (x=0; x < num_pixels; ++x) { int pixel_index = x*channels; for (n = 0; n < num_nonalpha; n++) { int index = pixel_index + nonalpha[n]; ((unsigned char*)output_buffer)[index] = stbir__linear_to_srgb_uchar(encode_buffer[index]); } if (!(stbir_info->flags & STBIR_FLAG_ALPHA_USES_COLORSPACE)) ((unsigned char *)output_buffer)[pixel_index + alpha_channel] = STBIR__ENCODE_LINEAR8(encode_buffer[pixel_index+alpha_channel]); } break; case STBIR__DECODE(STBIR_TYPE_UINT16, STBIR_COLORSPACE_LINEAR): for (x=0; x < num_pixels; ++x) { int pixel_index = x*channels; for (n = 0; n < channels; n++) { int index = pixel_index + n; ((unsigned short*)output_buffer)[index] = STBIR__ENCODE_LINEAR16(encode_buffer[index]); } } break; case STBIR__DECODE(STBIR_TYPE_UINT16, STBIR_COLORSPACE_SRGB): for (x=0; x < num_pixels; ++x) { int pixel_index = x*channels; for (n = 0; n < num_nonalpha; n++) { int index = pixel_index + nonalpha[n]; ((unsigned short*)output_buffer)[index] = (unsigned short)STBIR__ROUND_INT(stbir__linear_to_srgb(stbir__saturate(encode_buffer[index])) * stbir__max_uint16_as_float); } if (!(stbir_info->flags&STBIR_FLAG_ALPHA_USES_COLORSPACE)) ((unsigned short*)output_buffer)[pixel_index + alpha_channel] = STBIR__ENCODE_LINEAR16(encode_buffer[pixel_index + alpha_channel]); } break; case STBIR__DECODE(STBIR_TYPE_UINT32, STBIR_COLORSPACE_LINEAR): for (x=0; x < num_pixels; ++x) { int pixel_index = x*channels; for (n = 0; n < channels; n++) { int index = pixel_index + n; ((unsigned int*)output_buffer)[index] = (unsigned int)STBIR__ROUND_UINT(((double)stbir__saturate(encode_buffer[index])) * stbir__max_uint32_as_float); } } break; case STBIR__DECODE(STBIR_TYPE_UINT32, STBIR_COLORSPACE_SRGB): for (x=0; x < num_pixels; ++x) { int pixel_index = x*channels; for (n = 0; n < num_nonalpha; n++) { int index = pixel_index + nonalpha[n]; ((unsigned int*)output_buffer)[index] = (unsigned int)STBIR__ROUND_UINT(((double)stbir__linear_to_srgb(stbir__saturate(encode_buffer[index]))) * stbir__max_uint32_as_float); } if (!(stbir_info->flags&STBIR_FLAG_ALPHA_USES_COLORSPACE)) ((unsigned int*)output_buffer)[pixel_index + alpha_channel] = (unsigned int)STBIR__ROUND_INT(((double)stbir__saturate(encode_buffer[pixel_index + alpha_channel])) * stbir__max_uint32_as_float); } break; case STBIR__DECODE(STBIR_TYPE_FLOAT, STBIR_COLORSPACE_LINEAR): for (x=0; x < num_pixels; ++x) { int pixel_index = x*channels; for (n = 0; n < channels; n++) { int index = pixel_index + n; ((float*)output_buffer)[index] = encode_buffer[index]; } } break; case STBIR__DECODE(STBIR_TYPE_FLOAT, STBIR_COLORSPACE_SRGB): for (x=0; x < num_pixels; ++x) { int pixel_index = x*channels; for (n = 0; n < num_nonalpha; n++) { int index = pixel_index + nonalpha[n]; ((float*)output_buffer)[index] = stbir__linear_to_srgb(encode_buffer[index]); } if (!(stbir_info->flags&STBIR_FLAG_ALPHA_USES_COLORSPACE)) ((float*)output_buffer)[pixel_index + alpha_channel] = encode_buffer[pixel_index + alpha_channel]; } break; default: STBIR_ASSERT(!"Unknown type/colorspace/channels combination."); break; } } static void stbir__resample_vertical_upsample(stbir__info* stbir_info, int n) { int x, k; int output_w = stbir_info->output_w; stbir__contributors* vertical_contributors = stbir_info->vertical_contributors; float* vertical_coefficients = stbir_info->vertical_coefficients; int channels = stbir_info->channels; int alpha_channel = stbir_info->alpha_channel; int type = stbir_info->type; int colorspace = stbir_info->colorspace; int ring_buffer_entries = stbir_info->ring_buffer_num_entries; void* output_data = stbir_info->output_data; float* encode_buffer = stbir_info->encode_buffer; int decode = STBIR__DECODE(type, colorspace); int coefficient_width = stbir_info->vertical_coefficient_width; int coefficient_counter; int contributor = n; float* ring_buffer = stbir_info->ring_buffer; int ring_buffer_begin_index = stbir_info->ring_buffer_begin_index; int ring_buffer_first_scanline = stbir_info->ring_buffer_first_scanline; int ring_buffer_length = stbir_info->ring_buffer_length_bytes/sizeof(float); int n0,n1, output_row_start; int coefficient_group = coefficient_width * contributor; n0 = vertical_contributors[contributor].n0; n1 = vertical_contributors[contributor].n1; output_row_start = n * stbir_info->output_stride_bytes; STBIR_ASSERT(stbir__use_height_upsampling(stbir_info)); memset(encode_buffer, 0, output_w * sizeof(float) * channels); // I tried reblocking this for better cache usage of encode_buffer // (using x_outer, k, x_inner), but it lost speed. -- stb coefficient_counter = 0; switch (channels) { case 1: for (k = n0; k <= n1; k++) { int coefficient_index = coefficient_counter++; float* ring_buffer_entry = stbir__get_ring_buffer_scanline(k, ring_buffer, ring_buffer_begin_index, ring_buffer_first_scanline, ring_buffer_entries, ring_buffer_length); float coefficient = vertical_coefficients[coefficient_group + coefficient_index]; for (x = 0; x < output_w; ++x) { int in_pixel_index = x * 1; encode_buffer[in_pixel_index + 0] += ring_buffer_entry[in_pixel_index + 0] * coefficient; } } break; case 2: for (k = n0; k <= n1; k++) { int coefficient_index = coefficient_counter++; float* ring_buffer_entry = stbir__get_ring_buffer_scanline(k, ring_buffer, ring_buffer_begin_index, ring_buffer_first_scanline, ring_buffer_entries, ring_buffer_length); float coefficient = vertical_coefficients[coefficient_group + coefficient_index]; for (x = 0; x < output_w; ++x) { int in_pixel_index = x * 2; encode_buffer[in_pixel_index + 0] += ring_buffer_entry[in_pixel_index + 0] * coefficient; encode_buffer[in_pixel_index + 1] += ring_buffer_entry[in_pixel_index + 1] * coefficient; } } break; case 3: for (k = n0; k <= n1; k++) { int coefficient_index = coefficient_counter++; float* ring_buffer_entry = stbir__get_ring_buffer_scanline(k, ring_buffer, ring_buffer_begin_index, ring_buffer_first_scanline, ring_buffer_entries, ring_buffer_length); float coefficient = vertical_coefficients[coefficient_group + coefficient_index]; for (x = 0; x < output_w; ++x) { int in_pixel_index = x * 3; encode_buffer[in_pixel_index + 0] += ring_buffer_entry[in_pixel_index + 0] * coefficient; encode_buffer[in_pixel_index + 1] += ring_buffer_entry[in_pixel_index + 1] * coefficient; encode_buffer[in_pixel_index + 2] += ring_buffer_entry[in_pixel_index + 2] * coefficient; } } break; case 4: for (k = n0; k <= n1; k++) { int coefficient_index = coefficient_counter++; float* ring_buffer_entry = stbir__get_ring_buffer_scanline(k, ring_buffer, ring_buffer_begin_index, ring_buffer_first_scanline, ring_buffer_entries, ring_buffer_length); float coefficient = vertical_coefficients[coefficient_group + coefficient_index]; for (x = 0; x < output_w; ++x) { int in_pixel_index = x * 4; encode_buffer[in_pixel_index + 0] += ring_buffer_entry[in_pixel_index + 0] * coefficient; encode_buffer[in_pixel_index + 1] += ring_buffer_entry[in_pixel_index + 1] * coefficient; encode_buffer[in_pixel_index + 2] += ring_buffer_entry[in_pixel_index + 2] * coefficient; encode_buffer[in_pixel_index + 3] += ring_buffer_entry[in_pixel_index + 3] * coefficient; } } break; default: for (k = n0; k <= n1; k++) { int coefficient_index = coefficient_counter++; float* ring_buffer_entry = stbir__get_ring_buffer_scanline(k, ring_buffer, ring_buffer_begin_index, ring_buffer_first_scanline, ring_buffer_entries, ring_buffer_length); float coefficient = vertical_coefficients[coefficient_group + coefficient_index]; for (x = 0; x < output_w; ++x) { int in_pixel_index = x * channels; int c; for (c = 0; c < channels; c++) encode_buffer[in_pixel_index + c] += ring_buffer_entry[in_pixel_index + c] * coefficient; } } break; } stbir__encode_scanline(stbir_info, output_w, (char *) output_data + output_row_start, encode_buffer, channels, alpha_channel, decode); } static void stbir__resample_vertical_downsample(stbir__info* stbir_info, int n) { int x, k; int output_w = stbir_info->output_w; stbir__contributors* vertical_contributors = stbir_info->vertical_contributors; float* vertical_coefficients = stbir_info->vertical_coefficients; int channels = stbir_info->channels; int ring_buffer_entries = stbir_info->ring_buffer_num_entries; float* horizontal_buffer = stbir_info->horizontal_buffer; int coefficient_width = stbir_info->vertical_coefficient_width; int contributor = n + stbir_info->vertical_filter_pixel_margin; float* ring_buffer = stbir_info->ring_buffer; int ring_buffer_begin_index = stbir_info->ring_buffer_begin_index; int ring_buffer_first_scanline = stbir_info->ring_buffer_first_scanline; int ring_buffer_length = stbir_info->ring_buffer_length_bytes/sizeof(float); int n0,n1; n0 = vertical_contributors[contributor].n0; n1 = vertical_contributors[contributor].n1; STBIR_ASSERT(!stbir__use_height_upsampling(stbir_info)); for (k = n0; k <= n1; k++) { int coefficient_index = k - n0; int coefficient_group = coefficient_width * contributor; float coefficient = vertical_coefficients[coefficient_group + coefficient_index]; float* ring_buffer_entry = stbir__get_ring_buffer_scanline(k, ring_buffer, ring_buffer_begin_index, ring_buffer_first_scanline, ring_buffer_entries, ring_buffer_length); switch (channels) { case 1: for (x = 0; x < output_w; x++) { int in_pixel_index = x * 1; ring_buffer_entry[in_pixel_index + 0] += horizontal_buffer[in_pixel_index + 0] * coefficient; } break; case 2: for (x = 0; x < output_w; x++) { int in_pixel_index = x * 2; ring_buffer_entry[in_pixel_index + 0] += horizontal_buffer[in_pixel_index + 0] * coefficient; ring_buffer_entry[in_pixel_index + 1] += horizontal_buffer[in_pixel_index + 1] * coefficient; } break; case 3: for (x = 0; x < output_w; x++) { int in_pixel_index = x * 3; ring_buffer_entry[in_pixel_index + 0] += horizontal_buffer[in_pixel_index + 0] * coefficient; ring_buffer_entry[in_pixel_index + 1] += horizontal_buffer[in_pixel_index + 1] * coefficient; ring_buffer_entry[in_pixel_index + 2] += horizontal_buffer[in_pixel_index + 2] * coefficient; } break; case 4: for (x = 0; x < output_w; x++) { int in_pixel_index = x * 4; ring_buffer_entry[in_pixel_index + 0] += horizontal_buffer[in_pixel_index + 0] * coefficient; ring_buffer_entry[in_pixel_index + 1] += horizontal_buffer[in_pixel_index + 1] * coefficient; ring_buffer_entry[in_pixel_index + 2] += horizontal_buffer[in_pixel_index + 2] * coefficient; ring_buffer_entry[in_pixel_index + 3] += horizontal_buffer[in_pixel_index + 3] * coefficient; } break; default: for (x = 0; x < output_w; x++) { int in_pixel_index = x * channels; int c; for (c = 0; c < channels; c++) ring_buffer_entry[in_pixel_index + c] += horizontal_buffer[in_pixel_index + c] * coefficient; } break; } } } static void stbir__buffer_loop_upsample(stbir__info* stbir_info) { int y; float scale_ratio = stbir_info->vertical_scale; float out_scanlines_radius = stbir__filter_info_table[stbir_info->vertical_filter].support(1/scale_ratio) * scale_ratio; STBIR_ASSERT(stbir__use_height_upsampling(stbir_info)); for (y = 0; y < stbir_info->output_h; y++) { float in_center_of_out = 0; // Center of the current out scanline in the in scanline space int in_first_scanline = 0, in_last_scanline = 0; stbir__calculate_sample_range_upsample(y, out_scanlines_radius, scale_ratio, stbir_info->vertical_shift, &in_first_scanline, &in_last_scanline, &in_center_of_out); STBIR_ASSERT(in_last_scanline - in_first_scanline + 1 <= stbir_info->ring_buffer_num_entries); if (stbir_info->ring_buffer_begin_index >= 0) { // Get rid of whatever we don't need anymore. while (in_first_scanline > stbir_info->ring_buffer_first_scanline) { if (stbir_info->ring_buffer_first_scanline == stbir_info->ring_buffer_last_scanline) { // We just popped the last scanline off the ring buffer. // Reset it to the empty state. stbir_info->ring_buffer_begin_index = -1; stbir_info->ring_buffer_first_scanline = 0; stbir_info->ring_buffer_last_scanline = 0; break; } else { stbir_info->ring_buffer_first_scanline++; stbir_info->ring_buffer_begin_index = (stbir_info->ring_buffer_begin_index + 1) % stbir_info->ring_buffer_num_entries; } } } // Load in new ones. if (stbir_info->ring_buffer_begin_index < 0) stbir__decode_and_resample_upsample(stbir_info, in_first_scanline); while (in_last_scanline > stbir_info->ring_buffer_last_scanline) stbir__decode_and_resample_upsample(stbir_info, stbir_info->ring_buffer_last_scanline + 1); // Now all buffers should be ready to write a row of vertical sampling. stbir__resample_vertical_upsample(stbir_info, y); STBIR_PROGRESS_REPORT((float)y / stbir_info->output_h); } } static void stbir__empty_ring_buffer(stbir__info* stbir_info, int first_necessary_scanline) { int output_stride_bytes = stbir_info->output_stride_bytes; int channels = stbir_info->channels; int alpha_channel = stbir_info->alpha_channel; int type = stbir_info->type; int colorspace = stbir_info->colorspace; int output_w = stbir_info->output_w; void* output_data = stbir_info->output_data; int decode = STBIR__DECODE(type, colorspace); float* ring_buffer = stbir_info->ring_buffer; int ring_buffer_length = stbir_info->ring_buffer_length_bytes/sizeof(float); if (stbir_info->ring_buffer_begin_index >= 0) { // Get rid of whatever we don't need anymore. while (first_necessary_scanline > stbir_info->ring_buffer_first_scanline) { if (stbir_info->ring_buffer_first_scanline >= 0 && stbir_info->ring_buffer_first_scanline < stbir_info->output_h) { int output_row_start = stbir_info->ring_buffer_first_scanline * output_stride_bytes; float* ring_buffer_entry = stbir__get_ring_buffer_entry(ring_buffer, stbir_info->ring_buffer_begin_index, ring_buffer_length); stbir__encode_scanline(stbir_info, output_w, (char *) output_data + output_row_start, ring_buffer_entry, channels, alpha_channel, decode); STBIR_PROGRESS_REPORT((float)stbir_info->ring_buffer_first_scanline / stbir_info->output_h); } if (stbir_info->ring_buffer_first_scanline == stbir_info->ring_buffer_last_scanline) { // We just popped the last scanline off the ring buffer. // Reset it to the empty state. stbir_info->ring_buffer_begin_index = -1; stbir_info->ring_buffer_first_scanline = 0; stbir_info->ring_buffer_last_scanline = 0; break; } else { stbir_info->ring_buffer_first_scanline++; stbir_info->ring_buffer_begin_index = (stbir_info->ring_buffer_begin_index + 1) % stbir_info->ring_buffer_num_entries; } } } } static void stbir__buffer_loop_downsample(stbir__info* stbir_info) { int y; float scale_ratio = stbir_info->vertical_scale; int output_h = stbir_info->output_h; float in_pixels_radius = stbir__filter_info_table[stbir_info->vertical_filter].support(scale_ratio) / scale_ratio; int pixel_margin = stbir_info->vertical_filter_pixel_margin; int max_y = stbir_info->input_h + pixel_margin; STBIR_ASSERT(!stbir__use_height_upsampling(stbir_info)); for (y = -pixel_margin; y < max_y; y++) { float out_center_of_in; // Center of the current out scanline in the in scanline space int out_first_scanline, out_last_scanline; stbir__calculate_sample_range_downsample(y, in_pixels_radius, scale_ratio, stbir_info->vertical_shift, &out_first_scanline, &out_last_scanline, &out_center_of_in); STBIR_ASSERT(out_last_scanline - out_first_scanline + 1 <= stbir_info->ring_buffer_num_entries); if (out_last_scanline < 0 || out_first_scanline >= output_h) continue; stbir__empty_ring_buffer(stbir_info, out_first_scanline); stbir__decode_and_resample_downsample(stbir_info, y); // Load in new ones. if (stbir_info->ring_buffer_begin_index < 0) stbir__add_empty_ring_buffer_entry(stbir_info, out_first_scanline); while (out_last_scanline > stbir_info->ring_buffer_last_scanline) stbir__add_empty_ring_buffer_entry(stbir_info, stbir_info->ring_buffer_last_scanline + 1); // Now the horizontal buffer is ready to write to all ring buffer rows. stbir__resample_vertical_downsample(stbir_info, y); } stbir__empty_ring_buffer(stbir_info, stbir_info->output_h); } static void stbir__setup(stbir__info *info, int input_w, int input_h, int output_w, int output_h, int channels) { info->input_w = input_w; info->input_h = input_h; info->output_w = output_w; info->output_h = output_h; info->channels = channels; } static void stbir__calculate_transform(stbir__info *info, float s0, float t0, float s1, float t1, float *transform) { info->s0 = s0; info->t0 = t0; info->s1 = s1; info->t1 = t1; if (transform) { info->horizontal_scale = transform[0]; info->vertical_scale = transform[1]; info->horizontal_shift = transform[2]; info->vertical_shift = transform[3]; } else { info->horizontal_scale = ((float)info->output_w / info->input_w) / (s1 - s0); info->vertical_scale = ((float)info->output_h / info->input_h) / (t1 - t0); info->horizontal_shift = s0 * info->output_w / (s1 - s0); info->vertical_shift = t0 * info->output_h / (t1 - t0); } } static void stbir__choose_filter(stbir__info *info, stbir_filter h_filter, stbir_filter v_filter) { if (h_filter == 0) h_filter = stbir__use_upsampling(info->horizontal_scale) ? STBIR_DEFAULT_FILTER_UPSAMPLE : STBIR_DEFAULT_FILTER_DOWNSAMPLE; if (v_filter == 0) v_filter = stbir__use_upsampling(info->vertical_scale) ? STBIR_DEFAULT_FILTER_UPSAMPLE : STBIR_DEFAULT_FILTER_DOWNSAMPLE; info->horizontal_filter = h_filter; info->vertical_filter = v_filter; } static stbir_uint32 stbir__calculate_memory(stbir__info *info) { int pixel_margin = stbir__get_filter_pixel_margin(info->horizontal_filter, info->horizontal_scale); int filter_height = stbir__get_filter_pixel_width(info->vertical_filter, info->vertical_scale); info->horizontal_num_contributors = stbir__get_contributors(info->horizontal_scale, info->horizontal_filter, info->input_w, info->output_w); info->vertical_num_contributors = stbir__get_contributors(info->vertical_scale , info->vertical_filter , info->input_h, info->output_h); // One extra entry because floating point precision problems sometimes cause an extra to be necessary. info->ring_buffer_num_entries = filter_height + 1; info->horizontal_contributors_size = info->horizontal_num_contributors * sizeof(stbir__contributors); info->horizontal_coefficients_size = stbir__get_total_horizontal_coefficients(info) * sizeof(float); info->vertical_contributors_size = info->vertical_num_contributors * sizeof(stbir__contributors); info->vertical_coefficients_size = stbir__get_total_vertical_coefficients(info) * sizeof(float); info->decode_buffer_size = (info->input_w + pixel_margin * 2) * info->channels * sizeof(float); info->horizontal_buffer_size = info->output_w * info->channels * sizeof(float); info->ring_buffer_size = info->output_w * info->channels * info->ring_buffer_num_entries * sizeof(float); info->encode_buffer_size = info->output_w * info->channels * sizeof(float); STBIR_ASSERT(info->horizontal_filter != 0); STBIR_ASSERT(info->horizontal_filter < STBIR__ARRAY_SIZE(stbir__filter_info_table)); // this now happens too late STBIR_ASSERT(info->vertical_filter != 0); STBIR_ASSERT(info->vertical_filter < STBIR__ARRAY_SIZE(stbir__filter_info_table)); // this now happens too late if (stbir__use_height_upsampling(info)) // The horizontal buffer is for when we're downsampling the height and we // can't output the result of sampling the decode buffer directly into the // ring buffers. info->horizontal_buffer_size = 0; else // The encode buffer is to retain precision in the height upsampling method // and isn't used when height downsampling. info->encode_buffer_size = 0; return info->horizontal_contributors_size + info->horizontal_coefficients_size + info->vertical_contributors_size + info->vertical_coefficients_size + info->decode_buffer_size + info->horizontal_buffer_size + info->ring_buffer_size + info->encode_buffer_size; } static int stbir__resize_allocated(stbir__info *info, const void* input_data, int input_stride_in_bytes, void* output_data, int output_stride_in_bytes, int alpha_channel, stbir_uint32 flags, stbir_datatype type, stbir_edge edge_horizontal, stbir_edge edge_vertical, stbir_colorspace colorspace, void* tempmem, size_t tempmem_size_in_bytes) { size_t memory_required = stbir__calculate_memory(info); int width_stride_input = input_stride_in_bytes ? input_stride_in_bytes : info->channels * info->input_w * stbir__type_size[type]; int width_stride_output = output_stride_in_bytes ? output_stride_in_bytes : info->channels * info->output_w * stbir__type_size[type]; #ifdef STBIR_DEBUG_OVERWRITE_TEST #define OVERWRITE_ARRAY_SIZE 8 unsigned char overwrite_output_before_pre[OVERWRITE_ARRAY_SIZE]; unsigned char overwrite_tempmem_before_pre[OVERWRITE_ARRAY_SIZE]; unsigned char overwrite_output_after_pre[OVERWRITE_ARRAY_SIZE]; unsigned char overwrite_tempmem_after_pre[OVERWRITE_ARRAY_SIZE]; size_t begin_forbidden = width_stride_output * (info->output_h - 1) + info->output_w * info->channels * stbir__type_size[type]; memcpy(overwrite_output_before_pre, &((unsigned char*)output_data)[-OVERWRITE_ARRAY_SIZE], OVERWRITE_ARRAY_SIZE); memcpy(overwrite_output_after_pre, &((unsigned char*)output_data)[begin_forbidden], OVERWRITE_ARRAY_SIZE); memcpy(overwrite_tempmem_before_pre, &((unsigned char*)tempmem)[-OVERWRITE_ARRAY_SIZE], OVERWRITE_ARRAY_SIZE); memcpy(overwrite_tempmem_after_pre, &((unsigned char*)tempmem)[tempmem_size_in_bytes], OVERWRITE_ARRAY_SIZE); #endif STBIR_ASSERT(info->channels >= 0); STBIR_ASSERT(info->channels <= STBIR_MAX_CHANNELS); if (info->channels < 0 || info->channels > STBIR_MAX_CHANNELS) return 0; STBIR_ASSERT(info->horizontal_filter < STBIR__ARRAY_SIZE(stbir__filter_info_table)); STBIR_ASSERT(info->vertical_filter < STBIR__ARRAY_SIZE(stbir__filter_info_table)); if (info->horizontal_filter >= STBIR__ARRAY_SIZE(stbir__filter_info_table)) return 0; if (info->vertical_filter >= STBIR__ARRAY_SIZE(stbir__filter_info_table)) return 0; if (alpha_channel < 0) flags |= STBIR_FLAG_ALPHA_USES_COLORSPACE | STBIR_FLAG_ALPHA_PREMULTIPLIED; if (!(flags&STBIR_FLAG_ALPHA_USES_COLORSPACE) || !(flags&STBIR_FLAG_ALPHA_PREMULTIPLIED)) { STBIR_ASSERT(alpha_channel >= 0 && alpha_channel < info->channels); } if (alpha_channel >= info->channels) return 0; STBIR_ASSERT(tempmem); if (!tempmem) return 0; STBIR_ASSERT(tempmem_size_in_bytes >= memory_required); if (tempmem_size_in_bytes < memory_required) return 0; memset(tempmem, 0, tempmem_size_in_bytes); info->input_data = input_data; info->input_stride_bytes = width_stride_input; info->output_data = output_data; info->output_stride_bytes = width_stride_output; info->alpha_channel = alpha_channel; info->flags = flags; info->type = type; info->edge_horizontal = edge_horizontal; info->edge_vertical = edge_vertical; info->colorspace = colorspace; info->horizontal_coefficient_width = stbir__get_coefficient_width (info->horizontal_filter, info->horizontal_scale); info->vertical_coefficient_width = stbir__get_coefficient_width (info->vertical_filter , info->vertical_scale ); info->horizontal_filter_pixel_width = stbir__get_filter_pixel_width (info->horizontal_filter, info->horizontal_scale); info->vertical_filter_pixel_width = stbir__get_filter_pixel_width (info->vertical_filter , info->vertical_scale ); info->horizontal_filter_pixel_margin = stbir__get_filter_pixel_margin(info->horizontal_filter, info->horizontal_scale); info->vertical_filter_pixel_margin = stbir__get_filter_pixel_margin(info->vertical_filter , info->vertical_scale ); info->ring_buffer_length_bytes = info->output_w * info->channels * sizeof(float); info->decode_buffer_pixels = info->input_w + info->horizontal_filter_pixel_margin * 2; #define STBIR__NEXT_MEMPTR(current, newtype) (newtype*)(((unsigned char*)current) + current##_size) info->horizontal_contributors = (stbir__contributors *) tempmem; info->horizontal_coefficients = STBIR__NEXT_MEMPTR(info->horizontal_contributors, float); info->vertical_contributors = STBIR__NEXT_MEMPTR(info->horizontal_coefficients, stbir__contributors); info->vertical_coefficients = STBIR__NEXT_MEMPTR(info->vertical_contributors, float); info->decode_buffer = STBIR__NEXT_MEMPTR(info->vertical_coefficients, float); if (stbir__use_height_upsampling(info)) { info->horizontal_buffer = NULL; info->ring_buffer = STBIR__NEXT_MEMPTR(info->decode_buffer, float); info->encode_buffer = STBIR__NEXT_MEMPTR(info->ring_buffer, float); STBIR_ASSERT((size_t)STBIR__NEXT_MEMPTR(info->encode_buffer, unsigned char) == (size_t)tempmem + tempmem_size_in_bytes); } else { info->horizontal_buffer = STBIR__NEXT_MEMPTR(info->decode_buffer, float); info->ring_buffer = STBIR__NEXT_MEMPTR(info->horizontal_buffer, float); info->encode_buffer = NULL; STBIR_ASSERT((size_t)STBIR__NEXT_MEMPTR(info->ring_buffer, unsigned char) == (size_t)tempmem + tempmem_size_in_bytes); } #undef STBIR__NEXT_MEMPTR // This signals that the ring buffer is empty info->ring_buffer_begin_index = -1; stbir__calculate_filters(info->horizontal_contributors, info->horizontal_coefficients, info->horizontal_filter, info->horizontal_scale, info->horizontal_shift, info->input_w, info->output_w); stbir__calculate_filters(info->vertical_contributors, info->vertical_coefficients, info->vertical_filter, info->vertical_scale, info->vertical_shift, info->input_h, info->output_h); STBIR_PROGRESS_REPORT(0); if (stbir__use_height_upsampling(info)) stbir__buffer_loop_upsample(info); else stbir__buffer_loop_downsample(info); STBIR_PROGRESS_REPORT(1); #ifdef STBIR_DEBUG_OVERWRITE_TEST STBIR_ASSERT(memcmp(overwrite_output_before_pre, &((unsigned char*)output_data)[-OVERWRITE_ARRAY_SIZE], OVERWRITE_ARRAY_SIZE) == 0); STBIR_ASSERT(memcmp(overwrite_output_after_pre, &((unsigned char*)output_data)[begin_forbidden], OVERWRITE_ARRAY_SIZE) == 0); STBIR_ASSERT(memcmp(overwrite_tempmem_before_pre, &((unsigned char*)tempmem)[-OVERWRITE_ARRAY_SIZE], OVERWRITE_ARRAY_SIZE) == 0); STBIR_ASSERT(memcmp(overwrite_tempmem_after_pre, &((unsigned char*)tempmem)[tempmem_size_in_bytes], OVERWRITE_ARRAY_SIZE) == 0); #endif return 1; } static int stbir__resize_arbitrary( void *alloc_context, const void* input_data, int input_w, int input_h, int input_stride_in_bytes, void* output_data, int output_w, int output_h, int output_stride_in_bytes, float s0, float t0, float s1, float t1, float *transform, int channels, int alpha_channel, stbir_uint32 flags, stbir_datatype type, stbir_filter h_filter, stbir_filter v_filter, stbir_edge edge_horizontal, stbir_edge edge_vertical, stbir_colorspace colorspace) { stbir__info info; int result; size_t memory_required; void* extra_memory; stbir__setup(&info, input_w, input_h, output_w, output_h, channels); stbir__calculate_transform(&info, s0,t0,s1,t1,transform); stbir__choose_filter(&info, h_filter, v_filter); memory_required = stbir__calculate_memory(&info); extra_memory = STBIR_MALLOC(memory_required, alloc_context); if (!extra_memory) return 0; result = stbir__resize_allocated(&info, input_data, input_stride_in_bytes, output_data, output_stride_in_bytes, alpha_channel, flags, type, edge_horizontal, edge_vertical, colorspace, extra_memory, memory_required); STBIR_FREE(extra_memory, alloc_context); return result; } STBIRDEF int stbir_resize_uint8( const unsigned char *input_pixels , int input_w , int input_h , int input_stride_in_bytes, unsigned char *output_pixels, int output_w, int output_h, int output_stride_in_bytes, int num_channels) { return stbir__resize_arbitrary(NULL, input_pixels, input_w, input_h, input_stride_in_bytes, output_pixels, output_w, output_h, output_stride_in_bytes, 0,0,1,1,NULL,num_channels,-1,0, STBIR_TYPE_UINT8, STBIR_FILTER_DEFAULT, STBIR_FILTER_DEFAULT, STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_COLORSPACE_LINEAR); } STBIRDEF int stbir_resize_float( const float *input_pixels , int input_w , int input_h , int input_stride_in_bytes, float *output_pixels, int output_w, int output_h, int output_stride_in_bytes, int num_channels) { return stbir__resize_arbitrary(NULL, input_pixels, input_w, input_h, input_stride_in_bytes, output_pixels, output_w, output_h, output_stride_in_bytes, 0,0,1,1,NULL,num_channels,-1,0, STBIR_TYPE_FLOAT, STBIR_FILTER_DEFAULT, STBIR_FILTER_DEFAULT, STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_COLORSPACE_LINEAR); } STBIRDEF int stbir_resize_uint8_srgb(const unsigned char *input_pixels , int input_w , int input_h , int input_stride_in_bytes, unsigned char *output_pixels, int output_w, int output_h, int output_stride_in_bytes, int num_channels, int alpha_channel, int flags) { return stbir__resize_arbitrary(NULL, input_pixels, input_w, input_h, input_stride_in_bytes, output_pixels, output_w, output_h, output_stride_in_bytes, 0,0,1,1,NULL,num_channels,alpha_channel,flags, STBIR_TYPE_UINT8, STBIR_FILTER_DEFAULT, STBIR_FILTER_DEFAULT, STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_COLORSPACE_SRGB); } STBIRDEF int stbir_resize_uint8_srgb_edgemode(const unsigned char *input_pixels , int input_w , int input_h , int input_stride_in_bytes, unsigned char *output_pixels, int output_w, int output_h, int output_stride_in_bytes, int num_channels, int alpha_channel, int flags, stbir_edge edge_wrap_mode) { return stbir__resize_arbitrary(NULL, input_pixels, input_w, input_h, input_stride_in_bytes, output_pixels, output_w, output_h, output_stride_in_bytes, 0,0,1,1,NULL,num_channels,alpha_channel,flags, STBIR_TYPE_UINT8, STBIR_FILTER_DEFAULT, STBIR_FILTER_DEFAULT, edge_wrap_mode, edge_wrap_mode, STBIR_COLORSPACE_SRGB); } STBIRDEF int stbir_resize_uint8_generic( const unsigned char *input_pixels , int input_w , int input_h , int input_stride_in_bytes, unsigned char *output_pixels, int output_w, int output_h, int output_stride_in_bytes, int num_channels, int alpha_channel, int flags, stbir_edge edge_wrap_mode, stbir_filter filter, stbir_colorspace space, void *alloc_context) { return stbir__resize_arbitrary(alloc_context, input_pixels, input_w, input_h, input_stride_in_bytes, output_pixels, output_w, output_h, output_stride_in_bytes, 0,0,1,1,NULL,num_channels,alpha_channel,flags, STBIR_TYPE_UINT8, filter, filter, edge_wrap_mode, edge_wrap_mode, space); } STBIRDEF int stbir_resize_uint16_generic(const stbir_uint16 *input_pixels , int input_w , int input_h , int input_stride_in_bytes, stbir_uint16 *output_pixels , int output_w, int output_h, int output_stride_in_bytes, int num_channels, int alpha_channel, int flags, stbir_edge edge_wrap_mode, stbir_filter filter, stbir_colorspace space, void *alloc_context) { return stbir__resize_arbitrary(alloc_context, input_pixels, input_w, input_h, input_stride_in_bytes, output_pixels, output_w, output_h, output_stride_in_bytes, 0,0,1,1,NULL,num_channels,alpha_channel,flags, STBIR_TYPE_UINT16, filter, filter, edge_wrap_mode, edge_wrap_mode, space); } STBIRDEF int stbir_resize_float_generic( const float *input_pixels , int input_w , int input_h , int input_stride_in_bytes, float *output_pixels , int output_w, int output_h, int output_stride_in_bytes, int num_channels, int alpha_channel, int flags, stbir_edge edge_wrap_mode, stbir_filter filter, stbir_colorspace space, void *alloc_context) { return stbir__resize_arbitrary(alloc_context, input_pixels, input_w, input_h, input_stride_in_bytes, output_pixels, output_w, output_h, output_stride_in_bytes, 0,0,1,1,NULL,num_channels,alpha_channel,flags, STBIR_TYPE_FLOAT, filter, filter, edge_wrap_mode, edge_wrap_mode, space); } STBIRDEF int stbir_resize( const void *input_pixels , int input_w , int input_h , int input_stride_in_bytes, void *output_pixels, int output_w, int output_h, int output_stride_in_bytes, stbir_datatype datatype, int num_channels, int alpha_channel, int flags, stbir_edge edge_mode_horizontal, stbir_edge edge_mode_vertical, stbir_filter filter_horizontal, stbir_filter filter_vertical, stbir_colorspace space, void *alloc_context) { return stbir__resize_arbitrary(alloc_context, input_pixels, input_w, input_h, input_stride_in_bytes, output_pixels, output_w, output_h, output_stride_in_bytes, 0,0,1,1,NULL,num_channels,alpha_channel,flags, datatype, filter_horizontal, filter_vertical, edge_mode_horizontal, edge_mode_vertical, space); } STBIRDEF int stbir_resize_subpixel(const void *input_pixels , int input_w , int input_h , int input_stride_in_bytes, void *output_pixels, int output_w, int output_h, int output_stride_in_bytes, stbir_datatype datatype, int num_channels, int alpha_channel, int flags, stbir_edge edge_mode_horizontal, stbir_edge edge_mode_vertical, stbir_filter filter_horizontal, stbir_filter filter_vertical, stbir_colorspace space, void *alloc_context, float x_scale, float y_scale, float x_offset, float y_offset) { float transform[4]; transform[0] = x_scale; transform[1] = y_scale; transform[2] = x_offset; transform[3] = y_offset; return stbir__resize_arbitrary(alloc_context, input_pixels, input_w, input_h, input_stride_in_bytes, output_pixels, output_w, output_h, output_stride_in_bytes, 0,0,1,1,transform,num_channels,alpha_channel,flags, datatype, filter_horizontal, filter_vertical, edge_mode_horizontal, edge_mode_vertical, space); } STBIRDEF int stbir_resize_region( const void *input_pixels , int input_w , int input_h , int input_stride_in_bytes, void *output_pixels, int output_w, int output_h, int output_stride_in_bytes, stbir_datatype datatype, int num_channels, int alpha_channel, int flags, stbir_edge edge_mode_horizontal, stbir_edge edge_mode_vertical, stbir_filter filter_horizontal, stbir_filter filter_vertical, stbir_colorspace space, void *alloc_context, float s0, float t0, float s1, float t1) { return stbir__resize_arbitrary(alloc_context, input_pixels, input_w, input_h, input_stride_in_bytes, output_pixels, output_w, output_h, output_stride_in_bytes, s0,t0,s1,t1,NULL,num_channels,alpha_channel,flags, datatype, filter_horizontal, filter_vertical, edge_mode_horizontal, edge_mode_vertical, space); } #endif // STB_IMAGE_RESIZE_IMPLEMENTATION /* ------------------------------------------------------------------------------ This software is available under 2 licenses -- choose whichever you prefer. ------------------------------------------------------------------------------ ALTERNATIVE A - MIT License Copyright (c) 2017 Sean Barrett Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------ ALTERNATIVE B - Public Domain (www.unlicense.org) This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------ */
0
repos/simulations/libs/zstbi/libs
repos/simulations/libs/zstbi/libs/stbi/stb_image.h
/* stb_image - v2.28 - public domain image loader - http://nothings.org/stb no warranty implied; use at your own risk Do this: #define STB_IMAGE_IMPLEMENTATION before you include this file in *one* C or C++ file to create the implementation. // i.e. it should look like this: #include ... #include ... #include ... #define STB_IMAGE_IMPLEMENTATION #include "stb_image.h" You can #define STBI_ASSERT(x) before the #include to avoid using assert.h. And #define STBI_MALLOC, STBI_REALLOC, and STBI_FREE to avoid using malloc,realloc,free QUICK NOTES: Primarily of interest to game developers and other people who can avoid problematic images and only need the trivial interface JPEG baseline & progressive (12 bpc/arithmetic not supported, same as stock IJG lib) PNG 1/2/4/8/16-bit-per-channel TGA (not sure what subset, if a subset) BMP non-1bpp, non-RLE PSD (composited view only, no extra channels, 8/16 bit-per-channel) GIF (*comp always reports as 4-channel) HDR (radiance rgbE format) PIC (Softimage PIC) PNM (PPM and PGM binary only) Animated GIF still needs a proper API, but here's one way to do it: http://gist.github.com/urraka/685d9a6340b26b830d49 - decode from memory or through FILE (define STBI_NO_STDIO to remove code) - decode from arbitrary I/O callbacks - SIMD acceleration on x86/x64 (SSE2) and ARM (NEON) Full documentation under "DOCUMENTATION" below. LICENSE See end of file for license information. RECENT REVISION HISTORY: 2.28 (2023-01-29) many error fixes, security errors, just tons of stuff 2.27 (2021-07-11) document stbi_info better, 16-bit PNM support, bug fixes 2.26 (2020-07-13) many minor fixes 2.25 (2020-02-02) fix warnings 2.24 (2020-02-02) fix warnings; thread-local failure_reason and flip_vertically 2.23 (2019-08-11) fix clang static analysis warning 2.22 (2019-03-04) gif fixes, fix warnings 2.21 (2019-02-25) fix typo in comment 2.20 (2019-02-07) support utf8 filenames in Windows; fix warnings and platform ifdefs 2.19 (2018-02-11) fix warning 2.18 (2018-01-30) fix warnings 2.17 (2018-01-29) bugfix, 1-bit BMP, 16-bitness query, fix warnings 2.16 (2017-07-23) all functions have 16-bit variants; optimizations; bugfixes 2.15 (2017-03-18) fix png-1,2,4; all Imagenet JPGs; no runtime SSE detection on GCC 2.14 (2017-03-03) remove deprecated STBI_JPEG_OLD; fixes for Imagenet JPGs 2.13 (2016-12-04) experimental 16-bit API, only for PNG so far; fixes 2.12 (2016-04-02) fix typo in 2.11 PSD fix that caused crashes 2.11 (2016-04-02) 16-bit PNGS; enable SSE2 in non-gcc x64 RGB-format JPEG; remove white matting in PSD; allocate large structures on the stack; correct channel count for PNG & BMP 2.10 (2016-01-22) avoid warning introduced in 2.09 2.09 (2016-01-16) 16-bit TGA; comments in PNM files; STBI_REALLOC_SIZED See end of file for full revision history. ============================ Contributors ========================= Image formats Extensions, features Sean Barrett (jpeg, png, bmp) Jetro Lauha (stbi_info) Nicolas Schulz (hdr, psd) Martin "SpartanJ" Golini (stbi_info) Jonathan Dummer (tga) James "moose2000" Brown (iPhone PNG) Jean-Marc Lienher (gif) Ben "Disch" Wenger (io callbacks) Tom Seddon (pic) Omar Cornut (1/2/4-bit PNG) Thatcher Ulrich (psd) Nicolas Guillemot (vertical flip) Ken Miller (pgm, ppm) Richard Mitton (16-bit PSD) github:urraka (animated gif) Junggon Kim (PNM comments) Christopher Forseth (animated gif) Daniel Gibson (16-bit TGA) socks-the-fox (16-bit PNG) Jeremy Sawicki (handle all ImageNet JPGs) Optimizations & bugfixes Mikhail Morozov (1-bit BMP) Fabian "ryg" Giesen Anael Seghezzi (is-16-bit query) Arseny Kapoulkine Simon Breuss (16-bit PNM) John-Mark Allen Carmelo J Fdez-Aguera Bug & warning fixes Marc LeBlanc David Woo Guillaume George Martins Mozeiko Christpher Lloyd Jerry Jansson Joseph Thomson Blazej Dariusz Roszkowski Phil Jordan Dave Moore Roy Eltham Hayaki Saito Nathan Reed Won Chun Luke Graham Johan Duparc Nick Verigakis the Horde3D community Thomas Ruf Ronny Chevalier github:rlyeh Janez Zemva John Bartholomew Michal Cichon github:romigrou Jonathan Blow Ken Hamada Tero Hanninen github:svdijk Eugene Golushkov Laurent Gomila Cort Stratton github:snagar Aruelien Pocheville Sergio Gonzalez Thibault Reuille github:Zelex Cass Everitt Ryamond Barbiero github:grim210 Paul Du Bois Engin Manap Aldo Culquicondor github:sammyhw Philipp Wiesemann Dale Weiler Oriol Ferrer Mesia github:phprus Josh Tobin Neil Bickford Matthew Gregan github:poppolopoppo Julian Raschke Gregory Mullen Christian Floisand github:darealshinji Baldur Karlsson Kevin Schmidt JR Smith github:Michaelangel007 Brad Weinberger Matvey Cherevko github:mosra Luca Sas Alexander Veselov Zack Middleton [reserved] Ryan C. Gordon [reserved] [reserved] DO NOT ADD YOUR NAME HERE Jacko Dirks To add your name to the credits, pick a random blank space in the middle and fill it. 80% of merge conflicts on stb PRs are due to people adding their name at the end of the credits. */ #ifndef STBI_INCLUDE_STB_IMAGE_H #define STBI_INCLUDE_STB_IMAGE_H // DOCUMENTATION // // Limitations: // - no 12-bit-per-channel JPEG // - no JPEGs with arithmetic coding // - GIF always returns *comp=4 // // Basic usage (see HDR discussion below for HDR usage): // int x,y,n; // unsigned char *data = stbi_load(filename, &x, &y, &n, 0); // // ... process data if not NULL ... // // ... x = width, y = height, n = # 8-bit components per pixel ... // // ... replace '0' with '1'..'4' to force that many components per pixel // // ... but 'n' will always be the number that it would have been if you said 0 // stbi_image_free(data); // // Standard parameters: // int *x -- outputs image width in pixels // int *y -- outputs image height in pixels // int *channels_in_file -- outputs # of image components in image file // int desired_channels -- if non-zero, # of image components requested in result // // The return value from an image loader is an 'unsigned char *' which points // to the pixel data, or NULL on an allocation failure or if the image is // corrupt or invalid. The pixel data consists of *y scanlines of *x pixels, // with each pixel consisting of N interleaved 8-bit components; the first // pixel pointed to is top-left-most in the image. There is no padding between // image scanlines or between pixels, regardless of format. The number of // components N is 'desired_channels' if desired_channels is non-zero, or // *channels_in_file otherwise. If desired_channels is non-zero, // *channels_in_file has the number of components that _would_ have been // output otherwise. E.g. if you set desired_channels to 4, you will always // get RGBA output, but you can check *channels_in_file to see if it's trivially // opaque because e.g. there were only 3 channels in the source image. // // An output image with N components has the following components interleaved // in this order in each pixel: // // N=#comp components // 1 grey // 2 grey, alpha // 3 red, green, blue // 4 red, green, blue, alpha // // If image loading fails for any reason, the return value will be NULL, // and *x, *y, *channels_in_file will be unchanged. The function // stbi_failure_reason() can be queried for an extremely brief, end-user // unfriendly explanation of why the load failed. Define STBI_NO_FAILURE_STRINGS // to avoid compiling these strings at all, and STBI_FAILURE_USERMSG to get slightly // more user-friendly ones. // // Paletted PNG, BMP, GIF, and PIC images are automatically depalettized. // // To query the width, height and component count of an image without having to // decode the full file, you can use the stbi_info family of functions: // // int x,y,n,ok; // ok = stbi_info(filename, &x, &y, &n); // // returns ok=1 and sets x, y, n if image is a supported format, // // 0 otherwise. // // Note that stb_image pervasively uses ints in its public API for sizes, // including sizes of memory buffers. This is now part of the API and thus // hard to change without causing breakage. As a result, the various image // loaders all have certain limits on image size; these differ somewhat // by format but generally boil down to either just under 2GB or just under // 1GB. When the decoded image would be larger than this, stb_image decoding // will fail. // // Additionally, stb_image will reject image files that have any of their // dimensions set to a larger value than the configurable STBI_MAX_DIMENSIONS, // which defaults to 2**24 = 16777216 pixels. Due to the above memory limit, // the only way to have an image with such dimensions load correctly // is for it to have a rather extreme aspect ratio. Either way, the // assumption here is that such larger images are likely to be malformed // or malicious. If you do need to load an image with individual dimensions // larger than that, and it still fits in the overall size limit, you can // #define STBI_MAX_DIMENSIONS on your own to be something larger. // // =========================================================================== // // UNICODE: // // If compiling for Windows and you wish to use Unicode filenames, compile // with // #define STBI_WINDOWS_UTF8 // and pass utf8-encoded filenames. Call stbi_convert_wchar_to_utf8 to convert // Windows wchar_t filenames to utf8. // // =========================================================================== // // Philosophy // // stb libraries are designed with the following priorities: // // 1. easy to use // 2. easy to maintain // 3. good performance // // Sometimes I let "good performance" creep up in priority over "easy to maintain", // and for best performance I may provide less-easy-to-use APIs that give higher // performance, in addition to the easy-to-use ones. Nevertheless, it's important // to keep in mind that from the standpoint of you, a client of this library, // all you care about is #1 and #3, and stb libraries DO NOT emphasize #3 above all. // // Some secondary priorities arise directly from the first two, some of which // provide more explicit reasons why performance can't be emphasized. // // - Portable ("ease of use") // - Small source code footprint ("easy to maintain") // - No dependencies ("ease of use") // // =========================================================================== // // I/O callbacks // // I/O callbacks allow you to read from arbitrary sources, like packaged // files or some other source. Data read from callbacks are processed // through a small internal buffer (currently 128 bytes) to try to reduce // overhead. // // The three functions you must define are "read" (reads some bytes of data), // "skip" (skips some bytes of data), "eof" (reports if the stream is at the end). // // =========================================================================== // // SIMD support // // The JPEG decoder will try to automatically use SIMD kernels on x86 when // supported by the compiler. For ARM Neon support, you must explicitly // request it. // // (The old do-it-yourself SIMD API is no longer supported in the current // code.) // // On x86, SSE2 will automatically be used when available based on a run-time // test; if not, the generic C versions are used as a fall-back. On ARM targets, // the typical path is to have separate builds for NEON and non-NEON devices // (at least this is true for iOS and Android). Therefore, the NEON support is // toggled by a build flag: define STBI_NEON to get NEON loops. // // If for some reason you do not want to use any of SIMD code, or if // you have issues compiling it, you can disable it entirely by // defining STBI_NO_SIMD. // // =========================================================================== // // HDR image support (disable by defining STBI_NO_HDR) // // stb_image supports loading HDR images in general, and currently the Radiance // .HDR file format specifically. You can still load any file through the existing // interface; if you attempt to load an HDR file, it will be automatically remapped // to LDR, assuming gamma 2.2 and an arbitrary scale factor defaulting to 1; // both of these constants can be reconfigured through this interface: // // stbi_hdr_to_ldr_gamma(2.2f); // stbi_hdr_to_ldr_scale(1.0f); // // (note, do not use _inverse_ constants; stbi_image will invert them // appropriately). // // Additionally, there is a new, parallel interface for loading files as // (linear) floats to preserve the full dynamic range: // // float *data = stbi_loadf(filename, &x, &y, &n, 0); // // If you load LDR images through this interface, those images will // be promoted to floating point values, run through the inverse of // constants corresponding to the above: // // stbi_ldr_to_hdr_scale(1.0f); // stbi_ldr_to_hdr_gamma(2.2f); // // Finally, given a filename (or an open file or memory block--see header // file for details) containing image data, you can query for the "most // appropriate" interface to use (that is, whether the image is HDR or // not), using: // // stbi_is_hdr(char *filename); // // =========================================================================== // // iPhone PNG support: // // We optionally support converting iPhone-formatted PNGs (which store // premultiplied BGRA) back to RGB, even though they're internally encoded // differently. To enable this conversion, call // stbi_convert_iphone_png_to_rgb(1). // // Call stbi_set_unpremultiply_on_load(1) as well to force a divide per // pixel to remove any premultiplied alpha *only* if the image file explicitly // says there's premultiplied data (currently only happens in iPhone images, // and only if iPhone convert-to-rgb processing is on). // // =========================================================================== // // ADDITIONAL CONFIGURATION // // - You can suppress implementation of any of the decoders to reduce // your code footprint by #defining one or more of the following // symbols before creating the implementation. // // STBI_NO_JPEG // STBI_NO_PNG // STBI_NO_BMP // STBI_NO_PSD // STBI_NO_TGA // STBI_NO_GIF // STBI_NO_HDR // STBI_NO_PIC // STBI_NO_PNM (.ppm and .pgm) // // - You can request *only* certain decoders and suppress all other ones // (this will be more forward-compatible, as addition of new decoders // doesn't require you to disable them explicitly): // // STBI_ONLY_JPEG // STBI_ONLY_PNG // STBI_ONLY_BMP // STBI_ONLY_PSD // STBI_ONLY_TGA // STBI_ONLY_GIF // STBI_ONLY_HDR // STBI_ONLY_PIC // STBI_ONLY_PNM (.ppm and .pgm) // // - If you use STBI_NO_PNG (or _ONLY_ without PNG), and you still // want the zlib decoder to be available, #define STBI_SUPPORT_ZLIB // // - If you define STBI_MAX_DIMENSIONS, stb_image will reject images greater // than that size (in either width or height) without further processing. // This is to let programs in the wild set an upper bound to prevent // denial-of-service attacks on untrusted data, as one could generate a // valid image of gigantic dimensions and force stb_image to allocate a // huge block of memory and spend disproportionate time decoding it. By // default this is set to (1 << 24), which is 16777216, but that's still // very big. #ifndef STBI_NO_STDIO #include <stdio.h> #endif // STBI_NO_STDIO #define STBI_VERSION 1 enum { STBI_default = 0, // only used for desired_channels STBI_grey = 1, STBI_grey_alpha = 2, STBI_rgb = 3, STBI_rgb_alpha = 4 }; #include <stdlib.h> typedef unsigned char stbi_uc; typedef unsigned short stbi_us; #ifdef __cplusplus extern "C" { #endif #ifndef STBIDEF #ifdef STB_IMAGE_STATIC #define STBIDEF static #else #define STBIDEF extern #endif #endif ////////////////////////////////////////////////////////////////////////////// // // PRIMARY API - works on images of any type // // // load image by filename, open file, or memory buffer // typedef struct { int (*read) (void *user,char *data,int size); // fill 'data' with 'size' bytes. return number of bytes actually read void (*skip) (void *user,int n); // skip the next 'n' bytes, or 'unget' the last -n bytes if negative int (*eof) (void *user); // returns nonzero if we are at end of file/data } stbi_io_callbacks; //////////////////////////////////// // // 8-bits-per-channel interface // STBIDEF stbi_uc *stbi_load_from_memory (stbi_uc const *buffer, int len , int *x, int *y, int *channels_in_file, int desired_channels); STBIDEF stbi_uc *stbi_load_from_callbacks(stbi_io_callbacks const *clbk , void *user, int *x, int *y, int *channels_in_file, int desired_channels); #ifndef STBI_NO_STDIO STBIDEF stbi_uc *stbi_load (char const *filename, int *x, int *y, int *channels_in_file, int desired_channels); STBIDEF stbi_uc *stbi_load_from_file (FILE *f, int *x, int *y, int *channels_in_file, int desired_channels); // for stbi_load_from_file, file pointer is left pointing immediately after image #endif #ifndef STBI_NO_GIF STBIDEF stbi_uc *stbi_load_gif_from_memory(stbi_uc const *buffer, int len, int **delays, int *x, int *y, int *z, int *comp, int req_comp); #endif #ifdef STBI_WINDOWS_UTF8 STBIDEF int stbi_convert_wchar_to_utf8(char *buffer, size_t bufferlen, const wchar_t* input); #endif //////////////////////////////////// // // 16-bits-per-channel interface // STBIDEF stbi_us *stbi_load_16_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *channels_in_file, int desired_channels); STBIDEF stbi_us *stbi_load_16_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *channels_in_file, int desired_channels); #ifndef STBI_NO_STDIO STBIDEF stbi_us *stbi_load_16 (char const *filename, int *x, int *y, int *channels_in_file, int desired_channels); STBIDEF stbi_us *stbi_load_from_file_16(FILE *f, int *x, int *y, int *channels_in_file, int desired_channels); #endif //////////////////////////////////// // // float-per-channel interface // #ifndef STBI_NO_LINEAR STBIDEF float *stbi_loadf_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *channels_in_file, int desired_channels); STBIDEF float *stbi_loadf_from_callbacks (stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *channels_in_file, int desired_channels); #ifndef STBI_NO_STDIO STBIDEF float *stbi_loadf (char const *filename, int *x, int *y, int *channels_in_file, int desired_channels); STBIDEF float *stbi_loadf_from_file (FILE *f, int *x, int *y, int *channels_in_file, int desired_channels); #endif #endif #ifndef STBI_NO_HDR STBIDEF void stbi_hdr_to_ldr_gamma(float gamma); STBIDEF void stbi_hdr_to_ldr_scale(float scale); #endif // STBI_NO_HDR #ifndef STBI_NO_LINEAR STBIDEF void stbi_ldr_to_hdr_gamma(float gamma); STBIDEF void stbi_ldr_to_hdr_scale(float scale); #endif // STBI_NO_LINEAR // stbi_is_hdr is always defined, but always returns false if STBI_NO_HDR STBIDEF int stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void *user); STBIDEF int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len); #ifndef STBI_NO_STDIO STBIDEF int stbi_is_hdr (char const *filename); STBIDEF int stbi_is_hdr_from_file(FILE *f); #endif // STBI_NO_STDIO // get a VERY brief reason for failure // on most compilers (and ALL modern mainstream compilers) this is threadsafe STBIDEF const char *stbi_failure_reason (void); // free the loaded image -- this is just free() STBIDEF void stbi_image_free (void *retval_from_stbi_load); // get image dimensions & components without fully decoding STBIDEF int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp); STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp); STBIDEF int stbi_is_16_bit_from_memory(stbi_uc const *buffer, int len); STBIDEF int stbi_is_16_bit_from_callbacks(stbi_io_callbacks const *clbk, void *user); #ifndef STBI_NO_STDIO STBIDEF int stbi_info (char const *filename, int *x, int *y, int *comp); STBIDEF int stbi_info_from_file (FILE *f, int *x, int *y, int *comp); STBIDEF int stbi_is_16_bit (char const *filename); STBIDEF int stbi_is_16_bit_from_file(FILE *f); #endif // for image formats that explicitly notate that they have premultiplied alpha, // we just return the colors as stored in the file. set this flag to force // unpremultiplication. results are undefined if the unpremultiply overflow. STBIDEF void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply); // indicate whether we should process iphone images back to canonical format, // or just pass them through "as-is" STBIDEF void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert); // flip the image vertically, so the first pixel in the output array is the bottom left STBIDEF void stbi_set_flip_vertically_on_load(int flag_true_if_should_flip); // as above, but only applies to images loaded on the thread that calls the function // this function is only available if your compiler supports thread-local variables; // calling it will fail to link if your compiler doesn't STBIDEF void stbi_set_unpremultiply_on_load_thread(int flag_true_if_should_unpremultiply); STBIDEF void stbi_convert_iphone_png_to_rgb_thread(int flag_true_if_should_convert); STBIDEF void stbi_set_flip_vertically_on_load_thread(int flag_true_if_should_flip); // ZLIB client - used by PNG, available for other purposes STBIDEF char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen); STBIDEF char *stbi_zlib_decode_malloc_guesssize_headerflag(const char *buffer, int len, int initial_size, int *outlen, int parse_header); STBIDEF char *stbi_zlib_decode_malloc(const char *buffer, int len, int *outlen); STBIDEF int stbi_zlib_decode_buffer(char *obuffer, int olen, const char *ibuffer, int ilen); STBIDEF char *stbi_zlib_decode_noheader_malloc(const char *buffer, int len, int *outlen); STBIDEF int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen); #ifdef __cplusplus } #endif // // //// end header file ///////////////////////////////////////////////////// #endif // STBI_INCLUDE_STB_IMAGE_H #ifdef STB_IMAGE_IMPLEMENTATION #if defined(STBI_ONLY_JPEG) || defined(STBI_ONLY_PNG) || defined(STBI_ONLY_BMP) \ || defined(STBI_ONLY_TGA) || defined(STBI_ONLY_GIF) || defined(STBI_ONLY_PSD) \ || defined(STBI_ONLY_HDR) || defined(STBI_ONLY_PIC) || defined(STBI_ONLY_PNM) \ || defined(STBI_ONLY_ZLIB) #ifndef STBI_ONLY_JPEG #define STBI_NO_JPEG #endif #ifndef STBI_ONLY_PNG #define STBI_NO_PNG #endif #ifndef STBI_ONLY_BMP #define STBI_NO_BMP #endif #ifndef STBI_ONLY_PSD #define STBI_NO_PSD #endif #ifndef STBI_ONLY_TGA #define STBI_NO_TGA #endif #ifndef STBI_ONLY_GIF #define STBI_NO_GIF #endif #ifndef STBI_ONLY_HDR #define STBI_NO_HDR #endif #ifndef STBI_ONLY_PIC #define STBI_NO_PIC #endif #ifndef STBI_ONLY_PNM #define STBI_NO_PNM #endif #endif #if defined(STBI_NO_PNG) && !defined(STBI_SUPPORT_ZLIB) && !defined(STBI_NO_ZLIB) #define STBI_NO_ZLIB #endif #include <stdarg.h> #include <stddef.h> // ptrdiff_t on osx #include <stdlib.h> #include <string.h> #include <limits.h> #if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) #include <math.h> // ldexp, pow #endif #ifndef STBI_NO_STDIO #include <stdio.h> #endif #ifndef STBI_ASSERT #include <assert.h> #define STBI_ASSERT(x) assert(x) #endif #ifdef __cplusplus #define STBI_EXTERN extern "C" #else #define STBI_EXTERN extern #endif #ifndef _MSC_VER #ifdef __cplusplus #define stbi_inline inline #else #define stbi_inline #endif #else #define stbi_inline __forceinline #endif #ifndef STBI_NO_THREAD_LOCALS #if defined(__cplusplus) && __cplusplus >= 201103L #define STBI_THREAD_LOCAL thread_local #elif defined(__GNUC__) && __GNUC__ < 5 #define STBI_THREAD_LOCAL __thread #elif defined(_MSC_VER) #define STBI_THREAD_LOCAL __declspec(thread) #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 201112L && !defined(__STDC_NO_THREADS__) #define STBI_THREAD_LOCAL _Thread_local #endif #ifndef STBI_THREAD_LOCAL #if defined(__GNUC__) #define STBI_THREAD_LOCAL __thread #endif #endif #endif #if defined(_MSC_VER) || defined(__SYMBIAN32__) typedef unsigned short stbi__uint16; typedef signed short stbi__int16; typedef unsigned int stbi__uint32; typedef signed int stbi__int32; #else #include <stdint.h> typedef uint16_t stbi__uint16; typedef int16_t stbi__int16; typedef uint32_t stbi__uint32; typedef int32_t stbi__int32; #endif // should produce compiler error if size is wrong typedef unsigned char validate_uint32[sizeof(stbi__uint32)==4 ? 1 : -1]; #ifdef _MSC_VER #define STBI_NOTUSED(v) (void)(v) #else #define STBI_NOTUSED(v) (void)sizeof(v) #endif #ifdef _MSC_VER #define STBI_HAS_LROTL #endif #ifdef STBI_HAS_LROTL #define stbi_lrot(x,y) _lrotl(x,y) #else #define stbi_lrot(x,y) (((x) << (y)) | ((x) >> (-(y) & 31))) #endif #if defined(STBI_MALLOC) && defined(STBI_FREE) && (defined(STBI_REALLOC) || defined(STBI_REALLOC_SIZED)) // ok #elif !defined(STBI_MALLOC) && !defined(STBI_FREE) && !defined(STBI_REALLOC) && !defined(STBI_REALLOC_SIZED) // ok #else #error "Must define all or none of STBI_MALLOC, STBI_FREE, and STBI_REALLOC (or STBI_REALLOC_SIZED)." #endif #ifndef STBI_MALLOC #define STBI_MALLOC(sz) malloc(sz) #define STBI_REALLOC(p,newsz) realloc(p,newsz) #define STBI_FREE(p) free(p) #endif #ifndef STBI_REALLOC_SIZED #define STBI_REALLOC_SIZED(p,oldsz,newsz) STBI_REALLOC(p,newsz) #endif // x86/x64 detection #if defined(__x86_64__) || defined(_M_X64) #define STBI__X64_TARGET #elif defined(__i386) || defined(_M_IX86) #define STBI__X86_TARGET #endif #if defined(__GNUC__) && defined(STBI__X86_TARGET) && !defined(__SSE2__) && !defined(STBI_NO_SIMD) // gcc doesn't support sse2 intrinsics unless you compile with -msse2, // which in turn means it gets to use SSE2 everywhere. This is unfortunate, // but previous attempts to provide the SSE2 functions with runtime // detection caused numerous issues. The way architecture extensions are // exposed in GCC/Clang is, sadly, not really suited for one-file libs. // New behavior: if compiled with -msse2, we use SSE2 without any // detection; if not, we don't use it at all. #define STBI_NO_SIMD #endif #if defined(__MINGW32__) && defined(STBI__X86_TARGET) && !defined(STBI_MINGW_ENABLE_SSE2) && !defined(STBI_NO_SIMD) // Note that __MINGW32__ doesn't actually mean 32-bit, so we have to avoid STBI__X64_TARGET // // 32-bit MinGW wants ESP to be 16-byte aligned, but this is not in the // Windows ABI and VC++ as well as Windows DLLs don't maintain that invariant. // As a result, enabling SSE2 on 32-bit MinGW is dangerous when not // simultaneously enabling "-mstackrealign". // // See https://github.com/nothings/stb/issues/81 for more information. // // So default to no SSE2 on 32-bit MinGW. If you've read this far and added // -mstackrealign to your build settings, feel free to #define STBI_MINGW_ENABLE_SSE2. #define STBI_NO_SIMD #endif #if !defined(STBI_NO_SIMD) && (defined(STBI__X86_TARGET) || defined(STBI__X64_TARGET)) #define STBI_SSE2 #include <emmintrin.h> #ifdef _MSC_VER #if _MSC_VER >= 1400 // not VC6 #include <intrin.h> // __cpuid static int stbi__cpuid3(void) { int info[4]; __cpuid(info,1); return info[3]; } #else static int stbi__cpuid3(void) { int res; __asm { mov eax,1 cpuid mov res,edx } return res; } #endif #define STBI_SIMD_ALIGN(type, name) __declspec(align(16)) type name #if !defined(STBI_NO_JPEG) && defined(STBI_SSE2) static int stbi__sse2_available(void) { int info3 = stbi__cpuid3(); return ((info3 >> 26) & 1) != 0; } #endif #else // assume GCC-style if not VC++ #define STBI_SIMD_ALIGN(type, name) type name __attribute__((aligned(16))) #if !defined(STBI_NO_JPEG) && defined(STBI_SSE2) static int stbi__sse2_available(void) { // If we're even attempting to compile this on GCC/Clang, that means // -msse2 is on, which means the compiler is allowed to use SSE2 // instructions at will, and so are we. return 1; } #endif #endif #endif // ARM NEON #if defined(STBI_NO_SIMD) && defined(STBI_NEON) #undef STBI_NEON #endif #ifdef STBI_NEON #include <arm_neon.h> #ifdef _MSC_VER #define STBI_SIMD_ALIGN(type, name) __declspec(align(16)) type name #else #define STBI_SIMD_ALIGN(type, name) type name __attribute__((aligned(16))) #endif #endif #ifndef STBI_SIMD_ALIGN #define STBI_SIMD_ALIGN(type, name) type name #endif #ifndef STBI_MAX_DIMENSIONS #define STBI_MAX_DIMENSIONS (1 << 24) #endif /////////////////////////////////////////////// // // stbi__context struct and start_xxx functions // stbi__context structure is our basic context used by all images, so it // contains all the IO context, plus some basic image information typedef struct { stbi__uint32 img_x, img_y; int img_n, img_out_n; stbi_io_callbacks io; void *io_user_data; int read_from_callbacks; int buflen; stbi_uc buffer_start[128]; int callback_already_read; stbi_uc *img_buffer, *img_buffer_end; stbi_uc *img_buffer_original, *img_buffer_original_end; } stbi__context; static void stbi__refill_buffer(stbi__context *s); // initialize a memory-decode context static void stbi__start_mem(stbi__context *s, stbi_uc const *buffer, int len) { s->io.read = NULL; s->read_from_callbacks = 0; s->callback_already_read = 0; s->img_buffer = s->img_buffer_original = (stbi_uc *) buffer; s->img_buffer_end = s->img_buffer_original_end = (stbi_uc *) buffer+len; } // initialize a callback-based context static void stbi__start_callbacks(stbi__context *s, stbi_io_callbacks *c, void *user) { s->io = *c; s->io_user_data = user; s->buflen = sizeof(s->buffer_start); s->read_from_callbacks = 1; s->callback_already_read = 0; s->img_buffer = s->img_buffer_original = s->buffer_start; stbi__refill_buffer(s); s->img_buffer_original_end = s->img_buffer_end; } #ifndef STBI_NO_STDIO static int stbi__stdio_read(void *user, char *data, int size) { return (int) fread(data,1,size,(FILE*) user); } static void stbi__stdio_skip(void *user, int n) { int ch; fseek((FILE*) user, n, SEEK_CUR); ch = fgetc((FILE*) user); /* have to read a byte to reset feof()'s flag */ if (ch != EOF) { ungetc(ch, (FILE *) user); /* push byte back onto stream if valid. */ } } static int stbi__stdio_eof(void *user) { return feof((FILE*) user) || ferror((FILE *) user); } static stbi_io_callbacks stbi__stdio_callbacks = { stbi__stdio_read, stbi__stdio_skip, stbi__stdio_eof, }; static void stbi__start_file(stbi__context *s, FILE *f) { stbi__start_callbacks(s, &stbi__stdio_callbacks, (void *) f); } //static void stop_file(stbi__context *s) { } #endif // !STBI_NO_STDIO static void stbi__rewind(stbi__context *s) { // conceptually rewind SHOULD rewind to the beginning of the stream, // but we just rewind to the beginning of the initial buffer, because // we only use it after doing 'test', which only ever looks at at most 92 bytes s->img_buffer = s->img_buffer_original; s->img_buffer_end = s->img_buffer_original_end; } enum { STBI_ORDER_RGB, STBI_ORDER_BGR }; typedef struct { int bits_per_channel; int num_channels; int channel_order; } stbi__result_info; #ifndef STBI_NO_JPEG static int stbi__jpeg_test(stbi__context *s); static void *stbi__jpeg_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); static int stbi__jpeg_info(stbi__context *s, int *x, int *y, int *comp); #endif #ifndef STBI_NO_PNG static int stbi__png_test(stbi__context *s); static void *stbi__png_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); static int stbi__png_info(stbi__context *s, int *x, int *y, int *comp); static int stbi__png_is16(stbi__context *s); #endif #ifndef STBI_NO_BMP static int stbi__bmp_test(stbi__context *s); static void *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); static int stbi__bmp_info(stbi__context *s, int *x, int *y, int *comp); #endif #ifndef STBI_NO_TGA static int stbi__tga_test(stbi__context *s); static void *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); static int stbi__tga_info(stbi__context *s, int *x, int *y, int *comp); #endif #ifndef STBI_NO_PSD static int stbi__psd_test(stbi__context *s); static void *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri, int bpc); static int stbi__psd_info(stbi__context *s, int *x, int *y, int *comp); static int stbi__psd_is16(stbi__context *s); #endif #ifndef STBI_NO_HDR static int stbi__hdr_test(stbi__context *s); static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); static int stbi__hdr_info(stbi__context *s, int *x, int *y, int *comp); #endif #ifndef STBI_NO_PIC static int stbi__pic_test(stbi__context *s); static void *stbi__pic_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); static int stbi__pic_info(stbi__context *s, int *x, int *y, int *comp); #endif #ifndef STBI_NO_GIF static int stbi__gif_test(stbi__context *s); static void *stbi__gif_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); static void *stbi__load_gif_main(stbi__context *s, int **delays, int *x, int *y, int *z, int *comp, int req_comp); static int stbi__gif_info(stbi__context *s, int *x, int *y, int *comp); #endif #ifndef STBI_NO_PNM static int stbi__pnm_test(stbi__context *s); static void *stbi__pnm_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); static int stbi__pnm_info(stbi__context *s, int *x, int *y, int *comp); static int stbi__pnm_is16(stbi__context *s); #endif static #ifdef STBI_THREAD_LOCAL STBI_THREAD_LOCAL #endif const char *stbi__g_failure_reason; STBIDEF const char *stbi_failure_reason(void) { return stbi__g_failure_reason; } #ifndef STBI_NO_FAILURE_STRINGS static int stbi__err(const char *str) { stbi__g_failure_reason = str; return 0; } #endif static void *stbi__malloc(size_t size) { return STBI_MALLOC(size); } // stb_image uses ints pervasively, including for offset calculations. // therefore the largest decoded image size we can support with the // current code, even on 64-bit targets, is INT_MAX. this is not a // significant limitation for the intended use case. // // we do, however, need to make sure our size calculations don't // overflow. hence a few helper functions for size calculations that // multiply integers together, making sure that they're non-negative // and no overflow occurs. // return 1 if the sum is valid, 0 on overflow. // negative terms are considered invalid. static int stbi__addsizes_valid(int a, int b) { if (b < 0) return 0; // now 0 <= b <= INT_MAX, hence also // 0 <= INT_MAX - b <= INTMAX. // And "a + b <= INT_MAX" (which might overflow) is the // same as a <= INT_MAX - b (no overflow) return a <= INT_MAX - b; } // returns 1 if the product is valid, 0 on overflow. // negative factors are considered invalid. static int stbi__mul2sizes_valid(int a, int b) { if (a < 0 || b < 0) return 0; if (b == 0) return 1; // mul-by-0 is always safe // portable way to check for no overflows in a*b return a <= INT_MAX/b; } #if !defined(STBI_NO_JPEG) || !defined(STBI_NO_PNG) || !defined(STBI_NO_TGA) || !defined(STBI_NO_HDR) // returns 1 if "a*b + add" has no negative terms/factors and doesn't overflow static int stbi__mad2sizes_valid(int a, int b, int add) { return stbi__mul2sizes_valid(a, b) && stbi__addsizes_valid(a*b, add); } #endif // returns 1 if "a*b*c + add" has no negative terms/factors and doesn't overflow static int stbi__mad3sizes_valid(int a, int b, int c, int add) { return stbi__mul2sizes_valid(a, b) && stbi__mul2sizes_valid(a*b, c) && stbi__addsizes_valid(a*b*c, add); } // returns 1 if "a*b*c*d + add" has no negative terms/factors and doesn't overflow #if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) || !defined(STBI_NO_PNM) static int stbi__mad4sizes_valid(int a, int b, int c, int d, int add) { return stbi__mul2sizes_valid(a, b) && stbi__mul2sizes_valid(a*b, c) && stbi__mul2sizes_valid(a*b*c, d) && stbi__addsizes_valid(a*b*c*d, add); } #endif #if !defined(STBI_NO_JPEG) || !defined(STBI_NO_PNG) || !defined(STBI_NO_TGA) || !defined(STBI_NO_HDR) // mallocs with size overflow checking static void *stbi__malloc_mad2(int a, int b, int add) { if (!stbi__mad2sizes_valid(a, b, add)) return NULL; return stbi__malloc(a*b + add); } #endif static void *stbi__malloc_mad3(int a, int b, int c, int add) { if (!stbi__mad3sizes_valid(a, b, c, add)) return NULL; return stbi__malloc(a*b*c + add); } #if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) || !defined(STBI_NO_PNM) static void *stbi__malloc_mad4(int a, int b, int c, int d, int add) { if (!stbi__mad4sizes_valid(a, b, c, d, add)) return NULL; return stbi__malloc(a*b*c*d + add); } #endif // returns 1 if the sum of two signed ints is valid (between -2^31 and 2^31-1 inclusive), 0 on overflow. static int stbi__addints_valid(int a, int b) { if ((a >= 0) != (b >= 0)) return 1; // a and b have different signs, so no overflow if (a < 0 && b < 0) return a >= INT_MIN - b; // same as a + b >= INT_MIN; INT_MIN - b cannot overflow since b < 0. return a <= INT_MAX - b; } // returns 1 if the product of two signed shorts is valid, 0 on overflow. static int stbi__mul2shorts_valid(short a, short b) { if (b == 0 || b == -1) return 1; // multiplication by 0 is always 0; check for -1 so SHRT_MIN/b doesn't overflow if ((a >= 0) == (b >= 0)) return a <= SHRT_MAX/b; // product is positive, so similar to mul2sizes_valid if (b < 0) return a <= SHRT_MIN / b; // same as a * b >= SHRT_MIN return a >= SHRT_MIN / b; } // stbi__err - error // stbi__errpf - error returning pointer to float // stbi__errpuc - error returning pointer to unsigned char #ifdef STBI_NO_FAILURE_STRINGS #define stbi__err(x,y) 0 #elif defined(STBI_FAILURE_USERMSG) #define stbi__err(x,y) stbi__err(y) #else #define stbi__err(x,y) stbi__err(x) #endif #define stbi__errpf(x,y) ((float *)(size_t) (stbi__err(x,y)?NULL:NULL)) #define stbi__errpuc(x,y) ((unsigned char *)(size_t) (stbi__err(x,y)?NULL:NULL)) STBIDEF void stbi_image_free(void *retval_from_stbi_load) { STBI_FREE(retval_from_stbi_load); } #ifndef STBI_NO_LINEAR static float *stbi__ldr_to_hdr(stbi_uc *data, int x, int y, int comp); #endif #ifndef STBI_NO_HDR static stbi_uc *stbi__hdr_to_ldr(float *data, int x, int y, int comp); #endif static int stbi__vertically_flip_on_load_global = 0; STBIDEF void stbi_set_flip_vertically_on_load(int flag_true_if_should_flip) { stbi__vertically_flip_on_load_global = flag_true_if_should_flip; } #ifndef STBI_THREAD_LOCAL #define stbi__vertically_flip_on_load stbi__vertically_flip_on_load_global #else static STBI_THREAD_LOCAL int stbi__vertically_flip_on_load_local, stbi__vertically_flip_on_load_set; STBIDEF void stbi_set_flip_vertically_on_load_thread(int flag_true_if_should_flip) { stbi__vertically_flip_on_load_local = flag_true_if_should_flip; stbi__vertically_flip_on_load_set = 1; } #define stbi__vertically_flip_on_load (stbi__vertically_flip_on_load_set \ ? stbi__vertically_flip_on_load_local \ : stbi__vertically_flip_on_load_global) #endif // STBI_THREAD_LOCAL static void *stbi__load_main(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri, int bpc) { memset(ri, 0, sizeof(*ri)); // make sure it's initialized if we add new fields ri->bits_per_channel = 8; // default is 8 so most paths don't have to be changed ri->channel_order = STBI_ORDER_RGB; // all current input & output are this, but this is here so we can add BGR order ri->num_channels = 0; // test the formats with a very explicit header first (at least a FOURCC // or distinctive magic number first) #ifndef STBI_NO_PNG if (stbi__png_test(s)) return stbi__png_load(s,x,y,comp,req_comp, ri); #endif #ifndef STBI_NO_BMP if (stbi__bmp_test(s)) return stbi__bmp_load(s,x,y,comp,req_comp, ri); #endif #ifndef STBI_NO_GIF if (stbi__gif_test(s)) return stbi__gif_load(s,x,y,comp,req_comp, ri); #endif #ifndef STBI_NO_PSD if (stbi__psd_test(s)) return stbi__psd_load(s,x,y,comp,req_comp, ri, bpc); #else STBI_NOTUSED(bpc); #endif #ifndef STBI_NO_PIC if (stbi__pic_test(s)) return stbi__pic_load(s,x,y,comp,req_comp, ri); #endif // then the formats that can end up attempting to load with just 1 or 2 // bytes matching expectations; these are prone to false positives, so // try them later #ifndef STBI_NO_JPEG if (stbi__jpeg_test(s)) return stbi__jpeg_load(s,x,y,comp,req_comp, ri); #endif #ifndef STBI_NO_PNM if (stbi__pnm_test(s)) return stbi__pnm_load(s,x,y,comp,req_comp, ri); #endif #ifndef STBI_NO_HDR if (stbi__hdr_test(s)) { float *hdr = stbi__hdr_load(s, x,y,comp,req_comp, ri); return stbi__hdr_to_ldr(hdr, *x, *y, req_comp ? req_comp : *comp); } #endif #ifndef STBI_NO_TGA // test tga last because it's a crappy test! if (stbi__tga_test(s)) return stbi__tga_load(s,x,y,comp,req_comp, ri); #endif return stbi__errpuc("unknown image type", "Image not of any known type, or corrupt"); } static stbi_uc *stbi__convert_16_to_8(stbi__uint16 *orig, int w, int h, int channels) { int i; int img_len = w * h * channels; stbi_uc *reduced; reduced = (stbi_uc *) stbi__malloc(img_len); if (reduced == NULL) return stbi__errpuc("outofmem", "Out of memory"); for (i = 0; i < img_len; ++i) reduced[i] = (stbi_uc)((orig[i] >> 8) & 0xFF); // top half of each byte is sufficient approx of 16->8 bit scaling STBI_FREE(orig); return reduced; } static stbi__uint16 *stbi__convert_8_to_16(stbi_uc *orig, int w, int h, int channels) { int i; int img_len = w * h * channels; stbi__uint16 *enlarged; enlarged = (stbi__uint16 *) stbi__malloc(img_len*2); if (enlarged == NULL) return (stbi__uint16 *) stbi__errpuc("outofmem", "Out of memory"); for (i = 0; i < img_len; ++i) enlarged[i] = (stbi__uint16)((orig[i] << 8) + orig[i]); // replicate to high and low byte, maps 0->0, 255->0xffff STBI_FREE(orig); return enlarged; } static void stbi__vertical_flip(void *image, int w, int h, int bytes_per_pixel) { int row; size_t bytes_per_row = (size_t)w * bytes_per_pixel; stbi_uc temp[2048]; stbi_uc *bytes = (stbi_uc *)image; for (row = 0; row < (h>>1); row++) { stbi_uc *row0 = bytes + row*bytes_per_row; stbi_uc *row1 = bytes + (h - row - 1)*bytes_per_row; // swap row0 with row1 size_t bytes_left = bytes_per_row; while (bytes_left) { size_t bytes_copy = (bytes_left < sizeof(temp)) ? bytes_left : sizeof(temp); memcpy(temp, row0, bytes_copy); memcpy(row0, row1, bytes_copy); memcpy(row1, temp, bytes_copy); row0 += bytes_copy; row1 += bytes_copy; bytes_left -= bytes_copy; } } } #ifndef STBI_NO_GIF static void stbi__vertical_flip_slices(void *image, int w, int h, int z, int bytes_per_pixel) { int slice; int slice_size = w * h * bytes_per_pixel; stbi_uc *bytes = (stbi_uc *)image; for (slice = 0; slice < z; ++slice) { stbi__vertical_flip(bytes, w, h, bytes_per_pixel); bytes += slice_size; } } #endif static unsigned char *stbi__load_and_postprocess_8bit(stbi__context *s, int *x, int *y, int *comp, int req_comp) { stbi__result_info ri; void *result = stbi__load_main(s, x, y, comp, req_comp, &ri, 8); if (result == NULL) return NULL; // it is the responsibility of the loaders to make sure we get either 8 or 16 bit. STBI_ASSERT(ri.bits_per_channel == 8 || ri.bits_per_channel == 16); if (ri.bits_per_channel != 8) { result = stbi__convert_16_to_8((stbi__uint16 *) result, *x, *y, req_comp == 0 ? *comp : req_comp); ri.bits_per_channel = 8; } // @TODO: move stbi__convert_format to here if (stbi__vertically_flip_on_load) { int channels = req_comp ? req_comp : *comp; stbi__vertical_flip(result, *x, *y, channels * sizeof(stbi_uc)); } return (unsigned char *) result; } static stbi__uint16 *stbi__load_and_postprocess_16bit(stbi__context *s, int *x, int *y, int *comp, int req_comp) { stbi__result_info ri; void *result = stbi__load_main(s, x, y, comp, req_comp, &ri, 16); if (result == NULL) return NULL; // it is the responsibility of the loaders to make sure we get either 8 or 16 bit. STBI_ASSERT(ri.bits_per_channel == 8 || ri.bits_per_channel == 16); if (ri.bits_per_channel != 16) { result = stbi__convert_8_to_16((stbi_uc *) result, *x, *y, req_comp == 0 ? *comp : req_comp); ri.bits_per_channel = 16; } // @TODO: move stbi__convert_format16 to here // @TODO: special case RGB-to-Y (and RGBA-to-YA) for 8-bit-to-16-bit case to keep more precision if (stbi__vertically_flip_on_load) { int channels = req_comp ? req_comp : *comp; stbi__vertical_flip(result, *x, *y, channels * sizeof(stbi__uint16)); } return (stbi__uint16 *) result; } #if !defined(STBI_NO_HDR) && !defined(STBI_NO_LINEAR) static void stbi__float_postprocess(float *result, int *x, int *y, int *comp, int req_comp) { if (stbi__vertically_flip_on_load && result != NULL) { int channels = req_comp ? req_comp : *comp; stbi__vertical_flip(result, *x, *y, channels * sizeof(float)); } } #endif #ifndef STBI_NO_STDIO #if defined(_WIN32) && defined(STBI_WINDOWS_UTF8) STBI_EXTERN __declspec(dllimport) int __stdcall MultiByteToWideChar(unsigned int cp, unsigned long flags, const char *str, int cbmb, wchar_t *widestr, int cchwide); STBI_EXTERN __declspec(dllimport) int __stdcall WideCharToMultiByte(unsigned int cp, unsigned long flags, const wchar_t *widestr, int cchwide, char *str, int cbmb, const char *defchar, int *used_default); #endif #if defined(_WIN32) && defined(STBI_WINDOWS_UTF8) STBIDEF int stbi_convert_wchar_to_utf8(char *buffer, size_t bufferlen, const wchar_t* input) { return WideCharToMultiByte(65001 /* UTF8 */, 0, input, -1, buffer, (int) bufferlen, NULL, NULL); } #endif static FILE *stbi__fopen(char const *filename, char const *mode) { FILE *f; #if defined(_WIN32) && defined(STBI_WINDOWS_UTF8) wchar_t wMode[64]; wchar_t wFilename[1024]; if (0 == MultiByteToWideChar(65001 /* UTF8 */, 0, filename, -1, wFilename, sizeof(wFilename)/sizeof(*wFilename))) return 0; if (0 == MultiByteToWideChar(65001 /* UTF8 */, 0, mode, -1, wMode, sizeof(wMode)/sizeof(*wMode))) return 0; #if defined(_MSC_VER) && _MSC_VER >= 1400 if (0 != _wfopen_s(&f, wFilename, wMode)) f = 0; #else f = _wfopen(wFilename, wMode); #endif #elif defined(_MSC_VER) && _MSC_VER >= 1400 if (0 != fopen_s(&f, filename, mode)) f=0; #else f = fopen(filename, mode); #endif return f; } STBIDEF stbi_uc *stbi_load(char const *filename, int *x, int *y, int *comp, int req_comp) { FILE *f = stbi__fopen(filename, "rb"); unsigned char *result; if (!f) return stbi__errpuc("can't fopen", "Unable to open file"); result = stbi_load_from_file(f,x,y,comp,req_comp); fclose(f); return result; } STBIDEF stbi_uc *stbi_load_from_file(FILE *f, int *x, int *y, int *comp, int req_comp) { unsigned char *result; stbi__context s; stbi__start_file(&s,f); result = stbi__load_and_postprocess_8bit(&s,x,y,comp,req_comp); if (result) { // need to 'unget' all the characters in the IO buffer fseek(f, - (int) (s.img_buffer_end - s.img_buffer), SEEK_CUR); } return result; } STBIDEF stbi__uint16 *stbi_load_from_file_16(FILE *f, int *x, int *y, int *comp, int req_comp) { stbi__uint16 *result; stbi__context s; stbi__start_file(&s,f); result = stbi__load_and_postprocess_16bit(&s,x,y,comp,req_comp); if (result) { // need to 'unget' all the characters in the IO buffer fseek(f, - (int) (s.img_buffer_end - s.img_buffer), SEEK_CUR); } return result; } STBIDEF stbi_us *stbi_load_16(char const *filename, int *x, int *y, int *comp, int req_comp) { FILE *f = stbi__fopen(filename, "rb"); stbi__uint16 *result; if (!f) return (stbi_us *) stbi__errpuc("can't fopen", "Unable to open file"); result = stbi_load_from_file_16(f,x,y,comp,req_comp); fclose(f); return result; } #endif //!STBI_NO_STDIO STBIDEF stbi_us *stbi_load_16_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *channels_in_file, int desired_channels) { stbi__context s; stbi__start_mem(&s,buffer,len); return stbi__load_and_postprocess_16bit(&s,x,y,channels_in_file,desired_channels); } STBIDEF stbi_us *stbi_load_16_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *channels_in_file, int desired_channels) { stbi__context s; stbi__start_callbacks(&s, (stbi_io_callbacks *)clbk, user); return stbi__load_and_postprocess_16bit(&s,x,y,channels_in_file,desired_channels); } STBIDEF stbi_uc *stbi_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp) { stbi__context s; stbi__start_mem(&s,buffer,len); return stbi__load_and_postprocess_8bit(&s,x,y,comp,req_comp); } STBIDEF stbi_uc *stbi_load_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp) { stbi__context s; stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user); return stbi__load_and_postprocess_8bit(&s,x,y,comp,req_comp); } #ifndef STBI_NO_GIF STBIDEF stbi_uc *stbi_load_gif_from_memory(stbi_uc const *buffer, int len, int **delays, int *x, int *y, int *z, int *comp, int req_comp) { unsigned char *result; stbi__context s; stbi__start_mem(&s,buffer,len); result = (unsigned char*) stbi__load_gif_main(&s, delays, x, y, z, comp, req_comp); if (stbi__vertically_flip_on_load) { stbi__vertical_flip_slices( result, *x, *y, *z, *comp ); } return result; } #endif #ifndef STBI_NO_LINEAR static float *stbi__loadf_main(stbi__context *s, int *x, int *y, int *comp, int req_comp) { unsigned char *data; #ifndef STBI_NO_HDR if (stbi__hdr_test(s)) { stbi__result_info ri; float *hdr_data = stbi__hdr_load(s,x,y,comp,req_comp, &ri); if (hdr_data) stbi__float_postprocess(hdr_data,x,y,comp,req_comp); return hdr_data; } #endif data = stbi__load_and_postprocess_8bit(s, x, y, comp, req_comp); if (data) return stbi__ldr_to_hdr(data, *x, *y, req_comp ? req_comp : *comp); return stbi__errpf("unknown image type", "Image not of any known type, or corrupt"); } STBIDEF float *stbi_loadf_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp) { stbi__context s; stbi__start_mem(&s,buffer,len); return stbi__loadf_main(&s,x,y,comp,req_comp); } STBIDEF float *stbi_loadf_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp) { stbi__context s; stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user); return stbi__loadf_main(&s,x,y,comp,req_comp); } #ifndef STBI_NO_STDIO STBIDEF float *stbi_loadf(char const *filename, int *x, int *y, int *comp, int req_comp) { float *result; FILE *f = stbi__fopen(filename, "rb"); if (!f) return stbi__errpf("can't fopen", "Unable to open file"); result = stbi_loadf_from_file(f,x,y,comp,req_comp); fclose(f); return result; } STBIDEF float *stbi_loadf_from_file(FILE *f, int *x, int *y, int *comp, int req_comp) { stbi__context s; stbi__start_file(&s,f); return stbi__loadf_main(&s,x,y,comp,req_comp); } #endif // !STBI_NO_STDIO #endif // !STBI_NO_LINEAR // these is-hdr-or-not is defined independent of whether STBI_NO_LINEAR is // defined, for API simplicity; if STBI_NO_LINEAR is defined, it always // reports false! STBIDEF int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len) { #ifndef STBI_NO_HDR stbi__context s; stbi__start_mem(&s,buffer,len); return stbi__hdr_test(&s); #else STBI_NOTUSED(buffer); STBI_NOTUSED(len); return 0; #endif } #ifndef STBI_NO_STDIO STBIDEF int stbi_is_hdr (char const *filename) { FILE *f = stbi__fopen(filename, "rb"); int result=0; if (f) { result = stbi_is_hdr_from_file(f); fclose(f); } return result; } STBIDEF int stbi_is_hdr_from_file(FILE *f) { #ifndef STBI_NO_HDR long pos = ftell(f); int res; stbi__context s; stbi__start_file(&s,f); res = stbi__hdr_test(&s); fseek(f, pos, SEEK_SET); return res; #else STBI_NOTUSED(f); return 0; #endif } #endif // !STBI_NO_STDIO STBIDEF int stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void *user) { #ifndef STBI_NO_HDR stbi__context s; stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user); return stbi__hdr_test(&s); #else STBI_NOTUSED(clbk); STBI_NOTUSED(user); return 0; #endif } #ifndef STBI_NO_LINEAR static float stbi__l2h_gamma=2.2f, stbi__l2h_scale=1.0f; STBIDEF void stbi_ldr_to_hdr_gamma(float gamma) { stbi__l2h_gamma = gamma; } STBIDEF void stbi_ldr_to_hdr_scale(float scale) { stbi__l2h_scale = scale; } #endif static float stbi__h2l_gamma_i=1.0f/2.2f, stbi__h2l_scale_i=1.0f; STBIDEF void stbi_hdr_to_ldr_gamma(float gamma) { stbi__h2l_gamma_i = 1/gamma; } STBIDEF void stbi_hdr_to_ldr_scale(float scale) { stbi__h2l_scale_i = 1/scale; } ////////////////////////////////////////////////////////////////////////////// // // Common code used by all image loaders // enum { STBI__SCAN_load=0, STBI__SCAN_type, STBI__SCAN_header }; static void stbi__refill_buffer(stbi__context *s) { int n = (s->io.read)(s->io_user_data,(char*)s->buffer_start,s->buflen); s->callback_already_read += (int) (s->img_buffer - s->img_buffer_original); if (n == 0) { // at end of file, treat same as if from memory, but need to handle case // where s->img_buffer isn't pointing to safe memory, e.g. 0-byte file s->read_from_callbacks = 0; s->img_buffer = s->buffer_start; s->img_buffer_end = s->buffer_start+1; *s->img_buffer = 0; } else { s->img_buffer = s->buffer_start; s->img_buffer_end = s->buffer_start + n; } } stbi_inline static stbi_uc stbi__get8(stbi__context *s) { if (s->img_buffer < s->img_buffer_end) return *s->img_buffer++; if (s->read_from_callbacks) { stbi__refill_buffer(s); return *s->img_buffer++; } return 0; } #if defined(STBI_NO_JPEG) && defined(STBI_NO_HDR) && defined(STBI_NO_PIC) && defined(STBI_NO_PNM) // nothing #else stbi_inline static int stbi__at_eof(stbi__context *s) { if (s->io.read) { if (!(s->io.eof)(s->io_user_data)) return 0; // if feof() is true, check if buffer = end // special case: we've only got the special 0 character at the end if (s->read_from_callbacks == 0) return 1; } return s->img_buffer >= s->img_buffer_end; } #endif #if defined(STBI_NO_JPEG) && defined(STBI_NO_PNG) && defined(STBI_NO_BMP) && defined(STBI_NO_PSD) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) && defined(STBI_NO_PIC) // nothing #else static void stbi__skip(stbi__context *s, int n) { if (n == 0) return; // already there! if (n < 0) { s->img_buffer = s->img_buffer_end; return; } if (s->io.read) { int blen = (int) (s->img_buffer_end - s->img_buffer); if (blen < n) { s->img_buffer = s->img_buffer_end; (s->io.skip)(s->io_user_data, n - blen); return; } } s->img_buffer += n; } #endif #if defined(STBI_NO_PNG) && defined(STBI_NO_TGA) && defined(STBI_NO_HDR) && defined(STBI_NO_PNM) // nothing #else static int stbi__getn(stbi__context *s, stbi_uc *buffer, int n) { if (s->io.read) { int blen = (int) (s->img_buffer_end - s->img_buffer); if (blen < n) { int res, count; memcpy(buffer, s->img_buffer, blen); count = (s->io.read)(s->io_user_data, (char*) buffer + blen, n - blen); res = (count == (n-blen)); s->img_buffer = s->img_buffer_end; return res; } } if (s->img_buffer+n <= s->img_buffer_end) { memcpy(buffer, s->img_buffer, n); s->img_buffer += n; return 1; } else return 0; } #endif #if defined(STBI_NO_JPEG) && defined(STBI_NO_PNG) && defined(STBI_NO_PSD) && defined(STBI_NO_PIC) // nothing #else static int stbi__get16be(stbi__context *s) { int z = stbi__get8(s); return (z << 8) + stbi__get8(s); } #endif #if defined(STBI_NO_PNG) && defined(STBI_NO_PSD) && defined(STBI_NO_PIC) // nothing #else static stbi__uint32 stbi__get32be(stbi__context *s) { stbi__uint32 z = stbi__get16be(s); return (z << 16) + stbi__get16be(s); } #endif #if defined(STBI_NO_BMP) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) // nothing #else static int stbi__get16le(stbi__context *s) { int z = stbi__get8(s); return z + (stbi__get8(s) << 8); } #endif #ifndef STBI_NO_BMP static stbi__uint32 stbi__get32le(stbi__context *s) { stbi__uint32 z = stbi__get16le(s); z += (stbi__uint32)stbi__get16le(s) << 16; return z; } #endif #define STBI__BYTECAST(x) ((stbi_uc) ((x) & 255)) // truncate int to byte without warnings #if defined(STBI_NO_JPEG) && defined(STBI_NO_PNG) && defined(STBI_NO_BMP) && defined(STBI_NO_PSD) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) && defined(STBI_NO_PIC) && defined(STBI_NO_PNM) // nothing #else ////////////////////////////////////////////////////////////////////////////// // // generic converter from built-in img_n to req_comp // individual types do this automatically as much as possible (e.g. jpeg // does all cases internally since it needs to colorspace convert anyway, // and it never has alpha, so very few cases ). png can automatically // interleave an alpha=255 channel, but falls back to this for other cases // // assume data buffer is malloced, so malloc a new one and free that one // only failure mode is malloc failing static stbi_uc stbi__compute_y(int r, int g, int b) { return (stbi_uc) (((r*77) + (g*150) + (29*b)) >> 8); } #endif #if defined(STBI_NO_PNG) && defined(STBI_NO_BMP) && defined(STBI_NO_PSD) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) && defined(STBI_NO_PIC) && defined(STBI_NO_PNM) // nothing #else static unsigned char *stbi__convert_format(unsigned char *data, int img_n, int req_comp, unsigned int x, unsigned int y) { int i,j; unsigned char *good; if (req_comp == img_n) return data; STBI_ASSERT(req_comp >= 1 && req_comp <= 4); good = (unsigned char *) stbi__malloc_mad3(req_comp, x, y, 0); if (good == NULL) { STBI_FREE(data); return stbi__errpuc("outofmem", "Out of memory"); } for (j=0; j < (int) y; ++j) { unsigned char *src = data + j * x * img_n ; unsigned char *dest = good + j * x * req_comp; #define STBI__COMBO(a,b) ((a)*8+(b)) #define STBI__CASE(a,b) case STBI__COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b) // convert source image with img_n components to one with req_comp components; // avoid switch per pixel, so use switch per scanline and massive macros switch (STBI__COMBO(img_n, req_comp)) { STBI__CASE(1,2) { dest[0]=src[0]; dest[1]=255; } break; STBI__CASE(1,3) { dest[0]=dest[1]=dest[2]=src[0]; } break; STBI__CASE(1,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=255; } break; STBI__CASE(2,1) { dest[0]=src[0]; } break; STBI__CASE(2,3) { dest[0]=dest[1]=dest[2]=src[0]; } break; STBI__CASE(2,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=src[1]; } break; STBI__CASE(3,4) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2];dest[3]=255; } break; STBI__CASE(3,1) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); } break; STBI__CASE(3,2) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); dest[1] = 255; } break; STBI__CASE(4,1) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); } break; STBI__CASE(4,2) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); dest[1] = src[3]; } break; STBI__CASE(4,3) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2]; } break; default: STBI_ASSERT(0); STBI_FREE(data); STBI_FREE(good); return stbi__errpuc("unsupported", "Unsupported format conversion"); } #undef STBI__CASE } STBI_FREE(data); return good; } #endif #if defined(STBI_NO_PNG) && defined(STBI_NO_PSD) // nothing #else static stbi__uint16 stbi__compute_y_16(int r, int g, int b) { return (stbi__uint16) (((r*77) + (g*150) + (29*b)) >> 8); } #endif #if defined(STBI_NO_PNG) && defined(STBI_NO_PSD) // nothing #else static stbi__uint16 *stbi__convert_format16(stbi__uint16 *data, int img_n, int req_comp, unsigned int x, unsigned int y) { int i,j; stbi__uint16 *good; if (req_comp == img_n) return data; STBI_ASSERT(req_comp >= 1 && req_comp <= 4); good = (stbi__uint16 *) stbi__malloc(req_comp * x * y * 2); if (good == NULL) { STBI_FREE(data); return (stbi__uint16 *) stbi__errpuc("outofmem", "Out of memory"); } for (j=0; j < (int) y; ++j) { stbi__uint16 *src = data + j * x * img_n ; stbi__uint16 *dest = good + j * x * req_comp; #define STBI__COMBO(a,b) ((a)*8+(b)) #define STBI__CASE(a,b) case STBI__COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b) // convert source image with img_n components to one with req_comp components; // avoid switch per pixel, so use switch per scanline and massive macros switch (STBI__COMBO(img_n, req_comp)) { STBI__CASE(1,2) { dest[0]=src[0]; dest[1]=0xffff; } break; STBI__CASE(1,3) { dest[0]=dest[1]=dest[2]=src[0]; } break; STBI__CASE(1,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=0xffff; } break; STBI__CASE(2,1) { dest[0]=src[0]; } break; STBI__CASE(2,3) { dest[0]=dest[1]=dest[2]=src[0]; } break; STBI__CASE(2,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=src[1]; } break; STBI__CASE(3,4) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2];dest[3]=0xffff; } break; STBI__CASE(3,1) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); } break; STBI__CASE(3,2) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); dest[1] = 0xffff; } break; STBI__CASE(4,1) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); } break; STBI__CASE(4,2) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); dest[1] = src[3]; } break; STBI__CASE(4,3) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2]; } break; default: STBI_ASSERT(0); STBI_FREE(data); STBI_FREE(good); return (stbi__uint16*) stbi__errpuc("unsupported", "Unsupported format conversion"); } #undef STBI__CASE } STBI_FREE(data); return good; } #endif #ifndef STBI_NO_LINEAR static float *stbi__ldr_to_hdr(stbi_uc *data, int x, int y, int comp) { int i,k,n; float *output; if (!data) return NULL; output = (float *) stbi__malloc_mad4(x, y, comp, sizeof(float), 0); if (output == NULL) { STBI_FREE(data); return stbi__errpf("outofmem", "Out of memory"); } // compute number of non-alpha components if (comp & 1) n = comp; else n = comp-1; for (i=0; i < x*y; ++i) { for (k=0; k < n; ++k) { output[i*comp + k] = (float) (pow(data[i*comp+k]/255.0f, stbi__l2h_gamma) * stbi__l2h_scale); } } if (n < comp) { for (i=0; i < x*y; ++i) { output[i*comp + n] = data[i*comp + n]/255.0f; } } STBI_FREE(data); return output; } #endif #ifndef STBI_NO_HDR #define stbi__float2int(x) ((int) (x)) static stbi_uc *stbi__hdr_to_ldr(float *data, int x, int y, int comp) { int i,k,n; stbi_uc *output; if (!data) return NULL; output = (stbi_uc *) stbi__malloc_mad3(x, y, comp, 0); if (output == NULL) { STBI_FREE(data); return stbi__errpuc("outofmem", "Out of memory"); } // compute number of non-alpha components if (comp & 1) n = comp; else n = comp-1; for (i=0; i < x*y; ++i) { for (k=0; k < n; ++k) { float z = (float) pow(data[i*comp+k]*stbi__h2l_scale_i, stbi__h2l_gamma_i) * 255 + 0.5f; if (z < 0) z = 0; if (z > 255) z = 255; output[i*comp + k] = (stbi_uc) stbi__float2int(z); } if (k < comp) { float z = data[i*comp+k] * 255 + 0.5f; if (z < 0) z = 0; if (z > 255) z = 255; output[i*comp + k] = (stbi_uc) stbi__float2int(z); } } STBI_FREE(data); return output; } #endif ////////////////////////////////////////////////////////////////////////////// // // "baseline" JPEG/JFIF decoder // // simple implementation // - doesn't support delayed output of y-dimension // - simple interface (only one output format: 8-bit interleaved RGB) // - doesn't try to recover corrupt jpegs // - doesn't allow partial loading, loading multiple at once // - still fast on x86 (copying globals into locals doesn't help x86) // - allocates lots of intermediate memory (full size of all components) // - non-interleaved case requires this anyway // - allows good upsampling (see next) // high-quality // - upsampled channels are bilinearly interpolated, even across blocks // - quality integer IDCT derived from IJG's 'slow' // performance // - fast huffman; reasonable integer IDCT // - some SIMD kernels for common paths on targets with SSE2/NEON // - uses a lot of intermediate memory, could cache poorly #ifndef STBI_NO_JPEG // huffman decoding acceleration #define FAST_BITS 9 // larger handles more cases; smaller stomps less cache typedef struct { stbi_uc fast[1 << FAST_BITS]; // weirdly, repacking this into AoS is a 10% speed loss, instead of a win stbi__uint16 code[256]; stbi_uc values[256]; stbi_uc size[257]; unsigned int maxcode[18]; int delta[17]; // old 'firstsymbol' - old 'firstcode' } stbi__huffman; typedef struct { stbi__context *s; stbi__huffman huff_dc[4]; stbi__huffman huff_ac[4]; stbi__uint16 dequant[4][64]; stbi__int16 fast_ac[4][1 << FAST_BITS]; // sizes for components, interleaved MCUs int img_h_max, img_v_max; int img_mcu_x, img_mcu_y; int img_mcu_w, img_mcu_h; // definition of jpeg image component struct { int id; int h,v; int tq; int hd,ha; int dc_pred; int x,y,w2,h2; stbi_uc *data; void *raw_data, *raw_coeff; stbi_uc *linebuf; short *coeff; // progressive only int coeff_w, coeff_h; // number of 8x8 coefficient blocks } img_comp[4]; stbi__uint32 code_buffer; // jpeg entropy-coded buffer int code_bits; // number of valid bits unsigned char marker; // marker seen while filling entropy buffer int nomore; // flag if we saw a marker so must stop int progressive; int spec_start; int spec_end; int succ_high; int succ_low; int eob_run; int jfif; int app14_color_transform; // Adobe APP14 tag int rgb; int scan_n, order[4]; int restart_interval, todo; // kernels void (*idct_block_kernel)(stbi_uc *out, int out_stride, short data[64]); void (*YCbCr_to_RGB_kernel)(stbi_uc *out, const stbi_uc *y, const stbi_uc *pcb, const stbi_uc *pcr, int count, int step); stbi_uc *(*resample_row_hv_2_kernel)(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs); } stbi__jpeg; static int stbi__build_huffman(stbi__huffman *h, int *count) { int i,j,k=0; unsigned int code; // build size list for each symbol (from JPEG spec) for (i=0; i < 16; ++i) { for (j=0; j < count[i]; ++j) { h->size[k++] = (stbi_uc) (i+1); if(k >= 257) return stbi__err("bad size list","Corrupt JPEG"); } } h->size[k] = 0; // compute actual symbols (from jpeg spec) code = 0; k = 0; for(j=1; j <= 16; ++j) { // compute delta to add to code to compute symbol id h->delta[j] = k - code; if (h->size[k] == j) { while (h->size[k] == j) h->code[k++] = (stbi__uint16) (code++); if (code-1 >= (1u << j)) return stbi__err("bad code lengths","Corrupt JPEG"); } // compute largest code + 1 for this size, preshifted as needed later h->maxcode[j] = code << (16-j); code <<= 1; } h->maxcode[j] = 0xffffffff; // build non-spec acceleration table; 255 is flag for not-accelerated memset(h->fast, 255, 1 << FAST_BITS); for (i=0; i < k; ++i) { int s = h->size[i]; if (s <= FAST_BITS) { int c = h->code[i] << (FAST_BITS-s); int m = 1 << (FAST_BITS-s); for (j=0; j < m; ++j) { h->fast[c+j] = (stbi_uc) i; } } } return 1; } // build a table that decodes both magnitude and value of small ACs in // one go. static void stbi__build_fast_ac(stbi__int16 *fast_ac, stbi__huffman *h) { int i; for (i=0; i < (1 << FAST_BITS); ++i) { stbi_uc fast = h->fast[i]; fast_ac[i] = 0; if (fast < 255) { int rs = h->values[fast]; int run = (rs >> 4) & 15; int magbits = rs & 15; int len = h->size[fast]; if (magbits && len + magbits <= FAST_BITS) { // magnitude code followed by receive_extend code int k = ((i << len) & ((1 << FAST_BITS) - 1)) >> (FAST_BITS - magbits); int m = 1 << (magbits - 1); if (k < m) k += (~0U << magbits) + 1; // if the result is small enough, we can fit it in fast_ac table if (k >= -128 && k <= 127) fast_ac[i] = (stbi__int16) ((k * 256) + (run * 16) + (len + magbits)); } } } } static void stbi__grow_buffer_unsafe(stbi__jpeg *j) { do { unsigned int b = j->nomore ? 0 : stbi__get8(j->s); if (b == 0xff) { int c = stbi__get8(j->s); while (c == 0xff) c = stbi__get8(j->s); // consume fill bytes if (c != 0) { j->marker = (unsigned char) c; j->nomore = 1; return; } } j->code_buffer |= b << (24 - j->code_bits); j->code_bits += 8; } while (j->code_bits <= 24); } // (1 << n) - 1 static const stbi__uint32 stbi__bmask[17]={0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535}; // decode a jpeg huffman value from the bitstream stbi_inline static int stbi__jpeg_huff_decode(stbi__jpeg *j, stbi__huffman *h) { unsigned int temp; int c,k; if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); // look at the top FAST_BITS and determine what symbol ID it is, // if the code is <= FAST_BITS c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1); k = h->fast[c]; if (k < 255) { int s = h->size[k]; if (s > j->code_bits) return -1; j->code_buffer <<= s; j->code_bits -= s; return h->values[k]; } // naive test is to shift the code_buffer down so k bits are // valid, then test against maxcode. To speed this up, we've // preshifted maxcode left so that it has (16-k) 0s at the // end; in other words, regardless of the number of bits, it // wants to be compared against something shifted to have 16; // that way we don't need to shift inside the loop. temp = j->code_buffer >> 16; for (k=FAST_BITS+1 ; ; ++k) if (temp < h->maxcode[k]) break; if (k == 17) { // error! code not found j->code_bits -= 16; return -1; } if (k > j->code_bits) return -1; // convert the huffman code to the symbol id c = ((j->code_buffer >> (32 - k)) & stbi__bmask[k]) + h->delta[k]; if(c < 0 || c >= 256) // symbol id out of bounds! return -1; STBI_ASSERT((((j->code_buffer) >> (32 - h->size[c])) & stbi__bmask[h->size[c]]) == h->code[c]); // convert the id to a symbol j->code_bits -= k; j->code_buffer <<= k; return h->values[c]; } // bias[n] = (-1<<n) + 1 static const int stbi__jbias[16] = {0,-1,-3,-7,-15,-31,-63,-127,-255,-511,-1023,-2047,-4095,-8191,-16383,-32767}; // combined JPEG 'receive' and JPEG 'extend', since baseline // always extends everything it receives. stbi_inline static int stbi__extend_receive(stbi__jpeg *j, int n) { unsigned int k; int sgn; if (j->code_bits < n) stbi__grow_buffer_unsafe(j); if (j->code_bits < n) return 0; // ran out of bits from stream, return 0s intead of continuing sgn = j->code_buffer >> 31; // sign bit always in MSB; 0 if MSB clear (positive), 1 if MSB set (negative) k = stbi_lrot(j->code_buffer, n); j->code_buffer = k & ~stbi__bmask[n]; k &= stbi__bmask[n]; j->code_bits -= n; return k + (stbi__jbias[n] & (sgn - 1)); } // get some unsigned bits stbi_inline static int stbi__jpeg_get_bits(stbi__jpeg *j, int n) { unsigned int k; if (j->code_bits < n) stbi__grow_buffer_unsafe(j); if (j->code_bits < n) return 0; // ran out of bits from stream, return 0s intead of continuing k = stbi_lrot(j->code_buffer, n); j->code_buffer = k & ~stbi__bmask[n]; k &= stbi__bmask[n]; j->code_bits -= n; return k; } stbi_inline static int stbi__jpeg_get_bit(stbi__jpeg *j) { unsigned int k; if (j->code_bits < 1) stbi__grow_buffer_unsafe(j); if (j->code_bits < 1) return 0; // ran out of bits from stream, return 0s intead of continuing k = j->code_buffer; j->code_buffer <<= 1; --j->code_bits; return k & 0x80000000; } // given a value that's at position X in the zigzag stream, // where does it appear in the 8x8 matrix coded as row-major? static const stbi_uc stbi__jpeg_dezigzag[64+15] = { 0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63, // let corrupt input sample past end 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63 }; // decode one 64-entry block-- static int stbi__jpeg_decode_block(stbi__jpeg *j, short data[64], stbi__huffman *hdc, stbi__huffman *hac, stbi__int16 *fac, int b, stbi__uint16 *dequant) { int diff,dc,k; int t; if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); t = stbi__jpeg_huff_decode(j, hdc); if (t < 0 || t > 15) return stbi__err("bad huffman code","Corrupt JPEG"); // 0 all the ac values now so we can do it 32-bits at a time memset(data,0,64*sizeof(data[0])); diff = t ? stbi__extend_receive(j, t) : 0; if (!stbi__addints_valid(j->img_comp[b].dc_pred, diff)) return stbi__err("bad delta","Corrupt JPEG"); dc = j->img_comp[b].dc_pred + diff; j->img_comp[b].dc_pred = dc; if (!stbi__mul2shorts_valid(dc, dequant[0])) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); data[0] = (short) (dc * dequant[0]); // decode AC components, see JPEG spec k = 1; do { unsigned int zig; int c,r,s; if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1); r = fac[c]; if (r) { // fast-AC path k += (r >> 4) & 15; // run s = r & 15; // combined length if (s > j->code_bits) return stbi__err("bad huffman code", "Combined length longer than code bits available"); j->code_buffer <<= s; j->code_bits -= s; // decode into unzigzag'd location zig = stbi__jpeg_dezigzag[k++]; data[zig] = (short) ((r >> 8) * dequant[zig]); } else { int rs = stbi__jpeg_huff_decode(j, hac); if (rs < 0) return stbi__err("bad huffman code","Corrupt JPEG"); s = rs & 15; r = rs >> 4; if (s == 0) { if (rs != 0xf0) break; // end block k += 16; } else { k += r; // decode into unzigzag'd location zig = stbi__jpeg_dezigzag[k++]; data[zig] = (short) (stbi__extend_receive(j,s) * dequant[zig]); } } } while (k < 64); return 1; } static int stbi__jpeg_decode_block_prog_dc(stbi__jpeg *j, short data[64], stbi__huffman *hdc, int b) { int diff,dc; int t; if (j->spec_end != 0) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); if (j->succ_high == 0) { // first scan for DC coefficient, must be first memset(data,0,64*sizeof(data[0])); // 0 all the ac values now t = stbi__jpeg_huff_decode(j, hdc); if (t < 0 || t > 15) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); diff = t ? stbi__extend_receive(j, t) : 0; if (!stbi__addints_valid(j->img_comp[b].dc_pred, diff)) return stbi__err("bad delta", "Corrupt JPEG"); dc = j->img_comp[b].dc_pred + diff; j->img_comp[b].dc_pred = dc; if (!stbi__mul2shorts_valid(dc, 1 << j->succ_low)) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); data[0] = (short) (dc * (1 << j->succ_low)); } else { // refinement scan for DC coefficient if (stbi__jpeg_get_bit(j)) data[0] += (short) (1 << j->succ_low); } return 1; } // @OPTIMIZE: store non-zigzagged during the decode passes, // and only de-zigzag when dequantizing static int stbi__jpeg_decode_block_prog_ac(stbi__jpeg *j, short data[64], stbi__huffman *hac, stbi__int16 *fac) { int k; if (j->spec_start == 0) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); if (j->succ_high == 0) { int shift = j->succ_low; if (j->eob_run) { --j->eob_run; return 1; } k = j->spec_start; do { unsigned int zig; int c,r,s; if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1); r = fac[c]; if (r) { // fast-AC path k += (r >> 4) & 15; // run s = r & 15; // combined length if (s > j->code_bits) return stbi__err("bad huffman code", "Combined length longer than code bits available"); j->code_buffer <<= s; j->code_bits -= s; zig = stbi__jpeg_dezigzag[k++]; data[zig] = (short) ((r >> 8) * (1 << shift)); } else { int rs = stbi__jpeg_huff_decode(j, hac); if (rs < 0) return stbi__err("bad huffman code","Corrupt JPEG"); s = rs & 15; r = rs >> 4; if (s == 0) { if (r < 15) { j->eob_run = (1 << r); if (r) j->eob_run += stbi__jpeg_get_bits(j, r); --j->eob_run; break; } k += 16; } else { k += r; zig = stbi__jpeg_dezigzag[k++]; data[zig] = (short) (stbi__extend_receive(j,s) * (1 << shift)); } } } while (k <= j->spec_end); } else { // refinement scan for these AC coefficients short bit = (short) (1 << j->succ_low); if (j->eob_run) { --j->eob_run; for (k = j->spec_start; k <= j->spec_end; ++k) { short *p = &data[stbi__jpeg_dezigzag[k]]; if (*p != 0) if (stbi__jpeg_get_bit(j)) if ((*p & bit)==0) { if (*p > 0) *p += bit; else *p -= bit; } } } else { k = j->spec_start; do { int r,s; int rs = stbi__jpeg_huff_decode(j, hac); // @OPTIMIZE see if we can use the fast path here, advance-by-r is so slow, eh if (rs < 0) return stbi__err("bad huffman code","Corrupt JPEG"); s = rs & 15; r = rs >> 4; if (s == 0) { if (r < 15) { j->eob_run = (1 << r) - 1; if (r) j->eob_run += stbi__jpeg_get_bits(j, r); r = 64; // force end of block } else { // r=15 s=0 should write 16 0s, so we just do // a run of 15 0s and then write s (which is 0), // so we don't have to do anything special here } } else { if (s != 1) return stbi__err("bad huffman code", "Corrupt JPEG"); // sign bit if (stbi__jpeg_get_bit(j)) s = bit; else s = -bit; } // advance by r while (k <= j->spec_end) { short *p = &data[stbi__jpeg_dezigzag[k++]]; if (*p != 0) { if (stbi__jpeg_get_bit(j)) if ((*p & bit)==0) { if (*p > 0) *p += bit; else *p -= bit; } } else { if (r == 0) { *p = (short) s; break; } --r; } } } while (k <= j->spec_end); } } return 1; } // take a -128..127 value and stbi__clamp it and convert to 0..255 stbi_inline static stbi_uc stbi__clamp(int x) { // trick to use a single test to catch both cases if ((unsigned int) x > 255) { if (x < 0) return 0; if (x > 255) return 255; } return (stbi_uc) x; } #define stbi__f2f(x) ((int) (((x) * 4096 + 0.5))) #define stbi__fsh(x) ((x) * 4096) // derived from jidctint -- DCT_ISLOW #define STBI__IDCT_1D(s0,s1,s2,s3,s4,s5,s6,s7) \ int t0,t1,t2,t3,p1,p2,p3,p4,p5,x0,x1,x2,x3; \ p2 = s2; \ p3 = s6; \ p1 = (p2+p3) * stbi__f2f(0.5411961f); \ t2 = p1 + p3*stbi__f2f(-1.847759065f); \ t3 = p1 + p2*stbi__f2f( 0.765366865f); \ p2 = s0; \ p3 = s4; \ t0 = stbi__fsh(p2+p3); \ t1 = stbi__fsh(p2-p3); \ x0 = t0+t3; \ x3 = t0-t3; \ x1 = t1+t2; \ x2 = t1-t2; \ t0 = s7; \ t1 = s5; \ t2 = s3; \ t3 = s1; \ p3 = t0+t2; \ p4 = t1+t3; \ p1 = t0+t3; \ p2 = t1+t2; \ p5 = (p3+p4)*stbi__f2f( 1.175875602f); \ t0 = t0*stbi__f2f( 0.298631336f); \ t1 = t1*stbi__f2f( 2.053119869f); \ t2 = t2*stbi__f2f( 3.072711026f); \ t3 = t3*stbi__f2f( 1.501321110f); \ p1 = p5 + p1*stbi__f2f(-0.899976223f); \ p2 = p5 + p2*stbi__f2f(-2.562915447f); \ p3 = p3*stbi__f2f(-1.961570560f); \ p4 = p4*stbi__f2f(-0.390180644f); \ t3 += p1+p4; \ t2 += p2+p3; \ t1 += p2+p4; \ t0 += p1+p3; static void stbi__idct_block(stbi_uc *out, int out_stride, short data[64]) { int i,val[64],*v=val; stbi_uc *o; short *d = data; // columns for (i=0; i < 8; ++i,++d, ++v) { // if all zeroes, shortcut -- this avoids dequantizing 0s and IDCTing if (d[ 8]==0 && d[16]==0 && d[24]==0 && d[32]==0 && d[40]==0 && d[48]==0 && d[56]==0) { // no shortcut 0 seconds // (1|2|3|4|5|6|7)==0 0 seconds // all separate -0.047 seconds // 1 && 2|3 && 4|5 && 6|7: -0.047 seconds int dcterm = d[0]*4; v[0] = v[8] = v[16] = v[24] = v[32] = v[40] = v[48] = v[56] = dcterm; } else { STBI__IDCT_1D(d[ 0],d[ 8],d[16],d[24],d[32],d[40],d[48],d[56]) // constants scaled things up by 1<<12; let's bring them back // down, but keep 2 extra bits of precision x0 += 512; x1 += 512; x2 += 512; x3 += 512; v[ 0] = (x0+t3) >> 10; v[56] = (x0-t3) >> 10; v[ 8] = (x1+t2) >> 10; v[48] = (x1-t2) >> 10; v[16] = (x2+t1) >> 10; v[40] = (x2-t1) >> 10; v[24] = (x3+t0) >> 10; v[32] = (x3-t0) >> 10; } } for (i=0, v=val, o=out; i < 8; ++i,v+=8,o+=out_stride) { // no fast case since the first 1D IDCT spread components out STBI__IDCT_1D(v[0],v[1],v[2],v[3],v[4],v[5],v[6],v[7]) // constants scaled things up by 1<<12, plus we had 1<<2 from first // loop, plus horizontal and vertical each scale by sqrt(8) so together // we've got an extra 1<<3, so 1<<17 total we need to remove. // so we want to round that, which means adding 0.5 * 1<<17, // aka 65536. Also, we'll end up with -128 to 127 that we want // to encode as 0..255 by adding 128, so we'll add that before the shift x0 += 65536 + (128<<17); x1 += 65536 + (128<<17); x2 += 65536 + (128<<17); x3 += 65536 + (128<<17); // tried computing the shifts into temps, or'ing the temps to see // if any were out of range, but that was slower o[0] = stbi__clamp((x0+t3) >> 17); o[7] = stbi__clamp((x0-t3) >> 17); o[1] = stbi__clamp((x1+t2) >> 17); o[6] = stbi__clamp((x1-t2) >> 17); o[2] = stbi__clamp((x2+t1) >> 17); o[5] = stbi__clamp((x2-t1) >> 17); o[3] = stbi__clamp((x3+t0) >> 17); o[4] = stbi__clamp((x3-t0) >> 17); } } #ifdef STBI_SSE2 // sse2 integer IDCT. not the fastest possible implementation but it // produces bit-identical results to the generic C version so it's // fully "transparent". static void stbi__idct_simd(stbi_uc *out, int out_stride, short data[64]) { // This is constructed to match our regular (generic) integer IDCT exactly. __m128i row0, row1, row2, row3, row4, row5, row6, row7; __m128i tmp; // dot product constant: even elems=x, odd elems=y #define dct_const(x,y) _mm_setr_epi16((x),(y),(x),(y),(x),(y),(x),(y)) // out(0) = c0[even]*x + c0[odd]*y (c0, x, y 16-bit, out 32-bit) // out(1) = c1[even]*x + c1[odd]*y #define dct_rot(out0,out1, x,y,c0,c1) \ __m128i c0##lo = _mm_unpacklo_epi16((x),(y)); \ __m128i c0##hi = _mm_unpackhi_epi16((x),(y)); \ __m128i out0##_l = _mm_madd_epi16(c0##lo, c0); \ __m128i out0##_h = _mm_madd_epi16(c0##hi, c0); \ __m128i out1##_l = _mm_madd_epi16(c0##lo, c1); \ __m128i out1##_h = _mm_madd_epi16(c0##hi, c1) // out = in << 12 (in 16-bit, out 32-bit) #define dct_widen(out, in) \ __m128i out##_l = _mm_srai_epi32(_mm_unpacklo_epi16(_mm_setzero_si128(), (in)), 4); \ __m128i out##_h = _mm_srai_epi32(_mm_unpackhi_epi16(_mm_setzero_si128(), (in)), 4) // wide add #define dct_wadd(out, a, b) \ __m128i out##_l = _mm_add_epi32(a##_l, b##_l); \ __m128i out##_h = _mm_add_epi32(a##_h, b##_h) // wide sub #define dct_wsub(out, a, b) \ __m128i out##_l = _mm_sub_epi32(a##_l, b##_l); \ __m128i out##_h = _mm_sub_epi32(a##_h, b##_h) // butterfly a/b, add bias, then shift by "s" and pack #define dct_bfly32o(out0, out1, a,b,bias,s) \ { \ __m128i abiased_l = _mm_add_epi32(a##_l, bias); \ __m128i abiased_h = _mm_add_epi32(a##_h, bias); \ dct_wadd(sum, abiased, b); \ dct_wsub(dif, abiased, b); \ out0 = _mm_packs_epi32(_mm_srai_epi32(sum_l, s), _mm_srai_epi32(sum_h, s)); \ out1 = _mm_packs_epi32(_mm_srai_epi32(dif_l, s), _mm_srai_epi32(dif_h, s)); \ } // 8-bit interleave step (for transposes) #define dct_interleave8(a, b) \ tmp = a; \ a = _mm_unpacklo_epi8(a, b); \ b = _mm_unpackhi_epi8(tmp, b) // 16-bit interleave step (for transposes) #define dct_interleave16(a, b) \ tmp = a; \ a = _mm_unpacklo_epi16(a, b); \ b = _mm_unpackhi_epi16(tmp, b) #define dct_pass(bias,shift) \ { \ /* even part */ \ dct_rot(t2e,t3e, row2,row6, rot0_0,rot0_1); \ __m128i sum04 = _mm_add_epi16(row0, row4); \ __m128i dif04 = _mm_sub_epi16(row0, row4); \ dct_widen(t0e, sum04); \ dct_widen(t1e, dif04); \ dct_wadd(x0, t0e, t3e); \ dct_wsub(x3, t0e, t3e); \ dct_wadd(x1, t1e, t2e); \ dct_wsub(x2, t1e, t2e); \ /* odd part */ \ dct_rot(y0o,y2o, row7,row3, rot2_0,rot2_1); \ dct_rot(y1o,y3o, row5,row1, rot3_0,rot3_1); \ __m128i sum17 = _mm_add_epi16(row1, row7); \ __m128i sum35 = _mm_add_epi16(row3, row5); \ dct_rot(y4o,y5o, sum17,sum35, rot1_0,rot1_1); \ dct_wadd(x4, y0o, y4o); \ dct_wadd(x5, y1o, y5o); \ dct_wadd(x6, y2o, y5o); \ dct_wadd(x7, y3o, y4o); \ dct_bfly32o(row0,row7, x0,x7,bias,shift); \ dct_bfly32o(row1,row6, x1,x6,bias,shift); \ dct_bfly32o(row2,row5, x2,x5,bias,shift); \ dct_bfly32o(row3,row4, x3,x4,bias,shift); \ } __m128i rot0_0 = dct_const(stbi__f2f(0.5411961f), stbi__f2f(0.5411961f) + stbi__f2f(-1.847759065f)); __m128i rot0_1 = dct_const(stbi__f2f(0.5411961f) + stbi__f2f( 0.765366865f), stbi__f2f(0.5411961f)); __m128i rot1_0 = dct_const(stbi__f2f(1.175875602f) + stbi__f2f(-0.899976223f), stbi__f2f(1.175875602f)); __m128i rot1_1 = dct_const(stbi__f2f(1.175875602f), stbi__f2f(1.175875602f) + stbi__f2f(-2.562915447f)); __m128i rot2_0 = dct_const(stbi__f2f(-1.961570560f) + stbi__f2f( 0.298631336f), stbi__f2f(-1.961570560f)); __m128i rot2_1 = dct_const(stbi__f2f(-1.961570560f), stbi__f2f(-1.961570560f) + stbi__f2f( 3.072711026f)); __m128i rot3_0 = dct_const(stbi__f2f(-0.390180644f) + stbi__f2f( 2.053119869f), stbi__f2f(-0.390180644f)); __m128i rot3_1 = dct_const(stbi__f2f(-0.390180644f), stbi__f2f(-0.390180644f) + stbi__f2f( 1.501321110f)); // rounding biases in column/row passes, see stbi__idct_block for explanation. __m128i bias_0 = _mm_set1_epi32(512); __m128i bias_1 = _mm_set1_epi32(65536 + (128<<17)); // load row0 = _mm_load_si128((const __m128i *) (data + 0*8)); row1 = _mm_load_si128((const __m128i *) (data + 1*8)); row2 = _mm_load_si128((const __m128i *) (data + 2*8)); row3 = _mm_load_si128((const __m128i *) (data + 3*8)); row4 = _mm_load_si128((const __m128i *) (data + 4*8)); row5 = _mm_load_si128((const __m128i *) (data + 5*8)); row6 = _mm_load_si128((const __m128i *) (data + 6*8)); row7 = _mm_load_si128((const __m128i *) (data + 7*8)); // column pass dct_pass(bias_0, 10); { // 16bit 8x8 transpose pass 1 dct_interleave16(row0, row4); dct_interleave16(row1, row5); dct_interleave16(row2, row6); dct_interleave16(row3, row7); // transpose pass 2 dct_interleave16(row0, row2); dct_interleave16(row1, row3); dct_interleave16(row4, row6); dct_interleave16(row5, row7); // transpose pass 3 dct_interleave16(row0, row1); dct_interleave16(row2, row3); dct_interleave16(row4, row5); dct_interleave16(row6, row7); } // row pass dct_pass(bias_1, 17); { // pack __m128i p0 = _mm_packus_epi16(row0, row1); // a0a1a2a3...a7b0b1b2b3...b7 __m128i p1 = _mm_packus_epi16(row2, row3); __m128i p2 = _mm_packus_epi16(row4, row5); __m128i p3 = _mm_packus_epi16(row6, row7); // 8bit 8x8 transpose pass 1 dct_interleave8(p0, p2); // a0e0a1e1... dct_interleave8(p1, p3); // c0g0c1g1... // transpose pass 2 dct_interleave8(p0, p1); // a0c0e0g0... dct_interleave8(p2, p3); // b0d0f0h0... // transpose pass 3 dct_interleave8(p0, p2); // a0b0c0d0... dct_interleave8(p1, p3); // a4b4c4d4... // store _mm_storel_epi64((__m128i *) out, p0); out += out_stride; _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p0, 0x4e)); out += out_stride; _mm_storel_epi64((__m128i *) out, p2); out += out_stride; _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p2, 0x4e)); out += out_stride; _mm_storel_epi64((__m128i *) out, p1); out += out_stride; _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p1, 0x4e)); out += out_stride; _mm_storel_epi64((__m128i *) out, p3); out += out_stride; _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p3, 0x4e)); } #undef dct_const #undef dct_rot #undef dct_widen #undef dct_wadd #undef dct_wsub #undef dct_bfly32o #undef dct_interleave8 #undef dct_interleave16 #undef dct_pass } #endif // STBI_SSE2 #ifdef STBI_NEON // NEON integer IDCT. should produce bit-identical // results to the generic C version. static void stbi__idct_simd(stbi_uc *out, int out_stride, short data[64]) { int16x8_t row0, row1, row2, row3, row4, row5, row6, row7; int16x4_t rot0_0 = vdup_n_s16(stbi__f2f(0.5411961f)); int16x4_t rot0_1 = vdup_n_s16(stbi__f2f(-1.847759065f)); int16x4_t rot0_2 = vdup_n_s16(stbi__f2f( 0.765366865f)); int16x4_t rot1_0 = vdup_n_s16(stbi__f2f( 1.175875602f)); int16x4_t rot1_1 = vdup_n_s16(stbi__f2f(-0.899976223f)); int16x4_t rot1_2 = vdup_n_s16(stbi__f2f(-2.562915447f)); int16x4_t rot2_0 = vdup_n_s16(stbi__f2f(-1.961570560f)); int16x4_t rot2_1 = vdup_n_s16(stbi__f2f(-0.390180644f)); int16x4_t rot3_0 = vdup_n_s16(stbi__f2f( 0.298631336f)); int16x4_t rot3_1 = vdup_n_s16(stbi__f2f( 2.053119869f)); int16x4_t rot3_2 = vdup_n_s16(stbi__f2f( 3.072711026f)); int16x4_t rot3_3 = vdup_n_s16(stbi__f2f( 1.501321110f)); #define dct_long_mul(out, inq, coeff) \ int32x4_t out##_l = vmull_s16(vget_low_s16(inq), coeff); \ int32x4_t out##_h = vmull_s16(vget_high_s16(inq), coeff) #define dct_long_mac(out, acc, inq, coeff) \ int32x4_t out##_l = vmlal_s16(acc##_l, vget_low_s16(inq), coeff); \ int32x4_t out##_h = vmlal_s16(acc##_h, vget_high_s16(inq), coeff) #define dct_widen(out, inq) \ int32x4_t out##_l = vshll_n_s16(vget_low_s16(inq), 12); \ int32x4_t out##_h = vshll_n_s16(vget_high_s16(inq), 12) // wide add #define dct_wadd(out, a, b) \ int32x4_t out##_l = vaddq_s32(a##_l, b##_l); \ int32x4_t out##_h = vaddq_s32(a##_h, b##_h) // wide sub #define dct_wsub(out, a, b) \ int32x4_t out##_l = vsubq_s32(a##_l, b##_l); \ int32x4_t out##_h = vsubq_s32(a##_h, b##_h) // butterfly a/b, then shift using "shiftop" by "s" and pack #define dct_bfly32o(out0,out1, a,b,shiftop,s) \ { \ dct_wadd(sum, a, b); \ dct_wsub(dif, a, b); \ out0 = vcombine_s16(shiftop(sum_l, s), shiftop(sum_h, s)); \ out1 = vcombine_s16(shiftop(dif_l, s), shiftop(dif_h, s)); \ } #define dct_pass(shiftop, shift) \ { \ /* even part */ \ int16x8_t sum26 = vaddq_s16(row2, row6); \ dct_long_mul(p1e, sum26, rot0_0); \ dct_long_mac(t2e, p1e, row6, rot0_1); \ dct_long_mac(t3e, p1e, row2, rot0_2); \ int16x8_t sum04 = vaddq_s16(row0, row4); \ int16x8_t dif04 = vsubq_s16(row0, row4); \ dct_widen(t0e, sum04); \ dct_widen(t1e, dif04); \ dct_wadd(x0, t0e, t3e); \ dct_wsub(x3, t0e, t3e); \ dct_wadd(x1, t1e, t2e); \ dct_wsub(x2, t1e, t2e); \ /* odd part */ \ int16x8_t sum15 = vaddq_s16(row1, row5); \ int16x8_t sum17 = vaddq_s16(row1, row7); \ int16x8_t sum35 = vaddq_s16(row3, row5); \ int16x8_t sum37 = vaddq_s16(row3, row7); \ int16x8_t sumodd = vaddq_s16(sum17, sum35); \ dct_long_mul(p5o, sumodd, rot1_0); \ dct_long_mac(p1o, p5o, sum17, rot1_1); \ dct_long_mac(p2o, p5o, sum35, rot1_2); \ dct_long_mul(p3o, sum37, rot2_0); \ dct_long_mul(p4o, sum15, rot2_1); \ dct_wadd(sump13o, p1o, p3o); \ dct_wadd(sump24o, p2o, p4o); \ dct_wadd(sump23o, p2o, p3o); \ dct_wadd(sump14o, p1o, p4o); \ dct_long_mac(x4, sump13o, row7, rot3_0); \ dct_long_mac(x5, sump24o, row5, rot3_1); \ dct_long_mac(x6, sump23o, row3, rot3_2); \ dct_long_mac(x7, sump14o, row1, rot3_3); \ dct_bfly32o(row0,row7, x0,x7,shiftop,shift); \ dct_bfly32o(row1,row6, x1,x6,shiftop,shift); \ dct_bfly32o(row2,row5, x2,x5,shiftop,shift); \ dct_bfly32o(row3,row4, x3,x4,shiftop,shift); \ } // load row0 = vld1q_s16(data + 0*8); row1 = vld1q_s16(data + 1*8); row2 = vld1q_s16(data + 2*8); row3 = vld1q_s16(data + 3*8); row4 = vld1q_s16(data + 4*8); row5 = vld1q_s16(data + 5*8); row6 = vld1q_s16(data + 6*8); row7 = vld1q_s16(data + 7*8); // add DC bias row0 = vaddq_s16(row0, vsetq_lane_s16(1024, vdupq_n_s16(0), 0)); // column pass dct_pass(vrshrn_n_s32, 10); // 16bit 8x8 transpose { // these three map to a single VTRN.16, VTRN.32, and VSWP, respectively. // whether compilers actually get this is another story, sadly. #define dct_trn16(x, y) { int16x8x2_t t = vtrnq_s16(x, y); x = t.val[0]; y = t.val[1]; } #define dct_trn32(x, y) { int32x4x2_t t = vtrnq_s32(vreinterpretq_s32_s16(x), vreinterpretq_s32_s16(y)); x = vreinterpretq_s16_s32(t.val[0]); y = vreinterpretq_s16_s32(t.val[1]); } #define dct_trn64(x, y) { int16x8_t x0 = x; int16x8_t y0 = y; x = vcombine_s16(vget_low_s16(x0), vget_low_s16(y0)); y = vcombine_s16(vget_high_s16(x0), vget_high_s16(y0)); } // pass 1 dct_trn16(row0, row1); // a0b0a2b2a4b4a6b6 dct_trn16(row2, row3); dct_trn16(row4, row5); dct_trn16(row6, row7); // pass 2 dct_trn32(row0, row2); // a0b0c0d0a4b4c4d4 dct_trn32(row1, row3); dct_trn32(row4, row6); dct_trn32(row5, row7); // pass 3 dct_trn64(row0, row4); // a0b0c0d0e0f0g0h0 dct_trn64(row1, row5); dct_trn64(row2, row6); dct_trn64(row3, row7); #undef dct_trn16 #undef dct_trn32 #undef dct_trn64 } // row pass // vrshrn_n_s32 only supports shifts up to 16, we need // 17. so do a non-rounding shift of 16 first then follow // up with a rounding shift by 1. dct_pass(vshrn_n_s32, 16); { // pack and round uint8x8_t p0 = vqrshrun_n_s16(row0, 1); uint8x8_t p1 = vqrshrun_n_s16(row1, 1); uint8x8_t p2 = vqrshrun_n_s16(row2, 1); uint8x8_t p3 = vqrshrun_n_s16(row3, 1); uint8x8_t p4 = vqrshrun_n_s16(row4, 1); uint8x8_t p5 = vqrshrun_n_s16(row5, 1); uint8x8_t p6 = vqrshrun_n_s16(row6, 1); uint8x8_t p7 = vqrshrun_n_s16(row7, 1); // again, these can translate into one instruction, but often don't. #define dct_trn8_8(x, y) { uint8x8x2_t t = vtrn_u8(x, y); x = t.val[0]; y = t.val[1]; } #define dct_trn8_16(x, y) { uint16x4x2_t t = vtrn_u16(vreinterpret_u16_u8(x), vreinterpret_u16_u8(y)); x = vreinterpret_u8_u16(t.val[0]); y = vreinterpret_u8_u16(t.val[1]); } #define dct_trn8_32(x, y) { uint32x2x2_t t = vtrn_u32(vreinterpret_u32_u8(x), vreinterpret_u32_u8(y)); x = vreinterpret_u8_u32(t.val[0]); y = vreinterpret_u8_u32(t.val[1]); } // sadly can't use interleaved stores here since we only write // 8 bytes to each scan line! // 8x8 8-bit transpose pass 1 dct_trn8_8(p0, p1); dct_trn8_8(p2, p3); dct_trn8_8(p4, p5); dct_trn8_8(p6, p7); // pass 2 dct_trn8_16(p0, p2); dct_trn8_16(p1, p3); dct_trn8_16(p4, p6); dct_trn8_16(p5, p7); // pass 3 dct_trn8_32(p0, p4); dct_trn8_32(p1, p5); dct_trn8_32(p2, p6); dct_trn8_32(p3, p7); // store vst1_u8(out, p0); out += out_stride; vst1_u8(out, p1); out += out_stride; vst1_u8(out, p2); out += out_stride; vst1_u8(out, p3); out += out_stride; vst1_u8(out, p4); out += out_stride; vst1_u8(out, p5); out += out_stride; vst1_u8(out, p6); out += out_stride; vst1_u8(out, p7); #undef dct_trn8_8 #undef dct_trn8_16 #undef dct_trn8_32 } #undef dct_long_mul #undef dct_long_mac #undef dct_widen #undef dct_wadd #undef dct_wsub #undef dct_bfly32o #undef dct_pass } #endif // STBI_NEON #define STBI__MARKER_none 0xff // if there's a pending marker from the entropy stream, return that // otherwise, fetch from the stream and get a marker. if there's no // marker, return 0xff, which is never a valid marker value static stbi_uc stbi__get_marker(stbi__jpeg *j) { stbi_uc x; if (j->marker != STBI__MARKER_none) { x = j->marker; j->marker = STBI__MARKER_none; return x; } x = stbi__get8(j->s); if (x != 0xff) return STBI__MARKER_none; while (x == 0xff) x = stbi__get8(j->s); // consume repeated 0xff fill bytes return x; } // in each scan, we'll have scan_n components, and the order // of the components is specified by order[] #define STBI__RESTART(x) ((x) >= 0xd0 && (x) <= 0xd7) // after a restart interval, stbi__jpeg_reset the entropy decoder and // the dc prediction static void stbi__jpeg_reset(stbi__jpeg *j) { j->code_bits = 0; j->code_buffer = 0; j->nomore = 0; j->img_comp[0].dc_pred = j->img_comp[1].dc_pred = j->img_comp[2].dc_pred = j->img_comp[3].dc_pred = 0; j->marker = STBI__MARKER_none; j->todo = j->restart_interval ? j->restart_interval : 0x7fffffff; j->eob_run = 0; // no more than 1<<31 MCUs if no restart_interal? that's plenty safe, // since we don't even allow 1<<30 pixels } static int stbi__parse_entropy_coded_data(stbi__jpeg *z) { stbi__jpeg_reset(z); if (!z->progressive) { if (z->scan_n == 1) { int i,j; STBI_SIMD_ALIGN(short, data[64]); int n = z->order[0]; // non-interleaved data, we just need to process one block at a time, // in trivial scanline order // number of blocks to do just depends on how many actual "pixels" this // component has, independent of interleaved MCU blocking and such int w = (z->img_comp[n].x+7) >> 3; int h = (z->img_comp[n].y+7) >> 3; for (j=0; j < h; ++j) { for (i=0; i < w; ++i) { int ha = z->img_comp[n].ha; if (!stbi__jpeg_decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+ha, z->fast_ac[ha], n, z->dequant[z->img_comp[n].tq])) return 0; z->idct_block_kernel(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data); // every data block is an MCU, so countdown the restart interval if (--z->todo <= 0) { if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); // if it's NOT a restart, then just bail, so we get corrupt data // rather than no data if (!STBI__RESTART(z->marker)) return 1; stbi__jpeg_reset(z); } } } return 1; } else { // interleaved int i,j,k,x,y; STBI_SIMD_ALIGN(short, data[64]); for (j=0; j < z->img_mcu_y; ++j) { for (i=0; i < z->img_mcu_x; ++i) { // scan an interleaved mcu... process scan_n components in order for (k=0; k < z->scan_n; ++k) { int n = z->order[k]; // scan out an mcu's worth of this component; that's just determined // by the basic H and V specified for the component for (y=0; y < z->img_comp[n].v; ++y) { for (x=0; x < z->img_comp[n].h; ++x) { int x2 = (i*z->img_comp[n].h + x)*8; int y2 = (j*z->img_comp[n].v + y)*8; int ha = z->img_comp[n].ha; if (!stbi__jpeg_decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+ha, z->fast_ac[ha], n, z->dequant[z->img_comp[n].tq])) return 0; z->idct_block_kernel(z->img_comp[n].data+z->img_comp[n].w2*y2+x2, z->img_comp[n].w2, data); } } } // after all interleaved components, that's an interleaved MCU, // so now count down the restart interval if (--z->todo <= 0) { if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); if (!STBI__RESTART(z->marker)) return 1; stbi__jpeg_reset(z); } } } return 1; } } else { if (z->scan_n == 1) { int i,j; int n = z->order[0]; // non-interleaved data, we just need to process one block at a time, // in trivial scanline order // number of blocks to do just depends on how many actual "pixels" this // component has, independent of interleaved MCU blocking and such int w = (z->img_comp[n].x+7) >> 3; int h = (z->img_comp[n].y+7) >> 3; for (j=0; j < h; ++j) { for (i=0; i < w; ++i) { short *data = z->img_comp[n].coeff + 64 * (i + j * z->img_comp[n].coeff_w); if (z->spec_start == 0) { if (!stbi__jpeg_decode_block_prog_dc(z, data, &z->huff_dc[z->img_comp[n].hd], n)) return 0; } else { int ha = z->img_comp[n].ha; if (!stbi__jpeg_decode_block_prog_ac(z, data, &z->huff_ac[ha], z->fast_ac[ha])) return 0; } // every data block is an MCU, so countdown the restart interval if (--z->todo <= 0) { if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); if (!STBI__RESTART(z->marker)) return 1; stbi__jpeg_reset(z); } } } return 1; } else { // interleaved int i,j,k,x,y; for (j=0; j < z->img_mcu_y; ++j) { for (i=0; i < z->img_mcu_x; ++i) { // scan an interleaved mcu... process scan_n components in order for (k=0; k < z->scan_n; ++k) { int n = z->order[k]; // scan out an mcu's worth of this component; that's just determined // by the basic H and V specified for the component for (y=0; y < z->img_comp[n].v; ++y) { for (x=0; x < z->img_comp[n].h; ++x) { int x2 = (i*z->img_comp[n].h + x); int y2 = (j*z->img_comp[n].v + y); short *data = z->img_comp[n].coeff + 64 * (x2 + y2 * z->img_comp[n].coeff_w); if (!stbi__jpeg_decode_block_prog_dc(z, data, &z->huff_dc[z->img_comp[n].hd], n)) return 0; } } } // after all interleaved components, that's an interleaved MCU, // so now count down the restart interval if (--z->todo <= 0) { if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); if (!STBI__RESTART(z->marker)) return 1; stbi__jpeg_reset(z); } } } return 1; } } } static void stbi__jpeg_dequantize(short *data, stbi__uint16 *dequant) { int i; for (i=0; i < 64; ++i) data[i] *= dequant[i]; } static void stbi__jpeg_finish(stbi__jpeg *z) { if (z->progressive) { // dequantize and idct the data int i,j,n; for (n=0; n < z->s->img_n; ++n) { int w = (z->img_comp[n].x+7) >> 3; int h = (z->img_comp[n].y+7) >> 3; for (j=0; j < h; ++j) { for (i=0; i < w; ++i) { short *data = z->img_comp[n].coeff + 64 * (i + j * z->img_comp[n].coeff_w); stbi__jpeg_dequantize(data, z->dequant[z->img_comp[n].tq]); z->idct_block_kernel(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data); } } } } } static int stbi__process_marker(stbi__jpeg *z, int m) { int L; switch (m) { case STBI__MARKER_none: // no marker found return stbi__err("expected marker","Corrupt JPEG"); case 0xDD: // DRI - specify restart interval if (stbi__get16be(z->s) != 4) return stbi__err("bad DRI len","Corrupt JPEG"); z->restart_interval = stbi__get16be(z->s); return 1; case 0xDB: // DQT - define quantization table L = stbi__get16be(z->s)-2; while (L > 0) { int q = stbi__get8(z->s); int p = q >> 4, sixteen = (p != 0); int t = q & 15,i; if (p != 0 && p != 1) return stbi__err("bad DQT type","Corrupt JPEG"); if (t > 3) return stbi__err("bad DQT table","Corrupt JPEG"); for (i=0; i < 64; ++i) z->dequant[t][stbi__jpeg_dezigzag[i]] = (stbi__uint16)(sixteen ? stbi__get16be(z->s) : stbi__get8(z->s)); L -= (sixteen ? 129 : 65); } return L==0; case 0xC4: // DHT - define huffman table L = stbi__get16be(z->s)-2; while (L > 0) { stbi_uc *v; int sizes[16],i,n=0; int q = stbi__get8(z->s); int tc = q >> 4; int th = q & 15; if (tc > 1 || th > 3) return stbi__err("bad DHT header","Corrupt JPEG"); for (i=0; i < 16; ++i) { sizes[i] = stbi__get8(z->s); n += sizes[i]; } if(n > 256) return stbi__err("bad DHT header","Corrupt JPEG"); // Loop over i < n would write past end of values! L -= 17; if (tc == 0) { if (!stbi__build_huffman(z->huff_dc+th, sizes)) return 0; v = z->huff_dc[th].values; } else { if (!stbi__build_huffman(z->huff_ac+th, sizes)) return 0; v = z->huff_ac[th].values; } for (i=0; i < n; ++i) v[i] = stbi__get8(z->s); if (tc != 0) stbi__build_fast_ac(z->fast_ac[th], z->huff_ac + th); L -= n; } return L==0; } // check for comment block or APP blocks if ((m >= 0xE0 && m <= 0xEF) || m == 0xFE) { L = stbi__get16be(z->s); if (L < 2) { if (m == 0xFE) return stbi__err("bad COM len","Corrupt JPEG"); else return stbi__err("bad APP len","Corrupt JPEG"); } L -= 2; if (m == 0xE0 && L >= 5) { // JFIF APP0 segment static const unsigned char tag[5] = {'J','F','I','F','\0'}; int ok = 1; int i; for (i=0; i < 5; ++i) if (stbi__get8(z->s) != tag[i]) ok = 0; L -= 5; if (ok) z->jfif = 1; } else if (m == 0xEE && L >= 12) { // Adobe APP14 segment static const unsigned char tag[6] = {'A','d','o','b','e','\0'}; int ok = 1; int i; for (i=0; i < 6; ++i) if (stbi__get8(z->s) != tag[i]) ok = 0; L -= 6; if (ok) { stbi__get8(z->s); // version stbi__get16be(z->s); // flags0 stbi__get16be(z->s); // flags1 z->app14_color_transform = stbi__get8(z->s); // color transform L -= 6; } } stbi__skip(z->s, L); return 1; } return stbi__err("unknown marker","Corrupt JPEG"); } // after we see SOS static int stbi__process_scan_header(stbi__jpeg *z) { int i; int Ls = stbi__get16be(z->s); z->scan_n = stbi__get8(z->s); if (z->scan_n < 1 || z->scan_n > 4 || z->scan_n > (int) z->s->img_n) return stbi__err("bad SOS component count","Corrupt JPEG"); if (Ls != 6+2*z->scan_n) return stbi__err("bad SOS len","Corrupt JPEG"); for (i=0; i < z->scan_n; ++i) { int id = stbi__get8(z->s), which; int q = stbi__get8(z->s); for (which = 0; which < z->s->img_n; ++which) if (z->img_comp[which].id == id) break; if (which == z->s->img_n) return 0; // no match z->img_comp[which].hd = q >> 4; if (z->img_comp[which].hd > 3) return stbi__err("bad DC huff","Corrupt JPEG"); z->img_comp[which].ha = q & 15; if (z->img_comp[which].ha > 3) return stbi__err("bad AC huff","Corrupt JPEG"); z->order[i] = which; } { int aa; z->spec_start = stbi__get8(z->s); z->spec_end = stbi__get8(z->s); // should be 63, but might be 0 aa = stbi__get8(z->s); z->succ_high = (aa >> 4); z->succ_low = (aa & 15); if (z->progressive) { if (z->spec_start > 63 || z->spec_end > 63 || z->spec_start > z->spec_end || z->succ_high > 13 || z->succ_low > 13) return stbi__err("bad SOS", "Corrupt JPEG"); } else { if (z->spec_start != 0) return stbi__err("bad SOS","Corrupt JPEG"); if (z->succ_high != 0 || z->succ_low != 0) return stbi__err("bad SOS","Corrupt JPEG"); z->spec_end = 63; } } return 1; } static int stbi__free_jpeg_components(stbi__jpeg *z, int ncomp, int why) { int i; for (i=0; i < ncomp; ++i) { if (z->img_comp[i].raw_data) { STBI_FREE(z->img_comp[i].raw_data); z->img_comp[i].raw_data = NULL; z->img_comp[i].data = NULL; } if (z->img_comp[i].raw_coeff) { STBI_FREE(z->img_comp[i].raw_coeff); z->img_comp[i].raw_coeff = 0; z->img_comp[i].coeff = 0; } if (z->img_comp[i].linebuf) { STBI_FREE(z->img_comp[i].linebuf); z->img_comp[i].linebuf = NULL; } } return why; } static int stbi__process_frame_header(stbi__jpeg *z, int scan) { stbi__context *s = z->s; int Lf,p,i,q, h_max=1,v_max=1,c; Lf = stbi__get16be(s); if (Lf < 11) return stbi__err("bad SOF len","Corrupt JPEG"); // JPEG p = stbi__get8(s); if (p != 8) return stbi__err("only 8-bit","JPEG format not supported: 8-bit only"); // JPEG baseline s->img_y = stbi__get16be(s); if (s->img_y == 0) return stbi__err("no header height", "JPEG format not supported: delayed height"); // Legal, but we don't handle it--but neither does IJG s->img_x = stbi__get16be(s); if (s->img_x == 0) return stbi__err("0 width","Corrupt JPEG"); // JPEG requires if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); c = stbi__get8(s); if (c != 3 && c != 1 && c != 4) return stbi__err("bad component count","Corrupt JPEG"); s->img_n = c; for (i=0; i < c; ++i) { z->img_comp[i].data = NULL; z->img_comp[i].linebuf = NULL; } if (Lf != 8+3*s->img_n) return stbi__err("bad SOF len","Corrupt JPEG"); z->rgb = 0; for (i=0; i < s->img_n; ++i) { static const unsigned char rgb[3] = { 'R', 'G', 'B' }; z->img_comp[i].id = stbi__get8(s); if (s->img_n == 3 && z->img_comp[i].id == rgb[i]) ++z->rgb; q = stbi__get8(s); z->img_comp[i].h = (q >> 4); if (!z->img_comp[i].h || z->img_comp[i].h > 4) return stbi__err("bad H","Corrupt JPEG"); z->img_comp[i].v = q & 15; if (!z->img_comp[i].v || z->img_comp[i].v > 4) return stbi__err("bad V","Corrupt JPEG"); z->img_comp[i].tq = stbi__get8(s); if (z->img_comp[i].tq > 3) return stbi__err("bad TQ","Corrupt JPEG"); } if (scan != STBI__SCAN_load) return 1; if (!stbi__mad3sizes_valid(s->img_x, s->img_y, s->img_n, 0)) return stbi__err("too large", "Image too large to decode"); for (i=0; i < s->img_n; ++i) { if (z->img_comp[i].h > h_max) h_max = z->img_comp[i].h; if (z->img_comp[i].v > v_max) v_max = z->img_comp[i].v; } // check that plane subsampling factors are integer ratios; our resamplers can't deal with fractional ratios // and I've never seen a non-corrupted JPEG file actually use them for (i=0; i < s->img_n; ++i) { if (h_max % z->img_comp[i].h != 0) return stbi__err("bad H","Corrupt JPEG"); if (v_max % z->img_comp[i].v != 0) return stbi__err("bad V","Corrupt JPEG"); } // compute interleaved mcu info z->img_h_max = h_max; z->img_v_max = v_max; z->img_mcu_w = h_max * 8; z->img_mcu_h = v_max * 8; // these sizes can't be more than 17 bits z->img_mcu_x = (s->img_x + z->img_mcu_w-1) / z->img_mcu_w; z->img_mcu_y = (s->img_y + z->img_mcu_h-1) / z->img_mcu_h; for (i=0; i < s->img_n; ++i) { // number of effective pixels (e.g. for non-interleaved MCU) z->img_comp[i].x = (s->img_x * z->img_comp[i].h + h_max-1) / h_max; z->img_comp[i].y = (s->img_y * z->img_comp[i].v + v_max-1) / v_max; // to simplify generation, we'll allocate enough memory to decode // the bogus oversized data from using interleaved MCUs and their // big blocks (e.g. a 16x16 iMCU on an image of width 33); we won't // discard the extra data until colorspace conversion // // img_mcu_x, img_mcu_y: <=17 bits; comp[i].h and .v are <=4 (checked earlier) // so these muls can't overflow with 32-bit ints (which we require) z->img_comp[i].w2 = z->img_mcu_x * z->img_comp[i].h * 8; z->img_comp[i].h2 = z->img_mcu_y * z->img_comp[i].v * 8; z->img_comp[i].coeff = 0; z->img_comp[i].raw_coeff = 0; z->img_comp[i].linebuf = NULL; z->img_comp[i].raw_data = stbi__malloc_mad2(z->img_comp[i].w2, z->img_comp[i].h2, 15); if (z->img_comp[i].raw_data == NULL) return stbi__free_jpeg_components(z, i+1, stbi__err("outofmem", "Out of memory")); // align blocks for idct using mmx/sse z->img_comp[i].data = (stbi_uc*) (((size_t) z->img_comp[i].raw_data + 15) & ~15); if (z->progressive) { // w2, h2 are multiples of 8 (see above) z->img_comp[i].coeff_w = z->img_comp[i].w2 / 8; z->img_comp[i].coeff_h = z->img_comp[i].h2 / 8; z->img_comp[i].raw_coeff = stbi__malloc_mad3(z->img_comp[i].w2, z->img_comp[i].h2, sizeof(short), 15); if (z->img_comp[i].raw_coeff == NULL) return stbi__free_jpeg_components(z, i+1, stbi__err("outofmem", "Out of memory")); z->img_comp[i].coeff = (short*) (((size_t) z->img_comp[i].raw_coeff + 15) & ~15); } } return 1; } // use comparisons since in some cases we handle more than one case (e.g. SOF) #define stbi__DNL(x) ((x) == 0xdc) #define stbi__SOI(x) ((x) == 0xd8) #define stbi__EOI(x) ((x) == 0xd9) #define stbi__SOF(x) ((x) == 0xc0 || (x) == 0xc1 || (x) == 0xc2) #define stbi__SOS(x) ((x) == 0xda) #define stbi__SOF_progressive(x) ((x) == 0xc2) static int stbi__decode_jpeg_header(stbi__jpeg *z, int scan) { int m; z->jfif = 0; z->app14_color_transform = -1; // valid values are 0,1,2 z->marker = STBI__MARKER_none; // initialize cached marker to empty m = stbi__get_marker(z); if (!stbi__SOI(m)) return stbi__err("no SOI","Corrupt JPEG"); if (scan == STBI__SCAN_type) return 1; m = stbi__get_marker(z); while (!stbi__SOF(m)) { if (!stbi__process_marker(z,m)) return 0; m = stbi__get_marker(z); while (m == STBI__MARKER_none) { // some files have extra padding after their blocks, so ok, we'll scan if (stbi__at_eof(z->s)) return stbi__err("no SOF", "Corrupt JPEG"); m = stbi__get_marker(z); } } z->progressive = stbi__SOF_progressive(m); if (!stbi__process_frame_header(z, scan)) return 0; return 1; } static int stbi__skip_jpeg_junk_at_end(stbi__jpeg *j) { // some JPEGs have junk at end, skip over it but if we find what looks // like a valid marker, resume there while (!stbi__at_eof(j->s)) { int x = stbi__get8(j->s); while (x == 255) { // might be a marker if (stbi__at_eof(j->s)) return STBI__MARKER_none; x = stbi__get8(j->s); if (x != 0x00 && x != 0xff) { // not a stuffed zero or lead-in to another marker, looks // like an actual marker, return it return x; } // stuffed zero has x=0 now which ends the loop, meaning we go // back to regular scan loop. // repeated 0xff keeps trying to read the next byte of the marker. } } return STBI__MARKER_none; } // decode image to YCbCr format static int stbi__decode_jpeg_image(stbi__jpeg *j) { int m; for (m = 0; m < 4; m++) { j->img_comp[m].raw_data = NULL; j->img_comp[m].raw_coeff = NULL; } j->restart_interval = 0; if (!stbi__decode_jpeg_header(j, STBI__SCAN_load)) return 0; m = stbi__get_marker(j); while (!stbi__EOI(m)) { if (stbi__SOS(m)) { if (!stbi__process_scan_header(j)) return 0; if (!stbi__parse_entropy_coded_data(j)) return 0; if (j->marker == STBI__MARKER_none ) { j->marker = stbi__skip_jpeg_junk_at_end(j); // if we reach eof without hitting a marker, stbi__get_marker() below will fail and we'll eventually return 0 } m = stbi__get_marker(j); if (STBI__RESTART(m)) m = stbi__get_marker(j); } else if (stbi__DNL(m)) { int Ld = stbi__get16be(j->s); stbi__uint32 NL = stbi__get16be(j->s); if (Ld != 4) return stbi__err("bad DNL len", "Corrupt JPEG"); if (NL != j->s->img_y) return stbi__err("bad DNL height", "Corrupt JPEG"); m = stbi__get_marker(j); } else { if (!stbi__process_marker(j, m)) return 1; m = stbi__get_marker(j); } } if (j->progressive) stbi__jpeg_finish(j); return 1; } // static jfif-centered resampling (across block boundaries) typedef stbi_uc *(*resample_row_func)(stbi_uc *out, stbi_uc *in0, stbi_uc *in1, int w, int hs); #define stbi__div4(x) ((stbi_uc) ((x) >> 2)) static stbi_uc *resample_row_1(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) { STBI_NOTUSED(out); STBI_NOTUSED(in_far); STBI_NOTUSED(w); STBI_NOTUSED(hs); return in_near; } static stbi_uc* stbi__resample_row_v_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) { // need to generate two samples vertically for every one in input int i; STBI_NOTUSED(hs); for (i=0; i < w; ++i) out[i] = stbi__div4(3*in_near[i] + in_far[i] + 2); return out; } static stbi_uc* stbi__resample_row_h_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) { // need to generate two samples horizontally for every one in input int i; stbi_uc *input = in_near; if (w == 1) { // if only one sample, can't do any interpolation out[0] = out[1] = input[0]; return out; } out[0] = input[0]; out[1] = stbi__div4(input[0]*3 + input[1] + 2); for (i=1; i < w-1; ++i) { int n = 3*input[i]+2; out[i*2+0] = stbi__div4(n+input[i-1]); out[i*2+1] = stbi__div4(n+input[i+1]); } out[i*2+0] = stbi__div4(input[w-2]*3 + input[w-1] + 2); out[i*2+1] = input[w-1]; STBI_NOTUSED(in_far); STBI_NOTUSED(hs); return out; } #define stbi__div16(x) ((stbi_uc) ((x) >> 4)) static stbi_uc *stbi__resample_row_hv_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) { // need to generate 2x2 samples for every one in input int i,t0,t1; if (w == 1) { out[0] = out[1] = stbi__div4(3*in_near[0] + in_far[0] + 2); return out; } t1 = 3*in_near[0] + in_far[0]; out[0] = stbi__div4(t1+2); for (i=1; i < w; ++i) { t0 = t1; t1 = 3*in_near[i]+in_far[i]; out[i*2-1] = stbi__div16(3*t0 + t1 + 8); out[i*2 ] = stbi__div16(3*t1 + t0 + 8); } out[w*2-1] = stbi__div4(t1+2); STBI_NOTUSED(hs); return out; } #if defined(STBI_SSE2) || defined(STBI_NEON) static stbi_uc *stbi__resample_row_hv_2_simd(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) { // need to generate 2x2 samples for every one in input int i=0,t0,t1; if (w == 1) { out[0] = out[1] = stbi__div4(3*in_near[0] + in_far[0] + 2); return out; } t1 = 3*in_near[0] + in_far[0]; // process groups of 8 pixels for as long as we can. // note we can't handle the last pixel in a row in this loop // because we need to handle the filter boundary conditions. for (; i < ((w-1) & ~7); i += 8) { #if defined(STBI_SSE2) // load and perform the vertical filtering pass // this uses 3*x + y = 4*x + (y - x) __m128i zero = _mm_setzero_si128(); __m128i farb = _mm_loadl_epi64((__m128i *) (in_far + i)); __m128i nearb = _mm_loadl_epi64((__m128i *) (in_near + i)); __m128i farw = _mm_unpacklo_epi8(farb, zero); __m128i nearw = _mm_unpacklo_epi8(nearb, zero); __m128i diff = _mm_sub_epi16(farw, nearw); __m128i nears = _mm_slli_epi16(nearw, 2); __m128i curr = _mm_add_epi16(nears, diff); // current row // horizontal filter works the same based on shifted vers of current // row. "prev" is current row shifted right by 1 pixel; we need to // insert the previous pixel value (from t1). // "next" is current row shifted left by 1 pixel, with first pixel // of next block of 8 pixels added in. __m128i prv0 = _mm_slli_si128(curr, 2); __m128i nxt0 = _mm_srli_si128(curr, 2); __m128i prev = _mm_insert_epi16(prv0, t1, 0); __m128i next = _mm_insert_epi16(nxt0, 3*in_near[i+8] + in_far[i+8], 7); // horizontal filter, polyphase implementation since it's convenient: // even pixels = 3*cur + prev = cur*4 + (prev - cur) // odd pixels = 3*cur + next = cur*4 + (next - cur) // note the shared term. __m128i bias = _mm_set1_epi16(8); __m128i curs = _mm_slli_epi16(curr, 2); __m128i prvd = _mm_sub_epi16(prev, curr); __m128i nxtd = _mm_sub_epi16(next, curr); __m128i curb = _mm_add_epi16(curs, bias); __m128i even = _mm_add_epi16(prvd, curb); __m128i odd = _mm_add_epi16(nxtd, curb); // interleave even and odd pixels, then undo scaling. __m128i int0 = _mm_unpacklo_epi16(even, odd); __m128i int1 = _mm_unpackhi_epi16(even, odd); __m128i de0 = _mm_srli_epi16(int0, 4); __m128i de1 = _mm_srli_epi16(int1, 4); // pack and write output __m128i outv = _mm_packus_epi16(de0, de1); _mm_storeu_si128((__m128i *) (out + i*2), outv); #elif defined(STBI_NEON) // load and perform the vertical filtering pass // this uses 3*x + y = 4*x + (y - x) uint8x8_t farb = vld1_u8(in_far + i); uint8x8_t nearb = vld1_u8(in_near + i); int16x8_t diff = vreinterpretq_s16_u16(vsubl_u8(farb, nearb)); int16x8_t nears = vreinterpretq_s16_u16(vshll_n_u8(nearb, 2)); int16x8_t curr = vaddq_s16(nears, diff); // current row // horizontal filter works the same based on shifted vers of current // row. "prev" is current row shifted right by 1 pixel; we need to // insert the previous pixel value (from t1). // "next" is current row shifted left by 1 pixel, with first pixel // of next block of 8 pixels added in. int16x8_t prv0 = vextq_s16(curr, curr, 7); int16x8_t nxt0 = vextq_s16(curr, curr, 1); int16x8_t prev = vsetq_lane_s16(t1, prv0, 0); int16x8_t next = vsetq_lane_s16(3*in_near[i+8] + in_far[i+8], nxt0, 7); // horizontal filter, polyphase implementation since it's convenient: // even pixels = 3*cur + prev = cur*4 + (prev - cur) // odd pixels = 3*cur + next = cur*4 + (next - cur) // note the shared term. int16x8_t curs = vshlq_n_s16(curr, 2); int16x8_t prvd = vsubq_s16(prev, curr); int16x8_t nxtd = vsubq_s16(next, curr); int16x8_t even = vaddq_s16(curs, prvd); int16x8_t odd = vaddq_s16(curs, nxtd); // undo scaling and round, then store with even/odd phases interleaved uint8x8x2_t o; o.val[0] = vqrshrun_n_s16(even, 4); o.val[1] = vqrshrun_n_s16(odd, 4); vst2_u8(out + i*2, o); #endif // "previous" value for next iter t1 = 3*in_near[i+7] + in_far[i+7]; } t0 = t1; t1 = 3*in_near[i] + in_far[i]; out[i*2] = stbi__div16(3*t1 + t0 + 8); for (++i; i < w; ++i) { t0 = t1; t1 = 3*in_near[i]+in_far[i]; out[i*2-1] = stbi__div16(3*t0 + t1 + 8); out[i*2 ] = stbi__div16(3*t1 + t0 + 8); } out[w*2-1] = stbi__div4(t1+2); STBI_NOTUSED(hs); return out; } #endif static stbi_uc *stbi__resample_row_generic(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) { // resample with nearest-neighbor int i,j; STBI_NOTUSED(in_far); for (i=0; i < w; ++i) for (j=0; j < hs; ++j) out[i*hs+j] = in_near[i]; return out; } // this is a reduced-precision calculation of YCbCr-to-RGB introduced // to make sure the code produces the same results in both SIMD and scalar #define stbi__float2fixed(x) (((int) ((x) * 4096.0f + 0.5f)) << 8) static void stbi__YCbCr_to_RGB_row(stbi_uc *out, const stbi_uc *y, const stbi_uc *pcb, const stbi_uc *pcr, int count, int step) { int i; for (i=0; i < count; ++i) { int y_fixed = (y[i] << 20) + (1<<19); // rounding int r,g,b; int cr = pcr[i] - 128; int cb = pcb[i] - 128; r = y_fixed + cr* stbi__float2fixed(1.40200f); g = y_fixed + (cr*-stbi__float2fixed(0.71414f)) + ((cb*-stbi__float2fixed(0.34414f)) & 0xffff0000); b = y_fixed + cb* stbi__float2fixed(1.77200f); r >>= 20; g >>= 20; b >>= 20; if ((unsigned) r > 255) { if (r < 0) r = 0; else r = 255; } if ((unsigned) g > 255) { if (g < 0) g = 0; else g = 255; } if ((unsigned) b > 255) { if (b < 0) b = 0; else b = 255; } out[0] = (stbi_uc)r; out[1] = (stbi_uc)g; out[2] = (stbi_uc)b; out[3] = 255; out += step; } } #if defined(STBI_SSE2) || defined(STBI_NEON) static void stbi__YCbCr_to_RGB_simd(stbi_uc *out, stbi_uc const *y, stbi_uc const *pcb, stbi_uc const *pcr, int count, int step) { int i = 0; #ifdef STBI_SSE2 // step == 3 is pretty ugly on the final interleave, and i'm not convinced // it's useful in practice (you wouldn't use it for textures, for example). // so just accelerate step == 4 case. if (step == 4) { // this is a fairly straightforward implementation and not super-optimized. __m128i signflip = _mm_set1_epi8(-0x80); __m128i cr_const0 = _mm_set1_epi16( (short) ( 1.40200f*4096.0f+0.5f)); __m128i cr_const1 = _mm_set1_epi16( - (short) ( 0.71414f*4096.0f+0.5f)); __m128i cb_const0 = _mm_set1_epi16( - (short) ( 0.34414f*4096.0f+0.5f)); __m128i cb_const1 = _mm_set1_epi16( (short) ( 1.77200f*4096.0f+0.5f)); __m128i y_bias = _mm_set1_epi8((char) (unsigned char) 128); __m128i xw = _mm_set1_epi16(255); // alpha channel for (; i+7 < count; i += 8) { // load __m128i y_bytes = _mm_loadl_epi64((__m128i *) (y+i)); __m128i cr_bytes = _mm_loadl_epi64((__m128i *) (pcr+i)); __m128i cb_bytes = _mm_loadl_epi64((__m128i *) (pcb+i)); __m128i cr_biased = _mm_xor_si128(cr_bytes, signflip); // -128 __m128i cb_biased = _mm_xor_si128(cb_bytes, signflip); // -128 // unpack to short (and left-shift cr, cb by 8) __m128i yw = _mm_unpacklo_epi8(y_bias, y_bytes); __m128i crw = _mm_unpacklo_epi8(_mm_setzero_si128(), cr_biased); __m128i cbw = _mm_unpacklo_epi8(_mm_setzero_si128(), cb_biased); // color transform __m128i yws = _mm_srli_epi16(yw, 4); __m128i cr0 = _mm_mulhi_epi16(cr_const0, crw); __m128i cb0 = _mm_mulhi_epi16(cb_const0, cbw); __m128i cb1 = _mm_mulhi_epi16(cbw, cb_const1); __m128i cr1 = _mm_mulhi_epi16(crw, cr_const1); __m128i rws = _mm_add_epi16(cr0, yws); __m128i gwt = _mm_add_epi16(cb0, yws); __m128i bws = _mm_add_epi16(yws, cb1); __m128i gws = _mm_add_epi16(gwt, cr1); // descale __m128i rw = _mm_srai_epi16(rws, 4); __m128i bw = _mm_srai_epi16(bws, 4); __m128i gw = _mm_srai_epi16(gws, 4); // back to byte, set up for transpose __m128i brb = _mm_packus_epi16(rw, bw); __m128i gxb = _mm_packus_epi16(gw, xw); // transpose to interleave channels __m128i t0 = _mm_unpacklo_epi8(brb, gxb); __m128i t1 = _mm_unpackhi_epi8(brb, gxb); __m128i o0 = _mm_unpacklo_epi16(t0, t1); __m128i o1 = _mm_unpackhi_epi16(t0, t1); // store _mm_storeu_si128((__m128i *) (out + 0), o0); _mm_storeu_si128((__m128i *) (out + 16), o1); out += 32; } } #endif #ifdef STBI_NEON // in this version, step=3 support would be easy to add. but is there demand? if (step == 4) { // this is a fairly straightforward implementation and not super-optimized. uint8x8_t signflip = vdup_n_u8(0x80); int16x8_t cr_const0 = vdupq_n_s16( (short) ( 1.40200f*4096.0f+0.5f)); int16x8_t cr_const1 = vdupq_n_s16( - (short) ( 0.71414f*4096.0f+0.5f)); int16x8_t cb_const0 = vdupq_n_s16( - (short) ( 0.34414f*4096.0f+0.5f)); int16x8_t cb_const1 = vdupq_n_s16( (short) ( 1.77200f*4096.0f+0.5f)); for (; i+7 < count; i += 8) { // load uint8x8_t y_bytes = vld1_u8(y + i); uint8x8_t cr_bytes = vld1_u8(pcr + i); uint8x8_t cb_bytes = vld1_u8(pcb + i); int8x8_t cr_biased = vreinterpret_s8_u8(vsub_u8(cr_bytes, signflip)); int8x8_t cb_biased = vreinterpret_s8_u8(vsub_u8(cb_bytes, signflip)); // expand to s16 int16x8_t yws = vreinterpretq_s16_u16(vshll_n_u8(y_bytes, 4)); int16x8_t crw = vshll_n_s8(cr_biased, 7); int16x8_t cbw = vshll_n_s8(cb_biased, 7); // color transform int16x8_t cr0 = vqdmulhq_s16(crw, cr_const0); int16x8_t cb0 = vqdmulhq_s16(cbw, cb_const0); int16x8_t cr1 = vqdmulhq_s16(crw, cr_const1); int16x8_t cb1 = vqdmulhq_s16(cbw, cb_const1); int16x8_t rws = vaddq_s16(yws, cr0); int16x8_t gws = vaddq_s16(vaddq_s16(yws, cb0), cr1); int16x8_t bws = vaddq_s16(yws, cb1); // undo scaling, round, convert to byte uint8x8x4_t o; o.val[0] = vqrshrun_n_s16(rws, 4); o.val[1] = vqrshrun_n_s16(gws, 4); o.val[2] = vqrshrun_n_s16(bws, 4); o.val[3] = vdup_n_u8(255); // store, interleaving r/g/b/a vst4_u8(out, o); out += 8*4; } } #endif for (; i < count; ++i) { int y_fixed = (y[i] << 20) + (1<<19); // rounding int r,g,b; int cr = pcr[i] - 128; int cb = pcb[i] - 128; r = y_fixed + cr* stbi__float2fixed(1.40200f); g = y_fixed + cr*-stbi__float2fixed(0.71414f) + ((cb*-stbi__float2fixed(0.34414f)) & 0xffff0000); b = y_fixed + cb* stbi__float2fixed(1.77200f); r >>= 20; g >>= 20; b >>= 20; if ((unsigned) r > 255) { if (r < 0) r = 0; else r = 255; } if ((unsigned) g > 255) { if (g < 0) g = 0; else g = 255; } if ((unsigned) b > 255) { if (b < 0) b = 0; else b = 255; } out[0] = (stbi_uc)r; out[1] = (stbi_uc)g; out[2] = (stbi_uc)b; out[3] = 255; out += step; } } #endif // set up the kernels static void stbi__setup_jpeg(stbi__jpeg *j) { j->idct_block_kernel = stbi__idct_block; j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_row; j->resample_row_hv_2_kernel = stbi__resample_row_hv_2; #ifdef STBI_SSE2 if (stbi__sse2_available()) { j->idct_block_kernel = stbi__idct_simd; j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_simd; j->resample_row_hv_2_kernel = stbi__resample_row_hv_2_simd; } #endif #ifdef STBI_NEON j->idct_block_kernel = stbi__idct_simd; j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_simd; j->resample_row_hv_2_kernel = stbi__resample_row_hv_2_simd; #endif } // clean up the temporary component buffers static void stbi__cleanup_jpeg(stbi__jpeg *j) { stbi__free_jpeg_components(j, j->s->img_n, 0); } typedef struct { resample_row_func resample; stbi_uc *line0,*line1; int hs,vs; // expansion factor in each axis int w_lores; // horizontal pixels pre-expansion int ystep; // how far through vertical expansion we are int ypos; // which pre-expansion row we're on } stbi__resample; // fast 0..255 * 0..255 => 0..255 rounded multiplication static stbi_uc stbi__blinn_8x8(stbi_uc x, stbi_uc y) { unsigned int t = x*y + 128; return (stbi_uc) ((t + (t >>8)) >> 8); } static stbi_uc *load_jpeg_image(stbi__jpeg *z, int *out_x, int *out_y, int *comp, int req_comp) { int n, decode_n, is_rgb; z->s->img_n = 0; // make stbi__cleanup_jpeg safe // validate req_comp if (req_comp < 0 || req_comp > 4) return stbi__errpuc("bad req_comp", "Internal error"); // load a jpeg image from whichever source, but leave in YCbCr format if (!stbi__decode_jpeg_image(z)) { stbi__cleanup_jpeg(z); return NULL; } // determine actual number of components to generate n = req_comp ? req_comp : z->s->img_n >= 3 ? 3 : 1; is_rgb = z->s->img_n == 3 && (z->rgb == 3 || (z->app14_color_transform == 0 && !z->jfif)); if (z->s->img_n == 3 && n < 3 && !is_rgb) decode_n = 1; else decode_n = z->s->img_n; // nothing to do if no components requested; check this now to avoid // accessing uninitialized coutput[0] later if (decode_n <= 0) { stbi__cleanup_jpeg(z); return NULL; } // resample and color-convert { int k; unsigned int i,j; stbi_uc *output; stbi_uc *coutput[4] = { NULL, NULL, NULL, NULL }; stbi__resample res_comp[4]; for (k=0; k < decode_n; ++k) { stbi__resample *r = &res_comp[k]; // allocate line buffer big enough for upsampling off the edges // with upsample factor of 4 z->img_comp[k].linebuf = (stbi_uc *) stbi__malloc(z->s->img_x + 3); if (!z->img_comp[k].linebuf) { stbi__cleanup_jpeg(z); return stbi__errpuc("outofmem", "Out of memory"); } r->hs = z->img_h_max / z->img_comp[k].h; r->vs = z->img_v_max / z->img_comp[k].v; r->ystep = r->vs >> 1; r->w_lores = (z->s->img_x + r->hs-1) / r->hs; r->ypos = 0; r->line0 = r->line1 = z->img_comp[k].data; if (r->hs == 1 && r->vs == 1) r->resample = resample_row_1; else if (r->hs == 1 && r->vs == 2) r->resample = stbi__resample_row_v_2; else if (r->hs == 2 && r->vs == 1) r->resample = stbi__resample_row_h_2; else if (r->hs == 2 && r->vs == 2) r->resample = z->resample_row_hv_2_kernel; else r->resample = stbi__resample_row_generic; } // can't error after this so, this is safe output = (stbi_uc *) stbi__malloc_mad3(n, z->s->img_x, z->s->img_y, 1); if (!output) { stbi__cleanup_jpeg(z); return stbi__errpuc("outofmem", "Out of memory"); } // now go ahead and resample for (j=0; j < z->s->img_y; ++j) { stbi_uc *out = output + n * z->s->img_x * j; for (k=0; k < decode_n; ++k) { stbi__resample *r = &res_comp[k]; int y_bot = r->ystep >= (r->vs >> 1); coutput[k] = r->resample(z->img_comp[k].linebuf, y_bot ? r->line1 : r->line0, y_bot ? r->line0 : r->line1, r->w_lores, r->hs); if (++r->ystep >= r->vs) { r->ystep = 0; r->line0 = r->line1; if (++r->ypos < z->img_comp[k].y) r->line1 += z->img_comp[k].w2; } } if (n >= 3) { stbi_uc *y = coutput[0]; if (z->s->img_n == 3) { if (is_rgb) { for (i=0; i < z->s->img_x; ++i) { out[0] = y[i]; out[1] = coutput[1][i]; out[2] = coutput[2][i]; out[3] = 255; out += n; } } else { z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n); } } else if (z->s->img_n == 4) { if (z->app14_color_transform == 0) { // CMYK for (i=0; i < z->s->img_x; ++i) { stbi_uc m = coutput[3][i]; out[0] = stbi__blinn_8x8(coutput[0][i], m); out[1] = stbi__blinn_8x8(coutput[1][i], m); out[2] = stbi__blinn_8x8(coutput[2][i], m); out[3] = 255; out += n; } } else if (z->app14_color_transform == 2) { // YCCK z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n); for (i=0; i < z->s->img_x; ++i) { stbi_uc m = coutput[3][i]; out[0] = stbi__blinn_8x8(255 - out[0], m); out[1] = stbi__blinn_8x8(255 - out[1], m); out[2] = stbi__blinn_8x8(255 - out[2], m); out += n; } } else { // YCbCr + alpha? Ignore the fourth channel for now z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n); } } else for (i=0; i < z->s->img_x; ++i) { out[0] = out[1] = out[2] = y[i]; out[3] = 255; // not used if n==3 out += n; } } else { if (is_rgb) { if (n == 1) for (i=0; i < z->s->img_x; ++i) *out++ = stbi__compute_y(coutput[0][i], coutput[1][i], coutput[2][i]); else { for (i=0; i < z->s->img_x; ++i, out += 2) { out[0] = stbi__compute_y(coutput[0][i], coutput[1][i], coutput[2][i]); out[1] = 255; } } } else if (z->s->img_n == 4 && z->app14_color_transform == 0) { for (i=0; i < z->s->img_x; ++i) { stbi_uc m = coutput[3][i]; stbi_uc r = stbi__blinn_8x8(coutput[0][i], m); stbi_uc g = stbi__blinn_8x8(coutput[1][i], m); stbi_uc b = stbi__blinn_8x8(coutput[2][i], m); out[0] = stbi__compute_y(r, g, b); out[1] = 255; out += n; } } else if (z->s->img_n == 4 && z->app14_color_transform == 2) { for (i=0; i < z->s->img_x; ++i) { out[0] = stbi__blinn_8x8(255 - coutput[0][i], coutput[3][i]); out[1] = 255; out += n; } } else { stbi_uc *y = coutput[0]; if (n == 1) for (i=0; i < z->s->img_x; ++i) out[i] = y[i]; else for (i=0; i < z->s->img_x; ++i) { *out++ = y[i]; *out++ = 255; } } } } stbi__cleanup_jpeg(z); *out_x = z->s->img_x; *out_y = z->s->img_y; if (comp) *comp = z->s->img_n >= 3 ? 3 : 1; // report original components, not output return output; } } static void *stbi__jpeg_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) { unsigned char* result; stbi__jpeg* j = (stbi__jpeg*) stbi__malloc(sizeof(stbi__jpeg)); if (!j) return stbi__errpuc("outofmem", "Out of memory"); memset(j, 0, sizeof(stbi__jpeg)); STBI_NOTUSED(ri); j->s = s; stbi__setup_jpeg(j); result = load_jpeg_image(j, x,y,comp,req_comp); STBI_FREE(j); return result; } static int stbi__jpeg_test(stbi__context *s) { int r; stbi__jpeg* j = (stbi__jpeg*)stbi__malloc(sizeof(stbi__jpeg)); if (!j) return stbi__err("outofmem", "Out of memory"); memset(j, 0, sizeof(stbi__jpeg)); j->s = s; stbi__setup_jpeg(j); r = stbi__decode_jpeg_header(j, STBI__SCAN_type); stbi__rewind(s); STBI_FREE(j); return r; } static int stbi__jpeg_info_raw(stbi__jpeg *j, int *x, int *y, int *comp) { if (!stbi__decode_jpeg_header(j, STBI__SCAN_header)) { stbi__rewind( j->s ); return 0; } if (x) *x = j->s->img_x; if (y) *y = j->s->img_y; if (comp) *comp = j->s->img_n >= 3 ? 3 : 1; return 1; } static int stbi__jpeg_info(stbi__context *s, int *x, int *y, int *comp) { int result; stbi__jpeg* j = (stbi__jpeg*) (stbi__malloc(sizeof(stbi__jpeg))); if (!j) return stbi__err("outofmem", "Out of memory"); memset(j, 0, sizeof(stbi__jpeg)); j->s = s; result = stbi__jpeg_info_raw(j, x, y, comp); STBI_FREE(j); return result; } #endif // public domain zlib decode v0.2 Sean Barrett 2006-11-18 // simple implementation // - all input must be provided in an upfront buffer // - all output is written to a single output buffer (can malloc/realloc) // performance // - fast huffman #ifndef STBI_NO_ZLIB // fast-way is faster to check than jpeg huffman, but slow way is slower #define STBI__ZFAST_BITS 9 // accelerate all cases in default tables #define STBI__ZFAST_MASK ((1 << STBI__ZFAST_BITS) - 1) #define STBI__ZNSYMS 288 // number of symbols in literal/length alphabet // zlib-style huffman encoding // (jpegs packs from left, zlib from right, so can't share code) typedef struct { stbi__uint16 fast[1 << STBI__ZFAST_BITS]; stbi__uint16 firstcode[16]; int maxcode[17]; stbi__uint16 firstsymbol[16]; stbi_uc size[STBI__ZNSYMS]; stbi__uint16 value[STBI__ZNSYMS]; } stbi__zhuffman; stbi_inline static int stbi__bitreverse16(int n) { n = ((n & 0xAAAA) >> 1) | ((n & 0x5555) << 1); n = ((n & 0xCCCC) >> 2) | ((n & 0x3333) << 2); n = ((n & 0xF0F0) >> 4) | ((n & 0x0F0F) << 4); n = ((n & 0xFF00) >> 8) | ((n & 0x00FF) << 8); return n; } stbi_inline static int stbi__bit_reverse(int v, int bits) { STBI_ASSERT(bits <= 16); // to bit reverse n bits, reverse 16 and shift // e.g. 11 bits, bit reverse and shift away 5 return stbi__bitreverse16(v) >> (16-bits); } static int stbi__zbuild_huffman(stbi__zhuffman *z, const stbi_uc *sizelist, int num) { int i,k=0; int code, next_code[16], sizes[17]; // DEFLATE spec for generating codes memset(sizes, 0, sizeof(sizes)); memset(z->fast, 0, sizeof(z->fast)); for (i=0; i < num; ++i) ++sizes[sizelist[i]]; sizes[0] = 0; for (i=1; i < 16; ++i) if (sizes[i] > (1 << i)) return stbi__err("bad sizes", "Corrupt PNG"); code = 0; for (i=1; i < 16; ++i) { next_code[i] = code; z->firstcode[i] = (stbi__uint16) code; z->firstsymbol[i] = (stbi__uint16) k; code = (code + sizes[i]); if (sizes[i]) if (code-1 >= (1 << i)) return stbi__err("bad codelengths","Corrupt PNG"); z->maxcode[i] = code << (16-i); // preshift for inner loop code <<= 1; k += sizes[i]; } z->maxcode[16] = 0x10000; // sentinel for (i=0; i < num; ++i) { int s = sizelist[i]; if (s) { int c = next_code[s] - z->firstcode[s] + z->firstsymbol[s]; stbi__uint16 fastv = (stbi__uint16) ((s << 9) | i); z->size [c] = (stbi_uc ) s; z->value[c] = (stbi__uint16) i; if (s <= STBI__ZFAST_BITS) { int j = stbi__bit_reverse(next_code[s],s); while (j < (1 << STBI__ZFAST_BITS)) { z->fast[j] = fastv; j += (1 << s); } } ++next_code[s]; } } return 1; } // zlib-from-memory implementation for PNG reading // because PNG allows splitting the zlib stream arbitrarily, // and it's annoying structurally to have PNG call ZLIB call PNG, // we require PNG read all the IDATs and combine them into a single // memory buffer typedef struct { stbi_uc *zbuffer, *zbuffer_end; int num_bits; stbi__uint32 code_buffer; char *zout; char *zout_start; char *zout_end; int z_expandable; stbi__zhuffman z_length, z_distance; } stbi__zbuf; stbi_inline static int stbi__zeof(stbi__zbuf *z) { return (z->zbuffer >= z->zbuffer_end); } stbi_inline static stbi_uc stbi__zget8(stbi__zbuf *z) { return stbi__zeof(z) ? 0 : *z->zbuffer++; } static void stbi__fill_bits(stbi__zbuf *z) { do { if (z->code_buffer >= (1U << z->num_bits)) { z->zbuffer = z->zbuffer_end; /* treat this as EOF so we fail. */ return; } z->code_buffer |= (unsigned int) stbi__zget8(z) << z->num_bits; z->num_bits += 8; } while (z->num_bits <= 24); } stbi_inline static unsigned int stbi__zreceive(stbi__zbuf *z, int n) { unsigned int k; if (z->num_bits < n) stbi__fill_bits(z); k = z->code_buffer & ((1 << n) - 1); z->code_buffer >>= n; z->num_bits -= n; return k; } static int stbi__zhuffman_decode_slowpath(stbi__zbuf *a, stbi__zhuffman *z) { int b,s,k; // not resolved by fast table, so compute it the slow way // use jpeg approach, which requires MSbits at top k = stbi__bit_reverse(a->code_buffer, 16); for (s=STBI__ZFAST_BITS+1; ; ++s) if (k < z->maxcode[s]) break; if (s >= 16) return -1; // invalid code! // code size is s, so: b = (k >> (16-s)) - z->firstcode[s] + z->firstsymbol[s]; if (b >= STBI__ZNSYMS) return -1; // some data was corrupt somewhere! if (z->size[b] != s) return -1; // was originally an assert, but report failure instead. a->code_buffer >>= s; a->num_bits -= s; return z->value[b]; } stbi_inline static int stbi__zhuffman_decode(stbi__zbuf *a, stbi__zhuffman *z) { int b,s; if (a->num_bits < 16) { if (stbi__zeof(a)) { return -1; /* report error for unexpected end of data. */ } stbi__fill_bits(a); } b = z->fast[a->code_buffer & STBI__ZFAST_MASK]; if (b) { s = b >> 9; a->code_buffer >>= s; a->num_bits -= s; return b & 511; } return stbi__zhuffman_decode_slowpath(a, z); } static int stbi__zexpand(stbi__zbuf *z, char *zout, int n) // need to make room for n bytes { char *q; unsigned int cur, limit, old_limit; z->zout = zout; if (!z->z_expandable) return stbi__err("output buffer limit","Corrupt PNG"); cur = (unsigned int) (z->zout - z->zout_start); limit = old_limit = (unsigned) (z->zout_end - z->zout_start); if (UINT_MAX - cur < (unsigned) n) return stbi__err("outofmem", "Out of memory"); while (cur + n > limit) { if(limit > UINT_MAX / 2) return stbi__err("outofmem", "Out of memory"); limit *= 2; } q = (char *) STBI_REALLOC_SIZED(z->zout_start, old_limit, limit); STBI_NOTUSED(old_limit); if (q == NULL) return stbi__err("outofmem", "Out of memory"); z->zout_start = q; z->zout = q + cur; z->zout_end = q + limit; return 1; } static const int stbi__zlength_base[31] = { 3,4,5,6,7,8,9,10,11,13, 15,17,19,23,27,31,35,43,51,59, 67,83,99,115,131,163,195,227,258,0,0 }; static const int stbi__zlength_extra[31]= { 0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0 }; static const int stbi__zdist_base[32] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193, 257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0}; static const int stbi__zdist_extra[32] = { 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13}; static int stbi__parse_huffman_block(stbi__zbuf *a) { char *zout = a->zout; for(;;) { int z = stbi__zhuffman_decode(a, &a->z_length); if (z < 256) { if (z < 0) return stbi__err("bad huffman code","Corrupt PNG"); // error in huffman codes if (zout >= a->zout_end) { if (!stbi__zexpand(a, zout, 1)) return 0; zout = a->zout; } *zout++ = (char) z; } else { stbi_uc *p; int len,dist; if (z == 256) { a->zout = zout; return 1; } if (z >= 286) return stbi__err("bad huffman code","Corrupt PNG"); // per DEFLATE, length codes 286 and 287 must not appear in compressed data z -= 257; len = stbi__zlength_base[z]; if (stbi__zlength_extra[z]) len += stbi__zreceive(a, stbi__zlength_extra[z]); z = stbi__zhuffman_decode(a, &a->z_distance); if (z < 0 || z >= 30) return stbi__err("bad huffman code","Corrupt PNG"); // per DEFLATE, distance codes 30 and 31 must not appear in compressed data dist = stbi__zdist_base[z]; if (stbi__zdist_extra[z]) dist += stbi__zreceive(a, stbi__zdist_extra[z]); if (zout - a->zout_start < dist) return stbi__err("bad dist","Corrupt PNG"); if (zout + len > a->zout_end) { if (!stbi__zexpand(a, zout, len)) return 0; zout = a->zout; } p = (stbi_uc *) (zout - dist); if (dist == 1) { // run of one byte; common in images. stbi_uc v = *p; if (len) { do *zout++ = v; while (--len); } } else { if (len) { do *zout++ = *p++; while (--len); } } } } } static int stbi__compute_huffman_codes(stbi__zbuf *a) { static const stbi_uc length_dezigzag[19] = { 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15 }; stbi__zhuffman z_codelength; stbi_uc lencodes[286+32+137];//padding for maximum single op stbi_uc codelength_sizes[19]; int i,n; int hlit = stbi__zreceive(a,5) + 257; int hdist = stbi__zreceive(a,5) + 1; int hclen = stbi__zreceive(a,4) + 4; int ntot = hlit + hdist; memset(codelength_sizes, 0, sizeof(codelength_sizes)); for (i=0; i < hclen; ++i) { int s = stbi__zreceive(a,3); codelength_sizes[length_dezigzag[i]] = (stbi_uc) s; } if (!stbi__zbuild_huffman(&z_codelength, codelength_sizes, 19)) return 0; n = 0; while (n < ntot) { int c = stbi__zhuffman_decode(a, &z_codelength); if (c < 0 || c >= 19) return stbi__err("bad codelengths", "Corrupt PNG"); if (c < 16) lencodes[n++] = (stbi_uc) c; else { stbi_uc fill = 0; if (c == 16) { c = stbi__zreceive(a,2)+3; if (n == 0) return stbi__err("bad codelengths", "Corrupt PNG"); fill = lencodes[n-1]; } else if (c == 17) { c = stbi__zreceive(a,3)+3; } else if (c == 18) { c = stbi__zreceive(a,7)+11; } else { return stbi__err("bad codelengths", "Corrupt PNG"); } if (ntot - n < c) return stbi__err("bad codelengths", "Corrupt PNG"); memset(lencodes+n, fill, c); n += c; } } if (n != ntot) return stbi__err("bad codelengths","Corrupt PNG"); if (!stbi__zbuild_huffman(&a->z_length, lencodes, hlit)) return 0; if (!stbi__zbuild_huffman(&a->z_distance, lencodes+hlit, hdist)) return 0; return 1; } static int stbi__parse_uncompressed_block(stbi__zbuf *a) { stbi_uc header[4]; int len,nlen,k; if (a->num_bits & 7) stbi__zreceive(a, a->num_bits & 7); // discard // drain the bit-packed data into header k = 0; while (a->num_bits > 0) { header[k++] = (stbi_uc) (a->code_buffer & 255); // suppress MSVC run-time check a->code_buffer >>= 8; a->num_bits -= 8; } if (a->num_bits < 0) return stbi__err("zlib corrupt","Corrupt PNG"); // now fill header the normal way while (k < 4) header[k++] = stbi__zget8(a); len = header[1] * 256 + header[0]; nlen = header[3] * 256 + header[2]; if (nlen != (len ^ 0xffff)) return stbi__err("zlib corrupt","Corrupt PNG"); if (a->zbuffer + len > a->zbuffer_end) return stbi__err("read past buffer","Corrupt PNG"); if (a->zout + len > a->zout_end) if (!stbi__zexpand(a, a->zout, len)) return 0; memcpy(a->zout, a->zbuffer, len); a->zbuffer += len; a->zout += len; return 1; } static int stbi__parse_zlib_header(stbi__zbuf *a) { int cmf = stbi__zget8(a); int cm = cmf & 15; /* int cinfo = cmf >> 4; */ int flg = stbi__zget8(a); if (stbi__zeof(a)) return stbi__err("bad zlib header","Corrupt PNG"); // zlib spec if ((cmf*256+flg) % 31 != 0) return stbi__err("bad zlib header","Corrupt PNG"); // zlib spec if (flg & 32) return stbi__err("no preset dict","Corrupt PNG"); // preset dictionary not allowed in png if (cm != 8) return stbi__err("bad compression","Corrupt PNG"); // DEFLATE required for png // window = 1 << (8 + cinfo)... but who cares, we fully buffer output return 1; } static const stbi_uc stbi__zdefault_length[STBI__ZNSYMS] = { 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8 }; static const stbi_uc stbi__zdefault_distance[32] = { 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5 }; /* Init algorithm: { int i; // use <= to match clearly with spec for (i=0; i <= 143; ++i) stbi__zdefault_length[i] = 8; for ( ; i <= 255; ++i) stbi__zdefault_length[i] = 9; for ( ; i <= 279; ++i) stbi__zdefault_length[i] = 7; for ( ; i <= 287; ++i) stbi__zdefault_length[i] = 8; for (i=0; i <= 31; ++i) stbi__zdefault_distance[i] = 5; } */ static int stbi__parse_zlib(stbi__zbuf *a, int parse_header) { int final, type; if (parse_header) if (!stbi__parse_zlib_header(a)) return 0; a->num_bits = 0; a->code_buffer = 0; do { final = stbi__zreceive(a,1); type = stbi__zreceive(a,2); if (type == 0) { if (!stbi__parse_uncompressed_block(a)) return 0; } else if (type == 3) { return 0; } else { if (type == 1) { // use fixed code lengths if (!stbi__zbuild_huffman(&a->z_length , stbi__zdefault_length , STBI__ZNSYMS)) return 0; if (!stbi__zbuild_huffman(&a->z_distance, stbi__zdefault_distance, 32)) return 0; } else { if (!stbi__compute_huffman_codes(a)) return 0; } if (!stbi__parse_huffman_block(a)) return 0; } } while (!final); return 1; } static int stbi__do_zlib(stbi__zbuf *a, char *obuf, int olen, int exp, int parse_header) { a->zout_start = obuf; a->zout = obuf; a->zout_end = obuf + olen; a->z_expandable = exp; return stbi__parse_zlib(a, parse_header); } STBIDEF char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen) { stbi__zbuf a; char *p = (char *) stbi__malloc(initial_size); if (p == NULL) return NULL; a.zbuffer = (stbi_uc *) buffer; a.zbuffer_end = (stbi_uc *) buffer + len; if (stbi__do_zlib(&a, p, initial_size, 1, 1)) { if (outlen) *outlen = (int) (a.zout - a.zout_start); return a.zout_start; } else { STBI_FREE(a.zout_start); return NULL; } } STBIDEF char *stbi_zlib_decode_malloc(char const *buffer, int len, int *outlen) { return stbi_zlib_decode_malloc_guesssize(buffer, len, 16384, outlen); } STBIDEF char *stbi_zlib_decode_malloc_guesssize_headerflag(const char *buffer, int len, int initial_size, int *outlen, int parse_header) { stbi__zbuf a; char *p = (char *) stbi__malloc(initial_size); if (p == NULL) return NULL; a.zbuffer = (stbi_uc *) buffer; a.zbuffer_end = (stbi_uc *) buffer + len; if (stbi__do_zlib(&a, p, initial_size, 1, parse_header)) { if (outlen) *outlen = (int) (a.zout - a.zout_start); return a.zout_start; } else { STBI_FREE(a.zout_start); return NULL; } } STBIDEF int stbi_zlib_decode_buffer(char *obuffer, int olen, char const *ibuffer, int ilen) { stbi__zbuf a; a.zbuffer = (stbi_uc *) ibuffer; a.zbuffer_end = (stbi_uc *) ibuffer + ilen; if (stbi__do_zlib(&a, obuffer, olen, 0, 1)) return (int) (a.zout - a.zout_start); else return -1; } STBIDEF char *stbi_zlib_decode_noheader_malloc(char const *buffer, int len, int *outlen) { stbi__zbuf a; char *p = (char *) stbi__malloc(16384); if (p == NULL) return NULL; a.zbuffer = (stbi_uc *) buffer; a.zbuffer_end = (stbi_uc *) buffer+len; if (stbi__do_zlib(&a, p, 16384, 1, 0)) { if (outlen) *outlen = (int) (a.zout - a.zout_start); return a.zout_start; } else { STBI_FREE(a.zout_start); return NULL; } } STBIDEF int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen) { stbi__zbuf a; a.zbuffer = (stbi_uc *) ibuffer; a.zbuffer_end = (stbi_uc *) ibuffer + ilen; if (stbi__do_zlib(&a, obuffer, olen, 0, 0)) return (int) (a.zout - a.zout_start); else return -1; } #endif // public domain "baseline" PNG decoder v0.10 Sean Barrett 2006-11-18 // simple implementation // - only 8-bit samples // - no CRC checking // - allocates lots of intermediate memory // - avoids problem of streaming data between subsystems // - avoids explicit window management // performance // - uses stb_zlib, a PD zlib implementation with fast huffman decoding #ifndef STBI_NO_PNG typedef struct { stbi__uint32 length; stbi__uint32 type; } stbi__pngchunk; static stbi__pngchunk stbi__get_chunk_header(stbi__context *s) { stbi__pngchunk c; c.length = stbi__get32be(s); c.type = stbi__get32be(s); return c; } static int stbi__check_png_header(stbi__context *s) { static const stbi_uc png_sig[8] = { 137,80,78,71,13,10,26,10 }; int i; for (i=0; i < 8; ++i) if (stbi__get8(s) != png_sig[i]) return stbi__err("bad png sig","Not a PNG"); return 1; } typedef struct { stbi__context *s; stbi_uc *idata, *expanded, *out; int depth; } stbi__png; enum { STBI__F_none=0, STBI__F_sub=1, STBI__F_up=2, STBI__F_avg=3, STBI__F_paeth=4, // synthetic filters used for first scanline to avoid needing a dummy row of 0s STBI__F_avg_first, STBI__F_paeth_first }; static stbi_uc first_row_filter[5] = { STBI__F_none, STBI__F_sub, STBI__F_none, STBI__F_avg_first, STBI__F_paeth_first }; static int stbi__paeth(int a, int b, int c) { int p = a + b - c; int pa = abs(p-a); int pb = abs(p-b); int pc = abs(p-c); if (pa <= pb && pa <= pc) return a; if (pb <= pc) return b; return c; } static const stbi_uc stbi__depth_scale_table[9] = { 0, 0xff, 0x55, 0, 0x11, 0,0,0, 0x01 }; // create the png data from post-deflated data static int stbi__create_png_image_raw(stbi__png *a, stbi_uc *raw, stbi__uint32 raw_len, int out_n, stbi__uint32 x, stbi__uint32 y, int depth, int color) { int bytes = (depth == 16? 2 : 1); stbi__context *s = a->s; stbi__uint32 i,j,stride = x*out_n*bytes; stbi__uint32 img_len, img_width_bytes; int k; int img_n = s->img_n; // copy it into a local for later int output_bytes = out_n*bytes; int filter_bytes = img_n*bytes; int width = x; STBI_ASSERT(out_n == s->img_n || out_n == s->img_n+1); a->out = (stbi_uc *) stbi__malloc_mad3(x, y, output_bytes, 0); // extra bytes to write off the end into if (!a->out) return stbi__err("outofmem", "Out of memory"); if (!stbi__mad3sizes_valid(img_n, x, depth, 7)) return stbi__err("too large", "Corrupt PNG"); img_width_bytes = (((img_n * x * depth) + 7) >> 3); img_len = (img_width_bytes + 1) * y; // we used to check for exact match between raw_len and img_len on non-interlaced PNGs, // but issue #276 reported a PNG in the wild that had extra data at the end (all zeros), // so just check for raw_len < img_len always. if (raw_len < img_len) return stbi__err("not enough pixels","Corrupt PNG"); for (j=0; j < y; ++j) { stbi_uc *cur = a->out + stride*j; stbi_uc *prior; int filter = *raw++; if (filter > 4) return stbi__err("invalid filter","Corrupt PNG"); if (depth < 8) { if (img_width_bytes > x) return stbi__err("invalid width","Corrupt PNG"); cur += x*out_n - img_width_bytes; // store output to the rightmost img_len bytes, so we can decode in place filter_bytes = 1; width = img_width_bytes; } prior = cur - stride; // bugfix: need to compute this after 'cur +=' computation above // if first row, use special filter that doesn't sample previous row if (j == 0) filter = first_row_filter[filter]; // handle first byte explicitly for (k=0; k < filter_bytes; ++k) { switch (filter) { case STBI__F_none : cur[k] = raw[k]; break; case STBI__F_sub : cur[k] = raw[k]; break; case STBI__F_up : cur[k] = STBI__BYTECAST(raw[k] + prior[k]); break; case STBI__F_avg : cur[k] = STBI__BYTECAST(raw[k] + (prior[k]>>1)); break; case STBI__F_paeth : cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(0,prior[k],0)); break; case STBI__F_avg_first : cur[k] = raw[k]; break; case STBI__F_paeth_first: cur[k] = raw[k]; break; } } if (depth == 8) { if (img_n != out_n) cur[img_n] = 255; // first pixel raw += img_n; cur += out_n; prior += out_n; } else if (depth == 16) { if (img_n != out_n) { cur[filter_bytes] = 255; // first pixel top byte cur[filter_bytes+1] = 255; // first pixel bottom byte } raw += filter_bytes; cur += output_bytes; prior += output_bytes; } else { raw += 1; cur += 1; prior += 1; } // this is a little gross, so that we don't switch per-pixel or per-component if (depth < 8 || img_n == out_n) { int nk = (width - 1)*filter_bytes; #define STBI__CASE(f) \ case f: \ for (k=0; k < nk; ++k) switch (filter) { // "none" filter turns into a memcpy here; make that explicit. case STBI__F_none: memcpy(cur, raw, nk); break; STBI__CASE(STBI__F_sub) { cur[k] = STBI__BYTECAST(raw[k] + cur[k-filter_bytes]); } break; STBI__CASE(STBI__F_up) { cur[k] = STBI__BYTECAST(raw[k] + prior[k]); } break; STBI__CASE(STBI__F_avg) { cur[k] = STBI__BYTECAST(raw[k] + ((prior[k] + cur[k-filter_bytes])>>1)); } break; STBI__CASE(STBI__F_paeth) { cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k-filter_bytes],prior[k],prior[k-filter_bytes])); } break; STBI__CASE(STBI__F_avg_first) { cur[k] = STBI__BYTECAST(raw[k] + (cur[k-filter_bytes] >> 1)); } break; STBI__CASE(STBI__F_paeth_first) { cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k-filter_bytes],0,0)); } break; } #undef STBI__CASE raw += nk; } else { STBI_ASSERT(img_n+1 == out_n); #define STBI__CASE(f) \ case f: \ for (i=x-1; i >= 1; --i, cur[filter_bytes]=255,raw+=filter_bytes,cur+=output_bytes,prior+=output_bytes) \ for (k=0; k < filter_bytes; ++k) switch (filter) { STBI__CASE(STBI__F_none) { cur[k] = raw[k]; } break; STBI__CASE(STBI__F_sub) { cur[k] = STBI__BYTECAST(raw[k] + cur[k- output_bytes]); } break; STBI__CASE(STBI__F_up) { cur[k] = STBI__BYTECAST(raw[k] + prior[k]); } break; STBI__CASE(STBI__F_avg) { cur[k] = STBI__BYTECAST(raw[k] + ((prior[k] + cur[k- output_bytes])>>1)); } break; STBI__CASE(STBI__F_paeth) { cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k- output_bytes],prior[k],prior[k- output_bytes])); } break; STBI__CASE(STBI__F_avg_first) { cur[k] = STBI__BYTECAST(raw[k] + (cur[k- output_bytes] >> 1)); } break; STBI__CASE(STBI__F_paeth_first) { cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k- output_bytes],0,0)); } break; } #undef STBI__CASE // the loop above sets the high byte of the pixels' alpha, but for // 16 bit png files we also need the low byte set. we'll do that here. if (depth == 16) { cur = a->out + stride*j; // start at the beginning of the row again for (i=0; i < x; ++i,cur+=output_bytes) { cur[filter_bytes+1] = 255; } } } } // we make a separate pass to expand bits to pixels; for performance, // this could run two scanlines behind the above code, so it won't // intefere with filtering but will still be in the cache. if (depth < 8) { for (j=0; j < y; ++j) { stbi_uc *cur = a->out + stride*j; stbi_uc *in = a->out + stride*j + x*out_n - img_width_bytes; // unpack 1/2/4-bit into a 8-bit buffer. allows us to keep the common 8-bit path optimal at minimal cost for 1/2/4-bit // png guarante byte alignment, if width is not multiple of 8/4/2 we'll decode dummy trailing data that will be skipped in the later loop stbi_uc scale = (color == 0) ? stbi__depth_scale_table[depth] : 1; // scale grayscale values to 0..255 range // note that the final byte might overshoot and write more data than desired. // we can allocate enough data that this never writes out of memory, but it // could also overwrite the next scanline. can it overwrite non-empty data // on the next scanline? yes, consider 1-pixel-wide scanlines with 1-bit-per-pixel. // so we need to explicitly clamp the final ones if (depth == 4) { for (k=x*img_n; k >= 2; k-=2, ++in) { *cur++ = scale * ((*in >> 4) ); *cur++ = scale * ((*in ) & 0x0f); } if (k > 0) *cur++ = scale * ((*in >> 4) ); } else if (depth == 2) { for (k=x*img_n; k >= 4; k-=4, ++in) { *cur++ = scale * ((*in >> 6) ); *cur++ = scale * ((*in >> 4) & 0x03); *cur++ = scale * ((*in >> 2) & 0x03); *cur++ = scale * ((*in ) & 0x03); } if (k > 0) *cur++ = scale * ((*in >> 6) ); if (k > 1) *cur++ = scale * ((*in >> 4) & 0x03); if (k > 2) *cur++ = scale * ((*in >> 2) & 0x03); } else if (depth == 1) { for (k=x*img_n; k >= 8; k-=8, ++in) { *cur++ = scale * ((*in >> 7) ); *cur++ = scale * ((*in >> 6) & 0x01); *cur++ = scale * ((*in >> 5) & 0x01); *cur++ = scale * ((*in >> 4) & 0x01); *cur++ = scale * ((*in >> 3) & 0x01); *cur++ = scale * ((*in >> 2) & 0x01); *cur++ = scale * ((*in >> 1) & 0x01); *cur++ = scale * ((*in ) & 0x01); } if (k > 0) *cur++ = scale * ((*in >> 7) ); if (k > 1) *cur++ = scale * ((*in >> 6) & 0x01); if (k > 2) *cur++ = scale * ((*in >> 5) & 0x01); if (k > 3) *cur++ = scale * ((*in >> 4) & 0x01); if (k > 4) *cur++ = scale * ((*in >> 3) & 0x01); if (k > 5) *cur++ = scale * ((*in >> 2) & 0x01); if (k > 6) *cur++ = scale * ((*in >> 1) & 0x01); } if (img_n != out_n) { int q; // insert alpha = 255 cur = a->out + stride*j; if (img_n == 1) { for (q=x-1; q >= 0; --q) { cur[q*2+1] = 255; cur[q*2+0] = cur[q]; } } else { STBI_ASSERT(img_n == 3); for (q=x-1; q >= 0; --q) { cur[q*4+3] = 255; cur[q*4+2] = cur[q*3+2]; cur[q*4+1] = cur[q*3+1]; cur[q*4+0] = cur[q*3+0]; } } } } } else if (depth == 16) { // force the image data from big-endian to platform-native. // this is done in a separate pass due to the decoding relying // on the data being untouched, but could probably be done // per-line during decode if care is taken. stbi_uc *cur = a->out; stbi__uint16 *cur16 = (stbi__uint16*)cur; for(i=0; i < x*y*out_n; ++i,cur16++,cur+=2) { *cur16 = (cur[0] << 8) | cur[1]; } } return 1; } static int stbi__create_png_image(stbi__png *a, stbi_uc *image_data, stbi__uint32 image_data_len, int out_n, int depth, int color, int interlaced) { int bytes = (depth == 16 ? 2 : 1); int out_bytes = out_n * bytes; stbi_uc *final; int p; if (!interlaced) return stbi__create_png_image_raw(a, image_data, image_data_len, out_n, a->s->img_x, a->s->img_y, depth, color); // de-interlacing final = (stbi_uc *) stbi__malloc_mad3(a->s->img_x, a->s->img_y, out_bytes, 0); if (!final) return stbi__err("outofmem", "Out of memory"); for (p=0; p < 7; ++p) { int xorig[] = { 0,4,0,2,0,1,0 }; int yorig[] = { 0,0,4,0,2,0,1 }; int xspc[] = { 8,8,4,4,2,2,1 }; int yspc[] = { 8,8,8,4,4,2,2 }; int i,j,x,y; // pass1_x[4] = 0, pass1_x[5] = 1, pass1_x[12] = 1 x = (a->s->img_x - xorig[p] + xspc[p]-1) / xspc[p]; y = (a->s->img_y - yorig[p] + yspc[p]-1) / yspc[p]; if (x && y) { stbi__uint32 img_len = ((((a->s->img_n * x * depth) + 7) >> 3) + 1) * y; if (!stbi__create_png_image_raw(a, image_data, image_data_len, out_n, x, y, depth, color)) { STBI_FREE(final); return 0; } for (j=0; j < y; ++j) { for (i=0; i < x; ++i) { int out_y = j*yspc[p]+yorig[p]; int out_x = i*xspc[p]+xorig[p]; memcpy(final + out_y*a->s->img_x*out_bytes + out_x*out_bytes, a->out + (j*x+i)*out_bytes, out_bytes); } } STBI_FREE(a->out); image_data += img_len; image_data_len -= img_len; } } a->out = final; return 1; } static int stbi__compute_transparency(stbi__png *z, stbi_uc tc[3], int out_n) { stbi__context *s = z->s; stbi__uint32 i, pixel_count = s->img_x * s->img_y; stbi_uc *p = z->out; // compute color-based transparency, assuming we've // already got 255 as the alpha value in the output STBI_ASSERT(out_n == 2 || out_n == 4); if (out_n == 2) { for (i=0; i < pixel_count; ++i) { p[1] = (p[0] == tc[0] ? 0 : 255); p += 2; } } else { for (i=0; i < pixel_count; ++i) { if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2]) p[3] = 0; p += 4; } } return 1; } static int stbi__compute_transparency16(stbi__png *z, stbi__uint16 tc[3], int out_n) { stbi__context *s = z->s; stbi__uint32 i, pixel_count = s->img_x * s->img_y; stbi__uint16 *p = (stbi__uint16*) z->out; // compute color-based transparency, assuming we've // already got 65535 as the alpha value in the output STBI_ASSERT(out_n == 2 || out_n == 4); if (out_n == 2) { for (i = 0; i < pixel_count; ++i) { p[1] = (p[0] == tc[0] ? 0 : 65535); p += 2; } } else { for (i = 0; i < pixel_count; ++i) { if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2]) p[3] = 0; p += 4; } } return 1; } static int stbi__expand_png_palette(stbi__png *a, stbi_uc *palette, int len, int pal_img_n) { stbi__uint32 i, pixel_count = a->s->img_x * a->s->img_y; stbi_uc *p, *temp_out, *orig = a->out; p = (stbi_uc *) stbi__malloc_mad2(pixel_count, pal_img_n, 0); if (p == NULL) return stbi__err("outofmem", "Out of memory"); // between here and free(out) below, exitting would leak temp_out = p; if (pal_img_n == 3) { for (i=0; i < pixel_count; ++i) { int n = orig[i]*4; p[0] = palette[n ]; p[1] = palette[n+1]; p[2] = palette[n+2]; p += 3; } } else { for (i=0; i < pixel_count; ++i) { int n = orig[i]*4; p[0] = palette[n ]; p[1] = palette[n+1]; p[2] = palette[n+2]; p[3] = palette[n+3]; p += 4; } } STBI_FREE(a->out); a->out = temp_out; STBI_NOTUSED(len); return 1; } static int stbi__unpremultiply_on_load_global = 0; static int stbi__de_iphone_flag_global = 0; STBIDEF void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply) { stbi__unpremultiply_on_load_global = flag_true_if_should_unpremultiply; } STBIDEF void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert) { stbi__de_iphone_flag_global = flag_true_if_should_convert; } #ifndef STBI_THREAD_LOCAL #define stbi__unpremultiply_on_load stbi__unpremultiply_on_load_global #define stbi__de_iphone_flag stbi__de_iphone_flag_global #else static STBI_THREAD_LOCAL int stbi__unpremultiply_on_load_local, stbi__unpremultiply_on_load_set; static STBI_THREAD_LOCAL int stbi__de_iphone_flag_local, stbi__de_iphone_flag_set; STBIDEF void stbi_set_unpremultiply_on_load_thread(int flag_true_if_should_unpremultiply) { stbi__unpremultiply_on_load_local = flag_true_if_should_unpremultiply; stbi__unpremultiply_on_load_set = 1; } STBIDEF void stbi_convert_iphone_png_to_rgb_thread(int flag_true_if_should_convert) { stbi__de_iphone_flag_local = flag_true_if_should_convert; stbi__de_iphone_flag_set = 1; } #define stbi__unpremultiply_on_load (stbi__unpremultiply_on_load_set \ ? stbi__unpremultiply_on_load_local \ : stbi__unpremultiply_on_load_global) #define stbi__de_iphone_flag (stbi__de_iphone_flag_set \ ? stbi__de_iphone_flag_local \ : stbi__de_iphone_flag_global) #endif // STBI_THREAD_LOCAL static void stbi__de_iphone(stbi__png *z) { stbi__context *s = z->s; stbi__uint32 i, pixel_count = s->img_x * s->img_y; stbi_uc *p = z->out; if (s->img_out_n == 3) { // convert bgr to rgb for (i=0; i < pixel_count; ++i) { stbi_uc t = p[0]; p[0] = p[2]; p[2] = t; p += 3; } } else { STBI_ASSERT(s->img_out_n == 4); if (stbi__unpremultiply_on_load) { // convert bgr to rgb and unpremultiply for (i=0; i < pixel_count; ++i) { stbi_uc a = p[3]; stbi_uc t = p[0]; if (a) { stbi_uc half = a / 2; p[0] = (p[2] * 255 + half) / a; p[1] = (p[1] * 255 + half) / a; p[2] = ( t * 255 + half) / a; } else { p[0] = p[2]; p[2] = t; } p += 4; } } else { // convert bgr to rgb for (i=0; i < pixel_count; ++i) { stbi_uc t = p[0]; p[0] = p[2]; p[2] = t; p += 4; } } } } #define STBI__PNG_TYPE(a,b,c,d) (((unsigned) (a) << 24) + ((unsigned) (b) << 16) + ((unsigned) (c) << 8) + (unsigned) (d)) static int stbi__parse_png_file(stbi__png *z, int scan, int req_comp) { stbi_uc palette[1024], pal_img_n=0; stbi_uc has_trans=0, tc[3]={0}; stbi__uint16 tc16[3]; stbi__uint32 ioff=0, idata_limit=0, i, pal_len=0; int first=1,k,interlace=0, color=0, is_iphone=0; stbi__context *s = z->s; z->expanded = NULL; z->idata = NULL; z->out = NULL; if (!stbi__check_png_header(s)) return 0; if (scan == STBI__SCAN_type) return 1; for (;;) { stbi__pngchunk c = stbi__get_chunk_header(s); switch (c.type) { case STBI__PNG_TYPE('C','g','B','I'): is_iphone = 1; stbi__skip(s, c.length); break; case STBI__PNG_TYPE('I','H','D','R'): { int comp,filter; if (!first) return stbi__err("multiple IHDR","Corrupt PNG"); first = 0; if (c.length != 13) return stbi__err("bad IHDR len","Corrupt PNG"); s->img_x = stbi__get32be(s); s->img_y = stbi__get32be(s); if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); z->depth = stbi__get8(s); if (z->depth != 1 && z->depth != 2 && z->depth != 4 && z->depth != 8 && z->depth != 16) return stbi__err("1/2/4/8/16-bit only","PNG not supported: 1/2/4/8/16-bit only"); color = stbi__get8(s); if (color > 6) return stbi__err("bad ctype","Corrupt PNG"); if (color == 3 && z->depth == 16) return stbi__err("bad ctype","Corrupt PNG"); if (color == 3) pal_img_n = 3; else if (color & 1) return stbi__err("bad ctype","Corrupt PNG"); comp = stbi__get8(s); if (comp) return stbi__err("bad comp method","Corrupt PNG"); filter= stbi__get8(s); if (filter) return stbi__err("bad filter method","Corrupt PNG"); interlace = stbi__get8(s); if (interlace>1) return stbi__err("bad interlace method","Corrupt PNG"); if (!s->img_x || !s->img_y) return stbi__err("0-pixel image","Corrupt PNG"); if (!pal_img_n) { s->img_n = (color & 2 ? 3 : 1) + (color & 4 ? 1 : 0); if ((1 << 30) / s->img_x / s->img_n < s->img_y) return stbi__err("too large", "Image too large to decode"); } else { // if paletted, then pal_n is our final components, and // img_n is # components to decompress/filter. s->img_n = 1; if ((1 << 30) / s->img_x / 4 < s->img_y) return stbi__err("too large","Corrupt PNG"); } // even with SCAN_header, have to scan to see if we have a tRNS break; } case STBI__PNG_TYPE('P','L','T','E'): { if (first) return stbi__err("first not IHDR", "Corrupt PNG"); if (c.length > 256*3) return stbi__err("invalid PLTE","Corrupt PNG"); pal_len = c.length / 3; if (pal_len * 3 != c.length) return stbi__err("invalid PLTE","Corrupt PNG"); for (i=0; i < pal_len; ++i) { palette[i*4+0] = stbi__get8(s); palette[i*4+1] = stbi__get8(s); palette[i*4+2] = stbi__get8(s); palette[i*4+3] = 255; } break; } case STBI__PNG_TYPE('t','R','N','S'): { if (first) return stbi__err("first not IHDR", "Corrupt PNG"); if (z->idata) return stbi__err("tRNS after IDAT","Corrupt PNG"); if (pal_img_n) { if (scan == STBI__SCAN_header) { s->img_n = 4; return 1; } if (pal_len == 0) return stbi__err("tRNS before PLTE","Corrupt PNG"); if (c.length > pal_len) return stbi__err("bad tRNS len","Corrupt PNG"); pal_img_n = 4; for (i=0; i < c.length; ++i) palette[i*4+3] = stbi__get8(s); } else { if (!(s->img_n & 1)) return stbi__err("tRNS with alpha","Corrupt PNG"); if (c.length != (stbi__uint32) s->img_n*2) return stbi__err("bad tRNS len","Corrupt PNG"); has_trans = 1; // non-paletted with tRNS = constant alpha. if header-scanning, we can stop now. if (scan == STBI__SCAN_header) { ++s->img_n; return 1; } if (z->depth == 16) { for (k = 0; k < s->img_n; ++k) tc16[k] = (stbi__uint16)stbi__get16be(s); // copy the values as-is } else { for (k = 0; k < s->img_n; ++k) tc[k] = (stbi_uc)(stbi__get16be(s) & 255) * stbi__depth_scale_table[z->depth]; // non 8-bit images will be larger } } break; } case STBI__PNG_TYPE('I','D','A','T'): { if (first) return stbi__err("first not IHDR", "Corrupt PNG"); if (pal_img_n && !pal_len) return stbi__err("no PLTE","Corrupt PNG"); if (scan == STBI__SCAN_header) { // header scan definitely stops at first IDAT if (pal_img_n) s->img_n = pal_img_n; return 1; } if (c.length > (1u << 30)) return stbi__err("IDAT size limit", "IDAT section larger than 2^30 bytes"); if ((int)(ioff + c.length) < (int)ioff) return 0; if (ioff + c.length > idata_limit) { stbi__uint32 idata_limit_old = idata_limit; stbi_uc *p; if (idata_limit == 0) idata_limit = c.length > 4096 ? c.length : 4096; while (ioff + c.length > idata_limit) idata_limit *= 2; STBI_NOTUSED(idata_limit_old); p = (stbi_uc *) STBI_REALLOC_SIZED(z->idata, idata_limit_old, idata_limit); if (p == NULL) return stbi__err("outofmem", "Out of memory"); z->idata = p; } if (!stbi__getn(s, z->idata+ioff,c.length)) return stbi__err("outofdata","Corrupt PNG"); ioff += c.length; break; } case STBI__PNG_TYPE('I','E','N','D'): { stbi__uint32 raw_len, bpl; if (first) return stbi__err("first not IHDR", "Corrupt PNG"); if (scan != STBI__SCAN_load) return 1; if (z->idata == NULL) return stbi__err("no IDAT","Corrupt PNG"); // initial guess for decoded data size to avoid unnecessary reallocs bpl = (s->img_x * z->depth + 7) / 8; // bytes per line, per component raw_len = bpl * s->img_y * s->img_n /* pixels */ + s->img_y /* filter mode per row */; z->expanded = (stbi_uc *) stbi_zlib_decode_malloc_guesssize_headerflag((char *) z->idata, ioff, raw_len, (int *) &raw_len, !is_iphone); if (z->expanded == NULL) return 0; // zlib should set error STBI_FREE(z->idata); z->idata = NULL; if ((req_comp == s->img_n+1 && req_comp != 3 && !pal_img_n) || has_trans) s->img_out_n = s->img_n+1; else s->img_out_n = s->img_n; if (!stbi__create_png_image(z, z->expanded, raw_len, s->img_out_n, z->depth, color, interlace)) return 0; if (has_trans) { if (z->depth == 16) { if (!stbi__compute_transparency16(z, tc16, s->img_out_n)) return 0; } else { if (!stbi__compute_transparency(z, tc, s->img_out_n)) return 0; } } if (is_iphone && stbi__de_iphone_flag && s->img_out_n > 2) stbi__de_iphone(z); if (pal_img_n) { // pal_img_n == 3 or 4 s->img_n = pal_img_n; // record the actual colors we had s->img_out_n = pal_img_n; if (req_comp >= 3) s->img_out_n = req_comp; if (!stbi__expand_png_palette(z, palette, pal_len, s->img_out_n)) return 0; } else if (has_trans) { // non-paletted image with tRNS -> source image has (constant) alpha ++s->img_n; } STBI_FREE(z->expanded); z->expanded = NULL; // end of PNG chunk, read and skip CRC stbi__get32be(s); return 1; } default: // if critical, fail if (first) return stbi__err("first not IHDR", "Corrupt PNG"); if ((c.type & (1 << 29)) == 0) { #ifndef STBI_NO_FAILURE_STRINGS // not threadsafe static char invalid_chunk[] = "XXXX PNG chunk not known"; invalid_chunk[0] = STBI__BYTECAST(c.type >> 24); invalid_chunk[1] = STBI__BYTECAST(c.type >> 16); invalid_chunk[2] = STBI__BYTECAST(c.type >> 8); invalid_chunk[3] = STBI__BYTECAST(c.type >> 0); #endif return stbi__err(invalid_chunk, "PNG not supported: unknown PNG chunk type"); } stbi__skip(s, c.length); break; } // end of PNG chunk, read and skip CRC stbi__get32be(s); } } static void *stbi__do_png(stbi__png *p, int *x, int *y, int *n, int req_comp, stbi__result_info *ri) { void *result=NULL; if (req_comp < 0 || req_comp > 4) return stbi__errpuc("bad req_comp", "Internal error"); if (stbi__parse_png_file(p, STBI__SCAN_load, req_comp)) { if (p->depth <= 8) ri->bits_per_channel = 8; else if (p->depth == 16) ri->bits_per_channel = 16; else return stbi__errpuc("bad bits_per_channel", "PNG not supported: unsupported color depth"); result = p->out; p->out = NULL; if (req_comp && req_comp != p->s->img_out_n) { if (ri->bits_per_channel == 8) result = stbi__convert_format((unsigned char *) result, p->s->img_out_n, req_comp, p->s->img_x, p->s->img_y); else result = stbi__convert_format16((stbi__uint16 *) result, p->s->img_out_n, req_comp, p->s->img_x, p->s->img_y); p->s->img_out_n = req_comp; if (result == NULL) return result; } *x = p->s->img_x; *y = p->s->img_y; if (n) *n = p->s->img_n; } STBI_FREE(p->out); p->out = NULL; STBI_FREE(p->expanded); p->expanded = NULL; STBI_FREE(p->idata); p->idata = NULL; return result; } static void *stbi__png_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) { stbi__png p; p.s = s; return stbi__do_png(&p, x,y,comp,req_comp, ri); } static int stbi__png_test(stbi__context *s) { int r; r = stbi__check_png_header(s); stbi__rewind(s); return r; } static int stbi__png_info_raw(stbi__png *p, int *x, int *y, int *comp) { if (!stbi__parse_png_file(p, STBI__SCAN_header, 0)) { stbi__rewind( p->s ); return 0; } if (x) *x = p->s->img_x; if (y) *y = p->s->img_y; if (comp) *comp = p->s->img_n; return 1; } static int stbi__png_info(stbi__context *s, int *x, int *y, int *comp) { stbi__png p; p.s = s; return stbi__png_info_raw(&p, x, y, comp); } static int stbi__png_is16(stbi__context *s) { stbi__png p; p.s = s; if (!stbi__png_info_raw(&p, NULL, NULL, NULL)) return 0; if (p.depth != 16) { stbi__rewind(p.s); return 0; } return 1; } #endif // Microsoft/Windows BMP image #ifndef STBI_NO_BMP static int stbi__bmp_test_raw(stbi__context *s) { int r; int sz; if (stbi__get8(s) != 'B') return 0; if (stbi__get8(s) != 'M') return 0; stbi__get32le(s); // discard filesize stbi__get16le(s); // discard reserved stbi__get16le(s); // discard reserved stbi__get32le(s); // discard data offset sz = stbi__get32le(s); r = (sz == 12 || sz == 40 || sz == 56 || sz == 108 || sz == 124); return r; } static int stbi__bmp_test(stbi__context *s) { int r = stbi__bmp_test_raw(s); stbi__rewind(s); return r; } // returns 0..31 for the highest set bit static int stbi__high_bit(unsigned int z) { int n=0; if (z == 0) return -1; if (z >= 0x10000) { n += 16; z >>= 16; } if (z >= 0x00100) { n += 8; z >>= 8; } if (z >= 0x00010) { n += 4; z >>= 4; } if (z >= 0x00004) { n += 2; z >>= 2; } if (z >= 0x00002) { n += 1;/* >>= 1;*/ } return n; } static int stbi__bitcount(unsigned int a) { a = (a & 0x55555555) + ((a >> 1) & 0x55555555); // max 2 a = (a & 0x33333333) + ((a >> 2) & 0x33333333); // max 4 a = (a + (a >> 4)) & 0x0f0f0f0f; // max 8 per 4, now 8 bits a = (a + (a >> 8)); // max 16 per 8 bits a = (a + (a >> 16)); // max 32 per 8 bits return a & 0xff; } // extract an arbitrarily-aligned N-bit value (N=bits) // from v, and then make it 8-bits long and fractionally // extend it to full full range. static int stbi__shiftsigned(unsigned int v, int shift, int bits) { static unsigned int mul_table[9] = { 0, 0xff/*0b11111111*/, 0x55/*0b01010101*/, 0x49/*0b01001001*/, 0x11/*0b00010001*/, 0x21/*0b00100001*/, 0x41/*0b01000001*/, 0x81/*0b10000001*/, 0x01/*0b00000001*/, }; static unsigned int shift_table[9] = { 0, 0,0,1,0,2,4,6,0, }; if (shift < 0) v <<= -shift; else v >>= shift; STBI_ASSERT(v < 256); v >>= (8-bits); STBI_ASSERT(bits >= 0 && bits <= 8); return (int) ((unsigned) v * mul_table[bits]) >> shift_table[bits]; } typedef struct { int bpp, offset, hsz; unsigned int mr,mg,mb,ma, all_a; int extra_read; } stbi__bmp_data; static int stbi__bmp_set_mask_defaults(stbi__bmp_data *info, int compress) { // BI_BITFIELDS specifies masks explicitly, don't override if (compress == 3) return 1; if (compress == 0) { if (info->bpp == 16) { info->mr = 31u << 10; info->mg = 31u << 5; info->mb = 31u << 0; } else if (info->bpp == 32) { info->mr = 0xffu << 16; info->mg = 0xffu << 8; info->mb = 0xffu << 0; info->ma = 0xffu << 24; info->all_a = 0; // if all_a is 0 at end, then we loaded alpha channel but it was all 0 } else { // otherwise, use defaults, which is all-0 info->mr = info->mg = info->mb = info->ma = 0; } return 1; } return 0; // error } static void *stbi__bmp_parse_header(stbi__context *s, stbi__bmp_data *info) { int hsz; if (stbi__get8(s) != 'B' || stbi__get8(s) != 'M') return stbi__errpuc("not BMP", "Corrupt BMP"); stbi__get32le(s); // discard filesize stbi__get16le(s); // discard reserved stbi__get16le(s); // discard reserved info->offset = stbi__get32le(s); info->hsz = hsz = stbi__get32le(s); info->mr = info->mg = info->mb = info->ma = 0; info->extra_read = 14; if (info->offset < 0) return stbi__errpuc("bad BMP", "bad BMP"); if (hsz != 12 && hsz != 40 && hsz != 56 && hsz != 108 && hsz != 124) return stbi__errpuc("unknown BMP", "BMP type not supported: unknown"); if (hsz == 12) { s->img_x = stbi__get16le(s); s->img_y = stbi__get16le(s); } else { s->img_x = stbi__get32le(s); s->img_y = stbi__get32le(s); } if (stbi__get16le(s) != 1) return stbi__errpuc("bad BMP", "bad BMP"); info->bpp = stbi__get16le(s); if (hsz != 12) { int compress = stbi__get32le(s); if (compress == 1 || compress == 2) return stbi__errpuc("BMP RLE", "BMP type not supported: RLE"); if (compress >= 4) return stbi__errpuc("BMP JPEG/PNG", "BMP type not supported: unsupported compression"); // this includes PNG/JPEG modes if (compress == 3 && info->bpp != 16 && info->bpp != 32) return stbi__errpuc("bad BMP", "bad BMP"); // bitfields requires 16 or 32 bits/pixel stbi__get32le(s); // discard sizeof stbi__get32le(s); // discard hres stbi__get32le(s); // discard vres stbi__get32le(s); // discard colorsused stbi__get32le(s); // discard max important if (hsz == 40 || hsz == 56) { if (hsz == 56) { stbi__get32le(s); stbi__get32le(s); stbi__get32le(s); stbi__get32le(s); } if (info->bpp == 16 || info->bpp == 32) { if (compress == 0) { stbi__bmp_set_mask_defaults(info, compress); } else if (compress == 3) { info->mr = stbi__get32le(s); info->mg = stbi__get32le(s); info->mb = stbi__get32le(s); info->extra_read += 12; // not documented, but generated by photoshop and handled by mspaint if (info->mr == info->mg && info->mg == info->mb) { // ?!?!? return stbi__errpuc("bad BMP", "bad BMP"); } } else return stbi__errpuc("bad BMP", "bad BMP"); } } else { // V4/V5 header int i; if (hsz != 108 && hsz != 124) return stbi__errpuc("bad BMP", "bad BMP"); info->mr = stbi__get32le(s); info->mg = stbi__get32le(s); info->mb = stbi__get32le(s); info->ma = stbi__get32le(s); if (compress != 3) // override mr/mg/mb unless in BI_BITFIELDS mode, as per docs stbi__bmp_set_mask_defaults(info, compress); stbi__get32le(s); // discard color space for (i=0; i < 12; ++i) stbi__get32le(s); // discard color space parameters if (hsz == 124) { stbi__get32le(s); // discard rendering intent stbi__get32le(s); // discard offset of profile data stbi__get32le(s); // discard size of profile data stbi__get32le(s); // discard reserved } } } return (void *) 1; } static void *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) { stbi_uc *out; unsigned int mr=0,mg=0,mb=0,ma=0, all_a; stbi_uc pal[256][4]; int psize=0,i,j,width; int flip_vertically, pad, target; stbi__bmp_data info; STBI_NOTUSED(ri); info.all_a = 255; if (stbi__bmp_parse_header(s, &info) == NULL) return NULL; // error code already set flip_vertically = ((int) s->img_y) > 0; s->img_y = abs((int) s->img_y); if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); mr = info.mr; mg = info.mg; mb = info.mb; ma = info.ma; all_a = info.all_a; if (info.hsz == 12) { if (info.bpp < 24) psize = (info.offset - info.extra_read - 24) / 3; } else { if (info.bpp < 16) psize = (info.offset - info.extra_read - info.hsz) >> 2; } if (psize == 0) { // accept some number of extra bytes after the header, but if the offset points either to before // the header ends or implies a large amount of extra data, reject the file as malformed int bytes_read_so_far = s->callback_already_read + (int)(s->img_buffer - s->img_buffer_original); int header_limit = 1024; // max we actually read is below 256 bytes currently. int extra_data_limit = 256*4; // what ordinarily goes here is a palette; 256 entries*4 bytes is its max size. if (bytes_read_so_far <= 0 || bytes_read_so_far > header_limit) { return stbi__errpuc("bad header", "Corrupt BMP"); } // we established that bytes_read_so_far is positive and sensible. // the first half of this test rejects offsets that are either too small positives, or // negative, and guarantees that info.offset >= bytes_read_so_far > 0. this in turn // ensures the number computed in the second half of the test can't overflow. if (info.offset < bytes_read_so_far || info.offset - bytes_read_so_far > extra_data_limit) { return stbi__errpuc("bad offset", "Corrupt BMP"); } else { stbi__skip(s, info.offset - bytes_read_so_far); } } if (info.bpp == 24 && ma == 0xff000000) s->img_n = 3; else s->img_n = ma ? 4 : 3; if (req_comp && req_comp >= 3) // we can directly decode 3 or 4 target = req_comp; else target = s->img_n; // if they want monochrome, we'll post-convert // sanity-check size if (!stbi__mad3sizes_valid(target, s->img_x, s->img_y, 0)) return stbi__errpuc("too large", "Corrupt BMP"); out = (stbi_uc *) stbi__malloc_mad3(target, s->img_x, s->img_y, 0); if (!out) return stbi__errpuc("outofmem", "Out of memory"); if (info.bpp < 16) { int z=0; if (psize == 0 || psize > 256) { STBI_FREE(out); return stbi__errpuc("invalid", "Corrupt BMP"); } for (i=0; i < psize; ++i) { pal[i][2] = stbi__get8(s); pal[i][1] = stbi__get8(s); pal[i][0] = stbi__get8(s); if (info.hsz != 12) stbi__get8(s); pal[i][3] = 255; } stbi__skip(s, info.offset - info.extra_read - info.hsz - psize * (info.hsz == 12 ? 3 : 4)); if (info.bpp == 1) width = (s->img_x + 7) >> 3; else if (info.bpp == 4) width = (s->img_x + 1) >> 1; else if (info.bpp == 8) width = s->img_x; else { STBI_FREE(out); return stbi__errpuc("bad bpp", "Corrupt BMP"); } pad = (-width)&3; if (info.bpp == 1) { for (j=0; j < (int) s->img_y; ++j) { int bit_offset = 7, v = stbi__get8(s); for (i=0; i < (int) s->img_x; ++i) { int color = (v>>bit_offset)&0x1; out[z++] = pal[color][0]; out[z++] = pal[color][1]; out[z++] = pal[color][2]; if (target == 4) out[z++] = 255; if (i+1 == (int) s->img_x) break; if((--bit_offset) < 0) { bit_offset = 7; v = stbi__get8(s); } } stbi__skip(s, pad); } } else { for (j=0; j < (int) s->img_y; ++j) { for (i=0; i < (int) s->img_x; i += 2) { int v=stbi__get8(s),v2=0; if (info.bpp == 4) { v2 = v & 15; v >>= 4; } out[z++] = pal[v][0]; out[z++] = pal[v][1]; out[z++] = pal[v][2]; if (target == 4) out[z++] = 255; if (i+1 == (int) s->img_x) break; v = (info.bpp == 8) ? stbi__get8(s) : v2; out[z++] = pal[v][0]; out[z++] = pal[v][1]; out[z++] = pal[v][2]; if (target == 4) out[z++] = 255; } stbi__skip(s, pad); } } } else { int rshift=0,gshift=0,bshift=0,ashift=0,rcount=0,gcount=0,bcount=0,acount=0; int z = 0; int easy=0; stbi__skip(s, info.offset - info.extra_read - info.hsz); if (info.bpp == 24) width = 3 * s->img_x; else if (info.bpp == 16) width = 2*s->img_x; else /* bpp = 32 and pad = 0 */ width=0; pad = (-width) & 3; if (info.bpp == 24) { easy = 1; } else if (info.bpp == 32) { if (mb == 0xff && mg == 0xff00 && mr == 0x00ff0000 && ma == 0xff000000) easy = 2; } if (!easy) { if (!mr || !mg || !mb) { STBI_FREE(out); return stbi__errpuc("bad masks", "Corrupt BMP"); } // right shift amt to put high bit in position #7 rshift = stbi__high_bit(mr)-7; rcount = stbi__bitcount(mr); gshift = stbi__high_bit(mg)-7; gcount = stbi__bitcount(mg); bshift = stbi__high_bit(mb)-7; bcount = stbi__bitcount(mb); ashift = stbi__high_bit(ma)-7; acount = stbi__bitcount(ma); if (rcount > 8 || gcount > 8 || bcount > 8 || acount > 8) { STBI_FREE(out); return stbi__errpuc("bad masks", "Corrupt BMP"); } } for (j=0; j < (int) s->img_y; ++j) { if (easy) { for (i=0; i < (int) s->img_x; ++i) { unsigned char a; out[z+2] = stbi__get8(s); out[z+1] = stbi__get8(s); out[z+0] = stbi__get8(s); z += 3; a = (easy == 2 ? stbi__get8(s) : 255); all_a |= a; if (target == 4) out[z++] = a; } } else { int bpp = info.bpp; for (i=0; i < (int) s->img_x; ++i) { stbi__uint32 v = (bpp == 16 ? (stbi__uint32) stbi__get16le(s) : stbi__get32le(s)); unsigned int a; out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mr, rshift, rcount)); out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mg, gshift, gcount)); out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mb, bshift, bcount)); a = (ma ? stbi__shiftsigned(v & ma, ashift, acount) : 255); all_a |= a; if (target == 4) out[z++] = STBI__BYTECAST(a); } } stbi__skip(s, pad); } } // if alpha channel is all 0s, replace with all 255s if (target == 4 && all_a == 0) for (i=4*s->img_x*s->img_y-1; i >= 0; i -= 4) out[i] = 255; if (flip_vertically) { stbi_uc t; for (j=0; j < (int) s->img_y>>1; ++j) { stbi_uc *p1 = out + j *s->img_x*target; stbi_uc *p2 = out + (s->img_y-1-j)*s->img_x*target; for (i=0; i < (int) s->img_x*target; ++i) { t = p1[i]; p1[i] = p2[i]; p2[i] = t; } } } if (req_comp && req_comp != target) { out = stbi__convert_format(out, target, req_comp, s->img_x, s->img_y); if (out == NULL) return out; // stbi__convert_format frees input on failure } *x = s->img_x; *y = s->img_y; if (comp) *comp = s->img_n; return out; } #endif // Targa Truevision - TGA // by Jonathan Dummer #ifndef STBI_NO_TGA // returns STBI_rgb or whatever, 0 on error static int stbi__tga_get_comp(int bits_per_pixel, int is_grey, int* is_rgb16) { // only RGB or RGBA (incl. 16bit) or grey allowed if (is_rgb16) *is_rgb16 = 0; switch(bits_per_pixel) { case 8: return STBI_grey; case 16: if(is_grey) return STBI_grey_alpha; // fallthrough case 15: if(is_rgb16) *is_rgb16 = 1; return STBI_rgb; case 24: // fallthrough case 32: return bits_per_pixel/8; default: return 0; } } static int stbi__tga_info(stbi__context *s, int *x, int *y, int *comp) { int tga_w, tga_h, tga_comp, tga_image_type, tga_bits_per_pixel, tga_colormap_bpp; int sz, tga_colormap_type; stbi__get8(s); // discard Offset tga_colormap_type = stbi__get8(s); // colormap type if( tga_colormap_type > 1 ) { stbi__rewind(s); return 0; // only RGB or indexed allowed } tga_image_type = stbi__get8(s); // image type if ( tga_colormap_type == 1 ) { // colormapped (paletted) image if (tga_image_type != 1 && tga_image_type != 9) { stbi__rewind(s); return 0; } stbi__skip(s,4); // skip index of first colormap entry and number of entries sz = stbi__get8(s); // check bits per palette color entry if ( (sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32) ) { stbi__rewind(s); return 0; } stbi__skip(s,4); // skip image x and y origin tga_colormap_bpp = sz; } else { // "normal" image w/o colormap - only RGB or grey allowed, +/- RLE if ( (tga_image_type != 2) && (tga_image_type != 3) && (tga_image_type != 10) && (tga_image_type != 11) ) { stbi__rewind(s); return 0; // only RGB or grey allowed, +/- RLE } stbi__skip(s,9); // skip colormap specification and image x/y origin tga_colormap_bpp = 0; } tga_w = stbi__get16le(s); if( tga_w < 1 ) { stbi__rewind(s); return 0; // test width } tga_h = stbi__get16le(s); if( tga_h < 1 ) { stbi__rewind(s); return 0; // test height } tga_bits_per_pixel = stbi__get8(s); // bits per pixel stbi__get8(s); // ignore alpha bits if (tga_colormap_bpp != 0) { if((tga_bits_per_pixel != 8) && (tga_bits_per_pixel != 16)) { // when using a colormap, tga_bits_per_pixel is the size of the indexes // I don't think anything but 8 or 16bit indexes makes sense stbi__rewind(s); return 0; } tga_comp = stbi__tga_get_comp(tga_colormap_bpp, 0, NULL); } else { tga_comp = stbi__tga_get_comp(tga_bits_per_pixel, (tga_image_type == 3) || (tga_image_type == 11), NULL); } if(!tga_comp) { stbi__rewind(s); return 0; } if (x) *x = tga_w; if (y) *y = tga_h; if (comp) *comp = tga_comp; return 1; // seems to have passed everything } static int stbi__tga_test(stbi__context *s) { int res = 0; int sz, tga_color_type; stbi__get8(s); // discard Offset tga_color_type = stbi__get8(s); // color type if ( tga_color_type > 1 ) goto errorEnd; // only RGB or indexed allowed sz = stbi__get8(s); // image type if ( tga_color_type == 1 ) { // colormapped (paletted) image if (sz != 1 && sz != 9) goto errorEnd; // colortype 1 demands image type 1 or 9 stbi__skip(s,4); // skip index of first colormap entry and number of entries sz = stbi__get8(s); // check bits per palette color entry if ( (sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32) ) goto errorEnd; stbi__skip(s,4); // skip image x and y origin } else { // "normal" image w/o colormap if ( (sz != 2) && (sz != 3) && (sz != 10) && (sz != 11) ) goto errorEnd; // only RGB or grey allowed, +/- RLE stbi__skip(s,9); // skip colormap specification and image x/y origin } if ( stbi__get16le(s) < 1 ) goto errorEnd; // test width if ( stbi__get16le(s) < 1 ) goto errorEnd; // test height sz = stbi__get8(s); // bits per pixel if ( (tga_color_type == 1) && (sz != 8) && (sz != 16) ) goto errorEnd; // for colormapped images, bpp is size of an index if ( (sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32) ) goto errorEnd; res = 1; // if we got this far, everything's good and we can return 1 instead of 0 errorEnd: stbi__rewind(s); return res; } // read 16bit value and convert to 24bit RGB static void stbi__tga_read_rgb16(stbi__context *s, stbi_uc* out) { stbi__uint16 px = (stbi__uint16)stbi__get16le(s); stbi__uint16 fiveBitMask = 31; // we have 3 channels with 5bits each int r = (px >> 10) & fiveBitMask; int g = (px >> 5) & fiveBitMask; int b = px & fiveBitMask; // Note that this saves the data in RGB(A) order, so it doesn't need to be swapped later out[0] = (stbi_uc)((r * 255)/31); out[1] = (stbi_uc)((g * 255)/31); out[2] = (stbi_uc)((b * 255)/31); // some people claim that the most significant bit might be used for alpha // (possibly if an alpha-bit is set in the "image descriptor byte") // but that only made 16bit test images completely translucent.. // so let's treat all 15 and 16bit TGAs as RGB with no alpha. } static void *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) { // read in the TGA header stuff int tga_offset = stbi__get8(s); int tga_indexed = stbi__get8(s); int tga_image_type = stbi__get8(s); int tga_is_RLE = 0; int tga_palette_start = stbi__get16le(s); int tga_palette_len = stbi__get16le(s); int tga_palette_bits = stbi__get8(s); int tga_x_origin = stbi__get16le(s); int tga_y_origin = stbi__get16le(s); int tga_width = stbi__get16le(s); int tga_height = stbi__get16le(s); int tga_bits_per_pixel = stbi__get8(s); int tga_comp, tga_rgb16=0; int tga_inverted = stbi__get8(s); // int tga_alpha_bits = tga_inverted & 15; // the 4 lowest bits - unused (useless?) // image data unsigned char *tga_data; unsigned char *tga_palette = NULL; int i, j; unsigned char raw_data[4] = {0}; int RLE_count = 0; int RLE_repeating = 0; int read_next_pixel = 1; STBI_NOTUSED(ri); STBI_NOTUSED(tga_x_origin); // @TODO STBI_NOTUSED(tga_y_origin); // @TODO if (tga_height > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); if (tga_width > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); // do a tiny bit of precessing if ( tga_image_type >= 8 ) { tga_image_type -= 8; tga_is_RLE = 1; } tga_inverted = 1 - ((tga_inverted >> 5) & 1); // If I'm paletted, then I'll use the number of bits from the palette if ( tga_indexed ) tga_comp = stbi__tga_get_comp(tga_palette_bits, 0, &tga_rgb16); else tga_comp = stbi__tga_get_comp(tga_bits_per_pixel, (tga_image_type == 3), &tga_rgb16); if(!tga_comp) // shouldn't really happen, stbi__tga_test() should have ensured basic consistency return stbi__errpuc("bad format", "Can't find out TGA pixelformat"); // tga info *x = tga_width; *y = tga_height; if (comp) *comp = tga_comp; if (!stbi__mad3sizes_valid(tga_width, tga_height, tga_comp, 0)) return stbi__errpuc("too large", "Corrupt TGA"); tga_data = (unsigned char*)stbi__malloc_mad3(tga_width, tga_height, tga_comp, 0); if (!tga_data) return stbi__errpuc("outofmem", "Out of memory"); // skip to the data's starting position (offset usually = 0) stbi__skip(s, tga_offset ); if ( !tga_indexed && !tga_is_RLE && !tga_rgb16 ) { for (i=0; i < tga_height; ++i) { int row = tga_inverted ? tga_height -i - 1 : i; stbi_uc *tga_row = tga_data + row*tga_width*tga_comp; stbi__getn(s, tga_row, tga_width * tga_comp); } } else { // do I need to load a palette? if ( tga_indexed) { if (tga_palette_len == 0) { /* you have to have at least one entry! */ STBI_FREE(tga_data); return stbi__errpuc("bad palette", "Corrupt TGA"); } // any data to skip? (offset usually = 0) stbi__skip(s, tga_palette_start ); // load the palette tga_palette = (unsigned char*)stbi__malloc_mad2(tga_palette_len, tga_comp, 0); if (!tga_palette) { STBI_FREE(tga_data); return stbi__errpuc("outofmem", "Out of memory"); } if (tga_rgb16) { stbi_uc *pal_entry = tga_palette; STBI_ASSERT(tga_comp == STBI_rgb); for (i=0; i < tga_palette_len; ++i) { stbi__tga_read_rgb16(s, pal_entry); pal_entry += tga_comp; } } else if (!stbi__getn(s, tga_palette, tga_palette_len * tga_comp)) { STBI_FREE(tga_data); STBI_FREE(tga_palette); return stbi__errpuc("bad palette", "Corrupt TGA"); } } // load the data for (i=0; i < tga_width * tga_height; ++i) { // if I'm in RLE mode, do I need to get a RLE stbi__pngchunk? if ( tga_is_RLE ) { if ( RLE_count == 0 ) { // yep, get the next byte as a RLE command int RLE_cmd = stbi__get8(s); RLE_count = 1 + (RLE_cmd & 127); RLE_repeating = RLE_cmd >> 7; read_next_pixel = 1; } else if ( !RLE_repeating ) { read_next_pixel = 1; } } else { read_next_pixel = 1; } // OK, if I need to read a pixel, do it now if ( read_next_pixel ) { // load however much data we did have if ( tga_indexed ) { // read in index, then perform the lookup int pal_idx = (tga_bits_per_pixel == 8) ? stbi__get8(s) : stbi__get16le(s); if ( pal_idx >= tga_palette_len ) { // invalid index pal_idx = 0; } pal_idx *= tga_comp; for (j = 0; j < tga_comp; ++j) { raw_data[j] = tga_palette[pal_idx+j]; } } else if(tga_rgb16) { STBI_ASSERT(tga_comp == STBI_rgb); stbi__tga_read_rgb16(s, raw_data); } else { // read in the data raw for (j = 0; j < tga_comp; ++j) { raw_data[j] = stbi__get8(s); } } // clear the reading flag for the next pixel read_next_pixel = 0; } // end of reading a pixel // copy data for (j = 0; j < tga_comp; ++j) tga_data[i*tga_comp+j] = raw_data[j]; // in case we're in RLE mode, keep counting down --RLE_count; } // do I need to invert the image? if ( tga_inverted ) { for (j = 0; j*2 < tga_height; ++j) { int index1 = j * tga_width * tga_comp; int index2 = (tga_height - 1 - j) * tga_width * tga_comp; for (i = tga_width * tga_comp; i > 0; --i) { unsigned char temp = tga_data[index1]; tga_data[index1] = tga_data[index2]; tga_data[index2] = temp; ++index1; ++index2; } } } // clear my palette, if I had one if ( tga_palette != NULL ) { STBI_FREE( tga_palette ); } } // swap RGB - if the source data was RGB16, it already is in the right order if (tga_comp >= 3 && !tga_rgb16) { unsigned char* tga_pixel = tga_data; for (i=0; i < tga_width * tga_height; ++i) { unsigned char temp = tga_pixel[0]; tga_pixel[0] = tga_pixel[2]; tga_pixel[2] = temp; tga_pixel += tga_comp; } } // convert to target component count if (req_comp && req_comp != tga_comp) tga_data = stbi__convert_format(tga_data, tga_comp, req_comp, tga_width, tga_height); // the things I do to get rid of an error message, and yet keep // Microsoft's C compilers happy... [8^( tga_palette_start = tga_palette_len = tga_palette_bits = tga_x_origin = tga_y_origin = 0; STBI_NOTUSED(tga_palette_start); // OK, done return tga_data; } #endif // ************************************************************************************************* // Photoshop PSD loader -- PD by Thatcher Ulrich, integration by Nicolas Schulz, tweaked by STB #ifndef STBI_NO_PSD static int stbi__psd_test(stbi__context *s) { int r = (stbi__get32be(s) == 0x38425053); stbi__rewind(s); return r; } static int stbi__psd_decode_rle(stbi__context *s, stbi_uc *p, int pixelCount) { int count, nleft, len; count = 0; while ((nleft = pixelCount - count) > 0) { len = stbi__get8(s); if (len == 128) { // No-op. } else if (len < 128) { // Copy next len+1 bytes literally. len++; if (len > nleft) return 0; // corrupt data count += len; while (len) { *p = stbi__get8(s); p += 4; len--; } } else if (len > 128) { stbi_uc val; // Next -len+1 bytes in the dest are replicated from next source byte. // (Interpret len as a negative 8-bit int.) len = 257 - len; if (len > nleft) return 0; // corrupt data val = stbi__get8(s); count += len; while (len) { *p = val; p += 4; len--; } } } return 1; } static void *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri, int bpc) { int pixelCount; int channelCount, compression; int channel, i; int bitdepth; int w,h; stbi_uc *out; STBI_NOTUSED(ri); // Check identifier if (stbi__get32be(s) != 0x38425053) // "8BPS" return stbi__errpuc("not PSD", "Corrupt PSD image"); // Check file type version. if (stbi__get16be(s) != 1) return stbi__errpuc("wrong version", "Unsupported version of PSD image"); // Skip 6 reserved bytes. stbi__skip(s, 6 ); // Read the number of channels (R, G, B, A, etc). channelCount = stbi__get16be(s); if (channelCount < 0 || channelCount > 16) return stbi__errpuc("wrong channel count", "Unsupported number of channels in PSD image"); // Read the rows and columns of the image. h = stbi__get32be(s); w = stbi__get32be(s); if (h > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); if (w > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); // Make sure the depth is 8 bits. bitdepth = stbi__get16be(s); if (bitdepth != 8 && bitdepth != 16) return stbi__errpuc("unsupported bit depth", "PSD bit depth is not 8 or 16 bit"); // Make sure the color mode is RGB. // Valid options are: // 0: Bitmap // 1: Grayscale // 2: Indexed color // 3: RGB color // 4: CMYK color // 7: Multichannel // 8: Duotone // 9: Lab color if (stbi__get16be(s) != 3) return stbi__errpuc("wrong color format", "PSD is not in RGB color format"); // Skip the Mode Data. (It's the palette for indexed color; other info for other modes.) stbi__skip(s,stbi__get32be(s) ); // Skip the image resources. (resolution, pen tool paths, etc) stbi__skip(s, stbi__get32be(s) ); // Skip the reserved data. stbi__skip(s, stbi__get32be(s) ); // Find out if the data is compressed. // Known values: // 0: no compression // 1: RLE compressed compression = stbi__get16be(s); if (compression > 1) return stbi__errpuc("bad compression", "PSD has an unknown compression format"); // Check size if (!stbi__mad3sizes_valid(4, w, h, 0)) return stbi__errpuc("too large", "Corrupt PSD"); // Create the destination image. if (!compression && bitdepth == 16 && bpc == 16) { out = (stbi_uc *) stbi__malloc_mad3(8, w, h, 0); ri->bits_per_channel = 16; } else out = (stbi_uc *) stbi__malloc(4 * w*h); if (!out) return stbi__errpuc("outofmem", "Out of memory"); pixelCount = w*h; // Initialize the data to zero. //memset( out, 0, pixelCount * 4 ); // Finally, the image data. if (compression) { // RLE as used by .PSD and .TIFF // Loop until you get the number of unpacked bytes you are expecting: // Read the next source byte into n. // If n is between 0 and 127 inclusive, copy the next n+1 bytes literally. // Else if n is between -127 and -1 inclusive, copy the next byte -n+1 times. // Else if n is 128, noop. // Endloop // The RLE-compressed data is preceded by a 2-byte data count for each row in the data, // which we're going to just skip. stbi__skip(s, h * channelCount * 2 ); // Read the RLE data by channel. for (channel = 0; channel < 4; channel++) { stbi_uc *p; p = out+channel; if (channel >= channelCount) { // Fill this channel with default data. for (i = 0; i < pixelCount; i++, p += 4) *p = (channel == 3 ? 255 : 0); } else { // Read the RLE data. if (!stbi__psd_decode_rle(s, p, pixelCount)) { STBI_FREE(out); return stbi__errpuc("corrupt", "bad RLE data"); } } } } else { // We're at the raw image data. It's each channel in order (Red, Green, Blue, Alpha, ...) // where each channel consists of an 8-bit (or 16-bit) value for each pixel in the image. // Read the data by channel. for (channel = 0; channel < 4; channel++) { if (channel >= channelCount) { // Fill this channel with default data. if (bitdepth == 16 && bpc == 16) { stbi__uint16 *q = ((stbi__uint16 *) out) + channel; stbi__uint16 val = channel == 3 ? 65535 : 0; for (i = 0; i < pixelCount; i++, q += 4) *q = val; } else { stbi_uc *p = out+channel; stbi_uc val = channel == 3 ? 255 : 0; for (i = 0; i < pixelCount; i++, p += 4) *p = val; } } else { if (ri->bits_per_channel == 16) { // output bpc stbi__uint16 *q = ((stbi__uint16 *) out) + channel; for (i = 0; i < pixelCount; i++, q += 4) *q = (stbi__uint16) stbi__get16be(s); } else { stbi_uc *p = out+channel; if (bitdepth == 16) { // input bpc for (i = 0; i < pixelCount; i++, p += 4) *p = (stbi_uc) (stbi__get16be(s) >> 8); } else { for (i = 0; i < pixelCount; i++, p += 4) *p = stbi__get8(s); } } } } } // remove weird white matte from PSD if (channelCount >= 4) { if (ri->bits_per_channel == 16) { for (i=0; i < w*h; ++i) { stbi__uint16 *pixel = (stbi__uint16 *) out + 4*i; if (pixel[3] != 0 && pixel[3] != 65535) { float a = pixel[3] / 65535.0f; float ra = 1.0f / a; float inv_a = 65535.0f * (1 - ra); pixel[0] = (stbi__uint16) (pixel[0]*ra + inv_a); pixel[1] = (stbi__uint16) (pixel[1]*ra + inv_a); pixel[2] = (stbi__uint16) (pixel[2]*ra + inv_a); } } } else { for (i=0; i < w*h; ++i) { unsigned char *pixel = out + 4*i; if (pixel[3] != 0 && pixel[3] != 255) { float a = pixel[3] / 255.0f; float ra = 1.0f / a; float inv_a = 255.0f * (1 - ra); pixel[0] = (unsigned char) (pixel[0]*ra + inv_a); pixel[1] = (unsigned char) (pixel[1]*ra + inv_a); pixel[2] = (unsigned char) (pixel[2]*ra + inv_a); } } } } // convert to desired output format if (req_comp && req_comp != 4) { if (ri->bits_per_channel == 16) out = (stbi_uc *) stbi__convert_format16((stbi__uint16 *) out, 4, req_comp, w, h); else out = stbi__convert_format(out, 4, req_comp, w, h); if (out == NULL) return out; // stbi__convert_format frees input on failure } if (comp) *comp = 4; *y = h; *x = w; return out; } #endif // ************************************************************************************************* // Softimage PIC loader // by Tom Seddon // // See http://softimage.wiki.softimage.com/index.php/INFO:_PIC_file_format // See http://ozviz.wasp.uwa.edu.au/~pbourke/dataformats/softimagepic/ #ifndef STBI_NO_PIC static int stbi__pic_is4(stbi__context *s,const char *str) { int i; for (i=0; i<4; ++i) if (stbi__get8(s) != (stbi_uc)str[i]) return 0; return 1; } static int stbi__pic_test_core(stbi__context *s) { int i; if (!stbi__pic_is4(s,"\x53\x80\xF6\x34")) return 0; for(i=0;i<84;++i) stbi__get8(s); if (!stbi__pic_is4(s,"PICT")) return 0; return 1; } typedef struct { stbi_uc size,type,channel; } stbi__pic_packet; static stbi_uc *stbi__readval(stbi__context *s, int channel, stbi_uc *dest) { int mask=0x80, i; for (i=0; i<4; ++i, mask>>=1) { if (channel & mask) { if (stbi__at_eof(s)) return stbi__errpuc("bad file","PIC file too short"); dest[i]=stbi__get8(s); } } return dest; } static void stbi__copyval(int channel,stbi_uc *dest,const stbi_uc *src) { int mask=0x80,i; for (i=0;i<4; ++i, mask>>=1) if (channel&mask) dest[i]=src[i]; } static stbi_uc *stbi__pic_load_core(stbi__context *s,int width,int height,int *comp, stbi_uc *result) { int act_comp=0,num_packets=0,y,chained; stbi__pic_packet packets[10]; // this will (should...) cater for even some bizarre stuff like having data // for the same channel in multiple packets. do { stbi__pic_packet *packet; if (num_packets==sizeof(packets)/sizeof(packets[0])) return stbi__errpuc("bad format","too many packets"); packet = &packets[num_packets++]; chained = stbi__get8(s); packet->size = stbi__get8(s); packet->type = stbi__get8(s); packet->channel = stbi__get8(s); act_comp |= packet->channel; if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (reading packets)"); if (packet->size != 8) return stbi__errpuc("bad format","packet isn't 8bpp"); } while (chained); *comp = (act_comp & 0x10 ? 4 : 3); // has alpha channel? for(y=0; y<height; ++y) { int packet_idx; for(packet_idx=0; packet_idx < num_packets; ++packet_idx) { stbi__pic_packet *packet = &packets[packet_idx]; stbi_uc *dest = result+y*width*4; switch (packet->type) { default: return stbi__errpuc("bad format","packet has bad compression type"); case 0: {//uncompressed int x; for(x=0;x<width;++x, dest+=4) if (!stbi__readval(s,packet->channel,dest)) return 0; break; } case 1://Pure RLE { int left=width, i; while (left>0) { stbi_uc count,value[4]; count=stbi__get8(s); if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (pure read count)"); if (count > left) count = (stbi_uc) left; if (!stbi__readval(s,packet->channel,value)) return 0; for(i=0; i<count; ++i,dest+=4) stbi__copyval(packet->channel,dest,value); left -= count; } } break; case 2: {//Mixed RLE int left=width; while (left>0) { int count = stbi__get8(s), i; if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (mixed read count)"); if (count >= 128) { // Repeated stbi_uc value[4]; if (count==128) count = stbi__get16be(s); else count -= 127; if (count > left) return stbi__errpuc("bad file","scanline overrun"); if (!stbi__readval(s,packet->channel,value)) return 0; for(i=0;i<count;++i, dest += 4) stbi__copyval(packet->channel,dest,value); } else { // Raw ++count; if (count>left) return stbi__errpuc("bad file","scanline overrun"); for(i=0;i<count;++i, dest+=4) if (!stbi__readval(s,packet->channel,dest)) return 0; } left-=count; } break; } } } } return result; } static void *stbi__pic_load(stbi__context *s,int *px,int *py,int *comp,int req_comp, stbi__result_info *ri) { stbi_uc *result; int i, x,y, internal_comp; STBI_NOTUSED(ri); if (!comp) comp = &internal_comp; for (i=0; i<92; ++i) stbi__get8(s); x = stbi__get16be(s); y = stbi__get16be(s); if (y > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); if (x > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (pic header)"); if (!stbi__mad3sizes_valid(x, y, 4, 0)) return stbi__errpuc("too large", "PIC image too large to decode"); stbi__get32be(s); //skip `ratio' stbi__get16be(s); //skip `fields' stbi__get16be(s); //skip `pad' // intermediate buffer is RGBA result = (stbi_uc *) stbi__malloc_mad3(x, y, 4, 0); if (!result) return stbi__errpuc("outofmem", "Out of memory"); memset(result, 0xff, x*y*4); if (!stbi__pic_load_core(s,x,y,comp, result)) { STBI_FREE(result); result=0; } *px = x; *py = y; if (req_comp == 0) req_comp = *comp; result=stbi__convert_format(result,4,req_comp,x,y); return result; } static int stbi__pic_test(stbi__context *s) { int r = stbi__pic_test_core(s); stbi__rewind(s); return r; } #endif // ************************************************************************************************* // GIF loader -- public domain by Jean-Marc Lienher -- simplified/shrunk by stb #ifndef STBI_NO_GIF typedef struct { stbi__int16 prefix; stbi_uc first; stbi_uc suffix; } stbi__gif_lzw; typedef struct { int w,h; stbi_uc *out; // output buffer (always 4 components) stbi_uc *background; // The current "background" as far as a gif is concerned stbi_uc *history; int flags, bgindex, ratio, transparent, eflags; stbi_uc pal[256][4]; stbi_uc lpal[256][4]; stbi__gif_lzw codes[8192]; stbi_uc *color_table; int parse, step; int lflags; int start_x, start_y; int max_x, max_y; int cur_x, cur_y; int line_size; int delay; } stbi__gif; static int stbi__gif_test_raw(stbi__context *s) { int sz; if (stbi__get8(s) != 'G' || stbi__get8(s) != 'I' || stbi__get8(s) != 'F' || stbi__get8(s) != '8') return 0; sz = stbi__get8(s); if (sz != '9' && sz != '7') return 0; if (stbi__get8(s) != 'a') return 0; return 1; } static int stbi__gif_test(stbi__context *s) { int r = stbi__gif_test_raw(s); stbi__rewind(s); return r; } static void stbi__gif_parse_colortable(stbi__context *s, stbi_uc pal[256][4], int num_entries, int transp) { int i; for (i=0; i < num_entries; ++i) { pal[i][2] = stbi__get8(s); pal[i][1] = stbi__get8(s); pal[i][0] = stbi__get8(s); pal[i][3] = transp == i ? 0 : 255; } } static int stbi__gif_header(stbi__context *s, stbi__gif *g, int *comp, int is_info) { stbi_uc version; if (stbi__get8(s) != 'G' || stbi__get8(s) != 'I' || stbi__get8(s) != 'F' || stbi__get8(s) != '8') return stbi__err("not GIF", "Corrupt GIF"); version = stbi__get8(s); if (version != '7' && version != '9') return stbi__err("not GIF", "Corrupt GIF"); if (stbi__get8(s) != 'a') return stbi__err("not GIF", "Corrupt GIF"); stbi__g_failure_reason = ""; g->w = stbi__get16le(s); g->h = stbi__get16le(s); g->flags = stbi__get8(s); g->bgindex = stbi__get8(s); g->ratio = stbi__get8(s); g->transparent = -1; if (g->w > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); if (g->h > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); if (comp != 0) *comp = 4; // can't actually tell whether it's 3 or 4 until we parse the comments if (is_info) return 1; if (g->flags & 0x80) stbi__gif_parse_colortable(s,g->pal, 2 << (g->flags & 7), -1); return 1; } static int stbi__gif_info_raw(stbi__context *s, int *x, int *y, int *comp) { stbi__gif* g = (stbi__gif*) stbi__malloc(sizeof(stbi__gif)); if (!g) return stbi__err("outofmem", "Out of memory"); if (!stbi__gif_header(s, g, comp, 1)) { STBI_FREE(g); stbi__rewind( s ); return 0; } if (x) *x = g->w; if (y) *y = g->h; STBI_FREE(g); return 1; } static void stbi__out_gif_code(stbi__gif *g, stbi__uint16 code) { stbi_uc *p, *c; int idx; // recurse to decode the prefixes, since the linked-list is backwards, // and working backwards through an interleaved image would be nasty if (g->codes[code].prefix >= 0) stbi__out_gif_code(g, g->codes[code].prefix); if (g->cur_y >= g->max_y) return; idx = g->cur_x + g->cur_y; p = &g->out[idx]; g->history[idx / 4] = 1; c = &g->color_table[g->codes[code].suffix * 4]; if (c[3] > 128) { // don't render transparent pixels; p[0] = c[2]; p[1] = c[1]; p[2] = c[0]; p[3] = c[3]; } g->cur_x += 4; if (g->cur_x >= g->max_x) { g->cur_x = g->start_x; g->cur_y += g->step; while (g->cur_y >= g->max_y && g->parse > 0) { g->step = (1 << g->parse) * g->line_size; g->cur_y = g->start_y + (g->step >> 1); --g->parse; } } } static stbi_uc *stbi__process_gif_raster(stbi__context *s, stbi__gif *g) { stbi_uc lzw_cs; stbi__int32 len, init_code; stbi__uint32 first; stbi__int32 codesize, codemask, avail, oldcode, bits, valid_bits, clear; stbi__gif_lzw *p; lzw_cs = stbi__get8(s); if (lzw_cs > 12) return NULL; clear = 1 << lzw_cs; first = 1; codesize = lzw_cs + 1; codemask = (1 << codesize) - 1; bits = 0; valid_bits = 0; for (init_code = 0; init_code < clear; init_code++) { g->codes[init_code].prefix = -1; g->codes[init_code].first = (stbi_uc) init_code; g->codes[init_code].suffix = (stbi_uc) init_code; } // support no starting clear code avail = clear+2; oldcode = -1; len = 0; for(;;) { if (valid_bits < codesize) { if (len == 0) { len = stbi__get8(s); // start new block if (len == 0) return g->out; } --len; bits |= (stbi__int32) stbi__get8(s) << valid_bits; valid_bits += 8; } else { stbi__int32 code = bits & codemask; bits >>= codesize; valid_bits -= codesize; // @OPTIMIZE: is there some way we can accelerate the non-clear path? if (code == clear) { // clear code codesize = lzw_cs + 1; codemask = (1 << codesize) - 1; avail = clear + 2; oldcode = -1; first = 0; } else if (code == clear + 1) { // end of stream code stbi__skip(s, len); while ((len = stbi__get8(s)) > 0) stbi__skip(s,len); return g->out; } else if (code <= avail) { if (first) { return stbi__errpuc("no clear code", "Corrupt GIF"); } if (oldcode >= 0) { p = &g->codes[avail++]; if (avail > 8192) { return stbi__errpuc("too many codes", "Corrupt GIF"); } p->prefix = (stbi__int16) oldcode; p->first = g->codes[oldcode].first; p->suffix = (code == avail) ? p->first : g->codes[code].first; } else if (code == avail) return stbi__errpuc("illegal code in raster", "Corrupt GIF"); stbi__out_gif_code(g, (stbi__uint16) code); if ((avail & codemask) == 0 && avail <= 0x0FFF) { codesize++; codemask = (1 << codesize) - 1; } oldcode = code; } else { return stbi__errpuc("illegal code in raster", "Corrupt GIF"); } } } } // this function is designed to support animated gifs, although stb_image doesn't support it // two back is the image from two frames ago, used for a very specific disposal format static stbi_uc *stbi__gif_load_next(stbi__context *s, stbi__gif *g, int *comp, int req_comp, stbi_uc *two_back) { int dispose; int first_frame; int pi; int pcount; STBI_NOTUSED(req_comp); // on first frame, any non-written pixels get the background colour (non-transparent) first_frame = 0; if (g->out == 0) { if (!stbi__gif_header(s, g, comp,0)) return 0; // stbi__g_failure_reason set by stbi__gif_header if (!stbi__mad3sizes_valid(4, g->w, g->h, 0)) return stbi__errpuc("too large", "GIF image is too large"); pcount = g->w * g->h; g->out = (stbi_uc *) stbi__malloc(4 * pcount); g->background = (stbi_uc *) stbi__malloc(4 * pcount); g->history = (stbi_uc *) stbi__malloc(pcount); if (!g->out || !g->background || !g->history) return stbi__errpuc("outofmem", "Out of memory"); // image is treated as "transparent" at the start - ie, nothing overwrites the current background; // background colour is only used for pixels that are not rendered first frame, after that "background" // color refers to the color that was there the previous frame. memset(g->out, 0x00, 4 * pcount); memset(g->background, 0x00, 4 * pcount); // state of the background (starts transparent) memset(g->history, 0x00, pcount); // pixels that were affected previous frame first_frame = 1; } else { // second frame - how do we dispose of the previous one? dispose = (g->eflags & 0x1C) >> 2; pcount = g->w * g->h; if ((dispose == 3) && (two_back == 0)) { dispose = 2; // if I don't have an image to revert back to, default to the old background } if (dispose == 3) { // use previous graphic for (pi = 0; pi < pcount; ++pi) { if (g->history[pi]) { memcpy( &g->out[pi * 4], &two_back[pi * 4], 4 ); } } } else if (dispose == 2) { // restore what was changed last frame to background before that frame; for (pi = 0; pi < pcount; ++pi) { if (g->history[pi]) { memcpy( &g->out[pi * 4], &g->background[pi * 4], 4 ); } } } else { // This is a non-disposal case eithe way, so just // leave the pixels as is, and they will become the new background // 1: do not dispose // 0: not specified. } // background is what out is after the undoing of the previou frame; memcpy( g->background, g->out, 4 * g->w * g->h ); } // clear my history; memset( g->history, 0x00, g->w * g->h ); // pixels that were affected previous frame for (;;) { int tag = stbi__get8(s); switch (tag) { case 0x2C: /* Image Descriptor */ { stbi__int32 x, y, w, h; stbi_uc *o; x = stbi__get16le(s); y = stbi__get16le(s); w = stbi__get16le(s); h = stbi__get16le(s); if (((x + w) > (g->w)) || ((y + h) > (g->h))) return stbi__errpuc("bad Image Descriptor", "Corrupt GIF"); g->line_size = g->w * 4; g->start_x = x * 4; g->start_y = y * g->line_size; g->max_x = g->start_x + w * 4; g->max_y = g->start_y + h * g->line_size; g->cur_x = g->start_x; g->cur_y = g->start_y; // if the width of the specified rectangle is 0, that means // we may not see *any* pixels or the image is malformed; // to make sure this is caught, move the current y down to // max_y (which is what out_gif_code checks). if (w == 0) g->cur_y = g->max_y; g->lflags = stbi__get8(s); if (g->lflags & 0x40) { g->step = 8 * g->line_size; // first interlaced spacing g->parse = 3; } else { g->step = g->line_size; g->parse = 0; } if (g->lflags & 0x80) { stbi__gif_parse_colortable(s,g->lpal, 2 << (g->lflags & 7), g->eflags & 0x01 ? g->transparent : -1); g->color_table = (stbi_uc *) g->lpal; } else if (g->flags & 0x80) { g->color_table = (stbi_uc *) g->pal; } else return stbi__errpuc("missing color table", "Corrupt GIF"); o = stbi__process_gif_raster(s, g); if (!o) return NULL; // if this was the first frame, pcount = g->w * g->h; if (first_frame && (g->bgindex > 0)) { // if first frame, any pixel not drawn to gets the background color for (pi = 0; pi < pcount; ++pi) { if (g->history[pi] == 0) { g->pal[g->bgindex][3] = 255; // just in case it was made transparent, undo that; It will be reset next frame if need be; memcpy( &g->out[pi * 4], &g->pal[g->bgindex], 4 ); } } } return o; } case 0x21: // Comment Extension. { int len; int ext = stbi__get8(s); if (ext == 0xF9) { // Graphic Control Extension. len = stbi__get8(s); if (len == 4) { g->eflags = stbi__get8(s); g->delay = 10 * stbi__get16le(s); // delay - 1/100th of a second, saving as 1/1000ths. // unset old transparent if (g->transparent >= 0) { g->pal[g->transparent][3] = 255; } if (g->eflags & 0x01) { g->transparent = stbi__get8(s); if (g->transparent >= 0) { g->pal[g->transparent][3] = 0; } } else { // don't need transparent stbi__skip(s, 1); g->transparent = -1; } } else { stbi__skip(s, len); break; } } while ((len = stbi__get8(s)) != 0) { stbi__skip(s, len); } break; } case 0x3B: // gif stream termination code return (stbi_uc *) s; // using '1' causes warning on some compilers default: return stbi__errpuc("unknown code", "Corrupt GIF"); } } } static void *stbi__load_gif_main_outofmem(stbi__gif *g, stbi_uc *out, int **delays) { STBI_FREE(g->out); STBI_FREE(g->history); STBI_FREE(g->background); if (out) STBI_FREE(out); if (delays && *delays) STBI_FREE(*delays); return stbi__errpuc("outofmem", "Out of memory"); } static void *stbi__load_gif_main(stbi__context *s, int **delays, int *x, int *y, int *z, int *comp, int req_comp) { if (stbi__gif_test(s)) { int layers = 0; stbi_uc *u = 0; stbi_uc *out = 0; stbi_uc *two_back = 0; stbi__gif g; int stride; int out_size = 0; int delays_size = 0; STBI_NOTUSED(out_size); STBI_NOTUSED(delays_size); memset(&g, 0, sizeof(g)); if (delays) { *delays = 0; } do { u = stbi__gif_load_next(s, &g, comp, req_comp, two_back); if (u == (stbi_uc *) s) u = 0; // end of animated gif marker if (u) { *x = g.w; *y = g.h; ++layers; stride = g.w * g.h * 4; if (out) { void *tmp = (stbi_uc*) STBI_REALLOC_SIZED( out, out_size, layers * stride ); if (!tmp) return stbi__load_gif_main_outofmem(&g, out, delays); else { out = (stbi_uc*) tmp; out_size = layers * stride; } if (delays) { int *new_delays = (int*) STBI_REALLOC_SIZED( *delays, delays_size, sizeof(int) * layers ); if (!new_delays) return stbi__load_gif_main_outofmem(&g, out, delays); *delays = new_delays; delays_size = layers * sizeof(int); } } else { out = (stbi_uc*)stbi__malloc( layers * stride ); if (!out) return stbi__load_gif_main_outofmem(&g, out, delays); out_size = layers * stride; if (delays) { *delays = (int*) stbi__malloc( layers * sizeof(int) ); if (!*delays) return stbi__load_gif_main_outofmem(&g, out, delays); delays_size = layers * sizeof(int); } } memcpy( out + ((layers - 1) * stride), u, stride ); if (layers >= 2) { two_back = out - 2 * stride; } if (delays) { (*delays)[layers - 1U] = g.delay; } } } while (u != 0); // free temp buffer; STBI_FREE(g.out); STBI_FREE(g.history); STBI_FREE(g.background); // do the final conversion after loading everything; if (req_comp && req_comp != 4) out = stbi__convert_format(out, 4, req_comp, layers * g.w, g.h); *z = layers; return out; } else { return stbi__errpuc("not GIF", "Image was not as a gif type."); } } static void *stbi__gif_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) { stbi_uc *u = 0; stbi__gif g; memset(&g, 0, sizeof(g)); STBI_NOTUSED(ri); u = stbi__gif_load_next(s, &g, comp, req_comp, 0); if (u == (stbi_uc *) s) u = 0; // end of animated gif marker if (u) { *x = g.w; *y = g.h; // moved conversion to after successful load so that the same // can be done for multiple frames. if (req_comp && req_comp != 4) u = stbi__convert_format(u, 4, req_comp, g.w, g.h); } else if (g.out) { // if there was an error and we allocated an image buffer, free it! STBI_FREE(g.out); } // free buffers needed for multiple frame loading; STBI_FREE(g.history); STBI_FREE(g.background); return u; } static int stbi__gif_info(stbi__context *s, int *x, int *y, int *comp) { return stbi__gif_info_raw(s,x,y,comp); } #endif // ************************************************************************************************* // Radiance RGBE HDR loader // originally by Nicolas Schulz #ifndef STBI_NO_HDR static int stbi__hdr_test_core(stbi__context *s, const char *signature) { int i; for (i=0; signature[i]; ++i) if (stbi__get8(s) != signature[i]) return 0; stbi__rewind(s); return 1; } static int stbi__hdr_test(stbi__context* s) { int r = stbi__hdr_test_core(s, "#?RADIANCE\n"); stbi__rewind(s); if(!r) { r = stbi__hdr_test_core(s, "#?RGBE\n"); stbi__rewind(s); } return r; } #define STBI__HDR_BUFLEN 1024 static char *stbi__hdr_gettoken(stbi__context *z, char *buffer) { int len=0; char c = '\0'; c = (char) stbi__get8(z); while (!stbi__at_eof(z) && c != '\n') { buffer[len++] = c; if (len == STBI__HDR_BUFLEN-1) { // flush to end of line while (!stbi__at_eof(z) && stbi__get8(z) != '\n') ; break; } c = (char) stbi__get8(z); } buffer[len] = 0; return buffer; } static void stbi__hdr_convert(float *output, stbi_uc *input, int req_comp) { if ( input[3] != 0 ) { float f1; // Exponent f1 = (float) ldexp(1.0f, input[3] - (int)(128 + 8)); if (req_comp <= 2) output[0] = (input[0] + input[1] + input[2]) * f1 / 3; else { output[0] = input[0] * f1; output[1] = input[1] * f1; output[2] = input[2] * f1; } if (req_comp == 2) output[1] = 1; if (req_comp == 4) output[3] = 1; } else { switch (req_comp) { case 4: output[3] = 1; /* fallthrough */ case 3: output[0] = output[1] = output[2] = 0; break; case 2: output[1] = 1; /* fallthrough */ case 1: output[0] = 0; break; } } } static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) { char buffer[STBI__HDR_BUFLEN]; char *token; int valid = 0; int width, height; stbi_uc *scanline; float *hdr_data; int len; unsigned char count, value; int i, j, k, c1,c2, z; const char *headerToken; STBI_NOTUSED(ri); // Check identifier headerToken = stbi__hdr_gettoken(s,buffer); if (strcmp(headerToken, "#?RADIANCE") != 0 && strcmp(headerToken, "#?RGBE") != 0) return stbi__errpf("not HDR", "Corrupt HDR image"); // Parse header for(;;) { token = stbi__hdr_gettoken(s,buffer); if (token[0] == 0) break; if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1; } if (!valid) return stbi__errpf("unsupported format", "Unsupported HDR format"); // Parse width and height // can't use sscanf() if we're not using stdio! token = stbi__hdr_gettoken(s,buffer); if (strncmp(token, "-Y ", 3)) return stbi__errpf("unsupported data layout", "Unsupported HDR format"); token += 3; height = (int) strtol(token, &token, 10); while (*token == ' ') ++token; if (strncmp(token, "+X ", 3)) return stbi__errpf("unsupported data layout", "Unsupported HDR format"); token += 3; width = (int) strtol(token, NULL, 10); if (height > STBI_MAX_DIMENSIONS) return stbi__errpf("too large","Very large image (corrupt?)"); if (width > STBI_MAX_DIMENSIONS) return stbi__errpf("too large","Very large image (corrupt?)"); *x = width; *y = height; if (comp) *comp = 3; if (req_comp == 0) req_comp = 3; if (!stbi__mad4sizes_valid(width, height, req_comp, sizeof(float), 0)) return stbi__errpf("too large", "HDR image is too large"); // Read data hdr_data = (float *) stbi__malloc_mad4(width, height, req_comp, sizeof(float), 0); if (!hdr_data) return stbi__errpf("outofmem", "Out of memory"); // Load image data // image data is stored as some number of sca if ( width < 8 || width >= 32768) { // Read flat data for (j=0; j < height; ++j) { for (i=0; i < width; ++i) { stbi_uc rgbe[4]; main_decode_loop: stbi__getn(s, rgbe, 4); stbi__hdr_convert(hdr_data + j * width * req_comp + i * req_comp, rgbe, req_comp); } } } else { // Read RLE-encoded data scanline = NULL; for (j = 0; j < height; ++j) { c1 = stbi__get8(s); c2 = stbi__get8(s); len = stbi__get8(s); if (c1 != 2 || c2 != 2 || (len & 0x80)) { // not run-length encoded, so we have to actually use THIS data as a decoded // pixel (note this can't be a valid pixel--one of RGB must be >= 128) stbi_uc rgbe[4]; rgbe[0] = (stbi_uc) c1; rgbe[1] = (stbi_uc) c2; rgbe[2] = (stbi_uc) len; rgbe[3] = (stbi_uc) stbi__get8(s); stbi__hdr_convert(hdr_data, rgbe, req_comp); i = 1; j = 0; STBI_FREE(scanline); goto main_decode_loop; // yes, this makes no sense } len <<= 8; len |= stbi__get8(s); if (len != width) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("invalid decoded scanline length", "corrupt HDR"); } if (scanline == NULL) { scanline = (stbi_uc *) stbi__malloc_mad2(width, 4, 0); if (!scanline) { STBI_FREE(hdr_data); return stbi__errpf("outofmem", "Out of memory"); } } for (k = 0; k < 4; ++k) { int nleft; i = 0; while ((nleft = width - i) > 0) { count = stbi__get8(s); if (count > 128) { // Run value = stbi__get8(s); count -= 128; if ((count == 0) || (count > nleft)) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("corrupt", "bad RLE data in HDR"); } for (z = 0; z < count; ++z) scanline[i++ * 4 + k] = value; } else { // Dump if ((count == 0) || (count > nleft)) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("corrupt", "bad RLE data in HDR"); } for (z = 0; z < count; ++z) scanline[i++ * 4 + k] = stbi__get8(s); } } } for (i=0; i < width; ++i) stbi__hdr_convert(hdr_data+(j*width + i)*req_comp, scanline + i*4, req_comp); } if (scanline) STBI_FREE(scanline); } return hdr_data; } static int stbi__hdr_info(stbi__context *s, int *x, int *y, int *comp) { char buffer[STBI__HDR_BUFLEN]; char *token; int valid = 0; int dummy; if (!x) x = &dummy; if (!y) y = &dummy; if (!comp) comp = &dummy; if (stbi__hdr_test(s) == 0) { stbi__rewind( s ); return 0; } for(;;) { token = stbi__hdr_gettoken(s,buffer); if (token[0] == 0) break; if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1; } if (!valid) { stbi__rewind( s ); return 0; } token = stbi__hdr_gettoken(s,buffer); if (strncmp(token, "-Y ", 3)) { stbi__rewind( s ); return 0; } token += 3; *y = (int) strtol(token, &token, 10); while (*token == ' ') ++token; if (strncmp(token, "+X ", 3)) { stbi__rewind( s ); return 0; } token += 3; *x = (int) strtol(token, NULL, 10); *comp = 3; return 1; } #endif // STBI_NO_HDR #ifndef STBI_NO_BMP static int stbi__bmp_info(stbi__context *s, int *x, int *y, int *comp) { void *p; stbi__bmp_data info; info.all_a = 255; p = stbi__bmp_parse_header(s, &info); if (p == NULL) { stbi__rewind( s ); return 0; } if (x) *x = s->img_x; if (y) *y = s->img_y; if (comp) { if (info.bpp == 24 && info.ma == 0xff000000) *comp = 3; else *comp = info.ma ? 4 : 3; } return 1; } #endif #ifndef STBI_NO_PSD static int stbi__psd_info(stbi__context *s, int *x, int *y, int *comp) { int channelCount, dummy, depth; if (!x) x = &dummy; if (!y) y = &dummy; if (!comp) comp = &dummy; if (stbi__get32be(s) != 0x38425053) { stbi__rewind( s ); return 0; } if (stbi__get16be(s) != 1) { stbi__rewind( s ); return 0; } stbi__skip(s, 6); channelCount = stbi__get16be(s); if (channelCount < 0 || channelCount > 16) { stbi__rewind( s ); return 0; } *y = stbi__get32be(s); *x = stbi__get32be(s); depth = stbi__get16be(s); if (depth != 8 && depth != 16) { stbi__rewind( s ); return 0; } if (stbi__get16be(s) != 3) { stbi__rewind( s ); return 0; } *comp = 4; return 1; } static int stbi__psd_is16(stbi__context *s) { int channelCount, depth; if (stbi__get32be(s) != 0x38425053) { stbi__rewind( s ); return 0; } if (stbi__get16be(s) != 1) { stbi__rewind( s ); return 0; } stbi__skip(s, 6); channelCount = stbi__get16be(s); if (channelCount < 0 || channelCount > 16) { stbi__rewind( s ); return 0; } STBI_NOTUSED(stbi__get32be(s)); STBI_NOTUSED(stbi__get32be(s)); depth = stbi__get16be(s); if (depth != 16) { stbi__rewind( s ); return 0; } return 1; } #endif #ifndef STBI_NO_PIC static int stbi__pic_info(stbi__context *s, int *x, int *y, int *comp) { int act_comp=0,num_packets=0,chained,dummy; stbi__pic_packet packets[10]; if (!x) x = &dummy; if (!y) y = &dummy; if (!comp) comp = &dummy; if (!stbi__pic_is4(s,"\x53\x80\xF6\x34")) { stbi__rewind(s); return 0; } stbi__skip(s, 88); *x = stbi__get16be(s); *y = stbi__get16be(s); if (stbi__at_eof(s)) { stbi__rewind( s); return 0; } if ( (*x) != 0 && (1 << 28) / (*x) < (*y)) { stbi__rewind( s ); return 0; } stbi__skip(s, 8); do { stbi__pic_packet *packet; if (num_packets==sizeof(packets)/sizeof(packets[0])) return 0; packet = &packets[num_packets++]; chained = stbi__get8(s); packet->size = stbi__get8(s); packet->type = stbi__get8(s); packet->channel = stbi__get8(s); act_comp |= packet->channel; if (stbi__at_eof(s)) { stbi__rewind( s ); return 0; } if (packet->size != 8) { stbi__rewind( s ); return 0; } } while (chained); *comp = (act_comp & 0x10 ? 4 : 3); return 1; } #endif // ************************************************************************************************* // Portable Gray Map and Portable Pixel Map loader // by Ken Miller // // PGM: http://netpbm.sourceforge.net/doc/pgm.html // PPM: http://netpbm.sourceforge.net/doc/ppm.html // // Known limitations: // Does not support comments in the header section // Does not support ASCII image data (formats P2 and P3) #ifndef STBI_NO_PNM static int stbi__pnm_test(stbi__context *s) { char p, t; p = (char) stbi__get8(s); t = (char) stbi__get8(s); if (p != 'P' || (t != '5' && t != '6')) { stbi__rewind( s ); return 0; } return 1; } static void *stbi__pnm_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) { stbi_uc *out; STBI_NOTUSED(ri); ri->bits_per_channel = stbi__pnm_info(s, (int *)&s->img_x, (int *)&s->img_y, (int *)&s->img_n); if (ri->bits_per_channel == 0) return 0; if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); *x = s->img_x; *y = s->img_y; if (comp) *comp = s->img_n; if (!stbi__mad4sizes_valid(s->img_n, s->img_x, s->img_y, ri->bits_per_channel / 8, 0)) return stbi__errpuc("too large", "PNM too large"); out = (stbi_uc *) stbi__malloc_mad4(s->img_n, s->img_x, s->img_y, ri->bits_per_channel / 8, 0); if (!out) return stbi__errpuc("outofmem", "Out of memory"); if (!stbi__getn(s, out, s->img_n * s->img_x * s->img_y * (ri->bits_per_channel / 8))) { STBI_FREE(out); return stbi__errpuc("bad PNM", "PNM file truncated"); } if (req_comp && req_comp != s->img_n) { if (ri->bits_per_channel == 16) { out = (stbi_uc *) stbi__convert_format16((stbi__uint16 *) out, s->img_n, req_comp, s->img_x, s->img_y); } else { out = stbi__convert_format(out, s->img_n, req_comp, s->img_x, s->img_y); } if (out == NULL) return out; // stbi__convert_format frees input on failure } return out; } static int stbi__pnm_isspace(char c) { return c == ' ' || c == '\t' || c == '\n' || c == '\v' || c == '\f' || c == '\r'; } static void stbi__pnm_skip_whitespace(stbi__context *s, char *c) { for (;;) { while (!stbi__at_eof(s) && stbi__pnm_isspace(*c)) *c = (char) stbi__get8(s); if (stbi__at_eof(s) || *c != '#') break; while (!stbi__at_eof(s) && *c != '\n' && *c != '\r' ) *c = (char) stbi__get8(s); } } static int stbi__pnm_isdigit(char c) { return c >= '0' && c <= '9'; } static int stbi__pnm_getinteger(stbi__context *s, char *c) { int value = 0; while (!stbi__at_eof(s) && stbi__pnm_isdigit(*c)) { value = value*10 + (*c - '0'); *c = (char) stbi__get8(s); if((value > 214748364) || (value == 214748364 && *c > '7')) return stbi__err("integer parse overflow", "Parsing an integer in the PPM header overflowed a 32-bit int"); } return value; } static int stbi__pnm_info(stbi__context *s, int *x, int *y, int *comp) { int maxv, dummy; char c, p, t; if (!x) x = &dummy; if (!y) y = &dummy; if (!comp) comp = &dummy; stbi__rewind(s); // Get identifier p = (char) stbi__get8(s); t = (char) stbi__get8(s); if (p != 'P' || (t != '5' && t != '6')) { stbi__rewind(s); return 0; } *comp = (t == '6') ? 3 : 1; // '5' is 1-component .pgm; '6' is 3-component .ppm c = (char) stbi__get8(s); stbi__pnm_skip_whitespace(s, &c); *x = stbi__pnm_getinteger(s, &c); // read width if(*x == 0) return stbi__err("invalid width", "PPM image header had zero or overflowing width"); stbi__pnm_skip_whitespace(s, &c); *y = stbi__pnm_getinteger(s, &c); // read height if (*y == 0) return stbi__err("invalid width", "PPM image header had zero or overflowing width"); stbi__pnm_skip_whitespace(s, &c); maxv = stbi__pnm_getinteger(s, &c); // read max value if (maxv > 65535) return stbi__err("max value > 65535", "PPM image supports only 8-bit and 16-bit images"); else if (maxv > 255) return 16; else return 8; } static int stbi__pnm_is16(stbi__context *s) { if (stbi__pnm_info(s, NULL, NULL, NULL) == 16) return 1; return 0; } #endif static int stbi__info_main(stbi__context *s, int *x, int *y, int *comp) { #ifndef STBI_NO_JPEG if (stbi__jpeg_info(s, x, y, comp)) return 1; #endif #ifndef STBI_NO_PNG if (stbi__png_info(s, x, y, comp)) return 1; #endif #ifndef STBI_NO_GIF if (stbi__gif_info(s, x, y, comp)) return 1; #endif #ifndef STBI_NO_BMP if (stbi__bmp_info(s, x, y, comp)) return 1; #endif #ifndef STBI_NO_PSD if (stbi__psd_info(s, x, y, comp)) return 1; #endif #ifndef STBI_NO_PIC if (stbi__pic_info(s, x, y, comp)) return 1; #endif #ifndef STBI_NO_PNM if (stbi__pnm_info(s, x, y, comp)) return 1; #endif #ifndef STBI_NO_HDR if (stbi__hdr_info(s, x, y, comp)) return 1; #endif // test tga last because it's a crappy test! #ifndef STBI_NO_TGA if (stbi__tga_info(s, x, y, comp)) return 1; #endif return stbi__err("unknown image type", "Image not of any known type, or corrupt"); } static int stbi__is_16_main(stbi__context *s) { #ifndef STBI_NO_PNG if (stbi__png_is16(s)) return 1; #endif #ifndef STBI_NO_PSD if (stbi__psd_is16(s)) return 1; #endif #ifndef STBI_NO_PNM if (stbi__pnm_is16(s)) return 1; #endif return 0; } #ifndef STBI_NO_STDIO STBIDEF int stbi_info(char const *filename, int *x, int *y, int *comp) { FILE *f = stbi__fopen(filename, "rb"); int result; if (!f) return stbi__err("can't fopen", "Unable to open file"); result = stbi_info_from_file(f, x, y, comp); fclose(f); return result; } STBIDEF int stbi_info_from_file(FILE *f, int *x, int *y, int *comp) { int r; stbi__context s; long pos = ftell(f); stbi__start_file(&s, f); r = stbi__info_main(&s,x,y,comp); fseek(f,pos,SEEK_SET); return r; } STBIDEF int stbi_is_16_bit(char const *filename) { FILE *f = stbi__fopen(filename, "rb"); int result; if (!f) return stbi__err("can't fopen", "Unable to open file"); result = stbi_is_16_bit_from_file(f); fclose(f); return result; } STBIDEF int stbi_is_16_bit_from_file(FILE *f) { int r; stbi__context s; long pos = ftell(f); stbi__start_file(&s, f); r = stbi__is_16_main(&s); fseek(f,pos,SEEK_SET); return r; } #endif // !STBI_NO_STDIO STBIDEF int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp) { stbi__context s; stbi__start_mem(&s,buffer,len); return stbi__info_main(&s,x,y,comp); } STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const *c, void *user, int *x, int *y, int *comp) { stbi__context s; stbi__start_callbacks(&s, (stbi_io_callbacks *) c, user); return stbi__info_main(&s,x,y,comp); } STBIDEF int stbi_is_16_bit_from_memory(stbi_uc const *buffer, int len) { stbi__context s; stbi__start_mem(&s,buffer,len); return stbi__is_16_main(&s); } STBIDEF int stbi_is_16_bit_from_callbacks(stbi_io_callbacks const *c, void *user) { stbi__context s; stbi__start_callbacks(&s, (stbi_io_callbacks *) c, user); return stbi__is_16_main(&s); } #endif // STB_IMAGE_IMPLEMENTATION /* revision history: 2.20 (2019-02-07) support utf8 filenames in Windows; fix warnings and platform ifdefs 2.19 (2018-02-11) fix warning 2.18 (2018-01-30) fix warnings 2.17 (2018-01-29) change sbti__shiftsigned to avoid clang -O2 bug 1-bit BMP *_is_16_bit api avoid warnings 2.16 (2017-07-23) all functions have 16-bit variants; STBI_NO_STDIO works again; compilation fixes; fix rounding in unpremultiply; optimize vertical flip; disable raw_len validation; documentation fixes 2.15 (2017-03-18) fix png-1,2,4 bug; now all Imagenet JPGs decode; warning fixes; disable run-time SSE detection on gcc; uniform handling of optional "return" values; thread-safe initialization of zlib tables 2.14 (2017-03-03) remove deprecated STBI_JPEG_OLD; fixes for Imagenet JPGs 2.13 (2016-11-29) add 16-bit API, only supported for PNG right now 2.12 (2016-04-02) fix typo in 2.11 PSD fix that caused crashes 2.11 (2016-04-02) allocate large structures on the stack remove white matting for transparent PSD fix reported channel count for PNG & BMP re-enable SSE2 in non-gcc 64-bit support RGB-formatted JPEG read 16-bit PNGs (only as 8-bit) 2.10 (2016-01-22) avoid warning introduced in 2.09 by STBI_REALLOC_SIZED 2.09 (2016-01-16) allow comments in PNM files 16-bit-per-pixel TGA (not bit-per-component) info() for TGA could break due to .hdr handling info() for BMP to shares code instead of sloppy parse can use STBI_REALLOC_SIZED if allocator doesn't support realloc code cleanup 2.08 (2015-09-13) fix to 2.07 cleanup, reading RGB PSD as RGBA 2.07 (2015-09-13) fix compiler warnings partial animated GIF support limited 16-bpc PSD support #ifdef unused functions bug with < 92 byte PIC,PNM,HDR,TGA 2.06 (2015-04-19) fix bug where PSD returns wrong '*comp' value 2.05 (2015-04-19) fix bug in progressive JPEG handling, fix warning 2.04 (2015-04-15) try to re-enable SIMD on MinGW 64-bit 2.03 (2015-04-12) extra corruption checking (mmozeiko) stbi_set_flip_vertically_on_load (nguillemot) fix NEON support; fix mingw support 2.02 (2015-01-19) fix incorrect assert, fix warning 2.01 (2015-01-17) fix various warnings; suppress SIMD on gcc 32-bit without -msse2 2.00b (2014-12-25) fix STBI_MALLOC in progressive JPEG 2.00 (2014-12-25) optimize JPG, including x86 SSE2 & NEON SIMD (ryg) progressive JPEG (stb) PGM/PPM support (Ken Miller) STBI_MALLOC,STBI_REALLOC,STBI_FREE GIF bugfix -- seemingly never worked STBI_NO_*, STBI_ONLY_* 1.48 (2014-12-14) fix incorrectly-named assert() 1.47 (2014-12-14) 1/2/4-bit PNG support, both direct and paletted (Omar Cornut & stb) optimize PNG (ryg) fix bug in interlaced PNG with user-specified channel count (stb) 1.46 (2014-08-26) fix broken tRNS chunk (colorkey-style transparency) in non-paletted PNG 1.45 (2014-08-16) fix MSVC-ARM internal compiler error by wrapping malloc 1.44 (2014-08-07) various warning fixes from Ronny Chevalier 1.43 (2014-07-15) fix MSVC-only compiler problem in code changed in 1.42 1.42 (2014-07-09) don't define _CRT_SECURE_NO_WARNINGS (affects user code) fixes to stbi__cleanup_jpeg path added STBI_ASSERT to avoid requiring assert.h 1.41 (2014-06-25) fix search&replace from 1.36 that messed up comments/error messages 1.40 (2014-06-22) fix gcc struct-initialization warning 1.39 (2014-06-15) fix to TGA optimization when req_comp != number of components in TGA; fix to GIF loading because BMP wasn't rewinding (whoops, no GIFs in my test suite) add support for BMP version 5 (more ignored fields) 1.38 (2014-06-06) suppress MSVC warnings on integer casts truncating values fix accidental rename of 'skip' field of I/O 1.37 (2014-06-04) remove duplicate typedef 1.36 (2014-06-03) convert to header file single-file library if de-iphone isn't set, load iphone images color-swapped instead of returning NULL 1.35 (2014-05-27) various warnings fix broken STBI_SIMD path fix bug where stbi_load_from_file no longer left file pointer in correct place fix broken non-easy path for 32-bit BMP (possibly never used) TGA optimization by Arseny Kapoulkine 1.34 (unknown) use STBI_NOTUSED in stbi__resample_row_generic(), fix one more leak in tga failure case 1.33 (2011-07-14) make stbi_is_hdr work in STBI_NO_HDR (as specified), minor compiler-friendly improvements 1.32 (2011-07-13) support for "info" function for all supported filetypes (SpartanJ) 1.31 (2011-06-20) a few more leak fixes, bug in PNG handling (SpartanJ) 1.30 (2011-06-11) added ability to load files via callbacks to accomidate custom input streams (Ben Wenger) removed deprecated format-specific test/load functions removed support for installable file formats (stbi_loader) -- would have been broken for IO callbacks anyway error cases in bmp and tga give messages and don't leak (Raymond Barbiero, grisha) fix inefficiency in decoding 32-bit BMP (David Woo) 1.29 (2010-08-16) various warning fixes from Aurelien Pocheville 1.28 (2010-08-01) fix bug in GIF palette transparency (SpartanJ) 1.27 (2010-08-01) cast-to-stbi_uc to fix warnings 1.26 (2010-07-24) fix bug in file buffering for PNG reported by SpartanJ 1.25 (2010-07-17) refix trans_data warning (Won Chun) 1.24 (2010-07-12) perf improvements reading from files on platforms with lock-heavy fgetc() minor perf improvements for jpeg deprecated type-specific functions so we'll get feedback if they're needed attempt to fix trans_data warning (Won Chun) 1.23 fixed bug in iPhone support 1.22 (2010-07-10) removed image *writing* support stbi_info support from Jetro Lauha GIF support from Jean-Marc Lienher iPhone PNG-extensions from James Brown warning-fixes from Nicolas Schulz and Janez Zemva (i.stbi__err. Janez (U+017D)emva) 1.21 fix use of 'stbi_uc' in header (reported by jon blow) 1.20 added support for Softimage PIC, by Tom Seddon 1.19 bug in interlaced PNG corruption check (found by ryg) 1.18 (2008-08-02) fix a threading bug (local mutable static) 1.17 support interlaced PNG 1.16 major bugfix - stbi__convert_format converted one too many pixels 1.15 initialize some fields for thread safety 1.14 fix threadsafe conversion bug header-file-only version (#define STBI_HEADER_FILE_ONLY before including) 1.13 threadsafe 1.12 const qualifiers in the API 1.11 Support installable IDCT, colorspace conversion routines 1.10 Fixes for 64-bit (don't use "unsigned long") optimized upsampling by Fabian "ryg" Giesen 1.09 Fix format-conversion for PSD code (bad global variables!) 1.08 Thatcher Ulrich's PSD code integrated by Nicolas Schulz 1.07 attempt to fix C++ warning/errors again 1.06 attempt to fix C++ warning/errors again 1.05 fix TGA loading to return correct *comp and use good luminance calc 1.04 default float alpha is 1, not 255; use 'void *' for stbi_image_free 1.03 bugfixes to STBI_NO_STDIO, STBI_NO_HDR 1.02 support for (subset of) HDR files, float interface for preferred access to them 1.01 fix bug: possible bug in handling right-side up bmps... not sure fix bug: the stbi__bmp_load() and stbi__tga_load() functions didn't work at all 1.00 interface to zlib that skips zlib header 0.99 correct handling of alpha in palette 0.98 TGA loader by lonesock; dynamically add loaders (untested) 0.97 jpeg errors on too large a file; also catch another malloc failure 0.96 fix detection of invalid v value - particleman@mollyrocket forum 0.95 during header scan, seek to markers in case of padding 0.94 STBI_NO_STDIO to disable stdio usage; rename all #defines the same 0.93 handle jpegtran output; verbose errors 0.92 read 4,8,16,24,32-bit BMP files of several formats 0.91 output 24-bit Windows 3.0 BMP files 0.90 fix a few more warnings; bump version number to approach 1.0 0.61 bugfixes due to Marc LeBlanc, Christopher Lloyd 0.60 fix compiling as c++ 0.59 fix warnings: merge Dave Moore's -Wall fixes 0.58 fix bug: zlib uncompressed mode len/nlen was wrong endian 0.57 fix bug: jpg last huffman symbol before marker was >9 bits but less than 16 available 0.56 fix bug: zlib uncompressed mode len vs. nlen 0.55 fix bug: restart_interval not initialized to 0 0.54 allow NULL for 'int *comp' 0.53 fix bug in png 3->4; speedup png decoding 0.52 png handles req_comp=3,4 directly; minor cleanup; jpeg comments 0.51 obey req_comp requests, 1-component jpegs return as 1-component, on 'test' only check type, not whether we support this variant 0.50 (2006-11-19) first released version */ /* ------------------------------------------------------------------------------ This software is available under 2 licenses -- choose whichever you prefer. ------------------------------------------------------------------------------ ALTERNATIVE A - MIT License Copyright (c) 2017 Sean Barrett Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------ ALTERNATIVE B - Public Domain (www.unlicense.org) This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------ */
0
repos/simulations/libs/zstbi/libs
repos/simulations/libs/zstbi/libs/stbi/stb_image_write.h
/* stb_image_write - v1.16 - public domain - http://nothings.org/stb writes out PNG/BMP/TGA/JPEG/HDR images to C stdio - Sean Barrett 2010-2015 no warranty implied; use at your own risk Before #including, #define STB_IMAGE_WRITE_IMPLEMENTATION in the file that you want to have the implementation. Will probably not work correctly with strict-aliasing optimizations. ABOUT: This header file is a library for writing images to C stdio or a callback. The PNG output is not optimal; it is 20-50% larger than the file written by a decent optimizing implementation; though providing a custom zlib compress function (see STBIW_ZLIB_COMPRESS) can mitigate that. This library is designed for source code compactness and simplicity, not optimal image file size or run-time performance. BUILDING: You can #define STBIW_ASSERT(x) before the #include to avoid using assert.h. You can #define STBIW_MALLOC(), STBIW_REALLOC(), and STBIW_FREE() to replace malloc,realloc,free. You can #define STBIW_MEMMOVE() to replace memmove() You can #define STBIW_ZLIB_COMPRESS to use a custom zlib-style compress function for PNG compression (instead of the builtin one), it must have the following signature: unsigned char * my_compress(unsigned char *data, int data_len, int *out_len, int quality); The returned data will be freed with STBIW_FREE() (free() by default), so it must be heap allocated with STBIW_MALLOC() (malloc() by default), UNICODE: If compiling for Windows and you wish to use Unicode filenames, compile with #define STBIW_WINDOWS_UTF8 and pass utf8-encoded filenames. Call stbiw_convert_wchar_to_utf8 to convert Windows wchar_t filenames to utf8. USAGE: There are five functions, one for each image file format: int stbi_write_png(char const *filename, int w, int h, int comp, const void *data, int stride_in_bytes); int stbi_write_bmp(char const *filename, int w, int h, int comp, const void *data); int stbi_write_tga(char const *filename, int w, int h, int comp, const void *data); int stbi_write_jpg(char const *filename, int w, int h, int comp, const void *data, int quality); int stbi_write_hdr(char const *filename, int w, int h, int comp, const float *data); void stbi_flip_vertically_on_write(int flag); // flag is non-zero to flip data vertically There are also five equivalent functions that use an arbitrary write function. You are expected to open/close your file-equivalent before and after calling these: int stbi_write_png_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data, int stride_in_bytes); int stbi_write_bmp_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data); int stbi_write_tga_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data); int stbi_write_hdr_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const float *data); int stbi_write_jpg_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data, int quality); where the callback is: void stbi_write_func(void *context, void *data, int size); You can configure it with these global variables: int stbi_write_tga_with_rle; // defaults to true; set to 0 to disable RLE int stbi_write_png_compression_level; // defaults to 8; set to higher for more compression int stbi_write_force_png_filter; // defaults to -1; set to 0..5 to force a filter mode You can define STBI_WRITE_NO_STDIO to disable the file variant of these functions, so the library will not use stdio.h at all. However, this will also disable HDR writing, because it requires stdio for formatted output. Each function returns 0 on failure and non-0 on success. The functions create an image file defined by the parameters. The image is a rectangle of pixels stored from left-to-right, top-to-bottom. Each pixel contains 'comp' channels of data stored interleaved with 8-bits per channel, in the following order: 1=Y, 2=YA, 3=RGB, 4=RGBA. (Y is monochrome color.) The rectangle is 'w' pixels wide and 'h' pixels tall. The *data pointer points to the first byte of the top-left-most pixel. For PNG, "stride_in_bytes" is the distance in bytes from the first byte of a row of pixels to the first byte of the next row of pixels. PNG creates output files with the same number of components as the input. The BMP format expands Y to RGB in the file format and does not output alpha. PNG supports writing rectangles of data even when the bytes storing rows of data are not consecutive in memory (e.g. sub-rectangles of a larger image), by supplying the stride between the beginning of adjacent rows. The other formats do not. (Thus you cannot write a native-format BMP through the BMP writer, both because it is in BGR order and because it may have padding at the end of the line.) PNG allows you to set the deflate compression level by setting the global variable 'stbi_write_png_compression_level' (it defaults to 8). HDR expects linear float data. Since the format is always 32-bit rgb(e) data, alpha (if provided) is discarded, and for monochrome data it is replicated across all three channels. TGA supports RLE or non-RLE compressed data. To use non-RLE-compressed data, set the global variable 'stbi_write_tga_with_rle' to 0. JPEG does ignore alpha channels in input data; quality is between 1 and 100. Higher quality looks better but results in a bigger image. JPEG baseline (no JPEG progressive). CREDITS: Sean Barrett - PNG/BMP/TGA Baldur Karlsson - HDR Jean-Sebastien Guay - TGA monochrome Tim Kelsey - misc enhancements Alan Hickman - TGA RLE Emmanuel Julien - initial file IO callback implementation Jon Olick - original jo_jpeg.cpp code Daniel Gibson - integrate JPEG, allow external zlib Aarni Koskela - allow choosing PNG filter bugfixes: github:Chribba Guillaume Chereau github:jry2 github:romigrou Sergio Gonzalez Jonas Karlsson Filip Wasil Thatcher Ulrich github:poppolopoppo Patrick Boettcher github:xeekworx Cap Petschulat Simon Rodriguez Ivan Tikhonov github:ignotion Adam Schackart Andrew Kensler LICENSE See end of file for license information. */ #ifndef INCLUDE_STB_IMAGE_WRITE_H #define INCLUDE_STB_IMAGE_WRITE_H #include <stdlib.h> // if STB_IMAGE_WRITE_STATIC causes problems, try defining STBIWDEF to 'inline' or 'static inline' #ifndef STBIWDEF #ifdef STB_IMAGE_WRITE_STATIC #define STBIWDEF static #else #ifdef __cplusplus #define STBIWDEF extern "C" #else #define STBIWDEF extern #endif #endif #endif #ifndef STB_IMAGE_WRITE_STATIC // C++ forbids static forward declarations STBIWDEF int stbi_write_tga_with_rle; STBIWDEF int stbi_write_png_compression_level; STBIWDEF int stbi_write_force_png_filter; #endif #ifndef STBI_WRITE_NO_STDIO STBIWDEF int stbi_write_png(char const *filename, int w, int h, int comp, const void *data, int stride_in_bytes); STBIWDEF int stbi_write_bmp(char const *filename, int w, int h, int comp, const void *data); STBIWDEF int stbi_write_tga(char const *filename, int w, int h, int comp, const void *data); STBIWDEF int stbi_write_hdr(char const *filename, int w, int h, int comp, const float *data); STBIWDEF int stbi_write_jpg(char const *filename, int x, int y, int comp, const void *data, int quality); #ifdef STBIW_WINDOWS_UTF8 STBIWDEF int stbiw_convert_wchar_to_utf8(char *buffer, size_t bufferlen, const wchar_t* input); #endif #endif typedef void stbi_write_func(void *context, void *data, int size); STBIWDEF int stbi_write_png_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data, int stride_in_bytes); STBIWDEF int stbi_write_bmp_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data); STBIWDEF int stbi_write_tga_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data); STBIWDEF int stbi_write_hdr_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const float *data); STBIWDEF int stbi_write_jpg_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data, int quality); STBIWDEF void stbi_flip_vertically_on_write(int flip_boolean); #endif//INCLUDE_STB_IMAGE_WRITE_H #ifdef STB_IMAGE_WRITE_IMPLEMENTATION #ifdef _WIN32 #ifndef _CRT_SECURE_NO_WARNINGS #define _CRT_SECURE_NO_WARNINGS #endif #ifndef _CRT_NONSTDC_NO_DEPRECATE #define _CRT_NONSTDC_NO_DEPRECATE #endif #endif #ifndef STBI_WRITE_NO_STDIO #include <stdio.h> #endif // STBI_WRITE_NO_STDIO #include <stdarg.h> #include <stdlib.h> #include <string.h> #include <math.h> #if defined(STBIW_MALLOC) && defined(STBIW_FREE) && (defined(STBIW_REALLOC) || defined(STBIW_REALLOC_SIZED)) // ok #elif !defined(STBIW_MALLOC) && !defined(STBIW_FREE) && !defined(STBIW_REALLOC) && !defined(STBIW_REALLOC_SIZED) // ok #else #error "Must define all or none of STBIW_MALLOC, STBIW_FREE, and STBIW_REALLOC (or STBIW_REALLOC_SIZED)." #endif #ifndef STBIW_MALLOC #define STBIW_MALLOC(sz) malloc(sz) #define STBIW_REALLOC(p,newsz) realloc(p,newsz) #define STBIW_FREE(p) free(p) #endif #ifndef STBIW_REALLOC_SIZED #define STBIW_REALLOC_SIZED(p,oldsz,newsz) STBIW_REALLOC(p,newsz) #endif #ifndef STBIW_MEMMOVE #define STBIW_MEMMOVE(a,b,sz) memmove(a,b,sz) #endif #ifndef STBIW_ASSERT #include <assert.h> #define STBIW_ASSERT(x) assert(x) #endif #define STBIW_UCHAR(x) (unsigned char) ((x) & 0xff) #ifdef STB_IMAGE_WRITE_STATIC static int stbi_write_png_compression_level = 8; static int stbi_write_tga_with_rle = 1; static int stbi_write_force_png_filter = -1; #else int stbi_write_png_compression_level = 8; int stbi_write_tga_with_rle = 1; int stbi_write_force_png_filter = -1; #endif static int stbi__flip_vertically_on_write = 0; STBIWDEF void stbi_flip_vertically_on_write(int flag) { stbi__flip_vertically_on_write = flag; } typedef struct { stbi_write_func *func; void *context; unsigned char buffer[64]; int buf_used; } stbi__write_context; // initialize a callback-based context static void stbi__start_write_callbacks(stbi__write_context *s, stbi_write_func *c, void *context) { s->func = c; s->context = context; } #ifndef STBI_WRITE_NO_STDIO static void stbi__stdio_write(void *context, void *data, int size) { fwrite(data,1,size,(FILE*) context); } #if defined(_WIN32) && defined(STBIW_WINDOWS_UTF8) #ifdef __cplusplus #define STBIW_EXTERN extern "C" #else #define STBIW_EXTERN extern #endif STBIW_EXTERN __declspec(dllimport) int __stdcall MultiByteToWideChar(unsigned int cp, unsigned long flags, const char *str, int cbmb, wchar_t *widestr, int cchwide); STBIW_EXTERN __declspec(dllimport) int __stdcall WideCharToMultiByte(unsigned int cp, unsigned long flags, const wchar_t *widestr, int cchwide, char *str, int cbmb, const char *defchar, int *used_default); STBIWDEF int stbiw_convert_wchar_to_utf8(char *buffer, size_t bufferlen, const wchar_t* input) { return WideCharToMultiByte(65001 /* UTF8 */, 0, input, -1, buffer, (int) bufferlen, NULL, NULL); } #endif static FILE *stbiw__fopen(char const *filename, char const *mode) { FILE *f; #if defined(_WIN32) && defined(STBIW_WINDOWS_UTF8) wchar_t wMode[64]; wchar_t wFilename[1024]; if (0 == MultiByteToWideChar(65001 /* UTF8 */, 0, filename, -1, wFilename, sizeof(wFilename)/sizeof(*wFilename))) return 0; if (0 == MultiByteToWideChar(65001 /* UTF8 */, 0, mode, -1, wMode, sizeof(wMode)/sizeof(*wMode))) return 0; #if defined(_MSC_VER) && _MSC_VER >= 1400 if (0 != _wfopen_s(&f, wFilename, wMode)) f = 0; #else f = _wfopen(wFilename, wMode); #endif #elif defined(_MSC_VER) && _MSC_VER >= 1400 if (0 != fopen_s(&f, filename, mode)) f=0; #else f = fopen(filename, mode); #endif return f; } static int stbi__start_write_file(stbi__write_context *s, const char *filename) { FILE *f = stbiw__fopen(filename, "wb"); stbi__start_write_callbacks(s, stbi__stdio_write, (void *) f); return f != NULL; } static void stbi__end_write_file(stbi__write_context *s) { fclose((FILE *)s->context); } #endif // !STBI_WRITE_NO_STDIO typedef unsigned int stbiw_uint32; typedef int stb_image_write_test[sizeof(stbiw_uint32)==4 ? 1 : -1]; static void stbiw__writefv(stbi__write_context *s, const char *fmt, va_list v) { while (*fmt) { switch (*fmt++) { case ' ': break; case '1': { unsigned char x = STBIW_UCHAR(va_arg(v, int)); s->func(s->context,&x,1); break; } case '2': { int x = va_arg(v,int); unsigned char b[2]; b[0] = STBIW_UCHAR(x); b[1] = STBIW_UCHAR(x>>8); s->func(s->context,b,2); break; } case '4': { stbiw_uint32 x = va_arg(v,int); unsigned char b[4]; b[0]=STBIW_UCHAR(x); b[1]=STBIW_UCHAR(x>>8); b[2]=STBIW_UCHAR(x>>16); b[3]=STBIW_UCHAR(x>>24); s->func(s->context,b,4); break; } default: STBIW_ASSERT(0); return; } } } static void stbiw__writef(stbi__write_context *s, const char *fmt, ...) { va_list v; va_start(v, fmt); stbiw__writefv(s, fmt, v); va_end(v); } static void stbiw__write_flush(stbi__write_context *s) { if (s->buf_used) { s->func(s->context, &s->buffer, s->buf_used); s->buf_used = 0; } } static void stbiw__putc(stbi__write_context *s, unsigned char c) { s->func(s->context, &c, 1); } static void stbiw__write1(stbi__write_context *s, unsigned char a) { if ((size_t)s->buf_used + 1 > sizeof(s->buffer)) stbiw__write_flush(s); s->buffer[s->buf_used++] = a; } static void stbiw__write3(stbi__write_context *s, unsigned char a, unsigned char b, unsigned char c) { int n; if ((size_t)s->buf_used + 3 > sizeof(s->buffer)) stbiw__write_flush(s); n = s->buf_used; s->buf_used = n+3; s->buffer[n+0] = a; s->buffer[n+1] = b; s->buffer[n+2] = c; } static void stbiw__write_pixel(stbi__write_context *s, int rgb_dir, int comp, int write_alpha, int expand_mono, unsigned char *d) { unsigned char bg[3] = { 255, 0, 255}, px[3]; int k; if (write_alpha < 0) stbiw__write1(s, d[comp - 1]); switch (comp) { case 2: // 2 pixels = mono + alpha, alpha is written separately, so same as 1-channel case case 1: if (expand_mono) stbiw__write3(s, d[0], d[0], d[0]); // monochrome bmp else stbiw__write1(s, d[0]); // monochrome TGA break; case 4: if (!write_alpha) { // composite against pink background for (k = 0; k < 3; ++k) px[k] = bg[k] + ((d[k] - bg[k]) * d[3]) / 255; stbiw__write3(s, px[1 - rgb_dir], px[1], px[1 + rgb_dir]); break; } /* FALLTHROUGH */ case 3: stbiw__write3(s, d[1 - rgb_dir], d[1], d[1 + rgb_dir]); break; } if (write_alpha > 0) stbiw__write1(s, d[comp - 1]); } static void stbiw__write_pixels(stbi__write_context *s, int rgb_dir, int vdir, int x, int y, int comp, void *data, int write_alpha, int scanline_pad, int expand_mono) { stbiw_uint32 zero = 0; int i,j, j_end; if (y <= 0) return; if (stbi__flip_vertically_on_write) vdir *= -1; if (vdir < 0) { j_end = -1; j = y-1; } else { j_end = y; j = 0; } for (; j != j_end; j += vdir) { for (i=0; i < x; ++i) { unsigned char *d = (unsigned char *) data + (j*x+i)*comp; stbiw__write_pixel(s, rgb_dir, comp, write_alpha, expand_mono, d); } stbiw__write_flush(s); s->func(s->context, &zero, scanline_pad); } } static int stbiw__outfile(stbi__write_context *s, int rgb_dir, int vdir, int x, int y, int comp, int expand_mono, void *data, int alpha, int pad, const char *fmt, ...) { if (y < 0 || x < 0) { return 0; } else { va_list v; va_start(v, fmt); stbiw__writefv(s, fmt, v); va_end(v); stbiw__write_pixels(s,rgb_dir,vdir,x,y,comp,data,alpha,pad, expand_mono); return 1; } } static int stbi_write_bmp_core(stbi__write_context *s, int x, int y, int comp, const void *data) { if (comp != 4) { // write RGB bitmap int pad = (-x*3) & 3; return stbiw__outfile(s,-1,-1,x,y,comp,1,(void *) data,0,pad, "11 4 22 4" "4 44 22 444444", 'B', 'M', 14+40+(x*3+pad)*y, 0,0, 14+40, // file header 40, x,y, 1,24, 0,0,0,0,0,0); // bitmap header } else { // RGBA bitmaps need a v4 header // use BI_BITFIELDS mode with 32bpp and alpha mask // (straight BI_RGB with alpha mask doesn't work in most readers) return stbiw__outfile(s,-1,-1,x,y,comp,1,(void *)data,1,0, "11 4 22 4" "4 44 22 444444 4444 4 444 444 444 444", 'B', 'M', 14+108+x*y*4, 0, 0, 14+108, // file header 108, x,y, 1,32, 3,0,0,0,0,0, 0xff0000,0xff00,0xff,0xff000000u, 0, 0,0,0, 0,0,0, 0,0,0, 0,0,0); // bitmap V4 header } } STBIWDEF int stbi_write_bmp_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data) { stbi__write_context s = { 0 }; stbi__start_write_callbacks(&s, func, context); return stbi_write_bmp_core(&s, x, y, comp, data); } #ifndef STBI_WRITE_NO_STDIO STBIWDEF int stbi_write_bmp(char const *filename, int x, int y, int comp, const void *data) { stbi__write_context s = { 0 }; if (stbi__start_write_file(&s,filename)) { int r = stbi_write_bmp_core(&s, x, y, comp, data); stbi__end_write_file(&s); return r; } else return 0; } #endif //!STBI_WRITE_NO_STDIO static int stbi_write_tga_core(stbi__write_context *s, int x, int y, int comp, void *data) { int has_alpha = (comp == 2 || comp == 4); int colorbytes = has_alpha ? comp-1 : comp; int format = colorbytes < 2 ? 3 : 2; // 3 color channels (RGB/RGBA) = 2, 1 color channel (Y/YA) = 3 if (y < 0 || x < 0) return 0; if (!stbi_write_tga_with_rle) { return stbiw__outfile(s, -1, -1, x, y, comp, 0, (void *) data, has_alpha, 0, "111 221 2222 11", 0, 0, format, 0, 0, 0, 0, 0, x, y, (colorbytes + has_alpha) * 8, has_alpha * 8); } else { int i,j,k; int jend, jdir; stbiw__writef(s, "111 221 2222 11", 0,0,format+8, 0,0,0, 0,0,x,y, (colorbytes + has_alpha) * 8, has_alpha * 8); if (stbi__flip_vertically_on_write) { j = 0; jend = y; jdir = 1; } else { j = y-1; jend = -1; jdir = -1; } for (; j != jend; j += jdir) { unsigned char *row = (unsigned char *) data + j * x * comp; int len; for (i = 0; i < x; i += len) { unsigned char *begin = row + i * comp; int diff = 1; len = 1; if (i < x - 1) { ++len; diff = memcmp(begin, row + (i + 1) * comp, comp); if (diff) { const unsigned char *prev = begin; for (k = i + 2; k < x && len < 128; ++k) { if (memcmp(prev, row + k * comp, comp)) { prev += comp; ++len; } else { --len; break; } } } else { for (k = i + 2; k < x && len < 128; ++k) { if (!memcmp(begin, row + k * comp, comp)) { ++len; } else { break; } } } } if (diff) { unsigned char header = STBIW_UCHAR(len - 1); stbiw__write1(s, header); for (k = 0; k < len; ++k) { stbiw__write_pixel(s, -1, comp, has_alpha, 0, begin + k * comp); } } else { unsigned char header = STBIW_UCHAR(len - 129); stbiw__write1(s, header); stbiw__write_pixel(s, -1, comp, has_alpha, 0, begin); } } } stbiw__write_flush(s); } return 1; } STBIWDEF int stbi_write_tga_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data) { stbi__write_context s = { 0 }; stbi__start_write_callbacks(&s, func, context); return stbi_write_tga_core(&s, x, y, comp, (void *) data); } #ifndef STBI_WRITE_NO_STDIO STBIWDEF int stbi_write_tga(char const *filename, int x, int y, int comp, const void *data) { stbi__write_context s = { 0 }; if (stbi__start_write_file(&s,filename)) { int r = stbi_write_tga_core(&s, x, y, comp, (void *) data); stbi__end_write_file(&s); return r; } else return 0; } #endif // ************************************************************************************************* // Radiance RGBE HDR writer // by Baldur Karlsson #define stbiw__max(a, b) ((a) > (b) ? (a) : (b)) #ifndef STBI_WRITE_NO_STDIO static void stbiw__linear_to_rgbe(unsigned char *rgbe, float *linear) { int exponent; float maxcomp = stbiw__max(linear[0], stbiw__max(linear[1], linear[2])); if (maxcomp < 1e-32f) { rgbe[0] = rgbe[1] = rgbe[2] = rgbe[3] = 0; } else { float normalize = (float) frexp(maxcomp, &exponent) * 256.0f/maxcomp; rgbe[0] = (unsigned char)(linear[0] * normalize); rgbe[1] = (unsigned char)(linear[1] * normalize); rgbe[2] = (unsigned char)(linear[2] * normalize); rgbe[3] = (unsigned char)(exponent + 128); } } static void stbiw__write_run_data(stbi__write_context *s, int length, unsigned char databyte) { unsigned char lengthbyte = STBIW_UCHAR(length+128); STBIW_ASSERT(length+128 <= 255); s->func(s->context, &lengthbyte, 1); s->func(s->context, &databyte, 1); } static void stbiw__write_dump_data(stbi__write_context *s, int length, unsigned char *data) { unsigned char lengthbyte = STBIW_UCHAR(length); STBIW_ASSERT(length <= 128); // inconsistent with spec but consistent with official code s->func(s->context, &lengthbyte, 1); s->func(s->context, data, length); } static void stbiw__write_hdr_scanline(stbi__write_context *s, int width, int ncomp, unsigned char *scratch, float *scanline) { unsigned char scanlineheader[4] = { 2, 2, 0, 0 }; unsigned char rgbe[4]; float linear[3]; int x; scanlineheader[2] = (width&0xff00)>>8; scanlineheader[3] = (width&0x00ff); /* skip RLE for images too small or large */ if (width < 8 || width >= 32768) { for (x=0; x < width; x++) { switch (ncomp) { case 4: /* fallthrough */ case 3: linear[2] = scanline[x*ncomp + 2]; linear[1] = scanline[x*ncomp + 1]; linear[0] = scanline[x*ncomp + 0]; break; default: linear[0] = linear[1] = linear[2] = scanline[x*ncomp + 0]; break; } stbiw__linear_to_rgbe(rgbe, linear); s->func(s->context, rgbe, 4); } } else { int c,r; /* encode into scratch buffer */ for (x=0; x < width; x++) { switch(ncomp) { case 4: /* fallthrough */ case 3: linear[2] = scanline[x*ncomp + 2]; linear[1] = scanline[x*ncomp + 1]; linear[0] = scanline[x*ncomp + 0]; break; default: linear[0] = linear[1] = linear[2] = scanline[x*ncomp + 0]; break; } stbiw__linear_to_rgbe(rgbe, linear); scratch[x + width*0] = rgbe[0]; scratch[x + width*1] = rgbe[1]; scratch[x + width*2] = rgbe[2]; scratch[x + width*3] = rgbe[3]; } s->func(s->context, scanlineheader, 4); /* RLE each component separately */ for (c=0; c < 4; c++) { unsigned char *comp = &scratch[width*c]; x = 0; while (x < width) { // find first run r = x; while (r+2 < width) { if (comp[r] == comp[r+1] && comp[r] == comp[r+2]) break; ++r; } if (r+2 >= width) r = width; // dump up to first run while (x < r) { int len = r-x; if (len > 128) len = 128; stbiw__write_dump_data(s, len, &comp[x]); x += len; } // if there's a run, output it if (r+2 < width) { // same test as what we break out of in search loop, so only true if we break'd // find next byte after run while (r < width && comp[r] == comp[x]) ++r; // output run up to r while (x < r) { int len = r-x; if (len > 127) len = 127; stbiw__write_run_data(s, len, comp[x]); x += len; } } } } } } static int stbi_write_hdr_core(stbi__write_context *s, int x, int y, int comp, float *data) { if (y <= 0 || x <= 0 || data == NULL) return 0; else { // Each component is stored separately. Allocate scratch space for full output scanline. unsigned char *scratch = (unsigned char *) STBIW_MALLOC(x*4); int i, len; char buffer[128]; char header[] = "#?RADIANCE\n# Written by stb_image_write.h\nFORMAT=32-bit_rle_rgbe\n"; s->func(s->context, header, sizeof(header)-1); #ifdef __STDC_LIB_EXT1__ len = sprintf_s(buffer, sizeof(buffer), "EXPOSURE= 1.0000000000000\n\n-Y %d +X %d\n", y, x); #else len = sprintf(buffer, "EXPOSURE= 1.0000000000000\n\n-Y %d +X %d\n", y, x); #endif s->func(s->context, buffer, len); for(i=0; i < y; i++) stbiw__write_hdr_scanline(s, x, comp, scratch, data + comp*x*(stbi__flip_vertically_on_write ? y-1-i : i)); STBIW_FREE(scratch); return 1; } } STBIWDEF int stbi_write_hdr_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const float *data) { stbi__write_context s = { 0 }; stbi__start_write_callbacks(&s, func, context); return stbi_write_hdr_core(&s, x, y, comp, (float *) data); } STBIWDEF int stbi_write_hdr(char const *filename, int x, int y, int comp, const float *data) { stbi__write_context s = { 0 }; if (stbi__start_write_file(&s,filename)) { int r = stbi_write_hdr_core(&s, x, y, comp, (float *) data); stbi__end_write_file(&s); return r; } else return 0; } #endif // STBI_WRITE_NO_STDIO ////////////////////////////////////////////////////////////////////////////// // // PNG writer // #ifndef STBIW_ZLIB_COMPRESS // stretchy buffer; stbiw__sbpush() == vector<>::push_back() -- stbiw__sbcount() == vector<>::size() #define stbiw__sbraw(a) ((int *) (void *) (a) - 2) #define stbiw__sbm(a) stbiw__sbraw(a)[0] #define stbiw__sbn(a) stbiw__sbraw(a)[1] #define stbiw__sbneedgrow(a,n) ((a)==0 || stbiw__sbn(a)+n >= stbiw__sbm(a)) #define stbiw__sbmaybegrow(a,n) (stbiw__sbneedgrow(a,(n)) ? stbiw__sbgrow(a,n) : 0) #define stbiw__sbgrow(a,n) stbiw__sbgrowf((void **) &(a), (n), sizeof(*(a))) #define stbiw__sbpush(a, v) (stbiw__sbmaybegrow(a,1), (a)[stbiw__sbn(a)++] = (v)) #define stbiw__sbcount(a) ((a) ? stbiw__sbn(a) : 0) #define stbiw__sbfree(a) ((a) ? STBIW_FREE(stbiw__sbraw(a)),0 : 0) static void *stbiw__sbgrowf(void **arr, int increment, int itemsize) { int m = *arr ? 2*stbiw__sbm(*arr)+increment : increment+1; void *p = STBIW_REALLOC_SIZED(*arr ? stbiw__sbraw(*arr) : 0, *arr ? (stbiw__sbm(*arr)*itemsize + sizeof(int)*2) : 0, itemsize * m + sizeof(int)*2); STBIW_ASSERT(p); if (p) { if (!*arr) ((int *) p)[1] = 0; *arr = (void *) ((int *) p + 2); stbiw__sbm(*arr) = m; } return *arr; } static unsigned char *stbiw__zlib_flushf(unsigned char *data, unsigned int *bitbuffer, int *bitcount) { while (*bitcount >= 8) { stbiw__sbpush(data, STBIW_UCHAR(*bitbuffer)); *bitbuffer >>= 8; *bitcount -= 8; } return data; } static int stbiw__zlib_bitrev(int code, int codebits) { int res=0; while (codebits--) { res = (res << 1) | (code & 1); code >>= 1; } return res; } static unsigned int stbiw__zlib_countm(unsigned char *a, unsigned char *b, int limit) { int i; for (i=0; i < limit && i < 258; ++i) if (a[i] != b[i]) break; return i; } static unsigned int stbiw__zhash(unsigned char *data) { stbiw_uint32 hash = data[0] + (data[1] << 8) + (data[2] << 16); hash ^= hash << 3; hash += hash >> 5; hash ^= hash << 4; hash += hash >> 17; hash ^= hash << 25; hash += hash >> 6; return hash; } #define stbiw__zlib_flush() (out = stbiw__zlib_flushf(out, &bitbuf, &bitcount)) #define stbiw__zlib_add(code,codebits) \ (bitbuf |= (code) << bitcount, bitcount += (codebits), stbiw__zlib_flush()) #define stbiw__zlib_huffa(b,c) stbiw__zlib_add(stbiw__zlib_bitrev(b,c),c) // default huffman tables #define stbiw__zlib_huff1(n) stbiw__zlib_huffa(0x30 + (n), 8) #define stbiw__zlib_huff2(n) stbiw__zlib_huffa(0x190 + (n)-144, 9) #define stbiw__zlib_huff3(n) stbiw__zlib_huffa(0 + (n)-256,7) #define stbiw__zlib_huff4(n) stbiw__zlib_huffa(0xc0 + (n)-280,8) #define stbiw__zlib_huff(n) ((n) <= 143 ? stbiw__zlib_huff1(n) : (n) <= 255 ? stbiw__zlib_huff2(n) : (n) <= 279 ? stbiw__zlib_huff3(n) : stbiw__zlib_huff4(n)) #define stbiw__zlib_huffb(n) ((n) <= 143 ? stbiw__zlib_huff1(n) : stbiw__zlib_huff2(n)) #define stbiw__ZHASH 16384 #endif // STBIW_ZLIB_COMPRESS STBIWDEF unsigned char * stbi_zlib_compress(unsigned char *data, int data_len, int *out_len, int quality) { #ifdef STBIW_ZLIB_COMPRESS // user provided a zlib compress implementation, use that return STBIW_ZLIB_COMPRESS(data, data_len, out_len, quality); #else // use builtin static unsigned short lengthc[] = { 3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258, 259 }; static unsigned char lengtheb[]= { 0,0,0,0,0,0,0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0 }; static unsigned short distc[] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577, 32768 }; static unsigned char disteb[] = { 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13 }; unsigned int bitbuf=0; int i,j, bitcount=0; unsigned char *out = NULL; unsigned char ***hash_table = (unsigned char***) STBIW_MALLOC(stbiw__ZHASH * sizeof(unsigned char**)); if (hash_table == NULL) return NULL; if (quality < 5) quality = 5; stbiw__sbpush(out, 0x78); // DEFLATE 32K window stbiw__sbpush(out, 0x5e); // FLEVEL = 1 stbiw__zlib_add(1,1); // BFINAL = 1 stbiw__zlib_add(1,2); // BTYPE = 1 -- fixed huffman for (i=0; i < stbiw__ZHASH; ++i) hash_table[i] = NULL; i=0; while (i < data_len-3) { // hash next 3 bytes of data to be compressed int h = stbiw__zhash(data+i)&(stbiw__ZHASH-1), best=3; unsigned char *bestloc = 0; unsigned char **hlist = hash_table[h]; int n = stbiw__sbcount(hlist); for (j=0; j < n; ++j) { if (hlist[j]-data > i-32768) { // if entry lies within window int d = stbiw__zlib_countm(hlist[j], data+i, data_len-i); if (d >= best) { best=d; bestloc=hlist[j]; } } } // when hash table entry is too long, delete half the entries if (hash_table[h] && stbiw__sbn(hash_table[h]) == 2*quality) { STBIW_MEMMOVE(hash_table[h], hash_table[h]+quality, sizeof(hash_table[h][0])*quality); stbiw__sbn(hash_table[h]) = quality; } stbiw__sbpush(hash_table[h],data+i); if (bestloc) { // "lazy matching" - check match at *next* byte, and if it's better, do cur byte as literal h = stbiw__zhash(data+i+1)&(stbiw__ZHASH-1); hlist = hash_table[h]; n = stbiw__sbcount(hlist); for (j=0; j < n; ++j) { if (hlist[j]-data > i-32767) { int e = stbiw__zlib_countm(hlist[j], data+i+1, data_len-i-1); if (e > best) { // if next match is better, bail on current match bestloc = NULL; break; } } } } if (bestloc) { int d = (int) (data+i - bestloc); // distance back STBIW_ASSERT(d <= 32767 && best <= 258); for (j=0; best > lengthc[j+1]-1; ++j); stbiw__zlib_huff(j+257); if (lengtheb[j]) stbiw__zlib_add(best - lengthc[j], lengtheb[j]); for (j=0; d > distc[j+1]-1; ++j); stbiw__zlib_add(stbiw__zlib_bitrev(j,5),5); if (disteb[j]) stbiw__zlib_add(d - distc[j], disteb[j]); i += best; } else { stbiw__zlib_huffb(data[i]); ++i; } } // write out final bytes for (;i < data_len; ++i) stbiw__zlib_huffb(data[i]); stbiw__zlib_huff(256); // end of block // pad with 0 bits to byte boundary while (bitcount) stbiw__zlib_add(0,1); for (i=0; i < stbiw__ZHASH; ++i) (void) stbiw__sbfree(hash_table[i]); STBIW_FREE(hash_table); // store uncompressed instead if compression was worse if (stbiw__sbn(out) > data_len + 2 + ((data_len+32766)/32767)*5) { stbiw__sbn(out) = 2; // truncate to DEFLATE 32K window and FLEVEL = 1 for (j = 0; j < data_len;) { int blocklen = data_len - j; if (blocklen > 32767) blocklen = 32767; stbiw__sbpush(out, data_len - j == blocklen); // BFINAL = ?, BTYPE = 0 -- no compression stbiw__sbpush(out, STBIW_UCHAR(blocklen)); // LEN stbiw__sbpush(out, STBIW_UCHAR(blocklen >> 8)); stbiw__sbpush(out, STBIW_UCHAR(~blocklen)); // NLEN stbiw__sbpush(out, STBIW_UCHAR(~blocklen >> 8)); memcpy(out+stbiw__sbn(out), data+j, blocklen); stbiw__sbn(out) += blocklen; j += blocklen; } } { // compute adler32 on input unsigned int s1=1, s2=0; int blocklen = (int) (data_len % 5552); j=0; while (j < data_len) { for (i=0; i < blocklen; ++i) { s1 += data[j+i]; s2 += s1; } s1 %= 65521; s2 %= 65521; j += blocklen; blocklen = 5552; } stbiw__sbpush(out, STBIW_UCHAR(s2 >> 8)); stbiw__sbpush(out, STBIW_UCHAR(s2)); stbiw__sbpush(out, STBIW_UCHAR(s1 >> 8)); stbiw__sbpush(out, STBIW_UCHAR(s1)); } *out_len = stbiw__sbn(out); // make returned pointer freeable STBIW_MEMMOVE(stbiw__sbraw(out), out, *out_len); return (unsigned char *) stbiw__sbraw(out); #endif // STBIW_ZLIB_COMPRESS } static unsigned int stbiw__crc32(unsigned char *buffer, int len) { #ifdef STBIW_CRC32 return STBIW_CRC32(buffer, len); #else static unsigned int crc_table[256] = { 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0eDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D }; unsigned int crc = ~0u; int i; for (i=0; i < len; ++i) crc = (crc >> 8) ^ crc_table[buffer[i] ^ (crc & 0xff)]; return ~crc; #endif } #define stbiw__wpng4(o,a,b,c,d) ((o)[0]=STBIW_UCHAR(a),(o)[1]=STBIW_UCHAR(b),(o)[2]=STBIW_UCHAR(c),(o)[3]=STBIW_UCHAR(d),(o)+=4) #define stbiw__wp32(data,v) stbiw__wpng4(data, (v)>>24,(v)>>16,(v)>>8,(v)); #define stbiw__wptag(data,s) stbiw__wpng4(data, s[0],s[1],s[2],s[3]) static void stbiw__wpcrc(unsigned char **data, int len) { unsigned int crc = stbiw__crc32(*data - len - 4, len+4); stbiw__wp32(*data, crc); } static unsigned char stbiw__paeth(int a, int b, int c) { int p = a + b - c, pa = abs(p-a), pb = abs(p-b), pc = abs(p-c); if (pa <= pb && pa <= pc) return STBIW_UCHAR(a); if (pb <= pc) return STBIW_UCHAR(b); return STBIW_UCHAR(c); } // @OPTIMIZE: provide an option that always forces left-predict or paeth predict static void stbiw__encode_png_line(unsigned char *pixels, int stride_bytes, int width, int height, int y, int n, int filter_type, signed char *line_buffer) { static int mapping[] = { 0,1,2,3,4 }; static int firstmap[] = { 0,1,0,5,6 }; int *mymap = (y != 0) ? mapping : firstmap; int i; int type = mymap[filter_type]; unsigned char *z = pixels + stride_bytes * (stbi__flip_vertically_on_write ? height-1-y : y); int signed_stride = stbi__flip_vertically_on_write ? -stride_bytes : stride_bytes; if (type==0) { memcpy(line_buffer, z, width*n); return; } // first loop isn't optimized since it's just one pixel for (i = 0; i < n; ++i) { switch (type) { case 1: line_buffer[i] = z[i]; break; case 2: line_buffer[i] = z[i] - z[i-signed_stride]; break; case 3: line_buffer[i] = z[i] - (z[i-signed_stride]>>1); break; case 4: line_buffer[i] = (signed char) (z[i] - stbiw__paeth(0,z[i-signed_stride],0)); break; case 5: line_buffer[i] = z[i]; break; case 6: line_buffer[i] = z[i]; break; } } switch (type) { case 1: for (i=n; i < width*n; ++i) line_buffer[i] = z[i] - z[i-n]; break; case 2: for (i=n; i < width*n; ++i) line_buffer[i] = z[i] - z[i-signed_stride]; break; case 3: for (i=n; i < width*n; ++i) line_buffer[i] = z[i] - ((z[i-n] + z[i-signed_stride])>>1); break; case 4: for (i=n; i < width*n; ++i) line_buffer[i] = z[i] - stbiw__paeth(z[i-n], z[i-signed_stride], z[i-signed_stride-n]); break; case 5: for (i=n; i < width*n; ++i) line_buffer[i] = z[i] - (z[i-n]>>1); break; case 6: for (i=n; i < width*n; ++i) line_buffer[i] = z[i] - stbiw__paeth(z[i-n], 0,0); break; } } STBIWDEF unsigned char *stbi_write_png_to_mem(const unsigned char *pixels, int stride_bytes, int x, int y, int n, int *out_len) { int force_filter = stbi_write_force_png_filter; int ctype[5] = { -1, 0, 4, 2, 6 }; unsigned char sig[8] = { 137,80,78,71,13,10,26,10 }; unsigned char *out,*o, *filt, *zlib; signed char *line_buffer; int j,zlen; if (stride_bytes == 0) stride_bytes = x * n; if (force_filter >= 5) { force_filter = -1; } filt = (unsigned char *) STBIW_MALLOC((x*n+1) * y); if (!filt) return 0; line_buffer = (signed char *) STBIW_MALLOC(x * n); if (!line_buffer) { STBIW_FREE(filt); return 0; } for (j=0; j < y; ++j) { int filter_type; if (force_filter > -1) { filter_type = force_filter; stbiw__encode_png_line((unsigned char*)(pixels), stride_bytes, x, y, j, n, force_filter, line_buffer); } else { // Estimate the best filter by running through all of them: int best_filter = 0, best_filter_val = 0x7fffffff, est, i; for (filter_type = 0; filter_type < 5; filter_type++) { stbiw__encode_png_line((unsigned char*)(pixels), stride_bytes, x, y, j, n, filter_type, line_buffer); // Estimate the entropy of the line using this filter; the less, the better. est = 0; for (i = 0; i < x*n; ++i) { est += abs((signed char) line_buffer[i]); } if (est < best_filter_val) { best_filter_val = est; best_filter = filter_type; } } if (filter_type != best_filter) { // If the last iteration already got us the best filter, don't redo it stbiw__encode_png_line((unsigned char*)(pixels), stride_bytes, x, y, j, n, best_filter, line_buffer); filter_type = best_filter; } } // when we get here, filter_type contains the filter type, and line_buffer contains the data filt[j*(x*n+1)] = (unsigned char) filter_type; STBIW_MEMMOVE(filt+j*(x*n+1)+1, line_buffer, x*n); } STBIW_FREE(line_buffer); zlib = stbi_zlib_compress(filt, y*( x*n+1), &zlen, stbi_write_png_compression_level); STBIW_FREE(filt); if (!zlib) return 0; // each tag requires 12 bytes of overhead out = (unsigned char *) STBIW_MALLOC(8 + 12+13 + 12+zlen + 12); if (!out) return 0; *out_len = 8 + 12+13 + 12+zlen + 12; o=out; STBIW_MEMMOVE(o,sig,8); o+= 8; stbiw__wp32(o, 13); // header length stbiw__wptag(o, "IHDR"); stbiw__wp32(o, x); stbiw__wp32(o, y); *o++ = 8; *o++ = STBIW_UCHAR(ctype[n]); *o++ = 0; *o++ = 0; *o++ = 0; stbiw__wpcrc(&o,13); stbiw__wp32(o, zlen); stbiw__wptag(o, "IDAT"); STBIW_MEMMOVE(o, zlib, zlen); o += zlen; STBIW_FREE(zlib); stbiw__wpcrc(&o, zlen); stbiw__wp32(o,0); stbiw__wptag(o, "IEND"); stbiw__wpcrc(&o,0); STBIW_ASSERT(o == out + *out_len); return out; } #ifndef STBI_WRITE_NO_STDIO STBIWDEF int stbi_write_png(char const *filename, int x, int y, int comp, const void *data, int stride_bytes) { FILE *f; int len; unsigned char *png = stbi_write_png_to_mem((const unsigned char *) data, stride_bytes, x, y, comp, &len); if (png == NULL) return 0; f = stbiw__fopen(filename, "wb"); if (!f) { STBIW_FREE(png); return 0; } fwrite(png, 1, len, f); fclose(f); STBIW_FREE(png); return 1; } #endif STBIWDEF int stbi_write_png_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data, int stride_bytes) { int len; unsigned char *png = stbi_write_png_to_mem((const unsigned char *) data, stride_bytes, x, y, comp, &len); if (png == NULL) return 0; func(context, png, len); STBIW_FREE(png); return 1; } /* *************************************************************************** * * JPEG writer * * This is based on Jon Olick's jo_jpeg.cpp: * public domain Simple, Minimalistic JPEG writer - http://www.jonolick.com/code.html */ static const unsigned char stbiw__jpg_ZigZag[] = { 0,1,5,6,14,15,27,28,2,4,7,13,16,26,29,42,3,8,12,17,25,30,41,43,9,11,18, 24,31,40,44,53,10,19,23,32,39,45,52,54,20,22,33,38,46,51,55,60,21,34,37,47,50,56,59,61,35,36,48,49,57,58,62,63 }; static void stbiw__jpg_writeBits(stbi__write_context *s, int *bitBufP, int *bitCntP, const unsigned short *bs) { int bitBuf = *bitBufP, bitCnt = *bitCntP; bitCnt += bs[1]; bitBuf |= bs[0] << (24 - bitCnt); while(bitCnt >= 8) { unsigned char c = (bitBuf >> 16) & 255; stbiw__putc(s, c); if(c == 255) { stbiw__putc(s, 0); } bitBuf <<= 8; bitCnt -= 8; } *bitBufP = bitBuf; *bitCntP = bitCnt; } static void stbiw__jpg_DCT(float *d0p, float *d1p, float *d2p, float *d3p, float *d4p, float *d5p, float *d6p, float *d7p) { float d0 = *d0p, d1 = *d1p, d2 = *d2p, d3 = *d3p, d4 = *d4p, d5 = *d5p, d6 = *d6p, d7 = *d7p; float z1, z2, z3, z4, z5, z11, z13; float tmp0 = d0 + d7; float tmp7 = d0 - d7; float tmp1 = d1 + d6; float tmp6 = d1 - d6; float tmp2 = d2 + d5; float tmp5 = d2 - d5; float tmp3 = d3 + d4; float tmp4 = d3 - d4; // Even part float tmp10 = tmp0 + tmp3; // phase 2 float tmp13 = tmp0 - tmp3; float tmp11 = tmp1 + tmp2; float tmp12 = tmp1 - tmp2; d0 = tmp10 + tmp11; // phase 3 d4 = tmp10 - tmp11; z1 = (tmp12 + tmp13) * 0.707106781f; // c4 d2 = tmp13 + z1; // phase 5 d6 = tmp13 - z1; // Odd part tmp10 = tmp4 + tmp5; // phase 2 tmp11 = tmp5 + tmp6; tmp12 = tmp6 + tmp7; // The rotator is modified from fig 4-8 to avoid extra negations. z5 = (tmp10 - tmp12) * 0.382683433f; // c6 z2 = tmp10 * 0.541196100f + z5; // c2-c6 z4 = tmp12 * 1.306562965f + z5; // c2+c6 z3 = tmp11 * 0.707106781f; // c4 z11 = tmp7 + z3; // phase 5 z13 = tmp7 - z3; *d5p = z13 + z2; // phase 6 *d3p = z13 - z2; *d1p = z11 + z4; *d7p = z11 - z4; *d0p = d0; *d2p = d2; *d4p = d4; *d6p = d6; } static void stbiw__jpg_calcBits(int val, unsigned short bits[2]) { int tmp1 = val < 0 ? -val : val; val = val < 0 ? val-1 : val; bits[1] = 1; while(tmp1 >>= 1) { ++bits[1]; } bits[0] = val & ((1<<bits[1])-1); } static int stbiw__jpg_processDU(stbi__write_context *s, int *bitBuf, int *bitCnt, float *CDU, int du_stride, float *fdtbl, int DC, const unsigned short HTDC[256][2], const unsigned short HTAC[256][2]) { const unsigned short EOB[2] = { HTAC[0x00][0], HTAC[0x00][1] }; const unsigned short M16zeroes[2] = { HTAC[0xF0][0], HTAC[0xF0][1] }; int dataOff, i, j, n, diff, end0pos, x, y; int DU[64]; // DCT rows for(dataOff=0, n=du_stride*8; dataOff<n; dataOff+=du_stride) { stbiw__jpg_DCT(&CDU[dataOff], &CDU[dataOff+1], &CDU[dataOff+2], &CDU[dataOff+3], &CDU[dataOff+4], &CDU[dataOff+5], &CDU[dataOff+6], &CDU[dataOff+7]); } // DCT columns for(dataOff=0; dataOff<8; ++dataOff) { stbiw__jpg_DCT(&CDU[dataOff], &CDU[dataOff+du_stride], &CDU[dataOff+du_stride*2], &CDU[dataOff+du_stride*3], &CDU[dataOff+du_stride*4], &CDU[dataOff+du_stride*5], &CDU[dataOff+du_stride*6], &CDU[dataOff+du_stride*7]); } // Quantize/descale/zigzag the coefficients for(y = 0, j=0; y < 8; ++y) { for(x = 0; x < 8; ++x,++j) { float v; i = y*du_stride+x; v = CDU[i]*fdtbl[j]; // DU[stbiw__jpg_ZigZag[j]] = (int)(v < 0 ? ceilf(v - 0.5f) : floorf(v + 0.5f)); // ceilf() and floorf() are C99, not C89, but I /think/ they're not needed here anyway? DU[stbiw__jpg_ZigZag[j]] = (int)(v < 0 ? v - 0.5f : v + 0.5f); } } // Encode DC diff = DU[0] - DC; if (diff == 0) { stbiw__jpg_writeBits(s, bitBuf, bitCnt, HTDC[0]); } else { unsigned short bits[2]; stbiw__jpg_calcBits(diff, bits); stbiw__jpg_writeBits(s, bitBuf, bitCnt, HTDC[bits[1]]); stbiw__jpg_writeBits(s, bitBuf, bitCnt, bits); } // Encode ACs end0pos = 63; for(; (end0pos>0)&&(DU[end0pos]==0); --end0pos) { } // end0pos = first element in reverse order !=0 if(end0pos == 0) { stbiw__jpg_writeBits(s, bitBuf, bitCnt, EOB); return DU[0]; } for(i = 1; i <= end0pos; ++i) { int startpos = i; int nrzeroes; unsigned short bits[2]; for (; DU[i]==0 && i<=end0pos; ++i) { } nrzeroes = i-startpos; if ( nrzeroes >= 16 ) { int lng = nrzeroes>>4; int nrmarker; for (nrmarker=1; nrmarker <= lng; ++nrmarker) stbiw__jpg_writeBits(s, bitBuf, bitCnt, M16zeroes); nrzeroes &= 15; } stbiw__jpg_calcBits(DU[i], bits); stbiw__jpg_writeBits(s, bitBuf, bitCnt, HTAC[(nrzeroes<<4)+bits[1]]); stbiw__jpg_writeBits(s, bitBuf, bitCnt, bits); } if(end0pos != 63) { stbiw__jpg_writeBits(s, bitBuf, bitCnt, EOB); } return DU[0]; } static int stbi_write_jpg_core(stbi__write_context *s, int width, int height, int comp, const void* data, int quality) { // Constants that don't pollute global namespace static const unsigned char std_dc_luminance_nrcodes[] = {0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0}; static const unsigned char std_dc_luminance_values[] = {0,1,2,3,4,5,6,7,8,9,10,11}; static const unsigned char std_ac_luminance_nrcodes[] = {0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,0x7d}; static const unsigned char std_ac_luminance_values[] = { 0x01,0x02,0x03,0x00,0x04,0x11,0x05,0x12,0x21,0x31,0x41,0x06,0x13,0x51,0x61,0x07,0x22,0x71,0x14,0x32,0x81,0x91,0xa1,0x08, 0x23,0x42,0xb1,0xc1,0x15,0x52,0xd1,0xf0,0x24,0x33,0x62,0x72,0x82,0x09,0x0a,0x16,0x17,0x18,0x19,0x1a,0x25,0x26,0x27,0x28, 0x29,0x2a,0x34,0x35,0x36,0x37,0x38,0x39,0x3a,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4a,0x53,0x54,0x55,0x56,0x57,0x58,0x59, 0x5a,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6a,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7a,0x83,0x84,0x85,0x86,0x87,0x88,0x89, 0x8a,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9a,0xa2,0xa3,0xa4,0xa5,0xa6,0xa7,0xa8,0xa9,0xaa,0xb2,0xb3,0xb4,0xb5,0xb6, 0xb7,0xb8,0xb9,0xba,0xc2,0xc3,0xc4,0xc5,0xc6,0xc7,0xc8,0xc9,0xca,0xd2,0xd3,0xd4,0xd5,0xd6,0xd7,0xd8,0xd9,0xda,0xe1,0xe2, 0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,0xea,0xf1,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,0xf9,0xfa }; static const unsigned char std_dc_chrominance_nrcodes[] = {0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0}; static const unsigned char std_dc_chrominance_values[] = {0,1,2,3,4,5,6,7,8,9,10,11}; static const unsigned char std_ac_chrominance_nrcodes[] = {0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,0x77}; static const unsigned char std_ac_chrominance_values[] = { 0x00,0x01,0x02,0x03,0x11,0x04,0x05,0x21,0x31,0x06,0x12,0x41,0x51,0x07,0x61,0x71,0x13,0x22,0x32,0x81,0x08,0x14,0x42,0x91, 0xa1,0xb1,0xc1,0x09,0x23,0x33,0x52,0xf0,0x15,0x62,0x72,0xd1,0x0a,0x16,0x24,0x34,0xe1,0x25,0xf1,0x17,0x18,0x19,0x1a,0x26, 0x27,0x28,0x29,0x2a,0x35,0x36,0x37,0x38,0x39,0x3a,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4a,0x53,0x54,0x55,0x56,0x57,0x58, 0x59,0x5a,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6a,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7a,0x82,0x83,0x84,0x85,0x86,0x87, 0x88,0x89,0x8a,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9a,0xa2,0xa3,0xa4,0xa5,0xa6,0xa7,0xa8,0xa9,0xaa,0xb2,0xb3,0xb4, 0xb5,0xb6,0xb7,0xb8,0xb9,0xba,0xc2,0xc3,0xc4,0xc5,0xc6,0xc7,0xc8,0xc9,0xca,0xd2,0xd3,0xd4,0xd5,0xd6,0xd7,0xd8,0xd9,0xda, 0xe2,0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,0xea,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,0xf9,0xfa }; // Huffman tables static const unsigned short YDC_HT[256][2] = { {0,2},{2,3},{3,3},{4,3},{5,3},{6,3},{14,4},{30,5},{62,6},{126,7},{254,8},{510,9}}; static const unsigned short UVDC_HT[256][2] = { {0,2},{1,2},{2,2},{6,3},{14,4},{30,5},{62,6},{126,7},{254,8},{510,9},{1022,10},{2046,11}}; static const unsigned short YAC_HT[256][2] = { {10,4},{0,2},{1,2},{4,3},{11,4},{26,5},{120,7},{248,8},{1014,10},{65410,16},{65411,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {12,4},{27,5},{121,7},{502,9},{2038,11},{65412,16},{65413,16},{65414,16},{65415,16},{65416,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {28,5},{249,8},{1015,10},{4084,12},{65417,16},{65418,16},{65419,16},{65420,16},{65421,16},{65422,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {58,6},{503,9},{4085,12},{65423,16},{65424,16},{65425,16},{65426,16},{65427,16},{65428,16},{65429,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {59,6},{1016,10},{65430,16},{65431,16},{65432,16},{65433,16},{65434,16},{65435,16},{65436,16},{65437,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {122,7},{2039,11},{65438,16},{65439,16},{65440,16},{65441,16},{65442,16},{65443,16},{65444,16},{65445,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {123,7},{4086,12},{65446,16},{65447,16},{65448,16},{65449,16},{65450,16},{65451,16},{65452,16},{65453,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {250,8},{4087,12},{65454,16},{65455,16},{65456,16},{65457,16},{65458,16},{65459,16},{65460,16},{65461,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {504,9},{32704,15},{65462,16},{65463,16},{65464,16},{65465,16},{65466,16},{65467,16},{65468,16},{65469,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {505,9},{65470,16},{65471,16},{65472,16},{65473,16},{65474,16},{65475,16},{65476,16},{65477,16},{65478,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {506,9},{65479,16},{65480,16},{65481,16},{65482,16},{65483,16},{65484,16},{65485,16},{65486,16},{65487,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {1017,10},{65488,16},{65489,16},{65490,16},{65491,16},{65492,16},{65493,16},{65494,16},{65495,16},{65496,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {1018,10},{65497,16},{65498,16},{65499,16},{65500,16},{65501,16},{65502,16},{65503,16},{65504,16},{65505,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {2040,11},{65506,16},{65507,16},{65508,16},{65509,16},{65510,16},{65511,16},{65512,16},{65513,16},{65514,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {65515,16},{65516,16},{65517,16},{65518,16},{65519,16},{65520,16},{65521,16},{65522,16},{65523,16},{65524,16},{0,0},{0,0},{0,0},{0,0},{0,0}, {2041,11},{65525,16},{65526,16},{65527,16},{65528,16},{65529,16},{65530,16},{65531,16},{65532,16},{65533,16},{65534,16},{0,0},{0,0},{0,0},{0,0},{0,0} }; static const unsigned short UVAC_HT[256][2] = { {0,2},{1,2},{4,3},{10,4},{24,5},{25,5},{56,6},{120,7},{500,9},{1014,10},{4084,12},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {11,4},{57,6},{246,8},{501,9},{2038,11},{4085,12},{65416,16},{65417,16},{65418,16},{65419,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {26,5},{247,8},{1015,10},{4086,12},{32706,15},{65420,16},{65421,16},{65422,16},{65423,16},{65424,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {27,5},{248,8},{1016,10},{4087,12},{65425,16},{65426,16},{65427,16},{65428,16},{65429,16},{65430,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {58,6},{502,9},{65431,16},{65432,16},{65433,16},{65434,16},{65435,16},{65436,16},{65437,16},{65438,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {59,6},{1017,10},{65439,16},{65440,16},{65441,16},{65442,16},{65443,16},{65444,16},{65445,16},{65446,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {121,7},{2039,11},{65447,16},{65448,16},{65449,16},{65450,16},{65451,16},{65452,16},{65453,16},{65454,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {122,7},{2040,11},{65455,16},{65456,16},{65457,16},{65458,16},{65459,16},{65460,16},{65461,16},{65462,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {249,8},{65463,16},{65464,16},{65465,16},{65466,16},{65467,16},{65468,16},{65469,16},{65470,16},{65471,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {503,9},{65472,16},{65473,16},{65474,16},{65475,16},{65476,16},{65477,16},{65478,16},{65479,16},{65480,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {504,9},{65481,16},{65482,16},{65483,16},{65484,16},{65485,16},{65486,16},{65487,16},{65488,16},{65489,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {505,9},{65490,16},{65491,16},{65492,16},{65493,16},{65494,16},{65495,16},{65496,16},{65497,16},{65498,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {506,9},{65499,16},{65500,16},{65501,16},{65502,16},{65503,16},{65504,16},{65505,16},{65506,16},{65507,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {2041,11},{65508,16},{65509,16},{65510,16},{65511,16},{65512,16},{65513,16},{65514,16},{65515,16},{65516,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {16352,14},{65517,16},{65518,16},{65519,16},{65520,16},{65521,16},{65522,16},{65523,16},{65524,16},{65525,16},{0,0},{0,0},{0,0},{0,0},{0,0}, {1018,10},{32707,15},{65526,16},{65527,16},{65528,16},{65529,16},{65530,16},{65531,16},{65532,16},{65533,16},{65534,16},{0,0},{0,0},{0,0},{0,0},{0,0} }; static const int YQT[] = {16,11,10,16,24,40,51,61,12,12,14,19,26,58,60,55,14,13,16,24,40,57,69,56,14,17,22,29,51,87,80,62,18,22, 37,56,68,109,103,77,24,35,55,64,81,104,113,92,49,64,78,87,103,121,120,101,72,92,95,98,112,100,103,99}; static const int UVQT[] = {17,18,24,47,99,99,99,99,18,21,26,66,99,99,99,99,24,26,56,99,99,99,99,99,47,66,99,99,99,99,99,99, 99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99}; static const float aasf[] = { 1.0f * 2.828427125f, 1.387039845f * 2.828427125f, 1.306562965f * 2.828427125f, 1.175875602f * 2.828427125f, 1.0f * 2.828427125f, 0.785694958f * 2.828427125f, 0.541196100f * 2.828427125f, 0.275899379f * 2.828427125f }; int row, col, i, k, subsample; float fdtbl_Y[64], fdtbl_UV[64]; unsigned char YTable[64], UVTable[64]; if(!data || !width || !height || comp > 4 || comp < 1) { return 0; } quality = quality ? quality : 90; subsample = quality <= 90 ? 1 : 0; quality = quality < 1 ? 1 : quality > 100 ? 100 : quality; quality = quality < 50 ? 5000 / quality : 200 - quality * 2; for(i = 0; i < 64; ++i) { int uvti, yti = (YQT[i]*quality+50)/100; YTable[stbiw__jpg_ZigZag[i]] = (unsigned char) (yti < 1 ? 1 : yti > 255 ? 255 : yti); uvti = (UVQT[i]*quality+50)/100; UVTable[stbiw__jpg_ZigZag[i]] = (unsigned char) (uvti < 1 ? 1 : uvti > 255 ? 255 : uvti); } for(row = 0, k = 0; row < 8; ++row) { for(col = 0; col < 8; ++col, ++k) { fdtbl_Y[k] = 1 / (YTable [stbiw__jpg_ZigZag[k]] * aasf[row] * aasf[col]); fdtbl_UV[k] = 1 / (UVTable[stbiw__jpg_ZigZag[k]] * aasf[row] * aasf[col]); } } // Write Headers { static const unsigned char head0[] = { 0xFF,0xD8,0xFF,0xE0,0,0x10,'J','F','I','F',0,1,1,0,0,1,0,1,0,0,0xFF,0xDB,0,0x84,0 }; static const unsigned char head2[] = { 0xFF,0xDA,0,0xC,3,1,0,2,0x11,3,0x11,0,0x3F,0 }; const unsigned char head1[] = { 0xFF,0xC0,0,0x11,8,(unsigned char)(height>>8),STBIW_UCHAR(height),(unsigned char)(width>>8),STBIW_UCHAR(width), 3,1,(unsigned char)(subsample?0x22:0x11),0,2,0x11,1,3,0x11,1,0xFF,0xC4,0x01,0xA2,0 }; s->func(s->context, (void*)head0, sizeof(head0)); s->func(s->context, (void*)YTable, sizeof(YTable)); stbiw__putc(s, 1); s->func(s->context, UVTable, sizeof(UVTable)); s->func(s->context, (void*)head1, sizeof(head1)); s->func(s->context, (void*)(std_dc_luminance_nrcodes+1), sizeof(std_dc_luminance_nrcodes)-1); s->func(s->context, (void*)std_dc_luminance_values, sizeof(std_dc_luminance_values)); stbiw__putc(s, 0x10); // HTYACinfo s->func(s->context, (void*)(std_ac_luminance_nrcodes+1), sizeof(std_ac_luminance_nrcodes)-1); s->func(s->context, (void*)std_ac_luminance_values, sizeof(std_ac_luminance_values)); stbiw__putc(s, 1); // HTUDCinfo s->func(s->context, (void*)(std_dc_chrominance_nrcodes+1), sizeof(std_dc_chrominance_nrcodes)-1); s->func(s->context, (void*)std_dc_chrominance_values, sizeof(std_dc_chrominance_values)); stbiw__putc(s, 0x11); // HTUACinfo s->func(s->context, (void*)(std_ac_chrominance_nrcodes+1), sizeof(std_ac_chrominance_nrcodes)-1); s->func(s->context, (void*)std_ac_chrominance_values, sizeof(std_ac_chrominance_values)); s->func(s->context, (void*)head2, sizeof(head2)); } // Encode 8x8 macroblocks { static const unsigned short fillBits[] = {0x7F, 7}; int DCY=0, DCU=0, DCV=0; int bitBuf=0, bitCnt=0; // comp == 2 is grey+alpha (alpha is ignored) int ofsG = comp > 2 ? 1 : 0, ofsB = comp > 2 ? 2 : 0; const unsigned char *dataR = (const unsigned char *)data; const unsigned char *dataG = dataR + ofsG; const unsigned char *dataB = dataR + ofsB; int x, y, pos; if(subsample) { for(y = 0; y < height; y += 16) { for(x = 0; x < width; x += 16) { float Y[256], U[256], V[256]; for(row = y, pos = 0; row < y+16; ++row) { // row >= height => use last input row int clamped_row = (row < height) ? row : height - 1; int base_p = (stbi__flip_vertically_on_write ? (height-1-clamped_row) : clamped_row)*width*comp; for(col = x; col < x+16; ++col, ++pos) { // if col >= width => use pixel from last input column int p = base_p + ((col < width) ? col : (width-1))*comp; float r = dataR[p], g = dataG[p], b = dataB[p]; Y[pos]= +0.29900f*r + 0.58700f*g + 0.11400f*b - 128; U[pos]= -0.16874f*r - 0.33126f*g + 0.50000f*b; V[pos]= +0.50000f*r - 0.41869f*g - 0.08131f*b; } } DCY = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, Y+0, 16, fdtbl_Y, DCY, YDC_HT, YAC_HT); DCY = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, Y+8, 16, fdtbl_Y, DCY, YDC_HT, YAC_HT); DCY = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, Y+128, 16, fdtbl_Y, DCY, YDC_HT, YAC_HT); DCY = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, Y+136, 16, fdtbl_Y, DCY, YDC_HT, YAC_HT); // subsample U,V { float subU[64], subV[64]; int yy, xx; for(yy = 0, pos = 0; yy < 8; ++yy) { for(xx = 0; xx < 8; ++xx, ++pos) { int j = yy*32+xx*2; subU[pos] = (U[j+0] + U[j+1] + U[j+16] + U[j+17]) * 0.25f; subV[pos] = (V[j+0] + V[j+1] + V[j+16] + V[j+17]) * 0.25f; } } DCU = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, subU, 8, fdtbl_UV, DCU, UVDC_HT, UVAC_HT); DCV = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, subV, 8, fdtbl_UV, DCV, UVDC_HT, UVAC_HT); } } } } else { for(y = 0; y < height; y += 8) { for(x = 0; x < width; x += 8) { float Y[64], U[64], V[64]; for(row = y, pos = 0; row < y+8; ++row) { // row >= height => use last input row int clamped_row = (row < height) ? row : height - 1; int base_p = (stbi__flip_vertically_on_write ? (height-1-clamped_row) : clamped_row)*width*comp; for(col = x; col < x+8; ++col, ++pos) { // if col >= width => use pixel from last input column int p = base_p + ((col < width) ? col : (width-1))*comp; float r = dataR[p], g = dataG[p], b = dataB[p]; Y[pos]= +0.29900f*r + 0.58700f*g + 0.11400f*b - 128; U[pos]= -0.16874f*r - 0.33126f*g + 0.50000f*b; V[pos]= +0.50000f*r - 0.41869f*g - 0.08131f*b; } } DCY = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, Y, 8, fdtbl_Y, DCY, YDC_HT, YAC_HT); DCU = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, U, 8, fdtbl_UV, DCU, UVDC_HT, UVAC_HT); DCV = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, V, 8, fdtbl_UV, DCV, UVDC_HT, UVAC_HT); } } } // Do the bit alignment of the EOI marker stbiw__jpg_writeBits(s, &bitBuf, &bitCnt, fillBits); } // EOI stbiw__putc(s, 0xFF); stbiw__putc(s, 0xD9); return 1; } STBIWDEF int stbi_write_jpg_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data, int quality) { stbi__write_context s = { 0 }; stbi__start_write_callbacks(&s, func, context); return stbi_write_jpg_core(&s, x, y, comp, (void *) data, quality); } #ifndef STBI_WRITE_NO_STDIO STBIWDEF int stbi_write_jpg(char const *filename, int x, int y, int comp, const void *data, int quality) { stbi__write_context s = { 0 }; if (stbi__start_write_file(&s,filename)) { int r = stbi_write_jpg_core(&s, x, y, comp, data, quality); stbi__end_write_file(&s); return r; } else return 0; } #endif #endif // STB_IMAGE_WRITE_IMPLEMENTATION /* Revision history 1.16 (2021-07-11) make Deflate code emit uncompressed blocks when it would otherwise expand support writing BMPs with alpha channel 1.15 (2020-07-13) unknown 1.14 (2020-02-02) updated JPEG writer to downsample chroma channels 1.13 1.12 1.11 (2019-08-11) 1.10 (2019-02-07) support utf8 filenames in Windows; fix warnings and platform ifdefs 1.09 (2018-02-11) fix typo in zlib quality API, improve STB_I_W_STATIC in C++ 1.08 (2018-01-29) add stbi__flip_vertically_on_write, external zlib, zlib quality, choose PNG filter 1.07 (2017-07-24) doc fix 1.06 (2017-07-23) writing JPEG (using Jon Olick's code) 1.05 ??? 1.04 (2017-03-03) monochrome BMP expansion 1.03 ??? 1.02 (2016-04-02) avoid allocating large structures on the stack 1.01 (2016-01-16) STBIW_REALLOC_SIZED: support allocators with no realloc support avoid race-condition in crc initialization minor compile issues 1.00 (2015-09-14) installable file IO function 0.99 (2015-09-13) warning fixes; TGA rle support 0.98 (2015-04-08) added STBIW_MALLOC, STBIW_ASSERT etc 0.97 (2015-01-18) fixed HDR asserts, rewrote HDR rle logic 0.96 (2015-01-17) add HDR output fix monochrome BMP 0.95 (2014-08-17) add monochrome TGA output 0.94 (2014-05-31) rename private functions to avoid conflicts with stb_image.h 0.93 (2014-05-27) warning fixes 0.92 (2010-08-01) casts to unsigned char to fix warnings 0.91 (2010-07-17) first public release 0.90 first internal release */ /* ------------------------------------------------------------------------------ This software is available under 2 licenses -- choose whichever you prefer. ------------------------------------------------------------------------------ ALTERNATIVE A - MIT License Copyright (c) 2017 Sean Barrett Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------ ALTERNATIVE B - Public Domain (www.unlicense.org) This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------ */
0
repos/simulations/libs
repos/simulations/libs/zgui/README.md
# zgui v0.2.0 - dear imgui bindings Easy to use, hand-crafted API with default arguments, named parameters and Zig style text formatting. [Here](https://github.com/michal-z/zig-gamedev/tree/main/samples/minimal_zgpu_zgui) is a simple sample application, and [here](https://github.com/michal-z/zig-gamedev/tree/main/samples/gui_test_wgpu) is a full one. ## Features * Most public dear imgui API exposed * All memory allocations go through user provided Zig allocator * [DrawList API](#drawlist-api) for vector graphics, text rendering and custom widgets * [Plot API](#plot-api) for advanced data visualizations * [Test engine API](#test-engine-api) for automatic testing ## Versions * [ImGui](https://github.com/ocornut/imgui/tree/v1.90.4-docking) `1.90.4-docking` * [ImGui test engine](https://github.com/ocornut/imgui_test_engine/tree/v1.90.4) `1.90.4` * [ImPlot](https://github.com/epezent/implot) `O.17` ## Getting started Copy `zgui` to a subdirectory in your project and add the following to your `build.zig.zon` .dependencies: ```zig .zgui = .{ .path = "libs/zgui" }, ``` To get glfw/wgpu rendering backend working also copy `zglfw`, `system-sdk`, `zgpu` and `zpool` folders and add the depenency paths (see [zgpu](https://github.com/zig-gamedev/zig-gamedev/tree/main/libs/zgpu) for the details). Then in your `build.zig` add: ```zig pub fn build(b: *std.Build) void { const exe = b.addExecutable(.{ ... }); const zgui = b.dependency("zgui", .{ .shared = false, .with_implot = true, }); exe.root_module.addImport("zgui", zgui.module("root")); exe.linkLibrary(zgui.artifact("imgui")); { // Needed for glfw/wgpu rendering backend const zglfw = b.dependency("zglfw", .{}); exe.root_module.addImport("zglfw", zglfw.module("root")); exe.linkLibrary(zglfw.artifact("glfw")); const zpool = b.dependency("zpool", .{}); exe.root_module.addImport("zpool", zpool.module("root")); const zgpu = b.dependency("zgpu", .{}); exe.root_module.addImport("zgpu", zgpu.module("root")); exe.linkLibrary(zgpu.artifact("zdawn")); } } ``` Now in your code you may import and use `zgui`: ```zig const zgui = @import("zgui"); zgui.init(allocator); _ = zgui.io.addFontFromFile(content_dir ++ "Roboto-Medium.ttf", 16.0); zgui.backend.init( window, demo.gctx.device, @enumToInt(swapchain_format), @enumToInt(depth_format), ); ``` ```zig // Main loop while (...) { zgui.backend.newFrame(framebuffer_width, framebuffer_height); zgui.bulletText( "Average : {d:.3} ms/frame ({d:.1} fps)", .{ demo.gctx.stats.average_cpu_time, demo.gctx.stats.fps }, ); zgui.bulletText("W, A, S, D : move camera", .{}); zgui.spacing(); if (zgui.button("Setup Scene", .{})) { // Button pressed. } if (zgui.dragFloat("Drag 1", .{ .v = &value0 })) { // value0 has changed } if (zgui.dragFloat("Drag 2", .{ .v = &value0, .min = -1.0, .max = 1.0 })) { // value1 has changed } // Setup wgpu render pass here zgui.backend.draw(pass); } ``` ### Building a shared library If your project spans multiple zig modules that both use ImGui, such as an exe paired with a dll, you may want to build the `zgui` dependencies (`zgui_pkg.zgui_c_cpp`) as a shared library. This can be enabled with the `shared` build option. Then, in `build.zig`, use `zgui_pkg.link` to link `zgui` to all the modules that use ImGui. When built this way, the ImGui context will be located in the shared library. However, the `zgui` zig code (which is compiled separately into each module) requires its own memory buffer which has to be initialized separately with `initNoContext`. In your executable: ```zig const zgui = @import("zgui"); zgui.init(allocator); defer zgui.deinit(); ``` In your shared library: ```zig const zgui = @import("zgui"); zgui.initNoContext(allocator); defer zgui.deinitNoContxt(); ``` ### DrawList API ```zig draw_list.addQuad(.{ .p1 = .{ 170, 420 }, .p2 = .{ 270, 420 }, .p3 = .{ 220, 520 }, .p4 = .{ 120, 520 }, .col = 0xff_00_00_ff, .thickness = 3.0, }); draw_list.addText(.{ 130, 130 }, 0xff_00_00_ff, "The number is: {}", .{7}); draw_list.addCircleFilled(.{ .p = .{ 200, 600 }, .r = 50, .col = 0xff_ff_ff_ff }); draw_list.addCircle(.{ .p = .{ 200, 600 }, .r = 30, .col = 0xff_00_00_ff, .thickness = 11 }); draw_list.addPolyline( &.{ .{ 100, 700 }, .{ 200, 600 }, .{ 300, 700 }, .{ 400, 600 } }, .{ .col = 0xff_00_aa_11, .thickness = 7 }, ); ``` ### Plot API ```zig if (zgui.plot.beginPlot("Line Plot", .{ .h = -1.0 })) { zgui.plot.setupAxis(.x1, .{ .label = "xaxis" }); zgui.plot.setupAxisLimits(.x1, .{ .min = 0, .max = 5 }); zgui.plot.setupLegend(.{ .south = true, .west = true }, .{}); zgui.plot.setupFinish(); zgui.plot.plotLineValues("y data", i32, .{ .v = &.{ 0, 1, 0, 1, 0, 1 } }); zgui.plot.plotLine("xy data", f32, .{ .xv = &.{ 0.1, 0.2, 0.5, 2.5 }, .yv = &.{ 0.1, 0.3, 0.5, 0.9 }, }); zgui.plot.endPlot(); } ``` ### Test Engine API Zig wraper for [ImGUI test engine](https://github.com/ocornut/imgui_test_engine). ```zig var check_b = false; var _te: *zgui.te.TestEngine = zgui.te.getTestEngine().?; fn registerTests() void { _ = _te.registerTest( "Awesome", "should_do_some_another_magic", @src(), struct { pub fn gui(ctx: *zgui.te.TestContext) !void { _ = ctx; // autofix _ = zgui.begin("Test Window", .{ .flags = .{ .no_saved_settings = true } }); defer zgui.end(); zgui.text("Hello, automation world", .{}); _ = zgui.button("Click Me", .{}); if (zgui.treeNode("Node")) { defer zgui.treePop(); _ = zgui.checkbox("Checkbox", .{ .v = &check_b }); } } pub fn run(ctx: *zgui.te.TestContext) !void { ctx.setRef("/Test Window"); ctx.windowFocus(""); ctx.itemAction(.click, "Click Me", .{}, null); ctx.itemAction(.open, "Node", .{}, null); ctx.itemAction(.check, "Node/Checkbox", .{}, null); ctx.itemAction(.uncheck, "Node/Checkbox", .{}, null); std.testing.expect(true) catch |err| { zgui.te.checkTestError(@src(), err); return; }; } }, ); } ```
0
repos/simulations/libs
repos/simulations/libs/zgui/build.zig.zon
.{ .name = "zgui", .version = "0.1.0", .paths = .{ "build.zig", "build.zig.zon", "libs", "src", "README.md", }, .dependencies = .{ .zglfw = .{ .path = "../zglfw" }, .zgpu = .{ .path = "../zgpu" }, .system_sdk = .{ .path = "../system-sdk" }, }, }
0
repos/simulations/libs
repos/simulations/libs/zgui/build.zig
const std = @import("std"); pub const Backend = enum { no_backend, glfw_wgpu, glfw_opengl3, glfw_dx12, win32_dx12, glfw, }; pub fn build(b: *std.Build) void { const optimize = b.standardOptimizeOption(.{}); const target = b.standardTargetOptions(.{}); const options = .{ .backend = b.option(Backend, "backend", "Backend to build (default: no_backend)") orelse .no_backend, .shared = b.option( bool, "shared", "Bulid as a shared library", ) orelse false, .with_implot = b.option( bool, "with_implot", "Build with bundled implot source", ) orelse true, .with_te = b.option( bool, "with_te", "Build with bundled test engine support", ) orelse false, .use_wchar32 = b.option( bool, "use_wchar32", "Extended unicode support", ) orelse false, }; const options_step = b.addOptions(); inline for (std.meta.fields(@TypeOf(options))) |field| { options_step.addOption(field.type, field.name, @field(options, field.name)); } const options_module = options_step.createModule(); _ = b.addModule("root", .{ .root_source_file = b.path("src/gui.zig"), .imports = &.{ .{ .name = "zgui_options", .module = options_module }, }, }); const cflags = &.{ "-fno-sanitize=undefined", "-Wno-elaborated-enum-base" }; const imgui = if (options.shared) blk: { const lib = b.addSharedLibrary(.{ .name = "imgui", .target = target, .optimize = optimize, }); if (target.result.os.tag == .windows) { lib.defineCMacro("IMGUI_API", "__declspec(dllexport)"); lib.defineCMacro("IMPLOT_API", "__declspec(dllexport)"); lib.defineCMacro("ZGUI_API", "__declspec(dllexport)"); } if (target.result.os.tag == .macos) { lib.linker_allow_shlib_undefined = true; } break :blk lib; } else b.addStaticLibrary(.{ .name = "imgui", .target = target, .optimize = optimize, }); b.installArtifact(imgui); imgui.addIncludePath(b.path("libs")); imgui.addIncludePath(b.path("libs/imgui")); imgui.linkLibC(); if (target.result.abi != .msvc) imgui.linkLibCpp(); imgui.addCSourceFile(.{ .file = b.path("src/zgui.cpp"), .flags = cflags, }); imgui.addCSourceFiles(.{ .files = &.{ "libs/imgui/imgui.cpp", "libs/imgui/imgui_widgets.cpp", "libs/imgui/imgui_tables.cpp", "libs/imgui/imgui_draw.cpp", "libs/imgui/imgui_demo.cpp", }, .flags = cflags, }); if (options.with_implot) { imgui.defineCMacro("ZGUI_IMPLOT", "1"); imgui.addCSourceFiles(.{ .files = &.{ "libs/imgui/implot_demo.cpp", "libs/imgui/implot.cpp", "libs/imgui/implot_items.cpp", }, .flags = cflags, }); } else { imgui.defineCMacro("ZGUI_IMPLOT", "0"); } if (options.use_wchar32) { imgui.defineCMacro("IMGUI_USE_WCHAR32", "1"); } if (options.with_te) { imgui.defineCMacro("ZGUI_TE", "1"); imgui.defineCMacro("IMGUI_ENABLE_TEST_ENGINE", null); imgui.defineCMacro("IMGUI_TEST_ENGINE_ENABLE_COROUTINE_STDTHREAD_IMPL", "1"); imgui.addIncludePath(b.path("libs/imgui_test_engine/")); imgui.addCSourceFile(.{ .file = b.path("libs/imgui_test_engine/imgui_capture_tool.cpp"), .flags = cflags }); imgui.addCSourceFile(.{ .file = b.path("libs/imgui_test_engine/imgui_te_context.cpp"), .flags = cflags }); imgui.addCSourceFile(.{ .file = b.path("libs/imgui_test_engine/imgui_te_coroutine.cpp"), .flags = cflags }); imgui.addCSourceFile(.{ .file = b.path("libs/imgui_test_engine/imgui_te_engine.cpp"), .flags = cflags }); imgui.addCSourceFile(.{ .file = b.path("libs/imgui_test_engine/imgui_te_exporters.cpp"), .flags = cflags }); imgui.addCSourceFile(.{ .file = b.path("libs/imgui_test_engine/imgui_te_perftool.cpp"), .flags = cflags }); imgui.addCSourceFile(.{ .file = b.path("libs/imgui_test_engine/imgui_te_ui.cpp"), .flags = cflags }); imgui.addCSourceFile(.{ .file = b.path("libs/imgui_test_engine/imgui_te_utils.cpp"), .flags = cflags }); // TODO: Workaround because zig on win64 doesn have phtreads // TODO: Implement corutine in zig can solve this if (target.result.os.tag == .windows) { const src: []const []const u8 = &.{ "libs/winpthreads/src/nanosleep.c", "libs/winpthreads/src/cond.c", "libs/winpthreads/src/barrier.c", "libs/winpthreads/src/misc.c", "libs/winpthreads/src/clock.c", "libs/winpthreads/src/libgcc/dll_math.c", "libs/winpthreads/src/spinlock.c", "libs/winpthreads/src/thread.c", "libs/winpthreads/src/mutex.c", "libs/winpthreads/src/sem.c", "libs/winpthreads/src/sched.c", "libs/winpthreads/src/ref.c", "libs/winpthreads/src/rwlock.c", }; const winpthreads = b.addStaticLibrary(.{ .name = "winpthreads", .optimize = optimize, .target = target, }); winpthreads.want_lto = false; winpthreads.root_module.sanitize_c = false; if (optimize == .Debug or optimize == .ReleaseSafe) winpthreads.bundle_compiler_rt = true else winpthreads.root_module.strip = true; winpthreads.addCSourceFiles(.{ .files = src, .flags = &.{ "-Wall", "-Wextra", } }); winpthreads.defineCMacro("__USE_MINGW_ANSI_STDIO", "1"); winpthreads.addIncludePath(b.path("libs/winpthreads/include")); winpthreads.addIncludePath(b.path("libs/winpthreads/src")); winpthreads.linkLibC(); b.installArtifact(winpthreads); imgui.linkLibrary(winpthreads); imgui.addSystemIncludePath(b.path("libs/winpthreads/include")); } } else { imgui.defineCMacro("ZGUI_TE", "0"); } switch (options.backend) { .glfw_wgpu => { const zglfw = b.dependency("zglfw", .{}); const zgpu = b.dependency("zgpu", .{}); imgui.addIncludePath(zglfw.path("libs/glfw/include")); imgui.addIncludePath(zgpu.path("libs/dawn/include")); imgui.addCSourceFiles(.{ .files = &.{ "libs/imgui/backends/imgui_impl_glfw.cpp", "libs/imgui/backends/imgui_impl_wgpu.cpp", }, .flags = cflags, }); }, .glfw_opengl3 => { const zglfw = b.dependency("zglfw", .{}); imgui.addIncludePath(zglfw.path("libs/glfw/include")); imgui.addCSourceFiles(.{ .files = &.{ "libs/imgui/backends/imgui_impl_glfw.cpp", "libs/imgui/backends/imgui_impl_opengl3.cpp", }, .flags = &(cflags.* ++ .{"-DIMGUI_IMPL_OPENGL_LOADER_CUSTOM"}), }); }, .glfw_dx12 => { const zglfw = b.dependency("zglfw", .{}); imgui.addIncludePath(zglfw.path("libs/glfw/include")); imgui.addCSourceFiles(.{ .files = &.{ "libs/imgui/backends/imgui_impl_glfw.cpp", "libs/imgui/backends/imgui_impl_dx12.cpp", }, .flags = cflags, }); imgui.linkSystemLibrary("d3dcompiler_47"); }, .win32_dx12 => { imgui.addCSourceFiles(.{ .files = &.{ "libs/imgui/backends/imgui_impl_win32.cpp", "libs/imgui/backends/imgui_impl_dx12.cpp", }, .flags = cflags, }); imgui.linkSystemLibrary("d3dcompiler_47"); imgui.linkSystemLibrary("dwmapi"); switch (target.result.abi) { .msvc => imgui.linkSystemLibrary("Gdi32"), .gnu => imgui.linkSystemLibrary("gdi32"), else => {}, } }, .glfw => { const zglfw = b.dependency("zglfw", .{}); imgui.addIncludePath(zglfw.path("libs/glfw/include")); imgui.addCSourceFiles(.{ .files = &.{ "libs/imgui/backends/imgui_impl_glfw.cpp", }, .flags = cflags, }); }, .no_backend => {}, } if (target.result.os.tag == .macos) { const system_sdk = b.dependency("system_sdk", .{}); imgui.addSystemIncludePath(system_sdk.path("macos12/usr/include")); imgui.addFrameworkPath(system_sdk.path("macos12/System/Library/Frameworks")); } const test_step = b.step("test", "Run zgui tests"); const tests = b.addTest(.{ .name = "zgui-tests", .root_source_file = b.path("src/gui.zig"), .target = target, .optimize = optimize, }); b.installArtifact(tests); tests.root_module.addImport("zgui_options", options_module); tests.linkLibrary(imgui); test_step.dependOn(&b.addRunArtifact(tests).step); }
0
repos/simulations/libs/zgui
repos/simulations/libs/zgui/src/backend_win32_dx12.zig
const std = @import("std"); const gui = @import("gui.zig"); const backend_dx12 = @import("backend_dx12.zig"); pub fn init( hwnd: *const anyopaque, // HWND d3d12_device: *const anyopaque, // ID3D12Device* num_frames_in_flight: u16, rtv_format: u32, // DXGI_FORMAT cbv_srv_heap: *const anyopaque, // ID3D12DescriptorHeap* font_srv_cpu_desc_handle: backend_dx12.D3D12_CPU_DESCRIPTOR_HANDLE, font_srv_gpu_desc_handle: backend_dx12.D3D12_GPU_DESCRIPTOR_HANDLE, ) void { std.debug.assert(ImGui_ImplWin32_Init(hwnd)); backend_dx12.init( d3d12_device, num_frames_in_flight, rtv_format, cbv_srv_heap, font_srv_cpu_desc_handle, font_srv_gpu_desc_handle, ); } pub fn deinit() void { backend_dx12.deinit(); ImGui_ImplWin32_Shutdown(); } pub fn newFrame(fb_width: u32, fb_height: u32) void { ImGui_ImplWin32_NewFrame(); backend_dx12.newFrame(); gui.io.setDisplaySize(@as(f32, @floatFromInt(fb_width)), @as(f32, @floatFromInt(fb_height))); gui.io.setDisplayFramebufferScale(1.0, 1.0); gui.newFrame(); } pub fn draw(graphics_command_list: *const anyopaque) void { gui.render(); backend_dx12.render(gui.getDrawData(), graphics_command_list); } extern fn ImGui_ImplWin32_Init(hwnd: *const anyopaque) bool; extern fn ImGui_ImplWin32_Shutdown() void; extern fn ImGui_ImplWin32_NewFrame() void;
0
repos/simulations/libs/zgui
repos/simulations/libs/zgui/src/backend_glfw.zig
const gui = @import("gui.zig"); // This call will install GLFW callbacks to handle GUI interactions. // Those callbacks will chain-call user's previously installed callbacks, if any. // This means that custom user's callbacks need to be installed *before* calling zgpu.gui.init(). pub fn init( window: *const anyopaque, // zglfw.Window ) void { if (!ImGui_ImplGlfw_InitForOther(window, true)) { unreachable; } } pub fn initOpenGL( window: *const anyopaque, // zglfw.Window ) void { if (!ImGui_ImplGlfw_InitForOpenGL(window, true)) { unreachable; } } pub fn deinit() void { ImGui_ImplGlfw_Shutdown(); } pub fn newFrame() void { ImGui_ImplGlfw_NewFrame(); } // Those functions are defined in `imgui_impl_glfw.cpp` // (they include few custom changes). extern fn ImGui_ImplGlfw_InitForOther(window: *const anyopaque, install_callbacks: bool) bool; extern fn ImGui_ImplGlfw_InitForOpenGL(window: *const anyopaque, install_callbacks: bool) bool; extern fn ImGui_ImplGlfw_NewFrame() void; extern fn ImGui_ImplGlfw_Shutdown() void;
0
repos/simulations/libs/zgui
repos/simulations/libs/zgui/src/backend_glfw_wgpu.zig
const gui = @import("gui.zig"); const backend_glfw = @import("backend_glfw.zig"); // This call will install GLFW callbacks to handle GUI interactions. // Those callbacks will chain-call user's previously installed callbacks, if any. // This means that custom user's callbacks need to be installed *before* calling zgpu.gui.init(). pub fn init( window: *const anyopaque, // zglfw.Window wgpu_device: *const anyopaque, // wgpu.Device wgpu_swap_chain_format: u32, // wgpu.TextureFormat wgpu_depth_format: u32, // wgpu.TextureFormat ) void { backend_glfw.init(window); var info = ImGui_ImplWGPU_InitInfo{ .device = wgpu_device, .num_frames_in_flight = 1, .rt_format = wgpu_swap_chain_format, .depth_format = wgpu_depth_format, .pipeline_multisample_state = .{}, }; if (!ImGui_ImplWGPU_Init(&info)) { unreachable; } } pub fn deinit() void { ImGui_ImplWGPU_Shutdown(); backend_glfw.deinit(); } pub fn newFrame(fb_width: u32, fb_height: u32) void { ImGui_ImplWGPU_NewFrame(); backend_glfw.newFrame(); gui.io.setDisplaySize(@floatFromInt(fb_width), @floatFromInt(fb_height)); gui.io.setDisplayFramebufferScale(1.0, 1.0); gui.newFrame(); } pub fn draw(wgpu_render_pass: *const anyopaque) void { gui.render(); ImGui_ImplWGPU_RenderDrawData(gui.getDrawData(), wgpu_render_pass); } pub const ImGui_ImplWGPU_InitInfo = extern struct { device: *const anyopaque, num_frames_in_flight: u32 = 1, rt_format: u32, depth_format: u32, pipeline_multisample_state: extern struct { next_in_chain: ?*const anyopaque = null, count: u32 = 1, mask: u32 = @bitCast(@as(i32, -1)), alpha_to_coverage_enabled: bool = false, }, }; // Those functions are defined in 'imgui_impl_wgpu.cpp` // (they include few custom changes). extern fn ImGui_ImplWGPU_Init(init_info: *ImGui_ImplWGPU_InitInfo) bool; extern fn ImGui_ImplWGPU_NewFrame() void; extern fn ImGui_ImplWGPU_RenderDrawData(draw_data: *const anyopaque, pass_encoder: *const anyopaque) void; extern fn ImGui_ImplWGPU_Shutdown() void;
0
repos/simulations/libs/zgui
repos/simulations/libs/zgui/src/backend_glfw_dx12.zig
const gui = @import("gui.zig"); const backend_glfw = @import("backend_glfw.zig"); const backend_dx12 = @import("backend_dx12.zig"); pub fn init( window: *const anyopaque, // zglfw.Window device: *const anyopaque, // ID3D12Device num_frames_in_flight: u32, rtv_format: c_uint, // DXGI_FORMAT cbv_srv_heap: *const anyopaque, // ID3D12DescriptorHeap font_srv_cpu_desc_handle: backend_dx12.D3D12_CPU_DESCRIPTOR_HANDLE, font_srv_gpu_desc_handle: backend_dx12.D3D12_GPU_DESCRIPTOR_HANDLE, ) void { backend_glfw.init(window); backend_dx12.init( device, num_frames_in_flight, rtv_format, cbv_srv_heap, font_srv_cpu_desc_handle, font_srv_gpu_desc_handle, ); } pub fn deinit() void { backend_dx12.deinit(); backend_glfw.deinit(); } pub fn newFrame(fb_width: u32, fb_height: u32) void { backend_glfw.newFrame(); backend_dx12.newFrame(); gui.io.setDisplaySize(@as(f32, @floatFromInt(fb_width)), @as(f32, @floatFromInt(fb_height))); gui.io.setDisplayFramebufferScale(1.0, 1.0); gui.newFrame(); } pub fn draw( graphics_command_list: *const anyopaque, // *ID3D12GraphicsCommandList ) void { gui.render(); backend_dx12.render(gui.getDrawData(), graphics_command_list); }
0
repos/simulations/libs/zgui
repos/simulations/libs/zgui/src/te.zig
const std = @import("std"); const zgui = @import("gui.zig"); const te_enabled = @import("zgui_options").with_te; pub const Actions = enum(c_int) { unknown = 0, /// Move mouse hover, /// Move mouse and click click, /// Move mouse and double-click double_click, /// Check item if unchecked (Checkbox, MenuItem or any widget reporting ImGuiItemStatusFlags_Checkable) check, /// Uncheck item if checked uncheck, /// Open item if closed (TreeNode, BeginMenu or any widget reporting ImGuiItemStatusFlags_Openable) open, /// Close item if opened close, /// Start text inputing into a field (e.g. CTRL+Click on Drags/Slider, click on InputText etc.) input, /// Activate item with navigation nav_activate, }; pub const TestRunFlags = packed struct(c_int) { /// Used internally to temporarily disable the GUI func (at the end of a test, etc) gui_func_disable: bool = false, /// Set when user selects "Run GUI func" gui_func_only: bool = false, no_success_mgs: bool = false, no_stop_on_error: bool = false, no_break_on_error: bool = false, /// Disable input submission to let test submission raw input event (in order to test e.g. IO queue) enable_raw_inputs: bool = false, manual_run: bool = false, command_line: bool = false, _padding: u24 = 0, }; pub const TestOpFlags = packed struct(c_int) { // Don't check for HoveredId after aiming for a widget. A few situations may want this: while e.g. dragging or another items prevents hovering, or for items that don't use ItemHoverable() no_check_hovered_id: bool = false, /// Don't abort/error e.g. if the item cannot be found or the operation doesn't succeed. no_error: bool = false, /// Don't focus window when aiming at an item no_focus_window: bool = false, /// Disable automatically uncollapsing windows (useful when specifically testing Collapsing behaviors) no_auto_uncollapse: bool = false, /// Disable automatically opening intermediaries (e.g. ItemClick("Hello/OK") will automatically first open "Hello" if "OK" isn't found. Only works if ref is a string path. no_auto_open_full_path: bool = false, /// Used by recursing functions to indicate a second attempt is_second_attempt: bool = false, move_to_edge_l: bool = false, // Simple Dumb aiming helpers to test widget that care about clicking position. May need to replace will better functionalities. move_to_edge_r: bool = false, move_to_edge_u: bool = false, move_to_edge_d: bool = false, _padding: u22 = 0, }; pub const CheckFlags = packed struct(c_int) { silent_success: bool = false, _padding: u31 = 0, }; pub const RunSpeed = enum(c_int) { /// Run tests as fast as possible (teleport mouse, skip delays, etc.) fast = 0, /// Run tests at human watchable speed (for debugging) normal = 1, /// Run tests with pauses between actions (for e.g. tutorials) cinematic = 2, }; pub const TestGroup = enum(c_int) { unknown = -1, tests = 0, perfs = 1, }; pub const Test = anyopaque; pub const TestEngine = opaque { pub fn registerTest( engine: *TestEngine, category: [:0]const u8, name: [:0]const u8, src: std.builtin.SourceLocation, comptime Callbacks: type, ) *Test { return zguiTe_RegisterTest( engine, category.ptr, name.ptr, src.file.ptr, @intCast(src.line), if (std.meta.hasFn(Callbacks, "gui")) struct { fn f(context: *TestContext) callconv(.C) void { Callbacks.gui(context) catch undefined; } }.f else null, if (std.meta.hasFn(Callbacks, "run")) struct { fn f(context: *TestContext) callconv(.C) void { Callbacks.run(context) catch undefined; } }.f else null, ); } pub const showTestEngineWindows = zguiTe_ShowTestEngineWindows; extern fn zguiTe_ShowTestEngineWindows(engine: *TestEngine, p_open: ?*bool) void; pub const setRunSpeed = zguiTe_EngineSetRunSpeed; extern fn zguiTe_EngineSetRunSpeed(engine: *TestEngine, speed: RunSpeed) void; pub const stop = zguiTe_Stop; extern fn zguiTe_Stop(engine: *TestEngine) void; pub const tryAbortEngine = zguiTe_TryAbortEngine; extern fn zguiTe_TryAbortEngine(engine: *TestEngine) void; pub const postSwap = zguiTe_PostSwap; extern fn zguiTe_PostSwap(engine: *TestEngine) void; pub const isTestQueueEmpty = zguiTe_IsTestQueueEmpty; extern fn zguiTe_IsTestQueueEmpty(engine: *TestEngine) bool; pub const getResult = zguiTe_GetResult; extern fn zguiTe_GetResult(engine: *TestEngine, count_tested: *c_int, count_success: *c_int) void; pub const printResultSummary = zguiTe_PrintResultSummary; extern fn zguiTe_PrintResultSummary(engine: *TestEngine) void; pub fn queueTests(engine: *TestEngine, group: TestGroup, filter_str: [:0]const u8, run_flags: TestRunFlags) void { zguiTe_QueueTests(engine, group, filter_str.ptr, run_flags); } extern fn zguiTe_QueueTests(engine: *TestEngine, group: TestGroup, filter_str: [*]const u8, run_flags: TestRunFlags) void; pub fn exportJunitResult(engine: *TestEngine, filename: [:0]const u8) void { zguiTe_EngineExportJunitResult(engine, filename.ptr); } extern fn zguiTe_EngineExportJunitResult(engine: *TestEngine, filename: [*]const u8) void; }; pub const TestContext = opaque { pub fn setRef(ctx: *TestContext, ref: [:0]const u8) void { return zguiTe_ContextSetRef(ctx, ref.ptr); } pub fn windowFocus(ctx: *TestContext, ref: [:0]const u8) void { return zguiTe_ContextWindowFocus(ctx, ref.ptr); } pub fn yield(ctx: *TestContext, frame_count: i32) void { return zguiTe_ContextYield(ctx, frame_count); } pub fn itemAction(ctx: *TestContext, action: Actions, ref: [:0]const u8, flags: TestOpFlags, action_arg: ?*anyopaque) void { return zguiTe_ContextItemAction(ctx, action, ref.ptr, flags, action_arg); } pub fn itemInputStrValue(ctx: *TestContext, ref: [:0]const u8, value: [:0]const u8) void { return zguiTe_ContextItemInputStrValue(ctx, ref.ptr, value.ptr); } pub fn itemInputIntValue(ctx: *TestContext, ref: [:0]const u8, value: i32) void { return zguiTe_ContextItemInputIntValue(ctx, ref.ptr, value); } pub fn itemInputFloatValue(ctx: *TestContext, ref: [:0]const u8, value: f32) void { return zguiTe_ContextItemInputFloatValue(ctx, ref.ptr, value); } pub fn menuAction(ctx: *TestContext, action: Actions, ref: [*]const u8) void { return zguiTe_ContextMenuAction(ctx, action, ref); } pub fn dragAndDrop(ctx: *TestContext, ref_src: [:0]const u8, ref_dst: [:0]const u8, button: zgui.MouseButton) void { return zguiTe_ContextDragAndDrop(ctx, ref_src.ptr, ref_dst.ptr, button); } pub fn keyDown(ctx: *TestContext, key_chord: c_int) void { return zguiTe_ContextKeyDown(ctx, key_chord); } pub fn keyUp(ctx: *TestContext, key_chord: c_int) void { return zguiTe_ContextKeyUp(ctx, key_chord); } extern fn zguiTe_ContextSetRef(ctx: *TestContext, ref: [*]const u8) void; extern fn zguiTe_ContextWindowFocus(ctx: *TestContext, ref: [*]const u8) void; extern fn zguiTe_ContextYield(ctx: *TestContext, frame_count: c_int) void; extern fn zguiTe_ContextMenuAction(ctx: *TestContext, action: Actions, ref: [*]const u8) void; extern fn zguiTe_ContextItemAction(ctx: *TestContext, action: Actions, ref: [*]const u8, flags: TestOpFlags, action_arg: ?*anyopaque) void; extern fn zguiTe_ContextItemInputStrValue(ctx: *TestContext, ref: [*]const u8, value: [*]const u8) void; extern fn zguiTe_ContextItemInputIntValue(ctx: *TestContext, ref: [*]const u8, value: i32) void; extern fn zguiTe_ContextItemInputFloatValue(ctx: *TestContext, ref: [*]const u8, value: f32) void; extern fn zguiTe_ContextDragAndDrop(ctx: *TestContext, ref_src: [*]const u8, ref_dst: [*]const u8, button: zgui.MouseButton) void; extern fn zguiTe_ContextKeyDown(ctx: *TestContext, key_chord: c_int) void; extern fn zguiTe_ContextKeyUp(ctx: *TestContext, key_chord: c_int) void; }; const ImGuiTestGuiFunc = fn (context: *TestContext) callconv(.C) void; const ImGuiTestTestFunc = fn (context: *TestContext) callconv(.C) void; pub const createContext = zguiTe_CreateContext; extern fn zguiTe_CreateContext() *TestEngine; pub const destroyContext = zguiTe_DestroyContext; extern fn zguiTe_DestroyContext(engine: *TestEngine) void; extern fn zguiTe_Check(filename: [*]const u8, func: [*]const u8, line: u32, flags: CheckFlags, resul: bool, expr: [*]const u8) bool; pub fn check(src: std.builtin.SourceLocation, flags: CheckFlags, resul: bool, expr: [:0]const u8) bool { return zguiTe_Check(src.file.ptr, src.fn_name.ptr, src.line, flags, resul, expr.ptr); } pub extern fn zguiTe_RegisterTest( engine: *TestEngine, category: [*]const u8, name: [*]const u8, src: [*]const u8, src_line: c_int, gui_fce: ?*const ImGuiTestGuiFunc, gui_test_fce: ?*const ImGuiTestTestFunc, ) *Test; pub fn checkTestError( src: std.builtin.SourceLocation, err: anyerror, ) void { var buff: [128:0]u8 = undefined; const msg = std.fmt.bufPrintZ(&buff, "Assert error: {}", .{err}) catch undefined; _ = zguiTe_Check(src.file.ptr, src.fn_name.ptr, src.line, .{}, false, msg.ptr); } var _te_engine: ?*TestEngine = null; pub fn getTestEngine() ?*TestEngine { return _te_engine; } pub fn init() void { _te_engine = createContext(); } pub fn deinit() void { destroyContext(_te_engine.?); }
0
repos/simulations/libs/zgui
repos/simulations/libs/zgui/src/backend_dx12.zig
pub const D3D12_CPU_DESCRIPTOR_HANDLE = extern struct { ptr: c_ulonglong, }; pub const D3D12_GPU_DESCRIPTOR_HANDLE = extern struct { ptr: c_ulonglong, }; pub fn init( device: *const anyopaque, // ID3D12Device num_frames_in_flight: u32, rtv_format: c_uint, // DXGI_FORMAT cbv_srv_heap: *const anyopaque, // ID3D12DescriptorHeap font_srv_cpu_desc_handle: D3D12_CPU_DESCRIPTOR_HANDLE, font_srv_gpu_desc_handle: D3D12_GPU_DESCRIPTOR_HANDLE, ) void { if (!ImGui_ImplDX12_Init( device, num_frames_in_flight, rtv_format, cbv_srv_heap, font_srv_cpu_desc_handle, font_srv_gpu_desc_handle, )) { @panic("failed to init d3d12 for imgui"); } } pub fn deinit() void { ImGui_ImplDX12_Shutdown(); } pub fn newFrame() void { ImGui_ImplDX12_NewFrame(); } pub fn render( draw_data: *const anyopaque, // *gui.DrawData gfx_command_list: *const anyopaque, // *ID3D12GraphicsCommandList ) void { ImGui_ImplDX12_RenderDrawData(draw_data, gfx_command_list); } // Those functions are defined in 'imgui_impl_dx12.cpp` // (they include few custom changes). extern fn ImGui_ImplDX12_Init( device: *const anyopaque, // ID3D12Device num_frames_in_flight: u32, rtv_format: u32, // DXGI_FORMAT cbv_srv_heap: *const anyopaque, // ID3D12DescriptorHeap font_srv_cpu_desc_handle: D3D12_CPU_DESCRIPTOR_HANDLE, font_srv_gpu_desc_handle: D3D12_GPU_DESCRIPTOR_HANDLE, ) bool; extern fn ImGui_ImplDX12_Shutdown() void; extern fn ImGui_ImplDX12_NewFrame() void; extern fn ImGui_ImplDX12_RenderDrawData( draw_data: *const anyopaque, // *ImDrawData graphics_command_list: *const anyopaque, // *ID3D12GraphicsCommandList ) void;
0
repos/simulations/libs/zgui
repos/simulations/libs/zgui/src/zgui.cpp
#include "imgui.h" #if ZGUI_IMPLOT #include "implot.h" #endif #if ZGUI_TE #include "imgui_te_engine.h" #include "imgui_te_context.h" #include "imgui_te_ui.h" #include "imgui_te_utils.h" #include "imgui_te_exporters.h" #endif #include "imgui_internal.h" #ifndef ZGUI_API #define ZGUI_API #endif extern "C" { /* #include <stdio.h> ZGUI_API float zguiGetFloatMin(void) { printf("__FLT_MIN__ %.32e\n", __FLT_MIN__); return __FLT_MIN__; } ZGUI_API float zguiGetFloatMax(void) { printf("__FLT_MAX__ %.32e\n", __FLT_MAX__); return __FLT_MAX__; } */ ZGUI_API void zguiSetAllocatorFunctions( void* (*alloc_func)(size_t, void*), void (*free_func)(void*, void*) ) { ImGui::SetAllocatorFunctions(alloc_func, free_func, nullptr); } ZGUI_API void zguiSetNextWindowPos(float x, float y, ImGuiCond cond, float pivot_x, float pivot_y) { ImGui::SetNextWindowPos({ x, y }, cond, { pivot_x, pivot_y }); } ZGUI_API void zguiSetNextWindowSize(float w, float h, ImGuiCond cond) { ImGui::SetNextWindowSize({ w, h }, cond); } ZGUI_API void zguiSetNextWindowCollapsed(bool collapsed, ImGuiCond cond) { ImGui::SetNextWindowCollapsed(collapsed, cond); } ZGUI_API void zguiSetNextWindowFocus(void) { ImGui::SetNextWindowFocus(); } ZGUI_API void zguiSetNextWindowBgAlpha(float alpha) { ImGui::SetNextWindowBgAlpha(alpha); } ZGUI_API void zguiSetWindowFocus(const char* name) { ImGui::SetWindowFocus(name); } ZGUI_API void zguiSetKeyboardFocusHere(int offset) { ImGui::SetKeyboardFocusHere(offset); } ZGUI_API bool zguiBegin(const char* name, bool* p_open, ImGuiWindowFlags flags) { return ImGui::Begin(name, p_open, flags); } ZGUI_API void zguiEnd(void) { ImGui::End(); } ZGUI_API bool zguiBeginChild(const char* str_id, float w, float h, ImGuiChildFlags child_flags, ImGuiWindowFlags window_flags) { return ImGui::BeginChild(str_id, { w, h }, child_flags, window_flags); } ZGUI_API bool zguiBeginChildId(ImGuiID id, float w, float h, ImGuiChildFlags child_flags, ImGuiWindowFlags window_flags) { return ImGui::BeginChild(id, { w, h }, child_flags, window_flags); } ZGUI_API void zguiEndChild(void) { ImGui::EndChild(); } ZGUI_API float zguiGetScrollX(void) { return ImGui::GetScrollX(); } ZGUI_API float zguiGetScrollY(void) { return ImGui::GetScrollY(); } ZGUI_API void zguiSetScrollX(float scroll_x) { ImGui::SetScrollX(scroll_x); } ZGUI_API void zguiSetScrollY(float scroll_y) { ImGui::SetScrollY(scroll_y); } ZGUI_API float zguiGetScrollMaxX(void) { return ImGui::GetScrollMaxX(); } ZGUI_API float zguiGetScrollMaxY(void) { return ImGui::GetScrollMaxY(); } ZGUI_API void zguiSetScrollHereX(float center_x_ratio) { ImGui::SetScrollHereX(center_x_ratio); } ZGUI_API void zguiSetScrollHereY(float center_y_ratio) { ImGui::SetScrollHereY(center_y_ratio); } ZGUI_API void zguiSetScrollFromPosX(float local_x, float center_x_ratio) { ImGui::SetScrollFromPosX(local_x, center_x_ratio); } ZGUI_API void zguiSetScrollFromPosY(float local_y, float center_y_ratio) { ImGui::SetScrollFromPosY(local_y, center_y_ratio); } ZGUI_API bool zguiIsWindowAppearing(void) { return ImGui::IsWindowAppearing(); } ZGUI_API bool zguiIsWindowCollapsed(void) { return ImGui::IsWindowCollapsed(); } ZGUI_API bool zguiIsWindowFocused(ImGuiFocusedFlags flags) { return ImGui::IsWindowFocused(flags); } ZGUI_API bool zguiIsWindowHovered(ImGuiHoveredFlags flags) { return ImGui::IsWindowHovered(flags); } ZGUI_API void zguiGetWindowPos(float pos[2]) { const ImVec2 p = ImGui::GetWindowPos(); pos[0] = p.x; pos[1] = p.y; } ZGUI_API void zguiGetWindowSize(float size[2]) { const ImVec2 s = ImGui::GetWindowSize(); size[0] = s.x; size[1] = s.y; } ZGUI_API float zguiGetWindowWidth(void) { return ImGui::GetWindowWidth(); } ZGUI_API float zguiGetWindowHeight(void) { return ImGui::GetWindowHeight(); } ZGUI_API void zguiGetMouseDragDelta(ImGuiMouseButton button, float lock_threshold, float delta[2]) { const ImVec2 d = ImGui::GetMouseDragDelta(button, lock_threshold); delta[0] = d.x; delta[1] = d.y; } ZGUI_API void zguiResetMouseDragDelta(ImGuiMouseButton button) { ImGui::ResetMouseDragDelta(button); } ZGUI_API void zguiSpacing(void) { ImGui::Spacing(); } ZGUI_API void zguiNewLine(void) { ImGui::NewLine(); } ZGUI_API void zguiIndent(float indent_w) { ImGui::Indent(indent_w); } ZGUI_API void zguiUnindent(float indent_w) { ImGui::Unindent(indent_w); } ZGUI_API void zguiSeparator(void) { ImGui::Separator(); } ZGUI_API void zguiSeparatorText(const char* label) { ImGui::SeparatorText(label); } ZGUI_API void zguiSameLine(float offset_from_start_x, float spacing) { ImGui::SameLine(offset_from_start_x, spacing); } ZGUI_API void zguiDummy(float w, float h) { ImGui::Dummy({ w, h }); } ZGUI_API void zguiBeginGroup(void) { ImGui::BeginGroup(); } ZGUI_API void zguiEndGroup(void) { ImGui::EndGroup(); } ZGUI_API void zguiGetItemRectMax(float rect[2]) { const ImVec2 r = ImGui::GetItemRectMax(); rect[0] = r.x; rect[1] = r.y; } ZGUI_API void zguiGetItemRectMin(float rect[2]) { const ImVec2 r = ImGui::GetItemRectMin(); rect[0] = r.x; rect[1] = r.y; } ZGUI_API void zguiGetItemRectSize(float rect[2]) { const ImVec2 r = ImGui::GetItemRectSize(); rect[0] = r.x; rect[1] = r.y; } ZGUI_API void zguiGetCursorPos(float pos[2]) { const ImVec2 p = ImGui::GetCursorPos(); pos[0] = p.x; pos[1] = p.y; } ZGUI_API float zguiGetCursorPosX(void) { return ImGui::GetCursorPosX(); } ZGUI_API float zguiGetCursorPosY(void) { return ImGui::GetCursorPosY(); } ZGUI_API void zguiSetCursorPos(float local_x, float local_y) { ImGui::SetCursorPos({ local_x, local_y }); } ZGUI_API void zguiSetCursorPosX(float local_x) { ImGui::SetCursorPosX(local_x); } ZGUI_API void zguiSetCursorPosY(float local_y) { ImGui::SetCursorPosY(local_y); } ZGUI_API void zguiGetCursorStartPos(float pos[2]) { const ImVec2 p = ImGui::GetCursorStartPos(); pos[0] = p.x; pos[1] = p.y; } ZGUI_API void zguiGetCursorScreenPos(float pos[2]) { const ImVec2 p = ImGui::GetCursorScreenPos(); pos[0] = p.x; pos[1] = p.y; } ZGUI_API void zguiSetCursorScreenPos(float screen_x, float screen_y) { ImGui::SetCursorScreenPos({ screen_x, screen_y }); } ZGUI_API int zguiGetMouseCursor(void) { return ImGui::GetMouseCursor(); } ZGUI_API void zguiSetMouseCursor(int cursor) { ImGui::SetMouseCursor(cursor); } ZGUI_API void zguiGetMousePos(float pos[2]) { const ImVec2 p = ImGui::GetMousePos(); pos[0] = p.x; pos[1] = p.y; } ZGUI_API void zguiAlignTextToFramePadding(void) { ImGui::AlignTextToFramePadding(); } ZGUI_API float zguiGetTextLineHeight(void) { return ImGui::GetTextLineHeight(); } ZGUI_API float zguiGetTextLineHeightWithSpacing(void) { return ImGui::GetTextLineHeightWithSpacing(); } ZGUI_API float zguiGetFrameHeight(void) { return ImGui::GetFrameHeight(); } ZGUI_API float zguiGetFrameHeightWithSpacing(void) { return ImGui::GetFrameHeightWithSpacing(); } ZGUI_API bool zguiDragFloat( const char* label, float* v, float v_speed, float v_min, float v_max, const char* format, ImGuiSliderFlags flags ) { return ImGui::DragFloat(label, v, v_speed, v_min, v_max, format, flags); } ZGUI_API bool zguiDragFloat2( const char* label, float v[2], float v_speed, float v_min, float v_max, const char* format, ImGuiSliderFlags flags ) { return ImGui::DragFloat2(label, v, v_speed, v_min, v_max, format, flags); } ZGUI_API bool zguiDragFloat3( const char* label, float v[3], float v_speed, float v_min, float v_max, const char* format, ImGuiSliderFlags flags ) { return ImGui::DragFloat3(label, v, v_speed, v_min, v_max, format, flags); } ZGUI_API bool zguiDragFloat4( const char* label, float v[4], float v_speed, float v_min, float v_max, const char* format, ImGuiSliderFlags flags ) { return ImGui::DragFloat4(label, v, v_speed, v_min, v_max, format, flags); } ZGUI_API bool zguiDragFloatRange2( const char* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* format, const char* format_max, ImGuiSliderFlags flags ) { return ImGui::DragFloatRange2( label, v_current_min, v_current_max, v_speed, v_min, v_max, format, format_max, flags ); } ZGUI_API bool zguiDragInt( const char* label, int* v, float v_speed, int v_min, int v_max, const char* format, ImGuiSliderFlags flags ) { return ImGui::DragInt(label, v, v_speed, v_min, v_max, format, flags); } ZGUI_API bool zguiDragInt2( const char* label, int v[2], float v_speed, int v_min, int v_max, const char* format, ImGuiSliderFlags flags ) { return ImGui::DragInt2(label, v, v_speed, v_min, v_max, format, flags); } ZGUI_API bool zguiDragInt3( const char* label, int v[3], float v_speed, int v_min, int v_max, const char* format, ImGuiSliderFlags flags ) { return ImGui::DragInt3(label, v, v_speed, v_min, v_max, format, flags); } ZGUI_API bool zguiDragInt4( const char* label, int v[4], float v_speed, int v_min, int v_max, const char* format, ImGuiSliderFlags flags ) { return ImGui::DragInt4(label, v, v_speed, v_min, v_max, format, flags); } ZGUI_API bool zguiDragIntRange2( const char* label, int* v_current_min, int* v_current_max, float v_speed, int v_min, int v_max, const char* format, const char* format_max, ImGuiSliderFlags flags ) { return ImGui::DragIntRange2( label, v_current_min, v_current_max, v_speed, v_min, v_max, format, format_max, flags ); } ZGUI_API bool zguiDragScalar( const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags ) { return ImGui::DragScalar(label, data_type, p_data, v_speed, p_min, p_max, format, flags); } ZGUI_API bool zguiDragScalarN( const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags ) { return ImGui::DragScalarN(label, data_type, p_data, components, v_speed, p_min, p_max, format, flags); } ZGUI_API bool zguiBeginDragDropSource(ImGuiDragDropFlags flags = 0) { return ImGui::BeginDragDropSource(flags); } ZGUI_API bool zguiSetDragDropPayload( const char* type, const void* data, size_t sz, ImGuiCond cond = 0 ) { return ImGui::SetDragDropPayload(type, data, sz, cond); } ZGUI_API void zguiEndDragDropSource() { return ImGui::EndDragDropSource(); } ZGUI_API bool zguiBeginDragDropTarget() { return ImGui::BeginDragDropTarget(); } ZGUI_API const ImGuiPayload* zguiAcceptDragDropPayload( const char* type, ImGuiDragDropFlags flags = 0 ) { return ImGui::AcceptDragDropPayload(type); } ZGUI_API void zguiEndDragDropTarget() { return ImGui::EndDragDropTarget(); } ZGUI_API const ImGuiPayload* zguiGetDragDropPayload() { return ImGui::GetDragDropPayload(); } ZGUI_API void zguiImGuiPayload_Clear(ImGuiPayload* payload) { payload->Clear(); } ZGUI_API bool zguiImGuiPayload_IsDataType(const ImGuiPayload* payload, const char* type) { return payload->IsDataType(type); } ZGUI_API bool zguiImGuiPayload_IsPreview(const ImGuiPayload* payload) { return payload->IsPreview(); } ZGUI_API bool zguiImGuiPayload_IsDelivery(const ImGuiPayload* payload) { return payload->IsDelivery(); } ZGUI_API bool zguiCombo( const char* label, int* current_item, const char* items_separated_by_zeros, int popup_max_height_in_items ) { return ImGui::Combo(label, current_item, items_separated_by_zeros, popup_max_height_in_items); } ZGUI_API bool zguiBeginCombo(const char* label, const char* preview_value, ImGuiComboFlags flags) { return ImGui::BeginCombo(label, preview_value, flags); } ZGUI_API void zguiEndCombo(void) { ImGui::EndCombo(); } ZGUI_API bool zguiBeginListBox(const char* label, float w, float h) { return ImGui::BeginListBox(label, { w, h }); } ZGUI_API void zguiEndListBox(void) { ImGui::EndListBox(); } ZGUI_API bool zguiSelectable(const char* label, bool selected, ImGuiSelectableFlags flags, float w, float h) { return ImGui::Selectable(label, selected, flags, { w, h }); } ZGUI_API bool zguiSelectableStatePtr( const char* label, bool* p_selected, ImGuiSelectableFlags flags, float w, float h ) { return ImGui::Selectable(label, p_selected, flags, { w, h }); } ZGUI_API bool zguiSliderFloat( const char* label, float* v, float v_min, float v_max, const char* format, ImGuiSliderFlags flags ) { return ImGui::SliderFloat(label, v, v_min, v_max, format, flags); } ZGUI_API bool zguiSliderFloat2( const char* label, float v[2], float v_min, float v_max, const char* format, ImGuiSliderFlags flags ) { return ImGui::SliderFloat2(label, v, v_min, v_max, format, flags); } ZGUI_API bool zguiSliderFloat3( const char* label, float v[3], float v_min, float v_max, const char* format, ImGuiSliderFlags flags ) { return ImGui::SliderFloat3(label, v, v_min, v_max, format, flags); } ZGUI_API bool zguiSliderFloat4( const char* label, float v[4], float v_min, float v_max, const char* format, ImGuiSliderFlags flags ) { return ImGui::SliderFloat4(label, v, v_min, v_max, format, flags); } ZGUI_API bool zguiSliderInt( const char* label, int* v, int v_min, int v_max, const char* format, ImGuiSliderFlags flags ) { return ImGui::SliderInt(label, v, v_min, v_max, format, flags); } ZGUI_API bool zguiSliderInt2( const char* label, int v[2], int v_min, int v_max, const char* format, ImGuiSliderFlags flags ) { return ImGui::SliderInt2(label, v, v_min, v_max, format, flags); } ZGUI_API bool zguiSliderInt3( const char* label, int v[3], int v_min, int v_max, const char* format, ImGuiSliderFlags flags ) { return ImGui::SliderInt3(label, v, v_min, v_max, format, flags); } ZGUI_API bool zguiSliderInt4( const char* label, int v[4], int v_min, int v_max, const char* format, ImGuiSliderFlags flags ) { return ImGui::SliderInt4(label, v, v_min, v_max, format, flags); } ZGUI_API bool zguiSliderScalar( const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags ) { return ImGui::SliderScalar(label, data_type, p_data, p_min, p_max, format, flags); } ZGUI_API bool zguiSliderScalarN( const char* label, ImGuiDataType data_type, void* p_data, int components, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags ) { return ImGui::SliderScalarN(label, data_type, p_data, components, p_min, p_max, format, flags); } ZGUI_API bool zguiVSliderFloat( const char* label, float w, float h, float* v, float v_min, float v_max, const char* format, ImGuiSliderFlags flags ) { return ImGui::VSliderFloat(label, { w, h }, v, v_min, v_max, format, flags); } ZGUI_API bool zguiVSliderInt( const char* label, float w, float h, int* v, int v_min, int v_max, const char* format, ImGuiSliderFlags flags ) { return ImGui::VSliderInt(label, { w, h }, v, v_min, v_max, format, flags); } ZGUI_API bool zguiVSliderScalar( const char* label, float w, float h, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags ) { return ImGui::VSliderScalar(label, { w, h }, data_type, p_data, p_min, p_max, format, flags); } ZGUI_API bool zguiSliderAngle( const char* label, float* v_rad, float v_degrees_min, float v_degrees_max, const char* format, ImGuiSliderFlags flags ) { return ImGui::SliderAngle(label, v_rad, v_degrees_min, v_degrees_max, format, flags); } ZGUI_API ImGuiInputTextCallbackData zguiInputTextCallbackData_Init(void) { return ImGuiInputTextCallbackData(); } ZGUI_API void zguiInputTextCallbackData_DeleteChars( ImGuiInputTextCallbackData* data, int pos, int bytes_count ) { data->DeleteChars(pos, bytes_count); } ZGUI_API void zguiInputTextCallbackData_InsertChars( ImGuiInputTextCallbackData* data, int pos, const char* text, const char* text_end ) { data->InsertChars(pos, text, text_end); } ZGUI_API bool zguiInputText( const char* label, char* buf, size_t buf_size, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data ) { return ImGui::InputText(label, buf, buf_size, flags, callback, user_data); } ZGUI_API bool zguiInputTextMultiline( const char* label, char* buf, size_t buf_size, float w, float h, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data ) { return ImGui::InputTextMultiline(label, buf, buf_size, { w, h }, flags, callback, user_data); } ZGUI_API bool zguiInputTextWithHint( const char* label, const char* hint, char* buf, size_t buf_size, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data ) { return ImGui::InputTextWithHint(label, hint, buf, buf_size, flags, callback, user_data); } ZGUI_API bool zguiInputFloat( const char* label, float* v, float step, float step_fast, const char* format, ImGuiInputTextFlags flags ) { return ImGui::InputFloat(label, v, step, step_fast, format, flags); } ZGUI_API bool zguiInputFloat2( const char* label, float v[2], const char* format, ImGuiInputTextFlags flags ) { return ImGui::InputFloat2(label, v, format, flags); } ZGUI_API bool zguiInputFloat3( const char* label, float v[3], const char* format, ImGuiInputTextFlags flags ) { return ImGui::InputFloat3(label, v, format, flags); } ZGUI_API bool zguiInputFloat4( const char* label, float v[4], const char* format, ImGuiInputTextFlags flags ) { return ImGui::InputFloat4(label, v, format, flags); } ZGUI_API bool zguiInputInt( const char* label, int* v, int step, int step_fast, ImGuiInputTextFlags flags ) { return ImGui::InputInt(label, v, step, step_fast, flags); } ZGUI_API bool zguiInputInt2(const char* label, int v[2], ImGuiInputTextFlags flags) { return ImGui::InputInt2(label, v, flags); } ZGUI_API bool zguiInputInt3(const char* label, int v[3], ImGuiInputTextFlags flags) { return ImGui::InputInt3(label, v, flags); } ZGUI_API bool zguiInputInt4(const char* label, int v[4], ImGuiInputTextFlags flags) { return ImGui::InputInt4(label, v, flags); } ZGUI_API bool zguiInputDouble( const char* label, double* v, double step, double step_fast, const char* format, ImGuiInputTextFlags flags ) { return ImGui::InputDouble(label, v, step, step_fast, format, flags); } ZGUI_API bool zguiInputScalar( const char* label, ImGuiDataType data_type, void* p_data, const void* p_step, const void* p_step_fast, const char* format, ImGuiInputTextFlags flags ) { return ImGui::InputScalar(label, data_type, p_data, p_step, p_step_fast, format, flags); } ZGUI_API bool zguiInputScalarN( const char* label, ImGuiDataType data_type, void* p_data, int components, const void* p_step, const void* p_step_fast, const char* format, ImGuiInputTextFlags flags ) { return ImGui::InputScalarN(label, data_type, p_data, components, p_step, p_step_fast, format, flags); } ZGUI_API bool zguiColorEdit3(const char* label, float col[3], ImGuiColorEditFlags flags) { return ImGui::ColorEdit3(label, col, flags); } ZGUI_API bool zguiColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags) { return ImGui::ColorEdit4(label, col, flags); } ZGUI_API bool zguiColorPicker3(const char* label, float col[3], ImGuiColorEditFlags flags) { return ImGui::ColorPicker3(label, col, flags); } ZGUI_API bool zguiColorPicker4(const char* label, float col[4], ImGuiColorEditFlags flags, const float* ref_col) { return ImGui::ColorPicker4(label, col, flags, ref_col); } ZGUI_API bool zguiColorButton(const char* desc_id, const float col[4], ImGuiColorEditFlags flags, float w, float h) { return ImGui::ColorButton(desc_id, { col[0], col[1], col[2], col[3] }, flags, { w, h }); } ZGUI_API void zguiTextUnformatted(const char* text, const char* text_end) { ImGui::TextUnformatted(text, text_end); } ZGUI_API void zguiTextColored(const float col[4], const char* fmt, ...) { va_list args; va_start(args, fmt); ImGui::TextColoredV({ col[0], col[1], col[2], col[3] }, fmt, args); va_end(args); } ZGUI_API void zguiTextDisabled(const char* fmt, ...) { va_list args; va_start(args, fmt); ImGui::TextDisabledV(fmt, args); va_end(args); } ZGUI_API void zguiTextWrapped(const char* fmt, ...) { va_list args; va_start(args, fmt); ImGui::TextWrappedV(fmt, args); va_end(args); } ZGUI_API void zguiBulletText(const char* fmt, ...) { va_list args; va_start(args, fmt); ImGui::BulletTextV(fmt, args); va_end(args); } ZGUI_API void zguiLabelText(const char* label, const char* fmt, ...) { va_list args; va_start(args, fmt); ImGui::LabelTextV(label, fmt, args); va_end(args); } ZGUI_API void zguiCalcTextSize( const char* txt, const char* txt_end, bool hide_text_after_double_hash, float wrap_width, float* out_w, float* out_h ) { assert(out_w && out_h); const ImVec2 s = ImGui::CalcTextSize(txt, txt_end, hide_text_after_double_hash, wrap_width); *out_w = s.x; *out_h = s.y; } ZGUI_API bool zguiButton(const char* label, float x, float y) { return ImGui::Button(label, { x, y }); } ZGUI_API bool zguiSmallButton(const char* label) { return ImGui::SmallButton(label); } ZGUI_API bool zguiInvisibleButton(const char* str_id, float w, float h, ImGuiButtonFlags flags) { return ImGui::InvisibleButton(str_id, { w, h }, flags); } ZGUI_API bool zguiArrowButton(const char* str_id, ImGuiDir dir) { return ImGui::ArrowButton(str_id, dir); } ZGUI_API void zguiImage( ImTextureID user_texture_id, float w, float h, const float uv0[2], const float uv1[2], const float tint_col[4], const float border_col[4] ) { ImGui::Image( user_texture_id, { w, h }, { uv0[0], uv0[1] }, { uv1[0], uv1[1] }, { tint_col[0], tint_col[1], tint_col[2], tint_col[3] }, { border_col[0], border_col[1], border_col[2], border_col[3] } ); } ZGUI_API bool zguiImageButton( const char* str_id, ImTextureID user_texture_id, float w, float h, const float uv0[2], const float uv1[2], const float bg_col[4], const float tint_col[4] ) { return ImGui::ImageButton( str_id, user_texture_id, { w, h }, { uv0[0], uv0[1] }, { uv1[0], uv1[1] }, { bg_col[0], bg_col[1], bg_col[2], bg_col[3] }, { tint_col[0], tint_col[1], tint_col[2], tint_col[3] } ); } ZGUI_API void zguiBullet(void) { ImGui::Bullet(); } ZGUI_API bool zguiRadioButton(const char* label, bool active) { return ImGui::RadioButton(label, active); } ZGUI_API bool zguiRadioButtonStatePtr(const char* label, int* v, int v_button) { return ImGui::RadioButton(label, v, v_button); } ZGUI_API bool zguiCheckbox(const char* label, bool* v) { return ImGui::Checkbox(label, v); } ZGUI_API bool zguiCheckboxBits(const char* label, unsigned int* bits, unsigned int bits_value) { return ImGui::CheckboxFlags(label, bits, bits_value); } ZGUI_API void zguiProgressBar(float fraction, float w, float h, const char* overlay) { return ImGui::ProgressBar(fraction, { w, h }, overlay); } ZGUI_API ImGuiContext* zguiCreateContext(ImFontAtlas* shared_font_atlas) { return ImGui::CreateContext(shared_font_atlas); } ZGUI_API void zguiDestroyContext(ImGuiContext* ctx) { ImGui::DestroyContext(ctx); } ZGUI_API ImGuiContext* zguiGetCurrentContext(void) { return ImGui::GetCurrentContext(); } ZGUI_API void zguiSetCurrentContext(ImGuiContext* ctx) { ImGui::SetCurrentContext(ctx); } ZGUI_API void zguiNewFrame(void) { ImGui::NewFrame(); } ZGUI_API void zguiRender(void) { ImGui::Render(); } ZGUI_API ImDrawData* zguiGetDrawData(void) { return ImGui::GetDrawData(); } ZGUI_API void zguiShowDemoWindow(bool* p_open) { ImGui::ShowDemoWindow(p_open); } ZGUI_API void zguiBeginDisabled(bool disabled) { ImGui::BeginDisabled(disabled); } ZGUI_API void zguiEndDisabled(void) { ImGui::EndDisabled(); } ZGUI_API ImGuiStyle* zguiGetStyle(void) { return &ImGui::GetStyle(); } ZGUI_API ImGuiStyle zguiStyle_Init(void) { return ImGuiStyle(); } ZGUI_API void zguiStyle_ScaleAllSizes(ImGuiStyle* style, float scale_factor) { style->ScaleAllSizes(scale_factor); } ZGUI_API void zguiPushStyleColor4f(ImGuiCol idx, const float col[4]) { ImGui::PushStyleColor(idx, { col[0], col[1], col[2], col[3] }); } ZGUI_API void zguiPushStyleColor1u(ImGuiCol idx, ImU32 col) { ImGui::PushStyleColor(idx, col); } ZGUI_API void zguiPopStyleColor(int count) { ImGui::PopStyleColor(count); } ZGUI_API void zguiPushStyleVar1f(ImGuiStyleVar idx, float var) { ImGui::PushStyleVar(idx, var); } ZGUI_API void zguiPushStyleVar2f(ImGuiStyleVar idx, const float var[2]) { ImGui::PushStyleVar(idx, { var[0], var[1] }); } ZGUI_API void zguiPopStyleVar(int count) { ImGui::PopStyleVar(count); } ZGUI_API void zguiPushItemWidth(float item_width) { ImGui::PushItemWidth(item_width); } ZGUI_API void zguiPopItemWidth(void) { ImGui::PopItemWidth(); } ZGUI_API void zguiSetNextItemWidth(float item_width) { ImGui::SetNextItemWidth(item_width); } ZGUI_API void zguiSetItemDefaultFocus(void) { ImGui::SetItemDefaultFocus(); } ZGUI_API ImFont* zguiGetFont(void) { return ImGui::GetFont(); } ZGUI_API float zguiGetFontSize(void) { return ImGui::GetFontSize(); } ZGUI_API void zguiGetFontTexUvWhitePixel(float uv[2]) { const ImVec2 cs = ImGui::GetFontTexUvWhitePixel(); uv[0] = cs[0]; uv[1] = cs[1]; } ZGUI_API void zguiPushFont(ImFont* font) { ImGui::PushFont(font); } ZGUI_API void zguiPopFont(void) { ImGui::PopFont(); } ZGUI_API bool zguiTreeNode(const char* label) { return ImGui::TreeNode(label); } ZGUI_API bool zguiTreeNodeFlags(const char* label, ImGuiTreeNodeFlags flags) { return ImGui::TreeNodeEx(label, flags); } ZGUI_API bool zguiTreeNodeStrId(const char* str_id, const char* fmt, ...) { va_list args; va_start(args, fmt); const bool ret = ImGui::TreeNodeV(str_id, fmt, args); va_end(args); return ret; } ZGUI_API bool zguiTreeNodeStrIdFlags(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) { va_list args; va_start(args, fmt); const bool ret = ImGui::TreeNodeExV(str_id, flags, fmt, args); va_end(args); return ret; } ZGUI_API bool zguiTreeNodePtrId(const void* ptr_id, const char* fmt, ...) { va_list args; va_start(args, fmt); const bool ret = ImGui::TreeNodeV(ptr_id, fmt, args); va_end(args); return ret; } ZGUI_API bool zguiTreeNodePtrIdFlags(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) { va_list args; va_start(args, fmt); const bool ret = ImGui::TreeNodeExV(ptr_id, flags, fmt, args); va_end(args); return ret; } ZGUI_API bool zguiCollapsingHeader(const char* label, ImGuiTreeNodeFlags flags) { return ImGui::CollapsingHeader(label, flags); } ZGUI_API bool zguiCollapsingHeaderStatePtr(const char* label, bool* p_visible, ImGuiTreeNodeFlags flags) { return ImGui::CollapsingHeader(label, p_visible, flags); } ZGUI_API void zguiSetNextItemOpen(bool is_open, ImGuiCond cond) { ImGui::SetNextItemOpen(is_open, cond); } ZGUI_API void zguiTreePushStrId(const char* str_id) { ImGui::TreePush(str_id); } ZGUI_API void zguiTreePushPtrId(const void* ptr_id) { ImGui::TreePush(ptr_id); } ZGUI_API void zguiTreePop(void) { ImGui::TreePop(); } ZGUI_API void zguiPushStrId(const char* str_id_begin, const char* str_id_end) { ImGui::PushID(str_id_begin, str_id_end); } ZGUI_API void zguiPushStrIdZ(const char* str_id) { ImGui::PushID(str_id); } ZGUI_API void zguiPushPtrId(const void* ptr_id) { ImGui::PushID(ptr_id); } ZGUI_API void zguiPushIntId(int int_id) { ImGui::PushID(int_id); } ZGUI_API void zguiPopId(void) { ImGui::PopID(); } ZGUI_API ImGuiID zguiGetStrId(const char* str_id_begin, const char* str_id_end) { return ImGui::GetID(str_id_begin, str_id_end); } ZGUI_API ImGuiID zguiGetStrIdZ(const char* str_id) { return ImGui::GetID(str_id); } ZGUI_API ImGuiID zguiGetPtrId(const void* ptr_id) { return ImGui::GetID(ptr_id); } ZGUI_API void zguiSetClipboardText(const char* text) { ImGui::SetClipboardText(text); } ZGUI_API const char* zguiGetClipboardText(void) { return ImGui::GetClipboardText(); } ZGUI_API ImFont* zguiIoAddFontFromFileWithConfig( const char* filename, float size_pixels, const ImFontConfig* config, const ImWchar* ranges ) { return ImGui::GetIO().Fonts->AddFontFromFileTTF(filename, size_pixels, config, ranges); } ZGUI_API ImFont* zguiIoAddFontFromFile(const char* filename, float size_pixels) { return ImGui::GetIO().Fonts->AddFontFromFileTTF(filename, size_pixels, nullptr, nullptr); } ZGUI_API ImFont* zguiIoAddFontFromMemoryWithConfig( void* font_data, int font_size, float size_pixels, const ImFontConfig* config, const ImWchar* ranges ) { return ImGui::GetIO().Fonts->AddFontFromMemoryTTF(font_data, font_size, size_pixels, config, ranges); } ZGUI_API ImFont* zguiIoAddFontFromMemory(void* font_data, int font_size, float size_pixels) { ImFontConfig config = ImFontConfig(); config.FontDataOwnedByAtlas = false; return ImGui::GetIO().Fonts->AddFontFromMemoryTTF(font_data, font_size, size_pixels, &config, nullptr); } ZGUI_API ImFontConfig zguiFontConfig_Init(void) { return ImFontConfig(); } ZGUI_API ImFont* zguiIoGetFont(unsigned int index) { return ImGui::GetIO().Fonts->Fonts[index]; } ZGUI_API void zguiIoSetDefaultFont(ImFont* font) { ImGui::GetIO().FontDefault = font; } ZGUI_API unsigned char *zguiIoGetFontsTexDataAsRgba32(int *width, int *height) { unsigned char *font_pixels; int font_width, font_height; ImGui::GetIO().Fonts->GetTexDataAsRGBA32(&font_pixels, &font_width, &font_height); *width = font_width; *height = font_height; return font_pixels; } ZGUI_API void zguiIoSetFontsTexId(ImTextureID id) { ImGui::GetIO().Fonts->TexID = id; } ZGUI_API ImTextureID zguiIoGetFontsTexId(void) { return ImGui::GetIO().Fonts->TexID; } ZGUI_API void zguiIoSetConfigWindowsMoveFromTitleBarOnly(bool enabled) { ImGui::GetIO().ConfigWindowsMoveFromTitleBarOnly = enabled; } ZGUI_API bool zguiIoGetWantCaptureMouse(void) { return ImGui::GetIO().WantCaptureMouse; } ZGUI_API bool zguiIoGetWantCaptureKeyboard(void) { return ImGui::GetIO().WantCaptureKeyboard; } ZGUI_API bool zguiIoGetWantTextInput(void) { return ImGui::GetIO().WantTextInput; } ZGUI_API void zguiIoSetIniFilename(const char* filename) { ImGui::GetIO().IniFilename = filename; } ZGUI_API void zguiIoSetConfigFlags(ImGuiConfigFlags flags) { ImGui::GetIO().ConfigFlags = flags; } ZGUI_API void zguiIoSetDisplaySize(float width, float height) { ImGui::GetIO().DisplaySize = { width, height }; } ZGUI_API void zguiIoGetDisplaySize(float size[2]) { const ImVec2 ds = ImGui::GetIO().DisplaySize; size[0] = ds[0]; size[1] = ds[1]; } ZGUI_API void zguiIoSetDisplayFramebufferScale(float sx, float sy) { ImGui::GetIO().DisplayFramebufferScale = { sx, sy }; } ZGUI_API void zguiIoSetDeltaTime(float delta_time) { ImGui::GetIO().DeltaTime = delta_time; } ZGUI_API void zguiIoAddFocusEvent(bool focused) { ImGui::GetIO().AddFocusEvent(focused); } ZGUI_API void zguiIoAddMousePositionEvent(float x, float y) { ImGui::GetIO().AddMousePosEvent(x, y); } ZGUI_API void zguiIoAddMouseButtonEvent(ImGuiMouseButton button, bool down) { ImGui::GetIO().AddMouseButtonEvent(button, down); } ZGUI_API void zguiIoAddMouseWheelEvent(float x, float y) { ImGui::GetIO().AddMouseWheelEvent(x, y); } ZGUI_API void zguiIoAddKeyEvent(ImGuiKey key, bool down) { ImGui::GetIO().AddKeyEvent(key, down); } ZGUI_API void zguiIoAddInputCharactersUTF8(const char* utf8_chars) { ImGui::GetIO().AddInputCharactersUTF8(utf8_chars); } ZGUI_API void zguiIoSetKeyEventNativeData(ImGuiKey key, int keycode, int scancode) { ImGui::GetIO().SetKeyEventNativeData(key, keycode, scancode); } ZGUI_API void zguiIoAddCharacterEvent(unsigned int c) { ImGui::GetIO().AddInputCharacter(c); } ZGUI_API bool zguiIsItemHovered(ImGuiHoveredFlags flags) { return ImGui::IsItemHovered(flags); } ZGUI_API bool zguiIsItemActive(void) { return ImGui::IsItemActive(); } ZGUI_API bool zguiIsItemFocused(void) { return ImGui::IsItemFocused(); } ZGUI_API bool zguiIsItemClicked(ImGuiMouseButton mouse_button) { return ImGui::IsItemClicked(mouse_button); } ZGUI_API bool zguiIsMouseDown(ImGuiMouseButton button) { return ImGui::IsMouseDown(button); } ZGUI_API bool zguiIsMouseClicked(ImGuiMouseButton button) { return ImGui::IsMouseClicked(button); } ZGUI_API bool zguiIsMouseDoubleClicked(ImGuiMouseButton button) { return ImGui::IsMouseDoubleClicked(button); } ZGUI_API bool zguiIsItemVisible(void) { return ImGui::IsItemVisible(); } ZGUI_API bool zguiIsItemEdited(void) { return ImGui::IsItemEdited(); } ZGUI_API bool zguiIsItemActivated(void) { return ImGui::IsItemActivated(); } ZGUI_API bool zguiIsItemDeactivated(void) { return ImGui::IsItemDeactivated(); } ZGUI_API bool zguiIsItemDeactivatedAfterEdit(void) { return ImGui::IsItemDeactivatedAfterEdit(); } ZGUI_API bool zguiIsItemToggledOpen(void) { return ImGui::IsItemToggledOpen(); } ZGUI_API bool zguiIsAnyItemHovered(void) { return ImGui::IsAnyItemHovered(); } ZGUI_API bool zguiIsAnyItemActive(void) { return ImGui::IsAnyItemActive(); } ZGUI_API bool zguiIsAnyItemFocused(void) { return ImGui::IsAnyItemFocused(); } ZGUI_API void zguiGetContentRegionAvail(float pos[2]) { const ImVec2 p = ImGui::GetContentRegionAvail(); pos[0] = p.x; pos[1] = p.y; } ZGUI_API void zguiGetContentRegionMax(float pos[2]) { const ImVec2 p = ImGui::GetContentRegionMax(); pos[0] = p.x; pos[1] = p.y; } ZGUI_API void zguiGetWindowContentRegionMin(float pos[2]) { const ImVec2 p = ImGui::GetWindowContentRegionMin(); pos[0] = p.x; pos[1] = p.y; } ZGUI_API void zguiGetWindowContentRegionMax(float pos[2]) { const ImVec2 p = ImGui::GetWindowContentRegionMax(); pos[0] = p.x; pos[1] = p.y; } ZGUI_API void zguiPushTextWrapPos(float wrap_pos_x) { ImGui::PushTextWrapPos(wrap_pos_x); } ZGUI_API void zguiPopTextWrapPos(void) { ImGui::PopTextWrapPos(); } ZGUI_API bool zguiBeginTabBar(const char* string, ImGuiTabBarFlags flags) { return ImGui::BeginTabBar(string, flags); } ZGUI_API bool zguiBeginTabItem(const char* string, bool* p_open, ImGuiTabItemFlags flags) { return ImGui::BeginTabItem(string, p_open, flags); } ZGUI_API void zguiEndTabItem(void) { ImGui::EndTabItem(); } ZGUI_API void zguiEndTabBar(void) { ImGui::EndTabBar(); } ZGUI_API void zguiSetTabItemClosed(const char* tab_or_docked_window_label) { ImGui::SetTabItemClosed(tab_or_docked_window_label); } ZGUI_API bool zguiBeginMenuBar(void) { return ImGui::BeginMenuBar(); } ZGUI_API void zguiEndMenuBar(void) { ImGui::EndMenuBar(); } ZGUI_API bool zguiBeginMainMenuBar(void) { return ImGui::BeginMainMenuBar(); } ZGUI_API void zguiEndMainMenuBar(void) { ImGui::EndMainMenuBar(); } ZGUI_API bool zguiBeginMenu(const char* label, bool enabled) { return ImGui::BeginMenu(label, enabled); } ZGUI_API void zguiEndMenu(void) { ImGui::EndMenu(); } ZGUI_API bool zguiMenuItem(const char* label, const char* shortcut, bool selected, bool enabled) { return ImGui::MenuItem(label, shortcut, selected, enabled); } ZGUI_API bool zguiMenuItemPtr(const char* label, const char* shortcut, bool* selected, bool enabled) { return ImGui::MenuItem(label, shortcut, selected, enabled); } ZGUI_API bool zguiBeginTooltip(void) { return ImGui::BeginTooltip(); } ZGUI_API void zguiEndTooltip(void) { ImGui::EndTooltip(); } ZGUI_API bool zguiBeginPopup(const char* str_id, ImGuiWindowFlags flags){ return ImGui::BeginPopup(str_id, flags); } ZGUI_API bool zguiBeginPopupContextWindow(void) { return ImGui::BeginPopupContextWindow(); } ZGUI_API bool zguiBeginPopupContextItem(void) { return ImGui::BeginPopupContextItem(); } ZGUI_API bool zguiBeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags flags) { return ImGui::BeginPopupModal(name, p_open, flags); } ZGUI_API void zguiEndPopup(void) { ImGui::EndPopup(); } ZGUI_API void zguiOpenPopup(const char* str_id, ImGuiPopupFlags popup_flags) { ImGui::OpenPopup(str_id, popup_flags); } ZGUI_API void zguiCloseCurrentPopup(void) { ImGui::CloseCurrentPopup(); } //-------------------------------------------------------------------------------------------------- // // Tables // //-------------------------------------------------------------------------------------------------- ZGUI_API bool zguiBeginTable( const char* str_id, int column, ImGuiTableFlags flags, const float outer_size[2], float inner_width ) { return ImGui::BeginTable(str_id, column, flags, { outer_size[0], outer_size[1] }, inner_width); } ZGUI_API void zguiEndTable(void) { ImGui::EndTable(); } ZGUI_API void zguiTableNextRow(ImGuiTableRowFlags row_flags, float min_row_height) { ImGui::TableNextRow(row_flags, min_row_height); } ZGUI_API bool zguiTableNextColumn(void) { return ImGui::TableNextColumn(); } ZGUI_API bool zguiTableSetColumnIndex(int column_n) { return ImGui::TableSetColumnIndex(column_n); } ZGUI_API void zguiTableSetupColumn( const char* label, ImGuiTableColumnFlags flags, float init_width_or_height, ImGuiID user_id ) { ImGui::TableSetupColumn(label, flags, init_width_or_height, user_id); } ZGUI_API void zguiTableSetupScrollFreeze(int cols, int rows) { ImGui::TableSetupScrollFreeze(cols, rows); } ZGUI_API void zguiTableHeadersRow(void) { ImGui::TableHeadersRow(); } ZGUI_API void zguiTableHeader(const char* label) { ImGui::TableHeader(label); } ZGUI_API ImGuiTableSortSpecs* zguiTableGetSortSpecs(void) { return ImGui::TableGetSortSpecs(); } ZGUI_API int zguiTableGetColumnCount(void) { return ImGui::TableGetColumnCount(); } ZGUI_API int zguiTableGetColumnIndex(void) { return ImGui::TableGetColumnIndex(); } ZGUI_API int zguiTableGetRowIndex(void) { return ImGui::TableGetRowIndex(); } ZGUI_API const char* zguiTableGetColumnName(int column_n) { return ImGui::TableGetColumnName(column_n); } ZGUI_API ImGuiTableColumnFlags zguiTableGetColumnFlags(int column_n) { return ImGui::TableGetColumnFlags(column_n); } ZGUI_API void zguiTableSetColumnEnabled(int column_n, bool v) { ImGui::TableSetColumnEnabled(column_n, v); } ZGUI_API void zguiTableSetBgColor(ImGuiTableBgTarget target, ImU32 color, int column_n) { ImGui::TableSetBgColor(target, color, column_n); } //-------------------------------------------------------------------------------------------------- // // Color Utilities // //-------------------------------------------------------------------------------------------------- ZGUI_API void zguiColorConvertU32ToFloat4(ImU32 in, float rgba[4]) { const ImVec4 c = ImGui::ColorConvertU32ToFloat4(in); rgba[0] = c.x; rgba[1] = c.y; rgba[2] = c.z; rgba[3] = c.w; } ZGUI_API ImU32 zguiColorConvertFloat4ToU32(const float in[4]) { return ImGui::ColorConvertFloat4ToU32({ in[0], in[1], in[2], in[3] }); } ZGUI_API void zguiColorConvertRGBtoHSV(float r, float g, float b, float* out_h, float* out_s, float* out_v) { return ImGui::ColorConvertRGBtoHSV(r, g, b, *out_h, *out_s, *out_v); } ZGUI_API void zguiColorConvertHSVtoRGB(float h, float s, float v, float* out_r, float* out_g, float* out_b) { return ImGui::ColorConvertHSVtoRGB(h, s, v, *out_r, *out_g, *out_b); } //-------------------------------------------------------------------------------------------------- // // Inputs Utilities: Keyboard // //-------------------------------------------------------------------------------------------------- ZGUI_API bool zguiIsKeyDown(ImGuiKey key) { return ImGui::IsKeyDown(key); } //-------------------------------------------------------------------------------------------------- // // DrawList // //-------------------------------------------------------------------------------------------------- ZGUI_API ImDrawList *zguiGetWindowDrawList(void) { return ImGui::GetWindowDrawList(); } ZGUI_API ImDrawList *zguiGetBackgroundDrawList(void) { return ImGui::GetBackgroundDrawList(); } ZGUI_API ImDrawList *zguiGetForegroundDrawList(void) { return ImGui::GetForegroundDrawList(); } ZGUI_API ImDrawList *zguiCreateDrawList(void) { return IM_NEW(ImDrawList)(ImGui::GetDrawListSharedData()); } ZGUI_API void zguiDestroyDrawList(ImDrawList *draw_list) { IM_DELETE(draw_list); } ZGUI_API const char *zguiDrawList_GetOwnerName(ImDrawList *draw_list) { return draw_list->_OwnerName; } ZGUI_API void zguiDrawList_ResetForNewFrame(ImDrawList *draw_list) { draw_list->_ResetForNewFrame(); } ZGUI_API void zguiDrawList_ClearFreeMemory(ImDrawList *draw_list) { draw_list->_ClearFreeMemory(); } ZGUI_API int zguiDrawList_GetVertexBufferLength(ImDrawList *draw_list) { return draw_list->VtxBuffer.size(); } ZGUI_API ImDrawVert *zguiDrawList_GetVertexBufferData(ImDrawList *draw_list) { return draw_list->VtxBuffer.begin(); } ZGUI_API int zguiDrawList_GetIndexBufferLength(ImDrawList *draw_list) { return draw_list->IdxBuffer.size(); } ZGUI_API ImDrawIdx *zguiDrawList_GetIndexBufferData(ImDrawList *draw_list) { return draw_list->IdxBuffer.begin(); } ZGUI_API unsigned int zguiDrawList_GetCurrentIndex(ImDrawList *draw_list) { return draw_list->_VtxCurrentIdx; } ZGUI_API int zguiDrawList_GetCmdBufferLength(ImDrawList *draw_list) { return draw_list->CmdBuffer.size(); } ZGUI_API ImDrawCmd *zguiDrawList_GetCmdBufferData(ImDrawList *draw_list) { return draw_list->CmdBuffer.begin(); } ZGUI_API void zguiDrawList_SetFlags(ImDrawList *draw_list, ImDrawListFlags flags) { draw_list->Flags = flags; } ZGUI_API ImDrawListFlags zguiDrawList_GetFlags(ImDrawList *draw_list) { return draw_list->Flags; } ZGUI_API void zguiDrawList_PushClipRect( ImDrawList* draw_list, const float clip_rect_min[2], const float clip_rect_max[2], bool intersect_with_current_clip_rect ) { draw_list->PushClipRect( { clip_rect_min[0], clip_rect_min[1] }, { clip_rect_max[0], clip_rect_max[1] }, intersect_with_current_clip_rect ); } ZGUI_API void zguiDrawList_PushClipRectFullScreen(ImDrawList* draw_list) { draw_list->PushClipRectFullScreen(); } ZGUI_API void zguiDrawList_PopClipRect(ImDrawList* draw_list) { draw_list->PopClipRect(); } ZGUI_API void zguiDrawList_PushTextureId(ImDrawList* draw_list, ImTextureID texture_id) { draw_list->PushTextureID(texture_id); } ZGUI_API void zguiDrawList_PopTextureId(ImDrawList* draw_list) { draw_list->PopTextureID(); } ZGUI_API void zguiDrawList_GetClipRectMin(ImDrawList* draw_list, float clip_min[2]) { const ImVec2 c = draw_list->GetClipRectMin(); clip_min[0] = c.x; clip_min[1] = c.y; } ZGUI_API void zguiDrawList_GetClipRectMax(ImDrawList* draw_list, float clip_max[2]) { const ImVec2 c = draw_list->GetClipRectMax(); clip_max[0] = c.x; clip_max[1] = c.y; } ZGUI_API void zguiDrawList_AddLine( ImDrawList* draw_list, const float p1[2], const float p2[2], ImU32 col, float thickness ) { draw_list->AddLine({ p1[0], p1[1] }, { p2[0], p2[1] }, col, thickness); } ZGUI_API void zguiDrawList_AddRect( ImDrawList* draw_list, const float pmin[2], const float pmax[2], ImU32 col, float rounding, ImDrawFlags flags, float thickness ) { draw_list->AddRect({ pmin[0], pmin[1] }, { pmax[0], pmax[1] }, col, rounding, flags, thickness); } ZGUI_API void zguiDrawList_AddRectFilled( ImDrawList* draw_list, const float pmin[2], const float pmax[2], ImU32 col, float rounding, ImDrawFlags flags ) { draw_list->AddRectFilled({ pmin[0], pmin[1] }, { pmax[0], pmax[1] }, col, rounding, flags); } ZGUI_API void zguiDrawList_AddRectFilledMultiColor( ImDrawList* draw_list, const float pmin[2], const float pmax[2], ImU32 col_upr_left, ImU32 col_upr_right, ImU32 col_bot_right, ImU32 col_bot_left ) { draw_list->AddRectFilledMultiColor( { pmin[0], pmin[1] }, { pmax[0], pmax[1] }, col_upr_left, col_upr_right, col_bot_right, col_bot_left ); } ZGUI_API void zguiDrawList_AddQuad( ImDrawList* draw_list, const float p1[2], const float p2[2], const float p3[2], const float p4[2], ImU32 col, float thickness ) { draw_list->AddQuad({ p1[0], p1[1] }, { p2[0], p2[1] }, { p3[0], p3[1] }, { p4[0], p4[1] }, col, thickness); } ZGUI_API void zguiDrawList_AddQuadFilled( ImDrawList* draw_list, const float p1[2], const float p2[2], const float p3[2], const float p4[2], ImU32 col ) { draw_list->AddQuadFilled({ p1[0], p1[1] }, { p2[0], p2[1] }, { p3[0], p3[1] }, { p4[0], p4[1] }, col); } ZGUI_API void zguiDrawList_AddTriangle( ImDrawList* draw_list, const float p1[2], const float p2[2], const float p3[2], ImU32 col, float thickness ) { draw_list->AddTriangle({ p1[0], p1[1] }, { p2[0], p2[1] }, { p3[0], p3[1] }, col, thickness); } ZGUI_API void zguiDrawList_AddTriangleFilled( ImDrawList* draw_list, const float p1[2], const float p2[2], const float p3[2], ImU32 col ) { draw_list->AddTriangleFilled({ p1[0], p1[1] }, { p2[0], p2[1] }, { p3[0], p3[1] }, col); } ZGUI_API void zguiDrawList_AddCircle( ImDrawList* draw_list, const float center[2], float radius, ImU32 col, int num_segments, float thickness ) { draw_list->AddCircle({ center[0], center[1] }, radius, col, num_segments, thickness); } ZGUI_API void zguiDrawList_AddCircleFilled( ImDrawList* draw_list, const float center[2], float radius, ImU32 col, int num_segments ) { draw_list->AddCircleFilled({ center[0], center[1] }, radius, col, num_segments); } ZGUI_API void zguiDrawList_AddNgon( ImDrawList* draw_list, const float center[2], float radius, ImU32 col, int num_segments, float thickness ) { draw_list->AddNgon({ center[0], center[1] }, radius, col, num_segments, thickness); } ZGUI_API void zguiDrawList_AddNgonFilled( ImDrawList* draw_list, const float center[2], float radius, ImU32 col, int num_segments ) { draw_list->AddNgonFilled({ center[0], center[1] }, radius, col, num_segments); } ZGUI_API void zguiDrawList_AddText( ImDrawList* draw_list, const float pos[2], ImU32 col, const char* text_begin, const char* text_end ) { draw_list->AddText({ pos[0], pos[1] }, col, text_begin, text_end); } ZGUI_API void zguiDrawList_AddPolyline( ImDrawList* draw_list, const float points[][2], int num_points, ImU32 col, ImDrawFlags flags, float thickness ) { draw_list->AddPolyline((const ImVec2*)&points[0][0], num_points, col, flags, thickness); } ZGUI_API void zguiDrawList_AddConvexPolyFilled( ImDrawList* draw_list, const float points[][2], int num_points, ImU32 col ) { draw_list->AddConvexPolyFilled((const ImVec2*)&points[0][0], num_points, col); } ZGUI_API void zguiDrawList_AddBezierCubic( ImDrawList* draw_list, const float p1[2], const float p2[2], const float p3[2], const float p4[2], ImU32 col, float thickness, int num_segments ) { draw_list->AddBezierCubic( { p1[0], p1[1] }, { p2[0], p2[1] }, { p3[0], p3[1] }, { p4[0], p4[1] }, col, thickness, num_segments ); } ZGUI_API void zguiDrawList_AddBezierQuadratic( ImDrawList* draw_list, const float p1[2], const float p2[2], const float p3[2], ImU32 col, float thickness, int num_segments ) { draw_list->AddBezierQuadratic( { p1[0], p1[1] }, { p2[0], p2[1] }, { p3[0], p3[1] }, col, thickness, num_segments ); } ZGUI_API void zguiDrawList_AddImage( ImDrawList* draw_list, ImTextureID user_texture_id, const float pmin[2], const float pmax[2], const float uvmin[2], const float uvmax[2], ImU32 col ) { draw_list->AddImage( user_texture_id, { pmin[0], pmin[1] }, { pmax[0], pmax[1] }, { uvmin[0], uvmin[1] }, { uvmax[0], uvmax[1] }, col ); } ZGUI_API void zguiDrawList_AddImageQuad( ImDrawList* draw_list, ImTextureID user_texture_id, const float p1[2], const float p2[2], const float p3[2], const float p4[2], const float uv1[2], const float uv2[2], const float uv3[2], const float uv4[2], ImU32 col ) { draw_list->AddImageQuad( user_texture_id, { p1[0], p1[1] }, { p2[0], p2[1] }, { p3[0], p3[1] }, { p4[0], p4[1] }, { uv1[0], uv1[1] }, { uv2[0], uv2[1] }, { uv3[0], uv3[1] }, { uv4[0], uv4[1] }, col ); } ZGUI_API void zguiDrawList_AddImageRounded( ImDrawList* draw_list, ImTextureID user_texture_id, const float pmin[2], const float pmax[2], const float uvmin[2], const float uvmax[2], ImU32 col, float rounding, ImDrawFlags flags ) { draw_list->AddImageRounded( user_texture_id, { pmin[0], pmin[1] }, { pmax[0], pmax[1] }, { uvmin[0], uvmin[1] }, { uvmax[0], uvmax[1] }, col, rounding, flags ); } ZGUI_API void zguiDrawList_PathClear(ImDrawList* draw_list) { draw_list->PathClear(); } ZGUI_API void zguiDrawList_PathLineTo(ImDrawList* draw_list, const float pos[2]) { draw_list->PathLineTo({ pos[0], pos[1] }); } ZGUI_API void zguiDrawList_PathLineToMergeDuplicate(ImDrawList* draw_list, const float pos[2]) { draw_list->PathLineToMergeDuplicate({ pos[0], pos[1] }); } ZGUI_API void zguiDrawList_PathFillConvex(ImDrawList* draw_list, ImU32 col) { draw_list->PathFillConvex(col); } ZGUI_API void zguiDrawList_PathStroke(ImDrawList* draw_list, ImU32 col, ImDrawFlags flags, float thickness) { draw_list->PathStroke(col, flags, thickness); } ZGUI_API void zguiDrawList_PathArcTo( ImDrawList* draw_list, const float center[2], float radius, float a_min, float a_max, int num_segments ) { draw_list->PathArcTo({ center[0], center[1] }, radius, a_min, a_max, num_segments); } ZGUI_API void zguiDrawList_PathArcToFast( ImDrawList* draw_list, const float center[2], float radius, int a_min_of_12, int a_max_of_12 ) { draw_list->PathArcToFast({ center[0], center[1] }, radius, a_min_of_12, a_max_of_12); } ZGUI_API void zguiDrawList_PathBezierCubicCurveTo( ImDrawList* draw_list, const float p2[2], const float p3[2], const float p4[2], int num_segments ) { draw_list->PathBezierCubicCurveTo({ p2[0], p2[1] }, { p3[0], p3[1] }, { p4[0], p4[1] }, num_segments); } ZGUI_API void zguiDrawList_PathBezierQuadraticCurveTo( ImDrawList* draw_list, const float p2[2], const float p3[2], int num_segments ) { draw_list->PathBezierQuadraticCurveTo({ p2[0], p2[1] }, { p3[0], p3[1] }, num_segments); } ZGUI_API void zguiDrawList_PathRect( ImDrawList* draw_list, const float rect_min[2], const float rect_max[2], float rounding, ImDrawFlags flags ) { draw_list->PathRect({ rect_min[0], rect_min[1] }, { rect_max[0], rect_max[1] }, rounding, flags); } ZGUI_API void zguiDrawList_PrimReserve( ImDrawList* draw_list, int idx_count, int vtx_count) { draw_list->PrimReserve(idx_count, vtx_count); } ZGUI_API void zguiDrawList_PrimUnreserve( ImDrawList* draw_list, int idx_count, int vtx_count) { draw_list->PrimUnreserve(idx_count, vtx_count); } ZGUI_API void zguiDrawList_PrimRect( ImDrawList* draw_list, const float a[2], const float b[2], ImU32 col ) { draw_list->PrimRect({ a[0], a[1] }, { b[0], b[1] }, col); } ZGUI_API void zguiDrawList_PrimRectUV( ImDrawList* draw_list, const float a[2], const float b[2], const float uv_a[2], const float uv_b[2], ImU32 col ) { draw_list->PrimRectUV({ a[0], a[1] }, { b[0], b[1] }, { uv_a[0], uv_a[1] }, { uv_b[0], uv_b[1] }, col); } ZGUI_API void zguiDrawList_PrimQuadUV( ImDrawList* draw_list, const float a[2], const float b[2], const float c[2], const float d[2], const float uv_a[2], const float uv_b[2], const float uv_c[2], const float uv_d[2], ImU32 col ) { draw_list->PrimQuadUV( { a[0], a[1] }, { b[0], b[1] }, { c[0], c[1] }, { d[0], d[1] }, { uv_a[0], uv_a[1] }, { uv_b[0], uv_b[1] }, { uv_c[0], uv_c[1] }, { uv_d[0], uv_d[1] }, col ); } ZGUI_API void zguiDrawList_PrimWriteVtx( ImDrawList* draw_list, const float pos[2], const float uv[2], ImU32 col ) { draw_list->PrimWriteVtx({ pos[0], pos[1] }, { uv[0], uv[1] }, col); } ZGUI_API void zguiDrawList_PrimWriteIdx( ImDrawList* draw_list, ImDrawIdx idx) { draw_list->PrimWriteIdx(idx); } ZGUI_API void zguiDrawList_AddCallback(ImDrawList* draw_list, ImDrawCallback callback, void* callback_data) { draw_list->AddCallback(callback, callback_data); } ZGUI_API void zguiDrawList_AddResetRenderStateCallback(ImDrawList* draw_list) { draw_list->AddCallback(ImDrawCallback_ResetRenderState, NULL); } //-------------------------------------------------------------------------------------------------- // // Viewport // //-------------------------------------------------------------------------------------------------- ZGUI_API ImGuiViewport* zguiGetMainViewport(void) { return ImGui::GetMainViewport(); } ZGUI_API void zguiViewport_GetPos(ImGuiViewport* viewport, float p[2]) { const ImVec2 pos = viewport->Pos; p[0] = pos.x; p[1] = pos.y; } ZGUI_API void zguiViewport_GetSize(ImGuiViewport* viewport, float p[2]) { const ImVec2 sz = viewport->Size; p[0] = sz.x; p[1] = sz.y; } ZGUI_API void zguiViewport_GetWorkPos(ImGuiViewport* viewport, float p[2]) { const ImVec2 pos = viewport->WorkPos; p[0] = pos.x; p[1] = pos.y; } ZGUI_API void zguiViewport_GetWorkSize(ImGuiViewport* viewport, float p[2]) { const ImVec2 sz = viewport->WorkSize; p[0] = sz.x; p[1] = sz.y; } //-------------------------------------------------------------------------------------------------- // // Docking // //-------------------------------------------------------------------------------------------------- ZGUI_API ImGuiID zguiDockSpace(const char* str_id, float size[2], ImGuiDockNodeFlags flags) { return ImGui::DockSpace(ImGui::GetID(str_id), {size[0], size[1]}, flags); } ZGUI_API ImGuiID zguiDockSpaceOverViewport(const ImGuiViewport* viewport, ImGuiDockNodeFlags dockspace_flags) { return ImGui::DockSpaceOverViewport(viewport, dockspace_flags); } //-------------------------------------------------------------------------------------------------- // // DockBuilder (Unstable internal imgui API, subject to change, use at own risk) // //-------------------------------------------------------------------------------------------------- ZGUI_API void zguiDockBuilderDockWindow(const char* window_name, ImGuiID node_id) { ImGui::DockBuilderDockWindow(window_name, node_id); } ZGUI_API ImGuiID zguiDockBuilderAddNode(ImGuiID node_id, ImGuiDockNodeFlags flags) { return ImGui::DockBuilderAddNode(node_id, flags); } ZGUI_API void zguiDockBuilderRemoveNode(ImGuiID node_id) { ImGui::DockBuilderRemoveNode(node_id); } ZGUI_API void zguiDockBuilderSetNodePos(ImGuiID node_id, float pos[2]) { ImGui::DockBuilderSetNodePos(node_id, {pos[0], pos[1]}); } ZGUI_API void zguiDockBuilderSetNodeSize(ImGuiID node_id, float size[2]) { ImGui::DockBuilderSetNodeSize(node_id, {size[0], size[1]}); } ZGUI_API ImGuiID zguiDockBuilderSplitNode( ImGuiID node_id, ImGuiDir split_dir, float size_ratio_for_node_at_dir, ImGuiID* out_id_at_dir, ImGuiID* out_id_at_opposite_dir ) { return ImGui::DockBuilderSplitNode( node_id, split_dir, size_ratio_for_node_at_dir, out_id_at_dir, out_id_at_opposite_dir ); } ZGUI_API void zguiDockBuilderFinish(ImGuiID node_id) { ImGui::DockBuilderFinish(node_id); } #if ZGUI_IMPLOT //-------------------------------------------------------------------------------------------------- // // ImPlot // //-------------------------------------------------------------------------------------------------- ZGUI_API ImPlotContext* zguiPlot_CreateContext(void) { return ImPlot::CreateContext(); } ZGUI_API void zguiPlot_DestroyContext(ImPlotContext* ctx) { ImPlot::DestroyContext(ctx); } ZGUI_API ImPlotContext* zguiPlot_GetCurrentContext(void) { return ImPlot::GetCurrentContext(); } ZGUI_API ImPlotStyle zguiPlotStyle_Init(void) { return ImPlotStyle(); } ZGUI_API ImPlotStyle* zguiPlot_GetStyle(void) { return &ImPlot::GetStyle(); } ZGUI_API void zguiPlot_PushStyleColor4f(ImPlotCol idx, const float col[4]) { ImPlot::PushStyleColor(idx, { col[0], col[1], col[2], col[3] }); } ZGUI_API void zguiPlot_PushStyleColor1u(ImPlotCol idx, ImU32 col) { ImPlot::PushStyleColor(idx, col); } ZGUI_API void zguiPlot_PopStyleColor(int count) { ImPlot::PopStyleColor(count); } ZGUI_API void zguiPlot_PushStyleVar1i(ImPlotStyleVar idx, int var) { ImPlot::PushStyleVar(idx, var); } ZGUI_API void zguiPlot_PushStyleVar1f(ImPlotStyleVar idx, float var) { ImPlot::PushStyleVar(idx, var); } ZGUI_API void zguiPlot_PushStyleVar2f(ImPlotStyleVar idx, const float var[2]) { ImPlot::PushStyleVar(idx, { var[0], var[1] }); } ZGUI_API void zguiPlot_PopStyleVar(int count) { ImPlot::PopStyleVar(count); } ZGUI_API void zguiPlot_SetupLegend(ImPlotLocation location, ImPlotLegendFlags flags) { ImPlot::SetupLegend(location, flags); } ZGUI_API void zguiPlot_SetupAxis(ImAxis axis, const char* label, ImPlotAxisFlags flags) { ImPlot::SetupAxis(axis, label, flags); } ZGUI_API void zguiPlot_SetupAxisLimits(ImAxis axis, double v_min, double v_max, ImPlotCond cond) { ImPlot::SetupAxisLimits(axis, v_min, v_max, cond); } ZGUI_API void zguiPlot_SetupFinish(void) { ImPlot::SetupFinish(); } ZGUI_API bool zguiPlot_BeginPlot(const char* title_id, float width, float height, ImPlotFlags flags) { return ImPlot::BeginPlot(title_id, { width, height }, flags); } ZGUI_API void zguiPlot_PlotLineValues( const char* label_id, ImGuiDataType data_type, const void* values, int count, double xscale, double x0, ImPlotLineFlags flags, int offset, int stride ) { if (data_type == ImGuiDataType_S8) ImPlot::PlotLine(label_id, (const ImS8*)values, count, xscale, x0, flags, offset, stride); else if (data_type == ImGuiDataType_U8) ImPlot::PlotLine(label_id, (const ImU8*)values, count, xscale, x0, flags, offset, stride); else if (data_type == ImGuiDataType_S16) ImPlot::PlotLine(label_id, (const ImS16*)values, count, xscale, x0, flags, offset, stride); else if (data_type == ImGuiDataType_U16) ImPlot::PlotLine(label_id, (const ImU16*)values, count, xscale, x0, flags, offset, stride); else if (data_type == ImGuiDataType_S32) ImPlot::PlotLine(label_id, (const ImS32*)values, count, xscale, x0, flags, offset, stride); else if (data_type == ImGuiDataType_U32) ImPlot::PlotLine(label_id, (const ImU32*)values, count, xscale, x0, flags, offset, stride); else if (data_type == ImGuiDataType_Float) ImPlot::PlotLine(label_id, (const float*)values, count, xscale, x0, flags, offset, stride); else if (data_type == ImGuiDataType_Double) ImPlot::PlotLine(label_id, (const double*)values, count, xscale, x0, flags, offset, stride); else assert(false); } ZGUI_API void zguiPlot_PlotLine( const char* label_id, ImGuiDataType data_type, const void* xv, const void* yv, int count, ImPlotLineFlags flags, int offset, int stride ) { if (data_type == ImGuiDataType_S8) ImPlot::PlotLine(label_id, (const ImS8*)xv, (const ImS8*)yv, count, flags, offset, stride); else if (data_type == ImGuiDataType_U8) ImPlot::PlotLine(label_id, (const ImU8*)xv, (const ImU8*)yv, count, flags, offset, stride); else if (data_type == ImGuiDataType_S16) ImPlot::PlotLine(label_id, (const ImS16*)xv, (const ImS16*)yv, count, flags, offset, stride); else if (data_type == ImGuiDataType_U16) ImPlot::PlotLine(label_id, (const ImU16*)xv, (const ImU16*)yv, count, flags, offset, stride); else if (data_type == ImGuiDataType_S32) ImPlot::PlotLine(label_id, (const ImS32*)xv, (const ImS32*)yv, count, flags, offset, stride); else if (data_type == ImGuiDataType_U32) ImPlot::PlotLine(label_id, (const ImU32*)xv, (const ImU32*)yv, count, flags, offset, stride); else if (data_type == ImGuiDataType_Float) ImPlot::PlotLine(label_id, (const float*)xv, (const float*)yv, count, flags, offset, stride); else if (data_type == ImGuiDataType_Double) ImPlot::PlotLine(label_id, (const double*)xv, (const double*)yv, count, flags, offset, stride); else assert(false); } ZGUI_API void zguiPlot_PlotScatter( const char* label_id, ImGuiDataType data_type, const void* xv, const void* yv, int count, ImPlotScatterFlags flags, int offset, int stride ) { if (data_type == ImGuiDataType_S8) ImPlot::PlotScatter(label_id, (const ImS8*)xv, (const ImS8*)yv, count, flags, offset, stride); else if (data_type == ImGuiDataType_U8) ImPlot::PlotScatter(label_id, (const ImU8*)xv, (const ImU8*)yv, count, flags, offset, stride); else if (data_type == ImGuiDataType_S16) ImPlot::PlotScatter(label_id, (const ImS16*)xv, (const ImS16*)yv, count, flags, offset, stride); else if (data_type == ImGuiDataType_U16) ImPlot::PlotScatter(label_id, (const ImU16*)xv, (const ImU16*)yv, count, flags, offset, stride); else if (data_type == ImGuiDataType_S32) ImPlot::PlotScatter(label_id, (const ImS32*)xv, (const ImS32*)yv, count, flags, offset, stride); else if (data_type == ImGuiDataType_U32) ImPlot::PlotScatter(label_id, (const ImU32*)xv, (const ImU32*)yv, count, flags, offset, stride); else if (data_type == ImGuiDataType_Float) ImPlot::PlotScatter(label_id, (const float*)xv, (const float*)yv, count, flags, offset, stride); else if (data_type == ImGuiDataType_Double) ImPlot::PlotScatter(label_id, (const double*)xv, (const double*)yv, count, flags, offset, stride); else assert(false); } ZGUI_API void zguiPlot_PlotScatterValues( const char* label_id, ImGuiDataType data_type, const void* values, int count, double xscale, double x0, ImPlotScatterFlags flags, int offset, int stride ) { if (data_type == ImGuiDataType_S8) ImPlot::PlotScatter(label_id, (const ImS8*)values, count, xscale, x0, flags, offset, stride); else if (data_type == ImGuiDataType_U8) ImPlot::PlotScatter(label_id, (const ImU8*)values, count, xscale, x0, flags, offset, stride); else if (data_type == ImGuiDataType_S16) ImPlot::PlotScatter(label_id, (const ImS16*)values, count, xscale, x0, flags, offset, stride); else if (data_type == ImGuiDataType_U16) ImPlot::PlotScatter(label_id, (const ImU16*)values, count, xscale, x0, flags, offset, stride); else if (data_type == ImGuiDataType_S32) ImPlot::PlotScatter(label_id, (const ImS32*)values, count, xscale, x0, flags, offset, stride); else if (data_type == ImGuiDataType_U32) ImPlot::PlotScatter(label_id, (const ImU32*)values, count, xscale, x0, flags, offset, stride); else if (data_type == ImGuiDataType_Float) ImPlot::PlotScatter(label_id, (const float*)values, count, xscale, x0, flags, offset, stride); else if (data_type == ImGuiDataType_Double) ImPlot::PlotScatter(label_id, (const double*)values, count, xscale, x0, flags, offset, stride); else assert(false); } ZGUI_API void zguiPlot_PlotShaded( const char* label_id, ImGuiDataType data_type, const void* xv, const void* yv, int count, double yref, ImPlotShadedFlags flags, int offset, int stride ) { if (data_type == ImGuiDataType_S8) ImPlot::PlotShaded(label_id, (const ImS8*)xv, (const ImS8*)yv, count, yref, flags, offset, stride); else if (data_type == ImGuiDataType_U8) ImPlot::PlotShaded(label_id, (const ImU8*)xv, (const ImU8*)yv, count, yref, flags, offset, stride); else if (data_type == ImGuiDataType_S16) ImPlot::PlotShaded(label_id, (const ImS16*)xv, (const ImS16*)yv, count, yref, flags, offset, stride); else if (data_type == ImGuiDataType_U16) ImPlot::PlotShaded(label_id, (const ImU16*)xv, (const ImU16*)yv, count, yref, flags, offset, stride); else if (data_type == ImGuiDataType_S32) ImPlot::PlotShaded(label_id, (const ImS32*)xv, (const ImS32*)yv, count, yref, flags, offset, stride); else if (data_type == ImGuiDataType_U32) ImPlot::PlotShaded(label_id, (const ImU32*)xv, (const ImU32*)yv, count, yref, flags, offset, stride); else if (data_type == ImGuiDataType_Float) ImPlot::PlotShaded(label_id, (const float*)xv, (const float*)yv, count, yref, flags, offset, stride); else if (data_type == ImGuiDataType_Double) ImPlot::PlotShaded(label_id, (const double*)xv, (const double*)yv, count, yref, flags, offset, stride); else assert(false); } ZGUI_API void zguiPlot_PlotBars( const char* label_id, ImGuiDataType data_type, const void* xv, const void* yv, int count, double bar_size, ImPlotBarsFlags flags, int offset, int stride ) { if (data_type == ImGuiDataType_S8) ImPlot::PlotBars(label_id, (const ImS8*)xv, (const ImS8*)yv, count, bar_size, flags, offset, stride); else if (data_type == ImGuiDataType_U8) ImPlot::PlotBars(label_id, (const ImU8*)xv, (const ImU8*)yv, count, bar_size, flags, offset, stride); else if (data_type == ImGuiDataType_S16) ImPlot::PlotBars(label_id, (const ImS16*)xv, (const ImS16*)yv, count, bar_size, flags, offset, stride); else if (data_type == ImGuiDataType_U16) ImPlot::PlotBars(label_id, (const ImU16*)xv, (const ImU16*)yv, count, bar_size, flags, offset, stride); else if (data_type == ImGuiDataType_S32) ImPlot::PlotBars(label_id, (const ImS32*)xv, (const ImS32*)yv, count, bar_size, flags, offset, stride); else if (data_type == ImGuiDataType_U32) ImPlot::PlotBars(label_id, (const ImU32*)xv, (const ImU32*)yv, count, bar_size, flags, offset, stride); else if (data_type == ImGuiDataType_Float) ImPlot::PlotBars(label_id, (const float*)xv, (const float*)yv, count, bar_size, flags, offset, stride); else if (data_type == ImGuiDataType_Double) ImPlot::PlotBars(label_id, (const double*)xv, (const double*)yv, count, bar_size, flags, offset, stride); else assert(false); } ZGUI_API void zguiPlot_PlotBarsValues( const char* label_id, ImGuiDataType data_type, const void* values, int count, double bar_size, double shift, ImPlotBarsFlags flags, int offset, int stride ) { if (data_type == ImGuiDataType_S8) ImPlot::PlotBars(label_id, (const ImS8*)values, count, bar_size, shift, flags, offset, stride); else if (data_type == ImGuiDataType_U8) ImPlot::PlotBars(label_id, (const ImU8*)values, count, bar_size, shift, flags, offset, stride); else if (data_type == ImGuiDataType_S16) ImPlot::PlotBars(label_id, (const ImS16*)values, count, bar_size, shift, flags, offset, stride); else if (data_type == ImGuiDataType_U16) ImPlot::PlotBars(label_id, (const ImU16*)values, count, bar_size, shift, flags, offset, stride); else if (data_type == ImGuiDataType_S32) ImPlot::PlotBars(label_id, (const ImS32*)values, count, bar_size, shift, flags, offset, stride); else if (data_type == ImGuiDataType_U32) ImPlot::PlotBars(label_id, (const ImU32*)values, count, bar_size, shift, flags, offset, stride); else if (data_type == ImGuiDataType_Float) ImPlot::PlotBars(label_id, (const float*)values, count, bar_size, shift, flags, offset, stride); else if (data_type == ImGuiDataType_Double) ImPlot::PlotBars(label_id, (const double*)values, count, bar_size, shift, flags, offset, stride); else assert(false); } ZGUI_API bool zguiPlot_IsPlotHovered() { return ImPlot::IsPlotHovered(); } ZGUI_API void zguiPlot_GetLastItemColor(float color[4]) { const ImVec4 col = ImPlot::GetLastItemColor(); color[0] = col.x; color[1] = col.y; color[2] = col.z; color[3] = col.w; } ZGUI_API void zguiPlot_ShowDemoWindow(bool* p_open) { ImPlot::ShowDemoWindow(p_open); } ZGUI_API void zguiPlot_EndPlot(void) { ImPlot::EndPlot(); } ZGUI_API bool zguiPlot_DragPoint( int id, double* x, double* y, float col[4], float size, ImPlotDragToolFlags flags ) { return ImPlot::DragPoint( id, x, y, (*(const ImVec4*)&(col[0])), size, flags ); } ZGUI_API void zguiPlot_PlotText( const char* text, double x, double y, const float pix_offset[2], ImPlotTextFlags flags=0 ) { const ImVec2 p(pix_offset[0], pix_offset[1]); ImPlot::PlotText(text, x, y, p, flags); } #endif /* #ifdef ZGUI_IMPLOT */ //-------------------------------------------------------------------------------------------------- } /* extern "C" */ #if ZGUI_TE //-------------------------------------------------------------------------------------------------- // // ImGUI Test Engine // //-------------------------------------------------------------------------------------------------- extern "C" { ZGUI_API void *zguiTe_CreateContext(void) { ImGuiTestEngine *e = ImGuiTestEngine_CreateContext(); ImGuiTestEngine_Start(e, ImGui::GetCurrentContext()); ImGuiTestEngine_InstallDefaultCrashHandler(); return e; } ZGUI_API void zguiTe_DestroyContext(ImGuiTestEngine *engine) { ImGuiTestEngine_DestroyContext(engine); } ZGUI_API void zguiTe_EngineSetRunSpeed(ImGuiTestEngine *engine, ImGuiTestRunSpeed speed) { ImGuiTestEngine_GetIO(engine).ConfigRunSpeed = speed; } ZGUI_API void zguiTe_EngineExportJunitResult(ImGuiTestEngine *engine, const char *filename) { ImGuiTestEngine_GetIO(engine).ExportResultsFilename = filename; ImGuiTestEngine_GetIO(engine).ExportResultsFormat = ImGuiTestEngineExportFormat_JUnitXml; } ZGUI_API void zguiTe_TryAbortEngine(ImGuiTestEngine *engine) { ImGuiTestEngine_TryAbortEngine(engine); } ZGUI_API void zguiTe_Stop(ImGuiTestEngine *engine) { ImGuiTestEngine_Stop(engine); } ZGUI_API void zguiTe_PostSwap(ImGuiTestEngine *engine) { ImGuiTestEngine_PostSwap(engine); } ZGUI_API bool zguiTe_IsTestQueueEmpty(ImGuiTestEngine *engine) { return ImGuiTestEngine_IsTestQueueEmpty(engine); } ZGUI_API void zguiTe_GetResult(ImGuiTestEngine *engine, int *count_tested, int *count_success) { int ct = 0; int cs = 0; ImGuiTestEngine_GetResult(engine, ct, cs); *count_tested = ct; *count_success = cs; } ZGUI_API void zguiTe_PrintResultSummary(ImGuiTestEngine *engine) { ImGuiTestEngine_PrintResultSummary(engine); } ZGUI_API void zguiTe_QueueTests(ImGuiTestEngine *engine, ImGuiTestGroup group, const char *filter_str, ImGuiTestRunFlags run_flags) { ImGuiTestEngine_QueueTests(engine, group, filter_str, run_flags); } ZGUI_API void zguiTe_ShowTestEngineWindows(ImGuiTestEngine *engine, bool *p_open) { ImGuiTestEngine_ShowTestEngineWindows(engine, p_open); } ZGUI_API void *zguiTe_RegisterTest(ImGuiTestEngine *engine, const char *category, const char *name, const char *src_file, int src_line, ImGuiTestGuiFunc *gui_fce, ImGuiTestTestFunc *gui_test_fce) { auto t = ImGuiTestEngine_RegisterTest(engine, category, name, src_file, src_line); t->GuiFunc = gui_fce; t->TestFunc = gui_test_fce; return t; } ZGUI_API bool zguiTe_Check(const char *file, const char *func, int line, ImGuiTestCheckFlags flags, bool result, const char *expr) { return ImGuiTestEngine_Check(file, func, line, flags, result, expr); } // CONTEXT ZGUI_API void zguiTe_ContextSetRef(ImGuiTestContext *ctx, const char *ref) { ctx->SetRef(ref); } ZGUI_API void zguiTe_ContextWindowFocus(ImGuiTestContext *ctx, const char *ref) { ctx->WindowFocus(ref); } ZGUI_API void zguiTe_ContextItemAction(ImGuiTestContext *ctx, ImGuiTestAction action, const char *ref, ImGuiTestOpFlags flags = 0, void *action_arg = NULL) { ctx->ItemAction(action, ref, flags, action_arg); } ZGUI_API void zguiTe_ContextItemInputStrValue(ImGuiTestContext *ctx, const char *ref, const char *value) { ctx->ItemInputValue(ref, value); } ZGUI_API void zguiTe_ContextItemInputIntValue(ImGuiTestContext *ctx, const char *ref, int value) { ctx->ItemInputValue(ref, value); } ZGUI_API void zguiTe_ContextItemInputFloatValue(ImGuiTestContext *ctx, const char *ref, float value) { ctx->ItemInputValue(ref, value); } ZGUI_API void zguiTe_ContextYield(ImGuiTestContext *ctx, int frame_count) { ctx->Yield(frame_count); } ZGUI_API void zguiTe_ContextMenuAction(ImGuiTestContext *ctx, ImGuiTestAction action, const char *ref) { ctx->MenuAction(action, ref); } ZGUI_API void zguiTe_ContextDragAndDrop(ImGuiTestContext *ctx, const char *ref_src, const char *ref_dst, ImGuiMouseButton button) { ctx->ItemDragAndDrop(ref_src, ref_dst, button); } ZGUI_API void zguiTe_ContextKeyDown(ImGuiTestContext *ctx, ImGuiKeyChord key_chord) { ctx->KeyDown(key_chord); } ZGUI_API void zguiTe_ContextKeyUp(ImGuiTestContext *ctx, ImGuiKeyChord key_chord) { ctx->KeyUp(key_chord); } } /* extern "C" */ #endif
0
repos/simulations/libs/zgui
repos/simulations/libs/zgui/src/gui.zig
//-------------------------------------------------------------------------------------------------- // // Zig bindings for 'dear imgui' library. Easy to use, hand-crafted API with default arguments, // named parameters and Zig style text formatting. // //-------------------------------------------------------------------------------------------------- pub const plot = @import("plot.zig"); pub const te = @import("te.zig"); pub const backend = switch (@import("zgui_options").backend) { .glfw_wgpu => @import("backend_glfw_wgpu.zig"), .glfw_opengl3 => @import("backend_glfw_opengl.zig"), .glfw_dx12 => @import("backend_glfw_dx12.zig"), .glfw => @import("backend_glfw.zig"), .win32_dx12 => @import("backend_win32_dx12.zig"), .no_backend => .{}, }; const te_enabled = @import("zgui_options").with_te; //-------------------------------------------------------------------------------------------------- const std = @import("std"); const assert = std.debug.assert; //-------------------------------------------------------------------------------------------------- pub const f32_min: f32 = 1.17549435082228750796873653722225e-38; pub const f32_max: f32 = 3.40282346638528859811704183484517e+38; //-------------------------------------------------------------------------------------------------- pub const DrawIdx = u16; pub const DrawVert = extern struct { pos: [2]f32, uv: [2]f32, color: u32, }; //-------------------------------------------------------------------------------------------------- pub fn init(allocator: std.mem.Allocator) void { if (zguiGetCurrentContext() == null) { mem_allocator = allocator; mem_allocations = std.AutoHashMap(usize, usize).init(allocator); mem_allocations.?.ensureTotalCapacity(32) catch @panic("zgui: out of memory"); zguiSetAllocatorFunctions(zguiMemAlloc, zguiMemFree); _ = zguiCreateContext(null); temp_buffer = std.ArrayList(u8).init(allocator); temp_buffer.?.resize(3 * 1024 + 1) catch unreachable; if (te_enabled) { te.init(); } } } pub fn deinit() void { if (zguiGetCurrentContext() != null) { temp_buffer.?.deinit(); zguiDestroyContext(null); // Must be after destroy imgui context. // And before allocation check if (te_enabled) { te.deinit(); } if (mem_allocations.?.count() > 0) { var it = mem_allocations.?.iterator(); while (it.next()) |kv| { const address = kv.key_ptr.*; const size = kv.value_ptr.*; mem_allocator.?.free(@as([*]align(mem_alignment) u8, @ptrFromInt(address))[0..size]); std.log.info( "[zgui] Possible memory leak or static memory usage detected: (address: 0x{x}, size: {d})", .{ address, size }, ); } mem_allocations.?.clearAndFree(); } assert(mem_allocations.?.count() == 0); mem_allocations.?.deinit(); mem_allocations = null; mem_allocator = null; } } pub fn initNoContext(allocator: std.mem.Allocator) void { if (temp_buffer == null) { temp_buffer = std.ArrayList(u8).init(allocator); temp_buffer.?.resize(3 * 1024 + 1) catch unreachable; } } pub fn deinitNoContext() void { if (temp_buffer) |buf| { buf.deinit(); } } extern fn zguiCreateContext(shared_font_atlas: ?*const anyopaque) Context; extern fn zguiDestroyContext(ctx: ?Context) void; extern fn zguiGetCurrentContext() ?Context; //-------------------------------------------------------------------------------------------------- var mem_allocator: ?std.mem.Allocator = null; var mem_allocations: ?std.AutoHashMap(usize, usize) = null; var mem_mutex: std.Thread.Mutex = .{}; const mem_alignment = 16; fn zguiMemAlloc(size: usize, _: ?*anyopaque) callconv(.C) ?*anyopaque { mem_mutex.lock(); defer mem_mutex.unlock(); const mem = mem_allocator.?.alignedAlloc( u8, mem_alignment, size, ) catch @panic("zgui: out of memory"); mem_allocations.?.put(@intFromPtr(mem.ptr), size) catch @panic("zgui: out of memory"); return mem.ptr; } fn zguiMemFree(maybe_ptr: ?*anyopaque, _: ?*anyopaque) callconv(.C) void { if (maybe_ptr) |ptr| { mem_mutex.lock(); defer mem_mutex.unlock(); if (mem_allocations != null) { const size = mem_allocations.?.fetchRemove(@intFromPtr(ptr)).?.value; const mem = @as([*]align(mem_alignment) u8, @ptrCast(@alignCast(ptr)))[0..size]; mem_allocator.?.free(mem); } } } extern fn zguiSetAllocatorFunctions( alloc_func: ?*const fn (usize, ?*anyopaque) callconv(.C) ?*anyopaque, free_func: ?*const fn (?*anyopaque, ?*anyopaque) callconv(.C) void, ) void; //-------------------------------------------------------------------------------------------------- pub const ConfigFlags = packed struct(c_int) { nav_enable_keyboard: bool = false, nav_enable_gamepad: bool = false, nav_enable_set_mouse_pos: bool = false, nav_no_capture_keyboard: bool = false, no_mouse: bool = false, no_mouse_cursor_change: bool = false, dock_enable: bool = false, _pading0: u3 = 0, viewport_enable: bool = false, _pading1: u3 = 0, dpi_enable_scale_viewport: bool = false, dpi_enable_scale_fonts: bool = false, user_storage: u4 = 0, is_srgb: bool = false, is_touch_screen: bool = false, _padding: u10 = 0, }; pub const FontConfig = extern struct { font_data: ?*anyopaque, font_data_size: c_int, font_data_owned_by_atlas: bool, font_no: c_int, size_pixels: f32, oversample_h: c_int, oversample_v: c_int, pixel_snap_h: bool, glyph_extra_spacing: [2]f32, glyph_offset: [2]f32, glyph_ranges: [*c]u16, glyph_min_advance_x: f32, glyph_max_advance_x: f32, merge_mode: bool, font_builder_flags: c_uint, rasterizer_multiply: f32, rasterizer_density: f32, ellipsis_char: Wchar, name: [40]u8, dst_font: *Font, pub fn init() FontConfig { return zguiFontConfig_Init(); } extern fn zguiFontConfig_Init() FontConfig; }; pub const io = struct { pub fn addFontFromFile(filename: [:0]const u8, size_pixels: f32) Font { return zguiIoAddFontFromFile(filename, size_pixels); } extern fn zguiIoAddFontFromFile(filename: [*:0]const u8, size_pixels: f32) Font; pub fn addFontFromFileWithConfig( filename: [:0]const u8, size_pixels: f32, config: ?FontConfig, ranges: ?[*]const Wchar, ) Font { return zguiIoAddFontFromFileWithConfig(filename, size_pixels, if (config) |c| &c else null, ranges); } extern fn zguiIoAddFontFromFileWithConfig( filename: [*:0]const u8, size_pixels: f32, config: ?*const FontConfig, ranges: ?[*]const Wchar, ) Font; pub fn addFontFromMemory(fontdata: []const u8, size_pixels: f32) Font { return zguiIoAddFontFromMemory(fontdata.ptr, @intCast(fontdata.len), size_pixels); } extern fn zguiIoAddFontFromMemory(font_data: *const anyopaque, font_size: c_int, size_pixels: f32) Font; pub fn addFontFromMemoryWithConfig( fontdata: []const u8, size_pixels: f32, config: ?FontConfig, ranges: ?[*]const Wchar, ) Font { return zguiIoAddFontFromMemoryWithConfig( fontdata.ptr, @intCast(fontdata.len), size_pixels, if (config) |c| &c else null, ranges, ); } extern fn zguiIoAddFontFromMemoryWithConfig( font_data: *const anyopaque, font_size: c_int, size_pixels: f32, config: ?*const FontConfig, ranges: ?[*]const Wchar, ) Font; pub fn getFont(index: u32) Font { return zguiIoGetFont(index); } extern fn zguiIoGetFont(index: c_uint) Font; /// `pub fn setDefaultFont(font: Font) void` pub const setDefaultFont = zguiIoSetDefaultFont; extern fn zguiIoSetDefaultFont(font: Font) void; pub fn getFontsTextDataAsRgba32() struct { width: i32, height: i32, pixels: ?[*]const u32, } { var width: i32 = undefined; var height: i32 = undefined; const ptr = zguiIoGetFontsTexDataAsRgba32(&width, &height); return .{ .width = width, .height = height, .pixels = ptr, }; } extern fn zguiIoGetFontsTexDataAsRgba32(width: *c_int, height: *c_int) [*c]const u32; /// `pub fn setFontsTexId(id:TextureIdent) set the backend Id for the fonts atlas pub const setFontsTexId = zguiIoSetFontsTexId; extern fn zguiIoSetFontsTexId(id: TextureIdent) void; pub const getFontsTexId = zguiIoGetFontsTexId; extern fn zguiIoGetFontsTexId() TextureIdent; /// `pub fn zguiIoSetConfigWindowsMoveFromTitleBarOnly(bool) void` pub const setConfigWindowsMoveFromTitleBarOnly = zguiIoSetConfigWindowsMoveFromTitleBarOnly; extern fn zguiIoSetConfigWindowsMoveFromTitleBarOnly(enabled: bool) void; /// `pub fn zguiIoGetWantCaptureMouse() bool` pub const getWantCaptureMouse = zguiIoGetWantCaptureMouse; extern fn zguiIoGetWantCaptureMouse() bool; /// `pub fn zguiIoGetWantCaptureKeyboard() bool` pub const getWantCaptureKeyboard = zguiIoGetWantCaptureKeyboard; extern fn zguiIoGetWantCaptureKeyboard() bool; /// `pub fn zguiIoGetWantTextInput() bool` pub const getWantTextInput = zguiIoGetWantTextInput; extern fn zguiIoGetWantTextInput() bool; pub fn setIniFilename(filename: ?[*:0]const u8) void { zguiIoSetIniFilename(filename); } extern fn zguiIoSetIniFilename(filename: ?[*:0]const u8) void; /// `pub fn setDisplaySize(width: f32, height: f32) void` pub const setDisplaySize = zguiIoSetDisplaySize; extern fn zguiIoSetDisplaySize(width: f32, height: f32) void; pub fn getDisplaySize() [2]f32 { var size: [2]f32 = undefined; zguiIoGetDisplaySize(&size); return size; } extern fn zguiIoGetDisplaySize(size: *[2]f32) void; /// `pub fn setDisplayFramebufferScale(sx: f32, sy: f32) void` pub const setDisplayFramebufferScale = zguiIoSetDisplayFramebufferScale; extern fn zguiIoSetDisplayFramebufferScale(sx: f32, sy: f32) void; /// `pub fn setConfigFlags(flags: ConfigFlags) void` pub const setConfigFlags = zguiIoSetConfigFlags; extern fn zguiIoSetConfigFlags(flags: ConfigFlags) void; /// `pub fn setDeltaTime(delta_time: f32) void` pub const setDeltaTime = zguiIoSetDeltaTime; extern fn zguiIoSetDeltaTime(delta_time: f32) void; pub const addFocusEvent = zguiIoAddFocusEvent; extern fn zguiIoAddFocusEvent(focused: bool) void; pub const addMousePositionEvent = zguiIoAddMousePositionEvent; extern fn zguiIoAddMousePositionEvent(x: f32, y: f32) void; pub const addMouseButtonEvent = zguiIoAddMouseButtonEvent; extern fn zguiIoAddMouseButtonEvent(button: MouseButton, down: bool) void; pub const addMouseWheelEvent = zguiIoAddMouseWheelEvent; extern fn zguiIoAddMouseWheelEvent(x: f32, y: f32) void; pub const addKeyEvent = zguiIoAddKeyEvent; extern fn zguiIoAddKeyEvent(key: Key, down: bool) void; pub const addInputCharactersUTF8 = zguiIoAddInputCharactersUTF8; extern fn zguiIoAddInputCharactersUTF8(utf8_chars: ?[*:0]const u8) void; pub fn setKeyEventNativeData(key: Key, keycode: i32, scancode: i32) void { zguiIoSetKeyEventNativeData(key, keycode, scancode); } extern fn zguiIoSetKeyEventNativeData(key: Key, keycode: c_int, scancode: c_int) void; pub fn addCharacterEvent(char: i32) void { zguiIoAddCharacterEvent(char); } extern fn zguiIoAddCharacterEvent(char: c_int) void; }; pub fn setClipboardText(value: [:0]const u8) void { zguiSetClipboardText(value.ptr); } pub fn getClipboardText() [:0]const u8 { const value = zguiGetClipboardText(); return std.mem.span(value); } extern fn zguiSetClipboardText(text: [*:0]const u8) void; extern fn zguiGetClipboardText() [*:0]const u8; //-------------------------------------------------------------------------------------------------- const Context = *opaque {}; pub const DrawData = *extern struct { valid: bool, cmd_lists_count: c_int, total_idx_count: c_int, total_vtx_count: c_int, cmd_lists: Vector(DrawList), display_pos: [2]f32, display_size: [2]f32, framebuffer_scale: [2]f32, }; pub const Font = *opaque {}; pub const Ident = u32; pub const TextureIdent = *anyopaque; pub const Wchar = if (@import("zgui_options").use_wchar32) u32 else u16; pub const Key = enum(c_int) { none = 0, tab = 512, left_arrow, right_arrow, up_arrow, down_arrow, page_up, page_down, home, end, insert, delete, back_space, space, enter, escape, left_ctrl, left_shift, left_alt, left_super, right_ctrl, right_shift, right_alt, right_super, menu, zero, one, two, three, four, five, six, seven, eight, nine, a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z, f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12, f13, f14, f15, f16, f17, f18, f19, f20, f21, f22, f23, f24, apostrophe, comma, minus, period, slash, semicolon, equal, left_bracket, back_slash, right_bracket, grave_accent, caps_lock, scroll_lock, num_lock, print_screen, pause, keypad_0, keypad_1, keypad_2, keypad_3, keypad_4, keypad_5, keypad_6, keypad_7, keypad_8, keypad_9, keypad_decimal, keypad_divide, keypad_multiply, keypad_subtract, keypad_add, keypad_enter, keypad_equal, app_back, app_forward, gamepad_start, gamepad_back, gamepad_faceleft, gamepad_faceright, gamepad_faceup, gamepad_facedown, gamepad_dpadleft, gamepad_dpadright, gamepad_dpadup, gamepad_dpaddown, gamepad_l1, gamepad_r1, gamepad_l2, gamepad_r2, gamepad_l3, gamepad_r3, gamepad_lstickleft, gamepad_lstickright, gamepad_lstickup, gamepad_lstickdown, gamepad_rstickleft, gamepad_rstickright, gamepad_rstickup, gamepad_rstickdown, mouse_left, mouse_right, mouse_middle, mouse_x1, mouse_x2, mouse_wheel_x, mouse_wheel_y, mod_ctrl = 1 << 12, mod_shift = 1 << 13, mod_alt = 1 << 14, mod_super = 1 << 15, mod_mask_ = 0xf000, }; //-------------------------------------------------------------------------------------------------- pub const WindowFlags = packed struct(c_int) { no_title_bar: bool = false, no_resize: bool = false, no_move: bool = false, no_scrollbar: bool = false, no_scroll_with_mouse: bool = false, no_collapse: bool = false, always_auto_resize: bool = false, no_background: bool = false, no_saved_settings: bool = false, no_mouse_inputs: bool = false, menu_bar: bool = false, horizontal_scrollbar: bool = false, no_focus_on_appearing: bool = false, no_bring_to_front_on_focus: bool = false, always_vertical_scrollbar: bool = false, always_horizontal_scrollbar: bool = false, no_nav_inputs: bool = false, no_nav_focus: bool = false, unsaved_document: bool = false, no_docking: bool = false, _padding: u12 = 0, pub const no_nav = WindowFlags{ .no_nav_inputs = true, .no_nav_focus = true }; pub const no_decoration = WindowFlags{ .no_title_bar = true, .no_resize = true, .no_scrollbar = true, .no_collapse = true, }; pub const no_inputs = WindowFlags{ .no_mouse_inputs = true, .no_nav_inputs = true, .no_nav_focus = true, }; }; pub const ChildFlags = packed struct(c_int) { border: bool = false, no_move: bool = false, always_use_window_padding: bool = false, resize_x: bool = false, resize_y: bool = false, auto_resize_x: bool = false, auto_resize_y: bool = false, always_auto_resize: bool = false, frame_style: bool = false, _padding: u23 = 0, }; //-------------------------------------------------------------------------------------------------- pub const SliderFlags = packed struct(c_int) { _reserved0: bool = false, _reserved1: bool = false, _reserved2: bool = false, _reserved3: bool = false, always_clamp: bool = false, logarithmic: bool = false, no_round_to_format: bool = false, no_input: bool = false, _padding: u24 = 0, }; //-------------------------------------------------------------------------------------------------- pub const ButtonFlags = packed struct(c_int) { mouse_button_left: bool = false, mouse_button_right: bool = false, mouse_button_middle: bool = false, _padding: u29 = 0, }; //-------------------------------------------------------------------------------------------------- pub const Direction = enum(c_int) { none = -1, left = 0, right = 1, up = 2, down = 3, }; //-------------------------------------------------------------------------------------------------- pub const DataType = enum(c_int) { I8, U8, I16, U16, I32, U32, I64, U64, F32, F64 }; //-------------------------------------------------------------------------------------------------- pub const Condition = enum(c_int) { none = 0, always = 1, once = 2, first_use_ever = 4, appearing = 8, }; //-------------------------------------------------------------------------------------------------- // // Main // //-------------------------------------------------------------------------------------------------- /// `pub fn newFrame() void` pub const newFrame = zguiNewFrame; extern fn zguiNewFrame() void; //-------------------------------------------------------------------------------------------------- /// `pub fn render() void` pub const render = zguiRender; extern fn zguiRender() void; //-------------------------------------------------------------------------------------------------- /// `pub fn getDrawData() DrawData` pub const getDrawData = zguiGetDrawData; extern fn zguiGetDrawData() DrawData; //-------------------------------------------------------------------------------------------------- // // Demo, Debug, Information // //-------------------------------------------------------------------------------------------------- /// `pub fn showDemoWindow(popen: ?*bool) void` pub const showDemoWindow = zguiShowDemoWindow; extern fn zguiShowDemoWindow(popen: ?*bool) void; //-------------------------------------------------------------------------------------------------- // // Windows // //-------------------------------------------------------------------------------------------------- const SetNextWindowPos = struct { x: f32, y: f32, cond: Condition = .none, pivot_x: f32 = 0.0, pivot_y: f32 = 0.0, }; pub fn setNextWindowPos(args: SetNextWindowPos) void { zguiSetNextWindowPos(args.x, args.y, args.cond, args.pivot_x, args.pivot_y); } extern fn zguiSetNextWindowPos(x: f32, y: f32, cond: Condition, pivot_x: f32, pivot_y: f32) void; //-------------------------------------------------------------------------------------------------- const SetNextWindowSize = struct { w: f32, h: f32, cond: Condition = .none, }; pub fn setNextWindowSize(args: SetNextWindowSize) void { zguiSetNextWindowSize(args.w, args.h, args.cond); } extern fn zguiSetNextWindowSize(w: f32, h: f32, cond: Condition) void; //-------------------------------------------------------------------------------------------------- const SetNextWindowCollapsed = struct { collapsed: bool, cond: Condition = .none, }; pub fn setNextWindowCollapsed(args: SetNextWindowCollapsed) void { zguiSetNextWindowCollapsed(args.collapsed, args.cond); } extern fn zguiSetNextWindowCollapsed(collapsed: bool, cond: Condition) void; //-------------------------------------------------------------------------------------------------- /// `pub fn setNextWindowFocus() void` pub const setNextWindowFocus = zguiSetNextWindowFocus; extern fn zguiSetNextWindowFocus() void; //-------------------------------------------------------------------------------------------------- const SetNextWindowBgAlpha = struct { alpha: f32, }; pub fn setNextWindowBgAlpha(args: SetNextWindowBgAlpha) void { zguiSetNextWindowBgAlpha(args.alpha); } extern fn zguiSetNextWindowBgAlpha(alpha: f32) void; //-------------------------------------------------------------------------------------------------- pub fn setWindowFocus(name: ?[:0]const u8) void { zguiSetWindowFocus(name orelse null); } extern fn zguiSetWindowFocus(name: ?[*:0]const u8) void; //------------------------------------------------------------------------------------------------- pub fn setKeyboardFocusHere(offset: i32) void { zguiSetKeyboardFocusHere(offset); } extern fn zguiSetKeyboardFocusHere(offset: c_int) void; //-------------------------------------------------------------------------------------------------- const Begin = struct { popen: ?*bool = null, flags: WindowFlags = .{}, }; pub fn begin(name: [:0]const u8, args: Begin) bool { return zguiBegin(name, args.popen, args.flags); } /// `pub fn end() void` pub const end = zguiEnd; extern fn zguiBegin(name: [*:0]const u8, popen: ?*bool, flags: WindowFlags) bool; extern fn zguiEnd() void; //-------------------------------------------------------------------------------------------------- const BeginChild = struct { w: f32 = 0.0, h: f32 = 0.0, child_flags: ChildFlags = .{}, window_flags: WindowFlags = .{}, }; pub fn beginChild(str_id: [:0]const u8, args: BeginChild) bool { return zguiBeginChild(str_id, args.w, args.h, args.child_flags, args.window_flags); } pub fn beginChildId(id: Ident, args: BeginChild) bool { return zguiBeginChildId(id, args.w, args.h, args.child_flags, args.window_flags); } /// `pub fn endChild() void` pub const endChild = zguiEndChild; extern fn zguiBeginChild(str_id: [*:0]const u8, w: f32, h: f32, flags: ChildFlags, window_flags: WindowFlags) bool; extern fn zguiBeginChildId(id: Ident, w: f32, h: f32, flags: ChildFlags, window_flags: WindowFlags) bool; extern fn zguiEndChild() void; //-------------------------------------------------------------------------------------------------- /// `pub fn zguiGetScrollX() f32` pub const getScrollX = zguiGetScrollX; /// `pub fn zguiGetScrollY() f32` pub const getScrollY = zguiGetScrollY; /// `pub fn zguiSetScrollX(scroll_x: f32) void` pub const setScrollX = zguiSetScrollX; /// `pub fn zguiSetScrollY(scroll_y: f32) void` pub const setScrollY = zguiSetScrollY; /// `pub fn zguiGetScrollMaxX() f32` pub const getScrollMaxX = zguiGetScrollMaxX; /// `pub fn zguiGetScrollMaxY() f32` pub const getScrollMaxY = zguiGetScrollMaxY; extern fn zguiGetScrollX() f32; extern fn zguiGetScrollY() f32; extern fn zguiSetScrollX(scroll_x: f32) void; extern fn zguiSetScrollY(scroll_y: f32) void; extern fn zguiGetScrollMaxX() f32; extern fn zguiGetScrollMaxY() f32; const SetScrollHereX = struct { center_x_ratio: f32 = 0.5, }; const SetScrollHereY = struct { center_y_ratio: f32 = 0.5, }; pub fn setScrollHereX(args: SetScrollHereX) void { zguiSetScrollHereX(args.center_x_ratio); } pub fn setScrollHereY(args: SetScrollHereY) void { zguiSetScrollHereY(args.center_y_ratio); } const SetScrollFromPosX = struct { local_x: f32, center_x_ratio: f32 = 0.5, }; const SetScrollFromPosY = struct { local_y: f32, center_y_ratio: f32 = 0.5, }; pub fn setScrollFromPosX(args: SetScrollFromPosX) void { zguiSetScrollFromPosX(args.local_x, args.center_x_ratio); } pub fn setScrollFromPosY(args: SetScrollFromPosY) void { zguiSetScrollFromPosY(args.local_y, args.center_y_ratio); } extern fn zguiSetScrollHereX(center_x_ratio: f32) void; extern fn zguiSetScrollHereY(center_y_ratio: f32) void; extern fn zguiSetScrollFromPosX(local_x: f32, center_x_ratio: f32) void; extern fn zguiSetScrollFromPosY(local_y: f32, center_y_ratio: f32) void; //-------------------------------------------------------------------------------------------------- pub const FocusedFlags = packed struct(c_int) { child_windows: bool = false, root_window: bool = false, any_window: bool = false, no_popup_hierarchy: bool = false, dock_hierarchy: bool = false, _padding: u27 = 0, pub const root_and_child_windows = FocusedFlags{ .root_window = true, .child_windows = true }; }; //-------------------------------------------------------------------------------------------------- pub const HoveredFlags = packed struct(c_int) { child_windows: bool = false, root_window: bool = false, any_window: bool = false, no_popup_hierarchy: bool = false, dock_hierarchy: bool = false, allow_when_blocked_by_popup: bool = false, _reserved1: bool = false, allow_when_blocked_by_active_item: bool = false, allow_when_overlapped_by_item: bool = false, allow_when_overlapped_by_window: bool = false, allow_when_disabled: bool = false, no_nav_override: bool = false, for_tooltip: bool = false, stationary: bool = false, delay_none: bool = false, delay_normal: bool = false, delay_short: bool = false, no_shared_delay: bool = false, _padding: u14 = 0, pub const rect_only = HoveredFlags{ .allow_when_blocked_by_popup = true, .allow_when_blocked_by_active_item = true, .allow_when_overlapped_by_item = true, .allow_when_overlapped_by_window = true, }; pub const root_and_child_windows = HoveredFlags{ .root_window = true, .child_windows = true }; }; //-------------------------------------------------------------------------------------------------- /// `pub fn isWindowAppearing() bool` pub const isWindowAppearing = zguiIsWindowAppearing; /// `pub fn isWindowCollapsed() bool` pub const isWindowCollapsed = zguiIsWindowCollapsed; pub fn isWindowFocused(flags: FocusedFlags) bool { return zguiIsWindowFocused(flags); } pub fn isWindowHovered(flags: HoveredFlags) bool { return zguiIsWindowHovered(flags); } extern fn zguiIsWindowAppearing() bool; extern fn zguiIsWindowCollapsed() bool; extern fn zguiIsWindowFocused(flags: FocusedFlags) bool; extern fn zguiIsWindowHovered(flags: HoveredFlags) bool; //-------------------------------------------------------------------------------------------------- pub fn getWindowPos() [2]f32 { var pos: [2]f32 = undefined; zguiGetWindowPos(&pos); return pos; } pub fn getWindowSize() [2]f32 { var size: [2]f32 = undefined; zguiGetWindowSize(&size); return size; } pub fn getContentRegionAvail() [2]f32 { var size: [2]f32 = undefined; zguiGetContentRegionAvail(&size); return size; } pub fn getContentRegionMax() [2]f32 { var size: [2]f32 = undefined; zguiGetContentRegionMax(&size); return size; } pub fn getWindowContentRegionMin() [2]f32 { var size: [2]f32 = undefined; zguiGetWindowContentRegionMin(&size); return size; } pub fn getWindowContentRegionMax() [2]f32 { var size: [2]f32 = undefined; zguiGetWindowContentRegionMax(&size); return size; } /// `pub fn getWindowWidth() f32` pub const getWindowWidth = zguiGetWindowWidth; /// `pub fn getWindowHeight() f32` pub const getWindowHeight = zguiGetWindowHeight; extern fn zguiGetWindowPos(pos: *[2]f32) void; extern fn zguiGetWindowSize(size: *[2]f32) void; extern fn zguiGetWindowWidth() f32; extern fn zguiGetWindowHeight() f32; extern fn zguiGetContentRegionAvail(size: *[2]f32) void; extern fn zguiGetContentRegionMax(size: *[2]f32) void; extern fn zguiGetWindowContentRegionMin(size: *[2]f32) void; extern fn zguiGetWindowContentRegionMax(size: *[2]f32) void; //-------------------------------------------------------------------------------------------------- // // Docking // //-------------------------------------------------------------------------------------------------- pub const DockNodeFlags = packed struct(c_int) { keep_alive_only: bool = false, _reserved: u1 = 0, no_docking_over_central_node: bool = false, passthru_central_node: bool = false, no_docking_split: bool = false, no_resize: bool = false, auto_hide_tab_bar: bool = false, no_undocking: bool = false, _padding_0: u2 = 0, // Extended enum entries from imgui_internal (unstable, subject to change, use at own risk) dock_space: bool = false, central_node: bool = false, no_tab_bar: bool = false, hidden_tab_bar: bool = false, no_window_menu_button: bool = false, no_close_button: bool = false, no_resize_x: bool = false, no_resize_y: bool = false, docked_windows_in_focus_route: bool = false, no_docking_split_other: bool = false, no_docking_over_me: bool = false, no_docking_over_other: bool = false, no_docking_over_empty: bool = false, _padding_1: u9 = 0, }; extern fn zguiDockSpace(str_id: [*:0]const u8, size: *const [2]f32, flags: DockNodeFlags) Ident; pub fn DockSpace(str_id: [:0]const u8, size: [2]f32, flags: DockNodeFlags) Ident { return zguiDockSpace(str_id.ptr, &size, flags); } extern fn zguiDockSpaceOverViewport(viewport: Viewport, flags: DockNodeFlags) Ident; pub const DockSpaceOverViewport = zguiDockSpaceOverViewport; //-------------------------------------------------------------------------------------------------- // // DockBuilder (Unstable internal imgui API, subject to change, use at own risk) // //-------------------------------------------------------------------------------------------------- pub fn dockBuilderDockWindow(window_name: [:0]const u8, node_id: Ident) void { zguiDockBuilderDockWindow(window_name.ptr, node_id); } pub const dockBuilderAddNode = zguiDockBuilderAddNode; pub const dockBuilderRemoveNode = zguiDockBuilderRemoveNode; pub fn dockBuilderSetNodePos(node_id: Ident, pos: [2]f32) void { zguiDockBuilderSetNodePos(node_id, &pos); } pub fn dockBuilderSetNodeSize(node_id: Ident, size: [2]f32) void { zguiDockBuilderSetNodeSize(node_id, &size); } pub const dockBuilderSplitNode = zguiDockBuilderSplitNode; pub const dockBuilderFinish = zguiDockBuilderFinish; extern fn zguiDockBuilderDockWindow(window_name: [*:0]const u8, node_id: Ident) void; extern fn zguiDockBuilderAddNode(node_id: Ident, flags: DockNodeFlags) Ident; extern fn zguiDockBuilderRemoveNode(node_id: Ident) void; extern fn zguiDockBuilderSetNodePos(node_id: Ident, pos: *const [2]f32) void; extern fn zguiDockBuilderSetNodeSize(node_id: Ident, size: *const [2]f32) void; extern fn zguiDockBuilderSplitNode( node_id: Ident, split_dir: Direction, size_ratio_for_node_at_dir: f32, out_id_at_dir: ?*Ident, out_id_at_opposite_dir: ?*Ident, ) Ident; extern fn zguiDockBuilderFinish(node_id: Ident) void; //-------------------------------------------------------------------------------------------------- // // Style // //-------------------------------------------------------------------------------------------------- pub const Style = extern struct { alpha: f32, disabled_alpha: f32, window_padding: [2]f32, window_rounding: f32, window_border_size: f32, window_min_size: [2]f32, window_title_align: [2]f32, window_menu_button_position: Direction, child_rounding: f32, child_border_size: f32, popup_rounding: f32, popup_border_size: f32, frame_padding: [2]f32, frame_rounding: f32, frame_border_size: f32, item_spacing: [2]f32, item_inner_spacing: [2]f32, cell_padding: [2]f32, touch_extra_padding: [2]f32, indent_spacing: f32, columns_min_spacing: f32, scrollbar_size: f32, scrollbar_rounding: f32, grab_min_size: f32, grab_rounding: f32, log_slider_deadzone: f32, tab_rounding: f32, tab_border_size: f32, tab_min_width_for_close_button: f32, tab_bar_border_size: f32, table_angled_header_angle: f32, color_button_position: Direction, button_text_align: [2]f32, selectable_text_align: [2]f32, separator_text_border_size: f32, separator_text_align: [2]f32, separator_text_padding: [2]f32, display_window_padding: [2]f32, display_safe_area_padding: [2]f32, docking_separator_size: f32, mouse_cursor_scale: f32, anti_aliased_lines: bool, anti_aliased_lines_use_tex: bool, anti_aliased_fill: bool, curve_tessellation_tol: f32, circle_tessellation_max_error: f32, colors: [@typeInfo(StyleCol).Enum.fields.len][4]f32, hover_stationary_delay: f32, hover_delay_short: f32, hover_delay_normal: f32, hover_flags_for_tooltip_mouse: HoveredFlags, hover_flags_for_tooltip_nav: HoveredFlags, /// `pub fn init() Style` pub const init = zguiStyle_Init; extern fn zguiStyle_Init() Style; /// `pub fn scaleAllSizes(style: *Style, scale_factor: f32) void` pub const scaleAllSizes = zguiStyle_ScaleAllSizes; extern fn zguiStyle_ScaleAllSizes(style: *Style, scale_factor: f32) void; pub fn getColor(style: Style, idx: StyleCol) [4]f32 { return style.colors[@intCast(@intFromEnum(idx))]; } pub fn setColor(style: *Style, idx: StyleCol, color: [4]f32) void { style.colors[@intCast(@intFromEnum(idx))] = color; } }; /// `pub fn getStyle() *Style` pub const getStyle = zguiGetStyle; extern fn zguiGetStyle() *Style; //-------------------------------------------------------------------------------------------------- pub const StyleCol = enum(c_int) { text, text_disabled, window_bg, child_bg, popup_bg, border, border_shadow, frame_bg, frame_bg_hovered, frame_bg_active, title_bg, title_bg_active, title_bg_collapsed, menu_bar_bg, scrollbar_bg, scrollbar_grab, scrollbar_grab_hovered, scrollbar_grab_active, check_mark, slider_grab, slider_grab_active, button, button_hovered, button_active, header, header_hovered, header_active, separator, separator_hovered, separator_active, resize_grip, resize_grip_hovered, resize_grip_active, tab, tab_hovered, tab_active, tab_unfocused, tab_unfocused_active, docking_preview, docking_empty_bg, plot_lines, plot_lines_hovered, plot_histogram, plot_histogram_hovered, table_header_bg, table_border_strong, table_border_light, table_row_bg, table_row_bg_alt, text_selected_bg, drag_drop_target, nav_highlight, nav_windowing_highlight, nav_windowing_dim_bg, modal_window_dim_bg, }; pub fn pushStyleColor4f(args: struct { idx: StyleCol, c: [4]f32, }) void { zguiPushStyleColor4f(args.idx, &args.c); } extern fn zguiPushStyleColor4f(idx: StyleCol, col: *const [4]f32) void; pub fn pushStyleColor1u(args: struct { idx: StyleCol, c: u32, }) void { zguiPushStyleColor1u(args.idx, args.c); } extern fn zguiPushStyleColor1u(idx: StyleCol, col: c_uint) void; pub fn popStyleColor(args: struct { count: i32 = 1, }) void { zguiPopStyleColor(args.count); } extern fn zguiPopStyleColor(count: c_int) void; /// `fn pushTextWrapPos(wrap_pos_x: f32) void` pub const pushTextWrapPos = zguiPushTextWrapPos; extern fn zguiPushTextWrapPos(wrap_pos_x: f32) void; /// `fn popTextWrapPos() void` pub const popTextWrapPos = zguiPopTextWrapPos; extern fn zguiPopTextWrapPos() void; //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- pub const StyleVar = enum(c_int) { alpha, // 1f disabled_alpha, // 1f window_padding, // 2f window_rounding, // 1f window_border_size, // 1f window_min_size, // 2f window_title_align, // 2f child_rounding, // 1f child_border_size, // 1f popup_rounding, // 1f popup_border_size, // 1f frame_padding, // 2f frame_rounding, // 1f frame_border_size, // 1f item_spacing, // 2f item_inner_spacing, // 2f indent_spacing, // 1f cell_padding, // 2f scrollbar_size, // 1f scrollbar_rounding, // 1f grab_min_size, // 1f grab_rounding, // 1f tab_rounding, // 1f tab_bar_border_size, // 1f button_text_align, // 2f selectable_text_align, // 2f separator_text_border_size, // 1f separator_text_align, // 2f separator_text_padding, // 2f docking_separator_size, // 1f }; pub fn pushStyleVar1f(args: struct { idx: StyleVar, v: f32, }) void { zguiPushStyleVar1f(args.idx, args.v); } extern fn zguiPushStyleVar1f(idx: StyleVar, v: f32) void; pub fn pushStyleVar2f(args: struct { idx: StyleVar, v: [2]f32, }) void { zguiPushStyleVar2f(args.idx, &args.v); } extern fn zguiPushStyleVar2f(idx: StyleVar, v: *const [2]f32) void; pub fn popStyleVar(args: struct { count: i32 = 1, }) void { zguiPopStyleVar(args.count); } extern fn zguiPopStyleVar(count: c_int) void; //-------------------------------------------------------------------------------------------------- /// `void pushItemWidth(item_width: f32) void` pub const pushItemWidth = zguiPushItemWidth; /// `void popItemWidth() void` pub const popItemWidth = zguiPopItemWidth; /// `void setNextItemWidth(item_width: f32) void` pub const setNextItemWidth = zguiSetNextItemWidth; /// `void setItemDefaultFocus() void` pub const setItemDefaultFocus = zguiSetItemDefaultFocus; extern fn zguiPushItemWidth(item_width: f32) void; extern fn zguiPopItemWidth() void; extern fn zguiSetNextItemWidth(item_width: f32) void; extern fn zguiSetItemDefaultFocus() void; //-------------------------------------------------------------------------------------------------- /// `pub fn getFont() Font` pub const getFont = zguiGetFont; extern fn zguiGetFont() Font; /// `pub fn getFontSize() f32` pub const getFontSize = zguiGetFontSize; extern fn zguiGetFontSize() f32; /// `void pushFont(font: Font) void` pub const pushFont = zguiPushFont; extern fn zguiPushFont(font: Font) void; /// `void popFont() void` pub const popFont = zguiPopFont; extern fn zguiPopFont() void; pub fn getFontTexUvWhitePixel() [2]f32 { var uv: [2]f32 = undefined; zguiGetFontTexUvWhitePixel(&uv); return uv; } extern fn zguiGetFontTexUvWhitePixel(uv: *[2]f32) void; //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- const BeginDisabled = struct { disabled: bool = true, }; pub fn beginDisabled(args: BeginDisabled) void { zguiBeginDisabled(args.disabled); } /// `pub fn endDisabled() void` pub const endDisabled = zguiEndDisabled; extern fn zguiBeginDisabled(disabled: bool) void; extern fn zguiEndDisabled() void; //-------------------------------------------------------------------------------------------------- // // Cursor / Layout // //-------------------------------------------------------------------------------------------------- /// `pub fn separator() void` pub const separator = zguiSeparator; extern fn zguiSeparator() void; pub fn separatorText(label: [:0]const u8) void { zguiSeparatorText(label); } extern fn zguiSeparatorText(label: [*:0]const u8) void; //-------------------------------------------------------------------------------------------------- const SameLine = struct { offset_from_start_x: f32 = 0.0, spacing: f32 = -1.0, }; pub fn sameLine(args: SameLine) void { zguiSameLine(args.offset_from_start_x, args.spacing); } extern fn zguiSameLine(offset_from_start_x: f32, spacing: f32) void; //-------------------------------------------------------------------------------------------------- /// `pub fn newLine() void` pub const newLine = zguiNewLine; extern fn zguiNewLine() void; //-------------------------------------------------------------------------------------------------- /// `pub fn spacing() void` pub const spacing = zguiSpacing; extern fn zguiSpacing() void; //-------------------------------------------------------------------------------------------------- const Dummy = struct { w: f32, h: f32, }; pub fn dummy(args: Dummy) void { zguiDummy(args.w, args.h); } extern fn zguiDummy(w: f32, h: f32) void; //-------------------------------------------------------------------------------------------------- const Indent = struct { indent_w: f32 = 0.0, }; pub fn indent(args: Indent) void { zguiIndent(args.indent_w); } const Unindent = struct { indent_w: f32 = 0.0, }; pub fn unindent(args: Unindent) void { zguiUnindent(args.indent_w); } extern fn zguiIndent(indent_w: f32) void; extern fn zguiUnindent(indent_w: f32) void; //-------------------------------------------------------------------------------------------------- /// `pub fn beginGroup() void` pub const beginGroup = zguiBeginGroup; extern fn zguiBeginGroup() void; /// `pub fn endGroup() void` pub const endGroup = zguiEndGroup; extern fn zguiEndGroup() void; //-------------------------------------------------------------------------------------------------- pub fn getCursorPos() [2]f32 { var pos: [2]f32 = undefined; zguiGetCursorPos(&pos); return pos; } /// `pub fn getCursorPosX() f32` pub const getCursorPosX = zguiGetCursorPosX; /// `pub fn getCursorPosY() f32` pub const getCursorPosY = zguiGetCursorPosY; extern fn zguiGetCursorPos(pos: *[2]f32) void; extern fn zguiGetCursorPosX() f32; extern fn zguiGetCursorPosY() f32; //-------------------------------------------------------------------------------------------------- pub fn setCursorPos(local_pos: [2]f32) void { zguiSetCursorPos(local_pos[0], local_pos[1]); } /// `pub fn setCursorPosX(local_x: f32) void` pub const setCursorPosX = zguiSetCursorPosX; /// `pub fn setCursorPosY(local_y: f32) void` pub const setCursorPosY = zguiSetCursorPosY; extern fn zguiSetCursorPos(local_x: f32, local_y: f32) void; extern fn zguiSetCursorPosX(local_x: f32) void; extern fn zguiSetCursorPosY(local_y: f32) void; //-------------------------------------------------------------------------------------------------- pub fn getCursorStartPos() [2]f32 { var pos: [2]f32 = undefined; zguiGetCursorStartPos(&pos); return pos; } pub fn getCursorScreenPos() [2]f32 { var pos: [2]f32 = undefined; zguiGetCursorScreenPos(&pos); return pos; } pub fn setCursorScreenPos(screen_pos: [2]f32) void { zguiSetCursorPos(screen_pos[0], screen_pos[1]); } extern fn zguiGetCursorStartPos(pos: *[2]f32) void; extern fn zguiGetCursorScreenPos(pos: *[2]f32) void; extern fn zguiSetCursorScreenPos(screen_x: f32, screen_y: f32) void; //-------------------------------------------------------------------------------------------------- pub const Cursor = enum(c_int) { none = -1, arrow = 0, text_input, resize_all, resize_ns, resize_ew, resize_nesw, resize_nwse, hand, not_allowed, count, }; /// `pub fn getMouseCursor() MouseCursor` pub const getMouseCursor = zguiGetMouseCursor; /// `pub fn setMouseCursor(cursor: MouseCursor) void` pub const setMouseCursor = zguiSetMouseCursor; extern fn zguiGetMouseCursor() Cursor; extern fn zguiSetMouseCursor(cursor: Cursor) void; //-------------------------------------------------------------------------------------------------- pub fn getMousePos() [2]f32 { var pos: [2]f32 = undefined; zguiGetMousePos(&pos); return pos; } extern fn zguiGetMousePos(pos: *[2]f32) void; //-------------------------------------------------------------------------------------------------- /// `pub fn alignTextToFramePadding() void` pub const alignTextToFramePadding = zguiAlignTextToFramePadding; /// `pub fn getTextLineHeight() f32` pub const getTextLineHeight = zguiGetTextLineHeight; /// `pub fn getTextLineHeightWithSpacing() f32` pub const getTextLineHeightWithSpacing = zguiGetTextLineHeightWithSpacing; /// `pub fn getFrameHeight() f32` pub const getFrameHeight = zguiGetFrameHeight; /// `pub fn getFrameHeightWithSpacing() f32` pub const getFrameHeightWithSpacing = zguiGetFrameHeightWithSpacing; extern fn zguiAlignTextToFramePadding() void; extern fn zguiGetTextLineHeight() f32; extern fn zguiGetTextLineHeightWithSpacing() f32; extern fn zguiGetFrameHeight() f32; extern fn zguiGetFrameHeightWithSpacing() f32; //-------------------------------------------------------------------------------------------------- pub fn getItemRectMax() [2]f32 { var rect: [2]f32 = undefined; zguiGetItemRectMax(&rect); return rect; } pub fn getItemRectMin() [2]f32 { var rect: [2]f32 = undefined; zguiGetItemRectMin(&rect); return rect; } pub fn getItemRectSize() [2]f32 { var rect: [2]f32 = undefined; zguiGetItemRectSize(&rect); return rect; } extern fn zguiGetItemRectMax(rect: *[2]f32) void; extern fn zguiGetItemRectMin(rect: *[2]f32) void; extern fn zguiGetItemRectSize(rect: *[2]f32) void; //-------------------------------------------------------------------------------------------------- // // ID stack/scopes // //-------------------------------------------------------------------------------------------------- pub fn pushStrId(str_id: []const u8) void { zguiPushStrId(str_id.ptr, str_id.ptr + str_id.len); } extern fn zguiPushStrId(str_id_begin: [*]const u8, str_id_end: [*]const u8) void; pub fn pushStrIdZ(str_id: [:0]const u8) void { zguiPushStrIdZ(str_id); } extern fn zguiPushStrIdZ(str_id: [*:0]const u8) void; pub fn pushPtrId(ptr_id: *const anyopaque) void { zguiPushPtrId(ptr_id); } extern fn zguiPushPtrId(ptr_id: *const anyopaque) void; pub fn pushIntId(int_id: i32) void { zguiPushIntId(int_id); } extern fn zguiPushIntId(int_id: c_int) void; /// `pub fn popId() void` pub const popId = zguiPopId; extern fn zguiPopId() void; pub fn getStrId(str_id: []const u8) Ident { return zguiGetStrId(str_id.ptr, str_id.ptr + str_id.len); } extern fn zguiGetStrId(str_id_begin: [*]const u8, str_id_end: [*]const u8) Ident; pub fn getStrIdZ(str_id: [:0]const u8) Ident { return zguiGetStrIdZ(str_id); } extern fn zguiGetStrIdZ(str_id: [*:0]const u8) Ident; pub fn getPtrId(ptr_id: *const anyopaque) Ident { return zguiGetPtrId(ptr_id); } extern fn zguiGetPtrId(ptr_id: *const anyopaque) Ident; //-------------------------------------------------------------------------------------------------- // // Widgets: Text // //-------------------------------------------------------------------------------------------------- pub fn textUnformatted(txt: []const u8) void { zguiTextUnformatted(txt.ptr, txt.ptr + txt.len); } pub fn textUnformattedColored(color: [4]f32, txt: []const u8) void { pushStyleColor4f(.{ .idx = .text, .c = color }); textUnformatted(txt); popStyleColor(.{}); } //-------------------------------------------------------------------------------------------------- pub fn text(comptime fmt: []const u8, args: anytype) void { const result = format(fmt, args); zguiTextUnformatted(result.ptr, result.ptr + result.len); } pub fn textColored(color: [4]f32, comptime fmt: []const u8, args: anytype) void { pushStyleColor4f(.{ .idx = .text, .c = color }); text(fmt, args); popStyleColor(.{}); } extern fn zguiTextUnformatted(txt: [*]const u8, txt_end: [*]const u8) void; //-------------------------------------------------------------------------------------------------- pub fn textDisabled(comptime fmt: []const u8, args: anytype) void { zguiTextDisabled("%s", formatZ(fmt, args).ptr); } extern fn zguiTextDisabled(fmt: [*:0]const u8, ...) void; //-------------------------------------------------------------------------------------------------- pub fn textWrapped(comptime fmt: []const u8, args: anytype) void { zguiTextWrapped("%s", formatZ(fmt, args).ptr); } extern fn zguiTextWrapped(fmt: [*:0]const u8, ...) void; //-------------------------------------------------------------------------------------------------- pub fn bulletText(comptime fmt: []const u8, args: anytype) void { bullet(); text(fmt, args); } //-------------------------------------------------------------------------------------------------- pub fn labelText(label: [:0]const u8, comptime fmt: []const u8, args: anytype) void { zguiLabelText(label, "%s", formatZ(fmt, args).ptr); } extern fn zguiLabelText(label: [*:0]const u8, fmt: [*:0]const u8, ...) void; //-------------------------------------------------------------------------------------------------- const CalcTextSize = struct { hide_text_after_double_hash: bool = false, wrap_width: f32 = -1.0, }; pub fn calcTextSize(txt: []const u8, args: CalcTextSize) [2]f32 { var w: f32 = undefined; var h: f32 = undefined; zguiCalcTextSize( txt.ptr, txt.ptr + txt.len, args.hide_text_after_double_hash, args.wrap_width, &w, &h, ); return .{ w, h }; } extern fn zguiCalcTextSize( txt: [*]const u8, txt_end: [*]const u8, hide_text_after_double_hash: bool, wrap_width: f32, out_w: *f32, out_h: *f32, ) void; //-------------------------------------------------------------------------------------------------- // // Widgets: Main // //-------------------------------------------------------------------------------------------------- const Button = struct { w: f32 = 0.0, h: f32 = 0.0, }; pub fn button(label: [:0]const u8, args: Button) bool { return zguiButton(label, args.w, args.h); } extern fn zguiButton(label: [*:0]const u8, w: f32, h: f32) bool; //-------------------------------------------------------------------------------------------------- pub fn smallButton(label: [:0]const u8) bool { return zguiSmallButton(label); } extern fn zguiSmallButton(label: [*:0]const u8) bool; //-------------------------------------------------------------------------------------------------- const InvisibleButton = struct { w: f32, h: f32, flags: ButtonFlags = .{}, }; pub fn invisibleButton(str_id: [:0]const u8, args: InvisibleButton) bool { return zguiInvisibleButton(str_id, args.w, args.h, args.flags); } extern fn zguiInvisibleButton(str_id: [*:0]const u8, w: f32, h: f32, flags: ButtonFlags) bool; //-------------------------------------------------------------------------------------------------- const ArrowButton = struct { dir: Direction, }; pub fn arrowButton(label: [:0]const u8, args: ArrowButton) bool { return zguiArrowButton(label, args.dir); } extern fn zguiArrowButton(label: [*:0]const u8, dir: Direction) bool; //-------------------------------------------------------------------------------------------------- const Image = struct { w: f32, h: f32, uv0: [2]f32 = .{ 0.0, 0.0 }, uv1: [2]f32 = .{ 1.0, 1.0 }, tint_col: [4]f32 = .{ 1.0, 1.0, 1.0, 1.0 }, border_col: [4]f32 = .{ 0.0, 0.0, 0.0, 0.0 }, }; pub fn image(user_texture_id: TextureIdent, args: Image) void { zguiImage(user_texture_id, args.w, args.h, &args.uv0, &args.uv1, &args.tint_col, &args.border_col); } extern fn zguiImage( user_texture_id: TextureIdent, w: f32, h: f32, uv0: *const [2]f32, uv1: *const [2]f32, tint_col: *const [4]f32, border_col: *const [4]f32, ) void; //-------------------------------------------------------------------------------------------------- const ImageButton = struct { w: f32, h: f32, uv0: [2]f32 = .{ 0.0, 0.0 }, uv1: [2]f32 = .{ 1.0, 1.0 }, bg_col: [4]f32 = .{ 0.0, 0.0, 0.0, 0.0 }, tint_col: [4]f32 = .{ 1.0, 1.0, 1.0, 1.0 }, }; pub fn imageButton(str_id: [:0]const u8, user_texture_id: TextureIdent, args: ImageButton) bool { return zguiImageButton( str_id, user_texture_id, args.w, args.h, &args.uv0, &args.uv1, &args.bg_col, &args.tint_col, ); } extern fn zguiImageButton( str_id: [*:0]const u8, user_texture_id: TextureIdent, w: f32, h: f32, uv0: *const [2]f32, uv1: *const [2]f32, bg_col: *const [4]f32, tint_col: *const [4]f32, ) bool; //-------------------------------------------------------------------------------------------------- /// `pub fn bullet() void` pub const bullet = zguiBullet; extern fn zguiBullet() void; //-------------------------------------------------------------------------------------------------- pub fn radioButton(label: [:0]const u8, args: struct { active: bool, }) bool { return zguiRadioButton(label, args.active); } extern fn zguiRadioButton(label: [*:0]const u8, active: bool) bool; //-------------------------------------------------------------------------------------------------- pub fn radioButtonStatePtr(label: [:0]const u8, args: struct { v: *i32, v_button: i32, }) bool { return zguiRadioButtonStatePtr(label, args.v, args.v_button); } extern fn zguiRadioButtonStatePtr(label: [*:0]const u8, v: *c_int, v_button: c_int) bool; //-------------------------------------------------------------------------------------------------- pub fn checkbox(label: [:0]const u8, args: struct { v: *bool, }) bool { return zguiCheckbox(label, args.v); } extern fn zguiCheckbox(label: [*:0]const u8, v: *bool) bool; //-------------------------------------------------------------------------------------------------- pub fn checkboxBits(label: [:0]const u8, args: struct { bits: *u32, bits_value: u32, }) bool { return zguiCheckboxBits(label, args.bits, args.bits_value); } extern fn zguiCheckboxBits(label: [*:0]const u8, bits: *c_uint, bits_value: c_uint) bool; //-------------------------------------------------------------------------------------------------- const ProgressBar = struct { fraction: f32, w: f32 = -f32_min, h: f32 = 0.0, overlay: ?[:0]const u8 = null, }; pub fn progressBar(args: ProgressBar) void { zguiProgressBar(args.fraction, args.w, args.h, if (args.overlay) |o| o else null); } extern fn zguiProgressBar(fraction: f32, w: f32, h: f32, overlay: ?[*:0]const u8) void; //-------------------------------------------------------------------------------------------------- // // Widgets: Combo Box // //-------------------------------------------------------------------------------------------------- pub fn combo(label: [:0]const u8, args: struct { current_item: *i32, items_separated_by_zeros: [:0]const u8, popup_max_height_in_items: i32 = -1, }) bool { return zguiCombo( label, args.current_item, args.items_separated_by_zeros, args.popup_max_height_in_items, ); } /// creates a combo box directly from a pointer to an enum value using zig's /// comptime mechanics to infer the items for the list at compile time pub fn comboFromEnum( label: [:0]const u8, /// must be a pointer to an enum value (var my_enum: *FoodKinds = .Banana) /// that is backed by some kind of integer that can safely cast into an /// i32 (the underlying imgui restriction) current_item: anytype, ) bool { const EnumType = @TypeOf(current_item.*); const enum_type_info = switch (@typeInfo(EnumType)) { .Enum => |enum_type_info| enum_type_info, else => @compileError("Error: current_item must be a pointer-to-an-enum, not a " ++ @TypeOf(current_item)), }; const FieldNameIndex = std.meta.Tuple(&.{ []const u8, i32 }); comptime var item_names: [:0]const u8 = ""; comptime var field_name_to_index_list: [enum_type_info.fields.len]FieldNameIndex = undefined; comptime var index_to_enum: [enum_type_info.fields.len]EnumType = undefined; comptime { for (enum_type_info.fields, 0..) |f, i| { item_names = item_names ++ f.name ++ "\x00"; const e: EnumType = @enumFromInt(f.value); field_name_to_index_list[i] = .{ f.name, @intCast(i) }; index_to_enum[i] = e; } } const field_name_to_index = std.StaticStringMap(i32).initComptime(&field_name_to_index_list); var item: i32 = field_name_to_index.get(@tagName(current_item.*)).?; const result = combo(label, .{ .items_separated_by_zeros = item_names, .current_item = &item, }); current_item.* = index_to_enum[@intCast(item)]; return result; } extern fn zguiCombo( label: [*:0]const u8, current_item: *c_int, items_separated_by_zeros: [*:0]const u8, popup_max_height_in_items: c_int, ) bool; //-------------------------------------------------------------------------------------------------- pub const ComboFlags = packed struct(c_int) { popup_align_left: bool = false, height_small: bool = false, height_regular: bool = false, height_large: bool = false, height_largest: bool = false, no_arrow_button: bool = false, no_preview: bool = false, width_fit_preview: bool = false, _padding: u24 = 0, }; //-------------------------------------------------------------------------------------------------- const BeginCombo = struct { preview_value: [*:0]const u8, flags: ComboFlags = .{}, }; pub fn beginCombo(label: [:0]const u8, args: BeginCombo) bool { return zguiBeginCombo(label, args.preview_value, args.flags); } extern fn zguiBeginCombo(label: [*:0]const u8, preview_value: ?[*:0]const u8, flags: ComboFlags) bool; //-------------------------------------------------------------------------------------------------- /// `pub fn endCombo() void` pub const endCombo = zguiEndCombo; extern fn zguiEndCombo() void; //-------------------------------------------------------------------------------------------------- // // Widgets: Drag Sliders // //-------------------------------------------------------------------------------------------------- fn DragFloatGen(comptime T: type) type { return struct { v: *T, speed: f32 = 1.0, min: f32 = 0.0, max: f32 = 0.0, cfmt: [:0]const u8 = "%.3f", flags: SliderFlags = .{}, }; } //-------------------------------------------------------------------------------------------------- const DragFloat = DragFloatGen(f32); pub fn dragFloat(label: [:0]const u8, args: DragFloat) bool { return zguiDragFloat( label, args.v, args.speed, args.min, args.max, args.cfmt, args.flags, ); } extern fn zguiDragFloat( label: [*:0]const u8, v: *f32, speed: f32, min: f32, max: f32, cfmt: [*:0]const u8, flags: SliderFlags, ) bool; //-------------------------------------------------------------------------------------------------- const DragFloat2 = DragFloatGen([2]f32); pub fn dragFloat2(label: [:0]const u8, args: DragFloat2) bool { return zguiDragFloat2(label, args.v, args.speed, args.min, args.max, args.cfmt, args.flags); } extern fn zguiDragFloat2( label: [*:0]const u8, v: *[2]f32, speed: f32, min: f32, max: f32, cfmt: [*:0]const u8, flags: SliderFlags, ) bool; //-------------------------------------------------------------------------------------------------- const DragFloat3 = DragFloatGen([3]f32); pub fn dragFloat3(label: [:0]const u8, args: DragFloat3) bool { return zguiDragFloat3(label, args.v, args.speed, args.min, args.max, args.cfmt, args.flags); } extern fn zguiDragFloat3( label: [*:0]const u8, v: *[3]f32, speed: f32, min: f32, max: f32, cfmt: [*:0]const u8, flags: SliderFlags, ) bool; //-------------------------------------------------------------------------------------------------- const DragFloat4 = DragFloatGen([4]f32); pub fn dragFloat4(label: [:0]const u8, args: DragFloat4) bool { return zguiDragFloat4(label, args.v, args.speed, args.min, args.max, args.cfmt, args.flags); } extern fn zguiDragFloat4( label: [*:0]const u8, v: *[4]f32, speed: f32, min: f32, max: f32, cfmt: [*:0]const u8, flags: SliderFlags, ) bool; //-------------------------------------------------------------------------------------------------- const DragFloatRange2 = struct { current_min: *f32, current_max: *f32, speed: f32 = 1.0, min: f32 = 0.0, max: f32 = 0.0, cfmt: [:0]const u8 = "%.3f", cfmt_max: ?[:0]const u8 = null, flags: SliderFlags = .{}, }; pub fn dragFloatRange2(label: [:0]const u8, args: DragFloatRange2) bool { return zguiDragFloatRange2( label, args.current_min, args.current_max, args.speed, args.min, args.max, args.cfmt, if (args.cfmt_max) |fm| fm else null, args.flags, ); } extern fn zguiDragFloatRange2( label: [*:0]const u8, current_min: *f32, current_max: *f32, speed: f32, min: f32, max: f32, cfmt: [*:0]const u8, cfmt_max: ?[*:0]const u8, flags: SliderFlags, ) bool; //-------------------------------------------------------------------------------------------------- fn DragIntGen(comptime T: type) type { return struct { v: *T, speed: f32 = 1.0, min: i32 = 0.0, max: i32 = 0.0, cfmt: [:0]const u8 = "%d", flags: SliderFlags = .{}, }; } //-------------------------------------------------------------------------------------------------- const DragInt = DragIntGen(i32); pub fn dragInt(label: [:0]const u8, args: DragInt) bool { return zguiDragInt(label, args.v, args.speed, args.min, args.max, args.cfmt, args.flags); } extern fn zguiDragInt( label: [*:0]const u8, v: *i32, speed: f32, min: i32, max: i32, cfmt: [*:0]const u8, flags: SliderFlags, ) bool; //-------------------------------------------------------------------------------------------------- const DragInt2 = DragIntGen([2]i32); pub fn dragInt2(label: [:0]const u8, args: DragInt2) bool { return zguiDragInt2(label, args.v, args.speed, args.min, args.max, args.cfmt, args.flags); } extern fn zguiDragInt2( label: [*:0]const u8, v: *[2]i32, speed: f32, min: i32, max: i32, cfmt: [*:0]const u8, flags: SliderFlags, ) bool; //-------------------------------------------------------------------------------------------------- const DragInt3 = DragIntGen([3]i32); pub fn dragInt3(label: [:0]const u8, args: DragInt3) bool { return zguiDragInt3(label, args.v, args.speed, args.min, args.max, args.cfmt, args.flags); } extern fn zguiDragInt3( label: [*:0]const u8, v: *[3]i32, speed: f32, min: i32, max: i32, cfmt: [*:0]const u8, flags: SliderFlags, ) bool; //-------------------------------------------------------------------------------------------------- const DragInt4 = DragIntGen([4]i32); pub fn dragInt4(label: [:0]const u8, args: DragInt4) bool { return zguiDragInt4(label, args.v, args.speed, args.min, args.max, args.cfmt, args.flags); } extern fn zguiDragInt4( label: [*:0]const u8, v: *[4]i32, speed: f32, min: i32, max: i32, cfmt: [*:0]const u8, flags: SliderFlags, ) bool; //-------------------------------------------------------------------------------------------------- const DragIntRange2 = struct { current_min: *i32, current_max: *i32, speed: f32 = 1.0, min: i32 = 0.0, max: i32 = 0.0, cfmt: [:0]const u8 = "%d", cfmt_max: ?[:0]const u8 = null, flags: SliderFlags = .{}, }; pub fn dragIntRange2(label: [:0]const u8, args: DragIntRange2) bool { return zguiDragIntRange2( label, args.current_min, args.current_max, args.speed, args.min, args.max, args.cfmt, if (args.cfmt_max) |fm| fm else null, args.flags, ); } extern fn zguiDragIntRange2( label: [*:0]const u8, current_min: *i32, current_max: *i32, speed: f32, min: i32, max: i32, cfmt: [*:0]const u8, cfmt_max: ?[*:0]const u8, flags: SliderFlags, ) bool; //-------------------------------------------------------------------------------------------------- fn DragScalarGen(comptime T: type) type { return struct { v: *T, speed: f32 = 1.0, min: ?T = null, max: ?T = null, cfmt: ?[:0]const u8 = null, flags: SliderFlags = .{}, }; } pub fn dragScalar(label: [:0]const u8, comptime T: type, args: DragScalarGen(T)) bool { return zguiDragScalar( label, typeToDataTypeEnum(T), args.v, args.speed, if (args.min) |vm| &vm else null, if (args.max) |vm| &vm else null, if (args.cfmt) |fmt| fmt else null, args.flags, ); } extern fn zguiDragScalar( label: [*:0]const u8, data_type: DataType, pdata: *anyopaque, speed: f32, pmin: ?*const anyopaque, pmax: ?*const anyopaque, cfmt: ?[*:0]const u8, flags: SliderFlags, ) bool; //-------------------------------------------------------------------------------------------------- fn DragScalarNGen(comptime T: type) type { const ScalarType = @typeInfo(T).Array.child; return struct { v: *T, speed: f32 = 1.0, min: ?ScalarType = null, max: ?ScalarType = null, cfmt: ?[:0]const u8 = null, flags: SliderFlags = .{}, }; } pub fn dragScalarN(label: [:0]const u8, comptime T: type, args: DragScalarNGen(T)) bool { const ScalarType = @typeInfo(T).Array.child; const components = @typeInfo(T).Array.len; return zguiDragScalarN( label, typeToDataTypeEnum(ScalarType), args.v, components, args.speed, if (args.min) |vm| &vm else null, if (args.max) |vm| &vm else null, if (args.cfmt) |fmt| fmt else null, args.flags, ); } extern fn zguiDragScalarN( label: [*:0]const u8, data_type: DataType, pdata: *anyopaque, components: i32, speed: f32, pmin: ?*const anyopaque, pmax: ?*const anyopaque, cfmt: ?[*:0]const u8, flags: SliderFlags, ) bool; //-------------------------------------------------------------------------------------------------- // // Widgets: Regular Sliders // //-------------------------------------------------------------------------------------------------- fn SliderFloatGen(comptime T: type) type { return struct { v: *T, min: f32, max: f32, cfmt: [:0]const u8 = "%.3f", flags: SliderFlags = .{}, }; } pub fn sliderFloat(label: [:0]const u8, args: SliderFloatGen(f32)) bool { return zguiSliderFloat(label, args.v, args.min, args.max, args.cfmt, args.flags); } extern fn zguiSliderFloat( label: [*:0]const u8, v: *f32, min: f32, max: f32, cfmt: [*:0]const u8, flags: SliderFlags, ) bool; pub fn sliderFloat2(label: [:0]const u8, args: SliderFloatGen([2]f32)) bool { return zguiSliderFloat2(label, args.v, args.min, args.max, args.cfmt, args.flags); } extern fn zguiSliderFloat2( label: [*:0]const u8, v: *[2]f32, min: f32, max: f32, cfmt: [*:0]const u8, flags: SliderFlags, ) bool; pub fn sliderFloat3(label: [:0]const u8, args: SliderFloatGen([3]f32)) bool { return zguiSliderFloat3(label, args.v, args.min, args.max, args.cfmt, args.flags); } extern fn zguiSliderFloat3( label: [*:0]const u8, v: *[3]f32, min: f32, max: f32, cfmt: [*:0]const u8, flags: SliderFlags, ) bool; pub fn sliderFloat4(label: [:0]const u8, args: SliderFloatGen([4]f32)) bool { return zguiSliderFloat4(label, args.v, args.min, args.max, args.cfmt, args.flags); } extern fn zguiSliderFloat4( label: [*:0]const u8, v: *[4]f32, min: f32, max: f32, cfmt: [*:0]const u8, flags: SliderFlags, ) bool; //-------------------------------------------------------------------------------------------------- fn SliderIntGen(comptime T: type) type { return struct { v: *T, min: i32, max: i32, cfmt: [:0]const u8 = "%d", flags: SliderFlags = .{}, }; } pub fn sliderInt(label: [:0]const u8, args: SliderIntGen(i32)) bool { return zguiSliderInt(label, args.v, args.min, args.max, args.cfmt, args.flags); } extern fn zguiSliderInt( label: [*:0]const u8, v: *c_int, min: c_int, max: c_int, cfmt: [*:0]const u8, flags: SliderFlags, ) bool; pub fn sliderInt2(label: [:0]const u8, args: SliderIntGen([2]i32)) bool { return zguiSliderInt2(label, args.v, args.min, args.max, args.cfmt, args.flags); } extern fn zguiSliderInt2( label: [*:0]const u8, v: *[2]c_int, min: c_int, max: c_int, cfmt: [*:0]const u8, flags: SliderFlags, ) bool; pub fn sliderInt3(label: [:0]const u8, args: SliderIntGen([3]i32)) bool { return zguiSliderInt3(label, args.v, args.min, args.max, args.cfmt, args.flags); } extern fn zguiSliderInt3( label: [*:0]const u8, v: *[3]c_int, min: c_int, max: c_int, cfmt: [*:0]const u8, flags: SliderFlags, ) bool; pub fn sliderInt4(label: [:0]const u8, args: SliderIntGen([4]i32)) bool { return zguiSliderInt4(label, args.v, args.min, args.max, args.cfmt, args.flags); } extern fn zguiSliderInt4( label: [*:0]const u8, v: *[4]c_int, min: c_int, max: c_int, cfmt: [*:0]const u8, flags: SliderFlags, ) bool; //-------------------------------------------------------------------------------------------------- fn SliderScalarGen(comptime T: type) type { return struct { v: *T, min: T, max: T, cfmt: ?[:0]const u8 = null, flags: SliderFlags = .{}, }; } pub fn sliderScalar(label: [:0]const u8, comptime T: type, args: SliderScalarGen(T)) bool { return zguiSliderScalar( label, typeToDataTypeEnum(T), args.v, &args.min, &args.max, if (args.cfmt) |fmt| fmt else null, args.flags, ); } extern fn zguiSliderScalar( label: [*:0]const u8, data_type: DataType, pdata: *anyopaque, pmin: *const anyopaque, pmax: *const anyopaque, cfmt: ?[*:0]const u8, flags: SliderFlags, ) bool; //-------------------------------------------------------------------------------------------------- fn SliderScalarNGen(comptime T: type) type { const ScalarType = @typeInfo(T).Array.child; return struct { v: *T, min: ScalarType, max: ScalarType, cfmt: ?[:0]const u8 = null, flags: SliderFlags = .{}, }; } pub fn sliderScalarN(label: [:0]const u8, comptime T: type, args: SliderScalarNGen(T)) bool { const ScalarType = @typeInfo(T).Array.child; const components = @typeInfo(T).Array.len; return zguiSliderScalarN( label, typeToDataTypeEnum(ScalarType), args.v, components, &args.min, &args.max, if (args.cfmt) |fmt| fmt else null, args.flags, ); } extern fn zguiSliderScalarN( label: [*:0]const u8, data_type: DataType, pdata: *anyopaque, components: i32, pmin: *const anyopaque, pmax: *const anyopaque, cfmt: ?[*:0]const u8, flags: SliderFlags, ) bool; //-------------------------------------------------------------------------------------------------- pub fn vsliderFloat(label: [:0]const u8, args: struct { w: f32, h: f32, v: *f32, min: f32, max: f32, cfmt: [:0]const u8 = "%.3f", flags: SliderFlags = .{}, }) bool { return zguiVSliderFloat( label, args.w, args.h, args.v, args.min, args.max, args.cfmt, args.flags, ); } extern fn zguiVSliderFloat( label: [*:0]const u8, w: f32, h: f32, v: *f32, min: f32, max: f32, cfmt: [*:0]const u8, flags: SliderFlags, ) bool; //-------------------------------------------------------------------------------------------------- pub fn vsliderInt(label: [:0]const u8, args: struct { w: f32, h: f32, v: *i32, min: i32, max: i32, cfmt: [:0]const u8 = "%d", flags: SliderFlags = .{}, }) bool { return zguiVSliderInt(label, args.w, args.h, args.v, args.min, args.max, args.cfmt, args.flags); } extern fn zguiVSliderInt( label: [*:0]const u8, w: f32, h: f32, v: *i32, min: c_int, max: c_int, cfmt: [*:0]const u8, flags: SliderFlags, ) bool; //-------------------------------------------------------------------------------------------------- fn VSliderScalarGen(comptime T: type) type { return struct { w: f32, h: f32, v: *T, min: T, max: T, cfmt: ?[:0]const u8 = null, flags: SliderFlags = .{}, }; } pub fn vsliderScalar(label: [:0]const u8, comptime T: type, args: VSliderScalarGen(T)) bool { return zguiVSliderScalar( label, args.w, args.h, typeToDataTypeEnum(T), args.v, &args.min, &args.max, if (args.cfmt) |fmt| fmt else null, args.flags, ); } extern fn zguiVSliderScalar( label: [*:0]const u8, w: f32, h: f32, data_type: DataType, pdata: *anyopaque, pmin: *const anyopaque, pmax: *const anyopaque, cfmt: ?[*:0]const u8, flags: SliderFlags, ) bool; //-------------------------------------------------------------------------------------------------- const SliderAngle = struct { vrad: *f32, deg_min: f32 = -360.0, deg_max: f32 = 360.0, cfmt: [:0]const u8 = "%.0f deg", flags: SliderFlags = .{}, }; pub fn sliderAngle(label: [:0]const u8, args: SliderAngle) bool { return zguiSliderAngle( label, args.vrad, args.deg_min, args.deg_max, args.cfmt, args.flags, ); } extern fn zguiSliderAngle( label: [*:0]const u8, vrad: *f32, deg_min: f32, deg_max: f32, cfmt: [*:0]const u8, flags: SliderFlags, ) bool; //-------------------------------------------------------------------------------------------------- // // Widgets: Input with Keyboard // //-------------------------------------------------------------------------------------------------- pub const InputTextFlags = packed struct(c_int) { chars_decimal: bool = false, chars_hexadecimal: bool = false, chars_uppercase: bool = false, chars_no_blank: bool = false, auto_select_all: bool = false, enter_returns_true: bool = false, callback_completion: bool = false, callback_history: bool = false, callback_always: bool = false, callback_char_filter: bool = false, allow_tab_input: bool = false, ctrl_enter_for_new_line: bool = false, no_horizontal_scroll: bool = false, always_overwrite: bool = false, read_only: bool = false, password: bool = false, no_undo_redo: bool = false, chars_scientific: bool = false, callback_resize: bool = false, callback_edit: bool = false, escape_clears_all: bool = false, _padding: u11 = 0, }; //-------------------------------------------------------------------------------------------------- pub const InputTextCallbackData = extern struct { ctx: *Context, event_flag: InputTextFlags, flags: InputTextFlags, user_data: ?*anyopaque, event_char: Wchar, event_key: Key, buf: [*]u8, buf_text_len: i32, buf_size: i32, buf_dirty: bool, cursor_pos: i32, selection_start: i32, selection_end: i32, /// `pub fn init() InputTextCallbackData` pub const init = zguiInputTextCallbackData_Init; extern fn zguiInputTextCallbackData_Init() InputTextCallbackData; /// `pub fn deleteChars(data: *InputTextCallbackData, pos: i32, bytes_count: i32) void` pub const deleteChars = zguiInputTextCallbackData_DeleteChars; extern fn zguiInputTextCallbackData_DeleteChars( data: *InputTextCallbackData, pos: c_int, bytes_count: c_int, ) void; pub fn insertChars(data: *InputTextCallbackData, pos: i32, txt: []const u8) void { zguiInputTextCallbackData_InsertChars(data, pos, txt.ptr, txt.ptr + txt.len); } extern fn zguiInputTextCallbackData_InsertChars( data: *InputTextCallbackData, pos: c_int, text: [*]const u8, text_end: [*]const u8, ) void; pub fn selectAll(data: *InputTextCallbackData) void { data.selection_start = 0; data.selection_end = data.buf_text_len; } pub fn clearSelection(data: *InputTextCallbackData) void { data.selection_start = data.buf_text_len; data.selection_end = data.buf_text_len; } pub fn hasSelection(data: InputTextCallbackData) bool { return data.selection_start != data.selection_end; } }; pub const InputTextCallback = *const fn (data: *InputTextCallbackData) i32; //-------------------------------------------------------------------------------------------------- pub fn inputText(label: [:0]const u8, args: struct { buf: [:0]u8, flags: InputTextFlags = .{}, callback: ?InputTextCallback = null, user_data: ?*anyopaque = null, }) bool { return zguiInputText( label, args.buf.ptr, args.buf.len + 1, // + 1 for sentinel args.flags, if (args.callback) |cb| cb else null, args.user_data, ); } extern fn zguiInputText( label: [*:0]const u8, buf: [*]u8, buf_size: usize, flags: InputTextFlags, callback: ?*const anyopaque, user_data: ?*anyopaque, ) bool; //-------------------------------------------------------------------------------------------------- pub fn inputTextMultiline(label: [:0]const u8, args: struct { buf: [:0]u8, w: f32 = 0.0, h: f32 = 0.0, flags: InputTextFlags = .{}, callback: ?InputTextCallback = null, user_data: ?*anyopaque = null, }) bool { return zguiInputTextMultiline( label, args.buf.ptr, args.buf.len + 1, // + 1 for sentinel args.w, args.h, args.flags, if (args.callback) |cb| cb else null, args.user_data, ); } extern fn zguiInputTextMultiline( label: [*:0]const u8, buf: [*]u8, buf_size: usize, w: f32, h: f32, flags: InputTextFlags, callback: ?*const anyopaque, user_data: ?*anyopaque, ) bool; //-------------------------------------------------------------------------------------------------- pub fn inputTextWithHint(label: [:0]const u8, args: struct { hint: [:0]const u8, buf: [:0]u8, flags: InputTextFlags = .{}, callback: ?InputTextCallback = null, user_data: ?*anyopaque = null, }) bool { return zguiInputTextWithHint( label, args.hint, args.buf.ptr, args.buf.len + 1, // + 1 for sentinel args.flags, if (args.callback) |cb| cb else null, args.user_data, ); } extern fn zguiInputTextWithHint( label: [*:0]const u8, hint: [*:0]const u8, buf: [*]u8, buf_size: usize, flags: InputTextFlags, callback: ?*const anyopaque, user_data: ?*anyopaque, ) bool; //-------------------------------------------------------------------------------------------------- pub fn inputFloat(label: [:0]const u8, args: struct { v: *f32, step: f32 = 0.0, step_fast: f32 = 0.0, cfmt: [:0]const u8 = "%.3f", flags: InputTextFlags = .{}, }) bool { return zguiInputFloat( label, args.v, args.step, args.step_fast, args.cfmt, args.flags, ); } extern fn zguiInputFloat( label: [*:0]const u8, v: *f32, step: f32, step_fast: f32, cfmt: [*:0]const u8, flags: InputTextFlags, ) bool; //-------------------------------------------------------------------------------------------------- fn InputFloatGen(comptime T: type) type { return struct { v: *T, cfmt: [:0]const u8 = "%.3f", flags: InputTextFlags = .{}, }; } pub fn inputFloat2(label: [:0]const u8, args: InputFloatGen([2]f32)) bool { return zguiInputFloat2(label, args.v, args.cfmt, args.flags); } extern fn zguiInputFloat2( label: [*:0]const u8, v: *[2]f32, cfmt: [*:0]const u8, flags: InputTextFlags, ) bool; pub fn inputFloat3(label: [:0]const u8, args: InputFloatGen([3]f32)) bool { return zguiInputFloat3(label, args.v, args.cfmt, args.flags); } extern fn zguiInputFloat3( label: [*:0]const u8, v: *[3]f32, cfmt: [*:0]const u8, flags: InputTextFlags, ) bool; pub fn inputFloat4(label: [:0]const u8, args: InputFloatGen([4]f32)) bool { return zguiInputFloat4(label, args.v, args.cfmt, args.flags); } extern fn zguiInputFloat4( label: [*:0]const u8, v: *[4]f32, cfmt: [*:0]const u8, flags: InputTextFlags, ) bool; //-------------------------------------------------------------------------------------------------- pub fn inputInt(label: [:0]const u8, args: struct { v: *i32, step: i32 = 1, step_fast: i32 = 100, flags: InputTextFlags = .{}, }) bool { return zguiInputInt(label, args.v, args.step, args.step_fast, args.flags); } extern fn zguiInputInt( label: [*:0]const u8, v: *c_int, step: c_int, step_fast: c_int, flags: InputTextFlags, ) bool; //-------------------------------------------------------------------------------------------------- fn InputIntGen(comptime T: type) type { return struct { v: *T, flags: InputTextFlags = .{}, }; } pub fn inputInt2(label: [:0]const u8, args: InputIntGen([2]i32)) bool { return zguiInputInt2(label, args.v, args.flags); } extern fn zguiInputInt2(label: [*:0]const u8, v: *[2]c_int, flags: InputTextFlags) bool; pub fn inputInt3(label: [:0]const u8, args: InputIntGen([3]i32)) bool { return zguiInputInt3(label, args.v, args.flags); } extern fn zguiInputInt3(label: [*:0]const u8, v: *[3]c_int, flags: InputTextFlags) bool; pub fn inputInt4(label: [:0]const u8, args: InputIntGen([4]i32)) bool { return zguiInputInt4(label, args.v, args.flags); } extern fn zguiInputInt4(label: [*:0]const u8, v: *[4]c_int, flags: InputTextFlags) bool; //-------------------------------------------------------------------------------------------------- const InputDouble = struct { v: *f64, step: f64 = 0.0, step_fast: f64 = 0.0, cfmt: [:0]const u8 = "%.6f", flags: InputTextFlags = .{}, }; pub fn inputDouble(label: [:0]const u8, args: InputDouble) bool { return zguiInputDouble(label, args.v, args.step, args.step_fast, args.cfmt, args.flags); } extern fn zguiInputDouble( label: [*:0]const u8, v: *f64, step: f64, step_fast: f64, cfmt: [*:0]const u8, flags: InputTextFlags, ) bool; //-------------------------------------------------------------------------------------------------- fn InputScalarGen(comptime T: type) type { return struct { v: *T, step: ?T = null, step_fast: ?T = null, cfmt: ?[:0]const u8 = null, flags: InputTextFlags = .{}, }; } pub fn inputScalar(label: [:0]const u8, comptime T: type, args: InputScalarGen(T)) bool { return zguiInputScalar( label, typeToDataTypeEnum(T), args.v, if (args.step) |s| &s else null, if (args.step_fast) |sf| &sf else null, if (args.cfmt) |fmt| fmt else null, args.flags, ); } extern fn zguiInputScalar( label: [*:0]const u8, data_type: DataType, pdata: *anyopaque, pstep: ?*const anyopaque, pstep_fast: ?*const anyopaque, cfmt: ?[*:0]const u8, flags: InputTextFlags, ) bool; //-------------------------------------------------------------------------------------------------- fn InputScalarNGen(comptime T: type) type { const ScalarType = @typeInfo(T).Array.child; return struct { v: *T, step: ?ScalarType = null, step_fast: ?ScalarType = null, cfmt: ?[:0]const u8 = null, flags: InputTextFlags = .{}, }; } pub fn inputScalarN(label: [:0]const u8, comptime T: type, args: InputScalarNGen(T)) bool { const ScalarType = @typeInfo(T).Array.child; const components = @typeInfo(T).Array.len; return zguiInputScalarN( label, typeToDataTypeEnum(ScalarType), args.v, components, if (args.step) |s| &s else null, if (args.step_fast) |sf| &sf else null, if (args.cfmt) |fmt| fmt else null, args.flags, ); } extern fn zguiInputScalarN( label: [*:0]const u8, data_type: DataType, pdata: *anyopaque, components: i32, pstep: ?*const anyopaque, pstep_fast: ?*const anyopaque, cfmt: ?[*:0]const u8, flags: InputTextFlags, ) bool; //-------------------------------------------------------------------------------------------------- // // Widgets: Color Editor/Picker // //-------------------------------------------------------------------------------------------------- pub const ColorEditFlags = packed struct(c_int) { _reserved0: bool = false, no_alpha: bool = false, no_picker: bool = false, no_options: bool = false, no_small_preview: bool = false, no_inputs: bool = false, no_tooltip: bool = false, no_label: bool = false, no_side_preview: bool = false, no_drag_drop: bool = false, no_border: bool = false, _reserved1: bool = false, _reserved2: bool = false, _reserved3: bool = false, _reserved4: bool = false, _reserved5: bool = false, alpha_bar: bool = false, alpha_preview: bool = false, alpha_preview_half: bool = false, hdr: bool = false, display_rgb: bool = false, display_hsv: bool = false, display_hex: bool = false, uint8: bool = false, float: bool = false, picker_hue_bar: bool = false, picker_hue_wheel: bool = false, input_rgb: bool = false, input_hsv: bool = false, _padding: u3 = 0, pub const default_options = ColorEditFlags{ .uint8 = true, .display_rgb = true, .input_rgb = true, .picker_hue_bar = true, }; }; //-------------------------------------------------------------------------------------------------- const ColorEdit3 = struct { col: *[3]f32, flags: ColorEditFlags = .{}, }; pub fn colorEdit3(label: [:0]const u8, args: ColorEdit3) bool { return zguiColorEdit3(label, args.col, args.flags); } extern fn zguiColorEdit3(label: [*:0]const u8, col: *[3]f32, flags: ColorEditFlags) bool; //-------------------------------------------------------------------------------------------------- const ColorEdit4 = struct { col: *[4]f32, flags: ColorEditFlags = .{}, }; pub fn colorEdit4(label: [:0]const u8, args: ColorEdit4) bool { return zguiColorEdit4(label, args.col, args.flags); } extern fn zguiColorEdit4(label: [*:0]const u8, col: *[4]f32, flags: ColorEditFlags) bool; //-------------------------------------------------------------------------------------------------- const ColorPicker3 = struct { col: *[3]f32, flags: ColorEditFlags = .{}, }; pub fn colorPicker3(label: [:0]const u8, args: ColorPicker3) bool { return zguiColorPicker3(label, args.col, args.flags); } extern fn zguiColorPicker3(label: [*:0]const u8, col: *[3]f32, flags: ColorEditFlags) bool; //-------------------------------------------------------------------------------------------------- const ColorPicker4 = struct { col: *[4]f32, flags: ColorEditFlags = .{}, ref_col: ?[*]const f32 = null, }; pub fn colorPicker4(label: [:0]const u8, args: ColorPicker4) bool { return zguiColorPicker4( label, args.col, args.flags, if (args.ref_col) |rc| rc else null, ); } extern fn zguiColorPicker4( label: [*:0]const u8, col: *[4]f32, flags: ColorEditFlags, ref_col: ?[*]const f32, ) bool; //-------------------------------------------------------------------------------------------------- const ColorButton = struct { col: [4]f32, flags: ColorEditFlags = .{}, w: f32 = 0.0, h: f32 = 0.0, }; pub fn colorButton(desc_id: [:0]const u8, args: ColorButton) bool { return zguiColorButton(desc_id, &args.col, args.flags, args.w, args.h); } extern fn zguiColorButton( desc_id: [*:0]const u8, col: *const [4]f32, flags: ColorEditFlags, w: f32, h: f32, ) bool; //-------------------------------------------------------------------------------------------------- // // Widgets: Trees // //-------------------------------------------------------------------------------------------------- pub const TreeNodeFlags = packed struct(c_int) { selected: bool = false, framed: bool = false, allow_overlap: bool = false, no_tree_push_on_open: bool = false, no_auto_open_on_log: bool = false, default_open: bool = false, open_on_double_click: bool = false, open_on_arrow: bool = false, leaf: bool = false, bullet: bool = false, frame_padding: bool = false, span_avail_width: bool = false, span_full_width: bool = false, span_all_columns: bool = false, nav_left_jumps_back_here: bool = false, _padding: u17 = 0, pub const collapsing_header = TreeNodeFlags{ .framed = true, .no_tree_push_on_open = true, .no_auto_open_on_log = true, }; }; //-------------------------------------------------------------------------------------------------- pub fn treeNode(label: [:0]const u8) bool { return zguiTreeNode(label); } pub fn treeNodeFlags(label: [:0]const u8, flags: TreeNodeFlags) bool { return zguiTreeNodeFlags(label, flags); } extern fn zguiTreeNode(label: [*:0]const u8) bool; extern fn zguiTreeNodeFlags(label: [*:0]const u8, flags: TreeNodeFlags) bool; //-------------------------------------------------------------------------------------------------- pub fn treeNodeStrId(str_id: [:0]const u8, comptime fmt: []const u8, args: anytype) bool { return zguiTreeNodeStrId(str_id, "%s", formatZ(fmt, args).ptr); } pub fn treeNodeStrIdFlags( str_id: [:0]const u8, flags: TreeNodeFlags, comptime fmt: []const u8, args: anytype, ) bool { return zguiTreeNodeStrIdFlags(str_id, flags, "%s", formatZ(fmt, args).ptr); } extern fn zguiTreeNodeStrId(str_id: [*:0]const u8, fmt: [*:0]const u8, ...) bool; extern fn zguiTreeNodeStrIdFlags( str_id: [*:0]const u8, flags: TreeNodeFlags, fmt: [*:0]const u8, ..., ) bool; //-------------------------------------------------------------------------------------------------- pub fn treeNodePtrId(ptr_id: *const anyopaque, comptime fmt: []const u8, args: anytype) bool { return zguiTreeNodePtrId(ptr_id, "%s", formatZ(fmt, args).ptr); } pub fn treeNodePtrIdFlags( ptr_id: *const anyopaque, flags: TreeNodeFlags, comptime fmt: []const u8, args: anytype, ) bool { return zguiTreeNodePtrIdFlags(ptr_id, flags, "%s", formatZ(fmt, args).ptr); } extern fn zguiTreeNodePtrId(ptr_id: *const anyopaque, fmt: [*:0]const u8, ...) bool; extern fn zguiTreeNodePtrIdFlags( ptr_id: *const anyopaque, flags: TreeNodeFlags, fmt: [*:0]const u8, ..., ) bool; //-------------------------------------------------------------------------------------------------- pub fn treePushStrId(str_id: [:0]const u8) void { zguiTreePushStrId(str_id); } pub fn treePushPtrId(ptr_id: *const anyopaque) void { zguiTreePushPtrId(ptr_id); } extern fn zguiTreePushStrId(str_id: [*:0]const u8) void; extern fn zguiTreePushPtrId(ptr_id: *const anyopaque) void; //-------------------------------------------------------------------------------------------------- /// `pub fn treePop() void` pub const treePop = zguiTreePop; extern fn zguiTreePop() void; //-------------------------------------------------------------------------------------------------- const CollapsingHeaderStatePtr = struct { pvisible: *bool, flags: TreeNodeFlags = .{}, }; pub fn collapsingHeader(label: [:0]const u8, flags: TreeNodeFlags) bool { return zguiCollapsingHeader(label, flags); } pub fn collapsingHeaderStatePtr(label: [:0]const u8, args: CollapsingHeaderStatePtr) bool { return zguiCollapsingHeaderStatePtr(label, args.pvisible, args.flags); } extern fn zguiCollapsingHeader(label: [*:0]const u8, flags: TreeNodeFlags) bool; extern fn zguiCollapsingHeaderStatePtr(label: [*:0]const u8, pvisible: *bool, flags: TreeNodeFlags) bool; //-------------------------------------------------------------------------------------------------- const SetNextItemOpen = struct { is_open: bool, cond: Condition = .none, }; pub fn setNextItemOpen(args: SetNextItemOpen) void { zguiSetNextItemOpen(args.is_open, args.cond); } extern fn zguiSetNextItemOpen(is_open: bool, cond: Condition) void; //-------------------------------------------------------------------------------------------------- // // Selectables // //-------------------------------------------------------------------------------------------------- pub const SelectableFlags = packed struct(c_int) { dont_close_popups: bool = false, span_all_columns: bool = false, allow_double_click: bool = false, disabled: bool = false, allow_overlap: bool = false, _padding: u27 = 0, }; //-------------------------------------------------------------------------------------------------- const Selectable = struct { selected: bool = false, flags: SelectableFlags = .{}, w: f32 = 0, h: f32 = 0, }; pub fn selectable(label: [:0]const u8, args: Selectable) bool { return zguiSelectable(label, args.selected, args.flags, args.w, args.h); } extern fn zguiSelectable( label: [*:0]const u8, selected: bool, flags: SelectableFlags, w: f32, h: f32, ) bool; //-------------------------------------------------------------------------------------------------- const SelectableStatePtr = struct { pselected: *bool, flags: SelectableFlags = .{}, w: f32 = 0, h: f32 = 0, }; pub fn selectableStatePtr(label: [:0]const u8, args: SelectableStatePtr) bool { return zguiSelectableStatePtr(label, args.pselected, args.flags, args.w, args.h); } extern fn zguiSelectableStatePtr( label: [*:0]const u8, pselected: *bool, flags: SelectableFlags, w: f32, h: f32, ) bool; //-------------------------------------------------------------------------------------------------- // // Widgets: List Boxes // //-------------------------------------------------------------------------------------------------- const BeginListBox = struct { w: f32 = 0.0, h: f32 = 0.0, }; pub fn beginListBox(label: [:0]const u8, args: BeginListBox) bool { return zguiBeginListBox(label, args.w, args.h); } /// `pub fn endListBox() void` pub const endListBox = zguiEndListBox; extern fn zguiBeginListBox(label: [*:0]const u8, w: f32, h: f32) bool; extern fn zguiEndListBox() void; //-------------------------------------------------------------------------------------------------- // // Widgets: Tables // //-------------------------------------------------------------------------------------------------- pub const TableBorderFlags = packed struct(u4) { inner_h: bool = false, outer_h: bool = false, inner_v: bool = false, outer_v: bool = false, pub const h = TableBorderFlags{ .inner_h = true, .outer_h = true, }; // Draw horizontal borders. pub const v = TableBorderFlags{ .inner_v = true, .outer_v = true, }; // Draw vertical borders. pub const inner = TableBorderFlags{ .inner_v = true, .inner_h = true, }; // Draw inner borders. pub const outer = TableBorderFlags{ .outer_v = true, .outer_h = true, }; // Draw outer borders. pub const all = TableBorderFlags{ .inner_v = true, .inner_h = true, .outer_v = true, .outer_h = true, }; // Draw all borders. }; pub const TableFlags = packed struct(c_int) { resizable: bool = false, reorderable: bool = false, hideable: bool = false, sortable: bool = false, no_saved_settings: bool = false, context_menu_in_body: bool = false, row_bg: bool = false, borders: TableBorderFlags = .{}, no_borders_in_body: bool = false, no_borders_in_body_until_resize: bool = false, // Sizing Policy sizing: enum(u3) { none = 0, fixed_fit = 1, fixed_same = 2, stretch_prop = 3, stretch_same = 4, } = .none, // Sizing Extra Options no_host_extend_x: bool = false, no_host_extend_y: bool = false, no_keep_columns_visible: bool = false, precise_widths: bool = false, // Clipping no_clip: bool = false, // Padding pad_outer_x: bool = false, no_pad_outer_x: bool = false, no_pad_inner_x: bool = false, // Scrolling scroll_x: bool = false, scroll_y: bool = false, // Sorting sort_multi: bool = false, sort_tristate: bool = false, _padding: u4 = 0, }; pub const TableRowFlags = packed struct(c_int) { headers: bool = false, _padding: u31 = 0, }; pub const TableColumnFlags = packed struct(c_int) { // Input configuration flags disabled: bool = false, default_hide: bool = false, default_sort: bool = false, width_stretch: bool = false, width_fixed: bool = false, no_resize: bool = false, no_reorder: bool = false, no_hide: bool = false, no_clip: bool = false, no_sort: bool = false, no_sort_ascending: bool = false, no_sort_descending: bool = false, no_header_label: bool = false, no_header_width: bool = false, prefer_sort_ascending: bool = false, prefer_sort_descending: bool = false, indent_enable: bool = false, indent_disable: bool = false, _padding0: u6 = 0, // Output status flags, read-only via TableGetColumnFlags() is_enabled: bool = false, is_visible: bool = false, is_sorted: bool = false, is_hovered: bool = false, _padding1: u4 = 0, }; pub const TableColumnSortSpecs = extern struct { user_id: Ident, index: i16, sort_order: i16, sort_direction: enum(u8) { none = 0, ascending = 1, // Ascending = 0->9, A->Z etc. descending = 2, // Descending = 9->0, Z->A etc. }, }; pub const TableSortSpecs = *extern struct { specs: [*]TableColumnSortSpecs, count: c_int, dirty: bool, }; pub const TableBgTarget = enum(c_int) { none = 0, row_bg0 = 1, row_bg1 = 2, cell_bg = 3, }; pub fn beginTable(name: [:0]const u8, args: struct { column: i32, flags: TableFlags = .{}, outer_size: [2]f32 = .{ 0, 0 }, inner_width: f32 = 0, }) bool { return zguiBeginTable(name, args.column, args.flags, &args.outer_size, args.inner_width); } extern fn zguiBeginTable( str_id: [*:0]const u8, column: c_int, flags: TableFlags, outer_size: *const [2]f32, inner_width: f32, ) bool; pub fn endTable() void { zguiEndTable(); } extern fn zguiEndTable() void; pub const TableNextRow = struct { row_flags: TableRowFlags = .{}, min_row_height: f32 = 0, }; pub fn tableNextRow(args: TableNextRow) void { zguiTableNextRow(args.row_flags, args.min_row_height); } extern fn zguiTableNextRow(row_flags: TableRowFlags, min_row_height: f32) void; pub const tableNextColumn = zguiTableNextColumn; extern fn zguiTableNextColumn() bool; pub const tableSetColumnIndex = zguiTableSetColumnIndex; extern fn zguiTableSetColumnIndex(column_n: i32) bool; pub const TableSetupColumn = struct { flags: TableColumnFlags = .{}, init_width_or_height: f32 = 0, user_id: Ident = 0, }; pub fn tableSetupColumn(label: [:0]const u8, args: TableSetupColumn) void { zguiTableSetupColumn(label, args.flags, args.init_width_or_height, args.user_id); } extern fn zguiTableSetupColumn(label: [*:0]const u8, flags: TableColumnFlags, init_width_or_height: f32, user_id: Ident) void; pub const tableSetupScrollFreeze = zguiTableSetupScrollFreeze; extern fn zguiTableSetupScrollFreeze(cols: i32, rows: i32) void; pub const tableHeadersRow = zguiTableHeadersRow; extern fn zguiTableHeadersRow() void; pub fn tableHeader(label: [:0]const u8) void { zguiTableHeader(label); } extern fn zguiTableHeader(label: [*:0]const u8) void; pub const tableGetSortSpecs = zguiTableGetSortSpecs; extern fn zguiTableGetSortSpecs() ?TableSortSpecs; pub const tableGetColumnCount = zguiTableGetColumnCount; extern fn zguiTableGetColumnCount() i32; pub const tableGetColumnIndex = zguiTableGetColumnIndex; extern fn zguiTableGetColumnIndex() i32; pub const tableGetRowIndex = zguiTableGetRowIndex; extern fn zguiTableGetRowIndex() i32; pub const TableGetColumnName = struct { column_n: i32 = -1, }; pub fn tableGetColumnName(args: TableGetColumnName) [*:0]const u8 { return zguiTableGetColumnName(args.column_n); } extern fn zguiTableGetColumnName(column_n: i32) [*:0]const u8; pub const TableGetColumnFlags = struct { column_n: i32 = -1, }; pub fn tableGetColumnFlags(args: TableGetColumnFlags) TableColumnFlags { return zguiTableGetColumnFlags(args.column_n); } extern fn zguiTableGetColumnFlags(column_n: i32) TableColumnFlags; pub const tableSetColumnEnabled = zguiTableSetColumnEnabled; extern fn zguiTableSetColumnEnabled(column_n: i32, v: bool) void; pub fn tableSetBgColor(args: struct { target: TableBgTarget, color: u32, column_n: i32 = -1, }) void { zguiTableSetBgColor(args.target, args.color, args.column_n); } extern fn zguiTableSetBgColor(target: TableBgTarget, color: c_uint, column_n: c_int) void; //-------------------------------------------------------------------------------------------------- // // Item/Widgets Utilities and Query Functions // //-------------------------------------------------------------------------------------------------- pub fn isItemHovered(flags: HoveredFlags) bool { return zguiIsItemHovered(flags); } /// `pub fn isItemActive() bool` pub const isItemActive = zguiIsItemActive; /// `pub fn isItemFocused() bool` pub const isItemFocused = zguiIsItemFocused; pub const MouseButton = enum(u32) { left = 0, right = 1, middle = 2, }; /// `pub fn isMouseDown(mouse_button: MouseButton) bool` pub const isMouseDown = zguiIsMouseDown; /// `pub fn isMouseClicked(mouse_button: MouseButton) bool` pub const isMouseClicked = zguiIsMouseClicked; /// `pub fn isMouseDoubleClicked(mouse_button: MouseButton) bool` pub const isMouseDoubleClicked = zguiIsMouseDoubleClicked; /// `pub fn isItemClicked(mouse_button: MouseButton) bool` pub const isItemClicked = zguiIsItemClicked; /// `pub fn isItemVisible() bool` pub const isItemVisible = zguiIsItemVisible; /// `pub fn isItemEdited() bool` pub const isItemEdited = zguiIsItemEdited; /// `pub fn isItemActivated() bool` pub const isItemActivated = zguiIsItemActivated; /// `pub fn isItemDeactivated bool` pub const isItemDeactivated = zguiIsItemDeactivated; /// `pub fn isItemDeactivatedAfterEdit() bool` pub const isItemDeactivatedAfterEdit = zguiIsItemDeactivatedAfterEdit; /// `pub fn isItemToggledOpen() bool` pub const isItemToggledOpen = zguiIsItemToggledOpen; /// `pub fn isAnyItemHovered() bool` pub const isAnyItemHovered = zguiIsAnyItemHovered; /// `pub fn isAnyItemActive() bool` pub const isAnyItemActive = zguiIsAnyItemActive; /// `pub fn isAnyItemFocused() bool` pub const isAnyItemFocused = zguiIsAnyItemFocused; extern fn zguiIsMouseDown(mouse_button: MouseButton) bool; extern fn zguiIsMouseClicked(mouse_button: MouseButton) bool; extern fn zguiIsMouseDoubleClicked(mouse_button: MouseButton) bool; extern fn zguiIsItemHovered(flags: HoveredFlags) bool; extern fn zguiIsItemActive() bool; extern fn zguiIsItemFocused() bool; extern fn zguiIsItemClicked(mouse_button: MouseButton) bool; extern fn zguiIsItemVisible() bool; extern fn zguiIsItemEdited() bool; extern fn zguiIsItemActivated() bool; extern fn zguiIsItemDeactivated() bool; extern fn zguiIsItemDeactivatedAfterEdit() bool; extern fn zguiIsItemToggledOpen() bool; extern fn zguiIsAnyItemHovered() bool; extern fn zguiIsAnyItemActive() bool; extern fn zguiIsAnyItemFocused() bool; //-------------------------------------------------------------------------------------------------- // // Color Utilities // //-------------------------------------------------------------------------------------------------- pub fn colorConvertU32ToFloat4(in: u32) [4]f32 { var rgba: [4]f32 = undefined; zguiColorConvertU32ToFloat4(in, &rgba); return rgba; } pub fn colorConvertU32ToFloat3(in: u32) [3]f32 { var rgba: [4]f32 = undefined; zguiColorConvertU32ToFloat4(in, &rgba); return .{ rgba[0], rgba[1], rgba[2] }; } pub fn colorConvertFloat4ToU32(in: [4]f32) u32 { return zguiColorConvertFloat4ToU32(&in); } pub fn colorConvertFloat3ToU32(in: [3]f32) u32 { return colorConvertFloat4ToU32(.{ in[0], in[1], in[2], 1 }); } pub fn colorConvertRgbToHsv(r: f32, g: f32, b: f32) [3]f32 { var hsv: [3]f32 = undefined; zguiColorConvertRGBtoHSV(r, g, b, &hsv[0], &hsv[1], &hsv[2]); return hsv; } pub fn colorConvertHsvToRgb(h: f32, s: f32, v: f32) [3]f32 { var rgb: [3]f32 = undefined; zguiColorConvertHSVtoRGB(h, s, v, &rgb[0], &rgb[1], &rgb[2]); return rgb; } extern fn zguiColorConvertU32ToFloat4(in: u32, rgba: *[4]f32) void; extern fn zguiColorConvertFloat4ToU32(in: *const [4]f32) u32; extern fn zguiColorConvertRGBtoHSV(r: f32, g: f32, b: f32, out_h: *f32, out_s: *f32, out_v: *f32) void; extern fn zguiColorConvertHSVtoRGB(h: f32, s: f32, v: f32, out_r: *f32, out_g: *f32, out_b: *f32) void; //-------------------------------------------------------------------------------------------------- // // Inputs Utilities: Keyboard // //-------------------------------------------------------------------------------------------------- pub fn isKeyDown(key: Key) bool { return zguiIsKeyDown(key); } extern fn zguiIsKeyDown(key: Key) bool; //-------------------------------------------------------------------------------------------------- // // Helpers // //-------------------------------------------------------------------------------------------------- var temp_buffer: ?std.ArrayList(u8) = null; pub fn format(comptime fmt: []const u8, args: anytype) []const u8 { const len = std.fmt.count(fmt, args); if (len > temp_buffer.?.items.len) temp_buffer.?.resize(len + 64) catch unreachable; return std.fmt.bufPrint(temp_buffer.?.items, fmt, args) catch unreachable; } pub fn formatZ(comptime fmt: []const u8, args: anytype) [:0]const u8 { const len = std.fmt.count(fmt ++ "\x00", args); if (len > temp_buffer.?.items.len) temp_buffer.?.resize(len + 64) catch unreachable; return std.fmt.bufPrintZ(temp_buffer.?.items, fmt, args) catch unreachable; } //-------------------------------------------------------------------------------------------------- pub fn typeToDataTypeEnum(comptime T: type) DataType { return switch (T) { i8 => .I8, u8 => .U8, i16 => .I16, u16 => .U16, i32 => .I32, u32 => .U32, i64 => .I64, u64 => .U64, f32 => .F32, f64 => .F64, usize => switch (@sizeOf(usize)) { 1 => .U8, 2 => .U16, 4 => .U32, 8 => .U64, else => @compileError("Unsupported usize length"), }, else => @compileError("Only fundamental scalar types allowed: " ++ @typeName(T)), }; } //-------------------------------------------------------------------------------------------------- // // Menus // //-------------------------------------------------------------------------------------------------- /// `pub fn beginMenuBar() bool` pub const beginMenuBar = zguiBeginMenuBar; /// `pub fn endMenuBar() void` pub const endMenuBar = zguiEndMenuBar; /// `pub fn beginMainMenuBar() bool` pub const beginMainMenuBar = zguiBeginMainMenuBar; /// `pub fn endMainMenuBar() void` pub const endMainMenuBar = zguiEndMainMenuBar; pub fn beginMenu(label: [:0]const u8, enabled: bool) bool { return zguiBeginMenu(label, enabled); } /// `pub fn endMenu() void` pub const endMenu = zguiEndMenu; const MenuItem = struct { shortcut: ?[:0]const u8 = null, selected: bool = false, enabled: bool = true, }; pub fn menuItem(label: [:0]const u8, args: MenuItem) bool { return zguiMenuItem(label, if (args.shortcut) |s| s.ptr else null, args.selected, args.enabled); } const MenuItemPtr = struct { shortcut: ?[:0]const u8 = null, selected: *bool, enabled: bool = true, }; pub fn menuItemPtr(label: [:0]const u8, args: MenuItemPtr) bool { return zguiMenuItemPtr(label, if (args.shortcut) |s| s.ptr else null, args.selected, args.enabled); } extern fn zguiBeginMenuBar() bool; extern fn zguiEndMenuBar() void; extern fn zguiBeginMainMenuBar() bool; extern fn zguiEndMainMenuBar() void; extern fn zguiBeginMenu(label: [*:0]const u8, enabled: bool) bool; extern fn zguiEndMenu() void; extern fn zguiMenuItem(label: [*:0]const u8, shortcut: ?[*:0]const u8, selected: bool, enabled: bool) bool; extern fn zguiMenuItemPtr(label: [*:0]const u8, shortcut: ?[*:0]const u8, selected: *bool, enabled: bool) bool; //-------------------------------------------------------------------------------------------------- // // Popups // //-------------------------------------------------------------------------------------------------- /// `pub fn beginTooltip() bool` pub const beginTooltip = zguiBeginTooltip; /// `pub fn endTooltip() void` pub const endTooltip = zguiEndTooltip; extern fn zguiBeginTooltip() bool; extern fn zguiEndTooltip() void; /// `pub fn beginPopupContextWindow() bool` pub const beginPopupContextWindow = zguiBeginPopupContextWindow; /// `pub fn beginPopupContextItem() bool` pub const beginPopupContextItem = zguiBeginPopupContextItem; pub const PopupFlags = packed struct(c_int) { mouse_button_left: bool = false, mouse_button_right: bool = false, mouse_button_middle: bool = false, _reserved0: bool = false, _reserved1: bool = false, no_reopen: bool = false, _reserved2: bool = false, no_open_over_existing_popup: bool = false, no_open_over_items: bool = false, any_popup_id: bool = false, any_popup_level: bool = false, _padding: u21 = 0, pub const any_popup = PopupFlags{ .any_popup_id = true, .any_popup_level = true }; }; pub fn beginPopupModal(name: [:0]const u8, args: Begin) bool { return zguiBeginPopupModal(name, args.popen, args.flags); } pub fn openPopup(str_id: [:0]const u8, flags: PopupFlags) void { zguiOpenPopup(str_id, flags); } /// `pub fn beginPopup(str_id: [:0]const u8, flags: WindowFlags) bool` pub const beginPopup = zguiBeginPopup; /// `pub fn endPopup() void` pub const endPopup = zguiEndPopup; /// `pub fn closeCurrentPopup() void` pub const closeCurrentPopup = zguiCloseCurrentPopup; extern fn zguiBeginPopupContextWindow() bool; extern fn zguiBeginPopupContextItem() bool; extern fn zguiBeginPopupModal(name: [*:0]const u8, popen: ?*bool, flags: WindowFlags) bool; extern fn zguiBeginPopup(str_id: [*:0]const u8, flags: WindowFlags) bool; extern fn zguiEndPopup() void; extern fn zguiOpenPopup(str_id: [*:0]const u8, flags: PopupFlags) void; extern fn zguiCloseCurrentPopup() void; //-------------------------------------------------------------------------------------------------- // // Tabs // //-------------------------------------------------------------------------------------------------- pub const TabBarFlags = packed struct(c_int) { reorderable: bool = false, auto_select_new_tabs: bool = false, tab_list_popup_button: bool = false, no_close_with_middle_mouse_button: bool = false, no_tab_list_scrolling_buttons: bool = false, no_tooltip: bool = false, fitting_policy_resize_down: bool = false, fitting_policy_scroll: bool = false, _padding: u24 = 0, }; pub const TabItemFlags = packed struct(c_int) { unsaved_document: bool = false, set_selected: bool = false, no_close_with_middle_mouse_button: bool = false, no_push_id: bool = false, no_tooltip: bool = false, no_reorder: bool = false, leading: bool = false, trailing: bool = false, no_assumed_closure: bool = false, _padding: u23 = 0, }; pub fn beginTabBar(label: [:0]const u8, flags: TabBarFlags) bool { return zguiBeginTabBar(label, flags); } const BeginTabItem = struct { p_open: ?*bool = null, flags: TabItemFlags = .{}, }; pub fn beginTabItem(label: [:0]const u8, args: BeginTabItem) bool { return zguiBeginTabItem(label, args.p_open, args.flags); } /// `void endTabItem() void` pub const endTabItem = zguiEndTabItem; /// `void endTabBar() void` pub const endTabBar = zguiEndTabBar; pub fn setTabItemClosed(tab_or_docked_window_label: [:0]const u8) void { zguiSetTabItemClosed(tab_or_docked_window_label); } extern fn zguiBeginTabBar(label: [*:0]const u8, flags: TabBarFlags) bool; extern fn zguiBeginTabItem(label: [*:0]const u8, p_open: ?*bool, flags: TabItemFlags) bool; extern fn zguiEndTabItem() void; extern fn zguiEndTabBar() void; extern fn zguiSetTabItemClosed(tab_or_docked_window_label: [*:0]const u8) void; //-------------------------------------------------------------------------------------------------- // // Viewport // //-------------------------------------------------------------------------------------------------- pub const Viewport = *opaque { pub fn getPos(viewport: Viewport) [2]f32 { var pos: [2]f32 = undefined; zguiViewport_GetPos(viewport, &pos); return pos; } extern fn zguiViewport_GetPos(viewport: Viewport, pos: *[2]f32) void; pub fn getSize(viewport: Viewport) [2]f32 { var pos: [2]f32 = undefined; zguiViewport_GetSize(viewport, &pos); return pos; } extern fn zguiViewport_GetSize(viewport: Viewport, size: *[2]f32) void; pub fn getWorkPos(viewport: Viewport) [2]f32 { var pos: [2]f32 = undefined; zguiViewport_GetWorkPos(viewport, &pos); return pos; } extern fn zguiViewport_GetWorkPos(viewport: Viewport, pos: *[2]f32) void; pub fn getWorkSize(viewport: Viewport) [2]f32 { var pos: [2]f32 = undefined; zguiViewport_GetWorkSize(viewport, &pos); return pos; } extern fn zguiViewport_GetWorkSize(viewport: Viewport, size: *[2]f32) void; pub fn getCenter(viewport: Viewport) [2]f32 { const pos = viewport.getPos(); const size = viewport.getSize(); return .{ pos[0] + size[0] * 0.5, pos[1] + size[1] * 0.5, }; } pub fn getWorkCenter(viewport: Viewport) [2]f32 { const pos = viewport.getWorkPos(); const size = viewport.getWorkSize(); return .{ pos[0] + size[0] * 0.5, pos[1] + size[1] * 0.5, }; } }; pub const getMainViewport = zguiGetMainViewport; extern fn zguiGetMainViewport() Viewport; //-------------------------------------------------------------------------------------------------- // // Mouse Input // //-------------------------------------------------------------------------------------------------- pub const MouseDragDelta = struct { lock_threshold: f32 = -1.0, }; pub fn getMouseDragDelta(drag_button: MouseButton, args: MouseDragDelta) [2]f32 { var delta: [2]f32 = undefined; zguiGetMouseDragDelta(drag_button, args.lock_threshold, &delta); return delta; } pub const resetMouseDragDelta = zguiResetMouseDragDelta; extern fn zguiGetMouseDragDelta(button: MouseButton, lock_threshold: f32, delta: *[2]f32) void; extern fn zguiResetMouseDragDelta(button: MouseButton) void; //-------------------------------------------------------------------------------------------------- // // Drag and Drop // //-------------------------------------------------------------------------------------------------- pub const DragDropFlags = packed struct(c_int) { source_no_preview_tooltip: bool = false, source_no_disable_hover: bool = false, source_no_hold_open_to_others: bool = false, source_allow_null_id: bool = false, source_extern: bool = false, source_auto_expire_payload: bool = false, _padding0: u4 = 0, accept_before_delivery: bool = false, accept_no_draw_default_rect: bool = false, accept_no_preview_tooltip: bool = false, _padding1: u19 = 0, pub const accept_peek_only = @This(){ .accept_before_delivery = true, .accept_no_draw_default_rect = true }; }; const Payload = extern struct { data: *anyopaque = null, data_size: c_int = 0, source_id: c_uint = 0, source_parent_id: c_uint = 0, data_frame_count: c_int = -1, data_type: [32:0]c_char, preview: bool = false, delivery: bool = false, pub fn init() Payload { var payload = Payload{}; payload.clear(); return payload; } /// `pub fn clear(payload: *Payload) void` pub const clear = zguiImGuiPayload_Clear; extern fn zguiImGuiPayload_Clear(payload: *Payload) void; /// `pub fn isDataType(payload: *const Payload, type: [*:0]const u8) bool` pub const isDataType = zguiImGuiPayload_IsDataType; extern fn zguiImGuiPayload_IsDataType(payload: *const Payload, type: [*:0]const u8) bool; /// `pub fn isPreview(payload: *const Payload) bool` pub const isPreview = zguiImGuiPayload_IsPreview; extern fn zguiImGuiPayload_IsPreview(payload: *const Payload) bool; /// `pub fn isDelivery(payload: *const Payload) bool; pub const isDelivery = zguiImGuiPayload_IsDelivery; extern fn zguiImGuiPayload_IsDelivery(payload: *const Payload) bool; }; pub fn beginDragDropSource(flags: DragDropFlags) bool { return zguiBeginDragDropSource(flags); } /// Note: `payload_type` can be at most 32 characters long pub fn setDragDropPayload(payload_type: [*:0]const u8, data: []const u8, cond: Condition) bool { return zguiSetDragDropPayload(payload_type, @alignCast(@ptrCast(data.ptr)), data.len, cond); } pub fn endDragDropSource() void { zguiEndDragDropSource(); } pub fn beginDragDropTarget() bool { return zguiBeginDragDropTarget(); } /// Note: `payload_type` can be at most 32 characters long pub fn acceptDragDropPayload(payload_type: [*:0]const u8, flags: DragDropFlags) ?*Payload { return zguiAcceptDragDropPayload(payload_type, flags); } pub fn endDragDropTarget() void { zguiEndDragDropTarget(); } pub fn getDragDropPayload() ?*Payload { return zguiGetDragDropPayload(); } extern fn zguiBeginDragDropSource(flags: DragDropFlags) bool; extern fn zguiSetDragDropPayload(type: [*:0]const u8, data: *const anyopaque, sz: usize, cond: Condition) bool; extern fn zguiEndDragDropSource() void; extern fn zguiBeginDragDropTarget() bool; extern fn zguiAcceptDragDropPayload(type: [*:0]const u8, flags: DragDropFlags) [*c]Payload; extern fn zguiEndDragDropTarget() void; extern fn zguiGetDragDropPayload() [*c]Payload; //-------------------------------------------------------------------------------------------------- // // DrawFlags // //-------------------------------------------------------------------------------------------------- pub const DrawFlags = packed struct(c_int) { closed: bool = false, _padding0: u3 = 0, round_corners_top_left: bool = false, round_corners_top_right: bool = false, round_corners_bottom_left: bool = false, round_corners_bottom_right: bool = false, round_corners_none: bool = false, _padding1: u23 = 0, pub const round_corners_top = DrawFlags{ .round_corners_top_left = true, .round_corners_top_right = true, }; pub const round_corners_bottom = DrawFlags{ .round_corners_bottom_left = true, .round_corners_bottom_right = true, }; pub const round_corners_left = DrawFlags{ .round_corners_top_left = true, .round_corners_bottom_left = true, }; pub const round_corners_right = DrawFlags{ .round_corners_top_right = true, .round_corners_bottom_right = true, }; pub const round_corners_all = DrawFlags{ .round_corners_top_left = true, .round_corners_top_right = true, .round_corners_bottom_left = true, .round_corners_bottom_right = true, }; }; pub const DrawCmd = extern struct { clip_rect: [4]f32, texture_id: TextureIdent, vtx_offset: c_uint, idx_offset: c_uint, elem_count: c_uint, user_callback: ?DrawCallback, user_callback_data: ?*anyopaque, }; pub const DrawCallback = *const fn (*const anyopaque, *const DrawCmd) callconv(.C) void; pub const getWindowDrawList = zguiGetWindowDrawList; pub const getBackgroundDrawList = zguiGetBackgroundDrawList; pub const getForegroundDrawList = zguiGetForegroundDrawList; pub const createDrawList = zguiCreateDrawList; pub fn destroyDrawList(draw_list: DrawList) void { if (draw_list.getOwnerName()) |owner| { @panic(format("zgui: illegally destroying DrawList of {s}", .{owner})); } zguiDestroyDrawList(draw_list); } extern fn zguiGetWindowDrawList() DrawList; extern fn zguiGetBackgroundDrawList() DrawList; extern fn zguiGetForegroundDrawList() DrawList; extern fn zguiCreateDrawList() DrawList; extern fn zguiDestroyDrawList(draw_list: DrawList) void; pub const DrawList = *opaque { pub const getOwnerName = zguiDrawList_GetOwnerName; extern fn zguiDrawList_GetOwnerName(draw_list: DrawList) ?[*:0]const u8; pub fn reset(draw_list: DrawList) void { if (draw_list.getOwnerName()) |owner| { @panic(format("zgui: illegally resetting DrawList of {s}", .{owner})); } zguiDrawList_ResetForNewFrame(draw_list); } extern fn zguiDrawList_ResetForNewFrame(draw_list: DrawList) void; pub fn clearMemory(draw_list: DrawList) void { if (draw_list.getOwnerName()) |owner| { @panic(format("zgui: illegally clearing memory DrawList of {s}", .{owner})); } zguiDrawList_ClearFreeMemory(draw_list); } extern fn zguiDrawList_ClearFreeMemory(draw_list: DrawList) void; //---------------------------------------------------------------------------------------------- pub fn getVertexBufferLength(draw_list: DrawList) i32 { return zguiDrawList_GetVertexBufferLength(draw_list); } extern fn zguiDrawList_GetVertexBufferLength(draw_list: DrawList) c_int; pub const getVertexBufferData = zguiDrawList_GetVertexBufferData; extern fn zguiDrawList_GetVertexBufferData(draw_list: DrawList) [*]DrawVert; pub fn getVertexBuffer(draw_list: DrawList) []DrawVert { const len: usize = @intCast(draw_list.getVertexBufferLength()); return draw_list.getVertexBufferData()[0..len]; } pub fn getIndexBufferLength(draw_list: DrawList) i32 { return zguiDrawList_GetIndexBufferLength(draw_list); } extern fn zguiDrawList_GetIndexBufferLength(draw_list: DrawList) c_int; pub const getIndexBufferData = zguiDrawList_GetIndexBufferData; extern fn zguiDrawList_GetIndexBufferData(draw_list: DrawList) [*]DrawIdx; pub fn getIndexBuffer(draw_list: DrawList) []DrawIdx { const len: usize = @intCast(draw_list.getIndexBufferLength()); return draw_list.getIndexBufferData()[0..len]; } pub fn getCurrentIndex(draw_list: DrawList) u32 { return zguiDrawList_GetCurrentIndex(draw_list); } extern fn zguiDrawList_GetCurrentIndex(draw_list: DrawList) c_uint; pub fn getCmdBufferLength(draw_list: DrawList) i32 { return zguiDrawList_GetCmdBufferLength(draw_list); } extern fn zguiDrawList_GetCmdBufferLength(draw_list: DrawList) c_int; pub const getCmdBufferData = zguiDrawList_GetCmdBufferData; extern fn zguiDrawList_GetCmdBufferData(draw_list: DrawList) [*]DrawCmd; pub fn getCmdBuffer(draw_list: DrawList) []DrawCmd { const len: usize = @intCast(draw_list.getCmdBufferLength()); return draw_list.getCmdBufferData()[0..len]; } pub const DrawListFlags = packed struct(c_int) { anti_aliased_lines: bool = false, anti_aliased_lines_use_tex: bool = false, anti_aliased_fill: bool = false, allow_vtx_offset: bool = false, _padding: u28 = 0, }; pub const setDrawListFlags = zguiDrawList_SetFlags; extern fn zguiDrawList_SetFlags(draw_list: DrawList, flags: DrawListFlags) void; pub const getDrawListFlags = zguiDrawList_GetFlags; extern fn zguiDrawList_GetFlags(draw_list: DrawList) DrawListFlags; //---------------------------------------------------------------------------------------------- const ClipRect = struct { pmin: [2]f32, pmax: [2]f32, intersect_with_current: bool = false, }; pub fn pushClipRect(draw_list: DrawList, args: ClipRect) void { zguiDrawList_PushClipRect( draw_list, &args.pmin, &args.pmax, args.intersect_with_current, ); } extern fn zguiDrawList_PushClipRect( draw_list: DrawList, clip_rect_min: *const [2]f32, clip_rect_max: *const [2]f32, intersect_with_current_clip_rect: bool, ) void; //---------------------------------------------------------------------------------------------- pub const pushClipRectFullScreen = zguiDrawList_PushClipRectFullScreen; extern fn zguiDrawList_PushClipRectFullScreen(draw_list: DrawList) void; pub const popClipRect = zguiDrawList_PopClipRect; extern fn zguiDrawList_PopClipRect(draw_list: DrawList) void; //---------------------------------------------------------------------------------------------- pub const pushTextureId = zguiDrawList_PushTextureId; extern fn zguiDrawList_PushTextureId(draw_list: DrawList, texture_id: TextureIdent) void; pub const popTextureId = zguiDrawList_PopTextureId; extern fn zguiDrawList_PopTextureId(draw_list: DrawList) void; //---------------------------------------------------------------------------------------------- pub fn getClipRectMin(draw_list: DrawList) [2]f32 { var v: [2]f32 = undefined; zguiDrawList_GetClipRectMin(draw_list, &v); return v; } extern fn zguiDrawList_GetClipRectMin(draw_list: DrawList, clip_min: *[2]f32) void; pub fn getClipRectMax(draw_list: DrawList) [2]f32 { var v: [2]f32 = undefined; zguiDrawList_GetClipRectMax(draw_list, &v); return v; } extern fn zguiDrawList_GetClipRectMax(draw_list: DrawList, clip_min: *[2]f32) void; //---------------------------------------------------------------------------------------------- pub fn addLine(draw_list: DrawList, args: struct { p1: [2]f32, p2: [2]f32, col: u32, thickness: f32, }) void { zguiDrawList_AddLine(draw_list, &args.p1, &args.p2, args.col, args.thickness); } extern fn zguiDrawList_AddLine( draw_list: DrawList, p1: *const [2]f32, p2: *const [2]f32, col: u32, thickness: f32, ) void; //---------------------------------------------------------------------------------------------- pub fn addRect(draw_list: DrawList, args: struct { pmin: [2]f32, pmax: [2]f32, col: u32, rounding: f32 = 0.0, flags: DrawFlags = .{}, thickness: f32 = 1.0, }) void { zguiDrawList_AddRect( draw_list, &args.pmin, &args.pmax, args.col, args.rounding, args.flags, args.thickness, ); } extern fn zguiDrawList_AddRect( draw_list: DrawList, pmin: *const [2]f32, pmax: *const [2]f32, col: u32, rounding: f32, flags: DrawFlags, thickness: f32, ) void; //---------------------------------------------------------------------------------------------- pub fn addRectFilled(draw_list: DrawList, args: struct { pmin: [2]f32, pmax: [2]f32, col: u32, rounding: f32 = 0.0, flags: DrawFlags = .{}, }) void { zguiDrawList_AddRectFilled( draw_list, &args.pmin, &args.pmax, args.col, args.rounding, args.flags, ); } extern fn zguiDrawList_AddRectFilled( draw_list: DrawList, pmin: *const [2]f32, pmax: *const [2]f32, col: u32, rounding: f32, flags: DrawFlags, ) void; //---------------------------------------------------------------------------------------------- pub fn addRectFilledMultiColor(draw_list: DrawList, args: struct { pmin: [2]f32, pmax: [2]f32, col_upr_left: u32, col_upr_right: u32, col_bot_right: u32, col_bot_left: u32, }) void { zguiDrawList_AddRectFilledMultiColor( draw_list, &args.pmin, &args.pmax, args.col_upr_left, args.col_upr_right, args.col_bot_right, args.col_bot_left, ); } extern fn zguiDrawList_AddRectFilledMultiColor( draw_list: DrawList, pmin: *const [2]f32, pmax: *const [2]f32, col_upr_left: c_uint, col_upr_right: c_uint, col_bot_right: c_uint, col_bot_left: c_uint, ) void; //---------------------------------------------------------------------------------------------- pub fn addQuad(draw_list: DrawList, args: struct { p1: [2]f32, p2: [2]f32, p3: [2]f32, p4: [2]f32, col: u32, thickness: f32 = 1.0, }) void { zguiDrawList_AddQuad( draw_list, &args.p1, &args.p2, &args.p3, &args.p4, args.col, args.thickness, ); } extern fn zguiDrawList_AddQuad( draw_list: DrawList, p1: *const [2]f32, p2: *const [2]f32, p3: *const [2]f32, p4: *const [2]f32, col: u32, thickness: f32, ) void; //---------------------------------------------------------------------------------------------- pub fn addQuadFilled(draw_list: DrawList, args: struct { p1: [2]f32, p2: [2]f32, p3: [2]f32, p4: [2]f32, col: u32, }) void { zguiDrawList_AddQuadFilled(draw_list, &args.p1, &args.p2, &args.p3, &args.p4, args.col); } extern fn zguiDrawList_AddQuadFilled( draw_list: DrawList, p1: *const [2]f32, p2: *const [2]f32, p3: *const [2]f32, p4: *const [2]f32, col: u32, ) void; //---------------------------------------------------------------------------------------------- pub fn addTriangle(draw_list: DrawList, args: struct { p1: [2]f32, p2: [2]f32, p3: [2]f32, col: u32, thickness: f32 = 1.0, }) void { zguiDrawList_AddTriangle(draw_list, &args.p1, &args.p2, &args.p3, args.col, args.thickness); } extern fn zguiDrawList_AddTriangle( draw_list: DrawList, p1: *const [2]f32, p2: *const [2]f32, p3: *const [2]f32, col: u32, thickness: f32, ) void; //---------------------------------------------------------------------------------------------- pub fn addTriangleFilled(draw_list: DrawList, args: struct { p1: [2]f32, p2: [2]f32, p3: [2]f32, col: u32, }) void { zguiDrawList_AddTriangleFilled(draw_list, &args.p1, &args.p2, &args.p3, args.col); } extern fn zguiDrawList_AddTriangleFilled( draw_list: DrawList, p1: *const [2]f32, p2: *const [2]f32, p3: *const [2]f32, col: u32, ) void; //---------------------------------------------------------------------------------------------- pub fn addCircle(draw_list: DrawList, args: struct { p: [2]f32, r: f32, col: u32, num_segments: i32 = 0, thickness: f32 = 1.0, }) void { zguiDrawList_AddCircle( draw_list, &args.p, args.r, args.col, args.num_segments, args.thickness, ); } extern fn zguiDrawList_AddCircle( draw_list: DrawList, center: *const [2]f32, radius: f32, col: u32, num_segments: c_int, thickness: f32, ) void; //---------------------------------------------------------------------------------------------- pub fn addCircleFilled(draw_list: DrawList, args: struct { p: [2]f32, r: f32, col: u32, num_segments: u16 = 0, }) void { zguiDrawList_AddCircleFilled(draw_list, &args.p, args.r, args.col, args.num_segments); } extern fn zguiDrawList_AddCircleFilled( draw_list: DrawList, center: *const [2]f32, radius: f32, col: u32, num_segments: c_int, ) void; //---------------------------------------------------------------------------------------------- pub fn addNgon(draw_list: DrawList, args: struct { p: [2]f32, r: f32, col: u32, num_segments: u32, thickness: f32 = 1.0, }) void { zguiDrawList_AddNgon( draw_list, &args.p, args.r, args.col, args.num_segments, args.thickness, ); } extern fn zguiDrawList_AddNgon( draw_list: DrawList, center: *const [2]f32, radius: f32, col: u32, num_segments: c_int, thickness: f32, ) void; //---------------------------------------------------------------------------------------------- pub fn addNgonFilled(draw_list: DrawList, args: struct { p: [2]f32, r: f32, col: u32, num_segments: u32, }) void { zguiDrawList_AddNgonFilled(draw_list, &args.p, args.r, args.col, args.num_segments); } extern fn zguiDrawList_AddNgonFilled( draw_list: DrawList, center: *const [2]f32, radius: f32, col: u32, num_segments: c_int, ) void; //---------------------------------------------------------------------------------------------- pub fn addText(draw_list: DrawList, pos: [2]f32, col: u32, comptime fmt: []const u8, args: anytype) void { const txt = format(fmt, args); draw_list.addTextUnformatted(pos, col, txt); } pub fn addTextUnformatted(draw_list: DrawList, pos: [2]f32, col: u32, txt: []const u8) void { zguiDrawList_AddText(draw_list, &pos, col, txt.ptr, txt.ptr + txt.len); } extern fn zguiDrawList_AddText( draw_list: DrawList, pos: *const [2]f32, col: u32, text: [*]const u8, text_end: [*]const u8, ) void; //---------------------------------------------------------------------------------------------- pub fn addPolyline(draw_list: DrawList, points: []const [2]f32, args: struct { col: u32, flags: DrawFlags = .{}, thickness: f32 = 1.0, }) void { zguiDrawList_AddPolyline( draw_list, points.ptr, @intCast(points.len), args.col, args.flags, args.thickness, ); } extern fn zguiDrawList_AddPolyline( draw_list: DrawList, points: [*]const [2]f32, num_points: c_int, col: u32, flags: DrawFlags, thickness: f32, ) void; //---------------------------------------------------------------------------------------------- pub fn addConvexPolyFilled( draw_list: DrawList, points: []const [2]f32, col: u32, ) void { zguiDrawList_AddConvexPolyFilled( draw_list, points.ptr, @intCast(points.len), col, ); } extern fn zguiDrawList_AddConvexPolyFilled( draw_list: DrawList, points: [*]const [2]f32, num_points: c_int, col: u32, ) void; //---------------------------------------------------------------------------------------------- pub fn addBezierCubic(draw_list: DrawList, args: struct { p1: [2]f32, p2: [2]f32, p3: [2]f32, p4: [2]f32, col: u32, thickness: f32 = 1.0, num_segments: u32 = 0, }) void { zguiDrawList_AddBezierCubic( draw_list, &args.p1, &args.p2, &args.p3, &args.p4, args.col, args.thickness, args.num_segments, ); } extern fn zguiDrawList_AddBezierCubic( draw_list: DrawList, p1: *const [2]f32, p2: *const [2]f32, p3: *const [2]f32, p4: *const [2]f32, col: u32, thickness: f32, num_segments: c_int, ) void; //---------------------------------------------------------------------------------------------- pub fn addBezierQuadratic(draw_list: DrawList, args: struct { p1: [2]f32, p2: [2]f32, p3: [2]f32, col: u32, thickness: f32 = 1.0, num_segments: u32 = 0, }) void { zguiDrawList_AddBezierQuadratic( draw_list, &args.p1, &args.p2, &args.p3, args.col, args.thickness, args.num_segments, ); } extern fn zguiDrawList_AddBezierQuadratic( draw_list: DrawList, p1: *const [2]f32, p2: *const [2]f32, p3: *const [2]f32, col: u32, thickness: f32, num_segments: c_int, ) void; //---------------------------------------------------------------------------------------------- pub fn addImage(draw_list: DrawList, user_texture_id: TextureIdent, args: struct { pmin: [2]f32, pmax: [2]f32, uvmin: [2]f32 = .{ 0, 0 }, uvmax: [2]f32 = .{ 1, 1 }, col: u32 = 0xff_ff_ff_ff, }) void { zguiDrawList_AddImage( draw_list, user_texture_id, &args.pmin, &args.pmax, &args.uvmin, &args.uvmax, args.col, ); } extern fn zguiDrawList_AddImage( draw_list: DrawList, user_texture_id: TextureIdent, pmin: *const [2]f32, pmax: *const [2]f32, uvmin: *const [2]f32, uvmax: *const [2]f32, col: u32, ) void; //---------------------------------------------------------------------------------------------- pub fn addImageQuad(draw_list: DrawList, user_texture_id: TextureIdent, args: struct { p1: [2]f32, p2: [2]f32, p3: [2]f32, p4: [2]f32, uv1: [2]f32 = .{ 0, 0 }, uv2: [2]f32 = .{ 1, 0 }, uv3: [2]f32 = .{ 1, 1 }, uv4: [2]f32 = .{ 0, 1 }, col: u32 = 0xff_ff_ff_ff, }) void { zguiDrawList_AddImageQuad( draw_list, user_texture_id, &args.p1, &args.p2, &args.p3, &args.p4, &args.uv1, &args.uv2, &args.uv3, &args.uv4, args.col, ); } extern fn zguiDrawList_AddImageQuad( draw_list: DrawList, user_texture_id: TextureIdent, p1: *const [2]f32, p2: *const [2]f32, p3: *const [2]f32, p4: *const [2]f32, uv1: *const [2]f32, uv2: *const [2]f32, uv3: *const [2]f32, uv4: *const [2]f32, col: u32, ) void; //---------------------------------------------------------------------------------------------- pub fn addImageRounded(draw_list: DrawList, user_texture_id: TextureIdent, args: struct { pmin: [2]f32, pmax: [2]f32, uvmin: [2]f32 = .{ 0, 0 }, uvmax: [2]f32 = .{ 1, 1 }, col: u32 = 0xff_ff_ff_ff, rounding: f32 = 4.0, flags: DrawFlags = .{}, }) void { zguiDrawList_AddImageRounded( draw_list, user_texture_id, &args.pmin, &args.pmax, &args.uvmin, &args.uvmax, args.col, args.rounding, args.flags, ); } extern fn zguiDrawList_AddImageRounded( draw_list: DrawList, user_texture_id: TextureIdent, pmin: *const [2]f32, pmax: *const [2]f32, uvmin: *const [2]f32, uvmax: *const [2]f32, col: u32, rounding: f32, flags: DrawFlags, ) void; //---------------------------------------------------------------------------------------------- pub const pathClear = zguiDrawList_PathClear; extern fn zguiDrawList_PathClear(draw_list: DrawList) void; //---------------------------------------------------------------------------------------------- pub fn pathLineTo(draw_list: DrawList, pos: [2]f32) void { zguiDrawList_PathLineTo(draw_list, &pos); } extern fn zguiDrawList_PathLineTo(draw_list: DrawList, pos: *const [2]f32) void; //---------------------------------------------------------------------------------------------- pub fn pathLineToMergeDuplicate(draw_list: DrawList, pos: [2]f32) void { zguiDrawList_PathLineToMergeDuplicate(draw_list, &pos); } extern fn zguiDrawList_PathLineToMergeDuplicate(draw_list: DrawList, pos: *const [2]f32) void; //---------------------------------------------------------------------------------------------- pub fn pathFillConvex(draw_list: DrawList, col: u32) void { return zguiDrawList_PathFillConvex(draw_list, col); } extern fn zguiDrawList_PathFillConvex(draw_list: DrawList, col: c_uint) void; //---------------------------------------------------------------------------------------------- pub fn pathStroke(draw_list: DrawList, args: struct { col: u32, flags: DrawFlags = .{}, thickness: f32 = 1.0, }) void { zguiDrawList_PathStroke(draw_list, args.col, args.flags, args.thickness); } extern fn zguiDrawList_PathStroke(draw_list: DrawList, col: u32, flags: DrawFlags, thickness: f32) void; //---------------------------------------------------------------------------------------------- pub fn pathArcTo(draw_list: DrawList, args: struct { p: [2]f32, r: f32, amin: f32, amax: f32, num_segments: u16 = 0, }) void { zguiDrawList_PathArcTo( draw_list, &args.p, args.r, args.amin, args.amax, args.num_segments, ); } extern fn zguiDrawList_PathArcTo( draw_list: DrawList, center: *const [2]f32, radius: f32, amin: f32, amax: f32, num_segments: c_int, ) void; //---------------------------------------------------------------------------------------------- pub fn pathArcToFast(draw_list: DrawList, args: struct { p: [2]f32, r: f32, amin_of_12: u16, amax_of_12: u16, }) void { zguiDrawList_PathArcToFast(draw_list, &args.p, args.r, args.amin_of_12, args.amax_of_12); } extern fn zguiDrawList_PathArcToFast( draw_list: DrawList, center: *const [2]f32, radius: f32, a_min_of_12: c_int, a_max_of_12: c_int, ) void; //---------------------------------------------------------------------------------------------- pub fn pathBezierCubicCurveTo(draw_list: DrawList, args: struct { p2: [2]f32, p3: [2]f32, p4: [2]f32, num_segments: u16 = 0, }) void { zguiDrawList_PathBezierCubicCurveTo( draw_list, &args.p2, &args.p3, &args.p4, args.num_segments, ); } extern fn zguiDrawList_PathBezierCubicCurveTo( draw_list: DrawList, p2: *const [2]f32, p3: *const [2]f32, p4: *const [2]f32, num_segments: c_int, ) void; //---------------------------------------------------------------------------------------------- pub fn pathBezierQuadraticCurveTo(draw_list: DrawList, args: struct { p2: [2]f32, p3: [2]f32, num_segments: u16 = 0, }) void { zguiDrawList_PathBezierQuadraticCurveTo(draw_list, &args.p2, &args.p3, args.num_segments); } extern fn zguiDrawList_PathBezierQuadraticCurveTo( draw_list: DrawList, p2: *const [2]f32, p3: *const [2]f32, num_segments: c_int, ) void; //---------------------------------------------------------------------------------------------- const PathRect = struct { bmin: [2]f32, bmax: [2]f32, rounding: f32 = 0.0, flags: DrawFlags = .{}, }; pub fn pathRect(draw_list: DrawList, args: PathRect) void { zguiDrawList_PathRect(draw_list, &args.bmin, &args.bmax, args.rounding, args.flags); } extern fn zguiDrawList_PathRect( draw_list: DrawList, rect_min: *const [2]f32, rect_max: *const [2]f32, rounding: f32, flags: DrawFlags, ) void; //---------------------------------------------------------------------------------------------- pub const primReserve = zguiDrawList_PrimReserve; extern fn zguiDrawList_PrimReserve( draw_list: DrawList, idx_count: i32, vtx_count: i32, ) void; pub const primUnreserve = zguiDrawList_PrimUnreserve; extern fn zguiDrawList_PrimUnreserve( draw_list: DrawList, idx_count: i32, vtx_count: i32, ) void; pub fn primRect( draw_list: DrawList, a: [2]f32, b: [2]f32, col: u32, ) void { return zguiDrawList_PrimRect(draw_list, &a, &b, col); } extern fn zguiDrawList_PrimRect( draw_list: DrawList, a: *const [2]f32, b: *const [2]f32, col: u32, ) void; pub fn primRectUV( draw_list: DrawList, a: [2]f32, b: [2]f32, uv_a: [2]f32, uv_b: [2]f32, col: u32, ) void { return zguiDrawList_PrimRectUV(draw_list, &a, &b, &uv_a, &uv_b, col); } extern fn zguiDrawList_PrimRectUV( draw_list: DrawList, a: *const [2]f32, b: *const [2]f32, uv_a: *const [2]f32, uv_b: *const [2]f32, col: u32, ) void; pub fn primQuadUV( draw_list: DrawList, a: [2]f32, b: [2]f32, c: [2]f32, d: [2]f32, uv_a: [2]f32, uv_b: [2]f32, uv_c: [2]f32, uv_d: [2]f32, col: u32, ) void { return zguiDrawList_PrimQuadUV(draw_list, &a, &b, &c, &d, &uv_a, &uv_b, &uv_c, &uv_d, col); } extern fn zguiDrawList_PrimQuadUV( draw_list: DrawList, a: *const [2]f32, b: *const [2]f32, c: *const [2]f32, d: *const [2]f32, uv_a: *const [2]f32, uv_b: *const [2]f32, uv_c: *const [2]f32, uv_d: *const [2]f32, col: u32, ) void; pub fn primWriteVtx( draw_list: DrawList, pos: [2]f32, uv: [2]f32, col: u32, ) void { return zguiDrawList_PrimWriteVtx(draw_list, &pos, &uv, col); } extern fn zguiDrawList_PrimWriteVtx( draw_list: DrawList, pos: *const [2]f32, uv: *const [2]f32, col: u32, ) void; pub const primWriteIdx = zguiDrawList_PrimWriteIdx; extern fn zguiDrawList_PrimWriteIdx( draw_list: DrawList, idx: DrawIdx, ) void; //---------------------------------------------------------------------------------------------- pub fn addCallback(draw_list: DrawList, callback: DrawCallback, callback_data: ?*anyopaque) void { zguiDrawList_AddCallback(draw_list, callback, callback_data); } extern fn zguiDrawList_AddCallback(draw_list: DrawList, callback: DrawCallback, callback_data: ?*anyopaque) void; pub fn addResetRenderStateCallback(draw_list: DrawList) void { zguiDrawList_AddResetRenderStateCallback(draw_list); } extern fn zguiDrawList_AddResetRenderStateCallback(draw_list: DrawList) void; }; fn Vector(comptime T: type) type { return extern struct { len: c_int, capacity: c_int, items: [*]T, }; } test { const testing = std.testing; testing.refAllDeclsRecursive(@This()); init(testing.allocator); defer deinit(); io.setIniFilename(null); _ = io.getFontsTextDataAsRgba32(); io.setDisplaySize(1, 1); newFrame(); try testing.expect(begin("testing", .{})); defer end(); const Testing = enum { one, two, three, }; var value = Testing.one; _ = comboFromEnum("comboFromEnum", &value); }