diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index aba06be1..f62b7588 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -90,7 +90,7 @@ jobs: if ($result.eligible_interfaces -ne 7929) { throw "Classic COM census denominator changed: $($result.eligible_interfaces)" } - if ($result.complete_interfaces -lt 5691) { + if ($result.complete_interfaces -lt 5696) { throw "Classic COM complete coverage regressed: $($result.complete_interfaces)" } if ($result.coverage_percent -lt 70.0) { @@ -107,21 +107,21 @@ jobs: if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } $result = Get-Content (Join-Path $output 'classic-com-capability-summary.json') -Raw | ConvertFrom-Json - if ($result.eligible_interfaces -ne 7929 -or $result.safe_complete -ne 5691) { + if ($result.eligible_interfaces -ne 7929 -or $result.safe_complete -ne 5696) { throw "Classic COM safe totals changed in capability census" } $support = Import-Csv (Join-Path $output 'classic-com-interface-support.csv') if ( @($support).Count -ne 7929 -or - @($support | Where-Object { $_.safe_complete -eq 'true' }).Count -ne 5691 -or - @($support | Where-Object { $_.safe_complete -eq 'false' }).Count -ne 2238 + @($support | Where-Object { $_.safe_complete -eq 'true' }).Count -ne 5696 -or + @($support | Where-Object { $_.safe_complete -eq 'false' }).Count -ne 2233 ) { throw "Classic COM compact interface support index changed" } $expected = @{ - x64 = @(412, 1437, 389) - i686 = @(411, 1414, 413) - arm64 = @(412, 1437, 389) + x64 = @(412, 1432, 389) + i686 = @(411, 1409, 413) + arm64 = @(412, 1432, 389) } foreach ($target in @('x64', 'i686', 'arm64')) { $counts = $result.targets.$target @@ -134,16 +134,16 @@ jobs: } } if ( - $result.safeEvidence.safeComplete -ne 5691 -or + $result.safeEvidence.safeComplete -ne 5696 -or $result.safeEvidence.standardDerived -ne 5333 -or - $result.safeEvidence.exactRegistryDependent -ne 358 -or - $result.safeEvidence.metadataFactOccurrences -ne 5976 -or - $result.safeEvidence.comStandardFactOccurrences -ne 26114 -or - $result.safeEvidence.registeredExactEntries -ne 499 -or - $result.safeEvidence.metadataMatchedExactEntries -ne 499 -or - $result.safeEvidence.safeConsumedExactEntries -ne 408 -or - $result.safeEvidence.exactEntryInterfaceDependencies -ne 660 -or - $result.safeEvidence.exactFamilyInterfaceDependencies -ne 408 + $result.safeEvidence.exactRegistryDependent -ne 363 -or + $result.safeEvidence.metadataFactOccurrences -ne 5982 -or + $result.safeEvidence.comStandardFactOccurrences -ne 26129 -or + $result.safeEvidence.registeredExactEntries -ne 504 -or + $result.safeEvidence.metadataMatchedExactEntries -ne 504 -or + $result.safeEvidence.safeConsumedExactEntries -ne 413 -or + $result.safeEvidence.exactEntryInterfaceDependencies -ne 669 -or + $result.safeEvidence.exactFamilyInterfaceDependencies -ne 416 ) { throw "Classic COM safe evidence dependency census changed" } @@ -151,7 +151,8 @@ jobs: if ( @($statuses | Where-Object { -not $_.registered -or -not $_.metadataMatched }).Count -ne 0 -or @($statuses | Where-Object { $_.familyId -eq 'windows.borrowed-hwnd-output.v1' }).Count -ne 22 -or - @($statuses | Where-Object { $_.familyId -eq 'com.enumerator-next-exception.v1' }).Count -ne 73 + @($statuses | Where-Object { $_.familyId -eq 'com.enumerator-next-exception.v1' }).Count -ne 73 -or + @($statuses | Where-Object { $_.familyId -eq 'audio.conditional-output.v1' }).Count -ne 1 ) { throw "Classic COM exact registry entry validation changed" } diff --git a/README.md b/README.md index a5ad2321..c6e7f72e 100644 --- a/README.md +++ b/README.md @@ -142,12 +142,13 @@ is not a general Automation or native Win32 projection, and it does not project flat DLL exports. The current CI baseline against -`Microsoft.Windows.SDK.Win32Metadata` 71.0.14-preview is **5,691 of 7,929 -eligible interfaces (71.77%)** with complete safe code generation. Supported +`Microsoft.Windows.SDK.Win32Metadata` 71.0.14-preview is **5,696 of 7,929 +eligible interfaces (71.84%)** with complete safe code generation. Supported contracts include generated coclass activation and QueryInterface views, managed interface ownership, native POD layouts, typed counted buffers, BSTR/HSTRING, validated VARIANT, SAFEARRAY and PROPVARIANT subsets, the -target-device-independent `TYMED_HGLOBAL` FORMATETC/STGMEDIUM subset, and +target-device-independent `TYMED_HGLOBAL` FORMATETC/STGMEDIUM subset, +variable-length WAVEFORMATEX audio formats with exact CoTaskMem outputs, and synchronous JavaScript implementations of fully supported callback interfaces. Seventeen stock-Windows Node E2E runners exercise representative Shell, Automation, stream, callback, HWND, and WinRT interop scenarios. @@ -155,7 +156,7 @@ Automation, stream, callback, HWND, and WinRT interop scenarios. Safety takes priority over coverage. If metadata does not fully describe an interface's ABI, layout, ownership, allocator, or cleanup contract, generation fails before emitting a partial wrapper. Material gaps still include several -common graphics, audio, WMI, non-HGLOBAL/device-specific clipboard and +common graphics, advanced audio, WMI, non-HGLOBAL/device-specific clipboard and drag-and-drop, derived Automation, union, BYREF/InOut, and output-ownership shapes. diff --git a/bindings/js/Cargo.toml b/bindings/js/Cargo.toml index 69d4771b..a9be7a15 100644 --- a/bindings/js/Cargo.toml +++ b/bindings/js/Cargo.toml @@ -12,7 +12,7 @@ repository = "https://github.com/microsoft/dynwinrt" crate-type = ["cdylib"] [features] -test-hooks = ["windows/Win32_System_Wmi"] +test-hooks = ["windows/Win32_System_Wmi", "windows/Win32_Media_DeviceManager"] [dependencies] napi = { version = "3", features = ["napi7"] } diff --git a/bindings/js/__test__/generated-unsafe-companion.e2e.ts b/bindings/js/__test__/generated-unsafe-companion.e2e.ts index c6ab1f1a..593c807b 100644 --- a/bindings/js/__test__/generated-unsafe-companion.e2e.ts +++ b/bindings/js/__test__/generated-unsafe-companion.e2e.ts @@ -6,7 +6,7 @@ import { spawnSync } from 'node:child_process' import { lstatSync, readFileSync, readlinkSync, rmSync, mkdirSync, symlinkSync, writeFileSync } from 'node:fs' import { basename, dirname, join, resolve } from 'node:path' -test.serial('generated safe WMI and unsafe Audio companions preserve exact contracts', (t) => { +test.serial('generated safe COM and unsafe WinML companions preserve exact contracts', (t) => { const winmd = process.env.DYNWINRT_WIN32_WINMD t.truthy(winmd, 'DYNWINRT_WIN32_WINMD is required') const packageRoot = resolve(process.cwd()) @@ -33,7 +33,7 @@ test.serial('generated safe WMI and unsafe Audio companions preserve exact contr '--winmd', winmd!, '--class-name', - 'Windows.Win32.System.Wmi.IWbemServices,Windows.Win32.System.Wmi.IWbemClassObject,Windows.Win32.System.Wmi.IWbemCallResult,Windows.Win32.Media.Audio.IAudioClient,Windows.Win32.UI.Shell.IThumbnailProvider,Windows.Win32.System.Com.IDataObject,Windows.Win32.System.Ole.IOleCache,Windows.Win32.System.Ole.IOleCache2', + 'Windows.Win32.System.Wmi.IWbemServices,Windows.Win32.System.Wmi.IWbemClassObject,Windows.Win32.System.Wmi.IWbemCallResult,Windows.Win32.Media.Audio.IAudioClient,Windows.Win32.UI.Shell.IThumbnailProvider,Windows.Win32.System.Com.IDataObject,Windows.Win32.System.Ole.IOleCache,Windows.Win32.System.Ole.IOleCache2,Windows.Win32.AI.MachineLearning.WinML.IWinMLEvaluationContext,Windows.Win32.Media.DeviceManager.IMDSPDeviceControl,Windows.Win32.Media.DeviceManager.IWMDMDeviceControl', '--output', output, ] @@ -94,7 +94,10 @@ test.serial('generated safe WMI and unsafe Audio companions preserve exact contr const wbemCallResultBase = join(output, 'com', 'windows', 'win32', 'system', 'wmi', 'IWbemCallResult') const wbemClassObjectBase = join(output, 'com', 'unsafe', 'windows', 'win32', 'system', 'wmi', 'IWbemClassObjectUnsafe') const thumbnailBase = join(output, 'com', 'windows', 'win32', 'ui', 'shell', 'IThumbnailProvider') - const audioBase = join(output, 'com', 'unsafe', 'windows', 'win32', 'media', 'audio', 'IAudioClientUnsafe') + const audioBase = join(output, 'com', 'windows', 'win32', 'media', 'audio', 'IAudioClient') + const mdspDeviceControlBase = join(output, 'com', 'windows', 'win32', 'media', 'device-manager', 'IMDSPDeviceControl') + const wmdmDeviceControlBase = join(output, 'com', 'windows', 'win32', 'media', 'device-manager', 'IWMDMDeviceControl') + const evaluationBase = join(output, 'com', 'unsafe', 'windows', 'win32', 'ai', 'machine-learning', 'win-ml', 'IWinMLEvaluationContextUnsafe') const runner = join(output, 'generated-companion-runner.cjs') writeFileSync( runner, @@ -103,7 +106,7 @@ test.serial('generated safe WMI and unsafe Audio companions preserve exact contr "const assert = require('node:assert/strict')", "const { pathToFileURL } = require('node:url')", `const runtime = require(${JSON.stringify(join(packageRoot, 'dist', 'index.js'))})`, - "const { DynComFormatEtc, DynComStgMedium } = require('@microsoft/dynwinrt/com')", + "const { DynComAudioFormat, DynComFormatEtc, DynComStgMedium } = require('@microsoft/dynwinrt/com')", "const { DynComRaw, DynComRawMemory, DynComRawOwnedComPointer, DynComRawPointer, WinGuid } = require('@microsoft/dynwinrt/com/unsafe/raw')", `const strategyRuntime = require(${JSON.stringify(join(output, 'com', 'unsafe', 'runtime.js'))})`, 'const { UnsafePointee, UnsafePointerOutput, UnsafeHandleOutput, UnsafeInterfaceReplacement, UnsafeCountedBuffer, UnsafeRawCall, __prepareStrategy, __prepareWritableStorage, __prepareExactWritableSpan, __strategyArgument, __assertRawContract, __validateStrategySpans, __activateStrategies, __markDispatchEntered, __finishStrategy, __failStrategy, __releaseExtracted, __attachUnsafeOutputs, __testRunOwnedFinalizer, __testCreateOwnedPointer } = strategyRuntime', @@ -115,6 +118,9 @@ test.serial('generated safe WMI and unsafe Audio companions preserve exact contr `const wbemClassObject = require(${JSON.stringify(`${wbemClassObjectBase}.js`)})`, `const thumbnail = require(${JSON.stringify(`${thumbnailBase}.js`)})`, `const audio = require(${JSON.stringify(`${audioBase}.js`)})`, + `const mdspDeviceControl = require(${JSON.stringify(`${mdspDeviceControlBase}.js`)})`, + `const wmdmDeviceControl = require(${JSON.stringify(`${wmdmDeviceControlBase}.js`)})`, + `const evaluation = require(${JSON.stringify(`${evaluationBase}.js`)})`, `const safeBarrel = require(${JSON.stringify(join(output, 'com', 'index.js'))})`, `const cjsBarrel = require(${JSON.stringify(join(output, 'com', 'unsafe', 'index.js'))})`, 'function finishTransaction(records) {', @@ -138,6 +144,9 @@ test.serial('generated safe WMI and unsafe Audio companions preserve exact contr ` const esmWbemClassObject = await import(pathToFileURL(${JSON.stringify(`${wbemClassObjectBase}.js`)}).href)`, ` const esmThumbnail = await import(pathToFileURL(${JSON.stringify(`${thumbnailBase}.js`)}).href)`, ` const esmAudio = await import(pathToFileURL(${JSON.stringify(`${audioBase}.js`)}).href)`, + ` const esmMdspDeviceControl = await import(pathToFileURL(${JSON.stringify(`${mdspDeviceControlBase}.js`)}).href)`, + ` const esmWmdmDeviceControl = await import(pathToFileURL(${JSON.stringify(`${wmdmDeviceControlBase}.js`)}).href)`, + ` const esmEvaluation = await import(pathToFileURL(${JSON.stringify(`${evaluationBase}.js`)}).href)`, ` const esmSafeBarrel = await import(pathToFileURL(${JSON.stringify(join(output, 'com', 'index.mjs'))}).href)`, ` const esmBarrel = await import(pathToFileURL(${JSON.stringify(join(output, 'com', 'unsafe', 'index.mjs'))}).href)`, " assert.equal(typeof wbem.IWbemServices, 'function')", @@ -147,8 +156,17 @@ test.serial('generated safe WMI and unsafe Audio companions preserve exact contr " assert.equal(typeof wbemCallResult.IWbemCallResult, 'function')", " assert.equal(typeof wbemClassObject.IWbemClassObjectUnsafe, 'function')", " assert.equal(typeof thumbnail.IThumbnailProvider, 'function')", - " assert.equal(typeof audio.IAudioClientUnsafe, 'function')", - ' assert.equal(esmAudio.IAudioClientUnsafe, audio.IAudioClientUnsafe)', + " assert.equal(typeof audio.IAudioClient, 'function')", + " assert.equal(typeof mdspDeviceControl.IMDSPDeviceControl, 'function')", + " assert.equal(typeof wmdmDeviceControl.IWMDMDeviceControl, 'function')", + " assert.equal(typeof evaluation.IWinMLEvaluationContextUnsafe, 'function')", + ' assert.equal(esmAudio.IAudioClient, audio.IAudioClient)', + ' assert.equal(esmMdspDeviceControl.IMDSPDeviceControl, mdspDeviceControl.IMDSPDeviceControl)', + ' assert.equal(esmWmdmDeviceControl.IWMDMDeviceControl, wmdmDeviceControl.IWMDMDeviceControl)', + ' assert.equal(esmEvaluation.IWinMLEvaluationContextUnsafe, evaluation.IWinMLEvaluationContextUnsafe)', + ' assert.equal(safeBarrel.IAudioClient, audio.IAudioClient)', + ' assert.equal(safeBarrel.IMDSPDeviceControl, mdspDeviceControl.IMDSPDeviceControl)', + ' assert.equal(safeBarrel.IWMDMDeviceControl, wmdmDeviceControl.IWMDMDeviceControl)', ' assert.equal(safeBarrel.IWbemServices, wbem.IWbemServices)', ' assert.equal(safeBarrel.IDataObject, dataObject.IDataObject)', ' assert.equal(safeBarrel.IOleCache, oleCache.IOleCache)', @@ -165,6 +183,8 @@ test.serial('generated safe WMI and unsafe Audio companions preserve exact contr ' assert.equal(esmWbemClassObject.IWbemClassObjectUnsafe, wbemClassObject.IWbemClassObjectUnsafe)', ' assert.equal(esmThumbnail.IThumbnailProvider, thumbnail.IThumbnailProvider)', ' assert.equal(esmSafeBarrel.IWbemServices, wbem.IWbemServices)', + ' assert.equal(esmSafeBarrel.IMDSPDeviceControl, mdspDeviceControl.IMDSPDeviceControl)', + ' assert.equal(esmSafeBarrel.IWMDMDeviceControl, wmdmDeviceControl.IWMDMDeviceControl)', ' assert.equal(esmSafeBarrel.IOleCache, oleCache.IOleCache)', ' assert.equal(esmSafeBarrel.IOleCache2, oleCache2.IOleCache2)', ' assert.equal(esmBarrel.UnsafePointerOutput, UnsafePointerOutput)', @@ -351,6 +371,94 @@ test.serial('generated safe WMI and unsafe Audio companions preserve exact contr ' dataObjectWrapper?.release()', ' dataObjectFake?.release()', ' }', + ' const deviceControlFixtures = [', + " [mdspDeviceControl.IMDSPDeviceControl, runtime.createGeneratedMdspDeviceControlFake, runtime.generatedMdspDeviceControlStats, '1dcb3a04-33ed-11d3-8470-00c04f79dbc0'],", + " [wmdmDeviceControl.IWMDMDeviceControl, runtime.createGeneratedWmdmDeviceControlFake, runtime.generatedWmdmDeviceControlStats, '1dcb3a14-33ed-11d3-8470-00c04f79dbc0'],", + ' ]', + ' for (const [DeviceControl, createControl, controlStats, unrelatedIid] of deviceControlFixtures) {', + " assert.equal(typeof createControl, 'function')", + " assert.equal(typeof controlStats, 'function')", + ' let controlFake = createControl()', + ' let controlUnknown', + ' let controlWrapper', + ' try {', + ' assert.equal(controlStats().currentRefCount, 1)', + ' assert.throws(() => controlFake.cast(WinGuid.parse(unrelatedIid)), /interface|0x80004002/i)', + ' assert.equal(controlStats().currentRefCount, 1)', + " controlUnknown = controlFake.cast(WinGuid.parse('00000000-0000-0000-c000-000000000046'))", + ' assert.equal(controlStats().currentRefCount, 2)', + ' controlUnknown.release()', + ' controlUnknown = undefined', + ' assert.equal(controlStats().currentRefCount, 1)', + ' controlWrapper = DeviceControl._fromNative(controlFake)', + ' assert.equal(controlStats().currentRefCount, 2)', + ' const pcm = DynComAudioFormat.pcm(2, 48000, 16)', + ' const originalPcm = pcm.toBuffer()', + ' assert.equal(controlWrapper.record(null), undefined)', + ' const afterDefault = controlStats()', + ' assert.deepEqual([afterDefault.recordCalls, afterDefault.nullFormatCalls, afterDefault.explicitFormatCalls, afterDefault.currentRefCount], [1, 1, 0, 2])', + ' assert.deepEqual(pcm.toBuffer(), originalPcm)', + ' assert.equal(controlWrapper.record(pcm), undefined)', + ' const afterExplicit = controlStats()', + ' assert.deepEqual([afterExplicit.recordCalls, afterExplicit.nullFormatCalls, afterExplicit.explicitFormatCalls, afterExplicit.currentRefCount], [2, 1, 1, 2])', + ' assert.deepEqual(pcm.toBuffer(), originalPcm)', + ' controlWrapper.release()', + ' controlWrapper = undefined', + ' assert.equal(controlStats().currentRefCount, 1)', + ' controlFake.release()', + ' controlFake = undefined', + ' const released = controlStats()', + ' assert.equal(released.currentRefCount, 0)', + ' assert.equal(released.releaseCalls, released.addRefCalls + 1)', + ' } finally {', + ' controlWrapper?.release()', + ' controlUnknown?.release()', + ' controlFake?.release()', + ' }', + ' }', + ' const createSafeAudio = runtime.createGeneratedAudioClientFake', + ' const safeAudioStats = runtime.generatedAudioClientStats', + ' const setFormatSupportMode = runtime.setGeneratedAudioClientFormatSupportMode', + ' const setSafeAudioServiceMode = runtime.setGeneratedAudioClientGetServiceMode', + ' let safeAudioFake = createSafeAudio()', + ' let safeAudioWrapper', + ' try {', + ' safeAudioWrapper = audio.IAudioClient._fromNative(safeAudioFake)', + ' const pcm = DynComAudioFormat.pcm(2, 48000, 16)', + ' safeAudioWrapper.initialize(0, 0, 0n, 0n, pcm, null)', + ' setFormatSupportMode(0)', + ' assert.deepEqual(safeAudioWrapper.isFormatSupported(0, pcm), [0, null])', + ' setFormatSupportMode(1)', + ' const [closestStatus, closestFormat] = safeAudioWrapper.isFormatSupported(0, pcm)', + ' assert.equal(closestStatus, 1)', + ' assert.equal(closestFormat.channels, 1)', + ' assert.equal(closestFormat.samplesPerSecond, 44100)', + " assert.throws(() => safeAudioWrapper.isFormatSupported(1, pcm), /native call failed|HRESULT|0x88890008/i)", + ' setFormatSupportMode(-1)', + " assert.throws(() => safeAudioWrapper.isFormatSupported(0, pcm), /native call failed|HRESULT|0x80004005/i)", + ' const mix = safeAudioWrapper.getMixFormat()', + ' assert.equal(mix.channels, 2)', + ' assert.equal(mix.samplesPerSecond, 48000)', + ' setSafeAudioServiceMode(0)', + " const service = safeAudioWrapper.getService('1cb9ad4c-dbfa-4c32-b178-c2f568a703b2')", + ' service.release()', + ' assert.equal(safeAudioStats().initializeCalls, 1)', + ' assert.equal(safeAudioStats().isFormatSupportedCalls, 4)', + ' assert.equal(safeAudioStats().getMixFormatCalls, 1)', + ' assert.equal(safeAudioStats().getServiceCalls, 1)', + ' assert.equal(safeAudioStats().currentRefCount, 2)', + ' safeAudioWrapper.release()', + ' safeAudioFake.release()', + ' assert.equal(safeAudioStats().currentRefCount, 0)', + ' safeAudioWrapper = undefined', + ' safeAudioFake = undefined', + ' } finally {', + ' safeAudioWrapper?.release()', + ' safeAudioFake?.release()', + ' }', + ' const createAudio = runtime.createGeneratedEvaluationContextFake', + ' const audioStats = runtime.generatedEvaluationContextStats', + ' const setServiceMode = runtime.setGeneratedEvaluationContextOutputMode', ' const createOleCache = runtime.createGeneratedOleCacheFake', ' const oleCacheStats = runtime.generatedOleCacheStats', " assert.equal(typeof createOleCache, 'function')", @@ -395,9 +503,6 @@ test.serial('generated safe WMI and unsafe Audio companions preserve exact contr ' oleCacheUnknown?.release()', ' oleCacheFake?.release()', ' }', - ' const createAudio = runtime.createGeneratedAudioClientFake', - ' const audioStats = runtime.generatedAudioClientStats', - ' const setServiceMode = runtime.setGeneratedAudioClientGetServiceMode', ' const createCleanupResource = runtime.createGeneratedNativeCleanupResource', " assert.equal(typeof createAudio, 'function')", " assert.equal(typeof createCleanupResource, 'function')", @@ -411,7 +516,7 @@ test.serial('generated safe WMI and unsafe Audio companions preserve exact contr ' let audioFake = createAudio()', ' let audioWrapper', ' try {', - ' audioWrapper = audio.IAudioClientUnsafe.from(audioFake)', + ' audioWrapper = evaluation.IWinMLEvaluationContextUnsafe.from(audioFake)', ' const format = DynComRawMemory.allocate(22, 2)', ' format.writeU16(0, 1)', " const inPointeeContract = Object.freeze({ direction: 'in', nullable: false, pointeeLayouts: Object.freeze({ x64: null, i686: null, arm64: null }) })", @@ -420,11 +525,11 @@ test.serial('generated safe WMI and unsafe Audio companions preserve exact contr " const unknownWritablePointeeContract = Object.freeze({ direction: 'inout', nullable: false, pointeeLayouts: Object.freeze({ x64: null, i686: null, arm64: null }) })", " const nullableWritablePointeeContract = Object.freeze({ direction: 'out', nullable: true, pointeeLayouts: Object.freeze({ x64: null, i686: null, arm64: null }) })", " assert.throws(() => UnsafePointerOutput.comOwned({}), /WinGUID|convert|class/i)", - " assert.throws(() => UnsafePointerOutput.comOwned(new Proxy(audio.IAudioClientUnsafe.iid, {})), /WinGUID|convert|class/i)", + " assert.throws(() => UnsafePointerOutput.comOwned(new Proxy(evaluation.IWinMLEvaluationContextUnsafe.iid, {})), /WinGUID|convert|class/i)", ' const invalidReplacementOwner = DynComRawOwnedComPointer.addRef(audioFake)', " assert.throws(() => UnsafeInterfaceReplacement.unchanged(invalidReplacementOwner, {}), /WinGUID|convert|class/i)", ' invalidReplacementOwner.release()', - ' assert.equal(audioStats().isFormatSupportedCalls, 0)', + ' assert.equal(audioStats().getValueCalls, 0)', ' const hardened = UnsafePointerOutput.coTaskMem()', " const opaqueRecord = __prepareStrategy(UnsafePointee.required(format), 'UnsafePointee', 'opaque', inPointeeContract)", ' assert.equal(Object.isFrozen(opaqueRecord), true)', @@ -441,20 +546,20 @@ test.serial('generated safe WMI and unsafe Audio companions preserve exact contr ' assert.throws(() => { UnsafePointerOutput.prototype.prepare = () => null }, TypeError)', ' class ForgedOutput extends UnsafePointerOutput {}', ' assert.equal(Object.getPrototypeOf(ForgedOutput.coTaskMem()), UnsafePointerOutput.prototype)', - ' assert.throws(() => audioWrapper.isFormatSupported(1, UnsafePointee.required(format), new Proxy(hardened, {})), /exact generated UnsafePointerOutput/)', - ' assert.throws(() => audioWrapper.isFormatSupported(1, UnsafePointee.required(format), {}), /exact generated UnsafePointerOutput/)', - ' assert.equal(audioStats().isFormatSupportedCalls, 0)', - ' assert.throws(() => audioWrapper.isFormatSupported(1, UnsafePointee.required(DynComRawPointer.null()), UnsafePointerOutput.coTaskMem()), /non-null/)', - ' assert.throws(() => audioWrapper.isFormatSupported(1, UnsafePointee.required(null), UnsafePointerOutput.coTaskMem()), /non-null/)', + ' assert.throws(() => audioWrapper.getValueByName(format, new Proxy(hardened, {})), /exact generated UnsafePointerOutput/)', + ' assert.throws(() => audioWrapper.getValueByName(format, {}), /exact generated UnsafePointerOutput/)', + ' assert.equal(audioStats().getValueCalls, 0)', + ' assert.throws(() => audioWrapper.bindValue(UnsafePointee.required(DynComRawPointer.null())), /non-null/)', + ' assert.throws(() => audioWrapper.bindValue(UnsafePointee.required(null)), /non-null/)', ' const releasedFormat = DynComRawMemory.allocate(22, 2)', ' releasedFormat.release()', - ' assert.throws(() => audioWrapper.isFormatSupported(1, UnsafePointee.required(releasedFormat), UnsafePointerOutput.coTaskMem()), /released/)', + ' assert.throws(() => audioWrapper.bindValue(UnsafePointee.required(releasedFormat)), /released/)', ' const releasedSlot = DynComRawMemory.allocate(DynComRaw.pointerSize(), DynComRaw.pointerSize())', ' const releasedOutput = UnsafePointerOutput.coTaskMem(releasedSlot)', ' releasedSlot.release()', - ' assert.throws(() => audioWrapper.isFormatSupported(1, UnsafePointee.required(format), releasedOutput), /released/)', + ' assert.throws(() => audioWrapper.getValueByName(format, releasedOutput), /released/)', ' assert.throws(() => DynComRawMemory.fromUnsafeAddress(0n, 8, 1), /non-null/)', - ' assert.equal(audioStats().isFormatSupportedCalls, 0)', + ' assert.equal(audioStats().getValueCalls, 0)', ' const spanBase = DynComRawMemory.allocate(DynComRaw.pointerSize() * 2, DynComRaw.pointerSize())', ' const spanA = DynComRawMemory.fromUnsafePointer(spanBase.pointer(), DynComRaw.pointerSize(), DynComRaw.pointerSize())', ' const spanB = DynComRawMemory.fromUnsafePointer(spanBase.pointer(Math.floor(DynComRaw.pointerSize() / 2)), DynComRaw.pointerSize(), 1)', @@ -470,7 +575,7 @@ test.serial('generated safe WMI and unsafe Audio companions preserve exact contr " const partialExactSpan = __prepareStrategy(UnsafeCountedBuffer.required(spanB), 'UnsafeCountedBuffer', 'partialExactSpan')", ' assert.throws(() => __validateStrategySpans([exactSpan, partialExactSpan]), /overlap/)', ' for (const [kind, factory] of [', - " ['UnsafePointerOutput', slot => UnsafePointerOutput.comOwned(audio.IAudioClientUnsafe.iid, slot)],", + " ['UnsafePointerOutput', slot => UnsafePointerOutput.comOwned(evaluation.IWinMLEvaluationContextUnsafe.iid, slot)],", " ['UnsafePointerOutput', slot => UnsafePointerOutput.coTaskMem(slot)],", " ['UnsafePointerOutput', slot => UnsafePointerOutput.bstr(slot)],", " ['UnsafePointerOutput', slot => UnsafePointerOutput.localAlloc(slot)],", @@ -520,7 +625,7 @@ test.serial('generated safe WMI and unsafe Audio companions preserve exact contr " assert.ok(__strategyArgument(__prepareStrategy(UnsafePointee.nullable(DynComRawPointer.null()), 'UnsafePointee', 'nullableRawWritablePointee', nullableWritablePointeeContract)))", ' const replacementOwner = DynComRawOwnedComPointer.addRef(audioFake)', ' const replacementSlot = DynComRawMemory.fromUnsafePointer(spanBase.pointer(), DynComRaw.pointerSize(), 1)', - " const replacementRecord = __prepareStrategy(UnsafeInterfaceReplacement.unchanged(replacementOwner, audio.IAudioClientUnsafe.iid, replacementSlot), 'UnsafeInterfaceReplacement', 'replacementSpan')", + " const replacementRecord = __prepareStrategy(UnsafeInterfaceReplacement.unchanged(replacementOwner, evaluation.IWinMLEvaluationContextUnsafe.iid, replacementSlot), 'UnsafeInterfaceReplacement', 'replacementSpan')", ' assert.throws(() => __validateStrategySpans([exactSpan, replacementRecord]), /overlap/)', " const replacementOutput = __prepareStrategy(UnsafePointerOutput.rawResponsibility(replacementSlot), 'UnsafePointerOutput', 'replacementOutput')", ' assert.throws(() => __validateStrategySpans([replacementRecord, replacementOutput]), /overlap/)', @@ -543,76 +648,74 @@ test.serial('generated safe WMI and unsafe Audio companions preserve exact contr ' assert.equal(finishError.unsafeOutputs.length, 3)', ' for (const slot of finishSlots) slot.release()', ' }', - ' assert.equal(audioStats().isFormatSupportedCalls, 0)', + ' assert.equal(audioStats().getValueCalls, 0)', ' const closest = UnsafePointerOutput.coTaskMem()', - ' const formatResult = audioWrapper.isFormatSupported(1, UnsafePointee.required(format), closest)', - ' assert.equal(formatResult[0], 1)', - ' assert.equal(audioStats().isFormatSupportedCalls, 1)', - ' assert.equal(audioStats().lastShareMode, 1)', - ' assert.equal(audioStats().lastFormatTag, 1)', - ' const closestOwner = formatResult[1]', + ' setServiceMode(6)', + ' const closestOwner = audioWrapper.getValueByName(format, closest)', + ' assert.equal(audioStats().getValueCalls, 1)', ' const closestView = closestOwner.view(16, 4)', ' assert.equal(closestView.readU32(0), 0xaabbccdd)', ' closestView.release()', ' assert.equal(__testRunOwnedFinalizer(closestOwner), true)', ' assert.equal(__testRunOwnedFinalizer(closestOwner), true)', ' assert.throws(() => closestOwner.view(16, 4), /released/)', - ' assert.throws(() => audioWrapper.isFormatSupported(2, UnsafePointee.required(format), UnsafePointerOutput.coTaskMem()), /native call failed|HRESULT|0x80004005/i)', - ' assert.equal(audioStats().isFormatSupportedCalls, 2)', - ' assert.throws(() => audioWrapper.isFormatSupported(1, UnsafePointee.required(format), closest), /finished/)', - ' assert.equal(audioStats().isFormatSupportedCalls, 2)', - ' assert.throws(() => audioWrapper.isFormatSupported(1, UnsafePointee.required(format), UnsafePointee.required(format)), /UnsafePointerOutput/)', - ' assert.equal(audioStats().isFormatSupportedCalls, 2)', + ' setServiceMode(-6)', + ' assert.throws(() => audioWrapper.getValueByName(format, UnsafePointerOutput.coTaskMem()), /native call failed|HRESULT|0x80004005/i)', + ' assert.equal(audioStats().getValueCalls, 2)', + ' assert.throws(() => audioWrapper.getValueByName(format, closest), /finished/)', + ' assert.equal(audioStats().getValueCalls, 2)', + ' assert.throws(() => audioWrapper.getValueByName(format, UnsafePointee.required(format)), /UnsafePointerOutput/)', + ' assert.equal(audioStats().getValueCalls, 2)', ' const iidStorage = DynComRawMemory.allocate(16, 4)', ' setServiceMode(1)', ' const beforeFailureRefs = audioStats().currentRefCount', - ' assert.throws(() => audioWrapper.getService(iidStorage, UnsafePointerOutput.comOwned(audio.IAudioClientUnsafe.iid)), /native call failed|HRESULT|0x80004005/i)', - ' assert.equal(audioStats().getServiceCalls, 1)', + ' assert.throws(() => audioWrapper.getValueByName(iidStorage, UnsafePointerOutput.comOwned(evaluation.IWinMLEvaluationContextUnsafe.iid)), /native call failed|HRESULT|0x80004005/i)', + ' assert.equal(audioStats().getValueCalls, 3)', ' assert.equal(audioStats().currentRefCount, beforeFailureRefs)', ' const rawFailure = UnsafePointerOutput.rawResponsibility()', ' let rawFailureError', - ' try { audioWrapper.getService(iidStorage, rawFailure) } catch (error) { rawFailureError = error }', + ' try { audioWrapper.getValueByName(iidStorage, rawFailure) } catch (error) { rawFailureError = error }', ' assert.equal(rawFailureError.unsafeOutputs.length, 1)', ' const dirtyPointer = rawFailure.takeFailurePointer()', ' assert.equal(dirtyPointer.address, rawFailureError.unsafeOutputs[0].pointer.address)', ' assert.throws(() => rawFailure.takeFailurePointer(), /No raw failure pointer/)', - ' DynComRawOwnedComPointer.assumeTransferred(dirtyPointer, audio.IAudioClientUnsafe.iid).release()', + ' DynComRawOwnedComPointer.assumeTransferred(dirtyPointer, evaluation.IWinMLEvaluationContextUnsafe.iid).release()', ' assert.equal(audioStats().currentRefCount, beforeFailureRefs)', ' setServiceMode(-2)', ' const nullFailure = UnsafePointerOutput.rawResponsibility()', ' let nullFailureError', - ' try { audioWrapper.getService(iidStorage, nullFailure) } catch (error) { nullFailureError = error }', + ' try { audioWrapper.getValueByName(iidStorage, nullFailure) } catch (error) { nullFailureError = error }', ' assert.equal(nullFailureError.unsafeOutputs[0].pointer.isNull, true)', ' assert.equal(nullFailure.takeFailurePointer().isNull, true)', ' assert.throws(() => nullFailure.takeFailurePointer(), /No raw failure pointer/)', ' setServiceMode(0)', - ' const managedService = audioWrapper.getService(iidStorage, UnsafePointerOutput.comOwned(audio.IAudioClientUnsafe.iid))', + ' const managedService = audioWrapper.getValueByName(iidStorage, UnsafePointerOutput.comOwned(evaluation.IWinMLEvaluationContextUnsafe.iid))', ' assert.equal(audioStats().currentRefCount, beforeFailureRefs + 1)', ' managedService.release()', ' assert.equal(audioStats().currentRefCount, beforeFailureRefs)', " const wrongIid = WinGuid.parse('aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee')", - ' assert.throws(() => audioWrapper.getService(iidStorage, UnsafePointerOutput.comOwned(wrongIid)), /interface|0x80004002/i)', + ' assert.throws(() => audioWrapper.getValueByName(iidStorage, UnsafePointerOutput.comOwned(wrongIid)), /interface|0x80004002/i)', ' assert.equal(audioStats().currentRefCount, beforeFailureRefs)', ' setServiceMode(2)', - ' assert.throws(() => audioWrapper.getService(iidStorage, UnsafePointerOutput.comOwned(audio.IAudioClientUnsafe.iid)), /Required pointer output was null/)', - ' const nullable = audioWrapper.getService(iidStorage, UnsafePointerOutput.comOwned(audio.IAudioClientUnsafe.iid, null, true))', + ' assert.throws(() => audioWrapper.getValueByName(iidStorage, UnsafePointerOutput.comOwned(evaluation.IWinMLEvaluationContextUnsafe.iid)), /Required pointer output was null/)', + ' const nullable = audioWrapper.getValueByName(iidStorage, UnsafePointerOutput.comOwned(evaluation.IWinMLEvaluationContextUnsafe.iid, null, true))', ' assert.equal(nullable, null)', ' setServiceMode(3)', - ' assert.equal(__testRunOwnedFinalizer(audioWrapper.getService(iidStorage, UnsafePointerOutput.bstr())), true)', + ' assert.equal(__testRunOwnedFinalizer(audioWrapper.getValueByName(iidStorage, UnsafePointerOutput.bstr())), true)', ' setServiceMode(-3)', - ' assert.throws(() => audioWrapper.getService(iidStorage, UnsafePointerOutput.bstr()), /native call failed|HRESULT|0x80004005/i)', + ' assert.throws(() => audioWrapper.getValueByName(iidStorage, UnsafePointerOutput.bstr()), /native call failed|HRESULT|0x80004005/i)', ' setServiceMode(4)', - ' assert.equal(__testRunOwnedFinalizer(audioWrapper.getService(iidStorage, UnsafePointerOutput.localAlloc())), true)', + ' assert.equal(__testRunOwnedFinalizer(audioWrapper.getValueByName(iidStorage, UnsafePointerOutput.localAlloc())), true)', ' setServiceMode(-4)', - ' assert.throws(() => audioWrapper.getService(iidStorage, UnsafePointerOutput.localAlloc()), /native call failed|HRESULT|0x80004005/i)', + ' assert.throws(() => audioWrapper.getValueByName(iidStorage, UnsafePointerOutput.localAlloc()), /native call failed|HRESULT|0x80004005/i)', ' setServiceMode(5)', - ' assert.equal(__testRunOwnedFinalizer(audioWrapper.getService(iidStorage, UnsafePointerOutput.globalAlloc())), true)', + ' assert.equal(__testRunOwnedFinalizer(audioWrapper.getValueByName(iidStorage, UnsafePointerOutput.globalAlloc())), true)', ' setServiceMode(-5)', - ' assert.throws(() => audioWrapper.getService(iidStorage, UnsafePointerOutput.globalAlloc()), /native call failed|HRESULT|0x80004005/i)', + ' assert.throws(() => audioWrapper.getValueByName(iidStorage, UnsafePointerOutput.globalAlloc()), /native call failed|HRESULT|0x80004005/i)', ' setServiceMode(2)', - ' assert.equal(audioWrapper.getService(iidStorage, UnsafePointerOutput.borrowed(null, true)), null)', - ' assert.equal(audioWrapper.getService(iidStorage, UnsafePointerOutput.unclassified(null, true)), null)', - ' assert.equal(audioWrapper.getService(iidStorage, UnsafePointerOutput.rawResponsibility(null, true)), null)', + ' assert.equal(audioWrapper.getValueByName(iidStorage, UnsafePointerOutput.borrowed(null, true)), null)', + ' assert.equal(audioWrapper.getValueByName(iidStorage, UnsafePointerOutput.unclassified(null, true)), null)', + ' assert.equal(audioWrapper.getValueByName(iidStorage, UnsafePointerOutput.rawResponsibility(null, true)), null)', ' const rawSlot = DynComRawMemory.allocate(DynComRaw.pointerSize(), DynComRaw.pointerSize())', ' const handle = UnsafeHandleOutput.rawResponsibility(rawSlot)', " const handleRecord = __prepareStrategy(handle, 'UnsafeHandleOutput', 'handle')", @@ -639,7 +742,7 @@ test.serial('generated safe WMI and unsafe Audio companions preserve exact contr ' nativeSlot.release()', ' }', ' const owner = DynComRawOwnedComPointer.addRef(audioFake)', - ' const unchanged = UnsafeInterfaceReplacement.unchanged(owner, audio.IAudioClientUnsafe.iid)', + ' const unchanged = UnsafeInterfaceReplacement.unchanged(owner, evaluation.IWinMLEvaluationContextUnsafe.iid)', " const unchangedRecord = __prepareStrategy(unchanged, 'UnsafeInterfaceReplacement', 'unchanged')", ' __activateStrategies([unchangedRecord])', ' const unchangedResult = __finishStrategy(unchangedRecord)', @@ -648,7 +751,7 @@ test.serial('generated safe WMI and unsafe Audio companions preserve exact contr ' unchangedResult.release()', " assert.throws(() => __prepareStrategy(unchanged, 'UnsafeInterfaceReplacement', 'unchanged'), /finished/)", ' const preservesOwner = DynComRawOwnedComPointer.addRef(audioFake)', - ' const preserves = UnsafeInterfaceReplacement.preservesOld(preservesOwner, audio.IAudioClientUnsafe.iid)', + ' const preserves = UnsafeInterfaceReplacement.preservesOld(preservesOwner, evaluation.IWinMLEvaluationContextUnsafe.iid)', " const preservesRecord = __prepareStrategy(preserves, 'UnsafeInterfaceReplacement', 'preserves')", ' __activateStrategies([preservesRecord])', ' const preservesResult = __finishStrategy(preservesRecord)', @@ -656,7 +759,7 @@ test.serial('generated safe WMI and unsafe Audio companions preserve exact contr ' assert.equal(preservesResult.current, preservesOwner)', ' preservesResult.release()', ' const reentrantOwner = DynComRawOwnedComPointer.addRef(audioFake)', - ' const reentrant = UnsafeInterfaceReplacement.preservesOld(reentrantOwner, audio.IAudioClientUnsafe.iid)', + ' const reentrant = UnsafeInterfaceReplacement.preservesOld(reentrantOwner, evaluation.IWinMLEvaluationContextUnsafe.iid)', " const reentrantRecord = __prepareStrategy(reentrant, 'UnsafeInterfaceReplacement', 'reentrant')", ' __activateStrategies([reentrantRecord])', ' reentrantOwner.release()', @@ -666,7 +769,7 @@ test.serial('generated safe WMI and unsafe Audio companions preserve exact contr ' assert.equal(reentrantResult.current, reentrantResult.previous)', ' reentrantResult.release()', ' const consumesOwner = DynComRawOwnedComPointer.addRef(audioFake)', - ' const consumes = UnsafeInterfaceReplacement.consumesOld(consumesOwner, audio.IAudioClientUnsafe.iid)', + ' const consumes = UnsafeInterfaceReplacement.consumesOld(consumesOwner, evaluation.IWinMLEvaluationContextUnsafe.iid)', " const consumesRecord = __prepareStrategy(consumes, 'UnsafeInterfaceReplacement', 'consumes')", ' __activateStrategies([consumesRecord])', ' const consumesResult = __finishStrategy(consumesRecord)', @@ -674,7 +777,7 @@ test.serial('generated safe WMI and unsafe Audio companions preserve exact contr ' assert.ok(consumesResult.current)', ' consumesResult.release()', ' const preDispatchOwner = DynComRawOwnedComPointer.addRef(audioFake)', - ' const preDispatchReplacement = UnsafeInterfaceReplacement.consumesOld(preDispatchOwner, audio.IAudioClientUnsafe.iid)', + ' const preDispatchReplacement = UnsafeInterfaceReplacement.consumesOld(preDispatchOwner, evaluation.IWinMLEvaluationContextUnsafe.iid)', " const preDispatchRecord = __prepareStrategy(preDispatchReplacement, 'UnsafeInterfaceReplacement', 'preDispatch')", ' __activateStrategies([preDispatchRecord])', ' __markDispatchEntered([preDispatchRecord], DynComRaw.__createDispatchState())', @@ -684,12 +787,12 @@ test.serial('generated safe WMI and unsafe Audio companions preserve exact contr ' const preDispatchResult = __finishStrategy(preDispatchRetry)', ' preDispatchResult.release()', " const replacementFactories = [UnsafeInterfaceReplacement.consumesOld, UnsafeInterfaceReplacement.preservesOld, UnsafeInterfaceReplacement.unchanged]", - ' const aliasCallCount = audioStats().isFormatSupportedCalls', + ' const aliasCallCount = audioStats().getValueCalls', ' for (let first = 0; first < replacementFactories.length; first++) {', ' for (let second = first; second < replacementFactories.length; second++) {', ' const sharedOwner = DynComRawOwnedComPointer.addRef(audioFake)', ' const slots = [0, 1].map(() => DynComRawMemory.allocate(DynComRaw.pointerSize(), DynComRaw.pointerSize()))', - " const records = [first, second].map((mode, index) => __prepareStrategy(replacementFactories[mode](sharedOwner, audio.IAudioClientUnsafe.iid, slots[index]), 'UnsafeInterfaceReplacement', `pair${first}${second}${index}`))", + " const records = [first, second].map((mode, index) => __prepareStrategy(replacementFactories[mode](sharedOwner, evaluation.IWinMLEvaluationContextUnsafe.iid, slots[index]), 'UnsafeInterfaceReplacement', `pair${first}${second}${index}`))", ' assert.throws(() => __validateStrategySpans(records), /owner is used by multiple/)', ' assert.ok(sharedOwner.address > 0n)', ' sharedOwner.release()', @@ -701,7 +804,7 @@ test.serial('generated safe WMI and unsafe Audio companions preserve exact contr ' for (let third = second; third < replacementFactories.length; third++) {', ' const sharedOwner = DynComRawOwnedComPointer.addRef(audioFake)', ' const slots = [0, 1, 2].map(() => DynComRawMemory.allocate(DynComRaw.pointerSize(), DynComRaw.pointerSize()))', - " const records = [first, second, third].map((mode, index) => __prepareStrategy(replacementFactories[mode](sharedOwner, audio.IAudioClientUnsafe.iid, slots[index]), 'UnsafeInterfaceReplacement', `triple${first}${second}${third}${index}`))", + " const records = [first, second, third].map((mode, index) => __prepareStrategy(replacementFactories[mode](sharedOwner, evaluation.IWinMLEvaluationContextUnsafe.iid, slots[index]), 'UnsafeInterfaceReplacement', `triple${first}${second}${third}${index}`))", ' assert.throws(() => __validateStrategySpans(records), /owner is used by multiple/)', ' assert.ok(sharedOwner.address > 0n)', ' sharedOwner.release()', @@ -711,19 +814,19 @@ test.serial('generated safe WMI and unsafe Audio companions preserve exact contr ' }', ' const independentOwners = [0, 1, 2].map(() => DynComRawOwnedComPointer.addRef(audioFake))', ' const independentSlots = [0, 1, 2].map(() => DynComRawMemory.allocate(DynComRaw.pointerSize(), DynComRaw.pointerSize()))', - " const independentRecords = replacementFactories.map((factory, index) => __prepareStrategy(factory(independentOwners[index], audio.IAudioClientUnsafe.iid, independentSlots[index]), 'UnsafeInterfaceReplacement', `independent${index}`))", + " const independentRecords = replacementFactories.map((factory, index) => __prepareStrategy(factory(independentOwners[index], evaluation.IWinMLEvaluationContextUnsafe.iid, independentSlots[index]), 'UnsafeInterfaceReplacement', `independent${index}`))", ' __validateStrategySpans(independentRecords)', ' __activateStrategies(independentRecords)', ' const independentResults = independentRecords.map(record => __finishStrategy(record))', ' for (const result of independentResults) result.release()', ' for (const slot of independentSlots) slot.release()', - ' assert.equal(audioStats().isFormatSupportedCalls, aliasCallCount)', + ' assert.equal(audioStats().getValueCalls, aliasCallCount)', ' const rollbackOwnerA = DynComRawOwnedComPointer.addRef(audioFake)', ' const rollbackOwnerB = DynComRawOwnedComPointer.addRef(audioFake)', ' const rollbackSlotA = DynComRawMemory.allocate(DynComRaw.pointerSize(), DynComRaw.pointerSize())', ' const rollbackSlotB = DynComRawMemory.allocate(DynComRaw.pointerSize(), DynComRaw.pointerSize())', - ' const rollbackA = UnsafeInterfaceReplacement.consumesOld(rollbackOwnerA, audio.IAudioClientUnsafe.iid, rollbackSlotA)', - ' const rollbackB = UnsafeInterfaceReplacement.consumesOld(rollbackOwnerB, audio.IAudioClientUnsafe.iid, rollbackSlotB)', + ' const rollbackA = UnsafeInterfaceReplacement.consumesOld(rollbackOwnerA, evaluation.IWinMLEvaluationContextUnsafe.iid, rollbackSlotA)', + ' const rollbackB = UnsafeInterfaceReplacement.consumesOld(rollbackOwnerB, evaluation.IWinMLEvaluationContextUnsafe.iid, rollbackSlotB)', " const rollbackRecordA = __prepareStrategy(rollbackA, 'UnsafeInterfaceReplacement', 'rollbackA')", " const rollbackRecordB = __prepareStrategy(rollbackB, 'UnsafeInterfaceReplacement', 'rollbackB')", ' __validateStrategySpans([rollbackRecordA, rollbackRecordB])', @@ -795,18 +898,23 @@ test.serial('generated safe WMI and unsafe Audio companions preserve exact contr "import { IOleCache } from './com/windows/win32/system/ole/IOleCache.js'", "import { IOleCache2 } from './com/windows/win32/system/ole/IOleCache2.js'", "import { IThumbnailProvider } from './com/windows/win32/ui/shell/IThumbnailProvider.js'", - "import { IAudioClientUnsafe } from './com/unsafe/windows/win32/media/audio/IAudioClientUnsafe.js'", + "import { IAudioClient } from './com/windows/win32/media/audio/IAudioClient.js'", + "import { IMDSPDeviceControl } from './com/windows/win32/media/device-manager/IMDSPDeviceControl.js'", + "import { IWMDMDeviceControl } from './com/windows/win32/media/device-manager/IWMDMDeviceControl.js'", + "import { IWinMLEvaluationContextUnsafe } from './com/unsafe/windows/win32/ai/machine-learning/win-ml/IWinMLEvaluationContextUnsafe.js'", "import { IWbemServices as FromBarrel } from './com/index.js'", "import { UnsafePointee, UnsafePointerOutput } from './com/unsafe/runtime.js'", "import type { UnsafeOwnedPointer } from './com/unsafe/runtime.js'", "import type { DynComRawMemory, DynWinRtValue } from '@microsoft/dynwinrt/com/unsafe/raw'", - "import { DynComFormatEtc, DynComStgMedium } from '@microsoft/dynwinrt/com'", + "import { DynComAudioFormat, DynComFormatEtc, DynComStgMedium } from '@microsoft/dynwinrt/com'", 'declare const native: DynWinRtValue', 'declare const storage: DynComRawMemory', 'declare const thumbnails: IThumbnailProvider', 'declare const dataObjects: IDataObject', 'declare const oleCaches: IOleCache', 'declare const oleCaches2: IOleCache2', + 'declare const mdspControl: IMDSPDeviceControl', + 'declare const wmdmControl: IWMDMDeviceControl', 'const direct: IWbemServices = IWbemServices._fromNative(native)', 'const barrel: FromBarrel = FromBarrel._fromNative(native)', "const namespaceOutput = direct.openNamespace('root', { mode: 'sync' })", @@ -825,6 +933,28 @@ test.serial('generated safe WMI and unsafe Audio companions preserve exact contr 'dataObjects.setData(format, DynComStgMedium.hglobal(Buffer.from([1])))', '// @ts-expect-error SetData ownership transfer is intentionally hidden', 'dataObjects.setData(format, DynComStgMedium.hglobal(Buffer.from([1])), true)', + 'const audio = IAudioClient._fromNative(native)', + 'audio.isFormatSupported(0, DynComAudioFormat.pcm(2, 48_000, 16))', + '// @ts-expect-error IsFormatSupported still requires an explicit audio format', + 'audio.isFormatSupported(0, null)', + 'const pcm = DynComAudioFormat.pcm(2, 48_000, 16)', + 'const mdspDefaultResult: void = mdspControl.record(null)', + 'const mdspPcmResult: void = mdspControl.record(pcm)', + 'const wmdmDefaultResult: void = wmdmControl.record(null)', + 'const wmdmPcmResult: void = wmdmControl.record(pcm)', + 'void mdspDefaultResult', + 'void mdspPcmResult', + 'void wmdmDefaultResult', + 'void wmdmPcmResult', + '// @ts-expect-error Record accepts an audio format or null, not a plain object', + 'mdspControl.record({})', + '// @ts-expect-error Record does not accept an unrelated COM format value', + 'wmdmControl.record(format)', + '// @ts-expect-error selecting the default format requires explicit null', + 'mdspControl.record()', + '// @ts-expect-error selecting the default format requires explicit null', + 'wmdmControl.record()', + 'const unsafeEvaluation = IWinMLEvaluationContextUnsafe.from(native)', 'const cacheSetResult: void = oleCaches.setData(format, DynComStgMedium.hglobal(Buffer.from([1])))', 'const cache2SetResult: void = oleCaches2.setData(format, DynComStgMedium.hglobal(Buffer.from([1])))', 'void cacheSetResult', @@ -833,13 +963,14 @@ test.serial('generated safe WMI and unsafe Audio companions preserve exact contr 'oleCaches.setData(format, DynComStgMedium.hglobal(Buffer.from([1])), true)', '// @ts-expect-error inherited IOleCache2 SetData ownership transfer is intentionally hidden', 'oleCaches2.setData(format, DynComStgMedium.hglobal(Buffer.from([1])), true)', - 'const audio = IAudioClientUnsafe.from(native)', '// @ts-expect-error strategy result types are invariant', 'const wrongOutput: UnsafePointerOutput = UnsafePointerOutput.coTaskMem()', 'const ownedOutput: UnsafePointerOutput = UnsafePointerOutput.coTaskMem()', 'void wrongOutput', 'void ownedOutput', - 'audio.isFormatSupported(0, UnsafePointee.required(storage), UnsafePointerOutput.coTaskMem())', + 'unsafeEvaluation.bindValue(UnsafePointee.required(storage))', + 'unsafeEvaluation.getValueByName(storage, UnsafePointerOutput.coTaskMem())', + 'unsafeEvaluation.release()', 'audio.release()', 'barrel.release()', 'direct.release()', diff --git a/bindings/js/__test__/index.spec.ts b/bindings/js/__test__/index.spec.ts index bc724f88..848ef47f 100644 --- a/bindings/js/__test__/index.spec.ts +++ b/bindings/js/__test__/index.spec.ts @@ -23,7 +23,7 @@ import { unboxObject, } from '../dist/winrt.js' import * as winrtRuntime from '../dist/winrt.js' -import { DynComFormatEtc, DynComStgMedium } from '../dist/com.js' +import { DynComAudioFormat, DynComFormatEtc, DynComStgMedium } from '../dist/com.js' import * as comRuntime from '../dist/com.js' import { DynCom, @@ -149,6 +149,7 @@ test('package facades exactly partition native exports', (t) => { const safeComNames = new Set([ 'DynComDispatchParams', 'DynComAllocation', + 'DynComAudioFormat', 'DynComExcepInfo', 'DynComFormatEtc', 'DynComNativeStruct', @@ -231,6 +232,37 @@ test('FORMATETC and STGMEDIUM expose a closed HGLOBAL semantic subset', (t) => { t.throws(() => DynComStgMedium.hglobal(Buffer.alloc(0)), { message: /at least one byte/ }) }) +test('WAVEFORMATEX values preserve validated variable-length audio formats', (t) => { + const pcm = DynComAudioFormat.pcm(2, 48_000, 16) + t.is(pcm.formatTag, 1) + t.is(pcm.channels, 2) + t.is(pcm.samplesPerSecond, 48_000) + t.is(pcm.averageBytesPerSecond, 192_000) + t.is(pcm.blockAlign, 4) + t.is(pcm.bitsPerSample, 16) + t.deepEqual(pcm.extraData, Buffer.alloc(0)) + t.is(pcm.toBuffer().length, 18) + t.deepEqual(DynComAudioFormat.fromBuffer(pcm.toBuffer()).toBuffer(), pcm.toBuffer()) + + const extensible = DynComAudioFormat.waveFormatEx( + 0xfffe, + 2, + 48_000, + 192_000, + 4, + 16, + Buffer.alloc(22), + ) + t.is(extensible.formatTag, 0xfffe) + t.is(extensible.extraData.length, 22) + t.throws(() => DynComAudioFormat.pcm(2, 48_000, 12), { message: /multiple of eight/ }) + t.throws(() => DynComAudioFormat.fromBuffer(Buffer.alloc(17)), { message: /18-byte header/ }) + t.throws( + () => DynComAudioFormat.waveFormatEx(0xfffe, 2, 48_000, 192_000, 4, 16, Buffer.alloc(21)), + { message: /22 extension bytes/ }, + ) +}) + test('raw COM memory and pointers expose checked owner-retaining primitives', (t) => { const pointerSize = DynComRaw.pointerSize() t.true(pointerSize === 4 || pointerSize === 8) diff --git a/bindings/js/scripts/generate-entrypoints.mjs b/bindings/js/scripts/generate-entrypoints.mjs index 6ec952e3..b73dedeb 100644 --- a/bindings/js/scripts/generate-entrypoints.mjs +++ b/bindings/js/scripts/generate-entrypoints.mjs @@ -19,6 +19,7 @@ if (nativeExports.length === 0) { const comExports = new Set([ 'DynComDispatchParams', 'DynComAllocation', + 'DynComAudioFormat', 'DynComExcepInfo', 'DynComFormatEtc', 'DynComNativeStruct', diff --git a/bindings/js/src/com.rs b/bindings/js/src/com.rs index 8530df0c..10951ef9 100644 --- a/bindings/js/src/com.rs +++ b/bindings/js/src/com.rs @@ -42,6 +42,7 @@ enum AutomationValueKind { StatStg(dynwinrt::com::StatStgValue), FormatEtc(dynwinrt::com::FormatEtcValue), StgMedium(dynwinrt::com::StgMediumValue), + AudioFormat(dynwinrt::com::AudioFormatValue), } pub(super) struct AutomationValue { @@ -62,6 +63,7 @@ impl AutomationValue { dynwinrt::com::Value::StatStg(value) => AutomationValueKind::StatStg(value), dynwinrt::com::Value::FormatEtc(value) => AutomationValueKind::FormatEtc(value), dynwinrt::com::Value::StgMedium(value) => AutomationValueKind::StgMedium(value), + dynwinrt::com::Value::AudioFormat(value) => AutomationValueKind::AudioFormat(value), _ => unreachable!("AutomationValue requires an automation COM value"), }; Self { @@ -101,6 +103,7 @@ impl AutomationValue { AutomationValueKind::StatStg(value) => dynwinrt::com::Value::StatStg(value.clone()), AutomationValueKind::FormatEtc(value) => dynwinrt::com::Value::FormatEtc(value.clone()), AutomationValueKind::StgMedium(value) => dynwinrt::com::Value::StgMedium(value.clone()), + AutomationValueKind::AudioFormat(value) => dynwinrt::com::Value::AudioFormat(value.clone()), }) } @@ -181,6 +184,17 @@ impl AutomationValue { } } + pub(super) fn take_audio_format(&mut self) -> napi::Result { + self.ensure_owner_thread()?; + match self.value.take() { + Some(AutomationValueKind::AudioFormat(value)) => Ok(value), + value => { + self.value = value; + Err(napi::Error::from_reason("Value is not a COM WAVEFORMATEX")) + } + } + } + pub(super) fn leak_for_shutdown(&mut self) { if let Some(value) = self.value.take() { std::mem::forget(value); @@ -3179,6 +3193,103 @@ impl DynComStgMedium { } } +#[napi] +pub struct DynComAudioFormat { + value: dynwinrt::com::AudioFormatValue, +} + +#[napi] +impl DynComAudioFormat { + #[napi(factory)] + pub fn pcm(channels: u32, samples_per_second: u32, bits_per_sample: u32) -> napi::Result { + let channels = + u16::try_from(channels).map_err(|_| napi::Error::from_reason("channels must fit in u16"))?; + let bits_per_sample = u16::try_from(bits_per_sample) + .map_err(|_| napi::Error::from_reason("bitsPerSample must fit in u16"))?; + dynwinrt::com::AudioFormatValue::pcm(channels, samples_per_second, bits_per_sample) + .map(|value| Self { value }) + .map_err(|error| napi::Error::from_reason(error.message())) + } + + #[napi(factory)] + pub fn wave_format_ex( + format_tag: u32, + channels: u32, + samples_per_second: u32, + average_bytes_per_second: u32, + block_align: u32, + bits_per_sample: u32, + extra_data: Option, + ) -> napi::Result { + let format_tag = u16::try_from(format_tag) + .map_err(|_| napi::Error::from_reason("formatTag must fit in u16"))?; + let channels = + u16::try_from(channels).map_err(|_| napi::Error::from_reason("channels must fit in u16"))?; + let block_align = u16::try_from(block_align) + .map_err(|_| napi::Error::from_reason("blockAlign must fit in u16"))?; + let bits_per_sample = u16::try_from(bits_per_sample) + .map_err(|_| napi::Error::from_reason("bitsPerSample must fit in u16"))?; + dynwinrt::com::AudioFormatValue::wave_format_ex( + format_tag, + channels, + samples_per_second, + average_bytes_per_second, + block_align, + bits_per_sample, + extra_data.map_or_else(Vec::new, |bytes| bytes.to_vec()), + ) + .map(|value| Self { value }) + .map_err(|error| napi::Error::from_reason(error.message())) + } + + #[napi(factory)] + pub fn from_buffer(bytes: Buffer) -> napi::Result { + dynwinrt::com::AudioFormatValue::from_wave_format_ex(bytes.to_vec()) + .map(|value| Self { value }) + .map_err(|error| napi::Error::from_reason(error.message())) + } + + #[napi(getter)] + pub fn format_tag(&self) -> u32 { + u32::from(self.value.format_tag()) + } + + #[napi(getter)] + pub fn channels(&self) -> u32 { + u32::from(self.value.channels()) + } + + #[napi(getter)] + pub fn samples_per_second(&self) -> u32 { + self.value.samples_per_second() + } + + #[napi(getter)] + pub fn average_bytes_per_second(&self) -> u32 { + self.value.average_bytes_per_second() + } + + #[napi(getter)] + pub fn block_align(&self) -> u32 { + u32::from(self.value.block_align()) + } + + #[napi(getter)] + pub fn bits_per_sample(&self) -> u32 { + u32::from(self.value.bits_per_sample()) + } + + #[napi(getter)] + pub fn extra_data(&self) -> Buffer { + Buffer::from(self.value.extra_data().to_vec()) + } + + #[napi] + pub fn to_buffer(&self) -> Buffer { + Buffer::from(self.value.bytes().to_vec()) + } +} + #[napi] #[derive(Debug)] pub struct DynComOwnedHandle { @@ -4922,6 +5033,11 @@ impl DynCom { DynComType(dynwinrt::com::Type::stg_medium()) } + #[napi] + pub fn audio_format_type() -> DynComType { + DynComType(dynwinrt::com::Type::audio_format()) + } + #[napi] pub fn interface_type(iid: &WinGUID) -> DynComType { DynComType(dynwinrt::com::Type::winrt(TABLE.interface(iid.0))) @@ -5770,6 +5886,22 @@ impl DynCom { ) } + #[napi] + pub fn audio_format(value: &DynComAudioFormat) -> DynWinRTValue { + DynWinRTValue::from_com_value( + dynwinrt::com::Value::AudioFormat(value.value.clone()), + dynwinrt::com::PointerOutputKind::None, + ) + } + + #[napi] + pub fn null_audio_format() -> DynWinRTValue { + DynWinRTValue::from_com_value( + dynwinrt::com::Value::WinRt(dynwinrt::WinRTValue::Null), + dynwinrt::com::PointerOutputKind::None, + ) + } + #[napi] pub fn take_variant(value: &mut DynWinRTValue) -> napi::Result { let result = value @@ -5857,6 +5989,27 @@ impl DynCom { Ok(DynComStgMedium { value: result }) } + #[napi] + pub fn take_audio_format(value: &mut DynWinRTValue) -> napi::Result { + let result = value + .5 + .as_mut() + .ok_or_else(|| napi::Error::from_reason("Value is not a COM WAVEFORMATEX"))? + .take_audio_format()?; + value.5 = None; + Ok(DynComAudioFormat { value: result }) + } + + #[napi] + pub fn take_nullable_audio_format( + value: &mut DynWinRTValue, + ) -> napi::Result> { + if value.5.is_none() && value.0.is_null_object() { + return Ok(None); + } + Self::take_audio_format(value).map(Some) + } + #[napi] pub fn take_delete_object_handle(value: &mut DynWinRTValue) -> napi::Result { take_owned_handle( diff --git a/bindings/js/src/generated_unsafe_test_hooks.rs b/bindings/js/src/generated_unsafe_test_hooks.rs index 8d468e0a..339a9ebc 100644 --- a/bindings/js/src/generated_unsafe_test_hooks.rs +++ b/bindings/js/src/generated_unsafe_test_hooks.rs @@ -8,6 +8,12 @@ use std::{ use napi::bindgen_prelude::BigInt; use napi_derive::napi; +use windows::Win32::Media::{ + Audio::WAVEFORMATEX, + DeviceManager::{ + IMDSPDeviceControl, IMDSPDeviceControl_Vtbl, IWMDMDeviceControl, IWMDMDeviceControl_Vtbl, + }, +}; use windows::{ core::{IUnknown, IUnknown_Vtbl, Interface, BOOL, GUID, HRESULT, PCWSTR}, Win32::System::{ @@ -29,6 +35,7 @@ const IID_IWBEM_CLASS_OBJECT: GUID = GUID::from_u128(0xdc12a681_737f_11cf_884d_0 const IID_ITHUMBNAIL_PROVIDER: GUID = GUID::from_u128(0xe357fccd_a995_4576_b01f_234630154e96); const IID_IDATA_OBJECT: GUID = GUID::from_u128(0x0000010e_0000_0000_c000_000000000046); const IID_IAUDIO_CLIENT: GUID = GUID::from_u128(0x1cb9ad4c_dbfa_4c32_b178_c2f568a703b2); +const IID_IWINML_EVALUATION_CONTEXT: GUID = GUID::from_u128(0x95848f9e_583d_4054_af12_916387cd8426); const E_NOINTERFACE: HRESULT = HRESULT(0x80004002u32 as i32); const E_POINTER: HRESULT = HRESULT(0x80004003u32 as i32); const E_NOTIMPL: HRESULT = HRESULT(0x80004001u32 as i32); @@ -57,13 +64,20 @@ static CLASS_OBJECT_END_ENUMERATION_CALLS: AtomicU32 = AtomicU32::new(0); static CALL_RESULT_GET_STATUS_CALLS: AtomicU32 = AtomicU32::new(0); static LAST_OUTPUT_ADDRESS: AtomicUsize = AtomicUsize::new(0); static AUDIO_IS_FORMAT_SUPPORTED_CALLS: AtomicU32 = AtomicU32::new(0); +static AUDIO_INITIALIZE_CALLS: AtomicU32 = AtomicU32::new(0); +static AUDIO_GET_MIX_FORMAT_CALLS: AtomicU32 = AtomicU32::new(0); static AUDIO_GET_SERVICE_CALLS: AtomicU32 = AtomicU32::new(0); static AUDIO_LAST_SHARE_MODE: AtomicI32 = AtomicI32::new(0); static AUDIO_LAST_FORMAT_TAG: AtomicU32 = AtomicU32::new(0); +static AUDIO_FORMAT_SUPPORT_MODE: AtomicI32 = AtomicI32::new(0); static AUDIO_GET_SERVICE_MODE: AtomicI32 = AtomicI32::new(0); static AUDIO_ADD_REF_CALLS: AtomicU32 = AtomicU32::new(0); static AUDIO_RELEASE_CALLS: AtomicU32 = AtomicU32::new(0); static AUDIO_CURRENT_REF_COUNT: AtomicU32 = AtomicU32::new(0); +static EVALUATION_BIND_VALUE_CALLS: AtomicU32 = AtomicU32::new(0); +static EVALUATION_GET_VALUE_CALLS: AtomicU32 = AtomicU32::new(0); +static EVALUATION_OUTPUT_MODE: AtomicI32 = AtomicI32::new(0); +static EVALUATION_CURRENT_REF_COUNT: AtomicU32 = AtomicU32::new(0); static THUMBNAIL_CALLS: AtomicU32 = AtomicU32::new(0); static THUMBNAIL_CURRENT_REF_COUNT: AtomicU32 = AtomicU32::new(0); static DATA_OBJECT_GET_DATA_CALLS: AtomicU32 = AtomicU32::new(0); @@ -1558,6 +1572,241 @@ pub fn generated_ole_cache_stats() -> GeneratedOleCacheStats { } } +struct DeviceControlCounters { + record_calls: AtomicU32, + null_format_calls: AtomicU32, + explicit_format_calls: AtomicU32, + add_ref_calls: AtomicU32, + release_calls: AtomicU32, + current_ref_count: AtomicU32, +} + +impl DeviceControlCounters { + const fn new() -> Self { + Self { + record_calls: AtomicU32::new(0), + null_format_calls: AtomicU32::new(0), + explicit_format_calls: AtomicU32::new(0), + add_ref_calls: AtomicU32::new(0), + release_calls: AtomicU32::new(0), + current_ref_count: AtomicU32::new(0), + } + } + + fn reset(&self) { + for counter in [ + &self.record_calls, + &self.null_format_calls, + &self.explicit_format_calls, + &self.add_ref_calls, + &self.release_calls, + ] { + counter.store(0, Ordering::SeqCst); + } + self.current_ref_count.store(1, Ordering::SeqCst); + } + + fn snapshot(&self) -> GeneratedDeviceControlStats { + GeneratedDeviceControlStats { + record_calls: self.record_calls.load(Ordering::SeqCst), + null_format_calls: self.null_format_calls.load(Ordering::SeqCst), + explicit_format_calls: self.explicit_format_calls.load(Ordering::SeqCst), + add_ref_calls: self.add_ref_calls.load(Ordering::SeqCst), + release_calls: self.release_calls.load(Ordering::SeqCst), + current_ref_count: self.current_ref_count.load(Ordering::SeqCst), + } + } +} + +static MDSP_DEVICE_CONTROL_COUNTERS: DeviceControlCounters = DeviceControlCounters::new(); +static WMDM_DEVICE_CONTROL_COUNTERS: DeviceControlCounters = DeviceControlCounters::new(); + +#[repr(C)] +struct GeneratedDeviceControlFake { + vtable: *const IUnknown_Vtbl, + iid: GUID, + references: AtomicU32, + counters: &'static DeviceControlCounters, +} + +unsafe extern "system" fn device_control_query_interface( + this: *mut c_void, + iid: *const GUID, + result: *mut *mut c_void, +) -> HRESULT { + if iid.is_null() || result.is_null() { + return E_POINTER; + } + unsafe { + *result = std::ptr::null_mut(); + let object = &*this.cast::(); + if *iid != IUnknown::IID && *iid != object.iid { + return E_NOINTERFACE; + } + *result = this; + device_control_add_ref(this); + } + HRESULT(0) +} + +unsafe extern "system" fn device_control_add_ref(this: *mut c_void) -> u32 { + let object = unsafe { &*this.cast::() }; + object.counters.add_ref_calls.fetch_add(1, Ordering::SeqCst); + let count = object.references.fetch_add(1, Ordering::SeqCst) + 1; + object + .counters + .current_ref_count + .store(count, Ordering::SeqCst); + count +} + +unsafe extern "system" fn device_control_release(this: *mut c_void) -> u32 { + let object = unsafe { &*this.cast::() }; + object.counters.release_calls.fetch_add(1, Ordering::SeqCst); + let count = object.references.fetch_sub(1, Ordering::SeqCst) - 1; + object + .counters + .current_ref_count + .store(count, Ordering::SeqCst); + if count == 0 { + unsafe { + drop(Box::from_raw(this.cast::())); + } + } + count +} + +unsafe extern "system" fn device_control_get_u32(_this: *mut c_void, _value: *mut u32) -> HRESULT { + E_NOTIMPL +} + +unsafe extern "system" fn device_control_no_args(_this: *mut c_void) -> HRESULT { + E_NOTIMPL +} + +unsafe extern "system" fn device_control_record( + this: *mut c_void, + format: *const WAVEFORMATEX, +) -> HRESULT { + let counters = unsafe { &*this.cast::() }.counters; + counters.record_calls.fetch_add(1, Ordering::SeqCst); + if format.is_null() { + counters.null_format_calls.fetch_add(1, Ordering::SeqCst); + return HRESULT(0); + } + // WAVEFORMATEX is packed; copy the header without forming aligned field references. + let header = unsafe { format.read_unaligned() }; + if header.wFormatTag != 1 + || header.nChannels != 2 + || header.nSamplesPerSec != 48_000 + || header.nAvgBytesPerSec != 192_000 + || header.nBlockAlign != 4 + || header.wBitsPerSample != 16 + || header.cbSize != 0 + { + return HRESULT(0x80070057u32 as i32); + } + counters + .explicit_format_calls + .fetch_add(1, Ordering::SeqCst); + HRESULT(0) +} + +unsafe extern "system" fn device_control_seek( + _this: *mut c_void, + _mode: u32, + _offset: i32, +) -> HRESULT { + E_NOTIMPL +} + +static MDSP_DEVICE_CONTROL_VTABLE: IMDSPDeviceControl_Vtbl = IMDSPDeviceControl_Vtbl { + base__: IUnknown_Vtbl { + QueryInterface: device_control_query_interface, + AddRef: device_control_add_ref, + Release: device_control_release, + }, + GetDCStatus: device_control_get_u32, + GetCapabilities: device_control_get_u32, + Play: device_control_no_args, + Record: device_control_record, + Pause: device_control_no_args, + Resume: device_control_no_args, + Stop: device_control_no_args, + Seek: device_control_seek, +}; + +static WMDM_DEVICE_CONTROL_VTABLE: IWMDMDeviceControl_Vtbl = IWMDMDeviceControl_Vtbl { + base__: IUnknown_Vtbl { + QueryInterface: device_control_query_interface, + AddRef: device_control_add_ref, + Release: device_control_release, + }, + GetStatus: device_control_get_u32, + GetCapabilities: device_control_get_u32, + Play: device_control_no_args, + Record: device_control_record, + Pause: device_control_no_args, + Resume: device_control_no_args, + Stop: device_control_no_args, + Seek: device_control_seek, +}; + +fn create_generated_device_control_fake( + vtable: &'static IUnknown_Vtbl, + iid: GUID, + counters: &'static DeviceControlCounters, +) -> napi::Result { + counters.reset(); + // Each object has its own full SDK vtable and advertises only its matching IID. + let object = Box::new(GeneratedDeviceControlFake { + vtable, + iid, + references: AtomicU32::new(1), + counters, + }); + let unknown = unsafe { IUnknown::from_raw(Box::into_raw(object).cast()) }; + crate::com::apartment_bound_com_object(unknown) +} + +#[napi(object)] +pub struct GeneratedDeviceControlStats { + pub record_calls: u32, + pub null_format_calls: u32, + pub explicit_format_calls: u32, + pub add_ref_calls: u32, + pub release_calls: u32, + pub current_ref_count: u32, +} + +#[napi] +pub fn create_generated_mdsp_device_control_fake() -> napi::Result { + create_generated_device_control_fake( + &MDSP_DEVICE_CONTROL_VTABLE.base__, + IMDSPDeviceControl::IID, + &MDSP_DEVICE_CONTROL_COUNTERS, + ) +} + +#[napi] +pub fn create_generated_wmdm_device_control_fake() -> napi::Result { + create_generated_device_control_fake( + &WMDM_DEVICE_CONTROL_VTABLE.base__, + IWMDMDeviceControl::IID, + &WMDM_DEVICE_CONTROL_COUNTERS, + ) +} + +#[napi] +pub fn generated_mdsp_device_control_stats() -> GeneratedDeviceControlStats { + MDSP_DEVICE_CONTROL_COUNTERS.snapshot() +} + +#[napi] +pub fn generated_wmdm_device_control_stats() -> GeneratedDeviceControlStats { + WMDM_DEVICE_CONTROL_COUNTERS.snapshot() +} + #[repr(C)] struct GeneratedAudioClientVtbl { base__: IUnknown_Vtbl, @@ -1623,16 +1872,62 @@ unsafe extern "system" fn audio_release(this: *mut c_void) -> u32 { count } +fn valid_audio_format(format: *const c_void) -> bool { + if format.is_null() { + return false; + } + let bytes = unsafe { std::slice::from_raw_parts(format.cast::(), 18) }; + u16::from_le_bytes([bytes[0], bytes[1]]) != 0 + && u16::from_le_bytes([bytes[2], bytes[3]]) != 0 + && u32::from_le_bytes(bytes[4..8].try_into().unwrap()) != 0 + && u32::from_le_bytes(bytes[8..12].try_into().unwrap()) != 0 + && u16::from_le_bytes([bytes[12], bytes[13]]) != 0 +} + +unsafe fn write_audio_format( + output: *mut *mut c_void, + channels: u16, + samples_per_second: u32, + bits_per_sample: u16, +) -> HRESULT { + if output.is_null() { + return E_POINTER; + } + let block_align = channels * (bits_per_sample / 8); + let average_bytes_per_second = samples_per_second * u32::from(block_align); + let mut bytes = Vec::with_capacity(18); + bytes.extend_from_slice(&1u16.to_le_bytes()); + bytes.extend_from_slice(&channels.to_le_bytes()); + bytes.extend_from_slice(&samples_per_second.to_le_bytes()); + bytes.extend_from_slice(&average_bytes_per_second.to_le_bytes()); + bytes.extend_from_slice(&block_align.to_le_bytes()); + bytes.extend_from_slice(&bits_per_sample.to_le_bytes()); + bytes.extend_from_slice(&0u16.to_le_bytes()); + let allocation = unsafe { windows::Win32::System::Com::CoTaskMemAlloc(bytes.len()) }; + if allocation.is_null() { + return HRESULT(0x8007000eu32 as i32); + } + unsafe { + std::ptr::copy_nonoverlapping(bytes.as_ptr(), allocation.cast(), bytes.len()); + output.write(allocation); + } + HRESULT(0) +} + unsafe extern "system" fn audio_initialize( _this: *mut c_void, _share_mode: i32, _stream_flags: u32, _buffer_duration: i64, _periodicity: i64, - _format: *mut c_void, + format: *mut c_void, _session: *const GUID, ) -> HRESULT { - E_NOTIMPL + if !valid_audio_format(format.cast_const()) { + return HRESULT(0x80070057u32 as i32); + } + AUDIO_INITIALIZE_CALLS.fetch_add(1, Ordering::SeqCst); + HRESULT(0) } unsafe extern "system" fn audio_get_u32(_this: *mut c_void, _value: *mut u32) -> HRESULT { @@ -1649,35 +1944,47 @@ unsafe extern "system" fn audio_is_format_supported( format: *mut c_void, closest: *mut *mut c_void, ) -> HRESULT { - if format.is_null() || closest.is_null() { + if !valid_audio_format(format.cast_const()) { + return HRESULT(0x80070057u32 as i32); + } + if (share_mode == 0 && closest.is_null()) || (share_mode == 1 && !closest.is_null()) { return E_POINTER; } + if !matches!(share_mode, 0 | 1) { + return HRESULT(0x80070057u32 as i32); + } AUDIO_IS_FORMAT_SUPPORTED_CALLS.fetch_add(1, Ordering::SeqCst); AUDIO_LAST_SHARE_MODE.store(share_mode, Ordering::SeqCst); AUDIO_LAST_FORMAT_TAG.store( unsafe { u32::from(*format.cast::()) }, Ordering::SeqCst, ); - let allocation = unsafe { windows::Win32::System::Com::CoTaskMemAlloc(16) }; - if allocation.is_null() { - return HRESULT(0x8007000eu32 as i32); - } - unsafe { - allocation.cast::().write(0xaabb_ccdd); - *closest = allocation; + if !closest.is_null() { + unsafe { + *closest = std::ptr::null_mut(); + } } - if share_mode == 2 { - HRESULT(0x80004005u32 as i32) - } else { - HRESULT(1) + match AUDIO_FORMAT_SUPPORT_MODE.load(Ordering::SeqCst) { + 0 => HRESULT(0), + 1 if share_mode == 0 => { + let result = unsafe { write_audio_format(closest, 1, 44_100, 16) }; + if result.is_ok() { + HRESULT(1) + } else { + result + } + } + 1 => HRESULT(0x88890008u32 as i32), + _ => HRESULT(0x80004005u32 as i32), } } unsafe extern "system" fn audio_get_mix_format( _this: *mut c_void, - _format: *mut *mut c_void, + format: *mut *mut c_void, ) -> HRESULT { - E_NOTIMPL + AUDIO_GET_MIX_FORMAT_CALLS.fetch_add(1, Ordering::SeqCst); + unsafe { write_audio_format(format, 2, 48_000, 16) } } unsafe extern "system" fn audio_get_device_period( @@ -1780,7 +2087,9 @@ static AUDIO_VTABLE: GeneratedAudioClientVtbl = GeneratedAudioClientVtbl { #[napi(object)] pub struct GeneratedAudioClientStats { + pub initialize_calls: u32, pub is_format_supported_calls: u32, + pub get_mix_format_calls: u32, pub get_service_calls: u32, pub last_share_mode: i32, pub last_format_tag: u32, @@ -1791,10 +2100,13 @@ pub struct GeneratedAudioClientStats { #[napi] pub fn create_generated_audio_client_fake() -> napi::Result { + AUDIO_INITIALIZE_CALLS.store(0, Ordering::SeqCst); AUDIO_IS_FORMAT_SUPPORTED_CALLS.store(0, Ordering::SeqCst); + AUDIO_GET_MIX_FORMAT_CALLS.store(0, Ordering::SeqCst); AUDIO_GET_SERVICE_CALLS.store(0, Ordering::SeqCst); AUDIO_LAST_SHARE_MODE.store(0, Ordering::SeqCst); AUDIO_LAST_FORMAT_TAG.store(0, Ordering::SeqCst); + AUDIO_FORMAT_SUPPORT_MODE.store(0, Ordering::SeqCst); AUDIO_GET_SERVICE_MODE.store(0, Ordering::SeqCst); AUDIO_ADD_REF_CALLS.store(0, Ordering::SeqCst); AUDIO_RELEASE_CALLS.store(0, Ordering::SeqCst); @@ -1807,6 +2119,17 @@ pub fn create_generated_audio_client_fake() -> napi::Result { crate::com::apartment_bound_com_object(unknown) } +#[napi] +pub fn set_generated_audio_client_format_support_mode(mode: i32) -> napi::Result<()> { + if !(-1..=1).contains(&mode) { + return Err(napi::Error::from_reason( + "generated audio format-support mode must be -1, 0, or 1", + )); + } + AUDIO_FORMAT_SUPPORT_MODE.store(mode, Ordering::SeqCst); + Ok(()) +} + #[napi] pub fn set_generated_audio_client_get_service_mode(mode: i32) -> napi::Result<()> { if !(-5..=5).contains(&mode) { @@ -1821,7 +2144,9 @@ pub fn set_generated_audio_client_get_service_mode(mode: i32) -> napi::Result<() #[napi] pub fn generated_audio_client_stats() -> GeneratedAudioClientStats { GeneratedAudioClientStats { + initialize_calls: AUDIO_INITIALIZE_CALLS.load(Ordering::SeqCst), is_format_supported_calls: AUDIO_IS_FORMAT_SUPPORTED_CALLS.load(Ordering::SeqCst), + get_mix_format_calls: AUDIO_GET_MIX_FORMAT_CALLS.load(Ordering::SeqCst), get_service_calls: AUDIO_GET_SERVICE_CALLS.load(Ordering::SeqCst), last_share_mode: AUDIO_LAST_SHARE_MODE.load(Ordering::SeqCst), last_format_tag: AUDIO_LAST_FORMAT_TAG.load(Ordering::SeqCst), @@ -1831,6 +2156,198 @@ pub fn generated_audio_client_stats() -> GeneratedAudioClientStats { } } +#[repr(C)] +struct GeneratedEvaluationContextVtbl { + base__: IUnknown_Vtbl, + bind_value: unsafe extern "system" fn(*mut c_void, *const c_void) -> HRESULT, + get_value_by_name: + unsafe extern "system" fn(*mut c_void, *const u16, *mut *mut c_void) -> HRESULT, + clear: unsafe extern "system" fn(*mut c_void) -> HRESULT, +} + +#[repr(C)] +struct GeneratedEvaluationContextFake { + vtable: *const GeneratedEvaluationContextVtbl, + references: AtomicU32, +} + +unsafe extern "system" fn evaluation_query_interface( + this: *mut c_void, + iid: *const GUID, + result: *mut *mut c_void, +) -> HRESULT { + if iid.is_null() || result.is_null() { + return E_POINTER; + } + unsafe { + *result = std::ptr::null_mut(); + if *iid != IUnknown::IID && *iid != IID_IWINML_EVALUATION_CONTEXT { + return E_NOINTERFACE; + } + *result = this; + evaluation_add_ref(this); + } + HRESULT(0) +} + +unsafe extern "system" fn evaluation_add_ref(this: *mut c_void) -> u32 { + let object = unsafe { &*this.cast::() }; + let count = object.references.fetch_add(1, Ordering::SeqCst) + 1; + EVALUATION_CURRENT_REF_COUNT.store(count, Ordering::SeqCst); + count +} + +unsafe extern "system" fn evaluation_release(this: *mut c_void) -> u32 { + let object = unsafe { &*this.cast::() }; + let count = object.references.fetch_sub(1, Ordering::SeqCst) - 1; + EVALUATION_CURRENT_REF_COUNT.store(count, Ordering::SeqCst); + if count == 0 { + unsafe { + drop(Box::from_raw(this.cast::())); + } + } + count +} + +unsafe extern "system" fn evaluation_bind_value( + _this: *mut c_void, + descriptor: *const c_void, +) -> HRESULT { + if descriptor.is_null() { + return E_POINTER; + } + EVALUATION_BIND_VALUE_CALLS.fetch_add(1, Ordering::SeqCst); + HRESULT(0) +} + +unsafe extern "system" fn evaluation_get_value_by_name( + this: *mut c_void, + name: *const u16, + result: *mut *mut c_void, +) -> HRESULT { + if name.is_null() || result.is_null() { + return E_POINTER; + } + EVALUATION_GET_VALUE_CALLS.fetch_add(1, Ordering::SeqCst); + let mode = EVALUATION_OUTPUT_MODE.load(Ordering::SeqCst); + unsafe { + *result = std::ptr::null_mut(); + if mode == 2 { + return HRESULT(0); + } + if mode == -2 { + return HRESULT(0x80004005u32 as i32); + } + if mode.abs() == 3 { + *result = windows::core::BSTR::from("stage2-bstr") + .into_raw() + .cast_mut() + .cast(); + return if mode < 0 { + HRESULT(0x80004005u32 as i32) + } else { + HRESULT(0) + }; + } + if mode.abs() == 4 { + *result = + windows::Win32::System::Memory::LocalAlloc(windows::Win32::System::Memory::LMEM_FIXED, 32) + .map_or(std::ptr::null_mut(), |value| value.0); + return if mode < 0 { + HRESULT(0x80004005u32 as i32) + } else { + HRESULT(0) + }; + } + if mode.abs() == 5 { + *result = + windows::Win32::System::Memory::GlobalAlloc(windows::Win32::System::Memory::GMEM_FIXED, 32) + .map_or(std::ptr::null_mut(), |value| value.0); + return if mode < 0 { + HRESULT(0x80004005u32 as i32) + } else { + HRESULT(0) + }; + } + if mode.abs() == 6 { + *result = windows::Win32::System::Com::CoTaskMemAlloc(16); + if !(*result).is_null() { + (*result).cast::().write(0xaabb_ccdd); + } + return if mode < 0 { + HRESULT(0x80004005u32 as i32) + } else if (*result).is_null() { + HRESULT(0x8007000eu32 as i32) + } else { + HRESULT(0) + }; + } + evaluation_add_ref(this); + *result = this; + } + if mode == 1 { + HRESULT(0x80004005u32 as i32) + } else { + HRESULT(0) + } +} + +unsafe extern "system" fn evaluation_clear(_this: *mut c_void) -> HRESULT { + HRESULT(0) +} + +static EVALUATION_VTABLE: GeneratedEvaluationContextVtbl = GeneratedEvaluationContextVtbl { + base__: IUnknown_Vtbl { + QueryInterface: evaluation_query_interface, + AddRef: evaluation_add_ref, + Release: evaluation_release, + }, + bind_value: evaluation_bind_value, + get_value_by_name: evaluation_get_value_by_name, + clear: evaluation_clear, +}; + +#[napi(object)] +pub struct GeneratedEvaluationContextStats { + pub bind_value_calls: u32, + pub get_value_calls: u32, + pub current_ref_count: u32, +} + +#[napi] +pub fn create_generated_evaluation_context_fake() -> napi::Result { + EVALUATION_BIND_VALUE_CALLS.store(0, Ordering::SeqCst); + EVALUATION_GET_VALUE_CALLS.store(0, Ordering::SeqCst); + EVALUATION_OUTPUT_MODE.store(0, Ordering::SeqCst); + EVALUATION_CURRENT_REF_COUNT.store(1, Ordering::SeqCst); + let object = Box::new(GeneratedEvaluationContextFake { + vtable: &EVALUATION_VTABLE, + references: AtomicU32::new(1), + }); + let unknown = unsafe { IUnknown::from_raw(Box::into_raw(object).cast()) }; + crate::com::apartment_bound_com_object(unknown) +} + +#[napi] +pub fn set_generated_evaluation_context_output_mode(mode: i32) -> napi::Result<()> { + if !(-6..=6).contains(&mode) { + return Err(napi::Error::from_reason( + "generated evaluation output mode must be between -6 and 6", + )); + } + EVALUATION_OUTPUT_MODE.store(mode, Ordering::SeqCst); + Ok(()) +} + +#[napi] +pub fn generated_evaluation_context_stats() -> GeneratedEvaluationContextStats { + GeneratedEvaluationContextStats { + bind_value_calls: EVALUATION_BIND_VALUE_CALLS.load(Ordering::SeqCst), + get_value_calls: EVALUATION_GET_VALUE_CALLS.load(Ordering::SeqCst), + current_ref_count: EVALUATION_CURRENT_REF_COUNT.load(Ordering::SeqCst), + } +} + #[napi] pub fn create_generated_native_cleanup_resource(kind: u32) -> napi::Result { let address = match kind { diff --git a/bindings/js/src/lib.rs b/bindings/js/src/lib.rs index 725da524..e502de76 100644 --- a/bindings/js/src/lib.rs +++ b/bindings/js/src/lib.rs @@ -1228,6 +1228,17 @@ impl DynWinRTValue { ))), None, ), + dynwinrt::com::Value::AudioFormat(value) => Self( + dynwinrt::WinRTValue::Null, + None, + com::PointerProvenance::None, + None, + None, + Some(com::AutomationValue::new( + dynwinrt::com::Value::AudioFormat(value), + )), + None, + ), dynwinrt::com::Value::Buffer(value) => Self( dynwinrt::WinRTValue::Null, None, diff --git a/crates/dynwinrt/src/call.rs b/crates/dynwinrt/src/call.rs index 9c4a551c..4eca2706 100644 --- a/crates/dynwinrt/src/call.rs +++ b/crates/dynwinrt/src/call.rs @@ -414,6 +414,10 @@ pub(crate) trait ArgumentList { fn get_stg_medium(&self, _index: usize) -> Option<&crate::com::StgMediumValue> { None } + + fn get_audio_format(&self, _index: usize) -> Option<&crate::com::AudioFormatValue> { + None + } } impl ArgumentList for [WinRTValue] { @@ -736,6 +740,8 @@ where std::collections::BTreeMap::::new(); let mut stg_medium_out_values = std::collections::BTreeMap::::new(); + let mut audio_format_out_values = + std::collections::BTreeMap::::new(); let mut optional_out_requests: Vec> = Vec::with_capacity(out_count); // Array storage: Box'd for pointer stability (addresses don't change after creation) @@ -754,6 +760,7 @@ where let mut variant_by_value_in_slots: Vec = Vec::new(); let mut format_etc_in_slots: Vec> = Vec::new(); let mut stg_medium_in_slots: Vec = Vec::new(); + let mut audio_format_in_ptrs: Vec<*const c_void> = Vec::new(); // FillArray storage: caller-allocated buffers let mut fill_array_slots: Vec> = Vec::new(); @@ -1069,6 +1076,25 @@ where stg_medium_out_values.insert(p.value_index, value); array_out_map.push(None); fill_array_map.push(None); + } else if p.typ.is_audio_format() { + if p.is_in_out() { + return Err(windows_core::Error::new( + windows_core::HRESULT(0x80070057u32 as i32), + "WAVEFORMATEX in/out is not supported", + )); + } + let mut value = crate::com::AudioFormatOutput::new(); + out_ptrs.push(value.as_mut_ptr().cast_const()); + out_values.push(AbiValue::Pointer(std::ptr::null_mut())); + struct_out_values.push(None); + guid_out_values.push(None); + native_struct_out_values.push(None); + variant_out_values.push(None); + safe_array_out_values.push(None); + prop_variant_out_values.push(None); + audio_format_out_values.insert(p.value_index, value); + array_out_map.push(None); + fill_array_map.push(None); } else if p.typ.is_struct() { let val = if p.is_in_out() { args.get_value(p.input_index.expect("in/out input index")) @@ -1188,6 +1214,14 @@ where ) })?, ); + } else if p.is_input() && !p.is_out() && p.typ.is_audio_format() { + let input_index = p.input_index.expect("WAVEFORMATEX input index"); + let pointer = match args.get_audio_format(input_index) { + Some(format) => format.as_ptr(), + None if p.typ.is_nullable_audio_format_input() => std::ptr::null(), + None => panic!("validated WAVEFORMATEX input"), + }; + audio_format_in_ptrs.push(pointer); } } let native_struct_in_ptrs = native_struct_in_slots @@ -1300,6 +1334,7 @@ where let mut dispatch_params_in_idx = 0usize; let mut format_etc_in_idx = 0usize; let mut stg_medium_in_idx = 0usize; + let mut audio_format_in_idx = 0usize; for p in parameters { if p.is_out() { if let Some(slot_idx) = fill_array_map[p.value_index] { @@ -1353,6 +1388,9 @@ where } else if p.typ.is_stg_medium() { ffi_args.push(arg(&stg_medium_in_ptrs[stg_medium_in_idx])); stg_medium_in_idx += 1; + } else if p.typ.is_audio_format() { + ffi_args.push(arg(&audio_format_in_ptrs[audio_format_in_idx])); + audio_format_in_idx += 1; } else if p.typ.is_variant() { ffi_args.push(arg(&variant_in_ptrs[variant_in_idx])); variant_in_idx += 1; @@ -1742,6 +1780,16 @@ where ) }, )?)); + } else if let Some(value) = audio_format_out_values.remove(&p.value_index) { + match value.into_value(p.is_optional_out()).map_err(|error| { + windows_core::Error::new( + windows_core::HRESULT(0x80070057u32 as i32), + &error.message(), + ) + })? { + Some(value) => result_values.push(NativeCallValue::AudioFormat(value)), + None => result_values.push(NativeCallValue::WinRt(WinRTValue::Null)), + } } else if let Some(struct_val) = struct_out_values[p.value_index].take() { result_values.push(NativeCallValue::WinRt(WinRTValue::Struct(struct_val))); } else { diff --git a/crates/dynwinrt/src/com.rs b/crates/dynwinrt/src/com.rs index 883109b9..f2149b54 100644 --- a/crates/dynwinrt/src/com.rs +++ b/crates/dynwinrt/src/com.rs @@ -926,6 +926,198 @@ impl Drop for StgMediumStorage { } } +const WAVEFORMATEX_SIZE: usize = 18; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AudioFormatValue { + bytes: Arc<[u8]>, +} + +impl AudioFormatValue { + pub fn from_wave_format_ex(bytes: Vec) -> result::Result { + if bytes.len() < WAVEFORMATEX_SIZE { + return Err(invalid_argument( + "WAVEFORMATEX storage is smaller than its 18-byte header", + )); + } + let extra_size = u16::from_le_bytes([bytes[16], bytes[17]]) as usize; + if bytes.len() != WAVEFORMATEX_SIZE + extra_size { + return Err(invalid_argument(&format!( + "WAVEFORMATEX storage length {} does not match cbSize {}", + bytes.len(), + extra_size + ))); + } + let value = Self { + bytes: bytes.into(), + }; + if value.format_tag() == 0xfffe && extra_size < 22 { + return Err(invalid_argument( + "WAVEFORMATEXTENSIBLE storage requires at least 22 extension bytes", + )); + } + Ok(value) + } + + pub fn wave_format_ex( + format_tag: u16, + channels: u16, + samples_per_second: u32, + average_bytes_per_second: u32, + block_align: u16, + bits_per_sample: u16, + extra_data: Vec, + ) -> result::Result { + let extra_size = u16::try_from(extra_data.len()) + .map_err(|_| invalid_argument("WAVEFORMATEX extra data exceeds u16::MAX bytes"))?; + let mut bytes = Vec::with_capacity(WAVEFORMATEX_SIZE + extra_data.len()); + bytes.extend_from_slice(&format_tag.to_le_bytes()); + bytes.extend_from_slice(&channels.to_le_bytes()); + bytes.extend_from_slice(&samples_per_second.to_le_bytes()); + bytes.extend_from_slice(&average_bytes_per_second.to_le_bytes()); + bytes.extend_from_slice(&block_align.to_le_bytes()); + bytes.extend_from_slice(&bits_per_sample.to_le_bytes()); + bytes.extend_from_slice(&extra_size.to_le_bytes()); + bytes.extend_from_slice(&extra_data); + Self::from_wave_format_ex(bytes) + } + + pub fn pcm( + channels: u16, + samples_per_second: u32, + bits_per_sample: u16, + ) -> result::Result { + if channels == 0 || samples_per_second == 0 { + return Err(invalid_argument( + "PCM channel count and sample rate must be non-zero", + )); + } + if bits_per_sample == 0 || bits_per_sample % 8 != 0 { + return Err(invalid_argument( + "PCM bits per sample must be a non-zero multiple of eight", + )); + } + let block_align = u32::from(channels) + .checked_mul(u32::from(bits_per_sample / 8)) + .and_then(|value| u16::try_from(value).ok()) + .ok_or_else(|| invalid_argument("PCM block alignment exceeds u16::MAX"))?; + let average_bytes_per_second = samples_per_second + .checked_mul(u32::from(block_align)) + .ok_or_else(|| invalid_argument("PCM average byte rate exceeds u32::MAX"))?; + Self::wave_format_ex( + 1, + channels, + samples_per_second, + average_bytes_per_second, + block_align, + bits_per_sample, + Vec::new(), + ) + } + + pub fn format_tag(&self) -> u16 { + u16::from_le_bytes([self.bytes[0], self.bytes[1]]) + } + + pub fn channels(&self) -> u16 { + u16::from_le_bytes([self.bytes[2], self.bytes[3]]) + } + + pub fn samples_per_second(&self) -> u32 { + u32::from_le_bytes(self.bytes[4..8].try_into().unwrap()) + } + + pub fn average_bytes_per_second(&self) -> u32 { + u32::from_le_bytes(self.bytes[8..12].try_into().unwrap()) + } + + pub fn block_align(&self) -> u16 { + u16::from_le_bytes([self.bytes[12], self.bytes[13]]) + } + + pub fn bits_per_sample(&self) -> u16 { + u16::from_le_bytes([self.bytes[14], self.bytes[15]]) + } + + pub fn extra_data(&self) -> &[u8] { + &self.bytes[WAVEFORMATEX_SIZE..] + } + + pub fn bytes(&self) -> &[u8] { + &self.bytes + } + + pub(crate) fn as_ptr(&self) -> *const c_void { + self.bytes.as_ptr().cast() + } + + unsafe fn copy_from_native(value: *const c_void) -> result::Result { + if value.is_null() { + return Err(invalid_argument("WAVEFORMATEX output was null")); + } + let header = unsafe { std::slice::from_raw_parts(value.cast::(), WAVEFORMATEX_SIZE) }; + let format_tag = u16::from_le_bytes([header[0], header[1]]); + let extra_size = if format_tag == 1 { + 0 + } else { + u16::from_le_bytes([header[16], header[17]]) as usize + }; + let mut bytes = unsafe { + std::slice::from_raw_parts(value.cast::(), WAVEFORMATEX_SIZE + extra_size) + } + .to_vec(); + if format_tag == 1 { + bytes[16..18].copy_from_slice(&0u16.to_le_bytes()); + } + Self::from_wave_format_ex(bytes) + } +} + +pub(crate) struct AudioFormatOutput { + raw: Box<*mut c_void>, +} + +impl AudioFormatOutput { + pub(crate) fn new() -> Self { + Self { + raw: Box::new(std::ptr::null_mut()), + } + } + + pub(crate) fn as_mut_ptr(&mut self) -> *mut c_void { + (&mut *self.raw as *mut *mut c_void).cast() + } + + pub(crate) fn into_value(mut self, nullable: bool) -> result::Result> { + if self.raw.is_null() { + return if nullable { + Ok(None) + } else { + Err(invalid_argument("required WAVEFORMATEX output was null")) + }; + } + let value = unsafe { AudioFormatValue::copy_from_native(*self.raw) }; + self.free(); + value.map(Some) + } + + fn free(&mut self) { + if self.raw.is_null() { + return; + } + unsafe { + crate::native_call::OutputCleanup::CoTaskMemFree.cleanup(*self.raw); + } + *self.raw = std::ptr::null_mut(); + } +} + +impl Drop for AudioFormatOutput { + fn drop(&mut self) { + self.free(); + } +} + #[cfg(test)] static STATSTG_TEST_FREES: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); @@ -1275,6 +1467,7 @@ pub enum Value { StatStg(StatStgValue), FormatEtc(FormatEtcValue), StgMedium(StgMediumValue), + AudioFormat(AudioFormatValue), Buffer(ComBufferValue), } @@ -1293,6 +1486,7 @@ fn is_null_input_value(value: &Value) -> bool { | Value::StatStg(_) | Value::FormatEtc(_) | Value::StgMedium(_) + | Value::AudioFormat(_) | Value::Buffer(_) => false, } } @@ -2044,7 +2238,8 @@ impl BufferElementPlan { | ParameterType::ExcepInfo | ParameterType::StatStg | ParameterType::FormatEtc - | ParameterType::StgMedium => { + | ParameterType::StgMedium + | ParameterType::AudioFormat { .. } => { return Err(invalid_argument( "Automation buffer elements require dedicated ownership and cleanup plans", )); @@ -2362,6 +2557,15 @@ impl Type { } } + pub fn audio_format() -> Self { + Self { + abi: ParameterType::audio_format(false), + pointer_output: PointerOutputKind::None, + allow_direct_aggregate_return: false, + aggregate_capability: None, + } + } + fn pointer_with_output(pointer_output: PointerOutputKind) -> Self { Self { abi: ParameterType::pointer(), @@ -3296,7 +3500,9 @@ impl CallbackMethodPlan { | ParameterType::DispatchParams | ParameterType::ExcepInfo | ParameterType::StatStg => Some(crate::native_callback::CallbackAbiType::Pointer), - ParameterType::FormatEtc | ParameterType::StgMedium => None, + ParameterType::FormatEtc + | ParameterType::StgMedium + | ParameterType::AudioFormat { .. } => None, ParameterType::NativeStruct(layout) => { Some(crate::native_callback::CallbackAbiType::NativeStruct( format!("{layout:?}"), @@ -3753,7 +3959,8 @@ impl CallbackMethodPlan { ParameterType::NativeUnion(_) | ParameterType::VariantByValue | ParameterType::FormatEtc - | ParameterType::StgMedium => Err(SINK_E_FAIL), + | ParameterType::StgMedium + | ParameterType::AudioFormat { .. } => Err(SINK_E_FAIL), } } @@ -4406,7 +4613,8 @@ impl ComCallPlan { | Value::ExcepInfo(_) | Value::StatStg(_) | Value::FormatEtc(_) - | Value::StgMedium(_) => Err(invalid_argument( + | Value::StgMedium(_) + | Value::AudioFormat(_) => Err(invalid_argument( "COM-local result requires the COM value invocation path", )), Value::Buffer(_) => Err(invalid_argument( @@ -4604,7 +4812,8 @@ impl ComCallPlan { | Value::ExcepInfo(_) | Value::StatStg(_) | Value::FormatEtc(_) - | Value::StgMedium(_) => Err(invalid_argument( + | Value::StgMedium(_) + | Value::AudioFormat(_) => Err(invalid_argument( "COM-local value passed to a scalar COM method", )), Value::Buffer(_) => Err(invalid_argument( @@ -5673,7 +5882,10 @@ impl MethodSignature { self } - pub fn add_nullable_in(mut self, typ: Type) -> Self { + pub fn add_nullable_in(mut self, mut typ: Type) -> Self { + if let ParameterType::AudioFormat { nullable_input } = &mut typ.abi { + *nullable_input = true; + } self.parameters.push(ComParameterSpec { direction: ComParameterDirection::In, typ, @@ -6162,7 +6374,9 @@ fn validate_automation_contracts( { return Err(invalid_argument("FORMATETC does not support in/out")); } - if (parameter.typ.abi.is_format_etc() || parameter.typ.abi.is_stg_medium()) + if (parameter.typ.abi.is_format_etc() + || parameter.typ.abi.is_stg_medium() + || parameter.typ.abi.is_audio_format()) && parameter.direction != ComParameterDirection::In && !matches!( return_plan, @@ -6170,9 +6384,14 @@ fn validate_automation_contracts( ) { return Err(invalid_argument( - "FORMATETC/STGMEDIUM outputs require an HRESULT return convention", + "FORMATETC/STGMEDIUM/WAVEFORMATEX outputs require an HRESULT return convention", )); } + if parameter.typ.abi.is_audio_format() + && parameter.direction == ComParameterDirection::InOut + { + return Err(invalid_argument("WAVEFORMATEX does not support in/out")); + } if parameter.typ.abi.is_excep_info() && !matches!( return_plan, @@ -10977,6 +11196,126 @@ mod tests { HRESULT(0) } + unsafe extern "system" fn inspect_audio_format( + _this: *mut c_void, + format: *const c_void, + ) -> HRESULT { + if format.is_null() { + return HRESULT(0x80070057u32 as i32); + } + let header = unsafe { std::slice::from_raw_parts(format.cast::(), WAVEFORMATEX_SIZE) }; + if u16::from_le_bytes([header[0], header[1]]) != 1 + || u16::from_le_bytes([header[2], header[3]]) != 2 + || u32::from_le_bytes(header[4..8].try_into().unwrap()) != 48_000 + || u16::from_le_bytes([header[16], header[17]]) != 0 + { + return HRESULT(0x80070057u32 as i32); + } + HRESULT(0) + } + + unsafe extern "system" fn write_audio_format( + _this: *mut c_void, + output: *mut *mut c_void, + ) -> HRESULT { + if output.is_null() { + return HRESULT(0x80004003u32 as i32); + } + let bytes = AudioFormatValue::pcm(2, 48_000, 16).unwrap(); + let allocation = + unsafe { windows::Win32::System::Com::CoTaskMemAlloc(bytes.bytes().len()) }; + if allocation.is_null() { + return HRESULT(0x8007000eu32 as i32); + } + unsafe { + std::ptr::copy_nonoverlapping( + bytes.bytes().as_ptr(), + allocation.cast(), + bytes.bytes().len(), + ); + output.write(allocation); + } + HRESULT(0) + } + + unsafe extern "system" fn write_audio_format_then_fail( + this: *mut c_void, + output: *mut *mut c_void, + ) -> HRESULT { + let result = unsafe { write_audio_format(this, output) }; + if result.is_err() { + result + } else { + HRESULT(0x80004005u32 as i32) + } + } + + unsafe extern "system" fn write_invalid_audio_format( + _this: *mut c_void, + output: *mut *mut c_void, + ) -> HRESULT { + if output.is_null() { + return HRESULT(0x80004003u32 as i32); + } + let bytes = + AudioFormatValue::wave_format_ex(2, 2, 48_000, 192_000, 4, 16, vec![0; 21]).unwrap(); + let allocation = + unsafe { windows::Win32::System::Com::CoTaskMemAlloc(bytes.bytes().len()) }; + if allocation.is_null() { + return HRESULT(0x8007000eu32 as i32); + } + unsafe { + std::ptr::copy_nonoverlapping( + bytes.bytes().as_ptr(), + allocation.cast(), + bytes.bytes().len(), + ); + allocation.cast::().write(0xfffe); + output.write(allocation); + } + HRESULT(0) + } + + unsafe extern "system" fn write_pcm_with_ignored_extra_size( + this: *mut c_void, + output: *mut *mut c_void, + ) -> HRESULT { + let result = unsafe { write_audio_format(this, output) }; + if result.is_ok() { + unsafe { + (*output) + .cast::() + .add(16) + .cast::() + .write_unaligned(u16::MAX); + } + } + result + } + + unsafe extern "system" fn write_null_audio_format( + _this: *mut c_void, + output: *mut *mut c_void, + ) -> HRESULT { + if !output.is_null() { + unsafe { + output.write(std::ptr::null_mut()); + } + } + HRESULT(0) + } + + unsafe extern "system" fn require_null_audio_format_output( + _this: *mut c_void, + output: *mut *mut c_void, + ) -> HRESULT { + if output.is_null() { + HRESULT(0) + } else { + HRESULT(0x80004005u32 as i32) + } + } + fn invoke_test_stat_stg(function: *mut c_void, flags: u32) -> result::Result> { let table = MetadataTable::new(); invoke_test_pod( @@ -13959,6 +14298,217 @@ mod tests { ); } + #[test] + fn audio_format_nullable_inputs_preserve_null_slots_and_required_contracts() { + #[repr(C)] + struct AudioInputs { + vtable: *const *mut c_void, + calls: u32, + fail: bool, + } + + unsafe extern "system" fn observe( + this: *mut c_void, + first: *const c_void, + second: *const c_void, + ) -> HRESULT { + let state = unsafe { &mut *this.cast::() }; + state.calls += 1; + if state.fail { + return HRESULT(0x80004005u32 as i32); + } + for pointer in [first, second] { + if !pointer.is_null() { + let status = unsafe { inspect_audio_format(this, pointer) }; + if status.is_err() { + return status; + } + } + } + HRESULT(i32::from(first.is_null()) | (i32::from(second.is_null()) << 1)) + } + + let table = MetadataTable::new(); + let method = MethodSignature::new(&table) + .add_nullable_in(Type::audio_format()) + .add_nullable_in(Type::audio_format()) + .preserve_hresult() + .build(0) + .unwrap(); + let required = MethodSignature::new(&table) + .add_in(Type::audio_format()) + .add_nullable_in(Type::audio_format()) + .preserve_hresult() + .build(0) + .unwrap(); + let vtable = [observe as *mut c_void]; + let mut state = AudioInputs { + vtable: vtable.as_ptr(), + calls: 0, + fail: false, + }; + let format = AudioFormatValue::pcm(2, 48_000, 16).unwrap(); + let original = format.bytes().to_vec(); + for mask in 0..4 { + let arguments = (0..2) + .map(|index| { + if mask & (1 << index) != 0 { + Value::WinRt(WinRTValue::Null) + } else { + Value::AudioFormat(format.clone()) + } + }) + .collect::>(); + let output = method + .plan + .invoke_values((&mut state as *mut AudioInputs).cast(), &arguments) + .unwrap(); + assert!( + matches!(output.as_slice(), [Value::WinRt(WinRTValue::HResult(hr))] if hr.0 == mask) + ); + } + assert_eq!(state.calls, 4); + let null = || Value::WinRt(WinRTValue::Null); + let error = required + .plan + .invoke_values((&mut state as *mut AudioInputs).cast(), &[null(), null()]) + .unwrap_err(); + assert!( + error + .message() + .contains("required COM parameter 0 cannot be null") + ); + for invalid in [ + Value::WinRt(WinRTValue::I32(0)), + Value::WinRt(WinRTValue::RawPtr(std::ptr::null_mut())), + ] { + assert!( + method + .plan + .invoke_values((&mut state as *mut AudioInputs).cast(), &[invalid, null()]) + .is_err() + ); + } + assert_eq!(state.calls, 4); + state.fail = true; + let error = method + .plan + .invoke_values( + (&mut state as *mut AudioInputs).cast(), + &[null(), Value::AudioFormat(format.clone())], + ) + .unwrap_err(); + assert!(error.message().contains("80004005")); + assert_eq!(state.calls, 5); + assert_eq!(format.bytes(), original); + } + + #[test] + fn audio_format_calls_validate_variable_storage_and_cotaskmem_ownership() { + let table = MetadataTable::new(); + let format = AudioFormatValue::pcm(2, 48_000, 16).unwrap(); + assert_eq!(format.format_tag(), 1); + assert_eq!(format.channels(), 2); + assert_eq!(format.samples_per_second(), 48_000); + assert_eq!(format.average_bytes_per_second(), 192_000); + assert_eq!(format.block_align(), 4); + assert_eq!(format.bits_per_sample(), 16); + assert!(format.extra_data().is_empty()); + assert_eq!(format.bytes().len(), WAVEFORMATEX_SIZE); + assert!(AudioFormatValue::pcm(2, 48_000, 12).is_err()); + assert!(AudioFormatValue::from_wave_format_ex(vec![0; 17]).is_err()); + let mut wrong_size = format.bytes().to_vec(); + wrong_size[16..18].copy_from_slice(&1u16.to_le_bytes()); + assert!(AudioFormatValue::from_wave_format_ex(wrong_size).is_err()); + + invoke_test_pod( + inspect_audio_format as *mut c_void, + MethodSignature::new(&table).add_in(Type::audio_format()), + &[Value::AudioFormat(format.clone())], + ) + .unwrap(); + + crate::native_call::reset_co_task_mem_test_frees(); + let output = invoke_test_pod( + write_audio_format as *mut c_void, + MethodSignature::new(&table).add_out(Type::audio_format()), + &[], + ) + .unwrap(); + let Value::AudioFormat(output) = &output[0] else { + panic!("expected WAVEFORMATEX output"); + }; + assert_eq!(output, &format); + assert_eq!(crate::native_call::co_task_mem_test_frees(), 1); + + crate::native_call::reset_co_task_mem_test_frees(); + let output = invoke_test_pod( + write_pcm_with_ignored_extra_size as *mut c_void, + MethodSignature::new(&table).add_out(Type::audio_format()), + &[], + ) + .unwrap(); + let Value::AudioFormat(output) = &output[0] else { + panic!("expected normalized PCM WAVEFORMATEX output"); + }; + assert_eq!(output, &format); + assert_eq!(crate::native_call::co_task_mem_test_frees(), 1); + + crate::native_call::reset_co_task_mem_test_frees(); + let error = invoke_test_pod( + write_invalid_audio_format as *mut c_void, + MethodSignature::new(&table).add_out(Type::audio_format()), + &[], + ) + .unwrap_err(); + assert!(error.message().contains("at least 22 extension bytes")); + assert_eq!(crate::native_call::co_task_mem_test_frees(), 1); + + crate::native_call::reset_co_task_mem_test_frees(); + let error = invoke_test_pod( + write_audio_format_then_fail as *mut c_void, + MethodSignature::new(&table).add_out(Type::audio_format()), + &[], + ) + .unwrap_err(); + assert!(error.message().contains("80004005")); + assert_eq!(crate::native_call::co_task_mem_test_frees(), 1); + + let output = invoke_test_pod( + write_null_audio_format as *mut c_void, + MethodSignature::new(&table).add_optional_out(Type::audio_format()), + &[Value::WinRt(WinRTValue::Bool(true))], + ) + .unwrap(); + assert!(matches!( + output.as_slice(), + [Value::WinRt(WinRTValue::Null)] + )); + + let output = invoke_test_pod( + require_null_audio_format_output as *mut c_void, + MethodSignature::new(&table).add_optional_out(Type::audio_format()), + &[Value::WinRt(WinRTValue::Bool(false))], + ) + .unwrap(); + assert!(matches!( + output.as_slice(), + [Value::WinRt(WinRTValue::Null)] + )); + + let error = invoke_test_pod( + write_null_audio_format as *mut c_void, + MethodSignature::new(&table).add_out(Type::audio_format()), + &[], + ) + .unwrap_err(); + assert!( + error + .message() + .contains("required WAVEFORMATEX output was null") + ); + } + #[test] fn canonical_format_etc_result_rules_preserve_status_and_cleanup() { use windows::Win32::Foundation::{DATA_S_SAMEFORMATETC, S_OK}; diff --git a/crates/dynwinrt/src/native_call.rs b/crates/dynwinrt/src/native_call.rs index 3c570f59..004e422d 100644 --- a/crates/dynwinrt/src/native_call.rs +++ b/crates/dynwinrt/src/native_call.rs @@ -38,6 +38,7 @@ pub(crate) enum NativeCallValue { StatStg(crate::com::StatStgValue), FormatEtc(crate::com::FormatEtcValue), StgMedium(crate::com::StgMediumValue), + AudioFormat(crate::com::AudioFormatValue), } #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -78,6 +79,9 @@ pub(crate) enum ParameterType { StatStg, FormatEtc, StgMedium, + AudioFormat { + nullable_input: bool, + }, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -240,6 +244,10 @@ impl ParameterType { Self::StgMedium } + pub(crate) fn audio_format(nullable_input: bool) -> Self { + Self::AudioFormat { nullable_input } + } + pub(crate) fn as_winrt(&self) -> Option<&TypeHandle> { match self { Self::WinRT(typ) => Some(typ), @@ -258,7 +266,8 @@ impl ParameterType { | Self::ExcepInfo | Self::StatStg | Self::FormatEtc - | Self::StgMedium => None, + | Self::StgMedium + | Self::AudioFormat { .. } => None, } } @@ -279,7 +288,8 @@ impl ParameterType { | Self::ExcepInfo | Self::StatStg | Self::FormatEtc - | Self::StgMedium => None, + | Self::StgMedium + | Self::AudioFormat { .. } => None, } } @@ -372,6 +382,19 @@ impl ParameterType { matches!(self, Self::StgMedium) } + pub(crate) fn is_audio_format(&self) -> bool { + matches!(self, Self::AudioFormat { .. }) + } + + pub(crate) fn is_nullable_audio_format_input(&self) -> bool { + matches!( + self, + Self::AudioFormat { + nullable_input: true + } + ) + } + pub(crate) fn is_array(&self) -> bool { self.as_winrt().is_some_and(TypeHandle::is_array) } @@ -440,7 +463,8 @@ impl ParameterType { | Self::ExcepInfo | Self::StatStg | Self::FormatEtc - | Self::StgMedium => AbiType::Ptr, + | Self::StgMedium + | Self::AudioFormat { .. } => AbiType::Ptr, Self::NativeStruct(_) | Self::NativeUnion(_) | Self::VariantByValue => { panic!("aggregate values do not have a scalar AbiType") } @@ -462,7 +486,8 @@ impl ParameterType { | Self::ExcepInfo | Self::StatStg | Self::FormatEtc - | Self::StgMedium => libffi::middle::Type::pointer(), + | Self::StgMedium + | Self::AudioFormat { .. } => libffi::middle::Type::pointer(), Self::NativeStruct(layout) => layout.libffi_type(), Self::NativeUnion(layout) => layout.libffi_type(), Self::VariantByValue => variant_by_value_libffi_type(), @@ -499,7 +524,8 @@ impl ParameterType { | Self::ExcepInfo | Self::StatStg | Self::FormatEtc - | Self::StgMedium => { + | Self::StgMedium + | Self::AudioFormat { .. } => { panic!("native POD storage is allocated by the dynamic executor") } } @@ -523,7 +549,8 @@ impl ParameterType { | Self::ExcepInfo | Self::StatStg | Self::FormatEtc - | Self::StgMedium => { + | Self::StgMedium + | Self::AudioFormat { .. } => { unreachable!("native POD output conversion uses NativeStructValue") } } @@ -562,7 +589,8 @@ impl ParameterType { | Self::ExcepInfo | Self::StatStg | Self::FormatEtc - | Self::StgMedium, + | Self::StgMedium + | Self::AudioFormat { .. }, _, ) => { unreachable!("native POD output conversion uses NativeStructValue") @@ -583,6 +611,7 @@ impl ParameterType { Self::StatStg => OutputCleanup::None, Self::FormatEtc => OutputCleanup::None, Self::StgMedium => OutputCleanup::None, + Self::AudioFormat { .. } => OutputCleanup::None, Self::Bstr { .. } => OutputCleanup::BstrFree, Self::CoTaskMemWideString => OutputCleanup::CoTaskMemFree, Self::WinRT(_) @@ -861,6 +890,7 @@ impl AbiMethodSignature { || p.typ.is_stat_stg() || p.typ.is_format_etc() || p.typ.is_stg_medium() + || p.typ.is_audio_format() }); // Check if the single in-param (if any) is a simple non-HString, non-Struct type @@ -1404,7 +1434,8 @@ impl call::ArgumentList for ComInvocationArgs<'_> { | crate::com::Value::ExcepInfo(_) | crate::com::Value::StatStg(_) | crate::com::Value::FormatEtc(_) - | crate::com::Value::StgMedium(_) => { + | crate::com::Value::StgMedium(_) + | crate::com::Value::AudioFormat(_) => { panic!("COM-local argument requested as a WinRT value") } crate::com::Value::Buffer(_) => { @@ -1475,6 +1506,13 @@ impl call::ArgumentList for ComInvocationArgs<'_> { _ => None, } } + + fn get_audio_format(&self, index: usize) -> Option<&crate::com::AudioFormatValue> { + match &self.original[index] { + crate::com::Value::AudioFormat(value) => Some(value), + _ => None, + } + } } impl Method { @@ -1512,6 +1550,7 @@ impl Method { || parameter.typ.is_stat_stg() || parameter.typ.is_format_etc() || parameter.typ.is_stg_medium() + || parameter.typ.is_audio_format() }) || self.direct_return_type().is_some_and(|typ| { typ.native_struct_layout().is_some() || typ.native_union_layout().is_some() @@ -1525,6 +1564,7 @@ impl Method { || typ.is_stat_stg() || typ.is_format_etc() || typ.is_stg_medium() + || typ.is_audio_format() }) } @@ -2026,7 +2066,8 @@ impl Method { | NativeCallValue::ExcepInfo(_) | NativeCallValue::StatStg(_) | NativeCallValue::FormatEtc(_) - | NativeCallValue::StgMedium(_) => Err(invalid_argument( + | NativeCallValue::StgMedium(_) + | NativeCallValue::AudioFormat(_) => Err(invalid_argument( "COM-local result reached the WinRT invocation path", )), }) @@ -2236,6 +2277,21 @@ impl Method { continue; } + if parameter.typ.is_audio_format() { + let is_format = matches!(&args[input_index], crate::com::Value::AudioFormat(_)); + let is_nullable_input = parameter.typ.is_nullable_audio_format_input() + && matches!( + &args[input_index], + crate::com::Value::WinRt(WinRTValue::Null) + ); + if !is_format && !is_nullable_input { + return Err(invalid_argument( + "Argument type mismatch: expected WAVEFORMATEX", + )); + } + continue; + } + let crate::com::Value::WinRt(value) = &args[input_index] else { return Err(invalid_argument( "COM-local value passed to a scalar or pointer parameter", @@ -2304,6 +2360,7 @@ impl Method { NativeCallValue::StatStg(value) => crate::com::Value::StatStg(value), NativeCallValue::FormatEtc(value) => crate::com::Value::FormatEtc(value), NativeCallValue::StgMedium(value) => crate::com::Value::StgMedium(value), + NativeCallValue::AudioFormat(value) => crate::com::Value::AudioFormat(value), }) .collect() }) diff --git a/docs/architecture/classic-com-contract-evidence-registry.md b/docs/architecture/classic-com-contract-evidence-registry.md index a380e6cd..65f11eb8 100644 --- a/docs/architecture/classic-com-contract-evidence-registry.md +++ b/docs/architecture/classic-com-contract-evidence-registry.md @@ -338,11 +338,15 @@ Current code registries are migrated without changing behavior: - `STATSTG` and allocator-specific outputs; - `IDataObject::GetDataHere` caller-allocated, non-replacing STGMEDIUM InOut; - `IDataObject::SetData` and `IOleCache::SetData` caller-retained STGMEDIUM ownership; -- `IDataObject::GetCanonicalFormatEtc` output validity and ignored `tymed`; and +- `IDataObject::GetCanonicalFormatEtc` output validity and ignored `tymed`; +- `IAudioClient` shared/exclusive format negotiation and CoTaskMem format + outputs; +- `IMDSPDeviceControl::Record` and `IWMDMDeviceControl::Record` nullable + audio-format inputs selecting the device default; and - exact fail-closed hazards such as `GetPrivateData`. Migration or promotion is complete only when generated safe snapshots, the -5,691/7,929 safe census, generated unsafe manifests, and all live tests agree +5,696/7,929 safe census, generated unsafe manifests, and all live tests agree with the exact evidence dependencies. ## User contracts @@ -404,23 +408,23 @@ The safe-complete evidence census is: | Evidence class | Safe interfaces | | --- | ---: | | `standard_derived` | 5,333 | -| `exact_registry_dependent` | 358 | -| **Total** | **5,691** | +| `exact_registry_dependent` | 363 | +| **Total** | **5,696** | -The registry contains **499 declared entries**, all 499 match the pinned -metadata, and 408 distinct entries are consumed by safe plans. Safe plans have -660 entry/interface dependencies and 408 family/interface dependencies. -Per-interface dependency-set totals also include 5,976 metadata-attribute -dependencies and 26,114 COM-standard-rule dependencies. +The registry contains **504 declared entries**, all 504 match the pinned +metadata, and 413 distinct entries are consumed by safe plans. Safe plans have +669 entry/interface dependencies and 416 family/interface dependencies. +Per-interface dependency-set totals also include 5,982 metadata-attribute +dependencies and 26,129 COM-standard-rule dependencies. | Exact contract kind | Safe-interface dependencies | | --- | ---: | -| `ownership` | 176 | +| `ownership` | 180 | | `parameter-direction` | 45 | | `bounded-two-call` | 16 | -| `conditional-output` | 7 | +| `conditional-output` | 10 | | `flag-selected-buffer` | 3 | -| `null-input` | 2 | +| `null-input` | 4 | | `safearray` | 263 | | `enumerator-next` | 74 | | `borrowed-handle` | 54 | @@ -438,14 +442,16 @@ Family rollups deliberately count each interface once per family: | `com.sequential-stream-buffer.v1` | 2 | 2 | 7 | | `buffers.counted-buffer.v1` | 3 | 2 | 2 | | `buffers.bounded-two-call.v1` | 2 | 2 | 16 | -| `com.ownership.v1` | 165 | 114 | 119 | +| `com.ownership.v1` | 167 | 116 | 122 | | `com.parameter-direction.v1` | 3 | 3 | 15 | | `com.reserved-null-input.v1` | 2 | 2 | 1 | +| `com.nullable-input.v1` | 2 | 2 | 2 | | `com.semantic-hresult.v1` | 2 | 2 | 3 | | `automation.idispatch-invoke.v1` | 1 | 1 | 1 | | `graphics.private-data-hazard.v1` | 7 | 0 | 0 | | `shell.flag-selected-string.v1` | 1 | 1 | 3 | | `wmi.conditional-output.v1` | 7 | 7 | 1 | +| `audio.conditional-output.v1` | 1 | 1 | 3 | Universal rule dependencies are: @@ -456,11 +462,11 @@ Universal rule dependencies are: | `com.automation.bstr-replacement.v1` | 99 | | `com.enumerator-next.generic.v1` | 25 | | `com.handle.borrowed-no-cleanup.v1` | 45 | -| `com.hresult.failure.v1` | 5,573 | +| `com.hresult.failure.v1` | 5,578 | | `com.interface.input-borrow.v1` | 1,890 | | `com.interface.typed-output-plus-one.v1` | 3,457 | -| `com.iunknown.identity-refcount.v1` | 5,691 | -| `com.query-interface.output-plus-one.v1` | 5,691 | +| `com.iunknown.identity-refcount.v1` | 5,696 | +| `com.query-interface.output-plus-one.v1` | 5,696 | | `com.standard-cleanup.matching-allocator.v1` | 1,436 | These are dependency counts: an inherited contract can be consumed by several diff --git a/docs/architecture/classic-com-generated-unsafe.md b/docs/architecture/classic-com-generated-unsafe.md index ef6380cb..d67a3b38 100644 --- a/docs/architecture/classic-com-generated-unsafe.md +++ b/docs/architecture/classic-com-generated-unsafe.md @@ -49,9 +49,9 @@ generated/ │ ├── ITaskbarList3.js │ └── ITaskbarList3.d.ts └── unsafe/ - ├── windows/win32/media/audio/ - │ ├── IAudioClientUnsafe.js - │ └── IAudioClientUnsafe.d.ts + ├── windows/win32/ai/machine-learning/win-ml/ + │ ├── IWinMLEvaluationContextUnsafe.js + │ └── IWinMLEvaluationContextUnsafe.d.ts ├── index.js ├── index.mjs ├── index.d.ts @@ -83,16 +83,16 @@ Rules: The unsafe boundary is carried by the module path and class suffix: ```js -import { IAudioClientUnsafe } from "./generated/com/unsafe/index.js"; +import { IWinMLEvaluationContextUnsafe } from "./generated/com/unsafe/index.js"; ``` Methods keep their natural projected names: ```js -audio.isFormatSupported(...); +context.getValueByName(...); ``` -Do not emit a class named `IAudioClient` for an unsafe projection. Method names +Do not emit a class without the `Unsafe` suffix for an unsafe projection. Method names need an `Unsafe` suffix only if safe and unsafe methods are ever placed on the same class; the preferred design keeps them in separate companion classes. @@ -199,12 +199,12 @@ Generated unsafe companions do not add raw callback implementation. An unsafe companion wraps an existing managed native value: ```ts -export declare class IAudioClientUnsafe { +export declare class IWinMLEvaluationContextUnsafe { private constructor(); static from( value: DynWinRtValue | { readonly nativeValue: DynWinRtValue }, - ): IAudioClientUnsafe; + ): IWinMLEvaluationContextUnsafe; static readonly iid: WinGuid; static readonly support: UnsafeInterfaceSupport; readonly nativeValue: DynWinRtValue; @@ -212,11 +212,11 @@ export declare class IAudioClientUnsafe { /** * @unsafe Metadata-complete outbound ABI. */ - isFormatSupported( - shareMode: number, - format: UnsafePointee, - closestMatch: UnsafePointerOutput, - ): readonly [number, UnsafeOwnedPointer | null]; + bindValue(descriptor: UnsafePointee): void; + getValueByName( + name: DynComRawMemory | DynComRawPointer, + descriptor: UnsafePointerOutput, + ): UnsafeOwnedPointer; release(): void; } @@ -459,18 +459,18 @@ Generation emits `generated/com/unsafe/support.json`: "sha256": "..." } }, - "interfaceName": "Windows.Win32.Media.Audio.IAudioClient", - "interfaceIid": "1cb9ad4c-dbfa-4c32-b178-c2f568a703b2", + "interfaceName": "Windows.Win32.AI.MachineLearning.WinML.IWinMLEvaluationContext", + "interfaceIid": "95848f9e-583d-4054-af12-916387cd8426", "root": "IUnknown", "baseIids": [], - "unsafeClass": "IAudioClientUnsafe", - "modulePath": "windows/win32/media/audio/IAudioClientUnsafe", + "unsafeClass": "IWinMLEvaluationContextUnsafe", + "modulePath": "windows/win32/ai/machine-learning/win-ml/IWinMLEvaluationContextUnsafe", "methods": [ { - "name": "Initialize", - "projectedName": "initialize", - "declaringIid": "1cb9ad4c-dbfa-4c32-b178-c2f568a703b2", - "absoluteSlot": 4, + "name": "BindValue", + "projectedName": "bindValue", + "declaringIid": "95848f9e-583d-4054-af12-916387cd8426", + "absoluteSlot": 3, "signatureFingerprint": "...", "status": "manual_contract_required", "reasons": ["..."], @@ -521,7 +521,7 @@ also returns nonzero. Example output: ```text -[dry-run] Would generate IAudioClientUnsafe (metadata-complete: 8, manual: 4, blocked: 0) +[dry-run] Would generate IWinMLEvaluationContextUnsafe (metadata-complete: 1, manual: 2, blocked: 0) [dry-run] Report-only MFASYNCRESULTUnsafe {"metadataComplete":0,"manual":0,"blocked":5,"reasons":["missing_interface_iid"]} ``` @@ -659,7 +659,8 @@ Required tests include: 13. actual Node resolution of mixed WinRT, COM barrel, and unsafe canonical package exports. -The generated-artifact integration fixture combines safe WMI with unsafe Audio. +The generated-artifact integration fixture combines safe WMI, IDataObject, and +IAudioClient projections with an unsafe WinML companion. The complete seven-method WMI conditional-output family executes through a complete official `IWbemServices_Vtbl`. ABI-correct `IWbemClassObject` and `IWbemCallResult` tear-offs expose canonical IUnknown identity and shared @@ -674,12 +675,11 @@ a fake COM object that returns a real HBITMAP. It validates transfer into `DynComOwnedHandle`, explicit `DeleteObject` release, idempotence, and COM reference balance; a Rust regression separately covers the Drop path. -The unsafe portion uses official `IAudioClientUnsafe::isFormatSupported` and -`getService` vtable slots. It covers -CoTaskMem closest-format success/failure cleanup, BSTR/Local/Global dirty -failure cleanup, COM-owned output cleanup, required/nullable output, strategy -mismatch before dispatch, one-shot reuse, handle/raw/count strategies, and all -three interface-replacement modes. +The unsafe portion uses official +`IWinMLEvaluationContextUnsafe::bindValue` and `getValueByName` vtable slots. +It covers CoTaskMem/BSTR/Local/Global dirty failure cleanup, COM-owned output +cleanup, required/nullable output, strategy mismatch before dispatch, one-shot +reuse, handle/raw/count strategies, and all three interface-replacement modes. ## Rollout plan diff --git a/docs/architecture/classic-com-raw-unsafe.md b/docs/architecture/classic-com-raw-unsafe.md index 9718f424..07102aae 100644 --- a/docs/architecture/classic-com-raw-unsafe.md +++ b/docs/architecture/classic-com-raw-unsafe.md @@ -606,8 +606,8 @@ does not mutate persistent system state. ### Final Phase 1 outbound matrix The matrix uses real synchronous fake vtables and the exact Windows -`extern "system"` ABI. It proves raw reach; none of these interfaces become -safe-generated: +`extern "system"` ABI. It proves raw reach independently of later safe +promotion: | Scenario | Verified raw contract | | ------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | @@ -632,8 +632,9 @@ runtime gate. Public consumption examples live in `bindings/js/__test__/raw-phase1.spec.ts`. This provides broad in-process, current-apartment, outbound raw COM coverage -for completed scalar, pointer, memory, and struct contracts. It does not make -`IDataObject`, `IAudioClient`, private-data APIs, or WMI safe-generated. +for completed scalar, pointer, memory, and struct contracts. Later dedicated +semantic models make `IDataObject`, `IAudioClient`, and WMI safe-generated; +private-data APIs remain unsafe because their payload ownership is ambiguous. Phase 1 can be called complete for the documented in-process, current-apartment, outbound raw ABI subset on x64 and i686. The precise ABI diff --git a/docs/architecture/classic-com-support.md b/docs/architecture/classic-com-support.md index c8484b27..5c8dc3cb 100644 --- a/docs/architecture/classic-com-support.md +++ b/docs/architecture/classic-com-support.md @@ -4,8 +4,8 @@ general Automation or native Win32 projection. > **Status: preview, under active development.** The current CI baseline against -> `Microsoft.Windows.SDK.Win32Metadata` 71.0.14-preview is 5,691 complete safe -> interface projections out of 7,929 eligible interfaces (71.77%). Earlier +> `Microsoft.Windows.SDK.Win32Metadata` 71.0.14-preview is 5,696 complete safe +> interface projections out of 7,929 eligible interfaces (71.84%). Earlier > inventory and demand-snapshot sections retain the metadata versions and dates > stated in those sections. @@ -614,6 +614,7 @@ and `@microsoft/dynwinrt/com`. | SAFEARRAY | Rank 1–8, signed bounds, typed scalar/bool/BSTR/interface/VARIANT elements, SafeArray API validation and cleanup | Unsupported element VARTYPEs, rank > 8, untyped arrays whose VARTYPE cannot be proven, and Automation InOut replacement | | PROPVARIANT | Scalar numeric/bool, LPWSTR, CLSID, FILETIME, blob, and supported vectors with PropVariantClear | Nested VARIANT vectors, streams/interfaces, arrays, clipboard/storage types, BYREF, and unknown VARTYPEs | | FORMATETC / STGMEDIUM | Dedicated target-device-independent `TYMED_HGLOBAL` values; owned outputs use `ReleaseStgMedium`; exact `IDataObject::GetDataHere` evidence permits caller-allocation-preserving InOut; exact IID/slot/shape/fingerprint evidence pins `SetData.fRelease=FALSE` | `DVTARGETDEVICE`, non-HGLOBAL media, unproven InOut contracts, JavaScript callback implementation, and ownership-transfer input | +| Audio formats | Variable-length WAVEFORMATEX/WAVEFORMATEXTENSIBLE bytes with validated `cbSize`; PCM factory; exact shared/exclusive `IsFormatSupported` output selection; CoTaskMem-owned format outputs; exact nullable device-control `Record` inputs | Format-specific codec payload interpretation and JavaScript callback implementation | | Allocator ownership | COM Release, BSTR output/replacement and array elements, VARIANT clear, CoTaskMem buffers/PWSTR elements, boxed GUID, retained JS buffers | LocalFree, custom allocators, allocator interfaces, unknown ownership | | Interface pointers | Typed input/output interfaces, QueryInterface, dynamic IID output, and generated multi-interface callback objects with inherited IID aliases | Interface in/out replacement, aggregation, and `IInspectable` implementation | | Apartments | Explicit initialization, non-agile owner-thread implementations, synchronous same-thread callbacks, and rejection before entering JS on a foreign thread | Cross-apartment marshaling, GIT/agility handling, and callback dispatch | @@ -659,6 +660,7 @@ and `@microsoft/dynwinrt/com`. | SAFEARRAY | Supported subset | `DynComSafeArray` preserves rank/bounds and validates VARTYPE and element width through SafeArray APIs. Supported elements are the scalar integer/float family, VARIANT_BOOL, BSTR, IUnknown, IDispatch, and VARIANT. | | PROPVARIANT | Supported subset | `DynComPropVariant` supports the scalar family, LPWSTR, CLSID, FILETIME, BLOB, and vectors of numeric/bool/string/GUID/FILETIME elements. | | FORMATETC / STGMEDIUM | Supported HGLOBAL subset | `DynComFormatEtc.hglobal()` represents one exact DVASPECT with `ptd == NULL`; `DynComStgMedium.hglobal()` copies bytes into call-local movable HGLOBAL storage. Outputs are copied before `ReleaseStgMedium`, `GetDataHere` rejects replacement of caller-owned storage, and generated `IDataObject::SetData` and `IOleCache::SetData` (including `IOleCache2`) fix `fRelease` to `FALSE`. | +| WAVEFORMATEX / WAVEFORMATEXTENSIBLE | Supported | `DynComAudioFormat` validates the packed 18-byte header plus exact `cbSize` extension, provides a PCM factory and field accessors, and preserves unknown codec extension bytes. Exact contracts pass `IsFormatSupported.ppClosestMatch` only in shared mode and free GetMixFormat/current-engine-format outputs with `CoTaskMemFree`. The two device-control `Record` methods accept an explicit format or `null` for the device default. | | DISPPARAMS / EXCEPINFO | Supported for `IDispatch::Invoke` | `DynComDispatchParams` accepts natural-order `DynComVariant[]` plus optional named DISPIDs. `DynComExcepInfo` exposes code/source/description/helpFile/helpContext/scode. Optional Invoke outputs pass native null when not requested. | | Typed interface parameters and outputs | Supported | Interface outputs carry an owned COM reference. | | Opaque pointers and handle-shaped typedefs | Supported with limits | They are pointer values, not COM objects. Cleanup remains type-specific. | @@ -680,6 +682,13 @@ and `@microsoft/dynwinrt/com`. | Dynamic-IID `void**` outputs | Supported for explicit required REFIID shapes | The method must return ordinary HRESULT and contain exactly one required const `GUID*` named `iid`/`riid` plus one required mutable `void**`/Object** output with +1 COM ownership. Their explicit parameter indices may be non-adjacent/non-terminal. Optional, duplicate, array, FreeWith, InOut, by-value/mutable/deeper GUID, and wrong-depth output shapes fail closed. | | Explicit apartment initialization | Supported | `initializeCom()` never silently chooses an apartment for the caller. | +`IMDSPDeviceControl::Record` and `IWMDMDeviceControl::Record` have exact +nullable audio-input contracts. Their declarations accept +`DynComAudioFormat | null`, the COM signature retains input nullability, and +the executor passes a native NULL without constructing a dummy format. +Required inputs such as `IAudioClient::Initialize` and `IsFormatSupported` +remain non-nullable; unknown or drifted Record evidence fails generation. + `IDataObject::GetCanonicalFormatEtc` has a separate result contract. For `S_OK`, the runtime ignores the native output's `tymed` and retains the caller's supported transfer medium while decoding the remaining canonical fields. @@ -730,7 +739,7 @@ of every type in the 24 MB metadata file. | Unsupported BSTR pointer nesting, replacement arrays, or callee-allocated outer arrays | Automation collection APIs | Exact counted input/caller-output BSTR arrays are supported; deeper/replacement shapes still require authoritative outer allocation and per-element contracts. | Win32 winmd signature + ownership analysis | | Caller-owned ANSI output buffers | `PSTR` output-buffer APIs | Safe sizing and decoding are not yet projected. | Win32 winmd signature + projection limitation | | Private-data bytes or interface pointer | `IDXGIObject`, `ID3D10DeviceChild`, `ID3D10Device`, `ID3D11DeviceChild`, `ID3D11Device`, `ID3D12Object`, and `IDMLObject` `GetPrivateData` | The same GUID-keyed method may return ordinary bytes or an AddRef'd interface pointer. A `Buffer` projection would lose the interface ownership transfer; Direct3D 10 NULL calls are destructive, and DXGI's data parameter is required. | Exact Win32 winmd identities + Microsoft method documentation | -| Untyped output pointers without allocator/ownership | `IAudioClient::IsFormatSupported` and unrelated `void*` outputs | The runtime cannot infer whether the result is borrowed, COM-owned, `CoTaskMem`, or another allocator. | Win32 winmd + codegen diagnostics | +| Untyped output pointers without allocator/ownership | Unrelated `void*` outputs | The runtime cannot infer whether the result is borrowed, COM-owned, `CoTaskMem`, or another allocator. Audio-format outputs are supported only for exact pinned methods. | Win32 winmd + codegen diagnostics | | Interface `[in, out]` ownership | Generic typed `IFoo**` InOut parameters | Replacing an existing interface pointer requires explicit release/AddRef transfer semantics. `IWbemServices::OpenNamespace` is not in this category: exact SDK evidence corrects its two flags to Out. | Win32 winmd + codegen diagnostic | | Callback methods outside the validated implementation subset | Automation providers, custom marshaling, and resource-owning callbacks | The dynamic backend supports broad scalar/string/POD/buffer ABI shapes and multi-interface inheritance, but VARIANT/SAFEARRAY/PROPVARIANT callbacks, untagged unions, unknown pointers/allocators, interface replacement, and custom marshal contracts still fail the whole interface closed. | Runtime/codegen validation boundary | | COM aggregation | `IClassFactory::CreateInstance` with `pUnkOuter` | The public activation helper always creates a non-aggregated in-process object. | Runtime/public-API boundary | @@ -1245,12 +1254,14 @@ registries subsequently promote 114 additional complete interfaces, bringing that census to 5,681. The dedicated target-device-independent `TYMED_HGLOBAL` FORMATETC/STGMEDIUM model promotes 10 more interfaces after restricting InOut to proven caller-allocation-preserving contracts, bringing -the current literal census to **5,691 / 7,929 = 71.774499%**. The result remains -above the 70% target without admitting any unmodeled target-device, storage -medium, ownership-transfer, or callback shape. +that census to 5,691. The variable-length WAVEFORMATEX model and three pinned +audio method contracts promote five more interfaces, bringing the current +literal census to **5,696 / 7,929 = 71.837558%**. The result remains above the +70% target without admitting any unmodeled target-device, storage-medium, +audio-output ownership, ownership-transfer, or callback shape. CI reproduces this number with `dynwinrt-codegen com-census --json` and fails -if the denominator changes, complete generation drops below 5,691, or coverage +if the denominator changes, complete generation drops below 5,696, or coverage falls below 70%. ## Public-code frequency snapshot @@ -1319,7 +1330,7 @@ against the resolved namespace. | 21 | `IBindCtx` | 2,660 | 42 | Yes | Generates with exact `BIND_OPTS.cbStruct = sizeof(BIND_OPTS)` initialization and live `CreateBindCtx` coverage | | 22 | `IFileOpenDialog` | 2,536 | 92 | Yes | Generates and live-tested without showing UI | | 23 | `IRunningObjectTable` | 2,532 | 50 | Yes | Generates with POD `FILETIME`; acquisition/live test still needed | -| 24 | `IAudioClient` | 2,500 | 82 | Yes | Fail closed: format pointer/output ownership | +| 24 | `IAudioClient` | 2,500 | 82 | Yes | Generates completely with typed variable-length audio formats and exact IsFormatSupported/GetMixFormat ownership | | 25 | `IShellLinkW` | 2,128 | 67 | Yes | Generates and is live-tested with nested/fixed-array POD `WIN32_FIND_DATAW` | | 26 | `ITaskbarList3` / `TaskbarList` | 1,672 | 87 | Yes | Interface and newable coclass generate and are live-tested | | 27 | `ICoreWebView2` | 1,608 | 35 | **No** | Defined in WebView2 metadata, not Windows.Win32.winmd | @@ -1341,7 +1352,7 @@ against the resolved namespace. and non-HGLOBAL data-transfer media); - Automation contracts beyond the exact supported `IDispatch` compounds (XML and Task Scheduler BYREF/InOut and nested ownership); - - explicit output ownership (`DXGI`, audio); + - explicit output ownership (notably DXGI/private-data APIs); - remaining interface in/out replacement semantics; and - unsupported PROPVARIANT alternatives in Property System APIs beyond `IPropertyStore`. @@ -1353,7 +1364,7 @@ against the resolved namespace. This means the current suite provides useful ABI breadth, but it does **not** cover every high-frequency interface. In particular, -graphics interfaces, audio, non-HGLOBAL data transfer, and live real-object +graphics interfaces, advanced audio, non-HGLOBAL data transfer, and live real-object `IDispatch::Invoke` coverage remain material gaps. ## Engineering priority map @@ -1383,7 +1394,7 @@ hardware, and whether it adds a distinct ABI shape. | `ICreateErrorInfo` / `IErrorInfo` | COM rich error information | Complete generation and acquisition are live-tested for GUID, wide strings, owned BSTR output, thread-local storage, and one-shot consumption. | | `IMMDeviceEnumerator` | Audio endpoint discovery | Generates today, but live behavior depends on available audio endpoints. | | `IWbemServices` | WMI queries and method invocation | Complete generation uses exact sync/semisync output selection; selected outputs are owned COM references and `pCtx` is native null in the closed safe overloads. | -| `IAudioClient` | Low-level audio streaming | Fails closed because its format and output-pointer shapes are not fully modeled. | +| `IAudioClient` / `IAudioClient2` / `IAudioClient3` | Low-level audio streaming | Complete safe generation uses `DynComAudioFormat`; exact fingerprinted contracts model shared/exclusive closest-format selection and CoTaskMem-owned format outputs. Generated fake-vtable coverage is hardware-independent. | | `IDispatch` | Automation and scripting | Complete inherited real-metadata generation passes. `GetIDsOfNames` projects as `string[] -> number[]`; `Invoke` accepts `DynComDispatchParams` and explicit result/excepInfo/argErr request options, returning dedicated owning wrappers. Derived Automation interfaces remain independently validated. | | `IPropertyStore` | Shell/property metadata | Complete generation and live ShellLink `SetValue`/`GetValue`/`Commit` coverage pass with dedicated PROPVARIANT ownership. | | `IDataObject` | Clipboard and drag-and-drop | Complete safe generation for target-device-independent `TYMED_HGLOBAL`; generated fake-vtable coverage verifies owned GetData output, caller-owned GetDataHere storage, semantic HRESULT, canonical FORMATETC, and borrowed SetData input. | diff --git a/docs/guides/windows/classic-com-usage.md b/docs/guides/windows/classic-com-usage.md index a3a1b6d8..6f7895d9 100644 --- a/docs/guides/windows/classic-com-usage.md +++ b/docs/guides/windows/classic-com-usage.md @@ -144,52 +144,43 @@ remain intact. The ordinary command has no unsafe opt-in flag. If complete safe projection fails but one or more methods are `raw_metadata_complete`, codegen writes an isolated namespace-qualified companion such as -`generated/com/unsafe/windows/win32/media/audio/IAudioClientUnsafe.js` and +`generated/com/unsafe/windows/win32/ai/machine-learning/win-ml/IWinMLEvaluationContextUnsafe.js` +and records every method in `support.json`. Safe-complete interfaces use matching canonical namespace directories under `generated/com/`. ```powershell npx dynwinrt-codegen generate ` --winmd $winmd ` - --namespace Windows.Win32.Media.Audio ` - --class-name IAudioClient ` + --namespace Windows.Win32.AI.MachineLearning.WinML ` + --class-name IWinMLEvaluationContext ` --output .\generated ``` -`IAudioClientUnsafe` hides IID registration, inheritance, absolute slots, and -signature wiring while keeping unknown format/storage ownership explicit: +`IWinMLEvaluationContextUnsafe` hides IID registration, inheritance, absolute +slots, and signature wiring while keeping unknown descriptor layout and +ownership explicit: ```js +import { DynComRawMemory } from "@microsoft/dynwinrt/com/unsafe/raw"; import { - DynComRawMemory, -} from "@microsoft/dynwinrt/com/unsafe/raw"; -import { - IAudioClientUnsafe, + IWinMLEvaluationContextUnsafe, UnsafePointee, - UnsafePointerOutput, } from "./generated/com/unsafe/index.js"; -const audio = IAudioClientUnsafe.from(existingAudioClientValue); -const format = DynComRawMemory.allocate(18, 2); +const context = IWinMLEvaluationContextUnsafe.from(existingContextValue); +const descriptor = DynComRawMemory.allocate(descriptorSize, descriptorAlignment); try { - const [hresult, closest] = audio.isFormatSupported( - 1, - UnsafePointee.required(format), - UnsafePointerOutput.coTaskMem(), - ); - try { - // Inspect the explicitly owned closest-format result. - } finally { - closest?.release(); - } + context.bindValue(UnsafePointee.required(descriptor)); } finally { - format.release(); - audio.release(); + descriptor.release(); + context.release(); } ``` -The short barrel export is available only while `IAudioClientUnsafe` is -globally unique. If two namespaces contain `IFoo`, import their deep modules: +The short barrel export is available only while +`IWinMLEvaluationContextUnsafe` is globally unique. If two namespaces contain +`IFoo`, import their deep modules: ```js import { IFooUnsafe as FooA } from "./generated/com/unsafe/contoso/a/IFooUnsafe.js"; @@ -203,36 +194,49 @@ and cleanup rules against the native contract. A failing HRESULT may throw after native code has mutated caller-owned slots; inspect and reconcile such storage according to the API contract. See the [complete generated unsafe examples](generated-com-unsafe-example.zh-CN.md) for -synchronous/semisynchronous WMI and manual-contract audio calls. +synchronous/semisynchronous WMI and manual-contract raw calls. Stage 2 also emits `raw_manual_contract` methods with required strategies from -`generated/com/unsafe/runtime.js`. For audio format negotiation: +`generated/com/unsafe/runtime.js`. A pointer output with unknown ownership +remains caller-selected and explicit: ```js import { - IAudioClientUnsafe, - UnsafePointee, + IWinMLEvaluationContextUnsafe, UnsafePointerOutput, } from "./generated/com/unsafe/index.mjs"; -const format = DynComRawMemory.allocate(22, 2); -// Fill the exact WAVEFORMATEX bytes first. -const [status, closest] = audio.isFormatSupported( - shareMode, - UnsafePointee.required(format), - // S_OK leaves ppClosestMatch null; S_FALSE may return CoTaskMem storage. - UnsafePointerOutput.coTaskMem(null, true), +const context = IWinMLEvaluationContextUnsafe.from(existingContextValue); +const output = context.getValueByName( + nameStorage, + UnsafePointerOutput.rawResponsibility(), ); try { - const closestView = closest?.view(closestByteLength, closestAlignment); - // Interpret only the layout guaranteed by the selected audio contract. - closestView?.release(); + // Reconcile and clean up `output` only according to the application's + // authoritative contract. The unsafe wrapper does not guess an allocator. } finally { - closest?.release(); - format.release(); + context.release(); } ``` +Audio format negotiation is now on the safe surface: + +```js +import { DynComAudioFormat } from "@microsoft/dynwinrt/com"; +import { IAudioClient } from "./generated/com/windows/win32/media/audio/IAudioClient.js"; + +const audio = IAudioClient._fromNative(existingAudioClientValue); +const pcm = DynComAudioFormat.pcm(2, 48_000, 16); +const [status, closest] = audio.isFormatSupported(0, pcm); +const mixFormat = audio.getMixFormat(); +``` + +For `IMDSPDeviceControl` and `IWMDMDeviceControl`, `record(null)` selects the +device's default recording format after the required capability and seek +setup. `record(pcm)` supplies an explicit format. This nullable contract does +not apply to `IAudioClient.initialize` or `isFormatSupported`, whose format +inputs remain required. + `IDXGIObjectUnsafe.getPrivateData` keeps its exact caller-storage API because metadata proves the ABI but not whether the payload is bytes or an AddRef'd interface. Pass ordinary bounded memory for bytes. For an interface payload, diff --git a/docs/status/CLASSIC_COM_API_SUPPORT_PLAN.md b/docs/status/CLASSIC_COM_API_SUPPORT_PLAN.md index 14a4b760..d91b109e 100644 --- a/docs/status/CLASSIC_COM_API_SUPPORT_PLAN.md +++ b/docs/status/CLASSIC_COM_API_SUPPORT_PLAN.md @@ -32,15 +32,15 @@ B64EE4818A7ED9F9D135038D58C51BD08369184D4D5ED428F20E9DE55DF8121D | Result | Interfaces | Percentage | | ---------------------------------------------------- | ---------: | ---------: | | Externally addressable Classic COM interfaces | 7,929 | 100% | -| Complete safe generation | 5,691 | 71.77% | -| Rejected because at least one contract is incomplete | 2,238 | 28.23% | +| Complete safe generation | 5,696 | 71.84% | +| Rejected because at least one contract is incomplete | 2,233 | 28.16% | The denominator contains addressable COM interface identities, not flat Win32 DLL exports. A complete interface means that its full inherited vtable can be generated without guessing ABI, layout, count relationships, ownership, or cleanup. -The 5,691 figure is semantic codegen coverage, not a claim that every interface +The 5,696 figure is semantic codegen coverage, not a claim that every interface has a dedicated live Windows test or can be activated on every machine. Reproduce the census with: @@ -129,7 +129,6 @@ implementation, aggregation, or custom marshaling. | API or family | Current blocker | Raw direction | | ---------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | | Non-HGLOBAL/device-specific clipboard and drag-and-drop | `DVTARGETDEVICE` and the remaining `STGMEDIUM` alternatives have distinct layout and release rules. | Opaque aligned storage and explicit type-specific cleanup until each semantic alternative exists. | -| `IAudioClient` format negotiation | Variable audio-format layouts and untyped CoTaskMem output. | Raw format memory plus pointer output; later add a typed audio-format value. | | DXGI/D3D `GetPrivateData` | The same payload may be bytes or an AddRef'd interface pointer. | Caller-selected byte storage or pointer slot with explicit adoption. | | Generic typed interface `InOut` | Replacing an interface pointer requires explicit old/new reference transfer. | `UnsafeInterfaceReplacement` with one independent `+1` owner per slot. | | Advanced Automation | BYREF VARIANTs, additional alternatives, replacement arrays, and nested ownership are incomplete. | Raw storage can expose ABI reach; safe support still requires dedicated value and cleanup models. | @@ -279,10 +278,11 @@ conflicts, transaction-residue names, and unsupported reparse tags fail closed. Safe and unsafe modules use the canonical lowercase/kebab namespace layout, for example `com/windows/win32/ui/shell/ITaskbarList3.js` and -`com/unsafe/windows/win32/media/audio/IAudioClientUnsafe.js`. The short class -name remains `IAudioClientUnsafe`. A short barrel export is emitted only when -globally unique; ambiguous names are available only through deep modules, and -incremental order does not affect the resulting barrel. +`com/unsafe/windows/win32/ai/machine-learning/win-ml/IWinMLEvaluationContextUnsafe.js`. +The short class name remains `IWinMLEvaluationContextUnsafe`. A short barrel +export is emitted only when globally unique; ambiguous names are available only +through deep modules, and incremental order does not affect the resulting +barrel. Generated and retained paths share an ASCII case-folded Windows identity. Traversal, rooted/drive paths, trailing dots/spaces, reserved device names, and @@ -290,13 +290,14 @@ case-only namespace/type collisions fail closed. Existing cross-root shared ownership additionally requires the staged file to exist and exactly match the planned bytes before overwrite. -CI also generates the real official safe `IWbemServices` wrapper and -`IAudioClientUnsafe` companion. The WMI test object uses the official -`IWbemServices_Vtbl` through slot 25 and ABI-correct `IWbemClassObject` and -`IWbemCallResult` tear-offs with one canonical IUnknown and shared reference -counting. Generated calls execute both tear-off interfaces without requiring a -live WMI service while testing the actual generated CJS, ESM, and declaration -artifacts. +CI also generates real official safe `IWbemServices`, `IDataObject`, and +`IAudioClient` wrappers plus an `IWinMLEvaluationContextUnsafe` companion. The +WMI test object uses the official `IWbemServices_Vtbl` through slot 25 and +ABI-correct `IWbemClassObject` and `IWbemCallResult` tear-offs with one +canonical IUnknown and shared reference counting. The test hooks also validate +conditional output selection, data/audio storage cleanup, raw pointer-slot +mutation, CJS, ESM, and declarations without requiring live WMI or audio +hardware. Generated companions are outbound only. They do not infer output ownership, provide callbacks or `implement()`, solve acquisition or apartment transfer, or @@ -342,11 +343,11 @@ versus 16 (`WBEM_FLAG_RETURN_IMMEDIATELY`), adopt the requested non-null `+1`, a release dirty failure output. Generic interface InOut parameters remain manual replacement contracts. -**1,433 of 1,437** x64 manual-contract interfaces now have at least one portable -executable generated high-level method. **1,432** have an executable manual +**1,428 of 1,432** x64 manual-contract interfaces now have at least one portable +executable generated high-level method. **1,427** have an executable manual method, one retains only metadata-complete methods, and four have no portable executable method because every candidate is blocked on another generated -target. Across the portable generated surface there are **6,067 executable +target. Across the portable generated surface there are **6,048 executable manual methods**, **0 remaining portable manual-classified methods omitted**, and **1,161 runtime-blocked methods** still omitted. @@ -354,20 +355,20 @@ and **1,161 runtime-blocked methods** still omitted. Stage 1 of the [Classic COM contract evidence registry](../architecture/classic-com-contract-evidence-registry.md) -classifies all 5,691 safe-complete interfaces exactly once: +classifies all 5,696 safe-complete interfaces exactly once: | Evidence class | Interfaces | | --- | ---: | | `standard_derived` | 5,333 | -| `exact_registry_dependent` | 358 | +| `exact_registry_dependent` | 363 | -The registry declares 499 selector-specific entries; all 499 match pinned -metadata, 408 distinct entries are safe-consumed, and safe plans contain 660 -entry/interface plus 408 family/interface dependencies. They also consume -5,976 metadata-attribute and 26,114 universal COM-rule dependency sets. +The registry declares 504 selector-specific entries; all 504 match pinned +metadata, 413 distinct entries are safe-consumed, and safe plans contain 669 +entry/interface plus 416 family/interface dependencies. They also consume +5,982 metadata-attribute and 26,129 universal COM-rule dependency sets. Entry/interface dependencies by kind are SAFEARRAY 263, enumerator-next 74, -borrowed-handle 54, ownership 176, parameter-direction 45, bounded-two-call 16, -counted-buffer 16, conditional-output 7, flag-selected-buffer 3, null-input 2, +borrowed-handle 54, ownership 180, parameter-direction 45, bounded-two-call 16, +counted-buffer 16, conditional-output 10, flag-selected-buffer 3, null-input 4, semantic-HRESULT 3, and compound-dispatch 1. Complete per-entry status, per-family rollups, and per-interface entry IDs are retained in the summary and interface CSV. @@ -378,6 +379,14 @@ entries remain typed COM standard rules. Twenty-five safe interfaces consume the generic enumerator rule because one contract is inherited. ISequentialStream `Read`/`Write` and IDispatch `Invoke` are distinct exact entries with full selectors, fingerprints, and citations. +`IAudioClient::IsFormatSupported` adds an exact shared/exclusive conditional +output contract, while `GetMixFormat` and +`IAudioClient3::GetCurrentSharedModeEnginePeriod` add exact CoTaskMem-owned +variable-format outputs. +The two device-control `Record` methods have separate exact nullable-input +contracts: `null` selects the device default format without allocating a +placeholder WAVEFORMATEX. Other audio-format inputs remain required. + The storage-medium contracts also pin `IOleCache::SetData` (including inherited `IOleCache2` calls) to caller-retained ownership and describe the distinct `IDataObject::GetCanonicalFormatEtc` success/result semantics. @@ -401,18 +410,18 @@ allocator, or ownership declaration can corrupt memory or crash the process. For `Microsoft.Windows.SDK.Win32Metadata` 71.0.14-preview (`Windows.Win32.winmd` SHA-256 `B64EE4818A7ED9F9D135038D58C51BD08369184D4D5ED428F20E9DE55DF8121D`), -the safe census is 5,691 of 7,929 interfaces. The separate outbound raw census -classifies the 2,238 safe-incomplete interfaces as: +the safe census is 5,696 of 7,929 interfaces. The separate outbound raw census +classifies the 2,233 safe-incomplete interfaces as: | Target | Metadata-complete | Manual contract | Runtime-blocked | | ------ | ----------------: | --------------: | --------------: | -| x64 | 412 | 1,437 | 389 | -| i686 | 411 | 1,414 | 413 | -| ARM64 | 412 | 1,437 | 389 | +| x64 | 412 | 1,432 | 389 | +| i686 | 411 | 1,409 | 413 | +| ARM64 | 412 | 1,432 | 389 | -Including safe-complete interfaces, x64 and ARM64 have 6,103 -metadata-complete, 1,437 manual, and 389 blocked interfaces. i686 has 6,102 -metadata-complete, 1,414 manual, and 413 blocked interfaces. +Including safe-complete interfaces, x64 and ARM64 have 6,108 +metadata-complete, 1,432 manual, and 389 blocked interfaces. i686 has 6,107 +metadata-complete, 1,409 manual, and 413 blocked interfaces. Pointer-shaped types are analyzed recursively. A missing pointee layout for an external input pointer is manual-contract; the same missing layout for a @@ -422,14 +431,14 @@ writable/readable `T*` caller-storage contract is runtime-blocked. Thus layout is complete. Cleanup availability is no longer represented by ambiguous booleans. Per -target, 2,237 interfaces require no cleanup, 4,530 use a Phase 1 standard -cleanup, none use a known external cleanup, and 1,162 have unknown cleanup. +target, 2,237 interfaces require no cleanup, 4,533 use a Phase 1 standard +cleanup, none use a known external cleanup, and 1,159 have unknown cleanup. Every missing output ownership/allocator contract has `cleanup_unknown`. External pointer/callback requirements affect 1,089 x64/ARM64 interfaces and 1,090 i686 interfaces; 6,804 require external acquisition and all 7,929 retain the current-apartment rule. -For all 5,691 safe-complete interfaces, cleanup is derived from the validated +For all 5,696 safe-complete interfaces, cleanup is derived from the validated projected result conversions rather than the raw analyzer. Pure values, borrowed handles, caller buffers, and plain arrays are `none_required`. Managed COM/dynamic-IID adoption, BSTR, HSTRING, CoTaskMem, VARIANT, @@ -516,7 +525,7 @@ as ABI support. The legacy `com-census --json` output remains unchanged. ## Copyable user-facing statement > dynwinrt supports the Classic COM interface portion of Windows.Win32 -> metadata. With Win32Metadata 71.0.14-preview, 5,691 of 7,929 addressable COM +> metadata. With Win32Metadata 71.0.14-preview, 5,696 of 7,929 addressable COM > interfaces pass complete safe generation. Safe symbols never fall back to an > unsafe implementation; ordinary generation may instead emit an explicitly > named `*Unsafe` outbound companion containing only metadata-complete methods. diff --git a/docs/status/generated/classic-com-capability-summary.json b/docs/status/generated/classic-com-capability-summary.json index 9332ea9c..622aa102 100644 --- a/docs/status/generated/classic-com-capability-summary.json +++ b/docs/status/generated/classic-com-capability-summary.json @@ -80,34 +80,35 @@ "parsed_interface_identities": 7944, "eligible_interfaces": 7929, "not_addressable": 15, - "safe_complete": 5691, - "safe_incomplete": 2238, + "safe_complete": 5696, + "safe_incomplete": 2233, "safeEvidence": { - "safeComplete": 5691, + "safeComplete": 5696, "standardDerived": 5333, - "exactRegistryDependent": 358, - "metadataFactOccurrences": 5976, - "comStandardFactOccurrences": 26114, - "registeredExactEntries": 499, - "metadataMatchedExactEntries": 499, - "safeConsumedExactEntries": 408, - "exactEntryInterfaceDependencies": 660, - "exactFamilyInterfaceDependencies": 408, + "exactRegistryDependent": 363, + "metadataFactOccurrences": 5982, + "comStandardFactOccurrences": 26129, + "registeredExactEntries": 504, + "metadataMatchedExactEntries": 504, + "safeConsumedExactEntries": 413, + "exactEntryInterfaceDependencies": 669, + "exactFamilyInterfaceDependencies": 416, "byContractKind": { "borrowed-handle": 54, "bounded-two-call": 16, "compound-dispatch": 1, - "conditional-output": 7, + "conditional-output": 10, "counted-buffer": 16, "enumerator-next": 74, "flag-selected-buffer": 3, - "null-input": 2, - "ownership": 176, + "null-input": 4, + "ownership": 180, "parameter-direction": 45, "safearray": 263, "semantic-hresult": 3 }, "byEntryId": { + "audio.conditional-output.entry.windows-win32-media-audio.iaudioclient.1cb9ad4cdbfa4c32b178c2f568a703b2.isformatsupported.slot-7.v1": 3, "automation.idispatch-invoke.entry.windows-win32-system-com.idispatch.0002040000000000c000000000000046.invoke.slot-6.v1": 1, "automation.safearray.entry.windows-win32-media-directshow-tv.iesisdbcasresponseevent.2017cb03dc0f4c2483ca36307b2cd19f.getresponsedata.slot-11.param-0-pbdata.v1": 1, "automation.safearray.entry.windows-win32-media-directshow-tv.ieslicenserenewalresultevent.d5a48ef5a81b4df0acaa5e35e7ea45d4.getentitlementtoken.slot-17.param-0-pbdata.v1": 1, @@ -367,11 +368,15 @@ "com.enumerator-next-exception.entry.windows-win32-ui-textservices.ienumtfproperties.19188cb0aca911d2afc500105a2799b5.next.slot-4.v1": 1, "com.enumerator-next-exception.entry.windows-win32-ui-textservices.ienumtfranges.f99d3f408e3211d2bf4600105a2799b5.next.slot-4.v1": 1, "com.enumerator-next-exception.entry.windows-win32-ui-textservices.ienumtfuielements.887aa91eacba493184da3c5208cf543f.next.slot-4.v1": 1, + "com.nullable-input.entry.windows-win32-media-devicemanager.imdspdevicecontrol.1dcb3a1433ed11d3847000c04f79dbc0.record.slot-6.v1": 1, + "com.nullable-input.entry.windows-win32-media-devicemanager.iwmdmdevicecontrol.1dcb3a0433ed11d3847000c04f79dbc0.record.slot-6.v1": 1, "com.ownership.entry.windows-win32-devices-tapi.itcallinfo.350f85d1122711d383d400c04fb6809f.getcallinfobuffer.slot-17.param-2-ppcallinfobuffer.v1": 2, "com.ownership.entry.windows-win32-devices-tapi.itlegacycallmediacontrol.d624582fcc234436b8a547c625c8045d.getid.slot-9.param-2-ppdeviceid.v1": 2, "com.ownership.entry.windows-win32-graphics-direct3d-dxc.idxcversioninfo2.fb6904c442f04b629c46983af7da7c83.getcommitinfo.slot-5.param-1-pcommithash.v1": 1, "com.ownership.entry.windows-win32-graphics-direct3d-dxc.idxcversioninfo3.5e13e8439d25473c9ad203b2d0b44b1e.getcustomversionstring.slot-3.param-0-pversionstring.v1": 1, "com.ownership.entry.windows-win32-media-audio-apo.iaudiosystemeffectscustomformats.b1176e34bb7f4f05bebd1b18a534e097.getformatrepresentation.slot-5.param-1-ppwstrformatrep.v1": 1, + "com.ownership.entry.windows-win32-media-audio.iaudioclient.1cb9ad4cdbfa4c32b178c2f568a703b2.getmixformat.slot-8.v1": 3, + "com.ownership.entry.windows-win32-media-audio.iaudioclient3.7ed4ee078e674cd48c1a2b7a5987ad42.getcurrentsharedmodeengineperiod.slot-19.v1": 1, "com.ownership.entry.windows-win32-media-audio.iaudioeffectsmanager.4460b3ae4b44452786767548a8acd260.getaudioeffects.slot-5.param-0-effects.v1": 1, "com.ownership.entry.windows-win32-media-audio.iaudiosessioncontrol.f4b1a59972664319a8cae70acb11e8cd.getdisplayname.slot-4.param-0-pretval.v1": 1, "com.ownership.entry.windows-win32-media-audio.iaudiosessioncontrol.f4b1a59972664319a8cae70acb11e8cd.geticonpath.slot-6.param-0-pretval.v1": 1, @@ -518,12 +523,14 @@ "wmi.conditional-output.entry.windows-win32-system-wmi.iwbemservices.9556dc99828c11cfa37e00aa003240c7.putinstance.slot-14.v1": 1 }, "byFamilyId": { + "audio.conditional-output.v1": 3, "automation.idispatch-invoke.v1": 1, "automation.safearray.v1": 121, "buffers.bounded-two-call.v1": 16, "buffers.counted-buffer.v1": 2, "com.enumerator-next-exception.v1": 74, - "com.ownership.v1": 119, + "com.nullable-input.v1": 2, + "com.ownership.v1": 122, "com.parameter-direction.v1": 15, "com.reserved-null-input.v1": 1, "com.semantic-hresult.v1": 3, @@ -533,8 +540,8 @@ "wmi.conditional-output.v1": 1 }, "byMetadataAttribute": { - "CanReturnMultipleSuccessValuesAttribute": 43, - "ConstAttribute": 3328, + "CanReturnMultipleSuccessValuesAttribute": 46, + "ConstAttribute": 3331, "FreeWithAttribute": 3, "NativeArrayInfoAttribute": 2602 }, @@ -544,14 +551,32 @@ "com.automation.bstr-replacement.v1": 99, "com.enumerator-next.generic.v1": 25, "com.handle.borrowed-no-cleanup.v1": 45, - "com.hresult.failure.v1": 5573, + "com.hresult.failure.v1": 5578, "com.interface.input-borrow.v1": 1890, "com.interface.typed-output-plus-one.v1": 3457, - "com.iunknown.identity-refcount.v1": 5691, - "com.query-interface.output-plus-one.v1": 5691, + "com.iunknown.identity-refcount.v1": 5696, + "com.query-interface.output-plus-one.v1": 5696, "com.standard-cleanup.matching-allocator.v1": 1436 }, "exactEntryStatus": { + "audio.conditional-output.entry.windows-win32-media-audio.iaudioclient.1cb9ad4cdbfa4c32b178c2f568a703b2.isformatsupported.slot-7.v1": { + "familyId": "audio.conditional-output.v1", + "contractKind": "conditional-output", + "selector": { + "namespace": "Windows.Win32.Media.Audio", + "interface": "IAudioClient", + "iid": "1cb9ad4c-dbfa-4c32-b178-c2f568a703b2", + "method": "IsFormatSupported", + "slot": 7, + "parameter": null + }, + "sourceFingerprint": "8C96A1A91E80657C730E2729DEBC3B708E7B94CC8CF9BAF2F3FD0348237CB186", + "citation": "https://learn.microsoft.com/windows/win32/api/audioclient/nf-audioclient-iaudioclient-isformatsupported", + "registered": true, + "metadataMatched": true, + "safeConsumed": true, + "interfaceDependencies": 3 + }, "automation.idispatch-invoke.entry.windows-win32-system-com.idispatch.0002040000000000c000000000000046.invoke.slot-6.v1": { "familyId": "automation.idispatch-invoke.v1", "contractKind": "compound-dispatch", @@ -6375,6 +6400,42 @@ "safeConsumed": true, "interfaceDependencies": 1 }, + "com.nullable-input.entry.windows-win32-media-devicemanager.imdspdevicecontrol.1dcb3a1433ed11d3847000c04f79dbc0.record.slot-6.v1": { + "familyId": "com.nullable-input.v1", + "contractKind": "null-input", + "selector": { + "namespace": "Windows.Win32.Media.DeviceManager", + "interface": "IMDSPDeviceControl", + "iid": "1dcb3a14-33ed-11d3-8470-00c04f79dbc0", + "method": "Record", + "slot": 6, + "parameter": null + }, + "sourceFingerprint": "346C3A5C69100EF034C6B1773533C7B9AB74C66F05581FF8D1D02370C9506F52", + "citation": "https://learn.microsoft.com/windows/win32/api/mswmdm/nf-mswmdm-imdspdevicecontrol-record", + "registered": true, + "metadataMatched": true, + "safeConsumed": true, + "interfaceDependencies": 1 + }, + "com.nullable-input.entry.windows-win32-media-devicemanager.iwmdmdevicecontrol.1dcb3a0433ed11d3847000c04f79dbc0.record.slot-6.v1": { + "familyId": "com.nullable-input.v1", + "contractKind": "null-input", + "selector": { + "namespace": "Windows.Win32.Media.DeviceManager", + "interface": "IWMDMDeviceControl", + "iid": "1dcb3a04-33ed-11d3-8470-00c04f79dbc0", + "method": "Record", + "slot": 6, + "parameter": null + }, + "sourceFingerprint": "68EB1BDA9994CE96C21642D9D336EBBF7BC38DD14C04E799A9091025D0D55871", + "citation": "https://learn.microsoft.com/windows/win32/api/mswmdm/nf-mswmdm-iwmdmdevicecontrol-record", + "registered": true, + "metadataMatched": true, + "safeConsumed": true, + "interfaceDependencies": 1 + }, "com.ownership.entry.windows-win32-devices-portabledevices.iportabledevice.625e2df863924cf09ad13cfa5f17775c.getpnpdeviceid.slot-11.param-0-ppszpnpdeviceid.v1": { "familyId": "com.ownership.v1", "contractKind": "ownership", @@ -6543,6 +6604,42 @@ "safeConsumed": true, "interfaceDependencies": 1 }, + "com.ownership.entry.windows-win32-media-audio.iaudioclient.1cb9ad4cdbfa4c32b178c2f568a703b2.getmixformat.slot-8.v1": { + "familyId": "com.ownership.v1", + "contractKind": "ownership", + "selector": { + "namespace": "Windows.Win32.Media.Audio", + "interface": "IAudioClient", + "iid": "1cb9ad4c-dbfa-4c32-b178-c2f568a703b2", + "method": "GetMixFormat", + "slot": 8, + "parameter": null + }, + "sourceFingerprint": "2B32209119D444096A58A1E60C27D3056FACCDC9CD36A3411FBA3CA993537EC4", + "citation": "https://learn.microsoft.com/windows/win32/api/audioclient/nf-audioclient-iaudioclient-getmixformat", + "registered": true, + "metadataMatched": true, + "safeConsumed": true, + "interfaceDependencies": 3 + }, + "com.ownership.entry.windows-win32-media-audio.iaudioclient3.7ed4ee078e674cd48c1a2b7a5987ad42.getcurrentsharedmodeengineperiod.slot-19.v1": { + "familyId": "com.ownership.v1", + "contractKind": "ownership", + "selector": { + "namespace": "Windows.Win32.Media.Audio", + "interface": "IAudioClient3", + "iid": "7ed4ee07-8e67-4cd4-8c1a-2b7a5987ad42", + "method": "GetCurrentSharedModeEnginePeriod", + "slot": 19, + "parameter": null + }, + "sourceFingerprint": "5566DB7A948DDA6FD355EFC15B60BB90F5A932891255E32143C6554DFF920CAF", + "citation": "https://learn.microsoft.com/windows/win32/api/audioclient/nf-audioclient-iaudioclient3-getcurrentsharedmodeengineperiod", + "registered": true, + "metadataMatched": true, + "safeConsumed": true, + "interfaceDependencies": 1 + }, "com.ownership.entry.windows-win32-media-audio.iaudioeffectsmanager.4460b3ae4b44452786767548a8acd260.getaudioeffects.slot-5.param-0-effects.v1": { "familyId": "com.ownership.v1", "contractKind": "ownership", @@ -10727,27 +10824,27 @@ }, "targets": { "arm64": { - "raw_metadata_complete": 6103, - "raw_manual_contract": 1437, + "raw_metadata_complete": 6108, + "raw_manual_contract": 1432, "raw_runtime_blocked": 389, "safe_incomplete_raw_metadata_complete": 412, - "safe_incomplete_raw_manual_contract": 1437, + "safe_incomplete_raw_manual_contract": 1432, "safe_incomplete_raw_runtime_blocked": 389 }, "i686": { - "raw_metadata_complete": 6102, - "raw_manual_contract": 1414, + "raw_metadata_complete": 6107, + "raw_manual_contract": 1409, "raw_runtime_blocked": 413, "safe_incomplete_raw_metadata_complete": 411, - "safe_incomplete_raw_manual_contract": 1414, + "safe_incomplete_raw_manual_contract": 1409, "safe_incomplete_raw_runtime_blocked": 413 }, "x64": { - "raw_metadata_complete": 6103, - "raw_manual_contract": 1437, + "raw_metadata_complete": 6108, + "raw_manual_contract": 1432, "raw_runtime_blocked": 389, "safe_incomplete_raw_metadata_complete": 412, - "safe_incomplete_raw_manual_contract": 1437, + "safe_incomplete_raw_manual_contract": 1432, "safe_incomplete_raw_runtime_blocked": 389 } }, @@ -10794,12 +10891,12 @@ }, "manual_reason_counts": { "arm64": { - "external_pointee_storage": 976, - "missing_allocator": 1044, + "external_pointee_storage": 971, + "missing_allocator": 1041, "missing_count_relation": 83, "missing_handle_ownership": 211, "missing_interface_replacement_contract": 42, - "missing_output_ownership": 1044, + "missing_output_ownership": 1041, "nested_pointer_lifetime": 560, "opaque_pointee_contract": 289, "pointee_missing_layout": 404, @@ -10807,16 +10904,16 @@ "pointee_unsupported_bitfield": 16, "pointee_unsupported_flexible_array": 101, "pointee_unsupported_layout_kind": 33, - "pointee_unsupported_packing": 110, + "pointee_unsupported_packing": 105, "variant_safearray_element_contract": 2 }, "i686": { - "external_pointee_storage": 977, - "missing_allocator": 1044, + "external_pointee_storage": 972, + "missing_allocator": 1041, "missing_count_relation": 83, "missing_handle_ownership": 211, "missing_interface_replacement_contract": 42, - "missing_output_ownership": 1044, + "missing_output_ownership": 1041, "nested_pointer_lifetime": 534, "opaque_pointee_contract": 289, "pointee_missing_layout": 391, @@ -10824,16 +10921,16 @@ "pointee_unsupported_bitfield": 16, "pointee_unsupported_flexible_array": 101, "pointee_unsupported_layout_kind": 33, - "pointee_unsupported_packing": 146, + "pointee_unsupported_packing": 141, "variant_safearray_element_contract": 2 }, "x64": { - "external_pointee_storage": 976, - "missing_allocator": 1044, + "external_pointee_storage": 971, + "missing_allocator": 1041, "missing_count_relation": 83, "missing_handle_ownership": 211, "missing_interface_replacement_contract": 42, - "missing_output_ownership": 1044, + "missing_output_ownership": 1041, "nested_pointer_lifetime": 560, "opaque_pointee_contract": 289, "pointee_missing_layout": 404, @@ -10841,7 +10938,7 @@ "pointee_unsupported_bitfield": 16, "pointee_unsupported_flexible_array": 101, "pointee_unsupported_layout_kind": 33, - "pointee_unsupported_packing": 110, + "pointee_unsupported_packing": 105, "variant_safearray_element_contract": 2 } }, @@ -10849,8 +10946,8 @@ "arm64": { "cleanup_known_external": 0, "cleanup_none_required": 2237, - "cleanup_standard_supported": 4530, - "cleanup_unknown": 1162, + "cleanup_standard_supported": 4533, + "cleanup_unknown": 1159, "requires_current_apartment": 7929, "requires_external_acquisition": 6804, "requires_external_pointer_or_callback": 1089 @@ -10858,8 +10955,8 @@ "i686": { "cleanup_known_external": 0, "cleanup_none_required": 2237, - "cleanup_standard_supported": 4530, - "cleanup_unknown": 1162, + "cleanup_standard_supported": 4533, + "cleanup_unknown": 1159, "requires_current_apartment": 7929, "requires_external_acquisition": 6804, "requires_external_pointer_or_callback": 1090 @@ -10867,8 +10964,8 @@ "x64": { "cleanup_known_external": 0, "cleanup_none_required": 2237, - "cleanup_standard_supported": 4530, - "cleanup_unknown": 1162, + "cleanup_standard_supported": 4533, + "cleanup_unknown": 1159, "requires_current_apartment": 7929, "requires_external_acquisition": 6804, "requires_external_pointer_or_callback": 1089 diff --git a/docs/status/generated/classic-com-interface-support.csv b/docs/status/generated/classic-com-interface-support.csv index 6dac20cf..5cf2de56 100644 --- a/docs/status/generated/classic-com-interface-support.csv +++ b/docs/status/generated/classic-com-interface-support.csv @@ -1414,9 +1414,9 @@ Windows.Win32.Media.Audio,IAudioAutoGainControl,85401fd4-6de4-4b9d-9869-2d6753a8 Windows.Win32.Media.Audio,IAudioBass,a2b1a1d9-4db3-425d-a2b2-bd335cb3e2e5,true,standard_derived, Windows.Win32.Media.Audio,IAudioCaptureClient,c8adbd64-e71e-48a0-a4de-185c395cd317,false,,missing_allocator Windows.Win32.Media.Audio,IAudioChannelConfig,bb11c46f-ec28-493c-b88a-5db88062ce98,true,standard_derived, -Windows.Win32.Media.Audio,IAudioClient,1cb9ad4c-dbfa-4c32-b178-c2f568a703b2,false,,external_pointee_storage -Windows.Win32.Media.Audio,IAudioClient2,726778cd-f60a-4eda-82de-e47610cd78aa,false,,external_pointee_storage -Windows.Win32.Media.Audio,IAudioClient3,7ed4ee07-8e67-4cd4-8c1a-2b7a5987ad42,false,,external_pointee_storage +Windows.Win32.Media.Audio,IAudioClient,1cb9ad4c-dbfa-4c32-b178-c2f568a703b2,true,exact_registry_dependent, +Windows.Win32.Media.Audio,IAudioClient2,726778cd-f60a-4eda-82de-e47610cd78aa,true,exact_registry_dependent, +Windows.Win32.Media.Audio,IAudioClient3,7ed4ee07-8e67-4cd4-8c1a-2b7a5987ad42,true,exact_registry_dependent, Windows.Win32.Media.Audio,IAudioClientDuckingControl,c789d381-a28c-4168-b28f-d3a837924dc3,true,standard_derived, Windows.Win32.Media.Audio,IAudioClock,cd63314f-3fba-4a1b-812c-ef96358728e7,true,standard_derived, Windows.Win32.Media.Audio,IAudioClock2,6f49ff73-6727-49ac-a008-d98cf5e70048,true,standard_derived, @@ -1491,7 +1491,7 @@ Windows.Win32.Media.DeviceManager,IComponentAuthenticate,a9889c00-6d2b-11d3-8496 Windows.Win32.Media.DeviceManager,IMDSPDevice,1dcb3a12-33ed-11d3-8470-00c04f79dbc0,false,,external_pointee_storage Windows.Win32.Media.DeviceManager,IMDSPDevice2,420d16ad-c97d-4e00-82aa-00e9f4335ddd,false,,external_pointee_storage Windows.Win32.Media.DeviceManager,IMDSPDevice3,1a839845-fc55-487c-976f-ee38ac0e8c4e,false,,external_pointee_storage -Windows.Win32.Media.DeviceManager,IMDSPDeviceControl,1dcb3a14-33ed-11d3-8470-00c04f79dbc0,false,,external_pointee_storage +Windows.Win32.Media.DeviceManager,IMDSPDeviceControl,1dcb3a14-33ed-11d3-8470-00c04f79dbc0,true,exact_registry_dependent, Windows.Win32.Media.DeviceManager,IMDSPDirectTransfer,c2fe57a8-9304-478c-9ee4-47e397b912d7,true,standard_derived, Windows.Win32.Media.DeviceManager,IMDSPEnumDevice,1dcb3a11-33ed-11d3-8470-00c04f79dbc0,true,standard_derived, Windows.Win32.Media.DeviceManager,IMDSPEnumStorage,1dcb3a15-33ed-11d3-8470-00c04f79dbc0,true,standard_derived, @@ -1519,7 +1519,7 @@ Windows.Win32.Media.DeviceManager,ISCPSession,88a3e6ed-eee4-4619-bbb3-fd4fb62715 Windows.Win32.Media.DeviceManager,IWMDMDevice,1dcb3a02-33ed-11d3-8470-00c04f79dbc0,false,,external_pointee_storage Windows.Win32.Media.DeviceManager,IWMDMDevice2,e34f3d37-9d67-4fc1-9252-62d28b2f8b55,false,,external_pointee_storage Windows.Win32.Media.DeviceManager,IWMDMDevice3,6c03e4fe-05db-4dda-9e3c-06233a6d5d65,false,,external_pointee_storage -Windows.Win32.Media.DeviceManager,IWMDMDeviceControl,1dcb3a04-33ed-11d3-8470-00c04f79dbc0,false,,external_pointee_storage +Windows.Win32.Media.DeviceManager,IWMDMDeviceControl,1dcb3a04-33ed-11d3-8470-00c04f79dbc0,true,exact_registry_dependent, Windows.Win32.Media.DeviceManager,IWMDMDeviceSession,82af0a65-9d96-412c-83e5-3c43e4b06cc7,true,standard_derived, Windows.Win32.Media.DeviceManager,IWMDMEnumDevice,1dcb3a01-33ed-11d3-8470-00c04f79dbc0,true,standard_derived, Windows.Win32.Media.DeviceManager,IWMDMEnumStorage,1dcb3a05-33ed-11d3-8470-00c04f79dbc0,true,standard_derived, diff --git a/tools/dynwinrt-codegen/src/codegen/com/capability.rs b/tools/dynwinrt-codegen/src/codegen/com/capability.rs index 1a7fd2ae..c55a2a0d 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/capability.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/capability.rs @@ -4559,10 +4559,10 @@ mod tests { ) .unwrap(); assert_eq!(report.summary.eligible_interfaces, 7_929); - assert_eq!(report.summary.safe_complete, 5_691); - assert_eq!(report.summary.safe_evidence.safe_complete, 5_691); + assert_eq!(report.summary.safe_complete, 5_696); + assert_eq!(report.summary.safe_evidence.safe_complete, 5_696); assert_eq!(report.summary.safe_evidence.standard_derived, 5_333); - assert_eq!(report.summary.safe_evidence.exact_registry_dependent, 358); + assert_eq!(report.summary.safe_evidence.exact_registry_dependent, 363); assert_eq!( report.summary.safe_evidence.standard_derived + report.summary.safe_evidence.exact_registry_dependent, @@ -4570,34 +4570,34 @@ mod tests { ); assert_eq!( report.summary.safe_evidence.metadata_fact_occurrences, - 5_976 + 5_982 ); assert_eq!( report.summary.safe_evidence.com_standard_fact_occurrences, - 26_114 + 26_129 ); - assert_eq!(report.summary.safe_evidence.registered_exact_entries, 499); + assert_eq!(report.summary.safe_evidence.registered_exact_entries, 504); assert_eq!( report.summary.safe_evidence.metadata_matched_exact_entries, - 499 + 504 ); assert_eq!( report.summary.safe_evidence.safe_consumed_exact_entries, - 408 + 413 ); assert_eq!( report .summary .safe_evidence .exact_entry_interface_dependencies, - 660 + 669 ); assert_eq!( report .summary .safe_evidence .exact_family_interface_dependencies, - 408 + 416 ); assert_eq!( report.summary.safe_evidence.by_contract_kind, @@ -4605,12 +4605,12 @@ mod tests { ("borrowed-handle".into(), 54), ("bounded-two-call".into(), 16), ("compound-dispatch".into(), 1), - ("conditional-output".into(), 7), + ("conditional-output".into(), 10), ("counted-buffer".into(), 16), ("enumerator-next".into(), 74), ("flag-selected-buffer".into(), 3), - ("null-input".into(), 2), - ("ownership".into(), 176), + ("null-input".into(), 4), + ("ownership".into(), 180), ("parameter-direction".into(), 45), ("safearray".into(), 263), ("semantic-hresult".into(), 3), @@ -4618,7 +4618,15 @@ mod tests { ); assert_eq!( report.summary.safe_evidence.by_family_id["com.ownership.v1"], - 119 + 122 + ); + assert_eq!( + report.summary.safe_evidence.by_family_id["audio.conditional-output.v1"], + 3 + ); + assert_eq!( + report.summary.safe_evidence.by_family_id["com.nullable-input.v1"], + 2 ); assert_eq!( report.summary.safe_evidence.by_family_id["windows.borrowed-hwnd-output.v1"], @@ -4632,7 +4640,7 @@ mod tests { report.summary.safe_evidence.by_family_id["automation.idispatch-invoke.v1"], 1 ); - assert_eq!(report.summary.safe_evidence.by_entry_id.len(), 408); + assert_eq!(report.summary.safe_evidence.by_entry_id.len(), 413); assert!( report .summary @@ -4677,7 +4685,7 @@ mod tests { .values() .filter(|entry| entry.safe_consumed) .count(), - 408 + 413 ); let status = &report.summary.safe_evidence.exact_entry_status; assert_eq!( @@ -4708,6 +4716,13 @@ mod tests { .count(), 1 ); + assert_eq!( + status + .values() + .filter(|entry| entry.family_id == "audio.conditional-output.v1") + .count(), + 1 + ); assert!(status.values().all(|entry| { entry.source_fingerprint.len() == 64 && entry @@ -4840,7 +4855,7 @@ mod tests { ), ( 412 - usize::from(target == CensusTarget::I686), - 1_437 - 23 * usize::from(target == CensusTarget::I686), + 1_432 - 23 * usize::from(target == CensusTarget::I686), 389 + 24 * usize::from(target == CensusTarget::I686) ) ); diff --git a/tools/dynwinrt-codegen/src/codegen/com/generated_unsafe.rs b/tools/dynwinrt-codegen/src/codegen/com/generated_unsafe.rs index 42d6124f..1c131f95 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/generated_unsafe.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/generated_unsafe.rs @@ -2319,13 +2319,13 @@ mod tests { }; let coverage = measure_stage2_coverage(&winmd).unwrap(); println!("{}", serde_json::to_string(&coverage).unwrap()); - assert_eq!(coverage.x64_manual_interfaces, 1_437); - assert_eq!(coverage.x64_manual_interfaces_with_executable_method, 1_433); + assert_eq!(coverage.x64_manual_interfaces, 1_432); + assert_eq!(coverage.x64_manual_interfaces_with_executable_method, 1_428); assert_eq!( coverage.x64_manual_interfaces_with_executable_manual_method, - 1_432 + 1_427 ); - assert_eq!(coverage.executable_manual_methods, 6_067); + assert_eq!(coverage.executable_manual_methods, 6_048); assert_eq!(coverage.remaining_manual_methods, 0); assert_eq!(coverage.runtime_blocked_methods, 1_161); } diff --git a/tools/dynwinrt-codegen/src/codegen/com/ir.rs b/tools/dynwinrt-codegen/src/codegen/com/ir.rs index 91adc38a..72e9efb6 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/ir.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/ir.rs @@ -215,6 +215,7 @@ pub(super) enum ComType { StatStg, FormatEtc, StgMedium, + AudioFormat, ManagedInterface { iid: String, }, @@ -314,6 +315,7 @@ pub(super) enum ResultConversion { StatStg, FormatEtc, StgMedium, + AudioFormat, MallocAllocation, MallocReallocation, } @@ -459,6 +461,10 @@ pub(super) enum ProjectedComMethodKind { BorrowedStgMediumInput { release_param_index: usize, }, + AudioFormatSupport { + share_mode_param_index: usize, + closest_match_param_index: usize, + }, PreservedStgMediumInOut { medium_param_index: usize, }, @@ -585,7 +591,8 @@ pub(super) fn dispatch_shape(typ: &ComType) -> Option { ComType::ManagedInterface { .. } | ComType::DispatchParams | ComType::FormatEtc - | ComType::StgMedium => Some(DispatchShape::Object), + | ComType::StgMedium + | ComType::AudioFormat => Some(DispatchShape::Object), // Raw/aliased pointers and BSTR accept multiple overlapping JS input // shapes (`bigint`, `number`, `Buffer`, `Uint8Array`, or `string`) // depending on position, so they can collide with any other category diff --git a/tools/dynwinrt-codegen/src/codegen/com/javascript/render.rs b/tools/dynwinrt-codegen/src/codegen/com/javascript/render.rs index 1995100b..bf97a571 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/javascript/render.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/javascript/render.rs @@ -458,6 +458,9 @@ fn render_js(meta: &ProjectedComInterface) -> String { ProjectedComMethodKind::ConditionalInterfaceOutput { .. } => { emit_conditional_interface_output_method_js(&mut out, method, &iface_var) } + ProjectedComMethodKind::AudioFormatSupport { .. } => { + emit_audio_format_support_method_js(&mut out, method, &iface_var) + } } } out.push_str("}\n"); @@ -839,6 +842,9 @@ fn wrap_param_arg_js(param: &ProjectedComParam, variable: &str) -> String { matches!(encoding, StringEncoding::Wide) ), ComType::Bstr => format!("{variable} === null ? DynCom.nullBstr() : {wrapped}"), + ComType::AudioFormat => { + format!("{variable} === null ? DynCom.nullAudioFormat() : {wrapped}") + } _ => unreachable!("nullable projection was validated"), }; } @@ -901,6 +907,7 @@ fn out_abi_type_js(method: &ProjectedComMethod, param_index: usize, typ: &ComTyp | ResultConversion::StatStg | ResultConversion::FormatEtc | ResultConversion::StgMedium + | ResultConversion::AudioFormat | ResultConversion::MallocAllocation | ResultConversion::MallocReallocation, ) @@ -922,6 +929,85 @@ fn emit_method_js(out: &mut String, method: &ProjectedComMethod, iface_var: &str emit_method_js_named(out, method, iface_var, &method.camel_name); } +fn emit_audio_format_support_method_js( + out: &mut String, + method: &ProjectedComMethod, + iface_var: &str, +) { + let ProjectedComMethodKind::AudioFormatSupport { + share_mode_param_index, + closest_match_param_index, + } = method.kind + else { + unreachable!("audio format support emitter requires exact method semantics") + }; + let inputs = input_params(method); + let params = inputs + .iter() + .enumerate() + .map(|(surface, (_, param))| js_param_name(¶m.name, surface)) + .collect::>(); + let share_mode_surface = inputs + .iter() + .position(|(index, _)| *index == share_mode_param_index) + .expect("audio share mode must be a visible input"); + let share_mode_name = ¶ms[share_mode_surface]; + emit_method_doc_js(out, &method.doc); + out.push_str(&format!( + " {}({}) {{\n", + method.camel_name, + params.join(", ") + )); + out.push_str(&format!( + " if ({share_mode_name} !== 0 && {share_mode_name} !== 1) throw new RangeError('AUDCLNT_SHAREMODE must be 0 (shared) or 1 (exclusive)');\n" + )); + out.push_str(&format!( + " const _requestClosest = {share_mode_name} === 0;\n" + )); + let args = method + .params + .iter() + .enumerate() + .filter_map(|(index, param)| { + if index == closest_match_param_index { + return Some("DynCom.boolValue(_requestClosest)".into()); + } + if !param.surface_input { + return None; + } + let surface = inputs + .iter() + .position(|(input_index, _)| *input_index == index) + .expect("projected visible audio input"); + Some(wrap_param_arg_js( + param, + &js_param_name(¶m.name, surface), + )) + }) + .collect::>(); + out.push_str(&format!( + " const _r = {iface_var}.method({}).invokeAll(this._obj, [{}]);\n", + method.vtable_index, + args.join(", ") + )); + let status = unwrap_method_result_js(method, &method.results[0], "_r[0]"); + out.push_str(&format!(" const _status = {status};\n")); + out.push_str( + " const _closest = _requestClosest ? DynCom.takeNullableAudioFormat(_r[1]) : null;\n", + ); + out.push_str( + " if (_status !== 0 && _status !== 1) throw new Error(`Unexpected IsFormatSupported success HRESULT ${_status}`);\n", + ); + out.push_str( + " if (_status === 1 && _closest === null) throw new Error('IsFormatSupported returned S_FALSE without a closest shared-mode format');\n", + ); + out.push_str( + " if (_status === 0 && _closest !== null) throw new Error('IsFormatSupported returned S_OK with an unexpected closest format');\n", + ); + out.push_str(" return [_status, _closest];\n"); + out.push_str(" }\n"); +} + fn emit_dispatch_invoke_method_js( out: &mut String, method: &ProjectedComMethod, @@ -2436,6 +2522,10 @@ fn render_dts(meta: &ProjectedComInterface) -> String { | ProjectedComMethodKind::CanonicalFormatEtc { .. } => { (dts_params(method), dts_return_type(method)) } + ProjectedComMethodKind::AudioFormatSupport { .. } => ( + dts_params(method), + "readonly [number, DynComAudioFormat | null]".into(), + ), ProjectedComMethodKind::CallerSuppliedDynamicIid { iid_param_index, .. } => ( @@ -2651,6 +2741,7 @@ fn collect_pointer_aliases(meta: &ProjectedComInterface) -> Vec<(String, Pointer | ComType::StatStg | ComType::FormatEtc | ComType::StgMedium + | ComType::AudioFormat | ComType::ManagedInterface { .. } | ComType::CoTaskMemWideString | ComType::StringArray { .. } @@ -2753,6 +2844,7 @@ fn collect_native_pods(meta: &ProjectedComInterface) -> Vec {} @@ -2849,6 +2941,9 @@ fn collect_runtime_types(meta: &ProjectedComInterface) -> Vec<&'static str> { ComType::StgMedium => { types.insert("DynComStgMedium"); } + ComType::AudioFormat => { + types.insert("DynComAudioFormat"); + } ComType::AllocatorPointer | ComType::ConsumedAllocatorPointer | ComType::InspectedAllocatorPointer => { @@ -2929,6 +3024,7 @@ fn collect_scalar_alias( | ComType::StatStg | ComType::FormatEtc | ComType::StgMedium + | ComType::AudioFormat | ComType::ManagedInterface { .. } | ComType::CoTaskMemWideString | ComType::StringArray { .. } => {} diff --git a/tools/dynwinrt-codegen/src/codegen/com/javascript/render_tests.rs b/tools/dynwinrt-codegen/src/codegen/com/javascript/render_tests.rs index 52e82bea..fd0c0031 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/javascript/render_tests.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/javascript/render_tests.rs @@ -200,6 +200,50 @@ fn renderer_serializes_validated_com_sink_plan() { ); } +#[test] +fn nullable_audio_format_inputs_serialize_the_validated_contract() { + let mut method = ProjectedComMethod { + name: "UseFormat".into(), + camel_name: "useFormat".into(), + vtable_index: 6, + params: vec![ProjectedComParam { + name: "format".into(), + typ: ComType::AudioFormat, + direction: ComParamDirection::In, + surface_input: true, + surface_result: false, + nullable: true, + }], + return_convention: ComReturnConvention::HResult, + results: Vec::new(), + string_buffer: None, + typed_buffers: Vec::new(), + shared_counts: Vec::new(), + kind: ProjectedComMethodKind::Normal, + doc: None, + overload: None, + }; + assert_eq!( + super::build_method_sig_js(&method), + "new DynComMethodSig().addNullableIn(DynCom.audioFormatType())" + ); + assert_eq!(dts_params(&method), ["format: DynComAudioFormat | null"]); + assert_eq!( + wrap_param_arg_js(&method.params[0], "format"), + "format === null ? DynCom.nullAudioFormat() : DynCom.audioFormat(format)" + ); + method.params[0].nullable = false; + assert_eq!( + super::build_method_sig_js(&method), + "new DynComMethodSig().addIn(DynCom.audioFormatType())" + ); + assert_eq!(dts_params(&method), ["format: DynComAudioFormat"]); + assert_eq!( + wrap_param_arg_js(&method.params[0], "format"), + "DynCom.audioFormat(format)" + ); +} + #[test] fn storage_medium_result_rules_and_borrowing_are_serialized_from_ir() { let format_param = |name: &str, direction| ProjectedComParam { diff --git a/tools/dynwinrt-codegen/src/codegen/com/javascript/types.rs b/tools/dynwinrt-codegen/src/codegen/com/javascript/types.rs index b5f2d095..4efe660a 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/javascript/types.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/javascript/types.rs @@ -62,6 +62,7 @@ pub(super) fn abi_type_js(typ: &ComType) -> String { ComType::StatStg => "DynCom.statStgType()".into(), ComType::FormatEtc => "DynCom.formatEtcType()".into(), ComType::StgMedium => "DynCom.stgMediumType()".into(), + ComType::AudioFormat => "DynCom.audioFormatType()".into(), ComType::ManagedInterface { iid } => { format!("DynCom.interfaceType(WinGuid.parse('{iid}'))") } @@ -162,6 +163,7 @@ pub(super) fn type_dts(typ: &ComType) -> String { ComType::StatStg => "DynComStatStg".into(), ComType::FormatEtc => "DynComFormatEtc".into(), ComType::StgMedium => "DynComStgMedium".into(), + ComType::AudioFormat => "DynComAudioFormat".into(), ComType::ManagedInterface { .. } => "DynWinRtValue".into(), ComType::CoTaskMemWideString => "string".into(), ComType::StringArray { .. } => "string[]".into(), @@ -214,6 +216,7 @@ pub(super) fn result_type_dts(result: &ProjectedComResult) -> String { ResultConversion::StatStg => "DynComStatStg".into(), ResultConversion::FormatEtc => "DynComFormatEtc".into(), ResultConversion::StgMedium => "DynComStgMedium".into(), + ResultConversion::AudioFormat => "DynComAudioFormat".into(), ResultConversion::MallocAllocation | ResultConversion::MallocReallocation => { "DynComAllocation | null".into() } @@ -297,6 +300,7 @@ pub(super) fn wrap_arg_js(typ: &ComType, variable: &str) -> String { ComType::StatStg => unreachable!("STATSTG is output-only"), ComType::FormatEtc => format!("DynCom.formatEtc({variable})"), ComType::StgMedium => format!("DynCom.stgMedium({variable})"), + ComType::AudioFormat => format!("DynCom.audioFormat({variable})"), ComType::ManagedInterface { .. } => variable.to_string(), ComType::CoTaskMemWideString => { unreachable!("CoTaskMem string elements are output-only") @@ -384,6 +388,7 @@ pub(super) fn unwrap_result_js(result: &ProjectedComResult, expression: &str) -> ResultConversion::StatStg => format!("DynCom.takeStatStg({expression})"), ResultConversion::FormatEtc => format!("DynCom.takeFormatEtc({expression})"), ResultConversion::StgMedium => format!("DynCom.takeStgMedium({expression})"), + ResultConversion::AudioFormat => format!("DynCom.takeAudioFormat({expression})"), ResultConversion::MallocAllocation => { format!("DynCom.takeMallocAllocation(this._obj, {expression})") } @@ -479,6 +484,7 @@ fn unwrap_value_js(typ: &ComType, expression: &str) -> String { ComType::StatStg => format!("DynCom.takeStatStg({expression})"), ComType::FormatEtc => format!("DynCom.takeFormatEtc({expression})"), ComType::StgMedium => format!("DynCom.takeStgMedium({expression})"), + ComType::AudioFormat => format!("DynCom.takeAudioFormat({expression})"), ComType::ManagedInterface { .. } => expression.to_string(), ComType::CoTaskMemWideString => { unreachable!("CoTaskMem string elements are array-only") diff --git a/tools/dynwinrt-codegen/src/codegen/com/model/abi.rs b/tools/dynwinrt-codegen/src/codegen/com/model/abi.rs index 1f25b57e..4c0a8c58 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/model/abi.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/model/abi.rs @@ -167,6 +167,7 @@ pub(in crate::codegen::com) enum ComAbiType { StatStg, FormatEtc, StgMedium, + AudioFormat, FunctionPointer(SignatureId), Unknown(UnsupportedReason), } diff --git a/tools/dynwinrt-codegen/src/codegen/com/model/metadata.rs b/tools/dynwinrt-codegen/src/codegen/com/model/metadata.rs index 3e1f1157..0a9408bf 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/model/metadata.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/model/metadata.rs @@ -294,7 +294,7 @@ fn map_method( .map_err(ModelError::InvalidContract)?; crate::com_metadata::validate_attached_safe_array_evidence(raw) .map_err(ModelError::InvalidContract)?; - crate::com_metadata::validate_storage_medium_contract_presence(raw) + crate::com_metadata::validate_required_exact_contract_presence(raw) .map_err(ModelError::InvalidContract)?; if let Some(contract) = &raw.exact_contract { crate::com_metadata::validate_exact_method_contract( @@ -453,6 +453,21 @@ fn map_method( output_param: ParamIndex::new(1), }) } + Some( + RawExactMethodContractKind::AudioFormatOwnedOutput + | RawExactMethodContractKind::NullableAudioFormatInput, + ) => method, + Some(RawExactMethodContractKind::AudioFormatSupport) => { + let contract = raw.exact_contract.as_ref().unwrap(); + method.with_special_contract(ComMethodSpecialContract::AudioFormatSupport { + share_mode_param: ParamIndex::new( + contract + .discriminator_param_index + .expect("validated audio share-mode discriminator"), + ), + closest_match_param: ParamIndex::new(contract.buffer_param_index), + }) + } None => method, } }; @@ -525,6 +540,28 @@ fn map_param( )?, None, ) + } else if matches!( + &raw.typ.native_type, + RawNativeType::Named { + namespace, + name, + .. + } if namespace == "Windows.Win32.Media.Audio" + && name == "WAVEFORMATEX" + && matches!(raw.typ.pointer_depth, 1 | 2) + ) { + ( + insert_abi( + model, + Some(QualifiedName::new( + "Windows.Win32.Media.Audio", + "WAVEFORMATEX", + )?), + None, + ComAbiType::AudioFormat, + )?, + None, + ) } else if matches!( &raw.typ.native_type, RawNativeType::Named { @@ -696,7 +733,13 @@ fn map_param( param_index, dynamic_iid_output, )?; - let nullable = if !exact_null_input + let exact_nullable_audio_input = raw_method.exact_contract.as_ref().is_some_and(|contract| { + contract.kind == RawExactMethodContractKind::NullableAudioFormatInput + && contract.buffer_param_index == param_index + }); + let nullable = if exact_nullable_audio_input { + Nullability::Nullable + } else if !exact_null_input && (raw.optional || known_nullable_param_override( interface_namespace, @@ -1031,6 +1074,7 @@ pub(in crate::codegen::com) fn census_raw_base_category(raw: &RawComType) -> &'s ComAbiType::StatStg => "StatStg", ComAbiType::FormatEtc => "FormatEtc", ComAbiType::StgMedium => "StgMedium", + ComAbiType::AudioFormat => "AudioFormat", ComAbiType::FunctionPointer(_) => "FunctionPointer", ComAbiType::Unknown(_) => "Unknown", }; @@ -1534,6 +1578,7 @@ fn validate_pod_field_type( | ComAbiType::StatStg | ComAbiType::FormatEtc | ComAbiType::StgMedium + | ComAbiType::AudioFormat | ComAbiType::FunctionPointer(_) | ComAbiType::Unknown(_) => Err(ModelError::Unsupported(UnsupportedReason::UnknownLayout)), } @@ -1605,6 +1650,7 @@ fn abi_size_alignment( | ComAbiType::StatStg | ComAbiType::FormatEtc | ComAbiType::StgMedium + | ComAbiType::AudioFormat | ComAbiType::Unknown(_) => { return Err(ModelError::Unsupported(UnsupportedReason::UnknownLayout)); } @@ -1824,6 +1870,7 @@ fn buffer_element_ownership( | ComAbiType::StatStg | ComAbiType::FormatEtc | ComAbiType::StgMedium + | ComAbiType::AudioFormat | ComAbiType::FunctionPointer(_) | ComAbiType::Unknown(_) => BufferElementOwnership::Unknown, }; @@ -1966,12 +2013,37 @@ fn map_ownership( ComAbiType::StgMedium if direction == Direction::Out => { Ok((ComOwnership::StgMediumOwned, Cleanup::ReleaseStgMedium)) } + ComAbiType::AudioFormat + if direction == Direction::Out + && raw_method.exact_contract.as_ref().is_some_and(|contract| { + matches!( + contract.kind, + RawExactMethodContractKind::AudioFormatOwnedOutput + | RawExactMethodContractKind::AudioFormatSupport + ) && contract.buffer_param_index == param_index + }) => + { + Ok(( + ComOwnership::AudioFormatOwned, + Cleanup::CoTaskMemAudioFormat, + )) + } + ComAbiType::AudioFormat if direction == Direction::Out => Err(ModelError::Unsupported( + UnsupportedReason::Other( + "WAVEFORMATEX output requires exact CoTaskMem ownership evidence".into(), + ), + )), ComAbiType::FormatEtc if direction == Direction::InOut => Err( ModelError::Unsupported(UnsupportedReason::Other( "FORMATETC in/out requires a dedicated replacement contract".into(), )), ), - ComAbiType::FormatEtc | ComAbiType::StgMedium => { + ComAbiType::AudioFormat if direction == Direction::InOut => Err( + ModelError::Unsupported(UnsupportedReason::Other( + "WAVEFORMATEX in/out requires a dedicated replacement contract".into(), + )), + ), + ComAbiType::FormatEtc | ComAbiType::StgMedium | ComAbiType::AudioFormat => { Ok((ComOwnership::Borrowed, Cleanup::None)) } ComAbiType::DispatchParams if direction == Direction::Out => Err( diff --git a/tools/dynwinrt-codegen/src/codegen/com/model/method.rs b/tools/dynwinrt-codegen/src/codegen/com/model/method.rs index 13477a8d..9bd7ec49 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/model/method.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/model/method.rs @@ -56,6 +56,10 @@ pub(in crate::codegen::com) enum ComMethodSpecialContract { BorrowedStgMediumInput { release_param: ParamIndex, }, + AudioFormatSupport { + share_mode_param: ParamIndex, + closest_match_param: ParamIndex, + }, PreservedStgMediumInOut { medium_param: ParamIndex, }, @@ -191,6 +195,7 @@ impl ComMethodContract { | ComAbiType::StatStg | ComAbiType::FormatEtc | ComAbiType::StgMedium + | ComAbiType::AudioFormat ) { return Err(ModelError::InvalidContract(format!( diff --git a/tools/dynwinrt-codegen/src/codegen/com/model/ownership.rs b/tools/dynwinrt-codegen/src/codegen/com/model/ownership.rs index 8cf5b0f6..29f48c29 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/model/ownership.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/model/ownership.rs @@ -35,6 +35,7 @@ pub(in crate::codegen::com) enum ComOwnership { StatStgOwned, FormatEtcOwned, StgMediumOwned, + AudioFormatOwned, LocalOwned, HandleOwned(HandleCleanup), CustomOwned(CleanupId), @@ -55,6 +56,7 @@ pub(in crate::codegen::com) enum Cleanup { StatStgClear, FormatEtcClear, ReleaseStgMedium, + CoTaskMemAudioFormat, LocalFree, Handle(HandleCleanup), Custom(CleanupId), @@ -117,6 +119,7 @@ pub(super) fn validate_ownership_cleanup( | (ComOwnership::StatStgOwned, Cleanup::StatStgClear) | (ComOwnership::FormatEtcOwned, Cleanup::FormatEtcClear) | (ComOwnership::StgMediumOwned, Cleanup::ReleaseStgMedium) + | (ComOwnership::AudioFormatOwned, Cleanup::CoTaskMemAudioFormat) | (ComOwnership::LocalOwned, Cleanup::LocalFree) => true, (ComOwnership::HandleOwned(expected), Cleanup::Handle(actual)) => expected == actual, (ComOwnership::CustomOwned(expected), Cleanup::Custom(actual)) => expected == actual, diff --git a/tools/dynwinrt-codegen/src/codegen/com/project/mod.rs b/tools/dynwinrt-codegen/src/codegen/com/project/mod.rs index 2a69113f..1dd1c9d2 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/project/mod.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/project/mod.rs @@ -509,6 +509,7 @@ fn validate_projected_surface_names(meta: &ProjectedComInterface) -> Result<(), | ComType::StatStg | ComType::FormatEtc | ComType::StgMedium + | ComType::AudioFormat | ComType::ManagedInterface { .. } | ComType::CoTaskMemWideString | ComType::StringArray { .. } => {} @@ -695,6 +696,13 @@ fn project_method( release_param_index: release_param.index(), } } + Some(ComMethodSpecialContract::AudioFormatSupport { + share_mode_param, + closest_match_param, + }) => ProjectedComMethodKind::AudioFormatSupport { + share_mode_param_index: share_mode_param.index(), + closest_match_param_index: closest_match_param.index(), + }, Some(ComMethodSpecialContract::PreservedStgMediumInOut { medium_param }) => { ProjectedComMethodKind::PreservedStgMediumInOut { medium_param_index: medium_param.index(), @@ -868,6 +876,13 @@ fn project_method( fetched_param_index, .. } if *fetched_param_index == index + ) + || matches!( + &kind, + ProjectedComMethodKind::AudioFormatSupport { + closest_match_param_index, + .. + } if *closest_match_param_index == index )) => { ComParamDirection::OptionalOut @@ -1084,6 +1099,17 @@ fn project_method( ProjectedComMethodKind::ConditionalInterfaceOutput { .. } ) { // The exact mode contract controls which optional output is requested. + } else if let ProjectedComMethodKind::AudioFormatSupport { + closest_match_param_index, + .. + } = kind + { + if optional_outputs != [closest_match_param_index] { + return Err(format!( + "{}: audio format support requires exactly its closest-match optional output", + context() + )); + } } else { if interface_namespace != "Windows.Win32.System.Com" || interface_name != "IDispatch" @@ -1164,11 +1190,12 @@ fn project_method( | ComType::Bstr | ComType::ManagedInterface { .. } | ComType::SafeArray { .. } - ) || (direction == ComParamDirection::InputBuffer - && matches!( - typ, - ComType::TypedBuffer { .. } | ComType::StringArray { .. } - )) + ) || (direction == ComParamDirection::In && matches!(typ, ComType::AudioFormat)) + || (direction == ComParamDirection::InputBuffer + && matches!( + typ, + ComType::TypedBuffer { .. } | ComType::StringArray { .. } + )) } let mut return_convention = match method.return_kind() { @@ -1295,6 +1322,43 @@ fn project_method( } } + if let ProjectedComMethodKind::AudioFormatSupport { + share_mode_param_index, + closest_match_param_index, + } = kind + && (return_convention != ComReturnConvention::SemanticHResult + || !matches!( + params.get(share_mode_param_index), + Some(ProjectedComParam { + typ: ComType::Enum { + underlying: ComEnumUnderlying::I32, + .. + }, + direction: ComParamDirection::In, + surface_input: true, + .. + }) + ) + || !matches!( + params.get(closest_match_param_index), + Some(ProjectedComParam { + typ: ComType::AudioFormat, + direction: ComParamDirection::OptionalOut, + surface_result: true, + .. + }) + ) + || results.len() != 2 + || results[0].source != ResultSource::DirectReturn + || results[1].source != ResultSource::Param(closest_match_param_index) + || results[1].conversion != ResultConversion::AudioFormat) + { + return Err(format!( + "{}: audio format support no longer matches its exact projected result contract", + context() + )); + } + if let ProjectedComMethodKind::CanonicalFormatEtc { input_param_index, output_param_index, @@ -1706,6 +1770,7 @@ fn project_value_type( ComAbiType::StatStg => Ok(ComType::StatStg), ComAbiType::FormatEtc => Ok(ComType::FormatEtc), ComAbiType::StgMedium => Ok(ComType::StgMedium), + ComAbiType::AudioFormat => Ok(ComType::AudioFormat), ComAbiType::NativeUnion(_) | ComAbiType::FunctionPointer(_) | ComAbiType::Unknown(_) => { Err(format!( "unsupported Classic-COM semantic type {}", @@ -2108,6 +2173,7 @@ fn project_native_pod_field_type( | ComAbiType::StatStg | ComAbiType::FormatEtc | ComAbiType::StgMedium + | ComAbiType::AudioFormat | ComAbiType::FunctionPointer(_) | ComAbiType::Unknown(_) => Err(format!( "unsupported nested native POD field {}", @@ -2893,6 +2959,11 @@ fn result_conversion( { Ok(ResultConversion::StgMedium) } + (ComOwnership::AudioFormatOwned, Cleanup::CoTaskMemAudioFormat) + if matches!(typ, ComType::AudioFormat) => + { + Ok(ResultConversion::AudioFormat) + } (ownership, cleanup) => Err(format!( "{}: unsupported projected ownership {ownership:?} with cleanup {cleanup:?}", param.name() diff --git a/tools/dynwinrt-codegen/src/com_metadata.rs b/tools/dynwinrt-codegen/src/com_metadata.rs index 8a4f73e1..825b6904 100644 --- a/tools/dynwinrt-codegen/src/com_metadata.rs +++ b/tools/dynwinrt-codegen/src/com_metadata.rs @@ -384,6 +384,9 @@ pub enum RawExactMethodContractKind { BorrowedStgMediumInput, PreservedStgMediumInOut, CanonicalFormatEtc, + AudioFormatOwnedOutput, + AudioFormatSupport, + NullableAudioFormatInput, } #[derive(Debug, Clone, PartialEq, Eq)] @@ -417,9 +420,16 @@ impl RawExactMethodContract { RawExactMethodContractKind::StatStg | RawExactMethodContractKind::Malloc | RawExactMethodContractKind::BorrowedStgMediumInput + | RawExactMethodContractKind::AudioFormatOwnedOutput | RawExactMethodContractKind::PreservedStgMediumInOut => { crate::contract_registry::ExactFamilyId::Ownership } + RawExactMethodContractKind::AudioFormatSupport => { + crate::contract_registry::ExactFamilyId::AudioConditionalOutput + } + RawExactMethodContractKind::NullableAudioFormatInput => { + crate::contract_registry::ExactFamilyId::NullableInput + } RawExactMethodContractKind::CanonicalFormatEtc => { crate::contract_registry::ExactFamilyId::SemanticHresult } @@ -451,9 +461,16 @@ impl RawExactMethodContract { RawExactMethodContractKind::StatStg | RawExactMethodContractKind::Malloc | RawExactMethodContractKind::BorrowedStgMediumInput + | RawExactMethodContractKind::AudioFormatOwnedOutput | RawExactMethodContractKind::PreservedStgMediumInOut => { crate::contract_registry::ContractKind::Ownership } + RawExactMethodContractKind::AudioFormatSupport => { + crate::contract_registry::ContractKind::ConditionalOutput + } + RawExactMethodContractKind::NullableAudioFormatInput => { + crate::contract_registry::ContractKind::NullInput + } RawExactMethodContractKind::CanonicalFormatEtc => { crate::contract_registry::ContractKind::SemanticHresult } @@ -2190,6 +2207,9 @@ fn apply_exact_method_contract( } RawExactMethodContractKind::StatStg => {} RawExactMethodContractKind::Malloc => {} + RawExactMethodContractKind::AudioFormatOwnedOutput => {} + RawExactMethodContractKind::AudioFormatSupport => {} + RawExactMethodContractKind::NullableAudioFormatInput => {} RawExactMethodContractKind::BorrowedStgMediumInput | RawExactMethodContractKind::PreservedStgMediumInOut | RawExactMethodContractKind::CanonicalFormatEtc => {} @@ -2354,6 +2374,46 @@ fn registered_exact_method_contract( "IDataObject::SetData transfers STGMEDIUM ownership only when fRelease is TRUE; the safe projection pins fRelease to FALSE so call-local HGLOBAL storage remains caller-owned", "https://learn.microsoft.com/windows/win32/api/objidl/nf-objidl-idataobject-setdata", ), + ( + "Windows.Win32.Media.DeviceManager", + "IMDSPDeviceControl" | "IWMDMDeviceControl", + "Record", + ) => ( + RawExactMethodContractKind::NullableAudioFormatInput, + 0, + 0, + None, + "Record accepts a null WAVEFORMATEX pointer to select the device default format; explicit formats are borrowed for the call", + if interface == "IMDSPDeviceControl" { + "https://learn.microsoft.com/windows/win32/api/mswmdm/nf-mswmdm-imdspdevicecontrol-record" + } else { + "https://learn.microsoft.com/windows/win32/api/mswmdm/nf-mswmdm-iwmdmdevicecontrol-record" + }, + ), + ("Windows.Win32.Media.Audio", "IAudioClient", "IsFormatSupported") => ( + RawExactMethodContractKind::AudioFormatSupport, + 2, + 0, + None, + "IAudioClient::IsFormatSupported requests a closest-match output only for shared mode and returns that format with CoTaskMem ownership", + "https://learn.microsoft.com/windows/win32/api/audioclient/nf-audioclient-iaudioclient-isformatsupported", + ), + ("Windows.Win32.Media.Audio", "IAudioClient", "GetMixFormat") => ( + RawExactMethodContractKind::AudioFormatOwnedOutput, + 0, + 0, + None, + "IAudioClient::GetMixFormat returns variable-length WAVEFORMATEX storage allocated with CoTaskMem", + "https://learn.microsoft.com/windows/win32/api/audioclient/nf-audioclient-iaudioclient-getmixformat", + ), + ("Windows.Win32.Media.Audio", "IAudioClient3", "GetCurrentSharedModeEnginePeriod") => ( + RawExactMethodContractKind::AudioFormatOwnedOutput, + 0, + 0, + None, + "IAudioClient3::GetCurrentSharedModeEnginePeriod returns variable-length WAVEFORMATEX storage allocated with CoTaskMem", + "https://learn.microsoft.com/windows/win32/api/audioclient/nf-audioclient-iaudioclient3-getcurrentsharedmodeengineperiod", + ), ("Windows.Win32.System.Ole", "IOleCache", "SetData") => ( RawExactMethodContractKind::BorrowedStgMediumInput, 1, @@ -2438,6 +2498,8 @@ fn registered_exact_method_contract( "ID3D12Object" => "Windows.Win32.Graphics.Direct3D12", "IDMLObject" => "Windows.Win32.AI.MachineLearning.DirectML", "IStream" | "IDataObject" => "Windows.Win32.System.Com", + "IAudioClient" | "IAudioClient3" => "Windows.Win32.Media.Audio", + "IMDSPDeviceControl" | "IWMDMDeviceControl" => "Windows.Win32.Media.DeviceManager", "IOleCache" => "Windows.Win32.System.Ole", "IStorage" => "Windows.Win32.System.Com.StructuredStorage", "IContextMenu" => "Windows.Win32.UI.Shell", @@ -2458,6 +2520,10 @@ fn registered_exact_method_contract( "IContextMenu" => "IContextMenu", "IMalloc" => "IMalloc", "IDataObject" => "IDataObject", + "IAudioClient" => "IAudioClient", + "IAudioClient3" => "IAudioClient3", + "IMDSPDeviceControl" => "IMDSPDeviceControl", + "IWMDMDeviceControl" => "IWMDMDeviceControl", "IOleCache" => "IOleCache", _ => unreachable!("matched exact method interface"), }, @@ -2484,6 +2550,23 @@ fn registered_exact_method_contract( RawExactMethodContractKind::FlagSelectedString => { "000214e4-0000-0000-c000-000000000046" } + RawExactMethodContractKind::AudioFormatOwnedOutput + | RawExactMethodContractKind::AudioFormatSupport + if interface == "IAudioClient" => + { + "1cb9ad4c-dbfa-4c32-b178-c2f568a703b2" + } + RawExactMethodContractKind::AudioFormatOwnedOutput => { + "7ed4ee07-8e67-4cd4-8c1a-2b7a5987ad42" + } + RawExactMethodContractKind::AudioFormatSupport => { + unreachable!("audio format support belongs to IAudioClient") + } + RawExactMethodContractKind::NullableAudioFormatInput => match interface { + "IMDSPDeviceControl" => "1dcb3a14-33ed-11d3-8470-00c04f79dbc0", + "IWMDMDeviceControl" => "1dcb3a04-33ed-11d3-8470-00c04f79dbc0", + _ => unreachable!("matched exact nullable audio input"), + }, RawExactMethodContractKind::BorrowedStgMediumInput => match interface { "IDataObject" => "0000010e-0000-0000-c000-000000000046", "IOleCache" => "0000011e-0000-0000-c000-000000000046", @@ -2508,6 +2591,13 @@ fn registered_exact_method_contract( _ => unreachable!("matched exact IMalloc method"), }, RawExactMethodContractKind::FlagSelectedString => "GetCommandString", + RawExactMethodContractKind::AudioFormatOwnedOutput => match method { + "GetMixFormat" => "GetMixFormat", + "GetCurrentSharedModeEnginePeriod" => "GetCurrentSharedModeEnginePeriod", + _ => unreachable!("matched exact audio format output"), + }, + RawExactMethodContractKind::AudioFormatSupport => "IsFormatSupported", + RawExactMethodContractKind::NullableAudioFormatInput => "Record", RawExactMethodContractKind::BorrowedStgMediumInput => "SetData", RawExactMethodContractKind::PreservedStgMediumInOut => "GetDataHere", RawExactMethodContractKind::CanonicalFormatEtc => "GetCanonicalFormatEtc", @@ -2529,6 +2619,10 @@ fn registered_exact_method_contract( ("IMalloc", "GetSize") => 6, ("IMalloc", "DidAlloc") => 7, ("IMalloc", "HeapMinimize") => 8, + ("IAudioClient", "IsFormatSupported") => 7, + ("IAudioClient", "GetMixFormat") => 8, + ("IAudioClient3", "GetCurrentSharedModeEnginePeriod") => 19, + ("IMDSPDeviceControl" | "IWMDMDeviceControl", "Record") => 6, ("IDataObject" | "IOleCache", "SetData") => 7, ("IDataObject", "GetDataHere") => 4, ("IDataObject", "GetCanonicalFormatEtc") => 6, @@ -2537,20 +2631,38 @@ fn registered_exact_method_contract( buffer_param_index: buffer, capacity_param_index: capacity, actual_length_param_index: actual, - discriminator_param_index: (kind == RawExactMethodContractKind::FlagSelectedString) - .then_some(1), + discriminator_param_index: match kind { + RawExactMethodContractKind::FlagSelectedString => Some(1), + RawExactMethodContractKind::AudioFormatSupport => Some(0), + _ => None, + }, reserved_null_param_index: (kind == RawExactMethodContractKind::FlagSelectedString) .then_some(2), ownership_transfer_param_index: (kind == RawExactMethodContractKind::BorrowedStgMediumInput) .then_some(2), source_fingerprint: match (interface, method) { + ("IMDSPDeviceControl", "Record") => { + Some("346C3A5C69100EF034C6B1773533C7B9AB74C66F05581FF8D1D02370C9506F52") + } + ("IWMDMDeviceControl", "Record") => { + Some("68EB1BDA9994CE96C21642D9D336EBBF7BC38DD14C04E799A9091025D0D55871") + } ("IDataObject", "GetDataHere") => { Some("65165D814B216835E273E9342B4CBEC2A4F6F1A68477F3F07036C2479BDADBFF") } ("IDataObject", "SetData") => { Some("7AF093CB4139DC99AFD713365806F4914690BBCE84928887BAECD35E97B823B1") } + ("IAudioClient", "IsFormatSupported") => { + Some("8C96A1A91E80657C730E2729DEBC3B708E7B94CC8CF9BAF2F3FD0348237CB186") + } + ("IAudioClient", "GetMixFormat") => { + Some("2B32209119D444096A58A1E60C27D3056FACCDC9CD36A3411FBA3CA993537EC4") + } + ("IAudioClient3", "GetCurrentSharedModeEnginePeriod") => { + Some("5566DB7A948DDA6FD355EFC15B60BB90F5A932891255E32143C6554DFF920CAF") + } ("IOleCache", "SetData") => { Some("AACEA7AC7F8360EE26C559E2EC69F254DF944977174AB767769B40AF899D5573") } @@ -2676,7 +2788,7 @@ fn raw_hresult(typ: &RawComType) -> bool { .is_some_and(|underlying| matches!(underlying.native_type, RawNativeType::I32)) } -pub(crate) fn validate_storage_medium_contract_presence(raw: &RawComMethod) -> Result<(), String> { +pub(crate) fn validate_required_exact_contract_presence(raw: &RawComMethod) -> Result<(), String> { let required = registered_exact_method_contract( &raw.declaring_namespace, &raw.declaring_interface, @@ -2688,11 +2800,12 @@ pub(crate) fn validate_storage_medium_contract_presence(raw: &RawComMethod) -> R RawExactMethodContractKind::BorrowedStgMediumInput | RawExactMethodContractKind::PreservedStgMediumInOut | RawExactMethodContractKind::CanonicalFormatEtc + | RawExactMethodContractKind::NullableAudioFormatInput ) }); if required && raw.exact_contract.is_none() { return Err(format!( - "{}.{} requires its exact storage-medium contract", + "{}.{} requires exact contract evidence for its input/output semantics", raw.declaring_interface, raw.metadata_name )); } @@ -2917,6 +3030,23 @@ pub(crate) fn validate_exact_method_contract( }) && raw_hresult(&raw.return_type) } + RawExactMethodContractKind::NullableAudioFormatInput => { + raw_method_shape(raw) + == "Record@6(pFormat:in:required:noconstattr:Windows.Win32.Media.Audio.WAVEFORMATEX[Struct]/ptr1/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next" + } + RawExactMethodContractKind::AudioFormatOwnedOutput => { + if contract.method_name == "GetMixFormat" { + raw_method_shape(raw) + == "GetMixFormat@8(ppDeviceFormat:out:required:noconstattr:Windows.Win32.Media.Audio.WAVEFORMATEX[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next" + } else { + raw_method_shape(raw) + == "GetCurrentSharedModeEnginePeriod@19(ppFormat:out:required:noconstattr:Windows.Win32.Media.Audio.WAVEFORMATEX[Struct]/ptr2/Mutable,pCurrentPeriodInFrames:out:required:noconstattr:u32/ptr1/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next" + } + } + RawExactMethodContractKind::AudioFormatSupport => { + raw_method_shape(raw) + == "IsFormatSupported@7(ShareMode:in:required:noconstattr:Windows.Win32.Media.Audio.AUDCLNT_SHAREMODE[Enum]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified,pFormat:in:required:constattr:Windows.Win32.Media.Audio.WAVEFORMATEX[Struct]/ptr1/Mutable,ppClosestMatch:out:optional:noconstattr:Windows.Win32.Media.Audio.WAVEFORMATEX[Struct]/ptr2/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:semantic_hresult:not_enumerator_next" + } RawExactMethodContractKind::PreservedStgMediumInOut => { raw_method_shape(raw) == "GetDataHere@4(pformatetc:in:required:noconstattr:Windows.Win32.System.Com.FORMATETC[Struct]/ptr1/Mutable,pmedium:inout:required:noconstattr:Windows.Win32.System.Com.STGMEDIUM[Struct]/ptr1/Mutable)->Windows.Win32.Foundation.HRESULT[Struct]/ptr0/Unspecified/underlying=i32/ptr0/Unspecified:plain_hresult:not_enumerator_next" @@ -2954,6 +3084,24 @@ pub(crate) fn validate_exact_method_contract( && contract.discriminator_param_index.is_none() && contract.reserved_null_param_index.is_none() } + RawExactMethodContractKind::NullableAudioFormatInput => { + contract.buffer_param_index == 0 + && contract.capacity_param_index == 0 + && contract.actual_length_param_index.is_none() + && contract.discriminator_param_index.is_none() + && contract.reserved_null_param_index.is_none() + && contract.ownership_transfer_param_index.is_none() + } + RawExactMethodContractKind::AudioFormatOwnedOutput => { + contract.buffer_param_index == 0 + && contract.discriminator_param_index.is_none() + && contract.ownership_transfer_param_index.is_none() + } + RawExactMethodContractKind::AudioFormatSupport => { + contract.buffer_param_index == 2 + && contract.discriminator_param_index == Some(0) + && contract.ownership_transfer_param_index.is_none() + } RawExactMethodContractKind::PreservedStgMediumInOut | RawExactMethodContractKind::CanonicalFormatEtc => { contract.buffer_param_index == 1 @@ -2965,7 +3113,11 @@ pub(crate) fn validate_exact_method_contract( }; if !valid_shape || (raw.semantic_hresult.is_some() - && contract.kind != RawExactMethodContractKind::CanonicalFormatEtc) + && !matches!( + contract.kind, + RawExactMethodContractKind::AudioFormatSupport + | RawExactMethodContractKind::CanonicalFormatEtc + )) || raw.enumerator_next.is_some() || !indices_valid { @@ -5102,6 +5254,143 @@ mod tests { .unwrap(); } + #[test] + fn audio_record_nullability_contracts_are_exact() { + let Some(winmd) = std::env::var("DYNWINRT_WIN32_WINMD") + .ok() + .filter(|path| std::path::Path::new(path).exists()) + else { + return; + }; + let mut missing = Vec::new(); + for name in ["IMDSPDeviceControl", "IWMDMDeviceControl"] { + let namespace = "Windows.Win32.Media.DeviceManager"; + let interface = parse_com_interface(&winmd, namespace, name).unwrap(); + let raw = interface + .raw_methods + .as_ref() + .unwrap() + .iter() + .find(|method| method.metadata_name == "Record") + .unwrap(); + if let Some(contract) = &raw.exact_contract { + assert_eq!( + contract.kind, + RawExactMethodContractKind::NullableAudioFormatInput + ); + assert_eq!(contract.buffer_param_index, 0); + validate_exact_method_contract( + namespace, + name, + &interface.interface.iid, + raw, + contract, + ) + .unwrap(); + } else { + missing.push(format!( + "{name} {}: {} ({})", + interface.interface.iid, + raw_method_shape(raw), + raw_method_fingerprint(raw) + )); + } + } + assert!( + missing.is_empty(), + "missing nullable Record evidence: {missing:#?}" + ); + } + + #[test] + fn audio_format_exact_contracts_are_fingerprint_pinned() { + let Some(winmd) = std::env::var("DYNWINRT_WIN32_WINMD") + .ok() + .filter(|path| std::path::Path::new(path).exists()) + else { + return; + }; + let interface = + parse_com_interface(&winmd, "Windows.Win32.Media.Audio", "IAudioClient3").unwrap(); + let actual = interface + .raw_methods + .as_ref() + .unwrap() + .iter() + .filter_map(|raw| { + let contract = raw.exact_contract.as_ref()?; + matches!( + contract.kind, + RawExactMethodContractKind::AudioFormatOwnedOutput + | RawExactMethodContractKind::AudioFormatSupport + ) + .then(|| { + let mut source = raw.clone(); + source.exact_contract = None; + ( + raw.metadata_name.clone(), + raw_method_fingerprint(&source), + contract.source_fingerprint.unwrap().to_string(), + ) + }) + }) + .collect::>(); + assert_eq!( + actual + .iter() + .map(|(name, _, _)| name.as_str()) + .collect::>(), + [ + "IsFormatSupported", + "GetMixFormat", + "GetCurrentSharedModeEnginePeriod" + ] + ); + for (_, fingerprint, expected) in actual { + assert_eq!(fingerprint, expected); + } + for raw in interface.raw_methods.as_ref().unwrap() { + let Some(contract) = raw.exact_contract.as_ref().filter(|contract| { + matches!( + contract.kind, + RawExactMethodContractKind::AudioFormatOwnedOutput + | RawExactMethodContractKind::AudioFormatSupport + ) + }) else { + continue; + }; + if let Err(error) = validate_exact_method_contract( + contract.declaring_namespace, + contract.declaring_interface, + contract.declaring_iid, + raw, + contract, + ) { + panic!("{error}: {}", raw_method_shape(raw)); + } + } + let mut drift = interface + .raw_methods + .as_ref() + .unwrap() + .iter() + .find(|raw| raw.metadata_name == "IsFormatSupported") + .unwrap() + .clone(); + drift.params[2].optional = false; + let contract = drift.exact_contract.clone().unwrap(); + assert!( + validate_exact_method_contract( + contract.declaring_namespace, + contract.declaring_interface, + contract.declaring_iid, + &drift, + &contract, + ) + .is_err() + ); + } + #[test] fn storage_medium_contracts_pin_borrowing_and_canonical_results() { let Some(winmd) = std::env::var("DYNWINRT_WIN32_WINMD") diff --git a/tools/dynwinrt-codegen/src/contract_registry.rs b/tools/dynwinrt-codegen/src/contract_registry.rs index 34956b03..72e55d97 100644 --- a/tools/dynwinrt-codegen/src/contract_registry.rs +++ b/tools/dynwinrt-codegen/src/contract_registry.rs @@ -92,8 +92,10 @@ pub enum ExactFamilyId { SequentialStreamBuffer, DispatchInvoke, ReservedNullInput, + NullableInput, ParameterDirection, ShellCommandString, + AudioConditionalOutput, } impl ExactFamilyId { @@ -111,8 +113,10 @@ impl ExactFamilyId { Self::SequentialStreamBuffer => "com.sequential-stream-buffer.v1", Self::DispatchInvoke => "automation.idispatch-invoke.v1", Self::ReservedNullInput => "com.reserved-null-input.v1", + Self::NullableInput => "com.nullable-input.v1", Self::ParameterDirection => "com.parameter-direction.v1", Self::ShellCommandString => "shell.flag-selected-string.v1", + Self::AudioConditionalOutput => "audio.conditional-output.v1", } } @@ -130,8 +134,10 @@ impl ExactFamilyId { Self::SequentialStreamBuffer, Self::DispatchInvoke, Self::ReservedNullInput, + Self::NullableInput, Self::ParameterDirection, Self::ShellCommandString, + Self::AudioConditionalOutput, ] .into_iter() .find(|family| family.id() == value) @@ -475,12 +481,17 @@ pub(crate) fn statically_declared_exact_entry_ids() -> Result, } const ADDITIONAL_EXACT_ENTRY_IDS: &[&str] = &[ + "com.nullable-input.entry.windows-win32-media-devicemanager.imdspdevicecontrol.1dcb3a1433ed11d3847000c04f79dbc0.record.slot-6.v1", + "com.nullable-input.entry.windows-win32-media-devicemanager.iwmdmdevicecontrol.1dcb3a0433ed11d3847000c04f79dbc0.record.slot-6.v1", + "audio.conditional-output.entry.windows-win32-media-audio.iaudioclient.1cb9ad4cdbfa4c32b178c2f568a703b2.isformatsupported.slot-7.v1", "automation.idispatch-invoke.entry.windows-win32-system-com.idispatch.0002040000000000c000000000000046.invoke.slot-6.v1", "buffers.bounded-two-call.entry.windows-win32-media-mediafoundation.imfattributes.2cd2d921c44744a7a13c4adabfc247e3.getblob.slot-15.v1", "buffers.bounded-two-call.entry.windows-win32-storage-imapi.idiscrecorder.85ac9776ca884cf2894e09598c078a41.getrecorderguid.slot-4.param-0-pbyuniqueid.v1", "buffers.counted-buffer.entry.windows-win32-storage-imapi.idiscrecorder.85ac9776ca884cf2894e09598c078a41.init.slot-3.param-0-pbyuniqueid.v1", "buffers.counted-buffer.entry.windows-win32-storage-packaging-opc.iopcsignaturecustomobject.5d77a19e62c144e7becd45da5ae51a56.getxml.slot-3.param-0-xmlmarkup.v1", "buffers.counted-buffer.entry.windows-win32-system-com.itypeinfo.0002040100000000c000000000000046.getnames.slot-7.param-1-rgbstrnames.v1", + "com.ownership.entry.windows-win32-media-audio.iaudioclient.1cb9ad4cdbfa4c32b178c2f568a703b2.getmixformat.slot-8.v1", + "com.ownership.entry.windows-win32-media-audio.iaudioclient3.7ed4ee078e674cd48c1a2b7a5987ad42.getcurrentsharedmodeengineperiod.slot-19.v1", "com.ownership.entry.windows-win32-storage-packaging-opc.iopcsignaturecustomobject.5d77a19e62c144e7becd45da5ae51a56.getxml.slot-3.param-0-xmlmarkup.v1", "com.ownership.entry.windows-win32-system-com.idataobject.0000010e00000000c000000000000046.getdatahere.slot-4.v1", "com.ownership.entry.windows-win32-system-com.idataobject.0000010e00000000c000000000000046.setdata.slot-7.v1", @@ -1143,7 +1154,7 @@ mod tests { serde_json::from_str::(SCHEMA_JSON).unwrap(); let registry = load_registry().unwrap(); let ids = statically_declared_exact_entry_ids().unwrap(); - assert_eq!(ids.len(), 499); + assert_eq!(ids.len(), 504); assert_eq!(registry.conditional_outputs.len(), 7); assert_eq!(registry.ownership_outputs.len(), 148); assert_eq!( diff --git a/tools/dynwinrt-codegen/tests/win32_com_test.rs b/tools/dynwinrt-codegen/tests/win32_com_test.rs index 21b53c50..788b40af 100644 --- a/tools/dynwinrt-codegen/tests/win32_com_test.rs +++ b/tools/dynwinrt-codegen/tests/win32_com_test.rs @@ -2201,6 +2201,102 @@ fn data_object_projects_hglobal_format_and_medium_values() { assert!(!advise_output.dts.contains("IAdviseSinkImplementation")); } +#[test] +fn device_control_record_projects_exact_nullable_audio_formats() { + if !win32_available() { + eprintln!("Skipping: Win32 winmd not available"); + return; + } + for name in ["IMDSPDeviceControl", "IWMDMDeviceControl"] { + let interface = com_metadata::parse_com_interface( + &win32_winmd(), + "Windows.Win32.Media.DeviceManager", + name, + ) + .unwrap(); + let output = com::generate_com_interface_files(&interface, &win32_winmd()).unwrap(); + assert!( + output + .dts + .contains("record(pFormat: DynComAudioFormat | null): void;") + ); + assert!( + output + .js + .contains(".addNullableIn(DynCom.audioFormatType())") + ); + assert!( + output.js.contains( + "pFormat === null ? DynCom.nullAudioFormat() : DynCom.audioFormat(pFormat)" + ) + ); + let index = interface + .raw_methods + .as_ref() + .unwrap() + .iter() + .position(|method| method.metadata_name == "Record") + .unwrap(); + let raw = &interface.raw_methods.as_ref().unwrap()[index]; + assert!(!raw.params[0].optional); + assert_eq!( + raw.exact_contract.as_ref().unwrap().kind, + com_metadata::RawExactMethodContractKind::NullableAudioFormatInput + ); + for mutation in 0..7 { + let mut drift = interface.clone(); + let raw = &mut drift.raw_methods.as_mut().unwrap()[index]; + match mutation { + 0 => raw.exact_contract = None, + 1 => raw.vtable_index += 1, + 2 => raw.params[0].typ.pointer_depth = 2, + 3 => raw.params[0].direction = com_metadata::RawParamDirection::Out, + 4 => raw.params[0].optional = true, + 5 => raw.params[0].const_attribute = true, + 6 => raw.exact_contract.as_mut().unwrap().buffer_param_index = 1, + _ => unreachable!(), + } + assert!( + com::generate_com_interface_files(&drift, &win32_winmd()).is_err(), + "{name}.Record admitted mutation {mutation}" + ); + } + } +} + +#[test] +fn audio_clients_project_variable_wave_formats_and_exact_ownership() { + if !win32_available() { + eprintln!("Skipping: Win32 winmd not available"); + return; + } + for name in ["IAudioClient", "IAudioClient2", "IAudioClient3"] { + let interface = + com_metadata::parse_com_interface(&win32_winmd(), "Windows.Win32.Media.Audio", name) + .unwrap_or_else(|| panic!("{name} must exist")); + let output = com::generate_com_interface_files(&interface, &win32_winmd()) + .unwrap_or_else(|error| panic!("{name}: {error}")); + assert!(output.dts.contains("DynComAudioFormat")); + assert!(!output.js.contains("UnsafePointee")); + assert!(!output.js.contains("UnsafePointerOutput")); + assert!(output.js.contains("DynCom.audioFormatType()")); + assert!(output.js.contains("DynCom.takeAudioFormat")); + assert!(!output.js.contains("static implementation(handlers)")); + assert!(output.dts.contains( + "isFormatSupported(shareMode: AUDCLNT_SHAREMODE, pFormat: DynComAudioFormat): readonly [number, DynComAudioFormat | null];" + )); + assert!(output.js.contains("DynCom.boolValue(_requestClosest)")); + assert!(output.js.contains("DynCom.takeNullableAudioFormat(_r[1])")); + if name == "IAudioClient3" { + assert!( + output + .dts + .contains("getCurrentSharedModeEnginePeriod(): [DynComAudioFormat, number];") + ); + } + } +} + #[test] fn storage_medium_in_out_requires_exact_preservation_evidence() { if !win32_available() { @@ -5141,9 +5237,9 @@ fn safe_incomplete_interface_generates_an_isolated_unsafe_companion() { "--winmd", &win32_winmd(), "--namespace", - "Windows.Win32.Media.Audio", + "Windows.Win32.AI.MachineLearning.WinML", "--class-name", - "IAudioClient", + "IWinMLEvaluationContext", "--output", output.to_str().unwrap(), ]); @@ -5163,13 +5259,15 @@ fn safe_incomplete_interface_generates_an_isolated_unsafe_companion() { "{}", String::from_utf8_lossy(&first.stderr) ); - assert!(String::from_utf8_lossy(&first.stdout).contains("Generated IAudioClientUnsafe")); + assert!( + String::from_utf8_lossy(&first.stdout).contains("Generated IWinMLEvaluationContextUnsafe") + ); let unsafe_dir = output_dir.join("com").join("unsafe"); - let class_module = "windows/win32/media/audio/IAudioClientUnsafe"; + let class_module = "windows/win32/ai/machine-learning/win-ml/IWinMLEvaluationContextUnsafe"; let retained = [ - "windows/win32/media/audio/IAudioClientUnsafe.js", - "windows/win32/media/audio/IAudioClientUnsafe.d.ts", + "windows/win32/ai/machine-learning/win-ml/IWinMLEvaluationContextUnsafe.js", + "windows/win32/ai/machine-learning/win-ml/IWinMLEvaluationContextUnsafe.d.ts", "index.js", "index.mjs", "index.d.ts", @@ -5187,8 +5285,8 @@ fn safe_incomplete_interface_generates_an_isolated_unsafe_companion() { let js = fs::read_to_string(unsafe_dir.join(format!("{class_module}.js"))).unwrap(); let dts = fs::read_to_string(unsafe_dir.join(format!("{class_module}.d.ts"))).unwrap(); - assert!(js.contains("class IAudioClientUnsafe")); - assert!(js.contains("isFormatSupported(")); + assert!(js.contains("class IWinMLEvaluationContextUnsafe")); + assert!(js.contains("getValueByName(")); assert!(!js.contains("implement(") && !js.contains("implementation")); assert!(dts.contains("private constructor()")); assert!(dts.contains("static from(value: DynWinRtValue")); @@ -5200,7 +5298,7 @@ fn safe_incomplete_interface_generates_an_isolated_unsafe_companion() { assert_eq!(support["interfaces"][0]["modulePath"], class_module); let methods = support["interfaces"][0]["methods"].as_array().unwrap(); assert!(methods.iter().any(|method| { - method["name"] == "IsFormatSupported" && method["status"] == "raw_manual_contract" + method["name"] == "GetValueByName" && method["status"] == "raw_manual_contract" })); assert!(!output_dir.join("index.js").exists()); @@ -5213,7 +5311,7 @@ fn safe_incomplete_interface_generates_an_isolated_unsafe_companion() { assert!( !fs::read_to_string(path) .unwrap() - .contains("IAudioClientUnsafe") + .contains("IWinMLEvaluationContextUnsafe") ); } @@ -5261,10 +5359,10 @@ fn stage2_official_manual_interfaces_emit_exact_strategy_requirements() { remove_com_generation_lock(&output); let cases = [ ( - "Windows.Win32.Media.Audio", - "IAudioClient", - "windows/win32/media/audio/IAudioClientUnsafe", - "isFormatSupported(ShareMode: number, pFormat: UnsafePointee, ppClosestMatch: UnsafePointerOutput): readonly [number, T0]", + "Windows.Win32.AI.MachineLearning.WinML", + "IWinMLEvaluationContext", + "windows/win32/ai/machine-learning/win-ml/IWinMLEvaluationContextUnsafe", + "getValueByName(Name: DynComRawMemory | DynComRawPointer, pDescriptor: UnsafePointerOutput): T0", ), ( "Windows.Win32.Graphics.Dxgi", @@ -5321,21 +5419,24 @@ fn stage2_official_manual_interfaces_emit_exact_strategy_requirements() { ) .unwrap(); assert_eq!(support["schemaVersion"], com::UNSAFE_SUPPORT_SCHEMA_VERSION); - let audio = support["interfaces"] + let evaluation = support["interfaces"] .as_array() .unwrap() .iter() - .find(|interface| interface["interfaceName"] == "Windows.Win32.Media.Audio.IAudioClient") + .find(|interface| { + interface["interfaceName"] + == "Windows.Win32.AI.MachineLearning.WinML.IWinMLEvaluationContext" + }) .unwrap(); - let format = audio["methods"] + let output_method = evaluation["methods"] .as_array() .unwrap() .iter() - .find(|method| method["name"] == "IsFormatSupported") + .find(|method| method["name"] == "GetValueByName") .unwrap(); - assert_eq!(format["status"], "raw_manual_contract"); + assert_eq!(output_method["status"], "raw_manual_contract"); assert_eq!( - format["strategyRequirements"] + output_method["strategyRequirements"] .as_array() .unwrap() .iter() @@ -5344,15 +5445,22 @@ fn stage2_official_manual_interfaces_emit_exact_strategy_requirements() { requirement["strategy"].as_str().unwrap() )) .collect::>(), - vec![ - ("pFormat", "UnsafePointee"), - ("ppClosestMatch", "UnsafePointerOutput") - ] + vec![("pDescriptor", "UnsafePointerOutput")] ); - assert_eq!(format["strategyRequirements"][0]["direction"], "in"); - assert_eq!(format["strategyRequirements"][0]["nullable"], false); + let input_method = evaluation["methods"] + .as_array() + .unwrap() + .iter() + .find(|method| method["name"] == "BindValue") + .unwrap(); assert_eq!( - format["strategyRequirements"][0]["pointeeLayouts"], + input_method["strategyRequirements"][0]["strategy"], + "UnsafePointee" + ); + assert_eq!(input_method["strategyRequirements"][0]["direction"], "in"); + assert_eq!(input_method["strategyRequirements"][0]["nullable"], false); + assert_eq!( + input_method["strategyRequirements"][0]["pointeeLayouts"], serde_json::json!({"arm64": null, "i686": null, "x64": null}) ); assert!( @@ -5374,7 +5482,7 @@ fn stage2_official_manual_interfaces_emit_exact_strategy_requirements() { ) .unwrap(); for root in [ - "Windows.Win32.Media.Audio.IAudioClient", + "Windows.Win32.AI.MachineLearning.WinML.IWinMLEvaluationContext", "Windows.Win32.Graphics.Dxgi.IDXGIObject", "Windows.Win32.System.ClrHosting.IHostMalloc", "Windows.Win32.Devices.Fax.IStiDeviceControl", @@ -5483,7 +5591,7 @@ fn report_only_interface_persists_support_and_removes_only_owned_stale_files() { ); let unsafe_dir = output_dir.join("com").join("unsafe"); let mf_module = "windows/win32/media/media-foundation/MFASYNCRESULTUnsafe"; - let unsafe_module = "windows/win32/media/audio/IAudioClientUnsafe"; + let unsafe_module = "windows/win32/ai/machine-learning/win-ml/IWinMLEvaluationContextUnsafe"; assert!(unsafe_dir.join("support.json").is_file()); assert!(!unsafe_dir.join(format!("{mf_module}.js")).exists()); assert!(!unsafe_dir.join(format!("{mf_module}.d.ts")).exists()); @@ -5524,8 +5632,8 @@ fn report_only_interface_persists_support_and_removes_only_owned_stale_files() { let unsafe_success = run( &output_dir, - "Windows.Win32.Media.Audio", - "IAudioClient", + "Windows.Win32.AI.MachineLearning.WinML", + "IWinMLEvaluationContext", false, ); assert!( @@ -5545,7 +5653,7 @@ fn report_only_interface_persists_support_and_removes_only_owned_stale_files() { assert_eq!( merged_names, std::collections::BTreeSet::from([ - "Windows.Win32.Media.Audio.IAudioClient", + "Windows.Win32.AI.MachineLearning.WinML.IWinMLEvaluationContext", "Windows.Win32.Media.MediaFoundation.MFASYNCRESULT", ]) ); @@ -5637,7 +5745,10 @@ fn concurrent_incremental_com_generation_preserves_all_roots_and_reports() { }; let safe = spawn("Windows.Win32.UI.Shell", "ITaskbarList3"); - let unsafe_companion = spawn("Windows.Win32.Media.Audio", "IAudioClient"); + let unsafe_companion = spawn( + "Windows.Win32.AI.MachineLearning.WinML", + "IWinMLEvaluationContext", + ); let safe = safe.wait_with_output().unwrap(); let unsafe_companion = unsafe_companion.wait_with_output().unwrap(); assert!( @@ -5653,7 +5764,7 @@ fn concurrent_incremental_com_generation_preserves_all_roots_and_reports() { let com_dir = output_dir.join("com"); let unsafe_dir = com_dir.join("unsafe"); - let unsafe_module = "windows/win32/media/audio/IAudioClientUnsafe.js"; + let unsafe_module = "windows/win32/ai/machine-learning/win-ml/IWinMLEvaluationContextUnsafe.js"; assert!( generated_com_module(&output_dir, "Windows.Win32.UI.Shell", "ITaskbarList3", "js") .is_file() @@ -5662,14 +5773,17 @@ fn concurrent_incremental_com_generation_preserves_all_roots_and_reports() { let safe_barrel = fs::read_to_string(com_dir.join("index.js")).unwrap(); let unsafe_barrel = fs::read_to_string(unsafe_dir.join("index.js")).unwrap(); assert!(safe_barrel.contains("ITaskbarList3")); - assert!(!safe_barrel.contains("IAudioClientUnsafe")); - assert!(unsafe_barrel.contains("IAudioClientUnsafe")); + assert!(!safe_barrel.contains("IWinMLEvaluationContextUnsafe")); + assert!(unsafe_barrel.contains("IWinMLEvaluationContextUnsafe")); let manifest: serde_json::Value = serde_json::from_str( &fs::read_to_string(com_dir.join(".dynwinrt-com-manifest.json")).unwrap(), ) .unwrap(); assert!(manifest["roots"]["Windows.Win32.UI.Shell.ITaskbarList3"].is_array()); - assert!(manifest["roots"]["Windows.Win32.Media.Audio.IAudioClient"].is_array()); + assert!( + manifest["roots"]["Windows.Win32.AI.MachineLearning.WinML.IWinMLEvaluationContext"] + .is_array() + ); let safe_second = spawn("Windows.Win32.UI.Shell", "IShellLinkW"); let report_only = spawn("Windows.Win32.Media.MediaFoundation", "MFASYNCRESULT"); @@ -5700,7 +5814,7 @@ fn concurrent_incremental_com_generation_preserves_all_roots_and_reports() { for root in [ "Windows.Win32.UI.Shell.ITaskbarList3", "Windows.Win32.UI.Shell.IShellLinkW", - "Windows.Win32.Media.Audio.IAudioClient", + "Windows.Win32.AI.MachineLearning.WinML.IWinMLEvaluationContext", "Windows.Win32.Media.MediaFoundation.MFASYNCRESULT", ] { assert!( @@ -5830,8 +5944,8 @@ fn concurrent_com_and_winrt_writers_share_one_output_lock_in_both_orders() { let baseline_unsafe = spawn( &output, &win32_metadata, - "Windows.Win32.Media.Audio", - "IAudioClient", + "Windows.Win32.AI.MachineLearning.WinML", + "IWinMLEvaluationContext", None, None, ) @@ -5892,22 +6006,30 @@ fn concurrent_com_and_winrt_writers_share_one_output_lock_in_both_orders() { ); assert!(generated_com_module(&output, "Windows.Win32.UI.Shell", "IShellLinkW", "js").is_file()); assert!( - generated_unsafe_module(&output, "Windows.Win32.Media.Audio", "IAudioClient", "js") - .is_file() + generated_unsafe_module( + &output, + "Windows.Win32.AI.MachineLearning.WinML", + "IWinMLEvaluationContext", + "js" + ) + .is_file() ); let manifest: serde_json::Value = serde_json::from_str( &fs::read_to_string(output.join("com").join(".dynwinrt-com-manifest.json")).unwrap(), ) .unwrap(); assert!(manifest["roots"]["Windows.Win32.UI.Shell.IShellLinkW"].is_array()); - assert!(manifest["roots"]["Windows.Win32.Media.Audio.IAudioClient"].is_array()); + assert!( + manifest["roots"]["Windows.Win32.AI.MachineLearning.WinML.IWinMLEvaluationContext"] + .is_array() + ); let root_barrel = fs::read_to_string(output.join("index.d.ts")).unwrap(); let com_barrel = fs::read_to_string(output.join("com").join("index.d.ts")).unwrap(); let unsafe_barrel = fs::read_to_string(output.join("com").join("unsafe").join("index.d.ts")).unwrap(); assert!(root_barrel.contains("Uri") && !root_barrel.contains("Calendar")); assert!(com_barrel.contains("IShellLinkW")); - assert!(unsafe_barrel.contains("IAudioClientUnsafe")); + assert!(unsafe_barrel.contains("IWinMLEvaluationContextUnsafe")); let support: serde_json::Value = serde_json::from_str( &fs::read_to_string(output.join("com").join("unsafe").join("support.json")).unwrap(), ) @@ -5952,9 +6074,9 @@ fn generated_unsafe_fingerprint_includes_sibling_and_reference_metadata() { "--winmd", winmd.to_str().unwrap(), "--namespace", - "Windows.Win32.Media.Audio", + "Windows.Win32.AI.MachineLearning.WinML", "--class-name", - "IAudioClient", + "IWinMLEvaluationContext", "--output", output.to_str().unwrap(), ]); @@ -6085,7 +6207,7 @@ fn unified_output_transaction_rolls_back_first_and_incremental_failures() { ); let before = snapshot_tree(&output_dir); let incremental_failure = run( - "Windows.Win32.Media.Audio.IAudioClient", + "Windows.Win32.AI.MachineLearning.WinML.IWinMLEvaluationContext", Some("after_backup_rename"), ); assert!(!incremental_failure.status.success()); @@ -6107,7 +6229,7 @@ fn unified_output_transaction_rolls_back_first_and_incremental_failures() { "--winmd", &metadata, "--class-name", - "Windows.Win32.Media.Audio.IAudioClient", + "Windows.Win32.AI.MachineLearning.WinML.IWinMLEvaluationContext", "--output", output_dir.to_str().unwrap(), ]) @@ -6136,8 +6258,8 @@ fn unified_output_transaction_rolls_back_first_and_incremental_failures() { assert!( generated_unsafe_module( &output_dir, - "Windows.Win32.Media.Audio", - "IAudioClient", + "Windows.Win32.AI.MachineLearning.WinML", + "IWinMLEvaluationContext", "js" ) .is_file() @@ -6394,8 +6516,8 @@ fn mixed_unsafe_only_com_retains_com_package_exports() { run_codegen_command( &win32_winmd(), - Some("Windows.Win32.Media.Audio"), - "IAudioClient", + Some("Windows.Win32.AI.MachineLearning.WinML"), + "IWinMLEvaluationContext", &output, ); run_codegen_command( @@ -6406,8 +6528,13 @@ fn mixed_unsafe_only_com_retains_com_package_exports() { ); assert!( - generated_unsafe_module(&output, "Windows.Win32.Media.Audio", "IAudioClient", "js") - .is_file() + generated_unsafe_module( + &output, + "Windows.Win32.AI.MachineLearning.WinML", + "IWinMLEvaluationContext", + "js" + ) + .is_file() ); let package = fs::read_to_string(output.join("package.json")).unwrap(); assert!(package.contains("\".\":")); @@ -6421,7 +6548,7 @@ fn mixed_unsafe_only_com_retains_com_package_exports() { '@winapp/bindings',\ '@winapp/bindings/windows/foundation/Uri',\ '@winapp/bindings/com',\ - '@winapp/bindings/com/unsafe/windows/win32/media/audio/IAudioClientUnsafe'\ + '@winapp/bindings/com/unsafe/windows/win32/ai/machine-learning/win-ml/IWinMLEvaluationContextUnsafe'\ ]) console.log(require.resolve(id))", ]) .current_dir(&root)